query
stringlengths 9
14.6k
| document
stringlengths 8
5.39M
| metadata
dict | negatives
listlengths 0
30
| negative_scores
listlengths 0
30
| document_score
stringlengths 5
10
| document_rank
stringclasses 2
values |
---|---|---|---|---|---|---|
get the URL for the "loading" page to be used as iframe src while loading the Dropbox. | function loadingURL() {
return settings.assetHost + '/external/zenbox/v2.1/loading.html';
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function getLoaderUrl() {\n const { organizationId, pageId } = config;\n const base = config.isHipaaOrg ? \"https://platformhipaa.cloud.coveo.com\" : \"https://platform.cloud.coveo.com\";\n return `${base}/rest/organizations/${organizationId}/pages/${pageId}/inappwidget/loader`;\n}",
"getIntendedURL () {\n var url = page.loadingURL || page.getURL();\n if (url.startsWith('beaker:') && page.siteInfoOverride && page.siteInfoOverride.url) {\n // override, only if on a builtin beaker site\n url = page.siteInfoOverride.url;\n }\n return url\n }",
"getURL() { return Work.baseURL + this.url; }",
"function startLoad() {\n\t\tconst block = $(\".blob-wrapper a[href*='?raw=true']\");\n\t\tconst body = block && block.closest(\".Box-body\");\n\t\tif (body) {\n\t\t\tbody.classList.add(\"ghfp-body\");\n\t\t\tbody.innerHTML = \"<span class='gfp-loading ghd-invert'></span>\";\n\t\t}\n\t\treturn block && block.href;\n\t}",
"async _getPageUrl() {\n return this.executeScript(() => window.location.href);\n }",
"function getURL() {\n if (window.location != window.parent.location) {\n var link = document.createElement('a');\n link.href = document.referrer;\n // Make an split of the url referrer.\n param = link.pathname.split('/');\n for (var i = 1; i <= param.length; i++) {\n if (param[i] != \"_apps\") {\n //obtains collection, name project and team name (if the project has it).\n path = path + \"/\" + param[i];\n }\n else {\n break;\n }\n }\n ;\n var webContext = VSS.getWebContext();\n var workClient = VSS_Service.VssConnection\n .getConnection()\n .getHttpClient(Work_Client.WorkHttpClient, WebApi_Constants.ServiceInstanceTypes.TFS);\n var teamContext = { projectId: webContext.project.id, teamId: webContext.team.id, project: \"\", team: \"\" };\n workClient.getTeamIterations(teamContext, \"current\").then(function (iterations) {\n if (iterations.length > 0) {\n iterationPath = iterations[0].path;\n // Build the url to show the burnchart.\n url = link.protocol + \"//\"\n + link.host\n + path\n + \"/_api/_teamChart/Burndown?chartOptions=%7B%22Width%22%3A936%2C%22Height%22%3A503%2C%22ShowDetails%22%3Atrue%2C%22Title%22%3A%22%22%7D&counter=2&iterationPath=\"\n + encodeURIComponent(iterationPath)\n + \"&__v=5\";\n console.log(url);\n document.getElementById(\"imgBurnChart\").setAttribute(\"src\", url);\n }\n else {\n }\n }, function (error) {\n // If the iteration is less than 0, show an alert.\n alert(\"Unexpected error trying to obtain the Burnchart.\");\n });\n }\n else {\n // If the location child equals to the parent, show an alert.\n alert(\"Unexpected error trying to obtain the Burnchart.\");\n }\n VSS.notifyLoadSucceeded();\n }",
"function myURL() {\n\tvar myurl = (window.location != window.parent.location) ? window.parent.location : window.location;\n\treturn window.location;\t\t\t// just return iframe url to get params!\n}",
"function getURL(){\n\t\tvar scripts = document.getElementsByTagName('script');\n\t\tfor (var index = scripts.length-1; index >= 0; --index) {\n\t\t\tif (scripts[index].id == 'jAlbum') {\n\t\t\t\tvar curr = scripts[index].src;\n\t\t\t\treturn curr.substring(0, curr.lastIndexOf(\"/\") + 1);\n\t\t\t}\n\t\t}\n\t\treturn \"\";\n\t}",
"function loading( theURL ) {\n\n\t\t /* display the progress bar */\n\tbrowser.progress = true\n\t\n\t\t/* add a message to the console window */\n\tconsole.log(\"loading url '\" + theURL + \"'\")\n\t\n\t\t/* set the url text field to the new url */\n\tbrowser.url = theURL\n}",
"getURL() { return Abstract.baseURL + this.url; }",
"function getIframe(url) {\n var url_ok=true;\n try {\n var content = '<iframe src=\"' + url + '\" width=\"95%\" height=\"400\" scrolling=\"no\" frameborder=\"no\"></iframe>';\n }\n catch(e){\n url_ok=false;\n }\n if( url_ok==true){\n $(\"#container\").html(content);\n $(\"#container\").fadeIn(100);\n $(\"#link\").show();\n $(\"#descripcion\").show();\n }\n else{\n $(\"#imagen_descargar\").css(\"display\", \"none\");\n errorData(true);\n }\n}",
"function getBaseUrl() {\r\n\tvar base;\r\n\r\n\tif (getURLParameter($(parent.location).attr('href'), \"base\") != null) {\r\n\t\tbase = getURLParameter($(parent.location).attr('href'), \"base\");\r\n\t} else {\r\n\r\n\t\tif (window.location.protocol == 'http:' || window.location.protocol == 'https:')\r\n\t\t\tbase = window.location.protocol + \"//\" + window.location.host;\r\n\t\telse\r\n\t\t\tbase = window.location.host;\r\n\t}\r\n\r\n\treturn base;\r\n}",
"function getPageBaseURL() {\n var baseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;\n return baseURL;\n}",
"function getLoaderSnippet() {\n return `<script type=\"text/javascript\" src=\"${getLoaderUrl()}\" async ></script>`;\n}",
"loadURL (url, opts) {\n // reset some state\n page.isReceivingAssets = false;\n page.siteInfoOverride = null;\n\n // HACK to fix electron#8505\n // dont allow visibility: hidden until set active\n page.webviewEl.classList.remove('can-hide');\n\n // set and go\n page.loadingURL = url;\n page.isGuessingTheURLScheme = opts && opts.isGuessingTheScheme;\n if (!page.isWebviewReady) {\n // just do a sync call, otherwise loadURLAsync will drop it on the floor\n page.webviewEl.loadURL(url); // NOTE sync call\n } else {\n page.loadURLAsync(url);\n }\n }",
"function show_loading(portal_dir, target) {\n $(\"#\" + target).html(\"<img src='\" + portal_dir + \"/static/img/waiting.gif' style='display:block;margin-left: auto;margin-right: auto'/>\");\n}",
"function GetSlideShowUrl()\n{\n\ttry {\n\t\t//Drop current view\n\t\t//document.body.removeChild(Pick(SectionDetailsArray[indexClickedSection].divId));\n\t\tvar _albumUrl = this.handlerData.slideShowUrl;\n\t\tif (_albumUrl == -1) {\n\t\t\t//Make http call find slideShowUrl\n\t\t\tvar _slideShow = this.handlerData.slideShow;\n\t\t\tvar _httpManager = new HttpManager();\n\t\t\t_httpManager.GetFeedData(_slideShow, GetSlideShowUrlFromSlideShow);\n\t\t}\n\t\telse {\n\t\t\tGetPhotosList(_albumUrl);\n\t\t}\n\t}\n\tcatch(ex)\n\t{\n\t\talert(ex.message);\n\t}\n}",
"function getUrl() {\n// hamza todo\n var URL = location.href;\n return URL;\n}",
"function thisURL() {\n var scripts = document.getElementsByTagName('script');\n \n for (var i = 0; i < scripts.length; i++) {\n s = scripts[i];\n\n if (s.src && s.src.match(/esdmaps-embed(\\.min|)\\.js$/)) {\n return s.src;\n }\n }\n\n return null;\n }",
"function callIframe() {\n\t\t\tvar bcPlayer=\"<iframe id='bcPlayer' class='bc-iframe' style='border: 0; width: 100%;' src='' seamless>\t<a href='http://d8ts.bandcamp.com/album/da-tes'>DA/TES by Splotch & Emoticon Dream</a></iframe>\";\n\t\t\tvar srcUrl=\"http://bandcamp.com/EmbeddedPlayer/album=185332851/size=large/bgcol=ffffff/linkcol=0687f5/transparent=true/\";\n\t $('.bc-col').prepend(bcPlayer);\n \t$('iframe#bcPlayer').attr('src', srcUrl);\n\t $('iframe#bcPlayer').load(function() {\n\t\t\t\tsetHeight('.bc-iframe');\n\t });\n\t}",
"function _getBase() {\n\t\t\tvar protocol = window.location.protocol + \"//\",\n\t\t\t\thost = window.location.host;\n\t\t\treturn protocol + host;\n\t\t}",
"function getPageLocation()\n{\n\tvar path = window.location.pathname;\n\treturn path;\n}",
"function getBaseUrl() {\n // Remove the hash for HTML4 case\n var base = window.location.href.split('#')[0];\n // Then extract the base URL\n return removeLastSegment(base);\n}",
"function _(){return\"undefined\"==typeof document||null==document.location?\"\":document.location.href}",
"function getUrl(){\n return document.URL;\n}",
"get URL() {\n return this.location.href;\n }",
"get url() {\n return this.defaultStage ? this.defaultStage.url : undefined;\n }",
"function showRedirecting() {\n var loadingGif = dijit.byId(\"ESRIUK_Dijits_Loading_0\");\n if (loadingGif != undefined && loadingGif) {\n \n // Use lastChild as supported by both IE and FF\n loadingGif.domNode.lastChild.innerHTML = \" Redirecting ... \"\n loadingGif.domNode.style.display = \"block\";\n }\n}",
"function getHolderLoadingTemplate () {\n\t\t\n\t\tvar html = '';\n\t\t\thtml += '<div style=\"display: block; width: 100%; text-align: center; padding: 1em;\">';\n\t\t\t\thtml += '<img src=\"resources/images/loaders/azul_bg_transparent_24.gif\" />';\n\t\t\thtml += '</div>';\n\t\treturn html;\n\t}",
"function ask_ajax_page(url, callback) {\n\t$('#loading_page').css('display','inherit');\n\t$.getJSON(url, callback);\n}"
]
| [
"0.65660435",
"0.64362466",
"0.5959933",
"0.5924222",
"0.5852324",
"0.5830142",
"0.5762758",
"0.57375526",
"0.56045496",
"0.5561437",
"0.5489505",
"0.54825187",
"0.54799646",
"0.5433734",
"0.5430651",
"0.54007477",
"0.54004174",
"0.5393575",
"0.53686607",
"0.5362531",
"0.5358556",
"0.5353478",
"0.5353209",
"0.53469276",
"0.5334316",
"0.5332162",
"0.53262866",
"0.53231215",
"0.53229743",
"0.5286229"
]
| 0.7258426 | 0 |
upgrade the speed of delivery | upgrade() {
if (money >= this.priceUpgrade && this.unlock) {
this.lightYellow();
money -= this.priceUpgrade;
this.speedOfDelivery = this.getNewSPeed(this.speedOfDelivery);
this.worker.postMessage(this.speedOfDelivery)
ingredientChart[this.ingredient].initSpeed = this.speedOfDelivery;
this.priceUpgrade = this.getNewPrice(this.priceUpgrade)
ingredientChart[this.ingredient].initPrice = this.priceUpgrade;
this.speedDocument.textContent =
"every " + this.roundValue(this.speedOfDelivery / 1000, 2).toString(10) + "s";
this.button.textContent = this.priceUpgrade.toString(10) + "$";
for (var i = 0; i < 2; i++) {
this.add();
}
updateScore();
this.updateTootTip();
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"set SpeedUS(newSpeed){\n this.speed = newSpeed * 1.6\n }",
"set speedUS(speed) {\n this.speed = speed *= 1.6;\n }",
"function updateSpeed () {\n var progress = (100 * torrent.progress).toFixed(1)\n console.log(progress)\n // '<b>Peers:</b> ' + torrent.swarm.wires.length + ' ' +\n // '<b>Progress:</b> ' + progress + '% ' +\n // '<b>Download speed:</b> ' + prettyBytes(client.downloadSpeed()) + '/s ' +\n // '<b>Upload speed:</b> ' + prettyBytes(client.uploadSpeed()) + '/s'\n // progressBar.setAttribute('aria-valuenow', progress)\n // progressBar.setAttribute('style', 'width: ' + progress + '%')\n }",
"static increaseGameSpeed() {\n if (Game.refresh_delay > 0) {\n Game.refresh_delay *= 0.9;\n }\n }",
"function incrementSpeed() {\n CONFIG.incrementRounds.map(function(r) {\n if (sg.getRound() == r) {\n CONFIG.comTimeoutMS -= CONFIG.speedIncrement;\n }\n });\n }",
"upgrade () {\n if ( this.level == 1 && this.ship.credit > 100 ) {\n this.ship.credit -= 100;\n this.level = 2;\n this.ScanCP = 5;\n }\n else {\n addMessage( \"Can't upgrade sensor, check your sensor's lv or your credit\" );\n }\n }",
"function updateSpeed() {\n speed = speed - 0.1; //set speed animation to be 0,1 faster\n if (speed < minimumSpeed) //if the new speed value is lower than the minimum (0.7) we keep it as the minimum instead\n speed = minimumSpeed;\n $(\"#potion\").css(\"animation-duration\", speed + \"s\"); //update css animation-duration for the potion\n speedChange = false; //inform a speed change has been done and not needed again until next time\n }",
"function timeUpgrade() {\n\tif(points >= timeUCost) { //check points\n\t\tpoints = points - timeUCost; //subtract points\n\t\ttimeBetweenBoxes = timeBetweenBoxes/2; //apply upgrade\n\t\tif(inLoop) {\n\t\t\tclearInterval(boxInterval);\n\t\t\tinLoop = false;\n\t\t\tstartLoop();\n\t\t}\n\t\ttimeUCost = timeUCost*2; //change upgrade price\n\t\tupdateLook(); //updateLook();\n\t}\n}",
"up() {\n this.speed += this.lift;\n }",
"upgrade(){\n\t\tif (this.stage < Towns[\"niveau\"].length-1){\n\t\t\tthis.stage ++;\n\t\t}\n\n\t\tif(this.player.gold >= Towns[\"niveau\"][this.stage].cout){\n\t\t\tthis.timerConstruction = new Timer(Towns[\"niveau\"][this.stage].production, Date.now());\n\t\t\tthis.player.gold -= Towns[\"niveau\"][this.stage].cout;\n\t\t\n\t\t\tthis.hitPoints = this.hitPoints + (Towns[\"niveau\"][this.stage].points_vie - this.maxHitPoints);\n\t\t\tthis.maxHitPoints = Towns[\"niveau\"][this.stage].points_vie;\n\t\t}\n\t\telse{\n\t\t\tthat.sendError(\"Pas assez de ressource\");\n\t\t}\n\t}",
"function increaseFrogSpeed() {}",
"function resetSpeed() {\n newSpeed = speed;\n then = Date.now();\n }",
"function speedUp() {\n\t\t\tif(speed < CONFIG.maxCarSpeed) {\n\t\t\t\tspeed += CONFIG.accCarSpeed;\n\t\t\t}\n\t\t}",
"upgrade(times) {\n if (times === undefined) {\n times = 1;\n }\n\n let downgrade = false;\n if (times < 0) {\n downgrade = true;\n times = Math.abs(times);\n }\n\n for (let i = 0; i < times; i++) {\n if (downgrade) {\n if (this.proficiency > 0) {\n this.proficiency--;\n this.ability++;\n }\n } else {\n if (this.ability > 0) {\n this.ability--;\n this.proficiency++;\n } else {\n this.ability++;\n }\n }\n }\n }",
"changeSpeed(amount) {\n if (this.speed < this.maxSpeed)\n this.speed += amount;\n }",
"function cost_increase(upgrade_name) {\n\t\tupgrade_costs[upgrade_name].dirt = Math.ceil(upgrade_costs[upgrade_name].dirt* 1.1);\n\t\tupgrade_costs[upgrade_name].wood = Math.ceil(upgrade_costs[upgrade_name].wood* 1.1);\n\t\tupgrade_costs[upgrade_name].stone = Math.ceil(upgrade_costs[upgrade_name].stone * 1.1);\n\t\tupgrade_costs[upgrade_name].metal = Math.ceil(upgrade_costs[upgrade_name].metal * 1.1);\n\t}",
"_updatePosition(deltaTime) {\n\t\tvar sc = Math.min(6, 1 + (this._sct - 2) / 106);\n\t\tvar baseSpeed = config[\"nsp1\"] + config[\"nsp2\"];\n\t\t//Bigger snakes move slower\n\t\tvar scale = baseSpeed / (config[\"nsp1\"] + (config[\"nsp2\"] * sc) + 0.1);\n\n\t\tif (this._boost && this._length > 2) {\n\t\t\tthis._speed += 1.45;\n\n\t\t\tif (this._speed > config[\"maxSpeed\"]) this._speed = config[\"maxSpeed\"];\n\t\t} else {\n\t\t\tthis._speed -= 1.95;\n\t\t\tif (this._speed < baseSpeed) this._speed = baseSpeed;\n\t\t}\n\n\t\t//This is speed formula used in client\n\t\tlet formula = deltaTime / 8 * this._speed / 4;\n\n\t\t//Multiply by scale to slow down larger snakes\n\t\tlet distance = scale * formula;\n\t\tdistance = distance * config[\"speedMult\"] + config[\"speedBonus\"];\n\t\tthis._direction.x = parseInt(Math.cos(this._direction.angle) * distance);\n\t\tthis._direction.y = parseInt(Math.sin(this._direction.angle) * distance);\n\t\tthis._head.x += this._direction.x;\n\t\tthis._head.y += this._direction.y;\n\n\t\tvar sizeChange = baseSpeed - this._speed;\n\t\tif (sizeChange !== 0)\n\t\t\tthis.increaseSize(sizeChange * 4);\n\n\t\tthis._updateParts();\n\t\tif (Math.abs(this._direction.x) < 120 && Math.abs(this._direction.y) < 120) {\n\t\t\tthis.emit(\"updateSmall\", this);\n\t\t} else {\n\t\t\tthis.emit('update', this);\n\t\t}\n\t\tthis._lastSpeedSent = this._speed;\n\t\tthis._lastAngleSent = this._direction.angle;\n\t}",
"set speed(speed) {\n MULTIPLIER = speed\n SPEED = STEP * MULTIPLIER\n }",
"function updateRangeSpeed() {\r\n me.range = me.ships.findBest(ShipUtils.shortestRange).range();\r\n me.speed = me.ships.findBest(ShipUtils.slowest).speed();\r\n }",
"function speed_update() {\n var array_speed = parseInt(inp_aspeed.value);\n\n if (array_speed === 1) {\n speed = 1;\n }\n else if (array_speed === 2) {\n speed = 10;\n }\n else if (array_speed === 3) {\n speed = 100;\n }\n else if (array_speed === 4) {\n speed = 1000;\n }\n else if (array_speed === 5) {\n speed = 10000;\n }\n\n delay_time = 10000 / (Math.floor(array_size / 10) * speed);\n}",
"function updateModel()\n{\n// distanceTotal = computeDistance(coordsStart, coordsPrev);\n// time++;\n//\n// var speed = distanceTotal - distanceLastMinute;\n// if ((speed * 6 / 100) < rateDowntimeCitySpeedLimit)\n// {\n// cost += speed * rateDowntime;\n// }\n// else\n// {\n// cost += speed * rateCity;\n// }\n//\n// distanceLastMinute = distanceTotal;\n}",
"function speedUp(){\r\n if(itemTimer['speedUp'] != undefined)\r\n return;\r\n\r\n console.log('speedUp');\r\n preSpeed = speed;\r\n speed += 50;\r\n itemTimer['speedUp'] = 3000;\r\n}",
"function shippingRate2() {\r\n rate = (size + 1) * weight + speed;\r\n}",
"function speedUpgrade(callback) {\n //Speed increase every\n if (that.intervalSpeedLevel > 0) {\n gameLevelTimeout = setTimeout(function () {\n that.intervalSpeedLevel -= 1;\n that.speedLevelCount += 1;\n levelCount.innerHTML = 'SPEED ' + that.speedLevelCount;\n levelCountTimeout();\n callback();\n }, LEVEL_UP_TIMER);\n } else {\n clearTimeout(gameLevelTimeout);\n levelCount.innerHTML = 'GGWP<br>Try other obstacle Levels';\n levelCountTimeout();\n }\n }",
"function changeSpeed(val){\n if (overriding){\n if ((val == 87 || val == 38) && desSpeed<15) { // forward\n desSpeed+=1;\n } else if ((val == 83 || val == 40) && desSpeed>-15) { // backward\n desSpeed-=1;\n\n } else if ((val == 65 || val == 37) && desSteer>-40) { // left\n desSteer-=1;\n } else if ((val == 68 || val == 39) && desSteer<40) { //right\n desSteer+=1;\n }\n console.log(desSteer,desSpeed);\n \n if ((val == 32)){ // stop\n desSteer=0;\n desSpeed=0;\n sendInfo();\n }\n displaySpeed();\n }\n}",
"updateSpeed(dt){\n this.x += this.speed * dt;\n if (this.x > 505) {\n this.x = -115;\n }\n}",
"function increase_speed() {\n if (fall_time > 2500) {\n fall_time *= 0.7\n }\n}",
"function updateSpeed(speed) {\n //console.log('updating speed');\n for (i = 0; i < manual_clips.length; i++) {\n // this is because of a mistake during the animations\n //console.log(i);\n s = speed;\n if (i > 1) {\n if (URL.manual[i - 2].path == 'numbers' || URL.manual[i - 2].path == 'alphabet') {\n s = speed * 1.6;\n }\n }\n mixer.clipAction(manual_clips[i].clip).setEffectiveTimeScale(s);\n }\n for (i = 0; i < NON_MAN_VARS.clips_list.length; i++) {\n mixer.clipAction(NON_MAN_VARS.clips_list[i]).setEffectiveTimeScale(speed);\n }\n updateInterpolation(speed);\n}",
"function ResetSpeed() {\n UpdatedSpeed = DefaultSpeed;\n then = Date.now();\n}",
"async sledDelivery() {\n\n // If the dwarf is not working and the sled is not empty and not in delivery\n if (this.model.dwarf.status !== \"working\" && this.model.sled.status !== \"delivering\" && this.model.sled.currentWeight > 0) {\n\n // Before delivery\n this.model.dwarf.statusUpdate(\"waiting\");\n this.model.sled.statusUpdate(\"delivering\");\n this.view.updateDwarf(this.model.dwarf);\n this.view.updateSled(this.model.sled);\n\n // Delivery\n await this.model.sled.delivery();\n\n // After delivery\n this.model.dwarf.statusUpdate(\"available\");\n this.view.updateDwarf(this.model.dwarf);\n this.view.updateSled(this.model.sled);\n }\n }"
]
| [
"0.66828936",
"0.650004",
"0.64734894",
"0.6295966",
"0.62505984",
"0.622006",
"0.6208842",
"0.6206819",
"0.61661446",
"0.6165942",
"0.61629826",
"0.61595154",
"0.61470354",
"0.61392653",
"0.6130278",
"0.61277586",
"0.6106612",
"0.60987014",
"0.6097191",
"0.60749364",
"0.60438",
"0.6008513",
"0.60007143",
"0.5992056",
"0.5960634",
"0.5930736",
"0.59238464",
"0.5921452",
"0.59107006",
"0.59005165"
]
| 0.69945633 | 0 |
average speed of all unlocked reserve | averageSpeed() {
var speedAverage = 0;
var nbUnlockedReserve = 0;
for (var reserve of foodList) {
if (reserve.unlock) {
nbUnlockedReserve++;
speedAverage += reserve.speedOfDelivery;
}
}
return this.roundValue(speedAverage / nbUnlockedReserve);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"averagePrice() {\n var priceAverage = 0;\n var nbUnlockedReserve = 0;\n for (var reserve of foodList) {\n if (reserve.unlock) {\n nbUnlockedReserve++;\n priceAverage += reserve.priceUpgrade;\n }\n }\n return this.roundValue(priceAverage / nbUnlockedReserve);\n }",
"calculateAverageSpeed(time,distance){\n return distance/time;\n }",
"function cpuAverage() {\n\n //Initialise sum of idle and time of cores and fetch CPU info\n var totalIdle = 0, totalTick = 0;\n var cpus = os.cpus();\n\n //Loop through CPU cores\n for(var i = 0, len = cpus.length; i < len; i++) {\n\n //Select CPU core\n var cpu = cpus[i];\n\n //Total up the time in the cores tick\n for(type in cpu.times) {\n totalTick += cpu.times[type];\n } \n\n //Total up the idle time of the core\n totalIdle += cpu.times.idle;\n }\n\n //Return the average Idle and Tick times\n return {idle: totalIdle / cpus.length, total: totalTick / cpus.length};\n}",
"average(){\n return this.buffer.reduce((accum, current) => accum + current) / this.size;\n }",
"calcWater(){\n var avgMinutes = (this.hike.distance / 2.0) * 60.0;\n var avgWater = Math.ceil((avgMinutes / 15.0) * 9.0);\n return avgWater;\n }",
"function cpuAverage(){\n const cpus = os.cpus();\n //get ms in each mode, this number is since the last reboot\n //get it now and then in 100ms and compare\n let idleMs = 0;\n let totalMs = 0;\n //loop through each core\n cpus.forEach((aCore)=>{\n for (type in aCore.times){\n totalMs += aCore.times[type];\n }\n idleMs += aCore.times.idle;\n })\n return {\n idle: idleMs/cpus.length,\n total: totalMs/cpus.length\n }\n}",
"function cpuAverage() {\n const cpus = os.cpus();\n //Get ms in each mode, but this number is since reboot\n //So get it now, and get it in 100ms and compare\n let idleMs = 0;\n let totalMs = 0;\n cpus.forEach((core) => {\n //Loop through each property of the current core\n for (type in core.times) {\n totalMs += core.times[type];\n }\n idleMs += core.times.idle;\n });\n\n return {\n idle: idleMs / cpus.length,\n total: totalMs / cpus.length,\n };\n}",
"function cpuAverage(){\n const cpus = os.cpus();\n // get ms in each mode, BUT this number is since reboot\n // so get it now, and get it in 100ms and compare\n let idleMs = 0;\n let totalMs = 0;\n \n cpus.forEach((core)=>{\n // loop through each property of the current core\n for(type in core.times){\n totalMs += core.times[type];\n }\n idleMs += core.times.idle;\n });\n return {\n idle: idleMs / cpus.length,\n total: totalMs / cpus.length\n }\n}",
"function avgVel(){\r\n initialCondition();\r\n for(let i=0; i<steps; i++){\r\n sum = 0;\r\n //sum adds averagedVelocity of each particle at ith step\r\n for(let j=0; j<n; j++) displ[j] = stepCount[j];\r\n \r\n //Storing current displacements in the array\r\n ruleset();\r\n for(let j=0; j<n; j++) {\r\n sum += stepCount[j] - displ[j];\r\n velData[i][j] = stepCount[j] - displ[j];\r\n }\r\n //average averagedVelocity of all particles to be added in averagedVelocity array\r\n averagedVelocity.push(sum/n);\r\n }\r\n}",
"function computeStats() {\n kineticE = 0;\n gravitationalE = 0;\n momentumX = 0;\n momentumY = 0;\n var g = Number(getGravity());\n for (var i = 0; i < N; i++) {\n kineticE += 0.5 * (vx[i] * vx[i] + vy[i] * vy[i]);\n gravitationalE += g * y[i];\n momentumX += vx[i];\n momentumY += vy[i];\n }\n var currentT = kineticE / (N - fixedCount);\n safetyCheck(currentT);\n}",
"calculateAverage(distance) {\n var cache = this.state.dsCache;\n var cap = 7;\n if (distance != undefined && distance > 0) {\n cache.push(distance);\n }\n\n if (cache.length >= cap) {\n var newCache = new Array(cap);\n for (var i = 0; i < cap; i++) {\n newCache[i] = cache[i + 1];\n }\n this.setState({dsCache: newCache});\n } else {\n cap = cache.length;\n }\n \n var total = 0;\n var ds;\n cache = this.state.dsCache;\n for (ds in cache) {\n if (cache[ds] != undefined) {\n total += cache[ds];\n } else {\n cap--;\n }\n }\n\n // * 3.28084 gives approx foot conversion\n return (total / cap) * 3.28084;\n }",
"function calcSpeed(v) {\n\t var x = v.x, y = v.y;\n\t return Math.sqrt(x * x + y * y);\n\t }",
"function calcSpeed(v) {\n var x = v.x,\n y = v.y;\n return Math.sqrt(x * x + y * y);\n }",
"function getAccelerationRate(lastPt, mousePt) {\n let xpow = Math.pow(lastPt.x - mousePt.x, 2);\n let ypow = Math.pow(lastPt.y - mousePt.y, 2);\n let currentLength = Math.sqrt(xpow + ypow);\n let r = currentLength / (100 + currentLength) + 1.0;\n return r;\n }",
"function avgDistance(part,m) {\n\tvar distances = [];\n\tdistances.push(part.distance);\n\tfor (var i = 0; i < m; i++) {\n\t\tpart = particleMove(part);\n\t\tdistances.push(part.distance);\n\t}\n\t//console.log(distances);\n\treturn distances.reduce(((prev,cur) => prev + cur),0) / (m + 1);\n}",
"totalEnergy(timestep) {\n let energy = 0.0;\n this.eachNode(function(node, point) {\n const speed = point.velocity.length();\n energy += 0.5 * point.mass * speed * speed;\n });\n\n return energy;\n }",
"function averageStretch(route) {\n var average = []\n for (var i = 0; i < route.length; i++){\n var\n }\n return average\n\n}",
"calcEnergy(){\r\n this.kineticE=this.mass*(Math.pow(this.speed.x,2)+Math.pow(this.speed.y,2));\r\n this.totalE=this.kineticE+this.heatE;\r\n }",
"average() {\n\n let runner = this.head;\n let sum = 0;\n let cnt = 0;\n\n while (runner) {\n cnt++\n sum += runner.val;\n runner = runner.next;\n }\n\n return Math.round((sum / cnt) * 100) / 100;\n }",
"average() {\n if (this.length === 0) {\n throw new Error(\"EmptySortedList\")\n } else {\n return (this.items.reduce((prev, curr) => prev + curr)) / this.length;\n }\n }",
"getAvgAltitude() {\n return Math.max(0, this.altitude + (this.elevGain - this.elevLoss) / 2.0)\n }",
"accelerate() {\n this.speed += this.acceleration;\n console.log(\"Current speed: \" + this.speed);\n }",
"get userAcceleration() {}",
"calculateStress(_line, _totalReceived) {\n const _totalPriority = _.reduce(_line.claims, (_tot, _c) => _tot + _c.priority, 0);\n\n _.each(_line.claims, _claim => {\n let _recv = _totalReceived[_claim.claimer] || 0;\n let totalAvailable = this.calculateAvailableCharge( _line.t, _claim.deadline);\n _claim.available = totalAvailable * ( _claim.priority / _totalPriority ); \n //_claim.stress = ( _claim.chargeNeeded - _recv ) / _claim.available;\n \n\n //if stress > 1, means there is more available than you need\n //if stress < 1, means there is way less available than you need.\n //cap it to 20, because reasons.\n _claim.stress = _.min([_maxStress,Math.ceil(( _claim.chargeNeeded - _recv ) / _claim.available)]);\n\n });\n }",
"avg() {\n let t = 0;\n for (let i = 0; i < this._b.length; ++i) {\n t += this._b[i];\n }\n\n return t / this._b.lentgh;\n }",
"static get _FULL_SPEED_ADVANCES() {\n\t\treturn 10000;\n\t}",
"function avgComboDPS(mon, move1, move2, ivAtk, pokeLevel) {\n const cache = {}\n FinalEvos.forEach((opponent) => {\n const res = comboDPS(\n mon,\n opponent,\n ivAtk,\n N_IV,\n pokeLevel || N_LVL,\n N_LVL,\n move1,\n move2\n )\n cache[opponent.name] = res\n })\n\n const goodAgainst = FinalEvos\n .map(x => Object.assign({\n dps: cache[x.name].combo.dps,\n score: (\n cache[x.name].combo.dps *\n cp.getMaxCPForLevel(PokeCache[x.name], LevelToCPM[N_LVL])\n ),\n }, PokeCache[x.name]))\n .sort((a, b) => a.score > b.score ? -1 : 1)\n .slice(0, 10)\n\n const badAgainst = FinalEvos\n .map(x => cache[x.name])\n .sort((a, b) => a.combo.dps > b.combo.dps ? 1 : -1)\n .map(x => PokeCache[x.name])\n .slice(0, 10)\n\n const common = CommonGymPokemon\n .map(x => Object.assign({\n dps: cache[x.name].combo.dps,\n }, PokeCache[x.name]))\n\n const dpsAverage = GymPokemon.map(x => cache[x.name])\n const avg = getAvgFrom(dpsAverage)\n\n const dmg1 = avg(x => x.quick.dmg)\n const dmg2 = avg(x => x.charge.dmg)\n\n return {\n combo: {\n name: `${move1}/${move2}`,\n dps: fix(avg(x => x.combo.dps)),\n gymDPS: fix(avg(x => x.combo.gymDPS)),\n retired: mon.moves.combo.filter(x => x.A === move1 && x.B === move2).every(x => x.retired === true),\n },\n quick: Object.assign({}, schemaMove(mon, move1, dmg1)),\n charge: Object.assign({}, schemaMove(mon, move2, dmg2)),\n meta: { badAgainst, goodAgainst, common },\n }\n}",
"function calculateAverageTimeInterval() {\n var sumOfAllIntervals = 0;\n visibleHighlightedPoints = [];\n $.each(this.selectedPoints, getVisiblePoints.bind(this, visibleHighlightedPoints));\n\n visibleHighlightedPoints.sort(sorter);\n\n $.each(visibleHighlightedPoints, function(index, value) {\n if (index != visibleHighlightedPoints.length - 1)\n sumOfAllIntervals += visibleHighlightedPoints[index + 1] - value;\n });\n if (visibleHighlightedPoints.length == 1)\n return -1;\n return sumOfAllIntervals / (visibleHighlightedPoints.length - 1);\n }",
"calTotalEnergy(){\n this.energy = 0;\n this.Nodes.forEach(element => {\n this.energy += Math.pow(this.calVecNorm(element.v), 2) * 0.5 * element.m;\n })\n }",
"average() {\n let runner = this.head;\n let sum = 0;\n let cnt = 0;\n\n while (runner) {\n cnt++;\n sum += runner.data;\n runner = runner.next;\n }\n return sum / cnt;\n }"
]
| [
"0.6770601",
"0.63206214",
"0.5751441",
"0.57342494",
"0.5631219",
"0.56048125",
"0.55834824",
"0.5582153",
"0.55590516",
"0.5521785",
"0.5505836",
"0.5505342",
"0.54733264",
"0.5462948",
"0.54256374",
"0.5421072",
"0.5416692",
"0.53994256",
"0.5390854",
"0.5390568",
"0.5386258",
"0.5382022",
"0.5364874",
"0.53543055",
"0.5353035",
"0.53508943",
"0.53437805",
"0.5337151",
"0.53321314",
"0.5318567"
]
| 0.78668076 | 0 |
average price of all unlocked reserve | averagePrice() {
var priceAverage = 0;
var nbUnlockedReserve = 0;
for (var reserve of foodList) {
if (reserve.unlock) {
nbUnlockedReserve++;
priceAverage += reserve.priceUpgrade;
}
}
return this.roundValue(priceAverage / nbUnlockedReserve);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"averageSpeed() {\n var speedAverage = 0;\n var nbUnlockedReserve = 0;\n for (var reserve of foodList) {\n if (reserve.unlock) {\n nbUnlockedReserve++;\n speedAverage += reserve.speedOfDelivery;\n }\n }\n return this.roundValue(speedAverage / nbUnlockedReserve);\n }",
"priceRisk() {\n const tickets = this.props.tickets.tickets;\n if (tickets) {\n const eventId = this.props.ticket.event.id;\n const ticketPrice = this.props.ticket.price;\n const ticketsPerEvent = tickets.filter(x => x.event.id === eventId);\n const averagePrice =\n ticketsPerEvent\n .map(t => t.price)\n .reduce((price1, price2) => price1 + price2) / ticketsPerEvent.length;\n\n if (ticketPrice >= averagePrice) {\n return -Math.round(((ticketPrice - averagePrice) / ticketPrice) * 100);\n } else {\n return +Math.round(((averagePrice - ticketPrice) / averagePrice) * 100);\n }\n }\n }",
"function mean(housePrices) {\r\n let total = 0;\r\n let i;\r\n for (i=0; i < housePrices.length; i++){\r\n total += housePrices[i];\r\n }\r\n return total / housePrices.length;\r\n}",
"function avg(data){\n let sum = 0;\n for (let i = 0; i < data.products.length; i++) {\n sum += data.products[i].price;\n }\n let avgPrice = sum / data.size;\n return avgPrice;\n}",
"function averagePrice(array) {\n var sum = 0;\n var average = 0;\n array.forEach(function (element) {\n sum += element.price;\n });\n average = sum / array.length;\n return average.toFixed(3);\n }",
"function calculateAveragePrice(flavors) {\n\t\tvar totalPrice=0;\n\t\tvar totalNumber=0;\n\t\tfunction averagePrice(element,index, array){\n\t\t\ttotalNumber=parseInt(element.quantity)+totalNumber;\n\t\t\ttotalPrice=totalPrice+parseInt(element.quantity)*parseInt(element.price.slice(1,element.price.length));\n\t\t}\n\t\tflavors.forEach(averagePrice);\n\t\tvar average=(totalPrice/totalNumber).toFixed(2);\n\t\treturn average;\n\t}",
"function avg(data) {\n const { size, products } = data;\n let sum = 0;\n\n for (let i = 0; i < products.length; i++) {\n sum += products[i].price;\n }\n console.log(`Average price is $ ${sum / size}`);\n}",
"inventoryValue() {\n return this.inventory.reduce(\n (accumulator, book) => total + book.price,\n 0\n );\n }",
"function avgValue() {\n var totalSum = total();\n var avgSum = totalSum / accounts.length;\n return avgSum;\n}",
"function averageRevenue(drivers) {\n return totalRevenue(drivers)/ drivers.length\n}",
"function averagePrice(array) {\n var average = 0;\n for (var i = 0; i < array.length; i++) {\n average = average + array[i].price;\n }\n return (average/i).toFixed(3);\n}",
"function calcAverageProductPrice(products) {\r\n let total = 0;\r\n let priceCount = 0;\r\n for (let i = 0; i < products.length; i++) {\r\n total += products[i].price;\r\n priceCount++;\r\n }\r\n if (priceCount == 0) {\r\n return 0;\r\n }\r\n let averagePrice = total / products.length;\r\n return averagePrice;\r\n}",
"function calcVolatility (rows, range) {\n range = range || rows.length;\n var prices = _.pluck(rows.slice(0, range+1), 'average');\n var mean = _.reduce(prices, function (memo, price) {\n return memo + price;\n }, 0) / range;\n var avg_deviation = _.chain(prices).map(function (price) {\n return Math.pow(price - mean, 2);\n }).reduce(function (memo, price) {\n return memo + price;\n }, 0).value() / range;\n return (Math.sqrt(avg_deviation) / mean) * 100;\n }",
"function average(sum, totalItems) {\n return sum / totalItems;\n}",
"function rateAvg(leaves) {\n \n return d3.mean(leaves, function(d) {\n return d['BorrowerAPR'];\n });\n \n }",
"function avg(arr) {\n var sum = 0\n for (var n = 0; n < arr.length; n++) {\n var price = arr[n]\n sum += price\n }\n var average_price = sum / arr.length\n return average_price\n}",
"function getTotalPrice(details) {\n\t\ttotalPrice = details.pricePerServing*model.getNumberOfGuests();\n\t\treturn totalPrice;\n\t}",
"function calcAverageProductPrice(x) {\n if (x.length == 0) {\n console.log(0);\n return 0;\n }\n var totalProductPrice = 0;\n for (var i = 0; i < x.length; i++) {\n totalProductPrice += x[i].price;\n }\n var averageProductPrice = totalProductPrice / x.length;\n return averageProductPrice;\n}",
"getAvgRating() {\n var ratingSum = 0;\n this.ratings.forEach(mySum);\n function mySum(item) {\n ratingSum += item.rating;\n }\n return ratingSum / this.ratings.length;\n }",
"function question1 () {\nlet avg=0;\nfor (let i=0; i < data.length; i++){\navg = avg+data[i].price\n}\nreturn avg/data.length;\n}",
"average() {\n if (this.length === 0) {\n throw new Error(\"EmptySortedList\")\n } else {\n return (this.items.reduce((prev, curr) => prev + curr)) / this.length;\n }\n }",
"function question1 () {\n // Answer:\n let total = 0;\n let average = 0;\n for (let i = 0; i < data.length; i++) {\n total = total + data[i].price\n };\n average = total/data.length;\n\n console.log(\"The average price is $ \" + average.toFixed(2));\n }",
"function getAverage(){\n\t\t if(checkDWR() == false){\n\t\t\t return;\n\t\t }\n\t\t\n\t\tVotingManagerBean.getAverageAndAlreadyVoted(cpsId, function(data){\t\n\t\t\t\n\t\t\tif (data !=null ){\n\t\t\t\tsetStars (data[0], !data[1]);\n\t\t\t}\n\t\t});\n\t}",
"function averageCost(items) {\n var costTotal = [];\n for (var i = 0; i < items.length; i++) {\n costTotal += items.cost;\n console.log(items.cost);\n }\n\n}",
"function averageCost(avCost){\n\n\tvar sumCost = 0;\n\t\n\tavCost.forEach(function(cost){\n\t\tsumCost += cost.cost;\n\t});\n\n\tconsole.log('El coste medio de los vuelos es de ' + sumCost / avCost.length + ' lolales');\n\n}",
"function question1() {\n // Answer:\n let average = 0;\n let total = 0;\n for (var i = 0; i < data.length; i++) {\n total = total + data[i].price;\n }\n average = total / data.length;\n console.log(\"The average price is $\" + average.toFixed(2));\n}",
"getAverage() {\n return this.getSum() / this.getSize();\n }",
"getTotalMenuPrice() {\n\t\treturn (this.getFullMenu().reduce((a, b) => a + b.pricePerServing, 0) * this.getNumberOfGuests()).toFixed(2);\n\t}",
"totalPrice() {\n return this.collection.reduce(function(accumulator, current){\n return accumulator + current.getPrice();\n }, 0)\n }",
"getAverageRating() {\n let ratingsSum = this.ratings.reduce((currentSum, rating) => currentSum + rating, 0) / this._ratings.length;\n return ratingsSum;\n }"
]
| [
"0.7009207",
"0.6802831",
"0.6528656",
"0.6482315",
"0.64441395",
"0.6419299",
"0.63171864",
"0.6309896",
"0.6304184",
"0.62432075",
"0.62410724",
"0.6213201",
"0.6169113",
"0.61664844",
"0.61397547",
"0.6133566",
"0.6125896",
"0.6108614",
"0.6095981",
"0.6030787",
"0.6016122",
"0.5983627",
"0.5980544",
"0.595634",
"0.59460837",
"0.5920077",
"0.5907523",
"0.5876756",
"0.5853128",
"0.5837334"
]
| 0.8463523 | 0 |
UI enhancement to dismiss the Elements modal when the user clicks outside of the modal and in the window. | function dismissElementsModalOnWindowClick(event) {
var modal = document.querySelector(".ElementsModal--modal");
if (
event.target === modal &&
modal.classList[1] === "ElementsModal--show-modal"
) {
toggleElementsModalVisibility();
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function outsideClick(e) {\r\n if (e.target == modal) {\r\n modal.style.display = \"none\";\r\n }\r\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = \"none\";\n }\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = \"none\";\n }\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = \"none\";\n }\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = \"none\";\n }\n}",
"function outsideClick(e) {\r\n if (e.target == modal) {\r\n modal.style.display = 'none';\r\n }\r\n}",
"function outsideClick(e){\n\n if(e.target == modal){\n modal.style.display=\"none\";\n }\n }",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}",
"function clickOutside(e) {\r\n if (e.target == modal) {\r\n modal.style.display = \"none\";\r\n }\r\n}",
"function outsideClick (e) {\n if (e.target === modal) {\n modal.style.display = 'none';\n }\n}",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.visibility = 'hidden';\n }\n}",
"function outsideClick(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}",
"function outsideClick(e){\n if(e.target == modal){\n modal.style.display = 'none';\n}\n}",
"function outsideclick(e){\n if(e.target == modal){\n modal.style.display='none';\n }\n}",
"function clickOutside(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}",
"function clickOutside(e){\n if(e.target === modal){\n modal.style.display=\"none\";\n\n\n }\n }",
"function outsideClick(e){\n if(e.target == modal){\n closeModal();\n }\n}",
"function clickOutSideWindow(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}",
"function outsideClick(e) {\n\tif (e.target == modal) {\n\t\tmodal.style.display = 'none';\n\t}\n}",
"function clickOutside(e) {\n if(e.target === modal) {\n modal.style.display = \"none\";\n }\n}",
"function clickOutside(e){\n if(e.target == modal){\n modal.style.display = 'none'\n }\n}",
"function clickOutside(event) {\r\n if (event.target == clothModal) {\r\n clothModal.style.display = \"none\";\r\n }\r\n}",
"function _modal_close() {\n\t\t\tvar _overlay = wpmUi._modal_overlay();\n\t\t\tif ( ! _wnd ) { return false; }\n\t\t\tif ( ! _overlay instanceof jQuery ) { return false; }\n\n\t\t\t_overlay.off( 'click', _modal_close );\n\t\t\t_me.hide();\n\t\t}",
"function clickOutside(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}",
"function clickOutside(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}"
]
| [
"0.7739281",
"0.7709359",
"0.7709359",
"0.7709359",
"0.7709359",
"0.7692178",
"0.7680806",
"0.767722",
"0.767722",
"0.767722",
"0.767722",
"0.767722",
"0.767722",
"0.7663674",
"0.7656451",
"0.7636982",
"0.7629511",
"0.76252306",
"0.7602001",
"0.75960267",
"0.75871193",
"0.75854206",
"0.758447",
"0.7580968",
"0.75777113",
"0.7561721",
"0.7556201",
"0.7549771",
"0.7549334",
"0.7549334"
]
| 0.78201985 | 0 |
a poem class, no input params as of yet | function Poem() {
// a poem has a dictionary to query for words
this.dict = new Dictionary('brscript.txt');
// and an array to store things in temporarily
this.poem = [];
var self = this;
// when our dictionary has loaded all its words
this.dict.on('dictLoaded', function() {
self.emit('ready');
});
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"constructor(phrase, point){\r\n this.phrase = phrase;\r\n this.point = point;\r\n }",
"function Pact() {}",
"function Pessoa(nome, sobrenome) {\n this.nome = nome;\n this.sobrenome = sobrenome;\n}",
"function BookProto(title, awesome){\n this.title = title;\n this.awesome = awesome;\n}",
"constructor(nombre,precio,año){\n //variables que siempre tendra un objeto al ser creado \n this.nombre = nombre;\n this.precio = precio;\n this.año = año;\n }",
"function Programmer(name, position, age, language) {\n this.name = name;\n this.position = position;\n this.age = age;\n this.language = language;\n}",
"function IdeaConstructor(title, body, quality){\n this.id = Date.now();\n this.title = title;\n this.body = body;\n this.quality = \"swill\";\n}",
"constructor(params) {\n Vex.Merge(this, SmoNote.defaults);\n smoSerialize.serializedMerge(SmoNote.parameterArray, params, this);\n if (!this.attrs) {\n this.attrs = {\n id: VF.Element.newID(),\n type: 'SmoNote'\n };\n } // else inherit\n }",
"function pokemon(title, sound) {\n this.title = title;\n this.sound = sound;\n}",
"constructor(/* */) {\n\n }",
"constructor(phrase) {\n this.phrase = phrase;\n }",
"function Class(){}",
"function Class(){}",
"function Class(){}",
"constructor() {\n \n\n \n Tip.call(this);\n\n \n\n \n }",
"function poemBuilder() {\n // second, we need to append these poems to the dom\n console.log('i am a poem builder');\n console.log(app);\n var i = app.inc;\n // poem is stored in app.poems[i]\n var newPoem = new app.Poem(app.poems[i]);\n app.poemElements.push(newPoem);\n app.inc++;\n $('body > div:nth-child(2) > section').append(newPoem.el);\n}",
"constructor() {\n super(); // call super-class constructor to initialize variables in PNGRoom\n\n this.titleText = \"\";\n this.bodyText = \"\";\n }",
"constructor(pre, post) {\n this.pre = pre;\n this.post = post;\n }",
"constructor(){}",
"constructor(){}",
"constructor(){}",
"constructor(){}",
"constructor(){}",
"constructor(){}",
"constructor(){}",
"function Policeman() {\n Person.call(this); // calls the Person constructor so now have access to Person's properties.\n this.badgenumber = '1234';\n}",
"function Entity() {\n}",
"function Passage(paragraphs) {\n\tallUnits.push(this);\n\tthis.id = counter;\n\tcounter++;\n\tthis.units = new Array();\n\tif (units != null) {\n\t\tfor (var i=0; i< paragraphs.length; i++) {\n\t\t\tif (units[i] instanceof Paragraph) {\n\t\t\t\tthis.units.push(unit);\n\t\t\t}\n\t\t\telse { //an array of text.\n\t\t\t\tvar parag = new Paragraph(this, paragraphs[i]);\n\t\t\t\tthis.units.push(parag);\n\t\t\t}\n\t\t}\n\t}\n}",
"constructor (proto) {\n this.proto = proto;\n }",
"constructor(nombre,apellido){\n //console.log('Ejecutando el constructor');\n\n this.nombre = nombre;\n this.apellido = apellido;\n }"
]
| [
"0.6197458",
"0.60396737",
"0.5884632",
"0.581888",
"0.5762291",
"0.570981",
"0.56753",
"0.56683004",
"0.5658723",
"0.5658572",
"0.56345683",
"0.56335205",
"0.56335205",
"0.56335205",
"0.5625298",
"0.5613763",
"0.5596756",
"0.5595917",
"0.558306",
"0.558306",
"0.558306",
"0.558306",
"0.558306",
"0.558306",
"0.558306",
"0.5576197",
"0.5575925",
"0.55752957",
"0.55616236",
"0.5560438"
]
| 0.62724316 | 0 |
Loads the Babel standalone library | async loadBabel(options = {}) {
const { runtime } = this
const { assetLoader } = runtime
if (this.loading) {
return new Promise(resolve => {
setTimeout(resolve, 20)
}).then(() => this.loadBabel())
}
if (window.Babel) {
this.ready = true
this.emit('ready', window.Babel)
return window.Babel
}
this.loading = true
await assetLoader.inject.js(`https://unpkg.com/@babel/[email protected]/babel.min.js`)
this.ready = true
this.loading = false
this.emit('ready', window.Babel)
return window.Babel
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function Babel(config) {\n this.config = config;\n}",
"get _parallelBabel() {\n if (this.portableConfig.isParallelSafe) {\n return {\n requireFile: __filename,\n buildUsing: 'rehydrate',\n params: this.portableConfig.portable,\n };\n }\n }",
"async function bundle() {\n const { bundle } = await import('../../scripts/bundle.js');\n await bundle();\n}",
"_init() {\n\t\tthis.babel = require('babel-core');\n\t\treturn this._transform;\n\t}",
"function startBabelSource () {\n return new Promise((fulfill, reject) => {\n const babelSource = fork(\n path.join(modulePath, '.bin', 'babel'),\n 'src --out-dir dist --source-maps --presets latest'.split(' '),\n { silent: true }\n );\n\n children.push(babelSource);\n\n babelSource.on('exit', exitCode => {\n if (exitCode > 0) {\n return reject('Failed compiling source files');\n }\n\n logSuccess('Finished compiling source files');\n\n return fulfill();\n });\n\n babelSource.stdout.on('data', logInfo);\n babelSource.stderr.on('data', logError);\n });\n}",
"function getCustomBabelConfig(configFilePath){if(isJsonFile.exec(configFilePath)){const babelConfigRaw=(0,_fs.readFileSync)(configFilePath,'utf8');return JSON.parse(babelConfigRaw);}else if(isJsFile.exec(configFilePath)){return require(configFilePath);}throw new Error('The Next Babel loader does not support MJS or CJS config files.');}",
"function jsy_babel(config) {\n config = Object.assign({}, default_config, config);\n\n const jsy = jsy_babel.jsy_preset.slice();\n jsy[1] = Object.assign({}, jsy[1], config.env, config.jsy);\n\n config.presets = [jsy].concat(config.presets || []);\n\n const rpi = rpi_babel(config);\n rpi.name = 'jsy-babel';\n return rpi\n}",
"load() {\n (0, $ae7eaaa2c9c1e05d$export$817eb92a8194bab0)();\n }",
"load() {\n (0, $ae7eaaa2c9c1e05d$export$817eb92a8194bab0)();\n }",
"function getBabelVersion() {\n return require('babel-core/package.json').version;\n}",
"configure(bundle) {\n bundle.on('prebundle', () => {\n bundle.external('react/addons');\n bundle.external('react/lib/ReactContext');\n bundle.external('react/lib/ExecutionEnvironment');\n });\n }",
"async function buildBabel (dir, type) {\n const configs = CONFIGS.map((c) => path.join(process.cwd(), `../../${c}`));\n const outDir = path.join(process.cwd(), 'build');\n\n await babel({\n babelOptions: {\n configFile: type === 'esm'\n ? path.join(__dirname, '../config/babel-config-esm.cjs')\n : configs.find((f) => fs.existsSync(f)) || path.join(__dirname, '../config/babel-config-cjs.cjs')\n },\n cliOptions: {\n extensions: ['.ts', '.tsx'],\n filenames: ['src'],\n ignore: '**/*.d.ts',\n outDir,\n outFileExtension: type === 'esm' ? ESM : '.js'\n }\n });\n\n // rewrite a skeleton package.json with a type=module\n if (type !== 'esm') {\n [...CPX]\n .concat(`../../build/${dir}/src/**/*.d.ts`, `../../build/packages/${dir}/src/**/*.d.ts`)\n .forEach((src) => copySync(src, 'build'));\n }\n}",
"function babelTask() {\n return src(files.jsPath)\n .pipe(sourcemaps.init())\n .pipe(babel({\n presets: [\"@babel/preset-env\"]\n }))\n .pipe(concat('main.js'))\n .pipe(uglify())\n .pipe(sourcemaps.write('/.'))\n .pipe(dest('pub/js'))\n .pipe(browserSync.stream())\n}",
"function loadBundle(bundleId, _a, importer) {\n var dependentsList = _a.slice(0);\n var missingDependents = dependentsList.filter(function (d) { return !isLoadedBundle(d); });\n missingDependents.forEach(function (d) {\n var fileName = d.replace('.js', '.es5.js');\n loadFile(fileName);\n });\n execBundleCallback(bundleId, dependentsList, importer);\n }",
"function addBabelConfiguration(config, language) {\n config.transpiler = \"plugin-babel\";\n config.meta['*.jsx'] = {\n babelOptions: {\n react: true\n }\n };\n\n config.packages['app'] = {\n main: './main.' + language\n };\n\n config.map['plugin-babel'] = \"https://unpkg.com/[email protected]/plugin-babel.js\";\n config.map['systemjs-babel-build'] = 'https://unpkg.com/[email protected]/systemjs-babel-browser.js';\n }",
"function loadWebAssembly(fileName) {\n return fetch(fileName)\n .then(response => response.arrayBuffer())\n .then(buffer => WebAssembly.compile(buffer))\n .then(module => {return new WebAssembly.Instance(module) });\n }",
"require() {}",
"function loadbang() {\n setup();\n}",
"function ClassLoader() {\n}",
"function loader (content, inputSourceMap) {\n const options = {\n presets: ['@babel/preset-env'],\n inputSourceMap,\n sourceMaps: true,\n filename: path.basename(this.resourcePath)\n };\n const { code, map, ast } = babel.transformSync(content, options);\n // this.callback: 一个函数为了返回多个参数被同步或异步的调用\n // 如果你想要在loader之间共享公共的ASTs, 传入一个抽象语法树作为第四个参数来加速构建的时间是有用的\n return this.callback(null, code, map, ast);\n}",
"function BundleLoader() {\n\t\t// Already loaded loaders\n\t\tthis.loaders = { };\n\t}",
"function loadLib() {\n /**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global Packages: false, process: false, window: false, navigator: false,\n document: false, define: false */\n\n/**\n * A plugin that modifies any /env/ path to be the right path based on\n * the host environment. Right now only works for Node, Rhino and browser.\n */\n(function () {\n var pathRegExp = /(\\/|^)env\\/|\\{env\\}/,\n env = 'unknown';\n\n if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {\n env = 'node';\n } else if (typeof Packages !== 'undefined') {\n env = 'rhino';\n } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||\n (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {\n env = 'browser';\n } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {\n env = 'xpconnect';\n }\n\n define('env', {\n get: function () {\n return env;\n },\n\n load: function (name, req, load, config) {\n //Allow override in the config.\n if (config.env) {\n env = config.env;\n }\n\n name = name.replace(pathRegExp, function (match, prefix) {\n if (match.indexOf('{') === -1) {\n return prefix + env + '/';\n } else {\n return env;\n }\n });\n\n req([name], function (mod) {\n load(mod);\n });\n }\n });\n}());\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint plusplus: true */\n/*global define, java */\n\ndefine('lang', function () {\n 'use strict';\n\n var lang, isJavaObj,\n hasOwn = Object.prototype.hasOwnProperty;\n\n function hasProp(obj, prop) {\n return hasOwn.call(obj, prop);\n }\n\n isJavaObj = function () {\n return false;\n };\n\n if (typeof java !== 'undefined' && java.lang && java.lang.Object) {\n isJavaObj = function (obj) {\n return obj instanceof java.lang.Object;\n };\n }\n\n lang = {\n backSlashRegExp: /\\\\/g,\n ostring: Object.prototype.toString,\n\n isArray: Array.isArray || function (it) {\n return lang.ostring.call(it) === \"[object Array]\";\n },\n\n isFunction: function(it) {\n return lang.ostring.call(it) === \"[object Function]\";\n },\n\n isRegExp: function(it) {\n return it && it instanceof RegExp;\n },\n\n hasProp: hasProp,\n\n //returns true if the object does not have an own property prop,\n //or if it does, it is a falsy value.\n falseProp: function (obj, prop) {\n return !hasProp(obj, prop) || !obj[prop];\n },\n\n //gets own property value for given prop on object\n getOwn: function (obj, prop) {\n return hasProp(obj, prop) && obj[prop];\n },\n\n _mixin: function(dest, source, override){\n var name;\n for (name in source) {\n if(source.hasOwnProperty(name) &&\n (override || !dest.hasOwnProperty(name))) {\n dest[name] = source[name];\n }\n }\n\n return dest; // Object\n },\n\n /**\n * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,\n * then the source objects properties are force copied over to dest.\n */\n mixin: function(dest){\n var parameters = Array.prototype.slice.call(arguments),\n override, i, l;\n\n if (!dest) { dest = {}; }\n\n if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {\n override = parameters.pop();\n }\n\n for (i = 1, l = parameters.length; i < l; i++) {\n lang._mixin(dest, parameters[i], override);\n }\n return dest; // Object\n },\n\n /**\n * Does a deep mix of source into dest, where source values override\n * dest values if a winner is needed.\n * @param {Object} dest destination object that receives the mixed\n * values.\n * @param {Object} source source object contributing properties to mix\n * in.\n * @return {[Object]} returns dest object with the modification.\n */\n deepMix: function(dest, source) {\n lang.eachProp(source, function (value, prop) {\n if (typeof value === 'object' && value &&\n !lang.isArray(value) && !lang.isFunction(value) &&\n !(value instanceof RegExp)) {\n\n if (!dest[prop]) {\n dest[prop] = {};\n }\n lang.deepMix(dest[prop], value);\n } else {\n dest[prop] = value;\n }\n });\n return dest;\n },\n\n /**\n * Does a type of deep copy. Do not give it anything fancy, best\n * for basic object copies of objects that also work well as\n * JSON-serialized things, or has properties pointing to functions.\n * For non-array/object values, just returns the same object.\n * @param {Object} obj copy properties from this object\n * @param {Object} [result] optional result object to use\n * @return {Object}\n */\n deeplikeCopy: function (obj) {\n var type, result;\n\n if (lang.isArray(obj)) {\n result = [];\n obj.forEach(function(value) {\n result.push(lang.deeplikeCopy(value));\n });\n return result;\n }\n\n type = typeof obj;\n if (obj === null || obj === undefined || type === 'boolean' ||\n type === 'string' || type === 'number' || lang.isFunction(obj) ||\n lang.isRegExp(obj)|| isJavaObj(obj)) {\n return obj;\n }\n\n //Anything else is an object, hopefully.\n result = {};\n lang.eachProp(obj, function(value, key) {\n result[key] = lang.deeplikeCopy(value);\n });\n return result;\n },\n\n delegate: (function () {\n // boodman/crockford delegation w/ cornford optimization\n function TMP() {}\n return function (obj, props) {\n TMP.prototype = obj;\n var tmp = new TMP();\n TMP.prototype = null;\n if (props) {\n lang.mixin(tmp, props);\n }\n return tmp; // Object\n };\n }()),\n\n /**\n * Helper function for iterating over an array. If the func returns\n * a true value, it will break out of the loop.\n */\n each: function each(ary, func) {\n if (ary) {\n var i;\n for (i = 0; i < ary.length; i += 1) {\n if (func(ary[i], i, ary)) {\n break;\n }\n }\n }\n },\n\n /**\n * Cycles over properties in an object and calls a function for each\n * property value. If the function returns a truthy value, then the\n * iteration is stopped.\n */\n eachProp: function eachProp(obj, func) {\n var prop;\n for (prop in obj) {\n if (hasProp(obj, prop)) {\n if (func(obj[prop], prop)) {\n break;\n }\n }\n }\n },\n\n //Similar to Function.prototype.bind, but the \"this\" object is specified\n //first, since it is easier to read/figure out what \"this\" will be.\n bind: function bind(obj, fn) {\n return function () {\n return fn.apply(obj, arguments);\n };\n },\n\n //Escapes a content string to be be a string that has characters escaped\n //for inclusion as part of a JS string.\n jsEscape: function (content) {\n return content.replace(/([\"'\\\\])/g, '\\\\$1')\n .replace(/[\\f]/g, \"\\\\f\")\n .replace(/[\\b]/g, \"\\\\b\")\n .replace(/[\\n]/g, \"\\\\n\")\n .replace(/[\\t]/g, \"\\\\t\")\n .replace(/[\\r]/g, \"\\\\r\");\n }\n };\n return lang;\n});\n/**\n * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/requirejs/prim for details\n */\n\n/*global setImmediate, process, setTimeout, define, module */\n\n//Set prime.hideResolutionConflict = true to allow \"resolution-races\"\n//in promise-tests to pass.\n//Since the goal of prim is to be a small impl for trusted code, it is\n//more important to normally throw in this case so that we can find\n//logic errors quicker.\n\nvar prim;\n(function () {\n 'use strict';\n var op = Object.prototype,\n hasOwn = op.hasOwnProperty;\n\n function hasProp(obj, prop) {\n return hasOwn.call(obj, prop);\n }\n\n /**\n * Helper function for iterating over an array. If the func returns\n * a true value, it will break out of the loop.\n */\n function each(ary, func) {\n if (ary) {\n var i;\n for (i = 0; i < ary.length; i += 1) {\n if (ary[i]) {\n func(ary[i], i, ary);\n }\n }\n }\n }\n\n function check(p) {\n if (hasProp(p, 'e') || hasProp(p, 'v')) {\n if (!prim.hideResolutionConflict) {\n throw new Error('nope');\n }\n return false;\n }\n return true;\n }\n\n function notify(ary, value) {\n prim.nextTick(function () {\n each(ary, function (item) {\n item(value);\n });\n });\n }\n\n prim = function prim() {\n var p,\n ok = [],\n fail = [];\n\n return (p = {\n callback: function (yes, no) {\n if (no) {\n p.errback(no);\n }\n\n if (hasProp(p, 'v')) {\n prim.nextTick(function () {\n yes(p.v);\n });\n } else {\n ok.push(yes);\n }\n },\n\n errback: function (no) {\n if (hasProp(p, 'e')) {\n prim.nextTick(function () {\n no(p.e);\n });\n } else {\n fail.push(no);\n }\n },\n\n finished: function () {\n return hasProp(p, 'e') || hasProp(p, 'v');\n },\n\n rejected: function () {\n return hasProp(p, 'e');\n },\n\n resolve: function (v) {\n if (check(p)) {\n p.v = v;\n notify(ok, v);\n }\n return p;\n },\n reject: function (e) {\n if (check(p)) {\n p.e = e;\n notify(fail, e);\n }\n return p;\n },\n\n start: function (fn) {\n p.resolve();\n return p.promise.then(fn);\n },\n\n promise: {\n then: function (yes, no) {\n var next = prim();\n\n p.callback(function (v) {\n try {\n if (yes && typeof yes === 'function') {\n v = yes(v);\n }\n\n if (v && v.then) {\n v.then(next.resolve, next.reject);\n } else {\n next.resolve(v);\n }\n } catch (e) {\n next.reject(e);\n }\n }, function (e) {\n var err;\n\n try {\n if (!no || typeof no !== 'function') {\n next.reject(e);\n } else {\n err = no(e);\n\n if (err && err.then) {\n err.then(next.resolve, next.reject);\n } else {\n next.resolve(err);\n }\n }\n } catch (e2) {\n next.reject(e2);\n }\n });\n\n return next.promise;\n },\n\n fail: function (no) {\n return p.promise.then(null, no);\n },\n\n end: function () {\n p.errback(function (e) {\n throw e;\n });\n }\n }\n });\n };\n\n prim.serial = function (ary) {\n var result = prim().resolve().promise;\n each(ary, function (item) {\n result = result.then(function () {\n return item();\n });\n });\n return result;\n };\n\n prim.nextTick = typeof setImmediate === 'function' ? setImmediate :\n (typeof process !== 'undefined' && process.nextTick ?\n process.nextTick : (typeof setTimeout !== 'undefined' ?\n function (fn) {\n setTimeout(fn, 0);\n } : function (fn) {\n fn();\n }));\n\n if (typeof define === 'function' && define.amd) {\n define('prim', function () { return prim; });\n } else if (typeof module !== 'undefined' && module.exports) {\n module.exports = prim;\n }\n}());\nif(env === 'browser') {\n/**\n * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, load: false */\n\n//Just a stub for use with uglify's consolidator.js\ndefine('browser/assert', function () {\n return {};\n});\n\n}\n\nif(env === 'node') {\n/**\n * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, load: false */\n\n//Needed so that rhino/assert can return a stub for uglify's consolidator.js\ndefine('node/assert', ['assert'], function (assert) {\n return assert;\n});\n\n}\n\nif(env === 'rhino') {\n/**\n * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, load: false */\n\n//Just a stub for use with uglify's consolidator.js\ndefine('rhino/assert', function () {\n return {};\n});\n\n}\n\nif(env === 'xpconnect') {\n/**\n * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, load: false */\n\n//Just a stub for use with uglify's consolidator.js\ndefine('xpconnect/assert', function () {\n return {};\n});\n\n}\n\nif(env === 'browser') {\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, process: false */\n\ndefine('browser/args', function () {\n //Always expect config via an API call\n return [];\n});\n\n}\n\nif(env === 'node') {\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, process: false */\n\ndefine('node/args', function () {\n //Do not return the \"node\" or \"r.js\" arguments\n var args = process.argv.slice(2);\n\n //Ignore any command option used for main x.js branching\n if (args[0] && args[0].indexOf('-') === 0) {\n args = args.slice(1);\n }\n\n return args;\n});\n\n}\n\nif(env === 'rhino') {\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, process: false */\n\nvar jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));\n\ndefine('rhino/args', function () {\n var args = jsLibRhinoArgs;\n\n //Ignore any command option used for main x.js branching\n if (args[0] && args[0].indexOf('-') === 0) {\n args = args.slice(1);\n }\n\n return args;\n});\n\n}\n\nif(env === 'xpconnect') {\n/**\n * @license Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define, xpconnectArgs */\n\nvar jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0));\n\ndefine('xpconnect/args', function () {\n var args = jsLibXpConnectArgs;\n\n //Ignore any command option used for main x.js branching\n if (args[0] && args[0].indexOf('-') === 0) {\n args = args.slice(1);\n }\n\n return args;\n});\n\n}\n\nif(env === 'browser') {\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, console: false */\n\ndefine('browser/load', ['./file'], function (file) {\n function load(fileName) {\n eval(file.readFile(fileName));\n }\n\n return load;\n});\n\n}\n\nif(env === 'node') {\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, console: false */\n\ndefine('node/load', ['fs'], function (fs) {\n function load(fileName) {\n var contents = fs.readFileSync(fileName, 'utf8');\n process.compile(contents, fileName);\n }\n\n return load;\n});\n\n}\n\nif(env === 'rhino') {\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, load: false */\n\ndefine('rhino/load', function () {\n return load;\n});\n\n}\n\nif(env === 'xpconnect') {\n/**\n * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, load: false */\n\ndefine('xpconnect/load', function () {\n return load;\n});\n\n}\n\nif(env === 'browser') {\n/**\n * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint sloppy: true, nomen: true */\n/*global require, define, console, XMLHttpRequest, requirejs, location */\n\ndefine('browser/file', ['prim'], function (prim) {\n\n var file,\n currDirRegExp = /^\\.(\\/|$)/;\n\n function frontSlash(path) {\n return path.replace(/\\\\/g, '/');\n }\n\n function exists(path) {\n var status, xhr = new XMLHttpRequest();\n\n //Oh yeah, that is right SYNC IO. Behold its glory\n //and horrible blocking behavior.\n xhr.open('HEAD', path, false);\n xhr.send();\n status = xhr.status;\n\n return status === 200 || status === 304;\n }\n\n function mkDir(dir) {\n console.log('mkDir is no-op in browser');\n }\n\n function mkFullDir(dir) {\n console.log('mkFullDir is no-op in browser');\n }\n\n file = {\n backSlashRegExp: /\\\\/g,\n exclusionRegExp: /^\\./,\n getLineSeparator: function () {\n return '/';\n },\n\n exists: function (fileName) {\n return exists(fileName);\n },\n\n parent: function (fileName) {\n var parts = fileName.split('/');\n parts.pop();\n return parts.join('/');\n },\n\n /**\n * Gets the absolute file path as a string, normalized\n * to using front slashes for path separators.\n * @param {String} fileName\n */\n absPath: function (fileName) {\n var dir;\n if (currDirRegExp.test(fileName)) {\n dir = frontSlash(location.href);\n if (dir.indexOf('/') !== -1) {\n dir = dir.split('/');\n\n //Pull off protocol and host, just want\n //to allow paths (other build parts, like\n //require._isSupportedBuildUrl do not support\n //full URLs), but a full path from\n //the root.\n dir.splice(0, 3);\n\n dir.pop();\n dir = '/' + dir.join('/');\n }\n\n fileName = dir + fileName.substring(1);\n }\n\n return fileName;\n },\n\n normalize: function (fileName) {\n return fileName;\n },\n\n isFile: function (path) {\n return true;\n },\n\n isDirectory: function (path) {\n return false;\n },\n\n getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) {\n console.log('file.getFilteredFileList is no-op in browser');\n },\n\n copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) {\n console.log('file.copyDir is no-op in browser');\n\n },\n\n copyFile: function (srcFileName, destFileName, onlyCopyNew) {\n console.log('file.copyFile is no-op in browser');\n },\n\n /**\n * Renames a file. May fail if \"to\" already exists or is on another drive.\n */\n renameFile: function (from, to) {\n console.log('file.renameFile is no-op in browser');\n },\n\n /**\n * Reads a *text* file.\n */\n readFile: function (path, encoding) {\n var xhr = new XMLHttpRequest();\n\n //Oh yeah, that is right SYNC IO. Behold its glory\n //and horrible blocking behavior.\n xhr.open('GET', path, false);\n xhr.send();\n\n return xhr.responseText;\n },\n\n readFileAsync: function (path, encoding) {\n var xhr = new XMLHttpRequest(),\n d = prim();\n\n xhr.open('GET', path, true);\n xhr.send();\n\n xhr.onreadystatechange = function () {\n if (xhr.readyState === 4) {\n if (xhr.status > 400) {\n d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText));\n } else {\n d.resolve(xhr.responseText);\n }\n }\n };\n\n return d.promise;\n },\n\n saveUtf8File: function (fileName, fileContents) {\n //summary: saves a *text* file using UTF-8 encoding.\n file.saveFile(fileName, fileContents, \"utf8\");\n },\n\n saveFile: function (fileName, fileContents, encoding) {\n requirejs.browser.saveFile(fileName, fileContents, encoding);\n },\n\n deleteFile: function (fileName) {\n console.log('file.deleteFile is no-op in browser');\n },\n\n /**\n * Deletes any empty directories under the given directory.\n */\n deleteEmptyDirs: function (startDir) {\n console.log('file.deleteEmptyDirs is no-op in browser');\n }\n };\n\n return file;\n\n});\n\n}\n\nif(env === 'node') {\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint plusplus: false, octal:false, strict: false */\n/*global define: false, process: false */\n\ndefine('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) {\n\n var isWindows = process.platform === 'win32',\n windowsDriveRegExp = /^[a-zA-Z]\\:\\/$/,\n file;\n\n function frontSlash(path) {\n return path.replace(/\\\\/g, '/');\n }\n\n function exists(path) {\n if (isWindows && path.charAt(path.length - 1) === '/' &&\n path.charAt(path.length - 2) !== ':') {\n path = path.substring(0, path.length - 1);\n }\n\n try {\n fs.statSync(path);\n return true;\n } catch (e) {\n return false;\n }\n }\n\n function mkDir(dir) {\n if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {\n fs.mkdirSync(dir, 511);\n }\n }\n\n function mkFullDir(dir) {\n var parts = dir.split('/'),\n currDir = '',\n first = true;\n\n parts.forEach(function (part) {\n //First part may be empty string if path starts with a slash.\n currDir += part + '/';\n first = false;\n\n if (part) {\n mkDir(currDir);\n }\n });\n }\n\n file = {\n backSlashRegExp: /\\\\/g,\n exclusionRegExp: /^\\./,\n getLineSeparator: function () {\n return '/';\n },\n\n exists: function (fileName) {\n return exists(fileName);\n },\n\n parent: function (fileName) {\n var parts = fileName.split('/');\n parts.pop();\n return parts.join('/');\n },\n\n /**\n * Gets the absolute file path as a string, normalized\n * to using front slashes for path separators.\n * @param {String} fileName\n */\n absPath: function (fileName) {\n return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));\n },\n\n normalize: function (fileName) {\n return frontSlash(path.normalize(fileName));\n },\n\n isFile: function (path) {\n return fs.statSync(path).isFile();\n },\n\n isDirectory: function (path) {\n return fs.statSync(path).isDirectory();\n },\n\n getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {\n //summary: Recurses startDir and finds matches to the files that match regExpFilters.include\n //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,\n //and it will be treated as the \"include\" case.\n //Ignores files/directories that start with a period (.) unless exclusionRegExp\n //is set to another value.\n var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,\n i, stat, filePath, ok, dirFiles, fileName;\n\n topDir = startDir;\n\n regExpInclude = regExpFilters.include || regExpFilters;\n regExpExclude = regExpFilters.exclude || null;\n\n if (file.exists(topDir)) {\n dirFileArray = fs.readdirSync(topDir);\n for (i = 0; i < dirFileArray.length; i++) {\n fileName = dirFileArray[i];\n filePath = path.join(topDir, fileName);\n stat = fs.statSync(filePath);\n if (stat.isFile()) {\n if (makeUnixPaths) {\n //Make sure we have a JS string.\n if (filePath.indexOf(\"/\") === -1) {\n filePath = frontSlash(filePath);\n }\n }\n\n ok = true;\n if (regExpInclude) {\n ok = filePath.match(regExpInclude);\n }\n if (ok && regExpExclude) {\n ok = !filePath.match(regExpExclude);\n }\n\n if (ok && (!file.exclusionRegExp ||\n !file.exclusionRegExp.test(fileName))) {\n files.push(filePath);\n }\n } else if (stat.isDirectory() &&\n (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {\n dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);\n files.push.apply(files, dirFiles);\n }\n }\n }\n\n return files; //Array\n },\n\n copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {\n //summary: copies files from srcDir to destDir using the regExpFilter to determine if the\n //file should be copied. Returns a list file name strings of the destinations that were copied.\n regExpFilter = regExpFilter || /\\w/;\n\n //Normalize th directory names, but keep front slashes.\n //path module on windows now returns backslashed paths.\n srcDir = frontSlash(path.normalize(srcDir));\n destDir = frontSlash(path.normalize(destDir));\n\n var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),\n copiedFiles = [], i, srcFileName, destFileName;\n\n for (i = 0; i < fileNames.length; i++) {\n srcFileName = fileNames[i];\n destFileName = srcFileName.replace(srcDir, destDir);\n\n if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {\n copiedFiles.push(destFileName);\n }\n }\n\n return copiedFiles.length ? copiedFiles : null; //Array or null\n },\n\n copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {\n //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if\n //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.\n var parentDir;\n\n //logger.trace(\"Src filename: \" + srcFileName);\n //logger.trace(\"Dest filename: \" + destFileName);\n\n //If onlyCopyNew is true, then compare dates and only copy if the src is newer\n //than dest.\n if (onlyCopyNew) {\n if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {\n return false; //Boolean\n }\n }\n\n //Make sure destination dir exists.\n parentDir = path.dirname(destFileName);\n if (!file.exists(parentDir)) {\n mkFullDir(parentDir);\n }\n\n fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');\n\n return true; //Boolean\n },\n\n /**\n * Renames a file. May fail if \"to\" already exists or is on another drive.\n */\n renameFile: function (from, to) {\n return fs.renameSync(from, to);\n },\n\n /**\n * Reads a *text* file.\n */\n readFile: function (/*String*/path, /*String?*/encoding) {\n if (encoding === 'utf-8') {\n encoding = 'utf8';\n }\n if (!encoding) {\n encoding = 'utf8';\n }\n\n var text = fs.readFileSync(path, encoding);\n\n //Hmm, would not expect to get A BOM, but it seems to happen,\n //remove it just in case.\n if (text.indexOf('\\uFEFF') === 0) {\n text = text.substring(1, text.length);\n }\n\n return text;\n },\n\n readFileAsync: function (path, encoding) {\n var d = prim();\n try {\n d.resolve(file.readFile(path, encoding));\n } catch (e) {\n d.reject(e);\n }\n return d.promise;\n },\n\n saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {\n //summary: saves a *text* file using UTF-8 encoding.\n file.saveFile(fileName, fileContents, \"utf8\");\n },\n\n saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {\n //summary: saves a *text* file.\n var parentDir;\n\n if (encoding === 'utf-8') {\n encoding = 'utf8';\n }\n if (!encoding) {\n encoding = 'utf8';\n }\n\n //Make sure destination directories exist.\n parentDir = path.dirname(fileName);\n if (!file.exists(parentDir)) {\n mkFullDir(parentDir);\n }\n\n fs.writeFileSync(fileName, fileContents, encoding);\n },\n\n deleteFile: function (/*String*/fileName) {\n //summary: deletes a file or directory if it exists.\n var files, i, stat;\n if (file.exists(fileName)) {\n stat = fs.lstatSync(fileName);\n if (stat.isDirectory()) {\n files = fs.readdirSync(fileName);\n for (i = 0; i < files.length; i++) {\n this.deleteFile(path.join(fileName, files[i]));\n }\n fs.rmdirSync(fileName);\n } else {\n fs.unlinkSync(fileName);\n }\n }\n },\n\n\n /**\n * Deletes any empty directories under the given directory.\n */\n deleteEmptyDirs: function (startDir) {\n var dirFileArray, i, fileName, filePath, stat;\n\n if (file.exists(startDir)) {\n dirFileArray = fs.readdirSync(startDir);\n for (i = 0; i < dirFileArray.length; i++) {\n fileName = dirFileArray[i];\n filePath = path.join(startDir, fileName);\n stat = fs.lstatSync(filePath);\n if (stat.isDirectory()) {\n file.deleteEmptyDirs(filePath);\n }\n }\n\n //If directory is now empty, remove it.\n if (fs.readdirSync(startDir).length === 0) {\n file.deleteFile(startDir);\n }\n }\n }\n };\n\n return file;\n\n});\n\n}\n\nif(env === 'rhino') {\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n//Helper functions to deal with file I/O.\n\n/*jslint plusplus: false */\n/*global java: false, define: false */\n\ndefine('rhino/file', ['prim'], function (prim) {\n var file = {\n backSlashRegExp: /\\\\/g,\n\n exclusionRegExp: /^\\./,\n\n getLineSeparator: function () {\n return file.lineSeparator;\n },\n\n lineSeparator: java.lang.System.getProperty(\"line.separator\"), //Java String\n\n exists: function (fileName) {\n return (new java.io.File(fileName)).exists();\n },\n\n parent: function (fileName) {\n return file.absPath((new java.io.File(fileName)).getParentFile());\n },\n\n normalize: function (fileName) {\n return file.absPath(fileName);\n },\n\n isFile: function (path) {\n return (new java.io.File(path)).isFile();\n },\n\n isDirectory: function (path) {\n return (new java.io.File(path)).isDirectory();\n },\n\n /**\n * Gets the absolute file path as a string, normalized\n * to using front slashes for path separators.\n * @param {java.io.File||String} file\n */\n absPath: function (fileObj) {\n if (typeof fileObj === \"string\") {\n fileObj = new java.io.File(fileObj);\n }\n return (fileObj.getCanonicalPath() + \"\").replace(file.backSlashRegExp, \"/\");\n },\n\n getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {\n //summary: Recurses startDir and finds matches to the files that match regExpFilters.include\n //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,\n //and it will be treated as the \"include\" case.\n //Ignores files/directories that start with a period (.) unless exclusionRegExp\n //is set to another value.\n var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,\n i, fileObj, filePath, ok, dirFiles;\n\n topDir = startDir;\n if (!startDirIsJavaObject) {\n topDir = new java.io.File(startDir);\n }\n\n regExpInclude = regExpFilters.include || regExpFilters;\n regExpExclude = regExpFilters.exclude || null;\n\n if (topDir.exists()) {\n dirFileArray = topDir.listFiles();\n for (i = 0; i < dirFileArray.length; i++) {\n fileObj = dirFileArray[i];\n if (fileObj.isFile()) {\n filePath = fileObj.getPath();\n if (makeUnixPaths) {\n //Make sure we have a JS string.\n filePath = String(filePath);\n if (filePath.indexOf(\"/\") === -1) {\n filePath = filePath.replace(/\\\\/g, \"/\");\n }\n }\n\n ok = true;\n if (regExpInclude) {\n ok = filePath.match(regExpInclude);\n }\n if (ok && regExpExclude) {\n ok = !filePath.match(regExpExclude);\n }\n\n if (ok && (!file.exclusionRegExp ||\n !file.exclusionRegExp.test(fileObj.getName()))) {\n files.push(filePath);\n }\n } else if (fileObj.isDirectory() &&\n (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {\n dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);\n files.push.apply(files, dirFiles);\n }\n }\n }\n\n return files; //Array\n },\n\n copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {\n //summary: copies files from srcDir to destDir using the regExpFilter to determine if the\n //file should be copied. Returns a list file name strings of the destinations that were copied.\n regExpFilter = regExpFilter || /\\w/;\n\n var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),\n copiedFiles = [], i, srcFileName, destFileName;\n\n for (i = 0; i < fileNames.length; i++) {\n srcFileName = fileNames[i];\n destFileName = srcFileName.replace(srcDir, destDir);\n\n if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {\n copiedFiles.push(destFileName);\n }\n }\n\n return copiedFiles.length ? copiedFiles : null; //Array or null\n },\n\n copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {\n //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if\n //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.\n var destFile = new java.io.File(destFileName), srcFile, parentDir,\n srcChannel, destChannel;\n\n //logger.trace(\"Src filename: \" + srcFileName);\n //logger.trace(\"Dest filename: \" + destFileName);\n\n //If onlyCopyNew is true, then compare dates and only copy if the src is newer\n //than dest.\n if (onlyCopyNew) {\n srcFile = new java.io.File(srcFileName);\n if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {\n return false; //Boolean\n }\n }\n\n //Make sure destination dir exists.\n parentDir = destFile.getParentFile();\n if (!parentDir.exists()) {\n if (!parentDir.mkdirs()) {\n throw \"Could not create directory: \" + parentDir.getCanonicalPath();\n }\n }\n\n //Java's version of copy file.\n srcChannel = new java.io.FileInputStream(srcFileName).getChannel();\n destChannel = new java.io.FileOutputStream(destFileName).getChannel();\n destChannel.transferFrom(srcChannel, 0, srcChannel.size());\n srcChannel.close();\n destChannel.close();\n\n return true; //Boolean\n },\n\n /**\n * Renames a file. May fail if \"to\" already exists or is on another drive.\n */\n renameFile: function (from, to) {\n return (new java.io.File(from)).renameTo((new java.io.File(to)));\n },\n\n readFile: function (/*String*/path, /*String?*/encoding) {\n //A file read function that can deal with BOMs\n encoding = encoding || \"utf-8\";\n var fileObj = new java.io.File(path),\n input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),\n stringBuffer, line;\n try {\n stringBuffer = new java.lang.StringBuffer();\n line = input.readLine();\n\n // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324\n // http://www.unicode.org/faq/utf_bom.html\n\n // Note that when we use utf-8, the BOM should appear as \"EF BB BF\", but it doesn't due to this bug in the JDK:\n // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058\n if (line && line.length() && line.charAt(0) === 0xfeff) {\n // Eat the BOM, since we've already found the encoding on this file,\n // and we plan to concatenating this buffer with others; the BOM should\n // only appear at the top of a file.\n line = line.substring(1);\n }\n while (line !== null) {\n stringBuffer.append(line);\n stringBuffer.append(file.lineSeparator);\n line = input.readLine();\n }\n //Make sure we return a JavaScript string and not a Java string.\n return String(stringBuffer.toString()); //String\n } finally {\n input.close();\n }\n },\n\n readFileAsync: function (path, encoding) {\n var d = prim();\n try {\n d.resolve(file.readFile(path, encoding));\n } catch (e) {\n d.reject(e);\n }\n return d.promise;\n },\n\n saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {\n //summary: saves a file using UTF-8 encoding.\n file.saveFile(fileName, fileContents, \"utf-8\");\n },\n\n saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {\n //summary: saves a file.\n var outFile = new java.io.File(fileName), outWriter, parentDir, os;\n\n parentDir = outFile.getAbsoluteFile().getParentFile();\n if (!parentDir.exists()) {\n if (!parentDir.mkdirs()) {\n throw \"Could not create directory: \" + parentDir.getAbsolutePath();\n }\n }\n\n if (encoding) {\n outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);\n } else {\n outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));\n }\n\n os = new java.io.BufferedWriter(outWriter);\n try {\n os.write(fileContents);\n } finally {\n os.close();\n }\n },\n\n deleteFile: function (/*String*/fileName) {\n //summary: deletes a file or directory if it exists.\n var fileObj = new java.io.File(fileName), files, i;\n if (fileObj.exists()) {\n if (fileObj.isDirectory()) {\n files = fileObj.listFiles();\n for (i = 0; i < files.length; i++) {\n this.deleteFile(files[i]);\n }\n }\n fileObj[\"delete\"]();\n }\n },\n\n /**\n * Deletes any empty directories under the given directory.\n * The startDirIsJavaObject is private to this implementation's\n * recursion needs.\n */\n deleteEmptyDirs: function (startDir, startDirIsJavaObject) {\n var topDir = startDir,\n dirFileArray, i, fileObj;\n\n if (!startDirIsJavaObject) {\n topDir = new java.io.File(startDir);\n }\n\n if (topDir.exists()) {\n dirFileArray = topDir.listFiles();\n for (i = 0; i < dirFileArray.length; i++) {\n fileObj = dirFileArray[i];\n if (fileObj.isDirectory()) {\n file.deleteEmptyDirs(fileObj, true);\n }\n }\n\n //If the directory is empty now, delete it.\n if (topDir.listFiles().length === 0) {\n file.deleteFile(String(topDir.getPath()));\n }\n }\n }\n };\n\n return file;\n});\n\n}\n\nif(env === 'xpconnect') {\n/**\n * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n//Helper functions to deal with file I/O.\n\n/*jslint plusplus: false */\n/*global define, Components, xpcUtil */\n\ndefine('xpconnect/file', ['prim'], function (prim) {\n var file,\n Cc = Components.classes,\n Ci = Components.interfaces,\n //Depends on xpcUtil which is set up in x.js\n xpfile = xpcUtil.xpfile;\n\n function mkFullDir(dirObj) {\n //1 is DIRECTORY_TYPE, 511 is 0777 permissions\n if (!dirObj.exists()) {\n dirObj.create(1, 511);\n }\n }\n\n file = {\n backSlashRegExp: /\\\\/g,\n\n exclusionRegExp: /^\\./,\n\n getLineSeparator: function () {\n return file.lineSeparator;\n },\n\n lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ?\n '\\r\\n' : '\\n',\n\n exists: function (fileName) {\n return xpfile(fileName).exists();\n },\n\n parent: function (fileName) {\n return xpfile(fileName).parent;\n },\n\n normalize: function (fileName) {\n return file.absPath(fileName);\n },\n\n isFile: function (path) {\n return xpfile(path).isFile();\n },\n\n isDirectory: function (path) {\n return xpfile(path).isDirectory();\n },\n\n /**\n * Gets the absolute file path as a string, normalized\n * to using front slashes for path separators.\n * @param {java.io.File||String} file\n */\n absPath: function (fileObj) {\n if (typeof fileObj === \"string\") {\n fileObj = xpfile(fileObj);\n }\n return fileObj.path;\n },\n\n getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) {\n //summary: Recurses startDir and finds matches to the files that match regExpFilters.include\n //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,\n //and it will be treated as the \"include\" case.\n //Ignores files/directories that start with a period (.) unless exclusionRegExp\n //is set to another value.\n var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,\n fileObj, filePath, ok, dirFiles;\n\n topDir = startDir;\n if (!startDirIsObject) {\n topDir = xpfile(startDir);\n }\n\n regExpInclude = regExpFilters.include || regExpFilters;\n regExpExclude = regExpFilters.exclude || null;\n\n if (topDir.exists()) {\n dirFileArray = topDir.directoryEntries;\n while (dirFileArray.hasMoreElements()) {\n fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);\n if (fileObj.isFile()) {\n filePath = fileObj.path;\n if (makeUnixPaths) {\n if (filePath.indexOf(\"/\") === -1) {\n filePath = filePath.replace(/\\\\/g, \"/\");\n }\n }\n\n ok = true;\n if (regExpInclude) {\n ok = filePath.match(regExpInclude);\n }\n if (ok && regExpExclude) {\n ok = !filePath.match(regExpExclude);\n }\n\n if (ok && (!file.exclusionRegExp ||\n !file.exclusionRegExp.test(fileObj.leafName))) {\n files.push(filePath);\n }\n } else if (fileObj.isDirectory() &&\n (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) {\n dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);\n files.push.apply(files, dirFiles);\n }\n }\n }\n\n return files; //Array\n },\n\n copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {\n //summary: copies files from srcDir to destDir using the regExpFilter to determine if the\n //file should be copied. Returns a list file name strings of the destinations that were copied.\n regExpFilter = regExpFilter || /\\w/;\n\n var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),\n copiedFiles = [], i, srcFileName, destFileName;\n\n for (i = 0; i < fileNames.length; i += 1) {\n srcFileName = fileNames[i];\n destFileName = srcFileName.replace(srcDir, destDir);\n\n if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {\n copiedFiles.push(destFileName);\n }\n }\n\n return copiedFiles.length ? copiedFiles : null; //Array or null\n },\n\n copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {\n //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if\n //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.\n var destFile = xpfile(destFileName),\n srcFile = xpfile(srcFileName);\n\n //logger.trace(\"Src filename: \" + srcFileName);\n //logger.trace(\"Dest filename: \" + destFileName);\n\n //If onlyCopyNew is true, then compare dates and only copy if the src is newer\n //than dest.\n if (onlyCopyNew) {\n if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) {\n return false; //Boolean\n }\n }\n\n srcFile.copyTo(destFile.parent, destFile.leafName);\n\n return true; //Boolean\n },\n\n /**\n * Renames a file. May fail if \"to\" already exists or is on another drive.\n */\n renameFile: function (from, to) {\n var toFile = xpfile(to);\n return xpfile(from).moveTo(toFile.parent, toFile.leafName);\n },\n\n readFile: xpcUtil.readFile,\n\n readFileAsync: function (path, encoding) {\n var d = prim();\n try {\n d.resolve(file.readFile(path, encoding));\n } catch (e) {\n d.reject(e);\n }\n return d.promise;\n },\n\n saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {\n //summary: saves a file using UTF-8 encoding.\n file.saveFile(fileName, fileContents, \"utf-8\");\n },\n\n saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {\n var outStream, convertStream,\n fileObj = xpfile(fileName);\n\n mkFullDir(fileObj.parent);\n\n try {\n outStream = Cc['@mozilla.org/network/file-output-stream;1']\n .createInstance(Ci.nsIFileOutputStream);\n //438 is decimal for 0777\n outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0);\n\n convertStream = Cc['@mozilla.org/intl/converter-output-stream;1']\n .createInstance(Ci.nsIConverterOutputStream);\n\n convertStream.init(outStream, encoding, 0, 0);\n convertStream.writeString(fileContents);\n } catch (e) {\n throw new Error((fileObj && fileObj.path || '') + ': ' + e);\n } finally {\n if (convertStream) {\n convertStream.close();\n }\n if (outStream) {\n outStream.close();\n }\n }\n },\n\n deleteFile: function (/*String*/fileName) {\n //summary: deletes a file or directory if it exists.\n var fileObj = xpfile(fileName);\n if (fileObj.exists()) {\n fileObj.remove(true);\n }\n },\n\n /**\n * Deletes any empty directories under the given directory.\n * The startDirIsJavaObject is private to this implementation's\n * recursion needs.\n */\n deleteEmptyDirs: function (startDir, startDirIsObject) {\n var topDir = startDir,\n dirFileArray, fileObj;\n\n if (!startDirIsObject) {\n topDir = xpfile(startDir);\n }\n\n if (topDir.exists()) {\n dirFileArray = topDir.directoryEntries;\n while (dirFileArray.hasMoreElements()) {\n fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);\n\n if (fileObj.isDirectory()) {\n file.deleteEmptyDirs(fileObj, true);\n }\n }\n\n //If the directory is empty now, delete it.\n dirFileArray = topDir.directoryEntries;\n if (!dirFileArray.hasMoreElements()) {\n file.deleteFile(topDir.path);\n }\n }\n }\n };\n\n return file;\n});\n\n}\n\nif(env === 'browser') {\n/*global process */\ndefine('browser/quit', function () {\n 'use strict';\n return function (code) {\n };\n});\n}\n\nif(env === 'node') {\n/*global process */\ndefine('node/quit', function () {\n 'use strict';\n return function (code) {\n var draining = 0;\n var exit = function () {\n if (draining === 0) {\n process.exit(code);\n } else {\n draining -= 1;\n }\n };\n if (process.stdout.bufferSize) {\n draining += 1;\n process.stdout.once('drain', exit);\n }\n if (process.stderr.bufferSize) {\n draining += 1;\n process.stderr.once('drain', exit);\n }\n exit();\n };\n});\n\n}\n\nif(env === 'rhino') {\n/*global quit */\ndefine('rhino/quit', function () {\n 'use strict';\n return function (code) {\n return quit(code);\n };\n});\n\n}\n\nif(env === 'xpconnect') {\n/*global quit */\ndefine('xpconnect/quit', function () {\n 'use strict';\n return function (code) {\n return quit(code);\n };\n});\n\n}\n\nif(env === 'browser') {\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, console: false */\n\ndefine('browser/print', function () {\n function print(msg) {\n console.log(msg);\n }\n\n return print;\n});\n\n}\n\nif(env === 'node') {\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, console: false */\n\ndefine('node/print', function () {\n function print(msg) {\n console.log(msg);\n }\n\n return print;\n});\n\n}\n\nif(env === 'rhino') {\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, print: false */\n\ndefine('rhino/print', function () {\n return print;\n});\n\n}\n\nif(env === 'xpconnect') {\n/**\n * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false, print: false */\n\ndefine('xpconnect/print', function () {\n return print;\n});\n\n}\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint nomen: false, strict: false */\n/*global define: false */\n\ndefine('logger', ['env!env/print'], function (print) {\n var logger = {\n TRACE: 0,\n INFO: 1,\n WARN: 2,\n ERROR: 3,\n SILENT: 4,\n level: 0,\n logPrefix: \"\",\n\n logLevel: function( level ) {\n this.level = level;\n },\n\n trace: function (message) {\n if (this.level <= this.TRACE) {\n this._print(message);\n }\n },\n\n info: function (message) {\n if (this.level <= this.INFO) {\n this._print(message);\n }\n },\n\n warn: function (message) {\n if (this.level <= this.WARN) {\n this._print(message);\n }\n },\n\n error: function (message) {\n if (this.level <= this.ERROR) {\n this._print(message);\n }\n },\n\n _print: function (message) {\n this._sysPrint((this.logPrefix ? (this.logPrefix + \" \") : \"\") + message);\n },\n\n _sysPrint: function (message) {\n print(message);\n }\n };\n\n return logger;\n});\n//Just a blank file to use when building the optimizer with the optimizer,\n//so that the build does not attempt to inline some env modules,\n//like Node's fs and path.\n\n/*\n Copyright (C) 2013 Ariya Hidayat <[email protected]>\n Copyright (C) 2013 Thaddee Tyl <[email protected]>\n Copyright (C) 2013 Mathias Bynens <[email protected]>\n Copyright (C) 2012 Ariya Hidayat <[email protected]>\n Copyright (C) 2012 Mathias Bynens <[email protected]>\n Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]>\n Copyright (C) 2012 Kris Kowal <[email protected]>\n Copyright (C) 2012 Yusuke Suzuki <[email protected]>\n Copyright (C) 2012 Arpad Borsos <[email protected]>\n Copyright (C) 2011 Ariya Hidayat <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/*jslint bitwise:true plusplus:true */\n/*global esprima:true, define:true, exports:true, window: true,\nthrowErrorTolerant: true,\nthrowError: true, generateStatement: true, peek: true,\nparseAssignmentExpression: true, parseBlock: true, parseExpression: true,\nparseFunctionDeclaration: true, parseFunctionExpression: true,\nparseFunctionSourceElements: true, parseVariableIdentifier: true,\nparseLeftHandSideExpression: true,\nparseUnaryExpression: true,\nparseStatement: true, parseSourceElement: true */\n\n(function (root, factory) {\n 'use strict';\n\n // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,\n // Rhino, and plain browser loading.\n\n /* istanbul ignore next */\n if (typeof define === 'function' && define.amd) {\n define('esprima', ['exports'], factory);\n } else if (typeof exports !== 'undefined') {\n factory(exports);\n } else {\n factory((root.esprima = {}));\n }\n}(this, function (exports) {\n 'use strict';\n\n var Token,\n TokenName,\n FnExprTokens,\n Syntax,\n PropertyKind,\n Messages,\n Regex,\n SyntaxTreeDelegate,\n source,\n strict,\n index,\n lineNumber,\n lineStart,\n length,\n delegate,\n lookahead,\n state,\n extra;\n\n Token = {\n BooleanLiteral: 1,\n EOF: 2,\n Identifier: 3,\n Keyword: 4,\n NullLiteral: 5,\n NumericLiteral: 6,\n Punctuator: 7,\n StringLiteral: 8,\n RegularExpression: 9\n };\n\n TokenName = {};\n TokenName[Token.BooleanLiteral] = 'Boolean';\n TokenName[Token.EOF] = '<end>';\n TokenName[Token.Identifier] = 'Identifier';\n TokenName[Token.Keyword] = 'Keyword';\n TokenName[Token.NullLiteral] = 'Null';\n TokenName[Token.NumericLiteral] = 'Numeric';\n TokenName[Token.Punctuator] = 'Punctuator';\n TokenName[Token.StringLiteral] = 'String';\n TokenName[Token.RegularExpression] = 'RegularExpression';\n\n // A function following one of those tokens is an expression.\n FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',\n 'return', 'case', 'delete', 'throw', 'void',\n // assignment operators\n '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',\n '&=', '|=', '^=', ',',\n // binary/unary operators\n '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',\n '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',\n '<=', '<', '>', '!=', '!=='];\n\n Syntax = {\n AssignmentExpression: 'AssignmentExpression',\n ArrayExpression: 'ArrayExpression',\n BlockStatement: 'BlockStatement',\n BinaryExpression: 'BinaryExpression',\n BreakStatement: 'BreakStatement',\n CallExpression: 'CallExpression',\n CatchClause: 'CatchClause',\n ConditionalExpression: 'ConditionalExpression',\n ContinueStatement: 'ContinueStatement',\n DoWhileStatement: 'DoWhileStatement',\n DebuggerStatement: 'DebuggerStatement',\n EmptyStatement: 'EmptyStatement',\n ExpressionStatement: 'ExpressionStatement',\n ForStatement: 'ForStatement',\n ForInStatement: 'ForInStatement',\n FunctionDeclaration: 'FunctionDeclaration',\n FunctionExpression: 'FunctionExpression',\n Identifier: 'Identifier',\n IfStatement: 'IfStatement',\n Literal: 'Literal',\n LabeledStatement: 'LabeledStatement',\n LogicalExpression: 'LogicalExpression',\n MemberExpression: 'MemberExpression',\n NewExpression: 'NewExpression',\n ObjectExpression: 'ObjectExpression',\n Program: 'Program',\n Property: 'Property',\n ReturnStatement: 'ReturnStatement',\n SequenceExpression: 'SequenceExpression',\n SwitchStatement: 'SwitchStatement',\n SwitchCase: 'SwitchCase',\n ThisExpression: 'ThisExpression',\n ThrowStatement: 'ThrowStatement',\n TryStatement: 'TryStatement',\n UnaryExpression: 'UnaryExpression',\n UpdateExpression: 'UpdateExpression',\n VariableDeclaration: 'VariableDeclaration',\n VariableDeclarator: 'VariableDeclarator',\n WhileStatement: 'WhileStatement',\n WithStatement: 'WithStatement'\n };\n\n PropertyKind = {\n Data: 1,\n Get: 2,\n Set: 4\n };\n\n // Error messages should be identical to V8.\n Messages = {\n UnexpectedToken: 'Unexpected token %0',\n UnexpectedNumber: 'Unexpected number',\n UnexpectedString: 'Unexpected string',\n UnexpectedIdentifier: 'Unexpected identifier',\n UnexpectedReserved: 'Unexpected reserved word',\n UnexpectedEOS: 'Unexpected end of input',\n NewlineAfterThrow: 'Illegal newline after throw',\n InvalidRegExp: 'Invalid regular expression',\n UnterminatedRegExp: 'Invalid regular expression: missing /',\n InvalidLHSInAssignment: 'Invalid left-hand side in assignment',\n InvalidLHSInForIn: 'Invalid left-hand side in for-in',\n MultipleDefaultsInSwitch: 'More than one default clause in switch statement',\n NoCatchOrFinally: 'Missing catch or finally after try',\n UnknownLabel: 'Undefined label \\'%0\\'',\n Redeclaration: '%0 \\'%1\\' has already been declared',\n IllegalContinue: 'Illegal continue statement',\n IllegalBreak: 'Illegal break statement',\n IllegalReturn: 'Illegal return statement',\n StrictModeWith: 'Strict mode code may not include a with statement',\n StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',\n StrictVarName: 'Variable name may not be eval or arguments in strict mode',\n StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',\n StrictParamDupe: 'Strict mode function may not have duplicate parameter names',\n StrictFunctionName: 'Function name may not be eval or arguments in strict mode',\n StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',\n StrictDelete: 'Delete of an unqualified identifier in strict mode.',\n StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',\n AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',\n AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',\n StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',\n StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',\n StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',\n StrictReservedWord: 'Use of future reserved word in strict mode'\n };\n\n // See also tools/generate-unicode-regex.py.\n Regex = {\n NonAsciiIdentifierStart: new RegExp('[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]'),\n NonAsciiIdentifierPart: new RegExp('[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u08A0\\u08A2-\\u08AC\\u08E4-\\u08FE\\u0900-\\u0963\\u0966-\\u096F\\u0971-\\u0977\\u0979-\\u097F\\u0981-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BEF\\u0C01-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58\\u0C59\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C82\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D02\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D57\\u0D60-\\u0D63\\u0D66-\\u0D6F\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1CD0-\\u1CD2\\u1CD4-\\u1CF6\\u1D00-\\u1DE6\\u1DFC-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u200C\\u200D\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA697\\uA69F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA827\\uA840-\\uA873\\uA880-\\uA8C4\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A\\uAA7B\\uAA80-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE26\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]')\n };\n\n // Ensure the condition is true, otherwise throw an error.\n // This is only to have a better contract semantic, i.e. another safety net\n // to catch a logic error. The condition shall be fulfilled in normal case.\n // Do NOT use this to enforce a certain condition on any user input.\n\n function assert(condition, message) {\n /* istanbul ignore if */\n if (!condition) {\n throw new Error('ASSERT: ' + message);\n }\n }\n\n function isDecimalDigit(ch) {\n return (ch >= 48 && ch <= 57); // 0..9\n }\n\n function isHexDigit(ch) {\n return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;\n }\n\n function isOctalDigit(ch) {\n return '01234567'.indexOf(ch) >= 0;\n }\n\n\n // 7.2 White Space\n\n function isWhiteSpace(ch) {\n return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||\n (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);\n }\n\n // 7.3 Line Terminators\n\n function isLineTerminator(ch) {\n return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);\n }\n\n // 7.6 Identifier Names and Identifiers\n\n function isIdentifierStart(ch) {\n return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)\n (ch >= 0x41 && ch <= 0x5A) || // A..Z\n (ch >= 0x61 && ch <= 0x7A) || // a..z\n (ch === 0x5C) || // \\ (backslash)\n ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));\n }\n\n function isIdentifierPart(ch) {\n return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)\n (ch >= 0x41 && ch <= 0x5A) || // A..Z\n (ch >= 0x61 && ch <= 0x7A) || // a..z\n (ch >= 0x30 && ch <= 0x39) || // 0..9\n (ch === 0x5C) || // \\ (backslash)\n ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));\n }\n\n // 7.6.1.2 Future Reserved Words\n\n function isFutureReservedWord(id) {\n switch (id) {\n case 'class':\n case 'enum':\n case 'export':\n case 'extends':\n case 'import':\n case 'super':\n return true;\n default:\n return false;\n }\n }\n\n function isStrictModeReservedWord(id) {\n switch (id) {\n case 'implements':\n case 'interface':\n case 'package':\n case 'private':\n case 'protected':\n case 'public':\n case 'static':\n case 'yield':\n case 'let':\n return true;\n default:\n return false;\n }\n }\n\n function isRestrictedWord(id) {\n return id === 'eval' || id === 'arguments';\n }\n\n // 7.6.1.1 Keywords\n\n function isKeyword(id) {\n if (strict && isStrictModeReservedWord(id)) {\n return true;\n }\n\n // 'const' is specialized as Keyword in V8.\n // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next.\n // Some others are from future reserved words.\n\n switch (id.length) {\n case 2:\n return (id === 'if') || (id === 'in') || (id === 'do');\n case 3:\n return (id === 'var') || (id === 'for') || (id === 'new') ||\n (id === 'try') || (id === 'let');\n case 4:\n return (id === 'this') || (id === 'else') || (id === 'case') ||\n (id === 'void') || (id === 'with') || (id === 'enum');\n case 5:\n return (id === 'while') || (id === 'break') || (id === 'catch') ||\n (id === 'throw') || (id === 'const') || (id === 'yield') ||\n (id === 'class') || (id === 'super');\n case 6:\n return (id === 'return') || (id === 'typeof') || (id === 'delete') ||\n (id === 'switch') || (id === 'export') || (id === 'import');\n case 7:\n return (id === 'default') || (id === 'finally') || (id === 'extends');\n case 8:\n return (id === 'function') || (id === 'continue') || (id === 'debugger');\n case 10:\n return (id === 'instanceof');\n default:\n return false;\n }\n }\n\n // 7.4 Comments\n\n function addComment(type, value, start, end, loc) {\n var comment, attacher;\n\n assert(typeof start === 'number', 'Comment must have valid position');\n\n // Because the way the actual token is scanned, often the comments\n // (if any) are skipped twice during the lexical analysis.\n // Thus, we need to skip adding a comment if the comment array already\n // handled it.\n if (state.lastCommentStart >= start) {\n return;\n }\n state.lastCommentStart = start;\n\n comment = {\n type: type,\n value: value\n };\n if (extra.range) {\n comment.range = [start, end];\n }\n if (extra.loc) {\n comment.loc = loc;\n }\n extra.comments.push(comment);\n if (extra.attachComment) {\n extra.leadingComments.push(comment);\n extra.trailingComments.push(comment);\n }\n }\n\n function skipSingleLineComment(offset) {\n var start, loc, ch, comment;\n\n start = index - offset;\n loc = {\n start: {\n line: lineNumber,\n column: index - lineStart - offset\n }\n };\n\n while (index < length) {\n ch = source.charCodeAt(index);\n ++index;\n if (isLineTerminator(ch)) {\n if (extra.comments) {\n comment = source.slice(start + offset, index - 1);\n loc.end = {\n line: lineNumber,\n column: index - lineStart - 1\n };\n addComment('Line', comment, start, index - 1, loc);\n }\n if (ch === 13 && source.charCodeAt(index) === 10) {\n ++index;\n }\n ++lineNumber;\n lineStart = index;\n return;\n }\n }\n\n if (extra.comments) {\n comment = source.slice(start + offset, index);\n loc.end = {\n line: lineNumber,\n column: index - lineStart\n };\n addComment('Line', comment, start, index, loc);\n }\n }\n\n function skipMultiLineComment() {\n var start, loc, ch, comment;\n\n if (extra.comments) {\n start = index - 2;\n loc = {\n start: {\n line: lineNumber,\n column: index - lineStart - 2\n }\n };\n }\n\n while (index < length) {\n ch = source.charCodeAt(index);\n if (isLineTerminator(ch)) {\n if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {\n ++index;\n }\n ++lineNumber;\n ++index;\n lineStart = index;\n if (index >= length) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n } else if (ch === 0x2A) {\n // Block comment ends with '*/'.\n if (source.charCodeAt(index + 1) === 0x2F) {\n ++index;\n ++index;\n if (extra.comments) {\n comment = source.slice(start + 2, index - 2);\n loc.end = {\n line: lineNumber,\n column: index - lineStart\n };\n addComment('Block', comment, start, index, loc);\n }\n return;\n }\n ++index;\n } else {\n ++index;\n }\n }\n\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n\n function skipComment() {\n var ch, start;\n\n start = (index === 0);\n while (index < length) {\n ch = source.charCodeAt(index);\n\n if (isWhiteSpace(ch)) {\n ++index;\n } else if (isLineTerminator(ch)) {\n ++index;\n if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {\n ++index;\n }\n ++lineNumber;\n lineStart = index;\n start = true;\n } else if (ch === 0x2F) { // U+002F is '/'\n ch = source.charCodeAt(index + 1);\n if (ch === 0x2F) {\n ++index;\n ++index;\n skipSingleLineComment(2);\n start = true;\n } else if (ch === 0x2A) { // U+002A is '*'\n ++index;\n ++index;\n skipMultiLineComment();\n } else {\n break;\n }\n } else if (start && ch === 0x2D) { // U+002D is '-'\n // U+003E is '>'\n if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {\n // '-->' is a single-line comment\n index += 3;\n skipSingleLineComment(3);\n } else {\n break;\n }\n } else if (ch === 0x3C) { // U+003C is '<'\n if (source.slice(index + 1, index + 4) === '!--') {\n ++index; // `<`\n ++index; // `!`\n ++index; // `-`\n ++index; // `-`\n skipSingleLineComment(4);\n } else {\n break;\n }\n } else {\n break;\n }\n }\n }\n\n function scanHexEscape(prefix) {\n var i, len, ch, code = 0;\n\n len = (prefix === 'u') ? 4 : 2;\n for (i = 0; i < len; ++i) {\n if (index < length && isHexDigit(source[index])) {\n ch = source[index++];\n code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());\n } else {\n return '';\n }\n }\n return String.fromCharCode(code);\n }\n\n function getEscapedIdentifier() {\n var ch, id;\n\n ch = source.charCodeAt(index++);\n id = String.fromCharCode(ch);\n\n // '\\u' (U+005C, U+0075) denotes an escaped character.\n if (ch === 0x5C) {\n if (source.charCodeAt(index) !== 0x75) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n ++index;\n ch = scanHexEscape('u');\n if (!ch || ch === '\\\\' || !isIdentifierStart(ch.charCodeAt(0))) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n id = ch;\n }\n\n while (index < length) {\n ch = source.charCodeAt(index);\n if (!isIdentifierPart(ch)) {\n break;\n }\n ++index;\n id += String.fromCharCode(ch);\n\n // '\\u' (U+005C, U+0075) denotes an escaped character.\n if (ch === 0x5C) {\n id = id.substr(0, id.length - 1);\n if (source.charCodeAt(index) !== 0x75) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n ++index;\n ch = scanHexEscape('u');\n if (!ch || ch === '\\\\' || !isIdentifierPart(ch.charCodeAt(0))) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n id += ch;\n }\n }\n\n return id;\n }\n\n function getIdentifier() {\n var start, ch;\n\n start = index++;\n while (index < length) {\n ch = source.charCodeAt(index);\n if (ch === 0x5C) {\n // Blackslash (U+005C) marks Unicode escape sequence.\n index = start;\n return getEscapedIdentifier();\n }\n if (isIdentifierPart(ch)) {\n ++index;\n } else {\n break;\n }\n }\n\n return source.slice(start, index);\n }\n\n function scanIdentifier() {\n var start, id, type;\n\n start = index;\n\n // Backslash (U+005C) starts an escaped character.\n id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier();\n\n // There is no keyword or literal with only one character.\n // Thus, it must be an identifier.\n if (id.length === 1) {\n type = Token.Identifier;\n } else if (isKeyword(id)) {\n type = Token.Keyword;\n } else if (id === 'null') {\n type = Token.NullLiteral;\n } else if (id === 'true' || id === 'false') {\n type = Token.BooleanLiteral;\n } else {\n type = Token.Identifier;\n }\n\n return {\n type: type,\n value: id,\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n\n // 7.7 Punctuators\n\n function scanPunctuator() {\n var start = index,\n code = source.charCodeAt(index),\n code2,\n ch1 = source[index],\n ch2,\n ch3,\n ch4;\n\n switch (code) {\n\n // Check for most common single-character punctuators.\n case 0x2E: // . dot\n case 0x28: // ( open bracket\n case 0x29: // ) close bracket\n case 0x3B: // ; semicolon\n case 0x2C: // , comma\n case 0x7B: // { open curly brace\n case 0x7D: // } close curly brace\n case 0x5B: // [\n case 0x5D: // ]\n case 0x3A: // :\n case 0x3F: // ?\n case 0x7E: // ~\n ++index;\n if (extra.tokenize) {\n if (code === 0x28) {\n extra.openParenToken = extra.tokens.length;\n } else if (code === 0x7B) {\n extra.openCurlyToken = extra.tokens.length;\n }\n }\n return {\n type: Token.Punctuator,\n value: String.fromCharCode(code),\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n\n default:\n code2 = source.charCodeAt(index + 1);\n\n // '=' (U+003D) marks an assignment or comparison operator.\n if (code2 === 0x3D) {\n switch (code) {\n case 0x2B: // +\n case 0x2D: // -\n case 0x2F: // /\n case 0x3C: // <\n case 0x3E: // >\n case 0x5E: // ^\n case 0x7C: // |\n case 0x25: // %\n case 0x26: // &\n case 0x2A: // *\n index += 2;\n return {\n type: Token.Punctuator,\n value: String.fromCharCode(code) + String.fromCharCode(code2),\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n\n case 0x21: // !\n case 0x3D: // =\n index += 2;\n\n // !== and ===\n if (source.charCodeAt(index) === 0x3D) {\n ++index;\n }\n return {\n type: Token.Punctuator,\n value: source.slice(start, index),\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n }\n }\n\n // 4-character punctuator: >>>=\n\n ch4 = source.substr(index, 4);\n\n if (ch4 === '>>>=') {\n index += 4;\n return {\n type: Token.Punctuator,\n value: ch4,\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n // 3-character punctuators: === !== >>> <<= >>=\n\n ch3 = ch4.substr(0, 3);\n\n if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {\n index += 3;\n return {\n type: Token.Punctuator,\n value: ch3,\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n // Other 2-character punctuators: ++ -- << >> && ||\n ch2 = ch3.substr(0, 2);\n\n if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') {\n index += 2;\n return {\n type: Token.Punctuator,\n value: ch2,\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n // 1-character punctuators: < > = ! + - * % & | ^ /\n if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {\n ++index;\n return {\n type: Token.Punctuator,\n value: ch1,\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n\n // 7.8.3 Numeric Literals\n\n function scanHexLiteral(start) {\n var number = '';\n\n while (index < length) {\n if (!isHexDigit(source[index])) {\n break;\n }\n number += source[index++];\n }\n\n if (number.length === 0) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n\n if (isIdentifierStart(source.charCodeAt(index))) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n\n return {\n type: Token.NumericLiteral,\n value: parseInt('0x' + number, 16),\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n function scanOctalLiteral(start) {\n var number = '0' + source[index++];\n while (index < length) {\n if (!isOctalDigit(source[index])) {\n break;\n }\n number += source[index++];\n }\n\n if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n\n return {\n type: Token.NumericLiteral,\n value: parseInt(number, 8),\n octal: true,\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n function scanNumericLiteral() {\n var number, start, ch;\n\n ch = source[index];\n assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),\n 'Numeric literal must start with a decimal digit or a decimal point');\n\n start = index;\n number = '';\n if (ch !== '.') {\n number = source[index++];\n ch = source[index];\n\n // Hex number starts with '0x'.\n // Octal number starts with '0'.\n if (number === '0') {\n if (ch === 'x' || ch === 'X') {\n ++index;\n return scanHexLiteral(start);\n }\n if (isOctalDigit(ch)) {\n return scanOctalLiteral(start);\n }\n\n // decimal number starts with '0' such as '09' is illegal.\n if (ch && isDecimalDigit(ch.charCodeAt(0))) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n }\n\n while (isDecimalDigit(source.charCodeAt(index))) {\n number += source[index++];\n }\n ch = source[index];\n }\n\n if (ch === '.') {\n number += source[index++];\n while (isDecimalDigit(source.charCodeAt(index))) {\n number += source[index++];\n }\n ch = source[index];\n }\n\n if (ch === 'e' || ch === 'E') {\n number += source[index++];\n\n ch = source[index];\n if (ch === '+' || ch === '-') {\n number += source[index++];\n }\n if (isDecimalDigit(source.charCodeAt(index))) {\n while (isDecimalDigit(source.charCodeAt(index))) {\n number += source[index++];\n }\n } else {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n }\n\n if (isIdentifierStart(source.charCodeAt(index))) {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n\n return {\n type: Token.NumericLiteral,\n value: parseFloat(number),\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n // 7.8.4 String Literals\n\n function scanStringLiteral() {\n var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart;\n startLineNumber = lineNumber;\n startLineStart = lineStart;\n\n quote = source[index];\n assert((quote === '\\'' || quote === '\"'),\n 'String literal must starts with a quote');\n\n start = index;\n ++index;\n\n while (index < length) {\n ch = source[index++];\n\n if (ch === quote) {\n quote = '';\n break;\n } else if (ch === '\\\\') {\n ch = source[index++];\n if (!ch || !isLineTerminator(ch.charCodeAt(0))) {\n switch (ch) {\n case 'u':\n case 'x':\n restore = index;\n unescaped = scanHexEscape(ch);\n if (unescaped) {\n str += unescaped;\n } else {\n index = restore;\n str += ch;\n }\n break;\n case 'n':\n str += '\\n';\n break;\n case 'r':\n str += '\\r';\n break;\n case 't':\n str += '\\t';\n break;\n case 'b':\n str += '\\b';\n break;\n case 'f':\n str += '\\f';\n break;\n case 'v':\n str += '\\x0B';\n break;\n\n default:\n if (isOctalDigit(ch)) {\n code = '01234567'.indexOf(ch);\n\n // \\0 is not octal escape sequence\n if (code !== 0) {\n octal = true;\n }\n\n if (index < length && isOctalDigit(source[index])) {\n octal = true;\n code = code * 8 + '01234567'.indexOf(source[index++]);\n\n // 3 digits are only allowed when string starts\n // with 0, 1, 2, 3\n if ('0123'.indexOf(ch) >= 0 &&\n index < length &&\n isOctalDigit(source[index])) {\n code = code * 8 + '01234567'.indexOf(source[index++]);\n }\n }\n str += String.fromCharCode(code);\n } else {\n str += ch;\n }\n break;\n }\n } else {\n ++lineNumber;\n if (ch === '\\r' && source[index] === '\\n') {\n ++index;\n }\n lineStart = index;\n }\n } else if (isLineTerminator(ch.charCodeAt(0))) {\n break;\n } else {\n str += ch;\n }\n }\n\n if (quote !== '') {\n throwError({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n\n return {\n type: Token.StringLiteral,\n value: str,\n octal: octal,\n startLineNumber: startLineNumber,\n startLineStart: startLineStart,\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n function testRegExp(pattern, flags) {\n var value;\n try {\n value = new RegExp(pattern, flags);\n } catch (e) {\n throwError({}, Messages.InvalidRegExp);\n }\n return value;\n }\n\n function scanRegExpBody() {\n var ch, str, classMarker, terminated, body;\n\n ch = source[index];\n assert(ch === '/', 'Regular expression literal must start with a slash');\n str = source[index++];\n\n classMarker = false;\n terminated = false;\n while (index < length) {\n ch = source[index++];\n str += ch;\n if (ch === '\\\\') {\n ch = source[index++];\n // ECMA-262 7.8.5\n if (isLineTerminator(ch.charCodeAt(0))) {\n throwError({}, Messages.UnterminatedRegExp);\n }\n str += ch;\n } else if (isLineTerminator(ch.charCodeAt(0))) {\n throwError({}, Messages.UnterminatedRegExp);\n } else if (classMarker) {\n if (ch === ']') {\n classMarker = false;\n }\n } else {\n if (ch === '/') {\n terminated = true;\n break;\n } else if (ch === '[') {\n classMarker = true;\n }\n }\n }\n\n if (!terminated) {\n throwError({}, Messages.UnterminatedRegExp);\n }\n\n // Exclude leading and trailing slash.\n body = str.substr(1, str.length - 2);\n return {\n value: body,\n literal: str\n };\n }\n\n function scanRegExpFlags() {\n var ch, str, flags, restore;\n\n str = '';\n flags = '';\n while (index < length) {\n ch = source[index];\n if (!isIdentifierPart(ch.charCodeAt(0))) {\n break;\n }\n\n ++index;\n if (ch === '\\\\' && index < length) {\n ch = source[index];\n if (ch === 'u') {\n ++index;\n restore = index;\n ch = scanHexEscape('u');\n if (ch) {\n flags += ch;\n for (str += '\\\\u'; restore < index; ++restore) {\n str += source[restore];\n }\n } else {\n index = restore;\n flags += 'u';\n str += '\\\\u';\n }\n throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');\n } else {\n str += '\\\\';\n throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');\n }\n } else {\n flags += ch;\n str += ch;\n }\n }\n\n return {\n value: flags,\n literal: str\n };\n }\n\n function scanRegExp() {\n var start, body, flags, pattern, value;\n\n lookahead = null;\n skipComment();\n start = index;\n\n body = scanRegExpBody();\n flags = scanRegExpFlags();\n value = testRegExp(body.value, flags.value);\n\n if (extra.tokenize) {\n return {\n type: Token.RegularExpression,\n value: value,\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: start,\n end: index\n };\n }\n\n return {\n literal: body.literal + flags.literal,\n value: value,\n start: start,\n end: index\n };\n }\n\n function collectRegex() {\n var pos, loc, regex, token;\n\n skipComment();\n\n pos = index;\n loc = {\n start: {\n line: lineNumber,\n column: index - lineStart\n }\n };\n\n regex = scanRegExp();\n loc.end = {\n line: lineNumber,\n column: index - lineStart\n };\n\n /* istanbul ignore next */\n if (!extra.tokenize) {\n // Pop the previous token, which is likely '/' or '/='\n if (extra.tokens.length > 0) {\n token = extra.tokens[extra.tokens.length - 1];\n if (token.range[0] === pos && token.type === 'Punctuator') {\n if (token.value === '/' || token.value === '/=') {\n extra.tokens.pop();\n }\n }\n }\n\n extra.tokens.push({\n type: 'RegularExpression',\n value: regex.literal,\n range: [pos, index],\n loc: loc\n });\n }\n\n return regex;\n }\n\n function isIdentifierName(token) {\n return token.type === Token.Identifier ||\n token.type === Token.Keyword ||\n token.type === Token.BooleanLiteral ||\n token.type === Token.NullLiteral;\n }\n\n function advanceSlash() {\n var prevToken,\n checkToken;\n // Using the following algorithm:\n // https://github.com/mozilla/sweet.js/wiki/design\n prevToken = extra.tokens[extra.tokens.length - 1];\n if (!prevToken) {\n // Nothing before that: it cannot be a division.\n return collectRegex();\n }\n if (prevToken.type === 'Punctuator') {\n if (prevToken.value === ']') {\n return scanPunctuator();\n }\n if (prevToken.value === ')') {\n checkToken = extra.tokens[extra.openParenToken - 1];\n if (checkToken &&\n checkToken.type === 'Keyword' &&\n (checkToken.value === 'if' ||\n checkToken.value === 'while' ||\n checkToken.value === 'for' ||\n checkToken.value === 'with')) {\n return collectRegex();\n }\n return scanPunctuator();\n }\n if (prevToken.value === '}') {\n // Dividing a function by anything makes little sense,\n // but we have to check for that.\n if (extra.tokens[extra.openCurlyToken - 3] &&\n extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {\n // Anonymous function.\n checkToken = extra.tokens[extra.openCurlyToken - 4];\n if (!checkToken) {\n return scanPunctuator();\n }\n } else if (extra.tokens[extra.openCurlyToken - 4] &&\n extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {\n // Named function.\n checkToken = extra.tokens[extra.openCurlyToken - 5];\n if (!checkToken) {\n return collectRegex();\n }\n } else {\n return scanPunctuator();\n }\n // checkToken determines whether the function is\n // a declaration or an expression.\n if (FnExprTokens.indexOf(checkToken.value) >= 0) {\n // It is an expression.\n return scanPunctuator();\n }\n // It is a declaration.\n return collectRegex();\n }\n return collectRegex();\n }\n if (prevToken.type === 'Keyword') {\n return collectRegex();\n }\n return scanPunctuator();\n }\n\n function advance() {\n var ch;\n\n skipComment();\n\n if (index >= length) {\n return {\n type: Token.EOF,\n lineNumber: lineNumber,\n lineStart: lineStart,\n start: index,\n end: index\n };\n }\n\n ch = source.charCodeAt(index);\n\n if (isIdentifierStart(ch)) {\n return scanIdentifier();\n }\n\n // Very common: ( and ) and ;\n if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {\n return scanPunctuator();\n }\n\n // String literal starts with single quote (U+0027) or double quote (U+0022).\n if (ch === 0x27 || ch === 0x22) {\n return scanStringLiteral();\n }\n\n\n // Dot (.) U+002E can also start a floating-point number, hence the need\n // to check the next character.\n if (ch === 0x2E) {\n if (isDecimalDigit(source.charCodeAt(index + 1))) {\n return scanNumericLiteral();\n }\n return scanPunctuator();\n }\n\n if (isDecimalDigit(ch)) {\n return scanNumericLiteral();\n }\n\n // Slash (/) U+002F can also start a regex.\n if (extra.tokenize && ch === 0x2F) {\n return advanceSlash();\n }\n\n return scanPunctuator();\n }\n\n function collectToken() {\n var loc, token, range, value;\n\n skipComment();\n loc = {\n start: {\n line: lineNumber,\n column: index - lineStart\n }\n };\n\n token = advance();\n loc.end = {\n line: lineNumber,\n column: index - lineStart\n };\n\n if (token.type !== Token.EOF) {\n value = source.slice(token.start, token.end);\n extra.tokens.push({\n type: TokenName[token.type],\n value: value,\n range: [token.start, token.end],\n loc: loc\n });\n }\n\n return token;\n }\n\n function lex() {\n var token;\n\n token = lookahead;\n index = token.end;\n lineNumber = token.lineNumber;\n lineStart = token.lineStart;\n\n lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();\n\n index = token.end;\n lineNumber = token.lineNumber;\n lineStart = token.lineStart;\n\n return token;\n }\n\n function peek() {\n var pos, line, start;\n\n pos = index;\n line = lineNumber;\n start = lineStart;\n lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();\n index = pos;\n lineNumber = line;\n lineStart = start;\n }\n\n function Position(line, column) {\n this.line = line;\n this.column = column;\n }\n\n function SourceLocation(startLine, startColumn, line, column) {\n this.start = new Position(startLine, startColumn);\n this.end = new Position(line, column);\n }\n\n SyntaxTreeDelegate = {\n\n name: 'SyntaxTree',\n\n processComment: function (node) {\n var lastChild, trailingComments;\n\n if (node.type === Syntax.Program) {\n if (node.body.length > 0) {\n return;\n }\n }\n\n if (extra.trailingComments.length > 0) {\n if (extra.trailingComments[0].range[0] >= node.range[1]) {\n trailingComments = extra.trailingComments;\n extra.trailingComments = [];\n } else {\n extra.trailingComments.length = 0;\n }\n } else {\n if (extra.bottomRightStack.length > 0 &&\n extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments &&\n extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) {\n trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;\n delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;\n }\n }\n\n // Eating the stack.\n while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) {\n lastChild = extra.bottomRightStack.pop();\n }\n\n if (lastChild) {\n if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {\n node.leadingComments = lastChild.leadingComments;\n delete lastChild.leadingComments;\n }\n } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {\n node.leadingComments = extra.leadingComments;\n extra.leadingComments = [];\n }\n\n\n if (trailingComments) {\n node.trailingComments = trailingComments;\n }\n\n extra.bottomRightStack.push(node);\n },\n\n markEnd: function (node, startToken) {\n if (extra.range) {\n node.range = [startToken.start, index];\n }\n if (extra.loc) {\n node.loc = new SourceLocation(\n startToken.startLineNumber === undefined ? startToken.lineNumber : startToken.startLineNumber,\n startToken.start - (startToken.startLineStart === undefined ? startToken.lineStart : startToken.startLineStart),\n lineNumber,\n index - lineStart\n );\n this.postProcess(node);\n }\n\n if (extra.attachComment) {\n this.processComment(node);\n }\n return node;\n },\n\n postProcess: function (node) {\n if (extra.source) {\n node.loc.source = extra.source;\n }\n return node;\n },\n\n createArrayExpression: function (elements) {\n return {\n type: Syntax.ArrayExpression,\n elements: elements\n };\n },\n\n createAssignmentExpression: function (operator, left, right) {\n return {\n type: Syntax.AssignmentExpression,\n operator: operator,\n left: left,\n right: right\n };\n },\n\n createBinaryExpression: function (operator, left, right) {\n var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :\n Syntax.BinaryExpression;\n return {\n type: type,\n operator: operator,\n left: left,\n right: right\n };\n },\n\n createBlockStatement: function (body) {\n return {\n type: Syntax.BlockStatement,\n body: body\n };\n },\n\n createBreakStatement: function (label) {\n return {\n type: Syntax.BreakStatement,\n label: label\n };\n },\n\n createCallExpression: function (callee, args) {\n return {\n type: Syntax.CallExpression,\n callee: callee,\n 'arguments': args\n };\n },\n\n createCatchClause: function (param, body) {\n return {\n type: Syntax.CatchClause,\n param: param,\n body: body\n };\n },\n\n createConditionalExpression: function (test, consequent, alternate) {\n return {\n type: Syntax.ConditionalExpression,\n test: test,\n consequent: consequent,\n alternate: alternate\n };\n },\n\n createContinueStatement: function (label) {\n return {\n type: Syntax.ContinueStatement,\n label: label\n };\n },\n\n createDebuggerStatement: function () {\n return {\n type: Syntax.DebuggerStatement\n };\n },\n\n createDoWhileStatement: function (body, test) {\n return {\n type: Syntax.DoWhileStatement,\n body: body,\n test: test\n };\n },\n\n createEmptyStatement: function () {\n return {\n type: Syntax.EmptyStatement\n };\n },\n\n createExpressionStatement: function (expression) {\n return {\n type: Syntax.ExpressionStatement,\n expression: expression\n };\n },\n\n createForStatement: function (init, test, update, body) {\n return {\n type: Syntax.ForStatement,\n init: init,\n test: test,\n update: update,\n body: body\n };\n },\n\n createForInStatement: function (left, right, body) {\n return {\n type: Syntax.ForInStatement,\n left: left,\n right: right,\n body: body,\n each: false\n };\n },\n\n createFunctionDeclaration: function (id, params, defaults, body) {\n return {\n type: Syntax.FunctionDeclaration,\n id: id,\n params: params,\n defaults: defaults,\n body: body,\n rest: null,\n generator: false,\n expression: false\n };\n },\n\n createFunctionExpression: function (id, params, defaults, body) {\n return {\n type: Syntax.FunctionExpression,\n id: id,\n params: params,\n defaults: defaults,\n body: body,\n rest: null,\n generator: false,\n expression: false\n };\n },\n\n createIdentifier: function (name) {\n return {\n type: Syntax.Identifier,\n name: name\n };\n },\n\n createIfStatement: function (test, consequent, alternate) {\n return {\n type: Syntax.IfStatement,\n test: test,\n consequent: consequent,\n alternate: alternate\n };\n },\n\n createLabeledStatement: function (label, body) {\n return {\n type: Syntax.LabeledStatement,\n label: label,\n body: body\n };\n },\n\n createLiteral: function (token) {\n return {\n type: Syntax.Literal,\n value: token.value,\n raw: source.slice(token.start, token.end)\n };\n },\n\n createMemberExpression: function (accessor, object, property) {\n return {\n type: Syntax.MemberExpression,\n computed: accessor === '[',\n object: object,\n property: property\n };\n },\n\n createNewExpression: function (callee, args) {\n return {\n type: Syntax.NewExpression,\n callee: callee,\n 'arguments': args\n };\n },\n\n createObjectExpression: function (properties) {\n return {\n type: Syntax.ObjectExpression,\n properties: properties\n };\n },\n\n createPostfixExpression: function (operator, argument) {\n return {\n type: Syntax.UpdateExpression,\n operator: operator,\n argument: argument,\n prefix: false\n };\n },\n\n createProgram: function (body) {\n return {\n type: Syntax.Program,\n body: body\n };\n },\n\n createProperty: function (kind, key, value) {\n return {\n type: Syntax.Property,\n key: key,\n value: value,\n kind: kind\n };\n },\n\n createReturnStatement: function (argument) {\n return {\n type: Syntax.ReturnStatement,\n argument: argument\n };\n },\n\n createSequenceExpression: function (expressions) {\n return {\n type: Syntax.SequenceExpression,\n expressions: expressions\n };\n },\n\n createSwitchCase: function (test, consequent) {\n return {\n type: Syntax.SwitchCase,\n test: test,\n consequent: consequent\n };\n },\n\n createSwitchStatement: function (discriminant, cases) {\n return {\n type: Syntax.SwitchStatement,\n discriminant: discriminant,\n cases: cases\n };\n },\n\n createThisExpression: function () {\n return {\n type: Syntax.ThisExpression\n };\n },\n\n createThrowStatement: function (argument) {\n return {\n type: Syntax.ThrowStatement,\n argument: argument\n };\n },\n\n createTryStatement: function (block, guardedHandlers, handlers, finalizer) {\n return {\n type: Syntax.TryStatement,\n block: block,\n guardedHandlers: guardedHandlers,\n handlers: handlers,\n finalizer: finalizer\n };\n },\n\n createUnaryExpression: function (operator, argument) {\n if (operator === '++' || operator === '--') {\n return {\n type: Syntax.UpdateExpression,\n operator: operator,\n argument: argument,\n prefix: true\n };\n }\n return {\n type: Syntax.UnaryExpression,\n operator: operator,\n argument: argument,\n prefix: true\n };\n },\n\n createVariableDeclaration: function (declarations, kind) {\n return {\n type: Syntax.VariableDeclaration,\n declarations: declarations,\n kind: kind\n };\n },\n\n createVariableDeclarator: function (id, init) {\n return {\n type: Syntax.VariableDeclarator,\n id: id,\n init: init\n };\n },\n\n createWhileStatement: function (test, body) {\n return {\n type: Syntax.WhileStatement,\n test: test,\n body: body\n };\n },\n\n createWithStatement: function (object, body) {\n return {\n type: Syntax.WithStatement,\n object: object,\n body: body\n };\n }\n };\n\n // Return true if there is a line terminator before the next token.\n\n function peekLineTerminator() {\n var pos, line, start, found;\n\n pos = index;\n line = lineNumber;\n start = lineStart;\n skipComment();\n found = lineNumber !== line;\n index = pos;\n lineNumber = line;\n lineStart = start;\n\n return found;\n }\n\n // Throw an exception\n\n function throwError(token, messageFormat) {\n var error,\n args = Array.prototype.slice.call(arguments, 2),\n msg = messageFormat.replace(\n /%(\\d)/g,\n function (whole, index) {\n assert(index < args.length, 'Message reference must be in range');\n return args[index];\n }\n );\n\n if (typeof token.lineNumber === 'number') {\n error = new Error('Line ' + token.lineNumber + ': ' + msg);\n error.index = token.start;\n error.lineNumber = token.lineNumber;\n error.column = token.start - lineStart + 1;\n } else {\n error = new Error('Line ' + lineNumber + ': ' + msg);\n error.index = index;\n error.lineNumber = lineNumber;\n error.column = index - lineStart + 1;\n }\n\n error.description = msg;\n throw error;\n }\n\n function throwErrorTolerant() {\n try {\n throwError.apply(null, arguments);\n } catch (e) {\n if (extra.errors) {\n extra.errors.push(e);\n } else {\n throw e;\n }\n }\n }\n\n\n // Throw an exception because of the token.\n\n function throwUnexpected(token) {\n if (token.type === Token.EOF) {\n throwError(token, Messages.UnexpectedEOS);\n }\n\n if (token.type === Token.NumericLiteral) {\n throwError(token, Messages.UnexpectedNumber);\n }\n\n if (token.type === Token.StringLiteral) {\n throwError(token, Messages.UnexpectedString);\n }\n\n if (token.type === Token.Identifier) {\n throwError(token, Messages.UnexpectedIdentifier);\n }\n\n if (token.type === Token.Keyword) {\n if (isFutureReservedWord(token.value)) {\n throwError(token, Messages.UnexpectedReserved);\n } else if (strict && isStrictModeReservedWord(token.value)) {\n throwErrorTolerant(token, Messages.StrictReservedWord);\n return;\n }\n throwError(token, Messages.UnexpectedToken, token.value);\n }\n\n // BooleanLiteral, NullLiteral, or Punctuator.\n throwError(token, Messages.UnexpectedToken, token.value);\n }\n\n // Expect the next token to match the specified punctuator.\n // If not, an exception will be thrown.\n\n function expect(value) {\n var token = lex();\n if (token.type !== Token.Punctuator || token.value !== value) {\n throwUnexpected(token);\n }\n }\n\n // Expect the next token to match the specified keyword.\n // If not, an exception will be thrown.\n\n function expectKeyword(keyword) {\n var token = lex();\n if (token.type !== Token.Keyword || token.value !== keyword) {\n throwUnexpected(token);\n }\n }\n\n // Return true if the next token matches the specified punctuator.\n\n function match(value) {\n return lookahead.type === Token.Punctuator && lookahead.value === value;\n }\n\n // Return true if the next token matches the specified keyword\n\n function matchKeyword(keyword) {\n return lookahead.type === Token.Keyword && lookahead.value === keyword;\n }\n\n // Return true if the next token is an assignment operator\n\n function matchAssign() {\n var op;\n\n if (lookahead.type !== Token.Punctuator) {\n return false;\n }\n op = lookahead.value;\n return op === '=' ||\n op === '*=' ||\n op === '/=' ||\n op === '%=' ||\n op === '+=' ||\n op === '-=' ||\n op === '<<=' ||\n op === '>>=' ||\n op === '>>>=' ||\n op === '&=' ||\n op === '^=' ||\n op === '|=';\n }\n\n function consumeSemicolon() {\n var line;\n\n // Catch the very common case first: immediately a semicolon (U+003B).\n if (source.charCodeAt(index) === 0x3B || match(';')) {\n lex();\n return;\n }\n\n line = lineNumber;\n skipComment();\n if (lineNumber !== line) {\n return;\n }\n\n if (lookahead.type !== Token.EOF && !match('}')) {\n throwUnexpected(lookahead);\n }\n }\n\n // Return true if provided expression is LeftHandSideExpression\n\n function isLeftHandSide(expr) {\n return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;\n }\n\n // 11.1.4 Array Initialiser\n\n function parseArrayInitialiser() {\n var elements = [], startToken;\n\n startToken = lookahead;\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else {\n elements.push(parseAssignmentExpression());\n\n if (!match(']')) {\n expect(',');\n }\n }\n }\n\n lex();\n\n return delegate.markEnd(delegate.createArrayExpression(elements), startToken);\n }\n\n // 11.1.5 Object Initialiser\n\n function parsePropertyFunction(param, first) {\n var previousStrict, body, startToken;\n\n previousStrict = strict;\n startToken = lookahead;\n body = parseFunctionSourceElements();\n if (first && strict && isRestrictedWord(param[0].name)) {\n throwErrorTolerant(first, Messages.StrictParamName);\n }\n strict = previousStrict;\n return delegate.markEnd(delegate.createFunctionExpression(null, param, [], body), startToken);\n }\n\n function parseObjectPropertyKey() {\n var token, startToken;\n\n startToken = lookahead;\n token = lex();\n\n // Note: This function is called only from parseObjectProperty(), where\n // EOF and Punctuator tokens are already filtered out.\n\n if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {\n if (strict && token.octal) {\n throwErrorTolerant(token, Messages.StrictOctalLiteral);\n }\n return delegate.markEnd(delegate.createLiteral(token), startToken);\n }\n\n return delegate.markEnd(delegate.createIdentifier(token.value), startToken);\n }\n\n function parseObjectProperty() {\n var token, key, id, value, param, startToken;\n\n token = lookahead;\n startToken = lookahead;\n\n if (token.type === Token.Identifier) {\n\n id = parseObjectPropertyKey();\n\n // Property Assignment: Getter and Setter.\n\n if (token.value === 'get' && !match(':')) {\n key = parseObjectPropertyKey();\n expect('(');\n expect(')');\n value = parsePropertyFunction([]);\n return delegate.markEnd(delegate.createProperty('get', key, value), startToken);\n }\n if (token.value === 'set' && !match(':')) {\n key = parseObjectPropertyKey();\n expect('(');\n token = lookahead;\n if (token.type !== Token.Identifier) {\n expect(')');\n throwErrorTolerant(token, Messages.UnexpectedToken, token.value);\n value = parsePropertyFunction([]);\n } else {\n param = [ parseVariableIdentifier() ];\n expect(')');\n value = parsePropertyFunction(param, token);\n }\n return delegate.markEnd(delegate.createProperty('set', key, value), startToken);\n }\n expect(':');\n value = parseAssignmentExpression();\n return delegate.markEnd(delegate.createProperty('init', id, value), startToken);\n }\n if (token.type === Token.EOF || token.type === Token.Punctuator) {\n throwUnexpected(token);\n } else {\n key = parseObjectPropertyKey();\n expect(':');\n value = parseAssignmentExpression();\n return delegate.markEnd(delegate.createProperty('init', key, value), startToken);\n }\n }\n\n function parseObjectInitialiser() {\n var properties = [], property, name, key, kind, map = {}, toString = String, startToken;\n\n startToken = lookahead;\n\n expect('{');\n\n while (!match('}')) {\n property = parseObjectProperty();\n\n if (property.key.type === Syntax.Identifier) {\n name = property.key.name;\n } else {\n name = toString(property.key.value);\n }\n kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;\n\n key = '$' + name;\n if (Object.prototype.hasOwnProperty.call(map, key)) {\n if (map[key] === PropertyKind.Data) {\n if (strict && kind === PropertyKind.Data) {\n throwErrorTolerant({}, Messages.StrictDuplicateProperty);\n } else if (kind !== PropertyKind.Data) {\n throwErrorTolerant({}, Messages.AccessorDataProperty);\n }\n } else {\n if (kind === PropertyKind.Data) {\n throwErrorTolerant({}, Messages.AccessorDataProperty);\n } else if (map[key] & kind) {\n throwErrorTolerant({}, Messages.AccessorGetSet);\n }\n }\n map[key] |= kind;\n } else {\n map[key] = kind;\n }\n\n properties.push(property);\n\n if (!match('}')) {\n expect(',');\n }\n }\n\n expect('}');\n\n return delegate.markEnd(delegate.createObjectExpression(properties), startToken);\n }\n\n // 11.1.6 The Grouping Operator\n\n function parseGroupExpression() {\n var expr;\n\n expect('(');\n\n expr = parseExpression();\n\n expect(')');\n\n return expr;\n }\n\n\n // 11.1 Primary Expressions\n\n function parsePrimaryExpression() {\n var type, token, expr, startToken;\n\n if (match('(')) {\n return parseGroupExpression();\n }\n\n if (match('[')) {\n return parseArrayInitialiser();\n }\n\n if (match('{')) {\n return parseObjectInitialiser();\n }\n\n type = lookahead.type;\n startToken = lookahead;\n\n if (type === Token.Identifier) {\n expr = delegate.createIdentifier(lex().value);\n } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {\n if (strict && lookahead.octal) {\n throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);\n }\n expr = delegate.createLiteral(lex());\n } else if (type === Token.Keyword) {\n if (matchKeyword('function')) {\n return parseFunctionExpression();\n }\n if (matchKeyword('this')) {\n lex();\n expr = delegate.createThisExpression();\n } else {\n throwUnexpected(lex());\n }\n } else if (type === Token.BooleanLiteral) {\n token = lex();\n token.value = (token.value === 'true');\n expr = delegate.createLiteral(token);\n } else if (type === Token.NullLiteral) {\n token = lex();\n token.value = null;\n expr = delegate.createLiteral(token);\n } else if (match('/') || match('/=')) {\n if (typeof extra.tokens !== 'undefined') {\n expr = delegate.createLiteral(collectRegex());\n } else {\n expr = delegate.createLiteral(scanRegExp());\n }\n peek();\n } else {\n throwUnexpected(lex());\n }\n\n return delegate.markEnd(expr, startToken);\n }\n\n // 11.2 Left-Hand-Side Expressions\n\n function parseArguments() {\n var args = [];\n\n expect('(');\n\n if (!match(')')) {\n while (index < length) {\n args.push(parseAssignmentExpression());\n if (match(')')) {\n break;\n }\n expect(',');\n }\n }\n\n expect(')');\n\n return args;\n }\n\n function parseNonComputedProperty() {\n var token, startToken;\n\n startToken = lookahead;\n token = lex();\n\n if (!isIdentifierName(token)) {\n throwUnexpected(token);\n }\n\n return delegate.markEnd(delegate.createIdentifier(token.value), startToken);\n }\n\n function parseNonComputedMember() {\n expect('.');\n\n return parseNonComputedProperty();\n }\n\n function parseComputedMember() {\n var expr;\n\n expect('[');\n\n expr = parseExpression();\n\n expect(']');\n\n return expr;\n }\n\n function parseNewExpression() {\n var callee, args, startToken;\n\n startToken = lookahead;\n expectKeyword('new');\n callee = parseLeftHandSideExpression();\n args = match('(') ? parseArguments() : [];\n\n return delegate.markEnd(delegate.createNewExpression(callee, args), startToken);\n }\n\n function parseLeftHandSideExpressionAllowCall() {\n var previousAllowIn, expr, args, property, startToken;\n\n startToken = lookahead;\n\n previousAllowIn = state.allowIn;\n state.allowIn = true;\n expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();\n state.allowIn = previousAllowIn;\n\n for (;;) {\n if (match('.')) {\n property = parseNonComputedMember();\n expr = delegate.createMemberExpression('.', expr, property);\n } else if (match('(')) {\n args = parseArguments();\n expr = delegate.createCallExpression(expr, args);\n } else if (match('[')) {\n property = parseComputedMember();\n expr = delegate.createMemberExpression('[', expr, property);\n } else {\n break;\n }\n delegate.markEnd(expr, startToken);\n }\n\n return expr;\n }\n\n function parseLeftHandSideExpression() {\n var previousAllowIn, expr, property, startToken;\n\n startToken = lookahead;\n\n previousAllowIn = state.allowIn;\n expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();\n state.allowIn = previousAllowIn;\n\n while (match('.') || match('[')) {\n if (match('[')) {\n property = parseComputedMember();\n expr = delegate.createMemberExpression('[', expr, property);\n } else {\n property = parseNonComputedMember();\n expr = delegate.createMemberExpression('.', expr, property);\n }\n delegate.markEnd(expr, startToken);\n }\n\n return expr;\n }\n\n // 11.3 Postfix Expressions\n\n function parsePostfixExpression() {\n var expr, token, startToken = lookahead;\n\n expr = parseLeftHandSideExpressionAllowCall();\n\n if (lookahead.type === Token.Punctuator) {\n if ((match('++') || match('--')) && !peekLineTerminator()) {\n // 11.3.1, 11.3.2\n if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {\n throwErrorTolerant({}, Messages.StrictLHSPostfix);\n }\n\n if (!isLeftHandSide(expr)) {\n throwErrorTolerant({}, Messages.InvalidLHSInAssignment);\n }\n\n token = lex();\n expr = delegate.markEnd(delegate.createPostfixExpression(token.value, expr), startToken);\n }\n }\n\n return expr;\n }\n\n // 11.4 Unary Operators\n\n function parseUnaryExpression() {\n var token, expr, startToken;\n\n if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {\n expr = parsePostfixExpression();\n } else if (match('++') || match('--')) {\n startToken = lookahead;\n token = lex();\n expr = parseUnaryExpression();\n // 11.4.4, 11.4.5\n if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {\n throwErrorTolerant({}, Messages.StrictLHSPrefix);\n }\n\n if (!isLeftHandSide(expr)) {\n throwErrorTolerant({}, Messages.InvalidLHSInAssignment);\n }\n\n expr = delegate.createUnaryExpression(token.value, expr);\n expr = delegate.markEnd(expr, startToken);\n } else if (match('+') || match('-') || match('~') || match('!')) {\n startToken = lookahead;\n token = lex();\n expr = parseUnaryExpression();\n expr = delegate.createUnaryExpression(token.value, expr);\n expr = delegate.markEnd(expr, startToken);\n } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {\n startToken = lookahead;\n token = lex();\n expr = parseUnaryExpression();\n expr = delegate.createUnaryExpression(token.value, expr);\n expr = delegate.markEnd(expr, startToken);\n if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {\n throwErrorTolerant({}, Messages.StrictDelete);\n }\n } else {\n expr = parsePostfixExpression();\n }\n\n return expr;\n }\n\n function binaryPrecedence(token, allowIn) {\n var prec = 0;\n\n if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {\n return 0;\n }\n\n switch (token.value) {\n case '||':\n prec = 1;\n break;\n\n case '&&':\n prec = 2;\n break;\n\n case '|':\n prec = 3;\n break;\n\n case '^':\n prec = 4;\n break;\n\n case '&':\n prec = 5;\n break;\n\n case '==':\n case '!=':\n case '===':\n case '!==':\n prec = 6;\n break;\n\n case '<':\n case '>':\n case '<=':\n case '>=':\n case 'instanceof':\n prec = 7;\n break;\n\n case 'in':\n prec = allowIn ? 7 : 0;\n break;\n\n case '<<':\n case '>>':\n case '>>>':\n prec = 8;\n break;\n\n case '+':\n case '-':\n prec = 9;\n break;\n\n case '*':\n case '/':\n case '%':\n prec = 11;\n break;\n\n default:\n break;\n }\n\n return prec;\n }\n\n // 11.5 Multiplicative Operators\n // 11.6 Additive Operators\n // 11.7 Bitwise Shift Operators\n // 11.8 Relational Operators\n // 11.9 Equality Operators\n // 11.10 Binary Bitwise Operators\n // 11.11 Binary Logical Operators\n\n function parseBinaryExpression() {\n var marker, markers, expr, token, prec, stack, right, operator, left, i;\n\n marker = lookahead;\n left = parseUnaryExpression();\n\n token = lookahead;\n prec = binaryPrecedence(token, state.allowIn);\n if (prec === 0) {\n return left;\n }\n token.prec = prec;\n lex();\n\n markers = [marker, lookahead];\n right = parseUnaryExpression();\n\n stack = [left, token, right];\n\n while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {\n\n // Reduce: make a binary expression from the three topmost entries.\n while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {\n right = stack.pop();\n operator = stack.pop().value;\n left = stack.pop();\n expr = delegate.createBinaryExpression(operator, left, right);\n markers.pop();\n marker = markers[markers.length - 1];\n delegate.markEnd(expr, marker);\n stack.push(expr);\n }\n\n // Shift.\n token = lex();\n token.prec = prec;\n stack.push(token);\n markers.push(lookahead);\n expr = parseUnaryExpression();\n stack.push(expr);\n }\n\n // Final reduce to clean-up the stack.\n i = stack.length - 1;\n expr = stack[i];\n markers.pop();\n while (i > 1) {\n expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);\n i -= 2;\n marker = markers.pop();\n delegate.markEnd(expr, marker);\n }\n\n return expr;\n }\n\n\n // 11.12 Conditional Operator\n\n function parseConditionalExpression() {\n var expr, previousAllowIn, consequent, alternate, startToken;\n\n startToken = lookahead;\n\n expr = parseBinaryExpression();\n\n if (match('?')) {\n lex();\n previousAllowIn = state.allowIn;\n state.allowIn = true;\n consequent = parseAssignmentExpression();\n state.allowIn = previousAllowIn;\n expect(':');\n alternate = parseAssignmentExpression();\n\n expr = delegate.createConditionalExpression(expr, consequent, alternate);\n delegate.markEnd(expr, startToken);\n }\n\n return expr;\n }\n\n // 11.13 Assignment Operators\n\n function parseAssignmentExpression() {\n var token, left, right, node, startToken;\n\n token = lookahead;\n startToken = lookahead;\n\n node = left = parseConditionalExpression();\n\n if (matchAssign()) {\n // LeftHandSideExpression\n if (!isLeftHandSide(left)) {\n throwErrorTolerant({}, Messages.InvalidLHSInAssignment);\n }\n\n // 11.13.1\n if (strict && left.type === Syntax.Identifier && isRestrictedWord(left.name)) {\n throwErrorTolerant(token, Messages.StrictLHSAssignment);\n }\n\n token = lex();\n right = parseAssignmentExpression();\n node = delegate.markEnd(delegate.createAssignmentExpression(token.value, left, right), startToken);\n }\n\n return node;\n }\n\n // 11.14 Comma Operator\n\n function parseExpression() {\n var expr, startToken = lookahead;\n\n expr = parseAssignmentExpression();\n\n if (match(',')) {\n expr = delegate.createSequenceExpression([ expr ]);\n\n while (index < length) {\n if (!match(',')) {\n break;\n }\n lex();\n expr.expressions.push(parseAssignmentExpression());\n }\n\n delegate.markEnd(expr, startToken);\n }\n\n return expr;\n }\n\n // 12.1 Block\n\n function parseStatementList() {\n var list = [],\n statement;\n\n while (index < length) {\n if (match('}')) {\n break;\n }\n statement = parseSourceElement();\n if (typeof statement === 'undefined') {\n break;\n }\n list.push(statement);\n }\n\n return list;\n }\n\n function parseBlock() {\n var block, startToken;\n\n startToken = lookahead;\n expect('{');\n\n block = parseStatementList();\n\n expect('}');\n\n return delegate.markEnd(delegate.createBlockStatement(block), startToken);\n }\n\n // 12.2 Variable Statement\n\n function parseVariableIdentifier() {\n var token, startToken;\n\n startToken = lookahead;\n token = lex();\n\n if (token.type !== Token.Identifier) {\n throwUnexpected(token);\n }\n\n return delegate.markEnd(delegate.createIdentifier(token.value), startToken);\n }\n\n function parseVariableDeclaration(kind) {\n var init = null, id, startToken;\n\n startToken = lookahead;\n id = parseVariableIdentifier();\n\n // 12.2.1\n if (strict && isRestrictedWord(id.name)) {\n throwErrorTolerant({}, Messages.StrictVarName);\n }\n\n if (kind === 'const') {\n expect('=');\n init = parseAssignmentExpression();\n } else if (match('=')) {\n lex();\n init = parseAssignmentExpression();\n }\n\n return delegate.markEnd(delegate.createVariableDeclarator(id, init), startToken);\n }\n\n function parseVariableDeclarationList(kind) {\n var list = [];\n\n do {\n list.push(parseVariableDeclaration(kind));\n if (!match(',')) {\n break;\n }\n lex();\n } while (index < length);\n\n return list;\n }\n\n function parseVariableStatement() {\n var declarations;\n\n expectKeyword('var');\n\n declarations = parseVariableDeclarationList();\n\n consumeSemicolon();\n\n return delegate.createVariableDeclaration(declarations, 'var');\n }\n\n // kind may be `const` or `let`\n // Both are experimental and not in the specification yet.\n // see http://wiki.ecmascript.org/doku.php?id=harmony:const\n // and http://wiki.ecmascript.org/doku.php?id=harmony:let\n function parseConstLetDeclaration(kind) {\n var declarations, startToken;\n\n startToken = lookahead;\n\n expectKeyword(kind);\n\n declarations = parseVariableDeclarationList(kind);\n\n consumeSemicolon();\n\n return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind), startToken);\n }\n\n // 12.3 Empty Statement\n\n function parseEmptyStatement() {\n expect(';');\n return delegate.createEmptyStatement();\n }\n\n // 12.4 Expression Statement\n\n function parseExpressionStatement() {\n var expr = parseExpression();\n consumeSemicolon();\n return delegate.createExpressionStatement(expr);\n }\n\n // 12.5 If statement\n\n function parseIfStatement() {\n var test, consequent, alternate;\n\n expectKeyword('if');\n\n expect('(');\n\n test = parseExpression();\n\n expect(')');\n\n consequent = parseStatement();\n\n if (matchKeyword('else')) {\n lex();\n alternate = parseStatement();\n } else {\n alternate = null;\n }\n\n return delegate.createIfStatement(test, consequent, alternate);\n }\n\n // 12.6 Iteration Statements\n\n function parseDoWhileStatement() {\n var body, test, oldInIteration;\n\n expectKeyword('do');\n\n oldInIteration = state.inIteration;\n state.inIteration = true;\n\n body = parseStatement();\n\n state.inIteration = oldInIteration;\n\n expectKeyword('while');\n\n expect('(');\n\n test = parseExpression();\n\n expect(')');\n\n if (match(';')) {\n lex();\n }\n\n return delegate.createDoWhileStatement(body, test);\n }\n\n function parseWhileStatement() {\n var test, body, oldInIteration;\n\n expectKeyword('while');\n\n expect('(');\n\n test = parseExpression();\n\n expect(')');\n\n oldInIteration = state.inIteration;\n state.inIteration = true;\n\n body = parseStatement();\n\n state.inIteration = oldInIteration;\n\n return delegate.createWhileStatement(test, body);\n }\n\n function parseForVariableDeclaration() {\n var token, declarations, startToken;\n\n startToken = lookahead;\n token = lex();\n declarations = parseVariableDeclarationList();\n\n return delegate.markEnd(delegate.createVariableDeclaration(declarations, token.value), startToken);\n }\n\n function parseForStatement() {\n var init, test, update, left, right, body, oldInIteration;\n\n init = test = update = null;\n\n expectKeyword('for');\n\n expect('(');\n\n if (match(';')) {\n lex();\n } else {\n if (matchKeyword('var') || matchKeyword('let')) {\n state.allowIn = false;\n init = parseForVariableDeclaration();\n state.allowIn = true;\n\n if (init.declarations.length === 1 && matchKeyword('in')) {\n lex();\n left = init;\n right = parseExpression();\n init = null;\n }\n } else {\n state.allowIn = false;\n init = parseExpression();\n state.allowIn = true;\n\n if (matchKeyword('in')) {\n // LeftHandSideExpression\n if (!isLeftHandSide(init)) {\n throwErrorTolerant({}, Messages.InvalidLHSInForIn);\n }\n\n lex();\n left = init;\n right = parseExpression();\n init = null;\n }\n }\n\n if (typeof left === 'undefined') {\n expect(';');\n }\n }\n\n if (typeof left === 'undefined') {\n\n if (!match(';')) {\n test = parseExpression();\n }\n expect(';');\n\n if (!match(')')) {\n update = parseExpression();\n }\n }\n\n expect(')');\n\n oldInIteration = state.inIteration;\n state.inIteration = true;\n\n body = parseStatement();\n\n state.inIteration = oldInIteration;\n\n return (typeof left === 'undefined') ?\n delegate.createForStatement(init, test, update, body) :\n delegate.createForInStatement(left, right, body);\n }\n\n // 12.7 The continue statement\n\n function parseContinueStatement() {\n var label = null, key;\n\n expectKeyword('continue');\n\n // Optimize the most common form: 'continue;'.\n if (source.charCodeAt(index) === 0x3B) {\n lex();\n\n if (!state.inIteration) {\n throwError({}, Messages.IllegalContinue);\n }\n\n return delegate.createContinueStatement(null);\n }\n\n if (peekLineTerminator()) {\n if (!state.inIteration) {\n throwError({}, Messages.IllegalContinue);\n }\n\n return delegate.createContinueStatement(null);\n }\n\n if (lookahead.type === Token.Identifier) {\n label = parseVariableIdentifier();\n\n key = '$' + label.name;\n if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {\n throwError({}, Messages.UnknownLabel, label.name);\n }\n }\n\n consumeSemicolon();\n\n if (label === null && !state.inIteration) {\n throwError({}, Messages.IllegalContinue);\n }\n\n return delegate.createContinueStatement(label);\n }\n\n // 12.8 The break statement\n\n function parseBreakStatement() {\n var label = null, key;\n\n expectKeyword('break');\n\n // Catch the very common case first: immediately a semicolon (U+003B).\n if (source.charCodeAt(index) === 0x3B) {\n lex();\n\n if (!(state.inIteration || state.inSwitch)) {\n throwError({}, Messages.IllegalBreak);\n }\n\n return delegate.createBreakStatement(null);\n }\n\n if (peekLineTerminator()) {\n if (!(state.inIteration || state.inSwitch)) {\n throwError({}, Messages.IllegalBreak);\n }\n\n return delegate.createBreakStatement(null);\n }\n\n if (lookahead.type === Token.Identifier) {\n label = parseVariableIdentifier();\n\n key = '$' + label.name;\n if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {\n throwError({}, Messages.UnknownLabel, label.name);\n }\n }\n\n consumeSemicolon();\n\n if (label === null && !(state.inIteration || state.inSwitch)) {\n throwError({}, Messages.IllegalBreak);\n }\n\n return delegate.createBreakStatement(label);\n }\n\n // 12.9 The return statement\n\n function parseReturnStatement() {\n var argument = null;\n\n expectKeyword('return');\n\n if (!state.inFunctionBody) {\n throwErrorTolerant({}, Messages.IllegalReturn);\n }\n\n // 'return' followed by a space and an identifier is very common.\n if (source.charCodeAt(index) === 0x20) {\n if (isIdentifierStart(source.charCodeAt(index + 1))) {\n argument = parseExpression();\n consumeSemicolon();\n return delegate.createReturnStatement(argument);\n }\n }\n\n if (peekLineTerminator()) {\n return delegate.createReturnStatement(null);\n }\n\n if (!match(';')) {\n if (!match('}') && lookahead.type !== Token.EOF) {\n argument = parseExpression();\n }\n }\n\n consumeSemicolon();\n\n return delegate.createReturnStatement(argument);\n }\n\n // 12.10 The with statement\n\n function parseWithStatement() {\n var object, body;\n\n if (strict) {\n // TODO(ikarienator): Should we update the test cases instead?\n skipComment();\n throwErrorTolerant({}, Messages.StrictModeWith);\n }\n\n expectKeyword('with');\n\n expect('(');\n\n object = parseExpression();\n\n expect(')');\n\n body = parseStatement();\n\n return delegate.createWithStatement(object, body);\n }\n\n // 12.10 The swith statement\n\n function parseSwitchCase() {\n var test, consequent = [], statement, startToken;\n\n startToken = lookahead;\n if (matchKeyword('default')) {\n lex();\n test = null;\n } else {\n expectKeyword('case');\n test = parseExpression();\n }\n expect(':');\n\n while (index < length) {\n if (match('}') || matchKeyword('default') || matchKeyword('case')) {\n break;\n }\n statement = parseStatement();\n consequent.push(statement);\n }\n\n return delegate.markEnd(delegate.createSwitchCase(test, consequent), startToken);\n }\n\n function parseSwitchStatement() {\n var discriminant, cases, clause, oldInSwitch, defaultFound;\n\n expectKeyword('switch');\n\n expect('(');\n\n discriminant = parseExpression();\n\n expect(')');\n\n expect('{');\n\n cases = [];\n\n if (match('}')) {\n lex();\n return delegate.createSwitchStatement(discriminant, cases);\n }\n\n oldInSwitch = state.inSwitch;\n state.inSwitch = true;\n defaultFound = false;\n\n while (index < length) {\n if (match('}')) {\n break;\n }\n clause = parseSwitchCase();\n if (clause.test === null) {\n if (defaultFound) {\n throwError({}, Messages.MultipleDefaultsInSwitch);\n }\n defaultFound = true;\n }\n cases.push(clause);\n }\n\n state.inSwitch = oldInSwitch;\n\n expect('}');\n\n return delegate.createSwitchStatement(discriminant, cases);\n }\n\n // 12.13 The throw statement\n\n function parseThrowStatement() {\n var argument;\n\n expectKeyword('throw');\n\n if (peekLineTerminator()) {\n throwError({}, Messages.NewlineAfterThrow);\n }\n\n argument = parseExpression();\n\n consumeSemicolon();\n\n return delegate.createThrowStatement(argument);\n }\n\n // 12.14 The try statement\n\n function parseCatchClause() {\n var param, body, startToken;\n\n startToken = lookahead;\n expectKeyword('catch');\n\n expect('(');\n if (match(')')) {\n throwUnexpected(lookahead);\n }\n\n param = parseVariableIdentifier();\n // 12.14.1\n if (strict && isRestrictedWord(param.name)) {\n throwErrorTolerant({}, Messages.StrictCatchVariable);\n }\n\n expect(')');\n body = parseBlock();\n return delegate.markEnd(delegate.createCatchClause(param, body), startToken);\n }\n\n function parseTryStatement() {\n var block, handlers = [], finalizer = null;\n\n expectKeyword('try');\n\n block = parseBlock();\n\n if (matchKeyword('catch')) {\n handlers.push(parseCatchClause());\n }\n\n if (matchKeyword('finally')) {\n lex();\n finalizer = parseBlock();\n }\n\n if (handlers.length === 0 && !finalizer) {\n throwError({}, Messages.NoCatchOrFinally);\n }\n\n return delegate.createTryStatement(block, [], handlers, finalizer);\n }\n\n // 12.15 The debugger statement\n\n function parseDebuggerStatement() {\n expectKeyword('debugger');\n\n consumeSemicolon();\n\n return delegate.createDebuggerStatement();\n }\n\n // 12 Statements\n\n function parseStatement() {\n var type = lookahead.type,\n expr,\n labeledBody,\n key,\n startToken;\n\n if (type === Token.EOF) {\n throwUnexpected(lookahead);\n }\n\n if (type === Token.Punctuator && lookahead.value === '{') {\n return parseBlock();\n }\n\n startToken = lookahead;\n\n if (type === Token.Punctuator) {\n switch (lookahead.value) {\n case ';':\n return delegate.markEnd(parseEmptyStatement(), startToken);\n case '(':\n return delegate.markEnd(parseExpressionStatement(), startToken);\n default:\n break;\n }\n }\n\n if (type === Token.Keyword) {\n switch (lookahead.value) {\n case 'break':\n return delegate.markEnd(parseBreakStatement(), startToken);\n case 'continue':\n return delegate.markEnd(parseContinueStatement(), startToken);\n case 'debugger':\n return delegate.markEnd(parseDebuggerStatement(), startToken);\n case 'do':\n return delegate.markEnd(parseDoWhileStatement(), startToken);\n case 'for':\n return delegate.markEnd(parseForStatement(), startToken);\n case 'function':\n return delegate.markEnd(parseFunctionDeclaration(), startToken);\n case 'if':\n return delegate.markEnd(parseIfStatement(), startToken);\n case 'return':\n return delegate.markEnd(parseReturnStatement(), startToken);\n case 'switch':\n return delegate.markEnd(parseSwitchStatement(), startToken);\n case 'throw':\n return delegate.markEnd(parseThrowStatement(), startToken);\n case 'try':\n return delegate.markEnd(parseTryStatement(), startToken);\n case 'var':\n return delegate.markEnd(parseVariableStatement(), startToken);\n case 'while':\n return delegate.markEnd(parseWhileStatement(), startToken);\n case 'with':\n return delegate.markEnd(parseWithStatement(), startToken);\n default:\n break;\n }\n }\n\n expr = parseExpression();\n\n // 12.12 Labelled Statements\n if ((expr.type === Syntax.Identifier) && match(':')) {\n lex();\n\n key = '$' + expr.name;\n if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {\n throwError({}, Messages.Redeclaration, 'Label', expr.name);\n }\n\n state.labelSet[key] = true;\n labeledBody = parseStatement();\n delete state.labelSet[key];\n return delegate.markEnd(delegate.createLabeledStatement(expr, labeledBody), startToken);\n }\n\n consumeSemicolon();\n\n return delegate.markEnd(delegate.createExpressionStatement(expr), startToken);\n }\n\n // 13 Function Definition\n\n function parseFunctionSourceElements() {\n var sourceElement, sourceElements = [], token, directive, firstRestricted,\n oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, startToken;\n\n startToken = lookahead;\n expect('{');\n\n while (index < length) {\n if (lookahead.type !== Token.StringLiteral) {\n break;\n }\n token = lookahead;\n\n sourceElement = parseSourceElement();\n sourceElements.push(sourceElement);\n if (sourceElement.expression.type !== Syntax.Literal) {\n // this is not directive\n break;\n }\n directive = source.slice(token.start + 1, token.end - 1);\n if (directive === 'use strict') {\n strict = true;\n if (firstRestricted) {\n throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);\n }\n } else {\n if (!firstRestricted && token.octal) {\n firstRestricted = token;\n }\n }\n }\n\n oldLabelSet = state.labelSet;\n oldInIteration = state.inIteration;\n oldInSwitch = state.inSwitch;\n oldInFunctionBody = state.inFunctionBody;\n\n state.labelSet = {};\n state.inIteration = false;\n state.inSwitch = false;\n state.inFunctionBody = true;\n\n while (index < length) {\n if (match('}')) {\n break;\n }\n sourceElement = parseSourceElement();\n if (typeof sourceElement === 'undefined') {\n break;\n }\n sourceElements.push(sourceElement);\n }\n\n expect('}');\n\n state.labelSet = oldLabelSet;\n state.inIteration = oldInIteration;\n state.inSwitch = oldInSwitch;\n state.inFunctionBody = oldInFunctionBody;\n\n return delegate.markEnd(delegate.createBlockStatement(sourceElements), startToken);\n }\n\n function parseParams(firstRestricted) {\n var param, params = [], token, stricted, paramSet, key, message;\n expect('(');\n\n if (!match(')')) {\n paramSet = {};\n while (index < length) {\n token = lookahead;\n param = parseVariableIdentifier();\n key = '$' + token.value;\n if (strict) {\n if (isRestrictedWord(token.value)) {\n stricted = token;\n message = Messages.StrictParamName;\n }\n if (Object.prototype.hasOwnProperty.call(paramSet, key)) {\n stricted = token;\n message = Messages.StrictParamDupe;\n }\n } else if (!firstRestricted) {\n if (isRestrictedWord(token.value)) {\n firstRestricted = token;\n message = Messages.StrictParamName;\n } else if (isStrictModeReservedWord(token.value)) {\n firstRestricted = token;\n message = Messages.StrictReservedWord;\n } else if (Object.prototype.hasOwnProperty.call(paramSet, key)) {\n firstRestricted = token;\n message = Messages.StrictParamDupe;\n }\n }\n params.push(param);\n paramSet[key] = true;\n if (match(')')) {\n break;\n }\n expect(',');\n }\n }\n\n expect(')');\n\n return {\n params: params,\n stricted: stricted,\n firstRestricted: firstRestricted,\n message: message\n };\n }\n\n function parseFunctionDeclaration() {\n var id, params = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, startToken;\n\n startToken = lookahead;\n\n expectKeyword('function');\n token = lookahead;\n id = parseVariableIdentifier();\n if (strict) {\n if (isRestrictedWord(token.value)) {\n throwErrorTolerant(token, Messages.StrictFunctionName);\n }\n } else {\n if (isRestrictedWord(token.value)) {\n firstRestricted = token;\n message = Messages.StrictFunctionName;\n } else if (isStrictModeReservedWord(token.value)) {\n firstRestricted = token;\n message = Messages.StrictReservedWord;\n }\n }\n\n tmp = parseParams(firstRestricted);\n params = tmp.params;\n stricted = tmp.stricted;\n firstRestricted = tmp.firstRestricted;\n if (tmp.message) {\n message = tmp.message;\n }\n\n previousStrict = strict;\n body = parseFunctionSourceElements();\n if (strict && firstRestricted) {\n throwError(firstRestricted, message);\n }\n if (strict && stricted) {\n throwErrorTolerant(stricted, message);\n }\n strict = previousStrict;\n\n return delegate.markEnd(delegate.createFunctionDeclaration(id, params, [], body), startToken);\n }\n\n function parseFunctionExpression() {\n var token, id = null, stricted, firstRestricted, message, tmp, params = [], body, previousStrict, startToken;\n\n startToken = lookahead;\n expectKeyword('function');\n\n if (!match('(')) {\n token = lookahead;\n id = parseVariableIdentifier();\n if (strict) {\n if (isRestrictedWord(token.value)) {\n throwErrorTolerant(token, Messages.StrictFunctionName);\n }\n } else {\n if (isRestrictedWord(token.value)) {\n firstRestricted = token;\n message = Messages.StrictFunctionName;\n } else if (isStrictModeReservedWord(token.value)) {\n firstRestricted = token;\n message = Messages.StrictReservedWord;\n }\n }\n }\n\n tmp = parseParams(firstRestricted);\n params = tmp.params;\n stricted = tmp.stricted;\n firstRestricted = tmp.firstRestricted;\n if (tmp.message) {\n message = tmp.message;\n }\n\n previousStrict = strict;\n body = parseFunctionSourceElements();\n if (strict && firstRestricted) {\n throwError(firstRestricted, message);\n }\n if (strict && stricted) {\n throwErrorTolerant(stricted, message);\n }\n strict = previousStrict;\n\n return delegate.markEnd(delegate.createFunctionExpression(id, params, [], body), startToken);\n }\n\n // 14 Program\n\n function parseSourceElement() {\n if (lookahead.type === Token.Keyword) {\n switch (lookahead.value) {\n case 'const':\n case 'let':\n return parseConstLetDeclaration(lookahead.value);\n case 'function':\n return parseFunctionDeclaration();\n default:\n return parseStatement();\n }\n }\n\n if (lookahead.type !== Token.EOF) {\n return parseStatement();\n }\n }\n\n function parseSourceElements() {\n var sourceElement, sourceElements = [], token, directive, firstRestricted;\n\n while (index < length) {\n token = lookahead;\n if (token.type !== Token.StringLiteral) {\n break;\n }\n\n sourceElement = parseSourceElement();\n sourceElements.push(sourceElement);\n if (sourceElement.expression.type !== Syntax.Literal) {\n // this is not directive\n break;\n }\n directive = source.slice(token.start + 1, token.end - 1);\n if (directive === 'use strict') {\n strict = true;\n if (firstRestricted) {\n throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);\n }\n } else {\n if (!firstRestricted && token.octal) {\n firstRestricted = token;\n }\n }\n }\n\n while (index < length) {\n sourceElement = parseSourceElement();\n /* istanbul ignore if */\n if (typeof sourceElement === 'undefined') {\n break;\n }\n sourceElements.push(sourceElement);\n }\n return sourceElements;\n }\n\n function parseProgram() {\n var body, startToken;\n\n skipComment();\n peek();\n startToken = lookahead;\n strict = false;\n\n body = parseSourceElements();\n return delegate.markEnd(delegate.createProgram(body), startToken);\n }\n\n function filterTokenLocation() {\n var i, entry, token, tokens = [];\n\n for (i = 0; i < extra.tokens.length; ++i) {\n entry = extra.tokens[i];\n token = {\n type: entry.type,\n value: entry.value\n };\n if (extra.range) {\n token.range = entry.range;\n }\n if (extra.loc) {\n token.loc = entry.loc;\n }\n tokens.push(token);\n }\n\n extra.tokens = tokens;\n }\n\n function tokenize(code, options) {\n var toString,\n token,\n tokens;\n\n toString = String;\n if (typeof code !== 'string' && !(code instanceof String)) {\n code = toString(code);\n }\n\n delegate = SyntaxTreeDelegate;\n source = code;\n index = 0;\n lineNumber = (source.length > 0) ? 1 : 0;\n lineStart = 0;\n length = source.length;\n lookahead = null;\n state = {\n allowIn: true,\n labelSet: {},\n inFunctionBody: false,\n inIteration: false,\n inSwitch: false,\n lastCommentStart: -1\n };\n\n extra = {};\n\n // Options matching.\n options = options || {};\n\n // Of course we collect tokens here.\n options.tokens = true;\n extra.tokens = [];\n extra.tokenize = true;\n // The following two fields are necessary to compute the Regex tokens.\n extra.openParenToken = -1;\n extra.openCurlyToken = -1;\n\n extra.range = (typeof options.range === 'boolean') && options.range;\n extra.loc = (typeof options.loc === 'boolean') && options.loc;\n\n if (typeof options.comment === 'boolean' && options.comment) {\n extra.comments = [];\n }\n if (typeof options.tolerant === 'boolean' && options.tolerant) {\n extra.errors = [];\n }\n\n try {\n peek();\n if (lookahead.type === Token.EOF) {\n return extra.tokens;\n }\n\n token = lex();\n while (lookahead.type !== Token.EOF) {\n try {\n token = lex();\n } catch (lexError) {\n token = lookahead;\n if (extra.errors) {\n extra.errors.push(lexError);\n // We have to break on the first error\n // to avoid infinite loops.\n break;\n } else {\n throw lexError;\n }\n }\n }\n\n filterTokenLocation();\n tokens = extra.tokens;\n if (typeof extra.comments !== 'undefined') {\n tokens.comments = extra.comments;\n }\n if (typeof extra.errors !== 'undefined') {\n tokens.errors = extra.errors;\n }\n } catch (e) {\n throw e;\n } finally {\n extra = {};\n }\n return tokens;\n }\n\n function parse(code, options) {\n var program, toString;\n\n toString = String;\n if (typeof code !== 'string' && !(code instanceof String)) {\n code = toString(code);\n }\n\n delegate = SyntaxTreeDelegate;\n source = code;\n index = 0;\n lineNumber = (source.length > 0) ? 1 : 0;\n lineStart = 0;\n length = source.length;\n lookahead = null;\n state = {\n allowIn: true,\n labelSet: {},\n inFunctionBody: false,\n inIteration: false,\n inSwitch: false,\n lastCommentStart: -1\n };\n\n extra = {};\n if (typeof options !== 'undefined') {\n extra.range = (typeof options.range === 'boolean') && options.range;\n extra.loc = (typeof options.loc === 'boolean') && options.loc;\n extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;\n\n if (extra.loc && options.source !== null && options.source !== undefined) {\n extra.source = toString(options.source);\n }\n\n if (typeof options.tokens === 'boolean' && options.tokens) {\n extra.tokens = [];\n }\n if (typeof options.comment === 'boolean' && options.comment) {\n extra.comments = [];\n }\n if (typeof options.tolerant === 'boolean' && options.tolerant) {\n extra.errors = [];\n }\n if (extra.attachComment) {\n extra.range = true;\n extra.comments = [];\n extra.bottomRightStack = [];\n extra.trailingComments = [];\n extra.leadingComments = [];\n }\n }\n\n try {\n program = parseProgram();\n if (typeof extra.comments !== 'undefined') {\n program.comments = extra.comments;\n }\n if (typeof extra.tokens !== 'undefined') {\n filterTokenLocation();\n program.tokens = extra.tokens;\n }\n if (typeof extra.errors !== 'undefined') {\n program.errors = extra.errors;\n }\n } catch (e) {\n throw e;\n } finally {\n extra = {};\n }\n\n return program;\n }\n\n // Sync with *.json manifests.\n exports.version = '1.2.2';\n\n exports.tokenize = tokenize;\n\n exports.parse = parse;\n\n // Deep copy.\n /* istanbul ignore next */\n exports.Syntax = (function () {\n var name, types = {};\n\n if (typeof Object.create === 'function') {\n types = Object.create(null);\n }\n\n for (name in Syntax) {\n if (Syntax.hasOwnProperty(name)) {\n types[name] = Syntax[name];\n }\n }\n\n if (typeof Object.freeze === 'function') {\n Object.freeze(types);\n }\n\n return types;\n }());\n\n}));\n/* vim: set sw=4 ts=4 et tw=80 : */\n/**\n * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*global define, Reflect */\n\n/*\n * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac),\n * and the recursive nature of esprima can cause it to overflow pretty\n * quickly. So favor it built in Reflect parser:\n * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API\n */\ndefine('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) {\n if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') {\n return Reflect;\n } else {\n return esprima;\n }\n});\ndefine('uglifyjs/consolidator', [\"require\", \"exports\", \"module\", \"./parse-js\", \"./process\"], function(require, exports, module) {\n/**\n * @preserve Copyright 2012 Robert Gust-Bardon <http://robert.gust-bardon.org/>.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above\n * copyright notice, this list of conditions and the following\n * disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n */\n\n/**\n * @fileoverview Enhances <a href=\"https://github.com/mishoo/UglifyJS/\"\n * >UglifyJS</a> with consolidation of null, Boolean, and String values.\n * <p>Also known as aliasing, this feature has been deprecated in <a href=\n * \"http://closure-compiler.googlecode.com/\">the Closure Compiler</a> since its\n * initial release, where it is unavailable from the <abbr title=\n * \"command line interface\">CLI</a>. The Closure Compiler allows one to log and\n * influence this process. In contrast, this implementation does not introduce\n * any variable declarations in global code and derives String values from\n * identifier names used as property accessors.</p>\n * <p>Consolidating literals may worsen the data compression ratio when an <a\n * href=\"http://tools.ietf.org/html/rfc2616#section-3.5\">encoding\n * transformation</a> is applied. For instance, <a href=\n * \"http://code.jquery.com/jquery-1.7.1.js\">jQuery 1.7.1</a> takes 248235 bytes.\n * Building it with <a href=\"https://github.com/mishoo/UglifyJS/tarball/v1.2.5\">\n * UglifyJS v1.2.5</a> results in 93647 bytes (37.73% of the original) which are\n * then compressed to 33154 bytes (13.36% of the original) using <a href=\n * \"http://linux.die.net/man/1/gzip\">gzip(1)</a>. Building it with the same\n * version of UglifyJS 1.2.5 patched with the implementation of consolidation\n * results in 80784 bytes (a decrease of 12863 bytes, i.e. 13.74%, in comparison\n * to the aforementioned 93647 bytes) which are then compressed to 34013 bytes\n * (an increase of 859 bytes, i.e. 2.59%, in comparison to the aforementioned\n * 33154 bytes).</p>\n * <p>Written in <a href=\"http://es5.github.com/#x4.2.2\">the strict variant</a>\n * of <a href=\"http://es5.github.com/\">ECMA-262 5.1 Edition</a>. Encoded in <a\n * href=\"http://tools.ietf.org/html/rfc3629\">UTF-8</a>. Follows <a href=\n * \"http://google-styleguide.googlecode.com/svn-history/r76/trunk/javascriptguide.xml\"\n * >Revision 2.28 of the Google JavaScript Style Guide</a> (except for the\n * discouraged use of the {@code function} tag and the {@code namespace} tag).\n * 100% typed for the <a href=\n * \"http://closure-compiler.googlecode.com/files/compiler-20120123.tar.gz\"\n * >Closure Compiler Version 1741</a>.</p>\n * <p>Should you find this software useful, please consider <a href=\n * \"https://paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JZLW72X8FD4WG\"\n * >a donation</a>.</p>\n * @author follow.me@RGustBardon (Robert Gust-Bardon)\n * @supported Tested with:\n * <ul>\n * <li><a href=\"http://nodejs.org/dist/v0.6.10/\">Node v0.6.10</a>,</li>\n * <li><a href=\"https://github.com/mishoo/UglifyJS/tarball/v1.2.5\">UglifyJS\n * v1.2.5</a>.</li>\n * </ul>\n */\n\n/*global console:false, exports:true, module:false, require:false */\n/*jshint sub:true */\n/**\n * Consolidates null, Boolean, and String values found inside an <abbr title=\n * \"abstract syntax tree\">AST</abbr>.\n * @param {!TSyntacticCodeUnit} oAbstractSyntaxTree An array-like object\n * representing an <abbr title=\"abstract syntax tree\">AST</abbr>.\n * @return {!TSyntacticCodeUnit} An array-like object representing an <abbr\n * title=\"abstract syntax tree\">AST</abbr> with its null, Boolean, and\n * String values consolidated.\n */\n// TODO(user) Consolidation of mathematical values found in numeric literals.\n// TODO(user) Unconsolidation.\n// TODO(user) Consolidation of ECMA-262 6th Edition programs.\n// TODO(user) Rewrite in ECMA-262 6th Edition.\nexports['ast_consolidate'] = function(oAbstractSyntaxTree) {\n 'use strict';\n /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,\n latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,\n onevar:true, plusplus:true, regexp:true, undef:true, strict:true,\n sub:false, trailing:true */\n\n var _,\n /**\n * A record consisting of data about one or more source elements.\n * @constructor\n * @nosideeffects\n */\n TSourceElementsData = function() {\n /**\n * The category of the elements.\n * @type {number}\n * @see ESourceElementCategories\n */\n this.nCategory = ESourceElementCategories.N_OTHER;\n /**\n * The number of occurrences (within the elements) of each primitive\n * value that could be consolidated.\n * @type {!Array.<!Object.<string, number>>}\n */\n this.aCount = [];\n this.aCount[EPrimaryExpressionCategories.N_IDENTIFIER_NAMES] = {};\n this.aCount[EPrimaryExpressionCategories.N_STRING_LITERALS] = {};\n this.aCount[EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS] =\n {};\n /**\n * Identifier names found within the elements.\n * @type {!Array.<string>}\n */\n this.aIdentifiers = [];\n /**\n * Prefixed representation Strings of each primitive value that could be\n * consolidated within the elements.\n * @type {!Array.<string>}\n */\n this.aPrimitiveValues = [];\n },\n /**\n * A record consisting of data about a primitive value that could be\n * consolidated.\n * @constructor\n * @nosideeffects\n */\n TPrimitiveValue = function() {\n /**\n * The difference in the number of terminal symbols between the original\n * source text and the one with the primitive value consolidated. If the\n * difference is positive, the primitive value is considered worthwhile.\n * @type {number}\n */\n this.nSaving = 0;\n /**\n * An identifier name of the variable that will be declared and assigned\n * the primitive value if the primitive value is consolidated.\n * @type {string}\n */\n this.sName = '';\n },\n /**\n * A record consisting of data on what to consolidate within the range of\n * source elements that is currently being considered.\n * @constructor\n * @nosideeffects\n */\n TSolution = function() {\n /**\n * An object whose keys are prefixed representation Strings of each\n * primitive value that could be consolidated within the elements and\n * whose values are corresponding data about those primitive values.\n * @type {!Object.<string, {nSaving: number, sName: string}>}\n * @see TPrimitiveValue\n */\n this.oPrimitiveValues = {};\n /**\n * The difference in the number of terminal symbols between the original\n * source text and the one with all the worthwhile primitive values\n * consolidated.\n * @type {number}\n * @see TPrimitiveValue#nSaving\n */\n this.nSavings = 0;\n },\n /**\n * The processor of <abbr title=\"abstract syntax tree\">AST</abbr>s found\n * in UglifyJS.\n * @namespace\n * @type {!TProcessor}\n */\n oProcessor = (/** @type {!TProcessor} */ require('./process')),\n /**\n * A record consisting of a number of constants that represent the\n * difference in the number of terminal symbols between a source text with\n * a modified syntactic code unit and the original one.\n * @namespace\n * @type {!Object.<string, number>}\n */\n oWeights = {\n /**\n * The difference in the number of punctuators required by the bracket\n * notation and the dot notation.\n * <p><code>'[]'.length - '.'.length</code></p>\n * @const\n * @type {number}\n */\n N_PROPERTY_ACCESSOR: 1,\n /**\n * The number of punctuators required by a variable declaration with an\n * initialiser.\n * <p><code>':'.length + ';'.length</code></p>\n * @const\n * @type {number}\n */\n N_VARIABLE_DECLARATION: 2,\n /**\n * The number of terminal symbols required to introduce a variable\n * statement (excluding its variable declaration list).\n * <p><code>'var '.length</code></p>\n * @const\n * @type {number}\n */\n N_VARIABLE_STATEMENT_AFFIXATION: 4,\n /**\n * The number of terminal symbols needed to enclose source elements\n * within a function call with no argument values to a function with an\n * empty parameter list.\n * <p><code>'(function(){}());'.length</code></p>\n * @const\n * @type {number}\n */\n N_CLOSURE: 17\n },\n /**\n * Categories of primary expressions from which primitive values that\n * could be consolidated are derivable.\n * @namespace\n * @enum {number}\n */\n EPrimaryExpressionCategories = {\n /**\n * Identifier names used as property accessors.\n * @type {number}\n */\n N_IDENTIFIER_NAMES: 0,\n /**\n * String literals.\n * @type {number}\n */\n N_STRING_LITERALS: 1,\n /**\n * Null and Boolean literals.\n * @type {number}\n */\n N_NULL_AND_BOOLEAN_LITERALS: 2\n },\n /**\n * Prefixes of primitive values that could be consolidated.\n * The String values of the prefixes must have same number of characters.\n * The prefixes must not be used in any properties defined in any version\n * of <a href=\n * \"http://www.ecma-international.org/publications/standards/Ecma-262.htm\"\n * >ECMA-262</a>.\n * @namespace\n * @enum {string}\n */\n EValuePrefixes = {\n /**\n * Identifies String values.\n * @type {string}\n */\n S_STRING: '#S',\n /**\n * Identifies null and Boolean values.\n * @type {string}\n */\n S_SYMBOLIC: '#O'\n },\n /**\n * Categories of source elements in terms of their appropriateness of\n * having their primitive values consolidated.\n * @namespace\n * @enum {number}\n */\n ESourceElementCategories = {\n /**\n * Identifies a source element that includes the <a href=\n * \"http://es5.github.com/#x12.10\">{@code with}</a> statement.\n * @type {number}\n */\n N_WITH: 0,\n /**\n * Identifies a source element that includes the <a href=\n * \"http://es5.github.com/#x15.1.2.1\">{@code eval}</a> identifier name.\n * @type {number}\n */\n N_EVAL: 1,\n /**\n * Identifies a source element that must be excluded from the process\n * unless its whole scope is examined.\n * @type {number}\n */\n N_EXCLUDABLE: 2,\n /**\n * Identifies source elements not posing any problems.\n * @type {number}\n */\n N_OTHER: 3\n },\n /**\n * The list of literals (other than the String ones) whose primitive\n * values can be consolidated.\n * @const\n * @type {!Array.<string>}\n */\n A_OTHER_SUBSTITUTABLE_LITERALS = [\n 'null', // The null literal.\n 'false', // The Boolean literal {@code false}.\n 'true' // The Boolean literal {@code true}.\n ];\n\n (/**\n * Consolidates all worthwhile primitive values in a syntactic code unit.\n * @param {!TSyntacticCodeUnit} oSyntacticCodeUnit An array-like object\n * representing the branch of the abstract syntax tree representing the\n * syntactic code unit along with its scope.\n * @see TPrimitiveValue#nSaving\n */\n function fExamineSyntacticCodeUnit(oSyntacticCodeUnit) {\n var _,\n /**\n * Indicates whether the syntactic code unit represents global code.\n * @type {boolean}\n */\n bIsGlobal = 'toplevel' === oSyntacticCodeUnit[0],\n /**\n * Indicates whether the whole scope is being examined.\n * @type {boolean}\n */\n bIsWhollyExaminable = !bIsGlobal,\n /**\n * An array-like object representing source elements that constitute a\n * syntactic code unit.\n * @type {!TSyntacticCodeUnit}\n */\n oSourceElements,\n /**\n * A record consisting of data about the source element that is\n * currently being examined.\n * @type {!TSourceElementsData}\n */\n oSourceElementData,\n /**\n * The scope of the syntactic code unit.\n * @type {!TScope}\n */\n oScope,\n /**\n * An instance of an object that allows the traversal of an <abbr\n * title=\"abstract syntax tree\">AST</abbr>.\n * @type {!TWalker}\n */\n oWalker,\n /**\n * An object encompassing collections of functions used during the\n * traversal of an <abbr title=\"abstract syntax tree\">AST</abbr>.\n * @namespace\n * @type {!Object.<string, !Object.<string, function(...[*])>>}\n */\n oWalkers = {\n /**\n * A collection of functions used during the surveyance of source\n * elements.\n * @namespace\n * @type {!Object.<string, function(...[*])>}\n */\n oSurveySourceElement: {\n /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.\n /**\n * Classifies the source element as excludable if it does not\n * contain a {@code with} statement or the {@code eval} identifier\n * name. Adds the identifier of the function and its formal\n * parameters to the list of identifier names found.\n * @param {string} sIdentifier The identifier of the function.\n * @param {!Array.<string>} aFormalParameterList Formal parameters.\n * @param {!TSyntacticCodeUnit} oFunctionBody Function code.\n */\n 'defun': function(\n sIdentifier,\n aFormalParameterList,\n oFunctionBody) {\n fClassifyAsExcludable();\n fAddIdentifier(sIdentifier);\n aFormalParameterList.forEach(fAddIdentifier);\n },\n /**\n * Increments the count of the number of occurrences of the String\n * value that is equivalent to the sequence of terminal symbols\n * that constitute the encountered identifier name.\n * @param {!TSyntacticCodeUnit} oExpression The nonterminal\n * MemberExpression.\n * @param {string} sIdentifierName The identifier name used as the\n * property accessor.\n * @return {!Array} The encountered branch of an <abbr title=\n * \"abstract syntax tree\">AST</abbr> with its nonterminal\n * MemberExpression traversed.\n */\n 'dot': function(oExpression, sIdentifierName) {\n fCountPrimaryExpression(\n EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,\n EValuePrefixes.S_STRING + sIdentifierName);\n return ['dot', oWalker.walk(oExpression), sIdentifierName];\n },\n /**\n * Adds the optional identifier of the function and its formal\n * parameters to the list of identifier names found.\n * @param {?string} sIdentifier The optional identifier of the\n * function.\n * @param {!Array.<string>} aFormalParameterList Formal parameters.\n * @param {!TSyntacticCodeUnit} oFunctionBody Function code.\n */\n 'function': function(\n sIdentifier,\n aFormalParameterList,\n oFunctionBody) {\n if ('string' === typeof sIdentifier) {\n fAddIdentifier(sIdentifier);\n }\n aFormalParameterList.forEach(fAddIdentifier);\n },\n /**\n * Either increments the count of the number of occurrences of the\n * encountered null or Boolean value or classifies a source element\n * as containing the {@code eval} identifier name.\n * @param {string} sIdentifier The identifier encountered.\n */\n 'name': function(sIdentifier) {\n if (-1 !== A_OTHER_SUBSTITUTABLE_LITERALS.indexOf(sIdentifier)) {\n fCountPrimaryExpression(\n EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS,\n EValuePrefixes.S_SYMBOLIC + sIdentifier);\n } else {\n if ('eval' === sIdentifier) {\n oSourceElementData.nCategory =\n ESourceElementCategories.N_EVAL;\n }\n fAddIdentifier(sIdentifier);\n }\n },\n /**\n * Classifies the source element as excludable if it does not\n * contain a {@code with} statement or the {@code eval} identifier\n * name.\n * @param {TSyntacticCodeUnit} oExpression The expression whose\n * value is to be returned.\n */\n 'return': function(oExpression) {\n fClassifyAsExcludable();\n },\n /**\n * Increments the count of the number of occurrences of the\n * encountered String value.\n * @param {string} sStringValue The String value of the string\n * literal encountered.\n */\n 'string': function(sStringValue) {\n if (sStringValue.length > 0) {\n fCountPrimaryExpression(\n EPrimaryExpressionCategories.N_STRING_LITERALS,\n EValuePrefixes.S_STRING + sStringValue);\n }\n },\n /**\n * Adds the identifier reserved for an exception to the list of\n * identifier names found.\n * @param {!TSyntacticCodeUnit} oTry A block of code in which an\n * exception can occur.\n * @param {Array} aCatch The identifier reserved for an exception\n * and a block of code to handle the exception.\n * @param {TSyntacticCodeUnit} oFinally An optional block of code\n * to be evaluated regardless of whether an exception occurs.\n */\n 'try': function(oTry, aCatch, oFinally) {\n if (Array.isArray(aCatch)) {\n fAddIdentifier(aCatch[0]);\n }\n },\n /**\n * Classifies the source element as excludable if it does not\n * contain a {@code with} statement or the {@code eval} identifier\n * name. Adds the identifier of each declared variable to the list\n * of identifier names found.\n * @param {!Array.<!Array>} aVariableDeclarationList Variable\n * declarations.\n */\n 'var': function(aVariableDeclarationList) {\n fClassifyAsExcludable();\n aVariableDeclarationList.forEach(fAddVariable);\n },\n /**\n * Classifies a source element as containing the {@code with}\n * statement.\n * @param {!TSyntacticCodeUnit} oExpression An expression whose\n * value is to be converted to a value of type Object and\n * become the binding object of a new object environment\n * record of a new lexical environment in which the statement\n * is to be executed.\n * @param {!TSyntacticCodeUnit} oStatement The statement to be\n * executed in the augmented lexical environment.\n * @return {!Array} An empty array to stop the traversal.\n */\n 'with': function(oExpression, oStatement) {\n oSourceElementData.nCategory = ESourceElementCategories.N_WITH;\n return [];\n }\n /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.\n },\n /**\n * A collection of functions used while looking for nested functions.\n * @namespace\n * @type {!Object.<string, function(...[*])>}\n */\n oExamineFunctions: {\n /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.\n /**\n * Orders an examination of a nested function declaration.\n * @this {!TSyntacticCodeUnit} An array-like object representing\n * the branch of an <abbr title=\"abstract syntax tree\"\n * >AST</abbr> representing the syntactic code unit along with\n * its scope.\n * @return {!Array} An empty array to stop the traversal.\n */\n 'defun': function() {\n fExamineSyntacticCodeUnit(this);\n return [];\n },\n /**\n * Orders an examination of a nested function expression.\n * @this {!TSyntacticCodeUnit} An array-like object representing\n * the branch of an <abbr title=\"abstract syntax tree\"\n * >AST</abbr> representing the syntactic code unit along with\n * its scope.\n * @return {!Array} An empty array to stop the traversal.\n */\n 'function': function() {\n fExamineSyntacticCodeUnit(this);\n return [];\n }\n /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.\n }\n },\n /**\n * Records containing data about source elements.\n * @type {Array.<TSourceElementsData>}\n */\n aSourceElementsData = [],\n /**\n * The index (in the source text order) of the source element\n * immediately following a <a href=\"http://es5.github.com/#x14.1\"\n * >Directive Prologue</a>.\n * @type {number}\n */\n nAfterDirectivePrologue = 0,\n /**\n * The index (in the source text order) of the source element that is\n * currently being considered.\n * @type {number}\n */\n nPosition,\n /**\n * The index (in the source text order) of the source element that is\n * the last element of the range of source elements that is currently\n * being considered.\n * @type {(undefined|number)}\n */\n nTo,\n /**\n * Initiates the traversal of a source element.\n * @param {!TWalker} oWalker An instance of an object that allows the\n * traversal of an abstract syntax tree.\n * @param {!TSyntacticCodeUnit} oSourceElement A source element from\n * which the traversal should commence.\n * @return {function(): !TSyntacticCodeUnit} A function that is able to\n * initiate the traversal from a given source element.\n */\n cContext = function(oWalker, oSourceElement) {\n /**\n * @return {!TSyntacticCodeUnit} A function that is able to\n * initiate the traversal from a given source element.\n */\n var fLambda = function() {\n return oWalker.walk(oSourceElement);\n };\n\n return fLambda;\n },\n /**\n * Classifies the source element as excludable if it does not\n * contain a {@code with} statement or the {@code eval} identifier\n * name.\n */\n fClassifyAsExcludable = function() {\n if (oSourceElementData.nCategory ===\n ESourceElementCategories.N_OTHER) {\n oSourceElementData.nCategory =\n ESourceElementCategories.N_EXCLUDABLE;\n }\n },\n /**\n * Adds an identifier to the list of identifier names found.\n * @param {string} sIdentifier The identifier to be added.\n */\n fAddIdentifier = function(sIdentifier) {\n if (-1 === oSourceElementData.aIdentifiers.indexOf(sIdentifier)) {\n oSourceElementData.aIdentifiers.push(sIdentifier);\n }\n },\n /**\n * Adds the identifier of a variable to the list of identifier names\n * found.\n * @param {!Array} aVariableDeclaration A variable declaration.\n */\n fAddVariable = function(aVariableDeclaration) {\n fAddIdentifier(/** @type {string} */ aVariableDeclaration[0]);\n },\n /**\n * Increments the count of the number of occurrences of the prefixed\n * String representation attributed to the primary expression.\n * @param {number} nCategory The category of the primary expression.\n * @param {string} sName The prefixed String representation attributed\n * to the primary expression.\n */\n fCountPrimaryExpression = function(nCategory, sName) {\n if (!oSourceElementData.aCount[nCategory].hasOwnProperty(sName)) {\n oSourceElementData.aCount[nCategory][sName] = 0;\n if (-1 === oSourceElementData.aPrimitiveValues.indexOf(sName)) {\n oSourceElementData.aPrimitiveValues.push(sName);\n }\n }\n oSourceElementData.aCount[nCategory][sName] += 1;\n },\n /**\n * Consolidates all worthwhile primitive values in a range of source\n * elements.\n * @param {number} nFrom The index (in the source text order) of the\n * source element that is the first element of the range.\n * @param {number} nTo The index (in the source text order) of the\n * source element that is the last element of the range.\n * @param {boolean} bEnclose Indicates whether the range should be\n * enclosed within a function call with no argument values to a\n * function with an empty parameter list if any primitive values\n * are consolidated.\n * @see TPrimitiveValue#nSaving\n */\n fExamineSourceElements = function(nFrom, nTo, bEnclose) {\n var _,\n /**\n * The index of the last mangled name.\n * @type {number}\n */\n nIndex = oScope.cname,\n /**\n * The index of the source element that is currently being\n * considered.\n * @type {number}\n */\n nPosition,\n /**\n * A collection of functions used during the consolidation of\n * primitive values and identifier names used as property\n * accessors.\n * @namespace\n * @type {!Object.<string, function(...[*])>}\n */\n oWalkersTransformers = {\n /**\n * If the String value that is equivalent to the sequence of\n * terminal symbols that constitute the encountered identifier\n * name is worthwhile, a syntactic conversion from the dot\n * notation to the bracket notation ensues with that sequence\n * being substituted by an identifier name to which the value\n * is assigned.\n * Applies to property accessors that use the dot notation.\n * @param {!TSyntacticCodeUnit} oExpression The nonterminal\n * MemberExpression.\n * @param {string} sIdentifierName The identifier name used as\n * the property accessor.\n * @return {!Array} A syntactic code unit that is equivalent to\n * the one encountered.\n * @see TPrimitiveValue#nSaving\n */\n 'dot': function(oExpression, sIdentifierName) {\n /**\n * The prefixed String value that is equivalent to the\n * sequence of terminal symbols that constitute the\n * encountered identifier name.\n * @type {string}\n */\n var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;\n\n return oSolutionBest.oPrimitiveValues.hasOwnProperty(\n sPrefixed) &&\n oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?\n ['sub',\n oWalker.walk(oExpression),\n ['name',\n oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :\n ['dot', oWalker.walk(oExpression), sIdentifierName];\n },\n /**\n * If the encountered identifier is a null or Boolean literal\n * and its value is worthwhile, the identifier is substituted\n * by an identifier name to which that value is assigned.\n * Applies to identifier names.\n * @param {string} sIdentifier The identifier encountered.\n * @return {!Array} A syntactic code unit that is equivalent to\n * the one encountered.\n * @see TPrimitiveValue#nSaving\n */\n 'name': function(sIdentifier) {\n /**\n * The prefixed representation String of the identifier.\n * @type {string}\n */\n var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;\n\n return [\n 'name',\n oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&\n oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?\n oSolutionBest.oPrimitiveValues[sPrefixed].sName :\n sIdentifier\n ];\n },\n /**\n * If the encountered String value is worthwhile, it is\n * substituted by an identifier name to which that value is\n * assigned.\n * Applies to String values.\n * @param {string} sStringValue The String value of the string\n * literal encountered.\n * @return {!Array} A syntactic code unit that is equivalent to\n * the one encountered.\n * @see TPrimitiveValue#nSaving\n */\n 'string': function(sStringValue) {\n /**\n * The prefixed representation String of the primitive value\n * of the literal.\n * @type {string}\n */\n var sPrefixed =\n EValuePrefixes.S_STRING + sStringValue;\n\n return oSolutionBest.oPrimitiveValues.hasOwnProperty(\n sPrefixed) &&\n oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?\n ['name',\n oSolutionBest.oPrimitiveValues[sPrefixed].sName] :\n ['string', sStringValue];\n }\n },\n /**\n * Such data on what to consolidate within the range of source\n * elements that is currently being considered that lead to the\n * greatest known reduction of the number of the terminal symbols\n * in comparison to the original source text.\n * @type {!TSolution}\n */\n oSolutionBest = new TSolution(),\n /**\n * Data representing an ongoing attempt to find a better\n * reduction of the number of the terminal symbols in comparison\n * to the original source text than the best one that is\n * currently known.\n * @type {!TSolution}\n * @see oSolutionBest\n */\n oSolutionCandidate = new TSolution(),\n /**\n * A record consisting of data about the range of source elements\n * that is currently being examined.\n * @type {!TSourceElementsData}\n */\n oSourceElementsData = new TSourceElementsData(),\n /**\n * Variable declarations for each primitive value that is to be\n * consolidated within the elements.\n * @type {!Array.<!Array>}\n */\n aVariableDeclarations = [],\n /**\n * Augments a list with a prefixed representation String.\n * @param {!Array.<string>} aList A list that is to be augmented.\n * @return {function(string)} A function that augments a list\n * with a prefixed representation String.\n */\n cAugmentList = function(aList) {\n /**\n * @param {string} sPrefixed Prefixed representation String of\n * a primitive value that could be consolidated within the\n * elements.\n */\n var fLambda = function(sPrefixed) {\n if (-1 === aList.indexOf(sPrefixed)) {\n aList.push(sPrefixed);\n }\n };\n\n return fLambda;\n },\n /**\n * Adds the number of occurrences of a primitive value of a given\n * category that could be consolidated in the source element with\n * a given index to the count of occurrences of that primitive\n * value within the range of source elements that is currently\n * being considered.\n * @param {number} nPosition The index (in the source text order)\n * of a source element.\n * @param {number} nCategory The category of the primary\n * expression from which the primitive value is derived.\n * @return {function(string)} A function that performs the\n * addition.\n * @see cAddOccurrencesInCategory\n */\n cAddOccurrences = function(nPosition, nCategory) {\n /**\n * @param {string} sPrefixed The prefixed representation String\n * of a primitive value.\n */\n var fLambda = function(sPrefixed) {\n if (!oSourceElementsData.aCount[nCategory].hasOwnProperty(\n sPrefixed)) {\n oSourceElementsData.aCount[nCategory][sPrefixed] = 0;\n }\n oSourceElementsData.aCount[nCategory][sPrefixed] +=\n aSourceElementsData[nPosition].aCount[nCategory][\n sPrefixed];\n };\n\n return fLambda;\n },\n /**\n * Adds the number of occurrences of each primitive value of a\n * given category that could be consolidated in the source\n * element with a given index to the count of occurrences of that\n * primitive values within the range of source elements that is\n * currently being considered.\n * @param {number} nPosition The index (in the source text order)\n * of a source element.\n * @return {function(number)} A function that performs the\n * addition.\n * @see fAddOccurrences\n */\n cAddOccurrencesInCategory = function(nPosition) {\n /**\n * @param {number} nCategory The category of the primary\n * expression from which the primitive value is derived.\n */\n var fLambda = function(nCategory) {\n Object.keys(\n aSourceElementsData[nPosition].aCount[nCategory]\n ).forEach(cAddOccurrences(nPosition, nCategory));\n };\n\n return fLambda;\n },\n /**\n * Adds the number of occurrences of each primitive value that\n * could be consolidated in the source element with a given index\n * to the count of occurrences of that primitive values within\n * the range of source elements that is currently being\n * considered.\n * @param {number} nPosition The index (in the source text order)\n * of a source element.\n */\n fAddOccurrences = function(nPosition) {\n Object.keys(aSourceElementsData[nPosition].aCount).forEach(\n cAddOccurrencesInCategory(nPosition));\n },\n /**\n * Creates a variable declaration for a primitive value if that\n * primitive value is to be consolidated within the elements.\n * @param {string} sPrefixed Prefixed representation String of a\n * primitive value that could be consolidated within the\n * elements.\n * @see aVariableDeclarations\n */\n cAugmentVariableDeclarations = function(sPrefixed) {\n if (oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0) {\n aVariableDeclarations.push([\n oSolutionBest.oPrimitiveValues[sPrefixed].sName,\n [0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC) ?\n 'name' : 'string',\n sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length)]\n ]);\n }\n },\n /**\n * Sorts primitive values with regard to the difference in the\n * number of terminal symbols between the original source text\n * and the one with those primitive values consolidated.\n * @param {string} sPrefixed0 The prefixed representation String\n * of the first of the two primitive values that are being\n * compared.\n * @param {string} sPrefixed1 The prefixed representation String\n * of the second of the two primitive values that are being\n * compared.\n * @return {number}\n * <dl>\n * <dt>-1</dt>\n * <dd>if the first primitive value must be placed before\n * the other one,</dd>\n * <dt>0</dt>\n * <dd>if the first primitive value may be placed before\n * the other one,</dd>\n * <dt>1</dt>\n * <dd>if the first primitive value must not be placed\n * before the other one.</dd>\n * </dl>\n * @see TSolution.oPrimitiveValues\n */\n cSortPrimitiveValues = function(sPrefixed0, sPrefixed1) {\n /**\n * The difference between:\n * <ol>\n * <li>the difference in the number of terminal symbols\n * between the original source text and the one with the\n * first primitive value consolidated, and</li>\n * <li>the difference in the number of terminal symbols\n * between the original source text and the one with the\n * second primitive value consolidated.</li>\n * </ol>\n * @type {number}\n */\n var nDifference =\n oSolutionCandidate.oPrimitiveValues[sPrefixed0].nSaving -\n oSolutionCandidate.oPrimitiveValues[sPrefixed1].nSaving;\n\n return nDifference > 0 ? -1 : nDifference < 0 ? 1 : 0;\n },\n /**\n * Assigns an identifier name to a primitive value and calculates\n * whether instances of that primitive value are worth\n * consolidating.\n * @param {string} sPrefixed The prefixed representation String\n * of a primitive value that is being evaluated.\n */\n fEvaluatePrimitiveValue = function(sPrefixed) {\n var _,\n /**\n * The index of the last mangled name.\n * @type {number}\n */\n nIndex,\n /**\n * The representation String of the primitive value that is\n * being evaluated.\n * @type {string}\n */\n sName =\n sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length),\n /**\n * The number of source characters taken up by the\n * representation String of the primitive value that is\n * being evaluated.\n * @type {number}\n */\n nLengthOriginal = sName.length,\n /**\n * The number of source characters taken up by the\n * identifier name that could substitute the primitive\n * value that is being evaluated.\n * substituted.\n * @type {number}\n */\n nLengthSubstitution,\n /**\n * The number of source characters taken up by by the\n * representation String of the primitive value that is\n * being evaluated when it is represented by a string\n * literal.\n * @type {number}\n */\n nLengthString = oProcessor.make_string(sName).length;\n\n oSolutionCandidate.oPrimitiveValues[sPrefixed] =\n new TPrimitiveValue();\n do { // Find an identifier unused in this or any nested scope.\n nIndex = oScope.cname;\n oSolutionCandidate.oPrimitiveValues[sPrefixed].sName =\n oScope.next_mangled();\n } while (-1 !== oSourceElementsData.aIdentifiers.indexOf(\n oSolutionCandidate.oPrimitiveValues[sPrefixed].sName));\n nLengthSubstitution = oSolutionCandidate.oPrimitiveValues[\n sPrefixed].sName.length;\n if (0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC)) {\n // foo:null, or foo:null;\n oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=\n nLengthSubstitution + nLengthOriginal +\n oWeights.N_VARIABLE_DECLARATION;\n // null vs foo\n oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=\n oSourceElementsData.aCount[\n EPrimaryExpressionCategories.\n N_NULL_AND_BOOLEAN_LITERALS][sPrefixed] *\n (nLengthOriginal - nLengthSubstitution);\n } else {\n // foo:'fromCharCode';\n oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=\n nLengthSubstitution + nLengthString +\n oWeights.N_VARIABLE_DECLARATION;\n // .fromCharCode vs [foo]\n if (oSourceElementsData.aCount[\n EPrimaryExpressionCategories.N_IDENTIFIER_NAMES\n ].hasOwnProperty(sPrefixed)) {\n oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=\n oSourceElementsData.aCount[\n EPrimaryExpressionCategories.N_IDENTIFIER_NAMES\n ][sPrefixed] *\n (nLengthOriginal - nLengthSubstitution -\n oWeights.N_PROPERTY_ACCESSOR);\n }\n // 'fromCharCode' vs foo\n if (oSourceElementsData.aCount[\n EPrimaryExpressionCategories.N_STRING_LITERALS\n ].hasOwnProperty(sPrefixed)) {\n oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=\n oSourceElementsData.aCount[\n EPrimaryExpressionCategories.N_STRING_LITERALS\n ][sPrefixed] *\n (nLengthString - nLengthSubstitution);\n }\n }\n if (oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving >\n 0) {\n oSolutionCandidate.nSavings +=\n oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving;\n } else {\n oScope.cname = nIndex; // Free the identifier name.\n }\n },\n /**\n * Adds a variable declaration to an existing variable statement.\n * @param {!Array} aVariableDeclaration A variable declaration\n * with an initialiser.\n */\n cAddVariableDeclaration = function(aVariableDeclaration) {\n (/** @type {!Array} */ oSourceElements[nFrom][1]).unshift(\n aVariableDeclaration);\n };\n\n if (nFrom > nTo) {\n return;\n }\n // If the range is a closure, reuse the closure.\n if (nFrom === nTo &&\n 'stat' === oSourceElements[nFrom][0] &&\n 'call' === oSourceElements[nFrom][1][0] &&\n 'function' === oSourceElements[nFrom][1][1][0]) {\n fExamineSyntacticCodeUnit(oSourceElements[nFrom][1][1]);\n return;\n }\n // Create a list of all derived primitive values within the range.\n for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {\n aSourceElementsData[nPosition].aPrimitiveValues.forEach(\n cAugmentList(oSourceElementsData.aPrimitiveValues));\n }\n if (0 === oSourceElementsData.aPrimitiveValues.length) {\n return;\n }\n for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {\n // Add the number of occurrences to the total count.\n fAddOccurrences(nPosition);\n // Add identifiers of this or any nested scope to the list.\n aSourceElementsData[nPosition].aIdentifiers.forEach(\n cAugmentList(oSourceElementsData.aIdentifiers));\n }\n // Distribute identifier names among derived primitive values.\n do { // If there was any progress, find a better distribution.\n oSolutionBest = oSolutionCandidate;\n if (Object.keys(oSolutionCandidate.oPrimitiveValues).length > 0) {\n // Sort primitive values descending by their worthwhileness.\n oSourceElementsData.aPrimitiveValues.sort(cSortPrimitiveValues);\n }\n oSolutionCandidate = new TSolution();\n oSourceElementsData.aPrimitiveValues.forEach(\n fEvaluatePrimitiveValue);\n oScope.cname = nIndex;\n } while (oSolutionCandidate.nSavings > oSolutionBest.nSavings);\n // Take the necessity of adding a variable statement into account.\n if ('var' !== oSourceElements[nFrom][0]) {\n oSolutionBest.nSavings -= oWeights.N_VARIABLE_STATEMENT_AFFIXATION;\n }\n if (bEnclose) {\n // Take the necessity of forming a closure into account.\n oSolutionBest.nSavings -= oWeights.N_CLOSURE;\n }\n if (oSolutionBest.nSavings > 0) {\n // Create variable declarations suitable for UglifyJS.\n Object.keys(oSolutionBest.oPrimitiveValues).forEach(\n cAugmentVariableDeclarations);\n // Rewrite expressions that contain worthwhile primitive values.\n for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {\n oWalker = oProcessor.ast_walker();\n oSourceElements[nPosition] =\n oWalker.with_walkers(\n oWalkersTransformers,\n cContext(oWalker, oSourceElements[nPosition]));\n }\n if ('var' === oSourceElements[nFrom][0]) { // Reuse the statement.\n (/** @type {!Array.<!Array>} */ aVariableDeclarations.reverse(\n )).forEach(cAddVariableDeclaration);\n } else { // Add a variable statement.\n Array.prototype.splice.call(\n oSourceElements,\n nFrom,\n 0,\n ['var', aVariableDeclarations]);\n nTo += 1;\n }\n if (bEnclose) {\n // Add a closure.\n Array.prototype.splice.call(\n oSourceElements,\n nFrom,\n 0,\n ['stat', ['call', ['function', null, [], []], []]]);\n // Copy source elements into the closure.\n for (nPosition = nTo + 1; nPosition > nFrom; nPosition -= 1) {\n Array.prototype.unshift.call(\n oSourceElements[nFrom][1][1][3],\n oSourceElements[nPosition]);\n }\n // Remove source elements outside the closure.\n Array.prototype.splice.call(\n oSourceElements,\n nFrom + 1,\n nTo - nFrom + 1);\n }\n }\n if (bEnclose) {\n // Restore the availability of identifier names.\n oScope.cname = nIndex;\n }\n };\n\n oSourceElements = (/** @type {!TSyntacticCodeUnit} */\n oSyntacticCodeUnit[bIsGlobal ? 1 : 3]);\n if (0 === oSourceElements.length) {\n return;\n }\n oScope = bIsGlobal ? oSyntacticCodeUnit.scope : oSourceElements.scope;\n // Skip a Directive Prologue.\n while (nAfterDirectivePrologue < oSourceElements.length &&\n 'directive' === oSourceElements[nAfterDirectivePrologue][0]) {\n nAfterDirectivePrologue += 1;\n aSourceElementsData.push(null);\n }\n if (oSourceElements.length === nAfterDirectivePrologue) {\n return;\n }\n for (nPosition = nAfterDirectivePrologue;\n nPosition < oSourceElements.length;\n nPosition += 1) {\n oSourceElementData = new TSourceElementsData();\n oWalker = oProcessor.ast_walker();\n // Classify a source element.\n // Find its derived primitive values and count their occurrences.\n // Find all identifiers used (including nested scopes).\n oWalker.with_walkers(\n oWalkers.oSurveySourceElement,\n cContext(oWalker, oSourceElements[nPosition]));\n // Establish whether the scope is still wholly examinable.\n bIsWhollyExaminable = bIsWhollyExaminable &&\n ESourceElementCategories.N_WITH !== oSourceElementData.nCategory &&\n ESourceElementCategories.N_EVAL !== oSourceElementData.nCategory;\n aSourceElementsData.push(oSourceElementData);\n }\n if (bIsWhollyExaminable) { // Examine the whole scope.\n fExamineSourceElements(\n nAfterDirectivePrologue,\n oSourceElements.length - 1,\n false);\n } else { // Examine unexcluded ranges of source elements.\n for (nPosition = oSourceElements.length - 1;\n nPosition >= nAfterDirectivePrologue;\n nPosition -= 1) {\n oSourceElementData = (/** @type {!TSourceElementsData} */\n aSourceElementsData[nPosition]);\n if (ESourceElementCategories.N_OTHER ===\n oSourceElementData.nCategory) {\n if ('undefined' === typeof nTo) {\n nTo = nPosition; // Indicate the end of a range.\n }\n // Examine the range if it immediately follows a Directive Prologue.\n if (nPosition === nAfterDirectivePrologue) {\n fExamineSourceElements(nPosition, nTo, true);\n }\n } else {\n if ('undefined' !== typeof nTo) {\n // Examine the range that immediately follows this source element.\n fExamineSourceElements(nPosition + 1, nTo, true);\n nTo = void 0; // Obliterate the range.\n }\n // Examine nested functions.\n oWalker = oProcessor.ast_walker();\n oWalker.with_walkers(\n oWalkers.oExamineFunctions,\n cContext(oWalker, oSourceElements[nPosition]));\n }\n }\n }\n }(oAbstractSyntaxTree = oProcessor.ast_add_scope(oAbstractSyntaxTree)));\n return oAbstractSyntaxTree;\n};\n/*jshint sub:false */\n\n/* Local Variables: */\n/* mode: js */\n/* coding: utf-8 */\n/* indent-tabs-mode: nil */\n/* tab-width: 2 */\n/* End: */\n/* vim: set ft=javascript fenc=utf-8 et ts=2 sts=2 sw=2: */\n/* :mode=javascript:noTabs=true:tabSize=2:indentSize=2:deepIndent=true: */\n});\ndefine('uglifyjs/parse-js', [\"exports\"], function(exports) {\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n\n This version is suitable for Node.js. With minimal changes (the\n exports stuff) it should work on any JS platform.\n\n This file contains the tokenizer/parser. It is a port to JavaScript\n of parse-js [1], a JavaScript parser library written in Common Lisp\n by Marijn Haverbeke. Thank you Marijn!\n\n [1] http://marijn.haverbeke.nl/parse-js/\n\n Exported functions:\n\n - tokenizer(code) -- returns a function. Call the returned\n function to fetch the next token.\n\n - parse(code) -- returns an AST of the given JavaScript code.\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2010 (c) Mihai Bazon <[email protected]>\n Based on parse-js (http://marijn.haverbeke.nl/parse-js/).\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n/* -----[ Tokenizer (constants) ]----- */\n\nvar KEYWORDS = array_to_hash([\n \"break\",\n \"case\",\n \"catch\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"in\",\n \"instanceof\",\n \"new\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"typeof\",\n \"var\",\n \"void\",\n \"while\",\n \"with\"\n]);\n\nvar RESERVED_WORDS = array_to_hash([\n \"abstract\",\n \"boolean\",\n \"byte\",\n \"char\",\n \"class\",\n \"double\",\n \"enum\",\n \"export\",\n \"extends\",\n \"final\",\n \"float\",\n \"goto\",\n \"implements\",\n \"import\",\n \"int\",\n \"interface\",\n \"long\",\n \"native\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"short\",\n \"static\",\n \"super\",\n \"synchronized\",\n \"throws\",\n \"transient\",\n \"volatile\"\n]);\n\nvar KEYWORDS_BEFORE_EXPRESSION = array_to_hash([\n \"return\",\n \"new\",\n \"delete\",\n \"throw\",\n \"else\",\n \"case\"\n]);\n\nvar KEYWORDS_ATOM = array_to_hash([\n \"false\",\n \"null\",\n \"true\",\n \"undefined\"\n]);\n\nvar OPERATOR_CHARS = array_to_hash(characters(\"+-*&%=<>!?|~^\"));\n\nvar RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;\nvar RE_OCT_NUMBER = /^0[0-7]+$/;\nvar RE_DEC_NUMBER = /^\\d*\\.?\\d*(?:e[+-]?\\d*(?:\\d\\.?|\\.?\\d)\\d*)?$/i;\n\nvar OPERATORS = array_to_hash([\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"new\",\n \"void\",\n \"delete\",\n \"++\",\n \"--\",\n \"+\",\n \"-\",\n \"!\",\n \"~\",\n \"&\",\n \"|\",\n \"^\",\n \"*\",\n \"/\",\n \"%\",\n \">>\",\n \"<<\",\n \">>>\",\n \"<\",\n \">\",\n \"<=\",\n \">=\",\n \"==\",\n \"===\",\n \"!=\",\n \"!==\",\n \"?\",\n \"=\",\n \"+=\",\n \"-=\",\n \"/=\",\n \"*=\",\n \"%=\",\n \">>=\",\n \"<<=\",\n \">>>=\",\n \"|=\",\n \"^=\",\n \"&=\",\n \"&&\",\n \"||\"\n]);\n\nvar WHITESPACE_CHARS = array_to_hash(characters(\" \\u00a0\\n\\r\\t\\f\\u000b\\u200b\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\uFEFF\"));\n\nvar PUNC_BEFORE_EXPRESSION = array_to_hash(characters(\"[{(,.;:\"));\n\nvar PUNC_CHARS = array_to_hash(characters(\"[]{}(),;:\"));\n\nvar REGEXP_MODIFIERS = array_to_hash(characters(\"gmsiy\"));\n\n/* -----[ Tokenizer ]----- */\n\nvar UNICODE = { // Unicode 6.1\n letter: new RegExp(\"[\\\\u0041-\\\\u005A\\\\u0061-\\\\u007A\\\\u00AA\\\\u00B5\\\\u00BA\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02C1\\\\u02C6-\\\\u02D1\\\\u02E0-\\\\u02E4\\\\u02EC\\\\u02EE\\\\u0370-\\\\u0374\\\\u0376\\\\u0377\\\\u037A-\\\\u037D\\\\u0386\\\\u0388-\\\\u038A\\\\u038C\\\\u038E-\\\\u03A1\\\\u03A3-\\\\u03F5\\\\u03F7-\\\\u0481\\\\u048A-\\\\u0527\\\\u0531-\\\\u0556\\\\u0559\\\\u0561-\\\\u0587\\\\u05D0-\\\\u05EA\\\\u05F0-\\\\u05F2\\\\u0620-\\\\u064A\\\\u066E\\\\u066F\\\\u0671-\\\\u06D3\\\\u06D5\\\\u06E5\\\\u06E6\\\\u06EE\\\\u06EF\\\\u06FA-\\\\u06FC\\\\u06FF\\\\u0710\\\\u0712-\\\\u072F\\\\u074D-\\\\u07A5\\\\u07B1\\\\u07CA-\\\\u07EA\\\\u07F4\\\\u07F5\\\\u07FA\\\\u0800-\\\\u0815\\\\u081A\\\\u0824\\\\u0828\\\\u0840-\\\\u0858\\\\u08A0\\\\u08A2-\\\\u08AC\\\\u0904-\\\\u0939\\\\u093D\\\\u0950\\\\u0958-\\\\u0961\\\\u0971-\\\\u0977\\\\u0979-\\\\u097F\\\\u0985-\\\\u098C\\\\u098F\\\\u0990\\\\u0993-\\\\u09A8\\\\u09AA-\\\\u09B0\\\\u09B2\\\\u09B6-\\\\u09B9\\\\u09BD\\\\u09CE\\\\u09DC\\\\u09DD\\\\u09DF-\\\\u09E1\\\\u09F0\\\\u09F1\\\\u0A05-\\\\u0A0A\\\\u0A0F\\\\u0A10\\\\u0A13-\\\\u0A28\\\\u0A2A-\\\\u0A30\\\\u0A32\\\\u0A33\\\\u0A35\\\\u0A36\\\\u0A38\\\\u0A39\\\\u0A59-\\\\u0A5C\\\\u0A5E\\\\u0A72-\\\\u0A74\\\\u0A85-\\\\u0A8D\\\\u0A8F-\\\\u0A91\\\\u0A93-\\\\u0AA8\\\\u0AAA-\\\\u0AB0\\\\u0AB2\\\\u0AB3\\\\u0AB5-\\\\u0AB9\\\\u0ABD\\\\u0AD0\\\\u0AE0\\\\u0AE1\\\\u0B05-\\\\u0B0C\\\\u0B0F\\\\u0B10\\\\u0B13-\\\\u0B28\\\\u0B2A-\\\\u0B30\\\\u0B32\\\\u0B33\\\\u0B35-\\\\u0B39\\\\u0B3D\\\\u0B5C\\\\u0B5D\\\\u0B5F-\\\\u0B61\\\\u0B71\\\\u0B83\\\\u0B85-\\\\u0B8A\\\\u0B8E-\\\\u0B90\\\\u0B92-\\\\u0B95\\\\u0B99\\\\u0B9A\\\\u0B9C\\\\u0B9E\\\\u0B9F\\\\u0BA3\\\\u0BA4\\\\u0BA8-\\\\u0BAA\\\\u0BAE-\\\\u0BB9\\\\u0BD0\\\\u0C05-\\\\u0C0C\\\\u0C0E-\\\\u0C10\\\\u0C12-\\\\u0C28\\\\u0C2A-\\\\u0C33\\\\u0C35-\\\\u0C39\\\\u0C3D\\\\u0C58\\\\u0C59\\\\u0C60\\\\u0C61\\\\u0C85-\\\\u0C8C\\\\u0C8E-\\\\u0C90\\\\u0C92-\\\\u0CA8\\\\u0CAA-\\\\u0CB3\\\\u0CB5-\\\\u0CB9\\\\u0CBD\\\\u0CDE\\\\u0CE0\\\\u0CE1\\\\u0CF1\\\\u0CF2\\\\u0D05-\\\\u0D0C\\\\u0D0E-\\\\u0D10\\\\u0D12-\\\\u0D3A\\\\u0D3D\\\\u0D4E\\\\u0D60\\\\u0D61\\\\u0D7A-\\\\u0D7F\\\\u0D85-\\\\u0D96\\\\u0D9A-\\\\u0DB1\\\\u0DB3-\\\\u0DBB\\\\u0DBD\\\\u0DC0-\\\\u0DC6\\\\u0E01-\\\\u0E30\\\\u0E32\\\\u0E33\\\\u0E40-\\\\u0E46\\\\u0E81\\\\u0E82\\\\u0E84\\\\u0E87\\\\u0E88\\\\u0E8A\\\\u0E8D\\\\u0E94-\\\\u0E97\\\\u0E99-\\\\u0E9F\\\\u0EA1-\\\\u0EA3\\\\u0EA5\\\\u0EA7\\\\u0EAA\\\\u0EAB\\\\u0EAD-\\\\u0EB0\\\\u0EB2\\\\u0EB3\\\\u0EBD\\\\u0EC0-\\\\u0EC4\\\\u0EC6\\\\u0EDC-\\\\u0EDF\\\\u0F00\\\\u0F40-\\\\u0F47\\\\u0F49-\\\\u0F6C\\\\u0F88-\\\\u0F8C\\\\u1000-\\\\u102A\\\\u103F\\\\u1050-\\\\u1055\\\\u105A-\\\\u105D\\\\u1061\\\\u1065\\\\u1066\\\\u106E-\\\\u1070\\\\u1075-\\\\u1081\\\\u108E\\\\u10A0-\\\\u10C5\\\\u10C7\\\\u10CD\\\\u10D0-\\\\u10FA\\\\u10FC-\\\\u1248\\\\u124A-\\\\u124D\\\\u1250-\\\\u1256\\\\u1258\\\\u125A-\\\\u125D\\\\u1260-\\\\u1288\\\\u128A-\\\\u128D\\\\u1290-\\\\u12B0\\\\u12B2-\\\\u12B5\\\\u12B8-\\\\u12BE\\\\u12C0\\\\u12C2-\\\\u12C5\\\\u12C8-\\\\u12D6\\\\u12D8-\\\\u1310\\\\u1312-\\\\u1315\\\\u1318-\\\\u135A\\\\u1380-\\\\u138F\\\\u13A0-\\\\u13F4\\\\u1401-\\\\u166C\\\\u166F-\\\\u167F\\\\u1681-\\\\u169A\\\\u16A0-\\\\u16EA\\\\u16EE-\\\\u16F0\\\\u1700-\\\\u170C\\\\u170E-\\\\u1711\\\\u1720-\\\\u1731\\\\u1740-\\\\u1751\\\\u1760-\\\\u176C\\\\u176E-\\\\u1770\\\\u1780-\\\\u17B3\\\\u17D7\\\\u17DC\\\\u1820-\\\\u1877\\\\u1880-\\\\u18A8\\\\u18AA\\\\u18B0-\\\\u18F5\\\\u1900-\\\\u191C\\\\u1950-\\\\u196D\\\\u1970-\\\\u1974\\\\u1980-\\\\u19AB\\\\u19C1-\\\\u19C7\\\\u1A00-\\\\u1A16\\\\u1A20-\\\\u1A54\\\\u1AA7\\\\u1B05-\\\\u1B33\\\\u1B45-\\\\u1B4B\\\\u1B83-\\\\u1BA0\\\\u1BAE\\\\u1BAF\\\\u1BBA-\\\\u1BE5\\\\u1C00-\\\\u1C23\\\\u1C4D-\\\\u1C4F\\\\u1C5A-\\\\u1C7D\\\\u1CE9-\\\\u1CEC\\\\u1CEE-\\\\u1CF1\\\\u1CF5\\\\u1CF6\\\\u1D00-\\\\u1DBF\\\\u1E00-\\\\u1F15\\\\u1F18-\\\\u1F1D\\\\u1F20-\\\\u1F45\\\\u1F48-\\\\u1F4D\\\\u1F50-\\\\u1F57\\\\u1F59\\\\u1F5B\\\\u1F5D\\\\u1F5F-\\\\u1F7D\\\\u1F80-\\\\u1FB4\\\\u1FB6-\\\\u1FBC\\\\u1FBE\\\\u1FC2-\\\\u1FC4\\\\u1FC6-\\\\u1FCC\\\\u1FD0-\\\\u1FD3\\\\u1FD6-\\\\u1FDB\\\\u1FE0-\\\\u1FEC\\\\u1FF2-\\\\u1FF4\\\\u1FF6-\\\\u1FFC\\\\u2071\\\\u207F\\\\u2090-\\\\u209C\\\\u2102\\\\u2107\\\\u210A-\\\\u2113\\\\u2115\\\\u2119-\\\\u211D\\\\u2124\\\\u2126\\\\u2128\\\\u212A-\\\\u212D\\\\u212F-\\\\u2139\\\\u213C-\\\\u213F\\\\u2145-\\\\u2149\\\\u214E\\\\u2160-\\\\u2188\\\\u2C00-\\\\u2C2E\\\\u2C30-\\\\u2C5E\\\\u2C60-\\\\u2CE4\\\\u2CEB-\\\\u2CEE\\\\u2CF2\\\\u2CF3\\\\u2D00-\\\\u2D25\\\\u2D27\\\\u2D2D\\\\u2D30-\\\\u2D67\\\\u2D6F\\\\u2D80-\\\\u2D96\\\\u2DA0-\\\\u2DA6\\\\u2DA8-\\\\u2DAE\\\\u2DB0-\\\\u2DB6\\\\u2DB8-\\\\u2DBE\\\\u2DC0-\\\\u2DC6\\\\u2DC8-\\\\u2DCE\\\\u2DD0-\\\\u2DD6\\\\u2DD8-\\\\u2DDE\\\\u2E2F\\\\u3005-\\\\u3007\\\\u3021-\\\\u3029\\\\u3031-\\\\u3035\\\\u3038-\\\\u303C\\\\u3041-\\\\u3096\\\\u309D-\\\\u309F\\\\u30A1-\\\\u30FA\\\\u30FC-\\\\u30FF\\\\u3105-\\\\u312D\\\\u3131-\\\\u318E\\\\u31A0-\\\\u31BA\\\\u31F0-\\\\u31FF\\\\u3400-\\\\u4DB5\\\\u4E00-\\\\u9FCC\\\\uA000-\\\\uA48C\\\\uA4D0-\\\\uA4FD\\\\uA500-\\\\uA60C\\\\uA610-\\\\uA61F\\\\uA62A\\\\uA62B\\\\uA640-\\\\uA66E\\\\uA67F-\\\\uA697\\\\uA6A0-\\\\uA6EF\\\\uA717-\\\\uA71F\\\\uA722-\\\\uA788\\\\uA78B-\\\\uA78E\\\\uA790-\\\\uA793\\\\uA7A0-\\\\uA7AA\\\\uA7F8-\\\\uA801\\\\uA803-\\\\uA805\\\\uA807-\\\\uA80A\\\\uA80C-\\\\uA822\\\\uA840-\\\\uA873\\\\uA882-\\\\uA8B3\\\\uA8F2-\\\\uA8F7\\\\uA8FB\\\\uA90A-\\\\uA925\\\\uA930-\\\\uA946\\\\uA960-\\\\uA97C\\\\uA984-\\\\uA9B2\\\\uA9CF\\\\uAA00-\\\\uAA28\\\\uAA40-\\\\uAA42\\\\uAA44-\\\\uAA4B\\\\uAA60-\\\\uAA76\\\\uAA7A\\\\uAA80-\\\\uAAAF\\\\uAAB1\\\\uAAB5\\\\uAAB6\\\\uAAB9-\\\\uAABD\\\\uAAC0\\\\uAAC2\\\\uAADB-\\\\uAADD\\\\uAAE0-\\\\uAAEA\\\\uAAF2-\\\\uAAF4\\\\uAB01-\\\\uAB06\\\\uAB09-\\\\uAB0E\\\\uAB11-\\\\uAB16\\\\uAB20-\\\\uAB26\\\\uAB28-\\\\uAB2E\\\\uABC0-\\\\uABE2\\\\uAC00-\\\\uD7A3\\\\uD7B0-\\\\uD7C6\\\\uD7CB-\\\\uD7FB\\\\uF900-\\\\uFA6D\\\\uFA70-\\\\uFAD9\\\\uFB00-\\\\uFB06\\\\uFB13-\\\\uFB17\\\\uFB1D\\\\uFB1F-\\\\uFB28\\\\uFB2A-\\\\uFB36\\\\uFB38-\\\\uFB3C\\\\uFB3E\\\\uFB40\\\\uFB41\\\\uFB43\\\\uFB44\\\\uFB46-\\\\uFBB1\\\\uFBD3-\\\\uFD3D\\\\uFD50-\\\\uFD8F\\\\uFD92-\\\\uFDC7\\\\uFDF0-\\\\uFDFB\\\\uFE70-\\\\uFE74\\\\uFE76-\\\\uFEFC\\\\uFF21-\\\\uFF3A\\\\uFF41-\\\\uFF5A\\\\uFF66-\\\\uFFBE\\\\uFFC2-\\\\uFFC7\\\\uFFCA-\\\\uFFCF\\\\uFFD2-\\\\uFFD7\\\\uFFDA-\\\\uFFDC]\"),\n combining_mark: new RegExp(\"[\\\\u0300-\\\\u036F\\\\u0483-\\\\u0487\\\\u0591-\\\\u05BD\\\\u05BF\\\\u05C1\\\\u05C2\\\\u05C4\\\\u05C5\\\\u05C7\\\\u0610-\\\\u061A\\\\u064B-\\\\u065F\\\\u0670\\\\u06D6-\\\\u06DC\\\\u06DF-\\\\u06E4\\\\u06E7\\\\u06E8\\\\u06EA-\\\\u06ED\\\\u0711\\\\u0730-\\\\u074A\\\\u07A6-\\\\u07B0\\\\u07EB-\\\\u07F3\\\\u0816-\\\\u0819\\\\u081B-\\\\u0823\\\\u0825-\\\\u0827\\\\u0829-\\\\u082D\\\\u0859-\\\\u085B\\\\u08E4-\\\\u08FE\\\\u0900-\\\\u0903\\\\u093A-\\\\u093C\\\\u093E-\\\\u094F\\\\u0951-\\\\u0957\\\\u0962\\\\u0963\\\\u0981-\\\\u0983\\\\u09BC\\\\u09BE-\\\\u09C4\\\\u09C7\\\\u09C8\\\\u09CB-\\\\u09CD\\\\u09D7\\\\u09E2\\\\u09E3\\\\u0A01-\\\\u0A03\\\\u0A3C\\\\u0A3E-\\\\u0A42\\\\u0A47\\\\u0A48\\\\u0A4B-\\\\u0A4D\\\\u0A51\\\\u0A70\\\\u0A71\\\\u0A75\\\\u0A81-\\\\u0A83\\\\u0ABC\\\\u0ABE-\\\\u0AC5\\\\u0AC7-\\\\u0AC9\\\\u0ACB-\\\\u0ACD\\\\u0AE2\\\\u0AE3\\\\u0B01-\\\\u0B03\\\\u0B3C\\\\u0B3E-\\\\u0B44\\\\u0B47\\\\u0B48\\\\u0B4B-\\\\u0B4D\\\\u0B56\\\\u0B57\\\\u0B62\\\\u0B63\\\\u0B82\\\\u0BBE-\\\\u0BC2\\\\u0BC6-\\\\u0BC8\\\\u0BCA-\\\\u0BCD\\\\u0BD7\\\\u0C01-\\\\u0C03\\\\u0C3E-\\\\u0C44\\\\u0C46-\\\\u0C48\\\\u0C4A-\\\\u0C4D\\\\u0C55\\\\u0C56\\\\u0C62\\\\u0C63\\\\u0C82\\\\u0C83\\\\u0CBC\\\\u0CBE-\\\\u0CC4\\\\u0CC6-\\\\u0CC8\\\\u0CCA-\\\\u0CCD\\\\u0CD5\\\\u0CD6\\\\u0CE2\\\\u0CE3\\\\u0D02\\\\u0D03\\\\u0D3E-\\\\u0D44\\\\u0D46-\\\\u0D48\\\\u0D4A-\\\\u0D4D\\\\u0D57\\\\u0D62\\\\u0D63\\\\u0D82\\\\u0D83\\\\u0DCA\\\\u0DCF-\\\\u0DD4\\\\u0DD6\\\\u0DD8-\\\\u0DDF\\\\u0DF2\\\\u0DF3\\\\u0E31\\\\u0E34-\\\\u0E3A\\\\u0E47-\\\\u0E4E\\\\u0EB1\\\\u0EB4-\\\\u0EB9\\\\u0EBB\\\\u0EBC\\\\u0EC8-\\\\u0ECD\\\\u0F18\\\\u0F19\\\\u0F35\\\\u0F37\\\\u0F39\\\\u0F3E\\\\u0F3F\\\\u0F71-\\\\u0F84\\\\u0F86\\\\u0F87\\\\u0F8D-\\\\u0F97\\\\u0F99-\\\\u0FBC\\\\u0FC6\\\\u102B-\\\\u103E\\\\u1056-\\\\u1059\\\\u105E-\\\\u1060\\\\u1062-\\\\u1064\\\\u1067-\\\\u106D\\\\u1071-\\\\u1074\\\\u1082-\\\\u108D\\\\u108F\\\\u109A-\\\\u109D\\\\u135D-\\\\u135F\\\\u1712-\\\\u1714\\\\u1732-\\\\u1734\\\\u1752\\\\u1753\\\\u1772\\\\u1773\\\\u17B4-\\\\u17D3\\\\u17DD\\\\u180B-\\\\u180D\\\\u18A9\\\\u1920-\\\\u192B\\\\u1930-\\\\u193B\\\\u19B0-\\\\u19C0\\\\u19C8\\\\u19C9\\\\u1A17-\\\\u1A1B\\\\u1A55-\\\\u1A5E\\\\u1A60-\\\\u1A7C\\\\u1A7F\\\\u1B00-\\\\u1B04\\\\u1B34-\\\\u1B44\\\\u1B6B-\\\\u1B73\\\\u1B80-\\\\u1B82\\\\u1BA1-\\\\u1BAD\\\\u1BE6-\\\\u1BF3\\\\u1C24-\\\\u1C37\\\\u1CD0-\\\\u1CD2\\\\u1CD4-\\\\u1CE8\\\\u1CED\\\\u1CF2-\\\\u1CF4\\\\u1DC0-\\\\u1DE6\\\\u1DFC-\\\\u1DFF\\\\u20D0-\\\\u20DC\\\\u20E1\\\\u20E5-\\\\u20F0\\\\u2CEF-\\\\u2CF1\\\\u2D7F\\\\u2DE0-\\\\u2DFF\\\\u302A-\\\\u302F\\\\u3099\\\\u309A\\\\uA66F\\\\uA674-\\\\uA67D\\\\uA69F\\\\uA6F0\\\\uA6F1\\\\uA802\\\\uA806\\\\uA80B\\\\uA823-\\\\uA827\\\\uA880\\\\uA881\\\\uA8B4-\\\\uA8C4\\\\uA8E0-\\\\uA8F1\\\\uA926-\\\\uA92D\\\\uA947-\\\\uA953\\\\uA980-\\\\uA983\\\\uA9B3-\\\\uA9C0\\\\uAA29-\\\\uAA36\\\\uAA43\\\\uAA4C\\\\uAA4D\\\\uAA7B\\\\uAAB0\\\\uAAB2-\\\\uAAB4\\\\uAAB7\\\\uAAB8\\\\uAABE\\\\uAABF\\\\uAAC1\\\\uAAEB-\\\\uAAEF\\\\uAAF5\\\\uAAF6\\\\uABE3-\\\\uABEA\\\\uABEC\\\\uABED\\\\uFB1E\\\\uFE00-\\\\uFE0F\\\\uFE20-\\\\uFE26]\"),\n connector_punctuation: new RegExp(\"[\\\\u005F\\\\u203F\\\\u2040\\\\u2054\\\\uFE33\\\\uFE34\\\\uFE4D-\\\\uFE4F\\\\uFF3F]\"),\n digit: new RegExp(\"[\\\\u0030-\\\\u0039\\\\u0660-\\\\u0669\\\\u06F0-\\\\u06F9\\\\u07C0-\\\\u07C9\\\\u0966-\\\\u096F\\\\u09E6-\\\\u09EF\\\\u0A66-\\\\u0A6F\\\\u0AE6-\\\\u0AEF\\\\u0B66-\\\\u0B6F\\\\u0BE6-\\\\u0BEF\\\\u0C66-\\\\u0C6F\\\\u0CE6-\\\\u0CEF\\\\u0D66-\\\\u0D6F\\\\u0E50-\\\\u0E59\\\\u0ED0-\\\\u0ED9\\\\u0F20-\\\\u0F29\\\\u1040-\\\\u1049\\\\u1090-\\\\u1099\\\\u17E0-\\\\u17E9\\\\u1810-\\\\u1819\\\\u1946-\\\\u194F\\\\u19D0-\\\\u19D9\\\\u1A80-\\\\u1A89\\\\u1A90-\\\\u1A99\\\\u1B50-\\\\u1B59\\\\u1BB0-\\\\u1BB9\\\\u1C40-\\\\u1C49\\\\u1C50-\\\\u1C59\\\\uA620-\\\\uA629\\\\uA8D0-\\\\uA8D9\\\\uA900-\\\\uA909\\\\uA9D0-\\\\uA9D9\\\\uAA50-\\\\uAA59\\\\uABF0-\\\\uABF9\\\\uFF10-\\\\uFF19]\")\n};\n\nfunction is_letter(ch) {\n return UNICODE.letter.test(ch);\n};\n\nfunction is_digit(ch) {\n ch = ch.charCodeAt(0);\n return ch >= 48 && ch <= 57;\n};\n\nfunction is_unicode_digit(ch) {\n return UNICODE.digit.test(ch);\n}\n\nfunction is_alphanumeric_char(ch) {\n return is_digit(ch) || is_letter(ch);\n};\n\nfunction is_unicode_combining_mark(ch) {\n return UNICODE.combining_mark.test(ch);\n};\n\nfunction is_unicode_connector_punctuation(ch) {\n return UNICODE.connector_punctuation.test(ch);\n};\n\nfunction is_identifier_start(ch) {\n return ch == \"$\" || ch == \"_\" || is_letter(ch);\n};\n\nfunction is_identifier_char(ch) {\n return is_identifier_start(ch)\n || is_unicode_combining_mark(ch)\n || is_unicode_digit(ch)\n || is_unicode_connector_punctuation(ch)\n || ch == \"\\u200c\" // zero-width non-joiner <ZWNJ>\n || ch == \"\\u200d\" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)\n ;\n};\n\nfunction parse_js_number(num) {\n if (RE_HEX_NUMBER.test(num)) {\n return parseInt(num.substr(2), 16);\n } else if (RE_OCT_NUMBER.test(num)) {\n return parseInt(num.substr(1), 8);\n } else if (RE_DEC_NUMBER.test(num)) {\n return parseFloat(num);\n }\n};\n\nfunction JS_Parse_Error(message, line, col, pos) {\n this.message = message;\n this.line = line + 1;\n this.col = col + 1;\n this.pos = pos + 1;\n this.stack = new Error().stack;\n};\n\nJS_Parse_Error.prototype.toString = function() {\n return this.message + \" (line: \" + this.line + \", col: \" + this.col + \", pos: \" + this.pos + \")\" + \"\\n\\n\" + this.stack;\n};\n\nfunction js_error(message, line, col, pos) {\n throw new JS_Parse_Error(message, line, col, pos);\n};\n\nfunction is_token(token, type, val) {\n return token.type == type && (val == null || token.value == val);\n};\n\nvar EX_EOF = {};\n\nfunction tokenizer($TEXT) {\n\n var S = {\n text : $TEXT.replace(/\\r\\n?|[\\n\\u2028\\u2029]/g, \"\\n\").replace(/^\\uFEFF/, ''),\n pos : 0,\n tokpos : 0,\n line : 0,\n tokline : 0,\n col : 0,\n tokcol : 0,\n newline_before : false,\n regex_allowed : false,\n comments_before : []\n };\n\n function peek() { return S.text.charAt(S.pos); };\n\n function next(signal_eof, in_string) {\n var ch = S.text.charAt(S.pos++);\n if (signal_eof && !ch)\n throw EX_EOF;\n if (ch == \"\\n\") {\n S.newline_before = S.newline_before || !in_string;\n ++S.line;\n S.col = 0;\n } else {\n ++S.col;\n }\n return ch;\n };\n\n function eof() {\n return !S.peek();\n };\n\n function find(what, signal_eof) {\n var pos = S.text.indexOf(what, S.pos);\n if (signal_eof && pos == -1) throw EX_EOF;\n return pos;\n };\n\n function start_token() {\n S.tokline = S.line;\n S.tokcol = S.col;\n S.tokpos = S.pos;\n };\n\n function token(type, value, is_comment) {\n S.regex_allowed = ((type == \"operator\" && !HOP(UNARY_POSTFIX, value)) ||\n (type == \"keyword\" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||\n (type == \"punc\" && HOP(PUNC_BEFORE_EXPRESSION, value)));\n var ret = {\n type : type,\n value : value,\n line : S.tokline,\n col : S.tokcol,\n pos : S.tokpos,\n endpos : S.pos,\n nlb : S.newline_before\n };\n if (!is_comment) {\n ret.comments_before = S.comments_before;\n S.comments_before = [];\n // make note of any newlines in the comments that came before\n for (var i = 0, len = ret.comments_before.length; i < len; i++) {\n ret.nlb = ret.nlb || ret.comments_before[i].nlb;\n }\n }\n S.newline_before = false;\n return ret;\n };\n\n function skip_whitespace() {\n while (HOP(WHITESPACE_CHARS, peek()))\n next();\n };\n\n function read_while(pred) {\n var ret = \"\", ch = peek(), i = 0;\n while (ch && pred(ch, i++)) {\n ret += next();\n ch = peek();\n }\n return ret;\n };\n\n function parse_error(err) {\n js_error(err, S.tokline, S.tokcol, S.tokpos);\n };\n\n function read_num(prefix) {\n var has_e = false, after_e = false, has_x = false, has_dot = prefix == \".\";\n var num = read_while(function(ch, i){\n if (ch == \"x\" || ch == \"X\") {\n if (has_x) return false;\n return has_x = true;\n }\n if (!has_x && (ch == \"E\" || ch == \"e\")) {\n if (has_e) return false;\n return has_e = after_e = true;\n }\n if (ch == \"-\") {\n if (after_e || (i == 0 && !prefix)) return true;\n return false;\n }\n if (ch == \"+\") return after_e;\n after_e = false;\n if (ch == \".\") {\n if (!has_dot && !has_x && !has_e)\n return has_dot = true;\n return false;\n }\n return is_alphanumeric_char(ch);\n });\n if (prefix)\n num = prefix + num;\n var valid = parse_js_number(num);\n if (!isNaN(valid)) {\n return token(\"num\", valid);\n } else {\n parse_error(\"Invalid syntax: \" + num);\n }\n };\n\n function read_escaped_char(in_string) {\n var ch = next(true, in_string);\n switch (ch) {\n case \"n\" : return \"\\n\";\n case \"r\" : return \"\\r\";\n case \"t\" : return \"\\t\";\n case \"b\" : return \"\\b\";\n case \"v\" : return \"\\u000b\";\n case \"f\" : return \"\\f\";\n case \"0\" : return \"\\0\";\n case \"x\" : return String.fromCharCode(hex_bytes(2));\n case \"u\" : return String.fromCharCode(hex_bytes(4));\n case \"\\n\": return \"\";\n default : return ch;\n }\n };\n\n function hex_bytes(n) {\n var num = 0;\n for (; n > 0; --n) {\n var digit = parseInt(next(true), 16);\n if (isNaN(digit))\n parse_error(\"Invalid hex-character pattern in string\");\n num = (num << 4) | digit;\n }\n return num;\n };\n\n function read_string() {\n return with_eof_error(\"Unterminated string constant\", function(){\n var quote = next(), ret = \"\";\n for (;;) {\n var ch = next(true);\n if (ch == \"\\\\\") {\n // read OctalEscapeSequence (XXX: deprecated if \"strict mode\")\n // https://github.com/mishoo/UglifyJS/issues/178\n var octal_len = 0, first = null;\n ch = read_while(function(ch){\n if (ch >= \"0\" && ch <= \"7\") {\n if (!first) {\n first = ch;\n return ++octal_len;\n }\n else if (first <= \"3\" && octal_len <= 2) return ++octal_len;\n else if (first >= \"4\" && octal_len <= 1) return ++octal_len;\n }\n return false;\n });\n if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));\n else ch = read_escaped_char(true);\n }\n else if (ch == quote) break;\n else if (ch == \"\\n\") throw EX_EOF;\n ret += ch;\n }\n return token(\"string\", ret);\n });\n };\n\n function read_line_comment() {\n next();\n var i = find(\"\\n\"), ret;\n if (i == -1) {\n ret = S.text.substr(S.pos);\n S.pos = S.text.length;\n } else {\n ret = S.text.substring(S.pos, i);\n S.pos = i;\n }\n return token(\"comment1\", ret, true);\n };\n\n function read_multiline_comment() {\n next();\n return with_eof_error(\"Unterminated multiline comment\", function(){\n var i = find(\"*/\", true),\n text = S.text.substring(S.pos, i);\n S.pos = i + 2;\n S.line += text.split(\"\\n\").length - 1;\n S.newline_before = S.newline_before || text.indexOf(\"\\n\") >= 0;\n\n // https://github.com/mishoo/UglifyJS/issues/#issue/100\n if (/^@cc_on/i.test(text)) {\n warn(\"WARNING: at line \" + S.line);\n warn(\"*** Found \\\"conditional comment\\\": \" + text);\n warn(\"*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.\");\n }\n\n return token(\"comment2\", text, true);\n });\n };\n\n function read_name() {\n var backslash = false, name = \"\", ch, escaped = false, hex;\n while ((ch = peek()) != null) {\n if (!backslash) {\n if (ch == \"\\\\\") escaped = backslash = true, next();\n else if (is_identifier_char(ch)) name += next();\n else break;\n }\n else {\n if (ch != \"u\") parse_error(\"Expecting UnicodeEscapeSequence -- uXXXX\");\n ch = read_escaped_char();\n if (!is_identifier_char(ch)) parse_error(\"Unicode char: \" + ch.charCodeAt(0) + \" is not valid in identifier\");\n name += ch;\n backslash = false;\n }\n }\n if (HOP(KEYWORDS, name) && escaped) {\n hex = name.charCodeAt(0).toString(16).toUpperCase();\n name = \"\\\\u\" + \"0000\".substr(hex.length) + hex + name.slice(1);\n }\n return name;\n };\n\n function read_regexp(regexp) {\n return with_eof_error(\"Unterminated regular expression\", function(){\n var prev_backslash = false, ch, in_class = false;\n while ((ch = next(true))) if (prev_backslash) {\n regexp += \"\\\\\" + ch;\n prev_backslash = false;\n } else if (ch == \"[\") {\n in_class = true;\n regexp += ch;\n } else if (ch == \"]\" && in_class) {\n in_class = false;\n regexp += ch;\n } else if (ch == \"/\" && !in_class) {\n break;\n } else if (ch == \"\\\\\") {\n prev_backslash = true;\n } else {\n regexp += ch;\n }\n var mods = read_name();\n return token(\"regexp\", [ regexp, mods ]);\n });\n };\n\n function read_operator(prefix) {\n function grow(op) {\n if (!peek()) return op;\n var bigger = op + peek();\n if (HOP(OPERATORS, bigger)) {\n next();\n return grow(bigger);\n } else {\n return op;\n }\n };\n return token(\"operator\", grow(prefix || next()));\n };\n\n function handle_slash() {\n next();\n var regex_allowed = S.regex_allowed;\n switch (peek()) {\n case \"/\":\n S.comments_before.push(read_line_comment());\n S.regex_allowed = regex_allowed;\n return next_token();\n case \"*\":\n S.comments_before.push(read_multiline_comment());\n S.regex_allowed = regex_allowed;\n return next_token();\n }\n return S.regex_allowed ? read_regexp(\"\") : read_operator(\"/\");\n };\n\n function handle_dot() {\n next();\n return is_digit(peek())\n ? read_num(\".\")\n : token(\"punc\", \".\");\n };\n\n function read_word() {\n var word = read_name();\n return !HOP(KEYWORDS, word)\n ? token(\"name\", word)\n : HOP(OPERATORS, word)\n ? token(\"operator\", word)\n : HOP(KEYWORDS_ATOM, word)\n ? token(\"atom\", word)\n : token(\"keyword\", word);\n };\n\n function with_eof_error(eof_error, cont) {\n try {\n return cont();\n } catch(ex) {\n if (ex === EX_EOF) parse_error(eof_error);\n else throw ex;\n }\n };\n\n function next_token(force_regexp) {\n if (force_regexp != null)\n return read_regexp(force_regexp);\n skip_whitespace();\n start_token();\n var ch = peek();\n if (!ch) return token(\"eof\");\n if (is_digit(ch)) return read_num();\n if (ch == '\"' || ch == \"'\") return read_string();\n if (HOP(PUNC_CHARS, ch)) return token(\"punc\", next());\n if (ch == \".\") return handle_dot();\n if (ch == \"/\") return handle_slash();\n if (HOP(OPERATOR_CHARS, ch)) return read_operator();\n if (ch == \"\\\\\" || is_identifier_start(ch)) return read_word();\n parse_error(\"Unexpected character '\" + ch + \"'\");\n };\n\n next_token.context = function(nc) {\n if (nc) S = nc;\n return S;\n };\n\n return next_token;\n\n};\n\n/* -----[ Parser (constants) ]----- */\n\nvar UNARY_PREFIX = array_to_hash([\n \"typeof\",\n \"void\",\n \"delete\",\n \"--\",\n \"++\",\n \"!\",\n \"~\",\n \"-\",\n \"+\"\n]);\n\nvar UNARY_POSTFIX = array_to_hash([ \"--\", \"++\" ]);\n\nvar ASSIGNMENT = (function(a, ret, i){\n while (i < a.length) {\n ret[a[i]] = a[i].substr(0, a[i].length - 1);\n i++;\n }\n return ret;\n})(\n [\"+=\", \"-=\", \"/=\", \"*=\", \"%=\", \">>=\", \"<<=\", \">>>=\", \"|=\", \"^=\", \"&=\"],\n { \"=\": true },\n 0\n);\n\nvar PRECEDENCE = (function(a, ret){\n for (var i = 0, n = 1; i < a.length; ++i, ++n) {\n var b = a[i];\n for (var j = 0; j < b.length; ++j) {\n ret[b[j]] = n;\n }\n }\n return ret;\n})(\n [\n [\"||\"],\n [\"&&\"],\n [\"|\"],\n [\"^\"],\n [\"&\"],\n [\"==\", \"===\", \"!=\", \"!==\"],\n [\"<\", \">\", \"<=\", \">=\", \"in\", \"instanceof\"],\n [\">>\", \"<<\", \">>>\"],\n [\"+\", \"-\"],\n [\"*\", \"/\", \"%\"]\n ],\n {}\n);\n\nvar STATEMENTS_WITH_LABELS = array_to_hash([ \"for\", \"do\", \"while\", \"switch\" ]);\n\nvar ATOMIC_START_TOKEN = array_to_hash([ \"atom\", \"num\", \"string\", \"regexp\", \"name\" ]);\n\n/* -----[ Parser ]----- */\n\nfunction NodeWithToken(str, start, end) {\n this.name = str;\n this.start = start;\n this.end = end;\n};\n\nNodeWithToken.prototype.toString = function() { return this.name; };\n\nfunction parse($TEXT, exigent_mode, embed_tokens) {\n\n var S = {\n input : typeof $TEXT == \"string\" ? tokenizer($TEXT, true) : $TEXT,\n token : null,\n prev : null,\n peeked : null,\n in_function : 0,\n in_directives : true,\n in_loop : 0,\n labels : []\n };\n\n S.token = next();\n\n function is(type, value) {\n return is_token(S.token, type, value);\n };\n\n function peek() { return S.peeked || (S.peeked = S.input()); };\n\n function next() {\n S.prev = S.token;\n if (S.peeked) {\n S.token = S.peeked;\n S.peeked = null;\n } else {\n S.token = S.input();\n }\n S.in_directives = S.in_directives && (\n S.token.type == \"string\" || is(\"punc\", \";\")\n );\n return S.token;\n };\n\n function prev() {\n return S.prev;\n };\n\n function croak(msg, line, col, pos) {\n var ctx = S.input.context();\n js_error(msg,\n line != null ? line : ctx.tokline,\n col != null ? col : ctx.tokcol,\n pos != null ? pos : ctx.tokpos);\n };\n\n function token_error(token, msg) {\n croak(msg, token.line, token.col);\n };\n\n function unexpected(token) {\n if (token == null)\n token = S.token;\n token_error(token, \"Unexpected token: \" + token.type + \" (\" + token.value + \")\");\n };\n\n function expect_token(type, val) {\n if (is(type, val)) {\n return next();\n }\n token_error(S.token, \"Unexpected token \" + S.token.type + \", expected \" + type);\n };\n\n function expect(punc) { return expect_token(\"punc\", punc); };\n\n function can_insert_semicolon() {\n return !exigent_mode && (\n S.token.nlb || is(\"eof\") || is(\"punc\", \"}\")\n );\n };\n\n function semicolon() {\n if (is(\"punc\", \";\")) next();\n else if (!can_insert_semicolon()) unexpected();\n };\n\n function as() {\n return slice(arguments);\n };\n\n function parenthesised() {\n expect(\"(\");\n var ex = expression();\n expect(\")\");\n return ex;\n };\n\n function add_tokens(str, start, end) {\n return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);\n };\n\n function maybe_embed_tokens(parser) {\n if (embed_tokens) return function() {\n var start = S.token;\n var ast = parser.apply(this, arguments);\n ast[0] = add_tokens(ast[0], start, prev());\n return ast;\n };\n else return parser;\n };\n\n var statement = maybe_embed_tokens(function() {\n if (is(\"operator\", \"/\") || is(\"operator\", \"/=\")) {\n S.peeked = null;\n S.token = S.input(S.token.value.substr(1)); // force regexp\n }\n switch (S.token.type) {\n case \"string\":\n var dir = S.in_directives, stat = simple_statement();\n if (dir && stat[1][0] == \"string\" && !is(\"punc\", \",\"))\n return as(\"directive\", stat[1][1]);\n return stat;\n case \"num\":\n case \"regexp\":\n case \"operator\":\n case \"atom\":\n return simple_statement();\n\n case \"name\":\n return is_token(peek(), \"punc\", \":\")\n ? labeled_statement(prog1(S.token.value, next, next))\n : simple_statement();\n\n case \"punc\":\n switch (S.token.value) {\n case \"{\":\n return as(\"block\", block_());\n case \"[\":\n case \"(\":\n return simple_statement();\n case \";\":\n next();\n return as(\"block\");\n default:\n unexpected();\n }\n\n case \"keyword\":\n switch (prog1(S.token.value, next)) {\n case \"break\":\n return break_cont(\"break\");\n\n case \"continue\":\n return break_cont(\"continue\");\n\n case \"debugger\":\n semicolon();\n return as(\"debugger\");\n\n case \"do\":\n return (function(body){\n expect_token(\"keyword\", \"while\");\n return as(\"do\", prog1(parenthesised, semicolon), body);\n })(in_loop(statement));\n\n case \"for\":\n return for_();\n\n case \"function\":\n return function_(true);\n\n case \"if\":\n return if_();\n\n case \"return\":\n if (S.in_function == 0)\n croak(\"'return' outside of function\");\n return as(\"return\",\n is(\"punc\", \";\")\n ? (next(), null)\n : can_insert_semicolon()\n ? null\n : prog1(expression, semicolon));\n\n case \"switch\":\n return as(\"switch\", parenthesised(), switch_block_());\n\n case \"throw\":\n if (S.token.nlb)\n croak(\"Illegal newline after 'throw'\");\n return as(\"throw\", prog1(expression, semicolon));\n\n case \"try\":\n return try_();\n\n case \"var\":\n return prog1(var_, semicolon);\n\n case \"const\":\n return prog1(const_, semicolon);\n\n case \"while\":\n return as(\"while\", parenthesised(), in_loop(statement));\n\n case \"with\":\n return as(\"with\", parenthesised(), statement());\n\n default:\n unexpected();\n }\n }\n });\n\n function labeled_statement(label) {\n S.labels.push(label);\n var start = S.token, stat = statement();\n if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))\n unexpected(start);\n S.labels.pop();\n return as(\"label\", label, stat);\n };\n\n function simple_statement() {\n return as(\"stat\", prog1(expression, semicolon));\n };\n\n function break_cont(type) {\n var name;\n if (!can_insert_semicolon()) {\n name = is(\"name\") ? S.token.value : null;\n }\n if (name != null) {\n next();\n if (!member(name, S.labels))\n croak(\"Label \" + name + \" without matching loop or statement\");\n }\n else if (S.in_loop == 0)\n croak(type + \" not inside a loop or switch\");\n semicolon();\n return as(type, name);\n };\n\n function for_() {\n expect(\"(\");\n var init = null;\n if (!is(\"punc\", \";\")) {\n init = is(\"keyword\", \"var\")\n ? (next(), var_(true))\n : expression(true, true);\n if (is(\"operator\", \"in\")) {\n if (init[0] == \"var\" && init[1].length > 1)\n croak(\"Only one variable declaration allowed in for..in loop\");\n return for_in(init);\n }\n }\n return regular_for(init);\n };\n\n function regular_for(init) {\n expect(\";\");\n var test = is(\"punc\", \";\") ? null : expression();\n expect(\";\");\n var step = is(\"punc\", \")\") ? null : expression();\n expect(\")\");\n return as(\"for\", init, test, step, in_loop(statement));\n };\n\n function for_in(init) {\n var lhs = init[0] == \"var\" ? as(\"name\", init[1][0]) : init;\n next();\n var obj = expression();\n expect(\")\");\n return as(\"for-in\", init, lhs, obj, in_loop(statement));\n };\n\n var function_ = function(in_statement) {\n var name = is(\"name\") ? prog1(S.token.value, next) : null;\n if (in_statement && !name)\n unexpected();\n expect(\"(\");\n return as(in_statement ? \"defun\" : \"function\",\n name,\n // arguments\n (function(first, a){\n while (!is(\"punc\", \")\")) {\n if (first) first = false; else expect(\",\");\n if (!is(\"name\")) unexpected();\n a.push(S.token.value);\n next();\n }\n next();\n return a;\n })(true, []),\n // body\n (function(){\n ++S.in_function;\n var loop = S.in_loop;\n S.in_directives = true;\n S.in_loop = 0;\n var a = block_();\n --S.in_function;\n S.in_loop = loop;\n return a;\n })());\n };\n\n function if_() {\n var cond = parenthesised(), body = statement(), belse;\n if (is(\"keyword\", \"else\")) {\n next();\n belse = statement();\n }\n return as(\"if\", cond, body, belse);\n };\n\n function block_() {\n expect(\"{\");\n var a = [];\n while (!is(\"punc\", \"}\")) {\n if (is(\"eof\")) unexpected();\n a.push(statement());\n }\n next();\n return a;\n };\n\n var switch_block_ = curry(in_loop, function(){\n expect(\"{\");\n var a = [], cur = null;\n while (!is(\"punc\", \"}\")) {\n if (is(\"eof\")) unexpected();\n if (is(\"keyword\", \"case\")) {\n next();\n cur = [];\n a.push([ expression(), cur ]);\n expect(\":\");\n }\n else if (is(\"keyword\", \"default\")) {\n next();\n expect(\":\");\n cur = [];\n a.push([ null, cur ]);\n }\n else {\n if (!cur) unexpected();\n cur.push(statement());\n }\n }\n next();\n return a;\n });\n\n function try_() {\n var body = block_(), bcatch, bfinally;\n if (is(\"keyword\", \"catch\")) {\n next();\n expect(\"(\");\n if (!is(\"name\"))\n croak(\"Name expected\");\n var name = S.token.value;\n next();\n expect(\")\");\n bcatch = [ name, block_() ];\n }\n if (is(\"keyword\", \"finally\")) {\n next();\n bfinally = block_();\n }\n if (!bcatch && !bfinally)\n croak(\"Missing catch/finally blocks\");\n return as(\"try\", body, bcatch, bfinally);\n };\n\n function vardefs(no_in) {\n var a = [];\n for (;;) {\n if (!is(\"name\"))\n unexpected();\n var name = S.token.value;\n next();\n if (is(\"operator\", \"=\")) {\n next();\n a.push([ name, expression(false, no_in) ]);\n } else {\n a.push([ name ]);\n }\n if (!is(\"punc\", \",\"))\n break;\n next();\n }\n return a;\n };\n\n function var_(no_in) {\n return as(\"var\", vardefs(no_in));\n };\n\n function const_() {\n return as(\"const\", vardefs());\n };\n\n function new_() {\n var newexp = expr_atom(false), args;\n if (is(\"punc\", \"(\")) {\n next();\n args = expr_list(\")\");\n } else {\n args = [];\n }\n return subscripts(as(\"new\", newexp, args), true);\n };\n\n var expr_atom = maybe_embed_tokens(function(allow_calls) {\n if (is(\"operator\", \"new\")) {\n next();\n return new_();\n }\n if (is(\"punc\")) {\n switch (S.token.value) {\n case \"(\":\n next();\n return subscripts(prog1(expression, curry(expect, \")\")), allow_calls);\n case \"[\":\n next();\n return subscripts(array_(), allow_calls);\n case \"{\":\n next();\n return subscripts(object_(), allow_calls);\n }\n unexpected();\n }\n if (is(\"keyword\", \"function\")) {\n next();\n return subscripts(function_(false), allow_calls);\n }\n if (HOP(ATOMIC_START_TOKEN, S.token.type)) {\n var atom = S.token.type == \"regexp\"\n ? as(\"regexp\", S.token.value[0], S.token.value[1])\n : as(S.token.type, S.token.value);\n return subscripts(prog1(atom, next), allow_calls);\n }\n unexpected();\n });\n\n function expr_list(closing, allow_trailing_comma, allow_empty) {\n var first = true, a = [];\n while (!is(\"punc\", closing)) {\n if (first) first = false; else expect(\",\");\n if (allow_trailing_comma && is(\"punc\", closing)) break;\n if (is(\"punc\", \",\") && allow_empty) {\n a.push([ \"atom\", \"undefined\" ]);\n } else {\n a.push(expression(false));\n }\n }\n next();\n return a;\n };\n\n function array_() {\n return as(\"array\", expr_list(\"]\", !exigent_mode, true));\n };\n\n function object_() {\n var first = true, a = [];\n while (!is(\"punc\", \"}\")) {\n if (first) first = false; else expect(\",\");\n if (!exigent_mode && is(\"punc\", \"}\"))\n // allow trailing comma\n break;\n var type = S.token.type;\n var name = as_property_name();\n if (type == \"name\" && (name == \"get\" || name == \"set\") && !is(\"punc\", \":\")) {\n a.push([ as_name(), function_(false), name ]);\n } else {\n expect(\":\");\n a.push([ name, expression(false) ]);\n }\n }\n next();\n return as(\"object\", a);\n };\n\n function as_property_name() {\n switch (S.token.type) {\n case \"num\":\n case \"string\":\n return prog1(S.token.value, next);\n }\n return as_name();\n };\n\n function as_name() {\n switch (S.token.type) {\n case \"name\":\n case \"operator\":\n case \"keyword\":\n case \"atom\":\n return prog1(S.token.value, next);\n default:\n unexpected();\n }\n };\n\n function subscripts(expr, allow_calls) {\n if (is(\"punc\", \".\")) {\n next();\n return subscripts(as(\"dot\", expr, as_name()), allow_calls);\n }\n if (is(\"punc\", \"[\")) {\n next();\n return subscripts(as(\"sub\", expr, prog1(expression, curry(expect, \"]\"))), allow_calls);\n }\n if (allow_calls && is(\"punc\", \"(\")) {\n next();\n return subscripts(as(\"call\", expr, expr_list(\")\")), true);\n }\n return expr;\n };\n\n function maybe_unary(allow_calls) {\n if (is(\"operator\") && HOP(UNARY_PREFIX, S.token.value)) {\n return make_unary(\"unary-prefix\",\n prog1(S.token.value, next),\n maybe_unary(allow_calls));\n }\n var val = expr_atom(allow_calls);\n while (is(\"operator\") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {\n val = make_unary(\"unary-postfix\", S.token.value, val);\n next();\n }\n return val;\n };\n\n function make_unary(tag, op, expr) {\n if ((op == \"++\" || op == \"--\") && !is_assignable(expr))\n croak(\"Invalid use of \" + op + \" operator\");\n return as(tag, op, expr);\n };\n\n function expr_op(left, min_prec, no_in) {\n var op = is(\"operator\") ? S.token.value : null;\n if (op && op == \"in\" && no_in) op = null;\n var prec = op != null ? PRECEDENCE[op] : null;\n if (prec != null && prec > min_prec) {\n next();\n var right = expr_op(maybe_unary(true), prec, no_in);\n return expr_op(as(\"binary\", op, left, right), min_prec, no_in);\n }\n return left;\n };\n\n function expr_ops(no_in) {\n return expr_op(maybe_unary(true), 0, no_in);\n };\n\n function maybe_conditional(no_in) {\n var expr = expr_ops(no_in);\n if (is(\"operator\", \"?\")) {\n next();\n var yes = expression(false);\n expect(\":\");\n return as(\"conditional\", expr, yes, expression(false, no_in));\n }\n return expr;\n };\n\n function is_assignable(expr) {\n if (!exigent_mode) return true;\n switch (expr[0]+\"\") {\n case \"dot\":\n case \"sub\":\n case \"new\":\n case \"call\":\n return true;\n case \"name\":\n return expr[1] != \"this\";\n }\n };\n\n function maybe_assign(no_in) {\n var left = maybe_conditional(no_in), val = S.token.value;\n if (is(\"operator\") && HOP(ASSIGNMENT, val)) {\n if (is_assignable(left)) {\n next();\n return as(\"assign\", ASSIGNMENT[val], left, maybe_assign(no_in));\n }\n croak(\"Invalid assignment\");\n }\n return left;\n };\n\n var expression = maybe_embed_tokens(function(commas, no_in) {\n if (arguments.length == 0)\n commas = true;\n var expr = maybe_assign(no_in);\n if (commas && is(\"punc\", \",\")) {\n next();\n return as(\"seq\", expr, expression(true, no_in));\n }\n return expr;\n });\n\n function in_loop(cont) {\n try {\n ++S.in_loop;\n return cont();\n } finally {\n --S.in_loop;\n }\n };\n\n return as(\"toplevel\", (function(a){\n while (!is(\"eof\"))\n a.push(statement());\n return a;\n })([]));\n\n};\n\n/* -----[ Utilities ]----- */\n\nfunction curry(f) {\n var args = slice(arguments, 1);\n return function() { return f.apply(this, args.concat(slice(arguments))); };\n};\n\nfunction prog1(ret) {\n if (ret instanceof Function)\n ret = ret();\n for (var i = 1, n = arguments.length; --n > 0; ++i)\n arguments[i]();\n return ret;\n};\n\nfunction array_to_hash(a) {\n var ret = {};\n for (var i = 0; i < a.length; ++i)\n ret[a[i]] = true;\n return ret;\n};\n\nfunction slice(a, start) {\n return Array.prototype.slice.call(a, start || 0);\n};\n\nfunction characters(str) {\n return str.split(\"\");\n};\n\nfunction member(name, array) {\n for (var i = array.length; --i >= 0;)\n if (array[i] == name)\n return true;\n return false;\n};\n\nfunction HOP(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n};\n\nvar warn = function() {};\n\n/* -----[ Exports ]----- */\n\nexports.tokenizer = tokenizer;\nexports.parse = parse;\nexports.slice = slice;\nexports.curry = curry;\nexports.member = member;\nexports.array_to_hash = array_to_hash;\nexports.PRECEDENCE = PRECEDENCE;\nexports.KEYWORDS_ATOM = KEYWORDS_ATOM;\nexports.RESERVED_WORDS = RESERVED_WORDS;\nexports.KEYWORDS = KEYWORDS;\nexports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;\nexports.OPERATORS = OPERATORS;\nexports.is_alphanumeric_char = is_alphanumeric_char;\nexports.is_identifier_start = is_identifier_start;\nexports.is_identifier_char = is_identifier_char;\nexports.set_logger = function(logger) {\n warn = logger;\n};\n\n// Local variables:\n// js-indent-level: 4\n// End:\n});define('uglifyjs/squeeze-more', [\"require\", \"exports\", \"module\", \"./parse-js\", \"./squeeze-more\"], function(require, exports, module) {\nvar jsp = require(\"./parse-js\"),\n pro = require(\"./process\"),\n slice = jsp.slice,\n member = jsp.member,\n curry = jsp.curry,\n MAP = pro.MAP,\n PRECEDENCE = jsp.PRECEDENCE,\n OPERATORS = jsp.OPERATORS;\n\nfunction ast_squeeze_more(ast) {\n var w = pro.ast_walker(), walk = w.walk, scope;\n function with_scope(s, cont) {\n var save = scope, ret;\n scope = s;\n ret = cont();\n scope = save;\n return ret;\n };\n function _lambda(name, args, body) {\n return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];\n };\n return w.with_walkers({\n \"toplevel\": function(body) {\n return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];\n },\n \"function\": _lambda,\n \"defun\": _lambda,\n \"new\": function(ctor, args) {\n if (ctor[0] == \"name\") {\n if (ctor[1] == \"Array\" && !scope.has(\"Array\")) {\n if (args.length != 1) {\n return [ \"array\", args ];\n } else {\n return walk([ \"call\", [ \"name\", \"Array\" ], args ]);\n }\n } else if (ctor[1] == \"Object\" && !scope.has(\"Object\")) {\n if (!args.length) {\n return [ \"object\", [] ];\n } else {\n return walk([ \"call\", [ \"name\", \"Object\" ], args ]);\n }\n } else if ((ctor[1] == \"RegExp\" || ctor[1] == \"Function\" || ctor[1] == \"Error\") && !scope.has(ctor[1])) {\n return walk([ \"call\", [ \"name\", ctor[1] ], args]);\n }\n }\n },\n \"call\": function(expr, args) {\n if (expr[0] == \"dot\" && expr[1][0] == \"string\" && args.length == 1\n && (args[0][1] > 0 && expr[2] == \"substring\" || expr[2] == \"substr\")) {\n return [ \"call\", [ \"dot\", expr[1], \"slice\"], args];\n }\n if (expr[0] == \"dot\" && expr[2] == \"toString\" && args.length == 0) {\n // foo.toString() ==> foo+\"\"\n if (expr[1][0] == \"string\") return expr[1];\n return [ \"binary\", \"+\", expr[1], [ \"string\", \"\" ]];\n }\n if (expr[0] == \"name\") {\n if (expr[1] == \"Array\" && args.length != 1 && !scope.has(\"Array\")) {\n return [ \"array\", args ];\n }\n if (expr[1] == \"Object\" && !args.length && !scope.has(\"Object\")) {\n return [ \"object\", [] ];\n }\n if (expr[1] == \"String\" && !scope.has(\"String\")) {\n return [ \"binary\", \"+\", args[0], [ \"string\", \"\" ]];\n }\n }\n }\n }, function() {\n return walk(pro.ast_add_scope(ast));\n });\n};\n\nexports.ast_squeeze_more = ast_squeeze_more;\n\n// Local variables:\n// js-indent-level: 4\n// End:\n});\ndefine('uglifyjs/process', [\"require\", \"exports\", \"module\", \"./parse-js\", \"./squeeze-more\"], function(require, exports, module) {\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n\n This version is suitable for Node.js. With minimal changes (the\n exports stuff) it should work on any JS platform.\n\n This file implements some AST processors. They work on data built\n by parse-js.\n\n Exported functions:\n\n - ast_mangle(ast, options) -- mangles the variable/function names\n in the AST. Returns an AST.\n\n - ast_squeeze(ast) -- employs various optimizations to make the\n final generated code even smaller. Returns an AST.\n\n - gen_code(ast, options) -- generates JS code from the AST. Pass\n true (or an object, see the code for some options) as second\n argument to get \"pretty\" (indented) code.\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2010 (c) Mihai Bazon <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\nvar jsp = require(\"./parse-js\"),\n curry = jsp.curry,\n slice = jsp.slice,\n member = jsp.member,\n is_identifier_char = jsp.is_identifier_char,\n PRECEDENCE = jsp.PRECEDENCE,\n OPERATORS = jsp.OPERATORS;\n\n/* -----[ helper for AST traversal ]----- */\n\nfunction ast_walker() {\n function _vardefs(defs) {\n return [ this[0], MAP(defs, function(def){\n var a = [ def[0] ];\n if (def.length > 1)\n a[1] = walk(def[1]);\n return a;\n }) ];\n };\n function _block(statements) {\n var out = [ this[0] ];\n if (statements != null)\n out.push(MAP(statements, walk));\n return out;\n };\n var walkers = {\n \"string\": function(str) {\n return [ this[0], str ];\n },\n \"num\": function(num) {\n return [ this[0], num ];\n },\n \"name\": function(name) {\n return [ this[0], name ];\n },\n \"toplevel\": function(statements) {\n return [ this[0], MAP(statements, walk) ];\n },\n \"block\": _block,\n \"splice\": _block,\n \"var\": _vardefs,\n \"const\": _vardefs,\n \"try\": function(t, c, f) {\n return [\n this[0],\n MAP(t, walk),\n c != null ? [ c[0], MAP(c[1], walk) ] : null,\n f != null ? MAP(f, walk) : null\n ];\n },\n \"throw\": function(expr) {\n return [ this[0], walk(expr) ];\n },\n \"new\": function(ctor, args) {\n return [ this[0], walk(ctor), MAP(args, walk) ];\n },\n \"switch\": function(expr, body) {\n return [ this[0], walk(expr), MAP(body, function(branch){\n return [ branch[0] ? walk(branch[0]) : null,\n MAP(branch[1], walk) ];\n }) ];\n },\n \"break\": function(label) {\n return [ this[0], label ];\n },\n \"continue\": function(label) {\n return [ this[0], label ];\n },\n \"conditional\": function(cond, t, e) {\n return [ this[0], walk(cond), walk(t), walk(e) ];\n },\n \"assign\": function(op, lvalue, rvalue) {\n return [ this[0], op, walk(lvalue), walk(rvalue) ];\n },\n \"dot\": function(expr) {\n return [ this[0], walk(expr) ].concat(slice(arguments, 1));\n },\n \"call\": function(expr, args) {\n return [ this[0], walk(expr), MAP(args, walk) ];\n },\n \"function\": function(name, args, body) {\n return [ this[0], name, args.slice(), MAP(body, walk) ];\n },\n \"debugger\": function() {\n return [ this[0] ];\n },\n \"defun\": function(name, args, body) {\n return [ this[0], name, args.slice(), MAP(body, walk) ];\n },\n \"if\": function(conditional, t, e) {\n return [ this[0], walk(conditional), walk(t), walk(e) ];\n },\n \"for\": function(init, cond, step, block) {\n return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];\n },\n \"for-in\": function(vvar, key, hash, block) {\n return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];\n },\n \"while\": function(cond, block) {\n return [ this[0], walk(cond), walk(block) ];\n },\n \"do\": function(cond, block) {\n return [ this[0], walk(cond), walk(block) ];\n },\n \"return\": function(expr) {\n return [ this[0], walk(expr) ];\n },\n \"binary\": function(op, left, right) {\n return [ this[0], op, walk(left), walk(right) ];\n },\n \"unary-prefix\": function(op, expr) {\n return [ this[0], op, walk(expr) ];\n },\n \"unary-postfix\": function(op, expr) {\n return [ this[0], op, walk(expr) ];\n },\n \"sub\": function(expr, subscript) {\n return [ this[0], walk(expr), walk(subscript) ];\n },\n \"object\": function(props) {\n return [ this[0], MAP(props, function(p){\n return p.length == 2\n ? [ p[0], walk(p[1]) ]\n : [ p[0], walk(p[1]), p[2] ]; // get/set-ter\n }) ];\n },\n \"regexp\": function(rx, mods) {\n return [ this[0], rx, mods ];\n },\n \"array\": function(elements) {\n return [ this[0], MAP(elements, walk) ];\n },\n \"stat\": function(stat) {\n return [ this[0], walk(stat) ];\n },\n \"seq\": function() {\n return [ this[0] ].concat(MAP(slice(arguments), walk));\n },\n \"label\": function(name, block) {\n return [ this[0], name, walk(block) ];\n },\n \"with\": function(expr, block) {\n return [ this[0], walk(expr), walk(block) ];\n },\n \"atom\": function(name) {\n return [ this[0], name ];\n },\n \"directive\": function(dir) {\n return [ this[0], dir ];\n }\n };\n\n var user = {};\n var stack = [];\n function walk(ast) {\n if (ast == null)\n return null;\n try {\n stack.push(ast);\n var type = ast[0];\n var gen = user[type];\n if (gen) {\n var ret = gen.apply(ast, ast.slice(1));\n if (ret != null)\n return ret;\n }\n gen = walkers[type];\n return gen.apply(ast, ast.slice(1));\n } finally {\n stack.pop();\n }\n };\n\n function dive(ast) {\n if (ast == null)\n return null;\n try {\n stack.push(ast);\n return walkers[ast[0]].apply(ast, ast.slice(1));\n } finally {\n stack.pop();\n }\n };\n\n function with_walkers(walkers, cont){\n var save = {}, i;\n for (i in walkers) if (HOP(walkers, i)) {\n save[i] = user[i];\n user[i] = walkers[i];\n }\n var ret = cont();\n for (i in save) if (HOP(save, i)) {\n if (!save[i]) delete user[i];\n else user[i] = save[i];\n }\n return ret;\n };\n\n return {\n walk: walk,\n dive: dive,\n with_walkers: with_walkers,\n parent: function() {\n return stack[stack.length - 2]; // last one is current node\n },\n stack: function() {\n return stack;\n }\n };\n};\n\n/* -----[ Scope and mangling ]----- */\n\nfunction Scope(parent) {\n this.names = {}; // names defined in this scope\n this.mangled = {}; // mangled names (orig.name => mangled)\n this.rev_mangled = {}; // reverse lookup (mangled => orig.name)\n this.cname = -1; // current mangled name\n this.refs = {}; // names referenced from this scope\n this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes\n this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes\n this.directives = []; // directives activated from this scope\n this.parent = parent; // parent scope\n this.children = []; // sub-scopes\n if (parent) {\n this.level = parent.level + 1;\n parent.children.push(this);\n } else {\n this.level = 0;\n }\n};\n\nfunction base54_digits() {\n if (typeof DIGITS_OVERRIDE_FOR_TESTING != \"undefined\")\n return DIGITS_OVERRIDE_FOR_TESTING;\n else\n return \"etnrisouaflchpdvmgybwESxTNCkLAOM_DPHBjFIqRUzWXV$JKQGYZ0516372984\";\n}\n\nvar base54 = (function(){\n var DIGITS = base54_digits();\n return function(num) {\n var ret = \"\", base = 54;\n do {\n ret += DIGITS.charAt(num % base);\n num = Math.floor(num / base);\n base = 64;\n } while (num > 0);\n return ret;\n };\n})();\n\nScope.prototype = {\n has: function(name) {\n for (var s = this; s; s = s.parent)\n if (HOP(s.names, name))\n return s;\n },\n has_mangled: function(mname) {\n for (var s = this; s; s = s.parent)\n if (HOP(s.rev_mangled, mname))\n return s;\n },\n toJSON: function() {\n return {\n names: this.names,\n uses_eval: this.uses_eval,\n uses_with: this.uses_with\n };\n },\n\n next_mangled: function() {\n // we must be careful that the new mangled name:\n //\n // 1. doesn't shadow a mangled name from a parent\n // scope, unless we don't reference the original\n // name from this scope OR from any sub-scopes!\n // This will get slow.\n //\n // 2. doesn't shadow an original name from a parent\n // scope, in the event that the name is not mangled\n // in the parent scope and we reference that name\n // here OR IN ANY SUBSCOPES!\n //\n // 3. doesn't shadow a name that is referenced but not\n // defined (possibly global defined elsewhere).\n for (;;) {\n var m = base54(++this.cname), prior;\n\n // case 1.\n prior = this.has_mangled(m);\n if (prior && this.refs[prior.rev_mangled[m]] === prior)\n continue;\n\n // case 2.\n prior = this.has(m);\n if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))\n continue;\n\n // case 3.\n if (HOP(this.refs, m) && this.refs[m] == null)\n continue;\n\n // I got \"do\" once. :-/\n if (!is_identifier(m))\n continue;\n\n return m;\n }\n },\n set_mangle: function(name, m) {\n this.rev_mangled[m] = name;\n return this.mangled[name] = m;\n },\n get_mangled: function(name, newMangle) {\n if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use\n var s = this.has(name);\n if (!s) return name; // not in visible scope, no mangle\n if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope\n if (!newMangle) return name; // not found and no mangling requested\n return s.set_mangle(name, s.next_mangled());\n },\n references: function(name) {\n return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];\n },\n define: function(name, type) {\n if (name != null) {\n if (type == \"var\" || !HOP(this.names, name))\n this.names[name] = type || \"var\";\n return name;\n }\n },\n active_directive: function(dir) {\n return member(dir, this.directives) || this.parent && this.parent.active_directive(dir);\n }\n};\n\nfunction ast_add_scope(ast) {\n\n var current_scope = null;\n var w = ast_walker(), walk = w.walk;\n var having_eval = [];\n\n function with_new_scope(cont) {\n current_scope = new Scope(current_scope);\n current_scope.labels = new Scope();\n var ret = current_scope.body = cont();\n ret.scope = current_scope;\n current_scope = current_scope.parent;\n return ret;\n };\n\n function define(name, type) {\n return current_scope.define(name, type);\n };\n\n function reference(name) {\n current_scope.refs[name] = true;\n };\n\n function _lambda(name, args, body) {\n var is_defun = this[0] == \"defun\";\n return [ this[0], is_defun ? define(name, \"defun\") : name, args, with_new_scope(function(){\n if (!is_defun) define(name, \"lambda\");\n MAP(args, function(name){ define(name, \"arg\") });\n return MAP(body, walk);\n })];\n };\n\n function _vardefs(type) {\n return function(defs) {\n MAP(defs, function(d){\n define(d[0], type);\n if (d[1]) reference(d[0]);\n });\n };\n };\n\n function _breacont(label) {\n if (label)\n current_scope.labels.refs[label] = true;\n };\n\n return with_new_scope(function(){\n // process AST\n var ret = w.with_walkers({\n \"function\": _lambda,\n \"defun\": _lambda,\n \"label\": function(name, stat) { current_scope.labels.define(name) },\n \"break\": _breacont,\n \"continue\": _breacont,\n \"with\": function(expr, block) {\n for (var s = current_scope; s; s = s.parent)\n s.uses_with = true;\n },\n \"var\": _vardefs(\"var\"),\n \"const\": _vardefs(\"const\"),\n \"try\": function(t, c, f) {\n if (c != null) return [\n this[0],\n MAP(t, walk),\n [ define(c[0], \"catch\"), MAP(c[1], walk) ],\n f != null ? MAP(f, walk) : null\n ];\n },\n \"name\": function(name) {\n if (name == \"eval\")\n having_eval.push(current_scope);\n reference(name);\n }\n }, function(){\n return walk(ast);\n });\n\n // the reason why we need an additional pass here is\n // that names can be used prior to their definition.\n\n // scopes where eval was detected and their parents\n // are marked with uses_eval, unless they define the\n // \"eval\" name.\n MAP(having_eval, function(scope){\n if (!scope.has(\"eval\")) while (scope) {\n scope.uses_eval = true;\n scope = scope.parent;\n }\n });\n\n // for referenced names it might be useful to know\n // their origin scope. current_scope here is the\n // toplevel one.\n function fixrefs(scope, i) {\n // do children first; order shouldn't matter\n for (i = scope.children.length; --i >= 0;)\n fixrefs(scope.children[i]);\n for (i in scope.refs) if (HOP(scope.refs, i)) {\n // find origin scope and propagate the reference to origin\n for (var origin = scope.has(i), s = scope; s; s = s.parent) {\n s.refs[i] = origin;\n if (s === origin) break;\n }\n }\n };\n fixrefs(current_scope);\n\n return ret;\n });\n\n};\n\n/* -----[ mangle names ]----- */\n\nfunction ast_mangle(ast, options) {\n var w = ast_walker(), walk = w.walk, scope;\n options = defaults(options, {\n mangle : true,\n toplevel : false,\n defines : null,\n except : null,\n no_functions : false\n });\n\n function get_mangled(name, newMangle) {\n if (!options.mangle) return name;\n if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel\n if (options.except && member(name, options.except))\n return name;\n if (options.no_functions && HOP(scope.names, name) &&\n (scope.names[name] == 'defun' || scope.names[name] == 'lambda'))\n return name;\n return scope.get_mangled(name, newMangle);\n };\n\n function get_define(name) {\n if (options.defines) {\n // we always lookup a defined symbol for the current scope FIRST, so declared\n // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value\n if (!scope.has(name)) {\n if (HOP(options.defines, name)) {\n return options.defines[name];\n }\n }\n return null;\n }\n };\n\n function _lambda(name, args, body) {\n if (!options.no_functions && options.mangle) {\n var is_defun = this[0] == \"defun\", extra;\n if (name) {\n if (is_defun) name = get_mangled(name);\n else if (body.scope.references(name)) {\n extra = {};\n if (!(scope.uses_eval || scope.uses_with))\n name = extra[name] = scope.next_mangled();\n else\n extra[name] = name;\n }\n else name = null;\n }\n }\n body = with_scope(body.scope, function(){\n args = MAP(args, function(name){ return get_mangled(name) });\n return MAP(body, walk);\n }, extra);\n return [ this[0], name, args, body ];\n };\n\n function with_scope(s, cont, extra) {\n var _scope = scope;\n scope = s;\n if (extra) for (var i in extra) if (HOP(extra, i)) {\n s.set_mangle(i, extra[i]);\n }\n for (var i in s.names) if (HOP(s.names, i)) {\n get_mangled(i, true);\n }\n var ret = cont();\n ret.scope = s;\n scope = _scope;\n return ret;\n };\n\n function _vardefs(defs) {\n return [ this[0], MAP(defs, function(d){\n return [ get_mangled(d[0]), walk(d[1]) ];\n }) ];\n };\n\n function _breacont(label) {\n if (label) return [ this[0], scope.labels.get_mangled(label) ];\n };\n\n return w.with_walkers({\n \"function\": _lambda,\n \"defun\": function() {\n // move function declarations to the top when\n // they are not in some block.\n var ast = _lambda.apply(this, arguments);\n switch (w.parent()[0]) {\n case \"toplevel\":\n case \"function\":\n case \"defun\":\n return MAP.at_top(ast);\n }\n return ast;\n },\n \"label\": function(label, stat) {\n if (scope.labels.refs[label]) return [\n this[0],\n scope.labels.get_mangled(label, true),\n walk(stat)\n ];\n return walk(stat);\n },\n \"break\": _breacont,\n \"continue\": _breacont,\n \"var\": _vardefs,\n \"const\": _vardefs,\n \"name\": function(name) {\n return get_define(name) || [ this[0], get_mangled(name) ];\n },\n \"try\": function(t, c, f) {\n return [ this[0],\n MAP(t, walk),\n c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,\n f != null ? MAP(f, walk) : null ];\n },\n \"toplevel\": function(body) {\n var self = this;\n return with_scope(self.scope, function(){\n return [ self[0], MAP(body, walk) ];\n });\n },\n \"directive\": function() {\n return MAP.at_top(this);\n }\n }, function() {\n return walk(ast_add_scope(ast));\n });\n};\n\n/* -----[\n - compress foo[\"bar\"] into foo.bar,\n - remove block brackets {} where possible\n - join consecutive var declarations\n - various optimizations for IFs:\n - if (cond) foo(); else bar(); ==> cond?foo():bar();\n - if (cond) foo(); ==> cond&&foo();\n - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw\n - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}\n ]----- */\n\nvar warn = function(){};\n\nfunction best_of(ast1, ast2) {\n return gen_code(ast1).length > gen_code(ast2[0] == \"stat\" ? ast2[1] : ast2).length ? ast2 : ast1;\n};\n\nfunction last_stat(b) {\n if (b[0] == \"block\" && b[1] && b[1].length > 0)\n return b[1][b[1].length - 1];\n return b;\n}\n\nfunction aborts(t) {\n if (t) switch (last_stat(t)[0]) {\n case \"return\":\n case \"break\":\n case \"continue\":\n case \"throw\":\n return true;\n }\n};\n\nfunction boolean_expr(expr) {\n return ( (expr[0] == \"unary-prefix\"\n && member(expr[1], [ \"!\", \"delete\" ])) ||\n\n (expr[0] == \"binary\"\n && member(expr[1], [ \"in\", \"instanceof\", \"==\", \"!=\", \"===\", \"!==\", \"<\", \"<=\", \">=\", \">\" ])) ||\n\n (expr[0] == \"binary\"\n && member(expr[1], [ \"&&\", \"||\" ])\n && boolean_expr(expr[2])\n && boolean_expr(expr[3])) ||\n\n (expr[0] == \"conditional\"\n && boolean_expr(expr[2])\n && boolean_expr(expr[3])) ||\n\n (expr[0] == \"assign\"\n && expr[1] === true\n && boolean_expr(expr[3])) ||\n\n (expr[0] == \"seq\"\n && boolean_expr(expr[expr.length - 1]))\n );\n};\n\nfunction empty(b) {\n return !b || (b[0] == \"block\" && (!b[1] || b[1].length == 0));\n};\n\nfunction is_string(node) {\n return (node[0] == \"string\" ||\n node[0] == \"unary-prefix\" && node[1] == \"typeof\" ||\n node[0] == \"binary\" && node[1] == \"+\" &&\n (is_string(node[2]) || is_string(node[3])));\n};\n\nvar when_constant = (function(){\n\n var $NOT_CONSTANT = {};\n\n // this can only evaluate constant expressions. If it finds anything\n // not constant, it throws $NOT_CONSTANT.\n function evaluate(expr) {\n switch (expr[0]) {\n case \"string\":\n case \"num\":\n return expr[1];\n case \"name\":\n case \"atom\":\n switch (expr[1]) {\n case \"true\": return true;\n case \"false\": return false;\n case \"null\": return null;\n }\n break;\n case \"unary-prefix\":\n switch (expr[1]) {\n case \"!\": return !evaluate(expr[2]);\n case \"typeof\": return typeof evaluate(expr[2]);\n case \"~\": return ~evaluate(expr[2]);\n case \"-\": return -evaluate(expr[2]);\n case \"+\": return +evaluate(expr[2]);\n }\n break;\n case \"binary\":\n var left = expr[2], right = expr[3];\n switch (expr[1]) {\n case \"&&\" : return evaluate(left) && evaluate(right);\n case \"||\" : return evaluate(left) || evaluate(right);\n case \"|\" : return evaluate(left) | evaluate(right);\n case \"&\" : return evaluate(left) & evaluate(right);\n case \"^\" : return evaluate(left) ^ evaluate(right);\n case \"+\" : return evaluate(left) + evaluate(right);\n case \"*\" : return evaluate(left) * evaluate(right);\n case \"/\" : return evaluate(left) / evaluate(right);\n case \"%\" : return evaluate(left) % evaluate(right);\n case \"-\" : return evaluate(left) - evaluate(right);\n case \"<<\" : return evaluate(left) << evaluate(right);\n case \">>\" : return evaluate(left) >> evaluate(right);\n case \">>>\" : return evaluate(left) >>> evaluate(right);\n case \"==\" : return evaluate(left) == evaluate(right);\n case \"===\" : return evaluate(left) === evaluate(right);\n case \"!=\" : return evaluate(left) != evaluate(right);\n case \"!==\" : return evaluate(left) !== evaluate(right);\n case \"<\" : return evaluate(left) < evaluate(right);\n case \"<=\" : return evaluate(left) <= evaluate(right);\n case \">\" : return evaluate(left) > evaluate(right);\n case \">=\" : return evaluate(left) >= evaluate(right);\n case \"in\" : return evaluate(left) in evaluate(right);\n case \"instanceof\" : return evaluate(left) instanceof evaluate(right);\n }\n }\n throw $NOT_CONSTANT;\n };\n\n return function(expr, yes, no) {\n try {\n var val = evaluate(expr), ast;\n switch (typeof val) {\n case \"string\": ast = [ \"string\", val ]; break;\n case \"number\": ast = [ \"num\", val ]; break;\n case \"boolean\": ast = [ \"name\", String(val) ]; break;\n default:\n if (val === null) { ast = [ \"atom\", \"null\" ]; break; }\n throw new Error(\"Can't handle constant of type: \" + (typeof val));\n }\n return yes.call(expr, ast, val);\n } catch(ex) {\n if (ex === $NOT_CONSTANT) {\n if (expr[0] == \"binary\"\n && (expr[1] == \"===\" || expr[1] == \"!==\")\n && ((is_string(expr[2]) && is_string(expr[3]))\n || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {\n expr[1] = expr[1].substr(0, 2);\n }\n else if (no && expr[0] == \"binary\"\n && (expr[1] == \"||\" || expr[1] == \"&&\")) {\n // the whole expression is not constant but the lval may be...\n try {\n var lval = evaluate(expr[2]);\n expr = ((expr[1] == \"&&\" && (lval ? expr[3] : lval)) ||\n (expr[1] == \"||\" && (lval ? lval : expr[3])) ||\n expr);\n } catch(ex2) {\n // IGNORE... lval is not constant\n }\n }\n return no ? no.call(expr, expr) : null;\n }\n else throw ex;\n }\n };\n\n})();\n\nfunction warn_unreachable(ast) {\n if (!empty(ast))\n warn(\"Dropping unreachable code: \" + gen_code(ast, true));\n};\n\nfunction prepare_ifs(ast) {\n var w = ast_walker(), walk = w.walk;\n // In this first pass, we rewrite ifs which abort with no else with an\n // if-else. For example:\n //\n // if (x) {\n // blah();\n // return y;\n // }\n // foobar();\n //\n // is rewritten into:\n //\n // if (x) {\n // blah();\n // return y;\n // } else {\n // foobar();\n // }\n function redo_if(statements) {\n statements = MAP(statements, walk);\n\n for (var i = 0; i < statements.length; ++i) {\n var fi = statements[i];\n if (fi[0] != \"if\") continue;\n\n if (fi[3]) continue;\n\n var t = fi[2];\n if (!aborts(t)) continue;\n\n var conditional = walk(fi[1]);\n\n var e_body = redo_if(statements.slice(i + 1));\n var e = e_body.length == 1 ? e_body[0] : [ \"block\", e_body ];\n\n return statements.slice(0, i).concat([ [\n fi[0], // \"if\"\n conditional, // conditional\n t, // then\n e // else\n ] ]);\n }\n\n return statements;\n };\n\n function redo_if_lambda(name, args, body) {\n body = redo_if(body);\n return [ this[0], name, args, body ];\n };\n\n function redo_if_block(statements) {\n return [ this[0], statements != null ? redo_if(statements) : null ];\n };\n\n return w.with_walkers({\n \"defun\": redo_if_lambda,\n \"function\": redo_if_lambda,\n \"block\": redo_if_block,\n \"splice\": redo_if_block,\n \"toplevel\": function(statements) {\n return [ this[0], redo_if(statements) ];\n },\n \"try\": function(t, c, f) {\n return [\n this[0],\n redo_if(t),\n c != null ? [ c[0], redo_if(c[1]) ] : null,\n f != null ? redo_if(f) : null\n ];\n }\n }, function() {\n return walk(ast);\n });\n};\n\nfunction for_side_effects(ast, handler) {\n var w = ast_walker(), walk = w.walk;\n var $stop = {}, $restart = {};\n function stop() { throw $stop };\n function restart() { throw $restart };\n function found(){ return handler.call(this, this, w, stop, restart) };\n function unary(op) {\n if (op == \"++\" || op == \"--\")\n return found.apply(this, arguments);\n };\n function binary(op) {\n if (op == \"&&\" || op == \"||\")\n return found.apply(this, arguments);\n };\n return w.with_walkers({\n \"try\": found,\n \"throw\": found,\n \"return\": found,\n \"new\": found,\n \"switch\": found,\n \"break\": found,\n \"continue\": found,\n \"assign\": found,\n \"call\": found,\n \"if\": found,\n \"for\": found,\n \"for-in\": found,\n \"while\": found,\n \"do\": found,\n \"return\": found,\n \"unary-prefix\": unary,\n \"unary-postfix\": unary,\n \"conditional\": found,\n \"binary\": binary,\n \"defun\": found\n }, function(){\n while (true) try {\n walk(ast);\n break;\n } catch(ex) {\n if (ex === $stop) break;\n if (ex === $restart) continue;\n throw ex;\n }\n });\n};\n\nfunction ast_lift_variables(ast) {\n var w = ast_walker(), walk = w.walk, scope;\n function do_body(body, env) {\n var _scope = scope;\n scope = env;\n body = MAP(body, walk);\n var hash = {}, names = MAP(env.names, function(type, name){\n if (type != \"var\") return MAP.skip;\n if (!env.references(name)) return MAP.skip;\n hash[name] = true;\n return [ name ];\n });\n if (names.length > 0) {\n // looking for assignments to any of these variables.\n // we can save considerable space by moving the definitions\n // in the var declaration.\n for_side_effects([ \"block\", body ], function(ast, walker, stop, restart) {\n if (ast[0] == \"assign\"\n && ast[1] === true\n && ast[2][0] == \"name\"\n && HOP(hash, ast[2][1])) {\n // insert the definition into the var declaration\n for (var i = names.length; --i >= 0;) {\n if (names[i][0] == ast[2][1]) {\n if (names[i][1]) // this name already defined, we must stop\n stop();\n names[i][1] = ast[3]; // definition\n names.push(names.splice(i, 1)[0]);\n break;\n }\n }\n // remove this assignment from the AST.\n var p = walker.parent();\n if (p[0] == \"seq\") {\n var a = p[2];\n a.unshift(0, p.length);\n p.splice.apply(p, a);\n }\n else if (p[0] == \"stat\") {\n p.splice(0, p.length, \"block\"); // empty statement\n }\n else {\n stop();\n }\n restart();\n }\n stop();\n });\n body.unshift([ \"var\", names ]);\n }\n scope = _scope;\n return body;\n };\n function _vardefs(defs) {\n var ret = null;\n for (var i = defs.length; --i >= 0;) {\n var d = defs[i];\n if (!d[1]) continue;\n d = [ \"assign\", true, [ \"name\", d[0] ], d[1] ];\n if (ret == null) ret = d;\n else ret = [ \"seq\", d, ret ];\n }\n if (ret == null && w.parent()[0] != \"for\") {\n if (w.parent()[0] == \"for-in\")\n return [ \"name\", defs[0][0] ];\n return MAP.skip;\n }\n return [ \"stat\", ret ];\n };\n function _toplevel(body) {\n return [ this[0], do_body(body, this.scope) ];\n };\n return w.with_walkers({\n \"function\": function(name, args, body){\n for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)\n args.pop();\n if (!body.scope.references(name)) name = null;\n return [ this[0], name, args, do_body(body, body.scope) ];\n },\n \"defun\": function(name, args, body){\n if (!scope.references(name)) return MAP.skip;\n for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)\n args.pop();\n return [ this[0], name, args, do_body(body, body.scope) ];\n },\n \"var\": _vardefs,\n \"toplevel\": _toplevel\n }, function(){\n return walk(ast_add_scope(ast));\n });\n};\n\nfunction ast_squeeze(ast, options) {\n ast = squeeze_1(ast, options);\n ast = squeeze_2(ast, options);\n return ast;\n};\n\nfunction squeeze_1(ast, options) {\n options = defaults(options, {\n make_seqs : true,\n dead_code : true,\n no_warnings : false,\n keep_comps : true,\n unsafe : false\n });\n\n var w = ast_walker(), walk = w.walk, scope;\n\n function negate(c) {\n var not_c = [ \"unary-prefix\", \"!\", c ];\n switch (c[0]) {\n case \"unary-prefix\":\n return c[1] == \"!\" && boolean_expr(c[2]) ? c[2] : not_c;\n case \"seq\":\n c = slice(c);\n c[c.length - 1] = negate(c[c.length - 1]);\n return c;\n case \"conditional\":\n return best_of(not_c, [ \"conditional\", c[1], negate(c[2]), negate(c[3]) ]);\n case \"binary\":\n var op = c[1], left = c[2], right = c[3];\n if (!options.keep_comps) switch (op) {\n case \"<=\" : return [ \"binary\", \">\", left, right ];\n case \"<\" : return [ \"binary\", \">=\", left, right ];\n case \">=\" : return [ \"binary\", \"<\", left, right ];\n case \">\" : return [ \"binary\", \"<=\", left, right ];\n }\n switch (op) {\n case \"==\" : return [ \"binary\", \"!=\", left, right ];\n case \"!=\" : return [ \"binary\", \"==\", left, right ];\n case \"===\" : return [ \"binary\", \"!==\", left, right ];\n case \"!==\" : return [ \"binary\", \"===\", left, right ];\n case \"&&\" : return best_of(not_c, [ \"binary\", \"||\", negate(left), negate(right) ]);\n case \"||\" : return best_of(not_c, [ \"binary\", \"&&\", negate(left), negate(right) ]);\n }\n break;\n }\n return not_c;\n };\n\n function make_conditional(c, t, e) {\n var make_real_conditional = function() {\n if (c[0] == \"unary-prefix\" && c[1] == \"!\") {\n return e ? [ \"conditional\", c[2], e, t ] : [ \"binary\", \"||\", c[2], t ];\n } else {\n return e ? best_of(\n [ \"conditional\", c, t, e ],\n [ \"conditional\", negate(c), e, t ]\n ) : [ \"binary\", \"&&\", c, t ];\n }\n };\n // shortcut the conditional if the expression has a constant value\n return when_constant(c, function(ast, val){\n warn_unreachable(val ? e : t);\n return (val ? t : e);\n }, make_real_conditional);\n };\n\n function rmblock(block) {\n if (block != null && block[0] == \"block\" && block[1]) {\n if (block[1].length == 1)\n block = block[1][0];\n else if (block[1].length == 0)\n block = [ \"block\" ];\n }\n return block;\n };\n\n function _lambda(name, args, body) {\n return [ this[0], name, args, tighten(body, \"lambda\") ];\n };\n\n // this function does a few things:\n // 1. discard useless blocks\n // 2. join consecutive var declarations\n // 3. remove obviously dead code\n // 4. transform consecutive statements using the comma operator\n // 5. if block_type == \"lambda\" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }\n function tighten(statements, block_type) {\n statements = MAP(statements, walk);\n\n statements = statements.reduce(function(a, stat){\n if (stat[0] == \"block\") {\n if (stat[1]) {\n a.push.apply(a, stat[1]);\n }\n } else {\n a.push(stat);\n }\n return a;\n }, []);\n\n statements = (function(a, prev){\n statements.forEach(function(cur){\n if (prev && ((cur[0] == \"var\" && prev[0] == \"var\") ||\n (cur[0] == \"const\" && prev[0] == \"const\"))) {\n prev[1] = prev[1].concat(cur[1]);\n } else {\n a.push(cur);\n prev = cur;\n }\n });\n return a;\n })([]);\n\n if (options.dead_code) statements = (function(a, has_quit){\n statements.forEach(function(st){\n if (has_quit) {\n if (st[0] == \"function\" || st[0] == \"defun\") {\n a.push(st);\n }\n else if (st[0] == \"var\" || st[0] == \"const\") {\n if (!options.no_warnings)\n warn(\"Variables declared in unreachable code\");\n st[1] = MAP(st[1], function(def){\n if (def[1] && !options.no_warnings)\n warn_unreachable([ \"assign\", true, [ \"name\", def[0] ], def[1] ]);\n return [ def[0] ];\n });\n a.push(st);\n }\n else if (!options.no_warnings)\n warn_unreachable(st);\n }\n else {\n a.push(st);\n if (member(st[0], [ \"return\", \"throw\", \"break\", \"continue\" ]))\n has_quit = true;\n }\n });\n return a;\n })([]);\n\n if (options.make_seqs) statements = (function(a, prev) {\n statements.forEach(function(cur){\n if (prev && prev[0] == \"stat\" && cur[0] == \"stat\") {\n prev[1] = [ \"seq\", prev[1], cur[1] ];\n } else {\n a.push(cur);\n prev = cur;\n }\n });\n if (a.length >= 2\n && a[a.length-2][0] == \"stat\"\n && (a[a.length-1][0] == \"return\" || a[a.length-1][0] == \"throw\")\n && a[a.length-1][1])\n {\n a.splice(a.length - 2, 2,\n [ a[a.length-1][0],\n [ \"seq\", a[a.length-2][1], a[a.length-1][1] ]]);\n }\n return a;\n })([]);\n\n // this increases jQuery by 1K. Probably not such a good idea after all..\n // part of this is done in prepare_ifs anyway.\n // if (block_type == \"lambda\") statements = (function(i, a, stat){\n // while (i < statements.length) {\n // stat = statements[i++];\n // if (stat[0] == \"if\" && !stat[3]) {\n // if (stat[2][0] == \"return\" && stat[2][1] == null) {\n // a.push(make_if(negate(stat[1]), [ \"block\", statements.slice(i) ]));\n // break;\n // }\n // var last = last_stat(stat[2]);\n // if (last[0] == \"return\" && last[1] == null) {\n // a.push(make_if(stat[1], [ \"block\", stat[2][1].slice(0, -1) ], [ \"block\", statements.slice(i) ]));\n // break;\n // }\n // }\n // a.push(stat);\n // }\n // return a;\n // })(0, []);\n\n return statements;\n };\n\n function make_if(c, t, e) {\n return when_constant(c, function(ast, val){\n if (val) {\n t = walk(t);\n warn_unreachable(e);\n return t || [ \"block\" ];\n } else {\n e = walk(e);\n warn_unreachable(t);\n return e || [ \"block\" ];\n }\n }, function() {\n return make_real_if(c, t, e);\n });\n };\n\n function abort_else(c, t, e) {\n var ret = [ [ \"if\", negate(c), e ] ];\n if (t[0] == \"block\") {\n if (t[1]) ret = ret.concat(t[1]);\n } else {\n ret.push(t);\n }\n return walk([ \"block\", ret ]);\n };\n\n function make_real_if(c, t, e) {\n c = walk(c);\n t = walk(t);\n e = walk(e);\n\n if (empty(e) && empty(t))\n return [ \"stat\", c ];\n\n if (empty(t)) {\n c = negate(c);\n t = e;\n e = null;\n } else if (empty(e)) {\n e = null;\n } else {\n // if we have both else and then, maybe it makes sense to switch them?\n (function(){\n var a = gen_code(c);\n var n = negate(c);\n var b = gen_code(n);\n if (b.length < a.length) {\n var tmp = t;\n t = e;\n e = tmp;\n c = n;\n }\n })();\n }\n var ret = [ \"if\", c, t, e ];\n if (t[0] == \"if\" && empty(t[3]) && empty(e)) {\n ret = best_of(ret, walk([ \"if\", [ \"binary\", \"&&\", c, t[1] ], t[2] ]));\n }\n else if (t[0] == \"stat\") {\n if (e) {\n if (e[0] == \"stat\")\n ret = best_of(ret, [ \"stat\", make_conditional(c, t[1], e[1]) ]);\n else if (aborts(e))\n ret = abort_else(c, t, e);\n }\n else {\n ret = best_of(ret, [ \"stat\", make_conditional(c, t[1]) ]);\n }\n }\n else if (e && t[0] == e[0] && (t[0] == \"return\" || t[0] == \"throw\") && t[1] && e[1]) {\n ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);\n }\n else if (e && aborts(t)) {\n ret = [ [ \"if\", c, t ] ];\n if (e[0] == \"block\") {\n if (e[1]) ret = ret.concat(e[1]);\n }\n else {\n ret.push(e);\n }\n ret = walk([ \"block\", ret ]);\n }\n else if (t && aborts(e)) {\n ret = abort_else(c, t, e);\n }\n return ret;\n };\n\n function _do_while(cond, body) {\n return when_constant(cond, function(cond, val){\n if (!val) {\n warn_unreachable(body);\n return [ \"block\" ];\n } else {\n return [ \"for\", null, null, null, walk(body) ];\n }\n });\n };\n\n return w.with_walkers({\n \"sub\": function(expr, subscript) {\n if (subscript[0] == \"string\") {\n var name = subscript[1];\n if (is_identifier(name))\n return [ \"dot\", walk(expr), name ];\n else if (/^[1-9][0-9]*$/.test(name) || name === \"0\")\n return [ \"sub\", walk(expr), [ \"num\", parseInt(name, 10) ] ];\n }\n },\n \"if\": make_if,\n \"toplevel\": function(body) {\n return [ \"toplevel\", tighten(body) ];\n },\n \"switch\": function(expr, body) {\n var last = body.length - 1;\n return [ \"switch\", walk(expr), MAP(body, function(branch, i){\n var block = tighten(branch[1]);\n if (i == last && block.length > 0) {\n var node = block[block.length - 1];\n if (node[0] == \"break\" && !node[1])\n block.pop();\n }\n return [ branch[0] ? walk(branch[0]) : null, block ];\n }) ];\n },\n \"function\": _lambda,\n \"defun\": _lambda,\n \"block\": function(body) {\n if (body) return rmblock([ \"block\", tighten(body) ]);\n },\n \"binary\": function(op, left, right) {\n return when_constant([ \"binary\", op, walk(left), walk(right) ], function yes(c){\n return best_of(walk(c), this);\n }, function no() {\n return function(){\n if(op != \"==\" && op != \"!=\") return;\n var l = walk(left), r = walk(right);\n if(l && l[0] == \"unary-prefix\" && l[1] == \"!\" && l[2][0] == \"num\")\n left = ['num', +!l[2][1]];\n else if (r && r[0] == \"unary-prefix\" && r[1] == \"!\" && r[2][0] == \"num\")\n right = ['num', +!r[2][1]];\n return [\"binary\", op, left, right];\n }() || this;\n });\n },\n \"conditional\": function(c, t, e) {\n return make_conditional(walk(c), walk(t), walk(e));\n },\n \"try\": function(t, c, f) {\n return [\n \"try\",\n tighten(t),\n c != null ? [ c[0], tighten(c[1]) ] : null,\n f != null ? tighten(f) : null\n ];\n },\n \"unary-prefix\": function(op, expr) {\n expr = walk(expr);\n var ret = [ \"unary-prefix\", op, expr ];\n if (op == \"!\")\n ret = best_of(ret, negate(expr));\n return when_constant(ret, function(ast, val){\n return walk(ast); // it's either true or false, so minifies to !0 or !1\n }, function() { return ret });\n },\n \"name\": function(name) {\n switch (name) {\n case \"true\": return [ \"unary-prefix\", \"!\", [ \"num\", 0 ]];\n case \"false\": return [ \"unary-prefix\", \"!\", [ \"num\", 1 ]];\n }\n },\n \"while\": _do_while,\n \"assign\": function(op, lvalue, rvalue) {\n lvalue = walk(lvalue);\n rvalue = walk(rvalue);\n var okOps = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];\n if (op === true && lvalue[0] === \"name\" && rvalue[0] === \"binary\" &&\n ~okOps.indexOf(rvalue[1]) && rvalue[2][0] === \"name\" &&\n rvalue[2][1] === lvalue[1]) {\n return [ this[0], rvalue[1], lvalue, rvalue[3] ]\n }\n return [ this[0], op, lvalue, rvalue ];\n },\n \"call\": function(expr, args) {\n expr = walk(expr);\n if (options.unsafe && expr[0] == \"dot\" && expr[1][0] == \"string\" && expr[2] == \"toString\") {\n return expr[1];\n }\n return [ this[0], expr, MAP(args, walk) ];\n },\n \"num\": function (num) {\n if (!isFinite(num))\n return [ \"binary\", \"/\", num === 1 / 0\n ? [ \"num\", 1 ] : num === -1 / 0\n ? [ \"unary-prefix\", \"-\", [ \"num\", 1 ] ]\n : [ \"num\", 0 ], [ \"num\", 0 ] ];\n\n return [ this[0], num ];\n }\n }, function() {\n return walk(prepare_ifs(walk(prepare_ifs(ast))));\n });\n};\n\nfunction squeeze_2(ast, options) {\n var w = ast_walker(), walk = w.walk, scope;\n function with_scope(s, cont) {\n var save = scope, ret;\n scope = s;\n ret = cont();\n scope = save;\n return ret;\n };\n function lambda(name, args, body) {\n return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];\n };\n return w.with_walkers({\n \"directive\": function(dir) {\n if (scope.active_directive(dir))\n return [ \"block\" ];\n scope.directives.push(dir);\n },\n \"toplevel\": function(body) {\n return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];\n },\n \"function\": lambda,\n \"defun\": lambda\n }, function(){\n return walk(ast_add_scope(ast));\n });\n};\n\n/* -----[ re-generate code from the AST ]----- */\n\nvar DOT_CALL_NO_PARENS = jsp.array_to_hash([\n \"name\",\n \"array\",\n \"object\",\n \"string\",\n \"dot\",\n \"sub\",\n \"call\",\n \"regexp\",\n \"defun\"\n]);\n\nfunction make_string(str, ascii_only) {\n var dq = 0, sq = 0;\n str = str.replace(/[\\\\\\b\\f\\n\\r\\t\\x22\\x27\\u2028\\u2029\\0]/g, function(s){\n switch (s) {\n case \"\\\\\": return \"\\\\\\\\\";\n case \"\\b\": return \"\\\\b\";\n case \"\\f\": return \"\\\\f\";\n case \"\\n\": return \"\\\\n\";\n case \"\\r\": return \"\\\\r\";\n case \"\\u2028\": return \"\\\\u2028\";\n case \"\\u2029\": return \"\\\\u2029\";\n case '\"': ++dq; return '\"';\n case \"'\": ++sq; return \"'\";\n case \"\\0\": return \"\\\\0\";\n }\n return s;\n });\n if (ascii_only) str = to_ascii(str);\n if (dq > sq) return \"'\" + str.replace(/\\x27/g, \"\\\\'\") + \"'\";\n else return '\"' + str.replace(/\\x22/g, '\\\\\"') + '\"';\n};\n\nfunction to_ascii(str) {\n return str.replace(/[\\u0080-\\uffff]/g, function(ch) {\n var code = ch.charCodeAt(0).toString(16);\n while (code.length < 4) code = \"0\" + code;\n return \"\\\\u\" + code;\n });\n};\n\nvar SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ \"if\", \"while\", \"do\", \"for\", \"for-in\", \"with\" ]);\n\nfunction gen_code(ast, options) {\n options = defaults(options, {\n indent_start : 0,\n indent_level : 4,\n quote_keys : false,\n space_colon : false,\n beautify : false,\n ascii_only : false,\n inline_script: false\n });\n var beautify = !!options.beautify;\n var indentation = 0,\n newline = beautify ? \"\\n\" : \"\",\n space = beautify ? \" \" : \"\";\n\n function encode_string(str) {\n var ret = make_string(str, options.ascii_only);\n if (options.inline_script)\n ret = ret.replace(/<\\x2fscript([>\\/\\t\\n\\f\\r ])/gi, \"<\\\\/script$1\");\n return ret;\n };\n\n function make_name(name) {\n name = name.toString();\n if (options.ascii_only)\n name = to_ascii(name);\n return name;\n };\n\n function indent(line) {\n if (line == null)\n line = \"\";\n if (beautify)\n line = repeat_string(\" \", options.indent_start + indentation * options.indent_level) + line;\n return line;\n };\n\n function with_indent(cont, incr) {\n if (incr == null) incr = 1;\n indentation += incr;\n try { return cont.apply(null, slice(arguments, 1)); }\n finally { indentation -= incr; }\n };\n\n function last_char(str) {\n str = str.toString();\n return str.charAt(str.length - 1);\n };\n\n function first_char(str) {\n return str.toString().charAt(0);\n };\n\n function add_spaces(a) {\n if (beautify)\n return a.join(\" \");\n var b = [];\n for (var i = 0; i < a.length; ++i) {\n var next = a[i + 1];\n b.push(a[i]);\n if (next &&\n ((is_identifier_char(last_char(a[i])) && (is_identifier_char(first_char(next))\n || first_char(next) == \"\\\\\")) ||\n (/[\\+\\-]$/.test(a[i].toString()) && /^[\\+\\-]/.test(next.toString()) ||\n last_char(a[i]) == \"/\" && first_char(next) == \"/\"))) {\n b.push(\" \");\n }\n }\n return b.join(\"\");\n };\n\n function add_commas(a) {\n return a.join(\",\" + space);\n };\n\n function parenthesize(expr) {\n var gen = make(expr);\n for (var i = 1; i < arguments.length; ++i) {\n var el = arguments[i];\n if ((el instanceof Function && el(expr)) || expr[0] == el)\n return \"(\" + gen + \")\";\n }\n return gen;\n };\n\n function best_of(a) {\n if (a.length == 1) {\n return a[0];\n }\n if (a.length == 2) {\n var b = a[1];\n a = a[0];\n return a.length <= b.length ? a : b;\n }\n return best_of([ a[0], best_of(a.slice(1)) ]);\n };\n\n function needs_parens(expr) {\n if (expr[0] == \"function\" || expr[0] == \"object\") {\n // dot/call on a literal function requires the\n // function literal itself to be parenthesized\n // only if it's the first \"thing\" in a\n // statement. This means that the parent is\n // \"stat\", but it could also be a \"seq\" and\n // we're the first in this \"seq\" and the\n // parent is \"stat\", and so on. Messy stuff,\n // but it worths the trouble.\n var a = slice(w.stack()), self = a.pop(), p = a.pop();\n while (p) {\n if (p[0] == \"stat\") return true;\n if (((p[0] == \"seq\" || p[0] == \"call\" || p[0] == \"dot\" || p[0] == \"sub\" || p[0] == \"conditional\") && p[1] === self) ||\n ((p[0] == \"binary\" || p[0] == \"assign\" || p[0] == \"unary-postfix\") && p[2] === self)) {\n self = p;\n p = a.pop();\n } else {\n return false;\n }\n }\n }\n return !HOP(DOT_CALL_NO_PARENS, expr[0]);\n };\n\n function make_num(num) {\n var str = num.toString(10), a = [ str.replace(/^0\\./, \".\").replace('e+', 'e') ], m;\n if (Math.floor(num) === num) {\n if (num >= 0) {\n a.push(\"0x\" + num.toString(16).toLowerCase(), // probably pointless\n \"0\" + num.toString(8)); // same.\n } else {\n a.push(\"-0x\" + (-num).toString(16).toLowerCase(), // probably pointless\n \"-0\" + (-num).toString(8)); // same.\n }\n if ((m = /^(.*?)(0+)$/.exec(num))) {\n a.push(m[1] + \"e\" + m[2].length);\n }\n } else if ((m = /^0?\\.(0+)(.*)$/.exec(num))) {\n a.push(m[2] + \"e-\" + (m[1].length + m[2].length),\n str.substr(str.indexOf(\".\")));\n }\n return best_of(a);\n };\n\n var w = ast_walker();\n var make = w.walk;\n return w.with_walkers({\n \"string\": encode_string,\n \"num\": make_num,\n \"name\": make_name,\n \"debugger\": function(){ return \"debugger;\" },\n \"toplevel\": function(statements) {\n return make_block_statements(statements)\n .join(newline + newline);\n },\n \"splice\": function(statements) {\n var parent = w.parent();\n if (HOP(SPLICE_NEEDS_BRACKETS, parent)) {\n // we need block brackets in this case\n return make_block.apply(this, arguments);\n } else {\n return MAP(make_block_statements(statements, true),\n function(line, i) {\n // the first line is already indented\n return i > 0 ? indent(line) : line;\n }).join(newline);\n }\n },\n \"block\": make_block,\n \"var\": function(defs) {\n return \"var \" + add_commas(MAP(defs, make_1vardef)) + \";\";\n },\n \"const\": function(defs) {\n return \"const \" + add_commas(MAP(defs, make_1vardef)) + \";\";\n },\n \"try\": function(tr, ca, fi) {\n var out = [ \"try\", make_block(tr) ];\n if (ca) out.push(\"catch\", \"(\" + ca[0] + \")\", make_block(ca[1]));\n if (fi) out.push(\"finally\", make_block(fi));\n return add_spaces(out);\n },\n \"throw\": function(expr) {\n return add_spaces([ \"throw\", make(expr) ]) + \";\";\n },\n \"new\": function(ctor, args) {\n args = args.length > 0 ? \"(\" + add_commas(MAP(args, function(expr){\n return parenthesize(expr, \"seq\");\n })) + \")\" : \"\";\n return add_spaces([ \"new\", parenthesize(ctor, \"seq\", \"binary\", \"conditional\", \"assign\", function(expr){\n var w = ast_walker(), has_call = {};\n try {\n w.with_walkers({\n \"call\": function() { throw has_call },\n \"function\": function() { return this }\n }, function(){\n w.walk(expr);\n });\n } catch(ex) {\n if (ex === has_call)\n return true;\n throw ex;\n }\n }) + args ]);\n },\n \"switch\": function(expr, body) {\n return add_spaces([ \"switch\", \"(\" + make(expr) + \")\", make_switch_block(body) ]);\n },\n \"break\": function(label) {\n var out = \"break\";\n if (label != null)\n out += \" \" + make_name(label);\n return out + \";\";\n },\n \"continue\": function(label) {\n var out = \"continue\";\n if (label != null)\n out += \" \" + make_name(label);\n return out + \";\";\n },\n \"conditional\": function(co, th, el) {\n return add_spaces([ parenthesize(co, \"assign\", \"seq\", \"conditional\"), \"?\",\n parenthesize(th, \"seq\"), \":\",\n parenthesize(el, \"seq\") ]);\n },\n \"assign\": function(op, lvalue, rvalue) {\n if (op && op !== true) op += \"=\";\n else op = \"=\";\n return add_spaces([ make(lvalue), op, parenthesize(rvalue, \"seq\") ]);\n },\n \"dot\": function(expr) {\n var out = make(expr), i = 1;\n if (expr[0] == \"num\") {\n if (!/[a-f.]/i.test(out))\n out += \".\";\n } else if (expr[0] != \"function\" && needs_parens(expr))\n out = \"(\" + out + \")\";\n while (i < arguments.length)\n out += \".\" + make_name(arguments[i++]);\n return out;\n },\n \"call\": function(func, args) {\n var f = make(func);\n if (f.charAt(0) != \"(\" && needs_parens(func))\n f = \"(\" + f + \")\";\n return f + \"(\" + add_commas(MAP(args, function(expr){\n return parenthesize(expr, \"seq\");\n })) + \")\";\n },\n \"function\": make_function,\n \"defun\": make_function,\n \"if\": function(co, th, el) {\n var out = [ \"if\", \"(\" + make(co) + \")\", el ? make_then(th) : make(th) ];\n if (el) {\n out.push(\"else\", make(el));\n }\n return add_spaces(out);\n },\n \"for\": function(init, cond, step, block) {\n var out = [ \"for\" ];\n init = (init != null ? make(init) : \"\").replace(/;*\\s*$/, \";\" + space);\n cond = (cond != null ? make(cond) : \"\").replace(/;*\\s*$/, \";\" + space);\n step = (step != null ? make(step) : \"\").replace(/;*\\s*$/, \"\");\n var args = init + cond + step;\n if (args == \"; ; \") args = \";;\";\n out.push(\"(\" + args + \")\", make(block));\n return add_spaces(out);\n },\n \"for-in\": function(vvar, key, hash, block) {\n return add_spaces([ \"for\", \"(\" +\n (vvar ? make(vvar).replace(/;+$/, \"\") : make(key)),\n \"in\",\n make(hash) + \")\", make(block) ]);\n },\n \"while\": function(condition, block) {\n return add_spaces([ \"while\", \"(\" + make(condition) + \")\", make(block) ]);\n },\n \"do\": function(condition, block) {\n return add_spaces([ \"do\", make(block), \"while\", \"(\" + make(condition) + \")\" ]) + \";\";\n },\n \"return\": function(expr) {\n var out = [ \"return\" ];\n if (expr != null) out.push(make(expr));\n return add_spaces(out) + \";\";\n },\n \"binary\": function(operator, lvalue, rvalue) {\n var left = make(lvalue), right = make(rvalue);\n // XXX: I'm pretty sure other cases will bite here.\n // we need to be smarter.\n // adding parens all the time is the safest bet.\n if (member(lvalue[0], [ \"assign\", \"conditional\", \"seq\" ]) ||\n lvalue[0] == \"binary\" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]] ||\n lvalue[0] == \"function\" && needs_parens(this)) {\n left = \"(\" + left + \")\";\n }\n if (member(rvalue[0], [ \"assign\", \"conditional\", \"seq\" ]) ||\n rvalue[0] == \"binary\" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&\n !(rvalue[1] == operator && member(operator, [ \"&&\", \"||\", \"*\" ]))) {\n right = \"(\" + right + \")\";\n }\n else if (!beautify && options.inline_script && (operator == \"<\" || operator == \"<<\")\n && rvalue[0] == \"regexp\" && /^script/i.test(rvalue[1])) {\n right = \" \" + right;\n }\n return add_spaces([ left, operator, right ]);\n },\n \"unary-prefix\": function(operator, expr) {\n var val = make(expr);\n if (!(expr[0] == \"num\" || (expr[0] == \"unary-prefix\" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))\n val = \"(\" + val + \")\";\n return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? \" \" : \"\") + val;\n },\n \"unary-postfix\": function(operator, expr) {\n var val = make(expr);\n if (!(expr[0] == \"num\" || (expr[0] == \"unary-postfix\" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))\n val = \"(\" + val + \")\";\n return val + operator;\n },\n \"sub\": function(expr, subscript) {\n var hash = make(expr);\n if (needs_parens(expr))\n hash = \"(\" + hash + \")\";\n return hash + \"[\" + make(subscript) + \"]\";\n },\n \"object\": function(props) {\n var obj_needs_parens = needs_parens(this);\n if (props.length == 0)\n return obj_needs_parens ? \"({})\" : \"{}\";\n var out = \"{\" + newline + with_indent(function(){\n return MAP(props, function(p){\n if (p.length == 3) {\n // getter/setter. The name is in p[0], the arg.list in p[1][2], the\n // body in p[1][3] and type (\"get\" / \"set\") in p[2].\n return indent(make_function(p[0], p[1][2], p[1][3], p[2], true));\n }\n var key = p[0], val = parenthesize(p[1], \"seq\");\n if (options.quote_keys) {\n key = encode_string(key);\n } else if ((typeof key == \"number\" || !beautify && +key + \"\" == key)\n && parseFloat(key) >= 0) {\n key = make_num(+key);\n } else if (!is_identifier(key)) {\n key = encode_string(key);\n }\n return indent(add_spaces(beautify && options.space_colon\n ? [ key, \":\", val ]\n : [ key + \":\", val ]));\n }).join(\",\" + newline);\n }) + newline + indent(\"}\");\n return obj_needs_parens ? \"(\" + out + \")\" : out;\n },\n \"regexp\": function(rx, mods) {\n if (options.ascii_only) rx = to_ascii(rx);\n return \"/\" + rx + \"/\" + mods;\n },\n \"array\": function(elements) {\n if (elements.length == 0) return \"[]\";\n return add_spaces([ \"[\", add_commas(MAP(elements, function(el, i){\n if (!beautify && el[0] == \"atom\" && el[1] == \"undefined\") return i === elements.length - 1 ? \",\" : \"\";\n return parenthesize(el, \"seq\");\n })), \"]\" ]);\n },\n \"stat\": function(stmt) {\n return stmt != null\n ? make(stmt).replace(/;*\\s*$/, \";\")\n : \";\";\n },\n \"seq\": function() {\n return add_commas(MAP(slice(arguments), make));\n },\n \"label\": function(name, block) {\n return add_spaces([ make_name(name), \":\", make(block) ]);\n },\n \"with\": function(expr, block) {\n return add_spaces([ \"with\", \"(\" + make(expr) + \")\", make(block) ]);\n },\n \"atom\": function(name) {\n return make_name(name);\n },\n \"directive\": function(dir) {\n return make_string(dir) + \";\";\n }\n }, function(){ return make(ast) });\n\n // The squeezer replaces \"block\"-s that contain only a single\n // statement with the statement itself; technically, the AST\n // is correct, but this can create problems when we output an\n // IF having an ELSE clause where the THEN clause ends in an\n // IF *without* an ELSE block (then the outer ELSE would refer\n // to the inner IF). This function checks for this case and\n // adds the block brackets if needed.\n function make_then(th) {\n if (th == null) return \";\";\n if (th[0] == \"do\") {\n // https://github.com/mishoo/UglifyJS/issues/#issue/57\n // IE croaks with \"syntax error\" on code like this:\n // if (foo) do ... while(cond); else ...\n // we need block brackets around do/while\n return make_block([ th ]);\n }\n var b = th;\n while (true) {\n var type = b[0];\n if (type == \"if\") {\n if (!b[3])\n // no else, we must add the block\n return make([ \"block\", [ th ]]);\n b = b[3];\n }\n else if (type == \"while\" || type == \"do\") b = b[2];\n else if (type == \"for\" || type == \"for-in\") b = b[4];\n else break;\n }\n return make(th);\n };\n\n function make_function(name, args, body, keyword, no_parens) {\n var out = keyword || \"function\";\n if (name) {\n out += \" \" + make_name(name);\n }\n out += \"(\" + add_commas(MAP(args, make_name)) + \")\";\n out = add_spaces([ out, make_block(body) ]);\n return (!no_parens && needs_parens(this)) ? \"(\" + out + \")\" : out;\n };\n\n function must_has_semicolon(node) {\n switch (node[0]) {\n case \"with\":\n case \"while\":\n return empty(node[2]) || must_has_semicolon(node[2]);\n case \"for\":\n case \"for-in\":\n return empty(node[4]) || must_has_semicolon(node[4]);\n case \"if\":\n if (empty(node[2]) && !node[3]) return true; // `if' with empty `then' and no `else'\n if (node[3]) {\n if (empty(node[3])) return true; // `else' present but empty\n return must_has_semicolon(node[3]); // dive into the `else' branch\n }\n return must_has_semicolon(node[2]); // dive into the `then' branch\n case \"directive\":\n return true;\n }\n };\n\n function make_block_statements(statements, noindent) {\n for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {\n var stat = statements[i];\n var code = make(stat);\n if (code != \";\") {\n if (!beautify && i == last && !must_has_semicolon(stat)) {\n code = code.replace(/;+\\s*$/, \"\");\n }\n a.push(code);\n }\n }\n return noindent ? a : MAP(a, indent);\n };\n\n function make_switch_block(body) {\n var n = body.length;\n if (n == 0) return \"{}\";\n return \"{\" + newline + MAP(body, function(branch, i){\n var has_body = branch[1].length > 0, code = with_indent(function(){\n return indent(branch[0]\n ? add_spaces([ \"case\", make(branch[0]) + \":\" ])\n : \"default:\");\n }, 0.5) + (has_body ? newline + with_indent(function(){\n return make_block_statements(branch[1]).join(newline);\n }) : \"\");\n if (!beautify && has_body && i < n - 1)\n code += \";\";\n return code;\n }).join(newline) + newline + indent(\"}\");\n };\n\n function make_block(statements) {\n if (!statements) return \";\";\n if (statements.length == 0) return \"{}\";\n return \"{\" + newline + with_indent(function(){\n return make_block_statements(statements).join(newline);\n }) + newline + indent(\"}\");\n };\n\n function make_1vardef(def) {\n var name = def[0], val = def[1];\n if (val != null)\n name = add_spaces([ make_name(name), \"=\", parenthesize(val, \"seq\") ]);\n return name;\n };\n\n};\n\nfunction split_lines(code, max_line_length) {\n var splits = [ 0 ];\n jsp.parse(function(){\n var next_token = jsp.tokenizer(code);\n var last_split = 0;\n var prev_token;\n function current_length(tok) {\n return tok.pos - last_split;\n };\n function split_here(tok) {\n last_split = tok.pos;\n splits.push(last_split);\n };\n function custom(){\n var tok = next_token.apply(this, arguments);\n out: {\n if (prev_token) {\n if (prev_token.type == \"keyword\") break out;\n }\n if (current_length(tok) > max_line_length) {\n switch (tok.type) {\n case \"keyword\":\n case \"atom\":\n case \"name\":\n case \"punc\":\n split_here(tok);\n break out;\n }\n }\n }\n prev_token = tok;\n return tok;\n };\n custom.context = function() {\n return next_token.context.apply(this, arguments);\n };\n return custom;\n }());\n return splits.map(function(pos, i){\n return code.substring(pos, splits[i + 1] || code.length);\n }).join(\"\\n\");\n};\n\n/* -----[ Utilities ]----- */\n\nfunction repeat_string(str, i) {\n if (i <= 0) return \"\";\n if (i == 1) return str;\n var d = repeat_string(str, i >> 1);\n d += d;\n if (i & 1) d += str;\n return d;\n};\n\nfunction defaults(args, defs) {\n var ret = {};\n if (args === true)\n args = {};\n for (var i in defs) if (HOP(defs, i)) {\n ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];\n }\n return ret;\n};\n\nfunction is_identifier(name) {\n return /^[a-z_$][a-z0-9_$]*$/i.test(name)\n && name != \"this\"\n && !HOP(jsp.KEYWORDS_ATOM, name)\n && !HOP(jsp.RESERVED_WORDS, name)\n && !HOP(jsp.KEYWORDS, name);\n};\n\nfunction HOP(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n};\n\n// some utilities\n\nvar MAP;\n\n(function(){\n MAP = function(a, f, o) {\n var ret = [], top = [], i;\n function doit() {\n var val = f.call(o, a[i], i);\n if (val instanceof AtTop) {\n val = val.v;\n if (val instanceof Splice) {\n top.push.apply(top, val.v);\n } else {\n top.push(val);\n }\n }\n else if (val != skip) {\n if (val instanceof Splice) {\n ret.push.apply(ret, val.v);\n } else {\n ret.push(val);\n }\n }\n };\n if (a instanceof Array) for (i = 0; i < a.length; ++i) doit();\n else for (i in a) if (HOP(a, i)) doit();\n return top.concat(ret);\n };\n MAP.at_top = function(val) { return new AtTop(val) };\n MAP.splice = function(val) { return new Splice(val) };\n var skip = MAP.skip = {};\n function AtTop(val) { this.v = val };\n function Splice(val) { this.v = val };\n})();\n\n/* -----[ Exports ]----- */\n\nexports.ast_walker = ast_walker;\nexports.ast_mangle = ast_mangle;\nexports.ast_squeeze = ast_squeeze;\nexports.ast_lift_variables = ast_lift_variables;\nexports.gen_code = gen_code;\nexports.ast_add_scope = ast_add_scope;\nexports.set_logger = function(logger) { warn = logger };\nexports.make_string = make_string;\nexports.split_lines = split_lines;\nexports.MAP = MAP;\n\n// keep this last!\nexports.ast_squeeze_more = require(\"./squeeze-more\").ast_squeeze_more;\n\n// Local variables:\n// js-indent-level: 4\n// End:\n});\ndefine('uglifyjs/index', [\"require\", \"exports\", \"module\", \"./parse-js\", \"./process\", \"./consolidator\"], function(require, exports, module) {\n//convienence function(src, [options]);\nfunction uglify(orig_code, options){\n options || (options = {});\n var jsp = uglify.parser;\n var pro = uglify.uglify;\n\n var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST\n ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names\n ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations\n var final_code = pro.gen_code(ast, options.gen_options); // compressed code here\n return final_code;\n};\n\nuglify.parser = require(\"./parse-js\");\nuglify.uglify = require(\"./process\");\nuglify.consolidator = require(\"./consolidator\");\n\nmodule.exports = uglify\n});/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\ndefine('source-map/array-set', function (require, exports, module) {\n\n var util = require('./util');\n\n /**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\n function ArraySet() {\n this._array = [];\n this._set = {};\n }\n\n /**\n * Static method for creating ArraySet instances from an existing array.\n */\n ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n };\n\n /**\n * Add the given string to this set.\n *\n * @param String aStr\n */\n ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var isDuplicate = this.has(aStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n this._set[util.toSetString(aStr)] = idx;\n }\n };\n\n /**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\n ArraySet.prototype.has = function ArraySet_has(aStr) {\n return Object.prototype.hasOwnProperty.call(this._set,\n util.toSetString(aStr));\n };\n\n /**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\n ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (this.has(aStr)) {\n return this._set[util.toSetString(aStr)];\n }\n throw new Error('\"' + aStr + '\" is not in the set.');\n };\n\n /**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\n ArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n };\n\n /**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\n ArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n };\n\n exports.ArraySet = ArraySet;\n\n});\n/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\ndefine('source-map/base64-vlq', function (require, exports, module) {\n\n var base64 = require('./base64');\n\n // A single base 64 digit can contain 6 bits of data. For the base 64 variable\n // length quantities we use in the source map spec, the first bit is the sign,\n // the next four bits are the actual value, and the 6th bit is the\n // continuation bit. The continuation bit tells us whether there are more\n // digits in this value following this digit.\n //\n // Continuation\n // | Sign\n // | |\n // V V\n // 101011\n\n var VLQ_BASE_SHIFT = 5;\n\n // binary: 100000\n var VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n // binary: 011111\n var VLQ_BASE_MASK = VLQ_BASE - 1;\n\n // binary: 100000\n var VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n /**\n * Converts from a two-complement value to a value where the sign bit is\n * is placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\n function toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n }\n\n /**\n * Converts to a two-complement value from a value where the sign bit is\n * is placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\n function fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n }\n\n /**\n * Returns the base 64 VLQ encoded value.\n */\n exports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n };\n\n /**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string.\n */\n exports.decode = function base64VLQ_decode(aStr) {\n var i = 0;\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (i >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n digit = base64.decode(aStr.charAt(i++));\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n return {\n value: fromVLQSigned(result),\n rest: aStr.slice(i)\n };\n };\n\n});\n/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\ndefine('source-map/base64', function (require, exports, module) {\n\n var charToIntMap = {};\n var intToCharMap = {};\n\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n .split('')\n .forEach(function (ch, index) {\n charToIntMap[ch] = index;\n intToCharMap[index] = ch;\n });\n\n /**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\n exports.encode = function base64_encode(aNumber) {\n if (aNumber in intToCharMap) {\n return intToCharMap[aNumber];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + aNumber);\n };\n\n /**\n * Decode a single base 64 digit to an integer.\n */\n exports.decode = function base64_decode(aChar) {\n if (aChar in charToIntMap) {\n return charToIntMap[aChar];\n }\n throw new TypeError(\"Not a valid base 64 digit: \" + aChar);\n };\n\n});\n/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\ndefine('source-map/binary-search', function (require, exports, module) {\n\n /**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n */\n function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the next\n // closest element that is less than that element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element which is less than the one we are searching for, so we\n // return null.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return aHaystack[mid];\n }\n else if (cmp > 0) {\n // aHaystack[mid] is greater than our needle.\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);\n }\n // We did not find an exact match, return the next closest one\n // (termination case 2).\n return aHaystack[mid];\n }\n else {\n // aHaystack[mid] is less than our needle.\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);\n }\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (2) or (3) and return the appropriate thing.\n return aLow < 0\n ? null\n : aHaystack[aLow];\n }\n }\n\n /**\n * This is an implementation of binary search which will always try and return\n * the next lowest value checked if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n */\n exports.search = function search(aNeedle, aHaystack, aCompare) {\n return aHaystack.length > 0\n ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)\n : null;\n };\n\n});\n/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\ndefine('source-map/source-map-consumer', function (require, exports, module) {\n\n var util = require('./util');\n var binarySearch = require('./binary-search');\n var ArraySet = require('./array-set').ArraySet;\n var base64VLQ = require('./base64-vlq');\n\n /**\n * A SourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The only parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\n function SourceMapConsumer(aSourceMap) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = JSON.parse(aSourceMap.replace(/^\\)\\]\\}'/, ''));\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names, true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this.file = file;\n }\n\n /**\n * Create a SourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @returns SourceMapConsumer\n */\n SourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap) {\n var smc = Object.create(SourceMapConsumer.prototype);\n\n smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n\n smc.__generatedMappings = aSourceMap._mappings.slice()\n .sort(util.compareByGeneratedPositions);\n smc.__originalMappings = aSourceMap._mappings.slice()\n .sort(util.compareByOriginalPositions);\n\n return smc;\n };\n\n /**\n * The version of the source mapping spec that we are consuming.\n */\n SourceMapConsumer.prototype._version = 3;\n\n /**\n * The list of original sources.\n */\n Object.defineProperty(SourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._sources.toArray().map(function (s) {\n return this.sourceRoot ? util.join(this.sourceRoot, s) : s;\n }, this);\n }\n });\n\n // `__generatedMappings` and `__originalMappings` are arrays that hold the\n // parsed mapping coordinates from the source map's \"mappings\" attribute. They\n // are lazily instantiated, accessed via the `_generatedMappings` and\n // `_originalMappings` getters respectively, and we only parse the mappings\n // and create these arrays once queried for a source location. We jump through\n // these hoops because there can be many thousands of mappings, and parsing\n // them is expensive, so we only want to do it if we must.\n //\n // Each object in the arrays is of the form:\n //\n // {\n // generatedLine: The line number in the generated code,\n // generatedColumn: The column number in the generated code,\n // source: The path to the original source file that generated this\n // chunk of code,\n // originalLine: The line number in the original source that\n // corresponds to this chunk of generated code,\n // originalColumn: The column number in the original source that\n // corresponds to this chunk of generated code,\n // name: The name of the original symbol which generated this chunk of\n // code.\n // }\n //\n // All properties except for `generatedLine` and `generatedColumn` can be\n // `null`.\n //\n // `_generatedMappings` is ordered by the generated positions.\n //\n // `_originalMappings` is ordered by the original positions.\n\n SourceMapConsumer.prototype.__generatedMappings = null;\n Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n get: function () {\n if (!this.__generatedMappings) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n });\n\n SourceMapConsumer.prototype.__originalMappings = null;\n Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n get: function () {\n if (!this.__originalMappings) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n });\n\n /**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\n SourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var mappingSeparator = /^[,;]/;\n var str = aStr;\n var mapping;\n var temp;\n\n while (str.length > 0) {\n if (str.charAt(0) === ';') {\n generatedLine++;\n str = str.slice(1);\n previousGeneratedColumn = 0;\n }\n else if (str.charAt(0) === ',') {\n str = str.slice(1);\n }\n else {\n mapping = {};\n mapping.generatedLine = generatedLine;\n\n // Generated column.\n temp = base64VLQ.decode(str);\n mapping.generatedColumn = previousGeneratedColumn + temp.value;\n previousGeneratedColumn = mapping.generatedColumn;\n str = temp.rest;\n\n if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {\n // Original source.\n temp = base64VLQ.decode(str);\n mapping.source = this._sources.at(previousSource + temp.value);\n previousSource += temp.value;\n str = temp.rest;\n if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {\n throw new Error('Found a source, but no line and column');\n }\n\n // Original line.\n temp = base64VLQ.decode(str);\n mapping.originalLine = previousOriginalLine + temp.value;\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n str = temp.rest;\n if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {\n throw new Error('Found a source and line, but no column');\n }\n\n // Original column.\n temp = base64VLQ.decode(str);\n mapping.originalColumn = previousOriginalColumn + temp.value;\n previousOriginalColumn = mapping.originalColumn;\n str = temp.rest;\n\n if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {\n // Original name.\n temp = base64VLQ.decode(str);\n mapping.name = this._names.at(previousName + temp.value);\n previousName += temp.value;\n str = temp.rest;\n }\n }\n\n this.__generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n this.__originalMappings.push(mapping);\n }\n }\n }\n\n this.__generatedMappings.sort(util.compareByGeneratedPositions);\n this.__originalMappings.sort(util.compareByOriginalPositions);\n };\n\n /**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\n SourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator);\n };\n\n /**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source.\n * - column: The column number in the generated source.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null.\n * - column: The column number in the original source, or null.\n * - name: The original identifier, or null.\n */\n SourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var mapping = this._findMapping(needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositions);\n\n if (mapping && mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source && this.sourceRoot) {\n source = util.join(this.sourceRoot, source);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: util.getArg(mapping, 'name', null)\n };\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n /**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * availible.\n */\n SourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource) {\n if (!this.sourcesContent) {\n return null;\n }\n\n if (this.sourceRoot) {\n aSource = util.relative(this.sourceRoot, aSource);\n }\n\n if (this._sources.has(aSource)) {\n return this.sourcesContent[this._sources.indexOf(aSource)];\n }\n\n var url;\n if (this.sourceRoot\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = aSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + aSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + aSource)];\n }\n }\n\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n };\n\n /**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source.\n * - column: The column number in the original source.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null.\n * - column: The column number in the generated source, or null.\n */\n SourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n if (this.sourceRoot) {\n needle.source = util.relative(this.sourceRoot, needle.source);\n }\n\n var mapping = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions);\n\n if (mapping) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null)\n };\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n SourceMapConsumer.GENERATED_ORDER = 1;\n SourceMapConsumer.ORIGINAL_ORDER = 2;\n\n /**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\n SourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source;\n if (source && sourceRoot) {\n source = util.join(sourceRoot, source);\n }\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name\n };\n }).forEach(aCallback, context);\n };\n\n exports.SourceMapConsumer = SourceMapConsumer;\n\n});\n/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\ndefine('source-map/source-map-generator', function (require, exports, module) {\n\n var base64VLQ = require('./base64-vlq');\n var util = require('./util');\n var ArraySet = require('./array-set').ArraySet;\n\n /**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\n function SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = [];\n this._sourcesContents = null;\n }\n\n SourceMapGenerator.prototype._version = 3;\n\n /**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\n SourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source) {\n newMapping.source = mapping.source;\n if (sourceRoot) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n /**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\n SourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n this._validateMapping(generated, original, source, name);\n\n if (source && !this._sources.has(source)) {\n this._sources.add(source);\n }\n\n if (name && !this._names.has(name)) {\n this._names.add(name);\n }\n\n this._mappings.push({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n /**\n * Set the source content for a source file.\n */\n SourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent !== null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = {};\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n /**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\n SourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (!aSourceFile) {\n if (!aSourceMapConsumer.file) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n aSourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"aSourceFile\" relative if an absolute Url is passed.\n if (sourceRoot) {\n aSourceFile = util.relative(sourceRoot, aSourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"aSourceFile\"\n this._mappings.forEach(function (mapping) {\n if (mapping.source === aSourceFile && mapping.originalLine) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source !== null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name !== null && mapping.name !== null) {\n // Only use the identifier name if it's an identifier\n // in both SourceMaps\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content) {\n if (sourceRoot) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n /**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\n SourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n /**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\n SourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var mapping;\n\n // The mappings must be guaranteed to be in sorted order before we start\n // serializing them or else the generated line numbers (which are defined\n // via the ';' separators) will be all messed up. Note: it might be more\n // performant to maintain the sorting as we insert them, rather than as we\n // serialize them, but the big O is the same either way.\n this._mappings.sort(util.compareByGeneratedPositions);\n\n for (var i = 0, len = this._mappings.length; i < len; i++) {\n mapping = this._mappings[i];\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n result += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {\n continue;\n }\n result += ',';\n }\n }\n\n result += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source) {\n result += base64VLQ.encode(this._sources.indexOf(mapping.source)\n - previousSource);\n previousSource = this._sources.indexOf(mapping.source);\n\n // lines are stored 0-based in SourceMap spec version 3\n result += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n result += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name) {\n result += base64VLQ.encode(this._names.indexOf(mapping.name)\n - previousName);\n previousName = this._names.indexOf(mapping.name);\n }\n }\n }\n\n return result;\n };\n\n SourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents,\n key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n /**\n * Externalize the source map.\n */\n SourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n file: this._file,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._sourceRoot) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n /**\n * Render the source map being generated to a string.\n */\n SourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this);\n };\n\n exports.SourceMapGenerator = SourceMapGenerator;\n\n});\n/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\ndefine('source-map/source-node', function (require, exports, module) {\n\n var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\n var util = require('./util');\n\n /**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\n function SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine === undefined ? null : aLine;\n this.column = aColumn === undefined ? null : aColumn;\n this.source = aSource === undefined ? null : aSource;\n this.name = aName === undefined ? null : aName;\n if (aChunks != null) this.add(aChunks);\n }\n\n /**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n */\n SourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // The generated code\n // Processed fragments are removed from this array.\n var remainingLines = aGeneratedCode.split('\\n');\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n var code = \"\";\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, remainingLines.shift() + \"\\n\");\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[0];\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[0] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(remainingLines.shift() + \"\\n\");\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[0];\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[0] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLines.length > 0) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n var lastLine = remainingLines.shift();\n if (remainingLines.length > 0) lastLine += \"\\n\";\n addMappingWithCode(lastMapping, lastLine);\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.join(\"\\n\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content) {\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n mapping.source,\n code,\n mapping.name));\n }\n }\n };\n\n /**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\n SourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk instanceof SourceNode || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n };\n\n /**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\n SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk instanceof SourceNode || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n };\n\n /**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\n SourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk instanceof SourceNode) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n };\n\n /**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\n SourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n };\n\n /**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\n SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild instanceof SourceNode) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n };\n\n /**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\n SourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n /**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\n SourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i] instanceof SourceNode) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n /**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\n SourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n };\n\n /**\n * Returns the string representation of this source node along with a source\n * map.\n */\n SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n chunk.split('').forEach(function (ch, idx, array) {\n if (ch === '\\n') {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === array.length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n });\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n };\n\n exports.SourceNode = SourceNode;\n\n});\n/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\ndefine('source-map/util', function (require, exports, module) {\n\n /**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\n function getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n }\n exports.getArg = getArg;\n\n var urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.]*)(?::(\\d+))?(\\S*)$/;\n var dataUrlRegexp = /^data:.+\\,.+$/;\n\n function urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n }\n exports.urlParse = urlParse;\n\n function urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n }\n exports.urlGenerate = urlGenerate;\n\n /**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consequtive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '<dir>/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\n function normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = (path.charAt(0) === '/');\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n }\n exports.normalize = normalize;\n\n /**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\n function join(aRoot, aPath) {\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n }\n exports.join = join;\n\n /**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\n function toSetString(aStr) {\n return '$' + aStr;\n }\n exports.toSetString = toSetString;\n\n function fromSetString(aStr) {\n return aStr.substr(1);\n }\n exports.fromSetString = fromSetString;\n\n function relative(aRoot, aPath) {\n aRoot = aRoot.replace(/\\/$/, '');\n\n var url = urlParse(aRoot);\n if (aPath.charAt(0) == \"/\" && url && url.path == \"/\") {\n return aPath.slice(1);\n }\n\n return aPath.indexOf(aRoot + '/') === 0\n ? aPath.substr(aRoot.length + 1)\n : aPath;\n }\n exports.relative = relative;\n\n function strcmp(aStr1, aStr2) {\n var s1 = aStr1 || \"\";\n var s2 = aStr2 || \"\";\n return (s1 > s2) - (s1 < s2);\n }\n\n /**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\n function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp;\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.name, mappingB.name);\n if (cmp) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return mappingA.generatedColumn - mappingB.generatedColumn;\n };\n exports.compareByOriginalPositions = compareByOriginalPositions;\n\n /**\n * Comparator between two mappings where the generated positions are\n * compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\n function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {\n var cmp;\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n };\n exports.compareByGeneratedPositions = compareByGeneratedPositions;\n\n});\ndefine('source-map', function (require, exports, module) {\n\n/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./source-map/source-node').SourceNode;\n\n});\n\n//Distributed under the BSD license:\n//Copyright 2012 (c) Mihai Bazon <[email protected]>\ndefine('uglifyjs2', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) {\n\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n https://github.com/mishoo/UglifyJS2\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2012 (c) Mihai Bazon <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n\"use strict\";\n\nfunction array_to_hash(a) {\n var ret = Object.create(null);\n for (var i = 0; i < a.length; ++i)\n ret[a[i]] = true;\n return ret;\n};\n\nfunction slice(a, start) {\n return Array.prototype.slice.call(a, start || 0);\n};\n\nfunction characters(str) {\n return str.split(\"\");\n};\n\nfunction member(name, array) {\n for (var i = array.length; --i >= 0;)\n if (array[i] == name)\n return true;\n return false;\n};\n\nfunction find_if(func, array) {\n for (var i = 0, n = array.length; i < n; ++i) {\n if (func(array[i]))\n return array[i];\n }\n};\n\nfunction repeat_string(str, i) {\n if (i <= 0) return \"\";\n if (i == 1) return str;\n var d = repeat_string(str, i >> 1);\n d += d;\n if (i & 1) d += str;\n return d;\n};\n\nfunction DefaultsError(msg, defs) {\n Error.call(this, msg);\n this.msg = msg;\n this.defs = defs;\n};\nDefaultsError.prototype = Object.create(Error.prototype);\nDefaultsError.prototype.constructor = DefaultsError;\n\nDefaultsError.croak = function(msg, defs) {\n throw new DefaultsError(msg, defs);\n};\n\nfunction defaults(args, defs, croak) {\n if (args === true)\n args = {};\n var ret = args || {};\n if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i))\n DefaultsError.croak(\"`\" + i + \"` is not a supported option\", defs);\n for (var i in defs) if (defs.hasOwnProperty(i)) {\n ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i];\n }\n return ret;\n};\n\nfunction merge(obj, ext) {\n for (var i in ext) if (ext.hasOwnProperty(i)) {\n obj[i] = ext[i];\n }\n return obj;\n};\n\nfunction noop() {};\n\nvar MAP = (function(){\n function MAP(a, f, backwards) {\n var ret = [], top = [], i;\n function doit() {\n var val = f(a[i], i);\n var is_last = val instanceof Last;\n if (is_last) val = val.v;\n if (val instanceof AtTop) {\n val = val.v;\n if (val instanceof Splice) {\n top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);\n } else {\n top.push(val);\n }\n }\n else if (val !== skip) {\n if (val instanceof Splice) {\n ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);\n } else {\n ret.push(val);\n }\n }\n return is_last;\n };\n if (a instanceof Array) {\n if (backwards) {\n for (i = a.length; --i >= 0;) if (doit()) break;\n ret.reverse();\n top.reverse();\n } else {\n for (i = 0; i < a.length; ++i) if (doit()) break;\n }\n }\n else {\n for (i in a) if (a.hasOwnProperty(i)) if (doit()) break;\n }\n return top.concat(ret);\n };\n MAP.at_top = function(val) { return new AtTop(val) };\n MAP.splice = function(val) { return new Splice(val) };\n MAP.last = function(val) { return new Last(val) };\n var skip = MAP.skip = {};\n function AtTop(val) { this.v = val };\n function Splice(val) { this.v = val };\n function Last(val) { this.v = val };\n return MAP;\n})();\n\nfunction push_uniq(array, el) {\n if (array.indexOf(el) < 0)\n array.push(el);\n};\n\nfunction string_template(text, props) {\n return text.replace(/\\{(.+?)\\}/g, function(str, p){\n return props[p];\n });\n};\n\nfunction remove(array, el) {\n for (var i = array.length; --i >= 0;) {\n if (array[i] === el) array.splice(i, 1);\n }\n};\n\nfunction mergeSort(array, cmp) {\n if (array.length < 2) return array.slice();\n function merge(a, b) {\n var r = [], ai = 0, bi = 0, i = 0;\n while (ai < a.length && bi < b.length) {\n cmp(a[ai], b[bi]) <= 0\n ? r[i++] = a[ai++]\n : r[i++] = b[bi++];\n }\n if (ai < a.length) r.push.apply(r, a.slice(ai));\n if (bi < b.length) r.push.apply(r, b.slice(bi));\n return r;\n };\n function _ms(a) {\n if (a.length <= 1)\n return a;\n var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);\n left = _ms(left);\n right = _ms(right);\n return merge(left, right);\n };\n return _ms(array);\n};\n\nfunction set_difference(a, b) {\n return a.filter(function(el){\n return b.indexOf(el) < 0;\n });\n};\n\nfunction set_intersection(a, b) {\n return a.filter(function(el){\n return b.indexOf(el) >= 0;\n });\n};\n\n// this function is taken from Acorn [1], written by Marijn Haverbeke\n// [1] https://github.com/marijnh/acorn\nfunction makePredicate(words) {\n if (!(words instanceof Array)) words = words.split(\" \");\n var f = \"\", cats = [];\n out: for (var i = 0; i < words.length; ++i) {\n for (var j = 0; j < cats.length; ++j)\n if (cats[j][0].length == words[i].length) {\n cats[j].push(words[i]);\n continue out;\n }\n cats.push([words[i]]);\n }\n function compareTo(arr) {\n if (arr.length == 1) return f += \"return str === \" + JSON.stringify(arr[0]) + \";\";\n f += \"switch(str){\";\n for (var i = 0; i < arr.length; ++i) f += \"case \" + JSON.stringify(arr[i]) + \":\";\n f += \"return true}return false;\";\n }\n // When there are more than three length categories, an outer\n // switch first dispatches on the lengths, to save on comparisons.\n if (cats.length > 3) {\n cats.sort(function(a, b) {return b.length - a.length;});\n f += \"switch(str.length){\";\n for (var i = 0; i < cats.length; ++i) {\n var cat = cats[i];\n f += \"case \" + cat[0].length + \":\";\n compareTo(cat);\n }\n f += \"}\";\n // Otherwise, simply generate a flat `switch` statement.\n } else {\n compareTo(words);\n }\n return new Function(\"str\", f);\n};\n\nfunction all(array, predicate) {\n for (var i = array.length; --i >= 0;)\n if (!predicate(array[i]))\n return false;\n return true;\n};\n\nfunction Dictionary() {\n this._values = Object.create(null);\n this._size = 0;\n};\nDictionary.prototype = {\n set: function(key, val) {\n if (!this.has(key)) ++this._size;\n this._values[\"$\" + key] = val;\n return this;\n },\n add: function(key, val) {\n if (this.has(key)) {\n this.get(key).push(val);\n } else {\n this.set(key, [ val ]);\n }\n return this;\n },\n get: function(key) { return this._values[\"$\" + key] },\n del: function(key) {\n if (this.has(key)) {\n --this._size;\n delete this._values[\"$\" + key];\n }\n return this;\n },\n has: function(key) { return (\"$\" + key) in this._values },\n each: function(f) {\n for (var i in this._values)\n f(this._values[i], i.substr(1));\n },\n size: function() {\n return this._size;\n },\n map: function(f) {\n var ret = [];\n for (var i in this._values)\n ret.push(f(this._values[i], i.substr(1)));\n return ret;\n }\n};\n\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n https://github.com/mishoo/UglifyJS2\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2012 (c) Mihai Bazon <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n\"use strict\";\n\nfunction DEFNODE(type, props, methods, base) {\n if (arguments.length < 4) base = AST_Node;\n if (!props) props = [];\n else props = props.split(/\\s+/);\n var self_props = props;\n if (base && base.PROPS)\n props = props.concat(base.PROPS);\n var code = \"return function AST_\" + type + \"(props){ if (props) { \";\n for (var i = props.length; --i >= 0;) {\n code += \"this.\" + props[i] + \" = props.\" + props[i] + \";\";\n }\n var proto = base && new base;\n if (proto && proto.initialize || (methods && methods.initialize))\n code += \"this.initialize();\";\n code += \"}}\";\n var ctor = new Function(code)();\n if (proto) {\n ctor.prototype = proto;\n ctor.BASE = base;\n }\n if (base) base.SUBCLASSES.push(ctor);\n ctor.prototype.CTOR = ctor;\n ctor.PROPS = props || null;\n ctor.SELF_PROPS = self_props;\n ctor.SUBCLASSES = [];\n if (type) {\n ctor.prototype.TYPE = ctor.TYPE = type;\n }\n if (methods) for (i in methods) if (methods.hasOwnProperty(i)) {\n if (/^\\$/.test(i)) {\n ctor[i.substr(1)] = methods[i];\n } else {\n ctor.prototype[i] = methods[i];\n }\n }\n ctor.DEFMETHOD = function(name, method) {\n this.prototype[name] = method;\n };\n return ctor;\n};\n\nvar AST_Token = DEFNODE(\"Token\", \"type value line col pos endpos nlb comments_before file\", {\n}, null);\n\nvar AST_Node = DEFNODE(\"Node\", \"start end\", {\n clone: function() {\n return new this.CTOR(this);\n },\n $documentation: \"Base class of all AST nodes\",\n $propdoc: {\n start: \"[AST_Token] The first token of this node\",\n end: \"[AST_Token] The last token of this node\"\n },\n _walk: function(visitor) {\n return visitor._visit(this);\n },\n walk: function(visitor) {\n return this._walk(visitor); // not sure the indirection will be any help\n }\n}, null);\n\nAST_Node.warn_function = null;\nAST_Node.warn = function(txt, props) {\n if (AST_Node.warn_function)\n AST_Node.warn_function(string_template(txt, props));\n};\n\n/* -----[ statements ]----- */\n\nvar AST_Statement = DEFNODE(\"Statement\", null, {\n $documentation: \"Base class of all statements\",\n});\n\nvar AST_Debugger = DEFNODE(\"Debugger\", null, {\n $documentation: \"Represents a debugger statement\",\n}, AST_Statement);\n\nvar AST_Directive = DEFNODE(\"Directive\", \"value scope\", {\n $documentation: \"Represents a directive, like \\\"use strict\\\";\",\n $propdoc: {\n value: \"[string] The value of this directive as a plain string (it's not an AST_String!)\",\n scope: \"[AST_Scope/S] The scope that this directive affects\"\n },\n}, AST_Statement);\n\nvar AST_SimpleStatement = DEFNODE(\"SimpleStatement\", \"body\", {\n $documentation: \"A statement consisting of an expression, i.e. a = 1 + 2\",\n $propdoc: {\n body: \"[AST_Node] an expression node (should not be instanceof AST_Statement)\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.body._walk(visitor);\n });\n }\n}, AST_Statement);\n\nfunction walk_body(node, visitor) {\n if (node.body instanceof AST_Statement) {\n node.body._walk(visitor);\n }\n else node.body.forEach(function(stat){\n stat._walk(visitor);\n });\n};\n\nvar AST_Block = DEFNODE(\"Block\", \"body\", {\n $documentation: \"A body of statements (usually bracketed)\",\n $propdoc: {\n body: \"[AST_Statement*] an array of statements\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n walk_body(this, visitor);\n });\n }\n}, AST_Statement);\n\nvar AST_BlockStatement = DEFNODE(\"BlockStatement\", null, {\n $documentation: \"A block statement\",\n}, AST_Block);\n\nvar AST_EmptyStatement = DEFNODE(\"EmptyStatement\", null, {\n $documentation: \"The empty statement (empty block or simply a semicolon)\",\n _walk: function(visitor) {\n return visitor._visit(this);\n }\n}, AST_Statement);\n\nvar AST_StatementWithBody = DEFNODE(\"StatementWithBody\", \"body\", {\n $documentation: \"Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`\",\n $propdoc: {\n body: \"[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.body._walk(visitor);\n });\n }\n}, AST_Statement);\n\nvar AST_LabeledStatement = DEFNODE(\"LabeledStatement\", \"label\", {\n $documentation: \"Statement with a label\",\n $propdoc: {\n label: \"[AST_Label] a label definition\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.label._walk(visitor);\n this.body._walk(visitor);\n });\n }\n}, AST_StatementWithBody);\n\nvar AST_IterationStatement = DEFNODE(\"IterationStatement\", null, {\n $documentation: \"Internal class. All loops inherit from it.\"\n}, AST_StatementWithBody);\n\nvar AST_DWLoop = DEFNODE(\"DWLoop\", \"condition\", {\n $documentation: \"Base class for do/while statements\",\n $propdoc: {\n condition: \"[AST_Node] the loop condition. Should not be instanceof AST_Statement\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.condition._walk(visitor);\n this.body._walk(visitor);\n });\n }\n}, AST_IterationStatement);\n\nvar AST_Do = DEFNODE(\"Do\", null, {\n $documentation: \"A `do` statement\",\n}, AST_DWLoop);\n\nvar AST_While = DEFNODE(\"While\", null, {\n $documentation: \"A `while` statement\",\n}, AST_DWLoop);\n\nvar AST_For = DEFNODE(\"For\", \"init condition step\", {\n $documentation: \"A `for` statement\",\n $propdoc: {\n init: \"[AST_Node?] the `for` initialization code, or null if empty\",\n condition: \"[AST_Node?] the `for` termination clause, or null if empty\",\n step: \"[AST_Node?] the `for` update clause, or null if empty\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n if (this.init) this.init._walk(visitor);\n if (this.condition) this.condition._walk(visitor);\n if (this.step) this.step._walk(visitor);\n this.body._walk(visitor);\n });\n }\n}, AST_IterationStatement);\n\nvar AST_ForIn = DEFNODE(\"ForIn\", \"init name object\", {\n $documentation: \"A `for ... in` statement\",\n $propdoc: {\n init: \"[AST_Node] the `for/in` initialization code\",\n name: \"[AST_SymbolRef?] the loop variable, only if `init` is AST_Var\",\n object: \"[AST_Node] the object that we're looping through\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.init._walk(visitor);\n this.object._walk(visitor);\n this.body._walk(visitor);\n });\n }\n}, AST_IterationStatement);\n\nvar AST_With = DEFNODE(\"With\", \"expression\", {\n $documentation: \"A `with` statement\",\n $propdoc: {\n expression: \"[AST_Node] the `with` expression\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.expression._walk(visitor);\n this.body._walk(visitor);\n });\n }\n}, AST_StatementWithBody);\n\n/* -----[ scope and functions ]----- */\n\nvar AST_Scope = DEFNODE(\"Scope\", \"directives variables functions uses_with uses_eval parent_scope enclosed cname\", {\n $documentation: \"Base class for all statements introducing a lexical scope\",\n $propdoc: {\n directives: \"[string*/S] an array of directives declared in this scope\",\n variables: \"[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope\",\n functions: \"[Object/S] like `variables`, but only lists function declarations\",\n uses_with: \"[boolean/S] tells whether this scope uses the `with` statement\",\n uses_eval: \"[boolean/S] tells whether this scope contains a direct call to the global `eval`\",\n parent_scope: \"[AST_Scope?/S] link to the parent scope\",\n enclosed: \"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes\",\n cname: \"[integer/S] current index for mangling variables (used internally by the mangler)\",\n },\n}, AST_Block);\n\nvar AST_Toplevel = DEFNODE(\"Toplevel\", \"globals\", {\n $documentation: \"The toplevel scope\",\n $propdoc: {\n globals: \"[Object/S] a map of name -> SymbolDef for all undeclared names\",\n },\n wrap_enclose: function(arg_parameter_pairs) {\n var self = this;\n var args = [];\n var parameters = [];\n\n arg_parameter_pairs.forEach(function(pair) {\n var split = pair.split(\":\");\n\n args.push(split[0]);\n parameters.push(split[1]);\n });\n\n var wrapped_tl = \"(function(\" + parameters.join(\",\") + \"){ '$ORIG'; })(\" + args.join(\",\") + \")\";\n wrapped_tl = parse(wrapped_tl);\n wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){\n if (node instanceof AST_Directive && node.value == \"$ORIG\") {\n return MAP.splice(self.body);\n }\n }));\n return wrapped_tl;\n },\n wrap_commonjs: function(name, export_all) {\n var self = this;\n var to_export = [];\n if (export_all) {\n self.figure_out_scope();\n self.walk(new TreeWalker(function(node){\n if (node instanceof AST_SymbolDeclaration && node.definition().global) {\n if (!find_if(function(n){ return n.name == node.name }, to_export))\n to_export.push(node);\n }\n }));\n }\n var wrapped_tl = \"(function(exports, global){ global['\" + name + \"'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))\";\n wrapped_tl = parse(wrapped_tl);\n wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){\n if (node instanceof AST_SimpleStatement) {\n node = node.body;\n if (node instanceof AST_String) switch (node.getValue()) {\n case \"$ORIG\":\n return MAP.splice(self.body);\n case \"$EXPORTS\":\n var body = [];\n to_export.forEach(function(sym){\n body.push(new AST_SimpleStatement({\n body: new AST_Assign({\n left: new AST_Sub({\n expression: new AST_SymbolRef({ name: \"exports\" }),\n property: new AST_String({ value: sym.name }),\n }),\n operator: \"=\",\n right: new AST_SymbolRef(sym),\n }),\n }));\n });\n return MAP.splice(body);\n }\n }\n }));\n return wrapped_tl;\n }\n}, AST_Scope);\n\nvar AST_Lambda = DEFNODE(\"Lambda\", \"name argnames uses_arguments\", {\n $documentation: \"Base class for functions\",\n $propdoc: {\n name: \"[AST_SymbolDeclaration?] the name of this function\",\n argnames: \"[AST_SymbolFunarg*] array of function arguments\",\n uses_arguments: \"[boolean/S] tells whether this function accesses the arguments array\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n if (this.name) this.name._walk(visitor);\n this.argnames.forEach(function(arg){\n arg._walk(visitor);\n });\n walk_body(this, visitor);\n });\n }\n}, AST_Scope);\n\nvar AST_Accessor = DEFNODE(\"Accessor\", null, {\n $documentation: \"A setter/getter function. The `name` property is always null.\"\n}, AST_Lambda);\n\nvar AST_Function = DEFNODE(\"Function\", null, {\n $documentation: \"A function expression\"\n}, AST_Lambda);\n\nvar AST_Defun = DEFNODE(\"Defun\", null, {\n $documentation: \"A function definition\"\n}, AST_Lambda);\n\n/* -----[ JUMPS ]----- */\n\nvar AST_Jump = DEFNODE(\"Jump\", null, {\n $documentation: \"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)\"\n}, AST_Statement);\n\nvar AST_Exit = DEFNODE(\"Exit\", \"value\", {\n $documentation: \"Base class for “exits” (`return` and `throw`)\",\n $propdoc: {\n value: \"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, this.value && function(){\n this.value._walk(visitor);\n });\n }\n}, AST_Jump);\n\nvar AST_Return = DEFNODE(\"Return\", null, {\n $documentation: \"A `return` statement\"\n}, AST_Exit);\n\nvar AST_Throw = DEFNODE(\"Throw\", null, {\n $documentation: \"A `throw` statement\"\n}, AST_Exit);\n\nvar AST_LoopControl = DEFNODE(\"LoopControl\", \"label\", {\n $documentation: \"Base class for loop control statements (`break` and `continue`)\",\n $propdoc: {\n label: \"[AST_LabelRef?] the label, or null if none\",\n },\n _walk: function(visitor) {\n return visitor._visit(this, this.label && function(){\n this.label._walk(visitor);\n });\n }\n}, AST_Jump);\n\nvar AST_Break = DEFNODE(\"Break\", null, {\n $documentation: \"A `break` statement\"\n}, AST_LoopControl);\n\nvar AST_Continue = DEFNODE(\"Continue\", null, {\n $documentation: \"A `continue` statement\"\n}, AST_LoopControl);\n\n/* -----[ IF ]----- */\n\nvar AST_If = DEFNODE(\"If\", \"condition alternative\", {\n $documentation: \"A `if` statement\",\n $propdoc: {\n condition: \"[AST_Node] the `if` condition\",\n alternative: \"[AST_Statement?] the `else` part, or null if not present\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.condition._walk(visitor);\n this.body._walk(visitor);\n if (this.alternative) this.alternative._walk(visitor);\n });\n }\n}, AST_StatementWithBody);\n\n/* -----[ SWITCH ]----- */\n\nvar AST_Switch = DEFNODE(\"Switch\", \"expression\", {\n $documentation: \"A `switch` statement\",\n $propdoc: {\n expression: \"[AST_Node] the `switch` “discriminant”\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.expression._walk(visitor);\n walk_body(this, visitor);\n });\n }\n}, AST_Block);\n\nvar AST_SwitchBranch = DEFNODE(\"SwitchBranch\", null, {\n $documentation: \"Base class for `switch` branches\",\n}, AST_Block);\n\nvar AST_Default = DEFNODE(\"Default\", null, {\n $documentation: \"A `default` switch branch\",\n}, AST_SwitchBranch);\n\nvar AST_Case = DEFNODE(\"Case\", \"expression\", {\n $documentation: \"A `case` switch branch\",\n $propdoc: {\n expression: \"[AST_Node] the `case` expression\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.expression._walk(visitor);\n walk_body(this, visitor);\n });\n }\n}, AST_SwitchBranch);\n\n/* -----[ EXCEPTIONS ]----- */\n\nvar AST_Try = DEFNODE(\"Try\", \"bcatch bfinally\", {\n $documentation: \"A `try` statement\",\n $propdoc: {\n bcatch: \"[AST_Catch?] the catch block, or null if not present\",\n bfinally: \"[AST_Finally?] the finally block, or null if not present\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n walk_body(this, visitor);\n if (this.bcatch) this.bcatch._walk(visitor);\n if (this.bfinally) this.bfinally._walk(visitor);\n });\n }\n}, AST_Block);\n\nvar AST_Catch = DEFNODE(\"Catch\", \"argname\", {\n $documentation: \"A `catch` node; only makes sense as part of a `try` statement\",\n $propdoc: {\n argname: \"[AST_SymbolCatch] symbol for the exception\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.argname._walk(visitor);\n walk_body(this, visitor);\n });\n }\n}, AST_Block);\n\nvar AST_Finally = DEFNODE(\"Finally\", null, {\n $documentation: \"A `finally` node; only makes sense as part of a `try` statement\"\n}, AST_Block);\n\n/* -----[ VAR/CONST ]----- */\n\nvar AST_Definitions = DEFNODE(\"Definitions\", \"definitions\", {\n $documentation: \"Base class for `var` or `const` nodes (variable declarations/initializations)\",\n $propdoc: {\n definitions: \"[AST_VarDef*] array of variable definitions\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.definitions.forEach(function(def){\n def._walk(visitor);\n });\n });\n }\n}, AST_Statement);\n\nvar AST_Var = DEFNODE(\"Var\", null, {\n $documentation: \"A `var` statement\"\n}, AST_Definitions);\n\nvar AST_Const = DEFNODE(\"Const\", null, {\n $documentation: \"A `const` statement\"\n}, AST_Definitions);\n\nvar AST_VarDef = DEFNODE(\"VarDef\", \"name value\", {\n $documentation: \"A variable declaration; only appears in a AST_Definitions node\",\n $propdoc: {\n name: \"[AST_SymbolVar|AST_SymbolConst] name of the variable\",\n value: \"[AST_Node?] initializer, or null of there's no initializer\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.name._walk(visitor);\n if (this.value) this.value._walk(visitor);\n });\n }\n});\n\n/* -----[ OTHER ]----- */\n\nvar AST_Call = DEFNODE(\"Call\", \"expression args\", {\n $documentation: \"A function call expression\",\n $propdoc: {\n expression: \"[AST_Node] expression to invoke as function\",\n args: \"[AST_Node*] array of arguments\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.expression._walk(visitor);\n this.args.forEach(function(arg){\n arg._walk(visitor);\n });\n });\n }\n});\n\nvar AST_New = DEFNODE(\"New\", null, {\n $documentation: \"An object instantiation. Derives from a function call since it has exactly the same properties\"\n}, AST_Call);\n\nvar AST_Seq = DEFNODE(\"Seq\", \"car cdr\", {\n $documentation: \"A sequence expression (two comma-separated expressions)\",\n $propdoc: {\n car: \"[AST_Node] first element in sequence\",\n cdr: \"[AST_Node] second element in sequence\"\n },\n $cons: function(x, y) {\n var seq = new AST_Seq(x);\n seq.car = x;\n seq.cdr = y;\n return seq;\n },\n $from_array: function(array) {\n if (array.length == 0) return null;\n if (array.length == 1) return array[0].clone();\n var list = null;\n for (var i = array.length; --i >= 0;) {\n list = AST_Seq.cons(array[i], list);\n }\n var p = list;\n while (p) {\n if (p.cdr && !p.cdr.cdr) {\n p.cdr = p.cdr.car;\n break;\n }\n p = p.cdr;\n }\n return list;\n },\n to_array: function() {\n var p = this, a = [];\n while (p) {\n a.push(p.car);\n if (p.cdr && !(p.cdr instanceof AST_Seq)) {\n a.push(p.cdr);\n break;\n }\n p = p.cdr;\n }\n return a;\n },\n add: function(node) {\n var p = this;\n while (p) {\n if (!(p.cdr instanceof AST_Seq)) {\n var cell = AST_Seq.cons(p.cdr, node);\n return p.cdr = cell;\n }\n p = p.cdr;\n }\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.car._walk(visitor);\n if (this.cdr) this.cdr._walk(visitor);\n });\n }\n});\n\nvar AST_PropAccess = DEFNODE(\"PropAccess\", \"expression property\", {\n $documentation: \"Base class for property access expressions, i.e. `a.foo` or `a[\\\"foo\\\"]`\",\n $propdoc: {\n expression: \"[AST_Node] the “container” expression\",\n property: \"[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node\"\n }\n});\n\nvar AST_Dot = DEFNODE(\"Dot\", null, {\n $documentation: \"A dotted property access expression\",\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.expression._walk(visitor);\n });\n }\n}, AST_PropAccess);\n\nvar AST_Sub = DEFNODE(\"Sub\", null, {\n $documentation: \"Index-style property access, i.e. `a[\\\"foo\\\"]`\",\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.expression._walk(visitor);\n this.property._walk(visitor);\n });\n }\n}, AST_PropAccess);\n\nvar AST_Unary = DEFNODE(\"Unary\", \"operator expression\", {\n $documentation: \"Base class for unary expressions\",\n $propdoc: {\n operator: \"[string] the operator\",\n expression: \"[AST_Node] expression that this unary operator applies to\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.expression._walk(visitor);\n });\n }\n});\n\nvar AST_UnaryPrefix = DEFNODE(\"UnaryPrefix\", null, {\n $documentation: \"Unary prefix expression, i.e. `typeof i` or `++i`\"\n}, AST_Unary);\n\nvar AST_UnaryPostfix = DEFNODE(\"UnaryPostfix\", null, {\n $documentation: \"Unary postfix expression, i.e. `i++`\"\n}, AST_Unary);\n\nvar AST_Binary = DEFNODE(\"Binary\", \"left operator right\", {\n $documentation: \"Binary expression, i.e. `a + b`\",\n $propdoc: {\n left: \"[AST_Node] left-hand side expression\",\n operator: \"[string] the operator\",\n right: \"[AST_Node] right-hand side expression\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.left._walk(visitor);\n this.right._walk(visitor);\n });\n }\n});\n\nvar AST_Conditional = DEFNODE(\"Conditional\", \"condition consequent alternative\", {\n $documentation: \"Conditional expression using the ternary operator, i.e. `a ? b : c`\",\n $propdoc: {\n condition: \"[AST_Node]\",\n consequent: \"[AST_Node]\",\n alternative: \"[AST_Node]\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.condition._walk(visitor);\n this.consequent._walk(visitor);\n this.alternative._walk(visitor);\n });\n }\n});\n\nvar AST_Assign = DEFNODE(\"Assign\", null, {\n $documentation: \"An assignment expression — `a = b + 5`\",\n}, AST_Binary);\n\n/* -----[ LITERALS ]----- */\n\nvar AST_Array = DEFNODE(\"Array\", \"elements\", {\n $documentation: \"An array literal\",\n $propdoc: {\n elements: \"[AST_Node*] array of elements\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.elements.forEach(function(el){\n el._walk(visitor);\n });\n });\n }\n});\n\nvar AST_Object = DEFNODE(\"Object\", \"properties\", {\n $documentation: \"An object literal\",\n $propdoc: {\n properties: \"[AST_ObjectProperty*] array of properties\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.properties.forEach(function(prop){\n prop._walk(visitor);\n });\n });\n }\n});\n\nvar AST_ObjectProperty = DEFNODE(\"ObjectProperty\", \"key value\", {\n $documentation: \"Base class for literal object properties\",\n $propdoc: {\n key: \"[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.\",\n value: \"[AST_Node] property value. For setters and getters this is an AST_Function.\"\n },\n _walk: function(visitor) {\n return visitor._visit(this, function(){\n this.value._walk(visitor);\n });\n }\n});\n\nvar AST_ObjectKeyVal = DEFNODE(\"ObjectKeyVal\", null, {\n $documentation: \"A key: value object property\",\n}, AST_ObjectProperty);\n\nvar AST_ObjectSetter = DEFNODE(\"ObjectSetter\", null, {\n $documentation: \"An object setter property\",\n}, AST_ObjectProperty);\n\nvar AST_ObjectGetter = DEFNODE(\"ObjectGetter\", null, {\n $documentation: \"An object getter property\",\n}, AST_ObjectProperty);\n\nvar AST_Symbol = DEFNODE(\"Symbol\", \"scope name thedef\", {\n $propdoc: {\n name: \"[string] name of this symbol\",\n scope: \"[AST_Scope/S] the current scope (not necessarily the definition scope)\",\n thedef: \"[SymbolDef/S] the definition of this symbol\"\n },\n $documentation: \"Base class for all symbols\",\n});\n\nvar AST_SymbolAccessor = DEFNODE(\"SymbolAccessor\", null, {\n $documentation: \"The name of a property accessor (setter/getter function)\"\n}, AST_Symbol);\n\nvar AST_SymbolDeclaration = DEFNODE(\"SymbolDeclaration\", \"init\", {\n $documentation: \"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)\",\n $propdoc: {\n init: \"[AST_Node*/S] array of initializers for this declaration.\"\n }\n}, AST_Symbol);\n\nvar AST_SymbolVar = DEFNODE(\"SymbolVar\", null, {\n $documentation: \"Symbol defining a variable\",\n}, AST_SymbolDeclaration);\n\nvar AST_SymbolConst = DEFNODE(\"SymbolConst\", null, {\n $documentation: \"A constant declaration\"\n}, AST_SymbolDeclaration);\n\nvar AST_SymbolFunarg = DEFNODE(\"SymbolFunarg\", null, {\n $documentation: \"Symbol naming a function argument\",\n}, AST_SymbolVar);\n\nvar AST_SymbolDefun = DEFNODE(\"SymbolDefun\", null, {\n $documentation: \"Symbol defining a function\",\n}, AST_SymbolDeclaration);\n\nvar AST_SymbolLambda = DEFNODE(\"SymbolLambda\", null, {\n $documentation: \"Symbol naming a function expression\",\n}, AST_SymbolDeclaration);\n\nvar AST_SymbolCatch = DEFNODE(\"SymbolCatch\", null, {\n $documentation: \"Symbol naming the exception in catch\",\n}, AST_SymbolDeclaration);\n\nvar AST_Label = DEFNODE(\"Label\", \"references\", {\n $documentation: \"Symbol naming a label (declaration)\",\n $propdoc: {\n references: \"[AST_LoopControl*] a list of nodes referring to this label\"\n },\n initialize: function() {\n this.references = [];\n this.thedef = this;\n }\n}, AST_Symbol);\n\nvar AST_SymbolRef = DEFNODE(\"SymbolRef\", null, {\n $documentation: \"Reference to some symbol (not definition/declaration)\",\n}, AST_Symbol);\n\nvar AST_LabelRef = DEFNODE(\"LabelRef\", null, {\n $documentation: \"Reference to a label symbol\",\n}, AST_Symbol);\n\nvar AST_This = DEFNODE(\"This\", null, {\n $documentation: \"The `this` symbol\",\n}, AST_Symbol);\n\nvar AST_Constant = DEFNODE(\"Constant\", null, {\n $documentation: \"Base class for all constants\",\n getValue: function() {\n return this.value;\n }\n});\n\nvar AST_String = DEFNODE(\"String\", \"value\", {\n $documentation: \"A string literal\",\n $propdoc: {\n value: \"[string] the contents of this string\"\n }\n}, AST_Constant);\n\nvar AST_Number = DEFNODE(\"Number\", \"value\", {\n $documentation: \"A number literal\",\n $propdoc: {\n value: \"[number] the numeric value\"\n }\n}, AST_Constant);\n\nvar AST_RegExp = DEFNODE(\"RegExp\", \"value\", {\n $documentation: \"A regexp literal\",\n $propdoc: {\n value: \"[RegExp] the actual regexp\"\n }\n}, AST_Constant);\n\nvar AST_Atom = DEFNODE(\"Atom\", null, {\n $documentation: \"Base class for atoms\",\n}, AST_Constant);\n\nvar AST_Null = DEFNODE(\"Null\", null, {\n $documentation: \"The `null` atom\",\n value: null\n}, AST_Atom);\n\nvar AST_NaN = DEFNODE(\"NaN\", null, {\n $documentation: \"The impossible value\",\n value: 0/0\n}, AST_Atom);\n\nvar AST_Undefined = DEFNODE(\"Undefined\", null, {\n $documentation: \"The `undefined` value\",\n value: (function(){}())\n}, AST_Atom);\n\nvar AST_Hole = DEFNODE(\"Hole\", null, {\n $documentation: \"A hole in an array\",\n value: (function(){}())\n}, AST_Atom);\n\nvar AST_Infinity = DEFNODE(\"Infinity\", null, {\n $documentation: \"The `Infinity` value\",\n value: 1/0\n}, AST_Atom);\n\nvar AST_Boolean = DEFNODE(\"Boolean\", null, {\n $documentation: \"Base class for booleans\",\n}, AST_Atom);\n\nvar AST_False = DEFNODE(\"False\", null, {\n $documentation: \"The `false` atom\",\n value: false\n}, AST_Boolean);\n\nvar AST_True = DEFNODE(\"True\", null, {\n $documentation: \"The `true` atom\",\n value: true\n}, AST_Boolean);\n\n/* -----[ TreeWalker ]----- */\n\nfunction TreeWalker(callback) {\n this.visit = callback;\n this.stack = [];\n};\nTreeWalker.prototype = {\n _visit: function(node, descend) {\n this.stack.push(node);\n var ret = this.visit(node, descend ? function(){\n descend.call(node);\n } : noop);\n if (!ret && descend) {\n descend.call(node);\n }\n this.stack.pop();\n return ret;\n },\n parent: function(n) {\n return this.stack[this.stack.length - 2 - (n || 0)];\n },\n push: function (node) {\n this.stack.push(node);\n },\n pop: function() {\n return this.stack.pop();\n },\n self: function() {\n return this.stack[this.stack.length - 1];\n },\n find_parent: function(type) {\n var stack = this.stack;\n for (var i = stack.length; --i >= 0;) {\n var x = stack[i];\n if (x instanceof type) return x;\n }\n },\n has_directive: function(type) {\n return this.find_parent(AST_Scope).has_directive(type);\n },\n in_boolean_context: function() {\n var stack = this.stack;\n var i = stack.length, self = stack[--i];\n while (i > 0) {\n var p = stack[--i];\n if ((p instanceof AST_If && p.condition === self) ||\n (p instanceof AST_Conditional && p.condition === self) ||\n (p instanceof AST_DWLoop && p.condition === self) ||\n (p instanceof AST_For && p.condition === self) ||\n (p instanceof AST_UnaryPrefix && p.operator == \"!\" && p.expression === self))\n {\n return true;\n }\n if (!(p instanceof AST_Binary && (p.operator == \"&&\" || p.operator == \"||\")))\n return false;\n self = p;\n }\n },\n loopcontrol_target: function(label) {\n var stack = this.stack;\n if (label) for (var i = stack.length; --i >= 0;) {\n var x = stack[i];\n if (x instanceof AST_LabeledStatement && x.label.name == label.name) {\n return x.body;\n }\n } else for (var i = stack.length; --i >= 0;) {\n var x = stack[i];\n if (x instanceof AST_Switch || x instanceof AST_IterationStatement)\n return x;\n }\n }\n};\n\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n https://github.com/mishoo/UglifyJS2\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2012 (c) Mihai Bazon <[email protected]>\n Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n\"use strict\";\n\nvar KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with';\nvar KEYWORDS_ATOM = 'false null true';\nvar RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized this throws transient volatile yield'\n + \" \" + KEYWORDS_ATOM + \" \" + KEYWORDS;\nvar KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case';\n\nKEYWORDS = makePredicate(KEYWORDS);\nRESERVED_WORDS = makePredicate(RESERVED_WORDS);\nKEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);\nKEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);\n\nvar OPERATOR_CHARS = makePredicate(characters(\"+-*&%=<>!?|~^\"));\n\nvar RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;\nvar RE_OCT_NUMBER = /^0[0-7]+$/;\nvar RE_DEC_NUMBER = /^\\d*\\.?\\d*(?:e[+-]?\\d*(?:\\d\\.?|\\.?\\d)\\d*)?$/i;\n\nvar OPERATORS = makePredicate([\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"new\",\n \"void\",\n \"delete\",\n \"++\",\n \"--\",\n \"+\",\n \"-\",\n \"!\",\n \"~\",\n \"&\",\n \"|\",\n \"^\",\n \"*\",\n \"/\",\n \"%\",\n \">>\",\n \"<<\",\n \">>>\",\n \"<\",\n \">\",\n \"<=\",\n \">=\",\n \"==\",\n \"===\",\n \"!=\",\n \"!==\",\n \"?\",\n \"=\",\n \"+=\",\n \"-=\",\n \"/=\",\n \"*=\",\n \"%=\",\n \">>=\",\n \"<<=\",\n \">>>=\",\n \"|=\",\n \"^=\",\n \"&=\",\n \"&&\",\n \"||\"\n]);\n\nvar WHITESPACE_CHARS = makePredicate(characters(\" \\u00a0\\n\\r\\t\\f\\u000b\\u200b\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\"));\n\nvar PUNC_BEFORE_EXPRESSION = makePredicate(characters(\"[{(,.;:\"));\n\nvar PUNC_CHARS = makePredicate(characters(\"[]{}(),;:\"));\n\nvar REGEXP_MODIFIERS = makePredicate(characters(\"gmsiy\"));\n\n/* -----[ Tokenizer ]----- */\n\n// regexps adapted from http://xregexp.com/plugins/#unicode\nvar UNICODE = {\n letter: new RegExp(\"[\\\\u0041-\\\\u005A\\\\u0061-\\\\u007A\\\\u00AA\\\\u00B5\\\\u00BA\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02C1\\\\u02C6-\\\\u02D1\\\\u02E0-\\\\u02E4\\\\u02EC\\\\u02EE\\\\u0370-\\\\u0374\\\\u0376\\\\u0377\\\\u037A-\\\\u037D\\\\u0386\\\\u0388-\\\\u038A\\\\u038C\\\\u038E-\\\\u03A1\\\\u03A3-\\\\u03F5\\\\u03F7-\\\\u0481\\\\u048A-\\\\u0523\\\\u0531-\\\\u0556\\\\u0559\\\\u0561-\\\\u0587\\\\u05D0-\\\\u05EA\\\\u05F0-\\\\u05F2\\\\u0621-\\\\u064A\\\\u066E\\\\u066F\\\\u0671-\\\\u06D3\\\\u06D5\\\\u06E5\\\\u06E6\\\\u06EE\\\\u06EF\\\\u06FA-\\\\u06FC\\\\u06FF\\\\u0710\\\\u0712-\\\\u072F\\\\u074D-\\\\u07A5\\\\u07B1\\\\u07CA-\\\\u07EA\\\\u07F4\\\\u07F5\\\\u07FA\\\\u0904-\\\\u0939\\\\u093D\\\\u0950\\\\u0958-\\\\u0961\\\\u0971\\\\u0972\\\\u097B-\\\\u097F\\\\u0985-\\\\u098C\\\\u098F\\\\u0990\\\\u0993-\\\\u09A8\\\\u09AA-\\\\u09B0\\\\u09B2\\\\u09B6-\\\\u09B9\\\\u09BD\\\\u09CE\\\\u09DC\\\\u09DD\\\\u09DF-\\\\u09E1\\\\u09F0\\\\u09F1\\\\u0A05-\\\\u0A0A\\\\u0A0F\\\\u0A10\\\\u0A13-\\\\u0A28\\\\u0A2A-\\\\u0A30\\\\u0A32\\\\u0A33\\\\u0A35\\\\u0A36\\\\u0A38\\\\u0A39\\\\u0A59-\\\\u0A5C\\\\u0A5E\\\\u0A72-\\\\u0A74\\\\u0A85-\\\\u0A8D\\\\u0A8F-\\\\u0A91\\\\u0A93-\\\\u0AA8\\\\u0AAA-\\\\u0AB0\\\\u0AB2\\\\u0AB3\\\\u0AB5-\\\\u0AB9\\\\u0ABD\\\\u0AD0\\\\u0AE0\\\\u0AE1\\\\u0B05-\\\\u0B0C\\\\u0B0F\\\\u0B10\\\\u0B13-\\\\u0B28\\\\u0B2A-\\\\u0B30\\\\u0B32\\\\u0B33\\\\u0B35-\\\\u0B39\\\\u0B3D\\\\u0B5C\\\\u0B5D\\\\u0B5F-\\\\u0B61\\\\u0B71\\\\u0B83\\\\u0B85-\\\\u0B8A\\\\u0B8E-\\\\u0B90\\\\u0B92-\\\\u0B95\\\\u0B99\\\\u0B9A\\\\u0B9C\\\\u0B9E\\\\u0B9F\\\\u0BA3\\\\u0BA4\\\\u0BA8-\\\\u0BAA\\\\u0BAE-\\\\u0BB9\\\\u0BD0\\\\u0C05-\\\\u0C0C\\\\u0C0E-\\\\u0C10\\\\u0C12-\\\\u0C28\\\\u0C2A-\\\\u0C33\\\\u0C35-\\\\u0C39\\\\u0C3D\\\\u0C58\\\\u0C59\\\\u0C60\\\\u0C61\\\\u0C85-\\\\u0C8C\\\\u0C8E-\\\\u0C90\\\\u0C92-\\\\u0CA8\\\\u0CAA-\\\\u0CB3\\\\u0CB5-\\\\u0CB9\\\\u0CBD\\\\u0CDE\\\\u0CE0\\\\u0CE1\\\\u0D05-\\\\u0D0C\\\\u0D0E-\\\\u0D10\\\\u0D12-\\\\u0D28\\\\u0D2A-\\\\u0D39\\\\u0D3D\\\\u0D60\\\\u0D61\\\\u0D7A-\\\\u0D7F\\\\u0D85-\\\\u0D96\\\\u0D9A-\\\\u0DB1\\\\u0DB3-\\\\u0DBB\\\\u0DBD\\\\u0DC0-\\\\u0DC6\\\\u0E01-\\\\u0E30\\\\u0E32\\\\u0E33\\\\u0E40-\\\\u0E46\\\\u0E81\\\\u0E82\\\\u0E84\\\\u0E87\\\\u0E88\\\\u0E8A\\\\u0E8D\\\\u0E94-\\\\u0E97\\\\u0E99-\\\\u0E9F\\\\u0EA1-\\\\u0EA3\\\\u0EA5\\\\u0EA7\\\\u0EAA\\\\u0EAB\\\\u0EAD-\\\\u0EB0\\\\u0EB2\\\\u0EB3\\\\u0EBD\\\\u0EC0-\\\\u0EC4\\\\u0EC6\\\\u0EDC\\\\u0EDD\\\\u0F00\\\\u0F40-\\\\u0F47\\\\u0F49-\\\\u0F6C\\\\u0F88-\\\\u0F8B\\\\u1000-\\\\u102A\\\\u103F\\\\u1050-\\\\u1055\\\\u105A-\\\\u105D\\\\u1061\\\\u1065\\\\u1066\\\\u106E-\\\\u1070\\\\u1075-\\\\u1081\\\\u108E\\\\u10A0-\\\\u10C5\\\\u10D0-\\\\u10FA\\\\u10FC\\\\u1100-\\\\u1159\\\\u115F-\\\\u11A2\\\\u11A8-\\\\u11F9\\\\u1200-\\\\u1248\\\\u124A-\\\\u124D\\\\u1250-\\\\u1256\\\\u1258\\\\u125A-\\\\u125D\\\\u1260-\\\\u1288\\\\u128A-\\\\u128D\\\\u1290-\\\\u12B0\\\\u12B2-\\\\u12B5\\\\u12B8-\\\\u12BE\\\\u12C0\\\\u12C2-\\\\u12C5\\\\u12C8-\\\\u12D6\\\\u12D8-\\\\u1310\\\\u1312-\\\\u1315\\\\u1318-\\\\u135A\\\\u1380-\\\\u138F\\\\u13A0-\\\\u13F4\\\\u1401-\\\\u166C\\\\u166F-\\\\u1676\\\\u1681-\\\\u169A\\\\u16A0-\\\\u16EA\\\\u1700-\\\\u170C\\\\u170E-\\\\u1711\\\\u1720-\\\\u1731\\\\u1740-\\\\u1751\\\\u1760-\\\\u176C\\\\u176E-\\\\u1770\\\\u1780-\\\\u17B3\\\\u17D7\\\\u17DC\\\\u1820-\\\\u1877\\\\u1880-\\\\u18A8\\\\u18AA\\\\u1900-\\\\u191C\\\\u1950-\\\\u196D\\\\u1970-\\\\u1974\\\\u1980-\\\\u19A9\\\\u19C1-\\\\u19C7\\\\u1A00-\\\\u1A16\\\\u1B05-\\\\u1B33\\\\u1B45-\\\\u1B4B\\\\u1B83-\\\\u1BA0\\\\u1BAE\\\\u1BAF\\\\u1C00-\\\\u1C23\\\\u1C4D-\\\\u1C4F\\\\u1C5A-\\\\u1C7D\\\\u1D00-\\\\u1DBF\\\\u1E00-\\\\u1F15\\\\u1F18-\\\\u1F1D\\\\u1F20-\\\\u1F45\\\\u1F48-\\\\u1F4D\\\\u1F50-\\\\u1F57\\\\u1F59\\\\u1F5B\\\\u1F5D\\\\u1F5F-\\\\u1F7D\\\\u1F80-\\\\u1FB4\\\\u1FB6-\\\\u1FBC\\\\u1FBE\\\\u1FC2-\\\\u1FC4\\\\u1FC6-\\\\u1FCC\\\\u1FD0-\\\\u1FD3\\\\u1FD6-\\\\u1FDB\\\\u1FE0-\\\\u1FEC\\\\u1FF2-\\\\u1FF4\\\\u1FF6-\\\\u1FFC\\\\u2071\\\\u207F\\\\u2090-\\\\u2094\\\\u2102\\\\u2107\\\\u210A-\\\\u2113\\\\u2115\\\\u2119-\\\\u211D\\\\u2124\\\\u2126\\\\u2128\\\\u212A-\\\\u212D\\\\u212F-\\\\u2139\\\\u213C-\\\\u213F\\\\u2145-\\\\u2149\\\\u214E\\\\u2183\\\\u2184\\\\u2C00-\\\\u2C2E\\\\u2C30-\\\\u2C5E\\\\u2C60-\\\\u2C6F\\\\u2C71-\\\\u2C7D\\\\u2C80-\\\\u2CE4\\\\u2D00-\\\\u2D25\\\\u2D30-\\\\u2D65\\\\u2D6F\\\\u2D80-\\\\u2D96\\\\u2DA0-\\\\u2DA6\\\\u2DA8-\\\\u2DAE\\\\u2DB0-\\\\u2DB6\\\\u2DB8-\\\\u2DBE\\\\u2DC0-\\\\u2DC6\\\\u2DC8-\\\\u2DCE\\\\u2DD0-\\\\u2DD6\\\\u2DD8-\\\\u2DDE\\\\u2E2F\\\\u3005\\\\u3006\\\\u3031-\\\\u3035\\\\u303B\\\\u303C\\\\u3041-\\\\u3096\\\\u309D-\\\\u309F\\\\u30A1-\\\\u30FA\\\\u30FC-\\\\u30FF\\\\u3105-\\\\u312D\\\\u3131-\\\\u318E\\\\u31A0-\\\\u31B7\\\\u31F0-\\\\u31FF\\\\u3400\\\\u4DB5\\\\u4E00\\\\u9FC3\\\\uA000-\\\\uA48C\\\\uA500-\\\\uA60C\\\\uA610-\\\\uA61F\\\\uA62A\\\\uA62B\\\\uA640-\\\\uA65F\\\\uA662-\\\\uA66E\\\\uA67F-\\\\uA697\\\\uA717-\\\\uA71F\\\\uA722-\\\\uA788\\\\uA78B\\\\uA78C\\\\uA7FB-\\\\uA801\\\\uA803-\\\\uA805\\\\uA807-\\\\uA80A\\\\uA80C-\\\\uA822\\\\uA840-\\\\uA873\\\\uA882-\\\\uA8B3\\\\uA90A-\\\\uA925\\\\uA930-\\\\uA946\\\\uAA00-\\\\uAA28\\\\uAA40-\\\\uAA42\\\\uAA44-\\\\uAA4B\\\\uAC00\\\\uD7A3\\\\uF900-\\\\uFA2D\\\\uFA30-\\\\uFA6A\\\\uFA70-\\\\uFAD9\\\\uFB00-\\\\uFB06\\\\uFB13-\\\\uFB17\\\\uFB1D\\\\uFB1F-\\\\uFB28\\\\uFB2A-\\\\uFB36\\\\uFB38-\\\\uFB3C\\\\uFB3E\\\\uFB40\\\\uFB41\\\\uFB43\\\\uFB44\\\\uFB46-\\\\uFBB1\\\\uFBD3-\\\\uFD3D\\\\uFD50-\\\\uFD8F\\\\uFD92-\\\\uFDC7\\\\uFDF0-\\\\uFDFB\\\\uFE70-\\\\uFE74\\\\uFE76-\\\\uFEFC\\\\uFF21-\\\\uFF3A\\\\uFF41-\\\\uFF5A\\\\uFF66-\\\\uFFBE\\\\uFFC2-\\\\uFFC7\\\\uFFCA-\\\\uFFCF\\\\uFFD2-\\\\uFFD7\\\\uFFDA-\\\\uFFDC]\"),\n non_spacing_mark: new RegExp(\"[\\\\u0300-\\\\u036F\\\\u0483-\\\\u0487\\\\u0591-\\\\u05BD\\\\u05BF\\\\u05C1\\\\u05C2\\\\u05C4\\\\u05C5\\\\u05C7\\\\u0610-\\\\u061A\\\\u064B-\\\\u065E\\\\u0670\\\\u06D6-\\\\u06DC\\\\u06DF-\\\\u06E4\\\\u06E7\\\\u06E8\\\\u06EA-\\\\u06ED\\\\u0711\\\\u0730-\\\\u074A\\\\u07A6-\\\\u07B0\\\\u07EB-\\\\u07F3\\\\u0816-\\\\u0819\\\\u081B-\\\\u0823\\\\u0825-\\\\u0827\\\\u0829-\\\\u082D\\\\u0900-\\\\u0902\\\\u093C\\\\u0941-\\\\u0948\\\\u094D\\\\u0951-\\\\u0955\\\\u0962\\\\u0963\\\\u0981\\\\u09BC\\\\u09C1-\\\\u09C4\\\\u09CD\\\\u09E2\\\\u09E3\\\\u0A01\\\\u0A02\\\\u0A3C\\\\u0A41\\\\u0A42\\\\u0A47\\\\u0A48\\\\u0A4B-\\\\u0A4D\\\\u0A51\\\\u0A70\\\\u0A71\\\\u0A75\\\\u0A81\\\\u0A82\\\\u0ABC\\\\u0AC1-\\\\u0AC5\\\\u0AC7\\\\u0AC8\\\\u0ACD\\\\u0AE2\\\\u0AE3\\\\u0B01\\\\u0B3C\\\\u0B3F\\\\u0B41-\\\\u0B44\\\\u0B4D\\\\u0B56\\\\u0B62\\\\u0B63\\\\u0B82\\\\u0BC0\\\\u0BCD\\\\u0C3E-\\\\u0C40\\\\u0C46-\\\\u0C48\\\\u0C4A-\\\\u0C4D\\\\u0C55\\\\u0C56\\\\u0C62\\\\u0C63\\\\u0CBC\\\\u0CBF\\\\u0CC6\\\\u0CCC\\\\u0CCD\\\\u0CE2\\\\u0CE3\\\\u0D41-\\\\u0D44\\\\u0D4D\\\\u0D62\\\\u0D63\\\\u0DCA\\\\u0DD2-\\\\u0DD4\\\\u0DD6\\\\u0E31\\\\u0E34-\\\\u0E3A\\\\u0E47-\\\\u0E4E\\\\u0EB1\\\\u0EB4-\\\\u0EB9\\\\u0EBB\\\\u0EBC\\\\u0EC8-\\\\u0ECD\\\\u0F18\\\\u0F19\\\\u0F35\\\\u0F37\\\\u0F39\\\\u0F71-\\\\u0F7E\\\\u0F80-\\\\u0F84\\\\u0F86\\\\u0F87\\\\u0F90-\\\\u0F97\\\\u0F99-\\\\u0FBC\\\\u0FC6\\\\u102D-\\\\u1030\\\\u1032-\\\\u1037\\\\u1039\\\\u103A\\\\u103D\\\\u103E\\\\u1058\\\\u1059\\\\u105E-\\\\u1060\\\\u1071-\\\\u1074\\\\u1082\\\\u1085\\\\u1086\\\\u108D\\\\u109D\\\\u135F\\\\u1712-\\\\u1714\\\\u1732-\\\\u1734\\\\u1752\\\\u1753\\\\u1772\\\\u1773\\\\u17B7-\\\\u17BD\\\\u17C6\\\\u17C9-\\\\u17D3\\\\u17DD\\\\u180B-\\\\u180D\\\\u18A9\\\\u1920-\\\\u1922\\\\u1927\\\\u1928\\\\u1932\\\\u1939-\\\\u193B\\\\u1A17\\\\u1A18\\\\u1A56\\\\u1A58-\\\\u1A5E\\\\u1A60\\\\u1A62\\\\u1A65-\\\\u1A6C\\\\u1A73-\\\\u1A7C\\\\u1A7F\\\\u1B00-\\\\u1B03\\\\u1B34\\\\u1B36-\\\\u1B3A\\\\u1B3C\\\\u1B42\\\\u1B6B-\\\\u1B73\\\\u1B80\\\\u1B81\\\\u1BA2-\\\\u1BA5\\\\u1BA8\\\\u1BA9\\\\u1C2C-\\\\u1C33\\\\u1C36\\\\u1C37\\\\u1CD0-\\\\u1CD2\\\\u1CD4-\\\\u1CE0\\\\u1CE2-\\\\u1CE8\\\\u1CED\\\\u1DC0-\\\\u1DE6\\\\u1DFD-\\\\u1DFF\\\\u20D0-\\\\u20DC\\\\u20E1\\\\u20E5-\\\\u20F0\\\\u2CEF-\\\\u2CF1\\\\u2DE0-\\\\u2DFF\\\\u302A-\\\\u302F\\\\u3099\\\\u309A\\\\uA66F\\\\uA67C\\\\uA67D\\\\uA6F0\\\\uA6F1\\\\uA802\\\\uA806\\\\uA80B\\\\uA825\\\\uA826\\\\uA8C4\\\\uA8E0-\\\\uA8F1\\\\uA926-\\\\uA92D\\\\uA947-\\\\uA951\\\\uA980-\\\\uA982\\\\uA9B3\\\\uA9B6-\\\\uA9B9\\\\uA9BC\\\\uAA29-\\\\uAA2E\\\\uAA31\\\\uAA32\\\\uAA35\\\\uAA36\\\\uAA43\\\\uAA4C\\\\uAAB0\\\\uAAB2-\\\\uAAB4\\\\uAAB7\\\\uAAB8\\\\uAABE\\\\uAABF\\\\uAAC1\\\\uABE5\\\\uABE8\\\\uABED\\\\uFB1E\\\\uFE00-\\\\uFE0F\\\\uFE20-\\\\uFE26]\"),\n space_combining_mark: new RegExp(\"[\\\\u0903\\\\u093E-\\\\u0940\\\\u0949-\\\\u094C\\\\u094E\\\\u0982\\\\u0983\\\\u09BE-\\\\u09C0\\\\u09C7\\\\u09C8\\\\u09CB\\\\u09CC\\\\u09D7\\\\u0A03\\\\u0A3E-\\\\u0A40\\\\u0A83\\\\u0ABE-\\\\u0AC0\\\\u0AC9\\\\u0ACB\\\\u0ACC\\\\u0B02\\\\u0B03\\\\u0B3E\\\\u0B40\\\\u0B47\\\\u0B48\\\\u0B4B\\\\u0B4C\\\\u0B57\\\\u0BBE\\\\u0BBF\\\\u0BC1\\\\u0BC2\\\\u0BC6-\\\\u0BC8\\\\u0BCA-\\\\u0BCC\\\\u0BD7\\\\u0C01-\\\\u0C03\\\\u0C41-\\\\u0C44\\\\u0C82\\\\u0C83\\\\u0CBE\\\\u0CC0-\\\\u0CC4\\\\u0CC7\\\\u0CC8\\\\u0CCA\\\\u0CCB\\\\u0CD5\\\\u0CD6\\\\u0D02\\\\u0D03\\\\u0D3E-\\\\u0D40\\\\u0D46-\\\\u0D48\\\\u0D4A-\\\\u0D4C\\\\u0D57\\\\u0D82\\\\u0D83\\\\u0DCF-\\\\u0DD1\\\\u0DD8-\\\\u0DDF\\\\u0DF2\\\\u0DF3\\\\u0F3E\\\\u0F3F\\\\u0F7F\\\\u102B\\\\u102C\\\\u1031\\\\u1038\\\\u103B\\\\u103C\\\\u1056\\\\u1057\\\\u1062-\\\\u1064\\\\u1067-\\\\u106D\\\\u1083\\\\u1084\\\\u1087-\\\\u108C\\\\u108F\\\\u109A-\\\\u109C\\\\u17B6\\\\u17BE-\\\\u17C5\\\\u17C7\\\\u17C8\\\\u1923-\\\\u1926\\\\u1929-\\\\u192B\\\\u1930\\\\u1931\\\\u1933-\\\\u1938\\\\u19B0-\\\\u19C0\\\\u19C8\\\\u19C9\\\\u1A19-\\\\u1A1B\\\\u1A55\\\\u1A57\\\\u1A61\\\\u1A63\\\\u1A64\\\\u1A6D-\\\\u1A72\\\\u1B04\\\\u1B35\\\\u1B3B\\\\u1B3D-\\\\u1B41\\\\u1B43\\\\u1B44\\\\u1B82\\\\u1BA1\\\\u1BA6\\\\u1BA7\\\\u1BAA\\\\u1C24-\\\\u1C2B\\\\u1C34\\\\u1C35\\\\u1CE1\\\\u1CF2\\\\uA823\\\\uA824\\\\uA827\\\\uA880\\\\uA881\\\\uA8B4-\\\\uA8C3\\\\uA952\\\\uA953\\\\uA983\\\\uA9B4\\\\uA9B5\\\\uA9BA\\\\uA9BB\\\\uA9BD-\\\\uA9C0\\\\uAA2F\\\\uAA30\\\\uAA33\\\\uAA34\\\\uAA4D\\\\uAA7B\\\\uABE3\\\\uABE4\\\\uABE6\\\\uABE7\\\\uABE9\\\\uABEA\\\\uABEC]\"),\n connector_punctuation: new RegExp(\"[\\\\u005F\\\\u203F\\\\u2040\\\\u2054\\\\uFE33\\\\uFE34\\\\uFE4D-\\\\uFE4F\\\\uFF3F]\")\n};\n\nfunction is_letter(code) {\n return (code >= 97 && code <= 122)\n || (code >= 65 && code <= 90)\n || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code)));\n};\n\nfunction is_digit(code) {\n return code >= 48 && code <= 57; //XXX: find out if \"UnicodeDigit\" means something else than 0..9\n};\n\nfunction is_alphanumeric_char(code) {\n return is_digit(code) || is_letter(code);\n};\n\nfunction is_unicode_combining_mark(ch) {\n return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);\n};\n\nfunction is_unicode_connector_punctuation(ch) {\n return UNICODE.connector_punctuation.test(ch);\n};\n\nfunction is_identifier(name) {\n return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name);\n};\n\nfunction is_identifier_start(code) {\n return code == 36 || code == 95 || is_letter(code);\n};\n\nfunction is_identifier_char(ch) {\n var code = ch.charCodeAt(0);\n return is_identifier_start(code)\n || is_digit(code)\n || code == 8204 // \\u200c: zero-width non-joiner <ZWNJ>\n || code == 8205 // \\u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)\n || is_unicode_combining_mark(ch)\n || is_unicode_connector_punctuation(ch)\n ;\n};\n\nfunction is_identifier_string(str){\n var i = str.length;\n if (i == 0) return false;\n if (!is_identifier_start(str.charCodeAt(0))) return false;\n while (--i >= 0) {\n if (!is_identifier_char(str.charAt(i)))\n return false;\n }\n return true;\n};\n\nfunction parse_js_number(num) {\n if (RE_HEX_NUMBER.test(num)) {\n return parseInt(num.substr(2), 16);\n } else if (RE_OCT_NUMBER.test(num)) {\n return parseInt(num.substr(1), 8);\n } else if (RE_DEC_NUMBER.test(num)) {\n return parseFloat(num);\n }\n};\n\nfunction JS_Parse_Error(message, line, col, pos) {\n this.message = message;\n this.line = line;\n this.col = col;\n this.pos = pos;\n this.stack = new Error().stack;\n};\n\nJS_Parse_Error.prototype.toString = function() {\n return this.message + \" (line: \" + this.line + \", col: \" + this.col + \", pos: \" + this.pos + \")\" + \"\\n\\n\" + this.stack;\n};\n\nfunction js_error(message, filename, line, col, pos) {\n throw new JS_Parse_Error(message, line, col, pos);\n};\n\nfunction is_token(token, type, val) {\n return token.type == type && (val == null || token.value == val);\n};\n\nvar EX_EOF = {};\n\nfunction tokenizer($TEXT, filename, html5_comments) {\n\n var S = {\n text : $TEXT.replace(/\\r\\n?|[\\n\\u2028\\u2029]/g, \"\\n\").replace(/\\uFEFF/g, ''),\n filename : filename,\n pos : 0,\n tokpos : 0,\n line : 1,\n tokline : 0,\n col : 0,\n tokcol : 0,\n newline_before : false,\n regex_allowed : false,\n comments_before : []\n };\n\n function peek() { return S.text.charAt(S.pos); };\n\n function next(signal_eof, in_string) {\n var ch = S.text.charAt(S.pos++);\n if (signal_eof && !ch)\n throw EX_EOF;\n if (ch == \"\\n\") {\n S.newline_before = S.newline_before || !in_string;\n ++S.line;\n S.col = 0;\n } else {\n ++S.col;\n }\n return ch;\n };\n\n function forward(i) {\n while (i-- > 0) next();\n };\n\n function looking_at(str) {\n return S.text.substr(S.pos, str.length) == str;\n };\n\n function find(what, signal_eof) {\n var pos = S.text.indexOf(what, S.pos);\n if (signal_eof && pos == -1) throw EX_EOF;\n return pos;\n };\n\n function start_token() {\n S.tokline = S.line;\n S.tokcol = S.col;\n S.tokpos = S.pos;\n };\n\n var prev_was_dot = false;\n function token(type, value, is_comment) {\n S.regex_allowed = ((type == \"operator\" && !UNARY_POSTFIX(value)) ||\n (type == \"keyword\" && KEYWORDS_BEFORE_EXPRESSION(value)) ||\n (type == \"punc\" && PUNC_BEFORE_EXPRESSION(value)));\n prev_was_dot = (type == \"punc\" && value == \".\");\n var ret = {\n type : type,\n value : value,\n line : S.tokline,\n col : S.tokcol,\n pos : S.tokpos,\n endpos : S.pos,\n nlb : S.newline_before,\n file : filename\n };\n if (!is_comment) {\n ret.comments_before = S.comments_before;\n S.comments_before = [];\n // make note of any newlines in the comments that came before\n for (var i = 0, len = ret.comments_before.length; i < len; i++) {\n ret.nlb = ret.nlb || ret.comments_before[i].nlb;\n }\n }\n S.newline_before = false;\n return new AST_Token(ret);\n };\n\n function skip_whitespace() {\n while (WHITESPACE_CHARS(peek()))\n next();\n };\n\n function read_while(pred) {\n var ret = \"\", ch, i = 0;\n while ((ch = peek()) && pred(ch, i++))\n ret += next();\n return ret;\n };\n\n function parse_error(err) {\n js_error(err, filename, S.tokline, S.tokcol, S.tokpos);\n };\n\n function read_num(prefix) {\n var has_e = false, after_e = false, has_x = false, has_dot = prefix == \".\";\n var num = read_while(function(ch, i){\n var code = ch.charCodeAt(0);\n switch (code) {\n case 120: case 88: // xX\n return has_x ? false : (has_x = true);\n case 101: case 69: // eE\n return has_x ? true : has_e ? false : (has_e = after_e = true);\n case 45: // -\n return after_e || (i == 0 && !prefix);\n case 43: // +\n return after_e;\n case (after_e = false, 46): // .\n return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false;\n }\n return is_alphanumeric_char(code);\n });\n if (prefix) num = prefix + num;\n var valid = parse_js_number(num);\n if (!isNaN(valid)) {\n return token(\"num\", valid);\n } else {\n parse_error(\"Invalid syntax: \" + num);\n }\n };\n\n function read_escaped_char(in_string) {\n var ch = next(true, in_string);\n switch (ch.charCodeAt(0)) {\n case 110 : return \"\\n\";\n case 114 : return \"\\r\";\n case 116 : return \"\\t\";\n case 98 : return \"\\b\";\n case 118 : return \"\\u000b\"; // \\v\n case 102 : return \"\\f\";\n case 48 : return \"\\0\";\n case 120 : return String.fromCharCode(hex_bytes(2)); // \\x\n case 117 : return String.fromCharCode(hex_bytes(4)); // \\u\n case 10 : return \"\"; // newline\n default : return ch;\n }\n };\n\n function hex_bytes(n) {\n var num = 0;\n for (; n > 0; --n) {\n var digit = parseInt(next(true), 16);\n if (isNaN(digit))\n parse_error(\"Invalid hex-character pattern in string\");\n num = (num << 4) | digit;\n }\n return num;\n };\n\n var read_string = with_eof_error(\"Unterminated string constant\", function(){\n var quote = next(), ret = \"\";\n for (;;) {\n var ch = next(true);\n if (ch == \"\\\\\") {\n // read OctalEscapeSequence (XXX: deprecated if \"strict mode\")\n // https://github.com/mishoo/UglifyJS/issues/178\n var octal_len = 0, first = null;\n ch = read_while(function(ch){\n if (ch >= \"0\" && ch <= \"7\") {\n if (!first) {\n first = ch;\n return ++octal_len;\n }\n else if (first <= \"3\" && octal_len <= 2) return ++octal_len;\n else if (first >= \"4\" && octal_len <= 1) return ++octal_len;\n }\n return false;\n });\n if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));\n else ch = read_escaped_char(true);\n }\n else if (ch == quote) break;\n ret += ch;\n }\n return token(\"string\", ret);\n });\n\n function skip_line_comment(type) {\n var regex_allowed = S.regex_allowed;\n var i = find(\"\\n\"), ret;\n if (i == -1) {\n ret = S.text.substr(S.pos);\n S.pos = S.text.length;\n } else {\n ret = S.text.substring(S.pos, i);\n S.pos = i;\n }\n S.comments_before.push(token(type, ret, true));\n S.regex_allowed = regex_allowed;\n return next_token();\n };\n\n var skip_multiline_comment = with_eof_error(\"Unterminated multiline comment\", function(){\n var regex_allowed = S.regex_allowed;\n var i = find(\"*/\", true);\n var text = S.text.substring(S.pos, i);\n var a = text.split(\"\\n\"), n = a.length;\n // update stream position\n S.pos = i + 2;\n S.line += n - 1;\n if (n > 1) S.col = a[n - 1].length;\n else S.col += a[n - 1].length;\n S.col += 2;\n var nlb = S.newline_before = S.newline_before || text.indexOf(\"\\n\") >= 0;\n S.comments_before.push(token(\"comment2\", text, true));\n S.regex_allowed = regex_allowed;\n S.newline_before = nlb;\n return next_token();\n });\n\n function read_name() {\n var backslash = false, name = \"\", ch, escaped = false, hex;\n while ((ch = peek()) != null) {\n if (!backslash) {\n if (ch == \"\\\\\") escaped = backslash = true, next();\n else if (is_identifier_char(ch)) name += next();\n else break;\n }\n else {\n if (ch != \"u\") parse_error(\"Expecting UnicodeEscapeSequence -- uXXXX\");\n ch = read_escaped_char();\n if (!is_identifier_char(ch)) parse_error(\"Unicode char: \" + ch.charCodeAt(0) + \" is not valid in identifier\");\n name += ch;\n backslash = false;\n }\n }\n if (KEYWORDS(name) && escaped) {\n hex = name.charCodeAt(0).toString(16).toUpperCase();\n name = \"\\\\u\" + \"0000\".substr(hex.length) + hex + name.slice(1);\n }\n return name;\n };\n\n var read_regexp = with_eof_error(\"Unterminated regular expression\", function(regexp){\n var prev_backslash = false, ch, in_class = false;\n while ((ch = next(true))) if (prev_backslash) {\n regexp += \"\\\\\" + ch;\n prev_backslash = false;\n } else if (ch == \"[\") {\n in_class = true;\n regexp += ch;\n } else if (ch == \"]\" && in_class) {\n in_class = false;\n regexp += ch;\n } else if (ch == \"/\" && !in_class) {\n break;\n } else if (ch == \"\\\\\") {\n prev_backslash = true;\n } else {\n regexp += ch;\n }\n var mods = read_name();\n return token(\"regexp\", new RegExp(regexp, mods));\n });\n\n function read_operator(prefix) {\n function grow(op) {\n if (!peek()) return op;\n var bigger = op + peek();\n if (OPERATORS(bigger)) {\n next();\n return grow(bigger);\n } else {\n return op;\n }\n };\n return token(\"operator\", grow(prefix || next()));\n };\n\n function handle_slash() {\n next();\n switch (peek()) {\n case \"/\":\n next();\n return skip_line_comment(\"comment1\");\n case \"*\":\n next();\n return skip_multiline_comment();\n }\n return S.regex_allowed ? read_regexp(\"\") : read_operator(\"/\");\n };\n\n function handle_dot() {\n next();\n return is_digit(peek().charCodeAt(0))\n ? read_num(\".\")\n : token(\"punc\", \".\");\n };\n\n function read_word() {\n var word = read_name();\n if (prev_was_dot) return token(\"name\", word);\n return KEYWORDS_ATOM(word) ? token(\"atom\", word)\n : !KEYWORDS(word) ? token(\"name\", word)\n : OPERATORS(word) ? token(\"operator\", word)\n : token(\"keyword\", word);\n };\n\n function with_eof_error(eof_error, cont) {\n return function(x) {\n try {\n return cont(x);\n } catch(ex) {\n if (ex === EX_EOF) parse_error(eof_error);\n else throw ex;\n }\n };\n };\n\n function next_token(force_regexp) {\n if (force_regexp != null)\n return read_regexp(force_regexp);\n skip_whitespace();\n start_token();\n if (html5_comments) {\n if (looking_at(\"<!--\")) {\n forward(4);\n return skip_line_comment(\"comment3\");\n }\n if (looking_at(\"-->\") && S.newline_before) {\n forward(3);\n return skip_line_comment(\"comment4\");\n }\n }\n var ch = peek();\n if (!ch) return token(\"eof\");\n var code = ch.charCodeAt(0);\n switch (code) {\n case 34: case 39: return read_string();\n case 46: return handle_dot();\n case 47: return handle_slash();\n }\n if (is_digit(code)) return read_num();\n if (PUNC_CHARS(ch)) return token(\"punc\", next());\n if (OPERATOR_CHARS(ch)) return read_operator();\n if (code == 92 || is_identifier_start(code)) return read_word();\n parse_error(\"Unexpected character '\" + ch + \"'\");\n };\n\n next_token.context = function(nc) {\n if (nc) S = nc;\n return S;\n };\n\n return next_token;\n\n};\n\n/* -----[ Parser (constants) ]----- */\n\nvar UNARY_PREFIX = makePredicate([\n \"typeof\",\n \"void\",\n \"delete\",\n \"--\",\n \"++\",\n \"!\",\n \"~\",\n \"-\",\n \"+\"\n]);\n\nvar UNARY_POSTFIX = makePredicate([ \"--\", \"++\" ]);\n\nvar ASSIGNMENT = makePredicate([ \"=\", \"+=\", \"-=\", \"/=\", \"*=\", \"%=\", \">>=\", \"<<=\", \">>>=\", \"|=\", \"^=\", \"&=\" ]);\n\nvar PRECEDENCE = (function(a, ret){\n for (var i = 0; i < a.length; ++i) {\n var b = a[i];\n for (var j = 0; j < b.length; ++j) {\n ret[b[j]] = i + 1;\n }\n }\n return ret;\n})(\n [\n [\"||\"],\n [\"&&\"],\n [\"|\"],\n [\"^\"],\n [\"&\"],\n [\"==\", \"===\", \"!=\", \"!==\"],\n [\"<\", \">\", \"<=\", \">=\", \"in\", \"instanceof\"],\n [\">>\", \"<<\", \">>>\"],\n [\"+\", \"-\"],\n [\"*\", \"/\", \"%\"]\n ],\n {}\n);\n\nvar STATEMENTS_WITH_LABELS = array_to_hash([ \"for\", \"do\", \"while\", \"switch\" ]);\n\nvar ATOMIC_START_TOKEN = array_to_hash([ \"atom\", \"num\", \"string\", \"regexp\", \"name\" ]);\n\n/* -----[ Parser ]----- */\n\nfunction parse($TEXT, options) {\n\n options = defaults(options, {\n strict : false,\n filename : null,\n toplevel : null,\n expression : false,\n html5_comments : true,\n });\n\n var S = {\n input : (typeof $TEXT == \"string\"\n ? tokenizer($TEXT, options.filename,\n options.html5_comments)\n : $TEXT),\n token : null,\n prev : null,\n peeked : null,\n in_function : 0,\n in_directives : true,\n in_loop : 0,\n labels : []\n };\n\n S.token = next();\n\n function is(type, value) {\n return is_token(S.token, type, value);\n };\n\n function peek() { return S.peeked || (S.peeked = S.input()); };\n\n function next() {\n S.prev = S.token;\n if (S.peeked) {\n S.token = S.peeked;\n S.peeked = null;\n } else {\n S.token = S.input();\n }\n S.in_directives = S.in_directives && (\n S.token.type == \"string\" || is(\"punc\", \";\")\n );\n return S.token;\n };\n\n function prev() {\n return S.prev;\n };\n\n function croak(msg, line, col, pos) {\n var ctx = S.input.context();\n js_error(msg,\n ctx.filename,\n line != null ? line : ctx.tokline,\n col != null ? col : ctx.tokcol,\n pos != null ? pos : ctx.tokpos);\n };\n\n function token_error(token, msg) {\n croak(msg, token.line, token.col);\n };\n\n function unexpected(token) {\n if (token == null)\n token = S.token;\n token_error(token, \"Unexpected token: \" + token.type + \" (\" + token.value + \")\");\n };\n\n function expect_token(type, val) {\n if (is(type, val)) {\n return next();\n }\n token_error(S.token, \"Unexpected token \" + S.token.type + \" «\" + S.token.value + \"»\" + \", expected \" + type + \" «\" + val + \"»\");\n };\n\n function expect(punc) { return expect_token(\"punc\", punc); };\n\n function can_insert_semicolon() {\n return !options.strict && (\n S.token.nlb || is(\"eof\") || is(\"punc\", \"}\")\n );\n };\n\n function semicolon() {\n if (is(\"punc\", \";\")) next();\n else if (!can_insert_semicolon()) unexpected();\n };\n\n function parenthesised() {\n expect(\"(\");\n var exp = expression(true);\n expect(\")\");\n return exp;\n };\n\n function embed_tokens(parser) {\n return function() {\n var start = S.token;\n var expr = parser();\n var end = prev();\n expr.start = start;\n expr.end = end;\n return expr;\n };\n };\n\n function handle_regexp() {\n if (is(\"operator\", \"/\") || is(\"operator\", \"/=\")) {\n S.peeked = null;\n S.token = S.input(S.token.value.substr(1)); // force regexp\n }\n };\n\n var statement = embed_tokens(function() {\n var tmp;\n handle_regexp();\n switch (S.token.type) {\n case \"string\":\n var dir = S.in_directives, stat = simple_statement();\n // XXXv2: decide how to fix directives\n if (dir && stat.body instanceof AST_String && !is(\"punc\", \",\"))\n return new AST_Directive({ value: stat.body.value });\n return stat;\n case \"num\":\n case \"regexp\":\n case \"operator\":\n case \"atom\":\n return simple_statement();\n\n case \"name\":\n return is_token(peek(), \"punc\", \":\")\n ? labeled_statement()\n : simple_statement();\n\n case \"punc\":\n switch (S.token.value) {\n case \"{\":\n return new AST_BlockStatement({\n start : S.token,\n body : block_(),\n end : prev()\n });\n case \"[\":\n case \"(\":\n return simple_statement();\n case \";\":\n next();\n return new AST_EmptyStatement();\n default:\n unexpected();\n }\n\n case \"keyword\":\n switch (tmp = S.token.value, next(), tmp) {\n case \"break\":\n return break_cont(AST_Break);\n\n case \"continue\":\n return break_cont(AST_Continue);\n\n case \"debugger\":\n semicolon();\n return new AST_Debugger();\n\n case \"do\":\n return new AST_Do({\n body : in_loop(statement),\n condition : (expect_token(\"keyword\", \"while\"), tmp = parenthesised(), semicolon(), tmp)\n });\n\n case \"while\":\n return new AST_While({\n condition : parenthesised(),\n body : in_loop(statement)\n });\n\n case \"for\":\n return for_();\n\n case \"function\":\n return function_(AST_Defun);\n\n case \"if\":\n return if_();\n\n case \"return\":\n if (S.in_function == 0)\n croak(\"'return' outside of function\");\n return new AST_Return({\n value: ( is(\"punc\", \";\")\n ? (next(), null)\n : can_insert_semicolon()\n ? null\n : (tmp = expression(true), semicolon(), tmp) )\n });\n\n case \"switch\":\n return new AST_Switch({\n expression : parenthesised(),\n body : in_loop(switch_body_)\n });\n\n case \"throw\":\n if (S.token.nlb)\n croak(\"Illegal newline after 'throw'\");\n return new AST_Throw({\n value: (tmp = expression(true), semicolon(), tmp)\n });\n\n case \"try\":\n return try_();\n\n case \"var\":\n return tmp = var_(), semicolon(), tmp;\n\n case \"const\":\n return tmp = const_(), semicolon(), tmp;\n\n case \"with\":\n return new AST_With({\n expression : parenthesised(),\n body : statement()\n });\n\n default:\n unexpected();\n }\n }\n });\n\n function labeled_statement() {\n var label = as_symbol(AST_Label);\n if (find_if(function(l){ return l.name == label.name }, S.labels)) {\n // ECMA-262, 12.12: An ECMAScript program is considered\n // syntactically incorrect if it contains a\n // LabelledStatement that is enclosed by a\n // LabelledStatement with the same Identifier as label.\n croak(\"Label \" + label.name + \" defined twice\");\n }\n expect(\":\");\n S.labels.push(label);\n var stat = statement();\n S.labels.pop();\n if (!(stat instanceof AST_IterationStatement)) {\n // check for `continue` that refers to this label.\n // those should be reported as syntax errors.\n // https://github.com/mishoo/UglifyJS2/issues/287\n label.references.forEach(function(ref){\n if (ref instanceof AST_Continue) {\n ref = ref.label.start;\n croak(\"Continue label `\" + label.name + \"` refers to non-IterationStatement.\",\n ref.line, ref.col, ref.pos);\n }\n });\n }\n return new AST_LabeledStatement({ body: stat, label: label });\n };\n\n function simple_statement(tmp) {\n return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) });\n };\n\n function break_cont(type) {\n var label = null, ldef;\n if (!can_insert_semicolon()) {\n label = as_symbol(AST_LabelRef, true);\n }\n if (label != null) {\n ldef = find_if(function(l){ return l.name == label.name }, S.labels);\n if (!ldef)\n croak(\"Undefined label \" + label.name);\n label.thedef = ldef;\n }\n else if (S.in_loop == 0)\n croak(type.TYPE + \" not inside a loop or switch\");\n semicolon();\n var stat = new type({ label: label });\n if (ldef) ldef.references.push(stat);\n return stat;\n };\n\n function for_() {\n expect(\"(\");\n var init = null;\n if (!is(\"punc\", \";\")) {\n init = is(\"keyword\", \"var\")\n ? (next(), var_(true))\n : expression(true, true);\n if (is(\"operator\", \"in\")) {\n if (init instanceof AST_Var && init.definitions.length > 1)\n croak(\"Only one variable declaration allowed in for..in loop\");\n next();\n return for_in(init);\n }\n }\n return regular_for(init);\n };\n\n function regular_for(init) {\n expect(\";\");\n var test = is(\"punc\", \";\") ? null : expression(true);\n expect(\";\");\n var step = is(\"punc\", \")\") ? null : expression(true);\n expect(\")\");\n return new AST_For({\n init : init,\n condition : test,\n step : step,\n body : in_loop(statement)\n });\n };\n\n function for_in(init) {\n var lhs = init instanceof AST_Var ? init.definitions[0].name : null;\n var obj = expression(true);\n expect(\")\");\n return new AST_ForIn({\n init : init,\n name : lhs,\n object : obj,\n body : in_loop(statement)\n });\n };\n\n var function_ = function(ctor) {\n var in_statement = ctor === AST_Defun;\n var name = is(\"name\") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;\n if (in_statement && !name)\n unexpected();\n expect(\"(\");\n return new ctor({\n name: name,\n argnames: (function(first, a){\n while (!is(\"punc\", \")\")) {\n if (first) first = false; else expect(\",\");\n a.push(as_symbol(AST_SymbolFunarg));\n }\n next();\n return a;\n })(true, []),\n body: (function(loop, labels){\n ++S.in_function;\n S.in_directives = true;\n S.in_loop = 0;\n S.labels = [];\n var a = block_();\n --S.in_function;\n S.in_loop = loop;\n S.labels = labels;\n return a;\n })(S.in_loop, S.labels)\n });\n };\n\n function if_() {\n var cond = parenthesised(), body = statement(), belse = null;\n if (is(\"keyword\", \"else\")) {\n next();\n belse = statement();\n }\n return new AST_If({\n condition : cond,\n body : body,\n alternative : belse\n });\n };\n\n function block_() {\n expect(\"{\");\n var a = [];\n while (!is(\"punc\", \"}\")) {\n if (is(\"eof\")) unexpected();\n a.push(statement());\n }\n next();\n return a;\n };\n\n function switch_body_() {\n expect(\"{\");\n var a = [], cur = null, branch = null, tmp;\n while (!is(\"punc\", \"}\")) {\n if (is(\"eof\")) unexpected();\n if (is(\"keyword\", \"case\")) {\n if (branch) branch.end = prev();\n cur = [];\n branch = new AST_Case({\n start : (tmp = S.token, next(), tmp),\n expression : expression(true),\n body : cur\n });\n a.push(branch);\n expect(\":\");\n }\n else if (is(\"keyword\", \"default\")) {\n if (branch) branch.end = prev();\n cur = [];\n branch = new AST_Default({\n start : (tmp = S.token, next(), expect(\":\"), tmp),\n body : cur\n });\n a.push(branch);\n }\n else {\n if (!cur) unexpected();\n cur.push(statement());\n }\n }\n if (branch) branch.end = prev();\n next();\n return a;\n };\n\n function try_() {\n var body = block_(), bcatch = null, bfinally = null;\n if (is(\"keyword\", \"catch\")) {\n var start = S.token;\n next();\n expect(\"(\");\n var name = as_symbol(AST_SymbolCatch);\n expect(\")\");\n bcatch = new AST_Catch({\n start : start,\n argname : name,\n body : block_(),\n end : prev()\n });\n }\n if (is(\"keyword\", \"finally\")) {\n var start = S.token;\n next();\n bfinally = new AST_Finally({\n start : start,\n body : block_(),\n end : prev()\n });\n }\n if (!bcatch && !bfinally)\n croak(\"Missing catch/finally blocks\");\n return new AST_Try({\n body : body,\n bcatch : bcatch,\n bfinally : bfinally\n });\n };\n\n function vardefs(no_in, in_const) {\n var a = [];\n for (;;) {\n a.push(new AST_VarDef({\n start : S.token,\n name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),\n value : is(\"operator\", \"=\") ? (next(), expression(false, no_in)) : null,\n end : prev()\n }));\n if (!is(\"punc\", \",\"))\n break;\n next();\n }\n return a;\n };\n\n var var_ = function(no_in) {\n return new AST_Var({\n start : prev(),\n definitions : vardefs(no_in, false),\n end : prev()\n });\n };\n\n var const_ = function() {\n return new AST_Const({\n start : prev(),\n definitions : vardefs(false, true),\n end : prev()\n });\n };\n\n var new_ = function() {\n var start = S.token;\n expect_token(\"operator\", \"new\");\n var newexp = expr_atom(false), args;\n if (is(\"punc\", \"(\")) {\n next();\n args = expr_list(\")\");\n } else {\n args = [];\n }\n return subscripts(new AST_New({\n start : start,\n expression : newexp,\n args : args,\n end : prev()\n }), true);\n };\n\n function as_atom_node() {\n var tok = S.token, ret;\n switch (tok.type) {\n case \"name\":\n case \"keyword\":\n ret = _make_symbol(AST_SymbolRef);\n break;\n case \"num\":\n ret = new AST_Number({ start: tok, end: tok, value: tok.value });\n break;\n case \"string\":\n ret = new AST_String({ start: tok, end: tok, value: tok.value });\n break;\n case \"regexp\":\n ret = new AST_RegExp({ start: tok, end: tok, value: tok.value });\n break;\n case \"atom\":\n switch (tok.value) {\n case \"false\":\n ret = new AST_False({ start: tok, end: tok });\n break;\n case \"true\":\n ret = new AST_True({ start: tok, end: tok });\n break;\n case \"null\":\n ret = new AST_Null({ start: tok, end: tok });\n break;\n }\n break;\n }\n next();\n return ret;\n };\n\n var expr_atom = function(allow_calls) {\n if (is(\"operator\", \"new\")) {\n return new_();\n }\n var start = S.token;\n if (is(\"punc\")) {\n switch (start.value) {\n case \"(\":\n next();\n var ex = expression(true);\n ex.start = start;\n ex.end = S.token;\n expect(\")\");\n return subscripts(ex, allow_calls);\n case \"[\":\n return subscripts(array_(), allow_calls);\n case \"{\":\n return subscripts(object_(), allow_calls);\n }\n unexpected();\n }\n if (is(\"keyword\", \"function\")) {\n next();\n var func = function_(AST_Function);\n func.start = start;\n func.end = prev();\n return subscripts(func, allow_calls);\n }\n if (ATOMIC_START_TOKEN[S.token.type]) {\n return subscripts(as_atom_node(), allow_calls);\n }\n unexpected();\n };\n\n function expr_list(closing, allow_trailing_comma, allow_empty) {\n var first = true, a = [];\n while (!is(\"punc\", closing)) {\n if (first) first = false; else expect(\",\");\n if (allow_trailing_comma && is(\"punc\", closing)) break;\n if (is(\"punc\", \",\") && allow_empty) {\n a.push(new AST_Hole({ start: S.token, end: S.token }));\n } else {\n a.push(expression(false));\n }\n }\n next();\n return a;\n };\n\n var array_ = embed_tokens(function() {\n expect(\"[\");\n return new AST_Array({\n elements: expr_list(\"]\", !options.strict, true)\n });\n });\n\n var object_ = embed_tokens(function() {\n expect(\"{\");\n var first = true, a = [];\n while (!is(\"punc\", \"}\")) {\n if (first) first = false; else expect(\",\");\n if (!options.strict && is(\"punc\", \"}\"))\n // allow trailing comma\n break;\n var start = S.token;\n var type = start.type;\n var name = as_property_name();\n if (type == \"name\" && !is(\"punc\", \":\")) {\n if (name == \"get\") {\n a.push(new AST_ObjectGetter({\n start : start,\n key : as_atom_node(),\n value : function_(AST_Accessor),\n end : prev()\n }));\n continue;\n }\n if (name == \"set\") {\n a.push(new AST_ObjectSetter({\n start : start,\n key : as_atom_node(),\n value : function_(AST_Accessor),\n end : prev()\n }));\n continue;\n }\n }\n expect(\":\");\n a.push(new AST_ObjectKeyVal({\n start : start,\n key : name,\n value : expression(false),\n end : prev()\n }));\n }\n next();\n return new AST_Object({ properties: a });\n });\n\n function as_property_name() {\n var tmp = S.token;\n next();\n switch (tmp.type) {\n case \"num\":\n case \"string\":\n case \"name\":\n case \"operator\":\n case \"keyword\":\n case \"atom\":\n return tmp.value;\n default:\n unexpected();\n }\n };\n\n function as_name() {\n var tmp = S.token;\n next();\n switch (tmp.type) {\n case \"name\":\n case \"operator\":\n case \"keyword\":\n case \"atom\":\n return tmp.value;\n default:\n unexpected();\n }\n };\n\n function _make_symbol(type) {\n var name = S.token.value;\n return new (name == \"this\" ? AST_This : type)({\n name : String(name),\n start : S.token,\n end : S.token\n });\n };\n\n function as_symbol(type, noerror) {\n if (!is(\"name\")) {\n if (!noerror) croak(\"Name expected\");\n return null;\n }\n var sym = _make_symbol(type);\n next();\n return sym;\n };\n\n var subscripts = function(expr, allow_calls) {\n var start = expr.start;\n if (is(\"punc\", \".\")) {\n next();\n return subscripts(new AST_Dot({\n start : start,\n expression : expr,\n property : as_name(),\n end : prev()\n }), allow_calls);\n }\n if (is(\"punc\", \"[\")) {\n next();\n var prop = expression(true);\n expect(\"]\");\n return subscripts(new AST_Sub({\n start : start,\n expression : expr,\n property : prop,\n end : prev()\n }), allow_calls);\n }\n if (allow_calls && is(\"punc\", \"(\")) {\n next();\n return subscripts(new AST_Call({\n start : start,\n expression : expr,\n args : expr_list(\")\"),\n end : prev()\n }), true);\n }\n return expr;\n };\n\n var maybe_unary = function(allow_calls) {\n var start = S.token;\n if (is(\"operator\") && UNARY_PREFIX(start.value)) {\n next();\n handle_regexp();\n var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls));\n ex.start = start;\n ex.end = prev();\n return ex;\n }\n var val = expr_atom(allow_calls);\n while (is(\"operator\") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {\n val = make_unary(AST_UnaryPostfix, S.token.value, val);\n val.start = start;\n val.end = S.token;\n next();\n }\n return val;\n };\n\n function make_unary(ctor, op, expr) {\n if ((op == \"++\" || op == \"--\") && !is_assignable(expr))\n croak(\"Invalid use of \" + op + \" operator\");\n return new ctor({ operator: op, expression: expr });\n };\n\n var expr_op = function(left, min_prec, no_in) {\n var op = is(\"operator\") ? S.token.value : null;\n if (op == \"in\" && no_in) op = null;\n var prec = op != null ? PRECEDENCE[op] : null;\n if (prec != null && prec > min_prec) {\n next();\n var right = expr_op(maybe_unary(true), prec, no_in);\n return expr_op(new AST_Binary({\n start : left.start,\n left : left,\n operator : op,\n right : right,\n end : right.end\n }), min_prec, no_in);\n }\n return left;\n };\n\n function expr_ops(no_in) {\n return expr_op(maybe_unary(true), 0, no_in);\n };\n\n var maybe_conditional = function(no_in) {\n var start = S.token;\n var expr = expr_ops(no_in);\n if (is(\"operator\", \"?\")) {\n next();\n var yes = expression(false);\n expect(\":\");\n return new AST_Conditional({\n start : start,\n condition : expr,\n consequent : yes,\n alternative : expression(false, no_in),\n end : prev()\n });\n }\n return expr;\n };\n\n function is_assignable(expr) {\n if (!options.strict) return true;\n if (expr instanceof AST_This) return false;\n return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol);\n };\n\n var maybe_assign = function(no_in) {\n var start = S.token;\n var left = maybe_conditional(no_in), val = S.token.value;\n if (is(\"operator\") && ASSIGNMENT(val)) {\n if (is_assignable(left)) {\n next();\n return new AST_Assign({\n start : start,\n left : left,\n operator : val,\n right : maybe_assign(no_in),\n end : prev()\n });\n }\n croak(\"Invalid assignment\");\n }\n return left;\n };\n\n var expression = function(commas, no_in) {\n var start = S.token;\n var expr = maybe_assign(no_in);\n if (commas && is(\"punc\", \",\")) {\n next();\n return new AST_Seq({\n start : start,\n car : expr,\n cdr : expression(true, no_in),\n end : peek()\n });\n }\n return expr;\n };\n\n function in_loop(cont) {\n ++S.in_loop;\n var ret = cont();\n --S.in_loop;\n return ret;\n };\n\n if (options.expression) {\n return expression(true);\n }\n\n return (function(){\n var start = S.token;\n var body = [];\n while (!is(\"eof\"))\n body.push(statement());\n var end = prev();\n var toplevel = options.toplevel;\n if (toplevel) {\n toplevel.body = toplevel.body.concat(body);\n toplevel.end = end;\n } else {\n toplevel = new AST_Toplevel({ start: start, body: body, end: end });\n }\n return toplevel;\n })();\n\n};\n\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n https://github.com/mishoo/UglifyJS2\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2012 (c) Mihai Bazon <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n\"use strict\";\n\n// Tree transformer helpers.\n\nfunction TreeTransformer(before, after) {\n TreeWalker.call(this);\n this.before = before;\n this.after = after;\n}\nTreeTransformer.prototype = new TreeWalker;\n\n(function(undefined){\n\n function _(node, descend) {\n node.DEFMETHOD(\"transform\", function(tw, in_list){\n var x, y;\n tw.push(this);\n if (tw.before) x = tw.before(this, descend, in_list);\n if (x === undefined) {\n if (!tw.after) {\n x = this;\n descend(x, tw);\n } else {\n tw.stack[tw.stack.length - 1] = x = this.clone();\n descend(x, tw);\n y = tw.after(x, in_list);\n if (y !== undefined) x = y;\n }\n }\n tw.pop();\n return x;\n });\n };\n\n function do_list(list, tw) {\n return MAP(list, function(node){\n return node.transform(tw, true);\n });\n };\n\n _(AST_Node, noop);\n\n _(AST_LabeledStatement, function(self, tw){\n self.label = self.label.transform(tw);\n self.body = self.body.transform(tw);\n });\n\n _(AST_SimpleStatement, function(self, tw){\n self.body = self.body.transform(tw);\n });\n\n _(AST_Block, function(self, tw){\n self.body = do_list(self.body, tw);\n });\n\n _(AST_DWLoop, function(self, tw){\n self.condition = self.condition.transform(tw);\n self.body = self.body.transform(tw);\n });\n\n _(AST_For, function(self, tw){\n if (self.init) self.init = self.init.transform(tw);\n if (self.condition) self.condition = self.condition.transform(tw);\n if (self.step) self.step = self.step.transform(tw);\n self.body = self.body.transform(tw);\n });\n\n _(AST_ForIn, function(self, tw){\n self.init = self.init.transform(tw);\n self.object = self.object.transform(tw);\n self.body = self.body.transform(tw);\n });\n\n _(AST_With, function(self, tw){\n self.expression = self.expression.transform(tw);\n self.body = self.body.transform(tw);\n });\n\n _(AST_Exit, function(self, tw){\n if (self.value) self.value = self.value.transform(tw);\n });\n\n _(AST_LoopControl, function(self, tw){\n if (self.label) self.label = self.label.transform(tw);\n });\n\n _(AST_If, function(self, tw){\n self.condition = self.condition.transform(tw);\n self.body = self.body.transform(tw);\n if (self.alternative) self.alternative = self.alternative.transform(tw);\n });\n\n _(AST_Switch, function(self, tw){\n self.expression = self.expression.transform(tw);\n self.body = do_list(self.body, tw);\n });\n\n _(AST_Case, function(self, tw){\n self.expression = self.expression.transform(tw);\n self.body = do_list(self.body, tw);\n });\n\n _(AST_Try, function(self, tw){\n self.body = do_list(self.body, tw);\n if (self.bcatch) self.bcatch = self.bcatch.transform(tw);\n if (self.bfinally) self.bfinally = self.bfinally.transform(tw);\n });\n\n _(AST_Catch, function(self, tw){\n self.argname = self.argname.transform(tw);\n self.body = do_list(self.body, tw);\n });\n\n _(AST_Definitions, function(self, tw){\n self.definitions = do_list(self.definitions, tw);\n });\n\n _(AST_VarDef, function(self, tw){\n self.name = self.name.transform(tw);\n if (self.value) self.value = self.value.transform(tw);\n });\n\n _(AST_Lambda, function(self, tw){\n if (self.name) self.name = self.name.transform(tw);\n self.argnames = do_list(self.argnames, tw);\n self.body = do_list(self.body, tw);\n });\n\n _(AST_Call, function(self, tw){\n self.expression = self.expression.transform(tw);\n self.args = do_list(self.args, tw);\n });\n\n _(AST_Seq, function(self, tw){\n self.car = self.car.transform(tw);\n self.cdr = self.cdr.transform(tw);\n });\n\n _(AST_Dot, function(self, tw){\n self.expression = self.expression.transform(tw);\n });\n\n _(AST_Sub, function(self, tw){\n self.expression = self.expression.transform(tw);\n self.property = self.property.transform(tw);\n });\n\n _(AST_Unary, function(self, tw){\n self.expression = self.expression.transform(tw);\n });\n\n _(AST_Binary, function(self, tw){\n self.left = self.left.transform(tw);\n self.right = self.right.transform(tw);\n });\n\n _(AST_Conditional, function(self, tw){\n self.condition = self.condition.transform(tw);\n self.consequent = self.consequent.transform(tw);\n self.alternative = self.alternative.transform(tw);\n });\n\n _(AST_Array, function(self, tw){\n self.elements = do_list(self.elements, tw);\n });\n\n _(AST_Object, function(self, tw){\n self.properties = do_list(self.properties, tw);\n });\n\n _(AST_ObjectProperty, function(self, tw){\n self.value = self.value.transform(tw);\n });\n\n})();\n\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n https://github.com/mishoo/UglifyJS2\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2012 (c) Mihai Bazon <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n\"use strict\";\n\nfunction SymbolDef(scope, index, orig) {\n this.name = orig.name;\n this.orig = [ orig ];\n this.scope = scope;\n this.references = [];\n this.global = false;\n this.mangled_name = null;\n this.undeclared = false;\n this.constant = false;\n this.index = index;\n};\n\nSymbolDef.prototype = {\n unmangleable: function(options) {\n return (this.global && !(options && options.toplevel))\n || this.undeclared\n || (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with));\n },\n mangle: function(options) {\n if (!this.mangled_name && !this.unmangleable(options)) {\n var s = this.scope;\n if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda)\n s = s.parent_scope;\n this.mangled_name = s.next_mangled(options, this);\n }\n }\n};\n\nAST_Toplevel.DEFMETHOD(\"figure_out_scope\", function(options){\n options = defaults(options, {\n screw_ie8: false\n });\n\n // pass 1: setup scope chaining and handle definitions\n var self = this;\n var scope = self.parent_scope = null;\n var defun = null;\n var nesting = 0;\n var tw = new TreeWalker(function(node, descend){\n if (options.screw_ie8 && node instanceof AST_Catch) {\n var save_scope = scope;\n scope = new AST_Scope(node);\n scope.init_scope_vars(nesting);\n scope.parent_scope = save_scope;\n descend();\n scope = save_scope;\n return true;\n }\n if (node instanceof AST_Scope) {\n node.init_scope_vars(nesting);\n var save_scope = node.parent_scope = scope;\n var save_defun = defun;\n defun = scope = node;\n ++nesting; descend(); --nesting;\n scope = save_scope;\n defun = save_defun;\n return true; // don't descend again in TreeWalker\n }\n if (node instanceof AST_Directive) {\n node.scope = scope;\n push_uniq(scope.directives, node.value);\n return true;\n }\n if (node instanceof AST_With) {\n for (var s = scope; s; s = s.parent_scope)\n s.uses_with = true;\n return;\n }\n if (node instanceof AST_Symbol) {\n node.scope = scope;\n }\n if (node instanceof AST_SymbolLambda) {\n defun.def_function(node);\n }\n else if (node instanceof AST_SymbolDefun) {\n // Careful here, the scope where this should be defined is\n // the parent scope. The reason is that we enter a new\n // scope when we encounter the AST_Defun node (which is\n // instanceof AST_Scope) but we get to the symbol a bit\n // later.\n (node.scope = defun.parent_scope).def_function(node);\n }\n else if (node instanceof AST_SymbolVar\n || node instanceof AST_SymbolConst) {\n var def = defun.def_variable(node);\n def.constant = node instanceof AST_SymbolConst;\n def.init = tw.parent().value;\n }\n else if (node instanceof AST_SymbolCatch) {\n (options.screw_ie8 ? scope : defun)\n .def_variable(node);\n }\n });\n self.walk(tw);\n\n // pass 2: find back references and eval\n var func = null;\n var globals = self.globals = new Dictionary();\n var tw = new TreeWalker(function(node, descend){\n if (node instanceof AST_Lambda) {\n var prev_func = func;\n func = node;\n descend();\n func = prev_func;\n return true;\n }\n if (node instanceof AST_SymbolRef) {\n var name = node.name;\n var sym = node.scope.find_variable(name);\n if (!sym) {\n var g;\n if (globals.has(name)) {\n g = globals.get(name);\n } else {\n g = new SymbolDef(self, globals.size(), node);\n g.undeclared = true;\n g.global = true;\n globals.set(name, g);\n }\n node.thedef = g;\n if (name == \"eval\" && tw.parent() instanceof AST_Call) {\n for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope)\n s.uses_eval = true;\n }\n if (func && name == \"arguments\") {\n func.uses_arguments = true;\n }\n } else {\n node.thedef = sym;\n }\n node.reference();\n return true;\n }\n });\n self.walk(tw);\n});\n\nAST_Scope.DEFMETHOD(\"init_scope_vars\", function(nesting){\n this.directives = []; // contains the directives defined in this scope, i.e. \"use strict\"\n this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)\n this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)\n this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement\n this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`\n this.parent_scope = null; // the parent scope\n this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes\n this.cname = -1; // the current index for mangling functions/variables\n this.nesting = nesting; // the nesting level of this scope (0 means toplevel)\n});\n\nAST_Scope.DEFMETHOD(\"strict\", function(){\n return this.has_directive(\"use strict\");\n});\n\nAST_Lambda.DEFMETHOD(\"init_scope_vars\", function(){\n AST_Scope.prototype.init_scope_vars.apply(this, arguments);\n this.uses_arguments = false;\n});\n\nAST_SymbolRef.DEFMETHOD(\"reference\", function() {\n var def = this.definition();\n def.references.push(this);\n var s = this.scope;\n while (s) {\n push_uniq(s.enclosed, def);\n if (s === def.scope) break;\n s = s.parent_scope;\n }\n this.frame = this.scope.nesting - def.scope.nesting;\n});\n\nAST_Scope.DEFMETHOD(\"find_variable\", function(name){\n if (name instanceof AST_Symbol) name = name.name;\n return this.variables.get(name)\n || (this.parent_scope && this.parent_scope.find_variable(name));\n});\n\nAST_Scope.DEFMETHOD(\"has_directive\", function(value){\n return this.parent_scope && this.parent_scope.has_directive(value)\n || (this.directives.indexOf(value) >= 0 ? this : null);\n});\n\nAST_Scope.DEFMETHOD(\"def_function\", function(symbol){\n this.functions.set(symbol.name, this.def_variable(symbol));\n});\n\nAST_Scope.DEFMETHOD(\"def_variable\", function(symbol){\n var def;\n if (!this.variables.has(symbol.name)) {\n def = new SymbolDef(this, this.variables.size(), symbol);\n this.variables.set(symbol.name, def);\n def.global = !this.parent_scope;\n } else {\n def = this.variables.get(symbol.name);\n def.orig.push(symbol);\n }\n return symbol.thedef = def;\n});\n\nAST_Scope.DEFMETHOD(\"next_mangled\", function(options){\n var ext = this.enclosed;\n out: while (true) {\n var m = base54(++this.cname);\n if (!is_identifier(m)) continue; // skip over \"do\"\n\n // https://github.com/mishoo/UglifyJS2/issues/242 -- do not\n // shadow a name excepted from mangling.\n if (options.except.indexOf(m) >= 0) continue;\n\n // we must ensure that the mangled name does not shadow a name\n // from some parent scope that is referenced in this or in\n // inner scopes.\n for (var i = ext.length; --i >= 0;) {\n var sym = ext[i];\n var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);\n if (m == name) continue out;\n }\n return m;\n }\n});\n\nAST_Function.DEFMETHOD(\"next_mangled\", function(options, def){\n // #179, #326\n // in Safari strict mode, something like (function x(x){...}) is a syntax error;\n // a function expression's argument cannot shadow the function expression's name\n\n var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();\n while (true) {\n var name = AST_Lambda.prototype.next_mangled.call(this, options, def);\n if (!(tricky_def && tricky_def.mangled_name == name))\n return name;\n }\n});\n\nAST_Scope.DEFMETHOD(\"references\", function(sym){\n if (sym instanceof AST_Symbol) sym = sym.definition();\n return this.enclosed.indexOf(sym) < 0 ? null : sym;\n});\n\nAST_Symbol.DEFMETHOD(\"unmangleable\", function(options){\n return this.definition().unmangleable(options);\n});\n\n// property accessors are not mangleable\nAST_SymbolAccessor.DEFMETHOD(\"unmangleable\", function(){\n return true;\n});\n\n// labels are always mangleable\nAST_Label.DEFMETHOD(\"unmangleable\", function(){\n return false;\n});\n\nAST_Symbol.DEFMETHOD(\"unreferenced\", function(){\n return this.definition().references.length == 0\n && !(this.scope.uses_eval || this.scope.uses_with);\n});\n\nAST_Symbol.DEFMETHOD(\"undeclared\", function(){\n return this.definition().undeclared;\n});\n\nAST_LabelRef.DEFMETHOD(\"undeclared\", function(){\n return false;\n});\n\nAST_Label.DEFMETHOD(\"undeclared\", function(){\n return false;\n});\n\nAST_Symbol.DEFMETHOD(\"definition\", function(){\n return this.thedef;\n});\n\nAST_Symbol.DEFMETHOD(\"global\", function(){\n return this.definition().global;\n});\n\nAST_Toplevel.DEFMETHOD(\"_default_mangler_options\", function(options){\n return defaults(options, {\n except : [],\n eval : false,\n sort : false,\n toplevel : false,\n screw_ie8 : false\n });\n});\n\nAST_Toplevel.DEFMETHOD(\"mangle_names\", function(options){\n options = this._default_mangler_options(options);\n // We only need to mangle declaration nodes. Special logic wired\n // into the code generator will display the mangled name if it's\n // present (and for AST_SymbolRef-s it'll use the mangled name of\n // the AST_SymbolDeclaration that it points to).\n var lname = -1;\n var to_mangle = [];\n var tw = new TreeWalker(function(node, descend){\n if (node instanceof AST_LabeledStatement) {\n // lname is incremented when we get to the AST_Label\n var save_nesting = lname;\n descend();\n lname = save_nesting;\n return true; // don't descend again in TreeWalker\n }\n if (node instanceof AST_Scope) {\n var p = tw.parent(), a = [];\n node.variables.each(function(symbol){\n if (options.except.indexOf(symbol.name) < 0) {\n a.push(symbol);\n }\n });\n if (options.sort) a.sort(function(a, b){\n return b.references.length - a.references.length;\n });\n to_mangle.push.apply(to_mangle, a);\n return;\n }\n if (node instanceof AST_Label) {\n var name;\n do name = base54(++lname); while (!is_identifier(name));\n node.mangled_name = name;\n return true;\n }\n if (options.screw_ie8 && node instanceof AST_SymbolCatch) {\n to_mangle.push(node.definition());\n return;\n }\n });\n this.walk(tw);\n to_mangle.forEach(function(def){ def.mangle(options) });\n});\n\nAST_Toplevel.DEFMETHOD(\"compute_char_frequency\", function(options){\n options = this._default_mangler_options(options);\n var tw = new TreeWalker(function(node){\n if (node instanceof AST_Constant)\n base54.consider(node.print_to_string());\n else if (node instanceof AST_Return)\n base54.consider(\"return\");\n else if (node instanceof AST_Throw)\n base54.consider(\"throw\");\n else if (node instanceof AST_Continue)\n base54.consider(\"continue\");\n else if (node instanceof AST_Break)\n base54.consider(\"break\");\n else if (node instanceof AST_Debugger)\n base54.consider(\"debugger\");\n else if (node instanceof AST_Directive)\n base54.consider(node.value);\n else if (node instanceof AST_While)\n base54.consider(\"while\");\n else if (node instanceof AST_Do)\n base54.consider(\"do while\");\n else if (node instanceof AST_If) {\n base54.consider(\"if\");\n if (node.alternative) base54.consider(\"else\");\n }\n else if (node instanceof AST_Var)\n base54.consider(\"var\");\n else if (node instanceof AST_Const)\n base54.consider(\"const\");\n else if (node instanceof AST_Lambda)\n base54.consider(\"function\");\n else if (node instanceof AST_For)\n base54.consider(\"for\");\n else if (node instanceof AST_ForIn)\n base54.consider(\"for in\");\n else if (node instanceof AST_Switch)\n base54.consider(\"switch\");\n else if (node instanceof AST_Case)\n base54.consider(\"case\");\n else if (node instanceof AST_Default)\n base54.consider(\"default\");\n else if (node instanceof AST_With)\n base54.consider(\"with\");\n else if (node instanceof AST_ObjectSetter)\n base54.consider(\"set\" + node.key);\n else if (node instanceof AST_ObjectGetter)\n base54.consider(\"get\" + node.key);\n else if (node instanceof AST_ObjectKeyVal)\n base54.consider(node.key);\n else if (node instanceof AST_New)\n base54.consider(\"new\");\n else if (node instanceof AST_This)\n base54.consider(\"this\");\n else if (node instanceof AST_Try)\n base54.consider(\"try\");\n else if (node instanceof AST_Catch)\n base54.consider(\"catch\");\n else if (node instanceof AST_Finally)\n base54.consider(\"finally\");\n else if (node instanceof AST_Symbol && node.unmangleable(options))\n base54.consider(node.name);\n else if (node instanceof AST_Unary || node instanceof AST_Binary)\n base54.consider(node.operator);\n else if (node instanceof AST_Dot)\n base54.consider(node.property);\n });\n this.walk(tw);\n base54.sort();\n});\n\nvar base54 = (function() {\n var string = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789\";\n var chars, frequency;\n function reset() {\n frequency = Object.create(null);\n chars = string.split(\"\").map(function(ch){ return ch.charCodeAt(0) });\n chars.forEach(function(ch){ frequency[ch] = 0 });\n }\n base54.consider = function(str){\n for (var i = str.length; --i >= 0;) {\n var code = str.charCodeAt(i);\n if (code in frequency) ++frequency[code];\n }\n };\n base54.sort = function() {\n chars = mergeSort(chars, function(a, b){\n if (is_digit(a) && !is_digit(b)) return 1;\n if (is_digit(b) && !is_digit(a)) return -1;\n return frequency[b] - frequency[a];\n });\n };\n base54.reset = reset;\n reset();\n base54.get = function(){ return chars };\n base54.freq = function(){ return frequency };\n function base54(num) {\n var ret = \"\", base = 54;\n do {\n ret += String.fromCharCode(chars[num % base]);\n num = Math.floor(num / base);\n base = 64;\n } while (num > 0);\n return ret;\n };\n return base54;\n})();\n\nAST_Toplevel.DEFMETHOD(\"scope_warnings\", function(options){\n options = defaults(options, {\n undeclared : false, // this makes a lot of noise\n unreferenced : true,\n assign_to_global : true,\n func_arguments : true,\n nested_defuns : true,\n eval : true\n });\n var tw = new TreeWalker(function(node){\n if (options.undeclared\n && node instanceof AST_SymbolRef\n && node.undeclared())\n {\n // XXX: this also warns about JS standard names,\n // i.e. Object, Array, parseInt etc. Should add a list of\n // exceptions.\n AST_Node.warn(\"Undeclared symbol: {name} [{file}:{line},{col}]\", {\n name: node.name,\n file: node.start.file,\n line: node.start.line,\n col: node.start.col\n });\n }\n if (options.assign_to_global)\n {\n var sym = null;\n if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)\n sym = node.left;\n else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)\n sym = node.init;\n if (sym\n && (sym.undeclared()\n || (sym.global() && sym.scope !== sym.definition().scope))) {\n AST_Node.warn(\"{msg}: {name} [{file}:{line},{col}]\", {\n msg: sym.undeclared() ? \"Accidental global?\" : \"Assignment to global\",\n name: sym.name,\n file: sym.start.file,\n line: sym.start.line,\n col: sym.start.col\n });\n }\n }\n if (options.eval\n && node instanceof AST_SymbolRef\n && node.undeclared()\n && node.name == \"eval\") {\n AST_Node.warn(\"Eval is used [{file}:{line},{col}]\", node.start);\n }\n if (options.unreferenced\n && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)\n && node.unreferenced()) {\n AST_Node.warn(\"{type} {name} is declared but not referenced [{file}:{line},{col}]\", {\n type: node instanceof AST_Label ? \"Label\" : \"Symbol\",\n name: node.name,\n file: node.start.file,\n line: node.start.line,\n col: node.start.col\n });\n }\n if (options.func_arguments\n && node instanceof AST_Lambda\n && node.uses_arguments) {\n AST_Node.warn(\"arguments used in function {name} [{file}:{line},{col}]\", {\n name: node.name ? node.name.name : \"anonymous\",\n file: node.start.file,\n line: node.start.line,\n col: node.start.col\n });\n }\n if (options.nested_defuns\n && node instanceof AST_Defun\n && !(tw.parent() instanceof AST_Scope)) {\n AST_Node.warn(\"Function {name} declared in nested statement \\\"{type}\\\" [{file}:{line},{col}]\", {\n name: node.name.name,\n type: tw.parent().TYPE,\n file: node.start.file,\n line: node.start.line,\n col: node.start.col\n });\n }\n });\n this.walk(tw);\n});\n\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n https://github.com/mishoo/UglifyJS2\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2012 (c) Mihai Bazon <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n\"use strict\";\n\nfunction OutputStream(options) {\n\n options = defaults(options, {\n indent_start : 0,\n indent_level : 4,\n quote_keys : false,\n space_colon : true,\n ascii_only : false,\n unescape_regexps : false,\n inline_script : false,\n width : 80,\n max_line_len : 32000,\n beautify : false,\n source_map : null,\n bracketize : false,\n semicolons : true,\n comments : false,\n preserve_line : false,\n screw_ie8 : false,\n preamble : null,\n }, true);\n\n var indentation = 0;\n var current_col = 0;\n var current_line = 1;\n var current_pos = 0;\n var OUTPUT = \"\";\n\n function to_ascii(str, identifier) {\n return str.replace(/[\\u0080-\\uffff]/g, function(ch) {\n var code = ch.charCodeAt(0).toString(16);\n if (code.length <= 2 && !identifier) {\n while (code.length < 2) code = \"0\" + code;\n return \"\\\\x\" + code;\n } else {\n while (code.length < 4) code = \"0\" + code;\n return \"\\\\u\" + code;\n }\n });\n };\n\n function make_string(str) {\n var dq = 0, sq = 0;\n str = str.replace(/[\\\\\\b\\f\\n\\r\\t\\x22\\x27\\u2028\\u2029\\0]/g, function(s){\n switch (s) {\n case \"\\\\\": return \"\\\\\\\\\";\n case \"\\b\": return \"\\\\b\";\n case \"\\f\": return \"\\\\f\";\n case \"\\n\": return \"\\\\n\";\n case \"\\r\": return \"\\\\r\";\n case \"\\u2028\": return \"\\\\u2028\";\n case \"\\u2029\": return \"\\\\u2029\";\n case '\"': ++dq; return '\"';\n case \"'\": ++sq; return \"'\";\n case \"\\0\": return \"\\\\x00\";\n }\n return s;\n });\n if (options.ascii_only) str = to_ascii(str);\n if (dq > sq) return \"'\" + str.replace(/\\x27/g, \"\\\\'\") + \"'\";\n else return '\"' + str.replace(/\\x22/g, '\\\\\"') + '\"';\n };\n\n function encode_string(str) {\n var ret = make_string(str);\n if (options.inline_script)\n ret = ret.replace(/<\\x2fscript([>\\/\\t\\n\\f\\r ])/gi, \"<\\\\/script$1\");\n return ret;\n };\n\n function make_name(name) {\n name = name.toString();\n if (options.ascii_only)\n name = to_ascii(name, true);\n return name;\n };\n\n function make_indent(back) {\n return repeat_string(\" \", options.indent_start + indentation - back * options.indent_level);\n };\n\n /* -----[ beautification/minification ]----- */\n\n var might_need_space = false;\n var might_need_semicolon = false;\n var last = null;\n\n function last_char() {\n return last.charAt(last.length - 1);\n };\n\n function maybe_newline() {\n if (options.max_line_len && current_col > options.max_line_len)\n print(\"\\n\");\n };\n\n var requireSemicolonChars = makePredicate(\"( [ + * / - , .\");\n\n function print(str) {\n str = String(str);\n var ch = str.charAt(0);\n if (might_need_semicolon) {\n if ((!ch || \";}\".indexOf(ch) < 0) && !/[;]$/.test(last)) {\n if (options.semicolons || requireSemicolonChars(ch)) {\n OUTPUT += \";\";\n current_col++;\n current_pos++;\n } else {\n OUTPUT += \"\\n\";\n current_pos++;\n current_line++;\n current_col = 0;\n }\n if (!options.beautify)\n might_need_space = false;\n }\n might_need_semicolon = false;\n maybe_newline();\n }\n\n if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {\n var target_line = stack[stack.length - 1].start.line;\n while (current_line < target_line) {\n OUTPUT += \"\\n\";\n current_pos++;\n current_line++;\n current_col = 0;\n might_need_space = false;\n }\n }\n\n if (might_need_space) {\n var prev = last_char();\n if ((is_identifier_char(prev)\n && (is_identifier_char(ch) || ch == \"\\\\\"))\n || (/^[\\+\\-\\/]$/.test(ch) && ch == prev))\n {\n OUTPUT += \" \";\n current_col++;\n current_pos++;\n }\n might_need_space = false;\n }\n var a = str.split(/\\r?\\n/), n = a.length - 1;\n current_line += n;\n if (n == 0) {\n current_col += a[n].length;\n } else {\n current_col = a[n].length;\n }\n current_pos += str.length;\n last = str;\n OUTPUT += str;\n };\n\n var space = options.beautify ? function() {\n print(\" \");\n } : function() {\n might_need_space = true;\n };\n\n var indent = options.beautify ? function(half) {\n if (options.beautify) {\n print(make_indent(half ? 0.5 : 0));\n }\n } : noop;\n\n var with_indent = options.beautify ? function(col, cont) {\n if (col === true) col = next_indent();\n var save_indentation = indentation;\n indentation = col;\n var ret = cont();\n indentation = save_indentation;\n return ret;\n } : function(col, cont) { return cont() };\n\n var newline = options.beautify ? function() {\n print(\"\\n\");\n } : noop;\n\n var semicolon = options.beautify ? function() {\n print(\";\");\n } : function() {\n might_need_semicolon = true;\n };\n\n function force_semicolon() {\n might_need_semicolon = false;\n print(\";\");\n };\n\n function next_indent() {\n return indentation + options.indent_level;\n };\n\n function with_block(cont) {\n var ret;\n print(\"{\");\n newline();\n with_indent(next_indent(), function(){\n ret = cont();\n });\n indent();\n print(\"}\");\n return ret;\n };\n\n function with_parens(cont) {\n print(\"(\");\n //XXX: still nice to have that for argument lists\n //var ret = with_indent(current_col, cont);\n var ret = cont();\n print(\")\");\n return ret;\n };\n\n function with_square(cont) {\n print(\"[\");\n //var ret = with_indent(current_col, cont);\n var ret = cont();\n print(\"]\");\n return ret;\n };\n\n function comma() {\n print(\",\");\n space();\n };\n\n function colon() {\n print(\":\");\n if (options.space_colon) space();\n };\n\n var add_mapping = options.source_map ? function(token, name) {\n try {\n if (token) options.source_map.add(\n token.file || \"?\",\n current_line, current_col,\n token.line, token.col,\n (!name && token.type == \"name\") ? token.value : name\n );\n } catch(ex) {\n AST_Node.warn(\"Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]\", {\n file: token.file,\n line: token.line,\n col: token.col,\n cline: current_line,\n ccol: current_col,\n name: name || \"\"\n })\n }\n } : noop;\n\n function get() {\n return OUTPUT;\n };\n\n if (options.preamble) {\n print(options.preamble.replace(/\\r\\n?|[\\n\\u2028\\u2029]|\\s*$/g, \"\\n\"));\n }\n\n var stack = [];\n return {\n get : get,\n toString : get,\n indent : indent,\n indentation : function() { return indentation },\n current_width : function() { return current_col - indentation },\n should_break : function() { return options.width && this.current_width() >= options.width },\n newline : newline,\n print : print,\n space : space,\n comma : comma,\n colon : colon,\n last : function() { return last },\n semicolon : semicolon,\n force_semicolon : force_semicolon,\n to_ascii : to_ascii,\n print_name : function(name) { print(make_name(name)) },\n print_string : function(str) { print(encode_string(str)) },\n next_indent : next_indent,\n with_indent : with_indent,\n with_block : with_block,\n with_parens : with_parens,\n with_square : with_square,\n add_mapping : add_mapping,\n option : function(opt) { return options[opt] },\n line : function() { return current_line },\n col : function() { return current_col },\n pos : function() { return current_pos },\n push_node : function(node) { stack.push(node) },\n pop_node : function() { return stack.pop() },\n stack : function() { return stack },\n parent : function(n) {\n return stack[stack.length - 2 - (n || 0)];\n }\n };\n\n};\n\n/* -----[ code generators ]----- */\n\n(function(){\n\n /* -----[ utils ]----- */\n\n function DEFPRINT(nodetype, generator) {\n nodetype.DEFMETHOD(\"_codegen\", generator);\n };\n\n AST_Node.DEFMETHOD(\"print\", function(stream, force_parens){\n var self = this, generator = self._codegen;\n function doit() {\n self.add_comments(stream);\n self.add_source_map(stream);\n generator(self, stream);\n }\n stream.push_node(self);\n if (force_parens || self.needs_parens(stream)) {\n stream.with_parens(doit);\n } else {\n doit();\n }\n stream.pop_node();\n });\n\n AST_Node.DEFMETHOD(\"print_to_string\", function(options){\n var s = OutputStream(options);\n this.print(s);\n return s.get();\n });\n\n /* -----[ comments ]----- */\n\n AST_Node.DEFMETHOD(\"add_comments\", function(output){\n var c = output.option(\"comments\"), self = this;\n if (c) {\n var start = self.start;\n if (start && !start._comments_dumped) {\n start._comments_dumped = true;\n var comments = start.comments_before || [];\n\n // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112\n // and https://github.com/mishoo/UglifyJS2/issues/372\n if (self instanceof AST_Exit && self.value) {\n self.value.walk(new TreeWalker(function(node){\n if (node.start && node.start.comments_before) {\n comments = comments.concat(node.start.comments_before);\n node.start.comments_before = [];\n }\n if (node instanceof AST_Function ||\n node instanceof AST_Array ||\n node instanceof AST_Object)\n {\n return true; // don't go inside.\n }\n }));\n }\n\n if (c.test) {\n comments = comments.filter(function(comment){\n return c.test(comment.value);\n });\n } else if (typeof c == \"function\") {\n comments = comments.filter(function(comment){\n return c(self, comment);\n });\n }\n comments.forEach(function(c){\n if (/comment[134]/.test(c.type)) {\n output.print(\"//\" + c.value + \"\\n\");\n output.indent();\n }\n else if (c.type == \"comment2\") {\n output.print(\"/*\" + c.value + \"*/\");\n if (start.nlb) {\n output.print(\"\\n\");\n output.indent();\n } else {\n output.space();\n }\n }\n });\n }\n }\n });\n\n /* -----[ PARENTHESES ]----- */\n\n function PARENS(nodetype, func) {\n nodetype.DEFMETHOD(\"needs_parens\", func);\n };\n\n PARENS(AST_Node, function(){\n return false;\n });\n\n // a function expression needs parens around it when it's provably\n // the first token to appear in a statement.\n PARENS(AST_Function, function(output){\n return first_in_statement(output);\n });\n\n // same goes for an object literal, because otherwise it would be\n // interpreted as a block of code.\n PARENS(AST_Object, function(output){\n return first_in_statement(output);\n });\n\n PARENS(AST_Unary, function(output){\n var p = output.parent();\n return p instanceof AST_PropAccess && p.expression === this;\n });\n\n PARENS(AST_Seq, function(output){\n var p = output.parent();\n return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)\n || p instanceof AST_Unary // !(foo, bar, baz)\n || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8\n || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4\n || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})[\"foo\"] ==> 2\n || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]\n || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2\n || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)\n * ==> 20 (side effect, set a := 10 and b := 20) */\n ;\n });\n\n PARENS(AST_Binary, function(output){\n var p = output.parent();\n // (foo && bar)()\n if (p instanceof AST_Call && p.expression === this)\n return true;\n // typeof (foo && bar)\n if (p instanceof AST_Unary)\n return true;\n // (foo && bar)[\"prop\"], (foo && bar).prop\n if (p instanceof AST_PropAccess && p.expression === this)\n return true;\n // this deals with precedence: 3 * (2 + 1)\n if (p instanceof AST_Binary) {\n var po = p.operator, pp = PRECEDENCE[po];\n var so = this.operator, sp = PRECEDENCE[so];\n if (pp > sp\n || (pp == sp\n && this === p.right)) {\n return true;\n }\n }\n });\n\n PARENS(AST_PropAccess, function(output){\n var p = output.parent();\n if (p instanceof AST_New && p.expression === this) {\n // i.e. new (foo.bar().baz)\n //\n // if there's one call into this subtree, then we need\n // parens around it too, otherwise the call will be\n // interpreted as passing the arguments to the upper New\n // expression.\n try {\n this.walk(new TreeWalker(function(node){\n if (node instanceof AST_Call) throw p;\n }));\n } catch(ex) {\n if (ex !== p) throw ex;\n return true;\n }\n }\n });\n\n PARENS(AST_Call, function(output){\n var p = output.parent(), p1;\n if (p instanceof AST_New && p.expression === this)\n return true;\n\n // workaround for Safari bug.\n // https://bugs.webkit.org/show_bug.cgi?id=123506\n return this.expression instanceof AST_Function\n && p instanceof AST_PropAccess\n && p.expression === this\n && (p1 = output.parent(1)) instanceof AST_Assign\n && p1.left === p;\n });\n\n PARENS(AST_New, function(output){\n var p = output.parent();\n if (no_constructor_parens(this, output)\n && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)[\"getTime\"]()\n || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)\n return true;\n });\n\n PARENS(AST_Number, function(output){\n var p = output.parent();\n if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this)\n return true;\n });\n\n PARENS(AST_NaN, function(output){\n var p = output.parent();\n if (p instanceof AST_PropAccess && p.expression === this)\n return true;\n });\n\n function assign_and_conditional_paren_rules(output) {\n var p = output.parent();\n // !(a = false) → true\n if (p instanceof AST_Unary)\n return true;\n // 1 + (a = 2) + 3 → 6, side effect setting a = 2\n if (p instanceof AST_Binary && !(p instanceof AST_Assign))\n return true;\n // (a = func)() —or— new (a = Object)()\n if (p instanceof AST_Call && p.expression === this)\n return true;\n // (a = foo) ? bar : baz\n if (p instanceof AST_Conditional && p.condition === this)\n return true;\n // (a = foo)[\"prop\"] —or— (a = foo).prop\n if (p instanceof AST_PropAccess && p.expression === this)\n return true;\n };\n\n PARENS(AST_Assign, assign_and_conditional_paren_rules);\n PARENS(AST_Conditional, assign_and_conditional_paren_rules);\n\n /* -----[ PRINTERS ]----- */\n\n DEFPRINT(AST_Directive, function(self, output){\n output.print_string(self.value);\n output.semicolon();\n });\n DEFPRINT(AST_Debugger, function(self, output){\n output.print(\"debugger\");\n output.semicolon();\n });\n\n /* -----[ statements ]----- */\n\n function display_body(body, is_toplevel, output) {\n var last = body.length - 1;\n body.forEach(function(stmt, i){\n if (!(stmt instanceof AST_EmptyStatement)) {\n output.indent();\n stmt.print(output);\n if (!(i == last && is_toplevel)) {\n output.newline();\n if (is_toplevel) output.newline();\n }\n }\n });\n };\n\n AST_StatementWithBody.DEFMETHOD(\"_do_print_body\", function(output){\n force_statement(this.body, output);\n });\n\n DEFPRINT(AST_Statement, function(self, output){\n self.body.print(output);\n output.semicolon();\n });\n DEFPRINT(AST_Toplevel, function(self, output){\n display_body(self.body, true, output);\n output.print(\"\");\n });\n DEFPRINT(AST_LabeledStatement, function(self, output){\n self.label.print(output);\n output.colon();\n self.body.print(output);\n });\n DEFPRINT(AST_SimpleStatement, function(self, output){\n self.body.print(output);\n output.semicolon();\n });\n function print_bracketed(body, output) {\n if (body.length > 0) output.with_block(function(){\n display_body(body, false, output);\n });\n else output.print(\"{}\");\n };\n DEFPRINT(AST_BlockStatement, function(self, output){\n print_bracketed(self.body, output);\n });\n DEFPRINT(AST_EmptyStatement, function(self, output){\n output.semicolon();\n });\n DEFPRINT(AST_Do, function(self, output){\n output.print(\"do\");\n output.space();\n self._do_print_body(output);\n output.space();\n output.print(\"while\");\n output.space();\n output.with_parens(function(){\n self.condition.print(output);\n });\n output.semicolon();\n });\n DEFPRINT(AST_While, function(self, output){\n output.print(\"while\");\n output.space();\n output.with_parens(function(){\n self.condition.print(output);\n });\n output.space();\n self._do_print_body(output);\n });\n DEFPRINT(AST_For, function(self, output){\n output.print(\"for\");\n output.space();\n output.with_parens(function(){\n if (self.init) {\n if (self.init instanceof AST_Definitions) {\n self.init.print(output);\n } else {\n parenthesize_for_noin(self.init, output, true);\n }\n output.print(\";\");\n output.space();\n } else {\n output.print(\";\");\n }\n if (self.condition) {\n self.condition.print(output);\n output.print(\";\");\n output.space();\n } else {\n output.print(\";\");\n }\n if (self.step) {\n self.step.print(output);\n }\n });\n output.space();\n self._do_print_body(output);\n });\n DEFPRINT(AST_ForIn, function(self, output){\n output.print(\"for\");\n output.space();\n output.with_parens(function(){\n self.init.print(output);\n output.space();\n output.print(\"in\");\n output.space();\n self.object.print(output);\n });\n output.space();\n self._do_print_body(output);\n });\n DEFPRINT(AST_With, function(self, output){\n output.print(\"with\");\n output.space();\n output.with_parens(function(){\n self.expression.print(output);\n });\n output.space();\n self._do_print_body(output);\n });\n\n /* -----[ functions ]----- */\n AST_Lambda.DEFMETHOD(\"_do_print\", function(output, nokeyword){\n var self = this;\n if (!nokeyword) {\n output.print(\"function\");\n }\n if (self.name) {\n output.space();\n self.name.print(output);\n }\n output.with_parens(function(){\n self.argnames.forEach(function(arg, i){\n if (i) output.comma();\n arg.print(output);\n });\n });\n output.space();\n print_bracketed(self.body, output);\n });\n DEFPRINT(AST_Lambda, function(self, output){\n self._do_print(output);\n });\n\n /* -----[ exits ]----- */\n AST_Exit.DEFMETHOD(\"_do_print\", function(output, kind){\n output.print(kind);\n if (this.value) {\n output.space();\n this.value.print(output);\n }\n output.semicolon();\n });\n DEFPRINT(AST_Return, function(self, output){\n self._do_print(output, \"return\");\n });\n DEFPRINT(AST_Throw, function(self, output){\n self._do_print(output, \"throw\");\n });\n\n /* -----[ loop control ]----- */\n AST_LoopControl.DEFMETHOD(\"_do_print\", function(output, kind){\n output.print(kind);\n if (this.label) {\n output.space();\n this.label.print(output);\n }\n output.semicolon();\n });\n DEFPRINT(AST_Break, function(self, output){\n self._do_print(output, \"break\");\n });\n DEFPRINT(AST_Continue, function(self, output){\n self._do_print(output, \"continue\");\n });\n\n /* -----[ if ]----- */\n function make_then(self, output) {\n if (output.option(\"bracketize\")) {\n make_block(self.body, output);\n return;\n }\n // The squeezer replaces \"block\"-s that contain only a single\n // statement with the statement itself; technically, the AST\n // is correct, but this can create problems when we output an\n // IF having an ELSE clause where the THEN clause ends in an\n // IF *without* an ELSE block (then the outer ELSE would refer\n // to the inner IF). This function checks for this case and\n // adds the block brackets if needed.\n if (!self.body)\n return output.force_semicolon();\n if (self.body instanceof AST_Do\n && !output.option(\"screw_ie8\")) {\n // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE\n // croaks with \"syntax error\" on code like this: if (foo)\n // do ... while(cond); else ... we need block brackets\n // around do/while\n make_block(self.body, output);\n return;\n }\n var b = self.body;\n while (true) {\n if (b instanceof AST_If) {\n if (!b.alternative) {\n make_block(self.body, output);\n return;\n }\n b = b.alternative;\n }\n else if (b instanceof AST_StatementWithBody) {\n b = b.body;\n }\n else break;\n }\n force_statement(self.body, output);\n };\n DEFPRINT(AST_If, function(self, output){\n output.print(\"if\");\n output.space();\n output.with_parens(function(){\n self.condition.print(output);\n });\n output.space();\n if (self.alternative) {\n make_then(self, output);\n output.space();\n output.print(\"else\");\n output.space();\n force_statement(self.alternative, output);\n } else {\n self._do_print_body(output);\n }\n });\n\n /* -----[ switch ]----- */\n DEFPRINT(AST_Switch, function(self, output){\n output.print(\"switch\");\n output.space();\n output.with_parens(function(){\n self.expression.print(output);\n });\n output.space();\n if (self.body.length > 0) output.with_block(function(){\n self.body.forEach(function(stmt, i){\n if (i) output.newline();\n output.indent(true);\n stmt.print(output);\n });\n });\n else output.print(\"{}\");\n });\n AST_SwitchBranch.DEFMETHOD(\"_do_print_body\", function(output){\n if (this.body.length > 0) {\n output.newline();\n this.body.forEach(function(stmt){\n output.indent();\n stmt.print(output);\n output.newline();\n });\n }\n });\n DEFPRINT(AST_Default, function(self, output){\n output.print(\"default:\");\n self._do_print_body(output);\n });\n DEFPRINT(AST_Case, function(self, output){\n output.print(\"case\");\n output.space();\n self.expression.print(output);\n output.print(\":\");\n self._do_print_body(output);\n });\n\n /* -----[ exceptions ]----- */\n DEFPRINT(AST_Try, function(self, output){\n output.print(\"try\");\n output.space();\n print_bracketed(self.body, output);\n if (self.bcatch) {\n output.space();\n self.bcatch.print(output);\n }\n if (self.bfinally) {\n output.space();\n self.bfinally.print(output);\n }\n });\n DEFPRINT(AST_Catch, function(self, output){\n output.print(\"catch\");\n output.space();\n output.with_parens(function(){\n self.argname.print(output);\n });\n output.space();\n print_bracketed(self.body, output);\n });\n DEFPRINT(AST_Finally, function(self, output){\n output.print(\"finally\");\n output.space();\n print_bracketed(self.body, output);\n });\n\n /* -----[ var/const ]----- */\n AST_Definitions.DEFMETHOD(\"_do_print\", function(output, kind){\n output.print(kind);\n output.space();\n this.definitions.forEach(function(def, i){\n if (i) output.comma();\n def.print(output);\n });\n var p = output.parent();\n var in_for = p instanceof AST_For || p instanceof AST_ForIn;\n var avoid_semicolon = in_for && p.init === this;\n if (!avoid_semicolon)\n output.semicolon();\n });\n DEFPRINT(AST_Var, function(self, output){\n self._do_print(output, \"var\");\n });\n DEFPRINT(AST_Const, function(self, output){\n self._do_print(output, \"const\");\n });\n\n function parenthesize_for_noin(node, output, noin) {\n if (!noin) node.print(output);\n else try {\n // need to take some precautions here:\n // https://github.com/mishoo/UglifyJS2/issues/60\n node.walk(new TreeWalker(function(node){\n if (node instanceof AST_Binary && node.operator == \"in\")\n throw output;\n }));\n node.print(output);\n } catch(ex) {\n if (ex !== output) throw ex;\n node.print(output, true);\n }\n };\n\n DEFPRINT(AST_VarDef, function(self, output){\n self.name.print(output);\n if (self.value) {\n output.space();\n output.print(\"=\");\n output.space();\n var p = output.parent(1);\n var noin = p instanceof AST_For || p instanceof AST_ForIn;\n parenthesize_for_noin(self.value, output, noin);\n }\n });\n\n /* -----[ other expressions ]----- */\n DEFPRINT(AST_Call, function(self, output){\n self.expression.print(output);\n if (self instanceof AST_New && no_constructor_parens(self, output))\n return;\n output.with_parens(function(){\n self.args.forEach(function(expr, i){\n if (i) output.comma();\n expr.print(output);\n });\n });\n });\n DEFPRINT(AST_New, function(self, output){\n output.print(\"new\");\n output.space();\n AST_Call.prototype._codegen(self, output);\n });\n\n AST_Seq.DEFMETHOD(\"_do_print\", function(output){\n this.car.print(output);\n if (this.cdr) {\n output.comma();\n if (output.should_break()) {\n output.newline();\n output.indent();\n }\n this.cdr.print(output);\n }\n });\n DEFPRINT(AST_Seq, function(self, output){\n self._do_print(output);\n // var p = output.parent();\n // if (p instanceof AST_Statement) {\n // output.with_indent(output.next_indent(), function(){\n // self._do_print(output);\n // });\n // } else {\n // self._do_print(output);\n // }\n });\n DEFPRINT(AST_Dot, function(self, output){\n var expr = self.expression;\n expr.print(output);\n if (expr instanceof AST_Number && expr.getValue() >= 0) {\n if (!/[xa-f.]/i.test(output.last())) {\n output.print(\".\");\n }\n }\n output.print(\".\");\n // the name after dot would be mapped about here.\n output.add_mapping(self.end);\n output.print_name(self.property);\n });\n DEFPRINT(AST_Sub, function(self, output){\n self.expression.print(output);\n output.print(\"[\");\n self.property.print(output);\n output.print(\"]\");\n });\n DEFPRINT(AST_UnaryPrefix, function(self, output){\n var op = self.operator;\n output.print(op);\n if (/^[a-z]/i.test(op))\n output.space();\n self.expression.print(output);\n });\n DEFPRINT(AST_UnaryPostfix, function(self, output){\n self.expression.print(output);\n output.print(self.operator);\n });\n DEFPRINT(AST_Binary, function(self, output){\n self.left.print(output);\n output.space();\n output.print(self.operator);\n if (self.operator == \"<\"\n && self.right instanceof AST_UnaryPrefix\n && self.right.operator == \"!\"\n && self.right.expression instanceof AST_UnaryPrefix\n && self.right.expression.operator == \"--\") {\n // space is mandatory to avoid outputting <!--\n // http://javascript.spec.whatwg.org/#comment-syntax\n output.print(\" \");\n } else {\n // the space is optional depending on \"beautify\"\n output.space();\n }\n self.right.print(output);\n });\n DEFPRINT(AST_Conditional, function(self, output){\n self.condition.print(output);\n output.space();\n output.print(\"?\");\n output.space();\n self.consequent.print(output);\n output.space();\n output.colon();\n self.alternative.print(output);\n });\n\n /* -----[ literals ]----- */\n DEFPRINT(AST_Array, function(self, output){\n output.with_square(function(){\n var a = self.elements, len = a.length;\n if (len > 0) output.space();\n a.forEach(function(exp, i){\n if (i) output.comma();\n exp.print(output);\n // If the final element is a hole, we need to make sure it\n // doesn't look like a trailing comma, by inserting an actual\n // trailing comma.\n if (i === len - 1 && exp instanceof AST_Hole)\n output.comma();\n });\n if (len > 0) output.space();\n });\n });\n DEFPRINT(AST_Object, function(self, output){\n if (self.properties.length > 0) output.with_block(function(){\n self.properties.forEach(function(prop, i){\n if (i) {\n output.print(\",\");\n output.newline();\n }\n output.indent();\n prop.print(output);\n });\n output.newline();\n });\n else output.print(\"{}\");\n });\n DEFPRINT(AST_ObjectKeyVal, function(self, output){\n var key = self.key;\n if (output.option(\"quote_keys\")) {\n output.print_string(key + \"\");\n } else if ((typeof key == \"number\"\n || !output.option(\"beautify\")\n && +key + \"\" == key)\n && parseFloat(key) >= 0) {\n output.print(make_num(key));\n } else if (RESERVED_WORDS(key) ? output.option(\"screw_ie8\") : is_identifier_string(key)) {\n output.print_name(key);\n } else {\n output.print_string(key);\n }\n output.colon();\n self.value.print(output);\n });\n DEFPRINT(AST_ObjectSetter, function(self, output){\n output.print(\"set\");\n output.space();\n self.key.print(output);\n self.value._do_print(output, true);\n });\n DEFPRINT(AST_ObjectGetter, function(self, output){\n output.print(\"get\");\n output.space();\n self.key.print(output);\n self.value._do_print(output, true);\n });\n DEFPRINT(AST_Symbol, function(self, output){\n var def = self.definition();\n output.print_name(def ? def.mangled_name || def.name : self.name);\n });\n DEFPRINT(AST_Undefined, function(self, output){\n output.print(\"void 0\");\n });\n DEFPRINT(AST_Hole, noop);\n DEFPRINT(AST_Infinity, function(self, output){\n output.print(\"1/0\");\n });\n DEFPRINT(AST_NaN, function(self, output){\n output.print(\"0/0\");\n });\n DEFPRINT(AST_This, function(self, output){\n output.print(\"this\");\n });\n DEFPRINT(AST_Constant, function(self, output){\n output.print(self.getValue());\n });\n DEFPRINT(AST_String, function(self, output){\n output.print_string(self.getValue());\n });\n DEFPRINT(AST_Number, function(self, output){\n output.print(make_num(self.getValue()));\n });\n\n function regexp_safe_literal(code) {\n return [\n 0x5c , // \\\n 0x2f , // /\n 0x2e , // .\n 0x2b , // +\n 0x2a , // *\n 0x3f , // ?\n 0x28 , // (\n 0x29 , // )\n 0x5b , // [\n 0x5d , // ]\n 0x7b , // {\n 0x7d , // }\n 0x24 , // $\n 0x5e , // ^\n 0x3a , // :\n 0x7c , // |\n 0x21 , // !\n 0x0a , // \\n\n 0x0d , // \\r\n 0x00 , // \\0\n 0xfeff , // Unicode BOM\n 0x2028 , // unicode \"line separator\"\n 0x2029 , // unicode \"paragraph separator\"\n ].indexOf(code) < 0;\n };\n\n DEFPRINT(AST_RegExp, function(self, output){\n var str = self.getValue().toString();\n if (output.option(\"ascii_only\")) {\n str = output.to_ascii(str);\n } else if (output.option(\"unescape_regexps\")) {\n str = str.split(\"\\\\\\\\\").map(function(str){\n return str.replace(/\\\\u[0-9a-fA-F]{4}|\\\\x[0-9a-fA-F]{2}/g, function(s){\n var code = parseInt(s.substr(2), 16);\n return regexp_safe_literal(code) ? String.fromCharCode(code) : s;\n });\n }).join(\"\\\\\\\\\");\n }\n output.print(str);\n var p = output.parent();\n if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)\n output.print(\" \");\n });\n\n function force_statement(stat, output) {\n if (output.option(\"bracketize\")) {\n if (!stat || stat instanceof AST_EmptyStatement)\n output.print(\"{}\");\n else if (stat instanceof AST_BlockStatement)\n stat.print(output);\n else output.with_block(function(){\n output.indent();\n stat.print(output);\n output.newline();\n });\n } else {\n if (!stat || stat instanceof AST_EmptyStatement)\n output.force_semicolon();\n else\n stat.print(output);\n }\n };\n\n // return true if the node at the top of the stack (that means the\n // innermost node in the current output) is lexically the first in\n // a statement.\n function first_in_statement(output) {\n var a = output.stack(), i = a.length, node = a[--i], p = a[--i];\n while (i > 0) {\n if (p instanceof AST_Statement && p.body === node)\n return true;\n if ((p instanceof AST_Seq && p.car === node ) ||\n (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) ||\n (p instanceof AST_Dot && p.expression === node ) ||\n (p instanceof AST_Sub && p.expression === node ) ||\n (p instanceof AST_Conditional && p.condition === node ) ||\n (p instanceof AST_Binary && p.left === node ) ||\n (p instanceof AST_UnaryPostfix && p.expression === node ))\n {\n node = p;\n p = a[--i];\n } else {\n return false;\n }\n }\n };\n\n // self should be AST_New. decide if we want to show parens or not.\n function no_constructor_parens(self, output) {\n return self.args.length == 0 && !output.option(\"beautify\");\n };\n\n function best_of(a) {\n var best = a[0], len = best.length;\n for (var i = 1; i < a.length; ++i) {\n if (a[i].length < len) {\n best = a[i];\n len = best.length;\n }\n }\n return best;\n };\n\n function make_num(num) {\n var str = num.toString(10), a = [ str.replace(/^0\\./, \".\").replace('e+', 'e') ], m;\n if (Math.floor(num) === num) {\n if (num >= 0) {\n a.push(\"0x\" + num.toString(16).toLowerCase(), // probably pointless\n \"0\" + num.toString(8)); // same.\n } else {\n a.push(\"-0x\" + (-num).toString(16).toLowerCase(), // probably pointless\n \"-0\" + (-num).toString(8)); // same.\n }\n if ((m = /^(.*?)(0+)$/.exec(num))) {\n a.push(m[1] + \"e\" + m[2].length);\n }\n } else if ((m = /^0?\\.(0+)(.*)$/.exec(num))) {\n a.push(m[2] + \"e-\" + (m[1].length + m[2].length),\n str.substr(str.indexOf(\".\")));\n }\n return best_of(a);\n };\n\n function make_block(stmt, output) {\n if (stmt instanceof AST_BlockStatement) {\n stmt.print(output);\n return;\n }\n output.with_block(function(){\n output.indent();\n stmt.print(output);\n output.newline();\n });\n };\n\n /* -----[ source map generators ]----- */\n\n function DEFMAP(nodetype, generator) {\n nodetype.DEFMETHOD(\"add_source_map\", function(stream){\n generator(this, stream);\n });\n };\n\n // We could easily add info for ALL nodes, but it seems to me that\n // would be quite wasteful, hence this noop in the base class.\n DEFMAP(AST_Node, noop);\n\n function basic_sourcemap_gen(self, output) {\n output.add_mapping(self.start);\n };\n\n // XXX: I'm not exactly sure if we need it for all of these nodes,\n // or if we should add even more.\n\n DEFMAP(AST_Directive, basic_sourcemap_gen);\n DEFMAP(AST_Debugger, basic_sourcemap_gen);\n DEFMAP(AST_Symbol, basic_sourcemap_gen);\n DEFMAP(AST_Jump, basic_sourcemap_gen);\n DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);\n DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it\n DEFMAP(AST_Lambda, basic_sourcemap_gen);\n DEFMAP(AST_Switch, basic_sourcemap_gen);\n DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);\n DEFMAP(AST_BlockStatement, basic_sourcemap_gen);\n DEFMAP(AST_Toplevel, noop);\n DEFMAP(AST_New, basic_sourcemap_gen);\n DEFMAP(AST_Try, basic_sourcemap_gen);\n DEFMAP(AST_Catch, basic_sourcemap_gen);\n DEFMAP(AST_Finally, basic_sourcemap_gen);\n DEFMAP(AST_Definitions, basic_sourcemap_gen);\n DEFMAP(AST_Constant, basic_sourcemap_gen);\n DEFMAP(AST_ObjectProperty, function(self, output){\n output.add_mapping(self.start, self.key);\n });\n\n})();\n\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n https://github.com/mishoo/UglifyJS2\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2012 (c) Mihai Bazon <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n\"use strict\";\n\nfunction Compressor(options, false_by_default) {\n if (!(this instanceof Compressor))\n return new Compressor(options, false_by_default);\n TreeTransformer.call(this, this.before, this.after);\n this.options = defaults(options, {\n sequences : !false_by_default,\n properties : !false_by_default,\n dead_code : !false_by_default,\n drop_debugger : !false_by_default,\n unsafe : false,\n unsafe_comps : false,\n conditionals : !false_by_default,\n comparisons : !false_by_default,\n evaluate : !false_by_default,\n booleans : !false_by_default,\n loops : !false_by_default,\n unused : !false_by_default,\n hoist_funs : !false_by_default,\n keep_fargs : false,\n hoist_vars : false,\n if_return : !false_by_default,\n join_vars : !false_by_default,\n cascade : !false_by_default,\n side_effects : !false_by_default,\n pure_getters : false,\n pure_funcs : null,\n negate_iife : !false_by_default,\n screw_ie8 : false,\n drop_console : false,\n angular : false,\n\n warnings : true,\n global_defs : {}\n }, true);\n};\n\nCompressor.prototype = new TreeTransformer;\nmerge(Compressor.prototype, {\n option: function(key) { return this.options[key] },\n warn: function() {\n if (this.options.warnings)\n AST_Node.warn.apply(AST_Node, arguments);\n },\n before: function(node, descend, in_list) {\n if (node._squeezed) return node;\n var was_scope = false;\n if (node instanceof AST_Scope) {\n node = node.hoist_declarations(this);\n was_scope = true;\n }\n descend(node, this);\n node = node.optimize(this);\n if (was_scope && node instanceof AST_Scope) {\n node.drop_unused(this);\n descend(node, this);\n }\n node._squeezed = true;\n return node;\n }\n});\n\n(function(){\n\n function OPT(node, optimizer) {\n node.DEFMETHOD(\"optimize\", function(compressor){\n var self = this;\n if (self._optimized) return self;\n var opt = optimizer(self, compressor);\n opt._optimized = true;\n if (opt === self) return opt;\n return opt.transform(compressor);\n });\n };\n\n OPT(AST_Node, function(self, compressor){\n return self;\n });\n\n AST_Node.DEFMETHOD(\"equivalent_to\", function(node){\n // XXX: this is a rather expensive way to test two node's equivalence:\n return this.print_to_string() == node.print_to_string();\n });\n\n function make_node(ctor, orig, props) {\n if (!props) props = {};\n if (orig) {\n if (!props.start) props.start = orig.start;\n if (!props.end) props.end = orig.end;\n }\n return new ctor(props);\n };\n\n function make_node_from_constant(compressor, val, orig) {\n // XXX: WIP.\n // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){\n // if (node instanceof AST_SymbolRef) {\n // var scope = compressor.find_parent(AST_Scope);\n // var def = scope.find_variable(node);\n // node.thedef = def;\n // return node;\n // }\n // })).transform(compressor);\n\n if (val instanceof AST_Node) return val.transform(compressor);\n switch (typeof val) {\n case \"string\":\n return make_node(AST_String, orig, {\n value: val\n }).optimize(compressor);\n case \"number\":\n return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, {\n value: val\n }).optimize(compressor);\n case \"boolean\":\n return make_node(val ? AST_True : AST_False, orig).optimize(compressor);\n case \"undefined\":\n return make_node(AST_Undefined, orig).optimize(compressor);\n default:\n if (val === null) {\n return make_node(AST_Null, orig).optimize(compressor);\n }\n if (val instanceof RegExp) {\n return make_node(AST_RegExp, orig).optimize(compressor);\n }\n throw new Error(string_template(\"Can't handle constant of type: {type}\", {\n type: typeof val\n }));\n }\n };\n\n function as_statement_array(thing) {\n if (thing === null) return [];\n if (thing instanceof AST_BlockStatement) return thing.body;\n if (thing instanceof AST_EmptyStatement) return [];\n if (thing instanceof AST_Statement) return [ thing ];\n throw new Error(\"Can't convert thing to statement array\");\n };\n\n function is_empty(thing) {\n if (thing === null) return true;\n if (thing instanceof AST_EmptyStatement) return true;\n if (thing instanceof AST_BlockStatement) return thing.body.length == 0;\n return false;\n };\n\n function loop_body(x) {\n if (x instanceof AST_Switch) return x;\n if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {\n return (x.body instanceof AST_BlockStatement ? x.body : x);\n }\n return x;\n };\n\n function tighten_body(statements, compressor) {\n var CHANGED;\n do {\n CHANGED = false;\n if (compressor.option(\"angular\")) {\n statements = process_for_angular(statements);\n }\n statements = eliminate_spurious_blocks(statements);\n if (compressor.option(\"dead_code\")) {\n statements = eliminate_dead_code(statements, compressor);\n }\n if (compressor.option(\"if_return\")) {\n statements = handle_if_return(statements, compressor);\n }\n if (compressor.option(\"sequences\")) {\n statements = sequencesize(statements, compressor);\n }\n if (compressor.option(\"join_vars\")) {\n statements = join_consecutive_vars(statements, compressor);\n }\n } while (CHANGED);\n\n if (compressor.option(\"negate_iife\")) {\n negate_iifes(statements, compressor);\n }\n\n return statements;\n\n function process_for_angular(statements) {\n function make_injector(func, name) {\n return make_node(AST_SimpleStatement, func, {\n body: make_node(AST_Assign, func, {\n operator: \"=\",\n left: make_node(AST_Dot, name, {\n expression: make_node(AST_SymbolRef, name, name),\n property: \"$inject\"\n }),\n right: make_node(AST_Array, func, {\n elements: func.argnames.map(function(sym){\n return make_node(AST_String, sym, { value: sym.name });\n })\n })\n })\n });\n }\n return statements.reduce(function(a, stat){\n a.push(stat);\n var token = stat.start;\n var comments = token.comments_before;\n if (comments && comments.length > 0) {\n var last = comments.pop();\n if (/@ngInject/.test(last.value)) {\n // case 1: defun\n if (stat instanceof AST_Defun) {\n a.push(make_injector(stat, stat.name));\n }\n else if (stat instanceof AST_Definitions) {\n stat.definitions.forEach(function(def){\n if (def.value && def.value instanceof AST_Lambda) {\n a.push(make_injector(def.value, def.name));\n }\n });\n }\n else {\n compressor.warn(\"Unknown statement marked with @ngInject [{file}:{line},{col}]\", token);\n }\n }\n }\n return a;\n }, []);\n }\n\n function eliminate_spurious_blocks(statements) {\n var seen_dirs = [];\n return statements.reduce(function(a, stat){\n if (stat instanceof AST_BlockStatement) {\n CHANGED = true;\n a.push.apply(a, eliminate_spurious_blocks(stat.body));\n } else if (stat instanceof AST_EmptyStatement) {\n CHANGED = true;\n } else if (stat instanceof AST_Directive) {\n if (seen_dirs.indexOf(stat.value) < 0) {\n a.push(stat);\n seen_dirs.push(stat.value);\n } else {\n CHANGED = true;\n }\n } else {\n a.push(stat);\n }\n return a;\n }, []);\n };\n\n function handle_if_return(statements, compressor) {\n var self = compressor.self();\n var in_lambda = self instanceof AST_Lambda;\n var ret = [];\n loop: for (var i = statements.length; --i >= 0;) {\n var stat = statements[i];\n switch (true) {\n case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):\n CHANGED = true;\n // note, ret.length is probably always zero\n // because we drop unreachable code before this\n // step. nevertheless, it's good to check.\n continue loop;\n case stat instanceof AST_If:\n if (stat.body instanceof AST_Return) {\n //---\n // pretty silly case, but:\n // if (foo()) return; return; ==> foo(); return;\n if (((in_lambda && ret.length == 0)\n || (ret[0] instanceof AST_Return && !ret[0].value))\n && !stat.body.value && !stat.alternative) {\n CHANGED = true;\n var cond = make_node(AST_SimpleStatement, stat.condition, {\n body: stat.condition\n });\n ret.unshift(cond);\n continue loop;\n }\n //---\n // if (foo()) return x; return y; ==> return foo() ? x : y;\n if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {\n CHANGED = true;\n stat = stat.clone();\n stat.alternative = ret[0];\n ret[0] = stat.transform(compressor);\n continue loop;\n }\n //---\n // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;\n if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) {\n CHANGED = true;\n stat = stat.clone();\n stat.alternative = ret[0] || make_node(AST_Return, stat, {\n value: make_node(AST_Undefined, stat)\n });\n ret[0] = stat.transform(compressor);\n continue loop;\n }\n //---\n // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }\n if (!stat.body.value && in_lambda) {\n CHANGED = true;\n stat = stat.clone();\n stat.condition = stat.condition.negate(compressor);\n stat.body = make_node(AST_BlockStatement, stat, {\n body: as_statement_array(stat.alternative).concat(ret)\n });\n stat.alternative = null;\n ret = [ stat.transform(compressor) ];\n continue loop;\n }\n //---\n if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement\n && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {\n CHANGED = true;\n ret.push(make_node(AST_Return, ret[0], {\n value: make_node(AST_Undefined, ret[0])\n }).transform(compressor));\n ret = as_statement_array(stat.alternative).concat(ret);\n ret.unshift(stat);\n continue loop;\n }\n }\n\n var ab = aborts(stat.body);\n var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;\n if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)\n || (ab instanceof AST_Continue && self === loop_body(lct))\n || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {\n if (ab.label) {\n remove(ab.label.thedef.references, ab);\n }\n CHANGED = true;\n var body = as_statement_array(stat.body).slice(0, -1);\n stat = stat.clone();\n stat.condition = stat.condition.negate(compressor);\n stat.body = make_node(AST_BlockStatement, stat, {\n body: as_statement_array(stat.alternative).concat(ret)\n });\n stat.alternative = make_node(AST_BlockStatement, stat, {\n body: body\n });\n ret = [ stat.transform(compressor) ];\n continue loop;\n }\n\n var ab = aborts(stat.alternative);\n var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;\n if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)\n || (ab instanceof AST_Continue && self === loop_body(lct))\n || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {\n if (ab.label) {\n remove(ab.label.thedef.references, ab);\n }\n CHANGED = true;\n stat = stat.clone();\n stat.body = make_node(AST_BlockStatement, stat.body, {\n body: as_statement_array(stat.body).concat(ret)\n });\n stat.alternative = make_node(AST_BlockStatement, stat.alternative, {\n body: as_statement_array(stat.alternative).slice(0, -1)\n });\n ret = [ stat.transform(compressor) ];\n continue loop;\n }\n\n ret.unshift(stat);\n break;\n default:\n ret.unshift(stat);\n break;\n }\n }\n return ret;\n };\n\n function eliminate_dead_code(statements, compressor) {\n var has_quit = false;\n var orig = statements.length;\n var self = compressor.self();\n statements = statements.reduce(function(a, stat){\n if (has_quit) {\n extract_declarations_from_unreachable_code(compressor, stat, a);\n } else {\n if (stat instanceof AST_LoopControl) {\n var lct = compressor.loopcontrol_target(stat.label);\n if ((stat instanceof AST_Break\n && lct instanceof AST_BlockStatement\n && loop_body(lct) === self) || (stat instanceof AST_Continue\n && loop_body(lct) === self)) {\n if (stat.label) {\n remove(stat.label.thedef.references, stat);\n }\n } else {\n a.push(stat);\n }\n } else {\n a.push(stat);\n }\n if (aborts(stat)) has_quit = true;\n }\n return a;\n }, []);\n CHANGED = statements.length != orig;\n return statements;\n };\n\n function sequencesize(statements, compressor) {\n if (statements.length < 2) return statements;\n var seq = [], ret = [];\n function push_seq() {\n seq = AST_Seq.from_array(seq);\n if (seq) ret.push(make_node(AST_SimpleStatement, seq, {\n body: seq\n }));\n seq = [];\n };\n statements.forEach(function(stat){\n if (stat instanceof AST_SimpleStatement) seq.push(stat.body);\n else push_seq(), ret.push(stat);\n });\n push_seq();\n ret = sequencesize_2(ret, compressor);\n CHANGED = ret.length != statements.length;\n return ret;\n };\n\n function sequencesize_2(statements, compressor) {\n function cons_seq(right) {\n ret.pop();\n var left = prev.body;\n if (left instanceof AST_Seq) {\n left.add(right);\n } else {\n left = AST_Seq.cons(left, right);\n }\n return left.transform(compressor);\n };\n var ret = [], prev = null;\n statements.forEach(function(stat){\n if (prev) {\n if (stat instanceof AST_For) {\n var opera = {};\n try {\n prev.body.walk(new TreeWalker(function(node){\n if (node instanceof AST_Binary && node.operator == \"in\")\n throw opera;\n }));\n if (stat.init && !(stat.init instanceof AST_Definitions)) {\n stat.init = cons_seq(stat.init);\n }\n else if (!stat.init) {\n stat.init = prev.body;\n ret.pop();\n }\n } catch(ex) {\n if (ex !== opera) throw ex;\n }\n }\n else if (stat instanceof AST_If) {\n stat.condition = cons_seq(stat.condition);\n }\n else if (stat instanceof AST_With) {\n stat.expression = cons_seq(stat.expression);\n }\n else if (stat instanceof AST_Exit && stat.value) {\n stat.value = cons_seq(stat.value);\n }\n else if (stat instanceof AST_Exit) {\n stat.value = cons_seq(make_node(AST_Undefined, stat));\n }\n else if (stat instanceof AST_Switch) {\n stat.expression = cons_seq(stat.expression);\n }\n }\n ret.push(stat);\n prev = stat instanceof AST_SimpleStatement ? stat : null;\n });\n return ret;\n };\n\n function join_consecutive_vars(statements, compressor) {\n var prev = null;\n return statements.reduce(function(a, stat){\n if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {\n prev.definitions = prev.definitions.concat(stat.definitions);\n CHANGED = true;\n }\n else if (stat instanceof AST_For\n && prev instanceof AST_Definitions\n && (!stat.init || stat.init.TYPE == prev.TYPE)) {\n CHANGED = true;\n a.pop();\n if (stat.init) {\n stat.init.definitions = prev.definitions.concat(stat.init.definitions);\n } else {\n stat.init = prev;\n }\n a.push(stat);\n prev = stat;\n }\n else {\n prev = stat;\n a.push(stat);\n }\n return a;\n }, []);\n };\n\n function negate_iifes(statements, compressor) {\n statements.forEach(function(stat){\n if (stat instanceof AST_SimpleStatement) {\n stat.body = (function transform(thing) {\n return thing.transform(new TreeTransformer(function(node){\n if (node instanceof AST_Call && node.expression instanceof AST_Function) {\n return make_node(AST_UnaryPrefix, node, {\n operator: \"!\",\n expression: node\n });\n }\n else if (node instanceof AST_Call) {\n node.expression = transform(node.expression);\n }\n else if (node instanceof AST_Seq) {\n node.car = transform(node.car);\n }\n else if (node instanceof AST_Conditional) {\n var expr = transform(node.condition);\n if (expr !== node.condition) {\n // it has been negated, reverse\n node.condition = expr;\n var tmp = node.consequent;\n node.consequent = node.alternative;\n node.alternative = tmp;\n }\n }\n return node;\n }));\n })(stat.body);\n }\n });\n };\n\n };\n\n function extract_declarations_from_unreachable_code(compressor, stat, target) {\n compressor.warn(\"Dropping unreachable code [{file}:{line},{col}]\", stat.start);\n stat.walk(new TreeWalker(function(node){\n if (node instanceof AST_Definitions) {\n compressor.warn(\"Declarations in unreachable code! [{file}:{line},{col}]\", node.start);\n node.remove_initializers();\n target.push(node);\n return true;\n }\n if (node instanceof AST_Defun) {\n target.push(node);\n return true;\n }\n if (node instanceof AST_Scope) {\n return true;\n }\n }));\n };\n\n /* -----[ boolean/negation helpers ]----- */\n\n // methods to determine whether an expression has a boolean result type\n (function (def){\n var unary_bool = [ \"!\", \"delete\" ];\n var binary_bool = [ \"in\", \"instanceof\", \"==\", \"!=\", \"===\", \"!==\", \"<\", \"<=\", \">=\", \">\" ];\n def(AST_Node, function(){ return false });\n def(AST_UnaryPrefix, function(){\n return member(this.operator, unary_bool);\n });\n def(AST_Binary, function(){\n return member(this.operator, binary_bool) ||\n ( (this.operator == \"&&\" || this.operator == \"||\") &&\n this.left.is_boolean() && this.right.is_boolean() );\n });\n def(AST_Conditional, function(){\n return this.consequent.is_boolean() && this.alternative.is_boolean();\n });\n def(AST_Assign, function(){\n return this.operator == \"=\" && this.right.is_boolean();\n });\n def(AST_Seq, function(){\n return this.cdr.is_boolean();\n });\n def(AST_True, function(){ return true });\n def(AST_False, function(){ return true });\n })(function(node, func){\n node.DEFMETHOD(\"is_boolean\", func);\n });\n\n // methods to determine if an expression has a string result type\n (function (def){\n def(AST_Node, function(){ return false });\n def(AST_String, function(){ return true });\n def(AST_UnaryPrefix, function(){\n return this.operator == \"typeof\";\n });\n def(AST_Binary, function(compressor){\n return this.operator == \"+\" &&\n (this.left.is_string(compressor) || this.right.is_string(compressor));\n });\n def(AST_Assign, function(compressor){\n return (this.operator == \"=\" || this.operator == \"+=\") && this.right.is_string(compressor);\n });\n def(AST_Seq, function(compressor){\n return this.cdr.is_string(compressor);\n });\n def(AST_Conditional, function(compressor){\n return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);\n });\n def(AST_Call, function(compressor){\n return compressor.option(\"unsafe\")\n && this.expression instanceof AST_SymbolRef\n && this.expression.name == \"String\"\n && this.expression.undeclared();\n });\n })(function(node, func){\n node.DEFMETHOD(\"is_string\", func);\n });\n\n function best_of(ast1, ast2) {\n return ast1.print_to_string().length >\n ast2.print_to_string().length\n ? ast2 : ast1;\n };\n\n // methods to evaluate a constant expression\n (function (def){\n // The evaluate method returns an array with one or two\n // elements. If the node has been successfully reduced to a\n // constant, then the second element tells us the value;\n // otherwise the second element is missing. The first element\n // of the array is always an AST_Node descendant; if\n // evaluation was successful it's a node that represents the\n // constant; otherwise it's the original or a replacement node.\n AST_Node.DEFMETHOD(\"evaluate\", function(compressor){\n if (!compressor.option(\"evaluate\")) return [ this ];\n try {\n var val = this._eval(compressor);\n return [ best_of(make_node_from_constant(compressor, val, this), this), val ];\n } catch(ex) {\n if (ex !== def) throw ex;\n return [ this ];\n }\n });\n def(AST_Statement, function(){\n throw new Error(string_template(\"Cannot evaluate a statement [{file}:{line},{col}]\", this.start));\n });\n def(AST_Function, function(){\n // XXX: AST_Function inherits from AST_Scope, which itself\n // inherits from AST_Statement; however, an AST_Function\n // isn't really a statement. This could byte in other\n // places too. :-( Wish JS had multiple inheritance.\n throw def;\n });\n function ev(node, compressor) {\n if (!compressor) throw new Error(\"Compressor must be passed\");\n\n return node._eval(compressor);\n };\n def(AST_Node, function(){\n throw def; // not constant\n });\n def(AST_Constant, function(){\n return this.getValue();\n });\n def(AST_UnaryPrefix, function(compressor){\n var e = this.expression;\n switch (this.operator) {\n case \"!\": return !ev(e, compressor);\n case \"typeof\":\n // Function would be evaluated to an array and so typeof would\n // incorrectly return 'object'. Hence making is a special case.\n if (e instanceof AST_Function) return typeof function(){};\n\n e = ev(e, compressor);\n\n // typeof <RegExp> returns \"object\" or \"function\" on different platforms\n // so cannot evaluate reliably\n if (e instanceof RegExp) throw def;\n\n return typeof e;\n case \"void\": return void ev(e, compressor);\n case \"~\": return ~ev(e, compressor);\n case \"-\":\n e = ev(e, compressor);\n if (e === 0) throw def;\n return -e;\n case \"+\": return +ev(e, compressor);\n }\n throw def;\n });\n def(AST_Binary, function(c){\n var left = this.left, right = this.right;\n switch (this.operator) {\n case \"&&\" : return ev(left, c) && ev(right, c);\n case \"||\" : return ev(left, c) || ev(right, c);\n case \"|\" : return ev(left, c) | ev(right, c);\n case \"&\" : return ev(left, c) & ev(right, c);\n case \"^\" : return ev(left, c) ^ ev(right, c);\n case \"+\" : return ev(left, c) + ev(right, c);\n case \"*\" : return ev(left, c) * ev(right, c);\n case \"/\" : return ev(left, c) / ev(right, c);\n case \"%\" : return ev(left, c) % ev(right, c);\n case \"-\" : return ev(left, c) - ev(right, c);\n case \"<<\" : return ev(left, c) << ev(right, c);\n case \">>\" : return ev(left, c) >> ev(right, c);\n case \">>>\" : return ev(left, c) >>> ev(right, c);\n case \"==\" : return ev(left, c) == ev(right, c);\n case \"===\" : return ev(left, c) === ev(right, c);\n case \"!=\" : return ev(left, c) != ev(right, c);\n case \"!==\" : return ev(left, c) !== ev(right, c);\n case \"<\" : return ev(left, c) < ev(right, c);\n case \"<=\" : return ev(left, c) <= ev(right, c);\n case \">\" : return ev(left, c) > ev(right, c);\n case \">=\" : return ev(left, c) >= ev(right, c);\n case \"in\" : return ev(left, c) in ev(right, c);\n case \"instanceof\" : return ev(left, c) instanceof ev(right, c);\n }\n throw def;\n });\n def(AST_Conditional, function(compressor){\n return ev(this.condition, compressor)\n ? ev(this.consequent, compressor)\n : ev(this.alternative, compressor);\n });\n def(AST_SymbolRef, function(compressor){\n var d = this.definition();\n if (d && d.constant && d.init) return ev(d.init, compressor);\n throw def;\n });\n })(function(node, func){\n node.DEFMETHOD(\"_eval\", func);\n });\n\n // method to negate an expression\n (function(def){\n function basic_negation(exp) {\n return make_node(AST_UnaryPrefix, exp, {\n operator: \"!\",\n expression: exp\n });\n };\n def(AST_Node, function(){\n return basic_negation(this);\n });\n def(AST_Statement, function(){\n throw new Error(\"Cannot negate a statement\");\n });\n def(AST_Function, function(){\n return basic_negation(this);\n });\n def(AST_UnaryPrefix, function(){\n if (this.operator == \"!\")\n return this.expression;\n return basic_negation(this);\n });\n def(AST_Seq, function(compressor){\n var self = this.clone();\n self.cdr = self.cdr.negate(compressor);\n return self;\n });\n def(AST_Conditional, function(compressor){\n var self = this.clone();\n self.consequent = self.consequent.negate(compressor);\n self.alternative = self.alternative.negate(compressor);\n return best_of(basic_negation(this), self);\n });\n def(AST_Binary, function(compressor){\n var self = this.clone(), op = this.operator;\n if (compressor.option(\"unsafe_comps\")) {\n switch (op) {\n case \"<=\" : self.operator = \">\" ; return self;\n case \"<\" : self.operator = \">=\" ; return self;\n case \">=\" : self.operator = \"<\" ; return self;\n case \">\" : self.operator = \"<=\" ; return self;\n }\n }\n switch (op) {\n case \"==\" : self.operator = \"!=\"; return self;\n case \"!=\" : self.operator = \"==\"; return self;\n case \"===\": self.operator = \"!==\"; return self;\n case \"!==\": self.operator = \"===\"; return self;\n case \"&&\":\n self.operator = \"||\";\n self.left = self.left.negate(compressor);\n self.right = self.right.negate(compressor);\n return best_of(basic_negation(this), self);\n case \"||\":\n self.operator = \"&&\";\n self.left = self.left.negate(compressor);\n self.right = self.right.negate(compressor);\n return best_of(basic_negation(this), self);\n }\n return basic_negation(this);\n });\n })(function(node, func){\n node.DEFMETHOD(\"negate\", function(compressor){\n return func.call(this, compressor);\n });\n });\n\n // determine if expression has side effects\n (function(def){\n def(AST_Node, function(compressor){ return true });\n\n def(AST_EmptyStatement, function(compressor){ return false });\n def(AST_Constant, function(compressor){ return false });\n def(AST_This, function(compressor){ return false });\n\n def(AST_Call, function(compressor){\n var pure = compressor.option(\"pure_funcs\");\n if (!pure) return true;\n return pure.indexOf(this.expression.print_to_string()) < 0;\n });\n\n def(AST_Block, function(compressor){\n for (var i = this.body.length; --i >= 0;) {\n if (this.body[i].has_side_effects(compressor))\n return true;\n }\n return false;\n });\n\n def(AST_SimpleStatement, function(compressor){\n return this.body.has_side_effects(compressor);\n });\n def(AST_Defun, function(compressor){ return true });\n def(AST_Function, function(compressor){ return false });\n def(AST_Binary, function(compressor){\n return this.left.has_side_effects(compressor)\n || this.right.has_side_effects(compressor);\n });\n def(AST_Assign, function(compressor){ return true });\n def(AST_Conditional, function(compressor){\n return this.condition.has_side_effects(compressor)\n || this.consequent.has_side_effects(compressor)\n || this.alternative.has_side_effects(compressor);\n });\n def(AST_Unary, function(compressor){\n return this.operator == \"delete\"\n || this.operator == \"++\"\n || this.operator == \"--\"\n || this.expression.has_side_effects(compressor);\n });\n def(AST_SymbolRef, function(compressor){ return false });\n def(AST_Object, function(compressor){\n for (var i = this.properties.length; --i >= 0;)\n if (this.properties[i].has_side_effects(compressor))\n return true;\n return false;\n });\n def(AST_ObjectProperty, function(compressor){\n return this.value.has_side_effects(compressor);\n });\n def(AST_Array, function(compressor){\n for (var i = this.elements.length; --i >= 0;)\n if (this.elements[i].has_side_effects(compressor))\n return true;\n return false;\n });\n def(AST_Dot, function(compressor){\n if (!compressor.option(\"pure_getters\")) return true;\n return this.expression.has_side_effects(compressor);\n });\n def(AST_Sub, function(compressor){\n if (!compressor.option(\"pure_getters\")) return true;\n return this.expression.has_side_effects(compressor)\n || this.property.has_side_effects(compressor);\n });\n def(AST_PropAccess, function(compressor){\n return !compressor.option(\"pure_getters\");\n });\n def(AST_Seq, function(compressor){\n return this.car.has_side_effects(compressor)\n || this.cdr.has_side_effects(compressor);\n });\n })(function(node, func){\n node.DEFMETHOD(\"has_side_effects\", func);\n });\n\n // tell me if a statement aborts\n function aborts(thing) {\n return thing && thing.aborts();\n };\n (function(def){\n def(AST_Statement, function(){ return null });\n def(AST_Jump, function(){ return this });\n function block_aborts(){\n var n = this.body.length;\n return n > 0 && aborts(this.body[n - 1]);\n };\n def(AST_BlockStatement, block_aborts);\n def(AST_SwitchBranch, block_aborts);\n def(AST_If, function(){\n return this.alternative && aborts(this.body) && aborts(this.alternative);\n });\n })(function(node, func){\n node.DEFMETHOD(\"aborts\", func);\n });\n\n /* -----[ optimizers ]----- */\n\n OPT(AST_Directive, function(self, compressor){\n if (self.scope.has_directive(self.value) !== self.scope) {\n return make_node(AST_EmptyStatement, self);\n }\n return self;\n });\n\n OPT(AST_Debugger, function(self, compressor){\n if (compressor.option(\"drop_debugger\"))\n return make_node(AST_EmptyStatement, self);\n return self;\n });\n\n OPT(AST_LabeledStatement, function(self, compressor){\n if (self.body instanceof AST_Break\n && compressor.loopcontrol_target(self.body.label) === self.body) {\n return make_node(AST_EmptyStatement, self);\n }\n return self.label.references.length == 0 ? self.body : self;\n });\n\n OPT(AST_Block, function(self, compressor){\n self.body = tighten_body(self.body, compressor);\n return self;\n });\n\n OPT(AST_BlockStatement, function(self, compressor){\n self.body = tighten_body(self.body, compressor);\n switch (self.body.length) {\n case 1: return self.body[0];\n case 0: return make_node(AST_EmptyStatement, self);\n }\n return self;\n });\n\n AST_Scope.DEFMETHOD(\"drop_unused\", function(compressor){\n var self = this;\n if (compressor.option(\"unused\")\n && !(self instanceof AST_Toplevel)\n && !self.uses_eval\n ) {\n var in_use = [];\n var initializations = new Dictionary();\n // pass 1: find out which symbols are directly used in\n // this scope (not in nested scopes).\n var scope = this;\n var tw = new TreeWalker(function(node, descend){\n if (node !== self) {\n if (node instanceof AST_Defun) {\n initializations.add(node.name.name, node);\n return true; // don't go in nested scopes\n }\n if (node instanceof AST_Definitions && scope === self) {\n node.definitions.forEach(function(def){\n if (def.value) {\n initializations.add(def.name.name, def.value);\n if (def.value.has_side_effects(compressor)) {\n def.value.walk(tw);\n }\n }\n });\n return true;\n }\n if (node instanceof AST_SymbolRef) {\n push_uniq(in_use, node.definition());\n return true;\n }\n if (node instanceof AST_Scope) {\n var save_scope = scope;\n scope = node;\n descend();\n scope = save_scope;\n return true;\n }\n }\n });\n self.walk(tw);\n // pass 2: for every used symbol we need to walk its\n // initialization code to figure out if it uses other\n // symbols (that may not be in_use).\n for (var i = 0; i < in_use.length; ++i) {\n in_use[i].orig.forEach(function(decl){\n // undeclared globals will be instanceof AST_SymbolRef\n var init = initializations.get(decl.name);\n if (init) init.forEach(function(init){\n var tw = new TreeWalker(function(node){\n if (node instanceof AST_SymbolRef) {\n push_uniq(in_use, node.definition());\n }\n });\n init.walk(tw);\n });\n });\n }\n // pass 3: we should drop declarations not in_use\n var tt = new TreeTransformer(\n function before(node, descend, in_list) {\n if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {\n if (!compressor.option(\"keep_fargs\")) {\n for (var a = node.argnames, i = a.length; --i >= 0;) {\n var sym = a[i];\n if (sym.unreferenced()) {\n a.pop();\n compressor.warn(\"Dropping unused function argument {name} [{file}:{line},{col}]\", {\n name : sym.name,\n file : sym.start.file,\n line : sym.start.line,\n col : sym.start.col\n });\n }\n else break;\n }\n }\n }\n if (node instanceof AST_Defun && node !== self) {\n if (!member(node.name.definition(), in_use)) {\n compressor.warn(\"Dropping unused function {name} [{file}:{line},{col}]\", {\n name : node.name.name,\n file : node.name.start.file,\n line : node.name.start.line,\n col : node.name.start.col\n });\n return make_node(AST_EmptyStatement, node);\n }\n return node;\n }\n if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {\n var def = node.definitions.filter(function(def){\n if (member(def.name.definition(), in_use)) return true;\n var w = {\n name : def.name.name,\n file : def.name.start.file,\n line : def.name.start.line,\n col : def.name.start.col\n };\n if (def.value && def.value.has_side_effects(compressor)) {\n def._unused_side_effects = true;\n compressor.warn(\"Side effects in initialization of unused variable {name} [{file}:{line},{col}]\", w);\n return true;\n }\n compressor.warn(\"Dropping unused variable {name} [{file}:{line},{col}]\", w);\n return false;\n });\n // place uninitialized names at the start\n def = mergeSort(def, function(a, b){\n if (!a.value && b.value) return -1;\n if (!b.value && a.value) return 1;\n return 0;\n });\n // for unused names whose initialization has\n // side effects, we can cascade the init. code\n // into the next one, or next statement.\n var side_effects = [];\n for (var i = 0; i < def.length;) {\n var x = def[i];\n if (x._unused_side_effects) {\n side_effects.push(x.value);\n def.splice(i, 1);\n } else {\n if (side_effects.length > 0) {\n side_effects.push(x.value);\n x.value = AST_Seq.from_array(side_effects);\n side_effects = [];\n }\n ++i;\n }\n }\n if (side_effects.length > 0) {\n side_effects = make_node(AST_BlockStatement, node, {\n body: [ make_node(AST_SimpleStatement, node, {\n body: AST_Seq.from_array(side_effects)\n }) ]\n });\n } else {\n side_effects = null;\n }\n if (def.length == 0 && !side_effects) {\n return make_node(AST_EmptyStatement, node);\n }\n if (def.length == 0) {\n return side_effects;\n }\n node.definitions = def;\n if (side_effects) {\n side_effects.body.unshift(node);\n node = side_effects;\n }\n return node;\n }\n if (node instanceof AST_For) {\n descend(node, this);\n\n if (node.init instanceof AST_BlockStatement) {\n // certain combination of unused name + side effect leads to:\n // https://github.com/mishoo/UglifyJS2/issues/44\n // that's an invalid AST.\n // We fix it at this stage by moving the `var` outside the `for`.\n\n var body = node.init.body.slice(0, -1);\n node.init = node.init.body.slice(-1)[0].body;\n body.push(node);\n\n return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {\n body: body\n });\n }\n }\n if (node instanceof AST_Scope && node !== self)\n return node;\n }\n );\n self.transform(tt);\n }\n });\n\n AST_Scope.DEFMETHOD(\"hoist_declarations\", function(compressor){\n var hoist_funs = compressor.option(\"hoist_funs\");\n var hoist_vars = compressor.option(\"hoist_vars\");\n var self = this;\n if (hoist_funs || hoist_vars) {\n var dirs = [];\n var hoisted = [];\n var vars = new Dictionary(), vars_found = 0, var_decl = 0;\n // let's count var_decl first, we seem to waste a lot of\n // space if we hoist `var` when there's only one.\n self.walk(new TreeWalker(function(node){\n if (node instanceof AST_Scope && node !== self)\n return true;\n if (node instanceof AST_Var) {\n ++var_decl;\n return true;\n }\n }));\n hoist_vars = hoist_vars && var_decl > 1;\n var tt = new TreeTransformer(\n function before(node) {\n if (node !== self) {\n if (node instanceof AST_Directive) {\n dirs.push(node);\n return make_node(AST_EmptyStatement, node);\n }\n if (node instanceof AST_Defun && hoist_funs) {\n hoisted.push(node);\n return make_node(AST_EmptyStatement, node);\n }\n if (node instanceof AST_Var && hoist_vars) {\n node.definitions.forEach(function(def){\n vars.set(def.name.name, def);\n ++vars_found;\n });\n var seq = node.to_assignments();\n var p = tt.parent();\n if (p instanceof AST_ForIn && p.init === node) {\n if (seq == null) return node.definitions[0].name;\n return seq;\n }\n if (p instanceof AST_For && p.init === node) {\n return seq;\n }\n if (!seq) return make_node(AST_EmptyStatement, node);\n return make_node(AST_SimpleStatement, node, {\n body: seq\n });\n }\n if (node instanceof AST_Scope)\n return node; // to avoid descending in nested scopes\n }\n }\n );\n self = self.transform(tt);\n if (vars_found > 0) {\n // collect only vars which don't show up in self's arguments list\n var defs = [];\n vars.each(function(def, name){\n if (self instanceof AST_Lambda\n && find_if(function(x){ return x.name == def.name.name },\n self.argnames)) {\n vars.del(name);\n } else {\n def = def.clone();\n def.value = null;\n defs.push(def);\n vars.set(name, def);\n }\n });\n if (defs.length > 0) {\n // try to merge in assignments\n for (var i = 0; i < self.body.length;) {\n if (self.body[i] instanceof AST_SimpleStatement) {\n var expr = self.body[i].body, sym, assign;\n if (expr instanceof AST_Assign\n && expr.operator == \"=\"\n && (sym = expr.left) instanceof AST_Symbol\n && vars.has(sym.name))\n {\n var def = vars.get(sym.name);\n if (def.value) break;\n def.value = expr.right;\n remove(defs, def);\n defs.push(def);\n self.body.splice(i, 1);\n continue;\n }\n if (expr instanceof AST_Seq\n && (assign = expr.car) instanceof AST_Assign\n && assign.operator == \"=\"\n && (sym = assign.left) instanceof AST_Symbol\n && vars.has(sym.name))\n {\n var def = vars.get(sym.name);\n if (def.value) break;\n def.value = assign.right;\n remove(defs, def);\n defs.push(def);\n self.body[i].body = expr.cdr;\n continue;\n }\n }\n if (self.body[i] instanceof AST_EmptyStatement) {\n self.body.splice(i, 1);\n continue;\n }\n if (self.body[i] instanceof AST_BlockStatement) {\n var tmp = [ i, 1 ].concat(self.body[i].body);\n self.body.splice.apply(self.body, tmp);\n continue;\n }\n break;\n }\n defs = make_node(AST_Var, self, {\n definitions: defs\n });\n hoisted.push(defs);\n };\n }\n self.body = dirs.concat(hoisted, self.body);\n }\n return self;\n });\n\n OPT(AST_SimpleStatement, function(self, compressor){\n if (compressor.option(\"side_effects\")) {\n if (!self.body.has_side_effects(compressor)) {\n compressor.warn(\"Dropping side-effect-free statement [{file}:{line},{col}]\", self.start);\n return make_node(AST_EmptyStatement, self);\n }\n }\n return self;\n });\n\n OPT(AST_DWLoop, function(self, compressor){\n var cond = self.condition.evaluate(compressor);\n self.condition = cond[0];\n if (!compressor.option(\"loops\")) return self;\n if (cond.length > 1) {\n if (cond[1]) {\n return make_node(AST_For, self, {\n body: self.body\n });\n } else if (self instanceof AST_While) {\n if (compressor.option(\"dead_code\")) {\n var a = [];\n extract_declarations_from_unreachable_code(compressor, self.body, a);\n return make_node(AST_BlockStatement, self, { body: a });\n }\n }\n }\n return self;\n });\n\n function if_break_in_loop(self, compressor) {\n function drop_it(rest) {\n rest = as_statement_array(rest);\n if (self.body instanceof AST_BlockStatement) {\n self.body = self.body.clone();\n self.body.body = rest.concat(self.body.body.slice(1));\n self.body = self.body.transform(compressor);\n } else {\n self.body = make_node(AST_BlockStatement, self.body, {\n body: rest\n }).transform(compressor);\n }\n if_break_in_loop(self, compressor);\n }\n var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;\n if (first instanceof AST_If) {\n if (first.body instanceof AST_Break\n && compressor.loopcontrol_target(first.body.label) === self) {\n if (self.condition) {\n self.condition = make_node(AST_Binary, self.condition, {\n left: self.condition,\n operator: \"&&\",\n right: first.condition.negate(compressor),\n });\n } else {\n self.condition = first.condition.negate(compressor);\n }\n drop_it(first.alternative);\n }\n else if (first.alternative instanceof AST_Break\n && compressor.loopcontrol_target(first.alternative.label) === self) {\n if (self.condition) {\n self.condition = make_node(AST_Binary, self.condition, {\n left: self.condition,\n operator: \"&&\",\n right: first.condition,\n });\n } else {\n self.condition = first.condition;\n }\n drop_it(first.body);\n }\n }\n };\n\n OPT(AST_While, function(self, compressor) {\n if (!compressor.option(\"loops\")) return self;\n self = AST_DWLoop.prototype.optimize.call(self, compressor);\n if (self instanceof AST_While) {\n if_break_in_loop(self, compressor);\n self = make_node(AST_For, self, self).transform(compressor);\n }\n return self;\n });\n\n OPT(AST_For, function(self, compressor){\n var cond = self.condition;\n if (cond) {\n cond = cond.evaluate(compressor);\n self.condition = cond[0];\n }\n if (!compressor.option(\"loops\")) return self;\n if (cond) {\n if (cond.length > 1 && !cond[1]) {\n if (compressor.option(\"dead_code\")) {\n var a = [];\n if (self.init instanceof AST_Statement) {\n a.push(self.init);\n }\n else if (self.init) {\n a.push(make_node(AST_SimpleStatement, self.init, {\n body: self.init\n }));\n }\n extract_declarations_from_unreachable_code(compressor, self.body, a);\n return make_node(AST_BlockStatement, self, { body: a });\n }\n }\n }\n if_break_in_loop(self, compressor);\n return self;\n });\n\n OPT(AST_If, function(self, compressor){\n if (!compressor.option(\"conditionals\")) return self;\n // if condition can be statically determined, warn and drop\n // one of the blocks. note, statically determined implies\n // “has no side effects”; also it doesn't work for cases like\n // `x && true`, though it probably should.\n var cond = self.condition.evaluate(compressor);\n self.condition = cond[0];\n if (cond.length > 1) {\n if (cond[1]) {\n compressor.warn(\"Condition always true [{file}:{line},{col}]\", self.condition.start);\n if (compressor.option(\"dead_code\")) {\n var a = [];\n if (self.alternative) {\n extract_declarations_from_unreachable_code(compressor, self.alternative, a);\n }\n a.push(self.body);\n return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);\n }\n } else {\n compressor.warn(\"Condition always false [{file}:{line},{col}]\", self.condition.start);\n if (compressor.option(\"dead_code\")) {\n var a = [];\n extract_declarations_from_unreachable_code(compressor, self.body, a);\n if (self.alternative) a.push(self.alternative);\n return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);\n }\n }\n }\n if (is_empty(self.alternative)) self.alternative = null;\n var negated = self.condition.negate(compressor);\n var negated_is_best = best_of(self.condition, negated) === negated;\n if (self.alternative && negated_is_best) {\n negated_is_best = false; // because we already do the switch here.\n self.condition = negated;\n var tmp = self.body;\n self.body = self.alternative || make_node(AST_EmptyStatement);\n self.alternative = tmp;\n }\n if (is_empty(self.body) && is_empty(self.alternative)) {\n return make_node(AST_SimpleStatement, self.condition, {\n body: self.condition\n }).transform(compressor);\n }\n if (self.body instanceof AST_SimpleStatement\n && self.alternative instanceof AST_SimpleStatement) {\n return make_node(AST_SimpleStatement, self, {\n body: make_node(AST_Conditional, self, {\n condition : self.condition,\n consequent : self.body.body,\n alternative : self.alternative.body\n })\n }).transform(compressor);\n }\n if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {\n if (negated_is_best) return make_node(AST_SimpleStatement, self, {\n body: make_node(AST_Binary, self, {\n operator : \"||\",\n left : negated,\n right : self.body.body\n })\n }).transform(compressor);\n return make_node(AST_SimpleStatement, self, {\n body: make_node(AST_Binary, self, {\n operator : \"&&\",\n left : self.condition,\n right : self.body.body\n })\n }).transform(compressor);\n }\n if (self.body instanceof AST_EmptyStatement\n && self.alternative\n && self.alternative instanceof AST_SimpleStatement) {\n return make_node(AST_SimpleStatement, self, {\n body: make_node(AST_Binary, self, {\n operator : \"||\",\n left : self.condition,\n right : self.alternative.body\n })\n }).transform(compressor);\n }\n if (self.body instanceof AST_Exit\n && self.alternative instanceof AST_Exit\n && self.body.TYPE == self.alternative.TYPE) {\n return make_node(self.body.CTOR, self, {\n value: make_node(AST_Conditional, self, {\n condition : self.condition,\n consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),\n alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)\n })\n }).transform(compressor);\n }\n if (self.body instanceof AST_If\n && !self.body.alternative\n && !self.alternative) {\n self.condition = make_node(AST_Binary, self.condition, {\n operator: \"&&\",\n left: self.condition,\n right: self.body.condition\n }).transform(compressor);\n self.body = self.body.body;\n }\n if (aborts(self.body)) {\n if (self.alternative) {\n var alt = self.alternative;\n self.alternative = null;\n return make_node(AST_BlockStatement, self, {\n body: [ self, alt ]\n }).transform(compressor);\n }\n }\n if (aborts(self.alternative)) {\n var body = self.body;\n self.body = self.alternative;\n self.condition = negated_is_best ? negated : self.condition.negate(compressor);\n self.alternative = null;\n return make_node(AST_BlockStatement, self, {\n body: [ self, body ]\n }).transform(compressor);\n }\n return self;\n });\n\n OPT(AST_Switch, function(self, compressor){\n if (self.body.length == 0 && compressor.option(\"conditionals\")) {\n return make_node(AST_SimpleStatement, self, {\n body: self.expression\n }).transform(compressor);\n }\n for(;;) {\n var last_branch = self.body[self.body.length - 1];\n if (last_branch) {\n var stat = last_branch.body[last_branch.body.length - 1]; // last statement\n if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self)\n last_branch.body.pop();\n if (last_branch instanceof AST_Default && last_branch.body.length == 0) {\n self.body.pop();\n continue;\n }\n }\n break;\n }\n var exp = self.expression.evaluate(compressor);\n out: if (exp.length == 2) try {\n // constant expression\n self.expression = exp[0];\n if (!compressor.option(\"dead_code\")) break out;\n var value = exp[1];\n var in_if = false;\n var in_block = false;\n var started = false;\n var stopped = false;\n var ruined = false;\n var tt = new TreeTransformer(function(node, descend, in_list){\n if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {\n // no need to descend these node types\n return node;\n }\n else if (node instanceof AST_Switch && node === self) {\n node = node.clone();\n descend(node, this);\n return ruined ? node : make_node(AST_BlockStatement, node, {\n body: node.body.reduce(function(a, branch){\n return a.concat(branch.body);\n }, [])\n }).transform(compressor);\n }\n else if (node instanceof AST_If || node instanceof AST_Try) {\n var save = in_if;\n in_if = !in_block;\n descend(node, this);\n in_if = save;\n return node;\n }\n else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {\n var save = in_block;\n in_block = true;\n descend(node, this);\n in_block = save;\n return node;\n }\n else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {\n if (in_if) {\n ruined = true;\n return node;\n }\n if (in_block) return node;\n stopped = true;\n return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);\n }\n else if (node instanceof AST_SwitchBranch && this.parent() === self) {\n if (stopped) return MAP.skip;\n if (node instanceof AST_Case) {\n var exp = node.expression.evaluate(compressor);\n if (exp.length < 2) {\n // got a case with non-constant expression, baling out\n throw self;\n }\n if (exp[1] === value || started) {\n started = true;\n if (aborts(node)) stopped = true;\n descend(node, this);\n return node;\n }\n return MAP.skip;\n }\n descend(node, this);\n return node;\n }\n });\n tt.stack = compressor.stack.slice(); // so that's able to see parent nodes\n self = self.transform(tt);\n } catch(ex) {\n if (ex !== self) throw ex;\n }\n return self;\n });\n\n OPT(AST_Case, function(self, compressor){\n self.body = tighten_body(self.body, compressor);\n return self;\n });\n\n OPT(AST_Try, function(self, compressor){\n self.body = tighten_body(self.body, compressor);\n return self;\n });\n\n AST_Definitions.DEFMETHOD(\"remove_initializers\", function(){\n this.definitions.forEach(function(def){ def.value = null });\n });\n\n AST_Definitions.DEFMETHOD(\"to_assignments\", function(){\n var assignments = this.definitions.reduce(function(a, def){\n if (def.value) {\n var name = make_node(AST_SymbolRef, def.name, def.name);\n a.push(make_node(AST_Assign, def, {\n operator : \"=\",\n left : name,\n right : def.value\n }));\n }\n return a;\n }, []);\n if (assignments.length == 0) return null;\n return AST_Seq.from_array(assignments);\n });\n\n OPT(AST_Definitions, function(self, compressor){\n if (self.definitions.length == 0)\n return make_node(AST_EmptyStatement, self);\n return self;\n });\n\n OPT(AST_Function, function(self, compressor){\n self = AST_Lambda.prototype.optimize.call(self, compressor);\n if (compressor.option(\"unused\")) {\n if (self.name && self.name.unreferenced()) {\n self.name = null;\n }\n }\n return self;\n });\n\n OPT(AST_Call, function(self, compressor){\n if (compressor.option(\"unsafe\")) {\n var exp = self.expression;\n if (exp instanceof AST_SymbolRef && exp.undeclared()) {\n switch (exp.name) {\n case \"Array\":\n if (self.args.length != 1) {\n return make_node(AST_Array, self, {\n elements: self.args\n }).transform(compressor);\n }\n break;\n case \"Object\":\n if (self.args.length == 0) {\n return make_node(AST_Object, self, {\n properties: []\n });\n }\n break;\n case \"String\":\n if (self.args.length == 0) return make_node(AST_String, self, {\n value: \"\"\n });\n if (self.args.length <= 1) return make_node(AST_Binary, self, {\n left: self.args[0],\n operator: \"+\",\n right: make_node(AST_String, self, { value: \"\" })\n }).transform(compressor);\n break;\n case \"Number\":\n if (self.args.length == 0) return make_node(AST_Number, self, {\n value: 0\n });\n if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {\n expression: self.args[0],\n operator: \"+\"\n }).transform(compressor);\n case \"Boolean\":\n if (self.args.length == 0) return make_node(AST_False, self);\n if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {\n expression: make_node(AST_UnaryPrefix, null, {\n expression: self.args[0],\n operator: \"!\"\n }),\n operator: \"!\"\n }).transform(compressor);\n break;\n case \"Function\":\n if (all(self.args, function(x){ return x instanceof AST_String })) {\n // quite a corner-case, but we can handle it:\n // https://github.com/mishoo/UglifyJS2/issues/203\n // if the code argument is a constant, then we can minify it.\n try {\n var code = \"(function(\" + self.args.slice(0, -1).map(function(arg){\n return arg.value;\n }).join(\",\") + \"){\" + self.args[self.args.length - 1].value + \"})()\";\n var ast = parse(code);\n ast.figure_out_scope({ screw_ie8: compressor.option(\"screw_ie8\") });\n var comp = new Compressor(compressor.options);\n ast = ast.transform(comp);\n ast.figure_out_scope({ screw_ie8: compressor.option(\"screw_ie8\") });\n ast.mangle_names();\n var fun;\n try {\n ast.walk(new TreeWalker(function(node){\n if (node instanceof AST_Lambda) {\n fun = node;\n throw ast;\n }\n }));\n } catch(ex) {\n if (ex !== ast) throw ex;\n };\n var args = fun.argnames.map(function(arg, i){\n return make_node(AST_String, self.args[i], {\n value: arg.print_to_string()\n });\n });\n var code = OutputStream();\n AST_BlockStatement.prototype._codegen.call(fun, fun, code);\n code = code.toString().replace(/^\\{|\\}$/g, \"\");\n args.push(make_node(AST_String, self.args[self.args.length - 1], {\n value: code\n }));\n self.args = args;\n return self;\n } catch(ex) {\n if (ex instanceof JS_Parse_Error) {\n compressor.warn(\"Error parsing code passed to new Function [{file}:{line},{col}]\", self.args[self.args.length - 1].start);\n compressor.warn(ex.toString());\n } else {\n console.log(ex);\n throw ex;\n }\n }\n }\n break;\n }\n }\n else if (exp instanceof AST_Dot && exp.property == \"toString\" && self.args.length == 0) {\n return make_node(AST_Binary, self, {\n left: make_node(AST_String, self, { value: \"\" }),\n operator: \"+\",\n right: exp.expression\n }).transform(compressor);\n }\n else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == \"join\") EXIT: {\n var separator = self.args.length == 0 ? \",\" : self.args[0].evaluate(compressor)[1];\n if (separator == null) break EXIT; // not a constant\n var elements = exp.expression.elements.reduce(function(a, el){\n el = el.evaluate(compressor);\n if (a.length == 0 || el.length == 1) {\n a.push(el);\n } else {\n var last = a[a.length - 1];\n if (last.length == 2) {\n // it's a constant\n var val = \"\" + last[1] + separator + el[1];\n a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ];\n } else {\n a.push(el);\n }\n }\n return a;\n }, []);\n if (elements.length == 0) return make_node(AST_String, self, { value: \"\" });\n if (elements.length == 1) return elements[0][0];\n if (separator == \"\") {\n var first;\n if (elements[0][0] instanceof AST_String\n || elements[1][0] instanceof AST_String) {\n first = elements.shift()[0];\n } else {\n first = make_node(AST_String, self, { value: \"\" });\n }\n return elements.reduce(function(prev, el){\n return make_node(AST_Binary, el[0], {\n operator : \"+\",\n left : prev,\n right : el[0],\n });\n }, first).transform(compressor);\n }\n // need this awkward cloning to not affect original element\n // best_of will decide which one to get through.\n var node = self.clone();\n node.expression = node.expression.clone();\n node.expression.expression = node.expression.expression.clone();\n node.expression.expression.elements = elements.map(function(el){\n return el[0];\n });\n return best_of(self, node);\n }\n }\n if (compressor.option(\"side_effects\")) {\n if (self.expression instanceof AST_Function\n && self.args.length == 0\n && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) {\n return make_node(AST_Undefined, self).transform(compressor);\n }\n }\n if (compressor.option(\"drop_console\")) {\n if (self.expression instanceof AST_PropAccess &&\n self.expression.expression instanceof AST_SymbolRef &&\n self.expression.expression.name == \"console\" &&\n self.expression.expression.undeclared()) {\n return make_node(AST_Undefined, self).transform(compressor);\n }\n }\n return self.evaluate(compressor)[0];\n });\n\n OPT(AST_New, function(self, compressor){\n if (compressor.option(\"unsafe\")) {\n var exp = self.expression;\n if (exp instanceof AST_SymbolRef && exp.undeclared()) {\n switch (exp.name) {\n case \"Object\":\n case \"RegExp\":\n case \"Function\":\n case \"Error\":\n case \"Array\":\n return make_node(AST_Call, self, self).transform(compressor);\n }\n }\n }\n return self;\n });\n\n OPT(AST_Seq, function(self, compressor){\n if (!compressor.option(\"side_effects\"))\n return self;\n if (!self.car.has_side_effects(compressor)) {\n // we shouldn't compress (1,eval)(something) to\n // eval(something) because that changes the meaning of\n // eval (becomes lexical instead of global).\n var p;\n if (!(self.cdr instanceof AST_SymbolRef\n && self.cdr.name == \"eval\"\n && self.cdr.undeclared()\n && (p = compressor.parent()) instanceof AST_Call\n && p.expression === self)) {\n return self.cdr;\n }\n }\n if (compressor.option(\"cascade\")) {\n if (self.car instanceof AST_Assign\n && !self.car.left.has_side_effects(compressor)) {\n if (self.car.left.equivalent_to(self.cdr)) {\n return self.car;\n }\n if (self.cdr instanceof AST_Call\n && self.cdr.expression.equivalent_to(self.car.left)) {\n self.cdr.expression = self.car;\n return self.cdr;\n }\n }\n if (!self.car.has_side_effects(compressor)\n && !self.cdr.has_side_effects(compressor)\n && self.car.equivalent_to(self.cdr)) {\n return self.car;\n }\n }\n if (self.cdr instanceof AST_UnaryPrefix\n && self.cdr.operator == \"void\"\n && !self.cdr.expression.has_side_effects(compressor)) {\n self.cdr.operator = self.car;\n return self.cdr;\n }\n if (self.cdr instanceof AST_Undefined) {\n return make_node(AST_UnaryPrefix, self, {\n operator : \"void\",\n expression : self.car\n });\n }\n return self;\n });\n\n AST_Unary.DEFMETHOD(\"lift_sequences\", function(compressor){\n if (compressor.option(\"sequences\")) {\n if (this.expression instanceof AST_Seq) {\n var seq = this.expression;\n var x = seq.to_array();\n this.expression = x.pop();\n x.push(this);\n seq = AST_Seq.from_array(x).transform(compressor);\n return seq;\n }\n }\n return this;\n });\n\n OPT(AST_UnaryPostfix, function(self, compressor){\n return self.lift_sequences(compressor);\n });\n\n OPT(AST_UnaryPrefix, function(self, compressor){\n self = self.lift_sequences(compressor);\n var e = self.expression;\n if (compressor.option(\"booleans\") && compressor.in_boolean_context()) {\n switch (self.operator) {\n case \"!\":\n if (e instanceof AST_UnaryPrefix && e.operator == \"!\") {\n // !!foo ==> foo, if we're in boolean context\n return e.expression;\n }\n break;\n case \"typeof\":\n // typeof always returns a non-empty string, thus it's\n // always true in booleans\n compressor.warn(\"Boolean expression always true [{file}:{line},{col}]\", self.start);\n return make_node(AST_True, self);\n }\n if (e instanceof AST_Binary && self.operator == \"!\") {\n self = best_of(self, e.negate(compressor));\n }\n }\n return self.evaluate(compressor)[0];\n });\n\n function has_side_effects_or_prop_access(node, compressor) {\n var save_pure_getters = compressor.option(\"pure_getters\");\n compressor.options.pure_getters = false;\n var ret = node.has_side_effects(compressor);\n compressor.options.pure_getters = save_pure_getters;\n return ret;\n }\n\n AST_Binary.DEFMETHOD(\"lift_sequences\", function(compressor){\n if (compressor.option(\"sequences\")) {\n if (this.left instanceof AST_Seq) {\n var seq = this.left;\n var x = seq.to_array();\n this.left = x.pop();\n x.push(this);\n seq = AST_Seq.from_array(x).transform(compressor);\n return seq;\n }\n if (this.right instanceof AST_Seq\n && this instanceof AST_Assign\n && !has_side_effects_or_prop_access(this.left, compressor)) {\n var seq = this.right;\n var x = seq.to_array();\n this.right = x.pop();\n x.push(this);\n seq = AST_Seq.from_array(x).transform(compressor);\n return seq;\n }\n }\n return this;\n });\n\n var commutativeOperators = makePredicate(\"== === != !== * & | ^\");\n\n OPT(AST_Binary, function(self, compressor){\n var reverse = compressor.has_directive(\"use asm\") ? noop\n : function(op, force) {\n if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {\n if (op) self.operator = op;\n var tmp = self.left;\n self.left = self.right;\n self.right = tmp;\n }\n };\n if (commutativeOperators(self.operator)) {\n if (self.right instanceof AST_Constant\n && !(self.left instanceof AST_Constant)) {\n // if right is a constant, whatever side effects the\n // left side might have could not influence the\n // result. hence, force switch.\n\n if (!(self.left instanceof AST_Binary\n && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {\n reverse(null, true);\n }\n }\n if (/^[!=]==?$/.test(self.operator)) {\n if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) {\n if (self.right.consequent instanceof AST_SymbolRef\n && self.right.consequent.definition() === self.left.definition()) {\n if (/^==/.test(self.operator)) return self.right.condition;\n if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor);\n }\n if (self.right.alternative instanceof AST_SymbolRef\n && self.right.alternative.definition() === self.left.definition()) {\n if (/^==/.test(self.operator)) return self.right.condition.negate(compressor);\n if (/^!=/.test(self.operator)) return self.right.condition;\n }\n }\n if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) {\n if (self.left.consequent instanceof AST_SymbolRef\n && self.left.consequent.definition() === self.right.definition()) {\n if (/^==/.test(self.operator)) return self.left.condition;\n if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor);\n }\n if (self.left.alternative instanceof AST_SymbolRef\n && self.left.alternative.definition() === self.right.definition()) {\n if (/^==/.test(self.operator)) return self.left.condition.negate(compressor);\n if (/^!=/.test(self.operator)) return self.left.condition;\n }\n }\n }\n }\n self = self.lift_sequences(compressor);\n if (compressor.option(\"comparisons\")) switch (self.operator) {\n case \"===\":\n case \"!==\":\n if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||\n (self.left.is_boolean() && self.right.is_boolean())) {\n self.operator = self.operator.substr(0, 2);\n }\n // XXX: intentionally falling down to the next case\n case \"==\":\n case \"!=\":\n if (self.left instanceof AST_String\n && self.left.value == \"undefined\"\n && self.right instanceof AST_UnaryPrefix\n && self.right.operator == \"typeof\"\n && compressor.option(\"unsafe\")) {\n if (!(self.right.expression instanceof AST_SymbolRef)\n || !self.right.expression.undeclared()) {\n self.right = self.right.expression;\n self.left = make_node(AST_Undefined, self.left).optimize(compressor);\n if (self.operator.length == 2) self.operator += \"=\";\n }\n }\n break;\n }\n if (compressor.option(\"booleans\") && compressor.in_boolean_context()) switch (self.operator) {\n case \"&&\":\n var ll = self.left.evaluate(compressor);\n var rr = self.right.evaluate(compressor);\n if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) {\n compressor.warn(\"Boolean && always false [{file}:{line},{col}]\", self.start);\n return make_node(AST_False, self);\n }\n if (ll.length > 1 && ll[1]) {\n return rr[0];\n }\n if (rr.length > 1 && rr[1]) {\n return ll[0];\n }\n break;\n case \"||\":\n var ll = self.left.evaluate(compressor);\n var rr = self.right.evaluate(compressor);\n if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) {\n compressor.warn(\"Boolean || always true [{file}:{line},{col}]\", self.start);\n return make_node(AST_True, self);\n }\n if (ll.length > 1 && !ll[1]) {\n return rr[0];\n }\n if (rr.length > 1 && !rr[1]) {\n return ll[0];\n }\n break;\n case \"+\":\n var ll = self.left.evaluate(compressor);\n var rr = self.right.evaluate(compressor);\n if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) ||\n (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) {\n compressor.warn(\"+ in boolean context always true [{file}:{line},{col}]\", self.start);\n return make_node(AST_True, self);\n }\n break;\n }\n if (compressor.option(\"comparisons\")) {\n if (!(compressor.parent() instanceof AST_Binary)\n || compressor.parent() instanceof AST_Assign) {\n var negated = make_node(AST_UnaryPrefix, self, {\n operator: \"!\",\n expression: self.negate(compressor)\n });\n self = best_of(self, negated);\n }\n switch (self.operator) {\n case \"<\": reverse(\">\"); break;\n case \"<=\": reverse(\">=\"); break;\n }\n }\n if (self.operator == \"+\" && self.right instanceof AST_String\n && self.right.getValue() === \"\" && self.left instanceof AST_Binary\n && self.left.operator == \"+\" && self.left.is_string(compressor)) {\n return self.left;\n }\n if (compressor.option(\"evaluate\")) {\n if (self.operator == \"+\") {\n if (self.left instanceof AST_Constant\n && self.right instanceof AST_Binary\n && self.right.operator == \"+\"\n && self.right.left instanceof AST_Constant\n && self.right.is_string(compressor)) {\n self = make_node(AST_Binary, self, {\n operator: \"+\",\n left: make_node(AST_String, null, {\n value: \"\" + self.left.getValue() + self.right.left.getValue(),\n start: self.left.start,\n end: self.right.left.end\n }),\n right: self.right.right\n });\n }\n if (self.right instanceof AST_Constant\n && self.left instanceof AST_Binary\n && self.left.operator == \"+\"\n && self.left.right instanceof AST_Constant\n && self.left.is_string(compressor)) {\n self = make_node(AST_Binary, self, {\n operator: \"+\",\n left: self.left.left,\n right: make_node(AST_String, null, {\n value: \"\" + self.left.right.getValue() + self.right.getValue(),\n start: self.left.right.start,\n end: self.right.end\n })\n });\n }\n if (self.left instanceof AST_Binary\n && self.left.operator == \"+\"\n && self.left.is_string(compressor)\n && self.left.right instanceof AST_Constant\n && self.right instanceof AST_Binary\n && self.right.operator == \"+\"\n && self.right.left instanceof AST_Constant\n && self.right.is_string(compressor)) {\n self = make_node(AST_Binary, self, {\n operator: \"+\",\n left: make_node(AST_Binary, self.left, {\n operator: \"+\",\n left: self.left.left,\n right: make_node(AST_String, null, {\n value: \"\" + self.left.right.getValue() + self.right.left.getValue(),\n start: self.left.right.start,\n end: self.right.left.end\n })\n }),\n right: self.right.right\n });\n }\n }\n }\n // x * (y * z) ==> x * y * z\n if (self.right instanceof AST_Binary\n && self.right.operator == self.operator\n && (self.operator == \"*\" || self.operator == \"&&\" || self.operator == \"||\"))\n {\n self.left = make_node(AST_Binary, self.left, {\n operator : self.operator,\n left : self.left,\n right : self.right.left\n });\n self.right = self.right.right;\n return self.transform(compressor);\n }\n return self.evaluate(compressor)[0];\n });\n\n OPT(AST_SymbolRef, function(self, compressor){\n if (self.undeclared()) {\n var defines = compressor.option(\"global_defs\");\n if (defines && defines.hasOwnProperty(self.name)) {\n return make_node_from_constant(compressor, defines[self.name], self);\n }\n switch (self.name) {\n case \"undefined\":\n return make_node(AST_Undefined, self);\n case \"NaN\":\n return make_node(AST_NaN, self);\n case \"Infinity\":\n return make_node(AST_Infinity, self);\n }\n }\n return self;\n });\n\n OPT(AST_Undefined, function(self, compressor){\n if (compressor.option(\"unsafe\")) {\n var scope = compressor.find_parent(AST_Scope);\n var undef = scope.find_variable(\"undefined\");\n if (undef) {\n var ref = make_node(AST_SymbolRef, self, {\n name : \"undefined\",\n scope : scope,\n thedef : undef\n });\n ref.reference();\n return ref;\n }\n }\n return self;\n });\n\n var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];\n OPT(AST_Assign, function(self, compressor){\n self = self.lift_sequences(compressor);\n if (self.operator == \"=\"\n && self.left instanceof AST_SymbolRef\n && self.right instanceof AST_Binary\n && self.right.left instanceof AST_SymbolRef\n && self.right.left.name == self.left.name\n && member(self.right.operator, ASSIGN_OPS)) {\n self.operator = self.right.operator + \"=\";\n self.right = self.right.right;\n }\n return self;\n });\n\n OPT(AST_Conditional, function(self, compressor){\n if (!compressor.option(\"conditionals\")) return self;\n if (self.condition instanceof AST_Seq) {\n var car = self.condition.car;\n self.condition = self.condition.cdr;\n return AST_Seq.cons(car, self);\n }\n var cond = self.condition.evaluate(compressor);\n if (cond.length > 1) {\n if (cond[1]) {\n compressor.warn(\"Condition always true [{file}:{line},{col}]\", self.start);\n return self.consequent;\n } else {\n compressor.warn(\"Condition always false [{file}:{line},{col}]\", self.start);\n return self.alternative;\n }\n }\n var negated = cond[0].negate(compressor);\n if (best_of(cond[0], negated) === negated) {\n self = make_node(AST_Conditional, self, {\n condition: negated,\n consequent: self.alternative,\n alternative: self.consequent\n });\n }\n var consequent = self.consequent;\n var alternative = self.alternative;\n if (consequent instanceof AST_Assign\n && alternative instanceof AST_Assign\n && consequent.operator == alternative.operator\n && consequent.left.equivalent_to(alternative.left)\n ) {\n /*\n * Stuff like this:\n * if (foo) exp = something; else exp = something_else;\n * ==>\n * exp = foo ? something : something_else;\n */\n return make_node(AST_Assign, self, {\n operator: consequent.operator,\n left: consequent.left,\n right: make_node(AST_Conditional, self, {\n condition: self.condition,\n consequent: consequent.right,\n alternative: alternative.right\n })\n });\n }\n if (consequent instanceof AST_Call\n && alternative.TYPE === consequent.TYPE\n && consequent.args.length == alternative.args.length\n && consequent.expression.equivalent_to(alternative.expression)) {\n if (consequent.args.length == 0) {\n return make_node(AST_Seq, self, {\n car: self.condition,\n cdr: consequent\n });\n }\n if (consequent.args.length == 1) {\n consequent.args[0] = make_node(AST_Conditional, self, {\n condition: self.condition,\n consequent: consequent.args[0],\n alternative: alternative.args[0]\n });\n return consequent;\n }\n }\n // x?y?z:a:a --> x&&y?z:a\n if (consequent instanceof AST_Conditional\n && consequent.alternative.equivalent_to(alternative)) {\n return make_node(AST_Conditional, self, {\n condition: make_node(AST_Binary, self, {\n left: self.condition,\n operator: \"&&\",\n right: consequent.condition\n }),\n consequent: consequent.consequent,\n alternative: alternative\n });\n }\n return self;\n });\n\n OPT(AST_Boolean, function(self, compressor){\n if (compressor.option(\"booleans\")) {\n var p = compressor.parent();\n if (p instanceof AST_Binary && (p.operator == \"==\"\n || p.operator == \"!=\")) {\n compressor.warn(\"Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]\", {\n operator : p.operator,\n value : self.value,\n file : p.start.file,\n line : p.start.line,\n col : p.start.col,\n });\n return make_node(AST_Number, self, {\n value: +self.value\n });\n }\n return make_node(AST_UnaryPrefix, self, {\n operator: \"!\",\n expression: make_node(AST_Number, self, {\n value: 1 - self.value\n })\n });\n }\n return self;\n });\n\n OPT(AST_Sub, function(self, compressor){\n var prop = self.property;\n if (prop instanceof AST_String && compressor.option(\"properties\")) {\n prop = prop.getValue();\n if (RESERVED_WORDS(prop) ? compressor.option(\"screw_ie8\") : is_identifier_string(prop)) {\n return make_node(AST_Dot, self, {\n expression : self.expression,\n property : prop\n });\n }\n var v = parseFloat(prop);\n if (!isNaN(v) && v.toString() == prop) {\n self.property = make_node(AST_Number, self.property, {\n value: v\n });\n }\n }\n return self;\n });\n\n function literals_in_boolean_context(self, compressor) {\n if (compressor.option(\"booleans\") && compressor.in_boolean_context()) {\n return make_node(AST_True, self);\n }\n return self;\n };\n OPT(AST_Array, literals_in_boolean_context);\n OPT(AST_Object, literals_in_boolean_context);\n OPT(AST_RegExp, literals_in_boolean_context);\n\n})();\n\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n https://github.com/mishoo/UglifyJS2\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2012 (c) Mihai Bazon <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n\"use strict\";\n\n// a small wrapper around fitzgen's source-map library\nfunction SourceMap(options) {\n options = defaults(options, {\n file : null,\n root : null,\n orig : null,\n\n orig_line_diff : 0,\n dest_line_diff : 0,\n });\n var generator = new MOZ_SourceMap.SourceMapGenerator({\n file : options.file,\n sourceRoot : options.root\n });\n var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);\n function add(source, gen_line, gen_col, orig_line, orig_col, name) {\n if (orig_map) {\n var info = orig_map.originalPositionFor({\n line: orig_line,\n column: orig_col\n });\n if (info.source === null) {\n return;\n }\n source = info.source;\n orig_line = info.line;\n orig_col = info.column;\n name = info.name;\n }\n generator.addMapping({\n generated : { line: gen_line + options.dest_line_diff, column: gen_col },\n original : { line: orig_line + options.orig_line_diff, column: orig_col },\n source : source,\n name : name\n });\n };\n return {\n add : add,\n get : function() { return generator },\n toString : function() { return generator.toString() }\n };\n};\n\n/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier / compressor.\n https://github.com/mishoo/UglifyJS2\n\n -------------------------------- (C) ---------------------------------\n\n Author: Mihai Bazon\n <[email protected]>\n http://mihai.bazon.net/blog\n\n Distributed under the BSD license:\n\n Copyright 2012 (c) Mihai Bazon <[email protected]>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n * Redistributions of source code must retain the above\n copyright notice, this list of conditions and the following\n disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\n EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n ***********************************************************************/\n\n\"use strict\";\n\n(function(){\n\n var MOZ_TO_ME = {\n TryStatement : function(M) {\n return new AST_Try({\n start : my_start_token(M),\n end : my_end_token(M),\n body : from_moz(M.block).body,\n bcatch : from_moz(M.handlers[0]),\n bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null\n });\n },\n CatchClause : function(M) {\n return new AST_Catch({\n start : my_start_token(M),\n end : my_end_token(M),\n argname : from_moz(M.param),\n body : from_moz(M.body).body\n });\n },\n ObjectExpression : function(M) {\n return new AST_Object({\n start : my_start_token(M),\n end : my_end_token(M),\n properties : M.properties.map(function(prop){\n var key = prop.key;\n var name = key.type == \"Identifier\" ? key.name : key.value;\n var args = {\n start : my_start_token(key),\n end : my_end_token(prop.value),\n key : name,\n value : from_moz(prop.value)\n };\n switch (prop.kind) {\n case \"init\":\n return new AST_ObjectKeyVal(args);\n case \"set\":\n args.value.name = from_moz(key);\n return new AST_ObjectSetter(args);\n case \"get\":\n args.value.name = from_moz(key);\n return new AST_ObjectGetter(args);\n }\n })\n });\n },\n SequenceExpression : function(M) {\n return AST_Seq.from_array(M.expressions.map(from_moz));\n },\n MemberExpression : function(M) {\n return new (M.computed ? AST_Sub : AST_Dot)({\n start : my_start_token(M),\n end : my_end_token(M),\n property : M.computed ? from_moz(M.property) : M.property.name,\n expression : from_moz(M.object)\n });\n },\n SwitchCase : function(M) {\n return new (M.test ? AST_Case : AST_Default)({\n start : my_start_token(M),\n end : my_end_token(M),\n expression : from_moz(M.test),\n body : M.consequent.map(from_moz)\n });\n },\n Literal : function(M) {\n var val = M.value, args = {\n start : my_start_token(M),\n end : my_end_token(M)\n };\n if (val === null) return new AST_Null(args);\n switch (typeof val) {\n case \"string\":\n args.value = val;\n return new AST_String(args);\n case \"number\":\n args.value = val;\n return new AST_Number(args);\n case \"boolean\":\n return new (val ? AST_True : AST_False)(args);\n default:\n args.value = val;\n return new AST_RegExp(args);\n }\n },\n UnaryExpression: From_Moz_Unary,\n UpdateExpression: From_Moz_Unary,\n Identifier: function(M) {\n var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];\n return new (M.name == \"this\" ? AST_This\n : p.type == \"LabeledStatement\" ? AST_Label\n : p.type == \"VariableDeclarator\" && p.id === M ? (p.kind == \"const\" ? AST_SymbolConst : AST_SymbolVar)\n : p.type == \"FunctionExpression\" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)\n : p.type == \"FunctionDeclaration\" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)\n : p.type == \"CatchClause\" ? AST_SymbolCatch\n : p.type == \"BreakStatement\" || p.type == \"ContinueStatement\" ? AST_LabelRef\n : AST_SymbolRef)({\n start : my_start_token(M),\n end : my_end_token(M),\n name : M.name\n });\n }\n };\n\n function From_Moz_Unary(M) {\n var prefix = \"prefix\" in M ? M.prefix\n : M.type == \"UnaryExpression\" ? true : false;\n return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({\n start : my_start_token(M),\n end : my_end_token(M),\n operator : M.operator,\n expression : from_moz(M.argument)\n });\n };\n\n var ME_TO_MOZ = {};\n\n map(\"Node\", AST_Node);\n map(\"Program\", AST_Toplevel, \"body@body\");\n map(\"Function\", AST_Function, \"id>name, params@argnames, body%body\");\n map(\"EmptyStatement\", AST_EmptyStatement);\n map(\"BlockStatement\", AST_BlockStatement, \"body@body\");\n map(\"ExpressionStatement\", AST_SimpleStatement, \"expression>body\");\n map(\"IfStatement\", AST_If, \"test>condition, consequent>body, alternate>alternative\");\n map(\"LabeledStatement\", AST_LabeledStatement, \"label>label, body>body\");\n map(\"BreakStatement\", AST_Break, \"label>label\");\n map(\"ContinueStatement\", AST_Continue, \"label>label\");\n map(\"WithStatement\", AST_With, \"object>expression, body>body\");\n map(\"SwitchStatement\", AST_Switch, \"discriminant>expression, cases@body\");\n map(\"ReturnStatement\", AST_Return, \"argument>value\");\n map(\"ThrowStatement\", AST_Throw, \"argument>value\");\n map(\"WhileStatement\", AST_While, \"test>condition, body>body\");\n map(\"DoWhileStatement\", AST_Do, \"test>condition, body>body\");\n map(\"ForStatement\", AST_For, \"init>init, test>condition, update>step, body>body\");\n map(\"ForInStatement\", AST_ForIn, \"left>init, right>object, body>body\");\n map(\"DebuggerStatement\", AST_Debugger);\n map(\"FunctionDeclaration\", AST_Defun, \"id>name, params@argnames, body%body\");\n map(\"VariableDeclaration\", AST_Var, \"declarations@definitions\");\n map(\"VariableDeclarator\", AST_VarDef, \"id>name, init>value\");\n\n map(\"ThisExpression\", AST_This);\n map(\"ArrayExpression\", AST_Array, \"elements@elements\");\n map(\"FunctionExpression\", AST_Function, \"id>name, params@argnames, body%body\");\n map(\"BinaryExpression\", AST_Binary, \"operator=operator, left>left, right>right\");\n map(\"AssignmentExpression\", AST_Assign, \"operator=operator, left>left, right>right\");\n map(\"LogicalExpression\", AST_Binary, \"operator=operator, left>left, right>right\");\n map(\"ConditionalExpression\", AST_Conditional, \"test>condition, consequent>consequent, alternate>alternative\");\n map(\"NewExpression\", AST_New, \"callee>expression, arguments@args\");\n map(\"CallExpression\", AST_Call, \"callee>expression, arguments@args\");\n\n /* -----[ tools ]----- */\n\n function my_start_token(moznode) {\n return new AST_Token({\n file : moznode.loc && moznode.loc.source,\n line : moznode.loc && moznode.loc.start.line,\n col : moznode.loc && moznode.loc.start.column,\n pos : moznode.start,\n endpos : moznode.start\n });\n };\n\n function my_end_token(moznode) {\n return new AST_Token({\n file : moznode.loc && moznode.loc.source,\n line : moznode.loc && moznode.loc.end.line,\n col : moznode.loc && moznode.loc.end.column,\n pos : moznode.end,\n endpos : moznode.end\n });\n };\n\n function map(moztype, mytype, propmap) {\n var moz_to_me = \"function From_Moz_\" + moztype + \"(M){\\n\";\n moz_to_me += \"return new mytype({\\n\" +\n \"start: my_start_token(M),\\n\" +\n \"end: my_end_token(M)\";\n\n if (propmap) propmap.split(/\\s*,\\s*/).forEach(function(prop){\n var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);\n if (!m) throw new Error(\"Can't understand property map: \" + prop);\n var moz = \"M.\" + m[1], how = m[2], my = m[3];\n moz_to_me += \",\\n\" + my + \": \";\n if (how == \"@\") {\n moz_to_me += moz + \".map(from_moz)\";\n } else if (how == \">\") {\n moz_to_me += \"from_moz(\" + moz + \")\";\n } else if (how == \"=\") {\n moz_to_me += moz;\n } else if (how == \"%\") {\n moz_to_me += \"from_moz(\" + moz + \").body\";\n } else throw new Error(\"Can't understand operator in propmap: \" + prop);\n });\n moz_to_me += \"\\n})}\";\n\n // moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });\n // console.log(moz_to_me);\n\n moz_to_me = new Function(\"mytype\", \"my_start_token\", \"my_end_token\", \"from_moz\", \"return(\" + moz_to_me + \")\")(\n mytype, my_start_token, my_end_token, from_moz\n );\n return MOZ_TO_ME[moztype] = moz_to_me;\n };\n\n var FROM_MOZ_STACK = null;\n\n function from_moz(node) {\n FROM_MOZ_STACK.push(node);\n var ret = node != null ? MOZ_TO_ME[node.type](node) : null;\n FROM_MOZ_STACK.pop();\n return ret;\n };\n\n AST_Node.from_mozilla_ast = function(node){\n var save_stack = FROM_MOZ_STACK;\n FROM_MOZ_STACK = [];\n var ast = from_moz(node);\n FROM_MOZ_STACK = save_stack;\n return ast;\n };\n\n})();\n\nAST_Node.warn_function = function(txt) { logger.error(\"uglifyjs2 WARN: \" + txt); };\nexports.minify = function(files, options, name) {\n options = defaults(options, {\n spidermonkey : false,\n outSourceMap : null,\n sourceRoot : null,\n inSourceMap : null,\n fromString : false,\n warnings : false,\n mangle : {},\n output : null,\n compress : {}\n });\n base54.reset();\n\n // 1. parse\n var toplevel = null,\n sourcesContent = {};\n\n if (options.spidermonkey) {\n toplevel = AST_Node.from_mozilla_ast(files);\n } else {\n if (typeof files == \"string\")\n files = [ files ];\n files.forEach(function(file){\n var code = options.fromString\n ? file\n : rjsFile.readFile(file, \"utf8\");\n sourcesContent[file] = code;\n toplevel = parse(code, {\n filename: options.fromString ? name : file,\n toplevel: toplevel\n });\n });\n }\n\n // 2. compress\n if (options.compress) {\n var compress = { warnings: options.warnings };\n merge(compress, options.compress);\n toplevel.figure_out_scope();\n var sq = Compressor(compress);\n toplevel = toplevel.transform(sq);\n }\n\n // 3. mangle\n if (options.mangle) {\n toplevel.figure_out_scope();\n toplevel.compute_char_frequency();\n toplevel.mangle_names(options.mangle);\n }\n\n // 4. output\n var inMap = options.inSourceMap;\n var output = {};\n if (typeof options.inSourceMap == \"string\") {\n inMap = rjsFile.readFile(options.inSourceMap, \"utf8\");\n }\n if (options.outSourceMap) {\n output.source_map = SourceMap({\n file: options.outSourceMap,\n orig: inMap,\n root: options.sourceRoot\n });\n if (options.sourceMapIncludeSources) {\n for (var file in sourcesContent) {\n if (sourcesContent.hasOwnProperty(file)) {\n options.source_map.get().setSourceContent(file, sourcesContent[file]);\n }\n }\n }\n\n }\n if (options.output) {\n merge(output, options.output);\n }\n var stream = OutputStream(output);\n toplevel.print(stream);\n return {\n code : stream + \"\",\n map : output.source_map + \"\"\n };\n};\n\n// exports.describe_ast = function() {\n// function doitem(ctor) {\n// var sub = {};\n// ctor.SUBCLASSES.forEach(function(ctor){\n// sub[ctor.TYPE] = doitem(ctor);\n// });\n// var ret = {};\n// if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS;\n// if (ctor.SUBCLASSES.length > 0) ret.sub = sub;\n// return ret;\n// }\n// return doitem(AST_Node).sub;\n// }\n\nexports.describe_ast = function() {\n var out = OutputStream({ beautify: true });\n function doitem(ctor) {\n out.print(\"AST_\" + ctor.TYPE);\n var props = ctor.SELF_PROPS.filter(function(prop){\n return !/^\\$/.test(prop);\n });\n if (props.length > 0) {\n out.space();\n out.with_parens(function(){\n props.forEach(function(prop, i){\n if (i) out.space();\n out.print(prop);\n });\n });\n }\n if (ctor.documentation) {\n out.space();\n out.print_string(ctor.documentation);\n }\n if (ctor.SUBCLASSES.length > 0) {\n out.space();\n out.with_block(function(){\n ctor.SUBCLASSES.forEach(function(ctor, i){\n out.indent();\n doitem(ctor);\n out.newline();\n });\n });\n }\n };\n doitem(AST_Node);\n return out + \"\";\n};\n\n\n});\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint plusplus: true */\n/*global define: false */\n\ndefine('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) {\n 'use strict';\n\n function arrayToString(ary) {\n var output = '[';\n if (ary) {\n ary.forEach(function (item, i) {\n output += (i > 0 ? ',' : '') + '\"' + lang.jsEscape(item) + '\"';\n });\n }\n output += ']';\n\n return output;\n }\n\n //This string is saved off because JSLint complains\n //about obj.arguments use, as 'reserved word'\n var argPropName = 'arguments',\n //Default object to use for \"scope\" checking for UMD identifiers.\n emptyScope = {},\n mixin = lang.mixin,\n hasProp = lang.hasProp;\n\n //From an esprima example for traversing its ast.\n function traverse(object, visitor) {\n var key, child;\n\n if (!object) {\n return;\n }\n\n if (visitor.call(null, object) === false) {\n return false;\n }\n for (key in object) {\n if (object.hasOwnProperty(key)) {\n child = object[key];\n if (typeof child === 'object' && child !== null) {\n if (traverse(child, visitor) === false) {\n return false;\n }\n }\n }\n }\n }\n\n //Like traverse, but visitor returning false just\n //stops that subtree analysis, not the rest of tree\n //visiting.\n function traverseBroad(object, visitor) {\n var key, child;\n\n if (!object) {\n return;\n }\n\n if (visitor.call(null, object) === false) {\n return false;\n }\n for (key in object) {\n if (object.hasOwnProperty(key)) {\n child = object[key];\n if (typeof child === 'object' && child !== null) {\n traverseBroad(child, visitor);\n }\n }\n }\n }\n\n /**\n * Pulls out dependencies from an array literal with just string members.\n * If string literals, will just return those string values in an array,\n * skipping other items in the array.\n *\n * @param {Node} node an AST node.\n *\n * @returns {Array} an array of strings.\n * If null is returned, then it means the input node was not a valid\n * dependency.\n */\n function getValidDeps(node) {\n if (!node || node.type !== 'ArrayExpression' || !node.elements) {\n return;\n }\n\n var deps = [];\n\n node.elements.some(function (elem) {\n if (elem.type === 'Literal') {\n deps.push(elem.value);\n }\n });\n\n return deps.length ? deps : undefined;\n }\n\n /**\n * Main parse function. Returns a string of any valid require or\n * define/require.def calls as part of one JavaScript source string.\n * @param {String} moduleName the module name that represents this file.\n * It is used to create a default define if there is not one already for the\n * file. This allows properly tracing dependencies for builds. Otherwise, if\n * the file just has a require() call, the file dependencies will not be\n * properly reflected: the file will come before its dependencies.\n * @param {String} moduleName\n * @param {String} fileName\n * @param {String} fileContents\n * @param {Object} options optional options. insertNeedsDefine: true will\n * add calls to require.needsDefine() if appropriate.\n * @returns {String} JS source string or null, if no require or\n * define/require.def calls are found.\n */\n function parse(moduleName, fileName, fileContents, options) {\n options = options || {};\n\n //Set up source input\n var i, moduleCall, depString,\n moduleDeps = [],\n result = '',\n moduleList = [],\n needsDefine = true,\n astRoot = esprima.parse(fileContents);\n\n parse.recurse(astRoot, function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) {\n if (!deps) {\n deps = [];\n }\n\n if (callName === 'define' && (!name || name === moduleName)) {\n needsDefine = false;\n }\n\n if (!name) {\n //If there is no module name, the dependencies are for\n //this file/default module name.\n moduleDeps = moduleDeps.concat(deps);\n } else {\n moduleList.push({\n name: name,\n deps: deps\n });\n }\n\n if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) {\n return factoryIdentifier;\n }\n\n //If define was found, no need to dive deeper, unless\n //the config explicitly wants to dig deeper.\n return !!options.findNestedDependencies;\n }, options);\n\n if (options.insertNeedsDefine && needsDefine) {\n result += 'require.needsDefine(\"' + moduleName + '\");';\n }\n\n if (moduleDeps.length || moduleList.length) {\n for (i = 0; i < moduleList.length; i++) {\n moduleCall = moduleList[i];\n if (result) {\n result += '\\n';\n }\n\n //If this is the main module for this file, combine any\n //\"anonymous\" dependencies (could come from a nested require\n //call) with this module.\n if (moduleCall.name === moduleName) {\n moduleCall.deps = moduleCall.deps.concat(moduleDeps);\n moduleDeps = [];\n }\n\n depString = arrayToString(moduleCall.deps);\n result += 'define(\"' + moduleCall.name + '\",' +\n depString + ');';\n }\n if (moduleDeps.length) {\n if (result) {\n result += '\\n';\n }\n depString = arrayToString(moduleDeps);\n result += 'define(\"' + moduleName + '\",' + depString + ');';\n }\n }\n\n return result || null;\n }\n\n parse.traverse = traverse;\n parse.traverseBroad = traverseBroad;\n\n /**\n * Handles parsing a file recursively for require calls.\n * @param {Array} parentNode the AST node to start with.\n * @param {Function} onMatch function to call on a parse match.\n * @param {Object} [options] This is normally the build config options if\n * it is passed.\n * @param {Object} [fnExpScope] holds list of function expresssion\n * argument identifiers, set up internally, not passed in\n */\n parse.recurse = function (object, onMatch, options, fnExpScope) {\n //Like traverse, but skips if branches that would not be processed\n //after has application that results in tests of true or false boolean\n //literal values.\n var key, child, result, i, params, param, tempObject,\n hasHas = options && options.has;\n\n fnExpScope = fnExpScope || emptyScope;\n\n if (!object) {\n return;\n }\n\n //If has replacement has resulted in if(true){} or if(false){}, take\n //the appropriate branch and skip the other one.\n if (hasHas && object.type === 'IfStatement' && object.test.type &&\n object.test.type === 'Literal') {\n if (object.test.value) {\n //Take the if branch\n this.recurse(object.consequent, onMatch, options, fnExpScope);\n } else {\n //Take the else branch\n this.recurse(object.alternate, onMatch, options, fnExpScope);\n }\n } else {\n result = this.parseNode(object, onMatch, fnExpScope);\n if (result === false) {\n return;\n } else if (typeof result === 'string') {\n return result;\n }\n\n //Build up a \"scope\" object that informs nested recurse calls if\n //the define call references an identifier that is likely a UMD\n //wrapped function expression argument.\n if (object.type === 'ExpressionStatement' && object.expression &&\n object.expression.type === 'CallExpression' && object.expression.callee &&\n object.expression.callee.type === 'FunctionExpression') {\n tempObject = object.expression.callee;\n\n if (tempObject.params && tempObject.params.length) {\n params = tempObject.params;\n fnExpScope = mixin({}, fnExpScope, true);\n for (i = 0; i < params.length; i++) {\n param = params[i];\n if (param.type === 'Identifier') {\n fnExpScope[param.name] = true;\n }\n }\n }\n }\n\n for (key in object) {\n if (object.hasOwnProperty(key)) {\n child = object[key];\n if (typeof child === 'object' && child !== null) {\n result = this.recurse(child, onMatch, options, fnExpScope);\n if (typeof result === 'string') {\n break;\n }\n }\n }\n }\n\n //Check for an identifier for a factory function identifier being\n //passed in as a function expression, indicating a UMD-type of\n //wrapping.\n if (typeof result === 'string') {\n if (hasProp(fnExpScope, result)) {\n //result still in scope, keep jumping out indicating the\n //identifier still in use.\n return result;\n }\n\n return;\n }\n }\n };\n\n /**\n * Determines if the file defines the require/define module API.\n * Specifically, it looks for the `define.amd = ` expression.\n * @param {String} fileName\n * @param {String} fileContents\n * @returns {Boolean}\n */\n parse.definesRequire = function (fileName, fileContents) {\n var found = false;\n\n traverse(esprima.parse(fileContents), function (node) {\n if (parse.hasDefineAmd(node)) {\n found = true;\n\n //Stop traversal\n return false;\n }\n });\n\n return found;\n };\n\n /**\n * Finds require(\"\") calls inside a CommonJS anonymous module wrapped in a\n * define(function(require, exports, module){}) wrapper. These dependencies\n * will be added to a modified define() call that lists the dependencies\n * on the outside of the function.\n * @param {String} fileName\n * @param {String|Object} fileContents: a string of contents, or an already\n * parsed AST tree.\n * @returns {Array} an array of module names that are dependencies. Always\n * returns an array, but could be of length zero.\n */\n parse.getAnonDeps = function (fileName, fileContents) {\n var astRoot = typeof fileContents === 'string' ?\n esprima.parse(fileContents) : fileContents,\n defFunc = this.findAnonDefineFactory(astRoot);\n\n return parse.getAnonDepsFromNode(defFunc);\n };\n\n /**\n * Finds require(\"\") calls inside a CommonJS anonymous module wrapped\n * in a define function, given an AST node for the definition function.\n * @param {Node} node the AST node for the definition function.\n * @returns {Array} and array of dependency names. Can be of zero length.\n */\n parse.getAnonDepsFromNode = function (node) {\n var deps = [],\n funcArgLength;\n\n if (node) {\n this.findRequireDepNames(node, deps);\n\n //If no deps, still add the standard CommonJS require, exports,\n //module, in that order, to the deps, but only if specified as\n //function args. In particular, if exports is used, it is favored\n //over the return value of the function, so only add it if asked.\n funcArgLength = node.params && node.params.length;\n if (funcArgLength) {\n deps = (funcArgLength > 1 ? [\"require\", \"exports\", \"module\"] :\n [\"require\"]).concat(deps);\n }\n }\n return deps;\n };\n\n parse.isDefineNodeWithArgs = function (node) {\n return node && node.type === 'CallExpression' &&\n node.callee && node.callee.type === 'Identifier' &&\n node.callee.name === 'define' && node[argPropName];\n };\n\n /**\n * Finds the function in define(function (require, exports, module){});\n * @param {Array} node\n * @returns {Boolean}\n */\n parse.findAnonDefineFactory = function (node) {\n var match;\n\n traverse(node, function (node) {\n var arg0, arg1;\n\n if (parse.isDefineNodeWithArgs(node)) {\n\n //Just the factory function passed to define\n arg0 = node[argPropName][0];\n if (arg0 && arg0.type === 'FunctionExpression') {\n match = arg0;\n return false;\n }\n\n //A string literal module ID followed by the factory function.\n arg1 = node[argPropName][1];\n if (arg0.type === 'Literal' &&\n arg1 && arg1.type === 'FunctionExpression') {\n match = arg1;\n return false;\n }\n }\n });\n\n return match;\n };\n\n /**\n * Finds any config that is passed to requirejs. That includes calls to\n * require/requirejs.config(), as well as require({}, ...) and\n * requirejs({}, ...)\n * @param {String} fileContents\n *\n * @returns {Object} a config details object with the following properties:\n * - config: {Object} the config object found. Can be undefined if no\n * config found.\n * - range: {Array} the start index and end index in the contents where\n * the config was found. Can be undefined if no config found.\n * Can throw an error if the config in the file cannot be evaluated in\n * a build context to valid JavaScript.\n */\n parse.findConfig = function (fileContents) {\n /*jslint evil: true */\n var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch,\n quoteRegExp = /(:\\s|\\[\\s*)(['\"])/,\n astRoot = esprima.parse(fileContents, {\n loc: true\n });\n\n traverse(astRoot, function (node) {\n var arg,\n requireType = parse.hasRequire(node);\n\n if (requireType && (requireType === 'require' ||\n requireType === 'requirejs' ||\n requireType === 'requireConfig' ||\n requireType === 'requirejsConfig')) {\n\n arg = node[argPropName] && node[argPropName][0];\n\n if (arg && arg.type === 'ObjectExpression') {\n stringData = parse.nodeToString(fileContents, arg);\n jsConfig = stringData.value;\n foundRange = stringData.range;\n return false;\n }\n } else {\n arg = parse.getRequireObjectLiteral(node);\n if (arg) {\n stringData = parse.nodeToString(fileContents, arg);\n jsConfig = stringData.value;\n foundRange = stringData.range;\n return false;\n }\n }\n });\n\n if (jsConfig) {\n // Eval the config\n quoteMatch = quoteRegExp.exec(jsConfig);\n quote = (quoteMatch && quoteMatch[2]) || '\"';\n foundConfig = eval('(' + jsConfig + ')');\n }\n\n return {\n config: foundConfig,\n range: foundRange,\n quote: quote\n };\n };\n\n /** Returns the node for the object literal assigned to require/requirejs,\n * for holding a declarative config.\n */\n parse.getRequireObjectLiteral = function (node) {\n if (node.id && node.id.type === 'Identifier' &&\n (node.id.name === 'require' || node.id.name === 'requirejs') &&\n node.init && node.init.type === 'ObjectExpression') {\n return node.init;\n }\n };\n\n /**\n * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define\n * Does *not* do .config calls though. See pragma.namespace for the complete\n * set of namespace transforms. This function is used because require calls\n * inside a define() call should not be renamed, so a simple regexp is not\n * good enough.\n * @param {String} fileContents the contents to transform.\n * @param {String} ns the namespace, *not* including trailing dot.\n * @return {String} the fileContents with the namespace applied\n */\n parse.renameNamespace = function (fileContents, ns) {\n var lines,\n locs = [],\n astRoot = esprima.parse(fileContents, {\n loc: true\n });\n\n parse.recurse(astRoot, function (callName, config, name, deps, node) {\n locs.push(node.loc);\n //Do not recurse into define functions, they should be using\n //local defines.\n return callName !== 'define';\n }, {});\n\n if (locs.length) {\n lines = fileContents.split('\\n');\n\n //Go backwards through the found locs, adding in the namespace name\n //in front.\n locs.reverse();\n locs.forEach(function (loc) {\n var startIndex = loc.start.column,\n //start.line is 1-based, not 0 based.\n lineIndex = loc.start.line - 1,\n line = lines[lineIndex];\n\n lines[lineIndex] = line.substring(0, startIndex) +\n ns + '.' +\n line.substring(startIndex,\n line.length);\n });\n\n fileContents = lines.join('\\n');\n }\n\n return fileContents;\n };\n\n /**\n * Finds all dependencies specified in dependency arrays and inside\n * simplified commonjs wrappers.\n * @param {String} fileName\n * @param {String} fileContents\n *\n * @returns {Array} an array of dependency strings. The dependencies\n * have not been normalized, they may be relative IDs.\n */\n parse.findDependencies = function (fileName, fileContents, options) {\n var dependencies = [],\n astRoot = esprima.parse(fileContents);\n\n parse.recurse(astRoot, function (callName, config, name, deps) {\n if (deps) {\n dependencies = dependencies.concat(deps);\n }\n }, options);\n\n return dependencies;\n };\n\n /**\n * Finds only CJS dependencies, ones that are the form\n * require('stringLiteral')\n */\n parse.findCjsDependencies = function (fileName, fileContents) {\n var dependencies = [];\n\n traverse(esprima.parse(fileContents), function (node) {\n var arg;\n\n if (node && node.type === 'CallExpression' && node.callee &&\n node.callee.type === 'Identifier' &&\n node.callee.name === 'require' && node[argPropName] &&\n node[argPropName].length === 1) {\n arg = node[argPropName][0];\n if (arg.type === 'Literal') {\n dependencies.push(arg.value);\n }\n }\n });\n\n return dependencies;\n };\n\n //function define() {}\n parse.hasDefDefine = function (node) {\n return node.type === 'FunctionDeclaration' && node.id &&\n node.id.type === 'Identifier' && node.id.name === 'define';\n };\n\n //define.amd = ...\n parse.hasDefineAmd = function (node) {\n return node && node.type === 'AssignmentExpression' &&\n node.left && node.left.type === 'MemberExpression' &&\n node.left.object && node.left.object.name === 'define' &&\n node.left.property && node.left.property.name === 'amd';\n };\n\n //define.amd reference, as in: if (define.amd)\n parse.refsDefineAmd = function (node) {\n return node && node.type === 'MemberExpression' &&\n node.object && node.object.name === 'define' &&\n node.object.type === 'Identifier' &&\n node.property && node.property.name === 'amd' &&\n node.property.type === 'Identifier';\n };\n\n //require(), requirejs(), require.config() and requirejs.config()\n parse.hasRequire = function (node) {\n var callName,\n c = node && node.callee;\n\n if (node && node.type === 'CallExpression' && c) {\n if (c.type === 'Identifier' &&\n (c.name === 'require' ||\n c.name === 'requirejs')) {\n //A require/requirejs({}, ...) call\n callName = c.name;\n } else if (c.type === 'MemberExpression' &&\n c.object &&\n c.object.type === 'Identifier' &&\n (c.object.name === 'require' ||\n c.object.name === 'requirejs') &&\n c.property && c.property.name === 'config') {\n // require/requirejs.config({}) call\n callName = c.object.name + 'Config';\n }\n }\n\n return callName;\n };\n\n //define()\n parse.hasDefine = function (node) {\n return node && node.type === 'CallExpression' && node.callee &&\n node.callee.type === 'Identifier' &&\n node.callee.name === 'define';\n };\n\n /**\n * If there is a named define in the file, returns the name. Does not\n * scan for mulitple names, just the first one.\n */\n parse.getNamedDefine = function (fileContents) {\n var name;\n traverse(esprima.parse(fileContents), function (node) {\n if (node && node.type === 'CallExpression' && node.callee &&\n node.callee.type === 'Identifier' &&\n node.callee.name === 'define' &&\n node[argPropName] && node[argPropName][0] &&\n node[argPropName][0].type === 'Literal') {\n name = node[argPropName][0].value;\n return false;\n }\n });\n\n return name;\n };\n\n /**\n * Determines if define(), require({}|[]) or requirejs was called in the\n * file. Also finds out if define() is declared and if define.amd is called.\n */\n parse.usesAmdOrRequireJs = function (fileName, fileContents) {\n var uses;\n\n traverse(esprima.parse(fileContents), function (node) {\n var type, callName, arg;\n\n if (parse.hasDefDefine(node)) {\n //function define() {}\n type = 'declaresDefine';\n } else if (parse.hasDefineAmd(node)) {\n type = 'defineAmd';\n } else {\n callName = parse.hasRequire(node);\n if (callName) {\n arg = node[argPropName] && node[argPropName][0];\n if (arg && (arg.type === 'ObjectExpression' ||\n arg.type === 'ArrayExpression')) {\n type = callName;\n }\n } else if (parse.hasDefine(node)) {\n type = 'define';\n }\n }\n\n if (type) {\n if (!uses) {\n uses = {};\n }\n uses[type] = true;\n }\n });\n\n return uses;\n };\n\n /**\n * Determines if require(''), exports.x =, module.exports =,\n * __dirname, __filename are used. So, not strictly traditional CommonJS,\n * also checks for Node variants.\n */\n parse.usesCommonJs = function (fileName, fileContents) {\n var uses = null,\n assignsExports = false;\n\n\n traverse(esprima.parse(fileContents), function (node) {\n var type,\n exp = node.expression || node.init;\n\n if (node.type === 'Identifier' &&\n (node.name === '__dirname' || node.name === '__filename')) {\n type = node.name.substring(2);\n } else if (node.type === 'VariableDeclarator' && node.id &&\n node.id.type === 'Identifier' &&\n node.id.name === 'exports') {\n //Hmm, a variable assignment for exports, so does not use cjs\n //exports.\n type = 'varExports';\n } else if (exp && exp.type === 'AssignmentExpression' && exp.left &&\n exp.left.type === 'MemberExpression' && exp.left.object) {\n if (exp.left.object.name === 'module' && exp.left.property &&\n exp.left.property.name === 'exports') {\n type = 'moduleExports';\n } else if (exp.left.object.name === 'exports' &&\n exp.left.property) {\n type = 'exports';\n }\n\n } else if (node && node.type === 'CallExpression' && node.callee &&\n node.callee.type === 'Identifier' &&\n node.callee.name === 'require' && node[argPropName] &&\n node[argPropName].length === 1 &&\n node[argPropName][0].type === 'Literal') {\n type = 'require';\n }\n\n if (type) {\n if (type === 'varExports') {\n assignsExports = true;\n } else if (type !== 'exports' || !assignsExports) {\n if (!uses) {\n uses = {};\n }\n uses[type] = true;\n }\n }\n });\n\n return uses;\n };\n\n\n parse.findRequireDepNames = function (node, deps) {\n traverse(node, function (node) {\n var arg;\n\n if (node && node.type === 'CallExpression' && node.callee &&\n node.callee.type === 'Identifier' &&\n node.callee.name === 'require' &&\n node[argPropName] && node[argPropName].length === 1) {\n\n arg = node[argPropName][0];\n if (arg.type === 'Literal') {\n deps.push(arg.value);\n }\n }\n });\n };\n\n /**\n * Determines if a specific node is a valid require or define/require.def\n * call.\n * @param {Array} node\n * @param {Function} onMatch a function to call when a match is found.\n * It is passed the match name, and the config, name, deps possible args.\n * The config, name and deps args are not normalized.\n * @param {Object} fnExpScope an object whose keys are all function\n * expression identifiers that should be in scope. Useful for UMD wrapper\n * detection to avoid parsing more into the wrapped UMD code.\n *\n * @returns {String} a JS source string with the valid require/define call.\n * Otherwise null.\n */\n parse.parseNode = function (node, onMatch, fnExpScope) {\n var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode,\n args = node && node[argPropName],\n callName = parse.hasRequire(node);\n\n if (callName === 'require' || callName === 'requirejs') {\n //A plain require/requirejs call\n arg = node[argPropName] && node[argPropName][0];\n if (arg.type !== 'ArrayExpression') {\n if (arg.type === 'ObjectExpression') {\n //A config call, try the second arg.\n arg = node[argPropName][1];\n }\n }\n\n deps = getValidDeps(arg);\n if (!deps) {\n return;\n }\n\n return onMatch(\"require\", null, null, deps, node);\n } else if (parse.hasDefine(node) && args && args.length) {\n name = args[0];\n deps = args[1];\n factory = args[2];\n\n if (name.type === 'ArrayExpression') {\n //No name, adjust args\n factory = deps;\n deps = name;\n name = null;\n } else if (name.type === 'FunctionExpression') {\n //Just the factory, no name or deps\n factory = name;\n name = deps = null;\n } else if (name.type !== 'Literal') {\n //An object literal, just null out\n name = deps = factory = null;\n }\n\n if (name && name.type === 'Literal' && deps) {\n if (deps.type === 'FunctionExpression') {\n //deps is the factory\n factory = deps;\n deps = null;\n } else if (deps.type === 'ObjectExpression') {\n //deps is object literal, null out\n deps = factory = null;\n } else if (deps.type === 'Identifier' && args.length === 2) {\n // define('id', factory)\n deps = factory = null;\n }\n }\n\n if (deps && deps.type === 'ArrayExpression') {\n deps = getValidDeps(deps);\n } else if (factory && factory.type === 'FunctionExpression') {\n //If no deps and a factory function, could be a commonjs sugar\n //wrapper, scan the function for dependencies.\n cjsDeps = parse.getAnonDepsFromNode(factory);\n if (cjsDeps.length) {\n deps = cjsDeps;\n }\n } else if (deps || factory) {\n //Does not match the shape of an AMD call.\n return;\n }\n\n //Just save off the name as a string instead of an AST object.\n if (name && name.type === 'Literal') {\n name = name.value;\n }\n\n return onMatch(\"define\", null, name, deps, node,\n (factory && factory.type === 'Identifier' ? factory.name : undefined),\n fnExpScope);\n } else if (node.type === 'CallExpression' && node.callee &&\n node.callee.type === 'FunctionExpression' &&\n node.callee.body && node.callee.body.body &&\n node.callee.body.body.length === 1 &&\n node.callee.body.body[0].type === 'IfStatement') {\n bodyNode = node.callee.body.body[0];\n //Look for a define(Identifier) case, but only if inside an\n //if that has a define.amd test\n if (bodyNode.consequent && bodyNode.consequent.body) {\n exp = bodyNode.consequent.body[0];\n if (exp.type === 'ExpressionStatement' && exp.expression &&\n parse.hasDefine(exp.expression) &&\n exp.expression.arguments &&\n exp.expression.arguments.length === 1 &&\n exp.expression.arguments[0].type === 'Identifier') {\n\n //Calls define(Identifier) as first statement in body.\n //Confirm the if test references define.amd\n traverse(bodyNode.test, function (node) {\n if (parse.refsDefineAmd(node)) {\n refsDefine = true;\n return false;\n }\n });\n\n if (refsDefine) {\n return onMatch(\"define\", null, null, null, exp.expression,\n exp.expression.arguments[0].name, fnExpScope);\n }\n }\n }\n }\n };\n\n /**\n * Converts an AST node into a JS source string by extracting\n * the node's location from the given contents string. Assumes\n * esprima.parse() with loc was done.\n * @param {String} contents\n * @param {Object} node\n * @returns {String} a JS source string.\n */\n parse.nodeToString = function (contents, node) {\n var extracted,\n loc = node.loc,\n lines = contents.split('\\n'),\n firstLine = loc.start.line > 1 ?\n lines.slice(0, loc.start.line - 1).join('\\n') + '\\n' :\n '',\n preamble = firstLine +\n lines[loc.start.line - 1].substring(0, loc.start.column);\n\n if (loc.start.line === loc.end.line) {\n extracted = lines[loc.start.line - 1].substring(loc.start.column,\n loc.end.column);\n } else {\n extracted = lines[loc.start.line - 1].substring(loc.start.column) +\n '\\n' +\n lines.slice(loc.start.line, loc.end.line - 1).join('\\n') +\n '\\n' +\n lines[loc.end.line - 1].substring(0, loc.end.column);\n }\n\n return {\n value: extracted,\n range: [\n preamble.length,\n preamble.length + extracted.length\n ]\n };\n };\n\n /**\n * Extracts license comments from JS text.\n * @param {String} fileName\n * @param {String} contents\n * @returns {String} a string of license comments.\n */\n parse.getLicenseComments = function (fileName, contents) {\n var commentNode, refNode, subNode, value, i, j,\n //xpconnect's Reflect does not support comment or range, but\n //prefer continued operation vs strict parity of operation,\n //as license comments can be expressed in other ways, like\n //via wrap args, or linked via sourcemaps.\n ast = esprima.parse(contents, {\n comment: true,\n range: true\n }),\n result = '',\n existsMap = {},\n lineEnd = contents.indexOf('\\r') === -1 ? '\\n' : '\\r\\n';\n\n if (ast.comments) {\n for (i = 0; i < ast.comments.length; i++) {\n commentNode = ast.comments[i];\n\n if (commentNode.type === 'Line') {\n value = '//' + commentNode.value + lineEnd;\n refNode = commentNode;\n\n if (i + 1 >= ast.comments.length) {\n value += lineEnd;\n } else {\n //Look for immediately adjacent single line comments\n //since it could from a multiple line comment made out\n //of single line comments. Like this comment.\n for (j = i + 1; j < ast.comments.length; j++) {\n subNode = ast.comments[j];\n if (subNode.type === 'Line' &&\n subNode.range[0] === refNode.range[1] + 1) {\n //Adjacent single line comment. Collect it.\n value += '//' + subNode.value + lineEnd;\n refNode = subNode;\n } else {\n //No more single line comment blocks. Break out\n //and continue outer looping.\n break;\n }\n }\n value += lineEnd;\n i = j - 1;\n }\n } else {\n value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd;\n }\n\n if (!existsMap[value] && (value.indexOf('license') !== -1 ||\n (commentNode.type === 'Block' &&\n value.indexOf('/*!') === 0) ||\n value.indexOf('opyright') !== -1 ||\n value.indexOf('(c)') !== -1)) {\n\n result += value;\n existsMap[value] = true;\n }\n\n }\n }\n\n return result;\n };\n\n return parse;\n});\n/**\n * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*global define */\n\ndefine('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'],\nfunction (esprima, parse, logger, lang) {\n 'use strict';\n var transform,\n baseIndentRegExp = /^([ \\t]+)/,\n indentRegExp = /\\{[\\r\\n]+([ \\t]+)/,\n keyRegExp = /^[_A-Za-z]([A-Za-z\\d_]*)$/,\n bulkIndentRegExps = {\n '\\n': /\\n/g,\n '\\r\\n': /\\r\\n/g\n };\n\n function applyIndent(str, indent, lineReturn) {\n var regExp = bulkIndentRegExps[lineReturn];\n return str.replace(regExp, '$&' + indent);\n }\n\n transform = {\n toTransport: function (namespace, moduleName, path, contents, onFound, options) {\n options = options || {};\n\n var astRoot, contentLines, modLine,\n foundAnon,\n scanCount = 0,\n scanReset = false,\n defineInfos = [],\n applySourceUrl = function (contents) {\n if (options.useSourceUrl) {\n contents = 'eval(\"' + lang.jsEscape(contents) +\n '\\\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') +\n path +\n '\");\\n';\n }\n return contents;\n };\n\n try {\n astRoot = esprima.parse(contents, {\n loc: true\n });\n } catch (e) {\n logger.trace('toTransport skipping ' + path + ': ' +\n e.toString());\n return contents;\n }\n\n //Find the define calls and their position in the files.\n parse.traverse(astRoot, function (node) {\n var args, firstArg, firstArgLoc, factoryNode,\n needsId, depAction, foundId, init,\n sourceUrlData, range,\n namespaceExists = false;\n\n // If a bundle script with a define declaration, do not\n // parse any further at this level. Likely a built layer\n // by some other tool.\n if (node.type === 'VariableDeclarator' &&\n node.id && node.id.name === 'define' &&\n node.id.type === 'Identifier') {\n init = node.init;\n if (init && init.callee &&\n init.callee.type === 'CallExpression' &&\n init.callee.callee &&\n init.callee.callee.type === 'Identifier' &&\n init.callee.callee.name === 'require' &&\n init.callee.arguments && init.callee.arguments.length === 1 &&\n init.callee.arguments[0].type === 'Literal' &&\n init.callee.arguments[0].value &&\n init.callee.arguments[0].value.indexOf('amdefine') !== -1) {\n // the var define = require('amdefine')(module) case,\n // keep going in that case.\n } else {\n return false;\n }\n }\n\n namespaceExists = namespace &&\n node.type === 'CallExpression' &&\n node.callee && node.callee.object &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === namespace &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'define';\n\n if (namespaceExists || parse.isDefineNodeWithArgs(node)) {\n //The arguments are where its at.\n args = node.arguments;\n if (!args || !args.length) {\n return;\n }\n\n firstArg = args[0];\n firstArgLoc = firstArg.loc;\n\n if (args.length === 1) {\n if (firstArg.type === 'Identifier') {\n //The define(factory) case, but\n //only allow it if one Identifier arg,\n //to limit impact of false positives.\n needsId = true;\n depAction = 'empty';\n } else if (firstArg.type === 'FunctionExpression') {\n //define(function(){})\n factoryNode = firstArg;\n needsId = true;\n depAction = 'scan';\n } else if (firstArg.type === 'ObjectExpression') {\n //define({});\n needsId = true;\n depAction = 'skip';\n } else if (firstArg.type === 'Literal' &&\n typeof firstArg.value === 'number') {\n //define('12345');\n needsId = true;\n depAction = 'skip';\n } else if (firstArg.type === 'UnaryExpression' &&\n firstArg.operator === '-' &&\n firstArg.argument &&\n firstArg.argument.type === 'Literal' &&\n typeof firstArg.argument.value === 'number') {\n //define('-12345');\n needsId = true;\n depAction = 'skip';\n } else if (firstArg.type === 'MemberExpression' &&\n firstArg.object &&\n firstArg.property &&\n firstArg.property.type === 'Identifier') {\n //define(this.key);\n needsId = true;\n depAction = 'empty';\n }\n } else if (firstArg.type === 'ArrayExpression') {\n //define([], ...);\n needsId = true;\n depAction = 'skip';\n } else if (firstArg.type === 'Literal' &&\n typeof firstArg.value === 'string') {\n //define('string', ....)\n //Already has an ID.\n needsId = false;\n if (args.length === 2 &&\n args[1].type === 'FunctionExpression') {\n //Needs dependency scanning.\n factoryNode = args[1];\n depAction = 'scan';\n } else {\n depAction = 'skip';\n }\n } else {\n //Unknown define entity, keep looking, even\n //in the subtree for this node.\n return;\n }\n\n range = {\n foundId: foundId,\n needsId: needsId,\n depAction: depAction,\n namespaceExists: namespaceExists,\n node: node,\n defineLoc: node.loc,\n firstArgLoc: firstArgLoc,\n factoryNode: factoryNode,\n sourceUrlData: sourceUrlData\n };\n\n //Only transform ones that do not have IDs. If it has an\n //ID but no dependency array, assume it is something like\n //a phonegap implementation, that has its own internal\n //define that cannot handle dependency array constructs,\n //and if it is a named module, then it means it has been\n //set for transport form.\n if (range.needsId) {\n if (foundAnon) {\n logger.trace(path + ' has more than one anonymous ' +\n 'define. May be a built file from another ' +\n 'build system like, Ender. Skipping normalization.');\n defineInfos = [];\n return false;\n } else {\n foundAnon = range;\n defineInfos.push(range);\n }\n } else if (depAction === 'scan') {\n scanCount += 1;\n if (scanCount > 1) {\n //Just go back to an array that just has the\n //anon one, since this is an already optimized\n //file like the phonegap one.\n if (!scanReset) {\n defineInfos = foundAnon ? [foundAnon] : [];\n scanReset = true;\n }\n } else {\n defineInfos.push(range);\n }\n }\n }\n });\n\n\n if (!defineInfos.length) {\n return applySourceUrl(contents);\n }\n\n //Reverse the matches, need to start from the bottom of\n //the file to modify it, so that the ranges are still true\n //further up.\n defineInfos.reverse();\n\n contentLines = contents.split('\\n');\n\n modLine = function (loc, contentInsertion) {\n var startIndex = loc.start.column,\n //start.line is 1-based, not 0 based.\n lineIndex = loc.start.line - 1,\n line = contentLines[lineIndex];\n contentLines[lineIndex] = line.substring(0, startIndex) +\n contentInsertion +\n line.substring(startIndex,\n line.length);\n };\n\n defineInfos.forEach(function (info) {\n var deps,\n contentInsertion = '',\n depString = '';\n\n //Do the modifications \"backwards\", in other words, start with the\n //one that is farthest down and work up, so that the ranges in the\n //defineInfos still apply. So that means deps, id, then namespace.\n if (info.needsId && moduleName) {\n contentInsertion += \"'\" + moduleName + \"',\";\n }\n\n if (info.depAction === 'scan') {\n deps = parse.getAnonDepsFromNode(info.factoryNode);\n\n if (deps.length) {\n depString = '[' + deps.map(function (dep) {\n return \"'\" + dep + \"'\";\n }) + ']';\n } else {\n depString = '[]';\n }\n depString += ',';\n\n if (info.factoryNode) {\n //Already have a named module, need to insert the\n //dependencies after the name.\n modLine(info.factoryNode.loc, depString);\n } else {\n contentInsertion += depString;\n }\n }\n\n if (contentInsertion) {\n modLine(info.firstArgLoc, contentInsertion);\n }\n\n //Do namespace last so that ui does not mess upthe parenRange\n //used above.\n if (namespace && !info.namespaceExists) {\n modLine(info.defineLoc, namespace + '.');\n }\n\n //Notify any listener for the found info\n if (onFound) {\n onFound(info);\n }\n });\n\n contents = contentLines.join('\\n');\n\n return applySourceUrl(contents);\n },\n\n /**\n * Modify the contents of a require.config/requirejs.config call. This\n * call will LOSE any existing comments that are in the config string.\n *\n * @param {String} fileContents String that may contain a config call\n * @param {Function} onConfig Function called when the first config\n * call is found. It will be passed an Object which is the current\n * config, and the onConfig function should return an Object to use\n * as the config.\n * @return {String} the fileContents with the config changes applied.\n */\n modifyConfig: function (fileContents, onConfig) {\n var details = parse.findConfig(fileContents),\n config = details.config;\n\n if (config) {\n config = onConfig(config);\n if (config) {\n return transform.serializeConfig(config,\n fileContents,\n details.range[0],\n details.range[1],\n {\n quote: details.quote\n });\n }\n }\n\n return fileContents;\n },\n\n serializeConfig: function (config, fileContents, start, end, options) {\n //Calculate base level of indent\n var indent, match, configString, outDentRegExp,\n baseIndent = '',\n startString = fileContents.substring(0, start),\n existingConfigString = fileContents.substring(start, end),\n lineReturn = existingConfigString.indexOf('\\r') === -1 ? '\\n' : '\\r\\n',\n lastReturnIndex = startString.lastIndexOf('\\n');\n\n //Get the basic amount of indent for the require config call.\n if (lastReturnIndex === -1) {\n lastReturnIndex = 0;\n }\n\n match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start));\n if (match && match[1]) {\n baseIndent = match[1];\n }\n\n //Calculate internal indentation for config\n match = indentRegExp.exec(existingConfigString);\n if (match && match[1]) {\n indent = match[1];\n }\n\n if (!indent || indent.length < baseIndent) {\n indent = ' ';\n } else {\n indent = indent.substring(baseIndent.length);\n }\n\n outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g');\n\n configString = transform.objectToString(config, {\n indent: indent,\n lineReturn: lineReturn,\n outDentRegExp: outDentRegExp,\n quote: options && options.quote\n });\n\n //Add in the base indenting level.\n configString = applyIndent(configString, baseIndent, lineReturn);\n\n return startString + configString + fileContents.substring(end);\n },\n\n /**\n * Tries converting a JS object to a string. This will likely suck, and\n * is tailored to the type of config expected in a loader config call.\n * So, hasOwnProperty fields, strings, numbers, arrays and functions,\n * no weird recursively referenced stuff.\n * @param {Object} obj the object to convert\n * @param {Object} options options object with the following values:\n * {String} indent the indentation to use for each level\n * {String} lineReturn the type of line return to use\n * {outDentRegExp} outDentRegExp the regexp to use to outdent functions\n * {String} quote the quote type to use, ' or \". Optional. Default is \"\n * @param {String} totalIndent the total indent to print for this level\n * @return {String} a string representation of the object.\n */\n objectToString: function (obj, options, totalIndent) {\n var startBrace, endBrace, nextIndent,\n first = true,\n value = '',\n lineReturn = options.lineReturn,\n indent = options.indent,\n outDentRegExp = options.outDentRegExp,\n quote = options.quote || '\"';\n\n totalIndent = totalIndent || '';\n nextIndent = totalIndent + indent;\n\n if (obj === null) {\n value = 'null';\n } else if (obj === undefined) {\n value = 'undefined';\n } else if (typeof obj === 'number' || typeof obj === 'boolean') {\n value = obj;\n } else if (typeof obj === 'string') {\n //Use double quotes in case the config may also work as JSON.\n value = quote + lang.jsEscape(obj) + quote;\n } else if (lang.isArray(obj)) {\n lang.each(obj, function (item, i) {\n value += (i !== 0 ? ',' + lineReturn : '' ) +\n nextIndent +\n transform.objectToString(item,\n options,\n nextIndent);\n });\n\n startBrace = '[';\n endBrace = ']';\n } else if (lang.isFunction(obj) || lang.isRegExp(obj)) {\n //The outdent regexp just helps pretty up the conversion\n //just in node. Rhino strips comments and does a different\n //indent scheme for Function toString, so not really helpful\n //there.\n value = obj.toString().replace(outDentRegExp, '$1');\n } else {\n //An object\n lang.eachProp(obj, function (v, prop) {\n value += (first ? '': ',' + lineReturn) +\n nextIndent +\n (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+\n ': ' +\n transform.objectToString(v,\n options,\n nextIndent);\n first = false;\n });\n startBrace = '{';\n endBrace = '}';\n }\n\n if (startBrace) {\n value = startBrace +\n lineReturn +\n value +\n lineReturn + totalIndent +\n endBrace;\n }\n\n return value;\n }\n };\n\n return transform;\n});\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint regexp: true, plusplus: true */\n/*global define: false */\n\ndefine('pragma', ['parse', 'logger'], function (parse, logger) {\n 'use strict';\n function Temp() {}\n\n function create(obj, mixin) {\n Temp.prototype = obj;\n var temp = new Temp(), prop;\n\n //Avoid any extra memory hanging around\n Temp.prototype = null;\n\n if (mixin) {\n for (prop in mixin) {\n if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) {\n temp[prop] = mixin[prop];\n }\n }\n }\n\n return temp; // Object\n }\n\n var pragma = {\n conditionalRegExp: /(exclude|include)Start\\s*\\(\\s*[\"'](\\w+)[\"']\\s*,(.*)\\)/,\n useStrictRegExp: /['\"]use strict['\"];/g,\n hasRegExp: /has\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n configRegExp: /(^|[^\\.])(requirejs|require)(\\.config)\\s*\\(/g,\n nsWrapRegExp: /\\/\\*requirejs namespace: true \\*\\//,\n apiDefRegExp: /var requirejs,\\s*require,\\s*define;/,\n defineCheckRegExp: /typeof\\s+define\\s*===?\\s*[\"']function[\"']\\s*&&\\s*define\\s*\\.\\s*amd/g,\n defineStringCheckRegExp: /typeof\\s+define\\s*===?\\s*[\"']function[\"']\\s*&&\\s*define\\s*\\[\\s*[\"']amd[\"']\\s*\\]/g,\n defineTypeFirstCheckRegExp: /\\s*[\"']function[\"']\\s*==(=?)\\s*typeof\\s+define\\s*&&\\s*define\\s*\\.\\s*amd/g,\n defineJQueryRegExp: /typeof\\s+define\\s*===?\\s*[\"']function[\"']\\s*&&\\s*define\\s*\\.\\s*amd\\s*&&\\s*define\\s*\\.\\s*amd\\s*\\.\\s*jQuery/g,\n defineHasRegExp: /typeof\\s+define\\s*==(=)?\\s*['\"]function['\"]\\s*&&\\s*typeof\\s+define\\.amd\\s*==(=)?\\s*['\"]object['\"]\\s*&&\\s*define\\.amd/g,\n defineTernaryRegExp: /typeof\\s+define\\s*===?\\s*['\"]function[\"']\\s*&&\\s*define\\s*\\.\\s*amd\\s*\\?\\s*define/,\n amdefineRegExp: /if\\s*\\(\\s*typeof define\\s*\\!==\\s*'function'\\s*\\)\\s*\\{\\s*[^\\{\\}]+amdefine[^\\{\\}]+\\}/g,\n\n removeStrict: function (contents, config) {\n return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '');\n },\n\n namespace: function (fileContents, ns, onLifecycleName) {\n if (ns) {\n //Namespace require/define calls\n fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3(');\n\n\n fileContents = parse.renameNamespace(fileContents, ns);\n\n //Namespace define ternary use:\n fileContents = fileContents.replace(pragma.defineTernaryRegExp,\n \"typeof \" + ns + \".define === 'function' && \" + ns + \".define.amd ? \" + ns + \".define\");\n\n //Namespace define jquery use:\n fileContents = fileContents.replace(pragma.defineJQueryRegExp,\n \"typeof \" + ns + \".define === 'function' && \" + ns + \".define.amd && \" + ns + \".define.amd.jQuery\");\n\n //Namespace has.js define use:\n fileContents = fileContents.replace(pragma.defineHasRegExp,\n \"typeof \" + ns + \".define === 'function' && typeof \" + ns + \".define.amd === 'object' && \" + ns + \".define.amd\");\n\n //Namespace define checks.\n //Do these ones last, since they are a subset of the more specific\n //checks above.\n fileContents = fileContents.replace(pragma.defineCheckRegExp,\n \"typeof \" + ns + \".define === 'function' && \" + ns + \".define.amd\");\n fileContents = fileContents.replace(pragma.defineStringCheckRegExp,\n \"typeof \" + ns + \".define === 'function' && \" + ns + \".define['amd']\");\n fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp,\n \"'function' === typeof \" + ns + \".define && \" + ns + \".define.amd\");\n\n //Check for require.js with the require/define definitions\n if (pragma.apiDefRegExp.test(fileContents) &&\n fileContents.indexOf(\"if (!\" + ns + \" || !\" + ns + \".requirejs)\") === -1) {\n //Wrap the file contents in a typeof check, and a function\n //to contain the API globals.\n fileContents = \"var \" + ns + \";(function () { if (!\" + ns + \" || !\" + ns + \".requirejs) {\\n\" +\n \"if (!\" + ns + \") { \" + ns + ' = {}; } else { require = ' + ns + '; }\\n' +\n fileContents +\n \"\\n\" +\n ns + \".requirejs = requirejs;\" +\n ns + \".require = require;\" +\n ns + \".define = define;\\n\" +\n \"}\\n}());\";\n }\n\n //Finally, if the file wants a special wrapper because it ties\n //in to the requirejs internals in a way that would not fit\n //the above matches, do that. Look for /*requirejs namespace: true*/\n if (pragma.nsWrapRegExp.test(fileContents)) {\n //Remove the pragma.\n fileContents = fileContents.replace(pragma.nsWrapRegExp, '');\n\n //Alter the contents.\n fileContents = '(function () {\\n' +\n 'var require = ' + ns + '.require,' +\n 'requirejs = ' + ns + '.requirejs,' +\n 'define = ' + ns + '.define;\\n' +\n fileContents +\n '\\n}());';\n }\n }\n\n return fileContents;\n },\n\n /**\n * processes the fileContents for some //>> conditional statements\n */\n process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) {\n /*jslint evil: true */\n var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,\n matches, type, marker, condition, isTrue, endRegExp, endMatches,\n endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,\n i, dep, moduleName, collectorMod,\n lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,\n //Legacy arg defined to help in dojo conversion script. Remove later\n //when dojo no longer needs conversion:\n kwArgs = pragmas;\n\n //Mix in a specific lifecycle scoped object, to allow targeting\n //some pragmas/has tests to only when files are saved, or at different\n //lifecycle events. Do not bother with kwArgs in this section, since\n //the old dojo kwArgs were for all points in the build lifecycle.\n if (onLifecycleName) {\n lifecyclePragmas = config['pragmas' + onLifecycleName];\n lifecycleHas = config['has' + onLifecycleName];\n\n if (lifecyclePragmas) {\n pragmas = create(pragmas || {}, lifecyclePragmas);\n }\n\n if (lifecycleHas) {\n hasConfig = create(hasConfig || {}, lifecycleHas);\n }\n }\n\n //Replace has references if desired\n if (hasConfig) {\n fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {\n if (hasConfig.hasOwnProperty(test)) {\n return !!hasConfig[test];\n }\n return match;\n });\n }\n\n if (!config.skipPragmas) {\n\n while ((foundIndex = fileContents.indexOf(\"//>>\", startIndex)) !== -1) {\n //Found a conditional. Get the conditional line.\n lineEndIndex = fileContents.indexOf(\"\\n\", foundIndex);\n if (lineEndIndex === -1) {\n lineEndIndex = fileContents.length - 1;\n }\n\n //Increment startIndex past the line so the next conditional search can be done.\n startIndex = lineEndIndex + 1;\n\n //Break apart the conditional.\n conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);\n matches = conditionLine.match(pragma.conditionalRegExp);\n if (matches) {\n type = matches[1];\n marker = matches[2];\n condition = matches[3];\n isTrue = false;\n //See if the condition is true.\n try {\n isTrue = !!eval(\"(\" + condition + \")\");\n } catch (e) {\n throw \"Error in file: \" +\n fileName +\n \". Conditional comment: \" +\n conditionLine +\n \" failed with this error: \" + e;\n }\n\n //Find the endpoint marker.\n endRegExp = new RegExp('\\\\/\\\\/\\\\>\\\\>\\\\s*' + type + 'End\\\\(\\\\s*[\\'\"]' + marker + '[\\'\"]\\\\s*\\\\)', \"g\");\n endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));\n if (endMatches) {\n endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;\n\n //Find the next line return based on the match position.\n lineEndIndex = fileContents.indexOf(\"\\n\", endMarkerIndex);\n if (lineEndIndex === -1) {\n lineEndIndex = fileContents.length - 1;\n }\n\n //Should we include the segment?\n shouldInclude = ((type === \"exclude\" && !isTrue) || (type === \"include\" && isTrue));\n\n //Remove the conditional comments, and optionally remove the content inside\n //the conditional comments.\n startLength = startIndex - foundIndex;\n fileContents = fileContents.substring(0, foundIndex) +\n (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : \"\") +\n fileContents.substring(lineEndIndex + 1, fileContents.length);\n\n //Move startIndex to foundIndex, since that is the new position in the file\n //where we need to look for more conditionals in the next while loop pass.\n startIndex = foundIndex;\n } else {\n throw \"Error in file: \" +\n fileName +\n \". Cannot find end marker for conditional comment: \" +\n conditionLine;\n\n }\n }\n }\n }\n\n //If need to find all plugin resources to optimize, do that now,\n //before namespacing, since the namespacing will change the API\n //names.\n //If there is a plugin collector, scan the file for plugin resources.\n if (config.optimizeAllPluginResources && pluginCollector) {\n try {\n deps = parse.findDependencies(fileName, fileContents);\n if (deps.length) {\n for (i = 0; i < deps.length; i++) {\n dep = deps[i];\n if (dep.indexOf('!') !== -1) {\n moduleName = dep.split('!')[0];\n collectorMod = pluginCollector[moduleName];\n if (!collectorMod) {\n collectorMod = pluginCollector[moduleName] = [];\n }\n collectorMod.push(dep);\n }\n }\n }\n } catch (eDep) {\n logger.error('Parse error looking for plugin resources in ' +\n fileName + ', skipping.');\n }\n }\n\n //Strip amdefine use for node-shared modules.\n if (!config.keepAmdefine) {\n fileContents = fileContents.replace(pragma.amdefineRegExp, '');\n }\n\n //Do namespacing\n if (onLifecycleName === 'OnSave' && config.namespace) {\n fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);\n }\n\n\n return pragma.removeStrict(fileContents, config);\n }\n };\n\n return pragma;\n});\nif(env === 'browser') {\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false */\n\ndefine('browser/optimize', {});\n\n}\n\nif(env === 'node') {\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint strict: false */\n/*global define: false */\n\ndefine('node/optimize', {});\n\n}\n\nif(env === 'rhino') {\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint sloppy: true, plusplus: true */\n/*global define, java, Packages, com */\n\ndefine('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) {\n\n //Add .reduce to Rhino so UglifyJS can run in Rhino,\n //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce\n //but rewritten for brevity, and to be good enough for use by UglifyJS.\n if (!Array.prototype.reduce) {\n Array.prototype.reduce = function (fn /*, initialValue */) {\n var i = 0,\n length = this.length,\n accumulator;\n\n if (arguments.length >= 2) {\n accumulator = arguments[1];\n } else {\n if (length) {\n while (!(i in this)) {\n i++;\n }\n accumulator = this[i++];\n }\n }\n\n for (; i < length; i++) {\n if (i in this) {\n accumulator = fn.call(undefined, accumulator, this[i], i, this);\n }\n }\n\n return accumulator;\n };\n }\n\n var JSSourceFilefromCode, optimize,\n mapRegExp = /\"file\":\"[^\"]+\"/;\n\n //Bind to Closure compiler, but if it is not available, do not sweat it.\n try {\n // Try older closure compiler that worked on Java 6\n JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);\n } catch (e) {\n try {\n // Try for newer closure compiler that needs Java 7+\n JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.SourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);\n } catch (e) {}\n }\n\n //Helper for closure compiler, because of weird Java-JavaScript interactions.\n function closurefromCode(filename, content) {\n return JSSourceFilefromCode.invoke(null, [filename, content]);\n }\n\n\n function getFileWriter(fileName, encoding) {\n var outFile = new java.io.File(fileName), outWriter, parentDir;\n\n parentDir = outFile.getAbsoluteFile().getParentFile();\n if (!parentDir.exists()) {\n if (!parentDir.mkdirs()) {\n throw \"Could not create directory: \" + parentDir.getAbsolutePath();\n }\n }\n\n if (encoding) {\n outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);\n } else {\n outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));\n }\n\n return new java.io.BufferedWriter(outWriter);\n }\n\n optimize = {\n closure: function (fileName, fileContents, outFileName, keepLines, config) {\n config = config || {};\n var result, mappings, optimized, compressed, baseName, writer,\n outBaseName, outFileNameMap, outFileNameMapContent,\n srcOutFileName, concatNameMap,\n jscomp = Packages.com.google.javascript.jscomp,\n flags = Packages.com.google.common.flags,\n //Set up source input\n jsSourceFile = closurefromCode(String(fileName), String(fileContents)),\n sourceListArray = new java.util.ArrayList(),\n options, option, FLAG_compilation_level, compiler,\n Compiler = Packages.com.google.javascript.jscomp.Compiler,\n CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner;\n\n logger.trace(\"Minifying file: \" + fileName);\n\n baseName = (new java.io.File(fileName)).getName();\n\n //Set up options\n options = new jscomp.CompilerOptions();\n for (option in config.CompilerOptions) {\n // options are false by default and jslint wanted an if statement in this for loop\n if (config.CompilerOptions[option]) {\n options[option] = config.CompilerOptions[option];\n }\n\n }\n options.prettyPrint = keepLines || options.prettyPrint;\n\n FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];\n FLAG_compilation_level.setOptionsForCompilationLevel(options);\n\n if (config.generateSourceMaps) {\n mappings = new java.util.ArrayList();\n\n mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + \".src.js\"));\n options.setSourceMapLocationMappings(mappings);\n options.setSourceMapOutputPath(fileName + \".map\");\n }\n\n //Trigger the compiler\n Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);\n compiler = new Compiler();\n\n //fill the sourceArrrayList; we need the ArrayList because the only overload of compile\n //accepting the getDefaultExterns return value (a List) also wants the sources as a List\n sourceListArray.add(jsSourceFile);\n\n result = compiler.compile(CommandLineRunner.getDefaultExterns(), sourceListArray, options);\n if (result.success) {\n optimized = String(compiler.toSource());\n\n if (config.generateSourceMaps && result.sourceMap && outFileName) {\n outBaseName = (new java.io.File(outFileName)).getName();\n\n srcOutFileName = outFileName + \".src.js\";\n outFileNameMap = outFileName + \".map\";\n\n //If previous .map file exists, move it to the \".src.js\"\n //location. Need to update the sourceMappingURL part in the\n //src.js file too.\n if (file.exists(outFileNameMap)) {\n concatNameMap = outFileNameMap.replace(/\\.map$/, '.src.js.map');\n file.saveFile(concatNameMap, file.readFile(outFileNameMap));\n file.saveFile(srcOutFileName,\n fileContents.replace(/\\/\\# sourceMappingURL=(.+).map/,\n '/# sourceMappingURL=$1.src.js.map'));\n } else {\n file.saveUtf8File(srcOutFileName, fileContents);\n }\n\n writer = getFileWriter(outFileNameMap, \"utf-8\");\n result.sourceMap.appendTo(writer, outFileName);\n writer.close();\n\n //Not sure how better to do this, but right now the .map file\n //leaks the full OS path in the \"file\" property. Manually\n //modify it to not do that.\n file.saveFile(outFileNameMap,\n file.readFile(outFileNameMap).replace(mapRegExp, '\"file\":\"' + baseName + '\"'));\n\n fileContents = optimized + \"\\n//# sourceMappingURL=\" + outBaseName + \".map\";\n } else {\n fileContents = optimized;\n }\n return fileContents;\n } else {\n throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');\n }\n\n return fileContents;\n }\n };\n\n return optimize;\n});\n}\n\nif(env === 'xpconnect') {\ndefine('xpconnect/optimize', {});\n}\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint plusplus: true, nomen: true, regexp: true */\n/*global define: false */\n\ndefine('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',\n 'pragma', 'uglifyjs/index', 'uglifyjs2',\n 'source-map'],\nfunction (lang, logger, envOptimize, file, parse,\n pragma, uglify, uglify2,\n sourceMap) {\n 'use strict';\n\n var optimize,\n cssImportRegExp = /\\@import\\s+(url\\()?\\s*([^);]+)\\s*(\\))?([\\w, ]*)(;)?/ig,\n cssCommentImportRegExp = /\\/\\*[^\\*]*@import[^\\*]*\\*\\//g,\n cssUrlRegExp = /\\url\\(\\s*([^\\)]+)\\s*\\)?/g,\n protocolRegExp = /^\\w+:/,\n SourceMapGenerator = sourceMap.SourceMapGenerator,\n SourceMapConsumer =sourceMap.SourceMapConsumer;\n\n /**\n * If an URL from a CSS url value contains start/end quotes, remove them.\n * This is not done in the regexp, since my regexp fu is not that strong,\n * and the CSS spec allows for ' and \" in the URL if they are backslash escaped.\n * @param {String} url\n */\n function cleanCssUrlQuotes(url) {\n //Make sure we are not ending in whitespace.\n //Not very confident of the css regexps above that there will not be ending\n //whitespace.\n url = url.replace(/\\s+$/, \"\");\n\n if (url.charAt(0) === \"'\" || url.charAt(0) === \"\\\"\") {\n url = url.substring(1, url.length - 1);\n }\n\n return url;\n }\n\n function fixCssUrlPaths(fileName, path, contents, cssPrefix) {\n return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {\n var firstChar, hasProtocol, parts, i,\n fixedUrlMatch = cleanCssUrlQuotes(urlMatch);\n\n fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, \"/\");\n\n //Only do the work for relative URLs. Skip things that start with / or #, or have\n //a protocol.\n firstChar = fixedUrlMatch.charAt(0);\n hasProtocol = protocolRegExp.test(fixedUrlMatch);\n if (firstChar !== \"/\" && firstChar !== \"#\" && !hasProtocol) {\n //It is a relative URL, tack on the cssPrefix and path prefix\n urlMatch = cssPrefix + path + fixedUrlMatch;\n } else if (!hasProtocol) {\n logger.trace(fileName + \"\\n URL not a relative URL, skipping: \" + urlMatch);\n }\n\n //Collapse .. and .\n parts = urlMatch.split(\"/\");\n for (i = parts.length - 1; i > 0; i--) {\n if (parts[i] === \".\") {\n parts.splice(i, 1);\n } else if (parts[i] === \"..\") {\n if (i !== 0 && parts[i - 1] !== \"..\") {\n parts.splice(i - 1, 2);\n i -= 1;\n }\n }\n }\n\n return \"url(\" + parts.join(\"/\") + \")\";\n });\n }\n\n /**\n * Inlines nested stylesheets that have @import calls in them.\n * @param {String} fileName the file name\n * @param {String} fileContents the file contents\n * @param {String} cssImportIgnore comma delimited string of files to ignore\n * @param {String} cssPrefix string to be prefixed before relative URLs\n * @param {Object} included an object used to track the files already imported\n */\n function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) {\n //Find the last slash in the name.\n fileName = fileName.replace(lang.backSlashRegExp, \"/\");\n var endIndex = fileName.lastIndexOf(\"/\"),\n //Make a file path based on the last slash.\n //If no slash, so must be just a file name. Use empty string then.\n filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : \"\",\n //store a list of merged files\n importList = [],\n skippedList = [];\n\n //First make a pass by removing any commented out @import calls.\n fileContents = fileContents.replace(cssCommentImportRegExp, '');\n\n //Make sure we have a delimited ignore list to make matching faster\n if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== \",\") {\n cssImportIgnore += \",\";\n }\n\n fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {\n //Only process media type \"all\" or empty media type rules.\n if (mediaTypes && ((mediaTypes.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '')) !== \"all\")) {\n skippedList.push(fileName);\n return fullMatch;\n }\n\n importFileName = cleanCssUrlQuotes(importFileName);\n\n //Ignore the file import if it is part of an ignore list.\n if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + \",\") !== -1) {\n return fullMatch;\n }\n\n //Make sure we have a unix path for the rest of the operation.\n importFileName = importFileName.replace(lang.backSlashRegExp, \"/\");\n\n try {\n //if a relative path, then tack on the filePath.\n //If it is not a relative path, then the readFile below will fail,\n //and we will just skip that import.\n var fullImportFileName = importFileName.charAt(0) === \"/\" ? importFileName : filePath + importFileName,\n importContents = file.readFile(fullImportFileName),\n importEndIndex, importPath, flat;\n\n //Skip the file if it has already been included.\n if (included[fullImportFileName]) {\n return '';\n }\n included[fullImportFileName] = true;\n\n //Make sure to flatten any nested imports.\n flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);\n importContents = flat.fileContents;\n\n if (flat.importList.length) {\n importList.push.apply(importList, flat.importList);\n }\n if (flat.skippedList.length) {\n skippedList.push.apply(skippedList, flat.skippedList);\n }\n\n //Make the full import path\n importEndIndex = importFileName.lastIndexOf(\"/\");\n\n //Make a file path based on the last slash.\n //If no slash, so must be just a file name. Use empty string then.\n importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : \"\";\n\n //fix url() on relative import (#5)\n importPath = importPath.replace(/^\\.\\//, '');\n\n //Modify URL paths to match the path represented by this file.\n importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix);\n\n importList.push(fullImportFileName);\n return importContents;\n } catch (e) {\n logger.warn(fileName + \"\\n Cannot inline css import, skipping: \" + importFileName);\n return fullMatch;\n }\n });\n\n if (cssPrefix && topLevel) {\n //Modify URL paths to match the path represented by this file.\n fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix);\n }\n\n return {\n importList : importList,\n skippedList: skippedList,\n fileContents : fileContents\n };\n }\n\n optimize = {\n /**\n * Optimizes a file that contains JavaScript content. Optionally collects\n * plugin resources mentioned in a file, and then passes the content\n * through an minifier if one is specified via config.optimize.\n *\n * @param {String} fileName the name of the file to optimize\n * @param {String} fileContents the contents to optimize. If this is\n * a null value, then fileName will be used to read the fileContents.\n * @param {String} outFileName the name of the file to use for the\n * saved optimized content.\n * @param {Object} config the build config object.\n * @param {Array} [pluginCollector] storage for any plugin resources\n * found.\n */\n jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {\n if (!fileContents) {\n fileContents = file.readFile(fileName);\n }\n\n fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);\n\n file.saveUtf8File(outFileName, fileContents);\n },\n\n /**\n * Optimizes a file that contains JavaScript content. Optionally collects\n * plugin resources mentioned in a file, and then passes the content\n * through an minifier if one is specified via config.optimize.\n *\n * @param {String} fileName the name of the file that matches the\n * fileContents.\n * @param {String} fileContents the string of JS to optimize.\n * @param {Object} [config] the build config object.\n * @param {Array} [pluginCollector] storage for any plugin resources\n * found.\n */\n js: function (fileName, fileContents, outFileName, config, pluginCollector) {\n var optFunc, optConfig,\n parts = (String(config.optimize)).split('.'),\n optimizerName = parts[0],\n keepLines = parts[1] === 'keepLines',\n licenseContents = '';\n\n config = config || {};\n\n //Apply pragmas/namespace renaming\n fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);\n\n //Optimize the JS files if asked.\n if (optimizerName && optimizerName !== 'none') {\n optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];\n if (!optFunc) {\n throw new Error('optimizer with name of \"' +\n optimizerName +\n '\" not found for this environment');\n }\n\n optConfig = config[optimizerName] || {};\n if (config.generateSourceMaps) {\n optConfig.generateSourceMaps = !!config.generateSourceMaps;\n optConfig._buildSourceMap = config._buildSourceMap;\n }\n\n try {\n if (config.preserveLicenseComments) {\n //Pull out any license comments for prepending after optimization.\n try {\n licenseContents = parse.getLicenseComments(fileName, fileContents);\n } catch (e) {\n throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\\n' + e.toString());\n }\n }\n\n fileContents = licenseContents + optFunc(fileName,\n fileContents,\n outFileName,\n keepLines,\n optConfig);\n if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) {\n config._buildSourceMap = optConfig._buildSourceMap;\n }\n } catch (e) {\n if (config.throwWhen && config.throwWhen.optimize) {\n throw e;\n } else {\n logger.error(e);\n }\n }\n } else {\n if (config._buildSourceMap) {\n config._buildSourceMap = null;\n }\n }\n\n return fileContents;\n },\n\n /**\n * Optimizes one CSS file, inlining @import calls, stripping comments, and\n * optionally removes line returns.\n * @param {String} fileName the path to the CSS file to optimize\n * @param {String} outFileName the path to save the optimized file.\n * @param {Object} config the config object with the optimizeCss and\n * cssImportIgnore options.\n */\n cssFile: function (fileName, outFileName, config) {\n\n //Read in the file. Make sure we have a JS string.\n var originalFileContents = file.readFile(fileName),\n flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true),\n //Do not use the flattened CSS if there was one that was skipped.\n fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,\n startIndex, endIndex, buildText, comment;\n\n if (flat.skippedList.length) {\n logger.warn('Cannot inline @imports for ' + fileName +\n ',\\nthe following files had media queries in them:\\n' +\n flat.skippedList.join('\\n'));\n }\n\n //Do comment removal.\n try {\n if (config.optimizeCss.indexOf(\".keepComments\") === -1) {\n startIndex = 0;\n //Get rid of comments.\n while ((startIndex = fileContents.indexOf(\"/*\", startIndex)) !== -1) {\n endIndex = fileContents.indexOf(\"*/\", startIndex + 2);\n if (endIndex === -1) {\n throw \"Improper comment in CSS file: \" + fileName;\n }\n comment = fileContents.substring(startIndex, endIndex);\n\n if (config.preserveLicenseComments &&\n (comment.indexOf('license') !== -1 ||\n comment.indexOf('opyright') !== -1 ||\n comment.indexOf('(c)') !== -1)) {\n //Keep the comment, just increment the startIndex\n startIndex = endIndex;\n } else {\n fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);\n startIndex = 0;\n }\n }\n }\n //Get rid of newlines.\n if (config.optimizeCss.indexOf(\".keepLines\") === -1) {\n fileContents = fileContents.replace(/[\\r\\n]/g, \" \");\n fileContents = fileContents.replace(/\\s+/g, \" \");\n fileContents = fileContents.replace(/\\{\\s/g, \"{\");\n fileContents = fileContents.replace(/\\s\\}/g, \"}\");\n } else {\n //Remove multiple empty lines.\n fileContents = fileContents.replace(/(\\r\\n)+/g, \"\\r\\n\");\n fileContents = fileContents.replace(/(\\n)+/g, \"\\n\");\n }\n //Remove unnecessary whitespace\n if (config.optimizeCss.indexOf(\".keepWhitespace\") === -1) {\n //Remove leading and trailing whitespace from lines\n fileContents = fileContents.replace(/^[ \\t]+/gm, \"\");\n fileContents = fileContents.replace(/[ \\t]+$/gm, \"\");\n //Remove whitespace after semicolon, colon, curly brackets and commas\n fileContents = fileContents.replace(/(;|:|\\{|}|,)[ \\t]+/g, \"$1\");\n //Remove whitespace before opening curly brackets\n fileContents = fileContents.replace(/[ \\t]+(\\{)/g, \"$1\");\n //Truncate double whitespace\n fileContents = fileContents.replace(/([ \\t])+/g, \"$1\");\n //Remove empty lines\n fileContents = fileContents.replace(/^[ \\t]*[\\r\\n]/gm,'');\n }\n } catch (e) {\n fileContents = originalFileContents;\n logger.error(\"Could not optimized CSS file: \" + fileName + \", error: \" + e);\n }\n\n file.saveUtf8File(outFileName, fileContents);\n\n //text output to stdout and/or written to build.txt file\n buildText = \"\\n\"+ outFileName.replace(config.dir, \"\") +\"\\n----------------\\n\";\n flat.importList.push(fileName);\n buildText += flat.importList.map(function(path){\n return path.replace(config.dir, \"\");\n }).join(\"\\n\");\n\n return {\n importList: flat.importList,\n buildText: buildText +\"\\n\"\n };\n },\n\n /**\n * Optimizes CSS files, inlining @import calls, stripping comments, and\n * optionally removes line returns.\n * @param {String} startDir the path to the top level directory\n * @param {Object} config the config object with the optimizeCss and\n * cssImportIgnore options.\n */\n css: function (startDir, config) {\n var buildText = \"\",\n importList = [],\n shouldRemove = config.dir && config.removeCombined,\n i, fileName, result, fileList;\n if (config.optimizeCss.indexOf(\"standard\") !== -1) {\n fileList = file.getFilteredFileList(startDir, /\\.css$/, true);\n if (fileList) {\n for (i = 0; i < fileList.length; i++) {\n fileName = fileList[i];\n logger.trace(\"Optimizing (\" + config.optimizeCss + \") CSS file: \" + fileName);\n result = optimize.cssFile(fileName, fileName, config);\n buildText += result.buildText;\n if (shouldRemove) {\n result.importList.pop();\n importList = importList.concat(result.importList);\n }\n }\n }\n\n if (shouldRemove) {\n importList.forEach(function (path) {\n if (file.exists(path)) {\n file.deleteFile(path);\n }\n });\n }\n }\n return buildText;\n },\n\n optimizers: {\n uglify: function (fileName, fileContents, outFileName, keepLines, config) {\n var parser = uglify.parser,\n processor = uglify.uglify,\n ast, errMessage, errMatch;\n\n config = config || {};\n\n logger.trace(\"Uglifying file: \" + fileName);\n\n try {\n ast = parser.parse(fileContents, config.strict_semicolons);\n if (config.no_mangle !== true) {\n ast = processor.ast_mangle(ast, config);\n }\n ast = processor.ast_squeeze(ast, config);\n\n fileContents = processor.gen_code(ast, config);\n\n if (config.max_line_length) {\n fileContents = processor.split_lines(fileContents, config.max_line_length);\n }\n\n //Add trailing semicolon to match uglifyjs command line version\n fileContents += ';';\n } catch (e) {\n errMessage = e.toString();\n errMatch = /\\nError(\\r)?\\n/.exec(errMessage);\n if (errMatch) {\n errMessage = errMessage.substring(0, errMatch.index);\n }\n throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\\n' + errMessage);\n }\n return fileContents;\n },\n uglify2: function (fileName, fileContents, outFileName, keepLines, config) {\n var result, existingMap, resultMap, finalMap, sourceIndex,\n uconfig = {},\n existingMapPath = outFileName + '.map',\n baseName = fileName && fileName.split('/').pop();\n\n config = config || {};\n\n lang.mixin(uconfig, config, true);\n\n uconfig.fromString = true;\n\n if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) {\n uconfig.outSourceMap = baseName;\n\n if (config._buildSourceMap) {\n existingMap = JSON.parse(config._buildSourceMap);\n uconfig.inSourceMap = existingMap;\n } else if (file.exists(existingMapPath)) {\n uconfig.inSourceMap = existingMapPath;\n existingMap = JSON.parse(file.readFile(existingMapPath));\n }\n }\n\n logger.trace(\"Uglify2 file: \" + fileName);\n\n try {\n //var tempContents = fileContents.replace(/\\/\\/\\# sourceMappingURL=.*$/, '');\n result = uglify2.minify(fileContents, uconfig, baseName + '.src.js');\n if (uconfig.outSourceMap && result.map) {\n resultMap = result.map;\n if (existingMap) {\n resultMap = JSON.parse(resultMap);\n finalMap = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(resultMap));\n finalMap.applySourceMap(new SourceMapConsumer(existingMap));\n resultMap = finalMap.toString();\n } else if (!config._buildSourceMap) {\n file.saveFile(outFileName + '.src.js', fileContents);\n }\n\n fileContents = result.code;\n\n if (config._buildSourceMap) {\n config._buildSourceMap = resultMap;\n } else {\n file.saveFile(outFileName + '.map', resultMap);\n fileContents += \"\\n//# sourceMappingURL=\" + baseName + \".map\";\n }\n } else {\n fileContents = result.code;\n }\n } catch (e) {\n throw new Error('Cannot uglify2 file: ' + fileName + '. Skipping it. Error is:\\n' + e.toString());\n }\n return fileContents;\n }\n }\n };\n\n return optimize;\n});\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n/*\n * This file patches require.js to communicate with the build system.\n */\n\n//Using sloppy since this uses eval for some code like plugins,\n//which may not be strict mode compliant. So if use strict is used\n//below they will have strict rules applied and may cause an error.\n/*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */\n/*global require, define: true */\n\n//NOT asking for require as a dependency since the goal is to modify the\n//global require below\ndefine('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function (\n file,\n pragma,\n parse,\n lang,\n logger,\n commonJs,\n prim\n) {\n\n var allowRun = true,\n hasProp = lang.hasProp,\n falseProp = lang.falseProp,\n getOwn = lang.getOwn;\n\n //Turn off throwing on resolution conflict, that was just an older prim\n //idea about finding errors early, but does not comply with how promises\n //should operate.\n prim.hideResolutionConflict = true;\n\n //This method should be called when the patches to require should take hold.\n return function () {\n if (!allowRun) {\n return;\n }\n allowRun = false;\n\n var layer,\n pluginBuilderRegExp = /([\"']?)pluginBuilder([\"']?)\\s*[=\\:]\\s*[\"']([^'\"\\s]+)[\"']/,\n oldNewContext = require.s.newContext,\n oldDef,\n\n //create local undefined values for module and exports,\n //so that when files are evaled in this function they do not\n //see the node values used for r.js\n exports,\n module;\n\n /**\n * Reset \"global\" build caches that are kept around between\n * build layer builds. Useful to do when there are multiple\n * top level requirejs.optimize() calls.\n */\n require._cacheReset = function () {\n //Stored raw text caches, used by browser use.\n require._cachedRawText = {};\n //Stored cached file contents for reuse in other layers.\n require._cachedFileContents = {};\n //Store which cached files contain a require definition.\n require._cachedDefinesRequireUrls = {};\n };\n require._cacheReset();\n\n /**\n * Makes sure the URL is something that can be supported by the\n * optimization tool.\n * @param {String} url\n * @returns {Boolean}\n */\n require._isSupportedBuildUrl = function (url) {\n //Ignore URLs with protocols, hosts or question marks, means either network\n //access is needed to fetch it or it is too dynamic. Note that\n //on Windows, full paths are used for some urls, which include\n //the drive, like c:/something, so need to test for something other\n //than just a colon.\n if (url.indexOf(\"://\") === -1 && url.indexOf(\"?\") === -1 &&\n url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) {\n return true;\n } else {\n if (!layer.ignoredUrls[url]) {\n if (url.indexOf('empty:') === -1) {\n logger.info('Cannot optimize network URL, skipping: ' + url);\n }\n layer.ignoredUrls[url] = true;\n }\n return false;\n }\n };\n\n function normalizeUrlWithBase(context, moduleName, url) {\n //Adjust the URL if it was not transformed to use baseUrl.\n if (require.jsExtRegExp.test(moduleName)) {\n url = (context.config.dir || context.config.dirBaseUrl) + url;\n }\n return url;\n }\n\n //Overrides the new context call to add existing tracking features.\n require.s.newContext = function (name) {\n var context = oldNewContext(name),\n oldEnable = context.enable,\n moduleProto = context.Module.prototype,\n oldInit = moduleProto.init,\n oldCallPlugin = moduleProto.callPlugin;\n\n //Only do this for the context used for building.\n if (name === '_') {\n //For build contexts, do everything sync\n context.nextTick = function (fn) {\n fn();\n };\n\n context.needFullExec = {};\n context.fullExec = {};\n context.plugins = {};\n context.buildShimExports = {};\n\n //Override the shim exports function generator to just\n //spit out strings that can be used in the stringified\n //build output.\n context.makeShimExports = function (value) {\n var fn;\n if (context.config.wrapShim) {\n fn = function () {\n var str = 'return ';\n // If specifies an export that is just a global\n // name, no dot for a `this.` and such, then also\n // attach to the global, for `var a = {}` files\n // where the function closure would hide that from\n // the global object.\n if (value.exports && value.exports.indexOf('.') === -1) {\n str += 'root.' + value.exports + ' = ';\n }\n\n if (value.init) {\n str += '(' + value.init.toString() + '.apply(this, arguments))';\n }\n if (value.init && value.exports) {\n str += ' || ';\n }\n if (value.exports) {\n str += value.exports;\n }\n str += ';';\n return str;\n };\n } else {\n fn = function () {\n return '(function (global) {\\n' +\n ' return function () {\\n' +\n ' var ret, fn;\\n' +\n (value.init ?\n (' fn = ' + value.init.toString() + ';\\n' +\n ' ret = fn.apply(global, arguments);\\n') : '') +\n (value.exports ?\n ' return ret || global.' + value.exports + ';\\n' :\n ' return ret;\\n') +\n ' };\\n' +\n '}(this))';\n };\n }\n\n return fn;\n };\n\n context.enable = function (depMap, parent) {\n var id = depMap.id,\n parentId = parent && parent.map.id,\n needFullExec = context.needFullExec,\n fullExec = context.fullExec,\n mod = getOwn(context.registry, id);\n\n if (mod && !mod.defined) {\n if (parentId && getOwn(needFullExec, parentId)) {\n needFullExec[id] = depMap;\n }\n\n } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) ||\n (parentId && getOwn(needFullExec, parentId) &&\n falseProp(fullExec, id))) {\n context.require.undef(id);\n }\n\n return oldEnable.apply(context, arguments);\n };\n\n //Override load so that the file paths can be collected.\n context.load = function (moduleName, url) {\n /*jslint evil: true */\n var contents, pluginBuilderMatch, builderName,\n shim, shimExports;\n\n //Do not mark the url as fetched if it is\n //not an empty: URL, used by the optimizer.\n //In that case we need to be sure to call\n //load() for each module that is mapped to\n //empty: so that dependencies are satisfied\n //correctly.\n if (url.indexOf('empty:') === 0) {\n delete context.urlFetched[url];\n }\n\n //Only handle urls that can be inlined, so that means avoiding some\n //URLs like ones that require network access or may be too dynamic,\n //like JSONP\n if (require._isSupportedBuildUrl(url)) {\n //Adjust the URL if it was not transformed to use baseUrl.\n url = normalizeUrlWithBase(context, moduleName, url);\n\n //Save the module name to path and path to module name mappings.\n layer.buildPathMap[moduleName] = url;\n layer.buildFileToModule[url] = moduleName;\n\n if (hasProp(context.plugins, moduleName)) {\n //plugins need to have their source evaled as-is.\n context.needFullExec[moduleName] = true;\n }\n\n prim().start(function () {\n if (hasProp(require._cachedFileContents, url) &&\n (falseProp(context.needFullExec, moduleName) ||\n getOwn(context.fullExec, moduleName))) {\n contents = require._cachedFileContents[url];\n\n //If it defines require, mark it so it can be hoisted.\n //Done here and in the else below, before the\n //else block removes code from the contents.\n //Related to #263\n if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) {\n layer.existingRequireUrl = url;\n }\n } else {\n //Load the file contents, process for conditionals, then\n //evaluate it.\n return require._cacheReadAsync(url).then(function (text) {\n contents = text;\n\n if (context.config.cjsTranslate &&\n (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) {\n contents = commonJs.convert(url, contents);\n }\n\n //If there is a read filter, run it now.\n if (context.config.onBuildRead) {\n contents = context.config.onBuildRead(moduleName, url, contents);\n }\n\n contents = pragma.process(url, contents, context.config, 'OnExecute');\n\n //Find out if the file contains a require() definition. Need to know\n //this so we can inject plugins right after it, but before they are needed,\n //and to make sure this file is first, so that define calls work.\n try {\n if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) {\n layer.existingRequireUrl = url;\n require._cachedDefinesRequireUrls[url] = true;\n }\n } catch (e1) {\n throw new Error('Parse error using esprima ' +\n 'for file: ' + url + '\\n' + e1);\n }\n }).then(function () {\n if (hasProp(context.plugins, moduleName)) {\n //This is a loader plugin, check to see if it has a build extension,\n //otherwise the plugin will act as the plugin builder too.\n pluginBuilderMatch = pluginBuilderRegExp.exec(contents);\n if (pluginBuilderMatch) {\n //Load the plugin builder for the plugin contents.\n builderName = context.makeModuleMap(pluginBuilderMatch[3],\n context.makeModuleMap(moduleName),\n null,\n true).id;\n return require._cacheReadAsync(context.nameToUrl(builderName));\n }\n }\n return contents;\n }).then(function (text) {\n contents = text;\n\n //Parse out the require and define calls.\n //Do this even for plugins in case they have their own\n //dependencies that may be separate to how the pluginBuilder works.\n try {\n if (falseProp(context.needFullExec, moduleName)) {\n contents = parse(moduleName, url, contents, {\n insertNeedsDefine: true,\n has: context.config.has,\n findNestedDependencies: context.config.findNestedDependencies\n });\n }\n } catch (e2) {\n throw new Error('Parse error using esprima ' +\n 'for file: ' + url + '\\n' + e2);\n }\n\n require._cachedFileContents[url] = contents;\n });\n }\n }).then(function () {\n if (contents) {\n eval(contents);\n }\n\n try {\n //If have a string shim config, and this is\n //a fully executed module, try to see if\n //it created a variable in this eval scope\n if (getOwn(context.needFullExec, moduleName)) {\n shim = getOwn(context.config.shim, moduleName);\n if (shim && shim.exports) {\n shimExports = eval(shim.exports);\n if (typeof shimExports !== 'undefined') {\n context.buildShimExports[moduleName] = shimExports;\n }\n }\n }\n\n //Need to close out completion of this module\n //so that listeners will get notified that it is available.\n context.completeLoad(moduleName);\n } catch (e) {\n //Track which module could not complete loading.\n if (!e.moduleTree) {\n e.moduleTree = [];\n }\n e.moduleTree.push(moduleName);\n throw e;\n }\n }).then(null, function (eOuter) {\n\n if (!eOuter.fileName) {\n eOuter.fileName = url;\n }\n throw eOuter;\n }).end();\n } else {\n //With unsupported URLs still need to call completeLoad to\n //finish loading.\n context.completeLoad(moduleName);\n }\n };\n\n //Marks module has having a name, and optionally executes the\n //callback, but only if it meets certain criteria.\n context.execCb = function (name, cb, args, exports) {\n var buildShimExports = getOwn(layer.context.buildShimExports, name);\n\n if (buildShimExports) {\n return buildShimExports;\n } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) {\n return cb.apply(exports, args);\n }\n return undefined;\n };\n\n moduleProto.init = function (depMaps) {\n if (context.needFullExec[this.map.id]) {\n lang.each(depMaps, lang.bind(this, function (depMap) {\n if (typeof depMap === 'string') {\n depMap = context.makeModuleMap(depMap,\n (this.map.isDefine ? this.map : this.map.parentMap));\n }\n\n if (!context.fullExec[depMap.id]) {\n context.require.undef(depMap.id);\n }\n }));\n }\n\n return oldInit.apply(this, arguments);\n };\n\n moduleProto.callPlugin = function () {\n var map = this.map,\n pluginMap = context.makeModuleMap(map.prefix),\n pluginId = pluginMap.id,\n pluginMod = getOwn(context.registry, pluginId);\n\n context.plugins[pluginId] = true;\n context.needFullExec[pluginId] = map;\n\n //If the module is not waiting to finish being defined,\n //undef it and start over, to get full execution.\n if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) {\n context.require.undef(pluginMap.id);\n }\n\n return oldCallPlugin.apply(this, arguments);\n };\n }\n\n return context;\n };\n\n //Clear up the existing context so that the newContext modifications\n //above will be active.\n delete require.s.contexts._;\n\n /** Reset state for each build layer pass. */\n require._buildReset = function () {\n var oldContext = require.s.contexts._;\n\n //Clear up the existing context.\n delete require.s.contexts._;\n\n //Set up new context, so the layer object can hold onto it.\n require({});\n\n layer = require._layer = {\n buildPathMap: {},\n buildFileToModule: {},\n buildFilePaths: [],\n pathAdded: {},\n modulesWithNames: {},\n needsDefine: {},\n existingRequireUrl: \"\",\n ignoredUrls: {},\n context: require.s.contexts._\n };\n\n //Return the previous context in case it is needed, like for\n //the basic config object.\n return oldContext;\n };\n\n require._buildReset();\n\n //Override define() to catch modules that just define an object, so that\n //a dummy define call is not put in the build file for them. They do\n //not end up getting defined via context.execCb, so we need to catch them\n //at the define call.\n oldDef = define;\n\n //This function signature does not have to be exact, just match what we\n //are looking for.\n define = function (name) {\n if (typeof name === \"string\" && falseProp(layer.needsDefine, name)) {\n layer.modulesWithNames[name] = true;\n }\n return oldDef.apply(require, arguments);\n };\n\n define.amd = oldDef.amd;\n\n //Add some utilities for plugins\n require._readFile = file.readFile;\n require._fileExists = function (path) {\n return file.exists(path);\n };\n\n //Called when execManager runs for a dependency. Used to figure out\n //what order of execution.\n require.onResourceLoad = function (context, map) {\n var id = map.id,\n url;\n\n // Fix up any maps that need to be normalized as part of the fullExec\n // plumbing for plugins to participate in the build.\n if (context.plugins && lang.hasProp(context.plugins, id)) {\n lang.eachProp(context.needFullExec, function(value, prop) {\n // For plugin entries themselves, they do not have a map\n // value in needFullExec, just a \"true\" entry.\n if (value !== true && value.prefix === id && value.unnormalized) {\n var map = context.makeModuleMap(value.originalName, value.parentMap);\n context.needFullExec[map.id] = map;\n }\n });\n }\n\n //If build needed a full execution, indicate it\n //has been done now. But only do it if the context is tracking\n //that. Only valid for the context used in a build, not for\n //other contexts being run, like for useLib, plain requirejs\n //use in node/rhino.\n if (context.needFullExec && getOwn(context.needFullExec, id)) {\n context.fullExec[id] = map;\n }\n\n //A plugin.\n if (map.prefix) {\n if (falseProp(layer.pathAdded, id)) {\n layer.buildFilePaths.push(id);\n //For plugins the real path is not knowable, use the name\n //for both module to file and file to module mappings.\n layer.buildPathMap[id] = id;\n layer.buildFileToModule[id] = id;\n layer.modulesWithNames[id] = true;\n layer.pathAdded[id] = true;\n }\n } else if (map.url && require._isSupportedBuildUrl(map.url)) {\n //If the url has not been added to the layer yet, and it\n //is from an actual file that was loaded, add it now.\n url = normalizeUrlWithBase(context, id, map.url);\n if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) {\n //Remember the list of dependencies for this layer.\n layer.buildFilePaths.push(url);\n layer.pathAdded[url] = true;\n }\n }\n };\n\n //Called by output of the parse() function, when a file does not\n //explicitly call define, probably just require, but the parse()\n //function normalizes on define() for dependency mapping and file\n //ordering works correctly.\n require.needsDefine = function (moduleName) {\n layer.needsDefine[moduleName] = true;\n };\n };\n});\n/**\n * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint */\n/*global define: false, console: false */\n\ndefine('commonJs', ['env!env/file', 'parse'], function (file, parse) {\n 'use strict';\n var commonJs = {\n //Set to false if you do not want this file to log. Useful in environments\n //like node where you want the work to happen without noise.\n useLog: true,\n\n convertDir: function (commonJsPath, savePath) {\n var fileList, i,\n jsFileRegExp = /\\.js$/,\n fileName, convertedFileName, fileContents;\n\n //Get list of files to convert.\n fileList = file.getFilteredFileList(commonJsPath, /\\w/, true);\n\n //Normalize on front slashes and make sure the paths do not end in a slash.\n commonJsPath = commonJsPath.replace(/\\\\/g, \"/\");\n savePath = savePath.replace(/\\\\/g, \"/\");\n if (commonJsPath.charAt(commonJsPath.length - 1) === \"/\") {\n commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1);\n }\n if (savePath.charAt(savePath.length - 1) === \"/\") {\n savePath = savePath.substring(0, savePath.length - 1);\n }\n\n //Cycle through all the JS files and convert them.\n if (!fileList || !fileList.length) {\n if (commonJs.useLog) {\n if (commonJsPath === \"convert\") {\n //A request just to convert one file.\n console.log('\\n\\n' + commonJs.convert(savePath, file.readFile(savePath)));\n } else {\n console.log(\"No files to convert in directory: \" + commonJsPath);\n }\n }\n } else {\n for (i = 0; i < fileList.length; i++) {\n fileName = fileList[i];\n convertedFileName = fileName.replace(commonJsPath, savePath);\n\n //Handle JS files.\n if (jsFileRegExp.test(fileName)) {\n fileContents = file.readFile(fileName);\n fileContents = commonJs.convert(fileName, fileContents);\n file.saveUtf8File(convertedFileName, fileContents);\n } else {\n //Just copy the file over.\n file.copyFile(fileName, convertedFileName, true);\n }\n }\n }\n },\n\n /**\n * Does the actual file conversion.\n *\n * @param {String} fileName the name of the file.\n *\n * @param {String} fileContents the contents of a file :)\n *\n * @returns {String} the converted contents\n */\n convert: function (fileName, fileContents) {\n //Strip out comments.\n try {\n var preamble = '',\n commonJsProps = parse.usesCommonJs(fileName, fileContents);\n\n //First see if the module is not already RequireJS-formatted.\n if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) {\n return fileContents;\n }\n\n if (commonJsProps.dirname || commonJsProps.filename) {\n preamble = 'var __filename = module.uri || \"\", ' +\n '__dirname = __filename.substring(0, __filename.lastIndexOf(\"/\") + 1); ';\n }\n\n //Construct the wrapper boilerplate.\n fileContents = 'define(function (require, exports, module) {' +\n preamble +\n fileContents +\n '\\n});\\n';\n\n } catch (e) {\n console.log(\"commonJs.convert: COULD NOT CONVERT: \" + fileName + \", so skipping it. Error was: \" + e);\n return fileContents;\n }\n\n return fileContents;\n }\n };\n\n return commonJs;\n});\n/**\n * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n\n/*jslint plusplus: true, nomen: true, regexp: true */\n/*global define, requirejs, java, process, console */\n\n\ndefine('build', function (require) {\n 'use strict';\n\n var build,\n lang = require('lang'),\n prim = require('prim'),\n logger = require('logger'),\n file = require('env!env/file'),\n parse = require('parse'),\n optimize = require('optimize'),\n pragma = require('pragma'),\n transform = require('transform'),\n requirePatch = require('requirePatch'),\n env = require('env'),\n commonJs = require('commonJs'),\n SourceMapGenerator = require('source-map/source-map-generator'),\n hasProp = lang.hasProp,\n getOwn = lang.getOwn,\n falseProp = lang.falseProp,\n endsWithSemiColonRegExp = /;\\s*$/,\n endsWithSlashRegExp = /[\\/\\\\]$/,\n resourceIsModuleIdRegExp = /^[\\w\\/\\\\\\.]+$/;\n\n prim.nextTick = function (fn) {\n fn();\n };\n\n //Now map require to the outermost requirejs, now that we have\n //local dependencies for this module. The rest of the require use is\n //manipulating the requirejs loader.\n require = requirejs;\n\n //Caching function for performance. Attached to\n //require so it can be reused in requirePatch.js. _cachedRawText\n //set up by requirePatch.js\n require._cacheReadAsync = function (path, encoding) {\n var d;\n\n if (lang.hasProp(require._cachedRawText, path)) {\n d = prim();\n d.resolve(require._cachedRawText[path]);\n return d.promise;\n } else {\n return file.readFileAsync(path, encoding).then(function (text) {\n require._cachedRawText[path] = text;\n return text;\n });\n }\n };\n\n function makeBuildBaseConfig() {\n return {\n appDir: \"\",\n pragmas: {},\n paths: {},\n optimize: \"uglify\",\n optimizeCss: \"standard.keepLines.keepWhitespace\",\n inlineText: true,\n isBuild: true,\n optimizeAllPluginResources: false,\n findNestedDependencies: false,\n preserveLicenseComments: true,\n //By default, all files/directories are copied, unless\n //they match this regexp, by default just excludes .folders\n dirExclusionRegExp: file.dirExclusionRegExp,\n _buildPathToModuleIndex: {}\n };\n }\n\n /**\n * Some JS may not be valid if concatenated with other JS, in particular\n * the style of omitting semicolons and rely on ASI. Add a semicolon in\n * those cases.\n */\n function addSemiColon(text, config) {\n if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) {\n return text;\n } else {\n return text + \";\";\n }\n }\n\n function endsWithSlash(dirName) {\n if (dirName.charAt(dirName.length - 1) !== \"/\") {\n dirName += \"/\";\n }\n return dirName;\n }\n\n //Method used by plugin writeFile calls, defined up here to avoid\n //jslint warning about \"making a function in a loop\".\n function makeWriteFile(namespace, layer) {\n function writeFile(name, contents) {\n logger.trace('Saving plugin-optimized file: ' + name);\n file.saveUtf8File(name, contents);\n }\n\n writeFile.asModule = function (moduleName, fileName, contents) {\n writeFile(fileName,\n build.toTransport(namespace, moduleName, fileName, contents, layer));\n };\n\n return writeFile;\n }\n\n /**\n * Main API entry point into the build. The args argument can either be\n * an array of arguments (like the onese passed on a command-line),\n * or it can be a JavaScript object that has the format of a build profile\n * file.\n *\n * If it is an object, then in addition to the normal properties allowed in\n * a build profile file, the object should contain one other property:\n *\n * The object could also contain a \"buildFile\" property, which is a string\n * that is the file path to a build profile that contains the rest\n * of the build profile directives.\n *\n * This function does not return a status, it should throw an error if\n * there is a problem completing the build.\n */\n build = function (args) {\n var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree,\n i, j, errorMod,\n stackRegExp = /( {4}at[^\\n]+)\\n/,\n standardIndent = ' ';\n\n return prim().start(function () {\n if (!args || lang.isArray(args)) {\n if (!args || args.length < 1) {\n logger.error(\"build.js buildProfile.js\\n\" +\n \"where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file).\");\n return undefined;\n }\n\n //Next args can include a build file path as well as other build args.\n //build file path comes first. If it does not contain an = then it is\n //a build file path. Otherwise, just all build args.\n if (args[0].indexOf(\"=\") === -1) {\n buildFile = args[0];\n args.splice(0, 1);\n }\n\n //Remaining args are options to the build\n cmdConfig = build.convertArrayToObject(args);\n cmdConfig.buildFile = buildFile;\n } else {\n cmdConfig = args;\n }\n\n return build._run(cmdConfig);\n }).then(null, function (e) {\n var err;\n\n errorMsg = e.toString();\n errorTree = e.moduleTree;\n stackMatch = stackRegExp.exec(errorMsg);\n\n if (stackMatch) {\n errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1);\n }\n\n //If a module tree that shows what module triggered the error,\n //print it out.\n if (errorTree && errorTree.length > 0) {\n errorMsg += '\\nIn module tree:\\n';\n\n for (i = errorTree.length - 1; i > -1; i--) {\n errorMod = errorTree[i];\n if (errorMod) {\n for (j = errorTree.length - i; j > -1; j--) {\n errorMsg += standardIndent;\n }\n errorMsg += errorMod + '\\n';\n }\n }\n\n logger.error(errorMsg);\n }\n\n errorStack = e.stack;\n\n if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) {\n errorMsg += '\\n' + errorStack;\n } else {\n if (!stackMatch && errorStack) {\n //Just trim out the first \"at\" in the stack.\n stackMatch = stackRegExp.exec(errorStack);\n if (stackMatch) {\n errorMsg += '\\n' + stackMatch[0] || '';\n }\n }\n }\n\n err = new Error(errorMsg);\n err.originalError = e;\n throw err;\n });\n };\n\n build._run = function (cmdConfig) {\n var buildPaths, fileName, fileNames,\n paths, i,\n baseConfig, config,\n modules, srcPath, buildContext,\n destPath, moduleMap, parentModuleMap, context,\n resources, resource, plugin, fileContents,\n pluginProcessed = {},\n buildFileContents = \"\",\n pluginCollector = {};\n\n return prim().start(function () {\n var prop;\n\n //Can now run the patches to require.js to allow it to be used for\n //build generation. Do it here instead of at the top of the module\n //because we want normal require behavior to load the build tool\n //then want to switch to build mode.\n requirePatch();\n\n config = build.createConfig(cmdConfig);\n paths = config.paths;\n\n //Remove the previous build dir, in case it contains source transforms,\n //like the ones done with onBuildRead and onBuildWrite.\n if (config.dir && !config.keepBuildDir && file.exists(config.dir)) {\n file.deleteFile(config.dir);\n }\n\n if (!config.out && !config.cssIn) {\n //This is not just a one-off file build but a full build profile, with\n //lots of files to process.\n\n //First copy all the baseUrl content\n file.copyDir((config.appDir || config.baseUrl), config.dir, /\\w/, true);\n\n //Adjust baseUrl if config.appDir is in play, and set up build output paths.\n buildPaths = {};\n if (config.appDir) {\n //All the paths should be inside the appDir, so just adjust\n //the paths to use the dirBaseUrl\n for (prop in paths) {\n if (hasProp(paths, prop)) {\n buildPaths[prop] = paths[prop].replace(config.appDir, config.dir);\n }\n }\n } else {\n //If no appDir, then make sure to copy the other paths to this directory.\n for (prop in paths) {\n if (hasProp(paths, prop)) {\n //Set up build path for each path prefix, but only do so\n //if the path falls out of the current baseUrl\n if (paths[prop].indexOf(config.baseUrl) === 0) {\n buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl);\n } else {\n buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop.replace(/\\./g, \"/\");\n\n //Make sure source path is fully formed with baseUrl,\n //if it is a relative URL.\n srcPath = paths[prop];\n if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) {\n srcPath = config.baseUrl + srcPath;\n }\n\n destPath = config.dirBaseUrl + buildPaths[prop];\n\n //Skip empty: paths\n if (srcPath !== 'empty:') {\n //If the srcPath is a directory, copy the whole directory.\n if (file.exists(srcPath) && file.isDirectory(srcPath)) {\n //Copy files to build area. Copy all files (the /\\w/ regexp)\n file.copyDir(srcPath, destPath, /\\w/, true);\n } else {\n //Try a .js extension\n srcPath += '.js';\n destPath += '.js';\n file.copyFile(srcPath, destPath);\n }\n }\n }\n }\n }\n }\n }\n\n //Figure out source file location for each module layer. Do this by seeding require\n //with source area configuration. This is needed so that later the module layers\n //can be manually copied over to the source area, since the build may be\n //require multiple times and the above copyDir call only copies newer files.\n require({\n baseUrl: config.baseUrl,\n paths: paths,\n packagePaths: config.packagePaths,\n packages: config.packages\n });\n buildContext = require.s.contexts._;\n modules = config.modules;\n\n if (modules) {\n modules.forEach(function (module) {\n if (module.name) {\n module._sourcePath = buildContext.nameToUrl(module.name);\n //If the module does not exist, and this is not a \"new\" module layer,\n //as indicated by a true \"create\" property on the module, and\n //it is not a plugin-loaded resource, and there is no\n //'rawText' containing the module's source then throw an error.\n if (!file.exists(module._sourcePath) && !module.create &&\n module.name.indexOf('!') === -1 &&\n (!config.rawText || !lang.hasProp(config.rawText, module.name))) {\n throw new Error(\"ERROR: module path does not exist: \" +\n module._sourcePath + \" for module named: \" + module.name +\n \". Path is relative to: \" + file.absPath('.'));\n }\n }\n });\n }\n\n if (config.out) {\n //Just set up the _buildPath for the module layer.\n require(config);\n if (!config.cssIn) {\n config.modules[0]._buildPath = typeof config.out === 'function' ?\n 'FUNCTION' : config.out;\n }\n } else if (!config.cssIn) {\n //Now set up the config for require to use the build area, and calculate the\n //build file locations. Pass along any config info too.\n baseConfig = {\n baseUrl: config.dirBaseUrl,\n paths: buildPaths\n };\n\n lang.mixin(baseConfig, config);\n require(baseConfig);\n\n if (modules) {\n modules.forEach(function (module) {\n if (module.name) {\n module._buildPath = buildContext.nameToUrl(module.name, null);\n\n //If buildPath and sourcePath are the same, throw since this\n //would result in modifying source. This condition can happen\n //with some more tricky paths: config and appDir/baseUrl\n //setting, which is a sign of incorrect config.\n if (module._buildPath === module._sourcePath) {\n throw new Error('Module ID \\'' + module.name +\n '\\' has a source path that is same as output path: ' +\n module._sourcePath +\n '. Stopping, config is malformed.');\n }\n\n if (!module.create) {\n file.copyFile(module._sourcePath, module._buildPath);\n }\n }\n });\n }\n }\n\n //Run CSS optimizations before doing JS module tracing, to allow\n //things like text loader plugins loading CSS to get the optimized\n //CSS.\n if (config.optimizeCss && config.optimizeCss !== \"none\" && config.dir) {\n buildFileContents += optimize.css(config.dir, config);\n }\n }).then(function() {\n baseConfig = lang.deeplikeCopy(require.s.contexts._.config);\n }).then(function () {\n var actions = [];\n\n if (modules) {\n actions = modules.map(function (module, i) {\n return function () {\n //Save off buildPath to module index in a hash for quicker\n //lookup later.\n config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i;\n\n //Call require to calculate dependencies.\n return build.traceDependencies(module, config, baseConfig)\n .then(function (layer) {\n module.layer = layer;\n });\n };\n });\n\n return prim.serial(actions);\n }\n }).then(function () {\n var actions;\n\n if (modules) {\n //Now build up shadow layers for anything that should be excluded.\n //Do this after tracing dependencies for each module, in case one\n //of those modules end up being one of the excluded values.\n actions = modules.map(function (module) {\n return function () {\n if (module.exclude) {\n module.excludeLayers = [];\n return prim.serial(module.exclude.map(function (exclude, i) {\n return function () {\n //See if it is already in the list of modules.\n //If not trace dependencies for it.\n var found = build.findBuildModule(exclude, modules);\n if (found) {\n module.excludeLayers[i] = found;\n } else {\n return build.traceDependencies({name: exclude}, config, baseConfig)\n .then(function (layer) {\n module.excludeLayers[i] = { layer: layer };\n });\n }\n };\n }));\n }\n };\n });\n\n return prim.serial(actions);\n }\n }).then(function () {\n if (modules) {\n return prim.serial(modules.map(function (module) {\n return function () {\n if (module.exclude) {\n //module.exclude is an array of module names. For each one,\n //get the nested dependencies for it via a matching entry\n //in the module.excludeLayers array.\n module.exclude.forEach(function (excludeModule, i) {\n var excludeLayer = module.excludeLayers[i].layer,\n map = excludeLayer.buildFileToModule;\n excludeLayer.buildFilePaths.forEach(function(filePath){\n build.removeModulePath(map[filePath], filePath, module.layer);\n });\n });\n }\n if (module.excludeShallow) {\n //module.excludeShallow is an array of module names.\n //shallow exclusions are just that module itself, and not\n //its nested dependencies.\n module.excludeShallow.forEach(function (excludeShallowModule) {\n var path = getOwn(module.layer.buildPathMap, excludeShallowModule);\n if (path) {\n build.removeModulePath(excludeShallowModule, path, module.layer);\n }\n });\n }\n\n //Flatten them and collect the build output for each module.\n return build.flattenModule(module, module.layer, config).then(function (builtModule) {\n var finalText, baseName;\n //Save it to a temp file for now, in case there are other layers that\n //contain optimized content that should not be included in later\n //layer optimizations. See issue #56.\n if (module._buildPath === 'FUNCTION') {\n module._buildText = builtModule.text;\n module._buildSourceMap = builtModule.sourceMap;\n } else {\n finalText = builtModule.text;\n if (builtModule.sourceMap) {\n baseName = module._buildPath.split('/');\n baseName = baseName.pop();\n finalText += '\\n//# sourceMappingURL=' + baseName + '.map';\n file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap);\n }\n file.saveUtf8File(module._buildPath + '-temp', finalText);\n\n }\n buildFileContents += builtModule.buildText;\n });\n };\n }));\n }\n }).then(function () {\n var moduleName, outOrigSourceMap;\n if (modules) {\n //Now move the build layers to their final position.\n modules.forEach(function (module) {\n var finalPath = module._buildPath;\n if (finalPath !== 'FUNCTION') {\n if (file.exists(finalPath)) {\n file.deleteFile(finalPath);\n }\n file.renameFile(finalPath + '-temp', finalPath);\n\n //And finally, if removeCombined is specified, remove\n //any of the files that were used in this layer.\n //Be sure not to remove other build layers.\n if (config.removeCombined && !config.out) {\n module.layer.buildFilePaths.forEach(function (path) {\n var isLayer = modules.some(function (mod) {\n return mod._buildPath === path;\n }),\n relPath = build.makeRelativeFilePath(config.dir, path);\n\n if (file.exists(path) &&\n // not a build layer target\n !isLayer &&\n // not outside the build directory\n relPath.indexOf('..') !== 0) {\n file.deleteFile(path);\n }\n });\n }\n }\n\n //Signal layer is done\n if (config.onModuleBundleComplete) {\n config.onModuleBundleComplete(module.onCompleteData);\n }\n });\n }\n\n //If removeCombined in play, remove any empty directories that\n //may now exist because of its use\n if (config.removeCombined && !config.out && config.dir) {\n file.deleteEmptyDirs(config.dir);\n }\n\n //Do other optimizations.\n if (config.out && !config.cssIn) {\n //Just need to worry about one JS file.\n fileName = config.modules[0]._buildPath;\n if (fileName === 'FUNCTION') {\n outOrigSourceMap = config.modules[0]._buildSourceMap;\n config._buildSourceMap = outOrigSourceMap;\n config.modules[0]._buildText = optimize.js((config.modules[0].name ||\n config.modules[0].include[0] ||\n fileName) + '.build.js',\n config.modules[0]._buildText,\n null,\n config);\n if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) {\n config.modules[0]._buildSourceMap = config._buildSourceMap;\n config._buildSourceMap = null;\n }\n } else {\n optimize.jsFile(fileName, null, fileName, config);\n }\n } else if (!config.cssIn) {\n //Normal optimizations across modules.\n\n //JS optimizations.\n fileNames = file.getFilteredFileList(config.dir, /\\.js$/, true);\n fileNames.forEach(function (fileName) {\n var cfg, override, moduleIndex;\n\n //Generate the module name from the config.dir root.\n moduleName = fileName.replace(config.dir, '');\n //Get rid of the extension\n moduleName = moduleName.substring(0, moduleName.length - 3);\n\n //If there is an override for a specific layer build module,\n //and this file is that module, mix in the override for use\n //by optimize.jsFile.\n moduleIndex = getOwn(config._buildPathToModuleIndex, fileName);\n //Normalize, since getOwn could have returned undefined\n moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1;\n\n //Try to avoid extra work if the other files do not need to\n //be read. Build layers should be processed at the very\n //least for optimization.\n if (moduleIndex > -1 || !config.skipDirOptimize ||\n config.normalizeDirDefines === \"all\" ||\n config.cjsTranslate) {\n //Convert the file to transport format, but without a name\n //inserted (by passing null for moduleName) since the files are\n //standalone, one module per file.\n fileContents = file.readFile(fileName);\n\n\n //For builds, if wanting cjs translation, do it now, so that\n //the individual modules can be loaded cross domain via\n //plain script tags.\n if (config.cjsTranslate &&\n (!config.shim || !lang.hasProp(config.shim, moduleName))) {\n fileContents = commonJs.convert(fileName, fileContents);\n }\n\n if (moduleIndex === -1) {\n if (config.onBuildRead) {\n fileContents = config.onBuildRead(moduleName,\n fileName,\n fileContents);\n }\n\n //Only do transport normalization if this is not a build\n //layer (since it was already normalized) and if\n //normalizeDirDefines indicated all should be done.\n if (config.normalizeDirDefines === \"all\") {\n fileContents = build.toTransport(config.namespace,\n null,\n fileName,\n fileContents);\n }\n\n if (config.onBuildWrite) {\n fileContents = config.onBuildWrite(moduleName,\n fileName,\n fileContents);\n }\n }\n\n override = moduleIndex > -1 ?\n config.modules[moduleIndex].override : null;\n if (override) {\n cfg = build.createOverrideConfig(config, override);\n } else {\n cfg = config;\n }\n\n if (moduleIndex > -1 || !config.skipDirOptimize) {\n optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector);\n }\n }\n });\n\n //Normalize all the plugin resources.\n context = require.s.contexts._;\n\n for (moduleName in pluginCollector) {\n if (hasProp(pluginCollector, moduleName)) {\n parentModuleMap = context.makeModuleMap(moduleName);\n resources = pluginCollector[moduleName];\n for (i = 0; i < resources.length; i++) {\n resource = resources[i];\n moduleMap = context.makeModuleMap(resource, parentModuleMap);\n if (falseProp(context.plugins, moduleMap.prefix)) {\n //Set the value in context.plugins so it\n //will be evaluated as a full plugin.\n context.plugins[moduleMap.prefix] = true;\n\n //Do not bother if the plugin is not available.\n if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) {\n continue;\n }\n\n //Rely on the require in the build environment\n //to be synchronous\n context.require([moduleMap.prefix]);\n\n //Now that the plugin is loaded, redo the moduleMap\n //since the plugin will need to normalize part of the path.\n moduleMap = context.makeModuleMap(resource, parentModuleMap);\n }\n\n //Only bother with plugin resources that can be handled\n //processed by the plugin, via support of the writeFile\n //method.\n if (falseProp(pluginProcessed, moduleMap.id)) {\n //Only do the work if the plugin was really loaded.\n //Using an internal access because the file may\n //not really be loaded.\n plugin = getOwn(context.defined, moduleMap.prefix);\n if (plugin && plugin.writeFile) {\n plugin.writeFile(\n moduleMap.prefix,\n moduleMap.name,\n require,\n makeWriteFile(\n config.namespace\n ),\n context.config\n );\n }\n\n pluginProcessed[moduleMap.id] = true;\n }\n }\n\n }\n }\n\n //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, \" \"));\n\n\n //All module layers are done, write out the build.txt file.\n file.saveUtf8File(config.dir + \"build.txt\", buildFileContents);\n }\n\n //If just have one CSS file to optimize, do that here.\n if (config.cssIn) {\n buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText;\n }\n\n if (typeof config.out === 'function') {\n config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap);\n }\n\n //Print out what was built into which layers.\n if (buildFileContents) {\n logger.info(buildFileContents);\n return buildFileContents;\n }\n\n return '';\n });\n };\n\n /**\n * Converts command line args like \"paths.foo=../some/path\"\n * result.paths = { foo: '../some/path' } where prop = paths,\n * name = paths.foo and value = ../some/path, so it assumes the\n * name=value splitting has already happened.\n */\n function stringDotToObj(result, name, value) {\n var parts = name.split('.');\n\n parts.forEach(function (prop, i) {\n if (i === parts.length - 1) {\n result[prop] = value;\n } else {\n if (falseProp(result, prop)) {\n result[prop] = {};\n }\n result = result[prop];\n }\n\n });\n }\n\n build.objProps = {\n paths: true,\n wrap: true,\n pragmas: true,\n pragmasOnSave: true,\n has: true,\n hasOnSave: true,\n uglify: true,\n uglify2: true,\n closure: true,\n map: true,\n throwWhen: true\n };\n\n build.hasDotPropMatch = function (prop) {\n var dotProp,\n index = prop.indexOf('.');\n\n if (index !== -1) {\n dotProp = prop.substring(0, index);\n return hasProp(build.objProps, dotProp);\n }\n return false;\n };\n\n /**\n * Converts an array that has String members of \"name=value\"\n * into an object, where the properties on the object are the names in the array.\n * Also converts the strings \"true\" and \"false\" to booleans for the values.\n * member name/value pairs, and converts some comma-separated lists into\n * arrays.\n * @param {Array} ary\n */\n build.convertArrayToObject = function (ary) {\n var result = {}, i, separatorIndex, prop, value,\n needArray = {\n \"include\": true,\n \"exclude\": true,\n \"excludeShallow\": true,\n \"insertRequire\": true,\n \"stubModules\": true,\n \"deps\": true,\n \"mainConfigFile\": true\n };\n\n for (i = 0; i < ary.length; i++) {\n separatorIndex = ary[i].indexOf(\"=\");\n if (separatorIndex === -1) {\n throw \"Malformed name/value pair: [\" + ary[i] + \"]. Format should be name=value\";\n }\n\n value = ary[i].substring(separatorIndex + 1, ary[i].length);\n if (value === \"true\") {\n value = true;\n } else if (value === \"false\") {\n value = false;\n }\n\n prop = ary[i].substring(0, separatorIndex);\n\n //Convert to array if necessary\n if (getOwn(needArray, prop)) {\n value = value.split(\",\");\n }\n\n if (build.hasDotPropMatch(prop)) {\n stringDotToObj(result, prop, value);\n } else {\n result[prop] = value;\n }\n }\n return result; //Object\n };\n\n build.makeAbsPath = function (path, absFilePath) {\n if (!absFilePath) {\n return path;\n }\n\n //Add abspath if necessary. If path starts with a slash or has a colon,\n //then already is an abolute path.\n if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) {\n path = absFilePath +\n (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') +\n path;\n path = file.normalize(path);\n }\n return path.replace(lang.backSlashRegExp, '/');\n };\n\n build.makeAbsObject = function (props, obj, absFilePath) {\n var i, prop;\n if (obj) {\n for (i = 0; i < props.length; i++) {\n prop = props[i];\n if (hasProp(obj, prop) && typeof obj[prop] === 'string') {\n obj[prop] = build.makeAbsPath(obj[prop], absFilePath);\n }\n }\n }\n };\n\n /**\n * For any path in a possible config, make it absolute relative\n * to the absFilePath passed in.\n */\n build.makeAbsConfig = function (config, absFilePath) {\n var props, prop, i;\n\n props = [\"appDir\", \"dir\", \"baseUrl\"];\n for (i = 0; i < props.length; i++) {\n prop = props[i];\n\n if (getOwn(config, prop)) {\n //Add abspath if necessary, make sure these paths end in\n //slashes\n if (prop === \"baseUrl\") {\n config.originalBaseUrl = config.baseUrl;\n if (config.appDir) {\n //If baseUrl with an appDir, the baseUrl is relative to\n //the appDir, *not* the absFilePath. appDir and dir are\n //made absolute before baseUrl, so this will work.\n config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir);\n } else {\n //The dir output baseUrl is same as regular baseUrl, both\n //relative to the absFilePath.\n config.baseUrl = build.makeAbsPath(config[prop], absFilePath);\n }\n } else {\n config[prop] = build.makeAbsPath(config[prop], absFilePath);\n }\n\n config[prop] = endsWithSlash(config[prop]);\n }\n }\n\n build.makeAbsObject((config.out === \"stdout\" ? [\"cssIn\"] : [\"out\", \"cssIn\"]),\n config, absFilePath);\n build.makeAbsObject([\"startFile\", \"endFile\"], config.wrap, absFilePath);\n };\n\n /**\n * Creates a relative path to targetPath from refPath.\n * Only deals with file paths, not folders. If folders,\n * make sure paths end in a trailing '/'.\n */\n build.makeRelativeFilePath = function (refPath, targetPath) {\n var i, dotLength, finalParts, length, targetParts, targetName,\n refParts = refPath.split('/'),\n hasEndSlash = endsWithSlashRegExp.test(targetPath),\n dotParts = [];\n\n targetPath = file.normalize(targetPath);\n if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) {\n targetPath += '/';\n }\n targetParts = targetPath.split('/');\n //Pull off file name\n targetName = targetParts.pop();\n\n //Also pop off the ref file name to make the matches against\n //targetParts equivalent.\n refParts.pop();\n\n length = refParts.length;\n\n for (i = 0; i < length; i += 1) {\n if (refParts[i] !== targetParts[i]) {\n break;\n }\n }\n\n //Now i is the index in which they diverge.\n finalParts = targetParts.slice(i);\n\n dotLength = length - i;\n for (i = 0; i > -1 && i < dotLength; i += 1) {\n dotParts.push('..');\n }\n\n return dotParts.join('/') + (dotParts.length ? '/' : '') +\n finalParts.join('/') + (finalParts.length ? '/' : '') +\n targetName;\n };\n\n build.nestedMix = {\n paths: true,\n has: true,\n hasOnSave: true,\n pragmas: true,\n pragmasOnSave: true\n };\n\n /**\n * Mixes additional source config into target config, and merges some\n * nested config, like paths, correctly.\n */\n function mixConfig(target, source, skipArrays) {\n var prop, value, isArray, targetValue;\n\n for (prop in source) {\n if (hasProp(source, prop)) {\n //If the value of the property is a plain object, then\n //allow a one-level-deep mixing of it.\n value = source[prop];\n isArray = lang.isArray(value);\n if (typeof value === 'object' && value &&\n !isArray && !lang.isFunction(value) &&\n !lang.isRegExp(value)) {\n\n // TODO: need to generalize this work, maybe also reuse\n // the work done in requirejs configure, perhaps move to\n // just a deep copy/merge overall. However, given the\n // amount of observable change, wait for a dot release.\n // This change is in relation to #645\n if (prop === 'map') {\n if (!target.map) {\n target.map = {};\n }\n lang.deepMix(target.map, source.map);\n } else {\n target[prop] = lang.mixin({}, target[prop], value, true);\n }\n } else if (isArray) {\n if (!skipArrays) {\n // Some config, like packages, are arrays. For those,\n // just merge the results.\n targetValue = target[prop];\n if (lang.isArray(targetValue)) {\n target[prop] = targetValue.concat(value);\n } else {\n target[prop] = value;\n }\n }\n } else {\n target[prop] = value;\n }\n }\n }\n\n //Set up log level since it can affect if errors are thrown\n //or caught and passed to errbacks while doing config setup.\n if (lang.hasProp(target, 'logLevel')) {\n logger.logLevel(target.logLevel);\n }\n }\n\n /**\n * Converts a wrap.startFile or endFile to be start/end as a string.\n * the startFile/endFile values can be arrays.\n */\n function flattenWrapFile(wrap, keyName, absFilePath) {\n var keyFileName = keyName + 'File';\n\n if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) {\n wrap[keyName] = '';\n if (typeof wrap[keyFileName] === 'string') {\n wrap[keyFileName] = [wrap[keyFileName]];\n }\n wrap[keyFileName].forEach(function (fileName) {\n wrap[keyName] += (wrap[keyName] ? '\\n' : '') +\n file.readFile(build.makeAbsPath(fileName, absFilePath));\n });\n } else if (wrap[keyName] === null || wrap[keyName] === undefined) {\n //Allow missing one, just set to empty string.\n wrap[keyName] = '';\n } else if (typeof wrap[keyName] !== 'string') {\n throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed');\n }\n }\n\n function normalizeWrapConfig(config, absFilePath) {\n //Get any wrap text.\n try {\n if (config.wrap) {\n if (config.wrap === true) {\n //Use default values.\n config.wrap = {\n start: '(function () {',\n end: '}());'\n };\n } else {\n flattenWrapFile(config.wrap, 'start', absFilePath);\n flattenWrapFile(config.wrap, 'end', absFilePath);\n }\n }\n } catch (wrapError) {\n throw new Error('Malformed wrap config: ' + wrapError.toString());\n }\n }\n\n /**\n * Creates a config object for an optimization build.\n * It will also read the build profile if it is available, to create\n * the configuration.\n *\n * @param {Object} cfg config options that take priority\n * over defaults and ones in the build file. These options could\n * be from a command line, for instance.\n *\n * @param {Object} the created config object.\n */\n build.createConfig = function (cfg) {\n /*jslint evil: true */\n var buildFileContents, buildFileConfig, mainConfig,\n mainConfigFile, mainConfigPath, buildFile, absFilePath,\n config = {},\n buildBaseConfig = makeBuildBaseConfig();\n\n //Make sure all paths are relative to current directory.\n absFilePath = file.absPath('.');\n build.makeAbsConfig(cfg, absFilePath);\n build.makeAbsConfig(buildBaseConfig, absFilePath);\n\n lang.mixin(config, buildBaseConfig);\n lang.mixin(config, cfg, true);\n\n //Set up log level early since it can affect if errors are thrown\n //or caught and passed to errbacks, even while constructing config.\n if (lang.hasProp(config, 'logLevel')) {\n logger.logLevel(config.logLevel);\n }\n\n if (config.buildFile) {\n //A build file exists, load it to get more config.\n buildFile = file.absPath(config.buildFile);\n\n //Find the build file, and make sure it exists, if this is a build\n //that has a build profile, and not just command line args with an in=path\n if (!file.exists(buildFile)) {\n throw new Error(\"ERROR: build file does not exist: \" + buildFile);\n }\n\n absFilePath = config.baseUrl = file.absPath(file.parent(buildFile));\n\n //Load build file options.\n buildFileContents = file.readFile(buildFile);\n try {\n buildFileConfig = eval(\"(\" + buildFileContents + \")\");\n build.makeAbsConfig(buildFileConfig, absFilePath);\n\n //Mix in the config now so that items in mainConfigFile can\n //be resolved relative to them if necessary, like if appDir\n //is set here, but the baseUrl is in mainConfigFile. Will\n //re-mix in the same build config later after mainConfigFile\n //is processed, since build config should take priority.\n mixConfig(config, buildFileConfig);\n } catch (e) {\n throw new Error(\"Build file \" + buildFile + \" is malformed: \" + e);\n }\n }\n\n mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile);\n if (mainConfigFile) {\n if (typeof mainConfigFile === 'string') {\n mainConfigFile = [mainConfigFile];\n }\n\n mainConfigFile.forEach(function (configFile) {\n configFile = build.makeAbsPath(configFile, absFilePath);\n if (!file.exists(configFile)) {\n throw new Error(configFile + ' does not exist.');\n }\n try {\n mainConfig = parse.findConfig(file.readFile(configFile)).config;\n } catch (configError) {\n throw new Error('The config in mainConfigFile ' +\n configFile +\n ' cannot be used because it cannot be evaluated' +\n ' correctly while running in the optimizer. Try only' +\n ' using a config that is also valid JSON, or do not use' +\n ' mainConfigFile and instead copy the config values needed' +\n ' into a build file or command line arguments given to the optimizer.\\n' +\n 'Source error from parsing: ' + configFile + ': ' + configError);\n }\n if (mainConfig) {\n mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/'));\n\n //Add in some existing config, like appDir, since they can be\n //used inside the configFile -- paths and baseUrl are\n //relative to them.\n if (config.appDir && !mainConfig.appDir) {\n mainConfig.appDir = config.appDir;\n }\n\n //If no baseUrl, then use the directory holding the main config.\n if (!mainConfig.baseUrl) {\n mainConfig.baseUrl = mainConfigPath;\n }\n\n build.makeAbsConfig(mainConfig, mainConfigPath);\n mixConfig(config, mainConfig);\n }\n });\n }\n\n //Mix in build file config, but only after mainConfig has been mixed in.\n //Since this is a re-application, skip array merging.\n if (buildFileConfig) {\n mixConfig(config, buildFileConfig, true);\n }\n\n //Re-apply the override config values. Command line\n //args should take precedence over build file values.\n //Since this is a re-application, skip array merging.\n mixConfig(config, cfg, true);\n\n //Fix paths to full paths so that they can be adjusted consistently\n //lately to be in the output area.\n lang.eachProp(config.paths, function (value, prop) {\n if (lang.isArray(value)) {\n throw new Error('paths fallback not supported in optimizer. ' +\n 'Please provide a build config path override ' +\n 'for ' + prop);\n }\n config.paths[prop] = build.makeAbsPath(value, config.baseUrl);\n });\n\n //Set final output dir\n if (hasProp(config, \"baseUrl\")) {\n if (config.appDir) {\n if (!config.originalBaseUrl) {\n throw new Error('Please set a baseUrl in the build config');\n }\n config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir);\n } else {\n config.dirBaseUrl = config.dir || config.baseUrl;\n }\n //Make sure dirBaseUrl ends in a slash, since it is\n //concatenated with other strings.\n config.dirBaseUrl = endsWithSlash(config.dirBaseUrl);\n }\n\n\n //If out=stdout, write output to STDOUT instead of a file.\n if (config.out && config.out === 'stdout') {\n config.out = function (content) {\n var e = env.get();\n if (e === 'rhino') {\n var out = new java.io.PrintStream(java.lang.System.out, true, 'UTF-8');\n out.println(content);\n } else if (e === 'node') {\n process.stdout.setEncoding('utf8');\n process.stdout.write(content);\n } else {\n console.log(content);\n }\n };\n }\n\n //Check for errors in config\n if (config.main) {\n throw new Error('\"main\" passed as an option, but the ' +\n 'supported option is called \"name\".');\n }\n if (config.out && !config.name && !config.modules && !config.include &&\n !config.cssIn) {\n throw new Error('Missing either a \"name\", \"include\" or \"modules\" ' +\n 'option');\n }\n if (config.cssIn) {\n if (config.dir || config.appDir) {\n throw new Error('cssIn is only for the output of single file ' +\n 'CSS optimizations and is not compatible with \"dir\" or \"appDir\" configuration.');\n }\n if (!config.out) {\n throw new Error('\"out\" option missing.');\n }\n }\n if (!config.cssIn && !config.baseUrl) {\n //Just use the current directory as the baseUrl\n config.baseUrl = './';\n }\n if (!config.out && !config.dir) {\n throw new Error('Missing either an \"out\" or \"dir\" config value. ' +\n 'If using \"appDir\" for a full project optimization, ' +\n 'use \"dir\". If you want to optimize to one file, ' +\n 'use \"out\".');\n }\n if (config.appDir && config.out) {\n throw new Error('\"appDir\" is not compatible with \"out\". Use \"dir\" ' +\n 'instead. appDir is used to copy whole projects, ' +\n 'where \"out\" with \"baseUrl\" is used to just ' +\n 'optimize to one file.');\n }\n if (config.out && config.dir) {\n throw new Error('The \"out\" and \"dir\" options are incompatible.' +\n ' Use \"out\" if you are targeting a single file' +\n ' for optimization, and \"dir\" if you want the appDir' +\n ' or baseUrl directories optimized.');\n }\n\n if (config.dir) {\n // Make sure the output dir is not set to a parent of the\n // source dir or the same dir, as it will result in source\n // code deletion.\n if (!config.allowSourceOverwrites && (config.dir === config.baseUrl ||\n config.dir === config.appDir ||\n (config.baseUrl && build.makeRelativeFilePath(config.dir,\n config.baseUrl).indexOf('..') !== 0) ||\n (config.appDir &&\n build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) {\n throw new Error('\"dir\" is set to a parent or same directory as' +\n ' \"appDir\" or \"baseUrl\". This can result in' +\n ' the deletion of source code. Stopping. If' +\n ' you want to allow possible overwriting of' +\n ' source code, set \"allowSourceOverwrites\"' +\n ' to true in the build config, but do so at' +\n ' your own risk. In that case, you may want' +\n ' to also set \"keepBuildDir\" to true.');\n }\n }\n\n if (config.insertRequire && !lang.isArray(config.insertRequire)) {\n throw new Error('insertRequire should be a list of module IDs' +\n ' to insert in to a require([]) call.');\n }\n\n if (config.generateSourceMaps) {\n if (config.preserveLicenseComments && config.optimize !== 'none') {\n throw new Error('Cannot use preserveLicenseComments and ' +\n 'generateSourceMaps together. Either explcitly set ' +\n 'preserveLicenseComments to false (default is true) or ' +\n 'turn off generateSourceMaps. If you want source maps with ' +\n 'license comments, see: ' +\n 'http://requirejs.org/docs/errors.html#sourcemapcomments');\n } else if (config.optimize !== 'none' &&\n config.optimize !== 'closure' &&\n config.optimize !== 'uglify2') {\n //Allow optimize: none to pass, since it is useful when toggling\n //minification on and off to debug something, and it implicitly\n //works, since it does not need a source map.\n throw new Error('optimize: \"' + config.optimize +\n '\" does not support generateSourceMaps.');\n }\n }\n\n if ((config.name || config.include) && !config.modules) {\n //Just need to build one file, but may be part of a whole appDir/\n //baseUrl copy, but specified on the command line, so cannot do\n //the modules array setup. So create a modules section in that\n //case.\n config.modules = [\n {\n name: config.name,\n out: config.out,\n create: config.create,\n include: config.include,\n exclude: config.exclude,\n excludeShallow: config.excludeShallow,\n insertRequire: config.insertRequire,\n stubModules: config.stubModules\n }\n ];\n delete config.stubModules;\n } else if (config.modules && config.out) {\n throw new Error('If the \"modules\" option is used, then there ' +\n 'should be a \"dir\" option set and \"out\" should ' +\n 'not be used since \"out\" is only for single file ' +\n 'optimization output.');\n } else if (config.modules && config.name) {\n throw new Error('\"name\" and \"modules\" options are incompatible. ' +\n 'Either use \"name\" if doing a single file ' +\n 'optimization, or \"modules\" if you want to target ' +\n 'more than one file for optimization.');\n }\n\n if (config.out && !config.cssIn) {\n //Just one file to optimize.\n\n //Does not have a build file, so set up some defaults.\n //Optimizing CSS should not be allowed, unless explicitly\n //asked for on command line. In that case the only task is\n //to optimize a CSS file.\n if (!cfg.optimizeCss) {\n config.optimizeCss = \"none\";\n }\n }\n\n //Normalize cssPrefix\n if (config.cssPrefix) {\n //Make sure cssPrefix ends in a slash\n config.cssPrefix = endsWithSlash(config.cssPrefix);\n } else {\n config.cssPrefix = '';\n }\n\n //Cycle through modules and normalize\n if (config.modules && config.modules.length) {\n config.modules.forEach(function (mod) {\n\n //Combine any local stubModules with global values.\n if (config.stubModules) {\n mod.stubModules = config.stubModules.concat(mod.stubModules || []);\n }\n\n //Create a hash lookup for the stubModules config to make lookup\n //cheaper later.\n if (mod.stubModules) {\n mod.stubModules._byName = {};\n mod.stubModules.forEach(function (id) {\n mod.stubModules._byName[id] = true;\n });\n }\n\n // Legacy command support, which allowed a single string ID\n // for include.\n if (typeof mod.include === 'string') {\n mod.include = [mod.include];\n }\n\n //Allow wrap config in overrides, but normalize it.\n if (mod.override) {\n normalizeWrapConfig(mod.override, absFilePath);\n }\n });\n }\n\n normalizeWrapConfig(config, absFilePath);\n\n //Do final input verification\n if (config.context) {\n throw new Error('The build argument \"context\" is not supported' +\n ' in a build. It should only be used in web' +\n ' pages.');\n }\n\n //Set up normalizeDirDefines. If not explicitly set, if optimize \"none\",\n //set to \"skip\" otherwise set to \"all\".\n if (!hasProp(config, 'normalizeDirDefines')) {\n if (config.optimize === 'none' || config.skipDirOptimize) {\n config.normalizeDirDefines = 'skip';\n } else {\n config.normalizeDirDefines = 'all';\n }\n }\n\n //Set file.fileExclusionRegExp if desired\n if (hasProp(config, 'fileExclusionRegExp')) {\n if (typeof config.fileExclusionRegExp === \"string\") {\n file.exclusionRegExp = new RegExp(config.fileExclusionRegExp);\n } else {\n file.exclusionRegExp = config.fileExclusionRegExp;\n }\n } else if (hasProp(config, 'dirExclusionRegExp')) {\n //Set file.dirExclusionRegExp if desired, this is the old\n //name for fileExclusionRegExp before 1.0.2. Support for backwards\n //compatibility\n file.exclusionRegExp = config.dirExclusionRegExp;\n }\n\n //Track the deps, but in a different key, so that they are not loaded\n //as part of config seeding before all config is in play (#648). Was\n //going to merge this in with \"include\", but include is added after\n //the \"name\" target. To preserve what r.js has done previously, make\n //sure \"deps\" comes before the \"name\".\n if (config.deps) {\n config._depsInclude = config.deps;\n }\n\n\n //Remove things that may cause problems in the build.\n //deps already merged above\n delete config.deps;\n delete config.jQuery;\n delete config.enforceDefine;\n delete config.urlArgs;\n\n return config;\n };\n\n /**\n * finds the module being built/optimized with the given moduleName,\n * or returns null.\n * @param {String} moduleName\n * @param {Array} modules\n * @returns {Object} the module object from the build profile, or null.\n */\n build.findBuildModule = function (moduleName, modules) {\n var i, module;\n for (i = 0; i < modules.length; i++) {\n module = modules[i];\n if (module.name === moduleName) {\n return module;\n }\n }\n return null;\n };\n\n /**\n * Removes a module name and path from a layer, if it is supposed to be\n * excluded from the layer.\n * @param {String} moduleName the name of the module\n * @param {String} path the file path for the module\n * @param {Object} layer the layer to remove the module/path from\n */\n build.removeModulePath = function (module, path, layer) {\n var index = layer.buildFilePaths.indexOf(path);\n if (index !== -1) {\n layer.buildFilePaths.splice(index, 1);\n }\n };\n\n /**\n * Uses the module build config object to trace the dependencies for the\n * given module.\n *\n * @param {Object} module the module object from the build config info.\n * @param {Object} config the build config object.\n * @param {Object} [baseLoaderConfig] the base loader config to use for env resets.\n *\n * @returns {Object} layer information about what paths and modules should\n * be in the flattened module.\n */\n build.traceDependencies = function (module, config, baseLoaderConfig) {\n var include, override, layer, context, oldContext,\n rawTextByIds,\n syncChecks = {\n rhino: true,\n node: true,\n xpconnect: true\n },\n deferred = prim();\n\n //Reset some state set up in requirePatch.js, and clean up require's\n //current context.\n oldContext = require._buildReset();\n\n //Grab the reset layer and context after the reset, but keep the\n //old config to reuse in the new context.\n layer = require._layer;\n context = layer.context;\n\n //Put back basic config, use a fresh object for it.\n if (baseLoaderConfig) {\n require(lang.deeplikeCopy(baseLoaderConfig));\n }\n\n logger.trace(\"\\nTracing dependencies for: \" + (module.name ||\n (typeof module.out === 'function' ? 'FUNCTION' : module.out)));\n include = config._depsInclude || [];\n include = include.concat(module.name && !module.create ? [module.name] : []);\n if (module.include) {\n include = include.concat(module.include);\n }\n\n //If there are overrides to basic config, set that up now.;\n if (module.override) {\n if (baseLoaderConfig) {\n override = build.createOverrideConfig(baseLoaderConfig, module.override);\n } else {\n override = lang.deeplikeCopy(module.override);\n }\n require(override);\n }\n\n //Now, populate the rawText cache with any values explicitly passed in\n //via config.\n rawTextByIds = require.s.contexts._.config.rawText;\n if (rawTextByIds) {\n lang.eachProp(rawTextByIds, function (contents, id) {\n var url = require.toUrl(id) + '.js';\n require._cachedRawText[url] = contents;\n });\n }\n\n\n //Configure the callbacks to be called.\n deferred.reject.__requireJsBuild = true;\n\n //Use a wrapping function so can check for errors.\n function includeFinished(value) {\n //If a sync build environment, check for errors here, instead of\n //in the then callback below, since some errors, like two IDs pointed\n //to same URL but only one anon ID will leave the loader in an\n //unresolved state since a setTimeout cannot be used to check for\n //timeout.\n var hasError = false;\n if (syncChecks[env.get()]) {\n try {\n build.checkForErrors(context);\n } catch (e) {\n hasError = true;\n deferred.reject(e);\n }\n }\n\n if (!hasError) {\n deferred.resolve(value);\n }\n }\n includeFinished.__requireJsBuild = true;\n\n //Figure out module layer dependencies by calling require to do the work.\n require(include, includeFinished, deferred.reject);\n\n // If a sync env, then with the \"two IDs to same anon module path\"\n // issue, the require never completes, need to check for errors\n // here.\n if (syncChecks[env.get()]) {\n build.checkForErrors(context);\n }\n\n return deferred.promise.then(function () {\n //Reset config\n if (module.override && baseLoaderConfig) {\n require(lang.deeplikeCopy(baseLoaderConfig));\n }\n\n build.checkForErrors(context);\n\n return layer;\n });\n };\n\n build.checkForErrors = function (context) {\n //Check to see if it all loaded. If not, then throw, and give\n //a message on what is left.\n var id, prop, mod, idParts, pluginId, pluginResources,\n errMessage = '',\n failedPluginMap = {},\n failedPluginIds = [],\n errIds = [],\n errUrlMap = {},\n errUrlConflicts = {},\n hasErrUrl = false,\n hasUndefined = false,\n defined = context.defined,\n registry = context.registry;\n\n function populateErrUrlMap(id, errUrl, skipNew) {\n // Loader plugins do not have an errUrl, so skip them.\n if (!errUrl) {\n return;\n }\n\n if (!skipNew) {\n errIds.push(id);\n }\n\n if (errUrlMap[errUrl]) {\n hasErrUrl = true;\n //This error module has the same URL as another\n //error module, could be misconfiguration.\n if (!errUrlConflicts[errUrl]) {\n errUrlConflicts[errUrl] = [];\n //Store the original module that had the same URL.\n errUrlConflicts[errUrl].push(errUrlMap[errUrl]);\n }\n errUrlConflicts[errUrl].push(id);\n } else if (!skipNew) {\n errUrlMap[errUrl] = id;\n }\n }\n\n for (id in registry) {\n if (hasProp(registry, id) && id.indexOf('_@r') !== 0) {\n hasUndefined = true;\n mod = getOwn(registry, id);\n idParts = id.split('!');\n pluginId = idParts[0];\n\n if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) {\n populateErrUrlMap(id, mod.map.url);\n }\n\n //Look for plugins that did not call load()\n\n if (idParts.length > 1) {\n if (falseProp(failedPluginMap, pluginId)) {\n failedPluginIds.push(pluginId);\n }\n pluginResources = failedPluginMap[pluginId];\n if (!pluginResources) {\n pluginResources = failedPluginMap[pluginId] = [];\n }\n pluginResources.push(id + (mod.error ? ': ' + mod.error : ''));\n }\n }\n }\n\n // If have some modules that are not defined/stuck in the registry,\n // then check defined modules for URL overlap.\n if (hasUndefined) {\n for (id in defined) {\n if (hasProp(defined, id) && id.indexOf('!') === -1) {\n populateErrUrlMap(id, require.toUrl(id) + '.js', true);\n }\n }\n }\n\n if (errIds.length || failedPluginIds.length) {\n if (failedPluginIds.length) {\n errMessage += 'Loader plugin' +\n (failedPluginIds.length === 1 ? '' : 's') +\n ' did not call ' +\n 'the load callback in the build:\\n' +\n failedPluginIds.map(function (pluginId) {\n var pluginResources = failedPluginMap[pluginId];\n return pluginId + ':\\n ' + pluginResources.join('\\n ');\n }).join('\\n') + '\\n';\n }\n errMessage += 'Module loading did not complete for: ' + errIds.join(', ');\n\n if (hasErrUrl) {\n errMessage += '\\nThe following modules share the same URL. This ' +\n 'could be a misconfiguration if that URL only has ' +\n 'one anonymous module in it:';\n for (prop in errUrlConflicts) {\n if (hasProp(errUrlConflicts, prop)) {\n errMessage += '\\n' + prop + ': ' +\n errUrlConflicts[prop].join(', ');\n }\n }\n }\n throw new Error(errMessage);\n }\n };\n\n build.createOverrideConfig = function (config, override) {\n var cfg = lang.deeplikeCopy(config),\n oride = lang.deeplikeCopy(override);\n\n lang.eachProp(oride, function (value, prop) {\n if (hasProp(build.objProps, prop)) {\n //An object property, merge keys. Start a new object\n //so that source object in config does not get modified.\n cfg[prop] = {};\n lang.mixin(cfg[prop], config[prop], true);\n lang.mixin(cfg[prop], override[prop], true);\n } else {\n cfg[prop] = override[prop];\n }\n });\n\n return cfg;\n };\n\n /**\n * Uses the module build config object to create an flattened version\n * of the module, with deep dependencies included.\n *\n * @param {Object} module the module object from the build config info.\n *\n * @param {Object} layer the layer object returned from build.traceDependencies.\n *\n * @param {Object} the build config object.\n *\n * @returns {Object} with two properties: \"text\", the text of the flattened\n * module, and \"buildText\", a string of text representing which files were\n * included in the flattened module text.\n */\n build.flattenModule = function (module, layer, config) {\n var fileContents, sourceMapGenerator,\n sourceMapBase,\n buildFileContents = '';\n\n return prim().start(function () {\n var reqIndex, currContents, fileForSourceMap,\n moduleName, shim, packageMain, packageName,\n parts, builder, writeApi,\n namespace, namespaceWithDot, stubModulesByName,\n context = layer.context,\n onLayerEnds = [],\n onLayerEndAdded = {};\n\n //Use override settings, particularly for pragmas\n //Do this before the var readings since it reads config values.\n if (module.override) {\n config = build.createOverrideConfig(config, module.override);\n }\n\n namespace = config.namespace || '';\n namespaceWithDot = namespace ? namespace + '.' : '';\n stubModulesByName = (module.stubModules && module.stubModules._byName) || {};\n\n //Start build output for the module.\n module.onCompleteData = {\n name: module.name,\n path: (config.dir ? module._buildPath.replace(config.dir, \"\") : module._buildPath),\n included: []\n };\n\n buildFileContents += \"\\n\" +\n module.onCompleteData.path +\n \"\\n----------------\\n\";\n\n //If there was an existing file with require in it, hoist to the top.\n if (layer.existingRequireUrl) {\n reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl);\n if (reqIndex !== -1) {\n layer.buildFilePaths.splice(reqIndex, 1);\n layer.buildFilePaths.unshift(layer.existingRequireUrl);\n }\n }\n\n if (config.generateSourceMaps) {\n sourceMapBase = config.dir || config.baseUrl;\n fileForSourceMap = module._buildPath === 'FUNCTION' ?\n (module.name || module.include[0] || 'FUNCTION') + '.build.js' :\n module._buildPath.replace(sourceMapBase, '');\n sourceMapGenerator = new SourceMapGenerator.SourceMapGenerator({\n file: fileForSourceMap\n });\n }\n\n //Write the built module to disk, and build up the build output.\n fileContents = \"\";\n return prim.serial(layer.buildFilePaths.map(function (path) {\n return function () {\n var lineCount,\n singleContents = '';\n\n moduleName = layer.buildFileToModule[path];\n packageName = moduleName.split('/').shift();\n\n //If the moduleName is for a package main, then update it to the\n //real main value.\n packageMain = layer.context.config.pkgs &&\n getOwn(layer.context.config.pkgs, packageName);\n if (packageMain !== moduleName) {\n // Not a match, clear packageMain\n packageMain = undefined;\n }\n\n return prim().start(function () {\n //Figure out if the module is a result of a build plugin, and if so,\n //then delegate to that plugin.\n parts = context.makeModuleMap(moduleName);\n builder = parts.prefix && getOwn(context.defined, parts.prefix);\n if (builder) {\n if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) {\n onLayerEnds.push(builder);\n onLayerEndAdded[parts.prefix] = true;\n }\n\n if (builder.write) {\n writeApi = function (input) {\n singleContents += \"\\n\" + addSemiColon(input, config);\n if (config.onBuildWrite) {\n singleContents = config.onBuildWrite(moduleName, path, singleContents);\n }\n };\n writeApi.asModule = function (moduleName, input) {\n singleContents += \"\\n\" +\n addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, {\n useSourceUrl: layer.context.config.useSourceUrl\n }), config);\n if (config.onBuildWrite) {\n singleContents = config.onBuildWrite(moduleName, path, singleContents);\n }\n };\n builder.write(parts.prefix, parts.name, writeApi);\n }\n return;\n } else {\n return prim().start(function () {\n if (hasProp(stubModulesByName, moduleName)) {\n //Just want to insert a simple module definition instead\n //of the source module. Useful for plugins that inline\n //all their resources.\n if (hasProp(layer.context.plugins, moduleName)) {\n //Slightly different content for plugins, to indicate\n //that dynamic loading will not work.\n return 'define({load: function(id){throw new Error(\"Dynamic load not allowed: \" + id);}});';\n } else {\n return 'define({});';\n }\n } else {\n return require._cacheReadAsync(path);\n }\n }).then(function (text) {\n var hasPackageName;\n\n currContents = text;\n\n if (config.cjsTranslate &&\n (!config.shim || !lang.hasProp(config.shim, moduleName))) {\n currContents = commonJs.convert(path, currContents);\n }\n\n if (config.onBuildRead) {\n currContents = config.onBuildRead(moduleName, path, currContents);\n }\n\n if (packageMain) {\n hasPackageName = (packageName === parse.getNamedDefine(currContents));\n }\n\n if (namespace) {\n currContents = pragma.namespace(currContents, namespace);\n }\n\n currContents = build.toTransport(namespace, moduleName, path, currContents, layer, {\n useSourceUrl: config.useSourceUrl\n });\n\n if (packageMain && !hasPackageName) {\n currContents = addSemiColon(currContents, config) + '\\n';\n currContents += namespaceWithDot + \"define('\" +\n packageName + \"', ['\" + moduleName +\n \"'], function (main) { return main; });\\n\";\n }\n\n if (config.onBuildWrite) {\n currContents = config.onBuildWrite(moduleName, path, currContents);\n }\n\n //Semicolon is for files that are not well formed when\n //concatenated with other content.\n singleContents += addSemiColon(currContents, config);\n });\n }\n }).then(function () {\n var refPath, pluginId, resourcePath,\n sourceMapPath, sourceMapLineNumber,\n shortPath = path.replace(config.dir, \"\");\n\n module.onCompleteData.included.push(shortPath);\n buildFileContents += shortPath + \"\\n\";\n\n //Some files may not have declared a require module, and if so,\n //put in a placeholder call so the require does not try to load them\n //after the module is processed.\n //If we have a name, but no defined module, then add in the placeholder.\n if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) {\n shim = config.shim && (getOwn(config.shim, moduleName) || (packageMain && getOwn(config.shim, moduleName) || getOwn(config.shim, packageName)));\n if (shim) {\n if (config.wrapShim) {\n singleContents = '(function(root) {\\n' +\n namespaceWithDot + 'define(\"' + moduleName + '\", ' +\n (shim.deps && shim.deps.length ?\n build.makeJsArrayString(shim.deps) + ', ' : '[], ') +\n 'function() {\\n' +\n ' return (function() {\\n' +\n singleContents +\n // Start with a \\n in case last line is a comment\n // in the singleContents, like a sourceURL comment.\n '\\n' + (shim.exportsFn ? shim.exportsFn() : '') +\n '\\n' +\n ' }).apply(root, arguments);\\n' +\n '});\\n' +\n '}(this));\\n';\n } else {\n singleContents += '\\n' + namespaceWithDot + 'define(\"' + moduleName + '\", ' +\n (shim.deps && shim.deps.length ?\n build.makeJsArrayString(shim.deps) + ', ' : '') +\n (shim.exportsFn ? shim.exportsFn() : 'function(){}') +\n ');\\n';\n }\n } else {\n singleContents += '\\n' + namespaceWithDot + 'define(\"' + moduleName + '\", function(){});\\n';\n }\n }\n\n //Add line break at end of file, instead of at beginning,\n //so source map line numbers stay correct, but still allow\n //for some space separation between files in case ASI issues\n //for concatenation would cause an error otherwise.\n singleContents += '\\n';\n\n //Add to the source map\n if (sourceMapGenerator) {\n refPath = config.out ? config.baseUrl : module._buildPath;\n parts = path.split('!');\n if (parts.length === 1) {\n //Not a plugin resource, fix the path\n sourceMapPath = build.makeRelativeFilePath(refPath, path);\n } else {\n //Plugin resource. If it looks like just a plugin\n //followed by a module ID, pull off the plugin\n //and put it at the end of the name, otherwise\n //just leave it alone.\n pluginId = parts.shift();\n resourcePath = parts.join('!');\n if (resourceIsModuleIdRegExp.test(resourcePath)) {\n sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) +\n '!' + pluginId;\n } else {\n sourceMapPath = path;\n }\n }\n\n sourceMapLineNumber = fileContents.split('\\n').length - 1;\n lineCount = singleContents.split('\\n').length;\n for (var i = 1; i <= lineCount; i += 1) {\n sourceMapGenerator.addMapping({\n generated: {\n line: sourceMapLineNumber + i,\n column: 0\n },\n original: {\n line: i,\n column: 0\n },\n source: sourceMapPath\n });\n }\n\n //Store the content of the original in the source\n //map since other transforms later like minification\n //can mess up translating back to the original\n //source.\n sourceMapGenerator.setSourceContent(sourceMapPath, singleContents);\n }\n\n //Add the file to the final contents\n fileContents += singleContents;\n });\n };\n })).then(function () {\n if (onLayerEnds.length) {\n onLayerEnds.forEach(function (builder) {\n var path;\n if (typeof module.out === 'string') {\n path = module.out;\n } else if (typeof module._buildPath === 'string') {\n path = module._buildPath;\n }\n builder.onLayerEnd(function (input) {\n fileContents += \"\\n\" + addSemiColon(input, config);\n }, {\n name: module.name,\n path: path\n });\n });\n }\n\n if (module.create) {\n //The ID is for a created layer. Write out\n //a module definition for it in case the\n //built file is used with enforceDefine\n //(#432)\n fileContents += '\\n' + namespaceWithDot + 'define(\"' + module.name + '\", function(){});\\n';\n }\n\n //Add a require at the end to kick start module execution, if that\n //was desired. Usually this is only specified when using small shim\n //loaders like almond.\n if (module.insertRequire) {\n fileContents += '\\n' + namespaceWithDot + 'require([\"' + module.insertRequire.join('\", \"') + '\"]);\\n';\n }\n });\n }).then(function () {\n return {\n text: config.wrap ?\n config.wrap.start + fileContents + config.wrap.end :\n fileContents,\n buildText: buildFileContents,\n sourceMap: sourceMapGenerator ?\n JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') :\n undefined\n };\n });\n };\n\n //Converts an JS array of strings to a string representation.\n //Not using JSON.stringify() for Rhino's sake.\n build.makeJsArrayString = function (ary) {\n return '[\"' + ary.map(function (item) {\n //Escape any double quotes, backslashes\n return lang.jsEscape(item);\n }).join('\",\"') + '\"]';\n };\n\n build.toTransport = function (namespace, moduleName, path, contents, layer, options) {\n var baseUrl = layer && layer.context.config.baseUrl;\n\n function onFound(info) {\n //Only mark this module as having a name if not a named module,\n //or if a named module and the name matches expectations.\n if (layer && (info.needsId || info.foundId === moduleName)) {\n layer.modulesWithNames[moduleName] = true;\n }\n }\n\n //Convert path to be a local one to the baseUrl, useful for\n //useSourceUrl.\n if (baseUrl) {\n path = path.replace(baseUrl, '');\n }\n\n return transform.toTransport(namespace, moduleName, path, contents, onFound, options);\n };\n\n return build;\n});\n\n }",
"function SystemJSLoader() {\n SystemLoader.call(this);\n\n systemJSConstructor.call(this);\n}",
"static load(blueprintPath) {\n\t\tlet Constructor;\n\t\tconst constructorPath = path.resolve(blueprintPath, 'index.js');\n\n\t\tif (fs.lstatSync(blueprintPath).isDirectory()) {\n\t\t\tif (fileExists(constructorPath)) {\n\t\t\t\tconst blueprintModule = require(constructorPath);\n\t\t\t\tConstructor = mixin(Blueprint, blueprintModule);\n\n\t\t\t\treturn new Constructor(blueprintPath);\n\t\t\t}\n\t\t}\n\t}",
"function load(source) {\n let env = {};\n const moduleCode = loader.call(env, source);\n const moduleFunction = new Function(['module', 'exports', 'require'], moduleCode);\n let fakeModule = {exports: {}}\n moduleFunction(fakeModule, fakeModule.exports, require);\n return fakeModule.exports;\n}",
"function bundleDll() {\n return new Promise((resolve, reject) => {\n if (!__DEVELOPMENT__) {\n resolve();\n return;\n }\n\n webpack(dllConfig).run(error => {\n if (error) {\n reject(error);\n return;\n }\n\n resolve();\n });\n });\n}",
"function getConfigFromBabel(start) {\n if (start === '/') return [];\n\n const babelrc = path.join(start, '.babelrc');\n if (fs.existsSync(babelrc)) {\n const babelrcJson = JSON5.parse(fs.readFileSync(babelrc, 'utf8'));\n if (babelrcJson && Array.isArray(babelrcJson.plugins)) {\n const pluginConfig = babelrcJson.plugins.find(p => (\n p[0] === 'babel-plugin-root-import'\n ));\n // The src path inside babelrc are from the root so we have\n // to change the working directory for the same directory\n // to make the mapping to work properly\n process.chdir(path.dirname(babelrc));\n return pluginConfig[1];\n }\n }\n return getConfigFromBabel(path.dirname(start));\n}",
"function bundleScript () {\n return require('dnode/web').source()\n + ('browser/setup browser/sphere-fns browser/controls')\n .split(/\\s+/).map(function (filename) {\n var file = __dirname + '/lib/' + filename + '.js';\n var src = fs.readFileSync(file).toString()\n .replace(/^(module|exports)\\..*/mg, '')\n .replace(/^var \\S+\\s*=\\s*require\\(.*/mg, '')\n ;\n \n return src;\n }).join('\\n');\n}",
"Program(\n path,\n {\n opts: {\n log = \"off\",\n propRegex = undefined,\n\n // Hoisted function name prefix\n hoistedSlug = \"rbHoisted\",\n // Identifier name to assign the imported babelBind to\n babelBindSlug = \"rbBabelBind\",\n // Location of the main reflective-bind index file\n indexModule = \"reflective-bind\",\n },\n file,\n }\n ) {\n if (SKIP_RE.test(file.code)) {\n return;\n }\n logger.setLevel(log);\n _propRegexCompiled =\n propRegex != null ? new RegExp(propRegex) : undefined;\n _filename = file.opts.filename;\n _hoistPath = path;\n _hoistedSlug = hoistedSlug;\n _bableBindImportSlug = babelBindSlug;\n _indexModuleName = indexModule;\n\n // We only add the import if the cached name is undefined so that the\n // import is only added once per file.\n _cachedBabelBindImportIdentifierName = undefined;\n\n const state = {\n numTransformed: 0,\n };\n path.traverse(visitor, state);\n\n if (state.numTransformed > 0) {\n _totalTransformedInAllFiles += state.numTransformed;\n logger.debug(\n `Total inline functions transformed: ${_totalTransformedInAllFiles}`\n );\n\n // Have babel update all references after hoisting.\n // There's probably a more efficient way to do this.\n path.scope.crawl();\n }\n }",
"function startBabelTests () {\n return new Promise((fulfill, reject) => {\n const babelTests = fork(\n path.join(modulePath, '.bin', 'babel'),\n 'test/specs --out-dir test --presets es2015'.split(' '),\n { silent: true }\n );\n\n children.push(babelTests);\n\n babelTests.on('exit', exitCode => {\n if (exitCode > 0) {\n return reject('Failed compiling source files');\n }\n\n logSuccess('Finished compiling test files');\n\n return fulfill();\n });\n\n babelTests.stdout.on('data', logInfo);\n babelTests.stderr.on('data', logError);\n\n });\n}"
]
| [
"0.7090452",
"0.6223538",
"0.5940874",
"0.586632",
"0.5842965",
"0.57144344",
"0.5548846",
"0.55444837",
"0.55444837",
"0.5431258",
"0.53469723",
"0.5326572",
"0.5315413",
"0.5293458",
"0.52748847",
"0.5249645",
"0.52049714",
"0.51667213",
"0.5139053",
"0.51232827",
"0.5109968",
"0.50699675",
"0.50570446",
"0.5052702",
"0.5004613",
"0.49982092",
"0.49812657",
"0.4964772",
"0.49619544",
"0.49040323"
]
| 0.7735155 | 0 |
Reads the employees from a csv file and sets the employees variable. | function setEmployees() {
let csvData = readCsv(EMPLOYEE_FILE);
for(var i = 0; i < csvData.length; i++) {
employees.push({
id: csvData[i][0],
firstName: csvData[i][1],
lastName: csvData[i][2],
email: csvData[i][3],
hourlyWage: Number(csvData[i][4])
});
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function readFromCsvAndPopulateStaffSchema() {\n\tvar readStream = fs.createReadStream('../staff.csv');\n\tvar parser = csv.parse({columns:true});\n\n\tparser.on('readable', function() {\n\t\twhile (record = parser.read()) {\n\t\t\t// var split_name = record.name.split(\" \");\n\t\t\t// if (split_name.length == 2) {\n\t\t\t// \tvar first_name = split_name[0]\n\t\t\t// \tvar last_name = split_name[1]\n\t\t\t// } else {\n\t\t\t// \tvar first_name = split_name[0] + \" \" + split_name[1]\n\t\t\t// \tvar last_name = split_name[2]\n\t\t\t// }\n\n\t\t\t// db.populateStaffSchema(record.Name, record.Role, parseInt(record.Year), record.Bio)\n\t\t}\n\t});\n\n\tparser.on('error', function(err) {\n\t\tconsole.log(err.message);\n\t});\n\n\tparser.on('finish', (function() {\n\t\tconsole.log('finish');\n\t}));\n\n\treadStream.pipe(parser);\n}",
"function loadEmployees() {\n API.fetchEmployees()\n .then((res) => {\n return setEmployee({\n employees: res.data.results,\n });\n })\n .catch((err) => console.log(err));\n }",
"function populateEmployees(){\n connection.query(\"SELECT * FROM employees\", function(err, res) {\n if (err) {\n throw err;\n }\n else{\n const employeesArray = res;\n populateRoles(employeesArray);\n }\n return;\n });\n}",
"function writeEmployees() {\n\tlet csvData = [];\n\tfor(let i = 0; i < employees.length; i++) {\n\t\tlet employee = employees[i];\n\t\tlet row = [\n\t\t\temployee.id,\n\t\t\temployee.firstName,\n\t\t\temployee.lastName,\n\t\t\temployee.email,\n\t\t\tString(employee.hourlyWage)\n\t\t];\n\t\tcsvData.push(row);\n\t}\n\twriteCsv(EMPLOYEE_FILE, csvData);\n}",
"_parseData(lineParser) {\n const data = fs.readFileSync(sdnCsvFilename).toString()\n const lines = data.split('\\r\\n')\n for (const line of lines) {\n const cells = lineParser.parse(line)\n if (!cells || cells.length < 2) {\n continue\n }\n if (cells[2] !== 'individual') {\n continue\n }\n const values = cells[1].split(',').map(s => s.toLowerCase().trim())\n const firstName = values[0]\n const lastName = values[1]\n if (!firstName || !lastName) {\n continue\n }\n\n if (this.lastNames[lastName]) {\n this.lastNames[lastName].push(firstName)\n } else {\n this.lastNames[lastName] = [firstName]\n }\n }\n logger.info(\n `Read ${Object.keys(this.lastNames).length} records from SDN list.`\n )\n }",
"function add_from_csv_student() {\n csvdata = fs.readFileSync(\"data/201830-Subject_Course Timetables.csv\");\n csv(csvdata, { trim: true, skip_empty_lines: true, from_line: 2 })\n .on(\"readable\", function() {\n let record;\n while ((record = this.read())) {\n //checks if process.argv is part of program name\n if (record[1].includes(process.argv[2].toUpperCase())) {\n //cleaning data\n if (record[8].includes(\"*\") || record[8] == \" ,\" || record[0] == \"Inactive\") {\n continue;\n } else {\n student_xml(record)\n }\n }\n }\n })\n .on(\"end\", function() {\n studentSaveData(); // save our document\n });\n}",
"SET_EMPLOYEES(state, payload) {\n state.employees = payload;\n }",
"function setupData(){\n rawRecordsArray = csv.split('\\n');\n headerString = rawRecordsArray[0];\n //get recordsArray without header\n for(var i=1; i<rawRecordsArray.length; i++){\n recordsArray.push(rawRecordsArray[i])\n }\n //create titlesArray\n titlesArray = headerString.split(',');\n }",
"constructor(employees) {\n this.employees = employees;\n }",
"function handleReaderLoad(event, file) {\n \t\n \t//Set csv variable equal to file contents\n \tcsv = event.target.result;\n \t\n \t//Run CSV parsing function\n \tprocessData();\n}",
"function add_from_csv_teacher() {\n csvdata = fs.readFileSync(\"data/201830-Subject_Course Timetables.csv\");\n csv(csvdata, { trim: true, skip_empty_lines: true, from_line: 2 })\n .on(\"readable\", function() {\n let record;\n while ((record = this.read())) {\n //checks if process.argv is part of program name\n if (record[1].includes(process.argv[2].toUpperCase())) {\n //cleaning data\n if (record[8].includes(\"*\") || record[8] == \" ,\"|| record[0] == \"Inactive\") {\n continue;\n } else {\n teacher_xml(record)\n }\n }\n }\n })\n .on(\"end\", function() {\n teacherSaveData(); // save our document\n });\n}",
"function populate() {\n dataService.getCSV(vm.filename)\n .then(function(data) {\n vm.loading = false;\n vm.header = data.shift().header;\n vm.data = data;\n });\n }",
"function initializeEmployees() {\n const ids = [1, 2, 3, 4 , 5];\n const firstNames = [\"Alan\", \"Bertha\", \"Carl\", \"Denise\", \"Edward\"];\n const lastNames = [\"Benson\", \"Cartwright\", \"Decker\", \"Franklin\", \"Harrison\"];\n const titles = [\"President\", \"Vice President\", \"CFO\", \"CTO\", \"Operations Director\"];\n\n const employees =[];\n for (let i = 0; i < 5; i++) {\n employees.push(Object.freeze(new Employee(ids[i], firstNames[i], lastNames[i], titles[i])));\n }\n return employees;\n}",
"function loadFirstEmployee( itcb ) {\n // if we found an employee already then we can skip this step\n if ( employeeId ) { return itcb( null ); }\n\n Y.doccirrus.mongodb.runDb( {\n 'user': user,\n 'model': 'employee',\n 'query': { },\n 'options': { 'limit': 1 },\n 'callback': onFirstEmployeeLoaded\n } );\n\n function onFirstEmployeeLoaded( err, result ) {\n if ( !err && !result[0] ) { err = Y.doccirrus.errors.rest( 404, 'No employees found' ); }\n if ( err ) { return itcb( err ); }\n\n employeeId = result[0]._id;\n itcb( null );\n }\n }",
"function editEmployee() {\n\toutputEmployeeDetails();\n\tlet selectedEmployee = prompt.questionInt('Employee ID: ');\n\tlet employee = employees.find(emp => Number(emp.id) == selectedEmployee);\n\n\tif(employee != undefined) {\n\t\tconsole.log('------------------------------------');\n\t\tconsole.log('Press enter to keep current value. Any new input will be changed in the employees file.');\n\t\tvar firstName = prompt.question(`First Name (${employee.firstName}): `, { defaultInput: employee.firstName});\n\t\tvar lastName = prompt.question(`Last Name (${employee.lastName}):`, { defaultInput: employee.lastName});\n\t\tvar email = prompt.questionEMail(`Email (${employee.email}): `, { defaultInput: employee.email});\n\t\tvar hourlyWage = prompt.questionInt(`Hourly Wage (${employee.hourlyWage}): `, { defaultInput: employee.hourlyWage});\n\n\t\temployee.firstName = firstName;\n\t\temployee.lastName = lastName;\n\t\temployee.email = email;\n\t\temployee.hourlyWage = hourlyWage;\n\n\t\temployees[employees.indexOf(employee)] = employee;\n\t\toutputEmployeeDetails();\n\t} else {\n\t\tconsole.log('Employee ID not valid. Please try again.');\n\t\teditEmployee();\n\t}\n\n}",
"loadData(){\n\n\t\tvar _this = this\n\t\td3.csv(\"fortune_1000.csv\", function(err, data) {\n\n\t\t\tif(err){\n\t\t\t\talert(\"some problem with the data!\");\n\t\t\t\treturn\n\t\t\t}\n\t\t\t//pre process data\n\t\t\tdata.forEach(function(d) {\n\t\t d.rank = +d.rank;\n\t\t d.rank_change = +d.rank_change;\n\t\t d.revenue = +d.revenue.split(',').join(\"\")\n\t\t d.revenue_change = +d.revenue_change.slice(0,-1)\n\t\t d.profits = +d.profits.split(',').join(\"\")\n\t\t d.expenses = +d.expenses.split(',').join(\"\")\n\t\t d.profit_change = +d.profit_change.slice(0,-1)\n\t\t d.assets = +d.assets.slice(1).split(',').join(\"\")\n\t\t d.market_value = +d.market_value.slice(1).split(',').join(\"\")\n\t\t d.employees = +d.employees.split(',').join(\"\")\n\t\t // d.market_value = +d.market_value.slice(1).split(',').join(\"\")\n\t\t });\n\t\t\t_this.saveData(data)\n\t\t});\n\t}",
"function parseCSV(csv) {\n let meals = [];\n let lines = csv.split('\\n');\n if (Array.isArray(lines) && lines.length) {\n let keys = lines[0].replace(/\\r/g, \"\").split(\";\");\n for (var i = 1; i < lines.length; i++) {\n let values = lines[i].replace(/\\r/g, \"\").split(\";\");\n if (Array.isArray(values) && values.length > 1) {\n let meal = initializeMealObject(values, keys);\n meals.push(meal);\n }\n }\n }\n return meals;\n}",
"function Employee(firstName, lastName, emplId, emplTitle, salary) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.emplId = parseInt(emplId);\n this.emplTitle = emplTitle;\n this.salary = parseFloat(salary);\n} // end Employee",
"function loadCSV1(){\n\n\tdataManager = dataManagerConstructor();\n\n\tdataManager.read1(\"resources/REF2014_Results.csv\",\n\t\tfunction(error){ // to call in case of error\n\t\t\tconsole.log(\"Error\");\n\t\t\tconsole.log(error);\n\t\t},\n\t\tfunction(){ // to call if everything ok\n\t\t\tloadCSV2();\n\t\t});\n}",
"function getAllEmployees() {\n employeeService.getAll()\n .then(function (response) {\n $scope.employees = response.data;\n $scope.file = response.data;\n $scope.current_grid = 1;\n $scope.data_limit = 10;\n $scope.filter_data = $scope.employees.length;\n $scope.entire_user = $scope.employees.length;\n });\n }",
"async findAllEmployees() {\n return Clinic.findAll();\n }",
"function loadFile(){\n\tvar questions = [\n\t\t{\n\t\t\tname: 'fileName',\n\t\t\ttype: 'input',\n\t\t\tmessage: 'Enter a file to load, otherwise a default file (eList.txt) will be loaded\\n',\n\t\t\tvalidate: function (fileName) {\n\t\t\t\tif(fileName.indexOf('.txt') > -1) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else if ( fileName == ''){\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\treturn console.log('\\nPlease enter a valid .txt file or blank\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t];\n\n\tinquirer.prompt(questions).then(function(response) {\n\t\t// Set the file name to user input\n\t\tif(response.fileName != ''){\n\t\t\tm_list_name = response.fileName;\n\t\t} else {\n\t\t\tm_list_name = 'eList.txt';\n\t\t}\n\n\t\tconsole.log('Initializing employee list from ' + m_list_name + '...');\n\t\t// Load employee list from m_list_name\n\t\tfs.readFile(m_list_name, function(err, data) {\n\t\t if(err){\n\t\t \tconsole.log(\"Error reading file: \" + err);\n\t\t \tloadFile();\n\t\t } else {\n\t\t\t var array = data.toString().split(\"\\n\");\n\t\t\t \n\t\t\t var i = 0;\n\t\t\t for(i; i < array.length; i++) {\n\t\t\t m_employee_array.push(array[i]);\n\t\t\t }\n\n\t\t\t\tm_total_people = m_employee_array.length;\n\t\t\t\tconsole.log(\"Done!\");\n\t\t\t\tsortArray();\n\t\t\t\tshowMenu();\n\t\t }\n\t\t});\n\t});\n}",
"function importCSV(csvFileName) {\n var file = DriveApp.getFilesByName(csvFileName).next();\n var csvData1 = Utilities.parseCsv(file.getBlob().getDataAsString());\n var arrayData =[];\n for (var i = 0; i < csvData1.length; i++) {\n var netID = csvData1[i][0]; // netID is the first column of the csv data\n arrayData.push(netID + \"@nd.edu\");\n }\n return arrayData;\n}",
"async function setEmployees(arr) {\n arr.employees = await employee.employee_plant(arr.id)\n }",
"getEmployees() {\n API.getEmployees().then(function(res) {\n for (let i = 0; i < res.data.length; ++i) {\n employees.push(res.data[i].EMP_NAME);\n }\n console.log(\"employees table loaded!\");\n });\n }",
"function parseCSV(err, csvData) {\n if (err) console.log(err);\n csvParser(csvData, { delimiter: ',' }, readCSV);\n}",
"function getEmployees(res, mysql, context, complete) {\r\n mysql.pool.query(\"SELECT employeeID, firstName, lastName FROM Employees ORDER BY firstName, lastName ASC\", function(error, results, fields){\r\n if(error) {\r\n res.write(JSON.stringify(error));\r\n res.end();\r\n }\r\n context.employees = results;\r\n complete();\r\n });\r\n }",
"function importCSV(){\n // Import button that imports a file\n\n // Add the csv values to the person list\n\n \n\n}",
"function Employee (position) {\n this.position = position;\n this.office = \"\";\n}",
"function loadIsoCoord(CSV) {\n iso_geo_coord = CSV;\n}"
]
| [
"0.61388",
"0.6109641",
"0.5440017",
"0.53262705",
"0.531733",
"0.5293275",
"0.5209568",
"0.5193002",
"0.5163278",
"0.51000947",
"0.50778556",
"0.5051982",
"0.5017763",
"0.5005807",
"0.49946272",
"0.4964282",
"0.4963351",
"0.49368",
"0.4917712",
"0.4909844",
"0.48907244",
"0.48384035",
"0.48243922",
"0.4815732",
"0.47827986",
"0.47809902",
"0.47717363",
"0.4761223",
"0.47494957",
"0.47455156"
]
| 0.82427824 | 0 |
Writes the employees variable into the csv file. | function writeEmployees() {
let csvData = [];
for(let i = 0; i < employees.length; i++) {
let employee = employees[i];
let row = [
employee.id,
employee.firstName,
employee.lastName,
employee.email,
String(employee.hourlyWage)
];
csvData.push(row);
}
writeCsv(EMPLOYEE_FILE, csvData);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function setEmployees() {\n\tlet csvData = readCsv(EMPLOYEE_FILE);\n\tfor(var i = 0; i < csvData.length; i++) {\n\t\temployees.push({\n\t\t\tid: csvData[i][0],\n\t\t\tfirstName: csvData[i][1],\n\t\t\tlastName: csvData[i][2],\n\t\t\temail: csvData[i][3],\n\t\t\thourlyWage: Number(csvData[i][4])\n\t\t});\n\t}\n}",
"function writeToCsvFile(users, outputStream) {\n users.forEach(user => {\n let csvFormat = user.lastName ? `${user.email}, ${user.firstName} ${user.lastName}\\n`: `${user.email}, ${user.firstName}\\n`;\n outputStream.write(csvFormat);\n })\n}",
"function exportTable() {\n\n // Array to hold output values ( this is just to be able to calculate the payments and not show the adjustments...)\n let exportArray = [];\n let exPerson = [\"Name\", \"Nights\", \"Payment\"];\n\n exportArray.push(exPerson);\n\n personList.forEach(person => {\n\n exPerson = [\n person.name,\n person.nights,\n '$' + (+person.payment + +person.adjustment)\n ]\n\n exportArray.push(exPerson);\n });\n\n // console.log(exportArray);\n\n let csvContent = exportArray.map(e => e.join(\",\")).join(\"\\n\");\n\n // TODO make sure this link stays hidden\n let link = document.createElement('a')\n link.id = 'download-csv'\n link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csvContent));\n link.setAttribute('download', 'people.csv');\n document.body.appendChild(link)\n document.querySelector('#download-csv').click()\n\n}",
"function writeCSV(){\n\tvar rows = [\n\t\t\t [\"name1\", \"city1\", \"some other info\"],\n\t\t\t [\"name2\", \"city2\", \"more info\"]\n\t\t\t];\n\n\tlet csvContent = \"data:text/csv;charset=utf-8,\";\n\n\trows.forEach(function(rowArray) {\n\t let row = rowArray.join(\",\"); //combine everything in the array in a single string\n\t csvContent += row + \"\\r\\n\"; //add the row to the csv content\n\t});\n\n\tvar encodedUri = encodeURI(csvContent);\n\tvar link = document.createElement(\"a\");\n\tlink.setAttribute(\"href\", encodedUri);\n\tlink.setAttribute(\"download\", \"my_data.csv\");\n\tdocument.body.append(link); // Required for FF\n\n\tlink.click(); // This will download the data file named \"my_data.csv\".\n}",
"function createOutputData(employeeList){\n\tvar outputData;\n\n\toutputData = convertToCSVFile(employeeList);\n\tshowOutputData(employeeList);\n\tcreateDownloadLink(outputData);\n}",
"function outputEmployeeDetails() {\n\tfor(let i = 0; i < employees.length; i++) {\n\t\tlet employee = employees[i];\n\t\tconsole.log('\\n--------------------------------');\n\t\tconsole.log(`ID: ${employee.id}`);\n\t\tconsole.log(`Name: ${employee.firstName} ${employee.lastName}`);\n\t\tconsole.log(`Email: ${employee.email}`);\n\t\tconsole.log(`Hourly Wage: $${employee.hourlyWage.toFixed(2)}`);\n\t}\n}",
"function createCSV() {\n for (var i = 0; i < shirtData.length; i++) {\n data.push([shirtData[i][0], shirtData[i][1], shirtData[i][2], shirtData[i][3], time]);\n }\n stringify(data, { header: true, columns: columns }, (err, output) => {\n if (err) {\n errorHandler(err);\n } else {\n fs.writeFile(`./data/${fileName}.csv`, output, (err) => {\n if (err) {\n errorHandler(err);\n }\n });\n }\n });\n}",
"function CSV(list){\n list.unshift(1)\n fs.writeFileSync('table.csv','') //Clear the file\n generalOutput(list,\"\",\",\",function(){},function(line){\n line += '\\n'\n //Synchronously write to the file\n fs.appendFileSync('table.csv', line);\n })\n}",
"exportCSV(withtHeaders, options) {\n const r = this.exportTable(withtHeaders, options);\n return !r ? undefined : r.map((row) => row.join('\\t')).join('\\n');\n }",
"function exportDataToCSV(){\n var arr = [['x', 'y']];\n for(var i = 1; i <= arrX.length; i++){\n arr.push([arrX[i-1], arrY[i-1]]);\n }\n var csv = [];\n for(var i = 0; i < arr.length; i++){\n csv.push(arr[i].join()); //join() automatically adds commas\n }\n console.log(csv);\n var csvString = csv.join(\"%0A\"); //line feed or new line to separate each X, Y row object\n var anchor = document.createElement(\"a\");\n anchor.href = \"data:attachment/csv,\" + csvString;\n console.log(\"anchor href: \" + anchor.href);\n anchor.target = '_blank';\n anchor.download = fileName + '.csv';\n document.body.appendChild(anchor);\n anchor.click(); //click on the link to automatically open\n }",
"function createStudentPlanCSV() {\n var ws = fs.createWriteStream(\"./csv/student_plans.csv\");\n csv\n .write(studentPlans, { headers: true })\n .pipe(ws)\n .on(\"finish\", function () {\n console.log(\"\\n\" + \"student_plans.csv created successfully!\" + \"\\n\");\n });\n}",
"function createFile() {\n var date = document.getElementById(\"storeDate\").innerHTML;\n getRequest(\"/getAttendance/\" + date, \"\", createFileHelper);\n// var rows = [];\n// rows.push([\"things\", \"things2\", \"thing3\"]);\n// rows.push([\"things4\", \"things5\", \"thing6\"]);\n// rows.push([\"things7\", \"things8\", \"thing9\"]);\n// exportToCsv(\"testFile.csv\", rows);\n}",
"function handler_export(results, req, res){\n\n var content = \"User;Connection Date\\n\";\n for (var i =0; i<results.length; i++){\n console.log(results[i]);\n content += `${results[i][\"username\"]};${results[i][\"connection_date\"]}\\n`\n }\n var file = './media/export.csv';\n\n fs.writeFileSync(file, content);\n\n var filename = path.basename(file);\n var mimetype = \"text/csv\";\n\n res.setHeader('Content-disposition', 'attachment; filename=' + filename);\n res.setHeader('Content-type', mimetype);\n\n var filestream = fs.createReadStream(file);\n filestream.pipe(res);\n\n\n}",
"function generateCSV(title, tableId) {\n var title = title;//$(\"#SelectedEventReports :selected\").text().replace(/[\\\\\\/ \\.]+/g, \"_\");\n var report = \"\";\n var rows = $('#' + tableId +' > tbody > tr').each(function () {\n $(this).children('th, td').each(function (index) {\n if (index == 0) {\n return;\n }\n\n var text = $(this).text().replace(/\"/g, '\"\"').replace(/\\n[ \\t\\r\\v\\f]+/g, '\\n');\n\n if (index > 1) {\n report += ',';\n }\n\n report += '\"' + text.trim() + '\"';\n })\n\n report += \"\\n\";\n })\n\n var link = document.createElement('a');\n link.download = title + '.csv';\n link.href = 'data:text/csv;charset=UTF-8,' + encodeURIComponent(report);\n\n\n document.body.appendChild(link);\n link.click();\n\n document.body.removeChild(link);\n delete link;\n}",
"function exportParticipants(req, res) {\n\tconsole.log(\"exporting participants to csv\");\n\tdb.exportParticipants(function(err, rows) {\n\t\tif(err) {\n\t\t\terrorHandler(err, res);\n\t\t}\n\t\telse {\n\t\t\tres.setHeader(\"Content-Disposition\",\"attachment; filename=participants.csv\");\n\t\t\tres.setHeader('Content-Type', 'application/octet-stream');\n\t\t\tres.write(convertToCSV(JSON.stringify(rows)));\n\t\t\tres.end();\n\t\t}\n\t});\n}",
"function export_csv(arrayHeader, arrayData, delimiter, fileName) {\r\n let header = arrayHeader.join(delimiter) + '\\n';\r\n let csv = header;\r\n arrayData.forEach(obj => {\r\n let row = [];\r\n for (key in obj) {\r\n if (obj.hasOwnProperty(key)) {\r\n row.push(obj[key]);\r\n }\r\n }\r\n csv += row.join(delimiter) + \"\\n\";\r\n });\r\n\r\n let csvData = new Blob([csv], { type: 'text/csv' });\r\n let csvUrl = URL.createObjectURL(csvData);\r\n\r\n let hiddenElement = document.createElement('a');\r\n hiddenElement.href = csvUrl;\r\n hiddenElement.target = '_blank';\r\n hiddenElement.download = fileName + '.csv';\r\n hiddenElement.click();\r\n }",
"function download_csv() {\n var csv = 'Name,Title\\n';\n data.forEach(function(row) {\n csv += row.join(',');\n csv += \"\\n\";\n });\n\n console.log(csv);\n var hiddenElement = document.createElement('a');\n hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);\n hiddenElement.target = '_blank';\n hiddenElement.download = 'people.csv';\n hiddenElement.click();\n }",
"exportCSV() {\n let csvContent = `data:text/csv;charset=utf-8,Page,Edits,Editors,Views${this.shouldShowMobile() ? ',Mobile %' : ''}\\n`;\n\n this.pageData.forEach(entry => {\n if (this.excludes.includes(entry.article) || this.autoExcludes.includes(entry.article)) return;\n\n // Build an array of page titles for use in the CSV header\n const title = '\"' + entry.article.replace(/\"/g, '\"\"') + '\"';\n\n const editData = this.editData[entry.article] || {},\n edits = typeof editData.num_edits === 'number' ? editData.num_edits : '?',\n editors = typeof editData.num_users === 'number' ? editData.num_users : '?';\n\n csvContent += `${title},${edits},${editors},${entry.views}`;\n if (this.shouldShowMobile()) {\n csvContent += `,${this.percentMobile(entry)}`;\n }\n csvContent += '\\n';\n });\n\n this.downloadData(csvContent, 'csv');\n }",
"function exportToCsv(filename, rows) {\n var processRow = function (row) {\n var finalVal = '';\n for (var j = 0; j < row.length; j++) {\n var innerValue = row[j] === null ? '' : row[j].toString();\n if (row[j] instanceof Date) {\n innerValue = row[j].toLocaleString();\n };\n var result = innerValue.replace(/\"/g, '\"\"');\n if (result.search(/(\"|,|\\n)/g) >= 0)\n result = '\"' + result + '\"';\n if (j > 0)\n finalVal += ',';\n finalVal += result;\n }\n return finalVal + '\\n';\n };\n\n var csvFile = '';\n for (var i = 0; i < rows.length; i++) {\n csvFile += processRow(rows[i]);\n }\n\n var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });\n if (navigator.msSaveBlob) { // IE 10+\n navigator.msSaveBlob(blob, filename);\n } else {\n var link = document.createElement(\"a\");\n if (link.download !== undefined) { // feature detection\n // Browsers that support HTML5 download attribute\n var url = URL.createObjectURL(blob);\n link.setAttribute(\"href\", url);\n link.setAttribute(\"download\", filename);\n link.style.visibility = 'hidden';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n }",
"async writeAll(records) {\n //write the updated 'records' array back to this.filename.\n //JSON.stringify second argument is for custom formatting.\n //JSON.stringify third argument changes indentation.\n await fs.promises.writeFile(this.filename, JSON.stringify(records, null, 2));\n }",
"function _outputPayslip(err, payslip ){\n\n if(err) {\n console.error(\"** ERROR ** \", err);\n // write a line to CSV file\n _outputCsv.write(['', '', '', '', '', '', err.message]);\n }\n else {\n console.log(payslip);\n\n // write a line to CSV file\n _outputCsv.write([payslip.DisplayName, payslip.payPeriod, payslip.grossIncome, payslip.incomeTax, payslip.netIncome, payslip.superAmount, '']);\n }\n}",
"function exportDataAsCSV() {\n var csvContent = \"\";\n // Columns, from element's variable name\n elements.forEach(function (el) {\n return csvContent = csvContent + el.name + \",\";\n });\n csvContent += \"\\n\";\n // Columns, from element's extracted text\n elements.forEach(function (el) {\n return csvContent = csvContent + el.extractedText.replace(/(\\r\\n|\\n|\\r)/gm, \"\") + \",\";\n });\n\n var linkElement = window.document.createElement(\"a\");\n linkElement.setAttribute(\"href\", \"data:text/csv;charset=utf-8,\" + encodeURI(csvContent));\n linkElement.setAttribute(\"download\", \"upload_data.csv\");\n linkElement.click();\n linkElement.remove();\n}",
"function exportToCsv(filename, rows) {\n let processRow = function (row) {\n let finalVal = \"\";\n for (let j = 0; j < row.length; j++) {\n let innerValue = !row[j] ? \"\" : row[j].toString();\n if (row[j] instanceof Date) {\n innerValue = row[j].toLocaleString();\n }\n let result = innerValue.replace(/\"/g, '\"\"');\n if (result.search(/(\"|,|\\n)/g) >= 0) result = '\"' + result + '\"';\n if (j > 0) finalVal += \",\";\n finalVal += result;\n }\n return finalVal + \"\\n\";\n };\n let csvFile = \"\";\n for (let i = 0; i < rows.length; i++) {\n csvFile += processRow(rows[i]);\n }\n\n let blob = new Blob([csvFile], { type: \"text/csv;charset=utf-8;\" });\n if (navigator.msSaveBlob) {\n // IE 10+\n navigator.msSaveBlob(blob, filename);\n } else {\n let link = document.createElement(\"a\");\n if (link.download !== undefined) {\n // feature detection\n // Browsers that support HTML5 download attribute\n let url = URL.createObjectURL(blob);\n link.setAttribute(\"href\", url);\n link.setAttribute(\"download\", filename);\n link.style.visibility = \"hidden\";\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n }",
"function writeToFile() {\n fs.writeFileSync('./dist/profile.html', '');\n fs.appendFileSync('./dist/profile.html', templates.htmlTop);\n \n for (employee of employees) {\n const role = employee.getRole();\n const name = employee.getName();\n const id = employee.getId();\n const email = employee.getEmail();\n switch (role) {\n case 'Manager':\n const officeNumber = employee.getOfficeNumber();\n fs.appendFileSync('./dist/profile.html', templates.managerCard(name, id, email, officeNumber));\n break;\n case 'Engineer':\n const gitHub = employee.getGitHub();\n fs.appendFileSync('./dist/profile.html', templates.engineerCard(name, id, email, gitHub));\n break;\n case 'Intern':\n const school = employee.getSchool();\n fs.appendFileSync('./dist/profile.html', templates.internCard(name, id, email, school));\n break;\n }\n }\n fs.appendFileSync('./dist/profile.html', templates.htmlBottom);\n}",
"function appendEmployee() {\n console.log('append new employee');\n let employeeList = $('.employeeList');\n employeeList.empty();\n\n // loop employee properties\n for (let employee of employeesArray) {\n let firstName = `<td>${employee.firstName}</td>`;\n let lastName = `<td>${employee.lastName}</td>`;\n let idNum = `<td>${employee.idNum}</td>`;\n let jobTitle = `<td>${employee.jobTitle}</td>`;\n let annualSalary = `<td>${employee.annualSalary}</td>`;\n let removeBtn = '<td><button class=\"removeEmployee\">Remove</button></td>';\n let element = `<tr>${firstName} ${lastName} ${idNum} ${jobTitle} ${annualSalary} ${removeBtn}</tr>`;\n $('table tbody').append(element);\n } // end for-of\n} // end appendEmployee",
"function exportCSV() {\n\t\t\t\n\t\t\tvar data = [];\n\t\t\tvar titles = [];\n\t\t\t\n\t\t\t_$table.find(\"dl:visible\").each(function() {\n\t\t\t\t\n\t\t\t\tvar $target = $(this);\n\t\t\t\ttitles.push($target.find(\"dt\").text());\n\t\t\t\t\n\t\t\t\t$target.find(\"dd\").each(function(index) {\n\t\t\t\t\t\n\t\t\t\t\tvar $target = $(this);\n\t\t\t\t\tvar $stock = $target.find(\".stock\");\n\t\t\t\t\tvar $lastStock = $target.find(\".lastStock\");\n\t\t\t\t\t\n\t\t\t\t\tvar stock = $stock.text();\n\t\t\t\t\tvar lastStock = $lastStock.text();\n\t\t\t\t\t\n\t\t\t\t\tif (!data[index + 1]) data[index + 1] = [];\n\t\t\t\t\tdata[index + 1].push($stock.length ? stock : $target.text());\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t\t\n\t\t\t});\n\t\t\t\n\t\t\tdata[0] = titles;\n\t\t\t_ajax.exportCSV({ data:data });\n\t\t\t\n\t\t\treturn false;\n\t\t\t\n\t\t}",
"function exportToCsv(filename, rows) {\n var processRow = function (row) {\n var finalVal = '';\n for (var j = 0; j < row.length; j++) {\n var innerValue = row[j] === null ? '' : row[j].toString();\n if (row[j] instanceof Date) {\n innerValue = row[j].toLocaleString();\n };\n var result = innerValue.replace(/\"/g, '\"\"');\n if (result.search(/(\"|,|\\n)/g) >= 0)\n result = '\"' + result + '\"';\n if (j > 0)\n finalVal += ',';\n finalVal += result;\n }\n return finalVal + '\\n';\n };\n\n var csvFile = '';\n for (var i = 0; i < rows.length; i++) {\n csvFile += processRow(rows[i]);\n }\n\n var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });\n if (navigator.msSaveBlob) { // IE 10+\n navigator.msSaveBlob(blob, filename);\n } else {\n var link = document.createElement(\"a\");\n if (link.download !== undefined) { // feature detection\n // Browsers that support HTML5 download attribute\n var url = URL.createObjectURL(blob);\n link.setAttribute(\"href\", url);\n link.setAttribute(\"download\", filename);\n link.style.visibility = 'hidden';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n}",
"function createFinalCSV() {\n\tvar csv = encodeURIComponent(\"Data source,Data point,Value,Time\") + \"%0A\";\n \n for (var i in points) {\n\t var pointInfo = getDataPointInfo(points[i]);\n\t csv += createCSVHistory(pointInfo, startTime);\n }\n \n return csv;\n}",
"function saveCSVcontents(keys, data) {\n localStorage.setItem('csv', JSON.stringify({ tableHead : keys, tableBody : data }));\n }",
"function download_csv() {\n let csv = 'Name,Web Address\\n';\n users.forEach(function(webAddress, name) {\n csv += name + ',' + webAddress;\n csv += '\\n';\n });\n\n const encodedUri = encodeURI(csv);\n let link = document.createElement('a');\n link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodedUri);\n link.setAttribute('download', 'fb_group_users.csv');\n link.target = '_blank';\n link.innerHTML= 'Click Here to download fb_group_users.csv';\n document.body.appendChild(link); // Required for FF\n\n link.click();\n}"
]
| [
"0.6533477",
"0.6351464",
"0.6213126",
"0.6196487",
"0.61778516",
"0.6038391",
"0.57554775",
"0.5705484",
"0.5679781",
"0.5675083",
"0.5674872",
"0.56515294",
"0.56094223",
"0.55181044",
"0.5517091",
"0.54814583",
"0.54790294",
"0.5466736",
"0.5448518",
"0.54376006",
"0.54109657",
"0.5395944",
"0.5392305",
"0.5387802",
"0.5360418",
"0.5358491",
"0.53175414",
"0.5309371",
"0.53036714",
"0.5277395"
]
| 0.87644213 | 0 |
Shows the main menu and performs the action selected by the user. | function showMainMenu() {
console.log('---------------------------------------');
for(let i = 0; i < MAIN_MENU.length; i++) {
console.log(`${MAIN_MENU[i].text}`);
}
let selectedAction = prompt.questionInt(">>> ");
if(selectedAction > MAIN_MENU.length || selectedAction <= 0) {
console.log("\nInput not valid. Please try again.");
showMainMenu();
} else {
MAIN_MENU[selectedAction-1].action();
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function mainMenu() {\n inquirer.prompt({\n name: \"action\",\n type: \"list\",\n message: \"Select an action to perform: \",\n choices: menuSelections\n })\n .then(function(answer) { // menu branch table \n switch (answer.action) {\n case menuSelections[0]: // display all products\n readProducts();\n break;\n case menuSelections[1]: // display low inventory\n lowQuantity();\n break;\n case menuSelections[2]: // add inventory\n addInventory();\n break;\n case menuSelections[3]: // add product\n addNew();\n break;\n case menuSelections[4]: // exit app\n connection.end();\n break;\n }\n });\n }",
"function actionOnClick(){\n\t\tthis.game.state.start('MainMenu');\n\t }",
"doMenuButton()\n\t{\n\t\tif(game.paused) {\n\t\t\tgame.state.start('MainMenu');\n\t\t}\n\t}",
"function displayMenu(){\n console.log();\n console.log('What would you like to do?');\n console.log('1.Reload data from dataset');\n console.log('2.Save the data to a new file');\n console.log('3.Display specific record(s) from the data');\n console.log('4.Create a new record');\n console.log('5.Edit a record');\n console.log('6.Delete a record');\n console.log('7.Display the data structure')\n console.log('Enter \\'X\\' to exit');\n console.log();\n}",
"function SupervisorMenu() {\n if (DebugON) console.log (\"In SupervisorMenu()\".cyan);\n\n inquirer.prompt({ \n // prompt for action\n name: \"action\",\n type: \"rawlist\",\n message: \"What would you like to do?\",\n choices: [\n \"View Product Sales by Department\",\n \"Create New Department\",\n \"Exit Program\"\n ]\n }) // inquirer.prompt()\n .then(function(answer) {\n\n switch (answer.action) {\n case \"View Product Sales by Department\":\n DisplayDepartmentSales();\n break;\n \n case \"Create New Department\":\n CreateNewDepartment();\n break;\n \n case \"Exit Program\":\n console.log (\"\\nExiting Supervisor View Application\\n\".yellow);\n connection.end();\n return;\n break; \n } // switch()\n\n }); // .then()\n \n } // function SupervisorMenu()",
"function main() {\n\tloadData();\n\tshowMenu();\n}",
"function action(option) {\n switch (option) {\n case \"View Products for Sale\":\n listItems();\n break;\n case \"View Low Inventory\":\n lowItems();\n break;\n case \"Add to Inventory\":\n addItems();\n break;\n case \"Add New Product\":\n createProduct();\n\n }\n}",
"function showMenu() {\n\t\tshowStats();\n\t\tsuper.showMenu();\n\t}",
"function Menu(action) {\n let act = action;\n inquirer\n .prompt([\n {\n // list of queries\n type: 'list',\n name: 'selection',\n message: `${act} What do you want to do next?`,\n choices: [\n 'View All Employees',\n 'View All Roles',\n 'View All Departments',\n 'Add an Employee',\n 'Add a Role',\n 'Add a Department',\n 'Update an Employee Role',\n // 'Remove Employee',\n // 'Remove Role',\n // 'Remove Department',\n 'Exit Program',\n ],\n },\n ])\n ///will connect each prompt to the function\n .then((data) => {\n switch (data.selection) {\n case 'Add an Employee':\n addNewEmployee();\n break;\n case 'Add a Role':\n addNewRole();\n break;\n case 'Add a Department':\n addNewDept();\n break;\n case 'Remove Employee':\n removeEmployee();\n break;\n // case 'Remove Role':\n // removeRole();\n // break;\n // case 'Remove Department':\n // removeDept();\n // break;\n case 'Update an Employee Role':\n updateEmployeeRole();\n break;\n case 'View All Employees':\n viewEmployees();\n break;\n case 'View All Roles':\n viewRoles();\n break;\n case 'View All Departments':\n viewDepartments();\n break;\n default:\n console.log('Thank you for using!')\n db.end();\n }\n });\n\n }",
"function sideMenuAction(action)\n{\n switch (action){\n case 'addRealty':\n addRealty();\n break;\n case 'goToProjects':\n goToProjects();\n break;\n }\n}",
"doActionBySelectedIndex() {\n switch (this.selectedPosition) {\n case 0:\n changeCurrentScene(new GamePage());\n break;\n case 1:\n changeCurrentScene(new Instructions());\n break;\n case 2:\n changeCurrentScene(new About());\n break;\n }\n }",
"function mainMenu() {\n // prompt the user to choose between three options\n inquirer.prompt([\n {\n type: \"list\",\n name: \"menuChoice\",\n message: \"What would you like to do?\",\n choices: [\"View a quote\", \"Add a quote\", \"Exit\"]\n }\n ]).then(function (userChoice) {\n // depending on the user selection, \n switch (userChoice.menuChoice) {\n // call on a function to show the quotes\n case \"View a quote\":\n showQuotes();\n break;\n // call on a function to add a new quote\n case \"Add a quote\":\n addQuotes();\n break;\n // exit the application by not calling on any functions\n case \"Exit\":\n console.log(\"\\n Goodbye! Come back soon!\");\n }\n })\n}",
"performMenuAction() {\n this.absPause = true;\n this.requestAbsMenu = true;\n }",
"function openMenu() {\n Menu.set(true)\n }",
"function mainMenu() {\n inq.prompt(\n {\n type: 'list',\n name: 'choice',\n choices: [\"View Sales Data\", 'Create New Department', 'Exit'],\n message: 'Welcome to Blamazon Supervisor View'.magenta\n }\n ).then(function(ans){\n clear();\n switch(ans.choice) {\n case \"View Sales Data\":\n getSales();\n break;\n case 'Create New Department':\n newDept();\n break;\n default:\n con.end()\n return console.log(\"\\nHave a Great Day\".rainbow);\n break;\n } \n });\n}",
"runAction(action) {\n // run the given action of the clicked item\n action()\n // close the contextmenu afterwards\n this.props.hideMenu()\n }",
"function initialMenu() {\n\tconsole.log(view.separateLine);\n\tconsole.log(view.initMenu);\n\tuserInteract.question(\"Enter your choice: \", (menuOption) => {\n if(menuOption == 1) {\n\t\t\t// Option 1: Log In\n\t\t\tloginMenu();\n\t\t} else if (menuOption == 2) {\n\t\t\t// Option 2: Create New Account\n\t\t\tcreateAccountMenu();\n\t\t} else if (menuOption == 3) {\n\t\t\t// Option 3: Exit Application\n\t\t\tconsole.log(view.exitingApp);\n\t\t\tuserInteract.close();\n\t\t} else {\n\t\t\t// Incorrect input\n\t\t\tconsole.log(view.errorMenu + \"\\n\");\n\t\t\tinitialMenu();\n\t\t}\n })\n}",
"function mainMenu() {\n inquirer\n .prompt({\n name: \"action\",\n type: \"list\",\n message: \"Welcome! What would you like to do?\",\n choices: [\n \"View products for sale\",\n \"View low inventory\",\n \"Add to inventory\",\n \"Add new product\",\n \"Exit\"\n ]\n })\n .then(function(answer) {\n switch (answer.action) {\n case \"View products for sale\":\n displayProducts();\n break;\n case \"View low inventory\":\n lowInventory();\n break;\n case \"Add to inventory\":\n addInventory();\n break;\n case \"Add new product\":\n addProduct();\n break;\n case \"Exit\":\n console.log(\"\\nGoodbye!\\n\");\n connection.end();\n break;\n };\n });\n}",
"function start() {\n\tvar currentMenuItemId = params.CurrentMenuItemId.value;\n\tvar menuname = params.menuname.value;\n\tvar mainmenuname = params.mainmenuname.value;\n\n\tsession.privacy.currentMenuItemId = currentMenuItemId;\n\tsession.privacy.menuname = menuname;\n\tsession.privacy.mainmenuname = mainmenuname;\n\n\tvar viewObj = {\n\t\tCurrentMenuItemId: currentMenuItemId,\n\t\tmenuname: menuname,\n\t\tmainmenuname: mainmenuname,\n\t\titems: avItems()\n\t};\n\n\tapp.getView(viewObj).render('/avatax/avhelp');\n}",
"function show() {\n\t\tvar menu = $(this);\n\t\tmenu.children('.actions').fadeIn('fast');\n\t}",
"function main_menu() {\n stop_world();\n switch_div('form_main_menu');\n}",
"function startMenu() {\n image(earth, width/2, height/2, width, height);\n\n // start menu\n if (state === 0) {\n // title screen\n fill(217, 128, 38);\n text(\"WELCOME TO EQUESTRIA\", width/2, textTop);\n\n // options\n createNewSave();\n loadSave();\n }\n\n // files that have been saved\n else if (state === 1) {\n backButton();\n showSaves();\n }\n}",
"function onOpen(e) {\n SpreadsheetApp.getUi()\n .createMenu(\"Actions\")\n .addItem('Schedule Engineer Interview', 'manualSchedulerEngineers')\n .addItem('Schedule Product Interview', 'manualSchedulerProduct')\n .addToUi()\n}",
"function mainMenu() {\n\n // Prompting user to choose an option \n inquirer\n .prompt({\n name: \"main\",\n type: \"list\",\n message: \"MAIN MENU\",\n choices: [\n \"View all Departments\",\n \"View all Roles\",\n \"View all Employees\",\n \"Add Department\",\n \"Add a Role\",\n \"Add Employee\",\n \"Update employee role\",\n \"Add Employee Role\",\n \"Exit\",\n ],\n })\n .then((response) => {\n // Switch case depending on user option\n switch (response.main) {\n case \"View all Departments\":\n return viewAllDepartments();\n case \"View all Roles\":\n return viewAllRoles();\n case \"View all Employees\":\n return viewAllEmployees();\n case \"Add Department\":\n return addDeptartment();\n case \"Add Employee\":\n return addEmployee();\n case \"Update employee role\":\n return updateEmployeeRole();\n case \"Add Employee Role\":\n return addEmployeeRole();\n case \"Exit\":\n connection.end();\n\n default:\n mainMenu();\n }\n });\n }",
"function onOpen(e) {\n DocumentApp.getUi()\n .createMenu('SciAI')\n .addItem('Show SciAI', 'showSidebar')\n .addSeparator()\n .addItem('Save As SCI', 'exportSci')\n .addItem('Save As ClearDoc', 'exportClear')\n .addItem('Export to DOCX', 'exportDocx')\n .addItem('Export to PDF', 'exportPdf')\n .addItem('Test DP', 'testDP')\n .addToUi();\n}",
"function start() {\n showMainMenu();\n}",
"function onOpen() {\n var ui = SpreadsheetApp.getUi();\n ui.createMenu('Maestro Actions')\n .addItem('Generate Maestro Casting Notice', 'generateMaestroCasting')\n .addItem('Generate Maestro RAW Casting Notice', 'generateMaestroRawCasting')\n .addSeparator()\n .addItem('Generate Maestro Cast Message', 'generateMaestroCast')\n .addItem('Generate Maestro RAW Cast Message', 'generateMaestroRawCast')\n .addSeparator()\n .addItem('Send Maestro Reminder Email', 'maestroReminderEmail')\n .addItem('Send Maestro RAW Reminder Email', 'maestroRawReminderEmail')\n .addSeparator()\n .addItem('Create New Week', 'addNewWeek')\n .addItem('Get Maestro Stats', 'getMaestroStats')\n .addToUi();\n}",
"function menu() {\n inquirer\n .prompt([\n {\n type: \"list\",\n name: \"option\",\n message: \"Main Menu\",\n choices: [\"View Products for Sale\", \"View Low Inventory\", \"Add to Inventory\", \"Add New Product\"]\n }\n ])\n .then(answers => {\n //Once the answer is logged, the users choice is then passed through a new function, \n //and a connection is made to the SQL server\n var option = answers.option;\n connection.connect(function (err) {\n if (err) throw err;\n action(option);\n })\n })\n}",
"function menuexec(funct)\n{\n funct();\n openmenu();\n}",
"function menu() {\n inquirer.prompt({\n type: \"rawlist\",\n name: \"action\",\n message: \"Please Select:\",\n choices: [\"Add New Department\", \"Add New Role\", \"Add New Employee\", \"View All Employees\", \"View All Roles\", \"View Departments\", \"Change an Employee Role\", \"Exit\"]\n }).then((answer) => {\n switch (answer.action) {\n case \"Add New Department\":\n addDept();\n break;\n\n case \"Add New Role\":\n addRole();\n break;\n\n case \"Add New Employee\":\n addEmpl();\n break;\n\n case \"View All Employees\":\n viewEmpl();\n menu();\n break;\n\n case \"View All Roles\":\n viewRole();\n menu();\n break;\n\n case \"View all Departments\":\n viewDept();\n menu();\n break;\n\n case \"Change an Employee Role\":\n updateEmpl();\n break;\n\n case \"Exit\":\n connection.end();\n console.log(\"Good-Bye\");\n break;\n }\n }).catch(error => {\n if (error) throw error;\n });\n}"
]
| [
"0.73682797",
"0.71567684",
"0.6716586",
"0.6614407",
"0.6611907",
"0.6605272",
"0.65373707",
"0.6526098",
"0.65228325",
"0.65181464",
"0.65119946",
"0.65093666",
"0.64727575",
"0.64674264",
"0.64627934",
"0.64532",
"0.642728",
"0.6413099",
"0.63943297",
"0.6383278",
"0.6378993",
"0.6373217",
"0.6363762",
"0.63624537",
"0.6336131",
"0.6316757",
"0.6268024",
"0.6238818",
"0.6229526",
"0.6219881"
]
| 0.7396062 | 0 |
Asks for an employee id and allows the editing of that employee. | function editEmployee() {
outputEmployeeDetails();
let selectedEmployee = prompt.questionInt('Employee ID: ');
let employee = employees.find(emp => Number(emp.id) == selectedEmployee);
if(employee != undefined) {
console.log('------------------------------------');
console.log('Press enter to keep current value. Any new input will be changed in the employees file.');
var firstName = prompt.question(`First Name (${employee.firstName}): `, { defaultInput: employee.firstName});
var lastName = prompt.question(`Last Name (${employee.lastName}):`, { defaultInput: employee.lastName});
var email = prompt.questionEMail(`Email (${employee.email}): `, { defaultInput: employee.email});
var hourlyWage = prompt.questionInt(`Hourly Wage (${employee.hourlyWage}): `, { defaultInput: employee.hourlyWage});
employee.firstName = firstName;
employee.lastName = lastName;
employee.email = email;
employee.hourlyWage = hourlyWage;
employees[employees.indexOf(employee)] = employee;
outputEmployeeDetails();
} else {
console.log('Employee ID not valid. Please try again.');
editEmployee();
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function editEmployee(id) {\n\t$.get(\"/EmployeeList/\" + id, function (data) {\n\t\t$('#idEmployee').val(data.id);\n\t\t$('#name').val(data.name);\n\t\t$('#job').val(getJobCode(data.job));\n\t});\n\t$('#action').val('Actualitzar');\n\t$('#formType').html('Actualizar');\n}",
"canEdit(id) {}",
"function edit(id) {\r\n\r\n}",
"editEmployee(employee: User) {\n $('#verify-modal').modal('hide');\n this.props.onTeamChange(employee);\n }",
"function employeeEdit() \n{\n // CSS button magic.\n document.getElementById(\"editButton\").disabled = true; \n document.getElementById(\"editButton\").style.visibility = \"hidden\"; \n document.getElementById(\"submitButton\").style.visibility = \"visible\"; \n document.getElementById(\"submitButton\").innerHTML = '<input type=\"submit\" value=\"SUBMIT\">'; \n\n// This will wrap the employee details in editable input fields.\n document.getElementById(\"fullName\").innerHTML = '<input name=\"fullName\" value=\"' + jObj[0][\"fullName\"] + '\">' + '</input>';\n document.getElementById(\"species\").innerHTML = '<input name=\"species\" value=\"' + jObj[0][\"species\"] + '\">' + '</input>';\n document.getElementById(\"age\").innerHTML = '<input name=\"age\" value=\"' + jObj[0][\"age\"] + '\">' + '</input>';\n document.getElementById(\"gender\").innerHTML = '<input name=\"gender\" value=\"' + jObj[0][\"gender\"] + '\">' + '</input>';\n document.getElementById(\"occupation\").innerHTML = '<input name=\"occupation\" value=\"' + jObj[0][\"occupation\"] + '\">' + '</input>';\n document.getElementById(\"ethnicity\").innerHTML = '<input name=\"ethnicity\" value=\"' + jObj[0][\"ethnicity\"] + '\">' + '</input>';\n document.getElementById(\"hair\").innerHTML = '<input name=\"hair\" value=\"' + jObj[0][\"hair\"] + '\">' + '</input>';\n document.getElementById(\"eyes\").innerHTML = '<input name=\"eyes\" value=\"' + jObj[0][\"eyes\"] + '\">' + '</input>';\n}",
"function updateEmployee() {\n inquirer\n .prompt([\n {\n type: \"input\",\n message: \"Enter id of employee you want to update\",\n name: \"empID\"\n },\n {\n type: \"input\",\n message: \"Enter new role ID for the employee\",\n name: \"newRole\"\n }\n ])\n .then(function(answer) {\n connection.query('UPDATE emp SET role_id=? WHERE id= ?',[answer.newRole, answer.empID],function(err, res) {\n if (err) throw err;\n viewEmployees();\n });\n });\n }",
"function edit(edit_id) {\n open_form(APP_STATE.current_function, 'UPDATE', edit_id);\n}",
"function edit_employee_fill(eid){\n\t$('#modal-update-employee').modal('show');\n\t$('#modal-update-employee').find('.modal-title').text('Update Employee');\n\n\t//get employee data using ajax and fill the modal \n\t$.ajax({\n\t\t\turl: '../data/employee_profile.php',\n\t\t\ttype: 'post',\n\t\t\tdataType: 'json',\n\t\t\tdata: {\n\t\t\t\teid : eid\n\t\t\t},\n\t\t\tsuccess: function (data) {\n\t\t\t\tif(data){\n\t\t\t\t\t$('#update-fN').val(data.emp_fname);\n\t\t\t\t\t$('#update-mN').val(data.emp_mname);\n\t\t\t\t\t$('#update-lN').val(data.emp_lname);\n\t\t\t\t\t$('#update-position').val(data.pos_id);\n\t\t\t\t\t$('#update-office').val(data.off_id);\n\t\t\t\t\t$('#update-type').val(data.type_id);\n\n\t\t\t\t\t$('#update-eid').val(eid);\n\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error: L434+ update employee');\n\t\t\t}\n\t\t});\n}",
"function _edit(id) {\n vm.item.userId = id;\n console.log(\"Item ID:\", vm.item.userId);\n $window.location.href = \"/companies/\" + vm.item.userId + \"/edit\";\n }",
"function onSave(e, id) {\r\n e.preventDefault()\r\n setEdit(false)\r\n let { name, email, password, role } = e.target.elements;\r\n name = name.value;\r\n email = email.value;\r\n role = role.value;\r\n password = password.value;\r\n e.target.elements.password.value = '';\r\n fetch('/api/users/editUser', {\r\n method: 'PUT',\r\n body: JSON.stringify({ id, name, email, role, password }),\r\n headers: {\r\n \"Content-Type\": \"application/json\"\r\n }\r\n })\r\n .then(response => response.json())\r\n .then(data => {\r\n if (data.success == true) {\r\n alert('update sucsses');\r\n }\r\n else if (data.success == false) {\r\n alert(data.error)\r\n }\r\n })\r\n }",
"handleEdit(id) {\r\n this.props.history.push(\"/employee/edit/\" + id);\r\n }",
"function onEdit(e) {\r\n e.preventDefault();\r\n setEdit(true)\r\n }",
"function edit(id) {\n getSelectedUser(id);\n // Setting value to hidden element of table. We will use this value to recognize which row fit on edited user\n document.getElementById(\"rowId\").value = id;\n document.getElementById(\"confirmationType\").value = \"edit\";\n modalInformations.style.display = \"block\";\n}",
"updateEmployee(){\n let employee = this.state.activeEmployee;\n EmployeeActions.updateEmployee(employee);\n this.setState({ isEditFormVisible: false });\n }",
"function handleSubmit(id) {\n setIdEdit(id)\n setEdit(true)\n \n }",
"function empDetails(eid) { // fn to display emp details corresponding to emp id\n let empobj = employeeServices.empObject(eid);\n document.getElementById(\"emp-details\").style.visibility = \"visible\";\n document.getElementById(\"abc\").style.visibility = 'hidden';\n document.getElementById(\"update-name\").innerHTML = \"Hi \" + empobj.name;\n document.getElementById(\"emp-id\").value = empobj.id;\n document.getElementById(\"emp-name\").value = empobj.name;\n document.getElementById(\"emp-age\").value = empobj.age;\n document.getElementById(\"emp-state\").value = empobj.state;\n document.getElementById(\"emp-pincode\").value = empobj.pincode;\n}",
"function editOffer(offerId){\n jQuery(\"#id\").val(offerId);\n jQuery(\"#task\").val(\"managecompanyoffer.edit\");\n jQuery(\"#adminForm\").submit();\n}",
"function loadEmployee() \n{\n // CSS magic on the buttons.\n document.getElementById(\"editButton\").innerHTML = '<button type=\"button\" onclick=\"employeeEdit();\">EDIT</button>'; \n document.getElementById(\"editButton\").style.visibility = \"visible\"; \n document.getElementById(\"submitButton\").style.visibility = \"hidden\"; \n \n // Find which employee the user selected.\n getEmp();\n \n // Execute SQL query\n employeeSelect(empId);\n \n // Debugging...\n // document.getElementById(\"debug\").innerHTML = \"You selected: \" + empId;\n\n}",
"async edit ({ params, request, response, view }) {\n }",
"async edit ({ params, request, response, view }) {\n }",
"async edit ({ params, request, response, view }) {\n }",
"async edit ({ params, request, response, view }) {\n }",
"async edit ({ params, request, response, view }) {\n }",
"async edit ({ params, request, response, view }) {\n }",
"function updateEmployee() {\n userService.updateUser(employeeData)\n .then(function (data) {\n if (data.status == 201) {\n $rootScope.$broadcast('new-employee-added');\n $scope.closeModal();\n toaster.pop('success', $filter('translate')('INFORMATION'),\n $filter('translate')('SUCCESSFUL_EDIT_EMPLOYEE'));\n } else {\n toaster.pop('error', $filter('translate')('INFORMATION'),\n $filter('translate')('ERROR_EDIT_EMPLOYEE'));\n }\n });\n }",
"function edit(id)\n{\n\t\tclearErrorMessages();\n\n\t\t// llamada Ajax...\n\t\tajaxCall(httpMethod=\"GET\", \n\t\t\t\t\t\turi=\"${def:actionroot}/edit?id=\" + id , \n\t\t\t\t\t\tdivResponse=null, \n\t\t\t\t\t\tdivProgress=\"status\", \n\t\t\t\t\t\tformName=null, \n\t\t\t\t\t\tafterResponseFn=null, \n\t\t\t\t\t\tonErrorFn=null);\t\n}",
"function editUser (id) {\n username_state = true\n var firstname = _('firstname').value\n var lastname = _('lastname').value\n var middle = _('middlename').value\n var email = _('email').value\n var password = _('password').value\n var institution = _('institution').value\n var level = _('level').value\n var username = _('username').value\n\n if (username != '' && username_state === false) {\n _('username_status').focus()\n } else if (username_state && validatorUpdate.form()) {\n var ajax = ajaxObj('POST', 'userAction')\n ajax.onreadystatechange = function () {\n if (ajaxReturn(ajax) == true) {\n if (ajax.responseText == 'updated') {\n swal('updated!')\n }\n }\n }\n ajax.send(\n 'username=' +\n username +\n '&firstname=' +\n firstname +\n '&middlename=' +\n middle +\n '&password=' +\n password +\n '&email=' +\n email +\n '&institution=' +\n institution +\n '&level=' +\n level +\n '&lastname=' +\n lastname +\n '&id=' +\n id +\n '&edit=edit'\n )\n }\n}",
"handleEdit({ commit }, userSelected) {\n commit('HANDLE_EDIT', userSelected);\n }",
"onEdit(id) {\n this.edit.id = id;\n this.edit.visible = true;\n }",
"function edit(id) {\n let obj = entries[id];\n obj.firstName = $(\"#firstName\").val();\n obj.lastName = $(\"#lastName\").val();\n obj.phone = $(\"#phone\").val();\n obj.civility = $(\"#civility\").val();\n showForm();\n cardDisplay(id);\n display();\n }"
]
| [
"0.7749797",
"0.6743606",
"0.6677951",
"0.6673287",
"0.6648888",
"0.65658367",
"0.65467286",
"0.6511729",
"0.6338376",
"0.6334257",
"0.6270088",
"0.62324846",
"0.62293255",
"0.6196376",
"0.6161916",
"0.6160511",
"0.613893",
"0.6131841",
"0.6127872",
"0.6127872",
"0.6127872",
"0.6127872",
"0.6127872",
"0.6127872",
"0.6119557",
"0.6101935",
"0.60915744",
"0.60577184",
"0.60501534",
"0.60460377"
]
| 0.76465845 | 1 |
Asks for the first name, last name, email and hourly wage for a new employee, saving the data to the employees variable. | function addEmployee() {
let id = findNewEmployeeId();
let firstName = prompt.question("First Name: ");
let lastName = prompt.question("Last Name: ");
let email = prompt.questionEMail("Email: ");
let hourlyWage = prompt.questionInt("Hourly Wage: ");
employees.push({
id,
firstName,
lastName,
email,
hourlyWage
});
console.log('\nNew employee has been added!');
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function submitNewEmployee() {\n createNewEmployee();\n clearInputFields();\n appendEmloyeeArray();\n calculateTotalSalary();\n}",
"function setEmployees() {\n\tlet csvData = readCsv(EMPLOYEE_FILE);\n\tfor(var i = 0; i < csvData.length; i++) {\n\t\temployees.push({\n\t\t\tid: csvData[i][0],\n\t\t\tfirstName: csvData[i][1],\n\t\t\tlastName: csvData[i][2],\n\t\t\temail: csvData[i][3],\n\t\t\thourlyWage: Number(csvData[i][4])\n\t\t});\n\t}\n}",
"function addEmployee() {\n if (eName.value != \"\" && eHours.value != \"\" &&\n ePosition.value != \"\" && eParkingSpotNumberInput.value != \"\")\n {\n console.log(\"Values not empty. Allow creation of new Employee.\");\n\n // set the current employer objects name to the value given\n currentEmployer.name = employerInput.value;\n\n // Creating a variable that holds the value of the employees position converted to lowercase.\n var titleGiven = ePosition.value.toLowerCase();\n var personOrEmployee = null;\n\n // If statement to check if the position title entered is equal to boss.\n if(titleGiven === \"boss\") {\n // If it equals boss a person is created with passed values and saved to my personOrEmployee variable.\n personOrEmployee = new Person(eName.value, ePosition.value, eHours.value);\n }\n // Else for position check.\n else {\n // If the position does not equal boss a new position object is created.\n var position = new Position(ePosition.value, eHours.value);\n console.log(\"Created a new Position class instance: \", position);\n\n // A new employee is created with passed values and saved to my personOrEmployee variable.\n personOrEmployee = new Employee(eName.value, position, eParkingSpotNumberInput.value);\n console.log(\"Created a new Employee class instance: \", personOrEmployee);\n }\n\n console.log(\"Person or Employee object: \", personOrEmployee);\n\n // Pushing new Employee to employees array.\n employees.push(personOrEmployee);\n\n console.log(\"Total employees: \", employees.length);\n console.log(\"New array of employees: \", employees);\n\n displayInfo();\n clearInputs();\n\n eName.focus();\n }\n}",
"function createNewEmployee(){\n //assigning js values to user inputs\n let firstName = $('#firstName').val();\n let lastName = $('#lastName').val();\n let id = $('#id').val();\n let title = $('#title').val();\n let annualSalary = $('#annualSalary').val();\n if(annualSalary === ''){\n annualSalary = 0;\n }\n annualSalary = annualSalary.replace('$','');\n annualSalary = annualSalary.replace(',','');\n //build a new Employee using values assigned ^^\n let freshEmployee = new Employee(firstName,lastName,id,title,annualSalary);\n employeeArray.push(freshEmployee);\n}",
"function createEmployee() {\n\n let firstName = $('#firstName');\n let lastName = $('#lastName');\n let id = $('#id');\n let title = $('#title');\n let salary = $('#salary');\n\n let newEmployee = new employee(firstName.val(), lastName.val(), id.val(), title.val(), salary.val());\n employees.push(newEmployee);\n \n // clear the values of the input fields\n firstName.val('');\n lastName.val('');\n id.val('');\n title.val('');\n salary.val('');\n\n refreshEmployeeTable();\n}",
"function employeeInput() {\n // take in employee information\n const newEmployeeObj = {\n firstName: $('#firstNameInput').val(),\n lastName: $('#lastNameInput').val(),\n idNumber: $('#idNumberInput').val(),\n jobTitle: $('#jobTitleInput').val(),\n annualSalary: $('#annualSalaryInput').val()\n };\n // push to employee array\n employees.push(newEmployeeObj);\n\n // clear user input\n clearUserInput();\n\n} // end employeeInput",
"function insertNewEmployee(projectId, name, jobTitle, workingOn, skill, satisfaction, professionalism){\n //TODO Maybe verify values?\n var newEmployee = {\n projectId: projectId,\n name: name,\n jobTitle: jobTitle,\n workingOn: workingOn, \n skill: skill,\n satisfaction: satisfaction,\n\tprofessionalism: professionalism\n };\n \n //Put in database\n database.insertOneRecord(newEmployee, 'employees');\n \n //Add to assistant\n assistant.addEmployee(newEmployee.name);\n}",
"function addEmployee(){\n let name = document.getElementById(\"name\").value;\n let officeNumber = document.getElementById(\"office_number\").value;\n let telephoneNumber = document.getElementById(\"telephone_number\").value;\n if (name && officeNumber && telephoneNumber){\n employeeList.push({\n name: document.getElementById(\"name\").value,\n officeNum: document.getElementById(\"office_number\").value,\n phoneNum: document.getElementById(\"telephone_number\").value\n });\n viewAllEmployees();\n }else{\n alert (\"All fields must be completed.\")\n }\n}",
"function addEmployee() {\n event.preventDefault();\n alert('Add employee?');\n let newEmployee = {\n firstName: $('#firstNameInput').val(),\n lastName: $('#lastNameInput').val(),\n idNumber: parseInt($('#idNumberInput').val()),\n jobTitle: $('#jobTitleInput').val(),\n annualSalary: parseInt($('#annualSalaryInput').val()),\n };\n employeeObject.push(newEmployee);\n $('#firstNameInput').val('');\n $('#lastNameInput').val('');\n $('#idNumberInput').val('');\n $('#jobTitleInput').val('');\n $('#annualSalaryInput').val('');\n displayEmployee();\n totalSalary();\n console.log('Employee added');\n console.table(employeeObject);\n}",
"function employee(firstName, lastName, idNumber, jobTitle, annualSalary){\n this.firstName = firstName;\n this.lastName = lastName;\n this.idNumber = idNumber;\n this.jobTitle = jobTitle;\n this.annualSalary = annualSalary;\n}",
"function createEmployeeRecord(employee) {\n let emp = {\n firstName: employee[0], \n familyName: employee[1], \n title: employee[2], \n payPerHour: employee[3], \n timeInEvents: [], \n timeOutEvents: []\n }\n return emp\n}",
"function newEmployeeInputs() {\n console.log('in newEmployeeInputs');\n console.log($(this));\n let firstName = $('#first-name').val();\n let lastName = $('#last-name').val();\n let id = $('#id').val();\n let title = $('#title').val();\n let annualSalary = $('#annual-salary').val();\n let salaryNumber = parseInt(annualSalary);\n \n addNewEmployeeObject(firstName, lastName, id, title, annualSalary);\n // empty inputs after click\n $('#first-name').val('');\n $('#last-name').val('');\n $('#id').val('');\n $('#title').val('');\n $('#annual-salary').val('');\n displayEmployeeTable();\n calculateMonthlyCost();\n\n if (firstName === '' || lastName === '' || id === '' || \n title === '' || annualSalary === '') {\n window.alert('Inputs empty! Please enter additonal info.');\n }\n}",
"function Employee(firstName, lastName, emplId, emplTitle, salary) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.emplId = parseInt(emplId);\n this.emplTitle = emplTitle;\n this.salary = parseFloat(salary);\n} // end Employee",
"function save(){\n let empList =[];\n console.log(\"Hello\")\n let name = document.querySelector('#name').value;\n let gender = document.querySelector('input[name=gender]:checked').value;\n let departments = document.querySelectorAll('input[name=dept]:checked');\n let deptArray=[];\n departments.forEach((department)=>{\n deptArray.push(department.value)\n })\n let salary = document.querySelector('#salary').value\n let day = document.querySelector('#day').value\n let month = document.querySelector('#month').value\n let year = document.querySelector('#year').value\n let dateStr = `${day}-${month}-${year}`;\n let parts = dateStr.split('-');\n let startDate = new Date(\n parseInt(parts[2]),\n parseInt(parts[1])-1,\n parseInt(parts[0])\n )\n let notes = document.querySelector('#notes').value\n\n try{\n let employee = new EmployeePayroll(name,gender,deptArray,salary,startDate,notes)\n createLocalStorage(employee);\n saveToDatabase(employee);\n }\n catch (E){\n console.error(E)\n }\n \n}",
"function makeNewEmp(){\n firstName = $('.firstName').val();\n lastName = $('.lastName').val();\n eID = parseInt($('.eID').val());\n jobTitle = $('.jobTitle').val();\n annSal = parseInt($('.annSal').val());\n for (var j = 0; j < employees.length; j++) {\n empArr = employees[j];\n employees[j] = new Employee(firstName, lastName, eID, jobTitle, annSal);\n }\n\n for (var i = 0; i < employees.length; i++) {\n empArr = employees[i];\n mCost = Math.floor(mCost + empArr.annSal / employees.length / 12);\n $('.tBody').append('<tr><td class=\"cellData\">' + empArr.firstName + '</td><td>' + empArr.lastName + '</td><td>' + empArr.eID +\n '</td><td>' + empArr.jobTitle + '</td><td>' + '$' + empArr.annSal + '</td></tr>');\n $('#monCost').replaceWith(\"<h2 id='monCost'>Average Monthly Cost = $\" + mCost + \"</h2>\");\n return mCost;\n }\n}",
"function addEmployee(){\n\t\n\tvar questions = [\n\t\t{\n\t\t\tname: 'employee_name',\n\t\t\ttype: 'input',\n\t\t\tmessage: 'Please enter the name of the employee you wish to add: (0 to cancel)',\n\t\t\tvalidate: function (value) {\n\t\t\t\t// Any value except '0' is valid!\n\t\t\t\tif (value != ''){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t// In case of blanks\n\t\t\t\telse {\n\t\t\t\t\treturn 'Please enter a name to add!';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t];\n\n\tinquirer.prompt(questions).then(function(response) {\n\n\t\t// Add the employee to the list. We add an '\\n' to keep them separated by newlines\n\t\tif(response.employee_name != 0){\n\t\t\tfs.appendFile(m_list_name, ('\\n' + response.employee_name), function (err) {\n\t\t\t if (err) {\n\t\t\t \tthrow err;\n\t\t\t }\n\t\t\t else {\n\t\t\t \tm_employee_array.push(response.employee_name);\n\t\t\t \t// Increment the total number of people\n\t\t\t \tm_total_people++;\n\t\t\t \tconsole.log('Added ' + response.employee_name + ' to the list!\\n');\n\t\t\t }\n\t\t\t});\n\t\t} else {\n\t\t\tconsole.log('Cancelled adding an employee\\n');\n\t\t}\n\t\t// Return to showMenu menu\n\t\tshowMenu();\n\t});\n}",
"function Employee(name, salary, experience) {\n this.name = name;\n this.salary = salary;\n this.experience = experience;\n}",
"function editEmployee() {\n\toutputEmployeeDetails();\n\tlet selectedEmployee = prompt.questionInt('Employee ID: ');\n\tlet employee = employees.find(emp => Number(emp.id) == selectedEmployee);\n\n\tif(employee != undefined) {\n\t\tconsole.log('------------------------------------');\n\t\tconsole.log('Press enter to keep current value. Any new input will be changed in the employees file.');\n\t\tvar firstName = prompt.question(`First Name (${employee.firstName}): `, { defaultInput: employee.firstName});\n\t\tvar lastName = prompt.question(`Last Name (${employee.lastName}):`, { defaultInput: employee.lastName});\n\t\tvar email = prompt.questionEMail(`Email (${employee.email}): `, { defaultInput: employee.email});\n\t\tvar hourlyWage = prompt.questionInt(`Hourly Wage (${employee.hourlyWage}): `, { defaultInput: employee.hourlyWage});\n\n\t\temployee.firstName = firstName;\n\t\temployee.lastName = lastName;\n\t\temployee.email = email;\n\t\temployee.hourlyWage = hourlyWage;\n\n\t\temployees[employees.indexOf(employee)] = employee;\n\t\toutputEmployeeDetails();\n\t} else {\n\t\tconsole.log('Employee ID not valid. Please try again.');\n\t\teditEmployee();\n\t}\n\n}",
"function addNewEmployee() {\n inquirer.prompt([\n {\n name: \"newEmployeeFirstName\",\n type: \"input\",\n message: \"What is the employees first name?\",\n }, {\n name: \"newEmployeeLastName\",\n type: \"input\",\n message: \"What is the employees last name?\",\n }, {\n name: \"newEmployeeID\",\n type: \"input\",\n message: \"What is the employees role ID?\",\n }, {\n name: \"newEmployeeManager\",\n type: \"input\",\n message: \"What is the employees manager ID?\",\n },\n\n ]).then (function(response) {\n connection.query(\"INSERT INTO employee SET ?\", {\n first_name:response.newEmployeeFirstName,\n last_name:response.newEmployeeLastName,\n role_id:response.newEmployeeID,\n manager_id: response.newEmployeeManager\n }, function (err, data) {\n if (err) {\n throw err\n }\n askQuestions(data);\n })\n })\n}",
"function addEmployee() {\n inquirer\n .prompt(questions.generalQuestions)\n .then(generalEmployeeResponse => {\n switch (generalEmployeeResponse.employeeRole) {\n case 'Manager':\n inquirer\n .prompt(questions.managerQuestions)\n .then(managerResponse => {\n const teamMember = new Manager(generalEmployeeResponse.employeeName, generalEmployeeResponse.employeeId, generalEmployeeResponse.employeeEmail, managerResponse.officeNumber);\n teamMembers.push(teamMember);\n askAdditionalEmployee();\n });\n break;\n case 'Engineer':\n inquirer\n .prompt(questions.engineerQuestions)\n .then(engineerResponse => {\n const teamMember = new Engineer(generalEmployeeResponse.employeeName, generalEmployeeResponse.employeeId, generalEmployeeResponse.employeeEmail, engineerResponse.engineerGithub);\n teamMembers.push(teamMember);\n askAdditionalEmployee();\n })\n break;\n case 'Intern':\n inquirer\n .prompt(questions.internQuestions)\n .then(internResponse => {\n const teamMember = new Intern(generalEmployeeResponse.employeeName, generalEmployeeResponse.employeeId, generalEmployeeResponse.employeeEmail, internResponse.internSchool);\n teamMembers.push(teamMember);\n askAdditionalEmployee();\n })\n break;\n }\n })\n}",
"function addEmployee() {\n inquirer.prompt([\n {\n type: 'input',\n message: \"First Name?\",\n name: \"firstName\",\n },\n {\n type: \"input\",\n message: \"Last name?\",\n name: \"lastName\",\n },\n {\n type: \"list\",\n message: \"Employee's role?\",\n name: \"role\",\n choices: roleList\n },\n {\n type: \"list\",\n message: \"Employee's manager?\",\n name: \"manager\",\n choices: employeeList,\n }\n ]).then(function (response) {\n connection.query(\"INSERT INTO employee SET ?\",\n {\n first_name: response.firstName,\n last_name: response.lastName,\n role_id: response.role,\n manager_id: response.manager\n }, function (error) {\n if (error) throw error;\n })\n startProgram();\n })\n}",
"function Employee(name, surname, specialization, salary) {\n\n this.name = name;\n this.surname = surname;\n this.specialization = specialization;\n this.salary = salary;\n}",
"function addYourEmployee(employeeInfo) {\n console.log('woo');\n\n let yourEmployee = {\n firstName: $('#firstNameIn').val(),\n lastName: $('#lastNameIn').val(),\n iDtag: $('#idTagIn').val(),\n title: $('#titleIn').val(),\n annualWages: $('#annualWageIn').val(),\n // add another property here, htmlTag>>>&&&!1\n }\n // new item created here\n\n salaryTable.push(yourEmployee);\n // push newly created item into array\n\n salaryInfoOut();\n\n $('.deleteItem').val('');\n console.log('hi');\n\n}",
"function createEmployee (firstName, lastName, idNumber, jobTitle, annualSalary) {\n let newEmployee = new Employee (firstName, lastName, idNumber, jobTitle, annualSalary);\n employeeList.push(newEmployee);\n console.log(employeeList);\n}",
"function addEmployee(){\n inquirer.prompt([\n {\n type: \"list\",\n name: \"memberChoice\",\n message: \"Which type of team member would you like to add?\",\n choices: [\n \"Engineer\",\n \"Intern\",\n \"I don't want to add any more team members\"\n ]\n }\n ]).then(userChoice => {\n switch (userChoice.memberChoice) {\n case \"Engineer\":\n // begins prompts for an engineer team member\n addEngineer();\n break;\n case \"Intern\":\n // begins prompts for an intern team member\n addIntern();\n break;\n default:\n // outputs the team array to an html \n buildTeam();\n }\n });\n }",
"function Employee(name, salary, exp) {\n this.name = name;\n this.salary = salary;\n this.exp = exp;\n}",
"async function addEmployee() {\n const { employeeType } = await inquirer.prompt({\n name: \"employeeType\",\n message: \"What type of employee would you like to add?\",\n type: \"list\",\n choices: [\"Engineer\", \"Intern\", \"Manager\"],\n });\n // array of the common entries that all employees share\n let commonQuestions = [\n {\n name: \"name\",\n message: \"Enter employee's First Name\",\n type: \"input\",\n },\n {\n name: \"id\",\n message: \"Enter employee's id\",\n type: \"input\",\n },\n {\n name: \"email\",\n message: \"Enter employee's Email\",\n type: \"input\",\n },\n ];\n\n //if engineer prompt for github, and create new engineer,\n if (employeeType === \"Engineer\") {\n const answers = await inquirer.prompt([\n ...commonQuestions,\n {\n name: \"github\",\n message: \"What is your Github name?\",\n type: \"input\",\n },\n ]);\n\n const e = new Engineer(\n answers.name,\n answers.id,\n answers.email,\n answers.github\n );\n employees.push(e);\n //else if intern prompt for school and create intern\n } else if (employeeType === \"Intern\") {\n const answers = await inquirer.prompt([\n ...commonQuestions,\n {\n name: \"school\",\n message: \"What School do you go to?\",\n type: \"input\",\n },\n ]);\n\n const i = new Intern(\n answers.name,\n answers.id,\n answers.email,\n answers.school\n );\n employees.push(i);\n // else assume manager prompt for office, and create manager\n } else {\n const answers = await inquirer.prompt([\n ...commonQuestions,\n {\n name: \"officeNumber\",\n message: \"What is your office number?\",\n type: \"input\",\n },\n ]);\n const m = new Manager(\n answers.name,\n answers.id,\n answers.email,\n answers.officeNumber\n );\n employees.push(m);\n }\n // prompt to run the CLI and create employee\n const { shouldCreateEmployee } = await inquirer.prompt({\n name: \"shouldCreateEmployee\",\n message: \"Create new employee?\",\n type: \"confirm\",\n });\n\n return shouldCreateEmployee;\n}",
"function addEmployee(){\n console.log( 'in addEmployee' );\n // takes in input from user ${firstName}; <-----\n let newObject = {\n firstName: $( '#firstName' ).val(),\n lastName: $( '#lastName' ).val(),\n ID: $( '#ID' ).val(),\n title: $( '#title' ).val(),\n annualSalary: $( '#annualSalary' ).val()\n }\n employees.push(newObject);\n console.log(employees);\n // push employee object to DOM\n // could do\n $( '.body' ).append(`<tr id=\"row\"></tr><td>${newObject.firstName}</td><td>${newObject.lastName}</td><td>${newObject.ID}</td><td>${newObject.title}</td><td>${newObject.annualSalary}</td><td><button id=\"deleteRow\" onclick=\"deleteEntry(this)\">Delete</button></td>`);\n // update DOM\n // could use .empty() to empty\n monthly += Number(((newObject.annualSalary)/12));\n $( '#totalMonthly' ).text(`Total Monthly: ${monthly}`);\n \n if( monthly > 20000){\n $( '#totalMonthly' ).replaceWith(`<h2 class=\"red\" id=\"totalMonthly\">Total Monthly: ${monthly} </h2>`);\n console.log('in monthly');\n }// can do addClass and removeClass to add and remove .red instead of this\n}",
"function askAdditionalEmployee() {\n inquirer\n .prompt(questions.addEmployeeQuestion)\n .then(addEmployeeResponse => {\n addEmployeeResponse.addMoreEmployee ? addEmployee() : renderHTML(teamMembers);\n });\n}",
"function employee(name,salary,experience){\r\n this.name=name;\r\n this.salary=salary;\r\n this.experience=experience;\r\n\r\n}"
]
| [
"0.70700675",
"0.68909585",
"0.68107915",
"0.67175716",
"0.6676222",
"0.6637184",
"0.6545055",
"0.6515495",
"0.64712745",
"0.64204776",
"0.6387482",
"0.6385797",
"0.63852835",
"0.63647324",
"0.6344634",
"0.6342207",
"0.6334425",
"0.63334304",
"0.63319343",
"0.62406933",
"0.62380636",
"0.62261325",
"0.62158424",
"0.621042",
"0.6206819",
"0.62057066",
"0.6188415",
"0.61676234",
"0.61076885",
"0.61067796"
]
| 0.7337414 | 0 |
Asks for an employee id and then removes that employee from the employees variable. | function removeEmployee() {
console.log('--------------------------------------------');
outputEmployeeDetails();
let selectedEmployee = prompt.questionInt('\nEmployee ID: ');
let employee = employees.find(emp => Number(emp.id) == selectedEmployee);
if(employee == undefined) {
console.log('Employee ID invalid. Please try again.');
removeEmployee();
} else {
employees.splice(employees.indexOf(employee), 1);
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function removeEmployee() {\n inquirer.prompt([\n { name: \"id\", message: \"What is the employee's id number?\", type: \"input\" }\n ]).then((answer) => {\n connection.query(`DELETE FROM employee WHERE ?`,\n {\n id: answer.id\n },\n (err) => {\n if (err)\n throw err;\n console.table(`Employee removed`);\n promptUser();\n }\n );\n });\n}",
"function removeEmployee() {\n connection.query(\"SELECT * FROM employee\", (err, res) => {\n if (err) throw err;\n const employees = res.map(object => {\n return {\n name: `${object.firstname} ${object.lastname}`,\n value: object.id,\n };\n });\n inquirer\n .prompt([\n {\n name: \"employee\",\n type: \"list\",\n message: \"Which employee would you like to remove?\",\n choices: employees,\n },\n ])\n .then(function(answer) {\n connection.query(\n \"DELETE FROM employee WHERE ?\",\n [\n {\n id: answer.employee,\n },\n ],\n function(err) {\n if (err) throw err;\n },\n console.log(\"The employee was removed from the database!\"),\n start(),\n );\n });\n });\n}",
"function removeEmployee(employeeId) {\n employeeList = employeeList.filter(value => {\n return value[2] != employeeId;\n });\n populateTable();\n}",
"function removeEmployee() {\n\tvar questions = [\n\t\t{\n\t\t\tname: 'employeeName',\n\t\t\ttype: 'input',\n\t\t\tmessage: 'Enter an employee to exclude from the lunch groups: (0 to cancel)\\n',\n\t\t\tvalidate: function (employeeName) {\n\t\t\t\tif(employeeName == ''){\n\t\t\t\t\treturn console.log('\\nPlease enter a name\\n');\n\t\t\t\t} \n\t\t\t\telse {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t];\n\n\tinquirer.prompt(questions).then(function(response) {\n\t\tif(response.employeeName != 0){\n\t\t\tvar index = m_employee_array.indexOf(response.employeeName);\n\t\t\tif(index !== -1) {\n\t\t\t\t// Delete one instance of that name\n\t\t\t\tm_employee_array.splice(index, 1);\n\t\t\t\tconsole.log(\"Successfully removed \" + response.employeeName + \"!\");\n\t\t\t\t\n\t\t\t\t//Reduce people count\n\t\t\t\tm_total_people--;\n\n\t\t\t} else {\n\t\t\t\tconsole.log(response.employeeName + \" was not found...\");\n\t\t\t}\n\t\t} else {\n\t\t\tconsole.log(\"Cancelled removing an employee\\n\");\n\t\t}\n\n\t\tshowMenu();\n\t});\n}",
"function removeEmployee() {\n\n inquirer.prompt([\n {\n type: \"list\",\n message: \"Select Employee you wish to remove\",\n choices: employees,\n name: \"id\"\n }\n ]).then(answer => {\n connection.query(\"DELETE FROM employee WHERE id = ?\", answer.id, function (err, results) {\n if (err) {\n console.log(err);\n throw err\n }\n })\n employeeCall();\n restartQuestions();\n })\n}",
"async function removeEmployee () {\n const revEmployee = await db.findAllEmployees ();\n const employeeChoices = revEmployee.map(({ id, title }) => ({\n name: title,\n value: id\n }));\n const { employeeId } = await prompt ([\n {\n type: 'list',\n name: 'employeedId', \n message: 'Delete employee',\n choices: employeeChoices\n }\n ]);\n await db.deleteEmployee(employeeId);\n}",
"function removeEmployee(id) {\n return connection.query(\"DELETE FROM employee WHERE id = ?\", [id]);\n}",
"function deleteEmployee() {\n\tvar personID = prompt(\"Please enter the ID number of the employee you wish to delete\");\n\tvar deletedEmployee;\n\tfor(employee in employeeLog){\n\t\tif(employeeLog[employee].idNo==personID){\n\t\t\tdeletedEmployee = employeeLog[employee];\n\t\t\temployeeLog.splice(employee,1); //removes that employee from the array\n\t\t}\n\t}\n\tif (deletedEmployee == undefined){\n\t\talert(\"No employee has that ID Number!\");\n\t\treturn;\n\t}\n\tvar id = deletedEmployee.idNo;\n\tvar employee = '#employee' + id;\n\t$(employee).remove();\n\tconsole.log(\"Here is the new employee log\", employeeLog);\n}",
"function deleteEmployee() {\n\tconsole.log(\"Deleting an employee\");\n\n\tvar query = `SELECT e.id, e.first_name, e.last_name\n FROM employee e`;\n\n\tconnection.query(query, function (err, res) {\n\t\tif (err) throw err;\n\t\t// Select Employee to remove\n\t\tconst deleteEmployeeChoices = res.map(({ id, first_name, last_name }) => ({\n\t\t\tvalue: id,\n\t\t\tname: `${id} ${first_name} ${last_name}`,\n\t\t}));\n\n\t\tinquirer\n\t\t\t.prompt(prompt.deleteEmployeePrompt(deleteEmployeeChoices))\n\t\t\t.then(function (answer) {\n\t\t\t\tvar query = `DELETE FROM employee WHERE ?`;\n\t\t\t\t// after prompting, remove item from the db\n\t\t\t\tconnection.query(query, { id: answer.employeeId }, function (err, res) {\n\t\t\t\t\tif (err) throw err;\n\n\t\t\t\t\tconsole.log(\"\\n\" + res.affectedRows + \" employee deleted\");\n\t\t\t\t\tconsole.log(\"\\n-------------------------------------------------\\n\");\n\n\t\t\t\t\tfirstPrompt();\n\t\t\t\t});\n\t\t\t});\n\t});\n}",
"function removeEmployee() {\n inquirer.prompt({\n type: \"input\",\n message: \"Enter ID of employee to remove\",\n name: \"empID\"\n }).then(function(answer){\n // let value = [answer.empID];\n connection.query(\"DELETE FROM emp WHERE id = ?\", [answer.empID], function(err, res) {\n if (err) throw err;\n viewEmployees();\n })\n })\n}",
"function deleteEmployee(){\n connection.query(\"SELECT * FROM employees\", function(err, results) {\n if (err) throw err;\n inquirer\n .prompt([{\n name: \"employeeId\",\n type: \"list\",\n choices: results.map(employee=>\n {return {name: employee.first_name+\" \"+employee.last_name, value: employee.id} })\n \n }])\n\n .then(function(answer) {\n connection.query(\n \"Delete From employees WHERE ? \",\n [\n {\n id: answer.employeeId\n }\n ],\n function(error) {\n if (error) throw err;\n console.log(\"Employee removed.\");\n start();\n }\n );\n })\n })\n}",
"function RemoveEmployee() {\n connection.query('SELECT * FROM employee', function (err, res) {\n if (err) throw err;\n inquirer\n .prompt([\n {\n name: 'employee_name',\n type: 'list',\n message: 'Which employee do you want to update?',\n choices: [\n ...res.map(({ employee_id, first_name, last_name }) => ({\n name: first_name + ' ' + last_name,\n value: {\n name: first_name + ' ' + last_name,\n employee_id\n }\n }))\n ]\n }\n ])\n .then(function (answer) {\n var queryValidateRole = \"SELECT * FROM employee\";\n connection.query(queryValidateRole, function (err, res) {\n\n // console.log(\"empID: \",employeeID);\n var queryDelete = \"DELETE FROM employee WHERE employee_id = ?\";\n connection.query(queryDelete, answer.employee_name.employee_id, function (err, result) {\n if (err) throw err;\n displayEmployees();\n });\n });\n });\n });\n}",
"function deleteEmployee() {\n connection.query(\"SELECT * FROM employee\", function(err, res) {\n if (err) throw err;\n\n var emArr = res;\n var allEmployees = [];\n for (var i = 0; i < emArr.length; i++) {\n allEmployees.push(emArr[i].first_name + \" \" + emArr[i].last_name);\n }\n\n inquirer.prompt([\n {\n name: \"employeeName\",\n type: \"list\",\n message: \"Please select the employee you need to remove:\",\n choices: allEmployees\n }\n ]).then(function(answer) {\n var employeeID;\n for (var j = 0; j < res.length; j++) {\n if (res[j].first_name + \" \" + res[j].last_name === answer.employeeName) {\n employeeID = res[j].id;\n }\n }\n\n connection.query(\"DELETE FROM employee WHERE ?\",\n {\n id: employeeID\n },\n function(err, res) {\n if (err) throw err;\n console.log(\"Employee is removed.\");\n runSearch();\n }\n );\n });\n });\n}",
"function deleteEmp(id) {\n console.log(\"Deleting...\\n\");\n intId = parseInt(id);\n connection.query(\n \"DELETE FROM employee WHERE ?\",\n {\n id: intId,\n },\n function(err, res) {\n if (err) throw err;\n console.log(res.affectedRows + \" deleted!\\n\");\n\n }\n );\n homePg();\n }",
"function deleteEmployee(employee){\n connection.query(`DELETE FROM employees WHERE id = ${employee};`, function(err, res) {\n if (err) {\n throw err;\n }\n else{\n console.log(`${res.affectedRows} record(s) deleted`);\n populateEmployees();\n }\n });\n return;\n}",
"function deleteEmployees() {\n inquirer.prompt(\n {\n type: \"list\",\n message: \"Which employee would you like to delete?\",\n name: \"deleteEmp\",\n choices: () => arrays.empArray,\n loop: false\n }\n ).then(res => {\n // Extract ID from string passed into empArray.\n let empID = parseInt(res.deleteEmp.split(\")\")[0]);\n connection.query(\"DELETE FROM employee WHERE id = ?\", [empID], (err) => {\n if (err) throw err;\n\n // Empty emp array before pushing into it again\n arrays.empArray.length = 0;\n // Run push again as new values have been added to the emp_role table\n pushEmpsIntoArray();\n\n start();\n }) \n }) \n}",
"function deleteEmployee(emp_name) {\n // delete given employees\n query = \"DELETE FROM employees WHERE CONCAT(first_name, ' ', last_name) = ?;\";\n connection.query(query, emp_name, function(err, res) {\n if (err) console.log(err);\n console.log(\"\\n\\n\" + emp_name + \" was successfully deleted.\");\n });\n\n findEmployees(); // update employeeList \n findMgrs(); // update mgrs, in case a manager was deleted.\n} // end of deleteEmployee",
"function removeEmployee() {\n var query = \"SELECT first_name, last_name FROM employees\"\n connection.query(query, function (err, res) {\n if (err) throw err;\n inquirer.prompt([\n {\n name: \"employee\",\n type: \"rawlist\",\n message: \"Select which employee you would like to delete.\",\n choices: function () {\n var choiceArray = [];\n res.forEach(employee => {\n choiceArray.push(employee.first_name)\n })\n return choiceArray;\n }\n }\n ]).then((response) => {\n connection.query(\"DELETE FROM employees WHERE first_name = ?\", [response.employee], function(err, res) {\n console.log(\"Succesfully deleted.\");\n start();\n });\n });\n });\n}",
"function removeEmp() {\n inquirer\n .prompt([\n {\n type: \"list\",\n message: \"Please confirm that you wish to remove an employee.\",\n name: \"confirm\",\n choices: [\"Yes\", \"No\"],\n },\n {\n type: \"list\",\n message: \"Which employee do you wish to remove?\",\n name: \"remove\",\n choices: getEmpArray(),\n when: (answer) => answer.confirm === \"Yes\",\n },\n ])\n .then((res) => {\n if (res.confirm === \"No\") {\n initApp();\n } else {\n let employeeID = res.remove.id;\n connection.query(\n \"DELETE FROM employee WHERE id = ?\",\n [employeeID],\n (err, result) => {\n if (err) throw err;\n console.log(\n `${res.remove.first_name} ${res.remove.last_name} was successfully removed from the database.`\n );\n initApp();\n }\n );\n }\n })\n .catch((err) => {\n if (err) throw err;\n });\n}",
"function removeEmployee() {\n connection.query(`\n SELECT\n e.id, \n e.first_name AS First,\n e.last_name AS Last,\n r.title AS Title,\n d.department_name AS Department,\n r.salary AS Salary,\n CONCAT(m.first_name, \" \",m.last_name) AS Manager\n\n FROM employees e \n LEFT JOIN roles r ON e.role_id = r.id\n LEFT JOIN departments d ON r.department_id = d.id\n LEFT JOIN employees m ON e.manager_id = m.id\n ORDER BY e.id\n `,\n function(err, res) {\n if (err) throw err;\n console.table(res);\n\n // prompts user which employee they'd like to remove while being displayed a table as a reference guide\n inquirer.prompt({\n type: \"list\",\n name: \"employee\",\n message: \"Select an employee to remove:\",\n choices: function() {\n let employeeArray = [];\n for (let i = 0; i < res.length; i++) {\n employeeArray.push(`${res[i].First} ${res[i].Last}`);\n };\n return employeeArray;\n },\n }).then((data) => {\n let name = data.employee.split(\" \");\n\n let removefirstName = name[0];\n let removelastName = name[1];\n\n // query that removes the employee from the database by the first and last name\n connection.query(\"DELETE FROM employees WHERE ? AND ?\", [{\n first_name: removefirstName,\n\n }, {\n last_name: removelastName\n }],\n console.log(chalk.yellow(`Employee ${removefirstName} ${removelastName} has been removed`)),\n (err, res) => {\n if (err) throw err;\n return res;\n });\n begin();\n });\n });\n}",
"function removeEmployee() {\n let employeeArr = [];\n let query = \"SELECT employee.first_name, employee.last_name, departments.department\";\n query += \" FROM employee INNER JOIN role ON (employee.role_id = role.id) INNER JOIN departments ON (role.department_id = departments.id)\";\n query += \" ORDER BY employee.last_name\"\n connection.query(query, function (err, res){\n if (err) throw err; \n console.table(res);\n for (i = 0; i < res.length; i++){\n employeeArr.push(res[i].last_name); \n } \n inquirer.prompt([\n {\n type: \"list\",\n message: \"Which employee do you want to remove?\",\n choices: employeeArr,\n name: \"last_name\"\n }\n ]).then(function(response){ \n var query = \"DELETE FROM employee WHERE (?)\"; \n connection.query(query, response, function (err, res){\n if (err) throw err;\n console.log(res.affectedRows + \" Employee Deleted Succesfully\\n\");\n promptUser();\n })\n })\n })\n}",
"removeEmployee(id){\n let ourWorker = this.underlings;\n let index = ourWorker.findIndex();\n this.underlings.splice(index, 1);\n }",
"async deleteEmployee(e) {\n let employee_id = await this.db.query(`SELECT id FROM employees WHERE CONCAT(first_name, \" \", last_name)=\"${e.employee_name}\"`);\n employee_id = Object.values(employee_id[0][0])[0];\n\n await this.db.query(`DELETE FROM employees WHERE id = ${employee_id}`);\n console.log(`>>> Employee '${e.employee_name}' removed from db.\\n`);\n }",
"async function deleteEmployee() {\n const delEmp = await connection.query(\"SELECT id, first_name, last_name FROM employee\")\n const employeeChoices = delEmp.map(employee => ({\n name: `${employee.first_name} ${employee.last_name}`,\n value: employee.id\n }))\n\n const employeeId = await\n inquirer.prompt(\n {\n type: \"list\",\n name: \"eName\",\n message: \"Select the employee you want to delete:\",\n choices: employeeChoices\n })\n\n await connection.query(\"DELETE from employee where id=?\", [employeeId.eName]);\n console.log(\"Awesome! You have successfully deleted an employee!\")\n viewEmployees();\n}",
"function removeEmployee(){\n connection.query(\"SELECT * FROM employees\", function(err, results){\n inquirer.prompt({\n type: \"list\",\n message: \"Which employee would you like to remove?\",\n name: \"removeEmployee\",\n choices: function(){\n removeArray = [];\n for(let i = 0; i < results.length; i++){\n removeArray.push(`${results[i].first_name} ${results[i].last_name}`)\n \n }\n \n return removeArray;\n }\n }).then(answers => {\n //Used split method to split the employee name into an array, so the first and last name are available as separate values for DELETE query\n var nameSplit = answers.removeEmployee.split(\" \");\n \n connection.query(`DELETE FROM employees WHERE first_name = \"${nameSplit[0]}\" AND last_name = \"${nameSplit[1]}\" `, function(err, results){\n if (err) throw err;\n console.log(\"\\n Employee removed from system!\\n\");\n init();\n })\n })\n })\n}",
"function deleteEmployee() {\n inquirer.prompt([\n {\n name: \"deleteEmployee\",\n type: \"input\",\n message: \"What employee would you like to delete?\", \n\n validate: function(value) {\n if (isNaN(value) === false) {\n return true;\n }\n return false;\n }\n }\n ])\n //when finished prompting, insert into the DB\n .then(function(answer) {\n connection.query(\n \"DELETE FROM employee SET ?\",\n {\n deleteEmployee: answer.item\n },\n function(err) {\n if (err) throw err;\n console.log(\"You deleted an employee\")\n start();\n }\n );\n });\n}",
"function removeEmployee() {\n let employees = [];\n connection.query(\n \"SELECT * FROM employee ORDER BY last_name\",\n function (err, res) {\n if (err) throw err;\n for (i = 0; i < res.length; i++) {\n employees.push(res[i].first_name + \" \" + res[i].last_name);\n }\n inquirer.prompt({\n name: \"removeemployee\",\n type: \"list\",\n message: \"Select the employee you wish to remove.\",\n choices: employees\n }).then(function (answer) {\n let values = answer.removeemployee.split(\" \");\n let employeeFirstName = values.shift();\n let employeeLastName = values.join(' ');\n inquirer.prompt({\n name: \"confirmEmpDelete\",\n type: \"list\",\n message: \"\\n Are you sure you want to delete employee: \" + employeeLastName + \", \" + employeeFirstName + \"?\",\n choices: [\"Yes\", \"No\"]\n }).then(function (answer) {\n if (answer.confirmEmpDelete === \"No\") {\n console.log(\"\\n ! DELETION CANCELLED.\");\n restartApp();\n } else {\n connection.query(\n \"DELETE FROM employee WHERE first_name = ? AND last_name = ?\",\n [employeeFirstName, employeeLastName],\n function (err, res) {\n if (err) throw err;\n if (res.affectedRows === 0) {\n console.log(\"\\n ! ERROR deleting employee - please try again.\");\n } else {\n console.log(\"\\n $ SUCCESS deleted employee \" + employeeLastName + \", \" + employeeFirstName + \".\");\n restartApp();\n }\n });\n }\n });\n });\n });\n}",
"async function removeEmployee(event) {\n const id3 = event.target.getAttribute('data-id');\n const projectId = window.location.toString().split('/')[window.location.toString().split('/').length - 1];\n\n const response = await fetch(`/api/projects/remove/employee/${id3}`, {\n method: 'DELETE',\n body: JSON.stringify({ projectId }),\n headers: { 'Content-Type': 'application/json' }\n });\n\n if (response.ok) {\n document.location.replace(`/project/${projectId}`);\n } else {\n alert(response.statusText);\n }\n}",
"function removeEmployee() {\n let query = \"SELECT * FROM employee\";\n connection.query(query, function (err, res) {\n if (err) throw err;\n inquirer\n .prompt([\n {\n type: \"list\",\n message: \"Wich employee would you like to remove?\",\n name: \"choice\",\n choices: () => {\n let choicesArray = [];\n for (let i = 0; i < res.length; i++) {\n choicesArray.push(`${res[i].id} ${res[i].first_name} ${res[i].last_name}`);\n }\n return choicesArray;\n },\n }\n ])\n .then(function (answer) {\n const choice = answer.choice.split(\" \");\n const query = `DELETE FROM employee WHERE id = ${choice[0]}`;\n connection.query(query, function (err, res) {\n if (err) throw err;\n console.log(\"The employee has been deleted successfully!\");\n // call start function\n start();\n });\n });\n });\n\n}",
"async destroy(employee) {\n await axios.delete(`api/employees/${ employee.id }`);\n const employees = this.state.employees.filter(e => e.id !== employee.id);\n this.setState({ employees });\n }"
]
| [
"0.83639777",
"0.79515076",
"0.78371066",
"0.78334564",
"0.7747903",
"0.77362865",
"0.7709219",
"0.76958114",
"0.76894057",
"0.7684224",
"0.74126005",
"0.7367422",
"0.7268901",
"0.7211148",
"0.72015595",
"0.7141625",
"0.7065506",
"0.694101",
"0.68871045",
"0.67735505",
"0.6755781",
"0.67435104",
"0.6740309",
"0.67157584",
"0.67154837",
"0.66881675",
"0.66844976",
"0.6622063",
"0.6599665",
"0.6548214"
]
| 0.8668633 | 0 |
Parse daytime to string. Ex: [8, 30] > '8:30' | function time2string( /**Array */ daytime) {
assert(isNumber(daytime[0]) && isNumber(daytime[1]), 'Invalid arguments in time2string()');
return daytime[0] + ':' + (daytime[1] < 10 ? '0' : '') + daytime[1];
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function parseDayAndTime(dayAndTime) {\n var elts = dayAndTime.split(\"\");\n\n var days = {\n \"M\": \"Monday\",\n \"T\": \"Tuesday\",\n \"W\": \"Wednesday\",\n \"R\": \"Thursday\",\n \"F\": \"Friday\",\n \"S\": \"Saturday/Sunday\"\n }\n\n var times = {\n \"8\": \"8 am\",\n \"9\": \"9 am\",\n \"10\": \"10 am\",\n \"11\": \"11 am\",\n \"12\": \"12 pm\",\n \"13\": \"1 pm\",\n \"14\": \"2 pm\",\n \"15\": \"3 pm\",\n \"16\": \"4 pm\",\n \"17\": \"5 pm\",\n \"18\": \"6 pm\",\n \"19\": \"7 pm\",\n \"20\": \"8 pm\",\n \"21\": \"9 pm\"\n }\n\n return days[elts[0]] + \", \" + times[dayAndTime.slice(1, dayAndTime.length)]\n}",
"function parseTime(t) {\n var days = Math.floor(t / 24 / 60);\n var hours = Math.floor(t / 60 % 24);\n var minutes = Math.floor(t % 60);\n var timeString = (days > 0 ? days + \" days, \" : \"\") + (hours > 0 ? hours + \" hours, \" + (minutes < 10 ? \"0\" : \"\") : \"\") + minutes + \" minutes\"\n return timeString;\n}",
"function convertTime(times){\n let res = \"\"\n for (let i = 0; i < times.length; i ++){\n let time = times[i]\n let specific = time.split(\"-\")\n day = parseInt(specific[0])\n res += \"<span class='time'>\" + days[day] + \" \" + specific[1] + \":00 - \"\n res += specific[2] + \":00\" + \"</span><br>\"\n\n }\n return res\n}",
"parseTime( time ) {\n // console.log(time);\n // convert string to array\n let arrTime = time.split('');\n // console.log( arrTime );\n // find index of 'T'\n const indexStart = arrTime.findIndex( el => el === 'T' );\n // console.log( indexStart );\n // find index of '.'\n const indexEnd = arrTime.findIndex( el => el === '.' );\n // console.log( indexEnd );\n // use slice to create an array with the time\n arrTime = arrTime.slice( indexStart + 1, indexEnd );\n // console.log( arrTime );\n // convert the array with the time into a string\n arrTime = arrTime.toString();\n // console.log(arrTime);\n // remove commas\n arrTime = arrTime.replace( /,/gi, '' );\n // console.log(arrTime);\n // convert string into an array where each element is the hour the minute and the second\n arrTime = arrTime.split(':');\n // console.log(arrTime);\n // format time\n return this.formatTime( arrTime[0], arrTime[1] );\n }",
"function timeConverter(dayTime) {\n let result = \"\";\n const time = dayTime.split(\":\");\n const hours = time[0];\n const minutes = time[1].slice(0, 2);\n\n if (dayTime.includes(\"p.m.\")) {\n if (parseInt(hours, 10) >= 1 && parseInt(hours, 10) < 12) {\n result += (parseInt(hours, 10) + 12).toString();\n } else {\n result += hours;\n }\n } else if (dayTime.includes(\"a.m\")) {\n if (parseInt(hours, 10) <= 10) {\n result += \"0\" + hours;\n } else if (parseInt(hours, 10) === 12) {\n result += \"00\";\n } else {\n result += hours;\n }\n }\n result += \":\" + minutes;\n return result;\n}",
"function getTimeString(time) {\n //use dayjs to parse the time\n const start = dayjs(time.start_time)\n const end = dayjs(time.end_time)\n //convert to string\n const startStr = start.format('MM/DD/YYYY hh:mm A')\n const endStr = end.format(start.isSame(end,'day') ? 'hh:mm A' :'MM/DD/YYYY hh:mm A')\n //return a string like \"10:00-12:00\"\n return `${startStr} to ${endStr}`\n}",
"static parseDateDays(time) {\n const date = new Date(time);\n\n function addLeadingZero(num) {\n return (\"0\" + num).slice(-2);\n }\n\n const day = addLeadingZero(date.getDate());\n const month = addLeadingZero(date.getMonth() + 1);\n const year = date.getFullYear();\n\n const dateString = `${day}/${month}/${year}`;\n\n return dateString;\n }",
"function timestrShort(time) {\r\n time = parseInt (time);\r\n if (time > 86400){\r\n var m = [];\r\n time /= 3600;\r\n m.push (parseInt(time/24));\r\n m.push ('d ');\r\n m.push (parseInt(time%24));\r\n m.push ('h ');\r\n return m.join (''); \r\n } else\r\n return timestr (time);\r\n}",
"function timestrShort(time) {\r\n time = parseInt (time);\r\n if (time > 86400){\r\n var m = [];\r\n time /= 3600;\r\n m.push (parseInt(time/24));\r\n m.push ('d ');\r\n m.push (parseInt(time%24));\r\n m.push ('h ');\r\n return m.join (''); \r\n } else\r\n return timestr (time);\r\n}",
"function dateToDayTime(val) {\n var dayTime = val.split(\":\");\n var dayTimeVal;\n if (dayTime[0] / 24 >= 1) {\n dayTimeVal = \"DAY +\" + Math.floor(dayTime[0] / 24) + ((dayTime[0] % 24) < 10 ? \" 0\" + dayTime[0] % 24 : \" \" + dayTime[0] % 24) + \":\" + dayTime[1] + \":\" + dayTime[2];\n } else {\n dayTimeVal = val;\n }\n return dayTimeVal;\n}",
"function dateToDayTime(val) {\n var dayTime = val.split(\":\");\n var dayTimeVal;\n if (dayTime[0] / 24 >= 1) {\n dayTimeVal = \"DAY +\" + Math.floor(dayTime[0] / 24) + ((dayTime[0] % 24) < 10 ? \" 0\" + dayTime[0] % 24 : \" \" + dayTime[0] % 24) + \":\" + dayTime[1] + \":\" + dayTime[2];\n } else {\n dayTimeVal = val;\n }\n return dayTimeVal;\n}",
"function dateToDayTime(val) {\n var dayTime = val.split(\":\");\n var dayTimeVal;\n if (dayTime[0] / 24 >= 1) {\n dayTimeVal = \"DAY +\" + Math.floor(dayTime[0] / 24) + ((dayTime[0] % 24) < 10 ? \" 0\" + dayTime[0] % 24 : \" \" + dayTime[0] % 24) + \":\" + dayTime[1] + \":\" + dayTime[2];\n } else {\n dayTimeVal = val;\n }\n return dayTimeVal;\n}",
"function timestr(time, full) {\r\n time = parseInt (time);\r\n var m = [];\r\n var t = time;\r\n if (t < 61)\r\n return t + 's';\r\n if (t > 86400){\r\n m.push (parseInt(t/86400));\r\n m.push ('d ');\r\n t %= 86400;\r\n } \r\n if (t>3600 || time>3600){\r\n m.push (parseInt(t/3600));\r\n m.push ('h ');\r\n t %= 3600;\r\n } \r\n m.push (parseInt(t/60));\r\n m.push ('m');\r\n if (full || time<=3600 ){\r\n m.push (' ');\r\n m.push (t%60);\r\n m.push ('s'); \r\n }\r\n return m.join ('');\r\n}",
"function timestr(time, full) {\r\n time = parseInt (time);\r\n var m = [];\r\n var t = time;\r\n if (t < 61)\r\n return t + 's';\r\n if (t > 86400){\r\n m.push (parseInt(t/86400));\r\n m.push ('d ');\r\n t %= 86400;\r\n } \r\n if (t>3600 || time>3600){\r\n m.push (parseInt(t/3600));\r\n m.push ('h ');\r\n t %= 3600;\r\n } \r\n m.push (parseInt(t/60));\r\n m.push ('m');\r\n if (full || time<=3600 ){\r\n m.push (' ');\r\n m.push (t%60);\r\n m.push ('s'); \r\n }\r\n return m.join ('');\r\n}",
"function parse_time(string){\n var date = Date.parse(string)\n if (date) {\n function f(n) {\n return n < 10 ? '0' + n : n;\n }\n\n return [f(date.getHours()), f(date.getMinutes()), f(date.getSeconds())].join(':');\n } else return null\n}",
"function timeConversion(s) {\n let timeArr = [];\n let convertedArr = [];\n if(s.includes('PM') || s.includes('pm')){\n timeArr = s.split(/[^0-9]/);\n let n = timeArr.length;\n for(let i = 0; i<n;i++){\n if(timeArr[i] == '12'){\n convertedArr.push('12');\n }\n else if(timeArr[i] === timeArr[0]){\n convertedArr.push(Number(timeArr[0])+12);\n }else if(timeArr[i] != ''){\n convertedArr.push(timeArr[i]);\n }\n }\n return convertedArr.join(':');\n }else{\n timeArr = s.split(/[^0-9]/);\n let n = timeArr.length;\n for(let i = 0; i<n;i++){\n if(timeArr[i] == '12'){\n convertedArr.push('00');\n }else if(timeArr[i] != ''){\n convertedArr.push(timeArr[i]);\n }\n }\n return convertedArr.join(':')\n }\n \n}",
"function toTimeStr(timeLst){\n let res = '';\n for (let i=0;i<timeLst.length;i++){\n let subLst = timeLst[i].split(\"-\");\n switch(subLst[0]) {\n case '1':\n res += 'M';\n break;\n case '2':\n res += 'T';\n break;\n case '3':\n res += 'W';\n break;\n case '4':\n res += 'TH';\n break;\n default:\n res += 'F';\n break;\n }\n res+=subLst[1]+\"-\"+subLst[2];\n res+=\", \"\n }\n return res.slice(0,-2);\n}",
"function timestr(time, full) {\r\n time = parseInt (time);\r\n var m = [];\r\n var t = time;\r\n if (t < 61)\r\n return t + 's';\r\n if (t > 86400){\r\n m.push (parseInt(t/86400));\r\n m.push ('d ');\r\n t %= 86400;\r\n }\r\n if (t>3600 || time>3600){\r\n m.push (parseInt(t/3600));\r\n m.push ('h ');\r\n t %= 3600;\r\n }\r\n m.push (parseInt(t/60));\r\n m.push ('m');\r\n if (full || time<=3600 ){\r\n m.push (' ');\r\n m.push (t%60);\r\n m.push ('s');\r\n }\r\n return m.join ('');\r\n}",
"convertTimes(time) {\n console.log(\"== Grid: convertTimes ==\");\n var ampm = \"am\";\n var hour = parseInt(time.split(\":\")[0]);\n var min = time.split(\":\")[1];\n if (hour > 12) {\n hour = hour - 12\n ampm = \"pm\"\n }\n return hour + \":\" + min + ampm;\n }",
"function Timestr(timestring)\r\n{\r\n\tvar str = timestring;\r\n\tvar time = str.split(\":\");\r\n\ttime[0]=parseInt(time[0],10);\r\n\ttime[1]=parseInt(time[1],10);\r\n\treturn time;\r\n\t\r\n}",
"function parseTime(time) {\n\t\tvar time = time.split(\":\");\n\t\tvar SECONDS = parseInt(time[1]);\n\t\tvar MINUTES = parseInt(time[0]);\n\t\treturn [MINUTES, SECONDS];\n\t}",
"function datetimetostr(str){\nvar str=str.replace(/\\//g,\"-\") //si viene con / en vez de -\n var f=str.split(\" \");\n var fechastr=\"\"\n var horastr=\"00:00:00\";\n //tiene fecha y hora, sino, solo fecha\n fechastr=f[0]\n if(f.length>1){ \n horastr=f[1]\n }\n f=fechastr.split(\"-\")\n return f[2]+\"-\"+f[1]+\"-\"+f[0]+\" \"+horastr\n \n}",
"function timeConversion(s) {\n let [hours, minutes, seconds] = s.split(':')\n const period = seconds.substring(2, seconds.length)\n seconds = seconds.substring(0, 2)\n if (period === 'AM') {\n if (hours === '12') {\n hours = '00'\n }\n } else {\n hours = hours === '12' ? hours : Number(hours) + 12\n }\n return [\n hours,\n minutes,\n seconds\n ].join(':')\n}",
"function string_time(date) {\n if (is_previous_day(date)) {\n return _string_time(get_previous_day(date), 24);\n }\n return _string_time(date, 0);\n}",
"function get24Hour(time){\n console.log(time[0]);\n}",
"function toDaySeconds(time) {\n const parts = time.split(':');\n let pos;\n if ((pos = parts[0].indexOf('T')) !== -1) {\n parts[0] = parts[0].substring(pos);\n }\n const h = parseInt(parts[0], 10);\n const m = (parts[1] !== undefined) ? parseInt(parts[1], 10) : 0;\n const s = (parts[2] !== undefined) ? parseInt(parts[2], 10) : 0;\n return (h * 3600 + m * 60 + s) % (3600 * 24);\n}",
"timeToString(time) {\n const hour = (time.hour < 10) ? \"0\"+time.hour : time.hour\n const minutes = (time.minutes < 10) ? \"0\"+time.minutes : time.minutes\n const seconds = (time.seconds < 10) ? \"0\"+time.seconds : time.seconds\n return minutes+\":\"+seconds\n //return hour+\":\"+minutes+\":\"+seconds\n }",
"timeToString(time) {\n const date = new Date(time);\n return date.toISOString().split('T')[0];\n }",
"function d3_time_parseHour24(date, string, i) {\n d3_time_numberRe.lastIndex = 0;\n var n = d3_time_numberRe.exec(string.substring(i, i + 2));\n return n ? (date.H = +n[0], i += n[0].length) : -1;\n}",
"function d3_time_parseHour24(date, string, i) {\n d3_time_numberRe.lastIndex = 0;\n var n = d3_time_numberRe.exec(string.substring(i, i + 2));\n return n ? (date.H = +n[0], i += n[0].length) : -1;\n}"
]
| [
"0.67433816",
"0.66326666",
"0.6593559",
"0.6425339",
"0.6388786",
"0.63450277",
"0.627646",
"0.6241814",
"0.6241814",
"0.61966914",
"0.61966914",
"0.61905503",
"0.60105634",
"0.60105634",
"0.6005081",
"0.6002989",
"0.5988781",
"0.5972605",
"0.5918019",
"0.5908384",
"0.5879897",
"0.5878714",
"0.5872172",
"0.58111286",
"0.5808917",
"0.5800703",
"0.5796331",
"0.5795604",
"0.57486826",
"0.57486826"
]
| 0.74631965 | 0 |
Disable dragging for element | function disableDraggingFor(element) {
// this works for FireFox and WebKit in future according to http://help.dottoro.com/lhqsqbtn.php
element.draggable = false;
// this works for older web layout engines
element.onmousedown = function(event) {
event.preventDefault();
return false;
};
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function noDragStart() {\n return false;\n}",
"function noDragStart() {\n return false;\n}",
"notPressed(x, y) {\n this.dragging = false\n }",
"function makeUndraggable(element) {\n element.container.draggable = false;\n element.container.ondragstart = undefined;\n }",
"function noDragStart() {\n return false;\n }",
"function enableImageDrag(){off(window,'dragstart',preventDefault);}",
"function noDragStart() {\n\t return false;\n\t}",
"function mouseReleased() {\n dragging = false;\n}",
"function dragOverHelperFunction(ev){\n\n ev.preventDefault();\n\n}",
"function mouseDragged() {\n //prevent default\n\n return false;\n\n}",
"function disableDraggables(disable) {\t\n\tvar elem_array = $(\"#menu\").find(\"svg\").get();\n\tvar div_array = $(\"#content\").find(\"div\").get();\n\telem_array = elem_array.concat(div_array);\n\tfor (var i = 0; i < elem_array.length; i++) {\n\t\tif (elem_array[i].attributes[\"id\"] != undefined) {\n\t\t\tvar selector = \"#\"+elem_array[i].attributes[\"id\"].value;\n\t\t\tif ($( selector ).draggable( \"instance\" ) != undefined) {\n\t\t\t\tif (disable == true)\n\t\t\t\t\t$( selector ).draggable( \"disable\" );\n\t\t\t\telse\n\t\t\t\t\t$( selector ).draggable( \"enable\" );\n\t\t\t}\n\t\t}\n\t}\n}",
"function dragOver(event) {\n event.preventDefault();\n}",
"function r(e,t){e._internalDrag=!1,e.setMode(\"drag\"),t.preventDefault()}",
"function r(e){e._internalDrag=!0,e.setMode(\"drag\")}",
"handleDragOver(event) {\n event.preventDefault();\n }",
"function dragover(e) {\n e.preventDefault();\n}",
"handleDragOver(event) {\n event.preventDefault();\n }",
"function disableSelection($el){\n\tcss($el, {\n\t\t\"user-select\": \"none\",\n\t\t\"user-drag\": \"none\",\n\t\t\"touch-callout\": \"none\"\n\t})\n\t$el.setAttribute(\"unselectable\", \"on\")\n\ton($el, 'selectstart', preventDefault)\n}",
"mouseDown(event) {\n if (this.disableMouseDown) {\n event.preventDefault();\n }\n }",
"function handleDragOver(event){\n event.preventDefault();\n}",
"function dragHandler(evt) {\n evt.preventDefault();\n evt.stopPropagation();\n}",
"_supressDnD(event) {\n event.preventDefault()\n }",
"function onDocumentDragOver(evt) {\n evt.preventDefault();\n}",
"function onDocumentDragOver(evt) {\n evt.preventDefault();\n}",
"function onDocumentDragOver(evt) {\n evt.preventDefault();\n}",
"function onDocumentDragOver(evt) {\n evt.preventDefault();\n}",
"function onDocumentDragOver(evt) {\n evt.preventDefault();\n}",
"function onDocumentDragOver(evt) {\n evt.preventDefault();\n}",
"function onDocumentDragOver(evt) {\n evt.preventDefault();\n}",
"function disableAll() {\n container.style.pointerEvents = \"none\";\n}"
]
| [
"0.77933097",
"0.77933097",
"0.7654686",
"0.76443285",
"0.7552134",
"0.7437528",
"0.7425605",
"0.7346991",
"0.7251787",
"0.7208822",
"0.7201996",
"0.7145409",
"0.70214605",
"0.7003063",
"0.70027035",
"0.6988617",
"0.6980014",
"0.6939412",
"0.6930716",
"0.69276816",
"0.6923424",
"0.6903467",
"0.68454516",
"0.68454516",
"0.68454516",
"0.68454516",
"0.68454516",
"0.68454516",
"0.68454516",
"0.68278885"
]
| 0.8763229 | 0 |
Draw the calendar (once). | function drawCalendar() {
try {
paper = new Raphael("calendar_canvas", '100%', '100%');
} catch(e) {
if(console) {
console.log(e);
}
}
drawCalendarBackground();
disableDraggingFor(document.getElementById('calendar_canvas'));
$(document.body).addEvent("dragstart", function() {
return false;
});
var DayNavigationArrows = new Class({
initialize : function() {
this.left = new Arrow(paper, 'left', day2x(-0.35), 15, this.move_left_date);
this.right = new Arrow(paper, 'right', day2x(7.35), 15, this.move_right_date);
this.left.setBrother(this.right);
this.right.setBrother(this.left);
var that_monday = new Date(today);
that_monday.setDay(1);
if(dateRange(current_date, that_monday) < 7) {
this.left.disable();
}
},
move_left_date : function() {
if(!this.parent.is_disabled) {
/*var changed_date = new Date(current_date);
changed_date.setDate(changed_date.getDate() - 7);
paper.clear();
//drawCalendar();
paper.remove();
var rs = new ResourceScheduler(resource, on_setup_selection, changed_date);*/
/*current_date.setDate(current_date.getDate() - 7);
drawCalendarBackground();
drawCalendar();
createExistingSchedule(resource);*/
var changed_date = new Date(current_date);
changed_date.setDate(changed_date.getDate() - 7);
on_set_date(changed_date);
}
},
move_right_date : function() {
if(!this.parent.is_disabled) {
/*var changed_date = new Date(current_date);
changed_date.setDate(changed_date.getDate() + 7);
paper.clear();
//drawCalendar();
paper.remove();
var rs = new ResourceScheduler(resource, on_setup_selection, changed_date);*/
/*current_date.setDate(current_date.getDate() + 7);
drawCalendarBackground();
drawCalendar();
createExistingSchedule(resource);*/
var changed_date = new Date(current_date);
changed_date.setDate(changed_date.getDate() + 7);
on_set_date(changed_date);
}
},
left : null,
right : null
});
var nav = new DayNavigationArrows();
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"init() {\n document.getElementById(this.calendarId).innerHTML += '<div id=\"loading\">' + this.loadingText + '</div>';\n var t = this;\n t.drawHours();\n t.drawWeekdays();\n t.drawDates();\n t.addNavigationListeners(); \n t.drawReservations();\n t.redrawCurrent();\n setInterval(function(){\n t.redrawCurrent();\n }, t.redrawTimeInt * 1000);\n console.log('%cCalendar ready!', 'background-color:#28a745;color:#fff;font-size:14px;padding:6px;border-radius:4px;');\n }",
"function drawCalendar() \n{ \n\n // GET MONTH, AND YEAR FROM GLOBAL CALENDAR DATE\n month = this.currentMonth-1;\n year = this.currentYear;\n\t\n\t//this.debug();\n\n\t// hide monthList unconditionally\n\tcloseMonthList();\n\t\n\t// build Table Object \n\tvar oTbl = document.createElement('TABLE');\n\toTbl.cellPadding=0;\n\toTbl.cellSpacing=1;\n\toTbl.border=0\n\toTbl.bgColor=\"#808080\";\n\tvar wNameRow = oTbl.insertRow();\n\t\n\t// Day Name header array\n\tvar dayName = new Array('Su','Mo','Tu','We','Th','Fr','Sa');\n\n\t// build weekDayName header row with a loop \n\tfor(i=0;i<7;i++)\n\t{\n\t\tvar oWeekDayTD = document.createElement('TD');\n\t\toWeekDayTD.className='dayName';\n\t\toWeekDayTD.innerText=dayName[i]\n\t\twNameRow.appendChild(oWeekDayTD);\n\t}\n\t// alert(oTbl.innerHTML);\n\n\tday = this.currentDay;\n\n var i = 0;\n\n // DETERMINE THE NUMBER OF DAYS IN THE CURRENT MONTH\n var days = this.getDaysInMonth();\n // IF GLOBAL DAY VALUE IS > THAN DAYS IN MONTH, HIGHLIGHT LAST DAY IN MONTH\n if (day > days) {\n day = days;\n }\n // DETERMINE WHAT DAY OF THE WEEK THE CALENDAR STARTS ON\n var firstOfMonth = new Date (year, month, 1);\n\n // GET THE DAY OF THE WEEK THE FIRST DAY OF THE MONTH FALLS ON\n var startingPos = firstOfMonth.getDay();\n days += startingPos;\n\n // KEEP TRACK OF THE COLUMNS, START A NEW ROW AFTER EVERY 7 COLUMNS\n var columnCount = 0;\n\n\t// Add a new Row \n\tvar oRow= oTbl.insertRow();\n\n\n // MAKE BEGINNING NON-DATE CELLS BLANK\t\n for (i = 0; i < startingPos; i++) \n\t{\n\n oEmptyTD = document.createElement('TD');\n\t\toEmptyTD.className='day';\n\t\toEmptyTD.innerText=\"\";\n\t\toRow.appendChild(oEmptyTD);\n\tcolumnCount++;\n }\n\t//alert(oTbl.innerHTML);\t\t\n\t\n\n\t // SET VALUES FOR DAYS OF THE MONTH\n var currentDay = 0;\n var dayType = \"weekday\";\n\n // DATE CELLS CONTAIN A NUMBER\n for (i = startingPos; i < days; i++) \n\t{\n\n\tvar paddingChar = \" \";\n\n // ADJUST SPACING SO THAT ALL LINKS HAVE RELATIVELY EQUAL WIDTHS\n if (i-startingPos+1 < 10) {\n padding = \" \";\n }\n else {\n padding = \" \";\n }\n\n // GET THE DAY CURRENTLY BEING WRITTEN\n currentDay = i-startingPos+1;\n\n // SET THE TYPE OF DAY, THE focusDay GENERALLY APPEARS AS A DIFFERENT COLOR\n if (currentDay == day) {\n dayType = \"focusDay\";\n }\n else {\n dayType = \"weekDay\";\n }\n\n // ADD THE DAY TO THE CALENDAR GRID and render the cell\n \t \n\t\t\tvar oDayTD = document.createElement('TD');\n\t\t\tif(currentDay == _calCurrentDay)\n\t\t\t{\n\t\t\t\toDayTD.className=\"cday\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\toDayTD.className=\"day\";\n\t\t\t}\n\t\t\t//oDayTD.innerText=currentDay;\n\t\t\t// add day with link\n\t\t\tvar currentDateString = this.currentYear +\"\"+( (this.currentMonth.toString().length<2)? \"0\"+this.currentMonth : this.currentMonth )+\"\"+ ( (currentDay.toString().length<2) ? \"0\"+currentDay : currentDay );\n\t\t\t//alert(formatDate(currentDateString,_dateFormat));\n\t\t\t\n\t\t\t//currentDateString = formatDate(currentDateString,_dateFormat);\n\n\t\t\tvar dayStr= \"<a href=\\\"javascript:void(0)\\\" onclick=\\\"setDate('\"+ currentDateString + \"')\\\" class='lnk'>\" + currentDay + \"</a>\";\n\t\t\toDayTD.innerHTML= dayStr;\n\t\t\toRow.appendChild(oDayTD);\n \n\t\tcolumnCount++;\n\n // START A NEW ROW WHEN NECESSARY\n if (columnCount % 7 == 0) {\n //calDoc += \"</TR><TR>\";\n\t\t\toRow= oTbl.insertRow();\n }\n }// end for\n\n\t//alert(oTbl.innerHTML);\t\t\n\n\n\t// rest of Empty cell\n\t for (i=days; i<42; i++) \n\t {\n\n oEmptyTD = document.createElement('TD');\n\t\toEmptyTD.className='day';\n\t\toEmptyTD.innerText=\"\";\n\t\toRow.appendChild(oEmptyTD);\n\n\t\tcolumnCount++;\n\n // START A NEW ROW WHEN NECESSARY\n if (columnCount % 7 == 0) {\n //calDoc += \"</TR>\";\n if (i<41) {\n //calDoc += \"<TR>\";\n\t\t\t\toRow= oTbl.insertRow();\n }\n }\n }\n\n\t\n\t\n\tdocument.getElementById('gridContainer').appendChild(oTbl);\n\t//alert(document.getElementById('gridContainer').innerHTML);\t\n}",
"function drawCal(firstDay, lastDate, date, monthName, year) {\n // constant table settings\n //TODO: Clean up vars for styling\n var headerHeight = 50; // height of the table's header cell\n var border = 2; // 3D height of table's border\n var cellspacing = 4; // width of table's border\n var headerColor = 'midnightblue'; // color of table's header\n var headerSize = '+3'; // size of tables header font\n var colWidth = 60; // width of columns in table\n var dayCellHeight = 25; // height of cells containing days of the week\n var dayColor = 'darkblue'; // color of font representing week days\n var cellHeight = 40; // height of cells representing dates in the\n // calendar\n var todayColor = 'red'; // color specifying today's date in the calendar\n var timeColor = 'purple'; // color of font representing current time\n\n // calculate whether we should increment or decrement the year/month\n var monthNum = getMonthNumber(monthName);\n var theYear = parseInt(year);\n var lastYear;\n var nextYear;\n var theMonth = monthNum;\n var lastMonth = monthNum - 1;\n var nextMonth = monthNum + 1;\n if (lastMonth < 0) {\n lastMonth = 11;\n lastYear = parseInt(year, 10) - 1;\n } else if (nextMonth > 11) {\n nextMonth = 0;\n nextYear = parseInt(year, 10) + 1\n }\n console.log('YEAR: ' + (isEmpty(theYear) ? year : theYear) + ' | MONTH: ' + monthNum);\n\n // create basic table structure\n var text = ''; // initialize accumulative variable to empty string\n text += '<table class=\"calendar\" cellspacing=\"15\">'; // table settings\n text += '<th colspan=\"7\">'; // create table header cell\n text += '<a href=\"?year=' + (isEmpty(lastYear) ? theYear : lastYear) + '&month=' + (isEmpty(lastMonth) ? theMonth : lastMonth) + '\"><i class=\"fas fa-chevron-left\"></i></a> '\n + monthName + ' ' + (isEmpty(theYear) ? year : theYear)\n + ' <a href=\"?year=' + (isEmpty(nextYear) ? theYear : nextYear) + '&month=' + (isEmpty(nextMonth) ? theMonth : nextMonth) + '\"><i class=\"fas fa-chevron-right\"></i></a>';\n\n text += '</th>'; // close header cell\n\n // variables to hold constant settings\n var openCol = '<td><span>';\n var closeCol = '</span></td>';\n\n // create array of abbreviated day names\n var weekDay = new Array(7);\n weekDay[0] = 'Sunday';\n weekDay[1] = 'Monday';\n weekDay[2] = 'Tuesday';\n weekDay[3] = 'Wednesday';\n weekDay[4] = 'Thursday';\n weekDay[5] = 'Friday';\n weekDay[6] = 'Saturday';\n\n // create first row of table to set column width and specify week day\n text += '<tr>';\n for (var dayNum = 0; dayNum < 7; ++dayNum) {\n text += '<th class=\"calendarWeekDay\">' + weekDay[dayNum] + '</th>';\n }\n text += '</tr>';\n\n // declaration and initialization of two variables to help with tables\n var digit = 1;\n var curCell = 1;\n\n for (var row = 1; row <= Math.ceil((lastDate + firstDay - 1) / 7); ++row) {\n text += '<tr align=\"right\" valign=\"top\">';\n\n for (var col = 1; col <= 7; ++col) {\n if (digit > lastDate) {\n break;\n }\n\n if (curCell < firstDay) {\n text += '<td class=\"calendarEmpty\"></td>';\n curCell++;\n } else {\n // current cell represent today's date\n //digit == date\n var now = new Date();\n var year = now.getYear();\n if (year < 1000) {\n year += 1900;\n }\n var curMonth = now.getMonth();\n text += '<td class=\"' + ((digit === date && curMonth === monthNum && year === theYear) ? 'calendarCurDay' : 'calendarDay') + '\"><a href=\"dailyview.jsp?date=' + theYear + '-' + (\"0\" + (monthNum + 1)).slice(-2) + '-' + (\"0\" + digit).slice(-2) + '\">' + digit + '</a></td>';\n\n digit++;\n }\n }\n text += '</tr>';\n }\n // close all basic table tags\n text += '</table>';\n\n // print accumulative HTML string\n document.getElementById('calendar').innerHTML = text;\n}",
"function showCalendar() {\n canvasWrapper.fadeOut(\"linear\", function () {\n calendarEl.fadeIn(\"linear\").css(\"display\", \"block\");\n });\n }",
"function dispCalendar(){\r\n\r\n createRows();\r\n // HEAD OF CALENDAR \r\n $(head).text(monthNames[month] + \" \" + year);\r\n }",
"function Calendar(){ //Draws the Calendar on page\n\t\t$('#main-info').monthly({\n \t\t\tmode: 'event',\n \t\t\tdataType: 'json',\n \t\t\tevents: events\n\t\t});\n\t}",
"function drawCalendar(fullDate, month, year) {\n // Year\n // Month || Jan = 0. Feb = 1, Mar = 2\n // Day label\n var day = fullDate.getDay();\n var date = fullDate.getDate();\n // Days in Month -- Auto Leap Year\n var dIM = new Date(year, (month + 1), 0).getDate();\n // Month starts on day\n var startingDay = new Date(year, month, 1).getDay();\n // How many weeks in month to draw\n var rows = Math.ceil((dIM + startingDay - 1) / 7);\n\n console.log(\"True dIM = 'Days In Month + Days into month it starts at.\" + month_labels[month] +\n \": \" + dIM + \" + \" + (startingDay - 1) + \"/7 = \" + Math.ceil((dIM + startingDay - 1) / 7));\n console.log(rows);\n\n var html = '<div id=\"dayHead\">' +\n '<div class=\"calDayItem\">Sun</div><div class=\"calDayItem\">Mon</div><div class=\"calDayItem\">Tue</div>' +\n '<div class=\"calDayItem\">Wed</div><div class=\"calDayItem\">Thu</div><div class=\"calDayItem\">Fri</div>' +\n '<div class=\"calDayItem\">Sat</div></div><table id=\"calTable\">';\n\n console.log(events);\n // Drawing Calendar\n var curDay = 1;\n // Loop for rows -- Over compensating 9.\n for (var i = 0; i < rows; i++) {\n html += '<tr>';\n // this loop is for weekdays (cells)\n for (var j = 0; j <= 6; j++) {\n\n if (date == curDay && month == curMonth && year == curYear) {\n html += '<td class=\"curDay\">';\n html += curDay;\n html += '</td>';\n curDay++\n } else if (curDay <= dIM && (i > 0 || j >= startingDay)) {\n // Valid Day\n var eventBool = false;\n for (var k = 0; k <= events.length - 1; k++) {\n\n if (events[k].date.substr(-2) == curDay && events[k].date.substr(0, 4) == year &&\n (events[k].date.substr(5, 2) - 1) == month) {\n\n html += '<td class=\"eventDay\">';\n html += curDay;\n //html += '<p class=\"eventCap\">' + events[k].name + '</p>';\n html += '</td>';\n curDay++;\n eventBool = true;\n }\n }\n if (!eventBool) {\n html += '<td class=\"validDay\">';\n html += curDay;\n html += '</td>';\n curDay++;\n }\n } else {\n html += '<td class=\"invalidDay\">';\n html += '</td>';\n }\n }\n html += '</tr>';\n }\n html += \"</table>\";\n $('#listSwitch').html(html);\n\n // get Events\n\n // DEBUG\n // console.log(\"Day: \" + day_labels[day] + \" (\" + day + \")\");\n // console.log(\"Date: \" + date);\n // console.log(\"Month: \" + month_labels[month] + \" (\" + month + \")\");\n // console.log(\"Year: \" + year);\n // console.log(\"Days in this month: \" + dIM);\n // console.log(\"Starting Day: \" + day_labels[startingDay] + \" (\" + startingDay + \")\");\n }",
"function drawTable()\r\n{\r\n var i, j, w = \"\", cls;\r\n\r\n w += \"<html><head><title>Calendar</title>\";\r\n w += \"<style>\";\r\n w += \"body { margin:0px; background-color:buttonface;}\";\r\n w += \"body,td,a,th,select { cursor:default; font-family:Arial; font-size:8pt; font-weight:bold; color:black; }\";\r\n w += \"#selmonth { position:absolute; z-index:1; display:none; }\";\r\n w += \"#selyear { position:absolute; z-index:1; display:none; }\";\r\n w += \"#maintab { display:none; }\";\r\n w += \"#dispstatus { background-color:window; color:windowtext; font-weight:normal; text-align: center; height:20px; font-size:7pt; border:1px solid buttonhighlight; border-left-color:buttonshadow; border-top-color:buttonshadow; }\";\r\n w += \"td.cal_normal, td.cal_hilite, td.cal_holiday { \" + \"height:\" + CELLSIZE + \"px; width:\" + CELLSIZE + \"px; padding:1px; text-align:center; color:black; }\";\r\n w += \"td.cal_button, td.cal_arrow, td.cal_button2 { text-align: center; padding:1px; border:1px solid buttonhighlight; background-color:buttonface; border-right-color:buttonshadow; border-bottom-color:buttonshadow; color:buttontext; }\";\r\n w += \"td.cal_button { background: buttonface url(\" + IMGDIR + \"pick.gif) no-repeat 100% 100%; }\";\r\n w += \"td.cal_arrow { height:16px; width:16px; } \";\r\n w += \"#fwd { background: buttonface url(\" + IMGDIR + \"fwd.gif) no-repeat 50% 50%; }\";\r\n w += \"#ffwd { background: buttonface url(\" + IMGDIR + \"ffwd.gif) no-repeat 50% 50%; }\";\r\n w += \"#bkwd { background: buttonface url(\" + IMGDIR + \"bkwd.gif) no-repeat 50% 50%; }\";\r\n w += \"#fbkwd { background: buttonface url(\" + IMGDIR + \"fbkwd.gif) no-repeat 50% 50%; } \";\r\n w += \"th { background-color:black; color:white; text-align:center;}\";\r\n w += \"td.cal_normal { border:1px solid white; background-color:#dddddd; border-right-color:#999999; border-bottom-color:#999999; }\";\r\n w += \"td.cal_hilite { padding:0px; border:2px solid white; background-color:#eeeeee; border-right-color:#666666; border-bottom-color:#666666; }\";\r\n w += \"td.cal_holiday { border:1px solid white; background-color:#cccccc; border-right-color:#999999; border-bottom-color:#999999; }\";\r\n w += \"</style>\";\r\n w += \"</head><body></body></html>\";\r\n\r\n win.document.write(w);\r\n\r\n w = \"<select id=selmonth size=12 onchange='opener.updateCalendar()' \" +\r\n \"onclick='opener.hideDropdowns()' onblur='opener.hideDropdowns()' \" +\r\n \"onkeydown='opener.downKeySelectBox()' tabindex=4>\";\r\n for (i=0;i<12;i++)\r\n w += \"<option value='\" + (i+1) + \"'>\" + MONTHS[i] + \"</option>\";\r\n w += \"</select>\"; \r\n w += \"<select id=selyear size=8 onchange='opener.updateCalendar()' \" +\r\n \"onclick='opener.hideDropdowns()' onblur='opener.hideDropdowns()' \" +\r\n \"onkeydown='opener.downKeySelectBox()' tabindex=6>\";\r\n for (i=MINYEAR;i<=MAXYEAR;i++)\r\n w += \"<option value='\" + i + \"'>\" + i + \"</option>\";\r\n w += \"</select>\"; \r\n w += \"<table onkeydown='opener.downKey()' onmouseover='opener.setFocusHandler()' id=maintab border=0 cellspacing=0 cellpadding=0>\";\r\n w += \"<tr><td>\";\r\n\r\n w += \"<table onmouseover='opener.overButton()' onmouseout='opener.outButton()'\" +\r\n \" border=0 width='100%' cellspacing=0 cellpadding=0>\"; \r\n w += \"<tr><td id=fbkwd onclick=\\\"opener.go('<<')\\\" class=cal_arrow tabindex=1> </td>\";\r\n w += \"<td id=bkwd onclick=\\\"opener.go('<')\\\" class=cal_arrow tabindex=2> </td>\";\r\n w += \"<td id=dispmonth class=cal_button onclick='opener.toggle(this,selmonth)' tabindex=3>\";\r\n w += \"</td><td id=dispyear width=60 class=cal_button onclick='opener.toggle(this,selyear)' tabindex=5>\"; \r\n w += \"</td><td id=fwd onclick=\\\"opener.go('>')\\\" class=cal_arrow tabindex=7> \";\r\n w += \"</td><td id=ffwd onclick=\\\"opener.go('>>')\\\" class=cal_arrow tabindex=8> \"; \r\n w += \"</td></tr>\";\r\n w += \"</table>\";\r\n \r\n w += \"</td></tr><tr><td>\";\r\n \r\n w += \"<table onmouseover='opener.hideDropdowns();opener.overCell()' \" +\r\n \"onclick='opener.setDate()' onmouseout='opener.outCell()' \" +\r\n \"border=0 cellspacing=0 cellpadding=0>\";\r\n w += \"<tr>\"\r\n for (i=0;i<7;i++)\r\n w += \"<th id=w\" + i + \">\" + WEEKS[i].substr(0,WEEKHEAD_SIZE) + \"</th>\";\r\n w += \"</tr>\"\r\n for (i=0; i<5; i++)\r\n {\r\n w += \"<tr>\";\r\n for (j=0; j<7; j++)\r\n {\r\n cls = (j==0 || j==6) ? \"cal_holiday\" : \"cal_normal\";\r\n w += \"<td id=a\" + (i * 7 + j) + \" class=\" + cls + \"> </td>\";\r\n }\r\n w += \"</tr>\";\r\n }\r\n w += \"</table>\";\r\n \r\n w += \"</td></tr><tr><td id=dispstatus></td></tr><tr><td>\";\r\n \r\n w += \"<table onmouseover='opener.overButton()' onmouseout='opener.outButton()'\" +\r\n \" border=0 width='100%' cellspacing=0 cellpadding=0>\"; \r\n \r\n w += \"<tr><td id=disptoday class=cal_button2 tabindex=40 onclick=\\\"opener.go('today')\\\">\";\r\n w += TODAY_TEXT + \": \" + MONTHS[today.month-1].substr(0,3) + \" \" + today.day + \", \" + today.year; \r\n w += \"</td><td id=butblank class=cal_button2 tabindex=41 onclick='opener.setBlankDate()'>\"\r\n + BLANK_TEXT + \"</td>\";\r\n w += \"<td id=butclose class=cal_arrow tabindex=41 onclick='opener.closeWindow()'>×</td>\";\r\n w += \"</tr>\";\r\n w += \"</table>\"; \r\n\r\n w += \"</td></tr>\";\r\n w += \"</table>\";\r\n \r\n win.document.body.innerHTML = w;\r\n}",
"function construct_calendar() {\n\t\tgenerate_visuals();\n\t\tdisplay_day_names();\n\t\tvar date = get_current_date();\n\t\tgenerate_calendar(date);\n\t}",
"drawDates() {\n if (!document.getElementById('dates')) {\n document.getElementById(this.calendarId).innerHTML += '<ul id=\"dates\"></ul>';\n }\n var start = this.dateHelper.getMonday(new Date());\n var d = new Date();\n for (var i = 0; i < this.nextDays; i++) {\n d = this.dateHelper.addDays(start, i);\n var stamp = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);\n document.getElementById('dates').innerHTML += '<li data-date=\"' + stamp + '\" data-day=\"' + d.getDay() + '\"><span>' + d.getDate() + '/' + (d.getMonth() + 1) + '</span><section class=\"reservations\"></span></li>';\n }\n }",
"function DrawCalendar(stateName){\n\t\n\t// get all the sizes\n\tconst width = 900,\n height = 450,\n cellSize = 15,\n\t\tno_months_in_a_row = Math.floor(width / (cellSize * 7 + 50)),\n\t\tshift_up = cellSize * 3;\n\t\t\n\t// make a colour scale\n\tconst colourScale = d3.scaleLinear()\n\t\t.domain([-30, 0, 50])\n\t\t.range(['#007CC4', '#F7F7F7', '#E84302']);\n\t\n\t// get the months in the year and the necessery date formats\n\tconst day = d3.timeFormat('%w'), \n week = d3.timeFormat('%U'), \n month = d3.timeFormat('%m'), \n year = d3.timeFormat('%Y'),\n\t\tinformationDay = d3.timeFormat('%d'),\n\t\tinformationMonth = d3.timeFormat('%B');\n\t\t\n\t// make a svg\n const svg = d3.select('#calendar').selectAll('svg')\n .data(d3.range(2017, 2018))\n\t\t.enter().append('svg')\n\t\t\t.attr('width', width)\n\t\t\t.attr('height', height)\n\t\t\t.attr('id', 'outerCalendar')\n\t\t.append('g');\n\n\t// make a 'g' for every day\n const rect = svg.selectAll('.day')\n .data(function(d) { \n return d3.timeDays(new Date(d, 0, 1), new Date(d + 1, 0, 1));\n })\n\t\t.enter()\n\t\t.append('g')\n\t\t\t.attr('class', 'calendarSVG');\n\t\n\t// make a square for every day\n\trect.append('rect')\n\t\t.attr('class', 'day')\n\t\t.attr('id', function(d,i) { return i; })\n\t\t.attr('width', cellSize)\n\t\t.attr('height', cellSize)\n\t\t.attr('x', function(d) {\n\t\t\tlet month_padding = 1.2 * cellSize* 7 * \n\t\t\t\t((month(d) - 1) % (no_months_in_a_row));\n\t\t\treturn day(d) * cellSize + month_padding; \n\t\t})\n\t\t.attr('y', function(d) { \n\t\t\tlet week_diff = week(d) - \n\t\t\t\tweek(new Date(year(d), month(d) - 1, 1) ),\n\t\t\t\trowNum = Math.ceil(month(d) / (no_months_in_a_row));\n\t\t\treturn (week_diff * cellSize) + \n\t\t\t\trowNum * cellSize * 8 - cellSize / 2 - shift_up;\n\t\t})\n\t\t.style('fill', function(d,i) { \n\t\t\treturn colourScale(dataWeather[i][stateName])\n\t\t})\n\t\t.on('mouseover', function(d, i) { \n\t\t\td3.selectAll('.calendarLegenda').style('opacity', '0');\n\t\t\td3.selectAll('#calendarLegenda' + i).style('opacity', '1');\n\t\t});\n\t\n\t// make a tooltip\n\trect.append('text')\n\t\t.attr('class', 'calendarLegenda')\n\t\t.attr('id', function(d,i) { return 'calendarLegenda' + i; })\n\t\t.attr('x', function() { return width / 3 - 30})\n\t\t.attr('y', function() { return height * 2 / 3 + 30})\n\t\t.style('opacity', '0')\n\t\t.text(function(d,i) { \n\t\t\tinformation = 'On the ' + informationDay(d) + 'th of ' + \n\t\t\tinformationMonth(d) + ' 2017';\n\t\t\treturn information; \n\t\t})\n\trect.append('text')\n\t\t.attr('class', 'calendarLegenda')\n\t\t.attr('id', function(d,i) { return 'calendarLegenda' + i; })\n\t\t.attr('x', function() { return width / 3 - 30})\n\t\t.attr('y', function() { return height * 2 / 3 + 50})\n\t\t.style('opacity', '0')\n\t\t.text(function(d,i) { \n\t\t\tinformation = ' it was ' + \n\t\t\tdataWeather[i][stateName] + ' degrees celcius';\n\t\t\treturn information; \n\t\t});;\n\t\t\n\t// title the months\n const month_titles = svg.selectAll('.month-title') \n .data(function(d) { \n\t\t\treturn d3.timeMonths(new Date(d, 0, 1), new Date(d + 1, 0, 1)); \n\t\t\t})\n\t\t.enter().append('text')\n\t\t\t.text(function(d,i) { return informationMonth(d); })\n\t\t\t.attr('x', function(d, i) {\n\t\t\t\tlet month_padding = 1.2 * cellSize* 7 * \n\t\t\t\t\t((month(d)-1) % (no_months_in_a_row));\n\t\t\t\treturn month_padding;\n\t\t\t})\n\t\t\t.attr('y', function(d, i) {\n\t\t\t\tlet week_diff = week(d) - \n\t\t\t\t\tweek(new Date(year(d), month(d)-1, 1) ),\n\t\t\t\t\trow_level = Math.ceil(month(d) / (no_months_in_a_row));\n\t\t\t\treturn (week_diff*cellSize) + row_level * cellSize * 8 \n\t\t\t\t\t- cellSize - shift_up;\n\t\t\t})\n\t\t\t.attr('class', 'monthTitle');\n}",
"function initCalendar(){\n\n var monthNames = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\n var dayNames = [\"S\", \"M\", \"T\", \"W\", \"T\", \"F\", \"S\"];\n\n var now = new Date(),\n month = now.getMonth() + 1,\n year = now.getFullYear();\n\n var events = [\n [\n \"2/\"+month+\"/\"+year,\n 'The flower bed',\n '#',\n Sing.colors['brand-primary'],\n 'Contents here'\n ],\n [\n \"5/\"+month+\"/\"+year,\n 'Stop world water pollution',\n '#',\n Sing.colors['brand-warning'],\n 'Have a kick off meeting with .inc company'\n ],\n [\n \"18/\"+month+\"/\"+year,\n 'Light Blue 2.2 release',\n '#',\n Sing.colors['brand-success'],\n 'Some contents here'\n ],\n [\n \"29/\"+month+\"/\"+year,\n 'A link',\n 'http://www.flatlogic.com',\n Sing.colors['brand-danger']\n ]\n ];\n var $calendar = $('#events-calendar');\n $calendar.calendar({\n months: monthNames,\n days: dayNames,\n events: events,\n popover_options:{\n placement: 'top',\n html: true\n }\n });\n $calendar.find('.icon-arrow-left').addClass('fa fa-arrow-left');\n $calendar.find('.icon-arrow-right').addClass('fa fa-arrow-right');\n function restyleCalendar(){\n $calendar.find('.event').each(function(){\n var $this = $(this),\n $eventIndicator = $('<span></span>');\n $eventIndicator.css('background-color', $this.css('background-color')).appendTo($this.find('a'));\n $this.css('background-color', '');\n })\n }\n $calendar.find('.icon-arrow-left, .icon-arrow-right').parent().on('click', restyleCalendar);\n restyleCalendar();\n }",
"function DrawDays(position, radius, days)\r\n{\r\n\tvar anticlockwise = false;\r\n\tvar c=document.getElementById(\"myCanvas\");\r\n\tvar ctx=c.getContext(\"2d\");\r\n\t\r\n\t// Reset canvas for a new instance of clock. Otherwise new instance is printet over the old one.\r\n\t//c.width = c.width;\r\n\t\r\n\t// Draw the inner transparent filled circle.\r\n\tDrawTransparentCircle(position, radius);\r\n\t\r\n\t// Draw digits\r\n\tDrawDigits(days,\"Days\", position,\"rgb(236,94,84)\");\r\n\t\r\n\t// Draw a time rim around the transparent inner circle\r\n\tctx.beginPath();\r\n\tctx.lineWidth=9;\r\n\tctx.strokeStyle = \"rgba(236,94,84,.85)\";\r\n\tctx.arc(position.x, position.y, radius, DegreesToRadians(-90), DegreesToRadians(DaysToDegrees(days)-90), anticlockwise);\r\n\tctx.stroke();\r\n}",
"function startClock() {\r\n drawFace(graphic, radius);\r\n drawNumbers(graphic, radius);\r\n drawTime(graphic, radius);\r\n}",
"static drawGrid(){\n\t\t// [1]\n\t\tvar calendarId = \"calendar\";\n\t\tvar calendar = document.getElementById(calendarId);\n\t\tvar boxSide = calendar.getBoundingClientRect().width/7;\n\t\tvar width = calendar.getBoundingClientRect().width;\n\t\tvar height = calendar.getBoundingClientRect().height;\n\n\t\t// [2]\n\t\tfor(var i = 0; i < 6; i++){\n\t\t\tfor(var j = 0; j < 7; j++){\n\t\t\t\tvar g = document.createElementNS(\"http://www.w3.org/2000/svg\", \"g\");\n\t\t\t\tg.setAttribute(\"id\", [i, \",\", j].join(\"\"));\n\t\t\t\tg.setAttribute(\"transform\", [\"translate(\", j * boxSide, \",\", i * boxSide, \")\"].join(\"\"));\n\t\t\t\tcalendar.appendChild(g);\n\t\t\t}\n\t\t}\n\n\t\t// [3]\n\t\tfor(var i = 0; i <= 7; i++){\n\t\t\tvar line = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n\t\t\tline.setAttribute(\"x1\", i * boxSide);\n\t\t\tline.setAttribute(\"y1\", 0);\n\t\t\tline.setAttribute(\"x2\", i * boxSide);\n\t\t\tline.setAttribute(\"y2\", height);\n\t\t\tline.setAttribute(\"stroke-width\", 2);\n\t\t\tline.setAttribute(\"stroke\", \"#383f51\");\n\t\t\tcalendar.appendChild(line);\n\t\t}\n\n\t\tfor(var i = 0; i <= 6; i++){\n\t\t\tvar line = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n\t\t\tline.setAttribute(\"x1\", 0);\n\t\t\tline.setAttribute(\"y1\", i * boxSide);\n\t\t\tline.setAttribute(\"x2\", width);\n\t\t\tline.setAttribute(\"y2\", i * boxSide);\n\t\t\tline.setAttribute(\"stroke-width\", 2);\n\t\t\tline.setAttribute(\"stroke\", \"#383f51\");\n\t\t\tcalendar.appendChild(line);\n\t\t}\n\t}",
"function drawCalendarPicker(obj, date) {\n \n \n obj.focus()\n \n // Default to NOW for calendar.\n var now = new Date()\n \n // if called with an existing date (YYYY-MM-DD),\n // convert it to a JS date object and use that for\n // rendering the calendar\n if (date) {\n var ar = date.split(/-/)\n now = new Date(ar[0],parseInt(ar[1])-1,ar[2])\n }\n var days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']\n var mat = now\n \n // Go to first day of the month\n mat.setDate(1)\n \n obj.innerHTML = \"<h3>\" + months[mat.getMonth()] + \", \" + mat.getFullYear() + \":</h3>\"\n var tm = mat.getMonth()\n \n // -- Nav buttons --\n \n // back-a-year button\n var a = document.createElement('a')\n fixupPicker(a)\n a.setAttribute(\"onclick\", \"drawCalendarPicker(this.parentNode, '\" + (mat.getFullYear()-1) + '-' + (mat.getMonth()+1) + '-' + mat.getDate() + \"');\")\n a.setAttribute(\"href\", \"javascript:void(0);\")\n a.innerHTML = \"≪\"\n obj.appendChild(a)\n \n // back-a-month button\n a = document.createElement('a')\n fixupPicker(a)\n a.setAttribute(\"onclick\", \"drawCalendarPicker(this.parentNode, '\" + mat.getFullYear() + '-' + (mat.getMonth()) + '-' + mat.getDate() + \"');\")\n a.setAttribute(\"href\", \"javascript:void(0);\")\n a.innerHTML = \"<\"\n obj.appendChild(a)\n \n // forward-a-month button\n a = document.createElement('a')\n fixupPicker(a)\n a.setAttribute(\"onclick\", \"drawCalendarPicker(this.parentNode, '\" + mat.getFullYear() + '-' + (mat.getMonth()+2) + '-' + mat.getDate() + \"');\")\n a.setAttribute(\"href\", \"javascript:void(0);\")\n a.innerHTML = \">\"\n obj.appendChild(a)\n \n // forward-a-year button\n a = document.createElement('a')\n fixupPicker(a)\n a.setAttribute(\"onclick\", \"drawCalendarPicker(this.parentNode, '\" + (mat.getFullYear()+1) + '-' + (mat.getMonth()+1) + '-' + mat.getDate() + \"');\")\n a.setAttribute(\"href\", \"javascript:void(0);\")\n a.innerHTML = \"≫\"\n obj.appendChild(a)\n obj.appendChild(document.createElement('br'))\n \n \n // Table containing the dates of the selected month\n var table = document.createElement('table')\n \n table.setAttribute(\"border\", \"1\")\n table.style.margin = \"0 auto\"\n \n // Add header day names\n var tr = document.createElement('tr');\n for (var m = 0; m < 7; m++) {\n var td = document.createElement('th')\n td.innerHTML = days[m]\n tr.appendChild(td)\n }\n table.appendChild(tr)\n \n // Until we hit the first day in a month, add blank days\n tr = document.createElement('tr');\n var weekday = mat.getDay()\n if (weekday == 0) {\n weekday = 7\n }\n weekday--;\n for (var i = 0; i < weekday; i++) {\n var td = document.createElement('td')\n tr.appendChild(td)\n }\n \n // While still in this month, add day then increment date by 1 day.\n while (mat.getMonth() == tm) {\n weekday = mat.getDay()\n if (weekday == 0) {\n weekday = 7\n }\n weekday--;\n if (weekday == 0) {\n table.appendChild(tr)\n tr = document.createElement('tr');\n }\n td = document.createElement('td')\n // onclick for setting the calendarPicker's parent to this val.\n td.setAttribute(\"onclick\", \"setCalendarDate('\" + mat.getFullYear() + '-' + (mat.getMonth()+1) + '-' + mat.getDate() + \"');\")\n td.innerHTML = mat.getDate()\n mat.setDate(mat.getDate()+1)\n tr.appendChild(td)\n }\n \n table.appendChild(tr)\n obj.appendChild(table)\n}",
"function calendar() {\n 'use strict';\n var day = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],\n month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],\n date = new Date();\n\n setText('calendar-day', day[date.getDay()]);\n setText('calendar-date', date.getDate());\n setText('calendar-month-year', month[date.getMonth()] + ' ' + (1900 + date.getYear()));\n}",
"generateCalendarView() {\n this.calendarViewModel = new CalendarViewModel(this.calendar, this.selectedDay, this.focusedDay, this.today, this._localeHelperService.firstDayOfWeek, this._dateIOService.disabledDates);\n }",
"function setCal(_year, _month) {\n // standard time attributes\n var now = new Date();\n var year = _year || now.getYear();\n if (year < 1000) {\n year += 1900;\n }\n var month = _month || now.getMonth();\n var monthName = getMonthName(month);\n var date = now.getDate();\n\n // create instance of first day of month, and extract the day on which it\n // occurs\n var firstDayInstance = new Date(year, month, 1);\n var firstDay = firstDayInstance.getDay();\n firstDayInstance = null;\n\n // number of days in current month\n var days = getDays(month, year);\n\n // call function to draw calendar\n drawCal(firstDay + 1, days, date, monthName, year);\n}",
"render() {\n this.element.innerHTML = '';\n this.renderCalendarHeader();\n this.renderCalendar();\n db.loadEventsFromDB();\n }",
"static draw() {\r\n\t\t// Ribbon : thick line\r\n\t\tstrokeWeight(4);\r\n\t\tstroke('#DDD');\r\n\t\tline(0, Earth.RADIUS, 0, Earth.RADIUS + Ribbon.LENGTH);\r\n\r\n\t\tnoStroke();\r\n\t\tellipseMode(CENTER);\r\n\t\t\r\n\t\t// GEO station circle\r\n\t\tfill('#4D3066');\r\n\t\tellipse(0, Earth.GEO_RADIUS, 4)\r\n\t\t\r\n\t\t// Counterweight circle\r\n\t\tfill('#22339F');\r\n\t\tellipse(0, Earth.RADIUS + Ribbon.LENGTH, 10)\r\n\t}",
"function UI_Calendar()\r\n{\r\n var pCalendar = UI_Shadow();\r\n\r\n var pHeader = pCalendar.contentPane.appendChild(document.createElement(\"TABLE\"));\r\n var pBody = pCalendar.contentPane.appendChild(document.createElement(\"TABLE\"));\r\n\r\n pCalendar.onselect = null;\r\n pCalendar.onselectmonth = null;\r\n pCalendar.contentPane.className = \"calendar\";\r\n\r\n pBody.className =\"calendar_body\";\r\n\r\n pHeader.cellPadding = 0;\r\n pHeader.cellSpacing = 0;\r\n\r\n var pRow = pHeader.insertRow(-1);\r\n pRow.insertCell(-1).innerHTML = \"<img src='\"+UI.imagesURL+\"widgets/calendar_previous.png'/>\";\r\n pRow.insertCell(-1).className = \"calendar_header\"\r\n pRow.insertCell(-1).innerHTML = \"<img src='\"+UI.imagesURL+\"widgets/calendar_next.png'/>\";\r\n \r\n //Insure that if these events occur on the event they are not bouble to the body and window.\r\n pCalendar.onscroll = function(event){ return UI.cancelBubble(event); };\r\n pCalendar.onresize = function(event){ return UI.cancelBubble(event); };\r\n pCalendar.onkeypress = function(event){ return UI.cancelBubble(event); };\r\n pCalendar.onmousedown = function(event){ return UI.cancelBubble(event); };\r\n\r\n /**\r\n * @param iYear The full year, ex 1978.\r\n * @param iMonth The month as an integer between 0 and 11.\r\n * @param iDate The date as an integer between 1 and 31\r\n */\r\n pCalendar.paintDate = function(iYear, iMonth, iDate)\r\n {\r\n var pDate = new Date(iYear, iMonth, iDate);\r\n\r\n //TODO: support different languages.\r\n var aMonths = new Array(\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\");\r\n\r\n pHeader.rows[0].cells[0].onclick = function(){ iMonth--; if (iMonth < 0) pCalendar.paintDate(iYear-1, 11, 1); else pCalendar.paintDate(iYear, iMonth, iDate); };\r\n pHeader.rows[0].cells[1].onclick = function(){ pCalendar.paintMonth(iYear, iMonth, iDate); };\r\n pHeader.rows[0].cells[2].onclick = function(){ iMonth++; if (iMonth > 11) pCalendar.paintDate(iYear+1, 0, 1); else pCalendar.paintDate(iYear, iMonth, iDate); };\r\n\r\n pHeader.rows[0].cells[1].innerHTML = aMonths[iMonth] + \", \" + iYear;\r\n\r\n pCalendar.clearBody();\r\n pCalendar.paintWeeks();\r\n pCalendar.paintDays(pDate);\r\n }\r\n \r\n pCalendar.paintWeeks = function()\r\n {\r\n //TODO: support different languages.\r\n var aWeeks = new Array(\"Su\", \"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\");\r\n\r\n var pRow = pBody.insertRow(-1);\r\n for (var iWeek = 0; iWeek < 7; iWeek++)\r\n {\r\n var pCell = pRow.insertCell(-1);\r\n pCell.innerHTML = aWeeks[iWeek];\r\n }\r\n }\r\n \r\n pCalendar.paintDays = function(pDate)\r\n {\r\n var iDay = pDate.getDate();\r\n var iMonth = pDate.getMonth();\r\n var iYear = pDate.getFullYear();\r\n\r\n pDate.setDate(1); \r\n var iCurrentWeekDay = pDate.getDay();\r\n for(var iWeek = 0; iWeek < 6; iWeek++)\r\n {\r\n var pRow = pBody.insertRow( -1 );\r\n for(var iWeekDay = 0; iWeekDay < 7; iWeekDay++)\r\n {\r\n var pCell = pRow.insertCell( -1 );\r\n if(iCurrentWeekDay == iWeekDay)\r\n {\r\n pCell.date = pDate.getDate();\r\n pCell.innerHTML = pDate.getDate();\r\n pCell.onmouseout = function() { this.className = \"\"; };\r\n pCell.onmouseover = function() { this.className = \"calendar_body_over\"; };\r\n pCell.onclick = function(){ if (pCalendar.onselect != null) pCalendar.onselect(iYear, iMonth+1, this.date) };\r\n \r\n if (pDate.getDate() == iDay) pCell.className = \"calendar_body_over\";\r\n\r\n pDate.setDate(pDate.getDate() + 1);\r\n iCurrentWeekDay = (pDate.getMonth() == iMonth ? pDate.getDay() : -1);\r\n }\r\n }\r\n\r\n if(iCurrentWeekDay == -1) break;\r\n }\r\n }\r\n \r\n\r\n pCalendar.paintMonth = function(iYear, iMonth, iDay)\r\n {\r\n pHeader.rows[0].cells[0].onclick = function(){ pCalendar.paintMonth(iYear-1, iMonth, iDay); };\r\n pHeader.rows[0].cells[1].innerHTML = iYear;\r\n pHeader.rows[0].cells[2].onclick = function(){ pCalendar.paintMonth(iYear+1, iMonth, iDay); };\r\n\r\n pCalendar.clearBody();\r\n\r\n var iIndex = 0;\r\n \r\n //TODO: support different languages.\r\n var aMonths = new Array(\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\");\r\n\r\n for (var r = 0; r < 3; r++)\r\n {\r\n var pRow = pBody.insertRow(-1);\r\n\r\n for (var c = 0; c < 4; c++)\r\n {\r\n var pCell = pRow.insertCell(-1);\r\n pCell.month = iIndex;\r\n pCell.innerHTML = aMonths[iIndex];\r\n pCell.className = (iIndex == iMonth ? \"calendar_cell_month_over\" : \"calendar_cell_month\");\r\n pCell.onclick = function(){ if (pCalendar.onselectmonth != null && pCalendar.onselectmonth(iYear, this.month, iDay) == false) return; pCalendar.paintDate(iYear, this.month, iDay); };\r\n pCell.onmouseout = function(){ this.className = \"calendar_cell_month\"; };\r\n pCell.onmouseover = function(){ this.className = \"calendar_cell_month_over\"; };\r\n \r\n iIndex++;\r\n }\r\n }\r\n }\r\n\r\n pCalendar.clearBody = function()\r\n {\r\n while (pBody.firstChild != null) pBody.removeChild(pBody.firstChild);\r\n }\r\n\r\n /**\r\n * Show the calendar using the specified date and relative to the specified object.\r\n * If the date is null or undefined, use the current date.\r\n *\r\n * @param sDate can be a null, undifiend, string, or Date object.\r\n * @param oRelativeTo an html object.\r\n * @param iOffsetX optional integer x offset. Default is 20.\r\n * @param iOffsetY optional integer y offset. Default is -10.\r\n */\r\n pCalendar.showRelativeTo = function(sDate, oRelativeTo, iOffsetX, iOffsetY)\r\n {\r\n var oDate = new Date();\r\n\r\n iOffsetX = UI.defaultValue(iOffsetX, 20);\r\n iOffsetY = UI.defaultValue(iOffsetY, -10);\r\n \r\n if (typeof(sDate) == \"string\")\r\n {\r\n var aDate = sDate.split(\"-\");\r\n oDate.setFullYear(parseInt(aDate[0]));\r\n oDate.setMonth(parseInt(aDate[1])-1);\r\n oDate.setDate(parseInt(aDate[2]));\r\n }\r\n\r\n pCalendar.paintDate(oDate.getFullYear(), oDate.getMonth(), oDate.getDate());\r\n\r\n UI.showPopupRelativeTo(pCalendar, oRelativeTo, iOffsetX, iOffsetX);\r\n };\r\n\r\n return pCalendar;\r\n}",
"function generateMainCal(){\n document.write(\"<div id = 'calendar'></div><div id = 'activity'></div>\");\n}",
"function init() {\n var d = new Date(); // current time from computer's clock\n \n // Set up the object date\n var yyyy = d.getUTCFullYear();\n var mm = d.getUTCMonth()+1;\n var dd = d.getUTCDate();\n var h = d.getUTCHours();\n var m = d.getUTCMinutes();\n var s = d.getUTCSeconds()+1e-3*d.getUTCMilliseconds();\n var dateString = generateDateString(yyyy,mm,dd);\n var timeString = generateTimeString(h,m,s);\n var D = getDm(yyyy,mm,dd,0) + (h+m/60+s/3600)/24;\n var T = D/36525;\n var dT = DeltaT(T);\n date = {yyyy:yyyy, mm:mm, dd:dd, h:h, m:m, s:s,\n dateString:dateString, \n timeString:timeString, D:D, T:T, dT:dT};\n \n tipsEnabled = true;\n tips = [[], [], []];\n highPrecCalInTips = true;\n $(\"#canvasNorth\").on(\"click\", function(event) {displayPopup(event, \"canvasNorth\");});\n $(\"#canvasCentral\").on(\"click\", function(event) {displayPopup(event, \"canvasCentral\");});\n $(\"#canvasSouth\").on(\"click\", function(event) {displayPopup(event, \"canvasSouth\");});\n \n starCharts();\n}",
"function writeCalendar()\r\n{\r\n var calDocBottom = GetCalendarContents();\r\n document.getElementById('trBottom').innerHTML = calDocBottom;\r\n}",
"mountCalender() {\n this.mountMonthAndYear();\n this.mountWeek();\n this.mountDate();\n }",
"function displayCalendar() {\n\t$(function() {\n\t\tif ($('#calendar').length == 0) {\n\t\t\tsetTimeout(\"displayCalendar()\", 250);\n\t\t}\n\t\t$('#calendar').datepicker( \n\t\t\t{navigationAsDateFormat: true,\n\t\t\tclearText: 'Erase', \t\n\t\t\thideIfNoPrevNext: false,\n\t\t\tprevText: '', \n\t\t\tnextText: '', \n\t\t\tchangeYear: false,\n\t\t\tshowStatus: false,\n\t\t\tcurrentText:'', \n\t\t\tfirstDay:0,\n\t\t\t_currentClass: 'highlite',\n\t\t\tchangeMonth: false, \n\t\t\tchangeFirstDay: false, \n\t\t\thighlightWeek: false, \n\t\t\thighlightDays: false,\n\t\t\trangeSelect: false, \n\t\t\tgotoCurrent: true \n\t\t});\n\t\tif ($.browser.msie && parseInt($.browser.version()) < 7) {\n\t\t\t$('.ui-datepicker-current-day').trigger('mouseout');\n\t\t}\n\t\t$('#calendar').find('a').each(function(){\n\t\t\t$(this).replaceWith($('<p>'+$(this).html()+'</p>'));\n\t\t});\n\t\t$('#calendar').find('td').unbind('click').unbind('mousout');\n\t\t$('#calendar').find('*').unbind('click').unbind('mouseup').unbind('mousedown');\n\t\t$('#calendar').unbind('click').unbind('mouseup').unbind('mousedown');\n\t});\n}",
"function InitializeCalenderStartEnd() \r\n{\r\n \r\n // initialize blank cell \r\n blankCell = \"<TD align=center style='background-color:#B7CA97;'></TD>\"; \r\n \r\n // calendar begin\r\n var weekdays = GetWeekdayList(); \r\n calendarBegin = \"<CENTER>\";\r\n if (isNav) \r\n {\r\n calendarBegin += \"<TABLE CELLPADDING=0 CELLSPACING=0 BORDER=0 ALIGN=CENTER width=100%><TR><TD>\";\r\n }\r\n calendarBegin += \"<TABLE class='daysgrid' align='center' 'width=100%'>\" + weekdays; \r\n // calender end\r\n calendarEnd = \"\"; \r\n if (isNav) \r\n {\r\n calendarEnd += \"</TD></TR></TABLE>\";\r\n }\r\n calendarEnd += \"</TABLE>\" + \"</CENTER>\";\r\n}",
"function generateCalendar() {\n const dates = fillDates(vm.currentDate);\n const weeks = [];\n while (dates.length > 0) {\n weeks.push(dates.splice(0, 7));\n }\n vm.weeks = weeks;\n vm.lastWeek = vm.weeks[vm.weeks.length - 1];\n }",
"function drawNormalWatch() {\n var datetime = tizen.time.getCurrentDateTime(),\n hour = datetime.getHours(),\n minute = datetime.getMinutes(),\n second = datetime.getSeconds(),\n nextMove = 1000 - datetime.getMilliseconds();\n\n // Clear canvas\n ctxContent.clearRect(0, 0, ctxContent.canvas.width, ctxContent.canvas.height);\n \n // Draw the text for date\n //renderText(ctxContent, hour, center.x, center.y + 25 , 300, \"#cccccc\");\n \n // Draw the minute/hour circle\n //renderCircle(ctxContent, center, watchRadius, \"#CCCCCC\", 3/2 * Math.PI, 2 * Math.PI / 60 * (minute + second / 60) - 0.5 * Math.PI);\n //renderCircle(ctxContent, center, watchRadius, \"#CCCCCC\",2 * Math.PI / 60 * (minute + (second - 1) / 60) - 0.5 * Math.PI, 3/2 * Math.PI);\n var x = 180 + 180 * Math.sin(Math.PI * 2 * (minute + second / 60) / 60);\n var y = 180 + 180 * Math.sin(Math.PI * 2 * (minute + second / 60 - 15) / 60);\n document.getElementById(\"svg\").innerHTML = '<defs>' +\n\t '<filter id=\"f1\" x=\"-50%\" y=\"-50%\" width=\"200%\" height=\"200%\">' +\n\t ' <feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"2\" result=\"gaussOut\" />' +\n\t ' <feColorMatrix result=\"matrixOut\" in=\"gaussOut\" type=\"matrix\"' +\n \t'\t\tvalues=\"0 0 0 0 0'+\n\t '\t\t\t\t0 0 0 0 0'+\n\t ' 0 0 0 0 0'+\n\t ' 0 0 0 1 0\" />' +\n\t ' <feOffset result=\"offOut\" in=\"matrixOut\" dx=\"3\" dy=\"3\" />' +\n\t ' <feBlend in=\"gaussOut\" in2=\"offOut\" mode=\"normal\" />' +\n\t '</filter>' +\n\t '<clipPath id=\"c\">' +\n\t ' <path d=\"M 180 0' +\n\t\t '\t\t\tA 180 180 0 1 1 ' + x + ' ' + y +\n\t\t '\t\t\tL 180 180 Z\" />' +\n\t ' </clipPath>' +\n\t ' <clipPath id=\"notc\">' +\n\t ' <path d=\"M ' + x + ' ' + y +\n\t\t '\t\t\tA 180 180 0 1 1 180 0' +\n\t\t '\t\t\tL 180 180 Z\" />' +\n\t ' </clipPath>' +\n\t ' <filter id=\"f2\" x=\"0\" y=\"0\" width=\"200%\" height=\"200%\">' +\n\t ' <feColorMatrix result=\"matrixOut\" in=\"SourceGraphic\" type=\"matrix\"' +\n '\t values=\"0 0 0 0 0'+\n\t '\t\t\t\t0 0 0 0 0'+\n\t ' 0 0 0 0 0'+\n\t ' 0 0 0 1 0\" />' +\n\t ' <feOffset result=\"offOut\" in=\"matrixOut\" dx=\"3\" dy=\"3\" />' +\n\t ' <feBlend in=\"SourceGraphic\" in2=\"offOut\" mode=\"normal\" />' +\n\t ' </filter>' +\n\t '</defs>' +\n\t '<text text-anchor=\"middle\" x=\"180\" y=\"280\" font-family=\"helvetica\" filter=\"url(#f2)\" font-size=\"300px\" clip-path=\"url(#notc)\" fill=\"lightgrey\">' + hour + '</text>' +\n\t \n\t '<text text-anchor=\"middle\" x=\"180\" y=\"280\" font-family=\"helvetica\" filter=\"url(#f1)\" clip-path=\"url(#c)\" font-size=\"300px\" fill=\"lightgrey\">' + hour + '</text>' +\n\t '<path d=\"M 180 0' +\n\t '\t\t\tA 180 180 0 1 1 ' + x + ' ' + y +\n\t '\t\t\tL 180 180 Z\" fill=\"lightgrey\" fill-opacity=\"0.4\" />\"' +\n\t '<line x1=\"180\" y1=\"0\" x2=\"180\" y2=\"180\" stroke=\"black\" stroke-width=\"2\" stroke-opacity=\"0.4\"/>\"' +\n\t '<line x1=\"180\" y1=\"180\" x2=\"'+ x +'\" y2=\"'+ y+'\" stroke-width=\"2\" stroke=\"black\" stroke-opacity=\"0.4\"/>\"'\n\n //document.getElementById(\"hour\").innerHTML = hour;\n animTimeout = setTimeout(function() {\n animRequest = window.requestAnimationFrame(drawNormalWatch);\n }, nextMove);\n }"
]
| [
"0.71955496",
"0.70713305",
"0.7017036",
"0.68672836",
"0.6840271",
"0.6832336",
"0.6719701",
"0.6679412",
"0.6580672",
"0.64909595",
"0.64786917",
"0.6460753",
"0.6451954",
"0.6424762",
"0.6388877",
"0.6315354",
"0.6273391",
"0.6270469",
"0.6266505",
"0.6210532",
"0.61417776",
"0.61370796",
"0.61368245",
"0.6132592",
"0.61142766",
"0.6108743",
"0.60678345",
"0.60621876",
"0.60516214",
"0.6034679"
]
| 0.73711884 | 0 |
Set the creep's new target. | function setNewTarget(creep) {
var modified_extension;
var extensionTarget = creep.pos.findClosestByRange(FIND_STRUCTURES, {filter: str => (str.structureType == STRUCTURE_EXTENSION) && (str.energy < str.energyCapacity)});
if (typeof extensionTarget == "undefined") {
creep.memory.target = creep.pos.findClosestByPath(FIND_MY_SPAWNS)["id"];
creep.moveTo(Game.getObjectById(creep.memory["target"]));
}
else {
creep.memory.target = extensionTarget["id"];
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"setTarget(target) {\n this.target = target;\n }",
"setTowerTarget(tower, target) {\n if (target !== undefined) {\n return super.setTowerTarget(tower, target)\n }\n if (tower.target && tower.target.id && this.enemies.byId[tower.target.id]) {\n return tower.setTarget(this.enemies.byId[tower.target.id])\n }\n tower.selectTarget()\n }",
"function SetNewTarget (newTarget: Transform) \n{\n target = newTarget;\n}",
"function setTarget(target : GameObject) {\n\tthis.target.setTarget(target);\n}",
"function SetTarget (newTarget : Transform) {\n\tSetTarget (newTarget, false);\n}",
"setTarget(x, y, z) {\n this[$goalTarget].set(x, y, z);\n }",
"setTarget(x, y) {\n // override this in sublcasses.\n }",
"sendSetTowerTarget(tower, target) {\n console.log('In sendSetTowerTarget');\n this.setTowerTarget(tower, target)\n }",
"changeTarget(target) {\n this.targetElem = target\n }",
"function pushTarget(_target){\n // push to stack\n // if(Dep.target){\n // targetStack.push(_target);\n // }\n\n // set current target \n Dep.target = _target;\n}",
"setSelectedTowerTarget(target) {\n const tower = this.selectedEntity\n if (!target || !tower || tower.type !== 'Tower') { return }\n this.sendSetTowerTarget(tower, target)\n }",
"setTarget(x, y) {\n this.spawnX = x;\n this.spawnY = y;\n }",
"function pushTarget( target ) {\n if ( Dep.target ) {\n targetStack.push( target );\n }\n Dep.target = target;\n}",
"setTarget(target) {\n this.player = target;\n }",
"function ManageTarget(){}",
"async setDefaultTarget(target) {\n if (!target) {\n target = await this.showTargetSelector();\n }\n if (!target) {\n return;\n }\n await this._setDefaultBuildTarget(target);\n }",
"function makeTarget(newState) {\n\t\tjsPlumb.makeTarget(newState, {\n\t\t\tanchor : 'Continuous',\n\t\t\tendpoint : 'Blank'\n\t\t});\n\t}",
"setTarget(x, y) {\n this.destinationX = x;\n this.destinationY = y;\n }",
"setBaseTarget(key, value) {\n this.baseTarget[key] = value;\n }",
"set(targetIndex, value) {\n\t\tlet targetNode = this._getNodeAtIndex(targetIndex);\n\t\tif (targetNode === null) {\n\t\t\treturn;\n\t\t}\n\t\ttargetNode.value = value;\n\t}",
"async _targetDoorStateSetHandler(newValue, callback) {\n const d = this.device\n\n if (this.targetState === newValue) {\n callback()\n return\n }\n\n this._targetState = newValue\n\n const position = newValue === Characteristic.TargetDoorState.OPEN\n ? 100\n : 0\n\n this.log.debug(\n 'Setting',\n this._positionProperty,\n 'of device',\n d.type,\n d.id,\n 'to',\n position\n )\n\n try {\n await this._setPosition(position)\n callback()\n } catch (e) {\n handleFailedRequest(\n this.log,\n d,\n e,\n 'Failed to set ' + this._positionProperty\n )\n callback(e)\n }\n }",
"function setTarget() {\n target = Math.floor( Math.random() * 101 ) + 19; // creates a random # between 19 and 120(inclusive)\n $(\"#target-score\").html(target);\n console.log(target);\n }",
"function popTarget() {\n Dep.target = targetStack.pop();\n}",
"function targetPlanet(name) {\n // Find the planet\n var newtarget = getPlanet(name);\n if (newtarget == null) {\n console.log(\"Error: Attempted to target an unknown planet.\");\n return;\n }\n\n // Set the target\n target = newtarget;\n\n // Move the camera to face the planet\n updateView();\n}",
"_work(creep) {\r\n \tthis._commuteBetweenSourceAndTarget(creep, target => creep.build(target));\r\n }",
"function jump(target, coords = []) {\n const originNode = traverseTree(origin.tree, coords);\n\n // set the state of the origin tree\n originNode.component.setState(target.state, () => {\n // iterate through new children once state has been set\n target.children.forEach((child, i) => {\n jump(child, coords.concat(i));\n });\n });\n }",
"function setPork() {\n meatType = 2;\n}",
"moveToTarget(tX, tY) {\n this.moving = true;\n this.destination = { x: tX, y: tY };\n this.path = this.astar({ x: this.me.x, y: this.me.y }, this.destination);\n }",
"get target() {\n return this._target;\n }",
"setRenderTarget(target) {\n if (this.currentTarget !== target) {\n this.flush();\n if (target == null) {\n this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null);\n this.gl.viewport(0, 0, this.canvas.width, this.canvas.height);\n }\n else {\n this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, target.frameBuffer);\n this.gl.viewport(0, 0, target.width, target.height);\n }\n this.currentTarget = target;\n }\n }"
]
| [
"0.689435",
"0.6622014",
"0.66070825",
"0.6514949",
"0.6512465",
"0.6355385",
"0.6221557",
"0.6211309",
"0.6153178",
"0.60638857",
"0.6062399",
"0.5959567",
"0.59303045",
"0.59299266",
"0.57968056",
"0.5790191",
"0.57532614",
"0.5665332",
"0.5622372",
"0.5524426",
"0.54695344",
"0.5427313",
"0.54158145",
"0.5375794",
"0.53156114",
"0.5290472",
"0.5286087",
"0.5250405",
"0.5191291",
"0.5186923"
]
| 0.7246137 | 0 |
Max sum in the array | function maxSum() {
const array = [4, 6, -3, 5, -2, 1];
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function maxSum(arr) {\n let cur_max = arr[0];\n let max_so_far = arr[0];\n for (let i in arr) {\n cur_max = Math.max(arr[i], curr_max + arr[i]);\n max_so_far = Math.max(max_so_far, cur_max);\n }\n return max_so_far;\n}",
"function alternativeMaxSum(arr) {\n arr.sort((a, b) => a - b);\n\n let sum = arr.reduce((a,b) => a + b);\n let minSum = sum - arr[arr.length - 1];\n let maxSum = sum - arr[0];\n\n console.log(minSum + \" \" + maxSum);\n}",
"function maxSum(array) {\n let currentSum = 0\n let maxSum = 0\n for(let i = 0; i < array.length; i++) {\n currentSum = currentSum + array[i]\n if(currentSum > currentSum + array[i + 1]) {\n maxSum = currentSum\n }\n }\n console.log(maxSum)\n}",
"function getMaxSubSum(arr) {\n\tvar sum = 0;\n\tvar max = 0;\n\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tsum += arr[i];\n\n\t\tif(sum <= 0) {\n\t\t\tsum = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(sum > max) {\n\t\t\tmax = sum;\n\t\t}\n\n\t}\n\n\treturn max;\n}",
"function maxSumSubArray(array) {\n let maxSum = 0;\n let currSum = 0;\n\n for (let i = 0; i < array.length; i++) {\n\n currSum = currSum + array[i];\n if (currSum > maxSum) {\n maxSum = currSum;\n }\n if (currSum < 0){\n currSum = 0\n }\n }\n return maxSum;\n}",
"function largestSubArraySum (array) {\n if (array.length < 1) return null;\n\n let maxSum = 0;\n let currMaxSum = 0;\n\n for (let num of array) {\n currMaxSum = Math.max(num, currMaxSum + num);\n maxSum = Math.max(currMaxSum, maxSum);\n }\n return maxSum;\n}",
"function maxSubarraySum(arr, num) {\n if ( num > arr.length){\n return null;\n }\n var max = -Infinity;\n for (let i = 0; i < arr.length - num + 1; i ++){\n temp = 0;\n for (let j = 0; j < num; j++){\n temp += arr[i + j];\n }\n if (temp > max) {\n max = temp;\n }\n // console.log(temp,max);\n }\n return max;\n }",
"function maxSumSubArray(arr){\n\tvar max_so_far = arr[0],max_here = arr[0];\n\tfor(var i = 1; i<arr.length;i++){\n\t\tmax_here += arr[i];\t\n\t\t// to handle -ve numbers\n\t\tif(max_here < arr[i]){\n\t\t\tmax_here = arr[i];\n\t\t}\n\t\tif(max_so_far < max_here){\n\t\t\tmax_so_far = max_here;\n\t\t}\n\t}\n\tconsole.log(max_so_far);\n\treturn max_so_far;\n}",
"function maxSubsetSum(arr) {\n\n if (arr.length === 0 ) return 0\n if (arr.length === 1 ) return arr[0]\n if (arr.length === 2 ) return Max.apply(this, arr[0], arr[1])\n // filter out all the - and the zeros from the equation: there\n // is no point ever putting a minus in there, ever.\n // Then for the rest, we need to see which ones can go next to each other.\n\n // Generate the sum map\n let prev = 0\n // let sumMap = arr.reverse().map((v)=> v > 0 ? prev+=v : v)\n // 1-, 3, 5\n\n let i = 3\n let maxes = [getAboveZeroPart(arr[0]), getAboveZeroPart(arr[1])]\n maxes[2] = getAboveZeroPart(arr[2]) + maxes[0]\n\n while(i < arr.length){\n maxes[i] = getAboveZeroPart(arr[i]) + Math.max(maxes[i-2], maxes[i-3])\n i++\n }\n\n // console.log(Math.max(maxes[maxes.length-1], maxes[maxes.length-2]))\n\n return Math.max(maxes[maxes.length-1], maxes[maxes.length-2])\n\n // Always pick one to two\n}",
"function maxSumInArray3(arr) {\n let currentSum = 0;\n let maxSum = 0;\n\n for(let i=0; i < arr.length; i++) {\n \n let currentNum = arr[i];\n currentSum = Math.max((currentSum + currentNum), 0);\n maxSum = Math.max(currentSum, maxSum);\n }\n return maxSum;\n}",
"function getMaxSubSum(arr) {\n let maxSum = 0;\n let partialSum = 0;\n //Iterate through array\n for (let item of arr) {\n //Add item to partialSum\n partialSum += item;\n //Remember the maximum\n maxSum = Math.max(maxSum,partialSum);\n //Zero if inegative\n if (partialSum < 0) partialSum = 0;\n }\n return maxSum;\n}",
"function maxSubarraySum1(arr, num) {\n let maxSum = 0;\n let tempSum = 0;\n if (arr.length < num) return null;\n for (let i = 0; i < num; i++) {\n maxSum += arr[i];\n }\n tempSum = maxSum;\n for (let i = num; i < arr.length; i++) {\n tempSum = tempSum - arr[i - num] + arr[i];\n maxSum = Math.max(maxSum, tempSum);\n }\n console.log(maxSum);\n return maxSum;\n}",
"function maxSubarraySum(arr, num) {\n let maxSum = 0;\n for (let i = 0; i < num; i++) {\n maxSum += arr[i];\n }\n console.log(maxSum);\n let tempSum = maxSum;\n for (let i = num; i < arr.length; i++) {\n tempSum = tempSum - arr[i - num] + arr[i];\n maxSum = Math.max(maxSum, tempSum);\n }\n return maxSum;\n}",
"function getMaxSubSum(arr) {\n let maxSum = 0;\n let partialSum = 0;\n\n for (let item of arr) { // for each item of arr\n partialSum += item; // add it to partialSum\n maxSum = Math.max(maxSum, partialSum); // remember the maximum\n if (partialSum < 0) partialSum = 0; // zero if negative\n }\n\n return maxSum;\n}",
"function getMaxSubSum(arr) {\n let maxSum = 0;\n let partialSum = 0;\n\n for (let item of arr) { // for each item of arr\n partialSum += item; // add it to partialSum\n maxSum = Math.max(maxSum, partialSum); // remember the maximum\n if (partialSum < 0) partialSum = 0; // zero if negative\n }\n\n return maxSum;\n}",
"function maxSubsetSum(arr) {\n let incl = 0;\n let excl = 0;\n\n for (let i = 0; i < arr.length; i++) {\n \n let newExcl = Math.max(incl, excl);\n\n incl = excl + arr[i];\n excl = newExcl;\n }\n\n return Math.max(incl, excl);\n\n}",
"function maxSubsetSum(arr) {\n let arrayOfSums = [];\n if ( arr.length === 0 ) {\n return 0;\n } else if (arr.length === 2 ) {\n return Math.max( arr[0], arr[1] );\n }\n else {\n arrayOfSums.push(arr[0]);\n arrayOfSums.push(Math.max( arr[0], arr[1] ));\n for( let i = 2; i < arr.length; i++ ) {\n // current\n let currentValue = arr[ i ];\n // current value + the max sum 2 positions before in the arrayOfSums\n let currensPlusNonAdjacent = arrayOfSums[ i - 2 ] + arr[ i ];\n // the value in the middle in the arrayOfSums\n let middle = arrayOfSums[ i - 1 ];\n // the max of current and sum\n let maxOfCurrents = Math.max(currensPlusNonAdjacent, currentValue);\n // the max of the 3 is store\n arrayOfSums[i] = Math.max( maxOfCurrents, middle );\n }\n }\n return arrayOfSums[ arrayOfSums.length -1 ];\n}",
"function largestSum(arr){\n\tvar object = [];\n\tsubarr = 0;\n\tfor (var i = 0; i < arr.length; i++){\n\t\tfor (var j = 1; j <= arr.length; j++){\n\t\t\tsubarr = (arr.slice(i,j));\n\t\t\tsum = 0;\n\t\t\tfor (var k = 0; k < subarr.length; k++){\n\t\t\t\tsum += subarr[k];\n\t\t\t}\n\t\t\tobject.push({subarr: subarr, sum: sum});\n\t\t}\n\t}\n\tobject.sort(function(c,b){\n\t\treturn b.sum - c.sum;\n\t});\n\treturn object[0].subarr;\n}",
"function miniMaxSum(arr) {\n // Write your code here \n var totals = [];\n for (let i=0; i<arr.length; i++) { \n let sum = 0;\n for (let j=0; j<arr.length; j++) { \n if (j != i) {\n sum += arr[j];\n } \n }\n totals.push(sum); \n }\n console.log(Math.min.apply(Math,totals)+\" \"+Math.max.apply(Math,totals));\n}",
"function maxSubarraySum(arr, num) {\n if ( num > arr.length){\n return null;\n }\n var max = -Infinity;\n for (let i = 0; i < arr.length - num + 1; i ++){\n temp = 0;\n for (let j = 0; j < num; j++){\n temp += arr[i + j];\n }\n if (temp > max) {\n max = temp;\n }\n }\n return max;\n}",
"function maxSubarraySum(arr, num) {\n if (arr.length < num) return null;\n\n let total = 0;\n // Storing the first 2 values in total\n for (let i = 0; i < num; i++) {\n total += arr[i];\n }\n\n // Let's put total in a temporary variable to utilise it\n let currentTotal = total;\n // Iterate over array starting at num\n // Because now we want to use currentTotal to store those values\n // Then at the end get the maximum value\n for (let i = num; i < arr.length; i++) {\n currentTotal += arr[i] - arr[i-num];\n // Get the max\n total = Math.max(total, currentTotal);\n\n }\n return total;\n}",
"function maxSum(arr){\n maxSum = 0 \n var currentSum\n var maxLength\n var someArr\n for(i=0;i<arr.length;i++){\n //console.log(`starting at ${i}`)\n maxLength = arr.length-i \n\n for (x=1;x<maxLength+1;x++){\n //currentSum = sumMe(arr.slice(i,i+x))\n someArr = [...arr.slice(i,i+x)]\n currentSum = someArr.reduce((a,b)=>{return a+b})\n //console.log(x,someArr,currentSum)\n if (currentSum>maxSum){\n maxSum = currentSum\n }\n }\n }\n return maxSum\n}",
"function maxSubarraySum(arr, num) {\r\n if ( num > arr.length){\r\n return null;\r\n }\r\n var max = -Infinity;\r\n for (let i = 0; i < arr.length - num + 1; i++){\r\n let temp = 0;\r\n for (let j = 0; j < num; j++){\r\n temp += arr[i + j];\r\n }\r\n if (temp > max) {\r\n max = temp;\r\n }\r\n }\r\n return max;\r\n}",
"function maxSubsetSum(arr) {\n const result = [Math.max(arr[0], 0), Math.max(arr[0], arr[1], 0)];\n\n for (let i = 2; i < arr.length; i++) {\n result.push(Math.max(result[i - 1], result[i - 2] + arr[i]));\n }\n\n return result.slice(-1);\n}",
"function maxSubsetSumNoAdjacent(array) {\n if (array.length === 0) return 0;\n if (array.length === 1) return array[0];\n \n // copy input array\n // this ensures 1st base case maxSums[0] = array[0]\n let maxSums = array.slice(0);\n // 2nd base case gets max value of the 1st 2 values\n maxSums[1] = Math.max(array[0], array[1]);\n \n for (let i = 2; i < array.length; i++) {\n maxSums[i] = Math.max(maxSums[i - 1], maxSums[i - 2] + array[i]);\n }\n // return the last value in maxSums \n return maxSums[maxSums.length - 1];\n}",
"function maxSubarraySum(arr,num) { //time complexity - O(n)\r\n let maxSum = 0;\r\n let tempSum = 0;\r\n if (arr.length < num) return null;\r\n\r\n for(let i = 0; i < num; i++) {\r\n maxSum += arr[i];\r\n // console.log(maxSum) //3\r\n }\r\n tempSum = maxSum; \r\n for (let i = num; i < arr.length; i++) { \r\n tempSum = tempSum - arr[i - num] + arr[i]; //7\r\n maxSum = Math.max(maxSum, tempSum);\r\n }\r\n return maxSum;\r\n}",
"function miniMaxSum(arr) {\n const sorted = arr.sort();\n \n const add = (accum, val) => accum + val;\n \n const min = sorted.slice(0,4).reduce(add);\n const max = sorted.slice(1).reduce(add);\n \n console.log(`${min} ${max}`);\n}",
"function maxSubArrSum(arr, num) {\n if ( num > arr.length){\n return null;\n }\n var max = -Infinity;\n for (let i = 0; i < arr.length - num + 1; i ++){\n temp = 0;\n for (let j = 0; j < num; j++){\n temp += arr[i + j];\n }\n if (temp > max) {\n max = temp;\n }\n }\n return max;\n }",
"function miniMaxSum(arr) {\n arr.sort((a, b) => a - b);\n \n let minSum = arr.slice(0, arr.length - 1);\n minSum = minSum.reduce((a,b) => a + b);\n\n let maxSum = arr.slice(1, arr.length);\n maxSum = maxSum.reduce((a,b) => a + b);\n \n console.log(minSum + \" \" + maxSum);\n}",
"function maxSubarraySum(arr, num) {\n if (arr.length < num) return null;\n let max = 0;\n for (let i = 0; i < num; i++) {\n max += arr[i];\n }\n let tempMax = max;\n for (let i = num; i < arr.length; i++) {\n tempMax = tempMax - arr[i-num] + arr[i];\n max = Math.max(max, tempMax);\n }\n return max;\n}"
]
| [
"0.79587615",
"0.7882176",
"0.7668545",
"0.76643306",
"0.75575155",
"0.75424725",
"0.7474357",
"0.7403314",
"0.74032277",
"0.74018055",
"0.73536205",
"0.73458606",
"0.733912",
"0.7329903",
"0.7329903",
"0.7328786",
"0.73031586",
"0.72859037",
"0.72772527",
"0.7266382",
"0.7232771",
"0.72286576",
"0.72262424",
"0.7215953",
"0.72041166",
"0.7200491",
"0.7193805",
"0.7188576",
"0.7177168",
"0.7174492"
]
| 0.85247463 | 0 |
function that logs the data into the call log in the spreadsheet | function logData(sheet, date, caller, duration, callNotes, resolutionNotes, callBack, callBackDate) {
sheet.insertRowBefore(20);
sheet.getRange("A20").setValue(date);
sheet.getRange("B20").setValue(caller);
sheet.getRange("C20").setValue(duration);
sheet.getRange("D20:H20").setValue(callNotes);
sheet.getRange("D20:H20").merge();
sheet.getRange("I20:M20").setValue(resolutionNotes);
sheet.getRange("I20:M20").merge();
sheet.getRange("N20").setValue(callBack);
sheet.getRange("O20").setValue(callBackDate);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function logger(log){\n return;\n \n // - try fetching the sheet by name\n var sheetObject = SpreadsheetApp.getActive().getSheetByName(\"DebugLog\");\n \n // - if has no sheet\n if (sheetObject == null) {\n sheetObject = SpreadsheetApp.getActive().insertSheet(\"DebugLog\");\n \n }\n \n // - append header row information\n sheetObject.appendRow([new Date(), log]);\n}",
"function logger(someList){\n someList.push(String(new Date()));\n logsheet.appendRow(someList);\n}",
"function SaveToLog(Log) {\n LogToConsole(\"Updating Log sheet...\", true, 0);\n\n var rowToInsert = [];\n for (var i = 0; i < logHeaders.length; i++) {\n rowToInsert.push(null); //pre-fill with null values\n }\n rowToInsert[0] = (Utilities.formatDate(new Date(), GetSettingsValue(\"Time zone\"), GetSettingsValue(\"Date format\"))); //Place the current date+time to the first cell\n var Components = Object.getOwnPropertyNames(Log);\n for (var i = 0; i < Components.length; i++) {\n var Properties = Object.getOwnPropertyNames(Log[Components[i]]);\n for (var j = 0; j < Properties.length; j++) {\n var key = Components[i] + '_' + Properties[j];\n if (!logHeaders.includes(key)) {\n logHeaders.push(key); //add key to the header's end\n rowToInsert.push(); //add empty value to the end\n }\n rowToInsert[logHeaders.indexOf(key)] = Log[Components[i]][Properties[j]]; //insert the value under the matching heading\n }\n }\n LogToConsole(\"Heading: \" + logHeaders, true, 2);\n LogToConsole(\"Data: \" + rowToInsert, true, 2);\n logSheet.getRange(1, 1, 1, logHeaders.length).setValues([logHeaders]);\n logSheet.appendRow(rowToInsert);\n //ApplyFormatting();\n}",
"function sendAll(datas) {\n var success = false;\n var sheet = SpreadsheetApp.openById('1fHShi7L1ZLxKPYojl7gjMxFjiL6L4txAeZ7akf9vzd0').getActiveSheet(); // ID for Timesheet\n var logSheet = SpreadsheetApp.openById('1fHShi7L1ZLxKPYojl7gjMxFjiL6L4txAeZ7akf9vzd0').getSheetByName(\"Log\");\n var duration = null;\n var total = null;\n jump();\n var Avals = sheet.getRange(\"A1:A\").getValues();\n var Alast = Avals.filter(String).length;\n var lastrow = sheet.getRange(Alast+1, 1, 1, 9);\n var values = [[datas.enterDate, datas.enterStartTime, datas.enterEndTime, duration, total, datas.enterFullName, datas.enterCategory, datas.enterActivity, datas.enterLink]];\n lastrow.setValues(values);\n var timezone = \"GMT+\" + new Date().getTimezoneOffset()/60;\n var date = Utilities.formatDate(new Date(), timezone, \"yyyy-MM-dd HH:mm\"); \n logSheet.appendRow([date, \"Data entered by \" + datas.enterFullName]);\n return success = true;\n}",
"function save_data(tag, value){\r\n Logger.log(\"--- save_data ---\"); \r\n \r\n \r\n try {\r\n var dateTime = new Date();\r\n \r\n // Paste the URL of the Google Sheets starting from https thru /edit\r\n // For e.g.: https://docs.google.com/..../edit \r\n var ss = SpreadsheetApp.openByUrl(\"https://docs.google.com/---Your-Script-ID--Goes-Here---/edit\");\r\n var dataLoggerSheet = ss.getSheetByName(\"DataLogger\");\r\n \r\n \r\n // Get last edited row from DataLogger sheet\r\n var row = dataLoggerSheet.getLastRow() + 1;\r\n \r\n \r\n // Start Populating the data\r\n dataLoggerSheet.getRange(\"A\" + row).setValue(row -1); // ID\r\n dataLoggerSheet.getRange(\"B\" + row).setValue(dateTime); // dateTime\r\n dataLoggerSheet.getRange(\"C\" + row).setValue(tag); // tag\r\n dataLoggerSheet.getRange(\"D\" + row).setValue(value); // value\r\n \r\n \r\n }\r\n \r\n catch(error) {\r\n Logger.log(JSON.stringify(error));\r\n }\r\n \r\n Logger.log(\"--- save_data end---\"); \r\n}",
"function getLogSheet(){\n var ss = openSheetById();\n var sheet = ss.getActiveSheet();\n var rows = sheet.getDataRange();\n var values = rows.getValues();\n \n for(var i = 0; i < values.length; i++){\n var row = values[i];\n Logger.log(row);\n }\n }",
"function log(action) {\n var date = new Date();\n var dateString = date.getFullYear() + \"-\" + ((date.getMonth() < 9) ? \"0\" : \"\") + (date.getMonth() + 1) + \"-\" + ((date.getDate() < 10) ? \"0\" : \"\") + date.getDate() + \" \" + date.getHours() + \":\" + date.getMinutes() + \":\" + ((date.getSeconds() < 10) ? \"0\" : \"\") + date.getSeconds();\n csvData.push([dateString, user, (currentIndex >= 3) ? \"Authentication\" : \"Create\", passwords[((currentIndex >= 3) ? randomIndex : currentIndex)][0], action]);\n}",
"function logCall() {\n var callData = {\n 'id': vm.callLogUid,\n 'data': {\n 'type': 'call_log',\n 'attributes': {\n 'caller_uid': vm.identity,\n 'callee_uid': vm.partner,\n 'call_sid': vm.activeConversation.sid,\n 'call_type': $stateParams.callType\n }\n }\n };\n\n new CallLogService(callData).$update({id: vm.callLogUid}).then(function(response) {\n log('Call log updated');\n });\n }",
"function record_data(e,fileUrl) {\n try {\n \n //function to copy formats and formulas\n function copyFormatAndFormulas(rangeSource, rangeDestination) {\n rangeSource.copyTo(rangeDestination, {formatOnly: true});\n\n var formulas = rangeSource.getFormulasR1C1();\n for(var x in formulas) {\n for(var y in formulas[x]) {\n if(formulas[x][y] == \"\") continue;\n rangeDestination.getCell(parseInt(x) + 1, parseInt(y) + 1).setFormulaR1C1(formulas[x][y]);\n }\n }\n }\n \n var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty(\"key\"));\n Logger.log(SCRIPT_PROP.getProperty(\"key\"));\n var sheet = doc.getSheets()[0];\n /*var sheet = doc.getSheetByName(\"responses\"); // select the responses sheet*/\n \n var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];\n \n var lastRow = sheet.getLastRow(); // get last row\n var nextRow = sheet.getLastRow()+1; // get next row\n //var formattedDate = Utilities.formatDate(new Date(), \"GMT\", \"yyyy-MM-dd'T'HH:mm:ss'Z'\"); \n var todaysdateformatrecorddata = Utilities.formatDate(todaysdate,\"GMT+2\",\"MM-dd-YYYY' 'HH:mm:ss\")\n var row = [ todaysdateformatrecorddata ]; // first element in the row should always be a timestamp\n // loop through the header columns\n Logger.log(\"are we getting here row\" + row);\n for (var i = 1; i < headers.length; i++) { // start at 1 to avoid Timestamp column\n \n if(headers[i].length > 0 && headers[i] == \"googledriveurl\") {\n row.push(fileUrl); // add data to row\n }\n else if(headers[i].length > 0) {\n row.push(e.parameter[headers[i]]); // add data to row\n }\n }\n \n // more efficient to set values as [][] array than individually\n sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);\n // copy down format and formulas\n var range_lastRow = sheet.getRange(lastRow, 1, 1, row.length);\n var range_nextRow = sheet.getRange(nextRow, 1, 1, row.length);\n copyFormatAndFormulas(range_lastRow, range_nextRow);\n \n \n \n Logger.log(row);\n }\n catch(error) {\n Logger.log(e);\n }\n finally {\n return;\n }\n\n}",
"function getLogSheetRevision(){\n var spreadsheet = SpreadsheetApp.getActive();\n var sheet = spreadsheet.getActiveSheet();\n var values = sheet.getDataRange().getValues();\n for(var i = 0; i < values.length; i++){\n Logger.log(values[i]);\n }\n}",
"function log(data) {\n logger.innerHTML =\n '\\n' + log.line++ + ': ' +\n JSON.stringify(data) + (\n channel_name ?\n ' - from \"' + channel_name + '\" Channel.' :\n '' ) + logger.innerHTML;\n}",
"function clicked(id, phone){\n var gs = SpreadsheetApp.openByUrl(url);\n var sheet = gs.getSheetByName(\"template\");\n sheet.appendRow([id,phone,new Date()])\n \n Logger.log(id)\n Logger.log(phone)\n \n}",
"function saveLog(params) {\r\n if (params.logString !== {}) {\r\n try {\r\n const logString = params.logString;\r\n const logObject = JSON.parse(logString);\r\n\t // This is the object that would be used to post the final data to the Dynamics CRUD method.\r\n const finalLogObject = new Object();\r\n const requestCounterLocal = getRequestCounter();\r\n const activityDetails = {\r\n params: params\r\n };\r\n mapActivityDetails[requestCounterLocal] = activityDetails;\r\n if (logObject.hasOwnProperty('FromandToId')) {\r\n mapActivityDetails[requestCounterLocal].fromandToId = logObject['FromandToId'].Id;\r\n mapActivityDetails[requestCounterLocal].fromandToType = logObject['FromandToId'].LogicalName;\r\n }\r\n else {\r\n mapActivityDetails[requestCounterLocal].fromandToId = currentUserId;\r\n mapActivityDetails[requestCounterLocal].fromandToType = 'systemuser';\r\n reportTrace('logDebug', 'customAmcCif.saveLog message: Defaulting Call From/ To to systemuser');\r\n }\r\n mapActivityDetails[requestCounterLocal].callDirectionCode = logObject['directioncode'];\r\n\t // In case the activity has already been created and has an acitivity id, then it needs to be updated.\r\n if (logObject.hasOwnProperty('ActivityId')) {\r\n reportTrace('logDebug', 'customAmcCif.saveLog message: Activity being updated with Activity Id:- '\r\n + logObject['ActivityId'] + ' and data:- ' + params.logString);\r\n mapActivityDetails[requestCounterLocal].activityId = logObject['ActivityId'];\r\n mapActivityDetails[requestCounterLocal].operation = 'open';\r\n setRecordStatus('phonecall', mapActivityDetails[requestCounterLocal].activityId, '0', '1', function (requestId, ref) { setRecordStatusCallback(requestId, ref); }.bind(null, requestCounterLocal.toString()), function (requestId, ref) { setRecordStatusCallback(requestId, ref); }.bind(null, requestCounterLocal.toString()));\r\n }\r\n else {\r\n for (const property in logObject) {\r\n if (property !== 'FromandToId') {\r\n finalLogObject[property] = logObject[property];\r\n }\r\n }\r\n const activityParties = new Array();\r\n const participantParty = populateActivityParty(requestCounterLocal.toString(), 'customer');\r\n const userParty = populateActivityParty(requestCounterLocal.toString(), 'systemuser');\r\n const participantLogicalName = participantParty.partyid.LogicalName.toLowerCase();\r\n const strParticipant = 'partyid_' + participantLogicalName + '@odata.bind';\r\n const participantActivityParty = {};\r\n participantActivityParty[strParticipant] = '/' + getPluralName(participantLogicalName) + '(' + participantParty.partyid.Id + ')';\r\n participantActivityParty['participationtypemask'] = participantParty.participationtypemask;\r\n activityParties[0] = participantActivityParty;\r\n activityParties[1] = {\r\n '[email protected]': '/systemusers(' + userParty.partyid.Id\r\n + ')', 'participationtypemask': userParty.participationtypemask\r\n };\r\n finalLogObject['phonecall_activity_parties'] = activityParties;\r\n reportTrace('logDebug', 'customAmcCif.saveLog message: Activity being created with data:- ' + params.logString);\r\n for (const key in finalLogObject) {\r\n if (finalLogObject[key].Id && finalLogObject[key].LogicalName) {\r\n finalLogObject[key + '_' + finalLogObject[key].LogicalName + '@odata.bind'] = '/' +\r\n getPluralName(finalLogObject[key].LogicalName) + '(' + finalLogObject[key].Id + ')';\r\n delete finalLogObject[key];\r\n }\r\n }\r\n Microsoft.CIFramework.createRecord('phonecall', JSON.stringify(finalLogObject))\r\n .then(function (requestId, party, ref) { callActivityCallback(requestId, party, JSON.parse(ref)); }\r\n .bind(null, requestCounterLocal.toString(), 'systemuser'), function (requestId, party, ref) { callActivityCallback(requestId, party, JSON.parse(ref)); }\r\n .bind(null, requestCounterLocal.toString(), 'systemuser'));\r\n }\r\n }\r\n catch (e) {\r\n reportTrace('logError', 'customAmcCif.saveLog: Exception .. message:' + e.message);\r\n saveLogCallback('error:' + e.message, params);\r\n }\r\n }\r\n}",
"function log(data){\n\t\tdata.checkRequired([\"log_id\"]);\n\t\tdata.setDefaultProperties({\n\t\t\ttype:\"\",\n\t\t\tlabel:\"\",\n\t\t\tdetail:\"\",\n\t\t\tapp_name:\"\",\n\t\t\tevent_ts:\"\",\n\t\t\thostname:\"\",\n\t\t\tinstance_id:\"\",\n\t\t\tlog_elapsed:\"\",\n\t\t\tpurpose:\"\",\n\t\t\trequest_elapsed:\"\",\n\t\t\trequest_id:\"\"\n\t\t})\n\t\t\n\t\tnew Myna.Query({\n\t\t\tds:\"myna_log\",\n\t\t\tsql:(/* jshint ignore:start */\n\t\t\t<ejs>\n\t\t\t\tinsert into myna_log_general(\n\t\t\t\t\tapp_name,\n\t\t\t\t\tdetail,\n\t\t\t\t\tevent_ts,\n\t\t\t\t\thostname,\n\t\t\t\t\tinstance_id,\n\t\t\t\t\tlabel,\n\t\t\t\t\tlog_elapsed,\n\t\t\t\t\tlog_id,\n\t\t\t\t\tpurpose,\n\t\t\t\t\trequest_elapsed,\n\t\t\t\t\trequest_id,\n\t\t\t\t\ttype\n\t\t\t\t) values (\n\t\t\t\t\t{app_name},\n\t\t\t\t\t{detail},\n\t\t\t\t\t{event_ts:timestamp},\n\t\t\t\t\t{hostname},\n\t\t\t\t\t{instance_id},\n\t\t\t\t\t{label},\n\t\t\t\t\t{log_elapsed:bigint},\n\t\t\t\t\t{log_id},\n\t\t\t\t\t{purpose},\n\t\t\t\t\t{request_elapsed:bigint},\n\t\t\t\t\t{request_id},\n\t\t\t\t\t{type}\n\t\t\t\t)\n\t\t\t</ejs>\n\t\t\t/* jshint ignore:end */),\n\t\t\tvalues:data\n\t\t})\n\t\t//new Myna.DataManager(\"myna_log\").getManager(\"myna_log_general\").create(data)\n\t\t\n\t}",
"function writeLogs( aSection, aRow ) {\n var myEmptyRow = getFirstEmptyRow();\n var myCount = 0\n var myString = getProperty( aSection )+\"\";\n myCount = getProperty( aSection + '_count' );\n var mySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName( 'Logs' );\n if ( myString != null ) {\n mySheet.getRange( aRow + \"\" + myEmptyRow ).setNote( myString );\n if (aSection == \"BuyCardAndRecycle\") {\n if (myString.indexOf(\"Rarity:4\") >= 0) {\n mySheet.getRange( aRow + \"\" + myEmptyRow ).setBackground('#b517dc');\n mySheet.getRange( aRow + \"\" + myEmptyRow ).setFontColor('white');\n } else if (myString.indexOf(\"Rarity:3\") >= 0) {\n mySheet.getRange( aRow + \"\" + myEmptyRow ).setBackground('#26f2ff');\n mySheet.getRange( aRow + \"\" + myEmptyRow ).setFontColor('white');\n } else if (myString.indexOf(\"Rarity:2\") >= 0) {\n mySheet.getRange( aRow + \"\" + myEmptyRow ).setBackground('#87d97a');\n mySheet.getRange( aRow + \"\" + myEmptyRow ).setFontColor('white');\n } else {\n mySheet.getRange( aRow + \"\" + myEmptyRow ).setBackground('#d9d9d9');\n //mySheet.getRange( aRow + \"\" + myEmptyRow ).setFontColor('white');\n }\n }\n }\n mySheet.getRange( aRow + \"\" + myEmptyRow ).setValue( myCount );\n setProperty( aSection, '' )\n setProperty( aSection + '_count', 0 );\n}",
"function log_donation_by_email(content, contact_sheet, main_page){\n\n var facility = content.substring(content.indexOf(\"Facility: \")+10, content.indexOf(\"Number Of\")-1)\n var number_boxes = content.substring(content.indexOf(\"Number Of Boxes: \")+17, content.indexOf(\"Contact\")-1)\n var contact = content.substring(content.indexOf(\"Contact: \")+8, content.indexOf(\"Supplies\")-1)\n \n var supplies = \"\"\n var upload_name = \"\"\n \n if(content.indexOf(\"Records Filename:\") > -1){\n var supplies_requested = (content.indexOf(\"Supplies:\")+9) != (content.indexOf(\"Records Filename:\")-2)\n if(supplies_requested) supplies = content.substring(content.indexOf(\"Supplies:\")+9, content.indexOf(\"Records Filename:\")).trim()\n upload_name = content.substring(content.indexOf(\"Records Filename:\")+17,content.indexOf(\"END\"))\n \n } else {\n var supplies_requested = (content.indexOf(\"Supplies:\")+9) != (content.indexOf(\"END\")-2)\n if(supplies_requested) supplies = content.substring(content.indexOf(\"Supplies:\")+9, content.indexOf(\"END\")).trim()\n } \n \n var indexes = get_main_indexes() \n var index_contact = indexes.indexContact\n \n var res = 1;\n var fake_number = \"Email-Log\"\n if(upload_name.length > 0) fake_number += \"\\nRecord Uploaded Filename: \" + upload_name\n\n if(number_boxes.trim() == '0'){\n Logger.log(\"adding supply request row\")\n res = add_donation_row(\"Email-Log-Supply\", fake_number,facility.trim(), contact_sheet, main_page, supplies) //the return value is 0 if there was a typo in the name\n var last_row = main_page.getLastRow()\n main_page.getRange(last_row, index_contact+1).setValue(contact) //override contact sheet \n }\n \n for(var i=0;i<parseInt(number_boxes,10);i++){ //has to do this for each box, as per the email specs\n res = add_donation_row(\"Email-Log\", fake_number,facility.trim(), contact_sheet, main_page, supplies) //the return value is 0 if there was a typo in the name\n var last_row = main_page.getLastRow()\n main_page.getRange(last_row, index_contact+1).setValue(contact) //override contact sheet\n \n if(res == 0) i = parseInt(number_boxes,10)\n } \n}",
"function log(){}",
"function requestAddDataToSheet(response, track) {\n return gapi.client.request({\n path: `https://sheets.googleapis.com/v4/spreadsheets/${response.spreadsheetId}/values/Logs!A1:D1:append?valueInputOption=USER_ENTERED`,\n method: 'POST',\n body: addDataSheetRequest(track)\n });\n}",
"function activityLogging(activity, callBack) {\n\ttry {\n\t\tnew sql.Request(db)\n\t\t\t.input('ActivityName', sql.VarChar(50), activity.activityname)\n\t\t\t.input('UserID', sql.NVarChar(100), activity.userId)\n\t\t\t.input('elevatorID', sql.NVarChar(50), activity.elevatorId)\n\t\t\t.input('alarmId', sql.NVarChar(100), activity.alarmId == ''? null: activity.alarmId)\n\t\t\t.execute('spInsertActivityLog', (error, result) => {\n\t\t\t\treturnResult(error, result, callBack);\n\t\t\t});\n\t}\n\tcatch (e) {\n\t}\n}",
"function doGet(e) {\n var params = JSON.stringify(e.parameters);\n var jsonMapping = JSON.parse(params);\n var sheet = SpreadsheetApp.openById(ID).getSheetByName(DATA_SHEET_NAME);\n // Just append call details to the spreadsheet\n sheet.appendRow([jsonMapping[\"CallSid\"][0], jsonMapping[\"From\"][0], jsonMapping[\"To\"][0], jsonMapping[\"StartTime\"][0], jsonMapping[\"CurrentTime\"][0], jsonMapping[\"DialWhomNumber\"][0], jsonMapping[\"digits\"][0]]);\n postKudos(e);\n return ContentService.createTextOutput(JSON.stringify(e.parameters));\n}",
"function LogIt(action, value, result){\n //resultCol.push(result);\n \n console.log(result);\n\n fs.appendFile(\"./log.txt\", \"\\n\" + action + \"\\n\"+ value + result + \"\\n-------------\", function(err){\n if(err){\n console.log(err);\n return;\n }\n //console.log(\"logged\");\n });\n}",
"function collectDataFromZipabox() {\n zipabox.showlog = true;\n \n /**************************\n * ### CALLBACK EVENTS ###\n **************************/\n \n // Callback event: Init properties before connect\n zipabox.events.OnBeforeConnect = _initLogin;\n \n // Callback event: Check if a sheet should be generated for the device\n zipabox.events.OnAfterLoadDevice = function(device) {\n writelog(\"OnAfterLoadDevice\");\n }\n \n // Callback event: Load all devices from Zipabox after connect\n zipabox.events.OnAfterConnect = function(){\n writelog(\"OnAfterConnect\");\n zipabox.LoadDevices();\t\n };\n \n // Callback event: Get logs for debug after disconnect\n zipabox.events.OnAfterDisconnect = function() {\n //var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"Logs\");\n //sheet.getRange(1, 1).setValue(Logger.getLog());\n };\n \n /****************************\n * ### FUNCTION MAIN PART ###\n ****************************/\n \n // Connecting to Zipabox \n zipabox.Connect();\n}",
"function postDataToSheet(e) {\n var rows = sheet.getDataRange().getValues();\n var headings = rows[0].map(String.toLowerCase);\n var row = [];\n for (i in headings)\n headings[i] == \"timestamp\" ? row.push(new Date()) : row.push(e.parameter[headings[i]]);\n\n sheet.appendRow(row);\n }",
"function sheetAuditor() {\n \n var ss = SpreadsheetApp.getActiveSpreadsheet();\n \n try {\n \n var audit_data = auditUrl(ss);\n Logger.log(audit_data);\n Browser.msgBox(\"Number of sheets: \" + audit_data[0] + \n \"\\\\nTotal cells used: \" + audit_data[1] + \n \"\\\\nPercent cells used: \" + Math.round(audit_data[2]*100) + \"%\");\n\n }\n catch(e) {\n Logger.log(e);\n }\n}",
"function logAndSendEmail(formdata) {\n try {\n\n var template = HtmlService.createTemplateFromFile('email');\n template.formdata = formdata;\n var html = template.evaluate().getContent();\n \n var racename = formdata.race.text;\n \n // figure out RD email for this race\n var racelevels = getRaces();\n var rdemail = racelevels.races[racename].email;\n \n var cclist = ['[email protected]',rdemail].join(',');\n \n // log time and formdata from request\n // collect time and formdata\n var dt = Date();\n var logdata = { time : dt }\n for (var i=0; i<formdata._keyorder.length; i++) {\n field = formdata._keyorder[i];\n value = formdata[field].text;\n logdata[field] = value;\n };\n \n // open first sheet\n var logfoldername = 'webapp-sponsor-database';\n var thisfolder = DriveApp.getFoldersByName(logfoldername).next();\n // first file is ok as this filename should be only once in this folder\n var logfile = thisfolder.getFilesByName('race sponsor log').next();\n var log = SpreadsheetApp.open(logfile);\n var sheet = log.getSheets()[0]; // always use first sheet -- is this ok?\n \n // write data to sheet\n writeJSONtoSheet(sheet, logdata)\n \n // send email about sponsorship\n GmailApp.sendEmail(formdata.email.text, \n 'Thanks for sponsoring '+racename+'!', html, \n {\n cc: cclist,\n htmlBody: html,\n name: racename,\n from: '[email protected]',\n replyTo: cclist,\n });\n return 'OK';\n }\n \n catch(err) {\n try {\n GmailApp.sendEmail(\n '[email protected]',\n '[race-sponsorship error] exception occurred on race sponsorship registration form',\n 'Error details: ' + err.message\n );\n }\n \n finally {\n return err.message;\n }\n };\n \n}",
"function DAILY_RECORD() {\n\n // Get daily recordings sheet.\n var dailyRecordingsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"Daily Recordings\");\n\n // Get the daily recordings sheet.\n var lastRow = dailyRecordingsSheet.getLastRow() + 1;\n\n // Get daily mailing sheet.\n var dailyEmailSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"Daily Email\");\n\n //Date,In Progress,Staging Tests,Sent For Signing,Not Started(Customer),Not Started(Internal),Unassigned(Customer),Unassigned(Internal),Team Members\n var dataCells = [\"G2\",\"L8\",\"L9\",\"L10\",\"L11\",\"L12\",\"L13\",\"L14\",\"H4\"];\n for(var counter = 0; counter < dataCells.length ; counter = counter + 1){\n dailyRecordingsSheet.getRange(lastRow, counter + 1).setValue(dailyEmailSheet.getRange(dataCells[counter]).getValue());\n }\n Logger.log(\"Daily recording successfully updated\");\n}",
"function logData(data, callback){\n allData = data;\n callbacks(allData);\n }",
"function saveLog_LogExt() {\r\n\tif(logVal_LogExt!=\"\") {\r\n\t\tchrome.extension.sendRequest({cmd: \"log\",url: log_server+\"/log.do?command=logData&\" +logVal_LogExt} , handleSendLog_LogExt);\r\n\t\t//xmlreqGET_LogExt(\"http://129.78.24.121:8080/chrome-log-ext/log.jsp?\" + logVal_LogExt, \"handleSendLog_LogExt\");\r\n\t\tlogVal_LogExt = \"\"; // reset log data\r\n\t}\r\n}",
"function log_unexpected_shipment_info(contact_sheet, tracking_number, from_facility, contact_indexes, main_page, date){\n console.log(\"unexpected!\")\n \n //check if it's a facility we even have, in which case update some info, otherwise make a note\n var note = \"NOT MATCHED TO A ROW & NOT IN DB\"\n var data = contact_sheet.getDataRange().getValues();\n var state = \"?\"\n var action = \"?\"\n var contact = \"?\"\n var message = \"Could not match \" + from_facility + \"with how any contact is written. I put their donation with tracking number \" + tracking_number + \" in a dummy row. Please sort this all out.\"\n var issue = \"\"\n var data_format = \"\"\n var update_command = \" FAX NUMBER NOT FOUND: \" + from_facility\n \n for(var i = 0; i < data.length; ++i){\n if(data[i][contact_indexes.indexFacility].toString().toLowerCase().indexOf(from_facility.trim().toLowerCase()) > -1){ //then we have the contact, just didn't have a fax. So it's a different situation\n state = data[i][contact_indexes.indexState].toString()\n action = data[i][contact_indexes.indexIssue].toString()\n contact = data[i][contact_indexes.indexContact].toString()\n data_format = data[i][contact_indexes.indexImportFormat].toString()\n note = \"UNEXPECTED SHIPMENT\"\n issue = \"UNEXPECTED SHIPMENT\"\n message = \"Got a shipped email from \" + from_facility + \"but I wasn't expecting it, so I had to create a new row. Check it out.\"\n update_command = \"\"\n }\n }\n \n var auto_res = \"\"\n var auto_no = \"\"\n \n if(data_format.length == 0){\n if(note.indexOf('NOT IN DB') == -1){\n issue += \" Contact doesn't have a specific V1 import format on Salesforce. Double check Donor is in 2-Contacts Sheet\";\n }\n } else {\n data_format += \" \" + date\n if(data_format.toLowerCase().indexOf(\"coleman\") == -1) {\n auto_res = \"Auto-Resolved because facility data format is \" + data_format\n auto_no = \"#NO\"\n }\n }\n \n main_page.appendRow([note, \"Bertha\", from_facility, state, action,contact,\"\",\"\",\"\",\"\",data_format,auto_no,issue,auto_res,tracking_number,Utilities.formatDate(new Date(), \"GMT-07:00\", \"MM/dd/yyyy HH:mm:ss\"), \"\", \"Shipped Email\",\"\",\"\",\"\",\"\",\"\",update_command,Math.floor(Math.random() * 500000)]) //creates a sort of dummy row for a shipped email taht didn't match any faxes\n //addTrackingToDB(tracking_number.trim(), from_facility.trim(), tracking_db_sheet) //TODO uncomment\n \n auto_group(from_facility)\n send_alert_email(5,\"\",\"\",message,\"\")\n}",
"function test_log_firebase() {\n\n var firebaseUrl = PropertiesService.getScriptProperties().getProperty('FIREBASE_URL')\n var firebaseSecret = PropertiesService.getScriptProperties().getProperty('FIREBASE_SECRET')\n var firebaseDb = FirebaseApp.getDatabaseByUrl(firebaseUrl, firebaseSecret); \n \n if (firebaseUrl === null || firebaseSecret === null) {\n throw new Error('Manually create the script properties: FIREBASE_URL & FIREBASE_SECRET')\n }\n\n var log = BBLog.getLog({\n level: BBLog.Level.INFO,\n sheetId: null, // Don't use GSheet for logging\n firebaseUrl: firebaseUrl,\n firebaseSecret: firebaseSecret,\n });\n \n log.clear()\n \n log.info('Just logged to Firebase, not sheet (sheetId null)'); \n fbAssert('Just logged to Firebase, not sheet (sheetId null)')\n\n var lock = LockService.getScriptLock()\n\n var log = BBLog.getLog({\n level: BBLog.Level.INFO,\n firebaseUrl: firebaseUrl,\n firebaseSecret: firebaseSecret,\n lock: lock, \n });\n \n log.info('Logged to Firebase & sheet');\n fbAssert('Logged to Firebase & sheet');\n sheetAssert_('Logged to Firebase & sheet');\n\n var log = BBLog.getLog({\n level: BBLog.Level.INFO, \n displayFunctionNames: BBLog.DisplayFunctionNames.YES, \n displayUserId: BBLog.DisplayUserId.EMAIL_FULL,\n firebaseUrl: firebaseUrl,\n firebaseSecret: firebaseSecret,\n lock: lock, \n });\n\n log.info('Logged to Firebase & sheet with email & function name');\n fbAssert('Logged to Firebase & sheet with email & function name');\n sheetAssert_(' (test_log_firebase) Logged to Firebase & sheet with email & function name');\n\n var log = BBLog.getLog({\n level: BBLog.Level.INFO,\n firebaseUrl: firebaseUrl,\n firebaseSecret: firebaseSecret,\n lock: lock, \n });\n\n log.info('!!!!!! ALL FIREBASE LOG TESTS PASSED !!!!!!');\n\n return\n\n function fbAssert(testString) { \n var callingfunction = 'test_log_firebase()';\n var data = firebaseDb.getData();\n var keys = Object.keys(data);\n var numberOfEntries = keys.length;\n var lastMessage = data[keys[numberOfEntries - 1]].message;\n Assert.assert(lastMessage.indexOf(testString) !== -1, callingfunction, 'TEST FAILED on \"' + testString + '\"');\n }\n \n} // test_log_firebase()"
]
| [
"0.72204787",
"0.68887705",
"0.68877",
"0.6812282",
"0.6735156",
"0.6717823",
"0.6593695",
"0.6367291",
"0.6214419",
"0.6134424",
"0.6076461",
"0.6064715",
"0.60631096",
"0.6005006",
"0.5929494",
"0.59234893",
"0.5921967",
"0.5914048",
"0.5904103",
"0.5901238",
"0.5886574",
"0.5882252",
"0.58501905",
"0.5843293",
"0.58225816",
"0.5805245",
"0.5762712",
"0.57624304",
"0.5754232",
"0.5749077"
]
| 0.7828464 | 0 |
function that populates cell B13 with the value 'yes' when run | function onClickYes() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// update information in cell B13 to yes
sheet.getRange("B13").setValue('yes');
// allow the use of the calendar
sheet.getRange("B14").setBackground(null);
sheet.getRange("B14").setValue("select date");
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function myFunction() {\n var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"Respuestas\");\n var value = sheet.getRange(sheet.getLastRow(), 14).getValue();\n if(value == 'Agua residual tratamiento/Wastewater treatment'){\n sheet.setActiveRange(sheet.getRange(sheet.getLastRow(), 21)).setValue('Yes');\n } else {\n sheet.setActiveRange(sheet.getRange(sheet.getLastRow(), 21)).setValue('No');\n }\n}",
"function onClickNo() {\n var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();\n \n // update information in cell B13 to no\n sheet.getRange(\"B13\").setValue('no');\n \n // dissallow the use of the calendar\n sheet.getRange(\"B14\").setBackground('Grey');\n sheet.getRange(\"B14\").setValue(\"call back not selected\");\n}",
"function checkYesNo(data_,rowUse_,attribute_){\n\tvar Tong=rowUse_.length;\n\tvar Yes=0;\n var hang;\n\tfor(var i=0;i<rowUse_.length;i++)\n\t{\n\t\thang=rowUse_[i];\n\t\tif(data_[hang][attribute_[attribute_.length-1]]==='Yes')\n\t\t{\n\t\t\tYes++;\n\t\t}\n\t}\n // alert('Tong yes: ',Yes);\n\t// tat ca la Yes\n\tif(Yes==Tong)\n\t{\n\t\treturn 1;\n\t}\n //Tat ca la no\n\tif(Yes==0)\n\t{\n\t\treturn 0;\n\t}\n\treturn -1;\n\n}",
"function pushYesno (value) {\n\t\tif (!value) { showNumbers(); }\n\t\telse { pushNumber(_this.agent.lastGuess); }\n\t}",
"function yes() {\n nextQuestion();\n}",
"function YesNo( really ){\n\treturn jyonif( really );\n}",
"function random_yes_no(yes = 3, no = 7) {\n arrYesNO = [];\n for (let i = 0; i < yes; i++) {\n arrYesNO.push('yes');\n }\n for (let j = 0; j < no; j++) {\n arrYesNO.push('no');\n }\n return random_item(arrYesNO);\n }",
"public setYesNo(yes : boolean) : void {\n if (ComponentWithYesNo.lastMonitored === this.elem.data('kbid'))\n ComponentWithYesNo.monitorOrigVal = this.elem.val(); // Lest the polling detects the change and removes the yes/no mark\n\n if (yes) {\n this.yesIcon.show();\n this.noIcon.hide();\n }\n else {\n this.yesIcon.hide();\n this.noIcon.show();\n }\n this.noneIcon.hide();\n }",
"function convertYesNo(value, data, done) {\n done( false, value !== 'y/N' && yesRegExp.test(value) );\n }",
"function checkHB() {\n for (var k = 0; k <= arrayAds.length; k++) {\n if (arrayAds[k].phb == 'yes') {\n //console.log('yes');\n return 'yes';\n } else {\n return 'no';\n }\n }\n}",
"function yes(){\n \telement[\"innerHTML\"] = \"Thanks for submitting your response, the poster will be dealt with accordingly.\";\n \talert(\"user pressed yes\");\n r1.score++;\n\n r1.timesChecked++;\n // need to increment score by 1\n // need to increment timesChecked\n // need to check if timesChecked = 5\n }",
"function answer1() {\n //the answer should be \"yes\" or \"no\"\n return \"no\"\n}",
"function ask (question, yes, no) {\n\n if (confirm(question)){\n yes();\n }\n else {\n no();\n }\n}",
"function ask(question, yes, no) {\n if (confirm(question)) yes()\n else no();\n }",
"function ask(question, yes, no) {\n if (confirm(question)) yes()\n else no();\n }",
"function ask1 (question1, yes1, no1) {\n if (confirm(question1)) {\n yes1();\n }\n else {\n no1();\n }\n}",
"function yesNo(input){\n if(input.toLowerCase() == \"yes\" || input.toLowerCase() == \"no\"){\n return true;\n }\n else{\n return false;\n }\n}",
"function confirmation(message,hiddenID){ \n var answer = confirm(message)\n \n if (answer){ \ndocument.getElementById(hiddenID).value = \"Yes\";\nreturn true;\n }\n else{\n document.getElementById(hiddenID).value = \"No\";\n return false; \n } \n}",
"function ask(question, yes, no){ \n confirm(question) ? yes() : no();\n}",
"function yesNo(input) {\n if (input.toLowerCase() == \"yes\" || input.toLowerCase() == \"no\") {\n return true;\n }\n else {\n return false;\n }\n}",
"function yesNo(input) {\n if (input.toLowerCase() == \"yes\" || input.toLowerCase() == \"no\") {\n return true;\n }\n else {\n return false;\n }\n}",
"function yesNo(input) {\n if (input.toLowerCase() == \"yes\" || input.toLowerCase() == \"no\") {\n return true;\n } \n else {\n return false;\n }\n}",
"function yesNo(input) {\n if (input.toLowerCase() == \"yes\" || input.toLowerCase() == \"no\") {\n return true;\n } else {\n return false;\n }\n}",
"function getBooleanValue(data) {\n if (data == 1 || data == 'yes') {\n return true;\n }\n return false;\n}",
"function updateCell(mine, cell) {\n var elem = document.getElementById(mine).getElementsByClassName(cell)[0];\n var result = configs[mine][cell] ? \"Y\" : \"N\";\n elem.innerHTML = result;\n elem.setAttribute(\"class\", result);\n}",
"function boolToWord( bool ){\n if ( bool === true) {\n return 'Yes'\n } else {\n return 'No'\n }\n\n}",
"function setFriendlyBoolean(data){\n let output = '';\n if(data === true){\n output = 'yes';\n } else if (data === false){\n output = 'no';\n }\n return output;\n }",
"function randomQuiz(ans, printYes, printNo) {\n if (ans==='love') {\n printYes();\n } else {\n printNo();\n }\n}",
"function boolToWord( bool ){\n if (bool === true) {\n return \"Yes\";\n };\n if (bool != true) {\n return \"No\"\n };\n}",
"function launchYesNoPrompt(title, question, onYesFn, onNoFn) {\n google.script.run.withSuccessHandler(function(obj) {\n if (obj && onYesFn) {\n onYesFn()\n } else if (!obj && onNoFn) {\n onNoFn()\n }\n }).launchYesNoPrompt(\"Delete metric\", \"Are you sure you want to delete this metric?\")\n }"
]
| [
"0.61702704",
"0.6025758",
"0.5920587",
"0.5845759",
"0.58204854",
"0.56389046",
"0.56085354",
"0.5607097",
"0.5601381",
"0.5581333",
"0.5527495",
"0.5473366",
"0.54724765",
"0.546809",
"0.546809",
"0.5445533",
"0.54019916",
"0.5391472",
"0.5373581",
"0.5357853",
"0.5357853",
"0.53576946",
"0.5338926",
"0.53374165",
"0.52677363",
"0.5261306",
"0.52430403",
"0.5236404",
"0.52192473",
"0.52171445"
]
| 0.65627474 | 0 |
function that populates cell B13 with the value 'no' when run | function onClickNo() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// update information in cell B13 to no
sheet.getRange("B13").setValue('no');
// dissallow the use of the calendar
sheet.getRange("B14").setBackground('Grey');
sheet.getRange("B14").setValue("call back not selected");
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function onClickYes() {\n var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();\n \n // update information in cell B13 to yes\n sheet.getRange(\"B13\").setValue('yes');\n \n // allow the use of the calendar\n sheet.getRange(\"B14\").setBackground(null);\n sheet.getRange(\"B14\").setValue(\"select date\");\n}",
"function pushYesno (value) {\n\t\tif (!value) { showNumbers(); }\n\t\telse { pushNumber(_this.agent.lastGuess); }\n\t}",
"function myFunction() {\n var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"Respuestas\");\n var value = sheet.getRange(sheet.getLastRow(), 14).getValue();\n if(value == 'Agua residual tratamiento/Wastewater treatment'){\n sheet.setActiveRange(sheet.getRange(sheet.getLastRow(), 21)).setValue('Yes');\n } else {\n sheet.setActiveRange(sheet.getRange(sheet.getLastRow(), 21)).setValue('No');\n }\n}",
"function updateCell(mine, cell) {\n var elem = document.getElementById(mine).getElementsByClassName(cell)[0];\n var result = configs[mine][cell] ? \"Y\" : \"N\";\n elem.innerHTML = result;\n elem.setAttribute(\"class\", result);\n}",
"siNo(data) {\n return data === 1 || data === true ? 'SI' : 'NO';\n }",
"function setCell(y, x, n) {\n if (n==0) Tref[y][x].innerHTML = \"\";\n else Tref[y][x].innerHTML = n.toString();\n}",
"function\nsetWorkOrderStatus(workorder, date, address, email, status, notes)\n{ \n var ss = SpreadsheetApp.openById(Global().s_wos_register);\n var sheet = ss.getSheetByName(Global().t_workorders);\n var data = sheet.getDataRange().getValues();\n \n for (var i = 0; i < data.length; ++i)\n {\n if (data[i][0] == workorder)\n {\n sheet.getRange(i+1,7).setValue(status);\n sheet.getRange(i+1,8).setValue(notes);\n return;\n }\n }\n \n sheet.getRange(sheet.getLastRow()+1,1,1,8).setValues([[workorder, date, \"\", address, email, \"\", status, notes]]); // ADD ROW IF WORKORDER DID NOT ALREADY EXIST.\n}",
"function checkYesNo(data_,rowUse_,attribute_){\n\tvar Tong=rowUse_.length;\n\tvar Yes=0;\n var hang;\n\tfor(var i=0;i<rowUse_.length;i++)\n\t{\n\t\thang=rowUse_[i];\n\t\tif(data_[hang][attribute_[attribute_.length-1]]==='Yes')\n\t\t{\n\t\t\tYes++;\n\t\t}\n\t}\n // alert('Tong yes: ',Yes);\n\t// tat ca la Yes\n\tif(Yes==Tong)\n\t{\n\t\treturn 1;\n\t}\n //Tat ca la no\n\tif(Yes==0)\n\t{\n\t\treturn 0;\n\t}\n\treturn -1;\n\n}",
"function abc(numb){\n if (document.getElementById(\"row2\").innerText === \"0\" ) {\n document.getElementById(\"row2\").innerText = numb;\n }else{\n document.getElementById(\"row2\").innerText += numb;\n }\n \n}",
"function numberUnfixed()\n{\n var fixedRangeValues = fixedRange.getValues();\n var dataRangeValues = dataRange.getValues();\n Logger.log('Data!' + dataRangeValues);\n var lastVal = fixedRange.getLastRow();\n var noCount = 0;\n \n for (i = 0; i <= lastVal; i++) {\n if (fixedRangeValues[i] == 'No' && dataRangeValues[i][0] > 0) { // only edit cells that are not fixed \n noCount++;\n }\n }\n return noCount;\n}",
"function updateCellValue() {\n var props = app.currentPage.properties;\n\n var cell_num = CURR_ROW;\n //0-f-name, 1-l-name, 2-email, 3-number, 4-camp, 5-contact-status, 6-notes\n var cells = [\"B\"+cell_num , \"C\"+cell_num, \"D\"+cell_num, \"E\"+cell_num, \"F\"+cell_num, \"G\"+cell_num, \"H\"+cell_num, \"I\"+cell_num];\n setCell(cells[0], props.CalleeFName);\n setCell(cells[1], props.CalleeLName);\n setCell(cells[2], props.CalleeEmail);\n setCell(cells[3], props.CalleeNumber);\n setCell(cells[4], props.Camp);\n setCell(cells[5], props.ContactOption);\n setCell(cells[6], props.CalleeNote);\n setCell(cells[7], (props.ContactDate).toISOString());\n}",
"function fillCell(cell, letter) {\n if (cell.innerHTML == \"\") {\n cell.innerHTML = letter\n }\n}",
"function YesNo( really ){\n\treturn jyonif( really );\n}",
"function setCellValue(sheet, row, col, value)\n {\n var single_cell = sheet.getRange(row, col, 1, 1);\n single_cell.setValue(value);\n }",
"function random_yes_no(yes = 3, no = 7) {\n arrYesNO = [];\n for (let i = 0; i < yes; i++) {\n arrYesNO.push('yes');\n }\n for (let j = 0; j < no; j++) {\n arrYesNO.push('no');\n }\n return random_item(arrYesNO);\n }",
"function updateCell(sheet,row,colTitle,value,overwrite) {\n if(value) {\n var col = headers.indexOf(colTitle) \n if(col > -1) {\n if(sheet.getRange(row,col+1).getValue() == \"\" || overwrite) {\n sheet.getRange(row,col+1).setValue(value)\n } else {\n SpreadsheetApp.getActiveSpreadsheet().toast('Existing values in ' + colTitle + ' were not overwritten')\n }\n } else {\n Logger.log(\"No column found for \" + colTitle) \n }\n }\n}",
"function updateNextRumble( aCheck,aTime ) {\n var mySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName( \"Settings\" );\n if ( aCheck == true ) {\n mySheet.getRange( \"C9\" ).setValue( 'Next Rumble Check ' + aTime );\n } else {\n mySheet.getRange( \"C9\" ).setValue( 'Disabled at ' + formattedTime() );\n }\n}",
"function printPossibles(cell) {\n\tif (filledNumbers[cell] > 0) {\n\t\t// Do nothing, since there is already a value in the cell.\n\t} else {\n\t\tdocument.getElementById(cell).innerHTML = trackPossibleValues[cell];\n\t\tdocument.getElementById(cell).style.fontSize = \"35%\";\n\t}\n}",
"function updateNext( aCheck ) {\n var mySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName( \"Settings\" );\n if ( aCheck == true ) {\n mySheet.getRange( \"C8\" ).setValue( 'Next check ' + myFormattedTimeNext() );\n } else {\n mySheet.getRange( \"C8\" ).setValue( 'Disabled at ' + formattedTime() );\n }\n}",
"function doesExercise() {\n if ((firstPatient.dailyExercise = \"no\")) {\n console.log(\"does not exercise\");\n }\n}",
"function updateCell(index, num) {\n var cellID = \"#cell\" + index;\n $(cellID).text(num);\n\n if (num == 0) {\n $(cellID).removeClass(\"UserFilledButton CellIncorrect CellSelected\");\n $(cellID).addClass(\"EmptyButton\");\n } else {\n $(cellID).removeClass(\"EmptyButton CellIncorrect CellSelected\");\n $(cellID).addClass(\"UserFilledButton\");\n }\n}",
"function new_add_to_coleman_sheet(data_row, coleman_to_do_sheet,row_index, main_sheet, existing_tracking_nums, indexes){\n\n\n var indexActualIssues = indexes.indexActualIssues\n var indexInSirum = indexes.indexInSirum\n var indexColemanTracking = indexes.indexColemanTracking\n var indexResolved = indexes.indexHumanIssues\n var indexColoradElig = indexes.indexCOFwd\n var indexState = indexes.indexState\n var indexFacility = indexes.indexFacilityName\n var colorado_tag = \"Log NDC: CO eligible donation\"\n \n var date_string = Utilities.formatDate(new Date(), \"GMT-07:00\", \"MM/dd/yyyy\")\n \n if((data_row[indexColemanTracking].toString().trim().length > 0) //there is a tracking number populated in column R\n && (((data_row[indexActualIssues].toString().trim().length > 0) && (data_row[indexResolved].toString().toLowerCase().indexOf(\"resolv\") > -1)) \n || (data_row[indexActualIssues].toString().trim().length == 0))\n && (data_row[indexColoradElig].toString().indexOf(\"FORWARD ME\") == -1) //either empty or already been forwarded\n \n ){\n \n //if eligible, add note: \"Log NDCS\" in one of the coleman columns\n \n var facility = data_row[indexFacility]\n var tracking_nums = data_row[indexColemanTracking].toString().trim()\n var coleman_note = \"\" //may become the tag if eligible\n \n if((data_row[indexColoradElig].toString().indexOf(\"eligible\") > -1) && (data_row[indexColoradElig].toString().indexOf(\"ineligible\") == -1)){\n coleman_note = colorado_tag\n }\n \n if(tracking_nums.length < 6){\n tracking_nums = (\"000000\"+tracking_nums).slice(-6);\n }\n \n var full_name = facility + \" \" + tracking_nums //assume you need to do this\n \n if(tracking_nums.indexOf(\"|\") > -1){ //if facility name here, extract number, but also still use the setup\n full_name = \"\" + tracking_nums\n var split_arr = tracking_nums.split(\"|\") //extract tracking nums still\n tracking_nums = split_arr[1].trim()\n }\n\n \n if(existing_tracking_nums.indexOf(tracking_nums) == -1){\n coleman_to_do_sheet.appendRow([\"\",\"\",\"\",\"\",coleman_note,full_name,facility,tracking_nums])\n main_sheet.getRange((row_index+1), (indexInSirum+1)).setValue(\"On coleman sheet \" + date_string)\n existing_tracking_nums.push(tracking_nums)\n } else {\n main_sheet.getRange((row_index+1), (indexInSirum+1)).setValue(\"ALREADY ON COLEMAN SHEET\")\n }\n }\n \n return existing_tracking_nums\n}",
"function changeStatus(option, row){\n const bookTitle = row.children[0].innerHTML; \n for (i = 0; i < myLibrary.length; i++) { \n if (myLibrary[i].title == bookTitle) { \n bookToChange = myLibrary[i];\n }\n }\n bookToChange.read = (option == true) ? true : false;\n console.log(bookToChange.read);\n}",
"function SetCellValue(sheet,row,column,value)\n{\n sheet.getRange(row, column).setValue(value);\n}",
"function theySaidNo() {\n alert(`Sorry to hear that, maybe next time...`);\n}",
"function ADL1BTrainShifts(opsProgressSheet, emailData, data) {\n var L1B_COL = \"AD\";\n\n for (var i = 0; i < data.length; i++) {\n if (data[i][1] == \"\") {\n break;\n }\n if (data[i][1] == \"L1 - Train AV \\(*Basic - 1st Round\\)\" || data[i][1] == \"L1 - Train AV \\(*Basic - 2nd Round\\)\") {\n if (data[i][4] != \"\" && getStudentRow(emailData, data[i][4]) != -1){\n var currentValue = opsProgressSheet.getRange(L1B_COL + getStudentRow(emailData, data[i][4])).getValue();\n if (currentValue == \"\") {\n opsProgressSheet.getRange(L1B_COL + getStudentRow(emailData, data[i][4])).setValue(1.0/2.0);\n }else{\n opsProgressSheet.getRange(L1B_COL + getStudentRow(emailData, data[i][4])).setValue(parseFloat(currentValue) + (parseFloat(1.0/2.0)));\n }\n }\n }else{\n Logger.log(\"Error \" + data[i][4]);\n }\n }\n}",
"function getsheetdata(empid){\r\n var ss= SpreadsheetApp.getActiveSpreadsheet();\r\n var dataSheet = ss.getSheetByName(\"Datasheet\");\r\n var getLastRow = dataSheet.getLastRow();\r\n var getLastColumn = dataSheet.getLastColumn();\r\n console.log(getLastColumn ,getLastRow);\r\n var f1 = dataSheet.createTextFinder(\"Emp Number\").findNext();\r\n if ( f1 !== null ){\r\n if (f1.getRow() == 1){\r\n if (dataSheet.createTextFinder(empid).findNext().getColumn() == f1.getColumn()){\r\n var fcol = f1.getColumn()\r\n var frow = dataSheet.createTextFinder(empid).findNext().getRow()\r\n }\r\n }\r\n }\r\n if(getLastRow > 1) {\r\n var data_array = dataSheet.getRange(2, 1, getLastRow - 1, getLastColumn-1).getValues(); \r\n }\r\n var farray = data_array ;\r\n for ( var i = 0 ; i <= (getLastRow -2) ; i = i +1){\r\n for ( var j = 0 ; j <= (getLastColumn -2) ; j = j +1){\r\n farray[i][j] = data_array[i][j] \r\n if (j == (getLastColumn -2) ){\r\n farray[i][j+1] = 'N '\r\n if ( i == (frow - 2)){\r\n farray[i][j+1] = 'Y'\r\n }\r\n }\r\n }\r\n }\r\n// console.log(data_array[frow - 2][fcol - 2]);\r\n console.log(data_array);\r\n return (data_array) ;\r\n}",
"function updateCellData(elCell, cell, i, j) {//fixed\n elCell.innerText = cell;\n elCell.style.background = 'lightgrey';\n gBoard[i][j].isShown = true;\n gState.shownCount++;\n}",
"importCell(x, y, val) {\n this.sheet.updateCell(x, y, val, null);\n let cell = this.sheet.getCell(x, y).cell;\n cell.innerText = val;\n cell.setAttribute('title', val);\n }",
"function handleClick(cell){\n //test to make sure cell is working correctly - displays div ID\n console.log(cell.target.id);\n \n //if the cell is empty replace with current piece variable, if not return statement. \n if(document.getElementById(cell.target.id).innerText === ''){\n document.getElementById(cell.target.id).innerText = piece;\n } else {\n return; \n } \n \n //if the turn is even X is the current piece. otherwise the piece is O.\n if( turn % 2 === 0){\n piece = 'X'\n } else {\n piece = 'O'\n }\n \n //winCondition();\n //call turn change turn++\n turnChange();\n}"
]
| [
"0.57166207",
"0.5679675",
"0.5603662",
"0.5462435",
"0.54386437",
"0.5420212",
"0.54011106",
"0.5342055",
"0.5327353",
"0.52852154",
"0.5267119",
"0.5162464",
"0.51609695",
"0.51129305",
"0.5100007",
"0.5098904",
"0.5054318",
"0.5043797",
"0.50423676",
"0.50339776",
"0.5011886",
"0.5007736",
"0.49684563",
"0.4964781",
"0.49586657",
"0.49389452",
"0.49359745",
"0.49062315",
"0.49051616",
"0.48935336"
]
| 0.6403364 | 0 |
Adds a reset to the master timeline. | _addReset() {
const tl = this.timeline;
tl.set(this._bgRect.node, { drawSVG: '0%', 'fill-opacity': 0 });
tl.set(this.$.label, { scaleX: 0, color: 'transparent', clipPath: '' });
tl.call(this.$.tweet._addReset, undefined, this.$.tweet);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"reset() {\n this.timeline.reset.apply(this.timeline, arguments);\n return this;\n }",
"reset () {\n this.timeline.reset.apply( this.timeline, arguments );\n return this;\n }",
"function reset() {}",
"function reset(){}",
"function reset() {\n setTime(30);\n setIsActive(false);\n }",
"function reset() {\n\n}",
"function reset() {\n\n}",
"function reset() {\n\n}",
"reset() {\n scoreboard.render({\n lines: {\n [index]: {\n animated: false,\n display: initialLine,\n nameIndex: initialNameIndex,\n score: scoreboard.state.lines[index].score\n }\n }\n });\n }",
"function resetBrew() {\n // Have all of the timers reset\n $scope.$broadcast('resetTimer');\n\n $(\"timer\").addClass(\"hidden\");\n\n // Reset any completed steps back to inactive\n $(\".brew-step--finished\").addClass(\"brew-step--inactive\");\n $(\".brew-step--finished\").removeClass(\"brew-step--finished\");\n\n // Reset the current step\n $(\".brew-step--current\").addClass(\"brew-step--inactive\");\n $(\".brew-step--current\").removeClass(\"brew-step--current\");\n\n // Make sure the reset step is not flagged as inactive\n $(\".brew-step--restart\").removeClass(\"brew-step--inactive\");\n $(\".countdown\").removeClass(\"hidden\");\n $(\".brew-step--countdown\").addClass(\"hidden\");\n\n // Hide the timeline\n $(`.time-${vm.countdownVal}`).removeClass(\"timeline\");\n\n // Show \"Restart Brew\" and \"Add Note\", hide \"Reset\"\n $(\".brew-step--restart\").removeClass(\"hidden\");\n $(\"a[href].add-brew-note\").removeClass(\"hidden\");\n $(\"a[href].reset-brew\").addClass(\"hidden\");\n vm.showStars = true;\n }",
"function resetTimelineStatus() {\n for (let year = 1990; year < 2021; year++) {\n timelineStatus[year] = 0;\n }\n}",
"function reset() {\n setTimeout(function() {\n game.stage.removeChild(game.objects.line);\n vm.mistakeCount++;\n }, 1000);\n }",
"reset() {\n this.last = -1;\n this.time = 0;\n this.update(0);\n }",
"enterResetMaster(ctx) {\n\t}",
"function reset() {\n setShortBreak();\n }",
"function Reset () {}",
"function Reset () {}",
"function reset() {\n userScoreArea.innerText = \"Number Entered By You : \" + 0;\n compScoreArea.innerText = \"Number guessed By Computer: \" + 0;\n sumArea.innerText =\n \"Total sum = Previous Sum + \" + 0 + \" + \" + 0 + \" = \" + 0;\n button.setAttribute(\"style\", \"display:block\");\n window.location.reload();\n }",
"function reset() {\n toggleBlink(false);\n time.hour = 0;\n time.minute = 0;\n time.second = 0;\n display();\n save();\n }",
"function reset(){\n stop();\n start();\n}",
"_reset() {\n this._emit({\n type: 'reset',\n parent: this\n });\n }",
"function reset (){\n computerScore = 0;\n playerScore = 0;\n document.querySelector(\"#reset\").style = \"visibility:hidden\";\n document.querySelector(\"#status\").innerHTML = \"Select one;\";\n updateScore();\n}",
"function reset() {\n score = 0\n timeLeft = 75\n}",
"function reset() {\n title.style.display = null; // Reset to CSS\n resetButton.style.display = \"none\";\n \n currentRanges = null;\n currentKey = null;\n display(initialColors.map(x => x.color));\n}",
"enterResetStatement(ctx) {\n\t}",
"function reset() {\n time.stopTimer(tiempo);\n moves = 0;\n deck = shuffle(deck);\n printDeck(deck);\n printMove(moves);\n open = [];\n printStars(3);\n $('.time-played').text(\"00:00:00\");\n\n}",
"function resetQuiz() {\n $(\"#timer\").text(\"00:00\");\n scoreRegistry = 0;\n $(\"#scoreRegistry\").text(\"Score: \" + scoreRegistry);\n $(\"#answerField\").empty();\n startBtnClicked = false;\n $(\"#startQuizBtn\").html(\"🟢 Start Quiz\");\n $(\"#startQuizBtn\").on(\"click\", buttonCycle);\n $(\"#resetBtn\").remove();\n numOfQuestCalled = 1;\n}",
"function reset() {\n stopBonus();\n localStorage.setItem('score', '0');\n localStorage.setItem('auto', '0');\n localStorage.setItem('multiplier', '0');\n refreshDisplay();\n}",
"function resetCA() {\n setAutomaton(); //check type\n clearTables();\n printfDiff();\n score.splice(1, count); //we must clear the x-axis in the linear-chart\n drawCrosshairs();\n count = 1;\n clearInterval(epochs);\n}",
"function reset() {\n player.reset();\n resetBugs();\n game.timesAcross = 0;\n game.score = 0;\n updateDisplay();\n}"
]
| [
"0.66486454",
"0.6633295",
"0.6024589",
"0.60026294",
"0.5880154",
"0.5847417",
"0.5847417",
"0.5847417",
"0.5801165",
"0.57822704",
"0.57219064",
"0.5699668",
"0.56572104",
"0.56514484",
"0.5631687",
"0.5610092",
"0.5610092",
"0.5605673",
"0.5584712",
"0.5561084",
"0.556005",
"0.5517768",
"0.548592",
"0.547078",
"0.5460753",
"0.54581183",
"0.54422605",
"0.5434638",
"0.5431913",
"0.5426288"
]
| 0.6861819 | 0 |
Creates an exit animation timeline. | _createExitAnim() {
const tl = new TimelineLite();
tl.add('exit');
tl.to(this._bgRect.node, 0.5, {
'fill-opacity': 0,
ease: Sine.easeOut
}, 'exit');
tl.to(this._bgRect.node, 1.5, {
drawSVG: '0%',
ease: Power2.easeIn
}, 'exit');
tl.fromTo(this.$.label, 0.334, {
clipPath: 'inset(0 0% 0 0)'
}, {
clipPath: 'inset(0 100% 0 0)',
ease: Sine.easeInOut
}, 'exit+=0.9');
tl.add(this.$.tweet._createExitAnim(), 'exit');
tl.add(this.$.image.exit(), 'exit+=0.1');
return tl;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function animateOut() {\n return timeline([\n {\n track: 'modal',\n to: {opacity: 0, scale: 0.9, y: '3rem'},\n from: {opacity: 1, scale: 1, y: '0rem'},\n duration: 200,\n ease: easing.easeOut,\n },\n '-100',\n {\n track: 'scrim',\n from: {opacity: 1},\n to: {opacity: 0},\n duration: 200,\n },\n ]);\n}",
"function createExit() {\n if (exitButton !== undefined) {\n exitButton.parentNode.remove(exitButton);\n }\n\n exitButton = document.createElement('a-entity');\n exitButton.setAttribute('geometry', 'primitive: plane; height: 1; width: 1');\n exitButton.setAttribute('material', 'shader: flat; src: #exit');\n exitButton.setAttribute('position', '-3.59 2 0'); // -3.59 because of z-fighting\n exitButton.setAttribute('rotation', '0 90 0');\n exitButton.setAttribute('click', 'scaleOnHover: true; function: exit');\n\n return exitButton;\n}",
"_onLeaveAnimation() {\n this._timelineLeave = new TimelineLite({\n onStart: () => {\n window.scrollTo(0, document.body.scrollHeight)\n this.props.beforeLeave()\n },\n z: 0.1,\n rotationZ: 0.01,\n force3D: true,\n })\n\n const top = (28.5 * window.innerHeight) / 100\n\n this._timelineLeave.set(document.body, { overflow: 'hidden' })\n this._timelineLeave.to(\n this._letters,\n 0.4,\n {\n paddingLeft: '2px',\n paddingRight: '2px',\n ease: Power2.easeOut,\n },\n 0\n )\n this._timelineLeave.staggerTo(\n this._letters,\n 0.2,\n {\n y: '-100%',\n ease: Power2.easeIn,\n },\n 0.05,\n 0.4\n )\n this._timelineLeave.to(\n this.$footer.current,\n 1.2,\n {\n height: '100vh',\n y: '-30vh',\n autoRound: false,\n ease: Power2.easeInOut,\n },\n 0.5\n )\n this._timelineLeave.set(this.$footer.current, {\n position: 'fixed',\n bottom: 0,\n y: 0,\n })\n this._timelineLeave.add(() => this.props.setTripContentStyle())\n this._timelineLeave.set(window, { scrollTo: { y: 0, x: 0 } })\n this._timelineLeave.to(\n this.$footer.current,\n 0.6,\n {\n height: `${(window.innerWidth * 9) / 16}px`,\n y: `${top - 140}px`,\n autoRound: false,\n bottom: 'initial',\n top: 0,\n ease: Power2.easeInOut,\n },\n 1.8\n )\n }",
"add_exit(exit){\n if(this.exits === undefined){\n this.exits = [];\n }\n // properties all exits would have:\n exit.display_body.set_strokeStyle('green');\n exit.display_body.set_lineWidth(3);\n exit.set_pass_through();\n\n this.exits.push(exit);\n }",
"function mouseexit (event)\n{\n\tif (flipShown)\n\t{\n\t\t// fade in the flip widget\n\t\tif (animation.timer != null)\n\t\t{\n\t\t\tclearInterval (animation.timer);\n\t\t\tanimation.timer = null;\n\t\t}\n\t\t\n\t\tvar starttime = (new Date).getTime() - 13;\n\t\t\n\t\tanimation.duration = 500;\n\t\tanimation.starttime = starttime;\n\t\tanimation.firstElement = document.getElementById ('flip');\n\t\tanimation.timer = setInterval (\"animate();\", 13);\n\t\tanimation.from = animation.now;\n\t\tanimation.to = 0.0;\n\t\tanimate();\n\t\tflipShown = false;\n\t}\n}",
"animate_out() {\n let self = this;\n // Pop the front of the list to fade out the most recent run.\n let run_to_pop = self.container.querySelectorAll(\".schedule-element\")[0];\n\n if(run_to_pop) {\n // Fade out the existing nodes\n run_to_pop.classList.add(\"fade\");\n self.container.classList.add(\"tickerSlideLeft\");\n setTimeout(function() {\n run_to_pop.remove();\n self.container.classList.remove(\"tickerSlideLeft\");\n }, 1200);\n }\n }",
"function endAnimation(status){\n\t\n\tlet $stage = $(\"#stage\"),\n\t$ending = $(\"#end_title\"),\n\tmsg = `You DIED`,\n\ttl = new TimelineLite();\n\ttl.to($stage,3,{opacity:0});\n\ttl.to($stage,0,{display:\"none\"});\n\tif(status==\"2\"){\n\t\tmsg=\"You escaped\"\n\t}\n\tdocument.querySelector(\"#end_title\").style.display = \"block\";\n\tdocument.querySelector(\"#end_title\").innerHTML = msg;\n\ttl.to($ending,3,{opacity:1});\n\t\n}",
"exit(effect = 'fade', duration = 500, delay = 0, remove = false) {\n return exit(this, effect, duration, delay, remove);\n }",
"deathAnimation() {\n\t\treturn;\n\t}",
"exit() {\n if (!this._destroyed) {\n this._animationState = 'hidden';\n this._changeDetectorRef.markForCheck();\n }\n }",
"function animateOut() {\n \"use strict\";\n\n var logContext = \"intro.js > animateOut()\";\n\n $.activity_indicator.hide();\n\n var oAnimation = Ti.UI.createAnimation({\n transform : Ti.UI.create2DMatrix({\n scale : 0.7\n }),\n opacity : 0,\n duration : 1000\n });\n oAnimation.addEventListener(\"complete\", function() {\n Log.trace(\"raising $.ended event...\", logContext);\n $.trigger(\"ended\");\n });\n $.my_shout_circle.animate(oAnimation);\n}",
"animateTimelines() {\n\n //master timeline\n new TimelineMax()\n .add(this.loadAnimations());\n // .add(this.landAnimations())\n }",
"finishAnimations() {\n for (const animation of this.animations) {\n animation.finish();\n }\n return this;\n }",
"exit() {\n if (this.destroyed) {\n return;\n }\n this.animationState = McSidepanelAnimationState.Hidden;\n this.changeDetectorRef.markForCheck();\n }",
"function animationEnd() {\n animatingDetail = 0\n }",
"function leaveTrail(center) {\n\n\t\tasteroidExplosions[astNames] = MyGame.components.system({\n\t\t\tcenter: {x: center.x, y: center.y},\n\t\t\tsize: {width: .0069, height: .015},\n\t\t\tspeed: {mean: .07, stdev: .03},\n\t\t\tlifetime: {mean: 1, stdev: .35},\n\t\t\ttoCreate: 1,\n\t\t\timg1: MyGame.assets['ice'],\n\t\t\timg2: MyGame.assets['ice'],\n\t\t\ttype: 'circular'\n\t\t});\n\t\tasteroidRenderers[astNames] = MyGame.renderer.particleSystemRenderer(asteroidExplosions[astNames++], MyGame.graphics);\n\t}",
"function nodeOnExit(nodeExit,node,source){\n\t\t\treturn node.exit().transition()\n\t\t\t\t.duration(duration)\n\t\t\t\t.attr(\"transform\", function(d) {\n\t\t\t\t\treturn \"translate(\" + source.y + \",\" + source.x + \")\";\n\t\t\t\t})\n\t\t\t\t.remove();\n\t\t}",
"endGame() {\n\n this.levelsAmbience.stop();\n this.zombiesAmbience.stop();\n\n this.endingMusic.play();\n\n this.engdingAnim = new AnimatedEntity(this.sceneDown, (1125 / 2) * this.sceneDown.zoom, (1125 / 2) * this.sceneDown.zoom, this.sceneDown.zoom, 'endingSpriteSheet');\n createAnimationsFireEnding(this.sceneDown);\n this.engdingAnim.anims.play('garageEnding', true);\n\n this.sceneUp.write(\"¡Hurraaaa, se abre la puerta del garaje!\");\n\n this.time.delayedCall(3000, function () {\n\n this.sceneUp.write(\"Espero que nos podamos salvar del apocalipsis...\");\n\n this.sceneDown.cameras.main.fadeOut(6000);\n this.sceneUp.cameras.main.fadeOut(6000);\n\n let codeArea = document.getElementById('codeArea');\n codeArea.style.opacity = '0';\n codeArea.style.setProperty(\"-webkit-transition\", \"opacity 6000ms linear\");\n codeArea.style.setProperty(\"transition\", \"opacity 6000ms linear\");\n setTimeout(function () {\n codeArea.parentNode.removeChild(codeArea);\n }, 6000);\n\n this.time.delayedCall(6000, function () {\n this.scene.stop('SceneUp');\n this.scene.stop('SceneDown');\n this.cm.style.display = 'none';\n\n this.scene.launch(\"EndScene\");\n }, [], this);\n\n }, [], this);\n\n }",
"end() {\n this.toggleAnimation().resetAngle().execute().updateHistory();\n }",
"function exit(event) {\n var site = event.target;\n site.style.transition = \"transform 1s ease, box-shadow 1s ease\";\n site.style.transform = \"rotateX(0deg) rotateY(0deg)\";\n }",
"_startExitAnimation() {\n this._state = 'exit';\n // Mark the container for check so it can react if the\n // view container is using OnPush change detection.\n this._changeDetectorRef.markForCheck();\n }",
"function stop() {\n renderer.setAnimationLoop(null);\n}",
"exitRoom () {\n var myDoor = this.currentRoom.doors[this.door];\n this.previousRoom = this.roomsJSON[this.currentRoom.name];\n \n this.enableInput(false);\n\n // use exit animation if present\n if (myDoor.animation.exit) {\n\n this.exitRoomAnimation();\n\n } else if (myDoor.offPoint) {\n \n this.tweenOut();\n \n }\n }",
"destroy() {\n for (const layerId of this.groups) {\n const current = this.current[layerId];\n if (current && !current.isFinished) {\n current.kill();\n }\n }\n this.animations = {};\n this.animGroupMap = {};\n this.animFinalValueMap = {};\n this.animUnstoppableMap = {};\n this.current = {};\n this.currentAnimName = {};\n delete this.object.animator;\n }",
"onExit(){\n this.remove();\n console.log(this.namespace + \" Exit\")\n // this.music.pause();\n // this.remove();\n // this.style.display=\"none\";\n // this.world.removeEventListener(\"gameover\", this.onGameOver, false);\n // console.warn(this.namespace + \" Ended\");\n // this.onReset();\n // this.music.pause();\n }",
"exitLinageFootingAt(ctx) {\n\t}",
"function stopIntroduction() {\n \n //Fade out and destroy containers\n d3.select(\"#intro\")\n .transition()\n .duration(mediumTransition)\n .on(\"end\", function() {\n d3.select(\"div#intro\").remove();\n createPageLayout();\n draw();\n prepareAnimation();\n })\n .style(\"opacity\", 0);\n}",
"function animateRemoval() {\n animationRunner = $animateCss(element, {addClass: 'md-leave'});\n return animationRunner.start();\n }",
"function exit() {\n\t\trunner.exit();\n\t}",
"function Exit(sheet, posX, posY, bboffsetX, bboffsetY, width, height,target, parent)\n{\n//console.log(\"[Exit] pos:\"+posX+\",\"+posY+\" offset:\"+bboffsetX+\",\"+bboffsetY);\n this.boundingBox = new Rectangle(posX+bboffsetX,posY+bboffsetY,width, height);\n this.bboffsetX = bboffsetX;\n this.bboffsetY = bboffsetY;\n this.centreX = posX + width * 0.5;\n this.target = target;\n this.parent = parent;\n this.sheet = sheet;\n this.triggered = false;\n this.active = true;\n this.dirty = true;\n\n this.position = function()\n {\n return {x:this.boundingBox.x, y:this.boundingBox.y};\n }\n\n this.setPosition = function(posX, posY)\n {\n this.boundingBox.x = posX;\n this.boundingBox.y = posY;\n }\n this.isColliding = function()\n {\n return this.boundingBox.intersects(this.target.boundingBox);\n }\n this.isBoxIntersecting = function(box)\n {\n return this.boundingBox.intersects(box);\n }\n this.hitResponse = function()\n {\n if(!this.target.contact) return;\n this.sheet.goToColumn(1);//Start at beginning of anim\n this.dirty=true;\n this.triggered = true;\n }\n\n this.render = function()\n {\n if(!this.active) return;\n if(!this.dirty) return;\n //Only render if in view\n\n this.sheet.update();\n this.sheet.render();\n\n this.dirty=false;\n }\n this.destroy = function()\n {\n this.sheet.destroy();\n this.boundingBox = null;\n this.target = null;\n this.parent = null;\n this.sheet = null;\n }\n}"
]
| [
"0.6962266",
"0.62466145",
"0.59754485",
"0.5598517",
"0.5597063",
"0.55704826",
"0.55560315",
"0.5485349",
"0.54176",
"0.53704435",
"0.53160816",
"0.52903587",
"0.52854323",
"0.5249321",
"0.52222747",
"0.5191636",
"0.51915854",
"0.518022",
"0.51678205",
"0.51488996",
"0.51477695",
"0.5093374",
"0.5088528",
"0.5080871",
"0.5054209",
"0.5023484",
"0.50085175",
"0.49789318",
"0.49756277",
"0.49678427"
]
| 0.7942597 | 0 |
clear the radius,volume and canvas | function onClear() {
document.getElementById("radius").value = "";
document.querySelector(".volume").innerHTML = "Calculates the Volume...";
ctx.beginPath();
ctx.clearRect(0, 0, 300, 300);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"clear() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); }",
"function clearCanvas() {\n\t}",
"clearCircle(center, radius) {\n this.ctx.save();\n this.ctx.globalCompositeOperation = 'destination-out';\n this.ctx.beginPath();\n this.ctx.arc(center.x, center.y, radius, 0, 2 * Math.PI, false);\n this.ctx.fill();\n this.ctx.restore();\n }",
"clearCanvas() {\n this.ctx.clearRect(0, 0, this.width, this.height);\n }",
"clear() {\n this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);\n }",
"clearCanvas() {\n this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);\n }",
"function clearCanvas() {\n let canvas = document.getElementById(\"circle-canvas\");\n let context = canvas.getContext('2d');\n context.clearRect(0, 0, canvas.width, canvas.height);\n}",
"clearCanvas() {\n this.canvas.width = this.canvas.width;\n // this.canvas.height = this.canvas.height;\n this.drawStyle();\n }",
"function clearCanvas() {\n erasing = false;\n filling = false;\n changeBtnColor(\"white\", \"white\", \"white\");\n ctx.clearRect(0, 0, 800, 650);\n defaultConditions();\n saveFillColor = \"white\"\n saveStrokeColor = \"black\";\n range.value = \"5\"\n\n // Clear paint history\n paintHistory = [];\n index = -1;\n}",
"clear(){\n this.ctx.clearRect(0, 0, this.width, this.height);\n }",
"function clear_canvas() {\n\n ctx = undefined;\n perimeter = new Array();\n perimeters = new Array();\n perimeter_per_object = new Array();\n object_cats = new Array();\n object_ctxs = new Array();\n object_colors = new Array();\n object_colors_transparent = new Array();\n\n perimeter_per_object.push(0);\n\n fill_class_list();\n\n $('#object_btn_list').empty();\n\n start();\n}",
"clearCanvas() {\n this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);\n }",
"clearCanvas () {\n this.ctx.clearRect(0, 0, this.state.canvasWidth, this.state.canvasHeight)\n }",
"function Clear(){\n canvas.clear();\n}",
"function clearRain() {\n // Stops the rain in current canvas dimensions \n context2d.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas\n\n clearInterval(rainInterval); // Stop the rain function\n }",
"function clearCanvas() {\n\tperform({kind: 'clear'});\n}",
"clear(){\n this.opacity = 0;\n this.color = `rgb(0,0,0)`;\n pixCtx.clearRect(0,0,pixCanvas.width,pixCanvas.height);\n }",
"clear_canvas() {\n var ctx = this.canva.getContext(\"2d\");\n\n ctx.clearRect(0, 0, this.canva.width, this.canva.height);\n }",
"function clearCanvas() {\r\n\r\n ctx.clearRect(-canvasWidth/2, -canvasHeight/2, canvas.width, canvas.height);\r\n\r\n }",
"function clearCanvas() {\r\n \r\n //self.sendNotification(\"SHOW_ALERT\", {title: \"Board\", message: \"CLEAR\", timer: 1200});\r\n sdb.color = std_color;\r\n sdb.weight = std_weight;\r\n color_input.value = std_color;\r\n weight_input.value = std_weight;\r\n \r\n sdb.clear(); \r\n \r\n }",
"clear() {\n this.getContext().clearRect(0,0,this.canvas.width,this.canvas.height);\n }",
"clearRect() {\n this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);\n }",
"function reset()\n\t{\n\t\ttry \n\t\t{\n\t\t\tparameters.radius = startVals.radius;\n\t\t\tparameters.widthSegments = startVals.widthSegments;\n\t\t\tparameters.heightSegments = startVals.heightSegments;\n\t\t\tparameters.phiStart = startVals.phiStart;\n\t\t\tparameters.phiLength = startVals.phiLength;\n\t\t\tparameters.thetaStart = startVals.thetaStart;\n\t\t\tparameters.thetaLength = startVals.thetaLength;\n\n\t\t\tupdate();\n\t\t\tupdateDisplay( item_3d_gui.gui );\n\t\t}\n\t\tcatch( err ) \n\t\t{\n\t\t\tvar message = \"Error, please click reset button. Err message: \" + err.message;\n \t\talert( message );\n\t\t}\t\n\t}",
"function clearCanvas(){\r\n ctx.clearRect(0,0,920,600);\r\n }",
"function clearCanvas() {\n\t// Clear canvas\n\tctx.fillStyle = '#f0f8ff';\n\tctx.fillRect(0,0,canvasSize.width,canvasSize.height);\n }",
"function clear() {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n }",
"function clear() {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n }",
"function clearCanvas() {\r\n // Remove all the shapes.\r\n shapes = [];\r\n\r\n currentShape = -1;\r\n \r\n // Update the display.\r\n drawShapes();\r\n}",
"function reset()\n\t{\n\t\ttry \n\t\t{\n\t\t\tparameters.radius \t\t\t= startVals.radius;\n\t\t\tparameters.widthSegments \t= startVals.widthSegments;\n\t\t\tparameters.heightSegments \t= startVals.heightSegments;\n\t\t\tparameters.phiStart \t\t= startVals.phiStart;\n\t\t\tparameters.phiLength \t\t= startVals.phiLength;\n\t\t\tparameters.thetaStart \t\t= startVals.thetaStart;\n\t\t\tparameters.thetaLength \t\t= startVals.thetaLength;\n\n\t\t\tupdate();\n\t\t\tupdateDisplay( item_3d_gui.gui );\n\t\t}\n\t\tcatch( err ) \n\t\t{\n\t\t\tvar message = \"Error, please click reset button. Err message: \" + err.message;\n \t\talert( message );\n\t\t}\t\n\t}",
"function clearCanvas(){\n clear();\n socket.emit('clear canvas');\n}"
]
| [
"0.7122396",
"0.71146774",
"0.7110031",
"0.7080268",
"0.7079772",
"0.7057169",
"0.70450073",
"0.7028832",
"0.7014813",
"0.7013211",
"0.7011248",
"0.6997983",
"0.69823134",
"0.6964222",
"0.69482076",
"0.6881215",
"0.68727416",
"0.6865544",
"0.6849",
"0.68155205",
"0.6813576",
"0.68101907",
"0.6791669",
"0.67895526",
"0.6781983",
"0.6772987",
"0.6772987",
"0.67678344",
"0.6760691",
"0.6752746"
]
| 0.80103886 | 0 |
Get the information of a specific show | static async getShowInfo(showNumber){
const showResponse = await fetch(`http://api.tvmaze.com/shows/${showNumber}`);
const showData = await showResponse.json();
return showData;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"async getShowDetails ( { commit, state }, id )\n\t{\n\t\tcommit( 'SET_SHOW_ID', id )\t\t\t\t\n\t\tconst res = await tvShowsServices.getRequestDetails(\n\t\t\t'/shows/' + state.showId )\t\t\n\t\tif ( res.data )\n\t\t{\t\t\t\n\t\t\tcommit( 'SET_IS_VALID_ID', true )\n\t\t\tcommit( 'SET_SHOW_DETAILS', res.data );\n\t\t}\n\t\telse\t\t\t\t\t\n\t\t\tcommit( 'SET_IS_VALID_ID', false )\t\t\n\t}",
"function fetchShowDetails(id) {\n const castURL = `http://api.tvmaze.com/shows/${id}?embed=cast`\n return fetch(castURL).then(r => r.json())\n}",
"async function getTitleInfo(showId) {\n option = {\n tconst: showId\n }\n const getOverView = \"https://imdb8.p.rapidapi.com/title/get-overview-details\";\n const queryStr = formatQuery(option);\n const searchForInfo = getOverView + \"?\" + queryStr;\n const options = {\n headers: new Headers({\n \"x-rapidapi-key\": apiKey\n })\n };\n const showInfo = await fetch(searchForInfo, options)\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseData => {\n displayInfo(responseData);\n console.log(responseData);\n })\n .catch(err => {\n $('#error').text(`Try Again: ${err.message}`);\n });\n}",
"show (id) {}",
"function show(){\n\treturn this.data;\n}",
"function show(req, res) {\n Spot.findById(req.params.spot_id, function(err, spot) {\n if (err) res.send(err);\n\n // return that spot\n res.json(spot);\n });\n}",
"async show ({ params, request, response, view }) {\n }",
"async show ({ params, request, response, view }) {\n }",
"async show ({ params, request, response, view }) {\n }",
"async show ({ params, request, response, view }) {\n }",
"async show ({ params, request, response, view }) {\n }",
"async show ({ params, request, response, view }) {\n }",
"function show() {\n return this.data;\n}",
"async show({ params, request, response, view }) {}",
"async show({ params, request, response, view }) {}",
"function getShow(s) {\n var showData;\n\n for (var k in d['originals']) {\n\n if (String(d['originals'][k].id) === String(s)) {\n showData = d['originals'][k];\n }\n\n }\n\n //Sends back a null value if no match is found\n return showData;\n }",
"function show(id) {\n\n return resource.fetch(id)\n .then(function(data){ return data.data; });\n }",
"function showDetails(req, res) {\n // if(req.params > 0){\n // console.log('OUR REQUEST PARAMS: ', req.params[0]);\n\n // let sql = 'SELECT * FROM series WHERE id=$1;';\n // let safeValues = [req.params];\n // client.query(sql, safeValues)\n // .then(sqlResults => {\n // console.log('SQL RESULTS :', sqlResults.rows);\n // res.status(200).render('pages/detail.ejs', { show: sqlResults.rows[0] })\n // }).catch(error => console.log(error));\n // } else {\n console.log(req.query);\n const title = req.query.title;\n const tmdbId = req.query.id;\n const image_url = req.query.image_url;\n trakt.search.id({\n id: tmdbId,\n id_type: 'tmdb',\n extended: 'full',\n type: 'show'\n }).then(response => {\n let url = 'https://utelly-tv-shows-and-movies-availability-v1.p.rapidapi.com/idlookup';\n let queryParams = {\n 'country': 'US',\n 'source_id': tmdbId,\n 'source': 'tmdb'\n };\n superagent.get(url, queryParams)\n .set({ 'x-rapidapi-host': 'utelly-tv-shows-and-movies-availability-v1.p.rapidapi.com' })\n .set({ 'x-rapidapi-key': process.env.RAPID_API_KEY })\n .set({ 'useQueryString': true })\n .then(results => {\n let platforms = results.body.collection.locations\n .map(location => {\n console.log(location.display_name);\n return location.display_name.replace('IVAUS', '');\n });\n console.log(results.body);\n console.log(response.data)\n let showData = new Show(response.data[0].show, image_url, tmdbId, platforms);\n console.log('constructed show', showData);\n res.status(200).render('pages/detail.ejs', { show: showData })\n }).catch(err => {\n let platforms = [];\n if (response) {\n let showData = new Show(response.data[0].show, image_url, tmdbId, platforms);\n console.log('constructed show', showData);\n res.status(200).render('pages/detail.ejs', { show: showData })\n }\n console.log(err)\n }).catch(err => {\n console.log(err);\n let platforms = [];\n let showData = new Show({ title: title }, image_url, tmdbId, platforms);\n res.status(200).render('pages/detail.ejs', { show: showData })\n })\n }).catch(err => console.log(err))\n}",
"function fetchShow(property, value, parseFetch){\n \tparseFetch.greaterThanOrEqualTo(property, value).find({\n \t\tsuccess: function(obj){\n \t\t\tconsole.log(obj);\n \t\t\tobj.forEach(function(item){\n \t\t\t\t// The structure of the object is...\n \t\t\t\t// console.log(item.attributes.title);\n\n \t\t\t\t//I can also call the Parse function .get(attr)\n \t\t\t\tconsole.log(item.get('title'));\n \t\t\t});\n \t\t},\n \t\terror: function(err){\n \t\t\tconsole.log(err);\n \t\t}\n \t});\n\t}",
"function getData() {\r\n const nameShow = inputSearch.value;\r\n const apiUrl = \"https://api.tvmaze.com/search/shows?q=\";\r\n fetch(`${apiUrl} + ${nameShow}`)\r\n .then(function (response) {\r\n return response.json();\r\n })\r\n .then(function (data) {\r\n shows = data;\r\n paintShows();\r\n paintFavorites();\r\n listenShows();\r\n });\r\n}",
"function show(id) {\n\n \treturn $http.get(beerBase + \"/\" + id)\n .then(function(data){ console.log('URL-GET: ' + data.config.url); return data.data; });\n }",
"function searchShow(showQuery){\n fetch(`https://api.tvmaze.com/search/shows?q=${showQuery}`)\n .then(response => {\n if (response.ok){\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseJson => displayShows(responseJson))\n .catch(err => alert(`Something went wrong: ${err.message}`));\n}",
"function showDataExtraction(rawShowData) {\n let { id, name, summary, image } = rawShowData.show;\n\n //check for null\n id = checkForNullInfo(id);\n image = checkForNullImage(image);\n name = checkForNullInfo(name);\n summary = checkForNullInfo(summary);\n\n console.log(\"show IDs\", id)\n return { id, name, summary, image };\n}",
"function getShow(show, shows) {\n // if there's still shows left, then get each date\n var dates = show.dates;\n var date = dates.shift();\n getShowForDate(show, shows, date, dates);\n}",
"function details() {\n\n var storeID = request.httpParameterMap.StoreID.value;\n var store = dw.catalog.StoreMgr.getStore(storeID);\n\n var pageMeta = require('*/cartridge/scripts/meta');\n pageMeta.update(store);\n\n app.getView({Store: store})\n .render('storelocator/storedetails');\n\n}",
"function handleShow(req,res)\n{\n let diskid = req.params.diskid;\n\n let q = \"SELECT D.title,A.name as artist,D.length,D.genre,D.year \" +\n\t \"FROM disk D, artist A \" +\n\t \"WHERE D.id = $1 AND A.id = D.artistid\";\n database.query(q,[diskid],function (e1,d1) { handleShow1(req,res,e1,d1); } );\n}",
"function getShowLoc(showLocId) {\n const showLoc = showLocation[showLocId]\n const loc = location[showLoc.location[0]]\n return pick(loc, 'id', 'name')\n }",
"function func_ShowDetailsTvSeason(tvshowID) {\n//---- TODO - NOT USED at moment, maybe later show TV Season Details...-----\n}",
"function displayShows(shows) {\n for (show of shows) {\n const name = show.name;\n const images = show.image;\n let thumbnail = images === null ? null : images.medium;\n createThumbnail(name, thumbnail);\n console.log(`${name} for ${thumbnail}`);\n }\n }",
"function showDetail(id) {\n return fetch(\"https://www.omdbapi.com/?apikey=2efeaa26&i=\" + id)\n .then((response) => response.json())\n .then((movie) => movie);\n}"
]
| [
"0.7307014",
"0.68623537",
"0.66413784",
"0.6525289",
"0.6523838",
"0.64646757",
"0.64368844",
"0.64368844",
"0.64368844",
"0.64368844",
"0.64368844",
"0.64368844",
"0.6422969",
"0.640647",
"0.640647",
"0.6397187",
"0.63463986",
"0.63048315",
"0.6285951",
"0.62838846",
"0.62626123",
"0.6251185",
"0.6214124",
"0.6204239",
"0.61592287",
"0.6127106",
"0.61103743",
"0.61099416",
"0.6104747",
"0.6068992"
]
| 0.7142503 | 1 |
Call to update the tank by checking movement, collision and firing | update(){
// Rotate the tank if it currently has a rotation speed
this.rotate();
if(this.moving){
this.move();
// Check collision
let collision = checkCollisions(this);
if(collision.colliding){
// Revert move
this.move(-1);
// Alert the user of a collision by vibrating their phone
vibrateUser(this.id);
}
}
// Fire a projectile if allowed to
if(this.firing){
if(this.firingCooldown == 0)
this.fire();
else
this.firingCooldown -= 1;
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function update() {\r\n\t// if(input.isDown())\r\n\t// update the frame count\r\n\tframes++;\r\n\t\r\n\t// update tank position depending on pressed keys\r\n\tif (input.isDown(37)) { // Left\r\n\t\ttank.x -= 4;\r\n\t}\r\n\tif (input.isDown(39)) { // Right\r\n\t\ttank.x += 4;\r\n\t}\r\n\tif(input1.isDown(65)) { //Left //A Key\r\n\t\ttank1.x -= 4;\r\n\t}\r\n\tif(input1.isDown(68)) { //Right //D Key\r\n\t\ttank1.x += 4;\r\n\t}\r\n\t// keep the tank sprite inside of the canvas\r\n\ttank.x = Math.max(Math.min(tank.x, display.width - (30 + taSprite.w)), 30);\r\n\ttank1.x = Math.max(Math.min(tank1.x, display.width - (30 + taSprite.w)), 30);\r\n\t// append new bullet to the bullet array if spacebar is\r\n\t// pressed\r\n\r\n\t//in case u need it - space key is 32\r\n\t\r\n\tif (input.isPressed(87)) { // W key\r\n\t\tbullets.push(new Bullet(tank1.x + 10, tank1.y, -8, 2, 6, \"#fff000\"));\r\n\t}\r\n\tif(input.isPressed(38)){ // up key\r\n\t\tbullets.push(new Bullet(tank.x + 10, tank.y, -8, 2, 6, \"#fff000\"))\r\n\t}\r\n\r\n\t// update all bullets position and checks\r\n\tfor (var i = 0, len = bullets.length; i < len; i++) {\r\n\t\tvar b = bullets[i];\r\n\t\tb.update();\r\n\t\t// remove bullets outside of the canvas\r\n\t\tif (b.y + b.height < 0 || b.y > display.height) {\r\n\t\t\tbullets.splice(i, 1);\r\n\t\t\ti--;\r\n\t\t\tlen--;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t// check if bullet hits any city\r\n\t\tvar h2 = b.height * 0.5; // half hight is used for\r\n\t\t\t\t\t\t\t\t // simplicity\r\n\t\tif (cities.y < b.y+h2 && b.y+h2 < cities.y + cities.h) {\r\n\t\t\tif (cities.hits(b.x, b.y+h2)) {\r\n\t\t\t\tbullets.splice(i, 1);\r\n\t\t\t\ti--;\r\n\t\t\t\tlen--;\r\n\t\t\t\ttheyHit++;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t}\r\n\t\t// check if bullet hit any aliens\r\n\t\tfor (var j = 0, len2 = aliens.length; j < len2; j++) {\r\n\t\t\tvar a = aliens[j];\r\n\t\t\tif (AABBIntersect(b.x, b.y, b.width, b.height, a.x, a.y, a.w, a.h)) {\r\n\t\t\t\taliens.splice(j, 1);\r\n\t\t\t\tj--;\r\n\t\t\t\tlen2--;\r\n\t\t\t\tbullets.splice(i, 1);\r\n\t\t\t\ti--;\r\n\t\t\t\tlen--;\r\n\t\t\t\tweHit++;\r\n\t\t\t\tenemyCount--;\r\n\t\t\t\t//console.log(enemyCount);\r\n\t\t\t\t// increase the movement frequence of the aliens\r\n\t\t\t\t// when there are less of them\r\n\t\t\t\tswitch (len2) {\r\n\t\t\t\t\tcase 30: {\r\n\t\t\t\t\t\tthis.lvFrame = 40;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcase 10: {\r\n\t\t\t\t\t\tthis.lvFrame = 20;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcase 5: {\r\n\t\t\t\t\t\tthis.lvFrame = 15;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcase 1: {\r\n\t\t\t\t\t\tthis.lvFrame = 6;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t// makes the alien shoot in an random fashion \r\n\tif (Math.random() < 0.03 && aliens.length > 0) {\r\n\t\t\r\n\t\t// mySound1 = new sound(\"Laser Blasts\");\r\n\t\t// mySound1.play();\r\n\r\n\t\tvar a = aliens[Math.round(Math.random() * (aliens.length - 1))];\r\n\t\t// iterate through aliens and check collision to make\r\n\t\t// sure only shoot from front line\r\n\t\tfor (var i = 0, len = aliens.length; i < len; i++) {\r\n\t\t\tvar b = aliens[i];\r\n\r\n\t\t\tif (AABBIntersect(a.x, a.y, a.w, 100, b.x, b.y, b.w, b.h)) {\r\n\t\t\t\ta = b;\r\n\t\t\t}\r\n\t\t}\r\n\t\t// create and append new bullet\r\n\t\tbullets.push(new Bullet(a.x + a.w*0.5, a.y + a.h, 4, 2, 4, \"#f00e08\"));\r\n\t}\r\n\t// update the aliens at the current movement frequence\r\n\tif (frames % lvFrame === 0) {\r\n\t\tspFrame = (spFrame + 1) % 2;\r\n\r\n\t\tvar _max = 0, _min = display.width;\r\n\t\t// iterate through aliens and update postition\r\n\t\tfor (var i = 0, len = aliens.length; i < len; i++) {\r\n\t\t\tvar a = aliens[i];\r\n\t\t\ta.x += 30 * dir;\r\n\t\t\t// find min/max values of all aliens for direction\r\n\t\t\t// change test\r\n\t\t\t_max = Math.max(_max, a.x + a.w);\r\n\t\t\t_min = Math.min(_min, a.x);\r\n\t\t}\r\n\t\t// check if aliens should move down and change direction\r\n\t\tif (_max > display.width - 30 || _min < 30) {\r\n\t\t\t// mirror direction and update position\r\n\t\t\tdir *= -1;\r\n\t\t\tfor (var i = 0, len = aliens.length; i < len; i++) {\r\n\t\t\t\taliens[i].x += 30 * dir;\r\n\t\t\t\taliens[i].y += 30;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t//console.log(theyHit);\r\n\tif(frames>4000 && enemyCount!=0){\r\n\t\tdisplay.clear();\r\n\t\tdisplay.ctx.fillStyle = \"yello\";\r\n\t\tdisplay.ctx.font = \"20px Arial\";\r\n\t\tdisplay.ctx.fillText(\"We lost the war. The invaders are successful \", 30, 250);\r\n\t\tdisplay.ctx.fillText(\"in stealing our natural resources..\",30,270);\r\n\t\tdisplay.ctx.fillText(\"specially the solar energy by using the Dyson Sphere.\",30,290);\r\n\t}\r\n\telse if(enemyCount==0){\r\n\t\t//frames--;\r\n\t\tdisplay.clear();\r\n\t\tdisplay.ctx.fillStyle = \"yello\";\r\n\t\tdisplay.ctx.font = \"20px Arial\";\r\n\t\tdisplay.ctx.fillText(\"We have won!! But not entirely. This isn't the end..\", 30, 250);\r\n\t\t//mySleep(4000);\r\n\t\t// display.clear();\r\n\t\tdisplay.ctx.fillStyle = \"yellow\";\r\n\t\tdisplay.ctx.font = \"20px Arial\";\r\n\t\tdisplay.ctx.fillText(\"We are having two choices..\", 30, 270);\r\n\r\n\t\tdisplay.ctx.fillStyle = \"red\";\r\n\t\tdisplay.ctx.font = \"20px Arial\";\r\n\t\tdisplay.ctx.fillText(\"Either we let them go..Or use their advaance tech\", 30, 290);\r\n\t\tdisplay.ctx.fillText(\"to invade their planet for natural resources.\",30,310);\r\n\t\tdisplay.ctx.fillStyle = \"yellow\";\r\n\t\tdisplay.ctx.fillText(\"What's say !?\",30,330);\r\n\r\n\t\tdisplay.ctx.fillStyle = \"green\";\r\n\t\tdisplay.ctx.fillText(\"(Press Y to invade them..N to let them go)\",30,390);\r\n\r\n\t\tdisplay.ctx.fillStyle = \"red\";\r\n\t\tdisplay.ctx.font = \"20px Arial\";\r\n\r\n\t\tif (enemyCount==0){\r\n\r\n\t\t} else {\r\n\t\t\tscoree = (weHit-theyHit)-(frames/1000);\r\n\t\t}\r\n\t\t\r\n\t\tscoree = Math.round(scoree*100)/100;\r\n\t\tdisplay.ctx.fillText(\"Score: \" + scoree, 5, 29);\r\n\t\t//sleep(100);\r\n\t\tvar invade;\r\n\t\t// if(inputController.isDown(78)){\r\n\t\t// \tdisplay.clear();\r\n\t\t// \tdisplay.ctx.fillText(\"You made a right choice. This is a cause not just for humanity but bigger. Others have a right to live peacefully too.\",30,250);\r\n\t\t// } else if (inputController.isDown(89)){\r\n\t\t// \tdisplay.clear();\r\n\t\t// \tdisplay.ctx.fillText(\"You made a poor choice..This is against our principles..This is beyond only our cause.\",30,250);\r\n\t\t// } else {\r\n\r\n\t\t// }\r\n\r\n\r\n\t\t// if(invade==true){\r\n\t\t// \tdisplay.clear();\r\n\t\t// \tdisplay.ctx.fillStyle = \"red\";\r\n\t\t// \tdisplay.ctx.fillText(\"You made a poor choice..This is against our principles..This is beyond only our cause.\",30,250);\r\n\t\t// } else if(invade==false) {\r\n\t\t// \tdisplay.clear();\r\n\t\t// \tdisplay.ctx.fillStyle = \"red\";\r\n\t\t// \tdisplay.ctx.fillText(\"You made a right choice. This is a cause not just for humanity but bigger. Others have a right to live peacefully too.\",30,250);\r\n\t\t// }\r\n\t\tresultOfEndgame();\r\n\t}\r\n}",
"tick() {\n\t\tthis.playerObj.tick();\n\t\tthis.dynamics.forEach(s => {\n\t\t\ts.tick();\n\t\t});\n\t\t\n\t\t//camera movement\n\t\tthis.tick_camera();\n\t\n\t\t//orbs\n\t\tthis.statics.forEach(o => {\n\t\t\to.tick();\n\t\t});\n\n\t\t//exit\n\t\tthis.tick_exit();\n\t}",
"update() {\n\t\tthis.handleInput();\n\t\tthis.gravity();\n\t\tthis.collide();\n\t}",
"updateAttack() {\n if (this.keys.z.polled && this.silentDuration >= Config.fireDelay) {\n this.silentDuration = 0;\n this.fireLaser();\n }\n if (this.keys.x.polled && this.numBombs > 0) {\n gm.bombScreen();\n this.numBombs--;\n this.keys.x.polled = false;\n }\n }",
"function update() {\n // if Game is running/ didn't end\n if (gameState === 0) {\n $(\"#text\").text(\"Control the Object with left/ right/ up/ down on keyboard. You have \" + fuel + \" fuel.\");\n // Check Winning/ Loosing Conditions before moving\n checkGameState();\n if (left) {x_speed--; }\n if (right) {x_speed++; }\n \n // Implementing fuel and loosing fuel\n if (up) {\n y_speed--;\n fuel--;\n // What happens, when there is no fuel left\n if (fuel <= 0.5) {\n fuel = 0;\n gravity = 1.0;\n up = false;\n }\n }\n \n // implementing Gravity\n if (!up) {\n y_speed++;\n y_speed *= gravity;\n }\n \n // Clearing Canvas, removing anything rendered before\n context.clearRect(0, 0, canvas.width, canvas.height);\n lander = new Lander();\n platform = new Platform();\n \n // Movement and Accleration\n playerX += x_speed;\n playerY += y_speed;\n x_speed *= acc;\n y_speed *= acc;\n }\n}",
"update (time, delta) {\n\n // =======================\n // PLAYER ACTIONS\n // =======================\n\n // when left arrow is down, player moves left\n if (this.cursors.left.isDown) {\n this.player.body.setVelocityX(-100);\n this.player.anims.play(\"run\", true);\n this.player.flipX = true;\n // when right arrow is down, player moves right\n } else if (this.cursors.right.isDown) {\n this.player.body.setVelocityX(100);\n this.player.anims.play(\"run\", true);\n this.player.flipX = false;\n // when idle, player does not move\n } else {\n this.player.body.setVelocityX(0);\n this.player.anims.play(\"idle\", true);\n };\n // player jumps\n if ((this.cursors.up.isDown || this.cursors.space.isDown) && this.player.body.onFloor()) {\n let jumpSound = this.sound.add(\"jump\");\n jumpSound.play();\n this.player.setVelocityY(-170);\n };\n\n // =======================\n // BAT ACTIONS\n // =======================\n\n // select the group of bats\n let enemies = this.bats.getChildren();\n\n // loop through the bats\n for (let i = 0; i < enemies.length; i++) {\n // starts initial movement\n if (enemies[i].hasStartedMoving === false) {\n // change to true so that this will never be accessed again\n enemies[i].hasStartedMoving = true;\n // set initial velocity\n enemies[i].setVelocityX(100);\n // set initial animation\n enemies[i].anims.play(\"fly-right\", true);\n };\n // if the bat is moving right and is blocked\n if (enemies[i].body.blocked.right === true) {\n if (enemies[i].setDirection === \"right\") {\n // change setDirection\n enemies[i].setDirection = \"left\";\n // change animation\n enemies[i].anims.play(\"fly-left\", true);\n // change setVelocityX\n enemies[i].setVelocityX(-100);\n };\n // if the bat is moving left and is blocked\n } else if (enemies[i].body.blocked.left == true) {\n if (enemies[i].setDirection === \"left\") {\n // change setDirection\n enemies[i].setDirection = \"right\";\n // change animation\n enemies[i].anims.play(\"fly-right\", true);\n // change setVelocityX\n enemies[i].setVelocityX(100);\n };\n };\n };\n\n // =======================\n // LEVEL COMPLETE\n // =======================\n\n if (this.levelComplete === true) {\n // redirect to new game\n this.time.delayedCall(500, function () {\n this.levelComplete = false;\n this.scene.start(\"Level02\", this.score);\n }, [], this);\n }\n\n // =======================\n // GAME OVER\n // =======================\n\n if (this.gameOver === true) {\n // camera shakes\n this.cameras.main.shake(400);\n // redirect to new game\n this.time.delayedCall(400, function () {\n this.score = 0;\n this.gameOver = false;\n this.scene.start(\"MenuScene\");\n }, [], this);\n };\n\n }",
"update(t){\n this.checkKeys();\n\n //this.myPyramid.update();\n\n //this.myFish.update(t);\n\n\n //Moving Fish movement\n this.movingFish.update(t);\n\n this.animatedFishes.forEach( fish=>{\n fish.update(t);\n });\n this.nestRocks.forEach( rock=>{\n if(rock.hasMovement)\n rock.update();\n });\n\n this.waterSurface.waterShader.setUniformsValues({ timeFactor: t / 500 % 100});\n }",
"updateTanks(){\n\t\tthis.tanks.map((tank)=>tank.update(this.deltaTime));\n\t}",
"function moveAlienTank()\n\t{\n\t\talienTank.position.x = 0;\n\t\talienTank.position.z = 5;\n\t\t\n\t\tif(alienTank.position.y > 100)\n\t\t{\n\t\t\tshipCycleUpward = false;\n\t\t}\n\t\telse if(alienTank.position.y < -100)\n\t\t{\n\t\t\tshipCycleUpward = true;\n\t\t}\n\t\tif(shipCycleUpward == true)\n\t\t{\n\t\t\talienTank.position.y += 0.5;\n\t\t}\n\t\telse if(shipCycleUpward == false)\n\t\t{\n\t\t\talienTank.position.y -= 0.5;\n\t\t}\n\t}",
"update(deltaT, gameInfo) {\n if(this.movementTimer <= 0) {\n // Movement is only allowed when previous movement has finished\n this.movementX = 0;\n this.movementY = 0;\n\n // Check if the tile in the requested direction is passable, then set various animation and movement variables.\n if(gameInfo.input.keyPressed(\"ArrowLeft\")) {\n if(gameInfo.getTile(this.x - 1, this.y)[\"passable\"]) {\n this.movementX = -1;\n this.x--;\n this.movementTimer = this.movementDuration;\n this.faceDirection = 3;\n this.animationTimer = 0;\n }\n } else if (gameInfo.input.keyPressed(\"ArrowRight\")) {\n if(gameInfo.getTile(this.x + 1, this.y)[\"passable\"]) {\n this.movementX = 1;\n this.x++;\n this.movementTimer = this.movementDuration;\n this.faceDirection = 1;\n this.animationTimer = 0;\n }\n } else if (gameInfo.input.keyPressed(\"ArrowUp\")) {\n if(gameInfo.getTile(this.x, this.y - 1)[\"passable\"]) {\n this.movementY = -1;\n this.y--;\n this.movementTimer = this.movementDuration;\n this.faceDirection = 0;\n this.animationTimer = 0;\n }\n } else if (gameInfo.input.keyPressed(\"ArrowDown\")) {\n if(gameInfo.getTile(this.x, this.y + 1)[\"passable\"]) {\n this.movementY = 1;\n this.y++;\n this.movementTimer = this.movementDuration;\n this.faceDirection = 2;\n this.animationTimer = 0;\n }\n }\n }\n this.movementTimer -= deltaT;\n\n // If we are standing in a tile marked with water properties, cut off the lower part of the character to make it\n // look like they are wading in the water.\n if(gameInfo.getTile(this.x, this.y)[\"water\"]) {\n this.playerHeightToDraw = 24;\n } else {\n this.playerHeightToDraw = 32;\n }\n }",
"subClassUpdate() {\n if (Math.abs(this.startX - this.x) > 1800 || this.kills.length > 1) {\n this.isDead = true;\n this.game.blink.waveattackInstance = null;\n }\n if (this.isHeadingRight) {\n this.x += this.game.clockTick * this.speed;\n } else {\n this.x -= this.game.clockTick * this.speed;\n }\n\n this.boundX = this.x + 19;\n this.boundY = this.y + 20;\n if (!this.isHeadingRight) {\n this.boundX = this.x + 25;\n }\n this.updateMyHitBoxes();\n }",
"update(dt) {\n if (this.y < -5) {\n this.x = 202;\n this.y = 425;\n this.pass += 1;\n if (this.pass > 2 && this.level < 6) {\n this.level += 1;\n this.pass = 0;\n enemyLevelUp();\n //nest if for gemLevelup, create function for gems, like enemyLevelUp\n }\n }\n if (this.y >= 405) {\n this.y = 405;\n }\n if (this.x > 405) {\n this.x = 405;\n }\n if (this.x <= 0) {\n this.x = 0;\n }\n if (this.lives <= 0 || this.level > 4) {\n winModal();\n }\n }",
"function update(){\n // boundCheckX('x', comet.getPos().x + comet.velX, comet.getPos().z, camera)\n sceneMovement(asteroids);\n // orbiter.update();\n}",
"onUpdate(/*t*/) {\n let sprite = this.sprite,\n map = sprite.currentMap,\n nextX = sprite.x + sprite.vx,\n nextY = sprite.y + sprite.vy,\n hitBox = sprite.getHitBox(),\n hitTest = null;\n\n // reached ground ? revert vy\n hitTest = map.hitObjectTest(nextX + hitBox.x, nextY + hitBox.y2, nextX + hitBox.x2, nextY + hitBox.y2, Tile.TYPE.WALL);\n if (hitTest) {\n if (this.onGround) {\n this.onGround();\n }\n this.resetY();\n if (Math.abs(sprite.vy) <= sprite.gravity) {\n sprite.movable = false;\n if (this.onEnd) {\n this.onEnd();\n }\n }\n } else {\n sprite.vy += sprite.gravity;\n\n sprite.y += sprite.vy;\n }\n }",
"tick() {\n Body.setAngle(this.body, math.lerpAngle(this.angle, this.targetrot, this.stat.rotspeed))\n Body.setPosition(this.body, math.lerpVector(this.position, this.targetpos, config.smooth.tower.pos))\n if (this.isPlayer) {\n this.doControl()\n }\n }",
"function PlayerTank(width, height, image, x, y, type) {\n this.type = type;\n this.lives = 3;\n this.image = new Image();\n this.image.src = image;\n this.width = width;\n this.height = height;\n this.x = x;\n this.y = y;\n this.speedX = 0;\n this.speedY = 0;\n this.direction = \"up\";\n this.update = function () {\n ctx = myGameArea.context;\n ctx.drawImage(this.image, this.x, this.y, this.width, this.height);\n };\n this.newPos = function () {\n this.speedX = 0;\n this.speedY = 0;\n\n if (myGameArea.keys && myGameArea.keys[37]) { this.speedX = -1; this.image.src = \"images/tank_player1_left_c0_t1.png\"; this.direction = \"left\" };\n if (myGameArea.keys && myGameArea.keys[39]) { this.speedX = 1; this.image.src = \"images/tank_player1_right_c0_t1.png\"; this.direction = \"right\" };\n if (myGameArea.keys && myGameArea.keys[38]) { this.speedY = -1; this.image.src = \"images/tank_player1_up_c0_t1.png\"; this.direction = \"up\" };\n if (myGameArea.keys && myGameArea.keys[40]) { this.speedY = 1; this.image.src = \"images/tank_player1_down_c0_t1.png\"; this.direction = \"down\" };\n if (myGameArea.keys && myGameArea.keys[32]) { if (!this.fired) { this.shoot() }; };\n\n this.x += this.speedX;\n this.y += this.speedY;\n };\n this.borderCheck = function (object, i) {\n var borderBottom = myGameArea.bottomBorder - this.height;\n var borderTop = myGameArea.topBorder;\n var borderLeft = myGameArea.leftBorder;\n var borderRight = myGameArea.rightBorder - this.width;\n\n if (this.y > borderBottom) {\n this.y = borderBottom;\n } else if (this.y < borderTop) {\n this.y = borderTop;\n } else if (this.x < borderLeft) {\n this.x = borderLeft;\n } else if (this.x > borderRight) {\n this.x = borderRight;\n }\n\n for (var i = 0; i < object.length; i++) {\n if (typeof object[i] != \"undefined\") {\n if ((this.y < object[i].y + object[i].height) &&\n (this.y + this.height > object[i].y) &&\n (this.x + this.width > object[i].x) &&\n (this.x < object[i].x + object[i].width)) {\n this.speedX = 0;\n this.speedY = 0;\n \n if (this.direction == \"up\") {\n this.y += 1;\n } else if (this.direction == \"right\") {\n this.x -= 1 \n } else if (this.direction == \"down\") {\n this.y -= 1;\n } else if (this.direction == \"left\") {\n this.x += 1;\n }\n return \"collided\";\n }\n }\n }\n }\n this.shoot = function () {\n bullet.push(new Bullet(this));\n this.fired = true;\n }\n}",
"move() {\n if(this.active) {\n this.updateTarget();\n if(this.remainingAttackTimer > 0) this.remainingAttackTimer -= 1;\n this.checkFire();\n }\n }",
"function update() {\n // update the frame count\n frames++;\n // update ship position depending on pressed keys\n if (input.isDown(37)||input.isDown(65)) { // Left\n ship.x -= 4;\n }\n if (input.isDown(39)||input.isDown(68)) { // Right\n ship.x += 4;\n }\n // keep the tank sprite inside of the canvas\n ship.x = Math.max(Math.min(ship.x, display.width - (30 + shipSprite.w)), 30);\n // append new bullet to the bullet array if spacebar is\n // pressed\n if (input.isPressed(32)) { // Space\n bullets.push(new Bullet(ship.x + 10, ship.y, -8, 2, 6, \"#fff\"));\n }\n // update all bullets position and checks\n for (var i = 0, len = bullets.length; i < len; i++) {\n var b = bullets[i];\n b.update();\n // remove bullets outside of the canvas\n if (b.y + b.height < 0 || b.y > display.height) {\n bullets.splice(i, 1);\n i--;\n len--;\n bulletMiss++;\n score--;\n continue;\n }\n // check if bullet hits any city\n var h2 = b.height * 0.5; // half hight is used for\n // simplicity\n if (cities.y < b.y + h2 && b.y + h2 < cities.y + cities.h) {\n if (cities.hits(b.x, b.y + h2)) {\n bullets.splice(i, 1);\n i--;\n len--;\n\n// cityPopulation = cityPopulation - getRandomInt(1000, 10000);\n// if (cityPopulation < 0) {\n// cityPopulation = 0;\n// }\n continue;\n }\n }\n // check if bullet hit any aliens\n for (var j = 0, len2 = aliens.length; j < len2; j++) {\n var a = aliens[j];\n if (AABBIntersect(b.x, b.y, b.width, b.height, a.x, a.y, a.w, a.h)) {\n\n aliens.splice(j, 1);\n j--;\n len2--;\n bullets.splice(i, 1);\n i--;\n len--;\n score = score + 3;\n bulletHit++;\n // increase the movement frequence of the aliens\n // when there are less of them\n switch (len2) {\n case 30:\n {\n this.lvFrame = 30;\n break;\n }\n case 10:\n {\n this.lvFrame = 20;\n break;\n }\n case 5:\n {\n this.lvFrame = 15;\n break;\n }\n case 1:\n {\n this.lvFrame = 10;\n break;\n }\n }\n }\n }\n }// END BULLETS\n // update all bombs position and checks\n for (var i = 0, len = bombs.length; i < len; i++) {\n var b = bombs[i];\n b.update();\n // remove bombs outside of the canvas\n if (b.y + b.height < 0 || b.y > display.height) {\n bombs.splice(i, 1);\n i--;\n len--;\n continue;\n }\n // check if bombs hits any city\n var h2 = b.height * 0.5; // half hight is used for\n // simplicity\n if (cities.y < b.y + h2 && b.y + h2 < cities.y + cities.h) {\n if (cities.hits(b.x, b.y + h2)) {\n bombs.splice(i, 1);\n i--;\n len--;\n cityPopulation = cityPopulation - getRandomInt(1000, 5000);\n continue;\n }\n }\n // Check if bombhit Tank\n if (AABBIntersect(b.x, b.y, b.width, b.height, ship.x, ship.y, ship.w, ship.h)) {\n bombs.splice(i, 1);\n i--;\n len--;\n shipHP--;\n continue;\n }\n }// END BOMBS\n //\n // ALIEN DROP BOMBS\n if (Math.random() < 0.03 && aliens.length > 0) {\n var a = aliens[Math.round(Math.random() * (aliens.length - 1))];\n // iterate through aliens and check collision to make\n // sure only shoot from front line\n for (var i = 0, len = aliens.length; i < len; i++) {\n var b = aliens[i];\n if (AABBIntersect(a.x, a.y, a.w, 100, b.x, b.y, b.w, b.h)) {\n a = b;\n }\n }\n // create and append new bullet\n bombs.push(new Bomb(a.x + a.w * 0.5, a.y + a.h, 4, 2, 4, \"#fff\"));\n }\n // ALIEN MOVEMENT\n if (frames % lvFrame === 0) {\n spFrame = (spFrame + 1) % 2;\n var _max = 0, _min = display.width;\n // iterate through aliens and update postition\n for (var i = 0, len = aliens.length; i < len; i++) {\n var a = aliens[i];\n a.x += 30 * dir;\n // find min/max values of all aliens for direction\n // change test\n _max = Math.max(_max, a.x + a.w);\n _min = Math.min(_min, a.x);\n }\n // check if aliens should move down and change direction\n if (_max > display.width - 30 || _min < 30) {\n // mirror direction and update position\n dir *= -1;\n for (var i = 0, len = aliens.length; i < len; i++) {\n aliens[i].x += 30 * dir;\n aliens[i].y += 50;\n }\n }\n }\n}",
"step(){\n\t\tvar player = this.findPlayer();\n\t\tif(player == null) return;\n\n\t\tthis.face(player.x, player.y);\n\t\tthis.cooldown--;\n\t\tif(this.cooldown==0){\n\t\t\tthis.fire();\n\t\t\tthis.resetCooldown();\n\t\t}\n\t\tif(this.dist(player.x, player.y) < this.range) return;\n\n\t\tvar velocity = this.getOffset(4, this.facing);\n\t\tthis.velocity.x=velocity.x;\n\t\tthis.velocity.y=velocity.y;\n\t\tsuper.step();\n\t}",
"function Tankcpanimate3() {\n requestAnimFrame(Tankcpanimate3);\n if (StartgametankCp3) {\n drawCompetitorTankCP3();\n if (shootcout3 > 335 && count_die3 < 2) {\n tankcp3.ship.move();\n shootcout3++;\n } else if (shootcout3 < 338) {\n shootcout3++;\n } else {\n shootcout3 = 0;\n }\n if (tanknav_chang3 > 135 && tanknav_chang3 < 137 && count_die3 < 2) {\n TankCp2Stop();\n tankStop_senddatatoserver(\"random\", CurrentSesion, \"tank2\", 0, 0, 0, 0, xstop3, ystop3);\n tanknav_chang3++;\n } else if (tanknav_chang3 < 300) {\n tanknav_chang3++;\n } else {\n tanknav_chang3 = 0;\n }\n tankcp3.ship.bulletPool.animate();//list bullet of ship\n }\n}",
"updateMovementDependencies() {\r\n // if (this.hitZone) {\r\n // this.hitZone.x = this.x;\r\n // this.hitZone.y = this.y;\r\n // }\r\n }",
"update(dt) {\n this.updateSpeed(dt);\n // once the player collides with the enemy change his position back to start and update current score\n if (this.checkDetection(allplayers[1], this) === true) {\n this.decreaseScore();\n setTimeout(() => {\n this.resetPositon();\n }, 1);\n }\n}",
"function gameloop(TimeStamp) {\n\t// stats.begin();\n\tlet dt = TimeStamp - LastTime;\n\tLastTime = TimeStamp;\n\n\tGAME.clear();\n\t// GAME.ctx.clearRect(0, 0, 1000, 1000);\n\n\tif (hero.x > 500) hero.x = -500;\n\n\tif (hero1.x > 500) hero1.x = -500;\n\n\tif (hero2.y > 500) hero2.y = -500;\n\n\tif (hero3.x > 500) {\n\t\thero3.x = -500;\n\t\thero3.y = -500;\n\t}\n\t// tank.rotation.omega=0.01\n\t//console.log(control.upPressed);\n\tif (control.key[0].pressed) {\n\t\t// GAME.camera.move.x -= 1 * dt;\n\n\t\t// tank.move.x -= 1 * dt;\n\t\t// tank.vx=-1;\n\t\tGAME.camera.rotation.omega = -0.01;\n\t\ttank.rotation.omega = -0.01;\n\t} else if (control.key[1].pressed) {\n\t\t// GAME.camera.move.x += 1 * dt;\n\n\t\t// tank.move.x += 1 * dt;\n\n\t\tGAME.camera.rotation.omega = 0.01;\n\t\ttank.rotation.omega = 0.01;\n\t} else {\n\t\ttank.rotation.omega = 0;\n\t\tGAME.camera.rotation.omega = 0\n\t}\n\tif (control.key[2].pressed) {\n\t\t// GAME.camera.move.y += 1 * dt;\n\t\t// tank.move.y += 1 * dt;\n\t\t// tank.vx=-1;\n\t\tGAME.camera.move(0,1,dt)\n\t\ttank.move(0,1,dt)\n\n\t\t// tank.x += 1*Math.sin(tank.rotation.angle)*dt;\n\t\t// tank.y += 1*Math.cos(tank.rotation.angle)*dt;\n\t} else if (control.key[3].pressed) {\n\t\t// GAME.camera.move.y -= 1 * dt;\n\t\t// tank.move.y -= 1 * dt;\n\t\t// tank.vy = -1;\n\t\ttank.move(0,-1,dt)\n\t\tGAME.camera.move(0,-1,dt)\n\t\t// tank.x += -1*Math.sin(tank.rotation.angle)*dt;\n\t\t// tank.y += -1*Math.cos(tank.rotation.angle)*dt;\n\t}\n\tif (tank.vy != 0 && tank.vx != 0) {\n\t\ttank.vx /= Math.SQRT2;\n\t\ttank.vy /= Math.SQRT2;\n\t}\n\tif (control.key[4].pressed) {\n\t\tGAME.camera.rotation.angle -= 0.01 * dt;\n\t\t// tank.rotation.angle -= 0.01 * dt;\n\t}\n\tif (control.key[5].pressed) {\n\t\tGAME.camera.rotation.angle += 0.01 * dt;\n\t\t// tank.rotation.angle += 0.01 * dt;\n\t}\n\t// GAME.camera=tank\n\t// GAME.camera.rotation.angle=0\n\tif (GAME.collisionsBetween(villain, hero)) {\n\t\thero.colour = \"#4768ff\";\n\t}\n\t// output.innerHTML=\"i just got hit\";\n\telse hero.colour = \"\";\n\n\t// output.innerHTML=\"<br>\";\n\tstylishhero.animate(0, 2, 30, dt);\n\tGAME.updateCamera(dt)\n\tGAME.render(villain, dt);\n\t// GAME.render(hero1, dt);\n\t// GAME.render(hero2, dt);\n\t// GAME.render(hero3, dt);\n\tGAME.render(hero, dt);\n\tGAME.render(stylishhero, dt);\n\tGAME.render(tank, dt);\n\n\t// console.log(hero.x)\n\n\t// GAME.render(GAME.wall.left,dt)\n\t// console.log(event.clientX)\n\t// console.log(hero.points[0])\n\t// stats.end();\n\t// console.log(GAME.collisionsBetween(villain, stylishhero));\n\n\twindow.requestAnimationFrame(gameloop);\n}",
"function playerControls(scene, duck, flyingDuck) {\r\n\r\n /*\r\n -- subscribe\r\n speedboost (params: start, stop)\r\n jump\r\n arrow keys\r\n fly\r\n \r\n\r\n -- then check if \r\n grid.isInCallRadius() //returns duck object to follow or null to ignore call \r\n\r\n -- check what's around you\r\n grid.getSquareInfo(x,z)\r\n\r\n -- find next location \r\n path.getPath(), could return either an array of points or just the next grid location\r\n\r\n -- must update grid after every move\r\n grid.updateActor(actorID)\r\n\r\n -- ALL functions MUST be filtered through: if(!active) return;\r\n */\r\n\r\n var nestBuilder = new assetGen(scene);\r\n\r\n //when game is paused\r\n var active = false;\r\n var currentState = playerState.init;\r\n\r\n // custom duck data configured here\r\n duck.userData.currentDirection = 'down';\r\n duck.userData.inAir = false;\r\n duck.userData.inWater = false;\r\n duck.position.y = .1;\r\n flyingDuck.visible = false;\r\n\r\n var maxPos = 185;\r\n\r\n var nextPoint = {};\r\n\r\n var duckMover = new ObjectMover(duck, true);\r\n\r\n // superquack variables\r\n // var localStun = false;\r\n // var beginStun;\r\n var stunTimeoutId = null;\r\n var foxes = [];\r\n var hawks = [];\r\n var croqs = [];\r\n\r\n // invis variables\r\n var invisTimeoutId = null;\r\n\r\n var skillLockTimeoutId = null;\r\n var skillLockoutLength = 30;\r\n var stunLock = false;\r\n var speedLock = false;\r\n var invisLock = false;\r\n\r\n //!!! Add if(active) to all core functions\r\n //in Mover, \r\n\r\n // subscriptions\r\n bus.subscribe(\"moveLeft\", duckMover.left);\r\n bus.subscribe(\"rotateLeft\", duckMover.rotateLeft);\r\n bus.subscribe(\"duckLeft\", duckLeft);\r\n bus.subscribe(\"moveRight\", duckMover.right);\r\n bus.subscribe(\"rotateRight\", duckMover.rotateRight);\r\n bus.subscribe(\"duckRight\", duckRight);\r\n bus.subscribe(\"moveDown\", duckMover.down);\r\n bus.subscribe(\"rotateDown\", duckMover.rotateDown);\r\n bus.subscribe(\"duckDown\", duckDown);\r\n bus.subscribe(\"moveUp\", duckMover.up);\r\n bus.subscribe(\"rotateUp\", duckMover.rotateUp);\r\n bus.subscribe(\"duckUp\", duckUp);\r\n bus.subscribe(\"flyToggle\", fly);\r\n bus.subscribe(\"jump\", jumpSkill);\r\n bus.subscribe(\"call\", callSkill);\r\n bus.subscribe(\"nest\", nestSkill);\r\n bus.subscribe(\"quackSkillRequested\", superQuackSkill);\r\n bus.subscribe(\"speedSkillRequested\", speedBoostSkill);\r\n bus.subscribe(\"invisibilitySkillRequested\", invisibilitySkill);\r\n bus.subscribe(\"kill\", kill);\r\n bus.subscribe(\"foundStick\", stickCounter);\r\n\r\n\r\n bus.subscribe(\"gridTest\", gridTest);\r\n\r\n function gridTest() {\r\n grid.testSquareInfo(duck.position.z, duck.position.x);\r\n }\r\n\r\n function fly() {\r\n if (!active)\r\n {\r\n return;\r\n }\r\n duckMover.flyToggle();\r\n if (duck.userData.inAir) {\r\n duck.visible = false;\r\n flyingDuck.visible = true;\r\n }\r\n else {\r\n flyingDuck.visible = false;\r\n duck.visible = true;\r\n }\r\n }\r\n\r\n function duckUp(object) {\r\n if (!active) {\r\n return;\r\n }\r\n\r\n bus.publish(\"rotateUp\");\r\n var isLegal;\r\n isLegal = isLegalMove(duck);\r\n if (isLegal) {\r\n nextPoint.z = duck.position.z;\r\n nextPoint.x = duck.position.x - 10;\r\n stickCheck(nextPoint);\r\n bus.publish(\"moveUp\");\r\n bus.publish(\"playerMove\");\r\n\r\n }\r\n }\r\n\r\n function duckDown(object) {\r\n if (!active) {\r\n return;\r\n }\r\n\r\n bus.publish(\"rotateDown\");\r\n var isLegal;\r\n isLegal = isLegalMove(duck);\r\n if (isLegal) {\r\n nextPoint.z = duck.position.z;\r\n nextPoint.x = duck.position.x + 10\r\n stickCheck(nextPoint);\r\n bus.publish(\"moveDown\");\r\n bus.publish(\"playerMove\");\r\n }\r\n }\r\n\r\n function duckLeft(object) {\r\n if (!active) {\r\n return;\r\n }\r\n\r\n bus.publish(\"rotateLeft\");\r\n var isLegal\r\n isLegal = isLegalMove(duck);\r\n if (isLegal) {\r\n nextPoint.z = duck.position.z + 10;\r\n nextPoint.x = duck.position.x;\r\n stickCheck(nextPoint);\r\n bus.publish(\"moveLeft\");\r\n bus.publish(\"playerMove\");\r\n }\r\n }\r\n\r\n function duckRight(object) {\r\n if (!active) {\r\n return;\r\n }\r\n\r\n bus.publish(\"rotateRight\");\r\n var isLegal\r\n isLegal = isLegalMove(duck);\r\n if (isLegal) {\r\n nextPoint.z = duck.position.z - 10;\r\n nextPoint.x = duck.position.x;\r\n stickCheck(nextPoint);\r\n bus.publish(\"moveRight\");\r\n bus.publish(\"playerMove\");\r\n }\r\n }\r\n\r\n function stickCheck(point) {\r\n if (duck.userData.inAir === true) {\r\n return;\r\n }\r\n\r\n var stickObject;\r\n\r\n if (grid.getSquareInfo(point.z, point.x) == componentType.stick) {\r\n stickObject = grid.getActorObject(point);\r\n bus.publish(\"foundStick\", stickObject);\r\n }\r\n }\r\n\r\n function stickCounter() {\r\n var currentSticks = document.getElementById('sticksOutput');\r\n var numSticks = currentSticks.innerHTML;\r\n numSticks++;\r\n currentSticks.innerHTML = numSticks;\r\n }\r\n\r\n function jumpSkill(object) {\r\n if (!active) {\r\n return;\r\n }\r\n\r\n var nextSquare;\r\n\r\n var facing = duck.userData.currentDirection;\r\n if (duck.userData.inAir === true) {\r\n return;\r\n }\r\n\r\n // get type of square duck is facing\r\n if (facing === 'up') {\r\n nextSquare = grid.getSquareInfo(duck.position.z, duck.position.x - 10);\r\n nextPoint.z = duck.position.z;\r\n nextPoint.x = duck.position.x - 10;\r\n }\r\n else if (facing === 'left') {\r\n nextSquare = grid.getSquareInfo(duck.position.z + 10, duck.position.x);\r\n nextPoint.z = duck.position.z + 10;\r\n nextPoint.x = duck.position.x;\r\n }\r\n else if (facing === 'down') {\r\n nextSquare = grid.getSquareInfo(duck.position.z, duck.position.x + 10);\r\n nextPoint.z = duck.position.z;\r\n nextPoint.x = duck.position.x + 10\r\n }\r\n else if (facing === 'right') {\r\n nextSquare = grid.getSquareInfo(duck.position.z - 10, duck.position.x);\r\n nextPoint.z = duck.position.z - 10;\r\n nextPoint.x = duck.position.x;\r\n }\r\n\r\n // if duck isn't in water and the square it is facing is water, go ahead\r\n if (duck.userData.inWater === false && nextSquare == componentType.water && nextSquare != componentType.duckling) {\r\n bus.publish(\"jumpSound\");\r\n duck.userData.inWater = true;\r\n\r\n if (facing === 'up') {\r\n bus.publish(\"moveUp\");\r\n }\r\n else if (facing === 'left') {\r\n bus.publish(\"moveLeft\");\r\n }\r\n else if (facing === 'down') {\r\n bus.publish(\"moveDown\");\r\n }\r\n else if (facing === 'right') {\r\n bus.publish(\"moveRight\");\r\n }\r\n }\r\n\r\n // if duck is in water and the square it is facing is land, duckling, grass, egg, stick, or nest go ahead\r\n if (duck.userData.inWater === true && (nextSquare == componentType.land || nextSquare == componentType.grass || nextSquare == componentType.egg || nextSquare == componentType.stick || nextSquare == componentType.nest)) {\r\n\r\n bus.publish(\"jumpSound\");\r\n duck.userData.inWater = false;\r\n\r\n if (nextSquare == 11) {\r\n stickCheck(nextPoint);\r\n }\r\n\r\n if (facing === 'up') {\r\n bus.publish(\"moveUp\");\r\n }\r\n else if (facing === 'left') {\r\n bus.publish(\"moveLeft\");\r\n }\r\n else if (facing === 'down') {\r\n bus.publish(\"moveDown\");\r\n }\r\n else if (facing === 'right') {\r\n bus.publish(\"moveRight\");\r\n }\r\n }\r\n\r\n\r\n }\r\n\r\n function callSkill() {\r\n if (!active) {\r\n return;\r\n }\r\n\r\n if (duck.userData.inAir === false) {\r\n bus.publish(\"callSound\");\r\n }\r\n }\r\n\r\n function nestSkill(scene) {\r\n if (!active) {\r\n return;\r\n }\r\n\r\n var currentSticks = document.getElementById('sticksOutput');\r\n var numSticks = currentSticks.innerHTML;\r\n\r\n if (numSticks < 4) {\r\n return;\r\n }\r\n\r\n var duckZ = duck.position.z;\r\n var duckX = duck.position.x;\r\n\r\n // don't check anything if duck is in water or air\r\n if (duck.userData.inWater === false && duck.userData.inAir === false) {\r\n\r\n var validArea = grid.getNestArea(duck.position.z, duck.position.x);\r\n\r\n if (validArea != 0 && duck.userData.inWater === false) {\r\n\r\n // top right\r\n if (validArea == 1) {\r\n nestBuilder.generateNest(duckZ - 5, duckX - 5);\r\n\r\n }\r\n // bottom right\r\n if (validArea == 2) {\r\n nestBuilder.generateNest(duckZ - 5, duckX + 5);\r\n\r\n }\r\n // bottom left\r\n if (validArea == 3) {\r\n nestBuilder.generateNest(duckZ + 5, duckX + 5);\r\n\r\n }\r\n // top left\r\n if (validArea == 4) {\r\n nestBuilder.generateNest(duckZ + 5, duckX - 5);\r\n }\r\n\r\n bus.publish(\"nestSound\");\r\n numSticks -= 4;\r\n currentSticks.innerHTML = numSticks;\r\n }\r\n }\r\n }\r\n\r\n\r\n function superQuackSkill() {\r\n if (!active || stunLength <= 0) {\r\n return;\r\n }\r\n\r\n if (stunLock === true) {\r\n return;\r\n }\r\n else {\r\n foxes = grid.getActorsInRadius(duck.position, callRadius, componentType.fox);\r\n hawks = grid.getActorsInRadius(duck.position, callRadius, componentType.hawk);\r\n croqs = grid.getActorsInRadius(duck.position, callRadius, componentType.croq);\r\n\r\n\r\n if (foxes.length > 0 || hawks.length > 0 || croqs.length > 0) {\r\n bus.publish(\"superQuackSound\");\r\n bus.publish(\"stunSound\");\r\n\r\n for (i = 0; i < foxes.length; i++) {\r\n bus.publish(\"stunned\", foxes[i]);\r\n }\r\n\r\n for (i = 0; i < hawks.length; i++) {\r\n bus.publish(\"stunned\", hawks[i]);\r\n }\r\n\r\n for (i = 0; i < croqs.length; i++) {\r\n bus.publish(\"stunned\", croqs[i]);\r\n }\r\n\r\n stunTimeoutId = setTimeout(function () { resetStunStatus(); }, stunLength * 1000);\r\n }\r\n skillLockout(\"stun\");\r\n }\r\n }\r\n\r\n // called by update function after (stunLength) seconds has elapsed\r\n function resetStunStatus() {\r\n while (foxes.length > 0) {\r\n foxes.shift();\r\n }\r\n while (hawks.length > 0) {\r\n hawks.shift();\r\n }\r\n while (croqs.length > 0) {\r\n croqs.shift();\r\n }\r\n\r\n bus.publish(\"stopStunSound\");\r\n\r\n }\r\n\r\n function speedBoostSkill() {\r\n if (!active || speedLength <= 0) {\r\n return;\r\n }\r\n\r\n if (speedLock === true) {\r\n return;\r\n }\r\n else {\r\n bus.publish(\"speedBoostSound\");\r\n bus.publish(\"toggleSpeedBoost\");\r\n speedTimeoutId = setTimeout(function () \r\n { \r\n bus.publish(\"toggleSpeedBoost\"); \r\n bus.publish(\"clearSpeedTimers\");\r\n \r\n }, speedLength * 1000);\r\n skillLockout(\"speed\");\r\n }\r\n\r\n }\r\n\r\n function invisibilitySkill() {\r\n if (!active || invisLength <= 0) {\r\n return;\r\n }\r\n\r\n if (invisLock === true) {\r\n return;\r\n }\r\n else {\r\n bus.publish(\"invisibilitySound\");\r\n invisActive = true;\r\n invisTimeoutId = setTimeout(function () { invisActive = false; }, invisLength * 1000);\r\n skillLockout(\"invis\");\r\n }\r\n }\r\n\r\n function skillLockout(skill) {\r\n\r\n if (skill == \"stun\") {\r\n if (stunLock === false) {\r\n stunLock = true;\r\n skillLockTimeoutId = setTimeout(function () { skillLockout(\"stun\"); }, skillLockoutLength * 1000);\r\n }\r\n else {\r\n stunLock = false;\r\n }\r\n }\r\n\r\n else if (skill == \"speed\") {\r\n if (speedLock === false) {\r\n speedLock = true;\r\n skillLockTimeoutId = setTimeout(function () { skillLockout(\"speed\"); }, skillLockoutLength * 1000);\r\n }\r\n else {\r\n speedLock = false;\r\n }\r\n }\r\n\r\n else if (skill == \"invis\") {\r\n if (invisLock === false) {\r\n invisLock = true;\r\n skillLockTimeoutId = setTimeout(function () { skillLockout(\"invis\"); }, skillLockoutLength * 1000);\r\n }\r\n else {\r\n invisLock = false;\r\n }\r\n }\r\n }\r\n\r\n function resetLocks() {\r\n stunLock = false;\r\n speedLock = false;\r\n invisLock = false;\r\n }\r\n\r\n function kill(victim) {\r\n if (victim != duck) {\r\n return;\r\n }\r\n var location = new THREE.Vector3(duck.position.x, duck.position.y, duck.position.z);\r\n anim = new animation(scene);\r\n anim.placeBlood(location);\r\n victim.position.y = -100;\r\n\r\n setTimeout(callback, 1000);\r\n active = false;\r\n nestBuilder.cleanup();\r\n function callback() {\r\n currentState = playerState.dead;\r\n }\r\n\r\n }\r\n\r\n function isLegalMove(object) {\r\n\r\n if (!active) {\r\n return false;\r\n }\r\n\r\n var nextSquare;\r\n var facing = duck.userData.currentDirection;\r\n\r\n // all in-air moves are legal since they are over all tiles\r\n if (duck.userData.inAir === true) {\r\n return true;\r\n }\r\n\r\n // get type of square duck is facing\r\n if (facing === 'up') {\r\n nextSquare = grid.getSquareInfo(duck.position.z, duck.position.x - 10);\r\n }\r\n else if (facing === 'left') {\r\n nextSquare = grid.getSquareInfo(duck.position.z + 10, duck.position.x);\r\n }\r\n else if (facing === 'down') {\r\n nextSquare = grid.getSquareInfo(duck.position.z, duck.position.x + 10);\r\n }\r\n else if (facing === 'right') {\r\n nextSquare = grid.getSquareInfo(duck.position.z - 10, duck.position.x);\r\n }\r\n\r\n // moving from land to land, duckling, grass, egg, stick, or nest\r\n if (duck.userData.inWater === false && (nextSquare == componentType.land || nextSquare == componentType.grass || nextSquare == componentType.stick || nextSquare == componentType.nest)) {\r\n return true;\r\n }\r\n\r\n // moving from water to water, requires jumpSkill to move to land\r\n if (duck.userData.inWater === true && nextSquare == componentType.water) {\r\n return true;\r\n }\r\n\r\n // we run into ground predator and die \r\n if (nextSquare === componentType.fox || ((nextSquare === componentType.croq || nextSquare === componentType.hawk) && duck.userData.inWater === true)) {\r\n currentState = playerState.dead;\r\n return true;\r\n }\r\n\r\n // all other moves are illegal\r\n return false;\r\n }\r\n\r\n this.getState = function () {\r\n\r\n return currentState;\r\n };\r\n\r\n this.setState = function (newState) {\r\n\r\n currentState = newState;\r\n };\r\n\r\n this.reset = function () {\r\n duck.userData.inWater = false;\r\n duck.userData.inAir = false;\r\n }\r\n\r\n this.idSelf = function () {\r\n\r\n return \"duck\";\r\n };\r\n\r\n this.setActive = function (value) {\r\n active = value;\r\n }\r\n\r\n this.spawn = function () {\r\n grid.placeActor(duck);\r\n duckMover.updateCam();\r\n //setTimeout(function () { duckMover.updateCam(); 500 });\r\n }\r\n\r\n this.getActor = function () {\r\n return duck;\r\n }\r\n\r\n this.cleanup = function () {\r\n nestBuilder.cleanup();\r\n resetLocks();\r\n if (duck.userData.inAir === true) {\r\n fly();\r\n }\r\n }\r\n\r\n\r\n this.update = function () {\r\n\r\n if (!active)\r\n return;\r\n\r\n var elapsedTime = clock.getElapsedTime();\r\n\r\n if (duck.userData.inAir) {\r\n flyingDuck.position.x = duck.position.x;\r\n flyingDuck.position.y = duck.position.y;\r\n flyingDuck.position.z = duck.position.z;\r\n flyingDuck.rotation.x = duck.rotation.x;\r\n flyingDuck.rotation.y = duck.rotation.y;\r\n flyingDuck.rotation.z = duck.rotation.z;\r\n\r\n }\r\n }\r\n}",
"tick() {\n this.gettingHungry();\n this.gettingSick();\n this.checkSickness();\n this.gettingBored();\n }",
"update (dt){\n // You should multiply any movement by the dt parameter\n // which will ensure the game runs at the same speed for\n // all computers.\n // Enemy moves only to the right, y coordinate stays the same.\n this.setEnemyX(this.x + dt * this.speed);\n this.checkCoordinats();\n\n }",
"update() {\n this.isCollision();\n this.isCollisionEnemy();\n this.x += speed * this.dt;\n //This condition checks when enemy is out of board \n if (this.x >= 520) {\n this.y = posY[enemyNumber];\n this.x = posX[enemyNumber];\n enemyNumber++;\n if (enemyNumber === 3) {\n enemyNumber = 0;\n }\n this.dt = Math.floor(Math.random() * 2 + 1) * speed;\n }\n\n\n\n }",
"function update(){\r\n //Clears the scene so we have clean movement\r\n scene.clear();\r\n checkTime();\r\n updateGUI(); \r\n //MOVE THINGS\r\n leaves.update();\r\n \r\n for(var i = 0; i < flies.length; i++){\r\n flies[i].wriggle();\r\n checkCollisions(i);\r\n flies[i].update();\r\n }\r\n \r\n frog.checkKeys();\r\n //REDRAW THINGS\r\n frog.update();\r\n \r\n}",
"update(dt) {\n // You should multiply any movement by the dt parameter\n // which will ensure the game runs at the same speed for\n // all computers.\n if (this.x < this.boundary) {\n //If bug is within the boudary, move it\n this.x += this.speed * dt;\n } else {\n //If bug is outside of the boundary, reset it\n this.x = this.resetPos;\n }\n }",
"function update(dt) {\n updateEntities(dt);\n // checkCollisions();\n }"
]
| [
"0.6939964",
"0.67906034",
"0.6733706",
"0.671663",
"0.67082286",
"0.67050236",
"0.66832983",
"0.66646653",
"0.66596305",
"0.6654068",
"0.66005886",
"0.658824",
"0.6572592",
"0.65694284",
"0.654105",
"0.6527926",
"0.652132",
"0.6518753",
"0.64736015",
"0.6466151",
"0.6450213",
"0.64239395",
"0.64061165",
"0.63799834",
"0.6372126",
"0.63719976",
"0.63638425",
"0.6351365",
"0.6351286",
"0.6348791"
]
| 0.8118924 | 0 |
Call to rotate the tank with its turningSpeed | rotate(){
this.angle += this.turningSpeed;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function changeRotationDirection() {\n rotationSpeed = -rotationSpeed;\n}",
"function Update () {\n\t//Rotiert um die Rotation Speed in Echtzeit\n\ttransform.Rotate (0.0f, rotateSpeed*Time.deltaTime, 0.0f);\n}",
"function TurtleTurn(angle) {\n turtle.a += angle; // svg uses anti-clockwise but we want clockwise\n if(turtle.a < -180) turtle.a += 360;\n if(turtle.a > 180) turtle.a -= 360;\n\n var delay = Math.abs(angle) / speed; // calculate delay for animation\n \n // angle to turn sprite\n var turn = turtle.a;\n if(turn < -180) turn += 360;\n if(turn > 180) turn -= 360;\n\n turtle.s.animate(delay, '<>', 0).rotate(turn);\n // todo: fix occasional bug of extra rotation of sprite (multiple of 180?)\n\n // add to delay for animation\n //turtle.d += delay;\n}",
"changeSpeed() {\n\n // ternary operator to choose from +1 and -1\n var sign = Phaser.Math.Between(0, 1) == 0 ? -1 : 1;\n\n // random number between -gameOptions.rotationVariation and gameOptions.rotationVariation\n var variation = Phaser.Math.FloatBetween(-gameOptions.rotationVariation, gameOptions.rotationVariation);\n\n // new rotation speed\n this.newRotationSpeed = (this.currentRotationSpeed + variation) * sign;\n\n // setting new rotation speed limits\n this.newRotationSpeed = Phaser.Math.Clamp(this.newRotationSpeed, -gameOptions.maxRotationSpeed, gameOptions.maxRotationSpeed);\n }",
"turn(angle) {\n const { lockAngle, currentAngle } = this.state\n let knobRotation = angle - lockAngle + currentAngle\n\n // Keep angle value less than 360 but keep the right rotation\n if (knobRotation > 360)\n knobRotation = knobRotation % 360\n if (knobRotation < 0)\n knobRotation = knobRotation + 360\n\n // Callback\n this.props.callback(this.calcValue(knobRotation), knobRotation)\n\n this.setState({\n knobRotation: knobRotation,\n })\n }",
"function Update () {\n transform.Rotate(new Vector3(0, 30,0) * Time.deltaTime);\n}",
"function rotateWheel() {\n currentTime += 30;\n // Stops wheel after given seconds i.e. TotalTime.\n if (currentTime >= TotalTime) {\n stopWheel();\n return;\n }\n // calculating spinAngle based on initial angle - easeInOut method for difference to make wheel looks elastic\n const spinAngle = spinAngleStart - easeInOut(currentTime, 0, spinAngleStart, TotalTime);\n func.startangle.set(func.startangle.get() + (spinAngle * Math.PI) / 180);\n drawWheel();\n // using RAF to control the spin\n afterSpin = requestAnimationFrame(rotateWheel);\n}",
"function Obj.prototype.Turn(deg)\n{\n\tthis.wto.setRotation(0,1,0, deg);\n}",
"function rotateWheel() {\n\telapsedSpinTime += 10;\n\tif (elapsedSpinTime >= totalSpinTime) {\n\t\tstopWheelAndGetPlayer();\n\t\treturn;\n\t}\n\t// to slow down the wheel near end by reducing the angle of rotation per loop\n\tvar spinAngle =\n\t\tspinSpeed - easeOut(elapsedSpinTime, 0, spinSpeed, totalSpinTime);\n\n\t//startAngle is in rad and spinAngle is in deg\n\tstartAngle += (spinAngle * pi) / 180;\n\tdrawWheel();\n\tspinTimeout = setTimeout(\"rotateWheel()\", 10);\n}",
"function turnCar(cur, top, turnSpeed) {\n //Cannot use single tenary line as must not change if carAngle = wheelAngle\n carAngle < wheelAngle ? carAngle += (cur / top) * turnSpeed : carAngle;\n carAngle > wheelAngle ? carAngle -= (cur / top) * turnSpeed : carAngle;\n carElement.style.transform = `rotate(${carAngle}deg)`;\n}",
"turn(angle){\n\t\tangle = angle * (180 / Math.PI);// convert radians to degrees\n\t\tthis.game.physics.arcade.velocityFromAngle(angle, this.body.speed, this.body.velocity);\n\t}",
"rotate() {\n this.angle += (((Math.PI * 2) / 360) * 1);\n }",
"rotate() {\n if (this.rotation < GAME_CONFIG.MAX_ANGLE) {\n return;\n }\n if (this.rotation > GAME_CONFIG.MIN_ANGLE) {\n return;\n }\n\n this.ctx.translate(this.x, this.y + this.height / 2);\n this.ctx.rotate(this.rotation ? this._degToRad(this.rotation) : 0);\n this.ctx.translate(-this.x, -this.y - this.height / 2);\n }",
"turn(degrees) {\n console.log(`Turning ${degrees} degrees from ${this.direction}`);\n this.angle += degrees;\n console.log(`to ${this.direction}`);\n }",
"function turnWheels() {\n if (leftSteer) carAngle - 90 < wheelAngle ? wheelAngle -= 1 : wheelAngle;\n if (rightSteer) carAngle + 90 > wheelAngle ? wheelAngle += 1 : wheelAngle;\n resetWheelAngles();\n updateCarWheels();\n updateStats();\n}",
"rotate(rotAngle) {\n this.rotAngle += rotAngle;\n }",
"rotate(){\n switch (this.mode){\n case 0:\n this.rotation.y += 0.01;\n if(this.rotation.y > Math.PI){\n this.mode++;\n }\n break;\n case 1:\n this.rotation.y -= 0.01;\n if(this.rotation.y < -(Math.PI)){\n this.mode = 0;\n }\n break;\n default:\n this.mode = 0;\n break;\n }\n }",
"function angleShooter(name, value) {\n robot.rotator.run_to_position(value, 50);\n}",
"rotate() {\n this.rotateX(rotateX);\n this.rotateY(rotateY)\n }",
"rotater() {\n switch (this.axis) {\n case 'x':\n rotateX(this.dir * this.angle);\n break;\n case 'y':\n rotateY(-1 * this.dir * this.angle);\n break;\n case 'z':\n rotateZ(this.dir * this.angle);\n break;\n }\n }",
"rotateTurtle(x, y, z) {\n var e = new THREE.Euler(\n x * 3.14/180,\n\t\t\t\ty * 3.14/180,\n\t\t\t\tz * 3.14/180);\n this.state.dir.applyEuler(e);\n }",
"function spinWheel(){ degrees+=120; $('.spinWheel').css('transform', 'rotate(' + degrees + 'deg)'); }",
"function rotateLights(speed) {\n light1.position.applyAxisAngle(new THREE.Vector3(0, 1, 0), THREE.MathUtils.degToRad(speed));\n light2.position.applyAxisAngle(new THREE.Vector3(0, 1, 0), THREE.MathUtils.degToRad(speed));\n light3.position.applyAxisAngle(new THREE.Vector3(0, 1, 0), THREE.MathUtils.degToRad(speed));\n}",
"rotate() {\n if (this.widthX == this.depthZ) {\n //console.log(\"Rotating a square is pointless, skipping.\");\n return;\n }\n // If even, it'll just rotate around the center, only do odd:\n if ((this.widthX % 2 == 0 && this.depthZ % 2 != 0) ||\n (this.depthZ % 2 == 0 && this.widthX % 2 != 0)) {\n if (this._mesh.rotation.y == 0) {\n this._mesh.position.x -= 0.5;\n this._mesh.position.z -= 0.5;\n }\n else if (this._mesh.rotation.y == Math.PI / 2) {\n this._mesh.position.x -= 0.5;\n this._mesh.position.z += 0.5;\n }\n else if (this._mesh.rotation.y == Math.PI) {\n this._mesh.position.x += 0.5;\n this._mesh.position.z += 0.5;\n }\n else {\n this._mesh.position.x += 0.5;\n this._mesh.position.z -= 0.5;\n }\n }\n currentRotation = (this._mesh.rotation.y + (Math.PI / 2)) % (Math.PI * 2);\n // console.log(currentRotation);\n TempBrick.rebuildTemp(this.owner);\n }",
"function updateCrownRotate()\n{\n\t// Get the current rotation of the crown\n\tvar transform = script.crownParent.getTransform();\n\tvar rotation = transform.getLocalRotation();\n\n\t// The rotation speed is applied to the crown, rotating it by a tiny amount\n\t// every frame (30 times per second)\n\tvar rotateBy = quat.angleAxis(Math.PI * getDeltaTime() * script.rotationSpeed, vec3.up());\n\trotation = rotation.multiply(rotateBy);\n\n\t// Set the crown's rotation with our newly calculated rotation\n\ttransform.setLocalRotation(rotation);\t\n}",
"_rotate(amount) {\n // Update current rotation\n const rotation = this.rotation;\n rotation.add(amount);\n\n // Lock the rotation in X (pitch) to avoid gimbal lock\n const max = (Math.PI / 2 - 0.01);\n if(rotation.x < -max) rotation.x = -max;\n else if(rotation.x > max) rotation.x = max;\n\n // Create a euler transform \n const euler = new THREE.Euler( \n rotation.x,\n rotation.y,\n rotation.z,\n 'ZYX' // Order of operations is important! XYZ does not produce desired result\n );\n\n // Update forward direction\n const newForward = this.initialForward.clone();\n newForward.applyEuler(euler);\n this.forward = newForward;\n }",
"function turnRotation(){\n // the player has the first go\n console.log(\"fireball throw\");\n if(enemYAttack==true||playerPickShield==true){\n if(enemyfireBallSpawnX<knightPositionX)\n {\n enemyfireBallSpawnX++;\n }\n if(enemyfireBallSpawnY<knightPositionY)\n {\n enemyfireBallSpawnY++;\n }\n if(enemyfireBallSpawnX.x>knightPositionX)\n {\n enemyfireBallSpawnX--;\n }\n if(enemyfireBallSpawnY>knightPositionY)\n {\n enemyfireBallSpawnY--;\n }\n }\n \n \n}",
"rotate() {\n const now = Date.now();\n const delta = now - this.lastUpdate;\n this.lastUpdate = now;\n\n this.setState({rotation: this.state.rotation + delta / 1000});\n this.frameHandle = requestAnimationFrame(this.rotate);\n }",
"function TurnRight()\n{\n turn = (turn - VIEW_TURN_RATE) % 360;\n}",
"function rotate() {\n if(spaceLeft(currentTet) && spaceRight(currentTet)) {\n undraw();\n currentRotation ++;\n currentRotation = currentRotation%4;\n currentTet = tetArr[currType][currentRotation];\n draw();\n }\n}"
]
| [
"0.7271589",
"0.6997725",
"0.6936559",
"0.68122375",
"0.67627",
"0.6705555",
"0.6684365",
"0.6598149",
"0.65428036",
"0.65403044",
"0.6530011",
"0.6495075",
"0.64848685",
"0.64549565",
"0.6419079",
"0.64176047",
"0.6405081",
"0.6396024",
"0.6388298",
"0.63851595",
"0.63731545",
"0.63590926",
"0.6356619",
"0.6320795",
"0.6318546",
"0.6313415",
"0.6313065",
"0.6307257",
"0.6284555",
"0.6278386"
]
| 0.77516055 | 0 |
Call to respawn tank | respawn(){
// Vibrate the user's phone to indicate its death
vibrateUser(this.id, 500);
// Calculate a new spawnpoint and assign it
let newspawn = newSpawnpoint();
this.x = newspawn.x;
this.y = newspawn.y;
this.angle = newspawn.angle;
// Reset everything else
this.moving = false;
this.firing = false;
this.health = tankSettings["health"];
this.spawnProtection = true;
// Give it spawn protection (invincible for a short period after spawning)
setTimeout(() => { this.spawnProtection = false; }, tankSettings["spawnProtection"]);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"respawn() {\n this.state = new CreatureState(this, this.gameEngine, this.getDefaultMaxHealth());\n this.position.x = this.spawnX;\n this.position.y = this.spawnY;\n this.velocity.x = 0;\n this.velocity.y = 0;\n }",
"function handelDeath( yes ) {\n if( yes ) { //respawn from nearest camp if there is one\n if ( player.respawn() ) { \n player.draw = true;\n game = true;\n player.color = 'yellow';\n } else {\n init(); \n }\n } else {\n ctx.clearRect( 0, 0, w, h );\n document.getElementById( \"introToast\" ).className = \"toast\";\n }\n document.getElementById( \"deadToast\" ).className = \"invis\";\n }",
"respawnPlayer(){\n this.playerHealth = 1;\n this.player.anims.play(\"idle\");\n this.player.setX(225);\n this.player.setY(625);\n this.player.setVisible(true);\n }",
"function callKnightClick() {\n score -= 2000;\n man = new Knight();\n callMan();\n }",
"respawn(memory, name){\n if(memory.home && memory.source){\n // deleting from other lad too\n for(var j=0; j < this._roomData.resourceData[memory.source].harvesters.length; j++){\n // iterate over our creep array\n if(this._roomData.resourceData[memory.source].harvesters[j] == name){\n this._roomData.resourceData[memory.source].harvesters.splice(j,1);\n //console.log(\"deleted \", name, \" now \", memory.source, \".\");\n }\n\n \n }\n\n for(var j=0; j < this._roomData.resourceData[memory.source].transporters.length; j++){\n // iterate over our creep array\n if(this._roomData.resourceData[memory.source].transporters[j] == name){\n this._roomData.resourceData[memory.source].transporters.splice(j,1);\n //console.log(\"deleted \", name, \" now \", memory.source, \".\");\n }\n \n }\n\n }\n\n console.log(\"creep died should re-add to spawnQueue\");\n // re-init.\n memory.state = States.INIT;\n this.updateRole(memory.role);\n }",
"CanRespaw() {\n if(this.player1.deadOrAlive === 0) {\n if(this.player1.hp > 0) {\n this.player1.deadOrAlive = 1;\n setTimeout( this.player1.spawnPlayer() , 3000);\n this.player1.hp -= 1;\n document.querySelector('.player1hp ').innerHTML -= 1;\n \n }\n }\n \n if(this.playerNumb === 2) {\n if(this.player2.deadOrAlive === 0) {\n if(this.player2.hp > 0) {\n setTimeout( this.player2.spawnPlayer2() , 3000);\n this.player2.deadOrAlive = 1;\n this.player2.hp -= 1;\n document.querySelector('.player2hp ').innerHTML -= 1;\n \n }\n }\n }6\n this.gameOver();\n}",
"static tick() {\n this.counter = 0;\n this.pokemonAttack();\n }",
"function rankUp(){\r\n \t$rootScope.buttonLimiter++;\r\n \tif($rootScope.buttonLimiter==1)\r\n \t{\r\n \t\tif($rootScope.canRankUp == 'true')\r\n \t\t{\r\n\t\t \t$rootScope.rsrank += 1;\r\n\t\t \t$rootScope.rsnextrankup = Decimal.add($rootScope.rsnextrankup,Decimal.mul(Decimal.add($rootScope.rsascensions,1),5));\r\n\t\t \t$rootScope.rsnextrankuptxt = formatNumbers($rootScope.rsnextrankup,$rootScope.numberNotation);\r\n\t\t \tcomputeDamageMul();\r\n\r\n\t\t\t\t$rootScope.rsdamage = Decimal.mul(Decimal.mul($rootScope.rsstatpower,1),$rootScope.rstotaldamagemul);\r\n\t\t\t\t$rootScope.rsdamagetxt = formatNumbers($rootScope.rsdamage,$rootScope.numberNotation);\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar limiter = function(){\r\n \t\t$rootScope.buttonLimiter = 0;\r\n \t}\r\n \t$timeout(limiter,2000);\r\n }",
"function bb(p) {\n Stats[p.name].disconnect();\n room.kickPlayer(p.id, \"rip !\", false);\n}",
"function C012_AfterClass_Pool_Shower() {\n\tCurrentTime = CurrentTime + 290000;\n\tCommon_PlayerPose = \"Showering\";\n}",
"function autoRoboTrimp() {\n //exit if the cooldown is active, or we havent unlocked robotrimp.\n if (game.global.roboTrimpCooldown > 0 || !game.global.roboTrimpLevel) return;\n var robotrimpzone = parseInt(getPageSetting('AutoRoboTrimp'));\n //exit if we have the setting set to 0\n if (robotrimpzone == 0) return;\n //activate the button when we are above the cutoff zone, and we are out of cooldown (and the button is inactive)\n if (game.global.world >= robotrimpzone && !game.global.useShriek){\n magnetoShriek();\n if (MODULES[\"other\"].enableRoboTrimpSpam)\n debug(\"Activated Robotrimp MagnetoShriek Ability @ z\" + game.global.world, \"graphs\", '*podcast');\n }\n}",
"function attemptRespawn() {\n\tif ((g_Minigame.CurrentScene().m_bIsDead) && \n\t\t\t((g_Minigame.CurrentScene().m_rgPlayerData.time_died * 1000) + 5000) < (new Date().getTime())) {\n\t\tRespawnPlayer();\n\t}\n}",
"interact() {\n battle()\n }",
"function respawn() {\n\tball.x = canvas.width/2;\n\tball.y = BALL_Y_MARGIN;\n\tball.dx = ball.startDX;\n\tball.dy = ball.startDY;\n\tpaddle.x = PADDLE_START_X;\n\tstartPressed = false;\n}",
"function kickPlayer(pc) {\n\tif(!this.players[pc.tsid]) {\n\t\tlog.info('[GAMES] '+this+' '+pc+' trying to kick, but not a player');\n\t\treturn;\n\n\t}\n\t\n\tlog.info('[GAMES] '+this+' '+pc+' kicking');\n\n\t// Find the player's instance\n\tvar id = this.players[pc.tsid].id;\n\t// Evacuate player from instance location\n\tpc.instances_exit(this.getInstanceName(id));\n}",
"function kill(data) {\n // Increase passage counter\n passage++;\n // Increase index of kill command so we get the next one\n data.index++;\n // Reset attempts now that we've successfully issued a command\n attempts = 0;\n\n // Check if we're at the end of the kill commands\n if (data.index === data.encounter.commands.length) {\n // He's dead! So add corpse text to the location\n map[currentPlace][\"corpse\"] = data.encounter.corpse.replace('[[object]]',data.object);\n map[currentPlace][\"no_encounters\"] = true;\n\n // Reset encounter state\n currentEncounter = undefined;\n currentObject = undefined;\n\n // Remove him from the encounters list\n let encounterIndex = encounters.indexOf(data.encounter);\n if (encounterIndex !== -1) {\n // console.log(\"Removing \",encounterIndex);\n // encounters = encounters.slice(encounterIndex,encounterIndex+1);\n encounters.splice(encounterIndex,1);\n // console.log(encounters);\n }\n\n if (encounters.length === 0) {\n let $gameOver = $('<div><p>Having eliminated the final terrorist agent, you holster your pistol and lean against a wall.</p><p>Over your radio, a distant yet close voice says, \"Counter-Terrorists win.\"</p><p style=\"font-weight:bold\">GAME OVER.</p></div>');\n showPassage($('<div></div>'),$gameOver,SINGLE_PAGES);\n }\n else {\n // If so \"move\" to the current location\n move({ destination:currentPlace, long:false, clear: SINGLE_PAGES, resetEncounter: true });\n }\n }\n else {\n // Otherwise, build the next command\n annyangCommands = {};\n let command = { command: data.encounter.commands[data.index], id: \"T1-\"+passage };\n command.command = command.command.replace('[[object]]',map[\"currentObject\"]);\n\n let $passage = $('<div></div>');\n let $commands = $('<div></div>');\n data.clear = SINGLE_KILL_PAGES;\n\n let $command = buildCommand(command,kill,data);\n $commands.append($command);\n annyangCommands[command.command] = function () {\n execute($command,kill,data);\n }\n // $text.append($commands);\n setAnnyangCommands(annyangCommands);\n showPassage(undefined,$commands,SINGLE_PAGES && (SINGLE_KILL_PAGES || data.index===1));\n }\n}",
"function resetCharacter() {\n\tif(character.rip) {\n\t\tSTATE = \"TIMEOUT\";\n\t\tsetTimeout(() => {\n\t\t\trespawn();\n\t\t\tSTATE = \"MOVING\";\n\t\t}, 15000);\n\t}\n}",
"function resetCharacter() {\n\tif(character.rip) {\n\t\tSTATE = \"TIMEOUT\";\n\t\tsetTimeout(() => {\n\t\t\trespawn();\n\t\t\tSTATE = \"MOVING\";\n\t\t}, 15000);\n\t}\n}",
"endGame(giveUp){\n let pc, player;\n let victory=false;\n if(this.computerPlayer == WHITE_DISK){\n pc = this.whiteDisksPlayer;\n player = this.blackDisksPlayer;\n }\n else{\n pc = this.blackDisksPlayer\n player = this.whiteDisksPlayer;\n }\n if(pc.disks > player.disks){\n victory=false;\n }\n else{\n victory = true;\n }\n if(giveUp){\n this.playState.giveUpMessage();\n victory = false;\n }\n else{\n this.playState.displayVictoryOrDefeat(victory);\n }\n\n this.gameBoard.board.style.setProperty(\"opacity\", 0.2);\n\n this.updateClassifications(victory);\n\n this.restart.showRestartGame();\n \n }",
"function C009_Library_Yuki_Sleep() {\n\tActorSetPose(\"Sleeping\");\n\tGameLogAdd(\"Sleep\");\n\tLeaveIcon = \"Leave\";\n\tCurrentTime = CurrentTime + 50000;\n\tC009_Library_Library_CurrentZone = \"007\";\n\tC009_Library_Yuki_CanFindPlayer = false;\n}",
"function cmd_Climb() {\n\t\tif ((current_loc === 3) && (loc_desc_used()[current_loc] === loc_desc_alt[current_loc])) {\n\t\t\tplayer_Win();\n\t\t}\n\t\telse {\n\t\t\tgameplayError(2);\n\t\t}\n\t}",
"end()\n {\nconsole.log(\"Game Ended\");\n//console.log(player.rank);\ngame.update(2);\n\n\n\n }",
"function updateRespawns(dt)\n{\n\t// PLAYER RESPAWNS HANDLED IMMEDIATELY\n\t//updateListOfRespawns_Players(); // TODO: sometimes triggers when it shouldnt?\n\t\n\t// THE REST ONLY OCCUR ON A PERIODIC\n\t// TIMER INTERVAL\n\tif (game_state.actorRespawnTimer >= 0)\n\t{\n\t\tgame_state.actorRespawnTimer -= dt;\n\t\treturn;\n\t}\n\tgame_state.actorRespawnTimer = game_state.actorRespawnInterval;\n\t//console.log(\"Running periodic respawn check...\");\n\t\n\t// echo globally the census data\n\t//socket.broadcast.emit('tellusersglobalstuff', 'green', 'There are currently ' + game_state.getDataMemberCount(game_state.users) + ' spaceships in this region');\n\t//console.log(\"------\");\n\t//console.log('There are currently ' + game_state.getDataMemberCount(game_state.users) + ' players in this region');\n\t\n\tvar lTime = game_clock.showClockTime();\n\t//console.log(lTime + \" - \" + game_state.getDataMemberCount(game_state.users) + \" Player IPs in game: \");\n\t//for(var i in game_state.users) { console.log(game_state.users[i].request.connection.remoteAddress); }\n\t//console.log(\"------\");\n\t\n\t// a player's stored IP address does not match their connection IP!\n\tfor(var i in game_state.users) { \n\t\t//if (game_state.userIPs[i] != game_state.users[i].request.connection.remoteAddress) \n\t\t//\tconsole.log(i + \": \" + game_state.userIPs[i] + \" != \" + game_state.users[i].request.connection.remoteAddress); \n\t\t\n\t\tif (game_state.userIPs[i] != game_state.getUserIP(i)) \n\t\t\tconsole.log(i + \": \" + game_state.userIPs[i] + \" != \" + game_state.getUserIP(i)); \n\t}\n\t\n\t// RANDOM AI ACTORS\n\tupdateListOfRespawns_AiPlayers();\n\t// SOLAR SYSTEMS\n\tupdateListOfRespawns_SolarSystems();\n\t// WORMHOLES\n\tupdateListOfRespawns_Wormholes();\n\t\n}",
"tick (player) {\n if (this.punched) this.move(player);\n this.setHandLocation(player);\n }",
"function fctnPlayerAbilityJump(){\n playerObject.setTempYMomentum(playerObject.getTempYMomentum()-intJumpHeight*intGravityDirection);\n}",
"function defend() {\r\n battle.lock_action(this, 0, 'defend');\r\n}",
"function Tankcpanimate3() {\n requestAnimFrame(Tankcpanimate3);\n if (StartgametankCp3) {\n drawCompetitorTankCP3();\n if (shootcout3 > 335 && count_die3 < 2) {\n tankcp3.ship.move();\n shootcout3++;\n } else if (shootcout3 < 338) {\n shootcout3++;\n } else {\n shootcout3 = 0;\n }\n if (tanknav_chang3 > 135 && tanknav_chang3 < 137 && count_die3 < 2) {\n TankCp2Stop();\n tankStop_senddatatoserver(\"random\", CurrentSesion, \"tank2\", 0, 0, 0, 0, xstop3, ystop3);\n tanknav_chang3++;\n } else if (tanknav_chang3 < 300) {\n tanknav_chang3++;\n } else {\n tanknav_chang3 = 0;\n }\n tankcp3.ship.bulletPool.animate();//list bullet of ship\n }\n}",
"runMove()\n {\n const targetPos = new RoomPosition(this.memory.targetPos.x,\n this.memory.targetPos.y,\n this.memory.targetPos.roomName);\n\n // Has the creep arrived?\n if (this.instance.pos.getRangeTo(targetPos) <= 1)\n {\n this.calcNextState();\n this.run();\n return;\n }\n\n // Not there yet? Move.\n if (!this.instance.fatigue)\n this.instance.moveTo(targetPos, {visualizePathStyle: {stroke: '#ffffff'}});\n }",
"respawn() {\n // Generate a random x and y position\n this.x = randomInteger(0, world.width)\n this.y = randomInteger(0, world.height)\n return true\n }",
"function shotPlayer(player) {\n\t// player.body.rotation = 90;\n\tplayer.customData.killed = true;\n\tplayer.visible = false;\n\tplayer.text.visible = false;\n\tplayer.body.velocity.x = 0;\n\tif (player === getMyPlayer()) {\n\t\twindow.setTimeout(sendReborn, 3000, player);\n\t}\n}"
]
| [
"0.6211061",
"0.5837684",
"0.57725304",
"0.56855625",
"0.5656597",
"0.56466365",
"0.5628008",
"0.55790925",
"0.5516154",
"0.5509695",
"0.5494012",
"0.54748064",
"0.5469703",
"0.5468253",
"0.54681754",
"0.5455974",
"0.54552823",
"0.54552823",
"0.5448233",
"0.54419255",
"0.5435965",
"0.542503",
"0.54240924",
"0.54135334",
"0.540897",
"0.5393855",
"0.53937876",
"0.53913206",
"0.53723395",
"0.5365476"
]
| 0.7293473 | 0 |
Call to fire a projectile | fire(){
// Calculate the origin of the projectile based on the tank's pipe
let px = this.x + (this.w / 2) + (cos(-this.angle) * 10) + 4;
let py = this.y + (this.h / 2) + (sin(-this.angle) * 15);
// Spawn a projectile
this.projectiles.push(new Projectile(px, py, this.angle, this));
this.firingCooldown = tankSettings["projectileCooldown"];
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"fireProjectile () {\n this.gameObjectsGroup.projectilesGroup.spawn(this.sprite.x, this.sprite.y, this.sprite.angle);\n }",
"fire(x, y, scene, pointer) {\n // displays the projectile\n this.body.reset(x, y)\n this.setActive(true)\n this.setVisible(true)\n \n this.setSize(15,3)\n\n let angle = Phaser.Math.Angle.BetweenPoints(this, pointer)\n this.rotation = angle\n scene.physics.velocityFromRotation(angle, 150, this.body.velocity)\n\n }",
"function fireprojectile(angle, id){\n\t\t\t//console.log(\"FP Called from\" + id);\n\t\t\tvar timeStamp = Date.now();\n\t\t\t//var sinceLastShot = timeStamp - lastShotTime;\n\t\t\t//console.log(\"Fire triggered\");\n\t\t\tfor(i = 0; i < Students.length; i++){\n\t\t\t\t\t\n\t\t\t\t\t//If the student Id is the one that issued the command\n\t\t\t\t\tif(Students[i].id == id){\n\t\t\t\t\tvar sinceLastShot = timeStamp - Students[i].lastShotTime;\n\t\t\t\t\t// So I check if its an upgraded shots or not\n\t\t\t\t\tif (Students[i].eraserBullets > 0){\n\t\t\t\t\t\tif( sinceLastShot > Students[i].fireRate){\n\t\t\t\t\t\t\t\tStudents[i].lastShotTime = timeStamp;\n\t\t\t\t\t\t\t\tproj1 = Projectile(Students[i].x+50,Students[i].y+50, Students[i], \"eraser\", angle, 90);\n\t\t\t\t\t\t\t\tproj1.draw();\n\t\t\t\t\t\t\t\tprojectiles.push(proj1);\n\t\t\t\t\t\t\t\tproj1.shotBy.eraserBullets --;\n\t\t\t\t\t\t\t\tproj1.shotBy.speedShots --;\n\t\t\t\t\t\t\t\tconsole.log(\"FP upgraded Called from\" + id);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\n\t\t\t\t\t}\n\t\t\t\t\telse if (Students[i].extensionBullets > 0){\n\t\t\t\t\t\tif( sinceLastShot > Students[i].fireRate){\n\t\t\t\t\t\t\t\tStudents[i].lastShotTime = timeStamp;\n\t\t\t\t\t\t\t\tproj1 = Projectile(Students[i].x+50,Students[i].y+50, Students[i], \"extension\", angle, 70);\n\t\t\t\t\t\t\t\tproj1.draw();\n\t\t\t\t\t\t\t\tprojectiles.push(proj1);\n\t\t\t\t\t\t\t\tproj1.shotBy.extensionBullets --;\n\t\t\t\t\t\t\t\tproj1.shotBy.speedShots --;\n\t\t\t\t\t\t\t\tconsole.log(\"extension Bullets\" + proj1.shotBy.extensionBullets);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\n\t\t\t\t\t}\n\t\t\t\t\telse if(Students[i].bulletCount > 0){\n\t\t\t\t\t\t\tif( sinceLastShot > Students[i].fireRate){\n\t\t\t\t\t\t\t\tconsole.log(\"FP Called from\" + id);\n\t\t\t\t\t\t\t\tStudents[i].lastShotTime = timeStamp;\n\t\t\t\t\t\t\t\tproj1 = Projectile(Students[i].x+50,Students[i].y+50, Students[i], \"basic\", angle, 50);\n\t\t\t\t\t\t\t\tproj1.draw();\n\t\t\t\t\t\t\t\tprojectiles.push(proj1);\n\t\t\t\t\t\t\t\tproj1.shotBy.bulletCount --;\n\t\t\t\t\t\t\t\tproj1.shotBy.speedShots --;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\t\t\n\t\t\t}",
"function Shoot() {\n\n\t//Add fireRate and current time to nextFire\n\tnextFire = Time.time + fireRate;\n\t\n\t//Instantiate the projectile\n\tvar clone = Instantiate (projectile, transform.position, transform.rotation);\n\t\t\n\t//Name the clone \"Shot\" ::: this name will appear in the Hierarchy View when you Instantiate the object\n\tclone.name = \"Shot\";\n\t\n\t//Add speed to the target\n\tclone.GetComponent.<Rigidbody>().velocity = transform.TransformDirection (Vector3.forward * Velocity);\n\t\n}",
"function shootActionF () {\n playerIterations++;\n fireball.revive();\n fireball.position.x = player.position.x;\n fireball.position.y = player.position.y;\n\n fireball.animations.play('fire_' + directions[direction]);\n\n fireball.body.velocity.x = 0;\n fireball.body.velocity.y = 0;\n\n if (direction == 0)\n fireball.body.velocity.y = 150;\n else if (direction == 2)\n fireball.body.velocity.y = -150;\n else if (direction == 1)\n fireball.body.velocity.x = -150;\n else if (direction == 3)\n fireball.body.velocity.x = +150;\n\n player.frame = directionFrames[direction] - 1;\n}",
"get fireAlias(){\n\t\tvar p = new playerProjectile(this.pos);\n\t\tp.vel = vec2.fromAng(this.rotation, this.firePow);\n\t\tp.explode = function(){this.vel = new vec2(NaN)};\n\t\treturn p;\n\t}",
"touchTile(entity){\n entity.effect.add('fire', 3);\n }",
"fire(i,obj,$div,boolean,ammoIndex) {\n if (ammoIndex===0) {\n this.pearBomb(i,obj,$div)\n } else if (ammoIndex===1) {\n this.bananaCluster(i,obj,$div,boolean)\n } else if (ammoIndex===2) {\n this.homingMelon(i,obj,$div,boolean)\n } else if (ammoIndex===3) {\n this.grapesOfWrath(i,obj,$div,boolean) \n } else {\n this.nuketerine(i,obj,$div)\n }\n }",
"fire(){\n\t\tvar hand = this.getOffset(25, this.facing);\n\t\tvar posision = new Pair(hand.x + this.x, hand.y + this.y);\n\t\tvar velocity = this.getOffset(15, this.facing);\n\t\tvar color = 'rgba(255, 0, 0, 1)';\n\t\tthis.stage.addActor(new Bullet(this.stage, posision, velocity, color, 4, 30, this.stage.params['opponentDamage'], 'enemy'));\n\t}",
"function use (user) {\n //Fire a projectile\n user.fireProjectile(240, 120, this.properties.tileset, function (tp, a, b, c) {\n if (tp === 'actor') {\n console.log('Adjusting health of ' + a.id);\n a.decStat('health', 100); \n }\n });\n}",
"finishFire(){\n\t\tif(this.firePow < 2){\n\t\t\tthis.firePow = 0;\n\t\t\tthis.fireAdj = false;\n\t\t\treturn;\n\t\t}\n\t\tplayerProjectile.fire(this.pos, this.rotation, this.firePow);\n\t\tthis.firePow = 0;\n\t\tthis.fireAdj = false;\n\t\tthis.ammo -= 1;\n\t\tif(!this.isAlias)\n\t\t\tplaySound(sfx.shoot);\n\t}",
"function fire(player)\n{\n\tvar line = new Phaser.Line(player.x, player.y, game.input.worldX, game.input.worldY);\n\tvar ang = normRad(line.angle);\n\n\tif(ang >= 325 || ang <= 45)\n\t{\n\t\tplayer.animations.play('rightShoot');\n\t\tplayer.facingRight = true;\n\t}\n\telse if(ang > 45 && ang < 135)\n\t{\n\t\tplayer.animations.play('downShoot');\n\t\tplayer.facingRight = true;\n\t}\n\telse if(ang >= 135 && ang <= 225)\n\t{\n\t\tplayer.animations.play('leftShoot');\n\t\tplayer.facingRight = false;\n\t}\n\telse \n\t{\n\t\tplayer.animations.play('upShoot');\n\t\tplayer.facingRight = true;\n\t}\n\n\tplayer.shooting = true;\n}",
"function fire() {\n stopFireTimer();\n startFireTimer();\n myTankO.fireShell();\n if(this.readyToFire == false) {\n\n }\n else {\n }\n \n}",
"fire(qx, qy, theta){\n\t\tthis.quadrant.x = qx;\n\t\tthis.quadrant.y = qy;\n\t\tthis.facing = theta;\n\t\tthis.weapon1.shoot();\n\t}",
"fire() {\n if (Date.now() - this.lastFire < COOLDOWN_TIME) {\n return;\n }\n // Play sound.\n Audio.get().playSound('xwing_fire', .5);\n // Create laser at a certain point.\n this.emitters.forEach((emitter) => {\n const laser = new Laser().build();\n laser.position.copy(emitter.getWorldPosition(WORLD_POS_VEC));\n Engine.get().getScene().add(laser);\n });\n this.lastFire = Date.now();\n }",
"fireLaser(x, y) {\n const enemyLaser = this.getFirstDead(false);\n if (enemyLaser) {\n enemyLaser.fire(x, y);\n }\n \n }",
"function fireWeapon(attacker) { \r\n if (fireCooldown == false) {\r\n missiles.push(new Unit(10, 20, \"img/defender_rocket.png\", attacker.x + attacker.width/2-5 , attacker.y, \"image\"));\r\n fireCooldown = true;\r\n lastLaunchTime = (new Date()).valueOf();\r\n missileSfx = new sound(\"sound/missile_launch.mp3\");\r\n missileSfx.play();\r\n delete missileSfx;\r\n }\r\n}",
"update() {\r\n this.draw(); // call draw method when use update method of projectile\r\n this.x = this.x + this.velocity.x;\r\n this.y = this.y + this.velocity.y;\r\n }",
"update() {\r\n this.draw(); // call draw method when use update method of projectile\r\n this.x = this.x + this.velocity.x;\r\n this.y = this.y + this.velocity.y;\r\n }",
"function projectile(){\n \n//makes things easier, it cannot be global\n const H = windowHeight;\n const W = windowWidth;\n \n this.Y = p.posY;\n this.X = p.posX;\n this.dR = (W * 1/50);\n this.spd = 7;\n \n \n \n this.work = function(){\n //color\n fill(255, 127, 80); \n //move up\n\tthis.Y -= this.spd;\n //THis can change\n ellipseMode(CENTER);\n //display\n ellipse(this.X,this.Y,this.dR,this.dR);\n }\n}",
"function fireRocket() {\n\trocket.x = player.x;\n\trocket.y = player.y;\n\tvar newRocketIndex = activeRockets.length + 1;\n\tvar newRocket = new drawRocket(newRocketIndex);\n\tactiveRockets.push(newRocket);\n}",
"flap(){\r\n this.bird.jump();\r\n }",
"shoot(x, y) {\n\t\tvar projectile = new Projectile(this, stage, new Pair(this.position.x, this.position.y), new Pair(x, y), 5, 3, 1000, 20);\n\t\tthis.stage.addActor(projectile);\n\t}",
"function Projectile() {\n\tthis.speed = 25;\n\tthis.x = canvas.width/2;\n\tthis.y = canvas.height/2;\n\tthis.fired = false;\n\tallProjectiles.push(this);\n}",
"fire(vector) {\n // console.log('bang in ' + vector.x + \" \" + vector.y);\n }",
"fireLaser() {\n this.gm.createLaser();\n }",
"function fireGun(e) {\n //Lets check if we can allow this to occur \n if(canIclick== 0 && gameEnded==0 && $(\"#SZ0_2\").css('opacity') != 1){\n //looks like we can so we better set our flag \n canIclick=1;\n $(\"#SZ0_1\").animateSprite(\"play\", \"fire\");\n //increment our shots\n current_shots++;\n //play the fire sound \n $.playSound('sounds/fire');\n //check to see if we have reached the maximum\n if(current_shots>=max_shots){\n //show the reload button\n $(\"#SZ0_2\").css({opacity:1});\n }//if\n }\n}",
"function fire() {\n throw \"No fire() method defined.\";\n}",
"update () {\n // Fire a projectile\n if (this.canFire) {\n this.fireProjectile();\n // Prevent the saucer from firing again until <1 / FIRE_RATE>\n // seconds have passed\n this.canFire = false;\n this.scene.time.addEvent({\n delay: 1000 / (this.constructor.FIRE_RATE * this.levelMultiplier),\n callback: function () { this.canFire = true; },\n callbackScope: this\n });\n }\n\n // Keep saucers within the physics world bounds\n this.scene.physics.world.wrap(this.sprite, this.constructor.WRAP_PADDING);\n }",
"function fire() {\n var laser = createLaser();\n playArea.appendChild(laser);\n var audioLaser = new Audio('audio/laser-sfx.m4a');\n audioLaser.play();\n moveLaser(laser);\n}"
]
| [
"0.77957875",
"0.7091245",
"0.69315416",
"0.6596553",
"0.6539098",
"0.6496126",
"0.64751554",
"0.6463797",
"0.6458848",
"0.6417896",
"0.6364606",
"0.6340049",
"0.63023305",
"0.6282061",
"0.6262579",
"0.62603843",
"0.6177524",
"0.61766654",
"0.61766654",
"0.6165898",
"0.61475575",
"0.6140272",
"0.61275595",
"0.6107095",
"0.6098634",
"0.6038939",
"0.6035129",
"0.60248566",
"0.60078156",
"0.60012627"
]
| 0.7781981 | 1 |
Adicionar un servicio qu presta | function adicionarServicio(apl) {
if (regServPresta.getForm().isValid()) {
regServPresta.getForm().submit({
url: 'insertarservicio',
waitMsg: perfil.etiquetas.lbMsgEsperaRegServ,
params: {idsistema: arbolServ.getSelectionModel().getSelectedNode().attributes.id, idprocess: cbProcesos.getValue(), tabactivo: tpPrincipal.getActiveTab().id}, //arregloservicios:Ext.encode(resultado)},
failure: function(form, action) {
if (action.result.codMsg != 3) {
mostrarMensaje(action.result.codMsg, perfil.etiquetas.lbMsgAddServ);
regServPresta.getForm().reset();
if (!apl)
winIns.hide();
stGpServicio.reload();
sm.clearSelections();
btnModificar.disable();
//btnEliminar.disable();
}
if (action.result.codMsg == 3)
mostrarMensaje(action.result.codMsg, action.result.mensaje);
}
});
}
else
mostrarMensaje(3, perfil.etiquetas.lbMsgErrorEnCamops);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"addServicio(){\n\t\t\tif(this.get('addNewServicio')) {\n\t\t\t\tthis.set('addNewServicio', false)\n\t\t\t} else {\n\t\t\t\tthis.set('addNewServicio', true)\n\t\t\t}\n\t\t}",
"registerService(service) {\n this.services.push(service);\n }",
"function addTempService(faceId, serviceId) {\n var service = new OdontogramaService.service($scope.checkId, faceId, serviceId);\n OdontogramaService.servicesTemp.unshift(service);\n }",
"function registrar_servicio(){\n\t\tenviarFormulario(\"#form_servicios_registrar\", 'Servicios/registrar_servicio', '#cuadro2');\n\t}",
"_storeServiceName(service) {\n let service_name = services.SERVICES[services.SERVICE_LABELS.indexOf(service)];\n let service_data = require(\"./services/\" + service_name);\n this.options.bluemix[service_name] = service_data[service_name];\n this.options.bluemix.server.services.push(service_name.toUpperCase() + \"_INSTANCE_REPLACE_ME\");\n }",
"function createService(req, res){\n var userId = req.params.id;\n var hotelId = req.params.hid;\n var service = new Service();\n var params = req.body;\n params.nameService = params.nameService.toLowerCase();\n\n if(userId != req.user.sub){\n return res.status(400).send({message:'No posees permisos para hacer esta accion'});\n }else{\n if(params.nameService && params.price){\n Hotel.findById(hotelId, (err, hotelFind) => {\n if(err){\n return res.status(400).send({message:'Error general al intentar buscar el hotel'});\n }else if(hotelFind.user == userId){\n Service.findOne({nameService: params.nameService, _id: {\"$in\": hotelFind.services}}, (err, findService) => {\n if(err){\n return res.status(400).send({message:'Error general al intentar buscar Service'});\n }else if(findService){\n return res.send({message:'Este servicio ya ha sido creado anteriormente'});\n }else{ \n service.nameService = params.nameService.toLowerCase();\n service.price = params.price;\n \n service.save((err, serviceSaved) => {\n if(err){\n return res.status(400).send({message:'Error general al intentar crear Service'});\n }else if(serviceSaved){\n Hotel.findByIdAndUpdate(hotelId, {$push:{services: serviceSaved._id}}, {new: true}, (err, servicePush)=>{\n if(err){\n return res.status(500).send({message: 'Error general al agergar servicio'})\n }else if(servicePush){\n return res.send({message:'El servicio se creo exitosamente', showService: serviceSaved});\n }else{\n return res.status(500).send({message: 'Error al agregar servicio'})\n }\n })\n }else{\n return res.status(400).send({message:'No sea ha podido crear el servicio'});\n }\n })\n }\n })\n }else{\n return res.status(404).send({message:'No se ha encontrado el hotel'});\n }\n })\n }else{\n return res.status(400).send({message:'Por favor ingresa todos los parametros'});\n } \n }\n}",
"function addServices() {\n // Read preinstalled services\n var servicespath = path.join(app.getAppPath(), 'services')\n \n var files = fs.readdirSync(servicespath)\n\n files.forEach((file) => {\n var jsonfile = path.join(servicespath, file, 'service.json')\n data = fs.readFileSync(jsonfile)\n var serviceinfo = JSON.parse(data)\n services[serviceinfo.name] = serviceinfo\n services[serviceinfo.name].iconpath = path.join(app.getAppPath(), 'services', serviceinfo.name, 'icon.png').replace(/\\\\/g, \"/\")\n if (!serviceinfo.appservice) {\n config.set(serviceinfo.name + '.name', serviceinfo.name)\n }\n })\n\n // Read user-added services\n servicespath = path.join(app.getPath('userData'), 'services')\n \n if(!fs.existsSync(servicespath)) {\n fs.mkdirSync(servicespath)\n }\n \n files = fs.readdirSync(servicespath)\n console.log(servicespath + ' files: ' + files)\n\n files.forEach((file) => {\n var jsonfile = path.join(servicespath, file, 'service.json')\n data = fs.readFileSync(jsonfile)\n var serviceinfo = JSON.parse(data)\n services[serviceinfo.name] = serviceinfo\n services[serviceinfo.name].iconpath = path.join(app.getPath('userData'), 'services', serviceinfo.name, 'icon.png').replace(/\\\\/g, \"/\")\n \n if (!serviceinfo.appservice) {\n config.set(serviceinfo.name + '.name', serviceinfo.name)\n }\n })\n}",
"function add( name, parent, service ) {\n\t\t\t\n\t\t\t// parent is optional, and therefore might actually be the service object\n\t\t\tif( $.isPlainObject( parent ) ) {\n\t\t\t\tservice = parent;\n\t\t\t\tparent = false;\n\t\t\t} \n\t\t\t\n\t\t\t// Parent needs to be the name of a service that exists\n\t\t\tif( $.type( parent ) === \"string\" && services[parent] ) {\n\t\t\t\tparent = services[parent];\n\t\t\t} else {\n\t\t\t\tparent = {};\n\t\t\t}\n\t\t\t\n\t\t\t// Can't add what you can't add.\n\t\t\tif( service && $.isPlainObject( service ) ) {\n\t\t\t\tservices[name] = $.extend({}, masterService, parent, service);\n\t\t\t}\n\t\t\t\n\t\t\treturn !!services[name];\t\t\t\n\t\t}",
"function addService() {\n\tvar currentUser = getCurrentUser();\n\tconsole.log(\"Adding Service\");\n\n\tvar description = $('input#addDescriptionField').val();\n\tvar cost = $('input#addCostField').val();\n\n\tconsole.log(description);\n\tconsole.log(cost);\n\n\tcreateService(currentUser.UserID, description, cost);\n\tsetTimeout(function() {\n\t\talert(\"Service has been created.\");\n\t\t$.mobile.back();\n\t}, 500);\n\n}",
"async register(opts) {\n if (typeof opts === \"string\") {\n opts = { name: opts };\n }\n\n opts = utils.normalizeKeys(opts);\n opts = utils.defaults(opts, this.consul._defaults);\n\n const req = {\n name: \"agent.service.register\",\n path: \"/agent/service/register\",\n type: \"json\",\n body: {},\n };\n\n if (!opts.name) {\n throw this.consul._err(errors.Validation(\"name required\"), req);\n }\n\n try {\n req.body = utils.createService(opts);\n } catch (err) {\n throw this.consul._err(errors.Validation(err.message), req);\n }\n\n utils.options(req, opts);\n\n return await this.consul._put(req, utils.empty);\n }",
"static setService(req, res, next) {\r\n if (!req.hasNewService) {\r\n log.info(`Instantiate new CoreService; attach to req`);\r\n req.hasNewService = true;\r\n _service = new CoreService();\r\n }\r\n return next();\r\n }",
"function addUserService(serviceinfo) {\n var servicepath = path.join(app.getPath('userData'), 'services', serviceinfo.name)\n fs.mkdirSync(servicepath)\n var data = JSON.stringify(serviceinfo)\n fs.writeFileSync(path.join(servicepath, 'service.json'), data)\n let buff = new Buffer(serviceinfo.icon64, 'base64')\n fs.writeFileSync(path.join(servicepath, 'icon.png'), buff)\n}",
"static addApiServiceSpec(servicename,spec){Env.api.services[servicename]=spec}",
"registerServices() {\n app.logger.info(` - Registering ${Object.keys(app.service).length} services`);\n _.each(app.service, (Service, key) => {\n let ServiceProvider = new Service;\n\n if (!ServiceProvider.registerService()) {\n //\n }\n\n app.service[key] = ServiceProvider;\n });\n }",
"function addServices(concepto, descripcion,precio,duracion){\n var con = $(concepto).val();\n var des = $(descripcion).val();\n var pre = $(precio).val();\n var dur = $(duracion+ \" :selected\").val();\n var otroID = $(\"#idDireccion\").val();\n //post para el envio de la informacion\n if( con != \"\" && des != \"\" && pre != \"\" && dur != \"time\" ){\n $.post('/addServices',{\n concepto:con,\n descripcion: des,\n precio: pre,\n duracion: dur,\n otroID: otroID\n },function(data){\n if(data == true){\n maquetaServices();\n $(\"#exitoAgregado\").removeClass('hidden');\n $(concepto).html('');\n $(descripcion).html('');\n $(precio).html('');\n }else{\n console.log(\"Entro aqui\");\n $(\"#exitoNoAgregado\").removeClass('hidden');\n }\n });\n }\n}",
"registerServiceName(service_name){\r\n if(!service_name){\r\n throw new TypeError('service_name is not defined')\r\n }\r\n\r\n return this.service_name = service_name;\r\n }",
"function service(target) {\n //doing nothing here;\n target['@RPC.Service'] = {};\n }",
"addService(args) {\n let { name, service, options } = args\n\n this.add(\n name,\n (_, filterArgs) => {\n _.push(service(filterArgs))\n return _\n },\n options\n )\n }",
"function makeService(url, id){\r\n var service = new ArcGISDynamicMapServiceLayer(url, {\"imageParameters\": imageParameters});\r\n service.suspend();\r\n layers.push(service);\r\n identifyTasks[url] = new IdentifyTask(url);\r\n servicesById[id] = service;\r\n on(query(\"#\"+id+\" input\"), \"click\", function(){updateLayerVisibility(service,this.parentNode.parentNode)});\r\n service.on(\"load\",function(e){serviceDescriptions[id] = e.layer.description})\r\n }",
"registerService(service$$1){const valueTypes=service$$1.getValueTypes();valueTypes.forEach(valueType=>{if(this._serviceRegistry.has(valueType)){throw getLdsInternalError(\"SERVICE_ALREADY_REGISTERED\",\"A service has already been registered for valueType: \"+service$$1.getValueTypes().toString(),true);}this._serviceRegistry.set(valueType,service$$1);// Register any affected key handler.\n const affectedKeyHandler=service$$1.getAffectedKeyHandler();if(affectedKeyHandler){this.registerAffectedKeyHandler(valueType,affectedKeyHandler);}});}",
"function insertDataService(){\n//INSERT SERVICE\n\tinsertDocumentTest(\"service\",{name:\"Banho\",price:30, description:\"Banho em animais\", picture:\"./src/images/services/shower.png\", scheduledAmount:0, priority:1});\n\tinsertDocumentTest(\"service\",{name:\"Tosa\",price:40, description:\"Tosa em animais\", picture:\"./src/images/services/cut.png\", scheduledAmount:0, priority:2});\n\tinsertDocumentTest(\"service\",{name:\"Veterinário\",price:35, description:\"Veterinário para animais\", picture:\"./src/images/services/vet.png\", scheduledAmount:0, priority:3});\n\tinsertDocumentTest(\"service\",{name:\"Leva e traz\",price:10, description:\"Leva e traz animais\", picture:\"./src/images/services/van.png\", scheduledAmount:0, priority:4});\n}",
"addToCart(currentProdotto) {\r\n this.cartService.create(currentProdotto);\r\n window.alert('Prodotto aggiunto al carrello!');\r\n }",
"addToCart(currentProdotto) {\r\n this.cartService.create(currentProdotto);\r\n window.alert('Prodotto aggiunto al carrello!');\r\n }",
"function addServiceInPkgInfo(next) {\n log.verbose(\"addServiceInPkgInfo\");\n if (!this.rom) {\n const filename = path.join(this.packageDir, \"packageinfo.json\");\n let pkginfo, validServiceCount;\n try {\n const data = fs.readFileSync(filename);\n validServiceCount = 0;\n log.verbose(\"PACKAGEINFO >>\" + data + \"<<\");\n pkginfo = JSON.parse(data);\n } catch (err) {\n console.error(err);\n setImmediate(next, err);\n }\n this.services.filter(function(s) {\n return s.valid;\n }).forEach(function(service) {\n getPkgServiceNames(service.serviceInfo).forEach(function(serviceName) {\n this.pkgServiceNames.push(serviceName);\n validServiceCount++;\n }.bind(this));\n }.bind(this));\n\n if (validServiceCount > 0) {\n pkginfo.services = this.pkgServiceNames;\n const data = JSON.stringify(pkginfo, null, 2) + \"\\n\";\n log.verbose(\"Modified package.json: \" + data);\n fs.writeFile(path.join(this.packageDir, \"packageinfo.json\"), data, next);\n } else {\n setImmediate(next);\n }\n } else {\n setImmediate(next);\n }\n }",
"function service(target) {\n //doing nothing here;\n target['@RPC.Service'] = {};\n}",
"function extraccionARealizar() {\n if ($scope.showElemAusente && $scope.showExtraccion && $scope.showExtraccionRealizada) {\n var faceId = null, serviceId = 3;\n var x = $(\"#\" + $scope.tratamientoPiezaId);\n x.removeClass('red');\n x.addClass('blue');\n $scope.tratamientoPieza = 'X';\n $scope.$apply(); \n addTempService(faceId, serviceId);\n $scope.showExtraccion = false;\n };\n }",
"register(name, definition, dependencies) {\n this._services.set(name, {definition, dependencies});\n }",
"function SetServicio(data)\n{\n var servicio = new Servicio();\n \n servicio.ServicioId = data.ServicioId;\n servicio.Nombre = data.Nombre;\n servicio.CostoUnidad = parseFloat(data.CostoUnidad);\n servicio.PrecioVenta = parseFloat(data.PrecioVenta);\n \n if(data.Activo == \"1\")\n {\n servicio.Activo = true;\n }\n else\n {\n servicio.Activo = false;\n }\n \n if(data.Obligatorio == \"1\")\n {\n servicio.Obligatorio = true;\n }\n else\n {\n servicio.Obligatorio = false;\n }\n \n \n return servicio;\n}",
"function register(service) {\n if (undefined !== 'production') {\n assert.isTrue(isObject(service), `Invalid service declaration, ${service}: service must be an object`);\n }\n\n for (let i = 0; i < hooks.length; ++i) {\n const hookName = hooks[i];\n\n if (hookName in service) {\n let l = Services[hookName];\n\n if (isUndefined$3(l)) {\n Services[hookName] = l = [];\n }\n\n ArrayPush$2.call(l, service[hookName]);\n }\n }\n}",
"function ws_createService( service, callback ){\n\tvar request = new Object();\n request.requestId = genRequestID();\n request.msg = \"createService\";\n //request.provider = service.provider;\n request.name = service.name;\n request.path = service.path;\n request.shpath = service.shpath;\n request.preshpath = service.preshpath;\n request.postshpath = service.postshpath;\n request.image = service.image;\n\t// stagin folders\n\trequest.stageinDirs = service.stageinDirs;\n\trequest.stageoutDirs = service.stageoutDirs;\n\t\n\t// stagout folders\n //request.producer = service.producer;\n if( service.status == true ){\n \trequest.status = true;\n }\n //request.icon = ( service.icon && service.icon.name ) ? service.icon.name : \"\";\n if ( service.iconfile ) {\n \t//console.log(\" service.iconfile = \");\n \t//console.log( service.iconfile );\n \t//alert(\"ws_createService\");\n \trequest.icon = service.iconfile.name;\n }\n\trequest.maxElapsedTime = service.maxElapsedTime;\n\trequest.numberOfNodes = service.noNodes;\n\trequest.description = service.descript;\n request.params = {};\n request.params.items = [];\n console.log( \"service = \" );\n console.log( service );\n $.each( service.params, function (index) {\n \trequest.params.items.push( \n \t\t\t{ \n \t\t\t\t\"id\" : this.id,\n \t\t\t\t\"name\" : this.name, \n \t\t\t\t\"type\" : this.type, \n \t\t\t\t\"defaultValue\" : this.defaultValue,\n \t\t\t\t\"isRequired\" : this.isRequired,\n \t\t\t\t\"isOutput\" : this.isOutput,\n \t\t\t\t\"prefix\" : this.prefix,\n \t\t\t\t\"description\" : this.descript,\n \t\t\t\t} );\n });\n send(request, callback);\n}"
]
| [
"0.70349646",
"0.6497937",
"0.6412341",
"0.63957417",
"0.61807615",
"0.6089338",
"0.6018023",
"0.59645915",
"0.5893071",
"0.5889909",
"0.58460647",
"0.5816108",
"0.5773784",
"0.57416844",
"0.5737744",
"0.572951",
"0.5710991",
"0.57005084",
"0.5670962",
"0.56590587",
"0.56270576",
"0.5511533",
"0.5511533",
"0.5498252",
"0.5441208",
"0.54388994",
"0.5391492",
"0.5364619",
"0.53644264",
"0.53520495"
]
| 0.67210513 | 1 |
Eliminar un servicio qu presta | function eliminarServicio() {
mostrarMensaje(2, perfil.etiquetas.lbMsgDeseaEliminar, elimina);
function elimina(btnPresionado) {
if (btnPresionado == 'ok') {
Ext.Ajax.request({
url: 'eliminarservicio',
method: 'POST',
params: {idservicio: sm.getSelected().data.idservicio},
callback: function(options, success, response) {
responseData = Ext.decode(response.responseText);
if (responseData.codMsg == 1) {
mostrarMensaje(responseData.codMsg, perfil.etiquetas.lbMsgDelServ);
stGpServicio.reload();
sm.clearSelections();
btnModificar.disable();
//btnEliminar.disable();
}
if (responseData.codMsg == 3)
mostrarMensaje(responseData.codMsg, responseData.mensaje);
}
});
}
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function eliminarServicioLocalStorage(servicio){\n let serviciosLS;\n // obtenemos el arreglo de servicios\n serviciosLS = obtenerServiciosLocalStorage();\n // iteramos comparando el ID del servicio con los del LS\n serviciosLS.forEach(function(servicioLS, index){\n if(servicioLS.id === servicio){\n serviciosLS.splice(index, 1);\n }\n });\n // Añadimos el arreglo actual\n localStorage.setItem('servicios', JSON.stringify(serviciosLS));\n}",
"DELETE_SERVICE(state, service_id) {\n let serv = state.services.filter(s => s.id != service_id);\n state.services = serv;\n }",
"function eliminarCliente(seleccionado) {\n delete_registrer(seleccionado, 'escenario/eliminar')\n}",
"function eliminarPlatoCesta(idCesta) {\n $.ajax({\n url: `/cesta/${idCesta}`,\n type: \"DELETE\",\n contentType: \"application/json\",\n complete: function (xhr, status) {\n let error = status !== \"success\"\n let data = {\n message: xhr.responseJSON.message,\n error: error\n }\n\n imprimirResultado(data, null, true)\n\n obtenerCesta().then(()=>{\n document.querySelector(`#itemCesta${idCesta}`).remove()\n imprimirTotalPedido()\n imprimirContadorCesta()\n if (cesta.length === 0) {imprimirCesta()}\n })\n }\n })\n}",
"remover(){\r\n axios.delete(`http://localhost:3003/api/tarefas/?sort=-createdAt`).then(resp =>{\r\n this.buscaTarefas()\r\n })\r\n }",
"eliminarCliente(cliente) {\n axios.delete(this.uri + '/' + cliente.id).then(() => {\n this.obtenerClientes();\n this.btnCancelar();\n this.accion = 'eliminarE';\n })\n }",
"eliminarIngresoInsumo(id) {\n return axios.delete(`${API_URL}/ingreso_insumo/${id}`);\n }",
"function eliminarElemento(event){\n event.preventDefault();\n let padre = event.target.parentNode.parentNode;\n let idElement = padre.firstElementChild.getAttribute(\"data-id\");\n let typeElement = padre.firstElementChild.getAttribute(\"data-type\");\n $.ajax({\n type: \"DELETE\",\n url: '/api/v1/' + typeElement + '/' + idElement,\n headers: {\"Authorization\": logeado},\n // dataType: 'json',\n success: function (data) {\n //eliminar relaciones\n }\n })\n padre.remove();\n}",
"function supprimerServices() {\n\tvar url = \"http://localhost/?method=deleteAllServices\";\n\n\t$.ajax({\n\t\turl: url,\n\t\tdatatype: 'json',\n\t\tsuccess: function(){\n\t\t\tadminDisplayServices(0);\n\t\t}\n\t});\n}",
"function eliminar_todo(){\n ELIMINAR(\"seccion_cuenta\");\n ELIMINAR(\"seccion_siguiendo\");\n ELIMINAR(\"seccion_seguidores\");\n ELIMINAR(\"seccion_buscar\");\n ELIMINAR(\"seccion_misrutas\");\n ELIMINAR(\"seccion_ruta\");\n\n}",
"function eliminarVuelo() {\r\n alert(`Consulta la consola para conocer el Id del vuelo a eliminar?`);\r\n\r\n eliminar = prompt(`Introduce el Id del vuelo a eliminar.`);\r\n alert(\r\n \"Se eliminará el vuelo: \" +\r\n flights[eliminar].from +\r\n \"-\" +\r\n flights[eliminar].to\r\n );\r\n flights.splice(eliminar, 1);\r\n console.log(flights);\r\n }",
"function removeTarefa() {\n // Remove tarefa e executa callback em seguida\n api.delete(`/${props.id}/`).then(props.aoRemover);\n }",
"function Eliminar(){\n console.log(\"Se va eliminar el dashboard seleccionado\");\n\t\tServicio_Dashboard.Actualizar(\n\t\t\tdashboard.id,//ID del dashboard\n\t\t\t{activo:'false'},//El valor a cambiar es la columna activo a false\n\t\t\tfunction(data){//Éxito!\n\t\t\t\tconsole.log(\"Se han eliminadi los datos de forma éxitosa\");\n\t\t\t\t$scope.Constructor();//Recargamos el array\n\t\t\t},\n\t\t\tfunction(data){//Fracaso\n\t\t\t\tconsole.log(\"Se ha generado un error al intentar eliminar los datos del servidor\");\n\t\t\t\tconsole.log(data);\n\t\t\t}\n\t\t); \n }",
"function removeTramite ( oficina, key ) {\n swal({\n title: '¿Esta seguro?',\n text: \"Realmente desea eliminar el tramite\",\n type: 'warning',\n showCancelButton: true,\n confirmButtonColor: '#3085d6',\n cancelButtonColor: '#d33',\n confirmButtonText: 'Sí',\n cancelButtonText: 'No'\n }).then(function () {\n switch ( oficina ) {\n case \"Registro y Control\":\n fire.ref( 'rh/tramites/registroyControl/' + key ).remove().then(function(){\n swal(\n '¡Borrado!',\n 'El tramite ha sido borrado',\n 'success'\n )\n });\n break;\n \n case \"Servicios al Personal\":\n fire.ref( 'rh/tramites/serviciosalPersonal/' + key ).remove().then(function(){\n swal(\n '¡Borrado!',\n 'El tramite ha sido borrado',\n 'success'\n )\n });\n break;\n }\n\n });\n }",
"eliminarAplicacion({\n item\n }) {\n let url = `https://gestion-movilidad-api.herokuapp.com/aplicacion/${item.id}`\n\n this.$swal.fire({\n title: \"Precaución\",\n text: \"¿Desea eliminar la aplicación?\",\n showCancelButton: true,\n confirmButtonText: 'Si, Eliminar',\n cancelButtonText: 'No, Cancelar',\n reverseButtons: true\n }).then(r => {\n if (r.value) {\n this.$axios.delete(url, this.datosFormulario()).then(respuesta => {\n this.cargarLista();\n }).catch(error => {});\n this.$swal.fire({\n title: 'Eliminada!',\n text: 'La aplicación ha sido eliminada correctamente.',\n type: 'success',\n timer: 3000\n })\n } else {\n this.$swal.fire({\n title: 'Cancelada',\n text: 'La operación ha sido cancelada',\n type: 'error',\n timer: 3000\n })\n }\n });\n\n }",
"function eliminarProducto(id) {\n let productoAEliminar = carrito.find(el => el.id == id)\n let indice = carrito.indexOf(productoAEliminar)\n carrito.splice(indice, 1)\n localStorage.carrito = JSON.stringify(carrito)\n actualizarCarrito()\n calcularTotal()\n}",
"function removeTudo(tipo){\n \n switch(tipo){\n case 'removeTodosServicos':\n $('.linhaservico').remove();\n break;\n case 'removeTodosSoftware':\n $('.linhasoftware').remove();\n break;\n case 'removeTodosHardwares':\n $('.linhahardware').remove();\n break;\n default:\n break; \n }\n }",
"function eliminarPlato (id) {\n var correo = $('#correoS').val()\n\n var WSurl3 = 'http://serviciosnullpointer.azurewebsites.net/WSPedido.svc/ModificarPedido?correo=' + correo + '&plato=' + id;\n\n var req1 = $.ajax({\n url: WSurl3,\n contentType:'text/json; charset:UTF-8',\n dataType: \"jsonp\",\n success: function(datos) {platoEliminado()},\n error: function(x, t, m) {MensajeError(x, t, m)}\n });\n}",
"function eliminarCarrito(e) {\n console.log(e.target.id);\n let posicion = carrito.findIndex(p => p.id == e.target.id);\n carrito.splice(posicion, 1);\n console.log(carrito);\n // GENERAR NUEVAMENTE INTERFAZ\n carritoUI(carrito);\n // GUARDAR EN STORAGE EL NUEVO CARRITO\n localStorage.setItem(\"carrito\", JSON.stringify(carrito));\n}",
"destroy(req, res) {\n Service.destroy({\n where: {\n id: req.params.id\n }\n })\n .then(function () {\n res.status(200).json({ message: \"Reklamation raderades\" });\n })\n .catch(function (error) {\n res.status(500).json({ error: \"Kan inte radera reklamation\" });\n })\n }",
"deleteID(req,res){ \n var produtos = [\n {'id': 1 ,'nome': 'Iphone','description': 'Iphone geração 10','quantidade':2},\n {'id': 2 ,'nome': 'Notebook','description': 'notebook core i7, 8 GB','quantidade':1},\n {'id': 3 ,'name': 'Samsung','description': 'Descrição do produto aqui','quantidade':1}\n ];\n var id = req.params.id;\n var ret = \"\" ;\n var removido = false;\n if(!req.params.id){\n ret = 'Produto inválido!';\n }else{\n for(var i =0 ; i < produtos.length; i++){ \n if(id==produtos[i].id){\n produtos.splice(i,1);\n i-- \n removido =true; // indica que o produto foi removido \n ret ='Produto removido do carr com sucesso!';\n }\n }\n\n if(removido==true){\n ret ='Produto removido com sucesso!'; \n }else{\n ret ='Nenhum produto encontrado!'; \n }\n } \n res.json({ret:ret});\n}",
"function eliminarProd(event, idx)\n{\n event.preventDefault();\n //console.log('ELIMINAR EYTER');\n detalles[idx].estado = 0;\n detalles.splice(idx, 1);//removemos el indice del objeto\n listarDetalles();\n}",
"deleteProdotto() {\r\n if (this.currentProdotto.key) {\r\n this.prodottoService.delete(this.currentProdotto.key)\r\n .then(() => {\r\n window.alert('Prodotto eliminato!');\r\n window.location.reload();\r\n })\r\n .catch(err => console.log(err));\r\n }\r\n }",
"function eliminarDetalleProm(indice){\n\t//console.log($(\".idPromo\"+indice));\n\t$(\".idPromo\"+indice).remove();\n\tcalculaTotalesSalida();\n\tdetalles=detalles-1;\n\tevaluarSalida();\n}",
"deletePessoa() {\n const formData = app.toFormData(app.currentPessoa);\n axios.post(\"http://localhost/Projeto%20DG%20Solutions/system.php?action=delete\", 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 }",
"async function remover(id) {\n await api.delete(`dados/${id}`)\n }",
"function eliminar(boton) {\n boton.parentNode.parentNode.remove();\n var index = productos.indexOf(boton.parentNode.parentNode.querySelector('.nombre').innerText);\n console.log(index);\n if (index !== -1) {\n productos.splice(index, 1);\n }\n calcularTotal();\n}",
"eliminarEvento(evento) {\n // console.log(evento);\n this.mServ.elminarElemento(evento.eid, this.tipoDato).subscribe(resp => {\n // si todo esta bien\n sweetalert2__WEBPACK_IMPORTED_MODULE_2___default.a.fire({\n icon: 'success',\n title: resp.msg,\n showConfirmButton: false,\n timer: 1500\n });\n this.dameEventos();\n }, (err) => {\n // si ocurre un error\n sweetalert2__WEBPACK_IMPORTED_MODULE_2___default.a.fire({\n title: 'Error',\n text: err.error.msg,\n icon: 'error'\n });\n });\n }",
"async destroy({auth,params,response}){\n let{id}=params\n let user = await User.findOrFail(auth.user.id)\n const service = await Service.findOrFail(id)\n if(service.client==user.id){\n service.client=null\n await service.save()\n return response.status(200).json(service)\n }\n return response.status(400).send({'msg':'Service not client'}); \n \n }",
"function eliminarPrenda(e) {\n e.preventDefault();\n if(e.target.classList.contains('borrar-curso') ) {\n // e.target.parentElement.parentElement.remove();\n const prendaId = e.target.getAttribute('data-id')\n \n // Eliminar del arreglo del carrito\n articulosCarrito = articulosCarrito.filter(prenda => {\n if(prenda.id === prendaId){\n if(prenda.cantidad > 1){\n prenda.cantidad--;\n return prenda;\n }else{\n delete prenda;\n }\n }else{\n return prenda;\n }\n });\n\n carritoHTML();\n }\n}"
]
| [
"0.71138006",
"0.70236236",
"0.6882087",
"0.68239105",
"0.6820071",
"0.6728283",
"0.67099303",
"0.6703508",
"0.66938317",
"0.6648827",
"0.66248053",
"0.66029334",
"0.6571089",
"0.654071",
"0.6510583",
"0.6456987",
"0.64400053",
"0.6411762",
"0.64049745",
"0.6401741",
"0.6389608",
"0.6381558",
"0.63797146",
"0.6378007",
"0.6366655",
"0.6360741",
"0.6351265",
"0.63247305",
"0.63222426",
"0.63181394"
]
| 0.7070905 | 1 |
infinite slider only works with 3+ slides, so if less than 3 we need to duplicate | function duplicateSlides(slider, slides) {
if(slides.length < 3) {
// Duplicate slider content
slider.append(slider.html());
// Re count slides
var slidesRecount = jQuery('.slider .slider__slide');
// Recursive function until more than 3 slides
duplicateSlides(slider, slidesRecount);
} else {
// Remove active class if any already added
slides.removeClass('slider__slide--active');
// Only add active class to first slide once recursion has finished
jQuery(slides[0]).addClass('slider__slide--active');
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function slide_carousel() {\n var site_width = jQuery(window).width(),\n site_height = jQuery(window).height(),\n sliderList = jQuery('.pm_gallery.effect_slide'),\n slide_item = jQuery(sliderList).find('li');\n slide_item.width(site_width - 80);\n var increment = jQuery(sliderList).children().outerWidth(true),\n elmnts = jQuery(sliderList).children(),\n numElmts = elmnts.length,\n sizeFirstElmnt = increment,\n shownInViewport = Math.round(jQuery(window).width() / sizeFirstElmnt),\n firstElementOnViewPort = 1,\n isAnimating = false,\n next_button = jQuery('.pm_next_slide_button'),\n prev_button = jQuery('.pm_prev_slide_button'),\n i;\n\n if (elmnts) {\n for (i = 0; i < shownInViewport; i++) {\n jQuery(sliderList).css('width', (numElmts + shownInViewport) * increment + increment + \"px\");\n jQuery(sliderList).append(jQuery(elmnts[i]).clone().addClass('cloned_slide'));\n }\n\n slide_item.first().addClass('visible_slide'); // Thumbnails\n\n var current_item = jQuery('.pm_gallery.effect_slide li.visible_slide'),\n next_thumb_back = current_item.next().attr('data-thumbnail'),\n prev_thumb_back = slide_item.last().attr('data-thumbnail');\n next_button.find('.pm_next_thumb_cont').css({\n 'background-image': 'url(' + next_thumb_back + ')'\n });\n prev_button.find('.pm_prev_thumb_cont').css({\n 'background-image': 'url(' + prev_thumb_back + ')'\n }); // Navigation\n\n next_button.on('click', function () {\n slide_carousel_next_slide(isAnimating, firstElementOnViewPort, numElmts, sliderList, increment);\n\n if (firstElementOnViewPort > numElmts) {\n firstElementOnViewPort = 2;\n } else {\n firstElementOnViewPort++;\n }\n });\n prev_button.on('click', function () {\n slide_carousel_prev_slide(isAnimating, firstElementOnViewPort, numElmts, sliderList, increment, sizeFirstElmnt);\n\n if (firstElementOnViewPort == 1) {\n firstElementOnViewPort = numElmts;\n } else {\n firstElementOnViewPort--;\n }\n });\n }\n} // Next Slide //",
"function sliderMultipleItems(){\n $('.multiple-items').slick({\n\t dots: true,\n infinite: true,\n speed: 500,\n slidesToShow: 4,\n slidesToScroll: 4,\n arrows: false,\n autoplay: true,\n pauseOnDotsHover: true,\n autoplaySpeed: 5000,\n responsive: [\n {\n breakpoint: 1100,\n settings: {\n slidesToShow: 3,\n slidesToScroll: 3,\n infinite: true,\n dots: true\n }\n },\n {\n breakpoint: 830,\n settings: {\n slidesToShow: 2,\n slidesToScroll: 2,\n infinite: true,\n dots: true\n }\n },\n {\n breakpoint: 550,\n settings: {\n sildesToShow: 1,\n slidesToScroll: 1,\n infinite: true,\n dots: true\n }\n },\n {\n breakpoint: 480,\n settings: {\n slidesToShow: 1,\n slidesToScroll: 1,\n infinite: true,\n dots: true\n }\n }\n ]\n\t});\n}",
"initSlides_() {\n let slideNumber = this.plugins.hash.constructor.getSlideNumber(); // Not valid\n\n if (slideNumber === null || slideNumber >= this.maxSlide_) {\n slideNumber = 0;\n } // Keeping the order\n\n\n if (slideNumber !== 0) {\n let i = 0;\n\n while (i < slideNumber) {\n this.slides[i].moveAfterLast();\n i++;\n }\n }\n\n this.goToSlide(slideNumber);\n }",
"function listing_post_format_image_slider(i) {\n var listing_id = '#' + i,\n slider_container = jQuery(listing_id),\n elements = jQuery(slider_container).children(),\n number_of_elements = elements.length,\n slide_item = jQuery(slider_container).find('li'),\n intervalID,\n next_button = jQuery(slider_container).parent().parent().find('.pm_prev_image_slide_button'),\n prev_button = jQuery(\".pm_media_output_cont_wrapper .pm_prev_slide_button\"),\n current_item,\n slide_number;\n slide_item.first().addClass(\"visible\"); // Navigation\n\n slider_container.parent().parent().find('.pm_prev_image_slide_button').on('click', function () {\n current_item = jQuery(slider_container).find('li.visible');\n slide_number = current_item.attr('data-number');\n\n if (slide_number == \"1\") {\n jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\");\n slide_item.last().addClass('visible');\n } else {\n jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\").prev().addClass(\"visible\");\n }\n });\n slider_container.parent().parent().find('.pm_next_image_slide_button').on('click', function () {\n current_item = jQuery(slider_container).find('li.visible');\n slide_number = current_item.attr('data-number');\n\n if (slide_number < number_of_elements) {\n jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\").next().addClass(\"visible\");\n } else {\n jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\");\n slide_item.first().addClass(\"visible\");\n }\n });\n} ////////////////////////////////////////////",
"function blog_listing_post_format_image_slider(i) {\n var listing_id = '#' + i,\n slider_container = jQuery(listing_id),\n elements = jQuery(slider_container).children(),\n number_of_elements = elements.length,\n slide_item = jQuery(slider_container).find('li'),\n intervalID,\n next_button = jQuery(slider_container).parent().parent().find('.pm_prev_image_slide_button'),\n prev_button = jQuery(\".pm_media_output_cont_wrapper .pm_prev_slide_button\"),\n current_item,\n slide_number;\n slide_item.first().addClass(\"visible\"); // Navigation\n\n slider_container.parent().parent().find('.pm_prev_image_slide_button').on('click', function () {\n current_item = jQuery(slider_container).find('li.visible');\n slide_number = current_item.attr('data-number');\n\n if (slide_number == \"1\") {\n jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\");\n slide_item.last().addClass('visible');\n } else {\n jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\").prev().addClass(\"visible\");\n }\n });\n slider_container.parent().parent().find('.pm_next_image_slide_button').on('click', function () {\n current_item = jQuery(slider_container).find('li.visible');\n slide_number = current_item.attr('data-number');\n\n if (slide_number < number_of_elements) {\n jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\").next().addClass(\"visible\");\n } else {\n jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\");\n slide_item.first().addClass(\"visible\");\n }\n });\n} /////////////////////////////////////////////////",
"function blog_listing_carousel_tape(i) {\n var site_width = jQuery(window).width(),\n site_height = jQuery(window).height(),\n header_height = jQuery('header').height(),\n slider_height = site_height - header_height - i,\n slider_container = jQuery('.pm_blog_listing_tape_container'),\n slider_list = jQuery(slider_container).find('.pm_gallery'),\n elements = jQuery(slider_list).children(),\n number_of_elements = elements.length,\n gallery_item = slider_list.find('.pm_gallery_item'),\n gallery_image_width = jQuery(gallery_item).find('img').width();\n\n if (site_width < 737) {\n slider_height = site_height - header_height - 60;\n }\n\n slider_container.height(slider_height).css('margin-top', header_height);\n slider_list.height(slider_height * 0.91).css({\n 'margin-top': slider_height * 0.044,\n 'margin-bottom': slider_height * 0.044\n });\n gallery_item.width(gallery_image_width);\n gallery_item.find('.pm_media_output_cont_wrapper').width(gallery_image_width);\n var current_item;\n current_item = jQuery('#item_1').addClass('current_item');\n gallery_item.last().addClass('prev_item').prev().addClass('prev_item_2');\n current_item.next().addClass('next_item').next().addClass('next_item_2');\n blog_listing_tape_position();\n} /////////////////////////////////////////////",
"function slide_carousel(){var site_width=jQuery(window).width(),site_height=jQuery(window).height(),sliderList=jQuery('.pm_gallery.effect_slide'),slide_item=jQuery(sliderList).find('li');slide_item.width(site_width-80);var increment=jQuery(sliderList).children().outerWidth(true),elmnts=jQuery(sliderList).children(),numElmts=elmnts.length,sizeFirstElmnt=increment,shownInViewport=Math.round(jQuery(window).width()/sizeFirstElmnt),firstElementOnViewPort=1,isAnimating=false,next_button=jQuery('.pm_next_slide_button'),prev_button=jQuery('.pm_prev_slide_button'),i;if(elmnts){for(i=0;i<shownInViewport;i++){jQuery(sliderList).css('width',(numElmts+shownInViewport)*increment+increment+\"px\");jQuery(sliderList).append(jQuery(elmnts[i]).clone().addClass('cloned_slide'));}slide_item.first().addClass('visible_slide');// Thumbnails\nvar current_item=jQuery('.pm_gallery.effect_slide li.visible_slide'),next_thumb_back=current_item.next().attr('data-thumbnail'),prev_thumb_back=slide_item.last().attr('data-thumbnail');next_button.find('.pm_next_thumb_cont').css({'background-image':'url('+next_thumb_back+')'});prev_button.find('.pm_prev_thumb_cont').css({'background-image':'url('+prev_thumb_back+')'});// Navigation\nnext_button.on('click',function(){slide_carousel_next_slide(isAnimating,firstElementOnViewPort,numElmts,sliderList,increment);if(firstElementOnViewPort>numElmts){firstElementOnViewPort=2;}else{firstElementOnViewPort++;}});prev_button.on('click',function(){slide_carousel_prev_slide(isAnimating,firstElementOnViewPort,numElmts,sliderList,increment,sizeFirstElmnt);if(firstElementOnViewPort==1){firstElementOnViewPort=numElmts;}else{firstElementOnViewPort--;}});}}// Next Slide //",
"function slide_carousel(){var site_width=jQuery(window).width(),site_height=jQuery(window).height(),sliderList=jQuery('.pm_gallery.effect_slide'),slide_item=jQuery(sliderList).find('li');slide_item.width(site_width-80);var increment=jQuery(sliderList).children().outerWidth(true),elmnts=jQuery(sliderList).children(),numElmts=elmnts.length,sizeFirstElmnt=increment,shownInViewport=Math.round(jQuery(window).width()/sizeFirstElmnt),firstElementOnViewPort=1,isAnimating=false,next_button=jQuery('.pm_next_slide_button'),prev_button=jQuery('.pm_prev_slide_button'),i;if(elmnts){for(i=0;i<shownInViewport;i++){jQuery(sliderList).css('width',(numElmts+shownInViewport)*increment+increment+\"px\");jQuery(sliderList).append(jQuery(elmnts[i]).clone().addClass('cloned_slide'));}slide_item.first().addClass('visible_slide');// Thumbnails\nvar current_item=jQuery('.pm_gallery.effect_slide li.visible_slide'),next_thumb_back=current_item.next().attr('data-thumbnail'),prev_thumb_back=slide_item.last().attr('data-thumbnail');next_button.find('.pm_next_thumb_cont').css({'background-image':'url('+next_thumb_back+')'});prev_button.find('.pm_prev_thumb_cont').css({'background-image':'url('+prev_thumb_back+')'});// Navigation\nnext_button.on('click',function(){slide_carousel_next_slide(isAnimating,firstElementOnViewPort,numElmts,sliderList,increment);if(firstElementOnViewPort>numElmts){firstElementOnViewPort=2;}else{firstElementOnViewPort++;}});prev_button.on('click',function(){slide_carousel_prev_slide(isAnimating,firstElementOnViewPort,numElmts,sliderList,increment,sizeFirstElmnt);if(firstElementOnViewPort==1){firstElementOnViewPort=numElmts;}else{firstElementOnViewPort--;}});}}// Next Slide //",
"function loadimages() {\n var slideHtml = '';\n for (i = 0; i < 6; i++) {\n var j = (count * 6 + i) % (imgList.length);\n if (i == 0) {\n slideHtml += '<div class=\"item active\">';\n } else {\n slideHtml += '<div class=\"item\">';\n\n }\n\n slideHtml +=\n ' <img src=\"http://static.panoramio.com/photos/medium/' + imgList[j].id + '.jpg\" alt=\"junjunguo.com\">' +\n ' <div class=\"carousel-caption\">' +\n ' <p>' + imgList[j].title + '</p>' +\n ' </div>' +\n '</div>';\n }\n //$(\"#my-carousel\").carousel(\"pause\").removeData();\n document.getElementById(\"my-slides\").innerHTML = slideHtml;\n count++;\n}",
"function fixLessSlides(slideCount, slides, index) {\n // If window width is less than 992\n if (window.matchMedia(\"(max-width: 991px)\").matches) {\n $('.portfolio-infographic .infographic-slider .tab-content .col').off('click');\n\n // If window width is less than 481px\n if (window.matchMedia(\"(max-width: 480px)\").matches) {\n return;\n }\n\n // If window width is greater than 481px & less than 992px\n else {\n\n // If there are 2 slides\n if (slideCount === 2) {\n $('.portfolio-infographic .infographic-slider .tab-content .col').clone().insertAfter('.portfolio-infographic .infographic-slider .tab-content .col:last-of-type');\n slick.slick('reinit');\n slick.slick('slickGoTo', 0);\n } else {\n return;\n }\n }\n }\n\n // If window width is greater than 992px\n else {\n\n // If there are less than 4 slides or greater than 1 slide\n if (slideCount > 1 && slideCount < 4) {\n\n // If there are 3 slides\n if (slideCount === 3) {\n $('.portfolio-infographic .infographic-slider .tab-content .col').clone().insertAfter('.portfolio-infographic .infographic-slider .tab-content .col:last-of-type');\n slick.slick('reinit');\n slick.slick('slickGoTo', 0);\n }\n\n // If there are 2 slides\n else if (slideCount === 2) {\n $(document).on('click', '.portfolio-infographic .infographic-slider .tab-content .' + index, function (e) {\n if (!$(this).hasClass('slick-current')) {\n e.preventDefault();\n $(this).parent().find('.col').removeClass('slick-current');\n $(this).addClass('slick-current');\n $('body').removeClass('overlay-active');\n $('.video-overlay').find('iframe').attr('src', '');\n }\n });\n }\n }\n\n // If there are greater than 4 slides or 1 slide\n else {\n return;\n }\n }\n }",
"function createLoop(s) {\n // Remove duplicated slides\n Object(__WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"c\" /* eachChild */])(s._wrapper, '.' + __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slide + '.' + __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slideDuplicate, function (ele) {\n ele.parentElement.removeChild(ele);\n });\n var slides = s._wrapper.querySelectorAll('.' + __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slide);\n if (s.slidesPerView === 'auto' && !s.loopedSlides) {\n s.loopedSlides = slides.length;\n }\n s.loopedSlides = parseInt((s.loopedSlides || s.slidesPerView), 10);\n s.loopedSlides = s.loopedSlides + s.loopAdditionalSlides;\n if (s.loopedSlides > slides.length) {\n s.loopedSlides = slides.length;\n }\n var prependSlides = [];\n var appendSlides = [];\n for (var i = 0; i < slides.length; i++) {\n var slide = slides[i];\n if (i < s.loopedSlides)\n appendSlides.push(slide);\n if (i < slides.length && i >= slides.length - s.loopedSlides)\n prependSlides.push(slide);\n slide.setAttribute('data-swiper-slide-index', i);\n }\n for (i = 0; i < appendSlides.length; i++) {\n var appendClone = appendSlides[i].cloneNode(true);\n Object(__WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"b\" /* addClass */])(appendClone, __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slideDuplicate);\n s._wrapper.appendChild(appendClone);\n }\n for (i = prependSlides.length - 1; i >= 0; i--) {\n var prependClone = prependSlides[i].cloneNode(true);\n Object(__WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"b\" /* addClass */])(prependClone, __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slideDuplicate);\n s._wrapper.insertBefore(prependClone, s._wrapper.firstElementChild);\n }\n}",
"function currentPage3(n) {\n\n clearInterval(timeValue3);\n timeValue3 = setInterval(function () {\n addOne3(n + 1)\n }, 5000);\n showSlides3(indexSlide3 = n);\n}",
"function sliders(){\n $('.slider').not('.loaded').addClass('loaded').each(function(index){\n\t var frame = $(this);\n\t var container = frame.children('.swiper-container');\n\t var toggle = container.children('.top-right')\n\t var slider = container.swiper({mode:'horizontal',loop: true, pagination:'#pagination'+container.attr('id'),paginationClickable:1,grabCursor:1,keyboardControl:1});\n\t container.children('.center-left').click(function(e){slider.swipePrev();e.preventDefault()});\n\t container.children('.center-right').click(function(e){slider.swipeNext();e.preventDefault()});\n\n\t toggle.click(function(e){\n\t\t if (!frame.hasClass('fullscreen')) {$('html, body').css('overflow','hidden');$('#layer').show();frame.css({'height':$(window).height()-20,'width':$(window).width()-20,'margin':0,'top':10,'left':10,'z-index':1000,'position':'fixed'})}\n\t\t else if (frame.hasClass('fullscreen')) {$('html, body').css('overflow','visible');$('#layer').hide();frame.removeAttr('style');$('html, body').scrollTop(frame.offset().top-($(window).height()/2)+110)}\n\t\t frame.toggleClass('fullscreen');\n\t\t e.preventDefault();\n\t\t slider.resizeFix()\n\t });\n\n\t $(document).keyup(function(e){\n\t\t if(e.keyCode === 27)\n\t\t\t if (frame.hasClass('fullscreen')) {e.preventDefault();$('html, body').css('overflow','visible').scrollTop(frame.offset().top);$('#layer').hide();frame.removeClass('fullscreen').removeAttr('style');slider.resizeFix();$('html, body').scrollTop(frame.offset().top-($(window).height()/2)+110)}\n\t });\n\t $(window).resize(function() {\n\t\t if (frame.hasClass('fullscreen')) {frame.css({'height':$(window).height()-20,'width':$(window).width()-20});}\n\t\t slider.resizeFix();\n\t });\n });\n $('.swiper-slide').not('.loaded').addClass('loaded').each(function(){\n\t $(this).css('background-image','url('+$(this).attr('data-bg')+')');\n });\n $('.spip_image').not('.loaded').addClass('loaded').each(function(){\n\t $(this).css('background-image','url('+$(this).attr('data-bg')+')');\n\t $(this).children('img').attr('src',$(this).children('img').attr('data-src'));\n\n\t if ($(this).find('.top-right').length) {\n\t var frame = $(this);\n\t var toggle = frame.children('.top-right')\n\t var style = frame.attr('style');\n\t var hd = toggle.attr('href')\n\t toggle.click(function(e){\n\t if (!frame.hasClass('fullscreen')) {$('html, body').css('overflow','hidden');$('#layer').show();frame.css({'background-color':'transparent','background-image':'url('+hd+')','height':$(window).height()-20,'width':$(window).width()-20,'margin':0,'top':10,'left':10,'z-index':1000,'position':'fixed'})}\n\t else if (frame.hasClass('fullscreen')) {$('html, body').css('overflow','visible');$('#layer').hide();frame.attr('style',style);$('html, body').scrollTop(frame.offset().top-($(window).height()/2)+110)}\n\t\t frame.toggleClass('fullscreen');\n\t\t e.preventDefault();\n\t });\n\t $(document).keyup(function(e){\n\t\t if(e.keyCode === 27)\n if (frame.hasClass('fullscreen')) {$('html, body').css('overflow','visible');$('#layer').hide();frame.removeClass('fullscreen').attr('style',style);$('html, body').scrollTop(frame.offset().top-($(window).height()/2)+110)}\n\t });\n\t $(window).resize(function() {\n\t\t if (frame.hasClass('fullscreen')) {frame.css({'height':$(window).height()-20,'width':$(window).width()-20});}\n\t });\n\n\t }\n });\n\n}",
"function showDataOnSlider(productsArrayLength) {\r\n $('.multiple-items').slick({\r\n infinite: true,\r\n arrows: true,\r\n slidesToShow: itemsToSlide,\r\n slidesToScroll: itemsToSlide\r\n });\r\n}",
"function pm_stripe_carousel() {\n var site_width = jQuery(window).width(),\n slider_list = jQuery('.pm_gallery'),\n increment = slider_list.find('li.pm_gallery_item').width(),\n elements = jQuery(slider_list).children(),\n number_elements = elements.length,\n elements_in_window = Math.round(jQuery(this).width() / increment),\n first_element_in_window = 1,\n isAnimating = false,\n i;\n\n if (elements) {\n for (i = 0; i < elements_in_window + 1; i++) {\n jQuery(slider_list).css('width', (number_elements + elements_in_window) * increment + increment + \"px\");\n jQuery(slider_list).append(jQuery(elements[i]).clone().removeClass('pm_gallery_item').addClass('pm_gallery_item_clone'));\n }\n\n jQuery(slider_list).find('.pm_gallery_item_clone.first_item').removeClass('first_item');\n jQuery(slider_list).find('.pm_gallery_item_clone.last_item').removeClass('last_item');\n } // Thumbnails\n\n\n var stripe_item = jQuery('.pm_gallery_item'),\n first_item = stripe_item.first(),\n last_item = jQuery(slider_list).find('#item_6'),\n first_item_num = jQuery(first_item).attr('data-number'),\n last_item_num = jQuery(last_item).attr('data-number'),\n prev_thumb_back,\n next_thumb_back,\n all_slides = stripe_item.length,\n next_button = jQuery('.pm_next_slide_button'),\n prev_button = jQuery('.pm_prev_slide_button');\n first_item.addClass('first_item');\n last_item.addClass('last_item');\n prev_thumb_back = stripe_item.last().attr('data-thumbnail');\n\n if (last_item_num < all_slides) {\n next_thumb_back = last_item.next().attr('data-thumbnail');\n } else {\n next_thumb_back = first_item.attr('data-thumbnail');\n }\n\n next_button.find('.pm_next_thumb_cont').css({\n 'background-image': 'url(' + next_thumb_back + ')'\n });\n prev_button.find('.pm_prev_thumb_cont').css({\n 'background-image': 'url(' + prev_thumb_back + ')'\n }); // Next Slide\n\n next_button.on('click', function () {\n stripe_next_slide();\n });\n\n function stripe_next_slide() {\n if (!isAnimating) {\n if (first_element_in_window > number_elements) {\n first_element_in_window = 2;\n jQuery(slider_list).css('left', \"0px\");\n } else {\n first_element_in_window++;\n }\n\n jQuery(slider_list).animate({\n left: \"-=\" + increment,\n y: 0,\n queue: true\n }, \"swing\", function () {\n isAnimating = false;\n });\n isAnimating = true;\n } // Next Thumbnail\n\n\n var stripe_container = jQuery('.pm_gallery'),\n stripe_item = jQuery(stripe_container).find('.pm_gallery_item'),\n first_item = jQuery(stripe_container).find('.first_item'),\n last_item = jQuery(stripe_container).find('.last_item'),\n first_item_num = jQuery(first_item).attr('data-number'),\n last_item_num = jQuery(last_item).attr('data-number'),\n all_slides = stripe_item.length,\n next_button = jQuery('.pm_next_slide_button'),\n prev_button = jQuery('.pm_prev_slide_button'),\n new_first_item,\n new_last_item,\n prev_thumb_back,\n next_thumb_back;\n\n if (last_item_num < all_slides) {\n last_item.removeClass('last_item').next().addClass('last_item');\n } else {\n last_item.removeClass('last_item');\n stripe_item.first().addClass('last_item');\n }\n\n if (first_item_num < all_slides) {\n first_item.removeClass('first_item').next().addClass('first_item');\n } else {\n first_item.removeClass('first_item');\n stripe_item.first().addClass('first_item');\n }\n\n new_last_item = jQuery(stripe_container).find('.last_item');\n new_first_item = jQuery(stripe_container).find('.first_item');\n last_item_num = new_last_item.attr('data-number');\n first_item_num = new_first_item.attr('data-number');\n\n if (last_item_num < all_slides) {\n next_thumb_back = new_last_item.next().attr('data-thumbnail');\n } else {\n next_thumb_back = stripe_item.first().attr('data-thumbnail');\n }\n\n if (first_item_num !== '1') {\n prev_thumb_back = new_first_item.prev().attr('data-thumbnail');\n } else {\n prev_thumb_back = stripe_item.last().attr('data-thumbnail');\n }\n\n next_button.find('.pm_next_thumb_cont').css({\n 'background-image': 'url(' + next_thumb_back + ')'\n });\n prev_button.find('.pm_prev_thumb_cont').css({\n 'background-image': 'url(' + prev_thumb_back + ')'\n });\n } // Prev Slide\n\n\n prev_button.on('click', function () {\n stripe_prev_slide();\n });\n\n function stripe_prev_slide() {\n if (!isAnimating) {\n if (first_element_in_window == 1) {\n jQuery(slider_list).css('left', \"-\" + number_elements * increment + \"px\");\n first_element_in_window = number_elements;\n } else {\n first_element_in_window--;\n }\n\n jQuery(slider_list).animate({\n left: \"+=\" + increment,\n y: 0,\n queue: true\n }, \"swing\", function () {\n isAnimating = false;\n });\n isAnimating = true;\n } // Prev Thumbnail\n\n\n var stripe_container = jQuery('.pm_gallery'),\n stripe_item = jQuery(stripe_container).find('.pm_gallery_item'),\n first_item = jQuery(stripe_container).find('.first_item'),\n last_item = jQuery(stripe_container).find('.last_item'),\n first_item_num = jQuery(first_item).attr('data-number'),\n last_item_num = jQuery(last_item).attr('data-number'),\n all_slides = stripe_item.length,\n next_button = jQuery('.pm_next_slide_button'),\n prev_button = jQuery('.pm_prev_slide_button'),\n new_first_item,\n new_last_item,\n prev_thumb_back,\n next_thumb_back;\n\n if (last_item_num !== '1') {\n last_item.removeClass('last_item').prev().addClass('last_item');\n } else {\n last_item.removeClass('last_item');\n stripe_item.last().addClass('last_item');\n }\n\n if (first_item_num !== '1') {\n first_item.removeClass('first_item').prev().addClass('first_item');\n } else {\n first_item.removeClass('first_item');\n stripe_item.last().addClass('first_item');\n }\n\n new_last_item = jQuery(stripe_container).find('.last_item');\n new_first_item = jQuery(stripe_container).find('.first_item');\n last_item_num = new_last_item.attr('data-number');\n first_item_num = new_first_item.attr('data-number');\n\n if (last_item_num < all_slides) {\n next_thumb_back = new_last_item.next().attr('data-thumbnail');\n } else {\n next_thumb_back = stripe_item.first().attr('data-thumbnail');\n }\n\n if (first_item_num !== '1') {\n prev_thumb_back = new_first_item.prev().attr('data-thumbnail');\n } else {\n prev_thumb_back = stripe_item.last().attr('data-thumbnail');\n }\n\n next_button.find('.pm_next_thumb_cont').css({\n 'background-image': 'url(' + next_thumb_back + ')'\n });\n prev_button.find('.pm_prev_thumb_cont').css({\n 'background-image': 'url(' + prev_thumb_back + ')'\n });\n }\n /* Autoplay */\n\n\n var autoplay_status = 'on',\n slide_duration = '5000',\n intervalID;\n\n if (autoplay_status == 'on') {\n intervalID = setInterval(stripe_next_slide, slide_duration);\n jQuery('.pm_pause_button').on('click', function () {\n if (jQuery(this).hasClass('pm_paused')) {\n intervalID = setInterval(stripe_next_slide, slide_duration);\n jQuery(this).removeClass('pm_paused');\n } else {\n clearInterval(intervalID);\n jQuery(this).addClass('pm_paused');\n }\n });\n } else {\n jQuery('.pm_pause_button').remove();\n }\n} /////////////////////////////////////",
"function plusSlides(n) {\n clearInterval(myTimer);\n if (n < 0) {\n showSlides(slideIndex -= 1);\n } else {\n showSlides(slideIndex += 1);\n }\n\n\n\n if (n === -1) {\n myTimer = setInterval(function () { plusSlides(n + 2) }, 4000);\n } else {\n myTimer = setInterval(function () { plusSlides(n + 1) }, 4000);\n }\n}",
"function changeSlide(n) {\n SlideIndex += n;\n //===== Upper or lower limit exceeded - pass through - set global variable SlideIndex\n if (SlideIndex > SlideCount) { \n SlideIndex = 1;\n } else if (SlideIndex < 1) {\n SlideIndex = SlideCount;\n } \n slideShow();\n}",
"function changeSlides(n) {\n showSlides(slideIndex += n);\n}",
"function nextSlider(){\n if( imgPos >= imgItems){imgPos = 1;} \n else {imgPos++;}\n\n $('.slider li').fadeOut(); // Ocultamos todos los slides\n $('.slider li:nth-child('+ imgPos +')').fadeIn(); // Mostramos el Slide seleccionado\n\n}",
"function currentPage(n) {\n\n clearInterval(timeValue);\n timeValue = setInterval(function () {\n addOne(n + 1)\n }, 5000);\n showSlides(indexSlide = n);\n}",
"function currentSlide(n) {\r\n showSlides(slideCounter = n);\r\n}",
"function loadFimgs() {\n $(\"#my-carousel-flickr\").carousel(0);\n var fhtml = '';\n for (var i = 0; i < 6; i++) {\n var j = (fcount * 6 + i) % (furlList.length);\n if (i == 0) {\n fhtml +=\n '<div class=\"item active animated ' + animate() + '\">';\n } else {\n fhtml +=\n '<div class=\"item\">';\n }\n fhtml +=\n ' <img src=\"' + furlList[j].url +\n '\" alt=\"photo: ' + furlList[j].title + '\">' +\n ' <div class=\"carousel-caption\">';\n\n if (i == 5) {\n fhtml +=\n '<div>' +\n ' <h4 class=\"animated fadeInDownBig\"><a href=\"https://www.flickr.com/photos/guojunjun/albums/72157646082323705\" class=\"icon fa-flickr\">' +\n ' View my photo gallery at Flickr</a></h4>' +\n ' <h2 class=\"animated flip\"><a id=\"flickr-next\" class=\"icon fa-forward\"> Next slider</a></h2>' +\n '</div>';\n }\n\n fhtml +=\n ' <p class=\"animated ' + animate() + '\">' + furlList[j].title + '</p>' +\n ' </div>' +\n '</div>';\n }\n document.getElementById(\"my-flickr-slides\").innerHTML = fhtml;\n fcount++;\n document.getElementById(\"flickr-next\").addEventListener(\"click\", loadFimgs);\n}",
"infiniteLoop() {\n\t\tthis.$clonedFirst = this.$firstItem.clone(true).addClass(this.options.cloneClass);\n\t\tthis.$clonedLast = this.$lastItem.clone(true).addClass(this.options.cloneClass);\n\n\t\tif (this.options.infinite) {\n\t\t\tthis.$clonedFirst.find(this.paginationItemSel).attr('data-index', this.itemsLength);\n\t\t\tthis.$clonedLast.find(this.paginationItemSel).attr('data-index', -1);\n\t\t}\n\n\t\tthis.$firstItem.before(this.$clonedLast);\n\t\tthis.$lastItem.after(this.$clonedFirst);\n\n\t\tthis.$items = $(this.options.items, this.$el);\n\t}",
"function slideSlick() {\n\t$('#film-gallery-carousel').slick({\n\t\tinfinite: true,\n\t\tcenterMode: true,\n\t\tvariableWidth: true,\n\t\tslidesToShow: 3,\n\t\tdots: false,\n\t\tarrows: false,\n\t\tautoplay: false,\n\t\tresponsive: [{\n\t\t\tbreakpoint: 768,\n\t\t\tsettings: {\n\t\t\t\tslidesToShow: 1,\n\t\t\t\tcenterMode: false,\n\t\t\t\tvariableWidth: false,\n\t\t\t}\n\t\t}]\n\t});\n}",
"function createLoop(s) {\n // Remove duplicated slides\n __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"h\" /* eachChild */])(s._wrapper, '.' + __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slide + '.' + __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slideDuplicate, function (ele) {\n ele.parentElement.removeChild(ele);\n });\n var slides = s._wrapper.querySelectorAll('.' + __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slide);\n if (s.slidesPerView === 'auto' && !s.loopedSlides) {\n s.loopedSlides = slides.length;\n }\n s.loopedSlides = parseInt((s.loopedSlides || s.slidesPerView), 10);\n s.loopedSlides = s.loopedSlides + s.loopAdditionalSlides;\n if (s.loopedSlides > slides.length) {\n s.loopedSlides = slides.length;\n }\n var prependSlides = [];\n var appendSlides = [];\n for (var i = 0; i < slides.length; i++) {\n var slide = slides[i];\n if (i < s.loopedSlides)\n appendSlides.push(slide);\n if (i < slides.length && i >= slides.length - s.loopedSlides)\n prependSlides.push(slide);\n slide.setAttribute('data-swiper-slide-index', i);\n }\n for (i = 0; i < appendSlides.length; i++) {\n var appendClone = appendSlides[i].cloneNode(true);\n __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"i\" /* addClass */])(appendClone, __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slideDuplicate);\n s._wrapper.appendChild(appendClone);\n }\n for (i = prependSlides.length - 1; i >= 0; i--) {\n var prependClone = prependSlides[i].cloneNode(true);\n __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"i\" /* addClass */])(prependClone, __WEBPACK_IMPORTED_MODULE_0__swiper_utils__[\"a\" /* CLS */].slideDuplicate);\n s._wrapper.insertBefore(prependClone, s._wrapper.firstElementChild);\n }\n}",
"function listing_post_format_image_slider(i){var listing_id='#'+i,slider_container=jQuery(listing_id),elements=jQuery(slider_container).children(),number_of_elements=elements.length,slide_item=jQuery(slider_container).find('li'),intervalID,next_button=jQuery(slider_container).parent().parent().find('.pm_prev_image_slide_button'),prev_button=jQuery(\".pm_media_output_cont_wrapper .pm_prev_slide_button\"),current_item,slide_number;slide_item.first().addClass(\"visible\");// Navigation\nslider_container.parent().parent().find('.pm_prev_image_slide_button').on('click',function(){current_item=jQuery(slider_container).find('li.visible');slide_number=current_item.attr('data-number');if(slide_number==\"1\"){jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\");slide_item.last().addClass('visible');}else{jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\").prev().addClass(\"visible\");}});slider_container.parent().parent().find('.pm_next_image_slide_button').on('click',function(){current_item=jQuery(slider_container).find('li.visible');slide_number=current_item.attr('data-number');if(slide_number<number_of_elements){jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\").next().addClass(\"visible\");}else{jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\");slide_item.first().addClass(\"visible\");}});}////////////////////////////////////////////",
"function listing_post_format_image_slider(i){var listing_id='#'+i,slider_container=jQuery(listing_id),elements=jQuery(slider_container).children(),number_of_elements=elements.length,slide_item=jQuery(slider_container).find('li'),intervalID,next_button=jQuery(slider_container).parent().parent().find('.pm_prev_image_slide_button'),prev_button=jQuery(\".pm_media_output_cont_wrapper .pm_prev_slide_button\"),current_item,slide_number;slide_item.first().addClass(\"visible\");// Navigation\nslider_container.parent().parent().find('.pm_prev_image_slide_button').on('click',function(){current_item=jQuery(slider_container).find('li.visible');slide_number=current_item.attr('data-number');if(slide_number==\"1\"){jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\");slide_item.last().addClass('visible');}else{jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\").prev().addClass(\"visible\");}});slider_container.parent().parent().find('.pm_next_image_slide_button').on('click',function(){current_item=jQuery(slider_container).find('li.visible');slide_number=current_item.attr('data-number');if(slide_number<number_of_elements){jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\").next().addClass(\"visible\");}else{jQuery(slider_container).find(\"li.visible\").removeClass(\"visible\");slide_item.first().addClass(\"visible\");}});}////////////////////////////////////////////",
"function blog_listing_carousel_tape(i){var site_width=jQuery(window).width(),site_height=jQuery(window).height(),header_height=jQuery('header').height(),slider_height=site_height-header_height-i,slider_container=jQuery('.pm_blog_listing_tape_container'),slider_list=jQuery(slider_container).find('.pm_gallery'),elements=jQuery(slider_list).children(),number_of_elements=elements.length,gallery_item=slider_list.find('.pm_gallery_item'),gallery_image_width=jQuery(gallery_item).find('img').width();if(site_width<737){slider_height=site_height-header_height-60;}slider_container.height(slider_height).css('margin-top',header_height);slider_list.height(slider_height*0.91).css({'margin-top':slider_height*0.044,'margin-bottom':slider_height*0.044});gallery_item.width(gallery_image_width);gallery_item.find('.pm_media_output_cont_wrapper').width(gallery_image_width);var current_item;current_item=jQuery('#item_1').addClass('current_item');gallery_item.last().addClass('prev_item').prev().addClass('prev_item_2');current_item.next().addClass('next_item').next().addClass('next_item_2');blog_listing_tape_position();}/////////////////////////////////////////////",
"function blog_listing_carousel_tape(i){var site_width=jQuery(window).width(),site_height=jQuery(window).height(),header_height=jQuery('header').height(),slider_height=site_height-header_height-i,slider_container=jQuery('.pm_blog_listing_tape_container'),slider_list=jQuery(slider_container).find('.pm_gallery'),elements=jQuery(slider_list).children(),number_of_elements=elements.length,gallery_item=slider_list.find('.pm_gallery_item'),gallery_image_width=jQuery(gallery_item).find('img').width();if(site_width<737){slider_height=site_height-header_height-60;}slider_container.height(slider_height).css('margin-top',header_height);slider_list.height(slider_height*0.91).css({'margin-top':slider_height*0.044,'margin-bottom':slider_height*0.044});gallery_item.width(gallery_image_width);gallery_item.find('.pm_media_output_cont_wrapper').width(gallery_image_width);var current_item;current_item=jQuery('#item_1').addClass('current_item');gallery_item.last().addClass('prev_item').prev().addClass('prev_item_2');current_item.next().addClass('next_item').next().addClass('next_item_2');blog_listing_tape_position();}/////////////////////////////////////////////",
"function startSlider(){\r\n count = $(\".slider > .slider-img\").length;\r\n\r\n loop = setInterval(function(){\r\n\r\n if(sliderNext > count){\r\n sliderNext = 1;\r\n sliderInt = 1;\r\n }\r\n\r\n $(\".slider > .slider-img\").fadeOut(500);\r\n $(\".slider > .slider-img#\" + sliderNext).fadeIn(500);\r\n\r\n sliderInt = sliderNext;\r\n sliderNext = sliderNext + 1;\r\n },8000);\r\n}"
]
| [
"0.7095931",
"0.69714695",
"0.68233114",
"0.6769172",
"0.6725968",
"0.6718358",
"0.6696815",
"0.6696815",
"0.6674874",
"0.6654848",
"0.6640396",
"0.6624667",
"0.6620997",
"0.6581502",
"0.6560405",
"0.65543944",
"0.65497243",
"0.65387833",
"0.65345144",
"0.6532842",
"0.65225047",
"0.65061736",
"0.6504128",
"0.6493715",
"0.6472199",
"0.64711905",
"0.64711905",
"0.6454222",
"0.6454222",
"0.6446666"
]
| 0.7266895 | 0 |
Construct an instance of Tri2DInfo, you can either pass null to a, b and c and the instance will be allocated "clear", or give actual triangle info and the center/radius will be computed | function Tri2DInfo(a, b, c) {
if (a === null && b === null && c === null) {
this.a = BABYLON.Vector2.Zero();
this.b = BABYLON.Vector2.Zero();
this.c = BABYLON.Vector2.Zero();
this.center = BABYLON.Vector2.Zero();
this.radius = 0;
return;
}
this.a = a.clone();
this.b = b.clone();
this.c = c.clone();
this._updateCenterRadius();
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function Triangle(base, lato1, lato2){\n\tthis.base = base;\n\tthis.lato1 = lato1;\n\tthis.lato2 = lato2;\n}",
"function Triangle(cateto1,cateto2,ipotenusa){\n\tthis.cateto1 = cateto1;\n\tthis.cateto2 = cateto2;\n\tthis.ipotenusa = ipotenusa;\n}",
"constructor(a, b, c, color, normalA, normalB, normalC) {\n\n this.a = a;\n this.b = b;\n this.c = c;\n this.color = color;\n this.ac = this.c.subtract(this.a);\n this.ab = this.b.subtract(this.a);\n this.bc = this.c.subtract(this.b);\n this.ca = this.a.subtract(this.c);\n this.name = \"triangle\";\n this.na = normalA;\n this.nb = normalB;\n this.nc = normalC;\n\n // compute normal vector of plane that triangle lies in\n var norm = this.ab.cross(this.ac);\n this.planeNorm = norm.unit();\n\n // compute area of triangle\n this.area = norm.length() / 2.0;\n\n }",
"function Triangle(ab, bc, ca) {\n this.ab = ab || new Connections();\n this.bc = bc || new Connections();\n this.ca = ca || new Connections();\n}",
"function trikampis(a,b){\n\tthis.a=a\n\tthis.b=b\n\tthis.c=this.getC()\n\tthis.perimetras=this.getPerimetras()\n}",
"_addTriangle(i0, i1, i2, a, b, c) {\n const t = this.trianglesLen;\n this._triangles[t] = i0;\n this._triangles[t + 1] = i1;\n this._triangles[t + 2] = i2;\n this._link(t, a);\n this._link(t + 1, b);\n this._link(t + 2, c);\n this.trianglesLen += 3;\n return t;\n }",
"function tri(shape, a, b, c, coords) {\r\n shape.numPositions += 3;\r\n var t1 = subtract(shape.vertices[b], shape.vertices[a]);\r\n var t2 = subtract(shape.vertices[c], shape.vertices[b]);\r\n var normal = normalize(cross(t1, t2));\r\n normal = vec4(normal[0], normal[1], normal[2], 0.0);\r\n var tangent = vec4(t1[0], t1[1], t1[2], 0.0);\r\n\r\n shape.positionsArray.push(shape.vertices[a]);\r\n shape.normalsArray.push(normal);\r\n shape.colorsArray.push(shape.color);\r\n shape.texCoordsArray.push(shape.texCoord[coords[0]]);\r\n shape.tangentsArray.push(tangent);\r\n\r\n shape.positionsArray.push(shape.vertices[b]);\r\n shape.normalsArray.push(normal);\r\n shape.colorsArray.push(shape.color);\r\n shape.texCoordsArray.push(shape.texCoord[coords[1]]);\r\n shape.tangentsArray.push(tangent);\r\n\r\n shape.positionsArray.push(shape.vertices[c]);\r\n shape.normalsArray.push(normal);\r\n shape.colorsArray.push(shape.color);\r\n shape.texCoordsArray.push(shape.texCoord[coords[2]]);\r\n shape.tangentsArray.push(tangent);\r\n}",
"_addTriangle(i0, i1, i2, a, b, c) {\n const t = this.trianglesLen;\n\n this._triangles[t] = i0;\n this._triangles[t + 1] = i1;\n this._triangles[t + 2] = i2;\n\n this._link(t, a);\n this._link(t + 1, b);\n this._link(t + 2, c);\n\n this.trianglesLen += 3;\n\n return t;\n }",
"_addTriangle(i0, i1, i2, a, b, c) {\n const t = this.trianglesLen;\n\n this._triangles[t] = i0;\n this._triangles[t + 1] = i1;\n this._triangles[t + 2] = i2;\n\n this._link(t, a);\n this._link(t + 1, b);\n this._link(t + 2, c);\n\n this.trianglesLen += 3;\n\n return t;\n }",
"_addTriangle(i0, i1, i2, a, b, c) {\n const t = this.trianglesLen;\n\n this._triangles[t] = i0;\n this._triangles[t + 1] = i1;\n this._triangles[t + 2] = i2;\n\n this._link(t, a);\n this._link(t + 1, b);\n this._link(t + 2, c);\n\n this.trianglesLen += 3;\n\n return t;\n }",
"_addTriangle(i0, i1, i2, a, b, c) {\n const t = this.trianglesLen;\n\n this._triangles[t] = i0;\n this._triangles[t + 1] = i1;\n this._triangles[t + 2] = i2;\n\n this._link(t, a);\n this._link(t + 1, b);\n this._link(t + 2, c);\n\n this.trianglesLen += 3;\n\n return t;\n }",
"_addTriangle(i0, i1, i2, a, b, c) {\n const t = this.trianglesLen;\n\n this._triangles[t] = i0;\n this._triangles[t + 1] = i1;\n this._triangles[t + 2] = i2;\n\n this._link(t, a);\n this._link(t + 1, b);\n this._link(t + 2, c);\n\n this.trianglesLen += 3;\n\n return t;\n }",
"function getTri(x, y) {\n\n\t\tvar dx = x - cx,\n\t\t\tdy = y - cy;\n\n\t\treturn {\n\t\t\tdist: Math.sqrt(dx*dx + dy*dy),\n\t\t\tangle: Math.atan2(dy, dx)\n\t\t}\n\t}",
"_addTriangle(i0, i1, i2, a, b, c) {\n const t = this.trianglesLen;\n this._triangles[t] = i0;\n this._triangles[t + 1] = i1;\n this._triangles[t + 2] = i2;\n\n this._link(t, a);\n\n this._link(t + 1, b);\n\n this._link(t + 2, c);\n\n this.trianglesLen += 3;\n return t;\n }",
"function _triangles() {\n \n // Cube is positioned on the origin\n var leftX = -1.5;\n var rightX = 1.5;\n var downY = -1.5;\n var upY = 1.5;\n var frontZ = -1.5;\n var backZ = 1.5;\n\n var a = vec3.fromValues(leftX, upY, frontZ);\n var b = vec3.fromValues(leftX, downY, frontZ);\n var c = vec3.fromValues(rightX, downY, frontZ);\n var d = vec3.fromValues(rightX, upY, frontZ);\n var e = vec3.fromValues(leftX, upY, backZ);\n var f = vec3.fromValues(leftX, downY, backZ);\n var g = vec3.fromValues(rightX, downY, backZ);\n var h = vec3.fromValues(rightX, upY, backZ);\n\n var lightgreen = vec3.fromValues(77/255, 204/255, 157/255);\n var lightpink = vec3.fromValues(194/255, 86/255, 146/255);\n\n var colorTexture1 = new ColorTexture(lightgreen);\n var colorTexture2 = new ColorTexture(lightpink);\n \n var th = texture.h - 1;\n var tw = texture.w - 1;\n \n // TODO: must define some order that these should be given in.\n // TODO: and also handle case where pixels are flipped in rasterizer I think\n var upperTextureCoords = [[tw, th], [tw, 0], [0, 0]];\n var lowerTextureCoords = [[0, th], [tw, th], [0, 0]];\n\n // A cube\n return [\n // front\n new Triangle(b, c, a, texture, lowerTextureCoords),\n new Triangle(c, d, a, texture, upperTextureCoords),\n\n // left\n new Triangle(a, f, b, colorTexture2),\n new Triangle(a, e, f, colorTexture1),\n\n // right\n new Triangle(c, g, d, colorTexture1),\n new Triangle(g, h, d, colorTexture2),\n\n // bottom\n new Triangle(c, b, f, colorTexture1),\n new Triangle(c, f, g, colorTexture1),\n\n // top\n new Triangle(a, h, e, colorTexture1),\n new Triangle(a, d, h, colorTexture2),\n\n // back\n new Triangle(e, h, f, colorTexture2),\n new Triangle(h, g, f, colorTexture2)\n ];\n }",
"constructor(f, x, y, n) {\n this.f = f;\n if (f === 1) {\n this.circulo = circulo1;\n this.triangulo = triangulo1;\n } else if (f === 2) {\n this.circulo = circulo2;\n this.triangulo = triangulo2;\n } else if (f === 3) {\n this.circulo = circulo3;\n this.triangulo = triangulo3;\n } else if (f === 4) {\n this.circulo = circulo4;\n this.triangulo = triangulo4;\n }\n this.quadrado = quadrado;\n this.x = x;\n this.y = y;\n this.n = n;\n }",
"function Triangle(x1, y1, x2, y2, x3, y3)\n {\n this.X = [0.0, 0.0, 0.0];\n this.Y = [0.0, 0.0, 0.0];\n \n if (x1 instanceof Triangle)\n {\n this.X[0] = x1.X[0];\n this.X[1] = x1.X[1];\n this.X[2] = x1.X[2];\n this.Y[0] = x1.Y[0];\n this.Y[1] = x1.Y[1];\n this.Y[2] = x1.Y[2];\n }\n else\n {\n var dx1 = x2 - x1;\n var dx2 = x3 - x1;\n var dy1 = y2 - y1;\n var dy2 = y3 - y1;\n var cross = dx1 * dy2 - dx2 * dy1;\n var ccw = (cross > 0);\n if (ccw)\n {\n this.X[0] = x1;\n this.X[1] = x2;\n this.X[2] = x3;\n this.Y[0] = y1;\n this.Y[1] = y2;\n this.Y[2] = y3;\n }\n else\n {\n this.X[0] = x1;\n this.X[1] = x3;\n this.X[2] = x2;\n this.Y[0] = y1;\n this.Y[1] = y3;\n this.Y[2] = y2;\n }\n }\n \n this.IsInside = function(x, y)\n {\n if (x < this.X[0] && x < this.X[1] && x < this.X[2]) return false;\n if (x > this.X[0] && x > this.X[1] && x > this.X[2]) return false;\n if (y < this.Y[0] && y < this.Y[1] && y < this.Y[2]) return false;\n if (y > this.Y[0] && y > this.Y[1] && y > this.Y[2]) return false;\n\n var vx2 = x - this.X[0];\n var vy2 = y - this.Y[0];\n var vx1 = this.X[1] - this.X[0];\n var vy1 = this.Y[1] - this.Y[0];\n var vx0 = this.X[2] - this.X[0];\n var vy0 = this.Y[2] - this.Y[0];\n\n var dot00 = vx0 * vx0 + vy0 * vy0;\n var dot01 = vx0 * vx1 + vy0 * vy1;\n var dot02 = vx0 * vx2 + vy0 * vy2;\n var dot11 = vx1 * vx1 + vy1 * vy1;\n var dot12 = vx1 * vx2 + vy1 * vy2;\n var invDenom = 1.0 / (dot00 * dot11 - dot01 * dot01);\n var u = (dot11 * dot02 - dot01 * dot12) * invDenom;\n var v = (dot00 * dot12 - dot01 * dot02) * invDenom;\n\n return ((u > 0) && (v > 0) && (u + v < 1));\n }\n }",
"function setupTriangles() {\r\n var p = setupPoints();\r\n return [\r\n //top\r\n p[0], p[4], p[1],\r\n p[1], p[4], p[5],\r\n p[1], p[5], p[2],\r\n p[2], p[5], p[6],\r\n p[2], p[6], p[3],\r\n p[3], p[6], p[7],\r\n \r\n //middle\r\n p[5], p[9], p[6],\r\n p[6], p[9], p[10],\r\n \r\n //bottom\r\n p[8], p[12], p[9],\r\n p[9], p[12], p[13],\r\n p[9], p[13], p[10],\r\n p[10], p[13], p[14],\r\n p[10], p[14], p[11],\r\n p[11], p[14], p[15]\r\n ];\r\n}",
"function Triangle(triSideOne, triSideTwo, triSideThree) {\n Polygon.call(this, [new Side(triSideOne), new Side(triSideTwo), new Side(triSideThree)])\n}",
"function triangleHelp(a, b, c)\n{\n points.push(c);\n points.push(b);\n points.push(a);\n //Below 3 lines gets the coordinates for triangle\n texturecoords.push(texCoord[0]);\n texturecoords.push(texCoord[1]);\n texturecoords.push(texCoord[2]);\n increment += 3;\n}",
"function Triangle(sideA, sideB, sideC) {\n this.sideA = sideA;\n this.sideB = sideB;\n this.sideC = sideC;\n}",
"function Triangle(sideA, sideB, sideC) {\n this.sideA = sideA;\n this.sideB = sideB;\n this.sideC = sideC;\n}",
"function triangle1(a,b,c)\n {\n var p = [0,0,1];\n var q = [0, Math.sin(c), Math.cos(c)];\n var rz = Math.cos(b);\n var ry = (Math.cos(a)-q[2]*rz)/q[1];\n var t = 1-rz*rz-ry*ry;\n if (t < 0) t = 0; // Clamp to avoid rounding problems\n var r = [Math.sqrt(t),ry,rz];\n // This used to reverse q and r to get a +ve OpenGL triangle to start\n // with, but that mucks up the tri coordinates, and anyway the complicated\n // stuff needs drawing both sides.\n return [p,q,r];\n }",
"function createTriangle(_triangleArray, _triangleCenter, _radius){\n\tvar c = _triangleCenter;\n\tvar Radius = _radius;\n\n\tvar points = [\n\t\tnew Point(c.x + Radius, c.y+Radius),\n\t\tnew Point(c.x - Radius, c.y+Radius),\n\t\tnew Point(c.x, c.y-Radius)\n\t\t];\n\n\tvar path = new Path(points);\n\n\tvar triangleColor = colours[Math.floor(Math.random()*colours.length)];\n\t// var triangleColor = Color.random();\n\tpath.fillColor = triangleColor;\n\t_triangleArray.push(path);\n}",
"function createTriangle(_triangleArray, _triangleCenter, _radius){\n\tvar c = _triangleCenter;\n\tvar Radius = _radius;\n\n\tvar points = [\n\t\tnew Point(c.x + Radius, c.y+Radius),\n\t\tnew Point(c.x - Radius, c.y+Radius),\n\t\tnew Point(c.x, c.y-Radius)\n\t\t];\n\n\tvar path = new Path(points);\n\n\tvar triangleColor = colours[Math.floor(Math.random()*colours.length)];\n\t// var triangleColor = Color.random();\n\tpath.fillColor = triangleColor;\n\t_triangleArray.push(path);\n}",
"function MakeTri(Name : String, ThisScale : float, ThisParent : Transform, ThisLayer : int){\nvar ThisMesh : Transform = new GameObject(Name).transform;\nvar mesh : Mesh = ThisMesh.gameObject.AddComponent(MeshFilter).mesh;\nThisScale *= .5;\n\nvar vertices : Vector3[] = new Vector3[4];\nvertices[0] = Vector3( -ThisScale, -ThisScale, 0);\nvertices[1] = Vector3( 0, ThisScale, 0);\nvertices[2] = Vector3(ThisScale, -ThisScale, 0);\n\nvar uv : Vector2[] = new Vector2[4];\nuv[0] = Vector2(0, 0);\nuv[1] = Vector2(0, 1);\nuv[2] = Vector2(1, 0);\nuv[3] = Vector2(1, 1);\n\nvar triangles : int[] = new int[6];\ntriangles[0] = 0;\ntriangles[1] = 1; \ntriangles[2] = 2;\n\nmesh.vertices = vertices;\nmesh.uv = uv;\nmesh.triangles = triangles;\n\nThisMesh.gameObject.AddComponent(MeshRenderer);\nThisMesh.GetComponent.<Renderer>().receiveShadows = false;\nThisMesh.GetComponent.<Renderer>().castShadows = false;\nThisMesh.GetComponent.<Renderer>().enabled = false;\nThisMesh.parent = ThisParent;\nThisMesh.gameObject.layer = ThisLayer;\nThisMesh.GetComponent.<Renderer>().material = RadarAtlasMaterial;\nreturn ThisMesh;\n}",
"function Triangle(i, pLeft, p, pRight)\n\t{\n\t\t// index of triangle in line\n\t\tthis.i = i;\n\t\tthis.pLeft = pLeft;\n\t\tthis.p = p;\n\t\tthis.pRight = pRight;\n\t\tthis.area = Geometry.triangleArea(pLeft, p, pRight);\n\t\t// left neighbor\n\t\tthis.nLeft = null;\n\t\t// right neighbor\n\t\tthis.nRight = null;\n\t}",
"constructor(container_node, width, height, triangle_width, triangle_height) {\n\n assert_eq_type(container_node, document.createElement(\"div\"));\n assert_eq_type(triangle_width, 0);\n assert_eq_type(triangle_height, 0);\n\n const [rows, cols] = calculate_necessary_triangles(width, height, triangle_width, triangle_height);\n\n this.container = container_node;\n this.triangle_array = create_array_properly(rows, cols, 0);\n this.triangle_width = triangle_width;\n this.triangle_height = triangle_height;\n }",
"calculateTriangele() {\n if (Object.keys(this.dimensions).length !== 3) {\n throw BadRequest(\"Invalid parameters for a triangle, provide only length_a, length_a and length_c\");\n }\n const { length_a, length_b, length_c } = this.dimensions;\n if (!length_a || !length_b || !length_c) {\n throw BadRequest(\"triangle data is not complete\");\n }\n const formula = \"√s * (s − length_a) * (s − length_b) * (s − length_c)\";\n const s = (length_a + length_b + length_c) / 2;\n const calculation = `√${s} * (${s} - ${length_a}) * (${s} - ${length_b}) * (${s} - ${length_c})`;\n const X = (s * (s - length_a) * (s - length_b) * (s - length_c));\n const area = Math.sqrt(X);\n this.area = area.toFixed(2);\n this.calculation = calculation;\n this.formula = formula;\n return this.area;\n }",
"function makeFirstTriangle( ) {\r\n\t\t\t\r\n\t\t\txp = xs;\r\n\t\t\typ = ys;\r\n\t\t\tzp = zs;\r\n\t\t\t\r\n\t\t\titerationNewton( );\r\n\t\t\t\r\n\t\t\t// first point\r\n\t\t\tg.positions[ posIdx ] = xp;\r\n\t\t\tg.positions[ posIdx + 1 ] = yp;\r\n\t\t\tg.positions[ posIdx + 2 ] = zp;\r\n\t\t\t\r\n\t\t\t// first normal\r\n\t\t\tg.normals[ posIdx ] = xn;\r\n\t\t\tg.normals[ posIdx + 1 ] = yn;\r\n\t\t\tg.normals[ posIdx + 2 ] = zn;\r\n\t\t\t\r\n\t\t\tfront.push( { idx: posIdx / 3, ang: 0 } ); // first front point\r\n\t\t\t\r\n\t\t\tposIdx += 3;\r\n\t\t\t\r\n\t\t\t// start point neighbour\r\n\t\t\tx1 = xs + d / 32;\r\n\t\t\ty1 = ys + d / 32;\r\n\t\t\tz1 = zs + d / 32;\r\n\t\t\t\r\n\t\t\tcalculateTangentsPoint( ); // start point and neighbour\r\n\t\t\t\r\n\t\t\txc = xp;\r\n\t\t\tyc = yp;\r\n\t\t\tzc = zp;\r\n\t\t\t\r\n\t\t\tphi = 0;\r\n\t\t\t\r\n\t\t\tfor ( let i = 0; i < 2; i ++ ) {\r\n\t\t\t\t\r\n\t\t\t\tcalculateSurfacePointAndNormal( );\r\n\t\t\t\t\r\n\t\t\t\tfront.push( { idx: posIdx / 3, ang: 0 } ); \r\n\t\t\t\t\r\n\t\t\t\tposIdx += 3;\r\n\t\t\t\t\r\n\t\t\t\tphi += Math.PI / 3;\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tg.indices[ indIdx ] = 0;\r\n\t\t\tg.indices[ indIdx + 1 ] = 1;\r\n\t\t\tg.indices[ indIdx + 2 ] = 2;\r\n\t\t\t\r\n\t\t\tindIdx += 3;\r\n\t\t\t\r\n\t\t\tfrontStock += 1;\r\n\t\t\t\r\n\t\t}"
]
| [
"0.6091806",
"0.59719497",
"0.593979",
"0.58621716",
"0.56427634",
"0.55245465",
"0.5521736",
"0.548732",
"0.548732",
"0.548732",
"0.54677004",
"0.54653597",
"0.5454679",
"0.5436464",
"0.5375392",
"0.536829",
"0.53450286",
"0.53385115",
"0.5336885",
"0.53142023",
"0.5300683",
"0.5300683",
"0.52795464",
"0.52771556",
"0.52771556",
"0.52311754",
"0.5216397",
"0.5215805",
"0.51921177",
"0.51775116"
]
| 0.8638009 | 0 |
Create a new instance of the FontTexture class | function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
if (maxCharCount === void 0) { maxCharCount = 200; }
if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
if (superSample === void 0) { superSample = false; }
if (signedDistanceField === void 0) { signedDistanceField = false; }
var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
_this._curCharCount = 0;
_this._lastUpdateCharCount = -1;
_this._usedCounter = 1;
_this.name = name;
_this.debugMode = false;
_this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
_this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
_this._sdfScale = 8;
_this._signedDistanceField = signedDistanceField;
_this._superSample = false;
_this._isPremultipliedAlpha = !signedDistanceField;
_this.name = "FontTexture " + font;
// SDF will use super sample no matter what, the resolution is otherwise too poor to produce correct result
if (superSample || signedDistanceField) {
var sfont = _this.getSuperSampleFont(font);
if (sfont) {
_this._superSample = true;
font = sfont;
}
}
// First canvas creation to determine the size of the texture to create
_this._canvas = document.createElement("canvas");
_this._context = _this._canvas.getContext("2d");
_this._context.font = font;
_this._context.fillStyle = "white";
_this._context.textBaseline = "top";
var res = _this.getFontHeight(font, "j$|");
_this._lineHeightSuper = res.height; //+4;
_this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
_this._offset = res.offset;
res = _this.getFontHeight(font, "f");
_this._baseLine = res.height + res.offset - _this._offset;
var maxCharWidth = Math.max(_this._context.measureText("W").width, _this._context.measureText("_").width);
_this._spaceWidthSuper = _this._context.measureText(" ").width;
_this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
_this._xMargin = Math.ceil(maxCharWidth / 32);
_this._yMargin = _this._xMargin;
// This is an approximate size, but should always be able to fit at least the maxCharCount
var totalEstSurface = (Math.ceil(_this._lineHeightSuper) + (_this._yMargin * 2)) * (Math.ceil(maxCharWidth) + (_this._xMargin * 2)) * maxCharCount;
var edge = Math.sqrt(totalEstSurface);
var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
// Create the texture that will store the font characters
_this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
var textureSize = _this.getSize();
_this.hasAlpha = _this._signedDistanceField === false;
// Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
_this._canvas = document.createElement("canvas");
_this._canvas.width = textureSize.width;
_this._canvas.height = textureSize.height;
_this._context = _this._canvas.getContext("2d");
_this._context.textBaseline = "top";
_this._context.font = font;
_this._context.fillStyle = "white";
_this._context.imageSmoothingEnabled = false;
_this._context.clearRect(0, 0, textureSize.width, textureSize.height);
// Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
// into this 2D context, then get the bitmap data, create the SDF char and push the result in the _context (which hold the whole Font Texture content)
// So you can see this context as an intermediate one, because it is.
if (_this._signedDistanceField) {
var sdfC = document.createElement("canvas");
var s = _this._sdfScale;
sdfC.width = (Math.ceil(maxCharWidth) + _this._xMargin * 2) * s;
sdfC.height = (Math.ceil(_this._lineHeightSuper) + _this._yMargin * 2) * s;
var sdfCtx = sdfC.getContext("2d");
sdfCtx.scale(s, s);
sdfCtx.textBaseline = "top";
sdfCtx.font = font;
sdfCtx.fillStyle = "white";
sdfCtx.imageSmoothingEnabled = false;
_this._sdfCanvas = sdfC;
_this._sdfContext = sdfCtx;
}
_this._currentFreePosition = BABYLON.Vector2.Zero();
// Add the basic ASCII based characters
for (var i = 0x20; i < 0x7F; i++) {
var c = String.fromCharCode(i);
_this.getChar(c);
}
_this.update();
return _this;
//this._saveToImage("");
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {\n if (maxCharCount === void 0) { maxCharCount = 200; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n if (superSample === void 0) { superSample = false; }\n if (signedDistanceField === void 0) { signedDistanceField = false; }\n _super.call(this, null, scene, true, false, samplingMode);\n this._charInfos = {};\n this._curCharCount = 0;\n this._lastUpdateCharCount = -1;\n this._usedCounter = 1;\n this.name = name;\n this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this._sdfScale = 8;\n this._signedDistanceField = signedDistanceField;\n this._superSample = false;\n // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result\n if (superSample || signedDistanceField) {\n var sfont = this.getSuperSampleFont(font);\n if (sfont) {\n this._superSample = true;\n font = sfont;\n }\n }\n // First canvas creation to determine the size of the texture to create\n this._canvas = document.createElement(\"canvas\");\n this._context = this._canvas.getContext(\"2d\");\n this._context.font = font;\n this._context.fillStyle = \"white\";\n this._context.textBaseline = \"top\";\n this._cachedFontId = null;\n var res = this.getFontHeight(font);\n this._lineHeightSuper = res.height + 4;\n this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;\n this._offset = res.offset - 1;\n this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...\n this._yMargin = this._xMargin;\n var maxCharWidth = this._context.measureText(\"W\").width;\n this._spaceWidthSuper = this._context.measureText(\" \").width;\n this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;\n // This is an approximate size, but should always be able to fit at least the maxCharCount\n var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;\n var edge = Math.sqrt(totalEstSurface);\n var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));\n // Create the texture that will store the font characters\n this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);\n var textureSize = this.getSize();\n this.hasAlpha = this._signedDistanceField === false;\n // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)\n this._canvas = document.createElement(\"canvas\");\n this._canvas.width = textureSize.width;\n this._canvas.height = textureSize.height;\n this._context = this._canvas.getContext(\"2d\");\n this._context.textBaseline = \"top\";\n this._context.font = font;\n this._context.fillStyle = \"white\";\n this._context.imageSmoothingEnabled = false;\n this._context.clearRect(0, 0, textureSize.width, textureSize.height);\n // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times\n // into this 2D context, then get the bitmap data, create the sdf char and push the result in the _context (which hold the whole Font Texture content)\n // So you can see this context as an intermediate one, because it is.\n if (this._signedDistanceField) {\n var sdfC = document.createElement(\"canvas\");\n var s = this._sdfScale;\n sdfC.width = maxCharWidth * s;\n sdfC.height = this._lineHeightSuper * s;\n var sdfCtx = sdfC.getContext(\"2d\");\n sdfCtx.scale(s, s);\n sdfCtx.textBaseline = \"top\";\n sdfCtx.font = font;\n sdfCtx.fillStyle = \"white\";\n sdfCtx.imageSmoothingEnabled = false;\n this._sdfCanvas = sdfC;\n this._sdfContext = sdfCtx;\n }\n this._currentFreePosition = BABYLON.Vector2.Zero();\n // Add the basic ASCII based characters\n for (var i = 0x20; i < 0x7F; i++) {\n var c = String.fromCharCode(i);\n this.getChar(c);\n }\n this.update();\n }",
"function FontTexture(name, font, scene, maxCharCount, samplingMode) {\n if (maxCharCount === void 0) { maxCharCount = 200; }\n if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }\n _super.call(this, null, scene, true, false, samplingMode);\n this._charInfos = {};\n this._curCharCount = 0;\n this._lastUpdateCharCount = -1;\n this._usedCounter = 1;\n this.name = name;\n this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;\n this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;\n // First canvas creation to determine the size of the texture to create\n this._canvas = document.createElement(\"canvas\");\n this._context = this._canvas.getContext(\"2d\");\n this._context.font = font;\n this._context.fillStyle = \"white\";\n var res = this.getFontHeight(font);\n this._lineHeight = res.height;\n this._offset = res.offset - 1;\n var maxCharWidth = this._context.measureText(\"W\").width;\n this._spaceWidth = this._context.measureText(\" \").width;\n // This is an approximate size, but should always be able to fit at least the maxCharCount\n var totalEstSurface = this._lineHeight * maxCharWidth * maxCharCount;\n var edge = Math.sqrt(totalEstSurface);\n var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));\n // Create the texture that will store the font characters\n this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);\n var textureSize = this.getSize();\n // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)\n this._canvas = document.createElement(\"canvas\");\n this._canvas.width = textureSize.width;\n this._canvas.height = textureSize.height;\n this._context = this._canvas.getContext(\"2d\");\n this._context.textBaseline = \"top\";\n this._context.font = font;\n this._context.fillStyle = \"white\";\n this._context.imageSmoothingEnabled = false;\n this._currentFreePosition = BABYLON.Vector2.Zero();\n // Add the basic ASCII based characters\n for (var i = 0x20; i < 0x7F; i++) {\n var c = String.fromCharCode(i);\n this.getChar(c);\n }\n this.update();\n }",
"createTexture(textureOptions = {}) {\n // create a new texture with the specified options\n const texture = new Texture(this.renderer, Object.assign(textureOptions, this._texturesOptions));\n // add the texture to the mesh\n texture.addParent(this);\n\n return texture;\n }",
"constructor(texture = null, fontData = null) {\n if (!BitmapFont.sDefaultOptions)\n BitmapFont.sDefaultOptions = new TextOptions()\n // if no texture is passed in, we create the minimal, embedded font\n if (!texture && !fontData) {\n const miniBitmapFont = getMiniBitmapFont()\n texture = miniBitmapFont.texture\n fontData = miniBitmapFont.fontData\n } else if (!texture || !fontData) {\n throw new Error(\n `[ArgumentError] Set both of the 'texture' and 'fontData' arguments\n to valid objects or leave both of them null.`\n )\n }\n\n const { CHAR_MISSING } = BitmapFont\n\n this._name = 'unknown'\n this._lineHeight = this._size = this._baseline = 14\n this._offsetX = this._offsetY = this._padding = 0.0\n this._texture = texture\n this._chars = new Map()\n this._helperImage = new Image(texture)\n this._type = BitmapFontType.STANDARD\n this._distanceFieldSpread = 0.0\n\n this.addChar(CHAR_MISSING, new BitmapChar(CHAR_MISSING, null, 0, 0, 0))\n\n this.parseFontData(fontData)\n }",
"constructor(textureSrc){\n this.textureSrc = textureSrc;\n }",
"SetTexture() {}",
"createTexture(text, options = {}) {\n let { noOffsets, noSpaces } = options;\n let canvas = document.createElement(\"canvas\");\n let context = canvas.getContext(\"2d\");\n let height = canvas.height = this.data.height;\n\n // Calculates the width of the canvas based on the text and the font\n let width = canvas.width = _.reduce(text, (width, c) => {\n // No-space option means that the characters will be\n // drawn with no any space between them\n if (noSpaces) {\n return width + this.getCharSprite(c).width;\n }\n\n return width + this.data.chars[c].width;\n }, 0);\n\n // A custom size can be specified for a font as well\n if (this.size) {\n let ratio = this.size / this.data.size;\n canvas.height *= ratio;\n canvas.width *= ratio;\n context.scale(ratio, ratio);\n }\n\n // No we are going to draw each char on the canvas individually,\n // naturally, there should be an offset after we draw each character.\n // This variable will be used to calculate the offset\n let offset = 0;\n\n // Get for each char\n _.map(text, (char) => {\n return this.getCharSprite(char);\n })\n // Start drawing each char on the canvas\n .forEach((charSprite, index) => {\n let charData = this.data.chars[text.charAt(index)];\n\n // Each char in the font xml has a native offset in addition to its rectangle.\n // This option will disable the calculation of the native offset\n if (noOffsets) {\n charSprite.draw(context, offset);\n }\n else {\n charSprite.draw(context, offset + charData.offset.x, charData.offset.y);\n }\n\n if (noSpaces) {\n offset += charSprite.width;\n }\n else {\n offset += charData.width;\n }\n\n // A color for the font can be specified as well\n if (this.color) {\n let overlayCanvas = document.createElement(\"canvas\");\n let overlayContext = overlayCanvas.getContext(\"2d\");\n overlayCanvas.width = width;\n overlayCanvas.height = height;\n overlayContext.beginPath();\n overlayContext.rect(0, 0, width, height);\n overlayContext.fillStyle = this.color;\n overlayContext.fill();\n\n context.save();\n context.globalCompositeOperation = \"source-in\";\n context.drawImage(overlayCanvas, 0, 0);\n context.restore();\n }\n });\n\n // The canvas will be treated like an image\n return canvas;\n }",
"function RenderTexture()\n{\n //*************\n // Data members\n //*************\n var m_Name = 'test';\n var m_FBO;\n var m_ColorTexture;\n var m_DepthTexture;\n \n //**********\n // Accessors\n //**********\n this.getName = function() {return m_Name ;};\n this.getFBO = function() {return m_FBO ;};\n this.getColorTexture = function() {return m_ColorTexture;};\n this.getDepthTexture = function() {return m_DepthTexture;};\n\n this.setName = function(aName ) {m_Name = aName ;};\n this.setFBO = function(aFBO ) {m_FBO = aFBO ;};\n this.setColorTexture = function(aColorTexture) {m_ColorTexture = aColorTexture;};\n this.setDepthTexture = function(aDepthTexture) {m_DepthTexture = aDepthTexture;};\n \n //\n // TODO: think about abstracting away initialization\n //\n \n}",
"constructor() {\n /**\n * Texture width in pixels\n * @type {number}\n */\n this.width = 1;\n /**\n * Texture height in pixels\n * @type {number}\n */\n this.height = 1;\n /**\n * Buffer of texture data, each pixel is represented with 4 bytes\n * @type {Uint8Array}\n */\n this.buffer = new Uint8Array([255, 0, 255, 255]);\n /**\n * Textures that size is power of 2 can be mip mapped\n * @type {boolean}\n */\n this.isPowerOf2 = false;\n /**\n * Texture object used by WebGL2\n * @type {WebGLTexture}\n */\n this.textureObject = undefined;\n }",
"constructor(scene, text, font) {\n this.scene = scene;\n this.text = text;\n\n this.objects = [];\n \n for(var i = 0; i < this.text.length; ++i) {\n this.objects[i] = new MyRectangle(this.scene, 0, 0, 1, 1);\n }\n\n this.appearance = this.scene.defaultAppearance;\n\n var fontPath;\n font == null ? fontPath = \"assets/images/fonts/font5_1.png\" : fontPath = font;\n this.textSprite = new CGFtexture(this.scene, fontPath); //text sprite\n\n //this.spritesheet = new MySpriteSheet(this.scene, this.textSprite, 15, 8); // font sheet\n this.spritesheet = new MySpriteSheet(this.scene, this.textSprite, 16, 16);\n this.sheetSize = 16*16;\n }",
"function DigitalRainFontTexture(name, font, text, scene) {\r\n if (scene === void 0) { scene = null; }\r\n var _this = _super.call(this, scene) || this;\r\n scene = _this.getScene();\r\n if (!scene) {\r\n return _this;\r\n }\r\n _this.name = name;\r\n _this._text == text;\r\n _this._font == font;\r\n _this.wrapU = Texture.CLAMP_ADDRESSMODE;\r\n _this.wrapV = Texture.CLAMP_ADDRESSMODE;\r\n // Get the font specific info.\r\n var maxCharHeight = _this.getFontHeight(font);\r\n var maxCharWidth = _this.getFontWidth(font);\r\n _this._charSize = Math.max(maxCharHeight.height, maxCharWidth);\r\n // This is an approximate size, but should always be able to fit at least the maxCharCount.\r\n var textureWidth = _this._charSize;\r\n var textureHeight = Math.ceil(_this._charSize * text.length);\r\n // Create the texture that will store the font characters.\r\n _this._texture = scene.getEngine().createDynamicTexture(textureWidth, textureHeight, false, Texture.NEAREST_SAMPLINGMODE);\r\n //scene.getEngine().setclamp\r\n var textureSize = _this.getSize();\r\n // Create a canvas with the final size: the one matching the texture.\r\n var canvas = document.createElement(\"canvas\");\r\n canvas.width = textureSize.width;\r\n canvas.height = textureSize.height;\r\n var context = canvas.getContext(\"2d\");\r\n context.textBaseline = \"top\";\r\n context.font = font;\r\n context.fillStyle = \"white\";\r\n context.imageSmoothingEnabled = false;\r\n // Sets the text in the texture.\r\n for (var i = 0; i < text.length; i++) {\r\n context.fillText(text[i], 0, i * _this._charSize - maxCharHeight.offset);\r\n }\r\n // Flush the text in the dynamic texture.\r\n scene.getEngine().updateDynamicTexture(_this._texture, canvas, false, true);\r\n return _this;\r\n }",
"function TextureWrap(renderer, tex) {\n if (!(this instanceof TextureWrap))\n return new TextureWrap(renderer, tex)\n this.renderer = renderer\n this.texture = tex\n this._shape = [0, 0]\n}",
"constructor(texture, x = 0, y = 0, width = 10, height = 10)\n\t{\n\t\tvar atlas = texture;\n\t\tif (texture.indexOf('.') != -1) {\n\t\t\tvar parts = texture.split('.');\n\t\t\tatlas = parts[0];\n\t\t\ttexture = parts[1] + '.png';\n\t\t} else {\n\t\t\ttexture = null;\n\t\t}\n\t\tsuper(core, x, y, width, height, atlas, texture);\n\t}",
"setTexture(texture) {\n this.texture = texture;\n }",
"function Texture(width, height) {\n this.width = width;\n this.height = height;\n }",
"function BitmapFontDescriptor(bitmapFontUrl){\n //stores the webgl texture \n this.texture;\n\tthis.bitmapFontUrl = bitmapFontUrl;\n //height and width of the texture\n this.size = new Object();\n\tthis.size.height = null;\t\n\tthis.size.width = null;\n //Hash map storing character information, Key is ASCII code\n this.chars = new Object(); \n}",
"constructor() {\n /**\n * Base color texture\n */\n this.color0 = new Texture();\n /**\n * Texture that will overlay base texture (based on alpha channel)\n */\n this.color1 = new Texture();\n /**\n * Normal map texture, not used yet\n */\n this.normal0 = new Texture();\n }",
"function createATexture() {\n var tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n\n gl.texImage2D(\n gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE,\n new Uint8Array([0, 0, 255, 255, 255, 0, 0, 255, 0, 0, 255, 255, 0, 0, 255, 255])\n );\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n console.log(\"Default Texture Set\");\n}",
"function _createTexture( key )\n {\n\n // get full relative url to asset source url\n var sourceUrl = assetClass.baseUrl + assetList[ key ],\n\n // push new texture instance to the collection\n newTexture = collection[ \n collection.push( \n new Texture() ) - 1 ];\n\n // set texture name\n newTexture.id = key;\n\n // set texture group to reflect asset group\n newTexture.group = lookup.name;\n\n // set the asset classType to the texture\n newTexture.class = lookup.class;\n\n // load the texture from item's source url\n newTexture.load( sourceUrl, progressReport, _loadSuccess );\n\n }",
"function Texture(spec) {\n var that = {};\n\n //todo\n\n return that;\n }",
"function SimpleTextureLoader () {\n}",
"createSprite(width, height, text, format, options = null) {\n const charLocations = this.arrangeChars(\n width,\n height,\n text,\n format,\n options\n )\n const numChars = charLocations.length\n const smoothing = this.smoothing\n const sprite = new Sprite()\n\n for (let i = 0; i < numChars; ++i) {\n const charLocation = charLocations[i]\n const char = charLocation.char.createImage()\n char.x = charLocation.x\n char.y = charLocation.y\n char.scale = charLocation.scale\n char.color = format.color\n char.textureSmoothing = smoothing\n sprite.addChild(char)\n }\n\n BitmapCharLocation.rechargePool()\n return sprite\n }",
"function NewTexture(width, height, type, format){\n\t\tvar texture = gl.createTexture();\n\t\tgl.bindTexture(gl.TEXTURE_2D, texture);\n\t\tgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\t\tgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n\t\tgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n\t\tgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\t\tgl.texImage2D(gl.TEXTURE_2D, 0, type, width, height, 0, type, format, null);\n\t\treturn texture;\n\t}",
"create() {\r\n if (this.created)\r\n return;\r\n this.tryInit(true);\r\n const gl = this.ctx.gl;\r\n gl.bindTexture(gl.TEXTURE_2D, this._glTex);\r\n const [internalFormat, format, type] = texture_format_1.mapGLFormat(gl, this.format);\r\n gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, this.width, this.height, 0, format, type, null);\r\n this.created = true;\r\n this.updateParameters();\r\n }",
"constructor(container, def) {\n super(container, def);\n this._resolution = __1.Vector2.One();\n this._wrapU = TextureWrapMode.Repeat;\n this._wrapV = TextureWrapMode.Repeat;\n this._internal = new assetInternal_1.AssetInternal(this);\n if (!def.texture) {\n throw new Error(\"Cannot construct texture from non-texture definition\");\n }\n this.copy(def);\n }",
"function new_texture(target) {\n var texture = gl.createTexture();\n\n gl.bindTexture(target, texture);\n gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n\n if (target == gl.TEXTURE_2D) {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n } else if (target == gl.TEXTURE_CUBE_MAP) {\n _.each(gl_cubemap_faces, function(face) {\n gl.texImage2D(face, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n });\n }\n\n return texture;\n }",
"function fnMakeText (argFontURL, argText, argX, argY, argZ) {\n var loader = new THREE.FontLoader();\n\tloader.load (\n argFontURL,\n function (response) {\n\t oGlobalFont = response;\n // Create mesh only when ready\n fnCreateText (argText, argX, argY, argZ); // Fwd args\n \t } // End inner anon function\n ); // End .load\n} // End function",
"function loadTexture() {\n\n console.log(\"loading Texture\");\n\n var image = new Image();\n\n // create a texture object\n lennaTxt.textureObj = gl.createTexture();\n\n image.onload = function () {\n\n initTexture(image, lennaTxt.textureObj);\n\n // make sure there is a redraw after the loading of the texture\n draw();\n\n };\n\n image.src = \"lena512.png\";\n\n}",
"function Texture(obj) {\n this.idx = obj.idx;\n this.atlases = [];\n this.atlasProgress = {};\n this.loadedAtlases = 0;\n this.onProgress = obj.onProgress;\n this.onLoad = obj.onLoad;\n this.canvas = null;\n this.ctx = null;\n this.load();\n}",
"initTexture(path){\n //var index = this.texture.length;\n this.texture = this.gl.createTexture();\n this.texture.image = new Image();\n var self = this;\n this.texture.image.onload = function(){\n self.handleLoadedTexture(self.texture);\n }\n this.texture.image.src = path;\n }"
]
| [
"0.7482161",
"0.73678553",
"0.7165617",
"0.7147427",
"0.6987609",
"0.6833418",
"0.67857116",
"0.6765549",
"0.6721022",
"0.66958845",
"0.66625774",
"0.66583985",
"0.6651396",
"0.66148245",
"0.65469986",
"0.6533586",
"0.65244186",
"0.64643025",
"0.6458663",
"0.6425966",
"0.6403143",
"0.63286877",
"0.6320835",
"0.63183105",
"0.6288175",
"0.62429637",
"0.62409043",
"0.62334555",
"0.62331045",
"0.6224282"
]
| 0.75199157 | 0 |
Construct a WireFrameGroup2D object | function WireFrameGroup2D(id, defaultColor) {
if (id === void 0) { id = null; }
if (defaultColor === void 0) { defaultColor = null; }
this._id = (id == null) ? BABYLON.Tools.RandomId() : id;
this._uid = BABYLON.Tools.RandomId();
this._defaultColor = (defaultColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : defaultColor;
this._buildingStrip = false;
this._vertices = new Array();
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function WireFrame2D(wireFrameGroups, settings) {\n var _this = this;\n if (!settings) {\n settings = {};\n }\n _this = _super.call(this, settings) || this;\n _this._wireFrameGroups = new BABYLON.StringDictionary();\n for (var _i = 0, wireFrameGroups_1 = wireFrameGroups; _i < wireFrameGroups_1.length; _i++) {\n var wfg = wireFrameGroups_1[_i];\n _this._wireFrameGroups.add(wfg.id, wfg);\n }\n _this._vtxTransparent = false;\n if (settings.size != null) {\n _this.size = settings.size;\n }\n _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;\n return _this;\n }",
"constructor() {\n this._out = PIXI.GroupD8;\n }",
"function Group2D(settings) {\n var _this = this;\n if (settings == null) {\n settings = {};\n }\n if (settings.origin == null) {\n settings.origin = new BABYLON.Vector2(0, 0);\n }\n _this = _super.call(this, settings) || this;\n var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));\n if (!(_this instanceof BABYLON.WorldSpaceCanvas2D)) {\n _this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;\n _this._trackedNodeOffset = (settings.trackNodeOffset == null) ? null : settings.trackNodeOffset;\n if (_this._trackedNode && _this.owner) {\n _this.owner._registerTrackedNode(_this);\n }\n }\n _this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;\n var rd = _this._renderableData;\n if (rd) {\n rd._noResizeOnScale = (_this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;\n }\n _this.size = size;\n _this._viewportPosition = BABYLON.Vector2.Zero();\n _this._viewportSize = BABYLON.Size.Zero();\n return _this;\n }",
"constructor(group = {}) {\n if (!group.sketchObject) {\n // eslint-disable-next-line no-param-reassign\n group.sketchObject = Factory.createNative(Group)\n .alloc()\n .initWithFrame(new Rectangle(0, 0, 100, 100).asCGRect())\n }\n\n super(group)\n }",
"createWorldGroupBB () {\n var worldGroupBorders = new Array(this.wmoGroupArray.length);\n var volumeWorldGroupBorders = new Array(this.wmoGroupArray.length);\n for (var i = 0; i < this.wmoGroupArray.length; i++) {\n var groupInfo = this.wmoObj.groupInfos[i];\n var bb1 = groupInfo.bb1,\n bb2 = groupInfo.bb2;\n\n var bb1vec = vec4.fromValues(bb1.x, bb1.y, bb1.z, 1);\n var bb2vec = vec4.fromValues(bb2.x, bb2.y, bb2.z, 1);\n\n var worldAABB = mathHelper.transformAABBWithMat4(this.placementMatrix, [bb1vec, bb2vec]);\n\n\n worldGroupBorders[i] = worldAABB;\n volumeWorldGroupBorders[i] = worldAABB.slice(0);\n }\n\n this.worldGroupBorders = worldGroupBorders;\n this.volumeWorldGroupBorders = volumeWorldGroupBorders;\n }",
"bonus2Builder() {\n this.bonus2Group = this.add.physicsGroup();\n // name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY\n this.tileMap.createFromObjects(\n this.objects.layer,\n \"bonus2\",\n this.objects.spritesheet,\n 3,\n true,\n false,\n this.bonus2Group\n );\n }",
"function LayerGroup() {\n\n\tthis.isGroup = true;\n\tthis.thickness = undefined;\n\n\tthis.members = [];\n\n\tthis.createMembers();\n\n}",
"function Layer() {\n\t\tthis.oldMbbs = new Mbbs();\t\t\t\t\t// oldMbbs\n\t\tthis.mbbs = new Mbbs();\t\t\t\t\t\t// mbbs\n\t\tthis.gobjs = [];\t\t\t\t\t\t\t// gobjs\n\t\tthis.savedState = 0;\n\t\tthis.created = 2*tick + asyncPhase;\n\t\tthis.lastUpdated = 0;\n\t\tthis.lastReorder = 0;\n\t\tthis.opacity = 1;\t\t\t\t\t\t\t// {joj 2/10/16}\n\t\tthis.flags = 0;\t\t\t\t\t\t\t\t// {joj 17/10/16}\n\t\tif (nlayer == 0) {\n\t\t\tthis.canvas = canvas;\n\t\t\tthis.ctx = ctx;\n\t\t} else {\n\t\t\tthis.canvas = document.createElement(\"canvas\");\n\t\t\tthis.canvas.style.width = canvas.style.width;\t\t// this way keeps IE happy\n\t\t\tthis.canvas.style.height = canvas.style.height;\n\t\t\tthis.canvas.style.position = \"absolute\";\n\t\t\tthis.canvas.style.zIndex = canvas.style.zIndex + nlayer;\n\t\t\tthis.canvas.style.pointerEvents = \"none\";\n\t\t\tthis.canvas.style.overflow = \"hidden\";\n\t\t\tthis.canvas.style.display = \"block\";\n\t\t\tthis.canvas.style.left = canvas.offsetLeft + \"px\";\n\t\t\tthis.canvas.style.top = canvas.offsetTop + \"px\";\n\t\t\tthis.canvas.width = canvas.width;\n\t\t\tthis.canvas.height = canvas.height;\n\t\t\tcanvas.parentNode.appendChild(this.canvas); // expects to append to <body> or <div> element\n\t\t\tthis.ctx = this.canvas.getContext(\"2d\");\n\t\t}\n\t\tlayer[nlayer] = this;\n\t\tnlayer++;\n\t\t//console.log(\"zIndex=\" + layer[nlayer - 1].canvas.style.zIndex);\n\t}",
"create(x,y) {\n this.group.create(x + this.width/2, y + this.height/2, this.image);\n }",
"bonus1Builder() {\n this.bonus1Group = this.add.physicsGroup();\n // name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY\n this.tileMap.createFromObjects(\n this.objects.layer,\n \"bonus1\",\n this.objects.spritesheet,\n 0,\n true,\n false,\n this.bonus1Group\n );\n }",
"function createLayer() {}",
"createGroup(groupName) {\n if (this.groups.hasOwnProperty(groupName))\n console.error(`Pulse Collection: Group ${groupName} already exists`);\n let group = new group_1.default(() => this);\n group.name = groupName;\n this.groups[groupName] = group;\n return group;\n }",
"constructor(params){\n\t\tsuper(params);\n\t\tthis.type = GroupAllocator.getType();\n\t}",
"smallWallBuilder() {\n this.smallWallGroup = this.add.physicsGroup();\n // name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY\n this.tileMap.createFromObjects(\n this.objects.layer,\n \"smallWall\",\n this.objects.spritesheet,\n 5,\n true,\n false,\n this.smallWallGroup\n );\n }",
"_newLayer() { return L.layerGroup(); }",
"constructor() {\n this.__groupArray__ = [];\n }",
"function create() {\n bufferSize = spec.size.x / 2;\n let rotation = (spec.startLoc.x == 0) ? Math.PI : 0;\n let spaceBetween = (spec.canvasWidth + spec.size.x) / (spec.numGroups);\n\n for(let i = 0; i < spec.numGroups; i++){\n let groupBuffer = spaceBetween * i;\n for(let j = 0; j < spec.groupSize; j++){\n let spacing = (j * spec.size.x + groupBuffer) * spec.direction;\n let turtle = {\n center: { x: spec.startLoc.x + spacing, y: spec.startLoc.y },\n size: spec.size,\n direction: {x: spec.direction, y: 0},\n speed: spec.speed, // gridlengths per second\n rotation: rotation,\n spriteIndex: 0,\n spriteTime: spec.spriteTime,\n animationTime: i*spec.spriteTime[0],\n subAnimationTime: 0,\n subAnimationSpriteTime: [200, 500],\n subAnimationIndex: 0,\n level: spec.level,\n };\n turtles[nextTurtle++] = turtle;\n }\n }\n }",
"function wAddCuadrom2Layer(id)\t\t//\tcrea el bloque cuadromino y lo agrega al layer\n{\n\tif (DEBUG)\n\t{\n\t\tconsole.log('linea 3151, id: ' + id );\n\t\tconsole.log('linea 3152, wCuadromGroup: ' + wCuadromGroup );\n\t\tconsole.log('linea 3153, wCuadromGroup[id].x: ' + wCuadromGroup.x );\n\t\tconsole.log('linea 3153, wCuadromGroup[id].y: ' + wCuadromGroup[id].y );\n\t}\n\t//\twCreateCuadrado(wCuadromGroup[id]);\n\twCreateCuadrado(wCuadromGroup);\n\n\tfor(var g = 0; g < wPolyCuadrom.length; g++) {\n\t\t//\tgBoardLayer.add(gPolyGroup[g].poly);\n\t\tgBoardLayer.add(wCuadromGroup[0].poly);\n\t}\n}",
"function create_layer() {\n let new_layer = document.createElement('canvas');\n new_layer.width = canvas.width;\n new_layer.height = canvas.height;\n\n return new_layer;\n }",
"AddGroup(w, h, position) {\n let self = this;\n this.Group = new Konva.Group({\n id: \"gondola_group_\" + self.ID,\n name: \"gondola_group\",\n x: position.x,\n y: position.y,\n width: w,\n height: h\n });\n\n this.Layer.add(this.Group);\n }",
"constructor() {\r\n super();\r\n this.setMetadata(CTGroupTileMetadata.instance);\r\n }",
"static createDeviceGroup(payload) {\n return HttpClient.post(`${ENDPOINT}devicegroups`, payload)\n .map(toDeviceGroupModel);\n }",
"function createBlockConstructor() {\n var graphics = new PIXI.Graphics();\n graphics.beginFill(COLORS.BLUE);\n graphics.drawRoundedRect(0,0,DIM,DIM,2)\n graphics.endFill();\n graphics.color = COLORS.BLUE\n graphics.interactive = true\n console.log(\"graphics dims\",graphics.width,graphics.height)\n graphics.on('pointerdown',() => {\n setTimeout(()=>{newBlock(graphics.width,graphics.height,constructorBlock.x+constructorBlock.width/2,constructorBlock.y+constructorBlock.height/2)},100)\n })\n return graphics\n}",
"badGuyBuilder() {\n this.badGuyGroup = this.add.physicsGroup();\n // name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY\n this.tileMap.createFromObjects(\n this.objects.layer,\n \"badguy\",\n this.objects.spritesheet,\n 7,\n true,\n false,\n this.badGuyGroup\n );\n }",
"speedUpBuilder() {\n this.speedUpGroup = this.add.physicsGroup();\n // name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY\n this.tileMap.createFromObjects(\n this.objects.layer,\n \"fast\",\n this.objects.spritesheet,\n 2,\n true,\n false,\n this.speedUpGroup\n );\n }",
"toGroup (groupName, obj) {\r\n if (typeof(this.Groups[groupName])=='undefined'){\r\n this.Groups[groupName] = new THREE.Object3D();\r\n if (this.Draw)\r\n this.WG.scene.add(this.Groups[groupName])\r\n }\r\n\r\n this.Groups[groupName].add(obj)\r\n }",
"constructor(startFrame, endFrame, bitType) {\n this.startFrame = startFrame;\n this.endFrame = endFrame;\n this.bitType = bitType;\n }",
"slowDownBuilder() {\n this.slowDownGroup = this.add.physicsGroup();\n // name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY\n this.tileMap.createFromObjects(\n this.objects.layer,\n \"slow\",\n this.objects.spritesheet,\n 1,\n true,\n false,\n this.slowDownGroup\n );\n }",
"function buildBusStop2(){\r\n for(var i=0; i<length; i++){\r\n allData[i] = new busStop(stopName[i], stopId[i], stopLat[i], stopLon[i], distance[i]);\r\n }\r\n }",
"function Group(grp, layer, options, x, y, ix, iy, iw, ih) {\n\t\tRectangle.call(this, grp, layer, options, 0, 0, x, y, ix, iy, iw, ih, 0, 0, \"\");\n\t\tthis.gobjs = [];\n\t}"
]
| [
"0.74495625",
"0.6265473",
"0.5944891",
"0.5894844",
"0.5858623",
"0.5729615",
"0.5725358",
"0.5231564",
"0.5230764",
"0.52303684",
"0.52231187",
"0.52165115",
"0.5191939",
"0.5152477",
"0.51376414",
"0.50719154",
"0.50400424",
"0.5020096",
"0.49820948",
"0.49797887",
"0.49751666",
"0.49499574",
"0.49197924",
"0.49164963",
"0.49132797",
"0.48998508",
"0.48950943",
"0.48882437",
"0.4875705",
"0.48543167"
]
| 0.7377141 | 1 |
Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below) | function Lines2D(points, settings) {
var _this = this;
if (!settings) {
settings = {};
}
_this = _super.call(this, settings) || this;
_this._fillVB = null;
_this._fillIB = null;
_this._borderVB = null;
_this._borderIB = null;
_this._boundingMin = null;
_this._boundingMax = null;
var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
var startCap = (settings.startCap == null) ? 0 : settings.startCap;
var endCap = (settings.endCap == null) ? 0 : settings.endCap;
var closed = (settings.closed == null) ? false : settings.closed;
_this.points = points;
_this.fillThickness = fillThickness;
_this.startCap = startCap;
_this.endCap = endCap;
_this.closed = closed;
return _this;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"createLines() {\n stroke(this.stroke);\n strokeWeight(this.strokeWeight);\n fill(this.color);\n ellipse(this.head_x, this.head_y, 50);\n ellipse(this.eye_x, this.eye_y, 15);\n line(this.x, this.y, this.head_x, this.head_y);\n\n }",
"function Lines(){}",
"function createPlugLines(startX, startY, endX, endY){\n\twireData.lines_arr.push({lines:[], drawLine:0});\n\t\n\taddPoint(startX, startY, true);\n\taddPoint(startX, startY, false);\n\taddPoint(startX, startY, false);\n\taddPoint(startX, startY, false);\n\taddPoint(endX, endY, true);\n\t\n\twireData.lines_arr[wireData.lineNum].drawLine = new createjs.Shape();\n\twirePlugLineContainer.addChild(wireData.lines_arr[wireData.lineNum].drawLine);\n\t\n\twireData.lineNum++;\n}",
"drawLines () {\n const halfW = Math.ceil(this.width/2);\n const halfH = Math.ceil(this.height/2);\n this.graphics.s(this.color);\n for (var i = -halfW; i <= halfW; i+=this.blockSize) {\n this.graphics.mt(i, -halfH).lt(i, halfH);\n }\n for (var i = -halfH; i <= halfH; i+=this.blockSize) {\n this.graphics.mt(-halfH, i).lt(halfH, i);\n }\n }",
"function Line() {}",
"function Line() {}",
"function Line() {}",
"function Line2(grp, layer, options, pen) {\n\t\tlet arg4 = arguments[4] || 0;\n\t\tlet arg5 = arguments[5] || 0;\n\t\tlet a = [grp, layer, options, pen, arg4, arg5, 0, 0];\n\t\tfor (let i = 6; i < arguments.length; i += 2) {\n\t\t\tif (options & ABSOLUTE) {\n\t\t\t\ta.push(arguments[i] - arg4);\t\t// make ABSOLUTE for Line!\n\t\t\t\ta.push(arguments[i + 1] - arg5);\n\t\t\t} else {\n\t\t\t\ta.push(arguments[i]);\t\t\t\t// still RELATIVE for Line\n\t\t\t\ta.push(arguments[i + 1]);\n\t\t\t}\n\t\t}\n\t\tLine.apply(this, a);\n\t}",
"buildShapes() {\n // Create two two-dimension arrays for storing the type of horizontal and vertical lines\n let hLineType = [], vLineType = [];\n for (let i = 0; i <= this.nRows; i++) {\n hLineType[i] = [];\n vLineType[i] = [];\n }\n\n for (let row = 0; row < this.nRows; row++) {\n for (let col = 0; col < this.nCols; col++) {\n hLineType[row][col] = row === 0 ? 0 : 1 + (this.randomLines ? Math.round(Math.random() * 9) : row + col) % 2;\n vLineType[row][col] = col === 0 ? 0 : 1 + (this.randomLines ? Math.round(Math.random() * 9) : col + row + 1) % 2;\n if (col === this.nCols - 1)\n vLineType[row][col + 1] = 0;\n if (row === this.nRows - 1)\n hLineType[row + 1][col] = 0;\n }\n }\n\n const w = 1 / this.nCols, h = 1 / this.nRows;\n for (let r = 0; r < this.nRows; r++) {\n for (let c = 0; c < this.nCols; c++) {\n const x = w * c;\n const y = h * r;\n const sd = new Path([new PathStroke('M', [x, y])]);\n this.hLine(sd, hLineType[r][c], x + 0, y + 0, w, h, false);\n this.vLine(sd, vLineType[r][c + 1], x + w, y + 0, w, h, false);\n this.hLine(sd, hLineType[r + 1][c], x + w, y + h, w, h, true);\n this.vLine(sd, vLineType[r][c], x + 0, y + h, w, h, true);\n sd.addStroke(new PathStroke('X'));\n sd.calcEnclosingRect();\n // Save the Path in `shapeData`\n this.shapeData[r * this.nCols + c] = sd;\n }\n }\n this.initiated = true;\n }",
"function renderLine(props) {\n const {\n debug,\n primitive = \"lines\",\n scaleInvariant = false,\n depth,\n blend: blend$$1\n } = props;\n const numInputPoints = props.points.length;\n\n if (numInputPoints < 2) {\n return;\n }\n\n const alreadyClosed = numInputPoints > 2 && pointsEqual(props.points[0], props.points[numInputPoints - 1]); // whether the first point needs to be duplicated after the last point\n\n const shouldClose = !alreadyClosed && props.closed;\n const pointData = fillPointArray(props.points, alreadyClosed, shouldClose);\n positionBuffer1({\n data: pointData,\n usage: \"dynamic\"\n });\n positionBuffer2({\n data: pointData,\n usage: \"dynamic\"\n });\n const monochrome = !(props.colors && props.colors.length);\n const colorData = fillColorArray(props.color, props.colors, monochrome, shouldClose);\n colorBuffer$$1({\n data: colorData,\n usage: \"dynamic\"\n });\n const joined = primitive === \"line strip\";\n const effectiveNumPoints = numInputPoints + (shouldClose ? 1 : 0);\n const instances = joined ? effectiveNumPoints - 1 : Math.floor(effectiveNumPoints / 2); // fill instanced pose buffers\n\n const {\n poses\n } = props;\n const hasInstancedPoses = !!poses && poses.length > 0;\n\n if (hasInstancedPoses && poses) {\n if (instances !== poses.length) {\n console.error(`Expected ${instances} poses but given ${poses.length} poses: will result in webgl error.`);\n return;\n }\n\n const {\n positionData,\n rotationData\n } = fillPoseArrays(instances, poses);\n posePositionBuffer({\n data: positionData,\n usage: \"dynamic\"\n });\n poseRotationBuffer({\n data: rotationData,\n usage: \"dynamic\"\n });\n }\n\n render({\n debug,\n depth,\n blend: blend$$1\n }, () => {\n // Use Object.assign because it's actually faster than babel's object spread polyfill.\n command(Object.assign({}, props, {\n joined,\n primitive: \"triangle strip\",\n alpha: debug ? 0.2 : 1,\n monochrome,\n instances,\n scaleInvariant,\n hasInstancedPoses\n }));\n\n if (debug) {\n command(Object.assign({}, props, {\n joined,\n primitive: \"line strip\",\n alpha: 1,\n monochrome,\n instances,\n scaleInvariant,\n hasInstancedPoses\n }));\n }\n });\n }",
"function LineSymbol()\n{\n\tthis.first = [[1],[1],[1],[1]];\n\tthis.second = [[1,1,1,1]];\n\tthis.blocks = [this.first,this.second];\n\tthis.cur = 0;\n\tthis.color = 0;\n\tthis.x = 5;\n\tthis.y = -4;\n}",
"function mxShapeElectricalDualInLineIC(bounds, fill, stroke, strokewidth)\n{\n\tmxShape.call(this);\n\tthis.bounds = bounds;\n\tthis.fill = fill;\n\tthis.stroke = stroke;\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\n}",
"function Line(){}",
"function Line(){}",
"function line()\n {\n gl.useProgram(program2);\n var linesVertices = new Float32Array([\n //x,y //r,g,b\n -0.15,0.5, 1.0, 1.0, 0.0,\n 0.15,0.5, 1.0, 1.0, 0.0,\n 0.05,0.3, 1.0, 1.0, 0.0,\n -0.05,0.3, 1.0, 1.0, 0.0,\n -0.05,0.1, 1.0, 1.0, 0.0,\n 0.05,0.1, 1.0, 1.0, 0.0,\n 0.15,0.0, 1.0, 1.0, 0.0,\n 0.05,-0.1, 1.0, 1.0, 0.0,\n -0.05,-0.1, 1.0, 1.0, 0.0,\n -0.05,-0.3, 1.0, 1.0, 0.0,\n 0.05,-0.3, 1.0, 1.0, 0.0,\n 0.15,-0.5, 1.0, 1.0, 0.0,\n -0.15,-0.5, 1.0, 1.0, 0.0\n ]);\n\n var linesVerticesBufferObject = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, linesVerticesBufferObject);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(linesVertices), gl.STATIC_DRAW);\n\n var vPosition = gl.getAttribLocation(program2, 'vPosition');\n var vColor = gl.getAttribLocation(program2, 'vColor');\n gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, gl.FALSE, 5 * Float32Array.BYTES_PER_ELEMENT, 0);\n gl.vertexAttribPointer(vColor, 3, gl.FLOAT, gl.FALSE, 5 * Float32Array.BYTES_PER_ELEMENT, 2 * Float32Array.BYTES_PER_ELEMENT);\n\n gl.enableVertexAttribArray(vPosition);\n gl.enableVertexAttribArray(vColor);\n\n theta += Math.PI * 0.0127; // 0.0NRP\n gl.uniform1f(thetaLoc2, theta);\n }",
"function Rem_Lines() {\n this.initialize.apply(this, arguments);\n}",
"function generateLines() {\n // Margin is Restfläche nach generieren aller Lines\n let linesMargin = width / drawingParams.linesCnt;\n let lines = [];\n for(cnt = 1; cnt < drawingParams.linesCnt; cnt++) {\n let posX1 = cnt*linesMargin;\n let posY1 = 0;\n let posX2 = cnt*linesMargin;\n let posY2 = width;\n let brightness = map(dist(posX1, 0, width/2, 0), 0, width/2, 0, 100);\n lines.push({posX1, posY1, posX2, posY2, brightness});\n } \n return lines;\n}",
"function lines(width, height, w, h) {\n for (let i = 0; i < h; i++) {\n //horizontal lines\n context.fillStyle = \"#000000\";\n context.beginPath();\n context.moveTo(0, i * height / h);\n context.lineTo(width, i * height / h);\n context.stroke();\n }\n for (let i = 0; i < w; i++) {\n //vertical lines\n context.fillStyle = \"#000000\";\n context.beginPath();\n context.moveTo(i * width / w, 0);\n context.lineTo(i * width / w, height);\n context.stroke();\n }\n}",
"function Shape(){\n\tthis.tool = \"line\";\n\tthis.color = \"black\";\n\tthis.width = 1;\n\tthis.points = [];\n}",
"generateLine(points) {\r\n const lineFunction = Object(d3_shape__WEBPACK_IMPORTED_MODULE_4__[\"line\"])()\r\n .x(d => d.x)\r\n .y(d => d.y)\r\n .curve(this.curve);\r\n return lineFunction(points);\r\n }",
"function makeLines() {\n\t// SVG container lines\n\tlet l1 = document.getElementById(\"line-left\"),\n\t l2 = document.getElementById(\"line-right\");\n\n\n\tlet rootPos = lMidOf(dropdowns[1]),\n\t leftLeafPos = uMidOf(dropdowns[0]),\n\t rightLeafPos = uMidOf(dropdowns[2]);\n\n\tmakeLine(l1, rootPos.mx, leftLeafPos.mx, rootPos.my, leftLeafPos.my);\n\tmakeLine(l2, rootPos.mx, rightLeafPos.mx, rootPos.my, rightLeafPos.my);\n}",
"function LineDraw(ctor) {\n this._ctor = ctor || Line_1$1;\n this.group = new graphic.Group();\n}",
"constructor(p1, p2) {\n super();\n this.type = 'line';\n this.p1 = p1;\n this.p2 = p2;\n this.edgeColor = new Color(0, 0, 0);\n this.fillColor = new Color(255, 255, 255);\n }",
"toLine(){return{x1:this[0][0],y1:this[0][1],x2:this[1][0],y2:this[1][1]}}",
"function line(x1, y1, x2, y2) {\r\n ctx.beginPath();\r\n ctx.moveTo(x1, y1); //Endpoint 1\r\n ctx.lineTo(x2, y2); //Endpoint 2\r\n ctx.stroke();\r\n}",
"function mxPolyline(points, stroke, strokewidth)\n{\n\tmxShape.call(this);\n\tthis.points = points;\n\tthis.stroke = stroke;\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\n}",
"function line(x1, y1, x2, y2) {\r\n ctx.beginPath();\r\n ctx.moveTo(x1, y1,); //Endpoint 1\r\n ctx.lineTo(x2, y2); //Endpoint 2\r\n ctx.stroke();\r\n}",
"function createLineLevel2(){\n\n\tresetCounter(5);\n\n\tfor(var depth=0; depth<dimensionMatrixBlock; depth++){\n\t\n\t\tmatrixBlock[depth] = new Array(numBlock);\n\t\tmatrixBlockHit[depth] = new Array(numBlock);\n\n\t\tvar arrayOdd = new Array(0);\n\t\tvar arrayEven = new Array(0);\n\n\t\tfor(var i=0; i<numBlock; i++){\n\t\t\tif(i%2 == 0)\tarrayEven.push(i);\n\t\t\telse\tarrayOdd.push(i);\n\t\t}\n\n\t\tif(depth % 2 == 0){\n\t\t\tcreateLine(depth,arrayOdd,0,new Array(0));\n\t\t}\n\t\telse{\n\t\t\tcreateLine(depth,arrayEven,1,new Array(0));\t\n\t\t}\n\n\t}\n}",
"function Lines() {\n this.lines = [];\n}",
"function Line(objectID_1, objectID_2) {\n\tthis.point1 = objectID_1;\n\tthis.point2 = objectID_2;\n\tthis.x = 0;\n\tthis.y = 0;\n\tthis.angle = 0;\n\tthis.length = 0;\n\tthis.id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5); // assign a random id for the line\n}"
]
| [
"0.701058",
"0.6726683",
"0.66893303",
"0.6530985",
"0.649167",
"0.649167",
"0.649167",
"0.6411638",
"0.638956",
"0.6389251",
"0.6370789",
"0.6341706",
"0.63241094",
"0.63241094",
"0.62645364",
"0.6252093",
"0.6245384",
"0.6244473",
"0.6229703",
"0.614161",
"0.61414486",
"0.61349756",
"0.6131131",
"0.6124583",
"0.61003596",
"0.6097348",
"0.6073974",
"0.60231495",
"0.601631",
"0.6014801"
]
| 0.6948523 | 1 |
Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space. This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon. | function WorldSpaceCanvas2D(scene, size, settings) {
var _this = this;
BABYLON.Prim2DBase._isCanvasInit = true;
var s = settings;
s.isScreenSpace = false;
if (settings.unitScaleFactor != null) {
s.size = size.multiplyByFloats(settings.unitScaleFactor, settings.unitScaleFactor);
}
else {
s.size = size.clone();
}
settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
}
_this = _super.call(this, scene, settings) || this;
BABYLON.Prim2DBase._isCanvasInit = false;
_this._unitScaleFactor = (settings.unitScaleFactor != null) ? settings.unitScaleFactor : 1;
_this._renderableData._useMipMap = true;
_this._renderableData._anisotropicLevel = 8;
//if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
// throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
//}
_this._trackNode = (settings.trackNode != null) ? settings.trackNode : null;
_this._trackNodeOffset = (settings.trackNodeOffset != null) ? settings.trackNodeOffset : BABYLON.Vector3.Zero();
_this._trackNodeBillboard = (settings.trackNodeBillboard != null) ? settings.trackNodeBillboard : true;
var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
_this._customWorldSpaceNode = !createWorldSpaceNode;
var id = settings ? settings.id || null : null;
// Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
var capMaxTextSize = _this.engine.getCaps().maxRenderTextureSize;
var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 1K if allowed otherwise the max allowed
if (settings.maxAdaptiveCanvasSize == null) {
_this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
}
else {
// We still clip the given value with the max allowed, the user may not be aware of these limitations
_this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
}
if (createWorldSpaceNode) {
var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, _this);
var vertexData = BABYLON.VertexData.CreatePlane({
width: size.width,
height: size.height,
sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
});
var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
_this.applyCachedTexture(vertexData, mtl);
vertexData.applyToMesh(plane, true);
mtl.specularColor = new BABYLON.Color3(0, 0, 0);
mtl.disableLighting = true;
mtl.useAlphaFromDiffuseTexture = true;
if (settings && settings.sideOrientation) {
mtl.backFaceCulling = (settings.sideOrientation === BABYLON.Mesh.DEFAULTSIDE || settings.sideOrientation === BABYLON.Mesh.FRONTSIDE);
}
plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
plane.material = mtl;
_this._worldSpaceNode = plane;
}
else {
_this._worldSpaceNode = settings.customWorldSpaceNode;
_this.applyCachedTexture(null, null);
}
_this.propertyChanged.add(function (e, st) {
if (e.propertyName !== "isVisible") {
return;
}
var mesh = _this._worldSpaceNode;
if (mesh) {
mesh.isVisible = e.newValue;
}
}, BABYLON.Prim2DBase.isVisibleProperty.flagId);
return _this;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"createCanvas() {\n const canvas = this.bGMap.createCanvas(this.id);\n\n /**\n * @type {Object} _webgl - WebGL object. Init webgl properties\n * @property {WebGLRenderingContext} _webgl.gl - The WebGLRenderingContext to be used.\n * @property {WebGLProgram} _webgl.program - The WebGLProgram to be used. \n * @property {Float32Array} _webgl.projection - The projection to be used. Deprecated in favor of better projection to work with multiple map background providers.\n * @see Diogo's thesis page 64+\n */\n this._webgl = {\n gl: null,\n program: null\n };\n\n this._webgl.gl = canvas.getContext(\"webgl\");\n window.canvas = canvas;\n this._webgl.gl.viewport(0, 0, this.bGMap.getContainer().offsetWidth, this.bGMap.getContainer().offsetHeight);\n this._webgl.gl.disable(this._webgl.gl.DEPTH_TEST);\n }",
"createCanvas() {\n\n //const canvasDiv = document.getElementById('canvasDiv');\n const canvas = document.createElement('canvas')\n document.getElementById(\"canvasDiv\").appendChild(canvas);\n canvas.height = this.height\n canvas.width = this.width\n const gl = this.gl = canvas.getContext('webgl2')\n gl.clearColor(1, 1, 1, 1) // @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/clearColor\n gl.viewport(0, 0, gl.canvas.width, gl.canvas.height) // @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/viewport\n\n }",
"function mapgen_canvas(w, h) {\n var obj = {};\n if (\"undefined\" != typeof global) {\n obj.canv = new canvas();\n } else {\n obj.canv = document.createElement(\"canvas\");\n }\n obj.cont = obj.canv.getContext(\"2d\");\n obj.canv.width = w;\n obj.canv.height = h;\n obj.cont.fillStyle = \"#fff\";\n obj.w = w;\n obj.h = h;\n return obj;\n}",
"function mapgen_canvas(w, h) {\n var obj = {};\n if (\"undefined\" != typeof global) {\n obj.canv = new canvas();\n } else {\n obj.canv = document.createElement(\"canvas\");\n }\n obj.cont = obj.canv.getContext(\"2d\");\n obj.canv.width = w;\n obj.canv.height = h;\n obj.cont.fillStyle = \"#fff\";\n obj.w = w;\n obj.h = h;\n return obj;\n}",
"function ScreenSpaceCanvas2D(scene, settings) {\n var _this = this;\n BABYLON.Prim2DBase._isCanvasInit = true;\n _this = _super.call(this, scene, settings) || this;\n return _this;\n }",
"createCanvas () {\n this.canvas.left.element = document.createElement('canvas')\n this.canvas.left.element.width = window.innerWidth / 2\n this.canvas.left.element.height = window.innerHeight\n document.getElementById('webglviewer').appendChild(this.canvas.left.element)\n\n this.canvas.right.element = document.createElement('canvas')\n this.canvas.right.element.width = window.innerWidth / 2\n this.canvas.right.element.height = window.innerHeight\n document.getElementById('webglviewer').appendChild(this.canvas.right.element)\n\n this.canvas.left.context = this.canvas.left.element.getContext('2d')\n this.canvas.right.context = this.canvas.right.element.getContext('2d')\n }",
"WorldToCanvas(worldCoords)\n {\n let canCoords = \n {\n x: worldCoords.x * this.zoom - this.x + 0.5 * this.w,\n y: worldCoords.y * this.zoom - this.y + 0.5 * this.h\n };\n return canCoords;\n }",
"function defineCanvas()\n {\n var canvas = document.getElementById(\"mainCanvas\");\n var context = canvas.getContext(\"2d\");\n canvas.width = c.CANVAS_WIDTH;\n canvas.height = c.CANVAS_HEIGHT;\n\n var bgBuffer = document.createElement(\"canvas\");\n var bgContext = bgBuffer.getContext(\"2d\");\n bgBuffer.width = c.GAME_WIDTH;\n bgBuffer.height = c.GAME_HEIGHT;\n\n world.on(\"before:render\", function() {\n context.clearRect(0, 0, c.CANVAS_WIDTH, c.CANVAS_HEIGHT);\n });\n\n world.context = context;\n world.bgBuffer = bgBuffer;\n world.bgContext = bgContext;\n }",
"create() {\n if(this.ctx !== null) {\n console.log('Canvas already created!');\n return;\n } else {\n let divWrapper = document.createElement('div');\n let canvasElem = document.createElement('canvas');\n this.parent.appendChild(divWrapper);\n divWrapper.appendChild(canvasElem);\n\n divWrapper.id = this.id;\n canvasElem.width = this.width;\n canvasElem.height = this.height;\n\n this.ctx = canvasElem.getContext('2d');\n }\n }",
"function newCanvas() {\n\t// define and resize canvas\n\tconst content = document.getElementById('content');\n content.style.height = window.innerHeight - 90; \n const canvasHtml = '<canvas id=\"canvas\" width=\"'+window.innerWidth+'\" height=\"'+(window.innerHeight-90)+'\"></canvas>';\n\tcontent.innerHTML = canvasHtml;\n \n // setup canvas\n\tconst canvas = document.getElementById('canvas');\n\tmyCanvas = new DrawingArea(canvas);\n\tmyCanvas.setOffset(0, 44);\n}",
"function worldToDevice(w_x, w_y){\n\tvar d_x = (w_x-w_X_min)*canvas.width/w_width;\n\tvar d_y = canvas.height - ((w_y-w_Y_min)*canvas.height/w_height);\n\t\n\treturn vec2(d_x, d_y);\n}",
"function createCanvas(props) {\n let {container = document.body} = props;\n\n if (typeof container === 'string') {\n container = document.getElementById(container);\n }\n\n if (!container) {\n throw Error('Deck: container not found');\n }\n\n // Add DOM elements\n const containerStyle = window.getComputedStyle(container);\n if (containerStyle.position === 'static') {\n container.style.position = 'relative';\n }\n\n const mapCanvas = document.createElement('div');\n container.appendChild(mapCanvas);\n Object.assign(mapCanvas.style, CANVAS_STYLE);\n\n const deckCanvas = document.createElement('canvas');\n container.appendChild(deckCanvas);\n Object.assign(deckCanvas.style, CANVAS_STYLE);\n\n return {container, mapCanvas, deckCanvas};\n}",
"createCanvas(width, height) {\n const canvas = document.createElement('canvas')\n const ctx = canvas.getContext('2d')\n const scale = window.devicePixelRatio\n\n this.width = width\n this.height = height\n canvas.style.width = width + 'px'\n canvas.style.height = height + 'px'\n canvas.width = Math.floor(width * scale)\n canvas.height = Math.floor(height * scale)\n ctx.scale(scale, scale)\n\n document.body.appendChild(canvas)\n return canvas\n }",
"function WebXRManagedOutputCanvas(_xrSessionManager, _options) {\n var _this = this;\n if (_options === void 0) { _options = WebXRManagedOutputCanvasOptions.GetDefaults(); }\n this._options = _options;\n this._canvas = null;\n /**\n * xr layer for the canvas\n */\n this.xrLayer = null;\n /**\n * Obseervers registered here will be triggered when the xr layer was initialized\n */\n this.onXRLayerInitObservable = new Observable();\n this._engine = _xrSessionManager.scene.getEngine();\n if (!_options.canvasElement) {\n var canvas = document.createElement(\"canvas\");\n canvas.style.cssText = this._options.newCanvasCssStyle || \"position:absolute; bottom:0px;right:0px;\";\n this._setManagedOutputCanvas(canvas);\n }\n else {\n this._setManagedOutputCanvas(_options.canvasElement);\n }\n _xrSessionManager.onXRSessionInit.add(function () {\n _this._addCanvas();\n });\n _xrSessionManager.onXRSessionEnded.add(function () {\n _this._removeCanvas();\n });\n }",
"function initCanvas(canvasSelector, w, h) {\n\n\t\tw = w || 400;\n\t\th = h || 225;\n\n\t\tvar selCanvas = document.querySelector(canvasSelector),\n\t\t\tnewCanvas,\n\t\t\tctx;\n\n\t\tif (selCanvas == null) {\n\t\t\tconsole.error(\"Canvas DOM container not found:\", canvasSelector);\n\t\t\tcanvasSelector = \"body\";\n\t\t\tselCanvas = document.querySelector(canvasSelector);\n\t\t}\n\n\t\tif (selCanvas.nodeName.toUpperCase() === \"CANVAS\") {\n\t\t\tvar explicitWidth = selCanvas.getAttribute(\"width\"),\n\t\t\t\texplicitHeight = selCanvas.getAttribute(\"height\");\n\n\t\t\tif (explicitWidth === null) {\n\t\t\t\tselCanvas.setAttribute(\"width\", w);\n\t\t\t}\n\t\t\tif (explicitHeight === null) {\n\t\t\t\tselCanvas.setAttribute(\"height\", h);\n\t\t\t}\n\t\t\tctx = selCanvas.getContext(\"2d\");\n\t\t} else {\n\t\t\tnewCanvas = document.createElement(\"canvas\");\n\t\t\tnewCanvas.setAttribute(\"width\", w);\n\t\t\tnewCanvas.setAttribute(\"height\", h);\n\t\t\tselCanvas.appendChild(newCanvas);\n\t\t\tctx = newCanvas.getContext(\"2d\");\n\t\t}\n\t\tctx.imageSmoothingEnabled = false;\n\t\tctx.mozImageSmoothingEnabled = false;\n\t\tctx.webkitImageSmoothingEnabled = false;\n\n\t\tif (!ctx) {\n\t\t\tconsole.error(\"Could not get 2D context.\");\n\t\t}\n\n\t\treturn ctx;\n\t}",
"function Renderer(canvas)\n{\n\t//The canvas element to draw to.\n\tvar _canvas = canvas;\n\t//The viewport to draw to.\n\tvar _currentViewport = undefined;\n\n\tthis.setViewport = function(viewPort) { _currentViewport = viewPort;}\n\t//TODO eventually we could have multiple layered canvases for different elements (Game, minimap, UI)\n\n\n\t//Experiment with high performance drawing by blitting an offscreen canvas to the screen for repeated identical objects (zombies)\n\tvar zombieBlitCanvas = document.createElement('canvas');\n\tvar zombieBlitCanvasContext = zombieBlitCanvas.getContext('2d');\n\tzombieBlitCanvas.height = globalVals.ZOMBIE_RADIUS * 2;\n\tzombieBlitCanvas.width = globalVals.ZOMBIE_RADIUS * 2;\n\tdrawCircle(zombieBlitCanvasContext, globalVals.ZOMBIE_RADIUS, globalVals.ZOMBIE_RADIUS, globalVals.ZOMBIE_RADIUS, 45, '#FF0000');\n\tvar zombieImage = zombieBlitCanvasContext.getImageData(0,0,globalVals.ZOMBIE_RADIUS * 2,globalVals.ZOMBIE_RADIUS * 2); \n \n \n\n\n\tthis.render = function(gameWorldObject)\n\t{\n\t\tdrawBackground();\n\t\tdrawGrid(gameWorldObject.worldWidth, gameWorldObject.worldHeight);\n\t\t\n\t\tdrawZombies(gameWorldObject.zombies);\n\t\tdrawPlayers(gameWorldObject.players);\n\t\tdrawBorder(gameWorldObject.worldWidth, gameWorldObject.worldHeight);\n\t\tdrawDebugValues(canvas);\n\t}\n\n\t//internal functions\n\n\n\tfunction drawBackground()\n\t{\n\t\t_canvas.fillStyle = '#FFFFFF';\n\t\t_canvas.fillRect(0, 0, screenWidth, screenHeight);\n\t}\n\n\tfunction drawGrid(worldWidth, worldHeight)\n\t{\n\t\t//simple grid to let player have frame of reference for movement\n\t\tvar gridSpacing = 100;\n\t\tvar gridColor = \"#999999\";\n\t\t_canvas.strokeStyle = gridColor\n\n\t\t//needs to align to world canvas, but only draw over viewport\n\t\tvar startX = -_currentViewport.getPosition().x % gridSpacing;\n\t\tif(startX < _currentViewport.getViewOffset(0,0).x) { startX += Math.floor(_currentViewport.getViewOffset(0,0).x / gridSpacing) * gridSpacing;}\n\t\tvar stopX = Math.min( _currentViewport.getDimensions().x, _currentViewport.getViewOffset(worldWidth,0).x);\n\n\t\tvar startY = -_currentViewport.getPosition().y % gridSpacing;\n\t\tif(startY < _currentViewport.getViewOffset(0,0).y) { startY+= Math.floor(_currentViewport.getViewOffset(0,0).y / gridSpacing) * gridSpacing;}\n\t\tvar stopY = Math.min( _currentViewport.getDimensions().y, _currentViewport.getViewOffset(0,worldHeight).y);\n\n\t\tfor(var i = startX; i < stopX; i += gridSpacing)\n\t\t{\n\t\t\t_canvas.beginPath();\n\t\t\t_canvas.moveTo(i, Math.max(0, _currentViewport.getViewOffset(0,0).y)); //start at top of viewport or edge of world border\n\t\t\t_canvas.lineTo(i, stopY );\n\t\t\t_canvas.stroke();\n\t\t}\n\t\t\n\t\tfor(var i = startY; i < stopY; i += gridSpacing)\n\t\t{\n\t\t\t_canvas.beginPath();\n\t\t\t_canvas.moveTo(Math.max(0, _currentViewport.getViewOffset(0,0).x),i); //start at top of viewport or edge of world border\n\t\t\t_canvas.lineTo(stopX, i );\n\t\t\t_canvas.stroke();\n\t\t}\n\n\n\t}\n\n\tfunction drawZombies(zombies)\n\t{\n\t\tvar zombieColor = '#FF0000';\n\n\t\tvar adjustedPosition;\n\t\tvar drawnZombies = 0;\n\t\tfor(var i = 0; i < zombies.length; i++)\n\t\t{\n\n\t\t\tadjustedPosition = _currentViewport.getViewOffsetFromVec(zombies[i].position);\n\n\t\t\tif(_currentViewport.isInView(zombies[i].position))\n\t\t\t{\n\t\t\t\tdrawnZombies++;\n\t\t\t\t// 'efficient' way to draw zombies\n\t\t\t\t_canvas.drawImage(zombieBlitCanvas, adjustedPosition.x - globalVals.ZOMBIE_RADIUS, adjustedPosition.y - globalVals.ZOMBIE_RADIUS);\n\t\t\t\t\n\t\t\t\t// Simple way to draw zombies\n\t\t\t\t//drawCircle(_canvas, adjustedPosition.x, adjustedPosition.y, globalVals.ZOMBIE_RADIUS, 30, zombieColor);\n\t\t\t}\n\t\t}\n\t\tdebugLog(\"#zombiesDrawn\", drawnZombies);\n\t};\n\n\tfunction drawPlayers(players)\n\t{\n\t\tvar playerColor = '#00FF00';\n\n\t\t_canvas.font = \"30px Arial\";\n\n\t\tdebugLog(\"Viewport X\" , _currentViewport.getPosition().x);\n\t\tdebugLog(\"Viewport Y\" , _currentViewport.getPosition().y);\n\n\t\tvar adjustedPosition;\n\t\tfor(var i = 0; i < players.length; i++)\n\t\t{\n\t\t\tadjustedPosition = _currentViewport.getViewOffsetFromVec(players[i].position);\n\t\t\tdrawCircle(_canvas, adjustedPosition.x, adjustedPosition.y, globalVals.PLAYER_RADIUS, 10, playerColor);\n\t\t}\n\t};\n\n\tfunction drawBorder(width, height)\n\t{\n\t\tvar adj = _currentViewport.getViewOffset;\n\t\tvar adjustedPosition;\n\n\t\t_canvas.lineStyle = \"#0000FF\"\n\t\t_canvas.beginPath();\n\t\t_canvas.moveTo(adj(0,0).x, adj(0,0).y);\n\t\t_canvas.lineTo(adj(width,0).x, adj(width,0).y);\n\t\t_canvas.lineTo(adj(width,height).x, adj(width,height).y);\n\t\t_canvas.lineTo(adj(0,height).x, adj(0,height).y);\n\t\t_canvas.lineTo(adj(0,0).x, adj(0,0).y);\n\t\t_canvas.stroke();\n\t}\n\n\n\n\t//function drawUI();\n\n\n\t//primitive functions (Move to lib?)\n\n\tfunction drawCircle(canvas, centerX, centerY, radius, sides, color) {\n\t var theta = 0;\n\t var x = 0;\n\t var y = 0;\n\n\t canvas.fillStyle = color;\n\t canvas.beginPath();\n\n\t for (var i = 0; i < sides; i++) {\n\t theta = (i / sides) * 2 * Math.PI;\n\t x = centerX + radius * Math.sin(theta);\n\t y = centerY + radius * Math.cos(theta);\n\t canvas.lineTo(x, y);\n\t }\n\n\t canvas.closePath();\n\t //canvas.stroke();\n\t canvas.fill();\n\t}\n\n}",
"function createCanvas() {\n\tvar width = arguments[0] * arguments[2];\n\tvar height = arguments[1] * arguments[2];\n\tvar can = document.createElement(\"canvas\");\n\tcan.width = width;\n\tcan.height = height;\n\tcan.style.width = width + \"px\";\n\tcan.style.height = height + \"px\";\n\treturn can;\n}",
"function draw_world(world, context) \n{\n //convert the canvas coordinate directions to cartesian coordinate direction by translating and scaling\n ctx.save();\n ctx.translate(0 , canvas_height);\n ctx.scale(1 , -1);\n world.DrawDebugData();\n ctx.restore();\n \n //write some text\n ctx.textAlign = 'right';\n ctx.fillStyle = '#fff';\n ctx.font = 'bold 15px arial';\n ctx.fillText('Rope using box2d', canvas_width - 10, canvas_height - 10);\n}",
"function CreateCanvas(r, c, l){\r\n\t \tcanvas = document.getElementById('canvas'); // get the canvas element by id\r\n\r\n\t \tcanvas.width = 800;\r\n\t \tcanvas.height= 600;\r\n\r\n\t \trows = (r)? r: 3;\r\n\t \tcols = (c)? c: 3;\r\n\t \tlayout = (l)? l: \"V-TL2B\";\r\n\r\n //check if an get canvas context\r\n\t\tif(canvas.getContext) {\r\n\t\t\tcontext = canvas.getContext(\"2d\");\t// get the canvas context 2d\r\n\t\t\tCreateBlocks();\r\n\t\t}\r\n\t }",
"function Canvas(){\n\tconst container = document.createElement('div');\n\tcontainer.style.position = \"absolute\";\n\tcontainer.style.display = \"flex\";\n\tcontainer.style.top = container.style.bottom = container.style.left = container.style.right = 0;\n\n\tconst canvas = document.createElement('canvas');\n\tcanvas.width = 40;\n\tcanvas.height = 40;\n\tcanvas.style.margin = \"auto\";\n\tcanvas.style.imageRendering = \"pixelated\";\n\tcanvas.style.zoom = 20;\n\tcanvas.style.background = \"#333\"\n\n\tdocument.body.appendChild(container);\n\tcontainer.appendChild(canvas);\n\treturn canvas;\n}",
"function Group2D(settings) {\n var _this = this;\n if (settings == null) {\n settings = {};\n }\n if (settings.origin == null) {\n settings.origin = new BABYLON.Vector2(0, 0);\n }\n _this = _super.call(this, settings) || this;\n var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));\n if (!(_this instanceof BABYLON.WorldSpaceCanvas2D)) {\n _this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;\n _this._trackedNodeOffset = (settings.trackNodeOffset == null) ? null : settings.trackNodeOffset;\n if (_this._trackedNode && _this.owner) {\n _this.owner._registerTrackedNode(_this);\n }\n }\n _this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;\n var rd = _this._renderableData;\n if (rd) {\n rd._noResizeOnScale = (_this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;\n }\n _this.size = size;\n _this._viewportPosition = BABYLON.Vector2.Zero();\n _this._viewportSize = BABYLON.Size.Zero();\n return _this;\n }",
"function deviceToWorld(d_x, d_y){\n\tvar w_x = (w_width*d_x/canvas.width) + w_X_min;\n\tvar w_y = (w_height*(canvas.height-d_y)/canvas.height) + w_Y_min;\n\t\n\treturn vec2(w_x, w_y);\n}",
"function createCanvas(_width, _height) {\r\n let canvas = document.createElement(\"canvas\");\r\n canvas.width = _width;\r\n canvas.height = _height;\r\n document.body.appendChild(canvas);\r\n crc2 = canvas.getContext(\"2d\");\r\n}",
"function World() {\n this.canvas = document.querySelector('#pixplot-canvas');\n this.scene = this.getScene();\n this.camera = this.getCamera();\n this.renderer = this.getRenderer();\n this.controls = this.getControls();\n // this.stats = this.getStats();\n this.color = new THREE.Color();\n this.center = {};\n this.group = {};\n this.state = {\n flying: false,\n transitioning: false,\n displayed: false,\n mode: 'pan', // 'pan' || 'select'\n };\n this.elems = {\n pointSize: document.querySelector('#pointsize-range-input'),\n };\n this.addEventListeners();\n //var gl = this.canvas.getContext('webgl');\n //gl.clearColor(0.75, 0.85, 0.8, 1.0);\n //gl.clear(gl.COLOR_BUFFER_BIT);\n}",
"function CanvasView() {\n this._canvas = document.createElement('canvas');\n this._element = document.getElementById(ELEMENT_ID);\n if (!this._element) {\n this._element = document.createElement('div');\n this._element.id = ELEMENT_ID;\n document.body.insertBefore(this._element, document.body.childNodes[0] ||\n null);\n }\n\n makeAbsoluteAndFullScreen(this._element);\n makeAbsoluteAndFullScreen(this._canvas);\n this._element.appendChild(this._canvas);\n\n this._width = 0;\n this._height = 0;\n this._updateSize();\n\n window.addEventListener('resize', this._handleResize.bind(this));\n }",
"function Context() {\n Element.call(this);\n\n document.body.appendChild(this.domElement);\n\n this.domElement.setAttribute('id', 'dom-renderer');\n\n this.width = 0;\n this.height = 0;\n }",
"function combineCanvases() {\n var metric_canvas = drawCanvas(metersPerPixel, true);\n var miles_canvas = drawCanvas(metersPerPixel, false);\n\n var canvas = document.createElement(\"canvas\");\n canvas.width = canvas_width;\n canvas.height = canvas_height * 2; // multiply by 2 so we can fit both\n var ctx = canvas.getContext('2d');\n ctx.drawImage(metric_canvas, 0, 0);\n ctx.drawImage(miles_canvas, 0, canvas_height);\n\n // append to page for easy testing\n // document.body.appendChild(canvas);\n // canvas.setAttribute(\"style\",\"position: absolute; top:0;left:0;z-index:999999;width:\" + (canvas.width / 2) + \"px;height:\" + (canvas.height / 2) + \"px\");\n\n return canvas;\n }",
"function createCanvas (opt = {}) {\n // default to full screen (no width/height specified)\n const viewport = opt.viewport || [ 0, 0 ];\n\n const canvas = opt.canvas || document.createElement('canvas');\n canvas.style.position = 'absolute';\n canvas.style.top = `${viewport[0]}px`;\n canvas.style.left = `${viewport[1]}px`;\n\n // Resize the canvas with the proper device pixel ratio\n const resizeCanvas = () => {\n // default to fullscreen if viewport width/height is unspecified\n const width = typeof viewport[2] === 'number' ? viewport[2] : window.innerWidth;\n const height = typeof viewport[3] === 'number' ? viewport[3] : window.innerHeight;\n const dpr = window.devicePixelRatio;\n canvas.width = width * dpr;\n canvas.height = height * dpr;\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n };\n\n // Ensure the grab cursor appears even when the mouse is outside the window\n const setupGrabCursor = () => {\n canvas.addEventListener('mousedown', () => {\n document.documentElement.classList.remove('grabbing');\n document.documentElement.classList.add('grabbing');\n });\n window.addEventListener('mouseup', () => {\n document.documentElement.classList.remove('grabbing');\n });\n };\n\n window.addEventListener('resize', resizeCanvas);\n resizeCanvas();\n setupGrabCursor();\n return canvas;\n}",
"constructor(global) {\n this.doc = global.document;\n this.win = global.window;\n this.canvas = this.doc.createElement('canvas');\n this.ctx = this.canvas.getContext('2d');\n this.lastTime;\n this.canvas.width = 909;\n this.canvas.height = 606;\n this.doc.body.appendChild(this.canvas);\n global.ctx = this.ctx;\n }",
"function initBuffers2d(gl) {\n\n // Create a buffer for the square's positions.\n const positionBuffer = gl.createBuffer();\n\n // Select the positionBuffer as the one to apply buffer\n // operations to from here out.\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n // Now create an array of positions for the square.\n const positions = [\n 1.0, 1.0,\n -1.0, 1.0,\n 1.0, -1.0,\n -1.0, -1.0,\n ];\n\n // Now pass the list of positions into WebGL to build the\n // shape. We do this by creating a Float32Array from the\n // JavaScript array, then use it to fill the current buffer.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);\n\n return {\n position: positionBuffer,\n };\n}"
]
| [
"0.6654555",
"0.6387135",
"0.62271255",
"0.62271255",
"0.60870016",
"0.6048239",
"0.59847337",
"0.5925782",
"0.57963586",
"0.57728875",
"0.5759807",
"0.57407415",
"0.57108516",
"0.5636972",
"0.56345516",
"0.5631851",
"0.5630428",
"0.5618284",
"0.5602033",
"0.55960655",
"0.55953485",
"0.55845726",
"0.5583",
"0.55809903",
"0.5574307",
"0.55607486",
"0.55537844",
"0.55486923",
"0.5527999",
"0.5525553"
]
| 0.76380646 | 0 |
Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the bottom/left corner of the screen. ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI. All caching strategies will be available. PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5] | function ScreenSpaceCanvas2D(scene, settings) {
var _this = this;
BABYLON.Prim2DBase._isCanvasInit = true;
_this = _super.call(this, scene, settings) || this;
return _this;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function WorldSpaceCanvas2D(scene, size, settings) {\n var _this = this;\n BABYLON.Prim2DBase._isCanvasInit = true;\n var s = settings;\n s.isScreenSpace = false;\n if (settings.unitScaleFactor != null) {\n s.size = size.multiplyByFloats(settings.unitScaleFactor, settings.unitScaleFactor);\n }\n else {\n s.size = size.clone();\n }\n settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;\n if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {\n throw new Error(\"Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!\");\n }\n _this = _super.call(this, scene, settings) || this;\n BABYLON.Prim2DBase._isCanvasInit = false;\n _this._unitScaleFactor = (settings.unitScaleFactor != null) ? settings.unitScaleFactor : 1;\n _this._renderableData._useMipMap = true;\n _this._renderableData._anisotropicLevel = 8;\n //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {\n // throw new Error(\"CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas\");\n //}\n _this._trackNode = (settings.trackNode != null) ? settings.trackNode : null;\n _this._trackNodeOffset = (settings.trackNodeOffset != null) ? settings.trackNodeOffset : BABYLON.Vector3.Zero();\n _this._trackNodeBillboard = (settings.trackNodeBillboard != null) ? settings.trackNodeBillboard : true;\n var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);\n _this._customWorldSpaceNode = !createWorldSpaceNode;\n var id = settings ? settings.id || null : null;\n // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap\n var capMaxTextSize = _this.engine.getCaps().maxRenderTextureSize;\n var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 1K if allowed otherwise the max allowed\n if (settings.maxAdaptiveCanvasSize == null) {\n _this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;\n }\n else {\n // We still clip the given value with the max allowed, the user may not be aware of these limitations\n _this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);\n }\n if (createWorldSpaceNode) {\n var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, _this);\n var vertexData = BABYLON.VertexData.CreatePlane({\n width: size.width,\n height: size.height,\n sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE\n });\n var mtl = new BABYLON.StandardMaterial(id + \"_Material\", scene);\n _this.applyCachedTexture(vertexData, mtl);\n vertexData.applyToMesh(plane, true);\n mtl.specularColor = new BABYLON.Color3(0, 0, 0);\n mtl.disableLighting = true;\n mtl.useAlphaFromDiffuseTexture = true;\n if (settings && settings.sideOrientation) {\n mtl.backFaceCulling = (settings.sideOrientation === BABYLON.Mesh.DEFAULTSIDE || settings.sideOrientation === BABYLON.Mesh.FRONTSIDE);\n }\n plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();\n plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();\n plane.material = mtl;\n _this._worldSpaceNode = plane;\n }\n else {\n _this._worldSpaceNode = settings.customWorldSpaceNode;\n _this.applyCachedTexture(null, null);\n }\n _this.propertyChanged.add(function (e, st) {\n if (e.propertyName !== \"isVisible\") {\n return;\n }\n var mesh = _this._worldSpaceNode;\n if (mesh) {\n mesh.isVisible = e.newValue;\n }\n }, BABYLON.Prim2DBase.isVisibleProperty.flagId);\n return _this;\n }",
"createCanvas() {\n\n //const canvasDiv = document.getElementById('canvasDiv');\n const canvas = document.createElement('canvas')\n document.getElementById(\"canvasDiv\").appendChild(canvas);\n canvas.height = this.height\n canvas.width = this.width\n const gl = this.gl = canvas.getContext('webgl2')\n gl.clearColor(1, 1, 1, 1) // @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/clearColor\n gl.viewport(0, 0, gl.canvas.width, gl.canvas.height) // @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/viewport\n\n }",
"setupDisplay() {\n // Handles display setup if no canvas element is provided in constructor.\n if (!this.domElement) {\n const id = EzGame.randomId();\n this.domElement = document.createElement('CANVAS');\n this.domElement.id = `$game_${id}`;\n const $parent = this.parentDomElement || document.body;\n $parent.appendChild(this.domElement);\n }\n\n if (this.pixelPerfect) {\n this.domElement.style['image-rendering'] = 'pixelated';\n }\n\n this.display = this.domElement.getContext('2d'); // setup buffer display dimensions\n\n this.buffer.element.width = this.width;\n this.buffer.element.height = this.height; // setup actual display dimensions\n\n this.domElement.width = this.width;\n this.domElement.height = this.height;\n this.display.fillStyle = '#000';\n this.display.fillRect(0, 0, this.width, this.height);\n }",
"createCanvas () {\n this.canvas.left.element = document.createElement('canvas')\n this.canvas.left.element.width = window.innerWidth / 2\n this.canvas.left.element.height = window.innerHeight\n document.getElementById('webglviewer').appendChild(this.canvas.left.element)\n\n this.canvas.right.element = document.createElement('canvas')\n this.canvas.right.element.width = window.innerWidth / 2\n this.canvas.right.element.height = window.innerHeight\n document.getElementById('webglviewer').appendChild(this.canvas.right.element)\n\n this.canvas.left.context = this.canvas.left.element.getContext('2d')\n this.canvas.right.context = this.canvas.right.element.getContext('2d')\n }",
"function defineCanvas()\n {\n var canvas = document.getElementById(\"mainCanvas\");\n var context = canvas.getContext(\"2d\");\n canvas.width = c.CANVAS_WIDTH;\n canvas.height = c.CANVAS_HEIGHT;\n\n var bgBuffer = document.createElement(\"canvas\");\n var bgContext = bgBuffer.getContext(\"2d\");\n bgBuffer.width = c.GAME_WIDTH;\n bgBuffer.height = c.GAME_HEIGHT;\n\n world.on(\"before:render\", function() {\n context.clearRect(0, 0, c.CANVAS_WIDTH, c.CANVAS_HEIGHT);\n });\n\n world.context = context;\n world.bgBuffer = bgBuffer;\n world.bgContext = bgContext;\n }",
"function Screen() {\n\tthis.canvas = null;\n\tthis.context = null;\n\tthis.width = 0;\n\tthis.height = 0;\n\tthis.posX = 0; //used, but this is a hack!\n\tthis.posY = 0;\n\tthis.clearColor = \"rgb(64,64,64)\";\n\tthis.clearAlpha = 1.0; //unused\n\tthis.useTouch = false;\n}",
"function canvasToViewport(p2d) {\n\treturn {\n\t\tx: p2d[0] * viewport_size / c.width,\n\t\ty: p2d[1] * viewport_size / c.height,\n\t\tz: projection_plane_z\n\t}\n}",
"function newCanvas() {\n\t// define and resize canvas\n\tconst content = document.getElementById('content');\n content.style.height = window.innerHeight - 90; \n const canvasHtml = '<canvas id=\"canvas\" width=\"'+window.innerWidth+'\" height=\"'+(window.innerHeight-90)+'\"></canvas>';\n\tcontent.innerHTML = canvasHtml;\n \n // setup canvas\n\tconst canvas = document.getElementById('canvas');\n\tmyCanvas = new DrawingArea(canvas);\n\tmyCanvas.setOffset(0, 44);\n}",
"function createScene() {\n // create asset\n branch = Scenes.createAxisCross();\n // initialize RenderManager and transmit content\n ƒ.RenderManager.initialize();\n ƒ.RenderManager.addBranch(branch);\n ƒ.RenderManager.update();\n // initialize viewport\n camera = Scenes.createCamera(new ƒ.Vector3(3, 3, 5));\n let cmpCamera = camera.getComponent(ƒ.ComponentCamera);\n cmpCamera.projectCentral(1, 45);\n canvas = Scenes.createCanvas();\n document.body.appendChild(canvas);\n viewport = new ƒ.Viewport();\n viewport.initialize(\"TestViewport\", branch, cmpCamera, canvas);\n viewport.draw();\n }",
"createCanvas() {\n const canvas = this.bGMap.createCanvas(this.id);\n\n /**\n * @type {Object} _webgl - WebGL object. Init webgl properties\n * @property {WebGLRenderingContext} _webgl.gl - The WebGLRenderingContext to be used.\n * @property {WebGLProgram} _webgl.program - The WebGLProgram to be used. \n * @property {Float32Array} _webgl.projection - The projection to be used. Deprecated in favor of better projection to work with multiple map background providers.\n * @see Diogo's thesis page 64+\n */\n this._webgl = {\n gl: null,\n program: null\n };\n\n this._webgl.gl = canvas.getContext(\"webgl\");\n window.canvas = canvas;\n this._webgl.gl.viewport(0, 0, this.bGMap.getContainer().offsetWidth, this.bGMap.getContainer().offsetHeight);\n this._webgl.gl.disable(this._webgl.gl.DEPTH_TEST);\n }",
"function CanvasView() {\n this._canvas = document.createElement('canvas');\n this._element = document.getElementById(ELEMENT_ID);\n if (!this._element) {\n this._element = document.createElement('div');\n this._element.id = ELEMENT_ID;\n document.body.insertBefore(this._element, document.body.childNodes[0] ||\n null);\n }\n\n makeAbsoluteAndFullScreen(this._element);\n makeAbsoluteAndFullScreen(this._canvas);\n this._element.appendChild(this._canvas);\n\n this._width = 0;\n this._height = 0;\n this._updateSize();\n\n window.addEventListener('resize', this._handleResize.bind(this));\n }",
"function Screen(useTouch) {\n\tthis.canvas = null;\n\tthis.context = null;\n\tthis.width = 0;\n\tthis.height = 0;\n\tthis.posX = 0; //used, but this is a hack!\n\tthis.posY = 0;\n\tthis.clearColor = \"rgb(64,64,64)\";\n\tthis.clearAlpha = 1.0; //unused\n\tthis.useTouch = useTouch || false;\n}",
"function dipToScreenRect(window, rect) {\n return new Rectangle();\n }",
"function drawScreen()\n{\n context.save();\n context.strokeStyle=\"#aaa\";\n context.fillStyle=\"#000\";\n context.strokeRect(XOFFSET - 1, YOFFSET - 1, scope.width + 2, scope.height + 2);\n context.restore();\n}",
"initCanvas() {\n // get the html5 canvas and its context\n this.canvas = document.getElementById('canvas');\n\n this.canvas.width = SCREEN_WIDTH;\n this.canvas.height = SCREEN_HEIGHT;\n\n this.ctx = canvas.getContext('2d');\n }",
"function setupCanvas() {\n // Get the canvas set up\n var context = canvas.getContext('2d');\n if (scale) { // If we're doing autoscaling\n canvas.width = 640; // make sure canvas is full size \n canvas.height = 400;\n context.setTransform(1, 0, 0, 1, 0, 0); // Reset scaling\n context.scale(scaleX, scaleY); // Set scaling to the ST(E) graphics mode\n context.imageSmoothingEnabled = false; // Switch off interpolation\n } else {\n canvas.width = screen_width; // Otherwise set canvas to actual screen dimensions\n canvas.height = screen_height;\n }\n return context; // Return canvas context\n }",
"_createWindow() {\n const gameHeight = this._getGameHeight();\n const gameWidth = this._getGameWidth();\n const dimensions = this._calculateWindowDimensions(gameWidth, gameHeight);\n this.graphics = this.scene.add.graphics();\n\n this._createOuterWindow(\n dimensions.x,\n dimensions.y,\n dimensions.rectWidth,\n dimensions.rectHeight\n );\n this._createInnerWindow(\n dimensions.x,\n dimensions.y,\n dimensions.rectWidth,\n dimensions.rectHeight\n );\n }",
"function newCanvas() {\n //define and resize canvas\n $(\"#content\").height($(window).height() - 90);\n var canvas = '<canvas id=\"canvas\" width=\"' + $(window).width() + '\" height=\"' + ($(window).height() - 90) + '\"></canvas>';\n $(\"#content\").html(canvas);\n\n // setup canvas\n ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.strokeStyle = color;\n ctx.lineWidth = 5;\n\n // set starting point in center\n ctx.beginPath();\n x = $(window).width() / 2;\n y = ($(window).height() - 90) / 2;\n ctx.moveTo(x, y);\n\n // setup to trigger drawing on mouse or touch\n $(\"#canvas\").drawTouch();\n $(\"#canvas\").drawPointer();\n $(\"#canvas\").drawMouse();\n }",
"render(){\n this.renderingContext.fillRect(0, 0, this.renderingCanvas.width, this.renderingCanvas.height);\n this.sceneManager.getCurrentScene().render(this.renderingContext);\n this.debugger.draw(this.debugCanvas.getContext('2d'));\n }",
"constructor() {\n super();\n this.init();\n this.ctx = Board.screenCanvas.context;\n }",
"function newCanvas(){\n //define and resize canvas\n $(\"#content\").height($(window).height()-90);\n var canvas = '<canvas id=\"canvas\" width=\"'+$(window).width()+'\" height=\"'+($(window).height()-90)+'\"></canvas>';\n $(\"#content\").html(canvas);\n\n // setup canvas\n ctx=document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.strokeStyle = color;\n ctx.lineWidth = 10;\n\n // setup to trigger drawing on mouse or touch\n $(\"#canvas\").drawTouch();\n $(\"#canvas\").drawPointer();\n $(\"#canvas\").drawMouse();\n}",
"initCanvas() {\n this.canvas = document.createElement('canvas');\n this.canvas.width = this.chip8.DISPLAY_WIDTH * this.scaler;\n this.canvas.height = this.chip8.DISPLAY_HEIGHT * this.scaler;\n\n document.getElementById('display').appendChild(this.canvas);\n this.context = this.canvas.getContext('2d');\n }",
"setViewPort() {\n gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);\n }",
"window_create(width, height, color) {\r\n\r\n // Create canvas and give it attributes\r\n this.surface.canvas = document.createElement(\"canvas\");\r\n this.surface.canvas.setAttribute(\"id\", \"main_canvas\");\r\n\r\n this.surface.canvas.width = width;\r\n this.surface.canvas.height = height;\r\n \r\n // Create the canvas to draw on.\r\n this.surface.context = this.surface.canvas.getContext(\"2d\");\r\n\r\n\r\n // create div container\r\n var container = document.createElement(\"div\");\r\n container.setAttribute(\"id\", \"main_canvas_container\");\r\n container.appendChild(this.surface.canvas);\r\n\r\n document.body.insertBefore(container, document.body.childNodes[0]);\r\n //document.body.appendChild(this.surface.canvas, document.body.childNodes[0]);\r\n //document.body.insertBefore(this.surface.canvas, document.body.childNodes[0]);\r\n\r\n\r\n // Create keyboard event handling.\r\n var self = this; \r\n document.addEventListener(\"keydown\", function(event){ \r\n event.preventDefault(); \r\n self.window_keydown(self, event);\r\n },false);\r\n\r\n document.addEventListener(\"keyup\", function(event){\r\n event.preventDefault();\r\n self.window_keyup(self, event);\r\n },false);\r\n \r\n //document.addEventListener(\"keydown\", this.window_keydown, false);\r\n //document.addEventListener(\"keyup\", this.window_keyup, false);\r\n if (color != null && color != undefined) {\r\n if (color==0) \r\n color = '#000';\r\n\r\n if (color.charAt(0)!='#')\r\n color = '#' + color; \r\n\r\n this.set_background_color(color);\r\n } \r\n }",
"function worldToDevice(w_x, w_y){\n\tvar d_x = (w_x-w_X_min)*canvas.width/w_width;\n\tvar d_y = canvas.height - ((w_y-w_Y_min)*canvas.height/w_height);\n\t\n\treturn vec2(d_x, d_y);\n}",
"function Canvas(){\n\tconst container = document.createElement('div');\n\tcontainer.style.position = \"absolute\";\n\tcontainer.style.display = \"flex\";\n\tcontainer.style.top = container.style.bottom = container.style.left = container.style.right = 0;\n\n\tconst canvas = document.createElement('canvas');\n\tcanvas.width = 40;\n\tcanvas.height = 40;\n\tcanvas.style.margin = \"auto\";\n\tcanvas.style.imageRendering = \"pixelated\";\n\tcanvas.style.zoom = 20;\n\tcanvas.style.background = \"#333\"\n\n\tdocument.body.appendChild(container);\n\tcontainer.appendChild(canvas);\n\treturn canvas;\n}",
"update() {\n this.gl.clear(this.gl.COLOR_BUFFER_BIT)\n // Mapping from clip-space coords to the viewport in pixels\n this.gl.viewport(0, 0, this.canvas.width, this.canvas.height)\n }",
"function createGameScreen() {\n var gameScreen = buildDom(`\n <main class=\"game container\">\n <header>\n <div class=\"lives\">\n <span class=\"label\">Lives:</span>\n <span class=\"value\"></span>\n </div>\n <div class=\"score\">\n <span class=\"label\">Score:</span>\n <span class=\"value\"></span>\n </div>\n </header>\n <div class=\"canvas-container\">\n <canvas></canvas>\n </div>\n </main>\n `);\n\n document.body.appendChild(gameScreen);\n return gameScreen;\n }",
"function createCanvas(){\n\tif(!game.scalingCanvas){\n\t\tconsole.log(\"Canvas not yet initialized! Canvas creation aborted\");\n\t\treturn;\n\t}\n\n\t// add scaling canvas\n\tdocument.body.appendChild(game.scalingCanvas);\n\tconsole.log(\"Scaling canvas successfully appended to HTML body!\");\n}",
"drawScene() {\n const gl = this.gl\n\n this.createBuffers()\n\n gl.clear(gl.COLOR_BUFFER_BIT) // @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/clear\n\n const modes = [ // @see https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants#Rendering_primitives\n gl.POINTS,\n gl.LINES,\n gl.LINE_STRIP,\n gl.LINE_LOOP,\n gl.TRIANGLES,\n gl.TRIANGLE_STRIP,\n gl.TRIANGLE_FAN,\n ]\n const dimensions = 2\n const mode = modes[0]\n const first = 0\n const count = this.data.positions.length / dimensions\n gl.drawArrays(mode, first, count) // @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawArrays\n }"
]
| [
"0.6580784",
"0.63275576",
"0.6192251",
"0.61601263",
"0.6120177",
"0.6085641",
"0.6079565",
"0.60681146",
"0.6064712",
"0.60522974",
"0.6024036",
"0.5948543",
"0.59427124",
"0.59239095",
"0.5892803",
"0.5880003",
"0.5843403",
"0.5839106",
"0.5814356",
"0.57947123",
"0.5792587",
"0.5786615",
"0.577723",
"0.5774799",
"0.57675743",
"0.57587785",
"0.57344264",
"0.5732328",
"0.57234913",
"0.5718938"
]
| 0.7532558 | 0 |
Traverse tree and make visible only needed meshes | function makeVisibleMeshes(object, checker) {
if (object && object.traverse) {
object.traverse((obj) => {
if (obj instanceof THREE.Mesh) {
obj.visible = checker(obj);
}
});
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function makeVisible(mesh){\r\n var children = mesh.getChildMeshes();\r\n mesh.isVisible = true;\r\n for (var i = 0, len = children.length; i < len; i++) {\r\n children[i].isVisible = true;\r\n }\r\n }",
"function makeVisible(mesh){\r\n var children = mesh.getChildMeshes();\r\n mesh.isVisible = true;\r\n for (var i = 0, len = children.length; i < len; i++) {\r\n children[i].isVisible = true;\r\n }\r\n }",
"function makeVisible(mesh){\r\n var children = mesh.getChildMeshes();\r\n mesh.isVisible = true;\r\n for (var i = 0, len = children.length; i < len; i++) {\r\n children[i].isVisible = true;\r\n }\r\n }",
"function unchecNodes(node) {\r\n\t\tfor (var counter = 5; counter < map.layers.length; ++counter) {\r\n//\t\t\tif (map.layers[counter]!=baselayer) {\r\n\t\t\tmap.layers[counter].setVisibility(false);\r\n//\t\t}\r\n\t\t}\r\n\t}",
"getVisibleChildren(){\n return _.filter(_.flattenDeep(this.triangles), (obj)=>{ return obj.visible});\n }",
"showhidemeshes() {\n for (let st=0;st<this.internal.meshsets.length;st++) \n this.internal.meshsets[st].showMeshes(this.internal.meshvisible[st]);\n }",
"function traverseMeshes( cb ) {\n\n\t\t\tobject.traverse( function ( child ) {\n\n\t\t\t\tif ( child.isMesh === true || child.isPoints ) {\n\n\t\t\t\t\tconst mesh = child;\n\t\t\t\t\tconst geometry = mesh.geometry;\n\n\t\t\t\t\tif ( geometry.hasAttribute( 'position' ) === true ) {\n\n\t\t\t\t\t\tcb( mesh, geometry );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} );\n\n\t\t}",
"_markDefs() {\n const nodeDefs = this.json.nodes || [];\n const skinDefs = this.json.skins || [];\n const meshDefs = this.json.meshes || [];\n for (let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {\n const joints = skinDefs[skinIndex].joints;\n for (let i4 = 0, il = joints.length; i4 < il; i4++) {\n nodeDefs[joints[i4]].isBone = true;\n }\n }\n for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {\n const nodeDef = nodeDefs[nodeIndex];\n if (nodeDef.mesh !== void 0) {\n this._addNodeRef(this.meshCache, nodeDef.mesh);\n if (nodeDef.skin !== void 0) {\n meshDefs[nodeDef.mesh].isSkinnedMesh = true;\n }\n }\n if (nodeDef.camera !== void 0) {\n this._addNodeRef(this.cameraCache, nodeDef.camera);\n }\n }\n }",
"function changeShading()\n{\n if(isFlatShading){\n floor.material = new THREE.MeshPhongMaterial({\n color: 0X5be686,\n flatShading: true\n });\n trees.forEach(forfunc);\n function forfunc(item){\n if(item.children.length >6){\n item.children[0].material =new THREE.MeshPhongMaterial({\n color: 0x38761D,\n flatShading: true});\n\n item.material = new THREE.MeshPhongMaterial({\n color: 0x874a5c,\n flatShading: true});}\n else\n {\n item.children[0].material =new THREE.MeshPhongMaterial({\n color: 0x95c088,\n flatShading: true});\n if(item.children[1] != undefined) \n {\n item.children[1].material =new THREE.MeshPhongMaterial({\n color: 0x95c088,\n flatShading: true});\n item.children[2].material =new THREE.MeshPhongMaterial({\n color: 0x95c088,\n flatShading: true});\n item.children[3].material =new THREE.MeshPhongMaterial({\n color: 0x95c088,\n flatShading: true});\n }\n\n item.material = new THREE.MeshPhongMaterial({\n color: 0x874a5c,\n flatShading: true});\n\n }\n } \n rocks1.forEach(forfunc2);\n rocks2.forEach(forfunc2);\n rocks3.forEach(forfunc2);\n rocks4.forEach(forfunc2);\n function forfunc2(item)\n {\n var color = item.material.color;\n item.material = new THREE.MeshPhongMaterial({\n color: color,\n flatShading: true});\n }\n fruitlist.forEach(forfunc3); \n function forfunc3(item)\n {\n var color = new THREE.Color(0xffff00)\n var color1 = redAppleMat.color;\n var color2 = greenAppleMat.color;\n if(item.material.color.equals(color))\n {\n item.material = new THREE.MeshPhongMaterial({\n color: color,\n flatShading: true});\n }\n \n else if(item.material.color.equals(color1))\n {\n item.material = new THREE.MeshPhongMaterial({\n color: color1,\n flatShading: true});\n }\n \n else\n {\n item.material = new THREE.MeshPhongMaterial({\n color: color2,\n flatShading: true});\n }\n\n } \n }\n else{\n floor.material = new THREE.MeshLambertMaterial({\n color: 0X5be686,\n flatShading: false\n \n });\n \n trees.forEach(forfunc);\n function forfunc(item){\n if(item.children.length>7)\n {\n item.children[0].material =new THREE.MeshLambertMaterial({\n color: 0x38761D,\n flatShading: false});\n item.material = new THREE.MeshLambertMaterial({\n color: 0x874a5c,\n flatShading: false});}\n else\n {\n item.children[0].material =new THREE.MeshLambertMaterial({\n color: 0x95c088,\n flatShading: false});\n if(item.children[1] != undefined) \n {\n item.children[1].material =new THREE.MeshLambertMaterial({\n color: 0x95c088,\n flatShading: false});\n item.children[2].material =new THREE.MeshLambertMaterial({\n color: 0x95c088,\n flatShading: false});\n item.children[3].material =new THREE.MeshLambertMaterial({\n color: 0x95c088,\n flatShading: false});\n } \n\n item.material = new THREE.MeshLambertMaterial({\n color: 0x874a5c,\n flatShading: false});\n }\n }\n rocks1.forEach(forfunc2);\n rocks2.forEach(forfunc2);\n rocks3.forEach(forfunc2);\n rocks4.forEach(forfunc2);\n function forfunc2(item)\n {\n var color = item.material.color;\n item.material = new THREE.MeshLambertMaterial({\n color: color,\n flatShading: false});\n }\n\n fruitlist.forEach(forfunc3); \n function forfunc3(item)\n {\n var color = new THREE.Color(0xffff00)\n var color1 = redAppleMat.color;\n var color2 = greenAppleMat.color;\n if(item.material.color.equals(color))\n {\n item.material = new THREE.MeshLambertMaterial({\n color: color,\n flatShading: false});\n }\n \n else if(item.material.color.equals(color1))\n {\n item.material = new THREE.MeshLambertMaterial({\n color: color1,\n flatShading: false});\n }\n \n else\n {\n item.material = new THREE.MeshLambertMaterial({\n color: color2,\n flatShading: false});\n }\n\n } \n }\n\n \n}",
"Rebuild()\n {\n this.Unload();\n EvePlaneSet.RebuildItems(this);\n this._rebuildPending = false;\n const itemCount = this._visibleItems.length;\n if (!itemCount) return;\n\n const\n vertexSize = 35,\n mat4_0 = EvePlaneSet.global.mat4_0;\n\n const array = new Float32Array(itemCount * 4 * vertexSize);\n for (let i = 0; i < itemCount; ++i)\n {\n const\n item = this._visibleItems[i],\n offset = i * 4 * vertexSize;\n\n array[offset + vertexSize - 3] = 0;\n array[offset + vertexSize + vertexSize - 3] = 1;\n array[offset + 2 * vertexSize + vertexSize - 3] = 2;\n array[offset + 3 * vertexSize + vertexSize - 3] = 3;\n\n const itemTransform = mat4.fromRotationTranslationScale(mat4_0, item.rotation, item.position, item.scaling);\n\n for (let j = 0; j < 4; ++j)\n {\n const vtxOffset = offset + j * vertexSize;\n array[vtxOffset] = itemTransform[0];\n array[vtxOffset + 1] = itemTransform[4];\n array[vtxOffset + 2] = itemTransform[8];\n array[vtxOffset + 3] = itemTransform[12];\n array[vtxOffset + 4] = itemTransform[1];\n array[vtxOffset + 5] = itemTransform[5];\n array[vtxOffset + 6] = itemTransform[9];\n array[vtxOffset + 7] = itemTransform[13];\n array[vtxOffset + 8] = itemTransform[2];\n array[vtxOffset + 9] = itemTransform[6];\n array[vtxOffset + 10] = itemTransform[10];\n array[vtxOffset + 11] = itemTransform[14];\n\n array[vtxOffset + 12] = item.color[0];\n array[vtxOffset + 13] = item.color[1];\n array[vtxOffset + 14] = item.color[2];\n array[vtxOffset + 15] = item.color[3];\n\n array[vtxOffset + 16] = item.layer1Transform[0];\n array[vtxOffset + 17] = item.layer1Transform[1];\n array[vtxOffset + 18] = item.layer1Transform[2];\n array[vtxOffset + 19] = item.layer1Transform[3];\n\n array[vtxOffset + 20] = item.layer2Transform[0];\n array[vtxOffset + 21] = item.layer2Transform[1];\n array[vtxOffset + 22] = item.layer2Transform[2];\n array[vtxOffset + 23] = item.layer2Transform[3];\n\n array[vtxOffset + 24] = item.layer1Scroll[0];\n array[vtxOffset + 25] = item.layer1Scroll[1];\n array[vtxOffset + 26] = item.layer1Scroll[2];\n array[vtxOffset + 27] = item.layer1Scroll[3];\n\n array[vtxOffset + 28] = item.layer2Scroll[0];\n array[vtxOffset + 29] = item.layer2Scroll[1];\n array[vtxOffset + 30] = item.layer2Scroll[2];\n array[vtxOffset + 31] = item.layer2Scroll[3];\n\n array[vtxOffset + 33] = item.boneIndex;\n array[vtxOffset + 34] = item.maskAtlasID;\n }\n }\n\n this._vertexBuffer = device.gl.createBuffer();\n device.gl.bindBuffer(device.gl.ARRAY_BUFFER, this._vertexBuffer);\n device.gl.bufferData(device.gl.ARRAY_BUFFER, array, device.gl.STATIC_DRAW);\n device.gl.bindBuffer(device.gl.ARRAY_BUFFER, null);\n\n const indexes = new Uint16Array(itemCount * 6);\n for (let i = 0; i < itemCount; ++i)\n {\n const\n offset = i * 6,\n vtxOffset = i * 4;\n\n indexes[offset] = vtxOffset;\n indexes[offset + 1] = vtxOffset + 2;\n indexes[offset + 2] = vtxOffset + 1;\n indexes[offset + 3] = vtxOffset;\n indexes[offset + 4] = vtxOffset + 3;\n indexes[offset + 5] = vtxOffset + 2;\n }\n\n this._indexBuffer = device.gl.createBuffer();\n device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);\n device.gl.bufferData(device.gl.ELEMENT_ARRAY_BUFFER, indexes, device.gl.STATIC_DRAW);\n device.gl.bindBuffer(device.gl.ELEMENT_ARRAY_BUFFER, null);\n this._indexBuffer.count = itemCount * 6;\n }",
"refreshChildren() {\n this.children = this.children.filter(child => child.isValidAndVisible());\n }",
"function setBoundary(){\n\t//outside bordering fence ie trees\n\tfor(let i = 0;i < 41;i++){\n\t\tvar mtlloader = new THREE.MTLLoader(loadingManager);\n\t\tmtlloader.load(\"static/SnowModels/treePineSnowed.mtl\",function(materials){\n\t\t\tmaterials.preload();\n\t\t\tvar objloader = new THREE.OBJLoader(loadingManager);\n\t\t\tobjloader.setMaterials(materials);\n\t\t\tobjloader.load(\"static/SnowModels/treePineSnowed.obj\",function(mesh){\n\t\t\t\tmesh.traverse(function(node){\n\t\t\t\t\tif(node instanceof THREE.Mesh){\n\t\t\t\t\t\tnode.castShadow = true;\n\t\t\t\t\t\tnode.receiveShadow = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tmesh.scale.set(10,30,25);\n\t\t\t\tmesh.position.set(-300,0.4,300-i*15);\n\t\t\t\tscene.add(mesh);\n\t\t\t\tobjects.push(mesh);\n\t\t\t});\n\t\t});\n\t}\n\n\tfor(let i = 0;i < 41;i++){\n\t\tvar mtlloader = new THREE.MTLLoader(loadingManager);\n\t\tmtlloader.load(\"static/SnowModels/treePineSnowed.mtl\",function(materials){\n\t\t\tmaterials.preload();\n\t\t\tvar objloader = new THREE.OBJLoader(loadingManager);\n\t\t\tobjloader.setMaterials(materials);\n\t\t\tobjloader.load(\"static/SnowModels/treePineSnowed.obj\",function(mesh){\n\t\t\t\tmesh.traverse(function(node){\n\t\t\t\t\tif(node instanceof THREE.Mesh){\n\t\t\t\t\t\tnode.castShadow = true;\n\t\t\t\t\t\tnode.receiveShadow = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tmesh.scale.set(10,30,25);\n\t\t\t\tmesh.rotation.set(0,Math.PI/2,0);\n\t\t\t\tmesh.position.set(-300+i*15,0.4,300);\n\t\t\t\tscene.add(mesh);\n\t\t\t\tobjects.push(mesh);\n\t\t\t});\n\t\t});\n\t}\n\n\tfor(let i = 0;i < 41;i++){\n\t\tvar mtlloader = new THREE.MTLLoader(loadingManager);\n\t\tmtlloader.load(\"static/SnowModels/treePineSnowed.mtl\",function(materials){\n\t\t\tmaterials.preload();\n\t\t\tvar objloader = new THREE.OBJLoader(loadingManager);\n\t\t\tobjloader.setMaterials(materials);\n\t\t\tobjloader.load(\"static/SnowModels/treePineSnowed.obj\",function(mesh){\n\t\t\t\tmesh.traverse(function(node){\n\t\t\t\t\tif(node instanceof THREE.Mesh){\n\t\t\t\t\t\tnode.castShadow = true;\n\t\t\t\t\t\tnode.receiveShadow = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tmesh.scale.set(10,30,25);\n\t\t\t\tmesh.position.set(300,0.4,300-i*15);\n\t\t\t\tscene.add(mesh);\n\t\t\t\tobjects.push(mesh);\n\t\t\t});\n\t\t});\n\t}\n\n\tfor(let i = 0;i < 41;i++){\n\t\tvar mtlloader = new THREE.MTLLoader(loadingManager);\n\t\tmtlloader.load(\"static/SnowModels/treePineSnowed.mtl\",function(materials){\n\t\t\tmaterials.preload();\n\t\t\tvar objloader = new THREE.OBJLoader(loadingManager);\n\t\t\tobjloader.setMaterials(materials);\n\t\t\tobjloader.load(\"static/SnowModels/treePineSnowed.obj\",function(mesh){\n\t\t\t\tmesh.traverse(function(node){\n\t\t\t\t\tif(node instanceof THREE.Mesh){\n\t\t\t\t\t\tnode.castShadow = true;\n\t\t\t\t\t\tnode.receiveShadow = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tmesh.scale.set(10,30,25);\n\t\t\t\tmesh.rotation.set(0,Math.PI/2,0);\n\t\t\t\tmesh.position.set(-300+i*15,0.4,-300);\n\t\t\t\tscene.add(mesh);\n\t\t\t\tobjects.push(mesh);\n\t\t\t});\n\t\t});\n\t}\n}",
"traverseGraph(idNode, idCurrentMaterial, idCurrentTexture, currentLenghtS, currentLengthT) {\n \n let currentNode = this.components[idNode];\n\n // Updates the current material's id\n if(currentNode.materialIds[this.clickM % currentNode.materialIds.length] !== 'inherit')\n idCurrentMaterial = currentNode.materialIds[(this.clickM) % (currentNode.materialIds.length)]; //0 FOR NOW\n \n\n // Updates the current texture's id\n if(currentNode.textureId !== 'inherit') {\n idCurrentTexture = currentNode.textureId;\n currentLenghtS = currentNode.textureLengthS;\n currentLengthT = currentNode.textureLengthT;\n }\n\n // Pushes the matrix so that changes don't affect other components unwillingly\n this.scene.pushMatrix();\n\n this.scene.multMatrix(currentNode.transformationMatrix);\n \n // Updates the current transformation Matrix\n if(currentNode.animationId) {\n const animation = this.animations[currentNode.animationId];\n animation.apply(this.scene);\n }\n \n \n \n const material = this.materials[idCurrentMaterial];\n if(material === undefined)\n console.log(\"Undefined material used in the \"+idNode+\" component\");\n \n const texture = this.textures[idCurrentTexture];\n\n // Traverses the primitives and displays them\n for(let i = 0; i < currentNode.primitiveIds.length; i++) {\n \n // If the texture is differente from 'none', applies it...\n if(texture !== undefined){\n material.setTexture(texture);\n material.setTextureWrap('REPEAT', 'REPEAT');\n this.primitives[currentNode.primitiveIds[i]].updateTexCoords(currentLenghtS, currentLengthT);\n }\n // ..Otherwise, sets it to null\n else\n material.setTexture(null);\n\n material.apply();\n\n /*if(currentNode.pickable){\n this.scene.registerForPick(this.hashCode(currentNode.id+'_'+currentNode.primitiveIds[i]), this.primitives[currentNode.primitiveIds[i]]);\n }*/\n\n this.primitives[currentNode.primitiveIds[i]].display();\n }\n\n for(let i = 0; i < currentNode.componentIds.length; i++) {\n this.traverseGraph(currentNode.componentIds[i], idCurrentMaterial, idCurrentTexture, currentLenghtS, currentLengthT);\n }\n\n this.scene.popMatrix(); \n }",
"function groupMesher(mesher, map, step) {\n var found = 0;\n var ne, se, sw, nw, test;\n var height = map.height;\n var width = map.width;\n \n for (var y = 0; y < height - step; y += step * 2) {\n for (var x = 0; x < width - step; x += step * 2) {\n ne = mesher[x+step][y];\n se = mesher[x+step][y+step];\n sw = mesher[x][y+step];\n nw = mesher[x][y];\n \n //mesh.c:192\n if (ne.used && ne.size === step &&\n se.used && se.size === step &&\n sw.used && sw.size === step &&\n nw.used && nw.size === step &&\n ne.link[DIR_NNW] === ne.link[DIR_NNE] &&\n ne.link[DIR_ENE] === ne.link[DIR_ESE] &&\n se.link[DIR_ENE] === se.link[DIR_ESE] &&\n se.link[DIR_SSE] === se.link[DIR_SSW] &&\n sw.link[DIR_SSE] === sw.link[DIR_SSW] &&\n sw.link[DIR_WSW] === sw.link[DIR_WNW] &&\n nw.link[DIR_WSW] === nw.link[DIR_WNW] &&\n nw.link[DIR_NNW] === nw.link[DIR_NNE] &&\n ne.link[DIR_NE] !== null &&\n se.link[DIR_SE] !== null &&\n sw.link[DIR_SW] !== null && nw.link[DIR_NW] !== null) {\n \n ne.used = 0;\n se.used = 0;\n sw.used = 0;\n\n nw.size = step * 2;\n nw.link[DIR_NNE] = ne.link[DIR_NNE];\n nw.link[DIR_NE] = ne.link[DIR_NE];\n nw.link[DIR_ENE] = ne.link[DIR_ENE];\n nw.link[DIR_ESE] = se.link[DIR_ESE];\n nw.link[DIR_SE] = se.link[DIR_SE];\n nw.link[DIR_SSE] = se.link[DIR_SSE];\n nw.link[DIR_SSW] = sw.link[DIR_SSW];\n nw.link[DIR_SW] = sw.link[DIR_SW];\n nw.link[DIR_WSW] = sw.link[DIR_WSW];\n\n for (var j=0; j<NB_DIRS; ++j) {\n for (var k=0; k<NB_DIRS; ++k) {\n if (nw.link[j]) {\n test = nw.link[j].link[k];\n if (test === ne || test === se || test === sw) {\n nw.link[j].link[k] = nw;\n }\n }\n }\n }\n \n // We've merged meshers!!!\n ++found;\n }\n }\n }\n \n return found;\n}",
"function showAllPlanes() {\n var allPlanes = sceneElements.sceneGraph.getObjectByName(\"allPlane\").children;\n for (var i=0; i<allPlanes.length; i++) {\n var elem = allPlanes[i].children[0];\n var edges = allPlanes[i].children[1];\n elem.visible = true;\n edges.visible = true;\n }\n\n}",
"getFlatHierarchy() {\n const successors = [];\n successors.push(this);\n this.visualElements.forEach(successor => {\n successors.push(...successor.getFlatHierarchy());\n });\n return successors;\n }",
"function checkValid(node) {\n if ((node.apparentX - current.x) * node.apparentZoom / current.zoom > stage.canvas.width * 10 ||\n (node.apparentX - current.x) * node.apparentZoom / current.zoom < -stage.canvas.width * 10 ||\n (node.apparentY - current.y) * node.apparentZoom / current.zoom > stage.canvas.height * 10 ||\n (node.apparentY - current.y) * node.apparentZoom / current.zoom < -stage.canvas.height * 10) {\n// node.valid = false;\n// deleteNode(node);\n } else if (node.apparentZoom < current.zoom / ZOOM_THRESHOLD) {\n node.valid = false;\n node.links.forEach(function(link) {\n if (link.child) {\n deleteNode(link.child);\n delete link.child;\n }\n });\n } else if (node.apparentZoom > current.zoom * ZOOM_THRESHOLD) {\n node.valid = false;\n if (node.parentId && current.nodes[node.parentId] && !current.nodes[node.parentId].valid) {\n deleteNode(current.nodes[node.parentId]);\n }\n } else {\n if (!node.valid) {\n node.links.forEach(function(link) {\n if (!link.child) {\n // This is a little confusing but links are the specific text element in a body of text that whole nodes should be attached to\n current.branches[link.id] = node.id;\n }\n });\n }\n node.valid = true;\n }\n}",
"function drawAllNodes(){\n\t//split the nodes data into levels\t\n\tvar levels = [];\n\t//for each level, check if it is the outdoor level (index -1)\n\tfor(var index in nodes){\n\t\tnode = nodes[index]\n\t\tif(typeof levels[node.properties.Level] === 'undefined'){\n\t\t\tlevels[node.properties.Level] = [];\n\t\t}\n\t\tlevels[node.properties.Level].push(node);\n\t}\n\t\n\tfor(var level in levels){\n\t\taddMarkers(levels[level], level);\n\t}\n}",
"updateGraph() {\n this.faultyDefs = [];\n this.entitiesByID = {};\n this.nodes = [];\n this.edges = [];\n\n let created = [];\n\n this.updateSearchOptions();\n\n [$Field.materials, $Field.lyphs].forEach(prop => {\n (this._model[prop] || []).forEach(m => {\n if (!m.id) {\n this.faultyDefs.push({item: m, reason: \"No ID\"});\n return;\n }\n m._inMaterials = [];\n this.entitiesByID[m.id] = m;\n });\n });\n\n [$Field.materials, $Field.lyphs].forEach(prop => {\n (this._model[prop] || []).forEach(m => {\n (m.materials || []).forEach(childID => {\n if (!this.entitiesByID[childID]) {\n this.entitiesByID[childID] = {\n \"id\": childID,\n \"_generated\": true,\n \"_inMaterials\": [],\n };\n created.push(this.entitiesByID[childID]);\n }\n });\n (m.materials || []).forEach(childID => this.entitiesByID[childID]._inMaterials.push(m));\n });\n });\n\n //Create nodes for visualization\n (this._model.materials || []).forEach(m => {\n this.nodes.push(new Node(\n m.id,\n (m._inMaterials || []).map(parent => parent.id),\n (m.materials || []).map(child => child.id ? child.id : child),\n m.name || m.id,\n \"type-material\",\n m\n ));\n this.entitiesByID[m.id]._class = $SchemaClass.Material;\n });\n (this._model.lyphs || []).forEach(m => {\n if ((m._inMaterials || []).length > 0 || (m.materials || []).length > 0 || m._included) {\n this.nodes.push(new Node(\n m.id,\n (m._inMaterials || []).map(parent => parent.id),\n (m.materials || []).map(child => child.id ? child.id : child),\n m.name || m.id,\n \"type-lyph\",\n m\n ));\n m._included = true;\n }\n this.entitiesByID[m.id]._class = $SchemaClass.Lyph;\n });\n (created || []).forEach(m => {\n if (m.id) {\n this.nodes.push(new Node(\n m.id,\n (m._inMaterials || []).map(parent => parent.id),\n (m.materials || []).map(child => child.id ? child.id : child),\n m.name || m.id,\n \"type-undefined\",\n m\n ));\n }\n });\n\n // Create edges for visualization\n this.nodes.forEach(node => {\n (node.parents || []).forEach(p => {\n let edge = new Edge(node.id + '---' + p, this.entitiesByID[p], node.resource, 'has-material');\n this.edges.push(edge);\n });\n });\n this.nodes::sortBy([\"id\"]);\n }",
"function toggleViz(tempFolder) {\n\tfor (var i = 0; i<tempFolder.length; i++) {\n\t\ttempFolder[i].particle.visible = true;\n\t}\n}",
"resetTree() {\n this.root.nodes.forEach((node) => { var _a; return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); });\n this.root.nodes.forEach(clearMeasurements);\n this.root.sharedNodes.clear();\n }",
"function syanFancyTree(treeParams, materials){\n var fancyTree = new THREE.Object3D();\n var barkGeom = new THREE.ConeGeometry(treeParams.baseRadius, treeParams.totalHeight, 32);\n var tier1Geom = new THREE.TorusBufferGeometry(treeParams.radius1, treeParams.radius1*2, 32, 32);\n var tier2Geom = new THREE.TorusBufferGeometry(treeParams.radius2, treeParams.radius2*2, 32, 32);\n var tier3Geom = new THREE.TorusBufferGeometry(treeParams.radius3, treeParams.radius3*2, 32, 32);\n\n var bark = new THREE.Mesh(barkGeom, materials.treeBarkMaterial);\n var tier1 = new THREE.Mesh(tier1Geom, materials.treeLeafMaterial);\n var tier2 = new THREE.Mesh(tier2Geom, materials.treeLeafMaterial);\n var tier3 = new THREE.Mesh(tier3Geom, materials.treeLeafMaterial);\n\n // enable shadows\n bark.castShadow = true;\n tier1.castShadow = true;\n tier2.castShadow = true;\n tier3.castShadow = true;\n bark.receiveShadow = true;\n tier1.receiveShadow = true;\n tier2.receiveShadow = true;\n tier3.receiveShadow = true;\n\n tier1.rotation.x = Math.PI/2;\n tier1.scale.z = 0.25;\n tier2.rotation.x = Math.PI/2;\n tier2.scale.z = 0.25;\n tier3.rotation.x = Math.PI/2;\n tier3.scale.z = 0.25;\n\n bark.position.set(0, treeParams.totalHeight/2, 0);\n tier1.position.set(0, treeParams.radius1*0.25 + treeParams.bottomSpace, 0);\n tier2.position.set(0, treeParams.radius2*0.25 + treeParams.spacing +\n treeParams.radius1*0.25 + treeParams.bottomSpace, 0);\n tier3.position.set(0, treeParams.radius3*0.25 + treeParams.spacing +\n treeParams.radius2*0.25 + treeParams.spacing + treeParams.radius1*0.25 +\n treeParams.bottomSpace, 0);\n\n fancyTree.add(bark);\n fancyTree.add(tier1);\n fancyTree.add(tier2);\n fancyTree.add(tier3);\n\n return fancyTree;\n}",
"buildVisualization(data) {\n /**\n * Get nodes and links\n */\n \n const root = d3.hierarchy({name: 'everything', children: data});\n console.log(data);\n console.log(root);\n let clusters = [];\n\n // Adds an identity field to each node - useful for data joins\n // Also adds a cluster ID to each node - useful for blobs\n function flatten(root) {\n let i = 0, cluster = 0;\n \n function recurse(node) {\n if (node.children) {\n node.children.forEach(recurse);\n }\n if (node.children && node.depth > 1) {\n node._children = node.children;\n node.children = null;\n }\n if (!node.identity) node.identity = ++i;\n }\n\n function recurseCluster(node) {\n if(node.children) {\n node.children.forEach(recurseCluster);\n }\n node.cluster = cluster;\n }\n root.children.forEach((child) => {\n recurseCluster(child);\n cluster++;\n })\n recurse(root);\n \n }\n\n flatten(root)\n\n function getLinks() { // remove links from root to all children\n const links = root.links();\n console.log(links);\n // if link.source.identity == root.identity, delete this link\n while(links[0].source.identity === root.identity) {\n links.shift();\n }\n return links;\n }\n\n function getNodes() { // remove everything node\n const nodes = root.descendants();\n nodes.shift();\n return nodes;\n }\n\n let links = getLinks();\n let nodes = getNodes();\n \n // set up clusters appropriately\n nodes.forEach((node) => {\n if(clusters[node.cluster] === undefined) {\n clusters[node.cluster] = [];\n }\n clusters[node.cluster].push(node);\n })\n\n /**\n * Create force simulation, color schemes, and overall svg\n */\n const width = 1000;\n const height = 490;\n const xDivisor = 2.5;\n const yDivisor = 1.4;\n nodes.forEach((node) => {\n node.x = (node.cluster%7) * width/xDivisor - width*1.1; \n node.y = Math.floor(node.cluster/7)*(height/yDivisor) - height*1.2;\n })\n\n const simulation = d3.forceSimulation(nodes)\n .force(\"link\", d3.forceLink(links).id(d => d.identity)\n .distance((d) => (d.target.children || d.target._children) ? 80 : 45)\n .strength(1.8))\n .force(\"charge\", d3.forceManyBody().strength((d) => {\n return d.children || d._children ? -200 : -50;\n }))\n .force('collision', d3.forceCollide().radius(function(d) {\n return d.children || d._children ? 15: 11;\n }))\n .force(\"x\", d3.forceX().x((d) => (d.cluster%7) * width/xDivisor - width*1.1).strength((d) => {\n console.log(d);\n return d.parent.depth === 0 ? 1 : 0.01\n }))\n .force(\"y\", d3.forceY().y((d) => (Math.floor(d.cluster/7)*(height/yDivisor) - height*1.2)).strength((d) => {\n console.log(d);\n return d.parent.depth === 0 ? 1 : 0.01\n }))\n .alpha(0.15)\n\n const color = d3.scaleOrdinal()\n .domain(data, (d) => d.name) \n .range(d3.schemeTableau10);\n\n // Enable zooming, panning\n function zoomed({transform}) {\n currentScale = transform.k\n forcePlot.attr(\"transform\", transform);\n }\n\n let currentScale = 1;\n\n const zoom = d3.zoom()\n .scaleExtent([0.3, 3])\n .on(\"zoom\", zoomed);\n\n \n \n const forceSvg = d3.select(this._rootNode)\n .append('svg')\n .attr('id', 'force-svg')\n .attr('viewBox', [0, 0, width, height])\n .attr(\"preserveAspectRatio\", \"xMidYMid meet\")\n .call(zoom);\n \n const forcePlot = forceSvg.append('g')\n\n forceSvg.call(zoom.translateTo,\n 550,\n 300); // note? WHY???? \n forceSvg.transition().duration(400).call(\n zoom.scaleTo,\n 0.5); \n /**\n * Interactivity\n */\n \n // drag interactions\n const drag = simulation => {\n function dragstarted(event, d) {\n if (!event.active) simulation.alphaTarget(0.3).restart();\n d.fx = d.x;\n d.fy = d.y;\n }\n\n function dragged(event, d) {\n d.fx = event.x;\n d.fy = event.y;\n }\n \n function dragended(event, d) {\n if (!event.active) simulation.alphaTarget(0);\n d.fx = null;\n d.fy = null;\n }\n \n return d3.drag()\n .on(\"start\", dragstarted)\n .on(\"drag\", dragged)\n .on(\"end\", dragended);\n }\n\n const {selectClub} = this.props;\n // Click interactions\n async function click(event, d) {\n if (event.defaultPrevented) return; // ignore drag\n // handles tag actions\n if (d.children) { // make them disappear\n const descendants = d.descendants();\n clusters[d.cluster] = clusters[d.cluster].filter((thing) => {\n return (descendants.filter((node) => node.identity === thing.identity).length === 1) ? 0 : 1;\n });\n d._children = d.children;\n d.children = null;\n } else if (d._children) { // make them appear, if not a leaf\n centerElement(event, this, 4);\n d.children = d._children;\n const descendants = d.descendants();\n descendants.forEach((kid) => clusters[kid.cluster].push(kid));\n d.children.map((node) => { // make children appear in the right place\n let delta_x = 0;\n let slope = 1;\n if (node.parent !== null && node.parent.parent !== null && node.parent.parent.identity !== root.identity) { // have a grandparent?\n // travel a bit in the rough direction of the line our parent/grandparent make\n delta_x = node.parent.x - node.parent.parent.x;\n const delta_y = node.parent.y - node.parent.parent.y;\n slope = delta_y / delta_x;\n }\n node.x = node.parent.x + delta_x * 3/4 + Math.random() * 10;\n node.y = node.parent.y + slope * delta_x * 3/4 + Math.random() * 10;\n return node;\n })\n d._children = null;\n } else { // handles leaf actions\n await positionLeaf(event, this);\n d3.select(this).transition()\n .duration(750)\n .attr('fill', (d) => d3.rgb(color(d.data.key)).darker(1))\n .attr('r', 8);\n const tagColors = d.data.tags.map((tag) => color(tag));\n const newData = {...d.data, colors: tagColors};\n selectClub(newData);\n }\n \n \n update(); // update forces some data joins, then restarts the vis\n }\n\n // update nodes, links, then restart visualization\n function update() {\n\n nodes = getNodes();\n links = getLinks();\n\n link = link.data(links, d => [d.source, d.target])\n .join('line');\n\n node = node.data(nodes, d => d.identity)\n .join('circle')\n .attr('fill', (d) => d.children || d._children ? null : color(d.data.key))\n .attr('stroke', (d) => d.children || d._children ? color(d.data.name) : '#fff')\n .attr('stroke-width', (d) => d.children || d._children ? 2 : 1)\n .attr('r', (d) => d.children || d._children ? 11 : 10)\n .on('click', click)\n .on('mouseover', handleMouseOver)\n .on('mouseout', handleMouseOut)\n .call(drag(simulation));\n \n node.append(\"title\")\n .text(d => d.data.name);\n \n simulation.nodes(nodes);\n simulation.force(\"link\").links(links);\n simulation.restart();\n } \n\n // hover interactions\n const tooltip = d3.select(this._rootNode).append('div')\n .attr('class', 'hidden tooltip');\n\n function handleMouseOver(event, node) {\n tooltip.classed('hidden', false)\n .attr('style', 'left:' + (event.clientX + 10*currentScale) + 'px; top:' + (event.clientY - 10*currentScale) + 'px')\n .html(`<p>${node.data.name}</p>`);\n\n d3.select(this)\n .attr('cursor', 'pointer')\n .transition()\n .duration(150)\n .attr('r', (d) => d.children || d._children ? 13 : 12);\n }\n\n function handleMouseOut() {\n tooltip.classed('hidden', true);\n d3.select(this).transition()\n .delay(30)\n .duration(200)\n .attr('r', (d) => d.children || d._children ? 12 : 11);\n }\n\n // BLOB ME UP\n const groupPath = function(d) {\n const hull = d3.polygonHull(d.map((node) => [node.x, node.y]))\n return hull;\n };\n\n function getCentroid(element) {\n const bbox = element.getBBox();\n return [bbox.x + bbox.width/2, bbox.y + bbox.height/2];\n }\n\n async function positionLeaf(event, element) {\n event.stopPropagation();\n let x, y;\n const center = getCentroid(element)\n x = center[0];\n y = center[1];\n // zoom it\n await forceSvg.transition().duration(10).call(zoom.scaleTo, 3).end();\n // move it\n x += width/(currentScale*2.5)\n await forceSvg.transition().duration(650).call(\n zoom.translateTo,\n x, \n y\n ).end();\n }\n\n async function centerElement(event, element, k) {\n event.stopPropagation();\n let x, y;\n \n const center = getCentroid(element);\n x = center[0];\n y = center[1];\n \n await forceSvg.transition().duration(650).call(\n zoom.translateTo,\n x,\n y).end();\n await forceSvg.transition().duration(400).call(\n zoom.scaleTo,\n k\n ).end();\n }\n\n function centerZoomBlob(event) {\n centerElement(event, this, 1);\n }\n\n // tick interactions\n simulation.on('tick', () => {\n link.attr('x1', d => d.source.x)\n .attr('y1', d => d.source.y)\n .attr('x2', d => d.target.x)\n .attr('y2', d => d.target.y);\n node.attr('cx', d => d.x)\n .attr('cy', d => d.y)\n \n convexHull.data(clusters)\n .join('path')\n // convexHull.transition()\n // .duration(600)\n .attr('d', (d) => {\n const points = groupPath(d);\n return smoothHull(points);\n })\n .attr('fill', (d, i) => color(data[i].name))\n .attr('stroke', 'white')\n .attr('stroke-width', 0.2)\n .attr('stroke-linejoin', 'round')\n .attr('opacity', 0.08)\n .on('click', centerZoomBlob);\n\n // update labels here too \n // clusterLabels.data(clusters)\n \n\n forceSvg.attr('viewBox', [-window.innerWidth/2, -window.innerHeight/2, window.innerWidth, window.innerHeight])\n })\n\n /**\n * Functions that are magical, and which I do not fully understand\n * but am using because I WANT THE PRETTY: \n * http://bl.ocks.org/hollasch/9d3c098022f5524220bd84aae7623478\n */\n const hullPadding = 35;\n\n // Point/Vector Operations\n\n const vecFrom = function (p0, p1) { // Vector from p0 to p1\n return [ p1[0] - p0[0], p1[1] - p0[1] ];\n }\n\n const vecScale = function (v, scale) { // Vector v scaled by 'scale'\n return [ scale * v[0], scale * v[1] ];\n }\n\n const vecSum = function (pv1, pv2) { // The sum of two points/vectors\n return [ pv1[0] + pv2[0], pv1[1] + pv2[1] ];\n }\n\n const vecUnit = function (v) { // Vector with direction of v and length 1\n var norm = Math.sqrt (v[0]*v[0] + v[1]*v[1]);\n return vecScale (v, 1/norm);\n }\n\n const vecScaleTo = function (v, length) { // Vector with direction of v with specified length\n return vecScale (vecUnit(v), length);\n }\n\n const unitNormal = function (pv0, p1) { // Unit normal to vector pv0, or line segment from p0 to p1\n if (p1 != null) pv0 = vecFrom (pv0, p1);\n var normalVec = [ -pv0[1], pv0[0] ];\n return vecUnit (normalVec);\n };\n\n\n // Hull Generators\n\n const lineFn = d3.line()\n .curve (d3.curveCatmullRomClosed)\n .x (function(d) { return d.p[0]; })\n .y (function(d) { return d.p[1]; });\n\n\n const smoothHull = (polyPoints) => {\n // Returns the SVG path data string representing the polygon, expanded and smoothed.\n if(polyPoints === null) {\n return;\n }\n const pointCount = polyPoints.length;\n\n // Handle special cases\n if (!polyPoints || pointCount < 1) return \"\";\n if (pointCount === 1) return smoothHull1 (polyPoints);\n if (pointCount === 2) return smoothHull2 (polyPoints);\n\n const hullPoints = polyPoints.map (function (point, index) {\n var pNext = polyPoints[(index + 1) % pointCount];\n return {\n p: point,\n v: vecUnit (vecFrom (point, pNext))\n };\n });\n\n // Compute the expanded hull points, and the nearest prior control point for each.\n for (let i = 0; i < hullPoints.length; ++i) {\n const priorIndex = (i > 0) ? (i-1) : (pointCount - 1);\n const extensionVec = vecUnit (vecSum (hullPoints[priorIndex].v, vecScale (hullPoints[i].v, -1)));\n hullPoints[i].p = vecSum (hullPoints[i].p, vecScale (extensionVec, hullPadding));\n }\n\n return lineFn (hullPoints);\n }\n\n\n const smoothHull1 = function (polyPoints) {\n // Returns the path for a circular hull around a single point.\n\n const p1 = [polyPoints[0][0], polyPoints[0][1] - hullPadding];\n const p2 = [polyPoints[0][0], polyPoints[0][1] + hullPadding];\n\n return 'M ' + p1\n + ' A ' + [hullPadding, hullPadding, '0,0,0', p2].join(',')\n + ' A ' + [hullPadding, hullPadding, '0,0,0', p1].join(',');\n };\n\n\n const smoothHull2 = function (polyPoints) {\n // Returns the path for a rounded hull around two points.\n\n const v = vecFrom (polyPoints[0], polyPoints[1]);\n const extensionVec = vecScaleTo(v, hullPadding);\n\n const extension0 = vecSum (polyPoints[0], vecScale(extensionVec, -1));\n const extension1 = vecSum (polyPoints[1], extensionVec);\n\n const tangentHalfLength = 1.2 * hullPadding;\n const controlDelta = vecScaleTo (unitNormal(v), tangentHalfLength);\n const invControlDelta = vecScale (controlDelta, -1);\n\n const control0 = vecSum (extension0, invControlDelta);\n const control1 = vecSum (extension1, invControlDelta);\n const control3 = vecSum (extension0, controlDelta);\n\n return 'M ' + extension0\n + ' C ' + [control0, control1, extension1].join(',')\n + ' S ' + [ control3, extension0].join(',')\n + ' Z';\n };\n\n\n /**\n * Visualization initialization\n */\n\n let convexHull = forcePlot.selectAll('.blob')\n .data(clusters)\n .join('path')\n .attr('id', (d, i) => {\n return `${data[i].name}-path`\n })\n .attr('class', 'hull');\n\n forcePlot.selectAll('.cluster-labels')\n .data(clusters)\n .enter()\n .append('text')\n .attr('dy', 40)\n // .attr('width', 50)\n .append('textPath')\n .attr('xlink:href', (d, i) => `#${data[i].name}-path`)\n .style(\"text-anchor\",\"middle\")\n .attr('startOffset', \"60%\")\n .attr('font-size', 28)\n .attr('font-family', 'Roboto')\n .attr('letter-spacing', 0.02)\n .text((d, i) => data[i].name);\n\n let link = forcePlot.append('g')\n .attr('stroke', '#999')\n .attr('stroke-opacity', 0.6)\n .selectAll('line')\n .data(links, (d) => [d.source, d.target])\n .join('line');\n\n let node = forcePlot.append('g')\n .attr('fill', '#fff')\n .attr('stroke', '#000')\n .attr('stroke-width', 1.5)\n .selectAll('circle')\n .data(nodes, d => d.identity)\n .join('circle')\n .attr('fill', (d) => d.children || d._children ? null : color(d.data.key))\n .attr('stroke', d => d.children || d._children ? color(d.data.name) : '#fff')\n .attr('stroke-width', (d) => d.children || d._children ? 2 : 1)\n .attr('r', (d) => d.children || d._children ? 11 : 10)\n .on(\"click\", click)\n .on('mouseover', handleMouseOver)\n .on('mouseout', handleMouseOut)\n .call(drag(simulation))\n\n node.append(\"title\")\n .text(d => d.data.name);\n\n }",
"function set_visibility(mesh, visible, init=false)\n{\n\tfor (key in mesh_types)\n\t{\n\t\tif (mesh_types[key] in mesh)\n\t\t{\n\t\t\tmesh[mesh_types[key]].visible = visible;\n\t\t\tif (init) { scene.add(mesh[mesh_types[key]]); }\n\t\t} \n\t}\n\t// camera.position.z = mesh.surf.geometry.parameters.radius * 3;\n}",
"function masksVisib()\n {\n eachprop( stdMod.decor, dec => {\n dec.undisplay = true;\n });\n\n rg.pathIx_2_pathSubsteps.forEach( (fragment,fix) => {\n fragment.forEach( (fgroup,gix) => {\n fgroup.forEach( ( paintee, mix ) => {\n //paintee.undisplay = true;\n //todm ... make following line to follow from above line\n $$.$(paintee.svgel).addClass( 'undisplay' );\n });\n });\n });\n }",
"getFlatHierarchy() {\n\t const successors = [];\n\t successors.push(this);\n\t this.visualElements.forEach(successor => {\n\t successors.push(...successor.getFlatHierarchy());\n\t });\n\t return successors;\n\t }",
"generatePlanetPartition(tiles, action){\n \tvar icosahedron = this.generateIcosahedron();\n \taction.executeSubaction(function (action){\n \t\t\tfor (var i = 0; i < icosahedron.faces.length; ++i){\n \t\t\t\tvar face = icosahedron.faces[i];\n \t\t\t\tvar p0 = icosahedron.nodes[face.n[0]].p.clone().multiplyScalar(1000);\n \t\t\t\tvar p1 = icosahedron.nodes[face.n[1]].p.clone().multiplyScalar(1000);\n \t\t\t\tvar p2 = icosahedron.nodes[face.n[2]].p.clone().multiplyScalar(1000);\n \t\t\t\tvar center = p0.clone().add(p1).add(p2).divideScalar(3);\n \t\t\t\tvar radius = Math.max(center.distanceTo(p0), center.distanceTo(p2), center.distanceTo(p2));\n \t\t\t\tface.boundingSphere = new THREE.Sphere(center, radius);\n \t\t\t\tface.children = [];\n \t\t\t}\n \t});\n\n \tvar unparentedTiles = [];\n \tvar maxDistanceFromOrigin = 0;\n \taction.executeSubaction(function (action){\n \t\t\tfor (var i = 0; i < tiles.length; ++i){\n \t\t\t\tvar tile = tiles[i];\n \t\t\t\tmaxDistanceFromOrigin = Math.max(maxDistanceFromOrigin, tile.boundingSphere.center.length() + tile.boundingSphere.radius);\n\n \t\t\t\tvar parentFound = false;\n \t\t\t\tfor (var j = 0; j < icosahedron.faces.length; ++j){\n \t\t\t\t\tvar face = icosahedron.faces[j];\n \t\t\t\t\tvar distance = tile.boundingSphere.center.distanceTo(face.boundingSphere.center) + tile.boundingSphere.radius;\n \t\t\t\t\tif (distance < face.boundingSphere.radius){\n \t\t\t\t\t\tface.children.push(tile);\n \t\t\t\t\t\tparentFound = true;\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t\tif (!parentFound){\n \t\t\t\t\tunparentedTiles.push(tile);\n \t\t\t\t}\n \t\t\t}\n \t});\n\n \tvar rootPartition;\n \taction.executeSubaction(function (action){\n \t\t\trootPartition = new SpatialPartition(new THREE.Sphere(new THREE.Vector3(0, 0, 0), maxDistanceFromOrigin), [], unparentedTiles);\n \t\t\tfor (var i = 0; i < icosahedron.faces.length; ++i){\n \t\t\t\tvar face = icosahedron.faces[i];\n \t\t\t\trootPartition.partitions.push(new SpatialPartition(face.boundingSphere, [], face.children));\n \t\t\t\tdelete face.boundingSphere;\n \t\t\t\tdelete face.children;\n \t\t\t}\n \t});\n\n \taction.provideResult(function () {\n \t\t\treturn rootPartition;\n \t});\n }",
"resetTree() {\n this.root.nodes.forEach((node) => { var _a; return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); });\n this.root.nodes.forEach(clearMeasurements);\n this.root.sharedNodes.clear();\n }",
"refresh()\n {\n // Naively iterate over all nodes. If a branch node has 4 empty leaf nodes, \n // then remove the leaf nodes and make the branch node a leaf.\n for(let i = 0; i < this.quadNodes.count; ++i)\n {\n let branchNode = this.quadNodes.get(i);\n\n // If this is a branch\n if(!this._isLeaf(branchNode))\n {\n let childUL = this.quadNodes.get(branchNode.firstChild + 0);\n let childUR = this.quadNodes.get(branchNode.firstChild + 1);\n let childLR = this.quadNodes.get(branchNode.firstChild + 2);\n let childLL = this.quadNodes.get(branchNode.firstChild + 3);\n\n if(childUL.numElements == -1 || childUR.numElements == -1 || childLR.numElements == -1 || childLL.numElements == -1)\n {\n // One of the children is another branch\n continue;\n }\n \n let numLeafChildren = childUL.numElements + childUR.numElements + childLR.numElements + childLL.numElements;\n\n // If all of the leaf objects could be combined into one\n if(numLeafChildren <= this.elementsPerNode)\n {\n this.quadNodes.remove(branchNode.firstChild + 0);\n this.quadNodes.remove(branchNode.firstChild + 1);\n this.quadNodes.remove(branchNode.firstChild + 2);\n this.quadNodes.remove(branchNode.firstChild + 3);\n\n if(numLeafChildren == 0)\n {\n branchNode.firstChild = -1;\n branchNode.numElements = 0;\n }\n else\n {\n // Get list of all object nodes referenced by the child leaf nodes\n let childObjectNodes = this._getObjectNodeIdList(childUL.firstChild)\n .concat(this._getObjectNodeIdList(childUR.firstChild))\n .concat(this._getObjectNodeIdList(childLR.firstChild))\n .concat(this._getObjectNodeIdList(childLL.firstChild));\n\n // Get list of all unique scene objects referenced by the object nodes\n let sceneObjects = new Set();\n for(let j = 0; j < childObjectNodes.length; ++j) { sceneObjects.add(this.objectNodes.get(childObjectNodes[j]).objectId); }\n sceneObjects = Array.from(sceneObjects);\n\n // Remove the old object nodes and add new ones\n this.objectNodes.removeGroup(childObjectNodes);\n\n let newObjectNodes = [];\n\n for(let j = 0; j < sceneObjects.length; ++j)\n {\n newObjectNodes.push(new QuadTreeObjectNode(sceneObjects[j]));\n }\n\n let firstChild = this.objectNodes.addGroup(newObjectNodes);\n\n // Build the object node linked list\n for(let j = 0; j < sceneObjects.length - 1; ++j)\n {\n this.objectNodes.get(firstChild + j).next = firstChild + j + 1;\n }\n\n // Turn the branch node into a leaf\n branchNode.firstChild = firstChild; \n branchNode.numElements = newObjectNodes.length;\n }\n }\n }\n }\n }",
"function updateLayerVisibility(){\n visible = [];\n\n for(var i = 0; i < toc.layerInfos[3].layer._tocInfos.length; i++){\n\n var layer = toc.layerInfos[3].layer._tocInfos[i];\n\n if (layer.visible === true){\n\n visible.push(layer.id);\n\n }\n }\n }"
]
| [
"0.650075",
"0.650075",
"0.650075",
"0.60602695",
"0.6041239",
"0.5966542",
"0.5869482",
"0.5647776",
"0.5621197",
"0.5609314",
"0.55820805",
"0.5558085",
"0.5527385",
"0.55081284",
"0.54752636",
"0.5460541",
"0.5450856",
"0.5432929",
"0.5417923",
"0.54133844",
"0.54021364",
"0.53946716",
"0.53825223",
"0.5374112",
"0.5372673",
"0.53602225",
"0.53467387",
"0.53412735",
"0.53328836",
"0.5331411"
]
| 0.6588245 | 0 |
...................................fetching data from timezones.allTimeZones................................... | function all_city_data() {
var all_city = timezones.allTimeZones()
process.send(all_city)
process.exit()
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function getTimezone () {\n let opts = { \n 'pageSize': 1000,\n 'pageNumber': 1\n };\n\n telephonyProvidersEdgeApi.getTelephonyProvidersEdgesTimezones(opts)\n .then((data) => {\n let timezone = data.entities;\n timezone.forEach(addTimezoneToSelect);\n })\n .catch((err) => {\n console.log('There was a failure calling getTimezones');\n console.error(err);\n $(\"#siteFailedModal\").modal();\n document.getElementById(\"siteError\").innerHTML = err.body.message;\n });\n}",
"function getTZData(){\n let timeStampUTC = Date.now()/1000\n let googTZapiURL = \"https://maps.googleapis.com/maps/api/timezone/json?location=\" + countryLat + \",\" + countryLong + \"×tamp=\" + timeStampUTC + \"&key=\" + googKey\n return $.get(googTZapiURL)\n}",
"function addAllTimeZones() {\n const countriesCodeAndName = [\n [\"AD\", \"Andorra\"],\n [\"AE\", \"United Arab Emirates\"],\n [\"AF\", \"Afghanistan\"],\n [\"AG\", \"Antigua & Barbuda\"],\n [\"AI\", \"Anguilla\"],\n [\"AL\", \"Albania\"],\n [\"AM\", \"Armenia\"],\n [\"AO\", \"Angola\"],\n [\"AQ\", \"Antarctica\"],\n [\"AR\", \"Argentina\"],\n [\"AS\", \"Samoa (American)\"],\n [\"AT\", \"Austria\"],\n [\"AU\", \"Australia\"],\n [\"AW\", \"Aruba\"],\n [\"AX\", \"Aaland Islands\"],\n [\"AZ\", \"Azerbaijan\"],\n [\"BA\", \"Bosnia & Herzegovina\"],\n [\"BB\", \"Barbados\"],\n [\"BD\", \"Bangladesh\"],\n [\"BE\", \"Belgium\"],\n [\"BF\", \"Burkina Faso\"],\n [\"BG\", \"Bulgaria\"],\n [\"BH\", \"Bahrain\"],\n [\"BI\", \"Burundi\"],\n [\"BJ\", \"Benin\"],\n [\"BL\", \"St Barthelemy\"],\n [\"BM\", \"Bermuda\"],\n [\"BN\", \"Brunei\"],\n [\"BO\", \"Bolivia\"],\n [\"BQ\", \"Caribbean Netherlands\"],\n [\"BR\", \"Brazil\"],\n [\"BS\", \"Bahamas\"],\n [\"BT\", \"Bhutan\"],\n [\"BW\", \"Botswana\"],\n [\"BY\", \"Belarus\"],\n [\"BZ\", \"Belize\"],\n [\"CA\", \"Canada\"],\n [\"CC\", \"Cocos (Keeling) Islands\"],\n [\"CD\", \"Congo (Dem. Rep.)\"],\n [\"CF\", \"Central African Rep.\"],\n [\"CG\", \"Congo (Rep.)\"],\n [\"CH\", \"Switzerland\"],\n [\"CI\", \"Cote d'Ivoire\"],\n [\"CK\", \"Cook Islands\"],\n [\"CL\", \"Chile\"],\n [\"CM\", \"Cameroon\"],\n [\"CN\", \"China\"],\n [\"CO\", \"Colombia\"],\n [\"CR\", \"Costa Rica\"],\n [\"CU\", \"Cuba\"],\n [\"CV\", \"Cape Verde\"],\n [\"CW\", \"Curacao\"],\n [\"CX\", \"Christmas Island\"],\n [\"CY\", \"Cyprus\"],\n [\"CZ\", \"Czech Republic\"],\n [\"DE\", \"Germany\"],\n [\"DJ\", \"Djibouti\"],\n [\"DK\", \"Denmark\"],\n [\"DM\", \"Dominica\"],\n [\"DO\", \"Dominican Republic\"],\n [\"DZ\", \"Algeria\"],\n [\"EC\", \"Ecuador\"],\n [\"EE\", \"Estonia\"],\n [\"EG\", \"Egypt\"],\n [\"EH\", \"Western Sahara\"],\n [\"ER\", \"Eritrea\"],\n [\"ES\", \"Spain\"],\n [\"ET\", \"Ethiopia\"],\n [\"FI\", \"Finland\"],\n [\"FJ\", \"Fiji\"],\n [\"FK\", \"Falkland Islands\"],\n [\"FM\", \"Micronesia\"],\n [\"FO\", \"Faroe Islands\"],\n [\"FR\", \"France\"],\n [\"GA\", \"Gabon\"],\n [\"GB\", \"Britain (UK)\"],\n [\"GD\", \"Grenada\"],\n [\"GE\", \"Georgia\"],\n [\"GF\", \"French Guiana\"],\n [\"GG\", \"Guernsey\"],\n [\"GH\", \"Ghana\"],\n [\"GI\", \"Gibraltar\"],\n [\"GL\", \"Greenland\"],\n [\"GM\", \"Gambia\"],\n [\"GN\", \"Guinea\"],\n [\"GP\", \"Guadeloupe\"],\n [\"GQ\", \"Equatorial Guinea\"],\n [\"GR\", \"Greece\"],\n [\"GS\", \"South Georgia & the South Sandwich Islands\"],\n [\"GT\", \"Guatemala\"],\n [\"GU\", \"Guam\"],\n [\"GW\", \"Guinea-Bissau\"],\n [\"GY\", \"Guyana\"],\n [\"HK\", \"Hong Kong\"],\n [\"HN\", \"Honduras\"],\n [\"HR\", \"Croatia\"],\n [\"HT\", \"Haiti\"],\n [\"HU\", \"Hungary\"],\n [\"ID\", \"Indonesia\"],\n [\"IE\", \"Ireland\"],\n [\"IL\", \"Israel\"],\n [\"IM\", \"Isle of Man\"],\n [\"IN\", \"India\"],\n [\"IO\", \"British Indian Ocean Territory\"],\n [\"IQ\", \"Iraq\"],\n [\"IR\", \"Iran\"],\n [\"IS\", \"Iceland\"],\n [\"IT\", \"Italy\"],\n [\"JE\", \"Jersey\"],\n [\"JM\", \"Jamaica\"],\n [\"JO\", \"Jordan\"],\n [\"JP\", \"Japan\"],\n [\"KE\", \"Kenya\"],\n [\"KG\", \"Kyrgyzstan\"],\n [\"KH\", \"Cambodia\"],\n [\"KI\", \"Kiribati\"],\n [\"KM\", \"Comoros\"],\n [\"KN\", \"St Kitts & Nevis\"],\n [\"KP\", \"Korea (North)\"],\n [\"KR\", \"Korea (South)\"],\n [\"KW\", \"Kuwait\"],\n [\"KY\", \"Cayman Islands\"],\n [\"KZ\", \"Kazakhstan\"],\n [\"LA\", \"Laos\"],\n [\"LB\", \"Lebanon\"],\n [\"LC\", \"St Lucia\"],\n [\"LI\", \"Liechtenstein\"],\n [\"LK\", \"Sri Lanka\"],\n [\"LR\", \"Liberia\"],\n [\"LS\", \"Lesotho\"],\n [\"LT\", \"Lithuania\"],\n [\"LU\", \"Luxembourg\"],\n [\"LV\", \"Latvia\"],\n [\"LY\", \"Libya\"],\n [\"MA\", \"Morocco\"],\n [\"MC\", \"Monaco\"],\n [\"MD\", \"Moldova\"],\n [\"ME\", \"Montenegro\"],\n [\"MF\", \"St Martin (French part)\"],\n [\"MG\", \"Madagascar\"],\n [\"MH\", \"Marshall Islands\"],\n [\"MK\", \"Macedonia\"],\n [\"ML\", \"Mali\"],\n [\"MM\", \"Myanmar (Burma)\"],\n [\"MN\", \"Mongolia\"],\n [\"MO\", \"Macau\"],\n [\"MP\", \"Northern Mariana Islands\"],\n [\"MQ\", \"Martinique\"],\n [\"MR\", \"Mauritania\"],\n [\"MS\", \"Montserrat\"],\n [\"MT\", \"Malta\"],\n [\"MU\", \"Mauritius\"],\n [\"MV\", \"Maldives\"],\n [\"MW\", \"Malawi\"],\n [\"MX\", \"Mexico\"],\n [\"MY\", \"Malaysia\"],\n [\"MZ\", \"Mozambique\"],\n [\"NA\", \"Namibia\"],\n [\"NC\", \"New Caledonia\"],\n [\"NE\", \"Niger\"],\n [\"NF\", \"Norfolk Island\"],\n [\"NG\", \"Nigeria\"],\n [\"NI\", \"Nicaragua\"],\n [\"NL\", \"Netherlands\"],\n [\"NO\", \"Norway\"],\n [\"NP\", \"Nepal\"],\n [\"NR\", \"Nauru\"],\n [\"NU\", \"Niue\"],\n [\"NZ\", \"New Zealand\"],\n [\"OM\", \"Oman\"],\n [\"PA\", \"Panama\"],\n [\"PE\", \"Peru\"],\n [\"PF\", \"French Polynesia\"],\n [\"PG\", \"Papua New Guinea\"],\n [\"PH\", \"Philippines\"],\n [\"PK\", \"Pakistan\"],\n [\"PL\", \"Poland\"],\n [\"PM\", \"St Pierre & Miquelon\"],\n [\"PN\", \"Pitcairn\"],\n [\"PR\", \"Puerto Rico\"],\n [\"PS\", \"Palestine\"],\n [\"PT\", \"Portugal\"],\n [\"PW\", \"Palau\"],\n [\"PY\", \"Paraguay\"],\n [\"QA\", \"Qatar\"],\n [\"RE\", \"Reunion\"],\n [\"RO\", \"Romania\"],\n [\"RS\", \"Serbia\"],\n [\"RU\", \"Russia\"],\n [\"RW\", \"Rwanda\"],\n [\"SA\", \"Saudi Arabia\"],\n [\"SB\", \"Solomon Islands\"],\n [\"SC\", \"Seychelles\"],\n [\"SD\", \"Sudan\"],\n [\"SE\", \"Sweden\"],\n [\"SG\", \"Singapore\"],\n [\"SH\", \"St Helena\"],\n [\"SI\", \"Slovenia\"],\n [\"SJ\", \"Svalbard & Jan Mayen\"],\n [\"SK\", \"Slovakia\"],\n [\"SL\", \"Sierra Leone\"],\n [\"SM\", \"San Marino\"],\n [\"SN\", \"Senegal\"],\n [\"SO\", \"Somalia\"],\n [\"SR\", \"Suriname\"],\n [\"SS\", \"South Sudan\"],\n [\"ST\", \"Sao Tome & Principe\"],\n [\"SV\", \"El Salvador\"],\n [\"SX\", \"St Maarten (Dutch part)\"],\n [\"SY\", \"Syria\"],\n [\"SZ\", \"Swaziland\"],\n [\"TC\", \"Turks & Caicos Is\"],\n [\"TD\", \"Chad\"],\n [\"TF\", \"French Southern & Antarctic Lands\"],\n [\"TG\", \"Togo\"],\n [\"TH\", \"Thailand\"],\n [\"TJ\", \"Tajikistan\"],\n [\"TK\", \"Tokelau\"],\n [\"TL\", \"East Timor\"],\n [\"TM\", \"Turkmenistan\"],\n [\"TN\", \"Tunisia\"],\n [\"TO\", \"Tonga\"],\n [\"TR\", \"Turkey\"],\n [\"TT\", \"Trinidad & Tobago\"],\n [\"TV\", \"Tuvalu\"],\n [\"TW\", \"Taiwan\"],\n [\"TZ\", \"Tanzania\"],\n [\"UA\", \"Ukraine\"],\n [\"UG\", \"Uganda\"],\n [\"UM\", \"US minor outlying islands\"],\n [\"US\", \"United States\"],\n [\"UY\", \"Uruguay\"],\n [\"UZ\", \"Uzbekistan\"],\n [\"VA\", \"Vatican City\"],\n [\"VC\", \"St Vincent\"],\n [\"VE\", \"Venezuela\"],\n [\"VG\", \"Virgin Islands (UK)\"],\n [\"VI\", \"Virgin Islands (US)\"],\n [\"VN\", \"Vietnam\"],\n [\"VU\", \"Vanuatu\"],\n [\"WF\", \"Wallis & Futuna\"],\n [\"WS\", \"Samoa (western)\"],\n [\"YE\", \"Yemen\"],\n [\"YT\", \"Mayotte\"],\n [\"ZA\", \"South Africa\"],\n [\"ZM\", \"Zambia\"],\n [\"ZW\", \"Zimbabwe\"],\n ];\n let zoneData = [];\n for (let index = 0; index < countriesCodeAndName.length; index++) {\n moment.tz\n .zonesForCountry(countriesCodeAndName[index][0])\n .forEach((zone) => {\n zoneData.push({\n countryCode: countriesCodeAndName[index][0],\n countryName: countriesCodeAndName[index][1],\n zoneName: zone\n .split(\"/\")\n [zone.split(\"/\").length - 1].replace(\"_\", \" \"),\n zoneTimeDate: moment().tz(zone),\n completZoneName: zone,\n });\n });\n }\n return zoneData;\n}",
"function lookupTimezones(cityN) {\n /*\n var myUrl;\n switch (cityN) {\n\n //If its london----------------------------------------------------------------\n case 'London':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=Europe/London';\n break;\n\n //If its New York------------------------------------------------------------\n case 'NewYork':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=America/NewYork';\n break;\n\n //If its Santo Domingo------------------------------------------------------------\n case 'SantoDomingo':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=America/SantoDomingo';\n break;\n //If its Turkey------------------------------------------------------------\n case 'Turkey':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=Asia/Turkey';\n break;\n\n //If its Paris------------------------------------------------------------\n case 'Paris':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=Europe/Paris';\n\n break;\n default:break;\n }\nconsole.log(myUrl);\n $.ajax({\n datatype: 'JSON',\n url: myUrl,\n success: function(Response){\n console.log(Response);\n var myDate = new Date(Response.timestamp*1100);\n console.log(myDate);\n var myhour= myDate.getHours();\n console.log(myhour);\n },\n complete: function(){}\n\n\n\n });\n */\n }",
"function getZones() {\n return srvModelZone.getZones();\n }",
"renderTimezoneSelect() {\n // Users timezone\n const userTimezone = {\n [this.currentTimezone]:\n 'Your timezone: (GMT' + moment.tz(this.currentTimezone).format('Z') + ') ' + this.currentTimezone,\n };\n\n // List with common timezones\n const commonTimezones = {\n 'Pacific/Honolulu': '(GMT-10:00) Hawaiian/Aleutian Time',\n 'America/Anchorage': '(GMT-08:00) Alaska Time',\n 'America/Los_Angeles': '(GMT-07:00) Pacific Time (US)',\n 'America/Phoenix': '(GMT-07:00) Mountain Time (Arizona)',\n 'America/Denver': '(GMT-06:00) Mountain Time (US)',\n 'America/Chicago': '(GMT-05:00) Central Time (US)',\n 'America/New_York': '(GMT-04:00) Eastern Time (US)',\n 'America/Indiana/Knox': '(GMT-05:00) Central Time (Indiana)',\n 'America/Indiana/Indianapolis': '(GMT-04:00) Eastern Time (Indiana)',\n 'America/Regina': '(GMT-06:00) Central Time (Saskatchewan)',\n 'America/Monterrey': '(GMT-05:00) Central Time (Mexico City, Monterey)',\n 'America/Lima': '(GMT-05:00) UTC/GMT -5 hours',\n 'America/Manaus': '(GMT-04:00) Atlantic Time',\n 'America/Montevideo': '(GMT-03:00) Uruguay',\n 'America/Puerto_Rico': '(GMT-04:00) Atlantic Time (Puerto Rico)',\n 'America/Thule': '(GMT-03:00) Western Greenland Time',\n 'America/Sao_Paulo': '(GMT-03:00) Eastern Brazil',\n 'America/St_Johns': '(GMT-02:30) Newfoundland Time',\n 'America/Godthab': '(GMT-02:00) Central Greenland Time',\n 'Etc/GMT+2': '(GMT-02:00) GMT-2:00',\n 'America/Scoresbysund': '(GMT+00:00) Eastern Greenland Time',\n 'Atlantic/Reykjavik': '(GMT+00:00) Western European Time (Iceland)',\n UTC: '(GMT+00:00) UTC',\n 'Europe/London': '(GMT+01:00) British Time (London)',\n 'Etc/GMT-1': '(GMT+01:00) GMT+1:00',\n 'Europe/Lisbon': '(GMT+01:00) Western European Time (Lisbon)',\n 'Europe/Paris': '(GMT+02:00) Western European Time',\n 'Europe/Berlin': '(GMT+02:00) Central European Time',\n 'Europe/Bucharest': '(GMT+03:00) Eastern European Time',\n 'Africa/Johannesburg': '(GMT+02:00) South Africa Standard Time',\n 'Africa/Kampala': '(GMT+03:00) Eastern Africa Time',\n 'Etc/GMT-3': '(GMT+03:00) Moscow',\n 'Asia/Tehran': '(GMT+04:30) Iran Standard Time',\n 'Asia/Dubai': '(GMT+04:00) UAE (Dubai)',\n 'Asia/Karachi': '(GMT+05:00) Pakistan Standard Time (Karachi)',\n 'Asia/Calcutta': '(GMT+05:30) India',\n 'Asia/Dhaka': '(GMT+06:00) Bangladesh Standard Time',\n 'Asia/Jakarta': '(GMT+07:00) Western Indonesian Time (Jakarta)',\n 'Asia/Bangkok': '(GMT+07:00) Thailand (Bangkok)',\n 'Asia/Hong_Kong': '(GMT+08:00) Hong Kong',\n 'Asia/Singapore': '(GMT+08:00) Singapore',\n 'Australia/West': '(GMT+08:00) Australian Western Time',\n 'Asia/Tokyo': '(GMT+09:00) Tokyo',\n 'Australia/North': '(GMT+09:30) Australian Central Time (Northern Territory)',\n 'Australia/Adelaide': '(GMT+09:30) Australian Central Time (Adelaide)',\n 'Australia/Queensland': '(GMT+10:00) Australian Eastern Time (Queensland)',\n 'Australia/Sydney': '(GMT+10:00) Australian Eastern Time (Sydney)',\n 'Pacific/Noumea': '(GMT+11:00) Noumea, New Caledonia',\n 'Pacific/Norfolk': '(GMT+11:00) Norfolk Island (Australia)',\n 'Pacific/Tarawa': '(GMT+12:00) Tarawa',\n 'Pacific/Auckland': '(GMT+12:00) New Zealand Time',\n 'Pacific/Apia': '(GMT+13:00) Apia, Samoa',\n };\n\n const selectOptions = {\n options: Object.assign(userTimezone, commonTimezones),\n };\n\n // Parse select html\n const $select = document.querySelector('#timezone-select');\n const source = document.querySelector('#timezone-template').innerHTML;\n const template = Handlebars.compile(source);\n $select.innerHTML = template(selectOptions);\n }",
"function getApiSchemas() {\n return telephonyScheduler\n .getAvailableTimeZones()\n .then((availableTimeZones) => {\n self.timeZones = availableTimeZones;\n });\n }",
"function sendAllSelectedOptions(){\nvar allOptions = document.getElementsByClassName(\"allSelects\");\n// for(var i=0; i<allOptions.length; i++){\n// console.log(\"These are the values you need FOR COUNTRY NAME- \"+allOptions[i].value);\n// }\n\n//var allZones = document.getElementsByClassName(\"allZones\");\nvar timeZone = document.getElementsByClassName(\"allZones\");\nfor(var i=0; i<timeZone.length; i++){\nconsole.log(\"These are the values you need FOR ALL TIME ZONES- \"+timeZone[i].value);\n }\n\n var xhttp = new XMLHttpRequest();\nvar dataURL = 'http://api.timezonedb.com/v2/list-time-zone?key=LHW0VPUEFWFT&format=json';\n\n//var timeZone = [\"America/Los_Angeles\", \"Asia/Kolkata\", \"Africa/Lagos\",\"America/New_York\",\"Europe/London\"];\n//var timeZone = [\"Asia/Kolkata\", \"America/New_York\", \"Asia/Kolkata\",\"Asia/Kolkata\",\"Asia/Kolkata\"];\n\n//var timeZone = JSON.parse(JSON.stringify(allZones));\n\n/*for(var i=0;i<4;i++)\n {\n console.log(\"Getting Data \" + allZones[i]);\n } */\n\nvar arrayLength = timeZone.length;\nvar allTime = [];\n\n\nsetInterval(function(){\nxhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n // Typical action to be performed when the document is ready:\n var results = JSON.parse(xhttp.responseText);\n console.log(results);\n var localDate = new Date();\n //Local Time GMT Offset Correction\n var timeOffset = localDate.getTimezoneOffset();\n var hours = localDate.getHours();\n var minutes = \"0\" + localDate.getMinutes();\n var seconds = \"0\" + localDate.getSeconds();\n var localTime = hours + minutes.substr(-2);\n localTime = parseInt(localTime, 10);\n console.log(\"Local Time in 24hours format: \" + localTime);\n //Format 12 Hours\n var hoursAMPM = (hours >= 12 ? 'PM' : 'AM');\n hours = hours % 12 || 12;\n var formattedLocalTime = hours + ':' + minutes.substr(-2) + ' ' + hoursAMPM;\n document.getElementById(\"localTime\").innerHTML = \"Local time: \" + formattedLocalTime;\n document.getElementById(\"cityTime\").innerHTML = \"The time in the selected Cities: \";\n var ul = document.getElementById(\"listTime\");\n //ul.removeChild(li);\n var node = document.getElementById('listTime');\n while(node.firstChild){\n node.removeChild(node.firstChild);\n }\n for(var i =0;i<arrayLength;i++)\n {\n for(var j =0;j<424;j++)\n {\n if(timeZone[i].value == results.zones[j].zoneName)\n {\n //console.log(results.zones[j].zoneName);\n //getFormattedTime(results.zones[j].timestamp);\n //console.log(results.zones[j].timestamp);\n //Time of location in UTC\n var locationTime = results.zones[j].timestamp + (timeOffset * 60);\n var locationDate = new Date(locationTime * 1000);\n // Hours part from the timestamp\n hours = locationDate.getHours();\n // Minutes part from the timestamp\n minutes = \"0\" + locationDate.getMinutes();\n // Seconds part from the timestamp\n seconds = \"0\" + locationDate.getSeconds();\n // Will display time in 10:30:23 format\n var newTime = hours + minutes.substr(-2); //24 hour format for calculation\n newTime = parseInt(newTime, 10);\n //console.log(newTime);\n allTime[i] = newTime;\n //Format 12 Hours\n hoursAMPM = (hours >= 12 ? 'PM' : 'AM');\n hours = hours % 12 || 12;\n var formattedTime = hours + ':' + minutes.substr(-2) + ' ' + hoursAMPM;\n //$('.time').html(formattedTime);\n //allTime[i] = formattedTime;\n console.log(timeZone[i].value + \" : \" + formattedTime);\n var li = document.createElement(\"li\");\n li.innerHTML = timeZone[i].value + \" : \" + formattedTime;\n //li.appendChild(document.createTextNode(timeZone[i].value + \" : \" + formattedTime));\n ul.appendChild(li);\n }\n }\n\n }\n collabTime(allTime, localTime);\n\n }\n};\n\n\nxhttp.open(\"GET\", dataURL, true);\nxhttp.send();\n\n}, 2000);\n\n\nfunction collabTime(calcTime, localTime)\n{\n //console.log(\"Local City: \" + localTime);\n var collabCheck = [\"\"];\n var collabStatus;\n if(localTime>=800 && localTime< 2200)\n {\n console.log(\"Local City: Collab\");\n for(var i =0;i<arrayLength;i++)\n {\n console.log(calcTime[i] );\n if(calcTime[i]>=800 && calcTime[i] < 2200)\n {\n collabCheck[i] = \"Collab\";\n }\n else\n {\n collabCheck[i] = \"No Collab\";\n }\n console.log(collabCheck[i]);\n }\n for(var i =0;i<arrayLength-1;i++)\n {\n if(collabCheck[i] == \"Collab\" && collabCheck[i] == collabCheck[i+1])\n {\n collabStatus = \"true\";\n }\n else\n {\n collabStatus = \"false\";\n break;\n }\n }\n console.log(collabStatus);\n document.getElementById(\"collabState\").innerHTML = \"Collaboration is possible\";\n }\n else\n {\n console.log(\"Local City: No Collab\");\n document.getElementById(\"collabState\").innerHTML = \"Collaboration is not possible\";\n }\n}\n\n\n} //end of function",
"function places_with_walltime(goal_time){\n\tvar countries = new Array;\n\tvar timezones = new Array;\n\t//for all countries where walltime == goal_time, array_push that country name and timezone into their respective arrays\n\tfor (var zid in zonelist) {\n\t\tif (zonelist.hasOwnProperty(zid)) {\n\t\t\tvar walltime = moment().tz(zid).hours();\n\t\t\tif (walltime == goal_time && ztc(zid)!== false){\n\t\t\t\tcountries.push(ztc(zid));\n\t\t\t\ttimezones.push(moment.tz(zid).format(\"Z\"));\n\t\t\t}\t\t\t\n\t\t}\n\t};\n\tvar res = {countries: countries, timezones: timezones};\n\treturn res;\n}",
"function searchAllTimeZones(stringToSearch) {\n let foundAllTimeZones = [];\n addAllTimeZones().forEach(function (zone) {\n let zoneSearchHit = false;\n if (zone.countryCode.toLowerCase().search(stringToSearch) != -1) {\n zoneSearchHit = true;\n }\n if (zone.countryName.toLowerCase().search(stringToSearch) != -1) {\n zoneSearchHit = true;\n }\n if (zone.zoneName.toLowerCase().search(stringToSearch) != -1) {\n zoneSearchHit = true;\n }\n if (zoneSearchHit == true) {\n foundAllTimeZones.push({...zone});\n }\n });\n allTimeZonesToRender = foundAllTimeZones; // update the allTimeZonesToRender with a list of timeZones in which the search string was found\n formatAllTimeZones();\n addAllTimeZonesListners();\n}",
"function custom_fetchDmzZones(selectId, custom_selectedZone) {\n custom_appendDefaultOptions(selectId, custom_selectedZone);\n\n $.ajax({\n url : \"/api/v1.0/zones\",\n type: 'GET',\n dataType : 'json',\n cache: false,\n success : function(data) {\n var zonesList = data.zones;\n if (zonesList && zonesList.length > 0) {\n custom_fillDmzZonesSelect(selectId, custom_selectedZone, zonesList);\n }\n },\n error: function(jqXHR, textStatus, errorThrown) {\n alert(\"Error occurred on retrieving Network Zone.\");\n }\n })\n }",
"get availabilityZones() {\n return this.getListAttribute('availability_zones');\n }",
"get availabilityZones() {\n return this.getListAttribute('availability_zones');\n }",
"async function GetTheTimezoneInfoForAspecificLocation() {\n let timeService = new time.TimeService(process.env.MICRO_API_TOKEN);\n let rsp = await timeService.zone({\n location: \"London\",\n });\n console.log(rsp);\n}",
"function addAllTimeZonesListners() {\n allTimeZonesToRender.forEach(function (zone, index) {\n const button = document.getElementById(\"Add_\" + String(index));\n if (button) {\n button.addEventListener(\"click\", function () {\n // becauase datetime cannot be saved in localstorage I\n // only chose to save these fields. With these\n // fields the corresponding dateTime can be found.\n const toLocalStorage = {\n countryCode: zone.countryCode,\n countryName: zone.countryName,\n zoneName: zone.zoneName,\n };\n saveTimeZoneToFavorites(toLocalStorage); // the new favorite timeZone nees to be saved to localstorage\n updateFavoriteTimeZones(); // after an add the favoriteTimeZonesToRender grows\n formatFavoriteTimeZones(); //because favoriteTimeZonesToRender has grown the table has to be rerenderd.\n // addFavoriteTimeZonesListners(); // the rerenderd table needs to have the button listeners added.\n });\n }\n });\n}",
"function object_literal(){\n date.tz(timezoneDataService.myLocation);\n vm.zone_list.push({name: timezoneDataService.myLocation, data: {item:[]}});\n for( var i = 0; i < timezoneDataService.participants.length; i++) {\n if (timezoneDataService.participants[i].address) {\n vm.zone_list.push({name : timezoneDataService.participants[i].address, data : {item:[]} });\n }\n }\n }",
"function zonaHoraria() {\n var offset = (new Date()).getTimezoneOffset();\n var timezones = {\n '-12': 'Pacific/Kwajalein',\n '-11': 'Pacific/Samoa',\n '-10': 'Pacific/Honolulu',\n '-9': 'America/Juneau',\n '-8': 'America/Los_Angeles',\n '-7': 'America/Denver',\n '-6': 'America/Mexico_City',\n '-5': 'America/Lima',\n '-4': 'America/Caracas',\n '-3.5': 'America/St_Johns',\n '-3': 'America/Argentina/Buenos_Aires',\n '-2': 'Atlantic/Azores',\n '-1': 'Atlantic/Azores',\n '0': 'Europe/London',\n '1': 'Europe/Paris',\n '2': 'Europe/Helsinki',\n '3': 'Europe/Moscow',\n '3.5': 'Asia/Tehran',\n '4': 'Asia/Baku',\n '4.5': 'Asia/Kabul',\n '5': 'Asia/Karachi',\n '5.5': 'Asia/Calcutta',\n '6': 'Asia/Colombo',\n '7': 'Asia/Bangkok',\n '8': 'Asia/Singapore',\n '9': 'Asia/Tokyo',\n '9.5': 'Australia/Darwin',\n '10': 'Pacific/Guam',\n '11': 'Asia/Magadan',\n '12': 'Asia/Kamchatka'\n };\n return timezones[-offset / 60];\n}",
"function updateFavoriteTimeZones() {\n let tempFavZones = [];\n locallySavedTimeZones.forEach(function (favZone) {\n allTimeZones.forEach(function (allZone) {\n if (\n favZone.countryName == allZone.countryName &&\n favZone.countryCode == allZone.countryCode &&\n favZone.zoneName == allZone.zoneName\n ) {\n // this is needed because when the zone is copied to favorite zones\n // the old zoneTimeDate is used, not the constantly updated zoneTimeDate in allTimeZones\n //therefore the zoneTimeDate needs to be updated to current timeDate\n let allZoneCopy = {...allZone};\n allZoneCopy.zoneTimeDate = moment().tz(allZoneCopy.completZoneName);\n tempFavZones.push(allZoneCopy);\n }\n });\n });\n favoriteTimeZonesToRender = tempFavZones;\n}",
"async getZones() {\n try {\n let response = await getZones();\n var zones = response.data.data;\nconsole.log(response)\n //looping over zones and converting lat and lng to float to be able to draw on map.\n zones.forEach((zoneObject) => {\n let points = zoneObject.points;\n let newPoints = points.map((a) => {\n return { lat: parseFloat(a.lat), lng: parseFloat(a.lng) };\n });\n zoneObject.points = newPoints;\n });\n\n // looping over zones and creating polygons for each zone and adding them to map.\n zones.forEach((zone) => {\n this.createPolygon(zone);\n });\n } catch (error) {\n console.log(error);\n }\n\n this.downloadZones();\n }",
"function getCurrentHourData() {\n\t return result.filter(function (item) { \n\t\t\t\tvar date = new Date((item.timestampMs/1000)*1000);\n\t\t\t\tvar hours = date.getHours();\n\t\t\t\treturn hours === d.getHours();\n\t\t\t})\n\t\t\t.map( function(item){ \n\t\t\t\treturn [item.latitudeE7 * SCALAR_E7, item.longitudeE7 * SCALAR_E7]; \n\t\t\t})\n\t }",
"async function getZones() {\r\n let res = await fetch(STOCK_API_URL + \"getZones\", {\r\n method: 'GET',\r\n mode: 'cors',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n }\r\n })\r\n .then(res => res.ok ? res.json() : \"FAIL\");\r\n return res;\r\n}",
"function tableTimezone() {\n tableBase.apply( this, arguments ); // initialize parent object's members\n \n this.init = function()\n {\n this.name = \"timezone\";\n \n this.desc = \"idtz SMALLSERIAL PRIMARY KEY\";\n this.desc += \", timezone TEXT not null\";\n this.desc += \", UNIQUE( timezone )\";\n };\n \n this.load = function( client ) // override of the method of the base object\n {\n // chargement a partir du fichier de moment-timezone\n \n var file = \"../node_modules/moment-timezone/data/unpacked/latest.json\";\n var chaine = fs.readFileSync( file, \"UTF-8\" );\n var timezones = JSON.parse( chaine );\n \n timezones.zones.forEach( function( item, index ) {\n \n // insertion en bdd\n \n var params = [ item.name ];\n var query = client.query( \"INSERT INTO timezone( timezone ) values( $1 )\", params );\n \n query.on( 'error', function( error ) {\n logger.trace( \"ERROR : \" + error.message );\n });\n });\n \n // on liste le contenu de la tableau\n \n var query2 = client.query( \"SELECT COUNT(*) FROM timezone\" );\n \n query2.on( 'error', function( error ) {\n logger.trace( \"ERROR : \" + error.message );\n });\n \n query2.on('row', function( row, result ) {\n result.addRow(row); // accumule les records dans l'objets result, cela permettra d'utiliser result.rows[] dans le gestionnaire de l'event 'end'\n }); \n\n query2.on('end', function( result ) {\n if( result.rowCount <= 0 ) { return; }\n logger.trace( \"table timezone count : \" + result.rows[0].count );\n }); \n };\n}",
"function getRegions() {\n\tif (this.readyState == READYSTATE_COMPLETE && this.status == STATUS_OK) {\n\t\tvar response=this.responseXML;\n\t\t/* the regions select */\n\t\tvar select = document.getElementById('region_select');\n\t\tif (response == null) {\n\t\t\t/* remove last options */\n\t\t\tselect.innerHTML = \"\";\n\t\t\t/* disable select */\n\t\t\tselect.disabled = true;\n\t\t} else {\n\t\t\tselect.innerHTML = \"\";\n\t\t\t/* enable the regions select */\n\t\t\tselect.disabled = false;\n\t\t\t/* take the response from ajax */\n\t\t\tvar xml = response.documentElement;\n\t\t\t/* the regions */\n\t\t\tvar regionElements = xml.getElementsByTagName('region');\n\t\t\tif (regionElements.length == 0) {\n\t\t\t\t/* the country does not have regions */\n\t\t\t\tselect.disabled = true;\n\t\t\t} else {\n\t\t\t\tvar reg_option_number = 0;\n\t\t\t\tvar options = \"\";\n\t\t\t\t/* append the options to the regions select */\n\t\t\t\tfor (var i = 0; i < regionElements.length; i++) {\n\t\t\t\t\tvar regionElement = regionElements[i];\n\t\t\t\t\tvar regionChilds = regionElement.childNodes;\n\t\t\t\t\tselect.options[reg_option_number] = new Option(regionChilds[1].childNodes[0].nodeValue, regionChilds[0].childNodes[0].nodeValue);\n\t\t\t\t\treg_option_number = reg_option_number + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t/* the timezones select */\n\t\t\tvar tm_select = document.getElementById('timezone');\n\t\t\ttm_select.innerHTML = \"\";\n\t\t\t/* get the timezones from the response */\n\t\t\tvar timezoneElements = xml.getElementsByTagName('timezone');\n\t\t\tvar tm_options = \"\";\n\t\t\tvar tm_option_number = 0;\n\t\t\t/* complete the options of the timezones select */\n\t\t\tfor (var i = 0; i < timezoneElements.length; i++) {\n\t\t\t\tvar timezoneElement = timezoneElements[i];\n\t\t\t\tvar timezoneChilds = timezoneElement.childNodes;\n\t\t\t\ttm_select[tm_option_number] = new Option(timezoneChilds[1].childNodes[0].nodeValue, timezoneChilds[0].childNodes[0].nodeValue);\n\t\t\t\ttm_option_number = tm_option_number + 1;\n\t\t\t}\n\t\t}\n\t}\n}",
"startAllZones(data, duration) {\n // Set array to empty in case there is data already set\n this.zoneData = [];\n for (let i = 0; i < data.length; i++) {\n this.zoneData[i] = {\n 'id': data[i].id,\n 'duration': duration * 60,\n 'sortOrder': i + 1,\n }\n }\n this.startZones();\n }",
"getZones(countryId) {\n countryId = countryId || null\n let obj = this.settings.cartConfig.zones\n\n if (countryId !== null && !isNaN(countryId)) {\n return this.zones[countryId]\n } else if (Object.keys(this.zones).length === 1) {\n // Default country\n let zones = this.zones[Object.keys(this.zones)[0]]\n // TODO: This works, but if countryId isn't supplied and zones haven't loaded\n // it returns an object instead of an array (which is expected); we addressed this\n // in the return but yeah, this needs to be rewritten\n return (zones instanceof Array) ? zones : [\n {\n id: null,\n value: ''\n }\n ]\n }\n\n return [\n {\n id: null,\n value: ''\n }\n ]\n }",
"function getCurrentTime(w_lon,w_lat){\r\n $.ajax({\r\n url:'libs/php/getTimezone.php',\r\n type:'POST',\r\n data:{lat:w_lat,\r\n lon: w_lon },\r\n dataType: 'JSON',\r\n success:(result)=> {\r\n //console.log('----------get data from timeZone api------')\r\n //console.log(result);\r\n let timezone = result.data.timezoneId;\r\n // console.log(timezone)\r\n $('#timezoneId').html(result['data']['timezoneId']);\r\n $('#sunrise').html(result['data']['sunrise']);\r\n $('#sunset').html(result['data']['sunset']);\r\n //$('#time').html(result['data']['time']);\r\n let DTime =result['data']['time'];\r\n let CDTime = new Date(DTime)\r\n let CDT =CDTime.toUTCString();\r\n // console.log(CDT)\r\n $('#time').html(`${CDT}`);\r\n\r\n }\r\n })\r\n\r\n}",
"_retrieveSunTimes(callback) {\n\t\tWeatherRecord.find({}, (err, doc) => {\n\t\t\tif (err) callback(err, null);\n\t\t\telse callback(null, doc.sun_times);\n\t\t});\n\t}",
"getLocalTime (data) {\n\t\tlet timezone = data.hotel.timezone;\n\t\treturn moment().tz(timezone);\n\t}",
"function dateTimeFunc(latitude,longitude){\n let timeZone_API_Address = `http://api.timezonedb.com/v2.1/get-time-zone?key=${timeZone_API_Key}&format=json&by=position&lat=${latitude}&lng=${longitude}`\n fetch(timeZone_API_Address)\n .then((response)=>{\n let data2 = response.json();\n \n return data2\n \n \n \n \n \n })\n .then((data2)=>{\n datetime=data2.formatted;\n const usertimezoneElement = document.getElementById(\"user-time-zone\");\n usertimezoneElement.innerHTML = datetime;\n \n \n\n })\n \n\n }",
"function chooseTimeZone()\r\n{\r\n $('#timeZones').show();\r\n}"
]
| [
"0.74123484",
"0.6824664",
"0.65279114",
"0.6332223",
"0.6302334",
"0.6249967",
"0.6223362",
"0.6193533",
"0.60745037",
"0.602877",
"0.595395",
"0.5923163",
"0.5923163",
"0.5823316",
"0.57803667",
"0.5766893",
"0.5738937",
"0.56979984",
"0.56973153",
"0.56712854",
"0.56580997",
"0.5642459",
"0.56402755",
"0.563358",
"0.561857",
"0.5602524",
"0.55945075",
"0.55818224",
"0.55669445",
"0.5566336"
]
| 0.6850194 | 1 |
...................................fetching data from timezones.timeForOneCity................................... | function get_city_data(city) {
var city_data = timezones.timeForOneCity(city)
process.send(city_data)
process.exit()
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function lookupTimezones(cityN) {\n /*\n var myUrl;\n switch (cityN) {\n\n //If its london----------------------------------------------------------------\n case 'London':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=Europe/London';\n break;\n\n //If its New York------------------------------------------------------------\n case 'NewYork':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=America/NewYork';\n break;\n\n //If its Santo Domingo------------------------------------------------------------\n case 'SantoDomingo':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=America/SantoDomingo';\n break;\n //If its Turkey------------------------------------------------------------\n case 'Turkey':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=Asia/Turkey';\n break;\n\n //If its Paris------------------------------------------------------------\n case 'Paris':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=Europe/Paris';\n\n break;\n default:break;\n }\nconsole.log(myUrl);\n $.ajax({\n datatype: 'JSON',\n url: myUrl,\n success: function(Response){\n console.log(Response);\n var myDate = new Date(Response.timestamp*1100);\n console.log(myDate);\n var myhour= myDate.getHours();\n console.log(myhour);\n },\n complete: function(){}\n\n\n\n });\n */\n }",
"function all_city_data() {\r\n var all_city = timezones.allTimeZones()\r\n process.send(all_city)\r\n process.exit()\r\n}",
"function getTimezone () {\n let opts = { \n 'pageSize': 1000,\n 'pageNumber': 1\n };\n\n telephonyProvidersEdgeApi.getTelephonyProvidersEdgesTimezones(opts)\n .then((data) => {\n let timezone = data.entities;\n timezone.forEach(addTimezoneToSelect);\n })\n .catch((err) => {\n console.log('There was a failure calling getTimezones');\n console.error(err);\n $(\"#siteFailedModal\").modal();\n document.getElementById(\"siteError\").innerHTML = err.body.message;\n });\n}",
"function getTZData(){\n let timeStampUTC = Date.now()/1000\n let googTZapiURL = \"https://maps.googleapis.com/maps/api/timezone/json?location=\" + countryLat + \",\" + countryLong + \"×tamp=\" + timeStampUTC + \"&key=\" + googKey\n return $.get(googTZapiURL)\n}",
"async function GetTheTimezoneInfoForAspecificLocation() {\n let timeService = new time.TimeService(process.env.MICRO_API_TOKEN);\n let rsp = await timeService.zone({\n location: \"London\",\n });\n console.log(rsp);\n}",
"async function getCityData() {\n if (!user) return;\n try {\n const URL = `https://travel-tracker-be.herokuapp.com/cities?countryId=${state.currentCountry._id}`;\n const cities = await fetch(URL).then(res => res.json());\n setState(prevState => ({\n ...prevState,\n currentCountry: {\n ...prevState.currentCountry,\n cities\n }\n }))\n } catch (error) {\n console.log(error);\n }\n }",
"function dateTimeFunc(latitude,longitude){\n let timeZone_API_Address = `http://api.timezonedb.com/v2.1/get-time-zone?key=${timeZone_API_Key}&format=json&by=position&lat=${latitude}&lng=${longitude}`\n fetch(timeZone_API_Address)\n .then((response)=>{\n let data2 = response.json();\n \n return data2\n \n \n \n \n \n })\n .then((data2)=>{\n datetime=data2.formatted;\n const usertimezoneElement = document.getElementById(\"user-time-zone\");\n usertimezoneElement.innerHTML = datetime;\n \n \n\n })\n \n\n }",
"renderTimezoneSelect() {\n // Users timezone\n const userTimezone = {\n [this.currentTimezone]:\n 'Your timezone: (GMT' + moment.tz(this.currentTimezone).format('Z') + ') ' + this.currentTimezone,\n };\n\n // List with common timezones\n const commonTimezones = {\n 'Pacific/Honolulu': '(GMT-10:00) Hawaiian/Aleutian Time',\n 'America/Anchorage': '(GMT-08:00) Alaska Time',\n 'America/Los_Angeles': '(GMT-07:00) Pacific Time (US)',\n 'America/Phoenix': '(GMT-07:00) Mountain Time (Arizona)',\n 'America/Denver': '(GMT-06:00) Mountain Time (US)',\n 'America/Chicago': '(GMT-05:00) Central Time (US)',\n 'America/New_York': '(GMT-04:00) Eastern Time (US)',\n 'America/Indiana/Knox': '(GMT-05:00) Central Time (Indiana)',\n 'America/Indiana/Indianapolis': '(GMT-04:00) Eastern Time (Indiana)',\n 'America/Regina': '(GMT-06:00) Central Time (Saskatchewan)',\n 'America/Monterrey': '(GMT-05:00) Central Time (Mexico City, Monterey)',\n 'America/Lima': '(GMT-05:00) UTC/GMT -5 hours',\n 'America/Manaus': '(GMT-04:00) Atlantic Time',\n 'America/Montevideo': '(GMT-03:00) Uruguay',\n 'America/Puerto_Rico': '(GMT-04:00) Atlantic Time (Puerto Rico)',\n 'America/Thule': '(GMT-03:00) Western Greenland Time',\n 'America/Sao_Paulo': '(GMT-03:00) Eastern Brazil',\n 'America/St_Johns': '(GMT-02:30) Newfoundland Time',\n 'America/Godthab': '(GMT-02:00) Central Greenland Time',\n 'Etc/GMT+2': '(GMT-02:00) GMT-2:00',\n 'America/Scoresbysund': '(GMT+00:00) Eastern Greenland Time',\n 'Atlantic/Reykjavik': '(GMT+00:00) Western European Time (Iceland)',\n UTC: '(GMT+00:00) UTC',\n 'Europe/London': '(GMT+01:00) British Time (London)',\n 'Etc/GMT-1': '(GMT+01:00) GMT+1:00',\n 'Europe/Lisbon': '(GMT+01:00) Western European Time (Lisbon)',\n 'Europe/Paris': '(GMT+02:00) Western European Time',\n 'Europe/Berlin': '(GMT+02:00) Central European Time',\n 'Europe/Bucharest': '(GMT+03:00) Eastern European Time',\n 'Africa/Johannesburg': '(GMT+02:00) South Africa Standard Time',\n 'Africa/Kampala': '(GMT+03:00) Eastern Africa Time',\n 'Etc/GMT-3': '(GMT+03:00) Moscow',\n 'Asia/Tehran': '(GMT+04:30) Iran Standard Time',\n 'Asia/Dubai': '(GMT+04:00) UAE (Dubai)',\n 'Asia/Karachi': '(GMT+05:00) Pakistan Standard Time (Karachi)',\n 'Asia/Calcutta': '(GMT+05:30) India',\n 'Asia/Dhaka': '(GMT+06:00) Bangladesh Standard Time',\n 'Asia/Jakarta': '(GMT+07:00) Western Indonesian Time (Jakarta)',\n 'Asia/Bangkok': '(GMT+07:00) Thailand (Bangkok)',\n 'Asia/Hong_Kong': '(GMT+08:00) Hong Kong',\n 'Asia/Singapore': '(GMT+08:00) Singapore',\n 'Australia/West': '(GMT+08:00) Australian Western Time',\n 'Asia/Tokyo': '(GMT+09:00) Tokyo',\n 'Australia/North': '(GMT+09:30) Australian Central Time (Northern Territory)',\n 'Australia/Adelaide': '(GMT+09:30) Australian Central Time (Adelaide)',\n 'Australia/Queensland': '(GMT+10:00) Australian Eastern Time (Queensland)',\n 'Australia/Sydney': '(GMT+10:00) Australian Eastern Time (Sydney)',\n 'Pacific/Noumea': '(GMT+11:00) Noumea, New Caledonia',\n 'Pacific/Norfolk': '(GMT+11:00) Norfolk Island (Australia)',\n 'Pacific/Tarawa': '(GMT+12:00) Tarawa',\n 'Pacific/Auckland': '(GMT+12:00) New Zealand Time',\n 'Pacific/Apia': '(GMT+13:00) Apia, Samoa',\n };\n\n const selectOptions = {\n options: Object.assign(userTimezone, commonTimezones),\n };\n\n // Parse select html\n const $select = document.querySelector('#timezone-select');\n const source = document.querySelector('#timezone-template').innerHTML;\n const template = Handlebars.compile(source);\n $select.innerHTML = template(selectOptions);\n }",
"function getCurrentTime(w_lon,w_lat){\r\n $.ajax({\r\n url:'libs/php/getTimezone.php',\r\n type:'POST',\r\n data:{lat:w_lat,\r\n lon: w_lon },\r\n dataType: 'JSON',\r\n success:(result)=> {\r\n //console.log('----------get data from timeZone api------')\r\n //console.log(result);\r\n let timezone = result.data.timezoneId;\r\n // console.log(timezone)\r\n $('#timezoneId').html(result['data']['timezoneId']);\r\n $('#sunrise').html(result['data']['sunrise']);\r\n $('#sunset').html(result['data']['sunset']);\r\n //$('#time').html(result['data']['time']);\r\n let DTime =result['data']['time'];\r\n let CDTime = new Date(DTime)\r\n let CDT =CDTime.toUTCString();\r\n // console.log(CDT)\r\n $('#time').html(`${CDT}`);\r\n\r\n }\r\n })\r\n\r\n}",
"getLocalTime (data) {\n\t\tlet timezone = data.hotel.timezone;\n\t\treturn moment().tz(timezone);\n\t}",
"async getWeatherByCity(city) {\r\n\r\n const base = 'https://api.openweathermap.org/data/2.5/weather';\r\n const query = `?q=${city}&appid=${this.key}`;\r\n const resultWeather = await fetch(base + query);\r\n const resultByCity = await resultWeather.json(); \r\n \r\n return resultByCity;\r\n }",
"function places_with_walltime(goal_time){\n\tvar countries = new Array;\n\tvar timezones = new Array;\n\t//for all countries where walltime == goal_time, array_push that country name and timezone into their respective arrays\n\tfor (var zid in zonelist) {\n\t\tif (zonelist.hasOwnProperty(zid)) {\n\t\t\tvar walltime = moment().tz(zid).hours();\n\t\t\tif (walltime == goal_time && ztc(zid)!== false){\n\t\t\t\tcountries.push(ztc(zid));\n\t\t\t\ttimezones.push(moment.tz(zid).format(\"Z\"));\n\t\t\t}\t\t\t\n\t\t}\n\t};\n\tvar res = {countries: countries, timezones: timezones};\n\treturn res;\n}",
"function setTimeZone(timeInfo){\r\n\tlet searchTerm = $(\"#searchInput\").val();\r\n\t// Capitalize the city name\r\n\tlet cityName = searchTerm.charAt(0).toUpperCase() + searchTerm.slice(1);\r\n\tlet formattedTime = timeInfo.formatted;\r\n\tlet timeZone = timeInfo.abbreviation;\r\n\tlet countryName = timeInfo.countryCode;\r\n\t$(\"#TimeZoneInfo\").html(`It is currently ${formattedTime.slice(10)} ${timeZone}, ${formattedTime.slice(0, 10)} in ${cityName}, ${countryName}.`);\r\n\r\n\t// Convert formatted time into unix timestamp\r\n\tDate.prototype.getUnixTime = function() { return this.getTime()/1000|0 };\r\n\tlet timeTag;\r\n\tlet timeInSeconds = new Date(`${formattedTime}`).getUnixTime();\r\n\tlet timeInHour;\r\n\r\n\t// Set upcoming hours for the hourly forecast columns\r\n\tfor(let k = 1; k < 7; k++){\r\n\t\ttimeTag = `#timeInHour${k}`;\r\n\t\t// Convert unix timestamps into hour of day\r\n\t\ttimeInHour = hourConverter(timeInSeconds);\r\n\t\t$(timeTag).html(timeInHour);\r\n\t\t// Add an hour\r\n\t\ttimeInSeconds += 3600; \r\n\t}\r\n}",
"function calcTime(Cities, offset) {\r\n let time = document.getElementById(\"Time\");\r\n // get UTC time in msec and add offset of local time in msec\r\n utc = date.getTime() + (date.getTimezoneOffset() * 60000);\r\n // create new Date object for different city\r\n nd = new Date(utc + (3600000 * offset));\r\n time.innerHTML = Cities + \" Time is \" + nd.toLocaleString();\r\n}",
"function next_weather_data(ctdn, hrs) {\r\n var all_city = timezones.allTimeZones()\r\n var hours = timezones.nextNhoursWeather(ctdn, hrs, all_city)\r\n process.send(hours)\r\n process.exit()\r\n}",
"function findExactCity(id,country,data) {\n var countryName=country;\n var humidity;\n var temperature;\n var windSpeed;\n var description;\n \n for(var i=0;i<data.length;i++) {\n if(data[i].fifa_id==id) {\n humidity=data[i].weather.humidity;\n temperature=data[i].weather.temp_celsius;\n windSpeed=data[i].weather.wind_speed;\n description=data[i].weather.description;\n }\n } showCityDetails(humidity,temperature,windSpeed,description,countryName);\n}",
"_retrieveSunTimes(callback) {\n\t\tWeatherRecord.find({}, (err, doc) => {\n\t\t\tif (err) callback(err, null);\n\t\t\telse callback(null, doc.sun_times);\n\t\t});\n\t}",
"function displayCityData(beachLocation, depDate, returnDate, userAirportCode) {\n //Restaurant API\n var clientID = \"-_-qsu9VN_Mu1cRQ_CEfbA\"\n var apikey = \"eGyFYoGa3oYrHwELLpuXsE9A1l9W6d6AoJszCKMPa3M9SNgR2kx1md-nelFS1jJdfOb1sCD3knBmuWA7kDTZSoZMehkn0-Avx1VDY6QMhAX45RpIuKyxSBZ53eTsW3Yx\"\n var queryURL = \"https://developers.zomato.com/api/v2.1/locations?query=\" + beachLocation + \"&apikey=937d785cc1c1b2ac1098e43a13b9cf22\";\n\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n var entityID = response.location_suggestions[0].entity_id;\n var entityType = response.location_suggestions[0].entity_type;\n var locationDetailQueryURL = \"https://developers.zomato.com/api/v2.1/location_details?entity_id=\" + entityID + \"&entity_type=\" + entityType + \"&apikey=937d785cc1c1b2ac1098e43a13b9cf22\"\n\n $.ajax({\n url: locationDetailQueryURL,\n method: \"GET\"\n }).then(function (response) {\n var topRestaurant = response.best_rated_restaurant[0].restaurant.name;\n var topRestaurantURL = response.best_rated_restaurant[0].restaurant.url;\n var topRestaurantAddress = response.best_rated_restaurant[0].restaurant.location.address;\n var avgCostForTwo = response.best_rated_restaurant[0].restaurant.average_cost_for_two\n var restaurantID = response.best_rated_restaurant[0].restaurant.R.res_id;\n\n var restaurntDetailQueryURL = \"https://developers.zomato.com/api/v2.1/restaurant?res_id=\" + restaurantID + \"&apikey=937d785cc1c1b2ac1098e43a13b9cf22\"\n $.ajax({\n url: restaurntDetailQueryURL,\n method: \"GET\"\n }).then(function (response) {\n var restaurantLocation = response.location.address\n var avgCost = response.average_cost_for_two;\n var cuisines = response.cuisines;\n //Flight API\n $.ajax({\n url: \"https://api.sandbox.amadeus.com/v1.2/flights/low-fare-search?apikey=HEbMkphMv3ReciH7JfBcCzGQLfGG2UCk&origin=\" + userAirportCode + \"&destination=\" + selectedDestinationCode + \"&departure_date=\" + depDate + \"&return_date=\" + returnDate + \"&number_of_results=1\",\n method: \"GET\"\n }).then(function (response) {\n var flightPrice = response.results[0].fare.total_price;\n var departsAt = moment(response.results[0].itineraries[0].outbound.flights[0].departs_at).format(\"MM/DD/YYYY hh:mm a \");\n var arrivesAt = moment(response.results[0].itineraries[0].outbound.flights[(response.results[0].itineraries[0].outbound.flights.length - 1)].arrives_at).format(\"MM/DD/YYYY hh:mm a\");\n var duration = response.results[0].itineraries[0].outbound.duration;\n var airlineCode = response.results[0].itineraries[0].outbound.flights[0].operating_airline;\n var retDepartsAt = moment(response.results[0].itineraries[0].inbound.flights[0].departs_at).format(\"MM/DD/YYYY hh:mm a \");\n var retArrivesAt = moment(response.results[0].itineraries[0].inbound.flights[(response.results[0].itineraries[0].inbound.flights.length - 1)].arrives_at).format(\"MM/DD/YYYY hh:mm a\");\n var retDuration = response.results[0].itineraries[0].inbound.duration;\n var retAirlineCode = response.results[0].itineraries[0].inbound.flights[0].operating_airline;\n console.log(retDepartsAt, retAirlineCode, retArrivesAt, retDuration)\n $('.Cuisines').append(cuisines);\n $('.ResName').html(`<a href=\"${topRestaurantURL}\" target=\"blank\">${topRestaurant}</a>`)\n $('.ResforTwo').append(\"$\" + avgCostForTwo);\n $('.ResAddress').append(topRestaurantAddress);\n $(\".ArrivalAirport\").append(`<a href=\"https://en.wikipedia.org/wiki/List_of_airports_by_IATA_code:_A\" target=\"blank\">${selectedDestinationCode}</a>`)\n $(\".Airline\").append(`<a href=\"https://www.airfarewatchdog.com/airline-codes/\" target=\"blank\">${airlineCode}</a>`)\n $(\".FlightPrice\").append(\"$\" + flightPrice);\n $(\".LeaveDate\").append(departsAt);\n $(\".FlightArrival\").append(arrivesAt);\n $(\".Duration\").append(duration);\n $(\".retFlightPrice\").append(\"Above\");\n $(\".retArrivalAirport\").append(`<a href=\"https://en.wikipedia.org/wiki/List_of_airports_by_IATA_code:_A\" target=\"blank\">${userAirportCode}</a>`)\n $(\".retAirline\").append(`<a href=\"https://www.airfarewatchdog.com/airline-codes/\" target=\"blank\">${retAirlineCode}</a>`)\n $(\".retLeaveDate\").append(retDepartsAt);\n $(\".retFlightArrival\").append(retArrivesAt);\n $(\".retDuration\").append(retDuration);\n\n populateHotelData();\n }).catch(function (error) {\n $('td').empty();\n alert(error.responseJSON.message);\n $('td').empty();\n })\n })\n })\n\n //Hotel API --- NOT WORKING(AMADEUS SUPPORT WORKING ON ISSUE) REPLACEMENT BAND AID ABOVE\n // var hotelQueryURL = \"https://api.sandbox.amadeus.com/v1.2/hotels/search-airport/?apikey=KWxHu3JXbSfuZ0ZfU5AmxbNfkmVaKQTX&location=\" + selectedDestinationCode + \"&check_in=\" + depDate + \"&check_out=\" + returnDate;\n // var hotelQueryURL = \"https://api.sandbox.amadeus.com/v1.2/hotels/search-airport/?apikey=KWxHu3JXbSfuZ0ZfU5AmxbNfkmVaKQTX&location=\" + selectedDestinationCode + \"&check_in=2019-01-02&check_out=2019-01-09\"\n // $.ajax({\n // url: hotelQueryURL,\n // method: \"GET\"\n // }).then(function (response) {\n // console.log(JSON.stringify(response));\n // var hotelName = response.results[0].property_name;\n // var hotelPrice = response.results[0].total_price.amount;\n // var hotelStreet = response.results[0].address.line1;\n // var hotelCity = response.results[0].address.city;\n // var hotelState = response.results[0].address.region;\n // var hotelPostal = response.results[0].address.postal_code;\n // var fullAddress = hotelStreet + \"\" + hotelCity + \"\" + hotelState + \"\" + hotelPostal;\n // var roomType = response.results[0].rooms[0].room_type_info.room_type;\n\n // $(\".HoName\").append(hotelName);\n // $(\".HoPrice\").append(\"$\" + hotelPrice);\n // $(\".HoAddress\").append(fullAddress);\n // $(\".HoRoomType\").append(roomType);\n // })\n\n\n })\n}",
"getWeather(cityName) {\n console.log(`cityName is ${cityName}`);\n if (cityName === null) {\n return {};\n }\n\n // For now let's assume, we are only returning today's temperature\n let date = 'today';\n\n return this.WEATHER_DATA[date][cityName] || this.WEATHER_DATA[date]['seattle'];\n }",
"getcityDetails() {\n\t\tlet xmlHttp = new XMLHttpRequest();\n\t\tlet c = null;\n\t\tlet val = document.getElementById(\"city\").value;\n\t\txmlHttp.open(\"GET\", \"https://developers.zomato.com/api/v2.1/cities?q=\" + val, true);\n\t\txmlHttp.setRequestHeader(\"user-key\", this.state.key);\n\t\txmlHttp.setRequestHeader(\"Accept\", \"application/json\");\n\t\txmlHttp.onload = function () {\n\t\t\tif (xmlHttp.readyState === 4) {\n\t\t\t\tif (xmlHttp.status === 200) {\n\t\t\t\t\tlet location = JSON.parse(xmlHttp.response).location_suggestions;\n\t\t\t\t\tc = location.map(function (element) {\n\t\t\t\t\t\tvar newObj = { id: element.id, city: element.name };\n\t\t\t\t\t\treturn newObj;\n\t\t\t\t\t});\n\t\t\t\t\t// console.log(c);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(\"not ok\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\txmlHttp.onloadend = () => {\n\t\t\tlet newState = this.state.showResult\n\t\t\tthis.setState({\n\t\t\t\tcurrentCity: c,\n\t\t\t\tshowResult: !newState\n\t\t\t}\n\t\t\t)\n\t\t\t// console.log(typeof select);\n\t\t\t// console.log(this.state.currentCity[0].id);\n\n\t\t\tthis.getCollections(this.state.currentCity[0].id);\n\n\t\t}\n\t\txmlHttp.send();\n\t}",
"function getCityDataset () {\n\t\t\tvar overtime = 'eightOT',\n\t\t\t\tselect = document.getElementById(\"city\");\n\t\t\treturn select.options[select.selectedIndex].value;\t\t\n\t\t}",
"async getCity(city){\n const query = `?apikey=${this.key}&q=${city}`;\n const response = await fetch(this.cityURI + query); //awaits the promise until it resolves and assigns it to var\n const data = await response.json(); //awaits the promise to resolve and returns the data\n return data[0];\n }",
"function getCurrentHourData() {\n\t return result.filter(function (item) { \n\t\t\t\tvar date = new Date((item.timestampMs/1000)*1000);\n\t\t\t\tvar hours = date.getHours();\n\t\t\t\treturn hours === d.getHours();\n\t\t\t})\n\t\t\t.map( function(item){ \n\t\t\t\treturn [item.latitudeE7 * SCALAR_E7, item.longitudeE7 * SCALAR_E7]; \n\t\t\t})\n\t }",
"async function pullData(city) {\n\n var requestUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=imperial`;\n \n var outCome = await fetch(requestUrl)\n .then(response => response.json())\n .then(data => {\n return data;\n })\n\n var latLong = {\n latitude: outCome.coord.lat,\n longitude: outCome.coord.lon\n }\n\n var oneCallURL = `https://api.openweathermap.org/data/2.5/onecall?lat=${latLong.latitude}&lon=${latLong.longitude}&appid=${API_KEY}&units=imperial`;\n\n var oneCall = await fetch(oneCallURL)\n .then(response => response.json())\n .then(data => {\n return data;\n })\n\n // displays the current date on current day card\n var date = new Date(oneCall.current.dt * 1000);\n\n var dateString = `(${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()})`;\n \n $(`.cd-date`).text(`${outCome.name} ${dateString}`);\n \n return oneCall;\n}",
"function getCordinats(city) {\n var cityname = city.toLowerCase();\n\n var coordUrl =\n \"https://api.openweathermap.org/data/2.5/weather?q=\" +\n cityname +\n \"&appid=\" +\n apikey;\n\n $.ajax({\n url: coordUrl,\n method: \"GET\",\n }).then(function (data) {\n longitude = data.coord.lon;\n latitude = data.coord.lat;\n getCurrentWether(longitude, latitude);\n });\n }",
"fetchWeatherData(city) {\n const baseUrl = `http://api.openweathermap.org`;\n const path = `/data/2.5/weather`;\n const appId = `1fbaf6e0d29ea877ae5852504eef4e82`;\n const query = `units=imperial&appId=${appId}`;\n fetch(`${baseUrl}${path}?q=${city}&${query}`)\n .then( (response) => {\n return response.json();\n })\n .then( (data) => {\n let date = new Date();\n let time = date.getHours(); // current hour of the day\n this.setState({\n time: time,\n temp: Math.round(data.main.temp), // current weather at current location\n location: city,\n weather_code: data.weather[0].id // code for current weather conditions\n });\n })\n .catch( (error) => {\n console.log(error);\n });\n }",
"function getWeatherData(url) {\n fetch(url)\n .then(function(response) {\n if (response.ok) {\n return response.json();\n }\n throw new ERROR(\"Net work response was ok.\");\n })\n .then(function (data){\n console.log(data);\n let cityName = data.Preston.properties.relativeLocation.properties.city;\n console.log(cityName);\n \n sessStore.setItem('cityName', cityName);\n document.querySelector(\"#unique\").innerHTML = sessStore.getItem('cityName');\n let hourURL = data.Preston.properties.forecastHourly;\n getHourly(hourURL);\n })\n .catch(function (error){\n console.log('There was a problem: ', error.message);\n statusContainer.innerHTML = 'Sorry, the data could not be processed.';\n })\n \n}",
"async function get() {\n const response = await fetch('https://worldtimeapi.org/api/timezone/' + valeur);\n let data = await response.json();\n let { datetime } = data;\n console.log(datetime);\n let horaire = datetime.substring(11, 19);\n //1 - Ecrire l'heure récupéré via l'API dans la zonne HH:MM:SS\n document.getElementById('horaire').innerText = horaire;\n\n temp(horaire);\n }",
"function addAllTimeZones() {\n const countriesCodeAndName = [\n [\"AD\", \"Andorra\"],\n [\"AE\", \"United Arab Emirates\"],\n [\"AF\", \"Afghanistan\"],\n [\"AG\", \"Antigua & Barbuda\"],\n [\"AI\", \"Anguilla\"],\n [\"AL\", \"Albania\"],\n [\"AM\", \"Armenia\"],\n [\"AO\", \"Angola\"],\n [\"AQ\", \"Antarctica\"],\n [\"AR\", \"Argentina\"],\n [\"AS\", \"Samoa (American)\"],\n [\"AT\", \"Austria\"],\n [\"AU\", \"Australia\"],\n [\"AW\", \"Aruba\"],\n [\"AX\", \"Aaland Islands\"],\n [\"AZ\", \"Azerbaijan\"],\n [\"BA\", \"Bosnia & Herzegovina\"],\n [\"BB\", \"Barbados\"],\n [\"BD\", \"Bangladesh\"],\n [\"BE\", \"Belgium\"],\n [\"BF\", \"Burkina Faso\"],\n [\"BG\", \"Bulgaria\"],\n [\"BH\", \"Bahrain\"],\n [\"BI\", \"Burundi\"],\n [\"BJ\", \"Benin\"],\n [\"BL\", \"St Barthelemy\"],\n [\"BM\", \"Bermuda\"],\n [\"BN\", \"Brunei\"],\n [\"BO\", \"Bolivia\"],\n [\"BQ\", \"Caribbean Netherlands\"],\n [\"BR\", \"Brazil\"],\n [\"BS\", \"Bahamas\"],\n [\"BT\", \"Bhutan\"],\n [\"BW\", \"Botswana\"],\n [\"BY\", \"Belarus\"],\n [\"BZ\", \"Belize\"],\n [\"CA\", \"Canada\"],\n [\"CC\", \"Cocos (Keeling) Islands\"],\n [\"CD\", \"Congo (Dem. Rep.)\"],\n [\"CF\", \"Central African Rep.\"],\n [\"CG\", \"Congo (Rep.)\"],\n [\"CH\", \"Switzerland\"],\n [\"CI\", \"Cote d'Ivoire\"],\n [\"CK\", \"Cook Islands\"],\n [\"CL\", \"Chile\"],\n [\"CM\", \"Cameroon\"],\n [\"CN\", \"China\"],\n [\"CO\", \"Colombia\"],\n [\"CR\", \"Costa Rica\"],\n [\"CU\", \"Cuba\"],\n [\"CV\", \"Cape Verde\"],\n [\"CW\", \"Curacao\"],\n [\"CX\", \"Christmas Island\"],\n [\"CY\", \"Cyprus\"],\n [\"CZ\", \"Czech Republic\"],\n [\"DE\", \"Germany\"],\n [\"DJ\", \"Djibouti\"],\n [\"DK\", \"Denmark\"],\n [\"DM\", \"Dominica\"],\n [\"DO\", \"Dominican Republic\"],\n [\"DZ\", \"Algeria\"],\n [\"EC\", \"Ecuador\"],\n [\"EE\", \"Estonia\"],\n [\"EG\", \"Egypt\"],\n [\"EH\", \"Western Sahara\"],\n [\"ER\", \"Eritrea\"],\n [\"ES\", \"Spain\"],\n [\"ET\", \"Ethiopia\"],\n [\"FI\", \"Finland\"],\n [\"FJ\", \"Fiji\"],\n [\"FK\", \"Falkland Islands\"],\n [\"FM\", \"Micronesia\"],\n [\"FO\", \"Faroe Islands\"],\n [\"FR\", \"France\"],\n [\"GA\", \"Gabon\"],\n [\"GB\", \"Britain (UK)\"],\n [\"GD\", \"Grenada\"],\n [\"GE\", \"Georgia\"],\n [\"GF\", \"French Guiana\"],\n [\"GG\", \"Guernsey\"],\n [\"GH\", \"Ghana\"],\n [\"GI\", \"Gibraltar\"],\n [\"GL\", \"Greenland\"],\n [\"GM\", \"Gambia\"],\n [\"GN\", \"Guinea\"],\n [\"GP\", \"Guadeloupe\"],\n [\"GQ\", \"Equatorial Guinea\"],\n [\"GR\", \"Greece\"],\n [\"GS\", \"South Georgia & the South Sandwich Islands\"],\n [\"GT\", \"Guatemala\"],\n [\"GU\", \"Guam\"],\n [\"GW\", \"Guinea-Bissau\"],\n [\"GY\", \"Guyana\"],\n [\"HK\", \"Hong Kong\"],\n [\"HN\", \"Honduras\"],\n [\"HR\", \"Croatia\"],\n [\"HT\", \"Haiti\"],\n [\"HU\", \"Hungary\"],\n [\"ID\", \"Indonesia\"],\n [\"IE\", \"Ireland\"],\n [\"IL\", \"Israel\"],\n [\"IM\", \"Isle of Man\"],\n [\"IN\", \"India\"],\n [\"IO\", \"British Indian Ocean Territory\"],\n [\"IQ\", \"Iraq\"],\n [\"IR\", \"Iran\"],\n [\"IS\", \"Iceland\"],\n [\"IT\", \"Italy\"],\n [\"JE\", \"Jersey\"],\n [\"JM\", \"Jamaica\"],\n [\"JO\", \"Jordan\"],\n [\"JP\", \"Japan\"],\n [\"KE\", \"Kenya\"],\n [\"KG\", \"Kyrgyzstan\"],\n [\"KH\", \"Cambodia\"],\n [\"KI\", \"Kiribati\"],\n [\"KM\", \"Comoros\"],\n [\"KN\", \"St Kitts & Nevis\"],\n [\"KP\", \"Korea (North)\"],\n [\"KR\", \"Korea (South)\"],\n [\"KW\", \"Kuwait\"],\n [\"KY\", \"Cayman Islands\"],\n [\"KZ\", \"Kazakhstan\"],\n [\"LA\", \"Laos\"],\n [\"LB\", \"Lebanon\"],\n [\"LC\", \"St Lucia\"],\n [\"LI\", \"Liechtenstein\"],\n [\"LK\", \"Sri Lanka\"],\n [\"LR\", \"Liberia\"],\n [\"LS\", \"Lesotho\"],\n [\"LT\", \"Lithuania\"],\n [\"LU\", \"Luxembourg\"],\n [\"LV\", \"Latvia\"],\n [\"LY\", \"Libya\"],\n [\"MA\", \"Morocco\"],\n [\"MC\", \"Monaco\"],\n [\"MD\", \"Moldova\"],\n [\"ME\", \"Montenegro\"],\n [\"MF\", \"St Martin (French part)\"],\n [\"MG\", \"Madagascar\"],\n [\"MH\", \"Marshall Islands\"],\n [\"MK\", \"Macedonia\"],\n [\"ML\", \"Mali\"],\n [\"MM\", \"Myanmar (Burma)\"],\n [\"MN\", \"Mongolia\"],\n [\"MO\", \"Macau\"],\n [\"MP\", \"Northern Mariana Islands\"],\n [\"MQ\", \"Martinique\"],\n [\"MR\", \"Mauritania\"],\n [\"MS\", \"Montserrat\"],\n [\"MT\", \"Malta\"],\n [\"MU\", \"Mauritius\"],\n [\"MV\", \"Maldives\"],\n [\"MW\", \"Malawi\"],\n [\"MX\", \"Mexico\"],\n [\"MY\", \"Malaysia\"],\n [\"MZ\", \"Mozambique\"],\n [\"NA\", \"Namibia\"],\n [\"NC\", \"New Caledonia\"],\n [\"NE\", \"Niger\"],\n [\"NF\", \"Norfolk Island\"],\n [\"NG\", \"Nigeria\"],\n [\"NI\", \"Nicaragua\"],\n [\"NL\", \"Netherlands\"],\n [\"NO\", \"Norway\"],\n [\"NP\", \"Nepal\"],\n [\"NR\", \"Nauru\"],\n [\"NU\", \"Niue\"],\n [\"NZ\", \"New Zealand\"],\n [\"OM\", \"Oman\"],\n [\"PA\", \"Panama\"],\n [\"PE\", \"Peru\"],\n [\"PF\", \"French Polynesia\"],\n [\"PG\", \"Papua New Guinea\"],\n [\"PH\", \"Philippines\"],\n [\"PK\", \"Pakistan\"],\n [\"PL\", \"Poland\"],\n [\"PM\", \"St Pierre & Miquelon\"],\n [\"PN\", \"Pitcairn\"],\n [\"PR\", \"Puerto Rico\"],\n [\"PS\", \"Palestine\"],\n [\"PT\", \"Portugal\"],\n [\"PW\", \"Palau\"],\n [\"PY\", \"Paraguay\"],\n [\"QA\", \"Qatar\"],\n [\"RE\", \"Reunion\"],\n [\"RO\", \"Romania\"],\n [\"RS\", \"Serbia\"],\n [\"RU\", \"Russia\"],\n [\"RW\", \"Rwanda\"],\n [\"SA\", \"Saudi Arabia\"],\n [\"SB\", \"Solomon Islands\"],\n [\"SC\", \"Seychelles\"],\n [\"SD\", \"Sudan\"],\n [\"SE\", \"Sweden\"],\n [\"SG\", \"Singapore\"],\n [\"SH\", \"St Helena\"],\n [\"SI\", \"Slovenia\"],\n [\"SJ\", \"Svalbard & Jan Mayen\"],\n [\"SK\", \"Slovakia\"],\n [\"SL\", \"Sierra Leone\"],\n [\"SM\", \"San Marino\"],\n [\"SN\", \"Senegal\"],\n [\"SO\", \"Somalia\"],\n [\"SR\", \"Suriname\"],\n [\"SS\", \"South Sudan\"],\n [\"ST\", \"Sao Tome & Principe\"],\n [\"SV\", \"El Salvador\"],\n [\"SX\", \"St Maarten (Dutch part)\"],\n [\"SY\", \"Syria\"],\n [\"SZ\", \"Swaziland\"],\n [\"TC\", \"Turks & Caicos Is\"],\n [\"TD\", \"Chad\"],\n [\"TF\", \"French Southern & Antarctic Lands\"],\n [\"TG\", \"Togo\"],\n [\"TH\", \"Thailand\"],\n [\"TJ\", \"Tajikistan\"],\n [\"TK\", \"Tokelau\"],\n [\"TL\", \"East Timor\"],\n [\"TM\", \"Turkmenistan\"],\n [\"TN\", \"Tunisia\"],\n [\"TO\", \"Tonga\"],\n [\"TR\", \"Turkey\"],\n [\"TT\", \"Trinidad & Tobago\"],\n [\"TV\", \"Tuvalu\"],\n [\"TW\", \"Taiwan\"],\n [\"TZ\", \"Tanzania\"],\n [\"UA\", \"Ukraine\"],\n [\"UG\", \"Uganda\"],\n [\"UM\", \"US minor outlying islands\"],\n [\"US\", \"United States\"],\n [\"UY\", \"Uruguay\"],\n [\"UZ\", \"Uzbekistan\"],\n [\"VA\", \"Vatican City\"],\n [\"VC\", \"St Vincent\"],\n [\"VE\", \"Venezuela\"],\n [\"VG\", \"Virgin Islands (UK)\"],\n [\"VI\", \"Virgin Islands (US)\"],\n [\"VN\", \"Vietnam\"],\n [\"VU\", \"Vanuatu\"],\n [\"WF\", \"Wallis & Futuna\"],\n [\"WS\", \"Samoa (western)\"],\n [\"YE\", \"Yemen\"],\n [\"YT\", \"Mayotte\"],\n [\"ZA\", \"South Africa\"],\n [\"ZM\", \"Zambia\"],\n [\"ZW\", \"Zimbabwe\"],\n ];\n let zoneData = [];\n for (let index = 0; index < countriesCodeAndName.length; index++) {\n moment.tz\n .zonesForCountry(countriesCodeAndName[index][0])\n .forEach((zone) => {\n zoneData.push({\n countryCode: countriesCodeAndName[index][0],\n countryName: countriesCodeAndName[index][1],\n zoneName: zone\n .split(\"/\")\n [zone.split(\"/\").length - 1].replace(\"_\", \" \"),\n zoneTimeDate: moment().tz(zone),\n completZoneName: zone,\n });\n });\n }\n return zoneData;\n}",
"function fetchCityData(callback) {\n // FILL THIS IN\n\t$.ajax({\n method: 'GET',\n url: baseUrl + '/city-data',\n // When a request completes, call `showRoute()` to display the\n // route on the web page.\n success: callback,\n error: function ajaxError(jqXHR, textStatus, errorThrown) {\n console.error(\n 'Error fetching city data: ', \n textStatus, \n ', Details: ', \n errorThrown);\n console.error('Response: ', jqXHR.responseText);\n alert('An error occurred when requesting a route by its ID:\\n' + jqXHR.responseText);\n }\n })\n }"
]
| [
"0.70274866",
"0.69701564",
"0.6771241",
"0.6597231",
"0.61396354",
"0.5962474",
"0.590981",
"0.5865134",
"0.5855035",
"0.5828331",
"0.5785521",
"0.57737494",
"0.57648915",
"0.5760151",
"0.5753902",
"0.5735601",
"0.570362",
"0.56397593",
"0.56142706",
"0.55930305",
"0.5577887",
"0.55619586",
"0.5559428",
"0.5552568",
"0.55517447",
"0.5547778",
"0.5518983",
"0.55136025",
"0.5513431",
"0.5492717"
]
| 0.70345205 | 0 |
.......................fetching data from timezones.allTimeZones and nextNhoursWeather............................ | function next_weather_data(ctdn, hrs) {
var all_city = timezones.allTimeZones()
var hours = timezones.nextNhoursWeather(ctdn, hrs, all_city)
process.send(hours)
process.exit()
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function getTimezone () {\n let opts = { \n 'pageSize': 1000,\n 'pageNumber': 1\n };\n\n telephonyProvidersEdgeApi.getTelephonyProvidersEdgesTimezones(opts)\n .then((data) => {\n let timezone = data.entities;\n timezone.forEach(addTimezoneToSelect);\n })\n .catch((err) => {\n console.log('There was a failure calling getTimezones');\n console.error(err);\n $(\"#siteFailedModal\").modal();\n document.getElementById(\"siteError\").innerHTML = err.body.message;\n });\n}",
"function lookupTimezones(cityN) {\n /*\n var myUrl;\n switch (cityN) {\n\n //If its london----------------------------------------------------------------\n case 'London':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=Europe/London';\n break;\n\n //If its New York------------------------------------------------------------\n case 'NewYork':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=America/NewYork';\n break;\n\n //If its Santo Domingo------------------------------------------------------------\n case 'SantoDomingo':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=America/SantoDomingo';\n break;\n //If its Turkey------------------------------------------------------------\n case 'Turkey':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=Asia/Turkey';\n break;\n\n //If its Paris------------------------------------------------------------\n case 'Paris':\n myUrl= 'http://api.timezonedb.com/v2/get-time-zone?key=BGC297R9GDMR&format=json&by=zone&zone=Europe/Paris';\n\n break;\n default:break;\n }\nconsole.log(myUrl);\n $.ajax({\n datatype: 'JSON',\n url: myUrl,\n success: function(Response){\n console.log(Response);\n var myDate = new Date(Response.timestamp*1100);\n console.log(myDate);\n var myhour= myDate.getHours();\n console.log(myhour);\n },\n complete: function(){}\n\n\n\n });\n */\n }",
"function all_city_data() {\r\n var all_city = timezones.allTimeZones()\r\n process.send(all_city)\r\n process.exit()\r\n}",
"function getTZData(){\n let timeStampUTC = Date.now()/1000\n let googTZapiURL = \"https://maps.googleapis.com/maps/api/timezone/json?location=\" + countryLat + \",\" + countryLong + \"×tamp=\" + timeStampUTC + \"&key=\" + googKey\n return $.get(googTZapiURL)\n}",
"function addAllTimeZones() {\n const countriesCodeAndName = [\n [\"AD\", \"Andorra\"],\n [\"AE\", \"United Arab Emirates\"],\n [\"AF\", \"Afghanistan\"],\n [\"AG\", \"Antigua & Barbuda\"],\n [\"AI\", \"Anguilla\"],\n [\"AL\", \"Albania\"],\n [\"AM\", \"Armenia\"],\n [\"AO\", \"Angola\"],\n [\"AQ\", \"Antarctica\"],\n [\"AR\", \"Argentina\"],\n [\"AS\", \"Samoa (American)\"],\n [\"AT\", \"Austria\"],\n [\"AU\", \"Australia\"],\n [\"AW\", \"Aruba\"],\n [\"AX\", \"Aaland Islands\"],\n [\"AZ\", \"Azerbaijan\"],\n [\"BA\", \"Bosnia & Herzegovina\"],\n [\"BB\", \"Barbados\"],\n [\"BD\", \"Bangladesh\"],\n [\"BE\", \"Belgium\"],\n [\"BF\", \"Burkina Faso\"],\n [\"BG\", \"Bulgaria\"],\n [\"BH\", \"Bahrain\"],\n [\"BI\", \"Burundi\"],\n [\"BJ\", \"Benin\"],\n [\"BL\", \"St Barthelemy\"],\n [\"BM\", \"Bermuda\"],\n [\"BN\", \"Brunei\"],\n [\"BO\", \"Bolivia\"],\n [\"BQ\", \"Caribbean Netherlands\"],\n [\"BR\", \"Brazil\"],\n [\"BS\", \"Bahamas\"],\n [\"BT\", \"Bhutan\"],\n [\"BW\", \"Botswana\"],\n [\"BY\", \"Belarus\"],\n [\"BZ\", \"Belize\"],\n [\"CA\", \"Canada\"],\n [\"CC\", \"Cocos (Keeling) Islands\"],\n [\"CD\", \"Congo (Dem. Rep.)\"],\n [\"CF\", \"Central African Rep.\"],\n [\"CG\", \"Congo (Rep.)\"],\n [\"CH\", \"Switzerland\"],\n [\"CI\", \"Cote d'Ivoire\"],\n [\"CK\", \"Cook Islands\"],\n [\"CL\", \"Chile\"],\n [\"CM\", \"Cameroon\"],\n [\"CN\", \"China\"],\n [\"CO\", \"Colombia\"],\n [\"CR\", \"Costa Rica\"],\n [\"CU\", \"Cuba\"],\n [\"CV\", \"Cape Verde\"],\n [\"CW\", \"Curacao\"],\n [\"CX\", \"Christmas Island\"],\n [\"CY\", \"Cyprus\"],\n [\"CZ\", \"Czech Republic\"],\n [\"DE\", \"Germany\"],\n [\"DJ\", \"Djibouti\"],\n [\"DK\", \"Denmark\"],\n [\"DM\", \"Dominica\"],\n [\"DO\", \"Dominican Republic\"],\n [\"DZ\", \"Algeria\"],\n [\"EC\", \"Ecuador\"],\n [\"EE\", \"Estonia\"],\n [\"EG\", \"Egypt\"],\n [\"EH\", \"Western Sahara\"],\n [\"ER\", \"Eritrea\"],\n [\"ES\", \"Spain\"],\n [\"ET\", \"Ethiopia\"],\n [\"FI\", \"Finland\"],\n [\"FJ\", \"Fiji\"],\n [\"FK\", \"Falkland Islands\"],\n [\"FM\", \"Micronesia\"],\n [\"FO\", \"Faroe Islands\"],\n [\"FR\", \"France\"],\n [\"GA\", \"Gabon\"],\n [\"GB\", \"Britain (UK)\"],\n [\"GD\", \"Grenada\"],\n [\"GE\", \"Georgia\"],\n [\"GF\", \"French Guiana\"],\n [\"GG\", \"Guernsey\"],\n [\"GH\", \"Ghana\"],\n [\"GI\", \"Gibraltar\"],\n [\"GL\", \"Greenland\"],\n [\"GM\", \"Gambia\"],\n [\"GN\", \"Guinea\"],\n [\"GP\", \"Guadeloupe\"],\n [\"GQ\", \"Equatorial Guinea\"],\n [\"GR\", \"Greece\"],\n [\"GS\", \"South Georgia & the South Sandwich Islands\"],\n [\"GT\", \"Guatemala\"],\n [\"GU\", \"Guam\"],\n [\"GW\", \"Guinea-Bissau\"],\n [\"GY\", \"Guyana\"],\n [\"HK\", \"Hong Kong\"],\n [\"HN\", \"Honduras\"],\n [\"HR\", \"Croatia\"],\n [\"HT\", \"Haiti\"],\n [\"HU\", \"Hungary\"],\n [\"ID\", \"Indonesia\"],\n [\"IE\", \"Ireland\"],\n [\"IL\", \"Israel\"],\n [\"IM\", \"Isle of Man\"],\n [\"IN\", \"India\"],\n [\"IO\", \"British Indian Ocean Territory\"],\n [\"IQ\", \"Iraq\"],\n [\"IR\", \"Iran\"],\n [\"IS\", \"Iceland\"],\n [\"IT\", \"Italy\"],\n [\"JE\", \"Jersey\"],\n [\"JM\", \"Jamaica\"],\n [\"JO\", \"Jordan\"],\n [\"JP\", \"Japan\"],\n [\"KE\", \"Kenya\"],\n [\"KG\", \"Kyrgyzstan\"],\n [\"KH\", \"Cambodia\"],\n [\"KI\", \"Kiribati\"],\n [\"KM\", \"Comoros\"],\n [\"KN\", \"St Kitts & Nevis\"],\n [\"KP\", \"Korea (North)\"],\n [\"KR\", \"Korea (South)\"],\n [\"KW\", \"Kuwait\"],\n [\"KY\", \"Cayman Islands\"],\n [\"KZ\", \"Kazakhstan\"],\n [\"LA\", \"Laos\"],\n [\"LB\", \"Lebanon\"],\n [\"LC\", \"St Lucia\"],\n [\"LI\", \"Liechtenstein\"],\n [\"LK\", \"Sri Lanka\"],\n [\"LR\", \"Liberia\"],\n [\"LS\", \"Lesotho\"],\n [\"LT\", \"Lithuania\"],\n [\"LU\", \"Luxembourg\"],\n [\"LV\", \"Latvia\"],\n [\"LY\", \"Libya\"],\n [\"MA\", \"Morocco\"],\n [\"MC\", \"Monaco\"],\n [\"MD\", \"Moldova\"],\n [\"ME\", \"Montenegro\"],\n [\"MF\", \"St Martin (French part)\"],\n [\"MG\", \"Madagascar\"],\n [\"MH\", \"Marshall Islands\"],\n [\"MK\", \"Macedonia\"],\n [\"ML\", \"Mali\"],\n [\"MM\", \"Myanmar (Burma)\"],\n [\"MN\", \"Mongolia\"],\n [\"MO\", \"Macau\"],\n [\"MP\", \"Northern Mariana Islands\"],\n [\"MQ\", \"Martinique\"],\n [\"MR\", \"Mauritania\"],\n [\"MS\", \"Montserrat\"],\n [\"MT\", \"Malta\"],\n [\"MU\", \"Mauritius\"],\n [\"MV\", \"Maldives\"],\n [\"MW\", \"Malawi\"],\n [\"MX\", \"Mexico\"],\n [\"MY\", \"Malaysia\"],\n [\"MZ\", \"Mozambique\"],\n [\"NA\", \"Namibia\"],\n [\"NC\", \"New Caledonia\"],\n [\"NE\", \"Niger\"],\n [\"NF\", \"Norfolk Island\"],\n [\"NG\", \"Nigeria\"],\n [\"NI\", \"Nicaragua\"],\n [\"NL\", \"Netherlands\"],\n [\"NO\", \"Norway\"],\n [\"NP\", \"Nepal\"],\n [\"NR\", \"Nauru\"],\n [\"NU\", \"Niue\"],\n [\"NZ\", \"New Zealand\"],\n [\"OM\", \"Oman\"],\n [\"PA\", \"Panama\"],\n [\"PE\", \"Peru\"],\n [\"PF\", \"French Polynesia\"],\n [\"PG\", \"Papua New Guinea\"],\n [\"PH\", \"Philippines\"],\n [\"PK\", \"Pakistan\"],\n [\"PL\", \"Poland\"],\n [\"PM\", \"St Pierre & Miquelon\"],\n [\"PN\", \"Pitcairn\"],\n [\"PR\", \"Puerto Rico\"],\n [\"PS\", \"Palestine\"],\n [\"PT\", \"Portugal\"],\n [\"PW\", \"Palau\"],\n [\"PY\", \"Paraguay\"],\n [\"QA\", \"Qatar\"],\n [\"RE\", \"Reunion\"],\n [\"RO\", \"Romania\"],\n [\"RS\", \"Serbia\"],\n [\"RU\", \"Russia\"],\n [\"RW\", \"Rwanda\"],\n [\"SA\", \"Saudi Arabia\"],\n [\"SB\", \"Solomon Islands\"],\n [\"SC\", \"Seychelles\"],\n [\"SD\", \"Sudan\"],\n [\"SE\", \"Sweden\"],\n [\"SG\", \"Singapore\"],\n [\"SH\", \"St Helena\"],\n [\"SI\", \"Slovenia\"],\n [\"SJ\", \"Svalbard & Jan Mayen\"],\n [\"SK\", \"Slovakia\"],\n [\"SL\", \"Sierra Leone\"],\n [\"SM\", \"San Marino\"],\n [\"SN\", \"Senegal\"],\n [\"SO\", \"Somalia\"],\n [\"SR\", \"Suriname\"],\n [\"SS\", \"South Sudan\"],\n [\"ST\", \"Sao Tome & Principe\"],\n [\"SV\", \"El Salvador\"],\n [\"SX\", \"St Maarten (Dutch part)\"],\n [\"SY\", \"Syria\"],\n [\"SZ\", \"Swaziland\"],\n [\"TC\", \"Turks & Caicos Is\"],\n [\"TD\", \"Chad\"],\n [\"TF\", \"French Southern & Antarctic Lands\"],\n [\"TG\", \"Togo\"],\n [\"TH\", \"Thailand\"],\n [\"TJ\", \"Tajikistan\"],\n [\"TK\", \"Tokelau\"],\n [\"TL\", \"East Timor\"],\n [\"TM\", \"Turkmenistan\"],\n [\"TN\", \"Tunisia\"],\n [\"TO\", \"Tonga\"],\n [\"TR\", \"Turkey\"],\n [\"TT\", \"Trinidad & Tobago\"],\n [\"TV\", \"Tuvalu\"],\n [\"TW\", \"Taiwan\"],\n [\"TZ\", \"Tanzania\"],\n [\"UA\", \"Ukraine\"],\n [\"UG\", \"Uganda\"],\n [\"UM\", \"US minor outlying islands\"],\n [\"US\", \"United States\"],\n [\"UY\", \"Uruguay\"],\n [\"UZ\", \"Uzbekistan\"],\n [\"VA\", \"Vatican City\"],\n [\"VC\", \"St Vincent\"],\n [\"VE\", \"Venezuela\"],\n [\"VG\", \"Virgin Islands (UK)\"],\n [\"VI\", \"Virgin Islands (US)\"],\n [\"VN\", \"Vietnam\"],\n [\"VU\", \"Vanuatu\"],\n [\"WF\", \"Wallis & Futuna\"],\n [\"WS\", \"Samoa (western)\"],\n [\"YE\", \"Yemen\"],\n [\"YT\", \"Mayotte\"],\n [\"ZA\", \"South Africa\"],\n [\"ZM\", \"Zambia\"],\n [\"ZW\", \"Zimbabwe\"],\n ];\n let zoneData = [];\n for (let index = 0; index < countriesCodeAndName.length; index++) {\n moment.tz\n .zonesForCountry(countriesCodeAndName[index][0])\n .forEach((zone) => {\n zoneData.push({\n countryCode: countriesCodeAndName[index][0],\n countryName: countriesCodeAndName[index][1],\n zoneName: zone\n .split(\"/\")\n [zone.split(\"/\").length - 1].replace(\"_\", \" \"),\n zoneTimeDate: moment().tz(zone),\n completZoneName: zone,\n });\n });\n }\n return zoneData;\n}",
"processData(data){\n //Set timezone offset\n let offset = data[\"city\"][\"timezone\"]/3600\n \n data = data[\"list\"]\n //Process data for 3 hour view\n let threeHrData = {}\n let dateList = []\n\n //Loop through each 3hr period\n for (let i = 0; i < data.length; i++){\n \n //Get local time\n let offset_datetime = util.offsetDateTime(data[i][\"dt_txt\"], offset)\n let date, time, ampm\n [date, time, ampm] = (offset_datetime).split(\" \")\n\n if (!(date in threeHrData)){\n threeHrData[date] = []\n dateList.push(date)\n }\n threeHrData[date].push({\n \"time\": parseInt(time) + ampm,\n \"temp_min\": data[i][\"main\"][\"temp_min\"],\n \"temp_max\": data[i][\"main\"][\"temp_max\"],\n \"weather\": data[i][\"weather\"][0][\"description\"],\n \"weatherid\": data[i][\"weather\"][0][\"id\"],\n \"wind\": data[i][\"wind\"][\"speed\"],\n \"deg\": data[i][\"wind\"][\"deg\"],\n \"icon\": data[i][\"weather\"][0][\"icon\"]\n })\n }\n\n console.log(threeHrData)\n this.setState({\n threeHrData: threeHrData,\n dateList: dateList\n })\n\n //Process data for daily summary\n let dailyData = {}\n Object.keys(threeHrData).forEach(date=>{\n let temp_max = -999\n let temp_min = 999\n let worst_weather_id = 0\n let cloud_weather_id = 800\n let worst_weather = ''\n let cloud_weather = 'clear sky'\n let wind_max = 0\n let worst_weather_icon = ''\n let cloud_weather_icon = '01d'\n //Get min/max temp, and worst weather and wind for that day.\n for (let i = 0; i < threeHrData[date].length; i++){\n if (threeHrData[date][i][\"temp_max\"] > temp_max) temp_max = threeHrData[date][i][\"temp_max\"]\n if (threeHrData[date][i][\"temp_min\"] < temp_min) temp_min = threeHrData[date][i][\"temp_min\"]\n if (threeHrData[date][i][\"wind\"] > wind_max) wind_max = threeHrData[date][i][\"wind\"]\n if (threeHrData[date][i][\"weatherid\"] > worst_weather_id && threeHrData[date][i][\"weatherid\"] < 800)\n {\n worst_weather_id = threeHrData[date][i][\"weatherid\"]\n worst_weather = threeHrData[date][i][\"weather\"]\n worst_weather_icon= threeHrData[date][i][\"icon\"]\n } \n\n if (threeHrData[date][i][\"weatherid\"] > cloud_weather_id)\n {\n cloud_weather_id = threeHrData[date][i][\"weatherid\"]\n cloud_weather = threeHrData[date][i][\"weather\"]\n cloud_weather_icon= threeHrData[date][i][\"icon\"]\n } \n\n }\n\n /*For daily summary,\n If have multiple weather_id throughout the day, show the worst weather for that day.\n Show Highest weather_id within 0 < id < 800. Otherwise show the highest value from group 8xx (cloudy statuses).\n */\n let weather_id\n let weather\n let icon\n if (worst_weather_id > 0){\n weather_id = worst_weather_id\n weather = worst_weather\n icon = worst_weather_icon\n } else {\n weather_id = cloud_weather_id\n weather = cloud_weather\n icon = cloud_weather_icon\n }\n\n dailyData[date] = {\n \"temp_max\": temp_max,\n \"temp_min\": temp_min,\n \"weather_id\": weather_id,\n \"weather\": weather,\n \"wind_max\": wind_max,\n \"icon\": icon\n }\n })\n\n this.setState({dailyData:dailyData})\n console.log(dailyData)\n }",
"function getWeather(userLocation){\r\n\t// Declaring apiKey and queryURL\r\n\tvar apiKey = \"dcdb5e1e6d6e436d95224746171310\"; \r\n\tvar queryURL = \"http://api.apixu.com/v1/forecast.json?key=\"+apiKey+\"&q=\"+userLocation.lat+\",\"+userLocation.long+\"&days=5\";\r\n\r\n\t// Create an AJAX call to retrieve data in console https://www.apixu.com/doc/forecast.aspx\r\n\t$.ajax({\r\n\t\turl:queryURL,\r\n\t\tmethod: \"GET\"\r\n\t}).done(function(response){\r\n\t\tweather = response;\r\n\t\t// Get array of forecast: temp(f),text,icon localtime. Then output for each day for max/min temp, condition, icon and format of date.\r\n\t\tvar forecast = [];\r\n\t\tfor (var i = 0; i<5; i++){\r\n\t\t\tvar tempForecast = {};\r\n\r\n\t\t\t/*The current temperature could have been stored separately, since the data is different. However, the desire was to only pass a single object, hence why this method of storing the data was chosen.*/\r\n\t\t\tif (i === 0){\r\n\t\t\t\ttempForecast = {\r\n\t\t\t\t\tcurrentTemp: weather.current.temp_f,\r\n\t\t\t\t\tcurrentHumidity: weather.current.humidity,\r\n\t\t\t\t\tcurrentWindSpeed: weather.current.wind_mph.toFixed(0),\r\n\t\t\t\t\tcurrentWindDirection: weather.current.wind_dir,\r\n\t\t\t\t\tcurrentCondition: weather.current.condition.text,\r\n\t\t\t\t\tcurrentConditionIcon: weather.current.condition.icon,\r\n\t\t\t\t\tcurrentConditionCode: weather.current.condition.code,\r\n\t\t\t\t\tcurrentConditionNewIcon: \"\",\r\n\t\t\t\t\tcurrentTime: moment(weather.location.localtime).format(\"hh:mm\"),\r\n\t\t\t\t\tcurrentAMPM: moment(weather.location.localtime).format(\"A\"),\r\n\t\t\t\t\tcurrentDate: moment(weather.location.localtime).format(\"ddd MMM. DD\")\r\n\t\t\t\t};\r\n\t\t\t\tforecast.push(tempForecast); \r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\ttempForecast = {\r\n\t\t\t\t\tmaxTemp:weather.forecast.forecastday[i].day.maxtemp_f,\r\n\t\t\t\t\tminTemp: weather.forecast.forecastday[i].day.mintemp_f,\r\n\t\t\t\t\tcondition: weather.forecast.forecastday[i].day.condition.text,\r\n\t\t\t\t\tconditionIcon: weather.forecast.forecastday[i].day.condition.icon,\r\n\t\t\t\t\tconditionCode: weather.forecast.forecastday[i].day.condition.code,\r\n\t\t\t\t\tconditionNewIcon: \"\",\r\n\t\t\t\t\tdate: getDayfromNum(new Date(weather.forecast.forecastday[i].date.replace(/-/, '/').replace(/-/,'/')).getDay())\r\n\t\t\t\t};\r\n\t\t\t\tforecast.push(tempForecast);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Builds the Weather Widget\r\n\t\tbuildWeatherWidget(userLocation, forecast);\r\n\t});\r\n}",
"function getWeatherResults(query) {\r\n fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)\r\n .then(function(resp) { return resp.json() })\r\n .then(function(weather) {\r\n //obtains data from API and sets that data\r\n let city = document.querySelector('.city');\r\n let temp = document.querySelector('.temp');\r\n let date = document.querySelector('.date');\r\n let weather_el = document.querySelector('.weather');\r\n let hilow = document.querySelector('.hAndl');\r\n \r\n // Prints values to webpage\r\n city.innerText = `${weather.name}, ${weather.sys.country}`;\r\n temp.innerHTML = `${((Math.round(weather.main.temp)) * (9/5) + 32).toFixed(1)}<span>°F</span>`;\r\n weather_el.innerText = weather.weather[0].main;\r\n hilow.innerText = `${((Math.round(weather.main.temp_min)) * (9/5) + 32).toFixed(1)}°F - ${((Math.round(weather.main.temp_max)) * (9/5) + 32).toFixed(1)}°F`;\r\n \r\n //Helper function to build dates\r\n let currDate = new Date();\r\n date.innerText = getDate(currDate);\r\n \r\n // Reading in coordinates for location\r\n let countryCode = weather.sys.country;\r\n getCountryID(countryCode);\r\n\r\n })\r\n .catch(function() {\r\n console.log(\"error\");\r\n })\r\n}",
"function getCurrentHourData() {\n\t return result.filter(function (item) { \n\t\t\t\tvar date = new Date((item.timestampMs/1000)*1000);\n\t\t\t\tvar hours = date.getHours();\n\t\t\t\treturn hours === d.getHours();\n\t\t\t})\n\t\t\t.map( function(item){ \n\t\t\t\treturn [item.latitudeE7 * SCALAR_E7, item.longitudeE7 * SCALAR_E7]; \n\t\t\t})\n\t }",
"function getWeather() \r\n{\r\n const date = (new Date().toLocaleDateString('en-IE', {day: 'numeric', month: 'long'}));\r\n const currentDate = new Date().toLocaleTimeString('en-IE', {hour: '2-digit', minute: '2-digit', hour12: true }); \r\n $(\"#CityAndTime\").html(`${date}, ${currentDate}`)\r\n $.get(\"/weather/hourly\", function(data, status){\r\n\r\n $(\"#weatherTemp\").html(data[\"hourly_forecast\"][0][\"temp\"][\"metric\"] + \" ℃\");\r\n $(\"#weatherImage\").attr(\"src\", data[\"hourly_forecast\"][0][\"icon_url\"]);\r\n $(\"#weatherFeelsLike\").html(\" Feels like: \" + data[\"hourly_forecast\"][0][\"feelslike\"][\"metric\"] + \" ℃\");\r\n $(\"#weatherDescription\").html(data[\"hourly_forecast\"][0][\"condition\"]);\r\n $(\"#weatherWind\").html(\"Wind: \" + data[\"hourly_forecast\"][0][\"wspd\"][\"metric\"] + \" km/h\");\r\n let rainBinary = 0;\r\n if(data[\"hourly_forecast\"][0][\"condition\"] == 'Rain' )\r\n {\r\n rainBinary = 1;\r\n }\r\n weatherData = {\r\n \"description\": data[\"hourly_forecast\"][0][\"condition\"], \r\n \"rainBinary\": rainBinary , \r\n \"temperature\":data[\"hourly_forecast\"][0][\"temp\"][\"metric\"]\r\n }\r\n for (i=2; i<5; i+=2)\r\n {\r\n $(\"#lowerPart\").append(\r\n `<hr> \r\n <div class = \"row lessPadding\">\r\n <div class=\"col-md-4\">\r\n <p class=\"text-left\">${data[\"hourly_forecast\"][i][\"FCTTIME\"][\"civil\"]}</p>\r\n </div>\r\n <div class=\"col-md-4\">\r\n <image id = \"weatherImage\" src = \"${data[\"hourly_forecast\"][i][\"icon_url\"]}\"> </image>\r\n </div>\r\n <div class=\"col-md-4\">\r\n <p class=\"text-right\">${data[\"hourly_forecast\"][i][\"temp\"][\"metric\"]} ℃</p>\r\n </div>\r\n </div>`\r\n ); \r\n }\r\n });\r\n \r\n \r\n}",
"function getData() {\n dbService.getWeatherData()\n .then(function(entries){\n applyEntries(entries);\n });\n }",
"renderTimezoneSelect() {\n // Users timezone\n const userTimezone = {\n [this.currentTimezone]:\n 'Your timezone: (GMT' + moment.tz(this.currentTimezone).format('Z') + ') ' + this.currentTimezone,\n };\n\n // List with common timezones\n const commonTimezones = {\n 'Pacific/Honolulu': '(GMT-10:00) Hawaiian/Aleutian Time',\n 'America/Anchorage': '(GMT-08:00) Alaska Time',\n 'America/Los_Angeles': '(GMT-07:00) Pacific Time (US)',\n 'America/Phoenix': '(GMT-07:00) Mountain Time (Arizona)',\n 'America/Denver': '(GMT-06:00) Mountain Time (US)',\n 'America/Chicago': '(GMT-05:00) Central Time (US)',\n 'America/New_York': '(GMT-04:00) Eastern Time (US)',\n 'America/Indiana/Knox': '(GMT-05:00) Central Time (Indiana)',\n 'America/Indiana/Indianapolis': '(GMT-04:00) Eastern Time (Indiana)',\n 'America/Regina': '(GMT-06:00) Central Time (Saskatchewan)',\n 'America/Monterrey': '(GMT-05:00) Central Time (Mexico City, Monterey)',\n 'America/Lima': '(GMT-05:00) UTC/GMT -5 hours',\n 'America/Manaus': '(GMT-04:00) Atlantic Time',\n 'America/Montevideo': '(GMT-03:00) Uruguay',\n 'America/Puerto_Rico': '(GMT-04:00) Atlantic Time (Puerto Rico)',\n 'America/Thule': '(GMT-03:00) Western Greenland Time',\n 'America/Sao_Paulo': '(GMT-03:00) Eastern Brazil',\n 'America/St_Johns': '(GMT-02:30) Newfoundland Time',\n 'America/Godthab': '(GMT-02:00) Central Greenland Time',\n 'Etc/GMT+2': '(GMT-02:00) GMT-2:00',\n 'America/Scoresbysund': '(GMT+00:00) Eastern Greenland Time',\n 'Atlantic/Reykjavik': '(GMT+00:00) Western European Time (Iceland)',\n UTC: '(GMT+00:00) UTC',\n 'Europe/London': '(GMT+01:00) British Time (London)',\n 'Etc/GMT-1': '(GMT+01:00) GMT+1:00',\n 'Europe/Lisbon': '(GMT+01:00) Western European Time (Lisbon)',\n 'Europe/Paris': '(GMT+02:00) Western European Time',\n 'Europe/Berlin': '(GMT+02:00) Central European Time',\n 'Europe/Bucharest': '(GMT+03:00) Eastern European Time',\n 'Africa/Johannesburg': '(GMT+02:00) South Africa Standard Time',\n 'Africa/Kampala': '(GMT+03:00) Eastern Africa Time',\n 'Etc/GMT-3': '(GMT+03:00) Moscow',\n 'Asia/Tehran': '(GMT+04:30) Iran Standard Time',\n 'Asia/Dubai': '(GMT+04:00) UAE (Dubai)',\n 'Asia/Karachi': '(GMT+05:00) Pakistan Standard Time (Karachi)',\n 'Asia/Calcutta': '(GMT+05:30) India',\n 'Asia/Dhaka': '(GMT+06:00) Bangladesh Standard Time',\n 'Asia/Jakarta': '(GMT+07:00) Western Indonesian Time (Jakarta)',\n 'Asia/Bangkok': '(GMT+07:00) Thailand (Bangkok)',\n 'Asia/Hong_Kong': '(GMT+08:00) Hong Kong',\n 'Asia/Singapore': '(GMT+08:00) Singapore',\n 'Australia/West': '(GMT+08:00) Australian Western Time',\n 'Asia/Tokyo': '(GMT+09:00) Tokyo',\n 'Australia/North': '(GMT+09:30) Australian Central Time (Northern Territory)',\n 'Australia/Adelaide': '(GMT+09:30) Australian Central Time (Adelaide)',\n 'Australia/Queensland': '(GMT+10:00) Australian Eastern Time (Queensland)',\n 'Australia/Sydney': '(GMT+10:00) Australian Eastern Time (Sydney)',\n 'Pacific/Noumea': '(GMT+11:00) Noumea, New Caledonia',\n 'Pacific/Norfolk': '(GMT+11:00) Norfolk Island (Australia)',\n 'Pacific/Tarawa': '(GMT+12:00) Tarawa',\n 'Pacific/Auckland': '(GMT+12:00) New Zealand Time',\n 'Pacific/Apia': '(GMT+13:00) Apia, Samoa',\n };\n\n const selectOptions = {\n options: Object.assign(userTimezone, commonTimezones),\n };\n\n // Parse select html\n const $select = document.querySelector('#timezone-select');\n const source = document.querySelector('#timezone-template').innerHTML;\n const template = Handlebars.compile(source);\n $select.innerHTML = template(selectOptions);\n }",
"function parseWeatherData(){\n\t\n\tforecastArr.push(new Forecast(ipJSON.lat, ipJSON.lon, ipJSON.city, ipJSON.region, ipJSON.countryCode));\n\tforecastIndex = forecastArr.length - 1;\n\t\n\tfor(var i = 0;i<numDaysToShow;i++){\n\t\t\n\t\t\n\t\t//Convert time to formatted date (day, month date)\n\t\tvar dayDate = new Date(weatherJSON.daily.data[i].time * 1000); //Convert time to milliseconds\n\t\tvar sunriseDate = new Date(weatherJSON.daily.data[i].sunriseTime * 1000);\n\t\tvar sunsetDate = new Date(weatherJSON.daily.data[i].sunsetTime * 1000);\n\t\t\n\t\tvar sunriseTime = formatTime(sunriseDate);\n\t\tvar sunsetTime = formatTime(sunsetDate);\n\t\t\n\t\tforecastArr[forecastIndex].dayArr.push(new Day(\n\t\t\tdayNamesArr[dayDate.getDay()] + \", \" + monthNamesArr[dayDate.getMonth()] + \" \" + dayDate.getDate(),\n\t\t\tweatherJSON.daily.data[i].icon,\n\t\t\tweatherJSON.daily.data[i].summary,\n\t\t\t[weatherJSON.daily.data[i].temperatureMin, weatherJSON.daily.data[i].temperatureMax],\n\t\t\t[sunriseTime, sunsetTime],\n\t\t\tMath.round(weatherJSON.daily.data[i].precipProbability * 100)\n\t\t));\n\t\n\t\t//Add the current weather weather information to the first Day (today)\n\t\tif(i === 0){\n\t\t\tforecastArr[forecastIndex].dayArr[i].curIcon = weatherJSON.currently.icon;\n\t\t\tforecastArr[forecastIndex].dayArr[i].curWeather = weatherJSON.currently.summary + \", \";\n\t\t\tforecastArr[forecastIndex].dayArr[i].curTemp = weatherJSON.currently.temperature;\n\t\t}\n\t\t\n\t\tdisplayWeatherData(forecastArr[forecastIndex], i, false);\n\t}\n}",
"function getWeather(cityName,cityIndexWL)\n{\n // some handy special characters for use down the road\n const degStr = String.fromCharCode(8457);\n const SEArrowStr = String.fromCharCode(8600);\n const downArrowStr = String.fromCharCode(8595);\n const NEArrowStr = String.fromCharCode(8599);\n\n // ok, let's get some weather info!\n\n // our query strings are assembled here.\n var baseURL = \"https://api.openweathermap.org/data/2.5/\";\n var openWeatherKey = \"35a41f79e853928d773cad1da927b1b4\";\n var appId = \"&appid=\"+openWeatherKey;\n var units = \"&units=imperial\"\n var currentW = \"weather?q=\";\n var forecastW = \"forecast?q=\";\n var uviW = \"uvi?\";\n var currentURL = baseURL+currentW+cityName+appId+units;\n var forecastURL = baseURL+forecastW+cityName+appId+units;\n var uviURL = baseURL+uviW+appId\n +\"&lat=\" + weatherLocs[cityIndexWL][\"city\"][\"coord\"][\"lat\"]\n +\"&lon=\" + weatherLocs[cityIndexWL][\"city\"][\"coord\"][\"lon\"];\n\n $.ajax({url: currentURL,method: \"GET\"}).then(\n function(response) \n {\n if (response)\n {\n if (ajaxDebug) {console.log(\"current weather\"); console.log(response);}\n\n // the hard work is done and we're staring at a big sack of potatoes.\n // start peelin'\n weatherObj.city = cityName;\n weatherObj.lat = response.coord.lat;\n weatherObj.lon = response.coord.lon;\n uviURL = uviURL+\"&lat=\"+response.coord.lat+\"&lon=\"+response.coord.lon;\n weatherObj.timezone = response.timezone;\n weatherObj.timeUTCUnix = response.dt;\n var dtObj = makeLocalTime(weatherObj.timeUTCUnix,weatherObj.timezone);\n var localTime = dtObj.dayOfWeek+\", \"+dtObj.hour+\":\"+dtObj.minute;\n weatherObj.temp = Math.round(response.main.temp);\n weatherObj.rH = response.main.humidity;\n weatherObj.description = response.weather[0].description;\n weatherObj.icon = response.weather[0].icon;\n weatherObj.windS = Math.round(0.621371*response.wind.speed);\n var dir = response.wind.deg;\n dir = dir < 0? dir+360 : dir;\n weatherObj.windD = dir > 22.5 && dir <= 67.5 ? \"NE\" :\n (dir > 67.5 && dir <= 112.5 ? \"E\" :\n (dir > 112.5 && dir <= 157.5 ? \"SE\" :\n (dir > 157.5 && dir <= 202.5 ? \"S\" :\n (dir > 202.5 && dir <= 247.5 ? \"SW\" :\n (dir > 247.5 && dir <= 292.5 ? \"W\" :\n (dir > 292.5 && dir <= 337.5 ? \"NW\" : \"N\"))))));\n\n // that was a load. let's get some content on the page.\n $(\"#todayCardCity\").text(cityName.toUpperCase() +\", local time: \"+localTime);\n $(\"#todayCardTemp\").text(weatherObj.temp+degStr);\n var iconStr = \"https://api.openweathermap.org/img/w/\"+weatherObj.icon+\".png\";\n $(\"#todayCardIcon\").attr(\"src\",iconStr);\n $(\"#todayCardDesc\").text(weatherObj.description);\n $(\"#todayCardRH\").text(\"Humidity: \"+weatherObj.rH+\"%\");\n $(\"#todayCardWind\").text(\"Wind: \" +weatherObj.windD+\" at \"+weatherObj.windS+\" mph\");\n }\n });\n\n if (ajaxDebug) {console.log(\"UVI URL: \"+uviURL);}\n\n $.ajax({url: uviURL,method: \"GET\"}).then(\n function(response) \n {\n if (response)\n {\n // we make this query just to get the UV Index\n if (ajaxDebug) {console.log(\"UV Index\"); console.log(response);}\n\n weatherObj.uvScore = Math.round(10*response.value)/10;\n var uScore = weatherObj.uvScore;\n $(\"#todayCardUV\").text(\"UV Index: \");\n // we also color-code the range of the UV Index. the method \n // is to use HTML class assignment with alternate CSS rules.\n var uv = $(\".todayCardUVIcon\");\n uv.text(uScore);\n uv.removeClass(\"noSun lowSun highSun\");\n uv.addClass(uScore < 3 ? \"noSun\" : (uScore < 7 ? \"lowSun\" : \"highSun\") );\n }\n });\n\n // the forecast holds 40 future records, all separated in forecast time by 3 hours\n // so 40*3 / 24 = 5 days of records are delivered. the first will be for sometime\n // in the next 3 hours, so some of the records will be for today (unless we are\n // approaching midnight).\n $.ajax({url: forecastURL,method: \"GET\"}).then(\n function(response) \n {\n if (response)\n {\n if (ajaxDebug) {console.log(\"Forecast\"); console.log(response);}\n\n // there should be 5 days of work through the next 5 days to make 5-day forecast info\n\n // we will find the first record for tomorrow. keep in mind that our city could\n // be anywhere in the world -- any timezone. so we need to work in local time.\n // fortunately, OpenWeather provides a UTC time offset for each supported city.\n // we use makeLocalTime to get the city's local time.\n var dtObj = makeLocalTime(weatherObj.timeUTCUnix,weatherObj.timezone); \n // our starting day is taken from the current weather request.\n var currentForecastDayOfMonth = dtObj.dayOfMonth;\n\n if (debug) {console.log(\"dayOfMonth in current forecast: \" + currentForecastDayOfMonth);}\n\n // using a 'while()' to emphasize the persistence of recordIndex\n var recordIndex = 0;\n do\n {\n dtObj = makeLocalTime(response.list[recordIndex].dt, weatherObj.timezone);\n if (debug) {console.log(\"looking for tomorrow, found \"+dtObj.dayOfMonth+\", \"+dtObj.hour);}\n }\n while (recordIndex++ < 40 && dtObj.dayOfMonth == currentForecastDayOfMonth)\n\n // note that the loop structure causes causes recordIndex to be high by one\n // run with debug turned on to see for yourself...\n recordIndex--;\n\n if (debug) {console.log(\"first record on new day: \"+recordIndex);}\n\n // recordIndex will be < 8 unless the data is fouled.\n if (recordIndex < 8)\n {\n // we now have the index of the first 'tomorrow' record\n // each calendar day is spanned by the current and next 7 records, so we work\n // in groups of 8, with the exception of the last day, which will probably\n // have less than 8.\n forecastDay = 0;\n while (recordIndex < 40)\n {\n // here's the trick to take care of the last day. \n var recordsInDay = recordIndex < 33 ? 8 : (40-recordIndex);\n\n // prep for the searches for minima and maxima in humidity and temperature\n var minTemp = 500;\n var maxTemp = -500;\n var minRH = 101;\n var maxRH = -1;\n\n // oh, BTW, we're ready to write our first record of this day -- the date\n dtObj = makeLocalTime(response.list[recordIndex].dt, weatherObj.timezone);\n var dateStr = dtObj.dayOfWeek+\", \"+dtObj.dayOfMonth+\" \"+dtObj.monthNameShort;\n if (debug) {console.log(dateStr);}\n\n weatherObj.forecastDates[forecastDay] = dateStr;\n\n // now we move through the day, gleaning from each 3-hr record. \n for (let inDay = 0; inDay < recordsInDay; inDay++)\n {\n // get the hour to be able to show when the high and low temperatures\n // are forecast to occur.\n dtObj = makeLocalTime(response.list[recordIndex].dt, weatherObj.timezone);\n var hr = dtObj.hour;\n if (debug) {console.log(\"by record: recordIndex \"+recordIndex+\", dayOfMonth \"+\n dtObj.dayOfMonth+\", hour \"+hr)}\n // minima and maxima checks. \n temp = response.list[recordIndex].main.temp;\n if (temp < minTemp) {minTemp = temp; minTempTOD = hr;}\n if (temp > minTemp) {maxTemp = temp; maxTempTOD = hr;}\n var RH = response.list[recordIndex].main.humidity;\n minRH = RH < minRH ? RH : minRH;\n maxRH = RH > maxRH ? RH : maxRH;\n\n // the weather icon is a single sample. this test is assured to give us a\n // sample, even if the last day only has one record. but it won't take a\n // sample after early afternoon.\n if (inDay < 4) \n {\n weatherObj.forecastIcons[forecastDay] = response.list[recordIndex].weather[0].icon;\n }\n // remember the outer loop...\n recordIndex++;\n }\n // alright, let's tally our treasure.\n weatherObj.forecastRHhighs[forecastDay] = maxRH = Math.round(maxRH);\n weatherObj.forecastRHlows[forecastDay] = minRH = Math.round(minRH);\n weatherObj.forecastHighs[forecastDay] = maxTemp = Math.round(maxTemp);\n weatherObj.forecastHTOD[forecastDay] = maxTempTOD;\n weatherObj.forecastLows[forecastDay] = minTemp = Math.round(minTemp);\n weatherObj.forecastLTOD[forecastDay] = minTempTOD;\n\n // and get this dayCard posted on the page. \n\n // each dayCard<n> has a div; here <n> is forecastDay. this chunk of code\n // is stuffing what we've accumulated for the day onto (into?) the day's div.\n dayId = $(\".dayCard\"+forecastDay);\n dayId.empty();\n\n var newP = $(\"<p>\"); \n newP.text(weatherObj.forecastDates[forecastDay]).addClass(\"dayCardDate\"); \n newP.appendTo(dayId);\n\n // note the mapping to the icons at OpenWeather\n var newImg=$(\"<img>\");\n var iconStr = \"https://api.openweathermap.org/img/w/\"+weatherObj.forecastIcons[forecastDay]+\".png\";\n newImg.attr(\"src\",iconStr).addClass(\"dayCardIcon\"); \n newImg.appendTo(dayId);\n\n // the local variables used in the inDay loop are still in context.\n var newP = $(\"<p>\"); \n newP.text(\"humidity: \" + minRH + \"%-\" + maxRH +\"%\").addClass(\"dayCardRH\");\n newP.appendTo(dayId);\n\n // and here's where the special characters are used.\n var highStr = maxTemp + degStr + \" at \" + maxTempTOD + \"00\"; \n var lowStr = minTemp + degStr + \" at \" + minTempTOD + \"00\"; \n var newHiP = $(\"<p>\"); \n newHiP.text(highStr).addClass(\"dayCardHighTemp\");\n var newLoP = $(\"<p>\"); \n newLoP.text(lowStr).addClass(\"dayCardLowTemp\");\n var newArP = $(\"<p>\"); \n\n // the dayCard has the feature of showing the high and low temps\n // for the day with the high left of the low if the low happens later - \n // and vice versa. (yes, they're lined up if they're the same.)\n var arrowStr = downArrowStr;\n if (maxTempTOD > minTempTOD) //hottest is later than coolest\n {\n arrowStr = NEArrowStr;\n newHiP.addClass(\"right\");\n }\n else if (maxTempTOD < minTempTOD) // hottest is earlier than coolest\n {\n arrowStr = SEArrowStr;\n newLoP.addClass(\"right\");\n }\n \n newArP.text(arrowStr).addClass(\"dayCardArrow\");\n \n newHiP.appendTo(dayId);\n newArP.appendTo(dayId);\n newLoP.appendTo(dayId);\n\n // onward to the next day.\n forecastDay++;\n }\n }\n }\n });\n\n if (ajaxDebug) {console.log(\"weatherObj: \"); console.log(weatherObj);}\n}",
"async function GetTheTimezoneInfoForAspecificLocation() {\n let timeService = new time.TimeService(process.env.MICRO_API_TOKEN);\n let rsp = await timeService.zone({\n location: \"London\",\n });\n console.log(rsp);\n}",
"function getWeatherConditions(i, target) {\n var times = [];\n $.ajax({\n url: peakInfo[i].weatherLink,\n method: \"GET\"\n \n }).then(function(response){\n // console.log(response);\n for (var n = 0; n < 6; n++) {\n times.push({\n number: response.properties.periods[n].number,\n startTime: response.properties.periods[n].startTime,\n temperature: response.properties.periods[n].temperature,\n windSpeed: response.properties.periods[n].windSpeed,\n windDirection: response.properties.periods[n].windDirection,\n shortForecast: response.properties.periods[n].shortForecast,\n detailedForecast: response.properties.periods[n].detailedForecast\n });\n \n };\n console.log(times[0]);\n\n //Render weather to tables\n $(\"#mtn-\" + (target) + \"-wind\").text(times[0].windSpeed);\n $(\"#mtn-\" + (target) + \"-temperature\").text(times[0].temperature + \" F\");\n $(\"#mtn-\" + (target) + \"-wind-direction\").text(times[0].windDirection);\n // $(\"#mtn-\" + (target) + \"-short-forecast\").text(times[0].shortForecast);\n \n //Conditional Formatting for Windspeed\n var windSpeedString = times[0].windSpeed;\n var windSpeedRange = windSpeedString.match(/\\d+/g).map(Number);\n //This returns array of low and high wind speeds\n var windConditions = $(\"#mtn-\" + (target) + \"-wind\") \n\n if (windSpeedRange[1] > 75) {\n windConditions.css(\"background-color\", \"rgba(191, 78, 63, 0.4)\")\n } else if ( (windSpeedRange[0] > 30) && (windSpeedRange[1] <= 75 ) ) {\n windConditions.css(\"background-color\", \"rgba(229, 238, 73, 0.4)\")\n } else {\n windConditions.css(\"background-color\", \"rgba(63, 191, 63, 0.4)\")\n }\n\n //Conditional Formatting for Temperature\n var temp = times[0].temperature;\n\n var tempConditions = $(\"#mtn-\" + target + \"-temperature\");\n\n if (temp < 32) {\n tempConditions.css(\"background-color\", \"rgb(30, 201, 255, 0.4)\");\n } else if ((temp > 32) && (temp < 60) ) {\n tempConditions.css(\"background-color\", \"rgba(63, 191, 63, 0.4)\");\n } else {\n tempConditions.css(\"background-color\", \"rgba(191, 78, 63, 0.4)\");\n }\n\n //Conditional Formatting for Short Forecast\n var shortForecast = times[0].shortForecast;\n\n var shortForecastConditions = $(\"#mtn-\" + (target) + \"-short-forecast\");\n\n if ((shortForecast === \"Chance Snow Showers\") ||\n (shortForecast === \"Snow Showers Likely\") ||\n (shortForecast === \"Snow Showers\") ||\n (shortForecast === \"Slight Chance Snow Showers\") ||\n (shortForecast === \"Partly Cloudy then Slight Chance Snow Showers\") ||\n (shortForecast === \"Mostly Cloudy then Chance Snow Showers\") ||\n (shortForecast === \"Isolated Snow Showers then Mostly Sunny\")\n ) {\n shortForecastConditions.css('background-image', 'url(\"http://icons.iconarchive.com/icons/icons8/christmas-flat-color/256/snowflake-icon.png\")')\n } else {\n shortForecastConditions.text(shortForecast);\n }\n });\n \n \n }",
"function sendAllSelectedOptions(){\nvar allOptions = document.getElementsByClassName(\"allSelects\");\n// for(var i=0; i<allOptions.length; i++){\n// console.log(\"These are the values you need FOR COUNTRY NAME- \"+allOptions[i].value);\n// }\n\n//var allZones = document.getElementsByClassName(\"allZones\");\nvar timeZone = document.getElementsByClassName(\"allZones\");\nfor(var i=0; i<timeZone.length; i++){\nconsole.log(\"These are the values you need FOR ALL TIME ZONES- \"+timeZone[i].value);\n }\n\n var xhttp = new XMLHttpRequest();\nvar dataURL = 'http://api.timezonedb.com/v2/list-time-zone?key=LHW0VPUEFWFT&format=json';\n\n//var timeZone = [\"America/Los_Angeles\", \"Asia/Kolkata\", \"Africa/Lagos\",\"America/New_York\",\"Europe/London\"];\n//var timeZone = [\"Asia/Kolkata\", \"America/New_York\", \"Asia/Kolkata\",\"Asia/Kolkata\",\"Asia/Kolkata\"];\n\n//var timeZone = JSON.parse(JSON.stringify(allZones));\n\n/*for(var i=0;i<4;i++)\n {\n console.log(\"Getting Data \" + allZones[i]);\n } */\n\nvar arrayLength = timeZone.length;\nvar allTime = [];\n\n\nsetInterval(function(){\nxhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n // Typical action to be performed when the document is ready:\n var results = JSON.parse(xhttp.responseText);\n console.log(results);\n var localDate = new Date();\n //Local Time GMT Offset Correction\n var timeOffset = localDate.getTimezoneOffset();\n var hours = localDate.getHours();\n var minutes = \"0\" + localDate.getMinutes();\n var seconds = \"0\" + localDate.getSeconds();\n var localTime = hours + minutes.substr(-2);\n localTime = parseInt(localTime, 10);\n console.log(\"Local Time in 24hours format: \" + localTime);\n //Format 12 Hours\n var hoursAMPM = (hours >= 12 ? 'PM' : 'AM');\n hours = hours % 12 || 12;\n var formattedLocalTime = hours + ':' + minutes.substr(-2) + ' ' + hoursAMPM;\n document.getElementById(\"localTime\").innerHTML = \"Local time: \" + formattedLocalTime;\n document.getElementById(\"cityTime\").innerHTML = \"The time in the selected Cities: \";\n var ul = document.getElementById(\"listTime\");\n //ul.removeChild(li);\n var node = document.getElementById('listTime');\n while(node.firstChild){\n node.removeChild(node.firstChild);\n }\n for(var i =0;i<arrayLength;i++)\n {\n for(var j =0;j<424;j++)\n {\n if(timeZone[i].value == results.zones[j].zoneName)\n {\n //console.log(results.zones[j].zoneName);\n //getFormattedTime(results.zones[j].timestamp);\n //console.log(results.zones[j].timestamp);\n //Time of location in UTC\n var locationTime = results.zones[j].timestamp + (timeOffset * 60);\n var locationDate = new Date(locationTime * 1000);\n // Hours part from the timestamp\n hours = locationDate.getHours();\n // Minutes part from the timestamp\n minutes = \"0\" + locationDate.getMinutes();\n // Seconds part from the timestamp\n seconds = \"0\" + locationDate.getSeconds();\n // Will display time in 10:30:23 format\n var newTime = hours + minutes.substr(-2); //24 hour format for calculation\n newTime = parseInt(newTime, 10);\n //console.log(newTime);\n allTime[i] = newTime;\n //Format 12 Hours\n hoursAMPM = (hours >= 12 ? 'PM' : 'AM');\n hours = hours % 12 || 12;\n var formattedTime = hours + ':' + minutes.substr(-2) + ' ' + hoursAMPM;\n //$('.time').html(formattedTime);\n //allTime[i] = formattedTime;\n console.log(timeZone[i].value + \" : \" + formattedTime);\n var li = document.createElement(\"li\");\n li.innerHTML = timeZone[i].value + \" : \" + formattedTime;\n //li.appendChild(document.createTextNode(timeZone[i].value + \" : \" + formattedTime));\n ul.appendChild(li);\n }\n }\n\n }\n collabTime(allTime, localTime);\n\n }\n};\n\n\nxhttp.open(\"GET\", dataURL, true);\nxhttp.send();\n\n}, 2000);\n\n\nfunction collabTime(calcTime, localTime)\n{\n //console.log(\"Local City: \" + localTime);\n var collabCheck = [\"\"];\n var collabStatus;\n if(localTime>=800 && localTime< 2200)\n {\n console.log(\"Local City: Collab\");\n for(var i =0;i<arrayLength;i++)\n {\n console.log(calcTime[i] );\n if(calcTime[i]>=800 && calcTime[i] < 2200)\n {\n collabCheck[i] = \"Collab\";\n }\n else\n {\n collabCheck[i] = \"No Collab\";\n }\n console.log(collabCheck[i]);\n }\n for(var i =0;i<arrayLength-1;i++)\n {\n if(collabCheck[i] == \"Collab\" && collabCheck[i] == collabCheck[i+1])\n {\n collabStatus = \"true\";\n }\n else\n {\n collabStatus = \"false\";\n break;\n }\n }\n console.log(collabStatus);\n document.getElementById(\"collabState\").innerHTML = \"Collaboration is possible\";\n }\n else\n {\n console.log(\"Local City: No Collab\");\n document.getElementById(\"collabState\").innerHTML = \"Collaboration is not possible\";\n }\n}\n\n\n} //end of function",
"function first() {\n\n for (var i = 0; i < convertedCoords.length; i++) {\n var queryURL = \"https://api.openweathermap.org/data/2.5/forecast?q=\" + convertedCoords[i] + \"&appid=fe2767efcdc5875e488e5fcdeb27a943&units=imperial\"\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n // console.log(response)\n // console.log(response.city.name)\n var sunrise = response.city.sunrise;\n var sunset = response.city.sunset;\n // console.log(\"+++++++\")\n convertedMorning = timeConverter(sunrise)\n // console.log(\"+++++++\")\n convertedNight = timeConverter(sunset)\n // console.log(\"+++++++\")\n // console.log(\"___________\")\n // console.log(\"___________\")\n $(\"#tb\").append(\n $(\"<tr>\").append(\n $(\"<td>\").text(response.city.name),\n // console.log(response.list[1].wind),\n $(\"<td>\").text(response.list[1].wind.speed),\n $(\"<td>\").text(response.list[1].main.humidity),\n $(\"<td>\").text(response.list[1].main.temp),\n $(\"<td>\").text(convertedMorning),\n $(\"<td>\").text(convertedNight),\n // console.log(response.list[1].weather[0].description),\n $(\"<td>\").text(response.list[1].weather[0].description)\n\n ))\n\n })\n\n }\n\n\n // Unix time converter:\n function timeConverter(a) {\n let unix_timestamp = a\n // Create a new JavaScript Date object based on the timestamp\n // multiplied by 1000 so that the argument is in milliseconds, not seconds.\n var date = new Date(unix_timestamp * 1000);\n // Hours part from the timestamp\n var hours = date.getHours();\n // Minutes part from the timestamp\n var minutes = \"0\" + date.getMinutes();\n // Seconds part from the timestamp\n var seconds = \"0\" + date.getSeconds();\n\n // Will display time in 10:30:23 format\n var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);\n\n // console.log(\"this is the formatted time: \", formattedTime);\n return formattedTime\n }\n\n\n }",
"function weather(value) {\r\n fetch(\r\n `https://api.openweathermap.org/data/2.5/weather?q=${value}&appid=5babc5498e87eb8a8514cf59bf97d03d`\r\n )\r\n .then((res) => {\r\n return res.json();\r\n })\r\n .then((data) => {\r\n ///adding Location\r\n const country = data.sys.country;\r\n const place = data.name;\r\n loc.innerHTML = `${place},${country}`;\r\n\r\n\r\n //create date time with time zone of that place\r\n fetch(\r\n `https://api.opencagedata.com/geocode/v1/json?q=${value}&key=63e0ba773c1f48cab08fb5207ed83498`\r\n )\r\n .then((res) => {\r\n return res.json();\r\n })\r\n .then((resp) => {\r\n const timezone = resp.results[0].annotations.timezone.name;\r\n const dateandtime = new Date().toLocaleString(\"en-US\", {\r\n timeZone: timezone,\r\n });\r\n let hours = new Date(dateandtime).getHours();\r\n let h = new Date(dateandtime).getHours();\r\n let mins = new Date(dateandtime).getMinutes();\r\n const date = new Date(dateandtime);\r\n let day;\r\n switch (date.getDay()) {\r\n case 1:\r\n day = \"Mon\";\r\n break;\r\n case 2:\r\n day = \"Tue\";\r\n break;\r\n case 3:\r\n day = \"Wed\";\r\n break;\r\n case 4:\r\n day = \"Thu\";\r\n break;\r\n case 5:\r\n day = \"Fri\";\r\n break;\r\n case 6:\r\n day = \"Sat\";\r\n break;\r\n case 7:\r\n day = \"Sun\";\r\n break;\r\n }\r\n console.log(h);\r\n let periods;\r\n if (h > 11) {\r\n periods = \"PM\";\r\n } else {\r\n periods = \"AM\";\r\n }\r\n if (h > 12) {\r\n h -= 12;\r\n }\r\n if (mins < 10) {\r\n mins = \"0\" + mins;\r\n }\r\n const time = `${date.getDate()}||${day}||${h}:${mins}${periods}`;\r\n displaytime.innerHTML = time;\r\n //adding icon\r\n icon.innerHTML = \" \";\r\n const condition = data.weather[0].main.toLowerCase();\r\n if (condition === \"clear\"&&(hours > 19 || hours < 6)) { \r\n icon.innerHTML = `<img src=\"https://img.icons8.com/external-justicon-flat-justicon/64/000000/external-night-weather-justicon-flat-justicon-2.png\"/>`;\r\n }\r\n else if (condition === \"clear\") {\r\n icon.innerHTML = `<img src='https://img.icons8.com/color/80/000000/sun--v2.png'/>`;\r\n } else if (condition === \"mist\") {\r\n icon.innerHTML = `<img src=\"https://img.icons8.com/dusk/64/000000/foggy-night-1.png\"/>`;\r\n } else {\r\n icon.innerHTML = `<img src='https://img.icons8.com/color/80/000000/${condition}--v2.png'/>`;\r\n }\r\n //adding background image\r\n if (condition === \"clear\"&&(hours > 19 || hours < 6)){\r\n background.style.backgroundImage =\r\n \"url('https://images.unsplash.com/photo-1574723507225-6d4bdb5707be?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=747&q=80')\";\r\n }\r\n else if (condition === \"clear\") {\r\n background.style.backgroundImage =\r\n \"url('https://images.pexels.com/photos/592658/pexels-photo-592658.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940')\";\r\n } else if (condition === \"haze\") {\r\n background.style.backgroundImage =\r\n \"url('https://images.unsplash.com/36/STzPBJUsSza3mzUxiplj_DSC09775.JPG?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=742&q=80')\";\r\n } else if (condition === \"rain\") {\r\n background.style.backgroundImage =\r\n \"url('https://images.unsplash.com/photo-1475116127127-e3ce09ee84e1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=750&q=80')\";\r\n } else if (condition === \"clouds\") {\r\n background.style.backgroundImage =\r\n \"url('https://images.unsplash.com/photo-1530743373890-f3c506b0b5b1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=806&q=80')\";\r\n } else if (condition === \"mist\") {\r\n background.style.backgroundImage =\r\n \"url('https://images.unsplash.com/photo-1575918748665-fbade67a07ed?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80')\";\r\n } else if (condition === \"snow\") {\r\n background.style.backgroundImage =\r\n \"url('https://images.pexels.com/photos/839462/pexels-photo-839462.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940')\";\r\n }\r\n con.innerHTML = `${condition}`;\r\n });\r\n //converting kel to celsius & adding\r\n const kel = data.main.temp;\r\n celsius = parseInt(kel - 273.15);\r\n temp.innerHTML = `${celsius}℃`;\r\n const minkel = data.main.temp_min;\r\n const maxkel = data.main.temp_max;\r\n const mincel = parseInt(minkel - 273.15);\r\n const maxcel = parseInt(maxkel - 273.15);\r\n minmax.innerHTML = `${mincel}℃(min)|${maxcel}℃(max)`;\r\n }) //error message\r\n .catch((err) => {\r\n alert(\r\n \"SomeThing Went Wrong🚨,Please Enter Some Value😎 Or Correct Value🚦\"\r\n );\r\n });\r\n}",
"function places_with_walltime(goal_time){\n\tvar countries = new Array;\n\tvar timezones = new Array;\n\t//for all countries where walltime == goal_time, array_push that country name and timezone into their respective arrays\n\tfor (var zid in zonelist) {\n\t\tif (zonelist.hasOwnProperty(zid)) {\n\t\t\tvar walltime = moment().tz(zid).hours();\n\t\t\tif (walltime == goal_time && ztc(zid)!== false){\n\t\t\t\tcountries.push(ztc(zid));\n\t\t\t\ttimezones.push(moment.tz(zid).format(\"Z\"));\n\t\t\t}\t\t\t\n\t\t}\n\t};\n\tvar res = {countries: countries, timezones: timezones};\n\treturn res;\n}",
"function zonaHoraria() {\n var offset = (new Date()).getTimezoneOffset();\n var timezones = {\n '-12': 'Pacific/Kwajalein',\n '-11': 'Pacific/Samoa',\n '-10': 'Pacific/Honolulu',\n '-9': 'America/Juneau',\n '-8': 'America/Los_Angeles',\n '-7': 'America/Denver',\n '-6': 'America/Mexico_City',\n '-5': 'America/Lima',\n '-4': 'America/Caracas',\n '-3.5': 'America/St_Johns',\n '-3': 'America/Argentina/Buenos_Aires',\n '-2': 'Atlantic/Azores',\n '-1': 'Atlantic/Azores',\n '0': 'Europe/London',\n '1': 'Europe/Paris',\n '2': 'Europe/Helsinki',\n '3': 'Europe/Moscow',\n '3.5': 'Asia/Tehran',\n '4': 'Asia/Baku',\n '4.5': 'Asia/Kabul',\n '5': 'Asia/Karachi',\n '5.5': 'Asia/Calcutta',\n '6': 'Asia/Colombo',\n '7': 'Asia/Bangkok',\n '8': 'Asia/Singapore',\n '9': 'Asia/Tokyo',\n '9.5': 'Australia/Darwin',\n '10': 'Pacific/Guam',\n '11': 'Asia/Magadan',\n '12': 'Asia/Kamchatka'\n };\n return timezones[-offset / 60];\n}",
"function getWeatherReport(latitude, longitude) {\n\n var apiKey = '383d16ca6466f351cb25cf3639e1fa01',\n\t\t\turl = 'https://api.darksky.net/forecast/',\n\t\t\tlati = latitude,\n\t\t\tlongi = longitude,\n\t\t\tapi_call = url + apiKey + \"/\" + lati + \",\" + longi + \"?extend=hourly&callback=?\";\n\n // Call to the DarkSky API to retrieve JSON\n $.getJSON(api_call, function (forecast)\n {\n var report = {};\n report.tempFahrenheit = forecast.currently.temperature; //текущая темп.\n report.apparentTempFahrenheit = forecast.currently.apparentTemperature; //по ощущениям\n report.visibility = forecast.currently.visibility; //видимость\n report.cloudCover = forecast.currently.cloudCover; //облачность\n report.dewPoint = forecast.currently.dewPoint; //точка росы\n report.humidity = forecast.currently.humidity; //влажность\n report.ozone = forecast.currently.ozone; //озон\n report.pressure = forecast.currently.pressure; //давление\n report.summary = forecast.currently.summary; //вывод(словами)\n report.windBearing = forecast.currently.windBearing; //направление ветра\n report.windSpeed = forecast.currently.windSpeed; //скорость ветра\n report.timezone = forecast.timezone; //где это\n\n // Сonvert degrees to celsius for general forecast report\n report.tempCelsius = fToC(report.tempFahrenheit);\n report.apparentTempCelsius = fToC(report.apparentTempFahrenheit);\n\n // Round temperature to the 1st sign after coma\n report.tempCelsius = roundPlus(report.tempCelsius, 1);\n report.apparentTempCelsius = roundPlus(report.apparentTempCelsius, 1);\n\n console.log(report);\n\t\t\n//\t\tvar date = new Date().toLocaleString('en-US', { timeZone: report.timezone });\n//\t\t\n//\t\tconsole.log(date);\n//\t\tvar night = date.getHours\n\t\t\n // Put values into the tooltip\n $('#temperature').html(report.tempCelsius + ' °C');\n $('#weather').html(report.summary);\n $('#weather_icon').css({backgroundPosition: `${chooseIcon(report.summary, NIGHTMODE)[0]}px ${chooseIcon(report.summary, NIGHTMODE)[1]}px`});\n $('#wind').html(windDirect(report.windBearing) + ' - '+ roundPlus(kmhToMs(mphToKmh(report.windSpeed)),1) + ' m/s');\n $('#pressure').html(roundPlus(hpaToMmhg(report.pressure),2) + ' mmHg');\n $('#humid').html(roundPlus(report.humidity*100,2) + '%');\n });\n}",
"_retrieveSunTimes(callback) {\n\t\tWeatherRecord.find({}, (err, doc) => {\n\t\t\tif (err) callback(err, null);\n\t\t\telse callback(null, doc.sun_times);\n\t\t});\n\t}",
"async function get() {\n const response = await fetch('https://worldtimeapi.org/api/timezone/' + valeur);\n let data = await response.json();\n let { datetime } = data;\n console.log(datetime);\n let horaire = datetime.substring(11, 19);\n //1 - Ecrire l'heure récupéré via l'API dans la zonne HH:MM:SS\n document.getElementById('horaire').innerText = horaire;\n\n temp(horaire);\n }",
"function getforecastDayWeather(city){\n // console.log(city);\n \n var queryUrl = \"https://api.openweathermap.org/data/2.5/forecast?appid=\" + appid + \"&units=imperial&q=\" + city; \n $.ajax({\n url: queryUrl,\n method: \"GET\"\n }).then(function(response){\n console.log(response);\n\n var filteredList = response.list.filter(function(date){\n return date.dt_txt.indexOf(\"15:00:00\") > -1;\n });\n console.log(filteredList);\n filteredList.forEach(function(date,i){\n $(\".day\" + (i+1)).find(\".date\").text(date.dt_txt.slice(0, date.dt_txt.indexOf(\" \")));\n $(\".day\" + (i+1)).find(\".icon\").attr(\"src\", weatherIcons + date.weather[0].icon + \".png\");\n $(\".day\" + (i+1)).find(\".temperature span\").text(date.main.temp);\n $(\".day\" + (i+1)).find(\".temperatureFeelLike span\").text(date.main.feels_like);\n $(\".day\" + (i+1)).find(\".humid span\").text(date.main.humidity);\n $(\".day\" + (i+1)).find(\".windSpeed span\").text(date.wind.speed);\n $(\".day\" + (i+1)).find(\".windDirection span\").text(date.wind.deg);\n \n });\n\n forecast.show();\n }).catch(function(err){\n console.log(\"Cant Find City\");\n });\n }",
"function getTimeData() {\n axios\n .get(worldTimeApiUrl)\n .then((response) => {\n const { data } = response\n\n const dt = DateTime.fromISO(data.datetime)\n\n updateTimeData(\n data.abbreviation,\n data.timezone,\n data.day_of_week,\n data.day_of_year,\n data.week_number,\n dt.toLocaleString(DateTime.TIME_24_SIMPLE)\n )\n\n if (dt.hour >= 0 && dt.hour < 5) {\n setDayOrNight('nighttime', 'Good evening')\n } else if (dt.hour >= 5 && dt.hour < 12) {\n setDayOrNight('daytime', 'Good morning')\n } else if (dt.hour >= 12 && dt.hour < 18) {\n setDayOrNight('daytime', 'Good afternoon')\n } else if (dt.hour >= 18) {\n setDayOrNight('nighttime', 'Good evening')\n }\n })\n .catch((err) =>\n console.error(\n `There was a problem retrieving data from ${worldTimeApiUrl}:`,\n err\n )\n )\n }",
"function displayCityData(beachLocation, depDate, returnDate, userAirportCode) {\n //Restaurant API\n var clientID = \"-_-qsu9VN_Mu1cRQ_CEfbA\"\n var apikey = \"eGyFYoGa3oYrHwELLpuXsE9A1l9W6d6AoJszCKMPa3M9SNgR2kx1md-nelFS1jJdfOb1sCD3knBmuWA7kDTZSoZMehkn0-Avx1VDY6QMhAX45RpIuKyxSBZ53eTsW3Yx\"\n var queryURL = \"https://developers.zomato.com/api/v2.1/locations?query=\" + beachLocation + \"&apikey=937d785cc1c1b2ac1098e43a13b9cf22\";\n\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n var entityID = response.location_suggestions[0].entity_id;\n var entityType = response.location_suggestions[0].entity_type;\n var locationDetailQueryURL = \"https://developers.zomato.com/api/v2.1/location_details?entity_id=\" + entityID + \"&entity_type=\" + entityType + \"&apikey=937d785cc1c1b2ac1098e43a13b9cf22\"\n\n $.ajax({\n url: locationDetailQueryURL,\n method: \"GET\"\n }).then(function (response) {\n var topRestaurant = response.best_rated_restaurant[0].restaurant.name;\n var topRestaurantURL = response.best_rated_restaurant[0].restaurant.url;\n var topRestaurantAddress = response.best_rated_restaurant[0].restaurant.location.address;\n var avgCostForTwo = response.best_rated_restaurant[0].restaurant.average_cost_for_two\n var restaurantID = response.best_rated_restaurant[0].restaurant.R.res_id;\n\n var restaurntDetailQueryURL = \"https://developers.zomato.com/api/v2.1/restaurant?res_id=\" + restaurantID + \"&apikey=937d785cc1c1b2ac1098e43a13b9cf22\"\n $.ajax({\n url: restaurntDetailQueryURL,\n method: \"GET\"\n }).then(function (response) {\n var restaurantLocation = response.location.address\n var avgCost = response.average_cost_for_two;\n var cuisines = response.cuisines;\n //Flight API\n $.ajax({\n url: \"https://api.sandbox.amadeus.com/v1.2/flights/low-fare-search?apikey=HEbMkphMv3ReciH7JfBcCzGQLfGG2UCk&origin=\" + userAirportCode + \"&destination=\" + selectedDestinationCode + \"&departure_date=\" + depDate + \"&return_date=\" + returnDate + \"&number_of_results=1\",\n method: \"GET\"\n }).then(function (response) {\n var flightPrice = response.results[0].fare.total_price;\n var departsAt = moment(response.results[0].itineraries[0].outbound.flights[0].departs_at).format(\"MM/DD/YYYY hh:mm a \");\n var arrivesAt = moment(response.results[0].itineraries[0].outbound.flights[(response.results[0].itineraries[0].outbound.flights.length - 1)].arrives_at).format(\"MM/DD/YYYY hh:mm a\");\n var duration = response.results[0].itineraries[0].outbound.duration;\n var airlineCode = response.results[0].itineraries[0].outbound.flights[0].operating_airline;\n var retDepartsAt = moment(response.results[0].itineraries[0].inbound.flights[0].departs_at).format(\"MM/DD/YYYY hh:mm a \");\n var retArrivesAt = moment(response.results[0].itineraries[0].inbound.flights[(response.results[0].itineraries[0].inbound.flights.length - 1)].arrives_at).format(\"MM/DD/YYYY hh:mm a\");\n var retDuration = response.results[0].itineraries[0].inbound.duration;\n var retAirlineCode = response.results[0].itineraries[0].inbound.flights[0].operating_airline;\n console.log(retDepartsAt, retAirlineCode, retArrivesAt, retDuration)\n $('.Cuisines').append(cuisines);\n $('.ResName').html(`<a href=\"${topRestaurantURL}\" target=\"blank\">${topRestaurant}</a>`)\n $('.ResforTwo').append(\"$\" + avgCostForTwo);\n $('.ResAddress').append(topRestaurantAddress);\n $(\".ArrivalAirport\").append(`<a href=\"https://en.wikipedia.org/wiki/List_of_airports_by_IATA_code:_A\" target=\"blank\">${selectedDestinationCode}</a>`)\n $(\".Airline\").append(`<a href=\"https://www.airfarewatchdog.com/airline-codes/\" target=\"blank\">${airlineCode}</a>`)\n $(\".FlightPrice\").append(\"$\" + flightPrice);\n $(\".LeaveDate\").append(departsAt);\n $(\".FlightArrival\").append(arrivesAt);\n $(\".Duration\").append(duration);\n $(\".retFlightPrice\").append(\"Above\");\n $(\".retArrivalAirport\").append(`<a href=\"https://en.wikipedia.org/wiki/List_of_airports_by_IATA_code:_A\" target=\"blank\">${userAirportCode}</a>`)\n $(\".retAirline\").append(`<a href=\"https://www.airfarewatchdog.com/airline-codes/\" target=\"blank\">${retAirlineCode}</a>`)\n $(\".retLeaveDate\").append(retDepartsAt);\n $(\".retFlightArrival\").append(retArrivesAt);\n $(\".retDuration\").append(retDuration);\n\n populateHotelData();\n }).catch(function (error) {\n $('td').empty();\n alert(error.responseJSON.message);\n $('td').empty();\n })\n })\n })\n\n //Hotel API --- NOT WORKING(AMADEUS SUPPORT WORKING ON ISSUE) REPLACEMENT BAND AID ABOVE\n // var hotelQueryURL = \"https://api.sandbox.amadeus.com/v1.2/hotels/search-airport/?apikey=KWxHu3JXbSfuZ0ZfU5AmxbNfkmVaKQTX&location=\" + selectedDestinationCode + \"&check_in=\" + depDate + \"&check_out=\" + returnDate;\n // var hotelQueryURL = \"https://api.sandbox.amadeus.com/v1.2/hotels/search-airport/?apikey=KWxHu3JXbSfuZ0ZfU5AmxbNfkmVaKQTX&location=\" + selectedDestinationCode + \"&check_in=2019-01-02&check_out=2019-01-09\"\n // $.ajax({\n // url: hotelQueryURL,\n // method: \"GET\"\n // }).then(function (response) {\n // console.log(JSON.stringify(response));\n // var hotelName = response.results[0].property_name;\n // var hotelPrice = response.results[0].total_price.amount;\n // var hotelStreet = response.results[0].address.line1;\n // var hotelCity = response.results[0].address.city;\n // var hotelState = response.results[0].address.region;\n // var hotelPostal = response.results[0].address.postal_code;\n // var fullAddress = hotelStreet + \"\" + hotelCity + \"\" + hotelState + \"\" + hotelPostal;\n // var roomType = response.results[0].rooms[0].room_type_info.room_type;\n\n // $(\".HoName\").append(hotelName);\n // $(\".HoPrice\").append(\"$\" + hotelPrice);\n // $(\".HoAddress\").append(fullAddress);\n // $(\".HoRoomType\").append(roomType);\n // })\n\n\n })\n}",
"function gotData(data) {\n\n weather = data;\n winDeg = weather.wind.deg;\n clouds = weather.clouds.all;\n mylatitude = weather.coord.lat;\n mylongitude = weather.coord.lon;\n\n\n //\n winSpe = (weather.wind.speed);\n //winSpe =7;\n //console.log(winSpe);\n winSpeline = (1/winSpe)*80;\n // console.log(winSpeline);\n\n\n loc = weather.name;\n time = weather.dt;\n\n\n var date = new Date(time * 1000);\n var timezone = weather.timezone;\n //var minutesshifttimeuser = (timezone/60);\n\n var utcstamp = Math.floor((new Date()).getTime() / 1000);\n var utcatlocation = utcstamp + timezone;\n dateObj = new Date(utcatlocation * 1000);\n utcString = dateObj.toUTCString();\n hourslice = (utcString.slice(-12, -10))*1;\n mydaynum = dateObj.getUTCDay();\n\n\n\n var daylist = { 0 : \"Sunday\",\n 1 : \"Monday\",\n 2 : \"Tuesday\",\n 3 : \"Wednesday\",\n 4 : \"Thursday\",\n 5 : \"Friday\",\n 6 : \"Saturday\",\n };\n\n\n\n//console.log(timezone);\n\n//console.log(utcatlocation);\n//console.log(utcString);\n console.log(hourslice);\n\n //var hours = date.getHours();\n //var minutes = date.getMinutes();\n\n\n feelslike = weather.main.feels_like;\n feelslikef = (feelslike-273.15)*1.8+32;\n feelslikec = (Math.round(feelslike-273.15));\n //feelslikecircle = Math.log2(feelslikec)*15;\n feelslikecircle = feelslikef*0.5;\n console.log('tempppppp in f ' + feelslikef);\n console.log('tempppppp in c ' + feelslikec);\n console.log('my latitude ' + mylatitude);\n console.log('my latitude ' + mylongitude);\n\n main = weather.weather[0].main;\n\n\n // console.log(weather.wind.deg);\n //console.log(weather.main.temp_min);\n // console.log(winDeg);\n\n //console.log(feelslikec);\n // console.log(loc);\n // console.log(main);\n //console.log(clouds);\n\n // console.log(cold(feelslikec));\n\n function mytime() {\n\n\n\n if (hourslice >= 0 && hourslice < 5){\n samay = 'mid-night';\n setGradient(d1, d2);\n }\n\n else if (hourslice >= 5 && hourslice < 7){\n samay = 'mid-night';\n setGradient(e1, e2);\n }\n\n else if (hourslice >= 7 && hourslice < 8){\n samay = 'early morning';\n setGradient(f1, f2);\n }\n\n else if (hourslice >= 8 && hourslice < 12) {\n samay = 'morning';\n setGradient(b1, b2);\n }\n\n else if (hourslice >= 12 && hourslice < 16) {\n samay = 'afternoon';\n setGradient(a1, a2);\n }\n\n else if (hourslice >= 16 && hourslice < 19) {\n samay = 'evening';\n setGradient(b1, b2);\n }\n\n else if (hourslice >= 19 && hourslice < 24) {\n samay = 'night';\n setGradient(c1,c2);\n }\n else {\n samay = 'not working';\n setGradient(b1,b2);\n }\n return samay;\n }\n\n\n\n mymonth = date.toLocaleString('default', { month: 'long' });\n\n\n\n fmonth = mymonth.toLowerCase();\n\n var message = 'As im writing you this ' + mymonth.toLowerCase() + ' ' + mytime() + '. The weather outside is ' + main + 'y, ' + cloudsfun(clouds)+ ' but it feels ' + cold(feelslikec);\n\n var footer= 'From somewhere around ' + loc + '.' ;\n\n\n push();\n translate(0,-100);\n rotate(winDeg);\n\n for(var x= -1000; x<6500; x=x+winSpeline) {\n\n\n push();\n strokeWeight(1);\n stroke(255,255,255, 80);\n\n blendMode(HARD_LIGHT);\n line(x,-1600,x,3200);\n pop()\n\n\n}\n\n pop();\n\n\n//return cloudcolor;\nfunction circlo() {\nif (hourslice>=7 && hourslice<19) {\n\n cicleincolor = '';\n}\n\nelse {\n cicleincolor = '255, 255, 255';\n}\n\nreturn cicleincolor;\n}\n\n\n\n\n\n\n\nif (hourslice>=8 && hourslice<=19) {\n push();\n noStroke();\n blendMode(SOFT_LIGHT);\n fill(0,clouds*0.09*255);\n circle(random(0,800),0, random(clouds*3,clouds*8));\n circle(0,random(0,480), random(clouds*3,clouds*8));\n circle(800,random(0,480), random(clouds*3,clouds*8));\n circle(random(0,800),480, random(clouds*3,clouds*8));\n pop();\n console.log('im putting black clouds');\n}\nelse {\n\n push();\n noStroke();\n blendMode(SOFT_LIGHT);\n fill(255,clouds*0.09*255);\n circle(random(0,800),0, random(clouds*3,clouds*8));\n circle(0,random(0,480), random(clouds*3,clouds*8));\n circle(800,random(0,480), random(clouds*3,clouds*8));\n circle(random(0,800),480, random(clouds*3,clouds*8));\n pop();\n console.log('im putting white clouds');\n}\n\n\n // for(var i=0+feelslikecircle/2; i <800; i=i+feelslikecircle) {\n //\n // for(var j=0+feelslikecircle/2; j<440; j=j+feelslikecircle) {\n //\n\n\n for(var i=40; i <800; i=i+80) {\n\n for(var j=40; j<480; j=j+80) {\n\n\n\n\n //\n // push();\n // noStroke();\n // fill(255,0,255);\n // circle(i*1.7,j*1.7,feelslikecircle);\n // pop()\n //\n // push();\n // translate(i*1.7,j*1.7);\n // fill(255,226,0);\n // noStroke();\n // rotate(winDeg);\n // rectMode(CENTER);\n // // rect(feelslikecircle/9, feelslikecircle/9, random(feelslikecircle/2, feelslikecircle/5), feelslikecircle, feelslikecircle/4);\n // rect(feelslikecircle/9, feelslikecircle/9, random(feelslikecircle/2, feelslikecircle/5), feelslikecircle*1.2, feelslikecircle/4);\n // pop();\n //\n // push();\n // translate(i*1.7,j*1.7);\n // blendMode(MULTIPLY);\n // rotate(winDeg);\n // noStroke();\n // fill(0, 50);\n // circle(feelslikecircle/9,feelslikecircle/2*0.7,feelslikecircle/6);\n\n // pop();\n\n\n push();\n noStroke();\n fill(255,0,255);\n circle(i,j,feelslikecircle);\n pop()\n\n push();\n translate(i,j);\n fill(255,226,0);\n noStroke();\n rotate(winDeg);\n rectMode(CENTER);\n // rect(feelslikecircle/9, feelslikecircle/9, random(feelslikecircle/2, feelslikecircle/5), feelslikecircle, feelslikecircle/4);\n rect(0, 0, random(feelslikecircle/2, feelslikecircle/5), feelslikecircle*1.2, feelslikecircle/4);\n pop();\n\n push();\n translate(i,j);\n blendMode(MULTIPLY);\n rotate(winDeg);\n noStroke();\n fill(0, 50);\n circle(0,feelslikecircle/2*0.7,feelslikecircle/6);\n\n pop();\n }\n }\n\n\n angleMode(DEGREES);\n // fill('white');\n //\n // textSize(36);\n // stroke(100);\n // textStyle(BOLD);\n // textLeading(38);\n // text(message, 15, 15, 400, 600);\n // textSize(18);\n // textStyle(BOLD);\n // text(footer, 15, 300, 400, 600);\n\n\n console.log(message)\n console.log(footer);\n //console.log(winSpe);\n\n\n\n\n\n var lexicon = new RiLexicon();\n\n\n weather = ['cloudy', 'Hazy', 'Rainy', 'Cleary', 'Sonwy', 'smokey'];\n daytime = ['morning', 'afternoon', 'evening', 'night'];\n months = ['January', 'April', 'December', 'July', 'September'];\n temp = ['Hot', 'Cold', 'great', 'warm', 'freezing cold'];\n clouds = ['clear', 'cloudy', 'dark and cloudy', 'scattered clouds', 'a bit cloudy'];\n test = ['December', 'september'];\n //mymonth = ['December', 'september'];\n mylocation = ['Hyderabad', 'Bengaluru'];\n hrsfromsun = ['sunset is far', 'sunset is here', 'sunset is near'];\n // myday = ['sunday', 'monday'];\n\n fweather = main + 'y';\n fdaytime = samay;\n\n fmyday = daylist[mydaynum];\n console.log(fmyday);\n ftemp = random(temp);\n // fclouds = random(clouds);\n fclouds = cloudcover;\n\n fmylocation = loc;\n fhrsfromsun = random(hrsfromsun);\n\n\n\n lexsenA = lexicon.randomWord('jj') +' ' + lexicon.randomWord('nn') + ' ' +lexicon.randomWord('md') + ' ' + lexicon.randomWord('vbp');\n lexsenB = lexicon.randomWord('cd') + ' ' + lexicon.randomWord('jj') + ' ' + lexicon.randomWord('nns');\n lexsenC = lexicon.randomWord('nn') + ' ' + lexicon.randomWord('md') + ' ' + lexicon.randomWord('rb') + ' ' + lexicon.randomWord('vb');\n lexsenD = lexicon.randomWord('jj') + ' ' + lexicon.randomWord('md') + ' ' + lexicon.randomWord('vbp');\n lexsenE = lexicon.randomWord('jjs') + ' ' + lexicon.randomWord('md') + ' ' + lexicon.randomWord('rbs');\n lexsenF = lexicon.randomWord('dt') + ' ' + lexicon.randomWord('jj') + ' ' + lexicon.randomWord('vbn');\n lexsenG = lexicon.randomWord('jj') + ' ' + lexicon.randomWord('vbn') + ' ' + lexicon.randomWord('jj');\n lexsenH = lexicon.randomWord('dt') + ' ' + lexicon.randomWord('vb') + ' ' + lexicon.randomWord('rb');\n lexsenI = lexicon.randomWord('nn') + ' ' + lexicon.randomWord('vbp') + ' ' + lexicon.randomWord('nns');\n lexsenJ = lexicon.randomWord('nn') + ' ' + lexicon.randomWord('md') + ' ' + lexicon.randomWord('rb') + ' ' + lexicon.randomWord('vb');\n lexsenK = lexicon.randomWord('md') + ' ' + lexicon.randomWord('vb') + ' ' + lexicon.randomWord('rb');\n\n\n console.log(lexsenA);\n console.log(lexsenB);\n console.log(lexsenC);\n console.log(lexsenD);\n console.log(lexsenE);\n console.log(lexsenF);\n console.log(lexsenG);\n console.log(lexsenH);\n console.log(lexsenJ);\n console.log(lexsenK);\n\n\n var sen1 = [\"At \"+ fmylocation, \"Its \" + fmyday, \"A \" +fweather+\" morning\", fmylocation + \" postcards\", fdaytime + \" is falling\", fdaytime + \" stillness\", fmyday + ' ' + fdaytime, fdaytime + \" Traffic\", \"A \" + fweather + ' ' + fmyday + ' '+ fdaytime];\n var sen2 = [\"A frog jumps\", \"Donkeys flank\", \"The worm wiggles\", \"A parrot asks \" + lexicon.randomWord('rb'), \"The oceans loud\", \"A cat watches traffic\", \"A cat watches \" + fdaytime + \" traffic\", \"A cat watches \" + fmonth + \" traffic\", \"The parrot sings \" + lexicon.randomWord('rb'), \"Two butterflies warm the road\", \"Spider webs and plastic bags\", \"Someone is upset\", \"Empty bottle \" + lexicon.randomWord('vbz') +' ' + lexicon.randomWord('rb'), \"A loudspeaker barks\", \"A frog jumps\", \"Leaves tremble\", \"A silkworm spinning\", \"A worm digs silently still\", \"A fly crosses the street\", \"Traffic light turn green\", \"A sparrow bathes\", \"The sunflower drips\", \"A sparrow takes a dust bath\", \"A sparrow chips\",\"Road and sky align\", \"A butterfly trapped\", \"An ant climbs\", \"The birds cry\", \"Bullfrogs croak\", \"A cow stares the road\", \"Buzzards wait\", \"Leaves fall\", \"Dead batteries\", \"The cat watches\", \"Who cares how stocks did\", \"Butterfly wings clap\" , \"my shadow grows\", \"my shadow grows \" + lexicon.randomWord('rb'), \"Obama is busy\", fdaytime + \" is falling\" ];\n\n var senb2 = [\"At \"+ fweather, \"A \" +fweather + ' ' + fdaytime, fdaytime + \" stillness\", fmyday + \" \" + fdaytime, fweather + ' ' + fmyday + ' ' + fdaytime];\n var senc1 = [\"At \"+ fmylocation, \"Its \" + fmonth, \"A \" + fweather + ' '+ fmonth, fmonth +\" postcards \", fmonth +\" stillness\", fmonth + \" \" + fdaytime, fmyday + ' ' + fmonth + \" Traffic\", \"A \" + fweather + ' ' + fmyday + ' ' + fdaytime ];\n var senc3 = [fdaytime + \" passes in \" + fmylocation , \"A sunflower drips at \" + fmylocation , \"A bus passes by in \" + fmylocation , \"Another \" + fdaytime +\" is falling\", \"A sparrow chips \" + fmylocation ];\n\n\n\n\n rg = new RiGrammar();\n rg.addRule(\"<start>\",\" % <line-a1> % <line-a2> % <line-a3> | % <line-b1> % <line-b2> % <line-b3> | % <line-c1> % <line-c2> % <line-c3> | % <line-d1> % <line-d2> % <line-d3> | % <line-e1> % <line-e2> % <line-e3> \" , 1);\n\n\n rg.addRule(\"<line-a1>\",RiTa.randomItem(sen1), 1);\n rg.addRule(\"<line-a2>\",RiTa.randomItem(sen2), 1);\n rg.addRule(\"<line-a3>\",lexsenG + ' | '+ lexsenF, 1);\n\n rg.addRule(\"<line-b1>\",RiTa.randomItem(sen2), 1);\n rg.addRule(\"<line-b2>\",RiTa.randomItem(senb2), 1);\n rg.addRule(\"<line-b3>\",lexsenI, 1);\n\n rg.addRule(\"<line-c1>\",RiTa.randomItem(senc1), 1);\n rg.addRule(\"<line-c2>\",RiTa.randomItem(sen2), 1);\n rg.addRule(\"<line-c3>\",RiTa.randomItem(senc3), 1);\n\n rg.addRule(\"<line-d1>\",lexsenJ, 1);\n rg.addRule(\"<line-d2>\",RiTa.randomItem(sen2), 1);\n rg.addRule(\"<line-d3>\",RiTa.randomItem(sen1), 1);\n\n rg.addRule(\"<line-e1>\", RiTa.randomItem(senc1), 1);\n rg.addRule(\"<line-e2>\",lexsenK, 1);\n rg.addRule(\"<line-e3>\",RiTa.randomItem(sen2), 1);\n\n\n rg2 = new RiGrammar();\n rg2.addRule(\"<word-5>\", \" Good \" + fdaytime + \" from \" + \"<locationdeg>\" + \" | \" + \" Somewhere around \" + \"<locationdeg>\" + \" | \" + \"<locationdeg>\" + \" Says hi\" + \" | \" + \" Wishes from \" + \"<locationdeg>\" + \" | \" + \" with love from \" + \"<locationdeg>\" , 1);\n\nrg2.addRule(\"<locationdeg>\", mylatitude +', ' + mylongitude +\" | \" + fmylocation)\n\n\n\n\n var expanded = rg.expand();\n console.log(expanded);\n\n\n\n var haiku = expanded.split(\"%\");\n // haikuupper2 = haiku[0].toUpperCase() +\n // haiku.slice(1);\n\n for (let i = 0; i < haiku.length; i++) {\n\n console.log(haiku[i]);\n\n\n\n\n fill('white');\n\n textSize(36);\n stroke(100);\n textStyle(BOLD);\n textLeading(38);\n stroke(0);\n strokeWeight(1);\n // noStroke();\n text(haiku[i], 10, 160+(40*i));\n\n }\n\n push();\n translate(780,470);\n rotate(90);\n\n textSize(12);\n stroke(100);\n textStyle(BOLD);\n textAlign(RIGHT);\n\n\n rg2.addRule(\"<start>\",\"<word-5>\", 1);\n endstatement = rg2.expand();\n\n rs = new RiString(endstatement);\n\n\n text(rs.toUpperCase(), 0, 0);\n console.log(endstatement);\n pop();\n\n\n//\n// save(cnv, 'myCanvas.jpg');\n//\n }",
"function getAllWeather(zips, callback){\n // CONCAT 1 - GET WEATHER FOR ONE ZIP\n var getWeather = function(zip, callback){\n var url = \"http://api.wunderground.com/api/\"+process.env.WEATHER_APP_KEY+\"/forecast10day/q/zmw:\"+zip+\".json\";\n request.get(url, function(error, response, body){\n var singleWeather = JSON.parse(body);\n weather[zip] = singleWeather;\n callback(null, singleWeather);\n });\n };\n\n // CONCAT FOR GETTING WEATHER FOR ALL ZIPS USING GET WEATHER FOR ONE\n async.concat(zips, getWeather, function(err, results){\n callback(null, zips);\n });\n\n }",
"function queryTravelTime () {\n return Promise.all([request(urlToWork, { json: true }), request(urlFromWork, { json: true })])\n .then(resArray => {\n let [toWork, fromWork] = resArray.map(res => res.rows[0].elements[0].duration_in_traffic.value)\n return { toWork, fromWork }\n })\n }"
]
| [
"0.6899908",
"0.6882605",
"0.6534397",
"0.63125616",
"0.6287536",
"0.61826557",
"0.61163193",
"0.60600704",
"0.6045612",
"0.60342085",
"0.6034115",
"0.6025975",
"0.6017806",
"0.60151064",
"0.5990498",
"0.598306",
"0.5975896",
"0.5961549",
"0.5955626",
"0.59231037",
"0.5912302",
"0.588918",
"0.58857524",
"0.5850027",
"0.5849856",
"0.5835182",
"0.5812665",
"0.5806331",
"0.5803309",
"0.58031815"
]
| 0.689791 | 1 |
ProcessState is responsible for keeping process related state. Certain probes are regularly updating the state. | function ProcessState(agent) {
this.agent = agent;
this.bytesRead = 0;
this.bytesWritten = 0;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"process() {\r\n //stateAttributes must have been set by call to computeScalarStates\r\n this.attributes = this.state.devState.stateAttributes.split(\",\");\r\n this.savedAttributes = this.getLocalAttribute(\"savedAttributes\");\r\n if (!this.savedAttributes) this.savedAttributes = [];\r\n if (!this.state.devState.restoreState) return;\r\n if (!this.state.reloadLocal) return;\r\n this.savedAttributes.forEach(attr => {\r\n let value = (this.state[attr] = this.getLocalAttribute(attr));\r\n\r\n if (this.state.devState.logDiags.restore)\r\n console.log(\"Restoring \", attr, value);\r\n }); // await actions.restoreSavedAttrs();\r\n // this.restoreSavedAttrs();\r\n }",
"function InternalBreakpointState() { }",
"changeState(state) {\r\n if(!this.states.hasOwnProperty(state)) {\r\n return Err;\r\n }\r\n this.currentState = state;\r\n this.history = [...this.history,state];\r\n this.count += 1;\r\n }",
"function setState(value) {\n var prom;\n if (!value || typeof value !== 'object') {\n throw new Error('supplied state MUST be an object');\n }\n internal.loader.cache().setState(value);\n internal.loader.setState(value);\n prom = []; //To store promises\n internal.disableEnsurePadding = true;\n //Note: Filter must be done first as it clears data and\n // sets index to null when changed\n if (value.hasOwnProperty('filter')) {\n self.setFilter(value.filter);\n }\n if (value.hasOwnProperty('index')) {\n self.setIndex(value.index);\n }\n if (value.hasOwnProperty('maxPages')) {\n self.setMaxPages(value.maxPages);\n }\n if (value.hasOwnProperty('padLow')) {\n self.setPadLow(value.padLow);\n }\n //Re-enable before the pad high call so ensurePadding is called internally.\n if (value.hasOwnProperty('padHigh')) {\n self.setPadHigh(value.padHigh);\n }\n internal.disableEnsurePadding = false;\n if (value.hasOwnProperty('countMode')) {\n self.setCountMode(value.countMode);\n }\n\n prom = ensurePadding();\n prom = prom.exec;\n return prom;\n }",
"function StateModule() {\n \n var state = {};\n\n function logState(){\n console.log(state);\n }\n\n function getState(){\n return state;\n }\n\n function setState(key,value) { // making all state properties arrays so that previous value is held on to\n // current state to be accessed as state[key][0].\n if ( state[key] === undefined ) {\n state[key] = [value];\n PubSub.publish(key, value);\n console.log('STATE CHANGE', key, value);\n } else if ( state[key][0] !== value ) {\n state[key].unshift(value);\n PubSub.publish(key, value);\n console.log('STATE CHANGE', key, value);\n if ( state[key].length > 2 ) {\n state[key].length = 2;\n }\n }\n \n }\n return {\n logState: logState,\n getState: getState,\n setState: setState\n }\n}",
"function InstructionState() { }",
"function InstructionState() { }",
"function InstructionState() { }",
"function saveState(state) {\n assign(stateCache, state);\n}",
"setState(state) {\n this.currentState = state;\n }",
"change_state(new_state) {\n this.current_state = new_state;\n }",
"changeState(state) {\n if (this.states.hasOwnProperty(state) === false) throw new Error(\"There is no such state in FSM!\");\n this.history.push(this.activeState);\n this.activeState = state;\n this.undoHistory.clear();\n }",
"function InstructionState() {}",
"function InstructionState() {}",
"function setState(new_state)\n{\n\tstate = new_state;\n}",
"produce() { this.state += 1; }",
"function State(env, prog) {\n this.env = env;\n this.stack = [];\n this.prog = prog;\n \n switch (env) {\n case 'glyf':\n this.zp0 = this.zp1 = this.zp2 = 1;\n this.rp0 = this.rp1 = this.rp2 = 0;\n /* fall through */\n case 'prep':\n this.fv = this.pv = this.dpv = xUnitVector;\n this.round = roundToGrid;\n }\n }",
"function State(\n env,\n prog\n ) {\n this.env = env;\n this.stack = [];\n this.prog = prog;\n switch (env) {\n case \"glyf\":\n this.zp0 = this.zp1 = this.zp2 = 1;\n this.rp0 = this.rp1 = this.rp2 = 0;\n /* fall through */ case \"prep\":\n this.fv = this.pv = this.dpv = xUnitVector;\n this.round = roundToGrid;\n }\n }",
"function applicationStateCheckpoint() {\n //TODO: Save State\n }",
"function State(env, prog) {\n this.env = env;\n this.stack = [];\n this.prog = prog;\n\n switch (env) {\n case 'glyf':\n this.zp0 = this.zp1 = this.zp2 = 1;\n this.rp0 = this.rp1 = this.rp2 = 0;\n /* fall through */\n case 'prep':\n this.fv = this.pv = this.dpv = xUnitVector;\n this.round = roundToGrid;\n }\n }",
"apply_state(state) {\n let old_state = this.state;\n this.state = state;\n return old_state;\n }",
"changeState(state) {\r\n var exception = 0;\r\n for (var keys in this.states) {\r\n if (keys == state){\r\n this.current = state;\r\n\t\t\t\tthis.history[this.historyCounter + 1] = state;\r\n this.historyCounter++;\r\n exception = 1;\r\n break;\r\n }\r\n }\r\n if (exception == 0){\r\n throw new exception(\"An exception occurs: Incorrent input data\");\r\n }\r\n }",
"function State(env, prog) {\n this.env = env;\n this.stack = [];\n this.prog = prog;\n\n switch (env) {\n case 'glyf':\n this.zp0 = this.zp1 = this.zp2 = 1;\n this.rp0 = this.rp1 = this.rp2 = 0;\n\n /* fall through */\n\n case 'prep':\n this.fv = this.pv = this.dpv = xUnitVector;\n this.round = roundToGrid;\n }\n}",
"function State(env, prog) {\n\t this.env = env;\n\t this.stack = [];\n\t this.prog = prog;\n\n\t switch (env) {\n\t case 'glyf' :\n\t this.zp0 = this.zp1 = this.zp2 = 1;\n\t this.rp0 = this.rp1 = this.rp2 = 0;\n\t /* fall through */\n\t case 'prep' :\n\t this.fv = this.pv = this.dpv = xUnitVector;\n\t this.round = roundToGrid;\n\t }\n\t}",
"changeState(state) {\r\n const isStateExists = this.currentConfig.states[state]; \r\n (isStateExists) ? (this.back.push(this.currentState = state), this.forward = []) : (throws.stateIsMissing()); \r\n }",
"function getState() {\n\t\treturn currentState;\n\t}",
"function getState() {\r\n return currentState;\r\n }",
"function State(env, prog) {\n this.env = env;\n this.stack = [];\n this.prog = prog;\n\n switch (env) {\n case 'glyf' :\n this.zp0 = this.zp1 = this.zp2 = 1;\n this.rp0 = this.rp1 = this.rp2 = 0;\n /* fall through */\n case 'prep' :\n this.fv = this.pv = this.dpv = xUnitVector;\n this.round = roundToGrid;\n }\n}",
"function State(env, prog) {\n this.env = env;\n this.stack = [];\n this.prog = prog;\n\n switch (env) {\n case 'glyf' :\n this.zp0 = this.zp1 = this.zp2 = 1;\n this.rp0 = this.rp1 = this.rp2 = 0;\n /* fall through */\n case 'prep' :\n this.fv = this.pv = this.dpv = xUnitVector;\n this.round = roundToGrid;\n }\n}",
"function State(env, prog) {\n this.env = env;\n this.stack = [];\n this.prog = prog;\n\n switch (env) {\n case 'glyf' :\n this.zp0 = this.zp1 = this.zp2 = 1;\n this.rp0 = this.rp1 = this.rp2 = 0;\n /* fall through */\n case 'prep' :\n this.fv = this.pv = this.dpv = xUnitVector;\n this.round = roundToGrid;\n }\n}"
]
| [
"0.59684765",
"0.580765",
"0.57068855",
"0.5695865",
"0.56459796",
"0.5558699",
"0.5558699",
"0.5558699",
"0.55393535",
"0.54576117",
"0.5454095",
"0.54407346",
"0.54221845",
"0.54221845",
"0.5394893",
"0.5385489",
"0.53741056",
"0.5362265",
"0.5334524",
"0.53296536",
"0.53253955",
"0.5325374",
"0.5319709",
"0.5317105",
"0.5311449",
"0.53016573",
"0.5299187",
"0.5286444",
"0.5286444",
"0.5286444"
]
| 0.73499566 | 0 |
Get the component with specified class and base name | getComponent(klass, baseName) {
const component = _.find(this.components, (c) => {
return (c instanceof klass) && c.baseName == baseName;
})
return component;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"getComponent(name){\n\t\tfor(let component of this.components){\n\t\t\tif(component.constructor.name == name)\n\t\t\t\treturn component;\n\t\t}\n\t\t//If we didn't find it, search any children we have\n\t\tfor(let child of this.children){\n\t\t\tlet component = child.getComponent(name);\n\t\t\tif(component) return component;\n\t\t}\n\t}",
"function getComponentByName(name) {\n var i,\n component = that.cp;\n\n if (name.indexOf(\".\") > -1) {\n name = name.split(\".\");\n for (i = 0; i < name.length; i++) {\n if (!component) {\n break;\n }\n component = component[name[i]];\n }\n } else {\n component = component[name];\n }\n\n return component;\n }",
"find(className) {\n let component = null;\n this.components.each((c) => {\n if (c instanceof className) {\n component = c;\n return false;\n }\n });\n return component;\n }",
"getComponent(name) {\n return (this._nextDict[name] || [undefined])[0];\n }",
"getclassname() {\n return \"Component\";\n }",
"function getBobrilComponent( name, $injector ) {\n // if name is a function assume it is component and return it\n if (angular.isFunction(name)) {\n return name;\n }\n\n // a Bobril component name must be specified\n if (!name) {\n throw new Error('BobrilComponent name attribute must be specified');\n }\n\n // ensure the specified Bobril component is accessible, and fail fast if it's not\n var bobrilComponent;\n try {\n bobrilComponent = $injector.get(name);\n } catch(e) { }\n\n if (!bobrilComponent) {\n try {\n bobrilComponent = name.split('.').reduce(function(current, namePart) {\n return current[namePart];\n }, window);\n } catch (e) { }\n }\n\n if (!bobrilComponent) {\n throw Error('Cannot find bobril component ' + name);\n }\n\n return bobrilComponent;\n }",
"getSpecificType() {\r\n var isComponent = this.hasTag('component');\r\n if (isComponent) {\r\n return this.isAbstract ? 'abstract-component': 'component'\r\n } else {\r\n return super.getSpecificType()\r\n }\r\n }",
"guessComponent (): ?Object {\n const registeredComponents = this.component.components\n if (!registeredComponents) {\n return null\n }\n const name = this.guessComponentName()\n return Object.values(registeredComponents)\n .find(component => {\n return component.name === name\n }) || null\n }",
"function getComponent(elem, comp) {\n var instance;\n var i;\n var ele = typeof elem === 'string' ? document.getElementById(elem) : elem;\n for (i = 0; i < ele.ej2_instances.length; i++) {\n instance = ele.ej2_instances[i];\n if (typeof comp === 'string') {\n var compName = instance.getModuleName();\n if (comp === compName) {\n return instance;\n }\n }\n else {\n // tslint:disable-next-line:no-any\n if (instance instanceof comp) {\n return instance;\n }\n }\n }\n return undefined;\n}",
"getComponent(type) {\n for (let c of this.components) {\n if (c instanceof type) {\n return c;\n }\n }\n\n return null;\n }",
"get baseName() {\n return Component.getName(this.baseQName);\n }",
"get _componentName() {\n return this.constructor._componentName || getConstructorName(this.constructor);\n }",
"function BaseComponent() {\n return Reflect.construct(HTMLElement, [], new.target);\n }",
"get componentInstance() {\n const nativeElement = this.nativeNode;\n return nativeElement &&\n (getComponent(nativeElement) || getOwningComponent(nativeElement));\n }",
"static get Component() {\n return Component;\n }",
"getComponentConstructorForType(type) {\n if (typeof type === \"function\") return type;\n\n let component = type;\n if (this.controller) {\n component = this.controller.getComponentConstructorForType(type);\n }\n if (!component) {\n console.warn(`${this}.getComponentConstructorForType(${type}): cant find component, returning <Stub/>`);\n component = Stub;\n }\n return component;\n }",
"getComponent() {\r\n return this._comp\r\n }",
"function getWidgetComponent(type) {\n var widgets = require('../widgets');\n return widgets.getWidgetComponent(type);\n}",
"function getComponentDef(type) {\n return type[NG_COMPONENT_DEF] || null;\n}",
"function getComponentDef(type) {\n return type[NG_COMPONENT_DEF] || null;\n}",
"function getComponentDef(type) {\n return type[NG_COMPONENT_DEF] || null;\n}",
"getSelectionComponent(variableName, origName) {\n let sel = this.component.selection[variableName];\n\n if (!sel && this.parent) {\n sel = this.parent.getSelectionComponent(variableName, origName);\n }\n\n if (!sel) {\n throw new Error(log.message.selectionNotFound(origName));\n }\n\n return sel;\n }",
"function extractComponent(node: ShallowWrapper): string {\n if (node.hasClass('module-workload-component')) {\n return extractComponent(node.find('h5').first());\n }\n\n if (node.hasClass('module-workload-blocks')) {\n return extractComponent(node.children().first());\n }\n\n const match = node.get(0).props.className.match(/workload-([^-]+)/);\n return _.capitalize(match[1]);\n}",
"activeComponent(){\n if(this.state.data.editor){\n return this.formComponent()\n }else{\n return(this.listComponent())\n }\n }",
"function UnknownComponent() {}",
"function DOM$ComponentByElement(element) {\n var component = element.$xui;\n while (!component) {\n element = element.parentNode;\n if (!element) return null;\n component = element.$xui;\n }\n return component;\n}",
"function getComponentDef(type) {\n return type[NG_COMP_DEF] || null;\n}",
"function getComponentDef(type) {\n return type[NG_COMP_DEF] || null;\n}",
"function getComponentDef(type) {\n return type[NG_COMP_DEF] || null;\n}",
"function getComponentDef(type) {\n return type[NG_COMP_DEF] || null;\n}"
]
| [
"0.71207714",
"0.67850626",
"0.66684514",
"0.6628898",
"0.63930124",
"0.6344684",
"0.6259778",
"0.6195836",
"0.6188117",
"0.61708695",
"0.5992314",
"0.5922367",
"0.59094685",
"0.58856493",
"0.5830801",
"0.5730385",
"0.566933",
"0.5600672",
"0.55656266",
"0.55656266",
"0.55656266",
"0.55315435",
"0.55228287",
"0.5515876",
"0.54773694",
"0.5444872",
"0.5417493",
"0.5417493",
"0.5417493",
"0.5417493"
]
| 0.8546157 | 0 |
eg: The Stanton measure of [1, 4, 3, 2, 1, 2, 3, 2] is 3 because 1 occurs 2 times in the array and 2 occurs 3 times. Write a function stantonMeasure/StantonMeasure which takes an integer array and returns its Stanton measure. / function: stantonMeasure input: integer array output: stanton measure of the array | function stantonMeasure(arr){
var number = 0;
var answer = 0;
for (var i = 0; i < arr.length; i++){
if(arr[i] === 1 ){
number ++;
}
}
for(var j = 0; j < arr.length; j++){
if(arr[j] === number){
answer ++;
}
}
return answer;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function stantonMeasure(arr) {\n let n = arr.filter(a=>a===1).length;\n return arr.filter(a=>a===n).length;\n}",
"function stantonMeasure(arr) {\n return arr.filter(a=>a===arr.filter(a=>a===1).length).length;\n}",
"function stanDeviate(arr){\n var meanOfOrg = (arr.reduce(function(l,r){return l+r;}))/arr.length;\n var theSqrdSet = arr.map(function(el){ return Math.pow((el - meanOfOrg),2)});\n var theResult = Math.sqrt((theSqrdSet.reduce(function(l,r){return l+r;}))/theSqrdSet.length);\n return theResult;\n}",
"function findTwins(arr) {\n let freqCount = arr.reduce((acc,val) => {acc[val] = acc[val]+1 || 1; return acc},{});\n for (let key in freqCount) {\n if(freqCount[key] > 1) return Number(key); \n }\n return null;\n}",
"function countMean(array) {\n if (!array.length) throw new Error('Provided empty array')\n\n let sum = 0\n array.forEach(item => sum += item)\n\n return sum / array.length\n}",
"function getStandardDeviation (array) {\n const n = array.length\n const mean = array.reduce((a, b) => a + b) / n\n return Math.sqrt(array.map(x => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n)\n }",
"function stdevp(arr) {\n let mean = _.mean(arr);\n return Math.sqrt(_.sumBy(arr, function (x) {\n return (x - mean) ** 2\n }) / (arr.length - 1));\n }",
"function countsMiddleElement(array) {\n var result;\n result = Math.round(array.length / 2);\n return result;\n}",
"function mean(array) {\n let dataArr = 0;\n let hasil = 0;\n for(let i=0; i<array.length; i++){\n dataArr+= array[i]\n }\n hasil = Math.round(dataArr/array.length)\n return hasil\n}",
"function singles(arr) {\n if (arr === undefined) throw new Error(\"array is required\");\n let difference = 0;\n let result = 0;\n const noDuplicatesArray = Array.from(new Set(arr));\n\n const noDuplicatesArraySum = noDuplicatesArray.reduce(function (\n accumulator,\n currentValue\n ) {\n return accumulator + currentValue;\n },\n 0);\n\n const arraySum = arr.reduce(function (accumulator, currentValue) {\n return accumulator + currentValue;\n }, 0);\n\n if (arraySum > noDuplicatesArraySum) {\n difference = arraySum - noDuplicatesArraySum;\n result = arraySum - difference * 2;\n } else {\n result = arraySum;\n }\n return result;\n}",
"function getMean(array) {\n var sum = 0;\n array.forEach(num => {\n sum += num;\n });\n var mean = sum / array.length;\n return mean;\n}",
"function getFrequency(arr) {\n // Your code goes here ...\n}",
"function mean(array) {\n function plus(a, b) { return a + b; }\n return array.reduce(plus) / array.length;\n}",
"function mean(array){\n return console.log(array.reduce(function(a, b) {\n return a + b;\n }) / array.length);\n}",
"function mean(array){\n return console.log(array.reduce(function(a, b) {\n return a + b;\n }) / array.length);\n}",
"function mean(array){\n return sum(array)/array.length;\n}",
"function count(test, array) {\n return array.reduce(function(total, item) {\n return total + (test(item) ? 1 : 0);\n }, 0);\n }",
"function mean(array) {\nvar total = 0;\n total += array[i];\n}",
"function maleCount(array){\n\n}",
"function s(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}",
"function s(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}",
"function mean(array) {\n return sum(array)/array.length;\n}",
"function mean(array) {\n return sum(array) / array.length;\n}",
"function mean(array) {\n return sum(array) / array.length;\n}",
"function femaleCount(array){\n\n}",
"function getMean (array) {\n let mean = array.reduce((agg, x) => (agg + x), 0)/ array.length\n return mean\n}",
"function skewness(arr){\r\n let skewness;\r\n var total = 0;\r\n for(let i=0; i<arr.length; i++)total += (arr[i] - mean(arr))**3;\r\n skewness = total/((arr.length-1)*standardDev(arr)**(3/2));\r\n return skewness;\r\n}",
"function mean(array) {\n\treturn sum(array) / array.length;\n}",
"function averages(array){\n\tvar newArray = 0;\n\tfor (var i = 0; i < array.length; i++) {\n\t\tnewArray = newArray + array[i]\t\n\t}\n\treturn Math.floor(newArray/array.length)\n}",
"function timeMeasure(arrayOfArrays){\n var size = arrayOfArrays.length; // For use in for loop and average time\n var sum = 0; // sum of all the times\n for(var i = 0; i < size; i++){\n var timeStart = new Date().getTime();\n\n // Start of function to be time measured\n\n threeSumCount(arrayOfArrays[i]);\n\n // End of function to be time measured\n\n var timeEnd = new Date().getTime();\n sum += timeEnd - timeStart; // adds run time to sum\n }\n\n return sum / size;\n}"
]
| [
"0.7704051",
"0.7616463",
"0.6020489",
"0.59281343",
"0.5906624",
"0.5889507",
"0.58173496",
"0.5742107",
"0.56053865",
"0.55331486",
"0.5498617",
"0.5455393",
"0.5447202",
"0.5439379",
"0.5439379",
"0.54257333",
"0.5414083",
"0.5384884",
"0.538185",
"0.5375504",
"0.5375504",
"0.53538483",
"0.5352332",
"0.5352332",
"0.5326667",
"0.53264064",
"0.53227556",
"0.53078276",
"0.5301473",
"0.52898914"
]
| 0.7958783 | 0 |
still working on it.... dont worry about this one... remove the polling intervals on a given i2cQueue | function clearPolls(i2cQueue) {
console.log('in clear polls for bus: '+i2cQueue.getBusNumber());
console.log('current active interval ids: ', Object.keys(_pollIds));
for (var intervalId in _pollIds) {
if (_pollIds[intervalId] === i2cQueue.getBusNumber()) {
console.log('clear hit');
clearInterval(intervalId);
delete _pollIds[intervalId];
}
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"clearOutQueue() {\n if (this.queue == null) {\n clearInterval(this.intervalHandler);\n } else if (this.queue.expectedAt < Date.now()) {\n let temp = this.queue;\n this.queue = temp.next;\n temp.next = null;\n this.count--;\n }\n }",
"_clean () {\n const queues = Object.values(this._queues)\n queues.forEach(dialQueue => {\n // Clear if the queue has reached max denylist\n if (dialQueue.denylisted === Infinity) {\n dialQueue.abort()\n delete this._queues[dialQueue.id]\n return\n }\n\n // Keep track of denylisted queues\n if (dialQueue.denylisted) return\n\n // Clear if peer is no longer active\n // To avoid reallocating memory, dont delete queues of\n // connected peers, as these are highly likely to leverage the\n // queues in the immediate term\n if (!dialQueue.isRunning && dialQueue.length < 1) {\n let isConnected = false\n try {\n const peerInfo = this.switch._peerBook.get(dialQueue.id)\n isConnected = Boolean(peerInfo.isConnected())\n } catch (_) {\n // If we get an error, that means the peerbook doesnt have the peer\n }\n\n if (!isConnected) {\n dialQueue.abort()\n delete this._queues[dialQueue.id]\n }\n }\n })\n\n this._cleanInterval.reschedule(QUARTER_HOUR)\n }",
"function _pollDevice(i2cQueue, regs, interval_s, callback) {\n var intervalId = setInterval(function onTimeout(error) {\n _poll(i2cQueue, regs, intervalId, function(error){\n if (error) return callback(error);\n callback(error);\n delete _pollIds[intervalId]; // remove hash entry after polling completed\n });\n }, interval_s*1000);\n _pollIds[intervalId] = i2cQueue.getBusNumber(); // create 'hash-entry' for key=intervalId, value=i2cbusnumber\n}",
"function removeFromQueue() {\n queueItems.shift();\n processNextInConnectionQueue(name, origin);\n }",
"cancelAll() {\n let current = this.queue;\n while (current) {\n clearTimeout(current.timeoutHandler);\n current = current.next;\n }\n }",
"function processQueue() {\n\t var queue = nextTick.queue;\n\t var digest = nextTick.digest;\n\n\t nextTick.queue = [];\n\t nextTick.timeout = null;\n\t nextTick.digest = false;\n\n\t queue.forEach(function(queueItem) {\n\t var skip = queueItem.scope && queueItem.scope.$$destroyed;\n\t if (!skip) {\n\t queueItem.callback();\n\t }\n\t });\n\n\t if (digest) $rootScope.$digest();\n\t }",
"function pruneEventQueue() {\n // remove all eventQueue entries older than <timeUnit> milliseconds\n var t = eventQueue[0].t;\n for(var x=1,l=eventQueue.length;x<l;x++) {\n if( (t - eventQueue[x].t) > timeUnit ) break;\n }\n eventQueue = eventQueue.slice(0, x);\n }",
"function processQueue () {\n var queue = nextTick.queue;\n var digest = nextTick.digest;\n\n nextTick.queue = [];\n nextTick.timeout = null;\n nextTick.digest = false;\n\n queue.forEach(function (callback) { callback(); });\n\n if (digest) $rootScope.$digest();\n }",
"function unqueue(name) {\n var item = queues[name].shift();\n\n if (!item) {\n delete queues[name];\n return;\n }\n\n var obj = item[0];\n var fn = item[1];\n\n var delay = (60 / RATE) * 1000;\n delay = delay < 0 ? delay : 0;\n\n setTimeout(function() {\n\n // immutable .length hack :\\\n if (!fn) {\n oldEnd.call(obj, function() {\n unqueue(name);\n });\n } else if (fn.length == 1) {\n oldEnd.call(obj, function(res) {\n fn && fn(res);\n unqueue(name);\n });\n } else {\n oldEnd.call(obj, function(err, res) {\n fn && fn(err, res);\n unqueue(name);\n });\n }\n }, delay);\n }",
"function clearQueue(){updateQueue.length=0;markupQueue.length=0;}",
"function processQueue() {\n var queue = nextTick.queue;\n var digest = nextTick.digest;\n\n nextTick.queue = [];\n nextTick.timeout = null;\n nextTick.digest = false;\n\n queue.forEach(function (queueItem) {\n var skip = queueItem.scope && queueItem.scope.$$destroyed;\n if (!skip) {\n queueItem.callback();\n }\n });\n\n if (digest) $rootScope.$digest();\n }",
"function processQueue() {\n var queue = nextTick.queue;\n var digest = nextTick.digest;\n\n nextTick.queue = [];\n nextTick.timeout = null;\n nextTick.digest = false;\n\n queue.forEach(function(queueItem) {\n var skip = queueItem.scope && queueItem.scope.$$destroyed;\n if (!skip) {\n queueItem.callback();\n }\n });\n\n if (digest) $rootScope.$digest();\n }",
"function processQueue() {\n var queue = nextTick.queue;\n var digest = nextTick.digest;\n\n nextTick.queue = [];\n nextTick.timeout = null;\n nextTick.digest = false;\n\n queue.forEach(function(queueItem) {\n var skip = queueItem.scope && queueItem.scope.$$destroyed;\n if (!skip) {\n queueItem.callback();\n }\n });\n\n if (digest) $rootScope.$digest();\n }",
"function processQueue() {\n var queue = nextTick.queue;\n var digest = nextTick.digest;\n\n nextTick.queue = [];\n nextTick.timeout = null;\n nextTick.digest = false;\n\n queue.forEach(function(queueItem) {\n var skip = queueItem.scope && queueItem.scope.$$destroyed;\n if (!skip) {\n queueItem.callback();\n }\n });\n\n if (digest) $rootScope.$digest();\n }",
"function processQueue() {\n var queue = nextTick.queue;\n var digest = nextTick.digest;\n\n nextTick.queue = [];\n nextTick.timeout = null;\n nextTick.digest = false;\n\n queue.forEach(function(queueItem) {\n var skip = queueItem.scope && queueItem.scope.$$destroyed;\n if (!skip) {\n queueItem.callback();\n }\n });\n\n if (digest) $rootScope.$digest();\n }",
"function clearQueue(){\n _queue.forEach(function(timeout){\n clearTimeout(timeout)\n })\n _queue = []\n }",
"stop () {\n this.isRunning = false\n // Clear the general queue\n this._queue.clear()\n // Clear the cold call queue\n this._coldCallQueue.clear()\n\n this._cleanInterval.clear()\n\n // Abort the individual peer queues\n const queues = Object.values(this._queues)\n queues.forEach(dialQueue => {\n dialQueue.abort()\n delete this._queues[dialQueue.id]\n })\n }",
"cancel() {\r\n this.discardQueue();\r\n this.pending = null;\r\n }",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}",
"function clearQueue() {\n\t updateQueue.length = 0;\n\t markupQueue.length = 0;\n\t}"
]
| [
"0.67017174",
"0.66170037",
"0.6446916",
"0.64462495",
"0.62762064",
"0.61542034",
"0.6102532",
"0.6098445",
"0.6083377",
"0.60793847",
"0.60670954",
"0.60625",
"0.60625",
"0.60625",
"0.60625",
"0.6040644",
"0.5960726",
"0.5915781",
"0.5913964",
"0.5913964",
"0.5913964",
"0.5913964",
"0.5913964",
"0.5913964",
"0.5913964",
"0.5913964",
"0.5913964",
"0.5913964",
"0.5913964",
"0.5913964"
]
| 0.76895285 | 0 |
Controller for toBuyList operations | function ToBuyController(ShoppingListsService) {
var toBuy = this;
toBuy.getToBuyList = function functionName() {
return ShoppingListsService.getToBuyList();
};
toBuy.setItemBought = function(index) {
ShoppingListsService.setItemBought(index);
};
toBuy.isEmptyList = function() {
return ShoppingListsService.getToBuyList().length == 0;
};
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function getPurchasesListingAction(params) {\n const action = {\n type: ApiConstants.API_GET_PURCHASES_LISTING_LOAD,\n params,\n };\n return action;\n}",
"function listTransactions() {\n // Render the template\n ISML.renderTemplate('transactions/list');\n}",
"function listAction(request, response) {\n model.getAll(request.userId).then(\n bookings => {\n if(bookings.length < 1){\n response.status(200).json({message:\"keine Buchungen vorhanden\"});\n }\n else{\n response.status(200).json(bookings);\n }\n },\n error => response.send(error),\n\n );\n}",
"function listTransactions()\n{\n // Render the template\n ISML.renderTemplate('transactions/list');\n}",
"index () {\n return Api().get('wishlists')\n }",
"getWishlist(context){\n context.commit('setWishlist');\n }",
"function orderList() {\n var pageSize = request.httpParameterMap.pagesize.value; // eslint-disable-line no-undef\n var pageNumber = request.httpParameterMap.pagenumber.value; // eslint-disable-line no-undef\n var orderNumber = request.httpParameterMap.ordernumber.value || ''; // eslint-disable-line no-undef\n \n pageSize = pageSize ? parseInt(pageSize, 10) : 10;\n pageNumber = pageNumber ? parseInt(pageNumber, 10) : 1;\n\n orderListResponse = require('~/cartridge/scripts/getOrders').output({\n pageSize: pageSize,\n pageNumber: pageNumber,\n orderNumber: orderNumber\n \n\n });\n\n ISML.renderTemplate('application/orderlist', orderListResponse);\n}",
"function AlreadyBoughtController(ShoppingListsService) {\n var albou = this;\n albou.getAlreadyList = function functionName() {\n return ShoppingListsService.getAlreadyList();\n };\n albou.isEmptyList = function() {\n return ShoppingListsService.getAlreadyList().length == 0;\n };\n }",
"getList(cb) {\n return this.dataProvider.send({type: 'product.list'}).then(cb);\n }",
"addListToCart() {\n const self = this;\n const requestConfig = {};\n self.manageProfileShoppingListService.addListToCart(\n requestConfig,\n self.handleAddListResponse,\n self.handleAddistError,\n self.listName,\n );\n }",
"static get service() {\n return 'shoppingLists';\n }",
"function list(req, res) {\n res.json({ data: orders });\n}",
"function ShoppingListCheckOffService(){\n\tvar service=this;\n\n\tvar toBuyList=[\n{\n name:\"Jeans\",\n quantity:5\n},\n{\n name:\"Perfume\",\n quantity:6\n},\n{\n name:\"Jacket\",\n quantity:8\n},\n{\n name:\"T-shirt\",\n quantity:4\n},\n{\n name:\"SunGlass\",\n quantity:1\n},\n{\nname:\"Belt\",\nquantity:3\n}\n];\n\n// initially bought item is empty.\nvar boughtList = [];\n\nservice.moveToBoughtList=function(itemIndex){\n\tboughtList.push(toBuyList[itemIndex]);\n\ttoBuyList.splice(itemIndex,1);\n}\t\n\n\nservice.getBoughtList=function(){\n\treturn boughtList;\n\t};\n\nservice.getToBuyList=function(){\n return toBuyList;\n};\n\n}",
"function listItemsCredit() {\n var items = $(\"#items\").val();\n var company_id = $(\"#invoice_company_id\").val();\n \n $.get('/invoices/list_items/' + company_id, {\n items: items\n },\n function(data) {\n $(\"#list_items\").html(data);\n documentReady();\n });\n }",
"function list(req, res) {\n\n let p = req.swagger.params;\n let params = req.swagger.params.data.value;\n params['storage'] = p.storage.value || 'main';\n\n let appKey = req.header('x-app-key');\n let appSecret = req.header('x-app-secret');\n console.log(\"x-app-key: \", appKey);\n console.log(\"Params: \", params);\n console.log(\"Method: \", 'catalog::list');\n\n apiAppModel.get(appKey, appSecret, function (err, appData) {\n if (err) return res.json(responseModel.getErrorResponse('App error', {query: params}));\n if ((!params.keys || !params.keys.length) && (!params.pids || !params.pids.length))\n return res.json(responseModel.getErrorResponse('Params error', {query: params}));\n\n catalogKeyModel.getByNames(appData.namespace, params.keys, (err, catalogKeys) => {\n if (err) return res.json(responseModel.getErrorResponse('Error', err));\n if (!catalogKeys || !catalogKeys.length) return res.json(responseModel.getErrorResponse('No keys found'));\n\n catalogModel.getOrdersIds(appData.namespace, params.storage, params.limit, catalogKeys, params.order,(err, catalogIds) => {\n if (err || !catalogIds.length) return res.json(responseModel.getErrorResponse('Internal error', {query: params}));\n res.json(catalogResponseModel.getCatalogIdsResponse(catalogIds));\n });\n });\n });\n}",
"function displayItems() {\n db.product.list(promptPurchase, products);\n}",
"function buy(buyerID, sellerID, listingID) {\n \n}",
"function OrderVoucherListModel() {\n ListModel.apply(this, arguments);\n\n // 列表请求器 (*)\n this.listRequester = api.voucherOrderList;\n\n }",
"async showList() {\n const character = this.character;\n\n let attachments = new Attachments().add({\n title: __(\"What equipment did you want to sell?\"),\n fields: character.getFields(),\n color: COLORS.INFO\n });\n\n let options = new Options();\n\n for (const item of character.equipment.list()) {\n options.add(\n `${item.getDisplayName(character)}: ${item.getSellPriceDescription(character)}`,\n { action: ACTION_SELL, item: item.type }\n );\n }\n\n attachments.addSelect(__(\"Sell\"), COMMAND_NAME, options.getCollection());\n attachments.addButton(__(\"Cancel\"), \"look\", { params: { resetDescription: \"true\" } });\n\n await this.updateLast({ attachments });\n }",
"function listController(obj){\n $('.listing').click(function(){\n var item = dataParse($(this).attr('data-index'), obj);\n //console.log(item);\n $('.modal-listings').html(\"\");\n $('.modal-listings').html(template(item));\n });\n }",
"function updatePrice(list)\n{\n action=\"getPriceList\";\n request = 'ordercode=getPriceList&name='+list;\n sendHttpReq(request,action); \n}",
"async function list_Item(){\n let _name= listItemNameField.value;\n let _price= listItemPriceField.value;\n let _quantity= listItemQuantityField.value;\n window.web3 = await Moralis.Web3.enable();\n let contractInstance = new web3.eth.Contract(window.abi, \"0xcF2E4550d68bF506Dd5E7B33073260eC3816D252\")\n contractInstance.methods.listItem(_name, _price, _quantity).send({from: ethereum.selectedAddress, value:0})\n .on('receipt', function(receipt){\n console.log(receipt);\n alert(receipt.events.newProduct.returnValues);\n })\n }",
"function buyStore(req, res, next) {\n user.getUserField(req.user.uid, 'currency', function(err, points) {\n if (err) {\n return next(err);\n }\n \n // TODO: lookup item from req params\n // TODO: perform transaction (assign item to user, remove points)\n // TODO: return salient info\n\n res.json({\n transaction : true \n });\n });\n}",
"list(req, res){\n\t\t// Number of records for page\n\t\tlet limit = 12;\n \tlet offset = 0;\n\t\tconst token = req.body.token || req.query.token || req.headers['x-access-token'];\n\t\tvar decoded = jwt.decode(token, {complete: true});\n\n\t\t// selected page\n\t\tconst page = req.params.page == null ? 1 : req.params.page;\n\t\tconst order = req.params.order == null ? 'ASC' : req.params.order.toUpperCase();\n\t\tconst orderColumn = 'updatedAt';\n\t\tif(order == \"ASC\" || order == \"DESC\"){\n\t\t\t// Count all record to display\n\t\t\treturn PurchaseOrder.findAndCountAll({\n\t\t\t\tattributes: ['id', 'order_id', 'total_amount','status', 'createdAt', 'updatedAt'],\n\t\t\t\twhere: {\n\t\t\t\t\tuser_id: decoded.payload.user_id\n\t\t\t\t}\n\t\t\t})\n\t\t\t.then((data) => {\n\t\t\t\t// calculate the number of pages\n\t\t\t\tconst pages = Math.ceil(data.count / limit);\n\t\t\t\toffset = limit * (page - 1);\n\t\t\t\t// calculate results using limit and offset\n\t\t\t\tPurchaseOrder.findAll({\n\t\t\t\t\tattributes: ['id', 'order_id', 'total_amount','status', 'createdAt', 'updatedAt'],\n\t\t\t\t\tlimit: limit,\n\t\t offset: offset,\n\t\t $sort: { id: 1 },\n\t\t\t\t\tinclude: [\n\t\t\t\t\t\t{ model: LineItem, as: 'line_items' }\n\t\t\t\t\t],\n\t\t\t\t\twhere: {\n\t\t\t\t\t\tuser_id: decoded.payload.user_id\n\t\t\t\t\t},\n\t\t\t\t\torder: [\n\t\t\t\t\t\t[orderColumn, order]\n\t\t\t\t\t]\n\t\t\t\t})\n\t\t\t\t.then(purchase_orders => res.status(200).send(\n\t\t\t\t\t{\n\t\t\t\t\t\t'result': purchase_orders,\n\t\t\t\t\t\t'records': data.count,\n\t\t\t\t\t\t'pages': pages,\n\t\t\t\t\t\t'current_page': page\n\t\t\t\t\t}\n\t\t\t\t))\n\t\t\t\t.catch(error => res.status(400).send(error));\n\t\t\t})\n\t\t\t.catch(error => res.status(400).send(error));\n\t\t}\n\t\telse{\n\t\t\tres.status(404).send({\n\t\t\t\tmessage: 'Please provide a valid sort method'\n\t\t\t});\n\t\t}\n\t}",
"function _changeOrderButton() {\n if (vm.targetList.length > 0) {\n var lists = $(\".unorderedList\").find(\".ibox\");\n for (var i = 0; i < lists.length; i++) {\n vm.targetList[i].displayOrder = (i);\n }\n console.log(vm.targetList);\n vm.service.tncPutAll(vm.targetList)\n .then(_tncPutAllSuccess, _tncPutAllError);\n }\n }",
"function ShoppingListAddController(ShoppingListService){\n var itemAdder = this;\n //var shoppingList = ShoppingListService();\n\n itemAdder.itemName = null;\n itemAdder.itemQuantity = null;\n\n itemAdder.addItem = function(){\n try {\n ShoppingListService.addItem(itemAdder.itemName, itemAdder.itemQuantity);\n clearText();\n } catch (e) {\n itemAdder.errorMessage = e.message;\n }\n }\n\n\n function clearText(){\n itemAdder.itemName = null;\n itemAdder.itemQuantity = null;\n }\n}",
"function viewAll(list) {\n\n\t\t// Console logs each product along with id, price, and quantity\n\t\tlist.forEach(function(product) {\n\t\t\t\n\t\t\tvar str = \"id: \" + product.item_id;\n\t\t\tstr += \" | product: \" + product.product_name;\n\t\t\tstr += \" | price: $\" + product.price;\n\t\t\tstr += \" | quantity: \" + product.stock_quantity;\n\n\t\t\tconsole.log(str);\n\t\t});\n\n\t\tconnection.end();\n\t}",
"index({ params }, response) {\n\n\t\torderModel.find().exec().then(result => {\n\t\t\tresponse.send(result)\n\t\t}).then(err => {\n\t\t\tresponse.status(500).send(err)\n\t\t});\n\t}",
"function RequestUserList() {\n}",
"function ShoppingListService(){\n\n\t// reference service\n\tvar service = this;\n\n\t// array to hold list of shopping items\n\tvar boughtItems = [];\n\n\t// add 5 items to the by section\n\tvar buyItems =\n\t[\n\t\t{\n\t\t\tname: \"Cookies\",\n\t\t \tquantity: 10,\n\t\t \tprice: 2.00\n\t\t}, \n\t\t{\n\t\t\tname: \"Coke\", \n\t\t\tquantity: 3,\n\t\t\tprice: 2.99\n\t\t},\n\t\t{\n\t\t\tname: \"Chips\",\n\t\t\tquantity: 4,\n\t\t\tprice: 3.99\n\t\t},\n\t\t{\n\t\t\tname: \"Candy\",\n\t\t\tquantity: 5,\n\t\t\tprice: 1.59\n\t\t},\n\t\t{\n\t\t\tname: \"Apples\", \n\t\t\tquantity: 6,\n\t\t\tprice: 5.99\n\t\t}\n\t];\n\n\t// adds item and pushes it to boughtItem\n\tservice.addBuyItem = function(item, quantity, price){\n\t var boughtItem =\n\t {\n\t name: item,\n\t quantity: quantity,\n\t price: price\n\t };\n\t buyItems.push(boughtItem);\n\t}\n\n\t// moves elements from one buyItems array to boughtItems array\n\tservice.buyItem = function (itemIndex){\n\t\tvar item = buyItems[itemIndex];\n\t\tboughtItems.push(item)\n\t\tbuyItems.splice(itemIndex, 1);\n\t};\n\n\t// show items that are ready to buy\n\tservice.getBuyItems = function(){\n\t\treturn buyItems;\n\t};\n\n\t// show items that have been bought\n\tservice.getBoughtItems = function(){\n\t\treturn boughtItems;\n\t};\n}"
]
| [
"0.6141911",
"0.61204714",
"0.61053926",
"0.6006504",
"0.59730804",
"0.59261787",
"0.58732516",
"0.57969713",
"0.5719631",
"0.5681086",
"0.56512636",
"0.56393844",
"0.56391513",
"0.5628379",
"0.56281585",
"0.5579075",
"0.553555",
"0.55200267",
"0.55018234",
"0.5471585",
"0.54691404",
"0.5439356",
"0.5437579",
"0.54356724",
"0.5428342",
"0.5425413",
"0.5417133",
"0.54035914",
"0.5401142",
"0.5398365"
]
| 0.73389655 | 0 |
Controller for AlreadyboughtList operations | function AlreadyBoughtController(ShoppingListsService) {
var albou = this;
albou.getAlreadyList = function functionName() {
return ShoppingListsService.getAlreadyList();
};
albou.isEmptyList = function() {
return ShoppingListsService.getAlreadyList().length == 0;
};
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function listAction(request, response) {\n model.getAll(request.userId).then(\n bookings => {\n if(bookings.length < 1){\n response.status(200).json({message:\"keine Buchungen vorhanden\"});\n }\n else{\n response.status(200).json(bookings);\n }\n },\n error => response.send(error),\n\n );\n}",
"processCreateNewList() {\n // MAKE A BRAND NEW LIST\n window.todo.model.loadNewList();\n\n // CHANGE THE SCREEN\n window.todo.model.goList();\n }",
"processCreateNewList() {\n // MAKE A BRAND NEW LIST\n window.todo.model.loadNewList();\n\n // CHANGE THE SCREEN\n window.todo.model.goList();\n }",
"static async createBucketlist(req, res) {\n try {\n const { name } = req.body;\n // verify that the bucketlist doesnt exist\n\n const listCheck = await Bucketlist.findOne({\n where: { name, created_by: req.user.id }\n });\n\n if (listCheck) {\n throw new Error(\"this bucketlist already exist\");\n }\n\n const newBucketlist = await Bucketlist.create({\n name,\n created_by: req.user.id\n });\n\n if (!newBucketlist) {\n throw new Error(\"oops!, could not create the list, try again\");\n }\n\n // fetch this bucketlist and return\n const returnedBucketlist = await Bucketlist.findOne({\n include: [\n {\n model: Item,\n as: \"items\"\n }\n ],\n where: { name, created_by: req.user.id }\n });\n\n return res.status(201).json({\n status: \"success\",\n message: \"Bucketlist created successfully\",\n data: returnedBucketlist\n });\n } catch (error) {\n return res.status(400).json({\n status: \"error\",\n message: error.message\n });\n }\n }",
"getWishlist(context){\n context.commit('setWishlist');\n }",
"function RequestUserList() {\n}",
"function getNewListItem() {\n\t\n\t\t$.ajax({\n\t\t\tmethod: 'GET',\n\t\t\turl: base_url + \"/das/systemAdmin/listItem\",\n\t\t\tsuccess: function(response) {\n\t\t\t\tconsole.log(response);\n\t\t\t\t$('.list-form').prepend(response);\n\t\t\t},\n\t\t\tcomplete: function() {\n\t\t\t\trecalculate_list_order();\n\t\t\t},\n\t\t\terror: function() {\n\t\t\t\t$('.list-form').html(\"<div class='alert alert-danger'><strong>Error: </strong>Could not get list data</div>\");\n\t\t\t}\n\t\t});\t\t\n\t\t\t\n\t}",
"create(event) {\n event.preventDefault()\n let formData = event.target\n let newList = {\n title: formData.listName.value\n }\n\n\n ListService.create(newList)\n _drawLists()\n formData.reset() \n }",
"function newCheckList() {\n var name = $(\"#myInput\").val(); // Takes the input from the user\n doPost(\"/saveList\", {\"name\":name}, newCheckListCreated)\n}",
"function candidateList() {\n history.push(\"/CandidateListAdmin\");\n }",
"index(request, reply) {\n this.ToDo.findAll()\n .then((response) => reply(response))\n .catch((err) => reply(this.Boom.wrap(err)))\n }",
"function updateTodoList(){\n $scope.toDoList = dataPool.getTodoListByCategory();\n }",
"function create_list(request,response,next) {\n response.data = new_list(request.body.value);\n next();\n}",
"index () {\n return Api().get('wishlists')\n }",
"function postList() {\n let dataSent = {\n name: listTitle.title,\n items: listArr\n };\n\n instance\n .post(listID.current, dataSent, {\n cancelToken: cancelTokenSource.token,\n withCredentials: true\n })\n .then(function(response) {\n //if a new list was saved, it pulls that lists ID\n if (!listID.current) {\n listID.current = response.data;\n }\n })\n .catch(function(error) {\n console.log(error);\n });\n }",
"function returnToList() {\r\n $state.transitionTo('node.list', {}, {\r\n reload: false,\r\n inherit: false,\r\n notify: true\r\n });\r\n }",
"function initialize() {\n if (__DEVONLY__) $log.debug(`ListController initialize for ${vm.list.name}`);\n if (!vm.list._id) {\n if (__DEVONLY__) $log.warn(`ListController initialize for ${vm.list.name} awaiting post results`);\n return;\n }\n \n listManager.getItemsInList(vm.list)\n .then((items) => {\n if (__DEVONLY__) $log.log(`ListController initialize: SUCCESS for ${vm.list.name}`);\n if (vm.list.items.length === 0) vm.addItemVisible = true;\n // $scope.$digest();\n })\n .catch((err) => {\n if (__DEVONLY__) $log.error('ListController initialize: ', err);\n });\n }",
"appendNewListToView(newList) {\r\n // GET THE UI CONTROL WE WILL APPEND IT TO\r\n let listsElement = document.getElementById(\"todo-lists-list\");\r\n\r\n // MAKE AND ADD THE NODE\r\n let newListId = \"todo-list-\" + newList.id;\r\n let listElement = document.createElement(\"div\");\r\n listElement.setAttribute(\"id\", newListId);\r\n listElement.setAttribute(\"class\", \"todo_button\");\r\n\r\n listElement.style.display = \"flex\";\r\n listElement.style.alignContent = \"center\";\r\n listElement.style.justifyContent = \"center\";\r\n listElement.style.minHeight = \"40px\";\r\n\r\n listElement.appendChild(document.createTextNode(newList.name));\r\n listsElement.appendChild(listElement);\r\n\r\n // SETUP THE HANDLER FOR WHEN SOMEONE MOUSE CLICKS ON OUR LIST\r\n let thisController = this.controller;\r\n listElement.onmousedown = function() {\r\n window.localStorage.setItem(\"view\", true);\r\n\r\n thisController.model.tps.clearAllTransactions();\r\n\r\n for (var i = 0; i < listsElement.children.length; i++) {\r\n listsElement.children.item(i).style.backgroundColor = \"\";\r\n listsElement.children.item(i).style.color = \"white\";\r\n }\r\n thisController.handleLoadList(newList.id);\r\n listElement.style.backgroundColor = \"rgb(255,200,25)\";\r\n listElement.style.color = \"black\";\r\n\r\n listsElement.insertBefore(listElement, listsElement.children.item(0));\r\n }\r\n }",
"function addNewList(list) {\n console.log('aalatief - Entered List: ' + angular.toJson(list));\n var deferred = $q.defer();\n var query = \"INSERT INTO list (listLocalId,listName,listDescription,listServerId,listColor,listOrder,deleted,newCount, crossCount, lastUpdateDate, lastUpdateBy, origin, flag, listOwnerServerId) \" +\n \"VALUES (null,?,?,'','','','N',0,0,datetime('now','localtime'),?,'L', 'N', ?)\";\n\n global.db.transaction(function (tx) {\n tx.executeSql(query, [list.listName, list.listDescription, 'L', global.userServerId], function (tx, response) {\n //Success Callback\n console.log(\"localListHandlerV2.addNewList res \" + angular.toJson(response));\n list.listLocalId = response.insertId;\n serverHandlerListV2.maintainGlobalLists(list, \"ADD\");\n deferred.resolve(response.insertId);\n }, function (error) {\n console.error(\"localListHandlerV2.addNewList error \" + error.message);\n deferred.reject(error);\n });\n }, function (err) {\n console.error(\"localListHandlerV2.addNewList error \" + angular.toJson(error));\n defer.reject(err);\n }, function () {\n\n });\n return deferred.promise;\n }",
"constructor() {\n super('List', []);\n this.success();\n this.lists = {};\n }",
"get list() {\n return Controller.list;\n }",
"get list() {\n return Controller.list;\n }",
"_updateList(){\n let req = this._request,\n self = this;\n\n // show preloader\n this._startPreloader();\n\n this.hidePage(req.action).then(function(){\n // send request\n return self._db.get(req);\n }).then(function(data){\n // add pagination\n self._addPagination(data);\n\n // update view\n return self._renderList(data);\n }).then(function(){\n // show loaded content\n self.openPage(req.action);\n }).catch(function(err){\n // display errors\n console.log(err);\n }).then(function(){\n // hide preloader\n self._stopPreloader();\n });\n }",
"static async updateBucketlist(req, res) {\n try {\n const { id } = req.params;\n const { name } = req.body;\n\n const bucketlist = await Bucketlist.findOne({\n where: { id, created_by: req.user.id }\n });\n\n if (!bucketlist) {\n throw new Error(\"could not retrieve the bucketlist\");\n }\n\n // make sure the sent data is different\n if (name === bucketlist.name) {\n throw new Error(\"please modify the bucketlist name or cancel\");\n }\n\n // update the bucket list\n const updatedBucketList = await Bucketlist.update(\n { name },\n { where: { id, created_by: req.user.id } }\n );\n\n if (!updatedBucketList) {\n throw new Error(\"could not modify this bucketlist\");\n }\n\n const bucketlistReturned = await Bucketlist.findOne({\n include: [\n {\n model: Item,\n as: \"items\"\n }\n ],\n where: { id, created_by: req.user.id }\n });\n\n return res.status(200).json({\n status: \"success\",\n message: \"bucketlist retrieved successfully\",\n data: bucketlistReturned\n });\n } catch (error) {\n return res.status(400).json({\n status: \"error\",\n message: error.message\n });\n }\n }",
"function openlist() {\n $state.go(BaseStateService.baseState);\n }",
"create(req, res) {\n\n\t\tlet {board, list} = req.params.all();\n\t\t\n\t\tQ.all([\n\t\t\tBoard.findOne({id: board.id}),\n\t\t\tList.create(list)\n\t\t])\n\t\t.spread((_board, _list) => {\n\t\t\t\n\t\t\tif (!_board || !_list) return res.status(400).send({});\n\n\t\t\tif (!_board.lists) _board.lists = [];\n\t\t\t_board.lists.push(_list.id);\n\t\t\t_board.save();\n\t\t\tres.send(_list);\n\t\t})\n\t\t.catch(function (error) {\n \t\tres.status(400).send({});\n\t\t})\n\n\t}",
"addItem(event, taskIndex) {\n event.preventDefault()\n\n let form = event.target\n\n let newItem = form.item.value\n\n _listService.addItem(taskIndex, newItem)\n _drawLists()\n }",
"addWishlist(context, product){\n context.commit('updateWishlist', product);\n }",
"addTrackerListHandle(){\n const projectid = this.props.projectInfo.id;\n let listOrder = this.state.lists.length + 1;\n let listName = this.state.listName;\n let body = {listName, listOrder};\n\n createTrackerList(projectid, body)\n .then(res => {\n if(res.status !== 200){\n console.log(res);\n }\n else {\n findTrackerLists(projectid)\n .then( res => {\n if (res.status !== 200) {\n console.log(res);\n }\n else {\n this.setState({\n lists: res.data,\n isAddListInputOpen: false,\n listName: '',\n })\n }\n })\n }\n })\n }",
"function ShoppingListAddController(ShoppingListService){\n var itemAdder = this;\n //var shoppingList = ShoppingListService();\n\n itemAdder.itemName = null;\n itemAdder.itemQuantity = null;\n\n itemAdder.addItem = function(){\n try {\n ShoppingListService.addItem(itemAdder.itemName, itemAdder.itemQuantity);\n clearText();\n } catch (e) {\n itemAdder.errorMessage = e.message;\n }\n }\n\n\n function clearText(){\n itemAdder.itemName = null;\n itemAdder.itemQuantity = null;\n }\n}"
]
| [
"0.6517936",
"0.64162314",
"0.64162314",
"0.6340543",
"0.6236118",
"0.6077065",
"0.5945623",
"0.5909195",
"0.5903696",
"0.5901167",
"0.5857137",
"0.5841116",
"0.5811142",
"0.5801406",
"0.57809806",
"0.5772753",
"0.5748415",
"0.57297343",
"0.57218754",
"0.5716855",
"0.57157224",
"0.57157224",
"0.5709313",
"0.5706901",
"0.5699532",
"0.5697187",
"0.569138",
"0.56619364",
"0.56567574",
"0.5648299"
]
| 0.697672 | 0 |
Get the minutes the user enters in the input field | function getMinutes(event) {
// Prevent the page to update when the mins are submitted
event.preventDefault();
// console.log(this.minutes.value);
// Save the input value in a variable
const mins = this.minutes.value;
// Change mins to seconds and use the input value in the function to set the timer
timer(mins * 60);
// reset the input field
this.reset();
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function minutes () {\n let minute=parseInt(prompt(\"enter number of minutes\"));\n let second=minute*60;\n console.log(second);\n}",
"function calculateMinutes(minutes){\n var minutesFromMinutes = minutes.split(\"min\")\n return minutesFromMinutes[0]\n }",
"sanitizeMinutes(e) {\n let minutes = e.target.value;\n // handle invalid values of minutes\n if (minutes < 0){\n minutes = 0;\n e.target.value = minutes;\n }\n \n return minutes;\n }",
"function getMinutes(time)\n{\n var delimiter = \":\";\n var res;\n\n var index = time.search(delimiter);\n var minSecString = time.substring(index + 1, time.length);\n\n index = minSecString.search(delimiter);\n var min = minSecString.substring(0, index);\n\n// if (parseInt(min) <= 9) {\n if (parseInt(min) <= 9 && (parseInt(min) > 0)) {\n res = \"0\" + parseInt(min);\n }\n else {\n if (min == \"00\") res = \"0\" + 0;\n else if (min == \"08\") res = \"0\" + 8;\n else if (min == \"09\") res = \"0\" + 9;\n else res = parseInt(min);\n }\n\n return res;\n}",
"get minutes() {\n return Math.floor(this.currentTime / SECONDS_IN_MINUTE) % MINUTES_IN_HOUR;\n }",
"function getMM(min){\n \n if (min == '' || min == '00'){\n return '00';\n }\n \n var mm = min;\n \n if (isNaN(min)) {\n return mm;\n }\n if (min.length == 1) {\n mm = min + '0';\n }\n if (min.length > 2) {\n mm = min[0] + min[1];\n }\n if (parseInt(min) >= 60){\n return mm;\n }\n \n return mm;\n\n}",
"function convertTimeToMinutes() {\n var inputValue = $('#expire-timeout').val();\n var selectValue = $('#time-value').val();\n\n return inputValue * selectValue;\n}",
"getMinutes(){\n return parseInt(this.currentTime / 60);\n }",
"function GetMinutes(str){\n var t = str.split(\":\");\n var hours = parseInt(t[0]);\n var minutes = parseInt(t[1].substring(0,2));\n if (str.endsWith('pm')) {\n hours += 12;\n }\n return minutes + hours * 60;\n}",
"get Minute() {\n return this._minutes;\n }",
"function minutes(num){\r\n var hr = \"Hours\"\r\n var min = 60;\r\n var hours = num/min;\r\n return hours+ \"\" +hr;\r\n}",
"function timeInMinutes(time) {\n time = time.split(':');\n const hour = parseInt(time[0]) * 60;\n const minute = parseInt(time[1]);\n const timeInMin = hour + minute;\n return timeInMin;\n}",
"function printMinutes() {\n let minutes = chronometer.twoDigitsNumber(chronometer.getMinutes());\n minDec.innerText = minutes.charAt(0);\n minUni.innerText = minutes.charAt(1);\n console.log(chronometer.currentTime);\n}",
"function getMinutes( hours ) {\r\n return hours * 60;\r\n}",
"function getMinutes() {\n if (totalSeconds > 3599) {\n totalSeconds -= 3600;\n totalHours++;\n }\n return (totalSeconds / 60);\n}",
"function getBreak(5) {\n var minutes\n}",
"function getTimeInMinutes(time, unit) {\n switch (unit) {\n case 'd': {\n time *= 24;\n }\n case 'h': {\n time *= 60;\n }\n }\n return time;\n}",
"function getMinutes() {\n return tehDate.getMinutes();\n }",
"function getMinutes() {\n return tehDate.getMinutes();\n }",
"function checkTmLmt(inputval){\n\tvar strtMin = document.getElementById(\"strtMin\");\n\tif(inputval > 60){\n\t\tstrtMin.value=0;\n\t}\n}",
"function minutes_in_hours(m) {\n return m / 60;\n}",
"function lateRide(inputMinutes) {\t\n\n\t// Step1: Create a current time string by finding \n\t// the hours and minutes\n\tconst hours = String(Math.floor(inputMinutes / 60))\n\tconst minutes = String(inputMinutes % 60)\n\tconst time = hours.concat(minutes)\n\n\t// Step2: Loop over the time string and add the \n\t// digits together\n\tlet temp = 0\n\tfor(let i=0; i<time.length; i++){\n\t\ttemp += Number(time[i])\n\t}\n\treturn temp\n}",
"function time2minutes(n){\r\n\t\tvar a = n.split(\":\");\r\n\t\tif(a.length == 2){\r\n\t\t\tvar x = a[0]*60;\r\n\t\t\tvar y = a[1]*1;\r\n\t\t}\r\n\t\treturn ((x+y)*60000);\r\n\t}",
"function checkValidInput(time){\n\tif(time == \"\")\n\t\treturn 0;\n\telse if(time >= 60)\n\t\treturn 60;\n\telse if(time <= 0)\n\t\treturn 0;\n\telse\n\t\treturn time;\n}",
"function setCountDownMinutes(e) {\n if (e.keyCode == 13) {\n startingMinutes = minutesInput.val();\n time = startingMinutes * 60;\n minutesInput.addClass(\"d-none\");\n $(\"#minutes\").removeClass(\"d-none\");\n $(\"#minutes\").text(`${startingMinutes}:00`);\n }\n}",
"get blockDurationMinutesInput() {\n return this._blockDurationMinutes;\n }",
"function test10() {\n const birthday = new Date('March 13, 08 04:20');\n\n console.log(birthday.getMinutes());\n // expected output: 20\n}",
"function hoursToMinutes() {\n\n}",
"function hoursToMinutes() {\n\n}",
"function minutes(min, max) {\r\n min = 10;\r\n max = 15;\r\n return Math.floor(Math.random() * (max - min + 1) + min);\r\n }"
]
| [
"0.73578656",
"0.7203445",
"0.7075389",
"0.68035567",
"0.676812",
"0.6687088",
"0.6676536",
"0.6676415",
"0.6477413",
"0.642947",
"0.6423358",
"0.63419926",
"0.6311858",
"0.62572855",
"0.6233581",
"0.62334466",
"0.62266695",
"0.62047195",
"0.62047195",
"0.6181648",
"0.6180695",
"0.6173475",
"0.6172925",
"0.6165299",
"0.6126031",
"0.6118216",
"0.60477656",
"0.60395336",
"0.60395336",
"0.60247064"
]
| 0.8170429 | 0 |
Adds a message to the message registry. | function addMessageToRegistry(messageId) {
var found = false
for (var i = 0; i < messageRegistry.length; i++) {
if (messageRegistry[i] === messageId) {
found = true
break
}
}
if (!found) {
messageRegistry.push(messageId)
buildAndShowMessageBar(messageId, "messagebar_register")
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function addMessage(message) {\n self.messages.push(message);\n }",
"function addMessage(message) {\n var text = message.content ? message.content.code.trim() : '';\n if (!text) {\n return;\n }\n\n message.content.code = text;\n _messages.push(message);\n\n // If there is no message already being processed, go ahead and process this message\n // immediately.\n if (_idle) {\n processNextMessage();\n }\n}",
"function addMessage(messages, newMessage) {\n\n if (!isUndefinedOrNull(messages) && newMessage) {\n messages.push(newMessage);\n }\n }",
"push(message) {\n }",
"function appendMessage(message) {\n vm.messages.push(message);\n}",
"function appendToQueue(message) {\n _messageQueue.push(message);\n }",
"add(container, message) {\n\t\tlet messages = this.containers[container]\n\n\t\tif (messages.isNil) {\n\t\t\tmessages = new MessagesContainer(container)\n\t\t\tthis.containers[container] = messages\n\t\t}\n\n\t\tmessages.add(message)\n\t}",
"function addMessage() {\n var timestamp = new Date().getTime();\n _self.messages.$add({\n user: _self.email,\n pseudo: _self.pseudo,\n text: _self.newMessageText,\n img: _self.img,\n time: timestamp\n }).then(function() {\n _self.scroll();\n });\n _self.newMessageText = '';\n }",
"register(msg) {\n this.client.addCommand(msg.command);\n }",
"function addMsg(msg) {\n setMsgs((prevMsgs) => [...prevMsgs, msg]);\n }",
"static addMessage(message, url) {\n\t\tconst encodedDomain = encodeURIComponent(url.hostname).replace(/\\./g, '%2E');\n\t\tconst encodedPath = encodeURIComponent(url.pathname).replace(/\\./g, '%2E');\n\t\tconst ref = firebase.database().ref('domains/' + encodedDomain + '/pages/' + encodedPath + '/messages/' + message.id);\n\n\t\tref.set(message.serialize());\n\t}",
"handleMessageReceived(message) {\n this.messageList.push(message)\n }",
"_createMessageElement(message) {\n const messageElement = this._document.createElement('div');\n this._setMessageId(messageElement);\n messageElement.textContent = message;\n this._createMessagesContainer();\n messagesContainer.appendChild(messageElement);\n messageRegistry.set(message, { messageElement, referenceCount: 0 });\n }",
"function addChangeMessage(messages, messagesHash, msg) {\n messages.push(msg);\n messagesHash[msg.path] = msg;\n }",
"addMessage() {\n const message = this.state.messages[0];\n this.referenceChatMessages.add({\n _id: message._id,\n text: message.text || '',\n createdAt: message.createdAt,\n user: message.user,\n uid: this.state.uid,\n image: message.image || null,\n location: message.location || null,\n });\n }",
"function addSystemMessage(message) {\n $('#messages').append($('<li>').attr(\"id\", \"systemMessage\").text(message));\n }",
"function save_new_message(new_message) {\n console.log(new_message);\n queue_message(new_message);\n}",
"async pushMessageToQueue(queue, newMessage) {\n if (this.messageHandler) {\n const wrappedMessage = {\n content: Buffer.from(JSON.stringify(newMessage)),\n };\n this.messageHandler(wrappedMessage);\n } else {\n // Just warning and no exception because the test might want to simulate that\n console.error(\n 'A new message put into the fake queue but no handlers exist'\n );\n }\n }",
"sendMessage(state, message) {\n state.conversation.push(message);\n }",
"addMessage(message) {\n let messages = this.state.messages;\n messages.push(message);\n this.setState({\n messages: messages\n })\n }",
"function addMessage(message) {\n console.log('addMessage working! ', message.responseText.results );\n app.fetch(message);\n $('#chats').append('<div>' + message.responseText.results + '</div>');\n\n }",
"addNewMessage(user, message) {\n const newMessage = { username: user, color: this.state.currentUser.color, content: message, type: 'message' };\n const toServer = JSON.stringify(newMessage);\n this.socket.send(toServer);\n }",
"function add_message(text) {\n $.post(\n '/server/index.php',\n { action : 'store', name : user_name, message: text },\n function () {\n chat_screen.html('');\n index();\n }\n );\n }",
"addMessage() {\n const message = this.state.messages[0];\n this.referenceChatMessages.add({\n _id: message._id,\n uid: this.state.uid,\n createdAt: message.createdAt,\n text: message.text || null,\n user: message.user,\n image: message.image || null,\n location: message.location || null,\n });\n }",
"addMessage(message) {\n if (this.firstMessage) {\n this.firstMessage = false;\n this.cache.messages.innerHTML = '';\n }\n\n const newMessage = document.createElement('div');\n newMessage.classList.add('chat__message');\n\n // add an extra class to the div for styling purposes if current user is the sender\n if (message.user === this.nickname) {\n newMessage.classList.add('chat__message--reply');\n }\n // otherwise prepend the name of the user to the message\n else {\n newMessage.textContent = message.user + ': ';\n }\n\n newMessage.textContent += message.message;\n this.cache.messages.appendChild(newMessage);\n\n // scroll the user to the bottom of the message container\n this.cache.messagesWrapper.scrollTop = this.cache.messagesWrapper.scrollHeight;\n }",
"static saveMessage(message) {\n repository.write(() => {\n repository.create('Message', message);\n });\n }",
"message(value) {\n this.newMessage = value\n }",
"_add(attribute, messages) {\n messages = this._findOrCreateMessages(attribute, messages);\n this.addObjects(messages);\n Ember.get(this, 'errorsByAttributeName').get(attribute).addObjects(messages);\n\n this.notifyPropertyChange(attribute);\n }",
"_addMessageReference(element, message) {\n const registeredMessage = messageRegistry.get(message);\n // Add the aria-describedby reference and set the\n // describedby_host attribute to mark the element.\n addAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);\n element.setAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE, '');\n registeredMessage.referenceCount++;\n }",
"function addChatMsg(message, roomID, user) {\n const assignMsg = roomsState[roomID].chat;\n\n const chatObj = {\n user: user.username,\n id: user.id,\n message: message,\n };\n\n assignMsg.push(chatObj);\n\n // return console.log('NEW Message: ', assignMsg);\n}"
]
| [
"0.7756207",
"0.7193801",
"0.6656581",
"0.66377217",
"0.6581155",
"0.65675676",
"0.655871",
"0.6511005",
"0.64611125",
"0.6458658",
"0.6329502",
"0.61966276",
"0.61813605",
"0.6132389",
"0.6129137",
"0.61154133",
"0.60857195",
"0.6002693",
"0.60007447",
"0.59915364",
"0.59797746",
"0.59506",
"0.5948724",
"0.5932795",
"0.5932182",
"0.59265727",
"0.58893675",
"0.58704126",
"0.5866472",
"0.58347476"
]
| 0.7424487 | 1 |
Checks if the message registry is empty. | function isMessageRegistryEmpty() {
if ((messageRegistry.length === 1 && messageRegistry[0] === "WRN_INPUT_PASSWORD") || messageRegistry.length === 0) {
return true
} else {
return false
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function isEmpty() {\n\t\treturn messages.length == 0;\n \t}",
"function checkIsEmpty() {\n if (this.isEmpty()) this.set_msg_empty();\n}",
"function isEmpty() {\n return _.isEmpty(modelSubscribersByType);\n }",
"function isEmpty() {\n return Object.keys(this.value()).length === 0;\n}",
"function isEmpty() {\n return Object.keys(this.value()).length === 0;\n}",
"isEmpty () {\n return this.queued.length === 0 && this.active.length === 0\n }",
"isEmpty() {\n\t\treturn this.items.length == 0;\n\t}",
"function isEmpty() {\n return this._storage.length === 0;\n}",
"function areAnyComponentsEmpty(){\n\t\tif(alert_0131.list!=''){\n\t\t\tvar message = alert_0131.message+alert_0131.list+\".\";\n\t\t\tthrowAlert(alert_0131,message);\n\t\t}\n\t}",
"isEmpty() {\n return this.#items.length === 0;\n }",
"isEmpty() {\n\t\treturn this.stack.length === 0;\n\t}",
"isEmpty() {\n return this._items.length === 0;\n }",
"isEmpty() {\n return this.native.isEmpty();\n }",
"isEmpty() {\n return this.native.isEmpty();\n }",
"function isEmpty() {\n return _.isEmpty(singletons);\n }",
"get isEmpty() {\n return (this._queue.length == 0);\n }",
"isEmpty() {\n return this._info.sizeInBytes === 0;\n }",
"isEmpty(){\r\n\t\treturn this.items.length == 0;\r\n\t}",
"isEmpty() {\n return this.items.length == 0;\n }",
"isEmpty() {\n return this.items.length == 0;\n }",
"isEmpty() {\n\t\treturn ( parseInt( this.products.length ) == 0 );\n\t}",
"is_empty() {\n return this.qsize() == 0\n }",
"isEmpty() {\n\t\treturn this.length === 0;\n\t}",
"isQueueEmpty() {\n return this.length === 0;\n }",
"isEmpty() {\r\n return this.items.length == 0;\r\n }",
"isEmpty(){\n\t\t\treturn this.size == 0;\n\t\t}",
"isEmpty() {\n if (this.items.length == 0) {\n return true;\n }\n else {\n return false;\n }\n }",
"function empty(){\n\tif(this.dataStore.length == 0){\n\t\treturn true;\n\t}else{\n\t\treturn false;\n\t}\n}",
"function empty() {\n if (this.dataStore.length == 0) {\n return true;\n } else {\n return false;\n }\n}",
"empty(){\n\t\tif(this.stack.length === 0){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}"
]
| [
"0.7520145",
"0.73215955",
"0.6601768",
"0.6558132",
"0.6558132",
"0.64924145",
"0.6420497",
"0.63648695",
"0.63263255",
"0.6317788",
"0.6309287",
"0.6307014",
"0.6270835",
"0.6270835",
"0.6260009",
"0.6255162",
"0.6254462",
"0.62402946",
"0.6236229",
"0.6236229",
"0.6206832",
"0.6197284",
"0.6196146",
"0.6186792",
"0.61556304",
"0.61433524",
"0.61401916",
"0.6140143",
"0.6122438",
"0.61142343"
]
| 0.83277506 | 0 |
====================================================================================// ================================== MAIN FUNCTIONS ==================================// ====================================================================================// Determines the register container style for responsiveness. | function determineContainerStyle() {
if ($(window).height() < "555") {
if ($("#register_container").hasClass("container_free")) {
$("#register_container").removeClass("container_free")
}
$("#register_container").addClass("container_fitting")
} else if ($(window).height() >= "555" && $(window).height() < "835") {
if ($(window).width() < "1200") {
if ($("#register_container").hasClass("container_free")) {
$("#register_container").removeClass("container_free")
}
$("#register_container").addClass("container_fitting")
} else if ($(window).width() >= "1200") {
if ($("#register_container").hasClass("container_fitting")) {
$("#register_container").removeClass("container_fitting")
}
$("#register_container").addClass("container_free")
}
} else if ($(window).height() >= "835") {
if ($("#register_container").hasClass("container_fitting")) {
$("#register_container").removeClass("container_fitting")
}
$("#register_container").addClass("container_free")
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"_builContainerStyle() {\n const { position } = this.props;\n // Depending on the chosen position we use a margin of 32 pixels from the\n // corresponding side.\n return {\n ...NotificationContainer.STYLE.container,\n bottom: position.indexOf('bottom') !== -1 && 32,\n left: position.indexOf('left') !== -1 && 32,\n right: position.indexOf('right') !== -1 && 32,\n top: position.indexOf('top') !== -1 && 32,\n };\n }",
"function mobileStyles() {\n const mainContainer = document.querySelector('#app');\n const mainPreloader = document.querySelector('.main-preloader');\n const weatherContainer = document.querySelector('.current-weather');\n\n const mainContainerWidth = mainContainer.offsetWidth;\n const mainContainerHeight = mainContainer.offsetHeight;\n\n /* styles for body */\n document.querySelector('body').style.background = '#d3d3d3';\n\n /* styles for main preloader depending on the device's orientation */\n if(!weatherContainer) {\n if (this.state.screenLandscapeOrientation && window.innerHeight <= mainContainerHeight / 1.65) {\n mainPreloader.style.paddingTop ='1em';\n }\n else {\n mainPreloader.style.paddingTop ='5em';\n }\n }\n\n /* styles for main container depending on screen resolution */\n if(window.innerHeight > mainContainerHeight * 1.05 && window.innerWidth > mainContainerWidth * 1.05) {\n mainContainer.style.boxShadow = '0 0 4px black';\n } else {\n mainContainer.style.boxShadow = 'none';\n }\n}",
"applyRenderAttributes() {\n let me = this,\n container = Neo.getComponent(me.containerId),\n prefix = me.prefix,\n cls = container && container.cls;\n\n if (!container) {\n Neo.logError('layout.Flexbox: applyRenderAttributes -> container not yet created', me.containerId);\n }\n\n _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"].add(cls || [], prefix + 'container');\n\n if (me.align) {\n _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"].add(cls, prefix + 'align-' + me.align);\n }\n if (me.direction) {\n _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"].add(cls, prefix + 'direction-' + me.direction);\n }\n if (me.pack) {\n _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"].add(cls, prefix + 'pack-' + me.pack);\n }\n if (me.wrap) {\n _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"].add(cls, prefix + 'wrap-' + me.wrap);\n }\n\n container.cls = cls;\n }",
"function prepareAndStyle() { // 6789\n var iconSize = this.config ? this.config.iconSize : config.defaultIconSize; // 6790\n angular.forEach({ // 6791\n 'fit' : '', // 6792\n 'height': '100%', // 6793\n 'width' : '100%', // 6794\n 'preserveAspectRatio': 'xMidYMid meet', // 6795\n 'viewBox' : this.element.getAttribute('viewBox') || ('0 0 ' + iconSize + ' ' + iconSize) // 6796\n }, function(val, attr) { // 6797\n this.element.setAttribute(attr, val); // 6798\n }, this); // 6799\n // 6800\n angular.forEach({ // 6801\n 'pointer-events' : 'none', // 6802\n 'display' : 'block' // 6803\n }, function(val, style) { // 6804\n this.element.style[style] = val; // 6805\n }, this); // 6806\n } // 6807",
"function carouselContainerDim(){\n carouselContainerWid = $carousel.width();\n carouselContainerHt = carouselHt;\n }",
"updateContainerSize() {\n\t\tconst chartContainer = this.chartContainer.current;\n\n\t\tif (!chartContainer) {\n\t\t\t// chartContainer will not be rendered on the first invocation as\n\t\t\t// context (cq-context element) needs to be available first\n\t\t\t// wait until it is available and try again\n\t\t\tsetTimeout(this.updateContainerSize, 10);\n\t\t\treturn;\n\t\t}\n\n\t\tconst {\n\t\t\tclientWidth: width,\n\t\t\tclientHeight: containerHeight\n\t\t} = chartContainer;\n\t\tconst { UIContext } = this.state;\n\t\tconst {\n\t\t\tbreakpoints: size,\n\t\t\tbreakpointSymbolPlaceholders: symbolPlaceholders\n\t\t} = this.state.config;\n\n\t\tconst labels = ['sm', 'md', 'lg']; // ui container class suffixes for various break points\n\t\tconst breakpointSize =\n\t\t\twidth < size[0] ? labels[0] : width < size[1] ? labels[1] : labels[2];\n\n\t\tconst symbolPlaceholder =\n\t\t\twidth < size[0]\n\t\t\t\t? symbolPlaceholders[0]\n\t\t\t\t: width < size[1]\n\t\t\t\t? symbolPlaceholders[1]\n\t\t\t\t: symbolPlaceholders[2];\n\n\t\tUIContext.uiLayout = {\n\t\t\t...UIContext.uiLayout,\n\t\t\tbreakpointSize,\n\t\t\tcontainerWidth: width,\n\t\t\tcontainerHeight,\n\t\t\tsymbolPlaceholder\n\t\t};\n\n\t\tthis.resizeScreen();\n\t}",
"getContainerStyle(){\n\n\t\tconst { autoHeight, autoHeightMin, autoHeightMax } = this.props;\n\n\t\treturn {\n\t\t\tposition: 'relative',\n\t\t\toverflow: 'hidden',\n\t\t\twidth : '100%',\n\t\t\t...( autoHeight && {\n\t\t\t\theight : 'auto',\n\t\t\t\tminHeight: autoHeightMin,\n\t\t\t\tmaxHeight: autoHeightMax\n\t\t\t}),\n\t\t\t...( !autoHeight && {\n\t\t\t\theight: '100%',\n\t\t\t}),\n\t\t\t...this.props.style,\n\t\t\t...this.props.containerStyle,\n\t\t};\n\n\t}",
"applyRenderAttributes() {\n let me = this,\n container = Neo.getComponent(me.containerId),\n cls = container && container.cls;\n\n if (!container) {\n Neo.logError('layout.Fit: applyRenderAttributes -> container not yet created', me.containerId);\n }\n\n _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"].add(cls || [], 'neo-layout-fit');\n\n container.cls = cls;\n }",
"glowContainers() {\n // Util.glowContainer(\"sc-coordinate-webmercator-x\", \"green\");\n // Util.glowContainer(\"sc-coordinate-webmercator-y\", \"green\");\n Util.glowContainer(\"sc-coordinate-latlong-x\", \"green\");\n Util.glowContainer(\"sc-coordinate-latlong-y\", \"green\");\n // Util.glowContainer(\"sc-coordinate-nad83-x\", \"green\");\n // Util.glowContainer(\"sc-coordinate-nad83-y\", \"green\");\n // Util.glowContainer(\"sc-coordinate-nad27-x\", \"green\");\n // Util.glowContainer(\"sc-coordinate-nad27-y\", \"green\");\n }",
"function injectStyle() {\n // Inject once for all the instances\n if (!styleInjected) {\n var style = document.createElement('style');\n style.innerHTML = '\\n .react-swipeable-view-container {\\n display: -webkit-box;\\n display: -ms-flexbox;\\n }\\n .react-swipeable-view-container > div {\\n -ms-flex-negative: 0;\\n }\\n ';\n\n if (document.body) {\n document.body.appendChild(style);\n }\n styleInjected = true;\n }\n}",
"function injectStyle() {\n // Inject once for all the instances\n if (!styleInjected) {\n var style = document.createElement('style');\n style.innerHTML = '\\n .react-swipeable-view-container {\\n display: -webkit-box;\\n display: -ms-flexbox;\\n }\\n .react-swipeable-view-container > div {\\n -ms-flex-negative: 0;\\n }\\n ';\n\n if (document.body) {\n document.body.appendChild(style);\n }\n styleInjected = true;\n }\n}",
"function injectStyle() {\n // Inject once for all the instances\n if (!styleInjected) {\n var style = document.createElement('style');\n style.innerHTML = '\\n .react-swipeable-view-container {\\n display: -webkit-box;\\n display: -ms-flexbox;\\n }\\n .react-swipeable-view-container > div {\\n -ms-flex-negative: 0;\\n }\\n ';\n\n if (document.body) {\n document.body.appendChild(style);\n }\n styleInjected = true;\n }\n}",
"function injectStyle() {\n // Inject once for all the instances\n if (!styleInjected) {\n var style = document.createElement('style');\n style.innerHTML = '\\n .react-swipeable-view-container {\\n display: -webkit-box;\\n display: -ms-flexbox;\\n }\\n .react-swipeable-view-container > div {\\n -ms-flex-negative: 0;\\n }\\n ';\n\n if (document.body) {\n document.body.appendChild(style);\n }\n styleInjected = true;\n }\n}",
"function initStyle() {\n\n\t\t// +jquery ui css + images\n\t\tvar jqUI_CSS = GM_getResourceText(\"jqUI_CSS\"),\n\t\treg,\n\t\tresources = {\n\t\t\t'animated-overlay.gif' : GM_getResourceURL('jqui_img01'),\n\t\t\t'ui-bg_diagonals-thick_18_b81900_40x40.png' : GM_getResourceURL('jqui_img02'),\n\t\t\t'ui-bg_diagonals-thick_20_666666_40x40.png' : GM_getResourceURL('jqui_img03'),\n\t\t\t'ui-bg_flat_10_000000_40x100.png' : GM_getResourceURL('jqui_img04'),\n\t\t\t'ui-bg_glass_65_ffffff_1x400.png' : GM_getResourceURL('jqui_img05'),\n\t\t\t'ui-bg_glass_100_f6f6f6_1x400.png' : GM_getResourceURL('jqui_img06'),\n\t\t\t'ui-bg_glass_100_fdf5ce_1x400.png' : GM_getResourceURL('jqui_img07'),\n\t\t\t'ui-bg_gloss-wave_35_f6a828_500x100.png' : GM_getResourceURL('jqui_img08'),\n\t\t\t'ui-bg_highlight-soft_75_ffe45c_1x100.png' : GM_getResourceURL('jqui_img09'),\n\t\t\t'ui-bg_highlight-soft_100_eeeeee_1x100.png' : GM_getResourceURL('jqui_img10'),\n\t\t\t'ui-icons_228ef1_256x240.png' : GM_getResourceURL('jqui_img11'),\n\t\t\t'ui-icons_222222_256x240.png' : GM_getResourceURL('jqui_img12'),\n\t\t\t'ui-icons_ef8c08_256x240.png' : GM_getResourceURL('jqui_img13'),\n\t\t\t'ui-icons_ffd27a_256x240.png' : GM_getResourceURL('jqui_img14'),\n\t\t\t'ui-icons_ffffff_256x240.png' : GM_getResourceURL('jqui_img15')\n\t\t};\n\n\t\t//jqUI_CSS = jqUI_CSS.replace (/images\\//g, \"\");\n\t\t$.each(resources, function (resName, resUrl) {\n\t\t\t//console.log(resourceName + ': ' + resourceUrl);\n\t\t\treg = new RegExp('images/' + resName, \"g\"); // replaceAll\n\t\t\tjqUI_CSS = jqUI_CSS.replace(reg, resUrl);\n\t\t});\n\n\t\t// adding styles:\n\t\tGM_addStyle((\"\" +\n\t\t\t\t/* on GS public profile page jqUI_CSS forces the boxes with owned caches/trackables to be shown at the bottom of the page;\n\t\t\t\tsince jqUI_CSS seems to only affect the GS public profile page it's safe to be removed */\n\t\t\t\t//jqUI_CSS+\"\"+\n\t\t\t\t\"/*\" +\n\t\t\t\t\"* GCTourNG - Container\" +\n\t\t\t\t\"*/\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#gctourngButtonWrapper {\" +\n\t\t\t\t\" height: 32px !important;\" +\n\t\t\t\t\" padding: 0 !important;\" +\n\t\t\t\t\" position: fixed !important;\" +\n\t\t\t\t\" top: 30px !important;\" +\n\t\t\t\t\" width: 35px !important;\" +\n\t\t\t\t\" background-color: #fff;\" +\n\t\t\t\t\" z-index: 1001 !important;\" +\n\t\t\t\t\" border: 1px solid #333;\" +\n\t\t\t\t\" border-width: 1px 1px 1px 0;\" +\n\t\t\t\t\" border-radius: 0 5px 5px 0;\" +\n\t\t\t\t\" -moz-user-select: none;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#gctourngButtonWrapper img {\" +\n\t\t\t\t\" position: relative;\" +\n\t\t\t\t\" top: 8px;\" +\n\t\t\t\t\" left: 8px;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#gctourngContainer {\" +\n\t\t\t\t\" background-color: #fff;\" +\n\t\t\t\t\" overflow: hidden;\" +\n\t\t\t\t\" left: -210px;\" +\n\t\t\t\t\" padding: 0 !important;\" +\n\t\t\t\t\" position: fixed !important;\" +\n\t\t\t\t\" top: 30px !important;\" +\n\t\t\t\t\" width: 200px;\" +\n\t\t\t\t\" z-index: 1002 !important;\" +\n\t\t\t\t\" border: 1px solid #333;\" +\n\t\t\t\t\" border-left: 0px;\" +\n\t\t\t\t\" border-radius: 0 5px 5px 0;\" +\n\t\t\t\t\" font-size: 12px;\" +\n\t\t\t\t\" font-family: Arial;\" +\n\t\t\t\t\" line-height: 1.5;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#gctourngContainer .cachelist {\" +\n\t\t\t\t\" width: 100%;\" +\n\t\t\t\t\" margin: 0;\" +\n\t\t\t\t\" padding:0;\" +\n\t\t\t\t\" font-size:80%;\" +\n\t\t\t\t\" list-style-type:none;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#gctourngContainer .cachelist li {\" +\n\t\t\t\t\" color:#000;\" +\n\t\t\t\t\" margin:0.5em;\" +\n\t\t\t\t\" padding:3px;\" +\n\t\t\t\t\" width:120px;\" +\n\t\t\t\t\" min-height:44px;\" +\n\t\t\t\t\" list-style-position:inside;\" +\n\t\t\t\t\" border:1pt dashed gray;\" +\n\t\t\t\t\" background-color:#FFF;\" +\n\t\t\t\t\" -moz-background-clip:border;\" +\n\t\t\t\t\" -moz-background-inline-policy:continuous;\" +\n\t\t\t\t\" -moz-background-origin:padding;\" +\n\t\t\t\t\" -moz-border-radius:8px 0 8px 0;\" +\n\t\t\t\t\" border-radius:8px 0 8px 0;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#gctourngContainer img.imgShadow {\" +\n\t\t\t\t\" -moz-box-shadow: 0 0 4px 2px rgba(0, 0, 0, 0.2);\" +\n\t\t\t\t\" box-shadow: 0 0 4px 2px rgba(0, 0, 0, 0.2);\" +\n\t\t\t\t\" background-color: lightgray;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#gctourngContainer img.tourImage {\" +\n\t\t\t\t\" cursor: pointer;\" +\n\t\t\t\t\" margin: 0 2px 0 2px;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"/* Styling the placeholder for when the user starts dragging an item */\" +\n\t\t\t\t\"#gctourngContainer li.ui-sortable-placeholder {\" +\n\t\t\t\t\" min-height:50px;\" +\n\t\t\t\t\" max-height:80px;\" +\n\t\t\t\t\" width: 90%;\" +\n\t\t\t\t\" background-color: rgba(0, 0, 0, 0.03);\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"/*\" +\n\t\t\t\t\"* GCTourNG - Grand\" +\n\t\t\t\t\"*/\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gctourng-grand-default {\" +\n\t\t\t\t\" /* http://www.colorzilla.com/gradient-editor/#a7cfef+0,c9dded+3,ffffff+10;gctourng-grand-default\" +\n\t\t\t\t\" * http://css3please.com/\" +\n\t\t\t\t\" */\" +\n\t\t\t\t\" background: rgb(167,207,239); /* Old browsers */\" +\n\t\t\t\t\" background: -moz-linear-gradient(top, rgba(167,207,239,1) 0%, rgba(201,221,237,1) 3px, rgba(255,255,255,1) 10px); /* FF3.6+ */\" +\n\t\t\t\t\" background: -webkit-linear-gradient(top, rgba(167,207,239,1) 0%,rgba(201,221,237,1) 3px,rgba(255,255,255,1) 10px); /* Chrome10+,Safari5.1+ */\" +\n\t\t\t\t\" background: -o-linear-gradient(top, rgba(167,207,239,1) 0%,rgba(201,221,237,1) 3px,rgba(255,255,255,1) 10px); /* Opera 11.10+ */\" +\n\t\t\t\t\" background: linear-gradient(top, rgba(167,207,239,1) 0%,rgba(201,221,237,1) 3px,rgba(255,255,255,1) 10px); /* W3C */\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gctourng-grand-hover {\" +\n\t\t\t\t\" /* http://www.colorzilla.com/gradient-editor/#ffad32+0,ffd699+3,ffffff+10;gctourng-grand-hover */\" +\n\t\t\t\t\" background: rgb(255,173,50); /* Old browsers */\" +\n\t\t\t\t\" background: -moz-linear-gradient(top, rgba(255,173,50,1) 0%, rgba(255,214,153,1) 3px, rgba(255,255,255,1) 10px); /* FF3.6+ */\" +\n\t\t\t\t\" background: -webkit-linear-gradient(top, rgba(255,173,50,1) 0%,rgba(255,214,153,1) 3px,rgba(255,255,255,1) 10px); /* Chrome10+,Safari5.1+ */\" +\n\t\t\t\t\" background: -o-linear-gradient(top, rgba(255,173,50,1) 0%,rgba(255,214,153,1) 3px,rgba(255,255,255,1) 10px); /* Opera 11.10+ */\" +\n\t\t\t\t\" background: linear-gradient(top, rgba(255,173,50,1) 0%,rgba(255,214,153,1) 3px,rgba(255,255,255,1) 10px); /* W3C */\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gctourng-grand-highlight {\" +\n\t\t\t\t\" /* http://www.colorzilla.com/gradient-editor/#ffe000+0,ffee7f+3,ffffff+10;gctourng-grand-highlight */\" +\n\t\t\t\t\" background: rgb(255,224,0); /* Old browsers */\" +\n\t\t\t\t\" background: -moz-linear-gradient(top, rgba(255,224,0,1) 0%, rgba(255,238,127,1) 3px, rgba(255,255,255,1) 10px); /* FF3.6+ */\" +\n\t\t\t\t\" background: -webkit-linear-gradient(top, rgba(255,224,0,1) 0%,rgba(255,238,127,1) 3px,rgba(255,255,255,1) 10px); /* Chrome10+,Safari5.1+ */\" +\n\t\t\t\t\" background: -o-linear-gradient(top, rgba(255,224,0,1) 0%,rgba(255,238,127,1) 3px,rgba(255,255,255,1) 10px); /* Opera 11.10+ */\" +\n\t\t\t\t\" background: linear-gradient(top, rgba(255,224,0,1) 0%,rgba(255,238,127,1) 3px,rgba(255,255,255,1) 10px); /* W3C */\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gctourng-grand-active {\" +\n\t\t\t\t\" /* Grün http://www.colorzilla.com/gradient-editor/#3dff32+0,9eff99+3,ffffff+10;gctourng-grand-active */\" +\n\t\t\t\t\" background: rgb(61,255,50); /* Old browsers */\" +\n\t\t\t\t\" background: -moz-linear-gradient(top, rgba(61,255,50,1) 0%, rgba(158,255,153,1) 3px, rgba(255,255,255,1) 10px); /* FF3.6+ */\" +\n\t\t\t\t\" background: -webkit-linear-gradient(top, rgba(61,255,50,1) 0%,rgba(158,255,153,1) 3px,rgba(255,255,255,1) 10px); /* Chrome10+,Safari5.1+ */\" +\n\t\t\t\t\" background: linear-gradient(top, rgba(61,255,50,1) 0%,rgba(158,255,153,1) 3px,rgba(255,255,255,1) 10px); /* W3C */$$$$\" +\n\t\t\t\t\" background: -o-linear-gradient(top, rgba(61,255,50,1) 0%,rgba(158,255,153,1) 3px,rgba(255,255,255,1) 10px); /* Opera 11.10+ */\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gctourng-grand-error {\" +\n\t\t\t\t\" /* http://www.colorzilla.com/gradient-editor/#ff3232+0,ff9999+3,ffffff+10;gctourng-grand-error */\" +\n\t\t\t\t\" background: rgb(255,50,50); /* Old browsers */\" +\n\t\t\t\t\" background: -moz-linear-gradient(top, rgba(255,50,50,1) 0%, rgba(255,153,153,1) 3px, rgba(255,255,255,1) 10px); /* FF3.6+ */\" +\n\t\t\t\t\" background: -webkit-linear-gradient(top, rgba(255,50,50,1) 0%,rgba(255,153,153,1) 3px,rgba(255,255,255,1) 10px); /* Chrome10+,Safari5.1+ */\" +\n\t\t\t\t\" background: -o-linear-gradient(top, rgba(255,50,50,1) 0%,rgba(255,153,153,1) 3px,rgba(255,255,255,1) 10px); /* Opera 11.10+ */\" +\n\t\t\t\t\" background: linear-gradient(top, rgba(255,50,50,1) 0%,rgba(255,153,153,1) 3px,rgba(255,255,255,1) 10px); /* W3C */\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"/*\" +\n\t\t\t\t\"* GCTourNG Slider\" +\n\t\t\t\t\"*/\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gct_scrollbar {\" +\n\t\t\t\t\" background-color:pink;\" +\n\t\t\t\t\" height: 20px;\" +\n\t\t\t\t\" left: 0;\" +\n\t\t\t\t\" position: absolute;\" +\n\t\t\t\t\" top: 0;\" +\n\t\t\t\t\" width: 100%;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gct_scroller{\" +\n\t\t\t\t\" background-color:lime;\" +\n\t\t\t\t\" height: 20px;\" +\n\t\t\t\t\" left: 0;\" +\n\t\t\t\t\" position: absolute;\" +\n\t\t\t\t\" top: 0;\" +\n\t\t\t\t\" width: 20px; \" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"/*\" +\n\t\t\t\t\" * GCTourNG Pop-Up\" +\n\t\t\t\t\" */\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gct_popup{\" +\n\t\t\t\t\" position:absolute;\" +\n\t\t\t\t\" z-index:10; \" +\n\t\t\t\t\" width:172px;\" +\n\t\t\t\t\" height:102px;\" +\n\t\t\t\t\" text-align:center;\" +\n\t\t\t\t\" color:#FF0000;\" +\n\t\t\t\t\" font: 14px Verdana, Arial, Helvetica, sans-serif;\" +\n\t\t\t\t\" background-color:lime;\" +\n\t\t\t\t\" border-radius: 5px;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gct_popup_header{\" +\n\t\t\t\t\" border-radius: 5px 5px 0px 0px;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogMask {\" +\n\t\t\t\t\" background-image:url(##dialogMaskImage##);\" +\n\t\t\t\t\" height:100%;\" +\n\t\t\t\t\" left:0;\" +\n\t\t\t\t\" opacity:0.7;\" +\n\t\t\t\t\" position:fixed;\" +\n\t\t\t\t\" top:0;\" +\n\t\t\t\t\" width:100%;\" +\n\t\t\t\t\" z-index:1100;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogBody {\" +\n\t\t\t\t\" -moz-border-radius:5px;\" +\n\t\t\t\t\" border-radius:5px;\" +\n\t\t\t\t\" background:none repeat scroll 0 0 #fff;\" +\n\t\t\t\t\" border:1px solid #333333;\" +\n\t\t\t\t\" color:#333333;\" +\n\t\t\t\t\" cursor:default;\" +\n\t\t\t\t\" font-family:Arial;\" +\n\t\t\t\t\" font-size:12px;\" +\n\t\t\t\t\" left:50%;\" +\n\t\t\t\t\" margin-left:-250px;\" +\n\t\t\t\t\" margin-top:20px;\" +\n\t\t\t\t\" padding:0 0 1em;\" +\n\t\t\t\t\" position:fixed;\" +\n\t\t\t\t\" text-align:left;\" +\n\t\t\t\t\" top:0;\" +\n\t\t\t\t\" width:600px;\" +\n\t\t\t\t\" z-index:1101;\" +\n\t\t\t\t\" max-height:85%;\" +\n\t\t\t\t\" min-height:440px;\" +\n\t\t\t\t\" overflow:auto;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogBody p {\" +\n\t\t\t\t\" font-size:12px;\" +\n\t\t\t\t\" font-weight:normal;\" +\n\t\t\t\t\" margin:1em 0;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".header h1 {\" +\n\t\t\t\t\" background-color:#B2D4F3;\" +\n\t\t\t\t\" background-repeat:repeat-x;\" +\n\t\t\t\t\" font-size:110% !important;\" +\n\t\t\t\t\" font-family:Helvetica Neue,Arial,Helvetica,sans-serif;\" +\n\t\t\t\t\" margin-bottom:0.2em;\" +\n\t\t\t\t\" margin-top:0;\" +\n\t\t\t\t\" padding:0.5em;\" +\n\t\t\t\t\" -moz-border-radius: 5px 5px 0 0;\" +\n\t\t\t\t\" border-radius: 5px 5px 0 0;\" +\n\t\t\t\t\" color:#333333;\" +\n\t\t\t\t\" background-image:url(##tabBgImage##)\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"/*\" +\n\t\t\t\t\".dialogBody h1 {\" +\n\t\t\t\t\" background-color:#7A7A7A;\" +\n\t\t\t\t\" border-bottom:1px solid #333333;\" +\n\t\t\t\t\" font-size:110%;\" +\n\t\t\t\t\" font-family:Helvetica Neue,Arial,Helvetica,sans-serif;\" +\n\t\t\t\t\" margin-bottom:0.2em;\" +\n\t\t\t\t\" padding:0.5em;\" +\n\t\t\t\t\" -moz-border-radius:5px 5px 0px 0px;\" +\n\t\t\t\t\" border-radius:5px 5px 0px 0px;\" +\n\t\t\t\t\" color:#fff;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"*/\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogHistory {\" +\n\t\t\t\t\" border:1px inset #999999;\" +\n\t\t\t\t\" margin:0 1em 1em;\" +\n\t\t\t\t\" padding-bottom: 1em;\" +\n\t\t\t\t\" max-height: 200px;\" +\n\t\t\t\t\" overflow-y:auto;\" +\n\t\t\t\t\" width:518px;\" +\n\t\t\t\t\" padding-left:1em;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogHistory ul {\" +\n\t\t\t\t\" margin-left:2em;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogHistory li {\" +\n\t\t\t\t\" list-style-type:circle;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogFooter input {\" +\n\t\t\t\t\" -moz-border-radius:3px;\" +\n\t\t\t\t\" border-radius:3px;\" +\n\t\t\t\t\" background:none no-repeat scroll 4px center #EEEEEE;\" +\n\t\t\t\t\" border:1px outset #666666;\" +\n\t\t\t\t\" cursor:pointer;\" +\n\t\t\t\t\" float:right;\" +\n\t\t\t\t\" margin-left:0.5em;\" +\n\t\t\t\t\" padding:3px 5px 5px 20px;\" +\n\t\t\t\t\" min-width:100px;\" +\n\t\t\t\t\" font-size: 12px;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogFooter input:hover {\" +\n\t\t\t\t\" background-color:#f9f9f9;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogContent {\" +\n\t\t\t\t\" padding:0 10px 0 10px;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogMin {\" +\n\t\t\t\t\" min-height:0 !important\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"/* neuer Dialog-Style mit jQuery-ui + gcTour Header (.gct_dialog) */\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gct_dialog {\" +\n\t\t\t\t\" font-size: 10pt;\" +\n\t\t\t\t\" font-family: Arial;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".gct_dialog .ui-widget {\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".gct_dialog.ui-dialog {\" +\n\t\t\t\t\" padding: 0;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".gct_dialog.ui-dialog .ui-widget-header {\" +\n\t\t\t\t\" border: 0;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".gct_dialog.ui-dialog .ui-dialog-titlebar {\" +\n\t\t\t\t\" padding: 0.2em 0.1em;\" +\n\t\t\t\t\" background: -moz-linear-gradient(center top, #A7CFEF 0%, #C9DDED 3px, #FFFFFF 10px) repeat scroll 0 0 transparent;\" +\n\t\t\t\t\" color: #000;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".gct_dialog.ui-dialog .ui-dialog-title {\" +\n\t\t\t\t\" padding-top: 4px;\" +\n\t\t\t\t\" text-align: left;\" +\n\t\t\t\t\" padding-left: 120px;\" +\n\t\t\t\t\" width: 75%;\" +\n\t\t\t\t\" background: url(##gctourngLogo##) 2px 2px no-repeat;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".gct_dialog.ui-dialog .ui-dialog-buttonpane {\" +\n\t\t\t\t\" padding: 0 0.4em 0 0.4em;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".gct_dialog .ui-button-text-only .ui-button-text {\" +\n\t\t\t\t\" padding: 0.2em 0.8em;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".gct_dialog .ui-progressbar .ui-progressbar-value {\" +\n\t\t\t\t\" margin: 0;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".gct_dialog .progressbar-label {\" +\n\t\t\t\t\" width: 80%;\" +\n\t\t\t\t\" text-align: center;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#dialogDetails {\" +\n\t\t\t\t\" height:364px;\" +\n\t\t\t\t\" padding:3px;\" +\n\t\t\t\t\" overflow:auto;\" +\n\t\t\t\t\" background-color:#eff4f9;\" +\n\t\t\t\t\" border:1px solid #C0CEE3;\" +\n\t\t\t\t\" -moz-border-radius: 0 5px 5px 0;\" +\n\t\t\t\t\" width:424px;\" +\n\t\t\t\t\" position: absolute;\" +\n\t\t\t\t\" right: 10px;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogList li {\" +\n\t\t\t\t\" font-size:10px;\" +\n\t\t\t\t\" padding:3px;\" +\n\t\t\t\t\" clear:both;\" +\n\t\t\t\t\" list-style-type: none;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".dialogList {\" +\n\t\t\t\t\" margin:0;\" +\n\t\t\t\t\" padding:0\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".activeTour {\" +\n\t\t\t\t\" border: 1px solid #C0CEE3;\" +\n\t\t\t\t\" -moz-border-radius: 5px 0 0 5px;\" +\n\t\t\t\t\" border-radius: 5px 0 0 5px;\" +\n\t\t\t\t\" background-color:#eff4f9;\" +\n\t\t\t\t\" padding:1px;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"#dialogListContainer {\" +\n\t\t\t\t\" height:374px;\" +\n\t\t\t\t\" overflow:auto;\" +\n\t\t\t\t\" width:146px;\" +\n\t\t\t\t\" position: absolute;\" +\n\t\t\t\t\" left: 10px;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".unselectable {\" +\n\t\t\t\t\" -o-user-select: none;\" +\n\t\t\t\t\" -webkit-user-select: none;\" +\n\t\t\t\t\" -moz-user-select: -none;\" +\n\t\t\t\t\" -khtml-user-select: none;\" +\n\t\t\t\t\" user-select: none;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#cacheList .counter {\" +\n\t\t\t\t\" position:absolute;\" +\n\t\t\t\t\" right:4px;\" +\n\t\t\t\t\" bottom: 0;\" +\n\t\t\t\t\" z-index:0;\" +\n\t\t\t\t\" overflow:hidden;\" +\n\t\t\t\t\" font: normal 24px arial,sans-serif;\" +\n\t\t\t\t\" color: #d5d5d5;\" +\n\t\t\t\t\" text-align:right;\" +\n\t\t\t\t\" text-shadow: 1px 1px 1px #C0C0C0;\" +\n\t\t\t\t\" vertical-align: text-bottom;\" +\n\t\t\t\t\" background-color: transparent;\" +\n\t\t\t\t\" margin-right:0;\" +\n\t\t\t\t\" margin-bottom:0;\" +\n\t\t\t\t\" padding: 0;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#gctourng-notification-box {\" +\n\t\t\t\t\" position: fixed;\" +\n\t\t\t\t\" right: 4px;\" +\n\t\t\t\t\" bottom: 2%;\" +\n\t\t\t\t\" width: 220px;\" +\n\t\t\t\t\" height: auto;\" +\n\t\t\t\t\" max-height: 96%;\" +\n\t\t\t\t\" overflow: hidden;\" +\n\t\t\t\t\" overflow-y: auto;\" +\n\t\t\t\t\" list-style-type: none;\" +\n\t\t\t\t\" margin: 0;\" +\n\t\t\t\t\" padding: 0;\" +\n\t\t\t\t\" z-index: 1100;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"#gctourng-notification-box li {\" +\n\t\t\t\t\" overflow: hidden;\" +\n\t\t\t\t\" background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAoCAYAAAAPOoFWAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPZJREFUeNq81tsOgjAMANB2ov7/7ypaN7IlIwi9rGuT8QSc9EIDAsAznxvY4pXPKr05RUE5MEVB+TyWfCEl9LZApYopCmo9C4FKSMtYoI8Bwv79aQJU4l6hXXCZrQbokJEksxHo9KMOgc6w1atHXM8K9DVC7FQnJ0i8iK3QooGgbnyKgMDygBWyYFZoqx4qS27KqLZJjA1D0jK6QJcYEQEiWv9PGkTsbqxQ8oT+ZtZB6AkdsJnQDnMoHXHLGKOgDYuCWmYhEERCI5gaamW0bnHdA3k2ltlIN+2qKRyCND0bhqSYCyTB3CAOc4WusBEIpkeBuPgJMAAX8Hs1NfqHRgAAAABJRU5ErkJggg==');\" +\n\t\t\t\t\" background-repeat: repeat-x;\" +\n\t\t\t\t\" background-attachment: scroll;\" +\n\t\t\t\t\" background-position: left top;\" +\n\t\t\t\t\" box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.5);\" +\n\t\t\t\t\" width: 220px;\" +\n\t\t\t\t\" cursor: pointer;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gctourng-notification-green {\" +\n\t\t\t\t\" background-color: lightgreen;\" +\n\t\t\t\t\" color: #000000;\" +\n\t\t\t\t\" border: 1px solid #50C24E;\" +\n\t\t\t\t\" text-shadow: 0 1px 0 #FFFFFF;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gctourng-notification-red {\" +\n\t\t\t\t\" background-color: red;\" +\n\t\t\t\t\" border: 1px solid #8B0000;\" +\n\t\t\t\t\" color: #FFFFFF;\" +\n\t\t\t\t\" text-shadow: 0 1px 0 #000000;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gctourng-notification-blue {\" +\n\t\t\t\t\" background-color: #57B7E2;\" +\n\t\t\t\t\" border: 1px solid #0B90C4;\" +\n\t\t\t\t\" color: #000000;\" +\n\t\t\t\t\" text-shadow: 0 1px 0 #FFFFFF;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gctourng-notification-yellow {\" +\n\t\t\t\t\" background-color: #FFFC00;\" +\n\t\t\t\t\" border: 1px solid #FFC237;\" +\n\t\t\t\t\" color: #000000;\" +\n\t\t\t\t\" text-shadow: 0 1px 0 #FFFFFF;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"/*\" +\n\t\t\t\t\"* jquery ui overwrite\" +\n\t\t\t\t\"*/\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".ui-front {\" +\n\t\t\t\t\" z-index: 1100 !important;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".ui-button-icon-only .ui-icon {\" +\n\t\t\t\t\" margin-top: -8px !important;\" +\n\t\t\t\t\" margin-left: -8px !important;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".gct .ui-widget-content {\" +\n\t\t\t\t\" background: #FFFFFF;\" +\n\t\t\t\t\" /* border: 0; */\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\".ui-button-text-only .ui-button-text {\" +\n\t\t\t\t\" padding: .2em .6em;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\"input.ui-button {\" +\n\t\t\t\t\" padding: .2em .6em;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t\"\" +\n\t\t\t\t\".ui-dialog .ui-dialog-buttonpane {\" +\n\t\t\t\t\" margin-top: 0;\" +\n\t\t\t\t\"}\" +\n\t\t\t\t +\n\t\t\t\t\"\")\n\t\t\t.replace(\"##gctourngLogo##\", $.gctourng.img.gctourngLogo)\n\t\t\t.replace(\"##dialogMaskImage##\", $.gctourng.img.dialogMask)\n\t\t\t.replace(\"##tabBgImage##\", $.gctourng.img.tabBg));\n\n\t}",
"function ProcessManagementComponentStyle()\r\n{\r\n this.initByNamespace(\"pm\");\r\n}",
"setStyle() {\n let ratio = this.items.length / this.slidesVisible;\n this.container.style.width = (ratio * 100) + \"%\";\n\n // Aligner les item en affectant une width en fonction du nombre de slides visibles\n this.items.forEach(item => item.style.width = (100 / this.slidesVisible) / ratio + \"%\");\n\n switch (this.options.anime) {\n case 'translateX': this.container.style.display = 'flex'; break;\n case 'translateY':\n this.container.style.display = 'block';\n this.root.style.height = this.container.firstChild.offsetHeight + 'px';\n this.container.children.forEach((item) => {\n item.classList.remove('carousel__item');\n });\n this.spacial_setColorBackground();\n break;\n }\n }",
"function defineCssClassStyles(){\n\n\tvar generalCss = \"\\\n\thtml, body\\\n\t\t{overflow:hidden !important; padding:0; margin:0; max-width:100%;}\\\n\t.ANDI508\\\n\t\t{background-color:black !important; color:white !important; box-shadow:0 0 20px 0 gray; padding:4px; margin:0; height:auto; position:fixed; top:0; left:0; z-index:9999; display:block; width:100%; border-radius:0;}\\\n\t#ANDI508 *, #ANDI508 h1, #ANDI508 h4, #ANDI508 h3, #ANDI508 div, #ANDI508 span, #ANDI508 ul, #ANDI508 li, #ANDI508 a, #ANDI508 p, #ANDI508 button \\\n\t\t{font:normal normal normal 10pt/normal Verdana; line-height:normal; letter-spacing:normal; text-align:left;\\\n\t\t background:black !important; color:white !important; appearance:normal; text-transform:none; opacity:1 !important;\\\n\t\t margin:0; padding:0; border:none; border-radius:0; left:0; top:0; vertical-align:baseline; float:none;\\\n\t\t width:auto; height:auto; min-width:0; max-width:none; min-height:0; max-height:none; overflow:visible; transform:none;}\\\n\t#ANDI508 img\\\n\t\t{box-shadow:none;}\\\n\t#ANDI508 *[tabindex]:focus, #ANDI508 a:focus, #ANDI508 button:focus\\\n\t\t{outline:1px solid #dedab7 !important; box-shadow:0 0 6px 0 #dedab7;}\\\n\t#ANDI508 *::before, #ANDI508 *:before, #ANDI508 *::after, #ANDI508 *:after\\\n\t\t{content:none}\\\n\t#ANDI508 a\\\n\t\t{text-decoration:none;}\\\n\t#ANDI508 a:hover, #ANDI508 a:active\\\n\t\t{text-decoration:underline; font-family:'Verdana'; background:none;}\\\n\t#ANDI508 .ANDI508-heading\\\n\t\t{font-size:12pt; color:white !important; white-space:nowrap; margin:0; display:inline; position:relative; }\\\n\t#ANDI508 .ANDI508-heading a, #ANDI508 .ANDI508-heading a:hover, #ANDI508 .ANDI508-heading span, #ANDI508 .ANDI508-heading a *\\\n\t\t{font-size:12pt; color:white !important; font-weight:normal;}\\\n\t#ANDI508 .ANDI508-screenReaderOnly\\\n\t\t{height:0; width:0px; overflow:hidden; position:absolute;}\\\n\t\";\n\n\tvar majorSectionsCss = \"\\\n\t#ANDI508 #ANDI508-toolName\\\n\t\t{font-family:Verdana; font-size:20pt; font-weight:bold; color:white !important; margin:0 5px 1px 5px; float:left; cursor:pointer; text-shadow: 1px 1px 3px #808080;}\\\n\t#ANDI508 #ANDI508-toolName:hover\\\n\t\t{text-decoration:none !important;}\\\n\t#ANDI508 #ANDI508-header\\\n\t\t{float:left; width:100%; display:inline-block; position:relative;}\\\n\t#ANDI508 #ANDI508-header h1\\\n\t\t{position:absolute;}\\\n\t#ANDI508 #ANDI508-activeElementInspection\\\n\t\t{min-width:300px; width:40%; padding-left:3%; float:left; display:inline-block; min-height:2em; margin-top:2px;}\\\n\t#ANDI508 #ANDI508-pageAnalysis\\\n\t\t{width: 50%; float:left; padding-left:3%; display:inline-block; margin-bottom:5px; background-color:black !important;}\\\n\t#ANDI508-testPage\\\n\t\t{padding-left:5px; overflow-y:auto; overflow-x:hidden; position:relative; top:0; width:100%;}\\\n\t\";\n\t\n\tvar hokeyListCss = \"\\\n\t#ANDI508 #ANDI508-hotkeyList\\\n\t\t{display:none; position:absolute; top:2.5em; left:60px; border:1px solid gray; padding-right:1em; padding-left:5px; z-index:1;}\\\n\t#ANDI508 #ANDI508-hotkeyList li\\\n\t\t{font-size:8pt; list-style-type: none !important;}\\\n\t#ANDI508 #ANDI508-hotkeyList .ANDI508-code\\\n\t\t{font-family:monospace; font-size:10pt;}\\\n\t\";\n\t\t\n\tvar lasersCss = \"\\\n\t#ANDI508-laser-container\\\n\t\t{position:absolute; top:0; z-index:9998; display:none; background:none;}\\\n\t#ANDI508-laser, #ANDI508-lasers\\\n\t\t{stroke:deeppink; stroke-width:3}\\\n\t#ANDI508 .ANDI508-laserTarget\\\n\t\t{cursor:default;}\\\n\t\";\n\n\tvar accesskeysCss = \"\\\n\t#ANDI508 #ANDI508-accesskeysFound\\\n\t\t{margin-left:3%; display:none; white-space:nowrap; margin-top:1px;}\\\n\t#ANDI508 #ANDI508-accesskeysFound a, #ANDI508 #ANDI508-accesskeysFound a:visited, #ANDI508 #ANDI508-accesskeysFound a:active, #ANDI508 #ANDI508-accesskeysFound a:hover\\\n\t\t{color:white !important;}\\\n\t\";\n\n\tvar alertsCss = \"\\\n\t#ANDI508 #ANDI508-alerts-list\\\n\t\t{min-width:420px; width:80%; margin:0; clear:both; font-size:12pt; padding:0 5px 5px 0; display:none; margin-top:1px !important;}\\\n\t#ANDI508 li\\\n\t\t{margin:0 1px 2px 4%; line-height:120%;}\\\n\t#ANDI508 ul li\\\n\t\t{list-style:disc outside none; vertical-align:top;}\\\n\t#ANDI508 ol li\\\n\t\t{list-style:decimal outside none;}\\\n\t#ANDI508 ol\\\n\t\t{margin:0 0 5px 0;}\\\n\t#ANDI508 li, #ANDI508 li a, #ANDI508 li a:hover, #ANDI508 li a:active, #ANDI508 li a:visited\\\n\t\t{font-size:9pt; font-weight:normal;}\\\n\t#ANDI508 #ANDI508-alerts-list img\\\n\t\t{width:16px; margin-right:3px;}\\\n\t\\\n\t#ANDI508 .ANDI508-display-danger, #ANDI508 .ANDI508-display-danger a, #ANDI508 .ANDI508-display-danger a:visited, #ANDI508 .ANDI508-display-danger a:active, #ANDI508 .ANDI508-display-danger a:hover, #ANDI508 .ANDI508-display-danger span\\\n\t\t{color:#ff6767 !important;}\\\n\t#ANDI508 .ANDI508-display-warning, #ANDI508 .ANDI508-display-warning a, #ANDI508 .ANDI508-display-warning a:visited, #ANDI508 .ANDI508-display-warning a:active, #ANDI508 .ANDI508-display-warning a:hover, #ANDI508 .ANDI508-display-warning span\\\n\t\t{color:#ffab2e !important;}\\\n\t#ANDI508 .ANDI508-display-caution, #ANDI508 .ANDI508-display-caution a, #ANDI508 .ANDI508-display-caution a:visited, #ANDI508 .ANDI508-display-caution a:active, #ANDI508 .ANDI508-display-caution a:hover, #ANDI508 .ANDI508-display-caution span\\\n\t\t{color:#ffffb9 !important;}\\\n\t\\\n\t#ANDI508 #ANDI508-alerts-container-scrollable\\\n\t\t{min-height:3.3em; max-height:10em; margin:3px 0 0 0; padding-top:1px; overflow-y:auto; overflow-x:hidden;\\\n\t\t scrollbar-arrow-color:#ff6767 !important; scrollbar-shadow-color:#ff6767 !important; scrollbar-face-color:black !important; scrollbar-highlight-color:black !important; scrollbar-track-color:black !important;}\\\n\t#ANDI508 #ANDI508-alerts-container-scrollable::-webkit-scrollbar\\\n\t\t{width:1em;}\\\n\t#ANDI508 #ANDI508-alerts-container-scrollable::-webkit-scrollbar-track\\\n\t\t{background-color:black;border:1px solid #ff6767}\\\n\t#ANDI508 #ANDI508-alerts-container-scrollable::-webkit-scrollbar-thumb\\\n\t\t{background:#ff6767;}\\\n\t\\\n\t#ANDI508 .ANDI508-alertGroup-container\\\n\t\t{display:none;}\\\n\t#ANDI508 .ANDI508-alertGroup-container h4\\\n\t\t{margin-bottom:2px;}\\\n\t#ANDI508 .ANDI508-alertGroup-list\\\n\t\t{margin-top:3px; margin-left:1.5em; display:none;}\\\n\t#ANDI508 a.ANDI508-alertGroup-toggler, #ANDI508 a.ANDI508-alertGroup-toggler:visited, #ANDI508 a.ANDI508-alertGroup-toggler:active, #ANDI508 a.ANDI508-alertGroup-toggler:hover\\\n\t\t{font-size:10pt; padding-bottom:1px;}\\\n\t\";\n\n\tvar buttonsCss = \"\\\n\t#ANDI508 #ANDI508-controls\\\n\t\t{padding-top:5px; position:relative; float:right; white-space:nowrap;}\\\n\t#ANDI508 .ANDI508-control-buttons-container\\\n\t\t{margin-right:1em;}\\\n\t#ANDI508 .ANDI508-control-buttons-container button\\\n\t\t{box-shadow: 1px 1px 2px 0px #808080; margin: 1px 1px 1px 0.6em !important; padding:0 !important}\\\n\t#ANDI508 .ANDI508-control-buttons-container button:hover\\\n\t\t{border:1px solid lemonchiffon !important}\\\n\t#ANDI508 .ANDI508-control-buttons-container button img\\\n\t\t{width:22px}\\\n\t#ANDI508 #ANDI508-button-relaunch, #ANDI508 #ANDI508-button-highlights, #ANDI508 #ANDI508-button-minimode, #ANDI508 #ANDI508-button-keys, #ANDI508 #ANDI508-button-help, #ANDI508 #ANDI508-button-close\\\n\t\t{border:1px solid gray; padding:0; text-align:center;\\\n\t\t font-weight:bold; display:inline !important; font-size:10pt; height:25px; width:25px}\\\n\t#ANDI508 #ANDI508-button-prevElement, #ANDI508 #ANDI508-button-nextElement\\\n\t\t{box-shadow:none; background:none; cursor:pointer; display:inline !important; margin-left:2px !important; padding:0 !important}\\\n\t#ANDI508 #ANDI508-button-prevElement\\\n\t\t{margin-right:2px !important;}\\\n\t#ANDI508 #ANDI508-button-nextElement\\\n\t\t{margin-right:4px; !important;}\\\n\t\";\n\n\tvar minimodeCss = \"\\\n\t#ANDI508 #ANDI508-outputContainer.ANDI508-minimode\\\n\t\t{display:inline !important}\\\n\t#ANDI508 #ANDI508-outputText.ANDI508-minimode\\\n\t\t{display:inline !important; margin-left:0;}\\\n\t#ANDI508 #ANDI508-activeElementInspection.ANDI508-minimode\\\n\t\t{width:100%; max-width:100%; margin-left:0;}\\\n\t#ANDI508 #ANDI508-tagNameContainer.ANDI508-minimode.ANDI508-tagNameContainer-visible\\\n\t\t{display:inline !important}\\\n\t\";\n\n\tvar activeElementInspectionCss = \"\\\n\t#ANDI508 #ANDI508-startUpSummary\\\n\t\t{font-size:11pt; margin-right:10px; margin-top:5px; padding-left:1em; height:5em; width:250px}\\\n\t#ANDI508 #ANDI508-tagNameContainer\\\n\t\t{white-space:nowrap; display:none; margin-bottom:1px;}\\\n\t#ANDI508 #ANDI508-tagNameContainer.ANDI508-tagNameContainer-visible\\\n\t\t{display:block;}\\\n\t#ANDI508 .ANDI508-code *, #ANDI508 .ANDI508-code a, #ANDI508 .ANDI508-code a:hover, #ANDI508 .ANDI508-code a:active\\\n\t\t{font-family:monospace; font-size:12pt; padding-bottom:2px;}\\\n\t\\\n\t#ANDI508 #ANDI508-accessibleComponentsTableContainer\\\n\t\t{visibility:hidden;}\\\n\t#ANDI508 #ANDI508-accessibleComponentsTable\\\n\t\t{width:97%; border-collapse:collapse; line-height:100%; margin-top:2px; margin-left:2%;}\\\n\t#ANDI508 #ANDI508-accessibleComponentsTable th\\\n\t\t{font:9pt Verdana !important; width:1%; text-align:right; border:none; vertical-align:top; padding:0; margin:0; white-space:nowrap;}\\\n\t#ANDI508 #ANDI508-accessibleComponentsTable td, #ANDI508 #ANDI508-accessibleComponentsTable td *{\\\n\t\tfont:9pt Tahoma !important; white-space:nowrap; display:inline-block;}\\\n\t#ANDI508 #ANDI508-accessibleComponentsTable td\\\n\t\t{overflow:hidden; text-overflow:ellipsis; max-width:430px; max-height:1.2em; border:none; vertical-align:top; padding:0 0 0 5px; margin:0;}\\\n\t#ANDI508 #ANDI508-accessibleComponentsTable-noData\\\n\t\t{text-align:left !important; color:#ff6767 !important; font-size:9pt; padding-left:0;}\\\n\t\\\n\t#ANDI508 #ANDI508-outputContainer .ANDI508-heading\\\n\t\t{margin-right:5px}\\\n\t#ANDI508 #ANDI508-outputContainer\\\n\t\t{margin-top:2px; margin-right:1px; display:none; padding:1px}\\\n\t#ANDI508 #ANDI508-outputText:hover\\\n\t\t{overflow:visible; display:block; z-index:9999; position:relative;}\\\n\t#ANDI508 #ANDI508-outputText\\\n\t\t{word-wrap:break-word; max-height:5em; line-height:0.5; display:block; overflow:hidden; margin-top:1px; padding:1px; margin-left:2%;\\\n\t\tpadding-left: 1.8em !important; background-size: 18px 18px !important; background-repeat: no-repeat !important; background-image: url(\"+icons_url+\"output.png) !important;}\\\n\t#ANDI508 #ANDI508-outputText span\\\n\t\t{font-size:10pt !important;}\\\n\t#ANDI508 #ANDI508-outputText img\\\n\t\t{width:16px; display:inline; margin-right:3px;}\\\n\t#ANDI508 #ANDI508-outputText .ANDI508-subtreeComponent\\\n\t\t{display:none;}\\\n\t#ANDI508 #ANDI508-outputIcon\\\n\t\t{width:16px;}\\\n\t\";\n\t\t\n\tvar componentsCss = \"\\\n\t#ANDI508 .ANDI508-display-legend, #ANDI508 .ANDI508-display-figcaption, #ANDI508 .ANDI508-display-caption\\\n\t\t{color:#e75dff !important}\\\n\t#ANDI508 .ANDI508-display-aria-label\\\n\t\t{color:#62ff8f !important}\\\n\t#ANDI508 .ANDI508-display-aria-labelledby, #ANDI508 .ANDI508-display-aria-labelledby *\\\n\t\t{color:#00e741 !important}\\\n\t#ANDI508 .ANDI508-display-aria-describedby, #ANDI508 .ANDI508-display-aria-describedby *\\\n\t\t{color:#00dae2 !important}\\\n\t#ANDI508 .ANDI508-display-label, #ANDI508 .ANDI508-display-alt, #ANDI508 .ANDI508-display-label *\\\n\t\t{color:#9fffba !important}\\\n\t#ANDI508 .ANDI508-display-title\\\n\t\t{color:#7cfbff !important}\\\n\t#ANDI508 .ANDI508-display-innerText, #ANDI508 .ANDI508-display-value\\\n\t\t{color:#c1c1c1 !important}\\\n\t#ANDI508 .ANDI508-display-imageSrc\\\n\t\t{color:#faebd7 !important}\\\n\t#ANDI508 .ANDI508-display-<subtree>\\\n\t\t{color:#ffffff !important}\\\n\t#ANDI508 .ANDI508-subtreeComponent\\\n\t\t{color: inherit !important}\\\n\t#ANDI508 .ANDI508-display-addOnProperties\\\n\t\t{color:#ffbdeb !important}\\\n\t\";\n\n\tvar elementCss = \"\\\n\t.ANDI508-element\\\n\t\t{opacity:1 !important;}\\\n\t.ANDI508-highlight.ANDI508-element\\\n\t\t{outline:2px dotted orange !important;}\\\n\t.ANDI508-highlight.ANDI508-element-danger\\\n\t\t{outline:2px dotted red !important;}\\\n\t.ANDI508-highlight.ANDI508-element-active\\\n\t\t{outline:4px solid deeppink !important;}\\\n\t\";\n\t\n\tvar andiCss = generalCss + majorSectionsCss + hokeyListCss + lasersCss + accesskeysCss + alertsCss + buttonsCss + minimodeCss + activeElementInspectionCss + componentsCss + elementCss;\n\tvar style = \"<style type='text/css' id='ANDI508-css'>\"+andiCss+\"</style>\";\n\t\n\t//If special css is needed for ie<=7, put it here:\n\tvar ie7Css = \"\\\n\t.ANDI508{background-color:black !important; display:inline-block;}\\\n\t#ANDI508-testPage\\\n\t\t{position:absolute; left:0; z-index:0}\\\n\t#ANDI508-testPage .ANDI508-highlight.ANDI508-element\\\n\t\t{border:2px dotted orange !important; outline:none;}\\\n\t#ANDI508-testPage .ANDI508-highlight.ANDI508-element-danger\\\n\t\t{border:2px dotted red !important; outline:none;}\\\n\t#ANDI508-testPage .ANDI508-highlight.ANDI508-element-active\\\n\t\t{border:3px solid deeppink !important; outline:none;}\\\n\t#ANDI508 #ANDI508-activeElementInspection\\\n\t\t{width:400px;}\\\n\t#ANDI508 #ANDI508-alerts-list\\\n\t\t{width:420px;}\\\n\t#ANDI508 ol li\\\n\t\t{list-style-type:disc;}\\\n\t#ANDI508 ul li, #ANDI508 #ANDI508-accesskeysFound\\\n\t\t{margin-left:1.3em}\\\n\t#ANDI508 #ANDI508-accessibleComponentsTable\\\n\t\t{margin-left:0;}\\\n\t\";\n\t//If special css is needed for ie<9, put it here:\n\tvar ie8Css = \"\\\n\t#ANDI508 #ANDI508-outputText\\\n\t\t{background-image: url(\"+icons_url+\"output18x18.png) !important;}\\\n\t#ANDI508-laser-container\\\n\t\t{height:0px; width:0px;}\\\n\t\";\n\tstyle += \"<!--[if lte IE 7]><style type='text/css'>\"+ie7Css+\"</style><![endif]-->\\\n\t\t\t <!--[if lt IE 9]><style type='text/css'>\"+ie8Css+\"</style><![endif]-->\";\n\n\t\t//Append css to the head of the page\n\t\t$(\"head\").append(style.replace(/\\t/g,'')); //remove tabs and insert style\n\t}",
"function setupContainer(containerId) {\n\t\tvar container = document.getElementById(containerId);\n\t\tcontainer.style.width = gameContainer.size.width + 'px';\n\t\tcontainer.style.height = gameContainer.size.height + 'px';\n\t}",
"applyRenderAttributes() {\n let me = this,\n container = Neo.getComponent(me.containerId),\n cls = container && container.cls;\n\n if (!container) {\n Neo.logError('layout.Card: applyRenderAttributes -> container not yet created', me.containerId);\n }\n\n _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"].add(cls || [], 'neo-layout-card');\n\n container.cls = cls;\n }",
"function DebugStyling(){}",
"function container_initial(){\n var wHeight = $(window).height(),\n wWidth = $(window).width(),\n navHeight = 60,\n searchHeight = 42,\n filternavHeight = 29,\n selectListHeight = $('.select-list').height() + 10,\n gapHeight = 36,\n routeListWidth = $('.routelist').width(),\n margintop = 5,\n marginleft = 15,\n routelist_border = 5;\n $('#map_inner').css('width',wWidth - routeListWidth - marginleft);\n $('#map_inner').css('height',wHeight - margintop - navHeight);\n $('.routelist').css('height',wHeight - searchHeight - filternavHeight - selectListHeight - gapHeight - margintop - navHeight + routelist_border);\n\n $(window).resize(function(){\n var wWidth = $(window).width();\n $('#map_inner').css('width',wWidth - routeListWidth - marginleft);\n });\n }",
"function injectStyles() {\n\tvar head = document.getElementsByTagName('head')[0];\n\tif (head) {\n\t\tvar style = \".reurope-filter {\";\n\t\tstyle += \"display: inline-block; \\n\";\n\t\tstyle += \"border: medium; \\n\";\n\t\tstyle += \"color: #FFF;\\n\";\n\t\tstyle += \"height: 30px; \\n\";\n\t\tstyle += \"margin: 5px 5px 5px 2px; \\n\";\n\t\tstyle += \"cursor: pointer; \\n\";\n\t\tstyle += \"font-size: 13px; \\n\";\n\t\tstyle += \"font-family: arial,helvetica,sans-serif; \\n\";\n\t\tstyle += \"border-radius: 2px; \\n\";\n\t\tstyle += \"} \\n\";\n\t\tstyle += \".reurope-filter>.screen {\";\n\t\tstyle += \"background: #666; \\n\";\n\t\tstyle += \"padding: 8px 6px 6px 6px;\\n\";\n\t\tstyle += \"} \\n\";\n\t\tstyle += \".reurope-filter>.screen.active {\";\n\t\tstyle += \"background: transparent; \\n\";\n\t\tstyle += \"} \\n\";\n\t\tstyle += \".reurope-filter>.screen>span {\";\n\t\tstyle += \"display: inline-block; \\n\";\n\t\tstyle += \"position: relative; \\n\";\n\t\tstyle += \"top: -0.1em; \\n\";\n\t\tstyle += \"} \\n\";\n\t\tstyle += \".reurope-filter>.screen>.reurope-removebtn {\";\n\t\tstyle += \"background: rgba(0, 0, 0, 0.2); \\n\";\n\t\tstyle += \"margin-right: 0.3em; \\n\";\n\t\tstyle += \"top: 0; \\n\";\n\t\tstyle += \"width: 1.1em; \\n\";\n\t\tstyle += \"height: 1.1em; \\n\";\n\t\tstyle += \"border-radius: 0.55em; \\n\";\n\t\tstyle += \"} \\n\";\n\t\tstyle += \".reurope-filter>.screen>.reurope-removebtn>span {\";\n\t\tstyle += \"display: block; \\n\";\n\t\tstyle += \"position: relative; \\n\";\n\t\tstyle += \"top: -0.13em; \\n\";\n\t\tstyle += \"left: 0.27em; \\n\";\n\t\tstyle += \"color: rgba(255, 255, 255, 0.3); \\n\";\n\t\tstyle += \"font-weight: 700 \\n\";\n\t\tstyle += \"} \\n\";\n\t\tstyle += \"#reurope-dialog-inner { \\n\";\n\t\tstyle += \"background: #f5f5f5 none repeat scroll 0 0; \\n\";\n\t\tstyle += \"border: 3px solid #4553a0; \\n\";\n\t\tstyle += \"border-radius: 6px; \\n\";\n\t\tstyle += \"left: 50%; \\n\";\n\t\tstyle += \"margin-right: -50%; \\n\";\n\t\tstyle += \"height: 15em; \\n\";\n\t\tstyle += \"padding: 2em; \\n\";\n\t\tstyle += \"position: absolute; \\n\";\n\t\tstyle += \"right: auto; \\n\";\n\t\tstyle += \"top: 50%; \\n\";\n\t\tstyle += \"transform: translate(-50%, -50%); \\n\";\n\t\tstyle += \"width: 30em; \\n\";\n\t\tstyle += \"box-shadow: 0 0 6px rgba(49, 63, 200, 0.6);\\n\";\n\t\tstyle += \"} \\n\";\n\t\tstyle += \"#reurope-dialog input[type='text'] { \\n\";\n\t\tstyle += \"border: 1px solid #dbdada; \\n\";\n\t\tstyle += \"border-radius: 2px; \\n\";\n\t\tstyle += \"font-size: 14px; \\n\";\n\t\tstyle += \"padding: 4px; \\n\";\n\t\tstyle += \"width: 15em; \\n\";\n\t\tstyle += \"box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset; \\n\";\n\t\tstyle += \"transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s; \\n\";\n\t\tstyle += \"} \\n\";\n\t\tstyle += \"#reurope-dialog input[type='text']:focus { \\n\";\n\t\tstyle += \"border: 1px solid #4553a0; \\n\";\n\t\tstyle += \"box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset, 0 0 4px rgba(49, 63, 200, 0.15);\\n\";\n\t\tstyle += \"} \\n\";\n\t\tstyle += \"#reurope-dialog-inner>table td { \\n\";\n\t\tstyle += \"padding: 4px 6px 4px 6px; \\n\";\n\t\tstyle += \"} \\n\";\n\n\t\tvar sContainer = document.createElement(\"style\");\n\t\tsContainer.type = 'text/css';\n\t\tsContainer.appendChild(document.createTextNode(style));\n\t\thead.appendChild (sContainer);\n\t}\n}",
"function DebugStyling() { }",
"function qodefInitElementsHolderResponsiveStyle(){\n\t\tvar elementsHolder = $('.qodef-elements-holder');\n\t\t\n\t\tif(elementsHolder.length){\n\t\t\telementsHolder.each(function() {\n\t\t\t\tvar thisElementsHolder = $(this),\n\t\t\t\t\telementsHolderItem = thisElementsHolder.children('.qodef-eh-item'),\n\t\t\t\t\tstyle = '',\n\t\t\t\t\tresponsiveStyle = '';\n\t\t\t\t\n\t\t\t\telementsHolderItem.each(function() {\n\t\t\t\t\tvar thisItem = $(this),\n\t\t\t\t\t\titemClass = '',\n\t\t\t\t\t\tlargeLaptop = '',\n\t\t\t\t\t\tsmallLaptop = '',\n\t\t\t\t\t\tipadLandscape = '',\n\t\t\t\t\t\tipadPortrait = '',\n\t\t\t\t\t\tmobileLandscape = '',\n\t\t\t\t\t\tmobilePortrait = '';\n\t\t\t\t\t\n\t\t\t\t\tif (typeof thisItem.data('item-class') !== 'undefined' && thisItem.data('item-class') !== false) {\n\t\t\t\t\t\titemClass = thisItem.data('item-class');\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof thisItem.data('1280-1600') !== 'undefined' && thisItem.data('1280-1600') !== false) {\n\t\t\t\t\t\tlargeLaptop = thisItem.data('1280-1600');\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof thisItem.data('1024-1280') !== 'undefined' && thisItem.data('1024-1280') !== false) {\n\t\t\t\t\t\tsmallLaptop = thisItem.data('1024-1280');\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof thisItem.data('768-1024') !== 'undefined' && thisItem.data('768-1024') !== false) {\n\t\t\t\t\t\tipadLandscape = thisItem.data('768-1024');\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof thisItem.data('680-768') !== 'undefined' && thisItem.data('680-768') !== false) {\n\t\t\t\t\t\tipadPortrait = thisItem.data('680-768');\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof thisItem.data('680') !== 'undefined' && thisItem.data('680') !== false) {\n\t\t\t\t\t\tmobileLandscape = thisItem.data('680');\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(largeLaptop.length || smallLaptop.length || ipadLandscape.length || ipadPortrait.length || mobileLandscape.length || mobilePortrait.length) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(largeLaptop.length) {\n\t\t\t\t\t\t\tresponsiveStyle += \"@media only screen and (min-width: 1281px) and (max-width: 1600px) {.qodef-eh-item-content.\"+itemClass+\" { padding: \"+largeLaptop+\" !important; } }\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(smallLaptop.length) {\n\t\t\t\t\t\t\tresponsiveStyle += \"@media only screen and (min-width: 1025px) and (max-width: 1280px) {.qodef-eh-item-content.\"+itemClass+\" { padding: \"+smallLaptop+\" !important; } }\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(ipadLandscape.length) {\n\t\t\t\t\t\t\tresponsiveStyle += \"@media only screen and (min-width: 769px) and (max-width: 1024px) {.qodef-eh-item-content.\"+itemClass+\" { padding: \"+ipadLandscape+\" !important; } }\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(ipadPortrait.length) {\n\t\t\t\t\t\t\tresponsiveStyle += \"@media only screen and (min-width: 681px) and (max-width: 768px) {.qodef-eh-item-content.\"+itemClass+\" { padding: \"+ipadPortrait+\" !important; } }\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(mobileLandscape.length) {\n\t\t\t\t\t\t\tresponsiveStyle += \"@media only screen and (max-width: 680px) {.qodef-eh-item-content.\"+itemClass+\" { padding: \"+mobileLandscape+\" !important; } }\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\tif(responsiveStyle.length) {\n\t\t\t\t\tstyle = '<style type=\"text/css\">'+responsiveStyle+'</style>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(style.length) {\n\t\t\t\t\t$('head').append(style);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (typeof qodef.modules.common.qodefOwlSlider === \"function\") {\n\t\t\t\t\tqodef.modules.common.qodefOwlSlider();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}",
"function getStyles(props, context) {\n var toolbar = context.uiTheme.toolbar;\n\n\n return {\n container: [toolbar.container, props.style.container]\n };\n}",
"function getResizeStyle(context){var stretch='100% 100%';var resize=context.resize||stretch;var bgSize=['cover','contain',stretch].indexOf(resize)>-1?resize:stretch;return{'background-size':bgSize};}",
"_addStyles() {\n let sheet = this._createSheet()\n sheet.addRule('.widgetry-overlay', 'position: fixed !important')\n sheet.addRule('.widgetry-overlay', 'top: 0 !important')\n sheet.addRule('.widgetry-overlay', 'left: 0 !important')\n sheet.addRule('.widgetry-overlay', 'width: 100% !important')\n sheet.addRule('.widgetry-overlay', 'height: 100% !important')\n sheet.addRule('.widgetry-overlay', 'background: rgba(127, 144, 197, 0.28)')\n sheet.addRule('.widgetry-overlay', 'z-index: 100000 !important')\n sheet.addRule('.widgetry-overlay', 'display: none !important')\n sheet.addRule('.widgetry-frame', 'border: 0 none transparent !important')\n sheet.addRule('.widgetry-embedded', 'width: 100% !important')\n sheet.addRule('.widgetry-embedded', 'max-width: 670px !important')\n sheet.addRule('.widgetry-embedded', 'height: 470px !important')\n sheet.addRule('.widgetry-overlay.widgetry-visible', 'display: block !important')\n }",
"function Container() {\n var _this;\n\n _classCallCheck(this, Container);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(Container).call(this)); // Add shadow root and slot for user markup...\n\n _defineProperty(_assertThisInitialized(_this), \"_style\", null);\n\n var shadowRoot = _this.shadowCaster(); // Attach styles to shadowRoot....\n\n\n _this._style = _this.addStyles(shadowRoot, containerStyles); /// Register the component's prop object...\n\n _this.registerProps(containerProps);\n\n return _this;\n } // Complete post mounting Component work here...",
"function getStyles(container) {\n\t return container.values().map(function (style) { return style.getStyles(); }).join('');\n\t}",
"function getBackgroundContainer(){\n var tmp_container = engine.createContainer();\n var tmp_slate = engine.createSlate();\n \n Logger.log( 'm_menu_widget.getDisplayNode().width = ' + m_menu_widget.getDisplayNode().width );\n tmp_slate = engine.createSlate();\n tmp_slate.width = 410;\n tmp_slate.height = 1080*2;\n tmp_container.x = -96;\n tmp_container.y = -1080;\n \n tmp_slate.shader = ShaderCreatorInstance.createSolidColorShader( RGBLibraryInstance.getBLACK( 1 ) );\n \n tmp_container.addChild( tmp_slate );\n \n return tmp_container;\n }"
]
| [
"0.62551",
"0.5942364",
"0.5837674",
"0.5763219",
"0.5734829",
"0.56915724",
"0.56620973",
"0.5639743",
"0.5591183",
"0.5495324",
"0.5495324",
"0.5495324",
"0.5495324",
"0.54875153",
"0.5480891",
"0.54311204",
"0.5409652",
"0.536091",
"0.5356015",
"0.5344911",
"0.53382206",
"0.5333052",
"0.5330927",
"0.5329252",
"0.53115153",
"0.530512",
"0.52938247",
"0.52891093",
"0.5283656",
"0.5278466"
]
| 0.70130396 | 0 |
The paths config to use when compiling your react app for development or production. | paths(paths, env) {
// if (env === 'production') {
// const dirName = __dirname.replace('/src/Client', '');
// paths.appBuild = `${dirName}/public/dist`;
// }
return paths;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"bindPaths() {\n Object.entries(this.resolvePaths()).forEach(([key, value]) => {\n const name = this.stringHelper.singular(key);\n this.app.configurePaths({\n [name]: value\n });\n });\n Object.entries(this.resolveSourcePaths()).forEach(([key, value]) => {\n const name = this.stringHelper.singular(key);\n this.app.configurePaths({\n [`src.${name}`]: value\n });\n });\n }",
"webpack(config) {\n config.resolve.alias['@root'] = path.join(__dirname);\n config.resolve.alias['@components'] = path.join(__dirname, 'components');\n config.resolve.alias['@pages'] = path.join(__dirname, 'pages');\n return config;\n }",
"static setPaths() {\n\t\tthis._url_app = this.dirname(import.meta.url);\n\t\tthis._url_page = this.dirname(location.href);\n\t}",
"function config () {\n return {\n name: 'backend build',\n entry: path.resolve('server/main.js'),\n resolve: {\n extensions: ['.js']\n },\n externals: webpackHelper.getExcludedModules(),\n output: {\n path: path.resolve('server'),\n filename: 'bundle.js'\n },\n target: 'node',\n plugins: [\n\n ]\n }\n}",
"function makeLocalDevConfig(EXAMPLE_DIR = LIB_DIR) {\n return {\n // suppress warnings about bundle size\n devServer: {\n stats: {\n warnings: false,\n },\n },\n\n devtool: 'source-map',\n\n resolve: {\n extensions: ['.js', '.ts', '.tsx'],\n alias: {\n 'nebula.gl/dist': MAIN_SRC_DIR,\n 'nebula.gl': MAIN_SRC_DIR,\n\n '@nebula.gl/edit-modes/dist': EDIT_MODES_SRC_DIR,\n '@nebula.gl/edit-modes': EDIT_MODES_SRC_DIR,\n\n '@nebula.gl/layers/dist': LAYERS_SRC_DIR,\n '@nebula.gl/layers': LAYERS_SRC_DIR,\n\n '@nebula.gl/overlays/dist': OVERLAYS_SRC_DIR,\n '@nebula.gl/overlays': OVERLAYS_SRC_DIR,\n\n '@nebula.gl/editor/dist': EDITOR_SRC_DIR,\n '@nebula.gl/editor': EDITOR_SRC_DIR,\n\n 'react-map-gl-draw/dist': REACT_EDITOR_LITE_SRC_DIR,\n 'react-map-gl-draw': REACT_EDITOR_LITE_SRC_DIR,\n\n 'react-map-gl': resolve(LIB_DIR, './node_modules/react-map-gl'),\n\n '@deck.gl/core': resolve(LIB_DIR, './node_modules/@deck.gl/core'),\n '@deck.gl/layers': resolve(LIB_DIR, './node_modules/@deck.gl/layers'),\n\n // Use luma.gl specified by root package.json\n 'luma.gl': resolve(LIB_DIR, './node_modules/luma.gl'),\n // Important: ensure shared dependencies come from the main node_modules dir\n // Versions will be controlled by the deck.gl top level package.json\n 'math.gl': resolve(LIB_DIR, './node_modules/math.gl'),\n seer: resolve(LIB_DIR, './node_modules/seer'),\n react: resolve(LIB_DIR, './node_modules/react'),\n },\n },\n module: {\n rules: [\n {\n // Unfortunately, webpack doesn't import library sourcemaps on its own...\n test: /\\.js$|\\.ts$|\\.tsx$/,\n use: ['source-map-loader'],\n enforce: 'pre',\n },\n {\n test: /\\.tsx?$/,\n use: 'ts-loader',\n exclude: /node_modules/,\n },\n ],\n },\n // Optional: Enables reading mapbox token from environment variable\n plugins: [new webpack.EnvironmentPlugin(['MapboxAccessToken'])],\n };\n}",
"function getConfig() {\n if (shouldAddPublicConfig()) {\n const plugins = [\n new HtmlWebpackPlugin({\n template: paths.appPublicHtmlTemplate(),\n title: appName,\n filename: `${publicFolderName}/index.html`,\n inject: false,\n chunks: [publicFolderName],\n minify: {\n collapseWhitespace: true\n }\n })\n ]\n\n if (useCozyClientJs) {\n /* We need to put all assets in the public build folder since \n public pages will need to have them public */\n plugins.push(\n new CopyPlugin([\n {\n from: paths.appCozyClientJs(),\n to: buildPublicCozyClientJs\n }\n ]),\n new HtmlWebpackIncludeAssetsPlugin({\n assets: [`${publicFolderName}/cozy-client-js.js`],\n append: false,\n publicPath: true\n })\n )\n }\n\n return {\n entry: {\n // since the file extension depends on the framework here\n // we get it from a function call\n [publicFolderName]: [\n require.resolve('@babel/polyfill'),\n paths.appPublicIndex()\n ]\n },\n plugins\n }\n }\n return {}\n}",
"extend (config, { isDev }) {\n //每次构建打包时给文件名加上时间戳,保证版本更新时与上版本文件名不一样\n config.output.filename = `js/[name].${new Date().getTime()}.js`;\n config.output.chunkFilename = `js/[name].${new Date().getTime()}.js`;\n if (isDev && process.client) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n // config.module.rules.push({\n // test: /\\.postcss$/,\n // use: [\n // 'vue-style-loader',\n // 'css-loader',\n // {\n // loader: 'postcss-loader'\n // }\n // ]\n // })\n }\n }",
"webpack (config) {\n Object.assign(config.resolve.alias, {\n '@': path.resolve(__dirname)\n })\n return config\n }",
"devServer(configFunction) {\n // Return the replacement function for create-react-app to use to generate the Webpack\n // Development Server config. \"configFunction\" is the function that would normally have\n // been used to generate the Webpack Development server config - you can use it to create\n // a starting configuration to then modify instead of having to create a config from scratch.\n return function (proxy, allowedHost) {\n // Create the default config by calling configFunction with the proxy/allowedHost parameters\n const config = configFunction(proxy, allowedHost);\n\n // Change the https certificate options to match your certificate, using the .env file to\n // set the file paths & passphrase.\n const fs = require('fs');\n\n // create .env file for example:\n // REACT_HTTPS_KEY=\"/path/to/key\"\n // REACT_HTTPS_CERT=\"/path/to/cert\"\n\n if (process.env.REACT_HTTPS_KEY && process.env.REACT_HTTPS_CERT) {\n config.https = {\n key: fs.readFileSync(process.env.REACT_HTTPS_KEY, 'utf8'),\n cert: fs.readFileSync(process.env.REACT_HTTPS_CERT, 'utf8'),\n };\n }\n // Return your customised Webpack Development Server config.\n return config;\n };\n }",
"extend(config, { isDev, isClient }) {\n if (!isDev) {\n // relative links, please.\n config.output.publicPath = './assets/'\n // config.output.maxChunks = 1\n }\n return config\n }",
"extend(config, { isDev, isClient }) {\n\t\t\tconfig.performance.maxAssetSize = 500000\n\t\t\tconfig.resolve.alias['@style'] = path.resolve(__dirname, './assets/css')\n\t\t\tconst alias = (config.resolve.alias = config.resolve.alias || {})\n\t\t\talias['@r'] = '~'\n\t\t\talias['@c'] = '~/components/'\n\t\t\talias['@styles'] = '~/assets/css'\n\t\t\tif (isDev && isClient) {\n\t\t\t\tconfig.module.rules.push({\n\t\t\t\t\tenforce: 'pre',\n\t\t\t\t\ttest: /\\.(js|vue)$/,\n\t\t\t\t\tloader: 'eslint-loader',\n\t\t\t\t\texclude: /(node_modules)/\n\t\t\t\t})\n\t\t\t}\n\t\t}",
"function init() {\n if (config.paths) {\n paths.helpers = config.paths.helpers || paths.helpers;\n paths.gadgets = config.paths.gadgets || paths.gadgets;\n }\n }",
"function createDevServer(env, { allowedHost, proxy } = {}) {\n const { https = false } = env;\n const locations = env.locations || (0, env_1.getPaths)(env.projectRoot, env);\n const { publicPath: publicUrlOrPath } = (0, env_1.getPublicPaths)(env);\n const disableFirewall = !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true';\n // Attempt to keep this as close to create-react-native app as possible.\n // https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/config/webpackDevServer.config.js\n return {\n // WebpackDevServer 2.4.3 introduced a security fix that prevents remote\n // websites from potentially accessing local content through DNS rebinding:\n // https://github.com/webpack/webpack-dev-server/issues/887\n // https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a\n // However, it made several existing use cases such as development in cloud\n // environment or subdomains in development significantly more complicated:\n // https://github.com/facebook/create-react-app/issues/2271\n // https://github.com/facebook/create-react-app/issues/2233\n // While we're investigating better solutions, for now we will take a\n // compromise. Since our WDS configuration only serves files in the `public`\n // folder we won't consider accessing them a vulnerability. However, if you\n // use the `proxy` feature, it gets more dangerous because it can expose\n // remote code execution vulnerabilities in backends like Django and Rails.\n // So we will disable the host check normally, but enable it if you have\n // specified the `proxy` setting. Finally, we let you override it if you\n // really know what you're doing with a special environment variable.\n // Note: [\"localhost\", \".localhost\"] will support subdomains - but we might\n // want to allow setting the allowedHosts manually for more complex setups\n allowedHosts: disableFirewall ? ['all'] : [allowedHost].filter(Boolean),\n // Enable gzip compression of generated files.\n compress: true,\n static: {\n // By default WebpackDevServer serves physical files from current directory\n // in addition to all the virtual build products that it serves from memory.\n // This is confusing because those files won’t automatically be available in\n // production build folder unless we copy them. However, copying the whole\n // project directory is dangerous because we may expose sensitive files.\n // Instead, we establish a convention that only files in `public` directory\n // get served. Our build script will copy `public` into the `build` folder.\n // In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:\n // <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\">\n // In JavaScript code, you can access it with `process.env.PUBLIC_URL`.\n // Note that we only recommend to use `public` folder as an escape hatch\n // for files like `favicon.ico`, `manifest.json`, and libraries that are\n // for some reason broken when imported through webpack. If you just want to\n // use an image, put it in `src` and `import` it from JavaScript instead.\n directory: locations.template.folder,\n publicPath: [publicUrlOrPath],\n // By default files from `contentBase` will not trigger a page reload.\n watch: {\n // Reportedly, this avoids CPU overload on some systems.\n // https://github.com/facebook/create-react-app/issues/293\n // src/node_modules is not ignored to support absolute imports\n // https://github.com/facebook/create-react-app/issues/1065\n ignored: (0, ignoredFiles_1.ignoredFiles)(locations.root),\n },\n },\n client: {\n webSocketURL: {\n // Enable custom sockjs pathname for websocket connection to hot reloading server.\n // Enable custom sockjs hostname, pathname and port for websocket connection\n // to hot reloading server.\n hostname: defaults_1.sockHost,\n pathname: defaults_1.sockPath,\n port: defaults_1.sockPort,\n },\n // overlay: true,\n overlay: false,\n // TODO: This is nonstandard, prevents logging in the browser\n // logging: 'none',\n },\n webSocketServer: {\n type: 'ws',\n options: {\n host: defaults_1.sockHost,\n port: defaults_1.sockPort,\n path: defaults_1.sockPath,\n },\n },\n devMiddleware: {\n index: true,\n // It is important to tell WebpackDevServer to use the same \"publicPath\" path as\n // we specified in the webpack config. When homepage is '.', default to serving\n // from the root.\n // remove last slash so user can land on `/test` instead of `/test/`\n publicPath: publicUrlOrPath.slice(0, -1),\n },\n https: getHttpsConfig(env.projectRoot, https),\n host: defaults_1.host,\n historyApiFallback: {\n // Paths with dots should still use the history fallback.\n // See https://github.com/facebook/create-react-app/issues/387.\n disableDotRule: true,\n index: publicUrlOrPath,\n },\n // `proxy` is run between `before` and `after` `webpack-dev-server` hooks\n proxy,\n setupMiddlewares(middlewares, devServer) {\n (0, assert_1.default)(devServer, 'webpack-dev-server is not defined');\n middlewares.unshift(\n // Keep `evalSourceMapMiddleware`\n // middlewares before `redirectServedPath` otherwise will not have any effect\n // This lets us fetch source contents from webpack for the error overlay\n (0, evalSourceMapMiddleware_1.createEvalSourceMapMiddleware)(devServer), \n // Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match\n (0, redirectServedPathMiddleware_1.createRedirectServedPathMiddleware)(publicUrlOrPath), \n // This service worker file is effectively a 'no-op' that will reset any\n // previous service worker registered for the same host:port combination.\n // We do this in development to avoid hitting the production cache if\n // it used the same host and port.\n // https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432\n (0, noopServiceWorkerMiddleware_1.createNoopServiceWorkerMiddleware)(publicUrlOrPath));\n return middlewares;\n },\n };\n}",
"extend(config, ctx) {\n config.resolve.alias.components = path.resolve(__dirname, 'components')\n config.resolve.alias.plugins = path.resolve(__dirname, 'plugins')\n config.resolve.alias.assets = path.resolve(__dirname, 'assets')\n\n return config\n }",
"webpack(config) {\n config.module.rules.forEach((rule) => {\n const { oneOf } = rule;\n if (oneOf) {\n oneOf.forEach((one) => {\n if (!`${one.issuer?.and}`.includes(\"_app\")) return;\n one.issuer.and = [path.resolve(__dirname)];\n });\n }\n });\n return config;\n }",
"async rewrites() {\n /**\n * If you have multiple manifest for different environment\n * i.e: manifest.prod.json, manifest.dev.json, manifest.staging.json, etc\n * you can also rewrite it in here so it point out /manifest.json but read from\n * each different environment by reading your env configuration.\n */\n return [\n /* {\n source: '/graphql', // when we call graphql API\n destination: process.env.GRAPHQL_URL + '*path' // https://backend.com/graphql become https://localhost:3000/graphql\n } */\n ]\n }",
"function createConfig (env) {\n if (env === undefined) env = process.env.NODE_ENV;\n const isProduction = env === 'production';\n const map = env === 'production' ? 'nosources-source-map' : 'cheap-module-source-map';\n\n function generateHtmlPlugins (templateDir) {\n const files = glob.sync(`${templateDir}/**/*.twig`, [])\n return files.map(item => {\n const replaced = item.replace('./src/pages/', '')\n const parts = replaced.split(\".\");\n const [name, extension] = parts;\n return new HtmlWebpackPlugin({\n filename: `${name}.html`,\n template: path.resolve(__dirname, `${templateDir}/${name}.${extension}`),\n inject: false,\n minify: false,\n });\n });\n // })\n }\n\n const htmlPlugins = generateHtmlPlugins(\"./src/pages\");\n\n\n const webpackConfig = {\n mode: isProduction ? 'production' : 'development',\n // context: path.join(__dirname, config.src.js),\n target: false,\n entry: {\n app: ['./src/js/app.js'],\n },\n output: {\n // path: path.join(__dirname, config.dest.js),\n path: path.join(__dirname, 'build'),\n // filename: '[name].js',\n filename: './js/[name].js',\n publicPath: '',\n chunkFormat: false,\n chunkLoading: false,\n wasmLoading: false,\n },\n devtool: map,\n watch: !isProduction,\n watchOptions: {\n aggregateTimeout: 500,\n },\n plugins: [\n // new webpack.optimize.CommonsChunkPlugin({\n // name: 'vendor',\n // filename: '[name].js',\n // minChunks: Infinity\n // }),\n new webpack.LoaderOptionsPlugin({\n options: {\n eslint: {\n formatter: require('eslint-formatter-pretty')\n }\n }\n }),\n new webpack.ProvidePlugin({\n $: 'jquery',\n jQuery: 'jquery',\n 'window.jQuery': 'jquery',\n Promise: 'es6-promise-promise',\n }),\n new webpack.NoEmitOnErrorsPlugin(),\n\n // new BundleAnalyzerPlugin({\n // analyzerMode: 'static',\n // analyzerPort: 4000,\n // openAnalyzer: false,\n // }),\n ].concat(htmlPlugins),\n resolve: {\n extensions: ['.html', '.twig', '.js'],\n modules: [\"node_modules\"],\n alias: {\n TweenLite: path.resolve('node_modules', 'gsap/src/uncompressed/TweenLite.js'),\n TweenMax: path.resolve('node_modules', 'gsap/src/uncompressed/TweenMax.js'),\n TimelineLite: path.resolve('node_modules', 'gsap/src/uncompressed/TimelineLite.js'),\n TimelineMax: path.resolve('node_modules', 'gsap/src/uncompressed/TimelineMax.js'),\n ScrollMagic: path.resolve('node_modules', 'scrollmagic/scrollmagic/uncompressed/ScrollMagic.js'),\n 'animation.gsap': path.resolve('node_modules', 'scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js'),\n 'debug.addIndicators': path.resolve('node_modules', 'scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators.js'),\n },\n },\n optimization: {\n minimize: isProduction\n },\n module: {\n rules: [\n {\n enforce: 'pre',\n test: /\\.js$/,\n exclude: [\n path.resolve(__dirname, 'node_modules'),\n ],\n loader: 'eslint-loader',\n options: {\n fix: true,\n cache: true,\n ignorePattern: path.resolve(__dirname, '/src/js/lib/'),\n }\n },\n {\n test: /\\.js$/,\n loader: 'babel-loader',\n exclude: [\n path.resolve(__dirname, 'node_modules'),\n ],\n },\n // { test: /\\.(glsl|frag|vert)$/, loader: 'raw-loader', exclude: /node_modules/ },\n // { test: /\\.(glsl|frag|vert)$/, loader: 'glslify-loader', exclude: /node_modules/ },\n {\n test: /\\.twig$/,\n use: [\n 'raw-loader',\n {\n loader: 'twig-html-loader',\n options: {\n namespaces: {\n 'templates': path.join(__dirname, './src/templates'),\n 'layouts': path.join(__dirname, './src/templates/layouts'),\n 'partials': path.join(__dirname, './src/templates/partials'),\n 'components': path.join(__dirname, './src/templates/components'),\n 'mixins': path.join(__dirname, './src/templates/mixins'),\n 'pages': path.join(__dirname, './src/templates/pages'),\n },\n // debug: !isProduction,\n data: (context) => {\n let globalData = {}\n let fileData = {}\n const contextPath = context.resourcePath;\n const name = contextPath.split(path.sep).pop().split('.').shift();\n const data = path.join(__dirname, `src/data/${name}.json`);\n const global = path.join(__dirname, 'src/data/_global.json');\n\n if (fs.existsSync(global)) {\n context.addDependency(global);\n globalData = context.fs.readJsonSync(global, { throws: false }) || {};\n }\n\n if (fs.existsSync(data)) {\n context.addDependency(data);\n fileData = context.fs.readJsonSync(data, { throws: false }) || {};\n }\n\n return ({ ...globalData, ...fileData }) || {};\n }\n }\n }\n ]\n }\n ],\n },\n };\n\n if (isProduction) {\n webpackConfig.plugins.push(\n new webpack.LoaderOptionsPlugin({\n minimize: true,\n }),\n );\n }\n\n return webpackConfig;\n}",
"function createWebConfig({\n isDev = false,\n workspace,\n constants = new Map(),\n inputDir = '',\n outputDir = '',\n}) {\n let BabiliPlugin;\n const HtmlWebpackPlugin = require('html-webpack-plugin');\n const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');\n\n if (!isDev) {\n BabiliPlugin = require('babili-webpack-plugin');\n }\n\n // Add a leading slash if a nested directory value was provided.\n inputDir = inputDir !== '' ? `/${inputDir}` : inputDir;\n outputDir = outputDir !== '' ? `/${outputDir}` : outputDir;\n return {\n // If there is an error when building for production it’s not worth trying\n // to salvage the build.\n bail: !isDev,\n // In most cases we are targeting the web, but if our target is Electron\n // then we are actually targeting an Electron renderer.\n target: Target.matches(workspace.target, 'electron')\n ? 'electron-renderer'\n : 'web',\n // In development we want a fast devtool that won’t slow down the build, but\n // in production we prefer a robust devtool.\n //\n // `create-react-app` chose to use `cheap-module-source-map` as the\n // development default, but we may also consider `eval` which will show the\n // compiled source.\n devtool: isDev ? 'cheap-module-source-map' : 'source-map',\n\n entry: [\n // In development we want to include some extra scripts to assist in hot\n // reloading and other aspects of developer experience.\n ...(isDev\n ? [\n // We use this as an alternative client to the one provided by\n // `webpack-dev-server` as it is optimized for the single-page-app\n // React developer experience. Syntax errors will render a custom\n // overlay to provide high signal to the changes that need to be\n // made.\n require.resolve('react-dev-utils/webpackHotDevClient'),\n // Errors should be considered fatal in development so that they get\n // fixed instead of ignored.\n require.resolve('react-error-overlay'),\n ]\n : []),\n // App code must always go last so that if there is an error it doesn’t\n // break the development tools we have configured.\n `${workspace.absolutePath}${inputDir}/main`,\n ],\n output: {\n // Put the final output in our workspace’s build directory.\n path: `${workspace.buildPath}/__dist__${outputDir}`,\n // Add /* filename */ comments to generated require()s in the output.\n pathinfo: true,\n // The filename at which our JavaScript code will be output.\n filename: isDev || Target.matches(workspace.target, 'electron')\n ? 'static/js/main.js'\n : 'static/js/main.[chunkhash:8].js',\n // We also want to name our chunks in production, but in development we\n // don’t care about the name.\n chunkFilename: isDev ? undefined : 'static/js/chunk.[chunkhash:8].js',\n // The path that the application will be served under. For now we assume\n // that path is `/` everywhere. Unless we are in Electron where we want\n // relative paths.\n publicPath: Target.matches(workspace.target, 'electron') ? '' : '/',\n // Point sourcemap entries to original disk location.\n devtoolModuleFilenameTemplate: info =>\n path.resolve(info.absoluteResourcePath),\n },\n resolve: {\n // The extensions the module resolution algorithm will use. We need to\n // include TypeScript extensions as they will not be detected by default.\n // Note that JS goes first. This is so that we don’t accidently resolve\n // `.d.ts` files from dependencies.\n extensions: ['.js', '.ts', '.tsx', '.json'],\n\n alias: {\n // Alias the tilda as the universe root path as this is the style we\n // want to use for importing a sibling when deep in the file tree.\n '~': Universe.ROOT_PATH,\n // Always use the browser build for `debug`. When we are building for\n // Electron Webpack will want to use the Node.js version of `debug`. In\n // this case the browser version of `debug` is what we want so that we\n // may configure what is debugged with `localStorage`.\n debug: path.resolve(__dirname, '../node_modules/debug/src/browser.js'),\n },\n },\n externals: [\n // For Node.js based workspaces we want to externalize our dependencies in\n // `node_modules` instead of bundling them.\n ...(Target.matches(workspace.target, 'node')\n ? [createExternalizer({ isDev })]\n : []),\n ],\n module: {\n rules: [\n // Include a rule for transpiling our TypeScript files. We only ever\n // want to transpile. Type checking is done in other, more rigorous,\n // scripts. Only transpiling makes our build super fast.\n {\n test: /\\.(ts|tsx)$/,\n loader: require.resolve('ts-loader'),\n options: {\n // Don’t log. Since we are just transpiling TypeScript here we don’t\n // need to see any output. It also messes with our progress bar.\n silent: true,\n configFilePath: null,\n // Here is where we get to say that we only want to transpile.\n transpileOnly: true,\n // Provide some minimal compiler options to aid in the transpilation\n // step.\n compilerOptions: {\n // Supposedly this helps when we are only transpiling.\n isolatedModules: true,\n // Create source maps, but only in production.\n sourceMap: !isDev,\n // Transpile JSX into the React syntax.\n jsx: 'react',\n // Import all helpers from `tslib`.\n importHelpers: true,\n // Always use ES2015 modules even in an ES5 environment.\n module: 'es2015',\n // Build for ES5 unless we are in Electron or development. Then we\n // are most likely using the latest version web browser version\n // and have access to all of the nice ES2017 features including\n // native async functions!\n target: isDev || Target.matches(workspace.target, 'electron')\n ? 'es2017'\n : 'es5',\n },\n },\n },\n ],\n },\n plugins: [\n // Generates an `index.html` file with the <script> injected.\n new HtmlWebpackPlugin({\n inject: true,\n template: `${workspace.absolutePath}${inputDir}/main.html`,\n filename: 'index.html',\n // Minify the HTML in production, but not in development.\n minify: isDev\n ? undefined\n : {\n removeComments: true,\n collapseWhitespace: true,\n removeRedundantAttributes: true,\n useShortDoctype: true,\n removeEmptyAttributes: true,\n removeStyleLinkTypeAttributes: true,\n keepClosingSlash: true,\n minifyJS: true,\n minifyCSS: true,\n minifyURLs: true,\n },\n }),\n // Add module names to factory functions so they appear in browser\n // profiler.\n new webpack.NamedModulesPlugin(),\n // Define our environment so that React will be built appropriately.\n new webpack.DefinePlugin(\n Object.assign(\n {\n // Throughout our repo we expect a global `__DEV__` boolean to\n // enable/disable features in development.\n __DEV__: isDev ? 'true' : 'false',\n // Many libraries, including React, use `NODE_ENV` so we need to\n // define it.\n 'process.env.NODE_ENV': isDev ? \"'development'\" : \"'production'\",\n },\n // Create an object of defiens from our loaded constants object.\n createConstantDefines(constants),\n ),\n ),\n ...(isDev\n ? // Enable some extra plugins in development.\n [\n // This is necessary to emit hot updates (currently CSS only).\n new webpack.HotModuleReplacementPlugin(),\n // If you require a missing module and then `npm install` it, you\n // still have to restart the development server for Webpack to\n // discover it. This plugin makes the discovery automatic so you\n // don’t have to restart.\n new WatchMissingNodeModulesPlugin(\n `${Universe.ROOT_PATH}/node_modules`,\n ),\n ]\n : // Enable some extra plugins in production.\n [\n // Scope hoist all of the modules that we can in production. Make\n // sure this runs before the minification plugin as a scope hoisted\n // module is more easily minified.\n new webpack.optimize.ModuleConcatenationPlugin(),\n // Minify the code with Babili which understands ES2015+ syntax\n // unlike UglifyJS.\n new BabiliPlugin(),\n ]),\n ],\n // Turn off performance hints during development because we don't do any\n // splitting or minification in interest of speed. These warnings become\n // cumbersome.\n performance: {\n hints: !isDev ? 'warning' : false,\n },\n };\n}",
"extend(config, ctx) {\n\n\n if (ctx.isDev && ctx.isClient) {\n config.module.rules.push()\n }\n config.resolve.alias['components'] = path.resolve(__dirname, 'components')\n }",
"function isDev() {\n\n // Assets will be in a non-root folder in production\n return fs.existsSync('assets')\n\n}",
"function getConfig() {\n var src = './src/';\n var config = {\n src: './src/',\n js: [\n src + '**/*.js',\n src + '**/*.module.js',\n '!' + src + '**/*.spec.js' // '!' mean is that exclude\n ],\n css: src + '**/*.css',\n index: src + 'views/index.html'\n };\n return config;\n}",
"paths(paths) {\n return paths;\n }",
"getProjectRoots() {\n return [__dirname];\n }",
"extend(config, {\n isDev,\n isClient\n }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n config.plugins.push(\n new webpack.EnvironmentPlugin(['APIKEY', 'AUTHDOMAIN', 'DATABASEURL', 'PROJECTID', 'STORAGEBUCKET', 'MESSAGINGSENDERID'])\n )\n }",
"webpackPlugins() {\n let CleanPlugin = require('clean-webpack-plugin');\n let config = this.config;\n let paths = this.paths;\n\n if (!paths) {\n paths = [path.resolve(Config.publicPath)];\n config.exclude.push('.gitignore', '.gitkeep', 'hot');\n }\n\n return new CleanPlugin(paths, config);\n }",
"extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n\n config.module.rules.push({\n test: /\\.(png|jpe?g|gif|svg)$/,\n loader: 'url-loader',\n query: {\n limit: 1000, // 1kB\n name: 'img/[name].[hash:7].[ext]'\n }\n });\n config.module.rules.push({\n test: /\\.(ico)$/,\n loader: 'file-loader',\n query: {\n name: 'img/[name].[hash:7].[ext]'\n }\n });\n\n config.module.rules.push({\n test: /\\.(woff2?|eot|ttf|otf)(\\?.*)?$/,\n loader: 'url-loader',\n query: {\n limit: 1000, // 1kB\n name: 'fonts/[name].[hash:7].[ext]'\n }\n });\n\n \n if (isClient) {\n config.devtool = 'eval-source-map'\n }\n }",
"getBasePath() {\n return process.env.BASE_PATH || '/api/1';\n }",
"static buildPaths(parts) {\n const paths = [];\n if (parts.isFromAddon) {\n const fullPath = Resolver.makePath([parts.factoryPods, parts.factoryName + 's', parts.modulePods, parts.moduleName]);\n paths.push(`${fullPath}.js`);\n paths.push(fullPath);\n return paths;\n }\n\n if (parts.namespace) {\n paths.push(Resolver.makePath([parts.appPath, parts.namespace, parts.factorySubTree, parts.modulePods, parts.moduleName, parts.factoryName + '.js']));\n paths.push(Resolver.makePath([parts.appPath, parts.namespace, parts.factorySubTree, parts.modulePods, parts.moduleName + '.js']));\n paths.push(Resolver.makePath([parts.appPath, parts.namespace, parts.factoryName + 's', parts.modulePods, parts.moduleName + '.js']));\n paths.push(Resolver.makePath([parts.appPath, parts.namespace, parts.factoryName + 's', parts.modulePods, parts.moduleName]));\n }\n\n paths.push(Resolver.makePath([parts.appPath, parts.factorySubTree, parts.modulePods, parts.moduleName, parts.factoryName + '.js']));\n paths.push(Resolver.makePath([parts.appPath, parts.factoryName + 's', parts.modulePods, parts.moduleName + '.js']));\n paths.push(Resolver.makePath([parts.appPath, parts.factoryName + 's', parts.modulePods, parts.moduleName]));\n\n // driven fallback\n paths.push(Resolver.makePath([parts.frameworkPath, parts.factoryName + 's', parts.modulePods, parts.moduleName + '.js']));\n paths.push(Resolver.makePath([parts.frameworkPath, parts.factoryName + 's', parts.modulePods, parts.moduleName]));\n\n return paths;\n }",
"static defineComponents() {\n const componentsList = require.context('../components/', true, /\\.js$/);\n componentsList.keys().forEach((path) => {\n require(`../components/${path.slice(2)}`);\n });\n }",
"config() {\n this.fs.copyTpl(\n this.templatePath('_package.json'),\n this.destinationPath('package.json'), \n {\n props: this.props\n }\n );\n this.fs.copy(\n this.templatePath('_webpack.config.js'),\n this.destinationPath('webpack.config.js')\n );\n this.fs.copy(\n this.templatePath('_gitignore'),\n this.destinationPath('.gitignore')\n );\n }"
]
| [
"0.63037205",
"0.6021101",
"0.5852944",
"0.58106655",
"0.5761457",
"0.5705637",
"0.5623962",
"0.56005895",
"0.5573901",
"0.55706507",
"0.55180603",
"0.5483755",
"0.5449212",
"0.5429339",
"0.54280347",
"0.54251844",
"0.54243994",
"0.5409194",
"0.53941864",
"0.53737104",
"0.53504246",
"0.5316338",
"0.52906924",
"0.52772087",
"0.5273453",
"0.5237743",
"0.5222925",
"0.5218448",
"0.52182156",
"0.52088225"
]
| 0.8001737 | 0 |
Variabes var recipeJson; init | function init() {
'use strict';
//recipeJson = localStorage.getItem('recipeJson');
loadRecipe();
} // end init | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function createRecipeObject() {\n let addRecipeDataObj = {\n title: $addRecipeTitle.val(),\n recipeDescription: $addRecipeText.val(),\n // TODO need to find the google service that will turn pic file uploads to urls\n file: $addRecipeFile.val(),\n personName: $addRecipeName.val(),\n ingredient: getAllIngredients(),\n step: getAllSteps()\n };\n\n return (createRecipeData = JSON.stringify(addRecipeDataObj));\n }",
"function Recipe (recipeData) {\n this.sId =recipeData.id;\n this.title = recipeData.title;\n this.time = recipeData.readyInMinutes ? recipeData.readyInMinutes : 'N/A';\n this.servings = recipeData.servings ? recipeData.servings : 'N/A';\n this.image = recipeData.image;\n this.vegetarian = `${recipeData.vegetarian}`;\n this.vegan = `${recipeData.vegan}`;\n this.instructions = recipeData.instructions;\n this.ingredients_string = recipeData.extendedIngredients.map(ingredient => ingredient.originalString)\n this.ingredients_name = recipeData.extendedIngredients.map(ingredient => ingredient.name);\n this.ingredients_unit = recipeData.extendedIngredients.map(ingredient => ingredient.unit);\n this.ingredients_amount = recipeData.extendedIngredients.map(ingredient => ingredient.amount);\n this.credit = recipeData.creditsText;\n this.source_name = recipeData.sourceName;\n this.source_url = recipeData.sourceUrl;\n}",
"function init_restaurant_geolocation_dict() {\n $.getJSON(\"restaurant_location/restaurant_location.json\", function(response) {\n rest_dict = response;\n console.log(rest_dict);\n });\n}",
"constructor() {\n super();\n this.state = {\n recipe: new RecipeDefinition(0, \"\", 0, \"\", 0, [], [], \"\")\n }\n }",
"function init() {\n // load details from data file\n loadDataAndParse('ShoppingItems.json')\n}",
"function createRecipe(title, ingredients , menuItemType){\n var brunch = {\n title: title,\n ingredients: ingredients,\n type: menuItemType,\n }\n return brunch\n}",
"fromJson(json) {\n this.name = json.name;\n this.notes = json.notes;\n this.reactions = json.reactions;\n this.molecules = json.molecules;\n this.molecules_number = json.molecules_number;\n this.parameters_number = json.parameters_number;\n this.parameters = json.parameters;\n this.growth = json.growth;\n this.division_trigger = json.division_trigger;\n this.volume_share = json.volume_share;\n }",
"constructor(props) {\n super(props);\n let temp_robot_list;\n \n //TODO weird behavior when imported json check why default\n temp_robot_list=jsonSource.default;\n console.log(temp_robot_list);\n \n \n //creation of an initial state, a json object\n this.state = {\n robot_list:temp_robot_list,\n selected_robot_id:0,\n selected_parts:[],\n }; \n this.handleOnRobotSelected=this.handleOnRobotSelected.bind(this);\n this.getRobotFromId=this.getRobotFromId.bind(this);\n }",
"printRecipeInfo(data) {\n\t\tlet recipes = [];\n \n\t\tfor (let i = 0; i < data.hits.length; i++) {\n\t\t\tconst ptr = data.hits[i].recipe;\n\t\t\tlet recipe = {\n\t\t\t\tname: ptr.label,\n\t\t\t\tdescription: ptr.uri,\n\t\t\t\timage: null,\n\t\t\t\timageURL: ptr.image,\n\t\t\t\tgluten_free: (Math.random() > 0.5),\n\t\t\t\tdairy_free: (Math.random() > 0.5),\n\t\t\t\tvegetarian: (Math.random() > 0.5),\n\t\t\t\tvegan: (Math.random() > 0.5),\n\t\t\t\tprep_time: Math.floor(Math.random() * 60),\n\t\t\t\tcook_time: Math.floor(Math.random() * 180),\n\t\t\t\tinstructions: ptr.url, \n\t\t\t\trating: Math.floor(Math.random() * 10) + 1 \n\t\t\t};\n\t\t\trecipes.push(recipe);\n\t\t}\n \n\t\tconst jRecipes = JSON.stringify(recipes);\n\t\tconsole.log(jRecipes);\n\t}",
"function init() {\n loadJSON(function (response) {\n // Parse JSON string into object\n let actual_JSON = JSON.parse(response);\n\n setDisplay(actual_JSON);\n });\n}",
"setup(jsonEntry) {\n this.name = jsonEntry.name;\n this.altNames = jsonEntry.altNames;\n this.iconName = jsonEntry.iconName;\n this.visible = jsonEntry.visible;\n this.priority = jsonEntry.priority;\n this.iconMinLevel = jsonEntry.iconMinLevel;\n this.iconMaxLevel = jsonEntry.iconMaxLevel;\n this.textMinLevel = jsonEntry.textMinLevel;\n this.textMaxLevel = jsonEntry.textMaxLevel;\n switch (jsonEntry.stackMode) {\n case \"yes\":\n this.stackMode = harp_datasource_protocol_1.PoiStackMode.Show;\n break;\n case \"no\":\n this.stackMode = harp_datasource_protocol_1.PoiStackMode.Hide;\n break;\n case \"parent\":\n this.stackMode = harp_datasource_protocol_1.PoiStackMode.ShowParent;\n break;\n default:\n }\n }",
"constructor(props) {\n super(props);\n let temp_robot_list;\n \n temp_robot_list=jsonSource.default;\n console.log(temp_robot_list);\n \n \n //creation of an initial state, a json object\n this.state = {\n robot_list:temp_robot_list, \n }; \n }",
"function init(){\n\n JSON();\n\t\n}",
"function Recipe() { }",
"function packIntoJson(name, description, unitsProvided, ingredients, isIntermediate, packageName, temperatureZone, nativeUnit, numUnitPerPackage, productionLines){\n\tvar formulaJson = new Object();\n\tformulaJson.name = name;\n\tformulaJson.description = description;\n\tformulaJson.ingredients = ingredients;\n\tformulaJson.unitsProvided = unitsProvided;\n\tformulaJson.isIntermediate = isIntermediate;\n\tformulaJson.numUnitPerPackage = numUnitPerPackage;\n\tformulaJson.nativeUnit = nativeUnit;\n\tformulaJson.packageName = packageName;\n\tformulaJson.temperatureZone = temperatureZone;\n\tformulaJson.productionLines = productionLines;\n\t//console.log(ingredients);\n\treturn formulaJson;\n}",
"function getRecipes() {\n let jsn = fetchData('/recipes');\n }",
"function Recipe(recipeName, recipeIngredients, recipeServings, recipeCalories, recipeFatGrams, recipeProteinGrams, recipeSodiumGrams) {\n\tthis.name = recipeName;\n\tthis.ingredients = recipeIngredients;\n\tthis.servings = recipeServings;\n\tthis.calories = recipeCalories;\n\tthis.fatGrams = recipeFatGrams;\n\tthis.proteinGrams = recipeProteinGrams;\n\tthis.sodiumGrams = recipeSodiumGrams;\n}",
"function ingredientsJSON() {\n let arIngredients = [];\n let objIngredients = [];\n // Loop through all recipes\n for (let i = 0; i < arList.length; i++) {\n const thisRecipe = arList[i];\n // Add the ingredients from this recipe into the mast list\n let tempArray = thisRecipe.shopping.concat(arIngredients);\n // Filter out the duplicates\n tempArray = tempArray.filter(onlyUnique);\n arIngredients = tempArray;\n }\n arIngredients.sort();\n\n for (let i = 0; i < arIngredients.length; i++) {\n const obj = {\n 'name': arIngredients[i],\n 'id': arIngredients[i].toLowerCase().replace(/\\s+/g,'-'),\n 'keto': true,\n 'dairy': false,\n 'meat': false,\n 'alcohol': false,\n 'caffeine': false,\n 'eggs': false,\n 'fish': false,\n 'gluten': false,\n 'lactose': false,\n 'lamb': false,\n 'nuts': false,\n 'shellfish': false,\n 'soy': false\n };\n objIngredients.push(obj);\n }\n console.log(objIngredients);\n }",
"function recipeJSONizer() {\n // Creating a stream through which each file will pass\n return through.obj(function (file, encoding, callback) {\n if (file === null) {\n // return empty file\n return callback(null, file);\n }\n if (file.isBuffer()) {\n console.log(\"Processing recipe \" + file.path.substring(process.cwd().length));\n var fileAsString = String(file.contents);\n var lines = splitIntoLines(fileAsString);\n var recipe = parseIntoRecipe(lines);\n var recipeAsJonString = JSON.stringify(recipe, undefined, 2);\n file.contents = Buffer.from(recipeAsJonString);\n file.path = file.path.replace(\".recipe\", \".json\");\n console.log(\"\");\n }\n if (file.isStream()) {\n throw new PluginError(PLUGIN_NAME, \"I'm afraid you haven't implemented a stream solution yet, Dave\");\n }\n callback(null, file);\n });\n}",
"function fillOptionalRecipeData(recipe) {\n if (recipe.result != null && recipe.result_count == null) {\n recipe.result_count = 1;\n }\n //console.log(recipe);\n if (recipe.category == null) {\n recipe.category = \"crafting\";\n }\n\n if (recipe.energy_required == null) {\n recipe.energy_required = 0.5;\n }\n\n if (recipe.enabled == null) {\n recipe.enabled = \"true\";\n }\n}",
"static prepareData(json) {\n // Define variables\n json.currentScene = \"\";\n json.parsedChoices = \"\";\n if (json.currentInventory === undefined) {\n json.currentInventory = 0;\n }\n if (json.inventories === undefined) {\n json.inventories = [[]];\n }\n if (json.inventories.length === 0) {\n json.inventories[0] = [];\n }\n if (json.scenes === undefined) {\n json.scenes = [{}];\n }\n if (json.tagPresets === undefined) {\n json.tagPresets = [];\n }\n if (json.sounds === undefined) {\n json.sounds = [];\n }\n for (let k = 0; k < json.inventories.length; k++) {\n let i = json.inventories[k];\n for (let i1 = 0; i1 < i.length; i1++) {\n let j = i[i1];\n if (j.displayName === undefined) {\n j.displayName = j.name;\n }\n }\n }\n // Prepare scenes\n for (let j1 = 0; j1 < json.scenes.length; j1++) {\n let s = json.scenes[j1];\n s.combinedText = \"\";\n s.parsedText = \"\";\n s.visited = false;\n if (s.text === undefined) {\n console.warn(`WARNING! scene ${s.name} has no text`);\n s.text = \"\";\n }\n if (s.choices === undefined) {\n console.warn(`WARNING! scene ${s.name} has no choices`);\n s.choices = [];\n }\n for (let k1 = 0; k1 < s.choices.length; k1++) {\n let c = s.choices[k1];\n c.parsedText = \"\";\n if (c.alwaysShow === undefined) {\n c.alwaysShow = false;\n }\n }\n }\n // Set default settings\n if (json.settings === undefined) {\n json.settings = {};\n }\n if (json.settings.debugMode === undefined) {\n json.settings.debugMode = false;\n }\n if (json.settings.saveMode === undefined) {\n json.settings.saveMode = \"text\";\n }\n if (json.settings.language === undefined) {\n json.settings.language = \"english\";\n }\n if (json.settings.showSaveButtons === undefined) {\n json.settings.showSaveButtons = true;\n }\n if (json.settings.showSkipButton === undefined) {\n json.settings.showSkipButton = false;\n }\n if (json.settings.inventoryHidden === undefined) {\n json.settings.inventoryHidden = false;\n }\n if (json.settings.choicesHidden === undefined) {\n json.settings.choicesHidden = false;\n }\n if (json.settings.alwaysShowDisabledChoices === undefined) {\n json.settings.alwaysShowDisabledChoices = false;\n }\n if (json.settings.floatPrecision === undefined) {\n json.settings.floatPrecision = 5;\n }\n if (json.settings.scrollSettings === undefined) {\n json.settings.scrollSettings = {};\n }\n if (json.settings.scrollSettings.defaultScrollSpeed === undefined) {\n json.settings.scrollSettings.defaultScrollSpeed = 60;\n }\n if (json.settings.scrollSettings.revisitSkipEnabled === undefined) {\n json.settings.scrollSettings.revisitSkipEnabled = true;\n }\n if (json.settings.scrollSettings.textSkipEnabled === undefined) {\n json.settings.scrollSettings.textSkipEnabled = true;\n }\n if (json.settings.scrollSettings.skipWithKeyboard === undefined) {\n json.settings.scrollSettings.skipWithKeyboard = false;\n }\n if (json.settings.scrollSettings.continueWithKeyboard === undefined) {\n json.settings.scrollSettings.continueWithKeyboard = true;\n }\n if (json.settings.scrollSettings.fastScrollWithKeyboard === undefined) {\n json.settings.scrollSettings.fastScrollWithKeyboard = true;\n }\n if (json.settings.scrollSettings.fastScrollSpeedMultiplier === undefined) {\n json.settings.scrollSettings.fastScrollSpeedMultiplier = 20;\n }\n if (json.settings.scrollSettings.tickFreqThreshold === undefined) {\n json.settings.scrollSettings.tickFreqThreshold = 100;\n }\n if (json.settings.soundSettings === undefined) {\n json.settings.soundSettings = {};\n }\n if (json.settings.soundSettings.soundVolume === undefined) {\n json.settings.soundSettings.soundVolume = 0.5;\n }\n if (json.settings.soundSettings.musicVolume === undefined) {\n json.settings.soundSettings.musicVolume = 0.4;\n }\n // Set default UI language values\n if (json.uiText === undefined) {\n return json.uiText = JSON.parse([\n {\"name\": \"saveText\", \"language\": \"english\", \"content\": \"Copy and save your save data:\" },\n {\"name\": \"loadText\", \"language\": \"english\", \"content\": \"Paste your save data here:\" },\n {\"name\": \"closeButton\", \"language\": \"english\", \"content\": \"Close\" },\n {\"name\": \"copyButton\", \"language\": \"english\", \"content\": \"Copy\" },\n {\"name\": \"saveButton\", \"language\": \"english\", \"content\": \"Save\" },\n {\"name\": \"loadButton\", \"language\": \"english\", \"content\": \"Load\" },\n {\"name\": \"loadDataButton\", \"language\": \"english\", \"content\": \"Load\" },\n {\"name\": \"skipButton\", \"language\": \"english\", \"content\": \"Skip\" },\n {\"name\": \"continueButton\", \"language\": \"english\", \"content\": \"Continue\" },\n {\"name\": \"inventoryTitle\", \"language\": \"english\", \"content\": \"Inventory:\" },\n {\"name\": \"hiddenInventoryTitle\", \"language\": \"english\", \"content\": \"Stats:\" }\n ]);\n }\n return json;\n }",
"processMeal(recipeInfo) {\n let ingredients = {};\n for (let i = 1; i <= 20; i++) {\n if (recipeInfo['strIngredient' + i.toString()]) {\n ingredients[recipeInfo['strIngredient' + i.toString()]] = recipeInfo['strMeasure' + i.toString()];\n }\n }\n const data = {\n 'name': recipeInfo['strMeal'],\n 'category': recipeInfo['strCategory'],\n 'area': recipeInfo['strArea'],\n 'ingredients': ingredients,\n 'instructions': recipeInfo['strInstructions'],\n 'image': recipeInfo['strMealThumb'],\n 'video': recipeInfo['strYoutube'],\n 'source': recipeInfo['strSource']\n };\n this.setState({\n loaded: true,\n recipe: data,\n });\n }",
"loadJSON(json) {\n this.area = json.area;\n this.type = json.type;\n }",
"function criaJsonVazio(){\n\tvar json = {};\n\treturn json;\n}",
"static prepareLoadedJson(json) {\n json = this.prepareData(json);\n novelData.novel = json;\n novelData.debugMode = novelData.novel.settings.debugMode;\n SoundManager.init();\n UI.init();\n novelData.novel.currentScene = SceneManager.changeScene(novelData.novel.scenes[0].name);\n novelData.status = \"Ready\";\n if (novelData.debugMode) {\n console.log(novelData);\n }\n return console.log(\"-- Loading Novel.js complete! --\");\n }",
"function Recipe(uuid, title, body, images, type) {\n this.title = title;\n this.body = body;\n this.images = images;\n this.uuid = uuid;\n this.type = type;\n }",
"function Recipe(title, image, id) {\n this.title = title;\n this.image = image;\n this.id = id;\n}",
"function Recipe(label, ingredients, image, url) {\n this.label = label;\n this.ingredients = ingredients;\n this.image = image;\n this.url = url;\n}",
"constructJsonObject ( shortName, description , dueDate, size, author, rewards ) {\n\n const taskDescriptionSingleObject = {};\n\n taskDescriptionSingleObject.shortName = shortName;\n taskDescriptionSingleObject.description = description;\n taskDescriptionSingleObject.dueDate = dueDate;\n taskDescriptionSingleObject.size = size;\n taskDescriptionSingleObject.author = author;\n taskDescriptionSingleObject.rewards = rewards;\n\n return JSON.stringify(taskDescriptionSingleObject);\n }",
"fetchRecipes()\n {\n fetch(`${PATH_BASE}${PATH_JSON}${PARAM_TYPE}`).then(response => response.json()).then(results => this.setState({ results }))\n }"
]
| [
"0.6471491",
"0.608637",
"0.606799",
"0.6017638",
"0.6016969",
"0.597",
"0.59593177",
"0.5933476",
"0.5918051",
"0.5867398",
"0.58452666",
"0.5821816",
"0.5797253",
"0.5783352",
"0.5777188",
"0.577637",
"0.57761616",
"0.57750916",
"0.5719448",
"0.5701435",
"0.5696114",
"0.5682246",
"0.5682238",
"0.5679111",
"0.5676083",
"0.5671499",
"0.5670681",
"0.5658849",
"0.5654158",
"0.5629766"
]
| 0.705978 | 0 |
on load it will try to get details, if there is a loggedin user | function loadDetails() {
return API.getUserDetails()
.done(function (data) {
userData = data;
renderUser(data)
})
.fail(function (err) {
/// message("Something went wrong");
if (err.status == 302) {
window.location = err.getResponseHeader('FORCE_REDIRECT');
return;
};
})
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"load() {\r\n this.userIdService.invokeWithUserId((userId) => {\r\n if (userId !== OCC_USER_ID_ANONYMOUS) {\r\n this.store.dispatch(new LoadUserDetails(userId));\r\n }\r\n });\r\n }",
"function loadCurrentUser() {\n UserService.GetCurrentUser().then(function (response) {\n vm.user = response.data;\n });\n }",
"function onLoad(){\n if(loggedUser.isLoggedIn === false){\n userHasAuthenticated(false);\n } else {\n userHasAuthenticated(true) \n }\n }",
"loadUser() {\n const needLogin = () => this.emit(\"loginRequired\");\n\n if (this.loadUserCredentials()) {\n const self = this;\n \n this.apiGet('auth/user', {}).then((response) => {\n const data = response.data;\n\n if (data.authority) {\n this.userInfo = data;\n \n this.emit(\"login\", {\n authenticated: true, \n userType: data.authority, \n userInfo: data,\n });\n\n } else {\n needLogin();\n }\n }).catch( error => {\n needLogin();\n });\n \n } else {\n needLogin();\n }\n \n }",
"function loadUser() {\n osapi.people.getViewer().execute(\n function(result){\n if (result.error){\n var lf_message = \"loadUser(): \" + result.error.message;\n mini.createDismissibleMessage(lf_message);\n } else {\n gf_userId = result.id;\n loadOwner();\n }\n }\n );\n}",
"function loadUser() {\n return Auth.currentAuthenticatedUser({ bypassCache: true });\n }",
"function populateUser() {\n // check if user is logged in server side...\n loginService.checkLoginStatus()\n .then(function(response){\n // if logged in, populate user from sessionStorage\n if (!!response.data) {\n $scope.user = sessionService.getUser();\n populateShoppingList();\n }\n });\n }",
"function getAuth(){\n firebase.auth().onAuthStateChanged(function(user) {\n if (user) {\n // console.log('user signed in', user)\n vm.userInfo = user;\n vm.status = true;\n vm.uuuid = user.uid;\n console.log(vm.userInfo, vm.status)\n getUserInfo(id, vm.uuuid)\n } else {\n console.log(\"// No user is signed in.\");\n var blank_user = {email: \"----\"}\n // vm.userInfo.email = 'NONE';\n }\n });\n }",
"async loadLoggedUser() {\n const currentUserId = await AsyncStorage.getItem('userID');\n const formattedUserId = await JSON.parse(currentUserId);\n const xAuthKey = await AsyncStorage.getItem('xAuth');\n const formattedXAuth = await JSON.parse(xAuthKey);\n this.setState({\n xAuth: formattedXAuth,\n userID: formattedUserId,\n });\n this.getProfile();\n console.log(\n 'Loaded logged userID: ' +\n this.state.userID +\n ' and x-auth: ' +\n this.state.xAuth,\n );\n }",
"function _getUser() {\n scope.user = true;\n Authentication.getAuthenticatedAccount().then(success, error);\n\n function success(user) {\n if (!user) {\n scope.user = null;\n scope.promoBar = true;\n return;\n }\n scope.user = user;\n scope.userLogged = true;\n Authentication.isOrganizer().then(function (result) {\n scope.user.is_organizer = result;\n scope.subItems ={\n activities: false,\n account: false,\n reviews: false,\n transactions: false\n }\n if(scope.user.is_organizer){\n scope.promoBar = false;\n _getOrganizerReviews();\n }\n \n });\n Authentication.isStudent().then(function (result) {\n scope.user.is_student = result;\n scope.subItems ={\n activities: false\n }\n if(scope.user.is_student){\n scope.promoBar = false;\n _getStudentMessages();\n }\n \n });\n _mapDisplayName(scope.user);\n _setUserChangedWatch();\n \n }\n \n function error() {\n scope.user = null;\n console.log(scope.user);\n _setUserChangedWatch();\n }\n \n \n }",
"function init(){\n UserService\n .getCurrentUser()\n .then(function(user){\n if(user.data){\n console.log(user.data);\n $rootScope.currentUser = user.data;\n $scope.user = null;\n }else{\n $location.url(\"/login\");\n }\n });\n\n //find all the forms for user\n UserService\n .findAllUsers()\n .then(function(response){\n $scope.users = response.data;\n },\n function(err){\n $scope.error = err;\n });\n }",
"fetchCurrentUser() {\n authFetch(\"/api/get-user\").then(response => response.json())\n .then(data => {\n if (data.id === this.state.username) {\n this.setState({\n currentUser: data.id,\n email: data.email,\n bio: data.about,\n private_acc: false,\n isLoading: false\n })\n } else {\n this.setState({\n currentUser: data.id,\n })\n this.fetchUserDetails();\n }\n this.fetchPosts();\n })\n .catch(error => this.setState({ userError: error, isLoading: false }));\n }",
"function getLoggedInUser() {\n\t$.ajax({\n\t\ttype : \"GET\",\n\t\turl : \"rest/user\",\n\t\tasync : false,\n\t\tbeforeSend : function(xhr) {\n\t\t\tvar token = window.sessionStorage.getItem(\"sessionToken\");\n\t\t\txhr.setRequestHeader('Authorization', 'Bearer ' + token);\n\t\t},\n\t\tsuccess : function(data) {\n\t\t\t//Set user object from data\n\t\t\tuser = data;\n\t\t\t\n\t\t\t//Update header\n\t\t\tsetHeader();\n\t\t},\n\t\terror : function(xhr, ajaxOptions, thrownError) {\n\t\t\t//Give error by code\n\t\t\tswitch (xhr.status) {\n\t\t\t\tcase 403:\n\t\t\t\t\tuser = null;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: \n\t\t\t\t\tdisplayError(\"Kan gebruikersdata niet ophalen.\");\n\t\t\t}\n\t\t}\n\t});\n}",
"async function checkIfLoggedIn() {\n\t\tconst token = localStorage.getItem('token');\n\t\tconst username = localStorage.getItem('username');\n\t\tcurrentUser = await User.getLoggedInUser(token, username);\n\t\tawait generateStories();\n\n\t\tif (currentUser) {\n\t\t\tshowProfile();\n\t\t\tshowNavForLoggedInUser();\n\t\t}\n\t}",
"function getUserInformation() {\n // perform get request\n $.get(\"/users/me\")\n .done(initializePage)\n .fail(function() {\n // if failed, show the login link\n $(\"#login-link\").show();\n $(\"#logout-link\").hide();\n $(\"#user-name\").text(\"\");\n // configure login modal to show when navigating from home tab\n $('#home-tab').on('hide.bs.tab', function (e) {\n $(\"#login-modal\").modal(\"show\");\n });\n });\n}",
"async loadUserFromLocalStorage() {\n let userInfo = (await this.oreId.getUser()) || {};\n if(userInfo.accountName) this.setState({ userInfo, isLoggedIn: true });\n }",
"async loadUserFromLocalStorage() {\n let userInfo = (await this.oreId.getUser()) || {};\n if(userInfo.accountName) this.setState({ userInfo, isLoggedIn: true });\n }",
"function init() {\n UserService\n // .findUserById(id)\n .findCurrentUser()\n .then(function (response) {\n vm.user = response.data;\n if(vm.user){\n console.log(vm.user._id);\n vm.success=\"Please Complete your information\";\n }else {\n vm.error = \"User not Found\";\n }\n });\n }",
"function checkIfUserInitialized() {\n if (currentuser) {\n loadHomePage();\n } else {\n updateCurrentUser().then(function () {\n loadHomePage();\n }).catch(function () {\n loadSettingsPage();\n });\n }\n}",
"async function onLoad() {\n try {\n const loggedInUser = sessionStorage.getItem(\"username\");\n if (loggedInUser) {\n userHasAuthenticated(true);\n } else {\n userHasAuthenticated(false);\n sessionStorage.setItem(\"username\", \"generalUser\");\n sessionStorage.setItem(\"userType\", \"client\");\n }\n }\n catch(e) {\n if (e !== 'No current user') {\n onError(e);\n }\n }\n\n setIsAuthenticating(false);\n }",
"function getUser() {\n // API request for the current user.\n $.ajax({\n cache: false\n , crossDomain: true\n , dataType: 'jsonp'\n , success: function (data, requestStatus) {\n if (requestStatus === 'success') {\n if (data.user) {\n updateLoginText(data.user);\n } else {\n $('.accounts-login-link a').each(function()\n {\n this.href = this.href.replace(/\\/accounts/, '/accounts/user/login');\n });\n updateLoginText(\"Login\");\n }\n }\n }\n , type: 'GET'\n , url: Drupal.settings.basePath + 'user/state'\n });\n }",
"_loadActiveUser() {\r\n\t\ttry {\r\n\t\t\tif(window.localStorage) {\r\n\t\t\t\tthis._activeUserID = localStorage.getItem(\"active_user\");\r\n\t\t\t}\r\n\t\t} catch(error) {\r\n\t\t\t//Fail silently\r\n\t\t}\r\n\t}",
"loadInformation() {\n //Check if the user exists first\n var userExists = false, referThis = this;\n var userId = referThis.props.userId;\n database.ref('users/').child(userId).on('value', function (snapshot) {\n if (snapshot.val() !== null) {\n userExists = true;\n }\n\n //If the user exits, then the refill the sections, if not ask to fill it in. \n if (userExists) {\n\n //Set the Profile Pic and Background Pics from the URLs in the Firebase Dtabase\n referThis.nameAndPicSetup(userId);\n\n /**\n * Fill in the About section.\n */\n referThis.fillAboutSection(userId);\n } else {\n window.alert(\"This user does not Exist\");\n window.location.replace(\"/\");\n }\n });\n }",
"function loadUserInfo() {\n \t $.ajax({\n \t\t\turl: \"/Demand1/auth/GetCurrentUser.html\",\n \t\t\ttype: \"GET\",\n \t\t\tdataType: \"json\",\n \t\t\tsuccess:initUserData\n \t\t});\t\t\n\t}",
"async function checkIfLoggedIn() {\n\t\t// let's see if we're logged in\n\t\tconst token = localStorage.getItem('token');\n\t\tconst username = localStorage.getItem('username');\n\n\t\t// if there is a token in localStorage, call User.getLoggedInUser\n\t\t// to get an instance of User with the right details\n\t\t// this is designed to run once, on page load\n\t\tcurrentUser = await User.getLoggedInUser(token, username);\n\t\tawait generateStories();\n\n\t\tif (currentUser) {\n\t\t\tgenerateProfile();\n\t\t\tshowNavForLoggedInUser();\n\t\t}\n\t}",
"async function checkIfLoggedIn() {\n\t\t// let's see if we're logged in\n\t\tconst token = localStorage.getItem('token');\n\t\tconst username = localStorage.getItem('username');\n\n\t\t// if there is a token in localStorage, call User.getLoggedInUser\n\t\t// to get an instance of User with the right details\n\t\t// this is designed to run once, on page load\n\t\tcurrentUser = await User.getLoggedInUser(token, username);\n\t\tawait generateStories();\n\n\t\tif (currentUser) {\n\t\t\tshowNavForLoggedInUser();\n\t\t}\n\t}",
"function init() {\n MeService.getUserInfo().then(function ( data ) {\n vm.info = angular.merge({}, data, UserService.getInfo());\n });\n }",
"function currentUser() {\n return loadCache({\n id: 'login'\n });\n }",
"function getUser(id) {\n if (id === undefined) {\n id = userSettings.user_id;\n }\n\n return $.when(\n getItem('User', id, {expand_dropdowns: '0'})\n ).done(function(user) {\n console.info(\"Got signed-in user information\");\n\n // Store user information\n userSettings.user_data = user;\n\n $.Event(\"user_identified\", {message: \"Welcome \" + user.firstname + \" \" + user.realname + \".\"})\n })\n}",
"function getUserLoggedIn() {\n\t//console.log('getUserLoggedIn');\n\t\n\t// Not used anymore\n\t\t\n\t\n}"
]
| [
"0.7307482",
"0.71317965",
"0.68721694",
"0.686145",
"0.67589873",
"0.6721293",
"0.6711474",
"0.67027605",
"0.66994476",
"0.66971534",
"0.66786444",
"0.66509473",
"0.65928626",
"0.65892994",
"0.6564492",
"0.6554724",
"0.6554724",
"0.65513384",
"0.65355587",
"0.6531277",
"0.6521365",
"0.6510181",
"0.6504085",
"0.6484206",
"0.648244",
"0.6444967",
"0.64390206",
"0.6438795",
"0.6436455",
"0.64355296"
]
| 0.72173035 | 1 |
Insert data into 'real_estate' table | insertRealEstate(data, callback){
this.executeMySQL("INSERT INTO real_estates(real_estate_name, real_estate_price, real_estate_area, real_estate_date, real_estate_url, district_id) VALUES ?", [data]).then(function(success){
callback(true);
}).catch(function(err){
console.log(err);
callback(false);
})
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function sendStatesDataToDB(result) {\n let stmt = \"UPDATE states SET covid_death = ?, covid_count = ?, trajectory_hospitalize = ?, \" +\n \" trajectory_test = ? WHERE state_ab = ?;\";\n var query = \"\";\n var data = [];\n \n result.forEach(function(singleState) {\n query += stmt;\n data.push(singleState.deathIncrease);\n data.push(singleState.positiveIncrease);\n data.push(singleState.hospitalizedIncrease);\n data.push(singleState.totalTestResultsIncrease);\n data.push(singleState.state);\n });\n \n connection.query(query, data, function(error, results) {\n if(error) throw error;\n \n console.log(\"Update successful!\");\n });\n}",
"function insertdata(data){\n\n let cases = db.sequelize.query('INSERT INTO \"SACases\" (`date`, `date1`, `EC`, `FS`, `GP`, `KZN`, `LP`, `MP`, `NC`, `NW`, `WC`, `UNKNOWN`, `total`, `source`, `createdAt`, `updatedAt`) VALUES (:date, :date, :EC, :FS, :GP, :KZN, :LP, :MP, :NC, :NW, :WC, :UNKNOWN, :total, :source, DATE(\"now\"), DATE(\"now\"))', {\n replacements: {date: data.date , date1:data.date, EC:data.EC, FS:data.FS, GP:data.GP, KZN:data.KZN, LP:data.LP, MP:data.MP, NC:data.NC, NW:data.NW, WC:data.WC, UNKNOWN:data.UNKNOWN, total:data.total, source:data.source },\n type: db.sequelize.QueryTypes.INSERT\n });\n\n console.log(\"Getdata ran\");\n }",
"function saveBusArrivalEntry(data, connection, errCounter) {\n // INSERT INTO `Bus_arrival` VALUES (1,2,false,'2010-01-19 03:14:07') ON DUPLICATE KEY UPDATE `prediction`='2020-01-19 03:14:07'\n return connection.query(`INSERT INTO \\`Bus_arrival\\`(\\`route\\`,\\`sn\\`,\\`is_reverse\\`,\\`prediction\\`) VALUES (${data.route},${data.sn},${data.isReverse},'${util.toSqlTimestamp(data.nextBus.timestamp)}') ON DUPLICATE KEY UPDATE \\`prediction\\`='${util.toSqlTimestamp(data.nextBus.timestamp)}'`);\n}",
"function addEmployees(data) {\n\n connection.query(\"INSERT INTO employee SET ?\",\n {\n first_name: data.firstName,\n last_name: data.lastName,\n role_id: data.title,\n manager_id: data.manager\n }, function (error, res) {\n if (error) throw error;\n connection.query(\"SELECT * from employee\", function (error, res) {\n // console.log(error, res);\n showemployees = res.map(emp => ({ name: `${emp.first_name} ${emp.last_name}`, value: emp.id }))\n })\n })\n endOrMenu();\n}",
"function insertToTemporaryTable() {\n\t\tclient\n\t\t.query(query2)\n\t\t.then(res => {\n\t\t\tconsole.log(\"Added ingredients_needed\");\n\t\t\tsearchForRecipes();\n\t\t})\n\t\t.catch(e => console.error(e.stack))\n\t}",
"function insertdata1(data){\n\n let wcases = db.sequelize.query('INSERT INTO \"WorldCases\" (`Date_reported`, `Country_code` , `Country`, `WHO_region`, `New_cases`, `Cumulative_cases`, `New_deaths`, `Cumulative_deaths`, `createdAt`, `updatedAt`) VALUES (:Date_reported, :Country_code, :Country, :WHO_region, :New_cases, :Cumulative_cases, :New_deaths, :Cumulative_deaths, DATE(\"now\"), DATE(\"now\"))', {\n replacements: {Date_reported: data.Date_reported , Country_code:data.Country_code, Country:data.Country, WHO_region:data.WHO_region, New_cases:data.New_cases, Cumulative_cases:data.Cumulative_cases, New_deaths:data.New_deaths, Cumulative_deaths:data.Cumulative_deaths },\n type: db.sequelize.QueryTypes.INSERT\n });\n\n console.log(\"Worlddata ran\");\n}",
"function prepareDataInsertDb(evid, thash, ptoken, pdata) {\n var data = {\n \"id\": evid,\n \"token\": ptoken,\n \"txHash\": thash,\n \"blockNumber\": pdata.blockNumber,\n \"blockHash\": pdata.blockHash,\n \"chainId\": pdata.chainId,\n \"condition\": pdata.condition,\n \"creates\": pdata.creates,\n \"from\": pdata.from,\n \"gas\": pdata.gas,\n \"gasPrice\": pdata.gasPrice,\n \"hash\": pdata.hash,\n \"input\": pdata.input,\n \"nonce\": pdata.nonce,\n \"publicKey\": pdata.publicKey,\n \"r\": pdata.r,\n \"raw\": pdata.raw,\n \"s\": pdata.s,\n \"standardV\": pdata.standardV,\n \"to\": pdata.to,\n \"transactionIndex\": pdata.transactionIndex,\n \"v\": pdata.v,\n \"value\": pdata.value,\n }\n // console.log(data)\n setToDB(data)\n}",
"static insert(data = []) {\n return execute(`INSERT INTO parcels (id, origin, destination, user_id, created_date, price, present_location, weight)\n VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, data);\n }",
"function setStationInDB(title, source, site, section) {\n var db = getDatabase();\n var res = \"\";\n db.transaction(function(tx) {\n var rs = tx.executeSql('INSERT OR REPLACE INTO stations VALUES (?,?,?,?);', [title,source,site,section]);\n //console.log(rs.rowsAffected)\n if (rs.rowsAffected > 0) {\n res = \"OK\";\n } else {\n res = \"Error\";\n }\n }\n );\n // The function returns “OK” if it was successful, or “Error” if it wasn't\n console.log(\"Fav set to db:\"+\" title:\"+title+\" source:\"+source+\" site:\"+site+\" section:\"+section)\n return res;\n}",
"function insertData()\n{\n //Location\n \n var id=document.getElementById(\"IdH\").innerHTML;\n var country=document.getElementById(\"country\").innerHTML;\n var city=document.getElementById(\"city\").innerHTML;\n //Weather\n var temp=document.getElementById(\"tempW\").innerHTML;\n var condition=document.getElementById(\"condition\").innerHTML;\n var date=document.getElementById(\"lastUpdated\").innerHTML;\n db.transaction(function(tx) {\n tx.executeSql('INSERT INTO history VALUES (?,?,?,?,?,?)', [id,country, city, temp , condition, date]);\n\n }, function(error) {\n console.log('Transaction ERROR: ' + error.message);\n }, function() {\n console.log('Populated database OK');\n });\n generateID();\n}",
"function insertRecital(recital) {\n\tconst { date, end_time, start_time } = recital;\n\tdb.query(`INSERT INTO recital (date, end_time, start_time) `+\n\t\t`VALUES(\"${date}\",\"${end_time}\",\"${start_time}\")`);\n\n}",
"addLocation(location, adress, success) {\n connection.query('insert into Sted (sted_navn, adresse) values (?, ?)', [location, adress], (error, results) =>{\n if (error) return console.error(error);\n\n success();\n });\n }",
"function addEmployeeRole(data) {\n connection.query(\"INSERT INTO role SET ?\", {\n title: data.title,\n salary: data.salary,\n department_id: data.id\n }, function (error, res) {\n // console.log(error, res);\n if (error) throw error;\n connection.query(\"SELECT * from role\", function (error, res) {\n showroles = res.map(role => ({ name: role.title, value: role.id }))\n })\n });\n endOrMenu();\n}",
"dataInsert(e) { \n console.log(`--- data:insert fired ---`, e.detail);\n let newValues = {\n breed: e.detail.ZGData.data.breed,\n name: e.detail.ZGData.data.name,\n };\n // push record to our array\n this.datastore.push(newValues);\n this.stringifyData();\n }",
"add(table, data) {\n return new Promise((resolve, reject) => {\n switch (table) {\n case \"current\":\n //Insert new record into current table\n this.pool.query(`INSERT INTO current values('${data.id}', '${data.name}', '${data.description}', ${data.state})`, (error, results, fields) => {\n if (this.checkError(error)) { reject() }\n else {\n Logger.info(\"sql\", `Inserted into current: ${data.id}`);\n resolve();\n }\n })\n break;\n case \"query\":\n //Insert new record into query table\n this.pool.query(`INSERT INTO query values('${data.id}', '${data.playersOn}', '${data.playersMax}', '${data.version}', '${data.players}')`, (error, results, fields) => {\n if (this.checkError(error)) { reject() }\n else {\n Logger.info(\"sql\", `Inserted into current: ${data.id}`);\n resolve();\n }\n })\n break;\n default:\n Logger.error(\"sql\", \"none\", \"Given invalid table, cannot create new record\");\n reject();\n }\n })\n }",
"function insert_to_users_table(data)\n{\n const email = data[0];\n const name = data[1];\n const hash = data[2];\n\n console.log(\"inserting user to users table\");\n return new Promise((resolve, reject) =>\n {\n var data = {USERNAME: name, PASSHASH: hash, EMAIL: email};\n db.query(\"INSERT INTO ?? SET ?\", [init.db.user_table, data], (err, res) =>\n {\n if (err) reject([err.code, err.sql]);\n else\n {\n console.log(email, \" inserted into table of users.\", \"hash: \", hash);\n resolve(data);\n }\n });\n });\n}",
"function insertInFlightDetails(obj) {\n return new Promise((resolve,reject)=>{\n connection.query(\n `INSERT INTO flight_details(flight_id, flight_name, capacity) \n VALUES(?,?,?)`,\n [obj.flightId,obj.flightName,obj.capacity],\n function(err,result)\n {\n if(err)\n reject(err)\n else \n resolve(result)\n }\n )\n })\n}",
"function add_travel_info(date_duration, person_id, to_location, from_location, callback){\n db_connection.query(\"INSERT INTO \\\"TravelInfo\\\" (\\\"DateDuration\\\", \\\"PersonID\\\", \\\"ToLocation\\\", \\\"FromLocation\\\") VALUES ($1, $2, $3, $4);\",\n [date_duration, person_id, to_location, from_location], callback);\n }",
"saveBusinesDetails(businessId, businessSectorId, rangeOfService, website, restrictedBusiness, selectedIndustries){ \n return new Promise((resolve, reject) => {\n let sql = `insert into business_sector_details (business_id,business_sector,range_of_service,website,restricted_business,selected_industries)\n values (${businessId},${businessSectorId},${rangeOfService},${website},${restrictedBusiness},\n ${selectedIndustries})`;\n dbInstance.executeQuery(sql)\n .then(result=>{\n resolve(result);\n })\n .catch(err=>{\n reject(err);\n });\n })\n }",
"function dbData(db, username, body){\r\n var sql = `INSERT INTO timetable.${username} (activities, priority, lunch, hygene, sleep) VALUES ('${body.activities}', '${body.priority}', '${body.meal}','${body.sleep}','${body.hygene}')`;\r\n db.query(sql, function(err){\r\n if(err) throw err\r\n console.log('succeed addting activities to account');\r\n })\r\n}",
"function insertIntoDB(rideObj) {\n //TODO: Remove hard coded values and use real value from users\n console.log(\"Insert into DB\");\n dbClient.query(\n `INSERT INTO ride(user_id, start_location, end_location, capacity, available, embedded_map, ride_date, created_on, price_per_seat) VALUES ($1, $2, $3, $4, $5, $6, (TIMESTAMP '${rideObj.ride_date}'), Now(), $7);`,\n [rideObj.user_id, rideObj.start_location, rideObj.end_location, rideObj.capacity, rideObj.available, rideObj.embedded_map, rideObj.price_per_seat],\n (err, res) => {\n if (res) {\n console.log(res);\n } else {\n console.log(\"There was an error inserting user into database \" + err);\n }\n }\n );\n}",
"sensorSpace(idSensor, idSpace, result) {\n sql.query(\n `Insert into sensor_space SET idSensor=?,idSpace=?`,\n [idSensor, idSpace],\n (err, rows) => {\n if (err) {\n console.log(\"ERRO?\", err); //Falar com alvaro\n result(err, rows);\n return;\n }\n console.log(idSensor, idSpace);\n\n result(null, rows);\n console.log(rows);\n }\n );\n }",
"add(body, res) {\n res.locals.connection.query('INSERT INTO personal_car SET ?', body, function (error, results, fields) {\n if (error) throw error;\n res.end(JSON.stringify(results));\n });\n }",
"function add_location_info(location, callback){\n db_connection.query(\"INSERT INTO \\\"Location\\\" (\\\"Location\\\") VALUES ($1);\", [location], callback);\n }",
"function insertRecord(info) {\n db.transaction(function(tx) {\n tx.executeSql(insertIntoTable, info, function(){}, onInsertError);\n });\n }",
"function insertRecords(state, payload) {\n const { entity, records } = payload;\n new Connection(this, state.$name, entity).insertRecords(records);\n}",
"function updateStatesTable() {\n getLatestCOVIDStatesInfo()\n .then(sendStatesDataToDB)\n .catch(function(error){\n console.log(error);\n });\n}",
"function insertRowIntoGoogleFusionTable(lat, lng, address) {\n console.log(\"Insert called\");\n\n var query = \"INSERT INTO \" + fusionTableId + \" (Address, Location) VALUES ('\" + address + \"', '\" + lat + \", \" + lng + \"')\";\n\n gapi.client.fusiontables.query.sql({sql:query}).execute(function(response){console.log(response);});\n}",
"async function addStructure(req, res, next){\r\n const db = await makeDb(config);\r\n let results = {};\r\n //console.log(req.body);\r\n \r\n var data = {\r\n user_id: req.body.user_id,\r\n title: req.body.title,\r\n type: req.body.type,\r\n place: req.body.place,\r\n street: req.body.street,\r\n number: req.body.number,\r\n post_code: req.body.post_code,\r\n description: req.body.description,\r\n location_description: req.body.location_description,\r\n beds: req.body.beds,\r\n price: req.body.price,\r\n fullboard: req.body.fullboard,\r\n wifi: req.body.wifi,\r\n parking: req.body.parking,\r\n kitchen: req.body.kitchen,\r\n airConditioner: req.body.airConditioner,\r\n image1: req.body.image1,\r\n image2: req.body.image2,\r\n image3: req.body.image3,\r\n image4: req.body.image4,\r\n start_date: req.body.start_date\r\n };\r\n var sql = 'INSERT INTO structure SET ?';\r\n try {\r\n await withTransaction(db, async() => {\r\n // inserimento utente\r\n results = await db.query(sql, data, (err, result) => {\r\n if(err) throw err;\r\n });\r\n });\r\n res.status(201);\r\n res.end();\r\n }catch (err) {\r\n console.log(err);\r\n next(createError(500));\r\n }\r\n}",
"save(data,cb) {\n conn.query('SELECT * FROM team where id = ?', data.id, (err,rows) => {\n console.log(`Num de registros: ${rows.length}`);\n\n if(!err) {\n return (rows.length == 1) \n ? conn.query('UPDATE team SET ? WHERE id = ?', [data, data.id], cb)\n : conn.query('INSERT INTO team SET ?', data, cb);\n }\n });\n }"
]
| [
"0.55630094",
"0.5552992",
"0.54735714",
"0.54402804",
"0.53643495",
"0.5342236",
"0.52883154",
"0.5274545",
"0.5263654",
"0.5248683",
"0.5242633",
"0.52060825",
"0.520223",
"0.5177058",
"0.51674086",
"0.51644",
"0.515226",
"0.5142226",
"0.51367766",
"0.51305705",
"0.5125357",
"0.5106022",
"0.51013666",
"0.5078729",
"0.5065851",
"0.50100946",
"0.49928877",
"0.49784926",
"0.49681455",
"0.49499103"
]
| 0.6507925 | 0 |
Mark this game object for destroy | destroy(){
this.markedDestroy = true;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function destroy(){}",
"destroy() {\n this.reset(false);\n this.options.onDestroy(this);\n }",
"destroy() {\n this.spriteObject.destroy();\n }",
"function destroy(){\n\t\t// TODO\n\t}",
"destroy(){}",
"destroy(){}",
"function destroy () {\n\t\t// TODO\n\t}",
"willDestroy() {}",
"function destroy(){\r\n }",
"function destroy(){\r\n }",
"markForDestruction(r) { r._destroy = true; }",
"destroy(delay = 0) { GameObject.destroy(this, delay); }",
"destroyed() { }",
"destroy() {\n\t let timer = destroyTimer;\n\t \n\t // animate the ball to disappear\n\t if (this.status != \"destroyed\" && (frameCount % 10 == 0 && timer > 0)) {\n\t\t this.diameter = this.diameter / 2;\n this.vy = -10;\n\t\t timer--;\n\t }\n\t \n\t // actually get rid of it from the array\n\t if (timer <= 0) {\n\t\t this.status = \"destroyed\";\n\t\t balls.splice(id,1);\t// remove the ball\n\t\t console.log(this.id + \"destroyed\");\n\t }\n }",
"destroy() {\n this.Sprite.destroy();\n delete this;\n }",
"destroy() {\n if (this.manager) {\n this.manager.kill();\n }\n if (lastFrame) {\n cancelFrame(lastFrame);\n }\n this.initialized = false;\n }",
"destroy() {\n if (!this._lottie) {\n return;\n }\n\n this._lottie.destroy();\n\n this.currentState = exports.PlayerState.Destroyed;\n this.dispatchEvent(new CustomEvent(exports.PlayerEvents.Destroyed));\n this.remove();\n }",
"destroy() {\n this.destroyed = true;\n this.disconnect();\n }",
"async destroy() {\r\n this.stop();\r\n }",
"destroy() {\n //TODO this.\n }",
"_destroy() {\n if (this._destroyed) {\n return;\n }\n this._destroyed = true;\n this.emit('end');\n }",
"postDestroy() {\n this.scope = null;\n this.canvas = null;\n }",
"destroy() {\n\t\t// Do somthing here\n\t}",
"destroy()\n {\n if (this.ticking)\n {\n SharedTicker.remove(this.tick, this);\n }\n this.ticking = false;\n this.addHooks = null;\n this.uploadHooks = null;\n this.renderer = null;\n this.completes = null;\n this.queue = null;\n this.ctx = null;\n this.canvas = null;\n }",
"destroy () {\n if (this._destroyables) {\n _.invoke(this._destroyables, 'destroy');\n this._destroyables = null;\n }\n this.trigger('destroy');\n if (this._listeners) {\n this._listeners = null;\n }\n }",
"destroy() {\n this._camera = null;\n this._scene = null;\n }",
"destroy() {\n this.clear();\n }",
"function OnRemoveFromManager() // Callback by the manager.\r\n\t{\r\n\t\tif (canDestroy)\t\t\r\n\t\t\tDestroy(gameObject);\t\t\r\n\t}",
"destroy() { super.destroy({ children: true, texture: true }); }",
"destroy() { super.destroy({ children: true, texture: true }); }"
]
| [
"0.74294096",
"0.7390618",
"0.7362749",
"0.7221283",
"0.7209021",
"0.7209021",
"0.71896374",
"0.71837884",
"0.7167157",
"0.7167157",
"0.70875853",
"0.7081102",
"0.7054614",
"0.700984",
"0.697873",
"0.69145703",
"0.6902593",
"0.6902515",
"0.6838855",
"0.6828801",
"0.68215644",
"0.67998636",
"0.67930245",
"0.67780524",
"0.6760338",
"0.6718431",
"0.66972667",
"0.6691396",
"0.66887885",
"0.66887885"
]
| 0.79606366 | 0 |
Get a game object by name | getGameObject(name){
for(let child of this.children){
if(child.name == name) return child;
let foundChild = child.getGameObject(name);
if(foundChild) return foundChild;
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function FindGameObjectWithName (name) {\n for (var i = 0; i < _gameobjects.length; i++) {\n if (_gameobjects[i].name === name) return _gameobjects[i];\n }\n return false;\n}",
"getGameObject(name) {\n for (let child of this.children) {\n if (child.name == name) return child;\n let foundChild = child.getGameObject(name);\n if (foundChild) return foundChild;\n }\n //console.error(\"Couldn't find game component \" + name)\n }",
"static async getObjectFromName(objectName){\n let objectID = RPM.game.hero.system.id; //Gets the hero's ID so that only camera view is considered.\n\n //Portions of the map based on the event's position.\n let globalPortion = SceneMap.getGlobalPortion(RPM.currentMap.allObjects[\n objectID]);\n \n let localPortion = RPM.currentMap.getLocalPortion(globalPortion);\n let mapPortion;\n \n let returningObj = null; //The object that is returned.\n if (RPM.currentMap.isInPortion(localPortion))\n {\n \n mapPortion = RPM.currentMap.getMapPortionByPortion(localPortion);\n let objects = mapPortion.objectsList;\n for (let i = 0; i < objects.length; i++)\n { \n if (objects[i].system.name === objectName)\n {\n returningObj = objects[i]; \n break;\n }\n }\n }\n return returningObj;\n }",
"function getPlayer(name) {\n for (let uuid in players) {\n if (players[uuid].name === name) return players[uuid];\n }\n}",
"function getObject(name){\n\treturn w[name]\n}",
"function getObjectByName(objName) {\n var objFound;\n var runTime = _pGlob !== undefined;\n objFound = runTime ? _pGlob.objCache[objName] : null;\n\n if (objFound && objFound.name === objName)\n return objFound;\n\n appInstance.scene.traverse(function(obj) {\n if (!objFound && notIgnoredObj(obj) && (obj.name == objName)) {\n objFound = obj;\n if (runTime) {\n _pGlob.objCache[objName] = objFound;\n }\n }\n });\n return objFound;\n}",
"function getObjectByName(objName) {\n var objFound;\n var runTime = _pGlob !== undefined;\n objFound = runTime ? _pGlob.objCache[objName] : null;\n\n if (objFound && objFound.name === objName)\n return objFound;\n\n appInstance.scene.traverse(function(obj) {\n if (!objFound && notIgnoredObj(obj) && (obj.name == objName)) {\n objFound = obj;\n if (runTime) {\n _pGlob.objCache[objName] = objFound;\n }\n }\n });\n return objFound;\n}",
"function getObjectByName(objName) {\n var objFound;\n var runTime = _pGlob !== undefined;\n objFound = runTime ? _pGlob.objCache[objName] : null;\n\n if (objFound && objFound.name === objName)\n return objFound;\n\n appInstance.scene.traverse(function(obj) {\n if (!objFound && notIgnoredObj(obj) && (obj.name == objName)) {\n objFound = obj;\n if (runTime) {\n _pGlob.objCache[objName] = objFound;\n }\n }\n });\n return objFound;\n}",
"function getObjectByName(objName) {\n var objFound;\n var runTime = _pGlob !== undefined;\n objFound = runTime ? _pGlob.objCache[objName] : null;\n\n if (objFound && objFound.name === objName)\n return objFound;\n\n appInstance.scene.traverse(function(obj) {\n if (!objFound && notIgnoredObj(obj) && (obj.name == objName)) {\n objFound = obj;\n if (runTime) {\n _pGlob.objCache[objName] = objFound;\n }\n }\n });\n return objFound;\n}",
"get_instance(name){\n for (instance in this.arr){\n if (instance[1] == name) {\n return instance[0];\n }\n }\n }",
"get gameObject() {}",
"function getObject(name) {\n return document.getElementById(name);\n}",
"function getObjectById(_id){\n\t\t\n\t\tfor (var i = 0; i < gameObjects.length; i++){\n\t\t\t\n\t\t\tif(gameObjects[i].hasOwnProperty('id')){\n\t\t\t\t\n\t\t\t\tif(gameObjects[i].id == _id)\n\t\t\t\t\treturn gameObjects[i];\n\t\t\t}\n\t\t}\n\t}",
"function FindGameObjectsWithName (name) {\n var aG = []\n for (var i = 0; i < _gameobjects.length; i++) {\n if (_gameobjects[i].name === name) aG.push(_gameobjects[i]);\n }\n return aG;\n}",
"function getPlayer(name) {\n return new Player(name);\n }",
"static findSceneByName(name) {\n Util.checkFormat(name,'string');\n for (let j = 0; j < novelData.novel.scenes.length; j++) {\n let i = novelData.novel.scenes[j];\n if (i.name === name) {\n return i;\n }\n }\n return console.error(`ERROR: Scene by name '${name}' not found!`);\n }",
"getPlayer(name) {\n\t\tfor (let i = 0; i < this.players.length; i++) {\n\t\t\tif (this.players[i].name === name) {\n\t\t\t\treturn this.players[i];\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}",
"static async getByName(name) {\n let sql = `\n SELECT name, type, data\n FROM instance\n WHERE name = ?\n `;\n let args = [name];\n let results = await db.query(sql, args)\n .then(x => x)\n .catch(err => {\n console.error('[Instance] Error:', err);\n return null;\n });\n if (results && results.length > 0) {\n let result = results[0];\n return new Instance(\n result.name,\n result.type,\n JSON.parse(result.data)\n );\n }\n return null;\n }",
"static get(name) {\n return SpriteBank.bank[name];\n }",
"getGameObjectById({ id }) {\n for (let index = 0; index < this.meshes.length; index++) {\n if (this.meshes[index].id === id) {\n return this.meshes[index];\n }\n }\n }",
"function GetObject(id: int): GameObject\n{\n var gameObj: GameObject;\n \n if(Pool.length > id)\n\t {\n\t\tgameObj = Pool[id] as GameObject;\n\t\tPool.RemoveAt(id);\n\t\t \n\t\tif (gameObj)\n\t\t {\n\t\t\tgameObj.transform.parent = null;\n\t\t\tgameObj.SetActive(true);\n\t\t\t\n \t\t return gameObj;\n\t\t }\n\t\t \n }\n else \n\t Debug.Log(\"You've tried to get object with ID outside of Pool length!\");\n\t \n return null;\n}",
"function get_npc(name)\n{\n\tvar npc = parent.G.maps[character.map].npcs.filter(npc => npc.id == name);\n\n\tif(npc.length > 0)\n\t{\n\t\treturn npc[0];\n\t}\n\n\treturn null;\n}",
"function findObject(name, env) {\n if (env == null) env = window;\n var cur = env, spl = name.split(\".\");\n for (var i = 0; i < spl.length; i++) {\n cur = cur[spl[i]];\n }\n return cur;\n}",
"getParticleObj(name) {\n for (var i = 0; i < this.particleData.length; i++) {\n if (this.particleData[i].name == name) {\n return this.particleData[i];\n }\n }\n }",
"function getIngredientObjectByName(name) {\n for (let i = 0; i < allIngredients.length; i++) {\n if(name == allIngredients[i].name) {\n return allIngredients[i];\n }\n }\n }",
"function getObjectByName(x) {\r\n\t\r\n\tvar a = null;\r\n\t\r\n\tsettings.objUniverse.some(function(b) {\r\n\t\tif(b.name === x) {\r\n\t\t\ta = b;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\t\r\n\t\telse {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\t});\r\n\t\r\n\treturn a;\r\n\t\r\n}",
"function getObjectByName( obj, idpath ) {\n if ( obj.name === idpath ) {\n return obj;\n }\n for ( var i = 0; i < obj.children.length; i ++ ) {\n var found = getObjectByName( obj.children[ i ], idpath);\n if ( found !== null && found !== undefined) {\n return found;\n }\n }\n return null;\n }",
"function findGod(name) {\n //use the js function array.find()\n return gods.find(function(god) {\n return name == god.name\n })\n}",
"static getPlayer(ipAddress, name = Player.DEFAULT_NAME) {\n let gameRecords = Player.loadGameRecords();\n let uniqueKey = this.getUniqueKey(ipAddress, name);\n if (!(uniqueKey in gameRecords)) {\n let player = new Player({ ipAddress: ipAddress, name: name });\n player.save();\n return player;\n } else {\n return new Player(gameRecords[uniqueKey]);\n }\n }",
"getPlayerByName(name) {\n return this.bingoAdmin.getPlayerByName(name);\n }"
]
| [
"0.75299186",
"0.7209909",
"0.70038813",
"0.69633025",
"0.69596165",
"0.6847257",
"0.6847257",
"0.6847257",
"0.6847257",
"0.67339563",
"0.6711304",
"0.6648906",
"0.6419546",
"0.6400634",
"0.6370408",
"0.6357262",
"0.61927474",
"0.6180662",
"0.61068773",
"0.6088772",
"0.60654366",
"0.6041463",
"0.6027144",
"0.59386843",
"0.59289604",
"0.5899773",
"0.58929795",
"0.5857699",
"0.5856136",
"0.5846525"
]
| 0.72688115 | 1 |
Find a component by name | getComponent(name){
for(let component of this.components){
if(component.constructor.name == name)
return component;
}
//If we didn't find it, search any children we have
for(let child of this.children){
let component = child.getComponent(name);
if(component) return component;
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function getComponentByName(name) {\n var i,\n component = that.cp;\n\n if (name.indexOf(\".\") > -1) {\n name = name.split(\".\");\n for (i = 0; i < name.length; i++) {\n if (!component) {\n break;\n }\n component = component[name[i]];\n }\n } else {\n component = component[name];\n }\n\n return component;\n }",
"find(className) {\n let component = null;\n this.components.each((c) => {\n if (c instanceof className) {\n component = c;\n return false;\n }\n });\n return component;\n }",
"getComponent(name) {\n return (this._nextDict[name] || [undefined])[0];\n }",
"getComponent(klass, baseName) {\n const component = _.find(this.components, (c) => {\n return (c instanceof klass) && c.baseName == baseName;\n })\n return component;\n }",
"guessComponent (): ?Object {\n const registeredComponents = this.component.components\n if (!registeredComponents) {\n return null\n }\n const name = this.guessComponentName()\n return Object.values(registeredComponents)\n .find(component => {\n return component.name === name\n }) || null\n }",
"function findComponent(compName, rootComp) {\n var result = null;\n\n // search the component subtree first.\n if (rootComp != null) {\n result = rootComp.findComponent(compName);\n }\n\n // if we did not find the comp in the \n // subtree search the rest of the page.\n if (result == null || rootComp == null) {\n result = AdfPage.findComponent(compName);\n }\n\n return result;\n}",
"getGameObject(name) {\n for (let child of this.children) {\n if (child.name == name) return child;\n let foundChild = child.getGameObject(name);\n if (foundChild) return foundChild;\n }\n //console.error(\"Couldn't find game component \" + name)\n }",
"function findComponentByTagName(node, name) {\n if (node.type === vueTemplateCompilerTypes.component) {\n if (node.tag === name) {\n return node;\n }\n\n let component;\n for (let child of node.children) {\n component = findComponentByTagName(child, name);\n if (component) {\n break;\n }\n }\n\n return component;\n }\n}",
"function getComponent(elem, comp) {\n var instance;\n var i;\n var ele = typeof elem === 'string' ? document.getElementById(elem) : elem;\n for (i = 0; i < ele.ej2_instances.length; i++) {\n instance = ele.ej2_instances[i];\n if (typeof comp === 'string') {\n var compName = instance.getModuleName();\n if (comp === compName) {\n return instance;\n }\n }\n else {\n // tslint:disable-next-line:no-any\n if (instance instanceof comp) {\n return instance;\n }\n }\n }\n return undefined;\n}",
"async getOrThrow(id) {\n const component = await this.get(id);\n if (!component) throw new (_exceptions().ComponentNotFound)(id);\n return component;\n }",
"function getComponent(array, componentName) {\n if (componentName == undefined) {\n return undefined;\n }\n\n for (var i = 0; i < array.length; i++) {\n if (array[i].component_name === componentName) {\n return array[i];\n }\n }\n return undefined;\n}",
"findTag(pack, name) {\n let searched = null;\n pack.forEach(function (tag) {\n if (\n tag.root.getAttribute(\"name\").toLowerCase() == name.toLowerCase() ||\n tag.root.tagName.toLowerCase() == name.toLowerCase() ||\n tag.root.getAttribute(\"ref\").toLowerCase() == name.toLowerCase()\n ) {\n searched = tag;\n }\n });\n return searched;\n }",
"function queryPlugin(name) {\n var retval = Modul_widget; // fallback if no such plugin exists\n $.each(plugins.modules, function (index, module) {\n if (module.widgetname == name) { retval = module; return false; }\n });\n return retval;\n }",
"function get_element_by_name(name) {\n return YAHOO.util.Dom.getElementsBy(function(el) { return el.getAttribute(\"name\") == name; })[0]\n}",
"findRegisteredEl() {\n let { $componentEl, options } = this\n // $componentEl could be hidden by v-if\n if (!$componentEl) {\n return null\n }\n return select($componentEl, options.el)\n }",
"function findChildByName(element, name) {\t\n if (element.name !== undefined && element.name === name) return element;\n \n\treturn element.querySelector(\"[name='\" + name + \"']\");\n}",
"function getBobrilComponent( name, $injector ) {\n // if name is a function assume it is component and return it\n if (angular.isFunction(name)) {\n return name;\n }\n\n // a Bobril component name must be specified\n if (!name) {\n throw new Error('BobrilComponent name attribute must be specified');\n }\n\n // ensure the specified Bobril component is accessible, and fail fast if it's not\n var bobrilComponent;\n try {\n bobrilComponent = $injector.get(name);\n } catch(e) { }\n\n if (!bobrilComponent) {\n try {\n bobrilComponent = name.split('.').reduce(function(current, namePart) {\n return current[namePart];\n }, window);\n } catch (e) { }\n }\n\n if (!bobrilComponent) {\n throw Error('Cannot find bobril component ' + name);\n }\n\n return bobrilComponent;\n }",
"function getComponent (alias, callback) {\n async.until(\n function(){ return alias in components; },\n function(cb){ setTimeout(cb, 0); },\n function(){ callback(components[alias]); }\n );\n }",
"setCurrentIndexByName(name) {\n const { children = [] } = this;\n const matched = children.filter((child) => child.getComputedName() === name);\n if (matched.length) {\n this.setCurrentIndex(matched[0].index);\n }\n }",
"getSelectionComponent(variableName, origName) {\n let sel = this.component.selection[variableName];\n\n if (!sel && this.parent) {\n sel = this.parent.getSelectionComponent(variableName, origName);\n }\n\n if (!sel) {\n throw new Error(log.message.selectionNotFound(origName));\n }\n\n return sel;\n }",
"function DOM$ComponentByElement(element) {\n var component = element.$xui;\n while (!component) {\n element = element.parentNode;\n if (!element) return null;\n component = element.$xui;\n }\n return component;\n}",
"getGameObject(name){\n\t\tfor(let child of this.children){\n\t\t\tif(child.name == name) return child;\n\t\t\tlet foundChild = child.getGameObject(name);\n\t\t\tif(foundChild) return foundChild;\n\t\t}\n\t\t\n\t}",
"function getComponent(el) {\n var cmp,\n target = el;\n\n while (target) {\n cmp = Ext.getCmp(target.id);\n\n if (cmp) {\n return cmp;\n }\n\n target = target.parentNode;\n }\n\n return null;\n}",
"function findInputPort(name){\n\t\t\tlet selectedInput = null;\n\t\t\tmidi.inputs.forEach(function(input, key){\n\t\t\t\tif (input.name == name){\n\t\t\t\t\tselectedInput = input;\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn selectedInput;\n\t\t}",
"function getElement(name)\n {\n return dwv.gui.getElement(containerDivId, name);\n }",
"function find(name) {\n return adapters[name] || null;\n }",
"function FindGameObjectWithName (name) {\n for (var i = 0; i < _gameobjects.length; i++) {\n if (_gameobjects[i].name === name) return _gameobjects[i];\n }\n return false;\n}",
"function findBackend(name) {\n return ENGINE.findBackend(name);\n}",
"function findBackend(name) {\n return ENGINE.findBackend(name);\n}",
"function findBackend(name) {\n return ENGINE.findBackend(name);\n}"
]
| [
"0.7262049",
"0.70103645",
"0.6993525",
"0.69635135",
"0.6887969",
"0.6740571",
"0.65638405",
"0.64327854",
"0.6159689",
"0.60296863",
"0.59928286",
"0.59233046",
"0.58793825",
"0.5870629",
"0.58386356",
"0.5819555",
"0.5813072",
"0.5809756",
"0.57970345",
"0.5755373",
"0.57506645",
"0.5737528",
"0.5736589",
"0.57357204",
"0.5732983",
"0.57094455",
"0.56986785",
"0.56326103",
"0.5629329",
"0.5629329"
]
| 0.77876216 | 0 |
pretty = external move object | function make_pretty(ugly_move) {
var move = clone(ugly_move);
move.san = move_to_san(move, false);
move.to = algebraic(move.to);
move.from = algebraic(move.from);
var flags = '';
for (var flag in BITS) {
if (BITS[flag] & move.flags) {
flags += FLAGS[flag];
}
}
move.flags = flags;
return move;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function make_pretty(ugly_move) {\n var move = clone(ugly_move);\n move.san = move_to_san(move, false);\n move.to = algebraic(move.to);\n move.from = algebraic(move.from);\n\n var flags = '';\n\n for (var flag in BITS) {\n if (BITS[flag] & move.flags) {\n flags += FLAGS[flag];\n }\n }\n move.flags = flags;\n\n return move;\n }",
"function make_pretty(ugly_move) {\n var move = clone(ugly_move);\n move.san = move_to_san(move, false);\n move.to = algebraic(move.to);\n move.from = algebraic(move.from);\n\n var flags = '';\n\n for (var flag in BITS) {\n if (BITS[flag] & move.flags) {\n flags += FLAGS[flag];\n }\n }\n move.flags = flags;\n\n return move;\n }",
"function printMove(move){\n\tif (move == null){\n\t\treturn \"Null\";\n\t}else{\n\t\treturn \"Move: \" + move.move + \"Direction: \" + move.dir;\n\t}\n}",
"function PrintMove(move) {\n\tvar MvStr;\n\t\n\t// Gets the file and rank of the from square and the to square\n\tvar fromFile = FilesBrd[FROMSQ(move)];\n\tvar fromRank = RanksBrd[FROMSQ(move)];\n\tvar toFile = FilesBrd[TOSQ(move)];\n\tvar toRank = RanksBrd[TOSQ(move)];\n\t\n\t// Adds the files and ranks of the from square and the to square and converts it into algebraic notation\n\tMvStr = FileChar[fromFile] + RankChar[fromRank] + FileChar[toFile] + RankChar[toRank];\n\t\n var promoted = PROMOTED(move);\n\t\n\t// If the move was a promotion it adds what the piece was promoted to to the end of the move string\n\tif(promoted != PIECES.EMPTY) {\n console.log('promoted = ' + promoted);\n\t\tvar pchar = 'q';\n\t\tif(PieceKnight[promoted] == true) {\n\t\t\tpchar = 'n';\n\t\t} else if(PieceRookQueen[promoted] == true && PieceBishopQueen[promoted] == false) {\n\t\t\tpchar = 'r';\n\t\t} else if(PieceRookQueen[promoted] == false && PieceBishopQueen[promoted] == true) {\n\t\t\tpchar = 'b';\n\t\t}\n\t\tMvStr += pchar;\n\t}\n\treturn MvStr;\n}",
"move(dir) {\n return `m ${this.id} ${dir}`;\n }",
"showObject(indent, obj) {\n if (obj.name) {\n // see https://stackoverflow.com/a/35063563/1497139\n var wt = new THREE.Vector3(),\n wr = new THREE.Quaternion(),\n ws = new THREE.Vector3();\n obj.matrixWorld.decompose(wt, wr, ws);\n var wts = Debug.asString(\"wx\", \"wy\", \"wz\", wt)\n var wrs = Debug.asString(\"wrx\", \"wry\", \"wrz\", wr, 180 / Math.PI);\n var sizes = \"\";\n var parentName = \"\";\n if (obj.parent)\n if (obj.parent.name)\n parentName = \"parent: \" + obj.parent.name;\n if (obj.userData[\"size\"]) {\n var size = obj.userData[\"size\"];\n sizes = Debug.asString(\"six\", \"siy\", \"siz\", size);\n }\n console.log(Debug.rightJustify(indent + obj.name, 45, \" \") +\n wts +\n wrs + sizes + parentName);\n console.log(Debug.rightJustify(\"\", 45, \" \") +\n Debug.asString(\"x\", \"y\", \"z\", obj.position) +\n Debug.asString(\"rx\", \"ry\", \"rz\", obj.rotation, 180 / Math.PI));\n }\n }",
"function stringifyMove(move) {\n if (move.type === Board.QUANTUM) {\n return move.cells[0] + '-' + move.cells[1];\n }\n if (move.type === Board.COLLAPSE) {\n return '->' + move.cells;\n }\n if (move.type === Board.CLASSICAL) {\n return move.cells.toString();\n }\n return '';\n }",
"move() {\n console.log('sshhhh...');\n }",
"function sanToSimpleMoveObject(sanMove) {\n var output = {\n from : '',\n to : '',\n promotion : '',\n capture : false,\n };\n\n output.from = sanMove.substring(0,2);\n if (sanMove.charAt(2) == 'x') {\n output.capture = true;\n output.to = sanMove.substring(3,5);\n }\n else output.to = sanMove.substring(2,4);\n if (sanMove.indexOf('=') > -1) {\n output.promotion = sanMove.charAt(sanMove.indexOf('=')+1);\n }\n\n return output;\n }",
"function objDest (object) {\n console.log(` NAME is ${object.name}`)\n console.log(` Age is ${object.age}`)\n}",
"debugObject(obj) {\n obj.setInteractive()\n this.input.setDraggable(obj)\n var showPosition = this.add.text(32, 32)\n showPosition.setStyle({ color: '#ffffff', fontSize: '30px' })\n\n this.input.on('dragstart', function(pointer, gameObject) {\n this.children.bringToTop(gameObject)\n }, this)\n\n this.input.on('drag', function(pointer, gameObject, dragX, dragY) {\n gameObject.x = dragX\n gameObject.y = dragY\n showPosition.setText('X: ' + gameObject.x + '\\nY:' + gameObject.y)\n })\n\n }",
"unprettyPrinter(config, obj) {\n return JSON.stringify(obj);\n }",
"function PrintMoveList() {\n\tvar index;\n\tvar move;\n\tvar num = 1;\n\tconsole.log('MoveList:');\n\n\t// Loops through all of the moves and prints them\n\tfor(index = Board.moveListStart[Board.ply]; index < Board.moveListStart[Board.ply+1]; ++index) {\n\t\tmove = Board.moveList[index];\n\t\tconsole.log('Move:' + num + ':' + PrintMove(move));\n\t\tnum++;\n\t}\n}",
"move(x,y){return this.attr(this.array().move(x,y).toLine())}",
"function printMoves(){\n\tstr = \"\";\n\tfor (var j = 0; j < movesMade.length; j++){\n\t\tfor (var i = 0; i < movesMade[j].length; i++){\n\t\t\tstr = str + \"Move : \" + movesMade[j][i].move + \" Direction : \" + movesMade[j][i].dir + \"\\n\";\n\t\t}\n\t}\n\treturn str;\n}",
"generateMoveEmbed(data) {\n\t\tconst [, , move] = data;\n\t\tconst details = {\n\t\t\t'Priority': move.priority,\n\t\t\t'Gen': move.gen || 'CAP',\n\t\t};\n\n\t\t// Move flag handling from Pokmemon Showdown\n\t\tif (move.secondary || move.secondaries) details['Secondary effect'] = '';\n\t\tif (move.flags['contact']) details['Contact'] = '';\n\t\tif (move.flags['sound']) details['Sound'] = '';\n\t\tif (move.flags['bullet']) details['Bullet'] = '';\n\t\tif (move.flags['pulse']) details['Pulse'] = '';\n\t\tif (!move.flags['protect'] && !/(ally|self)/i.test(move.target)) details['Bypasses Protect'] = '';\n\t\tif (move.flags['authentic']) details['Bypasses Substitutes'] = '';\n\t\tif (move.flags['defrost']) details['Thaws user'] = '';\n\t\tif (move.flags['bite']) details['Bite'] = '';\n\t\tif (move.flags['punch']) details['Punch'] = '';\n\t\tif (move.flags['powder']) details['Powder'] = '';\n\t\tif (move.flags['reflectable']) details['Bounceable'] = '';\n\t\tif (move.flags['gravity']) details['Suppressed by Gravity'] = '';\n\n\t\tif (move.zMovePower) {\n\t\t\tdetails['Z-Power'] = move.zMovePower;\n\t\t}\n\t\telse if (move.zMoveEffect) {\n\t\t\tdetails['Z-Effect'] = {\n\t\t\t\t'clearnegativeboost': 'Restores negative stat stages to 0',\n\t\t\t\t'crit2': 'Crit ratio +2',\n\t\t\t\t'heal': 'Restores HP 100%',\n\t\t\t\t'curse': 'Restores HP 100% if user is Ghost type, otherwise Attack +1',\n\t\t\t\t'redirect': 'Redirects opposing attacks to user',\n\t\t\t\t'healreplacement': 'Restores replacement\\'s HP 100%',\n\t\t\t}[move.zMoveEffect];\n\t\t}\n\t\telse if (move.zMoveBoost) {\n\t\t\tdetails['Z-Effect'] = '';\n\t\t\tconst boost = move.zMoveBoost;\n\t\t\tconst stats = {\n\t\t\t\tatk: 'Attack',\n\t\t\t\tdef: 'Defense',\n\t\t\t\tspa: 'Sp. Atk',\n\t\t\t\tspd: 'Sp. Def',\n\t\t\t\tspe: 'Speed',\n\t\t\t\taccuracy: 'Accuracy',\n\t\t\t\tevasion: 'Evasiveness'\n\t\t\t};\n\t\t\tfor (const i in boost) {\n\t\t\t\tdetails['Z-Effect'] += ' ' + stats[i] + ' +' + boost[i];\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tdetails['Z-Effect'] = 'None';\n\t\t}\n\n\t\tdetails['Target'] = {\n\t\t\t'normal': 'One Adjacent Pokmon',\n\t\t\t'self': 'User',\n\t\t\t'adjacentAlly': 'One Ally',\n\t\t\t'adjacentAllyOrSelf': 'User or Ally',\n\t\t\t'adjacentFoe': 'One Adjacent Opposing Pokmon',\n\t\t\t'allAdjacentFoes': 'All Adjacent Opponents',\n\t\t\t'foeSide': 'Opposing Side',\n\t\t\t'allySide': 'User\\'s Side',\n\t\t\t'allyTeam': 'User\\'s Side',\n\t\t\t'allAdjacent': 'All Adjacent Pokmon',\n\t\t\t'any': 'Any Pokmon',\n\t\t\t'all': 'All Pokmon',\n\t\t}[move.target] || 'Unknown';\n\n\t\tif (move.id === 'mirrormove') {\n\t\t\tdetails['https://pokemonshowdown.com/dex/moves/mirrormove'] = '';\n\t\t}\n\n\t\t// Change the details array into text\n\t\tconst { detailstext, propstext } = this.dtextrender(details);\n\n\t\treturn new MessageEmbed()\n\t\t\t.setAuthor(move.name)\n\t\t\t.setDescription(stripIndents`\n ${move.desc}`)\n\t\t\t.addField('Info', stripIndents`\n **Type:** ${move.type}\n **Category:** ${move.category}\n **Base Power:** ${move.hasOwnProperty('basePower') ? move.basePower : 'N/A'}\n\t\t${detailstext}`, true)\n\t\t\t.setColor(hexes.default)\n\t\t\t.addField('Properties', propstext ? propstext : 'No special properties', true);\n\t}",
"function Move() {\n\n this.moveNumber = 1; // The squence number of this move.\n this.team = Teams.white; // The team which the moved piece belongs to.\n this.piece = Pieces.none; // The piece type that is moved.\n this.from = new Point(0, 0); // The location the piece moves from.\n this.to = new Point(0, 0); // The location the piece moves to.\n this.capturePiece = Pieces.none; // The type of the captured piece.\n this.promotePiece = Pieces.none; // The piece type that a pawn would get promoted to.\n this.check = false; // Does this move put the opponent in check?\n this.checkmate = false; // Does this move put the opponent in checkmate?\n this.castling = false; // Is this a special castling move?\n\n\n //-------------------------------------------------------------------------\n // Get a description of what happings during this move.\n this.getDescription = function() {\n var description = \"Moving \" + Teams.getName(this.team) +\n \" \" + Pieces.getName(this.piece) +\n \" from \" + Notation.getLocationNotation(this.from) +\n \" to \" + Notation.getLocationNotation(this.to);\n if (this.capturePiece != Pieces.none)\n description += \", capturing a \" + Pieces.getName(this.capturePiece);\n return description;\n }\n}",
"function writePrettyPirateOffset(p) {\r\n\tvar strRet='';\r\n\tif (null !== p) {\r\n\t\tif (0 < p.offset) {\r\n\t\t\tstrRet+='+';\r\n\t\t}\r\n\t\tstrRet+=p.offset;\r\n\t}\r\n\treturn strRet;\r\n}",
"function obj2Html(theObj, number) {\r\n var retStr = \" \";\r\n var lastseq = true;\r\n var number = number || 1;\r\n for (var i = 0; i < theObj.length; i++) {\r\n var move = theObj[i];\r\n var seq = true;\r\n var moveStr = \"\";\r\n var commentStr = \"\",\r\n nagStr = \"\",\r\n ravStr = \"\";\r\n for (var p in move) {\r\n if (typeof move[p] == 'object') {\r\n switch (p) {\r\n case \"comments\":\r\n for (var j = 0; j < move[p].length; j++) {\r\n if (!move[p][j].match(/^\\[%/)) {\r\n if (move[p][j].length !=0) {\r\n\t\t\t\t\t\t\t\t\tcommentStr += \" { <span class=\\\"comment\\\">\" + move[p][j] + \" </span> } \";\r\n\t\t\t\t\t\t\t\t\tseq = false;\r\n\t\t\t\t\t\t\t\t}\t\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\t\t\r\n break;\r\n case \"rav\":\r\n for (var j = 0; j < move[p].length; j++) {\r\n var strNum = \"\";\r\n strNum = number % 2 ? \"\" : number / 2 + \"... \";\r\n if ( move[p][j].length !=0 ) { \r\n\t\t\t\t\t\t\travStr += \" (\" + strNum + obj2Html(move[p][j], number) + \" ) \";\r\n\t\t\t\t\t\t\tseq = false;\r\n\t\t\t\t\t\t\t}\r\n }\r\n\t\t\t\t\t\tbreak;\r\n case \"nag\":\r\n for (var j = 0; j < move[p].length; j++) {\r\n nagStr += nagConvert( move[p][j]); \r\n }\r\n seq = nagStr == ''? true:false;\r\n break;\r\n case \"fen\":\r\n case \"point\":\r\n case \"rate\":\r\n case \"eval\":\r\n case \"bestmove\":\r\n case \"snapshot\":\r\n default:\r\n break;\r\n }\r\n } else {\r\n if (p == \"san\") {\r\n var strNum = \"\";\r\n if ((!lastseq)) {\r\n strNum = (number % 2) ? (number + 1) / 2 + \". \" : number / 2 + \"... \";\r\n } else {\r\n strNum = (number % 2) ? (number + 1) / 2 + \". \" : \" \";\r\n }\r\n moveStr = strNum + \"<a id=\\\"\" + move[\"oid\"] + \"\\\">\" + move[p] + \" </a>\" \r\n\t\t\t\t\tnumber++;\r\n\r\n }\r\n }\r\n\r\n }\r\n\t\tif ( (i <theObj.length-1) && theObj[i+1].rav) {\r\n\t\tmoveStr = moveStr.replace(\"<a \",\"<a class=\\\"moveselect\\\" \");\r\n\t\t}\r\n\t\tmoveStr += nagStr + \" \" + commentStr + ravStr;\r\n//\t\tnumber++;\r\n\t\tlastseq = seq;\r\n retStr += moveStr;\r\n }\r\n return retStr;\r\n\r\n}",
"prettyPrinter(config, obj) {\n return JSON.stringify(obj, null, config.prettyPrintIndent);\n }",
"function showDef(obj) {\n return \"\" + obj;\n}",
"function MoveSummary () {\n this.moves = [];\n this.sources = {};\n}",
"function sanMoveToObject(sanMove) {\n // I really want to replace all the san/coords bullshit with move objects internally. TODO\n // this is just the beginning.....\n var output = {\n from : '',\n to : '',\n promotion : '',\n capture : false,\n piece : '',\n color : '',\n check : false,\n checkmate : false\n };\n\n output.from = sanMove.substring(0,2);\n if (sanMove.charAt(2) == 'x') {\n output.capture = true;\n output.to = sanMove.substring(3,5);\n }\n else output.to = sanMove.substring(2,4);\n if (sanMove.indexOf('=') > -1) {\n output.promotion = sanMove.charAt(sanMove.indexOf('=')+1);\n }\n\n output.piece = BOARD[sanToBoardPos(output.from)];\n output.color = getColorAt(output.from);\n if (output.capture == false) {\n output.capture = !isEmpty(output.to);\n }\n executeMove(sanToSimpleMoveObject(sanMove));\n if (inCheck()) {\n if (legalMoves().length == 0) {\n output.checkmate = true;\n } else {\n output.check = true;\n }\n }\n undo();\n\n return output;\n }",
"function ObjectDump(obj, name) {\n this.result = \"[ \" + name + \" ]\\n\";\n this.indent = 0;\n \n this.dumpLayer = function(obj) {\n this.indent += 2;\n \n for (var i in obj) {\n if(typeof(obj[i]) == \"object\") {\n // alert ('typeof(obj[i]) == \"object\"'));\n this.result += \"\\n\" +\n \" \".substring(0,this.indent) + i +\n \": \" + \"\\n\";\n this.dumpLayer(obj[i]);\n \n } else {\n this.result +=\n \" \".substring(0,this.indent) + i +\n \": \" + obj[i] + \"\\n\";\n }\n }\n \n this.indent -= 2;\n }\n \n this.showResult = function() {\n /*\n var pre = document.createElement('pre');\n pre.innerHTML = this.result;\n document.body.appendChild(pre);\n /**/\n alert(this.result);\n }\n \n this.dumpLayer(obj);\n this.showResult();\n}",
"function generateMoveInstruction(from, to, pistolStatus) {\n let startX = from.row;\n let startY = from.col;\n let endX = to.row;\n let endY = to.col;\n let command = '';\n command = command + \"201\" + pistolStatus + \"#401\" + pistolStatus + \"#\";\n if (endX <= startX) {\n command = command + '0' + String((startX - endX) * 2).padStart(2, '0') + pistolStatus + '#'\n } else {\n command = command + '4' + String((endX - startX) * 2).padStart(2, '0') + pistolStatus + '#'\n }\n if (endY <= startY) {\n command = command + '6' + String((startY - endY) * 2).padStart(2, '0') + pistolStatus + '#'\n } else {\n command = command + '2' + String((endY - startY) * 2).padStart(2, '0') + pistolStatus + '#'\n }\n command = command + \"001\" + pistolStatus + \"#601\" + pistolStatus + \"#\";\n return command;\n}",
"function movePiece(){\n\n return (console.log());\n}",
"dump() {\n let s;\n\n for (let v of this.vertexes) {\n if (v.pos) {\n s = v.value + ' (' + v.pos.x + ',' + v.pos.y + '):';\n } else {\n s = v.value + ':';\n }\n\n for (let e of v.edges) {\n s += ` ${e.destination.value}`;\n }\n console.log(\"s\", s);\n }\n }",
"dump() {\n let s;\n\n for (let v of this.vertexes) {\n if (v.pos) {\n s = v.value + ' (' + v.pos.x + ',' + v.pos.y + '):';\n } else {\n s = v.value + ':';\n }\n\n for (let e of v.edges) {\n s += ` ${e.destination.value}`;\n }\n console.log(s);\n }\n }",
"uci(move) {\n return move.from + move.to + (move.flags === \"p\" ? move.piece : \"\");\n }",
"function o2s(obj) {\n var s = \"\";\n for (key in obj) {\n var line = key + \"->\" + obj[key];\n line.replace(\"\\n\", \" \");\n s += line + \"\\n\";\n }\n return s;\n}"
]
| [
"0.7024698",
"0.7024698",
"0.6777846",
"0.61500937",
"0.61427796",
"0.6053221",
"0.6041881",
"0.59004897",
"0.57987034",
"0.56136435",
"0.56041354",
"0.5601243",
"0.5585633",
"0.5507589",
"0.55063355",
"0.5502591",
"0.5474692",
"0.5418301",
"0.5346111",
"0.529343",
"0.5279197",
"0.52467847",
"0.52450126",
"0.52253485",
"0.51922774",
"0.5190113",
"0.5164146",
"0.5153068",
"0.5147886",
"0.51468337"
]
| 0.70291734 | 0 |
Prepend a space if necessary | function prepend_space(sb) {
if ( (!sb.isEmpty()) && (sb.lastChar() != " ")) {
sb.append(" ");
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function insertSpaces(value) {\n if (!value) {\n return value;\n }\n return value.replace(/[-_]/g, ' ').trim();\n}",
"function qwerty_addSpaceText() {\n\tqwerty_appendText(\" \");\n}",
"function qwerty_addSpaceText() {\n\tqwerty_appendText(\" \");\n}",
"function addSpaces(str) {\n\treturn ' '+str+' ';\n}",
"function concatStringsWithSpace(before, after) {\n return before == null || before === '' ? after === null ? '' : after : after == null || after === '' ? before : before + ' ' + after;\n }",
"function insertSpace(match) { return ' ' + match; }",
"function concatStringsWithSpace(before, after) {\n return before == null || before === '' ? after === null ? '' : after : after == null || after === '' ? before : before + ' ' + after;\n }",
"function addPrewrapSpaces () {\n let input = inputWithoutPrewrapSpaces();\n let paddedInput;\n let {selectionStart, selectionEnd, selectionDirection} = typingArea;\n selectionStart = Math.min(selectionStart, input.length);\n selectionEnd = Math.min(selectionEnd, input.length);\n\n // hyphens wrap differently\n if (input.slice(-1) === '-') {\n paddedInput = input;\n } else {\n // What's left of the current word (characters until next space/hyphen/end)\n let [wordRemainder] = currentQuote.slice(input.length).split(/[\\s-]/, 1);\n let padding = new Array(wordRemainder.length).fill(noBreakSpace).join('');\n paddedInput = input + padding;\n }\n\n if (paddedInput !== typingArea.value) {\n typingArea.value = paddedInput;\n Object.assign(typingArea, {selectionStart, selectionEnd, selectionDirection});\n }\n}",
"function replaceSpaces(str)\r\n\t{\r\n\t\tif (str[0] === ' ')\r\n\t\t\tstr = '\\u00A0' + str;;\r\n\t\tif (_.endsWith(str, ' '))\r\n\t\t\tstr += '\\u00A0';\r\n\r\n\t\treturn str;\r\n\t}",
"spaceIfNoPref (s) {\n return this.id ? this.prefix(s, ' ').slice(1) : this.spaceIfNoKey(s)\n }",
"function emsp (x) {\n return ' '\n}",
"function concatStringsWithSpace(before, after) {\r\n return (before == null || before === '') ?\r\n (after === null ? '' : after) :\r\n ((after == null || after === '') ? before : before + ' ' + after);\r\n}",
"function replaceEmptySpaces(address){\n return address.replace(/ /g, '+');\n}",
"function ACCspace()\n{\n\twriteText(' ');\n}",
"function spacer(spaceWord) {\n var res = '';\n for(var i = 0; i < spaceWord.length + 2; i++){\n res += ' '\n }\n return res\n }",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function concatStringsWithSpace(before, after) {\n return (before == null || before === '') ?\n (after === null ? '' : after) :\n ((after == null || after === '') ? before : before + ' ' + after);\n}",
"function addSpace(parent) {\n addText(parent, ' ');\n }",
"function noSpace(x){return x.split(' ').join('')}",
"function noSpace(x){\n let newString = x.split(' ').join('')\n return newString\n}"
]
| [
"0.73188084",
"0.68877447",
"0.68877447",
"0.6698276",
"0.6696459",
"0.66911507",
"0.6681704",
"0.6498426",
"0.6424722",
"0.6421804",
"0.6398122",
"0.63795674",
"0.6379474",
"0.6350345",
"0.6342515",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6340782",
"0.6311729",
"0.6282847",
"0.6222478"
]
| 0.7799992 | 1 |
Returns the moves, ensures that the pgn string is read. | function getMoves() {
if (typeof that.moves != 'undefined') {
return that.moves;
} else {
load_pgn();
return that.moves;
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function ParseMove (move, plyCount)\n {\n var ii, ll;\n var toRowMarker = -1;\n\n /*\n * Reset the global move variables.\n */\n castleRook = -1;\n mvIsCastling = 0;\n mvIsPromotion = 0;\n mvCapture = 0;\n mvFromCol = -1;\n mvFromRow = -1;\n mvToCol = -1;\n mvToRow = -1;\n mvPiece = -1;\n mvPieceId = -1;\n mvPieceOnTo = -1;\n mvCaptured = -1;\n mvCapturedId = -1;\n\n /*\n * Given the move as something like Rdxc3 or exf8=Q+ extract the destination\n * column and row and remember whatever is left of the string.\n */\n for (ii = 1; ii < move.length; ii++)\n if (!isNaN (move.charAt (ii)))\n {\n mvToCol = move.charCodeAt ( ii - 1) - 97;\n mvToRow = move.charAt ( ii ) - 1;\n reminder = move.substring (0, ii - 1);\n toRowMarker = ii;\n }\n\n /*\n * The final square did not make sense, maybe it is a castle.\n */\n if ((mvToCol < 0) || (mvToCol > 7) || (mvToRow < 0) || (mvToRow > 7))\n if ((move.indexOf ('O') >= 0) || (move.indexOf ('0') >= 0))\n {\n /*\n * Do long castling first since looking for o-o will get it too.\n */\n if ((move.indexOf ('O-O-O') >= 0) || (move.indexOf ('0-0-0') >= 0))\n {\n mvIsCastling = 1;\n mvPiece = 1;\n mvPieceId = 0;\n mvPieceOnTo = 1;\n mvFromCol = 4;\n mvToCol = 2;\n mvFromRow = 7 * MoveColor;\n mvToRow = 7 * MoveColor;\n\n return CheckLegality ('O-O-O', plyCount);\n }\n\n if ((move.indexOf('O-O') >= 0) || (move.indexOf('0-0') >= 0))\n {\n mvIsCastling = 1;\n mvPiece = 1;\n mvPieceId = 0;\n mvPieceOnTo = 1;\n mvFromCol = 4;\n mvToCol = 6;\n mvFromRow = 7 * MoveColor;\n mvToRow = 7 * MoveColor;\n return CheckLegality ('O-O', plyCount);\n }\n }\n\n /*\n * Now extract the piece and the origin square. If it is a capture (the 'x'\n * is present) mark the as such.\n */\n mvPiece = 6;\n\n ll = reminder.length;\n if (ll > 0)\n {\n for(ii = 1; ii < 6; ++ii) { if (reminder.charAt (0) == PieceCode [ii - 1]) mvPiece = ii; }\n\n if (reminder.charAt (ll - 1) == 'x') mvCapture = 1;\n\n if (isNaN (move.charAt (ll - 1 - mvCapture)))\n {\n mvFromCol = move.charCodeAt (ll - 1 - mvCapture) - 97;\n if ((mvFromCol < 0) || (mvFromCol > 7)) mvFromCol = -1;\n }\n else\n {\n mvFromRow = move.charAt (ll - 1 - mvCapture) - 1;\n if ((mvFromRow < 0) || (mvFromRow > 7)) mvFromRow = -1;\n }\n }\n mvPieceOnTo = mvPiece;\n\n /*\n * If the to square is occupied mark the move as capture. Take care of\n * the special en passant case.\n */\n if ((Board [mvToCol][mvToRow] != 0) || ((mvPiece == 6) && (enPassant) && (mvToCol == enPassantCol) && (mvToRow == 5 - 3 * MoveColor)))\n mvCapture = 1;\n\n /*\n * Take care of promotions. If there is a '=' in the move or if the\n * destination row is not the last character in the move, then it may be a\n * pawn promotion.\n */\n ii = move.indexOf ('=');\n if (ii < 0) ii = toRowMarker;\n if ((ii > 0) && (ii < move.length - 1))\n if (mvPiece == 6)\n {\n var newPiece = move.charAt (ii + 1);\n\n if (newPiece == PieceCode [1]) mvPieceOnTo = 2;\n else if (newPiece == PieceCode [2]) mvPieceOnTo = 3;\n else if (newPiece == PieceCode [3]) mvPieceOnTo = 4;\n else if (newPiece == PieceCode [4]) mvPieceOnTo = 5;\n\n mvIsPromotion = 1;\n }\n\n /*\n * Find which piece was captured. The first part checks normal captures.\n * If nothing is found then it has to be a pawn making an en-passant\n * capture.\n */\n if (mvCapture)\n {\n mvCapturedId = 15;\n while ((mvCapturedId >= 0) && (mvCaptured < 0))\n if ((PieceType [1 - MoveColor][mvCapturedId] > 0) &&\n (PieceCol [1 - MoveColor][mvCapturedId] == mvToCol) &&\n (PieceRow [1 - MoveColor][mvCapturedId] == mvToRow))\n mvCaptured = PieceType [1 - MoveColor][mvCapturedId];\n else\n --mvCapturedId;\n\n if ((mvPiece == 6) && (mvCapturedId < 1) && (enPassant))\n {\n mvCapturedId = 15;\n while((mvCapturedId >= 0) && (mvCaptured < 0))\n if ((PieceType [1 - MoveColor][mvCapturedId] == 6) &&\n (PieceCol [1 - MoveColor][mvCapturedId] == mvToCol) &&\n (PieceRow [1 - MoveColor][mvCapturedId] == 4 - MoveColor))\n mvCaptured = PieceType [1 - MoveColor][mvCapturedId];\n else\n --mvCapturedId;\n }\n }\n\n /*\n * Check the move legality.\n */\n var retVal;\n retVal = CheckLegality (PieceCode [mvPiece - 1], plyCount);\n if (!retVal) return false;\n\n /*\n * If a pawn was moved check if it enables the en-passant capture on next\n * move;\n */\n enPassant = false;\n enPassantCol = -1;\n if ((mvPiece == 6) && (Math.abs (HistRow [0][plyCount] - mvToRow) == 2)) { enPassant = true; enPassantCol = mvToCol; }\n\n return true;\n }",
"function getMoves(){\n var moves = \"\";\n var history = board.getMoveHistory();\n for(var i =0;i<history.length;i++){\n var move = history[i];\n moves+= \" \" + move.from + move.to + (move.promotion?move.promotion:\"\");\n }\n console.log(\"******************\");\n console.log(\"MOVES : \" + moves);\n return moves;\n }",
"function getMove(text) {\n\tconsole.log(`........ getMove(text)`, text)\n\tlet dict = {\n\t\t'<verb>': ['play', 'move', 'push'],\n\t\t'<count>': ['1', '2', '3', '4', '5', '6', '7', '8', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'],\n\t\t'<counted>': ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth'],\n\t\t'<direction>': ['forward', 'back', 'backward', 'left', 'right', 'forward-left', 'forward-right', 'backward-left', 'backward-right', 'back-left', 'back-right'],\n\t}\n\t// let [otext, piece] = match(text, `<verb> <file> <sqcolor> <piece>`, dict);\n\t// if(piece) return [otext, piece];\n\t// let [otext, move] = match(text, `<verb> <count> <direction>`, dict);\n\t// if(move) return [otext, move];\n\tlet otext, move;\n\t[otext, move] = match(text, `<verb> <direction> <count> <direction> <count>`, dict, [0,2,1,4,3]);\tif(move) return [otext, move];\n\t[otext, move] = match(text, `<verb> <count> <direction> <count> <direction>`, dict, [0,1,2,3,4]);\tif(move) return [otext, move];\n\t[otext, move] = match(text, `<direction> <count> <direction> <count>`, dict, [1,0,3,2]);\tif(move) return [otext, move];\n\t[otext, move] = match(text, `<count> <direction> <count> <direction>`, dict, [0,1,2,3]);\tif(move) return [otext, move];\n\t[otext, move] = match(text, `<verb> <count> <direction>`, dict);\tif(move) return [otext, move];\n\t[otext, move] = match(text, `<verb> <direction> <count>`, dict);\tif(move) return [otext, move];\n\t[otext, move] = match(text, `<count> <direction>`, dict);\tif(move) return [otext, move];\n\t[otext, move] = match(text, `<direction> <count>`, dict);\tif(move) return [otext, move];\n\treturn [];\n}",
"function parseMove(s) {\n var a, b;\n if (s.match(/\\d-\\d/)) {\n a = +s.charAt(0);\n b = +s.charAt(2);\n if (a && b) {\n return { type: Board.QUANTUM, cells: [a, b] };\n }\n } else if (s.match(/->\\d/)) {\n a = +s.charAt(2);\n if (a) {\n return { type: Board.COLLAPSE, cells: a };\n }\n } else if (s.match(/\\d/)) {\n a = +s;\n if (a) {\n return { type: Board.CLASSICAL, cells: a };\n }\n }\n return null;\n }",
"function ParsePGNGameString (gameString)\n {\n var ss = gameString;\n var lastKet = ss.lastIndexOf (']');\n\n /*\n * Get rid of the PGN tags and remove the result at the end.\n */\n ss = ss.substring (++lastKet, ss.length);\n ss = ss.replace (/\\s+/g, ' ');\n ss = ss.replace (/^\\s/, '');\n ss = ss.replace (/1-0/, '');\n ss = ss.replace (/0-1/, '');\n ss = ss.replace (/1\\/2-1\\/2/, '');\n ss = ss.replace (/\\*/, '');\n ss = ss.replace (/\\s$/, '');\n\n PlyNumber = 0;\n var moveCount = Math.floor (PlyNumber / 2) + 1;\n var searchThis = moveCount + '.';\n var start = ss.indexOf (searchThis, 0);\n var end, move, startcomment, endcomment, MoveTime;\n MovesTimes [StartPly + PlyNumber] = 0;\n\n while (start >= 0)\n {\n /* search for next move */\n start += searchThis.length + 1;\n end = ss.indexOf (' ', start); if (end < 0) end = ss.length;\n move = ss.substring (start, end);\n\n Moves [StartPly + PlyNumber] = ClearMove (move);\n MovesTimes [StartPly + PlyNumber] = 0;\n PlyNumber++;\n\n /* looking for comments */\n startcomment = ss.indexOf (\"{\", end);\n while (startcomment == end + 1)\n {\n // we found comment(s) after first half-move\n endcomment = ss.indexOf (\"}\", end);\n\n MoveTime = GetComment (ss.substring (startcomment, endcomment));\n if (!isNaN (MoveTime))\n {\n // if the comment is a number, treat it as move time, otherwise treat it as a comment and display it\n gameMoveTimesAvail = 1;\n MovesTimes [StartPly + PlyNumber - 1] = MoveTime;\n }\n\n start = endcomment + 2; // skip the space behind the comment\n end = start - 1; if (start >= ss.length) break;\n\n startcomment = ss.indexOf (\"{\", end);\n }\n\n start = end + 1;\n if ((start >= ss.length) || (end >= ss.length)) break;\n\n end = ss.indexOf (' ', start); // next move\n if (end < 0) end = ss.length;\n\n move = ss.substring (start, end);\n Moves [StartPly + PlyNumber] = ClearMove (move);\n MovesTimes [StartPly + PlyNumber] = 0;\n PlyNumber++;\n\n /* looking for comments */\n startcomment = ss.indexOf (\"{\", end);\n while (startcomment == end + 1)\n {\n // we found comment(s) after first half-move\n endcomment = ss.indexOf (\"}\", end);\n if (endcomment < 0) { alert (\"Error in move list: closing comment bracket } not found.\"); break; }\n\n MoveTime = GetComment (ss.substring (startcomment, endcomment));\n if (!isNaN (MoveTime))\n {\n // if the comment is a number, treat it as move time, otherwise discard it\n MovesTimes [StartPly + PlyNumber - 1] = MoveTime;\n }\n\n start = endcomment + 2; // skip the space behind the comment\n end = start - 1;\n if (start >= ss.length) break;\n startcomment = ss.indexOf (\"{\", end);\n }\n\n start = end + 1;\n if ((start >= ss.length) || (end >= ss.length)) break;\n\n moveCount = Math.floor (PlyNumber / 2) + 1;\n searchThis = moveCount + '.';\n start = ss.indexOf (searchThis, end);\n }\n }",
"get moves () { return this._moves.slice() }",
"getMoves(cmd, state, cb, eb) { /* {{{ */\n // Do this here so we only do it once, plus if there is a long delay between clock message and move message, we'll\n // subtract that missing time from what we tell the bot.\n //\n this.loadClock(state);\n\n // Only relevent with persistent bots. Leave the setting on until we actually have requested a move.\n // Must be after loadClock() since loadClock() checks this.firstmove!\n //\n this.firstmove = false;\n\n this.command(cmd, (line) => {\n line = typeof(line) === \"string\" ? line.toLowerCase() : null;\n let parts = line.split(/ +/);\n let moves = [];\n\n for (let i=0; i < parts.length; i++) {\n let move = parts[i];\n\n let resign = move === 'resign';\n let pass = move === 'pass';\n let x=-1, y=-1;\n if (!resign && !pass) {\n if (move && move[0]) {\n x = gtpchar2num(move[0]);\n y = state.width - parseInt(move.substr(1))\n } else {\n this.log(cmd + \" failed, resigning\");\n resign = true;\n }\n }\n moves.push({'x': x, 'y': y, 'text': move, 'resign': resign, 'pass': pass});\n }\n\n cb(moves);\n },\n eb,\n true /* final command */\n )\n }",
"getCheckingMoves () {\n\t\tlet moves = []\n\n\t\tmoves.push([this.currentCoordinates[0]+1, this.currentCoordinates[1]+2]);\n\t\tmoves.push([this.currentCoordinates[0]+2, this.currentCoordinates[1]+1]);\n\t\tmoves.push([this.currentCoordinates[0]+2, this.currentCoordinates[1]-1]);\n\t\tmoves.push([this.currentCoordinates[0]+1, this.currentCoordinates[1]-2]);\n\t\tmoves.push([this.currentCoordinates[0]-1, this.currentCoordinates[1]-2]);\n\t\tmoves.push([this.currentCoordinates[0]-2, this.currentCoordinates[1]-1]);\n\t\tmoves.push([this.currentCoordinates[0]-2, this.currentCoordinates[1]+1]);\n\t\tmoves.push([this.currentCoordinates[0]-1, this.currentCoordinates[1]+2]);\n\n\t\treturn moves;\n\t}",
"function getGamePgn() {\n let moveStack = engine.moveStack();\n let pgn = '';\n\n for (let index = 0; index < moveStack.length; index++) {\n let move = moveStack[index].move;\n let moveScore = moveStack[index].score;\n let moveDepth = moveStack[index].depth;\n let moveTime = moveStack[index].time;\n let movePv = moveStack[index].pv;\n let moveString = engine.moveToString(move);\n let moveNumber = ((index % 2) ? '': ((index / 2 + 1) + '. '));\n let displayScore = (((moveScore / 100) == 0) ? '-0.00' : (moveScore / 100)) + '/' + moveDepth + ' ';\n \n if (displayScore.toString().includes('NaN') && moveScore.includes('M'))\n displayScore = moveScore.replace('M', 'mate in ') + ' # ';\n \n let stats = (movePv ? '(' + movePv.trim() + ')' + ' ': '') + \n (moveDepth ? ((moveScore > 0) ? ('+' + displayScore) : displayScore): '') +\n Math.round(moveTime / 1000);\n \n let nextMove = moveNumber + moveString + (moveTime ? ' {' + stats + '}' : '');\n \n pgn += nextMove + ' ';\n userTime = 0; \n }\n\n return pgn;\n}",
"get_move() {\n var m = this.raw_move;\n var move_str = \"\";\n if((m === 0x0107) || (m === 0x0f3f)) {\n move_str = \"O-O\";\n } else if((m === 0x0100) || (m === 0x0f38)) {\n move_str = \"O-O-O\";\n } else {\n var promo_piece = this.get_promo_piece();\n move_str = \"abcdefgh\".charAt(this.get_from_col()) + \"12345678\".charAt(this.get_from_row()) + \"-\" + \"abcdefgh\".charAt(this.get_to_col()) + \"12345678\".charAt(this.get_to_row())\n if(promo_piece > 0) {\n move_str = move_str + \"=\" + \"-NBRQ\".charAt(promo_piece);\n }\n }\n return move_str;\n }",
"function availableMove(board) {\r\n\tvar text = \"\";\r\n\tswitch (findBlank(board)) {\r\n\t\tcase 1 :\r\n\t\t\tmoves = [0,\"R\",\"D\",0];\r\n\t\t\tmovePosition = [\"\",2,4,\"\"];\r\n\t\t\tbreak;\r\n\t\tcase 2:\r\n\t\t\tmoves = [0,\"R\",\"D\",\"L\"];\r\n\t\t\tmovePosition = [\"\",3,5,1];\r\n\t\t\tbreak;\r\n\t\tcase 3:\r\n\t\t\tmoves = [0,0,\"D\",\"L\"];\r\n\t\t\tmovePosition = [\"\",\"\",6,2];\r\n\t\t\tbreak;\r\n\t\tcase 4:\r\n\t\t\tmoves = [\"U\",\"R\",\"D\",0];\r\n\t\t\tmovePosition = [1,5,7,\"\"];\r\n\t\t\tbreak;\r\n\t\tcase 5:\r\n\t\t\tmoves = [\"U\",\"R\",\"D\",\"L\"];\r\n\t\t\tmovePosition = [2,6,8,4];\r\n\t\t\tbreak;\r\n\t\tcase 6:\r\n\t\t\tmoves = [\"U\",0,\"D\",\"L\"];\r\n\t\t\tmovePosition = [3,\"\",9,5];\r\n\t\t\tbreak;\r\n\t\tcase 7:\r\n\t\t\tmoves = [\"U\",\"R\",0,0];\r\n\t\t\tmovePosition = [4,8,\"\",\"\"];\r\n\t\t\tbreak;\r\n\t\tcase 8:\r\n\t\t\tmoves = [\"U\",\"R\",0,\"L\"];\r\n\t\t\tmovePosition = [5,9,\"\",7];\r\n\t\t\tbreak;\r\n\t\tcase 9:\r\n\t\t\tmoves = [\"U\",0,0,\"L\"];\r\n\t\t\tmovePosition = [6,\"\",\"\",8];\r\n\t\t\tbreak;\r\n\t}\r\n}",
"function parseMove(movestr) {\n var pmove = {};\n var parts = movestr.split(' ');\n if(parts[0] == \"DRAW\") {\n pmove.type = MoveType.DRAW;\n if(parts.length > 1) {\n pmove.value = parseInt(parts[1]);\n } else {\n pmove.value = 1;\n }\n return pmove;\n }\n if(parts[0] == \"PLAY\") {\n pmove.type = MoveType.PLAY;\n pmove.handid = parseInt(parts[1]);\n if(parts[2].indexOf(\"MBR\") == 0) {\n pmove.slotty = SlotType.MEMROLE;\n } else if(parts[2].indexOf(\"MEM\") == 0) {\n pmove.slotty = SlotType.MEME;\n } else if(parts[2].indexOf(\"CH\") == 0) {\n pmove.slotty = SlotType.CHANNEL;\n } else {\n pmove.slotty = SlotType.MEME;\n }\n pmove.slotid = parts[2];\n return pmove;\n }\n if(parts[0] == \"PHASE\") {\n pmove.type = MoveType.PHASE;\n if(parts[1].indexOf(\"BATTLE\") == 0) {\n pmove.value = DuelPhase.BATTLE;\n } else if(parts[1].indexOf(\"END\") == 0) {\n pmove.value = DuelPhase.END;\n } else if(parts[1].indexOf(\"EFFECT\") == 0) {\n pmove.value = DuelPhase.EFFECT;\n } else if(parts[1].indexOf(\"ACTION\") == 0) {\n pmove.value = DuelPhase.ACTION;\n } else {\n pmove.value = DuelPhase.END;\n }\n return pmove;\n }\n if(parts[0] == \"DISCARD\") {\n pmove.type = MoveType.DISCARD;\n pmove.handid = parseInt(parts[1]);\n return pmove;\n }\n if(parts[0] == \"ATTACK\") {\n pmove.type = MoveType.ATTACK;\n pmove.slotid = parts[1];\n if(parts[1].indexOf(\"MBR\") == 0) {\n pmove.slotty = SlotType.MEMROLE;\n } else if(parts[1].indexOf(\"MEM\") == 0) {\n pmove.slotty = SlotType.MEME;\n } else {\n pmove.slotty = SlotType.MEME;\n }\n pmove.slot2id = parts[2];\n if(parts[2].indexOf(\"MBR\") == 0) {\n pmove.slot2ty = SlotType.MEMROLE;\n } else if(parts[2].indexOf(\"MEM\") == 0) {\n pmove.slot2ty = SlotType.MEME;\n } else if(parts[2].indexOf(\"CH\") == 0) {\n pmove.slot2ty = SlotType.CHANNEL;\n } else {\n pmove.slot2ty = SlotType.MEME;\n }\n return pmove;\n }\n}",
"function PrintMove(move) {\n\tvar MvStr;\n\t\n\t// Gets the file and rank of the from square and the to square\n\tvar fromFile = FilesBrd[FROMSQ(move)];\n\tvar fromRank = RanksBrd[FROMSQ(move)];\n\tvar toFile = FilesBrd[TOSQ(move)];\n\tvar toRank = RanksBrd[TOSQ(move)];\n\t\n\t// Adds the files and ranks of the from square and the to square and converts it into algebraic notation\n\tMvStr = FileChar[fromFile] + RankChar[fromRank] + FileChar[toFile] + RankChar[toRank];\n\t\n var promoted = PROMOTED(move);\n\t\n\t// If the move was a promotion it adds what the piece was promoted to to the end of the move string\n\tif(promoted != PIECES.EMPTY) {\n console.log('promoted = ' + promoted);\n\t\tvar pchar = 'q';\n\t\tif(PieceKnight[promoted] == true) {\n\t\t\tpchar = 'n';\n\t\t} else if(PieceRookQueen[promoted] == true && PieceBishopQueen[promoted] == false) {\n\t\t\tpchar = 'r';\n\t\t} else if(PieceRookQueen[promoted] == false && PieceBishopQueen[promoted] == true) {\n\t\t\tpchar = 'b';\n\t\t}\n\t\tMvStr += pchar;\n\t}\n\treturn MvStr;\n}",
"function postGenerateMoves() {\n function findMoveForStart() {\n let startPlay = that.configuration.startPlay;\n if (!isNaN(startPlay)) { // the following goes only over the main line, move number cannot denote a variation\n startPlay = startPlay - 1;\n let move = that.mypgn.getMove(0);\n while (startPlay > 0) {\n startPlay = startPlay - 1;\n move = that.mypgn.getMove(move.next);\n }\n return move;\n }\n let moves = that.mypgn.getMoves();\n for (let move of moves) {\n if (move.fen.startsWith(startPlay)) {\n return move;\n } else if (move.notation.notation == startPlay) {\n return move;\n }\n }\n return undefined;\n }\n\n if (that.configuration.startPlay && !that.configuration.hideMovesBefore) {\n let move = findMoveForStart();\n if (move === undefined) {\n logError('Could not find startPlay: ' + that.configuration.startPlay);\n return;\n }\n makeMove(move.prev, move.index, move.fen);\n unmarkMark(move.index);\n }\n\n if (that.configuration.showResult) {\n // find the result from the header\n let endGame = that.mypgn.getEndGame();\n // Insert it as new span\n let span = createEle(\"span\", movesId + \"Result\", \"move\", theme,\n document.getElementById(movesId));\n span.innerHTML = endGame ? endGame : \"*\";\n\n }\n }",
"function calculatePositionFromMoves (position, moves) {\n let newPosition = deepCopy(position);\n\n for (let i in moves) {\n if (!moves.hasOwnProperty(i)) continue;\n\n // skip the move if the position doesn't have a piece on the source square\n if (!newPosition.hasOwnProperty(i)) continue;\n \n let piece = ''\n if (validBoardSquare(i)) {\n piece = newPosition[i];\n delete newPosition[i];\n } else {\n piece = i[0] + i[2];\n newPosition[i]--;\n }\n\n newPosition[moves[i]] = piece; \n }\n\n return newPosition;\n }",
"function getMoves () {\n return new Promise((resolve, reject) => { \n var user = JSON.parse(StorageService.getStorage('loggedInUser'));\n resolve(user.moves)\n })\n}",
"function ParseMove(from, to) {\n\t\n\tGenerateMoves();\n\n\tvar Move = NOMOVE;\n\tvar PromPce = PIECES.EMPTY;\n\tvar found = false;\n\n\t// Loops through all of the possible moves at the current position\n\tfor(var index = Board.moveListStart[Board.ply]; index < Board.moveListStart[Board.ply + 1]; ++index) {\n\t\tMove = Board.moveList[index];\n\t\t// Checks if the move the user made is one of the possible moves or not\n\t\tif(FROMSQ(Move) == from && TOSQ(Move) == to) {\n\t\t\tPromPce = PROMOTED(Move);\n\t\t\t// Checks if the move was a promoting move\n\t\t\tif(PromPce != PIECES.EMPTY) {\n\t\t\t\t// Checks if the promotion was to a queen or not\n\t\t\t\tif((PromPce == PIECES.wQ && Board.side == COLOURS.WHITE) || (PromPce == PIECES.bQ && Board.side == COLOURS.BLACK)); {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Checks if it is a legal move or not\n\tif(found != false) {\n\t\tif(MakeMove(Move) == false) {\n\t\t\treturn NOMOVE;\n\t\t}\n\t\tTakeMove();\n\t\treturn Move;\n\t}\n\n\treturn NOMOVE;\n}",
"function legalMoves() {\n var output = [];\n var outmoves = [];\n for (var i = 0; i < BOARD.length; i++) {\n if (BOARD[i] != EMPTY) {\n if ((turn == WHITE && BOARD[i] == BOARD[i].toUpperCase()) ||\n (turn == BLACK && BOARD[i] == BOARD[i].toLowerCase()))\n outmoves = outmoves.concat(getPieceBySymbol(BOARD[i]).legalMoves(boardPosToSan(i)));\n }\n }\n\n // verify moves avoid check:\n for (i = 0; i < outmoves.length; i++) {\n var cr = testMove(outmoves[i]);\n if (!inCheck()) output.push(outmoves[i]);\n loadFEN(cr);\n }\n\n return output;\n }",
"function moveRead (nom) {\n if (info.testState) return test (nom);\n let lDest, cDest;\n let v;\n let carPiece;\n let res;\n let prise;\n let elem = document.getElementById (nom);\n let pawnMove = false;\n\n if ((gamer.kingState == KINGSTATE.NOEXIST) || (gamer.kingState == KINGSTATE.IS_MATE))\n return;\n\n if (gamer.lastPlayC == '') { // saisie de la case source\n [lSource, cSource] = stringToLC (nom);\n if (choiceIsOK (jeu, lSource, cSource, gamer.color)) { \n gamer.lastPlayC = nom; // la case source\n elem.style.background = 'olive';\n elem.style.color = 'white';\n }\n return;\n }\n\n [lDest, cDest] = stringToLC (nom); // saisie case destination\n if (lSource == lDest && cSource == cDest) { // on annule tout\n gamer.lastPlayC = '';\n display ();\n return;\n }\n res = verification (jeu, lSource, cSource, lDest, cDest, gamer.color);\n \n // en passant\n if ((Math.abs(jeu [lSource][cSource]) == PAWN) && (cDest == cSource) && (Math.abs (lDest - lSource) == 2)) // en Passant possible\n gamer.ep = nom [0] + (lSource + 1 - gamer.color); // genre : c6. On ne change pas la colonne. \n else gamer.ep = \"-\";\n\n // limitation du roque si on touche au roi ou a la tour\n if (jeu [lSource][cSource] * gamer.color >= KING) { \n gamer.queenCastleOK = false;\n gamer.kingCastleOK = false;\n }\n if (jeu [lSource][cSource] * gamer.color == ROOK) {\n if (cSource == 7) gamer.kingCastleOK = false;\n else if (cSource == 0) gamer.queenCastleOK = false;\n }\n \n // gestion du roque\n if (res == CASTLING_GAMER) {\n gamer.kingCastleOK = false;\n gamer.queenCastleOK = false;\n if (cDest == 0) { // grand Roque\n jeu [lSource][0] = 0;\n jeu [lSource][2] = gamer.color * CASTLE_KING;\n jeu [lSource][3] = gamer.color * ROOK;\n jeu [lSource][4] = 0;\n gamer.lastPlayA = gamer.lastPlayC = \"O-O-O\";\n if ((info.story != '') && (gamer.color == -1)) info.story += '\\n';\n if (gamer.color == -1) info.story += info.nb.toString ().padStart (3, ' ');\n info.story += \" O-O-O\";\n }\n else if (cDest == 7) { // petit Roque\n jeu [lSource][4] = 0;\n jeu [lSource][5] = gamer.color * ROOK;\n jeu [lSource][6] = gamer.color * CASTLE_KING;\n jeu [lSource][7] = 0;\n gamer.lastPlayA = gamer.lastPlayC = \"O-O\";\n if ((info.story != '') && (gamer.color == -1)) info.story += '\\n';\n if (gamer.color == -1) info.story += info.nb.toString ().padStart (3, ' ');\n info.story += \" O-O\";\n }\n }\n\n // cas general\n if (res == true || res == EN_PASSANT) {\n v = Math.abs (jeu [lDest][cDest]);\n prise = (v != 0 || res == EN_PASSANT) ? 'x' : '-';\n v = Math.abs(jeu [lSource][cSource]);\n carPiece = DICT [v];\n gamer.lastPlayC = carPiece + gamer.lastPlayC + prise + nom; // source + destination\n if (res == EN_PASSANT) gamer.lastPlayC += \"e.p.\";\n gamer.lastPlayA = abbrev (jeu, gamer.lastPlayC);\n if ((info.story != '') && (gamer.color == -1)) info.story += '\\n';\n if (gamer.color == -1) info.story += info.nb.toString ().padStart (3, ' ') + gamer.lastPlayA.padStart(6, ' ');\n else info.story += gamer.lastPlayA.padStart (6, ' ');\n pawnMove = (Math.abs (jeu [lSource][cSource])) == PAWN;\n\n if (((jeu [lSource][cSource] == -PAWN) && (lDest == 7)) || \n ((jeu [lSource][cSource] == PAWN) && (lDest == 0))) {\n jeu [lDest][cDest] = gamer.color * QUEEN; // promotion\n info.story += \"=Q\";\n }\n else jeu [lDest][cDest] = jeu [lSource][cSource];\n if (res == EN_PASSANT) jeu [lSource][cDest] = 0; // bizarre mais vrai\n jeu [lSource][cSource] = 0;\n }\n\n if (res == CASTLING_GAMER || res == EN_PASSANT || res == true) {\n if (gamer.color == 1) info.nb += 1; // computer a les blancs\n if (prise == 'x' || pawnMove) \n info.cpt50 = 0;\n else info.cpt50 += 1; \n computer.lastPlayC = \"\"; // pour arreter le marquage evec mark ()\n fullDisplay ();\n clearInterval (gamer.count);\n if (info.cpt50 > CINQUANTE)\n alert (\"règle des 50 coups atteinte\");\n else serverRequest (); // on appelle le serveur\n }\n}",
"function getNextStates(move, playerIndex) {\n var board = move[1].set.value;\n var allPossibleMoveDeltas = getAllMoves(board, playerIndex);\n var allPossibleMoves = [];\n\n for (var i = 0; i < allPossibleMoveDeltas.length; i++) {\n allPossibleMoves[i] = checkersLogicService.createMove(angular.copy(board),\n allPossibleMoveDeltas[i][0], allPossibleMoveDeltas[i][1],\n playerIndex);\n }\n\n return allPossibleMoves;\n }",
"function buildMoves(san,moves) {\n var outMoves = [];\n for (var i = 0; i < moves.length; i++) {\n if (moves[i][0] == 'leap') {\n var inMoves = buildLeap(san,moves[i][1]);\n outMoves = outMoves.concat(inMoves);\n }\n\n if (moves[i][0] == 'slide') {\n var inMoves = buildSlide(san,moves[i][1]);\n outMoves = outMoves.concat(inMoves);\n }\n }\n return outMoves;\n }",
"function calculatePositionFromMoves(position, moves) {\n position = deepCopy(position);\n\n for (var i in moves) {\n if (moves.hasOwnProperty(i) !== true) continue;\n\n // skip the move if the position doesn't have a piece on the source square\n if (position.hasOwnProperty(i) !== true) continue;\n\n var piece = position[i];\n delete position[i];\n position[moves[i]] = piece;\n }\n\n return position;\n}",
"function calculatePositionFromMoves(position, moves) {\n position = deepCopy(position);\n\n for (var i in moves) {\n if (moves.hasOwnProperty(i) !== true) continue;\n\n // skip the move if the position doesn't have a piece on the source square\n if (position.hasOwnProperty(i) !== true) continue;\n\n var piece = position[i];\n delete position[i];\n position[moves[i]] = piece;\n }\n\n return position;\n}",
"legalMoves() {\n return this.chess.moves({ verbose: true });\n }",
"getPotentialPawnMoves([x, y]) {\n const color = this.turn;\n let moves = [];\n const [sizeX, sizeY] = [V.size.x, V.size.y];\n const shiftX = color == \"w\" ? -1 : 1;\n const startRank = color == \"w\" ? sizeX - 2 : 1;\n const lastRank = color == \"w\" ? 0 : sizeX - 1;\n\n const sq1 = this.getSquareAfter([x,y], [shiftX,0]);\n if (sq1 && this.board[sq1[0]][y] == V.EMPTY) {\n // One square forward (cannot be a promotion)\n moves.push(this.getBasicMove([x, y], [sq1[0], y]));\n if (x == startRank) {\n // If two squares after is available, then move is possible\n const sq2 = this.getSquareAfter([x,y], [2*shiftX,0]);\n if (sq2 && this.board[sq2[0]][y] == V.EMPTY)\n // Two squares jump\n moves.push(this.getBasicMove([x, y], [sq2[0], y]));\n }\n }\n // Captures\n for (let shiftY of [-1, 1]) {\n const sq = this.getSquareAfter([x,y], [shiftX,shiftY]);\n if (\n !!sq &&\n this.board[sq[0]][sq[1]] != V.EMPTY &&\n this.canTake([x, y], [sq[0], sq[1]])\n ) {\n const finalPieces = sq[0] == lastRank\n ? V.PawnSpecs.promotions\n : [V.PAWN];\n for (let piece of finalPieces) {\n moves.push(\n this.getBasicMove([x, y], [sq[0], sq[1]], {\n c: color,\n p: piece\n })\n );\n }\n }\n }\n\n return moves;\n }",
"function move_from_san(move, sloppy) {\n // strip off any move decorations: e.g Nf3+?!\n var clean_move = stripped_san(move);\n\n // if we're using the sloppy parser run a regex to grab piece, to, and from\n // this should parse invalid SAN like: Pe2-e4, Rc1c4, Qf3xf7\n if (sloppy) {\n var matches = clean_move.match(/([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnQRBN])?/);\n if (matches) {\n var piece = matches[1];\n var from = matches[2];\n var to = matches[3];\n var promotion = matches[4];\n }\n }\n\n var moves = generate_moves();\n for (var i = 0, len = moves.length; i < len; i++) {\n // try the strict parser first, then the sloppy parser if requested\n // by the user\n if ((clean_move === stripped_san(move_to_san(moves[i]))) ||\n (sloppy && clean_move === stripped_san(move_to_san(moves[i], true)))) {\n return moves[i];\n } else {\n if (matches &&\n (!piece || piece.toLowerCase() == moves[i].piece) &&\n SQUARES[from] == moves[i].from &&\n SQUARES[to] == moves[i].to &&\n (!promotion || promotion.toLowerCase() == moves[i].promotion)) {\n return moves[i];\n }\n }\n }\n\n return null;\n }",
"function onMove() {\n function pointAdd(a, b) {\n return {x:a.x + b.x, y:a.y + b.y}\n }\n const moves = [\n {dir:NORTH, to:pointAdd(pos, {x:0, y:-1})}, \n {dir:EAST, to:pointAdd(pos, {x:1, y:0})},\n {dir:SOUTH, to:pointAdd(pos, {x:0, y:1})},\n {dir:WEST, to:pointAdd(pos, {x:-1, y:0})}\n ].map((v) => ({...v, value:map.getPt(v.to) || {pixel:' ', count:0}}))\n .filter((v) => v.value.pixel !== '#')\n .sort((l,r) => l.value.count - r.value.count)\n \n testPos = moves[0].to\n return moves[0].dir\n}",
"function generateMoves(gameState){\n var avblMoves = [];\n \n for(var i = 0; i < 3; i++){\n for(var j = 0; j < 3; j++){\n if(gameState.board[i][j] === \" \"){\n avblMoves.push([i, j]);\n }\n }\n }\n return avblMoves;\n }",
"move(moveNumber) {\n if (moveNumber === 0) return [0, 0]\n\n let segment = this.segmentToMove(moveNumber)\n let moveIndex = this.segmentMoveIndex(moveNumber, segment)\n\n let to = this.target(segment, moveIndex)\n let from = this.target(segment, moveIndex - 1)\n\n return [from, to]\n }",
"function getMove(player, symbol){\n //flag = true;\n while(true){\n let move = readlineSync.question(player + '(' + symbol + '): '); // get a move\n if(move === 'Q'){\n return move;\n }\n else{\n result = move.split(' ');\n let r = Number(result[0]);\n let c = Number(result[1]); \n if(result.length === 2 && !isNaN(r) && !isNaN(c)){\n if (r <= size && r > 0 && c <= size && c > 0){//check if the input is in the board\n if (board[r][c] === ' '){\n return result;\n }else{\n console.log('\\x1b[33m%s\\x1b[0m', 'This position has been taken, choose another position.\\n');\n return getMove(player, symbol);\n }\n }else{//if not, repeat the process.\n console.log('\\x1b[31m%s\\x1b[0m', 'ERROR: ');\n console.log('\\x1b[36m%s\\x1b[0m', ' ' + move + ' is out of the range of the board.\\n\\n');\n return getMove(player, symbol);\n }\n }else{\n console.log('\\x1b[31m%s\\x1b[0m', 'ERROR: ');\n console.log('\\x1b[36m%s\\x1b[0m', ' Invalid input. Please type in numbers of a row and a column separated by one whitespace, or just type \"Q\" to quit.');\n return getMove(player, symbol);\n }\n \n }\n }\n \n}"
]
| [
"0.6612982",
"0.64753175",
"0.6350077",
"0.63373125",
"0.62834054",
"0.62319785",
"0.61688286",
"0.6059208",
"0.59429204",
"0.5895692",
"0.5820942",
"0.57854456",
"0.57703507",
"0.56876326",
"0.568096",
"0.5670227",
"0.5662928",
"0.5649098",
"0.5602697",
"0.5568647",
"0.55497605",
"0.5548605",
"0.5548605",
"0.5540293",
"0.5501717",
"0.5488149",
"0.54828787",
"0.54821455",
"0.54788786",
"0.54736245"
]
| 0.71292406 | 1 |
Returns the headers. Ensures that pgn is already read. | function getHeaders() {
if (typeof that.headers != 'undefined') {
return that.headers;
} else {
load_pgn();
return that.headers;
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"async _getHeaders() {\n const authToken = await this.authService.getToken();\n return this._headers(authToken.access_token);\n }",
"get hdr() {}",
"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 }",
"get headers() { return this.#headers_; }",
"getHeaders() {\n return this._headers;\n }",
"get headers() { return this._headers; }",
"headers () {\n return this.parseHeaders()\n }",
"function getHeaders() {\r\n var hdrList = [];\r\n for (var i = 1; i < 8; i++) {\r\n var headers = document.getElementsByTagName(\"h\" + i);\r\n hdrList.push.apply(hdrList, headers);\r\n }\r\n return hdrList;\r\n}",
"get headers () {\n webidl.brandCheck(this, Request)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\n }",
"get headers () {\n webidl.brandCheck(this, Request)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\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}",
"get headers() {\n return this.#headers;\n }",
"function getHeaders() {\n var sheet = SpreadsheetApp.getActiveSheet(); // Get this spreadsheet\n var startRow = 1; // First row of data to process\n var startCol = 1; // First column of data to process\n var numCols = sheet.getLastColumn(); // Number of columns to process\n var numRows = 1; // Number of rows to process\n var dataRange = sheet.getRange(startRow, startCol, numRows, numCols); // Fetch the range of cells \n return dataRange.getValues(); // Outputs the headers for this spreadsheet as an object\n Logger.log('Could not get usable header.'); // Alerts if data not found\n}",
"function getMessageHeaders() {\n var itemId = Office.context.mailbox.item.itemId;\n var headers = easyEws.getEwsHeaders(itemId, getCurrentMessage, errorCallback);\n }",
"getResponseHeaders () {\n return this.request('getResponseHeaders')\n }",
"getRequestHeaders () {\n return this.request('getRequestHeaders')\n }",
"async getRequestHeaders(url) {\n const client = await this.getClient();\n return client.getRequestHeaders(url);\n }",
"async getRequestHeaders(url) {\n const client = await this.getClient();\n return client.getRequestHeaders(url);\n }",
"headers() {\n var headers;\n if (!this.options.header) {\n return;\n }\n if (!this.options.columns) {\n return;\n }\n headers = this.options.columns.map(function(column) {\n return column.header;\n });\n if (this.options.eof) {\n headers = this.stringify(headers) + this.options.record_delimiter;\n } else {\n headers = this.stringify(headers);\n }\n return this.push(headers);\n }",
"get headers() {\n return this.#serverRequest.headers;\n }",
"extractHeaders(s){\n\t\tconst req = s.split('\\r\\n\\r\\n')[0].split('\\r\\n').slice(1);\n\t\tconst headers = {};\n\n\t\treq.forEach(function(p){\n\t\t\tconst pair = p.split(': ');\n\t\t\theaders[pair[0]] = pair[1];\n\t\t});\n\t\treturn headers;\n }",
"getHeaders () {\r\n return $$(this.headersCss).filter(function (header) {\r\n return header.isDisplayed()\r\n }).map(function (ele) {\r\n return ele.getText()\r\n })\r\n }",
"function headers() {\n return [\n \"Назва\",\n \"Факультет\",\n \"Спеціальність\"\n ];\n }",
"get headers() {\n return this.options.headers || {}\n }",
"function getHeaders(graph)\n{\n\t// If header id attribute is not present return false\n\tif(!(headerElement=document.getElementById(graph + '-header')))\n\t{\n\t\treturn null;\n\t}\n\n\tvar headers= new Array();\n\t\n\tif(!(headers[0]=headerElement.getAttribute('data-xAxis')))\n\t{\n\t\treturn null;\n\t}\n\tif(!(headers[1]=headerElement.getAttribute('data-yAxis')))\n\t{\n\t\treturn null;\n\t}\n\tif(!(headers[2]=headerElement.getAttribute('data-barColor')))\n\t{\n\t\treturn null;\n\t}\n\n\tif(!(headers[3]=headerElement.getAttribute('data-margin')))\n\t{\n\t\treturn null;\n\t}\n\tif(!(headers[4]=headerElement.getAttribute('data-barLabelPerc')))\n\t{\n\t\treturn null;\n\t}\n\tif(!(headers[5]=headerElement.getAttribute('data-legendSize')))\n\t{\n\t\treturn null;\n\t}\n\tif(!(headers[6]=headerElement.getAttribute('data-barSize')))\n\t{\n\t\treturn null;\n\t}\n\t\treturn headers;\n}",
"get header() {\n return this.headers\n }",
"getHeader (doc, header) {\n var kb = this.store\n var requests = kb.each(undefined, ns.link('requestedURI'), doc.uri)\n for (var r = 0; r < requests.length; r++) {\n var request = requests[r]\n if (request !== undefined) {\n var response = kb.any(request, ns.link('response'))\n if (request !== undefined) {\n var results = kb.each(response, ns.httph(header.toLowerCase()))\n if (results.length) {\n return results.map(function (v) {\n return v.value\n })\n }\n return []\n }\n }\n }\n return undefined\n }",
"getHeaders() {\n\n }",
"get header() {\n if (this.envelope) {\n return this.envelope.getElementsByTagNameNS(nsEnvelope, \"Header\")[0];\n }\n return null;\n }",
"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}"
]
| [
"0.7068289",
"0.69782346",
"0.6828954",
"0.6769882",
"0.66751254",
"0.65916806",
"0.6525979",
"0.65228117",
"0.65208364",
"0.65208364",
"0.64754516",
"0.6385975",
"0.6358754",
"0.63203096",
"0.63199353",
"0.6299253",
"0.627801",
"0.627801",
"0.62346566",
"0.6233533",
"0.61658037",
"0.61421925",
"0.603135",
"0.6018928",
"0.59940886",
"0.5910937",
"0.5903562",
"0.589003",
"0.5867528",
"0.58290696"
]
| 0.8435786 | 1 |
Unmark all marked moves, mark the next one. | function unmarkMark(next) {
var moveASpan = function (i) {
return document.querySelector('#' + movesId + i + '> a');
};
removeClass(document.querySelector('#' + movesId + " a.yellow"), 'yellow');
addClass(moveASpan(next), 'yellow');
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function unmarkMark(next) {\n var moveASpan = function(i) {\n return $('#' + movesId + i + \"> a\");\n };\n\n $(\"div#\" + movesId + \" a.yellow\").removeClass('yellow');\n moveASpan(next).addClass('yellow');\n }",
"function unmarker() {\n unmark = 1;\n\t\tmark = 0;\n }",
"function resetMove() {\r\n selected = false;\r\n selectedID = \"\";\r\n lockout = false;\r\n endLoc = 0;\r\n unhighlightMoves();\r\n}",
"function unmarkAll() {\r\n clearDetails();\r\n if (flightPath != null)\r\n flightPath.setMap(null);\r\n for (let marker of markersSet) {\r\n marker.pin.setIcon(\"img/inactive_plane_icon.png\");\r\n }\r\n for (let j = 0; j < intRows.length; j++) {\r\n intTable.rows[j].style.backgroundColor = \"White\";\r\n }\r\n for (let j = 0; j < extRows.length; j++) {\r\n extTable.rows[j].style.backgroundColor = \"White\";\r\n }\r\n }",
"function markFinished(state) {\n state.offset = null;\n}",
"unmark() {\n\t\t\tif(this.line != undefined && this.line instanceof Element) this.line.classList.remove('active');\n\t\t\telse if(this.line != undefined && this.line instanceof Array) {\n\t\t\t\tfor(let i = 0; i < this.line.length; i++) {\n\t\t\t\t\tthis.line[i].classList.remove('active');\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(this.segment != undefined) this.segment.classList.remove('active');\n\t\t\tthis.line = undefined;\n\t\t\tthis.segment = undefined;\n\t\t}",
"clearMark() {\n this.__isMarkActive = false;\n }",
"_unmarkAll() {\n if (!this.isEmpty()) {\n this._selection.forEach(value => this._unmarkSelected(value));\n }\n }",
"_unmarkAll() {\n if (!this.isEmpty()) {\n this._selection.forEach(value => this._unmarkSelected(value));\n }\n }",
"_unmarkAll() {\n if (!this.isEmpty()) {\n this._selection.forEach(value => this._unmarkSelected(value));\n }\n }",
"_unmarkAll() {\n if (!this.isEmpty()) {\n this._selection.forEach(value => this._unmarkSelected(value));\n }\n }",
"function marker() {\n mark = 1;\n\t\tunmark = 0;\n }",
"unmark() {\n this.disposeMarker();\n this.hidePreview();\n }",
"function unmarkAll() {\n if (!this.isEmpty()) {\n this.getArrayCastValue().forEach(value => unmarkSelected.call(this, value));\n }\n}",
"function clearMM(){\r\n mindMoves.forEach(element => {\r\n element.active = false;\r\n })\r\n}",
"move() {\n this.available_moves = [];\n this.unselect();\n\n // TODO: do the rest\n }",
"function moveAllMissiles() {\n\t\tfor (var i = allMissiles.length - 1; i >= 0; i--) {\n\t\t\tif (!allMissiles[i].move(deltaTime/1000)) {\n\t\t\t\tallMissiles.splice(i, 1);\n\t\t\t}\n\t\t}\n\t}",
"function _markRemoved() {\n this.shouldSkip = true;\n this.removed = true;\n this.node = null;\n}",
"_reset() {\n if (this.isDirty) {\n let record;\n let nextRecord;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = nextRecord) {\n record.previousIndex = record.currentIndex;\n nextRecord = record._nextMoved;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"function unblock() {\n\t\t\t\tif (token.block && !token.block.marked) {\n\t\t\t\t\ttoken.block.marked = true;\n\t\t\t\t\ttoken.block.next();\n\t\t\t\t}\n\t\t\t}",
"_reset() {\n if (this.isDirty) {\n let record;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = record._nextMoved) {\n record.previousIndex = record.currentIndex;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"_reset() {\n if (this.isDirty) {\n let record;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = record._nextMoved) {\n record.previousIndex = record.currentIndex;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"_reset() {\n if (this.isDirty) {\n let record;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = record._nextMoved) {\n record.previousIndex = record.currentIndex;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"_reset() {\n if (this.isDirty) {\n let record;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = record._nextMoved) {\n record.previousIndex = record.currentIndex;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"_reset() {\n if (this.isDirty) {\n let record;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = record._nextMoved) {\n record.previousIndex = record.currentIndex;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"_reset() {\n if (this.isDirty) {\n let record;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = record._nextMoved) {\n record.previousIndex = record.currentIndex;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"_reset() {\n if (this.isDirty) {\n let record;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = record._nextMoved) {\n record.previousIndex = record.currentIndex;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"_reset() {\n if (this.isDirty) {\n let record;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = record._nextMoved) {\n record.previousIndex = record.currentIndex;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"_reset() {\n if (this.isDirty) {\n let record;\n for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {\n record._nextPrevious = record._next;\n }\n for (record = this._additionsHead; record !== null; record = record._nextAdded) {\n record.previousIndex = record.currentIndex;\n }\n this._additionsHead = this._additionsTail = null;\n for (record = this._movesHead; record !== null; record = record._nextMoved) {\n record.previousIndex = record.currentIndex;\n }\n this._movesHead = this._movesTail = null;\n this._removalsHead = this._removalsTail = null;\n this._identityChangesHead = this._identityChangesTail = null;\n // TODO(vicb): when assert gets supported\n // assert(!this.isDirty);\n }\n }",
"markMultiple () {\n\t\tthis.setState({ markMode: !this.state.markMode });\n\t\tif (this.state.markMode) {\n\t\t\tthis.setState({ marked: [] });\n\t\t};\n\t}"
]
| [
"0.7276184",
"0.70077974",
"0.621034",
"0.5962253",
"0.59163034",
"0.5886681",
"0.5820942",
"0.5696865",
"0.5696865",
"0.5696865",
"0.5696865",
"0.5681608",
"0.5657213",
"0.56473386",
"0.5647259",
"0.5630975",
"0.5583178",
"0.55461985",
"0.5543661",
"0.55393153",
"0.5510641",
"0.5510641",
"0.5510641",
"0.5510641",
"0.5510641",
"0.5510641",
"0.5510641",
"0.5510641",
"0.5510641",
"0.55100554"
]
| 0.73989147 | 0 |
Fills the comment field depending on which and if a comment is filled for that move. | function fillComment(moveNumber) {
let myMove = that.mypgn.getMove(moveNumber);
if (!~myMove) return;
if (myMove.commentAfter) {
document.querySelector('#' + boardId + " input.afterComment").checked = true;
document.querySelector('#' + boardId + " textarea.comment").value = myMove.commentAfter;
} else if (myMove.commentBefore) {
document.querySelector('#' + boardId + " input.beforeComment").checked = true;
document.querySelector('#' + boardId + " textarea.comment").value = myMove.commentBefore;
} else if (myMove.commentMove) {
document.querySelector('#' + boardId + " input.moveComment").checked = true;
document.querySelector('#' + boardId + " textarea.comment").value = myMove.commentMove;
} else {
document.querySelector('#' + boardId + " textarea.comment").value = "";
}
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function fillComment(moveNumber) {\n var myMove = that.mypgn.getMove(moveNumber);\n if (myMove.commentAfter) {\n $(\"#\" + boardId + \" input.afterComment\").prop('checked', true);\n $(\"#\" + boardId + \" textarea.comment\").val(myMove.commentAfter);\n } else if (myMove.commentBefore) {\n $(\"#\" + boardId + \" input.beforeComment\").prop('checked', true);\n $(\"#\" + boardId + \" textarea.comment\").val(myMove.commentBefore);\n } else if (myMove.commentMove) {\n $(\"#\" + boardId + \" input.moveComment\").prop('checked', true);\n $(\"#\" + boardId + \" textarea.comment\").val(myMove.commentMove);\n } else {\n $(\"#\" + boardId + \" textarea.comment\").val(\"\");\n }\n }",
"_updateFromComment() {\n const oldComment = this.previous('comment');\n const comment = this.get('comment');\n\n if (oldComment) {\n oldComment.destroyIfEmpty();\n }\n\n if (comment) {\n const defaultRichText = this.defaults().richText;\n\n /*\n * Set the attributes based on what we know at page load time.\n *\n * Note that it is *possible* that the comments will have changed\n * server-side since loading the page (if the user is reviewing\n * the same diff in two tabs). However, it's unlikely.\n *\n * Doing this before the ready() call ensures that we'll have the\n * text and state up-front and that it won't overwrite what the\n * user has typed after load.\n *\n * Note also that we'll always want to use our default richText\n * value if it's true, and we'll fall back on the comment's value\n * if false. This is so that we can keep a consistent experience\n * when the \"Always edit Markdown by default\" value is set.\n */\n this.set({\n dirty: false,\n extraData: comment.get('extraData'),\n openIssue: comment.get('issueOpened') === null\n ? this.defaults().openIssue\n : comment.get('issueOpened'),\n requireVerification: comment.requiresVerification(),\n richText: defaultRichText || !!comment.get('richText'),\n });\n\n /*\n * We'll try to set the one from the appropriate text fields, if it\n * exists and is not empty. If we have this, then it came from a\n * previous save. If we don't have it, we'll fall back to \"text\",\n * which should be normalized content from the initial page load.\n */\n const textFields = (comment.get('richText') || !defaultRichText\n ? comment.get('rawTextFields')\n : comment.get('markdownTextFields'));\n\n this.set('text',\n !_.isEmpty(textFields)\n ? textFields.text\n : comment.get('text'));\n\n comment.ready({\n ready: this._updateState,\n }, this);\n }\n }",
"'SET_COMMENTS'(state, commentsall){\n state.comments = commentsall\n }",
"function addComment(comment) {\n\n if(comment.value !== '') {\n\n document.getElementById('comments').style.visibility = 'visible';\n\n var comment = comment.value;\n\n comments.unshift(comment);\n $(\"#comment\").val('');\n this.comments.forEach(displayComments);\n $(document).scrollTop($(document).height()); \n }\n}",
"async save_comment() {\n console.log(this.state.commentBox_data);\n let commentText = this.state.quill.getHTML();\n\n if (commentText == \"<p><br></p>\") {\n this.ui.toast.create_toast(\"You cannot save an empty comment!\", \"warning\");\n return;\n }\n\n let commentType = $(\".commentTypeDropdown\").val();\n\n let span = $(\".\" + escapeSpecialChar(this.state.rem_span));\n\n\n // if state.commentBox_data don't exist, the current comment to be saved is the starting comment of the thread\n let replyEppn = this.state.commentBox_data ? this.state.commentBox_data.eppn_to_reply_to : undefined;\n let replyHash = this.state.commentBox_data ? this.state.commentBox_data.hash_to_reply_to : undefined;\n let editCommentID = this.state.commentBox_data ? this.state.commentBox_data.edit_comment_id : undefined;\n\n /**\n * Determine if its a comment save or comment edit\n */\n if (editCommentID != undefined) {\n // edit/delete comment\n let commentCreatorEppn = $(\".replies\" + \"[commentid = '\" + editCommentID + \"']\").attr('name');\n\n // Check if this is a comment or reply (reply will not have a type)\n let type;\n if ($(\".replies\" + \"[commentid = '\" + editCommentID + \"']\").attr('type')) {\n type = $('.commentTypeDropdown').children(\"option:selected\").val();\n } else {\n type = null;\n }\n\n let data_edit = {\n creator: this.state.selected_creator,\n work: this.state.selected_work,\n commenter: commentCreatorEppn,\n hash: editCommentID,\n type: type,\n text: commentText,\n public: true,\n };\n\n //editOrDelete(data_edit, this.state.commentBox_data.edit_comment_id);\n\n let edit_comment_response = await this.state.api_data.comments_data.edit_comment(data_edit);\n this.ui.toast.create_toast(edit_comment_response);\n\n let firstCommentId = this.state.replyBox_data.first_comment_id;\n let firstCommentCreator = this.state.replyBox_data.first_comment_author;\n\n this.ui.replybox_controller.refreshReplyBox(data_edit[\"creator\"], data_edit[\"work\"], firstCommentCreator, firstCommentId, data_edit[\"type\"]);\n\n if (data_edit[\"type\"]) {\n $(\".commented-selection\" + \"[commentId = '\" + this.state.commentBox_data.edit_comment_id + \"']\").attr(\"typeof\", data_edit[\"type\"]);\n let work_comment_data = await this.state.api_data.comments_data.get_work_highlights();\n this.ui.base_events.filters_events.color_not_used_type_selector(work_comment_data, \"@stonybrook.edu\");\n console.log(this.state.filters.selected_comment_filter, data_edit[\"type\"]);\n if (data_edit[\"type\"] != this.state.filters.selected_comment_filter && this.state.filters.selected_comment_filter != \"show-all-types\") {\n await this.ui.comments_controller.recover_span(this.state.commentBox_data.edit_comment_id);\n //await this.ui.comments_controller.recover_span(this.state.commentBox_data.edit_comment_id);\n //checkSpansNeedRecover(this.state.commentBox_data.edit_comment_id, removeDeletedSpan);\n $(\"#replies\").parent().fadeOut();\n }\n }\n $(\"#comment-box\").parent().fadeOut();\n }\n // save new comment\n else {\n let data_save = {\n author: this.state.selected_creator,\n work: this.state.selected_work,\n commentText: commentText,\n commentType: commentType,\n startIndex: (span.attr(\"startIndex\") ? span.attr(\"startIndex\") : null),\n endIndex: (span.attr(\"endIndex\") ? span.attr(\"endIndex\") : null),\n replyTo: (replyEppn ? replyEppn : null),\n replyHash: (replyHash ? replyHash : null),\n visibility: true,\n };\n\n /**\n * Save the comment via API request\n */\n let save_comment_response = await this.state.api_data.comments_data.save_comment(data_save);\n\n // create a toast showing the response of saving the comment\n this.ui.toast.create_toast(save_comment_response.message);\n\n // hide the textarea comment box\n $(\"#comment-box\").parent().fadeOut();\n\n /**\n * Refresh the reply box if it's a reply,\n * Otherwise, dynamically insert the new comment/highlight into the DOM and display it\n */\n if (replyEppn) {\n let firstCommentId = this.state.replyBox_data.first_comment_id;\n let firstCommentCreator = this.state.replyBox_data.first_comment_author;\n\n this.ui.replybox_controller.refreshReplyBox(data_save[\"author\"], data_save[\"work\"], firstCommentCreator, firstCommentId);\n } else {\n /**\n * Since it's a new highlight, dynamically reset the filters for it.\n */\n console.log(this.state.filters);\n let work_comment_data = await this.state.api_data.comments_data.get_work_highlights();\n //TOCHECK\n //this.ui.base_events.filters_events.reset(work_comment_data);\n //this.ui.render_literature();\n\n let approved;\n let index = {\n 'start': $('.' + escapeSpecialChar(this.state.rem_span)).attr(\"startIndex\"),\n 'end': $('.' + escapeSpecialChar(this.state.rem_span)).attr(\"endIndex\")\n }\n\n $('.' + escapeSpecialChar(this.state.rem_span)).removeAttr('startindex endIndex');\n\n if (save_comment_response[\"approval\"] == true) {\n approved = true;\n } else {\n approved = false;\n $('.' + escapeSpecialChar(this.state.rem_span)).addClass(\"unapprovedComments\");\n }\n\n $('.' + escapeSpecialChar(this.state.rem_span)).attr({\n 'commentId': save_comment_response['commentHash'],\n 'creator': this.state.current_user.eppn,\n 'typeof': data_save['commentType'],\n 'approved': approved\n });\n\n $(\"<param/>\", {\n class: 'startDiv',\n commentId: save_comment_response['commentHash'],\n startIndex: index[\"start\"],\n colorId: 0\n }).insertBefore('.' + escapeSpecialChar(this.state.rem_span));\n\n $(\"<param/>\", {\n class: 'endDiv',\n commentId: save_comment_response['commentHash'],\n endIndex: index[\"end\"],\n colorId: 0\n }).insertAfter('.' + escapeSpecialChar(this.state.rem_span));\n\n $('.' + escapeSpecialChar(this.state.rem_span)).removeClass(this.state.rem_span);\n\n let allComments = createCommentData();\n this.ui.comments_controller.handleStartEndDiv(allComments);\n\n this.ui.base_events.filters_events.color_not_used_type_selector(work_comment_data, \"@stonybrook.edu\");\n\n //updateCommenterSelectors();\n\n //update the click event on this new added comment\n allowClickOnComment(data_save[\"work\"], data_save[\"author\"]);\n }\n\n // TODO: what's this do.\n // NOTE: This function colors the comment if this comment is a unapporved comment\n\n //getUnapprovedComments(data_save[\"author\"], data_save[\"work\"]);\n let response = await this.state.api_data.comments_data.get_unapprove_comments({creator: this.state.selected_creator, work: this.state.selected_work});\n console.log(response);\n response.forEach((data) => {\n let ancesHash = data[\"AncestorHash\"];\n let hash = data[\"CommentHash\"];\n //the first Level is unapproved\n if (ancesHash == hash) {\n $(\".commented-selection\" + \"[commentId = '\" + hash + \"']\").addClass(\"unapprovedComments\");\n } else {\n $(\".commented-selection\" + \"[commentId = '\" + ancesHash + \"']\").addClass(\"threadNotApproved\");\n }\n });\n }\n }",
"function getComment(){\n\t\tuserInput = document.getElementsByClassName(\"opcomment\")[0].value;\n\t\tdocument.getElementsByClassName(\"opcomment\")[0].value = \"\";\n\t\tsetUpSkeletonComment(userInput);\n\t}",
"updateComments() {\n\n const area = this.dom.commentArea\n const items = area.children // Pre-build comment items\n\n // Calculate the number of line of comments as per the current height of commentArea dynamically\n const areaWidth = this.areaWidth\n const areaHeight = this.areaHeight\n const lineHeight = this.lineHeight\n const lineNumber = this.lineNumber\n // console.log('lineNumber', lineNumber);\n\n for (let idx = 0; idx < this.threshold; idx += 1) {\n let comment = items[idx]\n\n // When the length of posArr equals to 0, it shows that the comments have already covered all the lines of the area,\n // then we could just start over again.\n if (this.posArr.length === 0) {\n for (let i = 0; i < lineNumber; i += 1) {\n this.posArr.push(i) // Set the line index into posArr\n }\n }\n\n // Get the line and delete it from posArr\n const randomPos = Utils.random.randomInt(this.posArr.length - 1)\n const lineIdx = this.posArr[randomPos]\n // console.log('this.posArr.length', this.posArr.length);\n // console.log('lineIdx', lineIdx);\n\n const top = lineIdx * lineHeight // Comment item top position\n comment.style.top = `${top}px`\n\n // Delete the used lineIdx\n this.posArr.splice(randomPos, 1)\n }\n\n }",
"addOrUpdateComment(state, comment) {\n if ((comment.Parent === comment.Post &&\n state.postMap[comment.Parent] == null) ||\n (comment.Parent !== comment.Post &&\n state.commentMap[comment.Parent] == null)) {\n // parent is not currently inserted yet, put into buffer\n state.commentBuffer.push(comment);\n return;\n }\n // comment already exists, no need to set child pointers of parents\n if (state.commentMap[comment.Hash] != null) {\n state.commentMap[comment.Hash].Score = comment.Score;\n state.commentMap[comment.Hash].Flag = comment.Flag;\n return;\n }\n if (comment.Parent === comment.Post) {\n if (!state.postMap[comment.Parent].ChildComments) {\n Vue.set(state.postMap[comment.Parent], ChildComments, {});\n }\n Vue.set(state.postMap[comment.Parent].ChildComments,\n comment.Hash, comment);\n } else {\n if (!state.commentMap[comment.Parent].ChildComments) {\n Vue.set(state.commentMap[comment.Parent], ChildComments, {});\n }\n Vue.set(state.commentMap[comment.Parent].ChildComments,\n comment.Hash, comment);\n }\n Vue.set(state.commentMap, comment.Hash, comment);\n }",
"function mungeComment() {\r\n mungeCommentQuoteURLs();\r\n // Previous munges are copied back to cccp_comment;\r\n cccp_comment.value = cccp_comment_dom.innerHTML;\r\n mungeCommentCode();\r\n}",
"SET_COMMENTS(state, payload) {\n state.comments = payload;\n }",
"function mst_initComments() {\n var alldivs = document.getElementsByTagName('div');\n for (var i=0; i<alldivs.length; ++i) {\n if (alldivs[i].className.match(/comments/) &&\n alldivs[i].id != 'prevDiv' && alldivs[i].id != 'prevDiv2' &&\n alldivs[i].innerHTML.match(/posted by/)) {\n comments.push(alldivs[i]);\n } // is a comment\n } // loop divs\n}",
"function expandComment() {\n const button = movementInput.find('CommentInput').find('button');\n button.simulate('click');\n }",
"function SetCommentHeight() {\n var height = (isMobileDevice) ? (dojo.window.getBox().h + 20) : (dojo.coords(dojo.byId('divInfoContent')).h - 10);\n if (height > 0) {\n dojo.byId('divCommentsContent').style.height = (height - ((isBrowser) ? 120 : 150)) + \"px\";\n }\n if (isMobileDevice) {\n dojo.byId('divInfoComments').style.width = dojo.window.getBox().w - 15 + \"px\";\n }\n}",
"function handleChange(e){\n const {name, value} = e.target\n setComment(prevComment => ({\n ...prevComment,\n [name]: value\n }))\n }",
"insertComment() {\n if (this.state.comment) {\n this.setState({\n data: {\n ...this.state.data,\n comments: [...this.state.data.comments, this.state.comment],\n },\n });\n }\n }",
"function synchronizeComments() {\r\n\t\tvar comments = document.getElementById(\"ticket_comments\").innerText;\r\n\t\tvar commands = [\"set access-rule layer \"+selectedLayer.uid+\" uid \" +selectedRule.uid+ \" comments \\\"\" + comments + \"\\\" --format json\"];\r\n\t\tcommitChanges(commands);\r\n\t}",
"function UpdateFightCommentToList(fightinfo) {\r\nvar username = GetUsernameFromFightComment(fightinfo);\r\nvar fighttime = GetTimeFromFightComment(fightinfo);\r\nvar fightcomments = GM_getValue(\"FightComment\" + getOwnUserID() + TOWNEXTENSION + username, \"\").split(\"|\");\r\nvar NrOfFightComments = GetNrOfFightCommentsInList(username);\r\nvar updatedfightcomments = \"\";\r\n\r\nfor (var i = 0; i < NrOfFightComments; i++) {\r\n// Wenn die übergebene Kampfzeit im aktuellen Eintrag gefunden wurde\r\nif (fightcomments[i].indexOf(fighttime) != -1) {\r\n// Wenn der Kommentar nicht leer ist\r\nif (GetCommentFromFightComment(fightinfo) != \"\") {\r\nupdatedfightcomments = updatedfightcomments + GetTimeFromFightComment(fightinfo) + \"*\" + GetCommentFromFightComment(fightinfo) + \"|\";\r\n}\r\n// sonst: Die übergebene Kampfzeit wurde im aktuellen Eintrag nicht gefunden\r\n} else {\r\nupdatedfightcomments = updatedfightcomments + fightcomments[i] + \"|\";\r\n}\r\n}\r\n\r\nGM_setValue(\"FightComment\" + getOwnUserID() + TOWNEXTENSION + username, updatedfightcomments);\r\n}",
"function checkComments()\n{\n data = JSON.parse(window.sessionStorage[\"chat-\" + chatid]);\n \n for (var i = 0; i < data.comments.length; ++i)\n {\n var name = data.comments[i].name;\n var comment = data.comments[i].text;\n \n // Don't process already processed comments\n if (commentIds.includes(data.comments[i].id))\n {\n continue;\n }\n commentIds.push(data.comments[i].id);\n \n var mat = regexMatch(comment);\n \n if (mat != null)\n {\n var tokens = tokenize(comment);\n var message = evaluate(tokens);\n var finalMsg = \"[\" + name + \"] \" + message;\n \n postResponse(finalMsg);\n }\n }\n}",
"function UpdateFightCommentToList(fightinfo) {\r\n\tvar username = GetUsernameFromFightComment(fightinfo);\r\n\tvar fighttime = GetTimeFromFightComment(fightinfo);\r\n\tvar fightcomments = GM_getValue(\"FightComment\" + m_ownuserid + TOWNEXTENSION + username, \"\").split(\"|\");\r\n\tvar NrOfFightComments = GetNrOfFightCommentsInList(username);\r\n\tvar updatedfightcomments = \"\";\r\n\r\n\tfor (var i = 0; i < NrOfFightComments; i++) {\r\n\t\t// Wenn die übergebene Kampfzeit im aktuellen Eintrag gefunden wurde\r\n\t\tif (fightcomments[i].indexOf(fighttime) != -1) {\r\n\t\t\t// Wenn der Kommentar nicht leer ist\r\n\t\t\tif (GetCommentFromFightComment(fightinfo) != \"\") {\r\n\t\t\t\tupdatedfightcomments = updatedfightcomments + GetTimeFromFightComment(fightinfo) + \"*\" + GetCommentFromFightComment(fightinfo) + \"|\";\r\n\t\t\t}\r\n\t\t// sonst: Die übergebene Kampfzeit wurde im aktuellen Eintrag nicht gefunden\r\n\t\t} else {\r\n\t\t\tupdatedfightcomments = updatedfightcomments + fightcomments[i] + \"|\";\r\n\t\t}\r\n\t}\r\n\r\n\tGM_setValue(\"FightComment\" + m_ownuserid + TOWNEXTENSION + username, updatedfightcomments);\r\n}",
"insertComments( { commit }, commentsall ){\n commit('SET_COMMENTS', commentsall)\n }",
"async function forComments(forComment_cb) {\r\n if (post.comments.length > 0) {\r\n //var counter = 0;\r\n async.each(post.comments, function(comm, comm_cb) {\r\n console.log('comm.creator:', comm.creator);\r\n if (users[comm.creator]) {\r\n comm['creator'] = users[post.creator];\r\n } else {\r\n\r\n User.getInfo(comm.creator, function(err, data) {\r\n if (data.Count > 0) {\r\n users[data.Items[0].attrs.userID] = data.Items[0].attrs;\r\n comm['creator'] = data.Items[0].attrs;\r\n }\r\n comm_cb();\r\n })\r\n }\r\n }, forComment_cb)\r\n } else forComment_cb();\r\n }",
"function validateComment(value) {\n if (!value) {\n return 'Please enter a comment'\n }\n }",
"_executeLineComments(model, builder, data, s) {\n let ops;\n if (data.shouldRemoveComments) {\n ops = LineCommentCommand._createRemoveLineCommentsOperations(data.lines, s.startLineNumber);\n }\n else {\n LineCommentCommand._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this._tabSize);\n ops = this._createAddLineCommentsOperations(data.lines, s.startLineNumber);\n }\n const cursorPosition = new position_1.Position(s.positionLineNumber, s.positionColumn);\n for (let i = 0, len = ops.length; i < len; i++) {\n builder.addEditOperation(ops[i].range, ops[i].text);\n if (range_1.Range.isEmpty(ops[i].range) && range_1.Range.getStartPosition(ops[i].range).equals(cursorPosition)) {\n const lineContent = model.getLineContent(cursorPosition.lineNumber);\n if (lineContent.length + 1 === cursorPosition.column) {\n this._deltaColumn = (ops[i].text || '').length;\n }\n }\n }\n this._selectionId = builder.trackSelection(s);\n }",
"function comment(){\n\t\n\tvar firstName;\n\tvar lastName;\n\tvar image;\n\t\n\tvar Comment = Parse.Object.extend(\"Comments\");\n\tvar comments = new Comment();\n\tvar input = $(\"#myComment\").val();\n\t\n\tcomments.set(\"EventId\", _id);\n\tcomments.set(\"Comment\", input);\n\tcomments.set(\"Commenter\", userID);\n\t\n\tvar employee = Parse.Object.extend(\"employee\");\n\tvar query = new Parse.Query(employee);\n\tvar myID = parseInt(userID);\n\t\n\tquery.equalTo(\"employee_id\", myID);\n\tquery.find({\n\t\tsuccess: function(result){\n\t\t\tvar emp = result[0];\n\t\t\tfirstName = emp.get(\"name\");\n\t\t\tlastName = emp.get(\"Last_Name\");\n\t\t\timage = emp.get(\"picture\").url;\n\t\t\t\n\t\t\tcomments.set(\"first_name\", firstName);\n\t\t\tcomments.set(\"last_name\", lastName);\n\t\t\tcomments.set(\"picture\", image);\n\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\tcomments.save(null, {\n\t\t\t\tsuccess: function(exchange) {\n\t\t\t\t\t\n\t\t\t\t},\n\t\t\t\terror: function(exchange, error) {\n\t\t\t\t\talert(\"Error\");\n\t\t\t\t\t$.mobile.changePage(\"#checkin-main\");\n\t\t\t\t}\n\t\t\t});\t\n\t\t}\n\t});\n}",
"handleCommentChange (e) {\n if (e.target == null) {\n this.setState({ comment: 'N/A' })\n } else {\n this.setState({ comment: e.target.value })\n }\n }",
"async handleComment () {\n const text = this.state.text\n if (text === '' || text === null) {\n this.setState({ error: true })\n } else {\n this.setState({ error: false })\n const blogId = this.props.blogId\n const time = moment().format('YYMMDDHHMMSS')\n const comment = {\n comment_id: `${blogId}-${time}`,\n text: text\n }\n this.setState({ text: '' })\n this.props.callbackFunction(blogId, comment)\n }\n }",
"function commentSaved(data) {\n\tif (data.error) {\n\t\talert(data.error);\n\t} else if (data.ok) {\n\t\t$('#comment_field').val('');\n\t\tdata['newer'] = true;\n\t\tdata['comments'] = data.comment;\n\t\tif (!data.idlesson) data['idlesson'] = 0;\n\t\tcommentsReceived(data);\n\t}\n\tenableButtons(['#comment_button']);\n}",
"addComment(){\n let user = new User();\n this.setState({sending:true});\n user.isLoggedIn().then((u) => {\n var comment = {\n user: this.state.currentUser,\n author: u,\n competence: this.props.competenceData,\n activity: this.props,\n comment: this.state.comment\n }\n comment.comment = comment.comment.trim();\n if(!comment.comment) {\n return;\n }\n let activity = new Activity();\n activity.comment(comment).then((d) => {\n let created = Date.now();\n this.state.commentsData.push({user:u.username, created:created, text:this.state.comment});\n this.setState({comments: this.state.comments.cloneWithRows(this.state.commentsData),\n comment:'',\n sending: false\n });\n });\n });\n dismissKeyboard();\n }",
"function enhanceComments()\r\n{\r\n var comment, commentNodes, replyNodes, reply, origReplyLink, bodyInside;\r\n var i, j;\r\n\r\n // iterate through parent comments\r\n commentNodes = findNodes('//div[@class=\"comment\"]/ol/li[@class!=\"\"]');\r\n for (i = 0; i < commentNodes.snapshotLength; i++)\r\n {\r\n comment = initComment(commentNodes.snapshotItem(i));\r\n \r\n bodyInside = $('cbody-inside-' + comment.getAttribute('commentId'));\r\n origReplyLink = findNode('div[@class=\"c-line\"]', bodyInside);\r\n bodyInside.removeChild(origReplyLink.singleNodeValue);\r\n \r\n bodyInside.appendChild(replyLinks(comment.getAttribute('commentId')));\r\n \r\n replyNodes = findNodes('ol/li', comment);\r\n if (replyNodes.snapshotLength > 0)\r\n {\r\n for (j = 0; j < replyNodes.snapshotLength; j++)\r\n {\r\n reply = initReply(replyNodes.snapshotItem(j), comment.getAttribute('commentId')); \r\n bodyInside = $('cbody-inside-' + reply.getAttribute('commentId'));\r\n bodyInside.appendChild(replyLinks(reply.getAttribute('commentId')));\r\n }\r\n }\r\n }\r\n}",
"function ParseRefreshComment(){\n ParseOwnerFieldUpdate();\n refreshNumber = refreshNumber+1;\n if (refreshNumber == 293) {\n return;\n }\n\n setTimeout(function(){\n ParseRefreshComment();\n }, 1000);\n}"
]
| [
"0.7499994",
"0.5694943",
"0.5510648",
"0.54800504",
"0.5427797",
"0.53654367",
"0.53386295",
"0.5328364",
"0.5323308",
"0.5311304",
"0.5233553",
"0.5231824",
"0.5215882",
"0.51919067",
"0.5184448",
"0.51829976",
"0.5178719",
"0.5162215",
"0.51332146",
"0.51237863",
"0.5102517",
"0.50932115",
"0.5078211",
"0.50676036",
"0.5045138",
"0.5044021",
"0.50433433",
"0.5020571",
"0.5009877",
"0.5006231"
]
| 0.7550228 | 0 |
1. Write a function named `giveCompliment` | function giveCompliment(name){
/*- It takes 1 argument: your name
- Inside the function create an array with 10 strings. Each string should be a compliment, like `"great"`, `"awesome"`
- Write logic that randomly selects a compliment
- Return a string: "You are [COMPLIMENT], [YOUR_NAME]!*/
let compliment=["great","good","awesome","the best","excellent","superb","amazing","flawless","victorious","the man"];
const randomCompliment = compliment[Math.floor(Math.random() * compliment.length)];
return console.log(`You are ${randomCompliment},${name}!`)
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function giveCompliment(myName) { // It takes 1 argument\n // create an array with 10 strings\n const complimentList = [\"great\", \"amazing\", \"awesome\", \"perfect\", \"handsome\",\n \"marvelous\", \"extraordinary\", \"wonderful\", \"talented\", \"clever\"];\n // Write logic that randomly selects a compliment\n let randOfComList = Math.floor(Math.random() * complimentList.length);\n let compliment = complimentList[randOfComList];\n // Return a string\n let result = `You are ${compliment}, ${myName}!`\n return result;\n\n}",
"function randomCompliment() {\n\nreturn compliments[Math.floor(Math.random() * (compliments.length - 1))]\n}",
"function getComp() {\n const rpsls = [\"rock\", \"paper\", \"scissors\", \"lizard\", \"spock\"];\n const computer = [Math.floor(Math.random() * rpsls.length)];\n return rpsls[computer];\n}",
"function createCompFromComp (myComp, myName) {\r try{\r var newComp;\r newComp = app.project.items.addComp(myName, myComp.width, myComp.height, 1, myComp.duration, myComp.frameRate);\r newComp.layers.add(myComp); //Adds file to comp\r return newComp;\r } catch(err){\r // alert(\"Error at line# \" + err.line.toString() + \"\\r\" + err.toString());\r return null;\r }\r}",
"makeAComplaint(){\n setAnElementToVisible(select(\"makeComplaintArea\"));\n retrieveBarbersListFromServer();\n }",
"function compChoice() {\n var compChoice = letters[Math.floor(Math.random() * letters.length)];\n console.log(\"comp chose \" + compChoice);\n\n return compChoice;\n }",
"function getSelectedComp() {\n return selectedComp;\n }",
"function circusParade(){\n \n}",
"async function getFetch(comp, requestedComp, length) {\n\tlet response,\n\t\tadress = __way + comp.name + '.mu',\n\t\tstatus = true;\n\t//Обработка адреса\n\tif (comp.extends!==\"noExtends\"&&comp.extends.name!==\"self\") {\n\t\tif (__patterns[comp.extends.name]!==undefined) {\n\t\t\tadress = __patterns[comp.extends.name];\n\t\t}else{\n\t\t\tlog.error(\"Unknown group on component \\\"\" + comp.name + \"\\\"\");\n\t\t\tstatus = false;\n\t\t}\n\t}else if(comp.group!==\"noGroup\"){\n\t\tadress = (__groups[comp.group]!==undefined ? __groups[comp.group] + comp.name + '.mu' : adress);\n\t}else if(comp.way!==\"noWay\"){\n\t\tadress = comp.way;\n\t}\n\t//Запрос\n\tawait fetch(adress)\n\t\t.then(result=>result.ok == true ? result.text() : 'error', e=>console.error(e))\n\t\t.then(res=>{\n\t\t\tif (res!=='error') {\n\t\t\t\tresponse = {\n\t\t\t\t\tname: comp.name,\n\t\t\t\t\tbody: comp.extends!==\"noExtends\" ? getExtendedComp(JSON.parse(comp.extends.data), res, status) : res,\n\t\t\t\t\tlvl: comp.nodeLvl,\n\t\t\t\t};\n\t\t\t\tcomp.group!=='noGroup' ? response.group = comp.group : '';\n\t\t\t\tcomp.extends!=='noExtends'&&status===true ? response.extends = comp.extends : '';\n\t\t\t}else{\n\t\t\t\tresponse = 'error';\n\t\t\t}\n\t\t})\n\trequestedComp.push(response);\n}",
"function compFunc(a, b){\n return a - b;\n}",
"function confirmarCompra(){\n\n}",
"function Composition() {}",
"function Composition() {}",
"function Composition() {}",
"function Composition() {}",
"function getCurrentComp() {\nvar comp = app.project.activeItem;\nif (comp instanceof CompItem) return comp;\nelse\n{\nalert(tr(\"Active composition not found.\\nPlease select a composition or activate the composition panel.\"));\nreturn null;\n}\n}",
"function DataTools4_getMainCompoName(){\r\n return this.getCompoName();\r\n}",
"function Company(name, addresse) {\n console.log(name,+ ' '+ addresse );\n return name,+ ' '+ addresse\n }",
"function addComp(options)\n\t{\n\tvar i = options.index;\n\tvar commands = options.commands;\n\tvar compArr = options.compArr;\n\tvar comp = options.comp;\n\n\tvar postParse;\n\tif( (postParse = parseCompNames\t({\tindex: i, commands: commands, comp: comp })) != null )\n\t\t{\n\t\tif (postParse.btwnNodes || postParse.btwnPoints)\n\t\t\t{\n\t\t\tcompArr[compArr.length] = postParse;\n\t\t\t}\n\n\t\treturn true;\n\t\t}\n\n\treturn false;\n\t}",
"function compCtrl(){\n\n}",
"get complication() {\n\t\treturn this.__complication;\n\t}",
"function randomCompliment () {\n\nif (person !== null)\n{\n $(\"#phrase\").append(person);\n}\n\nelse {\n var arrayOfCompliments = [\"handsome.\", \"cutie.\", \"human.\", \"pal.\", \"smarty pants.\", \"sexy.\",\"classy.\"];\n var randomCompliment = Math.floor(Math.random()*arrayOfCompliments.length);\n $(\"#phrase\").append(arrayOfCompliments[randomCompliment]);\n}\n}",
"function ConsoHerbe(entite,opts){\n\tComposant.call(this,entite);\n}",
"function getCompChoice() {\r\n const choices = ['r', 'p', 's'];\r\n const randomNumber = Math.floor(Math.random()*3);\r\n return choices[randomNumber];\r\n // to get a random number between 0 and 3\r\n}",
"static compilationCiation(saveChoice) {\n let citationCompiler = [];\n citationCompiler.push(this.randomItemFirst(saveChoice));\n citationCompiler.push(this.randomItem(saveChoice));\n citationCompiler.push(this.randomItemLast(saveChoice));\n\n return citationCompiler.join(\" \");\n }",
"function getCompChoice () {\n\tvar randomInt = Math.floor(Math.random() * 3);\n\tif (randomInt == 0) {\n\t\treturn \"rock\";\n\t} else if (randomInt == 1) {\n\t\treturn \"paper\";\n\t} else {\n\t\treturn \"scissors\";\n\t}\n}",
"findCorrespondingComponent(circ, givenComp) {\n for (let comp of circ.getComponents()) {\n if ( (comp.getEndPt1().equals(givenComp.getEndPt1()) && comp.getEndPt2().equals(givenComp.getEndPt2())) || (comp.getEndPt1().equals(givenComp.getEndPt2()) && comp.getEndPt2().equals(givenComp.getEndPt1())) ) {\n return comp;\n }\n }\n return null;\n }",
"function compFunc() {\n\n let computerChoice = Math.random();\n\n if (computerChoice < 0.2) {\n computerChoice = \"Rock\";\n } else if (computerChoice <= 0.4) {\n computerChoice = \"Paper\";\n }\n else if (computerChoice <= 0.6) {\n computerChoice = \"Scissors\";\n\n } else if (computerChoice <= 0.8) {\n computerChoice = \"Lizard\";\n\n }\n\n else {\n computerChoice = \"Spock\";\n }\n return computerChoice;\n}",
"function getCurrComp()\r\n\t\t{\r\n\t\t\tvar comps = getSelectedComps();\r\n\t\t\t\r\n\t\t\tif (comps.length === 1)\r\n\t\t\t\treturn comps;\r\n\t\t\telse\r\n\t\t\t\treturn null;\r\n\t\t}",
"function computerChoice() {\n var randomNum = Math.floor(Math.random() * 3);\n comp = names[randomNum];\n}"
]
| [
"0.6683876",
"0.667681",
"0.59986377",
"0.57679355",
"0.57417107",
"0.5566981",
"0.5564886",
"0.55515885",
"0.5532021",
"0.5457313",
"0.5451016",
"0.5433085",
"0.5433085",
"0.5433085",
"0.5433085",
"0.5403409",
"0.5395066",
"0.53683805",
"0.5354695",
"0.5313772",
"0.5306471",
"0.530414",
"0.52985364",
"0.5294711",
"0.529257",
"0.5281445",
"0.5272494",
"0.5267935",
"0.5260855",
"0.5243344"
]
| 0.699392 | 0 |
logic for handling updating of currNum & screen | function updateCurrNum(value) {
if (currNum.init) {
currNum = value;
currNum.init = false;
//need to fix logic for preventing leading zeros
} else if (currNum != '0') {
currNum += value;
}
updateScreen(currNum);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function updateScreen(x,y){\n if (!numSwitch){\n screenDown.innerHTML=num1\n }\n else{\n screenDown.innerHTML=num2\n }\n switch(x){\n case 0:\n screenUp.innerHTML= `${num1} ${y}`\n break\n\n case 1:\n screenUp.innerHTML+= num2;\n screenDown.innerHTML=y;\n break\n\n case 'c':\n screenUp.innerHTML=''\n screenDown.innerHTML=''\n break\n }\n\n}",
"function handleNumber() {\n this.blur();\n currentNum += this.value;\n addToScreen(currentNum);\n needsNum = false;\n}",
"function setNum() { \r\n if (resultNum) { // If a result was displayed, reset number\r\n resultNum = \"\";\r\n theNum = this.getAttribute(\"data-num\"); \r\n } else { // Otherwise, add digit to previous number (this is a string!)\r\n theNum = firstScreen.innerHTML+ this.getAttribute(\"data-num\");\r\n } \r\n\r\n if(oldNum == \"\"){\r\n firstScreen.innerHTML = theNum;\r\n } else{\r\n theNum = secondScreen.innerHTML+ this.getAttribute(\"data-num\");\r\n secondScreen.innerHTML = theNum; \r\n } \r\n }",
"function processNum(num) {\n\t\tcurrentVal += num;\n\t\tdisplayer(currentVal);\n\t}",
"function handleNumberClick(button) {\n if (overwrite) {\n screenNum = button;\n overwrite = false;\n } else {\n if (decEditing) {\n decValue = decValue * 10 + button;\n screenNum = Math.floor(screenNum) + (\".\" + decValue);\n } else {\n screenNum = screenNum * 10 + button;\n }\n }\n canEval = true;\n document.getElementById(\"screen\").innerHTML = screenNum;\n }",
"function updateScreen(number) {\n document.getElementById('display').innerText = number;\n}",
"function updateEverything(currentNumber) {\n $('#riverImage').attr('src',riverImages[currentNumber-1]);\n $('#riverName').text(riverNames[currentNumber-1]);\n $('#myNumber').text(currentNumber);\n}",
"function moveNum() { \r\n if(!firstScreen.innerHTML ==\"\" ) {\r\n secondScreen.setAttribute(\"contenteditable\", \"true\"); \r\n //1\r\n if(!operator && parseFloat(firstScreen.innerHTML) ){\r\n oldNum = parseFloat(firstScreen.innerHTML); \r\n theNum = \"\";\r\n }\r\n //2\r\n operator = this.getAttribute(\"data-ops\"); \r\n //3\r\n\r\n //Displaying Operators\r\n switch (operator) {\r\n case \"plus\": \r\n operatorScreen.innerHTML = \"+\";\r\n break;\r\n \r\n case \"minus\": \r\n operatorScreen.innerHTML = \"-\";\r\n break;\r\n \r\n case \"times\": \r\n operatorScreen.innerHTML = \"x\";\r\n break;\r\n \r\n case \"divided by\": \r\n operatorScreen.innerHTML = \"/\";\r\n break; \r\n } \r\n } \r\n }",
"function changeDisplayMeasurement(){\n currentIdx = (currentIdx + 1) % displayItems.length;\n console.log(\"Changed\")\n}",
"function updateDisplay() {\n robot.balls = countEvents(robot.events, 'pickup');\n robot.points.high = countEvents(robot.events, 'high');\n robot.points.low = countEvents(robot.events, 'low');\n robot.points.miss = countEvents(robot.events, 'miss');\n robot.defense.fouls = countEvents(robot.events, 'foul');\n robot.defense.tech = countEvents(robot.events, 'tech');\n\n if (robot.balls < 0) {\n robot.balls = 0;\n }\n\n $('#ball-count-display').text(robot.balls);\n $('#high-ball-display').text(robot.points.high);\n $('#low-ball-display').text(robot.points.low);\n $('#miss-display').text(robot.points.miss);\n $('#match-number-display').text('Match Number: ' + fieldAppState.currentMatch.matchNumber);\n $('#team-number-display').text('Team Number: ' + parseTeam(robot.team));\n $('#team-color-display').text('Alliance: ' + parsecolor(robot.color));\n $('#driver-station-display').text('Driver Station: ' + parseStation(settings.station));\n $('#main-team-number-display').text('Scouting: ' + parseTeam(robot.team));\n $('#robot-image').attr('src', robot.image);\n $('#fouls-display').text('Fouls: ' + robot.defense.fouls + ' ');\n $('#tech-fouls-display').text('Techs: ' + robot.defense.tech);\n\n $('#info-panel').addClass(robot.color);\n\n writeMods();\n\n checkForInvalidNumbers();\n }",
"function updateVisualSequence(num) {\n\tvisualSequence[4] = visualSequence[3];\n\tvisualSequence[3] = visualSequence[2];\n\tvisualSequence[2] = visualSequence[1];\n\tvisualSequence[1] = visualSequence[0];\n\tvisualSequence[0] = num;\n}",
"function displayNum() {\r\n // Convert string input to numbers\r\n if(!firstScreen.innerHTML == \"\" && !secondScreen.innerHTML ==\"\"){\r\n oldNum = parseFloat(oldNum);\r\n theNum = parseFloat(theNum); \r\n\r\n firstOperand = parseFloat(firstScreen.innerHTML);\r\n \r\n secondOperand = parseFloat(secondScreen.innerHTML)\r\n \r\n // Perform Operations\r\n switch (operator) {\r\n case \"plus\":\r\n resultNum = firstOperand + secondOperand;\r\n break;\r\n \r\n case \"minus\":\r\n resultNum = firstOperand - secondOperand; \r\n break;\r\n \r\n case \"times\":\r\n resultNum = firstOperand * secondOperand; \r\n break;\r\n \r\n case \"divided by\":\r\n resultNum = firstOperand / secondOperand; \r\n break;\r\n \r\n // If equal is pressed without an operator, keep number and continue\r\n default:\r\n resultNum = theNum; \r\n }\r\n \r\n firstScreen.innerHTML = resultNum;\r\n secondScreen.innerHTML =\"\";\r\n operatorScreen.innerHTML =\"\"\r\n operator = undefined;\r\n \r\n // Display result, finally!\r\n viewer.innerHTML = resultNum;\r\n \r\n // Now reset oldNum & keep result\r\n oldNum = 0;\r\n theNum = resultNum;\r\n } else{\r\n viewer.innerHTML = \"Enter Number\"\r\n }\r\n secondScreen.setAttribute(\"contenteditable\", \"false\"); \r\n }",
"update_current_info() {\n this.update_current_phase();\n this.update_current_time();\n }",
"updateCurrent(position) {\n this.DOM.current.innerHTML = position < 10 ? `0${position+1}` : position;\n }",
"function updateDisplay(){\r\n console.log(curr);\r\n $(\"#curr\").html(curr);\r\n $(\"#highest\").html(highest);\r\n $(\"#lowest\").html(lowest);\r\n $(\"#average\").html(average);\r\n}",
"function numButton() {\n // Get the number pressed\n let number = parseInt(this.innerHTML);\n // If screen is empty, just replace with number\n if (displaySpace == \"0\") {\n displaySpace = number.toString();\n } // If not, just tack number to the end\n else {\n displaySpace += number;\n }\n }",
"function updateDisplay(){\n if(values){\n displayItems[currentIdx].display();\n }\n}",
"function compWin() {\n ++scoreComp;\n $('#compScore').html(scoreComp);\n}",
"function updateCurrentScoreNumber() {\n currentScore++\n $(\".score-number\").text(`Current Score: ${currentScore}`);\n}",
"function screenDis(num) {\n $(\".screen\").append(num);\n }",
"function update() {\n // if reset button is clicked call init\n if (resetButton.restartGame === true) {\n resetButton.restartGame = false;\n resetButton.clearGameData(moveCounterElem, timerElem, starRatingElem, gameBoardHTML);\n init();\n }\n // keep setting current time of timer obj on every loop\n timer.getCurrentTime();\n // kick off the timer after mouseup of the first move.\n if (moveCount.currentMoveCount >= 1) {\n timer.keepTime();\n }\n // update the timer\n timer.updateDOMTimer(timerElem);\n\n // set checkedLastPair to false since array was cleared (only reason to be less than 2)\n if (iconDeck.currentPair.length < 2) {\n\n iconDeck.checkedLastPair = false;\n\n }\n\n // check if cards are a match\n if (iconDeck.checkedLastPair === false && iconDeck.currentPair.length === 2) {\n\n iconDeck.checkedLastPair = true;\n\n compareTiles(iconDeck.currentPair);\n // update the displayed number in the counter element.\n\n }\n\n if (moveCount.currentMoveCount > starRating.tempMoveCount) {\n starRating.tempMoveCount = moveCount.currentMoveCount;\n starRating.checkedStarRating = false;\n }\n\n // encapsulate condition to prevent multiple runs\n if (starRating.checkedStarRating === false && starRating.currentStarRating != 1) {\n starRating.checkedStarRating = true;\n // will a simple switch get the job done\n switch (moveCount.currentMoveCount) {\n case 20:\n {\n starRating.currentStarRating -= 1;\n starRating.updateDOM(starRatingElem, starRating.currentStarRating);\n // starRating.checkedStarRating = true;\n break;\n }\n case 30:\n {\n starRating.currentStarRating -= 1;\n starRating.updateDOM(starRatingElem, starRating.currentStarRating);\n // starRating.checkedStarRating = true;\n break;\n }\n default:\n {\n break;\n }\n\n }\n\n }\n // update the displayed number in the counter element.\n moveCount.updateDOM(moveCounterElem);\n }",
"function getNumber(number) {\n let curr = document.getElementById('window');\n if (clearScreen === true) {\n curr.value = \"\";\n clearScreen = false;\n }\n curr.value += number;\n pending = curr.value;\n }",
"function updateDisplay() {\n numberDisplay.innerText = currentNumber;\n operatorDisplay.innerText = currentOperator;\n}",
"function updateActiveDisplayWindow(){\n\t\t\n\t\tif(_currEntryMode === _MODES.DISPLAY){\n\t\t\t// placing in main keypad display area and into div\n\t\t var tString = buildHtmlStringFromArray();\n\t\t\t_$displayWindow.html(tString);\n\t\t\t\n\t\t\t//console.log(\"here is the string ------ \" + tString);\n\t\t\t\n\t\t\t// update div html and data-array on screen only if one is chosen\n\t\t\tif(_$currentTextDivOnScreen !== null){\n\t\t\t\t_$currentTextDivOnScreen.html(_$displayWindow.html());\n\t\t\t\t_$currentTextDivOnScreen.attr('data-htmlarray', JSON.stringify(_masterHtmlArray));\n\t\t\t\t_$currentTextDivOnScreen.attr('data-output', tString);\n\t\t\t\t\n\t\t\t\tvar isBuilderPHP = false;\n\t\t\t\tfor (var i = 0; i < pageName.length; i++) {\n\t\t\t\t\tif (pageName[i] == \"builder.php\") isBuilderPHP = true;\n\t\t\t\t}\n\n\t\t\t\t// iBuilder Store values in json\n\t\t\t\tif (isBuilderPHP) {\n\t\t\t\t\tLO_page_app.store_keypad(_$currentTextDivOnScreen.attr(\"id\"));\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// USE MATHJAX HERE\n\t\t\t// mathajax is in que so that cursor is reset after\n\t\t\tMathJax.Hub.Queue([\"Typeset\",MathJax.Hub]); \n\t\t\tMathJax.Hub.Queue(setBlinkingCursorDistance);\t\n\t\t\t\n\t\t\tMathJax.Hub.Queue(function () {\n\n\t\t\t\t$('.txt span').each(function() {\n\t\t\t\t\t$(this).css(\"visibility\",\"visible\");\n\t\t\t\t});\t\t\n\n\t\t\t});\n\t\t\t\n\t\t} else {\n\t\t\t// in fraction display\n\t\t\t// no MathJax needed\n\t\t\tif(_fractionMode === _MODES.TOPFRACTION){\n\t\t\t\t//place in top field\n\t\t\t\t var tString = buildHtmlStringFromArray();\n\t\t\t\t_$topFractionDisplay.html(tString);\n\t\t\t}else{\n\t\t\t\t//place in bottom field\n\t\t\t\t var tString = buildHtmlStringFromArray();\n\t\t\t\t_$botFractionDisplay.html(tString);\n\t\t\t}\n\t\t}\t\t\n\t}",
"function handlePosNeg(){\n console.log('true')\n if (currNum ){\n if(currNum > 0 ){\n console.log('changed to negative');\n currNum = currNum * -1;\n currNum = currNum.toString();\n console.log('currNum:',currNum);\n var firstPart = calcScreen.innerText.slice(0,calcScreen.innerText.length + 1 - currNum.length);\n console.log('firstPart:',firstPart);\n calcScreen.innerText = firstPart + currNum;\n }\n else if (currNum < 0){\n console.log('changed to positive')\n // firstPart = '';\n currNum = currNum * -1;\n currNum = currNum.toString();\n console.log('currNum:',currNum);\n var changeFirstPart = calcScreen.innerText.slice(0,calcScreen.innerText.length - 3 - currNum.length);\n console.log('changeFirstPart:',changeFirstPart);\n calcScreen.innerText = changeFirstPart + currNum;\n }\n }\n console.log('comp:', components);\n}",
"screenIndexChange() {\n\t\tthis.baseCountChange(this.navBaseCount);\n\t}",
"function updateCurrentText() {\n currentEl.innerText = `${currentActiveCard + 1}/${cardsEl.length}`\n}",
"function updateNumbers(){\n // look how I loop through all tiles\n tileSprites.forEach(function(item){\n // retrieving the proper value to show\n if (item == null)\n return;\n var value = fieldArray[item.pos];\n var currFramename = item.frameName;\n\n // remove tile\n if (value === 0){\n item.destroy();\n } else\n // update tile\n if (currFramename != tileNames[value]) {\n //update needed\n item.frameName=tileNames[value];\n item.scale.setTo(2.0, 2.0);\n game.add.tween(item.scale).to({x: tileScale, y: tileScale}, 150, Phaser.Easing.Bounce.Out, true);\n\n // scoring\n score += (value/2);\n updateScore();\n }\n });\n }",
"function updateCurrentText() { \n currentEl.innerText = `${currentActiveCard + 1}/${cardsEl.length}`\n}",
"function updateScreen(){\n const screen = document.querySelector('.screen');\n screen.innerHTML = calculator.screenValue;\n}"
]
| [
"0.67669946",
"0.6752814",
"0.6493039",
"0.6459563",
"0.6381617",
"0.6258436",
"0.6240207",
"0.6129744",
"0.61290735",
"0.6069174",
"0.6040527",
"0.601121",
"0.60052913",
"0.59985465",
"0.59736466",
"0.59180576",
"0.5906777",
"0.58814734",
"0.5862437",
"0.58563673",
"0.5853572",
"0.58506304",
"0.5848091",
"0.58480126",
"0.584714",
"0.58433646",
"0.5824795",
"0.581541",
"0.5799875",
"0.57942814"
]
| 0.75199705 | 0 |
Keys that should be rejected by the server | function getBadServerKeys(tbl, key, allowPartial) {
const badKeys = [
{},
{
nosuchfield: 1
},
//Invalid extra field: currently disabled since currently proxy
//allows extra fields, will reenable with next protocol version.
//Object.assign({}, key, { nosuchfield: 'aaaaa' }),
//invalid types for primary key
Object.assign({}, ...tbl.primaryKey.map(v => ({ [v]: null }))),
Object.assign({}, ...tbl.primaryKey.map(v => ({ [v]: () => {} }))),
Object.assign({}, ...tbl.primaryKey.map(v => ({ [v]: {} }))),
Object.assign({}, ...tbl.primaryKey.map(v => ({ [v]: [1, 2, 3] })))
];
if (tbl.primaryKey.length > 1) {
//missing primary key fields, first or last fields specified
const k1 = tbl.primaryKey[0];
const k2 = tbl.primaryKey[tbl.primaryKey.length - 1];
expect(key[k1]).to.exist;
expect(key[k2]).to.exist;
if (!allowPartial) {
badKeys.push({ k1: key[k1] });
}
badKeys.push({ k2: key[k2] });
}
return badKeys;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function getAllowedKeys(keys) {\n return keys.filter((key) => {\n return blacklist.indexOf(key) === -1;\n });\n}",
"keysToIgnoreWhenCheckingContentEquality() {\n return [];\n }",
"function warnOnInvalidKey(child, knownKeys) {\n\t {\n\t if (typeof child !== 'object' || child === null) {\n\t return knownKeys;\n\t }\n\t switch (child.$$typeof) {\n\t case REACT_ELEMENT_TYPE:\n\t case REACT_CALL_TYPE:\n\t case REACT_PORTAL_TYPE:\n\t warnForMissingKey(child);\n\t var key = child.key;\n\t if (typeof key !== 'string') {\n\t break;\n\t }\n\t if (knownKeys === null) {\n\t knownKeys = new Set();\n\t knownKeys.add(key);\n\t break;\n\t }\n\t if (!knownKeys.has(key)) {\n\t knownKeys.add(key);\n\t break;\n\t }\n\t warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n\t break;\n\t default:\n\t break;\n\t }\n\t }\n\t return knownKeys;\n\t }",
"validateNonKeyAttributes(nonKeyAttributes) {\n if (this.nonKeyAttributes.length + nonKeyAttributes.length > 20) {\n // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-secondary-indexes\n throw new RangeError('a maximum number of nonKeyAttributes across all of secondary indexes is 20');\n }\n // store all non-key attributes\n this.nonKeyAttributes.push(...nonKeyAttributes);\n // throw error if key attribute is part of non-key attributes\n this.attributeDefinitions.forEach(keyAttribute => {\n if (typeof keyAttribute.attributeName === 'string' && this.nonKeyAttributes.includes(keyAttribute.attributeName)) {\n throw new Error(`a key attribute, ${keyAttribute.attributeName}, is part of a list of non-key attributes, ${this.nonKeyAttributes}` +\n ', which is not allowed since all key attributes are added automatically and this configuration causes stack creation failure');\n }\n });\n }",
"function warnOnInvalidKey(child, knownKeys) {\n\t {\n\t if (typeof child !== 'object' || child === null) {\n\t return knownKeys;\n\t }\n\t switch (child.$$typeof) {\n\t case REACT_ELEMENT_TYPE:\n\t case REACT_PORTAL_TYPE:\n\t warnForMissingKey(child);\n\t var key = child.key;\n\t if (typeof key !== 'string') {\n\t break;\n\t }\n\t if (knownKeys === null) {\n\t knownKeys = new Set();\n\t knownKeys.add(key);\n\t break;\n\t }\n\t if (!knownKeys.has(key)) {\n\t knownKeys.add(key);\n\t break;\n\t }\n\t warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$7());\n\t break;\n\t default:\n\t break;\n\t }\n\t }\n\t return knownKeys;\n\t }",
"function warnOnInvalidKey(child, knownKeys) {\n\t {\n\t if (typeof child !== 'object' || child === null) {\n\t return knownKeys;\n\t }\n\t switch (child.$$typeof) {\n\t case REACT_ELEMENT_TYPE:\n\t case REACT_PORTAL_TYPE:\n\t warnForMissingKey(child);\n\t var key = child.key;\n\t if (typeof key !== 'string') {\n\t break;\n\t }\n\t if (knownKeys === null) {\n\t knownKeys = new Set();\n\t knownKeys.add(key);\n\t break;\n\t }\n\t if (!knownKeys.has(key)) {\n\t knownKeys.add(key);\n\t break;\n\t }\n\t warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$2());\n\t break;\n\t default:\n\t break;\n\t }\n\t }\n\t return knownKeys;\n\t }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n\t {\n\t if (typeof child !== 'object' || child === null) {\n\t return knownKeys;\n\t }\n\t switch (child.$$typeof) {\n\t case REACT_ELEMENT_TYPE:\n\t case REACT_PORTAL_TYPE:\n\t warnForMissingKey(child);\n\t var key = child.key;\n\t if (typeof key !== 'string') {\n\t break;\n\t }\n\t if (knownKeys === null) {\n\t knownKeys = new Set();\n\t knownKeys.add(key);\n\t break;\n\t }\n\t if (!knownKeys.has(key)) {\n\t knownKeys.add(key);\n\t break;\n\t }\n\t warning$1(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);\n\t break;\n\t default:\n\t break;\n\t }\n\t }\n\t return knownKeys;\n\t }",
"function warnOnInvalidKey(child, knownKeys) {\n\t {\n\t if (typeof child !== 'object' || child === null) {\n\t return knownKeys;\n\t }\n\t switch (child.$$typeof) {\n\t case REACT_ELEMENT_TYPE:\n\t case REACT_PORTAL_TYPE:\n\t warnForMissingKey(child);\n\t var key = child.key;\n\t if (typeof key !== 'string') {\n\t break;\n\t }\n\t if (knownKeys === null) {\n\t knownKeys = new Set();\n\t knownKeys.add(key);\n\t break;\n\t }\n\t if (!knownKeys.has(key)) {\n\t knownKeys.add(key);\n\t break;\n\t }\n\t warning$1(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);\n\t break;\n\t default:\n\t break;\n\t }\n\t }\n\t return knownKeys;\n\t }",
"function warnOnInvalidKey(child, knownKeys) {\n\t {\n\t if (typeof child !== 'object' || child === null) {\n\t return knownKeys;\n\t }\n\t switch (child.$$typeof) {\n\t case REACT_ELEMENT_TYPE:\n\t case REACT_PORTAL_TYPE:\n\t warnForMissingKey(child);\n\t var key = child.key;\n\t if (typeof key !== 'string') {\n\t break;\n\t }\n\t if (knownKeys === null) {\n\t knownKeys = new Set();\n\t knownKeys.add(key);\n\t break;\n\t }\n\t if (!knownKeys.has(key)) {\n\t knownKeys.add(key);\n\t break;\n\t }\n\t warning$1(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);\n\t break;\n\t default:\n\t break;\n\t }\n\t }\n\t return knownKeys;\n\t }",
"function warnOnInvalidKey(child, knownKeys) {\n\t {\n\t if (typeof child !== 'object' || child === null) {\n\t return knownKeys;\n\t }\n\t switch (child.$$typeof) {\n\t case REACT_ELEMENT_TYPE:\n\t case REACT_PORTAL_TYPE:\n\t warnForMissingKey(child);\n\t var key = child.key;\n\t if (typeof key !== 'string') {\n\t break;\n\t }\n\t if (knownKeys === null) {\n\t knownKeys = new Set();\n\t knownKeys.add(key);\n\t break;\n\t }\n\t if (!knownKeys.has(key)) {\n\t knownKeys.add(key);\n\t break;\n\t }\n\t warning$1(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);\n\t break;\n\t default:\n\t break;\n\t }\n\t }\n\t return knownKeys;\n\t }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_CALL_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$1());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n if (typeof key !== 'string') {\n break;\n }\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$7());\n break;\n default:\n break;\n }\n }\n return knownKeys;\n }",
"function missingSecret(){\n\tvar testName = 'Missing Secret';\n\tvar description = 'clinet missing secret should be rejected';\n\t\n\tvar options = {\n\t\thostname: 'capstone-ltemac.herokuapp.com',\n\t\tport: 443,\n\t\tpath: '/',\n\t\tmethod: 'GET'\n\t};\n\t\n\tvar req = https.request(options, function(res){\n\t\t\n\t\tif(res.statusCode === 400){\n\t\t\tconsole.log(colors.green(testName + ': ') + description);\n\t\t}\n\t\telse{\n\t\t\tconsole.log(colors.red(testName + ': ') + description);\n\t\t\tconsole.log(colors.blue('Status Code: ') + colors.white(res.statusCode));\n\t\t}\n\t});\n\t\n\t\n\treq.on('error', function(e){\n\t\tconsole.error(e);\n\t});\n\t\n\treq.end();\n}"
]
| [
"0.6038159",
"0.5908205",
"0.5719545",
"0.57131755",
"0.5693765",
"0.56937134",
"0.5668548",
"0.5668548",
"0.56413615",
"0.56413615",
"0.56413615",
"0.56413615",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.56307864",
"0.5627589",
"0.5627144"
]
| 0.62804693 | 0 |
La funcion lk1 trabaja con el contenido filtrado: | function lk1(){
const dr_estilo = document.querySelectorAll('#tabla_resultado .select_filtr');//Capturando contenido filtrado
const estilo5 = function (){
this.style.color = "#00acc1";
}
const estilo6 = function (){
this.style.color = "#fff";
}
const buscar = function (){
$('#contenidoFiltrado').html('<div class="preloader"></div>');
$('#search').val(this.childNodes[3].childNodes[0].innerHTML);//Ponemos en la busqueda la eleccion escogida
$('#tabla_resultado').html('<div></div>');//Quitamos los resultados filtrados
bandera_inicio_albums = this.childNodes[9].innerHTML;//representa el identificador del filtrado, si se trata de un album, artista o pista
que_es = this.childNodes[7].innerHTML;
if (bandera_inicio_albums == 4) {dr_posi = this.childNodes[11].innerHTML}
obtener_registros();//Mandamos a traer lo filtrado
$("html, body").animate({scrollTop: $('#divMenu').offset().top }, 1000);
}
dr_estilo.forEach(dr_botom => {
dr_botom.addEventListener("click", buscar);
dr_botom.addEventListener("mouseover", estilo5);
dr_botom.addEventListener("mouseout", estilo6);
});
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"filtrarSugerencias(resultados, busqueda) {\n const filtro = resultados.filter( filtro => filtro.calle.indexOf(busqueda) !== -1 );\n\n // Iniciar el mapa\n this.inicializarMapa();\n\n // Mostrar pines del Filtro\n this.mostrarMapa(filtro);\n }",
"function filtrering() {\n document.querySelector(\"#menu\").classList.add(\"hidden\");\n document.querySelector(\"#menu\").classList.remove(\"overlay_menu\");\n document.querySelector(\"#menuknap\").textContent = \"☰\";\n console.log(\"FILTER\");\n filter = this.dataset.kategori;\n\n document.querySelectorAll(\".filter\").forEach(elementer => {\n elementer.classList.remove(\"valgt\");\n })\n console.log(this)\n this.classList.add(\"valgt\");\n // document.querySelector(\"#menu\").classList.add(\"hidden\");\n visFisker();\n}",
"function fun1() {} // funcção, parametros e bloco de codigo da função",
"function filtrar(){\n const resultado = inventario.filter( filtrarmarca ).filter( filtrararticulo );\n mostrar(resultado);\n}",
"function sc_filter(proc, l1) {\n var dummy = { cdr : null };\n var tail = dummy;\n while (l1 !== null) {\n\tif (proc(l1.car) !== false) {\n\t tail.cdr = sc_cons(l1.car, null);\n\t tail = tail.cdr;\n\t}\n\tl1 = l1.cdr;\n }\n return dummy.cdr;\n}",
"function geraLDC(parametro1) {\n console.log(\"LDC \" + parametro1);\n arquivo += \"LDC \" + parametro1 + \"\\n\";\n}",
"function filtrarPorLetra(arreglo, letra) {\n let nuevoArreglo = [];\n\n for (let i = 0; i < arreglo.length; i++) {\n let nombre = arreglo[i];\n if (nombre[0] === letra) {\n nuevoArreglo.push(nombre);\n }\n \n }\n\n\n\n return nuevoArreglo;\n}",
"function f1(){\n \t return m.search();\n\t}",
"_loopByKey1(index0, key1, callback) {\n var key0, index1;\n for (key0 in index0) {\n index1 = index0[key0];\n if (index1[key1])\n callback(key0);\n }\n }",
"filtreTexte(data){\n model.samPresent({do:'filtreTexte', x:data.e.target.value })\n }",
"listenFilter(f) {\r\n //accedo al btn asignado de la clase filtro\r\n f.boton.addEventListener('click', () => f.aplicar(this.canvas));\r\n }",
"function geraLDV(parametro1) {\n console.log(\"LDV \" + parametro1);\n arquivo += \"LDV \" + parametro1 + \"\\n\";\n}",
"function filtrolabore(hab,i){\n\n\t\treturn hab[i]['idlele']==1;\n}",
"filtrarSugerencias(resultado, busqueda){\n //filtrar con .filter\n //con idexOf nos retornará la posicion en la que se encuentra, sino lo encuentra retornará -1\n //Aqui le decimos traeme todos en los que el resultado sea diferente a -1\n const filtro = resultado.filter(filtro => filtro.calle.indexOf(busqueda) !== -1);\n console.log(filtro);\n //mostrar los pines\n this.mostrarPines(filtro);\n }",
"function filtromixta(hab,filtrado,com,moneda){\n\n\t var enerotl=0;var febrerotl=0; var marzotl=0; var abriltl=0; var mayotl=0; var juniotl=0; var juliotl =0; var agostotl=0; var septiembretl=0; var octubretl =0; var noviembretl=0; var diciembretl =0; \n\t\n\n\tfor (var i=0; i < hab.length ; i++) {\n\n\t\t\tif (isNaN(hab[i]['enero'+com+''])){ hab[i]['enero'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['febrero'+com+''])){ hab[i]['febrero'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['marzo'+com+''])){ hab[i]['marzo'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['abril'+com+''])){ hab[i]['abril'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['mayo'+com+''])){ hab[i]['mayo'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['junio'+com+''])){ hab[i]['junio'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['julio'+com+''])){ hab[i]['julio'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['agosto'+com+''])){ hab[i]['agosto'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['septiembre'+com+''])){ hab[i]['septiembre'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['octubre'+com+''])){ hab[i]['octubre'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['noviembre'+com+''])){ hab[i]['noviembre'+com+'']=0; }\n\t\t\tif (isNaN(hab[i]['diciembre'+com+''])){ hab[i]['diciembre'+com+'']=0; }\n\n\n\t\t \tif(filtrado(hab,i) && hab[i]['idmoneda']== moneda){\n\t\t\t enerotl += parseFloat(hab[i]['enero'+com+'']);\n\t\t febrerotl += parseFloat(hab[i]['febrero'+com+'']); \n\t\t marzotl += parseFloat(hab[i]['marzo'+com+'']); \n\t\t abriltl += parseFloat(hab[i]['abril'+com+'']); \n\t\t mayotl += parseFloat(hab[i]['mayo'+com+'']); \n\t\t juniotl += parseFloat(hab[i]['junio'+com+'']); \n\t\t juliotl += parseFloat(hab[i]['julio'+com+'']); \n\t\t agostotl += parseFloat(hab[i]['agosto'+com+'']); \n\t\t septiembretl += parseFloat(hab[i]['septiembre'+com+'']); \n\t\t octubretl += parseFloat(hab[i]['octubre'+com+'']); \n\t\t noviembretl += parseFloat(hab[i]['noviembre'+com+'']); \n\t\t diciembretl += parseFloat(hab[i]['diciembre'+com+'']); \t\t\n\t\t}//fin if \n\t\n\t}//fin for \n\tvar labor = new Array(enerotl,febrerotl,marzotl,abriltl,mayotl,juniotl,juliotl,agostotl,septiembretl,octubretl,noviembretl,diciembretl);\n\treturn labor;\n}// fin funcion ",
"function addPaiFilho2(){ \n\t wdkAddChild('listaMaterial'); \n\t \n\t$( \"input[name*='vlrqtd___'], input[name*='qtdMat___']\" ).keyup(function(){\n\t\t\tvar indice = this.name.split(\"___\")[1];\t\t\n\t\t\tsetTimeout(function(){ replaceCalculaValorTotal(indice)}, 1);\n\t\t});\n\t}",
"function armaFiltro(theFormName) {\ntry {\n theForm = document.getElementById(theFormName);\n var qs = '';\n var tipo = '' ;\n for (e=0;e<theForm.elements.length;e++) {\n if (theForm.elements[e].name!=''&& theForm.elements[e].name.indexOf('bu_')>=0) {\n\t var str=theForm.elements[e].name;\n\t var str1=str.replace(/bu_/,\"wl_\");\n\t var str2=str.replace(/bu_/,\"nu_\");\t \n\n\t\tx=document.getElementsByName(str1)[0];\n\t\tx1=document.getElementsByName(str2)[0];\n\n \tif (x.value!='') { \n\t \ttry { tipo=x1.value; }\n\t \tcatch (err) { tipo=2; } \n\t \tif (tipo=2)\n\n \t\t{ \n\t \t\tqs+=(qs=='')?' ':' and ';\n\t\t\tif (x.value.indexOf('%')>=0) // si el dato tiene un % quiere decier que es un like\n\t \t{\n\t \t\tqs+=x.name.substring(3)+' like \\''+x.value+\"'\";\t \t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t \t\tqs+=x.name.substring(3)+'=\\''+x.value+\"'\"; // 20071107\n\t\t\t}\n\t \t}\n\n \t\t}\n }\n }\n\tfiltro=document.createElement(\"input\"); \n filtro.type='hidden'; /// firefox\n filtro.value=qs;\n filtro.id='_filtro_';\n filtro.name='_filtro_'; \n theForm.appendChild(filtro);\n \treturn qs\n} catch (err) { alert('error armaFiltro='+err); }\n}",
"function filtros(capa2, capa1, valor,activo){\n\n\tvar nuevo;\n\tvar responses, responses2;\n\tif(capa1 == \"datos\"){\n\t\tnuevo = capa1;\n\t\tcapa1 = \"empty\";\n\t}\t \t\t\n\n\tif(capa2 != 'empty' && capa1 != 'empty'){\n\t $.ajax({\n\t\t xhr: function(){ /////INDICADOR DE CARGA\n\t\t var xhr = new window.XMLHttpRequest();\n\t\t //Download progress\n\t\t xhr.addEventListener(\"progress\", function(evt){\n\t\t if (evt.lengthComputable) {\n\t\t pb.start(evt.total);\n\t\t pb.updateBar(evt.loaded);\n\t\t \tif(evt.loaded == evt.total){\n\t\t \tpb.hide();\n\t\t \t}\n\t\t }\n\t\t }, false);\n\t\t return xhr;\n\t\t },\n//\t\t url:\"/ARCA/UI/servicios.xsodata/GENERALS?$format=json&$groupby=TEXTO_CUSTOMER, LATITUD_RTM, LONGITUD_RTM&$select=TEXTO_CUSTOMER, LATITUD_RTM, LONGITUD_RTM\", data:{'$filter': capa2},\n\t\t url:\"/ARCA/UI/servicios.xsodata/NUEVO?$format=json&$select=LAT_CUS, LON_CUS, VENTA_CU, CUSTOMER\", data:{'$filter' : \"CUSTOMER ne '' and TEXTO_CUSTOMER ne '' and LAT_CUS ne 0 and LON_CUS ne 0 and \" + capa2},\n\t\t\t success:function(respuesta){\n\t\t\t if(respuesta.d.results.length == 0){\n\t\t\t\t\talert(\"No existe resultados para este criterio de búsqueda.\");\n\t\t\t\t\tdevuelve(1);\n\t\t }else{\t\n\t\t\t\t responses = respuesta.d.results;\n\t\t\t\t\tvar latlon1 = [];\n\t\t\t\t\tlatlonM = [];\n\t\t\t\t\t\n\t\t\t\t\tfor (var i in responses){\n//\t\t\t\t\t\tvar ubicacion = [responses[i].LATITUD_RTM, responses[i].LONGITUD_RTM];//, responses[i].TEXTO_CLIENTE, responses[i].TEXTO_CLIENTE,responses[i].ISSCOM,responses[i].SUBCANALresponses[i].TRZONE];\n\t\t\t\t\t\tvar ubicacion = [responses[i].LAT_CUS, responses[i].LON_CUS, responses[i].VENTA_CU, responses[i].CUSTOMER];\n\t\t\t\t\t\tlatlonM.push(ubicacion);\n//\t\t\t\t\t\tlatlon1.push({location: new google.maps.LatLng(responses[i].LATITUD_RTM, responses[i].LONGITUD_RTM)});\n\t\t\t\t\t\tlatlon1.push({location: new google.maps.LatLng(responses[i].LAT_CUS, responses[i].LON_CUS)});\n\t\t\t\t\t\t\n\t\t\t\t\t};\n\n\t\t\t\t\tlatilong = latlonM;//marcador\n\t\t\t\t\tlatlon = latlon1;//calor capa2\n\t\t\t\t\t\t\t\n\t\t\t\t//CAPA1\n\t\t\t\t $.ajax({\n//\t\t\t\t\t url:\"/ARCA/UI/servicios.xsodata/CAPA1S?$format=json\", data:{'$filter': capa1 },\n\t\t\t\t\t url:\"/ARCA/UI/servicios.xsodata/NUEVO?$format=json&$select=LAT_CUS, LON_CUS, CUSTOMER, TEXTO_CUSTOMER, TXT_CAN_ISSCOM, SUBCANAL, TRZONE, VENTA_CU\", data:{'$filter' : \"CUSTOMER ne '' and TEXTO_CUSTOMER ne '' and LAT_CUS ne 0 and LON_CUS ne 0 and \" + capa1},\n\t\t\t\t\t\t\tsuccess:function(respuesta){\n\t\t\t\t\t\tresponses2 = respuesta.d.results;\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tgen_coord(responses2);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(valor != \"\" && cedi_seleccion() == \"X\"){//En caso de ZONA realiza el zoom\n\t\t\t\t\t\t\t\tzoomzona(valor);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\tif(cedi_seleccion() != \"X\"){\n\n\t\t\t\t\t\t\t\tif(markers.length != 0){setMarcador(null);}\n\t\t\t\t\t\t\t\tcrea_marcador(latlng, latilong, activo)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdevuelve(0);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tswitch(diferencia){\n\t\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\t\theatmap.setMap(null);\n\t\t\t\t\t\t\t\tif(heatmaps != \"z\"){\n\t\t\t\t\t\t\t\theatmaps.setMap(null);\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\tif(cedi_seleccion() != \"X\"){\n\t\t\t\t\t\t\t\tsetMarcador(null);\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\tcalor(latlngM);\n\t\t\t\t\t\t\t\tmapa_calor_filtro(latlon);\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\t\theatmap.setMap(null);\n\t\t\t\t\t\t\t\tif(heatmaps != \"z\"){\n\t\t\t\t\t\t\t\theatmaps.setMap(null);\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\t\n\t\t\t\t\t\t\t\tif(cedi_seleccion() != \"X\"){\n\t\t\t\t\t\t\t\tsetMarcador(map);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t},\n\t\t\t\t\t\terror: function (respuesta) {\n\t\t\t\t\t\t\t alert(\"Error al realizar consulta\");\n\t\t\t\t\t\t\t}\n\t\t\t\t});\t\n\t\t\t}\n\t },\n\t error: function (respuesta) {\n\t \t alert(\"Error al realizar consulta\");\n\t \t}\n\t\t \n\t });\n\t \n\t\t\t\t\t\t\n\t}else if(capa2 != 'empty' && capa1 == 'empty'){\n\t\t $.ajax({\n\t\t\t xhr: function(){ /////INDICADOR DE CARGA\n\t\t\t var xhr = new window.XMLHttpRequest();\n\t\t\t //Download progress\n\t\t\t xhr.addEventListener(\"progress\", function(evt){\n\t\t\t if (evt.lengthComputable) {\n\t\t\t pb.start(evt.total);\n\t\t\t pb.updateBar(evt.loaded);\n\t\t\t \tif(evt.loaded == evt.total){\n\t\t\t \tpb.hide();\n\t\t\t \t}\n\t\t\t }\n\t\t\t }, false);\n\t\t\t return xhr;\n\t\t\t },\n//\t\t\t url:\"/ARCA/UI/servicios.xsodata/GENERALS?$format=json&$groupby=TEXTO_CUSTOMER, LATITUD_RTM, LONGITUD_RTM&$select=TEXTO_CUSTOMER, LATITUD_RTM, LONGITUD_RTM\", data:{'$filter': capa2},\n\t\t\t url:\"/ARCA/UI/servicios.xsodata/NUEVO?$format=json&$select=LAT_CUS, LON_CUS, VENTA_CU, CUSTOMER\", data:{'$filter' : \"CUSTOMER ne '' and TEXTO_CUSTOMER ne '' and LAT_CUS ne 0 and LON_CUS ne 0 and \" + capa2},\n\t\t\t\t success:function(respuesta){\n\t\t\t\t if(respuesta.d.results.length == 0){\n\t\t\t\t\t\talert(\"No existe resultados para este criterio de búsqueda.\");\n\t\t\t\t\t\tdevuelve(1);\n\t\t\t }else{\t\n\t\t\t\t\t responses = respuesta.d.results;\n\t\t\t\t\t\tvar latlon1 = [];\n\t\t\t\t\t\tlatlonM = [];\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (var i in responses){\n//\t\t\t\t\t\t\tvar ubicacion = [responses[i].LATITUD_RTM, responses[i].LONGITUD_RTM];//, responses[i].TEXTO_CLIENTE, responses[i].TEXTO_CLIENTE,responses[i].ISSCOM,responses[i].SUBCANALresponses[i].TRZONE];\n\t\t\t\t\t\t\tvar ubicacion = [responses[i].LAT_CUS, responses[i].LON_CUS,responses[i].VENTA_CU,, responses[i].CUSTOMER];\n\t\t\t\t\t\t\tlatlonM.push(ubicacion);\n//\t\t\t\t\t\t\tlatlon1.push({location: new google.maps.LatLng(responses[i].LATITUD_RTM, responses[i].LONGITUD_RTM)});\n\t\t\t\t\t\t\tlatlon1.push({location: new google.maps.LatLng(responses[i].LAT_CUS, responses[i].LON_CUS)});\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tlatilong = latlonM;//marcador\n\t\t\t\t\t\tlatlon = latlon1;//calor capa2\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(nuevo == 'datos'){\n\t\t\t\t\t\t\theatmap.setMap(null);\n\t\t\t\t\t\t\tif(heatmaps != \"z\"){heatmaps.setMap(null);}\n\t\t\t\t \t\t\tcalor(capa_principal);\n\t\t\t\t \t\t\tmap.setCenter(new google.maps.LatLng(20.520556, -99.895833));\n\t\t\t\t \t\t map.setZoom(5);\n\t\t\t\t \t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tdevuelve(0);\n\t\t\t\t\t\t\n\t\t\t\t\t\tswitch(diferencia){\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tif(heatmaps != \"z\"){\n\t\t\t\t\t\t\theatmaps.setMap(null);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(cedi_seleccion() != \"X\"){\n\t\t\t\t\t\t\tsetMarcador(null);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmapa_calor_filtro(latlon);\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tif(heatmaps != \"z\"){\n\t\t\t\t\t\t\t\theatmaps.setMap(null);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(cedi_seleccion() != \"X\"){\n\t\t\t\t\t\t\tsetMarcador(map);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t }},\n\t\t\t error: function (respuesta) {\n\t\t\t \t alert(\"Error al realizar consulta\");\n\t\t\t \t }\n\t\t\t \n\t\t });\t\t\t\n\n\t\t\t\t\t\t\n\t}else if(capa2 == 'empty' && capa1 != 'empty'){\n\t\t $.ajax({\n\t\t\t xhr: function(){ /////INDICADOR DE CARGA\n\t\t\t var xhr = new window.XMLHttpRequest();\n\t\t\t //Download progress\n\t\t\t xhr.addEventListener(\"progress\", function(evt){\n\t\t\t if (evt.lengthComputable) {\n\t\t\t pb.start(evt.total);\n\t\t\t pb.updateBar(evt.loaded);\n\t\t\t \tif(evt.loaded == evt.total){\n\t\t\t \tpb.hide();\n\t\t\t \t}\n\t\t\t }\n\t\t\t }, false);\n\t\t\t return xhr;\n\t\t\t },\n//\t\t\t url:\"/ARCA/UI/servicios.xsodata/CAPA1S?$format=json\", data:{'$filter': capa1},\n\t\t\t url:\"/ARCA/UI/servicios.xsodata/NUEVO?$format=json&$select=LAT_CUS, LON_CUS, CUSTOMER, TEXTO_CUSTOMER, TXT_CAN_ISSCOM, SUBCANAL, TRZONE, VENTA_CU\", data:{'$filter' : \"CUSTOMER ne '' and TEXTO_CUSTOMER ne '' and LAT_CUS ne 0 and LON_CUS ne 0 and \" + capa1},\n\t\t\t\t success:function(respuesta){\n\t\t\t\t if(respuesta.d.results.length == 0){\n\t\t\t\t\t\talert(\"No existe resultados para este criterio de búsqueda.\");\n\t\t\t\t\t\tdevuelve(1);\n\t\t\t }else{\t\n\t\t\t\t\t responses = respuesta.d.results;\n\t\t\t\t\t \n\t\t\t\t\t gen_coord(responses);\n\t\t\t\t\t\t\n\t\t\t\t\t\tlatilong = [];\n\t\t\t\t\t\tif(valor != \"\" && cedi_seleccion() == \"X\"){//En caso de ZONA realiza el zoom\n\t\t\t\t\t\t\tzoomzona(valor);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(cedi_seleccion() != \"X\"){\n\n\t\t\t\t\t\t\tif(markers.length != 0){setMarcador(null);}\n\t\t\t\t\t\t\tcrea_marcador(latlng, latilong, activo)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tdevuelve(0);\n\t\t\t\t\t\t\n\t\t\t\t\t\tswitch(diferencia){\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\theatmap.setMap(null);\n\t\t\t\t\t\t\tif(heatmaps != \"z\"){\n\t\t\t\t\t\t\theatmaps.setMap(null);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(cedi_seleccion() != \"X\"){\n\t\t\t\t\t\t\tsetMarcador(null);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcalor(latlngM);\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\theatmap.setMap(null);\n\t\t\t\t\t\t\tif(heatmaps != \"z\"){\n\t\t\t\t\t\t\t\theatmaps.setMap(null);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(cedi_seleccion() != \"X\"){\n\t\t\t\t\t\t\tsetMarcador(map);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t}},\n\terror: function (respuesta) {\n\t\t alert(\"Error al realizar consulta\");\n\t\t}\n\t\t\t \n\t\t });\n\t\t\t\t }\n}",
"function sc_filterBang(proc, l1) {\n var head = sc_cons(\"dummy\", l1);\n var it = head;\n var next = l1;\n while (next !== null) {\n if (proc(next.car) !== false) {\n\t it.cdr = next\n\t it = next;\n\t}\n\tnext = next.cdr;\n }\n it.cdr = null;\n return head.cdr;\n}",
"function filtroActorTkAfegir(e) {\n if (e.id_actor == $(\"#actor-editar\").val() && e.takes_restantes > 0){\n return e;\n }\n}",
"function filtrararticulo(inventario){\n if(datosBusqueda.articulo2){\n return inventario.articulo === datosBusqueda.articulo2;\n }\n return inventario;\n}",
"_loopByKey1(index0, key1, callback) {\n let key0, index1;\n for (key0 in index0) {\n index1 = index0[key0];\n if (index1[key1])\n callback(key0);\n }\n }",
"_loopByKey1(index0, key1, callback) {\n var key0, index1;\n for (key0 in index0) {\n index1 = index0[key0];\n if (index1[key1])\n callback(key0);\n }\n }",
"function filtrarmarca(inventario){\n if(datosBusqueda.marca2){\n return inventario.marca === datosBusqueda.marca2;\n }\n return inventario;\n}",
"function filtrarZapatos(){\n\t\n\t\tvar resultado = $(\"#resultado5A\");\n\t\tvar zapatos = ejer5.zapatos;\n\t\tvar resultados = mostrarZapatos(zapatos);\n\t\t\n\t\tresultado.html(resultados);\n\t}",
"_loopByKey1(index0, key1, callback) {\n var key0, index1;\n\n for (key0 in index0) {\n index1 = index0[key0];\n if (index1[key1]) callback(key0);\n }\n }",
"function readQ(){\n document.getElementById(\"Table22\").innerHTML='';\n var c = document.getElementById(\"Idgenero\").value;\n\n const lista_libros = JSON.parse(localStorage.getItem(\"libros\"));\n var librosC=lista_libros.filter(libro=>libro.genero==c);\n if(librosC)\n {\n librosC.forEach((libro)=>printRowQ(libro));\n }\n //console.log(librosC)\n}",
"function marcar_Filme_Visto(nome_e_Titulo) {\n\n // Encontra id do espectador e do filme\n const id_Do_Espectador = db('espectadores')\n .select('id')\n .where({ 'nome': nome_e_Titulo['nome'] });\n\n const id_Do_Filme = db('filmes')\n .select('id')\n .where({ 'titulo': nome_e_Titulo['titulo'] });\n\n\n // Encerra a função adicionando na lista de filmes assistidos o id do espectador e do filme\n return db('filmes_Assistidos').insert({ espectador_id: id_Do_Espectador, filme_id: id_Do_Filme });\n}",
"function grabTextFromFields(){\n\n // Select all the input tags; this is a current object; research \"this\" - homework\n var changedElement = d3.select(this).select(\"input\");\n var inputValue = changedElement.property(\"value\");\n var FilterKeys = changedElement.attr(\"id\");\n\n if(inputValue){\n trackFilters[FilterKeys] = inputValue;\n }\n else{\n delete trackFilters[FilterKeys];\n }\n\n filterTable();\n\n}",
"function filtrarCelulares(){\n\t\n\t\tvar resultado = $(\"#resultado4A\");\n\t\tvar celulares = ejer4.celulares;\n\t\tvar resultados = mayor2000Celulares(celulares);\n\t\t\n\t\tresultado.html(resultados);\n\t}"
]
| [
"0.53175664",
"0.5276723",
"0.5275403",
"0.5263181",
"0.52149326",
"0.51560205",
"0.50838006",
"0.5055052",
"0.5018888",
"0.49820137",
"0.4980397",
"0.4967882",
"0.49524117",
"0.4933793",
"0.49156064",
"0.4887934",
"0.48847938",
"0.48847714",
"0.48772037",
"0.48622492",
"0.48535416",
"0.48421133",
"0.4842024",
"0.4827229",
"0.48202398",
"0.48106843",
"0.48020256",
"0.4784782",
"0.47833124",
"0.47714686"
]
| 0.59630454 | 0 |
Funcion que activa los elementos del reproductor: | function activa_repro(){
//Activamos los elementos necesatios para utilizar el reproductor:
document.getElementById('art').style.display = 'block';
$('#Album_datos').attr("class", "col s3 m4 l3 hide-on-small-only");
$('#Controles_music').attr("class", "col s12 m8 l7");
slider.removeAttribute('disabled');
$("#barra_volumen").prop('disabled', false);
bandera_habilita_eventos = 1;
bandera_repro_pause = 0;
anima_datos();
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function ActivarElemento (idElemento) {\r\n\r\n}",
"function activar(copia, seccion, padre, a){\n\tvar btn_menos = copia.getElement(\".menos\");\n\tbtn_menos.addEvent('click', function(){\n\t\tbtnMenos.call(padre, seccion, a);\n\t});\n\t\n\treconteo('#'+seccion+' .registro', a);\n}",
"function activarBtnAddProduct() {\n $('#btnAddProduct').removeAttr('disabled');\n $('#btnCalcularDescuento').removeAttr('disabled');\n $('#btnMostrarPrecios').removeAttr('disabled');\n\n\n }",
"function activar(tbody, table){\n\t\t$(tbody).on(\"click\", \"span.activar\", function(){\n var data=table.row($(this).parents(\"tr\")).data();\n statusConfirmacion('productos/status_producto', data.id_producto, 1, \"¿Esta seguro de activar el registro?\", 'activar');\n });\n\t}",
"function element_on() {\n del_on();\n edit_on();\n add_on();\n }",
"function activate() {\n\n\n }",
"addEvent() {\n document.addEventListener('click', e => {\n let target = e.target;\n let obj = this.product.elements.filter(el => el.id == target.getAttribute('data-id'));\n // Verify all elements that match target element ID and creates an array \"obj\"\n \n target.classList.contains('add') && this.cart.addToCart(obj[0]);\n target.classList.contains('remove') && this.cart.removeFromCart(obj[0]);\n target.classList.contains('closeOrder') && this.cart.closeOrder();\n target.classList.contains('details') && this.product.showDetails(target.getAttribute('data-id'));\n target.classList.contains('modal__close') && this.product.closeDetails(target.getAttribute('data-id'));\n // Verify by class name if it add or remove an item and pass as argument only one item from array obj\n });\n }",
"function activar(tbody, table){\n\t\t$(tbody).on(\"click\", \"span.activar\", function(){\n var data=table.row($(this).parents(\"tr\")).data();\n statusConfirmacion('Planes/status_planes', data.id_planes, 1, \"¿Esta seguro de activar el registro?\", 'activar');\n });\n\t}",
"function arataMeniulAscunsDouaElemente(clasaButoane, clasaMeniuriAscunse) {\n const Butoane = document.querySelectorAll(clasaButoane);\n const MeniuriAscunse = document.querySelectorAll(clasaMeniuriAscunse);\n // const numarButoane = vnvButoane.length;\n \n for (let numarOrdin in Butoane) {\n Butoane[numarOrdin].onclick = function() {\n Butoane[numarOrdin].classList.toggle('active');\n MeniuriAscunse[numarOrdin].classList.toggle('active');\n }\n }\n}",
"function reemplazar( e ){\n\t\t// guardar el numero de la imagen actual \n\n\t\t// generar numero aleatorio \n\n\t\t// quito el numero original de la lista de activos\n\n\t\t// revisar si numero aleatorio generado esta activo \n\n\t\t// si no esta\n\t\t$(e).attr(\"src\", \"img/fotos/\" + getRandomArbitrary( 1, 165 ) + \".jpg\");\n\n\t\t// de lo contrario generar otro y volver a comparar\n\t}",
"function activateElement (element){\n\t//Remove class \"selected\" from sibling elements\n\t$(element).siblings().removeClass(\"selected\");\n\t//Add class \"selected\" to clicked element\n\t$(element).addClass(\"selected\");\n\n}",
"function activarEventosInventario () \n{\n \n}",
"function _seleccionarActividad(_actividad) {\n\n $('#divHorarios').css('display', 'block');\n $('#tituloModal').css('display', 'block');\n\n // Obtenemos la actividad que se selecciono\n _actividadSeleccionada = Actividades.filter(a => a.nombre === _actividad)[0];\n\n // armamos el titulo del modal\n $('#subtitulo').append(`<p>Los horarios disponibles para ${_actividadSeleccionada.nombre} son:</p>`);\n \n // recorremos los horarios disponibles\n for(const horario of _actividadSeleccionada.horarios){\n\n // mostramos los horarios\n $('#ulModal').append(\n `<li class=\"modal__modalContenido--horarioContainer__ulHorarios--li\">\n <p class=\"modal__modalContenido--horarioContainer__ulHorarios--li__p\" id=\"horarioId${horario.id}\");\">${horario.hora}</p>\n </li>\n `\n );\n\n // CAPTURAMOS EL HORARIO AL QUE SE LE HIZO CLICK.\n $(`#horarioId${horario.id}`).on('click', () => _seleccionarHorario(horario));\n }\n}",
"function activate(){\n\n\t\t}",
"function active() {\n // decimal\n decimal.disabled = false;\n // oprération\n for (let i = 0; i <bOperation.length; i++) {\n bOperation[i].disabled = false;\n }\n // chiffres\n for (let i = 0; i <chiffre.length; i++) {\n chiffre[i].disabled = true;\n }\n}",
"function ClickManuelBois() {\n\tressourceBois = ressourceBois + clickBois;\n\tAffichage();\n\t\n}",
"function activar() {\n let codigoCarrera = this.dataset.codigo;\n let carrera = buscarCarreraPorCodigo(codigoCarrera);\n\n carrera[6] = true;\n\n swal({\n title: \"Activar carrera\",\n text: \"¿Está seguro que desea activar esta carrera?\",\n buttons: [\"Cancelar\", \"Aceptar\"],\n }).then((willDelete) => {\n if (willDelete) {\n actualizarCarrera(carrera);\n mostrarCarrerasDesactivadas();\n }\n });\n}",
"function setNumActiveElements(num) {\n //Remove any existing element button listeners\n removeElementButtonListeners();\n //Set to value passed to function for initial loading\n if(typeof(num) === \"number\") {\n numActiveElements = num;\n }\n else {\n //Otherwise use the value in the radio button \n numActiveElements = this.value;\n }\n //Add the new number of element buttons.\n //Don't need to remove the old ones because the whole HTML structure is replaced.\n addElementButtons();\n //Add listeners to the new element buttons\n addElementButtonListeners();\n //Update the header and title text\n setHeaderTitleText();\n //Reset scores\n resetScores();\n resetDifficultyControls();\n}",
"function activa2(formulario,nombre){\r\n\r\nvar tamano = eval('document.'+formulario+'.elements.length');\r\nvar x = Number(tamano);\r\n\r\nfor (i=0; i<x ; i++) {\r\n\tif (\"document.forms['\"+formulario+\"'].elements[i].type=='button'\")\r\n\t\tif (eval(\"document.forms['\"+formulario+\"'].elements[i].name==nombre\")) {\r\n\t\t\t(eval(\"document.forms['\"+formulario+\"'].elements[i].disabled=false\"));\r\n\t\t}\r\n\t}\r\n}",
"function activate() {\r\n\t\t\t\r\n\t\t}",
"function ElementBtnClicked(){\n\t _ElementListWidget.clear();\n for(i = 0; i < Elements.length; i++){\n _ElementListWidget.addItem(Elements[i]);\n }\n\t ElementProxy.visible = true;\n\t SceneProxy.visible = ! ElementProxy.visible;\n\t BackgroundProxy.visible = ! ElementProxy.visible;\n\t clearPropTypeSubMenu(\"Element\");\n\t}",
"function setElements(){\r\n form_Primary_List= getElement(\"Primary\");\r\n form_Primary_List.onchange=list_primary_on_change;\r\n form_Secondary_List= getElement(\"Secondary\");\r\n form_Secondary_List.onchange=list_secondary_on_change;\r\n button_Submit_Choice= getElement(\"Main_Button\");\r\n ul_vernacular_terms=getElement(\"Vernacular\");\r\n ul_species_terms=getElement(\"Species\");\r\n ul_selection_history=getElement(\"History\");\r\n ul_all_feature_value_pairs=getElement(\"Related_features\");\r\n \r\n}",
"function seleccionHotel(listaHoteles) {\n listaHoteles.forEach((element) => {\n $(`#${element.id}`).click((e) => {\n $(\"#seleccionHotel\").append(\n `<p class='seleccion'>Elegiste ${element.nombre}</p>`\n );\n $(\".deshotel\").prop(\"disabled\", true);\n reserva.push(element.nombre)\n habitacionesCard()\n });\n });\n}",
"function seleccionHabitacion(listaHabitaciones) {\n listaHabitaciones.forEach((element) => {\n $(`#${element.id}`).click((e) => {\n $(\"#seleccionHabitacion\").append(\n `<p class='seleccion'>Elegiste ${element.nombre}</p>\n <p class=\"seleccion\">Precio de $<span id=\"precioHabitacion\">${element.precio}</span>`\n );\n $(\".deshabitacion\").prop(\"disabled\", true);\n reserva.push(element.nombre)\n serviciosCard()\n })\n })\n}",
"function activar(tbody, table){\n\t\t$(tbody).on(\"click\", \"span.activar\", function(){\n var data=table.row($(this).parents(\"tr\")).data();\n statusConfirmacion('Servicios/status_servicio', data.id_servicios, 1, \"¿Esta seguro de activar el registro?\", 'activar');\n });\n\t}",
"function activate() {\n\n }",
"function immaginePrecedente() {\n\n // creo una variabile che contiene la classe 'active' relativa alla visualizzazione dell'elemento\n var elementoCorrente = $('.images img.active');\n var pallinoCorrente = $('.nav i.active');\n // rimuovo la classe che rende visibile l'elemento\n elementoCorrente.removeClass('active');\n pallinoCorrente.removeClass('active');\n\n // se l'elemento corrente ha classe 'first' aggiungo la classe 'active' all'ultimo pallino\n if (elementoCorrente.hasClass('first')) {\n $('.images img.last').addClass('active');\n } // altrimenti, se non ha classe 'first', all'elemento precedente aggiungo la classe 'active'\n else {\n elementoCorrente.prev('img').addClass('active');\n }\n\n // se il pallino corrente ha classe 'first' aggiungo la classe 'active' all'ultimo pallino\n if (pallinoCorrente.hasClass('first')) {\n $('.nav i.last').addClass('active');\n } // altrimenti, se non ha classe 'first', al pallino precedente aggiungo la classe 'active'\n else {\n pallinoCorrente.prev('i').addClass('active');\n }\n}",
"activate() {\n\n\t\tthis.arbitrate();\n\n\t}",
"function activaB(formulario,botones){\r\nvar tamano = eval('document.'+formulario+'.elements.length');\r\nvar bsize = Number(botones.length);\r\nvar x = Number(tamano);\r\nfor (i=0; i<x ; i++) {\r\n\tif (\"document.forms['\"+formulario+\"'].elements[i].type=='button'\")\r\n\tfor (k=0; k<bsize; k++) {\r\n\t\tvar nombre = eval('document.'+formulario+'.'+botones[k]+'.name');\r\n\t\tif (eval(\"document.forms['\"+formulario+\"'].elements[i].name=='\"+nombre+\"'\")) (eval(\"document.forms['\"+formulario+\"'].elements[i].disabled=false\"));\r\n\t\t}\r\n\t}\r\n}",
"turnOn ()\n\t{ \n\t\tthis.intialItems();\n\t\t//this.itemRequest();\t\n this.itemRequest();\n\t}"
]
| [
"0.690029",
"0.61898553",
"0.61261797",
"0.59702396",
"0.5862063",
"0.5852063",
"0.58015305",
"0.5800982",
"0.57443315",
"0.5733752",
"0.57215196",
"0.5704066",
"0.56894505",
"0.5677984",
"0.5652153",
"0.564887",
"0.56395686",
"0.563247",
"0.5621341",
"0.5611243",
"0.5600414",
"0.5592076",
"0.5563795",
"0.5557166",
"0.5550773",
"0.55492365",
"0.55413806",
"0.5522427",
"0.5520498",
"0.55078775"
]
| 0.69290006 | 0 |
Funcion para animar el texto de los datos del album: | function anima_datos(){
var titulo_song = $('#title').text();
var artista_song = $('#artist').text();
var afecta_titulo = document.getElementById('title');
var afecta_artista = document.getElementById('artist');
if (titulo_song.length > 23) {
afecta_titulo.innerHTML = '<MARQUEE SCROLLDELAY =300>'+titulo_song+'</MARQUEE>';
}
if (artista_song.length > 23) {
afecta_artista.innerHTML = '<MARQUEE SCROLLDELAY =300>'+artista_song+'</MARQUEE>';
}
/*if ($('#title_movil').text().length > 30) {
$('#title_movil').html('<MARQUEE SCROLLDELAY =300>'+titulo_song+'</MARQUEE>')
}*/
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function animarTexto1(){\n //incremento la posicion en 1 y extraigo el texto a mostrar en este momento.\n pos = pos + 1;\n var textoActual = texto.substring(0,pos);\n //capturo el div donde se pone el texto\n var t = document.getElementById(miDiv);\n t.textContent = textoActual;\n //controla la cantidad de veces que se llama a la funcion 'animarTexto'\n if (pos <= texto.length){\n //llama varias veces a la función 'animarTexto'\n setTimeout(animarTexto1,vel);\n }\n if(pos == texto.length - 1) {\n \t\tiluminar(\"#text2\",0.0, 0.05);\n }\n}",
"function updateTitleUI(counterCurrentSong){\r\n const musicTrackList = musicData.map( musicList => musicList.musicTrack);\r\n musicOn.innerText = musicTrackList[counterCurrentSong];\r\n}",
"function artworkTitle(track) {\n $('#song-info-topbar-container').fadeOut('slow', function() {\n var titleSong;\n track.title.length > 45 ? titleSong = track.title.slice(0, 42) + '...' : titleSong = track.title\n var duration = formatTime(track);\n $('#artwork-url').attr('src', track.artwork_url || '/assets/jamlogo_sml.png');\n $('#song-title-topbar').text(titleSong);\n $('#artis-name-topbar').text(track.user.username);\n $('#duration-song-topbar').text('(' + duration + ')');\n\n $('#song-info-topbar-container').fadeIn('slow');\n });\n}",
"function updateInfo() {\n\tdocument.getElementById('mi_prelo1').style.display = \"none\";//Finaliza el preloader al ser reproducida la musica\n\tvar title_movil = 'title_movil'+guarda_id_album;\n title.textContent = song.title;\n artist.textContent = song.artist;\n document.getElementById(title_movil).innerHTML = song.title;\n nombre_pista=song.title;\n art.src = song.art;\n art.onload = function() {\n anima_datos();\n }\n}",
"function animtext(text, tofact) {\n ctbar.clearRect(0, 0, game.width, $(window).height());\n var ts = 70 + toplift / 2;\n ctbar.font = ts + \"pt Toona\";\n ctbar.fillStyle = \"#cc0000\";\n ctbar.lineWidth = 10;\n ctbar.strokeStyle = \"#ffcc00\";\n toplift += tofact;\n var textwidth = ctbar.measureText(text).width;\n ctbar.strokeText(text, game.width / 2 - textwidth / 2, $(window).height() / 3 - toplift);\n ctbar.fillText(text, game.width / 2 - textwidth / 2, $(window).height() / 3 - toplift);\n }",
"function displaySong(data){\n img.src ='/img/'+data[i].name +'.jpg';\n title.textContent = data[i].title;\n artist.textContent = data[i].artist\n music.src = '/music/'+data[i].name+'.mp3';\n}",
"function showSongDetail(){\n var currentSpotifyURI = \"spotify:artist:44gRHbEm4Uqa0ykW0rDTNk\";\n //hide textbarAlbums\n TweenMax.to(document.getElementById('helptext'), 1.5, { ease: Power2.easeInOut, x: 2000});\n\n //show vinyl\n TweenMax.to('.discAnimate', 0, {scale: 1});\n TweenMax.to('.discAnimate', 1.5, { ease: Power2.easeInOut, rotation: 20, x: -170 , scale: 1, delay: 1.4});\n TweenMax.to('.discAnimate', 1.3, { ease: Power3.easeInOut, rotation: 60, x: -380, delay: 2.9 });\n TweenMax.to('.discAnimate', 1.5, { ease: Power1.easeOut, rotation: 10, x: -75, scale: 1, delay: 5.1});\n TweenMax.to('.discAnimate', 1.85, { ease: Power4.easeInOut, rotation: 60, x: -380, delay: 6.7});\n\n canReveal = true;\n TweenMax.to(document.getElementById('aww-wrapper'), 2, { ease: Power2.easeInOut, opacity: 0});\n\n TweenMax.to('.discAnimate', 2.2, { ease: Power2.easeInOut, rotation: 0, x: 75, scale: 1, delay: 8.2});\n\n curPage = 'song';\n}",
"function createMarkupAlbum(data) {\n return (`\n <img class=\"album-image\" src=\"${data.images}\" alt=\"${data.name}\">\n <p class=\"album-title\">${data.name}</p>\n <p class=\"album-artist\">${data.artists}</p>\n <p class=\"album-counter\">${data.tracks.length} Músicas</p>\n `);\n}",
"function renderAlbumDetails(album) {\n var albumInfo = document.querySelector('.album-detail');\n albumInfo.innerHTML = \"\";\n\n var numberTrack = 0;\n var albumDetail = '<button class=\"close\">x</button><div class=\"modal-album-wrapper\"><div class=\"modal-album-image\"><p class=\"title\">' + album.name + '<span>' + album.artist + '</span></p><img src=\"' + album.image[3]['#text'] + '\"/></div>';\n albumDetail += '<div class=\"modal-tracks-album\">';\n for (var i = 0; i < album.tracks.track.length; i++) {\n albumDetail += '<p><span>' + (numberTrack += 1) + '</span><span>' + album.tracks.track[i].name + '</span><span>' + album.tracks.track[i].duration + '</span></p>';\n }\n albumDetail += '</div></div>';\n\n // pintar elems en #top-tracks\n albumInfo.innerHTML += albumDetail;\n albumInfo.classList.add('show');\n document.querySelector('.close').addEventListener('click', function() {\n albumInfo.classList.remove('show');\n });\n }",
"function showText(e) {\r\n const item = slide[e];\r\n info.textContent = item.text;\r\n }",
"function nextTrack() {\n\tif (bandera_habilita_eventos == 1) {\n\tdocument.getElementById('mi_prelo1').style.display = \"block\";\n\tif (bandera_loop == 0 && bandera_aleatorio == 1) {//Si esta activado solamente \"Aleatoriedad\"\n\t\tvar song_aleatorio = aleatorio(0,1000);\n\t\tcurrent_track = song_aleatorio;\n\t}else {\n\t\tcurrent_track++;\t\t\t\t\n\t}\n current_track = current_track % (songs.length);\n song = songs[current_track];\n audio.src = song.url;\n audio.play();\n \tupdateMetadata();\n \t$('.tooltipped').tooltip(\"close\");\n var captura_modal = 'modal'+guarda_id_album;//Formamos una cadena que sera el modal del album en reproduccion\n //Accedemos al album que se esta escuchando para cambiarle su estilo a la tupla que esta en reproduccion:\n\n\tvar yy = document.getElementById(''+captura_modal+'');\n\tyy.childNodes[3].childNodes[1].childNodes[3].childNodes[1].childNodes[3].childNodes[guarda_id_pista-1].style.color = '#fff';\n\tyy.childNodes[3].childNodes[1].childNodes[3].childNodes[1].childNodes[3].childNodes[guarda_id_pista-1].childNodes[1].innerHTML = guarda_id_pista;\n\n\tguarda_id_pista = current_track+1;\n\n\tguarda_pista_aux2 = yy.childNodes[3].childNodes[1].childNodes[3].childNodes[1].childNodes[3].childNodes[guarda_id_pista-1].childNodes[11].innerHTML;\n\tyy.childNodes[3].childNodes[1].childNodes[3].childNodes[1].childNodes[3].childNodes[guarda_id_pista-1].style.color = '#00acc1';\n\tyy.childNodes[3].childNodes[1].childNodes[3].childNodes[1].childNodes[3].childNodes[guarda_id_pista-1].childNodes[1].innerHTML = '<i class=\"material-icons\" style=\"font-size:25px;\">play_arrow</i>';\n \n audio.onloadeddata = function() {\n bandera_repro_pause = 1;\n $('#duracion_pista').text(convierte_duracion(audio.duration));\n slider.noUiSlider.updateOptions({\n range: {\n 'min': 0,\n 'max': audio.duration,\n }\n \t\t});\n $('#barra_pista').attr('max',audio.duration);\n updateInfo();\n }\n }\n}",
"mostrarTituloPais(title,content){\n $(title).fadeIn(1000, ()=>{\n $(title)[0].innerHTML = content\n $(title)[0].style.display = 'block'\n })\n }",
"function animateTxt(curSlide, action){\n\n if(action == 'in'){\n var i = 0;\n var animaDelay = 0;\n\n $('.slideN'+curSlide+':not([class*=clone])>.caption').css('display', 'block');\n\n $('.slideN'+curSlide+':not([class*=clone])>.caption>div').each(function( ) {\n if(Modernizr.csstransitions) { \n\n $(this).css('-webkit-animation-delay', animaDelay+'s');\n $(this).css('-moz-animation-delay', animaDelay+'s');\n $(this).css('-0-animation-delay', animaDelay+'s');\n $(this).css('-ms-animation-delay', animaDelay+'s');\n $(this).css('animation-delay-delay', animaDelay+'s');\n\n $(this).show().addClass('animated').addClass($(this).attr('data-animation'));\n\n }else{\n\n $('.slideN'+curSlide+':not([class*=clone])>.caption>div').hide();\n if (i == 0){timing = 0}else if(i == 1){timing = 300} else{ timing = 300 * i}\n $(this).delay(timing).fadeIn('fast');\n }\n i++;\n animaDelay = animaDelay+0.2;\n\n\n });\n\n }else{\n var j = 0;\n $('.slideN'+curSlide+':not([class*=clone])>.caption').css('display', 'none');\n\n $('.slideN'+curSlide+':not([class*=clone])>.caption>div').each(function( ) {\n if(Modernizr.csstransitions) { \n\n $(this).removeClass($(this).attr('data-animation')).removeClass('animated').hide();\n\n }else{\n $(this).hide();\n }\n j++;\n });\n }\n\n}",
"_animateText() {\n this.eventCounter++;\n this.scene.sound.play('bleep', { volume: 0.05, rate: 2.0, detune: -1200});\n this.text.setText(this.text.text + this.dialog[this.eventCounter - 1]);\n if (this.eventCounter === this.dialog.length) {\n this.done = true;\n this.prompt = this.scene.add.text(this.scene.cameras.main.midPoint.x + 80, this.scene.cameras.main.midPoint.y + 165, '[Space]', this.spaceConfig).setScale(0.2);\n this.timedEvent.remove();\n }\n }",
"function aktualisieren_1() {\n //nächstes Lied wird angezeigt\n lied1 = lieder.pop();\n headline1.innerHTML = lied1.name;\n karte1.style.backgroundImage = \"url('\" + lied1.album.images[1].url + \"')\";\n content1.innerHTML = lied1.artists[0].name + '<br>' + lied1.album.name;\n //hier gibt es sogar ein Audio-Sample\n audio1.src = lied1.preview_url;\n}",
"function setData() {\n tittle.innerText = songs[songsIndex];\n audio.src = `./audio/${songs[songsIndex]}.mp3`;\n cover.src = `./imgs/${songs[songsIndex]}.jpg`;\n}",
"playSong() { \n \n // DOM elements to display/play your songs.json info/audio file\n \n this.albumDiv.style.cssText = 'display: display';\n \n this.musicInfo.style.cssText = 'display: display';\n \n this.musicInfo.innerHTML = `<p>${event.target.title}<br>\n ${event.target.artist}<br>\n ${event.target.album}<br>\n </p>`;\n\n this.sound.src = `songs/${event.target.title}.mp3`;\n \n this.sound.play();\n \n this.albumDivImg.src = `images/albumArt/${event.target.album}.jpg`;\n \n \n \n }",
"function aktualisieren_2() {\n lied2 = lieder.pop();\n headline2.innerHTML = lied2.name;\n karte2.style.backgroundImage = \"url('\" + lied2.album.images[1].url + \"')\";\n content2.innerHTML = lied2.artists[0].name + '<br>' + lied2.album.name;\n audio2.src = lied2.preview_url;\n}",
"function animate_string(target) \n{\n var element = document.getElementById('target');\n var textNode = element.childNodes[0]; // assuming no other children\n var text = textNode.data;\n\nsetInterval(function () {\n text = text[text.length - 1] + text.substring(0, text.length - 1);\n textNode.data = text;\n}, 100);\n}",
"function showinfos() {\n ctbar.clearRect(0, 0, game.width, 100);\n\n /* draw the headbar containing points, levelname, lives*/\n if (!gamestate.is(\"beganimation\") && !gamestate.is(\"initzoom\")) {\n for (var i = 0; i < game.lives; i++) {\n ctbar.font = \"25pt Toona\";\n ctbar.fillStyle = \"#cc0000\";\n ctbar.lineWidth = 5;\n ctbar.strokeStyle = \"#ffcc00\";\n ctbar.textAlign = \"left\";\n ctbar.strokeText(game.points, 11, 30);\n ctbar.fillText(game.points, 10, 30);\n var textwidth = ctbar.measureText(game.levelname).width;\n ctbar.strokeText(game.levelname, game.width / 2 - textwidth / 2, 30);\n ctbar.fillText(game.levelname, game.width / 2 - textwidth / 2, 30);\n var heartbeat = Math.floor(game.frame % 5);\n ctbar.drawImage(Resources.get(img), 0, heart.v, heart.w, heart.h, game.width - (i + 1) * 40 + heartbeat / 2, -5, 40 - heartbeat, 50);\n }\n }\n /* call textanimation for levelbeginn, gameover, gamewon */\n if (gamestate.is(\"beganimation\")) {\n animtext(game.levelname, 1.5);\n if (toplift > $(window).height() / 3 + 70) {\n gamestate.step();\n toplift = 0;\n }\n }\n\n if (gamestate.is(\"gameover\")) {\n animtext(\"GAME OVER\", 0, \"\");\n }\n if (gamestate.is(\"gamewon\")) {\n animtext(\"Congratulations !!!\", 0);\n }\n\n /*draw the text animation\n * @ text [string]: text to be shown\n * @ tofact [integer]: altering of textpostion,zoom; 0 for static text\n */\n\n function animtext(text, tofact) {\n ctbar.clearRect(0, 0, game.width, $(window).height());\n var ts = 70 + toplift / 2;\n ctbar.font = ts + \"pt Toona\";\n ctbar.fillStyle = \"#cc0000\";\n ctbar.lineWidth = 10;\n ctbar.strokeStyle = \"#ffcc00\";\n toplift += tofact;\n var textwidth = ctbar.measureText(text).width;\n ctbar.strokeText(text, game.width / 2 - textwidth / 2, $(window).height() / 3 - toplift);\n ctbar.fillText(text, game.width / 2 - textwidth / 2, $(window).height() / 3 - toplift);\n }\n }",
"function setText(index) {\n var $text = document.querySelector('.animation-text-output');\n \n $text.classList.remove('slow-hide');\n $text.innerHTML = arrText[index];\n setTimeout(function() {\n $text.classList.add('slow-hide');\n }, changeDelay + 600);\n }",
"function openModalAlbum(musique){\n\tevent.target.style.color = \"white\";\n\tdocument.getElementById(\"fader\").style.display=\"block\";\n\tdocument.getElementById(\"popup_artiste\").innerHTML=\"\";\n\tlet popup_artiste = document.getElementById(\"popup_artiste\");\n\tlet div_info = document.createElement(\"div\");\n\tdiv_info.className = \"div_info\";\n\tdiv_info.innerHTML = \"<img src=\" + musique.img_album + \" style=width:400px>\" + \"<div id='nom_album'>\" + musique.nom_album + \"</div>\";\n\tdiv_info.style.fontSize = \"40px\";\n\tdiv_info.style.textAlign = \"center\";\n\tdiv_info.style.color = \"white\";\n\tdiv_info.style.width=\"380px\";\n\tdiv_info.style.marginLeft=\"auto\";\n\tdiv_info.style.marginRight=\"auto\";\n\tdiv_info.style.marginTop=\"100px\";\n\tdiv_info.style.marginBottom=\"100px\";\n\tpopup_artiste.appendChild(div_info);\n}",
"function setBubbleText(aes, dur, event) {\n\t\t\t\t\t// event == 'add' or 'remove'\n\t\t\t\t\taes.transition('addBubbleText')\n\t\t\t\t\t\t.duration(dur)\n\t\t\t\t\t\t.style('font-size', event === 'add' ? '10px' : '0px')\n\t\t\t\t\t\t.style('fill', '#333');\n\t\t\t\t}",
"function displayText() {\n\t$('#caption').html('');\n\tfor (var i = 0; i < words[sentenceCount].length; i++) {\n\t\t$('#caption').append('<li>'+ words[sentenceCount][i] +'</li>');\n\t\t$('#caption').css('opacity', 1);\n\t\telementCount++;\n\t}\n}",
"sayAnim (data) {\n // event called by call to this.say()\n\n var key = data.sprite;\n var animName = data.animation;\n var kill = data.kill ? data.kill: false;\n var hide = data.hide ? data.hide: false;\n var text = data.say;\n var color = data.color;\n var sprite;\n var loop = this.spritesJSON[key].animations[animName].loop;\n\n sprite = this.getSprite(key);\n this.showSprite(sprite, true);\n this.say(text, key, color);\n\n sprite.events.onAnimationComplete.addOnce(function () {\n hide ? this.showSprite(sprite, false):null;\n }, this);\n\n sprite.animations.play(animName, null, loop, kill);\n }",
"function displayAlbum1(data){\n // Set the album image\n var img= \"<img alt=\" +\"bicep \" +\"album \" + \"cover\" + \" id=\" + \"album1\" + \" src=\" +data.images[0].url + \" />\";\n $(\"#album1_image\").append(img);\n var albumTracks = data.tracks.items;\n for(var i=0; i<albumTracks.length; i++){\n var track = albumTracks[i].name;\n var href = albumTracks[i].external_urls.spotify;\n // Set the album tracks with link to spotify\n $(\"#album1_tracks\").append(\"<span>\" + (i+1) + \". \" + \"<a\" + \" target=\" + \"_blank\" + \"rel=\" +\"noreferrer\" + \" href=\" + href +\">\" + track + \"</a></span><br>\");\n }\n // Set the album information\n $(\"#album1_info\").append(\"<span>Name: \" + data.name + \"</span><br>\");\n $(\"#album1_info\").append(\"<span>Release Date: \" + data.release_date + \"</span><br>\");\n $(\"#album1_info\").append(\"<span>Label: \" + data.label + \"</span><br>\");\n $(\"#album1_info\").append(\"<span>Track Count: \" + data.total_tracks + \"</span><br>\");\n}",
"get caption () {\n const { image, index } = this.state;\n return (\n <View style={{ bottom: 0, height: 40, backgroundColor: 'rgba(98, 20, 36, 0.7)', width: '100%', position: 'absolute', justifyContent: 'center' }}>\n <Text style={{ textAlign: 'center', color: 'white', fontSize: 15, fontStyle: 'italic' }}>{ (image[index] && image[index].caption) || '' } </Text>\n </View>\n );\n }",
"function updateText() {\n var nameString = data.getName();\n var charArray;\n\n // Get the initials via regex and format to string\n charArray = nameString.match(/\\b(\\w)/g);\n\n nameString = \"\";\n\n if (charArray != null) {\n for (var i = 0; i < charArray.length; i++) {\n nameString += charArray[i] + \". \";\n }\n }\n\n textObj.text(nameString);\n\n // Adjust text position based on string length\n textObj.x(position.x - nameString.length * 2);\n textObj.y(position.y - 5);\n\n layer.draw();\n }",
"function showSongInfo(songInfo) {\n result.style.display = 'block';\n result.innerHTML = ` ${songInfo.data.map(song => `<p class=\"author lead song-result\"><strong class=\"song-title\">${song.title}</strong> Album by <span class=\"song-artist\">${song.artist.name}</span> <button song-data=\"${song.id}\" song-data-title=\"${song.title}\" song-data-artist=\"${song.artist.name}\" class=\"btn btn-success get-lyrics-button\">Get Lyrics</button></p>`).join('')}`;\n}",
"function showViewTextAnimated(text) {\n getViewForViewId(activeView).fadeOut(0, null);\n if (text.length === 0) {\n getViewForViewId(activeView).fadeIn(0, null);\n } else {\n let word = text[0];\n $(\"#text_animation\").html(word);\n viewTextAnimated.fadeIn(2000, function() {\n viewTextAnimated.fadeOut(4000, function() {\n showViewTextAnimated(text.slice(1, text.length));\n });\n });\n }\n}"
]
| [
"0.62413317",
"0.6238365",
"0.6200398",
"0.6193867",
"0.6043208",
"0.59675694",
"0.5925094",
"0.5878785",
"0.580754",
"0.5806127",
"0.5804636",
"0.5775848",
"0.57653916",
"0.57418805",
"0.5720484",
"0.5665257",
"0.5664565",
"0.5657824",
"0.5645497",
"0.5637493",
"0.56206185",
"0.5609065",
"0.56017536",
"0.5580715",
"0.5563404",
"0.5555186",
"0.55509883",
"0.55443966",
"0.5537176",
"0.5534083"
]
| 0.6569618 | 0 |
Check that password length is at least 6 | function validatePassword(password) {
if (password.length < 6) {
return false;
}
return true;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function isAcceptablePassword(password) {\r\n \r\n if (password.length <= 6) {\r\n return false;\r\n } else return true;\r\n\r\n}",
"function validPassword(password) {\n\treturn password.length >= 8;\n}",
"function checkPasswordLength(inPassword) {\n\treturn (inPassword.val().length >= 5);\n}",
"function check_password(value) {\n\t\tif (value.length < 8) return 'Must be 8 or more characters';\n\t}",
"function validatePassword(password) {\n var re = /^(?=.{6,})/;\n return re.test(password);\n}",
"validatePassword (value) {\n return value && value.length >= 8\n }",
"function validatePasswordLength(password) {\r\n return validator.isLength(password,8);\r\n}",
"function passwordLongEnough (password){\n\tif(password.length > 5){\n\t\treturn true\n\t}\n\telse return false;\n}",
"function validatePassword(password) {\r\n var re = /^(?=.{6,})/;\r\n return re.test(password);\r\n }",
"function isValidPassword(password) {\n if (password.length >= 8) {\n return true;\n }\n return false;\n}",
"function checkLength() {\n return $password.val().length > 8;\n}",
"function isPasswordValid(){\r\n\treturn $password.val().length >8;\r\n}",
"function isPassword(password) {\n // A password must be a string of at least 6 characters.\n return typeof password === 'string' && password.length >= 6;\n}",
"passwordValidation(e) {\n let password = e.target.value.length;\n if(password < 8) {\n return false;\n }\n return true;\n }",
"function is_valid_pass(pass) {\n if (pass == null || pass.length < 7) {\n errorMessage = \"Please enter longer password.\";\n return false;\n }\n return true;\n}",
"function passwordIsValid () {\n if($password.val().length > 8) {\n return true;\n } else {\n return false;\n }\n}",
"function pwLongEnough(password){\n\tif(password.length >= 8){\n\t\treturn true;\n\t}\n\treturn false;\n}",
"function validatepassword1long() {\r\n if(password1.val().length > 20) {\r\n passwordErrorMsg.text(\"Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.\");\r\n }\r\n }",
"function validatepassword1() {\r\n if(password1.val().length < 6) {\r\n passwordErrorMsg.text(\"Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.\");\r\n }\r\n }",
"function isValidPassword(str){\n return str.length >8 && !str.includes('password')\n}",
"function isValidPassword(input) {\n var lengthIsGood = input.length == 6;\n var hasAtLeastOneLetter;\n var hasAtLeastOneNumber;\n var hasLowerCaseLetter;\n var hasUpperCaseLetter;\n var alphaNumeric;\n\n return lengthIsGood && hasAtLeastOneLetter && hasAtLeastOneNumber && hasLowerCaseLetter&& hasUpperCaseLetter && alphaNumeric;\n}",
"function passwordCheck(password)\r\n{ \r\n if ((password.length <4) || (password.length > 10))\r\n { \r\n return false;\r\n }\r\n else\r\n {\r\n return true;\r\n }\r\n}",
"function validatePassword(password){\n var re = /(?=.*\\d)(?=.*[A-z]).{6,20}/;\n return re.test(password);\n }",
"checkPassIsValid() {\n if (this.state.Password.length < 6)\n this.setState({ ValidPass: false });\n else this.setState({ ValidPass: true });\n }",
"function valid_pswd(pswd){\n var div_pswd=document.getElementById(\"div_pswd\")\n if(pswd.length < 6){\n var p=document.createElement(\"p\")\n p.textContent=\"*****Password should have Min 6 Characters******\"\n div_pswd.appendChild(p)\n return 0\n }\n}",
"function validatePasswordLength(password, requirementEl) {\n var length = password !== null ? password.length : 0;\n var min = requirementEl.data('min-password-length');\n var max = requirementEl.data('max-password-length');\n return (!min || length >= min) && (!max || length <= max);\n }",
"function validate_password_length()\r\n{\r\n\tvar newPassword = document.forms.frmAddRecord.d_password.value; \r\n var newPasswordLen = newPassword.length; \r\n\r\n if( newPasswordLen < 7 )\r\n {\r\n alert(\"Invalid current password - minimum length is 7 characters \");\r\n $(\"input[name=d_password].inputField\").val(\"\");\r\n return false;\r\n }\r\n \r\n return true;\r\n}",
"function isValidPassword (password) {\n if (password.length >= 8 && !password.includes('password')) {\n return true\n } else {\n return false \n }\n }",
"function checkLength(passwordLength){\n if (passwordLength < 8){\n alert(\"Password must be 8 characters or greater\");\n return false;\n }\n else if (passwordLength > 128){\n alert(\"Password cannot be longer than 128 characters\");\n return false;\n }\n return true;\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;}"
]
| [
"0.8590005",
"0.8349175",
"0.82887477",
"0.82519",
"0.82242614",
"0.81997997",
"0.8102767",
"0.8091865",
"0.808067",
"0.80691314",
"0.80527306",
"0.79939777",
"0.794299",
"0.78595775",
"0.7837629",
"0.78310204",
"0.7763244",
"0.77145284",
"0.7706954",
"0.77009344",
"0.7665965",
"0.76635957",
"0.75901407",
"0.75381607",
"0.74556273",
"0.742444",
"0.74140507",
"0.73922837",
"0.73725754",
"0.73718643"
]
| 0.83508205 | 1 |
Check that date is valid (DDMMYYYY) and not in the past | function validateDate(date) {
const tokens = date.split('-');
if (tokens.length != 3) {
return false;
}
const rightDate = tokens[1] + '-' + tokens[0] + '-' + tokens[2];
// Check if date is valid
let newDate;
const timestamp = Date.parse(rightDate);
if (isNaN(timestamp) == false) {
newDate = new Date(timestamp);
} else {
return false;
}
// Check if date is in the past
if (newDate > new Date()) {
return false;
}
return true;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function dateValidation(date) {\n const isValid = moment(date).isValid();\n if(!isValid) return false;\n const now = moment();\n return moment(date).isBefore(now) ? true : false;\n}",
"dateIsValid () {\n const dateValid = new Date(this.date).getDate() <= new Date().getDate();\n return dateValid;\n }",
"function validDates(date){\n return new Date(date) > new Date();\n}",
"function checkForValidDate (date) {\n var checkoutDate = moment(date, 'MM-DD-YYYY').format('YYYY-MM-DD');\n var cutoffDate = '2020-06-01';\n return moment(checkoutDate).isBefore(cutoffDate);\n}",
"function checkLegalDate(date) {\n\tvar day = parseInt(date.day);\n\tvar year = parseInt(date.year);\n\n\treturn (day > 0 && day <= 31) && year > 0;\n}",
"function checkDatePast(inputDate) {\n var today = new Date();\n var dd = String(today.getDate()).padStart(2, '0');\n var mm = String(today.getMonth() + 1).padStart(2, '0');\n var yyyy = today.getFullYear();\n\n if (inputDate[0] < yyyy) {\n return true;\n } else if (inputDate[0] == yyyy) {\n if (inputDate[1] < mm) {\n return true;\n } else if (inputDate[1] == mm) {\n if (inputDate[2] <= dd) return true;\n else return false;\n } else {\n return false;\n }\n } else {\n return false;\n }\n}",
"function check_past_date(date) {\n var d = new Date();\n var current_year = d.getFullYear();\n var current_month = d.getMonth() + 1;\n var current_day = d.getDate();\n\n if (current_year > parseInt(date.substr(0,4)))\n return true;\n\n if (current_year == parseInt(date.substr(0,4))) {\n\n if (current_month > parseInt(date.substr(5,2)))\n return true;\n\n if (current_month == parseInt(date.substr(5,2))) {\n\n if (current_day > parseInt(date.substr(8,2))) {\n return true;\n }\n }\n }\n return false;\n}",
"validDate(current) {\n const yesterday = Datetime.moment(\"20190301\");\n return current.isAfter(yesterday);\n }",
"function dateValidation(date){ \n var today =new Date();\n var inputDate = new Date(date.value);\n if (date.value == \"\" ){\n \talert(\"Enter the date\");\n \tdate.focus();\n\t\t\t\t\tdate.select();\n return false;\n } else if (inputDate < today) {\n \talert(\"date cant be in the past\");\n \t\tdate.focus();\n\t\t\t\t\tdate.select();\n return false;\n } else {\n return true;\n }\n }",
"isPastDate(year, month, day) {\n const currentDate = new Date();\n const currentYear = currentDate.getFullYear();\n const currentMonth = currentDate.getMonth();\n const currentDay = currentDate.getDate();\n\n if (year < currentYear) {\n return false;\n }\n\n if (year <= currentYear && month < currentMonth) {\n return false;\n }\n\n if (year <= currentYear && month <= currentMonth && day < currentDay) {\n return false;\n }\n\n return true;\n }",
"function isValidDate(date){\n\treturn !/[0-9]{4}[-]{1}[0-9]{2}[-]{1}[0-9]{2}/.test(date);\n}",
"function validateDate(date) {\n\t\tif (date.length < 8) {\n\t\t\treturn true;\n\t\t}\n\t\tlet expiredate = moment(date, momentJsFormats['mm/dd/yyyy']);\n\t\treturn expiredate.isValid();\n\t}",
"dateValid() {\n const { date } = this.state;\n var dateParts = (!date) ? [] : date.split(\"-\");\n var validator = { isValid: false, text: \"Please fill out date\" };\n if (dateParts.length===3) {\n var year = parseInt(dateParts[0]);\n var month = parseInt(dateParts[1]);\n var day = parseInt(dateParts[2]);\n if(year<=currentYear) {\n var isCurrentYear = (year===currentYear);\n var isMonthValid = this.checkMonth(isCurrentYear,month);\n if(isMonthValid===true) {\n var isCurrentMonth = (isCurrentYear===true && month===currentMonth);\n var isDayValid = this.checkDay(isCurrentMonth,month,day);\n if(isDayValid===true) {\n validator = { isValid: true };\n }\n else {\n validator.text = (day<=months[month-1].days) ? 'Specified day is in the future' : `${months[month-1].name} only has ${months[month-1].days} days`;\n }\n }\n else {\n validator.text = `Specified month ${month<13 ? 'is in the future' : 'does not exist'}`;\n }\n }\n else {\n validator.text = \"Specified year is in the future\";\n }\n }\n return validator;\n }",
"function isPastDate(date) {\n var now = getToday();\n return date < now;\n }",
"function isValid(date){\n let check = new Date(date)\n if (!check.getTime()||!check.toUTCString()){\n return false;\n }else{\n return true;\n }\n}",
"function validDate(date) {\n if (!checkDateFormat(date)) return false;\n const today = formatDate(new Date());\n const todayYear = Number(today.substring(0, 4));\n const todayMonth = Number(today.substring(5, 7));\n const todayDay = Number(today.substring(8, 10));\n const dateYear = Number(date.substring(0, 4));\n const dateMonth = Number(date.substring(5, 7));\n const dateDay = Number(date.substring(8, 10));\n if (dateYear < todayYear) return false;\n if (dateMonth < todayMonth) return false;\n if (dateMonth === todayMonth) {\n return dateDay >= todayDay;\n }\n return true;\n}",
"function checkDate(date) {\n var yMin=1850; \n var yMax=2500; \n var separator=\"/\";\n var d=(date.substring(0,2));\n var m=(date.substring(3,5));\n var y=(date.substring(6));\n var ok=1;\n\n if ( ((isNaN(d))||(d<1)||(d>31)) && (ok==1) ) {\n console.error(\"Invalid day\"); ok=0;\n }\n if ( ((isNaN(m))||(m<1)||(m>12)) && (ok==1) ) {\n console.error(\"Invalid month.\"); ok=0;\n }\n if ( ((isNaN(y))||(y<yMin)||(y>yMax)) && (ok==1) ) {\n console.error(\"Invalid year\"); ok=0;\n }\n if ( ((date.substring(2,3)!=separator)||(date.substring(5,6)!=separator)) && (ok==1) ) {\n console.error(\"Invalid \"+separator); ok=0;\n }\n if (ok==1) {\n var date2=new Date(y,m-1,d);\n d2=date2.getDate();\n m2=date2.getMonth()+1;\n y2=date2.getYear();\n if (y2<=100) {y2=1900+y2}\n if ( (d!=d2)||(m!=m2)||(y!=y2) ) {\n console.error(\"Date \"+date+\" doesn't exist\");\n ok=0;\n }\n ok=date2;\n }\n return ok;\n}",
"function isValid(year,month,date){if(date < 1){return false;}if(month === 1 && date > 28){return date === 29 && (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0);}if(month === 3 || month === 5 || month === 8 || month === 10){return date < 31;}return true;}",
"function isTaskDateValid() {\n let inputDate = document.getElementById(\"taskDate\");\n inputDate.style.backgroundColor = \"\";\n\n if (inputDate.value == \"\") {\n inputDate.style.backgroundColor = \"pink\";\n alert(\"Please add date\");\n return false;\n }\n\n let presentDate = new Date();\n let inputDateCheck = new Date(inputDate.value);\n //reduce the digit to only ten wich give you only the date whithout time\n presentDate = presentDate.toISOString().slice(0, 10);\n inputDateCheck = inputDateCheck.toISOString().slice(0, 10);\n\n if (inputDateCheck < presentDate) {\n inputDate.style.backgroundColor = \"pink\";\n alert(\"Due date has passed\");\n return false;\n }\n return true;\n}",
"function checkDate(date) {\n return /\\d{1,4}-\\d{2}-\\d{2}/.test(date);\n}",
"function isDueDateValid(duedate) {\n var result = true;\n var now = new Date().getTime();\n if (duedate < now) {\n result = false;\n $log.error('ReceivableCtrl: -Invalid due date=\\'' + duedate + '\\', now=\\'' + now + '\\'.');\n }\n return result;\n }",
"function checkDate(date) {\n if (date.length == 0) {\n return true;\n }\n if (date.length != 4) {\n return false;\n }\n // This weird if structure accounts for NaN\n var year = Number(date);\n if (year < 1984 || year > 2012) {\n return false;\n }\n return true;\n}",
"function dataIsValid(date){\n if(date == null)\n return false;\n if (!date.match(/^\\d{4}-\\d{2}-\\d{2}$/))\n return false;\n\n var date_list = date.split(\"-\");\n year = date_list[0];\n month = date_list[1];\n day= date_list[2];\n\n if (month < 1 || month > 12 || day < 1 || day > 31)\n return false;\n else if ((month == 4 || month == 6 || month == 9 || month == 11)) {\n if (day == 31)\n return false;\n }\n else if (month == 2)\n {\n var leap_year = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));\n if (day > 29 || (day ==29 && !leap_year))\n return false;\n }\n return true;\n}",
"function isPastDate(txtDate){\n\t\t \n var dt1 = parseInt(txtDate.substring(0,2));\n var mon1 = parseInt(txtDate.substring(3,5));\n var yr1 = parseInt(txtDate.substring(6,10));\n var selectedDate = new Date(yr1, mon1-1, dt1);\n var now = new Date();\n \n if(now < selectedDate){\n return false;\n }\n return true;\n }",
"function validateDate(date) {\n var date_regex = /^(0[1-9]|1[0-2])\\/(0[1-9]|1\\d|2\\d|3[01])\\/(2)\\d{3}$/;\n if (date === \"DOES NOT EXPIRE\") {\n return true;\n }\n return date_regex.test(date);\n}",
"function validateDate(date) {\n if (moment(date, \"MM/DD/YYYY\", true).isValid()) {\n return true;\n } else {\n return false;\n }\n}",
"function isDateValid(date) {\n return date instanceof Date && !isNaN(date.valueOf());\n}",
"validateDate() {\n let value = this.date.value;\n let min = dayjs(this.date.min).startOf('day');\n let max = dayjs();\n let errorMessage = null;\n\n if (!this.inThisMoment) {\n if (!isEmpty(value)) {\n let date = dayjs(value, 'YYYY-MM-DD').startOf('day');\n if (date.isSameOrAfter(min)) {\n if (date.isSameOrBefore(max)) {\n this.date.isOk();\n //Se valida la hora\n if (this.setTime) {\n this.validateTime();\n }\n\n return true;\n } else {\n errorMessage = \"No se pueden agregar gastos en el futuro.\";\n }\n } else {\n errorMessage = \"La fecha debe ser mayor a la fecha del lote\";\n }\n } else {\n errorMessage = \"Se debe elegir una fecha valida\";\n }\n } else {\n return true;\n }\n\n this.date.setError(errorMessage);\n return false;\n }",
"function dateValidate(dateValue){\n\tvar ermsg = LocalizedMessage(\"date_error\"); \n\tvar mindate = new Date(1900,0,1);\n\tvar maxdate = new Date(2079,6,6);\n\tif(dateValue !== \"\"){\n\t\tdatearr = dateValue.split(\"-\");\n\t\tif(datearr.length!=3 || datearr[0]==\"\" || datearr[1]==\"\" || datearr[2]==\"\" || parseInt(datearr[0],10)!=datearr[0] || parseInt(datearr[1],10)!=datearr[1] || parseInt(datearr[2],10)!=datearr[2]){\n\t\t\talert(ermsg);\n\t\t\treturn false;\n\t\t}\n\t\tvar entdate = new Date(parseInt(datearr[0],10),parseInt(datearr[1],10)-1,parseInt(datearr[2],10));\n\t\tif(parseInt(datearr[0],10)>2079 || parseInt(datearr[0],10)<1900 || entdate<mindate || entdate>maxdate){\n\t\t\talert(ermsg);\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}",
"function isDateValid(theField) {\n\tvar err;\n\terr=false;\n\tstrDate = theField.value;\n\tif(strDate==\"\") {\n\t\treturn true;\n\t}\n\tlength1 = strDate.length;\n\tif((length1>10)||(length1<=9)){\n\t\terr=true;\n\t}else{\n\t\tvar findex,lindex,month,day,year,strDatelength,maxDays,lyear;\n\t\tfindex=strDate.indexOf(\"/\");\n\t\tlindex=strDate.lastIndexOf(\"/\");\n\t\tstrDatelength=length1;\n\t\tif((lindex==-1)||(lindex==findex)){\n\t\t\terr=true;\n\t\t}\n\t\tday=strDate.substring(0,findex);\n\t\tmonth=strDate.substring((findex+1),lindex);\n\t\tyear=strDate.substring((lindex+1),strDatelength);\n\t\tmaxDays=31;\n\t\tlyear=false;\n\t\tif(((year%4==0)&&(year%100!=0))||(year%400==0)){\n\t\t\tif(month==2){\n\t\t\t\tmaxDays=29\n\t\t\t\tlyear=true\n\t\t\t}\n\t\t}\n\t\tif((month==4)||(month==6)||(month==9)||(month==11)){\n\t\t\tmaxDays=30\n\t\t}\n\t\tif((month==2)&&(lyear==false)){\n\t\t\tmaxDays=28\n\t\t}\n\t\tif(isNaN(day)||isNaN(year)||isNaN(month)){\n\t\t\terr=true\n\t\t}\n\t\tif((month>12)||(month<=0)){\n\t\t\terr=true;\n\t\t}else if((day>maxDays)||(day<=0)){\n\t\t\terr=true;\n\t\t}else if ((year > 9999) || (year<=0)){\n\t\t\terr=true;\n\t\t}\n\t\telse if ((year.length < 4) || (year.length > 4)) {\n\t\t\terr = true;\n\t\t}\n\t}\n\tif(err){\n\t\treturn false;\n\t}\n\treturn true;\n}"
]
| [
"0.7739628",
"0.7701293",
"0.7650413",
"0.75839156",
"0.7496991",
"0.7480844",
"0.7463756",
"0.7398433",
"0.7341339",
"0.73073363",
"0.7287363",
"0.72549695",
"0.71467984",
"0.7136404",
"0.7128665",
"0.71243703",
"0.7121864",
"0.71130705",
"0.71064436",
"0.7106069",
"0.7057407",
"0.70515674",
"0.70494115",
"0.70411485",
"0.69265497",
"0.69260406",
"0.6916583",
"0.6911674",
"0.6910277",
"0.68901485"
]
| 0.7891535 | 0 |
Check that amount is between 0 and 10000000 | function validateAmount(amount) {
if (amount <= 0 || amount >= 10000000) {
return false;
}
return true;
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function checkAmount(amount) {\n return $.isNumeric(amount) && amount > 0;\n }",
"function checkBet (o, n, min, max) { \n if ( o.val() > max || o.val() < min ) {\n o.addClass( \"ui-state-error\" );\n updateTips( \"You can only bet with numeric money. Your betting power also cannot exceed the amount in your wallet, nor be negative.\" );\n return false;\n } else {\n return true;\n }\n }",
"ImproperCheck(value, amount){\n\t\n\t\n\treturn isNaN(value) ? amount : value ;\n\t}",
"function valid_limit(value) {\n if (value < 0) return false;\n return true;\n}",
"function checkInterger(x) {\n return (Math.abs(100 - x) <= 20) || (Math.abs(400 - x) <= 20);\n}",
"function verifyAmount(){\n // knowing the txid, get the balances from data\n console.log(\"txInfo.asset\", txInfo.asset)\n if (txInfo.asset === \"network\") {\n // TODO distinguish by Peercoin or BCH\n console.log(\"Peercoin was selected\")\n return txInfo.amount > 0.00000001\n }\n else if (cardCreate) {\n // If you are creating cards, the amount is okay\n return true\n }\n else{\n let amnt = 0\n data.forEach(v => {\n if (v.txid === txInfo.asset) {\n return txInfo.amount <= v.amount\n }\n }) \n }\n}",
"validateAmount() {\n let value = this.amount.value;\n let min = this.amount.min;\n let max = this.amount.max;\n let errorMessage = null;\n\n if (value) {\n if (value >= min) {\n if (value < max) {\n this.amount.isOk();\n return true;\n } else {\n errorMessage = `El importe debe ser menor que ` + window.formatCurrency(max, 0);\n }\n } else {\n errorMessage = \"El importe minimo debe ser de \" + window.formatCurrency(min, 0);\n }\n } else {\n errorMessage = \"Este campo es obligatorio.\"\n }\n\n this.amount.setError(errorMessage);\n return false;\n }",
"async function checkAmount(amount) {\n //If the amount is invalid...\n if(!amount){\n return false\n }\n //Else, return true.\n return true;\n}",
"function validForNumberAccumulator(value) {\n\treturn -1000000000000000 <= value || value <= 1000000000000000 || valueStr.indexOf('e') !== -1;\n}",
"validate(value){\n if (!isNaN(parseFloat(value)) && isFinite(value)){ //is numeric\n if (value >= 0 && value <= this.props.account.balanceUsd){\n return true;\n }\n }\n return false;\n }",
"function isAmount(value) {\n return new RegExp(regExpAmount, 'gi').test(value);\n}",
"function isAmountInRange(amount, min, max) {\n return amount >= min && amount <=max;\n}",
"function validateNumber() {\n // Check to be sure that the number is less than one billion.\n if (preDecimalNumbersArray.length > 16) {\n return false;\n } else if (postDecimal.length > 2) {\n return false;\n } else {\n return true;\n }\n }",
"function validaPeso(peso){\r\n if(peso >= 0 && peso < 1000){\r\n return true;\r\n } else{\r\n return false;\r\n }\r\n}",
"function threed(num) {\n if (num > 99 && num < 1000) { return true; }\n}",
"function checkAmount(element, event) {\n\tvar value = element.val();// .replace(/[e\\+\\-]/i, ' ');\n\tvalue = value.replace(/[e\\+\\-]/gi, '');\n\tvalue.replace(/^[0+]/g, '');\n\tvalue = parseInt(value, 10);\n\tvar theEvent = event || window.event;\n\tvar max = parseInt(element.attr(\"max\"), 10);\n\tvar regex = /^[1-9][0-9]*$/;\n\tif (!regex.test(value)) {\n\t\ttheEvent.returnValue = false;\n\t\tif (theEvent.preventDefault)\n\t\t\ttheEvent.preventDefault();\n\t}\n\tif (value < 1) {\n\t\tvalue = 1;\n\t}\n\tif (value > max) {\n\t\tvalue = max;\n\t}\n\telement.val(value);\n}",
"function isAmountValid(amount) {\n var result = true;\n if (amount <= 0) {\n result = false;\n $log.error('ReceivableCtrl: -Invalid amount: ' + amount + '.');\n }\n return result;\n }",
"function validateNumber(val, legalMin, legalMax) {\n return (!isNaN(val) && val >= legalMin && val <= legalMax);\n}",
"function controlNum(num){\n if(num <= 0 || isNaN(num) || num > 100){\n return false;\n }\n return true;\n}",
"function validateWholeDolalAmount(billerCorpAccounts_id , value) {\n\tvar programs = \"\";\n\tif(bp_account_lite_obj){\n\t\tif(bp_account_lite_obj.billerCorpAccounts && bp_account_lite_obj.billerCorpAccounts.length > 0){\n\t\t\tfor(var index in bp_account_lite_obj.billerCorpAccounts){\n\t\t\t\tif(billerCorpAccounts_id === bp_account_lite_obj.billerCorpAccounts[index].id){\n\t\t\t\t\tprograms = bp_account_lite_obj.billerCorpAccounts[index].programs;\t\n\t\t\t\t\tfor(var proIndex in programs){\n\t\t\t\t\t\tif(programs[proIndex].wholeDollar){\n\t\t\t\t\t\t\tif(value % 1 != 0){\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}",
"function isValidInput(numInput, originalAmountNum){\n\tif(numInput >= 1 && numInput <= originalAmountNum){\n\t\treturn true;\n\t}\n\treturn false;\n}",
"function validarNumero(x) {\n return (Math.abs(x - 100) <= 20) || (Math.abs(x - 500) <= 20);\n}",
"function between50And500(num) {\n if (num >= 50 && num <= 500) {\n return true\n }\n \n return false\n}",
"function lessThanOrEqualToZero(num) {\nvar num;\n if(num > 0){\n return false;\n }\n return true;\n}",
"function isBigEnough(value) {\n return value >= 10;\n}",
"function nearHundred(n)\n {\n if ((Math.abs(100 - n) <= 10) || (Math.abs(200 - n) <= 10)) {\n return true\n } else {\n return false\n }\n }",
"function isBigEnough(value) {\n return value >= 10;\n}",
"function controlNumDiff(num){\n if(num <= 0 || isNaN(num) || num > 50){\n return false;\n }\n return true;\n}",
"function verifyValue(value) {\n\tif (isNaN(value) || value<0) {\n\t\treturn 0;\n\t} else if (value>1000) {\n\t\treturn 1000;\n\t} return parseInt(value);\n}",
"function controlNumInt(num){\n if(num <= 0 || isNaN(num) || num > 80){\n return false;\n }\n return true;\n}"
]
| [
"0.7171745",
"0.6975108",
"0.6910955",
"0.6841685",
"0.67219603",
"0.6685663",
"0.6643425",
"0.6517834",
"0.65042984",
"0.6486624",
"0.64831585",
"0.64624715",
"0.64463305",
"0.6444857",
"0.64258564",
"0.63437414",
"0.63131064",
"0.62995416",
"0.62850255",
"0.627199",
"0.62644064",
"0.62528723",
"0.6242793",
"0.6226999",
"0.6217851",
"0.62126327",
"0.61991763",
"0.6181032",
"0.6180778",
"0.61796415"
]
| 0.8287717 | 0 |
Returns a promise that resolves to a token with the given length | function createToken(length) {
return crypto.randomBytesAsync(length || CRYPTO_LENGTH);
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"generateToken(length) {\n return (Math.random().toString(36)+'00000000000000000').slice(2, length + 2);\n }",
"function getToken(length) {\n var randomChars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n var result = ''\n for (var i = 0; i < length; i++) {\n result += randomChars.charAt(Math.floor(Math.random() * randomChars.length))\n }\n return result\n}",
"function makeToken(length) {\n var result = '';\n var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var charactersLength = characters.length;\n for ( var i = 0; i < length; i++ ) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}",
"function getRandomToken(tokenLength) {\n // E.g. 8 * 32 = 256 bits token\n var randomPool = new Uint8Array(tokenLength);\n crypto.getRandomValues(randomPool);\n var hex = '';\n for (var i = 0; i < randomPool.length; ++i) {\n hex += randomPool[i].toString(16);\n }\n return hex;\n}",
"function createToken() {\n return new Promise(function(resolve, reject) {\n FCMPlugin.getToken( function(token) {\n resolve(token);\n //alert(token);\n }, function(err){\n reject(err);\n }\n );\n });\n }",
"generateMnemonic(length) {\n return new Promise((resolve, reject) => {\n if (length && (length === 12 || length === 24)) {\n const phrase =\n length === 12 ? MnemonicTools.phrase12() : MnemonicTools.phrase24();\n this.phrase = phrase;\n this.generateVerification(phrase);\n resolve(phrase);\n } else {\n reject('Invalid length!');\n }\n });\n }",
"async function getToken(username) {\n\ttry {\n\t\tvar exp = new Date().getTime() + 180 * 1000;\n\t\t\n\t\tconst payload = new Buffer(JSON.stringify({ usr: username, exp: exp }))\n\t\t\t.toString('base64');\n\t\tconst plaintext = token_header + payload;\n\t\tconst signature = token_rsa.sign(plaintext, 'base64', 'base64');\n\t\tconst token = payload + '.' + signature;\n\t\t\n\t\treturn Promise.resolve(token);\n\t} catch (err) {\n\t\treturn Promise.reject('generation');\n\t}\n}",
"function generateToken() {\n crypto.randomBytes(48, (err, buffer) => {\n const token = buffer.toString('hex');\n })\n}",
"static getRandomToken(size = 32) {\n\t\treturn Crypto.randomBytes(size).toString('hex');\n\t}",
"makeToken(payload) {\n return new Promise((resolve, reject) => \n jwt.sign(\n payload,\n SECRET,\n (err, data) => err ? reject(err) : resolve(data)\n )\n );\n }",
"function getToken () {\n return new Promise(function (resolve, reject) {\n rp(TOWER_VARS.authOptions).then(function (response) {\n TOWER_VARS.token.value = response.token;\n TOWER_VARS.token.expires = response.expires;\n debug('getToken: ' + JSON.stringify(response));\n resolve(response);\n }).catch( function (err) {\n //console.log('Error occurred requesting token ' + err);\n reject(err);\n });\n });\n}",
"function generateToken(options) {\n // Create token variable\n let token;\n // Post request to URL to retrieve token\n request.post(options, (error, response, body) => {\n // Assign response body value\n token = body.access_token;\n });\n\n // Return Promise containing token\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve(token)\n }, 1000);\n });\n}",
"getToken() {\n return new Promise((resolve, reject) => {\n if (this.tokenInfo) {\n const now = new Date();\n const expire = new Date(this.tokenInfo.expires);\n if (now < expire) {\n resolve(this.tokenInfo.token);\n } else {\n this._setTokenInfo().then(() => {\n resolve(this.tokenInfo.token);\n });\n }\n } else {\n this._setTokenInfo().then(() => {\n resolve(this.tokenInfo.token);\n });\n }\n });\n }",
"getTokenP() {\n if (!_.isEmpty(this.token) && !this.isExpired()) {\n return lift(this.token, null);\n }\n return this.getTokenInternal()\n .then((token) => {\n return this.token = token;\n });\n }",
"static [getToken](): string {\n // JWT retrieval logic goes here.\n return '';\n }",
"function makeToken(payload) {\n // console.log('HIIII')\n return new Promise((resolve, reject) => {\n jwt.sign(\n payload,\n secret,\n (err, data) => err ? reject(err) : resolve(data)\n )\n });\n}",
"function generateToken(){\n counter +=1;\n if(counter>50000) counter = 0; //just not let it get to big\n return 10000 + counter;\n}",
"function createToken(password_digest) {\n let token = '';\n for(let i = 0; i < 60; i += 1) {\n if ((i + 1) % 3 === 0 ) {\n token += password_digest.charAt(i);\n }\n }\n return token;\n}",
"function getNewToken() {\n return crypto.randomBytes(24).toString('base64');\n}",
"function getUrlToken() {\n let l = window.location.href.replace(/.*\\?token=([a-zA-Z0-9]{24})$/, '$1')\n if (l.length === 24) {\n return l\n }\n return \"\"\n}",
"function getToken() {\n\n return Math.random().toString(36).substr( 2, 10 );\n}",
"function getToken() {\n\n return Math.random().toString(36).substr( 2, 10 );\n}",
"makeToken(payload) {\n\t\tconsole.log('SECRET', SECRET);\n\t\treturn new Promise((resolve, reject) =>\n\t\t\tjwt.sign(payload, SECRET, (err, data) => (err ? reject(err) : resolve(data)))\n\t\t);\n\t}",
"function tokenGenerate(user) {\n\tlet chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz\";\n\tlet string_length = 50;\n\tlet randomstring = '';\n\tfor (let i = 0; i < string_length; i++) {\n\t\tlet rnum = Math.floor(Math.random() * chars.length);\n\t\trandomstring += chars.substring(rnum, rnum + 1);\n\t}\n\t\n\treturn new Promise(function (resolve, reject) {\n\t\tToken.findOne({'token': randomstring}, function (err, token) {\n\t\t\tif (err) {\n\t\t\t\tconsole.log(err);\n\t\t\t\tres.send(err);\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tif (token == null) {\n\t\t\t\t\tlet new_token = new Token({\n\t\t\t\t\t\tuser: user,\n\t\t\t\t\t\ttoken: randomstring\n\t\t\t\t\t});\n\t\t\t\t\tnew_token.save(function (err, token) {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\t\t\t\t\t\t\tresolve(err);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// console.log(token.token);\n\t\t\t\t\t\t\tresolve(token.token);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\ttokenGenerate(user);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n}",
"function get_token (input, index) {\n let len = 0, type, value;\n for (let k in token_def) {\n\tconst regex = token_def[k];\n\tregex.lastIndex = index; // Match from specified index\n\tconst res = regex.exec(input);\n\t// New longest token\n\tif (res && res[0].length > len) {\n\t len = res[0].length;\n\t type = k;\n\t value = res[1];\n\t}\n }\n return {type, value, len};\n}",
"function decodificaToken(token){\n return new Promise((resolve,reject)=>{\n try{\n const payload = jwt.decode(token,SECRET, true);\n if(payload.exp <= moment().unix()){\n reject({\n status: 401,\n message: 'El token ha caducado'\n })\n\n }\n console.log(payload);\n resolve(payload.sub);\n\n }catch{\n reject({\n status: 500,\n message: 'El token no es valido'\n });\n }\n });\n}",
"async function generateCSRN(length){\n var salt = await crypto.randomBytes(length);\n return salt;\n }",
"async getToken() {\n const sessionId = await this.createSession(this.state.mySessionId);\n return await this.createToken(sessionId);\n }",
"async getToken() {\n const sessionId = await this.createSession(this.state.mySessionId);\n return await this.createToken(sessionId);\n }",
"async function _RT(_token, _tokens) {\n return new Promise(async (resolve, reject) =>{\n return resolve((await _token.getRealTokenAmount.call(_tokens)).toNumber());\n })\n}"
]
| [
"0.6873612",
"0.6640775",
"0.6544259",
"0.65362805",
"0.5980785",
"0.59255826",
"0.5916106",
"0.5823246",
"0.58219045",
"0.5796859",
"0.57472825",
"0.5737772",
"0.5723951",
"0.5617778",
"0.5592842",
"0.55838364",
"0.5582977",
"0.5581094",
"0.555345",
"0.55344516",
"0.5500022",
"0.5500022",
"0.5470803",
"0.53963715",
"0.53811336",
"0.53806996",
"0.53644955",
"0.53439045",
"0.53439045",
"0.53406304"
]
| 0.738494 | 0 |
Return a promise that resolves to the user queried by the email. | function getUser(email) {
console.log(db.getUser(email));
return db.getUser(email).then(result => {
console.log(result);
const user = result;
if (!user) return Promise.reject('User not found');
return Promise.resolve(user);
});
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"getUserByEmail(email) {\n console.assert(email);\n // TODO(madadam): Query userStore by email.\n // For now, iterate through all users in the UserStore (via Database).\n let filter = {\n type: 'User',\n };\n let queryProcessor = this.database.getQueryProcessor(Database.NAMESPACE.SYSTEM);\n console.assert(queryProcessor);\n return queryProcessor.queryItems({}, {}, filter)\n .then(items => {\n let user = _.find(items, { email });\n return user;\n });\n }",
"async getUserByEmail(email) {\r\n\t\tconst query = {\r\n\t\t\temail: email\r\n\t\t};\r\n\t\treturn User.findOne(query);\r\n\t}",
"getUserByEmail(email) {\n let thisUser = this;\n return new Promise((resolve, reject) => {\n thisUser.db.query(\"SELECT * FROM users WHERE email='\"+email+\"'\", (err, rows) => {\n if (rows.length > 0) {\n let user = rows[0];\n let actualUser = new User(thisUser.rclient, thisUser.db, thisUser.q, thisUser.passwordhash, thisUser.employeeRef);\n actualUser.email = email,\n actualUser.userlevel = user.user_level;\n thisUser.employeeRef.getEmployee(user.employee_id, true).then(resp => {\n thisUser.debug(\"Retrieved employee of user.\");\n actualUser.employee = resp[0];\n resolve(JSON.parse(JSON.stringify(actualUser)));\n });\n } else {\n resolve({});\n }\n });\n });\n }",
"static async fetchUserByEmail(email) {\n if (!email) {\n throw new BadRequestError(\"No email provided\");\n }\n\n const query = `SELECT * FROM users WHERE email = $1`;\n\n const result = await db.query(query, [email.toLowerCase()]);\n\n const user = result.rows[0];\n\n return user;\n }",
"static fetchUserByEmail(email, completion) {\n const text = `SELECT * FROM users WHERE email = '${email}'`;\n \n pool\n .query(text)\n .then(res => completion({ success: true, data: res.rows[0] }))\n .catch(err => completion({ success: false, data: err }));\n return null;\n }",
"function getUser(email /*string*/) {\n return new Promise((resolve, reject) => {\n const q = `SELECT users.*, roles.role \n FROM users \n LEFT JOIN roles\n ON users.roleid = roles.id\n WHERE users.email = '${email}' LIMIT 1`\n connection().query(q, (error, results, fields) => {\n if (error) {\n reject (error);\n }\n\n if (results) {\n resolve(results[0]);\n }\n else {\n resolve(false);\n }\n })\n })\n}",
"async emailUser(email){\n return User.findOne({where: {email}})\n }",
"getUserNameByEmail(email) {\n return new Promise(function (resolve, reject) {\n let sql = \"SELECT fname, lname FROM users WHERE email=?\";\n db.all(sql, [email], (err, rows) => {\n if (err) {\n reject(Error(\"Error:\" + err.message));\n }\n resolve({ fname: rows[0].fname, lname: rows[0].lname });\n });\n });\n }",
"async function getUserByEmail(email) {\n return await schemas.User.find({\n email: email\n });\n }",
"async function getUserByEmail(email){\n var sql = \"SELECT user_pk, user_username, user_fname, user_lname, user_email, user_hash, user_signup, user_username, user_last_signin, user_security_question, user_security_answer FROM users WHERE user_email=$1::text\";\n var params = [email]; \n var results = await pool.query(sql, params);\n return parseUserfromDB(results.rows[0]);\n }",
"async function getUserByEmail(email) {\n\ttry {\n\t\tconst result = await User\n\t\t\t.find({ email: email })\n\t\t\t.select({email: 1});\n\t\treturn result;\n\t} catch (error) {\n\t\tthrow error;\n\t}\n}",
"async function getUserFromEmail(email) {\n let query = `select * from ${USERS_DB} where email='${email}'`\n let result = await db.query(query)\n if (!result || !result.rows[0]) { return false }\n let user = await formatter.formatUser(result.rows[0])\n return user\n}",
"function userCheck(email) {\n return new Promise((resolve, reject) => {\n db.pool.query(\"SELECT * FROM users WHERE email = ?\", [email], (error, results, fields) => {\n if(error) throw error;\n\n if(results.length === 1) {\n resolve(results[0].id);\n } else {\n reject(\"User does not exist\");\n }\n });\n });\n}",
"getUser() {\n const token = new auth().getCachedToken();\n\n if (token != null) {\n let username = localStorage.getItem(\"username\");\n let uri = encodeURI(`${Api.apiUrl}Users/email?email=${username}`);\n return fetch(uri, { headers: new Headers({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer ' + token,\n })})\n .then((resp) => resp.json())\n .then(function(response) {\n return response;\n })\n .catch(function() {\n appInsights.trackPageView({name: `Failed to get user ${username}` });\n });\n }\n }",
"function findUserByEmail(emailAddress) {\n var defer = q.defer();\n UserModel.findOne({email:emailAddress}, function(err, foundUser) {\n if (err){\n defer.reject(err);\n }\n else {\n defer.resolve(foundUser);\n }\n });\n return defer.promise;\n }",
"async findUserByEmail(incomingEmail) {\n let user = null;\n try {\n GeneralUtils_1.default.printInitiateMessage(\"UserRepository.findUserByEmail\", \"Start\");\n user = await user_model_1.default.findOne({ where: { email: incomingEmail } });\n GeneralUtils_1.default.printInitiateMessage(\"UserRepository.findUserByEmail\", \"Result: \" + JSON.stringify(user));\n GeneralUtils_1.default.printInitiateMessage(\"UserRepository.findUserByEmail\", \"End\");\n }\n catch (error) {\n console.error(error);\n }\n return user;\n }",
"async getUser({ email }) {\n // Buscamos el email y de el sacamos todo el usuario.\n const [ user ] = await this.mongoDB.getAll(this.collection, { email });\n return user;\n }",
"async findUser () {\n\t\tthis.user = await this.data.users.getOneByQuery(\n\t\t\t{ searchableEmail: this.providerInfo.email.toLowerCase() },\n\t\t\t{ hint: Indexes.bySearchableEmail }\n\t\t);\n\t\tif (this.user) {\n\t\t\tthis.request.log(`Matched user ${this.user.id} by email`);\n\t\t\tif (this.user.get('isRegistered')) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (!this.okToCreateUser) {\n\t\t\tif (this.user) {\n\t\t\t\tthis.request.log('Unregistered user must create an account first');\n\t\t\t}\n\t\t\tthrow this.errorHandler.error('noIdentityMatch');\n\t\t}\n\t}",
"async getUserByEmailAddress(emailAddress) {\n return await this.users.getUserByEmailAddress(emailAddress);\n }",
"async findByEmail(req, res) {\n AuthService.findByEmail([req.body.email])\n .then((user) => {\n res.status(user.status).send({\n status: user.status,\n message: user.message,\n user: user.user.rows,\n });\n })\n .catch((err) => {\n res.status(400).send({\n status: 400,\n error: err.message,\n });\n });\n }",
"function getUserByEmail(email){\n return _.find(_users, (o) => { return o.email === email })\n}",
"async checkUser() {\n return this.connection.query('SELECT * FROM users WHERE email = ?', [this.email]);\n }",
"static async getByEmail(email) {\n try {\n const query = `SELECT * FROM Users WHERE email = '${email}' `;\n\n const response = await pool.query(query);\n return response;\n } catch (error) {\n return error;\n }\n }",
"async function getUserByEmail(email){\n try{\n let users = await Users.findOne({email:email})\n return users\n }catch(err){\n return err\n }\n}",
"async function getByEmail(email) {\n //connect to the collection \n const collection = await dbService.getCollection('user')\n try {\n //find a user with the spefific email\n const user = await collection.findOne({ email })\n return user\n } catch (err) {\n throw err;\n }\n}",
"function findUser(credential) {\n return new Promise((resolve, reject) => {\n // Call to get user by email Id\n UserSchema.getUser({ email: credential.email }, (user) => {\n if (user && user[0]) {\n user[0].password === credential.password ? resolve(user[0]) : reject('Either the username or password is incorrect.');\n } else {\n reject('Failed to find user!')\n }\n });\n })\n}",
"async function getUserByEmail(credentials ) {\n const user = await UserModels.findOne({where: { credentials }});\n if (!user) throw 'User not found';\n return user;\n}",
"function getUser(email) {\n debug('lib users.js getUser email :' + email);\n return User.findOne({email : email}).populate('photos').exec();\n}",
"async function verifyEmail(email) {\n var query = `SELECT * FROM user WHERE user.email = '${email}'`;\n var users = await dbService.runSQL(query);\n console.log(\"Verifing user\", users);\n if (users.length === 1) {\n const user = users[0];\n return user;\n }\n return;\n}",
"function getThisUser(req, res, next) {\n \n getUser(req.user.id, function(user) {\n c.db.one('select ' + relevantUserProps + ' from users where email=${email}',\n user)\n .then(function (data) {\n res.status(200)\n .json({\n status: \"success\",\n data: data\n });\n })\n .catch(function (err) {\n console.log(err);\n res.status(500)\n .json({\n status: \"Error\",\n data: err\n });\n });\n });\n \n}"
]
| [
"0.78970975",
"0.7563983",
"0.7544342",
"0.74932665",
"0.7492347",
"0.7429438",
"0.73304814",
"0.7302694",
"0.72959113",
"0.7287492",
"0.72796553",
"0.727723",
"0.7248472",
"0.720081",
"0.7168404",
"0.7153857",
"0.7133821",
"0.7044105",
"0.70056367",
"0.6975707",
"0.69435453",
"0.69176906",
"0.6876025",
"0.68703926",
"0.6869874",
"0.6837179",
"0.6809309",
"0.67709774",
"0.67342657",
"0.6708198"
]
| 0.76007026 | 1 |
Using jQuery create click event handler for Button that replaces content of a paragraph 4 with a number 42 | function m09task03() {
$("button").click(function () {
$("#last").text("42");
});
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function myButtonWasClicked() {\n // Select the tag with id=\"updateMe\" and set its inner content\n $(\"#updateMe\").text(\"The text is updated!\");\n}",
"function replaceWText(){\n $('#randPara').append('Replaced!');\n}",
"function updateButton(value) {\n abc.find('.awesome-button-text').html(\"\" + value + \" AWE\");\n }",
"function updateQuestionNumber() {\n questionNumber++;\n $('.questionNumber').text(questionNumber);\n console.log(\"updateQuestionNumber\");\n}",
"function theFunction(){\n \n $(\"p\").html(\"Ahoy Matey!\");\n \n document.getElementById(\"appendHTMLDiv\").onclick = function(){\n appendToP();\n }\n document.getElementById(\"replaceHTMLDiv\").onclick = function(){\n replaceHTMLToP();\n }\n \n}",
"function updateQuestionNumText(questionNumber) {\n $('#questionNumber').text(questionNumber);\n}",
"function handleAboutButtonPress(event){\n\n let replacingHTML = `<div id=\"main3\">\n <br><br><br>\n <p class=\"about-text form-size\">This website was made by Evan Falcinelli and Austin Joiner.<br><br>Designed with Bulma.</p>\n </div>`;\n\n let tmpObj=document.createElement(\"div\"); // created an empty 'div'\n tmpObj.innerHTML=replacingHTML; // replaced with whatever edit form html you had\n\n \n $(document.getElementById(\"main3\").replaceWith(tmpObj));\n $(\".aboutButton\").on(\"click\",handleAboutButtonPress);\n\n //makes the tab change colors when clicked\n $(\"button\").removeClass(\"is-info\");\n $(\"button\").removeClass(\"is-light\");\n $(\".aboutButton\").addClass(\"is-info\");\n $(\".aboutButton\").addClass(\"is-light\");\n\n}",
"function insertNumber() {\n var number = this.id\n this.innerText = number;\n }",
"function editNumber() {\n $(mover).text(theCount);\n theCount--;\n\n}",
"function changeQuestionNumber(){\n\t\tquestionNumber ++;\n\n\t$('.questionNumber').text(questionNumber+1);\n}",
"function modifyText(new_text, element) {\n // const t2 = document.getElementById(\"call-button\");\n element.firstChild.nodeValue = new_text;\n }",
"function changeQuestionNum(){\n questionNum ++;\n $('.questionNumber').text(questionNum+1);\n}",
"function changeQuestionNumber () {\n questionNumber ++;\n $('.js-showQuestionNumber').text(questionNumber+1);\n}",
"function changeParagraph() {\n // Take the ID of the paragraph which the user\n // wants to see, based on clicked icon's ID\n var clickedIconId = $(this).attr('id');\n var paragraph = clickedIconId.substr(0, clickedIconId.indexOf('-'));\n var paragraphContent = $('#' + paragraph + '-paragraph');\n \n if ( paragraphContent.hasClass('visible') ) {\n\t// If the wanted paragraph is already visible\n\t// stops the function\n\treturn;\n }\n \n // First, hide the visible paragraph and change classes\n $('.paragraph.visible').fadeOut(1000);\n setTimeout(function() {\n\t$('.paragraph.visible').addClass('invisible').removeClass('visible');\n }, 1000);\n // Then, show the paragraph the user want and change classes\n setTimeout(function() {\n\tparagraphContent.fadeIn(1000);\n\tparagraphContent.removeClass('invisible').addClass('visible');\n }, 1000);\n}",
"function xOn(){\n $(\".x\").on(\"click\", \"button\", function(){\n x1 = x1 + $(this).text();\n $(\"#answer\").text(x1);\n console.log(x1);\n});\n}",
"function updateQuestionNumber() {\n questionNumber++;\n $('.questionNumber').text(questionNumber + 1);\n}",
"function changeQuote(newQuote) {\n $(\".quote-text\").html(newQuote)\n}",
"function clickedButton(strID, strMsg, num, ft){ \n var btnHandler = document.getElementById(strID); \n btnHandler.textContent = strMsg + num + ft;\n}",
"function SetOnlyTextOnButton(theId, newtext) {\n\tvar cache = $(theId).children();\n\t$(theId).text(newtext).append(cache);\n}",
"function putRandomNumberInWindow(){\n $(\".randomNumber\").text(randomNumber);\n}",
"function clickMe() {\n var B = \"I love the color purple!\"; // assign variable for button text\n var P = \"Paragraph changed to tomato!\"; // assign variable for paragraph text\n \n // change text color and bold button text\n B = B.fontcolor(\"#634697\"); \n B = B.bold(); \n \n // change color and font size for paragraph\n P = P.fontcolor(\"tomato\");\n P = P.fontsize(16); \n document.getElementById(\"Purple_Text\").innerHTML = B; //return colored text to button\n document.getElementById(\"Tomato_Text\").innerHTML = P; //return colored text to paragraph \n}",
"function changeElementText(element, answer) {\n $(element).text(answer);\n}",
"function changeElementText(element, answer) {\n $(element).text(answer);\n}",
"function upIteButton(){\n multiply.html(\"x\" + clickValue + \" multiplier / coût: \" + multiplierCost);\n}",
"function changeText(string) {\r\n $(\".viewChange\").text(string);\r\n}",
"function buttonClick(){\n var element=document.getElementById('Some-paragraph');\n //console.log(element.innerHTML);//ja mes gribesim manipulet ar HTML dokumentu\n // console.log(element.innerText); //ja mes gribesim manipulet ar tekstu\n if (element.innerText=='foo')\n {element.innerText = 'bar';}\n else{element.innerText = 'foo';\n}\n //element.innerText = 'bar';\n //setTimeout(buttonClick,2000);//pec 2000milisekonudes izpildas \n}",
"function editBio(){\n var clickedCard = $(\".clicked\").find(\"span\").text();\n $(\"#userEditText\").val(clickedCard);\n}",
"function changeText(message) {\n $(\".box p\").text(message);\n}",
"function showQuestionNumber(){\n questionNumber++;\n $('.questionNumber').text(questionNumber + 1);\n}",
"function AgregadoACarrito(){\n let id = $(\"#carrito\").text();\n $(\"#carrito\").text(id + 1);\n }"
]
| [
"0.63807905",
"0.6179586",
"0.5974979",
"0.5891762",
"0.58906406",
"0.5810711",
"0.577352",
"0.5769662",
"0.5749224",
"0.57415116",
"0.5726678",
"0.5722828",
"0.5721746",
"0.56887496",
"0.56713176",
"0.566008",
"0.5649568",
"0.56260514",
"0.5592905",
"0.55723524",
"0.5560094",
"0.5540929",
"0.5540929",
"0.5535641",
"0.5523174",
"0.5512449",
"0.54891425",
"0.54804003",
"0.54667175",
"0.54569054"
]
| 0.6262017 | 1 |
watch for data changing NOT DROPPED SORT AND DICT (filtring and sorting dictionaries remains untouched) is using for pagging, recalculate max pages, and for sorting determine type of fields Generally, it is creating new data_base from tdata by filtring | function onchange_tdata()
{
scope.init_data(); //create copy of data to data_base
//for new data_base (filtred acc to current filt_state)
if (scope.call_from_directive['filterAll'])scope.call_from_directive['filterAll']();
//init new types for sorting columns
if (scope.call_from_directive['initSorting'])scope.call_from_directive['initSorting']();
//generate new page and calc max pages etc
if (scope.call_from_directive['createPage'])scope.call_from_directive['createPage']();
} | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"function onchange_data_base(new_val,old_val)\r\n {\r\n //make sorting of dataSet\r\n //!!!important to control only oncly raising this function\r\n //because maybe inifine loop, every resorting may retunr new data_base (in chrome)\r\n if (scope.call_from_directive['sortAll'])scope.call_from_directive['sortAll']();\r\n if (scope.call_from_directive['createPage'])scope.call_from_directive['createPage']();\r\n if (scope.map_state)scope.filter_map_state();\r\n }",
"function saveToJson(type,data) {\n var workingLength;\n var finalLength = 0;\n var offset = 0;\n var specialLength = 0; // for when curent page of data is less than sortNumber.\n if (searchActive == 1) {\n saveEntireJson(type,data);\n } else {\n workingLength = data[type].length - sortNumber;\n if (workingLength < sortNumber) {\n for (let findex = 0; findex < data[type].length; findex++) {\n if (data[type][findex]['newCheck']) {\n specialLength++;\n offset++;\n previousData[type] = insertBlankDataIntoObject(0,previousData[type],data[type][findex] ); // this fills in the blank space for the oldData stuff\n }\n }\n finalLength = data[type].length - offset;\n } else {\n specialLength = workingLength;\n finalLength = currentEndIndex;\n }\n var counterIndex = 0;\n // this will overwrite current table with value 1-10 of new table\n for (let dindex = currentStartIndex; dindex < finalLength; dindex++) {\n if (!(typeof data[type][counterIndex] == 'undefined')) { // prevents undefinded stuff on shortened last html page of short first page\n changeArray[type][dindex] = data[type][counterIndex];\n }\n counterIndex++;\n }\n //if there is extra by adding new table entries this will add that to the end\n for (let index = (changeArray[type].length); index < (changeArray[type].length + specialLength); index++) {\n \n if (!(typeof data[type][counterIndex] == 'undefined')) { // prevents undefinded stuff on shortened last html page of short first page\n changeArray[type][index] = data[type][counterIndex];\n if(type !=\"schools\"){\n console.log(getAllSelectTypes[type]);\n savedSelect[type][index] = getAllSelectTypes[type];\n }\n }\n counterIndex++;\n }\n //savedSelect[type] = tempArray;\n // console.log(tempArray);\n //console.log(savedSelect[type]);\n // console.log(previousData[type]);\n }\n\n\n }",
"refreshData() {\n this.lists = trelloDataStore.columns;\n if (this.currentList == \"full\") {\n this.clearFilter();\n } else if (this.currentList == 'date-filter') {\n this.searchDate();\n } else {\n this.searchTags();\n }\n }",
"function _processData(){\n if(_.isEmpty($scope.mdtRow)) {\n return;\n }\n\n //local search/filter\n if (angular.isUndefined($scope.mdtRowPaginator)) {\n $scope.$watch('mdtRow', function (mdtRow) {\n vm.dataStorage.storage = [];\n\n _addRawDataToStorage(mdtRow['data']);\n }, true);\n }else{\n //if it's used for 'Ajax pagination'\n }\n }",
"function remake_data(index_dict){\n // make a dynamic data as a template varible inside\n let dynamic_data = table_data;\n // run a loop to go through the index_dict\n for (let i = 0; i < 5; i++){\n let order = filter_all[i]\n const date_input = index_dict[order];\n // if any selection changed it will change the table\n if (date_input != 0){\n let temp_list = [];\n // use a loop to generate the new table\n for (let k = 0; k < dynamic_data.length; k++){\n let datas = dynamic_data[k];\n let datetime_inside = datas[order];\n if (datetime_inside === filter_list[i][date_input]){\n temp_list.push(datas)\n }\n }\n dynamic_data = temp_list\n }\n }\n return dynamic_data;\n}",
"function dataWatchFn(newData, oldData) {\n if (newData !== oldData){\n if (!scope._config.disabled) {\n scope._config.refreshDataOnly ? scope.api.update() : scope.api.refresh(); // if wanted to refresh data only, use update method, otherwise use full refresh.\n }\n }\n }",
"function dataWatchFn(newData, oldData) {\n if (newData !== oldData){\n if (!scope._config.disabled) {\n scope._config.refreshDataOnly ? scope.api.update() : scope.api.refresh(); // if wanted to refresh data only, use update method, otherwise use full refresh.\n }\n }\n }",
"function init_data()\r\n {\r\n scope.tdata = scope.tdata===undefined?[]:scope.tdata;\r\n scope.data_base = angular.copy(scope.tdata);\r\n scope.create_first_page(); //must be for default set (if no paging)\r\n }",
"setSortTypes() {\n let tf = this.tf,\n sortTypes = this.sortTypes,\n _sortTypes = [];\n\n tf.eachCol((i) => {\n let colType;\n if (sortTypes[i]) {\n colType = sortTypes[i];\n if (isObj(colType)) {\n if (colType.type === DATE) {\n colType = this._addDateType(i, sortTypes);\n }\n else if (colType.type === FORMATTED_NUMBER) {\n let decimal = colType.decimal || tf.decimalSeparator;\n colType = this._addNumberType(i, decimal);\n }\n } else {\n colType = colType.toLowerCase();\n if (colType === DATE) {\n colType = this._addDateType(i, sortTypes);\n }\n else if (colType === FORMATTED_NUMBER ||\n colType === NUMBER) {\n colType = this._addNumberType(i, tf.decimalSeparator);\n }\n else if (colType === NONE) {\n // TODO: normalise 'none' vs 'None'\n colType = 'None';\n }\n }\n } else {\n colType = STRING;\n }\n _sortTypes.push(colType);\n });\n\n //Public TF method to add sort type\n\n //Custom sort types\n this.addSortType('caseinsensitivestring', SortableTable.toUpperCase);\n this.addSortType(STRING);\n this.addSortType(IP_ADDRESS, ipAddress, sortIP);\n\n this.stt = new SortableTable(tf.dom(), _sortTypes);\n\n /*** external table headers adapter ***/\n if (this.asyncSort && this.triggerIds.length > 0) {\n let triggers = this.triggerIds;\n for (let j = 0; j < triggers.length; j++) {\n if (triggers[j] === null) {\n continue;\n }\n let trigger = elm(triggers[j]);\n if (trigger) {\n trigger.style.cursor = 'pointer';\n\n addEvt(trigger, 'click', (evt) => {\n let elm = evt.target;\n if (!this.tf.sort) {\n return;\n }\n this.stt.asyncSort(triggers.indexOf(elm.id));\n });\n trigger.setAttribute('_sortType', _sortTypes[j]);\n }\n }\n }\n }",
"function ec_refreshTierData() {\n eContacts.Queue_Controller.getTierData(function (result, event) {\n if (event.status) {\n if (result != null) {\n result.Processing_Cap = parseInt(result.Processing_Cap);\n result.Records_Processed = parseInt(result.Records_Processed);\n result.Ignore_Processing_Cap = (result.Ignore_Processing_Cap == 'true' ? true : false);\n result.OCR_Enabled = (result.OCR_Enabled == 'true' ? true : false);\n var tierData = new can.Map(result);\n tierData.each(function (value, key) {\n eContacts_app.attr('tierData.' + key, value);\n });\n }\n }\n });\n}",
"function initDataTagToJsonArrayDashboard(){\n if(dataTagToJsonArray.length > 0){\n for(i=0; i<dataTagToJsonArray.length; i++){\n dataTagToJsonArray[i].ref_tag = mgsEncode(dataTagToJsonArray[i].id, dataTagToJsonArray[i].secure);\n dataTagToJsonArray[i].oclient_ref = mgsEncodeClientRef(dataTagToJsonArray[i].ofirstname, dataTagToJsonArray[i].oid, dataTagToJsonArray[i].oclient_ref)\n // We concatenate the data\n dataTagToJsonArray[i].raw_data = dataTagToJsonArray[i].raw_data + dataTagToJsonArray[i].ref_tag + dataTagToJsonArray[i].oclient_ref;\n }\n\n //DEBUG\n /**** We do a load test here ! ****/\n /**** We do a load test here ! ****/\n /**** We do a load test here ! ****/\n /* AFTER Test we can go up to 2700 records / I have heard that 5K may be the max / Even the Excel work */\n /*\n\n var loadTestJSONArray = new Array();\n let j = 0;\n for(k=0; k<100; k++){\n\n for(i=0; i<dataTagToJsonArray.length; i++){\n //dataTagToJsonArray[i].id = j;\n loadTestJSONArray.push(dataTagToJsonArray[i]);\n j++;\n }\n }\n console.log('We have this data: ' + j);\n dataTagToJsonArray = loadTestJSONArray;\n filteredDataTagToJsonArray = dataTagToJsonArray;\n */\n\n /**** We do a load test here ! ****/\n /**** We do a load test here ! ****/\n /**** We do a load test here ! ****/\n\n $('#filter-all').keyup(function() {\n filterData();\n });\n\n $('#re-init-dash').click(function() {\n $('#filter-all').val('');\n clearDataPartner();\n });\n\n }\n runjsPartnerGrid();\n}",
"function analyze_data(database, items, data, src, dst, min, revision, inst_list, done)\n{\n // items are implicly sorted by username and time\n\n if(items[src] == {}) { // no data available\n return;\n }\n\n var db_data = [];\n \n for(var user in items[src]) {\n if(items[dst][user]) { // user exists in dest inst\n\n for(var src_rec in items[src][user]) {\n for(var dst_rec in items[dst][user]) {\n if((items[dst][user][dst_rec].timestamp - items[src][user][src_rec].timestamp) / 1000 < data[src][dst].time) {\n if(items[dst][user][dst_rec].timestamp - items[src][user][src_rec].timestamp >= 0) {\n var item = {\n timestamp : min,\n timestamp_1 : items[src][user][src_rec].timestamp,\n timestamp_2 : items[dst][user][dst_rec].timestamp,\n visinst_1 : items[src][user][src_rec].visinst,\n visinst_2 : items[dst][user][dst_rec].visinst,\n username : user,\n mac_address_1 : items[src][user][src_rec].csi,\n mac_address_2 : items[dst][user][dst_rec].csi,\n time_needed : Math.round(data[src][dst].time),\n dist : Math.round(data[src][dst].dist),\n revision : revision\n };\n\n db_data.push(item);\n }\n }\n }\n }\n }\n }\n\n // ==========================================\n // save to db\n\n if(done)\n save_to_db_callback(database, db_data, done);\n else\n save_to_db(database, db_data);\n}",
"function setupRefresh(){\n setInterval(function(){\n loadData(function(data){\n if (JSON.stringify(data) !== JSON.stringify(tableData) ){\n tableData = data;\n console.log(\"The file has changed\");\n updateChart();\n } else {\n console.log(\"The file has not changed\");\n }\n });\n }, 2000);\n }",
"async importerData({ dispatch, commit }, val) {\n // count keys length of object (store) to import\n let rootKeys = Object.keys(val);\n // iterate the keys of object (store)\n for (let iKeys = 0; iKeys < rootKeys.length; iKeys++) {\n // initiate name of keys\n let keys = rootKeys[iKeys];\n // if keys not status\n if (keys !== \"status\") {\n mydb.reWrite(keys, val[keys]);\n }\n // if (iKeys + 1 === rootKeys.length) {\n val[keys].length < 100 ? await mydb.tunggu(1500) : await mydb.tunggu(val[keys].length * 5)\n // await mydb.tunggu(val[\"absen\"].length * 9);\n // await mydb.tunggu(3000);\n // }\n } //end of for keys\n await mydb.tunggu(3500)\n dispatch(\"importAppend\", \"imported\");\n location.reload();\n }",
"function refreshData() {}",
"function changeData(val) {\n valueField=valueFields[Number(val)];\n\t/* console.log(valueField); */\n\tif(valueField != undefined){\n\t\tviz.update();\n\t}\n}",
"function prepareData() {\n try {\n var tempUniqueValues = pageDetails.singlediffarray.map(function (item) {\n return item.diff.toFixed(0);\n }).filter(function (value, index, self) {\n return self.indexOf(value) === index;\n });\n\n\n //get the unique values\n for (tempi = 0; tempi < tempUniqueValues.length; tempi++) {\n pageDetails.singlefirstlevedata.push(pageDetails.singlediffarray.filter(function (e1, index1) {\n return e1.diff.toFixed(0) === tempUniqueValues[tempi];\n }).map(function (e2, index2) {\n return e2;\n }));\n }\n\n //merge the unique values objects\n var resultObject = [];\n for (recount = 0; recount < pageDetails.singlefirstlevedata.length; recount++) {\n resultObject.push(pageDetails.singlefirstlevedata[recount].reduce(function (result, currentObject, curind) {\n\n for (var key in currentObject) {\n if (currentObject.hasOwnProperty(key)) {\n if (Array.isArray(currentObject[key])) {\n if (result.hasOwnProperty(key)) {\n result[key] = result[key].concat(currentObject[key]);\n } else {\n result[key] = currentObject[key]\n }\n } else {\n if (!isNaN(currentObject[key])) {\n result[key] = currentObject[key].toFixed(0);\n } else {\n result[key] = currentObject[key];\n }\n }\n }\n }\n result['totalLength'] = curind + 1;\n return result;\n }, {}));\n }\n\n pageDetails.singlefirstlevedata = resultObject;\n pageDetails.singlefirstlevedata.sort(compareValues('diff', 'asc'));\n pageDetails.singlefirstlevedata = sortArrayByObj(pageDetails.singlefirstlevedata, 'diff');\n\n } catch (error) {\n swal.fire({\n icon: 'error',\n title: 'Oops...',\n text: 'Something went wrong!',\n footer: JSON.stringify(error)\n });\n }\n }",
"function fixTimeData(viz) {\n var dataToTags = JSON.parse(sessionStorage.dataToTags);\n var keys = Object.keys(dataToTags);\n for (var j in keys) {\n var dataName = keys[j];\n var dataType = dataToTags[dataName][0];\n if (dataType == \"Temporal\") {\n viz.data(\"source\").update(\n function(d) { return true; },\n dataName,\n function(d) {\n if (typeof d[dataName] == \"string\") {\n return Date.parse(d[dataName]);\n }\n return d[dataName];\n }\n )\n }\n }\n viz.update();\n}",
"reloadFieldChanged(event) {\n console.log(\"reloading due to field change...\", event);\n if (event == this.sort_column || event == \"force_reload\")\n this.downloadJobs();\n }",
"handler(value, oldValue) {\n if (JSON.stringify(value) == JSON.stringify(oldValue)) return\n this.getData()\n }",
"on_update_data(json, meta) {\n // Note that the meta info is the original unmodified request\n this._log(`[${performance.now().toFixed(1)}] ` + `on_update_data(units: ${meta.units}, first: ${meta.first}, last: ${meta.last}) uid: ${meta.uid}, actual_range: ${meta.actual_range.units}, ${meta.actual_range.first}, ${meta.actual_range.last})`)\n }",
"function prepData(tableauData, settings) {\n \n // Define the base object\n let data = {\n \"object\": settings.salesforce.ObjectName,\n \"fields\":[],\n \"records\":[]\n }\n\n // Function to lookup a column's index\n const getColumn = (row, col) => {\n return row.findIndex((c)=> {\n return c.fieldName === col.tableau.fieldName;\n });\n }\n\n // Figure out which salesforce fields we are writing to\n let dict = {}\n let error = null;\n Object.keys(settings.salesforce.FieldMappings).forEach( (sfFieldName, index)=>{\n // Pull the reference to this selection\n const sfField = settings.salesforce.FieldMappings[sfFieldName];\n // Save to the fields array\n data.fields[index] = sfFieldName;\n // Figure out which column from the tableau worksheet, maps to this salesforce column\n const tIndex = getColumn(tableauData.columns, sfField);\n if (tIndex<0){\n // The fieldname from the extension config, was not found in the tableau worksheet\n error = `Could not find the field \"${sfField.tableau.fieldName}\" in your worksheet, please re-configure the extension's mapping`;\n } else {\n // Found the matching column name in the tableau worksheet\n sfField.tableau.columnNumber = tIndex;\n }\n // Define which tableau column maps to this field\n dict[index] = sfField;\n })\n\n // Check for any errors during the field mapping process\n if (error){\n toast.error(error);\n return null;\n }\n \n // Loop through each record in the dataset from Tableau\n tableauData.data.forEach( (row,index) => {\n // Create a record array\n let record = [];\n // Loop through the fields dictionary\n Object.keys(dict).forEach( (sfFieldIndex) => {\n // Save the value from the tableau dataset, into the proper salesforce column\n // First figure out which tableau column to pull\n const index = dict[sfFieldIndex].tableau.columnNumber;\n // and make sure to safely handle api versions 1.3 or older\n record[sfFieldIndex] = apiIs14Plus ? row[index].nativeValue : row[index].value;\n })\n // Save the record\n data.records.push(record)\n })\n\n return data;\n }",
"updateUserSyncData (tblname, field)\n\t{\n\t\t/*this.getHashFieldValue2 (this.redisSyncTableName, field, sSyncData => {\n\t\t\tlet doc = ('string' == typeof sSyncData && validator.isJSON(sSyncData)) ? JSON.parse(sSyncData) : {};\n\t\t\tdoc[tblname] = 1;\n\t\t\tthis.setHashFieldValue2 (this.redisSyncTableName, field, JSON.stringify(doc), () => {\n\t\t\t});\n\t\t});*/\n\t}",
"constructor() {\n this._films = [];\n this._filter = Filter.ALL;\n this._sortType = SortType.DEFAULT;\n this._filterChangeHandlers = [];\n this._dataChangeHandlers = [];\n }",
"static updateData(type,data) {\n if(type == 'pets')\n if(!data.version){\n if(data.items)\n delete data.items;\n data.items = [];\n if(data.stats.petDuplicates)\n data.stats.petDuplicates = data.stats.totalClaimed - data.stats.petsClaimed;\n if(!data.stats.petDuplicates) data.stats.petDuplicates = 0;\n if(data.tokens.count == null) data.tokens.count = 0;\n };\n data.version = 1;\n if(type == 'main')\n if(!data.version) data.version = 1;\n return data;\n }",
"function onDataChanged() {\n $timeout(makeSearch);\n }",
"function onDataChanged() {\n $timeout(makeSearch);\n }",
"function onDataChanged() {\n $timeout(makeSearch);\n }",
"function onDataChanged() {\n $timeout(makeSearch);\n }",
"function watchAllTaxiData() {\n $scope.$watch('vm.taxis', function (nVal, oVal) {\n if (!angular.equals(nVal, oVal)){\n vm.initialTaxis = angular.copy(vm.taxis);\n }\n }, true);\n }"
]
| [
"0.6572519",
"0.61168236",
"0.5740207",
"0.5713793",
"0.5610316",
"0.5535869",
"0.5535869",
"0.54664016",
"0.5378671",
"0.5364187",
"0.5316887",
"0.52674896",
"0.5262467",
"0.5257892",
"0.52319837",
"0.5230105",
"0.5219458",
"0.52030426",
"0.5201582",
"0.5164825",
"0.51489365",
"0.51447016",
"0.5123909",
"0.5123441",
"0.5121541",
"0.51152396",
"0.51152396",
"0.51152396",
"0.51152396",
"0.5109258"
]
| 0.70884395 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.