query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
find roles in xml
function hlp_parse_load_xml(xml) { var xmlDoc = $.parseXML(xml); xml_file = $(xmlDoc); var new_roles = xml_file.find('role'); return new_roles; }
[ "visitRole_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitRole_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function getAvailableRoles() {\n StaticDataFactory.getAvailableRoles().then(function (data) {\n vm.claimRoles = data.roles.role;\n if(typeof vm.claimRoles === 'string')\n {\n vm.claimRoles = [];\n vm.claimRoles.push(data.roles.role);\n }\n vm.selectedManagementRole = vm.claimRoles[0];\n console.log(\"ClaimRoles die binnenkomen:\", vm.claimRoles);\n });\n }", "static loadRoles() {\n let roleList = [];\n let dataFile = fs.readFileSync('./data/roles.json', 'utf8');\n if (dataFile === '') return roleList;\n\n let roleData = JSON.parse(dataFile);\n\n roleData.forEach((element) => {\n roleList.push(\n new Role(\n element.roleID,\n element.title,\n element.description,\n element.image,\n element.color,\n element.emote\n )\n );\n });\n\n return roleList;\n }", "findByRole(role, shuffle) {\n const result = [];\n this.nodes.forEach(node => {\n if (node.hasRole(role)) {\n result.push(node);\n }\n });\n\n if (shuffle) {\n var currentIndex = result.length, temporaryValue, randomIndex;\n while (0 !== currentIndex) {\n randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex -= 1;\n temporaryValue = result[currentIndex];\n result[currentIndex] = result[randomIndex];\n result[randomIndex] = temporaryValue;\n }\n }\n return result;\n }", "function getUserIdsFromRoleId(role_id) {\n var membershipProperties = openidm.read('config/commons').membershipProperties;\n if (!membershipProperties) {\n __.requestError('commons.json configuration for membershipProperties cannot be read.', 400)\n }\n \n var userIds = [];\n // Determine reverseProps based on commons.json membershipProperties\n var reverseProps = [];\n if (membershipProperties.indexOf('roles') >= 0) {\n reverseProps.push('members');\n }\n if (membershipProperties.indexOf('authzRoles') >= 0) {\n reverseProps.push('authzMembers');\n }\n \n var result = openidm.read(role_id, null, reverseProps);\n _.forEach(reverseProps, function(prop) {\n if (result && result[prop]) {\n userIds = _.union(userIds, _.map(result[prop], '_ref'));\n }\n });\n return userIds;\n}", "async getRoles() {\n let roles = await groupFunctions.getRoles(this.groupId, this._id);\n return [].concat(roles).map(x=> new Role(x, this.groupId, this._id));\n }", "function checkRoles(roles){\n var possibleRoles = [\"service provider\", \"device owner\", \"infrastructure operator\", \"administrator\", \"system integrator\", \"devOps\", \"user\", \"superUser\"];\n for(var i = 0, l = roles.length; i < l; i++){\n if(possibleRoles.indexOf(roles[i]) === -1){\n return {invalid: true, message: roles[i]};\n }\n }\n return {invalid: false, message: null};\n}", "function get_roles() {\n var retained_roles = [];\n var roles_count = $('input[type=number]');\n roles_count.each((index, r) => {\n for (var i = 0; i < r.value; i++) {\n //console.log(r.id.substring(5, retained_roles_id[i].id.length));\n retained_roles.push(roles[r.id.substring(5, r.id.length)][0]);\n }\n });\n return retained_roles;\n}", "role() {\n return this.props.projectData.role \n .map(role => \n <span className=\"tag is-size-5 is-white has-text-weight-bold\">{role}</span>\n );\n }", "function cleanRoles(roles) {\n var res = [];\n roles.forEach(function (item) {\n if (item === 'standard' || item === 'guest' || item === 'admin') {\n res.push(item);\n }\n });\n return res;\n}", "function showAllRoles() {\n query = 'SELECT * FROM role;';\n connection.query(query, (err, results) => {\n if (err) throw err;\n console.table(results);\n // return to main menu\n askUser();\n });\n}", "function seperateRole(){\n\n}", "function getUserRole(name, role){\n switch (role) {\n case \"admin\":\n return `${name} is admin with all access`\n break; //this is not neccesary\n\n case \"subadmin\":\n return `${name} is sub-admin acess to delete and create courses`\n break;\n\n case \"testprep\":\n return `${name} is test-prep access with to delete and create tests `\n break;\n case \"user\":\n return `${name} is a user to consume content`\n break;\n \n default:\n return `${name} is admin access with to delete and create tests `\n break;\n }\n}", "function roleExists(roleName){\r\n for (i = 0; i < Z_ROLES.length; i++) {\r\n var z_userrole = Z_ROLES[i].toString().substring(0,25).trim();\r\n\t if(z_userrole.toUpperCase() == roleName.toUpperCase()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}", "getAllEntities() {\n let queryParameters = {};\n let headerParams = this.defaultHeaders;\n let isFile = false;\n let formParams = {};\n return this.execute('GET', '/api/user/v1/role/get-all', queryParameters, headerParams, formParams, isFile, false, undefined);\n }", "get roleId() {\n return this.getStringAttribute('role_id');\n }", "function populate_roles_fields () {\n // Populate the fields from the roles table\n for (var i in roles) {\n var current_role = new Array();\n $('.roles-row').each(function(index) {\n user = $(this).attr('user_id');\n if ($('#checkbox-'+roles[i]+'-'+user).is(':checked')) {\n current_role.push(user);\n };\n });\n $('#'+roles[i]).val(current_role.join(','));\n $('#list-'+roles[i]+' span').html(current_role.join(', '));\n }\n}", "function GetSecurityRolesOfCurrentUser(executionContext) {\n try {\n //Get the form context\n var formContext = executionContext.getFormContext();\n //Get the Current User Guid\n var userRoles = formContext.context.getUserRoles();\n Xrm.Utility.alertDialog(userRoles);\n }\n catch (e) {\n Xrm.Utility.alertDialog(e.message);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an address for locations
function getLocation(name){ var location = _.detect(locations, function(location){ return name.match(location.re); }); return location ? location.address : ''; }
[ "function getLocationName() {}", "getPositionName(lat, lng){\n Geocoder.getFromLatLng(lat, lng).\n then(res=>\n {\n const formatted_address = res.results[0].formatted_address;\n const position = {\n lat:lat,\n lng:lng\n };\n\n this.setLocation(formatted_address, position);\n },\n err=>\n {\n return;\n }\n )\n }", "getLocation(name) { return this.#locations_.get(name) ?? null; }", "function formatLocation(city, state, country, zipCode) {\n return (\n city + \", \" + state + \" \" + zipCode + \" \" + country\n );\n}", "static address(v) { return new Typed(_gaurd, \"address\", v); }", "function getCoordinate(postalCode, map) {\r\n var geocoder = new google.maps.Geocoder();\r\n var result = \"\";\r\n geocoder.geocode({ 'address': String(postalCode) }, function (results, status) {\r\n if (status == google.maps.GeocoderStatus.OK) {\r\n currentCafeLocation = results[0].geometry.location;\r\n result = results[0].geometry.location;\r\n createMarker(result, map);\r\n setInfoWindow(map);\r\n } else {\r\n result = \"Unable to find address: \" + status;\r\n }\r\n });\r\n return result;\r\n}", "function createNewAddress() { return { type: types.CREATE_NEW_ADDRESS }; }", "function getSolicitorAddress(solicitor) {\n\n var myAddress = '';\n\n if ((solicitor == undefined) || (solicitor == null)) {\n\n return myAddress;\n }\n\n if ((solicitor.AddressLine1 !== undefined) && (solicitor.AddressLine1 !== null)) {\n myAddress = solicitor.AddressLine1.trim();\n }\n\n if ((solicitor.AddressLine2 !== undefined) && (solicitor.AddressLine2 !== null)) {\n\n if (myAddress.length == 0) {\n\n myAddress = solicitor.AddressLine2.trim();\n\n } else {\n\n myAddress += ' ' + solicitor.AddressLine2.trim();\n }\n\n }\n\n return myAddress;\n}", "function infoForMap(){\n var coordObj = {\n address : {\n state : shelterArray[shelterCount].state['$t'],\n city : shelterArray[shelterCount].city['$t'],\n name : shelterArray[shelterCount].name['$t']\n },\n latitude : parseFloat(shelterArray[shelterCount].latitude['$t']),\n longitude : parseFloat(shelterArray[shelterCount].longitude['$t'])\n };\n coordObj.address.text = coordObj.address.city + ', ' + coordObj.address.state;\n return coordObj;\n}", "function addAddressToMap(results, status) {\n //map.clearOverlays();\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n marker = new google.maps.Marker({\n map: map,\n position: results[0].geometry.location\n });\n //reverseGeocode(point.y,point.x);\n var CountryNameCode = \"\";\n var i = 0;\n while(results[0].address_components[i])\n {\n if(results[0].address_components[i].types[0] == \"country\")\n {\n CountryNameCode = results[0].address_components[i].short_name;\n break;\n }\n i++;\n }\n var contentString = results[0].formatted_address + '<br/>' +\n '<b>Country code:</b> ' + CountryNameCode;\n\n var infowindow = new google.maps.InfoWindow({content: contentString});\n infowindow.open(map,marker);\n\n } else {\n alert(\"Sorry, we were unable to geocode that address\");\n }\n return;\n }", "getLocation() {\n // using fetch API to get AJAX calls you can use XHP also\n fetch(\"https://geoip-db.com/json/\")\n .then(res => res.json())\n .then(result => {\n name.innerHTML += `${res.city}, ${res.state}`;\n });\n }", "function locationFinder() {\n\n // initializes an empty array\n let locations = [];\n\n // adds the single location property from bio to the locations array\n locations.push(bio.contacts.location);\n\n // iterates through school locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n education.schools.forEach(function (school) {\n locations.push(school.location);\n });\n\n // iterates through work locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide above.\n work.jobs.forEach(function (job) {\n locations.push(job.location);\n });\n\n return locations;\n }", "function getLocationName(lat, long) {\n console.log(lat, long)\n fetch(`https://api.geocod.io/v1.4/reverse?q=${lat},${long}&fields=census2010&api_key=8cccc5825cc2d2dc042d3db2d00b2d5dcd85bcd`)\n .then(response => {\n if (response.ok) {\n return response.json();\n } else console.log(\"That didn't work.\")\n })\n .then(responseJson => grabCensusData(responseJson))\n .catch(err => {\n console.log(err)\n })\n }", "function geocode (address, api_key, log=false) {\n address = xdmp.urlEncode(address);\n \n // First see if we cached this address already\n let geodata;\n let cache = cts.search(cts.andQuery([cts.collectionQuery(\"geodata\"), cts.jsonPropertyValueQuery('address', address)]));\n if (!fn.empty(cache)) {\n if (log) {console.log('GEOCODE: CACHED RESULT')};\n geodata = fn.head(cache).root.geodata;\n } else {\n // Call the geocoding service and sleep for 1000 ms\n let result = xdmp.httpGet('https://eu1.locationiq.com/v1/search.php?key=' + api_key + '&format=json&q=' + address);\n xdmp.sleep(1000);\n \n result = result.toArray();\n if (result[0].code == '200') {\n // When the HTTP response equals 200, take the result from the service\n if (log) {console.log('GEOCODE: MATCH (' + result[0].code + ' / ' + result[0].message + ')')};\n geodata = result[1].root[0];\n } else {\n // When there is another HTTP response, return an empty result\n if (log) {console.log('GEOCODE: ADDRES NOT FOUND (' + result[0].code + ' / ' + result[0].message + ')')};\n geodata = xdmp.toJSON({});\n }\n \n // Cache the data for future use\n let jsInsert = `\n declareUpdate();\n let geodoc = {\n \"address\": \"` + address + `\",\n \"geodata\": ` + geodata + `\n };\n xdmp.documentInsert(sem.uuidString(), geodoc, {collections: 'geodata'});`\n xdmp.eval(jsInsert, null);\n }\n\n return {\n coordinate: {\n \"lat\": geodata.lat,\n \"lon\": geodata.lon\n },\n \"class\": geodata.class,\n \"type\": geodata.type\n };\n}", "function locationFinder() {\n\n // initializes an empty array\n var locations = [];\n\n // adds the single location property from bio to the locations array\n locations.push(bio.contacts.location);\n\n // iterates through school locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n education.schools.forEach(function(school){\n locations.push(school.location);\n });\n\n // iterates through work locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n work.jobs.forEach(function(job){\n locations.push(job.location);\n });\n // console.log(locations);\n return locations;\n }", "function parseLocationInfo(location) {\n for (const key in LOCATIONS) {\n const abbr = location.substring(0, key.length)\n if (key.toLowerCase() == abbr.toLowerCase()) {\n const room = location.substring(key.length).trim()\n const { name, num } = LOCATIONS[key]\n return `(${num}) ${location} - ${name}, Room ${room}`\n }\n }\n return location\n}", "getPredictionAddress(prediction) {\n return prediction.description;\n }", "function geocodeLocation(location, mainDispatch, fromGeoLocation) {\n geocoder.geocode({ location: location }, function (results, status) {\n if (status === \"OK\") {\n var place = results[0];\n var address = {};\n var isBetweenAddress = -1;\n isBetweenAddress = place.formatted_address.indexOf(\" a \");\n if (isBetweenAddress === -1) {\n address['address'] = place.formatted_address;\n }\n else {\n var street = place.formatted_address.substr(0, isBetweenAddress);\n var city_1 = \"\";\n place.address_components.forEach(function (component) {\n if (component.types.indexOf(\"locality\") !== -1)\n city_1 = component.short_name;\n });\n address['address'] = street + \", \" + city_1;\n }\n address['location'] = {\n lat: place.geometry.location.lat(),\n lng: place.geometry.location.lng()\n };\n address['fromGeoLocation'] = fromGeoLocation;\n mainDispatch(mapAddressChanged(address));\n }\n });\n}", "function resolveAddress(postCode,callback){\n\tvar getCode=new Request(\"SELECT StateCode, County, City, CountryCode, TimeZone FROM SystemPostalCode WHERE PostalCode='\"+postCode+\"'\",function(err,rowCount,docRows){\n\t\tcallback(docRows[0]);\n\t});\n\t\n\tconnection.execSqlBatch(getCode);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to finish fade effect of an element
function finishFadeEffect(element) { var listener = function() { element.style.webkitTransition = ''; element.removeEventListener('webkitTransitionEnd', listener, false); }; element.removeEventListener('webkitTransitionEnd', listener, false); element.style.webkitTransition = ''; element.style.opacity = 0; }
[ "function myFadeOut(element, howLong)\n{\n // Creates the Animation Which Carries the Element from Opacity 1 to Opacity 0.\n element.animate([\n {opacity: 1}, \n {opacity: 0}\n ], { \n // How long the Element's Transition from Opacity 1 to Opacity 0 Should Take.\n duration: howLong,\n // Amount of Times to Produce the Animation.\n iterations: 1\n });\n up1ButtonVisible = true;\n element.style.opacity = 0;\n}", "function fadeAnimation(element,seconds,end, from, onEndCallback){\n if (from !== undefined)\n element.style.opacity = from/100;\n var initial = (parseFloat(element.style.opacity) || 1) * 100;\n var increment = initial > end ? -1 : 1;\n var curOpacity = initial;\n fadeAnimation.running = fadeAnimation.running || {};\n\n clearInterval(fadeAnimation.running[element.id]);\n var changeOpacity = function() {\n if (increment > 0 ? curOpacity >= end : curOpacity <= end){\n onEndCallback && onEndCallback();\n clearInterval(fadeAnimation.running[element.id]);\n } else {\n curOpacity += increment;\n element.style.opacity = curOpacity/100;\n element.style.filter = \"alpha(opacity=\"+curOpacity+\")\";\n }\n };\n changeOpacity();\n fadeAnimation.running[element.id] = setInterval(changeOpacity,seconds * 10);\n}", "function fadeOut() {\n\tif (opacity > 0) {\n\t\topacity = opacity - 0.05;\n\t\ttargetImage.style.opacity = opacity;\n\t\t// fade some more....\n\t\trequestAnimationFrame(fadeOut);\n\t} else {\n\t\tconsole.log('targetImage is transparent');\n\t\t// image is transparent, swap to the next image\n\t\ttargetImage.src = images[currentImage];\n\t\t// fade it back in \n\t\tfadeIn();\n\t}\n}", "function MM_effectAppearFade(targetElement, duration, from, to, toggle)\n{\n\tSpry.Effect.DoFade(targetElement, {duration: duration, from: from, to: to, toggle: toggle});\n}", "function teardownFade() {\n fader.removeClass(\"show fadeOut\");\n }", "function FadeInTransition() {}", "function fadeOut() {\n anime({\n targets: [\".logo\", \".burger\", \".navbar-right\", \".home-text1\", \".home-text2\", \".home-text3\", \".arrow-button\", \".socials\"],\n keyframes: [\n {\n opacity: 0,\n translateY: 50,\n easing: \"easeInCubic\",\n duration: 300,\n },\n ],\n });\n}", "function mFade() {\n\tgetId('t' + currTact).classList.add(\"faded\");\n}", "function fadeSubmit() {\r\n\tsubmit_button.style.animationDuration = \"2s\";\r\n\tsubmit_button.style.animationName = \"fadeOut\";\r\n}", "_doFadeIn() {\n if (this.isShowing) {\n let currentOpacity = parseFloat(this.$.infocarddiv.style.opacity);\n if (currentOpacity >= 0.9) {\n this.$.infocarddiv.style.opacity = \"1\";\n } else {\n currentOpacity += 0.1;\n this.$.infocarddiv.style.opacity = currentOpacity.toString();\n setTimeout(() => {\n this._doFadeIn();\n }, 40);\n }\n }\n }", "function fadeIn() {\n if (fadingOut == true) {\n sendOSC('/composition/video/fadeout/direction', 1);\n fadingOut = false;\n }\n}", "function fadeMessage() {\n $('.flash_message').fadeOut(500);\n}", "function stepOne(){\n $(\".col__Step-One\").fadeOut(500, function(){\n /*Conditional below ensures that the fadeOut function is only called once before callback function is executed.\n fadeOut function calls the callback function once per specified element */\n if(isFaded === true){\n $(\".col__Step-Two\").fadeIn(500);\n h1Changer.innerHTML = \"<a href=\\\"index.html\\\"><i class=\\\"far fa-arrow-alt-circle-left\\\"></i></a><span class=\\\"heading__top--highlight\\\">Step 2:</span> Select Your Product\";\n isFaded = !isFaded;\n }\n });\n stepTwoBinder();\n}", "function fade (targetElement, counterStart, counterEnd, counterValue, counterAdjust, intervalSetting, callback) {\n\n 'use strict';\n\n var adjustedValue, interval;\n\n // Redundancy settings, just to make sure everything is set properly (in case the function ended prematurely for some reason and the values did not reach their full/correct amount, although this should be prevented if possible by using the animating variable in the initializing function to track animations in progress)\n if (counterAdjust < 0) {\n\n // If counter adjust has a negative value, then it means the element needs to be faded out (since we will be counting down from 10, a negative value is needed). So make sure the element is in display: block and its opacity is 1.0 (0.9, 0.8, etc... will throw the counter off, best to make sure it is counting from 1.0)\n targetElement.style.display = \"block\";\n targetElement.style.opacity = 1;\n\n } else if (counterAdjust >= 0) {\n\n // If the counter is 0 or positive then it means the element needs to faded in (0 means no adjustment needed, so we need only to count from 0 to 10). So make sure the element is in display: block so that it can be seen, and thus faded in and that its opacity is at 0 (0.1, 0.2, etc... will throw the counter off, best to make sure it starts counting from 0)\n targetElement.style.display = \"block\";\n targetElement.style.opacity = 0;\n\n }\n\n // Start the interval for the animation process. This will continue to loop until counterStart reaches or exceeds counterEnd, at which point the interval will be cleared and the callback function initiated (if provided)\n interval = setInterval(function () {\n\n // If counterStart has reached or exceeded counterEnd then the loop is ready to be stopped\n if (counterStart >= counterEnd) {\n\n // If counterAdjust has a negative value, then that means the element is fading out, so set display: none. Even though opacity: 0 does hide it, display: none is needed on some elements so that they do not display on a page load. This check is not needed for elements that are being fade in, since they are already in display: block\n if (counterAdjust < 0) {\n\n targetElement.style.display = \"none\"; // If counterAdjust has a negative value then the element is being faded out, so set the element to display: none in order to complete the animation by hiding the element\n\n }\n\n // Callback function initiated here. If parameters are needed for the callback function, then wrap the needed function in an anonymous function and have the anonymous function called instead (this is how bounce as done, so refer to that for an example)\n if (callback) {\n callback();\n }\n\n clearInterval(interval); // Finally, clear the interval setting after all settings have been set\n\n // As long as counterStart is less than counterEnd, this will be looped over\n } else if (counterStart < counterEnd) {\n\n counterStart += counterValue; // Increase the counterStart variable by the counterValue variable; counterVariable should almost always be 1 since fading requires an exact process of dividing by powers of 10. To control the speed of fade, increasing (or decreasing) counterEnd by powers of 10 is the better way to do this. intervalSetting will control the speed as well\n\n adjustedValue = Math.abs(counterStart + counterAdjust) / counterEnd; // Add the counterAdjust variable to the new counterStart variable in order to get the correct settings for the opacity; Fading out elements will use a negative value for counterAdjust (fading in elements should be send 0, and thus are a moot point since we only need to count up from 0 to 10). For example, if we need to fade out from 1, then we send a -10 for counterAdjust which is added to counterStart, 1, to get a value of -9 for the adjustedValue. This will be converted back to a positive integer and then divided by counterEnd, 10, in order to arrive with a newSetting of 0.9 for our opacity setting\n\n targetElement.style.opacity = adjustedValue; // Apply the new value to the targetElement\n\n }\n\n }, intervalSetting); // intervalSetting was passed in from the initializing function; Adjusting this value will make the animation run faster or slower\n\n }", "function fadeNameIn(){\n$('#name_box').fadeIn(4000);\n$('#name_box').fadeOut(500);\n\n\n}", "function tasklistFadeOutResultText(){\n \n $( \"#tableWrapper\" ).animate({\n opacity: 1\n }, 1000, function() {\n if (!tasksFetched)\n tasklistFadeInResultText();\n });\n}", "function tasklistFadeInResultText(){\n \n $( \"#tableWrapper\" ).animate({\n opacity: 0.5\n }, 1000, function() {\n tasklistFadeOutResultText();\n });\n}", "function fadeEvent(index) {\n\t\t events[index].button.gotoAndStop(1);\n\t\t}", "function fadeColorIn() {\n $(\"#color-fade\").animate({\n backgroundColor: \"#ed3\"\n }, 4000, function() {\n fadeColorOut();\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop the gameloop. The handle is used
function stopLoop() { clearInterval (Defaults.game.handle); }
[ "stop() {\n if (!this.stopped) {\n for (let timeout of this.timeouts) {\n clearTimeout(timeout);\n }\n clearTimeout(this.mainLoopTimeout);\n this.stopped = true;\n }\n }", "function stopGame(){\n\tresetGame();\n\tgoPage('result');\n}", "function gameStop(){\r\n\r\n\t\t// updates user score after a game\r\n\t\tif (loggedIn){\r\n\t\t\tuserscore = points;\r\n\t\t}\r\n\t\tlives = 3;\r\n\t\tpoints = 0;\r\n\r\n\t\t//Resetting page layout to before game started.\r\n\t\tlet gameSpace = document.getElementById(\"topgame\");\r\n\t\tgameSpace.innerHTML = \"\";\r\n\t\tlet gameTitle = document.createElement(\"h3\");\r\n\t\tgameTitle.innerHTML = \"Breakout\";\r\n\t\tlet gameImg = document.createElement(\"img\");\r\n\t\tgameImg.src = \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT054y4d7kqbe3txi8_-beKdcXWjhvvhxim067vmnpQ-f6V7nLS\";\r\n\t\tgameImg.alt = \"break\";\r\n\t\tlet description = document.createElement(\"p\");\r\n\t\tdescription.innerHTML = \"Breakout is a game where the user breaks cubes with a ball!\";\r\n\t\tgameSpace.append(gameTitle);\r\n\t\tgameSpace.append(gameImg);\r\n\t\tgameSpace.append(description);\r\n\r\n\t\t// removing event listeners from page.\r\n\t\tdocument.removeEventListener(\"keydown\", keyDownHandler, false);\r\n\t\tdocument.removeEventListener(\"keyup\", keyUpHandler, false);\r\n\t\trunning = false; // game stops running.\r\n\t\tdocument.getElementById(\"startgame\").disabled = false;\r\n\t\tdocument.getElementById(\"stopgame\").disabled = true;\r\n\r\n\t\t// updates user score and text file holding all scores if a user is logged in.\r\n\t\tif (loggedIn){\r\n\r\n\t\t\tif (userscore > maxScore){\r\n\t\t\t\tmaxScore = userscore;\r\n\t\t\t}\r\n\r\n\t\t\tdocument.getElementById(\"scorekeeper\").innerHTML = \"Recent Score: \"+userscore + \"<br>\";\r\n\t\t\tdocument.getElementById(\"scorekeeper\").innerHTML += \"Best Score: \" + maxScore;\r\n\t\t\tupdateScores();\r\n\t\t\tupdateBoard();\r\n\r\n\t\t}\r\n\t}", "clearInterval() {\n if (this.handle === undefined) {\n throw new Error('The interval must be running for it to be stoppped');\n }\n cancelAnimationFrame(this.handle);\n //clearInterval(this.handle)\n this.handle = undefined;\n }", "_terminate() {\n console.log(\"terminate\");\n /*if (this.state !== or === ? GameStates.Terminating) {\n return; //error\n }*/\n\n this.state = GameStates.Terminating;\n clearTimeout(this.tick);\n this._clearTurn();\n this.destroy();\n }", "stop() {\n this.song_.stop();\n this.bitDepthSlider_.disable();\n this.reductionSlider_.disable();\n }", "function pauseGame() {\n \t\tclearInterval(gameLoop);\n \t}", "quit()\n\t{\n\t\t// stop game from listening for player input\n\t\tthis.input.shutdown();\n\n\t\t// blank screen\n\t\tthis.clearCanvas(\"#888\");\n\t}", "stop() {\n if (this.started) {\n this.keyboard.interceptKeys = false;\n this.cancelTickTimeout();\n this.started = false;\n }\n }", "endGame()\r\n {\r\n this.gameInProgress = false;\r\n game.arrowPosition = [];\r\n\r\n this.interface.gameOptions.open();\r\n this.interface.gameMovie = this.interface.gui.add(this, 'ViewGameFilm');\r\n }", "stop() {\n this.target = undefined;\n // @ts-expect-error\n const pathfinder = this.bot.pathfinder;\n pathfinder.setGoal(null);\n // @ts-expect-error\n this.bot.emit('stoppedAttacking');\n }", "endGame() {\n if (this.health <= 0) {\n backgroundMusic.stop();\n failSound.play();\n state = \"GAMEOVER\";\n return;\n } else if (this.score >= 40) {\n state = \"GAMEWIN\";\n return;\n }\n }", "function outOfFocus(){\n if(playGame) env.pause(true);\n }", "stop() {\n this.queueLock = true;\n this.queue = [];\n this.audioPlayer.stop(true);\n }", "endGame() {\n // All timers must be cleared to prevent against server crashes during prematurely ended games.\n if (this.serverState !== undefined) {\n this.serverState.clearTimers();\n clearTimeout(this.currentForcedTimer);\n }\n\n this.serverState = undefined;\n this.playerMap.removeInactivePlayers();\n this.playerMap.doAll((player) => { player.reset(); });\n }", "function stopBattleTimer() {\n clearInterval(battleIntervalId); //stops the interval\n }", "function stopBall() {\n if(counter === timeLeft) {\n ball.vx = 0;\n ball.vy = 0;\n }\n}", "function play_stop() {\n if(playing) {\n //video[v_index].play();\n video[v_index].loop();\n } else\n video[v_index].pause();\n\n playing = !playing;\n}", "function stop_slideshow() {\n\t\tclearInterval(intervalID);\n\t\tchange_image(default_image);\n\t\t$('#stop_button').hide();\n\t\t$('#start_button').show();\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
change instrument of a track
changeTrackInstrument(trackID, instrumentID) { let track = this.tracks[trackID]; let new_instr = instrumentArray[instrumentID]; track.instrument = new_instr; track.instrumentID = instrumentID; let trackName = this.generateTrackName(trackID, new_instr); this.trackNames[trackID] = trackName; this.controls.tracksElement.options[trackID] = new Option(trackName, trackName); this.controls.tracksElement.selectedIndex = trackID; //tracksElementを変更するとインデックスが変化するので元に戻す }
[ "function changeInstrument() {\n instrument = (instrument + 1) % instruments.length;\n console.log('change instrument');\n }", "changeCurrentTrackInstrument(instrumentID) {\n this.changeTrackInstrument(this.index, instrumentID);\n }", "updateAudioTrack(state, track) {\n\t\tVue.set(state.self.tracks, 'audio', track)\n\t}", "onChangeInstrumentHandler (i,value) {\n const instruments = this.state.instruments.slice();\n const instrument = instruments[i];\n if(instrument.type != value){\n instrument.type = value;\n instruments[i] = instrument;\n this.setState({instruments:instruments});\n }\n console.log('******Instrument Panel **********');\n console.log('Instrument type of:', i);\n console.log('Set to:', value);\n }", "function setNoteOn(stepNumber, instrumentIndex, noteNumber) {\n\tvar action = new Object();\n\taction.type = 'noteOn';\n\taction.instrumentIndex = instrumentIndex;\n\taction.noteNumber = noteNumber;\n\tstep[stepNumber].actionList.push(action);\n\t// update sequencer grid to reflect the change\n\tdocument.getElementById(constructGridId(stepNumber, instrumentIndex, noteNumber)).style.backgroundColor = '#FF0000';\n}", "set OverrideSampleRate(value) {}", "editTracksInfo () {\n //\n }", "function changeGain(i, j, newGain) {\n const key = `${i} ${j}`\n if (!soundMatrix.has(key)) {\n let soundNode = new OscillatorNode(audioCtx, {\n type: bubbles[i].type,\n frequency: bubbles[i].freq\n })\n let gainNode = audioCtx.createGain()\n let pannerNode = new StereoPannerNode(audioCtx)\n gainNode.gain.value = 0\n soundNode.connect(gainNode)\n gainNode.connect(pannerNode)\n pannerNode.connect(audioCtx.destination)\n soundNode.start()\n\n soundMatrix.set(key, {\n soundNode: soundNode,\n gainNode: gainNode,\n pannerNode: pannerNode\n })\n }\n soundObject = soundMatrix.get(key)\n soundObject.gainNode.gain.linearRampToValueAtTime(newGain, audioCtx.currentTime + (1/60))\n\n // panning is from -1 to 1, so make a range from 0 to 2 and subtract 1\n const panValue = (bubbles[i].pos[0] / (canvas.width / 2)) - 1\n soundObject.pannerNode.pan.linearRampToValueAtTime(panValue, audioCtx.currentTime + (1/60))\n}", "set PreserveSampleRate(value) {}", "labelCurrentTrack() {\n\t\tlet labl = 'empty';\n\t\tif (this.trks[tpos].usedInstruments.length === 1) {\n\t\t\tif (this.trks[tpos].hasPercussion) {\n\t\t\t\tlabl = 'Percussion';\n\t\t\t} else {\n\t\t\t\tlabl = getInstrumentLabel(this.trks[tpos].usedInstruments[0]);\n\t\t\t}\n\t\t} else if (this.trks[tpos].usedInstruments.length > 1) {\n\t\t\tlabl = 'Mixed Track';\n\t\t}\n\t\tthis.trks[tpos].label = `${labl} ${this.getLabelNumber(labl)}`;\n\t}", "function synthType(type) {\n selectedSound = type;\n}", "function Instrument (options) {\n\tvar i, waveForm, array, mod;\n\toptions = options || {};\n\n\tif (options.context) {\n\t\tthis.context = options.context;\n\t} else if (options.destination) {\n\t\tthis.context = options.destination.context;\n\t} else {\n\t\tthis.context = new AudioContext();\n\t}\n\tthis.mainGain = this.context.createGain();\n\tthis.mainGain.connect(options.destination || this.context.destination);\n\tthis.nextTime = 0;\n\n\twaveForm = options.waveForm;\n\tif (Array.isArray(waveForm)) {\n\t\twaveForm = {r: waveForm};\n\t}\n\tif (waveForm && (Array.isArray(waveForm.r) || Array.isArray(waveForm.i))) {\n\t\tif (waveForm.r) {\n\t\t\tarray = waveForm.r.slice();\n\t\t\tarray.unshift(0);\n\t\t\twaveForm.r = new Float32Array(array);\n\t\t}\n\t\tif (waveForm.i) {\n\t\t\tarray = waveForm.i.slice();\n\t\t\tarray.unshift(0);\n\t\t\twaveForm.i = new Float32Array(array);\n\t\t}\n\t\tif (!waveForm.r) {\n\t\t\twaveForm.r = new Float32Array(waveForm.i.length);\n\t\t}\n\t\tif (!waveForm.i) {\n\t\t\twaveForm.i = new Float32Array(waveForm.r.length);\n\t\t}\n\t\twaveForm = this.context.createPeriodicWave(waveForm.r, waveForm.i);\n\t}\n\n\tmod = this.context.createOscillator();\n\tmod.frequency.value = 5;\n\tmod.start();\n\tthis.mod = this.context.createGain();\n\tthis.mod.gain.value = 5;\n\tmod.connect(this.mod);\n\n\tthis.nodes = [];\n\tfor (i = 0; i < (options.c || 2); i++) {\n\t\tthis.nodes.push(this.createNode(waveForm, 5));\n\t}\n\tthis.currentNode = 0;\n\n\tthis.baseVolume = options.baseVolume || 1;\n\tthis.duration = options.duration || 0.5;\n\tthis.envelope = options.envelope || [0.3, 0.6, 1.2];\n}", "updateVideoTrack(state, track) {\n\t\tVue.set(state.self.tracks, 'audio', track)\n\t}", "function play(){\n\treadAndPlayNote(readInNotes(), 0, currentInstrument);\n}", "playCurrent() {\n\n let chord = this.sequence[this.playing]; // get the current chord / track from the sequence\n\n this.tracks[chord][this.mode].play(); // play the track\n\n }", "function introSwitch(){\n music.pause();\n italy.setVolume(0.05);\n italy.play();\n}", "toggleAirTracks () {\n const { entities } = this.viewer;\n const tracks = entities.getById('airTracks');\n if (tracks) {\n tracks.show = !tracks.show;\n } else {\n console.debug('cannot find tracks entity');\n }\n }", "function Musician(instrumentName) {\n this.uuid = uuidv4();\n this.instrumentName = instrumentName;\n this.instrumentSound = correspondingSound(this.instrumentName);\n\n /*\n * We will simulate instrument changes on a regular basis. That is something that\n * we implement in a class method (via the prototype)\n */\n // eslint-disable-next-line func-names\n Musician.prototype.update = function () {\n /*\n * Let's create the measure as a dynamic javascript object, \n * add the 2 properties (uuid and instrument), auditor will handle activeSince\n * and serialize the object to a JSON string\n */\n const musicianInfo = {\n uuid: this.uuid,\n sound: this.instrumentSound,\n };\n const payload = JSON.stringify(musicianInfo);\n\n /*\n* Finally, let's encapsulate the payload in a UDP datagram, which we publish on\n* the multicast address. All subscribers to this address will receive the message.\n*/\n const message = Buffer.from(payload);\n s.send(message, 0, message.length, protocol.PROTOCOL_PORT,\n protocol.PROTOCOL_MULTICAST_ADDRESS, () => {\n console.log(`Sending payload: ${payload} via port ${s.address().port}`);\n });\n };\n\n /*\n* Let's take and send a measure every 1 s (1000 ms)\n*/\n setInterval(this.update.bind(this), 1000);\n\n\n}", "function ChangeTheTime() {\n audio.currentTime = seekbar.value;\n \n \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This lets you inspect a contact after the solver is finished. This is useful / for inspecting impulses. / Note: the contact manifold does not include time of impact impulses, which can be / arbitrarily large if the substep is small. Hence the impulse is provided explicitly / in a separate data structure. / Note: this is only called for contacts that are touching, solid, and awake.
PostSolve(contact, impulse) { }
[ "set useContactForce(value) {}", "function pickContact() {\n var contacts = new Appworks.AWContacts(\n function (contact) {\n var output = \"\";\n if(contact == null) {\n output += \"No contact found\";\n } else {\n output += contactObjectToString(contact);\n }\n out(output);\n },\n function (contactError) {\n out(contactError);\n }\n );\n\n contacts.pickContact();\n}", "function callContact(){\n\t\n\t/**\n\t * Appcelerator Analytics Call\n\t */\n\tTi.Analytics.featureEvent(Ti.Platform.osname+\".details.callContactButton.clicked\");\n\t\n\t/**\n\t * Before we send the phone number to the platform for handling, lets first verify\n\t * with the user they meant to call the contact with an Alert Dialog\n\t * DOCS: http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.AlertDialog\n\t */\n\tvar dialog = Ti.UI.createAlertDialog({\n\t cancel: 0,\n\t buttonNames: ['Cancel', 'Ok'],\n\t message: \"Weet u zeker dat u wilt bellen naar \"+_args.phone+\" ?\"\n\t});\n\t\n\t/**\n\t * Event Handler associated with clicking the Alert Dialog, this handles the \n\t * actual call to the platform to make the phone call\n\t */\n\tdialog.addEventListener('click', function(e){\n\t\t if (e.index !== e.source.cancel){\n\t \n\t Ti.Platform.openURL(\"tel:\"+_args.phone);\n\t } \n\t});\n\t\n\t/**\n\t * After everything is setup, we show the Alert Dialog to the User\n\t */\n\tdialog.show();\n\t \n}", "function test_read_contact() {\n const kSomeID = 905;\n let contact = new Contact();\n contact.id = kSomeID;\n\n let done = false;\n contact.dba = {\n handleSync: function(aMethod, aModel, aOptions) {\n assert_equals(aMethod, \"read\");\n assert_equals(aModel.id, kSomeID);\n\n let retrieved = new Contact(kTestFields);\n aOptions.success(retrieved);\n done = true;\n },\n };\n\n contact.fetch();\n\n mc.waitFor(function() done);\n\n // Because the contact has been updated, we have to stringify, parse\n // and then grab the attributes like this. Lame, I know.\n assert_items_equal(JSON.parse(JSON.stringify(contact)).attributes,\n kResultingFields);\n}", "function handleUpdateContact() {\n updateContact(editContact);\n }", "function callContact(){\n $(\"#contact_body\").addClass(\"fadeIn animated\").stop().animate({opacity:100},200);\n}", "function patchContact(contact) {\n var patch = { id: contact.id };\n if (rnd(-10)) {\n if (addInPatch(patch, contact, 'firstname', faker.name.firstName())) {\n addInPatch(patch, contact, 'homeemail', createEmailAddress(contact.firstname, contact.lastname));\n addInPatch(patch, contact, 'workemail', createEmailAddress(contact.firstname, contact.lastname, createDomainName(contact.company)));\n }\n }\n else if (rnd(-10)) {\n addInPatch(patch, contact, 'homeemail', rnd(-3) ? null : createEmailAddress(contact.firstname, contact.lastname));\n }\n\n if (rnd(-10)) {\n addInPatch(patch, contact, 'homephone', rnd(-3) ? null : faker.phone.phoneNumber());\n }\n\n if (rnd(-10)) {\n addInPatch(patch, contact, 'avatar', rnd(-3) ? null : faker.image.imageUrl());\n }\n\n if (rnd(-10)) {\n addInPatch(patch, contact, 'homeaddress', rnd(-3) ? null : createAddress());\n }\n // updates professional data\n if (rnd(-10)) {\n var companyName = rnd(-3) ? null : faker.company.companyName();\n addInPatch(patch, contact, 'company', companyName);\n // nullifies the professional data\n if (companyName === null) {\n addInPatch(patch, contact, 'workwebsite', null);\n addInPatch(patch, contact, 'workemail', null);\n addInPatch(patch, contact, 'workaddress', null);\n addInPatch(patch, contact, 'workphone', null);\n }\n // updates the otherwise\n else {\n // builds the domain name\n var domainname = createDomainName(contact.company);\n if (addInPatch(patch, contact, 'workwebsite', rnd(-3) ? null : 'www.' + domainname)) {\n addInPatch(patch, contact, 'workemail', rnd(-3) ? null : createEmailAddress(contact.firstname, contact.lastname, domainname));\n }\n if (rnd(-5)) {\n addInPatch(patch, contact, 'workaddress', rnd(-3) ? null : createAddress(contact.company));\n }\n if (rnd(-5)) {\n addInPatch(patch, contact, 'workphone', rnd(-3) ? null : faker.phone.phoneNumber());\n }\n if (rnd(-8)) {\n addInPatch(patch, contact, 'workaddress', rnd(-3) ? null : createAddress(contact.company));\n }\n }\n }\n\n return patch;\n }", "function showContactInfo() {\n x$(\"#contact_name\")\n .html(contact.name.formatted || contact.displayName || \"Unknown Contact\");\n \n // display first email found\n if (contact.emails && contact.emails.length > 0) {\n x$(\"#contact_email\")\n .css({display: \"inline-block\"})\n .attr(\"href\", \"mailto:\" + contact.emails[0].value)\n .html(contact.emails[0].value.slice(0, 19) + \"...\");\n } else {\n x$(\"#contact_email\").css({display: \"none\"});\n }\n\n // display first phone number found\n if (contact.phoneNumbers && contact.phoneNumbers.length > 0) {\n x$(\"#contact_phone\")\n .html(contact.phoneNumbers[0].type + \": \" + contact.phoneNumbers[0].value)\n .attr(\"href\", \"tel:\" + contact.phoneNumbers[0].value)\n .css({display: \"inline-block\"});\n } else {\n x$(\"#contact_phone\").css({display: \"none\"});\n }\n\n display(\"#contact\");\n }", "function impulse(launchAngle, launchForce, timeApplied, projMass) {\n\tvar xVelocity = launchForce * Math.cos(launchAngle) * \t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\ttimeApplied / projMass; \t\t\t\t\t\t\t\t\t\n\tvar yVelocity = (-1 * launchForce * Math.sin(launchAngle) + G) * \t\t\n\t\t\t\t\t\t\t\t\t\ttimeApplied / projMass; \n\tvar velocity = new Vector(xVelocity, yVelocity);\n\treturn velocity;\n}", "function getContactInfo(json) {\n let str = \"\";\n str += appendField(json.Name);\n str += appendField(json.Address1);\n str += appendField(json.Address2);\n str += appendField(json.City, false);\n str += appendField(json.State, false);\n str += appendField(json.Zip);\n str += appendField(json.Country);\n str += appendField(json.Phone);\n str += appendField(json.Fax);\n str += appendField(json.Email);\n return str;\n}", "static get defaultContactOffset() {}", "addContact(contact){\n this.contactList.push(contact);\n super.notifyObservers(\"addContact\",contact);\n }", "function updateContacts(user, sphere, sessionData, view, res, req, isMobile){\n var contacts = sphere.getOtherMembers(user.id);\n\n // add the sphere members to invited user's contacts \n user.addSphereContacts(sphere.memberIds, function(members){\n\n sessionData.contacts = contacts;\n\n user.save(function(err){\n if(err){\n console.log(err);\n }else{\n //render feed \n if(isMobile == \"true\"){\n Session.respondJSON(res, sessionData);\n }else if(view == \"invite\"){\n res.redirect(\"/\");\n }else{\n Session.render(res, view, sessionData);\n }\n\n\n // store session data \n Session.storeData(req, sessionData);\n Session.sendCookie(res, user.email);\n }\n });\n sphere.save(function(err){console.log(err);})\n User.updateMemberContacts(members, user); \n }); \n}", "function test_saving_contact() {\n let done = false;\n let contact = new Contact(kTestFields);\n contact.dba = {\n handleSync: function(aMethod, aModel, aOptions) {\n aModel.id = 1; // Simulating we inserted a contact at row 1.\n assert_equals(aMethod, \"create\");\n assert_serializations_equal(aModel, kResultingFields);\n done = true;\n }\n };\n\n contact.save();\n mc.waitFor(function() done);\n\n done = false;\n // Ok, now let's try updating that contact.\n const kUpdatedName = [\"Something else\"];\n let updatedFields = _.extend({}, kResultingFields);\n updatedFields.name = kUpdatedName;\n\n contact.dba = {\n handleSync: function(aMethod, aModel, aOptions) {\n assert_equals(aMethod, \"update\");\n assert_serializations_equal(aModel, updatedFields);\n done = true;\n }\n };\n\n contact.save({name: kUpdatedName});\n mc.waitFor(function() done);\n}", "evaluateHit(ray, source) {\n\t\tlet superHit = super.evaluateHit(ray, source);\n\t\tif (superHit.isHit) {\n\t\t\tlet hitLocation = source.add(ray.scalarMult(superHit.distance));\n\t\t\tif (this.pointIsInThisTriangle(hitLocation)) {\n\t\t\t\treturn superHit;\n\t\t\t} else {\n\t\t\t\treturn new Contact(false);\n\t\t\t}\n\t\t} else {\n\t\t\treturn superHit;\n\t\t}\n\t}", "changeContact(newContactId,domElement){\n let selectedContact = this.getContactById(Number(newContactId));\n this.currentChatPartner = selectedContact;\n super.notifyObservers(\"contactChanged\",{contact:selectedContact,elem:domElement,userId:this.personnelId});\n }", "function b2ManifoldPoint()\n{\n\tthis.localPoint = new b2Vec2();\t\t///< usage depends on manifold type\n\tthis.normalImpulse = 0;\t\t\t\t///< the non-penetration impulse\n\tthis.tangentImpulse = 0;\t\t\t///< the friction impulse\n\tthis.id = new b2ContactID();\t\t///< uniquely identifies a contact point between two shapes\n}", "async initialStep(stepContext) {\n // Get the user details / state machine\n const unblockBotDetails = stepContext.options;\n\n // This sets the i18n local in a helper function \n setLocale(stepContext.context.activity.locale);\n\n // DEBUG\n // console.log('DEBUG UNBLOCKBOTDETAILS:', unblockBotDetails);\n\n // Set the text for the prompt\n const standardMsg = i18n.__('getPreferredMethodOfContactStepStandardMsg');\n\n getPreferredMethodOfContactStepStandardMsg\n\n\n // Set the text for the retry prompt\n const retryMsg = i18n.__('getPreferredMethodOfContactStepRetryMsg');\n \n // Check if the error count is greater than the max threshold\n if (unblockBotDetails.errorCount.getPreferredMethodOfContactStep >= MAX_ERROR_COUNT) {\n // Throw the master error flag\n unblockBotDetails.masterError = true;\n // End the dialog and pass the updated details state machine\n return await stepContext.endDialog(unblockBotDetails);\n }\n\n // Check the user state to see if unblockBotDetails.confirm_look_into_step is set to null or -1\n // If it is in the error state (-1) or or is set to null prompt the user\n // If it is false the user does not want to proceed\n if (unblockBotDetails.getPreferredMethodOfContactStep === null || unblockBotDetails.getPreferredMethodOfContactStep === -1) {\n // Setup the prompt message\n var promptMsg = '';\n\n // The current step is an error state\n if (unblockBotDetails.getPreferredMethodOfContactStep === -1) {\n promptMsg = retryMsg;\n }\n else {\n promptMsg = standardMsg;\n }\n const promptOptions = ['Email', 'Text message', 'Both'];\n\n const promptDetails = {\n prompt: ChoiceFactory.forChannel(stepContext.context, promptOptions, promptMsg),\n };\n\n return await stepContext.prompt(TEXT_PROMPT, promptDetails);\n }\n else {\n return await stepContext.next(false);\n }\n }", "function NoContactsLeft() {\n console.log(\"Ran out of contacts\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The villager just waits for the night to end
function villagerAction(){ dataStore.waitForAll("nightWait", postNightPhase, "$null"); document.getElementById("notice").innerHTML = "Waiting for night to end..."; document.getElementById("notice").style.display = "block"; }
[ "function waitForServantStartup(adviseLaunchInfo) {\n var waitLoop = setInterval(function() {\n monitorBulletinBoard(adviseLaunchInfo, waitLoop);\n }, 2000);\n}", "async afterBrowserStopped() {}", "async enterEndPhase() {\n let message = \"Het spel is bijna gedaan. Kom nu naar de tuin!\";\n for (const [key, game] of Object.entries(this.games)) {\n game.currentLocation = this.endLocation;\n }\n console.log(\"Starting end phase of game.\");\n let teamsArray = this.getTeamsAsArray();\n await Util.asyncForEach(teamsArray, async team => {\n await this.endLocation.onArrivalAtLocation(this, team.game, null);\n });\n console.log(\"End phase of game: messages sent to all teams.\");\n }", "async waitForBlock(goal) {\n let height = await this.height();\n while (height < goal) {\n await sleep(1000);\n height = await this.height();\n }\n return height;\n }", "function WaitStatus()\r\n\t\t{\r\n\t\t\twindow.status = \" \";\r\n\t\t}", "waitFor_raceMeetingNewsVideo_ContentDate() {\n if(!this.raceMeetingNewsVideo_ContentDate.isVisible()){\n this.raceMeetingNewsVideo_ContentDate.waitForVisible(5000);\n }\n }", "wait() {\n on (EPass ePass) : \n\t\t{\n\t\t\tif( m_eTeleportType == TELEPORT_DEFAULT )\n\t\t\t{\n\t\t\t\tif (m_penTarget!=NULL && m_bActive) \n\t\t\t\t{\n\t\t\t\t\tif (m_bPlayersOnly && !IsOfClass( ePass.penOther, &CPlayer_DLLClass)) {\n\t\t\t\t\t\tresume;\n\t\t\t\t\t}\n\t\t\t\t\tTeleportEntity(ePass.penOther, m_penTarget->GetPlacement());\n\t\t\t\t\tif (m_bForceStop && (ePass.penOther->GetPhysicsFlags()&EPF_MOVABLE) ) \n\t\t\t\t\t{\n\t\t\t\t\t((CMovableEntity*)&*ePass.penOther)->ForceFullStop();\n\t\t\t\t\t}\n\t\t\t\t\tstop;\n\t\t\t\t}\n\t\t\t\tresume;\n\t\t\t}\n\t\t\telse \n\t\t\tif( m_eTeleportType == TELEPORT_NETWORK )\n\t\t\t{\n\t\t\t\tif( m_bActive )\n\t\t\t\t{\n\t\t\t\t\t// HARD CODING ---wooss 060515-------------------------------------->>\n//\t\t\t\t\tif(m_eTeleportType == TELEPORT_DEFAULT) { m_iTeleportIndex = 999; }\n\t\t\t\t\t// -----------------------------------------------------------------<<\n\t\t\t\t\t\n\t\t\t\t\tif( !IsOfClass( ePass.penOther, &CPlayer_DLLClass))\n\t\t\t\t\t{\n\t\t\t\t\t\tresume;\n\t\t\t\t\t}\n\t\t\t\t\tASSERT( m_iTeleportIndex != -1 && \"Invalid Teleport Index!\" );\n\t\t\t\t\t// EDIT : BS : BEGIN : 텔레포트 보내고 Lock\n\t\t\t\t\tCPlayer* pPlayer = (CPlayer*)CEntity::GetPlayerEntity(0); // 캐릭터 자신\n\t\t\t\t\tif (pPlayer)\n\t\t\t\t\t{\n\t\t\t\t\t\tpPlayer->m_bRcvAtMsg\t\t\t= FALSE;\n\t\t\t\t\t\tpPlayer->m_bLockMove\t\t\t= TRUE;\n\t\t\t\t\t\tpPlayer->m_bReserveMove\t\t\t= FALSE;\n\t\t\t\t\t\tpPlayer->StopMove();\n\t\t\t\t\t}\n\t\t\t\t\t// EDIT : BS : END : 텔레포트 보내고 Lock\n\t\t\t\t\tFLOAT tmCurTime = _pTimer->GetHighPrecisionTimer().GetMilliseconds();\n\t\t\t\t\tif (tmCurTime - m_tmGoZoneSendedTime > 1000)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_tmGoZoneSendedTime = tmCurTime;\n\t\t\t\t\t\t_pNetwork->SendWarpTeleport( m_iTeleportIndex );\n\t\t\t\t\t}\n\t\t\t\t\tstop;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tresume;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif( m_bActive )\n\t\t\t\t{\n\t\t\t\t\tif( !IsOfClass( ePass.penOther, &CPlayer_DLLClass))\n\t\t\t\t\t{\n\t\t\t\t\t\tresume;\n\t\t\t\t\t}\n\t\t\t\t\tASSERT( m_iTeleportIndex != -1 && \"Invalid Teleport Index!\" );\n\t\t\t\t\tconst int iWorldNum = m_iTeleportIndex;\t\t\t\t\t\t// 월드 번호.\n\t\t\t\t\tconst int iExtraNum = m_iTeleportExtIndex;\t\t\t\t\t// Extra 번호.\n\n\t\t\t\t\t// [091120: selo] 보낸 시간 후 1초 이전에는 서버에 보내지 않는다\n\t\t\t\t\tFLOAT tmCurTime = _pTimer->GetHighPrecisionTimer().GetMilliseconds();\n\t\t\t\t\tif( tmCurTime - m_tmGoZoneSendedTime > 1000 )\n\t\t\t\t\t{\n\t\t\t\t\t\tm_tmGoZoneSendedTime = tmCurTime;\n\t\t\t\t\t\t_pNetwork->GoZone(iWorldNum, iExtraNum);\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\tstop;\n\t\t\t\t}\n\t\t\t\tresume;\n\t\t\t}\n }\n on (EActivate) : {\n SetFlagOn(ENF_PROPSCHANGED);\n if (_pNetwork->IsServer()) {\n SendEvent(ETeleportActivate(),TRUE);\n }\n resume;\n }\n on (ETeleportActivate) : {\n m_bActive = TRUE;\n\n\t\t if (m_penParticle != NULL)\n\t\t {\n\t\t\t m_penParticle->SendEvent(EActivate());\n\t\t }\n resume;\n }\n on (EDeactivate) : {\n SetFlagOn(ENF_PROPSCHANGED);\n if (_pNetwork->IsServer()) {\n SendEvent(ETeleportDeactivate(),TRUE);\n }\n resume;\n }\n on (ETeleportDeactivate) : {\n m_bActive = FALSE;\n\t\t \n\t\t if (m_penParticle != NULL)\n\t\t {\n\t\t\t m_penParticle->SendEvent(EDeactivate());\n\t\t }\n resume;\n }\n otherwise() : {\n resume;\n };\n }", "function SlowDown() {\r\n if (IncriseMillisecoundsToWait < 5000) {\r\n IncriseMillisecoundsToWait += 200;\r\n clearInterval(IDDisplayFight);\r\n if (ResponseObj.Player.Alive && ResponseObj.Enemy.Alive) {\r\n IDDisplayFight = setInterval(function () { DisplayFight(); }, IncriseMillisecoundsToWait);\r\n }\r\n else {\r\n IDDisplayFight = DisplayFightLastRoundWithEndAnimations();\r\n }\r\n }\r\n}", "function ksfHelp_mainTourEnd()\n{\n\tksfHelp_mainTour.end();\n}", "function awaitingCiteL34ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(){;}", "function C101_KinbakuClub_RopeGroup_WaitingForFriend() {\n\tif (C101_KinbakuClub_RopeGroup_FriendWaitCount == 0) C101_KinbakuClub_RopeGroup_FriendWaitCount = CurrentTime + 300000;\n\tC101_KinbakuClub_RopeGroup_FriendWaitCount++\n\tif (CurrentTime >= C101_KinbakuClub_RopeGroup_FriendWaitCount && !C101_KinbakuClub_RopeGroup_CassiVistied) {\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 662;\n\t\tC101_KinbakuClub_RopeGroup_LoadCassi();\n\t\tC101_KinbakuClub_RopeGroup_CassiVistied = true;\n\t\tif (GameLogQuery(CurrentChapter, CurrentActor, \"MetCassi\")) {\n\t\t\tOverridenIntroText = GetText(\"CassiAppears\");\n\t\t} else OverridenIntroText = GetText(\"NewGirlAppears\");\n\t} else {\n\t\tCurrentTime = CurrentTime + 60000;\n\t\tif (CurrentTime >= C101_KinbakuClub_RopeGroup_FriendWaitCount) CurrentTime = CurrentTime + 60000;\n\t}\n}", "buildLoop() {\n this.toGoPosition();\n\n setTimeout(() => {\n this.toStopPosition();\n }, 4000);\n }", "function quitRound() {\n clearInterval(timer);\n endRound();\n}", "function SpeedUpp() {\r\n if (IncriseMillisecoundsToWait > 200) {\r\n IncriseMillisecoundsToWait -= 200;\r\n clearInterval(IDDisplayFight);\r\n if (ResponseObj.Player.Alive && ResponseObj.Enemy.Alive) {\r\n IDDisplayFight = setInterval(function () { DisplayFight(); }, IncriseMillisecoundsToWait);\r\n }\r\n else {\r\n IDDisplayFight = DisplayFightLastRoundWithEndAnimations();\r\n }\r\n }\r\n}", "async function waitForZokrates() {\n logger.info('checking for zokrates_worker');\n try {\n while (\n // eslint-disable-next-line no-await-in-loop\n (await axios.get(`${config.PROTOCOL}${config.ZOKRATES_WORKER_HOST}/healthcheck`)).status !==\n 200\n ) {\n logger.warn(\n `No response from zokratesworker yet. That's ok. We'll wait three seconds and try again...`,\n );\n // eslint-disable-next-line no-await-in-loop\n await new Promise(resolve => setTimeout(resolve, 3000));\n }\n } catch (err) {\n logger.error(err);\n process.exit(1);\n }\n logger.info('zokrates_worker reports that it is healthy');\n}", "async function wait() {\n await driver.wait(until.elementIsEnabled(elCommand), 5000, \"CLI still not enabled after 5s\");\n }", "function workoutFinished(){\n\n }", "async function executeWeightCommand() {\n console.log('Command recognized. Computing...');\n await new Promise(r => setTimeout(r, 5000));\n console.log('> S S 100 g');\n}", "waitFor_raceMeetingNewsVideo_ContentTitle() {\n if(!this.raceMeetingNewsVideo_ContentTitle.isVisible()){\n this.raceMeetingNewsVideo_ContentTitle.waitForVisible(5000);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses a given value into a float number.
function safeParseFloat(value) { if (!value) { return 0.00; } if (ok(value, tyString)) { return parseFloat(value); } if (ok(value, tyNumber)) { return value; } return 0.00; }
[ "function float(val, def)\n {\n if (isNaN(val)) return def;\n\n return parseFloat(val);\n }", "function checkIfFloat(value) {\r\n if (value.toString().indexOf('.', 0) > -1) {\r\n return parseFloat(value).toFixed(2);\r\n }\r\n else {\r\n return value;\r\n }\r\n}", "function moeda2float(moeda){\r\n\r\nmoeda = moeda.replace(\".\",\"\");\r\n\r\nmoeda = moeda.replace(\",\",\".\");\r\n\r\nreturn parseFloat(moeda);\r\n\r\n}", "function readFloat(x, f)\n//\n// Input: none\n// Output: x = pointer to a float variable\n// Purpose: reads a floating point value from a hot start file\n//\n{\n // --- read a value from the file\n fread(x, sizeof(float), 1, f);\n\n // --- test if the value is NaN (not a number)\n if ( (x) != (x) )\n {\n report_writeErrorMsg(ERR_HOTSTART_FILE_READ, \"\");\n (x) = 0.0;\n return FALSE;\n }\n return TRUE;\n}", "function toFloat(n, fallback) {\n\tif (fallback === undefined) fallback = 0.0;\n\tn = parseFloat(n);\n\tif (isNaN(n)) n = fallback;\n\treturn n;\n}", "function InputFloat(label, v, step = 0.0, step_fast = 0.0, format = \"%.3f\", extra_flags = 0) {\r\n const _v = import_Scalar(v);\r\n const ret = bind.InputFloat(label, _v, step, step_fast, format, extra_flags);\r\n export_Scalar(_v, v);\r\n return ret;\r\n }", "function isValidUFloat(s) {\n return s.match(/^\\s*([0-9]+(\\.[0-9]*)?|\\.[0-9]+)\\s*$/)\n }", "function getNumberFromValue(name, value) {\n if (statsNameBlackList[name])\n return NaN;\n return parseFloat(value);\n}", "function toFloat(x) {\n return x / 255;\n}", "function parseFloats(str) {\r\n var floats = [];\r\n var regex = /[+-]?(?:(?:\\d+\\.?\\d*)|(?:\\d*\\.?\\d+))(?:[eE][+-]?\\d+)?/g;\r\n var match;\r\n while ((match = regex.exec(str))) {\r\n floats.push(parseFloat(match[0]));\r\n }\r\n return floats;\r\n }", "function n(value) {\n this.value = parseFloat(value)\n}", "function toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n const sign = value < 0 ? -1 : 1;\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}", "function validate_float(checkprice){\n\nif(/^[+-]?\\d+(\\.\\d+)?$/.test(checkprice)){\n\nreturn true;\n\n}else{\n return false;\n}\n\n}", "function parseFloatForInput(id){\n\t\treturn parseFloat(document.getElementById(id).value, 10);\n\t}", "function validate(n) {\n\tvar x = parseFloat(n);\n\treturn (!isNaN(x) && isFinite(x)) ? x : null;\n}", "function InputFloat3(label, v, format = \"%.3f\", extra_flags = 0) {\r\n const _v = import_Vector3(v);\r\n const ret = bind.InputFloat3(label, _v, format, extra_flags);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }", "function _parseF(strIn) {\n // let [num, inMeters] = _parse(strIn); --- This line crashes for some reason ... WHY???\n // --- TypeError: _parse is not a function\n // if (inMeters === undefined) {\n // return num;\n // }\n let num = _parse(strIn);\n if (typeof num === 'number') {\n return num;\n }\n return num[0] / METERS_PER_FOOT;\n }", "[symbols.call](obj=0.0)\n\t{\n\t\tif (typeof(obj) === \"string\")\n\t\t\treturn parseFloat(obj);\n\t\telse if (typeof(obj) === \"number\")\n\t\t\treturn obj;\n\t\telse if (obj === true)\n\t\t\treturn 1.0;\n\t\telse if (obj === false)\n\t\t\treturn 0.0;\n\t\tthrow new TypeError(\"float() argument must be a string or a number\");\n\t}", "function isAcceptableFloat(num) {\n const str = num.toString();\n return str.indexOf('.') === str.length - 2;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is an alias for `.declareType()`.
createOrReplaceType(name) { return this.declareType(name); }
[ "visitType_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function addType() {\n\t\tvar args = extract(\n\t\t\t{ name: 'name', test: function(o) { return typeof o === 'string'; } },\n\t\t\t{ name: 'type', parse: function(o) {\n\t\t\t\treturn (o instanceof Type) ? o : new Type(this.name || o.name, o);\n\t\t\t} }\n\t\t).from(arguments);\n\n\t\ttypeList.push(args.type);\n\t}", "enterTypeImportOnDemandDeclaration(ctx) {\n\t}", "static registerType(type) { ShareDB.types.register(type); }", "_createType (name) {\n\n\t\tif ( name !== undefined) AssertUtils.isString(name);\n\n\t\tconst getNoPgTypeResult = NoPgUtils.get_result(NoPg.Type);\n\n\t\treturn async data => {\n\n\t\t\tdata = data || {};\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tdata.$name = '' + name;\n\t\t\t}\n\n\t\t\tconst rows = await this._doInsert(NoPg.Type, data);\n\n\t\t\tconst result = getNoPgTypeResult(rows);\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tawait this.setupTriggersForType(name);\n\t\t\t}\n\n\t\t\treturn result;\n\n\t\t};\n\n\t}", "static define() {\n return new AnnotationType()\n }", "function TTypeParam(name) {\n this.name = name;\n}", "static from(type, value) {\n return new Typed(_gaurd, type, value);\n }", "enterTypeVariable(ctx) {\n\t}", "typeSpec() {\n const token = this.currentToken;\n if (this.currentToken.type === tokens.INTEGER) {\n this.eat(tokens.INTEGER);\n } else if (this.currentToken.type === tokens.REAL) {\n this.eat(tokens.REAL);\n }\n return new Type(token);\n }", "encodeType(name) {\n const result = this.#fullTypes.get(name);\n (0, index_js_4.assertArgument)(result, `unknown type: ${JSON.stringify(name)}`, \"name\", name);\n return result;\n }", "enterSingleTypeImportDeclaration(ctx) {\n\t}", "function InferTypes () {\n ASTTransform.call(this);\n this.varDefs = {};\n this.fnSignatures = {};\n this.fnTypeHints = {};\n this.fnRenaming = {};\n this.runAgain = false;\n}", "exitTypeImportOnDemandDeclaration(ctx) {\n\t}", "visitType_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "enterTypeAlias(ctx) {\n\t}", "set type(aValue) {\n this._logger.debug(\"type[set]\");\n this._type = aValue;\n }", "function parseType(parser) {\n var start = parser.token.start;\n var type = undefined;\n if (skip(parser, _lexer.TokenKind.BRACKET_L)) {\n type = parseType(parser);\n expect(parser, _lexer.TokenKind.BRACKET_R);\n type = {\n kind: _kinds.LIST_TYPE,\n type: type,\n loc: loc(parser, start)\n };\n } else {\n type = parseNamedType(parser);\n }\n if (skip(parser, _lexer.TokenKind.BANG)) {\n return {\n kind: _kinds.NON_NULL_TYPE,\n type: type,\n loc: loc(parser, start)\n };\n }\n return type;\n}", "function setType(itemType){\n\ttype = itemType;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an array of album ids of the artist.
function getAlbums(artistId) { var sp = getService(); var url = "https://api.spotify.com/v1/artists/" + artistId + "/albums"; var response = refreshToken(sp, function() { return UrlFetchApp.fetch(url, { headers: { Authorization: 'Bearer ' + sp.getAccessToken(), } }); }); var result = JSON.parse(response.getContentText()); var itemIds = getValues(result, "id"); // ids of all items var itemTypes = getValues(result, "type"); // looking for items of type "album" var albumIds = []; // ids of items of type "album" for (var i = 0; i < itemIds.length; i++) if (itemTypes[i] == "album") albumIds.push(itemIds[i]); return albumIds; }
[ "function getArtistIDArray(artist_array) {\n\tvar artist_id_array = []\n\treturn new Promise((resolve, reject) => {\n\t\tfor (var index = 0; index < artist_array.length; ++index) {\n\t\t\tsearchForArtist(artist_array[index]).then(function (data) {\n\t\t\t\tartist_id_array.push(data)\n\t\t\t\tresolve(artist_id_array);\n\t\t\t})\n\t\t}\n\t});\n\treturn artist_id_array;\n}", "function getMainArtists(songs) {\n return songs.map(song => {\n return song.artist.split(' featuring')[0];\n });\n}", "static getAlbums() {\n let albums;\n if (localStorage.getItem('albums') === null) {\n albums = [];\n } else {\n albums = JSON.parse(localStorage.getItem('albums'));\n }\n\n return albums;\n }", "function getSongsByArtist(songs, artist) {\n return songs.filter(song => song.artist === artist);\n}", "getBoughtAlbums () {\n return music.getBoughtAlbums().then((response) => {\n return response.data\n })\n }", "getAlbumSongs (idAlbum, options) {\n if (!options){ // Default Order by track\n options = { order: 'track'}\n // options.debug = true\n }\n return this.Restangular.one('albums', idAlbum).all('songs')\n \t.getList(options)\n \t.then(\tresponse => response )\n }", "function listArtists(event) {\n var theArtists = [];\n // console.log(event);\n for (let a = 0; a < event.artist.length; a++) {\n for (let b = 0; b < event.artist[a].length; b++) {\n var singleArtistListingObject = {\n link: event.artist[a][b].link,\n name: event.artist[a][b].name,\n };\n\n var singleArtist =\n '<div class=\"artist artist-' +\n singleArtistListingObject.name +\n '\">&nbsp;' +\n // '\">&nbsp;<a href=\"' +\n // singleArtistListingObject.link +\n // '\" target=\"_blank\">' +\n singleArtistListingObject.name +\n // \"</a></div>\";\n ' &nbsp;</div>';\n\n // push artists to array\n theArtists += singleArtist;\n }\n theArtists.toString(',');\n // theArtists.split(',');\n // console.log(typeof theArtists, theArtists);\n return theArtists;\n }\n}", "function getSongsByArtist(arr, name){\n\treturn arr.filter(function(val){\n\t\treturn val.artist === name;\n\t});\n\n}", "async function getArtistsByOwnerId(id) {\n const [ results ] = await mysqlPool.query(\n 'SELECT * FROM artist WHERE ownerid = ?',\n [ id ]\n );\n return results;\n}", "getPhotoIDs(placeDetails) {\r\n let photoIDs = [];\r\n if (placeDetails.hasOwnProperty('photos')) {\r\n for (var i = 0; i < placeDetails.photos.length; i++) {\r\n photoIDs.push(placeDetails.photos[i].photo_reference);\r\n }\r\n }\r\n return photoIDs;\r\n }", "function getSongCountByArtist(arr){\n\tvar listArtists = arr.map(function(val){\n\t\treturn val.artist;\n\t}); \n\tvar allArtists = listArtists.map(function(val){\n\t\tvar allSingers = val.split(\" featuring \"); \n return allSingers[0];\n\t});\n\treturn allArtists.reduce(function(acc,val){\n\t\tacc[val] = (acc[val] || 0)+1;\n\t\treturn acc;\n\t},{});\n}", "setArtwork(playlist_tracks) {\n debugger;\n var artCollection = [];\n if (playlist_tracks != undefined) {\n artCollection = Object.values(playlist_tracks).map(track => {\n return track.album_art;\n });\n }\n return this.createArtwork(artCollection);\n }", "function playlistFromArtists(input) {\n\treturn new Promise((resolve, reject) => {\n\t\tvar artist_array = input.split(',');\n\t\tgetArtistIDArray(artist_array).then(function (artist_id_array) {\n\t\t\tconsole.log('artist array is: ' + artist_id_array)\n\t\t\tgetPlaylist(artist_id_array).then(function (playlist) {\n\t\t\t\treturn resolve(playlist);\n\t\t\t})\n\t\t}).catch(function (err) {\n\t\t\tconsole.error(err)\n\t\t});\n\t});\n}", "function allBy(artist){\n console.log(\"inside function allBy \", artist);\n // - when run, this function should return an array of all records in \"collection\"-\n // - that are by the given artist\n let resultArray = [];\n\n for(let i = 0; i < vinyl_collection.length; i++ ){\n if(vinyl_collection[i].artist === artist ){\n resultArray.push(vinyl_collection[i]);\n }\n }\n return resultArray;\n}", "getObjectIDs() {\n let res = [];\n this.state.selectedCourses.map(function(info) {\n res.push(info._id);\n })\n return res;\n }", "async function _extract_image_ids (variants){\n if (variants.length == 0 || typeof variants === 'undefined' || variants === null || !Array.isArray(variants)){\n throw new VError(`variants parameter not usable`);\n }\n\n let ids = [];\n\n /*\n * Defaults to plucking the first image. This is fine now but in a future where\n * variants may have multiple images we'll need to do better\n */\n\n for (let i = 0; i < variants.length; i++){\n if (variants[i].image_ids.length > 0){\n ids.push(variants[i].image_ids[0]);\n }\n }\n\n return ids;\n}", "async function getRelatedArtists(bearerAccessToken, artistId) {\n var myHeaders = new Headers();\n myHeaders.append(\"Authorization\", \"Bearer \" + bearerAccessToken);\n\n var requestOptions = {\n method: 'GET',\n headers: myHeaders,\n redirect: 'follow'\n };\n\n return fetch(\"https://api.spotify.com/v1/artists/\" + artistId + \"/related-artists\", requestOptions)\n .then(response => response.json())\n .then(result => result)\n .catch(error => console.log('error', error));\n }", "function getArtists(id) {\n var access_token = getAccessToken();\n fetch('https://api.spotify.com/v1/me/top/artists?time_range=medium_term&limit=10', {\n headers: {\n 'Authorization': 'Bearer ' + access_token\n }\n }).then(res => res.json()).then(data => {\n console.log(\"artist data\");\n console.log(data);\n getTracks(id, data)\n })\n}", "function getSongCountByArtist(songs) {\n return songs.reduce((obj, song) => {\n let artist = song.artist;\n artist in obj ? obj[artist]++ : obj[artist] = 1;\n return obj;\n }, {});\n}", "loadAlbumTracks() {\n this._ApiFactory.getAlbumsTracks(this.albumId).query({}, (response) => {\n\n const tracks = [];\n response.items.forEach((i) => {\n const track = {\n name: i.name,\n images: i.images,\n duration: this.convertToMinutesSeconds(i.duration_ms)\n }\n tracks.push(track);\n });\n this.tracks = tracks;\n\n }, (response) => {\n if (response.status === 401 || response.status === 403 || response.status === 419 || response.status === 440)\n this._JWT.login();\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ENDS Function to validate site_privacy / Function to validate select_theme
function ssw_js_validate_theme() { var theme_button = document.getElementById('ssw-steps').select_theme; var theme_button_count = -1; for (var i=theme_button.length-1; i > -1; i--) { if (theme_button[i].checked) {theme_button_count = i; i = -1;} } if (theme_button_count > -1) { document.getElementById("ssw-themes-error").style.display="none"; return true; } else { document.getElementById("ssw-themes-error-label").innerHTML=ssw_theme_error_msg; document.getElementById("ssw-themes-error").style.display="block"; return false; } }
[ "function ssw_js_validate_terms() {\n \n var terms_checkbox = document.getElementById('ssw-steps').site_terms;\n \n if (terms_checkbox.checked) {\n document.getElementById(\"ssw-site-terms-error\").style.display=\"none\"; \n return true;\n }\n else {\n document.getElementById(\"ssw-site-terms-error-label\").innerHTML=ssw_terms_error_msg;\n document.getElementById(\"ssw-site-terms-error\").style.display=\"block\"; \n return false;\n }\n}", "function policy_name_is_predefined() {\n var cf = document.forms[0];\n var i;\n\n if(cf.category.selectedIndex == CATEGORY_APP || cf.category.selectedIndex == CATEGORY_GAME) {\n if (cf.apps.options.selectedIndex != cf.apps.options.length-1\n && cf.name.value == cf.apps.options[cf.apps.selectedIndex].text) {\n /* User selected predefined rules no need to check */\n return false;\n }\n }\n\n for(i=0; i<predef_qos.length; i++) {\n if(cf.name.value == predef_qos[i][_name]) {\n return true;\n }\n }\n return false;\n}", "function govern_VWC3(){\n if( ['Monthly', 'Yearly'].includes($('input[name=AGG3]:checked').val()) ){\n $('input[name=CONC_FLUX3][value=VWC]').removeAttr('disabled').siblings().css('color', '#485580');\n } else {\n $('input[name=CONC_FLUX3][value=VWC]').attr('disabled', 'disabled').siblings().css('color', 'gray');\n }\n }", "function pageValidate(){\n var txtFieldIdArr = new Array();\n txtFieldIdArr[0] = \"tf1_SysName,\"+LANG_LOCALE['12134'];\n if (txtFieldArrayCheck(txtFieldIdArr) == false) \n return false;\n \n if (alphaNumericValueCheck (\"tf1_SysName\", '-', '') == false) \n return false;\n\n if (isProblemCharArrayCheck(txtFieldIdArr, \"'\\\" \", NOT_SUPPORTED) == false) \n return false;\n}", "function isValidSkin(attr)\n{ \n if (attr == 'isLive')\n {\n if(VIDEO_LIVE_FEED.getCheckedState())\n {\n if(VIDEO_SKIN_NAMES.getValue().indexOf(\"Halo\") == -1)\n {\n alert(MSG_SelectHaloSkinForVCS);\n return false;\n }\n }\n }\n return true;\n}", "function valReason(frm){\n\tvar passed=true;\n\tvar errorCount=0;\n\tvar r= frm.reason.value;\n\t\n\tif(r==\"\" || r==null){\n\t\terrorCount++;\n\t\tdocument.getElementById(\"reason_err\").innerHTML=\"You must select a reason to deny the post.\";\n\t}\n\t\n\t\tif(errorCount !=0)\n\t{\n\t\treturn false;\n\t}\n}", "function validateAdsAddPageForm(formname,isimage)\n{\n var frmAdType = $(\"#\"+formname+\" input[type='radio']:checked\").val();\n \n if(frmAdType=='html'){\n if($('#frmTitle').val() == ''){\n alert(TIT_REQ);\n $('#frmTitle').focus()\n return false;\n }else if($('#frmHtmlCode').val() == ''){\n alert(HTML_REQ);\n $('#frmHtmlCode').focus()\n return false;\n }\n }else{ \n if($('#frmTitle').val() == ''){\n alert(TIT_REQ);\n $('#frmTitle').focus()\n return false;\n }else if($('#frmAdUrl').val() == ''){\n alert(URL_LINK_REQ);\n $('#frmAdUrl').focus()\n return false;\n }else if(IsUrlLink($('#frmAdUrl').val()) ==false){ \n alert(ENTER_VALID_LINK);\n $('#frmAdUrl').select();\n return false;\n }\n \n if(isimage==0){\n if($('#frmImg').val() == ''){\n alert(IMG_REQ);\n $('#frmImg').focus()\n return false;\n }\n }\n if($('#frmImg').val() != ''){\n var ff = $('#frmImg').val();\n var exte = ff.substring(ff.lastIndexOf('.') + 1);\n var ext = exte.toLowerCase();\n if(ext!='jpg' && ext!='jpeg' && ext!='gif' && ext!='png'){\n alert(ACCEPTED_IMAGE_FOR);\n $('#frmImg').focus();\n return false;\n }\n \n }\n }\n}", "function isPageObjValid (PageObj)\n{\n\tvar bCommerce = IsCommerceEnabled();\n\tvar bService = IsServiceEnabled();\n\tvar licenseFor = PageObj[gLICENSE_FOR];\n\tbValid = false;\n\tif (licenseFor.toLowerCase() == \"all\" ||\n\t\t(licenseFor.toLowerCase() == \"powercommerce\" && bCommerce) ||\n\t\t(licenseFor.toLowerCase() == \"powerservice\" && bService))\n\t\tbValid = true;\n\t\t\n\treturn (bValid);\n}", "function validateWeb() {\n var web = document.getElementById(\"website\").value;\n if (web == \"\" || web == null) {\n alert(\"Website must be filled\");\n return false;\n }\n if (/[-a-zA-Z0-9@:%_\\+.~#?&//=]{2,256}\\.[a-z]{2,4}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)?/gi.test(studentEnrollment.website.value)) {\n validateImage();\n }\n else {\n alert(\"Invalid web address!\");\n document.getElementById(\"website\").focus();\n return false;\n }\n}", "function validateCMSAddPageForm(formname)\n{\n \n if($('#frmDisplayPageTitle').val() == '')\n {\n alert(PAGE_DISP_TITLE);\n $('#frmDisplayPageTitle').focus()\n return false;\n }\n if($('#frmPageTitle').val() == '')\n {\n alert(PAGE_TIT_REQ);\n $('#frmPageTitle').focus()\n return false;\n } \n if($('#frmPageDisplayOrder').val() == '' )\n {\n alert(PAGE_ORDER_REQ);\n $('#frmPageDisplayOrder').focus()\n return false;\n } \n \n}", "function ssw_js_validate_site_address() {\n\n var site_address_regex = /^[a-zA-Z0-9]+[a-zA-Z0-9_]*$/;\n site_address = document.getElementById('ssw-steps').site_address.value;\n\n if (!site_address_regex.test(site_address)) {\n document.getElementById(\"ssw-site-address-error-label\").innerHTML=ssw_site_address_invalid_msg;\n document.getElementById(\"ssw-site-address-error\").style.display=\"block\"; \n return false;\n }\n else {\n document.getElementById(\"ssw-site-address-error\").style.display=\"none\";\n return true;\n }\n}", "function validaCiudad(){\r\n\t\tvar concepto = $(\"#concepto option:selected\").text();\r\n\t\t\r\n\t\tif((/Comidas/.test(concepto))){\r\n\t\t\tasignaClass(\"ciudad\",\"req\");\r\n\t\t\tmostrarElemento(\"tr_ciudad\");\r\n\t\t}else\r\n\t\t\tocultarElemento(\"tr_ciudad\");\r\n\t}", "function CheckSubscriptionOptions() {\r\n if (!document.getElementById(\"subscribeNewsletter\").checked && !document.getElementById(\"subscribeBreakingNews\").checked) {\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n}", "function checkRefopts ( )\n {\n \tparams.reftypes = getCheckList(\"pm_reftypes\");\n \tif ( params.reftypes == \"auth,class\" ) params.reftypes = 'taxonomy';\n \telse if ( params.reftypes == \"auth,class,ops\" ) params.reftypes = 'auth,ops';\n \telse if ( params.reftypes == \"auth,class,ops,occs,colls\" ) params.reftypes = 'all'\n \telse if ( params.reftypes == \"auth,ops,occs,colls\" ) params.reftypes = 'all'\n \tupdateFormState();\n }", "function fnCookieWarning(){\r\n if(fnGetConfig(\"Footer_Cookie_Policy\")){\r\n\r\n function createCookie(name, value, days){\r\n if(days){\r\n var date=new Date();\r\n date.setTime(date.getTime()+(days*24*60*60*1000));\r\n var expires=\"; expires=\"+ date.toGMTString();\r\n }else var expires=\"\";\r\n document.cookie=name +\"=\"+ value + expires +\"; path=/\";\r\n }\r\n\r\n function readCookie(name){\r\n var nameEQ=name +\"=\",\r\n ca=document.cookie.split(';');\r\n for(var i=0;i<ca.length;i++){\r\n var c=ca[i];\r\n while(c.charAt(0)==' ')c=c.substring(1,c.length);\r\n if(c.indexOf(nameEQ)==0)return c.substring(nameEQ.length,c.length);\r\n }\r\n return null;\r\n }\r\n\r\n function eraseCookie(name){createCookie(name,\"\",-1);}\r\n\r\n var cookieBody=document.getElementsByTagName(\"BODY\")[0],\r\n cookieLaw=document.getElementById(\"cookie-law\"),\r\n cookieURL=document.getElementById(\"cookie-url\"),\r\n cookieName=\"cookiewarning\",\r\n cookieWarning=document.createElement(\"div.\"+ cookieName);\r\n \r\n function setCookieWarning(active){(!!active)?cookieBody.classList.add(cookieName):cookieBody.classList.remove(cookieName);}\r\n\r\n cookieURL.href=\"/page,arq,cookie-policy-\"+ (\"0\"+FC$.Language).slice(-2) +\".htm,cookie\";\r\n cookieLaw.addEventListener(\"click\", function(){\r\n createCookie(cookieName,1,365)\r\n setCookieWarning(false);\r\n });\r\n\r\n if(readCookie(cookieName)!=1)setCookieWarning(true);\r\n\r\n function removeMe(){\r\n\teraseCookie(cookieName);\r\n\tsetCookieWarning(false);\r\n }\r\n }\r\n }", "function handleDistrictAndAssembly(country, initiative, $form) {\n var pattern1 = new RegExp(\"voter\", \"i\");\n var pattern2 = new RegExp(\"election\", \"i\");\n if (country != 'India') {\n $($form).find(\".district_dropdown_div\").css(\"visibility\", \"hidden\").end()\n .find(\".district_dropdown\").removeClass(\"required-field\").end()\n .find(\".assembly_constituency_dropdown_div\").css(\"visibility\", \"hidden\").end()\n .find(\".assembly_constituency_dropdown\").removeClass(\"required-field\");\n } else {\n $($form).find(\".district_dropdown_div\").css(\"visibility\", \"visible\").end()\n .find(\".district_dropdown\").removeClass(\"required-field\").end()\n .find(\".assembly_constituency_dropdown_div\").css(\"visibility\", \"visible\").end()\n .find(\".assembly_constituency_dropdown\").removeClass(\"required-field\");\n if (initiative != undefined) {\n if (initiative.match(pattern1) || initiative.match(pattern2)) {\n $($form).find(\".district_dropdown\").addClass(\"required-field\").end()\n .find(\".assembly_constituency_dropdown\").addClass(\"required-field\");\n }\n }\n }\n}", "function validateFunction(name,email,website,image,gender,skills){\n var flag=0;\n var str=\"\";\n //validating name\n if(validateName(name)==false)\n {\n flag=1;\n str=str+\"Name is Required \\n\";\n }\n var isEmailEntered=1;\n //validating email \n if(validateEmail(email)==false)\n {\n flag=1;\n isEmailEntered=0;\n str=str+\"Email is Required \\n\";\n }\n //varify only when email is entered\n if(varifyEmail(email)==false) \n {\n if(isEmailEntered==1){\n flag=1;\n str=str+\"Email is not correct \\n\";\n }\n \n }\n var isWebsiteEntered=1;\n //validating website\n if(validateWebsite(website)==false)\n {\n flag=1;\n isWebsiteEntered=0;\n str=str+\"Website is Required \\n\";\n }\n //varify website only when it is entered\n if((varifyWebsite(website)==false)&&(isWebsiteEntered==1))\n {\n flag=1;\n str=str+\"Unreached Website \\n\";\n }\n //validating image\n if(validateImage(image)==false)\n {\n flag=1;\n str=str+\"Image is required\\n\";\n }\n //validating gender\n if(validateGender(gender==false))\n {\n flag=1;\n str=str+\"Gender is required\\n\";\n }\n //validating skills\n if( validateskills(skills==false))\n {\n flag=1;\n str=str+\"Skill is required\\n\";\n }\n if(flag==0){\n \n return true;\n }\n else {\n alert(str);\n \n return false;\n }\n}", "function ssw_js_check_domain_available() {\n\n var site_exists = '';\n var site_address_bucket = document.getElementById('ssw-steps').site_address_bucket.value;\n var site_address = document.getElementById('ssw-steps').site_address.value;\n site_address = site_address.toLowerCase();\n var site_complete_path = ssw_js_get_site_complete_path();\n\n /* AJAX request with aync flag true as we need the response synchrnously for use in the \n ssw_js_validate_form() and ssw_js_submit_form_next() function \n */\n jQuery.ajax({\n type: \"POST\", \n url: ssw_custom_ajax.ajaxurl,\n dataType: \"html\",\n async: false,\n data: { \n action: 'ssw_check_domain_exists',\n site_address_bucket: site_address_bucket,\n site_address: site_address,\n site_complete_path: site_complete_path,\n ssw_ajax_nonce: ssw_custom_ajax.ssw_ajax_nonce \n },\n success: function(site_exists_value){\n site_exists = site_exists_value;\n } \n });\n\n if(site_exists == 2) { //this is a banned site address\n document.getElementById(\"ssw-site-address-error-label\").innerHTML=ssw_site_address_banned_msg;\n document.getElementById(\"ssw-site-address-error\").style.display=\"block\"; \n return false;\n }\n else if (site_exists == 1) { //site already exists\n document.getElementById(\"ssw-site-address-error-label\").innerHTML=ssw_site_address_unavailable_msg;\n document.getElementById(\"ssw-site-address-error\").style.display=\"block\"; \n return false;\n }\n else if (site_exists == 0) { //site doesn't exist, good to go\n return true;\n }\n else {\n document.getElementById(\"ssw-site-address-error-label\").innerHTML=ssw_site_address_other_error_msg;\n document.getElementById(\"ssw-site-address-error\").style.display=\"block\";\n return false; \n }\n}", "function checkVendorValues()\n{\n\tif (document.forms[0].txtVendorName.value == \"\")\n\t{\n\t\talert(\"Please enter a value for the vendor name\");\n\t\tdocument.forms[0].txtVendorName.focus();\n\t\treturn false;\n\t}\n\telse if (document.forms[0].txtVendorWebsite.value == \"\")\n\t{\n\t\talert(\"Please enter a value for the vendor website\");\n\t\tdocument.forms[0].txtVendorWebsite.focus();\n\t\treturn false;\n\t}\n\telse if (document.forms[0].uploadVendorPic.value == \"\")\n\t{\n\t\talert(\"Please select a vendor logo to upload\");\n\t\tdocument.forms[0].uploadVendorPic.focus();\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn true;\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calcSpeed(prevv, next) calculate speed based on old and new position
function calcSpeed(prev, next) { var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]); var greatest = x > y ? x : y; var speedModifier = 0.20; var speed = Math.ceil(greatest/speedModifier); //Keep speed at a constant if(speed < 3000 || speed > 3000) { speed = 3000; return speed; } return speed; }
[ "updateSpeedPhysics() {\n let speedChange = 0;\n const differenceBetweenPresentAndTargetSpeeds = this.speed - this.target.speed;\n\n if (differenceBetweenPresentAndTargetSpeeds === 0) {\n return;\n }\n\n if (this.speed > this.target.speed) {\n speedChange = -this.model.rate.decelerate * TimeKeeper.getDeltaTimeForGameStateAndTimewarp() / 2;\n\n if (this.isOnGround()) {\n speedChange *= PERFORMANCE.DECELERATION_FACTOR_DUE_TO_GROUND_BRAKING;\n }\n } else if (this.speed < this.target.speed) {\n speedChange = this.model.rate.accelerate * TimeKeeper.getDeltaTimeForGameStateAndTimewarp() / 2;\n speedChange *= extrapolate_range_clamp(0, this.speed, this.model.speed.min, 2, 1);\n }\n\n this.speed += speedChange;\n\n if (abs(speedChange) > abs(differenceBetweenPresentAndTargetSpeeds)) {\n this.speed = this.target.speed;\n }\n }", "speedCheck () {\r\n if (this.nextVertex.roadWorks) {\r\n this.speed = 1\r\n } else (this.speed = this.masterSpeed)\r\n if(this.nextVertex.speed && this.nextVertex.speed < this.speed) {\r\n this.speed = this.nextVertex.speed\r\n } \r\n \r\n }", "calculateTravelCost(previous, next) {\n if (next.row !== previous.row && next.col !== previous.col) {\n return 14;\n }\n return 10;\n }", "increaseSpeed(speedup){\n return this.speed = this.speed + speedup;\n\n }", "function speedCalc() {\n\t\t\treturn (0.4 + 0.01 * (50 - invadersAlive)) * difficulty;\n\t\t}", "function calculateSpinSpeed(startAngle, endAngle, minimumRotations, delta){\n\t //This is the number of degrees we need to move\n\t var totalDegrees = (((endAngle - startAngle)+360) % 360) + 360*minimumRotations;\n\t //Perform the iterative spin algo in reverse to get the required starting speed.\n\t var degreesSoFar = 0;\n\t var speed=0;\n\t while( (degreesSoFar + (speed+delta)) < totalDegrees){\n\t speed += delta;\n\t degreesSoFar += speed;\n\t }\n\t speed += ((totalDegrees - degreesSoFar) / speed)*delta; //do the last bit so we're exact\n\t degreesSoFar += speed;\n\t return speed;\n\t }", "function increment(v1, v2, dst) {\r\n let d = dist(v1.x, v1.y, v2.x, v2.y);\r\n let t = dst/d;\r\n if (t < 0) return v1;\r\n if (t > 1) return v2;\r\n let x = ((1 - t) * v1.x) + (t * v2.x);\r\n let y = ((1 - t) * v1.y) + (t * v2.y);\r\n return new Vector(x, y);\r\n}", "increaseSpeed(value){\r\n this.speed += value;\r\n }", "function slowMove_update() {\n this.frameCounter++;\n // this.frameCounter = this.frameCounter % 2;\n if (this.frameCounter % 2 === 1) {\n this.middleY = this.middleY + 1;\n }\n}", "animatePlayerSwap(p1, p2) {\n var done = false;\n if (p1 != undefined) {\n swapping[0] = p1;\n swapping[1] = p2;\n\n for (var p of swapping) {\n if ((p.pos.x < 400) && (p.pos.y < 200)) {\n for (var yval = 110 ; yval <= 300 ; yval += 10) {\n p.addStep(new Point(75, yval));\n }\n } else if ((p.pos.x < 400) && (200 < p.pos.y)) {\n for (var yval = 290 ; 100 <= yval ; yval -= 10) {\n p.addStep(new Point(75, yval));\n }\n } else if ((400 < p.pos.x) && (p.pos.y < 200)) {\n for (var yval = 110 ; yval <= 300 ; yval += 10) {\n p.addStep(new Point(805, yval));\n }\n } else if ((400 < p.pos.x) && (200 < p.pos.y)) {\n for (var yval = 290 ; 100 <= yval ; yval -= 10) {\n p.addStep(new Point(805, yval));\n }\n }\n }\n\n swapInterval = setInterval( function() {\n court.animatePlayerSwap();\n }, 20 );\n } else {\n this.draw();\n\n var moved = 0;\n for (var p of swapping) {\n moved += p.takeStep();\n }\n\n if (moved <= 0) {\n clearInterval(swapInterval);\n }\n }\n }", "incrementSpeed() {\n\t\t\tswitch (this.speed)\n\t\t\t{\n\t\t\t\tcase 1000:\n\t\t\t\t\tthis.speed = 2000;\n\t\t\t\tbreak;\n\t\t\t\tcase 2000:\n\t\t\t\t\tthis.speed = 5000;\n\t\t\t\tbreak;\n\t\t\t\tcase 5000:\n\t\t\t\t\tthis.speed = 10000;\n\t\t\t\tbreak;\n\t\t\t\tcase 10000:\n\t\t\t\t\tthis.speed = 20000;\n\t\t\t\tbreak;\n\t\t\t\tcase 20000:\n\t\t\t\t\tthis.speed = 50000;\n\t\t\t\tbreak;\n\t\t\t\tcase 50000:\n\t\t\t\t\tthis.speed = 60000; // one second is one minute\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthis.speed = 1000; // one second is one second\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "function slower () {\n\tvar extra = speed * 0.3;\n\tif (speed - extra < 0.000002) {\n\t\tspeed = 0.000002;\n\t} else {\n\t\tspeed -= extra;\n\t}\n\ttempSpeed = speed;\n}", "function linearStepwise(t0, v0, t1, v1, dt, t) {\n\t/*\n\t * perform the calculation according to formula\n\t * t - t0\n\t * dt ______\n\t * dt\n\t * v = v0 + (v1 - v0) ___________\n\t * t1 - t0\n\t *\n\t */\n\treturn v0 + Math.floor((v1 - v0) * Math.floor((t - t0) / dt) * dt / (t1 - t0));\n}", "_calculateTargetedSpeed() {\n if (this.mcp.autopilotMode !== MCP_MODE.AUTOPILOT.ON) {\n return;\n }\n\n if (this.flightPhase === FLIGHT_PHASE.LANDING) {\n return this._calculateTargetedSpeedDuringLanding();\n }\n\n switch (this.mcp.speedMode) {\n case MCP_MODE.SPEED.OFF:\n return this._calculateLegalSpeed(this.speed);\n\n case MCP_MODE.SPEED.HOLD:\n return this._calculateLegalSpeed(this.mcp.speed);\n\n // future functionality\n // case MCP_MODE.SPEED.LEVEL_CHANGE:\n // return;\n\n case MCP_MODE.SPEED.N1:\n return this._calculateLegalSpeed(this.model.speed.max);\n\n case MCP_MODE.SPEED.VNAV: {\n const vnavSpeed = this._calculateTargetedSpeedVnav();\n\n return this._calculateLegalSpeed(vnavSpeed);\n }\n\n default:\n console.warn('Expected MCP speed mode of \"OFF\", \"HOLD\", \"LEVEL_CHANGE\", \"N1\", or \"VNAV\", but ' +\n `received \"${this.mcp[MCP_MODE_NAME.SPEED]}\"`);\n return this._calculateLegalSpeed(this.speed);\n }\n }", "function calculateSpeed(distance, time){\n return distance / time;\n}", "function compute_future_position(position, velocity, dt)\n{\n\treturn position.add(velocity.scale(dt));\n}", "function linearlyApproach (current, target, delta) {\n if (Math.abs(current - target) < delta) {\n return target\n } else if (current < target) {\n return current + delta\n } else {\n return current - delta\n }\n }", "updateVelocity(newVelocity) {\r\n this.v = newVelocity;\r\n }", "function updateVelocity() {\n for (let i = 0; i < ballArray.length; i++) {\n let ball = ballArray[i];\n\n //velocity affected by acceleration\n ball.dx += ball.dx2;\n ball.dy += ball.dy2;\n\n //max velocity\n ball.dx = Math.min(MAX_VELOCITY, Math.max(-MAX_VELOCITY, ball.dx));\n ball.dy = Math.min(MAX_VELOCITY, Math.max(-MAX_VELOCITY, ball.dy));\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
registered returns true if the client has registered with that ws.
registeredOf(ws) { return this.ws === ws; }
[ "get isConnected() {\n return this.wsSocket && this.wsSocket.readyState === WebSocket.OPEN;\n }", "async isRegistered() {\n this.logger.debug(GuildService.name, this.isRegistered.name, \"Executing\");\n let profile = null;\n try {\n this.logger.debug(GuildService.name, this.isRegistered.name, \"Getting guild profile.\");\n profile = await this.getServerProfile();\n }\n catch(err) {\n this.logger.error(GuildService.name, this.isRegistered.name, err.message, err.stack);\n return false;\n }\n const isRegistered = (profile);\n\n if (isRegistered) {\n this.logger.debug(GuildService.name, this.isRegistered.name, \"Profile exists.\");\n this.logger.debug(GuildService.name, this.isRegistered.name, \"Guild is registered.\");\n }\n else {\n this.logger.debug(GuildService.name, this.isRegistered.name, \"Guild not registered.\");\n }\n this.logger.debug(GuildService.name, this.isRegistered.name, \"Exiting\");\n return isRegistered;\n }", "register(clientID, ws) {\n var c = this.client(clientID);\n c.register(ws);\n debug(\"Client %s registered in room %s\", clientID, this.id);\n\n // Sends the queued messages from the other client of the room.\n if (this.clients.size > 1) {\n for (var oc of this.clients.values()) {\n if (oc.id !== clientID) oc.sendQueued(c);\n }\n }\n }", "function isActive() {\n return socket && socket.readyState == WebSocket.OPEN;\n }", "function hasConnected( cb ){\r\n\ttool.logInfo.info( 'redis connnected status is :::::::' + client.connected );\r\n\tif( client.connected ){\r\n\t\tcb();\r\n\t} else {\r\n\t\tclient = redis.createClient( global.redisConfig.port, global.redisConfig.host );\r\n\t\tclient.on( 'connect', function( err, ret ){\r\n\t\t\ttool.logInfo.warn( 'redis connect again' );\r\n\t\t\tcb();\r\n\t\t})\r\n\t}\r\n}", "_register() {\n this._nodeHandle.registerSubscriber(this._topic, this._type)\n .then((resp) => {\n // if we were shutdown between the starting the registration and now, bail\n if (this.isShutdown()) {\n return;\n }\n\n // else handle response from register subscriber call\n let code = resp[0];\n let msg = resp[1];\n let pubs = resp[2];\n if ( code === 1 ) {\n // success! update state to reflect that we're registered\n this._state = REGISTERED;\n\n if (pubs.length > 0) {\n // this means we're ok and that publishers already exist on this topic\n // we should connect to them\n this.requestTopicFromPubs(pubs);\n }\n this.emit('registered');\n }\n })\n .catch((err, resp) => {\n this._log.warn('Error during subscriber %s registration: %s', this.getTopic(), err);\n })\n }", "function srs_can_republish() {\n var browser = get_browser_agents();\n \n if (browser.Chrome || browser.Firefox) {\n return true;\n }\n \n if (browser.MSIE || browser.QQBrowser) {\n return false;\n }\n \n return false;\n}", "hasWatchers() {\n return this.watchers.length > 0;\n }", "isRegisterName(str) {\n return this.architecture.hasRegisterName(str);\n }", "function isIPConnected(socket) {\n // Check if this sockets ip address is already exists in the clientSockets array\n for (i = 0; i < clientSockets.length; i++) {\n // socket.handshake.address returns the IP address\n if (socket.handshake.address === clientSockets[i].handshake.address) {\n return true;\n }\n }\n return false;\n} // End isIPConnected()", "get readyState() {\r\n return this._ws ? this._ws.readyState : ReconnectingWebSocket.CONNECTING;\r\n }", "function subscribe() {\n navigator.serviceWorker.ready\n .then(registration => {\n return registration.pushManager.subscribe({userVisibleOnly: true})\n })\n .then(subscription => {\n console.log('Subscribed ', subscription.endpoint)\n return fetch('http://localhost:4040/register', \n {\n method: 'post',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({\n endpoint: subscription.endpoint\n })\n })\n }).then(setUnsubscribeButton)\n}", "isOnline() {\n return this.worldManager && this.worldManager.isOnline();\n }", "function isNotificationAvailable() {\n return (\"Notification\" in window);\n}", "function ensureSubscribed() {\n if (!client) {\n client = getClient()\n }\n\n if (!subscribed) {\n subscribed = true\n client.on('message', (channel, message) => {\n const funcs = handlers[channel] || []\n for (const func of funcs) {\n func(channel, message)\n }\n })\n }\n}", "ifOnline() {\n return new Promise((resolve, reject) => {\n if (this._online) {\n resolve(true);\n }\n });\n }", "get isListening() {\n return this.listeners.length > 0;\n }", "function IsServiceRunning(/**string*/ name) /**boolean*/\n{\n\tvar strComputer = \".\";\n\tvar SWBemlocator = new ActiveXObject(\"WbemScripting.SWbemLocator\");\n\tvar objCtx = new ActiveXObject(\"WbemScripting.SWbemNamedValueSet\")\n\tobjCtx.Add(\"__ProviderArchitecture\", 64); \n\tvar objWMIService = SWBemlocator.ConnectServer(strComputer, \"/root/CIMV2\", \"\", \"\", null, null, null, objCtx);\n\t\n\tvar query = \"Select * from Win32_Service\";\n\tif(name)\n\t{\n\t\tquery += \" WHERE Name='\" + name + \"'\";\n\t}\n\tvar colItems = objWMIService.ExecQuery(query);\n\t\n\tvar e = new Enumerator(colItems);\n\tfor(; ! e.atEnd(); e.moveNext())\n\t{\n\t\tLog(e.item().Name + \":\" + e.item().State);\n\t\tif (name) \n\t\t{\n\t\t\tif (e.item().State.toLowerCase() == \"running\")\n\t\t\t{\n\t\t\t\treturn true;\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (name) return false;\n}", "isSubscribed(topic) {\n return this.getSubscriptions()\n .then(subscriptions => {\n return subscriptions.indexOf(topic) >= 0;\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if we should display information about this message type
function displayType(msgType, args) { let display = true; if (args.type && args.type.toLowerCase() !== msgType.toLowerCase()) { display = false; } return display; }
[ "function supportMessage(layerType) {\n\t\t\tif (layerType === 0) {\n\t\t\t\t$('.layerTypePrecomps').html('precomps')\n\t\t\t\t$('.supportMessaging').addClass('visible');\n\t\t\t}\n\t\t\telse if (layerType === 2) {\n\t\t\t\t//$('.layerTypeImages').html('images')\n\t\t\t\t//$('.supportMessaging').addClass('visible');\n\t\t\t}\n\t\t\telse if (layerType === 4) {\n\t\t\t\t$('.layerTypeShapes').html('shapes')\n\t\t\t\t$('.supportMessaging').addClass('visible');\n\t\t\t}\n\t\t\telse if (layerType === 5) {\n\t\t\t\t$('.layerTypeText').html('text layers')\n\t\t\t\t$('.supportMessaging').addClass('visible');\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$('.supportMessaging').removeClass('visible');\n\t\t\t}\n\t\t}", "function displayInfo (message, type) {\n alert(message)\n }", "function isChatVisible() {\n return jQuery(\".sizing-wrapper\").hasClass(\"with-chat\");\n }", "isValidType() {\n return Menu.getPizzaTypesSet().has(this.type.toLowerCase());\n }", "get _showControl() {\n return (\n !this.inlineEditing ||\n (this.inlineEditing && this.isEditing) ||\n (this.hasControlCallout && this.hasErrors)\n );\n }", "isEnabled() {\n //Override.\n return $gameMessage.currentWindow === this.SETTINGS.UNIQUE_ID;\n }", "function canGetDetails()\n{\n\tvar componentRec = dw.serverComponentsPalette.getSelectedNode();\n\tif ((componentRec != null) && (componentRec.detailsText != \"\"))\n\t{\n\t\treturn true;\n\t}\n\n\treturn false;\n}", "function requireCom() {\n return this.feedbackType === 'comment';\n}", "function changeTypeMessage(element) {\r\n\tswitch (element.value) {\r\n\t\tcase \"f\":\r\n\t\t\tshowElement(\"fieldFreeMessage\");\r\n\t\t\thideElement(\"fieldDigitalMessage\");\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase \"d\":\r\n\t\t\tshowElement(\"fieldDigitalMessage\");\r\n\t\t\thideElement(\"fieldFreeMessage\");\r\n\t\t\tbreak;\r\n\t}\r\n}", "function showMessage(input, message, type) {\n // get the small element and set the message\n const msg = input.parentNode.querySelector(\"small\");\n msg.innerText = message;\n // update the class for the input\n input.className = type ? \"success\" : \"error\";\n return type;\n}", "tracking_block(type) { return this.blocks[type] !== undefined; }", "isAdding() {\n return Template.instance().uiState.get(\"addChat\") == CANCEL_TXT;\n }", "function rtwDisplayMessage() {\n var docObj = top.rtwreport_document_frame.document;\n var msg = docObj.getElementById(RTW_TraceArgs.instance.fMessage);\n if (!msg) {\n msg = docObj.getElementById(\"rtwMsg_notTraceable\");\n }\n if (msg && msg.style) {\n msg.style.display = \"block\"; // make message visible\n var msgstr = msg.innerHTML;\n if (RTW_TraceArgs.instance.fBlock) {\n // replace '%s' in message with block name\n msgstr = msgstr.replace(\"%s\",RTW_TraceArgs.instance.fBlock);\n }\n msg.innerHTML = msgstr;\n }\n}", "function ShowInfo() {\n\t\tconsole.log('article: ', article);\n\t\t// console.log(articleText);\n\t}", "function show(type) { console.log(type.schema({exportAttrs: true})); }", "function showContactInfo() {\n x$(\"#contact_name\")\n .html(contact.name.formatted || contact.displayName || \"Unknown Contact\");\n \n // display first email found\n if (contact.emails && contact.emails.length > 0) {\n x$(\"#contact_email\")\n .css({display: \"inline-block\"})\n .attr(\"href\", \"mailto:\" + contact.emails[0].value)\n .html(contact.emails[0].value.slice(0, 19) + \"...\");\n } else {\n x$(\"#contact_email\").css({display: \"none\"});\n }\n\n // display first phone number found\n if (contact.phoneNumbers && contact.phoneNumbers.length > 0) {\n x$(\"#contact_phone\")\n .html(contact.phoneNumbers[0].type + \": \" + contact.phoneNumbers[0].value)\n .attr(\"href\", \"tel:\" + contact.phoneNumbers[0].value)\n .css({display: \"inline-block\"});\n } else {\n x$(\"#contact_phone\").css({display: \"none\"});\n }\n\n display(\"#contact\");\n }", "isCurrentlyDisplayed() {\n //Get current zoom level\n let zoomLevel = this.map.getView().getZoom();\n //Check visibility\n return this.isVisibleAtZoomLevel(zoomLevel);\n }", "static isDisplaySupported(requestEnvelope) {\n return requestEnvelope.context.System.device.supportedInterfaces.Display !== undefined;\n }", "static displayNoFlagsMessage() {\n return (\n <p>No Flags Found</p>\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creamos una funcion decipher la cual descifrara el texto
function decipher (text, n) { // Creamos una variable result, donde se almacenara nuestro resultado en modo de string var result = " "; // Hacemos un bucle que pase elemento por elemento for (var i = 0; i < text.length; i++) { // Creamos una variable letters para almacenar el codigo ASCII de cada caracter var letters = text.charCodeAt(i); // Creamos un algoritmo en el caso sean mayusculas if (65 <= letters && letters <= 90) { result += String.fromCharCode((letters + 65 + n) % 26 + 65);} // Creamos un algoritmo en el caso sean minusculas else if (97 <= letters && letters <= 122){ result += String.fromCharCode((letters + 97 + n) % 26 + 97);} // Si el usuario no coloca letras mandar un alert else { alert ("Texto no valido");} } return result; }
[ "function decipher(cifrado) {\n alert('Palabra Cifrada: ' + cifrado);\n var descifrado = '';\n\n // el for recorrera las letras del texto a descifrar//\n\n for (var j = 0; j < cifrado.length; j++) {\n var ubicacionDescifrado = (cifrado.charCodeAt(j) + 65 - 33) % 26 + 65;\n var palabraDescifrada = String.fromCharCode(ubicacionDescifrado);\n // acumular las letras descifradas//\n descifrado += palabraDescifrada;\n }\n return descifrado;\n}", "function decipher(message, nfijo) {\n var result = '';\n // Recorriendo con un for mi mensaje hasta la longitud de la misma\n for (var i = 0; i < message.length; i++) {\n // Convirtiendo con cada indice de mi letra a valor ascii\n var ascii = message.charCodeAt(i);\n // Validando letras mayusculas y aplicando formula para cambiar a el valor de mi alfabeto.\n if (65 <= ascii && ascii <= 90) {\n result += String.fromCharCode((ascii - nfijo) + 26);\n } else if (97 <= ascii && ascii <= 122) { // Validando letras minusculas y aplicando formula para cambiar a el valor de mi alfabeto.\n result += String.fromCharCode((ascii - nfijo) + 26);\n } else {\n // Colocando alerta en caso el cliente no coloque un mensaje valido\n result = alert('Ingresar solo letras');\n }\n }\n return result;\n}", "function cipher(message, nfijo) {\n var result = '';\n // Recorriendo con un for mi mensaje hasta la longitud de la misma\n for (var i = 0;i < message.length;i++) {\n // Convirtiendo con cada indice de mi letra a valor ascii\n var ascii = message.charCodeAt(i);\n // Validando letras mayusculas y aplicando formula para cambiar a el valor de mi alfabeto.\n if (65 <= ascii && ascii <= 90) {\n result += String.fromCharCode((ascii - 65 + nfijo) % 26 + 65);\n } else if (97 <= ascii && ascii <= 122) { // Validando letras minusculas y aplicando formula para cambiar a el valor de mi alfabeto.\n result += String.fromCharCode((ascii - 65 + nfijo) % 26 + 65);\n } else {\n // Colocando alerta en caso el cliente no coloque un mensaje valido\n result = alert('Ingresar solo letras');\n }\n }\n return result;\n}", "function invertirFrase(n) {\n let frase = \"\";\n for (let i = n.length - 1; i >= 0; i--) {\n frase += n[i];\n }\n return frase;\n }", "function leetspeak(text) {\n\tlet translatableChars = ['A', 'E', 'G', 'L', 'O', 'S', 'T'];\n\tlet translatedChars = [4, 3, 6, 1, 0, 5, 7];\n\tlet translatedText = '';\n\tlet translated = false;\n\tfor (let i = 0; i < text.length; i++) {\n\t\tfor (let j = 0; j < translatableChars.length; j++) {\n\t\t\tif (text[i].toLowerCase() == translatableChars[j].toLowerCase()) {\n\t\t\t\ttranslatedText += translatedChars[j];\n\t\t\t\ttranslated = true;\t\n\t\t\t}\n\t\t}\n\t\tif (!translated) {\n\t\t\ttranslatedText += text[i];\n\t\t\ttranslated = false;\t\n\t\t}\t\t\n\t}\n\treturn translatedText;\n}", "function constructText(ban) {\n var num = 0;\n var text = '';\n for(var iy=0; iy<nrow; iy++) {\n for(var ix=0; ix<nrow; ix++) {\n var index = nrow*iy + ix;\n if(ban[index]) {\n if(num > 0) {\n text += num;\n num = 0;\n }\n text += ban[index];\n }\n else {\n num++;\n }\n\n }\n if(num > 0) {\n text += num;\n num = 0;\n }\n if(iy < nrow - 1)\n text += '/'\n }\n\n text += ' b ';\n\n editor.senteHand = sortPieces(editor.senteHand);\n editor.goteHand = sortPieces(editor.goteHand);\n\n text += constructTextInHand(editor.senteHand).toUpperCase();\n text += constructTextInHand(editor.goteHand).toLowerCase();\n\n if(editor.senteHand.length == 0 && editor.goteHand.length == 0)\n text += '-';\n\n text += ' 1';\n\n var sfenText = document.getElementById(\"sfen\");\n sfenText.innerHTML = text;\n\n return text;\n}", "function outputText(text) {\n var pstr = \"\";\n for (var i = 0, len = text.length; i < len; i++) {\n\tvar c = text[i];\n\tif(\"\\b\\x07\".indexOf(c) >= 0) {\n\t if(pstr != \"\") {\n\t\toutputText_str(pstr);\n\t\tpstr = \"\";\n\t }\n\t \n\t if(c == '\\b')\n\t\toutputText_bs();\n\t} else {\n\t pstr += c;\n\t}\n }\n\n if(pstr != \"\")\n\toutputText_str(pstr);\n \n var i = document.getElementById(\"interactive\")\n i.scrollTop = i.scrollHeight;\n}", "function contamination(text, char){\n if (text === '' || char === '') return '';\n \n let length = text.length;\n\n let newStr = '';\n for (let i = 0; i < length; i++) {\n newStr += char;\n }\n return newStr;\n}", "function puttext(identity)\n{\n\tvar btn_alphabet=String(identity.innerHTML);\n\tbtn_alphabet=btn_alphabet.split(/>|</);\n\tdocument.getElementById(\"enteredText\").value += String(btn_alphabet[2]);\n}", "function leetspeak(text) {\n regularText = text;\n\n //The global modifier is used to change more than just the first occurence\n regularText = regularText.toUpperCase();\n regularText = regularText.replace(/A/g, '4');\n regularText = regularText.replace(/E/g, '3');\n regularText = regularText.replace(/G/g, '6');\n regularText = regularText.replace(/I/g, '1');\n regularText = regularText.replace(/O/g, '0');\n regularText = regularText.replace(/S/g, '5');\n regularText = regularText.replace(/T/g, '7');\n\n console.log(regularText);\n\n}", "generateSmallDescription(text){\r\n\t if(text){\r\n\t\tif(text.length > 120){\r\n\t\t text= text.slice(0,120) + '...';\r\n\t\t return text;\r\n\t\t}\r\n\t\telse{\r\n\t\t return text;\r\n\t\t}\r\n\t }\r\n\t}", "function decipher(e,offset){\n return cipher(e,-offset);\n }", "function asciiArtAssist(src,size,color,bgColor){\n\t//default values for src, size, color and bgColor\n\tsrc=!src?'none':src;\n\tsize=!size?'inherit':size;\n\tcolor=!color?'#fff':color;\n\tbgColor=!bgColor?'#000':bgColor;\n\tvar slf=window,txtA,F,r9=slf.Math.random().toFixed(9).replace(/\\./g,''),\n\t\tt=slf.document.getElementsByTagName('body')[0],\n\t\tE=slf.document.createElement('textarea');\n\tE.id='asciiA'+r9;\n\tE.style.cssText=\"color: \"+color+\";font-size: \"+size+\";background: url(\\'\"+src+\"\\') \"+bgColor+\" no-repeat;\";\n\ttxtA=t.appendChild(E),t=E=null;\n\t//returned function returns the current value of textarea tag\n\tF=function(){\n\t\treturn document.getElementById('asciiA'+r9).value;\n\t};\n\t//method to close textarea tag\n\tF.close=function(){\n\t\tvar r=document.getElementById('asciiA'+r9);\n\t\tr=r.parentNode.removeChild(r),r=null;\n\t};\n\treturn F;\n}", "function decode(message){\n var normAlph = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; \n var backAlph = normAlph.slice().reverse();\n var massive = message.split(\"\");\n \n return massive.map(function(item){\n var ind = normAlph.indexOf(item);\n\n if (item != ' ')\n {return backAlph[ind]}\n else {return item}\n }).join(\"\");\n }", "function invertirUnaPalabra(String){\r\n let alreves = \"\";\r\n let tamano = 3;\r\n let array = String.split(\"\");\r\n for(let i = tamano; i >= 0; i--){\r\n alreves+= array[i];\r\n }\r\n console.log(\"La palabra al reves es: \"+ alreves);\r\n return alreves;\r\n}", "function encodeDecode(text, mode) {\n if (text == null)\n return text;\n\n var textEncoded = '';\n for (var count = 0; count < text.length; count++) {\n var index = ALPHABET.indexOf(text.charAt(count));\n if ( index != -1) {\n textEncoded = textEncoded + ALPHABET.charAt((((index+(OFFSET*mode))+ALPHABET.length) % ALPHABET.length));\n } else {\n textEncoded = textEncoded + text.charAt(count);\n }\n }\n return textEncoded;\n}", "function translate(text, dictionary){\n\t// TODO: implementați funcția\n\t// TODO: implement the function\n}", "function owofied(sentence) {\n\tconst a = sentence.replace(/i/g, \"wi\");\n\tconst b = a.replace(/e/g, \"we\");\n\treturn b + \" owo\";\n}", "function polybius (text) {\n let result = '';\n let alpha = 'ABCDEFGHIKLMNOPQRSTUVWXYZ';\n\n for (char of text) {\n if (alpha.includes(char) || char === 'J') {\n let index = alpha.indexOf(char);\n if (char === 'J') index = alpha.indexOf('I');\n result += Math.floor(index / 5) + 1;\n result += index % 5 + 1;\n } else result += char;\n }\n\n return result;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
THREE.js Object3D constructed from Vessel.js Ship object. There are some serious limitations to this: 1. null values encountered are assumed to be either at the top or bottom of the given station. 2. The end caps and bulkheads are sometimes corrected with zeros where they should perhaps have been clipped because of null values. var hMat; //global for debugging
function Ship3D(ship, stlPath) { THREE.Group.call(this) this.ship = ship let hull = ship.structure.hull let LOA = hull.attributes.LOA let BOA = hull.attributes.BOA let Depth = hull.attributes.Depth //console.log("LOA:%.1f, BOA:%.1f, Depth:%.1f",LOA,BOA,Depth); this.position.z = -ship.designState.calculationParameters.Draft_design //Hull let stations = hull.halfBreadths.stations let waterlines = hull.halfBreadths.waterlines let table = hull.halfBreadths.table //None of these are changed during correction of the geometry. console.log(stations) console.log(waterlines) console.log(table) let N = stations.length let M = waterlines.length //Hull side, in principle Y offsets on an XZ plane: //Even though a plane geometry is usually defined in terms of Z offsets on an XY plane, the order of the coordinates for each vertex is not so important. What is important is to get the topology right. This is ensured by working with the right order of the vertices. let hGeom = new THREE.PlaneBufferGeometry(undefined, undefined, N - 1, M - 1) let pos = hGeom.getAttribute("position") let pa = pos.array //loop1: //zs let c = 0 //Iterate over waterlines for (let j = 0; j < M; j++) { //loop2: //xs //iterate over stations for (let i = 0; i < N; i++) { //if (table[j][i] === null) continue;// loop1; pa[c] = stations[i] //x //DEBUG, OK. No attempts to read outside of table /*if(typeof table[j] === "undefined") console.error("table[%d] is undefined", j); else if (typeof table[j][i] === "undefined") console.error("table[%d][%d] is undefined", j, i);*/ //y pa[c + 1] = table[j][i] //y pa[c + 2] = waterlines[j] //z c += 3 } } //console.error("c-pa.length = %d", c-pa.length); //OK, sets all cells //Get rid of nulls by merging their points with the closest non-null point in the same station: /*I am joining some uvs too. Then an applied texture will be cropped, not distorted, where the hull is cropped.*/ let uv = hGeom.getAttribute("uv") let uva = uv.array //Iterate over stations for (let i = 0; i < N; i++) { let firstNumberJ let lastNumberJ //Iterate over waterlines let j for (j = 0; j < M; j++) { let y = table[j][i] //If this condition is satisfied (number found), //the loop will be quitted //after the extra logic below: if (y !== null) { firstNumberJ = j lastNumberJ = j //copy vector for i,j to positions for all null cells below: let c = firstNumberJ * N + i let x = pa[3 * c] let y = pa[3 * c + 1] let z = pa[3 * c + 2] let d = c while (firstNumberJ > 0) { firstNumberJ-- d -= N pa[3 * d] = x pa[3 * d + 1] = y pa[3 * d + 2] = z uva[2 * d] = uva[2 * c] uva[2 * d + 1] = uva[2 * c + 1] } break } console.log("null encountered.") } //Continue up the hull (with same j counter), searching for upper number. This does not account for the existence of numbers above the first null encountered. for (; j < M; j++) { let y = table[j][i] if (y === null) { console.log("null encountered.") break } //else not null: lastNumberJ = j } //copy vector for i,j to positions for all null cells above: let c = lastNumberJ * N + i let x = pa[3 * c] let y = pa[3 * c + 1] let z = pa[3 * c + 2] let d = c while (lastNumberJ < M - 1) { lastNumberJ++ d += N pa[3 * d] = x pa[3 * d + 1] = y pa[3 * d + 2] = z uva[2 * d] = uva[2 * c] uva[2 * d + 1] = uva[2 * c + 1] } ////////// } //console.log(pa); pos.needsUpdate = true uv.needsUpdate = true hGeom.computeVertexNormals() //Bow cap: let bowPlaneOffsets = hull.getStation(LOA).map(str => str / (0.5 * BOA)) //normalized let bowCapG = new THREE.PlaneBufferGeometry(undefined, undefined, 1, M - 1) pos = bowCapG.getAttribute("position") pa = pos.array //constant x-offset yz plane for (let j = 0; j < M; j++) { pa[3 * (2 * j)] = 1 pa[3 * (2 * j) + 1] = bowPlaneOffsets[j] pa[3 * (2 * j) + 2] = waterlines[j] pa[3 * (2 * j + 1)] = 1 pa[3 * (2 * j + 1) + 1] = -bowPlaneOffsets[j] pa[3 * (2 * j + 1) + 2] = waterlines[j] } pos.needsUpdate = true //Aft cap: let aftPlaneOffsets = hull.getStation(0).map(str => str / (0.5 * BOA)) //normalized let aftCapG = new THREE.PlaneBufferGeometry(undefined, undefined, 1, M - 1) pos = aftCapG.getAttribute("position") pa = pos.array //constant x-offset yz plane for (let j = 0; j < M; j++) { pa[3 * (2 * j)] = 0 pa[3 * (2 * j) + 1] = -aftPlaneOffsets[j] pa[3 * (2 * j) + 2] = waterlines[j] pa[3 * (2 * j + 1)] = 0 pa[3 * (2 * j + 1) + 1] = aftPlaneOffsets[j] pa[3 * (2 * j + 1) + 2] = waterlines[j] } pos.needsUpdate = true //Bottom cap: let bottomPlaneOffsets = hull.getWaterline(0).map(hw => hw / (0.5 * BOA)) //normalized let bottomCapG = new THREE.PlaneBufferGeometry(undefined, undefined, N - 1, 1) pos = bottomCapG.getAttribute("position") pa = pos.array //constant z-offset xy plane for (let i = 0; i < N; i++) { pa[3 * i] = stations[i] pa[3 * i + 1] = -bottomPlaneOffsets[i] pa[3 * i + 2] = 0 pa[3 * (N + i)] = stations[i] pa[3 * (N + i) + 1] = bottomPlaneOffsets[i] pa[3 * (N + i) + 2] = 0 } pos.needsUpdate = true //Hull material let phong = THREE.ShaderLib.phong let commonDecl = "uniform float wlThreshold;uniform vec3 aboveWL; uniform vec3 belowWL;\nvarying vec3 vPos;" let hMat = new THREE.ShaderMaterial({ uniforms: THREE.UniformsUtils.merge([ phong.uniforms, { wlThreshold: new THREE.Uniform(ship.designState.calculationParameters.Draft_design / Depth), aboveWL: new THREE.Uniform(new THREE.Color(0x33aa33)), belowWL: new THREE.Uniform(new THREE.Color(0xaa3333)), }, ]), vertexShader: commonDecl + phong.vertexShader.replace("main() {", "main() {\nvPos = position.xyz;").replace("#define PHONG", ""), fragmentShader: commonDecl + phong.fragmentShader.replace("vec4 diffuseColor = vec4( diffuse, opacity );", "vec4 diffuseColor = vec4( (vPos.z>wlThreshold)? aboveWL.rgb : belowWL.rgb, opacity );").replace("#define PHONG", ""), side: THREE.DoubleSide, lights: true, transparent: true, }) hMat.uniforms.opacity.value = 0.5 let hullGroup = new THREE.Group() let port = new THREE.Mesh(hGeom, hMat) let starboard = new THREE.Mesh(hGeom, hMat) starboard.scale.y = -1 hullGroup.add(port, starboard) //Caps: hullGroup.add(new THREE.Mesh(bowCapG, hMat)) hullGroup.add(new THREE.Mesh(aftCapG, hMat)) hullGroup.add(new THREE.Mesh(bottomCapG, hMat)) hullGroup.scale.set(LOA, 0.5 * BOA, Depth) this.hullGroup = hullGroup this.add(hullGroup) //DEBUG, to show only hull: //return; //Decks: var decks = new THREE.Group() let deckMat = new THREE.MeshPhongMaterial({ color: 0xcccccc /*this.randomColor()*/, transparent: true, opacity: 0.2, side: THREE.DoubleSide }) //deckGeom.translate(0,0,-0.5); let ds = ship.structure.decks let dk = Object.keys(ds) let stss = stations.map(st => LOA * st) //use scaled stations for now console.log(dk) for (let i = 0; i < dk.length; i++) { let d = ds[dk[i]] //deck in ship structure //Will eventually use BoxBufferGeometry, but that is harder, because vertices are duplicated in the face planes. let deckGeom = new THREE.PlaneBufferGeometry(1, 1, stss.length, 1) //new THREE.BoxBufferGeometry(1,1,1,sts.length,1,1); console.log("d.zFloor=%.1f", d.zFloor) //DEBUG let zHigh = d.zFloor let zLow = d.zFloor - d.thickness let wlHigh = hull.getWaterline(zHigh) let wlLow = hull.getWaterline(zLow) let pos = deckGeom.getAttribute("position") let pa = pos.array for (let j = 0; j < stss.length + 1; j++) { let x = d.xAft + (j / stss.length) * (d.xFwd - d.xAft) let y1 = Vessel.f.linearFromArrays(stss, wlHigh, x) let y2 = Vessel.f.linearFromArrays(stss, wlLow, x) let y = Math.min(0.5 * d.breadth, y1, y2) pa[3 * j] = x pa[3 * j + 1] = y pa[3 * (stss.length + 1) + 3 * j] = x pa[3 * (stss.length + 1) + 3 * j + 1] = -y //test } pos.needsUpdate = true //DEBUG console.log("d.xFwd=%.1f, d.xAft=%.1f, 0.5*d.breadth=%.1f", d.xFwd, d.xAft, 0.5 * d.breadth) console.log(pa) let deck = new THREE.Mesh(deckGeom, deckMat) deck.name = dk[i] deck.position.z = d.zFloor //deck.scale.set(d.xFwd-d.xAft, d.breadth, d.thickness); //deck.position.set(0.5*(d.xFwd+d.xAft), 0, d.zFloor); decks.add(deck) } this.decks = decks this.add(decks) //Bulkheads: var bulkheads = new THREE.Group() bulkheads.scale.set(1, 0.5 * BOA, Depth) let bhGeom = new THREE.BoxBufferGeometry(1, 1, 1) bhGeom.translate(0, 0, 0.5) let bhMat = new THREE.MeshPhongMaterial({ color: 0xcccccc /*this.randomColor()*/, transparent: true, opacity: 0.5, side: THREE.DoubleSide }) bhGeom.translate(0.5, 0, 0) let bhs = ship.structure.bulkheads let bhk = Object.keys(bhs) for (let i = 0; i < bhk.length; i++) { let bulkhead = new THREE.Mesh(bhGeom, bhMat) let bh = bhs[bhk[i]] bulkhead.name = bhk[i] bulkhead.scale.set(bh.thickness, 1, 1) bulkhead.position.set(bh.xAft, 0, 0) bulkheads.add(bulkhead) } this.bulkheads = bulkheads this.add(bulkheads) //Objects this.materials = {} this.stlPath = stlPath let stlManager = new THREE.LoadingManager() this.stlLoader = new THREE.STLLoader(stlManager) /*stlManager.onLoad = function() { createGUI(materials, deckMat); }*/ this.blocks = new THREE.Group() this.add(this.blocks) //Default placeholder geometry this.boxGeom = new THREE.BoxBufferGeometry(1, 1, 1) this.boxGeom.translate(0, 0, 0.5) let objects = Object.values(ship.derivedObjects) for (let i = 0; i < objects.length; i++) { this.addObject(objects[i]) } //console.log("Reached end of Ship3D constructor."); }
[ "function creaInfissiFinestra(PortdimX,PortdimY,PortPosX,PortPosY,PortPosZ){\nvar infissi = new THREE.Object3D();\n\nvar infisso1 = createMeshPortWindow(new THREE.BoxGeometry(0.1, 0.02, PortdimY), 'PortText.jpg');\ninfisso1.position.set(-(PortdimX+0.05),-0.05,0);\nvar infisso2 = createMeshPortWindow(new THREE.BoxGeometry(0.1, 0.02, PortdimY), 'PortText.jpg');\ninfisso2.position.set(0.05,-0.05,0);\n\nvar infisso3 = createMeshPortWindow(new THREE.BoxGeometry(0.1, 0.02, PortdimY), 'PortText.jpg');\ninfisso3.position.set(-(PortdimX+0.05),0.05,0);\nvar infisso4 = createMeshPortWindow(new THREE.BoxGeometry(0.1, 0.02, PortdimY), 'PortText.jpg');\ninfisso4.position.set(0.05,0.05,0);\n\nvar infisso5 = createMeshPortWindow(new THREE.BoxGeometry(PortdimX+0.2, 0.02, 0.1), 'PortText.jpg');\ninfisso5.position.set(-(PortdimX/2),0.05,(PortdimY/2)+0.05);\nvar infisso6 = createMeshPortWindow(new THREE.BoxGeometry(PortdimX+0.2, 0.02, 0.1), 'PortText.jpg');\ninfisso6.position.set(-(PortdimX/2),-0.05,(PortdimY/2)+0.05);\n\nvar infisso7 = createMeshPortWindow(new THREE.BoxGeometry(PortdimX+0.2, 0.02, 0.1),'PortText.jpg');\ninfisso7.position.set(-((PortdimX/2)),-0.05,-((PortdimY/2)+0.05));\n\nvar infisso8 = createMeshPortWindow(new THREE.BoxGeometry(PortdimX+0.2, 0.02, 0.1),'PortText.jpg');\ninfisso8.position.set(-((PortdimX/2)),0.05,-((PortdimY/2)+0.05));\n\ninfissi.add(infisso1)\ninfissi.add(infisso2)\ninfissi.add(infisso3)\ninfissi.add(infisso4)\ninfissi.add(infisso5)\ninfissi.add(infisso6)\ninfissi.add(infisso7)\ninfissi.add(infisso8)\n\ninfissi.position.set(PortPosX+(PortdimX/2),PortPosY,(PortdimY/2)+PortPosZ);\nreturn infissi;\n\n\n }", "function createSwimmer(suit)\n{\nvar torso = createTorso(suit);\nvar arm = createArm(basicMaterial);\nvar leg = createLeg(basicMaterial);\nvar head = createHead(basicMaterial,basicMaterial2);\n\narm.rightShoulder.position.x = 3*Math.sin(-1.257);\narm.rightShoulder.position.y = 3*Math.cos(1.257);\narm.leftShoulder.position.x = 3*Math.sin(1.257);\narm.leftShoulder.position.y = 3*Math.cos(1.257);\narm.rightShoulder.rotation.y = Math.PI;\narm.leftShoulder.rotation.x = Math.PI;\nleg.rightHip.position.x = 3*Math.sin(0.628);\nleg.rightHip.position.y = 3*Math.cos(2.513);\nleg.rightHip.rotation.z = -Math.PI / 2;\nleg.leftHip.position.x = 3*Math.sin(-0.628);\nleg.leftHip.position.y = 3*Math.cos(2.513);\nleg.leftHip.rotation.z = -Math.PI / 2;\nhead.neck.position.y = 3;\n\nvar swimmer3 = new THREE.Object3D();\nswimmer3.name = \"swimmer\";\nswimmer3.add(torso.body);\nswimmer3.add(arm.rightShoulder);\nswimmer3.add(arm.leftShoulder);\nswimmer3.add(head.neck);\nswimmer3.add(leg.rightHip);\nswimmer3.add(leg.leftHip);\n\nswimmer = new Object();\nswimmer.whole = swimmer3;\nswimmer.torso = torso.body;\nswimmer.rightShoulder = arm.rightShoulder;\nswimmer.leftShoulder = arm.leftShoulder;\nswimmer.rightElbow = arm.rightElbow;\nswimmer.leftElbow = arm.leftElbow;\nswimmer.rightWrist = arm.rightWrist;\nswimmer.leftWrist = arm.leftWrist;\nswimmer.head = head.neck;\nswimmer.rightHip = leg.rightHip;\nswimmer.leftHip = leg.leftHip;\nswimmer.rightKnee = leg.rightKnee;\nswimmer.leftKnee = leg.leftKnee;\nswimmer.rightAnkle = leg.rightAnkle;\nswimmer.leftAnkle = leg.leftAnkle;\n\nreturn swimmer;\n}", "constructor(params) {\n // times\n this.time = new THREE.Clock(true);\n this.timeNum = 3;\n this.timeScale = 2;\n\n this.scale = params.scale;\n\n // parameters\n this.sketch = params.sketch;\n this.size = params.size;\n this.dist = params.dist;\n this.iIndex = params.indexes.i;\n this.xIndex = params.indexes.x;\n this.yIndex = params.indexes.y;\n this.zIndex = params.indexes.z;\n this.shadow = params.shadow;\n this.geometry = params.geometry;\n this.material = params.material;\n this.others = params.others;\n this.position = new THREE.Vector3(params.position.x, params.position.y, params.position.z);\n\n this.initialize();\n }", "createScene() {\n\n this.heightMap = new NoiseMap();\n this.heightMaps = this.heightMap.maps;\n\n this.moistureMap = new NoiseMap();\n this.moistureMaps = this.moistureMap.maps;\n\n this.textureMap = new TextureMap();\n this.textureMaps = this.textureMap.maps;\n\n this.normalMap = new NormalMap();\n this.normalMaps = this.normalMap.maps;\n\n this.roughnessMap = new RoughnessMap();\n this.roughnessMaps = this.roughnessMap.maps;\n\n for (let i=0; i<6; i++) { //Create 6 materials, each with white color\n let material = new THREE.MeshStandardMaterial({\n color: new THREE.Color(0xFFFFFF)\n });\n this.materials[i] = material;\n }\n\n let geo = new THREE.BoxGeometry(1, 1, 1, 64, 64, 64); //Creating a box\n let radius = this.size;\n for (var i in geo.vertices) {\n \t\tvar vertex = geo.vertices[i];\n \t\tvertex.normalize().multiplyScalar(radius);\n \t}\n this.computeGeometry(geo); //Squeezing a box into a sphere\n\n this.ground = new THREE.Mesh(geo, this.materials); //Create ground mesh with squeezed box sphere and 6 materials\n this.view.add(this.ground);\n }", "constructor(params) {\n this.OP = params.OP;\n this.x = params.x - 1;\n this.y = params.y - 1;\n this.z = params.z - 1;\n this.x2 = params.x2 ? params.x2 - 1 : null;\n this.y2 = params.y2 ? params.y2 - 1 : null;\n this.z2 = params.z2 ? params.z2 - 1 : null;\n this.W = params.W;\n }", "buildMaterials () {\n this._meshes.forEach((mesh) => {\n let material = mesh.material;\n\n let position = new THREE.PositionNode();\n let alpha = new THREE.FloatNode(1.0);\n let color = new THREE.ColorNode(0xEEEEEE);\n\n // Compute transformations\n material._positionVaryingNodes.forEach((varNode) => {\n position = new THREE.OperatorNode(\n position,\n varNode,\n THREE.OperatorNode.ADD\n );\n });\n\n let operator;\n material._transformNodes.forEach((transNode) => {\n position = getOperatornode(\n position,\n transNode.get('node'),\n transNode.get('operator')\n );\n });\n\n // Compute alpha\n material._alphaVaryingNodes.forEach((alphaVarNode) => {\n alpha = new THREE.OperatorNode(\n alpha,\n alphaVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._alphaNodes.forEach((alphaNode) => {\n alpha = getOperatornode(\n alpha,\n alphaNode.get('node'),\n alphaNode.get('operator')\n );\n });\n\n // Compute color\n material._colorVaryingNodes.forEach((colorVarNode) => {\n color = new THREE.OperatorNode(\n color,\n colorVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._colorNodes.forEach((colorNode) => {\n color = getOperatornode(\n color,\n colorNode.get('node'),\n colorNode.get('operator')\n );\n });\n\n // To display surfaces like 2D planes or iso-surfaces whatever\n // the point of view\n mesh.material.side = THREE.DoubleSide;\n\n // Set wireframe status and shading\n if (mesh.type !== 'LineSegments' && mesh.type !== 'Points') {\n mesh.material.wireframe = this._wireframe;\n mesh.material.shading = this._wireframe\n ? THREE.SmoothShading\n : THREE.FlatShading;\n } else {\n mesh.material.wireframe = false;\n // Why ?\n // mesh.material.shading = THREE.SmoothShading;\n }\n\n // Get isoColor node\n mesh.material.transform = position;\n mesh.material.alpha = alpha;\n mesh.material.color = color;\n mesh.material.build();\n });\n }", "initFloor() {\n var planeMaterial = new THREE.ShadowMaterial();\n planeMaterial.opacity = 0.5;\n\n var floorPlaneGeo = new THREE.PlaneGeometry(600, 600, 10, 10);\n floorPlaneGeo.rotateX(-Math.PI / 2);\n floorPlaneGeo.translate(0, -225, 0);\n\n var floorPlaneMesh = new THREE.Mesh(floorPlaneGeo, planeMaterial);\n floorPlaneMesh.visible = true;\n floorPlaneMesh.receiveShadow = true;\n\n this.scene.add(floorPlaneMesh);\n }", "UpdateViewDependentData()\n {\n if (!this.display || this._state === EveMissileWarhead.State.DEAD) return;\n mat4.transpose(this._perObjectData.vs.Get(\"WorldMat\"), this._transform);\n mat4.transpose(this._perObjectData.vs.Get(\"WorldMatLast\"), this._transform);\n }", "function create3DTarget(target) {\n let loader = new THREE.TextureLoader();\n let planetSize = .5;\n loader.load(`./assets/img/targets/${target.name}.jpg`, (texture) => {\n let geom = new THREE.SphereGeometry(planetSize, 30, 30);\n let mat = (target.name == 'Sun') ? new THREE.MeshBasicMaterial({map: texture}) : new THREE.MeshLambertMaterial({map: texture});\n let planet = new THREE.Mesh(geom, mat);\n planet.name = target.name; planet.targetIndex = targets.indexOf(target);\n // Positioning\n let targetCartesian = Math.cartesian(target.az, target.el, gridRadius);\n planet.position.x = -targetCartesian.x;\n planet.position.z = -targetCartesian.z;\n planet.position.y = targetCartesian.y;\n planet.lookAt(0, 0, 0); planet.rotateY(Math.radians(target.az));\n // Target specific features\n if (planet.name == 'Saturn') {\n loader.load(`./assets/img/targets/SaturnRing.png`, (texture) => {\n geom = new THREE.RingGeometry(planetSize * 1.116086235489221, planetSize * 2.326699834162521, 84, 1);\n for(var yi = 0; yi < geom.parameters.phiSegments; yi++) {\n var u0 = yi / geom.parameters.phiSegments;\n var u1=(yi + 1) / geom.parameters.phiSegments;\n for(var xi = 0; xi < geom.parameters.thetaSegments; xi++) {\n \t\tvar fi = 2 * (xi + geom.parameters.thetaSegments * yi);\n var v0 = xi / geom.parameters.thetaSegments;\n var v1 = (xi + 1) / geom.parameters.thetaSegments;\n geom.faceVertexUvs[0][fi][0].x = u0; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v0;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n fi++;\n geom.faceVertexUvs[0][fi][0].x = u1; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v1;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n }\n }\n mat = new THREE.MeshLambertMaterial( { map: texture, side: THREE.DoubleSide, transparent: true } );\n let ring = new THREE.Mesh(geom, mat);\n ring.rotateX(27);\n planet.add(ring);\n });\n } else if (target.name == 'Sun') {\n const light = new THREE.PointLight('#d4caba', 1, 500, 0 );\n let lightCartesian = Math.cartesian(target.az, target.el, gridRadius - .5);\n light.position.x = -lightCartesian.x;\n light.position.y = lightCartesian.y;\n light.position.z = -lightCartesian.z;\n scene.add(light);\n }\n // planet.add(new THREE.AxesHelper(5));\n scene.add(planet);\n });\n}", "makeCube(cx, cy, cz, sx, sy, sz) {\n let v0 = [ cx - sx / 2, cy - sy / 2, cz - sz / 2 ];\n let v1 = [ cx - sx / 2, cy - sy / 2, cz + sz / 2 ];\n let v2 = [ cx - sx / 2, cy + sy / 2, cz - sz / 2 ];\n let v3 = [ cx - sx / 2, cy + sy / 2, cz + sz / 2 ];\n let v4 = [ cx + sx / 2, cy - sy / 2, cz - sz / 2 ];\n let v5 = [ cx + sx / 2, cy - sy / 2, cz + sz / 2 ];\n let v6 = [ cx + sx / 2, cy + sy / 2, cz - sz / 2 ];\n let v7 = [ cx + sx / 2, cy + sy / 2, cz + sz / 2 ];\n\n let vertices = [];\n\n let insert = (x) => {\n vertices.push(x[0]);\n vertices.push(x[1]);\n vertices.push(x[2]);\n };\n\n insert(v0); insert(v3); insert(v1); insert(v0); insert(v2); insert(v3);\n insert(v3); insert(v5); insert(v1); insert(v3); insert(v7); insert(v5);\n insert(v3); insert(v6); insert(v7); insert(v3); insert(v2); insert(v6);\n insert(v1); insert(v4); insert(v0); insert(v1); insert(v5); insert(v4);\n insert(v5); insert(v6); insert(v4); insert(v5); insert(v7); insert(v6);\n insert(v0); insert(v6); insert(v2); insert(v0); insert(v4); insert(v6);\n\n let buffer = new Float32Array(vertices);\n\n let vertex_buffer = new GL.Buffer();\n let vertex_array = new GL.VertexArray();\n GL.bindBuffer(GL.ARRAY_BUFFER, vertex_buffer);\n GL.bufferData(GL.ARRAY_BUFFER, buffer.length * 4, buffer, GL.STATIC_DRAW);\n GL.bindVertexArray(vertex_array);\n GL.enableVertexAttribArray(0);\n GL.bindBuffer(GL.ARRAY_BUFFER, vertex_buffer);\n GL.vertexAttribPointer(0, 3, GL.FLOAT, GL.FALSE, 12, 0);\n GL.bindVertexArray(0);\n let m = { };\n m.vertex_buffer = vertex_buffer;\n m.vertex_array = vertex_array;\n m.vertex_count = vertices.length / 3;\n return m;\n }", "createModel () {\n var model = new THREE.Object3D()\n var loader = new THREE.TextureLoader();\n var texturaOvo = null;\n\n var texturaEsfera = null;\n \n //var texturaGrua = new THREE.TextureLoader().load(\"imgs/tgrua.jpg\");\n this.robot = new Robot({});\n this.robot.scale.set(3,3,3);\n //model.add (this.robot);\n\n //Crear Objetos voladores\n var comportamiento = null; //Buenos - Malos\n\n for (var i = 0; i < this.maxMeteoritos; ++i) {\n if (i < this.dificultad) {\n comportamiento = false;\n texturaOvo = loader.load (\"imgs/cesped1.jpg\");\n } else {\n comportamiento = true;\n texturaOvo = loader.load (\"imgs/fuego.jpg\");\n }\n this.objetosVoladores[i] = new Ovo(new THREE.MeshPhongMaterial ({map: texturaOvo}), comportamiento);\n //model.add(this.objetosVoladores[i]);\n\n\n this.esfera = new Ovo(new THREE.MeshPhongMaterial ({map: texturaOvo}), comportamiento);\n model.add(this.esfera);\n //model.add(this.createEsfera());\n\n }\n\n\n //var loader = new THREE.TextureLoader();\n var textura = loader.load (\"imgs/suelo1.jpg\");\n this.ground = new Ground (300, 300, new THREE.MeshPhongMaterial ({map: textura}), 4);\n model.add (this.ground);\n\n return model;\n }", "_Init(params) {\n this._sky = new Sky();\n this._sky.scale.setScalar(10000);\n params.scene.add(this._sky);\n\n params.guiParams.sky = {\n turbidity: 10.0,\n rayleigh: 2,\n mieCoefficient: 0.005,\n mieDirectionalG: 0.8,\n luminance: 1,\n };\n\n //determined by inclination and azimuth of the brightness of sun and darkness of the sky\n params.guiParams.sun = {\n inclination: 0.31,\n azimuth: 0.25,\n };\n\n const onShaderChange = () => {\n for (let k in params.guiParams.sky) {\n this._sky.material.uniforms[k].value = params.guiParams.sky[k];\n }\n for (let k in params.guiParams.general) {\n this._sky.material.uniforms[k].value = params.guiParams.general[k];\n }\n };\n\n const onSunChange = () => {\n var theta = Math.PI * (params.guiParams.sun.inclination - 0.5);\n var phi = 2 * Math.PI * (params.guiParams.sun.azimuth - 0.5);\n\n const sunPosition = new THREE.Vector3();\n sunPosition.x = Math.cos(phi);\n sunPosition.y = Math.sin(phi) * Math.sin(theta);\n sunPosition.z = Math.sin(phi) * Math.cos(theta);\n\n this._sky.material.uniforms['sunPosition'].value.copy(sunPosition);\n };\n\n //adds gui for the user to change\n const sunRollup = params.gui.addFolder('Day & Night');\n sunRollup.add(params.guiParams.sun, \"inclination\", 0.0, 1.0).onChange(\n onSunChange);\n sunRollup.add(params.guiParams.sun, \"azimuth\", 0.0, 1.0).onChange(\n onSunChange);\n\n onShaderChange();\n onSunChange();\n }", "loadZero()\n\t{\n\t\tthis._x = this._y = this._z = 0.0;\n\t}", "function Sphere3D(radius) {\r\n\tthis.point = new Array();\r\n\tthis.color = \"rgb(100,0,255)\"\r\n\tthis.radius = (typeof(radius) == \"undefined\") ? 20.0 : radius;\r\n\tthis.radius = (typeof(radius) != \"number\") ? 20.0 : radius;\r\n\tthis.numberOfVertexes = 0;\r\n\r\n\t// It builds the middle circle on the XZ plane. Loop of 2*pi with a step of 0.17 radians.\r\n\tfor(alpha = 0; alpha <= 6.28; alpha += 0.17) {\r\n\t\tp = this.point[this.numberOfVertexes] = new Point3D();\r\n\t\t\r\n\t\tp.x = Math.cos(alpha) * this.radius;\r\n\t\tp.y = 0;\r\n\t\tp.z = Math.sin(alpha) * this.radius;\r\n\r\n\t\tthis.numberOfVertexes++;\r\n\t}\r\n\r\n\t// It builds two hemispheres:\r\n\t// - First hemisphere: loop of pi/2 with step of 0.17 (direction = 1)\r\n\t// - Second hemisphere: loop of pi/2 with step of 0.17 (direction = -1)\r\n\t\r\n\tfor(var direction = 1; direction >= -1; direction -= 2) {\r\n\t\tfor(var beta = 0.17; beta < 1.445; beta += 0.17) {\r\n\t\t\tvar radius = Math.cos(beta) * this.radius;\r\n\t\t\tvar fixedY = Math.sin(beta) * this.radius * direction;\r\n\r\n\t\t\tfor(var alpha = 0; alpha < 6.28; alpha += 0.17) {\r\n\t\t\t\tp = this.point[this.numberOfVertexes] = new Point3D();\r\n\r\n\t\t\t\tp.x = Math.cos(alpha) * radius;\r\n\t\t\t\tp.y = fixedY;\r\n\t\t\t\tp.z = Math.sin(alpha) * radius;\r\n\r\n\t\t\t\tthis.numberOfVertexes++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}", "function componentSurface () {\r\n\r\n\t/* Default Properties */\r\n\tvar dimensions = { x: 80, y: 40, z: 160 };\r\n\tvar colors = [\"blue\", \"red\"];\r\n\tvar classed = \"d3X3domSurface\";\r\n\r\n\t/* Scales */\r\n\tvar xScale = void 0;\r\n\tvar yScale = void 0;\r\n\tvar zScale = void 0;\r\n\tvar colorScale = void 0;\r\n\r\n\t/**\r\n * Array to String\r\n *\r\n * @private\r\n * @param {array} arr\r\n * @returns {string}\r\n */\r\n\tvar array2dToString = function array2dToString(arr) {\r\n\t\treturn arr.reduce(function (a, b) {\r\n\t\t\treturn a.concat(b);\r\n\t\t}, []).reduce(function (a, b) {\r\n\t\t\treturn a.concat(b);\r\n\t\t}, []).join(\" \");\r\n\t};\r\n\r\n\t/**\r\n * Initialise Data and Scales\r\n *\r\n * @private\r\n * @param {Array} data - Chart data.\r\n */\r\n\tvar init = function init(data) {\r\n\t\tvar _dataTransform$summar = dataTransform(data).summary(),\r\n\t\t rowKeys = _dataTransform$summar.rowKeys,\r\n\t\t columnKeys = _dataTransform$summar.columnKeys,\r\n\t\t valueMax = _dataTransform$summar.valueMax;\r\n\r\n\t\tvar valueExtent = [600, 950];\r\n\t\tvar _dimensions = dimensions,\r\n\t\t dimensionX = _dimensions.x,\r\n\t\t dimensionY = _dimensions.y,\r\n\t\t dimensionZ = _dimensions.z;\r\n\r\n\r\n\t\tif (typeof xScale === \"undefined\") {\r\n\t\t\txScale = d3.scalePoint().domain(rowKeys).range([0, dimensionX]);\r\n\t\t}\r\n\r\n\t\tif (typeof yScale === \"undefined\") {\r\n\t\t\tyScale = d3.scaleLinear().domain(valueExtent).range([0, dimensionY]);\r\n\t\t}\r\n\r\n\t\tif (typeof zScale === \"undefined\") {\r\n\t\t\tzScale = d3.scalePoint().domain(columnKeys).range([0, dimensionZ]);\r\n\t\t}\r\n\r\n\t\tif (typeof colorScale === \"undefined\") {\r\n\t\t\tcolorScale = d3.scaleLinear().domain(valueExtent).range(colors).interpolate(d3.interpolateLab);\r\n\t\t}\r\n\t};\r\n\r\n\t/**\r\n * Constructor\r\n *\r\n * @constructor\r\n * @alias surface\r\n * @param {d3.selection} selection - The chart holder D3 selection.\r\n */\r\n\tvar my = function my(selection) {\r\n\t\tselection.each(function (data) {\r\n\t\t\tinit(data);\r\n\r\n\t\t\tvar element = d3.select(this).classed(classed, true);\r\n\r\n\t\t\tvar surfaceData = function surfaceData(d) {\r\n\r\n\t\t\t\tvar coordPoints = function coordPoints(data) {\r\n\t\t\t\t\treturn data.map(function (X) {\r\n\t\t\t\t\t\treturn X.values.map(function (d) {\r\n\t\t\t\t\t\t\treturn [xScale(X.key), yScale(d.value), zScale(d.key)];\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t});\r\n\t\t\t\t};\r\n\r\n\t\t\t\tvar coordIndex = function coordIndex(data) {\r\n\t\t\t\t\tvar ny = data.length;\r\n\t\t\t\t\tvar nx = data[0].values.length;\r\n\r\n\t\t\t\t\tvar coordIndexFront = Array.apply(0, Array(ny - 1)).map(function (_, j) {\r\n\t\t\t\t\t\treturn Array.apply(0, Array(nx - 1)).map(function (_, i) {\r\n\t\t\t\t\t\t\tvar start = i + j * nx;\r\n\t\t\t\t\t\t\treturn [start, start + nx, start + nx + 1, start + 1, start, -1];\r\n console.log(start);\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tvar coordIndexBack = Array.apply(0, Array(ny - 1)).map(function (_, j) {\r\n\t\t\t\t\t\treturn Array.apply(0, Array(nx - 1)).map(function (_, i) {\r\n\t\t\t\t\t\t\tvar start = i + j * nx;\r\n\t\t\t\t\t\t\treturn [start, start + 1, start + nx + 1, start + nx, start, -1];\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\treturn coordIndexFront.concat(coordIndexBack);\r\n\t\t\t\t};\r\n\r\n\t\t\t\tvar colorFaceSet = function colorFaceSet(data) {\r\n\t\t\t\t\treturn data.map(function (X) {\r\n\t\t\t\t\t\treturn X.values.map(function (d) {\r\n\t\t\t\t\t\t\tvar col = d3.color(colorScale(d.value));\r\n\t\t\t\t\t\t\treturn '' + Math.round(col.r / 2.55) / 100 + ' ' + Math.round(col.g / 2.55) / 100 + ' ' + Math.round(col.b / 2.55) / 100;\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t});\r\n\t\t\t\t};\r\n\r\n\t\t\t\treturn [{\r\n\t\t\t\t\tcoordindex: array2dToString(coordIndex(d)),\r\n\t\t\t\t\tpoint: array2dToString(coordPoints(d)),\r\n\t\t\t\t\tcolor: array2dToString(colorFaceSet(d))\r\n\t\t\t\t}];\r\n\t\t\t};\r\n\r\n\t\t\tvar surface = element.selectAll(\".surface\").data(surfaceData);\r\n\r\n\t\t\tvar surfaceSelect = surface.enter().append(\"shape\").classed(\"surface\", true).append(\"indexedfaceset\").attr(\"coordindex\", function (d) {\r\n\t\t\t\treturn d.coordindex;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceSelect.append(\"coordinate\").attr(\"point\", function (d) {\r\n\t\t\t\treturn d.point;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceSelect.append(\"color\").attr(\"color\", function (d) {\r\n\t\t\t\treturn d.color;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceSelect.merge(surface);\r\n\r\n\t\t\tvar surfaceTransition = surface.transition().select(\"indexedfaceset\").attr(\"coordindex\", function (d) {\r\n\t\t\t\treturn d.coordindex;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceTransition.select(\"coordinate\").attr(\"point\", function (d) {\r\n\t\t\t\treturn d.point;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceTransition.select(\"color\").attr(\"color\", function (d) {\r\n\t\t\t\treturn d.color;\r\n\t\t\t});\r\n\r\n\t\t\tsurface.exit().remove();\r\n\t\t});\r\n\t};\r\n\r\n\t/**\r\n * Dimensions Getter / Setter\r\n *\r\n * @param {{x: number, y: number, z: number}} _v - 3D object dimensions.\r\n * @returns {*}\r\n */\r\n\tmy.dimensions = function (_v) {\r\n\t\tif (!arguments.length) return dimensions;\r\n\t\tdimensions = _v;\r\n\t\treturn this;\r\n\t};\r\n\r\n\t/**\r\n * X Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 scale.\r\n * @returns {*}\r\n */\r\n\tmy.xScale = function (_v) {\r\n\t\tif (!arguments.length) return xScale;\r\n\t\txScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Y Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 scale.\r\n * @returns {*}\r\n */\r\n\tmy.yScale = function (_v) {\r\n\t\tif (!arguments.length) return yScale;\r\n\t\tyScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Z Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 scale.\r\n * @returns {*}\r\n */\r\n\tmy.zScale = function (_v) {\r\n\t\tif (!arguments.length) return zScale;\r\n\t\tzScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Color Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 color scale.\r\n * @returns {*}\r\n */\r\n\tmy.colorScale = function (_v) {\r\n\t\tif (!arguments.length) return colorScale;\r\n\t\tcolorScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Colors Getter / Setter\r\n *\r\n * @param {Array} _v - Array of colours used by color scale.\r\n * @returns {*}\r\n */\r\n\tmy.colors = function (_v) {\r\n\t\tif (!arguments.length) return colors;\r\n\t\tcolors = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Dispatch On Getter\r\n *\r\n * @returns {*}\r\n */\r\n\tmy.on = function () {\r\n\t\tvar value = dispatch.on.apply(dispatch, arguments);\r\n\t\treturn value === dispatch ? my : value;\r\n\t};\r\n\r\n\treturn my;\r\n}", "function creaFinestroni(DimX,DimY,PosX,PosY,aperturaFin){\nvar Finestrone1 = new THREE.Object3D();\nvar Finestrone2 = new THREE.Object3D();\nvar Perno = new THREE.Object3D();\n\nvar trave1 = createMeshPortWindow(new THREE.BoxGeometry(DimX/2, 0.1, 0.1), 'PortText.jpg');\ntrave1.position.set(DimX/4,0,0)\nvar trave2 = createMeshPortWindow(new THREE.BoxGeometry(DimX/2, 0.1, 0.1), 'PortText.jpg');\ntrave2.position.set(DimX-(DimX/4),0,0)\nvar trave3 = createMeshPortWindow(new THREE.BoxGeometry(DimX/2, 0.1, 0.1),'PortText.jpg');\ntrave3.position.set(DimX-(DimX/4),DimY,0)\nvar trave4 = createMeshPortWindow(new THREE.BoxGeometry(DimX/2, 0.1, 0.1), 'PortText.jpg');\ntrave4.position.set(DimX/4,DimY,0)\n\nvar trave5 = createMeshPortWindow(new THREE.BoxGeometry(0.1, DimY-0.1, 0.1), 'PortText.jpg');\ntrave5.position.set(0.05,DimY/2,0)\nvar trave6 =createMeshPortWindow(new THREE.BoxGeometry(0.1, DimY-0.1, 0.1), 'PortText.jpg');\ntrave6.position.set(DimX/2,DimY/2,0)\n\nvar trave8 = createMeshPortWindow(new THREE.BoxGeometry(0.1, DimY-0.1, 0.1), 'PortText.jpg');\ntrave8.position.set(DimX/2,DimY/2,0)\n\nvar trave7 = createMeshPortWindow(new THREE.BoxGeometry(0.1, DimY-0.1, 0.1), 'PortText.jpg');\ntrave7.position.set(DimX-0.05,DimY/2,0)\n\nvar specchio1Geometry = new THREE.BoxGeometry((DimX/2)-0.15, DimY-0.1, 0.1);\n var mGlass = new THREE.MeshLambertMaterial( {\n color: 0xccccff,opacity: 0.3, transparent: true} ); \n\nspecchio1 = new THREE.Mesh( specchio1Geometry, mGlass);\nspecchio1.position.set((DimX/4)+0.02,(DimY/2),0)\n\nspecchio2 = new THREE.Mesh( specchio1Geometry, mGlass);\nspecchio2.position.set((DimX-(DimX/4)-0.02),(DimY/2),0)\n\nFinestrone1.add(trave1)\nFinestrone1.add(trave4)\nFinestrone1.add(trave5)\nFinestrone1.add(trave6)\nFinestrone1.add(specchio1)\nFinestrone1.add(Perno)\n\nFinestrone2.add(trave2)\nFinestrone2.add(trave3)\nFinestrone2.add(trave7)\nFinestrone2.add(trave8)\nFinestrone2.add(specchio2)\nPerno.add(Finestrone2)\n\nFinestrone1.position.set(PosX,PosY,0.15);\nFinestrone1.rotation.x=Math.PI/2\nFinestrone1.specchio2=specchio2\n\nFinestrone2.PosX=PosX\nFinestrone2.PosY=PosY\nFinestrone2.DimX=DimX\n\n if(aperturaFin==0){\n specchio2.interact=function(){\n if(Finestrone2.position.x==PosX-((DimX/4)+0.025)){\n finestroneSound.play();\nfinestroneAnimation1(Finestrone2)} \n else {\n finestroneSound.play();\nfinestroneAnimation2(Finestrone2)}}}\n\n if(aperturaFin==1){\n specchio2.interact=function(){\n if(Finestrone2.position.x==PosX-(((DimX/4)+0.025)+(DimX*2))){\n finestroneSound.play();\n finestroneAnimation4(Finestrone2)} \n else {\n finestroneSound.play();\nfinestroneAnimation3(Finestrone2)}}}\n\n if(aperturaFin==2){\n specchio2.interact=function(){\n if(Finestrone2.position.x==PosX-((DimX/2)+0.25)){\n finestroneSound.play();\nfinestroneAnimation5(Finestrone2)} \n else {\n finestroneSound.play();\nfinestroneAnimation6(Finestrone2)}}}\n\n if(aperturaFin==3){\n specchio2.interact=function(){\n if(Finestrone2.position.x==PosX-(DimX+0.15)){\n finestroneSound.play();\nfinestroneAnimation8(Finestrone2)} \n else {\n finestroneSound.play();\nfinestroneAnimation7(Finestrone2)}}}\n return Finestrone1\n }", "function vxMeasure (name, pt1, pt2, nrml1, nrml2) {\n \n // Mesh Name\n this.Name = name;\n \n // The Owning Model\n this.Model = null;\n \n var col = 0.75;\n this.meshcolor = new vxColour(col, col, col, 1);\n \n this.colour = [0, 162/255, 1, 1];\n \n // Place holders to determine if the Hover index is with in this\n // mesh or not.\n this.IndexStart = 0;\n this.IndexEnd = 0;\n\n //Vertice Array\n this.mesh_vertices = [];\n this.edgevertices = [];\n \n //Normal Array\n this.vert_noramls = [];\n this.edge_noramls = [];\n\n // texture uvs for consistency\n this.vert_uvcoords = [];\n this.edge_uvcoords = [];\n \n //Colour Array\n this.vert_colours = [];\n this.wire_colours = [];\n this.edge_colours = [];\n \n //Selection Colour Array\n this.vert_selcolours = [];\n\n //Indices\n this.Indices = [];\n this.EdgeIndices = [];\n \n this.meshBuffers = {\n verticies: null,\n normals: null,\n uvCoords: null,\n colours: null,\n selectionColours: null,\n wireframeColours: null,\n indices: null,\n }\n \n this.edgeBuffers = {\n verticies: null,\n normals: null,\n uvCoords: null,\n colours: null,\n selectionColours: null,\n wireframeColours: null,\n indices: null,\n }\n\n this.Texture = null;\n\n //What is the model type\n this.meshType = MeshType.Lines;\n \n //Should it be Drawn\n this.Enabled = true;\n \n // The Max Point of this Mesh\n this.MaxPoint = new vxVertex3D(0,0,0);\n \n this.Center = [0,0,0];\n \n this.IndexStart = numOfFaces;\n \n this.Point1 = pt1;\n this.Point2 = pt2;\n\n // Get the average vector of the face and then normalise it.\n this.Direction = new vxVertex3D(0,0,0);\n\n // setup the cross product\n this.CrossProd = [0,0,0];\n\n this.Delta = [0,0,0];\n this.Delta[0] = this.Point2[0] - this.Point1[0];\n this.Delta[1] = this.Point2[1] - this.Point1[1];\n this.Delta[2] = this.Point2[2] - this.Point1[2];\n\n this.NormalAvg = [0,0,0];\n\n\n vec3.cross(this.CrossProd, nrml1, nrml2);\n vec3.avg(this.NormalAvg, nrml1, nrml2);\n\n\n // If two vectors are parrellal, then we need to shift the normal direction slightly and re try the cross prod\n if(this.CrossProd[0]==0 && this.CrossProd[1]==0 && this.CrossProd[1]==0) {\n \n nrml2[0] = 1;\n nrml2[1] = 0;\n nrml2[2] = 0;\n\n vec3.cross(this.CrossProd, nrml1, nrml2);\n vec3.avg(this.NormalAvg, nrml1, nrml2);\n\n if(this.CrossProd[0]==0 && this.CrossProd[1]==0 && this.CrossProd[1]==0) {\n \n nrml2[0] = 0;\n nrml2[1] = 0;\n nrml2[2] = 1;\n\n vec3.cross(this.CrossProd, nrml1, nrml2);\n vec3.avg(this.NormalAvg, nrml1, nrml2);\n }\n }\n\n // Now we have a vector which is 90 degrees to both normals, which means it's also\n // tangent to both faces. With this we can then calculate a new cross product between\n // the tanget vector, and the vector between the two points.\n this.FinalCrossProd = [0,0,0];\n\n vec3.cross(this.FinalCrossProd, this.CrossProd, this.Delta);\n\n // Now check the angle between the Final Cross prod and the average normal this is\n // to prevent the leader lines going into the mesh. \n var rad = vec3.angle(this.FinalCrossProd, this.NormalAvg);\n var angle = rad * 180/3.14159;\n var dirFactor = 1;\n if(angle > 90)\n dirFactor = -1;\n\n // First try setting the direction as the average of the two faces.\n this.Direction.X = this.FinalCrossProd[0] * dirFactor;\n this.Direction.Y = this.FinalCrossProd[1] * dirFactor;\n this.Direction.Z = this.FinalCrossProd[2] * dirFactor;\n\n this.Direction.Normalise();\n\n\n // now get the magnitude of the difference\n this.DeltaX = this.Point2[0] - this.Point1[0];\n this.DeltaY = this.Point2[1] - this.Point1[1];\n this.DeltaZ = this.Point2[2] - this.Point1[2];\n \n this.Length = Math.sqrt(this.DeltaX * this.DeltaX + this.DeltaY * this.DeltaY + this.DeltaZ * this.DeltaZ);\n \n // The height of the vertical lines\n this.vertLineHeight = this.Length;\n \n // height of the distance marker line\n this.leaderHeight = this.Length * 0.75;\n\n \n //log(\"Measurement\");\n //log(\"=================================\");\n //log(\"Point1 = \" + this.Point1);\n //log(\"Point2 = \" + this.Point2);\n //log(\"---------------------------------\");\n //log(\"Direction = \" + this.Direction.Z);\n //log(\"Length = \" + this.Length);\n //log(\"=================================\");\n \n this.leaderPadding = this.Length * 0.12525;\n\n// console.log(this.Direction);\n this.Direction.X = this.leaderHeight * this.Direction.X;\n this.Direction.Y = this.leaderHeight * this.Direction.Y;\n this.Direction.Z = this.leaderHeight * this.Direction.Z;\n \n // Top Distance Line\n this.AddVertices(-this.Point1[0] + this.Direction.X, -this.Point1[1] + this.Direction.Y, -this.Point1[2] + this.Direction.Z);\n this.AddVertices(-this.Point2[0] + this.Direction.X, -this.Point2[1] + this.Direction.Y, -this.Point2[2] + this.Direction.Z);\n \n\n this.Direction.X += this.leaderPadding * this.Direction.X;\n this.Direction.Y += this.leaderPadding * this.Direction.Y;\n this.Direction.Z += this.leaderPadding * this.Direction.Z;\n\n // First Leader Line\n this.AddVertices(-this.Point1[0], -this.Point1[1], -this.Point1[2]);\n this.AddVertices(-this.Point1[0] + this.Direction.X, -this.Point1[1] + this.Direction.Y, -this.Point1[2] + this.Direction.Z);\n \n // Second Leader Line\n this.AddVertices(-this.Point2[0], -this.Point2[1], -this.Point2[2]);\n this.AddVertices(-this.Point2[0] + this.Direction.X, -this.Point2[1] + this.Direction.Y, -this.Point2[2] + this.Direction.Z);\n \n \n this.InitialiseBuffers();\n //distanceMesh.meshType = MeshType.Lines;\n \n //this.Center = this.Point1[0];\n\n var lengthShort = this.Length.toString().substr(0, this.Length.toString().indexOf(\".\")+5);\n \n AddTreeNode(\"node_\"+name, name, measureNodeId, \"measure\");\n AddTreeNode(\"node_\"+name+\"_dist\", 'Distance: '+ lengthShort, \"node_\"+name, \"bullet_vector\");\n AddTreeNode(\"node_\"+name+\"_length\", 'Length: '+ this.Length, \"node_\"+name+\"_dist\", \"hash\");\n AddTreeNode(\"node_\"+name+\"_deltax\", 'Delta X: '+ this.DeltaX, \"node_\"+name+\"_dist\", \"bullet_red\");\n AddTreeNode(\"node_\"+name+\"_deltay\", 'Delta Y: '+ this.DeltaY, \"node_\"+name+\"_dist\", \"bullet_green\");\n AddTreeNode(\"node_\"+name+\"_deltaz\", 'Delta Z: '+ this.DeltaZ, \"node_\"+name+\"_dist\", \"bullet_blue\");\n \n this.TextPos = [0,0,0,0];\n this.TextCenter = [(-this.Point1[0] - this.Point2[0])/2 + this.Direction.X, (-this.Point1[1] - this.Point2[1])/2 + this.Direction.Y, (-this.Point1[2] - this.Point2[2])/2+ this.Direction.Z];\n \n var maindiv = document.getElementById(\"div_canvas\");\n \n this.text = document.createElement(\"a\");\n this.text.style.position = \"absolute\";\n this.text.style.top = \"200px\";\n this.text.style.left = \"300px\";\n this.text.innerHTML = this.Name +\" = \"+ lengthShort;\n //inp1.setAttribute(\"id\", id); // added line\n this.text.setAttribute(\"class\", \"measure\"); // added line\n \n maindiv.appendChild( this.text);\n}", "function Morpher () {\n // Number of parameters loaded\n this._params_loaded = 0;\n // If true, ignore requests to change the coordinates of Z\n this.freeze_coordinates = false;\n // Dimensions along which coordinates of Z will vary\n this.dimension_0 = index_mapping[28];\n this.dimension_1 = index_mapping[11];\n // Point in latent space, selected at random to begin with\n this.Z = this.sample_Z();\n // Model parameters\n this.d_W_2 = this._load(\"data/d_W_2.bin\", 400 * 2000, 2000, 400);\n this.d_W_1 = this._load(\"data/d_W_1.bin\", 2000 * 2000, 2000, 2000);\n this.d_W_0 = this._load(\"data/d_W_0.bin\", 48 * 48 * 2000, 48 * 48, 2000);\n this.d_b_2 = this._load(\"data/d_b_2.bin\", 2000, 0, 2000);\n this.d_b_1 = this._load(\"data/d_b_1.bin\", 2000, 0, 2000);\n this.d_b_0 = this._load(\"data/d_b_0.bin\", 48 * 48, 0, 48 * 48);\n\n // self.e_W_2 = numpy.load('data/e_W_2.npy')\n // self.e_b_2 = numpy.load('data/e_b_2.npy')\n // self.e_W_1 = numpy.load('data/e_W_1.npy')\n // self.e_b_1 = numpy.load('data/e_b_1.npy')\n // self.e_W_0 = numpy.load('data/e_W_0.npy')\n // self.e_b_0 = numpy.load('data/e_b_0.npy')\n}", "function createMeshes() {\r\n mesh_lantern1 = createLantern ();\r\n scene.add(mesh_lantern1);\r\n\r\n mesh_lantern2 = mesh_lantern1.clone();\r\n mesh_lantern2.translateX(15.0);\r\n scene.add(mesh_lantern2);\r\n\r\n mesh_lantern3 = mesh_lantern1.clone();\r\n mesh_lantern3.translateZ(-20.0);\r\n scene.add(mesh_lantern3);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursive function that assign positions to each node
assignPosition(node, position) { node.position = position if (node.children.length){ for (let child_node of node.children){ position = this.assignPosition(child_node, position) } }else{ position++; } return position }
[ "assignPosition(node, position) {\n this.spot = Math.max(this.spot, position);\n node.position = position;\n if (node.children.length > 0) {\n this.assignPosition(node.children[0], position);\n }\n for (let i = 1; i < node.children.length; i++) {\n if (this.spot > position) {\n this.assignPosition(node.children[i], this.spot+1);\n } else {\n this.assignPosition(node.children[i], position+1);\n }\n }\n }", "function setNodePosition(){\n\t\tvar num = 0;\n\t\tvar change = 0;\n\t\t//check if node is outside or not, when the status of node changes, the transition happens\n\t\tnodes.each(function(d){\n\t\t\tif (d.noLayer){\n\t\t\t\td.outside.isOutside = true;\n\t\t\t\td3.select(this)\n\t\t\t\t\t.transition()\n\t\t\t\t\t.duration(500)\n\t\t\t\t\t.attr(\"opacity\", 0.8)\n\t\t\t\t\t.attr(\"r\", nodeRadius)\n\t\t\t\t\t.attr(\"fill\", \"red\");\t\n\t\t\t\treturn;\t\t\t\t\n\t\t\t}\t\t\t\n\t\t\tvar offset = Math.max(xOffset - leftPanelWidth,0);\n\t\t\tif (d.position.x - nodeRadius < offset || d.position.x + nodeRadius > offset + windowWidth){\t\t\t\t\n\t\t\t\td3.select(this).classed(\"fixed\", d.fixed = false);\n\t \t\t\td.position.x = d.xpos;\n\t\t\t\td.position.y = height - nodeRadius - d.layer * unitLinkLength;\n\t\t\t}\n\t\t\tif (d.position.x - nodeRadius < offset || d.position.x + nodeRadius > offset + windowWidth){\n\t\t\t\tif (d.unAssigned == true){\n\n\t\t\t\t}\n\t\t\t\telse if (!d.outside.isOutside){\n\t\t\t\t\td.outside.isOutside = true;\t\t\t\t\n\t\t\t\t\td3.select(this)\n\t\t\t\t\t\t.transition()\n\t\t\t\t\t\t.duration(500)\n\t\t\t\t\t\t.attr(\"opacity\", 0.5)\n\t\t\t\t\t\t.attr(\"r\", nodeRadius)\n\t\t\t\t\t\t.attr(\"fill\", function(d){\n\t\t\t\t\t\t\treturn cScale(d.index + 1);\n\t\t\t\t\t\t});\t\t\t\t\t\n\t\t\t\t\tchange++;\n\t\t\t\t\tnum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (d.outside.isOutside){\n\t\t\t\t\td.outside.isOutside = false;\n\t\t\t\t\td3.select(this)\n\t\t\t\t\t\t.transition()\n\t\t\t\t\t\t.duration(500)\n\t\t\t\t\t\t.attr(\"opacity\", 0.7)\n\t\t\t\t\t\t.attr(\"r\", nodeRadius)\n\t\t\t\t\t\t.attr(\"fill\", \"red\");\n\n\t\t\t\t\tchange++;\n\t\t\t\t\tnum--;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//console.log(d.id + \" \" + d.outside.isOutside + \" \" + d.position.x);\n\t\t});\n\n\t\t//when some node changes its status, the correspoding links, labels and the x position of inside nodes should also change.\n\t\tif (change > 0 || firstTime){\n\t\t\tfirstTime = false;\n\t\t\toutsideNodesNum = num;\t\n\t\t\td3.selectAll(\".nodeLabel\")\n\t\t\t\t.attr(\"opacity\", function(d){\n\t\t\t\t\tif (d.node.noLayer){\n\t\t\t\t\t\td.node.showLabel = true;\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (d.type == \"nodeLabel\" && d.node.outside){\n\t\t\t\t\t\tif ((!d.node.outside.isOutside && d.node.type != \"anchor\") || (d.node.outside.isOutside && d.node.degree >= 3)){\n\t\t\t\t\t\t\td.node.showLabel = true;\n\t\t\t\t\t\t\treturn 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t\td.node.showLabel = false;\n\t\t\t\t\treturn 0;\t\t\t\n\t\t\t\t});\n\t\t\td3.selectAll(\".linkLabel\")\n\t\t\t\t.attr(\"opacity\", function(d){\n\t\t\t\t\tif (d.type == \"linkLabel\"){\n\t\t\t\t\t\tif (nodesData[d.node.tgt].noLayer){\n\t\t\t\t\t\t\td.show = true;\n\t\t\t\t\t\t\treturn 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (nodesData[d.node.src].outside.isOutside || nodesData[d.node.tgt].outside.isOutside){\n\t\t\t\t\t\t\td.show = false;\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\td.show = true;\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\td3.selectAll(\".edgeLinkLabel\")\n\t\t\t\t.attr(\"opacity\", function(d){\n\t\t\t\t\t//console.log(d.index);\n\t\t\t\t\tif (!d.node.src.show || nodesData[d.node.tgt].outside.isOutside){\n\t\t\t\t\t\td.show = false;\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\td.show = true;\n\t\t\t\t\treturn 1;\t\t\t\t\t\n\t\t\t\t});\n\t\t\td3.selectAll(\".clickBoard\")\n\t\t\t\t.attr(\"fill\", function(d){\n\t\t\t\t\tif (d.content == \"edgeLinks\"){\n\t\t\t\t\t\tif (nodesData[d.node.tgt].outside.isOutside || !d.node.src.show){\n\t\t\t\t\t\t\treturn \"node\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"transparent\";\n\t\t\t\t\t} else if (d.type == \"linkLabel\"){\n\t\t\t\t\t\tif (nodesData[d.node.src].outside.isOutside || nodesData[d.node.tgt].outside.isOutside){\n\t\t\t\t\t\t\treturn \"none\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"transparent\";\n\t\t\t\t\t} \n\t\t\t\t\treturn d.node.showLabel ? \"transparent\" : \"none\";\n\t\t\t\t});\n\n\t\t\tlinks.classed(\"outsideLink\", function(d){\n\t\t\t\tif (d.type == \"edgeLink\"){\n\t\t\t\t\treturn d.target.outside.isOutside;\n\t\t\t\t}\n\t\t\t\tif (d.target.noLayer){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (d.source.outside && d.target.outside){\n\t\t\t\t\t//console.log(d.source.outside.isOutside + \" \" + d.target.outside.isOutside);\n\t\t\t\t\treturn d.source.outside.isOutside || d.target.outside.isOutside;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t});\n\n\t\t\tlayerMap.forEach(function(d, i){\n\t\t\t\tif (i > 0){\n\t\t\t\t\td.forEach(function(e){\n\t\t\t\t\t\tif (!nodesData[e].outside.isOutside && !nodesData[e].fixed){\n\t\t\t\t\t\t\tvar tmp = [];\n\t\t\t\t\t\t\tnodesChildren[e].forEach(function(f){\n\t\t\t\t\t\t\t\tif (!nodesData[f].outside.isOutside){\n\t\t\t\t\t\t\t\t\ttmp.push(nodesData[f].xpos);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\t\t\t\t\n\t\t\t\t\t\t\tnodesData[e].xpos = (d3.min(tmp) + d3.max(tmp)) / 2;\n\t\t\t\t\t\t\tnodesData[e].position.x = nodesData[e].xpos;\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\tforce.start();\n\t\t}\n\t}", "reorder () {\n let nodes = []\n\n walk(this.root.children, (node) => {\n nodes.push(node)\n })\n\n let { baseOrder } = this\n nodes.forEach((node, i) => {\n node.order = baseOrder + i\n })\n }", "assignLevel(node, level) {\n node.level = level;\n if (level+1 > this.depth) {\n this.depth++;\n } \n for (let i = 0; i < node.children.length; i++) { \n this.assignLevel(node.children[i], level+1);\n }\n }", "assignLevel(node, level) {\n node.level = level;\n for (let n of node.children) {\n this.assignLevel(n, level+1);\n }\n }", "function put_to_nodes(node, obj) {\n\t var leaf = isleaf(node, obj);\n\t if (leaf.leaf) node.l.push(obj);else if (leaf.childnode) _put(leaf.childnode, obj);else return;\n\t }", "rebuildTreeIndex() {\n let columnIndex = 0;\n\n this.#rootsIndex.clear();\n\n arrayEach(this.#rootNodes, ([, { data: { colspan } }]) => {\n // Map tree range (colspan range/width) into visual column index of the root node.\n for (let i = columnIndex; i < columnIndex + colspan; i++) {\n this.#rootsIndex.set(i, columnIndex);\n }\n\n columnIndex += colspan;\n });\n }", "function populateRankList(node, ranklist) {\n //console.log(node.r.toLowerCase());\n node.listPosition = ranklist[node.r.toLowerCase()].length;\n ranklist[node.r.toLowerCase()].push(node);\n}", "function moveNodeForNew(node) {\n // when create new box dom, move pass to 150 right\n var first_sub_node_x = getFirstSubNodePosition(node).x;\n // move each node position\n // add paret node, then sub node change position\n // add sub node, then parent node do not change position\n $('g[data-object-id=\"'+node.parent_id+'\"]>use').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>text').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x+30);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>line').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x2\", x+50);\n });\n // moving px\n var px = 0;\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('use').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n px = x - parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('text').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('line').each(function(index_g, element_g){\n var x1 = parseInt($(element_g).attr(\"x1\"));\n var x2 = parseInt($(element_g).attr(\"x2\"));\n $(element_g).attr(\"x1\", x1-75);\n $(element_g).attr(\"x2\", x2-75);\n });\n }", "__groupNodesByPosition(rawNodes) {\n const nodes = [];\n let tmpStack = [];\n _.each(rawNodes, (rawNode, index) => {\n // Check current and next node position\n const $rawNode = $(rawNode);\n const currentNodePosition = this.__getBottomPosition($rawNode);\n let nextNodePosition = -9999;\n if (rawNodes[index + 1]) {\n nextNodePosition = this.__getBottomPosition(rawNodes[index + 1]);\n }\n\n const isListItem = this.__isListItem($rawNode);\n let gapThreshold = 20;\n if (isListItem) {\n gapThreshold = 15;\n }\n\n // Too far appart, we need to add them\n if (currentNodePosition - nextNodePosition > gapThreshold) {\n let content = $rawNode.html();\n\n // We have something in the stack, we need to add it\n if (tmpStack.length > 0) {\n tmpStack.push($rawNode);\n content = _.map(tmpStack, tmpNode => tmpNode.html()).join('\\n');\n tmpStack = [];\n }\n\n nodes.push({ type: this.getNodeType($rawNode), content });\n return;\n }\n\n // Too close, we keep in the stack\n tmpStack.push($rawNode);\n });\n return nodes;\n }", "function storeTreeCoords() {\n var treeId, treeObj, trunkTop, leafsTop;\n\n $trees.forEach(function ($tree) {\n treeId = $tree.getAttribute(\"data-id\");\n treesData[\"tree\" + treeId] = {};\n treeObj = treesData[\"tree\" + treeId];\n treeObj.isRight = $tree.classList.contains(\"m--right\");\n treeObj.$treeTrunk = $tree.querySelector(\".svgBg__tree-trunk\");\n treeObj.$treeLeafs = $tree.querySelector(\".svgBg__tree-leafs\");\n treeObj.trunkInitArrD = treeObj.$treeTrunk.getAttribute(\"d\").split(\" \");\n treeObj.leafsInitArrD = treeObj.$treeLeafs.getAttribute(\"d\").split(\" \");\n trunkTop = treeObj.trunkInitArrD[2];\n leafsTop = treeObj.leafsInitArrD[3];\n treeObj.trunkInitX = +trunkTop.split(\",\")[0];\n treeObj.leafsInitX = +leafsTop.split(\",\")[0];\n treeObj.trunkInitY = +trunkTop.split(\",\")[1];\n treeObj.leafsInitY = +leafsTop.split(\",\")[1];\n });\n }", "_reCalculateVisibleNodePosition() {\n // clear all to avoid leaving selected/select-ready dep lines\n // which created before node position changes.\n this.clearAllHighlight()\n // position calculation\n this.refreshDiagramElements()\n this._setAllDiagramElementsHandler()\n }", "function positionTiles(size_of_matrix){\n\tfor(var i=0;i<size_of_matrix;i++){\n\t\tfor(var j=0;j<size_of_matrix;j++){\n\t\tvar calculatedCoord = getFreeLocation(i,j);\n\t\tMATRIX[get1D(i,j)].coord.setCoord(calculatedCoord);\n\t\tconsole.log(i.toString()+ \" , \"+ j.toString()+ \" at \"+calculatedCoord.leftCoord.toString()+\" , \"+calculatedCoord.topCoord.toString());\n\t\t}\n\t}\n}", "function adjustTree(indexMapLeft,root){\n if(root.hasOwnProperty('children')){\n //console.log(root.data.name)\n var cL=root.children[0];\n var cR=root.children[1];\n //console.log(leavesL,leavesR)\n //console.log(bias0,bias1)\n\n var cross_result=optimizationFun_cross(cL,cR,indexMapLeft);\n if (cross_result<0){\n swapChildren(root);\n }\n else if(cross_result==0){\n if(optimizationFun_order(cL,cR,indexMapLeft)<0)\n swapChildren(root);\n }\n\n adjustTree(indexMapLeft,cL);\n adjustTree(indexMapLeft,cR);\n }\n }", "function swapChildren(root){\n var cR=root.children[0];\n var cL=root.children[1];\n root.children[0]=cL\n root.children[1]=cR;\n increaseSequence(cL,-cR.value);\n increaseSequence(cR,cL.value);\n }", "__update_position_hook() {\n for (var i = 0; i < this.__shapes.length; ++i) {\n this.__shapes[i].shape.set_position(this.__position.add(this.__shapes[i].offset));\n }\n }", "changePxPositionPostIts() {\n let elArray = this.main.children;\n this.getWindowSize();\n for (let i = 0; i < elArray.length; i++) {\n let element = elArray[i];\n let posX = element.getAttribute(\"posX\");\n let posY = element.getAttribute(\"posY\");\n let newPx = this.calculatePercentToPX(posX, posY);\n element.style.transform = `translate(${newPx.pxX}px, ${newPx.pxY}px)`;\n }\n }", "function populateTree(data) {\n for (let n=0;n<data.children.length;n++) {\n populateTree(data.children[n]);\n }\n console.log(\"adding node:'\"+ data.name + \"' id:\"+data.id);\n nodeListByName[data.name]=data.id;\n}", "_setChildren(item, data) {\n // find all children\n const children = data.filter((d) => item.id === d.parent);\n item.children = children;\n if (item.children.length > 0) {\n item.children.forEach((child) => {\n // recursively call itself\n this._setChildren(child, data);\n });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This namespace allows uniqueness over a certain space (uuid string, in this case).
static uuidNamespace() { return '8605fc0f-99cc-4e78-a31b-45b1a7236d9f'; // Generated with uuid v4 }
[ "function TestUuid(uuid){\n let pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n let isValid = pattern.test(uuid);\n return isValid;\n }", "function compute_oid_uuid(data)\n{\n return hex_to_bin(uuid_v5(data, NAMESPACE_OID));\n}", "function unique_node_id(name, type) {\n let idstring = node_machine_id_1.machineIdSync();\n return NODE_TYPE[type] + '-' + crypto_1.createHash('sha1').update(`${idstring}-${name}`).digest('base64');\n}", "function isUuid(value) {\n if (typeof value === \"string\" && value.length === 36) {\n return !!value.match(UUID_PATT)\n }\n return false;\n }", "function validateUUID(arg) {\n if (!arg) {\n console.error('Error: missing UUID');\n process.exit(1);\n }\n if (!UUID_REGEX.test(arg)) {\n console.error('Error: invalid UUID \"%s\"', arg);\n process.exit(1);\n }\n return arg;\n}", "function uuid() {\n // get sixteen unsigned 8 bit random values\n const u = crypto.getRandomValues(new Uint8Array(16))\n\n // set the version bit to v4\n u[6] = (u[6] & 0x0f) | 0x40\n\n // set the variant bit to \"don't care\" (yes, the RFC\n // calls it that)\n u[8] = (u[8] & 0xbf) | 0x80\n\n // hex encode them and add the dashes\n let uid = ''\n uid += u[0].toString(16)\n uid += u[1].toString(16)\n uid += u[2].toString(16)\n uid += u[3].toString(16)\n uid += '-'\n\n uid += u[4].toString(16)\n uid += u[5].toString(16)\n uid += '-'\n\n uid += u[6].toString(16)\n uid += u[7].toString(16)\n uid += '-'\n\n uid += u[8].toString(16)\n uid += u[9].toString(16)\n uid += '-'\n\n uid += u[10].toString(16)\n uid += u[11].toString(16)\n uid += u[12].toString(16)\n uid += u[13].toString(16)\n uid += u[14].toString(16)\n uid += u[15].toString(16)\n\n return uid\n}", "function service2id(n)\n {\n return \"dummy_\"+n.replace(\" \",\"_\");\n }", "findUniqueIdentifier() {\n const metadataId = this.attributes[\"unique-identifier\"];\n if (metadataId) {\n const uidMetadata = this.metadata.findItemWithId(\n \"dc:identifier\",\n metadataId\n );\n if (uidMetadata) {\n return uidMetadata.value;\n }\n }\n }", "function getUuid(htmlid)\n{\n var idInfo = htmlid.split(\"-\");\n var uuid = idInfo[1];\n \n for(var i=2; i < idInfo.length; i++)\n {\n uuid += \"-\"+idInfo[i];\n }\n \n return uuid\n}", "_generateUniqueConstraintName(table, columns) {\n let indexName = `uniq${table}${columns.join('')}`.replace(/[.,\"\\s]/g, '').toLowerCase();\n\n //Oracle doesn't support names with more that 32 characters, so we replace it by PK timestamp\n if (indexName.length > 30) {\n indexName = `uniq${table}${crc32(columns.join(''))}`.replace(/[.,\"\\s]/g, '').toLowerCase();\n\n if (indexName.length > 30) {\n const crcName = crc32(`${table}_${columns.join('')}`);\n indexName = `uniq${crcName}`.replace(/[.,\"\\s]/g, '').toLowerCase();\n }\n }\n\n return indexName;\n }", "register_random_uuid(desc) {\n let res = randomUUID();\n this._magic.register('uuid', res, desc);\n return res;\n }", "function generateUID() {\n return String(~~(Math.random()*Math.pow(10,8)))\n}", "function shortId() {\n\treturn crypto\n\t\t.randomBytes(5)\n\t\t.toString(\"base64\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/=+$/, \"\");\n}", "function kva_uuid() {\n var uuid = Cookies.get('kva_uuid');\n if (typeof uuid === 'undefined') {\n Cookies.set('kva_uuid', UUID(), {expires: 365});\n uuid = Cookies.get('kva_uuid');\n }\n return uuid;\n}", "function uniqueURI(container, callback) {\n\t\tvar candidate = addPath(container, 'res' + Date.now())\n\t\tdb.reserveURI(candidate, function(err) {\n\t\t\tcallback(err, candidate)\n\t\t});\n\t}", "function doGenerateUniqueID(studyID, caseID) {\n let newCID = caseID.includes('-') ? caseID.replace('-','') : caseID;\n return `${studyID}-${newCID}`\n}", "function uniqueString() {\n return \"&sUnique=\" + new Date().getTime();\n}", "function makeTuid() {\n return crypto.randomBytes(16).toString('hex')\n}", "function generateUuid() {\n let uuid = token();\n return uuid;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset zoom on the map to show all markers
function resetZoom() { map.setCenter({lat: 24.789973, lng: 46.656051}) map.setZoom(15) map.fitBounds(bounds) }
[ "function reset() {\n var browserWidth = $(window).width();\n if(browserWidth <= 1000) {\n map.setCenter(mapOptions.center);\n map.setZoom(11);\n } else if(browserWidth > 1000) {\n map.setCenter(mapOptions.center);\n map.setZoom(12);\n }\n }", "resetMapAndVars(){\n controller.infoWindow.close();\n model.map.setZoom(13);\n model.map.setCenter(model.athensCenter);\n }", "function clearMarkers() {\n let initialCitiesLength = Object.keys(INITIALCITIES).length;\n for (let i = MARKERS.length - 1; i >= initialCitiesLength; i--) {\n MARKERS[i].setMap(null);\n MARKERS.splice(i, 1);\n }\n }", "function clearMap() {\n for (var i = 0; i < facilityMarkers.length; ++i) {\n facilityMarkers[i].setMap(null);\n }\n facilityMarkers = [];\n}", "function resetScatterZoom() {\n window.scatter.resetZoom();\n}", "clearAllZoomRegions() {\n for (let i = 0; i < this._zoomRegions.length; i++)\n this._zoomRegions[i].setActive(false);\n\n this._zoomRegions.length = 0;\n this.stopTrackingMouse();\n this.showSystemCursor();\n }", "function setZoomOnMarkerClick(){\n const currentZoom = map.getZoom();\n if (currentZoom < 12){\n map.setZoom(17);\n }\n }", "function resetMarkers() {\n markers.forEach((marker) => {\n marker.setIcon('likes.png')\n marker.setAnimation(null)\n })\n }", "function zoom() {\n airbnbNodeMap.zoom();\n mapLineGraph.wrangleData_borough();\n}", "function reloadMap() {\n map.invalidateSize();\n}", "removeAllMarkers() {\n if (this.markerGroup) this.markerGroup.clearLayers();\n }", "function resetStreetViews(){\n for (var i = 0; i < svpArray.length; i++) {\n svpArray[i].marker.setMap(null);\n }\n svpArray = [];\n $(\"#loading\").css('visibility', 'visible');\n directionsDisplay.setMap(null);\n }", "function clearLat() {\n lat = [];\n}", "function resetPoints() {\n\tfor(var key in markerList) {\n\t\tmarkerList[key].marker.setIcon(markerList[key].markerImage);\n\t}\n}", "function hideAllStatesMarkers () {\n for (var stateName in states) {\n if (states.hasOwnProperty(stateName)) {\n states[stateName].marker.setMap(null)\n }\n }\n }", "function setZoomLevel(value=0){\n map.setZoom(value);\n}", "function zoomExtents() {\n var bounds = new google.maps.LatLngBounds();\n if (markers.length > 1) {\n for (var i = 0; i < markers.length; i++) {\n bounds.extend(markers[i].getPosition());\n map.fitBounds(bounds);\n }\n }else if (markers.length === 1 ){\n map.panTo(markers[0].position);\n map.setZoom(14)\n }\n}", "function reset() {\n if (polyline) {\n polyline.setMap(null);\n }\n\n if (polyline2) {\n polyline2.setMap(null);\n }\n\n for (var i in markers) {\n markers[i].setMap(null);\n }\n\n markers = [];\n\n document.getElementById('chart_div').style.display = 'none';\n document.getElementById('text_div').style.display = 'none';\n}", "function updateMapExtents() {\n var extent = [];\n if (dataLayers.length == 0) {\n extent = [0.0, 0.0, 1.0, 1.0];\n } else {\n extent = dataLayers[0].mapLayer.getSource().getExtent();\n // Make a clone\n extent = [...extent]\n for (var i = 1; i < dataLayers.length; i++) {\n var layerExtent = dataLayers[i].mapLayer.getSource().getExtent();\n extent[0] = Math.min(extent[0], layerExtent[0])\n extent[1] = Math.min(extent[1], layerExtent[1])\n extent[2] = Math.max(extent[2], layerExtent[2])\n extent[3] = Math.max(extent[3], layerExtent[3])\n }\n }\n zoomAllControl.extent = extent;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stringify an array of property tuples.
function stringifyProperties(properties) { var result = []; var _loop_1 = function (name, value) { if (value != null) { if (Array.isArray(value)) { value.forEach(function (value) { value && result.push(styleToString(name, value)); }); } else { result.push(styleToString(name, value)); } } }; for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var _a = properties_1[_i], name = _a[0], value = _a[1]; _loop_1(name, value); } return result.join(';'); }
[ "function arrToStr(arr) {\n\t//initialize resulting string\n\tvar res = \"Array[\";\n\t//loop thru array elements\n\tfor( var index = 0; index < arr.length; index++ ){\n\t\tres += (index > 0 ? \", \" : \"\") + objToStr(arr[index]);\n\t}\n\treturn res + \"]\";\n}", "function arrayToString()\n{\n\tif ( ! arguments.length ) { return '/' + this.map( mapValue ).join( '/' ) ; } // jshint ignore:line\n\telse { return '/' + Array.prototype.slice.apply( this , arguments ).map( mapValue ).join( '/' ) ; } // jshint ignore:line\n}", "_serialize() {\n return JSON.stringify([\n this._id,\n this._label,\n this._properties\n ]);\n }", "get assignedValuesString() {\n return `[ ${this.assignedValues.join(', ')} ]`;\n }", "function toString ()\n{\n let baleString = \"\";\n let fieldNames = Object.keys(PROPERTIES);\n\n // Loop through the fieldNames and build the string \n for (let name of fieldNames)\n {\n baleString += name + \":\" + this[name] +\";\";\n }\n\n return baleString;\n}", "function arrayElemsToString(arr, delim) {\n if (delim === undefined)\n delim = \" \";\n var ret = \"\";\n for (var i = 0;i < arr.length; ++i) {\n ret += arr[i];\n if (i < arr.length - 1)\n ret += delim;\n }\n return ret;\n}", "function arrayToData(values) {\n\t\t// Are we dealing with multi-dimensional array\n\t\t// If so then we need to convert array to a string, but with a \n\t\t// pipe seperating each array dimension\n\t\tif (typeof values[0] == \"object\") {\n\t\t\tvar r = '';\n\t\t\t// Loop through dimensions\n\t\t\tfor (var i = 0, len = values.length; i < len; i++) {\n\t\t\t\t// If we are onto another dimension then add a pipe character (marks seperation)\n\t\t\t\tif (i > 0) r = r.slice(0, -1) + '|';\n\t\t\t\t// Loop through values of array\n\t\t\t\tfor (var x = 0, ilen = values[i].length; x < ilen; x++) {\n\t\t\t\t\tr+= values[i][x] + ',';\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Return formatted string\n\t\t\treturn r.slice(0, -1);\n\t\t}\n\t\t// Else normal single dimensional array, so just return as is\n\t\telse { \n\t\t\treturn values;\n\t\t}\n\t}", "function concatValues(obj) {\n\n value = \"\";\n for (var prop in obj) {\n var parts = obj[prop].split(\",\");\n var vals = value.split(\",\");\n var newvals = cartesian(parts, vals);\n\n value = newvals.map(x => concatArr(x)).join(',');\n }\n\n return value;\n}", "serialize() {\n // cur level\n let sCurLevel = this.curLevelNum + '';\n // instrs shown\n let sInstructions = 'none';\n if (this.instructionsShown.size > 0) {\n sInstructions = Array.from(this.instructionsShown).join(';');\n }\n // level infos\n let sLevelInfos = 'none';\n if (this.levelInfos.size > 0) {\n let arrLevelInfos = [];\n for (let [n, lvlInfo] of this.levelInfos.entries()) {\n arrLevelInfos.push(n + ':' + lvlInfo.serialize());\n }\n sLevelInfos = arrLevelInfos.join(';');\n }\n return [sCurLevel, sInstructions, sLevelInfos].join('|');\n }", "function dumplist(l) { \n var i, rv = []; \n \n rv.push(\"has \"+l.length+\" elements:\"); \n for (i=0; i<l.length; i++) { \n rv.push(\" \"+i+\"\\t\"+l[i].toSpecifier()+ \n \"\\t\"+l[i].markupTag.name); \n } \n return rv.join(\"\\n\"); \n}", "function createValueString(fields) {\n const valueString = Object.values(fields).map( (_, index) => `$${index + 1}` ).join(', ');\n return valueString;\n}", "function stringifyBSPArray() {\n\tvar BSPArrayString = '';\n\t//console.log(shell.branchStartPages.BSPArray);\n\tvar num = 0;\n\tfor (key in shell.branchStartPages.BSPArray) {\n\t\tif (num != 0) {\n\t\t\tBSPArrayString += \"&&\";\n\t\t}\n\t\tvar currArray = shell.branchStartPages.BSPArray[key];\n\t\t//console.log(currArray);\n\t\tBSPArrayString += currArray[0].bsp+\"=\";\n\t\tfor (var i=0, j=currArray.length; i<j; i++) {\n\t\t\tvar currObj = currArray[i];\n\t\t\tBSPArrayString += currObj.id+\",\";\n\t\t\tBSPArrayString += currObj.trigger+\",\";\n\t\t\tBSPArrayString += currObj.isComplete;\n\t\t\tif (i != j-1) {\n\t\t\t\tBSPArrayString += \"!!\";\n\t\t\t}\n\t\t}\n\t\tnum++;\n\t};\n\t//console.log(BSPArrayString);\n\treturn BSPArrayString;\n}", "function zipObject(propArr, valArr){\n let result = {};\n //filling up the valArr with undefined\n if (propArr.length > valArr.length){\n let difference = propArr.length - valArr.length;\n while(difference > 0){\n valArr.push(undefined);\n difference --;\n }\n }\n for(let j=0; j<propArr.length; j++){\n result[propArr[j]]=valArr[j];\n }\n return result;\n}", "function listify(array){\n\tlist = [];\n\tfor (var i=0; i<array.length; i++){\n\t\tlist.push(array[i].product_name + \" | $\" + array[i].price);\n\t}\n\treturn list\n}", "function personsArrayToString(authorsArray) {\n /* jshint camelcase: false */\n /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */\n authorsArray = Array.isArray(authorsArray) ? authorsArray : [];\n\n return authorsArray.map(function (author) {\n if (author.first_name && 0 !== author.first_name.length) {\n return author.last_name + ', ' + author.first_name;\n } else {\n return author.last_name;\n }\n }).join('\\n');\n}", "function SysFmtStringToArray(){}", "function printResult( data, delimeter, ...propertiesToPrint ){\n\n if( data.length === 0 ){\n console.log(\"\\nEmpty data : \", data );\n return;\n }\n\n console.log(\"\\n*********************** Result Start ***********************\\n\");\n data.forEach( ( item, index ) => {\n\n let str = '';\n propertiesToPrint.forEach( property => {\n str = str + property + \": \" + item[ property ] + delimeter;\n });\n \n console.log(\n `${ index + 1 }. ${ str }`\n )\n\n });\n console.log(\"\\n*********************** Result End ***********************\\n\");\n\n}", "function v3ToString(v){\n\t\t\treturn v.x + ',' + v.y + ',' + v.z;\n\t}", "function polyExport(polygon) {\n return [polygon.totext, polygon.program, polygon.height, 'Polygon'];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct type info for reflection. This iterates over the flattened list of uniform type values and smashes them into a JSON object. The leaves of the resulting object are either indices or type strings representing primitive glslify types
function makeReflectTypes(uniforms, useIndex) { var obj = {} for(var i=0; i<uniforms.length; ++i) { var n = uniforms[i].name var parts = n.split(".") var o = obj for(var j=0; j<parts.length; ++j) { var x = parts[j].split("[") if(x.length > 1) { if(!(x[0] in o)) { o[x[0]] = [] } o = o[x[0]] for(var k=1; k<x.length; ++k) { var y = parseInt(x[k]) if(k<x.length-1 || j<parts.length-1) { if(!(y in o)) { if(k < x.length-1) { o[y] = [] } else { o[y] = {} } } o = o[y] } else { if(useIndex) { o[y] = i } else { o[y] = uniforms[i].type } } } } else if(j < parts.length-1) { if(!(x[0] in o)) { o[x[0]] = {} } o = o[x[0]] } else { if(useIndex) { o[x[0]] = i } else { o[x[0]] = uniforms[i].type } } } } return obj }
[ "function buildWebTypes() {\n const analysis = loadAnalysis();\n\n const packageJson = JSON.parse(fs.readFileSync(`./package.json`, 'utf8'));\n const entrypoints = analysis.modules.filter((el) => !el.path.startsWith('lib'));\n\n const plainWebTypes = createPlainWebTypes(packageJson, entrypoints);\n const plainWebTypesJson = JSON.stringify(plainWebTypes, null, 2);\n fs.writeFileSync(PLAIN_WEB_TYPES_FILE, plainWebTypesJson, 'utf8');\n\n const litWebTypes = createLitWebTypes(packageJson, entrypoints);\n const litWebTypesJson = JSON.stringify(litWebTypes, null, 2);\n fs.writeFileSync(path.join(LIT_WEB_TYPES_FILE), litWebTypesJson, 'utf8');\n}", "function initTypes() {\n // Boolean for production/file supplied/online or not\n var online = false;\n var json_raw_data = null;\n var var_types_url = null;\n if (online) {\n // Retrieve from dataverse API\n } else {\n // Read from local'\n var_types_url = \"../../data/preprocess_4_v1-0.json\";\n }\n\n d3.json(var_types_url, function(json_data) {\n var json_variables = json_data['variables'];\n // Loop through all the variables\n for(var key in json_variables) {\n var current_variable = json_variables[key];\n // Boolean\n if (current_variable['binary'] == 'yes') {\n types_for_vars[key] = 'Boolean';\n } else {\n var current_variable_nature = current_variable['nature'];\n if (current_variable_nature == 'ordinal') {\n // Numerical\n types_for_vars[key] = 'Numerical';\n } else if (current_variable_nature == 'nominal') {\n // Categorical\n types_for_vars[key] = 'Categorical';\n }\n }\n }\n generate_modal4();\n });\n}", "function setupTypeInfo() {\n for (var i in document.ANALYSIS_DATA) {\n var data = document.ANALYSIS_DATA[i];\n\n var el = document.getElementById(\"implements-\" + i);\n if (el != null) {\n // el != null => data is TypeInfoJSON.\n if (data.ImplGroups != null) {\n el.innerHTML = implementsHTML(data);\n el.parentNode.parentNode.style.display = \"block\";\n }\n }\n\n var el = document.getElementById(\"methodset-\" + i);\n if (el != null) {\n // el != null => data is TypeInfoJSON.\n if (data.Methods != null) {\n el.innerHTML = methodsetHTML(data);\n el.parentNode.parentNode.style.display = \"block\";\n }\n }\n }\n}", "encodeType(name) {\n const result = this.#fullTypes.get(name);\n (0, index_js_4.assertArgument)(result, `unknown type: ${JSON.stringify(name)}`, \"name\", name);\n return result;\n }", "visitSqlj_object_type_attr(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function addType() {\n\t\tvar args = extract(\n\t\t\t{ name: 'name', test: function(o) { return typeof o === 'string'; } },\n\t\t\t{ name: 'type', parse: function(o) {\n\t\t\t\treturn (o instanceof Type) ? o : new Type(this.name || o.name, o);\n\t\t\t} }\n\t\t).from(arguments);\n\n\t\ttypeList.push(args.type);\n\t}", "function collectTypes (path: NodePath): void {\n path.traverse({\n InterfaceDeclaration (path: NodePath) {\n path.scope.setData(`typechecker:${path.node.id.name}`, path);\n },\n TypeAlias (path: NodePath) {\n path.scope.setData(`typechecker:${path.node.id.name}`, path);\n },\n ImportDeclaration (path: NodePath) {\n if (path.node.importKind !== 'type') {\n return;\n }\n path.get('specifiers')\n .forEach(specifier => {\n const local = specifier.get('local');\n if (local.isIdentifier()) {\n path.scope.setData(`typechecker:${local.node.name}`, specifier);\n }\n else {\n path.scope.setData(`typechecker:${local.node.id.name}`, specifier);\n }\n });\n },\n \"Function|Class\" (path: NodePath) {\n const node = path.node;\n if (node.typeParameters && node.typeParameters.params) {\n path.get('typeParameters').get('params').forEach(typeParam => {\n path.get('body').scope.setData(`typeparam:${typeParam.node.name}`, typeParam);\n });\n }\n }\n });\n }", "consoleParseTypes(input) { return Parser.parse(input, { startRule: 'TYPES' }); }", "function discoverTypes () {\n // rdf:type properties of subjects, indexed by URI for the type.\n\n const types = {}\n\n // Get a list of statements that match: ? rdfs:type ?\n // From this we can get a list of subjects and types.\n\n const subjectList = kb.statementsMatching(\n undefined,\n UI.ns.rdf('type'),\n tableClass, // can be undefined OR\n sourceDocument\n ) // can be undefined\n\n // Subjects for later lookup. This is a mapping of type URIs to\n // lists of subjects (it is necessary to record the type of\n // a subject).\n\n const subjects = {}\n\n for (let i = 0; i < subjectList.length; ++i) {\n const type = subjectList[i].object\n\n if (type.termType !== 'NamedNode') {\n // @@ no bnodes?\n continue\n }\n\n const typeObj = getTypeForObject(types, type)\n\n if (!(type.uri in subjects)) {\n subjects[type.uri] = []\n }\n\n subjects[type.uri].push(subjectList[i].subject)\n typeObj.addUse()\n }\n\n return [subjects, types]\n }", "function dataTypeSeer(array) {\n\tfor (var i = 0; i < array.length; i++) {\n\t\tconsole.log(typeof array[i]);\n\t};\n}", "getTypes(pokemon) {\n let types = [];\n for(let i = 0; i < pokemon.types.length; i++) {\n const type = pokemon.types[i].type.name;\n types.push(\n <span\n className={\"b-outline type type-\" + type}\n key={type}\n >\n {type}\n </span>\n );\n }\n return types;\n }", "function guessTypeOfValue(tval) {\n if (tval['ctype'] === 'boolean') {\n return type.bool;\n } else if (tval['ctype'] === 'number') {\n let z = tval['value'];\n if (Math.abs(z['imag']) < 1e-5) { //eps test. for some reasons sin(1) might have some imag part of order e-17\n if ((z['real'] | 0) === z['real']) {\n return type.int;\n } else {\n return type.float;\n }\n } else {\n return type.complex;\n }\n } else if (tval['ctype'] === 'list') {\n let l = tval['value'];\n if (l.length === 3) {\n if (tval[\"usage\"] === \"Point\")\n return type.point;\n else if (tval[\"usage\"] === \"Line\")\n return type.line\n }\n if (l.length > 0) {\n let ctype = guessTypeOfValue(l[0]);\n for (let i = 1; i < l.length; i++) {\n ctype = lca(ctype, guessTypeOfValue(l[i]));\n }\n if (ctype) return {\n type: 'list',\n length: l.length,\n parameters: ctype\n };\n }\n } else if (tval['ctype'] === 'string' || tval['ctype'] === 'image') {\n return type.image;\n } else if (tval['ctype'] === 'geo' && tval['value']['kind'] === 'L') {\n return type.line;\n }\n console.error(`Cannot guess type of the following type:`);\n console.log(tval);\n return false;\n}", "constructor(options) {\n /// @internal\n this.typeNames = [\"\"];\n /// @internal\n this.typeIDs = Object.create(null);\n /// @internal\n this.prop = new NodeProp();\n this.flags = options.flags;\n this.types = options.types;\n this.flagMask = Math.pow(2, this.flags.length) - 1;\n this.typeShift = this.flags.length;\n let subtypes = options.subtypes || 0;\n let parentNames = [undefined];\n this.typeIDs[\"\"] = 0;\n let typeID = 1;\n for (let type of options.types) {\n let match = /^([\\w\\-]+)(?:=([\\w-]+))?$/.exec(type);\n if (!match)\n throw new RangeError(\"Invalid type name \" + type);\n let id = typeID++;\n this.typeNames[id] = match[1];\n this.typeIDs[match[1]] = id;\n parentNames[id] = match[2];\n for (let i = 0; i < subtypes; i++) {\n let subID = typeID++, name = match[1] + \"#\" + (i + 1);\n this.typeNames[subID] = name;\n this.typeIDs[name] = subID;\n parentNames[subID] = match[1];\n }\n }\n this.parents = parentNames.map(name => {\n if (name == null)\n return 0;\n let id = this.typeIDs[name];\n if (id == null)\n throw new RangeError(`Unknown parent type '${name}' specified`);\n return id;\n });\n if (this.flags.length > 30 || this.typeNames.length > Math.pow(2, 30 - this.flags.length))\n throw new RangeError(\"Too many style tag flags to fit in a 30-bit integer\");\n }", "function buildTargetTypes() {\n let url = `https://pokeapi.co/api/v2/move-target/`;\n superagent.get(url)\n .then((results) => {\n results.body.results.forEach((result) => {\n let SQL = `INSERT INTO target_type(api_id, name) VALUES($1, $2);`;\n let values = [result.url.split('/')[6], result.name];\n\n client.query(SQL, values);\n })\n })\n}", "function makePrimitives(sexpr) {\n var i, value, elems;\n\n if (sexpr.type === 'list') {\n elems = sexpr.value.map(function(s) {\n return makePrimitives(s);\n });\n\n return Data.List(elems);\n }\n\n if (sexpr.type === \"string\") {\n return Data.String(sexpr.value);\n }\n\n if (sexpr.type === 'symbol') {\n return reifySymbol(sexpr);\n }\n\n throw new Error(\"unrecognized s-expression type: \" + sexpr.type);\n }", "typesList(types) {\n this.snippet.appendText(\" [\");\n this.textOrPlaceholder(types, \"<Type>\");\n this.snippet.appendText(\"]\");\n }", "function rehype2json() {\n this.Compiler = node => {\n const rootNode = getRootNode(node)\n visit(rootNode, removePositionFromNode)\n return JSON.stringify(rootNode)\n }\n}", "function parseTypeExpressionList() {\n var elements = [];\n elements.push(parseTop());\n\n while (token === Token.COMMA) {\n consume(Token.COMMA);\n elements.push(parseTop());\n }\n\n return elements;\n } // TypeName :=", "function InferTypes () {\n ASTTransform.call(this);\n this.varDefs = {};\n this.fnSignatures = {};\n this.fnTypeHints = {};\n this.fnRenaming = {};\n this.runAgain = false;\n}", "typeSpec() {\n const token = this.currentToken;\n if (this.currentToken.type === tokens.INTEGER) {\n this.eat(tokens.INTEGER);\n } else if (this.currentToken.type === tokens.REAL) {\n this.eat(tokens.REAL);\n }\n return new Type(token);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
turn a string into yellow (for the interactive console)
function yellow(s) { return '\u001b[33m' + s + '\u001b[39m' }
[ "function analyzeColor(input) {\n if (input === \"blue\") {\n return \"blue is the color of the sky\";\n }\n if (input === \"red\") {\n return \"Strawberries are red\";\n }\n if (input === \"cyan\") {\n return \"I don't know anything about cyan\";\n } else {\n return \"A girl has no \" + input + \" color.\";\n }\n}", "function letterboxColor (command_) {\n\tvar argList = toArgList (command_);\n\n\tvar red = argList[1];\n\tvar green = argList[2];\n\tvar blue = argList[3];\n\n\tdocument.body.style.background = 'rgb(' + red + ',' + green + ',' +\n\t blue + ')';\n}", "function failure(text){\n return FAILURE_COLOUR + text + RESET_COLOUR;\n}", "function analyzeColor(color) {\n var colorMessage = \"\";\n if(color === \"blue\") {\n colorMessage = \"blue is the color of the sky\";\n } else if(color === \"red\") {\n colorMessage = \"Strawberries are red\";\n } else if(color === \"cyan\") {\n colorMessage = \"I don't know anything about cyan\";\n } else {\n colorMessage = \"I don't know about that color\";\n }\n\n return colorMessage;\n}", "function changeColor(color) {\n gMeme.currText.color = color\n}", "function highlight(str){\n\t\t \treturn '<a rel=\"nofollow\" href=\"https://twitter.com/hashtag/'+str.replace(/#/,'') +'\">'+str+'</a>';\n\t\t \t\n\t\t }", "function setColorText(hexcolor) {\n color.textContent = hexcolor;\n}", "_setColor() {\n this._container.classList.remove(\n `alert--${this._data.color === \"red\" ? \"green\" : \"red\"}`\n );\n this._container.classList.add(`alert--${this._data.color}`);\n }", "function producePrompt(message, promptLocation, color)\n{\n\tdocument.getElementById(promptLocation).innerHTML = message; \n\tdocument.getElementById(promptLocation).style.color = color; \n}", "static Yellow() {\n return new Color4(1, 1, 0, 1);\n }", "function colorSpan(color, text) {\n let span = document.createElement('SPAN');\n span.style.color = color;\n span.innerText = text;\n return span;\n}", "function TextColored(col, fmt /*, ...args: any[]*/) {\r\n bind.TextColored((col instanceof ImColor) ? col.Value : col, fmt /*, ...args*/);\r\n }", "function solveYellowLine(cube) {\n F(cube);\n R(cube);\n U(cube);\n Ri(cube);\n Ui(cube);\n Fi(cube);\n //console.log(\"front, right, up, right inverse, up inverse, front inverse (yellow cross created)\");\n commandSolveYellowCross += \"<br>Solves yellow 'line': front, right, up, right inverse, up inverse, front inverse, \";\n commandSolveAllEnd += \"front, right, up, right inverse, up inverse, front inverse, \";\n}", "static Yellow() {\n return new Color3(1, 1, 0);\n }", "function setCorrectColor(verb, isok = false) {\n if (isok)\n $(verb).css(\"background-color\", \"palegreen\");\n else\n $(verb).css(\"background-color\", \"\");\n}", "function printColor(){\n\tlet colorChange = getColor();\n\treturn document.body.style.background = colorChange\n}", "updateColor (color) {\n this._sendMessage([0x56].concat(color).concat(0xAA))\n }", "function redlistcolor(codein)\r\n{\r\n switch(codein)\r\n {\r\n case \"EX\":\r\n\t\t\treturn ('rgb(0,0,180)');\r\n //return ('rgb(0,0,0)');\r\n case \"EW\":\r\n\t\t\treturn ('rgb(60,50,135)');\r\n //return ('rgb(80,80,80)');\r\n case \"CR\":\r\n\t\t\treturn ('rgb(210,0,10)');\r\n case \"EN\":\r\n\t\t\treturn ('rgb(125,50,00)');\r\n case \"VU\":\r\n\t\t\treturn ('rgb(85,85,30)');\r\n case \"NT\":\r\n\t\t\treturn ('rgb(65,120,0)');\r\n case \"LC\":\r\n\t\t\treturn ('rgb(0,180,20)');\r\n case \"DD\":\r\n\t\t\treturn ('rgb(80,80,80)');\r\n //return ('rgb(60,50,135)');\r\n case \"NE\":\r\n\t\t\treturn ('rgb(0,0,0)');\r\n //return ('rgb(0,0,190)');\r\n default:\r\n\t\t\treturn ('rgb(0,0,0)');\r\n }\r\n}", "setTextColor(color) { this.textColor = color }", "function logShout(string) {\n console.log(string.toUpperCase());\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a box data object for the given node. The values of the returned object are read only.
function createBoxData(node) { var style = window.getComputedStyle(node); var bt = parseInt(style.borderTopWidth, 10) || 0; var bl = parseInt(style.borderLeftWidth, 10) || 0; var br = parseInt(style.borderRightWidth, 10) || 0; var bb = parseInt(style.borderBottomWidth, 10) || 0; var pt = parseInt(style.paddingTop, 10) || 0; var pl = parseInt(style.paddingLeft, 10) || 0; var pr = parseInt(style.paddingRight, 10) || 0; var pb = parseInt(style.paddingBottom, 10) || 0; var data = Object.create(boxDataProto); if (bt !== 0) data._m_bt = bt; if (bl !== 0) data._m_bl = bl; if (br !== 0) data._m_br = br; if (bb !== 0) data._m_bb = bb; if (pt !== 0) data._m_pt = pt; if (pl !== 0) data._m_pl = pl; if (pr !== 0) data._m_pr = pr; if (pb !== 0) data._m_pb = pb; return data; }
[ "function makeCustomBox(boxData) {\n\t\tif (boxData.condition == null || boxData.condition()) {\n\t\t\tvar box = makeBox(boxData);\n\t\t\tif (boxData.img != null) {\t\t\t\t\t\t\t\t\t\t\t//pic boxes\n\t\t\t\tvar pic = document.createElement(\"img\");\n\t\t\t\tpic.classList.add(\"picBox\");\n\t\t\t\tpic.src = BOX_PATH + simpleEval(boxData.img) + \".jpg\";\n\t\t\t\tgetById(\"picBoxes\").appendChild(pic);\n\t\t\t}\n\t\t\tif(boxData.addListeners != null) {\n\t\t\t\tboxData.addListeners(box);\n\t\t\t}\n\t\t\tgetById(\"boxes\").appendChild(box);\n\t\t}\n\t}", "function createNameData(data) {\n\tvar className = 'info-box';\n\tvar node = generateInfoBlock({\n\t\tname : data.name\n\t}, className);\n\tmark(node, 'name-box');\n\tconsole.log('create name data returns', node);\n\treturn node;\n}", "function Node(data){\n \n this.data = data;\n this.parent = null;\n this.children = [];\n\n}", "function Box2dModelNode(nodeType, view) {\n\tthis.view = view;\n\tthis.type = nodeType;\n\tthis.prevWorkNodeIds = [];\n\t\n\t/////\n\t////\tTHESE NEED TO BE PLACED IN box2dModelEvents as well;\n\n\tthis.customEventTypes = ['make-model', 'delete-model', 'make-beaker', 'delete-beaker', 'make-scale', 'delete-scale', 'make-beaker', 'delete-beaker', 'add-to-beaker', 'add-to-scale', 'add-to-balance', 'remove-from-beaker', 'remove-from-scale', 'remove-from-balance', 'test-in-beaker', 'test-on-scale', 'test-on-balance','gave-feedback'];\t\n}", "function _nodeViz(node) {\n var viz = {};\n\n // Color\n var color_el = _helpers.getFirstElementByTagNS(node, 'viz', 'color');\n\n if (color_el) {\n var color = ['r', 'g', 'b', 'a'].map(function (c) {\n return color_el.getAttribute(c);\n });\n\n viz.color = _helpers.getRGB(color);\n }\n\n // Position\n var pos_el = _helpers.getFirstElementByTagNS(node, 'viz', 'position');\n\n if (pos_el) {\n viz.position = {};\n\n ['x', 'y', 'z'].map(function (p) {\n viz.position[p] = +pos_el.getAttribute(p);\n });\n }\n\n // Size\n var size_el = _helpers.getFirstElementByTagNS(node, 'viz', 'size');\n if (size_el) viz.size = +size_el.getAttribute('value');\n\n // Shape\n var shape_el = _helpers.getFirstElementByTagNS(node, 'viz', 'shape');\n if (shape_el) viz.shape = shape_el.getAttribute('value');\n\n return viz;\n }", "function createContentDigest(node) {\n if (!node?.internal?.type) {\n // this doesn't look like a node, so let's just pass it as-is\n return _createContentDigest(node)\n }\n return _createContentDigest({\n ...node,\n internal: {\n ...node.internal,\n // Remove auto-generated fields that'd prevent\n // creating a consistent contentDigest.\n contentDigest: undefined,\n owner: undefined,\n fieldOwners: undefined,\n ignoreType: undefined,\n counter: undefined,\n },\n fields: undefined,\n })\n}", "function getNodeValue(node, type) {\n var array = keys(node.children);\n \n // Just get the leaf node value,\n // if a node is not a leaf node and its value is not undefined,\n // then the value is ignored.\n if (array.length === 0){\n // Mark the parent node is the second last node,\n // so it is convenient to know in which node can remove attributes\n node.parentNode.secondNode = true;\n return node.value;\n }\n\n var assignArray = map(array, function(key) {\n var child = node.children[key];\n return {\n key: child.key,\n value: getNodeValue(child, type),\n };\n });\n\n return assignData(node, assignArray, type);\n\n}", "function BinaryBox(x, y, size, isClickable) {\n this.size = size;\n this.isClickable = isClickable;\n\n\n if (size == BoxSize.LARGE) {\n LargeTextBox.call(this, x, y, size, size, \"0\", isClickable);\n \n } else {\n TextBox.call(this, x, y, size, size, \"0\", undefined, isClickable);\n }\n }", "function makeBox(ctx)\n{\n // box\n // v6----- v5\n // /| /|\n // v1------v0|\n // | | | |\n // | |v7---|-|v4\n // |/ |/\n // v2------v3\n //\n // vertex coords array\n var vertices = new Float32Array(\n [ 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1, // v0-v1-v2-v3 front\n 1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1, // v0-v3-v4-v5 right\n 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0-v5-v6-v1 top\n -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1, // v1-v6-v7-v2 left\n -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1, // v7-v4-v3-v2 bottom\n 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 ] // v4-v7-v6-v5 back\n );\n\n // normal array\n var normals = new Float32Array(\n [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0-v1-v2-v3 front\n 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0-v3-v4-v5 right\n 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0-v5-v6-v1 top\n -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1-v6-v7-v2 left\n 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7-v4-v3-v2 bottom\n 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 ] // v4-v7-v6-v5 back\n );\n\n\n // texCoord array\n var texCoords = new Float32Array(\n [ 1, 1, 0, 1, 0, 0, 1, 0, // v0-v1-v2-v3 front\n 0, 1, 0, 0, 1, 0, 1, 1, // v0-v3-v4-v5 right\n 1, 0, 1, 1, 0, 1, 0, 0, // v0-v5-v6-v1 top\n 1, 1, 0, 1, 0, 0, 1, 0, // v1-v6-v7-v2 left\n 0, 0, 1, 0, 1, 1, 0, 1, // v7-v4-v3-v2 bottom\n 0, 0, 1, 0, 1, 1, 0, 1 ] // v4-v7-v6-v5 back\n );\n\n // index array\n var indices = new Uint8Array(\n [ 0, 1, 2, 0, 2, 3, // front\n 4, 5, 6, 4, 6, 7, // right\n 8, 9,10, 8,10,11, // top\n 12,13,14, 12,14,15, // left\n 16,17,18, 16,18,19, // bottom\n 20,21,22, 20,22,23 ] // back\n );\n\n var retval = { };\n\n retval.normalObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.normalObject);\n ctx.bufferData(ctx.ARRAY_BUFFER, normals, ctx.STATIC_DRAW);\n\n retval.texCoordObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.texCoordObject);\n ctx.bufferData(ctx.ARRAY_BUFFER, texCoords, ctx.STATIC_DRAW);\n\n retval.vertexObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.vertexObject);\n ctx.bufferData(ctx.ARRAY_BUFFER, vertices, ctx.STATIC_DRAW);\n\n ctx.bindBuffer(ctx.ARRAY_BUFFER, null);\n\n retval.indexObject = ctx.createBuffer();\n ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, retval.indexObject);\n ctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, indices, ctx.STATIC_DRAW);\n ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, null);\n\n retval.numIndices = indices.length;\n retval.indexType = ctx.UNSIGNED_BYTE;\n return retval;\n}", "function wrapNode(node, template){\n return function() {\n return {\n name: template,\n data: node\n };\n };\n }", "function createSurnameData(data) {\n\tvar className = 'info-box';\n\tvar node = generateInfoBlock({\n\t\tsurname : data.surname\n\t}, className);\n\tmark(node, 'surname-box');\n\tconsole.log('create surname data returns', node);\n\treturn node;\n}", "function createAstNode(type, data){\n\tlet result = data.value;\n\tif(result === undefined){\n\t\tresult = {};\n\t}\n\tresult.type = type;\n\tresult.loc = {\n\t\tstart : data.start,\n\t\tend : data.end,\n\t};\n\treturn result;\n}", "function XML2jsobj(node) {\r\n\r\n var data = {};\r\n\r\n // append a value\r\n function Add(name, value) {\r\n if (data[name]) {\r\n if (data[name].constructor != Array) {\r\n data[name] = [data[name]];\r\n }\r\n data[name][data[name].length] = value;\r\n }\r\n else {\r\n data[name] = value;\r\n }\r\n };\r\n\r\n // element attributes\r\n if (node.nodeType == 1) {\r\n var c, cn;\r\n for (c = 0; cn = node.attributes[c]; c++) {\r\n Add(cn.name, cn.value);\r\n }\r\n }\r\n\r\n // child elements\r\n for (c = 0; cn = node.childNodes[c]; c++) {\r\n if (cn.nodeType == 1) {\r\n if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {\r\n // text value\r\n Add(cn.nodeName, cn.firstChild.nodeValue);\r\n }\r\n else {\r\n // sub-object\r\n if ((cn.nodeValue == null) && (cn.childNodes.length == 0)) {\r\n // its a text node with no children. it becomes an emptystring property of the object.\r\n if (cn.nodeValue == null) {\r\n Add(cn.nodeName, \"\");\r\n } else {\r\n Add(cn.nodeName, XML2jsobj(cn));\r\n }\r\n } else {\r\n Add(cn.nodeName, XML2jsobj(cn));\r\n }\r\n }\r\n }\r\n }\r\n\r\n return data;\r\n\r\n }", "function getBox(rows, cols){\n\t\n\t\treturn document.getElementById('box-'+rows+'-'+cols);\n\t\t\n\t}", "function showNodeData(d) {\n var object ={};\n object.name = d.name.toString(); // transform to string or it will show and array\n object.type = d.type;\n object.solvers = d.solvers;\n object.status = d.status;\n\n var ppTable = prettyPrint(object);\n document.getElementById('d6_1').innerHTML = \"Node\".bold();\n var item = document.getElementById('d6_2');\n\n if(item.childNodes[0]){\n item.replaceChild(ppTable, item.childNodes[0]); //Replace existing table\n }\n else{\n item.appendChild(ppTable);\n }\n\n}", "function copyNodeWithoutNeighbors(node) {\n // commonmark uses classes so it takes a bit of work to copy them\n const copy = new Node();\n\n for (const key in node) {\n if (!node.hasOwnProperty(key)) {\n continue;\n }\n\n copy[key] = node[key];\n }\n\n copy._parent = null;\n copy._firstChild = null;\n copy._lastChild = null;\n copy._prev = null;\n copy._next = null;\n\n // Deep copy list data since it's an object\n copy._listData = {...node._listData};\n\n return copy;\n}", "function createBoxGraph() {\n var graph = new Graph();\n\n for (var y = 0; y < map.length; ++y) {\n for (var x = 0; x < map[y].length; ++x) {\n if (map[y][x] !== WALL) {\n graph.addNode(keyFromCoordinates(x, y), [x, y]);\n }\n }\n }\n\n for (var y = 0; y < map.length; ++y) {\n for (var x = 0; x < map[y].length; ++x) {\n\n if (map[y][x] === WALL) {\n continue;\n }\n\n // Add straight boxes as edges with weight 1\n var straightBoxes = nearBoxes(x, y, COORD_MODE_STRAIGHT,\n FILTER_MODE_NO_WALL);\n for (var i = 0; i < straightBoxes.length; ++i) {\n var otherX = straightBoxes[i][0],\n otherY = straightBoxes[i][1];\n\n graph.addEdge(keyFromCoordinates(x, y),\n keyFromCoordinates(otherX, otherY), 1);\n\n grid.connectBoxes(x, y, otherX, otherY,\n options.connectColor);\n }\n\n var filterMode = FILTER_MODE_NO_WALL |\n FILTER_MODE_DIAGONAL_NOT_NEAR_WALL;\n // Diagonal boxes have 1.4 weight.\n var diagonalBoxes = nearBoxes(x, y, COORD_MODE_DIAGONAL,\n filterMode);\n for (var i = 0; i < diagonalBoxes.length; ++i) {\n var otherX = diagonalBoxes[i][0],\n otherY = diagonalBoxes[i][1];\n\n graph.addEdge(keyFromCoordinates(x, y),\n keyFromCoordinates(otherX, otherY),\n DIAGONAL_WEIGHT);\n grid.connectBoxes(x, y, otherX, otherY, options.connectColor);\n }\n }\n }\n grid.draw();\n return graph;\n }", "function box(sn,numBombs, bomb, clicked, flagged)\n{\n\t\n\tthis.sn=sn;\n\tthis.numBombs=numBombs;\n\tthis.bomb=bomb;\n\tthis.clicked=clicked;\n\tthis.flagged=flagged;\n\t//alert(\"here\");\n}", "function new_Hitbox(hitbox)\n{\n\tif(null == hitbox)\n\t\treturn null;\n\treturn new Hitbox(hitbox.width, hitbox.height);\t\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the total number of counters for the podCounters object
function podCounterTotal($podCounters) { var answer = 0; if ($podCounters) { angular.forEach(["ready", "valid", "waiting", "error"], function (name) { var value = $podCounters[name] || 0; answer += value; }); } return answer; }
[ "function createPodCounters(selector, pods, outputPods, podLinkQuery, podLinkUrl) {\n if (outputPods === void 0) { outputPods = []; }\n if (podLinkQuery === void 0) { podLinkQuery = null; }\n if (podLinkUrl === void 0) { podLinkUrl = null; }\n if (!podLinkUrl) {\n podLinkUrl = \"/kubernetes/pods\";\n }\n var filterFn;\n if (angular.isFunction(selector)) {\n filterFn = selector;\n }\n else {\n filterFn = function (pod) { return selectorMatches(selector, getLabels(pod)); };\n }\n var answer = {\n podsLink: \"\",\n ready: 0,\n valid: 0,\n waiting: 0,\n error: 0\n };\n if (selector) {\n if (!podLinkQuery) {\n podLinkQuery = Kubernetes.labelsToString(selector, \" \");\n }\n answer.podsLink = podLinkUrl + \"?q=\" + encodeURIComponent(podLinkQuery);\n angular.forEach(pods, function (pod) {\n if (filterFn(pod)) {\n outputPods.push(pod);\n var status = getStatus(pod);\n if (status) {\n var lower = status.toLowerCase();\n if (lower.startsWith(\"run\")) {\n if (isReady(pod)) {\n answer.ready += 1;\n }\n else {\n answer.valid += 1;\n }\n }\n else if (lower.startsWith(\"wait\") || lower.startsWith(\"pend\")) {\n answer.waiting += 1;\n }\n else if (lower.startsWith(\"term\") || lower.startsWith(\"error\") || lower.startsWith(\"fail\")) {\n answer.error += 1;\n }\n }\n else {\n answer.error += 1;\n }\n }\n });\n }\n return answer;\n }", "count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }", "function getTotalPatients(){\r\n let total = Object.keys(self.patients).length;\r\n // self.addnewPatient = total;\r\n return total;\r\n }", "function getCountedObjects(){\n var counted = {};\n for (var i = 0; i < detections.length; i++){\n var lbl = detections[i].label;\n if (!counted[lbl]) counted[lbl] = 0;\n counted[lbl]++;\n }\n return counted;\n}", "function refCount(pubs) {\n var total = 0;\n if (pubs) {\n pubs.forEach(function(pub) {\n total += pub.references ? pub.references.length : 0;\n });\n }\n return total;\n}", "function totalAmountAdjectives(obj) {\n\treturn Object.values(obj).length;\n}", "function countNbNotesPerCategory() {\n\tvar nbNotesPerCategory = new Array();\n\n\t// Fills nbNotesPerCategory Array.\n\tfor (var key in catNA) {\n\t\tvar catId = catNA[key];\n\t\tif (nbNotesPerCategory[catId])\n\t\t\tnbNotesPerCategory[catId]++;\n\t\telse\n\t\t\tnbNotesPerCategory[catId] = 1;\n\t}\n\n\t// Loops each category and updates #nb of notes per category.\n\t$('#categories-container').find('span[id^=catcount-]').each(function() {\n\t\tvar catId = $(this).attr('id').replace(/^catcount-/, '');\n\t\t$(this).html('(' + (nbNotesPerCategory[catId] ? nbNotesPerCategory[catId] : 0) + ')');\n\t});\n}", "function getTotalBooksCount (books) {\n return books.length;\n}", "function getCurrentCount(){\n return parseInt(counterTag.innerText)\n }", "countEpiniacReports() {\n return this.r.table('epiniac').count().run();\n }", "function diagnosticCount(state) {\n let lint = state.field(lintState, false)\n return lint ? lint.diagnostics.size : 0\n }", "function getSlotCount(device,slotcnt){\n\tif(device.SLOT != null && device.SLOT != undefined){\n\t\tfor(var t=0; t<device.SLOT.length; t++){\n\t\t\tvar slotpath = device.SLOT[t].ObjectPath.split(\".\");\n\t\t\tvar pathArr = slotpath[slotpath.length -1].split(\"_\");\n\t\t\tslotcnt = pathArr[1];\n\t\t}\n\t}\n\treturn slotcnt;\n}", "function updateCounter() {\n const totalTodosEl = document.querySelector('[data-total-todos]');\n totalTodosEl.innerText = `${todos.length} items left`;\n}", "getTotals (context) {\n db.ref('counts').on('value', snapshot => {\n const counts = snapshot.val()\n if (!counts) {\n return\n }\n\n context.commit('setTotal', counts.total)\n })\n }", "get totalComments() {\n return issues.reduce((total, obj) => total + obj.comments, 0);\n }", "function getFreeContainerCount(container) {\n\t\t\t// Get the prefix\n\t\t\tvar prefix = container.replace(/\\d+$/, '');\n\n\t\t\trackit.options.prefix = prefix;\n\n\t\t\t// Assert that the container exists, and is not to capacity\n\t\t\trackit.hContainers.should.have.property(container);\n\n\t\t\tvar count = rackit.hContainers[container].count;\n\t\t\tcount.should.be.below(50000);\n\t\t\treturn count;\n\t\t}", "function getAliveCount() {\n\tvar count = 0;\n\tcells.map(function(alive) {\n\t\tif (alive) count++;\n\t});\n\treturn count;\n}", "function getObjectLength(object) {\n // YOUR CODE BELOW HERE //\n \n var count = 0 //initialize a variable\n for (var key in object) { //iterate through the given object\n count++; //count each key/value and store the value in count variable\n }\n \n return count //return the number of key/value pairs\n // YOUR CODE ABOVE HERE //\n}", "function totalSize(array)\n{\n let size = 0;\n for(let idx = 0; idx < array.length; ++idx)\n {\n let item = array[idx];\n size += item.byteLength;\n }\n return size;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pokeSubmit submits a poke to the server, which submits it to the Pokees chan. Pokee is the ID of the user that is being poked.
function pokeSubmit(pokee) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url: '/poke', type: 'POST', data: {pokee: pokee}, error: function(data) { console.log("Something caught fire, probably server related!"); } }); }
[ "function instanzMessagePoke()\n\t{\n\t\tvar instanz\t\t\t\t\t\t=\t$(\"input[name='instanzMsgPoke']:checked\").val();\n\t\tvar message \t\t\t\t\t=\t$('#instanzMessagePokeContent').val();\n\t\tvar mode\t\t\t\t\t\t=\t$('#instanzMode').hasClass(\"active\");\n\t\t\n\t\tif(message != '')\n\t\t{\n\t\t\tvar dataString \t\t\t\t= \t'action=instanzMsgPoke&message='+message+'&mode='+mode+'&instanz='+instanz;\n\t\t\t$.ajax({\n\t\t\t\ttype: \"POST\",\n\t\t\t\turl: \"functionsTeamspeakPost.php\",\n\t\t\t\tdata: dataString,\n\t\t\t\tcache: true,\n\t\t\t\tasync: true,\n\t\t\t\tsuccess: function(data)\n\t\t\t\t{\n\t\t\t\t\tif(data == \"done\")\n\t\t\t\t\t{\n\t\t\t\t\t\t$.notify({\n\t\t\t\t\t\t\ttitle: '<strong>'+success+'</strong><br />',\n\t\t\t\t\t\t\tmessage: ts_msg_poke_done,\n\t\t\t\t\t\t\ticon: 'fa fa-check'\n\t\t\t\t\t\t},{\n\t\t\t\t\t\t\ttype: 'success',\n\t\t\t\t\t\t\tallow_dismiss: true,\n\t\t\t\t\t\t\tplacement:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfrom: 'bottom',\n\t\t\t\t\t\t\t\talign: 'right'\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\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$.notify({\n\t\t\t\t\t\t\ttitle: '<strong>'+failed+'</strong><br />',\n\t\t\t\t\t\t\tmessage: data,\n\t\t\t\t\t\t\ticon: 'fa fa-warning'\n\t\t\t\t\t\t},{\n\t\t\t\t\t\t\ttype: 'danger',\n\t\t\t\t\t\t\tallow_dismiss: true,\n\t\t\t\t\t\t\tplacement:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfrom: 'bottom',\n\t\t\t\t\t\t\t\talign: 'right'\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}", "function playerSendPloy(data) {\n\t// console.log('Player ID: ' + data.playerId + ' answered a question with: ' + data.answer);\n\n\t// The player's ploy is attached to the data object. \\\n\t// Emit an event with the ploy so it can be saved by the 'Host'\n\tio.sockets.in(data.gameId).emit('hostSavePloy', data);\n}", "function massactionsChangeMessagePoke()\n\t{\n\t\t// Daten sammeln\n\t\tvar group_id \t\t\t= \t$('#selectMessagePokeGroup').val();\n\t\tvar who\t\t\t\t\t=\t$(\"#selectMessagePokeGroup\").find(':selected').attr('group');\n\t\tvar channel\t\t\t\t=\t$('#selectMessagePokeChannel').val();\n\t\tvar group\t\t\t\t=\t'none';\n\t\tvar res \t\t\t\t= \tgroup_id.split(\"-\");\t// res[3]\n\t\t\n\t\tif(who != 'all')\n\t\t{\n\t\t\tgroup\t\t=\tres[3];\n\t\t};\n\t\t\n\t\t// Daten in Funktion übergeben\n\t\tmassactionsMassInfo(who, group, channel, 'msg');\n\t}", "async publishPost () {\n\t\tif (!this.post.get('teamId')) { return; }\n\t\tawait new PostPublisher({\n\t\t\tdata: this.responseData,\n\t\t\trequest: this,\n\t\t\tbroadcaster: this.api.services.broadcaster,\n\t\t\tteamId: this.post.get('teamId')\n\t\t}).publishPost();\n\t}", "function submitMessage({ name, text }) {\n return request.post(API_URL, { name, text });\n}", "onSubmitName(e, input) {\n e.preventDefault()\n input.disabled = true\n let self = this\n this.props.changeNameHolderClass('name__holder name__holder__deactive')\n\n if (this.props.player.name === ''){\n this.props.changePlayerName('ANONYMOUS');\n }\n\n axios.put('https://mapboxwhereisit.herokuapp.com/game/name/' + this.props.game.id,{\n 'name': this.props.player.name,\n 'host': this.props.player.host\n })\n .then(()=>{\n setTimeout(()=>{\n self.props.changeRequestHostName(false)\n }, 1600)\n })\n }", "submitBeaker()\n {\n\n if(this.beaker.compareBeaker(this.randomBeaker) === true && this.gameInProgress === true)\n {\n\n this.gameIsWon();\n }\n\n\n return;\n }", "function submit() {\n\tif(!is_valid_value()) {\n\t\t// should return some error code\n\t\t$('#error_msg').html('invalid input, try again')\n\t\tsetTimeout(function() {\n\t\t\t$('#error_msg').html('')\n\t\t}, 1000)\n\t\t$('#valueInput').val('').focus()\n return\n }\n\n // Otherwise, let's roll\n store_block_data(\"value submitted\", get_data('username'), url,\n $(\"#valueInput\").val());\n \n store.refresh()\n find_website(url).block_start_time = new Date().getTime();\n store.save()\n\n\tshow_block_stuff();\n\tsubmit_clicked = true;\n}", "function submitBuddy(buddy) {\n $.post(\"/api/buddies\", buddy, function() {\n window.location.href = \"/profile?=\" + buddy.email;\n\n });\n }", "function commitGroc() {\n var groceryId = grocSel;\n grocSel = null;\n var groc = Parse.Object.extend(\"groceryList\");\n var query = new Parse.Query(groc);\n query.equalTo(\"objectId\", groceryId);\n\n query.first({\n success: function(grocObj) {\n\n grocObj.set('user', Parse.User.current());\n grocObj.save(null, {\n success: function(saveSuccess) {\n alert(\"Success: Host has been notified\");\n $(\"#\" + groceryId).hide();\n\n },\n error: function(dinnerEvent, error) {\n alert(error.message);\n }\n });\n\n },\n error: function(error) {\n alert(\"Error: \" + error.code + \" \" + error.message);\n }\n });\n\n}", "function submitAmazonId() {\n var amazonId = $(\"#amazonId\").val().trim();\n if (amazonId.length == 0 || amazonId.indexOf(\"@\") != -1) {\n alert(\"Please enter your amazon ID (not your email).\");\n return;\n }\n\n $(\"#submitFinal\").attr(\"disabled\", \"disabled\");\n var data = {\n \"amazonId\" : amazonId,\n \"user\" : USER_IP,\n \"batch\" : BATCH,\n \"points\" : remainingPoints\n };\n\n $.post(SUBMIT_HIT, data).done(displayKey).fail(function(data) {\n alert(\"Unknown error, please try submitting again.\");\n $(\"#submi\ttFinal\").removeAttr(\"disabled\");\n });\n }", "function chuckJoke() {\n axios.get('https://api.icndb.com/jokes/random').then(res => {\n const joke = res.data.value.joke;\n\n const params = {\n icon_emoji: ':joy_cat:'\n };\n\n bot.postMessageToChannel('random', `Chuck Norris: ${joke}`, params);\n });\n}", "function postCoffee() {\r\n let name = document.getElementById(\"coffeetitle\");\r\n let combo = {};\r\n let text = document.getElementById(\"dynamictext\");\r\n\r\n // Build JSON.\r\n combo[\"name\"] = name.value.substring(0,21);\r\n combo[\"color\"] = coffeeColor;\r\n combo[\"sugar\"] = sugarContent;\r\n combo[\"cream\"] = creamerContent;\r\n\r\n // Conditional for adding a post.\r\n if (name.value !== \"\") {\r\n // Clear name.\r\n name.value = \"\";\r\n let url = \"https://coffeemakerservice.herokuapp.com/\";\r\n // Build the fetchOptions to be used.\r\n let fetchOptions = {\r\n method : 'POST',\r\n headers : {\r\n 'Accept': 'application/json',\r\n 'Content-Type' : 'application/json'\r\n },\r\n body : JSON.stringify(combo)\r\n };\r\n // Attempt to post the message.\r\n fetch(url, fetchOptions)\r\n .then(checkStatus)\r\n .then(function(responseText) {\r\n text.innerHTML = responseText;\r\n \t\t})\r\n \t\t.catch(function(error) {\r\n \t\t\ttext.innerHTML = error;\r\n \t\t});\r\n }\r\n }", "async submitDraft(doc) {\n const action = window.apos.modules[doc.type].action;\n try {\n const submitted = await apos.http.post(`${action}/${doc._id}/submit`, {\n busy: true,\n body: {},\n draft: true\n });\n apos.notify('apostrophe:submittedForReview', {\n type: 'success',\n icon: 'list-status-icon',\n dismiss: true\n });\n apos.bus.$emit('content-changed', {\n doc: submitted,\n action: 'submit'\n });\n return submitted;\n } catch (e) {\n await apos.alert({\n heading: this.$t('apostrophe:errorWhileSubmitting'),\n description: e.message || this.$t('apostrophe:errorWhileSubmittingDescription'),\n localize: false\n });\n return false;\n }\n }", "function eveCrack() {\n\n let keyBob = document.getElementById(\"eveBPriv\").innerHTML.split(\" \");\n let keyAlice = document.getElementById(\"eveAPriv\").innerHTML.split(\" \");\n\n let form = /^[0-9 ]+$/;\n for (let i = 0; i < messageList.names.length; i++) {\n let name = messageList.names[i];\n let message = messageList.messages[i];\n\n // if the input isn't a number, don't bother decrypting\n if (!form.exec(message)) {\n messageList.messages[i] = message;\n continue;\n }\n\n if (name === \"Bob\") {\n if (bobKey) {\n getMessage(message, keyBob[1], keyBob[0], \"Bob\", i);\n } else {\n messageList.messages[i] = message;\n }\n } else if (name === \"Alice\") {\n if (aliceKey) {\n getMessage(message, keyAlice[1], keyAlice[0], \"Alice\", i);\n } else {\n messageList.messages[i] = message;\n }\n } else {\n messageList.messages[i] = message;\n }\n }\n }", "submitFormWith (data) {\n for (let key in data) {\n this.type(data[data], key)\n }\n\n this.wrapper.find('button#submit').trigger('submit')\n }", "voteOnPost(id, vote) {\n const { dispatch } = this.props\n dispatch(votingPost(id, vote))\n alert(\"Thanks for \"+ vote +\" this post!\")\n}", "function submit() {\n var order = Order.get(request.httpParameterMap.order_id.stringValue);\n var orderPlacementStatus;\n if (order.object && request.httpParameterMap.order_token.stringValue === order.getOrderToken()) {\n orderPlacementStatus = Order.submit(order.object);\n if (!orderPlacementStatus.error) {\n clearForms();\n return app.getController('COSummary').ShowConfirmation(order.object);\n }\n }\n app.getController('COSummary').Start();\n}", "function sendTrickleCandidate(handleId, candidate) {\n\t\tif(!connected) {\n\t\t\tJanus.warn(\"Is the server down? (connected=false)\");\n\t\t\treturn;\n\t\t}\n\t\tvar pluginHandle = pluginHandles[handleId];\n\t\tif(!pluginHandle || !pluginHandle.webrtcStuff) {\n\t\t\tJanus.warn(\"Invalid handle\");\n\t\t\treturn;\n\t\t}\n\t\tvar request = { \"janus\": \"trickle\", \"candidate\": candidate, \"transaction\": Janus.randomString(12) };\n\t\tif(pluginHandle.token)\n\t\t\trequest[\"token\"] = pluginHandle.token;\n\t\tif(apisecret)\n\t\t\trequest[\"apisecret\"] = apisecret;\n\t\tJanus.vdebug(\"Sending trickle candidate (handle=\" + handleId + \"):\");\n\t\tJanus.vdebug(request);\n\t\tif(websockets) {\n\t\t\trequest[\"session_id\"] = sessionId;\n\t\t\trequest[\"handle_id\"] = handleId;\n\t\t\tws.send(JSON.stringify(request));\n\t\t\treturn;\n\t\t}\n\t\tJanus.httpAPICall(server + \"/\" + sessionId + \"/\" + handleId, {\n\t\t\tverb: 'POST',\n\t\t\twithCredentials: withCredentials,\n\t\t\tbody: request,\n\t\t\tsuccess: function(json) {\n\t\t\t\tJanus.vdebug(\"Candidate sent!\");\n\t\t\t\tJanus.vdebug(json);\n\t\t\t\tif(json[\"janus\"] !== \"ack\") {\n\t\t\t\t\tJanus.error(\"Ooops: \" + json[\"error\"].code + \" \" + json[\"error\"].reason);\t// FIXME\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(textStatus, errorThrown) {\n\t\t\t\tJanus.error(textStatus + \":\", errorThrown);\t// FIXME\n\t\t\t}\n\t\t});\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculating whether the placeholder should be hidden
placeholderHidden() { return !!(this.labels.length > 0 || this.value); }
[ "function IsHidden(){\n\treturn !_showGizmo;\n}//IsHidden", "handlePlaceholderVisibility() {\n if (!this.multiple)\n return;\n const e = this.choicesInstance.containerInner.element.querySelector(\n \"input.choices__input\"\n );\n this.placeholderText = e.placeholder ? e.placeholder : this.placeholderText;\n const t = this.choicesInstance.getValue().length;\n e.placeholder = t ? \"\" : this.placeholderText ? this.placeholderText : \"\", e.style.minWidth = \"0\", e.style.width = t ? \"1px\" : \"auto\", e.style.paddingTop = t ? \"0px\" : \"1px\", e.style.paddingBottom = t ? \"0px\" : \"1px\";\n }", "function isHidden ( elem ) {\n // @see http://stackoverflow.com/questions/19669786\n return window.getComputedStyle(elem).display === 'none';\n }", "shouldHide(show_condition) {\n return ClassNames({\n 'should-hide': show_condition ? false : true\n })\n }", "function checaVisibilidadePlano(){\n\n if($(\"#planoEstagio\").is(':visible')) {// checa se atributo esta visivel\n // faca nada\n }else{\n $( \"form > div > div\" ).hide();\n $(\"#planoEstagio\").show();\n }\n\n}", "visibleCheck(on) {\n this.clearInterval('visible');\n if (on) {\n this.setInterval('visible', () => {\n const tip = this.$tip;\n if (tip && !isVisible(this.$element) && hasClass(tip, ClassName.SHOW)) {\n // Element is no longer visible, so force-hide the tooltip\n this.forceHide();\n }\n }, 100);\n }\n }", "function handlePlaceholder() {\n\tvar inputfield = document.getElementById(\"equation-container\");\n\tvar placeholder = inputfield.getAttribute(\"placeholder\");\n\tif(placeholder != 0) {\n\t\t//Change equation to placeholder\n\t\tequation = placeholder.toString();\n\t\tif(equation.includes(\".\")) {\n\t\t\tdotExists = true;\n\t\t}\n\t\tupdate(equation);\n\t\t//Change placeholder to 0\n\t\tinputfield.setAttribute(\"placeholder\", 0);\n\t}\n}", "get placeholderCellRendered() {\n return this._placeholderCellRendered;\n }", "isVisible() {\n return this.toolbar.is(\":visible\");\n }", "function testNormalElementsAreHidden(item) {\n testElementsVisibility(item, normalElements, false);\n }", "_showBox () {\n\t\tif (Renderer.dice._$wrpRoll.css(\"display\") !== \"flex\") {\n\t\t\tRenderer.dice._$minRoll.hide();\n\t\t\tRenderer.dice._$wrpRoll.css(\"display\", \"flex\");\n\t\t\tRenderer.dice._$iptRoll.prop(\"placeholder\", `${Renderer.dice._getRandomPlaceholder()} or \"/help\"`);\n\t\t}\n\t}", "visible(bool: Boolean) {\n if (bool === undefined)\n // Is probably visible if any other value than 'hidden'\n return this.target.style.visibility === \"hidden\" ? false: true;\n this.target.style.visibility = bool ? \"visible\" : \"hidden\";\n }", "get heightChanged() {\n return (this.flags & 2) /* Height */ > 0\n }", "function isVisible(e) {\n\tif (e == null) return false;\n\tif (e == undefined) return false;\n\treturn !!(e.offsetWidth || e.offsetHeight || e.getClientRects().length);\n}", "isCurrentlyDisplayed() {\n //Get current zoom level\n let zoomLevel = this.map.getView().getZoom();\n //Check visibility\n return this.isVisibleAtZoomLevel(zoomLevel);\n }", "checkVisibility () {\n const vTop = window.pageYOffset\n const vHeight = window.innerHeight\n if (vTop + vHeight < this.box.top ||\n this.box.top + this.canvasHeight < vTop) {\n // viewport doesn't include canvas\n this.visible = false\n } else {\n // viewport includes canvas\n this.visible = true\n }\n }", "function isVisible(obj)\n\t{\n\t\treturn (obj.css('display') != 'none') && (obj.css('visibility') != 'hidden');\n\t}", "ensureButtonsHidden() {\n // TODO(fanlan1210)\n }", "isVisible (template) {\n if (template) {\n return QuickPopoverController.popover && QuickPopoverController.contentTemplate === template\n } else {\n return QuickPopoverController.popover !== undefined\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
On load 1) current movie details are posted to backend and saved inn database to store history 2) Load the video callback, when video ends, return to homepage 3) Add event listener for handling keyboard navigation
componentDidMount() { let { postHistoryActions, movie } = this.props; if (movie === null || movie === undefined || !movie.contents[0].url) { return null; } let historyData = { username: username, title: movie.title, description: movie.description, videoUrl: movie.contents[0].url, imageUrl: movie.images[0].url }; postHistoryActions(historyData); /* Handle keyboard navigation. If the header menu isn't focused, the left/right keys rewinds/skips 10s of video, and Enter/Space key toggles between playing and pausing the video */ document.onkeydown = e => { const toHandleKeydown = ArrowNavigation(e); if (toHandleKeydown) { let video = videojs("video"); switch (e.key) { case " ": case "Enter": video.paused() ? video.play() : video.pause(); break; case "ArrowRight": video.currentTime(video.currentTime() + 10); break; case "ArrowLeft": video.currentTime(video.currentTime() - 10); break; case "f": video.requestFullscreen(); break; default: break; } } }; //Back to homepage when video finished if (document.getElementById("video")) { let video = videojs("video"); video.play(); video.on("ended", function() { window.location.href = "/"; }); } }
[ "function search_for_video() {\n\n\t// console.log(\"search clicked\\n\");\n\n\tvar new_link = search_bar_input.value;\n\tif (new_link.length !== 0) {\n\n\t\tvar data_sections = new_link.split(\"&\");\n\t\t// console.log(data_sections);\n\n\t\tvar time = \"\";\n\t\tvar playlist = \"\";\n\t\tvar playlist_index = \"\";\n\n\t\tfor (var i = 0; i < data_sections.length; i++) {\n\n\t\t\tif (data_sections[i].includes(\"v=\")) {\n\n\t\t\t\tnew_link = data_sections[i].split(\"v=\").pop();\n\n\t\t\t} else if (data_sections[i].includes(\"t=\")\n\t\t\t\t&& !data_sections[i].includes(\"list=\")) {\n\n\t\t\t\ttime = data_sections[i].split(\"t=\").pop();\n\n\t\t\t} else if (data_sections[i].includes(\"list=\")) {\n\n\t\t\t\tplaylist = data_sections[i].split(\"list=\").pop();\n\n\t\t\t} else if (data_sections[i].includes(\"index=\")) {\n\n\t\t\t\tplaylist_index = data_sections[i].split(\"index=\").pop();\n\n\t\t\t}\n\n\t\t}\n\n\t\tyt_player.loadVideoById({videoId:new_link});\n\n\t\twhile(note_logs.firstChild) {\n\t\t\tnote_logs.removeChild(note_logs.firstChild);\n\t\t}\n\n\t\t// console.log(\"new video\\n\");\n\t\tsearch_bar_input.value = \"\";\n\t\twrite_note_textarea.value = \"\";\n\n\t\tpopulateNotes(new_link);\n\t\tsetSessionVideoId(new_link);\n\n\t}\n\n}", "function videoClick(clickedVideo){\n console.log('video es'+clickedVideo);\n sessionStorage.setItem('videoid', clickedVideo);\n}", "async function updateData() {\n urlForVideo = document.location.href;\n \n if (urlForVideo != lastURL) {\n lastURL = urlForVideo;\n startTimeStamp = Math.floor(Date.now() / 1000);\n }\n \n //* If page has all required propertys\n if($('.roomName.on').get(0) != undefined) {\n\n videoTitle = $('.roomName.on')[0].innerHTML\n videoAuthor = $('.sessionsCount')[0].innerHTML.match(\"[0-9]*\")[0] + \" \" + await getString(\"presence.watching\")\n playbackBoolean = true\n\n var data = {\n clientID: '516742299355578380',\n presenceData: {\n details: $('<div/>').html(videoTitle).text(),\n state: $('<div/>').html(videoAuthor).text(),\n largeImageKey: 'rt_lg',\n largeImageText: chrome.runtime.getManifest().name + ' V' + chrome.runtime.getManifest().version,\n startTimestamp: startTimeStamp\n },\n trayTitle: $('<div/>').html(videoTitle).text(),\n playback: playbackBoolean,\n service: 'Rabb.it'\n }\n\n } else if(document.location.pathname == \"/\") {\n data = {\n clientID: '516742299355578380',\n presenceData: {\n details: await getString(\"presence.browsing\"),\n largeImageKey: 'rt_lg',\n largeImageText: chrome.runtime.getManifest().name + ' V' + chrome.runtime.getManifest().version,\n startTimestamp: startTimeStamp\n },\n trayTitle: \"\",\n service: 'Rabbit',\n playback: true\n }\n }\n chrome.runtime.sendMessage({presence: data})\n}", "function addVideo(e) {\n const id = (e.target.id !== 'addVideo')\n ? e.target.value\n : domCache['videoId'].value;\n const found = state.videos.filter(video => id === video.id);\n\n if (e && e.target.id === 'addVideo' && found.length > 0) {\n log('add video', `not added; id ${id} already in list`);\n return;\n }\n\n const func = (!state.player)\n ? setPlayer\n : loadVideo;\n\n func(id).then((loaded) => {\n // video is loaded, will be updated in loaded event.\n }).catch(function(error) {\n // the video did not load.\n log(`${func.name} called`, `video id ${id} not loaded.`);\n });\n }", "function registerVideoEvent(videoEvent) {\n var isNewVideoEvent = checkIfNewVideoEvent(videoEvent);\n if (isNewVideoEvent) {\n _mostRecentVideoEventTime = videoEvent.timestamp;\n videoSeekTo(videoEvent.video_time_at);\n if (videoEvent.event_type === 'play') {\n playVideo();\n _mostRecentVideoEventType = 'play';\n } else if (videoEvent.event_type === 'pause') {\n pauseVideo();\n _mostRecentVideoEventType = 'pause';\n }\n }\n\n\n}", "function onTimeupdate(){\n //if the video has finished\n if ( this.currentTime >= this.duration ){\n //if we are offering e-mail sharing\n if (configHandler.get('showLocalShare')){\n var vidElem = document.getElementById('videoReview');\n //if we have not shown the e-mail option yet\n if (haveShownShare === false ){\n //remember that we have shown it\n haveShownShare = true;\n //transition in the other UI elements\n var container = document.getElementById('videoReviewContainer');\n container.classList.add('share');\n var btn = document.getElementById('breakButton');\n btn.classList.remove('enabled');\n btn.classList.add('disabled');\n vidElem.muted = true;\n //play the audio after the e-mail option\n // has transitioned in\n if (soundPlayer.exists()){\n soundTimeout = setTimeout(function(){\n soundPlayer.play();\n }, 1000);\n }\n }\n //replay the video\n vidElem.currentTime = 0;\n vidElem.play();\n } else {\n //if we are not offering e-mail sharing\n // just transition to the thank you screen\n window.events.dispatchEvent(new Event('special'));\n }\n }\n }", "function pushVideosToWatchedList(title_content, image_url, video_url) {\n recently_watched_videos.push({ title: title_content, image: image_url, video: video_url });\n localStorage.setItem('watchedVideosArray', JSON.stringify(recently_watched_videos));\n}", "function loadVideo() {\n\t\tvar d = new Date();\n\t\tvar lastYear = d.getFullYear() - 1;\n\t\tvar month = d.getMonth() +1;\n\t\tvar day = d.getDate();\n\t\tvar myKey = \"AIzaSyAr0fnc8B-t96isVPUByudWNPFDKJIugoc\";\n\t\tvar request = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&order=viewCount&publishedAfter='+lastYear+'-'+month+'-'+day+'T00%3A00%3A00Z&q=teaser|trailer -india|game&type=video&videoCaption=any&relevanceLanguage=en&videoCategoryId=24&videoEmbeddable=true&key=' + myKey;\n\t\t$.ajax({\n\t\t\turl: request,\n\t\t\tsuccess: function (data) {\n\t\t\t\tvar id = data.items[0].id.videoId;\n\n\t\t\t\tdata.items.forEach(buildArray);\n\n\t\t\t\tplayVideo();\n\n\t\t\t}\n\t\t});\n\t}", "function setMoviesPage() {\n\n // display movie genres list\n listMovieGenres();\n\n // display movie year list with forwarded range data\n listMovieYears(2000, 2021)\n\n // display popular movies at page startup\n displayPopularMovies();\n}", "savingChange (movie) {\n this.props.dispatch({ type: 'EDIT_MOVIE', payload: movie });\n this.props.dispatch({type: 'SET_MOOVIE', payload: movie});\n this.props.history.push(`/details/${this.state.id}`);\n\n\n }", "function runContentScript() {\n const videotags = document.getElementsByTagName(\"video\");\n player = videotags[0]\n\n if (!player) {\n setTimeout(runContentScript, 500);\n return;\n }\n\n for (action in Actions) {\n player.addEventListener(Actions[action], handleLocalAction(Actions[action]));\n }\n\n chrome.runtime.onMessage.addListener(handleBackgroundMessage);\n /* Send message to runtime.onMessage listener in backend.js to connect to room. */\n chrome.runtime.sendMessage({ type: WebpageMessageTypes.CONNECTION });\n}", "function load_video( href ) {\n\t\t\tvar data = {};\n\t\t\t/*var video = '<video width=\"' + data.width + '\" height=\"' + data.height + '\" controls=\"controls\" preload=\"autoplay\" poster=\"' + data.poster + '\">\n\t\t\t\t<source type=\"video/mp4\" src=\"' + href + '\" />\n\t\t\t\t<object width=\"928\" height=\"523\" type=\"application/x-shockwave-flash\" data=\"/wm/release-gq/js/libs/mediaelement/flashmediaelement.swf\">\n\t\t\t\t\t<param name=\"movie\" value=\"/wm/release-gq/js/libs/mediaelement/flashmediaelement.swf\" />\n\t\t\t\t\t<param name=\"flashvars\" value=\"controls=true&poster=/wm/release-gq/sites/gerling-quartier/media/pages/quarter_video/Gerling_Quartier_Hauptfilm_IF_928x522_poster.jpg&file=media/pages/quarter_video/Gerling_Quartier_Hauptfilm_IF_928x522.mp4\" />\n\t\t\t\t\t<img src=\"/wm/release-gq/sites/gerling-quartier/media/pages/quarter_video/Gerling_Quartier_Hauptfilm_IF_928x522_poster.jpg\" width=\"\" height=\"\" title=\"\">\n\t\t\t\t</object>\n\t\t\t</video>'*/\n\t\t}", "function initYouTubeList(){\r\n var tabUrl = window.location.href;\r\n var youTubeListId = getURLParameter(tabUrl, 'list');\r\n if (youTubeListId && youTubeListId != playlistId){\r\n playlistId = youTubeListId;\r\n extractVideosFromYouTubePlaylist(youTubeListId);\r\n }\r\n}", "function populateMyMoviesPage() {\n\tgetjson('https://user-enter-luke.firebaseio.com/users.json')\n\tp.then(function(data) {\n\t\tmoviesAdded = [];\n\t\tmoviesViewed = [];\n\t\tif (data !== null) {\n\t\tfor (var i = 0; i < data[userID].movies.length; i++) {\n\t\t\t\tmoviesAdded.push(data[userID].movies[i]);\n\t\t\t}\n\t\tfor (var i = 0; i < data[userID].watchedMovies.length; i++) {\n\t\t\t\tmoviesViewed.push(data[userID].watchedMovies[i]);\n\t\t\t}\n\t\t}\n\t$(document).click(function(e) {\n\t\tif (e.target.className === \"add btn btn-primary\") {\n\t\t\taddMovie(e);\n\t\t}\n\t});\n\t$(document).click(function(e) {\n\t\tif (e.target.className === \"remove btn btn-danger\") {\n\t\t\tremoveMovie(e);\n\t\t}\n\t});\n\n\t});\n}", "function openVideo() {\r\n\t\tTitanium.Platform.openURL(movie.trailerUrl);\r\n\t}", "function checkWatchedVideos(title_content, image_url, video_url) {\n recently_watched_videos = JSON.parse(localStorage.getItem('watchedVideosArray'));\n\n if (recently_watched_videos.length == 0) {\n // ADD FIRST VIDEO TO JSON\n pushVideosToWatchedList(title_content, image_url, video_url);\n } else {\n // ADD MORE VIDEO TO JSON\n var isExistInWatched = false;\n var watchedVideoIndex = 0;\n $.each(recently_watched_videos, function(ind, obj_val) {\n watchedVideoIndex = ind + 1;\n if (obj_val.title === title_content && obj_val.image === image_url && obj_val.video === video_url) {\n isExistInWatched = true;\n console.log(\"Index number = \" + ind);\n recently_watched_videos.splice(ind, 1);\n }\n if (recently_watched_videos.length === watchedVideoIndex) {\n pushVideosToWatchedList(title_content, image_url, video_url);\n }\n });\n }\n}", "function ChangeMenuVideo_listener(e) {\n // The DOM query selector does not create arrays, but nodeLists. They can be iterated with forEach but there\n // are many array functions they do not have. Some of them can be solved by transforming to an Array like in the following method.\n var index = Array.prototype.indexOf.call(menu_page_links, e.target);\n mouseover_bool = e.type === \"mouseover\" ? true : false;\n ChangeMenuVideo(index, mouseover_bool);\n}", "function getVideo() {\n firstPlay = false;\n var fileURLContent = document.getElementById(\"videoURLs\").value; // get select field\n if (fileURLContent != \"\") {\n var newFileURLContent = fileURLContent;\n video.src = newFileURLContent;\n document.getElementById(\"contentURL\").innerHTML = \"URL: \" + newFileURLContent;\n //get the selected index of the URL List\n var selectedURL = document.getElementById(\"videoURLs\");\n var optionIndex = selectedURL.selectedIndex;\n //set the index to the selected field\n document.getElementById(\"videoURLs\").selectedIndex = optionIndex;\n console.log(\"Loading:\" + newFileURLContent);\n video.load(); // if HTML source element is used\n console.log(\"Playing:\" + newFileURLContent);\n video.play();\n document.getElementById(\"playOrPauseIcon\").src = \"../icons/pause.png\";\n } else {\n errMessage(\"Enter a valid video URL\"); // fail silently\n }\n }", "displayMovieFromLS() {\n const movies = this.getMovieFromLS()\n movies.forEach(movie => {\n this.addMovieToUI(movie)\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the todo cards and populates them with the data from the API
function createCards(json) { // Get the container element for the todo cards const todoContainer = document.getElementById("todoContainer"); // Dynamically create one card for each todo object in the json data json.forEach(todo => { // Create the 'assigned to' card header var userId = document.createElement("span"); userId.innerText = "ASSIGNED TO: " + nameFromUserId(todo.userId); userId.className = "userId"; // Create the card title var title = document.createElement("h4"); title.innerText = todo.title; // Create task completion element var status = document.createElement("span"); // Create the card itself var card = document.createElement("div"); card.classList.add("card"); // Sets card class and text based on task completion if (todo.completed) { card.classList.add("complete"); status.innerText = "COMPLETED"; } else { card.classList.add("incomplete"); status.innerText = "NOT COMPLETED"; } // Append the elements to eachother and the card to its container card.appendChild(userId); card.appendChild(title); card.appendChild(status); todoContainer.appendChild(card); }); }
[ "function getToys() {\n fetch('http://localhost:3000/toys')\n .then(resp => resp.json())\n .then(toys => toys.forEach(toy => createToyCard(toy)))\n}", "function initCards() {\n let cards = [];\n //TODO: FIX\n for (let i = 0; i < count; i++) {\n cards.push(JSON.parse(localStorage.getItem(`cards-${i}`)));\n }\n console.log(cards);\n\n for (let card of cards) {\n if (card == null) {\n continue;\n }\n createCard(\n card.selectOptionType,\n card.inputCardNumber,\n card.formatedDate,\n card.id,\n true\n );\n }\n}", "async function _getCardsAPI() {\r\n try {\r\n const data = await fetch(\"https://api.pokemontcg.io/v1/cards\");\r\n if (!data) throw new Error();\r\n const cards = await data.json();\r\n const cardsData = await [...Object.values(cards)][0];\r\n const names = await cardsData.map((card) => card.name).sort();\r\n\r\n names.forEach(function (name) {\r\n const html = `<button type= \"button\" class=\"cardButton\" id=\"${name.toLowerCase()}\">${name}</button>`;\r\n listContainer.insertAdjacentHTML(\"beforeend\", html);\r\n\r\n // Save cards data into the local storage. This avoid having to make an AJAX call for each card button click. Saving it into a local storage is not really a good practice as the file is not safe. I do not know how to use Redux...yet!\r\n const save = JSON.stringify(cardsData);\r\n localStorage.setItem(\"cardsData\", save);\r\n\r\n return cardsData;\r\n });\r\n } catch (err) {\r\n _errorMsg(listContainer);\r\n listContainer.style.display = \"none\";\r\n cardInfo.style.display = \"none\";\r\n back.addEventListener(\"click\", _errorMsg(cardPage));\r\n console.log(err);\r\n }\r\n}", "function renderTaskCards() {\r\n // Clear task cards before rendering\r\n toDoDiv.innerHTML = `<h2>To do</h2>`;\r\n inProgressDiv.innerHTML = `<h2>In Progress</h2>`;\r\n finishedDiv.innerHTML = `<h2>Finished</h2>`;\r\n\r\n // Get tasks\r\n const taskArray = getLocalStorage(\"task\");\r\n\r\n // Create task card\r\n // Fill task card with info from task obj\r\n let number = 0;\r\n taskArray.forEach(task => {\r\n number++;\r\n let taskHtml = `\r\n \r\n <div class=\"taskCard\" id=\"taskDiv-${number}\" draggable=\"true\" ondragstart=\"drag(event)\">\r\n <div id=\"taskTitle\">${task.name}</div>\r\n <div id=\"taskDescription\">${task.description}</div>\r\n <div id=\"taskCardClickTarget\" onclick=\"clickTaskCard(event)\">\r\n </div></div>`;\r\n if (task.phase === \"todo\") {\r\n toDoDiv.innerHTML += taskHtml;\r\n } else if (task.phase === \"inProgress\") {\r\n inProgressDiv.innerHTML += taskHtml;\r\n } else {\r\n finishedDiv.innerHTML += taskHtml;\r\n }\r\n \r\n // Update progress bar\r\n checkProgress();\r\n });\r\n\r\n\r\n\r\n\r\n}", "function createTodo() {\n // get the string value of input todo\n var newTodo = $('#newTodo').val();\n\n pushToTodos(newTodo);\n\n displayTodoItems(todos);\n\n storeTodos();\n\n // empty the input feild\n $('#newTodo').val('');\n }", "function makeCards() {\n //clear previous search results\n cardWrapperDiv.innerHTML = ``;\n for (let i = 0; i < recipeList.length; i++) {\n let newCard = document.createElement(`div`);\n newCard.classList.add(`card`);\n newCard.setAttribute(`data-id`, [i]);\n newCard.setAttribute(`style`, `background-image: url(${recipeList[i].image}); background-position: center;`);\n\n newCard.innerHTML = `\n <div >\n <span class=\"card-title\">${recipeList[i].label}</span>\n </div> \n `;\n cardWrapperDiv.append(newCard);\n\n }\n\n }", "function addCardAppData(e) {\n\n// const listId =e.target.closest('.oneLists').getAttribute('data-id');\n\n // const listInAppData2 = appData.lists.board.find((list)=> listId === list.id);\n\n //\n // const cardOfAppData = {\n // members: [],\n // text: 'Add new task',\n // id: newCard.getAttribute(\"data-id\"),\n // }\n // listInAppData2.tasks.push(cardOfAppData);\n\n const title = e.target.closest('.oneLists').querySelector('.tagText').textContent\n const id =e.target.closest('.oneLists').getAttribute('data-id');\n\n const listInAppData =returnListReference(id)\n // appData.lists.board.find((bord) => id === bord.id)\n const cardId= e.target.closest('.oneLists').querySelector('.ulForCards li:last-child');\n\n const cardOfAppData = {\n members: [],\n text: 'Add new task',\n id: cardId.getAttribute('data-id'),\n }\n listInAppData.tasks.push(cardOfAppData)\n //pushnigNewCard(listInAppData, cardId);\n\n}", "function populateCoffeeArea(){\n cardArea.innerHTML = '';\n for(let x = 0; x<coffees.length;x++){\n cardArea.innerHTML += '<div class=\"card float-left mx-3 mb-2 border-dark-shade\" style=\"width: 40%;\">\\n' +\n ' <div class=\"card-body bg-soft-white \">\\n' +\n ' <h4 class=\"card-title text-center spookyText\">' + coffees[x].name + '</h4>\\n' +\n ' <h6 class=\"card-subtitle mb-2 text-muted text-center\">' + coffees[x].roast + '</h6>\\n' +\n ' <p class=\"card-text text-center\">'+ coffees[x].description +'</p>\\n' +\n ' <button type=\"button\" class=\"btn btn-outline-primary mx-auto w-100\">Buy Now!</button>\\n' +\n ' </div>\\n' +\n ' </div>'\n }\n}", "async function getAllToys() {\n let response = await fetch(toyBoxUrl);\n let data = await response.json();\n\n for (toy of data) {\n allToys.appendChild(createToyCard(toy));\n console.log(toy);\n }\n }", "generateIndexPage(obj, container, types, gradedLevels, statuses, arr) {\n\n /* function for generating edit form inside modal. Calls generateEditForm method defined in class */\n let generateEditForm = () => { return this.generateEditForm(obj, 'main', types, gradedLevels, statuses, arr);}\n\n /* function for toggleing modal, and appending it to div.edit-modal. Calls toggleModal method defined in class */\n let toggleModal = () => { return this.toggleModal('div.edit-modal') }\n\n /* functtion for creating an object in localstorage as a temporary storage soloution. Used to edit information about cards */\n let tempStorage = () => {return this.createTempStorage(obj.getId(), obj.getStatus(), obj.getTitle(), obj.getDesc(), obj.getType(), obj.getImgUrl(), obj.getAlt(), obj.getGradedLevel(), obj.getDate(), obj.getAddress())};\n\n /* function for deleting card object from the object array. Calls deleteCard method defined in class */\n let deleteCard = () => { return this.deleteCard(obj, arr); }\n\n /* function for updating counter for amount of tasks with a certain status. Calls updateCount method defined in class */\n let updateCount = () => { return this.updateCount(arr); }\n \n /* function for formatting status of card */\n let formatStatus = () => {\n /* conditional check if card has status 'Ikke løst' */\n if (obj.getStatus() == 'Ikke løst') {\n\n /* if it have, return css class x-negative */\n return 'case-card-content-status-negative';\n } else {\n\n /* else, return css class x-postivie */\n return 'case-card-content-status-positive'\n }\n }\n \n /* card structure, formatted for readability */\n let generateCard = `<article class=\"case-card-${obj.getId()} case-card\">\n <div>\n <!-- preserves UD by adding alt text -->\n <img class=\"case-card-img\" src=\"${obj.getImgUrl()}\" alt=\"${obj.getAlt()}\">\n </div> \n <div class=\"case-card-content\">\n <div class=\"flex justify-between items-center\">\n <!-- preserved UD by having strong grey color on a white background -->\n <p class=\"case-card-content-type\"> ${obj.getType()} • Sak ${obj.getId()}</p>\n <div>\n <!-- preserves UD by having a strong red color on a light red colored background -->\n <span class=\"${formatStatus()} flex items-center\">${obj.getStatus()}</span>\n </div>\n </div>\n <h2 class=\"case-card-content-title\">${obj.getTitle()}</h2>\n </div>\n <div class=\"case-card-meta\">\n <div class=\"flex items-center case-card-meta-content\">\n <!-- preserves UD by having a strong gray color against a white background -->\n <svg class=\"case-card-meta-icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\n <path d=\"M13 20v-5h-2v5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7.59l-.3.3a1 1 0 1 1-1.4-1.42l9-9a1 1 0 0 1 1.4 0l9 9a1 1 0 0 1-1.4 1.42l-.3-.3V20a2 2 0 0 1-2 2h-3a2 2 0 0 1-2-2zm5 0v-9.59l-6-6-6 6V20h3v-5c0-1.1.9-2 2-2h2a2 2 0 0 1 2 2v5h3z\"/>\n </svg>\n <span>${obj.getFormattedAddress()}</span>\n </div>\n <div class=\"flex items-center case-card-meta-content\">\n <!-- preserves UD by having a strong gray color against a white background -->\n <svg class=\"case-card-meta-icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\n <path d=\"M13 16v5a1 1 0 0 1-1 1H9l-3-6a2 2 0 0 1-2-2 2 2 0 0 1-2-2v-2c0-1.1.9-2 2-2 0-1.1.9-2 2-2h7.59l4-4H20a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-2.41l-4-4H13zm0-2h1.41l4 4H20V4h-1.59l-4 4H13v6zm-2 0V8H6v2H4v2h2v2h5zm0 2H8.24l2 4H11v-4z\"/>\n </svg>\n <span>Gradert ${obj.getGradedLevel()}</span>\n </div>\n <div class=\"flex items-center case-card-meta-content\">\n <!-- preserves UD by having a strong gray color against a white background -->\n <svg class=\"case-card-meta-icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\n <path d=\"M12 22a10 10 0 1 1 0-20 10 10 0 0 1 0 20zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm1-8.41l2.54 2.53a1 1 0 0 1-1.42 1.42L11.3 12.7A1 1 0 0 1 11 12V8a1 1 0 0 1 2 0v3.59z\"/>\n </svg>\n <span>Opprettet ${obj.getDate()}</span>\n </div>\n </div>\n <div class=\"case-card-action flex items-center justify-between\">\n <div class=\"case-card-action-btn-container w-1\">\n <!-- preserves UD by having a white text color against a dark gray background -->\n <a href=\"edit.html\" class=\"card-${obj.getId()} case-card-action-btn\">Se detaljer</a>\n </div>\n <div class=\"flex justify-end items-center case-card-action-icn-container\">\n <!-- preserves UD by having a white text color against a dark gray background -->\n <button type=\"button\" class=\"delete-card-${obj.getId()} flex items-center mr-2\">\n <svg class=\"icn actions-bar\" viewBox=\"0 0 20 20\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n <circle id=\"Oval\" fill=\"#000000\" cx=\"10\" cy=\"10\" r=\"10\"></circle>\n <path d=\"M5.6,5.8 L14,5.8 L13.466,14.872 C13.4278642,15.5064687 12.9016127,16.0011451 12.266,16.000002 L7.34,16.000002 C6.7043873,16.0011451 6.17813579,15.5064687 6.14,14.872 L5.6,5.8 Z M8.6,8.8 C8.26862915,8.8 8,9.06862915 8,9.4 L8,13 C8,13.3313708 8.26862915,13.6 8.6,13.6 C8.93137085,13.6 9.2,13.3313708 9.2,13 L9.2,9.4 C9.2,9.06862915 8.93137085,8.8 8.6,8.8 Z M11,8.8 C10.6686292,8.8 10.4,9.06862915 10.4,9.4 L10.4,13 C10.4,13.3313708 10.6686292,13.6 11,13.6 C11.3313708,13.6 11.6,13.3313708 11.6,13 L11.6,9.4 C11.6,9.06862915 11.3313708,8.8 11,8.8 Z\" id=\"Shape\" fill=\"#FFFFFF\"></path>\n <path d=\"M7.754,5.2 L8.774,4.18 C8.88624286,4.06548661 9.03965246,4.00066565 9.2,4 L10.4,4 C10.5582616,4.00225423 10.7092217,4.06695144 10.82,4.18 L11.852,5.2 L14,5.2 C14.3313708,5.2 14.6,5.46862915 14.6,5.8 C14.6,6.13137085 14.3313708,6.4 14,6.4 L5.6,6.4 C5.26862915,6.4 5,6.13137085 5,5.8 C5,5.46862915 5.26862915,5.2 5.6,5.2 L7.754,5.2 Z\" id=\"Path\" fill=\"#FFFFFF\"></path>\n </svg>\n </button>\n <!-- preserves UD by having a white text color against a dark gray background -->\n <button type=\"button\" class=\"card-${obj.getId()} edit-card-${obj.getId()} flex items-center\">\n <svg class=\"icn actions-bar\" viewBox=\"0 0 20 20\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n <circle id=\"Oval\" fill=\"#000000\" cx=\"10\" cy=\"10\" r=\"10\"></circle>\n <path d=\"M6,10.9929286 C6.00187852,10.8610439 6.05579287,10.7352438 6.15,10.6429286 L11.65,5.14292858 C11.8444218,4.95235714 12.1555782,4.95235714 12.35,5.14292858 L13.85,6.64292858 C14.0405714,6.83735033 14.0405714,7.14850682 13.85,7.34292858 L8.35,12.8429286 C8.25768477,12.9371357 8.13188463,12.9910501 8,12.9929286 L6.5,12.9929286 C6.22385763,12.9929286 6,12.769071 6,12.4929286 L6,10.9929286 L6,10.9929286 Z\" id=\"Path\" fill=\"#FFFFFF\"></path>\n <rect id=\"Rectangle\" fill=\"#FFFFFF\" x=\"5\" y=\"13.9929286\" width=\"10\" height=\"1\" rx=\"0.5\"></rect>\n </svg>\n </button>\n </div> \n </div> \n </article>`;\n\n /* append cards to 'container' */\n $(container).append(generateCard);\n\n /* after all cards are appended, run function for updating status count */\n updateCount();\n\n /* event handler for clicking \"Se detaljer\" button on each card */\n $('a.card-' + obj.getId()).on('click', function() {\n \n tempStorage(); /* call tempStorage to store object for editing */\n });\n\n /* event handler for clicking edit button on each card */\n $('button.card-' + obj.getId()).on('click', function() {\n \n tempStorage(); /* call tempStorage to store object for editing */\n generateEditForm() /* when object is stored in localstorage, generate edit form inside modal */\n toggleModal(); /* when form i generated, open modal populated with information from card clicked */\n });\n\n /* event handler for clicking delete button on each card */\n $('button.delete-card-' + obj.getId()).on('click', function() {\n\n /* send a confirmation alert. If \"yes\" is clicked, proceed */\n if (window.confirm(\"Are you sure you want to delete the card?\") == true) {\n\n /* fade out card deleted */\n $('article.case-card-' + obj.getId()).fadeOut('slow', function() {\n tempStorage();\n deleteCard(); /* delete it from the cards array by running the deleteCard function/method */\n updateCount(); /* update status count */\n });\n }\n });\n }", "function createList(filter) {\n const ids = (state = [], action) => {\n switch (action.type) {\n case \"FETCH_TODOS_SUCCESS\":\n return (filter === action.filter)\n ? action.response.result\n : state;\n case \"ADD_TODO_SUCCESS\":\n return (filter !== \"complete\")\n ? [...state, action.response.result]\n : state;\n case \"TOGGLE_TODO_SUCCESS\":\n return handleToggle(state, action)\n default:\n return state;\n }\n }\n\n function handleToggle(state, action) {\n const { result: toggledId, entities } = action.response;\n const { completed } = entities.todos[toggledId];\n\n const shouldRemove =\n (completed && filter === \"active\") ||\n (!completed && filter === \"complete\");\n\n return shouldRemove\n ? state.filter(id => id !== toggledId)\n : state;\n }\n\n const isFetching = (state = false, action) => {\n if (action.filter !== filter) {\n return state;\n }\n\n switch (action.type) {\n case \"FETCH_TODOS_REQUEST\":\n return true;\n case \"FETCH_TODOS_SUCCESS\":\n case \"FETCH_TODOS_FAILURE\":\n return false;\n default:\n return state;\n }\n }\n\n const errorMessage = (state = null, action) => {\n if (action.filter !== filter) {\n return state;\n }\n\n switch (action.type) {\n case \"FETCH_TODOS_FAILURE\":\n return action.message;\n case \"FETCH_TODOS_SUCCESS\":\n case \"FETCH_TODOS_REQUEST\":\n return null;\n default:\n return state;\n }\n }\n\n return combineReducers({\n ids,\n isFetching,\n errorMessage\n })\n}", "function Cards(Scabs) {\n for (let i = 0; i < Scabs.length; i++) {\n let Thread = {\n title: \"\",\n link: \"\",\n id: \"\"\n };\n Thread.title = Scabs[i].title;\n Thread.link = reddit + Scabs[i].link;\n Thread.id = Scabs[i].redditId\n //Creates the card\n $(\".row\").after(\n `<div class=\"col s12 m6\">\\\n <div class=\"card red-grey darken-1\">\\\n <div class=\"card-content white-text\">\\\n <span class=\"card-title\">'+ Thread.title + '</span>\\\n <p>' + Thread.title + '</p>\\\n </div>\\\n <div class=\"card-action\">\\\n <a href=\"' + Thread.link + '\">See the comments on Reddit</a>\\\n </div>\\\n </div >\\\n </div > `);\n }\n}", "function initializeCards() {\n cardsContainer.empty();\n var cardsToAdd = [];\n for (var i = 0; i < folUpCards.length; i++) {\n cardsToAdd.push(createNewCard(folUpCards[i]));\n }\n cardsContainer.append(cardsToAdd);\n }", "async getListTodos (context, listId) {\n try {\n const response = await fetch(`https://ap-todo-list.herokuapp.com/todosForList?listId=${listId}`)\n const data = await response.json()\n context.commit('setTodos', data)\n } catch (error) {\n // Set the error and clear the todos.\n console.error(error)\n context.commit('setTodos', [])\n }\n }", "function loadTodos() {\n const ul = document.querySelector('.todoList');\n const todos = getTodosFromLocalStorage();\n\n for (const todo of todos) {\n const li = createTodoElement(todo);\n ul.append(li);\n }\n}", "function getCards(){\r\n mosaic.innerHTML = ''\r\n fetch(SURVEY_URL)\r\n .then(resp => resp.json())\r\n .then(surveys => {\r\n const surveysArray = surveys['data']\r\n for (const survey of surveysArray) {\r\n mosaic.innerHTML += `\r\n <div class=\"card\" id=\"${survey.id}\">\r\n <div class=\"card-body\">\r\n <h5 class=\"card-title\">${survey['attributes']['name']}</h5>\r\n <p class=\"card-text survey_description\">${survey['attributes']['description']}</p>\r\n <button type=\"button\" class=\"btn btn-success\" data-toggle=\"modal\" data-target=\"#takeSurvey\" onclick=\"Survey.populate(${survey.id})\"> Take Survey </button>\r\n <button type=\"button\" class=\"btn btn-info\" data-toggle=\"modal\" data-target=\"#surveyResults\" onclick=\"Survey.results(${survey.id})\"> See Results </button>\r\n <br /><br />\r\n <button type=\"button\" class=\"btn btn-primary\" onclick=\"Survey.deleteSurvey(${survey.id})\"> Delete Survey </button>\r\n\r\n </div>\r\n </div>\r\n `\r\n }\r\n })\r\n}", "insertTodo(user_id, todo) {\n\t\tconst self = this;\n\t\tfetch(todosUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\ttitle: todo,\n\t\t\t\tcompleted: false,\n\t\t\t\tuserId: user_id\n\t\t\t}),\n\t\t\theaders: {\n\t\t\t\t\"Content-type\": \"application/json; charset=UTF-8\"\n\t\t\t}\n\t\t})\n\t\t.then(response => response.json())\n\t\t.then(json => {\n\t\t\tconsole.log(json);\n\t\t\tself.setState({todoSubmitted: true});\n\t\t})\n\t\t.catch(function(error) {\n\t\t console.log(error)\n\t\t}); \n\t}", "function fetchProject() {\n $.ajax({\n url: `${baseURL}/project`,\n method: 'GET',\n headers : {\n access_token : localStorage.getItem('jwtToken')\n }\n })\n .done(projects => {\n \n console.log(projects, 'fetch project');\n if (projects.length > 0) {\n $('.fixed-action-btn').show()\n $('.remark').hide()\n $('.project-cards').show()\n $('.detailed-project').hide()\n $('.project-cards').empty()\n projects.forEach(project => {\n // console.log(project, 'dari for each fetch');\n // console.log(project._id, 'dr fetch nyari id prjct ada gakkk');\n \n // <i class=\"material-icons\" style=\"color: orange;\">delete</i>\n\n $('.project-cards').append(`\n \n <div class=\"col s4\">\n <div class=\"card cyan darken-4\">\n <div class=\"card-content white-text\">\n <div class=\"project-title\">\n <span style=\"font-size: 35px; margin-bottom: 30px;\" class=\"card-title\">${project.title}</span>\n </div>\n <p>“Focus on being productive instead of busy.” <br>\n – Tim Ferriss</p>\n </div>\n <div class=\"card-action\">\n <div>\n <a href=\"#\"><i class=\"fas fa-users\"></i>&nbsp;${project.members.length}</a>\n <a href=\"#\"><i class=\"far fa-list-alt\"></i>&nbsp;${project.todos.length}</a>\n </div>\n <div>\n <i onclick=\"showDetailProject('${project._id}')\" class=\"material-icons clickable\" style=\"color: orange;\">navigate_next</i>\n </div>\n </div>\n </div>\n </div>\n \n `)\n })\n } else {\n $('.remark').show()\n $('.project-cards').hide()\n $('.detailed-project').hide()\n $('.fixed-action-btn').hide()\n }\n })\n .fail(err => {\n console.log(`failed to fetch project`);\n \n })\n .always(() => {\n console.log(`complete`);\n \n })\n}", "function displaytodo(todo) {\r\n console.log(\"Display\")\r\n if (todo.state == 0) {\r\n // create an item on the pending list\r\n var list = $(\"#todo\");\r\n list.append(`<li id=\"${todo.id}\" class=\"list-group-item\">${todo.text} <button class=\"btn btn-outline-primary float-right\" onclick=\"markDone(${todo.id});\" > Done </button> </li>`);\r\n }\r\n else {\r\n // create an item on the done list\r\n var list = $(\"#donetodo\");\r\n list.append('<li class=\"list-group-item\">' + todo.text + '</li>');\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: main Loads the story from the storage div, initializes macros and custom stylesheets, and displays the first passages of the story. Returns: nothing
function main() { tale = new Tale(); // process title, subtitle, author passages setPageElement('storyMenu', 'StoryMenu', ''); setPageElement('storyTitle', 'StoryTitle', 'Untitled Story'); setPageElement('storySubtitle', 'StorySubtitle', ''); setPageElement('storyAuthor', 'StoryAuthor', ''); if (tale.has('StoryTitle')) { document.title = tale.get('StoryTitle').text; if (tale.has('StorySubtitle')) document.title += ': ' + tale.get('StorySubtitle').text; }; // initialize macros for (macro in macros) if (typeof macro.init == 'function') macro.init(); // process passages tagged 'stylesheet' var styles = tale.lookup('tags', 'stylesheet'); for (var i = 0; i < styles.length; i++) addStyle(styles[i].text); // process passages tagged 'script' var scripts = tale.lookup('tags', 'script'); for (var i = 0; i < scripts.length; i++) try { eval(scripts[i].text); } catch (e) { alert('There is a technical problem with this story (' + scripts[i].title + ': ' + e.message + '). You may be able ' + 'to continue reading, but all parts of the story may not ' + 'work properly.'); }; // initialize history and display initial passages state = new History(); state.init(); console.log('init complete', tale, state); }
[ "static start() {\n\t\tconsole.log(\"Starting story.js...\");\n\t\tthis.loadJson(this.getJsonPath());\n\t\tUI.init();\n\t}", "function SimpleStoryCreator() {\n // ************************************************************\n // * All required lists *\n // ************************************************************\n\n // List of all possible story plots\n var rPlotList = [\n\t\"destroy\",\n\t\"kidnap\",\n\t\"witch\",\n\t\"revenge\"\n ];\n\n // List of story intros\n var rIntroList = [\n\t\"Once Upon a Time\",\n\t\"In a land far away\",\n\t\"Before you were born\",\n\t\"In a little village\"\n ];\n\n // List of possible endings for the story\n var rPlotEndList = [\n\t\"flee\",\n\t\"kill\",\n\t\"kill_weapon\"\n ];\n\n // List of all good people (read: Heros)\n var rHeroList = [\n\t{ Article: \"a\" , Name: \"trader\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"merchant\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"salesperson\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"salesman\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"peasant\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"farmer\", Gender: \"male\" },\n\t{ Article: \"a\" , Name: \"farmer's wife\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"hero\", Gender: \"male\" },\n\t{ Article: \"a\" , Name: \"heroine\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"blacksmith\", Gender: \"both\" },\n\t{ Article: \"an\", Name: \"artist\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"poet\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"programmer\", Gender: \"both\" },\n\t{ Article: \"an\", Name: \"artist\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"musician\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"princess\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"prince\", Gender: \"male\" }\n ];\n\n // List of all adjectives of the Hero\n var rHeroMainAdjectiveList = [\n\t{ Article: \"a\", Word: \"brave\" },\n\t{ Article: \"a\", Word: \"wealthy\" },\n\t{ Article: \"a\", Word: \"rich\" },\n\t{ Article: \"a\", Word: \"poor\" }\n ];\n\n var rHeroSecondaryAdjectiveList = [\n\t{ Male: \"kind to everyone\", Female: \"kind to everyone\" },\n\t{ Male: \"madly in love with his wife\", Female: \"madly in love with her husband\" },\n\t{ Male: \"handsome\", Female: \"beautiful\" }\n ];\n\n // List of all bad people (read: Villains)\n var rVillainList = [\n\t{ Article: \"a\" , Name: \"warlock\" },\n\t{ Article: \"a\" , Name: \"necromancer\" },\n\t{ Article: \"a\" , Name: \"ghost\" },\n\t{ Article: \"a\" , Name: \"demon\" },\n\t{ Article: \"a\" , Name: \"goblin\" },\n\t{ Article: \"a\" , Name: \"troll\" },\n\t{ Article: \"a\" , Name: \"monster\" },\n\t{ Article: \"a\" , Name: \"dwarf\" },\n\t{ Article: \"a\" , Name: \"giant\" },\n\t{ Article: \"a\" , Name: \"barbarian\" },\n\t{ Article: \"a\" , Name: \"grook\" },\n\t{ Article: \"a\" , Name: \"rogue\" },\n\t{ Article: \"a\" , Name: \"bandit\" },\n\t{ Article: \"a\" , Name: \"rascal\" },\n\t{ Article: \"a\" , Name: \"scoundrel\" },\n\t{ Article: \"an\", Name: \"orc\" },\n\t{ Article: \"an\", Name: \"ogre\" },\n\t{ Article: \"a\" , Name: \"soldier\" },\n\t{ Article: \"a\" , Name: \"warrior\" },\n\t{ Article: \"a\" , Name: \"fighter\" },\n\t{ Article: \"a\" , Name: \"viking\" },\n\t{ Article: \"a\" , Name: \"mage\" },\n\t{ Article: \"a\" , Name: \"villain\" },\n\t{ Article: \"an\", Name: \"archer\" },\n\t{ Article: \"a\" , Name: \"phantom\" }\n ];\n\n // List of possible wording for \"kill\"\n var rKillList = [\n\t\"killed\",\n\t\"murdered\",\n\t\"slayed\",\n\t\"assassinated\"\n ];\n\n // List of possible wording for \"flee\"\n var rFleeList = [\n\t\"fled\",\n\t\"fled in terror\",\n\t\"escaped\",\n\t\"manged to escape\",\n\t\"was able to flee\"\n ];\n\n // List of possible wording for \"cheat\"\n var rCheatList = [\n\t\"cheated\",\n\t\"tricked\",\n\t\"was able to trick\",\n\t\"managed to cheat\",\n\t\"fooled\"\n ];\n\n\n // Plot: Destroy; List of ways to destroy an object\n var rDestroyList = [\n\t\"destroy\",\n\t\"ruined\",\n\t\"wrecked\",\n\t\"smashed\",\n\t\"demolished\"\n ];\n\n // Plot: Destroy; List of objects that can be destroyed\n var rDestroyObjectList = [\n\t\"house\",\n\t\"garden\",\n\t\"doghouse\",\n\t\"temple\",\n\t\"clock\",\n\t\"field\",\n\t\"farm\",\n\t\"tower\",\n\t\"building\",\n\t\"residence\",\n\t\"domicile\",\n\t\"place of birth\",\n\t\"home\",\n\t\"hovel\",\n\t\"hut\",\n\t\"flat\",\n\t\"flatlet\",\n ];\n\n\n // Plot: Witch; List of ways to cast the spell\n var rWitchList = [\n\t\"enchanted\",\n\t\"spellbound\",\n\t\"bewitched\",\n\t\"entranced\"\n ];\n\n // Plot: Witch; List of ways to end the spell\n var rWitchEndList = [\n\t\"freed\",\n\t\"ended the spell casted on\",\n\t\"ended the enchantment of\"\n ];\n\n // Plot: Kidnap; List of ways to be kidnaped\n var rKidnapList = [\n\t\"kidnapped\",\n\t\"abducted\",\n\t\"carried off\"\n ];\n\n // List of final moments\n var rFinalMoment = [\n\t\"Then\",\n\t\"Finally\",\n\t\"Ultimately\",\n\t\"In the end\",\n\t\"Thereupon\",\n\t\"Thereat\",\n\t\"After that\"\n ];\n\n // List of \"One day\" events\n var rOneDayList = [\n\t\"One day\",\n\t\"There came a day\",\n\t\"One night\"\n ];\n\n // List of all possible relatives\n var rRelativeList = [\n\t\"dog\",\n\t\"cat\",\n\t\"mother\",\n\t\"father\",\n\t\"grandfather\",\n\t\"grandmother\",\n\t\"brother\",\n\t\"son\",\n\t\"sister\",\n\t\"daughter\",\n\t\"friend\",\n\t\"mate\",\n\t\"uncle\",\n\t\"aunt\",\n\t\"son-in-law\",\n\t\"dauther-in-law\",\n\t\"goldfish\",\n\t\"lover\",\n\t\"lawyer\",\n\t\"helper\"\n ];\n\n // List of possible weapons\n var rWeaponList = [\n\t\"bastard sword\",\n\t\"dagger\",\n\t\"shovel\",\n\t\"rifle\",\n\t\"magnum\",\n\t\"UZI\",\n\t\"AK-47\"\n ];\n\n\n var rStory = []; // Stores the actual story and is returned by GetStoryText\n\n // Name : sprintf\n // Parameters : At least 2 parameters are required. 1 as the actual message, and another for the content.\n // More values have to be added in case of more placeholders.\n // Description: This function replaces placeholders acording to their type. This way it's possible\n // to format a string the way the user wants it.\n // Disclaimer : This function is (C) 2006 by Naden Badalgogtapeh. The source can be found at\n // http://www.naden.de/blog/javascript-printf\n function sprintf() {\n\tif (sprintf.arguments.length < 2) {\n\t return;\n\t}\n\n\tvar data = sprintf.arguments[0];\n\n\tfor (var k = 1; k < sprintf.arguments.length; ++k) {\n\n\t switch (typeof (sprintf.arguments[k])) {\n\t case 'string':\n\t\tdata = data.replace(/%s/, sprintf.arguments[k]);\n\t\tbreak;\n\t case 'number':\n\t\tdata = data.replace(/%d/, sprintf.arguments[k]);\n\t\tbreak;\n\t case 'boolean':\n\t\tdata = data.replace(/%b/, sprintf.arguments[k] ? 'true' : 'false');\n\t\tbreak;\n\t default:\n\t\t/// function | object | undefined\n\t\tbreak;\n\t }\n\t}\n\treturn data;\n }\n\n\n // Name : rRandom\n // Parameters : This function requires 2 parameters:\n // - aMin (Integer); The lowest possible number\n // - aMax (Integer); The highest possible number\n // Description: Generates a random number and returning it.\n // Disclaimer : Exchanged this function with a more reliable solution.\n // The new version is taken from\n // http://www.naden.de/blog/zufallszahlen-in-javascript-mit-mathrandom\n // Authors are:\n // - (C) 2006 by Naden Badalgogtapeh\n // - (C) 2008 by batzee\n // - (C) 2012 by MHN\n function rRandom(aMin, aMax) {\n\tvar lMin = Math.floor( parseInt( aMin ) );\n\tvar lMax = Math.floor( parseInt( aMax ) );\n\n\tif ( lMin > lMax) {\n\t return rRandom( lMax, lMin ); // This is a suggestion from MHN\n\t}\n\n\tif ( lMin == lMax ) {\n\t return lMin;\n\t}\n\n\tvar lRandomNumber;\n\n\t// Prevent that we go over the destined area\n\tdo {\n\t lRandomNumber = Math.random();\n\t}\n\twhile( lRandomNumber == 1.0 );\n\t// End of prevention\n\n\treturn lMin + parseInt( lRandomNumber * ( lMax-lMin + 1 ) );\n }\n\n\n // Name : NewStory\n // Parameters : aStoryMode (optional; string) - In case you want\n // a specific kind of story. Can be ignored otherwise.\n // Description: Creates a plot and builds a story upon the plot.\n // Uses a random hero and a random villain for this.\n // The story is stored in the private variable rStory and can\n // be called by using the GetStoryText-routine\n this.createStory = function ( aStoryMode ) {\n\t// General information about the story\n\tvar lPlotMode = rPlotList[ rRandom( 1, rPlotList.length ) - 1 ];\n\tvar lIntro = rIntroList[ rRandom( 1, rIntroList.length ) - 1 ];\n\tvar lSubIntro = rRandom( 1, 99 );\n\tvar lPlotEndMode = rPlotEndList[ rRandom( 1, rPlotEndList.length ) - 1 ];\n\tvar lHeroID = rRandom( 1, rHeroList.length ) - 1;\n\tvar lVillainID = rRandom( 1, rVillainList.length ) - 1;\n\n\tvar lKill = rKillList[ rRandom( 1, rKillList.length ) - 1 ]; // Plot-End: kill\n\tvar lWeapon = rWeaponList[ rRandom( 1, rWeaponList.length ) - 1 ]; // Plot-End: kill_weapon\n\tvar lFlee = rFleeList[ rRandom( 1, rFleeList.length ) - 1 ]; // Plot-End: flee\n\tvar lDayMode = rRandom( 1, rOneDayList.length ) - 1;\n\tvar lFinal = rFinalMoment[ rRandom( 1, rFinalMoment.length ) - 1 ];\n\n\tvar lKidnapWay = rRandom( 1, rKidnapList.length ) - 1; // Plot: Kidnap\n\tvar lDestroyWay = rRandom( 1, rDestroyList.length ) - 1; // Plot: Destroy\n\tvar lWitchWay = rRandom( 1, rWitchList.length ) - 1; // Plot: Witch\n\tvar lWitchEnd = rWitchEndList[ rRandom( 1, rWitchEndList.length ) - 1 ];\n\n\tvar lObjectID = rRandom( 1, rDestroyObjectList.length ) - 1; // Plot: Destroy\n\tvar lRelativeID = rRandom( 1, rRelativeList.length ) - 1; // Plot: Revenge\n\n\tvar lHeroGender = rHeroList[lHeroID].Gender;\n\tvar lHeroAlternateGender;\n\tvar lHeroName = rHeroList[lHeroID].Name;\n\tvar lHeroArticle = rHeroList[lHeroID].Article;\n\tvar lHeroMainAdjective = rHeroMainAdjectiveList[ rRandom( 1, rHeroMainAdjectiveList.length ) - 1 ];\n\tvar lHeroSecondaryAdjective;\n\tvar lHeroSecondary = rHeroSecondaryAdjectiveList[ rRandom( 1, rHeroSecondaryAdjectiveList.length ) - 1 ];\n\tvar lCheatWord = rCheatList[ rRandom( 1, rCheatList.length ) - 1 ];\n\n\tvar lVillainName = rVillainList[lHeroID].Name;\n\tvar lVillainArticle = rVillainList[lHeroID].Article;\n\n\tif ( aStoryMode == \"destroy\" ) lPlotMode = \"destroy\";\n\tif ( aStoryMode == \"kidnap\" ) lPlotMode = \"kidnap\";\n\tif ( aStoryMode == \"mindcontrol\" ) lPlotMode = \"witch\";\n\tif ( aStoryMode == \"revenge\" ) lPlotMode = \"revenge\";\n\n\n\tswitch ( lHeroGender ) {\n\tcase \"both\":\n\t lHeroGender = \"He\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Male;\n\t if ( rRandom( 1, 100 ) > 50 ) {\n\t\tlHeroGender = \"She\";\n\t\tlHeroSecondaryAdjective = lHeroSecondary.Female;\n\t }\n\t break;\n\tcase \"female\":\n\t lHeroGender = \"She\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Female;\n\t break;\n\tcase \"male\":\n\t lHeroGender = \"He\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Male;\n\t break;\n\t}\n\tlHeroAlternateGender = \"his\";\n\tif ( lHeroGender.toLowerCase() == \"she\" ) lHeroAlternateGender = \"her\";\n\n\n\t// Preparing the story and the plot\n\trStory = [];\n\tvar lPlot = [];\n\tswitch ( lPlotMode ) {\n\tcase \"destroy\":\n\t lPlot.push( \"destroy\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\n\tcase \"kidnap\":\n\t lPlot.push( \"kidnap\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\n\tcase \"witch\":\n\t lPlot.push(\"witch\");\n\t lPlot.push(\"cheat\");\n\t lPlot.push(\"entwitch\");\n\t break;\n\n\tcase \"revenge\":\n\t lPlot.push( \"revenge\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\t}\n\tlPlot.push( lPlotEndMode );\n\n\n\t// Adding the intro\n\tvar lPlotLine = sprintf(\"%s there lived %s %s.\", lIntro, lHeroArticle, lHeroName);\n\tif ( lSubIntro > 33 ) lPlotLine = sprintf(\"%s there was %s %s %s.\", lIntro, lHeroMainAdjective.Article, lHeroMainAdjective.Word, lHeroName );\n\tif ( lSubIntro > 66 ) lPlotLine = sprintf(\"%s there was %s %s who was %s.\", lIntro, lHeroArticle, lHeroName, lHeroSecondaryAdjective );\n\trStory.push( lPlotLine );\n\n\t// Adding the rest of the plot\n\tfor (var lIndex = 0; lIndex < lPlot.length; lIndex++) {\n\n\t switch ( lPlot[ lIndex ] ) {\n\t case \"cheat\":\n\t\tlPlotLine = sprintf(\"%s %s the %s.\", lHeroGender, lCheatWord, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"The %s %s the %s.\", lHeroName, lCheatWord, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"destroy\":\n\t\tlPotLine = sprintf(\"%s %s %s %s the %s of the %s.\", rOneDayList[ lDayMode ], lVillainArticle, lVillainName, rDestroyList[ lDestroyWay ], rDestroyObjectList[ lObjectID ], lHeroName );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"entwitch\":\n\t\tlPotLine = sprintf(\"The %s %s the %s.\", lVillainName, lWitchEnd, lHeroName);\n\t\t//if ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"flee\":\n\t\tlPotLine = sprintf(\"%s %s %s.\", lFinal, lHeroGender.toLowerCase(), lFlee );\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s %s.\", lFinal, lHeroName, lFlee );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kidnap\":\n\t\tlPotLine = sprintf(\"%s %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroGender.toLowerCase(), rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kill\":\n\t\tlPotLine = sprintf(\"%s %s %s the %s.\", lFinal, lHeroGender.toLowerCase(), lKill, lVillainName );\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s %s.\", lFinal, lHeroName, lFlee );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kill_weapon\":\n\t\tlPotLine = sprintf(\"%s %s %s the %s with %s %s.\", lFinal, lHeroGender.toLowerCase(), lKill, lVillainName, lHeroAlternateGender, lWeapon );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"revenge\":\n\t\tlPotLine = sprintf(\"%s %s %s %s the %s of the %s.\", rOneDayList[ lDayMode ], lVillainArticle, lVillainName, lKill, rRelativeList[ lRelativeID ], lHeroName );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"witch\":\n\t\tlPotLine = sprintf(\"%s %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroGender.toLowerCase(), rWitchList[ lWitchWay ], lVillainArticle, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rWitchList[ lWitchWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\t };\n\t}\n };\n\n // Name : GetStoryText\n // Parameters : None\n // Description: Returns the stored story as an array where each line is an entry\n this.getStoryText = function () {\n\treturn rStory;\n };\n\n\n // Name : AddHero\n // Parameters : This function requires 3 parameters:\n // - aArticle (string); The article of the hero; Can either be \"a\", \"an\", \"the\"or \"\"\n // - aName (string); the nma or job of the hero\n // - aGender (string); the gender of the hero; Can either be \"male\", \"female\" or \"both\"\n // Description: Adds a new possible hero to the list of heros. The user can define the name/job, the gender and an article\n // which is to be used with the name.\n this.addHero = function (aArticle, aName) {\n\tvar lArticle = aArticle.toLowerCase();\n\tvar lGender = aGender.toLowerCase();\n\n\trHeroList.push( { Article: lArticle, Name: aName, Gender: lGender } );\n };\n\n this.createStory(); // Creatinng a story in advance\n}", "function main() {\n slideEls = document.querySelectorAll('.presentation > div')\n\n // Set up\n getSlideNumberFromUrlFragment()\n showSlide(true, true)\n onSlideEntry(slideEls[currentSlideNumber], false)\n\n // Specific slide preparations\n prepareFillLoupe()\n underlinePlaygroundPosition({ target: document.querySelector('#upo-p') })\n underlinePlaygroundSize({ target: document.querySelector('#upo-s') })\n underlinePlaygroundClearing({ target: document.querySelector('#upo-c') })\n underlinePlaygroundOpacity({ target: document.querySelector('#upo-o') })\n document.querySelectorAll('label').forEach(function(el) { el.classList.remove('visible') })\n\n // Slide manipulation\n hyphenateSlides()\n setUpBetterPunctuation()\n\n document.body.addEventListener('keydown', onKeyDown)\n document.body.focus()\n}", "function renderUI() {\n document.getElementById(\"story0\").innerHTML = yourStory;\n document.getElementById(\"allStories-items\").innerHTML = allStories;\n}", "function init() {\n let iframe = document.createElement('iframe');\n iframe.setAttribute('src', root + 'assets/html/' + page_key + \".html\");\n \n\n //This is the event listener for \"load\" for the iframe\n //object that hasn't been loaded to the screen yet\n //After the iframe is loaded, we can then load the css, js, and render\n //the html onto the screen\n iframe.addEventListener('load', () => {\n let ifr = document.querySelector('iframe');\n document.querySelector('main').innerHTML = ifr.contentDocument.querySelector('body').innerHTML;\n link_css(\"pages/\" + page_key);\n link_js(\"pages/\" + page_key);\n })\n \n //render the iframe onto the screen to load the sub page\n document.querySelector('#iframe-loader').appendChild(iframe);\n\n //underline the page button in the navbar\n underline_page_button();\n}", "function getStory() {\n\txhttp = new XMLHttpRequest(); // <-- create request\n\tchangeSong(); // <-- load first song\n\n\t// Each time the request-state changes...\n\txhttp.onreadystatechange = function() {\n\n\t\t// readyState(4) = Operation complete, status(200) = request succesfull\n\t\tif (this.readyState == 4 && this.status == 200) {\n\n\t\t\tstrStory = xhttp.responseText; // <-- retrieve text from query\n\t\t\tstoryParts = strStory.split(\"<END>\"); // <-- break string into array by '<END>' delimeter (was written into .txt file)\n\t\t\tstoryParts.unshift(intro); // <-- add intro portion\n\n\t\t\t// for each string element in array...\n\t\t\tfor (var i = 0; i < storyParts.length; i++) {\n\t\t\t\tstoryParts[i] = storyParts[i].trim(); // <-- trim any leading/trailing white-spaces\n\t\t\t}\n\t\t\ttextAreaEl.value = storyParts[0]; // <-- set opening window to first string (Intro)\n\t\t}\n\t}\n\txhttp.open(\"GET\", \"pupProcess.php?name=\" + storyName, true); // <-- Open .php file, passing 'name' parameter to open file\n\txhttp.send(); // <-- sent request\n}", "function loadContent() {\n\t\tMassIdea.loadHTML($contentList, URL_LOAD_CONTENT, {\n\t\t\tcategory : _category,\n\t\t\tsection : _section,\n\t\t\tpage : 0\n\t\t});\n\t}", "function MyStory()\n{\n\n this.getStoryPages = function getStoryPages(name) //public function\n {\n //alert(\"MyStory.getStoryPages() \"+name);\n\n if (name === \"testStoryBasicPageNumbers\")\n {\n //alert(\"MyStory.getStoryPages --- found '\"+name+\"'\");\n return getStoryBasicPageNumbers();\n }else if (name === \"testZero\")\n {\n //alert(\"MyStory.getStoryPages --- found '\"+name+\"'\");\n return getStoryPagesTestZero();\n }else if (name === \"testOne\")\n {\n //alert(\"MyStory.getStoryPages --- found '\"+name+\"'\");\n return getStoryPagesTestOne();\n }else if (name === \"orangeStory\")\n {\n //alert(\"MyStory.getStoryPages --- found '\"+name+\"'\");\n return getStoryOranges();\n }else if (name === \"zapperStory\")\n {\n //alert(\"MyStory.getStoryPages --- found '\"+name+\"'\");\n return getStoryZapper();\n }\n \n \n \n //in all other cases\n return getStoryPagesNotFound(name);\n }\n \n function getStoryPagesNotFound(name) //private function\n {\n\n var _storyPage = [];\n\n var animationList = [];\n animationList.push(new MyTitle(\"Story Not Found\", 0, 30, 80));\n animationList.push(new MyTitle(name, 0, 30, 180));\n \n var theText = \"Your story named '\"+name+\"' was not found in the MyStory.js file. If '\"+name+\"' is the name of your story, then check the MyStory.js file to make certain that the story name is listed in the 'getStoryPages' function. If '\"+name+\"' is not the name of your story, then check the .html file to correct the spelling of the name.\";\n animationList.push(new MyScrollingText(theText, 150, 250, 270));\n\n\t\tanimationList.push(new MyMovingTitle(\"tester\", 0, 30, 180));\n\n var optionList = [];\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"notFound\",animationList,optionList));\n //////////\n //////////\n \n return _storyPage;\n\n\t}\n\n\t\n function getStoryBasicPageNumbers() //private function\n {\n \n \t//alert(\"start getBasicPageNumbers()\");\n\n _storyPage = [];\n \n \n var animationList = [];\n animationList.push(new MyTitle(\"Page Not Found\", 0, 30, 80));\n animationList.push(new MyTitle(name, 0, 30, 180));\n \n var theText = \"The requested page was not found in the MyStory.js file. Check the name of your page reference.\";\n animationList.push(new MyScrollingText(theText, 150, 250, 270));\n\n\t\t//animationList.push(new MyMovingTitle(\"tester\", 0, 30, 180));\n\n var optionList = [];\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"notFound\",animationList,optionList));\n //////////\n //////////\n//CHANGE NAMES HERE\n animationList = [];\n //animationList.push(new MyMovingTitle(\"Hello There\", 0, 150, 80));\n animationList.push(new MySplashPage(\"Splash Page\", 20, -250, 80));\n //animationList.push(new MyMovingTitle(\"Page One\", -200, -450, 180));\n\n\n optionList = [];\n optionList.push(new PageOption(\"Start Game\",\n \"Click here to start the game. \" + _g_pathMainLabel,\n \"fuelingChallenge\"));\n\n optionList.push(new PageOption(\"New Game\",\n \"Click here to start a new game. \" + _g_pathMainLabel,\n \"fuelingChallenge\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n\t\t\n _storyPage.push(new PageBasic(\"splashPage\",animationList,optionList));\n\t\t//so this page has the name \"pageOne\"\n //////////\n //////////\n\n\n animationList = [];\n\t\t\t\n\t\tanimationList.push(new MyGroundBackground(\"BG\", 0, 0, 0));\n\t\t\t\n\t\tanimationList.push(new MyParagraph(0, 5, 20,\n\t\t\t\"Before leaving Earth, Major Tom must\",\n\t\t\t\"fuel the ship. Drag the fuel cans to\",\n\t\t\t\"the spaceship.\",\n\t\t\t\"\"));\n\t\t\t\n\t\tanimationList.push(new GasCan(\"Ball1\",0, 50, 200));\n animationList.push(new GasCan(\"Ball2\",0, 145, 270));\n animationList.push(new GasCan(\"Ball3\",0, 400, 185));\n\n\t\tanimationList.push(new Ship(\"Basket\", 0, 250, 170));\n\n optionList = [];\n optionList.push(new PageOption(\"Launch Ship\",\n \"After fueling the ship is complete, you launch the ship. \" + _g_pathMainLabel,\n \"launchShip\"));\n\n optionList.push(new PageOption(\"Strap In\",\n \"You're sitting on top of a giant explosive soda can that is about to launch you into space. What could go wrong? \" + _g_pathMainLabel,\n \"launchShip\"));\n\n _storyPage.push(new PageMoveGasCans(\"fuelingChallenge\",animationList,optionList));\n \n\t\t//////////\n //////////\n\n\n animationList = [];\n\t\tanimationList.push(new MyTitle(\"Launch\", 0, 150, 80));\n\t\t\n\t\tanimationList.push(new MyGroundBackground(\"BG\", 0, 0, 0));\n\t\tanimationList.push(new MyParagraph(0, 10, 20,\n\t\t\t\"This ship launches,\",\n\t\t\t\"and you are asked to\",\n\t\t\t\"enter the coordinates of\",\n\t\t\t\"Mars on the computer.\"));\n\t\tanimationList.push(new Ship(\"liftoff\", 0, 250, 170));\n\t\t\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"Let the Ship Navigate\",\n \"You decide to let the ship find its own way to Mars. \" + _g_pathSideLabel,\n \"shipNavigate\"));\n\n optionList.push(new PageOption(\"Input Coordinates\",\n \"You decide to enter Mars' coordinates into the computer. \" + _g_pathMainLabel,\n \"coordinatesChallenge\"));\n\n\n\n _storyPage.push(new PageBasic(\"launchShip\",animationList,optionList));\n\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Throttle Up\", 0, 150, 80));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new MySpaceBackground(\"earth\"));\n\t\tanimationList.push(new ShipRight(\"flying\", 0, 300, 125));\n\t\t\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"You decide to let the ship navigate.\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"Fly Away\",\n \"Leave Earth's orbit. \" + _g_pathSideLabel,\n \"aroundMoon\"));\n\n optionList.push(new PageOption(\"Ditch Planet Earth\",\n \"You never liked it much, anyway. Too many Walmarts. \" + _g_pathSideLabel,\n \"aroundMoon\"));\n\n _storyPage.push(new PageBasic(\"shipNavigate\",animationList,optionList));\n\n\t\t\n\t\t//////////\n //////////\n\t\t\n\t\t\n animationList = [];\n animationList.push(new MyTitle(\"Slingshot\", 0, 150, 80));\n\t\tanimationList.push(new MySpaceBackground(\"moon\"));\n\t\tanimationList.push(new ShipRight(\"slingshot\", 0, 200, 275));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"Your ship does a gravitational\",\n\t\t\t\"slingshot around the moon.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\t\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"Continue\",\n \"Continue on your path. \" + _g_pathSideLabel,\n \"returnToEarth\"));\n\n optionList.push(new PageOption(\"Continue\",\n \"Looks like we're back to square one. \" + _g_pathSideLabel,\n \"returnToEarth\"));\n\n\n\n _storyPage.push(new PageBasic(\"aroundMoon\",animationList,optionList));\n\n\t\t\n\t\t//////////\n //////////\n\t\t\n\t\t\n animationList = [];\n animationList.push(new MyTitle(\"Return\", 0, 150, 80));\n\t\t\t\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new MySpaceBackground(\"earth\"));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"You have returned to Earth. You must\",\n\t\t\t\"choose a way to get to Mars.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\tanimationList.push(new ShipRight(\"flying\", 0, -50, 125));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"Let the Ship Navigate\",\n \"You decide to let the ship find its own way to Mars. \" + _g_pathSideLabel,\n \"shipNavigate\"));\n\n optionList.push(new PageOption(\"Input Coordinates\",\n \"You decide to enter Mars' coordinates into the computer. \" + _g_pathMainLabel,\n \"coordinatesChallenge\"));\n\n\n\n _storyPage.push(new PageBasic(\"returnToEarth\",animationList,optionList));\n\n\t\t\n\t\t//////////\n //////////\n\t\t\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Coordinates\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"This will be a challenge page.\",\n\t\t\t\"You will be given coordinates to Mars,\",\n\t\t\t\"and you have to enter them into the computer.\",\n\t\t\t\"\"));\n\t\t\t\n\t\tanimationList.push(new CockpitView());\n\t\t\t\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"Fly Away\",\n \"Leave Earth's orbit. \" + _g_pathMainLabel,\n \"leaveEarth\"));\n\n optionList.push(new PageOption(\"Stay Here\",\n \"Stay in Earth's orbit. \" + _g_pathSideLabel,\n \"stayAtEarth\"));\n\n\n\n _storyPage.push(new PageComputerInput(\"coordinatesChallenge\",animationList,optionList));\n\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Stay\", 0, 150, 80));\n\t\tanimationList.push(new MySpaceBackground(\"earth\"));\n\t\tanimationList.push(new ShipRight(\"ship\", 0, 300, 125));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"You stay in Earth's orbit.\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\toptionList.push(new PageOption(\"Fly Away\",\n \"Leave Earth's orbit. \" + _g_pathMainLabel,\n \"leaveEarth\"));\n\t\t\n optionList.push(new PageOption(\"Ditch Planet Earth\",\n \"You never liked it much, anyway. Too many Walmarts. \" + _g_pathMainLabel,\n \"leaveEarth\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"stayAtEarth\",animationList,optionList));\n\t\n\t\t//////////\n //////////\n\n animationList = [];\n animationList.push(new MyTitle(\"Leave\", 0, 150, 80));\n\t\t\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new MySpaceBackground(\"earth\"));\n\t\tanimationList.push(new ShipRight(\"flying\", 0, 300, 125));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"Your ship takes off, and you must\",\n\t\t\t\"prepare for the long trip to Mars.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"Eat Some Food\",\n \"You eat some food. \" + _g_pathMainLabel,\n \"eatFood\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Eat Some Food\",\n \"You hope it's steak. \" + _g_pathMainLabel,\n \"eatFood\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"leaveEarth\",animationList,optionList));\n\t\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Eat\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"You eat some food before\",\n\t\t\t\"your cryosleep.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\tanimationList.push(new DrawThisObject(\"astronautIceCream\", 350, 100));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\toptionList.push(new PageOption(\"Take Pills\",\n \"You take your cryopills. \" + _g_pathMainLabel,\n \"takePills\"));\n\t\t\n optionList.push(new PageOption(\"Hope the Pills Taste Better\",\n \"After almost puking, you take your cryopills. \" + _g_pathMainLabel,\n \"takePills\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"eatFood\",animationList,optionList));\n\t\n\t\t//////////\n //////////\n\n\t\t\n animationList = [];\n animationList.push(new MyTitle(\"Take Pills\", 0, 100, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"You take your cryopills,\",\n\t\t\t\"which allow you to go into\",\n\t\t\t\"cryosleep and sleep for\",\n\t\t\t\"months at a time.\"));\n\t\t\n\t\tanimationList.push(new DrawThisObject(\"pills\", 300, 100));\n\t\t\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\toptionList.push(new PageOption(\"Get Some Rest\",\n \"You decide to go to sleep to prepare for the long journey ahead. \" + _g_pathMainLabel,\n \"getRest\"));\n\t\t\n optionList.push(new PageOption(\"Take a Nap\",\n \"There's not much else to do, so you take a nap. \" + _g_pathMainLabel,\n \"getRest\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"takePills\",animationList,optionList));\n\t\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Rest\", 0, 150, 80));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new Bedroom());\n\t\tanimationList.push(new DrawThisObject(\"astronaut\", 150, 150));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\toptionList.push(new PageOption(\"Wake Up\",\n \"An alarm is going off, causing you to wake up. \" + _g_pathMainLabel,\n \"wakeUp\"));\n\t\t\n optionList.push(new PageOption(\"Reluctantly Wake Up\",\n \"An alarm is going off, causing you to wake up. You turn off your alarm clock, and try to go back to sleep, but the buzzing continues. \" + _g_pathMainLabel,\n \"wakeUp\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"getRest\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Awaken\", 0, 150, 80));\n\t\tanimationList.push(new MySpaceBackground(\"asteroids\"));\n\t\tanimationList.push(new ShipRight(\"ship\", 0, 125, 200));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"There is an alert for an asteroid field ahead.\",\n\t\t\t\"You must choose to go through the asteroids\",\n\t\t\t\"and save fuel, or go around the asteroids and\",\n\t\t\t\"lose fuel.\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\toptionList.push(new PageOption(\"Go Through the Asteroids\",\n \"You decide to enter the asteroid field and save fuel. \" + _g_pathMainLabel,\n \"asteroidChallenge\"));\n\t\t\n optionList.push(new PageOption(\"Avoid the Asteroids\",\n \"You decide to attempt going around the asteroid field and lose fuel. \" + _g_pathSideLabel,\n \"avoidAsteroids\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"wakeUp\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Avoid Asteroids\", 0, 150, 80));\n\t\tanimationList.push(new MySpaceBackground(\"asteroids\"));\n\t\tanimationList.push(new ShipRight(\"ship\", 0, 125, 200));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"You try to avoid the asteroids,\",\n\t\t\t\"but you can't see the end of the\",\n\t\t\t\"asteroid field.\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Continue\",\n \"Continue flying, and try to find a way around the asteroid field. \" + _g_pathSideLabel,\n \"wakeUp\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Go Through the Asteroids\",\n \"You decide to enter the asteroid field and save fuel. \" + _g_pathMainLabel,\n \"asteroidChallenge\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"avoidAsteroids\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n animationList = [];\n animationList.push(new MyTitle(\"Asteroids\", 0, 150, 80));\n\t\tanimationList.push(new MySpaceBackground(\"asteroids2\"));\n\t\tanimationList.push(new ShipRight(\"ship\", 0, 200, 200));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"You decide to go through the asteroids.\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"The Ship Is Damaged\",\n \"While going through the asteroid field, your ship is damaged. \" + _g_pathMainLabel,\n \"damagedShip\"));\n\t\t\n\t\toptionList.push(new PageOption(\"You Broke Some Stuff\",\n \"Were you texting and flying when you hit those asteroids? \" + _g_pathMainLabel,\n \"damagedShip\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"asteroidChallenge\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n\t\t\n animationList = [];\n animationList.push(new MyTitle(\"Damaged\", 0, 150, 80));\n\t\tanimationList.push(new MySpaceBackground(\"asteroids3\"));\n\t\tanimationList.push(new ShipRight(\"ship\", 0, 350, 200));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"Your ship was damaged while navigating\",\n\t\t\t\"the asteroid field.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Check the Ship\",\n \"You made it out alive, but the ship is damaged, and you decide to check it. \" + _g_pathMainLabel,\n \"checkShip\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Check the Ship\",\n \"You don't want to check the ship, but an annoying alarm is buzzing until you do. \" + _g_pathMainLabel,\n \"checkShip\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"damagedShip\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n animationList = [];\n animationList.push(new MyTitle(\"Damage\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"This page will ask the player\",\n\t\t\t\"if they want to repair the ship.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new MySpaceBackground(\"space\"));\n\t\tanimationList.push(new DrawThisObject(\"flames\", 250, 80));\n\t\tanimationList.push(new DrawThisObject(\"shipLargeRight\", 150, 50));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"You checked the ship, and the damage looks\",\n\t\t\t\"severe. You think that it is able to be repaired.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\toptionList.push(new PageOption(\"Repair the Ship\",\n \"You decide to do an EVA and repair the outer hull of the ship. \" + _g_pathMainLabel,\n \"repairShip\"));\n\t\t\n optionList.push(new PageOption(\"Don't Repair the Ship\",\n \"You decide not to repair the outer hull of the ship. \" + _g_pathSideLabel,\n \"doNotRepairShip\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"checkShip\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n\t\t\n animationList = [];\n animationList.push(new MyTitle(\"Damage\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"This page will ask the player\",\n\t\t\t\"if they want to repair the ship.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new MySpaceBackground(\"space\"));\n\t\tanimationList.push(new DrawThisObject(\"flames\", 250, 80));\n\t\tanimationList.push(new DrawThisObject(\"shipLargeRight\", 150, 50));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"The ship is no longer able to move.\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\toptionList.push(new PageOption(\"Repair the Ship\",\n \"You decide to do an EVA and repair the outer hull of the ship. \" + _g_pathMainLabel,\n \"repairShip\"));\n\t\t\n optionList.push(new PageOption(\"Don't Repair the Ship\",\n \"You decide not to repair the outer hull of the ship. \" + _g_pathSideLabel,\n \"doNotRepairShipAgain\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"doNotRepairShip\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n\t\t\n animationList = [];\n animationList.push(new MyTitle(\"Damage\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"This page will ask the player\",\n\t\t\t\"if they want to repair the ship.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new MySpaceBackground(\"space\"));\n\t\tanimationList.push(new DrawThisObject(\"flames\", 250, 80));\n\t\tanimationList.push(new DrawThisObject(\"shipLargeRight\", 150, 50));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"The ship's computer is no longer working.\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\toptionList.push(new PageOption(\"Repair the Ship\",\n \"You decide to do an EVA and repair the outer hull of the ship. \" + _g_pathMainLabel,\n \"repairShip\"));\n\t\t\n optionList.push(new PageOption(\"Don't Repair the Ship\",\n \"You decide not to repair the outer hull of the ship. \" + _g_pathSideLabel,\n \"doNotRepairShip\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"doNotRepairShipAgain\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Repair\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"This page have an animation of\",\n\t\t\t\"Major Tom repairing the ship.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new MySpaceBackground(\"space\"));\n\t\tanimationList.push(new DrawThisObject(\"flames\", 250, 80));\n\t\tanimationList.push(new DrawThisObject(\"shipLargeRight\", 150, 50));\n\t\tanimationList.push(new DrawThisObject(\"astronaut\", 300, 20));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"You work on repairing the ship.\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Check The Systems\",\n \"You decide to check your ship's systems. \" + _g_pathMainLabel,\n \"systemsCheck\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Check The Systems\",\n \"You used a lot of duct tape, and you want to make sure it actually fixed everything. \" + _g_pathMainLabel,\n \"systemsCheck\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"repairShip\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Systems Check\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"You check all the systems on\",\n\t\t\t\"your ship.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new MySpaceBackground(\"space\"));\n\t\t//animationList.push(new DrawThisObject(\"flames\", 250, 80));\n\t\tanimationList.push(new DrawThisObject(\"shipLargeRight\", 150, 50));\n\t\t//animationList.push(new DrawThisObject(\"astronaut\", 300, 20));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"Everything seems to be in working\",\n\t\t\t\"order now.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Go Back To Sleep\",\n \"You start the engines and go back to cryosleep for the rest of your journey. \" + _g_pathMainLabel,\n \"backToSleep\"));\n\t\t\n\t\toptionList.push(new PageOption(\"That Was Hard Work\",\n \"You start the engines and take a nap. \" + _g_pathMainLabel,\n \"backToSleep\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"systemsCheck\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\t\t\n\n animationList = [];\n animationList.push(new MyTitle(\"Sleep\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"You go back to sleep for\",\n\t\t\t\"the rest of your journey.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\t\n\t\tanimationList.push(new Bedroom());\n\t\tanimationList.push(new DrawThisObject(\"astronaut\", 150, 150));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Wake Up\",\n \"You have entered Mars' orbit. \" + _g_pathMainLabel,\n \"putOnSuit\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Wake Up\",\n \"The computer alerts you that Mars is nearby. \" + _g_pathMainLabel,\n \"putOnSuit\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"backToSleep\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\t\t\n\t\t\n\n animationList = [];\n animationList.push(new MyTitle(\"Suit Up\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"You put your space suit on as\",\n\t\t\t\"your ship approaches Mars.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new DrawThisObject(\"astronaut\", 350, 125));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Prepare for Descent\",\n \"You have reached Mars and must prepare to descend to the Red Planet. \" + _g_pathMainLabel,\n \"prepareToDescend\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Prepare for Descent\",\n \"It's gonna be a bumpy ride. \" + _g_pathMainLabel,\n \"prepareToDescend\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"putOnSuit\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\t\t\n\t\tanimationList = [];\n //animationList.push(new MyTitle(\"Prepare\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 200,\n\t\t\t\"You must click each button so that you can\",\n\t\t\t\"prepare the ship for descent to Mars.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new Button(\"button\", 0, 100, 100));\n\t\tanimationList.push(new Button(\"button2\", 0, 250, 100));\n\t\tanimationList.push(new Button(\"button3\", 0, 400, 100));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Stay Onboard\",\n \"You decide to stay onboard the ship. \" + _g_pathSideLabel,\n \"stayOnboard\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Descend to Mars\",\n \"You decide to descend to Mars' surface. \" + _g_pathMainLabel,\n \"descendToMars\"));\n\t\t\n\t\t_storyPage.push(new PageHitButtons(\"prepareToDescend\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\t\t\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Systems Check\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"You check all the systems on\",\n\t\t\t\"your ship.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n\t\tanimationList.push(new MySpaceBackground(\"mars\"));\n\t\tanimationList.push(new ShipRight(\"shipRight\", 0, 180, 150));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"You decide to stay in Mars\",\n\t\t\t\"orbit for a little while.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Descend to Mars\",\n \"You decide to descend to Mars' surface. \" + _g_pathMainLabel,\n \"descendToMars\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Ditch the Ship\",\n \"You're sick of the ship, so you decide that you are going to leave it in some parking lot on Mars. \" + _g_pathMainLabel,\n \"descendToMars\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"stayOnboard\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"Descent\", 0, 150, 80));\n\t\tanimationList.push(new MyParagraph(0, 50, 150,\n\t\t\t\"This page will have an animation\",\n\t\t\t\"showing the ship descending to Mars.\",\n\t\t\t\"\",\n\t\t\t\"\"));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\t\t\n\t\tanimationList.push(new MySpaceBackground(\"mars2\"));\n\t\tanimationList.push(new Ship(\"descent\", 0, 250, 100));\n\t\tanimationList.push(new MyDarkBGParagraph(0, 10, 20,\n\t\t\t\"Your engines ignite as you\",\n\t\t\t\"reverse thrust and descend\",\n\t\t\t\"to Mars surface.\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Land Your Ship\",\n \"Land on the surface of Mars. \" + _g_pathMainLabel,\n \"landShip\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Continue Your Descent\",\n \"Continue descending and land on Mars. \" + _g_pathMainLabel,\n \"landShip\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"descendToMars\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\t\t\n\n animationList = [];\n animationList.push(new MyTitle(\"Landing\", 0, 150, 80));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\t\t\n\t\tanimationList.push(new MySpaceBackground(\"mars3\"));\n\t\tanimationList.push(new Ship(\"Basket\", 0, 250, 200));\n\t\tanimationList.push(new MyParagraph(0, 10, 20,\n\t\t\t\"You successfully landed on the surface of Mars.\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"));\n\t\t\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"End Game\",\n \"Go to the end game screen. \" + _g_pathMainLabel,\n \"end\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Game Over\",\n \"Go to the end game screen. \" + _g_pathMainLabel,\n \"end\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"landShip\",animationList,optionList));\n\t\t\n\t\t//////////\n //////////\n\n\n animationList = [];\n\t\t\n\t\tanimationList.push(new MySpaceBackground(\"mars3\"));\n\t\tanimationList.push(new DrawThisObject(\"meteorite\", 25, 100));\n\t\tanimationList.push(new DrawThisObject(\"astronautGuitar\", 150, 125));\n animationList.push(new MyTitle(\"The End\", 0, 120, 80));\n //animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n\t\t\n\t\toptionList.push(new PageOption(\"Restart\",\n \"Restart the game.\",\n \"splashPage\"));\n\t\t\n\t\toptionList.push(new PageOption(\"Start Over\",\n \"Restart the game.\",\n \"splashPage\"));\n\t\t\n\t\t_storyPage.push(new PageBasic(\"end\",animationList,optionList));\n\t\t\n\t\t\n\t\t\n\t\n\n\n //////////////////////////////////////////////////////////// *************\n //////////\n \n \n //////////\n //////////\n\n\n //////////\n //////////\n \n \n //////////\n //////////\n\n\n //////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"The End\", 0, 50, 80));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"restart story\",\n \"end of story\",\n \"pageOne\"));\n\n optionList.push(new PageOption(\"restart story\",\n \"end of story\",\n \"pageOne\"));\n\n\n\n _storyPage.push(new PageSimpleEnd(\"pageEnd\",animationList,optionList));\n \n //alert(\"emd getStoryPagesTestZero()\");\n\n return _storyPage;\n\n }\n \n ////////////////////////////////\n ////////////////////////////////\n\n function getStoryPagesTestZero() //private function\n {\n \n \t//alert(\"start getStoryPagesTestZero()\");\n\n _storyPage = [];\n \n \n var animationList = [];\n animationList.push(new MyTitle(\"Page Not Found\", 0, 30, 80));\n animationList.push(new MyTitle(name, 0, 30, 180));\n \n var theText = \"The requested page was not found in the MyStory.js file. Check the name of your page reference.\";\n animationList.push(new MyScrollingText(theText, 150, 250, 270));\n\n\t\t//animationList.push(new MyMovingTitle(\"tester\", 0, 30, 180));\n\n var optionList = [];\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"notFound\",animationList,optionList));\n //////////\n //////////\n\n animationList = [];\n //animationList.push(new MyMovingTitle(\"Hello There\", 0, 150, 80));\n animationList.push(new MyMovingTitle(\"Page One\", 20, -250, 80));\n //animationList.push(new MyMovingTitle(\"Page One\", -200, -450, 180));\n\n\n optionList = [];\n optionList.push(new PageOption(\"go pageFour\",\n \"You decide to try pageFour.\",\n \"pageFour\"));\n\n optionList.push(new PageOption(\"go pageFive\",\n \"You decide to try pageFive.\",\n \"pageFive\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageOne\",animationList,optionList));\n //////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"pageFive\", 0, 150, 80));\n\n optionList = [];\n optionList.push(new PageOption(\"end story\",\n \"You decide to end the story.\",\n \"pageEnd\"));\n\n optionList.push(new PageOption(\"restart story\",\n \"You decide to restart the story.\",\n \"pageOne\"));\n\n _storyPage.push(new PageBasic(\"pageFive\",animationList,optionList));\n //////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"pageFour\", 0, 150, 80));\n animationList.push(new MyMovingTitle(\" hello ----\", 0, -450, 180));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"try again\",\n \"You decide to restart this page.\",\n \"pageFour\"));\n\n optionList.push(new PageOption(\"restart story\",\n \"You decide to restart the story.\",\n \"pageOne\"));\n\n\n\n _storyPage.push(new PageBasic(\"pageFour\",animationList,optionList));\n\n\n //////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyTitle(\"The End\", 0, 50, 80));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"restart story\",\n \"end of story\",\n \"pageOne\"));\n\n optionList.push(new PageOption(\"restart story\",\n \"end of story\",\n \"pageOne\"));\n\n\n\n _storyPage.push(new PageSimpleEnd(\"pageEnd\",animationList,optionList));\n \n //alert(\"emd getStoryPagesTestZero()\");\n\n return _storyPage;\n\n }\n \n ////////////////////////////////\n ////////////////////////////////\n function getStoryPagesTestOne() //private function\n {\n\n _storyPage = [];\n \n \n var animationList = [];\n animationList.push(new MyTitle(\"Page Not Found\", 0, 30, 80));\n animationList.push(new MyTitle(name, 0, 30, 180));\n \n var theText = \"The requested page was not found in the MyStory.js file. Check the name of your page reference.\";\n animationList.push(new MyScrollingText(theText, 150, 250, 270));\n\n\t\t//animationList.push(new MyMovingTitle(\"tester\", 0, 30, 180));\n\n var optionList = [];\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"notFound\",animationList,optionList));\n //////////\n //////////\n\n animationList = [];\n animationList.push(new MyMovingTitle(\"1 1\", 0, -250, 80));\n animationList.push(new MyMovingTitle(\"one one\", 0, -250, 180));\n\n\n optionList = [];\n optionList.push(new PageOption(\"go pageFour\",\n \"You decide to do pageFour.\",\n \"pageFour\"));\n\n optionList.push(new PageOption(\"go pageFive\",\n \"You decide to do pageFive.\",\n \"pageFive\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"one\",animationList,optionList));\n //////////\n //////////\n\n animationList = [];\n animationList.push(new MyMovingTitle(\"22222\", 0, -250, 80));\n animationList.push(new MyMovingTitle(\"two 22 two\", 0, -250, 180));\n\n\n optionList = [];\n optionList.push(new PageOption(\"go pageFour\",\n \"You decide to do pageFour.\",\n \"pageFour\"));\n\n optionList.push(new PageOption(\"go pageFive\",\n \"You decide to do pageFive.\",\n \"pageFive\"));\n _storyPage.push(new PageBasic(\"two\",animationList,optionList));\n //////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyMovingTitle(\"22222\", 0, -250, 80));\n animationList.push(new Ball(\"Ball1\", 0, 50, 180));\n animationList.push(new Ball(\"Ball2\", 0, 250, 280));\n\n\n optionList = [];\n optionList.push(new PageOption(\"one\",\n \"'one' looks exciting.\",\n \"one\"));\n\n optionList.push(new PageOption(\"two\",\n \"Your favorite number is 'two'.\",\n \"two\"));\n\n\n _storyPage.push(new PageBasic(\"three\",animationList,optionList));\n //////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyMovingTitle(\"pageFive\", 0, -250, 80));\n animationList.push(new MyMovingTitle(\"---- pageFive ----\", 0, -250, 180));\n\n optionList = [];\n optionList.push(new PageOption(\"tres\",\n \"You decide to do three.\",\n \"three\"));\n\n optionList.push(new PageOption(\"cuatro\",\n \"You decide to do pageFour.\",\n \"pageFour\"));\n\n _storyPage.push(new PageBasic(\"pageFive\",animationList,optionList));\n //////////\n //////////\n\n\n animationList = [];\n animationList.push(new MyMovingTitle(\"FOUR FOUR\", 0, -250, 80));\n animationList.push(new MyMovingTitle(\"---- page FOUR ----\", 0, -250, 180));\n\n optionList = [];\n //Option(displayName, displayText, nextPageName)\n optionList.push(new PageOption(\"go one\",\n \"You decide to do one.\",\n \"one\"));\n\n optionList.push(new PageOption(\"go two\",\n \"You decide to do two.\",\n \"two\"));\n\n\n\n _storyPage.push(new PageBasic(\"pageFour\",animationList,optionList));\n\n return _storyPage;\n\n }\n \n ////////////////////////////////\n ////////////////////////////////\n function getStoryOranges() //private function\n {\n\n\t\t//alert(\"found getStoryOranges() !!!\");\n\t\t\n _storyPage = [];\n \n var animationList = [];\n animationList.push(new MyTitle(\"Page Not Found\", 0, 30, 80));\n animationList.push(new MyTitle(name, 0, 30, 180));\n \n var theText = \"The requested page was not found in the MyStory.js file. Check the name of your page reference.\";\n animationList.push(new MyScrollingText(theText, 150, 250, 270));\n\n\t\t//animationList.push(new MyMovingTitle(\"tester\", 0, 30, 180));\n\n var optionList = [];\n optionList.push(new PageOption(\"Sorry.\",\n \"Your page was not found.\",\n \"notFound\"));\n\n optionList.push(new PageOption(\"Sorry.\",\n \"Your page was not found.\",\n \"notFound\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"notFound\",animationList,optionList));\n //////////\n //////////\n //alert(\"getStoryOranges() 1\");\n \n animationList = [];\n animationList.push(new MyMovingOrangeTitle(\"Oranges\", 0, -250, 80));\n //animationList.push(new MyMovingTitle(\"(with the Orange Game)\", 0, -250, 180));\n\n\n optionList = [];\n optionList.push(new PageOption(\"head for the orange grove\",\n \"You decide to walk down the path towards the orange grove.\",\n \"pageHeadForOranges\"));\n\n optionList.push(new PageOption(\"take a little nap\",\n \"You are feeling sleepy, so a short nap seems ideal to you. There is a very comfortable rocking chair nearby.\",\n \"pageNapTime\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"start\",animationList,optionList));\n //////////\n //////////\n //alert(\"getStoryOranges() 2\");\n \n animationList = [];\n //animationList.push(new MyMovingTitle(\"Oranges\", 0, -250, 80));\n animationList.push(new Goal_1(\"goal one\", 0, 50, 80));\n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"You are walking down a pleasant road\",\n \t\"lined with beautiful flowers.\",\n \t\"And you arrive at a fork in the road.\",\n \t\"Should you go left or right?\"));\n\n\n optionList = [];\n optionList.push(new PageOption(\"take the left path\",\n \"The left path looks fun and exciting.\",\n \"start\"));\n\n optionList.push(new PageOption(\"take the right path\",\n \"The right path smells like oranges.\",\n \"pageOrangeTree\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageHeadForOranges\",animationList,optionList));\n //////////\n //////////\n //alert(\"getStoryOranges() 3\");\n \n animationList = [];\n animationList.push(new MyTitle(\"Orange Tree\", 0, 50, 80));\n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"Move the oranges just for fun.\",\n \t\"Then move on to the next\",\n \t\"orange tree.\",\n \t\" \"));\n \t\n animationList.push(new Ball( \"Ball1\",0, 350, 180));\n animationList.push(new Ball( \"Ball2\",0, 370, 250));\n animationList.push(new Ball( \"Ball3\",0, 450, 230));\n\n\n\n\n\n optionList = [];\n optionList.push(new PageOption(\"try the next tree\",\n \"There is another tree nearby that looks very interesting.\",\n \"pageOrangeTree2\"));\n\n optionList.push(new PageOption(\"take the right path\",\n \"The right path looks a little dangerous.\",\n \"start\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageOrangeTree\",animationList,optionList));\n //_storyPage.push(new PageDropObjectInBasket(\"pageOrangeTree\",animationList,optionList));\n \n \n //////////\n //////////\n //alert(\"getStoryOranges() 4\");\n \n animationList = [];\n animationList.push(new MyTitle(\"Orange Tree 2\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"Move the oranges to the Basket.\",\n \t\"Then move on to the next\",\n \t\"orange tree.\",\n \t\" \"));\n \t\n \tanimationList.push(new Ball( \"Ball1\",0, 35, 270));\n animationList.push(new Ball( \"Ball2\",0, 135, 270));\n animationList.push(new Ball( \"Ball3\",0, 235, 270));\n\n\t\tanimationList.push(new Basket( \"Basket\",0, 400, 280));\n \n\n\t\t//alert(\"animationList.length \"+animationList.length);\n\n optionList = [];\n optionList.push(new PageOption(\"try the next tree\",\n \"There is another tree nearby that looks very interesting.\",\n \"pageOrangeTree3\"));\n\n optionList.push(new PageOption(\"take the right path\",\n \"The right path looks a little dangerous.\",\n \"start\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageDropObjectInBasket(\"pageOrangeTree2\",animationList,optionList));\n //_storyPage.push(new PageDropObjectInBasket(\"pageOrangeTree2\",animationList,optionList));\n \n \n //////////\n //////////\n //alert(\"getStoryOranges() 5\"); \n \n animationList = [];\n animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"This is the last page.\",\n \t\"You can start over by\",\n \t\"clicking one of the 'start'\",\n \t\"buttons.\"));\n \t\n \t\n animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"start\",\n \"You've had fun and would like to start again.\",\n \"start\"));\n\n optionList.push(new PageOption(\"start\",\n \"You enjoy being in and endless loop, and would really like to start again.\",\n \"start\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageOrangeTree3\",animationList,optionList));\n \n \n //////////\n //////////\n \n //alert(\"end of getStoryOranges() !!!\");\n \n return _storyPage;\n \n \n }\n ////////////////////////////////\n ////////////////////////////////\n \n function getStoryZapper() //private function\n {\n\n _storyPage = [];\n \n \n var animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n animationList.push(new MyTitle(\"Page Not Found\", 0, 30, 80));\n animationList.push(new MyTitle(name, 0, 30, 180));\n \n var theText = \"The requested page was not found in the MyStory.js file. Check the name of your page reference.\";\n animationList.push(new MyScrollingText(theText, 150, 250, 270));\n\n\t\t//animationList.push(new MyMovingTitle(\"tester\", 0, 30, 180));\n\n var optionList = [];\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n optionList.push(new PageOption(\"Sorry.\",\n \"Your story was not found.\",\n \"notFound\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"notFound\",animationList,optionList));\n //////////\n //////////\n\n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyMovingTitle(\"1 1\", 0, -250, 80));\n animationList.push(new MyMovingOrangeTitle(\"Zapper Game Day\", 0, -394, 140));\n\n\n optionList = [];\n optionList.push(new PageOption(\"sleep\",\n _g_pathSideLabel+\"You feel like sleeping a little longer.\",\n \"pageSleep\"));\n\n optionList.push(new PageOption(\"begin the day\",\n _g_pathMainLabel+\"You are ready to begin your day.\",\n \"pageBeginDay\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageTitle\",animationList,optionList));\n \n \n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"After getting dressed you ask Mom if it's ok to\",\n \t\"play your your favorite computer game, Zapper. \",\n \t\"She says that you have to do your \",\n \t\"homework and clean your room first.\"));\n \t\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"do homework\",\n _g_pathMainLabel+\"You go to the living room to work on your homework.\",\n \"pageDoHomework\"));\n\n optionList.push(new PageOption(\"sleep\",\n _g_pathSideLabel+\"You suddenly feel very sleepy.\",\n \"pageSleep\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageBeginDay\",animationList,optionList));\n \n \n\t\t //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"do homework\",\n _g_pathMainLabel+\"Now you start working on your math homework.\",\n \"pageDoMathHomework\"));\n\n optionList.push(new PageOption(\"sleep\",\n _g_pathSideLabel+\"You suddenly feel very sleepy.\",\n \"pageSleep\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageQuiz1(\"pageDoHomework\",animationList,optionList));\n \n //PageQuiz1\n\t\t\n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"Solve three math problems.\",\n \t\" \",\n \t\"Number correct so far:\",\n \t\" \"));\n \t\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"do homework\",\n \"The homework was fun, so you decide to do some more.\",\n \"pageDoHomework\"));\n\n optionList.push(new PageOption(\"clean your room\",\n _g_pathMainLabel+\"You are eager to clean your room, because then you can play Zapper.\",\n \"pageCleanRoom\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageMathProblems(\"pageDoMathHomework\",animationList,optionList));\n \n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackgroundForCleanRoom(\"MyBackgroundForCleanRoom\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 40,\n \t\"Clean your room by putting your \",\n \t\"clothes in the basket. \",\n \t\" \",\n \t\" \"));\n \t\n \t\n \t\n animationList.push(new MyImage( \"shirt\",0, 60+35, 127));\n animationList.push(new MyImage( \"shoes\",0, 60+135, 127));\n animationList.push(new MyImage( \"pants\",0, 60+235, 127));\n \n animationList.push(new Ball( \"shirt\",0, 35, 270));\n animationList.push(new Ball( \"shoe\",0, 135, 270));\n animationList.push(new Ball( \"pants\",0, 235, 270));\n\n\t\tanimationList.push(new Basket( \"Basket\",0, 400, 280));\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"do homework\",\n \"The homework was so fun that you decide to do a little more.\",\n \"pageDoHomework\"));\n\n optionList.push(new PageOption(\"read Zapper instructions\",\n _g_pathMainLabel+\"You decide to read the Zapper instructions before playing.\",\n \"pageReadZapperInstructions\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageCleanRoom(\"pageCleanRoom\",animationList,optionList));\n \n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n animationList.push(new MyTitle(\"Zapper\", 0, 140, 60));\n animationList.push(new MyTitle(\"Instructions\", 0, 80, 140));\n \n \n animationList.push(new MyParagraph( 0, 50, 170,\n \t\" \",\n \t\"You need to Zap the aliens.\",\n \t\"(Use keys a, s, d, and w to move the ship.) \",\n \t\"(Use the space bar to shoot.) \"));\n \t\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"new day\",\n \"Start another day.\",\n \"pageSleep\"));\n\n optionList.push(new PageOption(\"play Zapper\",\n _g_pathMainLabel+\"You decide to play Zapper now.\",\n \"pagePlayZapper\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageReadZapperInstructions\",animationList,optionList));\n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"new day\",\n _g_pathMainLabel+\"Start another day.\",\n \"pageBeginDay2\"));\n\n optionList.push(new PageOption(\"play Zapper\",\n \"You decide to play Zapper again.\",\n \"pagePlayZapper\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PagePlayZapper(\"pagePlayZapper\",animationList,optionList));\n \n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"Sleeping is wonderful.\",\n \t\" \",\n \t\" \",\n \t\" \"));\n \t\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"sleep\",\n \"You go into a deep sleep.\",\n \"pageSleep\"));\n\n optionList.push(new PageOption(\"sleep\",\n _g_pathSideLabel+\"You start dreaming.\",\n \"pageDream1\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageSleep\",animationList,optionList));\n \n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"You dream of playing Zapper.\",\n \t\" \",\n \t\" \",\n \t\" \"));\n \t\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"strange turn\",\n _g_pathSideLabel+\"Your dream takes a strange turn.\",\n \"pageDream2\"));\n\n optionList.push(new PageOption(\"sleep\",\n \"The Zapper dream continues.\",\n \"pageDream1\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageDream1\",animationList,optionList));\n \n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"Strange little boxes start \",\n \t\"flying around your head. \",\n \t\" \",\n \t\" \"));\n \t\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"sleep\",\n \"The dream fades and you drift back into a peaceful sleep.\",\n \"pageSleep\"));\n\n optionList.push(new PageOption(\"begin a new day\",\n _g_pathSideLabel+\"You are ready to begin your day.\",\n \"pageBeginDay\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageDream2\",animationList,optionList));\n \n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"After getting dressed you ask Mom if it's ok to\",\n \t\"play your your favorite computer game, Zapper. \",\n \t\"She says that you have to do your \",\n \t\"homework and clean your room first.\"));\n \t\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"do homework\",\n \"*You go to the living room to work on your homework.\",\n \"pageDoHomework\"));\n\n optionList.push(new PageOption(\"sleep\",\n _g_pathSideLabel+\"You suddenly feel very sleepy.\",\n \"pageSleep\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"dddd\",animationList,optionList));\n \n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"After getting dressed you ask Mom if it's ok to\",\n \t\"play your your favorite computer game, Zapper. \",\n \t\"She says that you have to do your \",\n \t\"homework and clean your room first.\"));\n \t\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"do homework\",\n \"*You go to the living room to work on your homework.\",\n \"pageDoHomework\"));\n\n optionList.push(new PageOption(\"sleep\",\n _g_pathSideLabel+\"You suddenly feel very sleepy.\",\n \"pageSleep\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"fffff\",animationList,optionList));\n \n //////////\n //////////\n \n \n animationList = [];\n animationList.push(new MyBackground(\"MyBackground\", 0, 0, 0));\n \n //animationList.push(new MyTitle(\"Orange Tree 3\", 0, 50, 80));\n \n \n animationList.push(new MyParagraph( 0, 50, 180,\n \t\"After a good night's sleep you ask Mom if it's ok to\",\n \t\"play your your favorite computer game, Zapper. \",\n \t\"She says that you have to do your \",\n \t\"homework and clean your room first.\"));\n \t\n \t\n //animationList.push(new Ball( \"Ball1\",0, 70, 60));\n \n\n optionList = [];\n optionList.push(new PageOption(\"do homework\",\n _g_pathMainLabel+\"You go to the living room to work on your homework.\",\n \"pageDoHomework\"));\n\n optionList.push(new PageOption(\"sleep\",\n _g_pathSideLabel+\"You suddenly feel very sleepy.\",\n \"pageSleep\"));\n\n //alert(\"optionList[0].value \"+optionList[0].value);\n\n _storyPage.push(new PageBasic(\"pageBeginDay2\",animationList,optionList));\n \n \n \n\n\t\treturn _storyPage;\n \t}\n\n\t\n}//end class", "function loadLandingPage() {\n //Clearing the content on the page\n document.body.innerHTML = \"\";\n\n //Adding the static content in the landing page\n document.body.appendChild(createLandingPageContent());\n\n //Manage the music when the speaker is on\n if(speakerImage === 'speaker_on'){\n //If arrived from game over page, sounds may already be initaited\n //Stop the levelUp sound and start game sound in this case\n if(sounds.levelUp != undefined){\n //Stop levelup music\n sounds.levelUp.pause();\n sounds.levelUp.currentTime = 0.0;\n }\n if(sounds.game != undefined){\n //Start game music\n sounds.game.loop = true;\n sounds.game.play();\n }\n }\n //Resetting the score to zero\n score = 0;\n\n //Resetting the timer\n resetTimer();\n}", "function initializeLesson() {\r\n lesson11.init();\r\n animate();\r\n}", "function T1_init () {\n\n var codeBuffer = \"\";\n\n codeBuffer += '<!DOCTYPE html>';\n codeBuffer += '<html lang=\"en\">';\n codeBuffer += '<head>';\n codeBuffer += '<title>Generated Site</title>';\n codeBuffer += '<meta charset=\"UTF-8\">';\n codeBuffer += '<link rel=\"stylesheet\" href=\"layout.css\" type=\"text/css\">';\n codeBuffer += '<link rel=\"stylesheet\" href=\"http://htmlforge.com/Generated/template-1/layout.css\" type=\"text/css\">';\n codeBuffer += '<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css\" type=\"text/css\">';\n codeBuffer += '</head>';\n codeBuffer += '<body>';\n\n return codeBuffer;\n}", "function displayChapter(chapter, idChapter) {\n return function() {\n initDisplay();\n\t\n /**\n * Changing the style of the curretn chapter in summary\n\t \t */\n for (var i = 0; i < chaptersListArray.length - 1; i++) {\n\t document.getElementById(\"chapter\" + i).style.background = \"#120D16\";\n\t document.getElementById(\"chapter\" + i).firstChild.firstChild.style.color = \"lightblue\";\n\t}\n document.getElementById(\"chapter\" + idChapter).style.background = \"#52B6CC\";\n\tdocument.getElementById(\"chapter\" + idChapter).firstChild.firstChild.style.color = \"#120D16\";\n\t\n\tcurrentChapter = idChapter;\n\tisNotFirstPage = false;\n document.getElementById('chaptersList').style.display = \"none\";\n\tdocument.getElementById('containerChapter').style.display = \"block\";\n\t\n\t\t/**\n * Apply parameters (brightness...)\n\t \t */\n var parameters = readJson('parameters');\n\n if (parameters === null) {\n initializeParameter();\n }\n \n applyParameters();\n\n document.getElementById('previous').style.display = 'block';\n document.getElementById('next').style.display = 'block';\n\n\t\t/** \n * Re-Initialize 'paragraphs'\n\t \t */\n var iframe = document.getElementById(\"completeChapter\");\n iframe.contentWindow.document.body.innerHTML = \"\"; \n var paragraphs = document.getElementById('paragraphs');\n while (paragraphs.firstChild) {\n paragraphs.removeChild(paragraphs.firstChild);\n }\n\n document.getElementById(\"paragraphs\").style.display = 'block';\n document.getElementById(\"paragraphs\").addEventListener(\"click\", displayToolbar, false); \n\n iframe.contentWindow.document.body.innerHTML += chapter; \n\n var temp = document.getElementById('completeChapter').contentDocument;\n var ael = temp.getElementsByTagName(\"p\");\n\n for (var i = 0, c = ael.length ; i < c ; i++) {\t\t\n if (i === 0) { //First page of the chapter so display the title\n var title = temp.getElementsByTagName(\"h1\");\n var currentParagraph = title[0].cloneNode(true);\n var paragraph = document.createElement(\"h1\");\n paragraph.id = \"title\" + i;\n paragraph.innerHTML = currentParagraph.innerHTML;\n document.getElementById(\"paragraphs\").appendChild(paragraph);\n }\n\n var currentParagraph = ael[i].cloneNode(true);\n var paragraph = document.createElement(\"p\");\n paragraph.id = \"paragraph\" + i;\n paragraph.innerHTML = currentParagraph.innerHTML;\n document.getElementById(\"paragraphs\").appendChild(paragraph);\n\n if (paragraph instanceof Element) {\n var p = elementInViewport(paragraph);\n if (!p) {\n lastParagraph = i;\n break;\n }\n }\n }\n\tsaveLastPageRead2(currentChapterTitle, currentChapter, -3); //-3 because the last page read is the first page of the chapter\n document.getElementById('toolbar').style.display = \"block\";\n }\n}", "async function main() {\n\t// Have to wait for this to finish since commonMain loads the STORE and we need it to populate the page\n\tawait commonMain();\n\n\tSTORE.entriesPerPage = ENTRIES_PER_PAGE;\n\tSTORE.pagePrefix = 'projects';\n\tSTORE.displayed = [];\n\tSTORE.projects.forEach( p => p.id = cuid() );\n\n\t$('.menu').find('.projects-link').addClass('current-page-link');\n\t$(ownPageLinkHandler);\n\n\tdisplayPage( 0 );\n\t$(galleryHandler);\n\t$(galleryNextHandler);\n\t$(galleryPrevHandler);\n\t$(gallerySwipeLeftHander);\n\t$(gallerySwipeRightHander);\n\t$(gotoPageHandler);\n\t// Search field handlers\n\t$(clearSearchHandler);\n\t$(searchHandler);\n\t$(searchSubmitHandler);\n\n}", "function setDialogTextOfSpread() {\r var newCSInterface = new CSInterface();\r var allText = jsyaml.load($(\"textarea#scriptyaml\").val()) // have to use .val instead of .text for textareas\r newCSInterface.evalScript('getCurrentSpreadPages()', function (result) {\r var currentPages = JSON.parse(result);\r $(\"textarea#scriptyaml\").val(currentPages);\r for (var i=0; i < currentPages.length; i++) {\r for (var frame in allText[currentPages[i]]) {\r if (allText[currentPages[i]].hasOwnProperty(frame)) {\r setContentsOfFrame(currentPages[i], frame, allText[currentPages[i]][frame])\r }\r }\r }\r })\r}\r\r//setInterval( function () {\r// getDialogText();\r// }, 5000\r//)", "function generateStartPage() {\n $('.js-main').html(\n `<section id=\"start\">\n <div class=\"page\">\n <p>\n Identify as many creatures by their descriptions as you can!\n </p>\n <div id=\"start-button\">\n <button id=\"js-start\">Begin Quiz</button>\n </div>\n </div>\n </section>`)\n //console.log('generateStartPage ran')\n}", "function openStyleEditor() {\n let style = loadedStory.style;\n linkInputToProperty(style, \"title_font\", $(\"#style-title-font\"));\n linkInputToProperty(style, \"title_font_color\", $(\"#style-title-color\"));\n \n linkInputToProperty(style, \"text_font\", $(\"#style-text-font\"));\n linkInputToProperty(style, \"text_font_color\", $(\"#style-text-color\"));\n \n linkInputToProperty(style, \"activity_area_color\", $(\"#style-main-color\"));\n linkInputToProperty(style, \"activity_area_border\", $(\"#style-main-border-color\"));\n linkInputToProperty(style, \"activity_area_opacity\", $(\"#style-main-opacity\"));\n \n linkInputToProperty(style, \"buttons_color\", $(\"#style-buttons-color\"));\n linkInputToProperty(style, \"buttons_text_color\", $(\"#style-buttons-text-color\"));\n \n linkInputToProperty(style, \"chat_theme\", $(\"#style-chat-theme\"));\n \n //Background\n linkInputToProperty(style, \"background_color\", $(\"#style-background-color\"));\n \n $(\"#style-background-color-div\").toggle(!style.use_background_image);\n $(\"#style-background-image-div\").toggle(style.use_background_image);\n \n let background_checkbox = $(\"#style-has-background\");\n background_checkbox[0].checked = style.use_background_image;\n background_checkbox.off();\n background_checkbox.on(\"change\", (e) => {\n editorDirty = true;\n style.use_background_image = background_checkbox[0].checked;\n $(\"#style-background-color-div\").toggle(!style.use_background_image);\n $(\"#style-background-image-div\").toggle(style.use_background_image);\n });\n \n //Upload of background image\n let upload = $(\"#style-background-upload\");\n upload.off();\n upload[0].value = null; //clear the current value of the input\n upload.on(\"change\", () => {\n editorDirty = true;\n let image_url = URL.createObjectURL(upload[0].files[0]);\n uploadFileAndStoreURL(upload[0].files[0], style, \"background_image\", (url) => {\n updateStylePreview(style);\n });\n });\n \n $(\"#style-modal\").find(\"select, input\").on(\"change\", () => {\n updateStylePreview(style);\n });\n \n //make sure color and range inputs update also while dragging\n $(\"#style-modal\").find('input[type=\"color\"], input[type=\"range\"]').on(\"input\", (e) => {\n $(e.target).change();\n });\n \n updateStylePreview(style);\n}", "function loadStories() {\n const req = require.context('../stories', true, /.stories.(js|ts|tsx)$/)\n req.keys().forEach(filename => req(filename))\n}", "function startTutorial() {\n\t// May or may not be necessary\n\tgameType = 'tutorial';\n\tstartGame();\n\ttutorialInstructionIndex = -1;\n\tcallbackAfterMessage = nextTutorialMessage;\n\tnextTutorialMessage();\n}", "function startIntro(){\n\tvar intro = introJs();\n\t\tintro.setOptions({\n\t\t\tsteps: [\n\t\t\t\t{\n\t\t\t\t\tintro: \"Welcome! This webpage will help you explore unemployment data in different areas of Münster.\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#settingsBox',\n\t\t\t\t\tintro: \"Use this sidebar to customize the data that is displayed on the map.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#yearSection',\n\t\t\t\t\tintro: \"You can move this slider to get data from 2010 to 2014.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#criteriaSection',\n\t\t\t\t\tintro: \"Choose a criterion to select a specific group of unemployed.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#boundarySection',\n\t\t\t\t\tintro: \"You can also switch to districts to get finer granularity.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#legendBox',\n\t\t\t\t\tintro: \"This legend will tell how many unemployed are represented by each color.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#map',\n\t\t\t\t\tintro: \"Check the map to view your selected data! You can also click on all boundaries. A popup will show you a timeline to compare data of recent years and links to additional information.\",\n\t\t\t\t\tposition: 'left'\n\t\t\t\t}\n\t\t\t]\n\t\t});\n\n\t\tintro.start();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw (visible) content items
function drawContentItems() { // Get current range var range = Canvas.Timescale.getRange(); drawContentItemsLoop(_contentItems, range, true); drawContentItemsLoop(_contentItems, range, false); }
[ "function drawContentItem(range, contentItem) {\r\n // Check if content item visible in current range\r\n if (contentItem.getBeginDate() >= range.begin || contentItem.getEndDate() <= range.end) {\r\n contentItem.draw();\r\n }\r\n }", "draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }", "function viewItems () {\n\t//location variables for each bin \n\tlet landfillX = 900;\n\tlet landfillY = 160;\n\tlet compostX = 400;\n\tlet compostY = 160;\n\tlet recycleX = 400;\n\tlet recycleY = 450;\n\n\t//bin indexes used for sorting and organizing the layout of the bins. \n\tlet landfillIndex = 0;\n\tlet recycleIndex = 0;\n\tlet compostIndex = 0;\n\n\tfor ( let i = 0; i < itemLocations.length; i++ ) {\n\t\tif (itemLocations[i] === \"Landfill\") {\n\t\t\tif (landfillIndex === 0) {\n\t\t\t\ttext(shuffledItems[i], landfillX, landfillY);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttext(shuffledItems[i], landfillX, landfillY + (landfillIndex * 18));\n\t\t\t}\n\t\t\tlandfillIndex = landfillIndex +1;\n\t\t}\n\t\telse if (itemLocations[i] === \"Recycle\") {\n\t\t\tif (recycleIndex === 0) {\n\t\t\t\ttext(shuffledItems[i], recycleX, recycleY);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttext(shuffledItems[i], recycleX, recycleY + (recycleIndex * 18));\n\t\t\t}\n\t\t\trecycleIndex = recycleIndex +1;\n\t\t}\n\t\telse if (itemLocations[i] === \"Compost\") {\n\t\t\tif (compostIndex === 0) {\n\t\t\t\ttext(shuffledItems[i], compostX, compostY);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttext(shuffledItems[i], compostX, compostY + (compostIndex * 18));\n\t\t\t}\n\t\t\tcompostIndex = compostIndex +1;\n\t\t}\n\t}\n}", "function drawGridContent(){\n for( var i =0; i<=cw/100; i++){\n for(var j=0; j<=ch/100; j++){\n var cI = i.toString()+'-'+j.toString();\n if( cI in gridContent){\n\tif(gridContent[cI]>=0){\n\t if( pickThis == cI){\n\t /* Mouse motion: puzzle piece follows mouse coordiantes: */\n\t drawPiece(mx, my, 100,100, cI==selectedItem, cI);\n\t\t\t\t//0 + 100*i,21 + 100*j, 100,100);\n\t }else{\n\t //Puzzle piece is static: \n\t drawPiece(0 + 100*i,21 + 100*j, 100,100, cI==selectedItem, cI);\n\t }\n\t //draw(mx, my, 100, 100);\n\t}\n }\n }\n }\n}", "function addContent() {\n content.style.visibility = \"visible\";\n}", "function bbedit_components_draw_menu() {}", "function makeVisible() {\r\n for (var i = 0; i < items.length; i++) { \r\n if (isElementInViewport(items[i])) {\r\n items[i].classList.add(\"in-view\");\r\n }\r\n }\r\n }", "function drawEditionElements() {\n if (editionCheckbox.checked) {\n // Draw points\n for (var ptIndex = 0; ptIndex < customPoints.length; ptIndex++) {\n ctx.fillStyle = \"#f00\";\n ctx.fillRect(customPoints[ptIndex].x - (pointWidth / 2), customPoints[ptIndex].y - (pointHeight / 2), pointWidth, pointHeight);\n }\n // Draw lines\n if (polygonInConstruction.length > 0) {\n for (var i = 0; i < polygonInConstruction.length; i++) {\n point1 = findPointForId(polygonInConstruction[i][0]);\n point2 = findPointForId(polygonInConstruction[i][1]);\n ctx.strokeStyle = \"#0f0\";\n ctx.beginPath();\n ctx.moveTo(point1.x,point1.y);\n ctx.lineTo(point2.x, point2.y);\n ctx.stroke();\n }\n }\n // Draw polygons\n if (customPolygons.length > 0) {\n for (var i = 0; i < customPolygons.length; i++) {\n thePoly = []\n for (var j = 0; j < customPolygons[i].length; j++) {\n thePoint = findPointForId(customPolygons[i][j]);\n thePoly.push({x: thePoint.x, y: thePoint.y})\n }\n drawPolygon(thePoly);\n }\n }\n }\n}", "display() {\n this.draw(this.points.length);\n }", "display() {\n //set the color\n stroke(this.element*255) ;\n //draw the point\n point(this.identity.x,this.identity.y)\n }", "function extendedDraw() {\r\n this._drawBackground()\r\n this._drawHeader()\r\n originalDraw()\r\n }", "function handleClickOnContentItemWithChildren(contentItem) {\r\n // Show loader\r\n Canvas.WindowManager.showLoader(true);\r\n\r\n // Get children\r\n Canvas.ContentItemService.findContentItemsByParentContent(contentItem);\r\n }", "draw() {\n\t\tthis.components.forEach( component => component.draw() );\n\t}", "display() {\n push();\n fill(255,0,0);\n ellipse(this.x, this.y, this.size);\n pop();\n // if (x < 0 || x > width || y < 0 || y > height) {\n // var removed = obstacles.splice(this.index, 1);\n // }\n }", "display() {\n this.scene.pushMatrix();\n this.spritesheet.activateShader();\n\n this.scene.translate(this.center_shift, 0, 0)\n\n for (let i = 0; i < this.text.length; i++) {\n this.spritesheet.activateCellp(this.getCharacterPosition(this.text.charAt(i)));\n this.rectangle.display();\n this.scene.translate(1, 0, 0);\n }\n\n this.scene.setActiveShaderSimple(this.scene.defaultShader);\n this.scene.popMatrix();\n }", "draw(){\n\n for(let i=0; i<this.belt.length;i++){\n this.belt[i].draw();\n }\n }", "draw() {\n\t\tconst output = this.buffer.join(\",\");\n\t\tthis.style.applyCSS(output);\n\t}", "showContent () {\n this.loadingWrapper.style.display = 'none'\n this.canvas.style.display = 'block'\n }", "draw() {\n this.ghosts.forEach((ghost) => ghost.draw());\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Response to client asking to reveal fastest finger results.
showHostRevealFastestFingerResults(socket, data) { this.currentSocketEvent = 'showHostRevealFastestFingerResults'; Logger.logInfo(this.currentSocketEvent); // Nothing needs to be done here, as fastest finger grading happens on the fly. ServerState will // pass the results to the client. this.playSoundEffect(Audio.Sources.FASTEST_FINGER_WHO_WAS_CORRECT); // Check if at least one player got it all the way right. If nobody got it right, ask again. if (this.serverState.fastestFingerQuestion.allPlayersIncorrect()) { this.serverState.setShowHostStepDialog(this._getOneChoiceHostStepDialog({ nextSocketEvent: 'showHostCueFastestFingerQuestion', hostButtonMessage: LocalizedStrings.REASK_FASTEST_FINGER, aiTimeout: 3000 })); } else { this.serverState.setShowHostStepDialog(this._getOneChoiceHostStepDialog({ nextSocketEvent: 'showHostAcceptHotSeatPlayer', hostButtonMessage: LocalizedStrings.ACCEPT_HOT_SEAT_PLAYER, aiTimeout: 3000 })); } this._updateGame(); }
[ "showHostRevealFastestFingerQuestionChoices(socket, data) {\n this.currentSocketEvent = 'showHostRevealFastestFingerQuestionChoices';\n Logger.logInfo(this.currentSocketEvent);\n\n this.serverState.fastestFingerQuestion.revealAllChoices();\n this.serverState.fastestFingerQuestion.markStartTime();\n this.playMusic(Audio.Sources.FASTEST_FINGER_ANSWERING);\n this._updateGame();\n }", "showHostCueFastestFingerAnswerRevealAudio(socket, data) {\n this.currentSocketEvent = 'showHostCueFastestFingerAnswerRevealAudio';\n Logger.logInfo(this.currentSocketEvent);\n\n this.playMusic(Audio.Sources.FASTEST_FINGER_CORRECT_ORDER);\n\n // Human host will control flow, or 2.5 seconds until question text is shown\n this.serverState.setShowHostStepDialog(this._getOneChoiceHostStepDialog({\n nextSocketEvent: 'showHostRevealFastestFingerAnswer',\n hostButtonMessage: LocalizedStrings.REVEAL_FASTEST_FINGER_ANSWER,\n aiTimeout: 2500\n }));\n this._updateGame();\n }", "showHostShowFastestFingerQuestionText(socket, data) {\n this.currentSocketEvent = 'showHostShowFastestFingerQuestionText';\n Logger.logInfo(this.currentSocketEvent);\n\n this.serverState.fastestFingerQuestion = this.fastestFingerSession.getNewQuestion();\n\n // Human host will control flow, or 8 seconds will pass until choices are revealed\n this.serverState.setShowHostStepDialog(this._getOneChoiceHostStepDialog({\n nextSocketEvent: 'showHostCueFastestFingerThreeStrikes',\n hostButtonMessage: LocalizedStrings.REVEAL_FASTEST_FINGER_CHOICE,\n aiTimeout: 8000\n }));\n this._updateGame();\n }", "fastestFingerTimeUp(socket, data) {\n this.currentSocketEvent = 'fastestFingerTimeUp';\n Logger.logInfo(this.currentSocketEvent);\n\n // Even if this was triggered by the timeout expiring, we will be safe and clear the timeout, as\n // it may have been triggered by everyone answering.\n clearTimeout(this.currentForcedTimer);\n this.playSoundEffect(Audio.Sources.FASTEST_FINGER_OUT_OF_TIME,\n /*volume=*/1.0,\n /*stopPreviousSounds=*/true);\n\n // Human host will control flow, or 8 seconds will pass until choices are revealed\n this.serverState.setShowHostStepDialog(this._getOneChoiceHostStepDialog({\n nextSocketEvent: 'showHostCueFastestFingerAnswerRevealAudio',\n hostButtonMessage: LocalizedStrings.CUE_FASTEST_FINGER_ANSWER_REVEAL_AUDIO,\n aiTimeout: 2500\n }));\n this._updateGame();\n }", "showHostShowFastestFingerRules(socket, data) {\n this.currentSocketEvent = 'showHostShowFastestFingerRules';\n Logger.logInfo(this.currentSocketEvent);\n\n this.serverState.showHostInfoText = LocalizedStrings.SHOW_HOST_FASTEST_FINGER_RULES;\n this.serverState.contestantInfoText = LocalizedStrings.CONTESTANT_FASTEST_FINGER_RULES;\n this.playMusic(Audio.Sources.FASTEST_FINGER_RULES);\n\n // Human host will control flow, or 5 seconds are allotted for the rules to be shown\n this.serverState.setShowHostStepDialog(this._getOneChoiceHostStepDialog({\n nextSocketEvent: 'showHostCueFastestFingerQuestion',\n hostButtonMessage: LocalizedStrings.CUE_FASTEST_FINGER_MUSIC,\n aiTimeout: 8000\n }));\n this._updateGame();\n }", "showHostCueFastestFingerThreeStrikes(socket, data) {\n this.currentSocketEvent = 'showHostCueFastestFingerThreeStrikes';\n Logger.logInfo(this.currentSocketEvent);\n\n // First we cue the audio with no possible host step action.\n this.serverState.setShowHostStepDialog(undefined);\n this.playSoundEffect(Audio.Sources.FASTEST_FINGER_THREE_STRIKES,\n /*volume=*/1.0,\n /*stopPreviousSounds=*/true);\n this._updateGame();\n\n // After a small waiting period, we reveal all choices.\n this.currentForcedTimer = setTimeout(() => {\n this.showHostRevealFastestFingerQuestionChoices(data);\n }, /*timeoutMs*/2200);\n }", "finishAskTheAudience() {\n this.serverState.askTheAudience.populateAllAnswerBuckets();\n this.playSoundEffect(Audio.Sources.ASK_THE_AUDIENCE_END);\n\n // Update game is called first to make sure ask the audience end audio cue plays.\n this._updateGame();\n this.showHostRevealHotSeatChoice();\n }", "function showResult(isCorrect) {\r\n if (isCorrect) \r\n {\r\n correctAnswerScreen();\r\n currentScore(); \r\n }\r\n else \r\n {\r\n inCorrectAnswerScreen();\r\n \r\n } \r\n}", "function user_question_view(ref_id){\n var reply_type = \"json\";\n var vars = {};\n if (ref_id == '' || ref_id == undefined){\n vars.url = myhost+'/view/question_all/';\n vars.content = \"question\";\n } else {\n vars.url = myhost+'/view/question_replys/';\n vars.content = \"replys\";\n }\n vars.ref_id = ref_id;\n global.user_agent\n .get(vars.url)\n .set('Content-Type', 'application/json')\n .query({m_id:ref_id, reply_type:reply_type})\n .end(function(err, res){\n if (err) {\n myutil.error(\"== user_question_view ==\", err);\n return\n }\n if (res.ok){\n myutil.debug(\"== user_question_view ==\");\n var body = res.text;\n //myutil.debug(res.body, res.text);\n //user_question_view_not_leave(body, vars);\n var r = JSON.parse(body);\n var data = r.data;\n var i = Math.floor(Math.random()*data.length);\n var msg = data[i];\n vars.msg = msg;\n if (vars.msg == undefined) {vars.msg = {}; vars.msg._id= '';}\n vars.current_status = \"user_question_view\";\n decision(vars);\n } else {\n myutil.error(\"== user_question_view ==\", err, res.status);\n }\n });\n}", "function respond() {\n // Generating a random negative word from the array\n let negativeWord = negatives[Math.floor(Math.random() * negatives.length)];\n // Generating a random response from the array\n let randomReason = reasons[Math.floor(Math.random() * reasons.length)];\n\n // Pairing random negative word with reason\n // and displaying it then fading it out after delay\n $response.text(negativeWord + randomReason);\n $response.show().delay(RESPONSE_FADEOUT_DELAY).fadeOut(RESPONSE_FADEOUT_DURATION);\n\n // When user clicks button asking face if it is happy, display image with tear\n // because they realize how sad they truly are\n $faceImg.attr('src', 'assets/images/sad-face-1.png');\n\n // Also play a random crying sound from the array to show how truly sad they are\n let randomCryingSound = cryingSounds[Math.floor(Math.random() * cryingSounds.length)];\n randomCryingSound.play();\n}", "function responseTooQuickly(rt, loggvar){\n if(rt < dataService.timerOptions().tooFast){\n clearInterval(loggvar);\n $('#header').append(`<h2 style=\"position: absolute; left: 33%\" id=\"infoMessage\">${dataService.checkAnswer().quickMessage}</h2>`);\n }\n}", "function fingerChoice() {\n choiceDialog(0, 0, ghostDialog, 14000);\n}", "function displayHint() {\n tHint = setTimeout(function () {\n $(\"#hint-content\").addClass(\"hide\");\n }, 3750);\n }", "function showPopupFlap(action,resArr){\n\tsetTimeout(function(){\n\t\t$.mobile.changePage($(\"#flapPopupDiv\"),{\n\t\t\ttransition: \"pop\",\n\t\t\tchangeHash : false\n\t\t});\n\t\t$('.numbersOnly').keyup(function () { \n\t\t\tthis.value = this.value.replace(/[^0-9\\.]/g,'');\n\t\t});\n\n\t},1500);\n\n\t$(document).on(\"click\",\"#okFlap\", function(){\n\t\tvar count = $(\"#flapCount\").val();\n\t\tvar delay = $(\"#flapDelay\").val();\n\t\tlineConnectionQuery(action,resArr,count,delay);\n\t});\n}", "function progressPatient(queue) {\n setShow('send');\n }", "function displayAnswer() {\n $('.flashcard').toggleClass('flipped');\n responsiveVoice.speak(currentWord.foreignWord, speechLanguage[$('#toLanguage').val()]);\n}", "async function cardDisplayReactions (message, sentMsg, cardEmbed, cardDoc) {\n\n\tlet fuseConfirmState = false;\n\n\tlet collector = sentMsg.createReactionCollector(\n\t\t(reaction, user) => (reaction.emoji.name == favEmote || reaction.emoji.name == unFavEmote || reaction.emoji.name == fuseEmote || reaction.emoji.name == confirmEmote || reaction.emoji.name == cancelEmote) && user.id === message.author.id, {time:30000}\n\t)\n\tcollector.on('collect', r=> {\n\t\tif (fuseConfirmState === true) {\n\t\t\tif (r.emoji.name == confirmEmote) {\n\t\t\t\tcollector.stop(\"accept\")\n\t\t\t\tsentMsg.reactions.removeAll()\n\t\t\t\tsentMsg.edit(\"`----Fusing----`\")\n\t\t\t\tlet oldLevel = cardDoc.level;\n\t\t\t\tglobal.cardmanager.fuseCards(message, message.author, cardDoc, (fusedCard, numFused) => {\n\t\t\t\t\tsetTimeout(async function() {\n\t\t\t\t\t\tsentMsg.edit(`Fuse result! ${numFused} card(s) consumed. ${Math.floor(fusedCard.level)-Math.floor(oldLevel)} level(s) gained.`, {embed:utils.cardEmbed(fusedCard)})\n\t\t\t\t\t}, 1500)\n\t\t\t\t})\n\t\t\t} else if (r.emoji.name == cancelEmote) {\n\t\t\t\tfuseConfirmState == false;\n\t\t\t\tsentMsg.edit(\"Fuse cancelled.\", {embed:utils.cardEmbed(cardDoc)})\n\t\t\t}\n\t\t} else if (r.emoji.name == favEmote) {\n\t\t\tglobal.cardmanager.favoriteCard(sentMsg, cardDoc)\n\t\t\tcardDoc.favorite = true;\n\t\t\tsentMsg.edit(\"You have just favorited this card. It will not be consumed for fusion.\", {embed:utils.cardEmbed(cardDoc)})\n\t\t} else if (r.emoji.name == unFavEmote) {\n\t\t\tglobal.cardmanager.unFavoriteCard(sentMsg, cardDoc)\n\t\t\tcardDoc.favorite = false;\n\t\t\tsentMsg.edit(\"You have unfavorited this card. It may be consumed in fusion.\", {embed:utils.cardEmbed(cardDoc)})\n\t\t} else if (r.emoji.name == fuseEmote) {\n\t\t\tsentMsg.edit(\"You have selected the option to FUSE. Warning- this will consume any duplicate cards of this type that you have not favorited! Confirm?\", {embed:utils.cardEmbed(cardDoc)}).catch((err) => {\n\t\t\t\tmessage.channel.send({embed:utils.embed(`malfunction`,`Something went wrong! \\`\\`\\`${err}\\`\\`\\``, \"RED\")}) \n\t\t\t})\n\t\t\tfuseConfirmState = true;\n\t\t\tsentMsg.react(confirmEmote).then(\n\t\t\tsetTimeout(function() {\n\t\t\t\tsentMsg.react(cancelEmote)\n\t\t\t}, 500))\n\t\t}\n\t})\n\n\tsentMsg.react(favEmote).catch()\n\tawait sleep(500)\n\tsentMsg.react(unFavEmote).catch()\n\tawait sleep(500)\n\tsentMsg.react(fuseEmote).catch()\n}", "function sendNextProblemInputResponse (arg) {\n // send an InputResponse to the server with NO. callback fn should be processNextProblemResult\n servletGet(\"InputResponseNextProblemIntervention\",\"&probElapsedTime=\"+globals.probElapsedTime + \"&destination=\"+globals.destinationInterventionSelector + arg,\n processNextProblemResult)\n}", "function user_related_question_view(ref_id){\n var reply_type = \"json\";\n var vars = {};\n if (ref_id == '' || ref_id == undefined){\n vars.url = myhost+'/view/user_question_all/';\n vars.content = \"question\";\n } else {\n vars.url = myhost+'/view/user_question_replys/';\n vars.content = \"replys\";\n }\n vars.ref_id = ref_id;\n global.user_agent\n .get(vars.url)\n .set('Content-Type', 'application/json')\n .query({m_id:ref_id, reply_type:reply_type})\n .end(function(err, res){\n if (err) {\n myutil.error(\"== user_related_question_view ==\", err);\n return\n }\n if (res.ok){\n myutil.debug(\"== user_related_question_view ==\");\n var body = res.text;\n //myutil.debug(res.body, res.text);\n //user_related_question_view_not_leave(body, vars);\n var r = JSON.parse(body);\n var data = r.data;\n var i = Math.floor(Math.random()*data.length);\n myutil.info(data.length, i);\n var msg = data[i];// ref_id = msg._id somtime\n vars.msg = msg;\n if (vars.msg == undefined) {vars.msg = {}; vars.msg._id= '';}\n vars.current_status = \"user_related_question_view\";\n decision(vars);\n } else {\n myutil.error(\"== user_related_question_view ==\", err, res.status);\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes the selected items from the invoice (submits the entire page)
function removeItems() { if (checklocked() == false) { if ((remove_trade.length || remove_sale.length || remove_return.length) && confirm('Are you SURE you want to remove these items from the invoice?')) { var frm = document.remfrm; frm.remove_sale.value = remove_sale; frm.remove_trade.value = remove_trade; frm.remove_return.value = remove_return; frm.submit(); } } }
[ "function clearSelection() {\n currentPizza = undefined;\n $('input[name=\"e-item\"]').prop('checked', false);\n $('input[name=\"psize\"]').prop('checked', false);\n $(\".lists-wrapper\").hide();\n\n currentBeverage = undefined;\n $('input[name=\"bsize\"]').prop('checked', false);\n $(\".beverage-size-list\").hide();\n\n currentOrder = undefined;\n\n }", "function deselectItems() {\n $j(\"#open_item\").addClass(\"disabled\");\n $j(\"#go_to_item_location\").addClass(\"disabled\");\n $j(\".item.selected\").removeClass(\"selected\");\n }", "function HTL_removeIssues() {\n var selectedLocalIDs = [];\n for (var i = 0; i < issueRefs.length; i++) {\n issueRef = issueRefs[i]['project_name']+':'+issueRefs[i]['id'];\n var checkbox = document.getElementById('cb_' + issueRef);\n if (checkbox && checkbox.checked) {\n selectedLocalIDs.push(issueRef);\n }\n }\n\n if (selectedLocalIDs.length > 0) {\n if (!confirm('Remove all selected issues?')) {\n return;\n }\n var selectedLocalIDString = selectedLocalIDs.join(',');\n $('bulk_remove_local_ids').value = selectedLocalIDString;\n $('bulk_remove_value').value = 'true';\n setCurrentColSpec();\n\n var form = $('bulkremoveissues');\n form.submit();\n } else {\n alert('Please select some issues to remove');\n }\n}", "function removeOldFileSelections(){\n\t\tvar filenames = document.getElementsByClassName(\"choose-file\");\n\t\tfor (var i = 0; i < filenames.length; ++i){\n\t\t\tfilenames[i].value = \"\";\n\t\t}\n\t}", "function removerItem(index) {\n const finded = selecionados.indexOf(index);\n if (finded !== -1) {\n selecionados.splice(finded, 1)\n }\n if (selecionados.length === 0) excluirBtn.disabled = true\n}", "function deleteStock() {\n rows = getSelectedRowBoxes();\n\n for (var i=rows.length - 1; i >= 0; i--) {\n var prodId = rows[i].parentNode.parentNode.id;\n delete products[prodId];\n products.splice(prodId, 1);\n }\n saveData();\n displayInventory();\n}", "removeAll() {\n return spPost(ViewFields(this, \"removeallviewfields\"));\n }", "function deselectAll() {\n setSelectedEmails([]);\n }", "function clearPaymentMethod() {\n\t$(\".selectable\").each(function(){\n\t\t$(this).attr(\"checked\", false);\t\t\t\n\t\tisPaymentMethodSelected = false;\n\t\tpaymentProfileId = \"0\";\n\t});\t\n}", "function deselectAll() {\n selected = 0;\n\n let selectedCards = qsa(\".selected\");\n let i;\n for (i = 0; i < selectedCards.length; i++) {\n selectedCards[i].classList.remove(\"selected\");\n }\n }", "RemoveSelectedQfromAll(sel){\n while(sel.length>0){\n var x=sel.pop();\n if(this.questypes.indexOf(x)!==-1)\n this.questypes.splice(this.questypes.indexOf(x),1);\n }\n }", "cleanCheckboxSelection() {\n this.context.state.ingredients.forEach((igd) => {\n if(document.getElementById('igdID_' + igd.id) != null) {\n const checkbox = document.getElementById('igdID_' + igd.id);\n if(checkbox.checked) {\n checkbox.checked = false;\n }\n }\n });\n this.context.disableAllPreviewImg();\n }", "function cleanSelection() {\n $scope.presets = undefined;\n $scope.selectedCategory = undefined;\n $scope.selectedPreset = undefined;\n }", "function deselectAllLines(collectionId) {\n jQuery(\"#\" + collectionId + \" input:checkbox.kr-select-line\").attr('checked', false);\n setMultivalueLookupReturnButton(jQuery(\"#\" + collectionId + \" input:checkbox.kr-select-line\"));\n}", "function CtrlDeleteAllFieldsInOneCoupon(){\n addNewCouponFlag = 0; // we are not allowed to add new coupon\n UICtrl.deleteAllFieldsInOneCoupon();\n UICtrl.fieldsClickable();\n UICtrl.hideNextCouponButton();\n // jackpotCtrl.removeCoupon((UICtrl.getExpandedCoupon()).id); //we shoulnd call it here. ! instead , it should be called when click goBack button. in that way we are 100% sure the user wanted to delete\n checkedFields = 0;\n }", "removeNeededItems() {\n this.neededItems = [];\n }", "function rmEnquiry() {\n\t\t\tvm.enquiry.enquiries.pop();\n\t\t}", "unselectItem(item)\n {\n delete this._selectedItems[item.id];\n item.setHighlight(false);\n }", "function eliminakey(obj) {\r\n \tif(window.event.keyCode == 46){\r\n\t \tfor(i=0;i<obj.length;i++)\r\n\t\t{\t\r\n\t\t\tif(obj.options[i].selected)\r\n\t\t\t {\r\n\t\t\t\tobj.options[i] = null;\r\n\t\t\t\tobj.length-1;\r\n\t\t\t\ti--;\r\n\t\t\t }\t\r\n\t\t}\r\n\t}\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handler for selecting a phrase in the original text
function selectPhrase(editArea) { var startPos = editArea.selectionStart; var endPos = editArea.selectionEnd; var selPhrase = editArea.value.substring(startPos, endPos); var _phrase = document.getElementById('phrase'); if (_phrase) { _phrase.value = selPhrase; } }
[ "phrase(phrase) {\n for (let map of this.facet(EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase))\n return map[phrase];\n return phrase;\n }", "phrase(phrase) {\n for (let map of this.facet(dist_EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase))\n return map[phrase];\n return phrase;\n }", "function OneWordHelper_highlightPhrase(mainID) {\n for(var i = 0; i < this.locs.length; i++)\n for(var j = 0; j < this.phraseLength; j++)\n utl.id( 'w-'+(this.locs[i]+j) ).className = 'hl-phrase'\n this.showBar(this.locs, mainID)\n} // _highlightPhrase function", "function switchText_cb(new_string)\r\n{\r\n\twith(currObj);\r\n\tnew_string = new_string.replace(/~~~/gi, \"\\n\");\r\n\r\n\t// Remove the prefixed asterisk that was added in switchText().\r\n\tnew_string = new_string.substr(1);\r\n\tcurrObj.objToCheck.style.display = \"none\";\r\n\tcurrObj.objToCheck.value = new_string;\r\n\tcurrObj.objToCheck.disabled = false;\r\n\tif(currObj.spellingResultsDiv)\r\n\t{\r\n\t\tcurrObj.spellingResultsDiv.parentNode.removeChild(currObj.spellingResultsDiv);\r\n\t\tcurrObj.spellingResultsDiv = null;\r\n\t}\r\n\tcurrObj.objToCheck.style.display = \"block\";\r\n\tcurrObj.resetAction();\r\n}", "function getClickedWord(selRange, node) {\n var nodeText = document.createRange();\n nodeText.selectNode(node);\n\n var str = nodeText.toString();\n var loc = selRange.focusOffset;\n\n return isolateWord(str,loc);\n}", "_getChoiceResponse(step, text) {\n\t const choice = txt.conversation[step].answer_choice.find((choice) => choice.text === text);\n return choice ? choice.response : '';\n }", "function insertText(grounding) {\n const selection = DocumentApp.getActiveDocument().getSelection();\n const elements = selection.getSelectedElements();\n\n var element = elements[0]\n var selected_text = element.getElement().asText().getText()\n\n if (element.isPartial()) {\n var text = selected_text.substring(element.getStartOffset(),\n element.getEndOffsetInclusive() + 1);\n } else {\n var text = selected_text\n }\n\n if (element.isPartial()){\n element.getElement().asText().insertText(element.getEndOffsetInclusive() + 1, ' (' + grounding + ')')\n //.setLinkUrl(0, text.length, response_json[0]['term']['url'])\n } else {\n element.getElement().asText().setText(selected_text + ' (' + grounding + ')')\n }\n}", "phrase(phrase, ...insert) {\n for (let map of this.facet(EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase)) {\n phrase = map[phrase]\n break\n }\n if (insert.length)\n phrase = phrase.replace(/\\$(\\$|\\d*)/g, (m, i) => {\n if (i == '$') return '$'\n let n = +(i || 1)\n return !n || n > insert.length ? m : insert[n - 1]\n })\n return phrase\n }", "function highlight_word(searchpara) {\n\tlet text=document.getElementById(\"search_text\").value;\n\tif (text) {\n\t\tlet pattern = new RegExp(\"(\"+text+\")\", \"gi\");\n\t\tlet new_text = searchpara.replace(pattern, \"<span class='highlight'>\"+text+\"</span>\");\n\t\tdocument.getElementById(\"search_para\").innerHTML=new_text;\n\t}\n}", "function parseCommand(text) {\n var words = text.split(\" \");\n for (var i = 0; i < words.length; i++) {\n if (seeCommandList.indexOf(words[i]) > -1) {\n /*Randomly select messages to speak from the list in config.js file*/\n var mapArr = ['see', 'recognize', 'know'];\n var rand = mapArr[Math.floor(Math.random() * mapArr.length)];\n processCommand('see', rand);\n break;\n } else if (readCommandList.indexOf(words[i]) > -1) {\n processCommand('read', 'read');\n break;\n }\n }\n}", "receiveWord(playerId, word) {\n console.log(\"receiveWord\");\n switch (this.state) {\n case GameStates.Picking: {\n console.log(\"OK\t\", this.currentDrawer);\n if (this.currentDrawer.id === playerId) {\n console.log(\"receive selection\");\n this.currentWord = word;\n } else {\n //error non drawer can't select word\n }\n }\n break\n }\n }", "renderHighlightedText(text, subSting) {\n const replaceWith = `<span class=\"highlight\">${subSting}</span>`;\n const result = replaceAll(text, subSting, replaceWith);\n return result;\n }", "function srQuery(container, search, replace, caseSensitive, wholeWord) {\r if (search) {\r var args = getArgs(caseSensitive, wholeWord);\r rng = document.body.createTextRange();\r rng.moveToElementText(container);\r clearUndoBuffer();\r while (rng.findText(search, 10000, args)) {\r rng.select();\r rng.scrollIntoView();\r if (confirm(\"Replace?\")) {\r rng.text = replace;\r pushUndoNew(rng, search, replace);\r }\r rng.collapse(false) ;\r } \r }\r}", "function displayPhrase(id) {\n if (id != null) {\n var phrase = phrases[id];\n\n if (phrase != null)\n document.getElementById(\"translation-box\").innerHTML =\n \"<b>\" + phrase[0] + \"</b> \" + phrase[1];\n }\n}", "function handleMouseDown(e){\n e.preventDefault();\n startX=parseInt(e.clientX-offsetX);\n startY=parseInt(e.clientY-offsetY);\n \n // Put your mousedown stuff here\n for(var i = 0;i < texts.length;i++){\n \t if(textHittest(texts, startX, startY, i)){\n \t\t selectedType = 0;\n \t\t selectedText = i;\n \t\t// selectedId = texts[i].id;\n \t }\n }\n for(i = 0;i < arranged_texts.length;i++){\n \t if(textHittest(arranged_texts, startX, startY, i)){\n \t\t selectedType = 1;\n \t\t selectedText = i;\n \t }\n } \n }", "function updateTextUI() {\n select('#result_hf').html(currentText);\n}", "function setSelectedText(objectUrl) {\r\n var text_iframe = document.getElementById('text-input'); \r\n text_iframe.contentWindow.setSelectedText(objectUrl);\r\n }", "function acHighlightedText() {\n return Selector(\".autocomplete-item.highlighted\").textContent;\n}", "highlightText(moreResults, moreSearchText, query) {\n if (!moreResults) {\n return null;\n }\n return html `\n <span part=\"more-results-text\">\n ${unsafeHTML(moreSearchText.replace(/{0\\}/g, `<mark>${query ? query.toString() : ''}</mark>`))}\n </span>\n <span part=\"more-results-keys\" slot=\"right\"><kbd>SHIFT</kbd> + <kbd>ENTER</kbd></span>\n `;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maintain max lines in log
function maintainLogSize() { while ($scope.logs.length > MAX_LOG_SIZE) { $scope.logs.shift(); } }
[ "set maxLines(value) {}", "get maxLines() {}", "function changeLogLimit(obj){\n var digitRgx = /^\\d+$/;\n if (digitRgx.test(obj.val())){\n rendererData.logLimit = obj.val();\n if ($(\"#logContainer\").find(\".msg\").length > rendererData.logLimit){\n var tmpCnt = $(\"#logContainer\").find(\".msg\").length;\n $(\"#logContainer\").find(\".msg\").slice(0, (tmpCnt - rendererData.logLimit)).remove();\n }\n }else{\n obj.val(rendererData.logLimit);\n }\n\n}", "set minLines(value) {}", "overflown() {\n let _this = this;\n\n return this.result.split('\\n').some((line) => {\n return line.length > _this.config['max-len'];\n });\n }", "setLogCapacity(capacity) {\n this.config.capacity = capacity;\n }", "function cleanLog() {\n\tredis.zremrangebyscore('modLog', 0, Date.now() - 1000*60*60*24*7,\n\t\tfunction (err) {\n\t\t\tif (err)\n\t\t\t\twinston.error('Error cleaning up moderation log:', err);\n\t\t}\n\t);\n}", "function appendToLogs(new_rows)\n{\n var row_per_page = getRowPerPage();\n\n window.logs = window.logs.concat(new_rows);\n\n if(window.logs.length > row_per_page)\n\twindow.logs = window.logs.slice(Math.min(window.logs.length-row_per_page, window.logs.length-new_rows.length));\n\n if (new_rows.length)\n\tupdateLastLogID(new_rows[new_rows.length-1][\"log_id\"]);\n\n window.new_rows_count = new_rows.length;\n}", "processEntries() {\n let previousMinute = new Date();\n // One minute ago.\n previousMinute = previousMinute.setMinutes(previousMinute.getMinutes() - 1);\n\n // Keep only \"new\" log entries (less than 1 minute)\n this.logEntries = reduce(this.logEntries, (list, entry) => {\n if (entry >= previousMinute) {\n list.push(entry);\n }\n return list;\n }\n , {});\n }", "function processText(tmp){\n line = line + (tmp.length)/tailleMax\n if (line >= nbLineMax){\n erase_text()\n line = 0;\n }\n}", "function maxLength(txt){\n let nLines = txt.split('\\n');\n let i = 0;\n let max = nLines[0];\n \n while(i < nLines.length){\n if(max.length < nLines[i].length){\n max = nLines[i];\n }\n i++;\n }\n return max.length;\n}", "consumeLogs () {\n try {\n this.tail = new Tail(this.logPath)\n } catch (err) {\n console.log('Error while opening log file.', err)\n return\n }\n\n console.log(`Ready to consume new logs from ${this.logPath} file.`)\n\n this.tail.on('line', (line) => {\n console.log('New log:', line)\n this.update(line)\n })\n\n this.tail.on('error', (error) => {\n console.log('Error during log parsing', error)\n })\n\n // Summary of most hit section, runs every 10 seconds\n setInterval(() => {\n this.summarizeTraffic()\n }, this.SUMMARY_INTERVAL * 1000)\n }", "exceedsMaxSize() {\n return JSON.stringify(this.data).length > MAX_SESSION_DATA_SIZE;\n }", "function processLogData(data, url) {\n data = data.trim();\n if(data == \"\") {\n data = \"-- no data --\";\n }\n data = data.split('\\n');\n\n var obj = $scope.urlAndLogsHash[url];\n if (!obj) {\n $scope.urlAndLogsHash[url] = {previousLength: data.length, lastLineTxt: data[data.length - 1]};\n } else if (obj && obj.lastLineTxt == data[obj.previousLength - 1] && data.length == obj.previousLength) {\n data = [];\n } else if (obj && obj.lastLineTxt == data[obj.previousLength - 1] && data.length != obj.previousLength) {\n $scope.urlAndLogsHash[url] = {previousLength: data.length, lastLineTxt: data[data.length - 1]};\n data = data.splice(obj.previousLength);\n }\n return data;\n }", "get maxLength () {\n if (this._maxLength) return this._maxLength;\n let maxLength = Math.max(...this.lengths);\n if (this.allowNull === false && maxLength !== this.minLength) {\n let row = this.body.find(row => row.length > this.minLength);\n throw new Error(`extra column in row ${row.length + 1}. Use \"allowNull: true\" in options to parse anyway, or modify data to correct.\\n${row.join(\",\")}`);\n };\n return this._maxLength = maxLength;\n }", "saveChunk() {\n console.log(\"Saving Chunk for \" + this.name + \" @ \" + this.path + \"/fullLog.json\");\n\n // Load the Full Log.\n let fullLogRaw = fs.readFileSync(this.path + \"/fullLog.json\");\n let fullLog = JSON.parse(fullLogRaw);\n\n // Push the Current Chunk.\n fullLog.push(this.currentChunk);\n\n // Clear the Current Chunk.\n this.currentChunk = [];\n let logJSON = JSON.stringify(fullLog, null, 2);\n\n // Write the New Full Log.\n fs.writeFileSync(this.path + \"/fullLog.json\", logJSON);\n this.currentChunkIndex++;\n }", "function checkReceiptLogs(desired, hash, client, cb) {\n client.eth.getTransactionReceipt(hash, (err, receipt) => {\n if (err) { cb(err); }\n else if (receipt.logs.length < desired) { cb(null, false); }\n else { cb(null, true); }\n })\n}", "function trim()\n{\n if (maxMessages !== null)\n {\n while(messages.length > maxMessages)\n {\n messages.shift();\n }\n }\n}", "function createNewLogFile() {\n var basePath = (global.TYPE.int === global.TYPE_LIST.CLIENT.int ? \"./\" : path.join(__dirname, \"..\")); //Get base path\n if (fs.existsSync(path.join(basePath, \"Timbreuse.10.log\"))) //If log 10 exists, delete\n fs.unlinkSync(path.join(basePath, \"Timbreuse.10.log\"));\n for (var i = 9; i > 0; i--)\n if (fs.existsSync(path.join(basePath, \"Timbreuse.\" + i + \".log\"))) //Then move log n to log n+1\n fs.renameSync(path.join(basePath, \"Timbreuse.\" + i + \".log\"), path.join(basePath, \"Timbreuse.\" + (i + 1) + \".log\"));\n if (fs.existsSync(path.join(basePath, \"Timbreuse.log\"))) //If log exists, move it to log 1\n fs.renameSync(path.join(basePath, \"Timbreuse.log\"), path.join(basePath, \"Timbreuse.1.log\"));\n global.logFile = fs.createWriteStream(path.join(basePath, \"Timbreuse.log\"), { //Then create write stream to log file\n flags: 'w'\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION NAME : queryAutoDiscoveryLogs AUTHOR : kmmabignay DATE : March 12, 2014 MODIFIED BY : Cathyrine C. Bobis REVISION DATE : REVISION : DESCRIPTION : query for auto discovery logs PARAMETERS : filename,user,ip RETURN : data
function queryAutoDiscoveryLogs(fname,user,ip,pIp){ //var infoType = "XML"; if(globalInfoType == "XML"){ //var urlx = "/cgi-bin/Final/AutoCompleteCgiQuerry_withDb/querYCgi.fcgi"; var urlx = getURL("RM"); var queryS = "filename="+fname+"&user="+user+"&ip="+ip; }else{ var urlx = getURL("ConfigEditor2","JSON"); var queryS = "{ 'QUERY' : [{ 'filename' : '"+fname +"', 'user' : '"+user+"', 'ip' : '"+ip+"' }] }"; } if(globalDeviceType=="Mobile"){ loading("show"); } $.ajax({ url: urlx, data : { "action": "getdiscoverylogs", "query": queryS, }, method: 'POST', proccessData: false, async:false, dataType: 'html', success: function(data) { data = $.trim(data); if(globalDeviceType=="Mobile"){ loading("hide"); } if(data){ if(globalInfoType == "XML"){ var devInfo = data.split('&&')[0].split(","); var linkInfo = data.split('&&')[1]; var autodLogs = data.split('&&')[2]; }else{ var dat = data.replace(/'/g,'"'); var dat2 = $.parseJSON(dat); var DEVICE = dat2.DEVICE; var Access = DEVICE[0].Accessibility; var DevicePrep = DEVICE[0].DevicePreparation; var Mapping = DEVICE[0].SearchMapping; var Gather = DEVICE[0].GatheringInformation; var Ip = DEVICE[0].Ip; var devInfo = [Ip,Access,DevicePrep,Mapping,Gather].join(","); var linkInfo = DEVICE[0].PORT; var autodLogs = DEVICE[0].Logs; } showAutoDiscoveryStatus(fname,user,ip,pIp,devInfo,linkInfo,autodLogs); }else{ alertUser("Process failed.");return; } } }); }
[ "function queryLoggerData(starttime,endtime,doOnSuccess) {\n\tif(endtime!=\"now\")\n\t$.couch.db(\"dripline_logged_data\").view(\"log_access/all_logged_data\", {\n\t\tstartkey: starttime,\n\t\tendkey: endtime,\n\t\tsuccess: function(data) {\n\t\t\tdoOnSuccess(data); },\n\t\terror: function(data) {\n\t\t\tdocument.getElementById(\"error_div\").innerHTML=\"error getting data: \"+JSON.stringify(data);\n\t\t\t}\n\t\t\t});\n\telse\n\t$.couch.db(\"dripline_logged_data\").view(\"log_access/all_logged_data\", {\n\t\tstartkey: starttime,\n\t\tendkey: endtime,\n\t\tsuccess: function(data) {\n\t\t\tdoOnSuccess(data); },\n\t\terror: function(data) {\n\t\t\tdocument.getElementById(\"error_div\").innerHTML=\"error getting data: \"+JSON.stringify(data);\n\t\t\t}\n\t\t\t});\n}", "function getLogsFromServer() {\n if (!$scope.logs) return;\n\n var logs = $scope.logs;\n var len = logs.length;\n for (var i = 0; i < len; i++) {\n getLog(logs[i]);\n }\n }", "eth_getLogs(filter) {\n return this.request(\"eth_getLogs\", Array.from(arguments));\n }", "function queryPortalFxLogs(query, continuationToken, mergedResults) {\n mergedResults = mergedResults || [];\n //table service uses environmental var AZURE_STORAGE_CONNECTION_STRING\n if (process.env.AZURE_STORAGE_CONNECTION_STRING) {\n var tableSvc = storage.createTableService().withFilter(new storage.ExponentialRetryPolicyFilter());\n return Q.ninvoke(tableSvc, \"queryEntities\", \"PortalFxChangeLog\", query, continuationToken)\n .then(function (result) {\n var body = result[0];\n mergedResults = mergedResults.concat(body.entries);\n\n if (body.continuationToken) {\n //recurse continuation token \n return queryPortalFxLogs(query, body.continuationToken, mergedResults);\n } else {\n return Q.resolve(mergedResults);\n }\n });\n } else {\n return Q.reject(\"environmental var AZURE_STORAGE_CONNECTION_STRING required to generate breaking-changes.md document\");\n }\n}", "function retrieveLogs(simulation){\n\t//calls function from localSimulationManager\n\tvar device_list=getAllDeviceObjects(simulation);\n\t\n\tfor (var i =0;i<device_list.length;i++){\n\t\tsimulationLogs+=device_list[i].activity+'\\n';\n\t}\n\tvar simulationLogs= simulation.activity_logs;\n\treturn simulationLogs;\n}", "function fetchLogs(socket, callback = null) {\n const url = 'http://api.irail.be/logs';\n\n fetch(url)\n .then(response => response.json())\n .then(queryData => {\n // pass queries to the callback\n // not the first time though, because we don't know what our lastQuery is yet\n if (callback) {\n emitSingleQueries(socket, filterQueries(callback(queryData)));\n // data refreshed and events emitted, start a new timeout\n setTimeout(fetchLogs, 500, socket, getNewData);\n } else {\n // initialize lastQuery\n // at this point the first dataset has been fetched\n lastQuery = queryData[queryData.length - 1];\n fetchLogs(socket, getNewData);\n }\n })\n .catch(ex => {\n fetchLogs(socket, getNewData);\n });\n}", "function getLog(index) {\r\n\t//$.get('status_'+ index +'.log', function(datados) {\r\n $.get(cs_folder+'/status_'+index+'.log', function(datados) {\r\n\t\t$(\"#layout_logger_console_content_\"+index).html('');\r\n\t\tvar lines = datados.split(\"\\n\");\r\n\t\tfor (nm in lines)\t{\r\n\t\t\t//console.log('lineas' + nm);\r\n\t\t\t$(\"#layout_logger_console_content_\"+index).append('<p>'+lines[nm]+'</p>');\r\n\t\t}\r\n\t});\r\n}", "function scan_iprange(ip)\n{\n ip=$(\"#ip\").val();\n\n var myRegexp = /([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)/g;\n var match = myRegexp.exec(ip);\n targetIPs=[];\n for(i =0;i<255;i++)\n {\n targetip=match[1]+\".\"+match[2]+\".\"+match[3]+\".\"+i;\n targetIPs.push(targetip);\n }\n\n //async json pull\n $.each( targetIPs, function( key, val ) {\n get_info(val);\n });\n}", "getLogs() {\n if (this.auth()) {\n if (this.currentUser.type === \"admin\") {\n console.log(\"Saved logs: \");\n for (let i = 0; i < this.logs.length; i++) {\n console.log(this.logs[i]);\n }\n } else console.log('Access is denied')\n } else console.log('authorization required');\n }", "function run_getFileNameIdMap() {\n var fileNameIdMap = getFileNameIdMap();\n Logger.log(fileNameIdMap);\n}", "function filter_key_master(ulogs) {\n var flogs = [];\n for (var i = 0; i < ulogs.length; i++) {\n var d = ulogs[i];\n var pc = d.data;\n var ks = pc.ks;\n var cnode = ZPart.GetKeyNode(ks);\n if (cnode && cnode.device_uuid === ZH.MyUUID) flogs.push(d);\n }\n return flogs;\n}", "deviceDiscovery(){\n\t\ttry {\n\n\t\t\tthis.log.info(`Auto Discovery startet, new devices (or IP changes) will be detected automatically`);\n\t\t\tdiscovery = new Discovery();\n\n\t\t\tdiscovery.on('info', async (message) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.log.debug(`Discovery message ${JSON.stringify(message)}`);\n\t\t\t\t\tif (this.deviceInfo[message.address] == null){\n\t\t\t\t\t\tthis.log.info(`[AutoDiscovery] New ESPHome device found at IP ${message.address}`);\n\t\t\t\t\t\t// Store new Device information to device array in memory\n\t\t\t\t\t\tthis.deviceInfo[message.address] = {\n\t\t\t\t\t\t\tip: message.address,\n\t\t\t\t\t\t\tpassWord: apiPass\n\t\t\t\t\t\t};\n\t\t\t\t\t\tthis.connectDevices(`${message.address}`,`${apiPass}`);\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthis.log.error(`[deviceDiscovery handler] ${e}`);\n\t\t\t\t}\n\t\t\t});\n\t\t\tdiscovery.run();\n\t\t} catch (e) {\n\t\t\tthis.sendSentry(`[deviceDiscovery] ${e}`);\n\t\t}\n\t}", "function fetchLogs(count) {\n function Skipped(message) {\n this.message = message;\n }\n return gcs.conversationLogs.conversationLog.get().then(function (logs) {\n return repeatAndExit(function (exit) {\n var log = logs[nextTranscript.logIndex];\n var recipients = log.conversationLogRecipient;\n var subject = log.subject;\n return Task.waitAll([subject.get(), recipients.get()]).then(function () {\n if (recipients().length != 1)\n throw new Skipped('conference');\n return recipients(0).sipUri.get();\n }).then(function (sip) {\n if (sip != participants(0).uri())\n throw new Skipped('different participant');\n return log.conversationLogTranscripts.conversationLogTranscript.get();\n }).then(function (transcripts) {\n return repeat(function () {\n var transcript = transcripts[nextTranscript.transcriptIndex++];\n if (!transcript)\n throw new Skipped('no more transcripts');\n var messageTranscript = transcript.messageTranscript;\n var html = messageTranscript.htmlMessage.href;\n var text = messageTranscript.plainMessage.href;\n var time = transcript.timeStamp;\n var href = transcript.contact.href;\n var dir = log.direction;\n var message = new Internal.Message({\n ucwa: ucwa,\n href: dir() == 'Incoming' ? '' : null,\n sender: { person: contactManager.get(href) },\n time: time(),\n text: text(),\n html: html(),\n direction: dir()\n });\n addMessageActivityItem(message);\n count--;\n if (count < 1)\n exit();\n });\n }).catch(function (err) {\n if (err instanceof Skipped) {\n nextTranscript.logIndex++;\n nextTranscript.transcriptIndex = 0;\n }\n else {\n throw err;\n }\n });\n });\n });\n }", "function gatherDataAutoD(type){\n//\tsetAutoDVariable();\n\n\tvar data = autoDDevData[0];\n\tvar date = new Date();\n\tvar month = date.getMonth();\n var day = date.getDay();\n var year = date.getFullYear();\n var hour = date.getHours();\n var min = date.getMinutes();\n var sec = date.getMilliseconds();\n\tvar logname = globalUserName +\"_\"+ year + \"-\" + month + \"-\"+ day + \"-\" + hour + \"-\" + min + \"-\" + sec;\n\tdata.LogsName = logname;\n\n\tswitch(type){\n\t\tcase \"device\":\n\t\t\tif(!checkDataManuAutoD(type)){ return false; }\n\t\t\tif($('#addManualNewDevHostName').val()!=undefined){\n\t\t\t\tdata.HostName = $('#addManualNewDevHostName').val();\n\t\t\t}\n\t\t\tif($('#addDevTypeOpt > option:selected').text()!=\"Select\"){\n\t\t\t\tvar devtype = $('#addDevTypeOpt > option:selected').text()\n\t\t\t\tif(devtype==\"L1 Switch\"){devtype = \"Layer 1 Switch\";\n\t\t\t\t}else if(devtype==\"L2 Switch\"){devtype = \"Layer 2 Switch\";}\n\t\t\t\tdata.Type = devtype;\n\t\t\t\t}\n\t\t\tif($('#addNewDevManuOpt > option:selected').text()!=\"Select\"){\n\t\t\t\tdata.Manufacturer = $('#addNewDevManuOpt > option:selected').text();\n\t\t\t\tdata.DeviceType = $('#addNewDevManuOpt > option:selected').text();\n\t\t\t}\n\t\t\tdata.ManagementIp = $('#addNewDevMmgmtIp').val();\n\t\t\tif($('#addNewDevMmgmtIpPort').val()!=undefined){\n\t\t\t\tdata.ManagementPort = $('#addNewDevMmgmtIpPort').val();\n\t\t\t}\n\t\t\tif($('#addNewDevConIp').val()!=undefined && $('#addNewDevConIp').val().toLowerCase!=\"na\" && $('#addNewDevConIp').val().toLowerCase!=\"n/a\"){\n\t\t\t\tdata.ConsoleIp = $('#addNewDevConIp').val();\n\t\t\t}\n\t\t\tif($('#addNewDevConIpPort').val()!=undefined && $('#addNewDevConIpPort').val().toLowerCase!=\"na\"){\n\t\t\t\tdata.ConsolePort = $('#addNewDevConIpPort').val();\n\t\t\t}\n\t\t\tif($('#addNewDevUserN').val()!=undefined){\n\t\t\t\tdata.Username = $('#addNewDevUserN').val();\n\t\t\t}\n\t\t\tif($('#addNewDevCPassW').val()!=undefined){\n\t\t\t\tdata.Password = $('#addNewDevCPassW').val();\n\t\t\t}\n\t\t\tif($('#addNewDevDomainOpt > option:selected').text()!=\"Select\"){\n\t\t\t\tdata.Domain = $('#addNewDevDomainOpt > option:selected').text();\n\t\t\t\tdata.DomainId = $('#addNewDevDomainOpt > option:selected').val();\n\t\t\t}\n\t\t\tif($('#addNewDevAuxIp').val()!=undefined){\n\t\t\t\tdata.AuxiliaryIp = $('#addNewDevAuxIp').val();\n\t\t\t}\n\t\t\tif( $('#addNewDevAuxIpPort').val()!=undefined){\n\t\t\t\tdata.AuxiliaryPort = $('#addNewDevAuxIpPort').val();\n\t\t\t}\n\t\t\tif($('#autoDPartTypeOpt > option:selected').text()!=\"Select\"){\n\t\t\t\tvar partnertype = $('#autoDPartTypeOpt > option:selected').text();\n\t\t\t\tif(partnertype==\"L1 Switch\"){partnertype = \"Layer 1 Switch\";\n\t\t\t\t}else if(partnertype==\"L2 Switch\"){partnertype = \"Layer 2 Switch\";}\n\t\t\t\tdata.PartnerType = partnertype;\n\t\t\t}\n\t\t\tif($('#autoDPartAddOpt > option:selected').text()!=\"Select\"){\n\t\t\t\tdata.PartnerIp = $('#autoDPartAddOpt > option:selected').text();\n\t\t\t}\n\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\tif($('#newDevPartnerDevManuS').text()!=\"No Selection\"){\n\t\t\t\t\tdata.PartnerManufacturer = $('#newDevPartnerDevManuS').text();\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tif($('#newDevPartnerDevManu').children.length>0){\n\t\t\t\t\tdata.PartnerManufacturer = $('#newDevPartnerDevManuS').val();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif($('#autoDPartnerInfoTableCont').is(':visible')){\n\t\t\t\tdata.PartnerSlotNumber = \"\";\n\t\t\t\t$.each($('#autoDPartnerInfoTbody > tr'), function(index,object){\n\t\t\t\t\tif(globalDeviceType == \"Mobile\") {\n\t\t\t\t\t\tif(object.getAttribute('class')=='trAutoDP highlight'){\n\t\t\t\t\t\t\tvar tmpval = \",\"+object.children[0].innerHTML+\":\";\n\t\t\t\t\t\t\tvar tmpcnt = $(\"#\"+object.children[2].getAttribute('id')+\" > input\").val();\n//\t\t\t\t\t\t\tvar tmpcnt = object.children[2].getAttribute('value');\n\t\t\t\t\t\t\tif(tmpcnt!=undefined){ tmpval+=tmpcnt; }\n\t\t\t\t\t\t\tdata.PartnerSlotNumber += tmpval;\n\t\t\t\t\t\t}\n\t\t\t\t\t}else{\n\t\t\t\t\t\tvar tmpslot = object.children[1].innerHTML;\n\t\t\t\t\t\tvar tmpcnt = $(\"#\"+object.children[3].getAttribute('id')+\" > input\").val();\n\t\t\t\t\t\tvar tmpval =\",\"+tmpslot+\":\";\n\t\t\t\t\t\tif(tmpcnt!=undefined){\n\t\t\t\t\t\t\ttmpval+=tmpcnt;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif($(\"#\"+(object.children[0].children[0].getAttribute('id'))).is(':checked')){\n\t\t\t\t\t\t\tdata.PartnerSlotNumber += tmpval;\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\tvar totalports = $('#autoDPartPortsSrchNum').val();\n\t\t\tif(totalports!=undefined && totalports!=0){\n\t\t\t\tdata.TotalPortsToSearch = totalports;\n\t\t\t}\n\t\tbreak;\n\t\tcase \"testtool\":\n\t\t\tif(!checkDataManuAutoD(type)){ return false; }\n\t\t\tif($('#newTestTHostname').val()!=undefined){\n\t\t\t\tdata.HostName = $('#newTestTHostname').val();\n\t\t\t}\n\t\t\tdata.Type = \"TestTool\";\n\t\t\tif($('#addNewTestTManuOpt > option:selected').text()!=\"Select\"){\n\t\t\t\tdata.Manufacturer = $('#addNewTestTManuOpt > option:selected').text();\n\t\t\t\tdata.DeviceType = $('#addNewTestTManuOpt > option:selected').text();\n\t\t\t}\n\t\t\tif($('#addNewTestTMmgmtIp').val()!=undefined){\n\t\t\t\tdata.Host = $('#addNewTestTMmgmtIp').val();\n\t\t\t\tdata.ManagementIp = $('#addNewTestTMmgmtIp').val();\n\t\t\t}\n\t\t\t//data.ManagementIp = $('#addNewTestTMmgmtIp').val();\n\t\t\tif($('#addNewTestTMmgmtIpPort').val()!=undefined){\n\t\t\t\tdata.ManagementPort = $('#addNewTestTMmgmtIpPort').val();\n\t\t\t}\n\t\t\tif($('#addNewTestTConIp').val()!=undefined && $('#addNewTestTConIp').val().toLowerCase!=\"na\" && $('#addNewTestTConIp').val().toLowerCase!=\"n/a\"){\n\t\t\t\tdata.ConsoleIp = $('#addNewTestTConIp').val();\n\t\t\t}\n\t\t\tif($('#addNewTestTConIpPort').val()!=undefined){\n\t\t\t\tdata.ConsolePort = $('#addNewTestTConIpPort').val();\n\t\t\t}\n\t\t\tif($('#addNewTestTUserN').val()!=undefined){\n\t\t\t\tdata.Username = $('#addNewTestTUserN').val();\n\t\t\t}\n\t\t\tif($('#addNewTestTCPassW').val()!=undefined){\n\t\t\t\tdata.Password = $('#addNewTestTCPassW').val();\n\t\t\t}\n\t\t\tif($('#addNewTestTDomainOpt > option:selected').text()!=\"Select\"){\n\t\t\t\tdata.Domain = $('#addNewTestTDomainOpt > option:selected').text();\n\t\t\t\tdata.DomainId = $('#addNewTestTDomainOpt > option:selected').val();\n\t\t\t}\n\t\t\tif($('#addNewTestTAuxIp').val()!=undefined){\n\t\t\t\tdata.AuxiliaryIp = $('#addNewTestTAuxIp').val();\n\t\t\t}\n\t\t\tif($('#addNewTestTAuxIpPort').val()!=undefined){\n\t\t\t\tdata.AuxiliaryPort = $('#addNewTestTAuxIpPort').val();\n\t\t\t}\n\t\t\tif($('#autoDTestTPartTypeOpt > option:selected').text()!=\"Select\"){\n\t\t\t\tvar partnertype = $('#autoDTestTPartTypeOpt > option:selected').text();\n\t\t\t\tif(partnertype==\"L1 Switch\"){partnertype = \"Layer 1 Switch\";\n\t\t\t\t}else if(partnertype==\"L2 Switch\"){partnertype = \"Layer 2 Switch\";}\n\t\t\t\tdata.PartnerType = partnertype;\n\t\t\t}\n\t\t\tif($('#autoDTestTPartAddOpt > option:selected').text()!=\"Select\"){\n\t\t\t\tdata.PartnerIp = $('#autoDTestTPartAddOpt > option:selected').text();\n\t\t\t}\n\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\tif($('#newTestTPartnerDevManuS').text()!=\"No Selection\"){\n\t\t\t\t\tdata.PartnerManufacturer = $('#newTestTPartnerDevManuS').text();\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tif($('#newTestTPartnerDevManu').children.length>0){\n\t\t\t\t\tdata.PartnerManufacturer = $('#newTestTPartnerDevManuS').val();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif($('#autoDTestTPartnerInfoTableCont').is(':visible')){\n\t\t\t\tdata.PartnerSlotNumber = \"\";\n\t\t\t\t$.each($('#autoDTestTPartnerInfoTbody > tr'), function(index,object){\n\t\t\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\t\t\tif(object.getAttribute('class')=='trAutoDP highlight'){\n\t\t\t\t\t\t\tvar tmpval = \",\"+object.children[0].innerHTML+\":\";\n\t\t\t\t\t\t\tvar tmpcnt = $(\"#\"+object.children[2].getAttribute('id')+\" > input\").val();\n//\t\t\t\t\t\t\tvar tmpcnt = object.children[2].getAttribute('value');\n\t\t\t\t\t\t\tif(tmpcnt!=undefined){ tmpval+=tmpcnt; }\n\t\t\t\t\t\t\tdata.PartnerSlotNumber += tmpval;\n\t\t\t\t\t\t}\n\t\t\t\t\t}else{\n\t\t\t\t\t\tvar tmpslot = object.children[1].innerHTML;\n\t\t\t\t\t\tvar tmpcnt = $(\"#\"+object.children[3].getAttribute('id')+\" > input\").val();\n\t\t\t\t\t\tvar tmpval =\",\"+tmpslot+\":\";\n\t\t\t\t\t\tif(tmpcnt!=undefined){\n\t\t\t\t\t\t\ttmpval+=tmpcnt;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif($(\"#\"+(object.children[0].children[0].getAttribute('id'))).is(':checked')){\n\t\t\t\t\t\t\tdata.PartnerSlotNumber += tmpval;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t}\n\t\t\tvar totalports = \"\";\n\t\t\ttotalports = $('#autoDTestTPartPortSrchNumNum').val();\n\t\t\tif(totalports!=undefined && totalports!=0){\n\t\t\t\tdata.TotalPortsToSearch = totalports;\n\t\t\t}\n\t\tbreak;\n\t\tcase \"admin\":\n\t\t\treturn gatherAutoDAdminInfo(data);\n\t\tbreak;\n\t}\n\tautoDDevData[0] = data;\n\treturn true;\n}", "function lineConnectionQuery(action,resArr,count,delay){\n\tif(count==null || count==\"\" || count == undefined)\n\t\tcount =1;\n\tif(delay == null || delay == undefined || delay == \"\")\n\t\tdelay = 0;\n//\tvar url = \"/cgi-bin/Final/AutoCompletePythonCGI/FastQueryCgi.py\"\n\tif (globalInfoType == \"XML\"){\n\t\tvar query = \"Port1=\"+resArr[0].pDestination+\"^Port2=\"+resArr[0].pSource+\"^Count=\"+count+\"^Delay=\"+delay+\"^ResourceId=\"+window['variable' + dynamicResourceId[pageCanvas] ]+\"^ConfigName=\"+Name;\n\t\tvar url = getURL(\"ConfigEditor\");\n\t} else {\n\t\tvar query = \"{'QUERY':[{'Port1':'\"+resArr[0].pDestination+\"','Port2':'\"+resArr[0].pSource+\"','Count':'\"+count+\"','Delay':'\"+delay+\"','ResourceId':'\";\n\t\tquery += window[\"variable\" + dynamicResourceId[pageCanvas]];\n\t\tquery += \"','ConfigName':'\"+Name+\"'}]}\";\n\t\tvar url = getURL(\"ConfigEditor\",\"JSON\");\n\t}\n//\tvar url = \"https://\"+CURRENT_IP+url;\n\t$.ajax({\n\t\turl: url,\n\t\tdata:{\n\t\t\t\"action\":action,\n\t\t\t\"query\":query,\n\t\t},\n\t\tdataType: 'html',\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tsuccess: function(data) {\n\t\t\tdata = $.trim(data);\n\t\t\tif (globalInfoType == \"XML\"){\n\t\t\t\tif (data==\"1\"){\n\t\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t\terror(action+\" Successful\",action);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talerts(action+\" Successful\");\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t\terror(\"Failed to \"+action,action);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talerts(\"Failed to \"+action);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdata = data.replace(/'/g,'\"');\n\t\t\t\tvar jsonData = jQuery.parseJSON(data);\t\n\t\t\t\tvar row = jsonData.RESULT[0];\n\t\t\t\tif (row==\"1\"){\n\t\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t\terror(action+\" Successful\",action);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talerts(action+\" Successful\");\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t\terror(\"Failed to \"+action,action);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talerts(\"Failed to \"+action);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tsetTimeout(function(){\n\t\t\t\tif (globalDeviceType == 'Mobile'){\n\t\t\t\t\t$.mobile.changePage($('#configEditorPage'),{\n\t\t\t\t\t\ttransition: \"pop\"\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t$('#configPopUp').dialog('destroy');\n\t\t\t\t}\n\t\t\t},1000);\n\n\t\t}\n\t});\t\t\n}", "function getEventLogs(callback, n) {\n EventLog\n .find()\n .sort({\"timestamp\": -1})\n .limit(n || 10)\n .exec(callback);\n}", "function retrieveUserAnnotations(req, res) {\n let targetUserDoc = null;\n sec.authenticateApp(req.get('clientId')).then((result)=>{\n return sec.authorizeUser(req.get('username'), req.get('accessToken'));\n }).then(async (userDoc)=> {\n // If the user specifies a target user in their request, check if they \n // are an admin, if they aren't an admin, then throw an error\n if(req.get('targetUser') && !userDoc.isAdmin) {\n let err = new Error('User must have admin credentials to retrieve data of other users');\n err.code = constants.UNAUTHORIZED;\n throw err; \n } else if(req.get('targetUser')){\n // An admin account is attempting to retrieve another user's annotations\n userDoc = await User.findOne({'username' : req.get('targetUser').toLowerCase()}).exec();\n if (!userDoc) {\n let err = new Error('User specified by admin account does not exist');\n err.code = constants.NOT_FOUND;\n throw err;\n }\n }\n\n // Return the document in which to retrieve the annotations for\n return userDoc;\n }).then((userDoc) => {\n targetUserDoc = userDoc;\n // Get all of the hash values for all of the user annotations\n let hashValList = new Array();\n hashValList.push(...Array.from(targetUserDoc.annotations.keys()));\n\n // Do a query with the list of hash values\n return Source.find({\n 'hash' : {\n $in : hashValList\n }\n }).select('hash phrase annotations').exec();\n }).then((sourceDocList) =>{\n let userAnnotationList = new Array();\n\n // Retrieve the language => hash values for the user\n sourceDocList.forEach((sourceItem) => {\n // The current hash value\n let currHashVal = sourceItem.hash;\n // The original english phrase of the hash value\n let originalPhrase = sourceItem.phrase;\n \n // A mapping of the user's annotations\n let annotationMap = {\n 'phrase' : originalPhrase,\n 'hash' : currHashVal,\n 'list' : []\n };\n // Create a list of the languages the user annotated for the current hash\n targetUserDoc.annotations.get(currHashVal).forEach((value, language, anMap) => {\n // Retrieve the translation for the current hash in the current language\n let map = {};\n map.language = language;\n map.azureTranslation = sourceItem.annotations.get(language).azure.translation;\n map.isAzureCorrect = value.isAzureCorrect;\n map.googleTranslation = sourceItem.annotations.get(language).google.translation;\n map.isGoogleCorrect = value.isGoogleCorrect;\n map.yandexTranslation = sourceItem.annotations.get(language).yandex.translation;\n map.isYandexCorrect = value.isYandexCorrect;\n annotationMap.list.push(map);\n });\n // Append the newly created map to the user annotation list\n userAnnotationList.push(annotationMap);\n });\n return res.status(constants.OK).json({'annotations' : userAnnotationList});\n }).catch((err) => {\n util.log(`Error in retrieveUserAnnotations in user middleware.\\nError Message: ${err.message}`);\n return res.status(err.code).json({message : err.message});\n });\n}", "async errorLogs() {\n const options = this.buildOptions({\n path: `${this.path}/logs/error`,\n method: \"get\",\n body: {},\n });\n\n return this.apiCall(options);\n }", "function autoDCompleteDevInfo(ip,type,idx){\n\tif(globalInfoType == \"XML\"){\n\t\tvar urlx = getURL(\"ConfigEditor2\");\n\t\tvar queryS = \"hostname=\"+ip;\n\t}else{\n\t\tvar urlx = getURL(\"ConfigEditor\",\"JSON\");\n\t\tvar queryS = \"{ 'QUERY': [{ 'hostname': '\"+ip+\"' ,\"\n\t\tif(type){\n\t\t\tif(type==\"load\"){\n\t\t\t\tqueryS += \"'type': 'fetch' ,\";\n\t\t\t}\n\t\t}else{\n\t\t\tqueryS += \"'type': 'save' ,\";\n\t\t}\n\t\tqueryS+= \"'logsname': '\"+autoDDevData[0].LogsName+\"'}]}\";\n\t}\n\tif(globalDeviceType==\"Mobile\"){\n\t\tloading(\"show\");\n/* }else{\n\t\tif(type){\n\t\t\tif(type==\"load\"){\n\t\t\t\tajaxLoader('show','Processing Information ...');\n\t\t\t}\n\t\t}else{\n\t\t\tajaxLoader('show','Saving Discovered Information ...');\n\t\t}\n*/\n\t}\n\t$.ajax({\n\t\turl: urlx,\n\t\tdata : {\n\t\t\t\"action\": \"getmaplinkusingip\",\n\t\t\t\"query\": queryS,\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tdata = $.trim(data);\n\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\tloading(\"hide\");\n\t\t //}else{\n\t\t\t//\tajaxLoader('hide');\n\t\t\t}\n\t\t\tif(data){\n\t\t\t\t//show data in #autoDSaveDialog \n\t\t\t\tif (globalInfoType == \"XML\"){\n\t\t\t\t\tvar parser = new DOMParser();\n\t\t\t\t\tvar xmlDoc = parser.parseFromString(data , \"text/xml\" );\n\t\t\t\t\tvar DEVICES = xmlDoc.getElementsByTagName('DEVICES');\n\t\t\t\t\tvar DEVICE = xmlDoc.getElementsByTagName('DEVICE');\n\n\t\t\t\t\tvar host = DEVICE[0].getAttribute(\"DeviceName\");\n\t\t\t\t\tif(autoDDevData[0].HostName != host && autoDDevData[0].HostName!=\"\") {\n\t\t\t\t\t\tvar doCancel = \"$('#autoDSaveHost').val('\"+autoDDevData[0].HostName+\"');\";\n\t\t\t\t\t\tvar execFunc = \"$('#autoDSaveHost').val('\"+host+\"');\";\n\t\t\t\t\t\tconfirmation(\"Different Device Name '\"+host+\"' found. Do you want to use this?\",\"Confirmation\",execFunc,doCancel);\n\t\t\t\t\t}else{\n\t\t\t\t\t\t$('#autoDSaveHost').val(host);\n\t\t\t\t\t}\n\t\t\t\t\t$('#autoDSaveUsername').val(DEVICE[0].getAttribute(\"Username\"));\n\t\t\t\t\t$('#autoDSavePassword').val(DEVICE[0].getAttribute(\"Password\"));\n\t\t\t\t\t$('#autoDSaveMgmtIp').val(DEVICES[0].getAttribute(\"IpAddress\"));\n\t\t\t\t\t$('#autoDSaveNetMask').val(DEVICES[0].getAttribute(\"SubnetMask\"));\n\t\t\t\t\t$('#autoDSaveMgmtIntf').val(DEVICES[0].getAttribute(\"ManagementInterface\"));\n\t\t\t\t\t$('#autoDSaveTftpServer').val(DEVICES[0].getAttribute(\"TbTftpServerAddress\"));\n\t\t\t\t\t$('#autoDSaveGateway').val(DEVICES[0].getAttribute(\"TFTPGateway\"));\n\t\t\t\t\tvar rpCtr = (DEVICE[0].getAttribute(\"RouteProcessor\").split(\",\")).length;\n\n\t\t\t\t\tif(rpCtr>0) {\n\t\t\t\t\t\t$('#autoDSaveRP1').show();\n\t\t\t\t\t\tvar rp1 = DEVICES[0].getAttribute(\"RP0ConsoleIp\").split(\":\");\n\t\t\t\t\t\tif(rp1==\"\"){rp1 = DEVICES[0].getAttribute(\"ConsoleIp\").split(\":\");}\n\t\t\t\t\t\tif(rp1!=\"\"){$('#autoDSaveRP1ConAdd').val(rp1[0]);}\n\t\t\t\t\t\tif(rp1!=\"\" && rp1.length>1){$('#autoDSaveRP1ConPort').val(rp1[1]);}\n\t\t\t\t\t\t//$('#autoDSaveRP1AuxAdd').val();\n\t\t\t\t\t\t//$('#autoDSaveRP1AuxPort').val();\n\t\t\t\t\t}else{$('#autoDSaveRP1').hide();}\n\n\t\t\t\t\tif(rpCtr>1) {\n\t\t\t\t\t\t$('#autoDSaveRP2').show();\n\t\t\t\t\t\tvar rp2 = DEVICES[0].getAttribute(\"RP1ConsoleIp\").split(\":\");\n\t\t\t\t\t\tif(rp2!=\"\"){$('#autoDSaveRP2ConAdd').val(rp2[0]);}\n\t\t\t\t\t\tif(rp2!=\"\" && rp2.length>1){$('#autoDSaveRP2ConPort').val(rp2[1]);}\n\t\t\t\t\t\t//$('#autoDSaveRP2AuxAdd').val();\n\t\t\t\t\t\t//$('#autoDSaveRP2AuxPort').val();\n\t\t\t\t\t}else{$('#autoDSaveRP2').hide();}\n\n\t\t\t\t\t$('#autoDSaveSoftPriImg').val(DEVICES[0].getAttribute(\"SystemImageName\"));\n\t\t\t\t\t//$('#autoDSaveSoftSecImg').val();\n\t\t\t\t\t\n\t\t\t\t\t$('#autoDSaveConfPriImg').val(DEVICES[0].getAttribute(\"SystemConfigName\"));\n\t\t\t\t\t//$('#autoDSaveConfSecImg').val();\n\t\t\t\t\tvar rp1 = DEVICES[0].getAttribute(\"RP0ConsoleIp\").split(\":\");\n\t\t\t\t\tif(rp1!=\"\"){$('#autoDSaveRP1ConAdd').val(rp1[0]);}\n\t\t\t\t\tif(rp1!=\"\" && rp1.length>1){('#autoDSaveRP1ConPort').val(rp1[1]);}\n\t\t\t\t\t//$('#autoDSaveRP1AuxAdd').val();\n\t\t\t\t\t//$('#autoDSaveRP1AuxPort').val();\n\n\t\t\t\t\tvar rp2 = DEVICES[0].getAttribute(\"RP1ConsoleIp\").split(\":\");\n\t\t\t\t\tif(rp2!=\"\"){$('#autoDSaveRP2ConAdd').val(rp2[0]);}\n\t\t\t\t\tif(rp2!=\"\" && rp2.length>1){$('#autoDSaveRP2ConPort').val(rp2[1]);}\n\t\t\t\t\t//$('#autoDSaveRP2AuxAdd').val();\n\t\t\t\t\t//$('#autoDSaveRP2AuxPort').val();\n\t\t\t\t\t//$('#').val();\n\t\t\t\t}else{\n\t\t\t\t\tvar dat = data.replace(/'/g,'\"');\n\t\t\t var dat2 = $.parseJSON(dat);\n\t\t\t\t\tif(type){\n\t\t\t\t\t\tif(type==\"load\"){\n\t\t\t\t\t\t\tsaveAutoDDevNode = [];\n\t\t\t\t\t\t\t//pushdevices(DEVICES);\n\t\t\t\t\t\t\tgetDataForDeviceListJSON(dat2);\n\t\t\t\t\t\t\tdrawImage();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}else{saveAutoDDevNode = dat2;}\n\t\t\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\t\t\tassignValAutoDSave(dat2);\n\t\t\t\t\t}else{\n\t\t\t\t\n\t\t\t\t\t\t$( \"#autoDSaveDialog\" ).empty().append(\"<center id='processingPage'><div style='text-align:center;'>Processing Information...<br /><img src='img/ajax-loader.gif'/></div></center>\");\n\t\t\t\t\t\t$( \"#autoDSaveDialog\" ).load('pages/ConfigEditor/autoDSaveInfo.html',function(){\n\t\t\t\t\t\t\t$('.ui-dialog-title').css({'margin-left':'10px','text-align':'center','margin-top':'7px'});\n\t\t\t\t\t\t\t$('span.ui-dialog-title').text('Optional Device Information');\n\t\t\t\t\t\t\t$('#accordion').accordion();\n\t\t\t\t\t\t\t$(\"#autoDSaveDialog\").trigger('create');\n\n\t\t\t\t\t\t\t//$('#autoDSavePowerMan').hide();\n\t\t\t\t\t\t\t$('#autoDSaveFusionInfo').hide();\n\t\t\t\t\t\t\t$('#autoDSaveNATTableCont').hide();\n\t\t\t\t\t\t\tassignValAutoDSave(dat2);\n\n\t\t\t\t\t\t\t$(\".ui-dialog\").position({\n\t\t\t\t\t\t\t my: \"top\",\n\t\t\t\t\t\t\t at: \"top\",\n\t\t\t\t\t\t\t of: window\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t$('#processingPage').remove();\n\t\t\t\t\t\t\t$( \"#autoDSaveDialog\" ).width(1000);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tif(globalDeviceType=='Mobile'){\n\t\t\t\t}else{\n\t\t\t\t\t//$('#autoDSaveDialog').dialog('destroy');\n\t\t\t\t\t$('#autoDLogsDialog').dialog('destroy');\n\t\t\t\t}\n\t\t\t\tif(type==load){\n\t\t\t\t\tif(globalDeviceType==\"MOBILE\"){\n\t\t\t\t\t}else{\n\t\t\t\t\t\t$('#autoDSaveDialog').dialog('destroy');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\talerts(\"Process failed.\");return;\n\t\t\t}\n\t\t}\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the math node into a string, similar to innerText. Applies to MathDomNode's only.
toText() { // To avoid this, we would subclass documentFragment separately for // MathML, but polyfills for subclassing is expensive per PR 1469. // $FlowFixMe: Only works for ChildType = MathDomNode. const toText = child => child.toText(); return this.children.map(toText).join(""); }
[ "toNode() {\n if (this.character) {\n return document.createTextNode(this.character);\n } else {\n const node = document.createElementNS(\"http://www.w3.org/1998/Math/MathML\", \"mspace\");\n node.setAttribute(\"width\", this.width + \"em\");\n return node;\n }\n }", "toNode() {\n const node = document.createElementNS(\"http://www.w3.org/1998/Math/MathML\", this.type);\n\n for (const attr in this.attributes) {\n if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {\n node.setAttribute(attr, this.attributes[attr]);\n }\n }\n\n for (let i = 0; i < this.children.length; i++) {\n node.appendChild(this.children[i].toNode());\n }\n\n return node;\n }", "function buildMathML(tree, texExpression, options) {\n const expression = buildExpression$1(tree, options); // Wrap up the expression in an mrow so it is presented in the semantics\n // tag correctly, unless it's a single <mrow> or <mtable>.\n\n let wrapper;\n\n if (expression.length === 1 && expression[0] instanceof MathNode && utils.contains([\"mrow\", \"mtable\"], expression[0].type)) {\n wrapper = expression[0];\n } else {\n wrapper = new mathMLTree.MathNode(\"mrow\", expression);\n } // Build a TeX annotation of the source\n\n\n const annotation = new mathMLTree.MathNode(\"annotation\", [new mathMLTree.TextNode(texExpression)]);\n annotation.setAttribute(\"encoding\", \"application/x-tex\");\n const semantics = new mathMLTree.MathNode(\"semantics\", [wrapper, annotation]);\n const math = new mathMLTree.MathNode(\"math\", [semantics]); // You can't style <math> nodes, so we wrap the node in a span.\n // NOTE: The span class is not typed to have <math> nodes as children, and\n // we don't want to make the children type more generic since the children\n // of span are expected to have more fields in `buildHtml` contexts.\n // $FlowFixMe\n\n return buildCommon.makeSpan([\"katex-mathml\"], [math]);\n }", "toSTRING() {\n switch (this._type) {\n case \"NODE\":\n return this._value.nodeType === 1 ? this._value.outerHTML : this._value.nodeValue;\n case \"STRING\":\n return this._value;\n case \"YNGWIE\":\n console.log(this._value);\n let node = this._value.render();\n console.log(node)\n return node.nodeType === 1 ? node.outerHTML : node.nodeValue;\n default:\n throw new _Transform_main_js__WEBPACK_IMPORTED_MODULE_3__.default(\"Cannot transform to STRING from unsuppoted type\", this._value);\n }\n }", "string(node) {\n if (Text.isText(node)) {\n return node.text;\n } else {\n return node.children.map(Node$1.string).join('');\n }\n }", "function convertToMath() {\n\treturn eval(getId('result').value);\n}", "function formatMath(expr) {\n\treturn `${expr} = ${eval(expr.replace(\"x\", \"*\"))}`\n}", "function extUtils_convertNodeToString(node)\n{\n // NOTE: This function should employ some sort of caching mechanism\n var nodeStr = \"\";\n\n if (!node)\n {\n //do nothing, return blank string\n }\n else\n {\n nodeStr = dwscripts.getOuterHTML(node);\n\n if (!nodeStr && node.data)\n {\n nodeStr = node.data; //get just data in the case of comments or text\n }\n }\n\n return nodeStr;\n}", "function Math(props) {\n let value;\n\n // Assign value based on the operator\n switch (props.operator) {\n case \"+\":\n value = props.num1 + props.num2;\n break;\n case \"-\":\n value = props.num1 - props.num2;\n break;\n case \"*\":\n value = props.num1 * props.num2;\n break;\n case \"/\":\n value = props.num1 / props.num2;\n break;\n default:\n value = NaN;\n }\n\n // Return a span element containing the calculated value\n // Set the fontSize to the value in pixels\n return <span style={{ fontSize: value }}>{value}</span>;\n}", "infixStr() {\n const go = (node) => {\n if(node === null) return \"\";\n else if(node.isLeaf()) return `${node.value}`;\n else\n return `${go(node.left)} ${node.value} ${go(node.right)}`;\n };\n return go(this.root);\n }", "function nodeString(node) {\n return String(node.getString());\n }", "toHtml() {\n let node = createSpan(\"term\");\n if (this.items.length == 0 && this.charge == -1) {\n node.textContent = \"e\";\n node.append(createElem(\"sup\", MINUS));\n }\n else {\n for (const item of this.items)\n node.append(item.toHtml());\n if (this.charge != 0) {\n let s;\n if (Math.abs(this.charge) == 1)\n s = \"\";\n else\n s = Math.abs(this.charge).toString();\n if (this.charge > 0)\n s += \"+\";\n else\n s += MINUS;\n node.append(createElem(\"sup\", s));\n }\n }\n return node;\n }", "function quillGetText(quill) {\n var contents = quill.getContents();\n var quillText = \"\";\n\n for (op of contents.ops) {\n var opInsert = op.insert;\n if (opInsert == \"[object Object]\") { //If the op is inserting a formula, insert a single char instead to simulate single index\n opInsert = \"O\"; //Arbitrary value to represent a formula\n }\n quillText = quillText.concat(opInsert);\n }\n return quillText;\n}", "function getInlineTextValue(node)\n{\n if (( typeof node == 'undefined') || node == null)\n return \"\";\n\n if (isBackend) {\n return node.value;\n } else {\n var textValue = \"\";\n if(node.innerText){ // IE, Chrome, Opera\n textValue = node.innerText;\n } else {\n // Firefox\n // Note: there's no need to check <BR>, <br/> etc. as innerHTML unifies that to <br>\n textValue = node.innerHTML.replace(/<br>/gi, '\\n').replace(/(<([^>]+)>)/gi,\"\");\n }\n return textValue;\n }\n}", "function convert_tree_to_expression(root) {\n // checks if the root of the tree is null, if it is prints out error to console\n if(root == null) {\n console.log(\"Error: The tree or subtree has a null value in its root\");\n return null;\n }\n\n // base case for recursion\n // if the node is a leaf it will just return its own value\n if(root.leftChild == null && root.rightChild == null)\n return root.value;\n\n // the root's value is added to the expression when it is determined is\n // an internal node of the binary tree\n var string = root.value;\n // adds opening bracket, in which the children of the node will be added\n string += \"(\";\n // makes recursive call on left child if it exists, in the format in which\n // our example expressions are written there will always be a left node\n\tif(root.leftChild != null) {\n\t\tstring += convert_tree_to_expression(root.leftChild);\n }\n // make recursive call on right child if it exists\n // adds comma to separate the left and right children of the node\n\tif(root.rightChild != null){\n\t\tstring += \",\";\n\t\tstring += convert_tree_to_expression(root.rightChild);\n }\n // add closing bracket to close the expression described by the node's children\n string += \")\";\n\n // return the string that has the expression that describes the binary tree\n // rooted at the node passed into this function\n return string;\n}", "function NodeSegment_toString()\n{\n var retVal = \"\";\n\n retVal = dwscripts.getOuterHTML(this.node);\n\n retVal = retVal.substring(this.matchRangeMin, this.matchRangeMax);\n\n return retVal;\n}", "function getHtmlExprStmt(e, sO, parentPath, myPos) {\r\n\r\n\r\n var ret = \"\"; // returned html string\r\n\r\n var myPath = parentPath + e.mySeq + \":\"; // path to this node\r\n\r\n // record active parent expression in sO. This is the way we obtain\r\n // an ExprObj that correspond to a path string. \r\n //\r\n if (myPath == sO.activeParentPath) {\r\n sO.activeParentExpr = e;\r\n }\r\n\r\n\r\n if (e.deleted == DeletedState.Deleted) { // if expr is deleted\r\n\r\n ret = \"<span style='color:red'>\" + DefDeletedName + \"</span>\";\r\n\r\n } else if (e.deleted == DeletedState.NeedUpdate) { // if expr needs update\r\n\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n ret = \"<span style='color:red' \" + oncE + \">\" + DefNeedUpdateName +\r\n \"</span>\";\r\n\r\n } else if (e.deleted == DeletedState.PlaceHolder) { // if place holder\r\n\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n ret = \"<span style='color:orange' \" + oncE + \">\" + e.str +\r\n \"</span>\";\r\n\r\n } else if (e.isFuncCall()) {\r\n\r\n\tvar args = \"\"; // arguments within ( )\r\n\tvar numargs = e.exprArr.length;\r\n\r\n\tfor (var i=0; i <= numargs; i++) { // note '<='\r\n\r\n // onclick and properties for spaces within the function call.\r\n // spaces are used as insertion points (similar to in a stmt)\r\n //\r\n var oncS_args = \"\\\"\" + myPath + \"\\\",\" + i;\r\n var oncS = \" onclick='spaceClicked(\" + oncS_args + \")' \";\r\n var sprop = oncS; // child space is clickable\r\n var cprop = \"\"; // child's properties\r\n\r\n if ((i > 0) && (i < numargs)) args += \",\";\r\n\r\n // if this child is active (highlighted expr/space)\r\n //\r\n if ((myPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n i)) {\r\n\r\n if (!sO.isSpaceActive)\r\n cprop = \" style='background-color:#dcffed' \";\r\n else\r\n sprop += \" class='scursor' \";\r\n }\r\n\r\n // First add space, and then add spans for child expression\r\n //\r\n args += \"<span \" + sprop + \">&nbsp</span>\";\r\n // \r\n if (i < numargs) {\r\n\r\n var ccont = getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n args += \"<span \" + cprop + \">\" + ccont + \"</span>\";\r\n }\r\n\r\n } // for all args\r\n\r\n\r\n // put onclick function and cursor changing for func name\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='funcClicked(\" + onc_args + \")' \";\r\n var fprop = oncE + \" style='cursor:pointer' \";\r\n //\t\r\n // If the function name is already highlighted, clicking on it again\r\n // makes the function name editable\r\n //\r\n if ((parentPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n myPos)) {\r\n //var onin_args = \" oninput=\\\"updateFuncName(this)\\\" \"; \r\n var onin_args = \" onblur=\\\"updateFuncName(this)\\\" \";\r\n fprop += \" contenteditable \" + onin_args;\r\n }\r\n ret = \"<span \" + fprop + \">\" + e.str + \"</span>(\" + args + \")\";\r\n //+ \"<span \" + fprop + \">)</span>\";\r\n\r\n\r\n\r\n } else if (e.isGridCell()) {\r\n\r\n // Note: it is my parent's (callers) repsonsibility to put a span \r\n // around me (whole grid), with highlight if necessary. My\r\n // resposnsibility is to highlight a selected child. It's always\r\n // child resposnbility to handle onclick. \r\n // Note: There are no child spaces within a grid, so no space handling\r\n // is necessary\r\n //\r\n var gcont = \"\"; // grid contents within [ ]\r\n\r\n for (var i = 0; i < e.exprArr.length; i++) {\r\n\r\n var cprop = \"\";\r\n if (i > 0) gcont += \",\";\r\n\r\n // highlight my child (and all its children), if he has been\r\n // selected (clicked on) by the user\r\n //\r\n if ((myPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n i)) {\r\n\r\n cprop = \" style='background-color:#dcffed' \";\r\n }\r\n\r\n var ccont = getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n gcont += \"<span \" + cprop + \">\" + ccont + \"</span>\";\r\n\r\n }\r\n\r\n // put onclick function and cursor changing for grid name\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n var gprop = oncE + \" style='cursor:pointer' \";\r\n //\t\r\n var brack1 = (e.exprArr && e.exprArr.length) ? \"[\" : \"\";\r\n var brack2 = (e.exprArr && e.exprArr.length) ? \"]\" : \"\";\r\n //\r\n var cap = e.gO.caption; // if gO.caption updated, use that\r\n //\r\n ret = \"<span \" + gprop + \">\" + cap + brack1 + \"</span>\" + gcont +\r\n \"<span \" + gprop + \">\" + brack2 + \"</span>\";\r\n\r\n\r\n } else if (e.isStatement()) { // an assignment/if statement (expr statement)\r\n\r\n // Just go thru the exprArr in sequence and collect (print) all\r\n // the html values\r\n // Note: This is the case for handling the root node\r\n // Note: i includes exprArr.length, to handle the trailing space\r\n //\r\n for (var i = 0; i <= e.exprArr.length; i++) {\r\n\r\n var oncS_args = \"\\\"\" + myPath + \"\\\",\" + i;\r\n var oncS = \" onclick='spaceClicked(\" + oncS_args + \")' \";\r\n\r\n // Every child is always 'clickable' individually\r\n //\r\n var cprop = \"\";\r\n var sprop = oncS; // child space is clickable\r\n\r\n //alert(\"mypath:\" + myPath + \" cpos:\" + i);\r\n\r\n // if this child is active (highlighted)\r\n //\r\n if ((myPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n i)) {\r\n\r\n // alert(\"last space active\");\r\n\r\n // this child exprssion/space is selected. A selected\r\n // child is highlighted \r\n //\r\n if (!sO.isSpaceActive)\r\n cprop = \" style='background-color:#dcffed' \";\r\n else\r\n sprop += \" class='scursor' \";\r\n\r\n\r\n } else {\r\n // For showing where the spaces are\r\n // sprop += \" style='background-color:#fafafa' \";\r\n }\r\n\r\n // First add space, and then add spans for child expression\r\n // We insert insertion spaces only if a statement is editable\r\n //\r\n ret += \"<span \" + sprop + \">&nbsp</span>\";\r\n // \r\n if (i < e.exprArr.length) {\r\n\r\n var ccont = getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n ret += \"<span \" + cprop + \">\" + ccont + \"</span>\";\r\n\r\n }\r\n }\r\n\r\n // STEP: \r\n // Handle the leading *keyword* like if/else/elseif/foreach/...\r\n // NOTE: These keywords are NOT childrend of expression 'e' but\r\n // keywords are stroted in e.str which is the node itself.\r\n // in such cases, ROOTPOS is used as the child pos w/ \r\n // myPath (not parentPath + childPos)\r\n //\r\n if (e.isCondition() || e.isLoopStmt()) {\r\n\r\n // put onclick function and cursor changing\r\n // Note: since this is the root node property, we use myPath\r\n // instead of parentPath (plus ROOTPOS)\r\n //\r\n var onc_args = \"\\\"\" + myPath + \"\\\",\" + ROOTPOS;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n var gprop = oncE;\r\n //\t\r\n // if the keyword (at ROOTPS) is selected, highlight it\r\n // NOTE: keyword is in e.str and hence we use ROOTPOS as childPos\r\n //\r\n if ((sO.activeParentPath == myPath) &&\r\n (sO.activeChildPos == ROOTPOS)) {\r\n\r\n gprop += \" style='background-color:#dcffed'\";\r\n\r\n } else {\r\n gprop += \" style='cursor:pointer' \";\r\n }\r\n //\r\n if (!(ret == \"\") && (e.isIf() || e.isElseIf() || e.isBreakIf()))\r\n ret = \" (\" + ret + \")\";\r\n //\r\n ret = \"&nbsp;<span \" + gprop + \">\" + e.str + \"</span>\" + ret;\r\n\r\n }\r\n\r\n\r\n } else if (e.isRange()) {\r\n\r\n // Note: There are no child spaces within a range, so no space handling\r\n // is necessary\r\n //\r\n var rcont = \"\"; // range contents within ( )\r\n\r\n // whether the range name 'e.g., row, col' is highlighted by my parent\r\n //\r\n var amIhigh = (parentPath == sO.activeParentPath) &&\r\n (myPos == sO.activeChildPos);\r\n\r\n // if my parent has highlighted me OR if I am highligting a child of\r\n // mine like start/end/step, only then print start/step/end\r\n //\r\n if (amIhigh || (myPath == sO.activeParentPath)) {\r\n\r\n // Tool tips for each of he fields in the range\r\n //\r\n var rtips = ['grid name', 'start', 'end', 'step'];\r\n\r\n // For production caption/start/end/step. The output should\r\n // look like caption(start:end:step)\r\n //\r\n for (var i = 0; i < e.exprArr.length; i++) {\r\n\r\n // Add tool tip\r\n //\r\n var cprop = \" title='\" + rtips[i] + \"' \";\r\n\r\n if (i == 1) rcont += \"(\"; // after grid caption\r\n if (i > 1) rcont += \":\"; // after start/end\r\n\r\n // if this child is active (highlighted)\r\n //\r\n if ((myPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n i)) {\r\n\r\n cprop += \" style='background-color:#dcffed' \";\r\n }\r\n\r\n var ccont = getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n\r\n // alert(\"cont: \" + ccont);\r\n\r\n rcont += \"<span \" + cprop + \">\" + ccont + \"</span>\";\r\n }\r\n\r\n // put = ) around the 'caption(start:end:step' produced above\r\n //\r\n rcont = \"=\" + rcont + \")\";\r\n }\r\n\r\n // put onclick function and cursor changing for grid name\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='rangeClicked(\" + onc_args + \")' \";\r\n var rprop = oncE + \" style='cursor:pointer' \";\r\n rprop += \" title='index variable name' \";\r\n //\t\r\n ret = \"<span \" + rprop + \">\" + e.labelExpr.str + \"</span>\" +\r\n rcont;\r\n\r\n\r\n } else if (e.isLet()) {\r\n\r\n\r\n // This is a let definition (i.e., at position 0). Non definition\r\n // let names are handled as a regular leaf case\r\n\r\n // put onclick function for 'let' keyword\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos + \",\" + sO.curBox\r\n var oncLet = \" onclick='letClicked(\" + onc_args + \")' \";\r\n\r\n\r\n // Use mouse down/up functions on the let 'name'. Click and press to\r\n // edit. \r\n //\r\n var oncName = \" onmousedown='letNameMouseDown(\" + onc_args +\r\n \",this)' \" + \" onmouseup='letNameMouseUp(\" + onc_args +\r\n \",this)' \";\r\n\r\n var namestr = \"\";\r\n\r\n // the identifier for let is always at the 0th position\r\n //\r\n var ident = e.exprArr[0].str;\r\n\r\n // if this let definition is already selected, enable editing\r\n // of the let name. Otherwise, change cursor and font color to \r\n // show it is a clickable definition\r\n //\r\n if ((parentPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n myPos)) {\r\n //var onin_args = \" oninput=\\\"updateLetName(this)\\\" \"; \r\n var onin_args = \" onblur=\\\"updateLetName(this)\\\" \";\r\n oncName = \" contenteditable \" + onin_args;\r\n\r\n // NOTE: For some odd reason, we cannot put a space just before\r\n // the equal sign -- after </span> with contenteditable\r\n //\r\n namestr = \"<span \" + oncName + \">\" + ident + \"</span>=\";\r\n\r\n\r\n } else {\r\n\r\n // this let definition is not active. So, just draw it\r\n //\r\n oncName += \" style='cursor:pointer;color:brown' \";\r\n namestr = \"<span \" + oncName + \">\" + ident + \"</span> =\";\r\n\r\n }\r\n\r\n // Put let keyword and name\r\n //\r\n ret = \"<span \" + oncLet + \">let </span>\" + namestr;\r\n\r\n\r\n } else if (e.isLeaf()) { // any other leaf expr not handled above\r\n\r\n // Note: leaves like operators, indices are handled here\r\n //\r\n // Note: put leaf processing at the end because there are other\r\n // leaf expressions handled above which require special \r\n // handling\r\n // Note: Since this is a leaf, no highlighting is involved. \r\n // Highlighting is always parent's responsibility. However,\r\n // onclick handling for an expr is always child's responsibility.\r\n // For onclick, we need parent's seq# and my position --\r\n // position of e -- in parents exprArr().\r\n\r\n // if the leaf is selected (highlighted), in some cases we need to \r\n // allow editing of the leaf (e.g., for a number/string constant)\r\n //\r\n var prop = \"\";\r\n //\r\n if ((parentPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n myPos)) {\r\n\r\n if (e.isNumber()) {\r\n prop = \" contenteditable onblur=\\\"updateNumber(this)\\\" \";\r\n } else if (e.isString()) {\r\n prop = \" contenteditable onblur=\\\"updateString(this)\\\" \";\r\n }\r\n }\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n var quote = (e.isString()) ? \"'\" : \"\";\r\n //\r\n ret = quote + \"<span \" + oncE + prop + \">\" + e.str + \"</span>\" +\r\n quote;\r\n\r\n } else if (e.isConcat()) {\r\n\r\n //alert(\"Concat\");\r\n\r\n // if this is an index concatanation -- e.g., col+4\r\n //\r\n var cont = \"\"; // contents of the concatenated index expr\r\n //\r\n for (var i = 0; i < e.exprArr.length; i++) {\r\n\r\n // No highlighting of children in index conacatenation\r\n //\r\n cont += getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n }\r\n\r\n // Put a span and onclick function around this concatenated \r\n // expression (since the entire concatenated expression is treate\r\n // as a leaf)\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n ret = \"<span \" + oncE + \">\" + cont + \"</span>\";\r\n\r\n\r\n } else {\r\n\r\n alert(\"TODO: Handle expression not handled above\");\r\n }\r\n\r\n\r\n return ret;\r\n\r\n}", "toHtml(coefs) {\n if (coefs !== undefined && coefs.length != this.leftSide.length + this.rightSide.length)\n throw new RangeError(\"Mismatched number of coefficients\");\n let node = document.createDocumentFragment();\n let j = 0;\n function termsToHtml(terms) {\n let head = true;\n for (const term of terms) {\n const coef = coefs !== undefined ? coefs[j] : 1;\n if (coef != 0) {\n if (head)\n head = false;\n else\n node.append(createSpan(\"plus\", \" + \"));\n if (coef != 1) {\n let span = createSpan(\"coefficient\", coef.toString().replace(/-/, MINUS));\n if (coef < 0)\n span.classList.add(\"negative\");\n node.append(span);\n }\n node.append(term.toHtml());\n }\n j++;\n }\n }\n termsToHtml(this.leftSide);\n node.append(createSpan(\"rightarrow\", \" \\u2192 \"));\n termsToHtml(this.rightSide);\n return node;\n }", "function wordedMath(expr) {\n\tconst a = expr.toLowerCase().split(\" \");\n\tconst b = [];\n\tfor (let i = 0; i < a.length; i++) {\n\t\tswitch (a[i]) {\n\t\t\tcase \"zero\": b.push(\"0\");\n\t\t\t\tbreak;\n\t\t\tcase \"one\": b.push(\"1\");\n\t\t\t\tbreak;\n\t\t\tcase \"plus\": b.push(\"+\");\n\t\t\t\tbreak;\n\t\t\tcase \"minus\": b.push(\"-\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tif (eval(b.join(\" \")) === 0) {\n\t\treturn \"Zero\";\n\t} else \tif (eval(b.join(\" \")) === 1) {\n\t\treturn \"One\";\n\t} else \tif (eval(b.join(\" \")) === 2) {\n\t\treturn \"Two\";\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create the necessary PredictionLink to predict each candidate from the other
function linkCandidates(predictor, predictee) { message("linking candidates " + predictor.getName().getName() + " and " + predictee.getName().getName() + "\r\n"); var frequencyCountA = predictor.getNumFrequencyEstimators(); var ratingCountA = predictor.getNumRatingEstimators(); var frequencyCountB = predictee.getNumFrequencyEstimators(); var ratingCountB = predictee.getNumRatingEstimators(); var i, j; // using the frequency of A, try to predict the rating for B for (i = 0; i < frequencyCountA; i++) { message("getting frequency estimator\r\n"); var predictorAverage = predictor.getFrequencyEstimatorAtIndex(i); message("getting actual rating history\r\n"); var predicteeAverage = predictee.getActualRatingHistory(); message("linking averages\r\n"); this.linkAverages(predictorAverage, predicteeAverage); } // using the frequency of B, try to predict the rating for A /*for (j = 0; j < frequencyCountB; j++) { this.linkAverages(predictee.getFrequencyEstimatorAtIndex(j), predictor.getActualRatingHistory()); }*/ // using the rating for A, try to predict the rating for B for (i = 0; i < ratingCountA; i++) { this.linkAverages(predictor.getRatingEstimatorAtIndex(i), predictee.getActualRatingHistory()); } // using the rating for B, try to predict the rating for A /*for (j = 0; j < ratingCountB; j++) { this.linkAverages(predictee.getRatingEstimatorAtIndex(j), predictor.getActualRatingHistory()); }*/ }
[ "function predictBotOrTrolls(msgs) {\n // console.debug('predictBotOrTrolls:', msgs.length, msgs)\n\n // Will keep predictions in order after async POST to web service\n let predictions = []\n msgs.forEach((msg, m) => {\n const data = {\n ups: msg.ups,\n score: msg.score,\n controversiality: msg.controversiality ? 1 : 0,\n author_verified: msg.author_verified ? 1 : 0,\n no_follow: msg.no_follow ? 1 : 0,\n over_18: msg.over_18 ? 1 : 0,\n author_comment_karma: msg.author_comment_karma,\n author_link_karma: msg.author_link_karma,\n is_submitter: msg.is_submitter ? 1 : 0\n }\n\n // Integrate ML web service\n unirest\n .post('https://botidentification-comments.herokuapp.com/')\n .type('json')\n .send(data)\n .end((res) => {\n // console.debug('data sent', JSON.stringify(data))\n // TODO: Handle errors?\n if (2 != res.statusType) {\n // 2 = Ok 5 = Server Error\n console.error('Response not OK, HTTP code', res.code)\n console.error('Data sent', JSON.stringify(data))\n console.error('Response body', res.body)\n }\n // console.debug('res.body', res.body)\n predictions[m] = 2 == res.statusType ? res.body : { prediction: null }\n predictions[m].username = msg.author\n predictions[m].comment_prev = `${msg.body.slice(0, 200)}...`\n predictions[m].datetime = moment\n .unix(msg.created_utc)\n .format('MMM Do HH:mm:ss z')\n predictions[m].link_hash = msg.link_id.slice(3)\n\n // Determine behavior\n switch (predictions[m].prediction) {\n case 'Is a normal user':\n predictions[m].behavior = 'normal'\n break\n case 'Is a Bot':\n predictions[m].behavior = 'bot'\n break\n case 'Is a Troll':\n predictions[m].behavior = 'troll'\n break\n default:\n predictions[m].behavior = 'unknown'\n }\n // console.debug('prediction', m, predictions[m])\n\n // Push to wss once all messages have been predicted.\n // Anon fn. below counts non-empty elements in `predictions`\n if (\n msgs.length == predictions.reduce((ac, cv) => (cv ? ac + 1 : ac), 0)\n ) {\n // console.debug(m, `Pushing ${msgs.length} predictions to wss`)\n wss.clients.forEach((client) =>\n client.send(JSON.stringify(predictions))\n )\n }\n })\n //unirest.post\n })\n}", "function PredPrediction(pred, alt) {\n this.alt = alt;\n this.pred = pred;\n return this;\n}", "function setLinkIndexAndNum()\r\n {\r\n for (var i = 0; i < finalResult[1].length; i++)\r\n {\r\n if (i != 0 &&\r\n finalResult[1][i].source == finalResult[1][i - 1].source &&\r\n finalResult[1][i].target == finalResult[1][i - 1].target)\r\n {\r\n finalResult[1][i].linkindex = finalResult[1][i - 1].linkindex + 1;\r\n }\r\n else\r\n {\r\n finalResult[1][i].linkindex = 1;\r\n }\r\n // save the total number of links between two nodes\r\n if (mLinkNum[finalResult[1][i].target + \",\" + finalResult[1][i].source] !== undefined)\r\n {\r\n mLinkNum[finalResult[1][i].target + \",\" + finalResult[1][i].source] = finalResult[1][i].linkindex;\r\n }\r\n else\r\n {\r\n mLinkNum[finalResult[1][i].source + \",\" + finalResult[1][i].target] = finalResult[1][i].linkindex;\r\n }\r\n }\r\n }", "function use_nueral_net_before_storing(networky,array_to_predict_20) {\n\t var prediction; \nprediction = networky.activate(array_to_predict_20)\n//console.log( prediction);\nreturn prediction;\n}", "function cascade()\r\n{\r\n\ttest_data.read_train_from_file('./parity8.train');\r\n\ttrain_data.read_train_from_file('./parity8.test');\r\n\r\n\tvar input = train_data.num_input_train_data()\r\n\tvar output = train_data.num_output_train_data()\r\n\r\n\tconsole.log( ' input: ', input );\r\n\tconsole.log( 'output: ', output );\r\n\r\n\ttrain_data.scale_train_data( -1, 1);\r\n\ttest_data.scale_train_data( -1, 1);\r\n\t\r\n\t\r\n\tfann.create_shortcut(2, input, output );\r\n\t\r\n\tfann.set_training_algorithm( 2 ); // FANN_TRAIN_RPROP;\r\n\tfann.set_activation_function_hidden( 5 ); // ann, FANN_SIGMOID_SYMMETRIC\r\n\tfann.set_activation_function_output( 0 ); // ann, FANN_LINEAR\r\n\tfann.set_train_error_function( 0 );\t // ann, FANN_ERRORFUNC_LINEAR\r\n\t\r\n\t\r\n\tvar testdata = []\r\n\tvar result = fann.run( testdata );\r\n\r\n\tconsole.log( 'result:', result[0] );\r\n\t\r\n}", "function trainModel() {\n app.models.train(\"pets\").then(\n (response) => {\n console.log(response);\n },\n (error) => {\n console.error(error);\n } \n );\n}", "predictions(agencyTag, stops, cb) {\n var predictions = [ ],\n sliceSize = 150,\n concurrentRequestsCount = 0;\n\n var slices = [ ],\n sliceIndex = 0;\n if (stops.length <= sliceSize) {\n slices.push(stops);\n } else {\n for (var i = 0; i < stops.length; i += sliceSize) {\n slices.push(stops.slice(i, i + sliceSize));\n }\n }\n\n var waitForRequestsEnd = function() {\n if (concurrentRequestsCount > 0) {\n return;\n }\n\n cb(predictions);\n }.bind(this);\n\n var queryPredictionsForMultiStopBySlices = function(sliceIndex) {\n var currentPredictions,\n currentDirection;\n\n this._newRequest().query({\n command: 'predictionsForMultiStops', a: agencyTag, stops: slices[sliceIndex] }, function(e) {\n switch(e.name) {\n case 'error':\n cb(null, e.data);\n break;\n\n case 'opentag':\n var tag = e.data;\n var attributes = tag.attributes;\n \n if (tag.name === 'predictions') {\n currentPredictions = {\n routeTag: attributes.routeTag,\n stopTag: attributes.stopTag,\n directions: [ ],\n messages: [ ]\n };\n\n predictions.push(currentPredictions);\n } else if (tag.name === 'direction') {\n currentDirection = {\n title: attributes.title,\n predictions: [ ]\n };\n\n currentPredictions.directions.push(currentDirection);\n } else if (tag.name === 'prediction') {\n currentDirection.predictions.push({\n time: attributes.epochTime,\n seconds: parseInt(attributes.seconds),\n minutes: parseInt(attributes.minutes),\n isDeparture: attributes.isDeparture === 'true' ? true : false,\n delayed: attributes.delayed === 'true' ? true : false,\n slowness: attributes.slowness ? parseFloat(attributes.slowness) : undefined,\n affectedByLayover: attributes.affectedByLayover === 'true' ? true : false,\n dirTag: attributes.dirTag,\n vehicle: attributes.vehicle,\n block: attributes.block,\n tripTag: attributes.tripTag,\n branch: attributes.branch\n });\n } else if (tag.name === 'message') {\n currentPredictions.messages.push({\n text: attributes.text,\n priority: attributes.priority,\n });\n }\n break;\n\n case 'end':\n concurrentRequestsCount--;\n waitForRequestsEnd();\n break;\n }\n });\n };\n\n var tryToRequest = function() {\n if (concurrentRequestsCount >= this._maxConcurrentRequests) {\n setTimeout(tryToRequest.bind(this), 100);\n return;\n }\n\n concurrentRequestsCount++;\n\n process.nextTick(queryPredictionsForMultiStopBySlices.bind(this, sliceIndex));\n sliceIndex++;\n\n if (sliceIndex === slices.length) {\n return;\n }\n\n process.nextTick(tryToRequest.bind(this));\n }.bind(this);\n\n tryToRequest();\n }", "train() {\n this.settings.classifier.clear();\n this.docs.forEach((doc) => {\n this.settings.classifier.addObservation(this.textToFeatures(doc.utterance), doc.intent);\n });\n if (this.settings.classifier.observationCount > 0) {\n this.settings.classifier.train();\n }\n }", "linkMutate() {\n debug(\"Performing link mutation\");\n let neuron1 = this.getRandomNeuron(false);\n let neuron2 = this.getRandomNeuron(true);\n\n const gene = new Gene()\n if (neuron1.id < INPUT_NEURONS && neuron2.id < INPUT_NEURONS) {\n // Both input nodes, we can't link these\n return;\n }\n\n if (neuron1.id < neuron2.id) {\n gene.from = neuron1.id;\n gene.to = neuron2.id;\n } else {\n gene.from = neuron2.id;\n gene.to = neuron1.id;\n }\n\n if (this.hasSameGene(gene)) {\n // Don't want two links betwen the same pair of neurons\n return;\n }\n\n gene.innovation = Innovation.getNext();\n gene.weight = Math.random() * 4 - 2;\n\n debug(\"Inserting new gene: \", gene);\n this.genes.push(gene);\n }", "iterate() {\n var i;\n var link_id;\n var exp_id;\n var link_from, link_to;\n var link;\n var lx, ly, df;\n\n\n for (i = 0; i < this.EXP_LOOPS; i++) {\n for (exp_id = 0; exp_id < this.experiences.length; exp_id++) {\n link_from = this.experiences[exp_id];\n\n for (link_id = 0; link_id < link_from.links_from.length; link_id++) {\n //% //% experience 0 has a link to experience 1\n link = this.links[link_from.links_from[link_id]];\n link_to = this.experiences[link.exp_to_id];\n\n //% //% work out where e0 thinks e1 (x,y) should be based on the stored\n //% //% link information\n lx = link_from.x_m + link.d * Math.cos(link_from.th_rad + link.heading_rad);\n ly = link_from.y_m + link.d * Math.sin(link_from.th_rad + link.heading_rad);\n\n //% //% correct e0 and e1 (x,y) by equal but opposite amounts\n //% //% a 0.5 correction parameter means that e0 and e1 will be fully\n //% //% corrected based on e0's link information\n link_from.x_m += (link_to.x_m - lx) * this.EXP_CORRECTION;\n link_from.y_m += (link_to.y_m - ly) * this.EXP_CORRECTION;\n link_to.x_m -= (link_to.x_m - lx) * this.EXP_CORRECTION;\n link_to.y_m -= (link_to.y_m - ly) * this.EXP_CORRECTION;\n\n //% //% determine the angle between where e0 thinks e1's facing\n //% //% should be based on the link information\n df = gri.get_signed_delta_rad(link_from.th_rad + link.facing_rad, link_to.th_rad);\n\n //% //% correct e0 and e1 facing by equal but opposite amounts\n //% //% a 0.5 correction parameter means that e0 and e1 will be fully\n //% //% corrected based on e0's link information\n link_from.th_rad = gri.clip_rad_180(link_from.th_rad + df * this.EXP_CORRECTION);\n link_to.th_rad = gri.clip_rad_180(link_to.th_rad - df * this.EXP_CORRECTION);\n }\n }\n }\n\n return true;\n }", "function classifyPose() {\n if (pose) {\n let inputs = [];\n // Create input ignoreing hips and legs\n for (let i = 0; i < pose.keypoints.length - 6; i++) {\n let x1 = pose1.keypoints[i].position.x;\n let y1 = pose1.keypoints[i].position.y;\n let x2 = pose2.keypoints[i].position.x;\n let y2 = pose2.keypoints[i].position.y;\n let x3 = pose3.keypoints[i].position.x;\n let y3 = pose3.keypoints[i].position.y;\n inputs.push(x1);\n inputs.push(y1);\n inputs.push(x2);\n inputs.push(y2);\n inputs.push(x3);\n inputs.push(y3);\n }\n // Classify pose\n brain.classify(inputs, gotResult);\n }\n // else {\n // setTimeout(classifyPose, 100);\n // }\n}", "function classifyOtherPlayerPose() {\n if (otherPlayerPose) {\n let inputs = [];\n for (let i = 0; i < otherPlayerPose.keypoints.length; i++) {\n let x = otherPlayerPose.keypoints[i].position.x;\n let y = otherPlayerPose.keypoints[i].position.y;\n inputs.push(x);\n inputs.push(y);\n }\n brain.classify(inputs, gotOtherPlayerResult);\n } else {\n setTimeout(classifyOtherPlayerPose, 1000);\n }\n}", "function LDAModel(kernelP, refIdP) {\n this.kernelP = kernelP;\n this.refIdP = refIdP;\n}", "function separate() {\n // Training set is first part of data set.\n const trainingSetX = xSet.slice(0, separationSize);\n const trainingSetY = ySet.slice(0, separationSize);\n train(trainingSetX, trainingSetY);\n\n // Test (verification) set is latter part of data set.\n const testSetX = xSet.slice(separationSize);\n const testSetY = ySet.slice(separationSize);\n test(testSetX, testSetY);\n}", "function rateCandidate(candidate, when) {\n \n message(\"rating candidate with name: \" + candidate.getName().getName());\n printCandidate(candidate);\n var parents = candidate.getParents();\n var guesses = [];\n var currentDistribution;\n var i;\n var currentParent;\n // make sure that all of the parents are rated first\n for (i = parents.length - 1; i >= 0; i--) {\n currentParent = parents[i];\n // figure out if the parent was rated recently enough\n if (strictlyChronologicallyOrdered(currentParent.getLatestRatingDate(), when)) {\n // if we get here then the parent rating needs updating\n this.rateCandidate(currentParent, when);\n }\n }\n // Now get the prediction from each relevant link\n var shortTermAverageName = candidate.getActualRatingHistory().getName().getName();\n var links = predictionLinks[shortTermAverageName];\n var mapIterator = Iterator(links);\n\t var predictorName;\n\t var currentLink;\n\t var currentGuess;\n\t var predicteeName = candidate.getName().getName();\n\t // iterate over all relevant prediction links\n\t var childWeight = 0;\n for ([predictorName, currentLink] in mapIterator) {\n currentLink.update();\n message(\"Predicting \" + predicteeName + \" from \" + predictorName, 0);\n currentGuess = currentLink.guess(when);\n message(\" score: \" + currentGuess.getMean() + \"\\r\\n\", 0);\n //printDistribution(currentGuess);\n guesses.push(currentGuess);\n childWeight += currentGuess.getWeight();\n }\n var parentScale;\n if (childWeight < 1)\n parentScale = 1;\n else\n parentScale = 1 / childWeight;\n for (i = 0; i < parents.length; i++) {\n currentGuess = parents[i].getCurrentRating();\n guesses.push(new Distribution(currentGuess.getMean(), currentGuess.getStdDev(), currentGuess.getWeight() * parentScale));\n }\n \n \n // In addition to all of the above factors that may use lots of data to predict the rating\n // of the song, we should also use some other factors.\n // We want to:\n // Never forget a song completely\n // Avoid playing a song twice in a row without explicit reason to do so\n // Believe the user's recent ratings\n \n \n // We don't want to ever completely forget about a song. So, move it slowly closer to perfection\n // Whenever they give it a rating or listen to it, this resets\n var remembererDuration = candidate.getIdleDuration(when);\n if (remembererDuration < 1)\n\t\t remembererDuration = 1;\n\t\t \n\t\t// The goal is to make d = sqrt(t) where d is the duration between listenings and t = num seconds\n\t // Then n = sqrt(t) where n is the number of ratings\n\t // If the user reliably rates a song down, then for calculated distributions, stddev = 1 / n = 1 / sqrt(t) and weight = n = sqrt(t)\n\t // Then it is about ideal for the rememberer to have stddev = 1 / n and weight = d\n\t // If the user only usually rates a song down, then for calculated distributions, stddev = k and weight = n\n\t // Then it is about ideal for the rememberer to have stddev = k and weight = d\n\t // This is mostly equivalent to stddev = d^(-1/3), weight = d^(2/3)\n\t // So we could even make the rememberer stronger than the current stddev = d^(-1/3), weight = d^(1/3)\n\t //double squareRoot = sqrt(remembererDuration);\n\t var cubeRoot = Math.pow(remembererDuration, 1.0/3.0);\n\t //message(\"building rememberer\");\n\t var rememberer = new Distribution(1, 1.0 / cubeRoot, cubeRoot);\n\t guesses.push(rememberer);\n\t \n\t // We should also suspect that they don't want to hear the song twice in a row\n\t var spacerDuration = candidate.getDurationSinceLastPlayed(when);\n\t // if they just heard it then they we're pretty sure they don't want to hear it again\n\t // If it's been 10 hours then it's probably okay to play it again\n\t // The spacer has a max weight so it can be overpowered by learned data\n\t var spacerWeight = 20 * (1 - spacerDuration / 36000);\n\t if (spacerWeight > 0) {\n\t guesses.push(new Distribution(0, .05, spacerWeight));\n\t }\n\n // finally, combine all the distributions and return\n //message(\"averaging distributions\");\n var childRating = this.averageDistributions(guesses);\n candidate.setCurrentRating(childRating, when);\n message(\"name: \" + candidate.getName().getName() + \" score: \" + childRating.getMean() + \"\\r\\n\", 1);\n return childRating;\n }", "async function execute () {\n // no hidden layers...\n var network = new Network(2,1);\n \n // XOR dataset\n var trainingSet = [\n { input: [0,0], output: [0] },\n { input: [0,1], output: [1] },\n { input: [1,0], output: [1] },\n { input: [1,1], output: [0] }\n ];\n \n await network.evolve(trainingSet, {\n mutation: methods.mutation.FFW,\n equal: true,\n error: 0.05,\n elitism: 5,\n mutation_rate: 0.5\n });\n \n // and it works!\n const final = {}\n final.b0_0 = network.activate([0,0]); // 0.2413\n final.b0_1 = network.activate([0,1]); // 1.0000\n final.b1_0 = network.activate([1,0]); // 0.7663\n final.b1_1 = network.activate([1,1]); // 0.008\n console.log(final)\n}", "function linkPoints() {\n // for each point find the 5 closest points\n for(var i = 0; i < points.length; i++) {\n var closest = [];\n var p1 = points[i];\n for(var j = 0; j < points.length; j++) {\n var p2 = points[j];\n if(p1 !== p2) {\n var placed = false;\n for(var k = 0; k < 5; k++) {\n if(!placed) {\n if(closest[k] === undefined) {\n closest[k] = p2;\n placed = true;\n }\n }\n }\n\n for(k = 0; k < 5; k++) {\n if(!placed) {\n if(getDistance(p1, p2) < getDistance(p1, closest[k])) {\n closest[k] = p2;\n placed = true;\n }\n }\n }\n }\n }\n p1.closest = closest;\n }\n\n // assign a circle to each point\n for (i in points) {\n var c = new Circle(points[i], 2+Math.random()*2, 'rgba(255,255,255,0.3)');\n points[i].circle = c;\n }\n}", "_addLink(r1, r2) {\n this.elements.push({\n group: \"edges\",\n data: {\n id: `${r1.id}_${r2.id}`,\n source: r1.id,\n target: r2.id\n } \n })\n }", "function extendConnections() {\n\n for (var iteration = 0; iteration < selection.connections; iteration++) {\n \n var nodesCopy = [];\n\tsummaryNodes.forEach(function (d){nodesCopy.push(d);});\n\n\tfor (var i = 0; i < selection.network.links.length; i++) { // for each link {\n\t\n\t\tvar subjectFound = findNode(selection.network.links[i].source.id, nodesCopy);\n\t\tvar objectFound = findNode(selection.network.links[i].target.id, nodesCopy);\n\n\t\tif ((subjectFound == -1 || objectFound == -1) && (!(subjectFound == -1 && objectFound == -1)) &&\t\t\t\t// only one concept is in graph (else already present)\n\t\t\t(selection.network.links[i].source.novel == true && selection.network.links[i].target.novel == true) ) { \t// arguments are novel\n\n\t\t\tfor (var j = 0; j < selection.network.links[i].predicate.length; j++) { \t// for each predicate of each link\n\t\t\n\t\t\t\tif (findUnconnectedPreds(selection.network.links[i].predicate[j].label) == -1 &&\t\t\t\t\t\t\t\t\t// predication is not excluded for domain \n\t\t\t\t\t\tfindRelevanceRule(selection.network.links[i].predicate[j].label, selection.network.links[i].source.semtype, // predication fits within a domain rule\n\t\t\t\t\t\t\t\tselection.network.links[i].target.semtype) != -1) {\n\t\t\t\t\n\t\t\t\t\tif (findNode(selection.network.links[i].source.id, summaryNodes) == -1) summaryNodes.push(selection.network.links[i].source);\n\t\t\t\t\tif (findNode(selection.network.links[i].target.id, summaryNodes) == -1) summaryNodes.push(selection.network.links[i].target);\n\n\t\t\t\t\tvar linkFound;\n\t\t\t\t\tif (summaryLinks.length > 0) linkFound = findLink(selection.network.links[i], summaryLinks);\n\t\t\t\t\telse linkFound = -1;\n\t\n\n\t\t\t\t\tif (linkFound != -1) { // link exists\n\n\t\t\t\t\t\tvar predicateFound = findPredicate(selection.network.links[i].predicate[j], summaryLinks[linkFound] );\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (predicateFound == -1 ) { // predicate doesn't exist\n\n\t\t\t\t\t\t\tsummaryLinks[linkFound].predicate.push(selection.network.links[i].predicate[j]);\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t} else { summaryLinks.push(selection.network.links[i]); }\n\t\t\t\t\t\n\t\t\t\t} // not in unconnectedPreds list\n\t\t\t\t\n\t\t\t} // for each predicate\n\t\t\t\n\t\t} // object or subject found\n\t\t\n\t} // for each link\n\t\n } // iterations\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the List forward
printForward() { // Only if the list is not empty if (this.#head) { let current = this.#head; let output = ""; do { output += current.value; if (current.next != this.#head) output += " -> "; current = current.next; } while (current != this.#head); console.log(output); } }
[ "printList() {\n // First, let's check if the list is empty\n if(this.isEmpty()) {\n console.log(\"The list is empty!\")\n return;\n }\n // Let's start a runner at the beginning of the singly linked list itself\n var runner = this.head;\n // This string will be added to as we traverse along the SLL\n var string = \"\";\n\n\n // Now we need a way to traverse through the SLL\n\n // If the runner is not null, we're still looking at a node, so we have things to do!\n while(runner != null) {\n // We want to add the node's value to our string, and a fancy little arrow for looks\n string += runner.value + \" -> \";\n // Then, we want to progress the runner to the NEXT node in the SLL\n runner = runner.next;\n }\n \n // Once we've finished moving through the entire list, we want to print the string\n console.log(string);\n }", "print() {\n var runner = this.front; // Start at the front\n while (runner !== null) { // While we're not at the end\n console.log(runner.val); // Print value at current node\n runner = runner.next; // Move to next node\n }\n }", "function printRecursively(lst) {\n if (lst.length === 1) {\n console.log(lst[0]);\n } else if (lst.length === 0) {\n return;\n } else {\n console.log(lst.slice(0, 1)[0]);\n printRecursively(lst.slice(1));\n }\n}", "function dumplist(l) { \n var i, rv = []; \n \n rv.push(\"has \"+l.length+\" elements:\"); \n for (i=0; i<l.length; i++) { \n rv.push(\" \"+i+\"\\t\"+l[i].toSpecifier()+ \n \"\\t\"+l[i].markupTag.name); \n } \n return rv.join(\"\\n\"); \n}", "function printFavorites() {\n\t// DONE: clear out favorites section each time\n\t// before displaying new list of favorites\n\tlist.innerHTML = '';\n\n\n\t// TODO: concatenate all the favorites into one string\n\t// - hint: loop through all the favorites\n\t// - this should be stored in a variable named favoritesText\n\t// - each favorite should have an html br element between it (EG: \"<br>\")\n\tvar favoritesText='';\n\t\n\tfavorites.forEach(print);\n\tfunction print(favorite) {\n\t\tfavoritesText += favorite + '<br />';\n\t};\n\n\n\t// DONE: update the list element with the\n\t// new list of favorites\n\tlist.innerHTML = favoritesText;\n}", "print() { \n let str = \"\"; \n for (var i = 0; i < this.size(); i++) \n str += this.stack[i] + \" \"; \n console.log(str); \n }", "print() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++)\n this.nodes[layer][node].print();\n }\n }", "function printMoveList(moveList) {\n var listMoves = ' Move Piece Captured Flag Score\\n\\n';\n \n for (var index = 0; index < moveList.length; index++) {\n let move = moveList[index].move;\n listMoves += ' ' + COORDINATES[getSourceSquare(move)] + COORDINATES[getTargetSquare(move)];\n listMoves += ' ' + PIECE_TO_CHAR[getSourcePiece(move)] +\n ' ' + PIECE_TO_CHAR[getTargetPiece(move)] +\n ' ' + getCaptureFlag(move) +\n ' ' + moveList[index].score + '\\n';\n }\n \n listMoves += '\\n Total moves: ' + moveList.length;\n console.log(listMoves);\n }", "printNodes() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++) {\n document.writeln(this.nodes[layer][node].number + \" | \");\n }\n document.writeln(\"</br>\");\n }\n document.writeln(\n \"----------------------------------------------------------------</br>\"\n );\n }", "function showList(a_oItems, g_nLoc){\n \n var s_List = \"\"; \n for (var i=0; i< a_oItems.length; i++){\n s_List = s_List + \"\\n\" + a_oItems[i].Name(g_nLoc); \n } \n return s_List; \n}", "printConsole() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++)\n this.nodes[layer][node].printConsole();\n }\n }", "function printList(autoArr, bool)\n{\n autoArr.forEach(function(x)\n {\n x.logMe(bool)\n \n });\n}", "log() {\n console.info('Internal Playlist Model:')\n this.items.forEach((video, index) => {\n console.info('\\t️', `${index}.`, 'ℹ️', '(',video.position,')', '[Title]', video.title, '[Channel]', video.channel, '[Duration]', `${video.duration}s`, '[Language]', video.language)\n })\n }", "function firstNamePrinter1(arr) {\n arr.forEach(item => {\n document.write(item.firstName + ' '+item.tattoos + '<br>')\n })\n }", "function display_All()\n{\n\t\t\ti = 0;\n\t\t\twhile (i < trueNodeids.length) {\n\t\t\t\tconsole.log(trueNodeids[i].id);\n\t\t\t\ti++;\n\t\t\t}\n}", "function getBanList() {\n banList.forEach( function( each ) {\n console.log(each + \";\");\n });\n}", "function list() { console.log(students); }", "function write() {\n var length = arguments.length;\n for (var i = 0; i < length; i++) {\n output.print(String(arguments[i]));\n if (i < length - 1)\n output.print(' ');\n }\n}", "print() {\n console.log(this.ranges.map(range => `[${range.toString()})`).join(' '))\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates commonAncestorContainer and collapsed after boundary change
function updateCollapsedAndCommonAncestor(range) { range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset); range.commonAncestorContainer = range.collapsed ? range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer); }
[ "childrenChanged() {\n if (true === this.adjustGroupWhenChildrenChange) {\n this.adjustChildrenVertically();\n this.adjustChildrenHorizontally();\n }\n }", "adjustContentAreaPositionAndDimension() {\n if (isNull(this.frame)) {\n if (0 !== this._contentX1 || this.width !== this._contentWidth) {\n this._contentX1 = 0;\n this._contentWidth = this.width;\n this.disableGroupAdjustmentWhenChildrenChange();\n this.adjustChildrenHorizontally();\n this.enableGroupAdjustmentWhenChildrenChange();\n }\n if (0 !== this._contentY1 || this.height !== this._contentHeight) {\n this._contentY1 = 0;\n this._contentHeight = this.height;\n this.disableGroupAdjustmentWhenChildrenChange();\n this.adjustChildrenVertically();\n this.enableGroupAdjustmentWhenChildrenChange();\n }\n } else {\n let contentArea = this.frame.contentBox();\n if (contentArea.width === this.contentWidth && contentArea.height === this.contentHeight) {\n if (contentArea.x1 !== this.contentX1 || contentArea.y1 !== this.contentY1) {\n // If only the content area position has changed, adjust only the children position.\n let deltaX = contentArea.x1 - this.contentX1;\n let deltaY = contentArea.y1 - this.contentY1;\n this.disableGroupAdjustmentWhenChildrenChange();\n this.adjustChildrenPositionBy({x: deltaX, y: deltaY});\n this.enableGroupAdjustmentWhenChildrenChange();\n\n this._contentX1 = contentArea.x1;\n this._contentY1 = contentArea.y1;\n }\n } else {\n this.disableGroupAdjustmentWhenChildrenChange();\n if (contentArea.x1 !== this.contentX1 || contentArea.width !== this.contentWidth) {\n this._contentX1 = contentArea.x1;\n this._contentWidth = contentArea.width;\n this.adjustChildrenHorizontally();\n }\n if (contentArea.y1 !== this.contentY1 || contentArea.height !== this.contentHeight) {\n this._contentY1 = contentArea.y1;\n this._contentHeight = contentArea.height;\n this.adjustChildrenVertically();\n }\n this.enableGroupAdjustmentWhenChildrenChange();\n }\n }\n }", "function Expand() {\n var splitter = $('#horizontal').find('.k-splitbar');\n\n splitter.removeClass('k-collapsed');\n viewPort.expand(\"#right-pane\");\n SetDataProcessNiceScroll();\n}", "enableChildrenAdjustmentWhenGroupChanges() {\n this._adjustChildrenWhenGroupChanges--;\n }", "_hardcodeDimensions() {\n const currentHeight = this._current && this._current.getBoundingClientRect().height || 0;\n let tallestHeight = 0;\n\n // Hardcode the height of each collapse to allow CSS transition\n this._elements.forEach(el => {\n el.classList.remove('is-ready');\n el.style.height = 'auto';\n\n const itemHeight = el.closest('.accordion-list__item').getBoundingClientRect().height;\n const collapseHeight = el.getBoundingClientRect().height;\n\n el.style.height = `${collapseHeight}px`;\n el.classList.add('is-ready');\n tallestHeight = Math.max(tallestHeight, itemHeight);\n });\n\n // Set a min-height on the container to avoid wiggles during transitions\n this._accordion.style.minHeight = 'auto';\n const minHeight = this._accordion.getBoundingClientRect().height - currentHeight + tallestHeight + 18;\n this._accordion.style.minHeight = `${minHeight}px`;\n }", "function expandParent(cell, notebook) {\n let nearestParentCell = findNearestParentHeader(cell, notebook);\n if (!nearestParentCell) {\n return;\n }\n if (!getHeadingInfo(nearestParentCell).collapsed &&\n !nearestParentCell.isHidden) {\n return;\n }\n if (nearestParentCell.isHidden) {\n expandParent(nearestParentCell, notebook);\n }\n if (getHeadingInfo(nearestParentCell).collapsed) {\n setHeadingCollapse(nearestParentCell, false, notebook);\n }\n }", "function i2uiToggleContent(item, nest, relatedroutine)\r\n{\r\n // find the owning table for the item which received the event.\r\n // in this case the item is the expand/collapse image\r\n // note: the table may be several levels above as indicated by 'nest'\r\n var owningtable = item;\r\n //i2uitrace(1,\"nest=\"+nest+\" item=\"+item+\" tagname=\"+item.tagName);\r\n if (item.tagName == \"A\")\r\n {\r\n item = item.childNodes[0];\r\n //i2uitrace(1,\"new item=\"+item+\" parent=\"+item.parentNode+\" type=\"+item.tagName);\r\n }\r\n\r\n while (owningtable != null && nest > 0)\r\n {\r\n if (owningtable.parentElement)\r\n {\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentElement+\" level=\"+nest);\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentElement.tagName+\" level=\"+nest);\r\n owningtable = owningtable.parentElement;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentNode+\" level=\"+nest);\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentNode.tagName+\" level=\"+nest);\r\n owningtable = owningtable.parentNode;\r\n }\r\n if (owningtable != null && owningtable.tagName == 'TABLE')\r\n {\r\n nest--;\r\n }\r\n }\r\n\r\n var ownerid = owningtable.id;\r\n\r\n // for tabbed container, the true owning table is higher.\r\n // continue traversal in order to get the container id.\r\n if (ownerid == \"\")\r\n {\r\n var superowner = owningtable;\r\n while (superowner != null && ownerid == \"\")\r\n {\r\n if (superowner.parentElement)\r\n {\r\n //i2uitrace(1,\"tag=\"+superowner.tagName+\" parent=\"+superowner.parentElement.tagName+\" level=\"+nest+\" id=\"+superowner.parentElement.id);\r\n superowner = superowner.parentElement;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"tag=\"+superowner.tagName+\" parent=\"+superowner.parentNode.tagName+\" level=\"+nest+\" id=\"+superowner.parentNode.id);\r\n superowner = superowner.parentNode;\r\n }\r\n if (superowner != null && superowner.tagName == 'TABLE')\r\n {\r\n ownerid = superowner.id;\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"final id=\"+ownerid);\r\n\r\n // if found table, find child TBODY with proper id\r\n if (owningtable != null)\r\n {\r\n var pretogglewidth = owningtable.offsetWidth;\r\n\r\n //i2uitrace(1,owningtable.innerHTML);\r\n\r\n // can not simply use getElementById since the container\r\n // may itself contain containers.\r\n\r\n // determine how many TBODY tags are within the table\r\n var len = owningtable.getElementsByTagName('TBODY').length;\r\n //i2uitrace(1,'#TBODY='+len);\r\n\r\n // now find proper TBODY that holds the content\r\n var contenttbody;\r\n for (var i=0; i<len; i++)\r\n {\r\n contenttbody = owningtable.getElementsByTagName('TBODY')[i];\r\n //i2uitrace(1,'TBODY '+i+' id='+contenttbody.id);\r\n if (contenttbody.id == '_containerBody' ||\r\n contenttbody.id == '_containerbody' ||\r\n contenttbody.id == 'containerBodyIndent' ||\r\n contenttbody.id == 'containerbody')\r\n {\r\n //i2uitrace(1,'picked TBODY #'+i);\r\n\r\n var delta = 0;\r\n\r\n if (contenttbody.style.display == \"none\")\r\n {\r\n contenttbody.style.display = \"table\";\r\n\t\t contenttbody.style.width = \"100%\";\r\n item.src = i2uiImageDirectory+\"/container_collapse.gif\";\r\n delta = contenttbody.offsetHeight;\r\n }\r\n else\r\n {\r\n delta = 0 - contenttbody.offsetHeight;\r\n contenttbody.style.display = \"none\";\r\n item.src = i2uiImageDirectory+\"/container_expand.gif\";\r\n }\r\n if (i2uiToggleContentUserFunction != null)\r\n {\r\n\t\t eval(i2uiToggleContentUserFunction+\"('\"+ownerid+\"',\"+delta+\")\");\r\n }\r\n break;\r\n }\r\n }\r\n\r\n // restore width of container\r\n if (pretogglewidth != owningtable.offsetWidth)\r\n {\r\n owningtable.style.width = pretogglewidth;\r\n owningtable.width = pretogglewidth;\r\n }\r\n\r\n // call a related routine to handle any follow-up actions\r\n // intended for internal use. external use should use the\r\n // callback mechanism\r\n //i2uitrace(0,\"togglecontent related=[\"+relatedroutine+\"]\");\r\n if (relatedroutine != null)\r\n {\r\n // must invoke the routine 'in the future' to allow browser\r\n // to settle down, that is, finish rendering the effects of\r\n // the tree element changing state\r\n setTimeout(relatedroutine,200);\r\n }\r\n }\r\n}", "function switchToCollapsibleLayout() {\n layout = \"collapsible\";\n var sidebarFull = $(\".left-sidebar-toplevel\").detach();\n $(\".sidebar-target-collapsible\").prepend(sidebarFull);\n $(\".left-sidebar-toplevel\").addClass(\"left-sidebar-collapsible\");\n $(\".left-sidebar-toplevel\").removeClass(\"left-sidebar-fixed col-4 col-lg-4 col-xl-3 \");\n $(\".left-sidebar-togglebutton\").removeClass(\"hide\");\n $(\".center-content\").removeClass(\"col-8\");\n $(\".center-content\").addClass(\"col-12\");\n\t}", "function collapseExpandLayers(id, parentDisplayType) {\n var elements = document.getElementsByName(id);\n var displayType = getDisplayType(id, parentDisplayType);\n var layerLabel = displayType == 'block' ?\n getArrowImg('open') : getArrowImg('close');\n document.getElementById('collapse_' + id).innerHTML = layerLabel;\n for (var i = 0; i < elements.length; i++) {\n elements[i].style.display = displayType;\n }\n collapseChildLayers(id, displayType);\n}", "disableChildrenAdjustmentWhenGroupChanges() {\n this._adjustChildrenWhenGroupChanges++;\n }", "_reCalculateVisibleNodePosition() {\n // clear all to avoid leaving selected/select-ready dep lines\n // which created before node position changes.\n this.clearAllHighlight()\n // position calculation\n this.refreshDiagramElements()\n this._setAllDiagramElementsHandler()\n }", "relayoutNavigationElements(){\n\t\treturn;\n\t}", "disableGroupAdjustmentWhenChildrenChange() {\n this._adjustGroupWhenChildrenChange++;\n }", "readjustGroup() {\n // Calculate the new required group size, content box x1 and y1 based on\n // the minContentWidth and the minContentHeight.\n if (isNull(this.frame)) {\n this.width = this.minContentWidth;\n this.height = this.minContentHeight;\n } else {\n this._contentWidth = Math.max(this.minContentWidth, this.contentWidth);\n this._contentHeight = Math.max(this.minContentHeight, this.contentHeight);\n this.disableGroupAdjustmentWhenFrameChanges();\n this.frame.disableChangeNotifications();\n let contentBoundingBox = new BoundingBox({\n x: this.contentX1,\n y: this.contentY1,\n width: this.contentWidth,\n height: this.contentHeight\n });\n let requiredWidth = this.frame.widthToFit(contentBoundingBox);\n let requiredHeight = this.frame.heightToFit(contentBoundingBox);\n if (true === this.frame.preserveAspectRatio) {\n this.frame.width = requiredWidth;\n if (this.frame.height < requiredHeight) {\n this.frame.height = requiredHeight;\n }\n super.width = this.frame.width;\n super.height = this.frame.height;\n\n // Calculate the frame content area position and dimension.\n this.adjustContentAreaPositionAndDimension();\n } else {\n if (requiredWidth !== this.width) {\n this.width = requiredWidth;\n } else {\n this.adjustChildrenHorizontally();\n }\n if (requiredHeight !== this.height) {\n this.height = requiredHeight;\n } else {\n this.adjustChildrenVertically();\n }\n }\n\n this.notifyListeners(ChangeListenerConstants.DIMENSION);\n\n this.frame.enableChangeNotifications();\n this.frame.notifyListeners(ChangeListenerConstants.DIMENSION);\n this.enableGroupAdjustmentWhenFrameChanges();\n }\n }", "function updateUI() {\n if (isSmall) {\n view.ui.add(expandLegend, 'top-right');\n view.ui.remove(legend);\n view.ui.components = [\"attribution\"];\n } else {\n view.ui.add(legend, 'top-right');\n view.ui.remove(expandLegend);\n view.ui.components = [\"attribution\", \"zoom\"];\n }\n }", "function showCollapsable(showThisOne){\r\n\t\tvar toggledCollapsable = showThisOne;\r\n\r\n\t\t\t\r\n\t\tif(toggledCollapsable == 1){\r\n\t\t\tcontent = content1;\r\n\t\t\t// content[0].style.height = \"500px\";\r\n\t\t}else if(toggledCollapsable == 2){\r\n\t\t\tcontent = content2;\r\n\t\t}else if(toggledCollapsable == 3){\r\n\t\t\tcontent = content3;\r\n\t\t}else if(toggledCollapsable == 4){\r\n\t\t\tcontent = content4;\r\n\t\t}else{\r\n\t\t\tcontent = content5;\r\n\t\t}\r\n\r\n\t\tif(content.style.maxHeight){\r\n\t\t\tcontent.style.maxHeight = null;\r\n\t\t}else{\r\n\t\t\tcontent.style.maxHeight = content.scrollHeight + \"px\";\r\n\t\t\t$('#chimchom2-descriptive').animate({scrollTop: jQuery(content).offset().top}, 200);\r\n\t\t}\r\n\r\n\t\tif(currentOpen !== null && currentOpen !== content){\r\n\t\tcurrentOpen.style.maxHeight = null;\r\n\t\t}\r\n\t}", "_updateDirtyDomComponents() {\n // An item is marked dirty when:\n // - the item is not yet rendered\n // - the item's data is changed\n // - the item is selected/deselected\n if (this.dirty) {\n this._updateContents(this.dom.content);\n this._updateDataAttributes(this.dom.box);\n this._updateStyle(this.dom.box);\n \n // update class\n const className = this.baseClassName + ' ' + (this.data.className ? ' ' + this.data.className : '') +\n (this.selected ? ' vis-selected' : '') + ' vis-readonly';\n this.dom.box.className = 'vis-item ' + className;\n \n if (this.options.showStipes) {\n this.dom.line.className = 'vis-item vis-cluster-line ' + (this.selected ? ' vis-selected' : '');\n this.dom.dot.className = 'vis-item vis-cluster-dot ' + (this.selected ? ' vis-selected' : '');\n }\n \n if (this.data.end) {\n // turn off max-width to be able to calculate the real width\n // this causes an extra browser repaint/reflow, but so be it\n this.dom.content.style.maxWidth = 'none';\n }\n }\n }", "toggleSplitTracks() {\n this.layout.split_tracks = !this.layout.split_tracks;\n if (this.parent.legend && !this.layout.always_hide_legend) {\n this.parent.layout.margin.bottom = 5 + (this.layout.split_tracks ? 0 : this.parent.legend.layout.height + 5);\n }\n this.render();\n return this;\n }", "function tree_collapse() {\n let $allPanels = $('.nested').hide();\n let $elements = $('.treeview-animated-element');\n\n $('.closed').click(function () {\n \n $this = $(this);\n $target = $this.siblings('.nested');\n $pointer = $this.children('.fa-angle-right');\n\n $this.toggleClass('open')\n $pointer.toggleClass('down');\n\n !$target.hasClass('active') ? $target.addClass('active').slideDown() : \n $target.removeClass('active').slideUp();\n \n return false;\n });\n\n $elements.click(function () {\n \n $this = $(this);\n \n if ($this.hasClass('opened')) {\n ($this.removeClass('opened'));\n } else {\n ($elements.removeClass('opened'), $this.addClass('opened'));\n }\n\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shows the parents of an clicked node
function showParents(){ // empty map, then fill it if(nodeParentMap.size === 0) createNodeParentMap(); // old menu open ? then close it if(document.getElementById('contextmenuParent')) closeContextMenuParent(); let nodeId= $(clickedNode).attr('id'); let parents = nodeParentMap.get(nodeId); // {node : {string} nodeId, callSite: object} $("body").append( "<div id='contextmenuParent'>" + "<h3>Choose parent from <span>" + nodeId + "</span> to be shown:</h3>" + "<div id='parentSelection'>" + "</div>" + "<div id='contextmenuSubmit'>" + "<button id='cmb1' onclick='closeContextMenuParent()'>Close</button>" + "</div>"+ "</div>"); // has parents if(parents){ // sort them parents.sort(function(a,b){ if((a.node + a.callSite.line) < (b.node + b.callSite.line)) return -1; else if ((a.node + a.callSite.line) > (b.node + b.callSite.line)) return +1; else return 0; }); //display them let parentSelection = document.getElementById("parentSelection"); parents.forEach(function(parent){ parentSelection.innerHTML += "<div><p class='rmx' onclick='showParentAndCall(\""+parent.node+"\","+JSON.stringify(parent.callSite)+",\""+nodeId+"\")'>Create</p><p>" + parent.node + " at line " + parent.callSite.line +"</p></div>"; }); } }
[ "function showParent($node) {\n // just show only one superior level\n var $temp = $node.closest('table').closest('tr').siblings().removeClass('hidden');\n // just show only one line\n $temp.eq(2).children().slice(1, -1).addClass('hidden');\n // show parent node with animation\n var parent = $temp.eq(0).find('.node')[0];\n repaint(parent);\n $(parent).addClass('slide').removeClass('slide-down').one('transitionend', function() {\n $(parent).removeClass('slide');\n if (isInAction($node)) {\n switchVerticalArrow($node.children('.topEdge'));\n }\n });\n }", "function findParents(node){\n\t\tvar rst = [];\n\t\tvar currentNode = node.parent;\n\t\twhile(currentNode!==null){\n\t\t\trst.unshift(currentNode);\n\t\t\tcurrentNode = currentNode.parent;\n\t\t}\n\t\treturn rst;\n\t}", "parent() {\n\t const parents = [];\n\t this.each(el => {\n\t if (!parents.includes(el.parentNode)) {\n\t parents.push(el.parentNode);\n\t }\n\t });\n\t return new DOMNodeCollection(parents);\n\t }", "function getAncestors(node) {\r\n var path = [];\r\n var current = node;\r\n while (current.parent) {\r\n path.unshift(current);\r\n current = current.parent;\r\n }\r\n return path;\r\n }", "showChildren(node) {\n let that = this,\n temp = this._nextAll(node.parentNode.parentNode),\n descendants = [];\n\n this._removeClass(temp, 'hidden');\n if (temp.some((el) => el.classList.contains('verticalNodes'))) {\n temp.forEach((el) => {\n Array.prototype.push.apply(descendants, Array.from(el.querySelectorAll('.node')).filter((el) => {\n return that._isVisible(el);\n }));\n });\n } else {\n Array.from(temp[2].children).forEach((el) => {\n Array.prototype.push.apply(descendants,\n Array.from(el.querySelector('tr').querySelectorAll('.node')).filter((el) => {\n return that._isVisible(el);\n }));\n });\n }\n // the two following statements are used to enforce browser to repaint\n this._repaint(descendants[0]);\n this._one(descendants[0], 'transitionend', (event) => {\n this._removeClass(descendants, 'slide');\n if (this._isInAction(node)) {\n this._switchVerticalArrow(node.querySelector('.bottomEdge'));\n }\n }, this);\n this._addClass(descendants, 'slide');\n this._removeClass(descendants, 'slide-up');\n }", "function setChildrenAndParents() {\n\tif(relations) {\n\t\trelations.forEach(function(r) {\n\t\t\tvar target = document.getElementById(r.target.entity.name + \"_\" + r.target.name)\n\t\t\tappendClass(target, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\n\t\t\tvar source = document.getElementById(r.source.entity.name + \"_\" + r.source.name)\n\t\t\tappendClass(source, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\n\t\t\tvar targetAsset = document.getElementById('asset_' + r.target.entity.name)\n\t\t\tappendClass(targetAsset, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\tappendClass(targetAsset, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\n\t\t\tvar sourceAsset = document.getElementById('asset_' + r.source.entity.name)\n\t\t\tappendClass(sourceAsset, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\tappendClass(sourceAsset, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t})\n\t}\n\tif(relations2) {\n\t\trelations2.forEach(function(r) {\n\t\t\tif(r.associations) {\n\t\t\t\tr.associations.forEach(function(a, i) {\n\t\t\t\t\tassociationElem = document.getElementById(getAssociationId(a))\n\t\t\t\t\tappendClass(associationElem, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(associationElem, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t\tlinkElem = document.getElementById(\n\t\t\t\t\t\t\"link_\" + getAssociationId(a) + \n\t\t\t\t\t\t\"_\" + getPathId({source: r.source, target: r.target})\n\t\t\t\t\t)\n\t\t\t\t\tappendClass(linkElem, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(linkElem, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t\t\n\t\t\t\t\tvar a1 = document.getElementById('asset_' + a.source.name)\n\t\t\t\t\tappendClass(a1, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(a1, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\n\t\t\t\t\tvar a2 = document.getElementById('asset_' + a.target.name)\n\t\t\t\t\tappendClass(a2, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(a2, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t})\n\t\t\t} else if(r.link) {\n\t\t\t\tr.link.forEach(function(l, i) {\n if(i+1 < r.link.length) {\n\t\t\t\t\t\tisaElem = document.getElementById(\"inheritance_\" + \n\t\t\t\t\t\t\tr.link[i] + \"_\" +\n\t\t\t\t\t\t\tr.link[i+1]\n\t\t\t\t\t\t)\n\t\t\t\t\t\tappendClass(isaElem, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\t\tappendClass(isaElem, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\n\t\t\t\t\t\tlinkElem = document.getElementById(\n\t\t\t\t\t\t\t\"link_\" + getInheritanceId({subAsset: {name: r.link[i]}, superAsset: {name: r.link[i+1]}}) + \n\t\t\t\t\t\t\t\"_\" + getPathId({source: r.source, target: r.target})\n\t\t\t\t\t\t)\n\t\t\t\t\t\tappendClass(linkElem, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\t\tappendClass(linkElem, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t\t}\n\t\t\t\t\tvar a1 = document.getElementById('asset_' + l)\n\t\t\t\t\tappendClass(a1, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(a1, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n\n\tif(root.children) {\n\t\troot.children.forEach(function(asset) {\n\t\t\tif(asset.children) {\n\t\t\t\tasset.children.forEach(function(attackStep) {\n\t\t\t\t\tvar traversed = {}\n\t\t\t\t\ttraversed[attackStep.entity.name + \"_\" + attackStep.name] = true\n\t\t\t\t\tchildrenRecurse(attackStep, attackStep, traversed)\n\t\n\t\t\t\t\ttraversed = {}\n\t\t\t\t\ttraversed[attackStep.entity.name + \"_\" + attackStep.name] = true\n\t\t\t\t\tparentRecurse(attackStep, attackStep, traversed)\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n}", "function showSiblings($node, direction) {\n // firstly, show the sibling td tags\n var $siblings = $();\n if (direction) {\n if (direction === 'left') {\n $siblings = $node.closest('table').parent().prevAll().removeClass('hidden');\n } else {\n $siblings = $node.closest('table').parent().nextAll().removeClass('hidden');\n }\n } else {\n $siblings = $node.closest('table').parent().siblings().removeClass('hidden');\n }\n // secondly, show the lines\n var $upperLevel = $node.closest('table').closest('tr').siblings();\n if (direction) {\n $upperLevel.eq(2).children('.hidden').slice(0, $siblings.length * 2).removeClass('hidden');\n } else {\n $upperLevel.eq(2).children('.hidden').removeClass('hidden');\n }\n // thirdly, do some cleaning stuff\n if (!getNodeState($node, 'parent').visible) {\n $upperLevel.removeClass('hidden');\n var parent = $upperLevel.find('.node')[0];\n repaint(parent);\n $(parent).addClass('slide').removeClass('slide-down').one('transitionend', function() {\n $(this).removeClass('slide');\n });\n }\n // lastly, show the sibling nodes with animation\n $siblings.find('.node:visible').addClass('slide').removeClass('slide-left slide-right').eq(-1).one('transitionend', function() {\n $siblings.find('.node:visible').removeClass('slide');\n if (isInAction($node)) {\n switchHorizontalArrow($node);\n $node.children('.topEdge').removeClass('fa-chevron-up').addClass('fa-chevron-down');\n }\n });\n }", "function incomingLinks(node) {\n return d3.select(\"#maindiv${divnum}\")\n .selectAll(\".link\")\n .filter(function(d) {\n return d.target.id == node[0][0].__data__.id;\n });\n}", "function expandParentsNavTree(a, id) {\n\t//show this ul and all of its parents\n\tvar node = a;\n\tif (node != null)\n\t{\n\t\twhile (node.id != id)\n\t\t{\n\t\t\tif (String(node.tagName).toUpperCase() == \"LI\")\n\t\t\t{\n\t\t\t\tvar children = nodeChildrenByTagName(node, \"A\", 1);\n\t\t\t\tif (children[0]) {\n\t\t\t\t\tnodeAddClass(children[0], 'current');\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (String(node.tagName).toUpperCase() == \"UL\")\n\t\t\t{\n\t\t\t\tnode.style.display = 'block';\n\t\t\t}\n\t\t\tnode = node.parentNode;\n\t\t}\n\t}\n}", "getRelatedNodes(node, relation) {\n if (relation === 'parent') {\n return this._closest(node, (el) => el.classList.contains('nodes'))\n .parentNode.children[0].querySelector('.node');\n } else if (relation === 'children') {\n return Array.from(this._closest(node, (el) => el.nodeName === 'TABLE').lastChild.children)\n .map((el) => el.querySelector('.node'));\n } else if (relation === 'siblings') {\n return this._siblings(this._closest(node, (el) => el.nodeName === 'TABLE').parentNode)\n .map((el) => el.querySelector('.node'));\n }\n return [];\n }", "function hideAncestorsSiblings($node) {\n var $temp = $node.closest('table').closest('tr').siblings();\n if ($temp.eq(0).find('.spinner').length) {\n $node.closest('.orgchart').data('inAjax', false);\n }\n // hide the sibling nodes\n if (getNodeState($node, 'siblings').visible) {\n hideSiblings($node);\n }\n // hide the lines\n var $lines = $temp.slice(1);\n $lines.css('visibility', 'hidden');\n // hide the superior nodes with transition\n var $parent = $temp.eq(0).find('.node');\n var grandfatherVisible = getNodeState($parent, 'parent').visible;\n if ($parent.length && $parent.is(':visible')) {\n $parent.addClass('slide slide-down').one('transitionend', function() {\n $parent.removeClass('slide');\n $lines.removeAttr('style');\n $temp.addClass('hidden');\n });\n }\n // if the current node has the parent node, hide it recursively\n if ($parent.length && grandfatherVisible) {\n hideAncestorsSiblings($parent);\n }\n }", "function keepNodesOnTop() {\n $(\".nodeStrokeClass\").each(function( index ) {\n var gnode = this.parentNode;\n gnode.parentNode.appendChild(gnode);\n });\n }", "get parent() {\n return tag.configure(ContentType(this, \"parent\"), \"ct.parent\");\n }", "function selectTaxa(name, rdist){\n \n console.log(name + \"---\" + rdist);\n var rootIndex=-1;\n for(var i=0; i<taxaTree.length; i++){\n if((taxaTree[i][0]==rdist)&&(taxaTree[i][1]==name)){\n rootIndex=i;\n break;\n }\n }\n console.log(\"rootIndex=\"+rootIndex);\n /*\n var parentIndex=-1;\n for(var i=0; i<taxaTree.length; i++){\n if(taxaTree[i][3].indexOf(taxaTree[rootIndex][1])>-1){\n parentIndex=i;\n }\n }\n\n if(parentIndex<0){\n var searchOutput='<table border=\"3\"><tr><td>Parent</td><td> Undefined</td></tr><tr><td>Current</td><td>'+taxaTree[rootIndex][1]+\" (\"+taxaTree[rootIndex][2]+\")</td></tr><tr><td>Children </td><td>\";\n }else{\n var searchOutput='<table border=\"3\"><tr><td>Parent</td><td> <a href=\"#\" onclick=\"selectTaxa(\\''+taxaTree[parentIndex][1]+'\\','+taxaTree[parentIndex][0]+');\"><font color=\"yellow\" size=\"4\">'+taxaTree[parentIndex][1]+'</font></a> ('+taxaTree[parentIndex][2]+')</td></tr><tr><td>Current</td><td>'+taxaTree[rootIndex][1]+\" (\"+taxaTree[rootIndex][2]+\")</td></tr><tr><td>Children </td><td>\"; \n }\n\n for(var i=0; i<taxaTree[rootIndex][3].length; i++){\n var childNum;\n for(var j=0; j<taxaTree.length; j++){\n if(taxaTree[j][1]==taxaTree[rootIndex][3][i]){\n childNum=taxaTree[j][2];\n break;\n }\n }\n searchOutput+='<a href=\"#\" onclick=\"selectTaxa(\\''+taxaTree[rootIndex][3][i]+'\\','+String(taxaTree[rootIndex][0]+1)+');\"><font color=\"yellow\" size=\"4\">'+taxaTree[rootIndex][3][i]+'</font></a> ('+childNum+')';\n if(childNum>10){\n searchOutput+='&nbsp;<a href=\"load.html?mapid='+String(taxaTree[rootIndex][0]+1)+'_'+taxaTree[rootIndex][3][i]+'&specialmap=mtdna\"><font color=\"yellow\" size=\"4\">Zoom</font></a>';\n }\n searchOutput+='<br>';\n }\n searchOutput=searchOutput+\"</td></tr></table>\";\n document.getElementById(\"searchstatus\").innerHTML=searchOutput;\n */\n document.getElementById(\"tosearch\").value=taxaTree[rootIndex][1];\n startSearch();\n}", "function siblings () {\r\n return this.parent().children()\r\n}", "function indexInParent(node) {\n var children = node.parentNode.childNodes;\n var num = 0;\n for (var i=0; i<children.length; i++) {\n\tif (children[i]==node) return num;\n\tif (children[i].nodeType==1) num++;\n }\n return -1;\n}", "hideParent(node) {\n let temp = Array.from(this._closest(node, function (el) {\n return el.classList.contains('nodes');\n }).parentNode.children).slice(0, 3);\n\n if (temp[0].querySelector('.spinner')) {\n this.dataset.inAjax = false;\n }\n // hide the sibling nodes\n if (this._getNodeState(node, 'siblings').visible) {\n this.hideSiblings(node);\n }\n // hide the lines\n let lines = temp.slice(1);\n\n this._css(lines, 'visibility', 'hidden');\n // hide the superior nodes with transition\n let parent = temp[0].querySelector('.node'),\n grandfatherVisible = this._getNodeState(parent, 'parent').visible;\n\n if (parent && this._isVisible(parent)) {\n parent.classList.add('slide', 'slide-down');\n this._one(parent, 'transitionend', function () {\n parent.classList.remove('slide');\n this._removeAttr(lines, 'style');\n this._addClass(temp, 'hidden');\n }, this);\n }\n // if the current node has the parent node, hide it recursively\n if (parent && grandfatherVisible) {\n this.hideParent(parent);\n }\n }", "get parentId() {\n return this.getStringAttribute('parent_id');\n }", "function printNode(ID) {\n var childArray = new Array(); // store all children of node with ID into childArray[]\n var thisNode; // \"this\"\n for (i=0; i< nodes.length;i++){ // finding all children whose parentID == ID\n if (nodes[i][5] == ID){\n childArray.push(nodes[i]);\n //console.log(ID);\n }\n else if (nodes[i][0] == ID){\n thisNode = nodes[i];\n }\n }\n var numChildren = childArray.length;\n console.log(\"Number of children: \" + numChildren);\n\n var url = \"/story/\" + ID; // this is the url that will link to the edit's unique webpage\n \n // printing the icon and associated up/down votes\n p.image(\"/static/img/icons/doc3.png\", x-(img/2), y-(img/2), img, img)\n .hover(\n function(){\n this.attr({src: \"/static/img/icons/doc3_hovered.png\"});\n },\n function(){\n this.attr({src: \"/static/img/icons/doc3.png\"});\n })\n .attr({cursor: \"pointer\", href: url});\n \n var upVote = thisNode[6];\n var downVote = thisNode[7];\n p.text(x-(img/2.5), y+(img/2.5), upVote).attr({\"font-size\": 30, \"font-weight\": \"bold\", fill: \"#02820B\"});\n p.text(x+(img/2.5), y+(img/2.5), downVote).attr({\"font-size\": 30, \"font-weight\": \"bold\", fill: \"#B71306\"});\n console.log(\"Printed icon\"); // finish printing icon\n \n // if thisNode only has one child, draw a straight line downward to the child node\n if (numChildren == 1){\n y += 100;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n path += \" L \" + x + \" \" + y;\n //path += \" l 0 200\";\n \n printNode(childArray[0][0]);\n y -= 100;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n path += \" M \" + x + \" \" + y;\n }\n\n // if thisNode has multiple children, draw lines at 45-degrees in both directions downward, and if numChildren > 2, spaced equally inward from these outer lines\n else if (numChildren > 1){\n for (i=0; i < numChildren;i++){\n var newI = i;\n var newNum = numChildren;\n var angle = (((newI / (newNum-1))*200)-100);\n x += angle;\n y += 100;\n path += \" L \" + x + \" \" + y;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n console.log(childArray);\n \n printNode(childArray[i][0]);\n x -= angle;\n y -= 100;\n path += \" M \" + x + \" \" + y;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n i = newI;\n }\n }\n \n else if (numChildren == 0){\n console.log(\"No children\");\n return;\n }\n console.log(\"Number of children: \" + numChildren);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
unused harmony export getBanner
function getBanner(state) { return state.banner; }
[ "function d_Banner(objName) {\n\tthis.obj = objName;\n\tthis.aNodes = [];\n\tthis.currentBanner = 0;\n}", "function setupBanner(){\n\t\n\t/**\n\t * @constructor\n\t * @type {Banner}\n\t */\n\tbanner = new Banner({\n\t\tbanner: '#banner', // String identifying banner id\n\t\tbannerPreloader: '#bannerPreloader', // String identifying banner preloader id\n\t\tbannerNavigation: '#bannerNavigation .button', // String identifying banner navigation buttons\n\t\tbannerPlayback: '#bannerPlayback .button', // String identifying banner playback buttons\n\t\tbannerSlides: '#bannerSlides .slide', // String identifying banner slides\n\t\tlazyLoadNextSlide: false, //if set to true will preload the images for the next slide once it is done with the current\n\t\tduration: 6000, // Integer defining duration of slide playback in milliseconds\n\t\tautoPlay: true, // Boolean indicating whether slide show should auto play\n\t\tshuffle: false, // Shuffle slides and nav\n\t\tnavEvents: false // Runs buttonMouseOver and buttonMouseDown (on the bannerNavigation buttons) on slidechange automatically\n\t});\n\n\tbanner.initialize(); //INIT\n}", "function d_Banner2(objName) {\n\tthis.obj = objName;\n\tthis.aNodes = [];\n\tthis.bNodes = [];\n\tthis.currentBanner = 0;\n}", "function drawBanner (year) {\n\treturn drawAnImage(arrowSize, svgHeight - arrowSize-barPadding, svgWidth-arrowSize*2, arrowSize, \"../Resources/banners/banner_\"+year+\".png\" );\n}", "function toggleBanner() {\n\tif (bannered) {\n\t\thideBanner();\n\t\tclearExplication();\n\t} else {\n\t\tshowBanner();\n\t\tsaveExplication();\n\t}\n}", "function initBanner() {\n\tif (!isPath(homePath) && !isPath(\"/\")) {\n\t\tsaveBanner();\n\n\t\t$banTit.css({top: $barTit.position().top, left: $barTit.position().left, \"font-size\": $barTit.css(\"font-size\")});\n\t\t$banSub.css({top: $barSub.position().top, left: $barSub.position().left, \"font-size\": $barSub.css(\"font-size\")});\n\t\t\n\t\t$flap.css({top: -\t$flap.height()});\n\t\t$main.css({top: $topbar.height()});\n\t\t\n\t\tbannered = false;\n\t}\n}", "function showBanner() {\n\t//choose a perhaps-new explication\n\tdisplayExplication();\n\t\n\t$flap.height($flap.buffer + $explication.height());\n\t$flap.css(\"top\", $topbar.height() - $flap.height());\n\t\t\n\t$banTit.animate({top: $banTit.pos.top, left: $banTit.pos.left, \"font-size\": $banTit.size},\n\t\t\t{duration: dur});\n\t$banSub.animate({path: new $.path.bezier(subGrow), \"font-size\": $banSub.size}, {duration: dur});\n\t\n\t$flap.animate({top: 0}, {easing: \"easeOutBack\", duration: dur});\n\t$main.animate({top: $flap.height()}, {easing: \"swing\", duration: dur});\n\t\n\tbannered = true;\n}", "function makeBanner (text){\n var topBanner = ''\n var middleBanner = ''\n var bottomBanner = ''\n \n for (var i = 0; i < text.length + 4; i++){\n topBanner = topBanner + '*'\n }\n topBanner = topBanner + '\\n'\n \n middleBanner = '* ' + text + ' *' + '\\n'\n \n for (var i2 = 0; i2 < text.length + 4; i2++){\n bottomBanner = bottomBanner + '*'\n }\n bottomBanner = bottomBanner + '\\n'\n \n var totalBanner = topBanner + middleBanner + bottomBanner\n return totalBanner\n}", "function hideBanner() {\n\tif ($banSub.filter(\":animated\").length == 0) {\n\t\t// Because of that bug that causes the heights to be all wrong at first, this lets us \n\t\t// have nice heights after animating AND moving (otherwise animations would always be bad from small window\n\t\t// initial conditions).\n\t\t// Want to check that it isn't in the process of animating though when saving the values!\n\t\tsaveBanner();\n\t}\n\t\n\t$banTit.animate({top: $barTit.position().top, left: $barTit.position().left, \"font-size\": $barTit.css(\"font-size\")}, \n\t\t\t{duration: dur});\n\t$banSub.animate({path: new $.path.bezier(subShrink), \"font-size\": $barSub.css(\"font-size\")},\n\t\t\t{duration: dur});\n\t\n\t$flap.animate({top: $topbar.height() - $flap.height()}, \n\t\t\t{easing: 'easeInBack', duration: dur});\n\t$main.animate({top: $topbar.height()}, \n\t\t\t{easing: 'easeInBack', duration: dur});\n\t\n\tbannered = false;\n}", "function banner(slot) {\n var size = adSize(slot);\n return slot.nativeParams || slot.params.video ? null : {\n w: size[0],\n h: size[1],\n battr: slot.params.battr\n };\n}", "function ebiFrameworkCookieBanner() {\n console.warn('You are calling an old function name, update it to ebiFrameworkRunDataProtectionBanner();');\n ebiFrameworkRunDataProtectionBanner('1.4');\n}", "function fnHideShowBannersHome(){\r\n if(fnGetConfig(\"Home_Slideshow\")){\r\n var FCHideHomeBanners = document.getElementById('FC-HideHomeBanners');\r\n var FCShowHomeBanners = document.getElementById('FC-ShowHomeBanners');\r\n FCShowHomeBanners.innerHTML = FCHideHomeBanners.innerHTML;\r\n if(!FC$.isEH){ \r\n var oTxtSlide1 = document.getElementsByClassName(\"home-slide-txt-1\");\r\n for (i = 0; i < oTxtSlide1.length; i++) {\r\n oTxtSlide1[i].style.display=\"none\";\r\n } \r\n var oTxtSlide2 = document.getElementsByClassName(\"home-slide-txt-2\");\r\n for (i = 0; i < oTxtSlide2.length; i++) {\r\n oTxtSlide2[i].style.display=\"none\";\r\n } \r\n }\r\n }else{\r\n function fnDisplayOnlyBanner(displayMediaSize) {\r\n if (displayMediaSize.matches) {\r\n var FCHideHomeBanners = document.getElementById('FC-HideHomeBanners');\r\n var FCShowHomeBanners = document.getElementById('FC-ShowHomeBanners');\r\n FCShowHomeBanners.innerHTML = ''; \r\n } else {\r\n var FCHideHomeBanners = document.getElementById('FC-HideHomeBanners');\r\n var FCShowHomeBanners = document.getElementById('FC-ShowHomeBanners');\r\n FCShowHomeBanners.innerHTML = '<a href=\"'+ FCLib$.uk(\"url-sale\") +'\"><img src=\"'+FC$.PathImg +'fundotop.jpg\" width=\"100%\" alt=\"Banner\"'+ sLazy +'></a>'; \r\n }\r\n }\r\n var displayMediaSize = window.matchMedia(\"(max-width:1024px)\")\r\n fnDisplayOnlyBanner(displayMediaSize)\r\n displayMediaSize.addListener(fnDisplayOnlyBanner) \r\n }\r\n }", "function nntpchan_inject_banners(elem, prefix) {\n var n = Math.floor(Math.random() * banner_count);\n var banner = prefix + \"static/banner_\"+n+\".jpg\";\n var e = document.createElement(\"img\");\n e.src = banner;\n e.id = \"nntpchan_banner\";\n elem.appendChild(e);\n}", "function BannerManager(options) {\n this.banners = [];\n this.bannersIndex = [];\n this.server = null;\n this.displayBanner = false;\n this.rotationPeriod = 5000;\n this.carouselInitialised = false;\n \n this.bannerDialog = new BannerDialog();\n}", "function pmpro_sws_toggle_banner_settings() {\n\t\t\tvar banner = $( '#pmpro_sws_use_banner_select' ).val();\n\n\t\t\tif (typeof banner == 'undefined' ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (banner.length < 1 || banner == 'no') {\n\t\t\t\t$( '#pmpro_sws_banner_options' ).hide();\n\t\t\t\t$( '#pmpro_sws_css_selectors_description' ).hide();\n\t\t\t\t$( '.pmpro_sws_banner_css_selectors' ).hide();\n\t\t\t} else {\n\t\t\t\t$( '#pmpro_sws_css_selectors_description' ).show();\n\t\t\t\t$( '.pmpro_sws_banner_css_selectors' ).hide();\n\t\t\t\t$( '.pmpro_sws_banner_css_selectors[data-pmprosws-banner=' + banner + ']' ).show();\n\t\t\t\t$( '#pmpro_sws_banner_options' ).show();\n\t\t\t}\n\t\t}", "async getAds() {\n try {\n this.spinnerOn();\n const result = await this.axios.get(\n `${this.url}/ads/all?limit=${this.pageLimit}&page=${this.page}`,\n );\n return result.data.ads;\n } catch (error) {\n throw new Error(error);\n }\n }", "function IMNGetHeaderImage()\n{\n return \"imnhdr.gif\";\n}", "function printBanner(bannerText) {\n\tlet i = 0, j = 0, count = 0; s = \"\";\n\tfor (; j < 3; j++) {\n\t\tif (j != 1) {\n\t\t\tfor (i = 0; i < bannerText.length + 4; i++) {\n\t\t\t\ts += \"*\";\n\t\t\t}\n\t\t\tconsole.log(count + \": \" + s);\n\t\t} else {\n\t\t\ts = \"* \" + bannerText + \" *\";\n\t\t\tconsole.log(count + \": \" + s);\n\t\t}\n\t\ts = \"\";\n\t\tcount++;\n\t}\n}", "function getSiteLogoBanda(b) {\n var banda = docXML.getElementsByTagName(\"banda\")[b].getElementsByTagName(\"links\")[0];\n return \"img/\" + banda.getElementsByTagName(\"link\")[2].getAttribute(\"logo\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This auxiliary function is used to change Hex number.
function changeHex(h, n){ h=(typeof(h) == "string") ? parseInt(h,16) : h; if((h == 0 && n < 0)||(h == 255 && n > 0)){n = 0} h += n; h = (h > 255) ? 255 : (h < 0) ? 0 : h; return (h <= 15) ? "0" + h.toString(16) : h.toString(16); }
[ "function Hex(n) {\n n=Math.round(n);\n if (n < 0) {\n n = 0xFFFFFFFF + n + 1;\n }\n return n.toString(16).toUpperCase();\n}", "function fixedHex(number, length)\n{\n var str = number.toString(16).toUpperCase();\n while(str.length < length) {\n str = \"0\" + str;\n }\n return str;\n}", "function intToHex(integer){if(integer<0){throw new Error('Invalid integer as argument, must be unsigned!');}var hex=integer.toString(16);return hex.length%2?\"0\"+hex:hex;}", "function bigInt2hex(i){ return i.toString(16); }", "function setColorText(hexcolor) {\n color.textContent = hexcolor;\n}", "function hexReturnFull(hex) {\n\tvar shorthandRegex = /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i;\n\treturn hex.replace(shorthandRegex, function(m, r, g, b) {\n\t\treturn \"#\" + r + r + g + g + b + b;\n\t});\n}", "function toHex(byte) {\n\treturn ('0' + (byte & 0xFF).toString(16)).slice(-2);\n}", "function hex4(state) {\n return re(state, /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]/,\n function (s) {\n return parseInt(s, 16);\n });\n }", "function invertColor(hexColor) {\r\n var color = hexColor;\r\n color = color.substring(1); // remove #\r\n color = parseInt(color, 16); // convert to integer\r\n color = 0xFFFFFF ^ color; // invert three bytes\r\n color = color.toString(16); // convert to hex\r\n color = (\"000000\" + color).slice(-6); // pad with leading zeros\r\n color = \"#\" + color; // prepend #\r\n return color;\r\n}", "function swapEndian(hex) {\n if (hex.length % 2 !== 0) {\n return \"length must be a multiple of 2!\";\n }\n let data = \"\";\n for (let i = 1; i <= hex.length / 2; i++) {\n data += hex.substr(0 - 2 * i, 2);\n }\n return data;\n}", "function hex2hexKey(s){ return bigInt2hex(hex2bigIntKey(removeWhiteSpace(s))); }", "static ToHex(i) {\n const str = i.toString(16);\n if (i <= 15) {\n return ('0' + str).toUpperCase();\n }\n return str.toUpperCase();\n }", "function isHex(value) {\n if (value.length == 0) return false;\n if (value.startsWith('0x') || value.startsWith('0X')) {\n value = value.substring(2);\n }\n let reg_exp = /^[0-9a-fA-F]+$/;\n if (reg_exp.test(value) && value.length % 2 == 0) {\n return true;\n } else {\n return false;\n }\n}", "function updateColorOnClick(number, hex) {\n\t$('input[name=color]:nth('+ number +')').attr(\"checked\",\"checked\");\t\t\t\n\t$('#miniColors').miniColors('value', hex);\n\t$('#miniColors').focus();\n\treturn false;\n}", "function HexParse(i) {\n i = i.replace(/#/g, \"\");\n if (3 === i.length) {\n i = [i[0] + i[0], i[1] + i[1], i[2] + i[2]].join(\"\")\n }\n return i\n }", "function makeHexagons(){\r\n var hexX = 0;\r\n var hexY = 0;\r\n for(var i = 0; i < 91; i++){\r\n hexagons[i][1][0] = hexX;\r\n hexagons[i][1][1] = hexY;\r\n hexY += 1;\r\n if(hexX == 9 && hexY == 7){\r\n hexX += 1;\r\n hexY = 5;\r\n }\r\n if(hexX == 8 && hexY == 8){\r\n hexX += 1;\r\n hexY = 4;\r\n }\r\n if(hexX == 7 && hexY == 9){\r\n hexX += 1;\r\n hexY = 3;\r\n }\r\n if(hexX == 6 && hexY == 10){\r\n hexX += 1;\r\n hexY = 2;\r\n }\r\n if(hexX == 5 && hexY == 11){\r\n hexX += 1;\r\n hexY = 1;\r\n }\r\n if(hexY == 11){\r\n hexY = 0;\r\n hexX += 1;\r\n }\r\n }\r\n for(var i = 0; i < 91; i++){\r\n hexagons[i][0][1] = hexagons[i][1][1] - 5;\r\n hexagons[i][0][0] = (hexagons[i][0][1]) / importantNumber;\r\n hexagons[i][0][0] = Math.abs(hexagons[i][0][0]);\r\n hexagons[i][0][0] += hexagons[i][1][0];\r\n hexagons[i][0][1] += 5;\r\n hexagons[i][0][0] *= s/13;\r\n hexagons[i][0][1] *= s/14;\r\n hexagons[i][0][0] += s/13 * 1.5;\r\n hexagons[i][0][1] += s/13 * 1.5;\r\n }\r\n for(var i = 0; i < 91; i++){\r\n if(hexagons[i][1][1] == 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n if(hexagons[i][1][1] < 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n if(hexagons[i][1][1] > 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n }\r\n}", "function hexToDecimal(args) {\n var hexNumber = args[0],\n decNumber = 0,\n tempNumber,\n power = 1,\n i;\n\n for (i = hexNumber.length - 1; i >= 0; i -= 1) {\n switch (hexNumber[i]) {\n case 'A': tempNumber = '10'; break;\n case 'B': tempNumber = '11'; break;\n case 'C': tempNumber = '12'; break;\n case 'D': tempNumber = '13'; break;\n case 'E': tempNumber = '14'; break;\n case 'F': tempNumber = '15'; break;\n default: tempNumber = +hexNumber[i]; break;\n }\n\n decNumber += tempNumber * power;\n power *= 16;\n }\n\n console.log(decNumber);\n}", "function hexToInt(str, def)\n {\n if (typeof str === 'number')\n { return str; }\n\n const result = parseInt(str.replace('#', '0x'));\n\n if (isNaN(result)) return def;\n\n return result;\n }", "function getHexColor() {\n if (Math.round(Math.random())) {\n return \"ff\";\n } else {\n return \"00\";\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setzt die Daten dieses Scriptes in der Scriptdatenbank, die einen Datenaustausch zwischen den Scripten ermoeglicht optSet: Gesetzte Optionen (und Config)
function updateScriptDB(optSet) { // Eintrag ins Inhaltsverzeichnis... __DBTOC.versions[__DBMOD.name] = __DBMOD.version; // Permanente Speicherung der Eintraege... __DBMEM.setItem('__DBTOC.versions', JSON.stringify(__DBTOC.versions)); __DBMEM.setItem('__DBDATA.' + __DBMOD.name, JSON.stringify(optSet)); // Jetzt die inzwischen gefuellten Daten *dieses* Scripts ergaenzen... __DBDATA[__DBMOD.name] = getValue(optSet, { }); console.log(__DBDATA); }
[ "function initScriptDB(optSet) {\n const __INFO = GM_info;\n const __META = __INFO.script;\n\n //console.log(__INFO);\n\n __DBTOC.versions = getValue(JSON.parse(__DBMEM.getItem('__DBTOC.versions')), { });\n\n // Infos zu diesem Script...\n __DBMOD.name = __META.name;\n __DBMOD.version = __META.version;\n\n console.log(__DBMOD);\n\n // Zunaechst den alten Eintrag entfernen...\n __DBTOC.versions[__DBMOD.name] = undefined;\n\n // ... und die Daten der Fremdscripte laden...\n for (let module in __DBTOC.versions) {\n __DBDATA[module] = getValue(JSON.parse(__DBMEM.getItem('__DBDATA.' + module)), { });\n }\n}", "function startOptions(optConfig, optSet = undefined, classification = undefined) {\n optSet = initOptions(optConfig, optSet, true); // PreInit\n\n // Memory Storage fuer vorherige Speicherung...\n myOptMem = restoreMemoryByOpt(optSet.oldStorage);\n\n // Zwischengespeicherte Befehle auslesen...\n const __STOREDCMDS = getStoredCmds(myOptMem);\n\n // ... ermittelte Befehle ausführen...\n const __LOADEDCMDS = runStoredCmds(__STOREDCMDS, optSet, true); // BeforeLoad\n\n loadOptions(optSet);\n\n // Memory Storage fuer naechste Speicherung...\n myOptMem = startMemoryByOpt(optSet.storage, optSet.oldStorage);\n\n initScriptDB(optSet);\n\n optSet = initOptions(optConfig, optSet, false); // Rest\n\n if (classification !== undefined) {\n // Classification mit optSet verknuepfen...\n classification.optSet = optSet;\n\n // Umbenennungen durchfuehren...\n classification.renameOptions();\n }\n\n // ... ermittelte Befehle ausführen...\n runStoredCmds(__LOADEDCMDS, optSet, false); // Rest\n\n return optSet;\n}", "function loadSolutionSelectData() {\n \"use strict\";\n createS_Option();\n}", "function resetOptions(optSet, reload = true) {\n // Alle (nicht 'Permanent') gesetzten Optionen entfernen...\n deleteOptions(optSet, true, false, ! reload);\n\n if (reload) {\n // ... und Seite neu laden (mit \"Werkseinstellungen\")...\n window.location.reload();\n }\n}", "function setConfig (argv) {\n var configLookup = {}\n \n // expand defaults/aliases, in-case any happen to reference\n // the config.json file.\n applyDefaultsAndAliases(configLookup, aliases, defaults)\n \n Object.keys(flags.configs).forEach(function (configKey) {\n var configPath = argv[configKey] || configLookup[configKey]\n if (configPath) {\n try {\n var config = require(path.resolve(process.cwd(), configPath))\n \n Object.keys(config).forEach(function (key) {\n // setting arguments via CLI takes precedence over\n // values within the config file.\n if (argv[key] === undefined) {\n delete argv[key]\n setArg(key, config[key])\n }\n })\n } catch (ex) {\n if (argv[configKey]) error = Error('invalid json config file: ' + configPath)\n }\n }\n })\n }", "function initOptions(optConfig, optSet = undefined, preInit = undefined) {\n let value;\n\n if (optSet === undefined) {\n optSet = { };\n }\n\n for (let opt in optConfig) {\n const __OPTCONFIG = optConfig[opt];\n const __PREINIT = getValue(__OPTCONFIG.PreInit, false);\n\n if ((preInit === undefined) || (__PREINIT === preInit)) {\n const __CONFIG = getSharedConfig(__OPTCONFIG);\n const __ALTACTION = getValue(__CONFIG.AltAction, __CONFIG.Action);\n // Gab es vorher einen Aufruf, der einen Stub-Eintrag erzeugt hat? Wurde ggfs. bereits geaendert...\n const __USESTUB = ((preInit === false) && __PREINIT);\n const __LOADED = (__USESTUB ? optSet[opt].Loaded : false);\n const __VALUE = (__USESTUB ? optSet[opt].Value : initOptValue(__CONFIG));\n\n optSet[opt] = {\n 'Config' : __CONFIG,\n 'Loaded' : __LOADED,\n 'Value' : __VALUE,\n 'SetValue' : __CONFIG.SetValue,\n 'Action' : initOptAction(__CONFIG.Action, opt, optSet),\n 'AltAction' : initOptAction(__ALTACTION, opt, optSet)\n };\n } else if (preInit) { // erstmal nur Stub\n optSet[opt] = {\n 'Config' : __OPTCONFIG,\n 'Loaded' : false,\n 'Value' : initOptValue(__OPTCONFIG)\n };\n }\n }\n\n return optSet;\n}", "loadEngineDefaults() {\n for (let key in DEFAULT_SETTINGS) {\n const setting = new Setting(key, DEFAULT_SETTINGS[key]);\n super.set(setting.getName(), setting);\n }\n }", "ChangeScriptMap() {\n\n }", "function setOptions (seriesName, showData, showLabel) {\n\n\t\t\t\tif (seriesName === \"payoutObj\" || seriesName === \"givensObj\") {\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][0] = {};\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][1] =\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t \t // CropA\n\t\t\t\t\t\t \t label: \"Crop A\",\n\t\t\t\t\t\t lineWidth: 2,\n\t\t\t\t\t\t showMarker: false,\n\t\t\t\t\t\t renderer:$.jqplot.LineRenderer,\n\t\t\t\t\t\t xaxis:'xaxis',\n\t\t\t\t\t\t \tyaxis:'yaxis',\n\t\t\t\t\t\t show: true\n\t\t\t\t\t\t };\n\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][2] = {\n\t\t\t\t\t\t // CropB\n\t\t\t\t\t\t label: \"Crop B\",\n\t\t\t\t\t\t lineWidth: 2,\n\t\t\t\t\t\t showMarker: false,\n\t\t\t\t\t\t renderer:$.jqplot.LineRenderer,\n\t\t\t\t\t\t xaxis:'xaxis',\n\t\t\t\t\t\t \tyaxis:'yaxis',\n\t\t\t\t\t\t show: true\n\t\t\t\t\t\t };\n\t\t\t\t}\n\n\t\t\t\telse if (seriesName === \"historyObj\") {\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][0] = {\n\t\t\t\t\t\t\t\t// Weather\n\t\t\t\t\t \tlabel: \"Weather\",\n\t\t\t\t\t \tshowMarker: false,\n\t\t\t\t\t \trenderer:$.jqplot.BarRenderer,\n\t\t\t\t\t \trendererOptions: {\n\t\t\t\t\t \t\tbarWidth: 10,\n\t\t\t\t\t \t\tbarPadding: 0,\n\t \t\t\tbarMargin: 0,\n\t \t\t\tbarWidth: 10,\n\t\t\t\t\t \tfillToZero: true,\n\t\t\t\t\t \tshadowAlpha: 0\n\t\t\t\t\t \t},\n\t\t\t\t\t \txaxis:'xaxis',\n\t\t\t\t\t \tyaxis:'yaxis',\n\t\t\t\t\t \tshow: true\n\t\t\t\t\t};\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][1] = {};\n\t\t\t\t\tchartObjects[seriesName][\"seriesArray\"][2] = {};\n\t\t\t\t}\n\n\t\t\t\tgame.continuous.optionsObj[seriesName] = {\n\t\t\t\t\t series:\n\t\t\t\t\t chartObjects[seriesName][\"seriesArray\"]\n\t\t\t\t\t ,\n\n\t\t\t\t\t seriesColors:\n\t\t\t\t\t \t\tchartObjects[seriesName][\"color\"]\n\t\t\t\t\t ,\n\n\n\t\t\t\t\t grid: {\n\t\t\t \t\tdrawGridlines: true,\n\t\t\t \t\tshadow: false,\n\t\t\t \t\tborderWidth: 1,\n\t\t\t \t\tdrawBorder: true,\n\t\t\t \t },\n\n\t\t\t \t // The \"seriesDefaults\" option is an options object that will\n\t\t\t \t //be applied to all series in the chart.\n\t\t\t\t\t seriesDefaults: {\n\t\t\t\t\t shadow: false,\n\t\t\t\t\t rendererOptions: {\n\t\t\t\t\t smooth: true,\n\t\t\t\t\t highlightMouseOver: false,\n\t\t\t\t\t highlightMouseDown: false,\n\t\t\t \t\t\thighlightColor: null,\n\t\t\t \t\t\t},\n\t\t\t\t\t\t\t markerOptions: {\n\t\t\t \t\tshadow: false,\n\t\t\t\t\t },\n\n\n\t\t\t\t\t //pointLabels uses the final value in parabolaArray[i] as its data\n\t\t\t\t\t pointLabels: {\n\t\t\t\t\t \tshow: showData,\n\t\t\t\t\t \tlocation:'nw',\n\t\t\t\t\t \typadding: 3,\n\t\t\t\t\t \txpadding: 3,\n\t\t\t\t\t \tformatString: \"%#.0f\"\n\t\t\t\t\t }\n\t\t\t\t\t },\n\n\t\t\t\t\t axesDefaults: {\n\t \t\t\t\tlabelRenderer: $.jqplot.CanvasAxisLabelRenderer\n\t \t\t\t\t },\n\t\t\t\t\t axes: {\n\n\t\t\t \t\txaxis:{\n\t\t\t \t\t\tticks: ticksWeatherX,\n\t\t\t \t\t\tborderWidth: 1.5,\n\t\t\t \t\t\trendererOptions:{\n\t\t\t \ttickRenderer:$.jqplot.AxisTickRenderer\n\t\t\t },\n\t\t\t \ttickOptions:{\n\t\t\t mark: \"cross\",\n\t\t\t //formatString: \"%#.0f\",\n\t\t\t showMark: true,\n\t\t\t showGridline: true\n\t\t\t },\n\n\t\t\t \t\t\tlabel:'Rainfall (inches)',\n\t\t\t \t\t\tlabelRenderer: $.jqplot.AxisLabelRenderer,\n\t\t\t \t\t\tlabelOptions: {\n\t\t\t \t\t\tfontFamily: 'Georgia, serif',\n\t\t\t \t\t\tfontSize: '12pt'\n\t\t\t \t\t\t}\n\t\t\t \t\t},\n\n\t\t\t \t\tyaxis:{\n\t\t\t \t\t\tticks: ticksY,\n\t\t\t \t\t\trendererOptions:{\n\t\t\t \ttickRenderer:$.jqplot.CanvasAxisTickRenderer\n\t\t\t },\n\n\t\t\t \ttickOptions:{\n\t\t\t mark: \"cross\",\n\t\t\t showLabel: showData,\n\t\t\t //formatString: \"%#.0f\",\n\t\t\t showMark: true,\n\t\t\t showGridline: true\n\t\t\t },\n\n\t\t\t \t\t\tlabel:'Points',\n\t\t\t \t\t\tlabelRenderer: $.jqplot.CanvasAxisLabelRenderer,\n\t\t\t\t\t\t\t\t\tlabelOptions: {\n\t\t\t\t \t\t\tfontFamily: 'Georgia, serif',\n\t\t\t\t \t\t\tfontSize: '12pt',\n\t\t\t\t \t\t\tshow: showLabel\n\t\t\t \t\t\t\t}\n\t\t\t \t\t\t}\n\t\t\t \t\t }, // end of axes\n\n\t\t\t\t\t\tcanvasOverlay: {\n\t\t\t \t\tshow: true,\n\t\t\t\t objects:\n\n\t\t\t\t \t[chartObjects[seriesName][\"canvasOverlayLine\"]]\n\n\t\t\t\t\t\t} // end of canvasOverlay\n\n\t\t\t\t\t}; // end optionsObj object\n\n\t\t\t\treturn game.continuous.optionsObj[seriesName];\n\t\t\t}", "function set_settings(machine) {\r\n\t\tlet $st_ring = $('#stator').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$a_ring = $('#a_ring').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$b_ring = $('#b_ring').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$c_ring = $('#c_ring').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$th_ring = $('#thin_ring').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$re_ring = $('#reflector').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\r\n\t\t\t$st_set = $('#stator_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$a_set = $('#a_ring_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$b_set = $('#b_ring_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$c_set = $('#c_ring_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$th_set = $('#thin_ring_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$re_set = $('#reflector_ring_ring_setting').prop('disabled', false).val('0'),\r\n\r\n\t\t\t$st_grd = $('#stator_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$a_grd = $('#a_ring_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$b_grd = $('#b_ring_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$c_grd = $('#c_ring_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$th_grd = $('#thin_ring_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$re_grd = $('#reflector_ring_ground_setting').prop('disabled', false).val('0');\r\n\r\n\t\tfilter_ring($st_ring, machine.entry, $st_set, $st_grd); // the stator ring\r\n\t\tfilter_ring($a_ring, machine.rings, $a_set, $a_grd); // the a ring\r\n\t\tfilter_ring($b_ring, machine.rings, $b_set, $b_grd); // the b ring\r\n\t\tfilter_ring($c_ring, machine.rings, $c_set, $c_grd); // the c ring\r\n\t\tfilter_ring($th_ring, machine.extra, $th_set, $th_grd); // the thin ring\r\n\t\tfilter_ring($re_ring, machine.reflector, $re_set, $re_grd); // the reflector ring\r\n\r\n\t\tfilter_stecker(machine);\r\n\r\n\t\t// none of the machines have movable stators\r\n\t\t// disable the settings in strict mode\r\n\t\t$st_set.prop('disabled', true);\r\n\t\t$st_grd.prop('disabled', true);\r\n\r\n\t\t// reflector options\r\n\t\t$re_set.prop('disabled', ! machine.movable_reflector);\r\n\t\t$re_grd.prop('disabled', ! machine.movable_reflector);\r\n\t}", "_applyScript(value, old) {\n qx.bom.storage.Web.getSession().setItem(cboulanger.eventrecorder.UiController.CONFIG_KEY.SCRIPT, value);\n if (this.getRecorder()) {\n this.getRecorder().setScript(value);\n }\n }", "function setNamespace() {\n var namespace = _scriptTag.getAttribute('data-namespace');\n if (namespace) {\n if (constants.NAMESPACE_REGEX_VALIDATION.test(namespace)) {\n _config.namespace = namespace;\n } else {\n throw new Error(Errors.INVALID_NAMESPACE);\n }\n } else {\n _config.namespace = constants.DEFAULT_NAMESPACE;\n }\n}", "static setDebugOverrides() {\n if (!game.settings.get(this.MODULE_ID, this.SETTINGS.overrideConfigDebug)) {\n this.log(false, 'doing nothing in setDebugOverrides');\n return;\n }\n\n const debugOverrideSettings = game.settings.get(this.MODULE_ID, this.SETTINGS.debugOverrides);\n\n // set all debug values to match settings\n Object.keys(CONFIG.debug).forEach((debugKey) => {\n const relevantSetting = debugOverrideSettings[debugKey];\n\n // only override booleans to avoid conflicts with other modules\n if (relevantSetting !== undefined && typeof relevantSetting === 'boolean') {\n CONFIG.debug[debugKey] = relevantSetting;\n }\n\n this.log(false, 'setDebugOverride', debugKey, 'to', relevantSetting);\n });\n }", "function renameOptions(optSet, optSelect, renameParam = undefined, renameFun = prefixName) {\n if (renameFun === undefined) {\n console.error(\"RENAME: Illegale Funktion!\");\n }\n for (let opt in optSelect) {\n const __OPTPARAMS = optSelect[opt];\n const __OPT = optSet[opt];\n\n if (__OPT === undefined) {\n console.error(\"RENAME: Option '\" + opt + \"' nicht gefunden!\");\n } else {\n const __NAME = getOptName(__OPT);\n const __NEWNAME = renameFun(__NAME, renameParam);\n const __ISSCALAR = (typeof __OPTPARAMS === 'boolean');\n // Laedt die unter dem neuen Namen gespeicherten Daten nach?\n const __RELOAD = (__ISSCALAR ? __OPTPARAMS : __OPTPARAMS.reload);\n // Laedt auch Optionen mit 'AutoReset'-Attribut?\n const __FORCE = (__ISSCALAR ? true : __OPTPARAMS.force);\n\n renameOption(__OPT, __NEWNAME, __RELOAD, __FORCE);\n }\n }\n}", "function procHaupt() {\n const __TEAMPARAMS = getTeamParamsFromTable(getTable(1), __TEAMSEARCHHAUPT); // Link mit Team, Liga, Land...\n\n buildOptions(__OPTCONFIG, __OPTSET, {\n 'teamParams' : __TEAMPARAMS,\n 'hideMenu' : true\n });\n\n const __NEXTZAT = getZATNrFromCell(getRows(0)[2].cells[0]); // \"Der naechste ZAT ist ZAT xx und ...\"\n const __CURRZAT = __NEXTZAT - 1;\n const __DATAZAT = getOptValue(__OPTSET.datenZat);\n\n if (__CURRZAT >= 0) {\n console.log(\"Aktueller ZAT: \" + __CURRZAT);\n\n // Neuen aktuellen ZAT speichern...\n setOpt(__OPTSET.aktuellerZat, __CURRZAT, false);\n\n if (__CURRZAT !== __DATAZAT) {\n console.log(__DATAZAT + \" => \" + __CURRZAT);\n\n // ... und ZAT-bezogene Daten als veraltet markieren\n __TEAMCLASS.deleteOptions();\n\n // Neuen Daten-ZAT speichern...\n setOpt(__OPTSET.datenZat, __CURRZAT, false);\n }\n }\n}", "onOptionsChange(options) {\n this.vssue.setOptions(options);\n }", "function setGlobalOptions(options) {\n (0, utils_1.assertion)(typeof options === 'object', new TypeError('\"options\" argument needs to be an object!'));\n logSettings_1.logger.info('\"setGlobalOptions\" got called with', options);\n for (const key of Object.keys(options)) {\n data_1.globalOptions[key] = Object.assign({}, data_1.globalOptions[key], options[key]);\n }\n logSettings_1.logger.info('new Global Options:', options);\n}", "function setLigandOptions() {\n ligandSelect.innerHTML = \"\";\n var options = [[\"\", \"select ligand\"]];\n struc.structure.eachResidue(function(rp) {\n if (rp.isWater()) return;\n var sele = \"\";\n if (rp.resno !== undefined) sele += rp.resno;\n if (rp.inscode) sele += \"^\" + rp.inscode;\n if (rp.chain) sele += \":\" + rp.chainname;\n var name = (rp.resname ? \"[\" + rp.resname + \"]\" : \"\") + sele;\n if (rp.entity !== undefined) {\n if (rp.entity.description) name += \" (\" + rp.entity.description + \")\"};\n options.push([sele, name]);\n }, new NGL.Selection(ligandSele));\n options.forEach(function(d) {\n ligandSelect.add(\n createElement(\"option\", {\n value: d[0],\n text: d[1]\n })\n );\n });\n}", "static set_default_options(options) {\n $.extend(default_dialog_options, options);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The purpose of this kata is to implement the undoRedo function. This function takes an object and returns an object that has these actions to be performed on the object passed as a parameter: set(key, value) Assigns the value to the key. If the key does not exist, creates it. get(key) Returns the value associated to the key. del(key) removes the key from the object. undo() Undo the last operation (set or del) on the object. Throws an exception if there is no operation to undo. redo() Redo the last undo operation (redo is only possible after an undo). Throws an exception if there is no operation to redo. After set() or del() are called, there is nothing to redo. All actions must affect to the object passed to undoRedo(object) function. So you can not work with a copy of the object. Any set/del after an undo should disallow new undos.
function undoRedo(object) { function undoRedo(object) { var prevObj = []; var n = 0; var clone = {}; for(var keyC in object) { clone[keyC] = object[keyC]; } prevObj.push(clone); return { set: function(key, value) { object[key] = value; var cloneSet = {}; for(var keyCloneSet in object) { cloneSet[keyCloneSet] = object[keyCloneSet]; } prevObj.push(cloneSet); n++; }, get: function(key) { return object[key]; }, del: function(key) { delete object[key]; var cloneDel = {}; for(var keyCloneDel in object) { cloneDel[keyCloneDel] = object[keyCloneDel]; } prevObj.push(cloneDel); n++; }, undo: function() { if (n >= 1) { for (var key in object) { delete object[key]; } for(var keyClone in prevObj[n-1]) { object[keyClone] = prevObj[n-1][keyClone]; } n--; } else { throw new Error('There is nothing to undo'); } }, redo: function() { if (n < (prevObj.length - 1)) { for (var key in object) { delete object[key]; } n++; for(var keyClone in prevObj[n]) { object[keyClone] = prevObj[n][keyClone]; } } else { throw new Error('There is nothing to redo'); } } }; } }
[ "function Undoable() {\n\n // Contains the undo-redo pair...\n function memento(undo, redo) {\n this.undo = undo;\n this.redo = redo;\n };\n \n var undoStack = new Array();\n var redoStack = new Array();\n\n this.clear = function() {\n undoStack = new Array();\n redoStack = new Array();\n };\n\n this.add = function (undo, redo) {\n if (undo == undefined) {\n throw 'undo is undefined';\n }\n if (redo == undefined) {\n redo = function(){};\n }\n undoStack.push(new memento(undo, redo));\n redoStack = new Array();\n };\n\n this.canUndo = function() {\n if (undoStack.length != 0) {\n return true;\n }\n return false;\n };\n\n this.canRedo = function() {\n if (redoStack.length != 0) {\n return true;\n }\n return false;\n };\n\n this.undo = function() {\n if (undoStack.length == 0) {\n return;\n }\n\n var current = undoStack.pop();\n current.undo();\n\n redoStack.push(current);\n };\n\n this.redo = function() {\n if (redoStack.length == 0) {\n return;\n }\n\n var current = redoStack.pop();\n current.redo();\n\n undoStack.push(current);\n };\n}", "function initUndoRedo() {\n canvas.on(\"object:modified\", function () {\n state.save();\n });\n\n canvas.on(\"object:removed\", function () {\n state.save();\n });\n\n canvas.on(\"object:statechange\", function () {\n state.save();\n });\n}", "function UndoRedo(e) {\n var evtobj = window.event ? event : e\n\n if (evtobj.keyCode == 90 && evtobj.ctrlKey) {\n\n var rdAllowUndo = rdGetCookie(\"rdAllowUndo\")\n var divUndo = document.getElementById('divUndoEnabled');\n if (rdAllowUndo == \"True\" && divUndo)\n divUndo.click();\n }\n\n if (evtobj.keyCode == 89 && evtobj.ctrlKey) {\n\n var rdAllowRedo = rdGetCookie(\"rdAllowRedo\");\n var divRedo = document.getElementById('divRedoEnabled');\n\n if (rdAllowRedo == \"True\" && divRedo)\n divRedo.click();\n }\n}", "redo(callback) {\n if (this.redoStack.length > 0)\n this.applyState(this.stateStack, this.redoStack.pop(), callback);\n }", "function saveUndoState()\n{\n\t// $.extend is used to deep copy the array because JIT doesn't >:|\n\tundoStates.push({ graph: $.extend(true, [], rgraph.toJSON('graph')), root: rgraph.root.id});\n\tif(undoStates.length > MAX_UNDO)\n\t\tundoStates.shift();\n\t$('#undo').removeAttr('disabled');\n}", "function addUndo(func) {\n undoQueue.push(func);\n return;\n}", "function undo() {\n if (stateCurrent === 0) return false;\n stateCurrent--;\n return true;\n}", "undoMove() {\n let previousMove = this.gameSequence.getCurrentMove()\n\n if (previousMove) {\n this.undo = true\n this.gameSequence.undo();\n this.state.updateState(\"Animation Start\");\n return 0\n } else {\n console.warn('No moves to undo')\n return -1\n }\n }", "save() {\n undo.push();\n store.content.fromJSON(this.getValue());\n super.save();\n }", "undoButton() {\n this.state.undo();\n }", "handleUndoClick() {\n const newStep = this.state.currStep === 0 ? 0 : this.state.currStep - 1;\n let numCount = this.countNums(this.state.history[newStep].board);\n this.setState({\n currStep: newStep,\n numCount: numCount,\n });\n }", "function addRedo(func) {\n redoQueue.push(func);\n return;\n}", "applyTo(obj, prev, dest) {\n let selfChanges = {};\n let sObj = simpleObj(obj);\n\n let forwards = [];\n\n // forward changes\n let changes = this.forward.reduce( (m,p) => {\n if(sObj[p] !== prev[p]){\n m[p]=sObj[p];\n selfChanges[p]=prev[p];\n forwards.push(p);\n }\n return m;\n },{});\n // revert forwarded changes\n obj.set(selfChanges);\n\n // mirror changes\n changes = this.mirror.reduce( (m,p) => {\n if(sObj[p] !== prev[p] && !forwards.includes(p)){\n m[p] = sObj[p];\n }\n return m;\n },changes);\n\n\n this.adjustments.forEach(a => Object.assign(changes,a.getMods(changes,true)));\n\n let dMod = Modify.getInstanceFor(dest.id);\n dMod.applyFrom(obj,changes,dest,forwards);\n }", "function anim(effect, undo) {\n // returns a function that can be used to provide function calls that are applied later\n // when viewing the visualization\n return function () {\n var jsav = this; // this points to the objects whose function was decorated\n var args = $.makeArray(arguments),\n norecord = false;\n if (args.length > 0 && args[args.length - 1] && typeof args[args.length - 1] === \"object\" &&\n args[args.length - 1].record === false) {\n norecord = true;\n }\n if (!jsav.hasOwnProperty(\"_redo\")) {\n jsav = this.jsav;\n }\n if (jsav.options.animationMode === 'none' || norecord) { // if not recording, apply immediately\n effect.apply(this, arguments);\n } else {\n var stackTop = jsav._undo[jsav._undo.length - 1];\n if (!stackTop) {\n stackTop = new AnimStep();\n jsav._undo.push(stackTop);\n }\n // add to stack: [target object, effect function, arguments, undo function]\n var oper = new AnimatableOperation({\n obj: this,\n effect: effect,\n args: arguments,\n undo: undo\n });\n stackTop.add(oper);\n if (jsav._shouldAnimate()) {\n jsav.container.addClass(playingCl);\n }\n oper.apply();\n if (jsav._shouldAnimate()) {\n jsav._clearPlaying();\n }\n }\n return this;\n };\n }", "function OberservableUndoableList(factory) {\n _super.call(this);\n this._inCompound = false;\n this._isUndoable = true;\n this._madeCompoundChange = false;\n this._index = -1;\n this._stack = [];\n this._factory = null;\n this._factory = factory;\n this.changed.connect(this._onListChanged, this);\n }", "function addObject(copy, key, value) {\n\tcopy[key] = value;\n\treturn copy[key];\n}", "function objectChanged(_o) {\n replace(ka.objs, o, _o);\n recalc(ka);\n }", "get redoDepth() { return this.undone.events }", "function update_obj(dest, key, data, keys, context)\n{\n // There are further instructions remaining - we will need to recurse\n if (keys.length) {\n // There is a pre-existing destination object. Recurse through to the object key\n if (dest !== null && typeof dest !== 'undefined') {\n let o = update(dest[key.name], data, keys, context)\n if (o !== null && typeof o !== 'undefined')\n dest[key.name] = o\n }\n // There is no pre-existing object. Check to see if data exists before creating a new object\n else {\n // Check to see if there is a value before creating an object to store it\n let o = update(null, data, keys, context)\n if (o !== null) {\n dest = {}\n dest[key.name] = o\n }\n }\n }\n // This is a leaf. Set data into the dest\n else\n dest = set_data(dest, key, data, context)\n\n return dest\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the max limit to add a choise is reached.
hasReachedMaxLimit (list, maxLimit) { return list && list.length === maxLimit; }
[ "moreQuestionsAvailable() {\n\treturn (this.progress.qAnswered < this.progress.qTotal);\n }", "isMax() {\n if(this.weaponType == this.weaponTypeMax) {\n return true;\n }\n }", "function HasExceededclicklimit(selector)\n {\n var limit = Getclicklimit(selector);\n return (limit != 0 && parseInt(selector.data(\"data-clickCount\")) >= limit);\n }", "requestedSalaryIsMoreThanMax(application) {\n return application.posted_salary_max && \n application.requested_salary && \n application.posted_salary_max < application.requested_salary;\n }", "function OneShotLimitReached()\n{\n\treturn (crashesStarted + gearShiftsStarted) > oneShotLimit;\n}", "function busted(hand) {\n if (getTotal(hand) > MAX_VALUE) {\n return true;\n } else {\n return false;\n }\n}", "function canProceedToNextLevel(pelletsEaten) {\n return pelletsEaten === 244; // PacMan needs to eat all 244 pellets to proceed\n}", "function smallEnough(a, limit){\n // const isBelowThreshold = (currentValue) => currentValue < limit;\n return a.every(currentValue => currentValue <= limit)\n\n}", "function getPlayersOverVerify(objForm) {\n\tvar playersNumber = parseInt(objForm.total_players.value);\n\tvar playersMax = parseInt(objForm.max_players.value);\n\t\n\tif (playersNumber > playersMax) {\n\t\tvar answer = confirm(\"There will be \" + playersNumber + \" players when only \" + playersMax + \" players are allowed! Are you sure you want to override this setting?\");\n\t\t\n\t\tif (answer === true) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t} \n\t}\n\t\n\treturn true;\n}", "'players.allRolesAtMaximum'(){\n for(i = 0; i<CHARACTERS.length;i++){\n if(Players.findOne({'owner':Meteor.userId()}).characters[i].level < MAX_LEVEL)\n return false;\n }\n return true;\n }", "getCanReplicate() {\n return this.getMaximumReplications() === 1 ? false :\n this.getCurrentReplications() <= this.getMaximumReplications();\n }", "function validPickCount()\n {\n $scope.maxPicksReached1 = false;\n $scope.maxPicksReached2 = false;\n $scope.maxPicksReached3 = false;\n $scope.maxPicksReached4 = false;\n $scope.maxPicksReached5 = false;\n var returnVal = true;\n var valid = true;\n var hist = {};\n\n //check against max pick count\n $scope.displayedCollection.map(function (m)\n {\n m.ui_picks.map(function (a) {\n\n if (a.confidence_value == null)\n return;\n\n if (a.confidence_value in hist) {\n hist[a.confidence_value]++;\n if (hist[a.confidence_value] == $scope.detailsScope.detailsObject.max_pick_count) {\n\n switch (a.confidence_value) {\n case 1:\n $scope.maxPicksReached1 = true;\n break;\n case 2:\n $scope.maxPicksReached2 = true;\n break;\n case 3:\n $scope.maxPicksReached3 = true;\n break;\n case 4:\n $scope.maxPicksReached4 = true;\n break;\n case 5:\n $scope.maxPicksReached5 = true;\n break;\n }\n }\n\n if (hist[a.confidence_value] > $scope.detailsScope.detailsObject.max_pick_count) {\n returnVal = false;\n }\n\n }\n else {\n hist[a.confidence_value] = 1;\n } \n\n \n });\n });\n\n return returnVal;\n }", "function isEnoughCoinsForGraf() {\n if (state.activeCoins.length === 0) {\n return false;\n }\n return true;\n }", "hasRemainingUsers() {\n return this.remainingUsers !== 0\n }", "function CheckExpenseItems(itemCount)\n{\n if (itemCount > 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}", "function fetchMaxItems() {\n //Checking if the maximum level is exceeded\n if(level <= config.numberOfLevels){\n //Return the number of items allowed for the level\n return config.itemDifferencePerLevel * level;\n } else {\n //game over scenario is envoked if maximum level is exceeded\n gameOver();\n }\n}", "exceedsMaxSize() {\n return JSON.stringify(this.data).length > MAX_SESSION_DATA_SIZE;\n }", "function checkLoad() {\n if (elevator.loadFactor() < maxLoad && elevator.maxPassengerCount() <= 5) {\n var elevatorFull = false;\n } else if (elevator.loadFactor() < maxLargeLoad && elevator.maxPassengerCount() > 5) {\n var elevatorFull = false;\n } else if (elevator.loadFactor() > maxLoad && elevator.maxPassengerCount() <= 5) {\n var elevatorFull = true;\n } else if (elevator.loadFactor() > maxLargeLoad && elevator.maxPassengerCount() >= 5) {\n var elevatorFull = true;\n } else {\n var elevatorFull = false;\n }\n return elevatorFull;\n }", "static evalReadingLengthWithinLimit(dict, limit) {\n return (dict.ReadingSim.toString().length <= Number(limit));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configures file logging based on settings
function configureFileLogging () { var isEnabled = ('true' === process.env.LOGGING_FILE_ACTIVE) // mandatory envVar , logsPath = process.env.LOGGING_FILE_PATH || 'logs/' , logFile = process.env.LOGGING_FILE_FILENAME || 'node.log' , logFilename = path.normalize(path.join(logsPath, logFile)) , expressJsLog = getExpressJsLog() , clientAppLog = getClientAppLog(); if (isEnabled) { // prepare path for winston to write to and set logging file on path prepared successfully fs.mkdir(logsPath, undefined, function() { winston.add(winston.transports.File, { level: serverAppLogTreshold, filename: logFilename, timestamp: true }); expressJsLog.add(winston.transports.File, { level: serverAppLogTreshold, filename: logFilename, timestamp: true }); clientAppLog.add(winston.transports.File, { level: clientAppLogTreshold, filename: logFilename, timestamp: true }); }); } }
[ "function configureLog() {\n\t\n\t/**\n\t * create log file path\n\t */\n\tvar logdir = path.join(__dirname, 'logs');\n\n\tif (!fs.existsSync(logdir)){\n\t fs.mkdirSync(logdir);\n\t}else {\n\t\t/**\n\t\t * Delete previous log files\n\t\t */\n\t\ttry {\n\t\t\tfs.unlinkSync(path.join(__dirname, 'logs/webapp.log'));\n\t\t\tfs.unlinkSync(path.join(__dirname, 'logs/webrtc.log'));\n\t\t}catch(err){\n\t\t\tconsole.error(err);\n\t\t}\n\t}\n\n\tlog4js.configure(logger_cfg, { cwd: logging_path });\t\n}", "function setLogger(argv) {\n logger.level = argv.debug ? 'debug' : argv.verbose ? 'verbose' : 'info';\n}", "_initLogger() {\n\t\tglobal.logger = this.options.logger;\n\t}", "setDefaultLogger() {\n const defaultLevel = Meteor.isProduction ? 'error' : 'trace';\n const defaultLogger = loglevel.createLogger('', defaultLevel);\n\n this.setLogger(defaultLogger);\n }", "enableLog() {\n this.enabled = logCfg.enable;\n }", "function configureConsoleLogging () {\n var isEnabled = ('true' === process.env.LOGGING_CONSOLE_ACTIVE) // mandatory envVar\n , expressJsLog = getExpressJsLog()\n , clientAppLog = getClientAppLog();\n\n // remove default console, and if console logging enabled, add new console with our custom settings\n // headless testing doesn't have console instance attached, try-catch to prevent failure\n try { winston.remove(winston.transports.Console); } catch(err) {}\n try { expressJsLog.remove(winston.transports.Console); } catch(err) {}\n try { clientAppLog.remove(winston.transports.Console); } catch(err) {}\n\n if (isEnabled) {\n winston.add(winston.transports.Console, { level: serverAppLogTreshold, timestamp: true });\n expressJsLog.add(winston.transports.Console, { level: serverAppLogTreshold, timestamp: true });\n clientAppLog.add(winston.transports.Console, { level: clientAppLogTreshold, timestamp: true });\n }\n}", "_initRequestLogger() {\n\t\tif (this.options.requestLogging) {\n\t\t\tthis.app.use(morgan('tiny', {\n\t\t\t\tstream: {\n\t\t\t\t\twrite: (message) => {\n\t\t\t\t\t\tlogger.info(message);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}));\n\t\t}\n\t}", "function logFileChange(event) {\n\t\tvar fileName = require('path').relative(__dirname, event.path);\n\t\tconsole.log('[' + 'WATCH'.green + '] ' + fileName.magenta + ' was ' + event.type + ', running tasks...');\n\t}", "setConsoleLogger(consoleLogger) {\n global.G_configLogger = consoleLogger\n }", "function logConfiguration (program) {\n utils.log(chalk.bold.green.underline('\\nConfiguration: '))\n utils.log(`Desktop Converter Location: ${program.desktopConverter}`)\n utils.log(`Expanded Base Image: ${program.expandedBaseImage}`)\n utils.log(`Publisher: ${program.publisher}`)\n utils.log(`Dev Certificate: ${program.devCert}`)\n utils.log(`Windows Kit Location: ${program.windowsKit}`)\n utils.log(`Package Version: ${program.packageVersion}`)\n utils.log(`Signtool Params: ${program.signtoolParams}`)\n}", "function setupLogging(log) {\n function errorLogger(level, error) {\n var logMessage = {\n ts: new Date().toJSON(),\n level,\n [level]: error\n };\n if (level !== 'info') {\n log.push(logMessage);\n }\n logEmitter.emit('display', logMessage);\n }\n\n logEmitter.addListener('info', function (error) {\n return errorLogger('info', error);\n });\n logEmitter.addListener('warning', function (error) {\n return errorLogger('warning', error);\n });\n logEmitter.addListener('error', function (error) {\n return errorLogger('error', error);\n });\n}", "function logFileOutput(dataToLog) {\n\n file.appendFile(\"./log.txt\", dataToLog, function (err) {\n\n if (err) {\n console.log(err);\n }\n\n });\n\n}", "function writeConfigFiles(err) {\n if(err) throw err\n var settingsTemplate = args.envs ? functionTemplate : objectTemplate;\n _.mapValues(defaultConfig, function(v, k) {\n\n var pluginSettings = {\n file: (k === 'ApplicationEnvironment') ? objectTemplate(k,v) : settingsTemplate(k, v),\n path: path.join(pluginConfigDir, k + '.js')\n };\n fs.stat(pluginSettings.path, function(err, stats) {\n if(err && err.code === 'ENOENT') {\n fileHelpers.write(pluginSettings, 'Writing Plugin configs to', allDone);\n }\n else {\n console.log('Skipping existing file ./' + path.relative(process.cwd(), pluginSettings.path))\n allDone()\n }\n });\n })\n }", "async function log(config) {\n let s = `[${config['timestamp'].toISOString().replace('T', ' ').split('.')[0]}] [${config['severity'].toUpperCase()}]: [${config['uuid']}] ${config['message']}`;\n if (config['severity'].toUpperCase() == \"WARN\") console.warn(s);\n else if (config['severity'].toUpperCase() == \"ERROR\") console.error(s);\n else if (config['severity'].toUpperCase() == \"INFO\") console.info(s);\n else console.log(s);\n\n if (!config['nolog']) {\n fs.appendFileSync('logs.txt', `${s}\\n`, 'utf8');\n }\n}", "function logFile() {\n\tuserInput = userInput.join(' '); // join the array with spaces\n\tvar logEntry = userCommand + ' ' + userInput + '\\n'; // append new command and input into log\n\tfs.appendFile('log.txt', logEntry, function(err) {\n\t\tif (err) {\n\t\t\tconsole.log(err);\n\t\t} else {\n\t\t\tconsole.log('log was updated');\n\t\t}\n\t})\n}", "function createNewLogFile() {\n var basePath = (global.TYPE.int === global.TYPE_LIST.CLIENT.int ? \"./\" : path.join(__dirname, \"..\")); //Get base path\n if (fs.existsSync(path.join(basePath, \"Timbreuse.10.log\"))) //If log 10 exists, delete\n fs.unlinkSync(path.join(basePath, \"Timbreuse.10.log\"));\n for (var i = 9; i > 0; i--)\n if (fs.existsSync(path.join(basePath, \"Timbreuse.\" + i + \".log\"))) //Then move log n to log n+1\n fs.renameSync(path.join(basePath, \"Timbreuse.\" + i + \".log\"), path.join(basePath, \"Timbreuse.\" + (i + 1) + \".log\"));\n if (fs.existsSync(path.join(basePath, \"Timbreuse.log\"))) //If log exists, move it to log 1\n fs.renameSync(path.join(basePath, \"Timbreuse.log\"), path.join(basePath, \"Timbreuse.1.log\"));\n global.logFile = fs.createWriteStream(path.join(basePath, \"Timbreuse.log\"), { //Then create write stream to log file\n flags: 'w'\n });\n}", "function __log(context, msg, option) {\n var nowMs = Date.now();\n if (nowMs !== date.getTime()) {\n date.setTime(Date.now());\n\n //make head '23:59:59.999 '\n head = dpad2(date.getHours()) + ':' + dpad2(date.getMinutes()) + ':' + dpad2(date.getSeconds()) + '.' + dpad3(date.getMilliseconds()) + ' ';\n\n //close current and create new log file if date changed\n if (context.filePath && date.getDate() !== dd) {\n dd = date.getDate();\n __close(context);\n createNewLogFileForToday(context);\n }\n }\n\n msg = String(msg).replace('\\0', '');\n var actualHead = (option && option.head) ? (head + option.head) : head;\n\n //remove last new line char\n var origMsgIsEndedWithNewLine = (msg.charCodeAt(msg.length - 1) === 0xa);\n if (origMsgIsEndedWithNewLine) {\n msg = msg.slice(0, -1);\n }\n\n //prepend head to each line. To disable this, just change to \"var s = msg\"\n var s = msg.replace(/\\n/g, '\\n' + actualHead);\n\n if (option && option.noNewLine === true) {\n if (context.previousLineHaveEnded) {\n s = actualHead + s;\n }\n if (origMsgIsEndedWithNewLine) {\n s += '\\n';\n }\n context.isAutoAppendNewLineMode = false;\n context.previousLineHaveEnded = origMsgIsEndedWithNewLine;\n } else {\n if (context.previousLineHaveEnded) {\n s = actualHead + s + '\\n';\n } else {\n s = '\\n' + actualHead + s + '\\n';\n }\n context.isAutoAppendNewLineMode = true;\n context.previousLineHaveEnded = true;\n }\n\n //write to file if filePath is specified\n var ok = false;\n if (context.fd !== -1) {\n try {\n ok = fs.writeSync(context.fd, s);\n } catch (e) {\n if (!context.err_write) {\n context.err_write = true;\n lastError = 'Failed to append log to file. ' + e;\n process.stderr.write(actualHead + lastError + '\\n');\n }\n }\n }\n\n //write to stderr if failed or no filePath specified\n if (!ok || (option && option.stderr === true)) {\n try {\n process.stderr.write(s);\n } catch (e) {\n lastError = e.message;\n }\n }\n\n return nowMs;\n}", "function logFileOp(message) {\n events.emit('verbose', ' ' + message);\n}", "static augmentExistingLogs() {\n for (const lgName in winston.loggers.loggers) {\n if (winston.loggers.loggers.hasOwnProperty(lgName)) {\n const logger = winston.loggers.loggers[lgName];\n if (!logger.transports.memory) {\n logger.add(memoryTransport, null, true);\n } else if (logger.transports.memory !== memoryTransport) {\n logger.remove(memoryTransport, null, true);\n logger.add(memoryTransport, null, true);\n }\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given two numbers, return true if the sum of both numbers is less than 100. Otherwise return false.
function lessThan100(num1, num2) { if (num1 + num2 < 100) { return true } return false }
[ "function checkNumbers(a, b) {\n if (a === 50 || b === 50 || a + b === 50) return true;\n}", "function checkTwoGivenIntegers(int1, int2) {\n let sum = 50\n if ((sum === int1 + int2) || ((int1 === 50) || (int2 === 50))) {\n return true\n } else {\n return false\n }\n}", "function check(num1, num2) {\n var sum = 0;\n sum = sum + num1 + num2;\n if (sum <= 25) {\n console.log(\"true\")\n } else {\n console.log(\"false\")\n }\n}", "function sumRange(num1, num2) {\n let sum = num1 + num2;\n if (sum >= 50 && 80 >= sum) return 65;\n else return 80;\n}", "function temp(temp1, temp2){\n\tif((temp1 < 0 && temp2 > 100) || (temp1 > 100 && temp2 < 0)){\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "function sumOfInt(int1, int2) {\n if (int1 + int2 >= 50 && int1 + int2 < 80) {\n return 65;\n } else {\n return 80;\n }\n}", "function near(a,b) {\n var diff1 = 100 - a;\n var diff2 = 100 - b;\n if(diff1 === diff2) {\n console.log(a, \"is the nearest to 100\");\n }\n else\n {\n (diff1 < diff2) ? console.log(a, \"is the nearest to 100\") : console.log(b, \"is the nearest to 100\"); \n }\n}", "function sumAndDifference(int1, int2) {\n if (int1 + int2 === 8 || int1 - int2 === 8) {\n return true;\n } else return false;\n}", "function totalUnderWhat (first, second, third, fourth){\n if (first + second +third < fourth) {\n return true;\n\n } else {return false;\n\n }\n\n}", "function under50(num) {\n return num < 50;\n}", "function range(a, b) {\n return (((a >= 40 && a <= 60 || a >= 70 && a <= 100)) && ((b >= 40 && b <= 60 || b >= 70 && b <= 100)))\n}", "function greaterThanSum(nums) {\n\tlet a = 0;\n\tfor (let i = 0; i < nums.length; i++) {\n\t\tif (a >= nums[i]) return false;\n\t\ta += nums[i];\n\t}\n\treturn true;\n}", "function computeSumBetween(num1, num2) {\n\tvar results = 0;\n\tvar count = num1;\n\twhile (num1 < num2){\n\tresults = results + count++;\n\tnum2--;\n\t}\n\treturn results;\n}", "function arrayLessThan100(arr) {\n\treturn arr.reduce((x, i) => x + i) < 100;\n}", "function rangeFrom10To99({ first, second }) {\n function ifRange(number) {\n return ( number < 10 || number > 99 );\n }\n if (!ifRange(first) || !ifRange(second)) return \"Not in range\";\n const result = first.split(\"\").some(digit => (second.split(\"\").indexOf(digit) > -1));\n return result;\n}", "function isGreaterThan (first, second) {\n if (first > second) {\n return true;\n }\n}", "function multipleOf7Or11(n1, n2) {\n if (n1 % 7 === 0 || n1 % 11 === 0 || n2 % 7 === 0 || n2 % 11 === 0) {\n return true;\n } else {\n return false;\n }\n}", "function isGreaterThan (first,second){\n\tif (first > second){\n\t\treturn true;\n\t}\n}", "function isGreaterThan20(num){\r\n if(num>20){\r\n return true\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show or Hide Work Experience View Sub Div
function showHideWorkExperienceRoleDiv(){ if(document.getElementById('empExperienceMenuViewId').checked==true){ document.getElementById('workExperienceMenuSubTableDivId').style.display = "block"; }else{ document.getElementById('workExperienceMenuSubTableDivId').style.display = "none"; } }
[ "function showHideEducationRoleDiv(){ \n\tif(document.getElementById('educationMenuViewId').checked==true){\n\t\tdocument.getElementById('educationMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('educationMenuSubTableDivId').style.display = \"none\";\n\t}\n}", "function alterCalculationsScreen(){\n\t$(\"#youHaveNoProjects\").hide();\n\t$(\"#youHaveSomeProjects\").hide();\n\t$(\"#youHaveUntimelyProjects\").show();\n}", "function showHideReportToRoleDiv(){ \n\tif(document.getElementById('reportToMenuViewId').checked==true){\n\t\tdocument.getElementById('employeeReportToMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('employeeReportToMenuSubTableDivId').style.display = \"none\";\n\t}\n}", "function showHideChildrenRoleDiv(){ \n\tif(document.getElementById('childrenMenuViewId').checked==true){\n\t\tdocument.getElementById('childrenMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('childrenMenuSubTableDivId').style.display = \"none\";\n\t}\n}", "function showHideLocationHistoryRoleDiv(){ \n\tif(document.getElementById('locationHistoryMenuViewId').checked==true){\n\t\tdocument.getElementById('locationHistoryMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('locationHistoryMenuSubTableDivId').style.display = \"none\";\n\t}\n}", "function toggleView() {\n id(\"admin-sight\").classList.toggle(\"hidden\")\n id(\"tool-app\").classList.toggle(\"hidden\");\n id(\"tool-app\").classList.toggle(\"flex\");\n }", "function div_hide_learn() {\n\t\tdocument.getElementById('ghi').style.display = \"none\";\n\t}", "function showHidePayStubRoleDiv(){ \n\tif(document.getElementById('paystubMenuViewId').checked==true){\n\t\tdocument.getElementById('payStubMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('payStubMenuSubTableDivId').style.display = \"none\";\n\t}\n}", "function showHideLeaveQuotaRoleDiv(){ \n\tif(document.getElementById('leaveQuotaMenuViewId').checked==true){\n\t\tdocument.getElementById('leaveQuotaMenuSubTableDivId').style.display = \"block\";\n\t\t\n\t}else{\n\t\tdocument.getElementById('leaveQuotaMenuSubTableDivId').style.display = \"none\";\n\t\t\n\t\t}\n\t\n\t\t\n\t\n}", "function showHideLicenseRoleDiv(){ \n\tif(document.getElementById('licenseMenuViewId').checked==true){\n\t\tdocument.getElementById('licenseMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('licenseMenuSubTableDivId').style.display = \"none\";\n\t}\n}", "function showHidePassportRoleDiv(){ \n\tif(document.getElementById('empPassportMenuViewId').checked==true){\n\t\tdocument.getElementById('passportMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('passportMenuSubTableDivId').style.display = \"none\";\n\t}\n}", "function participants_view_hide() {\n\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"rgba(0,0,0,.2)\";\n\tsetTimeout(function() {\n\t\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"transparent\";\n\t\tparticipants_view_visible = false;\n\t\tDOM(\"PARTICIPANTS_VIEW\").style.top = \"-100%\";\n\t\tsetTimeout(function() {\n\t\t\tDOM(\"PARTICIPANTS_VIEW\").style.display = \"none\";\n\t\t}, 500);\n\t}, 50);\n}", "function showDepEmployeeViews() {\r\n if(this.checked) {\r\n $(\"#specific-view-rights\").css(\"display\", \"none\");\r\n } else {\r\n $(\"#specific-view-rights\").css(\"display\", \"block\");\r\n }\r\n }", "function toggleCharmTab(){\n // Flip flag\n charmsOpen = !charmsOpen; \n\n let resultsSec = document.getElementById(\"results-section\");\n let charmSec = document.getElementById(\"charms-section\");\n let armorSec = document.getElementById(\"armor-section\");\n // Render accordingly\n if(charmsOpen){\n armorOpen = false;\n // toggleButton.innerText = \"Hide\";\n resultsSec.style.display = \"none\";\n charmSec.style.display = \"flex\";\n armorSec.style.display = \"none\";\n } else{\n // toggleButton.innerText = \"Show\";\n resultsSec.style.display = \"flex\";\n charmSec.style.display = \"none\";\n armorSec.style.display = \"none\";\n }\n}", "function _toggleVisibility() {\n\n\t\tvisible = !visible;\n\n\t\tif (true === visible) {\n\t\t\tpanel.show();\n\t\t\t$(\"#phpviewlog-preview-icon\").addClass(\"active\");\n\t\t\tWorkspaceManager.recomputeLayout();\n\t\t} else {\n\t\t\tpanel.hide();\n\t\t\t$(\"#phpviewlog-preview-icon\").removeClass(\"active\");\n\t\t}\n\t}", "function openAbExhib() {\n document.getElementById(\"about__exhibition\").style.display = \"block\";\n document.getElementById(\"menuPopupBackg\").style.display = \"block\";\n}", "function ShowProcessPanel(bShow){\n $(\".processValuesPanel\").css(\"display\", bShow ? \"block\" : \"none\");\n}", "_hide() {\n this._updateTriggerWidth();\n if (this._settings.get_boolean('dock-fixed')) {\n return;\n }\n\n if (this._isHovering() || (this._hoveringDash && !Main.overview._shown)) {\n return;\n }\n\n let intellihideAction = this._settings.get_enum('intellihide-action');\n if (!Main.overview._shown && intellihideAction == IntellihideAction.SHOW_FULL && !this._autohideStatus) {\n return;\n }\n\n let overviewAction = this._settings.get_enum('overview-action');\n if (Main.overview._shown && overviewAction == OverviewAction.SHOW_FULL && !this._autohideStatus) {\n return;\n }\n\n // Only hide if dock is shown, is showing, or is partially shown\n if (this._dockState == DockState.SHOWN || this._dockState == DockState.SHOWING || this._slider.slidex > 0) {\n this._removeAnimations();\n\n // If the dock is shown, wait this._settings.get_double('show-delay') before hiding it;\n // otherwise hide it immediately.\n let delay = 0;\n if (this._dockState == DockState.SHOWN)\n delay = this._settings.get_double('hide-delay');\n\n if (Main.overview._shown && Main.overview.viewSelector._activePage == Main.overview.viewSelector._workspacesPage) {\n this._animateOut(this._settings.get_double('animation-time'), delay, false);\n } else {\n this._animateOut(this._settings.get_double('animation-time'), delay, this._autohideStatus);\n }\n }\n }", "function showSetDepEmployeeViews() {\r\n if(this.checked) {\r\n $(\"#set-specific-view-rights\").css(\"display\", \"none\");\r\n } else {\r\n $(\"#set-specific-view-rights\").css(\"display\", \"block\");\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCION DE REGISTRAR CAUSA
function registrar_causa(codigo_causa_mant, descr_causa_mant) { let user = obtener_user(); let codigo_causa_mant2 = codigo_causa_mant.toUpperCase().trim(); let descr_causa_mant2 = descr_causa_mant; $.ajax({ type: 'POST', url: url + '/GestionProyectos/public/index.php/regi_caus', dataType: 'json', data: { varCodiCausa: codigo_causa_mant2, varDescCausa: descr_causa_mant2, acti_usua: user, }, error: function (xhr, ajaxOptions, thrownError) { if (thrownError == "Internal Server Error") { registrar_causa(); } }, success: function (responses) { if (responses.data == "") { mensaje(true, "GUARDADO CON EXITO", "modal-create-causa"); listar_causa(); } else { mensaje(false, responses.data, "modal-create-causa"); } } }); }
[ "function comprobarAlias(a) {\n var contAlias = a.value;\n var expresionAlias = /^[A-Z,a-z,0-9]{3,14}$/;\n\n if(comprobarExpresion(a, expresionAlias)==true){\n validado[1] = true;\n if(debug){\n console.log(\"Validado 1=> \"+validado[1]);\n }\n }\n}", "function validaClave( form )\n\t{\n\t\tvar regreso;\n\t\t\tregreso = true;\n\t\t\tregreso = vtxtVacio( form.txt_clave, \"Clave\" );\n\t\t\tif ( regreso )\n\t\t\t\tregreso = vtxtLongitudMenorIgual( form.txt_clave, 10 );\t\t\t\n\t\t\tif ( regreso )\n\t\t\t\tregreso = vtxtEspacios( form.txt_clave );\n\t\t\tif( regreso )\n\t\t\t\tregreso = vtxtAlfa2( form.txt_clave );\n\t\treturn regreso;\t\t\n\t}", "function validaCPFCNPJ(controle) {\r\n //Chama rotina verifica CPF\r\n if (validaCPF(controle)) {\r\n return true;\r\n }\r\n else {\r\n //Chama rotina verifica CNPJ\r\n if (validaCNPJ(controle)) {\r\n return true;\r\n }\r\n else {\r\n alert('CPF ou CNPJ Inválido!');\r\n return false;\r\n }\r\n }\r\n}", "function PhoneRegister(country_code, cellphone, sms_code, pass_word, pass_word_hash, invit_code, wechat, group_id, suc_func, error_func) {\n let api_url = 'reg_phone.php',\n post_data = {\n 'country_code': country_code,\n 'cellphone': cellphone,\n 'sms_code': sms_code,\n 'pass_word': pass_word,\n 'pass_word_hash': pass_word_hash,\n 'invit_code': invit_code,\n 'wechat': wechat,\n 'group_id': group_id\n };\n CallApi(api_url, post_data, suc_func, error_func);\n}", "function registraUt()\r\n { \r\n \t Ext.apply(Ext.form.VTypes,{ \r\n \t \r\n\t\t \t VRange: function(val, field){ \r\n\t\t \t if(val >= 1 && val <= 60) \r\n\t\t \t\t return true;\r\n\t\t \t\telse\r\n\t\t \t\t\treturn false;\r\n\t\t \t },\r\n\t\t \t VRangeText: 'Entre 1 y 60', //mensaje de error \r\n\t\t \t VRangeMask: /[\\d\\.]/i\r\n\t\t \r\n\t });\r\n\r\n \t \tExt.apply(Ext.form.VTypes,{ \r\n \t \r\n \t VNorma: function(val, field){ \r\n \t\t\t\treturn true;\r\n\t \t },\r\n\t \t VNormaText: 'Norma no válida para este tipo de vehículo', //mensaje de error \r\n\t \t VNormaMask: /[\\d\\.]/i\r\n\t \r\n\t }); \r\n\t \r\n\t// Formulario para crear nuevas unidades de transportes\r\n var formNuevoUt = new Ext.FormPanel({ \r\n labelWidth:70,\t\t\r\n url:'registro_ut.php', \r\n frame:true, \r\n title:'Nueva Unidad de Transporte', \r\n monitorValid:true,\r\n \t\t defaults : {allowBlank: false,width:'300px'}, \r\n \t\t defaultType:'textfield',\r\n \t\t bodyStyle:'padding: 15px',\r\n \t\t items:[\r\n \t\t\t {name:'nombre',fieldLabel:'Nombre'},\r\n \t\t\t {xtype:'checkbox',name:'activo',fieldLabel:'Activo'},\r\n \t\t\t {\r\n \t\t\t\t xtype:'combo',\r\n \t\t\t\t id: 'estacionInicio',\r\n \t\t\t\t name:'estacionInicio',\r\n \t\t\t\t triggerAction: 'all', \r\n \t\t\t\t emptyText:'Selecciona una estación de inicio...',\r\n \t\t\t\t fieldLabel:'Inicio',\r\n \t\t\t\t editable:false,\r\n \t\t\t\t forceSelection:true, \r\n \t\t\t\t store:storeEs,\r\n \t\t\t\t hiddenName: 'estacionInicio',\r\n \t\t\t\t displayField:'nombre',\r\n \t\t\t\t valueField: 'id_estaciones'\r\n \t\t\t },\r\n \t\t\t {\r\n \t\t\t\t xtype:'combo',\r\n \t\t\t\t id: 'fEF',\r\n \t\t\t\t name:'estacionFin',\r\n \t\t\t\t triggerAction: 'all', \r\n \t\t\t\t emptyText:'Selecciona una estación de fin...',\r\n \t\t\t\t fieldLabel:'Fin',\r\n \t\t\t\t editable:false,\r\n \t\t\t\t forceSelection:true, \r\n \t\t\t\t store:storeEs,\r\n \t\t\t\t hiddenName: 'estacionFin', \t\t\t\t \t\t\t\t \t\t\t\t \r\n \t\t\t\t displayField:'nombre',\r\n \t\t\t valueField: 'id_estaciones'\t \r\n \t\t\t \r\n \t\t\t },\r\n \t\t\t {name:'costeXkm',fieldLabel:'Coste/Km(€)',vtype:'alfa',width:'60px',vtype:'VEntero'},\r\n \t\t\t {name:'costeXdia',fieldLabel:'Coste/dia(€)',vtype:'alfa',width:'60px',vtype:'VEntero'},\r\n \t\t\t {\r\n\t\t\t\t\t\t xtype:'combo',\r\n\t\t\t\t\t\t name:'tipo',\r\n\t\t\t\t\t\t emptyText: 'Selecciona el tipo de vehículo...',\r\n\t\t\t\t\t\t triggerAction: 'all', \t\t\t\t \r\n\t\t\t\t\t\t fieldLabel:'Tipo vehículo',\r\n\t\t\t\t\t\t editable:false,\r\n\t\t\t\t\t\t forceSelection:true, \r\n\t\t\t\t\t\t store:storeType,\r\n\t\t\t\t\t\t hiddenName: 'tipo',\r\n\t\t\t\t\t\t valueField: 'id_type',\r\n\t\t\t\t\t\t displayField:'tipo',\r\n\t\t\t\t\t\t listeners:{select:function(){\r\n\t\t\t\t\t\t \t formNuevoUt.getForm().findField('norma').focus();\r\n\t\t\t\t\t\t\t \tformNuevoUt.getForm().findField('tonelaje').focus();\r\n\t\t\t\t\t\t\t } \r\n\t\t\t\t\t\t } \r\n\t\t\t\t\t \r\n\t\t\t\t},\r\n\t\t\t\t{name:'tonelaje',fieldLabel:'Tonelaje',vtype:'alfa',width:'60px',vtype:'VRange', listeners:{focus:setRange}},\r\n\t\t\t\t{\r\n\t\t\t\t\t\t xtype:'combo',\r\n\t\t\t\t\t\t name:'norma',\r\n\t\t\t\t\t\t triggerAction: 'all', \t\t\t\t \r\n\t\t\t\t\t\t fieldLabel:'Antigüedad del vehículo',\r\n\t\t\t\t\t\t editable:false,\r\n\t\t\t\t\t\t forceSelection:true, \r\n\t\t\t\t\t\t store: storeNorma,\r\n\t\t\t\t\t\t hiddenName: 'norma',\r\n\t\t\t\t\t\t valueField: 'id_norma',\r\n\t\t\t\t\t\t displayField:'norma',\r\n\t\t\t\t\t\t vtype:'VNorma',\r\n\t\t\t\t\t\t listeners: {\r\n\t\t\t\t\t\t focus: function(){\r\n\t\t\t\t\t\t \tsetStoreNorma();\r\n\t\t\t\t\t\t },\r\n\t\t\t\t\t\t select: setStoreNorma\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t \r\n\t\t\t\t\t },\r\n \t\t\t ],\r\n \t\tbuttons:[{ \r\n text:'Guardar',\r\n formBind: true, \r\n handler:function(){ \r\n \tformNuevoUt.getForm().submit({ \r\n method:'POST', \r\n waitMsg:'Enviando datos...',\r\n \t\t\t\t\t\twaitTitle:'Espere por favor..', \r\n \t\t\t\t\t\t\r\n \t\t\t\t\t\t success:function(form, action){\r\n\t \tobj = Ext.util.JSON.decode(action.response.responseText);\r\n\t //\tconsole.log(obj.datos.id); \t \r\n \t\t\t\t\t\t // Se tiene que guardar en el store del grid de transportes\r\n \t // Se tiene que guardar en el store del grid de transportes, ya se ha grabado en bd\r\n \tvar vactivo=\"f\"; \t\r\n \tif(formNuevoUt.getForm().getValues().activo==\"on\") vactivo=\"t\"; \t\r\n \tvar registro = new storeUt.recordType({ //step 2\r\n \t\tid_transportes: obj.datos.id,\r\n nombre : formNuevoUt.getForm().getValues().nombre, \r\n activo : vactivo, \r\n estacionInicio : formNuevoUt.getForm().getValues().estacionInicio, \r\n estacionFin : formNuevoUt.getForm().getValues().estacionFin, \r\n nestacion_inicio : extraeNombre(formNuevoUt.getForm().findField('estacionInicio')),\r\n nestacion_fin : extraeNombre(formNuevoUt.getForm().findField('estacionFin')),\r\n coste_x_km : formNuevoUt.getForm().getValues().costeXkm,\r\n coste_x_dia : formNuevoUt.getForm().getValues().costeXdia,\r\n tipo : formNuevoUt.getForm().getValues().tipo, \r\n tonelaje : formNuevoUt.getForm().getValues().tonelaje,\r\n\r\n \r\n }); \r\n \t// Insertamos nuevo registro en el store->grid\r\n \t\r\n \tstoreUt.insert(0,registro);\r\n \t// Muestra mensaje de exito\r\n \tExt.Msg.show({\r\n title:'Registro',\r\n fn: function(){\r\n \tWCrearUt.close();\r\n },\r\n msg:'Se ha registrado con éxito',\r\n buttons: Ext.Msg.OK,\r\n icon: 'icoOK' \r\n });\r\n },\r\n \r\n failure:function(form, action){ \r\n if(action.failureType == 'server'){ \r\n obj = Ext.util.JSON.decode(action.response.responseText);\r\n if(obj.errores.razon=='false') // usuario no logeado\r\n {\r\n \t desconectar();\r\n }\r\n else\r\n {\r\n Ext.Msg.show({\r\n title:'Fallo de registro',\r\n msg:obj.errores.razon,\r\n buttons: Ext.Msg.OK,\r\n icon: 'icoFail'\r\n });\r\n }\r\n }else{ \r\n falloServidor(); \r\n } \r\n \r\n } \r\n }); \r\n } \r\n },\r\n { \r\n text:'Cancelar', \r\n handler:function(){\r\n \tformNuevoUt.destroy(); // destruye formulario para que no se duplique campos\r\n \tWCrearUt.hide();\r\n \t \r\n }\r\n }\r\n \t\t] \r\n }); \r\n \r\n\t\r\n\r\n \r\n // Funcion auxiliar para extrar el name de un combo segun su id(valueField)\r\n function extraeNombre (combo) {\r\n var value = combo.getValue();\r\n var valueField = combo.valueField;\r\n var record;\r\n combo.getStore().each(function(r){\r\n if(r.data[valueField] == value){\r\n record = r;\r\n return false;\r\n }\r\n });\r\n\r\n return record ? record.get(combo.displayField) : null;\r\n }\r\n \r\n \r\n // Ventana para crear nuevas unidades de transportes\r\n var WCrearUt = new Ext.Window({\t \r\n width:500, \r\n x:10,\t \r\n closable: false,\r\n resizable: false,\r\n plain: true,\r\n border: false, \r\n \t\tlayout: 'form', \r\n modal: true, //set the Window to modal \r\n items: [formNuevoUt]\r\n });\r\n \r\n \r\n\t \t \r\n\t WCrearUt.show();\r\n\r\n\t function setStoreNorma(){\r\n\t\t\t var param = formNuevoUt.getForm().getValues().tipo;\r\n\t\t\t Ext.Ajax.request({ \r\n\t\t url: 'consulta_norma.php?tipo=' +param, \r\n\t\t success: function(response)\r\n\t\t {\r\n\t\t \tobj = Ext.util.JSON.decode(response.responseText);\r\n\t\t \tstoreNorma.loadData(obj);\r\n\t\t \tsetNorma();\r\n\r\n\t\t }\r\n\t\t });\r\n\r\n\t }\r\n\r\n\t\t\r\n\r\n\t \t function setNorma(){\r\n\t \t\t var norma = formNuevoUt.getForm().getValues().norma;\r\n\t \t\t calculateNorma(norma);\r\n\r\n\t \t\t\r\n\t \t }\r\n\r\n\r\n\t function setRange(){\r\n\t \t\t var tipo = formNuevoUt.getForm().getValues().tipo;\r\n\t \t\t calculateRange(tipo);\r\n\r\n\t \t }\r\n\t }// fin de registraUt", "function valCPFCGC(oCampo,itipo,oForm) { // bmsg: se vai dar alert das mensagens\r\n\tvar atipo=[\"CPF/CNPJ\",\"CPF\",\"CNPJ\"]\r\n\titipo=(itipo)?itipo:0 // 0=qualquer, 1=cpf,2=cgc\r\n\tvar cpf='', cgc='', digito='',dg='', dgc='', digitoc='', k=0; i=0, j=0, soma=0, mt=0;\r\n\tvar cpfcgc = oCampo.value;\r\n\tvar bcpf=false\r\n\tvar bcgc=false\r\n\tif (itipo==0||itipo==1) bcpf= reCPF.test(cpfcgc)\t// valida tamanho e formato do CPF\r\n\tif (itipo==0||itipo==2) bcgc= reCGCMF.test(cpfcgc)\t// valida tamanho e formato do CCG\r\n\tif ((!bcpf)&&(!bcgc)) {// formato não reconhecido\r\n\t\talert (\"Conteúdo informado não reconhecido como \"+atipo[itipo]+\"\\nVerifique sua digitação\")\r\n\t\tDados.achaAbaErro(oCampo.name.toString());\r\n\t\treturn false\r\n\t}\r\n\t// tirar separadores\r\n\tif (bcpf) {cpfcgc=cpfcgc.replace(reCPF,feCPF)}\r\n\telse {cpfcgc=cpfcgc.replace(reCGCMF,feCGCMF)}\r\n\t// valida entradas fáceis\r\n\tvar cpferr = \"0000000000011111111111222222222223333333333344444444444\"+\r\n\t\t\t\t\t \"5555555555566666666666777777777778888888888899999999999\"\r\n\tif ( cpferr.indexOf(cpfcgc) >= 0) { // informado campo de facil entrada\r\n\t\t/*if (bmsg)*/ alert (\"Conteúdo não é aceito como \" + atipo[itipo] + \"\\nVerifique sua digitação\")\r\n\t\tDados.achaAbaErro(oCampo.name.toString());\r\n\t\treturn false\r\n\t}\r\n\t// tabela de pesos para colunas\r\n\tmult = [2,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9];\r\n\tif (bcgc) {\r\n\t\tcgc = cpfcgc.substring(0,12);\r\n\t\tdigito = cpfcgc.substring(12,14);\r\n\t\tfor (j = 1; j <= 2; j++) {\r\n\t\t\tdigitoc = impCalcDig11(cgc)\r\n\t\t\tif (digitoc == 10) {digitoc = 0}\r\n\t\t\tdgc +=digitoc;\r\n\t\t\tcgc+=digitoc;\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tcpf = cpfcgc.substring(0,9);\r\n\t\tdigito = cpfcgc.substring(9,11);\r\n\t\tfor (j = 1; j <= 2; j++) {\r\n\t\t\tsoma = 0;\r\n\t\t\tmt = 2;\r\n\t\t\tfor (i = 8 + j; i >= 1; i--) {\r\n\t\t\t\tsoma += parseInt(cpf.charAt(i-1),10) * mt;\r\n\t\t\t\tmt++;\r\n\t\t\t}\r\n\t\t\tdg = 11 - (soma % 11);\r\n\t\t\tif (dg > 9) {dg = 0};\r\n\t\t\tcpf += dg;\r\n\t\t\tdgc+=dg\r\n\t\t}\r\n\t}\r\n\t// digito inválido\r\n\tif (dgc != digito) {\r\n\t\talert (((bcgc)?\"CNPJ\":\"CPF\")+\" com dígitos inválidos\\nVerifique sua digitação\")\r\n\t\tDados.achaAbaErro(oCampo.name.toString());\r\n\t\treturn false\r\n\t}\r\n\telse {\r\n\t\toCampo.value=valFormat(oCampo.value,((bcgc)?reCGCMF:reCPF),((bcgc)?fsCGCMF:fsCPF))\r\n\t\treturn true\r\n\t}\r\n}", "function tratarRetornoEmulacionLocal(retornoEjecucion) {\n\tdocument.forms[0].SRVPRESENTACION_CONTEXTO_SALIDA.value = retornoEjecucion;\n\twindow.document.forms[0].evento.value='0x0E003270';\n\twindow.document.forms[0].submit();\n}", "function asignarProdutoSucursal(keyProducto){\n\t\t/*key sucursal es llamada del valor de un hidden que esta en area.php*/\t\n\t\tvar keySucursal= document.getElementById(\"lb1\").value;\n\t\n\t\tvar requestData = {};\n\t\t\n\t\trequestData.websafeSucursalKey=keySucursal;\n\t\trequestData.websafeProductoKey=keyProducto;\n\t\t\n\t\tgapi.client.doomiClientes.apiClientes.addProductoForSucursal(requestData).execute(\n\t\t\t\n\t\t\tfunction(resp) {\n\n\t\t\t\tif (!resp.code) {\n\t\t\t\t\t//se envia al metodo obtenerProductosXsucursal() para que actualize los productos \n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById('formrp').reset();\n\t\t\t\t\tobtenerProductosXsucursal();\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\talert(\"Ha ocurrido un error en Tu registro, intentalo de nuevo \");\n\t\t\t\t\t//window.location.href=\"registroCliente.html\";\n\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t});\n\t\n\t\t\n\t\t}", "function register(){\n\tfunction asyncCallback(status, result){\n \tkony.print(\"\\n------status------>\"+status);\n \tif(status==400){\n \t\tkony.print(\"\\n------result------>\"+JSON.stringify(result));\n \t\tif(result[\"opstatus\"]==8009)\n \t\t{\n \t\t\tif(result[\"message\"]!=undefined)\n \t\t\t\tupdateMessaageAlert(result[\"message\"]);\n \t\t\telse\n \t\t\t\tupdateMessaageAlert(\"email/mobile already registered\");\n \t\t\tkony.application.dismissLoadingScreen();\n \t\t\t//updateMessaageAlert(\"mobile or email already regestered..\");\n \t\t\treturn;\n \t\t}\n \t\tif(result[\"errmsg\"]!=undefined){\n \t\t\tupdateMessaageAlert(result[\"errmsg\"]);\n \t\t\tkony.application.dismissLoadingScreen();\n \t\t\treturn;\n \t\t}if(result[\"opstatus\"]==0){\t\n \t\t\taudienceID=result[\"id\"];\n \t\t\tkony.store.setItem(\"audienceID\", audienceID);\n \t\t\tupdateMessaageAlert(\"\"+result[\"message\"]);\n \t\t\tfrmProfilePreShow();\n \t\t\tfrmProfile.show();\n \t\t\tfrmRegistration.destroy();\n \t\t\tkony.application.dismissLoadingScreen();\n \t\t}\n \t\telse{\n \t\t\tupdateMessaageAlert(\"unable to process please try later..\");\n \t\t\tkony.application.dismissLoadingScreen();\n \t\t\treturn;\n \t\t}\n \t}\n }\n var inputParamTable={\n \thttpheaders:{\n \t\t\"AccessSecret\":accessSecret,\n \t\t\"AccessToken\":accessToken,\n \t\t\"Content-Type\":\"application/json\"\n \t},\n\t\t\thttpconfig:{method:\"POST\"},\n\t\t\tserviceID:\"CreateAudience\",appID:\"kmsapp\",\n\t\t\tchannel:\"rc\",\n\t\t\tactive: \"\\\"\"+audienceStatus+\"\\\"\",\n \t\t\temail: \"\\\"\"+audienceEmail+\"\\\"\",\n \t\t\temailSubscription:\"\\\"\"+audienceEmailSubs+\"\\\"\",\n \t\t\tfirstName: \"\\\"\"+audienceFirstName+\"\\\"\",\n \t\t\tlastName: \"\\\"\"+audienceLastName+\"\\\"\",\n \t\t\tmobileNumber: \"\\\"\"+audienceMob+\"\\\"\",\n \t\t\tpushSubscription: \"\\\"\"+audiencePushSubs+\"\\\"\",\n \t\t\tsmsSubscription: \"\\\"\"+audienceSmsSubs+\"\\\"\",\n \t\t\tkmsurl:KMSPROP.kmsserverurl\n\t};\n var url=appConfig.url;\n // var url=\"http://10.10.12.145:8080/middleware/MWServlet\";\n kony.print(\"\\n----url----->\"+url) ; \n try{\n kony.application.showLoadingScreen(\"sknLoading\",\"registering...\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true,null);\n\t\tvar connHandle = kony.net.invokeServiceAsync(\n url,inputParamTable,asyncCallback);\n\t}catch(err){\n \tkony.print(\"\\nexeption in invoking service---\\n\"+JSON.stringify(err));\n\t \talert(\"Error\"+err);\n\t \tkony.application.dismissLoadingScreen();\n\t}\t\n}", "function reg_validateForm(){\n\t// Effacer les erreurs précédents\n\tremove_errors();\n\tvar flag = true;\n\t\n\t// Vérifier la validté de l'entrée pour tout objet de la classe .ids \n\t$( \".ids_reg\" ).each(function() {\n\t\tvar e = $( this ).children(\"input\");\n\t\tflag &= validateEntry(e);\n\t\t});\n\t\n\tif( !validateEmail($(\"#mail_register\").val()) ){\n\t\tfonc_erreur($(\"#mail_register\"), \"Le mail n'est pas valide\");\n\t\treturn;\n\t}\n\t\n\tif($(\"#pass_register\").val() != $(\"#repass_register\").val()){\n\t\tfonc_erreur($(\"#repass_register\"), \"Les mots de pass ne sont pas égales\");\n\t\t\n\t\treturn;\n\t}\n\t\n\tif(flag){\n\t\tregister(\t$(\"#login_register\").val(),\n\t\t\t\t\t$(\"#mail_register\").val(),\n\t\t\t\t\t$(\"#nom_register\").val(),\n\t\t\t\t\t$(\"#prenom_register\").val(),\n\t\t\t\t\t$(\"#pass_register\").val()\n\t\t\n\t\t);\n\t\t\n\t}\n}", "function add_email_subscribe() {\n\n\tvar email_sub = document.forms[\"subscr\"][\"emails\"].value;\n\tvar checkEmailSub = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/;\n\n\t// It can not be registered if one of the fields is empty\n\tif (email_sub !== \"\") {\n\n\t\tif (!checkEmailSub.test(email_sub)) {\n\t\t\tswal(\"please Type your email correctly..! \");\n\t\t\treturn false;\n\t\t} else {\n\t\t\tcongratsSubscribe();\n\t\t\treturn false;\n\t\t}\n\t} else {\n\t\tswal(\"Empty Fields..!\");\n\t\treturn false;\n\t}\n\n}", "function save_existing_account()\r\n {\r\n if(!validate_dwolla_id()) return;\r\n\r\n charity_info.dwolla_id=$(\"#dwolla_id\").val();\r\n\r\n $.ajax(\r\n {\r\n url: \"/save_charity\",\r\n type: \"POST\",\r\n data: charity_info,\r\n success:\r\n function(data)\r\n {\r\n if(data.success)\r\n {\r\n charity_info.id=data.charity_id;\r\n $(\"#charity_id\").html(charity_info.id);\r\n _gaq.push([\"_trackPageView\",\"/register/step3\"]);\r\n show_next();\r\n }\r\n else\r\n {\r\n $(\"#error_list\").empty().append(\"<li>There was an internal problem saving your information, please try again later</li>\");\r\n $(\"#validation_errors\").popup();\r\n }\r\n },\r\n error:\r\n function(data)\r\n {\r\n $(\"#error_list\").empty().append(\"<li>There was a problem saving your information, please try again later</li>\");\r\n $(\"#validation_errors\").popup();\r\n }\r\n }); //end save_charity ajax call\r\n }", "function RegisterAccount(username, pass, email, phone, name, birthday, sex, avatarLink) {\n user.ThemUser(username, name, birthday, sex, phone, email, pass, avatarLink);\n return userIsExisting(username);\n}", "async registerCompany (ctx, companyCRN, companyName, location, organisationRole){\r\n //Creates a composite key for the new company.\r\n const companyCompositeKey = ctx.stub.createCompositeKey('org.pharmaNetwork.pharmachannel.pharmaContract',[companyCRN, companyName]);\r\n\r\n //Assigning hierarchy key as per the organisation role.\r\n switch(organisationRole.toLowerCase()){\r\n case \"manufacturer\" : hierarchyKey = 1;\r\n case \"distributor\" : hierarchyKey = 2;\r\n case \"retailer \" : hierarchyKey = 3;\r\n case \"default\" : hierarchyKey = 0;\r\n }\r\n\r\n //If organization doesn't belong to any of the roles viz. manufacturer, distributor, retailer than throw an error.\r\n if(hierarchyKey === 0) throw new Error(\"Wrong role provided.\");\r\n\r\n //Creates a company object to be stored on blockchain.\r\n let companyDetails = {\r\n companyID : companyCompositeKey,\r\n name : companyName,\r\n location : location,\r\n organisationRole : organisationRole, \r\n hierarchyKey : hierarchyKey\r\n }\r\n\r\n //Converts company object to buffer and put it's state on blockchain.\r\n let dataBuffer = Buffer.from(JSON.stringify(companyDetails));\r\n await ctx.stub.putState(companyCompositeKey, dataBuffer);\r\n return companyDetails;\r\n }", "function inicializarEventos(){\r\n var ob=document.getElementById('pass');\r\n addEvent(ob,'keyup',presionTecla,false);\r\n}", "validar() { }", "function startRegister() {\n\tif(request.httpParameterMap.MailExisted.value != null && request.httpParameterMap.MailExisted.value != 'true'){\n\t\tapp.getForm('profile').clear();\n\t}\n\n if (app.getForm('login.username').value() !== null) {\n app.getForm('profile.customer.email').object.value = app.getForm('login.username').object.value;\n }\n app.getView({\n ContinueURL: URLUtils.https('Account-RegistrationForm')\n }).render('account/user/registration');\n}", "register (credentials){\n return Api().post('register', credentials)\n }", "validaCPF(campo) {\n // Instanciando a constante cpf com a classe que fizemos no arquivo validaCPF.js\n const cpf = new ValidaCpf(campo.value);\n\n // Se nossa constante instanciada for validada como falso, retornamos um erro e a avaliaçãoo lógica em FALSO\n if (!cpf.valida()) {\n this.criaErro(campo, 'CPF inválido.');\n return false;\n }\n\n // Se o cpf for válido, retornamos o resultado lógico VERDADEIRO\n return true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Il permet de reconfigurer un item variant provenant d'un configurateur.
reconfigurer_item_variant(cdt, cdn) { var me = this; //Si un code à été saisit if (locals[cdt][cdn] && locals[cdt][cdn].item_code) { var soi = locals[cdt][cdn]; //Trouver le modele de l'item frappe.call({ method: "frappe.client.get_value", args: { "doctype": "Item", "filters": { "name": soi.item_code }, "fieldname": ["variant_of"] }, callback: function(res) { if (res.message.variant_of){ var variant_of = res.message.variant_of; frappe.call({ method: "radplusplus.radplusplus.controllers.configurator.get_item_variant_attributes_values", args: { "user_name": frappe.session.user, "item_code": soi.item_code }, callback: function(res) { //Convertir le message en Array var attributes = (res.message || []); var variantAttributes = {}; var grid_row = me.frm.open_grid_row(); //pour chaque attribut for (var j = 0; j < attributes.length; j++) { if (grid_row.grid_form.fields_dict[attributes[j][0]]){ grid_row.grid_form.fields_dict[attributes[j][0]].set_value(attributes[j][1]); } } //Assigner l'item_code du configurateur frappe.call({ method: "frappe.client.get_value", args: { "doctype": "Item", "filters": { "configurator_of": variant_of }, "fieldname": ["name"] }, callback: function(res) { soi.configurator_of = res.message.name; grid_row.grid_form.fields_dict.template.set_value(soi.configurator_of); } }); } }); } } }); } }
[ "create_item_variant(cdt, cdn, validate_attributes) {\r\n\t\tvar me = this;\r\n\t\t//Si un code à été saisit\r\n\t\tif (locals[cdt][cdn] && locals[cdt][cdn].template) {\r\n\r\n\t\t\tvar soi = locals[cdt][cdn];\r\n\r\n\t\t\t//Lancer le call\r\n\t\t\tfrappe.call({\r\n\t\t\t\tmethod: \"radplusplus.radplusplus.controllers.configurator.get_required_attributes_fields\",\r\n\t\t\t\targs: {\r\n\t\t\t\t\t\"item_code\": soi.template\r\n\t\t\t\t},\r\n\t\t\t\tcallback: function(res) {\t\t\t\t\t\t\t\r\n\t\t\t\t\t//Convertir le message en Array\r\n\t\t\t\t\tvar attributes = (res.message || []);\r\n\t\t\t\t\tvar variantAttributes = {};\r\n\r\n\t\t\t\t\t//pour chaque attribut\r\n\t\t\t\t\tfor (var j = 0; j < attributes.length; j++) {\r\n\t\t\t\t\t\tvar attribute_name = attributes[j].name;\r\n\t\t\t\t\t\tvar fieldname = attributes[j].field_name;\r\n\t\t\t\t\t\tvar currItem = soi[attributes[j].field_name];\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (currItem != undefined)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tvar idx = me.frm.cur_grid.grid_form.fields_dict[attributes[j].field_name].df.idx;\r\n\t\t\t\t\t\t\tvar options = me.frm.cur_grid.grid_form.fields[idx - 1].options;\r\n\t\t\t\t\t\t\tfor (var o = 0; o < options.length; o++) {\r\n\t\t\t\t\t\t\t\tif (options[o].value == currItem) {\r\n\t\t\t\t\t\t\t\t\tcurrItem = options[o].key;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t//Vérifier que la valeur n'est pas \"A venir\"\r\n\t\t\t\t\t\tif (currItem == undefined || validate_attributes && currItem.toLowerCase().trim() == \"à venir\")\r\n\t\t\t\t\t\t\tfrappe.throw(__(\"Tous les attributs doivent être définis.\"));\r\n\r\n\t\t\t\t\t\t//Ajouter la valuer dans la liste d'attributs\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tvariantAttributes[attributes[j].name] = currItem;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t//Lancer la création du variant\r\n\t\t\t\t\t//Convertir la liste d'attributs en json string\r\n\t\t\t\t\tvar attjson = JSON.stringify(variantAttributes);\r\n\r\n\t\t\t\t\t//Lancer le call\r\n\t\t\t\t\tfrappe.call({\r\n\t\t\t\t\t\tmethod: \"radplusplus.radplusplus.controllers.item_variant.create_variant_and_submit\",\r\n\t\t\t\t\t\targs: {\r\n\t\t\t\t\t\t\t\"template_item_code\": soi.configurator_of,\r\n\t\t\t\t\t\t\t\"args\": attjson\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\tcallback: function(res) {\r\n\t\t\t\t\t\t\tvar doclist = frappe.model.sync(res.message);\r\n\t\t\t\t\t\t\tvar variant = doclist[0];\r\n\t\t\t\t\t\t\tvar grid_row = me.frm.open_grid_row();\r\n\r\n\t\t\t\t\t\t\tgrid_row.grid_form.fields_dict.item_code.set_value(variant.name);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tfrappe.model.set_value(soi.doctype, soi.name, \"template\", \"\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t}", "handleMainPropertyChange(key, value) {\n const state = this.state;\n state.configuration[key] = value;\n this.setState(state);\n this.props.onConfigurationChange(state.configuration);\n }", "async function addToConfig(dir, render) {\n // For arcade roms we need clone info\n if (dir == 'arcade') { \n var metaData = await getMeta(dir);\n };\n // Update config file with current rom files\n let configFile = configPath + dir + '.json';\n let shaPath = hashPath + dir + '/roms/';\n let files = await fsw.readdir(shaPath);\n let config = await fsw.readFile(configFile, 'utf8');\n config = JSON.parse(config);\n config.items = {};\n if (files.length < 9) {\n var itemsLength = files.length;\n } else {\n var itemsLength = 9;\n };\n config.display_items = itemsLength;\n for await (let file of files) {\n let fileName = file.replace('.sha1','');\n let fileExtension = path.extname(fileName);\n let name = path.basename(fileName, fileExtension);\n let has_logo = fs.existsSync(dataRoot + dir + '/logos/' + name + '.png');\n let has_back = fs.existsSync(dataRoot + dir + '/backgrounds/' + name + '.png');\n let has_corner = fs.existsSync(dataRoot + dir + '/corners/' + name + '.png');\n let has_video = fs.existsSync(dataRoot + dir + '/videos/' + name + '.mp4');\n let positionFile = dataRoot + dir + '/videos/' + name + '.position';\n config.items[name] = {};\n var multi_disc = 0;\n if (fileExtension == '.disk1') {\n var roms = await fsw.readdir(dataRoot + dir + '/roms/');\n for await (var rom of roms) {\n var romExtension = path.extname(rom);\n var romName = path.basename(rom, romExtension);\n if (romName == name) {\n multi_disc++\n }\n };\n };\n if ((dir == 'arcade') && (metaData.hasOwnProperty(name)) && (metaData[name].hasOwnProperty('cloneof'))) {\n Object.assign(config.items[name], {'cloneof': metaData[name].cloneof});\n };\n if (multi_disc !== config.defaults.multi_disc) {\n Object.assign(config.items[name], {'multi_disc': multi_disc});\n };\n if (fs.existsSync(positionFile)) {\n let video_position = await fsw.readFile(positionFile, 'utf8');\n Object.assign(config.items[name], {'video_position': video_position});\n };\n if (has_logo !== config.defaults.has_logo) {\n Object.assign(config.items[name], {'has_logo': has_logo});\n };\n if (has_back !== config.defaults.has_back) {\n Object.assign(config.items[name], {'has_back': has_back});\n };\n if (has_corner !== config.defaults.has_corner) {\n Object.assign(config.items[name], {'has_corner': has_corner});\n };\n if (has_video !== config.defaults.has_video) {\n Object.assign(config.items[name], {'has_video': has_video});\n };\n if (fileExtension !== config.defaults.rom_extension) {\n Object.assign(config.items[name], {'rom_extension': fileExtension});\n };\n };\n var configContents = JSON.stringify(config, null, 2);\n await fsw.writeFile(configFile, configContents);\n // Update main to include stuff with roms\n var mainFile = configPath + 'main.json';\n var main = await fsw.readFile(mainFile, 'utf8');\n var main = JSON.parse(main);\n main.items = {};\n for await (var emu of emus) {\n var emuPath = dataRoot + 'hashes/' + emu.name + '/roms/';\n if (fs.existsSync(emuPath)) {\n var roms = await fsw.readdir(emuPath);\n if (roms.length > 0) {\n main.items[emu.name] = {'video_position': emu.video_position};\n };\n };\n };\n if (Object.keys(main.items).length < 9) {\n main.display_items = Object.keys(main.items).length;\n } else {\n main.display_items = 9;\n };\n var mainContents = JSON.stringify(main, null, 2);\n await fsw.writeFile(mainFile, mainContents);\n // Render page for user if needed\n if (render) {\n return '';\n } else {\n renderRoms();\n };\n }", "function on_change_key_config()\n{\n\tkey_config = key_config_presets[key_config_menu.selectedIndex];\n}", "function change_product_supplier_settings(product_id)\n{\n\twhile(order_list[product_id].supplier_settings.length>0){order_list[product_id].supplier_settings.pop()};\n\torder_list[product_id].supplier_settings = {};\n\t//get information from checkmark and supplier id and premium values from HTML\n\t$.each(suppliers_list, function (supplier_id, supplier_details)\n\t{\n\t\tif(typeof(supplier_details)!='undefined')\n\t\t{\n\t\t\tvar supplier_checkbox = \"supsettings_\"+supplier_id+\"_\"+product_id;\n\t\t\tvar premium_input_name = \"supsetting_premium_\"+supplier_id+\"_\"+product_id;\n\t\t\tif ($(\"#\"+supplier_checkbox).prop(\"checked\"))\n\t\t\t{\n\t\t\t\torder_list[product_id].supplier_settings[supplier_id]={};\n\t\t\t\torder_list[product_id].supplier_settings[supplier_id].name = suppliers_list[supplier_id].name;\n\t\t\t\torder_list[product_id].supplier_settings[supplier_id].premium = $(\"#\"+premium_input_name).val();\n\t\t\t}\t\t\t\n\t\t}\n\t});\n\t//To find recommend supplier and then redraw complete order list\n\tfind_recommended_supplier(product_id)\n\t//\n\thide_product_supplier_settings();\n\t//redraw order list\n\tredraw_order_list();\n}", "function reloadConfig() {\n saveConfig(true);\n if (typeof localStorage !== \"undefined\") {\n _drawMode.selectedObject = undefined;\n config = localStorage.getItem(\"config\");\n loadConfig(new Blob([config], {type: \"text/plain;charset=utf-8\"}));\n }\n}", "function editConfig(useNewData) {\n let useNewDataConfig;\n if (useNewData === true) {\n useNewDataConfig = \"false\";\n } else if (useNewData === false) {\n useNewDataConfig = \"true\";\n }\n\n TestService.editConfig(COMPONENT_ID, useNewDataConfig).then(function () {\n window.location.reload();\n getTestSensorList();\n });\n\n\n }", "async _merchantSettingChange(event, html) {\n event.preventDefault();\n console.log(\"Loot Sheet | Merchant settings changed\");\n\n const moduleNamespace = \"lootsheetnpcpf2e\";\n const expectedKeys = [\"rolltable\", \"shopQty\", \"itemQty\"];\n\n let targetKey = event.target.name.split('.')[3];\n\n if (expectedKeys.indexOf(targetKey) === -1) {\n console.log(`Loot Sheet | Error changing stettings for \"${targetKey}\".`);\n return ui.notifications.error(`Error changing stettings for \"${targetKey}\".`);\n }\n\n if (event.target.value) {\n await this.actor.setFlag(moduleNamespace, targetKey, event.target.value);\n } else {\n await this.actor.unsetFlag(moduleNamespace, targetKey, event.target.value);\n }\n }", "function AddEnumItem() {\n let e = d.Config.enums\n let enumName = u.ID(\"selectAdminEnum\").value;\n e[enumName].push(\"\");\n u.WriteConfig();\n}", "function choiceCoaProd() {\n var $coaSlider = $('#productSliderCoa');\n var $coaItem = $('#productSliderCoa .item');\n var $coaLink = $('#productSliderCoa .radioCoa');\n $coaLink.on('click', function (e) {\n e.preventDefault();\n $coaItem.removeClass('active');\n $(this).parent($coaItem).addClass('active');\n }); // hide arrows and :after if child elements <= 4\n\n $coaSlider.each(function (index) {\n var $slidesNum = $(this).find('.slick-slide').length;\n\n if ($slidesNum <= 4) {\n $(this).parent('.form-row-slider').addClass('hide');\n } else {\n $(this).parent('.form-row-slider').removeClass('hide');\n }\n }); // hide prev arrow and show if slider swipe\n\n $coaSlider.find('.slick-prev').hide();\n $coaSlider.on('afterChange', function () {\n $(this).find('.slick-prev').show();\n });\n }", "function setConfigOption(key, value){\n chrome.storage.sync.get(null, (result) =>{\n let config = result[\"config\"];\n if(!config)\n config = {};\n if(value)\n config[key] = value;\n else\n delete config[key];\n chrome.storage.sync.set({config: config});\n });\n}", "migrateSettings() {\n const newItems = {};\n const keysToRemove = [];\n // find the items that need to be replaced\n for (let i = 0, len = this.storage.length; i < len; ++i) {\n const match = this.storage.key(i).match(/^QoL.*/);\n if(match) {\n const oldKey = match.input;\n const newKey = this.translateKey(oldKey);\n newItems[newKey] = this.storage.getItem(oldKey);\n keysToRemove.push(oldKey);\n }\n }\n // remove the old style keys\n for(let j = 0; j < keysToRemove.length; j++) {\n this.storage.removeItem(keysToRemove[j]);\n }\n // add the new style keys\n for(const newKey in newItems) {\n this.storage.setItem(newKey, newItems[newKey]);\n }\n }", "_setCompatibilityOptions() {\n // Convert the product config to a placement configuration\n this.config.backwards = 'Ad';\n this.config.type = okanjo.Placement.ContentTypes.products;\n\n // Id / single mode is now ids\n this.config.url = null;\n if (this.config.id) {\n this.config.ids = [this.config.id];\n } else {\n okanjo.warn('Ad widget should have parameter `id` set.');\n }\n this.config.take = 1;\n delete this.config.id;\n\n // Content is automatically determined whether the placement element contains children\n delete this.config.content;\n }", "function change_product_substitutes(product_id)\n{\n\t//Empty the products substitutes for this product \n\twhile (order_list[product_id].substitutes.length>0) {order_list[product_id].substitutes.pop();}\n\t//iterate through HTML and find products which are checked \n\t$(\"#product_view2 input[type=checkbox]\").each(function() {\n \tif ($(this).prop('checked'))\n \t{\n \t\tvar substitute_product = $(this).prop('id');\n \t\torder_list[product_id].substitutes[substitute_product] = true;\n \t}\n\t});\n\t//hide the products substitutes modal \n\thide_product_substitutes();\n\t\n}", "function changeItem(direction){\n\t\t\n\t\tg_parent.switchSlideNums(direction);\n\t\tg_parent.placeNabourItems();\n\n\t}", "function addTranslation(item){\n if (item.hasOwnProperty(\"label\")){\n if (typeof languages[\"es\"][item.label.key] === 'undefined'){\n languages[\"es\"][item.label.key]=\"\";\n }\n if (typeof languages[\"en\"][item.label.key] === 'undefined'){\n languages[\"en\"][item.label.key]=\"\";\n }\n languages[\"es\"][item.label.key] = item.label.es;\n languages[\"en\"][item.label.key] = item.label.en;\n }\n}", "onDropItem(aItem) {\n // method that may be overridden by derived bindings...\n }", "_listenMaintainAspectChanged():void {\n var self = this;\n self.m_maintainAspectHandler = function (e) {\n if (!self.m_selected)\n return;\n var mode = $(e.target).prop('checked') == true ? 1 : 0;\n var domPlayerData = self._getBlockPlayerData();\n var xSnippet = $(domPlayerData).find('XmlItem');\n $(xSnippet).attr('maintainAspectRatio', mode);\n self._setBlockPlayerData(domPlayerData, BB.CONSTS.NO_NOTIFICATION);\n };\n $(Elements.JSON_ITEM_MAINTAIN_ASPECT_RATIO).on(\"change\", self.m_maintainAspectHandler);\n}", "addItem(itemId, quntity){\n if (itemId in this.items){\n this.items[itemId].quntity += quntity;\n return true;\n }else if (itemId in productList){\n var itemInfo = productList[itemId];\n this.items[itemId] = {unitPrice: itemInfo.unitPrice,\n quntity: quntity};\n return true;\n } else{\n return false;\n }\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
callback when create track button is clicked.
function createTrackClicked(track_element) { // Set the current track to active track_element.create_track_button.hidden = true; track_element.midi_options.hidden = false; track_element.pattern_chain.hidden = false; // and create a new track stub createTrack(); }
[ "function elemAddTrackButton(track_element) {\n var create_track_button = document.createElement(\"button\");\n create_track_button.id = \"track_create_\" + track_element.track_num;\n create_track_button.textContent = \"Create New Track\";\n create_track_button.onclick = () => createTrackClicked(track_element);\n return create_track_button;\n}", "function trackIsClicked(event, track) {\n console.log(track.id);\n let clickedTrackArea = document.getElementsByClassName(\"track-1\");\n let clickedTrackTitleTag = clickedTrackArea[0].childNodes[1].childNodes[0];\n let clickedTrackAudio = clickedTrackArea[0].childNodes[0].childNodes[0];\n\n clickedTrackAudio.src = track.bucket_link[\"url\"];\n clickedTrackAudio.controls = true;\n clickedTrackTitleTag.id = track.id;\n // debugger\n trackLink = track.link;\n clickedTrackTitleTag.innerText = trackLink;\n\n //clickedTrackArea.append(clickedTrack)\n}", "function addTrack() {\n SC.get('/tracks/' + track).then(function(player) {\n\n trackList.push({\n id: player.id,\n trackName: player.title,\n url: player.stream_url,\n artist: player.user.username\n });\n\n if (trackList.length === 1) {\n $('.picked-songs').empty();\n }\n $('.picked-songs').append('<li class=\"column column-block\"><button class=\"button small picked-song\" data-value=\"' + player.id + '\">' + player.title + '</button></li>');\n })\n $('#songName').attr('placeholder', 'Search for another song or artist!')\n }", "editTracksInfo () {\n //\n }", "function displayTracks(tracks) {\n var tracksList = document.getElementById('show_tracks'); //where to append the list\n var listSize = tracks.length;\n\n for (var i = 0; i < listSize; i++) {\n var trck = tracks[i]; //current track\n var tmpl = document.getElementById('track-template').content.cloneNode(true); //get the template\n\n //shortens long track names\n var trackName = trck.name;\n if (trackName.length > 35) {\n var extra = (trackName.length - 35) * -1;\n trackName = trackName.slice(0, extra) + \"...\";\n }\n //write track name to the template\n tmpl.querySelector('.track-title').innerText = trackName;\n\n //shortens long artist name\n var artistName = trck.artists[0].name; //get the first artist\n if (artistName.length > 25) {\n var ex = (artistName.length - 25) * -1;\n artistName = artistName.slice(0, ex) + \"...\";\n }\n tmpl.querySelector('.track-artist').innerText = artistName; //write to html\n\n //shortens long album names\n var albumName = trck.album.name;\n if (albumName.length > 25) {\n var ext = (albumName.length - 25) * -1;\n albumName = albumName.slice(0, ext) + \"...\";\n }\n\n //write album name and track duration to html\n tmpl.querySelector('.track-album').innerText = albumName;\n tmpl.querySelector('.cell3').innerText = getDuration(trck.duration_ms);\n\n tmpl.querySelector('.track-album').id = i.toString(); //add id for listener\n tmpl.querySelector('.track-artist').id = trck.artists[0].id + \"\" + i.toString(); //add id for listener\n tmpl.querySelector('.playbtn').id = trck.uri; //add id for listener\n tmpl.querySelector('.track-lyric').id = \"lyric\" + \"\" + i.toString() + \"\" + i.toString();\n tmpl.querySelector('.lyric-drop').id = i.toString() + \"\" + i.toString() + \"\" + \"lyric\";\n tracksList.appendChild(tmpl); //write template to html\n\n addAlbumListener(trck.album.id, trck.album.name, trck.artists[0].name, i.toString()); //add listener to album\n addArtistListener(trck.artists[0].name, trck.artists[0].id, trck.artists[0].id + \"\" + i); //add listener to album\n addPlayListener(trck.uri); //add listeners to play button\n addLyricListener(\"lyric\" + \"\" + i.toString() + \"\" + i.toString(), i.toString() + \"\" + i.toString() + \"\" + \"lyric\", trck.name, trck.artists[0].name);\n }\n}", "function AddNewTrack(req, res) {\n// Add a new artist by req.body\n}", "function onCreateTaskButtonClick(event) {\n createTask(event);\n}", "createTrack(id,name){\r\n const html =` <a href=\"#\" class=\"list-group-item list-group-item-action list-group-item-light\" id=\"${id}\">${name} </a>`;\r\n document.querySelector(DOMElements.divCancionLista).insertAdjacentHTML('beforeend',html);\r\n }", "function set_note_button_callback() {\n songList.name = song_title_box.value;\n if ( !(songList.notes.length == 0) ) {\n var n = note_production_label.note;\n \n alert(songList.notes[songList.length - 1]);\n commandStack.execute(new SetNoteCommand(new Note(n.pitch, n.length),\n songList));\n drawSongArea();\n saveSong(songList);\n }\n}", "function createAudioButton() {\n // creating the 'play' button\n var playButton1 = document.createElement(\"button\");\n playButton1.classList.add(\"play-button\");\n playButton1.innerText = \"PLAY\";\n selectParentDiv.appendChild(playButton1);\n\n playButton1.addEventListener(\"click\", playAudio);\n}", "function soundcloudButton() {\n\t$('.soundTitle__title').each(function(i, obj) {\n\t\tif ($(obj).parent().find(\".spotifyButton\").length == 0) {\n\t\t\tvar text = $(obj).find(\"span:first-child\").text();\n\t\t\tspotifyButton(text).insertAfter(obj);\n\t\t}\n\t});\n\n\tsoundcloudAdded = false;\n}", "createButton () {\n\n this.button = document.createElement('button')\n\n this.button.title = 'This model has multiple views ...'\n\n this.button.className = 'viewable-selector btn'\n\n this.button.onclick = () => {\n this.showPanel(true)\n }\n\n const span = document.createElement('span')\n span.className = 'fa fa-list-ul'\n this.button.appendChild(span)\n\n const label = document.createElement('label')\n this.button.appendChild(label)\n label.innerHTML = 'Views'\n \n this.viewer.container.appendChild(this.button)\n }", "function setupCreateNewPathwayButton() {\n var newItem;\n $(\"div[name='createNewPathway']\").click(function(){\n if ( newItem == undefined )\n newItem = \n\t\tcreateDialog(\"div.createPathway\", \n\t\t\t\t{position:[250,150], width: 700, height: 350, \n\t\t\t\ttitle: \"Create a New Pathway Analysis\"});\n $.get(\"pathway.jsp\", function(data){\n newItem.dialog(\"open\").html(data);\n\t\tcloseDialog(newItem);\n });\n });\n}", "function drawTracks(screen, data) {\n data.tracks.forEach(function(track, row) {\n track.steps.forEach(function(on, column) {\n drawButton(screen,\n column,\n row,\n on ? track.color : \"lightgray\");\n });\n });\n}", "function play_track(track_name)\n{\n $.post(\"/play_request\",{track: track_name},\n function(){\n setTimeout(function(){ refresh_play_state();}, refresh_delay_ms);\n })\n}", "function getTimePlayed(track) {\n /* YOUR CODE HERE */\n}", "function createNewPlayer(){\n let newPlayerButton = document.querySelector('#playername-submit');\n newPlayerButton.addEventListener(\"click\", getNewPlayer);\n}", "function handleClickAddMov() {\r\n alert(`Wow, you added the movie ${title} to your watch list!`);\r\n props.onAdd(id, title, banner, watched);\r\n props.onRemove(id);\r\n }", "function rtGuiClick() { rtGuiAdd(this.id); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col);
PrimRectUV(a, b, uv_a, uv_b, col) { this.native.PrimRectUV(a, b, uv_a, uv_b, col); }
[ "AddRectFilledMultiColor(a, b, col_upr_left, col_upr_right, col_bot_right, col_bot_left) {\r\n this.native.AddRectFilledMultiColor(a, b, col_upr_left, col_upr_right, col_bot_right, col_bot_left);\r\n }", "AddImage(user_texture_id, a, b, uv_a = ImVec2.ZERO, uv_b = ImVec2.UNIT, col = 0xFFFFFFFF) {\r\n this.native.AddImage(ImGuiContext.setTexture(user_texture_id), a, b, uv_a, uv_b, col);\r\n }", "setTextureVScale(v) {\n //TODO\n }", "setTextureUScale(u) {\n //TODO\n }", "AddImageQuad(user_texture_id, a, b, c, d, uv_a = ImVec2.ZERO, uv_b = ImVec2.UNIT_X, uv_c = ImVec2.UNIT, uv_d = ImVec2.UNIT_Y, col = 0xFFFFFFFF) {\r\n this.native.AddImageQuad(ImGuiContext.setTexture(user_texture_id), a, b, c, d, uv_a, uv_b, uv_c, uv_d, col);\r\n }", "function Image(user_texture_id, size, uv0 = ImVec2.ZERO, uv1 = ImVec2.UNIT, tint_col = ImVec4.WHITE, border_col = ImVec4.ZERO) {\r\n bind.Image(ImGuiContext.setTexture(user_texture_id), size, uv0, uv1, tint_col, border_col);\r\n }", "function getGridUvs(row, column, totalRows, totalColumns) {\n var columnWidth = 1 / totalColumns;\n var rowHeight = 1 / totalRows;\n\n // create a Map called `uvs` to hold the 4 UV pairs\n uvs[0].set(columnWidth * column, rowHeight * row + rowHeight);\n uvs[1].set(columnWidth * column, rowHeight * row);\n uvs[2].set(columnWidth * column + columnWidth, rowHeight * row);\n uvs[3].set(columnWidth * column + columnWidth, rowHeight * row + rowHeight);\n return uvs;\n}", "AddImageRounded(user_texture_id, a, b, uv_a, uv_b, col, rounding, rounding_corners = ImDrawCornerFlags.All) {\r\n this.native.AddImageRounded(ImGuiContext.setTexture(user_texture_id), a, b, uv_a, uv_b, col, rounding, rounding_corners);\r\n }", "function Rectangulo(x, y, ancho, alto)\n{\n\n this.x = x;\n this.y = y;\n this.ancho = ancho;\n this.alto = alto;\n\n}", "collide(rect) {\n return (this.left < rect.right && this.right > rect.left &&\n this.top < rect.bottom && this.bottom > rect.top);\n }", "function displayGridPaper()\r\n{\r\n for(var row = 0; row < noRows; row++)\r\n {\r\n for(var col = 0; col < noCols; col++)\r\n {\r\n var x = col * squareSize;\r\n var y = row * squareSize;\r\n\r\n cv.rect(x, y, squareSize, squareSize);\r\n }\r\n }\r\n}", "function render_pivot(context)\n{\n\tvar piece = get_selected_piece();\n\tstroke_tile(piece.pivot_x, piece.pivot_y, grid_pivot_color, context);\n}", "function perturbedRect(x, y, width, height, X_PERTURB, Y_PERTURB){\n\n\tvar topLeft = {x:(x + s.random(width*X_PERTURB) - (width*X_PERTURB*.5)), \n\t y:(y + s.random(height*Y_PERTURB) - (height*Y_PERTURB*.5))};\n\tvar topRight = {x:(x + width + s.random(width*X_PERTURB) - (width*X_PERTURB*.5)), \n\t y:(y + s.random(height*Y_PERTURB) - (height*Y_PERTURB*.5))};\n\tvar bottomRight = {x:(x + width + s.random(width*X_PERTURB) - (width*X_PERTURB*.5)),\n\t y:(y + height + s.random(height*Y_PERTURB) - (height*Y_PERTURB*.5))};\n\tvar bottomLeft = {x:(x + s.random(width*X_PERTURB) - (width*X_PERTURB*.5)),\n\t y:(y + height + s.random(height*Y_PERTURB) - (height*Y_PERTURB*.5))};\n\n\ts.line(topLeft.x, topLeft.y, topRight.x, topRight.y);\n\ts.line(topRight.x, topRight.y, bottomRight.x, bottomRight.y);\n\ts.line(bottomRight.x, bottomRight.y, bottomLeft.x, bottomLeft.y);\n\ts.line(bottomLeft.x, bottomLeft.y, topLeft.x, topLeft.y);\n}", "function uvStyles(uvIndex){\r\n\r\n \r\n if(uvIndex > 0 && (uvIndex < 3)) {\r\n \r\n cityUv.className = \"low\";\r\n \r\n }\r\n \r\n if(uvIndex > 3 && (uvIndex < 6)){\r\n \r\n cityUv.className = \"medium\";\r\n \r\n }\r\n \r\n if(uvIndex > 6 && (uvIndex < 8)){\r\n \r\n cityUv.className = \"high\";\r\n \r\n }\r\n \r\n if(uvIndex > 8 && (uvIndex < 11)){\r\n \r\n cityUv.className = \"very-high\";\r\n \r\n }\r\n if(uvIndex > 11 && (uvIndex < 3)){\r\n \r\n cityUv.className = \"extreme\";\r\n \r\n }\r\n }", "map (tu, tv) {\n if (this.internalBuffer) { \n // using a % operator to cycle/repeat the texture if needed\n let u = Math.abs(((tu * this.width) % this.width)) >> 0;\n let v = Math.abs(((tv * this.height) % this.height)) >> 0;\n\n let pos = (u + v * this.width) * 4;\n\n let r = this.internalBuffer.data[pos];\n let g = this.internalBuffer.data[pos + 1];\n let b = this.internalBuffer.data[pos + 2];\n let a = this.internalBuffer.data[pos + 3];\n\n return new BABYLON.Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);\n }\n // Image is not loaded yet\n else {\n return new BABYLON.Color4(1, 1, 1, 1);\n }\n }", "createRect(){\n let rect = Rect.createRect(this.activeColor);\n this.canvas.add(rect);\n this.notifyCanvasChange(rect.id, \"added\");\n }", "function inBounds(p) {\n // check bounds of display\n if((p[0]-2*bcr) <= width * 0.1 || //left\n (p[0]+2*bcr) >= width - (width * 0.1) || //right\n (p[1]-2*bcr) <= height * 0.1 ||\n (p[1]+2*bcr) >= height - (height * 0.1)) {\n return false;\n }\n return true;\n}", "function overlap_rect(o1, o2, buf) {\n\t if (!o1 || !o2) return true;\n\t if (o1.x + o1.w < o2.x - buf || o1.y + o1.h < o2.y - buf || o1.x - buf > o2.x + o2.w || o1.y - buf > o2.y + o2.h) return false;\n\t return true;\n\t }", "static normalize(rect) {\n if (rect.width < 0) {\n rect.width = -rect.width\n rect.x -= rect.width\n }\n\n if (rect.height < 0) {\n rect.height = -rect.height\n rect.y -= rect.height\n }\n }", "function Rect(width,height) {\n\tthis.width = width;\n\tthis.height = height;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given object is an instance of Key. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.
static isInstance(obj) { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Key.__pulumiType; }
[ "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === KeySigningKey.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === EncryptionConfig.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ContainerPolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === EipAssociation.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Record.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === JavaAppLayer.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === MountTarget.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Host.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PrivateLinkService.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Bot.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VirtualMachineResource.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RelationshipLink.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DisasterRecoveryConfig.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === SigningProfilePermission.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Resolver.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === UserGroup.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Snapshot.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VirtualMachineScaleSetVM.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ServiceLinkedRole.__pulumiType;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FORM VALIDATION SCRIPTS function to get cookie by key
function getCookie(key) { var regexp = new RegExp("(?:^" + key + "|;\s*"+ key + ")=(.*?)(?:;|$)", "g"); var result = regexp.exec(document.cookie); return (result === null) ? null : result[1]; }
[ "function get_cookie(request){\n console.log(request.headers.get('Cookie'));\n if (request.headers.get('Cookie')) {\n const pattern = new RegExp('variant=([10])');\n let match = request.headers.get('Cookie').match(pattern);\n if (match) { \n return match[1]; \n }\n }\n return null\n}", "static getCookie(name) {\n var arg = name + \"=\";\n var alen = arg.length;\n var clen = document.cookie.length;\n var i = 0;\n while (i < clen) {\n var j = i + alen;\n if (document.cookie.substring(i, j) == arg) {\n return CookieUtil.getCookieVal(j);\n }\n i = document.cookie.indexOf(\" \", i) + 1;\n if (i == 0) break;\n }\n return null;\n }", "function checkCookie(){\n\t// remove jwt\n\tcreateCookie(\"jwt\", \"\", 1);\n\tvar usrName = accessCookie(\"username\");\n\tvar usrPssword = accessCookie(\"usrpassword\");\n\n\tif (usrName!=\"\"){\n\t\tdocument.getElementById('inputUsername').value = usrName;\n\t\tdocument.getElementById('inputPassword').value = usrPssword;\n\t}\n}", "function getCheckCookie() {\r\n\treturn $.cookies.test();\r\n}", "function getValueFromCookie(cookieName, field) {\r\n\t/* Get the string of values from the cookie */\r\n\tvar str = getCookie(cookieName);\r\n\tvar values = str.split(','); /* Split the values by the , */\r\n\tvar n = document.forms[\"registerForm\"].length;\r\n\t/* Go over every field of the registration form to look for the index of the one we're looking for */\r\n\tfor (var i = 0; i < n-3; i++) {\r\n\t\tvar fieldName = document.forms[\"registerForm\"][i].name;\r\n\t\tif (fieldName == field) {\r\n\t\t\t/* Return the cookie value in the index of the field */\r\n\t\t\treturn values[i];\r\n\t\t}\r\n\t}\r\n\t/* Return an empty string if the value wasn't found */\r\n\treturn \"\";\r\n}", "keyForCookie(cookie) {\n const { domain, path, name } = cookie;\n return `${domain};${path};${name}`;\n }", "function parseCookie(){\n if(document.cookie.length < 1) return;\n var cString = document.cookie;\n var parts = cString.split(\";\");\n parts.forEach(function(part){\n var pp = part.split('=');\n if(pp.length < 2) return;\n cookie[pp[0].trim()] = pp[1].trim();\n });\n}", "function MatchCookie(name, value)\n{\n this.name = name;\n this.value = value;\n}", "function getSpCookie(cookieName, appID) {\n var matcher;\n console.log(appID);\n if(appID == undefined){\n matcher = new RegExp(cookieName + 'id\\\\.[0-9a-z]+=([0-9a-z\\-]+).*?');\n }\n else{\n matcher = new RegExp(cookieName + '[a-z0-9]+=([^;]+);?');\n }\n var match = document.cookie.match(matcher);\n console.log(document.cookie);\n console.log(match);\n if (match && match[1])\n return match[1].split()[0];\n else\n return null;\n }", "function getCookieLogin() {\r\n\tvar cookies = document.cookie; // gets the cookie\r\n\tif (cookies != \"\") {\r\n\t\tvar cookieArray = cookies.split(';');\r\n\t\tfor (var i = 0; i < cookieArray.length; i++) {\r\n\t\t\tvar key = cookieArray[i].split('=')[0];\r\n\t\t\tkey = key.trim();\r\n\t\t\tvar value = cookieArray[i].split('=')[1];\r\n\t\t\tvar valuesArray = value.split(\"---\");\r\n\t\t\tvar userEmail = decodeURI(valuesArray[0]);\r\n\t\t\treturn userEmail;\r\n\r\n\t\t}\r\n\t}\r\n}", "function getCookie(name) {\n var index = document.cookie.indexOf(name + \"=\")\n if (index == -1) { return \"undefined\"}\n index = document.cookie.indexOf(\"=\", index) + 1\n var end_string = document.cookie.indexOf(\";\", index)\n if (end_string == -1) { end_string = document.cookie.length }\n return unescape(document.cookie.substring(index, end_string))\n} // Based on JavaScript provided by Peter Curtis at www.pcurtis.com -->", "function loadCookies() {\n document.getElementById('name').value = getCookie('name');\n document.getElementById('brand').selectedIndex = getCookie('brand');\n document.getElementById('Type').selectedIndex = getCookie('type');\n document.getElementById('target').selectedIndex = getCookie('target');\n document.getElementById('condition').selectedIndex = getCookie('condition');\n document.getElementById('location').selectedIndex = getCookie('location');\n}", "function getTokenInCookie(){\n let token = document.cookie.slice(document.cookie.lastIndexOf(\"=\")+1);\n return token;\n}", "function _Cookie_load()\n{\n // First, get a list of all cookies that pertain to this document.\n // We do this by reading the magic Document.cookie property\n var allcookies = this.$document.cookie;\n if (allcookies == \"\") return false;\n\n // Now extract just the named cookie from that list.\n var start = allcookies.indexOf(this.$name + '=');\n if (start == -1) return false; // cookie not defined for this page.\n start += this.$name.length + 1; // skip name and equals sign.\n var end = allcookies.indexOf(';', start);\n if (end == -1) end = allcookies.length;\n var cookieval = allcookies.substring(start, end);\n\n // Now that we've extracted the value of the named cookie, we've\n // got to break that value down into individual state variable \n // names and values. The name/value pairs are separated from each\n // other with ampersands, and the individual names and values are\n // separated from each other with colons. We use the split method\n // to parse everything.\n var a = cookieval.split('&'); // break it into array of name/value pairs\n for(var i=0; i < a.length; i++) // break each pair into an array\n a[i] = a[i].split(':');\n\n // Now that we've parsed the cookie value, set all the names and values\n // of the state variables in this Cookie object. Note that we unescape()\n // the property value, because we called escape() when we stored it.\n for(var i = 0; i < a.length; i++) {\n this[a[i][0]] = unescape(a[i][1]);\n }\n\n // We're done, so return the success code\n return true;\n}", "function validateKey() {\n if ($(this).val()) {\n if ($(this).val().match(/^[A-Za-z0-9]*$/)) return hideError($(this).parent().children(\".error\"));\n else return validationError($(this).parent().children(\".error\"), i18n.KEY_VALIDATION_MESSAGE)\n }\n else return validationError($(this).parent().children(\".error\"), i18n.EMPTY_KEY_MESSAGE)\n }", "function searchCookieJar(url) {\n var cookie = '';\n for (var key in COOKIE_JAR) {\n // Check if url starts with key, see: http://stackoverflow.com/q/646628/2402914\n if (COOKIE_JAR.hasOwnProperty(key) && url.lastIndexOf(key, 0) === 0) {\n cookie = COOKIE_JAR[key];\n console.log(\"Using cookies for \" + key);\n break;\n }\n }\n return cookie;\n }", "function cookieExists() {\n return typeof $.cookie(cookie) !== 'undefined';\n }", "function bakeCookies() {\n\n}", "editHMAC() {\n\n\t\t\tlet input = prompt('Edit HMAC value:', Cookies.get(this.config.hmac));\n\n\t\t\t//Set cookie without js.cookie library due to speical char (~) in cookie.\n\t\t\tif (input !== null) document.cookie = this.config.hmac + '=' + input + '; domain=.www.adidas.' + this.config.locale.domain + '; path=/';\n\n\t\t\t//Remove cookie completely if empty.\n\t\t\tif (input === '') Cookies.remove(this.config.hmac, { domain: '.www.adidas.' + this.config.locale.domain });\n\n\t\t\tthis.checkHMAC();\n\n\t\t}", "function CookieUtilities_getSurveyCookie()\n {\n return this.getCookieValue(SiteRecruit_Config.cookieName);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up direct image editing implementation for a component with one image property.
function setupCommonDirectImageEditing(prototype, property, areafunction, sizefunction, isScalingFunction) { // implementation for IDirectImageEdit prototype.getImagePropertyPaths = function(instance) { return [ property ]; } // implementation for IDirectImageEdit prototype.getImageBounds = function(instance, propertyPath, laf) { //println( "image: " + instance.properties[propertyPath].bmpfile + "/" // +instance.properties[propertyPath].bmpid + "/" // +instance.properties[propertyPath].bmpmask ); if (areafunction) return areafunction(instance, laf, property); else { var size = instance.properties.size; return new Rectangle(0, 0, size.width, size.height); } } }
[ "function ciniki_writingcatalog_images() {\n this.webFlags = {\n '1':{'name':'Visible'},\n };\n this.init = function() {\n //\n // The panel to display the edit form\n //\n this.edit = new M.panel('Edit Image',\n 'ciniki_writingcatalog_images', 'edit',\n 'mc', 'medium', 'sectioned', 'ciniki.writingcatalog.images.edit');\n this.edit.default_data = {};\n this.edit.data = {};\n this.edit.writingcatalog_id = 0;\n this.edit.sections = {\n '_image':{'label':'Image', 'type':'imageform', 'fields':{\n 'image_id':{'label':'', 'type':'image_id', 'hidelabel':'yes', 'controls':'all', 'history':'no'},\n }},\n 'info':{'label':'Information', 'type':'simpleform', 'fields':{\n 'name':{'label':'Title', 'type':'text', },\n// 'webflags':{'label':'Website', 'type':'flags', 'join':'yes', 'flags':this.webFlags},\n }},\n '_website':{'label':'Website Information', 'fields':{\n 'webflags_1':{'label':'Visible', 'type':'flagtoggle', 'field':'webflags', 'bit':0x01, 'default':'on'},\n }},\n '_description':{'label':'Description', 'type':'simpleform', 'fields':{\n 'description':{'label':'', 'type':'textarea', 'size':'medium', 'hidelabel':'yes'},\n }},\n '_buttons':{'label':'', 'buttons':{\n 'save':{'label':'Save', 'fn':'M.ciniki_writingcatalog_images.saveImage();'},\n 'delete':{'label':'Delete', 'visible':'no', 'fn':'M.ciniki_writingcatalog_images.deleteImage();'},\n }},\n };\n this.edit.fieldValue = function(s, i, d) { \n if( this.data[i] != null ) {\n return this.data[i]; \n } \n return ''; \n };\n this.edit.fieldHistoryArgs = function(s, i) {\n return {'method':'ciniki.writingcatalog.imageHistory',\n 'args':{'tnid':M.curTenantID, \n 'writingcatalog_image_id':M.ciniki_writingcatalog_images.edit.writingcatalog_image_id, 'field':i}};\n };\n this.edit.addDropImage = function(iid) {\n M.ciniki_writingcatalog_images.edit.setFieldValue('image_id', iid, null, null);\n return true;\n };\n this.edit.sectionGuidedTitle = function(s) {\n if( s == '_image' ) {\n if( this.data.image_id != null && this.data.image_id > 0 ) {\n return this.sections[s]['gtitle-edit'];\n } else {\n return this.sections[s]['gtitle-add'];\n }\n }\n if( this.sections[s] != null && this.sections[s].gtitle != null ) { return this.sections[s].gtitle; }\n return null;\n };\n this.edit.sectionGuidedText = function(s) {\n if( s == '_image' ) {\n if( this.data.image_id != null && this.data.image_id > 0 ) {\n return this.sections[s]['gtext-edit'];\n } else {\n return this.sections[s]['gtext-add'];\n }\n }\n if( s == '_buttons' ) {\n if( this.sections[s].buttons.delete.visible == 'yes' ) {\n return this.sections[s]['gtext-edit'];\n } else {\n return this.sections[s]['gtext-add'];\n }\n }\n if( this.sections[s] != null && this.sections[s].gtext != null ) { return this.sections[s].gtext; }\n return null;\n };\n this.edit.sectionGuidedMore = function(s) {\n if( s == '_image' ) {\n if( this.data.image_id != null && this.data.image_id > 0 ) {\n return this.sections[s]['gmore-edit'];\n } else {\n return this.sections[s]['gmore-add'];\n }\n }\n if( s == '_buttons' ) {\n if( this.sections[s].buttons.delete.visible == 'yes' ) {\n return this.sections[s]['gmore-edit'];\n }\n }\n if( this.sections[s] != null && this.sections[s].gmore != null ) { return this.sections[s].gmore; }\n return null;\n };\n this.edit.addButton('save', 'Save', 'M.ciniki_writingcatalog_images.saveImage();');\n this.edit.addClose('Cancel');\n };\n\n this.start = function(cb, appPrefix, aG) {\n args = {};\n if( aG != null ) { args = eval(aG); }\n\n //\n // Create container\n //\n var appContainer = M.createContainer(appPrefix, 'ciniki_writingcatalog_images', 'yes');\n if( appContainer == null ) {\n M.alert('App Error');\n return false;\n }\n\n if( args.add != null && args.add == 'yes' ) {\n this.showEdit(cb, 0, args.writingcatalog_id);\n } else if( args.writingcatalog_image_id != null && args.writingcatalog_image_id > 0 ) {\n this.showEdit(cb, args.writingcatalog_image_id);\n }\n return false;\n }\n\n this.showEdit = function(cb, iid, eid) {\n if( iid != null ) { this.edit.writingcatalog_image_id = iid; }\n if( eid != null ) { this.edit.writingcatalog_id = eid; }\n this.edit.reset();\n if( this.edit.writingcatalog_image_id > 0 ) {\n this.edit.sections._buttons.buttons.delete.visible = 'yes';\n var rsp = M.api.getJSONCb('ciniki.writingcatalog.imageGet', \n {'tnid':M.curTenantID, 'writingcatalog_image_id':this.edit.writingcatalog_image_id}, function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n }\n M.ciniki_writingcatalog_images.edit.data = rsp.image;\n M.ciniki_writingcatalog_images.edit.refresh();\n M.ciniki_writingcatalog_images.edit.show(cb);\n });\n } else {\n this.edit.data = {};\n this.edit.sections._buttons.buttons.delete.visible = 'no';\n this.edit.refresh();\n this.edit.show(cb);\n }\n };\n\n this.saveImage = function() {\n if( this.edit.writingcatalog_image_id > 0 ) {\n var c = this.edit.serializeFormData('no');\n if( c != '' ) {\n var rsp = M.api.postJSONFormData('ciniki.writingcatalog.imageUpdate', \n {'tnid':M.curTenantID, \n 'writingcatalog_image_id':this.edit.writingcatalog_image_id}, c,\n function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n } else {\n M.ciniki_writingcatalog_images.edit.close();\n }\n });\n } else {\n this.edit.close();\n }\n } else {\n var c = this.edit.serializeFormData('yes');\n var rsp = M.api.postJSONFormData('ciniki.writingcatalog.imageAdd', \n {'tnid':M.curTenantID, 'writingcatalog_id':this.edit.writingcatalog_id}, c,\n function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n } else {\n M.ciniki_writingcatalog_images.edit.close();\n }\n });\n }\n };\n\n this.deleteImage = function() {\n M.confirm('Are you sure you want to delete this image?',null,function() {\n var rsp = M.api.getJSONCb('ciniki.writingcatalog.imageDelete', {'tnid':M.curTenantID, \n 'writingcatalog_image_id':M.ciniki_writingcatalog_images.edit.writingcatalog_image_id}, function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n }\n M.ciniki_writingcatalog_images.edit.close();\n });\n });\n };\n}", "async updateImageSource() {\n const source = await this.getThumbnailURL();\n this.getImage().setAttribute('src', source);\n }", "function setImagePage(){\r\n setPage('image-page');\r\n }", "function setupImageControls() {\n Data.Controls.Brightness = document.getElementById('brightness');\n Data.Controls.Contrast = document.getElementById('contrast');\n Data.Controls.Hue = document.getElementById('hue');\n Data.Controls.Saturation = document.getElementById('saturation');\n\n Data.Controls.Brightness.value = Settings.Filters.Brightness;\n Data.Controls.Contrast.value = Settings.Filters.Contrast;\n Data.Controls.Hue.value = Settings.Filters.Hue;\n Data.Controls.Saturation.value = Settings.Filters.Saturation;\n\n Data.Controls.Brightness.addEventListener('input', filterChange);\n Data.Controls.Contrast.addEventListener('input', filterChange);\n Data.Controls.Hue.addEventListener('input', filterChange);\n Data.Controls.Saturation.addEventListener('input', filterChange);\n\n document.getElementById('image-controls-reset').\n addEventListener('click', imageControlsResetClick);\n document.getElementById('image-controls-save').\n addEventListener('click', imageControlsSaveClick);\n}", "updateconvertedurl() {\n // src is only actually required property\n if (this.src) {\n const params = {\n height: this.height,\n width: this.width,\n quality: this.quality,\n src: this.src,\n rotate: this.rotate,\n fit: this.fit,\n watermark: this.watermark,\n wmspot: this.wmspot,\n format: this.format,\n };\n this.srcconverted = MicroFrontendRegistry.url(\n \"@core/imgManipulate\",\n params\n );\n }\n }", "function menuImageClick() {\n Data.Edit.Mode = EditModes.Image;\n updateMenu();\n}", "function i2uiSetImageDirectory(imageDirectory)\r\n{\r\n i2uiImageDirectory = imageDirectory;\r\n}", "function ImageFlow ()\r\n{\r\n\t/* Setting option defaults */\r\n\tthis.defaults =\r\n\t{\r\n\t\tanimationSpeed: 50, /* Animation speed in ms */\r\n\t\taspectRatio: 1.964, /* Aspect ratio of the ImageFlow container (width divided by height) */\r\n\t\tbuttons: false, /* Toggle navigation buttons */\r\n\t\tcaptions: true, /* Toggle captions */\r\n\t\tcircular: false, /* Toggle circular rotation */\r\n\t\timageCursor: 'default', /* Cursor type for all images - default is 'default' */\r\n\t\tImageFlowID: 'imageflow', /* Default id of the ImageFlow container */\r\n\t\timageFocusM: 1.0, /* Multiplicator for the focussed image size in percent */\r\n\t\timageFocusMax: 4, /* Max number of images on each side of the focussed one */\r\n\t\timagePath: '', /* Path to the images relative to the reflect_.php script */\r\n\t\timageScaling: true, /* Toggle image scaling */ \r\n\t\timagesHeight: 0.67, /* Height of the images div container in percent */\r\n\t\timagesM: 1.0, /* Multiplicator for all images in percent */\r\n\t\tonClick: function() { document.location = this.url; }, /* Onclick behaviour */\r\n\t\topacity: false, /* Toggle image opacity */\r\n\t\topacityArray: [10,8,6,4,2], /* Image opacity (range: 0 to 10) first value is for the focussed image */\r\n\t\tpercentLandscape: 118, /* Scale landscape format */\r\n\t\tpercentOther: 100, /* Scale portrait and square format */\r\n\t\tpreloadImages: true, /* Toggles loading bar (false: requires img attributes height and width) */\r\n\t\treflections: true, /* Toggle reflections */\r\n\t\treflectionGET: '', /* Pass variables via the GET method to the reflect_.php script */\r\n\t\treflectionP: 0.5, /* Height of the reflection in percent of the source image */\r\n\t\treflectionPNG: false, /* Toggle reflect2.php or reflect3.php */\r\n\t\treflectPath: '', /* Path to the reflect_.php script */\r\n\t\tscrollbarP: 0.6, /* Width of the scrollbar in percent */\r\n\t\tslider: true, /* Toggle slider */\r\n\t\tsliderCursor: 'e-resize', /* Slider cursor type - default is 'default' */\r\n\t\tsliderWidth: 14, /* Width of the slider in px */\r\n\t\tslideshow: false, /* Toggle slideshow */\r\n\t\tslideshowSpeed: 1500, /* Time between slides in ms */\r\n\t\tslideshowAutoplay: false, /* Toggle automatic slideshow play on startup */\r\n\t\tstartID: 1, /* Image ID to begin with */\r\n\t\tglideToStartID: true, /* Toggle glide animation to start ID */\r\n\t\tstartAnimation: false, /* Animate images moving in from the right on startup */\r\n\t\txStep: 150 /* Step width on the x-axis in px */\r\n\t};\r\n\r\n\r\n\t/* Closure for this */\r\n\tvar my = this;\r\n\r\n\r\n\t/* Initiate ImageFlow */\r\n\tthis.init = function (options)\r\n\t{\r\n\t\t/* Evaluate options */\r\n\t\tfor(var name in my.defaults) \r\n\t\t{\r\n\t\t\tthis[name] = (options !== undefined && options[name] !== undefined) ? options[name] : my.defaults[name];\r\n\t\t}\r\n\r\n\t\t/* Try to get ImageFlow div element */\r\n\t\tvar ImageFlowDiv = document.getElementById(my.ImageFlowID);\r\n\t\tif(ImageFlowDiv)\r\n\t\t{\r\n\t\t\t/* Set it global within the ImageFlow scope */\r\n\t\t\tImageFlowDiv.style.visibility = 'visible';\r\n\t\t\tthis.ImageFlowDiv = ImageFlowDiv;\r\n\r\n\t\t\t/* Try to create XHTML structure */\r\n\t\t\tif(this.createStructure())\r\n\t\t\t{\r\n\t\t\t\tthis.imagesDiv = document.getElementById(my.ImageFlowID+'_images');\r\n\t\t\t\tthis.captionDiv = document.getElementById(my.ImageFlowID+'_caption');\r\n\t\t\t\tthis.navigationDiv = document.getElementById(my.ImageFlowID+'_navigation');\r\n\t\t\t\tthis.scrollbarDiv = document.getElementById(my.ImageFlowID+'_scrollbar');\r\n\t\t\t\tthis.sliderDiv = document.getElementById(my.ImageFlowID+'_slider');\r\n\t\t\t\tthis.buttonNextDiv = document.getElementById(my.ImageFlowID+'_next');\r\n\t\t\t\tthis.buttonPreviousDiv = document.getElementById(my.ImageFlowID+'_previous');\r\n\t\t\t\tthis.buttonSlideshow = document.getElementById(my.ImageFlowID+'_slideshow');\r\n\r\n\t\t\t\tthis.indexArray = [];\r\n\t\t\t\tthis.current = 0;\r\n\t\t\t\tthis.imageID = 0;\r\n\t\t\t\tthis.target = 0;\r\n\t\t\t\tthis.memTarget = 0;\r\n\t\t\t\tthis.firstRefresh = true;\r\n\t\t\t\tthis.firstCheck = true;\r\n\t\t\t\tthis.busy = false;\r\n\r\n\t\t\t\t/* Set height of the ImageFlow container and center the loading bar */\r\n\t\t\t\tvar width = this.ImageFlowDiv.offsetWidth;\r\n\t\t\t\tvar height = Math.round(width / my.aspectRatio);\r\n\t\t\t\tdocument.getElementById(my.ImageFlowID+'_loading_txt').style.paddingTop = ((height * 0.5) -22) + 'px';\r\n\t\t\t\tImageFlowDiv.style.height = height + 'px';\r\n\r\n\t\t\t\t/* Init loading progress */\r\n\t\t\t\tthis.loadingProgress();\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Create HTML Structure */\r\n\tthis.createStructure = function()\r\n\t{\r\n\t\t/* Create images div container */\r\n\t\tvar imagesDiv = my.Helper.createDocumentElement('div','images');\r\n\r\n\t\t/* Shift all images into the images div */\r\n\t\tvar node, version, src, imageNode;\r\n\t\tvar max = my.ImageFlowDiv.childNodes.length;\r\n\t\tfor(var index = 0; index < max; index++)\r\n\t\t{\r\n\t\t\tnode = my.ImageFlowDiv.childNodes[index];\r\n\t\t\tif (node && node.nodeType == 1 && node.nodeName == 'IMG')\r\n\t\t\t{\r\n\t\t\t\t/* Add 'reflect.php?img=' */\r\n\t\t\t\tif(my.reflections === true)\r\n\t\t\t\t{\r\n\t\t\t\t\tversion = (my.reflectionPNG) ? '3' : '2';\r\n\t\t\t\t\tsrc = my.imagePath+node.getAttribute('src',2);\r\n\t\t\t\t\tsrc = my.reflectPath+'reflect'+version+'.php?img='+src+my.reflectionGET;\r\n\t\t\t\t\tnode.setAttribute('src',src);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Clone image nodes and append them to the images div */\r\n\t\t\t\timageNode = node.cloneNode(true);\r\n\t\t\t\timagesDiv.appendChild(imageNode);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Clone some more images to make a circular animation possible */\r\n\t\tif(my.circular)\r\n\t\t{\r\n\t\t\t/* Create temporary elements to hold the cloned images */\r\n\t\t\tvar first = my.Helper.createDocumentElement('div','images');\r\n\t\t\tvar last = my.Helper.createDocumentElement('div','images');\r\n\t\t\t\r\n\t\t\t/* Make sure, that there are enough images to use circular mode */\r\n\t\t\tmax = imagesDiv.childNodes.length;\r\n\t\t\tif(max < my.imageFocusMax)\r\n\t\t\t{\r\n\t\t\t\tmy.imageFocusMax = max;\r\n\t\t\t}\r\n\r\n\t\t\t/* Do not clone anything if there is only one image */\r\n\t\t\tif(max > 1)\r\n\t\t\t{\r\n\t\t\t\t/* Clone the first and last images */\r\n\t\t\t\tvar i;\r\n\t\t\t\tfor(i = 0; i < max; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\t/* Number of clones on each side equals the imageFocusMax */\r\n\t\t\t\t\tnode = imagesDiv.childNodes[i];\r\n\t\t\t\t\tif(i < my.imageFocusMax)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\timageNode = node.cloneNode(true);\r\n\t\t\t\t\t\tfirst.appendChild(imageNode);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(max-i < my.imageFocusMax+1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\timageNode = node.cloneNode(true);\r\n\t\t\t\t\t\tlast.appendChild(imageNode);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Sort the image nodes in the following order: last | originals | first */\r\n\t\t\t\tfor(i = 0; i < max; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tnode = imagesDiv.childNodes[i];\r\n\t\t\t\t\timageNode = node.cloneNode(true);\r\n\t\t\t\t\tlast.appendChild(imageNode);\r\n\t\t\t\t}\r\n\t\t\t\tfor(i = 0; i < my.imageFocusMax; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tnode = first.childNodes[i];\r\n\t\t\t\t\timageNode = node.cloneNode(true);\r\n\t\t\t\t\tlast.appendChild(imageNode);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t/* Overwrite the imagesDiv with the new order */\r\n\t\t\t\timagesDiv = last;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Create slideshow button div and append it to the images div */\r\n\t\tif(my.slideshow)\r\n\t\t{\r\n\t\t\tvar slideshowButton = my.Helper.createDocumentElement('div','slideshow');\r\n\t\t\timagesDiv.appendChild(slideshowButton);\r\n\t\t}\r\n\r\n\t\t/* Create loading text container */\r\n\t\tvar loadingP = my.Helper.createDocumentElement('p','loading_txt');\r\n\t\tvar loadingText = document.createTextNode(' ');\r\n\t\tloadingP.appendChild(loadingText);\r\n\r\n\t\t/* Create loading div container */\r\n\t\tvar loadingDiv = my.Helper.createDocumentElement('div','loading');\r\n\r\n\t\t/* Create loading bar div container inside the loading div */\r\n\t\tvar loadingBarDiv = my.Helper.createDocumentElement('div','loading_bar');\r\n\t\tloadingDiv.appendChild(loadingBarDiv);\r\n\r\n\t\t/* Create captions div container */\r\n\t\tvar captionDiv = my.Helper.createDocumentElement('div','caption');\r\n\r\n\t\t/* Create slider and button div container inside the scrollbar div */\r\n\t\tvar scrollbarDiv = my.Helper.createDocumentElement('div','scrollbar');\r\n\t\tvar sliderDiv = my.Helper.createDocumentElement('div','slider');\r\n\t\tscrollbarDiv.appendChild(sliderDiv);\r\n\t\tif(my.buttons)\r\n\t\t{\r\n\t\t\tvar buttonPreviousDiv = my.Helper.createDocumentElement('div','previous', 'button');\r\n\t\t\tvar buttonNextDiv = my.Helper.createDocumentElement('div','next', 'button');\r\n\t\t\tscrollbarDiv.appendChild(buttonPreviousDiv);\r\n\t\t\tscrollbarDiv.appendChild(buttonNextDiv);\r\n\t\t}\r\n\r\n\t\t/* Create navigation div container beneath images div */\r\n\t\tvar navigationDiv = my.Helper.createDocumentElement('div','navigation');\r\n\t\tnavigationDiv.appendChild(captionDiv);\r\n\t\tnavigationDiv.appendChild(scrollbarDiv);\r\n\t\r\n\t\t/* Update document structure and return true on success */\r\n\t\tvar success = false;\r\n\t\tif (my.ImageFlowDiv.appendChild(imagesDiv) &&\r\n\t\t\tmy.ImageFlowDiv.appendChild(loadingP) &&\r\n\t\t\tmy.ImageFlowDiv.appendChild(loadingDiv) &&\r\n\t\t\tmy.ImageFlowDiv.appendChild(navigationDiv))\r\n\t\t{\r\n\t\t\t/* Remove image nodes outside the images div */\r\n\t\t\tmax = my.ImageFlowDiv.childNodes.length;\r\n\t\t\tfor(index = 0; index < max; index++)\r\n\t\t\t{\r\n\t\t\t\tnode = my.ImageFlowDiv.childNodes[index];\r\n\t\t\t\tif (node && node.nodeType == 1 && node.nodeName == 'IMG')\r\n\t\t\t\t{\r\n\t\t\t\t\tmy.ImageFlowDiv.removeChild(node);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tsuccess = true;\r\n\t\t}\r\n\t\treturn success;\r\n\t};\r\n\r\n\r\n\t/* Manage loading progress and call the refresh function */\r\n\tthis.loadingProgress = function()\r\n\t{\r\n\t\tvar p = my.loadingStatus();\r\n\t\tif((p < 100 || my.firstCheck) && my.preloadImages)\r\n\t\t{\r\n\t\t\t/* Insert a short delay if the browser loads rapidly from its cache */\r\n\t\t\tif(my.firstCheck && p == 100)\r\n\t\t\t{\r\n\t\t\t\tmy.firstCheck = false;\r\n\t\t\t\twindow.setTimeout(my.loadingProgress, 100);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\twindow.setTimeout(my.loadingProgress, 40);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t/* Hide loading elements */\r\n\t\t\tdocument.getElementById(my.ImageFlowID+'_loading_txt').style.display = 'none';\r\n\t\t\tdocument.getElementById(my.ImageFlowID+'_loading').style.display = 'none';\r\n\r\n\t\t\t/* Refresh ImageFlow on window resize - delay adding this event for the IE */\r\n\t\t\twindow.setTimeout(my.Helper.addResizeEvent, 1000);\r\n\r\n\t\t\t/* Call refresh once on startup to display images */\r\n\t\t\tmy.refresh();\r\n\r\n\t\t\t/* Only initialize navigation elements if there is more than one image */\r\n\t\t\tif(my.max > 1)\r\n\t\t\t{\r\n\t\t\t\t/* Initialize mouse, touch and key support */\r\n\t\t\t\tmy.MouseWheel.init();\r\n\t\t\t\tmy.MouseDrag.init();\r\n\t\t\t\tmy.Touch.init();\r\n\t\t\t\tmy.Key.init();\r\n\t\t\t\t\r\n\t\t\t\t/* Toggle slideshow */\r\n\t\t\t\tif(my.slideshow)\r\n\t\t\t\t{\r\n\t\t\t\t\tmy.Slideshow.init();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Toggle scrollbar visibility */\r\n\t\t\t\tif(my.slider)\r\n\t\t\t\t{\r\n\t\t\t\t\tmy.scrollbarDiv.style.visibility = 'visible';\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Return loaded images in percent, set loading bar width and loading text */\r\n\tthis.loadingStatus = function()\r\n\t{\r\n\t\tvar max = my.imagesDiv.childNodes.length;\r\n\t\tvar i = 0, completed = 0;\r\n\t\tvar image = null;\r\n\t\tfor(var index = 0; index < max; index++)\r\n\t\t{\r\n\t\t\timage = my.imagesDiv.childNodes[index];\r\n\t\t\tif(image && image.nodeType == 1 && image.nodeName == 'IMG')\r\n\t\t\t{\r\n\t\t\t\tif(image.complete)\r\n\t\t\t\t{\r\n\t\t\t\t\tcompleted++;\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar finished = Math.round((completed/i)*100);\r\n\t\tvar loadingBar = document.getElementById(my.ImageFlowID+'_loading_bar');\r\n\t\tloadingBar.style.width = finished+'%';\r\n\r\n\t\t/* Do not count the cloned images */\r\n\t\tif(my.circular)\r\n\t\t{\r\n\t\t\ti = i - (my.imageFocusMax*2);\r\n\t\t\tcompleted = (finished < 1) ? 0 : Math.round((i/100)*finished);\r\n\t\t}\r\n\r\n\t\tvar loadingP = document.getElementById(my.ImageFlowID+'_loading_txt');\r\n\t\tvar loadingTxt = document.createTextNode('loading images '+completed+'/'+i);\r\n\t\tloadingP.replaceChild(loadingTxt,loadingP.firstChild);\r\n\t\treturn finished;\r\n\t};\r\n\r\n\r\n\t/* Cache EVERYTHING that only changes on refresh or resize of the window */\r\n\tthis.refresh = function()\r\n\t{\r\n\t\t/* Cache global variables */\r\n\t\tthis.imagesDivWidth = my.imagesDiv.offsetWidth+my.imagesDiv.offsetLeft;\r\n\t\tthis.maxHeight = Math.round(my.imagesDivWidth / my.aspectRatio);\r\n\t\tthis.maxFocus = my.imageFocusMax * my.xStep;\r\n\t\tthis.size = my.imagesDivWidth * 0.5;\r\n\t\tthis.sliderWidth = my.sliderWidth * 0.5;\r\n\t\tthis.scrollbarWidth = (my.imagesDivWidth - ( Math.round(my.sliderWidth) * 2)) * my.scrollbarP;\r\n\t\tthis.imagesDivHeight = Math.round(my.maxHeight * my.imagesHeight);\r\n\r\n\t\t/* Change imageflow div properties */\r\n\t\tmy.ImageFlowDiv.style.height = my.maxHeight + 'px';\r\n\r\n\t\t/* Change images div properties */\r\n\t\tmy.imagesDiv.style.height = my.imagesDivHeight + 'px'; \r\n\t\t\r\n\t\t/* Change images div properties */\r\n\t\tmy.navigationDiv.style.height = (my.maxHeight - my.imagesDivHeight) + 'px'; \r\n\r\n\t\t/* Change captions div properties */\r\n\t\tmy.captionDiv.style.width = my.imagesDivWidth + 'px';\r\n\t\tmy.captionDiv.style.paddingTop = Math.round(my.imagesDivWidth * 0.02) + 'px';\r\n\r\n\t\t/* Change scrollbar div properties */\r\n\t\tmy.scrollbarDiv.style.width = my.scrollbarWidth + 'px';\r\n\t\tmy.scrollbarDiv.style.marginTop = Math.round(my.imagesDivWidth * 0.02) + 'px';\r\n\t\tmy.scrollbarDiv.style.marginLeft = Math.round(((my.imagesDivWidth - my.scrollbarWidth)/2)) + 'px';\r\n\r\n\t\t/* Set slider attributes */\r\n\t\tmy.sliderDiv.style.cursor = my.sliderCursor;\r\n\t\tmy.sliderDiv.onmousedown = function () { my.MouseDrag.start(this); return false;};\r\n\r\n\t\tif(my.buttons)\r\n\t\t{\r\n\t\t\tmy.buttonPreviousDiv.onclick = function () { my.MouseWheel.handle(1); };\r\n\t\t\tmy.buttonNextDiv.onclick = function () { my.MouseWheel.handle(-1); };\r\n\t\t}\r\n\r\n\t\t/* Set the reflection multiplicator */\r\n\t\tvar multi = (my.reflections === true) ? my.reflectionP + 1 : 1;\r\n\r\n\t\t/* Set image attributes */\r\n\t\tvar max = my.imagesDiv.childNodes.length;\r\n\t\tvar i = 0;\r\n\t\tvar image = null;\r\n\t\tfor (var index = 0; index < max; index++)\r\n\t\t{\r\n\t\t\timage = my.imagesDiv.childNodes[index];\r\n\t\t\tif(image !== null && image.nodeType == 1 && image.nodeName == 'IMG')\r\n\t\t\t{\r\n\t\t\t\tthis.indexArray[i] = index;\r\n\r\n\t\t\t\t/* Set image attributes to store values */\r\n\t\t\t\timage.url = image.getAttribute('longdesc');\r\n\t\t\t\timage.xPosition = (-i * my.xStep);\r\n\t\t\t\timage.i = i;\r\n\r\n\t\t\t\t/* Add width and height as attributes only once */\r\n\t\t\t\tif(my.firstRefresh)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(image.getAttribute('width') !== null && image.getAttribute('height') !== null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\timage.w = image.getAttribute('width');\r\n\t\t\t\t\t\timage.h = image.getAttribute('height') * multi;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse{\r\n\t\t\t\t\t\timage.w = image.width;\r\n\t\t\t\t\t\timage.h = image.height;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Check source image format. Get image height minus reflection height! */\r\n\t\t\t\tif((image.w) > (image.h / (my.reflectionP + 1)))\r\n\t\t\t\t{\r\n\t\t\t\t\t/* Landscape format */\r\n\t\t\t\t\timage.pc = my.percentLandscape;\r\n\t\t\t\t\timage.pcMem = my.percentLandscape;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t/* Portrait and square format */\r\n\t\t\t\t\timage.pc = my.percentOther;\r\n\t\t\t\t\timage.pcMem = my.percentOther;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t/* Change image positioning */\r\n\t\t\t\tif(my.imageScaling === false)\r\n\t\t\t\t{\r\n\t\t\t\t\timage.style.position = 'relative';\r\n\t\t\t\t\timage.style.display = 'inline';\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Set image cursor type */\r\n\t\t\t\timage.style.cursor = my.imageCursor;\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.max = my.indexArray.length;\r\n\r\n\t\t/* Override dynamic sizes based on the first image */\r\n\t\tif(my.imageScaling === false)\r\n\t\t{\r\n\t\t\timage = my.imagesDiv.childNodes[my.indexArray[0]];\r\n\r\n\t\t\t/* Set left padding for the first image */\r\n\t\t\tthis.totalImagesWidth = image.w * my.max;\r\n\t\t\timage.style.paddingLeft = (my.imagesDivWidth/2) + (image.w/2) + 'px';\r\n\r\n\t\t\t/* Override images and navigation div height */\r\n\t\t\tmy.imagesDiv.style.height = image.h + 'px';\r\n\t\t\tmy.navigationDiv.style.height = (my.maxHeight - image.h) + 'px'; \r\n\t\t}\r\n\r\n\t\t/* Handle startID on the first refresh */\r\n\t\tif(my.firstRefresh)\r\n\t\t{\r\n\t\t\t/* Reset variable */\r\n\t\t\tmy.firstRefresh = false;\r\n\r\n\t\t\t/* Set imageID to the startID */\r\n\t\t\tmy.imageID = my.startID-1;\r\n\t\t\tif (my.imageID < 0 )\r\n\t\t\t{\r\n\t\t\t\tmy.imageID = 0;\r\n\t\t\t}\r\n\r\n\t\t\t/* Map image id range in cicular mode (ignore the cloned images) */\r\n\t\t\tif(my.circular)\r\n\t\t\t{\t\r\n\t\t\t\tmy.imageID = my.imageID + my.imageFocusMax;\r\n\t\t\t}\r\n\r\n\t\t\t/* Make sure, that the id is smaller than the image count */\r\n\t\t\tmaxId = (my.circular) ? (my.max-(my.imageFocusMax))-1 : my.max-1;\r\n\t\t\tif (my.imageID > maxId)\r\n\t\t\t{\r\n\t\t\t\tmy.imageID = maxId;\r\n\t\t\t}\r\n\r\n\t\t\t/* Toggle glide animation to start ID */\r\n\t\t\tif(my.glideToStartID === false)\r\n\t\t\t{\r\n\t\t\t\tmy.moveTo(-my.imageID * my.xStep);\r\n\t\t\t}\r\n\r\n\t\t\t/* Animate images moving in from the right */\r\n\t\t\tif(my.startAnimation)\r\n\t\t\t{\r\n\t\t\t\tmy.moveTo(5000);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Only animate if there is more than one image */\r\n\t\tif(my.max > 1)\r\n\t\t{\r\n\t\t\tmy.glideTo(my.imageID);\r\n\t\t}\r\n\r\n\t\t/* Display images in current order */\r\n\t\tmy.moveTo(my.current);\r\n\t};\r\n\r\n\r\n\t/* Main animation function */\r\n\tthis.moveTo = function(x)\r\n\t{\r\n\t\tthis.current = x;\r\n\t\tthis.zIndex = my.max;\r\n\r\n\t\t/* Main loop */\r\n\t\tfor (var index = 0; index < my.max; index++)\r\n\t\t{\r\n\t\t\tvar image = my.imagesDiv.childNodes[my.indexArray[index]];\r\n\t\t\tvar currentImage = index * -my.xStep;\r\n\r\n\t\t\t/* Enabled image scaling */\r\n\t\t\tif(my.imageScaling)\r\n\t\t\t{\r\n\t\t\t\t/* Don't display images that are not conf_focussed */\r\n\t\t\t\tif ((currentImage + my.maxFocus) < my.memTarget || (currentImage - my.maxFocus) > my.memTarget)\r\n\t\t\t\t{\r\n\t\t\t\t\timage.style.visibility = 'hidden';\r\n\t\t\t\t\timage.style.display = 'none';\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvar z = (Math.sqrt(10000 + x * x) + 100) * my.imagesM;\r\n\t\t\t\t\tvar xs = x / z * my.size + my.size;\r\n\r\n\t\t\t\t\t/* Still hide images until they are processed, but set display style to block */\r\n\t\t\t\t\timage.style.display = 'block';\r\n\r\n\t\t\t\t\t/* Process new image height and width */\r\n\t\t\t\t\tvar newImageH = (image.h / image.w * image.pc) / z * my.size;\r\n\t\t\t\t\tvar newImageW = 0;\r\n\t\t\t\t\tswitch (newImageH > my.maxHeight)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcase false:\r\n\t\t\t\t\t\t\tnewImageW = image.pc / z * my.size;\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tnewImageH = my.maxHeight;\r\n\t\t\t\t\t\t\tnewImageW = image.w * newImageH / image.h;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tvar newImageTop = (my.imagesDivHeight - newImageH) + ((newImageH / (my.reflectionP + 1)) * my.reflectionP);\r\n\r\n\t\t\t\t\t/* Set new image properties */\r\n\t\t\t\t\timage.style.left = xs - (image.pc / 2) / z * my.size + 'px';\r\n\t\t\t\t\tif(newImageW && newImageH)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\timage.style.height = newImageH + 'px';\r\n\t\t\t\t\t\timage.style.width = newImageW + 'px';\r\n\t\t\t\t\t\timage.style.top = newImageTop + 'px';\r\n\t\t\t\t\t}\r\n\t\t\t\t\timage.style.visibility = 'visible';\r\n\r\n\t\t\t\t\t/* Set image layer through zIndex */\r\n\t\t\t\t\tswitch ( x < 0 )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcase true:\r\n\t\t\t\t\t\t\tthis.zIndex++;\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tthis.zIndex = my.zIndex - 1;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* Change zIndex and onclick function of the focussed image */\r\n\t\t\t\t\tswitch ( image.i == my.imageID )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcase false:\r\n\t\t\t\t\t\t\timage.onclick = function() { my.glideTo(this.i);};\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tthis.zIndex = my.zIndex + 1;\r\n\t\t\t\t\t\t\tif(image.url !== '')\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\timage.onclick = my.onClick;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\timage.style.zIndex = my.zIndex;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/* Disabled image scaling */\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif ((currentImage + my.maxFocus) < my.memTarget || (currentImage - my.maxFocus) > my.memTarget)\r\n\t\t\t\t{\r\n\t\t\t\t\timage.style.visibility = 'hidden';\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\timage.style.visibility = 'visible';\r\n\r\n\t\t\t\t\t/* Change onclick function of the focussed image */\r\n\t\t\t\t\tswitch ( image.i == my.imageID )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcase false:\r\n\t\t\t\t\t\t\timage.onclick = function() { my.glideTo(this.i);};\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tif(image.url !== '')\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\timage.onclick = my.onClick;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\t\r\n\t\t\t\tmy.imagesDiv.style.marginLeft = (x - my.totalImagesWidth) + 'px';\r\n\t\t\t}\r\n\r\n\t\t\tx += my.xStep;\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Initializes image gliding animation */\r\n\tthis.glideTo = function(imageID)\r\n\t{\r\n\t\t/* Check for jumppoints */\r\n\t\tvar jumpTarget, clonedImageID;\r\n\t\tif(my.circular)\r\n\t\t{\r\n\t\t\t/* Trigger left jumppoint */\r\n\t\t\tif(imageID+1 === my.imageFocusMax)\r\n\t\t\t{\r\n\t\t\t\t/* Set jump target to the same cloned image on the right */\r\n\t\t\t\tclonedImageID = my.max - my.imageFocusMax;\r\n\t\t\t\tjumpTarget = -clonedImageID * my.xStep;\r\n\r\n\t\t\t\t/* Set the imageID to the last image */\r\n\t\t\t\timageID = clonedImageID-1 ;\r\n\t\t\t}\r\n\r\n\t\t\t/* Trigger right jumppoint */\r\n\t\t\tif(imageID === (my.max - my.imageFocusMax))\r\n\t\t\t{\r\n\t\t\t\t/* Set jump target to the same cloned image on the left */\r\n\t\t\t\tclonedImageID = my.imageFocusMax-1;\r\n\t\t\t\tjumpTarget = -clonedImageID * my.xStep;\r\n\t\t\t\t\r\n\t\t\t\t/* Set the imageID to the first image */\r\n\t\t\t\timageID = clonedImageID+1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Calculate new image position target */\r\n\t\tvar x = -imageID * my.xStep;\r\n\t\tthis.target = x;\r\n\t\tthis.memTarget = x;\r\n\t\tthis.imageID = imageID;\r\n\r\n\t\t/* Display new caption */\r\n\t\tvar caption = my.imagesDiv.childNodes[imageID].getAttribute('alt');\r\n\t\tif (caption === '' || my.captions === false)\r\n\t\t{\r\n\t\t\tcaption = '&nbsp;';\r\n\t\t}\r\n\t\tmy.captionDiv.innerHTML = caption;\r\n\r\n\t\t/* Set scrollbar slider to new position */\r\n\t\tif (my.MouseDrag.busy === false)\r\n\t\t{\r\n\t\t\tif(my.circular)\r\n\t\t\t{\r\n\t\t\t\tthis.newSliderX = ((imageID-my.imageFocusMax) * my.scrollbarWidth) / (my.max-(my.imageFocusMax*2)-1) - my.MouseDrag.newX;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthis.newSliderX = (imageID * my.scrollbarWidth) / (my.max-1) - my.MouseDrag.newX;\r\n\t\t\t}\r\n\t\t\tmy.sliderDiv.style.marginLeft = (my.newSliderX - my.sliderWidth) + 'px';\r\n\t\t}\r\n\r\n\t\t/* Only process if opacity or a multiplicator for the focussed image has been set */\r\n\t\tif(my.opacity === true || my.imageFocusM !== my.defaults.imageFocusM)\r\n\t\t{\r\n\t\t\t/* Set opacity for centered image */\r\n\t\t\tmy.Helper.setOpacity(my.imagesDiv.childNodes[imageID], my.opacityArray[0]);\r\n\t\t\tmy.imagesDiv.childNodes[imageID].pc = my.imagesDiv.childNodes[imageID].pc * my.imageFocusM;\r\n\r\n\t\t\t/* Set opacity for the other images that are displayed */\r\n\t\t\tvar opacityValue = 0;\r\n\t\t\tvar rightID = 0;\r\n\t\t\tvar leftID = 0;\r\n\t\t\tvar last = my.opacityArray.length;\r\n\r\n\t\t\tfor (var i = 1; i < (my.imageFocusMax+1); i++)\r\n\t\t\t{\r\n\t\t\t\tif((i+1) > last)\r\n\t\t\t\t{\r\n\t\t\t\t\topacityValue = my.opacityArray[last-1];\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\topacityValue = my.opacityArray[i];\r\n\t\t\t\t}\r\n\r\n\t\t\t\trightID = imageID + i;\r\n\t\t\t\tleftID = imageID - i;\r\n\r\n\t\t\t\tif (rightID < my.max)\r\n\t\t\t\t{\r\n\t\t\t\t\tmy.Helper.setOpacity(my.imagesDiv.childNodes[rightID], opacityValue);\r\n\t\t\t\t\tmy.imagesDiv.childNodes[rightID].pc = my.imagesDiv.childNodes[rightID].pcMem;\r\n\t\t\t\t}\r\n\t\t\t\tif (leftID >= 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tmy.Helper.setOpacity(my.imagesDiv.childNodes[leftID], opacityValue);\r\n\t\t\t\t\tmy.imagesDiv.childNodes[leftID].pc = my.imagesDiv.childNodes[leftID].pcMem;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Move the images to the jump target */\r\n\t\tif(jumpTarget)\r\n\t\t{\r\n\t\t\tmy.moveTo(jumpTarget);\r\n\t\t}\r\n\r\n\t\t/* Animate gliding to new x position */\r\n\t\tif (my.busy === false)\r\n\t\t{\r\n\t\t\tmy.busy = true;\r\n\t\t\tmy.animate();\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Animates image gliding */\r\n\tthis.animate = function()\r\n\t{\r\n\t\tswitch (my.target < my.current-1 || my.target > my.current+1)\r\n\t\t{\r\n\t\t\tcase true:\r\n\t\t\t\tmy.moveTo(my.current + (my.target-my.current)/3);\r\n\t\t\t\twindow.setTimeout(my.animate, my.animationSpeed);\r\n\t\t\t\tmy.busy = true;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tdefault:\r\n\t\t\t\tmy.busy = false;\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Used by user events to call the glideTo function */\r\n\tthis.glideOnEvent = function(imageID)\r\n\t{\r\n\t\t/* Interrupt slideshow on mouse wheel, keypress, touch and mouse drag */\r\n\t\tif(my.slideshow)\r\n\t\t{\r\n\t\t\tmy.Slideshow.interrupt();\r\n\t\t}\r\n\t\t\r\n\t\t/* Glide to new imageID */\r\n\t\tmy.glideTo(imageID);\r\n\t};\r\n\r\n\r\n\t/* Slideshow function */\r\n\tthis.Slideshow =\r\n\t{\r\n\t\tdirection: 1,\r\n\t\t\r\n\t\tinit: function()\r\n\t\t{\r\n\t\t\t/* Call start() if autoplay is enabled, stop() if it is disabled */\r\n\t\t\t(my.slideshowAutoplay) ? my.Slideshow.start() : my.Slideshow.stop();\t\r\n\t\t},\r\n\r\n\t\tinterrupt: function()\r\n\t\t{\t\r\n\t\t\t/* Remove interrupt event */\r\n\t\t\tmy.Helper.removeEvent(my.ImageFlowDiv,'click',my.Slideshow.interrupt);\r\n\t\t\t\r\n\t\t\t/* Interrupt the slideshow */\r\n\t\t\tmy.Slideshow.stop();\r\n\t\t},\r\n\r\n\t\taddInterruptEvent: function()\r\n\t\t{\r\n\t\t\t/* A click anywhere inside the ImageFlow div interrupts the slideshow */\r\n\t\t\tmy.Helper.addEvent(my.ImageFlowDiv,'click',my.Slideshow.interrupt);\r\n\t\t},\r\n\r\n\t\tstart: function()\r\n\t\t{\r\n\t\t\t/* Set button style to pause */\r\n\t\t\tmy.Helper.setClassName(my.buttonSlideshow, 'slideshow pause');\r\n\r\n\t\t\t/* Set onclick behaviour to stop */\r\n\t\t\tmy.buttonSlideshow.onclick = function () { my.Slideshow.stop(); };\r\n\r\n\t\t\t/* Set slide interval */\r\n\t\t\tmy.Slideshow.action = window.setInterval(my.Slideshow.slide, my.slideshowSpeed);\r\n\r\n\t\t\t/* Allow the user to always interrupt the slideshow */\r\n\t\t\twindow.setTimeout(my.Slideshow.addInterruptEvent, 100);\r\n\t\t},\r\n\r\n\t\tstop: function()\r\n\t\t{\r\n\t\t\t/* Set button style to play */\r\n\t\t\tmy.Helper.setClassName(my.buttonSlideshow, 'slideshow play');\r\n\t\t\t\r\n\t\t\t/* Set onclick behaviour to start */\r\n\t\t\tmy.buttonSlideshow.onclick = function () { my.Slideshow.start(); };\r\n\t\t\t\r\n\t\t\t/* Clear slide interval */\r\n\t\t\twindow.clearInterval(my.Slideshow.action);\r\n\t\t},\r\n\r\n\t\tslide: function()\r\n\t\t{\r\n\t\t\tvar newImageID = my.imageID + my.Slideshow.direction;\r\n\t\t\tvar reverseDirection = false;\r\n\t\t\t\r\n\t\t\t/* Reverse direction at the last image on the right */\r\n\t\t\tif(newImageID === my.max)\r\n\t\t\t{\r\n\t\t\t\tmy.Slideshow.direction = -1;\r\n\t\t\t\treverseDirection = true;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/* Reverse direction at the last image on the left */\r\n\t\t\tif(newImageID < 0)\r\n\t\t\t{\r\n\t\t\t\tmy.Slideshow.direction = 1;\r\n\t\t\t\treverseDirection = true;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/* If direction is reversed recall this method, else call the glideTo method */\r\n\t\t\t(reverseDirection) ? my.Slideshow.slide() : my.glideTo(newImageID);\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Mouse Wheel support */\r\n\tthis.MouseWheel =\r\n\t{\r\n\t\tinit: function()\r\n\t\t{\r\n\t\t\t/* Init mouse wheel listener */\r\n\t\t\tif(window.addEventListener)\r\n\t\t\t{\r\n\t\t\t\tmy.ImageFlowDiv.addEventListener('DOMMouseScroll', my.MouseWheel.get, false);\r\n\t\t\t}\r\n\t\t\tmy.Helper.addEvent(my.ImageFlowDiv,'mousewheel',my.MouseWheel.get);\r\n\t\t},\r\n\r\n\t\tget: function(event)\r\n\t\t{\r\n\t\t\tvar delta = 0;\r\n\t\t\tif (!event)\r\n\t\t\t{\r\n\t\t\t\tevent = window.event;\r\n\t\t\t}\r\n\t\t\tif (event.wheelDelta)\r\n\t\t\t{\r\n\t\t\t\tdelta = event.wheelDelta / 120;\r\n\t\t\t}\r\n\t\t\telse if (event.detail)\r\n\t\t\t{\r\n\t\t\t\tdelta = -event.detail / 3;\r\n\t\t\t}\r\n\t\t\tif (delta)\r\n\t\t\t{\r\n\t\t\t\tmy.MouseWheel.handle(delta);\r\n\t\t\t}\r\n\t\t\tmy.Helper.suppressBrowserDefault(event);\r\n\t\t},\r\n\r\n\t\thandle: function(delta)\r\n\t\t{\r\n\t\t\tvar change = false;\r\n\t\t\tvar newImageID = 0;\r\n\t\t\tif(delta > 0)\r\n\t\t\t{\r\n\t\t\t\tif(my.imageID >= 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tnewImageID = my.imageID -1;\r\n\t\t\t\t\tchange = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif(my.imageID < (my.max-1))\r\n\t\t\t\t{\r\n\t\t\t\t\tnewImageID = my.imageID +1;\r\n\t\t\t\t\tchange = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/* Glide to next (mouse wheel down) / previous (mouse wheel up) image */\r\n\t\t\tif(change)\r\n\t\t\t{\r\n\t\t\t\tmy.glideOnEvent(newImageID);\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Mouse Dragging */\r\n\tthis.MouseDrag =\r\n\t{\r\n\t\tobject: null,\r\n\t\tobjectX: 0,\r\n\t\tmouseX: 0,\r\n\t\tnewX: 0,\r\n\t\tbusy: false,\r\n\r\n\t\t/* Init mouse event listener */\r\n\t\tinit: function()\r\n\t\t{\r\n\t\t\tmy.Helper.addEvent(my.ImageFlowDiv,'mousemove',my.MouseDrag.drag);\r\n\t\t\tmy.Helper.addEvent(my.ImageFlowDiv,'mouseup',my.MouseDrag.stop);\r\n\t\t\tmy.Helper.addEvent(document,'mouseup',my.MouseDrag.stop);\r\n\r\n\t\t\t/* Avoid text and image selection while dragging */\r\n\t\t\tmy.ImageFlowDiv.onselectstart = function ()\r\n\t\t\t{\r\n\t\t\t\tvar selection = true;\r\n\t\t\t\tif (my.MouseDrag.busy)\r\n\t\t\t\t{\r\n\t\t\t\t\tselection = false;\r\n\t\t\t\t}\r\n\t\t\t\treturn selection;\r\n\t\t\t};\r\n\t\t},\r\n\r\n\t\tstart: function(o)\r\n\t\t{\r\n\t\t\tmy.MouseDrag.object = o;\r\n\t\t\tmy.MouseDrag.objectX = my.MouseDrag.mouseX - o.offsetLeft + my.newSliderX;\r\n\t\t},\r\n\r\n\t\tstop: function()\r\n\t\t{\r\n\t\t\tmy.MouseDrag.object = null;\r\n\t\t\tmy.MouseDrag.busy = false;\r\n\t\t},\r\n\r\n\t\tdrag: function(e)\r\n\t\t{\r\n\t\t\tvar posx = 0;\r\n\t\t\tif (!e)\r\n\t\t\t{\r\n\t\t\t\te = window.event;\r\n\t\t\t}\r\n\t\t\tif (e.pageX)\r\n\t\t\t{\r\n\t\t\t\tposx = e.pageX;\r\n\t\t\t}\r\n\t\t\telse if (e.clientX)\r\n\t\t\t{\r\n\t\t\t\tposx = e.clientX + document.body.scrollLeft\t+ document.documentElement.scrollLeft;\r\n\t\t\t}\r\n\t\t\tmy.MouseDrag.mouseX = posx;\r\n\r\n\t\t\tif(my.MouseDrag.object !== null)\r\n\t\t\t{\r\n\t\t\t\tvar newX = (my.MouseDrag.mouseX - my.MouseDrag.objectX) + my.sliderWidth;\r\n\r\n\t\t\t\t/* Make sure, that the slider is moved in proper relation to previous movements by the glideTo function */\r\n\t\t\t\tif(newX < ( - my.newSliderX))\r\n\t\t\t\t{\r\n\t\t\t\t\tnewX = - my.newSliderX;\r\n\t\t\t\t}\r\n\t\t\t\tif(newX > (my.scrollbarWidth - my.newSliderX))\r\n\t\t\t\t{\r\n\t\t\t\t\tnewX = my.scrollbarWidth - my.newSliderX;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* Set new slider position */\r\n\t\t\t\tvar step, imageID;\r\n\t\t\t\tif(my.circular)\r\n\t\t\t\t{\r\n\t\t\t\t\tstep = (newX + my.newSliderX) / (my.scrollbarWidth / (my.max-(my.imageFocusMax*2)-1));\r\n\t\t\t\t\timageID = Math.round(step)+my.imageFocusMax;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tstep = (newX + my.newSliderX) / (my.scrollbarWidth / (my.max-1));\r\n\t\t\t\t\timageID = Math.round(step);\r\n\t\t\t\t}\r\n\t\t\t\tmy.MouseDrag.newX = newX;\r\n\t\t\t\tmy.MouseDrag.object.style.left = newX + 'px';\r\n\t\t\t\tif(my.imageID !== imageID)\r\n\t\t\t\t{\r\n\t\t\t\t\tmy.glideOnEvent(imageID);\r\n\t\t\t\t}\r\n\t\t\t\tmy.MouseDrag.busy = true;\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Safari touch events on the iPhone and iPod Touch */\r\n\tthis.Touch =\r\n\t{\r\n\t\tx: 0,\r\n\t\tstartX: 0,\r\n\t\tstopX: 0,\r\n\t\tbusy: false,\r\n\t\tfirst: true,\r\n\r\n\t\t/* Init touch event listener */\r\n\t\tinit: function()\r\n\t\t{\r\n\t\t\tmy.Helper.addEvent(my.navigationDiv,'touchstart',my.Touch.start);\r\n\t\t\tmy.Helper.addEvent(document,'touchmove',my.Touch.handle);\r\n\t\t\tmy.Helper.addEvent(document,'touchend',my.Touch.stop);\t\r\n\t\t},\r\n\t\t\r\n\t\tisOnNavigationDiv: function(e)\r\n\t\t{\r\n\t\t\tvar state = false;\r\n\t\t\tif(e.touches)\r\n\t\t\t{\r\n\t\t\t\tvar target = e.touches[0].target;\r\n\t\t\t\tif(target === my.navigationDiv || target === my.sliderDiv || target === my.scrollbarDiv)\r\n\t\t\t\t{\r\n\t\t\t\t\tstate = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn state;\r\n\t\t},\r\n\r\n\t\tgetX: function(e)\r\n\t\t{\r\n\t\t\tvar x = 0;\r\n\t\t\tif(e.touches)\r\n\t\t\t{\r\n\t\t\t\tx = e.touches[0].pageX;\r\n\t\t\t}\r\n\t\t\treturn x;\r\n\t\t},\r\n\r\n\t\tstart: function(e)\r\n\t\t{\r\n\t\t\tmy.Touch.startX = my.Touch.getX(e);\r\n\t\t\tmy.Touch.busy = true;\r\n\t\t\tmy.Helper.suppressBrowserDefault(e);\r\n\t\t},\r\n\r\n\t\tisBusy: function()\r\n\t\t{\r\n\t\t\tvar busy = false;\r\n\t\t\tif(my.Touch.busy)\r\n\t\t\t{\r\n\t\t\t\tbusy = true;\r\n\t\t\t}\r\n\t\t\treturn busy;\r\n\t\t},\r\n\r\n\t\t/* Handle touch event position within the navigation div */\r\n\t\thandle: function(e)\r\n\t\t{\r\n\t\t\tif(my.Touch.isBusy && my.Touch.isOnNavigationDiv(e))\r\n\t\t\t{\r\n\t\t\t\tvar max = (my.circular) ? (my.max-(my.imageFocusMax*2)-1) : (my.max-1);\r\n\t\t\t\tif(my.Touch.first)\r\n\t\t\t\t{\r\n\t\t\t\t\tmy.Touch.stopX = (max - my.imageID) * (my.imagesDivWidth / max);\r\n\t\t\t\t\tmy.Touch.first = false;\r\n\t\t\t\t}\r\n\t\t\t\tvar newX = -(my.Touch.getX(e) - my.Touch.startX - my.Touch.stopX);\r\n\r\n\t\t\t\t/* Map x-axis touch coordinates in range of the ImageFlow width */\r\n\t\t\t\tif(newX < 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tnewX = 0;\r\n\t\t\t\t}\r\n\t\t\t\tif(newX > my.imagesDivWidth)\r\n\t\t\t\t{\r\n\t\t\t\t\tnewX = my.imagesDivWidth;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tmy.Touch.x = newX;\r\n\t\t\t\t\r\n\t\t\t\tvar imageID = Math.round(newX / (my.imagesDivWidth / max));\r\n\t\t\t\timageID = max - imageID;\r\n\t\t\t\tif(my.imageID !== imageID)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(my.circular)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\timageID = imageID + my.imageFocusMax;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tmy.glideOnEvent(imageID);\r\n\t\t\t\t}\r\n\t\t\t\tmy.Helper.suppressBrowserDefault(e);\r\n\t\t\t}\r\n\t\t},\r\n\r\n\t\tstop: function()\r\n\t\t{\r\n\t\t\tmy.Touch.stopX = my.Touch.x;\r\n\t\t\tmy.Touch.busy = false;\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Key support */\r\n\tthis.Key =\r\n\t{\r\n\t\t/* Init key event listener */\r\n\t\tinit: function()\r\n\t\t{\r\n\t\t\tdocument.onkeydown = function(event){ my.Key.handle(event); };\r\n\t\t},\r\n\r\n\t\t/* Handle the arrow keys */\r\n\t\thandle: function(event)\r\n\t\t{\r\n\t\t\tvar charCode = my.Key.get(event);\r\n\t\t\tswitch (charCode)\r\n\t\t\t{\r\n\t\t\t\t/* Right arrow key */\r\n\t\t\t\tcase 39:\r\n\t\t\t\t\tmy.MouseWheel.handle(-1);\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t/* Left arrow key */\r\n\t\t\t\tcase 37:\r\n\t\t\t\t\tmy.MouseWheel.handle(1);\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t},\r\n\r\n\t\t/* Get the current keycode */\r\n\t\tget: function(event)\r\n\t\t{\r\n\t\t\tevent = event || window.event;\r\n\t\t\treturn event.keyCode;\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t/* Helper functions */\r\n\tthis.Helper =\r\n\t{\r\n\t\t/* Add events */\r\n\t\taddEvent: function(obj, type, fn)\r\n\t\t{\r\n\t\t\tif(obj.addEventListener)\r\n\t\t\t{\r\n\t\t\t\tobj.addEventListener(type, fn, false);\r\n\t\t\t}\r\n\t\t\telse if(obj.attachEvent)\r\n\t\t\t{\r\n\t\t\t\tobj[\"e\"+type+fn] = fn;\r\n\t\t\t\tobj[type+fn] = function() { obj[\"e\"+type+fn]( window.event ); };\r\n\t\t\t\tobj.attachEvent( \"on\"+type, obj[type+fn] );\r\n\t\t\t}\r\n\t\t},\r\n\r\n\t\t/* Remove events */\r\n\t\tremoveEvent: function( obj, type, fn )\r\n\t\t{\r\n\t\t\tif (obj.removeEventListener)\r\n\t\t\t{\r\n\t\t\t\tobj.removeEventListener( type, fn, false );\r\n\t\t\t}\r\n\t\t\telse if (obj.detachEvent)\r\n\t\t\t{\r\n\t\t\t\t/* The IE breaks if you're trying to detach an unattached event http://msdn.microsoft.com/en-us/library/ms536411(VS.85).aspx */\r\n\t\t\t\tif(obj[type+fn] === undefined)\r\n\t\t\t\t{\r\n\t\t\t\t\talert('Helper.removeEvent » Pointer to detach event is undefined - perhaps you are trying to detach an unattached event?');\r\n\t\t\t\t}\r\n\t\t\t\tobj.detachEvent( 'on'+type, obj[type+fn] );\r\n\t\t\t\tobj[type+fn] = null;\r\n\t\t\t\tobj['e'+type+fn] = null;\r\n\t\t\t}\r\n\t\t},\r\n\r\n\t\t/* Set image opacity */\r\n\t\tsetOpacity: function(object, value)\r\n\t\t{\r\n\t\t\tif(my.opacity === true)\r\n\t\t\t{\r\n\t\t\t\tobject.style.opacity = value/10;\r\n\t\t\t\tobject.style.filter = 'alpha(opacity=' + value*10 + ')';\r\n\t\t\t}\r\n\t\t},\r\n\r\n\t\t/* Create HTML elements */\r\n\t\tcreateDocumentElement: function(type, id, optionalClass)\r\n\t\t{\r\n\t\t\tvar element = document.createElement(type);\r\n\t\t\telement.setAttribute('id', my.ImageFlowID+'_'+id);\r\n\t\t\tif(optionalClass !== undefined)\r\n\t\t\t{\r\n\t\t\t\tid += ' '+optionalClass;\r\n\t\t\t}\r\n\t\t\tmy.Helper.setClassName(element, id);\r\n\t\t\treturn element;\r\n\t\t},\r\n\r\n\t\t/* Set CSS class */\r\n\t\tsetClassName: function(element, className)\r\n\t\t{\r\n\t\t\tif(element)\r\n\t\t\t{\r\n\t\t\t\telement.setAttribute('class', className);\r\n\t\t\t\telement.setAttribute('className', className);\r\n\t\t\t}\r\n\t\t},\r\n\r\n\t\t/* Suppress default browser behaviour to avoid image/text selection while dragging */\r\n\t\tsuppressBrowserDefault: function(e)\r\n\t\t{\r\n\t\t\tif(e.preventDefault)\r\n\t\t\t{\r\n\t\t\t\te.preventDefault();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\te.returnValue = false;\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t},\r\n\r\n\t\t/* Add functions to the window.onresize event - can not be done by addEvent */\r\n\t\taddResizeEvent: function()\r\n\t\t{\r\n\t\t\tvar otherFunctions = window.onresize;\r\n\t\t\tif(typeof window.onresize != 'function')\r\n\t\t\t{\r\n\t\t\t\twindow.onresize = function()\r\n\t\t\t\t{\r\n\t\t\t\t\tmy.refresh();\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\twindow.onresize = function(){\r\n\t\t\t\t\tif (otherFunctions)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\totherFunctions();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tmy.refresh();\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n}", "function objSetImage(obj, imgPath) {\n if (imgPath != obj.imgPath) {\n obj.imgPath = imgPath;\n obj.div.style.backgroundImage = \"url('\" + imgPath + \"')\";\n obj.div.style.width = imgProp[imgPath].width + \"px\";\n obj.div.style.height = imgProp[imgPath].height + \"px\";\n }\n}", "changeImageProp() {\n if (['small-image', 'benefits-hero'].includes(this.bannerType)) {\n this.responsive = true;\n this.positionOfImageClass = (this.positionOfImage.toUpperCase() === 'RIGHT') ? ' reverse' : '';\n }\n else {\n this.responsive = false;\n if (this.bannerType === 'regular-banner' && window.innerWidth < 768) {\n this.responsive = true;\n }\n }\n }", "set imageURL(aValue) {\n this._logger.debug(\"imageURL[set]\");\n this._imageURL = aValue;\n }", "onFileChange(event) {\n const file = event.target.files[0];\n this.img = URL.createObjectURL(file);\n }", "function setImageSrc(image, location) {\n image.src = location + '-640_medium.webp';\n}", "function setSelectedImage(objectUrl) {\r\n var image_iframe = document.getElementById('image-input'); \r\n image_iframe.contentWindow.setSelectedImage(objectUrl);\r\n }", "function ImageItemModel(){\n this.attachementID;\n this.setAttachementID = function(val){\n this.attachementID = val;\n this.onChange();\n }\n this.getAttachementID = function(){\n return this.attachementID;\n }\n \n this.itemID;\n this.setIdItem = function(val){\n this.itemID = val;\n } \n this.getIdItem = function(){\n return this.itemID;\n }\n \n this.caption;\n this.setCaption = function(val){\n this.caption = val;\n this.onChange();\n }\n this.getCaption = function(val){\n return this.caption;\n }\n \n this.imageHeight;\n this.setImageHeight = function(val){\n this.imageHeight = val;\n }\n this.getImageHeight = function(){\n return this.imageHeight;\n }\n }", "function updateImageReader() {\r\n var newImageUrl = document.getElementById('image-search').value;\r\n\r\n clearImageSelection();\r\n\r\n if (mode == READ_MODE) {\r\n refreshAnnotations(newImageUrl, document.getElementById('textUrl').value);\r\n } else {\r\n document.getElementById('image-input').src = \"/alignment/imageReader.html?ui=embed&editable=true&url=\" + encodeURIComponent(newImageUrl);\r\n document.getElementById('imageUrl').value = newImageUrl;\r\n }\r\n }", "function imageSwitch() {\n tmp = $(this).attr('src');\n $(this).attr('src', $(this).attr('alt_src'));\n $(this).attr('alt_src', tmp);\n }", "function IaPic()\n\t\t{\n\t\t\tthis.el = new Image();\n\t\t\tthis.height = 0;\n\t\t\tthis.width = 0;\n\t\t\tthis.loaded = false;\n\t\t}", "checkFormulaImageFields() {\n if (this.formulaImageFields) {\n this.columns.forEach((col) => {\n if (this.formulaImageFields.indexOf(col.fieldName) !== -1) {\n col.type = 'image';\n }\n });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the Position for the Dialog
function setDialogInPos(posEl){ var size = getSize(posEl); posEl.style.left = x - (size.width/2); posEl.style.top = y - (size.height); posEl.classList.add("is-shown") }
[ "function SetControlWinPosition(position : Vector2){\n\t_controlWinPosition = position;\n}//SetControlWinPosition", "function setMenuLocation() {\n\t\tlet menu = ActiveItem.element.getBoundingClientRect();\n\t\t\n\t\tlet x = menu.left + menu.width + 8;\n\t\tlet y = menu.top;\n\t\t\n\t\tctrColor.propMenu.style.left = `${x}px`;\n\t\tctrColor.propMenu.style.top = `${y}px`;\n\t}", "function setSelfPosition() {\r\n var s = $self[0].style;\r\n\r\n // reset CSS so width is re-calculated for margin-left CSS\r\n $self.css({left: '50%', marginLeft: ($self.outerWidth() / 2) * -1, zIndex: (opts.zIndex + 3) });\r\n\r\n\r\n /* we have to get a little fancy when dealing with height, because lightbox_me\r\n is just so fancy.\r\n */\r\n\r\n // if the height of $self is bigger than the window and self isn't already position absolute\r\n if (($self.height() + 80 >= $(window).height()) && ($self.css('position') != 'absolute')) {\r\n\r\n // we are going to make it positioned where the user can see it, but they can still scroll\r\n // so the top offset is based on the user's scroll position.\r\n var topOffset = $(document).scrollTop() + 40;\r\n $self.css({position: 'absolute', top: topOffset + 'px', marginTop: 0})\r\n } else if ($self.height()+ 80 < $(window).height()) {\r\n //if the height is less than the window height, then we're gonna make this thing position: fixed.\r\n if (opts.centered) {\r\n $self.css({ position: 'fixed', top: '50%', marginTop: ($self.outerHeight() / 2) * -1})\r\n } else {\r\n $self.css({ position: 'fixed'}).css(opts.modalCSS);\r\n }\r\n if (opts.preventScroll) {\r\n $('body').css('overflow', 'hidden');\r\n }\r\n }\r\n }", "positionMenu_() {\n positionPopupAroundElement(\n this, this.menu, this.anchorType, this.invertLeftRight);\n }", "presentLayout() {\n super.presentLayout(this);\n\n const audioModule = this.UIManager._rnctx.AudioModule;\n if (this._handle) {\n const position = this.view.getWorldPosition().toArray();\n audioModule.setPosition(this._handle, position);\n }\n }", "function _setTooltipPosition() {\n // eslint-disable-next-line no-new\n new PopperJs($element, _tooltip, {\n placement: lumx.position || 'top',\n modifiers: {\n arrow: {\n // eslint-disable-next-line id-blacklist\n element: `.${CSS_PREFIX}-tooltip__arrow`,\n enabled: true,\n },\n },\n });\n }", "function updatePosition() {\n\t \n\t\tbox.css({\n\t\t\t'width': ($(element).width() - 2) + 'px',\n\t\t\t'top': ($(element).position().top + $(element).height()) + 'px',\n\t\t\t'left': $(element).position().left +'px'\n\t\t});\n\t}", "function setEditMenuPosition() {\n const menu = document.getElementById('menu');\n const panel = document.getElementById('edit-controls');\n\n const top = Data.Edit.Open ? menu.clientHeight : -panel.clientHeight - 2;\n panel.style.top = top + 'px';\n\n if (Data.Edit.Open)\n document.getElementById('menu-edit').classList.add('active');\n else\n document.getElementById('menu-edit').classList.remove('active');\n}", "function SetElementPos(el, x, y){\n el.style.top = y + 'px';\n el.style.left = x + 'px';\n}", "function setControlsPosition() {\n const menu = document.getElementById('menu');\n const panel = document.getElementById('image-controls');\n\n const top = Data.Controls.Open ? menu.clientHeight : -panel.clientHeight - 2;\n panel.style.top = top + 'px';\n\n if (Data.Controls.Open)\n document.getElementById('menu-controls').classList.add('active');\n else\n document.getElementById('menu-controls').classList.remove('active');\n}", "setCenter(x, y){ this.center.setPoint(x, y) }", "_resetPosition() {\n this._monitor = this._getMonitor();\n\n this._updateSize();\n\n this._updateAppearancePreferences();\n this._updateBarrier();\n }", "resetPosition() {\n if (this.hasGoneOffScreen()) {\n this.x = this.canvas.width;\n }\n }", "function initHelpTxtPos() {\n design = mapConfig['menuDesign'];\n}", "function setSpecificOptions(dialogOptions, name, title, message, width, height) {\n dialogOptions.Width = width;\n dialogOptions.Height = height;\n dialogOptions.Name = name;\n dialogOptions.Title = title;\n\n }", "setScreenPosition(inPosition) {\n switch (inPosition) {\n case GDesktopEnums.MagnifierScreenPosition.FULL_SCREEN:\n this.setFullScreenMode();\n break;\n case GDesktopEnums.MagnifierScreenPosition.TOP_HALF:\n this.setTopHalf();\n break;\n case GDesktopEnums.MagnifierScreenPosition.BOTTOM_HALF:\n this.setBottomHalf();\n break;\n case GDesktopEnums.MagnifierScreenPosition.LEFT_HALF:\n this.setLeftHalf();\n break;\n case GDesktopEnums.MagnifierScreenPosition.RIGHT_HALF:\n this.setRightHalf();\n break;\n }\n }", "function repositionHintBox(e, graph) {\n\t\tvar hbox = $(graph.hintBoxItem),\n\t\t\toffset = graph.offset(),\n\t\t\tpage_bottom = jQuery(window.top).scrollTop() + jQuery(window.top).height(),\n\t\t\tl = (document.body.clientWidth >= e.clientX + hbox.outerWidth() + 20)\n\t\t\t\t? e.clientX - offset.left + 20\n\t\t\t\t: e.clientX - hbox.outerWidth() - offset.left - 15,\n\t\t\tt = e.pageY - offset.top - graph.parent().scrollTop(),\n\t\t\tt = page_bottom >= t + offset.top + hbox.outerHeight() + 60 ? t + 60 : t - hbox.height();\n\n\t\thbox.css({'left': l, 'top': t});\n\t}", "_updateKnobPosition() {\n this._setKnobPosition(this._valueToPosition(this.getValue()));\n }", "function setCaretPosition(position) {\n\tdocument.getElementById(\"content-editor\").setSelectionRange(position, position);\n\tdocument.getElementById(\"content-editor\").focus();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shown if any bulk could not be saved
function show_bulk_error() { var err = {}; err[that.form.entity_name] = { __all__: ["Some " + that.form.entity_name + " (in red below) could not be saved. To correct errors and try saving them again - open a new add form"] }; that.form.show_errors(err, true); }
[ "function giveSaveBtnFeedback() {\n if ($newSetNameInput.classList.contains('invalid-input')) {\n $saveSetBtn.classList.add('invalid');\n $saveSetBtn.title = 'Invalid Set Name';\n }\n else if (currentSet.ids.length === 0) {\n $saveSetBtn.classList.add('invalid');\n $saveSetBtn.title = 'No folders selected';\n }\n else {\n $saveSetBtn.classList.remove('invalid');\n $saveSetBtn.title = 'Save';\n }\n }", "function checkUnsavedChanges()\n{\n\tif(store.dirty)\n\t\t{\n\t\tif(confirm(config.messages.unsavedChangesWarning))\n\t\t\tsaveChanges();\n\t\t}\n}", "function editSubmitButtonWarning() {\n\n const hasWordWarning = $('p.word-warning').is(':visible');\n const hasSentenceWarning = $('p.sentence-warning').is(':visible');\n const hasTranslationWarning = $('p.translation-warning').is(':visible');\n\n const hasNoSynonyms = $('input.english-synonym').val().split(',').length === 0;\n const hasNoSentence = $('input.sentence').val() === '';\n const hasNoWord = $('input.word').val() === '';\n const hasNoTranslation = $('input.translation').val() === '';\n\n const shouldShowWarning = hasWordWarning\n || hasSentenceWarning\n || hasTranslationWarning\n || hasNoSynonyms\n || hasNoSentence\n || hasNoWord\n || hasNoTranslation;\n\n if (shouldShowWarning) {\n $('p.submit-warning').show();\n return true;\n } else {\n $('p.submit-warning').hide();\n return false;\n }\n }", "function editError(){\n\tdisplayMessage(\"There has been an error submitting your art.\\nSave your work locally and try again later.\",\n\t\t removePrompt(),removePrompt(),false,false);\n}", "function validateSaved() {\n\t\t//Getting the save status\n\t\tvar status = productKey.getSaveStatus();\n\t\t//Visually displaying the save status\n\t\tVALIDATION_STATUS_HANDLE.innerHTML = status;\n\n\t\t//Toggling the save status\n\t\tif (productKey.isSaved()) {\n\t\t\t//Toggle the saved state from true to false\n\t\t\tproductKey.setSaved(false);\n\t\t} else {\n\t\t\t//Toggle the saved state from false to true\n\t\t\tproductKey.setSaved(true);\n\t\t}\n\n\t}", "renderSaveSuccessful()\n\t{\n\n\t\tif(this.state.isSaveSuccessful)\n\t\t{\n\n\t\t\treturn(<Message positive>\n\t\t\t\t\t\t<Message.Header>Successfully added an edit to the corpus!</Message.Header>\n\t\t\t\t </Message>)\n\n\t\t}\n\n\t}", "function shouldShowFromDefaultWarning() {\n return $scope.item.from_default && $scope.getCurrentTextValue() == $scope.values.saved;\n }", "function save() {\n for (var groupIndex in $scope.groups.groupList) {\n for (var studentIndex in $scope.groups.groupList[groupIndex].studentList) {\n // Student has been selected if any of Select All, Course group, or student itself has been selected. \n if ($scope.groups.groupList[groupIndex]._selected || $scope.groups.groupList[groupIndex].studentList[studentIndex]._selected) {\n StudentOptionEntry.create({\n studentId: $scope.groups.groupList[groupIndex].studentList[studentIndex].id,\n examOptionId: entity.customExam.examOptionId,\n statusId: 1,\n ediStatusId: 8,\n resit: 0,\n private: 0\n }).then(function(response) {}, function(response) {});\n }\n }\n }\n\n $uibModalInstance.close();\n }", "function checkFormState (){\n\t\tif (formModified && showUnsavedChangesPopup)\n\t\t\treturn 'There are unsaved changes';\n\t}", "function errorConfirm() {\n vm.onErrorConfirm();\n }", "updateErrors() {\n $('#rbro_style_panel .rbroFormRow').removeClass('rbroError');\n $('#rbro_style_panel .rbroErrorMessage').text('');\n let selectedObj = this.rb.getDataObject(this.selectedObjId);\n if (selectedObj !== null) {\n for (let error of selectedObj.getErrors()) {}\n }\n }", "function displayError(res) {\n if (res !== false) {\n var ok = res[0];\n var line = res[1];\n var err = res[2];\n if (!ok) {\n marker = editor.getSession().\n highlightLines(Math.max(0, line - 1),\n Math.max(0, line - 1));\n $(\"#editor-log\").html(\"Line \" + res[1] + \", \" + res[2]);\n // $(\"#editor-submit\").prop(\"disabled\", true);\n }\n else {\n $(\"#editor-log\").html(\"\");\n // $(\"#editor-submit\").prop(\"disabled\", false);\n }\n }\n }", "updateErrors() {\n $('#rbro_page_break_element_panel .rbroFormRow').removeClass('rbroError');\n $('#rbro_page_break_element_panel .rbroErrorMessage').text('');\n let selectedObj = this.rb.getDataObject(this.selectedObjId);\n if (selectedObj !== null) {\n for (let error of selectedObj.getErrors()) {}\n }\n }", "function operationComplete() {\n if ((successfulOperations.length + failedOperations.length) >= totalOperations) {\n saveComplete();\n }\n }", "function save(){\n if(checkFormat()){\n alert(\"Add Complete!\");\n insertRow();\n //reset form after insert (jq to dom)\n $(\".addForm\")[0].reset();\n closeDialog();\n }\n}", "function editSave() {\n if (!inputValid()) return;\n vm.editObj.id = -3;\n server.addBuoy(vm.editObj).then(function(res) {\n queryBuoys();\n queryBuoyInstances();\n gui.alertSuccess('Buoy added.');\n }, function(res) {\n gui.alertBadResponse(res);\n vm.buoys.splice(vm.buoys.length - 1, 1);\n });\n vm.editId = -1;\n }", "function showProjectLoadTypeFailDialogue() {\n showDialog({\n title: 'WARNING: Incorrect project type',\n text: 'Reselect a <b>DSS-Risk-Analysis-</b>&lt;ProjectTitle&gt;.json file:\\nCurrent project unchanged'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}", "saveMultiGrid(fobj) {\n // rework this!!!\n // webutil.createAlert('Landmarks loaded from ' +filename+' numpoints='+grid.getnumpoints());\n \n this.centerOnElectrode();\n fobj=bisgenericio.getFixedSaveFileName(fobj,this.internal.multigrid[this.internal.currentgridindex].filename);\n this.internal.multigrid.save(fobj);\n return false;\n }", "function TKR_HandleBulkEdit() {\n var selectedIssueRefs = GetSelectedIssuesRefs();\n var selectedLocalIDs = [];\n for(var i = 0; i < selectedIssueRefs.length; i++) {\n selectedLocalIDs.push(selectedIssueRefs[i]['id']);\n }\n if (selectedLocalIDs.length > 0) {\n var selectedLocalIDString = selectedLocalIDs.join(',');\n var url = 'bulkedit?ids=' + selectedLocalIDString;\n TKR_go(url + _ctxArgs);\n } else {\n alert('Please select some issues to edit');\n }\n}", "function ModConfirmSave(mode) {\n console.log(\" --- ModConfirmSave --- \");\n console.log(\"mode: \", mode);\n console.log(\"mod_dict: \", mod_dict);\n\n // mode : \"save\" \"reject\", \"remove\"\n// --- Upload Changes\n if (mod_dict.mode === \"check_birthcountry\"){\n const may_edit = (permit_dict.permit_crud && permit_dict.requsr_same_school);\n if(may_edit){\n const upload_dict = {\n mode: mod_dict.mode,\n table: \"student\"\n };\n UploadChanges(upload_dict, urls.url_change_birthcountry);\n };\n\n } else if([\"prelim_ex5\", \"prelim_ex6\", \"overview\"].includes(mod_dict.mode)){\n const el_modconfirm_link = document.getElementById(\"id_modconfirm_link\");\n if (el_modconfirm_link) {\n el_modconfirm_link.click();\n // show loader\n el_confirm_loader.classList.remove(cls_visible_hide)\n };\n\n } else if(mod_dict.mode === \"withdrawn\"){\n const may_edit = (permit_dict.permit_crud && permit_dict.requsr_same_school);\n if(may_edit){\n const upload_dict = {\n mode: mod_dict.mode,\n table: \"student\",\n student_pk: mod_dict.student_pk,\n withdrawn: mod_dict.withdrawn\n };\n UploadChanges(upload_dict, urls.url_student_upload);\n // --- change icon, before uploading\n // when validation on server side fails, the old value is reset by RefreshDataRowItem PR2022-05-27\n // updated_studsubj_rows must contain ie err_fields: ['has_reex']\n add_or_remove_class(mod_dict.el_input, \"tickmark_1_2\", mod_dict.withdrawn, \"tickmark_0_0\");\n };\n\n } else if(mod_dict.mode === \"gl_status\"){\n const may_edit = (permit_dict.permit_approve_result && permit_dict.requsr_role_insp);\n if (permit_dict.permit_approve_result && permit_dict.requsr_role_insp){\n\n const gl_status = (mode === \"remove\") ? 0 : (mode === \"reject\") ? 2 : 1;\n const upload_dict = {\n mode: mod_dict.mode,\n table: \"student\",\n //student_pk: mod_dict.student_pk,\n student_pk_list: mod_dict.student_pk_list,\n gl_status: gl_status\n };\n UploadChanges(upload_dict, urls.url_approve_result);\n // --- change icon, before uploading\n // when validation on server side fails, the old value is reset by RefreshDataRowItem PR2022-05-27\n // updated_studsubj_rows must contain ie err_fields: ['has_reex']\n add_or_remove_class(mod_dict.el_input, \"tickmark_1_2\", mod_dict.withdrawn, \"tickmark_0_0\");\n };\n };\n// --- hide modal\n $(\"#id_mod_confirm\").modal(\"hide\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This parseJson function takes a json file and extract the alertId, alertType, assetId, siteId, comments, and statusType. Then connect to a database and: If the alertId does not exist in the database and the statusType is 'Initiate', insert it with the fields listed above. If the alertId is already in the database and the statusType is not 'Initiate', update the current alertId to show the new status followed by the new comments. If any error occurs, show the log in the console and write it to the log file. Also log any JSON that comes through into the log file. alertId : primary key in staging area. Uniquely identifies alerts. alertType : specifies what kind of alert is being created. assetId : identifies machine that the alert is addressing. siteId : the location of the machine. comments: anything extra that the user wants to include about the alert. statusType: whether the alert is being initiated or updated.
function parseJson (inJson) { var alertId = inJson['alert']['id']; var alertType = inJson['alert']['alertDefinition']['alertType']['name']; var assetId = 'TEST_ASSET_ID'; var siteId = inJson['alert']['alertDefinition']['locationId']; var comments = inJson['alert']['alertComments'][0]['alertComment']; var statusType = inJson['type']; var timeStamp = inJson['timestamp']; return [timeStamp, alertId, alertType, assetId, siteId, comments, statusType]; //alertId - prime key in eandon //siteId - must start with "M00" }
[ "function handleFile(err, data){\n if(err){\n console.log(err);\n }\n\n obj = JSON.parse(data);\n console.log(\"JSON FILE: \"+ obj.main.temp);\n }", "function handleJson(rawData) {\r\n\tparsed = JSON.parse(rawData).data;\r\n\tsortIOSAndroid(parsed);\r\n\tparsedIOS.forEach(app => {\r\n\t\taddDistinct(\"IOS\", app.identifier ? app.identifier : \"missing\");\r\n\t});\r\n\tiOSPackages.forEach(packageName => {\r\n\t\tvar maxCounter = 0;\r\n\t\tparsedIOS.forEach(app => {\r\n\t\t\tif (app.identifier == packageName) {\r\n\t\t\t\tapp.counter > maxCounter ? maxCounter = app.counter : null;\r\n\t\t\t};\r\n\t\t});\r\n\t\tparsedIOS.forEach(app => {\r\n\t\t\tif (app.identifier == packageName && app.counter < maxCounter - maxAllowedApps) {\r\n\t\t\t\tappID = app.id;\r\n\t\t\t\tappIdentifier = app.identifier;\r\n\t\t\t\tvar postString = `{\"id\": \"${appID}\", \"identifier\": \"${appIdentifier}\"}`;\r\n\t\t\t\tconsole.log(postString + \"FROM LOOP\");\r\n\t\t\t\tpostStringArr.push(postString);\r\n\t\t\t};\r\n\t\t});\r\n\t});\r\n\tparsedAndroid.forEach(app => {\r\n\t\taddDistinct(\"Android\", app.identifier ? app.identifier : \"missing\");\r\n\t});\r\n\tandroidPackages.forEach(packageName => {\r\n\t\tvar maxCounter = 0;\r\n\t\tparsedAndroid.forEach(app => {\r\n\t\t\tif (app.identifier == packageName) {\r\n\t\t\t\tapp.counter > maxCounter ? maxCounter = app.counter : null;\r\n\t\t\t};\r\n\t\t});\r\n\t\tparsedAndroid.forEach(app => {\r\n\t\t\tif (app.identifier == packageName && app.counter < maxCounter - maxAllowedApps) {\r\n\t\t\t\tappID = app.id;\r\n\t\t\t\tappIdentifier = app.identifier;\r\n\t\t\t\tvar postString = `{\"id\": \"${appID}\", \"identifier\": \"${appIdentifier}\"}`;\r\n\t\t\t\tconsole.log(postString + \"FROM LOOP\");\r\n\t\t\t\tpostStringArr.push(postString);\r\n\t\t\t};\r\n\t\t});\r\n\t});\r\n\tsendDeletePosts();\r\n}", "function getAlertFile(id) {\n return alertDir + '/' + id + '.json';\n}", "function handleJsonImport(evt) {\r\n\t\t// Loop through the FileList and render image files as thumbnails.\r\n\t\t//project = new Project();\r\n\t\tvar files = evt.target.files; // FileList object\r\n\t\tfor (var i = 0, f; f = files[i]; i++) {\r\n\t\t\tvar reader = new FileReader();\r\n\t\t\treader.onload = (function(theFile) {\r\n\t\t\t\treturn function(e) {\r\n\t\t\t\t\t//console.log('handleJsonImport->'+theFile.name);\r\n\t\t\t\t\tloadImportProject(e.target.result,theFile.name);\r\n\t\t\t\t};\r\n\t\t\t})(f);\r\n\t\t\tif (i == files.length - 1)\r\n\t\t\t{\r\n\t\t\t\treader.onloadend = importProjectJsons;\r\n\t\t\t}\r\n\t\t\treader.readAsText(f, 'UTF-8');//readAsDataURL(f);//, 'UTF-8');\r\n\t\t}\r\n\t}", "function parseAudioJson() {\n fs.readFile(audioJson, 'utf8', function (err, data) {\n if (err) throw err;\n let newJson = JSON.parse(data);\n if (audio) {\n compareJson(audio, newJson);\n }\n audio = newJson;\n });\n}", "function readSingleFile(evt) { \n var f = evt.target.files[0]; //The target property is the element that has been registered for the event \n if (f) { //if the user load a readable file \n var r = new FileReader(); //The FileReader object is used to read the contents of files. It can read the content of File or Blob objects (which respectively represent a file or data).\n r.onload = function(e) { //when the object r is created, we can can read the content of the file \n var contents = e.target.result; //contents of the loaded file \n try{ \n jsonFileLoader(JSON.parse(contents)); //JSON.parse function parses a character string (contents of the file) in JSON format and constructs the JavaScript value of the object described by this string.\n }catch(error){ //if an error occurs in the try (with the JSON.parse function), the selected file isn't a json file \n alert(\"Error, this is not json file\"); //an alert modal to prevent the user that his selected file is not a JSON file. \n }\n }\n r.readAsText(f); //the JSON file will be read as text\n } else { \n alert(\"Failed to load file\"); //if the file can't be read\n }\n}", "function appendJSON(obj) {\n\n // Read in a JSON file\n var JSONfile = fs.readFileSync('Appointments.json', 'utf8');\n\n // Parse the JSON file in order to be able to edit it\n var JSONparsed = JSON.parse(JSONfile);\n\n //Geolocation\n //var address = obj.where.toString().split(' ').join('+');\n\n googleMapsClient.geocode({\n address: obj.where\n }, function(err, response) {\n if (!err) {\n //Getting the longitude and latitude object and add it to the object\n obj.coords = response.json.results[0].geometry.location;\n obj.who = parseInt(obj.who);\n obj.id = JSONparsed.appointment.length+1;\n // Add a new record into country array within the JSON file\n JSONparsed.appointment.push(obj);\n\n // Beautify the resulting JSON file\n var JSONformated = JSON.stringify(JSONparsed, null, 4);\n\n // Write the updated JSON file back to the system\n fs.writeFileSync('Appointments.json', JSONformated);\n\n // Convert the updated JSON file to XML\n var XMLformated = js2xmlparser.parse(\"appointments\", JSON.parse(JSONformated));\n\n // Write the resulting XML back to the system\n fs.writeFileSync('Appointments.xml', XMLformated);\n\n } else {console.log('Error:'+err)}\n return res.redirect('/');\n });\n }", "function json_merge() {\n var fname = process.argv[3];\n if (!fs.existsSync(fname)) { usage(\"File \"+fname+\" does not exist\"); }\n var j;\n try {\n // j = require(fname); // Does not for for files w/o .json\n var cont = fs.readFileSync(fname, 'utf8');\n j = JSON.parse(cont);\n }\n catch(ex) { usage(\"Error parsing JSON (\"+fname+\"): \"+ex); }\n if (!j) { usage(\"Error parsing JSON (\"+fname+\"), did hot get DS-handle\"); }\n //var fs = require(\"fs\");\n //var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0\n //var incont = stdinBuffer.toString();\n //console.log(incont);\n // require('split')() // was passsed to stdin.pipe()\n var sidata = \"\";\n console.error(\"Reading STDIN (if any)\\n\");\n var jin; // Declare here to have avail in --save block\n var newcont;\n process.stdin.on('data', (l) => {sidata += l; }).on(\"end\", () => {\n console.error(\"Got: \"+sidata);\n jin = JSON.parse(sidata);\n if (!jin) { usage(\"No Proper JSON from STDIN!\"); }\n console.error(JSON.stringify(jin, null, 2));\n \n // Merge\n merge(jin, j);\n newcont = JSON.stringify(j, null, 2);\n console.log(newcont);\n if (process.argv.includes(\"--save\")) {\n console.error(\"Save to '\"+fname+\"'\");\n // JSON.stringify(j, null, 2)\n fs.writeFileSync( fname, newcont, {encoding: \"utf8\"} );\n }\n\n });\n\n // Patch / merge. Internally use branch j.ansible_facts\n function merge(jin, j) {\n if (j.ansible_facts) { j = j.ansible_facts; }\n Object.keys(jin).forEach((k) => {\n // if (j[k]) { usage(\"Key \"+k+\" already in target JSON.\"); }\n console.error(\"Merging \"+k);\n j[k] = jin[k];\n });\n }\n //console.log(JSON.stringify(j, null, 2));\n //function processLine (line) {\n // console.log(line + '!')\n //}\n}", "function UpdateAlerts(Log){\n var spreadSheet = SpreadsheetApp.openById(spreadSheetID); ///Open the spreadsheet\n var alertsSheet = spreadSheet.getSheetByName(\"Alerts\"); ///Get the Settings sheet\n var settings = alertsSheet.getRange(3,1,alertsSheet.getLastRow(),1);\n var nextRow = alertsSheet.getLastRow() + 1; ///Get next row after the last row\n \n ///Add all other Header + Data pairs from the received Log JSON\n for each (var key in Object.keys(Log)){\n var match = settings.createTextFinder(key).matchEntireCell(true).findNext(); ///lookup the alert limit row for each Log key\n if(match == null){ ///If settings row does not exists\n alertsSheet.getRange(nextRow, 1).setValue(key); ///Insert key in first Key column \n var rule = SpreadsheetApp.newDataValidation().requireValueInList(['YES', 'NO']).build();\n alertsSheet.getRange(nextRow, 4).setDataValidation(rule); ///Add YES/NO options for Triggered column\n alertsSheet.getRange(nextRow, 4).setHorizontalAlignment(\"right\");\n nextRow++;\n } \n }\n}", "function validateDataFile(){\r\n var data, tmpObj;\r\n fs.readFile(path+dataFile, 'utf-8',function (err, data) {\r\n if (err) throw err;\r\n\r\n try{\r\n tmpObj=JSON.parse(data);\r\n logMsg(dataFile + ' has been verified as a valid JSON object.')\r\n }\r\n catch(e){\r\n console.log('An error has occurred: '+e.message)\r\n }\r\n });\r\n}", "function buildAlertObject(alertmessage) {\n var alert = {};\n\n alert.status = alertmessage.status;\n alert.startsAt = alertmessage.startsAt;\n alert.fingerprint = alertmessage.fingerprint;\n alert.alertname = alertmessage.labels.alertname;\n alert.severity = alertmessage.labels.severity;\n alert.message = alertmessage.annotations.message;\n\n return alert;\n}", "function loadImportProject(json, filename) {\r\n\t\tif (!tmp_storage)\r\n\t\t{\r\n\t\t\ttmp_storage = {\r\n\t\t\t\tfilenames: [],\r\n\t\t\t\tjsons: []\r\n\t\t\t};\r\n\t\t}\r\n\t\t//var length = tmp_storage.filenames.length;\r\n\t\ttmp_storage.filenames[tmp_storage.filenames.length] = filename;\r\n\t\ttmp_storage.jsons[tmp_storage.jsons.length] = json;\r\n\r\n\t\t//console.log('loadImportProject imported '+filename+' '+tmp_storage.jsons.length);\r\n\t}", "function uploadLocalJsonCollectionToDB(client, dataBaseName, collectionName) {\n\t\t\n\t\t//////////////////////////// Read json by nodejs fs (start) ////////////////////\n\t\t// var jsonObject;\n\t\tfs.readFile('db/sportsDB.json', 'utf8', function (err, data) {\n\t\tif (err) {\n\t\t\tconsole.error(\"Unable to read the json file\");\n\t\t\tthrow err;\n\t\t}\n\t\tconsole.error(\"Read the local json successfully\");\n\t\tconst jsonObject = JSON.parse(data);\n\t\tconsole.log(jsonObject);\n\t\tcreateMultipleDocuments(client, dataBaseName, collectionName, [jsonObject]);\n\t\t});\n\t\t//////////////////////////// Read json by nodejs fs (end) //////////////////////\n\t}", "function uploadJSON() {\r\n\r\n}", "function loadJSON() {\n var client = new XMLHttpRequest();\n client.open(\"GET\", databasefilename, true);\n client.onreadystatechange = function () { //callback\n if (client.readyState === 4) {\n if (client.status === 200 || client.status === 0) {\n database_obj = JSON.parse(client.responseText);\n processInput();\n }\n }\n };\n client.send();\n }", "createOne (json: jsonUpdate, callback: mixed) {\n\t\tlet val = [json.headline, json.category, json.contents, json.picture, json.importance];\n\t\tsuper.query(\n\t\t\t\"insert into NewsArticle (headline,category,contents, picture, importance) values (?,?,?,?,?)\",\n\t\t\tval,\n\t\t\tcallback\n\t\t);\n\t}", "function jsonArray(mdJson, jASchema ) {\r\n\t\r\n var newArray =[];\r\n\r\n try {\r\n\r\n\t\tif ( mdJson.length > 0 ) {\r\n\r\n\t for (var i = 0; i < mdJson.length; i++) {\r\n\r\n\t \t// recursively handle objects in array\r\n\r\n\t \tif ( typeof(jASchema) !== \"undefined\" && typeof(jASchema)==\"object\" ) {\r\n\t \t \tvar tjO = {};\r\n\t \t \tvar subData = mdJson[i];\r\n\t \t \tvar trail;\r\n\t \t \ttjO = SubObjectBuilder(subData, trail, jASchema, i); \r\n\t \t \ttjO.array_index = i;\r\n\t \t \tif ( typeof(mdJson[i].datatype) !== \"validationonly\" ) {\r\n\t \t \t\tif ( typeof(mdJson[i].validation) !== \"undefined\" ) {\r\n\t \t \t\t\ttjO.validateonly = mdJson[i].validation.toString();\r\n\t \t \t\t} else {\r\n\t \t \t\t\ttjO.validateonly = \"true\";\r\n\t \t \t\t}\r\n\t \t \t} \r\n\t \t \tnewArray.push(tjO);\r\n\t \t} else {\r\n\t \t \t var tjs = {};\r\n\t \t \ttjs = JSON.parse(JSON.stringify(jASchema)); // cheap copy\r\n\t \ttjs.value = mdJson[i].name;\r\n\t \ttjs.array_index = i; \r\n\r\n\t \t \tif ( typeof(mdJson[i].datatype) !== \"validationonly\" ) {\r\n\t \t \t\tif ( typeof(mdJson[i].validation) !== \"undefined\" ) {\r\n\t \t \t\t\ttjO.validateonly = mdJson[i].validation;\r\n\t \t \t\t} else {\r\n\t \t \t\t\ttjO.validateonly = \"true\";\r\n\t \t \t\t}\r\n\t \t \t}\r\n\t\t\t\t \tnewArray.push(tjs);\r\n\t \t}\r\n\t \r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t// Build empty array item\r\n\t\t newArray.push(jASchema);\r\n\t\t newArray[i].name = \"default\";\r\n\t\t\tnewArray[i].array_index = 0;\r\n\t\t}\r\n\r\n\t} catch (e) {\r\n \tconsole.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> JSON Array Error ' + JSON.stringify(e) );\r\n\t}\r\n\r\n\treturn newArray;\r\n}", "function readFileHandler(err, data) {\n\t\tlogger.debug('begin readFileHandler');\n\n\t\tif (err) logger.warn(\"readFileHanlder error: \", err);\n\n\t\ttry {\n\t\t\tcontent = JSON.parse(data);\n\t\t} catch (exc) {\n\t\t\tlogger.error('JSON.parse failed: ', exc);\n\t\t\treturn;\n\t\t}\n\t\tgetAuthentication();\n\t}", "function f_ProcessJSONData_Main(frame){\n\t//\tlog AppID received\t\t\t\n\t//f_RADOME_log(frame.AppID);\n\t//Check AppID and do what fit with that\n\tvar id = parseInt(frame.AppID);\n\tswitch(id) // inspect id found to dispatch the appropriate processing\n\t{\n\t\tcase APP_ID.LIST:\n\t\t\t// load JSON data (into 'frame') to update and fill the select '$(he_SelectRADOMECmds)'\n\t\t\tf_GUI_Update_Select(frame, $(he_SelectRADOMECmds));\t\n\t\t\tbreak;\n\t\t\n\t\tcase APP_ID.VERSION:\n\t\t\t// load data json to populate the angular model \"$scope.versionInfo\" \n\t\t\tf_RADOME_log(\"load data json to populate the angular model $scope.versionInfo\");\n\t\t\tf_GUI_Update_Version(frame);\t\n\t\t\tbreak;\t\n\t\t\t\n\t\t// if process is \"CAN\"\n\t\tcase APP_ID.CAN1:\n\t\tcase APP_ID.CAN2:\n\t\tcase APP_ID.CAN3:\n\t\tcase APP_ID.CAN4:\n\t\tcase APP_ID.CAN5:\n\t\t\t//Update GUI for the 'gauge' element\n\t\t\tf_ProcessJSONData_CAN(frame);\t\n\t\t\t// TO DO : simulate click on concerned tab menu\n\t\t\t//$(\"#menu2\").click();\n\t\t\tbreak;\n\n\t\tcase APP_ID.VIDEO:\n\t\t\t// Update GUI elements concerned \n\t\t\t\n\t\t\t// TO DO : simulate click on concerned tab menu\n\t\t\t//$(\"#menu3\").click();\n\t\t\tbreak;\n\t\t\n\t\tcase APP_ID.AUDIO:\n\t\t\t// Update GUI elements concerned \n\t\t\tf_GUI_Update_Select(frame, $(he_SelectRADOMEAudio));\t\n\t\t\t// TO DO : simulate click on concerned tab menu\n\t\t\t//$(\"#menu4\").click();\n\t\t\tbreak;\n\t\t\n\t\tcase APP_ID.NAVIG:\n\t\t\t// Update GUI elements concerned \n\t\t\t// TO DO : simulate click on concerned tab menu\n\t\t\t//$(\"#menu5\").click();\n\t\t\n\t\t\tf_RADOME_log(\"load data json to populate the angular model $scope.RADOME_NavigInfo\");\n\t\t\tf_GUI_Update_Nav(frame);\t\n\t\t\tbreak;\n\n\t\tcase APP_ID.DEMO:\n\t\t\t// load data json to populate the angular model \"$scope.RADOME_DemoInfo\" \n\t\t\tf_RADOME_log(\"load data json to populate the angular model $scope.RADOME_DemoInfo\");\n\t\t\tf_GUI_Update_Demo(frame);\t\n\t\t\tbreak;\t\n\t\t\t\n\t\tdefault:\n\t\t\t// unknown id\n\t\t\tf_RADOME_log(\"Unknown APP ID found : \" + frame.AppID);\n\t\t\tbreak;\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
region Sucessful responses Responds as Accepted with status code 202 and optional data.
accepted(res, data) { this.send(res, data, 202); }
[ "static getSuccessCodes() {\n return [\n 200\n ];\n }", "ensureSuccessStatusCode() { \n if (!this.isSuccessStatusCode) {\n throw new Error(`Request didn't finished with success. Status code: ${this.statusCode}. Reason phrase: ${this.reasonPhrase}`);\n } \n }", "ok(res, data) {\r\n this.send(res, data, 200);\r\n }", "function responseValid(response, data) {\n\tmessage = new Response();\n\tmessage.status = \"valid\";\n\tmessage.data = data;\n\n\tresponse.writeHead(200, {\"Content-Type\": \"text/plain\"});\n\tresponse.write(JSON.stringify(message));\n\tresponse.end();\n}", "validateResponse (data) {\n\t\tAssert.deepEqual(data, {}, 'request should return empty response');\n\t}", "function successResponse()\n{\n // Finished\n return newResponse(true);\n}", "toServerResponse() {\n // Process the body\n const body = this._getBody();\n // If there is a response type, set the content type header\n this._setContentType();\n // If there is no body and no content type and no set length, then set the\n // content length to 0\n if (!(body ||\n this.headers.has(\"Content-Type\") ||\n this.headers.has(\"Content-Length\"))) {\n this.headers.append(\"Content-Length\", \"0\");\n }\n return {\n status: this.status || (body ? deps_ts_5.Status.OK : deps_ts_5.Status.NotFound),\n body,\n headers: this.headers\n };\n }", "function successfulCallbackResponse (response) {\n var statusCode = response.statusCode\n return statusCode >= 200 && statusCode < 300\n}", "function wrapResponse(data) {\n return {\n \"meta\": {\n \"version\": \"0.1.1\",\n \"status\": \"ok\",\n \"message\": \"Everything executed as expected.\"\n },\n \"response\": data\n }\n}", "function success() {\n process.exit(ExitCode.Success);\n}", "function createResponse(status, body, contentType) {\n\n\t//remember that the response needs a whole empty line between the headers\n\t//and the body \n\treturn `HTTP/1.1 ${status} OK\\r\\nContent-Type: `+ contentType +`\\r\\n\\r\\n${body}`;\n\n}", "function errorResponse(exception)\n{\n // Finished\n return newResponse(false, true, exception);\n}", "function handleEmptyRequest() {\r\n const code = 400;\r\n const response = new Problem_1.Problem(code, \"/probs/properties-not-found\", \"Request body cannot be empty\", \"Request body cannot be empty\");\r\n Logger_1.logger.info(JSON.stringify(response));\r\n return response;\r\n }", "function sendCode(code,response,message) {\n response.status(code);\n response.send(message);\n}", "noContent(res, data) {\r\n this.send(res, data, 204);\r\n }", "function is_accepted(response) {\n if (response.token !== undefined) {\n return true;\n }\n\n if (response.success !== undefined && response.success == true) {\n return true;\n }\n return false;\n}", "function resultadosPost(status) {\n let mensaje = \"\";\n if (status == 201) {\n mensaje = \"Auditorio Guardado Con exito!\";\n } else if (status == 204) {\n mensaje = \"Este registro ya existe\";\n }\n alert(mensaje);\n}", "function handleCreateActivityResponse(status) {\n\tif (status.errCode === 1){\n window.location = '/?methodType=createActivity&errCode=' + status.errCode;\n } else if (status.errCode === 6){\n //missing required parameter\n var errMsg = 'Error: ' + status.message;\n if (status.message == 'null time1') {\n \terrMsg = 'Error: Null Start Time';\n } else if (status.message == 'null time2') {\n \terrMsg = 'Error: Null End Time';\n }\n $('#missingParams').html(errMsg);\n $('#missingParams').show();\n $('body').scrollTop(0);\n //window.location = '/#create_activity_page?errCode=' + status.errCode;\n }\n\t// window.location = '/';\n}", "function storeRespond(method, url, data, headers, params) {\n\n\t\t\t// Get a random header\n\t\t\tvar header = randomHeader();\n\n // If the result will be 200, execute the operation\n\t\t\tif(header == 200) {\n\t\t\t\tdata = JSON.parse(data);\n // Assisgn beer id - override if inserted\n data.id = beers.length;\n\n // Insert the new beer\n beers.push( data);\n\n // Return the success header\n return [header, data];\n }\n\n\t\t\t// Return the error header\n\t\t\treturn [header, {error:'Error storing the beer'}];\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates product prices based on line item quantities.
function calculateProductPrices (basket) { // iterate all product line items of the basket and set prices var productLineItems = basket.getAllProductLineItems().iterator(); while (productLineItems.hasNext()) { var productLineItem = productLineItems.next(); var product = productLineItem.product; // handle option line items if (productLineItem.optionProductLineItem) { // for bonus option line items, we do not update the price // the price is set to 0.0 by the promotion engine if (!productLineItem.bonusProductLineItem) { productLineItem.updateOptionPrice(); } // handle bundle line items, but only if they're not a bonus } else if (productLineItem.bundledProductLineItem) { // no price is set for bundled product line items // handle bonus line items // the promotion engine set the price of a bonus product to 0.0 // we update this price here to the actual product price just to // provide the total customer savings in the storefront // we have to update the product price as well as the bonus adjustment } else if (productLineItem.bonusProductLineItem && product !== null) { var price = product.priceModel.price; var adjustedPrice = productLineItem.adjustedPrice; productLineItem.setPriceValue(price.valueOrNull); // get the product quantity var quantity2 = productLineItem.quantity; // we assume that a bonus line item has only one price adjustment var adjustments = productLineItem.priceAdjustments; if (!adjustments.isEmpty()) { var adjustment = adjustments.iterator().next(); var adjustmentPrice = price.multiply(quantity2.value).multiply(-1.0).add(adjustedPrice); adjustment.setPriceValue(adjustmentPrice.valueOrNull); } // handle product line items unrelated to product } else if (product === null && productLineItem.catalogProduct) { productLineItem.setPriceValue(null); // handle normal product line items } else { productLineItem.setPriceValue(productLineItem.basePrice.valueOrNull); } } }
[ "function RefreshCost()\n{\n var TotalQuantity = 0;\n var Total = 0;\n var ThisItemTotal = 0;\n var LineCostItterator = document.getElementsByTagName(\"input\");\n for(var itt=0;itt<LineCostItterator.length;itt++)\n {\n // check if the ID starts with LINECOST\n if(LineCostItterator[itt].id.indexOf('LINECOST') == 0)\n {\n ThisItemTotal = 0;\n var thisID = LineCostItterator[itt].id.substr(8,LineCostItterator[itt].id.length-8);\n // now grab the line item cost value\n var ThisCost = LineCostItterator[itt].value;\n var ThisQTY = GetLineItemQuantity(thisID);\n \n var ThisUofM = GetLineItemUofM(thisID);\n TotalQuantity += ThisQTY * ThisUofM;\n Total += ((ThisQTY * ThisUofM ) * ThisCost);\n // now calculate the quantity for line items total\n document.getElementById('LINEEXTDCOST' + thisID).innerHTML = \"$\" + (ThisQTY * ThisUofM * ThisCost).toFixed(2); \n }\n } \n document.getElementById('EXTDCOST').innerHTML = \"$\" + Total.toFixed(2);\n if(TotalQuantity<OrderMinimum)\n {\n document.getElementById('ordererror').style.display = ''; \n }\n else\n {\n document.getElementById('ordererror').style.display = 'none'; \n }\n}", "function computeProductPriceComponent(inputProductData) {\n\n let extractedProductPrice = inputProductData.price.substring(1);\n let productPriceAsFloat = Number.parseFloat(extractedProductPrice);\n return (productPriceAsFloat * inputProductData.orderedQuantity);\n\n}", "function updateAislePrice(item1, item2, item3, item4) {\n updateItemPrice(item1);\n updateItemPrice(item2);\n updateItemPrice(item3);\n updateItemPrice(item4);\n}", "function get_item_prices(rarity_counts, price_dice) {\n// !!!\n}", "function calculateFinalPrice(product, unitPrice, quantity) {\n const productObj = newSlab.PRODUCTS.find(p => p.products.indexOf(product.toUpperCase()) > -1);\n if (productObj) {\n const gstApplicable = calculateGST(productObj.gstId, unitPrice, quantity);\n return (quantity * unitPrice) + gstApplicable;\n }\n else {\n throw (\"Product not found\");\n }\n\n}", "async function _extract_related_product_variant_ids (products, line_item_variants){\n let all_product_variants = [];\n \n for (let i = 0; i < products.length; i++){\n for (let j = 0; j < line_item_variants.length; j++){\n if (products[i].variant_ids.includes(line_item_variants[j])){\n all_product_variants.push(products[i].variant_ids);\n }\n }\n }\n \n return all_product_variants;\n}", "priceCalc(){\n var that = this;\n var equipmetCost = 0;\n var tempPrice = this.phoneStorage.filter(function(el){\n if(el.storage == that.selectedStorage ){\n return el;\n }\n });\n this.selectedEquipment.forEach(function(el){\n equipmetCost += Number(el);\n });\n this.total = equipmetCost + tempPrice[0].price - this.selectedRate;\n\n }", "function drawLinePrice() {\n\t\t\tlet svgHeight = 500;\n\n\t\t\tvar margin = {top: 10, right: 20, bottom: 50, left: 60}\n\t\t\t , width = svgWidth - margin.left - margin.right // Use the window's width \n\t\t\t , height = svgHeight - margin.top - margin.bottom;\n\n\t\t\tlet svg = d3.select(\"svg#line-price\")\n\t\t\t\t\t\t\t.attr(\"width\", svgWidth)\n\t\t\t\t\t\t\t.attr(\"height\", svgHeight)\n\t\t\t\t\t\t\t.attr(\"viewBox\", \"0 0 \" + svgWidth + \" \" + svgHeight);\n\n\t\t\tvar g = svg.append(\"g\")\n\t\t\t\t\t.attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n\t\t\tlet values = [];\n\n\t\t\tfor (let i = 2015; i < 2021; i++) {\n\t\t\t\tvalues.push({\n\t\t\t\t\tdate: i,\n\t\t\t\t\tvalue: price[i]\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet xScale = d3.scaleBand().range([0, width]);\n\n\t\t\txScale.domain(values.map(function(d) {\n\t\t\t\treturn d[\"date\"];\n\t\t\t}));\n\n\t\t\tlet yScale = d3.scaleLinear().range([height, 0]);\n\n\t\t\tyScale.domain([d3.min(values, function(d) { return d.value; }), d3.max(values, function(d) { return d.value; })]);\n\n\t\t\tvar line = d3.line()\n\t\t\t\t.x(function(d) { return xScale(d.date); }) // set the x values for the line generator\n\t\t\t\t.y(function(d) { return yScale(d.value); }) // set the y values for the line generator\n\n\t\t\tlet xAxis = g.append(\"g\")\n\t\t\t\t.attr(\"transform\", \"translate(0,\" + height + \")\")\n\t\t\t\t.call(d3.axisBottom(xScale))\n\t\t\t\t.attr(\"class\", \"x-axis\")\n\t\t\t\t.append(\"text\")\n\t\t\t\t.attr(\"class\", \"label\")\n\t\t\t\t.attr(\"y\", 40)\n\t\t\t\t.attr(\"x\", width)\n\t\t\t\t.attr(\"text-anchor\", \"end\")\n\t\t\t\t.attr(\"stroke\", \"#2d3666\")\n\t\t\t\t.text(\"Year\");\n\n\t\t\tlet yAxis = g.append(\"g\")\n\t\t\t\t.call(d3.axisLeft(yScale).tickFormat(function(d){\n\t\t\t\t\tif (d >= 1000000) {\n\t\t\t\t\t\treturn d / 1000000 + \"M\";\n\t\t\t\t\t} else if (d >= 1000) {\n\t\t\t\t\t\treturn d / 1000 + \"K\";\n\t\t\t\t\t} else if (d < 1000) {\n\t\t\t\t\t\treturn d;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.ticks(10))\n\t\t\t\t.attr(\"class\", \"y-axis\")\n\t\t\t\t.append(\"text\")\n\t\t\t\t.attr(\"transform\", \"rotate(-90)\")\n\t\t\t\t.attr(\"y\", -50)\n\t\t\t\t.attr(\"text-anchor\", \"end\")\n\t\t\t\t.attr(\"stroke\", \"#2d3666\")\n\t\t\t\t.attr(\"class\", \"label\")\n\t\t\t\t.text(\"Average Home Price\");\n\n\t\t\tg.append(\"path\")\n\t\t\t\t.datum(values) // 10. Binds data to the line \n\t\t\t\t.attr(\"class\", \"line\") // Assign a class for styling \n\t\t\t\t.attr('fill', 'none')\n\t\t\t\t.attr('stroke', colorMain)\n\t\t\t\t.attr('stroke-width', 1.5)\n\t\t\t\t.attr('d', line);\n\n\t\t\td3.select(\"div.line-price\").style(\"display\", \"none\");\n\t\t}", "function getTotalPrice() {\n var totalPrice = 0;\n _.each(createSaleCtrl.saleProducts, function(product) {\n totalPrice += product.price*createSaleCtrl.bought[product.barCode];\n });\n createSaleCtrl.totalPrice = totalPrice;\n }", "function getPriceValue(){\n var totalIngredientsPrice = 0;\n // get ingredients from panel price\n ingredients = updateIngredients();\n\n for (var i = 0; i < ingredients.length; i++) {\n var ingredient =$(ingredients[i]).html().split(\" \");\n var ingredientPrice = parseInt(ingredient[0].replace(\"$\", \"\"));\n console.log(ingredient);\n console.log(ingredientPrice);\n totalIngredientsPrice += ingredientPrice;\n }\n console.log(totalIngredientsPrice);\n return totalIngredientsPrice;\n}", "function updateCartItems(){\n\tvar totalItems = 0;\n\tvar productTotal = 0;\n\t$('.numbers :input').each(function(){\n\t\tproductTotal += getPrice($(this).attr('id'),parseInt($(this).val(), 10));\n\t\ttotalItems += parseInt($(this).val(), 10);\n\t});\n\t$('#total').html('$' + productTotal.toFixed(2));\n\t$('#cart').html('<img src=\"images/cart.svg\" alt=\"cart\" />' + totalItems);\n\t$('#sidecart').html('<img src=\"images/cart.svg\" alt=\"cart\" />' + totalItems);\n}", "verifyItemTotalPrice(productsDetails) {\n let itemTotalPrice = 0.0;\n for (let i = 0; i < productsDetails.length; i++) {\n itemTotalPrice += parseFloat(this.productPrices[i].getText().replace('$', ''));\n }\n expectChai(itemTotalPrice.toString()).to.equal(this.itemTotalPrice.getText().replace('Item total: $', ''));\n }", "function getpsPrice(product) {\n\n let $prod = $(product);\n let qty = $prod.find(\"option:selected\").data(\"qty\");\n let pprice_to = Number($prod.find(\"option:selected\").data(\"pprice\"));\n let pprice = pprice_to.toFixed(2);\n\n let sprice_to = Number($prod.find(\"option:selected\").data(\"sprice\"));\n let sprice = sprice_to.toFixed(2);\n if (pprice === \"\" || sprice === \"\" || pprice === \"0.00\" || sprice === \"0.00\") {\n\n $('input[name=\"u_price\"]').val(\"\");\n $('input[name=\"s_price\"]').val(\"\");\n } else {\n $('input[name=\"u_price\"]').val(pprice);\n $('input[name=\"s_price\"]').val(sprice);\n $('input[name=\"pquantity\"]').val(1);\n $('input[name=\"discount\"]').val(0);\n\n }\n // For Show Quantity of Purchase Goods\n if ($(\"#product\").val() === \"\")\n {\n $(\"#qa\").html(\"\");\n }\n else {\n\n\n $(\"#qa\").html(\"{<b> \" + qty + \" </b>}\");\n $(\"#quantity\").prop(\"max\", qty);\n\n\n }\n}", "function getMaterialsPriceQuery(item_id) {\n return `SELECT SUM(price*quantity) AS total_material_price FROM Materials \\\n\t\t \t\t\tINNER JOIN ItemsMaterials \\\n\t\t\t\t\tON Materials.material_id = ItemsMaterials.material_id \\\n\t\t\t\t\tWHERE ItemsMaterials.item_id=${item_id}`;\n}", "function calculate_price(vm_type){\n\n\t\tvar ID_SELECTOR = \"#\";\n\t\tvar CURRENCY = \"CHF\";\n\t\tvar final_price_selector = ID_SELECTOR.concat(vm_type.concat('-final-price'));\n\t\tvar final_price_input_selector = final_price_selector.concat('-input');\n\t\tvar core_selector = ID_SELECTOR.concat(vm_type.concat('-cores'));\n\t\tvar memory_selector = ID_SELECTOR.concat(vm_type.concat('-memory'));\n\t\tvar disk_size_selector = ID_SELECTOR.concat(vm_type.concat('-disk_space'));\n\n\t\t//Get vm type prices\n\t\tvar cores = $(core_selector).val();\n\t\tvar memory = $(memory_selector).val();\n\t\tvar disk_size = $(disk_size_selector).val();\n\t\tvar pricingData = eval(window.VMTypesData);\n\t\tvar company_prices = _.head(_.filter(pricingData, {hosting_company: vm_type}));\n\n\t\t//Calculate final price\n\t\tvar price = company_prices.base_price;\n\t\t\tprice += company_prices.core_price*cores;\n\t\t\tprice += company_prices.memory_price*memory;\n\t\t\tprice += company_prices.disk_size_price*disk_size;\n\t\t\n\t\tconsole.log(final_price_input_selector);\n\t\t$(final_price_selector).text(price.toString().concat(CURRENCY));\n\t\t$(final_price_input_selector).attr('value', price);\n\n\t}", "function reduceItems(item, quantity) {\n\tconnection.query(\"UPDATE products SET quantity = quantity -\"+quantity+\" WHERE id = \"+item, function(err,res) {\n\tif (err) throw err;\n\t})\n}", "function computeAndAppendTotalCartCostComponentToShoppingCart() {\n let totalCartItemCostElement = document.createElement('li');\n totalCartItemCostElement.className = 'mdl-menu__item';\n let totalCostTextContentElement = document.createElement('p');\n totalCostTextContentElement.className = 'total-cart-item-cost';\n let totalCost = 0.00;\n\n Object.values(currentShoppingCartData).forEach((prodData) => {\n totalCost += computeProductPriceComponent(prodData);\n });\n\n totalCostTextContentElement.textContent = `Total : $${totalCost}`;\n\n componentHandler.upgradeElement(totalCostTextContentElement);\n totalCartItemCostElement.appendChild(totalCostTextContentElement);\n componentHandler.upgradeElement(totalCartItemCostElement);\n shoppingCartList.appendChild(totalCartItemCostElement);\n}", "calcProjectMlProduct(project) {\n var _this = this;\n var Ml_values = []; // capture Ml values from each CRITERION - calc product for final calc\n // Loop through each CRITERIA of each CATEGORY - calculate sum of Ml values from each CRITERION\n $.each(project.categories, function(index, category) {\n Ml_values.push(category.Ml);\n });\n return Ml_values.reduce(_this.getProduct);\n }", "function profit(info) {\n //return console.log((info.inventory * info.sellPrice)-(info.inventory * info.costPrice)); // 54000 gewinn - 39204\n // shorter:\n return console.log(Math.round(info.inventory * (info.sellPrice-info.costPrice))); // needs to be rounded in this case\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
moved here to simplifiy dependencies (GHC.List) data Maybe a = Nothing | Just a deriving (Eq, Ord)
function Maybe(){}
[ "function maybe_5(xs) /* forall<a> (xs : list<a>) -> maybe<a> */ {\n return (xs == null) ? Nothing : Just(xs.head);\n}", "function Maybe(value){ \n this.value = value;\n }", "function maybe_3(m, nothing) /* forall<a> (m : maybe<a>, nothing : a) -> a */ {\n return $default(m, nothing);\n}", "function jsonSearcher(data,requirement){\n var validStructure;\n var i;\n for (i=0; i < requirement.length; i++){\n if (data[requirement[i]] == null){\n console.log(\"Checking value: \" + data[requirement[i]]);\n validStructure = false;\n break;\n } else{\n validStructure = true;\n }\n return validStructure;\n }\n }", "function dnull(c){\n return c==null?'0':c;\n}", "function removeNull(data){\n data.forEach(data => {\n for (let key in data) {\n if (data[key] == '#NULL!') {\n delete data[key];\n }\n }\n });\n return data;\n}", "function nullFields()\n{\n\treturn isEmpty(\"#myPattern\") || isEmpty(\"#frameRate\");\n}", "function head_2(xs, default0) /* forall<a> (xs : list<a>, default : a) -> a */ {\n return (xs != null) ? xs.head : default0;\n}", "_getAreaZero() {\n let newArr = [];\n this.area.map(el => {\n newArr.push(...el)\n });\n\n return newArr.some(el => el === null);\n }", "function null_1(i) /* (i : int) -> null<int> */ {\n return $null(maybe_7(i));\n}", "static isNull(value) { return value === null; }", "function maybe_7(i) /* (i : int) -> maybe<int> */ {\n return ($std_core._int_eq(i,0)) ? Nothing : Just(i);\n}", "function concat_maybe(xs) /* forall<a> (xs : list<maybe<a>>) -> list<a> */ {\n return concat(map_5(xs, list_3));\n}", "function not_DASH_empty(coll) {\n return ((0 == count(coll)) ?\n null :\n coll);\n}", "function xorForMaybe(a, b) {\n var aIsSome = Maybe_1.isNotNullAndUndefined(a);\n var bIsSome = Maybe_1.isNotNullAndUndefined(b);\n if (aIsSome && !bIsSome) {\n return a;\n }\n if (!aIsSome && bIsSome) {\n return b;\n }\n // XXX: We can choose both `null` and `undefined`.\n // But we return `undefined` to sort with [Optional Chaining](https://github.com/TC39/proposal-optional-chaining)\n return undefined;\n}", "visitDatatype_null_enable(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function isUndefined(){\n return;\n}", "if (type instanceof GraphQLNonNull) {\n if (!valueAST) {\n if (type.ofType.name) {\n return [ `Expected \"${String(type.ofType.name)}!\", found null.` ];\n }\n return [ 'Expected non-null value, found null.' ];\n }\n return isValidLiteralValue(type.ofType, valueAST);\n }", "function maybe_6(b) /* (b : bool) -> maybe<()> */ {\n return (b) ? Just(_unit_) : Nothing;\n}", "function verifyTeleportDataNotEmpty(data) {\n return !jQuery.isEmptyObject(data._embedded[`city:search-results`]);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The world object contains abstract data about the world. This is essentially a singleton object that provides organization and access for other objects. World generation will likely go here if we decide to procedurally generate dungeons. / Constructor for the region (map)
function World() { var i; /* These are all the data arrays indexed by world location. * The default world is 1260x756 */ this.dirty = true; this.grid = [[],[]] /* Holds the 'symbol' for the world tile */ this.gridcol = [[],[]]; /* Holds the color assigned to the tile */ this.gridheight = [[],[]]; /* Holds the height value for the tile */ this.gridmob=[[],[]]; /* Holds direct object refernces to mobs */ this.gridobj=[[],[]]; /* Holds object references like chests/doors */ /* Contains spawn points, which generate random monsters from classes */ this.spawn_points = []; /* Buffer variable used during map edit */ this.last_height = 0; /* Procedure to pull populate the arrays above from the world data files */ this.load_map(); /* Procedure to load the spawn points */ this.init_spawn_points(); }
[ "constructor() {\n this.worldObjects = new Map();\n this.transform = mat4.create();\n }", "init() {\n this.worldMap.parseMap();\n }", "load () {\n this.world = new window.World(this.game.ressources['map'])\n }", "function worldly(world) {\n if (!exports.Worlds[world.name]) {\n log(\"######## worldly: \" + world.name);\n exports.Worlds[world.name] = new world_1.default(world);\n }\n return exports.Worlds[world.name];\n}", "function Map() {\n _classCallCheck(this, Map);\n\n this[map] = {};\n this[zoom] = 16;\n this[init]();\n }", "function overworldDat(){\n\tthis.overDir = {'north':null, 'south':null,'east':null,'west':null};\t\t//save pointers to other overworlds\n\tthis.houseDat = {};\n\tthis.map = [];\n\tthis.doors = [];\n\tthis.index = -1;\n}", "function createRandomTerrain(){\n\t\t//first check world sizes not to small\n\t\tif(worldWidth < worldMinWidth){ worldWidth = worldMinWidth; }\n\t\tif(worldHeight < worldMinHeight){ worldHeight = worldMinHeight; }\n\t\t\n\t\t//world map grid\n\t\t//first we just create the whole array\n\t\tworldGrid = new Array(worldWidth);\n\t\tfor(var iX = 0; iX < worldWidth; iX++){\n\t\t\tworldGrid[iX] = new Array(worldHeight);\n\t\t\tfor(var iY = 0; iY < worldHeight; iY++){\n\t\t\t\tworldGrid[iX][iY] = new Object();\n\t\t\t\tworldGrid[iX][iY].blockType = BLOCKTYPENONE;\n\t\t\t\tworldGrid[iX][iY].frameName = \"blank.png\";\n\t\t\t\tworldGrid[iX][iY].position = new PIXI.Point(iX * worldBlockSize, iY * worldBlockSize);\n\t\t\t}\n\t\t}\n\t\t\n\t\t//random generation\n\t\tvar lastHeight = Math.round(worldHeight -(worldMinHeight / 3));\n\n\t\tfor(var iX = 0; iX < (worldWidth / 2); iX++){\n\t\t\t\n\t\t\t//randomize when not in start flat area\n\t\t\tif(iX < lowRangeStartArea || iX > highRangeStartArea){\n\t\t\t\tvar rndNum = Math.random();\n\t\t\t\tif(rndNum < 0.5){ lastHeight--; lastHeight--; }\n\t\t\t\tif(rndNum >= 0.5){ lastHeight++;}\n\t\t\t}\n\t\t\t\n\t\t\tif(lastHeight < 5){ lastHeight = 5; }\n\t\t\t\n\t\t\t// 1/4 of last height\n\t\t\tvar\tqLastHeight = Math.round((worldHeight - lastHeight) / 4);\n\t\t\t\n\t\t\tfor(var iY = (worldHeight - 1); iY > 0; iY--){ //y in reverse\n\t\t\t\tif(iY > lastHeight){\n\t\t\t\t\tworldGrid[iX][iY].blockType = BLOCKTYPEDIRT;\n\t\t\t\t\tworldGrid[iX][iY].frameName = getRandomDirtTexture(0);\n\t\t\t\t}\n\t\t\t\tif(iY > lastHeight + qLastHeight){\n\t\t\t\t\tworldGrid[iX][iY].blockType = BLOCKTYPEDIRT;\n\t\t\t\t\tworldGrid[iX][iY].frameName = getRandomDirtTexture(1);\n\t\t\t\t}\n\t\t\t\tif(iY > lastHeight + qLastHeight*2){\n\t\t\t\t\tworldGrid[iX][iY].blockType = BLOCKTYPEDIRT;\n\t\t\t\t\tworldGrid[iX][iY].frameName = getRandomDirtTexture(2);\n\t\t\t\t}\n\t\t\t\tif(iY > lastHeight + qLastHeight*3){\n\t\t\t\t\tworldGrid[iX][iY].blockType = BLOCKTYPEDIRT;\n\t\t\t\t\tworldGrid[iX][iY].frameName = getRandomDirtTexture(3);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//smooth out rough parts\n\t\tfor(var iX = 1; iX < (worldWidth / 2); iX++){\n\t\t\tfor(var iY = 1; iY < worldHeight - 1; iY++){\n\t\t\t\t//check not right at edge of world for array saftey net\n\t\t\t\tif(worldGrid[iX][iY].blockType != BLOCKTYPENONE ){\n\t\t\t\t\t//\n\t\t\t\t\tif(worldGrid[iX - 1][iY].blockType === BLOCKTYPENONE &&\n\t\t\t\t\t\t\tworldGrid[iX][iY - 1].blockType === BLOCKTYPENONE &&\n\t\t\t\t\t\t\tworldGrid[iX + 1][iY].blockType === BLOCKTYPENONE){\n\t\t\t\t\t\t\n\t\t\t\t\t\tworldGrid[iX][iY].blockType = BLOCKTYPENONE;\n\t\t\t\t\t\tworldGrid[iX][iY].frameName = \"blank.png\";\n\t\t\t\t\t\tworldGrid[iX+1][iY].blockType = BLOCKTYPENONE;\n\t\t\t\t\t\tworldGrid[iX+1][iY].frameName = \"blank.png\";\n\t\t\t\t\t\tworldGrid[iX-1][iY].blockType = BLOCKTYPENONE;\n\t\t\t\t\t\tworldGrid[iX-1][iY].frameName = \"blank.png\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t//grass topping\n\t\tvar grassLevels;\n\t\tfor(var iX = 1; iX < (worldWidth / 2); iX++){\n\t\t\tgrassLevels = 0;\n\t\t\tfor(var iY = 1; iY < worldHeight - 1; iY++){\n\t\t\t\t//check not right at edge of world for array saftey net\n\t\t\t\tif(worldGrid[iX][iY].blockType != BLOCKTYPENONE ){\n\t\t\t\t\t\tworldGrid[iX][iY].blockType = BLOCKTYPEGRASS;\n\t\t\t\t\t\tworldGrid[iX][iY].frameName = getRandomGrassTexture();\n\t\t\t\t\t\tgrassLevels++;\n\t\t\t\t\t\tif(grassLevels > 1){ break; }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//flip copy to second half of world\n\t\tfor(var iX = 0; iX < (worldWidth / 2); iX++){\n\t\t\tfor(var iY = 0; iY < worldHeight; iY++){\n\t\t\t\tif(worldGrid[iX][iY].blockType != BLOCKTYPENONE){\n\t\t\t\t\tworldGrid[worldWidth - iX - 1][iY].blockType = worldGrid[iX][iY].blockType;\n\t\t\t\t\tswitch(worldGrid[iX][iY].blockType){\n\t\t\t\t\tcase BLOCKTYPEDIRT:\n\t\t\t\t\t\tworldGrid[worldWidth - iX - 1][iY].frameName = worldGrid[iX][iY].frameName;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase BLOCKTYPEGRASS:\n\t\t\t\t\t\tworldGrid[worldWidth - iX - 1][iY].frameName = getRandomGrassTexture(60);\n\t\t\t\t\t\tbreak;\n\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\t\t\t\n\t}", "function Universe() {\n\n\t// the cached instance\n\tvar instance = this;\n\n\t// proceed as normal\n\tthis.start_time = 0;\n\tthis.bang = \"Big\";\n\n\t// rewrite the constructor\n\tUniverse = function () {\n\t\treturn instance;\n\t};\n\n}", "function makeOverworld(start_side=\"\", buildRange=[3,7]){\n\tlet m = baseOverworld(start_side);\n\tlet doorSet = makeBuildings(m,buildRange);\n\treturn {'map': m, 'doors': doorSet};\n}", "function world(snake, apple, bounds) {\n return {\n snake: snake,\n apple: apple,\n bounds: bounds\n };\n}", "getRegion(regionName) {\n var regions = this._regions || {};\n return regions[regionName];\n }", "get platformRegion() {\n return this._platformRegion;\n }", "function Window_BattleMap() {\n this.initialize.apply(this, arguments);\n}", "function Workspace() {\n this.paletteTermite = new ColorPalette();\n this.paletteWoodchip = new ColorPalette();\n this.initialWoodchipLocs = [];\n BitShadowMachine.System.Classes = {\n Woodchip: Woodchip,\n Termite: Termite\n };\n}", "function makeGlobe() {\n globe = true;\n svgGlobe.append(\"use\")\n .attr(\"class\", \"water\")\n .attr(\"xlink:href\", \"#sphere2\");\n\n svgGlobe.append(\"defs\").append(\"path\")\n .datum({type: \"Sphere\"})\n .attr(\"id\", \"sphere2\")\n .attr(\"d\", globePath);\n\n svgGlobe.append(\"path\")\n .datum(topojson.feature(world, world.objects.countries))\n .attr(\"class\", \"land\")\n .attr(\"d\", globePath);\n\n svgGlobe.append(\"path\")\n .datum(graticule)\n .attr(\"class\", \"graticule grat-globe\")\n .attr(\"d\", globePath);\n\n //Draw paths from Raleigh to 'X'\n // svgGlobe.append(\"path\")\n // .datum({type: \"LineString\", coordinates: raleighToX})\n // .attr({\n // \"class\": \"route\",\n // \"d\": globePath\n // })\n }", "static initMapSouthAfrica() {\r\n // Set Active Map\r\n mapOptions['map'] = 'za_mill_en';\r\n\r\n // Init Map\r\n jQuery('.js-vector-map-south-africa').vectorMap(mapOptions);\r\n }", "function VMRegion(startAddress, sizeInBytes, protectionFlags,\n mappedFile, byteStats) {\n this.startAddress = startAddress;\n this.sizeInBytes = sizeInBytes;\n this.protectionFlags = protectionFlags;\n this.mappedFile = mappedFile || '';\n this.byteStats = byteStats || {};\n }", "function GroundGeometry(id,scene,/**\n * Defines the width of the ground\n */width,/**\n * Defines the height of the ground\n */height,/**\n * Defines the subdivisions to apply to the ground\n */subdivisions,canBeRegenerated,mesh){if(mesh===void 0){mesh=null;}var _this=_super.call(this,id,scene,canBeRegenerated,mesh)||this;_this.width=width;_this.height=height;_this.subdivisions=subdivisions;return _this;}", "constructor() {\n this.game = undefined;\n\n this.mapKey = undefined; // should be string with name of map\n this.playerProperties = undefined; // should be object with properties of player\n this.monsterProperties = undefined; // should be array of objects with properties of each monster\n this.defaultAbilities = undefined; // should be array of default abilities\n\n this.player = undefined; // defined in createPlayer(); included here to avoid IDE warning\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
unique user email checking
async uniqueEmail(email){ let user=await dao.find(this.USERS,{email: email}) if(user.length) return false return true }
[ "async ensureUnique () {\n\t\tconst user = await this.data.users.getOneByQuery(\n\t\t\t{\n\t\t\t\tsearchableEmail: decodeURIComponent(this.request.body.toEmail).toLowerCase()\n\t\t\t},\n\t\t\t{\n\t\t\t\thint: UserIndexes.bySearchableEmail\n\t\t\t}\n\t\t);\n\t\tif (user) {\n\t\t\tthrow this.errorHandler.error('emailTaken');\n\t\t}\n\t}", "static checkUserExists(req, res, next) {\n User.getUserByEmail(req.body.email)\n .then(newUser =>{\n if (newUser.rows[0]) return errHandle(409, 'user already exists', res);\n return next();\n })\n }", "function checkEmail(email){\r\n\tif (!checkLength(email, 6)) {\r\n\t\treturn false;\r\n\t} else if (email.indexOf(\"@\") == -1) {\r\n\t\treturn false;\r\n\t} else if (email.indexOf(\".\") == -1) {\r\n\t\treturn false;\r\n\t} else if (email.lastIndexOf(\".\") < email.lastIndexOf(\"@\")) {\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}", "function check_email(email) {\n\t\t\t\t\tif(email === null) { \n\t\t\t\t\t\treturn false; \n\t\t\t\t\t}\n\t\t\t\t\telse if(email.domain === \"mumail.\") {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t} \n\t\t\t\t\telse return false;\n\t\t\t\t}", "function validateForgotPasswordEmail(email, id) {\n removeError(id);\n $.get(\"../../php/common/getData.php?table=user&column=email&value=\" + email, function (data, status) {\n if (data === 'false') {\n isForgotPasswordEmail = false;\n errorToggle(id, \"Email not exits!\", true);\n } else {\n isForgotPasswordEmail = true;\n errorToggle(id, \"Looks Good!\", false);\n }\n let regex = /^([a-zA-Z0-9_\\.\\-\\+])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;\n\n if(!regex.test(email)) {\n errorToggle(id, \"Invalid Email!\", true);\n isForgotPasswordEmail = false;\n }else{\n isForgotPasswordEmail = true;\n }\n });\n}", "function checkEmail (email,callback){\n console.log('checkEmail');\n db.connect(function(error){\n if (error){\n return console.log('CONNECTION error: ' + error);\n }\n this.query().select('*').from('emails').where('email=?',[email])\n .execute(function(error, rows) {\n if (error) {\n return console.log('ERROR: ' + error);\n }\n console.log(rows.length + ' ROWS');\n if (isEmpty(rows)){\n insertEmail(email,callback);\n } else {\n updateCount(rows[0],callback);\n }\n })\n });\n}", "function email_check() {\r\n email_warn(email_validate());\r\n final_validate();\r\n}", "function makeMyUsername(email){\n let username = email.slice(0,email.indexOf(\"@\"))\n return username;\n}", "static findUserByEmail(email, callback) {\n Account.findOne({'email': email}, (err, data) => {\n if(err) {\n return callback(err, null);\n } else {\n return callback(null, data);\n }\n });\n }", "function ssw_js_validate_email() {\n\n var email_regex = /^([\\w-]+(?:\\.[\\w-]+)*)@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$/;\n var email = document.getElementById('ssw-steps').admin_email.value;\n \n if (!email_regex.test(email)) {\n document.getElementById(\"ssw-validate-email-error-label\").innerHTML=ssw_email_invalid_msg;\n document.getElementById(\"ssw-validate-email-error\").style.display=\"block\"; \n return false;\n }\n else {\n document.getElementById(\"ssw-validate-email-error\").style.display=\"none\";\n return true;\n }\n}", "function getUsername() {\r\n \r\n // get's user email:\r\n var email = Session.getActiveUser().getEmail()\r\n // emails in form <username> @ mail.domain\r\n // split --> parse_emial = ['username','mail.com']\r\n var parse_email = email.split(\"@\")\r\n var username = parse_email[0]\r\n \r\n return username\r\n}", "#checkForEmail(line) {\n\n // the line must contain the @ symbol\n // then any of the parts of the line split on a space could be email\n // then if the part matches the normal email regular expression\n // WITH the addition of spaces that people might put in to avoid email checking\n\n let looksLikeEmail = false;\n let regex = /^[a-z0-9]+@[a-z]+\\.[a-z]{2,3}$/;\n let sep = line.indexOf('@');\n if (sep >= 0) {\n if (line.match(regex)) {\n looksLikeEmail = true;\n } else {\n let lineParts = line.split(' ');\n for (let i=0; i < lineParts.length; i++) {\n if (lineParts[i].match(regex)) {\n looksLikeEmail = true;\n }\n }\n }\n if (!looksLikeEmail) {\n // have they put in spaces to avoid the checks?\n // build a new string to check\n // start from the last space before the @\n // then remove all spaces\n let firstPart = line.substring(0, sep).trim();\n let newString = firstPart;\n let i = firstPart.lastIndexOf(' ');\n if (i > 0) {\n newString = firstPart.substring(i);\n }\n newString += line.substring(sep);\n let testString = newString.replace(/ /g, \"\")\n if (testString.match(regex)) {\n looksLikeEmail = true;\n }\n }\n }\n return looksLikeEmail;\n }", "_isValidInput() {\n if (!validate(this.email)) {\n return false;\n }\n const indexOfAt = this.email.indexOf(\"@\"); // index of @ symbol\n this.domain = this.email.substring(indexOfAt + 1);\n return true;\n }", "function userEmail(userID) {\n let emailObj = {};\n for (var user in users) {\n if (userID === users[user].id) {\n emailObj = users[user]\n }\n }\n return emailObj.email;\n}", "function confirmE() {\r\n if ((email.val() !== confirmEmail.val())) {\r\n errors.push(' - Email confirmation does not match email');\r\n }\r\n}", "function remove_user_validation(){\r\n\t\t\tvar username = document.forms['remove_user']['username'].value;\r\n\t\t\tvar email = document.forms['remove_user']['email'].value;\r\n\r\n\t\t\tvar email_pattern = /^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;\r\n\t\t\tif(!email_pattern.test(email)){\r\n\t\t\t\twindow.alert('Enter valid mail id');\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tvar user_pattern = /^[a-zA-Z]\\w*\\d*\\w*/;\r\n\t\t\tvar user_result = username.match(user_pattern);\r\n\t\t\tif(user_result != username){\r\n\t\t\t\twindow.alert('Enter valid username');\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tvar confirmation = confirm(\"Are you sure to remove?\");\r\n\r\n\t\t\treturn confirmation;\r\n}", "function validateEmail()\n{\n//variable email is set by element id contactEmail from the form\n\tvar email = document.getElementById(\"contactEmail\").value; \n\t\n\t//validation for email\n\tif(email.length == 0)\n\t{\n\t\tproducePrompt(\"Email is Required\", \"emailPrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tif(!email.match(/^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/)){\n\t\tproducePrompt(\"Email Address is Invalid\", \"emailPrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tproducePrompt(\"Valid Email\", \"emailPrompt\", \"green\"); \n\t\treturn true; \n}", "isEmailMatch(value, exactlyOneEmailExpected = false) {\n if (!value) return false;\n let isMatch = false;\n const result = ExtractEmails(value.toLowerCase());\n if (exactlyOneEmailExpected && result.count !== 1) {\n return false;\n }\n for (const v of result.emails) {\n if (this.re && v.match(this.re) !== null || this.arg === v) {\n isMatch = true;\n break;\n }\n }\n return this.not ? !isMatch : isMatch;\n }", "function getUsersByEmail (req, res, next) {\n let email = req.params.neteller_email_address;\n return User.findOne({neteller_email_address: email})\n .then(user => {\n if (!user) throw {status: 404, message: `There is no member with email address: ${email}`};\n else return res.status(200).send({user});\n })\n .catch(err => {\n if (err.status === 404) return next(err);\n else return next({status: 500, message: 'server error'});\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a listener that will be used to analize each action dispatched by asking for the 'action' property inside the payload and comparing it with the action provided here. If the payload itself is the action it will also match properly. See listenTo for docs on the other arguments.
listenToAction(action, handler, deferExecution) { this.listenTo('action', action, handler, deferExecution); }
[ "listenToMatchingAction (matcher, handler, deferExecution) {\n this._actionListeners.push({matcher, handler, deferExecution});\n }", "listenTo(actionKey, action, handler, deferExecution) {\n var actionListener = {actionKey, action, handler, deferExecution};\n validateActionListener(actionListener);\n this._actionListeners.push(actionListener);\n }", "action(type, payload) {\n var action;\n if (payload) {\n action = _.extend({}, payload, {actionType: type});\n } else {\n action = {actionType: type};\n }\n debug('Action: ' + type, action);\n this.dispatch(action);\n }", "add(actionToAdd) {\n\t\tif (!this.actions.some( action => action.name === actionToAdd.name)) {\n\t\t\tthis.actions.push(actionToAdd);\n\t\t}\n\t}", "publish(eventType, ...payload) {\n const subscribers = this.events.get(eventType);\n if (subscribers) {\n for (const eventHandler of subscribers) {\n eventHandler(...payload);\n }\n }\n }", "function addRequiredAction(action) {\n setActions([...actions,action]);\n }", "registerActions() {\n this.registerAction(\"read\", new read_action_1.default());\n this.registerAction(\"write\", new write_action_1.default());\n }", "stateActionDispatch (action) {\n this.send('state.action.dispatch', { action })\n }", "function actionCreator(action){\n return action\n}", "async [FmConfigActions_1.FmConfigAction.watchRouteChanges]({ dispatch, commit, rootState }, payload) {\n if (index_1.configuration.onRouteChange) {\n const ctx = {\n Watch: firemodel_1.Watch,\n Record: firemodel_1.Record,\n List: firemodel_1.List,\n dispatch,\n commit,\n state: rootState,\n leaving: payload.from.path,\n entering: payload.to.path,\n queryParams: payload.to.params\n };\n await runQueue_1.runQueue(ctx, \"route-changed\");\n }\n }", "function registerActionStateHandler(actionState/*:String*/, actionStateHandler/*:Function*/)/*:void*/ {\n if (this.actionStateHandlers$yRG0[actionState] !== undefined) {\n com.coremedia.ui.logging.Logger.debug(\"Notification Action State Handler for '\" + actionState + \"' is overriden\");\n }\n this.actionStateHandlers$yRG0[actionState] = actionStateHandler;\n }", "notifyChildAboutAction(action) {\n this.postMessageToChild(MessageType.action, action);\n }", "function wrapAction(name, action) {\r\n return function () {\r\n setActivePinia(pinia);\r\n const args = Array.from(arguments);\r\n const afterCallbackList = [];\r\n const onErrorCallbackList = [];\r\n function after(callback) {\r\n afterCallbackList.push(callback);\r\n }\r\n function onError(callback) {\r\n onErrorCallbackList.push(callback);\r\n }\r\n // @ts-expect-error\r\n triggerSubscriptions(actionSubscriptions, {\r\n args,\r\n name,\r\n store,\r\n after,\r\n onError,\r\n });\r\n let ret;\r\n try {\r\n ret = action.apply(this && this.$id === $id ? this : store, args);\r\n // handle sync errors\r\n }\r\n catch (error) {\r\n triggerSubscriptions(onErrorCallbackList, error);\r\n throw error;\r\n }\r\n if (ret instanceof Promise) {\r\n return ret\r\n .then((value) => {\r\n triggerSubscriptions(afterCallbackList, value);\r\n return value;\r\n })\r\n .catch((error) => {\r\n triggerSubscriptions(onErrorCallbackList, error);\r\n return Promise.reject(error);\r\n });\r\n }\r\n // trigger after callbacks\r\n triggerSubscriptions(afterCallbackList, ret);\r\n return ret;\r\n };\r\n }", "function ActionHandler(action, wait, dontCheckAlerts) {\n CommandHandler.call(this, \"action\", true, action);\n if (wait) {\n this.wait = true;\n }\n // note that dontCheckAlerts could be undefined!!!\n this.checkAlerts = (dontCheckAlerts) ? false : true;\n}", "function bindAction (type, handler, initialState) {\n return typeof initialState === 'undefined'\n ? handler ? function (state, action) {\n if (typeof state === 'undefined') {\n state = null\n }\n return action && action.type === type ? handler(state, action) : state\n } : function (state) { // an empty state reducer\n return typeof state === 'undefined' ? null : state\n }\n : handler ? function (state, action) {\n if (typeof state === 'undefined') {\n state = initialState\n }\n return action && action.type === type ? handler(state, action) : state\n } : function (state, action) {\n return typeof state === 'undefined' ? initialState : state\n }\n}", "function _dispatch(target, origin, payload) {\n target.postMessage(JSON.stringify(payload), origin);\n }", "function hasActionChanged() {\r\n\r\n return( action !== previousAction );\r\n\r\n }", "did(eventName, payload) {\n this.emitter.emit(`did-${eventName}`, payload);\n }", "function validateAction(action){\r\n\tvar actionArray = ['save', 'updateProfile', 'updateRSVP', 'delete', 'signout'];\r\n\tif(actionArray.includes(action)){\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::AppMesh::Route.HttpRouteHeader` resource
function cfnRouteHttpRouteHeaderPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnRoute_HttpRouteHeaderPropertyValidator(properties).assertSuccess(); return { Invert: cdk.booleanToCloudFormation(properties.invert), Match: cfnRouteHeaderMatchMethodPropertyToCloudFormation(properties.match), Name: cdk.stringToCloudFormation(properties.name), }; }
[ "function cfnGatewayRouteHttpGatewayRouteHeaderPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteHeaderPropertyValidator(properties).assertSuccess();\n return {\n Invert: cdk.booleanToCloudFormation(properties.invert),\n Match: cfnGatewayRouteHttpGatewayRouteHeaderMatchPropertyToCloudFormation(properties.match),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}", "function cfnRouteHttpRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnRouteHttpRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnRouteHttpRouteMatchPropertyToCloudFormation(properties.match),\n RetryPolicy: cfnRouteHttpRetryPolicyPropertyToCloudFormation(properties.retryPolicy),\n Timeout: cfnRouteHttpTimeoutPropertyToCloudFormation(properties.timeout),\n };\n}", "function cfnGatewayRouteHttpGatewayRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnGatewayRouteHttpGatewayRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnGatewayRouteHttpGatewayRouteMatchPropertyToCloudFormation(properties.match),\n };\n}", "function cfnGatewayRouteHttpGatewayRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteActionPropertyValidator(properties).assertSuccess();\n return {\n Rewrite: cfnGatewayRouteHttpGatewayRouteRewritePropertyToCloudFormation(properties.rewrite),\n Target: cfnGatewayRouteGatewayRouteTargetPropertyToCloudFormation(properties.target),\n };\n}", "function cfnGatewayRouteHttpGatewayRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Headers: cdk.listMapper(cfnGatewayRouteHttpGatewayRouteHeaderPropertyToCloudFormation)(properties.headers),\n Hostname: cfnGatewayRouteGatewayRouteHostnameMatchPropertyToCloudFormation(properties.hostname),\n Method: cdk.stringToCloudFormation(properties.method),\n Path: cfnGatewayRouteHttpPathMatchPropertyToCloudFormation(properties.path),\n Port: cdk.numberToCloudFormation(properties.port),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n QueryParameters: cdk.listMapper(cfnGatewayRouteQueryParameterPropertyToCloudFormation)(properties.queryParameters),\n };\n}", "function cfnGatewayRouteHttpGatewayRouteRewritePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteRewritePropertyValidator(properties).assertSuccess();\n return {\n Hostname: cfnGatewayRouteGatewayRouteHostnameRewritePropertyToCloudFormation(properties.hostname),\n Path: cfnGatewayRouteHttpGatewayRoutePathRewritePropertyToCloudFormation(properties.path),\n Prefix: cfnGatewayRouteHttpGatewayRoutePrefixRewritePropertyToCloudFormation(properties.prefix),\n };\n}", "function cfnRouteHttpRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpRouteActionPropertyValidator(properties).assertSuccess();\n return {\n WeightedTargets: cdk.listMapper(cfnRouteWeightedTargetPropertyToCloudFormation)(properties.weightedTargets),\n };\n}", "function cfnGatewayRouteGrpcGatewayRouteRewritePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteRewritePropertyValidator(properties).assertSuccess();\n return {\n Hostname: cfnGatewayRouteGatewayRouteHostnameRewritePropertyToCloudFormation(properties.hostname),\n };\n}", "function cfnRouteGrpcRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnRouteGrpcRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnRouteGrpcRouteMatchPropertyToCloudFormation(properties.match),\n RetryPolicy: cfnRouteGrpcRetryPolicyPropertyToCloudFormation(properties.retryPolicy),\n Timeout: cfnRouteGrpcTimeoutPropertyToCloudFormation(properties.timeout),\n };\n}", "function cfnGatewayRouteGrpcGatewayRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnGatewayRouteGrpcGatewayRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnGatewayRouteGrpcGatewayRouteMatchPropertyToCloudFormation(properties.match),\n };\n}", "function cfnRouteRouteSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_RouteSpecPropertyValidator(properties).assertSuccess();\n return {\n GrpcRoute: cfnRouteGrpcRoutePropertyToCloudFormation(properties.grpcRoute),\n Http2Route: cfnRouteHttpRoutePropertyToCloudFormation(properties.http2Route),\n HttpRoute: cfnRouteHttpRoutePropertyToCloudFormation(properties.httpRoute),\n Priority: cdk.numberToCloudFormation(properties.priority),\n TcpRoute: cfnRouteTcpRoutePropertyToCloudFormation(properties.tcpRoute),\n };\n}", "function cfnGatewayRouteHttpGatewayRoutePathRewritePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRoutePathRewritePropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n };\n}", "function cfnRouteGrpcRouteMetadataPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRouteMetadataPropertyValidator(properties).assertSuccess();\n return {\n Invert: cdk.booleanToCloudFormation(properties.invert),\n Match: cfnRouteGrpcRouteMetadataMatchMethodPropertyToCloudFormation(properties.match),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}", "function cfnGatewayRouteGrpcGatewayRouteMetadataPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteMetadataPropertyValidator(properties).assertSuccess();\n return {\n Invert: cdk.booleanToCloudFormation(properties.invert),\n Match: cfnGatewayRouteGatewayRouteMetadataMatchPropertyToCloudFormation(properties.match),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}", "function cfnGatewayRouteGatewayRouteSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GatewayRouteSpecPropertyValidator(properties).assertSuccess();\n return {\n GrpcRoute: cfnGatewayRouteGrpcGatewayRoutePropertyToCloudFormation(properties.grpcRoute),\n Http2Route: cfnGatewayRouteHttpGatewayRoutePropertyToCloudFormation(properties.http2Route),\n HttpRoute: cfnGatewayRouteHttpGatewayRoutePropertyToCloudFormation(properties.httpRoute),\n Priority: cdk.numberToCloudFormation(properties.priority),\n };\n}", "function cfnGatewayRouteGrpcGatewayRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Hostname: cfnGatewayRouteGatewayRouteHostnameMatchPropertyToCloudFormation(properties.hostname),\n Metadata: cdk.listMapper(cfnGatewayRouteGrpcGatewayRouteMetadataPropertyToCloudFormation)(properties.metadata),\n Port: cdk.numberToCloudFormation(properties.port),\n ServiceName: cdk.stringToCloudFormation(properties.serviceName),\n };\n}", "function cfnGatewayRouteGrpcGatewayRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteActionPropertyValidator(properties).assertSuccess();\n return {\n Rewrite: cfnGatewayRouteGrpcGatewayRouteRewritePropertyToCloudFormation(properties.rewrite),\n Target: cfnGatewayRouteGatewayRouteTargetPropertyToCloudFormation(properties.target),\n };\n}", "function cfnRouteHeaderMatchMethodPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HeaderMatchMethodPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n Range: cfnRouteMatchRangePropertyToCloudFormation(properties.range),\n Regex: cdk.stringToCloudFormation(properties.regex),\n Suffix: cdk.stringToCloudFormation(properties.suffix),\n };\n}", "function cfnRouteHttpPathMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpPathMatchPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n Regex: cdk.stringToCloudFormation(properties.regex),\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run all listsOprions methods and store them to this.lists
async buildLists () { console.log('Build Lists started') for ( const listOptions of this.listsOptions ) { const methodName = `Building ${listOptions.name}` console.time(methodName) const builtList = await listOptions.buildMethod() // Run the build method to get the lists this.lists[listOptions.name] = new Set( builtList ) console.timeEnd(methodName) console.log(`Finished ${listOptions.name} list with ${this.lists[listOptions.name].size} items`) } console.log('Build Lists finished') return }
[ "function buildList() {\n $log.debug(\"Building list...\");\n vm.list = Object.keys(queryFields); //get the keys\n vm.definitions = queryFields;\n $log.debug(vm.definitions);\n }", "function mainLists() {\n\t$('ul.lists .toolEdit a').bind(\"click\", function () {\n\t\tvar s = $(this).closest('.s');\n\t\tvar i = $(this).closest('.s').next('.itemeditor');\n\t\tvar li = $(this).closest('li');\n\n\t\tdefaultLists();\n\n\t\t$.ajax({\n\t\t\ttype: \"GET\",\n\t\t\turl: 'ajax/edit-main-mylisting.html',\n\t\t\tdataType: 'html',\n\t\t\tsuccess: function (data) {\n\t\t\t\t$(s).after(data);\n\t\t\t}\n\n\t\t});\n\n\t});\n}", "function testList() \n{\n \n // fnlist is what buildList returns\n var fnlist = buildList([1,2,3]);\n // using j only to help prevent confusion - could use i\n for (var j = 0; j < fnlist.length; j++) \n {\n fnlist[j]();\n }\n}", "function makeListsSortable() {\n\t\t// Get all lists\n\t\tvar ul = $(\".subpagelistContainer ul\");\n\t\t\n\t\t// Add click events on each sort arrow, toggle between ascending and descending order\n\t\t$.each(ul, function() {\n\t\t\t// Remove old click events\n $(this).children('.ssm-list-sort').unbind('click');\n \n // Add the new\n $(this).children('.ssm-list-sort').click(function(e) {\n\t\t\t\tif($(e.target).hasClass('dashicons-arrow-up-alt2')) {\n\t\t\t\t\t// Show down icon and sort list in descending order\n\t\t\t\t\tvar sortArrow = $(e.target);\n\t\t\t\t\tsortArrow.removeClass('dashicons-arrow-up-alt2');\n\t\t\t\t\tsortArrow.addClass('dashicons-arrow-down-alt2');\n\t\t\t\t\tsortList($(sortArrow.parent()), false);\n\t\t\t\t} else {\n\t\t\t\t\t// Show up icon and sort list in ascending order\n\t\t\t\t\tvar sortArrow = $(e.target);\n\t\t\t\t\tsortArrow.addClass('dashicons-arrow-up-alt2');\n\t\t\t\t\tsortArrow.removeClass('dashicons-arrow-down-alt2');\n\t\t\t\t\tsortList($(sortArrow.parent()), true);\n\t\t\t\t}\n\t\t\t})\n\t\t});\n\t}", "loadList(listId) {\n //finds list\n let listIndex = -1;\n for (let i = 0; (i < this.toDoLists.length) && (listIndex < 0); i++) {\n if (this.toDoLists[i].id === listId)\n listIndex = i;\n }\n //loads this list\n if (listIndex >= 0) {\n let listToLoad = this.toDoLists[listIndex];\n this.setCurrentList(listToLoad);\n //this.currentList = listToLoad;//change to set current list\n this.view.viewList(this.currentList);\n this.view.refreshLists(this.toDoLists);\n //set currentlist \n }\n this.tps.clearAllTransactions();\n this.buttonCheck();\n }", "function doResults(repos) {\n updateRateLimit();\n updateList(repos);\n }", "_addToLists(list) {\n const listObj = {\n index: this.lists.length,\n name: list.getAttribute('name'),\n element: list,\n editable: this.isEditable(list),\n };\n if(this.lists.length === 0) this.activeList = listObj;\n this.lists.push(listObj);\n }", "updateList() {\n console.log(\"$$$$$$$$ updateList\");\n this.forceUpdate();\n }", "function listAll() {\n $scope.voters = VoterService.listAllVoters();\n }", "list(state, { medias, corpuUid }) {\n Vue.set(state.lists, corpuUid, medias)\n }", "updateBeginningAndEndingItems(method) {\n this.updateListStart();\n this.updateListEnding(method);\n }", "constructor(listCommand){\n super();\n this.listCommand=listCommand;\n this.nextLine=0;\n this.actionNumber=-2;\n this.memory=new Map();\n this.direction=true;\n }", "function evalList(scope, list, valueConverters) {\n var length = list.length,\n cacheLength, i;\n\n for (cacheLength = evalListCache.length; cacheLength <= length; ++cacheLength) {\n evalListCache.push([]);\n }\n\n var result = evalListCache[length];\n\n for (i = 0; i < length; ++i) {\n result[i] = list[i].evaluate(scope, valueConverters);\n }\n\n return result;\n}", "static getMethodsList(methods){\n\t}", "function refresh_all_action_items() {\n\tconsole.log(\"now refreshing\");\n\t$(\"div#projects div.project\").each( function() {\n\t\trefresh_action_items(this);\n\t});\n}", "function callAllServiceFunctions() {\n\t\tgetAllDataSpeakers();\n\t\tgetAllDataSponsors();\n\t\tgetAllDataSessions();\n\t\tgetAllDataExhibitors();\n\t}", "addList(list) {\r\n this.#listList.set(list.listId, list);\r\n }", "function updateList(results) {\n var meta = _.get(results, 'meta');\n $log.info('Loaded', (meta.count + meta.offset), '/', meta.total, 'comics which title starts with `' +\n vm.filter + '`');\n // Update list of comics\n vm.comics = meta.offset === 0 ? results : _.unionBy(vm.comics, results, 'id');\n // Update meta\n meta = vm.comics.meta = results.meta;\n // Update boolean to know instantly if there is more\n vm.hasMoreData = meta && (meta.count + meta.offset) < meta.total;\n }", "function setListItems(items) {\n // copy the items to a local array\n listItems = [];\n if(items != undefined && items != null && items.length > 0) {\n for(u=0; u<items.length; u++) {\n listItems.splice(0,0,items[u]);\n filterAllowedItems(items[u]);\n }\n }\n\n \n renderListItems();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an ArrayBuffer to a base64 string and makes an image from that
static arrayBufferToImage(data) { var byteStr = ''; var bytes = new Uint8Array(data); var len = bytes.byteLength; for (var i = 0; i < len; i++) byteStr += String.fromCharCode(bytes[i]); var base64Image = window.btoa(byteStr); var str = 'data:image/png;base64,' + base64Image; var img = new Image(); img.src = str; return img; }
[ "static byteArrayToImage(data)\n\t{\n\t\tvar byteStr = '';\n\t\tvar bytes = new Uint8Array(data.arraybytes);\n\t\tvar len = bytes.byteLength;\n\t\tfor (var i = 0; i < len; i++)\n\t\t{\n\t\t\tbyteStr += String.fromCharCode(bytes[i]);\n\t\t}\n\t\tvar base64Image = window.btoa(byteStr);\n\t\tvar str = 'data:image/png;base64,' + base64Image;\n\t\tvar img = new Image();\n\t\timg.src = str;\n\t\treturn img;\n\t}", "function base64(data) {\n\tif (typeof data === 'object') data = JSON.stringify(data);\n\treturn Buffer.from(data).toString('base64');\n}", "function convert_to_image(image_data)\r\n{\r\n var canvas = document.createElement(\"canvas\");\r\n\tvar c = canvas.getContext(\"2d\");\r\n\tc.putImageData(image_data, 0, 0);\r\n\t\r\n\tvar img = new Image();\r\n\timg.src = canvas.toDataURL(\"image/png\");\r\n\treturn img;\r\n}", "base64Image(imagePath) {\n\t\tconst base64Content = readFileSync(imagePath).toString('base64')\n\t\treturn `data:image/jpeg;base64,${base64Content}`\n\t}", "function makeDataURI(image) {\n if (image.mime && image.data) {\n image.data = 'data:' + image.mime\n + ';base64,' + image.data;\n }\n }", "base64() {\n\t\tif (typeof btoa === 'function') return btoa(String.fromCharCode.apply(null, this.buildFile()));\n\t\treturn new Buffer(this.buildFile()).toString('base64');\n\t}", "static blobToImage(data)\n\t{\n\t\tvar URLObj = window['URL'] || window['webkitURL'];\n\t\tvar src = URLObj.createObjectURL(data);\n\t\tvar img = new Image();\n\t\timg.src = src;\n\t\treturn img;\n\t}", "function imageData2dataURL(imageData){\n var c = document.createElement('canvas');\n c.width = imageData.width;\n c.height = imageData.height;\n var ctx = c.getContext('2d');\n ctx.putImageData(imageData, 0, 0);\n return c.toDataURL('image/png');\n}", "function showByteArrayImage(id, bytes) {\n document.getElementById(id).src = \"data:image/png;base64,\" + bytes;\n}", "async base64(source, opts = {}) {\n const [res] = await this.capture(source, _.merge(opts, {\n type: 'base64'\n }));\n return res;\n }", "imageToBytes (img, flipY = false, imgFormat = 'RGBA') {\n // Create the gl context using the image width and height\n const {width, height} = img\n const gl = this.createCtx(width, height, 'webgl', {\n premultipliedAlpha: false\n })\n const fmt = gl[imgFormat]\n\n // Create and initialize the texture.\n const texture = gl.createTexture()\n gl.bindTexture(gl.TEXTURE_2D, texture)\n if (flipY) // Mainly used for pictures rather than data\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)\n // Insure [no color profile applied](https://goo.gl/BzBVJ9):\n gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE)\n // Insure no [alpha premultiply](http://goo.gl/mejNCK).\n // False is the default, but lets make sure!\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false)\n\n // gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img)\n gl.texImage2D(gl.TEXTURE_2D, 0, fmt, fmt, gl.UNSIGNED_BYTE, img)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)\n\n // Create the framebuffer used for the texture\n const framebuffer = gl.createFramebuffer()\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer)\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0)\n\n // See if it all worked. Apparently not async.\n const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)\n if (status !== gl.FRAMEBUFFER_COMPLETE)\n this.error(`imageToBytes: status not FRAMEBUFFER_COMPLETE: ${status}`)\n\n // If all OK, create the pixels buffer and read data.\n const pixSize = imgFormat === 'RGB' ? 3 : 4\n const pixels = new Uint8Array(pixSize * width * height)\n // gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels)\n gl.readPixels(0, 0, width, height, fmt, gl.UNSIGNED_BYTE, pixels)\n\n // Unbind the framebuffer and return pixels\n gl.bindFramebuffer(gl.FRAMEBUFFER, null)\n return pixels\n }", "function toString(arrayBuffer) {\n return String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));\n}", "toBase64() {\n return this._byteString.toBase64();\n }", "function convertURIToImageData(URI) {\n return new Promise(function(resolve, reject) {\n if (URI == null) return reject();\n var canvas = document.createElement('canvas'),\n context = canvas.getContext('2d'),\n image = new Image();\n image.addEventListener('load', function() {\n canvas.width = image.width;\n canvas.height = image.height;\n context.drawImage(image, 0, 0, canvas.width, canvas.height);\n resolve(context.getImageData(0, 0, canvas.width, canvas.height));\n }, false);\n image.src = URI;\n });\n}", "function Image(buffer) {\n this._buffer = buffer;\n this._text = null;\n}", "function convertToBase64(info) {\n var readMe = new FileReader();\n readMe.readAsDataURL(info);\n readMe.onload = function () {\n $(\"#base\").val(readMe.result)\n };\n readMe.onerror = function (error) {\n return \"There was an error with your file\"\n };\n }", "function processImageToString(image) {\n\treturn image.toString();\n}", "function allocateBase64Encoded(slab, length, types, allocator, ptr) {\n HEAPU8.set(base64DecToArr(slab), ptr);\n}", "static createBinaryBitmapFromMediaElem(mediaElement){const canvas=BrowserCodeReader$1.createCanvasFromMediaElement(mediaElement);return BrowserCodeReader$1.createBinaryBitmapFromCanvas(canvas);}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method(` Creates a WithNestedExpression from the given nestedCompiledExpression and adds it to the current assertionExpression. `)
addWithNestedExpression({ nestedValueGetter: nestedValueGetter, nestedCompiledExpression: nestedCompiledExpression }) { const withNestedExpression = WithNestedExpression.new({ nestedValueGetter: nestedValueGetter, nestedCompiledExpression: nestedCompiledExpression, }) this.addAssertion({ assertion: withNestedExpression }) }
[ "addWithEachExpression({ eachCompiledExpression: eachCompiledExpression }) {\n const withEachExpression = WithEachExpression.new({\n eachCompiledExpression: eachCompiledExpression\n })\n\n this.addAssertion({ assertion: withEachExpression })\n }", "function translateNested2(x){\n var newX = x;\n if (x.indexOf(\"(\")>0){\n // Find inner and outer terms.\n var innerStart = x.indexOf(\"(\");\n var innerEnd = x.indexOf(\")\");\n var inside = x.substring(innerStart+1,innerEnd);\n var outside = x.substring(0,innerStart);\n newX = inside+\"_\"+outside;\n }\n return newX;\n }", "function translateNested(x){\n var newX = x;\n if (x.indexOf(\"(\")>0){\n // Find inner and outer terms.\n var innerStart = x.indexOf(\"(\");\n var innerEnd = x.indexOf(\")\");\n var inside = x.substring(innerStart+1,innerEnd);\n var outside = x.substring(0,innerStart);\n newX = inside+\".\"+outside;\n }\n return newX;\n }", "function AddNested (array) {\n for (let i = 0; i < array.length; i++){\n let arrayElement = array[i]\n if (Array.isArray(arrayElement)){\n arrayElement.push('nested')\n }\n }\n return array\n}", "visitDml_event_nested_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function tableExpression2( machine )\n {\n rhs = machine.popToken();\n machine.checkToken(\"join\");\n machine.checkToken(\"inner\");\n lhs = machine.popToken();\n machine.pushToken( new joinExpression( \"inner\", lhs, rhs, \"true\" ) );\n }", "function buildNested (el) {\n let nestedCSS = el.egglement ? {...el.styles, position: 'absolute'} : el.styles\n\n if (typeof el.width !== 'undefined' && el.width !== null && el.width !== 'auto') {\n nestedCSS = {...nestedCSS, width: isNaN(el.width) ? el.width : (el.width + 'px')}\n }\n if (typeof el.height !== 'undefined' && el.height !== null && el.height !== 'auto') {\n nestedCSS = {...nestedCSS, height: isNaN(el.height) ? el.height : (el.height + 'px')}\n }\n if (typeof el.top !== 'undefined' && el.top !== null && el.top !== 'auto') {\n nestedCSS = {...nestedCSS, top: isNaN(el.top) ? el.top : (el.top + 'px')}\n }\n if (typeof el.left !== 'undefined' && el.left !== null && el.left !== 'auto') {\n nestedCSS = {...nestedCSS, left: isNaN(el.left) ? el.left : (el.left + 'px')}\n }\n if (typeof el.bottom !== 'undefined' && el.bottom !== null && el.bottom !== 'auto') {\n nestedCSS = {...nestedCSS, bottom: isNaN(el.bottom) ? el.bottom : (el.bottom + 'px')}\n }\n if (typeof el.right !== 'undefined' && el.right !== null && el.right !== 'auto') {\n nestedCSS = {...nestedCSS, right: isNaN(el.right) ? el.right : (el.right + 'px')}\n }\n if (typeof el.zIndex !== 'undefined' && el.zIndex !== null && el.zIndex !== 'auto') {\n nestedCSS = {...nestedCSS, 'z-index': el.zIndex}\n }\n\n /*\n * Tweak to apply the capability of defining the element dimension using\n * left/right (instead of width) for elements other than <div> or <span>\n *\n * Depending on the browser this is not necessary but it will apply to be safe\n */\n if (el.type !== 'div' || el.type !== 'span') {\n if (isNaN(el.width) &&\n (typeof el.right !== 'undefined' && el.right !== null && el.right !== 'auto') &&\n (typeof el.left !== 'undefined' && el.left !== null && el.left !== 'auto')) {\n const hHigh = Math.max(parseInt(el.left), parseInt(el.right))\n let left = isNaN(el.left) ? el.left : (el.left + 'px')\n let right = isNaN(el.right) ? el.right : (el.right + 'px')\n nestedCSS = {...nestedCSS, width: 'calc(100% - ' + left + ' - ' + right + ')'}\n nestedCSS = (hHigh === parseInt(el.left))\n ? {...nestedCSS, left, right: 'auto'}\n : {...nestedCSS, right, left: 'auto'}\n }\n }\n\n /*\n * Tweak to apply the capability of defining the element dimension using\n * top/bottom (instead of height), for <img> elements (there may be others)\n *\n * Depending on the browser this is not necessary but it will apply to be safe\n */\n if (el.type === 'img') {\n if (isNaN(el.height) &&\n (typeof el.top !== 'undefined' && el.top !== null && el.top !== 'auto') &&\n (typeof el.bottom !== 'undefined' && el.bottom !== null && el.bottom !== 'auto')) {\n const vHigh = Math.max(parseInt(el.top), parseInt(el.bottom))\n let top = isNaN(el.top) ? el.top : (el.top + 'px')\n let bottom = isNaN(el.bottom) ? el.bottom : (el.bottom + 'px')\n nestedCSS = {...nestedCSS, height: 'calc(100% - ' + top + ' - ' + bottom + ')'}\n nestedCSS = (vHigh === parseInt(el.top))\n ? {...nestedCSS, top, bottom: 'auto'}\n : {...nestedCSS, bottom, top: 'auto'}\n }\n }\n\n return el.global ? nestedCSS : {...nestedCSS, ...el.styles}\n}", "function surroundExpression(c) {\n return function(node, st, override, format) {\n st.compiler.jsBuffer.concat(\"(\");\n c(node, st, override, format);\n st.compiler.jsBuffer.concat(\")\");\n }\n}", "visitNested_item(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "createNestedAssembly(artifactId, displayName) {\n const directoryName = artifactId;\n const innerAsmDir = path.join(this.outdir, directoryName);\n this.addArtifact(artifactId, {\n type: cxschema.ArtifactType.NESTED_CLOUD_ASSEMBLY,\n properties: {\n directoryName,\n displayName,\n },\n });\n return new CloudAssemblyBuilder(innerAsmDir, {\n // Reuse the same asset output directory as the current Casm builder\n assetOutdir: this.assetOutdir,\n parentBuilder: this,\n });\n }", "enterBlockLevelExpression(ctx) {\n\t}", "function createNestedContextSubMenu(e) {\n var target = e.target;\n\n // Generate nested submenu elements as document fragment\n var ulSubMenu = document.createElement('ul');\n ulSubMenu.className = 'vjs-contextmenu-ui-submenu';\n playbackRates.forEach(function(rate) {\n var liSubMenu = document.createElement('li');\n liSubMenu.className = 'vjs-submenu-item';\n liSubMenu.innerHTML = rate + 'x';\n ulSubMenu.appendChild(liSubMenu);\n liSubMenu.onclick = function() {\n player.playbackRate(parseFloat(rate));\n };\n });\n docfrag.appendChild(ulSubMenu);\n\n // Create nested submenu\n if (matchesSelector(target, \"li.vjs-menu-item\")\n // if (target.matches(\"li.vjs-menu-item\")\n && target.innerText == getItem('speed').label\n && !target.querySelector('.vjs-contextmenu-ui-submenu') ) {\n target.appendChild(docfrag);\n }\n }", "addOrExpression() {\n const andExpression = OrExpression.new({\n leftExpression: this.assertionExpression,\n rightExpression: null,\n })\n\n this.assertionExpression = andExpression \n }", "new_isolated_subcontext() {\n this.check_overflow();\n\n const subcontext = Context.build({\n resource_limits: this.resource_limits,\n static_environments: this.static_environments,\n registers: new Dry.StaticRegisters(this.registers)\n });\n\n subcontext.base_scope_depth = this.base_scope_depth + 1;\n subcontext.exception_renderer = this.exception_renderer;\n subcontext.errors = this.errors;\n subcontext.warnings = this.warnings;\n\n subcontext.filters = this.filters;\n subcontext.strict_filters = this.strict_filters;\n\n subcontext.strainer = null;\n subcontext.disabled_tags = this.disabled_tags;\n\n subcontext.allow_this_variable = this.allow_this_variable;\n subcontext.inside_with_scope = this.inside_with_scope;\n subcontext[constants.symbols.kParentContext] = this;\n // console.log(subcontext)\n return subcontext;\n }", "_add_boolean_expression_subtree_to_ast(boolean_expression_node, parent_var_type) {\n this.verbose[this.verbose.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, INFO, `Adding ${boolean_expression_node.name} subtree to abstract syntax tree.`) // OutputConsoleMessage\n ); // this.verbose[this.verbose.length - 1].push\n let open_parenthesis_or_boolean_value_node = boolean_expression_node.children_nodes[0];\n // Enforce type matching in boolean expressions\n let valid_type = false;\n // If, no parent type was given to enforce type matching...\n if (parent_var_type === UNDEFINED) {\n // Enforce type matching using the current type from now on.\n parent_var_type = BOOLEAN;\n } // if\n // Else, there is a parent type to enforce type matching with.\n else {\n valid_type = !this.check_type(parent_var_type, open_parenthesis_or_boolean_value_node, BOOLEAN);\n } // else\n // Boolean expression ::== ( Expr BoolOp Expr )\n if (boolean_expression_node.children_nodes.length > 1) {\n // Ignore Symbol Open Argument [(] and Symbol Close Argument [)]\n // let open_parenthisis_node = boolean_expression_node.children_nodes[0];\n // let open_parenthisis_node = boolean_expression_node.children_nodes[4];\n let boolean_operator_value_node = boolean_expression_node.children_nodes[2].children_nodes[0];\n let left_expression_node = boolean_expression_node.children_nodes[1];\n let right_expression_node = boolean_expression_node.children_nodes[3];\n // FIRST Add the Boolean Operator\n this._current_ast.add_node(boolean_operator_value_node.name, NODE_TYPE_BRANCH, valid_type, false, boolean_operator_value_node.getToken()); // this._current_ast.add_node\n // Start by recursively evaluating the left side...\n // Note the type as it will be used to enforce type matching with the right side.\n let left_expression_type = this._add_expression_subtree(left_expression_node, UNDEFINED);\n // If it was an integer expression climb back up to the parent boolean expression node\n if (left_expression_node.children_nodes[0].name === NODE_NAME_INT_EXPRESSION) {\n while ((this._current_ast.current_node !== undefined || this._current_ast.current_node !== null)\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n if (this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n || this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n this._current_ast.climb_one_level();\n } // if\n } // while\n } // if\n // Ensures the correct order of nested operators in the ast.\n //\n // Look ahead in the tree on the left side of the \n // boolean expression and climb if it's an expression and not some value.\n if (left_expression_node.children_nodes[0].children_nodes[0].name == \"(\") {\n this._climb_ast_one_level();\n } // if\n // Then recursively deal with the right side...\n // To enforce type matching, use the left sides type as the parent type.\n let right_expression_type = this._add_expression_subtree(right_expression_node, left_expression_type);\n // If it was an integer expression climb back up to the parent boolean expression node\n if (right_expression_node.children_nodes[0].name === NODE_NAME_INT_EXPRESSION) {\n while ((this._current_ast.current_node !== undefined || this._current_ast.current_node !== null)\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n if (this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n || this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n this._current_ast.climb_one_level();\n } // if\n } // while\n } // if\n // Ensures the correct order of nested operators in the ast.\n //\n // Look ahead in the tree on the right side of the \n // boolean expression and climb if it's an expression and not some value.\n if (right_expression_node.children_nodes[0].children_nodes[0].name == \"(\") {\n this._climb_ast_one_level();\n } // if\n } // if\n // Boolean expression is: boolval\n else if (boolean_expression_node.children_nodes.length === 1) {\n this._current_ast.add_node(open_parenthesis_or_boolean_value_node.children_nodes[0].name, NODE_TYPE_LEAF, valid_type, false);\n } // else if\n // Boolean expression is neither: ( Expr BoolOp Expr ) NOR boolval...\n else {\n // Given a valid parse tree, this should never happen...\n throw Error(\"You messed up Parse: Boolean expression has no children, or negative children.\");\n } // else \n }", "function buildMathML(tree, texExpression, options) {\n const expression = buildExpression$1(tree, options); // Wrap up the expression in an mrow so it is presented in the semantics\n // tag correctly, unless it's a single <mrow> or <mtable>.\n\n let wrapper;\n\n if (expression.length === 1 && expression[0] instanceof MathNode && utils.contains([\"mrow\", \"mtable\"], expression[0].type)) {\n wrapper = expression[0];\n } else {\n wrapper = new mathMLTree.MathNode(\"mrow\", expression);\n } // Build a TeX annotation of the source\n\n\n const annotation = new mathMLTree.MathNode(\"annotation\", [new mathMLTree.TextNode(texExpression)]);\n annotation.setAttribute(\"encoding\", \"application/x-tex\");\n const semantics = new mathMLTree.MathNode(\"semantics\", [wrapper, annotation]);\n const math = new mathMLTree.MathNode(\"math\", [semantics]); // You can't style <math> nodes, so we wrap the node in a span.\n // NOTE: The span class is not typed to have <math> nodes as children, and\n // we don't want to make the children type more generic since the children\n // of span are expected to have more fields in `buildHtml` contexts.\n // $FlowFixMe\n\n return buildCommon.makeSpan([\"katex-mathml\"], [math]);\n }", "addAndThenExpression() {\n const thenExpression = AndThenExpression.new({\n leftExpression: this.assertionExpression,\n rightExpression: null,\n })\n\n this.assertionExpression = thenExpression\n }", "static from_nested_array(data) {\n \n // populate the queue with outermost elements\n var queue = new Array();\n for (var teData of data) {\n var toQueue = {'data': teData, 'children': [], 'parent': null};\n if (teData.length > 5) { toQueue['children'] = teData[5]; }\n queue.push(toQueue);\n }\n \n // go through queue and get elements until we've covered all\n var hierarchy = [];\n while (queue.length > 0) {\n \n // build the current templateElement\n var current = queue.shift();\n var te = VGVTemplateElement.from_array(current['data']);\n te.children = [];\n \n // deal with parentage\n if (current['parent']) {\n current['parent'].children.push(te); \n te.parent = current['parent']; \n }\n else { te.parent = null; hierarchy.push(te); }\n \n // add children to the queue\n if (current['children']) {\n for (var child of current['children']) { \n var toQueue = {'data': child, 'children': [], 'parent': te};\n if (child.length > 5) { toQueue['children'] = child[6]; }\n queue.push(toQueue);\n }\n }\n }\n return new VGVTemplateTooltip(hierarchy);\n }", "_handleNestedWhere(callback) {\r\n var query = new Query(); // Create a new instance for nested scope.\r\n callback.call(query, query);\r\n if (query._where) {\r\n this._where += \"(\" + query._where + \")\";\r\n this._bindings = this._bindings.concat(query._bindings);\r\n }\r\n return this;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses a string into an AST
parse(string) { this._string = string; this._tokenizer.init(string); // Prime the tokenizer to obtain the first // token which is our lookahead. The lookahead is // used for predictive parsing. this._lookahead = this._tokenizer.getNextToken(); return this.Program(); }
[ "function parse_StringExpr(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StringExpr()\" + '\\n';\n\tCSTREE.addNode('StringExpr', 'branch');\n\t\n\tmatchSpecChars(' \"',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\tparse_CharList();\n\n\t\n\tmatchSpecChars(' \"',parseCounter);\n\t\n\t\n\t\n\tparseCounter = parseCounter + 1;\n\t\n}", "function parseExpression() {\n let expr;\n //lookahead = lex();\n // if (!lookahead) { //significa que es white o undefined\n // lookahead = lex();\n // }\n if (lookahead.type == \"REGEXP\") {\n expr = new Regexp({type: \"regex\", regex: lookahead.value, flags: null});\n lookahead = lex();\n return expr;\n } else if (lookahead.type == \"STRING\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"NUMBER\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"WORD\") {\n const lookAheadValue = lookahead;\n lookahead = lex();\n if (lookahead.type == 'COMMA' && lookahead.value == ':') {\n expr = new Value({type: \"value\", value: '\"' + lookAheadValue.value + '\"'});\n return expr;\n }\n if (lookahead.type == 'DOT') {\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n }\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n } else if (lookahead.type == \"ERROR\") {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${lookahead.value}`);\n } else {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${program.slice(offset, offset + 10)}`);\n }\n}", "function parse(str) {\n\tif (str[0] !== '=') {\n\t\treturn;\n\t}\n\ttry {\n\t\tvar list = parser(str.slice(1).trim());\n\t\treturn {\n\t\t\tweights: pluck(list, 0),\n\t\t\tgenes: pluck(list, 1)\n\t\t};\n\t} catch (e) {\n\t\tconsole.log('parsing error', e);\n\t}\n\treturn;\n}", "function ExpressionParser() {\n \t\tthis.parse = function() {\n\t \t\treturn Statement(); \n\t \t}\n \t\t\n//\t\tStatement := Assignment | Expr\t\n\t\tthis.Statement=function() {return Statement();}\n\t \tfunction Statement() {\n\t \t\tdebugMsg(\"ExpressionParser : Statement\");\n\t\n \t var ast;\n \t // Expressin or Assignment ??\n \t if (lexer.skipLookAhead().type==\"assignmentOperator\") {\n \t \tast = Assignment(); \n \t } else {\n \t \tast = Expr();\n \t }\n \t return ast;\n\t \t}\n\t \t\n//\t\tAssignment := IdentSequence \"=\" Expr \n//\t\tAST: \"=\": l:target, r:source\n \t\tthis.Assignment = function() {return Assignment();}\n \t\tfunction Assignment() {\n \t\t\tdebugMsg(\"ExpressionParser : Assignment\");\n \t\t\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) return false;\n \t\t\n \t\t\tcheck(\"=\"); // Return if it's not an Assignment\n \t\t\n \t\t\tvar expr=Expr();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"=\",ident,expr);\n\t \t}\n \t\t\n\n//\t\tExpr := And {\"|\" And} \t\n//\t\tAST: \"|\": \"left\":And \"right\":And\n \t\tthis.Expr = function () {return Expr();}\t\n \t\tfunction Expr() {\n \t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\n \t\t\tvar ast=And();\n \t\t\tif (!ast) return false;\n \t\t\t\t\t\n \t\t\n \t\t\twhile (test(\"|\") && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"|\",ast,And());\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n \t\n//\t\tAnd := Comparison {\"&\" Comparison}\n//\t\tAST: \"&\": \"left\":Comparasion \"right\":Comparasion\t\n\t\tfunction And() {\n \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\tvar ast=Comparasion();\n \t\t\tif (!ast) return false;\n \t\t\t\t\n \t\t\twhile (test(\"&\") && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"&\",ast,Comparasion());\n\t \t\t}\n\t \t\treturn ast;\n\t \t}\n\t \t \t\n// \t\tComparison := Sum {(\"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" | \"in\") Sum}\n//\t\tAST: \"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" : \"left\":Sum \"right\":Sum\n\t\tfunction Comparasion() {\n \t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\tvar ast=Sum();\n\t\t\tif (!ast) return false;\n\t\t\n\t\t\twhile ((test(\"==\") ||\n\t\t\t\t\ttest(\"!=\") ||\n\t\t\t\t\ttest(\"<=\") ||\n\t\t\t\t\ttest(\">=\") ||\n\t\t\t\t\ttest(\"<\") ||\n\t\t\t\t\ttest(\">\")) ||\n\t\t\t\t\ttest(\"in\") &&\n\t\t\t\t\t!eof())\n\t\t\t{\n \t\t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\t\tvar symbol=lexer.current.content;\n\t\t\t\tlexer.next();\n\t \t\t\tast=new ASTBinaryNode(symbol,ast,Sum());\n\t\t\t} \t\n\t\t\treturn ast;\t\n\t \t}\n\t \t\n//\t\tSum := [\"+\" | \"-\"] Product {(\"+\" | \"-\") Product}\n//\t\tAST: \"+1\" | \"-1\" : l:Product\n//\t\tAST: \"+\" | \"-\" : l:Product | r:Product \n \t\tfunction Sum() {\n \t\t\tdebugMsg(\"ExpressionParser : Sum\");\n\t\t\n\t\t\tvar ast;\n\t\t\t// Handle Leading Sign\n\t\t\tif (test(\"+\") || test(\"-\")) {\n\t\t\t\tvar sign=lexer.current.content+\"1\";\n\t\t\t\tlexer.next();\n\t\t\t\tast=new ASTUnaryNode(sign,Product());\t\n\t \t\t} else {\n\t \t\t\tast=Product();\n\t \t\t} \n \t\t\t\n \t\t\twhile ((test(\"+\") || test(\"-\")) && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Sum\");\n \t\t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Product());\t\t\n \t\t\t} \t\n \t\t\treturn ast;\n \t\t}\n\n//\t\tProduct := Factor {(\"*\" | \"/\" | \"%\") Factor} \t\n\t \tfunction Product() {\n\t \t\tdebugMsg(\"ExpressionParser : Product\");\n\n \t\t\tvar ast=Factor();\n \t\t\n\t \t\twhile ((test(\"*\") || test(\"/\") || test(\"%\")) && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : Product\");\n\n\t \t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Factor());\n \t\t\t} \n\t \t\treturn ast;\n \t\t}\n \t\t\n// \t Factor := \t\t[(\"this\" | \"super\") \".\"]IdentSequence [\"(\" [Expr {\",\" Expr}] \")\"]\n//\t\t\t\t\t | \"!\" Expr \n//\t\t\t\t\t | \"(\" Expr \")\" \n//\t\t\t\t\t | Array \n//\t\t\t\t\t | Boolean\n//\t\t\t\t\t | Integer\n//\t\t\t\t\t | Number\n//\t\t\t\t\t | Character\n//\t\t\t\t\t | String \n \t\tfunction Factor() {\n \t\t\tdebugMsg(\"ExpressionParser : Factor\"+lexer.current.type);\n\n\t \t\tvar ast;\n \t\t\n\t \t\tswitch (lexer.current.type) {\n\t \t\t\t\n\t \t\t\tcase \"token\"\t:\n\t\t\t\t//\tAST: \"functionCall\": l:Ident(Name) r: [0..x]{Params}\n\t\t\t\t\tswitch (lexer.current.content) {\n\t\t\t\t\t\tcase \"new\": \n\t\t\t\t\t\t\tlexer.next();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar ident=Ident(true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcheck(\"(\");\n\t\t\t\t\t\t\n \t\t\t\t\t\t\tvar param=[];\n \t\t\t\t\t\t\tif(!test(\")\")){\n \t\t\t\t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\t\t\tparam[i]=Expr();\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t}\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\t\t\t\t\tast=new ASTBinaryNode(\"new\",ident,param);\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t\tcase \"this\":\n \t\t\t\t\t\tcase \"super\":\n\t\t\t\t\t\tcase \"constructor\": return IdentSequence();\n \t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n//\t\t\t\tFactor :=\tIdentSequence \t\t\t\t\n \t\t\t\tcase \"ident\":\n \t\t\t\t return IdentSequence();\n \t\t\t\tbreak;\n \t\t\t\t\n// \t\t\tFactor:= \"!\" Expr\t\t\t\n \t\t\t\tcase \"operator\": \n\t \t\t\t\tif (!test(\"!\")) {\n\t \t\t\t\t\terror.expressionExpected();\n\t \t\t\t\t\treturn false;\n \t\t\t\t\t}\n \t\t\t\t\tlexer.next();\n \t\t\t\t\n\t \t\t\t\tvar expr=Expr();\n \t\t\t\t\tast=new ASTUnaryNode(\"!\",expr);\n\t \t\t\tbreak;\n \t\t\t\t\n//\t\t\t\tFactor:= \"(\" Expr \")\" | Array \t\t\t\n \t\t\t\tcase \"brace\"\t:\n \t\t\t\t\tswitch (lexer.current.content) {\n \t\t\t\t\t\t\n// \t\t\t\t\t \"(\" Expr \")\"\n \t\t\t\t\t\tcase \"(\":\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\tast=Expr();\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\tbreak;\n \t\n \t\t\t\t\t\n \t\t\t\t\t\tdefault:\n \t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t \treturn false;\n\t \t\t\t\t\tbreak;\n\t \t\t\t\t}\n\t \t\t\tbreak;\n \t\t\t\n//\t\t\t\tFactor:= Boolean | Integer | Number | Character | String\n//\t\t\t\tAST: \"literal\": l: \"bool\" | \"int\" | \"float\" | \"string\" | \"char\": content: Value \n\t \t\t\tcase \"_$boolean\" \t\t:\t\t\t\n\t \t\t\tcase \"_$integer\" \t\t:\n\t \t\t\tcase \"_$number\" \t\t:\n\t \t\t\tcase \"_$string\"\t\t\t:\t\t\n\t\t\t\tcase \"_$character\"\t\t:\n\t\t\t\tcase \"null\"\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t\tast=new ASTUnaryNode(\"literal\",lexer.current);\n \t\t\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\tbreak;\n\t\t\t\t\n//\t\t\t\tNot A Factor \t\t\t\t \t\t\t\t\n \t\t\t\tdefault: \terror.expressionExpected();\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\treturn false;\n\t \t\t\t\t\t\tbreak;\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n\n \n//\t\tIdentSequence := (\"this\" | \"super\") | [(\"this\" | \"super\") \".\"] (\"constructor\" \"(\" [Expr {\",\" Expr}] \")\" | Ident {{ArrayIndex} | \".\" Ident } [\"(\" [Expr {\",\" Expr}] \")\"]);\n//\t\tAST: \"identSequence\": l: [0..x][\"_$this\"|\"_$super\"](\"constructor\" | Ident{Ident | ArrayIndex})\n// \t\tor AST: \"functionCall\": l:AST IdentSequence(Name), r: [0..x]{Params}\n\t\tthis.IdentSequence=function () {return IdentSequence();};\n \t\tfunction IdentSequence() {\n \t\t\tdebugMsg(\"ExpressionParser:IdentSequence()\");\n \t\t\t\n \t\t\tvar ast=new ASTListNode(\"identSequence\");\n \t\t\tif (test(\"this\") || test(\"super\")) {\n \t\t\t\tast.add({\"type\":\"ident\",\"content\":\"_$\"+lexer.current.content,\"line\":lexer.current.line,\"column\":lexer.current.column});\n \t\t\t\tlexer.next();\n \t\t\t\tif (!(test(\".\"))) return ast;\n \t\t\t\tlexer.next();\n \t\t\t}\n\n\t\t\tvar functionCall=false;\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tast.add({\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column});\n\t\t\t\tlexer.next();\n\t\t\t\tcheck(\"(\");\n\t\t\t\tfunctionCall=true;\n\t\t\t} else {\n \t\t\t\tvar ident=Ident(true);\n \t\t\t\n \t\t\t\tast.add(ident);\n \t\t\t\n \t\t\t\tvar index;\n \t\t\t\twhile((test(\".\") || test(\"[\")) && !eof()) {\n \t\t\t\t\t if (test(\".\")) {\n \t\t\t\t\t \tlexer.next();\n \t\t\t\t\t\tast.add(Ident(true));\n \t\t\t\t\t} else ast.add(ArrayIndex());\n \t\t\t\t}\n \t\t\t\tif (test(\"(\")) {\n \t\t\t\t\tfunctionCall=true;\n \t\t\t\t\tlexer.next();\n \t\t\t\t}\n \t\t\t}\n \t\n \t\t\tif (functionCall) {\t\n\t\t\t\tvar param=[];\n\t\t\t\tif(!test(\")\")){\n \t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\tparam[i]=Expr();\t\t\t\t\t\t\t\n \t\t\t\t\t}\n \t\t\t\t}\t \t\t\t\t\t\t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\tast=new ASTBinaryNode(\"functionCall\",ast,param);\n \t\t\t} \n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tArrayIndex:=\"[\" Expr \"]\"\n //\t\tAST: \"arrayIndex\": l: Expr\n \t\tfunction ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}\n\n//\t\tIdent := Letter {Letter | Digit | \"_\"}\n//\t\tAST: \"ident\", \"content\":Ident\n\t \tthis.Ident=function(forced) {return Ident(forced);}\n \t\tfunction Ident(forced) {\n \t\t\tdebugMsg(\"ExpressionParser:Ident(\"+forced+\")\");\n \t\t\tif (testType(\"ident\")) {\n \t\t\t\tvar ast=lexer.current;\n \t\t\t\tlexer.next();\n \t\t\t\treturn ast;\n \t\t\t} else {\n \t\t\t\tif (!forced) return false; \n \t\t\t\telse { \n \t\t\t\t\terror.identifierExpected();\n\t\t\t\t\treturn SystemIdentifier();\n\t\t\t\t}\n\t\t\t} \t\n \t\t}\n \t}", "function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}\n\t}", "static parseNode(ASTNode) {\n\n // To see all available types:\n // http://esprima.readthedocs.io/en/latest/syntax-tree-format.html\n const typeSwitcher = {\n\n /* A base-level token like 'x' */\n 'Identifier': (node) => {\n\n // Check if node is a Reduct reserved identifier (MissingExpression)\n if (node.name === '_' || node.name === '_b' || node.name === '__' || node.name === '_n') {\n let missing = new (ExprManager.getClass(node.name))();\n missing.__remain_unlocked = true;\n return missing;\n }\n else if (node.name.substring(0, 2) === '_t')\n return TypeInTextExpr.fromExprCode(node.name);\n else if (node.name === '_notch')\n return new (ExprManager.getClass('notch'))(1);\n else if (ExprManager.isPrimitive(node.name)) // If this is the name of a Reduct primitive (like 'star')...\n return this.makePrimitive(node.name);\n\n // Otherwise, treat this as a variable name...\n return new (ExprManager.getClass('var'))(node.name);\n },\n\n /* A primitive that's part of the language. Has 'value':\n boolean | number | string | RegExp | null\n and a corresponding 'raw' version, which is just the value-as-a-string.\n */\n 'Literal': (node) => {\n if (node.value instanceof RegExp) {\n console.error('Regular expressions are currently undefined.');\n return null;\n } else if (typeof node.value === 'string' || node.value instanceof String) {\n if (ExprManager.isPrimitive(node.value)) { // If this is the name of a Reduct primitive (like 'star')...\n return this.makePrimitive(node.value);\n }\n else { // Otherwise this stands for a \"string\" value.\n return new StringValueExpr(node.value);\n }\n } else if (Number.isNumber(node.value)) {\n return new (ExprManager.getClass('number'))(node.value);\n } else if (node.value === null) {\n return new NullExpr(0,0,64,64);\n } else { // Booleans should be left.\n return new (ExprManager.getClass(node.raw))();\n }\n },\n\n /* e.g. [2, true, x] */\n 'ArrayExpression': (node) => {\n let arr = new (ExprManager.getClass('array'))(0,0,54,54,[]);\n node.elements.forEach((e) => arr.addItem(this.parseNode(e)));\n return arr;\n },\n\n /* A single statement like (x == x); or (x) => x; */\n 'ExpressionStatement': (node) => {\n return this.parseNode(node.expression);\n },\n\n /* A function call of the form f(x) */\n 'CallExpression': (node) => {\n if (node.callee.type === 'Identifier' && node.callee.name === '$') {\n if (node.arguments.length === 0 || node.arguments.length > 1) {\n console.error('Malformed unlock expression $ with ' + node.arguments.length + ' arguments.');\n return null;\n } else {\n let unlocked_expr = this.parseNode(node.arguments[0]);\n unlocked_expr.unlock();\n unlocked_expr.__remain_unlocked = true; // When all inner expressions are locked in parse(), this won't be.\n return unlocked_expr;\n }\n } else if (node.callee.type === 'MemberExpression' && node.callee.property.name === 'map') {\n console.log(node.callee);\n return new (ExprManager.getClass('arrayobj'))(this.parseNode(node.callee.object), 'map', this.parseNode(node.arguments[0]));\n //return new (ExprManager.getClass('map'))(this.parseNode(node.arguments[0]), this.parseNode(node.callee.object));\n } else {\n console.error('Call expressions outside of the special $() unlock syntax are currently undefined.');\n return null;\n }\n },\n\n /* Anonymous functions of the form (x) => x */\n 'ArrowFunctionExpression': (node) => {\n if (node.params.length === 1 && node.params[0].type === 'Identifier') {\n // Return new Lambda expression (anonymous function) at current stage of concreteness.\n let lambda = new (ExprManager.getClass('lambda_abstraction'))([ new (ExprManager.getClass('hole'))(node.params[0].name) ]);\n if (node.body.type === 'Identifier' && node.body.name === 'xx') {\n lambda.addArg(this.parseNode( {type:'Identifier',name:'x'} ));\n lambda.addArg(this.parseNode( {type:'Identifier',name:'x'} ));\n }\n else if (node.body.type === 'Identifier' && node.body.name === 'xxx') {\n lambda.addArg(this.parseNode( {type:'Identifier',name:'x'} ));\n lambda.addArg(this.parseNode( {type:'Identifier',name:'x'} ));\n lambda.addArg(this.parseNode( {type:'Identifier',name:'x'} ));\n }\n else {\n let body = this.parseNode(node.body);\n lambda.addArg(body);\n }\n lambda.hole.__remain_unlocked = true;\n return lambda;\n } else {\n console.warn('Lambda expessions with more than one input are currently undefined.');\n return null;\n }\n },\n\n 'AssignmentExpression': (node) => {\n let result = new (ExprManager.getClass('assign'))(this.parseNode(node.left), this.parseNode(node.right));\n mag.Stage.getNodesWithClass(MissingExpression, [], true, [result]).forEach((n) => {\n n.__remain_unlocked = true;\n });\n return result;\n },\n\n /* BinaryExpression includes the operators:\n 'instanceof' | 'in' | '+' | '-' | '*' | '/' | '%' | '**' | '|' | '^' |\n '&' | '==' | '!=' | '===' | '!==' | '<' | '>' | '<=' | '<<' | '>>' | '>>>'\n */\n 'BinaryExpression': (node) => {\n if (node.operator === '>>>') { // Special typing-operators expression:\n let comp = new (ExprManager.getClass('=='))(this.parseNode(node.left), this.parseNode(node.right), '>>>');\n comp.holes[1] = TypeInTextExpr.fromExprCode('_t_equiv', (finalText) => {\n comp.funcName = finalText;\n }); // give it a nonexistent funcName\n return comp;\n }\n else if (ExprManager.hasClass(node.operator)) {\n let BinaryExprClass = ExprManager.getClass(node.operator);\n if (node.operator in CompareExpr.operatorMap())\n return new BinaryExprClass(this.parseNode(node.left), this.parseNode(node.right), node.operator);\n else\n return new BinaryExprClass(this.parseNode(node.left), this.parseNode(node.right));\n }\n },\n\n /* LogicalExpression includes && and || */\n 'LogicalExpression': (node) => {\n const map = { '&&':'and', '||':'or' };\n const op = map[node.operator];\n return new (ExprManager.getClass(op))(this.parseNode(node.left), this.parseNode(node.right), op);\n },\n\n 'UnaryExpression': (node) => {\n if (node.operator === '!') {\n return new (ExprManager.getClass('not'))(this.parseNode(node.argument), 'not');\n } else {\n console.warn('Unknown unary expression ' + node.operator + ' not supported at this time.');\n return null;\n }\n },\n\n /* Ternary expression ?: */\n 'ConditionalExpression': (node) => {\n return new (ExprManager.getClass('ifelse'))(this.parseNode(node.test), this.parseNode(node.consequent), this.parseNode(node.alternate));\n },\n\n /* A JS ES6 Class.\n In Reduct, an Object container.\n * TODO: Methods with the name _ should define unfilled 'notches' on the side of the object. *\n */\n 'ClassDeclaration': (node) => {\n let obj = new PlayPenExpr(node.id.name);\n let funcs = node.body.body.map((e) => this.parseNode(e));\n obj.setMethods(funcs);\n // TODO: Predefined methods, notches, floating exprs, etc.\n return obj;\n },\n 'MethodDefinition': (node) => { // This wraps a FunctionExpression for classes:\n if (node.key.name === '_notch') // extra notches inside objects\n return this.parseNode(node.key);\n node.value.id = node.key.name; // So that the FunctionExpression node parser knows the name of the function...\n return this.parseNode(node.value);\n },\n 'FunctionExpression': (node) => {\n return new DefineExpr(this.parseNode(node.body), node.id ? node.id : '???');\n },\n 'FunctionDeclaration': (node) => {\n return new DefineExpr(this.parseNode(node.body), node.id ? node.id.name : '???');\n },\n 'BlockStatement': (node) => {\n if (node.body.length === 1 && node.body[0].type === 'ReturnStatement') {\n return this.parseNode(node.body[0].argument);\n } else {\n console.error('Block expressions longer than a single return are not yet supported.');\n return null;\n }\n }\n }\n\n // Apply!\n if (ASTNode.type in typeSwitcher)\n return typeSwitcher[ASTNode.type](ASTNode);\n else {\n console.error('@ ES6Parser.parseNode: No converter specified for AST Node of type ' + ASTNode.type);\n return null;\n }\n }", "cfg2ast (cfg) {\n /* establish abstract syntax tree (AST) node generator */\n let asty = new ASTY()\n const AST = (type, ref) => {\n let ast = asty.create(type)\n if (typeof ref === \"object\" && ref instanceof Array && ref.length > 0)\n ref = ref[0]\n if (typeof ref === \"object\" && ref instanceof Tokenizr.Token)\n ast.pos(ref.line, ref.column, ref.pos)\n else if (typeof ref === \"object\" && asty.isA(ref))\n ast.pos(ref.pos().line, ref.pos().column, ref.pos().offset)\n return ast\n }\n\n /* establish lexical scanner */\n let lexer = new Tokenizr()\n lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/, (ctx, m) => {\n ctx.accept(\"id\")\n })\n lexer.rule(/[+-]?[0-9]+/, (ctx, m) => {\n ctx.accept(\"number\", parseInt(m[0]))\n })\n lexer.rule(/\"((?:\\\\\\\"|[^\\r\\n]+)+)\"/, (ctx, m) => {\n ctx.accept(\"string\", m[1].replace(/\\\\\"/g, \"\\\"\"))\n })\n lexer.rule(/\\/\\/[^\\r\\n]+\\r?\\n/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/[ \\t\\r\\n]+/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/./, (ctx, m) => {\n ctx.accept(\"char\")\n })\n\n /* establish recursive descent parser */\n let parser = {\n parseCfg () {\n let block = this.parseBlock()\n lexer.consume(\"EOF\")\n return AST(\"Section\", block).set({ ns: \"\" }).add(block)\n },\n parseBlock () {\n let items = []\n for (;;) {\n let item = lexer.alternatives(\n this.parseProperty.bind(this),\n this.parseSection.bind(this),\n this.parseEmpty.bind(this))\n if (item === undefined)\n break\n items.push(item)\n }\n return items\n },\n parseProperty () {\n let key = this.parseId()\n lexer.consume(\"char\", \"=\")\n let value = lexer.alternatives(\n this.parseNumber.bind(this),\n this.parseString.bind(this))\n return AST(\"Property\", value).set({ key: key.value, val: value.value })\n },\n parseSection () {\n let ns = this.parseId()\n lexer.consume(\"char\", \"{\")\n let block = this.parseBlock()\n lexer.consume(\"char\", \"}\")\n return AST(\"Section\", ns).set({ ns: ns.value }).add(block)\n },\n parseId () {\n return lexer.consume(\"id\")\n },\n parseNumber () {\n return lexer.consume(\"number\")\n },\n parseString () {\n return lexer.consume(\"string\")\n },\n parseEmpty () {\n return undefined\n }\n }\n\n /* parse syntax character string into abstract syntax tree (AST) */\n let ast\n try {\n lexer.input(cfg)\n ast = parser.parseCfg()\n }\n catch (ex) {\n console.log(ex.toString())\n process.exit(0)\n }\n return ast\n }", "function parseExpression(program) {\n program = skipSpace(program);\n let match, expr;\n // using 3 regex to spot either strings, #s or words\n if (match = /^\"([^\"]*)\"/.exec(program)) {\n expr = {type: \"value\", value: match[1]};\n } else if (match = /^\\d+\\b/.exec(program)) {\n expr = {type: \"value\", value: Number(match[0])};\n } else if (match = /^[^\\s(),#\"]+/.exec(program)) {\n expr = {type: \"word\", name: match[0]};\n } else {\n // if the input does not match any of the above 3 forms, it's not a valid expression\n // throw an error, specifically Syntax Error\n throw new SyntaxError(\"Unexpected syntax: \" + program);\n }\n// return what is matched and pass it along w/ the object for the expression to parseApply\n return parseApply(expr, program.slice(match[0].length));\n}", "function parseType() {\n var id;\n var params = [];\n var result = [];\n\n if (token.type === _tokenizer.tokens.identifier) {\n id = identifierFromToken(token);\n eatToken();\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.func)) {\n eatToken(); // (\n\n eatToken(); // func\n\n if (token.type === _tokenizer.tokens.closeParen) {\n eatToken(); // function with an empty signature, we can abort here\n\n return t.typeInstruction(id, t.signature([], []));\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.param)) {\n eatToken(); // (\n\n eatToken(); // param\n\n params = parseFuncParam();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.result)) {\n eatToken(); // (\n\n eatToken(); // result\n\n result = parseFuncResult();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.typeInstruction(id, t.signature(params, result));\n }", "function parseString(str, isCorrect) {\n if ((str.indexOf(\"+\") || str.indexOf(\"-\") || str.indexOf(\"{\") || str.indexOf(\"}\") || str.indexOf(\"|\")) < 0) {\n return {\"value\": str, \"code\": null};\n }\n\n //weird cases: {+Plantations.-plantations. / Plantations.|508}\n //have to remove /Plantations.\n if (str.indexOf('/') > -1) {\n let toRemove = \"/ \" + str.match(/\\+(.*)\\-/)[1];\n str = str.replace(toRemove, '');\n }\n\n //removing whitespace... necessary?\n // str = str.replace(/^\\s+|\\s+$/g,'');\n //if + comes before -\n if (str.indexOf('+') < str.indexOf('-')){\n value = isCorrect ? str.match(/\\+(.*)\\-/).pop() : str.match(/\\-(.*)\\|/).pop();\n } else {\n //if - comes before +\n value = isCorrect ? str.match(/\\-(.*)\\+/).pop() : str.match(/\\+(.*)\\|/).pop();\n }\n\n let code = str.match(/\\|(.*)/)[1];\n storeConceptCode(str, code);\n return {\"value\": value, \"code\": code};\n}", "parseSubmission(s) {\n // define the parser (babel) and the abstract syntax tree generated\n // from parsing the submission\n const babel = require(\"@babel/core\");\n const ast = babel.parse(s.getSubmission);\n // define iterating variable\n let i = 0;\n // define empty arrays for storing individual strings and tokens.\n // The array of strings is used to generate the array of tokens\n //let myStrings : Array<string> = []\n let myTokens = [];\n // myOriginalText = original strings from submission\n // myTypes = the type of expression of each string (e.g. NumericLiteral)\n let myOriginalText = [];\n let myTypes = [];\n // the parser traverses through the abstract syntax tree and adds\n // any strings that it passes through to the array of strings\n babel.traverse(ast, {\n enter(path) {\n myTypes.push(path.node.type);\n myOriginalText.push(path.node.name);\n }\n });\n // each string in the array of strings is used to create a new\n // token, which is then added to the array of tokens\n for (i = 0; i < myOriginalText.length; i++) {\n myTokens.push(new Token_1.default(myOriginalText[i], myTypes[i]));\n }\n // create a TokenManager that holds the array of tokens\n let myTokenManager = new TokenManager_1.default(myTokens);\n // return the TokenManager which holds all of the tokens generated\n // by the strings extracted from the original submission\n return myTokenManager;\n // t1 = new Token(originaltext1: String, identifier1: String)\n // t2 = new Token(originaltext2: String, identifier2: String)\n // ...\n // tokenList = new List<Token>\n // tokenList.add(t1)\n // tokenList.add(t2)\n // ...\n // tmanager = new TokenManager(tokenList)\n // this.tokenizedSubmission = tmanager\n }", "function lce_read_expr(input)\n{\n\tif (typeof input != 'string')\n\t{\n\t\treturn undefined;\n\t}\n\n\tvar i,j;\n\tvar current = undefined;\n\tvar temp;\n\tvar stack = [];\n\tvar MODE_EXPR = 0; // main mode, determines all type for all other expressions\n\tvar MODE_VARLIST = 1; // handles the function abstraction type, which has a restricted character set(meta-meanings)\n\tvar mode = MODE_EXPR;\n\tvar varstart = 0;\n\t\n\tfor (i = 0; i < input.length; i++)\n\t{\n\t\tif (mode == MODE_EXPR)\n\t\t{\n\t\t//recursively handle any parenthesis\n\t\t\tif (input[i] == '(')\n\t\t\t{\n\t\t\t\tj = findCloseBalance(input, i);\n\t\t\t\tif (j == -1)\n\t\t\t\t{\n\t\t\t\t\talert(\"Error: imbalance of parenthesis.\");\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\ttemp = lce_read_expr(input.substr(i+1, j-i-1));\n\t\t\t\tif (current == undefined)\n\t\t\t\t{\n\t\t\t\t\tcurrent = temp;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_app(current, temp);\n\t\t\t\t}\n\t\t\t\ti = j;\n\t\t\t\tvarstart = i + 1;\n\t\t\t}\n\t\t\t// detect the beginning of a functional abstraction\n\t\t\telse if (input[i] == '\\\\')\n\t\t\t{\n\t\t\t\tif (input.substr(i+1,6) == 'lambda')\n\t\t\t\t{\n\t\t\t\t\ti += 7;\n\t\t\t\t\tstack.push(new stack_pair(mode, current));\n\t\t\t\t\tmode = MODE_VARLIST;\n\t\t\t\t\tcurrent = new lce_expr_abs();\n\t\t\t\t\tvarstart = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// look for variable names and applications\n\t\t\telse if ((input[i].match(/\\s/) && strip_ws(input.substr(varstart,i+1-varstart)) != \"\")\n\t\t\t\t|| (i + 1 == input.length && strip_ws(input.substr(varstart,i+1-varstart)) != \"\"))\n\t\t\t{\n\t\t\t\tif (current == undefined)\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_var(input.substr(varstart,i+1-varstart));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_app(current, new lce_expr_var(input.substr(varstart,i+1-varstart)));\n\t\t\t\t}\n\t\t\t\tvarstart = i;\n\t\t\t}\n\t\t}\n\t\telse if (mode == MODE_VARLIST)\n\t\t{\n\t\t\t//detect the end of the variable list\n\t\t\tif (input[i] == '.')\n\t\t\t{\n\t\t\t\tif (current.varlist.length == 0)\n\t\t\t\t{\n\t\t\t\t\talert(\"Error: lambda without any bound variables.\");\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tstack.push(new stack_pair(mode, current));\n\t\t\t\tmode = MODE_EXPR;\n\t\t\t\tcurrent = undefined;\n\t\t\t\tvarstart = i + 1;\n\t\t\t}\n\t\t\t// detect illegal characters\n\t\t\telse if (input[i] == '\\\\' || input[i] == '(' || input[i] == ')')\n\t\t\t{\n\t\t\t\talert(\"Error: Illegal character, '\\\\', '(', ')' in variable list.\");\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\t// detect variable names and add to list\n\t\t\telse if ((input[i].match(/\\s/) && strip_ws(input.substr(varstart,i+1-varstart)) != \"\")\n\t\t\t\t|| ((i + 1 == input.length || input[i + 1] == '.') && strip_ws(input.substr(varstart,i+1-varstart)) != \"\"))\n\t\t\t{\n\t\t\t\tcurrent.addVar(input.substr(varstart,i+1-varstart));\n\t\t\t\tvarstart = i;\n\t\t\t}\n\t\t}\n\t}\n\n\t// unstack all stored partial results and combine into final result\n\twhile (stack.length > 0)\n\t{\n\t\tif (stack[stack.length - 1].mode == MODE_EXPR)\n\t\t{\n\t\t\tif (stack[stack.length - 1].expr != undefined)\n\t\t\t{\n\t\t\t\tif (current == undefined)\n\t\t\t\t{\n\t\t\t\t\tcurrent = stack[stack.length - 1].expr;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_app(stack[stack.length - 1].expr, current);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (stack[stack.length - 1].mode == MODE_VARLIST)\n\t\t{\n\t\t\tif (current == undefined)\n\t\t\t{\n\t\t\t\talert(\"Error: abstraction without sub-expression.\");\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tstack[stack.length - 1].expr.subexpr = current;\n\t\t\tcurrent = stack[stack.length - 1].expr;\n\t\t}\n\t\tstack.pop();\n\t}\n\t\n\treturn current;\n}", "function visit(text, visitor, options) {\n var _scanner = createScanner(text, false);\n function toNoArgVisit(visitFunction) {\n return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };\n }\n var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onError = toOneArgVisit(visitor.onError);\n var disallowComments = options && options.disallowComments;\n function scanNext() {\n while (true) {\n var token = _scanner.scan();\n switch (token) {\n case SyntaxKind.LineCommentTrivia:\n case SyntaxKind.BlockCommentTrivia:\n if (disallowComments) {\n handleError(ParseErrorCode.InvalidSymbol);\n }\n break;\n case SyntaxKind.Unknown:\n handleError(ParseErrorCode.InvalidSymbol);\n break;\n case SyntaxKind.Trivia:\n case SyntaxKind.LineBreakTrivia:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter, skipUntil) {\n if (skipUntilAfter === void 0) { skipUntilAfter = []; }\n if (skipUntil === void 0) { skipUntil = []; }\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n var token = _scanner.getToken();\n while (token !== SyntaxKind.EOF) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n var value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case SyntaxKind.NumericLiteral:\n var value = 0;\n try {\n value = JSON.parse(_scanner.getTokenValue());\n if (typeof value !== 'number') {\n handleError(ParseErrorCode.InvalidNumberFormat);\n value = 0;\n }\n }\n catch (e) {\n handleError(ParseErrorCode.InvalidNumberFormat);\n }\n onLiteralValue(value);\n break;\n case SyntaxKind.NullKeyword:\n onLiteralValue(null);\n break;\n case SyntaxKind.TrueKeyword:\n onLiteralValue(true);\n break;\n case SyntaxKind.FalseKeyword:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== SyntaxKind.StringLiteral) {\n handleError(ParseErrorCode.PropertyNameExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === SyntaxKind.ColonToken) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n }\n }\n else {\n handleError(ParseErrorCode.ColonExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n }\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n var needsComma = false;\n while (_scanner.getToken() !== SyntaxKind.CloseBraceToken && _scanner.getToken() !== SyntaxKind.EOF) {\n if (_scanner.getToken() === SyntaxKind.CommaToken) {\n if (!needsComma) {\n handleError(ParseErrorCode.ValueExpected, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n }\n else if (needsComma) {\n handleError(ParseErrorCode.CommaExpected, [], []);\n }\n if (!parseProperty()) {\n handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== SyntaxKind.CloseBraceToken) {\n handleError(ParseErrorCode.CloseBraceExpected, [SyntaxKind.CloseBraceToken], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n var needsComma = false;\n while (_scanner.getToken() !== SyntaxKind.CloseBracketToken && _scanner.getToken() !== SyntaxKind.EOF) {\n if (_scanner.getToken() === SyntaxKind.CommaToken) {\n if (!needsComma) {\n handleError(ParseErrorCode.ValueExpected, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n }\n else if (needsComma) {\n handleError(ParseErrorCode.CommaExpected, [], []);\n }\n if (!parseValue()) {\n handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (_scanner.getToken() !== SyntaxKind.CloseBracketToken) {\n handleError(ParseErrorCode.CloseBracketExpected, [SyntaxKind.CloseBracketToken], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case SyntaxKind.OpenBracketToken:\n return parseArray();\n case SyntaxKind.OpenBraceToken:\n return parseObject();\n case SyntaxKind.StringLiteral:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === SyntaxKind.EOF) {\n return true;\n }\n if (!parseValue()) {\n handleError(ParseErrorCode.ValueExpected, [], []);\n return false;\n }\n if (_scanner.getToken() !== SyntaxKind.EOF) {\n handleError(ParseErrorCode.EndOfFileExpected, [], []);\n }\n return true;\n }", "function parse() {\n var action;\n\n stackTop = 0;\n stateStack[0] = 0;\n stack[0] = null;\n lexicalToken = parserElement(true);\n state = 0;\n errorFlag = 0;\n errorCount = 0;\n\n if (isVerbose()) {\n console.log(\"Starting to parse\");\n parserPrintStack();\n }\n\n while(2 != 1) { // forever with break and return below\n action = parserAction(state, lexicalToken);\n if (action == ACCEPT) {\n if (isVerbose()) {\n console.log(\"Program Accepted\");\n }\n return 1;\n }\n\n if (action > 0) {\n if(parserShift(lexicalToken, action) == 0) {\n return 0;\n }\n lexicalToken = parserElement(false);\n if(errorFlag > 0) {\n errorFlag--; // properly recovering from error\n }\n } else if(action < 0) {\n if (parserReduce(lexicalToken, -action) == 0) {\n if(errorFlag == -1) {\n if(parserRecover() == 0) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n } else if(action == 0) {\n if (parserRecover() == 0) {\n return 0;\n }\n }\n }\n }", "function parseTree(text, errors, options) {\n if (errors === void 0) { errors = []; }\n var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n var visitor = {\n onObjectBegin: function (offset) {\n currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: function (name, offset, length) {\n currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });\n },\n onObjectEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: function (offset, length) {\n currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: function (value, offset, length) {\n onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: function (sep, offset, length) {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.columnOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: function (error) {\n errors.push({ error: error });\n }\n };\n visit(text, visitor, options);\n var result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}", "function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}", "function parseImport() {\n if (token.type !== _tokenizer.tokens.string) {\n throw new Error(\"Expected a string, \" + token.type + \" given.\");\n }\n\n var moduleName = token.value;\n eatToken();\n\n if (token.type !== _tokenizer.tokens.string) {\n throw new Error(\"Expected a string, \" + token.type + \" given.\");\n }\n\n var name = token.value;\n eatToken();\n eatTokenOfType(_tokenizer.tokens.openParen);\n var descr;\n\n if (isKeyword(token, _tokenizer.keywords.func)) {\n eatToken(); // keyword\n\n var fnParams = [];\n var fnResult = [];\n var typeRef;\n var fnName = t.identifier(getUniqueName(\"func\"));\n\n if (token.type === _tokenizer.tokens.identifier) {\n fnName = identifierFromToken(token);\n eatToken();\n }\n\n while (token.type === _tokenizer.tokens.openParen) {\n eatToken();\n\n if (lookaheadAndCheck(_tokenizer.keywords.type) === true) {\n eatToken();\n typeRef = parseTypeReference();\n } else if (lookaheadAndCheck(_tokenizer.keywords.param) === true) {\n eatToken();\n fnParams.push.apply(fnParams, _toConsumableArray(parseFuncParam()));\n } else if (lookaheadAndCheck(_tokenizer.keywords.result) === true) {\n eatToken();\n fnResult.push.apply(fnResult, _toConsumableArray(parseFuncResult()));\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in import of type\" + \", given \" + tokenToString(token));\n }();\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n if (typeof fnName === \"undefined\") {\n throw new Error(\"Imported function must have a name\");\n }\n\n descr = t.funcImportDescr(fnName, typeRef !== undefined ? typeRef : t.signature(fnParams, fnResult));\n } else if (isKeyword(token, _tokenizer.keywords.global)) {\n eatToken(); // keyword\n\n if (token.type === _tokenizer.tokens.openParen) {\n eatToken(); // (\n\n eatTokenOfType(_tokenizer.tokens.keyword); // mut keyword\n\n var valtype = token.value;\n eatToken();\n descr = t.globalType(valtype, \"var\");\n eatTokenOfType(_tokenizer.tokens.closeParen);\n } else {\n var _valtype = token.value;\n eatTokenOfType(_tokenizer.tokens.valtype);\n descr = t.globalType(_valtype, \"const\");\n }\n } else if (isKeyword(token, _tokenizer.keywords.memory) === true) {\n eatToken(); // Keyword\n\n descr = parseMemory();\n } else if (isKeyword(token, _tokenizer.keywords.table) === true) {\n eatToken(); // Keyword\n\n descr = parseTable();\n } else {\n throw new Error(\"Unsupported import type: \" + tokenToString(token));\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n return t.moduleImport(moduleName, name, descr);\n }", "function analyze_js(input, start, argPos) {\r\n\t\t\r\n\t// Set up starting variables\r\n\tvar currentArg\t\t= 1;\t\t\t\t // Only used if extracting argument position\r\n\tvar i\t\t\t\t\t= start;\t\t\t // Current character position\r\n\tvar length\t\t\t= input.length; // Length of document\r\n\tvar end\t\t\t\t= false;\t\t\t // Have we found the end?\r\n\tvar openObjects\t= 0;\t\t\t\t // Number of objects currently open\r\n\tvar openBrackets\t= 0;\t\t\t\t // Number of brackets currently open\r\n\tvar openArrays\t\t= 0;\t\t\t\t // Number of arrays currently open\r\n\t\r\n\t// Loop through input char by char\r\n\twhile ( end === false && i < length ) {\r\n\t\r\n\t\t// Extract current char\r\n\t\tvar currentChar = input.charAt(i);\r\n\t\r\n\t\t// Examine current char\r\n\t\tswitch ( currentChar ) {\r\n\t\t\r\n\t\t\t// String syntax\r\n\t\t\tcase '\"':\r\n\t\t\tcase \"'\":\r\n\t\t\t\r\n\t\t\t\t// Move up to the corresponding end of string position, taking\r\n\t\t\t\t// into account and escaping backslashes\r\n\t\t\t\twhile ( ( i = strpos(input, currentChar, i+1) ) && input.charAt(i-1) == '\\\\' );\r\n\t\t\t\r\n\t\t\t\t// False? Closing string delimiter not found... assume end of document \r\n\t\t\t\t// although technically we've screwed up (or the syntax is invalid)\r\n\t\t\t\tif ( i === false ) {\r\n\t\t\t\t\tend = length;\r\n\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\r\n\t\t\r\n\t\t\t// End of operation\r\n\t\t\tcase ';':\r\n\t\t\t\tend = i;\r\n\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t// Newlines\r\n\t\t\tcase \"\\n\":\r\n\t\t\tcase \"\\r\":\r\n\t\t\t\t\r\n\t\t\t\t// Newlines are ignored if we have an open bracket or array or object\r\n\t\t\t\tif ( openObjects || openBrackets || openArrays || argPos ) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\t// Newlines are also OK if followed by an opening function OR concatenation\r\n\t\t\t\t// e.g. someFunc\\n(params) or someVar \\n + anotherVar\r\n\t\t\t\t// Find next non-whitespace char position\r\n\t\t\t\tvar nextCharPos = i + strspn(input, \" \\t\\r\\n\", i+1) + 1;\r\n\t\t\t\t\r\n\t\t\t\t// And the char that refers to\r\n\t\t\t\tvar nextChar = input.charAt(nextCharPos);\r\n\t\t\t\t\r\n\t\t\t\t// Ensure not end of document and if not, char is allowed\r\n\t\t\t\tif ( nextCharPos <= length && ( nextChar == '(' || nextChar == '+' ) ) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Move up offset to our nextChar position and ignore this newline\r\n\t\t\t\t\ti = nextCharPos;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Still here? Newline not OK, set end to this position\r\n\t\t\t\tend = i;\r\n\t\t\t\tbreak;\r\n\r\n\r\n\t\t\t// Concatenation\r\n\t\t\tcase '+':\r\n\t\t\t\t// Our interest in the + operator is it's use in allowing an expression\r\n\t\t\t\t// to span multiple lines. If we come across a +, move past all whitespace,\r\n\t\t\t\t// including newlines (which would otherwise indicate end of expression).\r\n\t\t\t\ti += strspn(input, \" \\t\\r\\n\", i+1);\r\n\t\t\t\tbreak;\r\n\r\n\r\n\t\t\t// Opening chars (objects, parenthesis and arrays)\r\n\t\t\tcase '{':\r\n\t\t\t\t++openObjects;\r\n\t\t\t\tbreak;\r\n\t\t\tcase '(':\r\n\t\t\t\t++openBrackets;\r\n\t\t\t\tbreak;\r\n\t\t\tcase '[':\r\n\t\t\t\t++openArrays;\r\n\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t// Closing chars - is there a corresponding open char? \r\n\t\t\t// Yes = reduce stored count. No = end of statement.\r\n\t\t\tcase '}':\r\n\t\t\t\topenObjects\t ? --openObjects\t : end = i;\r\n\t\t\t\tbreak;\r\n\t\t\tcase ')':\r\n\t\t\t\topenBrackets ? --openBrackets : end = i;\r\n\t\t\t\tbreak;\r\n\t\t\tcase ']':\r\n\t\t\t\topenArrays\t ? --openArrays\t : end = i;\r\n\t\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t// Comma\r\n\t\t\tcase ',':\r\n\t\t\t\r\n\t\t\t\t// No interest here if not looking for argPos\r\n\t\t\t\tif ( ! argPos ) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Ignore commas inside other functions or whatnot\r\n\t\t\t\tif ( openObjects || openBrackets || openArrays ) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// End now\r\n\t\t\t\tif ( currentArg == argPos ) {\r\n\t\t\t\t\tend = i;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Increase the current argument number\r\n\t\t\t\t++currentArg;\r\n\t\t\t\t\r\n\t\t\t\t// If we're not after the first arg, start now?\r\n\t\t\t\tif ( currentArg == argPos ) {\r\n\t\t\t\t\tvar start = i+1;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t// Any other characters\r\n\t\t\tdefault:\r\n\t\t\t\t// Do nothing\r\n\t\t}\r\n\t\t\r\n\t\t// Increase offset\r\n\t\t++i;\r\n\t\r\n\t}\r\n\t\r\n\t// End not found? Use end of document\r\n\tif ( end === false ) {\r\n\t\tend = length;\r\n\t}\r\n\r\n\t// Return array of start/end if looking for argPos\r\n\tif ( argPos ) {\r\n\t\treturn [start, end];\r\n\t}\r\n\t\r\n\t// Return end\r\n\treturn end;\r\n\t\r\n}", "function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new db proxy to this cluster.
addProxy(id, options) { return new proxy_1.DatabaseProxy(this, id, { proxyTarget: proxy_1.ProxyTarget.fromCluster(this), ...options, }); }
[ "function register_proxy (uri, succeed, fail)\n{\n var options = url.parse(url.resolve(base, uri));\n \n test_host(options.hostname, \n function () {\n // local host so use local thing\n var thing = registry[options.href];\n \n if (thing)\n succeed(thing.thing);\n else // not yet created\n {\n console.log('waiting for ' + uri + ' to be created');\n record_handler(uri, succeed);\n }\n },\n function () {\n // remote host so find proxy\n console.log(options.hostname + \" is remote\");\n launch_proxy(options, succeed, fail);\n },\n function () {\n // unknown host name\n fail(\"server couldn't determine IP address for \" + options.hostname);\n });\n}", "addDataLayer(layer) {\n const newLayer = this._wrapper.createDataLayer({\n style: layer.style\n }).then(d => {\n if (layer.geoJson) {\n this.getDataFeatures(d, layer.geoJson).then(features => d.features = features);\n }\n\n return d;\n });\n\n this._layers.set(layer, newLayer);\n }", "function add(accessPoint) {\n\tlog.debug('adding ap data to db: %O', accessPoint)\n\treturn redis.pset(ACCESS_POINT_KEY(accessPoint.accessPointId), JSON.stringify(accessPoint))\n}", "proxy(aProxy = undefined) {\n if (!this._proxy) {\n assert(!this._runPromise); // do not create agents after run()\n assert(arguments.length === 1); // do not ask before setting\n assert(aProxy);\n this._proxy = aProxy;\n } else {\n assert(arguments.length === 0); // do not set twice\n }\n return this._proxy;\n }", "async function recreateProxy (serviceName, listenPort, proxyToPort) {\n try {\n await rp.delete({\n url: `${toxicli.host}/proxies/${serviceName}`\n })\n } catch (err) {}\n\n const proxy = await toxicli.createProxy({\n name: serviceName,\n listen: `0.0.0.0:${listenPort}`,\n upstream: `${serviceName}:${proxyToPort}`\n })\n\n // add some network latency simulation\n await proxy.addToxic(new toxiproxy.Toxic(proxy, {\n type: 'latency',\n attributes: {latency: 1, jitter: 1}\n }))\n\n // cause connections to be closed every some transferred bytes\n await proxy.addToxic(new toxiproxy.Toxic(proxy, {\n type: 'limit_data',\n attributes: {bytes: 5000}\n }))\n}", "addreplica(params) {\n this.options.qs = Object.assign({\n action: 'ADDREPLICA',\n }, params);\n\n return this.request(this.options);\n }", "function setProxyUrl(url) {\n proxyUrl = url;\n }", "function addProxyRule(url, proxy_type, proxy_location, proxy_port, active, global, caseinsensitive) {\n\t\n\tvar bkg = chrome.extension.getBackgroundPage();\n\t\n\t// uuid for the panels\n\tvar c = new Date().getTime();\n\t// draw the proxy rule\n\tvar htmlText = '<div class=\"proxy_rule_boxes fly_box\" id=\"proxy_rule_box_id_' + c + '\">' + $('#proxy_rules_template').html() + '</div>';\n\t// add the proxy rule box\n\t$('#proxy_rules_list').append(htmlText);\n\t// set up the parameters\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .url').html(url);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .url').keyup(function() { saveproxyRule() });\n\t\n\tif(typeof $('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type option')[proxy_type] != 'undefined')\n\t\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type option')[proxy_type].selected = true;\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type').change(function() { saveproxyRule() });\n\t\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_location').html(proxy_location);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_location').keyup(function() { saveproxyRule() });\n\t\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_port').html(proxy_port);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_port').keyup(function() { saveproxyRule() });\n\t\n\t// checkboxes\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .active').prop('checked', active ? 1 : 0);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .active').change(function() { saveproxyRule() });\n\t\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .global').prop('checked', global ? 1 : 0);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .global').change(function() { saveproxyRule() });\n\t\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .caseinsensitive').prop('checked', caseinsensitive ? 1 : 0);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .caseinsensitive').change(function() { saveproxyRule() });\n\n\t// attach the close button action\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .head a').click(\n\t\t\tfunction() {\n\t\t\t\tdeleteproxyRulePanel(c);\n\t\t\t}\n\t);\n\n\t// set active/inactive background on creation\n\tif(active!='1')\n\t\t$('#proxy_rules_list #proxy_rule_box_id_' + c).addClass('box_inactive');\n\n\t// attach active/inactive action\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .active').click(function() {\n\t\tif($(this).prop('checked'))\n\t\t\t$('#proxy_rules_list #proxy_rule_box_id_' + c).removeClass('box_inactive');\n\t\telse\n\t\t\t$('#proxy_rules_list #proxy_rule_box_id_' + c).addClass('box_inactive');\n\t});\n\n\t// attach even to hide/show unused fields depending of the proxy type\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type').change(function() {\n\t\tvar proxy_type = $('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type').prop(\"selectedIndex\");\t\n\t\tproxyTypeHideFields(proxy_type, c);\n\t} );\n\t\t\n\t// hide unused fields depending of proxy type\n\tproxyTypeHideFields(proxy_type, c);\n\t\n\t// make the pop-out animation effect\n\twindow.setTimeout( function() { $('#proxy_rules_list #proxy_rule_box_id_' + c).addClass('fly_box-zoomed');} , 100);\n\t\n\tsanitizeContenteditableDivs();\n}", "function addKoditoDB(discoveredData) {\r\n const ip = discoveredData.addresses[0];\r\n const httpPort = discoveredData.port;\r\n const reachable = true;\r\n const name = discoveredData.fullname.replace(/\\._xbmc-jsonrpc-h\\._tcp\\.local/g, \"\");\r\n const username = \"kodi\"; // Preparation for user pass setting.\r\n const password = \"kodi\"; // Preperation for user pass setting.\r\n\r\n kodiConnector.getMac(ip).then(mac => {\r\n console.log(`KODIdb: Discovered KODI instance with IP:${ip}, PORT:${httpPort}, MAC:${mac}, NAME:${name}.`);\r\n const ws = new kodiConnector(mac, ip, httpPort, username, password);\r\n kodiDB[mac] = { name, ip, httpPort, mac, reachable, ws };\r\n\r\n kodiDB[mac].ws.events.on(\"notification\", x => {\r\n handleKodiEvents(x);\r\n });\r\n\r\n kodiDB[mac].ws.events.on(\"connected\", x => {\r\n setTimeout(() => {\r\n conectedMessage(x.mac);\r\n }, 5000);\r\n });\r\n\r\n if (mac == discoveryConnect) {\r\n kodiDB[mac].ws.connect();\r\n }\r\n });\r\n}", "function DBCluster(props) {\n return __assign({ Type: 'AWS::Neptune::DBCluster' }, props);\n }", "function AddNewLayer(){\r\n /**\r\n * adding new layer to network.\r\n *\r\n */\r\n\tnewlayer = new Layer();\r\n\tcounter++;\r\n\tlayerslist.push(newlayer);\r\n\tcreateLayer(counter);\r\n}", "function register_proxy (uri, handler)\n{\n var options = url.parse(url.resolve(base, uri));\n\n // is this thing hosted by this server?\n if (options.host === baseUri.host) {\n return record_proxy(options.pathname, handler);\n }\n \n // otherwise on a remote server, so use HTTP to retrieve model\n \n return http.get (options, function(response) {\n var body = '';\n response.on('data', function(d) {\n body += d;\n });\n\n response.on('end', function() {\n try {\n var model = JSON.parse(body);\n \n // now get a socket for the remote server\n // first check if one already exists\n \n var ws = sockets[url.format(options)];\n \n if (ws)\n create_proxy(uri, model, ws, handler);\n else // we need to open a connection\n { \n ws = new WebSocket('ws://www.host.com/path');\n \n ws.on('open', function() {\n sockets[options.host] = ws;\n create_proxy(uri, model, ws, handler);\n });\n \n ws.on('message', function(message) {\n console.log('received: %s', message);\n });\n \n ws.on('close', function(message) {\n delete framework.sockets[options.host];\n \n });\n }\n } catch (e) {\n fail (\"couldn't load \" + uri + \", \" + e);\n }\n });\n \n response.on('error', function(err) {\n fail (\"couldn't load \" + uri + \", error: \" + err);\n });\n });\n}", "function addNew(newHost) {\n const host = addItem(hosts, newHost);\n return host;\n}", "function addPeer(gun, ip, port) {\n //const oldPeers = gun.opt()['_'].opt.peers;\n return gun.opt({peers: [`http: *${ip}:${port}/gun`]}); // Should these be linked both ways?\n }", "set gw( gw )\n {\n this.gateways.push( gw );\n }", "function connect(poolConfig) {\n return new Db(pg.Pool(poolConfig));\n}", "addAddressDataToLevelDB(address, value) {\n return new Promise((resolve, reject) => {\n addressdb.put(address, value, (err) => {\n if (err) {\n reject(err);\n }\n resolve(`Address data of #${address} is added.`);\n });\n });\n }", "function createDBDelegate(funcName) {\n return function(db, ...args) {\n if (db) {\n try {\n return db[funcName](...args);\n } catch (e) {\n cal.ERROR(\"Error calling '\" + funcName + \"' db error: '\" +\n lastErrorString(db) + \"'.\\nException: \" + e);\n cal.WARN(cal.STACK(10));\n }\n }\n };\n}", "async function addDataToPool(newData, newMetaData){\n dataPool.unshift({data:newData, meta:newMetaData})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set listeners on given date input
function setListenersDate(element){ element.addEventListener("focus", function(){eventFocusOnDate(element);}); element.addEventListener("blur", function(event){eventLostFocusOnDate(element, event);}); element.addEventListener("keyup", function(){eventKeyUp(element);}); }
[ "function setDateHandlers(field){\n \n $(field).on({\n \n // On focus...\n \n 'focus': function(event){\n \n // Remove validation\n \n $(this).removeClass('invalid');\n \n // Show date picker if not shown already\n \n if(!$(this).siblings('.date-picker').is(':visible')){\n \n showDatePicker(this);\n \n }\n \n },\n \n // On defocus, validate\n \n 'blur': function(event){\n \n // If valid date, format\n \n if(isValidDate($(this).val())){\n \n let date = new Date($(this).val());\n $(this).val(zeroPad(date.getMonth() + 1, 2) + '/' + zeroPad(date.getDate(), 2) + '/' + date.getFullYear());\n \n }\n \n // Otherwise, make invalid\n \n else if($(this).val().length > 0){\n \n $(this).addClass('invalid');\n \n }\n \n },\n \n // On tab, hide date picker\n \n 'keydown': function(event){\n \n if(event.which == 9){\n \n $(this).siblings('.date-picker').hide();\n \n }\n \n },\n \n // On typing...\n \n 'keyup': function(event){\n \n // Get current cursor position\n \n let cursorPosition = this.selectionStart;\n \n // Remove non-date characters\n \n let value = $(this).val();\n $(this).val(value.replace(/[^0-9\\/]/g, ''));\n \n // If if typed character was removed, adjust cursor position\n \n let startLength = value.length;\n let endLength = $(this).val().length;\n \n if(startLength > endLength){\n \n setCursorPosition(this, cursorPosition - 1);\n \n }\n \n // If valid date, adjust date picker\n \n if(isValidDate($(this).val())){\n \n showDatePicker(this);\n \n }\n \n }\n \n });\n \n}", "function addcalendarExtenderToDateInputs () {\n //get and loop all the input[type=date]s in the page that dont have \"haveCal\" class yet\n var dateInputs = document.querySelectorAll('input[type=date]:not(.haveCal)');\n [].forEach.call(dateInputs, function (dateInput) {\n //call calendarExtender function on the input\n new calendarExtender(dateInput);\n //mark that it have calendar\n dateInput.classList.add('haveCal');\n });\n}", "function prepareListener() {\n var droppy;\n droppy = document.getElementById(\"datecheck\");\n droppy.addEventListener(\"change\",getDoctors);\n}", "function initCal() {\n const cal = document.querySelector('#calendar');\n const datepicker = new Datepicker(cal, {\n autohide: true\n });\n \n cal.addEventListener('changeDate', updatePlaykit);\n}", "function processChange(value) {\n //console.log(\"Calendar clicked\");\n //If we are working with the start input\n if(cntrl.getStartCal()) {\n cntrl.setSelectedStartDate(value); \n }\n //If we are working with the end input\n else {\n cntrl.setSelectedEndDate(value);\n }\n //Autoclose after selection\n cntrl.updateDateRange();\n }", "function updateChosenDate(inputDate){\n setChosenDate(inputDate);\n }", "_listenDateFormatSelected() {\n var self = this;\n self.m_dateFormatChangeHandler = function (e) {\n if (!self.m_selected)\n return;\n var $selected = $(e.target).find(':selected');\n var value = $selected.val();\n var domPlayerData = self._getBlockPlayerData();\n var xSnippet = $(domPlayerData).find('XmlItem');\n $(xSnippet).attr('dateFormat', value);\n self._setBlockPlayerData(domPlayerData);\n };\n $(Elements.JSON_ITEM_DATE_FORMAT, self.$el).on('change', self.m_dateFormatChangeHandler);\n }", "function datePickerHook() {\n $('.select-options li').each(function () {\n $(this).on('click', function () {\n let startMonth = document.getElementById('date-range--start-month')\n .value\n let startYear = document.getElementById('date-range--start-year').value\n let endMonth = document.getElementById('date-range--end-month').value\n let endYear = document.getElementById('date-range--end-year').value\n const facetDate = document.getElementsByClassName(\n 'facetwp-facet-publish_date'\n )[0]\n\n facetDate.querySelectorAll('.fs-option').forEach(function (el) {\n const startDate = new Date(startYear, startMonth, 1)\n const endDate = new Date(endYear, endMonth, 1)\n const elDate = new Date(\n el.getAttribute('data-value').slice(0, 4),\n el.getAttribute('data-value').slice(4, 6) - 1,\n 1\n )\n if (elDate >= startDate && elDate <= endDate) {\n el.click()\n }\n })\n })\n })\n }", "function eventFocusOnDate(element){\n\tsetInputFormat(element);\n\tvar popup = element.parentNode.querySelector('.popup-date-picker');\n\tdisplayPopup(popup);\n}", "function handleDiliveryDateChange(e) {\n setDeliveryDate(e.target.value)\n setDrawer(false)\n }", "function handleDay(e) {\n\t\tsetDay(e.target.value)\n\t}", "function departureDateHandler() {\n\thandlePastDate();\t\t\t\t\t\t// Ensures that a past date is handled.\n\tdateInverter();\t\t\t\t\t\t\t// Inverts dates if necessary.\n}", "set_date(year, month) {\n if (year == null) {\n var d = new Date(),\n month = d.getMonth(),\n year = d.getFullYear();\n }\n\n var d1 = new Date(year, month + 1, 0);\n this.month = d1.getMonth();\n this.year = d1.getFullYear();\n this.num_days = d1.getDate();\n this.show_date(d1);\n }", "updateDateField(dateField) {\n const me = this;\n\n dateField.on({\n change({ userAction, value }) {\n if (userAction && !me.$isInternalChange) {\n me._isUserAction = true;\n me.value = value;\n me._isUserAction = false;\n }\n },\n thisObj : me\n });\n }", "function changeDay(){\n $(date_picker).val($(this).data('day'));\n}", "setListener(cell) {\n var self = this;\n switch(cell.type) {\n case 'date':\n cell.$td.on('focus', function(event) {\n cell.clearError();\n var $dateInput = $('<input value=\"' + cell.contents + '\">');\n $dateInput.css('width', '85px');\n $(this).empty();\n $(this).append($dateInput);\n var startDate = cell.contents ? cell.contents : new Date().toLocaleDateString(\"en-US\");\n\n var picker = datepicker($dateInput.get(0), (date) => {\n cell.contents = formatSlashDate(date);\n cell.columnInfo.set_column(self.item, cell.contents);\n self.sendUpdate();\n });\n $dateInput.on('focusout', function(event) {\n cell.$td.text(cell.contents);\n if(cell.errorMessage) {\n cell.showError(cell.errorMessage);\n }\n });\n\n $dateInput.focus();\n });\n break;\n // TODO: fill these options in\n case 'money':\n cell.$td.on('focusin', function(event) {\n cell.clearError($(this));\n cell.setText(unFormatMoney(cell.getText()));\n $(this).selectText();\n });\n cell.$td.on('focusout', function(event) {\n // HACK: event firing multiple times causes\n // text to go to $0.00 without this\n var text = cell.getText().replace('$', '')\n if(text == undefined) {\n return;\n }\n\n if(!isNaN(text)) {\n var amt = parseFloat(text);\n $(this).attr('value', amt);\n cell.contents = amt;\n // cell.setText(formatMoney(amt));\n cell.columnInfo.set_column(self.item, cell.contents);\n self.sendUpdate();\n } else {\n cell.setText(\"$0.00\");\n }\n });\n break;\n case 'selector':\n cell.$td.on('focus', event => {\n cell.clearError();\n cell.$td.empty();\n var datalist = self.makeSelectInput(cell);\n cell.$td.append(datalist);\n\n var $input = $(datalist[0]);\n $input.focus();\n $input.select();\n });\n \n break;\n case 'number':\n cell.$td.on('focusin', event => {\n cell.clearError();\n cell.$td.selectText();\n });\n cell.$td.on('focusout', event => {\n if(!isNaN(cell.getText())) {\n cell.setText()\n cell.columnInfo.set_column(self.item, cell.contents);\n self.sendUpdate();\n } else {\n cell.$td.text(\"0\");\n }\n });\n break;\n default: // type 'text'\n cell.$td.on('focusin', function(event) {\n cell.clearError($(this));\n $(this).selectText(); \n });\n cell.$td.on('focusout', function(event) {\n cell.setText();\n cell.columnInfo.set_column(self.item, cell.contents);\n self.sendUpdate();\n });\n break;\n }\n }", "function parseInputs(e) {\r\n e.preventDefault();\r\n let startDate = document.querySelector(\"#startDate\");\r\n let endDate = document.querySelector(\"#endDate\");\r\n startDate = new Date(startDate.value).getTime();\r\n endDate = new Date(endDate.value).getTime();\r\n\r\n if (!startDate || ! endDate || endDate - startDate <= 0) {\r\n alert(\"start date must be > end date\");\r\n return;\r\n } else {\r\n onSubmit(startDate, endDate)\r\n }\r\n }", "function fieldChanged(type, name, linenum) {\r\n\t\r\n\tsetStatusSetDate(name);\r\n\t\r\n}", "function enableDatePicker () {\n $('input[data-field-type=date]').datepicker({\n autoclose: true, // close on loast focus\n orientation: 'top auto', // show above the fiels\n todayBtn: 'linked', // show button to return to 'today'\n todayHighlight: true, // highlight current day\n endDate: '+1y', // set max date to +1 year\n startDate: '0d', // set the minimum date to today\n maxViewMode: 'decade' // set maximum zoom out to decades view\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: extPart.getInsertString DESCRIPTION: Get the text to be inserted for at a given location ARGUMENTS: groupName ext data group filename partName ext data participant filename paramObj insertLocation RETURNS: array of strings to be inserted at the given location
function extPart_getInsertString(groupName, partName, paramObj, insertLocation) { var retVal = ""; if (!insertLocation || extPart.getLocation(partName).indexOf(insertLocation) == 0) { var paramArray = extPart.expandParameterObject(groupName, partName, paramObj); for (var i=0; i < paramArray.length; i++) { retVal += extUtils.replaceParamsInStr(extPart.getRawInsertText(partName), paramArray[i]); //DEBUG alert("extPart.getRawInsertText(partName) = " + extPart.getRawInsertText(partName) + "\nparamArray[i] = " + paramArray[i] + "\nretVal = " + retVal); } } else if (extPart.getLocation(partName).indexOf("wrapSelection") == 0) { if (insertLocation == "beforeSelection" || insertLocation == "afterSelection") { var paramArray = extPart.expandParameterObject(groupName, partName, paramObj); for (var i=0; i < paramArray.length; i++) { //get the insert text var insertText = extUtils.replaceParamsInStr(extPart.getRawInsertText(partName), paramArray[i]); //search for the tag name within the insertText var match = insertText.match(/<([^<>%\s]+)/g); if (match && (match.length > 0)) { for (var i = 0; i < match.length; i ++) { match[i] = match[i].substring(1); } if (insertLocation == "beforeSelection") { // check if insert text already has a close tag, and remove it if found var closeTagPos = insertText.search(RegExp("<\\/"+ match[match.length-1], "i")); if (closeTagPos != -1) { insertText = insertText.substring(0, closeTagPos); } retVal += insertText; } else if (insertLocation == "afterSelection") { // Closing tags go on in reverse order for (var i = (match.length - 1); i >= 0; i--) { retVal += "</" + match[i] + ">"; } } } } } } return retVal; }
[ "function extGroup_getInsertStrings(groupName, paramObj, insertLocation)\n{\n var retVal = new Array();\n var partNames = extGroup.getParticipantNames(groupName);\n for (var i=0; i < partNames.length; i++)\n {\n theStr = extPart.getInsertString(groupName, partNames[i], paramObj, insertLocation);\n if (theStr)\n {\n retVal.push(theStr);\n }\n }\n\n return retVal;\n}", "function extPart_getRawInsertText(partName)\n{\n return dw.getExtDataValue(partName, \"insertText\");\n}", "function extGroup_getParticipantNames(groupName, insertLocation)\n{\n var partNames = dw.getExtDataArray(groupName, \"groupParticipants\");\n var retPartNames = new Array();\n\n for (var i=0; i < partNames.length; i++)\n {\n if (!insertLocation || extPart.getLocation(partNames[i]).indexOf(insertLocation) == 0)\n {\n retPartNames.push(partNames[i]);\n }\n }\n return retPartNames;\n}", "function extPart_getLocation(partName)\n{\n return dw.getExtDataValue(partName, \"insertText\", \"location\");\n}", "function extPart_getInsertText(partName, paramObj)\n{\n var retVal = extPart.getRawInsertText(partName);\n retVal = extUtils.replaceParamsInStr(retVal, paramObj); //replace any parameters in text\n\n //remove new lines from attributes.\n if (extPart.getLocation(partName).indexOf(\"nodeAttribute\") == 0)\n {\n retVal = retVal.replace(/[\\f\\n\\r]\\s*$/,\"\");\n }\n\n return retVal;\n}", "function extPart_getInsertNode(partName, paramObj)\n{\n var retVal = '';\n var nodeParamName = extPart.getNodeParamName(partName);\n if (extPart.getIsNodeRel(partName)) {\n if (nodeParamName) {\n retVal = paramObj[nodeParamName]; //get node from paramObj.prop\n } else {\n alert(MM.MSG_NoNodeSpecForRelInsert);\n }\n }\n return retVal;\n}", "function extGroup_partPositionMatchesGroup(groupName, partGroup, part, partList)\n{\n var retVal = true;\n\n for (var i=0; retVal && i < partGroup.length; i++)\n {\n var groupPart = partGroup[i];\n\n //only check parts which are both selection relative inserts or aboveHTML and\n // whose search locations match (so we can use the nodeNumber property)\n // Note that for 'aboveHTML' insert locations, we ONLY care if the location weights\n // are the same too.\n if ( (extPart.getIsSelectionRel(part.participantName) && extPart.getIsSelectionRel(groupPart.participantName))\n || (extPart.getIsAroundNode(part.participantName) && extPart.getIsAroundNode(groupPart.participantName))\n || ( extPart.getLocation(part.participantName).indexOf(\"aboveHTML\") != -1\n && extPart.getLocation(part.participantName) == extPart.getLocation(groupPart.participantName)\n )\n )\n {\n //assign the partBefore to the groupPart. This function is probably\n //being called in the group file order, which means the new part\n //would be after any previous parts most of the time.\n var partBefore = groupPart;\n var partAfter = part;\n\n // if they have the same insert location, check their order in the file\n var groupPartLoc = extPart.getLocation(groupPart.participantName);\n var partLoc = extPart.getLocation(part.participantName);\n if (partLoc == groupPartLoc)\n {\n var names = extGroup.getParticipantNames(groupName);\n for (var j=0; j < names.length; j++)\n {\n if (names[j] == groupPart.participantName)\n {\n break;\n }\n else if (names[j] == part.participantName)\n { //swap the order\n partBefore = part;\n partAfter = groupPart;\n break;\n }\n }\n }\n else\n {\n //because the locations are different,\n // use [before, replace, after] as the order.\n if (groupPartLoc.indexOf(\"after\") != -1 ||\n (groupPartLoc.indexOf(\"replace\") != -1 &&\n partLoc.indexOf(\"before\") != -1) )\n {\n partBefore = part;\n partAfter = groupPart;\n }\n }\n\n //check to see if partBefore is between partAfter and the node before it,\n // and partAfter is between partBefore and the node after it\n if ( partBefore.position != null && partAfter.position != null\n && partBefore.position < partAfter.position\n )\n {\n //now check that if parts of the same kind are between them, they are paired\n var count = 0;\n for (var j=partBefore.position + 1; j < partAfter.position; j++)\n {\n if (partList[j].participantName == partBefore.participantName)\n {\n count++;\n }\n if (partList[j].participantName == partAfter.participantName)\n {\n count--;\n }\n if (count < 0)\n { //found partAfter first, bad position\n retVal = false;\n break;\n }\n }\n if (retVal && count != 0)\n { //parts did not match, bad position\n retVal = false;\n }\n\n }\n else\n {\n retVal = false;\n }\n }\n }\n\n return retVal;\n}", "function extPart_findInString(partName, theStr, findMultiple)\n{\n var retVal = null;\n var searchPatts = extPart.getSearchPatterns(partName);\n var quickSearch = extPart.getQuickSearch(partName);\n if (extUtils.findPatternsInString(theStr, quickSearch, searchPatts, findMultiple))\n {\n retVal = extUtils.extractParameters(searchPatts);\n }\n else if (extPart.DEBUG)\n {\n var MSG = new Array();\n MSG.push(\"match failed for participant: \" + partName);\n MSG.push(\"\");\n MSG.push(\"against string:\");\n MSG.push(theStr);\n MSG.push(\"\");\n MSG.push(\"using pattern:\");\n if (quickSearch && theStr.indexOf(quickSearch) == -1) {\n MSG.push(quickSearch);\n }\n else\n {\n for (var j=0; j < searchPatts.length; j++) {\n if (!searchPatts[j].match || !searchPatts[j].match.length) {\n MSG.push(searchPatts[j].pattern);\n }\n }\n }\n alert(MSG.join(\"\\n\"));\n }\n\n return retVal;\n}", "function extPart_queueDocEdits(groupName, partName, paramObj, sbObj)\n{\n var location = extPart.getLocation(partName);\n \n // NOTE: This only updates the location for insertion.\n // Finds will need to be done separately, if they\n // rely on this new location.\n if (paramObj.MM_location != null)\n {\n location = paramObj.MM_location;\n }\n\n // Check that we have an insert location and insert text. Also check that we\n // have a prior node, or we have insert text. If we do not have a prior node\n // and have no insert text, the participant should be ignored. This may happen\n // if the entire participant is conditional and the condition fails.\n if ( location && extPart.getRawInsertText(partName)\n && ( (sbObj && sbObj.getNamedSBPart(partName))\n || extPart.getInsertText(partName, paramObj)\n )\n )\n {\n var sbPartList = (sbObj) ? sbObj.getParticipants() : new Array(); // existing SBParticipants\n var sbPart = null; // SBParticipant\n\n var paramArray = extPart.expandParameterObject(groupName, partName, paramObj);\n\n if (extPart.DEBUG && paramArray.length == 0) {\n alert(\"skipping participant \" + partName + \", with empty parameter\");\n }\n\n var priorNodeSegmentArray = null;\n var deleteNodeSegmentArray = null;\n if (extPart.getPartType(groupName, partName) == \"multiple\") {\n\n priorNodeSegmentArray = new Array();\n deleteNodeSegmentArray = new Array();\n\n //find the priorNodeSegments for each parameter object\n\n var partList = dw.getParticipants(partName);\n for (var j=0; partList && j < partList.length; j++) {\n //get the node information\n extPart.extractNodeParam(partName, partList[j].parameters, partList[j].participantNode);\n }\n\n for (var i=0; i < paramArray.length; i++) {\n if (sbObj && !sbObj.getForceMultipleUpdate())\n {\n for (var j=0; j < sbPartList.length; j++)\n {\n if ( sbPartList[j].getName() == partName\n && extPart.parametersMatch(partName, paramArray[i], sbPartList[j].getParameters())\n )\n {\n priorNodeSegmentArray.push(sbPartList[j].getNodeSegment());\n break;\n }\n }\n }\n\n if (!sbObj || j == sbPartList.length) {\n\n var existingNodeSegment = null;\n\n //look for an existing match on the page,\n //if the insert location is aboveHTML, belowHTML, or the child of a node\n if ((!sbObj || !sbObj.getForceMultipleUpdate()) &&\n (location.indexOf(\"aboveHTML\") != -1 ||\n location.indexOf(\"belowHTML\") != -1 ||\n location.indexOf(\"firstChildOfNode\") != -1 ||\n location.indexOf(\"lastChildOfNode\") != -1))\n {\n if (partList)\n {\n //select the correct match and assign it to existingNode\n for (var j=0; j < partList.length; j++)\n {\n //if we have a match, set existingNode and break\n if (extPart.parametersMatch(partName, paramArray[i], partList[j].parameters))\n {\n if (extPart.getVersion(partName) >= 5.0)\n {\n existingNodeSegment = new NodeSegment(partList[j].participantNode, partList[j].matchRangeMin, partList[j].matchRangeMax);\n }\n else\n {\n existingNodeSegment = new NodeSegment(partList[j].participantNode);\n }\n break;\n }\n }\n }\n }\n\n priorNodeSegmentArray.push(existingNodeSegment);\n }\n }\n\n //identify the prior nodes which need to be deleted\n //(no need to delete attributes because their values get replaced anyhow\n if (sbObj && location.indexOf(\"nodeAttribute+\") == -1) {\n for (var i=0; i < sbPartList.length; i++) {\n var nodeSegment = sbPartList[i].getNodeSegment();\n if (sbPartList[i].getName() == partName) {\n for (var j=0; j < priorNodeSegmentArray.length; j++) {\n if (priorNodeSegmentArray[j] != null &&\n nodeSegment.equals(priorNodeSegmentArray[j])) {\n break;\n }\n }\n if (j == priorNodeSegmentArray.length) {\n deleteNodeSegmentArray.push(nodeSegment);\n }\n }\n }\n }\n }\n\n\n //delete the extra multiple parameters\n if (deleteNodeSegmentArray != null) {\n for (var i=0; i < deleteNodeSegmentArray.length; i++) {\n var priorNodeSegment = deleteNodeSegmentArray[i];\n if (priorNodeSegment && !extUtils.isDependentNodeSegment(priorNodeSegment, true)) {\n\n if (extPart.DEBUG) alert(\"deleting the existing node: \" + partName);\n\n //delete the existing node\n sbPart = sbObj.getNamedSBPart(partName, priorNodeSegment.node);\n var weight = sbPart.getWeight();\n\n var optionFlags = 0;\n if (sbPart.getVersion() < 5.0)\n {\n optionFlags = docEdits.QUEUE_DONT_MERGE;\n }\n\n extPart.queueDocEdit(partName, \"\", priorNodeSegment, weight, null, optionFlags);\n }\n }\n }\n\n var optionFlags = 0;\n if (extPart.getVersion(partName) < 5.0)\n {\n optionFlags = docEdits.QUEUE_DONT_MERGE;\n }\n\n //now insert the new edits\n for (var index=0; index < paramArray.length; index++) {\n\n paramObj = paramArray[index];\n\n if (extPart.DEBUG) alert(\"adding edits for participant: \" + partName + \" [\"+ index + \"]\");\n\n var insertNode = extPart.getInsertNode(partName, paramObj);\n\n //handle the create link insert node\n if (typeof insertNode == \"string\" &&\n insertNode.indexOf(\"createAtSelection\") == 0)\n {\n if (location.indexOf(\"nodeAttribute\") == 0)\n {\n //get the tag and attribute names\n\n var whereToSearch = extPart.getWhereToSearch(partName);\n var tagName = whereToSearch.substring(whereToSearch.indexOf(\"+\") + 1);\n var attrName = location.substring(location.indexOf(\"+\") + 1);\n\n //get the text to insert within the tag from the insert node info\n var tagText = \"\";\n if (insertNode.indexOf(\"+\") != -1) {\n tagText = insertNode.substring(insertNode.indexOf(\"+\") + 1);\n }\n\n //create the insertion string\n insertText = extPart.getInsertText(partName, paramObj);\n insertText = \"<\" + tagName + \" \" + attrName + \"=\\\"\" + insertText + \"\\\">\"+ tagText + \"</\" + tagName + \">\";\n\n if (extPart.DEBUG) alert(\"adding new tag at selection for part: \" + partName);\n\n //add to the docEdits\n docEdits.queue(insertText,false,\"replaceSelection\", null, optionFlags);\n\n break;\n }\n else\n {\n // We are creating the node which these are relative to,\n // so change the weight to selection relative.\n if (location.indexOf(\"beforeNode\") == 0)\n {\n location = \"beforeSelection\";\n }\n else if (location.indexOf(\"afterNode\") == 0)\n {\n location = \"afterSelection\";\n }\n else if (location.indexOf(\"replaceNode\") == 0)\n {\n location = \"replaceSelection\";\n }\n }\n }\n\n\n //handle the wrapSelection location\n if (location.indexOf(\"wrapSelection\") == 0)\n {\n var insertText = extPart.getInsertText(partName, paramObj);\n\n if (!sbObj) {\n\n if (paramObj.MM_selection != null) {\n tagText = paramObj.MM_selection;\n } \n else \n {\n tagText = dwscripts.fixUpSelection(dw.getDocumentDOM(), false, false);\n }\n\n var match = insertText.match(/<([^<>%\\s]+)/g);\n\n if (match && (match.length > 0))\n {\n for (var i = 0; i < match.length; i ++)\n {\n match[i] = match[i].substring(1);\n }\n\n // check if insert text already has a close tag, and remove it if found\n\n var closeTagPos = insertText.search(RegExp(\"<\\\\/\"+ match[match.length-1], \"i\"));\n\n if (closeTagPos != -1)\n {\n insertText = insertText.substring(0, closeTagPos);\n }\n\n // now create the full string\n // closing tags go on in reverse order\n\n insertText = insertText + tagText;\n\n for (var i = (match.length - 1); i >= 0; i--)\n {\n insertText += \"</\" + match[i] + \">\";\n }\n }\n\n if (extPart.DEBUG) alert(\"wrapping tag around selection for part: \" + partName);\n\n //add to the docEdits\n docEdits.queue(insertText, false, \"replaceSelection\", null, optionFlags);\n }\n else\n {\n var priorSBPart = sbObj.getNamedSBPart(partName);\n var priorNodeSegment = (priorSBPart) ? priorSBPart.getNodeSegment() : null;\n\n if (priorNodeSegment != null) {\n\n if (extPart.DEBUG) alert(\"wrapping tag around selection for part: \" + partName);\n\n //add to the docEdits\n extPart.updateExistingNodeSegment(partName, priorNodeSegment, paramObj, \"replaceSelection\");\n\n }\n }\n\n break;\n }\n\n\n var priorNodeSegment = null;\n var existingNodeSegment = null;\n var updateNodeSegment = null;\n\n if (priorNodeSegmentArray != null)\n {\n //if we already identified the existing node, just set it\n existingNodeSegment = priorNodeSegmentArray[index];\n }\n else\n {\n //try and find the prior node\n //if re-edit, set the priorNode\n if (sbObj)\n {\n var priorSBPart = sbObj.getNamedSBPart(partName);\n priorNodeSegment = (priorSBPart) ? priorSBPart.getNodeSegment() : null;\n\n if (sbObj.getForcePriorUpdate() &&\n sbObj.getForcePriorUpdate().indexOf(partName) != -1)\n {\n updateNodeSegment = priorNodeSegment;\n }\n }\n\n //look for an existing match on the page,\n //if the insert location is aboveHTML, belowHTML, or the child of a node\n if ((!updateNodeSegment && !existingNodeSegment) &&\n (location.indexOf(\"aboveHTML\") != -1 ||\n location.indexOf(\"belowHTML\") != -1 ||\n location.indexOf(\"firstChildOfNode\") != -1 ||\n location.indexOf(\"lastChildOfNode\") != -1))\n {\n var partList = dw.getParticipants(partName);\n if (partList)\n {\n //get possible family name\n var familyName = extGroup.getFamily(groupName,paramObj);\n\n var ignoreFamily = false;\n if (paramObj.MM_ignoreFamily && paramObj.MM_ignoreFamily.indexOf(partName) != -1)\n {\n ignoreFamily = true;\n }\n\n //select the correct match and assign it to existingNode\n for (var j=0; j < partList.length; j++)\n {\n //get the node information\n extPart.extractNodeParam(partName, partList[j].parameters, partList[j].participantNode);\n if (extPart.getVersion(partName) >= 5.0)\n {\n var nodeSeg = new NodeSegment(partList[j].participantNode, partList[j].matchRangeMin, partList[j].matchRangeMax);\n }\n else\n {\n var nodeSeg = new NodeSegment(partList[j].participantNode);\n }\n \n // Check to make sure we have a valid node segment\n if (nodeSeg.node == null)\n {\n nodeSeg = null;\n }\n \n //if we have a match, set existingNode and break\n if (extPart.parametersMatch(partName, partList[j].parameters, paramObj))\n {\n existingNodeSegment = nodeSeg;\n break;\n }\n else if (!ignoreFamily && location.indexOf(\"HTML\")!=-1 && extUtils.onlyFamilyReferences(nodeSeg, familyName, paramObj.MM_ignoreOtherFamilies))\n {\n //if aboveHTML or belowHTML, check for family references, and may re-use an orphaned node\n updateNodeSegment = nodeSeg;\n //don't break, continue looking, in case there is an exact match\n }\n }\n }\n\n }\n\n //if we found both an existingNode and a node to update, choose the exact match\n if (existingNodeSegment && updateNodeSegment) {\n updateNodeSegment = null;\n }\n\n //if we did not find and existing or update segment, check if we can update\n // the prior node. This is possible if no other server behaviors depend\n // on the node.\n if (priorNodeSegment && !existingNodeSegment && !updateNodeSegment && !extUtils.isDependentNodeSegment(priorNodeSegment,!ignoreFamily)) {\n updateNodeSegment = priorNodeSegment;\n }\n\n }\n\n if (updateNodeSegment != null)\n {\n //change the existing node to match the new parameters\n //if prior object being updated, pass that weight. Otherwise, pass new location weight\n if (sbObj) {\n extPart.updateExistingNodeSegment(partName, updateNodeSegment, paramObj,\n sbObj.getNamedSBPart(partName, updateNodeSegment.node).getWeight()\n );\n } else {\n extPart.updateExistingNodeSegment(partName, updateNodeSegment, paramObj, location);\n }\n\n if (priorNodeSegment && !updateNodeSegment.equals(priorNodeSegment) &&\n !extUtils.isDependentNodeSegment(priorNodeSegment, true)) {\n\n if (extPart.DEBUG) alert(\"deleting the existing node: \" + partName);\n\n //delete the existing node\n extPart.queueDocEdit(partName, \"\", priorNodeSegment,\n sbObj.getNamedSBPart(partName, priorNodeSegment.node).getWeight(),\n null, optionFlags);\n }\n }\n else if (existingNodeSegment != null)\n {\n //correct node was found, possibly delete prior\n if (extPart.DEBUG) alert(\"correct node found, no change needed: \" + partName);\n\n //can we delete the existing one.\n if ( priorNodeSegment && !existingNodeSegment.equals(priorNodeSegment)\n && !extUtils.isDependentNodeSegment(priorNodeSegment,true)\n )\n {\n //delete the existing node\n extPart.queueDocEdit(partName, \"\", priorNodeSegment,\n sbObj.getNamedSBPart(partName, priorNodeSegment.node).getWeight(),\n null, optionFlags);\n }\n\n //add no-op node as positional placeholder so docEdits class knows how to order same-weight inserts\n docEdits.queue(null, existingNodeSegment, location);\n\n }\n else if (!sbObj || extPart.getSearchPatterns(partName).length)\n { //add node for first time\n if (extPart.DEBUG) alert(\"inserting new node: \" + partName + \" with weight \" + location);\n\n var insertText = extPart.getInsertText(partName, paramObj);\n\n docEdits.queue(insertText, false, location, insertNode, optionFlags);\n }\n //else\n //{\n // if (extPart.DEBUG) alert(\"skipping re-add of removed node: \" + partName + \" with weight \" + location);\n //}\n }\n } else {\n if (extPart.DEBUG) alert(\"skipping apply of empty participant: \" + partName);\n }\n}", "function extGroup_findInString(groupName, theStr)\n{\n var sbList = new Array();\n\n var foundMatch = false;\n var serverBehavior = new ServerBehavior(groupName);\n\n var partNames = extGroup.getParticipantNames(groupName);\n for (var i=0; i < partNames.length; i++)\n {\n var parameters = extPart.findInString(partNames[i], theStr);\n if (parameters != null)\n {\n serverBehavior.setParameters(parameters);\n foundMatch = true;\n }\n }\n\n if (foundMatch)\n sbList.push(serverBehavior);\n\n return sbList;\n}", "function extPart_getNodeParamName(partName)\n{\n return dw.getExtDataValue(partName, \"insertText\", \"nodeParamName\");\n}", "function extPart_getPartType(groupName, partName)\n{\n var retVal = \"\";\n\n if (groupName)\n {\n retVal = dw.getExtDataValue(groupName, \"groupParticipants\", partName, \"partType\");\n }\n\n return retVal;\n}", "function dwscripts_preprocessDocEditInsertText(insertText, editNode, isUpdate)\n{\n var retVal = insertText;\n\n var serverObj = dwscripts.getServerImplObject();\n \n if (serverObj != null && serverObj.preprocessDocEditInsertText != null)\n {\n retVal = serverObj.preprocessDocEditInsertText(insertText, editNode, isUpdate);\n }\n \n return retVal;\n}", "function DocEdit_toString()\n{\n var retVal = new Array();\n retVal.push(\"Text = \\n:\" + this.text + \":\");\n retVal.push(\"InsertPos = \" + this.insertPos);\n retVal.push(\"ReplacePos = \" + this.replacePos);\n retVal.push(\"Weight = \" + this.weight);\n if (this.priorNodeSegment)\n {\n retVal.push(\"PriorNode = \\n:\" + this.priorNodeSegment.toString() + \":\");\n }\n return retVal.join(\"\\n\");\n}", "function insertText(grounding) {\n const selection = DocumentApp.getActiveDocument().getSelection();\n const elements = selection.getSelectedElements();\n\n var element = elements[0]\n var selected_text = element.getElement().asText().getText()\n\n if (element.isPartial()) {\n var text = selected_text.substring(element.getStartOffset(),\n element.getEndOffsetInclusive() + 1);\n } else {\n var text = selected_text\n }\n\n if (element.isPartial()){\n element.getElement().asText().insertText(element.getEndOffsetInclusive() + 1, ' (' + grounding + ')')\n //.setLinkUrl(0, text.length, response_json[0]['term']['url'])\n } else {\n element.getElement().asText().setText(selected_text + ' (' + grounding + ')')\n }\n}", "function aeInsertTextIntoTextbox(aTextboxElt, aInsertedText)\n{\n var text, pre, post, pos;\n text = aTextboxElt.value;\n\n if (aTextboxElt.selectionStart == aTextboxElt.selectionEnd) {\n var point = aTextboxElt.selectionStart;\n pre = text.substring(0, point);\n post = text.substring(point, text.length);\n pos = point + aInsertedText.length;\n }\n else {\n var p1 = aTextboxElt.selectionStart;\n var p2 = aTextboxElt.selectionEnd;\n pre = text.substring(0, p1);\n post = text.substring(p2, text.length);\n pos = p1 + aInsertedText.length;\n }\n\n aTextboxElt.value = pre + aInsertedText + post;\n aTextboxElt.selectionStart = pos;\n aTextboxElt.selectionEnd = pos;\n}", "function extGroup_find(groupName, title, sbConstructor, participantList)\n{\n var sbList = new Array(); //array of ServerBehaviors\n\n var partList = (participantList) ? participantList : dw.getParticipants(groupName);\n\n if (extGroup.DEBUG) {\n if (partList) {\n for (var i=0; i < partList.length; i++) {\n var msg = new Array();\n msg.push(\"Participant \" + i);\n msg.push(\"\");\n msg.push(\"participantName = \" + partList[i].participantName);\n msg.push(\"\");\n msg.push(\"parameters = \");\n for (var j in partList[i].parameters) {\n msg.push(\" \" + j + \" = \" + partList[i].parameters[j] + \" (typeof \" + typeof partList[i].parameters[j] + \")\");\n }\n msg.push(\"\");\n msg.push(\"participantText = \");\n if (partList[i].participantNode)\n {\n var nodeHTML = dwscripts.getOuterHTML(partList[i].participantNode);\n msg.push(nodeHTML.substring(partList[i].matchRangeMin,partList[i].matchRangeMax));\n }\n else\n {\n msg.push(\"ERROR: null participantNode\");\n }\n\n alert(msg.join(\"\\n\"));\n }\n } else {\n alert(\"no participants found for group: \" + this.name);\n }\n }\n\n // Get group title. If no title is defined in the extension data, use the passed\n // in title. If, in addition, no title is passed in, use the groupName.\n var groupTitle = extGroup.getTitle(groupName);\n if (!groupTitle)\n {\n if (title)\n {\n groupTitle = title;\n }\n else\n {\n groupTitle = groupName;\n }\n }\n\n if (partList)\n {\n //sort participants for correct matching into groups later\n partList.sort( extGroup_participantCompare );\n\n //pull out extra information for each part\n for (var i=0; i < partList.length; i++)\n {\n //set the parts position within the master partList\n partList[i].position = i;\n\n //extract node parameter information\n extPart.extractNodeParam(partList[i].participantName, partList[i].parameters,\n partList[i].participantNode);\n\n }\n\n //now match up the found parts to create a list of part groups\n var partGroupList = extGroup.matchParts(groupName, partList);\n\n //now walk the partGroupList and create ServerBehaviors\n for (var i=0; i < partGroupList.length; i++)\n {\n var partGroup = partGroupList[i];\n\n // create a ServerBehavior\n var serverBehavior = null;\n if (sbConstructor == null)\n {\n serverBehavior = new ServerBehavior(groupName);\n }\n else\n {\n serverBehavior = new sbConstructor(groupName);\n }\n\n //sort the partGroup, so that the insert code finds the participant nodes\n // in the correct document order\n partGroup.sort(new Function(\"a\", \"b\", \"return a.position - b.position\"));\n\n //add the participant information to the ServerBehavior\n for (var j=0; j < partGroup.length; j++)\n {\n if (extPart.getVersion(partGroup[j].participantName) >= 5.0)\n {\n //add the information to the ServerBehavior\n var sbPart = new SBParticipant(partGroup[j].participantName, partGroup[j].participantNode,\n partGroup[j].matchRangeMin, partGroup[j].matchRangeMax,\n partGroup[j].parameters);\n }\n else\n {\n //add the information to the ServerBehavior\n var sbPart = new SBParticipant(partGroup[j].participantName, partGroup[j].participantNode,\n 0, 0,\n partGroup[j].parameters);\n }\n serverBehavior.addParticipant(sbPart);\n\n //set the selected node\n if (partGroup[j].participantName == extGroup.getSelectParticipant(groupName))\n {\n serverBehavior.setSelectedNode(partGroup[j].participantNode);\n }\n }\n\n //set the title\n serverBehavior.setTitle(extUtils.replaceParamsInStr(groupTitle,\n serverBehavior.getParameters(false)));\n\n //set the family\n serverBehavior.setFamily(extGroup.getFamily(groupName, serverBehavior.getParameters(false)));\n\n //check the ServerBehavior for completeness\n var partNames = extGroup.getParticipantNames(groupName);\n for (var j=0; j < partNames.length; j++)\n {\n var isOptional = extPart.getIsOptional(groupName, partNames[j]);\n sbPart = serverBehavior.getNamedSBPart(partNames[j]);\n var partNode = null;\n if (sbPart)\n {\n partNode = sbPart.getNodeSegment().node;\n }\n\n //if this is not an optional participant, check the ServerBehavior for completeness\n if (!isOptional && extPart.getWhereToSearch(partNames[j]) && partNode == null)\n {\n serverBehavior.setIsIncomplete(true);\n\n if (extGroup.DEBUG)\n {\n alert(\"setting record #\" + i + \" to incomplete: missing part: \" + partNames[j]);\n }\n }\n }\n\n // Make the sb object backward compatible with the UD4 sb object.\n serverBehavior.makeUD4Compatible();\n\n //add it to the list of ServerBehaviors\n sbList.push(serverBehavior);\n }\n }\n\n return sbList;\n}", "function manipulateString(string) {\n\t//alertrnf(\"from backup in manipulateString(): string received = \" + string);\n\t//alertrnf(\"renamedFileName = \" + renamedFileName);\nif(budgetSheet && !(renamedFileName.includes(\"bs\"))) {\n//restore.bs to filename //if backing up a budgetsheet after edit renamedFileName might already end in .bs\nrenamedFileName = renamedFileName + \".bs\";\n//protocolFileName = renamedFileName + \".bs\";\n//protocolFileName = renamedFileName + \".bs\";\n}//end if(budgetSheet) {\n\tposition = string.indexOf(\"_os\");\n\t//alertrnf(\"position = \" + position);\n\tpart = string.slice(position);\n\t//alertrnf(\"part = \" + part);\n\t//newPartString = \"{\\\"\" + protocolFileName;\n\tnewPartString = \"{\\\"\" + renamedFileName;\n\t//alertrnf(\"newPartString = \" + newPartString);\n\t//string.splice position = 17\n\t//string = \"This is a test of rename db filename!\"\n\tstring = newPartString+part;\n\t//alertrnf(\"Now string = \" + string);\n\t// dbTitle.textContent = renamedFileName;\n\t return string;\n}//end function manipulateString", "function extPart_expandParameterObject(groupName, partName, paramObj)\n{\n var retList = new Array();\n\n //find the parameter with the shortest length array.\n // We will use this parameter to iterate.\n var loopVar = '';\n\n var nodeParamValue = paramObj[extPart.getNodeParamName(partName)];\n\n // Only search for array parameters if type multiple\n if (extPart.getPartType(groupName, partName) == \"multiple\" ||\n (nodeParamValue != null && typeof nodeParamValue == \"object\" &&\n nodeParamValue.length != null)\n )\n {\n for (var j in paramObj)\n {\n //is this an array parameter and is it used in the current participant\n if ( typeof paramObj[j] == \"object\" && paramObj[j].length != null\n && (extPart.getRawInsertText(partName).indexOf(\"@@\"+j+\"@@\") != -1 ||\n extPart.getNodeParamName(partName) == j)\n )\n {\n if (!loopVar)\n {\n //we found the first parameter array\n loopVar = j;\n }\n else\n {\n //select the parameter array with the shortest length\n if (paramObj[j].length < paramObj[loopVar].length)\n {\n loopVar = j;\n }\n }\n }\n }\n }\n //if we found an array parameter, expand it into a list of parameter objects\n // otherwise just add the current parameter object\n if (loopVar)\n {\n if (extPart.DEBUG) alert(\"creating \" + paramObj[loopVar].length + \" copies of paramObj for \" + partName);\n\n // create a new parameter object for each array value\n for (var k=0; k < paramObj[loopVar].length; k++)\n {\n var tempParams = new Object();\n for (var j in paramObj)\n {\n if (typeof paramObj[j] == \"object\" && paramObj[j].length != null)\n {\n tempParams[j] = paramObj[j][k]; // add array parameters\n }\n else\n {\n tempParams[j] = paramObj[j]; // add normal parameters\n }\n }\n\n //add the new parameter object\n retList.push(tempParams);\n }\n\n }\n else\n {\n //add a single parameter object\n retList.push(paramObj);\n }\n\n return retList;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets specific listing by listing id
static async getListing(id) { const result = await db.query( `SELECT id, host_username, title, description, price FROM listings WHERE id = $1`, [id] ); let listing = result.rows[0]; return listing; }
[ "getListing(id, callback) {\n $.ajax({\n type: 'GET',\n url: `/listings${id}`,\n dataType: 'json',\n success: function(data) {\n callback(data);\n },\n error: function(err) {\n console.log('Could not retrieve listing: ', err);\n }\n });\n }", "one(id) {\n return fetch(`${BASE_URL}/listings/${id}`, {\n credentials: \"include\"\n }).then(res => res.json());\n }", "function show(req, res){\n Listing.findById(req.params.id).populate('listing'){\n if(err) return console.log(err)\n res.json(listing)\n }\n }", "function load(req, res, next, id) {\n Listing.get(id).then((listing) => {\n req.listing = listing; // eslint-disable-line no-param-reassign\n return next();\n }).error((e) => next(e));\n}", "function showSingleListing(req, res) {\n // get a single listing\n Listing.findOne({ slug: req.params.slug }, (err, listing) => {\n if (err) {\n res.status(404);\n res.send('Listing not found!');\n }\n\n res.render('pages/single-listing', { \n listing: listing,\n success: req.flash('success')\n });\n });\n}", "function getItemDescription(listingID) {\n // console.log(listing, listingID);\n var item = listing.get(listingID);\n var price = item.price;\n var blurb = item.blurb;\n var seller = item.seller;\n var description = item.description;\n var imagePath = item.imagePath;\n\n let itemGot = {\n \"price\": price,\n \"blurb\": blurb,\n \"seller\": seller,\n \"description\": description,\n \"imagePath\": imagePath\n };\n return itemGot;\n}", "function finditembyid (id) {\n\tfor (var i = 0; i < food_pickup.length; i++) {\n\t\tif (food_pickup[i].id == id) {\n\t\t\treturn food_pickup[i]; \n\t\t}\n\t}\n\treturn false; \n}", "function findById(id) {\r\n $.ajax({\r\n type: 'GET',\r\n url: rootURL + '/pizza/' + id,\r\n dataType: \"json\",\r\n contentType: 'application/json',\r\n\r\n success: function (data) {\r\n setPizza(data);\r\n }\r\n });\r\n}", "static getSong(id) {\n return SongManager.songList.find(s => s.songId == id);\n }", "getById(id) {\n return tag.configure(FieldLink(this).concat(`(guid'${id}')`), \"fls.getById\");\n }", "function get_details(id){\n console.log(\"You clicked Game ID: \" + id);\n fetch_by_id(id);\n}", "async getSignedAgentForListing(listing_id) {\n let listings = await this.getListingsWithId(listing_id);\n let listing = listings[0];\n //console.log(listing);\n if(listing.listing_status != 'Signed') {\n console.log(`dbAccess getAgentForListing: the named listing with id ${listing_id} is not signed, which means there is no agent to return.`);\n return [];\n }\n\n let query = 'SELECT DISTINCT users.first_name, users.last_name, users.display_name, users.email, agents.id, agents.title, agents.phone, agents.web_site from (((agents inner join bids on agents.id = bids.agent_id AND bids.bid_status=\"Signed\") INNER JOIN listings ON bids.listing_id = ?) INNER JOIN users on users.agent_id = agents.id)';\n let args = [listing_id];\n const rows = await this.connection.query(query, args);\n return rows;\n }", "function getDrink( id ) {\n return rp( {\n url: \"http://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=\" + id,\n json: true\n }).then(function (res) {\n return res.drinks[0];\n }, function(err) {\n return err;\n })\n}", "function allListings() {\n return itemListings.once('value')\n .then(data => data.val())\n .then(itemListings => {\n let items = Object.keys(itemListings)\n return items.filter(\n listingID => itemListings[listingID].forSale === true\n )\n })\n}", "function getAlbum (id) {\n return $http({\n url: 'local.json',\n method: 'GET'\n }).then(function(response) {\n return _.find(response.data, {'id': parseInt(id, 10)});\n });\n }", "retrieveHotel(id){\n return axios.get(`${CONST_API_URL}/showHotelDetails/${id}`);\n }", "getDroplet(id) {\n return this._request('GET', 'droplets/' + id);\n }", "async function searchForListings(searchTerm) {\n let items = await itemListings.once('value')\n .then(data => data.val())\n // console.log(items)\n return allListings()\n .then(listingIDs => listingIDs.filter(\n listingID => items[listingID].blurb.toLowerCase().includes(searchTerm.toLowerCase())\n ))\n}", "findBookingsByListing(listingId, status) {\n return new Promise((resolve, reject) => {\n //console.log(\"SERVICE err: \" + err); \n Booking.findBookingByListingId(listingId, status, (err, res) => {\n //console.log(\"SERVICE err: \" + err);\n if (err) {\n reject(err);\n } else {\n resolve(res);\n }\n });\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if the next guess should be a lower or higher number
function lowerOrHigher(){ if(gameData.playersGuess > gameData.winningNumber){ return "Your guess is too high "; } else if (gameData.playersGuess < gameData.winningNumber){ return "Your guess is too low "; } }
[ "function rangeCheck(){\n\tvar num;\n\n\tif(Math.abs(gameData.winningNumber - gameData.playersGuess) > 50){\n\t\treturn \"and more than 50 digits away from the winning number.\";\n\t} else {\n\t\tif(Math.abs(gameData.winningNumber - gameData.playersGuess) <= 5){\n\t\t\tnum = 5;\n\t\t} else if(Math.abs(gameData.winningNumber - gameData.playersGuess) <= 10){\n\t\t\tnum = 10;\n\t\t} else if(Math.abs(gameData.winningNumber - gameData.playersGuess) <= 20){\n\t\t\tnum = 20;\n\t\t} else if(Math.abs(gameData.winningNumber - gameData.playersGuess) <= 50){\n\t\t\tnum = 50;\n\t\t}\n\t}\n\treturn \"and within \" + num + \" digits of the winning number.\";\n}", "function suggestGuess(){\n\tif(guess<answer){\n\t\treturn \" guess higher.\";\n\t} else{\n\t\treturn \" guess lower.\";\n\t}\n}", "function validGuess(){\n//for guess to be valid, must be in 1-100 range\n//guesses must be remaining, is not be a repeat value, and game is not over\n\n\tif(gameData.playersGuess > 0 && \n\t\tgameData.playersGuess < 101 && \n\t\tgameData.guesses.length < 5 && \n\t\tgameData.guesses.indexOf(gameData.playersGuess) === -1 &&\n\t\t!gameData.gameOver) {\n\n\t\treturn true;\n\t} \n\telse {\n\t\treturn false;\n\t}\n}", "function lowerGuessCount(){\n remainingGuesses--;\n }", "function relativeFeedback(secretNumber, oldGuess, newGuess) {\n var oldDiff = parseInt(Math.abs(secretNumber - oldGuess));\n var newDiff = parseInt(Math.abs(secretNumber - newGuess));\n if (newDiff > oldDiff) {\n $('#relative-feedback').text('You are colder than the last guess!');\n } else if (newDiff === oldDiff) {\n $('#relative-feedback').text('You are as far as your previous guess!');\n } else {\n $('#relative-feedback').text('You are hotter than the last guess!');\n }\n }", "function favNumber(){\n\n var myNum = 8;\n var tries = 4;\n \n while(tries > 0){\n \n var userInput = prompt('Can you guess my favorite number?');\n var userInputInt = parseInt(userInput);\n \n if(userInputInt < myNum){\n alert('too small');\n tries --;\n } else if(userInputInt === myNum){\n alert('you are correct');\n tries --;\n break;\n } else if(userInputInt > myNum){\n alert('too large');\n tries--;\n } else {\n alert('The correct answer is 8');\n }\n }\n}", "function guessValidation () {\n if (+($(\"#userGuess\").val()) > 100 || +($(\"#userGuess\").val()) < 1) {\n alert(\"Please enter a number between 1 - 100\");\n }\n }", "function compareNumber(){\n var insideInputAsAString = number.value;\n var insideInput = parseInt(insideInputAsAString);\n if (insideInput===randomNumber){\n clues.innerHTML = 'HAS GANADO, CAMPEONA';\n console.log('HAS GANADO, CAMPEONA');\n }else if(insideInput<randomNumber){\n clues.innerHTML = 'Demasiado pequeño';\n console.log('Demasiado pequeño');\n }else if(insideInput>randomNumber){\n clues.innerHTML = 'Demasiado alto';\n console.log('Demasiado alto');\n }\n}", "function guessNumber(){\n\n let guess = user.value;\n user.value = '';\n\n /* Random Math Function */\n let number = Math.floor(Math.random() * 5 + 1);\n\n /* Correct guess */\n if(guess == number){\n story.innerHTML = `Bra jobbat! Du gissade ${number} och det var rätt och nu har spöket försvunnit och ingen behöver vara rädd mer!`;\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet';\n\n /* Guesss was to high */\n }else if(guess > number){\n story.innerHTML = 'Fel! Det var för högt. Försök igen!';\n\n /* Guess was to low */\n } else if(guess < number){\n story.innerHTML = 'Fel! Det var för lågt. Försök igen!';\n }\n }", "function guess() {\n\n // WRITE YOUR EXERCISE 4 CODE HERE\n let guess = 0;\n let number= 0;\n let attempt = 0;\nnumber = (Math.floor(Math.random()* 1000) + 1);\nguess = prompt (\"Please enter your guess. The range is a random integer between 1 to 1,000.\")\nattempt += 1\nwhile (guess != number){\n if (guess > 1000 || guess < 1 || guess%1 != 0)\n guess = prompt (\"Invalid guess. Try a valid number between 1 to 1,000.\")\nif (guess < number) {\n guess = prompt (\"Guess too small. Try another number between 1 to 1,000.\")\n attempt += 1\n}\nif (guess > number) {\n guess = prompt (\"Guess too big. Try another number between 1 to 1,000.\")\n attempt += 1\n}\n}\nif (guess == number) {\n var p = document.getElementById(\"guess-output\");\n p.innerHTML = \"You did it! The random integer was \" + number + \" and you took \" + attempt + \" tries or try (if you somehow got the random interger in your first guess) to figure out the random integer.\"\n}\n ////////////////// DO NOT MODIFY\n check('guess'); // DO NOT MODIFY\n ////////////////// DO NOT MODIFY\n}", "function checkInputNumber() {\n let userGuess = enteredNumber.value;\n\n if (userGuess == randomNumber) {\n alert('You are Winner!')\n } else {\n alert('Wrong answer!')\n }\n}", "function guess() {\n\t\t// Capture the guess value:\n\t\tvar inputValue = document.getElementById(\"input\").value;\n\t\t\n\t\t// Verify the guess is a number using the previously defined function (isNumber()):\n\t\tvar isNum = isNumber(inputValue);\n\t\tif ( isNum === false) {\n\t\t\tguesses += 1;\n\t\t\tdisplay(\"red\", true, \"You must enter a number!\");\n\t\t\tupdateGameGuesses(inputValue, \"Not a number\");\n\n\t\t// Was the guess too low?\n\t\t} else if ( inputValue < ranNum ) {\n\t\t\tguesses += 1;\n\t\t\tdisplay(\"yellow\", true, \"Too low\");\n\t\t\tupdateGameGuesses(inputValue, \"Too low\");\n\n\t\t// Was the guess too high?\n\t\t} else if ( inputValue > ranNum ) {\n\t\t\tguesses += 1;\n\t\t\tdisplay(\"yellow\", true, \"Too high\");\n\t\t\tupdateGameGuesses(inputValue, \"Too high\");\n\n\t\t// Was the guess correct?\n\t\t} else if (ranNum == inputValue) { \n\t\t\tguesses += 1;\n\t\t\t// Display a message if the user guessed correctly on their first try:\n\t\t\tif(guesses === 1) {\n\t\t\t\tdisplay(\"blue\", false, \"You got it! The number was \" + ranNum + \". It only took you one guess!\", \"Start again (it's ready).\");\n\t\t\t// Display a message if the user required 2 or more guesses:\n\t\t\t} else {\n\t\t\t\tdisplay(\"blue\", false, \"You got it! The number was \" + ranNum + \". It took you \" + guesses + \" guesses.\", \"Start again (it's ready).\")\n\t\t\t}\n\t\t\tupdateGameGuesses(inputValue, \"Correct\");\n\n\t\t\t// For this one game, that was guessed correctly, store the game stats:\n\t\t\tvar gameStat = [numRange, ranNum, guesses];\n\t\t\t// Add the game stat to an array that persists for the window session (is emptied after a page refresh):\n\t\t\tvar sessionScore = new Array();\n\t\t\tsessionScore[sessionScore.length] = gameStat;\n\n\t\t\t// Display the Session Scores in a table:\n\t\t\tfor( var i = 0; i < sessionScore.length; i++ ) {\n\t\t\t\tvar gameStat = sessionScore[i],\n\t\t\t\ttr = document.createElement(\"tr\"),\n\t\t\t\ttd0 = document.createElement(\"td\"),\n\t\t\t\ttd1 = document.createElement(\"td\"),\n\t\t\t\ttd2 = document.createElement(\"td\");\n\n\t\t\t\ttd0.appendChild(document.createTextNode(\"1 to \" + gameStat[0]));\n\t\t\t\ttd1.appendChild(document.createTextNode(gameStat[1]));\n\t\t\t\ttd2.appendChild(document.createTextNode(gameStat[2]));\n\t\t\t\ttr.appendChild(td0);\n\t\t\t\ttr.appendChild(td1);\n\t\t\t\ttr.appendChild(td2);\n\t\t\t\tsessionScoreTable.appendChild(tr);\n\t\t\t}\n\n\t\t\t// Reset the game:\n\t\t\tresetGameGuessesTable();\n\t\t\tgameGuesses.length = 0;\n\t\t\tgameStat = 0;\n\t\t\tguesses = 0;\n\t\t\tnewRanNum();\n\t\t}\n\t}", "function checkScore() {\n if (totalScoreNumber === currentGoalNumber && currentGoalNumber != 0) {\n wins++;\n $(\"#wins\").text(\"Wins: \" + wins);\n setNumbers();\n }\n else if (totalScoreNumber > currentGoalNumber) {\n losses++;\n $(\"#losses\").text(\"Losses: \" + losses);\n setNumbers();\n }\n }", "function handleGuess() {\n // Check if remaining guesses is -1 and setup a new game if so.\n\tif (remainingGuesses == -1) {\n\t\tsetupNewGame();\n\t}\n\n\tif (remainingGuesses == 1) {\n\t\tguessBtn.disabled = true;\n\t}\n\n // Retreive the user's newest guess.\n\tlet newestGuess = getGuessInput();\n\n // Check if the user has won. We should show a message, set remaining guesses to 0, and return from this function.\n \t// Check if the guess is higher or lower and show appropriate message.\n\t// The user has used a guess, decrement remainin guesses and show the new value.\n\n\tif (newestGuess == magicNumber) {\n\t\tshowMessage(\"win-message\");\n\t\tremainingGuesses = 0;\n\t\tshowRemainingGuesses(remainingGuesses);\n\t} else if (newestGuess < magicNumber) {\n\t\tshowMessage(\"higher-message\");\n\t\tremainingGuesses--;\n\t\tshowRemainingGuesses(remainingGuesses);\n\t} else if (newestGuess > magicNumber) {\n\t\tshowMessage(\"lower-message\");\n\t\tremainingGuesses--;\n\t\tshowRemainingGuesses(remainingGuesses);\n\t}\n\n // If the remaining guesses is 0, then the user has lost and that message should be shown.\n\tif ((remainingGuesses === 0) && (newestGuess != magicNumber)) {\n\t\tshowMessage(\"lose-message\");\n\t}\n}", "function correctGuess() {\n score += wrongAnswersLeft;\n if (score > hScore) {\n hScore = score;\n }\n setCorrectScreen(wrongAnswersLeft);\n }", "findMinRaiseAmount(lineup, dealer, lastRoundMaxBet, state) {\n if (!lineup || dealer === undefined) {\n throw new Error('invalid params.');\n }\n const lastRoundMaxBetInt = parseInt(lastRoundMaxBet, 10);\n // TODO: pass correct state\n const max = this.getMaxBet(lineup, state);\n if (max.amount === lastRoundMaxBetInt) {\n throw new Error('can not find minRaiseAmount.');\n }\n // finding second highest bet\n let secondMax = lastRoundMaxBetInt;\n for (let i = max.pos + 1; i < lineup.length + max.pos; i += 1) {\n const pos = i % lineup.length;\n const last = (lineup[pos].last) ? this.rc.get(lineup[pos].last).amount.toNumber() : 0;\n if (last > secondMax && last < max.amount) {\n secondMax = last;\n }\n }\n return max.amount - secondMax;\n }", "checkNaturalWin(){\n let win = false;\n\n //Player has natural 9\n if(this.playerHand.total === 9 && this.bankerHand.total <= 8 || \n //Player has natural 8\n this.playerHand.total === 8 && this.bankerHand.total <= 7 \n ){\n this.playerHand.win = true;\n win = true;\n }\n //Banker has a natural 9\n else if(this.bankerHand.total === 9 && this.playerHand.total <= 8 || \n //Player has natural 8\n this.bankerHand.total === 8 && this.playerHand.total <= 7 \n ){\n this.bankerHand.win = true;\n win = true;\n }\n\n return win;\n }", "function validNumber(n) {\n if(topBottom === \"top\") {\n n = (Math.round((n - topStart) / incrementTop) * incrementTop) + topStart;\n if(!isInRange(n, topStart, topEnd)) {\n if(!topInverted) {\n n = n < topStart ? topStart : topEnd;\n } else {\n n = n < topStart ? topEnd : topStart;\n }\n }\n } else {\n n = (Math.round((n - bottomStart) / incrementBottom) * incrementBottom) + bottomStart;\n if(!isInRange(n, bottomStart, bottomEnd)) {\n if(!bottomInverted) {\n n = n < bottomStart ? bottomStart : bottomEnd;\n } else {\n n = n < bottomStart ? bottomEnd : bottomStart;\n }\n }\n }\n return n;\n }", "function checkIfNumber(input) {\n\tlet i =0;\n\tlet value = input;\n\tif (!isNaN(value)) {\n\t\tpointsToWin = value;\n\t} else {\n\t\tdo {\n\t\t\talert(input + \" is not a number. Please enter a number 1-9.\");\n\t\t\tif (!isNaN(value = prompt(\"Please enter number of points to win (1-9).\") ) ) {\n\t\t\t\ti =+ 1;\n\t\t\t}\n\t\t} while (i !=1);\n\t\tpointsToWin = value;\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the hashed struct for %%value%% using %%types%% and %%name%%.
static hashStruct(name, types, value) { return TypedDataEncoder.from(types).hashStruct(name, value); }
[ "hashStruct(name, value) {\n return (0, index_js_2.keccak256)(this.encodeData(name, value));\n }", "static hash(domain, types, value) {\n return (0, index_js_2.keccak256)(TypedDataEncoder.encode(domain, types, value));\n }", "function hashMember(name, value, configuration) {\n if (ok(value, tyArray)) {\n var code = 0;\n /*jslint plusplus: true */\n for (var i = 0; i < value.length; i++) {\n code = code + hashPrimitiveMember(name, value[i], configuration);\n }\n return code;\n }\n return hashPrimitiveMember(name, value, configuration);\n }", "static encode(domain, types, value) {\n return (0, index_js_4.concat)([\n \"0x1901\",\n TypedDataEncoder.hashDomain(domain),\n TypedDataEncoder.from(types).hash(value)\n ]);\n }", "static uniqueIdentityToHashObject(uniqueIdentity) {\n var terms = uniqueIdentity.split(':');\n if (terms.length != 2) {\n throw \"unique-identity has invalid format\";\n }\n let hashType = terms[0];\n let hashValue = terms[1];\n if (SUPPORTED_COMMON_NAME_HASH_TYPES.indexOf(hashType) < 0) {\n throw \"hash function '\" + hashType + \"' is not supported for certificate Common Name unique identity\";\n }\n return {\n 'hashType': hashType,\n 'hashValue': hashValue\n };\n }", "function HashRegistryValue(registryValue) {\n return HashAll(registryValue.tweak, encodeString(registryValue.data), encodeUint8(registryValue.revision));\n}", "function structuralHash(term) {\n\n // The outer function does not take an environment.\n // Start recursing with an empty environment.\n return innerStructuralHash(term, Map());\n\n /**\n * An inner helper function that propagates an environment downward\n */\n function innerStructuralHash(term, env) {\n\n if (term.tag === \"bundle\") {\n return innerStructuralHash(term.proc, env);\n }\n\n // Hash of each AST is constructed from its tag and the \"rest\"\n // Rest depends on what type of AST we have.\n let rest;\n\n switch (term.tag) {\n\n case \"ground\":\n // Instantiated unforgeables are equivalent iff they have same randomState\n // See case \"new\" for internally-bound unforgeables.\n rest = qdHash(term.type) ^ qdHash(term.value);\n break;\n\n case \"send*\":\n throw \"hashing send* not yet implemented\";\n\n case \"send\":\n rest = innerStructuralHash(term.chan, env) ^ (innerStructuralHash(term.message, env) << 2);\n break;\n\n case \"join\":\n // Consider the continuation for proper joins (not join*s)\n // Merge this join's environment, shadowing as necessary\n rest = innerStructuralHash(term.body, env.merge(term.environment));\n // No break, so fall thorugh to remaining behavior that also applies to join*\n\n case \"join*\":\n //TODO This is broken. If listening on the same channel twice,\n // their hashes will cancel out. Bit-shifting isn't a great solution either\n // because then commutativity is lost. Normalization (link above)\n for (let action of term.actions) {\n rest ^= innerStructuralHash(action.chan, env) ^ innerStructuralHash(action.pattern, env);\n }\n\n break;\n\n case \"par\":\n throw \"hashing par not yet implemented\";\n\n case \"new\":\n // Bound unforgeables are inside. Rather than implementing additional logic\n // to do debruijn indices or maintain a map, Can we somehow start it with a\n // standard random State so that it will always hash the same.\n throw \"hashing new not yet implemented\";\n\n // Patterns need not be evaluated\n // Actually, why did this ever come up\n case \"variableP\":\n rest = 0;\n break;\n\n case \"variable\":\n // A variable always points to a fully concrete term,\n // so the environment we pass is irrelevant\n rest = innerStructuralHash(env.get(term.givenName), Map());\n break;\n\n default:\n throw \"Non-exhaustive pattern match in structuralHash: \" + term.tag;\n }\n\n return (qdHash(term.tag) ^ rest);\n }\n}", "static async resolveNames(domain, types, value, resolveName) {\n // Make a copy to isolate it from the object passed in\n domain = Object.assign({}, domain);\n // Allow passing null to ignore value\n for (const key in domain) {\n if (domain[key] == null) {\n delete domain[key];\n }\n }\n // Look up all ENS names\n const ensCache = {};\n // Do we need to look up the domain's verifyingContract?\n if (domain.verifyingContract && !(0, index_js_4.isHexString)(domain.verifyingContract, 20)) {\n ensCache[domain.verifyingContract] = \"0x\";\n }\n // We are going to use the encoder to visit all the base values\n const encoder = TypedDataEncoder.from(types);\n // Get a list of all the addresses\n encoder.visit(value, (type, value) => {\n if (type === \"address\" && !(0, index_js_4.isHexString)(value, 20)) {\n ensCache[value] = \"0x\";\n }\n return value;\n });\n // Lookup each name\n for (const name in ensCache) {\n ensCache[name] = await resolveName(name);\n }\n // Replace the domain verifyingContract if needed\n if (domain.verifyingContract && ensCache[domain.verifyingContract]) {\n domain.verifyingContract = ensCache[domain.verifyingContract];\n }\n // Replace all ENS names with their address\n value = encoder.visit(value, (type, value) => {\n if (type === \"address\" && ensCache[value]) {\n return ensCache[value];\n }\n return value;\n });\n return { domain, value };\n }", "encodeType(name) {\n const result = this.#fullTypes.get(name);\n (0, index_js_4.assertArgument)(result, `unknown type: ${JSON.stringify(name)}`, \"name\", name);\n return result;\n }", "computeKey(type, id) {\n if (type === undefined || id === undefined) {\n throw Error('computeKey() needs type, id');\n }\n\n let sha1sum = crypto.createHash('sha1');\n id = id || '';\n return type + ':' + sha1sum.update(id).digest('hex') + '-' + this.version;\n }", "function hasher(data) {\n var pre_string = data.lastname + data.firstname + data.gender + data.dob + data.drug;\n var hash = '', curr_str;\n\n hash = Sha1.hash(pre_string);\n\n /**\n // Increment 5 characters at a time\n for (var i = 0, len = pre_string.length; i < len; i += 5) {\n curr_str = '';\n\n // Extract 5 characters at a time\n for (var j = 0; j < 5; j++) {\n if (pre_string[i + j]) {\n curr_str += pre_string[i + j]\n }\n }\n\n // Hash the characters and append to hash\n var temp = mini_hash(curr_str); // Get number from the string\n var fromCode = String.fromCharCode(mini_hash(curr_str));\n hash += fromCode;\n\n } */\n\n\n return hash;\n}", "function genInput(name, value) {\n var input = document.createElement('input');\n input.name = name;\n input.value = value;\n return input;\n }", "function calculateID(info){\n\t// Hash object name\n\tvar hash = updateHash(info.name, 0);\n\n\t// Hash object attributes\n\thash = updateHash(info.isSettings, hash);\n\thash = updateHash(info.isSingleInst, hash);\n\n\t// Hash field information\n\tfor (var n = 0; n < info.fields.length; n++){\n\t\thash = updateHash(info.fields[n].name, hash);\n\t\thash = updateHash(info.fields[n].numElements, hash);\n\t\thash = updateHash(info.fields[n].type, hash);\n\n\t\tif (info.fields[n].type == 7){ // enum\n\t\t\tvar options = info.fields[n].options;\n\t\t\tfor (var m = 0; m < options.length; m++){\n\t\t\t\thash = updateHash(options[m], hash);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Done\n\treturn hash & 0xFFFFFFFE;\n}", "function create(value, struct) {\n const result = validate(value, struct, {\n coerce: true\n });\n\n if (result[0]) {\n throw result[0];\n } else {\n return result[1];\n }\n}", "function NewHash() {\n return blakejs_1[\"default\"].blake2bInit(32, null);\n}", "function hashFnDef( fn ) {\n\n return fn.toString(); // todo: actually hash this\n\n}", "static getHash(block){\r\n const {timestamp, lastHash, data, nonce} = block;\r\n return this.createHash(data, timestamp, lastHash, nonce, difficulty);\r\n }", "bucketFor(name) {\n return hashBucket(this.hashFor(name), this.size)\n }", "encodeData(type, value) {\n return this.getEncoder(type)(value);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hide create request container
function HideCreateRequestContainer() { selectedGraphics = null; map.infoWindow.hide(); map.getLayer(tempGraphicLayer).clear(); dojo.byId('divCreateRequestContainer').style.display = "none"; if (dojo.byId("divSubmitRequestContainer")) { dojo.destroy(dojo.byId("divSubmitRequestContainer")); } dojo.destroy(dojo.byId("divInfoContainer")); }
[ "constructor() {\n super();\n this.isContainer = false;\n }", "createContainer() {\n const existingContainer = document.querySelector('#bitski-dialog-container');\n if (existingContainer) {\n return existingContainer;\n }\n const container = document.createElement('div');\n container.id = 'bitski-dialog-container';\n document.body.appendChild(container);\n return container;\n }", "function hideStartupDiv() {\n // Appending Preview to Page2\n $(\"#page2\").empty();\n $(\"#page2\").html($(\"#importPage3Preview\").html());\n\n // Remove preview to prevent conflict\n $(\"#importPage3Preview\").empty();\n\n // Close the startup div\n createNew();\n}", "function hideProcessing(){\n vm.processing = false;\n }", "function hideCreateDialog() {\n if (document.getElementById('editID').value != '-1') {\n $('#rfelement' + document.getElementById('editID').value).show();\n document.getElementById('editID').value = '-1';\n }\n $('#textarea_preview').hide();\n $('#singlechoice_preview').hide();\n $('#multiplechoice_preview').hide();\n $('#matrix_preview').hide();\n $('#grading_preview').hide();\n $('#tendency_preview').hide();\n $('#newquestion').hide();\n $('#text_preview').show();\n //$('#newquestion_button').show();\n}", "function hideBuilder(){\n\tbuilder.style.display = \"none\";\n\thideButton.innerHTML = \"Show Builder\";\n}", "setVisibility() {\n errors.throwNotImplemented(\"setting visibility (dequeue options)\");\n }", "invisible()\n {\n for (let container of this.containers)\n {\n container.children.forEach(object => object[this.visible] = false)\n }\n }", "ensureButtonsHidden() {\n // TODO(fanlan1210)\n }", "function hidemenu_create(){\n\t//hide the close create menu\n\t$('#ClosecM').css('display','none');\n\t$('#ClosecMbacK').css('display','none');\n\t//reset the form\n\tvar form=document.getElementById('ClosecM_form');\t\n\tform.reset();\n\t//hide the tip\n\t$('#ClosecM_tip,#ClosecM_tip1,#ClosecM_cupname').css('display','none');\n\t \t$('#ClosecM_cupname').css({height:'25px'});\n\t \t$('#ClosecM_bom').css({marginTop:'0'});\t\t\t\t\n}", "function showCreateForm() {\n setID(\"\");\n setFullName(\"\");\n setEmail(\"\");\n setShowForm(true);\n setShowUpdateForm(false);\n }", "function showLoading() {\n loader.hidden = false;\n quoteContainer.hidden = true; \n}", "function hideAddDeviceForm() {\r\n $(\"#addDeviceControl\").show(); // Hide the add device link\r\n $(\"#addDeviceForm\").slideUp(); // Show the add device form\r\n $(\"#error\").hide();\r\n}", "function hideViz(){\n\tif (mainViz === null){\n\t\talertOrConsole('Viz must be rendered before it can be hidden');\n\t} else {\n\t\tmainViz.hide();\n\t}\n}", "function hideUI() {\n document.getElementById(\"options\").classList.add(\"hidden\");\n document.getElementById(\"fullelement\").classList.add(\"hidden\");\n document.getElementById(\"memorywindow\").classList.add(\"hidden\");\n}", "function hideXML(){\n document.getElementById(\"hiddenText\").hidden = true;\n document.getElementById(\"hiddenBtn\").hidden = true ;\n}", "function hideViz() {\n viz.hide();\n}", "function removeFrom() {\n form.style.display = 'none';\n }", "function hide_important_elements(){\n\tdocument.getElementById('segment_middle_part').style.display\t= \"none\";\n\tdocument.getElementById('groupe_add_container').style.display\t= \"none\";\n\tdocument.getElementById('segment_send_part').style.display\t= \"none\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs a function for side effects on the payload, only if the result is Ok.
function okDo(f) { return function (result) { if (isOk(result)) { f(result.ok); } return result; }; }
[ "function Action(event, next, fail){\n return function(err, data){\n if(err) return fail(err);\n event.data = data;\n next();\n }\n}", "function execute_application(fun, args, succeed, fail) {\n if (is_primitive_function(fun)) {\n succeed(apply_primitive_function(fun, args), fail);\n } else if (is_compound_function(fun)) {\n const body = function_body(fun);\n const locals = function_locals(fun);\n const names = insert_all(map(name_of_name, function_parameters(fun)),\n locals);\n const temp_values = map(x => no_value_yet,\n locals);\n const values = append(args, temp_values);\n body(extend_environment(names, values, function_environment(fun)),\n (val, fail2) => {\n if (is_return_value(val)) {\n succeed(return_value_content(val), fail2);\n } else {\n succeed(undefined, fail2);\n }\n },\n fail);\n } else {\n error(fun, \"Unknown function type in apply\");\n }\n}", "function maybe(item, action) {\n if(!item) {\n return;\n }\n return action(item);\n}", "static checkCallbackFnOrThrow(callbackFn){if(!callbackFn){throw new ArgumentException('`callbackFn` is a required parameter, you cannot capture results without it.');}}", "function shouldFix(errcode) {\n return program.apply.includes(errcode) && !(program.skip.includes(errcode))\n}", "function voidAction() {\n\n}", "function complexGenericBehavior (fn, value) { /* Do complicated stuff here */ }", "function processJSONBody(req, controller, methodName) {\n let body = [];\n req.on('data', chunk => {\n body.push(chunk);\n }).on('end', () => {\n try {\n // we assume that the data is in the JSON format\n if (req.headers['content-type'] === \"application/json\") {\n controller[methodName](JSON.parse(body));\n }\n else \n response.unsupported();\n } catch(error){\n console.log(error);\n response.unprocessable();\n }\n });\n }", "function successfulCallbackResponse (response) {\n var statusCode = response.statusCode\n return statusCode >= 200 && statusCode < 300\n}", "ok(res, data) {\r\n this.send(res, data, 200);\r\n }", "async function attack(target_id, attacker_id, damage, name) {\n // console.log(`attack(id=${target_id}, id=${attacker_id}, ${damage})`)\n const response = await fetch(window.GAME_BASE + '/attack', {\n method: 'POST',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n attacker: attacker_id,\n target: target_id,\n damage,\n attack_name: name,\n }),\n })\n\n if (response.status == 200) {\n const state = await response.json()\n return state\n }\n\n throw response\n}", "function greet(action){\n action();\n}", "static isFailedFuncTrigger(result) {\n if (CommonUtil.isDict(result)) {\n for (const fid in result) {\n const funcResult = result[fid];\n if (CommonUtil.isFailedFuncResultCode(funcResult.code)) {\n return true;\n }\n if (!CommonUtil.isEmpty(funcResult.op_results)) {\n for (const opResult of Object.values(funcResult.op_results)) {\n if (CommonUtil.isFailedTx(opResult.result)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }", "function fakeobj(val) {\n for (var i = 0; i < 1000; i++) {\n var result = fakeobjInternal(val);\n if (typeof result == \"object\"){\n return result;\n }\n }\n \n print(\"[-] Fakeobj didn't work. Prepare for WebContent to crash or other strange stuff to happen...\");\n throw \"See above\";\n}", "async function invokeAction () {\n setState({ ...state, actionInvokeInProgress: true, actionResult: 'calling action ... ' })\n const actionName = state.actionSelected\n const headers = state.actionHeaders || {}\n const params = state.actionParams || {}\n const startTime = Date.now()\n // all headers to lowercase\n Object.keys(headers).forEach((h) => {\n const lowercase = h.toLowerCase()\n if (lowercase !== h) {\n headers[lowercase] = headers[h]\n headers[h] = undefined\n delete headers[h]\n }\n })\n // set the authorization header and org from the ims props object\n if (props.ims.token && !headers.authorization) {\n headers.authorization = `Bearer ${props.ims.token}`\n }\n if (props.ims.org && !headers['x-gw-ims-org-id']) {\n headers['x-gw-ims-org-id'] = props.ims.org\n }\n let formattedResult = \"\"\n try {\n // invoke backend action\n const actionResponse = await actionWebInvoke(actions[actionName], headers, params)\n formattedResult = `time: ${Date.now() - startTime} ms\\n` + JSON.stringify(actionResponse,0,2)\n // store the response\n setState({\n ...state,\n actionResponse,\n actionResult:formattedResult,\n actionResponseError: null,\n actionInvokeInProgress: false\n })\n console.log(`Response from ${actionName}:`, actionResponse)\n } catch (e) {\n // log and store any error message\n formattedResult = `time: ${Date.now() - startTime} ms\\n` + e.message\n console.error(e)\n setState({\n ...state,\n actionResponse: null,\n actionResult:formattedResult,\n actionResponseError: e.message,\n actionInvokeInProgress: false\n })\n }\n }", "function dispatch() {\n var result = { code: 404 };\n if (path == \"/acme/new-authz\") {\n result = handleNewAuthz(request.method, request.headers, body);\n } else if (path == \"/acme/new-cert\") {\n result = handleNewCert(request.method, request.headers, body);\n } else if (path.match(\"^/acme/authz/\")) {\n result = handleAuthz(request.method, path, request.headers, body);\n } else if (path.match(\"^/acme/cert/\")) {\n result = handleCert(request.method, path, request.headers, body);\n }\n\n response.writeHead(result.code, result.headers);\n if (result.body) {\n response.write(result.body);\n }\n response.end();\n }", "function myFunc(arg1,arg2){\n console.log('=====');\n if((typeof arg1 === 'boolean')&&(arg1 === true)){\n if(typeof arg2 === 'function'){\n var result = arg2(arg1, arg2);\n console.log(result);\n return result;\n }\n }\n }", "static makeSuccess(msg) {\n\t\tif (msg === \"\" || msg === undefined) {\n\t\t\t// throw an error, or just do nothing, since lack of error means success\n\t\t\tthrow new Error(\"makeSuccessInJrResultCannotHaveBlankReason\");\n\t\t}\n\t\tconst jrResult = new JrResult();\n\t\tjrResult.pushSuccess(msg);\n\t\treturn jrResult;\n\t}", "visitTest_nocond(ctx) {\r\n console.log(\"visitTest_nocond\");\r\n if (ctx.or_test() !== null) {\r\n return this.visit(ctx.or_test());\r\n } else {\r\n return this.visit(ctx.lambdef_nocond());\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete button look through the new STATE called usersInDanger and finds where userID() matches id
function deleteUser(id) { // if it is NOT the same id return a list of all the users without that ID const updatedUsers_forDelete = usersInDanger_resc.filter(user => user.userID !== id); const deletedUser = usersInDanger_resc.filter(user => user.userID === id); setUsersInDanger_resc(updatedUsers_forDelete); console.log(deletedUser[0].userID); props.markSafe(deletedUser[0].userID); }
[ "function deleteUserid(ev)\n{\n var iu = this.id.substring(\"delete\".length);\n var userid = document.getElementById('User' + iu).value;\n if (debug.toLowerCase() == 'y')\n {\n alert(\"Users.js: deleteUserid: {\\\"user name\\\"=\" + userid + \"}\");\n }\n var cell = this.parentNode;\n var row = cell.parentNode;\n var inputs = row.getElementsByTagName('input');\n for (var i = 0; i < inputs.length; i++)\n {\n var elt = inputs[i];\n var name = elt.name;\n var matches = /^([a-zA-Z_$@#]*)(\\d*)$/.exec(name);\n var column = matches[1].toLowerCase();\n var id = matches[2];\n elt.type = 'hidden';\n if (column == 'auth')\n {\n elt.value = '';\n }\n }\n this.form.submit();\n}", "deleteUser( id ) {\n fluxUserManagementActions.deleteUser( id );\n }", "function deleteUser(event) {\n let id = getUserId(event.target);\n fetch(url+\"/api/users/\"+id, {\n method: \"DELETE\",\n headers: {\n \"authorization\": jwt\n }\n }).\n then((response) => {\n if (response.ok) {\n updateStateAndRefresh(\"User \" + id + \" has been deleted.\", true);\n }\n else {\n updateStateAndRefresh(\"User \" + id + \" not deleted!\", false);\n }\n });\n}", "function deleteFromList(user_id){\n return db('saved_list')\n .where({ user_id })\n // .andWhere({ book_id })\n .delete()\n}", "function DeleteUser(id) {\n\tvar confirmed = confirm(\"Are you sure you want to remove this user?\");\n\t\n\tif (confirmed) {\n\t\t// We could make an AJAX call here. That goes a little beyond what is expected in CIT 336.\n\t\t// Instead, let's redirect them through some other actions.\n\t\twindow.location = '/?action=deleteuser&id=' + id;\n\t}\t\n}", "function deleteUser(req, res, next) {\n //Check if the id is valid and exists in db\n \n Users.findOne({\"_id\": req.query.id},\n\n function(err, result) {\n if (err){\n console.log(err);\n\n } \n //console.log(result);\n //If the user exists, delete the user and his/her reviews\n if(result){\n //Remove the user from the db\n Users.remove({\"_id\": req.query.id}, function(err, result){\n res.status(200);\n res.json({message: 'Accounts and Reviews Deleted!'});\n });\n\n //Remove all the users reviews\n Reviews.remove({\"userID\": req.query.id}, function(err, result){\n //res.json({message: 'Reviews Deleted!'});\n });\n \n\n \n } else { //return 404 status if userid does not exist\n res.status(404);\n return res.json({ error: 'Invalid: User does not exist' });\n }\n }); \n\n}", "async onClick(){\n const user = this.props.user;\n const response = await this.deleteUser(user);\n this.props.removeUser(user.id);\n }", "function deleteButton() {\n const idToDelete = $(this)\n .parent()\n .attr('data-id');\n console.log(idToDelete);\n\n API.deleteBill(idToDelete).then(() => {\n refreshBillList();\n });\n}", "function removeadduser(level){\n\tif(level == \"add\"){\n\t\t$('.usernotexist').each(function(){\n\t\t\tif($(this).is(':checked')){\n\t\t\t\tvar did = $(this).attr('did');\n\t\t\t\tif (checkArray(did,userNotExistArray)){\n\t\t\t\t\tvar indx = userNotExistArray.indexOf(did);\n\t\t\t\t\tuserNotExistArray.splice(indx,1);\n\t\t\t\t}\n\t\t\t\tif (!checkArray(did,userExistArray)){\n\t\t\t\t\tuserExistArray.push(did);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}else{\n\t\t$('.userexist').each(function(){\n\t\t\tif($(this).is(':checked')){\n\t\t\t\tvar did = $(this).attr('did');\n\t\t\t\tif (checkArray(did,userExistArray)){\n\t\t\t\t\tvar indx = userExistArray.indexOf(did);\n\t\t\t\t\tuserExistArray.splice(indx,1);\n\t\t\t\t}\n\t\t\t\tif (!checkArray(did,userNotExistArray)){\n\t\t\t\t\tuserNotExistArray.push(did);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t}\n\tcreatetableforinvitation();\n}", "removeUsersFromThreads() {\n const usersThreadsRef = firebaseDB.database().ref(`/Users/${this.state.userId}/Threads`)\n usersThreadsRef.on('value', snapshot => {\n let usersThreads = snapshot.val();\n for (let usersThread in usersThreads) {\n var threadRef = firebaseDB.database().ref(`/Threads/${usersThread}`)\n threadRef.update({\n author: \"[deleted]\"\n })\n }\n })\n }", "removeUser(userId) {\n for (let user of this.getUsers()) {\n if (user._id === userId) {\n this.users.splice(this.users.indexOf(user), 1);\n }\n }\n }", "function confirmRemove(i)\n{\n for (let i=0;i<accounts._accounts.length;i++)\n {\n let emailId = user._emailId;\n if (accounts._accounts[i]._emailId == emailId)\n {\n user = accounts._accounts[i];\n updateLocalStorageUser(user)\n }\n }\n user.removeTrip(i);\n \n updateLocalStorageUser(user);\n updateLocalStorageAccount(accounts);\n window.location = \"scheduledTrips.html\";\n}", "removeUsersFromPosts() {\n const usersPostsRef = firebaseDB.database().ref(`/Users/${this.state.userId}/Posts`)\n usersPostsRef.on('value', snapshot => {\n let usersPosts = snapshot.val();\n for (let usersPost in usersPosts) {\n var postRef = firebaseDB.database().ref(`/Posts/${usersPost}`)\n postRef.update({\n author: \"[deleted]\"\n })\n }\n })\n }", "deleteUser({ params }, res) {\n User.findOneAndDelete({ _id: params.id })\n .then(dbUserData => {\n if (!dbUserData) {\n res.status(404).json({ message: 'No user found with this id!' });\n return;\n }\n //need to update any users that may have this user in friends list\n User.updateMany(\n //the id in their friends list\n {\n _id: { $in: dbUserData.friends }\n },\n //remove the user\n {\n $pull: { friends: params.id }\n }\n )\n .then(() => {\n //delete any thoughts this user has\n Thought.deleteMany(\n {\n username: dbUserData.username\n }\n )\n .then(response => {\n console.log(response);\n res.json({ message: 'User deleted successfully!' })\n })\n .catch(err => res.status(404).json(err));\n })\n .catch(err => res.status(404).json(err));\n })\n .catch(err => res.status(404).json(err));\n }", "static delete_all() {\n this.#users.remove({},{},function(err,num) {\n if (!err) {\n console.log(\"Deleted\",num,\"users\");\n }\n })\n }", "function removeTweet(deleteID){\n //filter TweetList by filter/letting stay any tweetInput's ID that IS NOT the deleteID\n tweetList = tweetList.filter(tweetInput => tweetInput.id != deleteID)\n //filter TweetList by filter/letting stay any retweetTweet's originTweet ID that is NOT the \n tweetList = tweetList.filter(retweetTweet => retweetTweet.originTweetId != deleteID)\n showTweet(tweetList)\n }", "function UserProfile() {\n const [user, setUser] = useState({});\n const { userId } = useParams();\n const history = useHistory();\n\n useEffect(() => {\n const abortController = new AbortController();\n fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, {\n signal: abortController.signal,\n })\n .then((response) => response.json())\n .then(setUser)\n .catch((error) => {\n if (error.name !== \"AbortError\") {\n console.error(error);\n }\n });\n\n return () => {\n abortController.abort(); // cancels any pending request or response\n };\n }, [userId]);\n\n const rows = Object.entries(user).map(([key, value]) => (\n <div key={key}>\n <label>{key}</label>: {JSON.stringify(value)}\n <hr />\n </div>\n ));\n\n const deleteHandler = (event) => {\n \n // This will be successful but will not actually delete the user.\n fetch(\n `https://jsonplaceholder.typicode.com/users/${userId}`,\n { method: \"DELETE\" } // the delete method tells the API to delete the user\n )\n .then((response) => response.json())\n .then((data) => console.log(`fetch returned:\"${data} . Next action= history.push(\"/\")`))\n .then(() => history.push(\"/\"));\n };\n\n if (user.id) {\n return (\n <div>\n <button type=\"button\" onClick={deleteHandler}>\n Delete\n </button>\n {rows}\n </div>\n );\n }\n return \"Loading...\";\n}", "function deleteFriend(uid) {\n //Delete on user's side\n var userFriendArrBackup = friendArr;\n var friendFriendArrBackup = [];\n var verifyDeleteBool = true;\n var toDelete = -1;\n\n for (var i = 0; i < friendArr.length; i++){\n if(friendArr[i] == uid) {\n toDelete = i;\n break;\n }\n }\n\n if(toDelete != -1) {\n friendArr.splice(toDelete, 1);\n\n for (var i = 0; i < friendArr.length; i++) {\n if (friendArr[i] == uid) {\n verifyDeleteBool = false;\n break;\n }\n }\n } else {\n verifyDeleteBool = false;\n }\n\n if(verifyDeleteBool){\n removeFriendElement(uid);\n user.friends = friendArr;\n generateAddUserBtn(); //Regenerate the button for new friendArr\n\n firebase.database().ref(\"users/\" + user.uid).update({\n friends: friendArr\n });\n\n //alert(\"Friend Successfully removed from your list!\");\n } else {\n friendArr = user.friends;\n firebase.database().ref(\"users/\" + user.uid).update({\n friends: userFriendArrBackup\n });\n alert(\"Delete failed, please try again later! (user)\");\n return;\n }\n\n\n\n //Delete on friend's side\n verifyDeleteBool = true;\n toDelete = -1;\n var friendFriendArr;//Weird name, I know, but it's the friend's friend Array...\n\n for (var i = 0; i < userArr.length; i++){\n if(userArr[i].uid == uid) {\n friendFriendArr = userArr[i].friends;\n friendFriendArrBackup = friendFriendArr;\n break;\n }\n }\n for (var i = 0; i < friendFriendArr.length; i++){\n if (friendFriendArr[i] == user.uid){\n toDelete = i;\n break;\n }\n }\n\n if(toDelete != -1) {\n friendFriendArr.splice(toDelete, 1);\n\n for (var i = 0; i < friendFriendArr.length; i++) {\n if (friendFriendArr[i] == user.uid) {\n verifyDeleteBool = false;\n break;\n }\n }\n } else {\n verifyDeleteBool = false;\n }\n\n if(verifyDeleteBool){\n firebase.database().ref(\"users/\" + uid).update({\n friends: friendFriendArr\n });\n\n //alert(\"Friend Successfully removed from their list!\");\n } else {\n firebase.database().ref(\"users/\" + uid).update({\n friends: friendFriendArrBackup\n });\n alert(\"Delete failed, please try again later! (friend)\");\n }\n }", "onDeletesuppliers(event) {\n event.preventDefault();\n if (this.state.suppliersId != \"\") {\n fetch(`${this.url}/${this.state.suppliersId}`, {method: 'DELETE'})\n .then(response => response.json())\n .then(data => { \n // returns the record that we deleted so the ids should be the same \n if (this.state.suppliersId == data.suppliersId)\n {\n this.state.suppliersId = \"\";\n this.state.suppliers = null;\n this.$suppliersId.value = \"\";\n this.clearsuppliersFields();\n this.enableButtons(\"pageLoad\");\n alert(\"suppliers was deleted.\")\n }\n else{\n alert('There was a problem deleting suppliers info!'); \n }\n })\n .catch(error => {\n alert('There was a problem deleting suppliers info!'); \n });\n }\n else {\n // this should never happen if the right buttons are enabled\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Este metodo renderiza todas las skills del usuario que fue seleccionado con el metodo "SelectCard()" y despliega el componente Skill en relacion con la cantidad que se haya encontrado en la base de datos.
renderSkils() { var me = this; const movieItems = []; (this.state.Skills[this.state.currentUser] && Object.keys(this.state.Skills[this.state.currentUser]).map((i) => { return (movieItems.push(<Skill type={i} amount={this.state.Skills[this.state.currentUser][i]} key={i} />)); })); return movieItems; }
[ "function renderSelectedSkills() {\n // Get div\n let selected = document.getElementById(\"selected-skills\");\n \n // Clear old skills\n while (selected.firstChild) {\n selected.removeChild(selected.firstChild);\n }\n\n // Create the skill name text and dropdown selector for each selected skill\n for(let name of Object.keys(selectedSkills)){\n // Create new skill div container\n let newSkill = document.createElement(\"div\");\n newSkill.className = \"skill\";\n let newSkillText = document.createElement(\"p\");\n newSkillText.innerText = name;\n\n // Add level selector dropdown\n let newSkillLevel = document.createElement(\"select\");\n newSkillLevel.className = \"selected-level\";\n newSkillLevel.onchange = function() {updateLevels(this)};\n createLevelRange(newSkillLevel, skillList[name], selectedSkills[name]);\n \n // Append to the skill list\n newSkill.appendChild(newSkillText);\n newSkill.appendChild(newSkillLevel);\n selected.appendChild(newSkill);\n }\n}", "function addSkill() {\n let select = document.getElementById(\"skill-select\");\n let options = select.options; \n let opt;\n for(let i=1; i<options.length; i++){\n opt = options[i];\n if(opt.selected && !Object.keys(selectedSkills).includes(opt.innerText)) {\n selectedSkills[opt.innerText] = 0;\n renderSelectedSkills();\n break;\n }\n }\n}", "function showSkills(req) {\n if (req.data.skills.length > 0) {\n for (i=0; i < req.data.skills.length; i++) {\n var skill = req.data.skills[i];\n showSkill(skill);\n }\n }\n else {\n $('#skills-list').append('<p>No skills added yet...</p>');\n }\n}", "function showSkill(skill) {\n var content =\n '<p>' + skill.title + '</p>' +\n '<div class=\"w3-light-grey w3-round-xlarge w3-small\" style=\"color:#52B77C;\">' +\n '<div class=\"w3-container w3-center w3-round-xlarge w3-teal\" style=\"width:' + skill.skill_level + '%\">' + skill.skill_level + '%</div>' +\n '</div>'\n $('#skills-list').append(content);\n}", "function addMasterSkillToMySkills(event) { \n const id = `#${event.currentTarget.id}`; \n let skill = $(id).text();\n\n let skillIndex = -1;\n if (!props.USER_PROFILE.skills) {\n props.USER_PROFILE.skills = []\n }\n\n // check if skill already exists in the user's skill collection\n // if so then update instead of add\n for(let idx=0; idx< props.USER_PROFILE.skills.length ; idx++)\n {\n if (props.USER_PROFILE.skills[idx].skill == skill) {\n skillIndex = idx;\n break;\n }\n }\n\n if (skillIndex > -1)\n {\n props.USER_PROFILE.skills[skillIndex].yearsOfExperience = 1;\n }\n else {\n props.USER_PROFILE.skills.push(JSON.parse(`{\"skill\": \"${skill.trim()}\",\"yearsOfExperience\":\"1\"}`)); \n }\n\n // create json object to update the user skills\n const userSkills = `{\"id\": \"${props.userProfileId}\",\"skills\": ${JSON.stringify(props.USER_PROFILE.skills)}}`; \n\n setTimeout(putCareerStrategyAPI(pathUserProfile, JSON.parse(userSkills), props.userProfileId, function(data) { \n renderUserSkills();\n }), 3000); \n}", "function displayMasterSkills(data) {\n if (apiReturnedError(data)) return;\n\n let skills = `\n <div flex-item>\n <div class=\"section-header\"><h3 tabindex=\"0\">Master list of skills</h3> <em> (click on a skill to add it to your skills)</em></div> \n <p flex-item-skills\">`; \n \n data.skill.map( function(skill, index) { \n skills += `<a href=# id=\"masterSkill${index}\" class=\"widget-button-one js-add-master-skill-to-user\">${skill.skill}</a>`; \n });\n skills += '</p>'; \n \n $('.js-page-content').append(`${skills}`); \n}", "render() {\n const { skillData, settings } = this.state;\n \n return (\n <div>\n {\n skillData.map((skill, index) => \n <div key={index}>\n <SkillInfo \n skillData={skill}\n name={skill.name}\n properties={{}}\n shortDesc={skill.shortDesc}\n maxLevel={skill.maxLevel}\n animationSetting={settings.animations}/>\n </div>\n )\n }\n <a href=\"#skill\"><span className=\"jump-button-tabs\"/></a>\n </div>\n );\n }", "function initArmorSkillDropdown(data){\n let dropdown = document.getElementById(\"skill-select\");\n for(let sk of Object.keys(data).sort()){\n // Create dropdown option\n let newSkill = document.createElement(\"option\");\n newSkill.innerText = sk;\n newSkill.value = sk;\n dropdown.appendChild(newSkill);\n }\n // Create charm dropdowns\n // ADD\n let addSkill1 = document.getElementById(\"add-skill1-label\");\n let clonedDropdown = dropdown.cloneNode(true);\n clonedDropdown.id = \"add-skill1\";\n // clonedDropdown.onchange = function() {updateAddCharm(this.id, this.value)}\n addSkill1.appendChild(clonedDropdown);\n\n let addSkill2 = document.getElementById(\"add-skill2-label\");\n clonedDropdown = dropdown.cloneNode(true);\n clonedDropdown.id = \"add-skill2\";\n // clonedDropdown.onchange = function() {updateAddCharm(this.id, this.value)}\n addSkill2.appendChild(clonedDropdown);\n\n let addSkill1Level = document.getElementById(\"add-level1-label\");\n let newSelect = document.createElement(\"select\");\n newSelect.id = \"add-level1\";\n createLevelRange(newSelect, 7, 0);\n addSkill1Level.appendChild(newSelect);\n\n let addSkill2Level = document.getElementById(\"add-level2-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"add-level2\";\n createLevelRange(newSelect, 7, 0);\n addSkill2Level.appendChild(newSelect);\n\n let addSlot1Level = document.getElementById(\"add-slot1-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"add-slot1\";\n createLevelRange(newSelect, 3, 0);\n addSlot1Level.appendChild(newSelect);\n\n let addSlot2Level = document.getElementById(\"add-slot2-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"add-slot2\";\n createLevelRange(newSelect, 3, 0);\n addSlot2Level.appendChild(newSelect);\n\n let addSlot3Level = document.getElementById(\"add-slot3-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"add-slot3\";\n createLevelRange(newSelect, 3, 0);\n addSlot3Level.appendChild(newSelect);\n\n // EDIT\n let editSkill1 = document.getElementById(\"edit-skill1-label\");\n clonedDropdown = dropdown.cloneNode(true);\n clonedDropdown.id = \"edit-skill1\";\n // clonedDropdown.onchange = function() {updateeditCharm(this.id, this.value)}\n editSkill1.appendChild(clonedDropdown);\n\n let editSkill2 = document.getElementById(\"edit-skill2-label\");\n clonedDropdown = dropdown.cloneNode(true);\n clonedDropdown.id = \"edit-skill2\";\n // clonedDropdown.onchange = function() {updateeditCharm(this.id, this.value)}\n editSkill2.appendChild(clonedDropdown);\n\n let editSkill1Level = document.getElementById(\"edit-level1-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-level1\";\n createLevelRange(newSelect, 7, 0);\n editSkill1Level.appendChild(newSelect);\n\n let editSkill2Level = document.getElementById(\"edit-level2-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-level2\";\n createLevelRange(newSelect, 7, 0);\n editSkill2Level.appendChild(newSelect);\n\n let editSlot1Level = document.getElementById(\"edit-slot1-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-slot1\";\n createLevelRange(newSelect, 3, 0);\n editSlot1Level.appendChild(newSelect);\n\n let editSlot2Level = document.getElementById(\"edit-slot2-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-slot2\";\n createLevelRange(newSelect, 3, 0);\n editSlot2Level.appendChild(newSelect);\n\n let editSlot3Level = document.getElementById(\"edit-slot3-label\");\n newSelect = document.createElement(\"select\");\n newSelect.id = \"edit-slot3\";\n createLevelRange(newSelect, 3, 0);\n editSlot3Level.appendChild(newSelect);\n // Save data object for later use\n skillList = data;\n}", "function SingleCampus(props) {\n\n\n const campusId = Number(props.match.params.campusid);\n const campuses = props.campus.campuses\n const selectedCampus = campuses.filter(campus => campus.id === campusId )\n const allstudents = props.student.students\n const studentlist = allstudents.filter(student=>student.campusId === campusId)\n\n return (\n <div>\n <h3>\n <span> {selectedCampus[0].name}</span>\n </h3>\n <div className=\"row\">\n {\n <div className=\"col-xs-3 tile\" key={selectedCampus[0].id}>\n <div className=\"thumbnail\" to={`/campus/${selectedCampus[0].id}`}>\n <ShowPix url={'/' + selectedCampus[0].imageurl} />\n </div>\n </div>\n\n }\n </div>\n <div>\n <h3>Students\n <button type=\"button\" className=\"btn btn-default btn-group-sm\">New Student</button>\n </h3>\n <div className=\"row\">\n {studentlist.map(student1 => (\n <Student student={student1} />\n ))\n }\n </div>\n </div>\n </div>\n );\n}", "function displayAllMembersAndNamesMenu(mainCanvasContainer, namesCanvasContainer) {\n\n fetch('http://sandbox.bittsdevelopment.com/code1/fetchemployees.php')\n .then((response) => {\n return response.json();\n })\n .then((allMembersObject) => {\n\n let cards = \"\";\n\n let namesMenu = `<form action=\"#\" method=\"GET\">\n <fieldset>\n <legend>Find Team Member By Name</legend>\n <div>\n <label for=\"employeenames\">Select an employee:</label>\n </div>\n <div>\n <select name=\"employeename\" id=\"employeenames\">`;\n \n // Iterate over each employee member to extract the employee id and name info for use to construct the employee selection drop down list\n Object.entries(allMembersObject).forEach(([key, value]) => {\n const card = generateCard(value);\n \n cards += card;\n\n namesMenu += `<option value=\"${value.employeeid}\">${value.employeefname} ${value.employeelname}</option>`;\n\n });\n\n namesMenu += `</select>\n </div>\n <button type=\"submit\" onclick=\"namesFormHandler(event);\">Select Member</button>\n </fieldset>\n </form>`;\n \n mainCanvasContainer.innerHTML = cards;\n namesCanvasContainer.innerHTML = namesMenu;\n\n })\n .catch((err) => {\n console.log(err)\n });\n\n}", "function addSkill()\n{\n var count = document.getElementById(\"skill-count\");\n var it = count.getAttribute(\"value\");\n if (it >= 8) {\n alert(\"You have reached maximum number of skills\");\n return;\n }\n count.setAttribute(\"value\", ++it);\n\n mainDiv = document.getElementById(\"skills\");\n\n var skill = document.createElement(\"div\"); // Create a <div> node\n skill.setAttribute(\"class\",\"edit-box partition interior-box-format \");\n var divName = \"skill\" + it;\n skill.setAttribute(\"id\",divName);\n\n var deleteButton = document.createElement(\"input\");\n deleteButton.setAttribute(\"type\", \"button\");\n var deleteSkillNum = \"delete-skill\" + it;\n deleteButton.setAttribute(\"id\", deleteSkillNum);\n deleteButton.setAttribute(\"value\", \"Delete\");\n deleteButton.setAttribute(\"class\", \"btn btn-danger\")\n var functionName = \"deleteSkill(\" + it + \",-1)\";\n deleteButton.setAttribute(\"onclick\", functionName);\n skill.appendChild(deleteButton);\n\n var skillChild = document.createElement(\"div\");\n skillChild.setAttribute(\"class\", \"sm-pad form-group\");\n\n var glyphicon = document.createElement(\"span\");\n glyphicon.setAttribute(\"class\",\"glyphicon glyphicon-info-sign\");\n\n var toolTip = document.createElement(\"a\");\n toolTip.setAttribute(\"href\",\"#!\");\n toolTip.setAttribute(\"data-toggle\",\"tooltip\");\n toolTip.setAttribute(\"data-placement\", \"top\");\n toolTip.setAttribute(\"title\",\"The preferred button indicates which card will be displayed when employers search for you!\");\n\n toolTip.appendChild(glyphicon);\n\n\n var prefP = document.createElement(\"label\");\n\n var prefLabel = document.createTextNode(\" Preferred: \");\n var pref = document.createElement(\"input\");\n pref.setAttribute(\"type\", \"radio\");\n pref.setAttribute(\"class\", \"pull-right\");\n var skillID = \"skill-preference\" + it;\n prefP.setAttribute(\"for\", skillID);\n pref.setAttribute(\"id\", skillID);\n pref.setAttribute(\"name\", \"skill-preference\");\n pref.setAttribute(\"value\", it);\n if (mainDiv.childNodes.length == 6) {\n pref.checked = true;\n }\n prefP.appendChild(toolTip);\n prefP.appendChild(prefLabel);\n skillChild.appendChild(prefP);\n skillChild.appendChild(pref);\n\n skill.appendChild(skillChild);\n\n skillChild = document.createElement(\"div\");\n skillChild.setAttribute(\"class\", \"form-group\");\n\n var fieldP = document.createElement(\"label\");\n var fieldLabel = document.createTextNode(\"Field:\");\n var field = document.createElement(\"select\");\n var fieldString = \"field\";\n fieldString = fieldString.concat(it.toString(10));\n fieldP.setAttribute(\"for\", fieldString);\n\n field.setAttribute(\"class\", \"form-control\")\n field.setAttribute(\"name\", fieldString);\n field.setAttribute(\"onclick\", \"updateFields(this)\")\n field.setAttribute(\"id\", fieldString);\n\n fieldP.appendChild(fieldLabel);\n skillChild.appendChild(fieldP);\n skillChild.appendChild(field);\n\n skill.append(skillChild);\n\n skillChild = document.createElement(\"div\");\n skillChild.setAttribute(\"class\", \"form-group\");\n\n var subFieldP = document.createElement(\"label\");\n var subFieldLabel = document.createTextNode(\"Sub-Field:\");\n var subField = document.createElement(\"select\");\n var subFieldString = \"sub-field\";\n var subFieldOption = document.createElement(\"option\");\n var subFieldOptionLabel = document.createTextNode(\"All Sub-Categories\");\n subFieldOption.setAttribute(\"value\", \"blank\");\n subFieldString = subFieldString.concat(it.toString(10));\n subFieldP.setAttribute(\"for\", subFieldString);\n subField.setAttribute(\"name\", subFieldString);\n subField.setAttribute(\"id\", subFieldString);\n subField.setAttribute(\"class\", \"form-control\");\n //subField.setAttribute(\"disabled\", true);\n\n subFieldP.appendChild(subFieldLabel);\n subFieldOption.appendChild(subFieldOptionLabel);\n subField.append(subFieldOption);\n skillChild.appendChild(subFieldP);\n skillChild.appendChild(subField);\n\n skill.appendChild(skillChild);\n\n skillChild = document.createElement(\"div\");\n skillChild.setAttribute(\"class\", \"form-group\");\n\n var contentsP = document.createElement(\"label\");\n var contentsLabel = document.createTextNode(\"About:\");\n var contents = document.createElement(\"textarea\");\n var contentsString = \"contents\";\n contentsString = contentsString.concat(it.toString(10));\n contentsP.setAttribute(\"for\", contentsString);\n\n contents.setAttribute(\"name\", contentsString);\n contents.setAttribute(\"class\", \"form-control\")\n contents.setAttribute(\"type\",\"text\");\n contents.setAttribute(\"size\",40);\n contents.setAttribute(\"rows\",3);\n contents.setAttribute(\"placeholder\",\"Alphanumeric characters only\");\n contents.setAttribute(\"pattern\", \"^[a-zA-Z0-9\\\\s-]+$\");\n //contents.setAttribute(\"disable\", true);\n\n contentsP.appendChild(contentsLabel);\n skillChild.appendChild(contentsP);\n skillChild.appendChild(contents);\n\n skill.appendChild(skillChild);\n\n mainDiv.appendChild(skill);\n\n getFields(\n function () {\n document.getElementById(fieldString).innerHTML = this.responseText;\n }\n )\n return false;\n\n}", "function TechnologyList() {\n const technologies = [\n {\n name: \"Node.js\",\n id: 1,\n },\n {\n name: \"Express\",\n id: 2,\n },\n {\n name: \"React\",\n id: 3,\n },\n {\n name: \"Jest\",\n id: 4,\n },\n {\n name: \"JWT\",\n id: 5,\n },\n {\n name: \"GraphQL\",\n id: 6,\n },\n {\n name: \"MySQL\",\n id: 7,\n },\n {\n name: \"MongoDB\",\n id: 8,\n },\n ];\n\n return (\n <div className=\"technologyContainer\">\n {technologies.map((skill) => (\n <TechnologyElement name={skill.name} key={skill.id} />\n ))}\n </div>\n );\n}", "function renderCollege(data) {\n let x=\"<option value='' disabled selected label='Select The collage that the book belongs to:'></option>\";\n data.forEach(item => {\n x+=\"<option value=\"+item.id+\">\"+item.name+\"</option>\" ;\n });\n college.innerHTML = x ;\n}", "function populateSkillTree() {\n // Get the skill tree DOM element and clear it\n var skillTree = document.getElementById(\"skill-tree\");\n skillTree.innerHTML = \"\";\n\n // Initially unlock the apple and the wheat\n if (!window.game.player.unlockedItems.includes(ITEM_APPLE) && !window.game.player.unlockedItems.includes(ITEM_WHEAT)) {\n window.game.player.unlockedItems.push(ITEM_APPLE);\n window.game.player.unlockedItems.push(ITEM_WHEAT);\n }\n\n // Create a row for each skill tree item\n ITEMS_FOR_SKILL.forEach(function(item, index) {\n skillTree.appendChild(createSkillRow(item, index));\n });\n\n // Resetup tooltips\n setupTooltips();\n \n // Repopulate the store\n populateStore();\n}", "function makeNewSkill (par,i, j) {\n\t\t\n\t\t//Add space-breaking elements.\n\t\tif ((j%3) == 0) {\n\t\t\t//If it's a multiple of three, add two BRs.\n\t\t\tpar.appendChild( document.createElement('br') );\n\t\t\tpar.appendChild( document.createElement('br') );\n\t\t}\n\t\telse {\n\t\t\t//Otherwise, just need a space.\n\t\t\tpar.append(\" \");\n\t\t}\n\t\t\n\t\t// Create the span.\n\t\tlet newSpan = document.createElement('span');\n\t\tnewSpan.classList.add(`skillspan`);\n\t\tnewSpan.id= `skillspan.${i}.${j}`;\n\t\tnewSpan.draggable = \"true\";\n\t\tnewSpan.ondragstart = pickUpSkill;\n\t\t\n\t\t// Create the dropdown.\n\t\tlet newSkill = document.createElement('select');\n\t\tnewSkill.id = `skills.${i}.${j}`;\n\t\tnewSkill.name = `skills${i}[]`;\n\t\tnewSkill.classList.add(`sheet.skillselect`);\n\t\tnewSkill.classList.add(`sheet.skillselect.${i}`);\n\t\tnewSkill.size = 1;\n\t\tnewSkill.innerHTML = options;\n\t\tnewSkill.onchange = skillsChange;\n\t\t\n\t\t//Has this skill existed on the page (and in the array) before?\n\t\tif (aSkills[i][j] != undefined) {\n\t\t\t//If yes, remember the old selection.\n\t\t\tnewSkill.value = aSkills[i][j];\n\t\t}\n\t\telse {\n\t\t\t//If no, fill it in with the placeholder.\n\t\t\tnewSkill.value = \"_\";\n\t\t\taSkills[i][j] = \"_\";\n\t\t}\n\t\t\n\t\t//Add this skill to the span.\n\t\tnewSpan.append(newSkill);\n\t\t\n\t\t//Add the whole thing to the parent.\n\t\tpar.append(newSpan);\n\t}", "function fadeOutSkills() {\n\n skillContent.fadeOut(500);\n\n skillContainer.fadeOut(500, () => {\n\n skillContainer.removeClass('col-lg-5');\n\n skillContainer.addClass('col-lg-12');\n\n for (let i = 0; i < skills.length; i++) {\n\n $(skills[i]).css(styles[i]);\n\n }\n\n skillContainer.fadeIn(500);\n\n });\n\n skillPicker = true;\n\n}", "drawPlayerMenu() {\n if (currentChar != \"none\") {\n push();\n // 2 supporting skills\n for (let i = 0; i < currentChar.abilities[0].length; i++) {\n strokeWeight(3);\n stroke(0);\n // if moused over, it is highlighted\n if (mouseOver.name === currentChar.abilities[0][i].name) {\n fill(0);\n } else {\n fill(255);\n }\n rectMode(CORNER);\n rect(width/7+(i*width/3.5), height-height/4.5, width/4, height/6);\n // name, cost and ability\n noStroke();\n // if moused over, it is highlighted\n if (mouseOver.name === currentChar.abilities[0][i].name) {\n fill(255);\n } else {\n fill(0);\n }\n textAlign(CENTER, CENTER);\n textSize(width/80+height/80);\n text(currentChar.abilities[0][i].name, width/3.75+(i*width/3.5), height-height/6);\n let abilityCostText = \"Cost: \" + currentChar.abilities[0][i].cost + \" Energy\";\n text(abilityCostText, width/3.75+(i*width/3.5), height-height/8);\n textSize(width/150+height/150);\n text(currentChar.abilities[0][i].description, width/3.75+(i*width/3.5), height-height/12);\n // if this is an ultimate, then let the player know\n if (currentChar.abilities[0][i].ultimate === true) {\n textSize(width/100+height/100);\n if (currentChar.ultCharge === 100) {\n fill(0, 255, 0);\n text(\"Ultimate Ready!\", width/3.75+(i*width/3.5), height-height/5);\n } else {\n fill(255, 0, 0);\n text(\"Ultimate Charging\", width/3.75+(i*width/3.5), height-height/5);\n }\n }\n // if this non-ultimate ability has been used this turn and cannot be used again\n if (currentChar.abilities[0][i].used === true && currentChar.abilities[0][i].ultimate === false) {\n textSize(width/100+height/100);\n fill(255, 0, 0);\n text(\"Used This Turn\", width/3.75+(i*width/3.5), height-height/5);\n }\n }\n pop();\n }\n }", "function fadeInSkills(clickedItem) {\n\n skillContainer.fadeOut(500, () => {\n\n skillContainer.removeClass('col-lg-12');\n\n skillContainer.addClass('col-lg-5');\n\n for (let i = 0; i < skills.length; i++) {\n\n $(skills[i]).attr('style', '');\n\n }\n\n clickedZIndex = clickedItem.css('z-index');\n\n clickedLeftPosition = clickedItem.css('left');\n\n clickedTopPosition = clickedItem.css('top');\n\n clickedItem.css({\n\n top: firstTopPozition,\n\n left: firstLeftPozition,\n\n zIndex: firstZIndedx\n\n });\n\n $('#skill1').css({\n\n top: clickedTopPosition,\n\n left: clickedLeftPosition,\n\n zIndex: clickedZIndex\n\n });\n\n var itemID = clickedItem.attr('id');\n\n skillContent.html(skillsDescription[itemID].desc);\n\n skillContainer.fadeIn(500);\n\n skillContent.fadeIn(500);\n\n });\n\n skillPicker = false;\n\n}", "static view() {\n const coursesByDepartment = getCoursesByDepartment(\n courses.list,\n selectedDepartment,\n );\n return getUniqueYears(coursesByDepartment).map(year =>\n m(expandableContent, { name: `Year ${year}`, level: 0 }, [\n getUniqueLecturesByYear(\n coursesByDepartment,\n year,\n ).map(lecture =>\n m(\n expandableContent,\n { name: lecture, level: 1 },\n coursesByDepartment\n .filter(course => course.lecture.year === year)\n .filter(course => course.lecture.title === lecture)\n .map(displayCard),\n ))]));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Here we are calling the discord api using the UrlFetchApp to send request with all the data The discord API can also take 'WEBHOOK' url as authentication rahter than access tokens This makes it extremely user friendly to use and execute The discord API takes the webhook url and 'params' Here, the params is the parameters list that is i.e., method (get/post), the payload (in JSON format that is basically the message), contentType, muteHttpExceptions etc. The Payload parameter takes JSON in string format and that JSON is contained with the matter that is to be posted or displayed. You can check out the Discord API documentation for more usage details. Here the fields param shows the name and value as name and discord id And the next content to be an image Getting only the image from Google Drive was the tricky part as we only get the html not the image file. Had to use > ' to get the image as only img so as to be accessible to the discord api And thats about it!
function postMessageToDiscord(length,naam,discord,file) { //updating sharing options to be accessible anywhere outside and setting its permission as 'VIEW' can also change to 'EDIT' if you'd like file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW); /* * this is the webhook url generated from discord app * to do so.. * 1. open the discord app * 2. Open the server you want to post in. (remember you need permissions or be the owner) * 3. Go to Server Settings > Integrations > Add Webhook > Set the name, avatar and CHANNEL you want the bot to post * 4. Copy the webhook URL and use it below as shown */ var discordUrl = 'https://discord.com/api/webhooks/123456789012345678/XXXXX-XXXXXXXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXX'; //the payload var discordPayload = { content: '', embeds: [{ type: 'rich', title: 'Meme No. '+length, color: 7506394, fields: [ { name : naam, value : discord } ], image : { url: 'https://drive.google.com/uc?export=view&id='+file.getId() } }] } var params = { method: 'post', payload: JSON.stringify(discordPayload), contentType: 'application/json' }; var response = UrlFetchApp.fetch(discordUrl, params); Logger.log(response.getContentText()); }
[ "function sendImage(date, id) {\n let year = date.getFullYear()\n let month = date.getMonth() + 1\n let day = date.getDate()\n //load the page\n request({\n uri: \"http://www.gocomics.com/calvinandhobbes/\" + year + \"/\" + month + \"/\" + day,\n }, function(error, response, body) {\n let $ = cheerio.load(body)\n //get the picture\n let pictureUrl = $('.item-comic-image img').attr('src')\n console.log(pictureUrl)\n //send pic to user\n bot.sendPhoto(id, pictureUrl)\n })\n}", "function inlineImage() {\n // var googleLogoUrl = \"http://www.google.com/intl/en_com/images/srpr/logo3w.png\";\n \n var youtubeLogoUrl =\n \"https://developers.google.com/youtube/images/YouTube_logo_standard_white.png\";\n\n // var googleLogoBlob = UrlFetchApp\n // .fetch(googleLogoUrl)\n // .getBlob()\n // .setName(\"googleLogoBlob\");\n var youtubeLogoBlob = UrlFetchApp\n .fetch(youtubeLogoUrl)\n .getBlob()\n .setName(\"youtubeLogoBlob\");\n MailApp.sendEmail({\n to: \"teeyonglim@hotmail.com\",\n subject: \"Logos\",\n htmlBody: \"inline Youtube Logo <img src = 'cid:youtubeLogo'>\",\n // htmlBody: \"inline Google Logo<img src='cid:googleLogo'> images! <br>\" +\n // \"inline YouTube Logo <img src='cid:youtubeLogo'>\",\n inlineImages:\n {\n // googleLogo: googleLogoBlob,\n youtubeLogo: youtubeLogoBlob\n }\n });\n }", "function sendImageMessage(recipientId,senderId,imageUrl){var messageData={recipient:{id:recipientId},message:{attachment:{type:\"image\",payload:{url:imageUrl}}}};return callSendAPI(messageData,senderId);}", "function webhookTrigger(){\n if(action_webhook){\n console.log('webhook trigger');\n\n var dataString = JSON.stringify(results_json); // '{\"something\":2}';\n\n var contentType = 'application/json';\n\n triggerEmail.httpSend(action_webhook_prototol, action_webhook_host, action_webhook_endpoint, action_webhook_method, contentType, dataString);\n }\n}", "async function comicOn(date) {\n // The direct image link seems to no longer be predictable, but it\n // can be readily parsed out of the meta tags of the comic page.\n let pageUrl = `https://www.gocomics.com/garfield/${date.replace(/-/g, \"/\")}`;\n\n // Non-existent comics now get a 302.\n let pageResponse = await snekfetch.get(pageUrl, {redirect: false});\n if (pageResponse.statusCode != 200) {\n throw new Error();\n }\n\n let $ = cheerio.load(pageResponse.body);\n let imgUrl = $(\"meta[property='og:image']\").attr(\"content\");\n let imgBuffer = (await snekfetch.get(imgUrl)).body;\n\n // The URLs no longer have an extension, so they don't embed in\n // Discord unless we change the filename. And we might as well\n // change it anyway, to show the date. As far as I can tell, the\n // old comics that existed before the redirect are still GIF but new\n // comics are JPEG.\n console.log(imgBuffer);\n let imgType = FileType(imgBuffer);\n let imgName = `${date}.${imgType.ext}`;\n return new MessageAttachment(imgBuffer, imgName);\n}", "function postAchievementsToSlack() {\n // Retrieve stored game information\n var gameJSONString = sessionStorage.getItem('currentGame');\n var gameJSON = JSON.parse(gameJSONString);\n\n var playerInFirst = JSON.parse(sessionStorage.getItem('playerInFirst'));\n var playerInLast = JSON.parse(sessionStorage.getItem('playerInLast'));\n\n var slackBody ='{\"text\": \"*Cheevos!*\", \"attachments\": [';\n for (i = 0; i < gameJSON.achievements.length; i++) {\n if (i == gameJSON.achievements.length - 1) {\n var cheevoAttachment = '{\"author_name\": \"Cheevo Bot\", \"author_icon\": \"http://a.slack-edge.com/7f18https://a.slack-edge.com/a8304/img/api/homepage_custom_integrations-2x.png\", \"image_url\": \"http://league-tracker-ui-2.mybluemix.net/images/' + gameJSON.achievements[i].name + '.png\" }, { \"title\": \"Eligible Players\", \"text\": \"' + playerInLast + '\"}';\n cheevoAttachment += ']}';\n } else {\n var cheevoAttachment = '{\"author_name\": \"Cheevo Bot\", \"author_icon\": \"http://a.slack-edge.com/7f18https://a.slack-edge.com/a8304/img/api/homepage_custom_integrations-2x.png\", \"image_url\": \"http://league-tracker-ui-2.mybluemix.net/images/' + gameJSON.achievements[i].name + '.png\" }, { \"title\": \"Eligible Players\", \"text\": \"NOT ' + playerInFirst + '\"}';\n cheevoAttachment += ',';\n }\n slackBody += cheevoAttachment;\n }\n console.log('Slack body = ' + slackBody);\n\n // Post the achievements to slack\n $.ajax({\n type: 'POST',\n// beforeSend: function(request) {\n// request.setRequestHeader(\"Content-type\", \"application/json\");\n// },\n url: 'https://hooks.slack.com/services/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',\n// data: '{ \"text\": \"Cheevos!\", \"attachments\": [{ \"title\": \"For NOT Elliot\", \"fields\": [{ \"title\": \"Volume\", \"value\": \"1\", \"short\": true }, { \"title\": \"Issue\", \"value\": \"3\", \"short\": true } ], \"author_name\": \"Stanford S. Strickland\", \"author_icon\": \"http://a.slack-edge.com/7f18https://a.slack-edge.com/a8304/img/api/homepage_custom_integrations-2x.png\", \"image_url\": \"http://league-tracker-ui-2.mybluemix.net/images/yaBasic.png\" }, { \"title\": \"Synopsis\", \"text\": \"After @episod pushed exciting changes to a devious new branch back in Issue 1, Slackbot notifies @don about an unexpected deploy...\" } ] }'\n data: slackBody,\n }).done(function(response) {\n console.log('Successfully POSTed results');\n// window.location.href=\"mainMenu.html?seasonId=\" + seasonId;\n }).fail(function(data) {\n console.log('Failed to POST results: ' + data);\n });\n}", "function inlineReceipt(row) {\n // var receiptUrl = row.pleaseAttachReceipt;\n var receiptUrl= \"https://drive.google.com/open?id=18_R-KqbVC-QHYHne7W2pGIVh-tqw3Mom\";\n var receiptBlob = UrlFetchApp\n .fetch(receiptUrl)\n .getBlob()\n .setName(\"receiptBlob\");\n \n MailApp.sendEmail({\n to: \"teeyonglim@hotmail.com\",\n subject: \"Receipt Test\",\n htmlBody: \"inline receipt <img src='cid:receipt'> <br>\",\n \n inlineImages:\n {\n receipt: receiptBlob\n \n }\n });\n }", "copyToSlack(data) {\n const body = {\n \"channel\": \"#dev-team\",\n \"username\": \"Standup_Times\",\n \"text\": data,\n \"icon_url\": \"https://pbs.twimg.com/profile_images/76277472/bender.jpg\"\n };\n // console.log(\"Send to Slack\");\n // console.log(this.timerData);\n request_1.default({\n url: \"https://hooks.slack.com/services/\" + this.slackUrl,\n method: \"POST\",\n json: true,\n body: body,\n headers: {\n \"content-type\": \"application/json\",\n }\n }, function (err, resp, body) {\n if (err) {\n // console.log(err, err.stack);\n }\n else {\n // console.log(resp.statusCode);\n // console.log(resp.statusMessage);\n // console.log(body);\n }\n });\n }", "function sendGifMessage(recipientId,senderId,gifUrl){var messageData={recipient:{id:recipientId},message:{attachment:{type:\"image\",payload:{url:SERVER_URL+gifUrl}}}};return callSendAPI(messageData,senderId);}", "static imageCommand (guild_id: string, name: string, imageUrl: string) {\n return new Response({\n guild_id: guild_id,\n name: name,\n content: imageUrl,\n is_image: true,\n requires_prefix: true\n });\n }", "function requestOCR(event, imgUrl) {\r\n const GOOGLE_API_KEY = '<<GOOGLE_API_KEY HERE>>';\r\n const URL = 'https://vision.googleapis.com/v1/images:annotate?key=' + GOOGLE_API_KEY;\r\n const MAX_RESULTS = 3;\r\n\r\n const senderID = event.sender.id;\r\n\r\n // Image URL cannot be extracted from event at this point because we lack the array index reference\r\n var imgOptions = { url: imgUrl, encoding: null };\r\n\r\n request.get(imgOptions, function (err, res, body) {\r\n const payload = {\r\n requests: [ {\r\n image: {\r\n content: base64.fromByteArray(body)\r\n },\r\n features: [\r\n {\r\n type: 'TEXT_DETECTION',\r\n maxResults: MAX_RESULTS\r\n } ]\r\n } ]\r\n }\r\n\r\n var options = {\r\n method: 'POST',\r\n body: payload,\r\n json: true,\r\n url: URL,\r\n headers: {'content-type': 'application/json'}\r\n }\r\n\t\r\n request(options, function (err, res, body) {\r\n if (err) {\r\n console.log('Error: ', err);\r\n sendTextMessage(senderID, 'Oops! There was an error processing the image. Please try again.');\r\n return;\r\n }\r\n // Build JSON object to insert into DB\r\n var insertData = {\r\n 'fbmessage': event,\r\n 'googleocr': body\r\n }\r\n\r\n esclient.index({\r\n index: 'receipt',\r\n type: 'fbmessenger',\r\n body: insertData\r\n }, function (err, res) {\r\n if (err) {\r\n console.log('Error: ', err);\r\n sendTextMessage(senderID, 'Oops! There was a problem saving the information. Please try again.');\r\n return;\r\n }\r\n\r\n const id = res._id;\r\n sendTextMessage(senderID, 'Added record with ID: ' + id);\r\n sendTextMessage(senderID, \"To view the extracted text, please enter 'view \" + id + \"'.\");\r\n });\r\n });\r\n });\r\n}", "function logEmbed(msg) {\n var embed = new Discord.RichEmbed()\n .setFooter(new Date().toLocaleDateString())\n .setAuthor(msg.author.username, msg.author.avatarURL)\n .setColor(\"#e8c67d\")\n .setDescription(msg.content);\n if (msg.attachments.first()) {\n embed.setImage(msg.attachments.first().url);\n }\n return embed;\n}", "function discordSuccessMsg(str) {\n const webhook = require(\"webhook-discord\");\n const Hook = new webhook.Webhook(\"Insert Webhook\");\n const msg = new webhook.MessageBuilder()\n .setName(\"Console\")\n .setColor(\"#3ce74c\")\n .setDescription(`${str}`);\n Hook.send(msg);\n}", "function makeRequest(APIkey, imageAs64) {\n //the request to be made to the Google Vision API\n var request = {\n requests: [{\n image: {\n content: imageAs64\n },\n features: [\n {\n type: \"LABEL_DETECTION\",\n maxResults: 10\n },\n {\n type: \"LOGO_DETECTION\",\n maxResults: 10\n },\n {\n type: \"TEXT_DETECTION\",\n maxResults: 10\n }\n\n ]\n }]\n };\n\n //make an ajax post \n return $.ajax({\n type: 'POST',\n url: URL + APIkey,\n data: JSON.stringify(request),\n contentType: \"application/json\",\n dataType: 'json'\n });\n}", "function getItems() {\n fetch('http://genshinnews.com/api')\n .then(response => response.text())\n .then(data => {\n discordHooks = JSON.parse(`[${data}]`)\n webhookLoop(discordHooks)\n });\n }", "function sendAccountLinking(recipientId,senderId,payload){var messageData={recipient:{id:recipientId},message:{attachment:{type:\"template\",payload:payload}}};/*\n\n {\n template_type: \"button\",\n text: \"Welcome. Link your account.\",\n buttons:[{\n type: \"account_link\",\n url: SERVER_URL + \"/authorize\"\n }]\n }\n\n * */return callSendAPI(messageData,senderId);}", "async function fetchBlobstoreUrl() {\n fetch('/blobstore-url')\n .then((response) => {\n return response.text();\n })\n .then((imageUploadUrl) => {\n const messageForm = document.getElementById('logo-form');\n messageForm.action = imageUploadUrl;\n });\n}", "async function updateIntentAPI(intentID,previousTrainingPhrases,newTrainingPhrases,previousMessageTexts,newMessageTexts,displayName) { // NEW EDITED\n // Imports the Dialogflow library\n \n // Instantiates clients\n const intentsClient = new dialogflow.IntentsClient(CONFIGURATION);\n\n const projectAgentPath = intentsClient.projectAgentPath(PROJECTID);\n\n console.log(projectAgentPath);\n\n // const request = {\n // parent: projectAgentPath,\n // };\n\n\n // const [response] = await intentsClient.listIntents(request);\n \n var intent =await getIntent(intentID);\n console.log(\"test data is \",intent);\n\n\n const trainingPhrases = [];\n\n const combinedMessageTextsOriginal =previousMessageTexts.concat(newMessageTexts);\n\n var combinedMessageTexts = combinedMessageTextsOriginal.filter((item,index)=>{\n\n return (combinedMessageTextsOriginal.indexOf(item)==index);\n\n })\n\n const messageText = {\n text: combinedMessageTexts,\n };\n\n const message = {\n text: messageText,\n };\n\n \n previousTrainingPhrases.forEach(textdata => {\n newTrainingPhrases.push(textdata);\n });\n\n newTrainingPhrases.forEach(phrase => {\n const part = {\n text: phrase\n };\n\n // Here we create a new training phrase for each provided part.\n const trainingPhrase = {\n type: \"EXAMPLE\",\n parts: [part]\n };\n trainingPhrases.push(trainingPhrase);\n });\n \n intent.trainingPhrases = trainingPhrases;\n intent.displayName = displayName;\n intent.messages = [message];\n\n\n\n\n const updateIntentRequest = {\n intent\n \n };\n\n // Send the request for update the intent.\n const result = await intentsClient.updateIntent(updateIntentRequest);\n console.log(\"Success.\")\n return result;\n}", "function postWinnerMessage(winnersInfo, channels, title, message) {\n let attachments = []\n \n winnersInfo.forEach(userInfo => {\n attachments.push({\n //pretext: message,\n color: '#36a64f',\n author_name: userInfo.real_name,\n author_icon: userInfo.profile.image_48,\n thumb_url: userInfo.profile.image_192,\n footer: title,\n ts: Date.now()\n })\n })\n \n let jsonPayload = {\n text: message,\n as_user: false,\n icon_emoji: \":tada\",\n attachments: attachments\n }\n postMessage(channels, jsonPayload)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
polyvecAdd adds two vectors of polynomials.
function polyvecAdd(a, b, paramsK) { var c = new Array(3); for (var i = 0; i < paramsK; i++) { c[i] = polyAdd(a[i], b[i]); } return c; }
[ "function polyAdd(a, b) {\r\n var c = new Array(384);\r\n for (var i = 0; i < paramsN; i++) {\r\n c[i] = a[i] + b[i];\r\n }\r\n return c;\r\n}", "static vAdd(a,b) { return newVec(a.x+b.x,a.y+b.y,a.z+b.z); }", "static Add(vector1, vector2) {\n return new Vector4(vector1.x, vector1.y, vector1.z, vector1.w).addInPlace(vector2);\n }", "function polySub(a, b) {\r\n for (var i = 0; i < paramsN; i++) {\r\n a[i] = a[i] - b[i];\r\n }\r\n return a;\r\n}", "function calculateSum(vectors){\n var sum = new THREE.Vector2();\n for (let i = 0; i < vectors.length; i++) {\n sum.x += vectors[i].x;\n sum.y += vectors[i].y;\n }\n return sum;\n}", "function vectorOperation(v1, v2, op) {\n let minLength = Math.min(v1.length, v2.length);\n let newV = [];\n for (let i = 0; i < minLength; i++) {\n newV.push(op(v1[i] * 1.0, v2[i]));\n }\n return newV;\n}", "function polyEval(evalPoint, constTerm, ...coeffs) {\n return add(constTerm, ...coeffs.map((c, j) => c.mul(scalar(evalPoint).toThe(scalar(j+1)))))\n}", "addVectors(aBar, bBar){\n if(aBar.length == bBar.length){\n for(let i = 0; i < aBar.length; i++){\n aBar[i] = aBar[i] + bBar[i];\n }\n }\n }", "addVector3(otherVector) {\n return new Vector2(this.x + otherVector.x, this.y + otherVector.y);\n }", "add(otherVector) {\n return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);\n }", "add(otherVector) {\n return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);\n }", "function polyvecNew(paramsK) {\r\n // make array containing 3 elements of type poly\r\n var pv = new Array(paramsK);\r\n for (var i = 0; i < paramsK; i++) {\r\n pv[i] = new Array(384);\r\n }\r\n return pv;\r\n}", "function polyvecReduce(r, paramsK) {\r\n for (var i = 0; i < paramsK; i++) {\r\n r[i] = polyReduce(r[i]);\r\n }\r\n return r;\r\n}", "function subVectors(vec1, vec2) {\n return new Vector(vec1.x - vec2.x, vec1.y - vec2.y);\n}", "function polyvecPointWiseAccMontgomery(a, b, paramsK) {\r\n var r = polyBaseMulMontgomery(a[0], b[0]);\r\n var t;\r\n for (var i = 1; i < paramsK; i++) {\r\n t = polyBaseMulMontgomery(a[i], b[i]);\r\n r = polyAdd(r, t);\r\n }\r\n return polyReduce(r);\r\n}", "function dotProduct(vec1, vec2) {\n return vec1[0]*vec2[0] + vec1[1]*vec2[1];\n}", "addToRef(otherVector, result) {\n return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);\n }", "function calculateDotProduct(vectors){\n var dot;\n var xdot;\n var ydot;\n for (let i = 0; i < vectors.length; i++) {\n if(i == 0)\n {\n xdot = vectors[i].x;\n ydot = vectors[i].y;\n }\n else\n {\n xdot = xdot* vectors[i].x;\n ydot = ydot* vectors[i].y;\n }\n }\n\n return xdot + ydot;\n}", "AddPolyline(points, num_points, col, closed, thickness) {\r\n this.native.AddPolyline(points, num_points, col, closed, thickness);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calling the stacks ApI to get the questions
function callStackAPI() { $.ajax({ url: urlStack, method: "GET" }).then(function (response) { for (var i = 0; i < 5; i++) { var qstnObject = {}; var keywordURL = ""; var keywordTitle = ""; qstnObject.keywordURL = response.items[i].link; qstnObject.keywordTitle = response.items[i].title; questionsArray.push(qstnObject); } showQuestions(questionsArray); }) }
[ "function getQuestion() {\n \n \n }", "function getQuestions() {\r\n\r\n\tclient = new XMLHttpRequest();\r\n\tclient.open('GET','http://developer.cege.ucl.ac.uk:30288/getquestions');\r\n\tclient.onreadystatechange = questionResponse;\r\n\tclient.send();\r\n}", "function fetchQuestions() {\n server.get('dailyQuestions')\n .then((response) => {\n setQuestions(response.data.questions);\n });\n }", "function getAllQuestionParts() {\n $.ajax({\n url: 'get/',\n dataType: 'json'\n }).done(function(data) {\n initQuestionParts(data['questions']);\n }).fail(function(request, error) {\n console.log('Error while getting all question parts');\n });\n }", "function showQuestions() {\n for (var i = 0; i < questionsArray.length; i++) {\n var questionHTML = getQuestionHTML(questionsArray[i], i + 1)\n $(\"#questions\").append(questionHTML);\n }\n }", "function askQ(qArray,toc,sections){\n let ans = [];\n inquirer.prompt(qArray).then((ans) => {\n createReadme(ans,toc,sections);\n}).catch(err => {console.log(err)})\n}", "function initialise (quizz){\n if (quizz === \"kaamelott\") {\n kaamelott.forEach(item => {\n questionArray.push(new Question(item[0], item[1], item[2], item[3], item[4], item[item[5]]));\n });\n } else if (quizz === \"manga\") {\n manga.forEach(item => {\n questionArray.push(new Question(item[0], item[1], item[2], item[3], item[4], item[item[5]]));\n });\n }\n addQuestion(questionArray[ind]);\n}", "async queryQnaService(endpoint, question, options) {\n const url = `${endpoint.host}/knowledgebases/${endpoint.knowledgeBaseId}/generateanswer`;\n const headers = this.getHeaders(endpoint);\n const queryOptions = { ...this._options, ...options };\n this.validateOptions(queryOptions);\n const qnaResult = await request({\n url: url,\n method: 'POST',\n headers: headers,\n json: {\n question: question,\n ...queryOptions\n }\n });\n return this.formatQnaResult(qnaResult);\n }", "function openQuiz(event, subject) {\n let questionsDiv = document.getElementById(\"questions\");\n questionsDiv.innerHTML = \"\";\n populateQuestions(questionsDiv, subject);\n console.log('populate questions by type');\n}", "showGroupQuestions() {\n const onDone = () => {\n return this.checkTaskEnd();\n };\n\n if (this.dones[this.groupIdx]) {\n return onDone();\n }\n\n // show form\n this.pswpOpen = false;\n this.$galleries.hide();\n this.$experiment.hide();\n this.$form.show();\n\n const group = this.data.groups[this.groupIdx];\n const schemaform = {\n schema: {\n ...group.questions.schema,\n ...this.data.extraQuestionsEachGroup.schema\n },\n form: [\n ...group.questions.form,\n ...this.data.extraQuestionsEachGroup.form\n ]\n };\n\n this.$form.empty();\n formFromJSON(this.$form, schemaform, (values) => {\n $.post({\n url: \"/api/group-survey\" + window.location.search,\n data: JSON.stringify({\n values,\n groupIdx: this.groupIdx\n }),\n contentType: \"application/json\"\n }).done(() => onDone());\n });\n }", "function setAvailableQuestions(){\n\tconst totalQuestions=quiz.length;\n\tfor(let i=0;i<totalQuestions; i++){\n\t\tavailableQuestions.push(quiz[i])\n\t}\n}", "function user_question_view(ref_id){\n var reply_type = \"json\";\n var vars = {};\n if (ref_id == '' || ref_id == undefined){\n vars.url = myhost+'/view/question_all/';\n vars.content = \"question\";\n } else {\n vars.url = myhost+'/view/question_replys/';\n vars.content = \"replys\";\n }\n vars.ref_id = ref_id;\n global.user_agent\n .get(vars.url)\n .set('Content-Type', 'application/json')\n .query({m_id:ref_id, reply_type:reply_type})\n .end(function(err, res){\n if (err) {\n myutil.error(\"== user_question_view ==\", err);\n return\n }\n if (res.ok){\n myutil.debug(\"== user_question_view ==\");\n var body = res.text;\n //myutil.debug(res.body, res.text);\n //user_question_view_not_leave(body, vars);\n var r = JSON.parse(body);\n var data = r.data;\n var i = Math.floor(Math.random()*data.length);\n var msg = data[i];\n vars.msg = msg;\n if (vars.msg == undefined) {vars.msg = {}; vars.msg._id= '';}\n vars.current_status = \"user_question_view\";\n decision(vars);\n } else {\n myutil.error(\"== user_question_view ==\", err, res.status);\n }\n });\n}", "function findQuestions(parentElement,contents)\r{\r var pattern = /^\\s*(\\d+)\\./gm;\r var patternTwo = /^\\s*(\\d+)\\./gm;\r do {\r var matchArray = pattern.exec(contents);\r var lastMatchedIndex = -1;\r if (matchArray != null && matchArray.length > 0) {\r // $.writeln(\"question lastIndex: \",pattern.lastIndex);\r lastMatchedIndex = pattern.lastIndex;\r var questionContent = \"\";\r if (matchArray.length > 1) {\r // $.writeln(\"matchArray[1]: \" + matchArray[1]);\r var questionNumber = matchArray[1];\r // $.writeln(\"questionNumber: \" + questionNumber);\r patternTwo.lastIndex = pattern.lastIndex;\r var nextMatch = patternTwo.exec(contents);\r if (nextMatch != null && nextMatch.length > 0) {\r if (nextMatch.length > 1) {\r questionContent = contents.substring(lastMatchedIndex,nextMatch.index);\r } else {\r questionContent = contents.substring(lastMatchedIndex);\r }\r } else {\r questionContent = contents.substring(lastMatchedIndex);\r }\r } else {\r questionContent = contents.substring(lastMatchedIndex);\r }\r var questionElement = parentElement.xmlElements.add(tags.questionTag);\r var questionNumberTag = questionElement.xmlElements.add(tags.questionNumberTag);\r questionNumberTag.contents = questionNumber;\r questionNumberTag.insertTextAsContent(\".\", XMLElementPosition.afterElement);\r var questionContentTag = questionElement.xmlElements.add(tags.questionContentTag);\r questionContentTag.contents = questionContent;\r }\r } while (matchArray != null);\r\r var myDocument = app.activeDocument;\r var myPage = app.activeWindow.activePage;\r // Add Question nodes to the textFrame\r // create the textFrame to put the questions into\r var myTextFrame = myPage.textFrames.add({geometricBounds:myGetBounds(myDocument, myPage)});\r var myStory = myTextFrame.parentStory;\r $.writeln(\"placeXML into page: \" + myPage.name + \" parentElement: \" + parentElement.markupTag.name); \r myStory.placeXML(parentElement); // insert the xml\r}", "function presentQuestions(){\n\n\tif (questionsAsked == 0){\n\t\tdocument.getElementById(\"ask\").innerHTML = questions[0];\n\t\tdocument.getElementById(\"qnumber\").innerText = questionsAsked + 1\n\t\n\t} else if (questionsAsked < questions.length) {\n\t\tdocument.getElementById(\"ask\").innerHTML = questions[questionsAsked];\n\t\tdocument.getElementById(\"qnumber\").innerText = questionsAsked + 1\n\t}\n}", "function quizSetUp() {\n for (i = 0; i < questionArray.length; i++) {\n question.textContent = questionArray[i];\n answer1.textContent = A1[i];\n answer2.textContent = A2[i];\n answer3.textContent = A3[i];\n answer4.textContent = A4[i];\n return;\n}}", "function onBtnAskClick(e) {\n e.preventDefault();\n \n // find out which of the [Choice][Range][Free] checkboxes are checked\n var ckb = null;\n for (i = 0; i < ckbChoices.length; i++) {\n if (ckbChoices[i].checked) {\n ckb = ckbChoices[i];\n break;\n }\n }\n \n if (txtQ.value.length < 1 || ckb == null) {\n alert(\"Question definition is incomplete!\");\n return;\n }\n \n // construct the JSON object to be sent to the server\n var question = { \"QuestionType\" : ckb.name, \"QuestionText\" : txtQ.value };\n \n // prepare the web POST request\n var request = new XMLHttpRequest();\n request.open(\"POST\", `${urlHostAPI}?name=${username}&cmd=ask`, true);\n request.timeout = 2000;\n request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');\n request.onload = onStatusResponse;\n request.send(JSON.stringify(question));\n}", "function getQuestionsByTag(req, res) {\n\n console.log(\"Inside question controllers -> getQuestionsByTag()\");\n // console.log(\"req.params.tag: \" + req.params.tag);\n let tagName = req.params.tag;\n\n // db.getCollection('questions').find({'userTags':'REST'},{'_id':1})\n\n Question.find(\n { userTags: tagName },\n // { _id: 1 }\n )\n .then(dbQuestionData => {\n console.log(dbQuestionData);\n res.status(200).json(dbQuestionData)\n })\n .catch(err => {\n console.log(err);\n res.status(500).json(err);\n });\n\n}", "function getCurrentSurvey() {\n return $.get(config.server + \"/current-question\");\n}", "questionCreate(){\n const q = new Question( this.config.dimensions );\n this.questions.push( q );\n this.currentQuestion = q;\n this.gameState = 'question';\n this.view.showQuestion( q );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute the last step in a traversal that ends with an HTTP GET. This is similar to lib/transforms/fetch_resource.js refactoring potential?
function fetchLastResource(t, callback) { // always check for aborted before doing an HTTP request if (t.aborted) { return abortTraversal.callCallbackOnAbort(t); } httpRequests.fetchResource(t, function(err, t) { log.debug('fetchResource returned (fetchLastResource).'); if (err) { if (!err.aborted) { log.debug('error while executing http request'); log.error(err); } return t.callback(err); } callback(t); }); }
[ "step() {\n const instruction = this.fetch();\n return this.execute(instruction);\n }", "function visitNextPage() {\n\t var _url = _this.visitableList.pop();\n\t\tvar getPage = request(_url, function(error, response, body){\n\t\t\t_this.totalVisit += 1;\n\t\t\tif(_this.toVisit>0 && _this.totalVisit >= _this.toVisit) {\n\t\t\t\tcontinueVisit = false;\n\t\t\t}\n\t\t\tif(error) {\n\t\t\t\t//Skip to next page if avaiable\n\t\t\t\tif(_this.visitableList.length) {\n\t\t\t\t\tvisitNextPage();\n\t\t\t\t}\n\t\t\t\t_this.emit('error',error, _url);\n\t\t\t}else {\n\t\t\t\tparseLink(response, body, _url);\n\t\t\t\t_this.emit('crawl', {url:_url, totalIndexed:_this.totalIndexed});\n\t\t\t}\n\t\t});\n\t}", "requestNextStep() {\n this.requestNextStepCallback();\n }", "getOngoing({commit}, data) {\n commit('setElectionsLoadStatus', 1);\n\n ElectionAPI.getOngoing(\n data.url\n )\n .then( function(response) {\n commit('setElections', response.data.data);\n commit('setElectionsLoadStatus', 2);\n commit('setElPagination', {\n meta: response.data.meta,\n links: response.data.links\n });\n })\n .catch( function() {\n commit('setElections', []);\n commit('setElectionsLoadStatus', 3);\n });\n }", "_runRequestCycle () {\n const everyStep = (step, next) => {\n if (this.response.isResponded) {\n return next(new Error('Response was sent'))\n }\n\n if (this.response.error) {\n return next(this.response.error)\n }\n\n if (!step) {\n return next()\n }\n\n return step.call(this, this, next)\n }\n\n const finalStep = (error) => {\n if (this.response.isResponded) {\n return\n }\n\n if (error) {\n this.setResponse(error)\n }\n\n this._runResponseCycle()\n }\n\n const _onRequest = this._getMergedExtensions('onRequest')\n const _onPreMethod = this._getMergedExtensions('onPreMethod')\n const _onMethod = this._executeMethod\n const _onPostMethod = this._getMergedExtensions('onPostMethod')\n\n const cycle = new Cycle(everyStep, finalStep)\n\n cycle.add(_onRequest)\n cycle.add(_onPreMethod)\n cycle.add(_onMethod)\n cycle.add(_onPostMethod)\n\n cycle.start()\n }", "function query() {\n var pagesParams = CODES.node1.title + '|' + CODES.node2.title;\n var queryURL = makeQueryURL(150, 2, pagesParams);\n $.when(\n $.getJSON(\n queryURL,\n function(data) {\n var htmlSnippets = addQueryInfo(data);\n Object.keys(htmlSnippets).forEach(function(node) {\n pathDiv.append(htmlSnippets[node]);\n });\n $('#page0').after('<div class=\"page loading\"></div>');\n }),\n $.get(\n '/query',\n CODES,\n function(data) {\n response = JSON.parse(data);\n })\n ).then(function() {\n try {\n return getInnerImages();\n } catch(err) {}\n }).done(function() {\n pathDiv.empty();\n if (response.path != 'None') {\n updateIndexCodes();\n pathDiv.empty();\n drawGraph(response.results);\n buildSidebar();\n } else {\n $('.path-not-found').removeClass('hidden');\n }\n });\n}", "[FETCH_PATIENT_SIBLINGS]({ commit }) {\n let endpoint = `/api/v1/patient-sibling-b03/`;\n commit(FETCH_START);\n apiService(endpoint)\n .then(response => {\n commit(SET_PATIENT_SIBLINGS, response);\n commit(FETCH_END);\n })\n .catch(error => {\n console.log(error);\n });\n }", "function get_loads(req){\r\n var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\r\n //Limit to three boat results per page\r\n var q = datastore.createQuery(LOAD).limit(5);\r\n\r\n var results = {};\r\n\r\n if(Object.keys(req.query).includes(\"cursor\")){\r\n q = q.start(req.query.cursor);\r\n }\r\n\r\n return datastore.runQuery(q).then( (entities) => {\r\n results.loads = entities[0].map(ds.fromDatastore);\r\n for (var object in results.loads)\r\n {\r\n if(results.loads[object].carrier.length === 1)\r\n {\r\n var bid = results.loads[object].carrier[0];\r\n var boatUrl = req.protocol + '://' + req.get('host') + '/boats/' + bid;\r\n results.loads[object].carrier = [];\r\n results.loads[object].carrier = {\"id\": bid, \"self\": boatUrl};\r\n }\r\n \r\n // Make sure self link does not have cursor in it\r\n if(Object.keys(req.query).includes(\"cursor\"))\r\n {\r\n results.loads[object].self = req.protocol + '://' + req.get('host') + results.loads[object].id;\r\n }\r\n else\r\n {\r\n results.loads[object].self = fullUrl +'/' + results.loads[object].id;\r\n }\r\n }\r\n if(entities[1].moreResults !== ds.Datastore.NO_MORE_RESULTS){\r\n results.next = req.protocol + \"://\" + req.get(\"host\") + req.baseUrl + \"?cursor=\" + encodeURIComponent(entities[1].endCursor);\r\n }\r\n }).then(() =>{\r\n return count_loads().then((number) => {\r\n results.total_count = number;\r\n return results; \r\n });\r\n });\r\n}", "dispatch(req, res, done) {\n let idx = 0;\n const stack = this.stack;\n if (stack.length === 0) {\n return done();\n }\n\n let method = req.method.toLowerCase();\n if (method === 'head' && !this.methods['head']) {\n method = 'get';\n }\n\n req.route = this;\n\n next();\n\n function next(err) {\n // signal to exit route\n if (err && err === 'route') {\n return done();\n }\n\n // signal to exit router\n if (err && err === 'router') {\n return done(err)\n }\n\n const layer = stack[idx++];\n if (!layer) {\n return done(err);\n }\n\n if (layer.method && layer.method !== method) {\n return next(err);\n }\n\n if (err) {\n layer.handle_error(err, req, res, next);\n } else {\n layer.handle_request(req, res, next);\n }\n }\n }", "function getResource(map, base, internal, path, callback, addLineHints) {\n\t\tvar\n\t\t\treduced = reduce(map, path),\n\t\t\treducedMap = reduced.map,\n\t\t\treducedMapType = nodeType(reducedMap),\n\t\t\treducedPrefix = reduced.prefix,\n\t\t\treducedSuffix = reduced.suffix,\n\t\t\tfirstChar = path.charAt(0),\n\t\t\ttemporary = firstChar === '~',\n\t\t\tliteral = firstChar === '='\n\t\t;\n\n\t\tif (isURL(path)) {\n\t\t\twget(path, callback);\n\n\t\t} else if (literal) {\n\t\t\tcallback(null, new Buffer(path.substr(1) + '\\n'));\n\n\t\t} else if (temporary && !internal) {\n\t\t\t// External request for a temporary resource.\n\t\t\tcallback({ code: 403, message: 'Forbidden' });\n\n\t\t} else if (reducedSuffix) {\n\t\t\t// We did NOT find an exact match in the map.\n\n\t\t\tif (!reducedPrefix && internal) {\n\t\t\t\tgetFile(base, path, callback, addLineHints);\n\t\t\t} else if (reducedMapType === 'string') {\n\t\t\t\tgetFile(base, reducedMap + '/' + reducedSuffix, callback, addLineHints);\n\t\t\t} else {\n\t\t\t\tcallback({ code: 404, message: 'Not Found' });\n\t\t\t}\n\n\t\t} else {\n\t\t\t// We found an exact match in the map.\n\n\t\t\tif (reducedMap === reducedPrefix) {\n\t\t\t\t// This is just a local file/dir to expose.\n\t\t\t\tgetFile(base, reducedPrefix, callback, addLineHints);\n\n\t\t\t} else if (reducedMapType === 'string') {\n\t\t\t\t// A string value may be a web URL.\n\t\t\t\tif (isURL(reducedMap)) {\n\t\t\t\t\twget(reducedMap, callback);\n\t\t\t\t} else {\n\t\t\t\t\t// Otherwise, it's another resource path.\n\t\t\t\t\tgetResource(map, base, true, reducedMap, callback, addLineHints);\n\t\t\t\t}\n\n\t\t\t} else if (reducedMapType === 'array') {\n\t\t\t\t// An array is a list of resources to get packed together.\n\t\t\t\tpackResources(map, base, reducedMap, callback);\n\n\t\t\t//} else if (reducedMapType === 'object') {\n\t\t\t\t// An object is a directory. We could return a listing...\n\t\t\t\t// TODO: Do we really want to support listings?\n\n\t\t\t} else {\n\t\t\t\tcallback({ code: 500, message: 'Unable to read gravity.map.' });\n\t\t\t}\n\t\t}\n\t}", "function recurse() {\n if(linkNextPage != null) {\n $.when( listRepoIssues(linkNextPage) )\n .then( function() { recurse(); } )\n .fail( function() { logErr('Failed getting next page...'); } )\n }\n}", "function recursiveGetFactory ({path: resPath, domain, setupTree, token, headers, funcMode}) {\n function recursiveGet({state, resolve, path, oada}) {\n return Promise.resolve().then(() => {\n //Remove the path if we are running in function mode, so paths in original action work\n let _path = (funcMode) ? null : path;\n //Resolve path, domain, and token values if they are tags\n\t\t\tlet _resPath = resolve.value(resPath);\n\t\t\tlet _setupTree = resolve.value(setupTree);\n\t\t\tlet _headers = resolve.value(headers);\n let _domain = resolve.value(domain) || state.get('Connections.oada_domain');\n let _token = resolve.value(token) || state.get('Connections.oada_token')\n /*\n - Execute get -\n Use axios if our websocket isn't configured, or isn't configured for the\n correct domain\n\t\t\t*/\n return _oada.recursiveGet(_domain, _token, _resPath, _setupTree, _headers, oada)\n\t\t\t.then((response) => {\n if (_path) return _path.success(response);\n return response;\n }).catch((error) => {\n if (_path) return _path.error({error});\n throw error;\n });\n });\n }\n return recursiveGet\n}", "function fetchCurrentRevision (post, next) {\n RevisionModel.findById (post.currentRevision, function (error, revision) {\n if (!error) {\n next (revision);\n }\n else {\n console.log ('Erorr occured while retrieving current revision: ' + error);\n next (null);\n }\n });\n}", "get nextPath() { return this.next && this.next.path }", "function quickFetch(url, func, param){\n fetch(url)\n .then(function(response){\n if (response.status !== 200){\n console.log('There was an error with your fetch. Response was not 200.')\n }\n return response.json()\n })\n .then(function(data){\n param = data;\n func(param)\n })\n}", "finalizeSlicedFindPath() {\n\n\t\tlet path = [];\n\t\tif (this.m_query.status == Status.FAILURE) {\n\t\t\t// Reset query.\n\t\t\tthis.m_query = new QueryData();\n\t\t\treturn new FindPathResult(Status.FAILURE, path);\n\t\t}\n\n\t\tif (this.m_query.startRef == this.m_query.endRef) {\n\t\t\t// Special case: the search starts and ends at same poly.\n\t\t\tpath.push(this.m_query.startRef);\n\t\t} else {\n\t\t\t// Reverse the path.\n\t\t\tif (this.m_query.lastBestNode.id != this.m_query.endRef)\n\t\t\t\tthis.m_query.status = Status.PARTIAL_RESULT;\n\n\t\t\tlet prev = null;\n\t\t\tlet node = this.m_query.lastBestNode;\n\t\t\tlet prevRay = 0;\n\t\t\tdo {\n\t\t\t\tlet next = this.m_nodePool.getNodeAtIdx(node.pidx);\n\t\t\t\tnode.pidx = this.m_nodePool.getNodeIdx(prev);\n\t\t\t\tprev = node;\n\t\t\t\tlet nextRay = node.flags & Node.DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut)\n\t\t\t\tnode.flags = this.or(this.and(node.flags, ~Node.DT_NODE_PARENT_DETACHED), prevRay); // and store it in the reversed path's node\n\t\t\t\tprevRay = nextRay;\n\t\t\t\tnode = next;\n\t\t\t} while (node != null);\n\n\t\t\t// Store path\n\t\t\tnode = prev;\n\t\t\tdo {\n\t\t\t\tlet next = this.m_nodePool.getNodeAtIdx(node.pidx);\n\t\t\t\tif ((node.flags & Node.DT_NODE_PARENT_DETACHED) != 0) {\n\t\t\t\t\tlet iresult = raycast(node.id, node.pos, next.pos, this.m_query.filter, 0, 0);\n\t\t\t\t\tpath.addAll(iresult.path);\n\t\t\t\t\t// raycast ends on let boundary and the path might include the next let boundary.\n\t\t\t\t\tif (path[path.length - 1] == next.id)\n\t\t\t\t\t\tpath.remove(path.length - 1); // remove to aduplicates\n\t\t\t\t} else {\n\t\t\t\t\tpath.push(node.id);\n\t\t\t\t}\n\n\t\t\t\tnode = next;\n\t\t\t} while (node != null);\n\t\t}\n\n\t\tlet status = this.m_query.status;\n\t\t// Reset query.\n\t\tthis.m_query = new QueryData();\n\n\t\treturn new FindPathResult(status, path);\n\t}", "function getWalk(url, cb) {\n let xhr = new XMLHttpRequest();\n xhr.open('GET', url.replace(/(\\/+|)$/, '/json'));\n xhr.onload = function() {\n let data;\n try {\n data = JSON.parse(this.responseText);\n cb(null, migrateToV1(data));\n } catch (e) {\n cb('Error parsing JSON returned on walk' + url);\n }\n };\n xhr.onerror = function() {\n cb('Failed to load walk ' + url);\n };\n xhr.send();\n}", "async getNext() {\n if (this.hasNext) {\n const items = Items([this.parent, this.nextUrl], \"\");\n return items.getPaged();\n }\n return null;\n }", "visitFetch_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function startResourceGet(id) {\n return { type: START_RESOURCE_GET,\n id: id};\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether we should try to autoFill.
get _shouldAutofill() { // First of all, check for the autoFill pref. if (!Prefs.autofill) return false; if (!this._searchTokens.length == 1) return false; // autoFill can only cope with history or bookmarks entries. if (!this.hasBehavior("history") && !this.hasBehavior("bookmark")) return false; // autoFill doesn't search titles or tags. if (this.hasBehavior("title") || this.hasBehavior("tag")) return false; // Don't try to autofill if the search term includes any whitespace. // This may confuse completeDefaultIndex cause the AUTOCOMPLETE_MATCH // tokenizer ends up trimming the search string and returning a value // that doesn't match it, or is even shorter. if (/\s/.test(this._originalSearchString)) return false; if (this._searchString.length == 0) return false; return true; }
[ "checkUnrecognizedAutoFill() {\n if (this.state.username !== \"\" || this.state.password !== \"\") {\n return false;\n }\n let username = this.props.testBlankUsername\n ? this.props.testBlankUsername\n : this.usernameField.value;\n let password = this.props.testBlankPassword\n ? this.props.testBlankPassword\n : this.passwordField.value;\n this.setState({ username: username, password: password }); // doesn't set immediately, hence separate login() call\n this.login(username, password);\n\n return true;\n }", "_checkIfDirty(){\n if (this._isDirty === true){\n this._isDirty = false;\n this._refresh();\n }\n }", "function testCheckForeignKeysForUpdate_Deferrable() {\n checkForeignKeysForUpdate(\n lf.ConstraintTiming.DEFERRABLE,\n 'testCheckForeignKeysForUpdate_Deferrable');\n}", "function supportsAutocomplete_(tableType) {\n return ('mgmt' != tableType)\n }", "check(abstract) {\n let resolved_abstract = this.resolveAbstract(abstract);\n if (this.bindings[resolved_abstract] === undefined) {\n return false;\n } else {\n return true;\n }\n }", "function validarCampo() {\n if (\n id_a.value == \"\" ||\n owner_a.value == \"\" ||\n capacity_a.value == \"\" ||\n cat_a.value == \"\" ||\n nombre_a.value == \"\"\n ) {\n return true;\n } else {\n return false;\n }\n}", "isFirstColumn(): boolean {\n return this.getColumnIndex() === 0;\n }", "checkValidity() {\n this.select.checkValidity();\n }", "get autoRecoverySupported() {\n return this.getBooleanAttribute('auto_recovery_supported');\n }", "function enableAutoFocus(parent) {\n if (parent.find(inputs).filter(filterNotEmpty).length === 0) {\n parent.data('auto-focus-enabled', true);\n }\n }", "hasMissingMapping() {\n let isMissing = false;\n\n try {\n this._getAPIDiseases();\n } catch (err) {\n isMissing = true;\n }\n\n try {\n this._getAPIInterventions();\n } catch (err) {\n isMissing = true;\n }\n\n //Phase\n try {\n this._getAPIPhases();\n } catch (err) {\n isMissing = true;\n }\n\n //trialtype\n try {\n this._getAPITrialTypes();\n } catch (err) {\n isMissing = true;\n }\n\n return isMissing;\n }", "checkValidityProblems() {\n\t\t//Check whether there are any unnamed items or items without prices\n\t\tlet problems = false;\n\t\tif(this.state.albumName === \"\") {\n\t\t\tproblems = true;\n\t\t}\n\t\tfor (let item of this.state.items) {\n\t\t\tif(item.itemName === \"\" || (this.state.isISO && item.description === \"\") || (!this.state.isISO && (item.price === \"\" || item.pic === null)) ) {\n\t\t\t\tproblems = true;\n\t\t\t}\n\t\t}\n\t\tif (problems) {\n\t\t\tlet items = this.state.items;\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\titems[i].highlighted = true;\n\t\t\t}\n\t\t\tthis.setState({\n\t\t\t\tshowMissingFieldsPopup: true,\n\t\t\t\thighlighted: true,\n\t\t\t\titems: items\n\t\t\t})\n\t\t}\n\t\treturn(problems);\n\t}", "isComplete() {\n return this.selection != null;\n }", "isFirstRow(): boolean {\n return this.getRowIndex() === 0;\n }", "function setAutocomplete()\n{\n if (navigator.userAgent.toLowerCase().indexOf('chrome') >= 0)\n {\n setTimeout(function () {\n document.getElementById('emailAddress').setAttribute('autocomplete', 'off');\n }, 100);\n }\n}", "fillsuppliersFields() {\n // fill the fields\n this.$suppliersName.value = this.state.suppliers.name;\n this.$suppliersPhone.value = this.state.suppliers.phone;\n this.$suppliersEmail.value = this.state.suppliers.email;\n this.$suppliersWebsite.value = this.state.suppliers.website;\n this.$suppliersContactFirstName.value = this.state.suppliers.contactFirstName;\n this.$suppliersContactLastName.value = this.state.suppliers.contactLastName;\n this.$suppliersContactPhone.value = this.state.suppliers.contactPhone;\n this.$suppliersContactEmail.value = this.state.suppliers.contactEmail;\n this.$suppliersNote.value = this.state.suppliers.note;\n this.makeFieldsReadOnly();\n }", "function Master_DataCheck(){ \n\t\tif(LINE_PART.bindcolval == \"\" ) {\n\t\t\talert(\"Project 누락\"); \n\t\t\treturn false;\n\t\t} \n\n\t\tif(LINE_PART.index != 3) {\n\t\t\tif( PROJECT.index == 0 ) {\n\t\t\t\talert(\"물류비 부담 누락\"); \n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tif(strim(ETD_DT.Text) == \"\" ) {\n\t\t\talert(\"반출일자 누락\"); \n\t\t\treturn false;\n\t\t}\n\n\t\tif(strim(txt_obj_remk.value) == \"\" ) {\n\t\t\talert(\"투입목적/공정 누락\"); \n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t/**\n\t\tif (DLVL_TYPE.bindcolval!=\"0001\")\t{\n\t\t\tif(strim(FAC_PERSON.value) == \"\" || strim(FAC_PRSTEL.value) == \"\") {\n\t\t\t\talert(\"공장담당자정보 누락\"); \n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t**/\n\n\t\tif(strim(CUST_CD.Text) == \"\" ) {\n\t\t\talert(\"신청업체 누락\"); \n\t\t\treturn false;\n\t\t} \n\n\t\tif(strim(CUST_PRSN.value) == \"\" ) {\n\t\t\talert(\"신청업체 담당자 누락\"); \n\t\t\treturn false;\n\t\t}\n\n\t\tif(strim(CUST_TELNO.value) == \"\" ) {\n\t\t\talert(\"신청업체 전화번호 누락\"); \n\t\t\treturn false;\n\t\t} \n\n\t\tif(strim(SHIPPER.Text) == \"\" ) {\n\t\t\talert(\"실화주 누락\"); \n\t\t\treturn false;\n\t\t}\n\n\t\tif(strim(SHIPPERPS.value) == \"\" ) {\n\t\t\talert(\"실화주 담당자 누락\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif(strim(SHIPPERTEL.value) == \"\" ) {\n\t\t\talert(\"실화주 전화번호 누락\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif(CARGO_TYPE.bincolval == \"\" ) {\n\t\t\talert(\"적재구분 누락\"); \n\t\t\treturn false;\n\t\t}\n\n\t\tfor (var i=1; i<=gcDs4.countrow; i++) {\n\t\t\tif (strim(gcDs4.namevalue(i,\"CARTYPENO\"))==\"\")\t{\n\t\t\t\talert(\"차량정보 (차량) 누락\");\n\t\t\t\treturn false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (strim(gcDs4.namevalue(i,\"CTN_STDRD\"))==\"\")\t{\n\t\t\t\talert(\"차량정보 (대표품목) 누락\");\n\t\t\t\treturn false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (strim(gcDs4.namevalue(i,\"LD_CARGO\"))==\"\")\t{\n\t\t\t\talert(\"차량정보 (상차지) 누락\");\n\t\t\t\treturn false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (strim(gcDs4.namevalue(i,\"OFF_CARGO\"))==\"\")\t{\n\t\t\t\talert(\"차량정보 (하차지) 누락\");\n\t\t\t\treturn false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true ; //누락 된 건이 한개도 없을때\n\t}", "any() {\n return Object.keys(this.datos).length > 0;\n }", "isFirstCell(): boolean {\n return this.isFirstRow() && this.isFirstColumn();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check to see if either player is blocking
function checkForBlocking(p1Action, p2Action) { // Since the player with the most stamina will set the current actionCount we // need to see which ones has less or if they're equal. If one has less stamina then // we'll set up which block they chose. (i.e. punch-blocking, low-lick-blocking, high-kick-blocking) if(player1.liveStamina < actionCount) { setBlocks("player1", p1Action, p2Action); } else if(player2.liveStamina < actionCount) { setBlocks("player2", p1Action, p2Action); } else { calculateAttack(p1Action, p2Action); } }
[ "is_blocker() {\n return true;\n }", "is_blocker() {\n return false;\n }", "playerWins(){ // i2 - put inline\n\t\tif (this.player === activePlayer && playing === false) {\n\t\t\treturn true;\n\t\t}\t}", "canSeePlayer(){\n\t\t//enemy should act like it doesn't know where the player is if they're dead\n\t\tif(lostgame)\n\t\t\treturn false;\n\t\t\n\t\t// casts a ray to see if the line of sight has anything in the way\n\t\tvar rc = ray.fromPoints(this.pos, p1.pos);\n\t\t\n\t\t// creates a bounding box for the ray so that the ray only tests intersection\n\t\t// for the blocks in that bounding box\n\t\tvar rcbb = box.fromPoints(this.pos, p1.pos);\n\t\tvar poscols = []; // the blocks in the bounding box\n\t\tfor(var i = 0; i < blocks.length; i++){\n\t\t\tif(box.testOverlap(blocks[i].col, rcbb))\n\t\t\t\tposcols.push(blocks[i]);\n\t\t}\n\t\t\n\t\t// tests ray intersection for all the blocks in th ebounding box\n\t\tfor(var i = 0; i < poscols.length; i++){\n\t\t\tif(poscols[i].col.testIntersect(rc))\n\t\t\t\treturn false; // there is a ray intersection, the enemy's view is obstructed\n\t\t}\n\t\treturn true;\n\t}", "function setBlocks(player, p1Action, p2Action) {\n\t// If a player is blocking set which move they used to block. (i.e. If they chose\n\t// punch and have less stamina then we'll set it to punch-blocking). This will \n\t// tell us which animations to play when calculating the attack.\n\tif(player == \"player1\") {\n\t\tp1Action += \"-blocking\";\n\t\tconsole.log(\"Player 1 action is \" + p1Action);\n\t}\n\telse {\n\t\tp2Action += \"-blocking\";\n\t\tconsole.log(\"Player 2 action is \" + p2Action);\n\t}\n\tcalculateAttack(p1Action, p2Action);\n}", "function is_playing() {\n return player.getPlayerState() == 1;\n}", "async canPlayerJoin(client, playerId)\n {\n const inGame = this.players.some(x => x.id === playerId);\n return inGame || this.game.allowJoin;\n }", "function isInGame(player)\n\t{\n\t\treturn ((player == boardgameserver.p1) || (player == boardgameserver.p2));\n\t}", "function checkWinner() {\n if (player1Score === 20) {\n setMessage(\"player 1 wins\");\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n playAgain();\n } else if (player2Score === 20) {\n setMessage(\"player 2 wins\");\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n playAgain();\n }\n }", "function isInDistance (player, block) {\n const firstCondition = (Math.abs(block.dataset['x'] - player.position.x) <= 3)\n && (block.dataset['y'] === player.position.y);\n const secondCondition = (Math.abs(block.dataset['y'] - player.position.y) <= 3) \n && (block.dataset['x'] === player.position.x);\n return (firstCondition || secondCondition);\n }", "function winnerIs(player) {\n\tconsole.log(player == \"player1\" ? \"Player 1 wins\" : \"Player 2 wins\");\n\tshowMessege(player == \"player1\" ? \"#\" + player1.short + \"-hits\" : \"#\" + player2.short + \"-hits\");\n\tif(player == \"player1\") {\n\t\tsetStamina(player1, \"player-1-stamina\", \"add\");\n\t\tsetStamina(player2, \"player-2-stamina\", \"subtract\");\n\t} else {\n\t\tsetStamina(player1, \"player-1-stamina\", \"subtract\");\n\t\tsetStamina(player2, \"player-2-stamina\", \"add\");\t\t\n\t}\n\tplayer == \"player1\" ? decreaseHealth(player2, \"player2\") : decreaseHealth(player1, \"player1\");\n\t$(\"#player-1-health\").html(player1.health);\n\t$(\"#player-2-health\").html(player2.health);\n\tif(player == \"player1\" && player2.health == 0) {\n\t\tplayer2.dead = true;\n\t} else if(player1.health == 0) {\n\t\tplayer1.dead = true;\n\t}\n}", "function waitForPlayer(successFunction) {\n firebaseGame.child('player').on('value', function(snapshot) {\n var players = snapshot.val();\n if(players && players['1'] && players['2']) {\n firebaseGame.child('player').off('value');\n successFunction();\n }\n });\n }", "static needPlayers() {\n\t\talert('There\\'s not enough players in the room');\n\t}", "function isGameOver(){\n if (player1.health <= 0){\n player1.health = 0;\n $( \".fightButton1\" ).css( \"display\", \"none\" );\n $( \".fightButton2\" ).css( \"display\", \"none\" );\n displayStats(player1);\n // timeout used so the health can be seen before the modal box\n setTimeout(\n function(){ \n background.pause();\n horn.play();\n celebrate.play();\n document.getElementById(\"match-winner\").innerHTML = \"Loki, the god of mischief\";\n document.getElementById(\"winner-img\").src =\"images/loki.png\";\n document.getElementById(\"winner-gif\").src = \"images/fireworks.gif\"\n endModal.style.display = \"block\" ;\n }, \n 800);\n }\n if (player2.health <= 0){\n player2.health = 0;\n $( \".fightButton1\" ).css( \"display\", \"none\" );\n $( \".fightButton2\" ).css( \"display\", \"none\" );\n displayStats(player2);\n setTimeout(\n function(){ \n background.pause();\n horn.play();\n celebrate.play();\n document.getElementById(\"match-winner\").innerHTML = \"Thor, son of Odin\";\n document.getElementById(\"winner-img\").src = \"images/Thor.png\";\n document.getElementById(\"winner-gif\").src = \"images/giphyThunder.gif\";\n endModal.style.display = \"block\";\n }, \n 800);\n }\n }", "function checkTuneGeniePlayerState(e) {\n\t\t\tif (e === true) {\n\t\t\t\tlog('TuneGenie Player is streaming.');\n\t\t\t\tme.start();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tlog('TuneGenie Player has stopped.');\n\t\t\tme.stop();\n\t\t\treturn false;\n\t\t}", "function checkForMatch() {\n let isMatch = firstCard.dataset.name === secondCard.dataset.name;\n let soundFlag = true;\n\n if (firstCard.dataset.name === secondCard.dataset.name) {\n sound.pause();\n sound.currentTime = 0;\n sound.play();\n soundFlag = false;\n }\n\n isMatch ? disableCards() : unflipCards();\n}", "isLocalOnHold() {\n if (this.state !== CallState.Connected) return false;\n if (this.unholdingRemote) return false;\n let callOnHold = true; // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n\n for (const tranceiver of this.peerConn.getTransceivers()) {\n const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }", "function isUserStillWaiting(request) {\n\treturn false; //Allow user to return the pool for selection.\n}", "function commence(p1, p2) {\n\t// Check if both players are ready to fight, if\n\t// they aren't, then we return. If they are, then\n\t// we'll begin fighting\n\tif(p1 == false || p2 == false) {\n\t\treturn;\n\t}\n\telse {\n\t\t// Here we'll want to wait a few seconds before we begin. We \n\t\t// don't want the action to happen instantly after the last \n\t\t// player chooses their last action. The strikePause variable \n\t\t// sets the delay\n\t\tsetTimeout(function()\n\t\t{\n\t\t\tconsole.log(\"Starting Round 1\");\n\t\t\t// Grab the first action from both players and calculate\n\t\t\t// who wins\n\t\t\tvar p1Action = player1.actions[0].toString();\n\t\t\tvar p2Action = player2.actions[0].toString();\n\t\t\tcalculateAttack(p1Action, p2Action);\n\t\t\t\n\t\t\t// Check to see if there are two actions that\n\t\t\t// will happen. If so, then we'll proceed to\n\t\t\t// the next moves. We'll also check if a player\n\t\t\t// has been defeated. If they are, then we'll \n\t\t\t// skip to the finishing animations\n\t\t\tif(player1.dead == false && player2.dead == false)\n\t\t\t{\n\t\t\t\tif(actionCount >= 2)\n\t\t\t\t{\n\t\t\t\t\t// Use strikePause to set a slight attack delay\n\t\t\t\t\tsetTimeout(function()\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Starting Round 2\");\n\t\t\t\t\t\tvar p1Action = player1.actions[1].toString();\n\t\t\t\t\t\tvar p2Action = player2.actions[1].toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Check to see if either player is currently blocking. Since stamina\n\t\t\t\t\t\t// can be no less than 1 we can only be blocking in rounds 2 and 3\n\t\t\t\t\t\tcheckForBlocking(p1Action, p2Action);\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Check to see if there is a third action that\n\t\t\t\t\t\t// will happen. If so, then we'll continue fighting\n\t\t\t\t\t\t// We'll also check if a player has been defeated. \n\t\t\t\t\t\t// If they are, then we'll skip to the finishing animations\n\t\t\t\t\t\tif(player1.dead == false && player2.dead == false)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(actionCount == 3)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsetTimeout(function()\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconsole.log(\"Starting Round 3\");\n\t\t\t\t\t\t\t\t\tvar p1Action = player1.actions[2].toString();\n\t\t\t\t\t\t\t\t\tvar p2Action = player2.actions[2].toString();\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcheckForBlocking(p1Action, p2Action);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif(player1.dead == false && player2.dead == false)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"Resetting after round 3 for next fight\");\n\t\t\t\t\t\t\t\t\t\t// If neither player died then reset for the next round\n\t\t\t\t\t\t\t\t\t\tresetForNextRound();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t// Check to see who died and play their finishing animation\n\t\t\t\t\t\t\t\t\t\tplayer1.dead == true ? endGame(\"player1\") : endGame(\"player2\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}, strikePause);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t// If we're done fighting then we'll reset\n\t\t\t\t\t\t\t\t// our stats for the next round\n\t\t\t\t\t\t\t\tconsole.log(\"Resetting after round 2 for next fight\");\n\t\t\t\t\t\t\t\tresetForNextRound();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Check to see who died and play their finishing animation\n\t\t\t\t\t\t\tplayer1.dead == true ? endGame(\"player1\") : endGame(\"player2\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}, strikePause);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// If we're done fighting then we'll reset\n\t\t\t\t\t// our stats for the next round\n\t\t\t\t\tconsole.log(\"Resetting after round 1 for next fight\");\n\t\t\t\t\tresetForNextRound();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Check to see who died and play their finishing animation\n\t\t\t\tplayer1.dead == true ? endGame(\"player1\") : endGame(\"player2\");\n\t\t\t}\n\t\t}, strikePause);\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert alert object (for watchdog) to string
function formatWatchdog(alert) { return getTimestampString((new Date()).toISOString()) + ' ' + '[' + getTimestampString(alert.startsAt) + '] ' + '(' + alert.status + ') ' + alert.alertname; }
[ "function createAlert_return(alert, textAlert) {\n var result = \"<div class=\\\"col-md-12\\\"><div class=\\\"alert alert-\" + alert + \"\\\">\"\n + \"<button aria-hidden=\\\"true\\\" data-dismiss=\\\"alert\\\" class=\\\"close\\\" type=\\\"buttonn\\\">&times;</button><p>\" + textAlert + \"</p></div></div>\";\n return result;\n}", "function populateAlert(obj){\n if (obj instanceof Error){\n alert.innerHTML += obj;\n }\n}", "alert( alertId, text ) {\n let alertText = null;\n\n if ( Array.isArray( text ) ) {\n alertText = \"\";\n for ( let part of text ) {\n alertText += part;\n }\n }\n else {\n alertText = text;\n }\n\n this.eventBus.message(\n {\n headers: {\n routing: {\n incoming: \"none\",\n outgoing: \"client\"\n }\n },\n message: {\n aps: {\n type: \"aps-alert\"\n },\n content: {\n targetId: alertId,\n markdown: alertText\n }\n }\n }\n );\n }", "function buildAlertObject(alertmessage) {\n var alert = {};\n\n alert.status = alertmessage.status;\n alert.startsAt = alertmessage.startsAt;\n alert.fingerprint = alertmessage.fingerprint;\n alert.alertname = alertmessage.labels.alertname;\n alert.severity = alertmessage.labels.severity;\n alert.message = alertmessage.annotations.message;\n\n return alert;\n}", "static alert(cause)\n {\n connection.send(JSON.stringify({\n type: 'emergency',\n message: cause\n }));\n }", "function bboalertLog(txt) {\n\tvar p1 = document.getElementById('bboalert-p1');\n\tif (p1 == null) return;\n\tp1.innerHTML = '';\n\tp1.innerHTML = txt;\n}", "function getMsgAlertContextMenuObject() {\n return ({\n '': {\n title: 'reload this application',\n icon: './images/icon/refresh_16x16.png',\n onclick: function() {\n location.reload();\n }\n }\n });\n }", "function getAlertFile(id) {\n return alertDir + '/' + id + '.json';\n}", "function popupText(data) {\n\t\tvar text = '<p class=\"alertHeader\">'+data.header+'</p>' +\n\t\t\t\t\t'<p class=\"alertBody1\">'+data.body1+'</p>' +\n\t\t\t\t\t'<p class=\"alertBody2\">'+data.body2+'</p>';\n\t\treturn text;\n\t}", "getAlerts() {\n return [\n {\n key: 'applicationUpdated',\n icon: 'cloud download',\n message: (\n <div className={styles['single-line-message']}>\n New application version available\n ({this.renderVersionChange()})\n {this.renderClickToUpgradeLink()}\n </div>\n ),\n isVisible: this.isApplicationUpdatedAlertVisible,\n onDismiss: this.createGenericOnDismiss('applicationUpdated'),\n heightPx: 48,\n severity: 'info',\n },\n ];\n }", "function messageWithIcon(alertObject,customMessage){\n\t\tvar message = \"<img alt='\"+alertObject.type+\": ' src='\"+icons_url+alertObject.type+\".png' />\";\n\t\tif(customMessage !== undefined)\n\t\t\tmessage += customMessage; //use custom message\n\t\telse\n\t\t\tmessage += alertObject.message; //use default alert message\n\t\treturn message;\n\t}", "function getMessage(){\n const myTimestamp = getTimestamp();\n const msg = {};\n msg['level'] = getRandomLogLevel();\n msg['time'] = new Date().getMilliseconds();\n msg['content'] = `Now is ${myTimestamp}`;\n return JSON.stringify(msg);\n}", "function generateAlertHTML(alert, type) {\n //Construct alert content\n var content;\n if (type === \"sub alert\") content = `<strong>${alert.Name}</strong> ${Resources.IsNowTrending}`\n else if (type === \"user alert\") content = `<strong>${alert.Name}</strong> ${Resources.IsNowAvailable}`\n\n //Construct alert message\n var read = \"\";\n if (alert.IsRead) {\n read = \"alertRead\";\n }\n\n var alertItem = $(\"<li />\",\n {\n \"class\": `alertMessage${alert.AlertId} ${read}`,\n onclick: `markAsRead(${alert.AlertId})`\n });\n\n var alertCloseButton = $(\"<div />\",\n {\n \"class\": \"alertClose\",\n title: Resources.RemoveAlert\n }).append($(\"<a />\",\n {\n \"class\": \"fa fa-close\",\n onclick: `removeAlert(${alert.AlertId})`\n\n }));\n let alertBody = \"\";\n if (type === \"user alert\") {\n alertBody = $(\"<a />\",\n {\n href: `/User/UserWeeklyReview`\n });\n\n } else {\n alertBody = $(\"<a />\",\n {\n href: `/Person/Details/${alert.ItemId}`\n });\n }\n var alertIcon = $(\"<div />\",\n {\n \"class\": \"alertIcon\"\n }).append($(\"<i />\",\n {\n \"class\": \"fa fa-user\"\n }));\n var alertContent = $(\"<span />\",\n {\n \"class\": \"font_16\",\n html: content\n });\n var alertTime = $(\"<span />\",\n {\n \"class\": \"alertTime\",\n html: `<i class=\"font_11 fa fa-clock-o\"></i> ${jQuery.timeago(alert.TimeStamp)}`\n });\n alertBody.append(alertIcon).append(alertContent).append(alertTime);\n alertItem.append(alertCloseButton).append(alertBody);\n return alertItem;\n}", "function noAlert(s) {\n\tif (s == null) { return s; }\n\treturn s.replace(/alert[(][^)]*[)]/g, '');\n}", "function jsdump(str)\r\n{\r\n Components.classes['@mozilla.org/consoleservice;1']\r\n .getService(Components.interfaces.nsIConsoleService)\r\n .logStringMessage(str);\r\n}", "function cfnAlertPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlertPropsValidator(properties).assertSuccess();\n return {\n Action: cfnAlertActionPropertyToCloudFormation(properties.action),\n AlertSensitivityThreshold: cdk.numberToCloudFormation(properties.alertSensitivityThreshold),\n AnomalyDetectorArn: cdk.stringToCloudFormation(properties.anomalyDetectorArn),\n AlertDescription: cdk.stringToCloudFormation(properties.alertDescription),\n AlertName: cdk.stringToCloudFormation(properties.alertName),\n };\n}", "dir(object) {\n return this._send(util.inspect(object) + '\\n', SysLogger.Severity.notice);\n }", "function object_to_string(obj)\r\n{\r\n var res = \"\";\r\n for (var key in obj)\r\n {\r\n res += key + \"\\t\" + obj[key] + \"\\n\";\r\n }\r\n return res;\r\n}", "function cfnAlertActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlert_ActionPropertyValidator(properties).assertSuccess();\n return {\n LambdaConfiguration: cfnAlertLambdaConfigurationPropertyToCloudFormation(properties.lambdaConfiguration),\n SNSConfiguration: cfnAlertSNSConfigurationPropertyToCloudFormation(properties.snsConfiguration),\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
presents the question based on which questions has been asked also writes the number of the question (Question 1, Question 2, etc.)
function presentQuestions(){ if (questionsAsked == 0){ document.getElementById("ask").innerHTML = questions[0]; document.getElementById("qnumber").innerText = questionsAsked + 1 } else if (questionsAsked < questions.length) { document.getElementById("ask").innerHTML = questions[questionsAsked]; document.getElementById("qnumber").innerText = questionsAsked + 1 } }
[ "function nextQuestion(){\n deleteButton(buttonDiv);\n deleteButton(questionTitle);\n if (q !== questions.length - 1){\n q++;\n showNextQA();\n } else {\n finalScore();\n deleteButton(buttonDiv);\n deleteButton(questionTitle);\n }\n}", "function renderQuestion() {\n $(\"#quiz\").html(`\n <p>${myQuestions[questCounter].question}</p>\n <p><button class=\"answers\">${myQuestions[questCounter].answers.a}</button></p>\n <p><button class=\"answers\">${myQuestions[questCounter].answers.b}</button></p>\n <p><button class=\"answers\">${myQuestions[questCounter].answers.c}</button></p>\n `)\n }", "function displayQuestionNumber () {\n $('.question-key').html('Question Number: ' + (questionNumber + 1) + '/10')\n}", "function showQuestions() {\n for (var i = 0; i < questionsArray.length; i++) {\n var questionHTML = getQuestionHTML(questionsArray[i], i + 1)\n $(\"#questions\").append(questionHTML);\n }\n }", "function setNextQuestion() {}", "function showQuestion3() {\n questionBox.innerHTML = questions[2].question;\n answerBoxA.innerHTML = questions[2].answers[0].answer;\n answerBoxB.innerHTML = questions[2].answers[1].answer;\n answerBoxC.innerHTML = questions[2].answers[2].answer;\n}", "function setNextQuestion() {\n if (availableQuestions.length === 0 || questionCounter > MAX_QUESTIONS) {\n localStorage.setItem('mostRecentScore', score);\n game.classList.add('hide');\n final.classList.remove('hide');\n setFinalScore();\n }\n questionCounter++;\n headerText.innerText = `\n Question ${questionCounter} of ${MAX_QUESTIONS}\n `;\n const questionsIndex = Math.floor(Math.random() * availableQuestions.length);\n currentQuestion = availableQuestions[questionsIndex];\n question.innerText = currentQuestion.question;\n options.forEach(function (option) {\n const number = option.dataset.number;\n option.innerText = currentQuestion['option' + number];\n });\n\n availableQuestions.splice(questionsIndex, 1);\n acceptingAnswers = true;\n}", "function questionIndexIncrease() {\n questionIndex++;\n}", "function loadQuestion (questionIndex) {\n var q = questions[questionIndex];\n questionEl.textContent = (questionIndex + 1) + '.' + q.question;\n opt1.textContent = q.option1;\n opt2.textContent = q.option2;\n opt3.textContent = q.option3;\n opt4.textContent = q.option4;\n\n}", "function nextQuestion() {\n // clear out divs (image and win/loss/outoftime)\n console.log(questionIndex + \"entering\");\n\n questionIndex++;\n clearDivs();\n console.log(questionIndex + \"after\");\n asking();\n }", "function questionOpen(idx) {\n // idx will always begin at Zero (0), so we bump it up once.\n return '<p><a href=\"#\" class=\"answer-choice\" data-val=\"' + idx + '\">' + (idx + 1) + \". \";\n}", "function resultTrivia(){\n\n //if counter is 8 check hide all the divs and show the results div\n if(counter == 8){\n $(\"#timeUpQues\" + counter).hide();\n $(\"#ansQues\" + counter).hide();\n $(\"#incorQues\" + counter).hide();\n $(\"#results\").show();\n $(\"#correctA\").text(\"Correct Answers:\" + \" \" + correct );\n $(\"#incorrectA\").text(\"Incorrect Answers:\" + \" \" + wrong );\n $(\"#unasweredA\").text(\"Unanswered :\" + \" \" + unanswered );\n }\n}", "function loadNextQuestion() {\n var questionHeader = document.getElementById(\"question\"); // Will insert questions into this HTML element\n var answerChoices = allQuestions[questionQueue].choices; // Fetching answers\n var questionLegend = document.getElementById(\"qnum\"); // Displays which question the user is currently viewing\n var inputs = document.getElementsByTagName(\"input\"); // To insert questions\n\n questionLegend.innerHTML = \"Question \" + (questionQueue + 1);\n questionHeader.innerHTML = allQuestions[questionQueue].question; // Inserting question text\n\n for(var i = 0, len = answerChoices.length; i < len; i++) {\n label = document.getElementsByTagName(\"label\")[i];\n label.textContent = answerChoices[i];\n document.forms.quiz.elements.answer[i].checked = false; // Ghetto making sure the radio button isn't checked onload!\n }\n\n}", "function showQuestion2() {\n questionBox.innerHTML = questions[1].question;\n answerBoxA.innerHTML = questions[1].answers[0].answer;\n answerBoxB.innerHTML = questions[1].answers[1].answer;\n answerBoxC.innerHTML = questions[1].answers[2].answer;\n}", "function review () { \n\tfor (var i = 0; i < questions.length; i++) {\n\t\tvar userChoice = $(\"input[name = 'question-\" + i +\"']:checked\");\n\t\tif (userChoice.val() == questions[i].correctAnswer) {\n\t\t\tcorrectAnswers++; \n\n\t\t\t} else {\n\t\t\t\tincorrectAnswers++;\n\t\t\t\t\n\t\t}\n\t}\n\t$(\"#correctAnswers\").append(\" \" + correctAnswers);\n\t$(\"#incorrectAnswers\").append(\" \" + incorrectAnswers); \n}", "function generateQuestionReviewView() {\r\n let question = store.questions[store.questionNumber];\r\n let html = `\r\n <div id=\"question-page\">\r\n <div id=\"question-count\">Question ${store.questionNumber + 1} of ${store.questions.length}</div>\r\n <h2 id=\"question\">${question.question}</h2>\r\n <h3> You got the question ${(question.correctAnswer === store.submittedAnswer) ? 'correct!' : 'wrong!'}</h3>\r\n <ul id=\"answers-results\">`;\r\n //For each answer, check if it's right or wrong and highlight it appriorately\r\n question.answers.forEach(answer => {\r\n //answer right\r\n if(answer === question.correctAnswer) {\r\n html += `<li class=\"correct-answer\">${answer}</li>`;\r\n }\r\n //answer wrong and user selected\r\n else if(answer !== question.correctAnswer && answer === store.submittedAnswer) {\r\n html += `<li class=\"wrong-answer\">${answer}</li>`;\r\n }\r\n //answer wrong\r\n else {\r\n html += `<li>${answer}</li>`;\r\n }\r\n });\r\n html += `\r\n </ul>\r\n <div>\r\n <p id=\"count\">Score: ${store.score} out of ${store.questions.length}</p>\r\n <button id=\"next\">${(store.questionNumber < store.questions.length - 1) ? 'NEXT' : 'FINISH'}</button>\r\n </div>\r\n </div>`;\r\n return html;\r\n}", "function createDisplayAnswers() {\r\n\tvar correctPlace = getCorrectPlace();\r\n\tanswers[correctPlace[0]].innerHTML = question[0] + question[1];\r\n\tanswers[correctPlace[1]].innerHTML = Math.floor(Math.random() * 100) + Math.floor(Math.random() * 100);\r\n}", "function loadQuestion(questionIndex){\n q = questions[questionIndex];\n questionEl.text(q.question);\n //$(\"#question\").text(q.question);\n opt0.text(q.option0);\n opt1.text(q.option1);\n opt2.text(q.option2);\n opt3.text(q.option3);\n ans = q.answer;\n}", "function askQuestion() {\n inquirer.prompt([\n {\n type: \"input\",\n message: questionArray[count].partial,\n name: \"answer\"\n }\n ]).then(function(resp) {\n // The answer was correct\n if (resp.answer.toLowerCase() === questionArray[count].cloze.toLowerCase()) {\n console.log(\"Correct\");\n score++; // Increase score\n }\n // The answer was incorrect\n else {\n console.log(\"Incorrect\");\n console.log(\"The correct answer was \" + questionArray[count].cloze)\n }\n count++;\n // If there are more presidents left, ask another question\n if (count < questionArray.length) {\n askQuestion();\n }\n // Otherwise the game is over, display final score\n else {\n console.log(\"Quiz over. You got \" + score + \"/\" + questionArray.length + \" correct.\");\n }\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates and updates the tags and tagData props in the state to reflect the results in the objectList param
updateTags(objectList) { let self = this; const newTags = []; const newTagData = {}; for (let i = 0; i < objectList.length; i++) { const data = [objectList[i].Culture, objectList[i].Medium, objectList[i].Classification]; // New tags dynamically created from objects' culture, medium, and classification data for (let j = 0; j < data.length; j++) { if ( data[j] != null && minTagLength < data[j].length && data[j].length < maxTagLength && !(data[j] in newTagData) ) { // Filter out unwanted tags newTags.push(data[j]); newTagData[data[j]] = false; } } } self.setState({ tags: newTags, tagData: newTagData }); }
[ "updateTagAll(value) {\n\t\tlet items = this.state.items;\n\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\titems[i].tag = value;\n\t\t}\n\t\tthis.setState({\n\t\t\ttagAll: value,\n\t\t\titems: items\n\t\t})\n\t}", "function generateTags(tagsObj){\r\n\tvar tags = tagsObj.photo.tags.tag;\r\n\tvar htmlBlock = '<ul class=\"list-tags\">';\r\n\tif(Object.keys(tags).length > 0){\r\n\t\tvar count = 0;\r\n\t\ttags.forEach( function(tag, index) {\r\n\t\t\thtmlBlock += buildHTMLTagsBlock(tag, index);\r\n\t\t\tcount = index;\r\n\t\t});\t\r\n\t\tif(count >= 3)\r\n\t\t\thtmlBlock += '<li class=\"tag tagButton\" id=\"tag-'+tagsObj.photo.id+' \"onclick=\"showAllTags(this)\")>...</li>'\r\n\t\t\r\n\t\thtmlBlock += '</ul>';\r\n\t\tdocument.getElementById(tagsObj.photo.id).innerHTML += htmlBlock;\r\n\t\tdeleteElement('btn-'+ tagsObj.photo.id);\r\n\t}\r\n\telse{\r\n\t\tdeleteElement('btn-'+ tagsObj.photo.id);\r\n\t\tdocument.getElementById(tagsObj.photo.id).innerHTML += '<div class=\"alert alert-warning bottom\">This image has no tags!</div>';\t\r\n\t}\t\r\n\r\n}", "__update_tags_hook() {\n // update all shapes about the new tags\n for (var i = 0; i < this.__shapes; ++i) {\n var shape = this.__shapes[i].shape;\n shape.__collision_tags_val = this.__collision_tags_val;\n shape.__collision_tags = this.__collision_tags;\n }\n }", "generateTags() {\n var tagArray = []\n this.props.tags.forEach((tag, index) => {\n tagArray.push(<Badge id={\"product-tag-\" + index}>{tag}</Badge>)\n })\n return tagArray;\n }", "addNewItem() {\n\t\tconst newItem = {itemName: \"\", tag: \"None\", description:\"\", price:\"\", pic:\"\"};\n\t\tthis.setState((prevState, props) => ({\n\t\t\titems: prevState.items.concat(newItem)\n\t\t}))\n\t}", "handleTagChange(newTag, index) {\n\t\tif (!this.state.tagAll) { //If no tag all selection\n\t\t\tlet items = this.state.items;\n\t\t\titems[index].tag = newTag;\n\t\t\tthis.setState({\n\t\t\t\titems: items\n\t\t\t})\n\t\t} else {\n\t\t\tif (!this.state.isISO) {\n\t\t\t\tthis.setState({\n\t\t\t\t\tshowTagAllPopup: true\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}", "setData () {\n let forksArr = []\n let starsArr = []\n let watchersArr = []\n let repoNameArr = []\n this.props.repos.map((repo) => {\n repoNameArr.push(repo.name)\n forksArr.push(repo.forks_count)\n starsArr.push(repo.stargazers_count)\n watchersArr.push(repo.watchers)\n })\n this.setState(() => {\n return {\n forksArr: forksArr,\n starsArr: starsArr,\n watchersArr: watchersArr,\n repoNameArr: repoNameArr\n }\n })\n }", "showUpdatingSubCategory(e, ch) {\n e.preventDefault(e);\n\n //tags input to show\n let mappedTagsInputs = [];\n ch.properties.map((prop) => {\n mappedTagsInputs.push(prop.key);\n });\n //subcategory to show\n let subcategory = {\n name: ch.name,\n slug: ch.slug,\n };\n this.setState({\n subcategory: subcategory,\n tagsinput: mappedTagsInputs,\n idSubcategory: ch._id,\n tagsinputToUpdate: ch.properties,\n // handle the view\n showUpdate: true,\n showCategoryUpdate: false,\n showSubCategoryUpdate: true,\n });\n }", "function updatePokemonObject(pokemonData) {\n PokemonObject.name = pokemonData.name;\n PokemonObject.height = pokemonData.height;\n PokemonObject.weight = pokemonData.weight;\n PokemonObject.frontImgSrc = pokemonData.sprites.front_default;\n PokemonObject.backImgSrc = pokemonData.sprites.back_default;\n PokemonObject.typeList = [];\n PokemonObject.namesRelatedToTypesUrls = [];\n\n for (let type of pokemonData.types){\n PokemonObject.typeList.push(type.type.name);\n PokemonObject.namesRelatedToTypesUrls.push(type.type.url);\n }\n}", "function buildTags()\n {\n TagAPI.get().done((results) => {\n let $modal = $('#tags-modal'),\n id = $(this).attr('data-id'),\n tags = $(results[id]),\n tagCloud = [];\n\n if (tags.length > 0)\n {\n tags.each(function (index, tag) {\n tagCloud.push(\n '<div class=\"tag-entry\">',\n '<strong>' + tag.label + '</strong>',\n '<button type=\"button\" class=\"tag-remove\" data-id=\"' + tag.id + '\"><span class=\"glyphicon glyphicon-trash\"></span></a>',\n '</div>'\n );\n });\n\n $modal.find('#tags-list').html(tagCloud.join(\"\\n\"));\n }\n\n $modal.find('#item-tags').val('');\n $modal.find('#item-id').val(id);\n $modal.modal('show');\n });\n }", "addComponent(postData){\n const components = this.state.components;\n components.push(postData);\n this.setState({\n components:components\n });\n }", "componentDidUpdate() {\n const tipStates = this.tipStates\n if (this.state.tipState === tipStates.loading) {\n this.props.getLinkInfo((data) => {\n const linkArray = data.map((el, index) => (\n <li key={index}>\n <a href={el.href}>{el.text}</a> - {el.status}\n </li>\n ))\n this.setState({\n tipState: this.tipStates.revealing,\n tipJSX: (\n <React.Fragment>\n <h4>Competetor Links</h4>\n <ul style={{textAlign: 'left'}}>\n {linkArray}\n </ul>\n </React.Fragment>\n )\n })\n },\n (error) => {\n this.setState({tipState: tipStates.error})\n console.log(error.message)\n })\n }\n }", "renderLists() {\n const renderedItems = [];\n\n if (!this.state.rankingData.length) {\n this.addList();\n }\n\n for (let i = 0; i < this.state.rankingData.length; i++) {\n\n const ranking = this.state.rankingData[i];\n \n renderedItems.push(\n <div>\n <RankingList\n items={ranking[1]['items']}\n listDisplayName = {ranking[1]['listDisplayName']}\n listName = {ranking[0]}\n type = {ranking[1]['type']}\n user={this}\n owner={ranking[1]['owner']}\n />\n </div>\n )\n }\n\n this.setState({renderedItems: renderedItems});\n }", "createPlayerList() {\n let playerList = {};\n // Create playerBig object\n for (let i = 0; i < this.props.players.big; i++) {\n // Initialize position/coordinates\n const size = 3;\n const position = this.setPlayerPosition(\n BORDER_SIZE + 2,\n this.props.xDimension - size - BORDER_SIZE - 2,\n size\n );\n const coordinates = this.setPlayerCoordinates(size, position);\n\n let playerObj = {\n type: 'big',\n color: 'red',\n border: '2px solid black',\n size,\n moveReady: true,\n delay: 100,\n // need to pass in created object to refer to the object that size is being called on\n // already bound to class, so can't use this.size\n // ie. position: ()=>this.setPlayerPosition(0,this.props.xDimension-playerObj.size)\n position,\n coordinates,\n };\n playerList.playerBig = playerObj;\n }\n\n // Create playerSmall objects\n for (let i = 0; i < this.props.players.small; i++) {\n // Initialize position/coordinates\n const size = 1;\n let position = this.setPlayerPosition(\n this.props.yDimension - size - i * size - BORDER_SIZE,\n i * size + BORDER_SIZE,\n size\n );\n const coordinates = this.setPlayerCoordinates(size, position);\n\n let playerObj = {\n type: 'small',\n color: playerColorKey[i],\n border: '2px solid black',\n size,\n moveReady: true,\n delay: 0,\n position,\n coordinates,\n };\n playerList[`playerSmall${i + 1}`] = playerObj;\n }\n return playerList;\n }", "renderAuthorBooks() {\n const authorBooks = this.state.authorBooks;\n return (\n <ul>\n {authorBooks.map((book) => <BookList key={book.id} {...book} />)}\n </ul>\n );\n }", "async updateHouses() {\n let length = await this.state.houseToken.methods.nextId().call()\n \n const houses = []\n for(let i=1; i<length; i++){\n let currentHouse = await this.state.houseToken.methods.houses(i).call()\n houses.push(currentHouse)\n }\n \n await this.setState({houseTokenList: houses, filteredHouseList: houses}) \n }", "renderTags(){\n // Call to database to populate the possible tags\n interests = eventActions.renderPossibleInterests();\n\n var interestsViews = [];\n for (i in interests)\n {\n var interest = i;\n var isSelected = this.state.interests.indexOf(interest) == -1 ? false : true;\n // var backgroundColor = this.state.interests.indexOf(interest) == -1 ? styleVariables.greyColor : '#0B82CC';\n interestsViews.push(\n <Button ref={interest} underlayColor={'#FFFFFF'} key={i} style={isSelected ? styles.selectedCell : styles.interestCell} textStyle={isSelected ? styles.selectedCellText : styles.interestCellText} onPress={this.buttonPressed.bind(this,interest)}>{interest.toUpperCase()}</Button>\n );\n }\n\n return interestsViews;\n }", "handlePackagingChange(event, data) {\n let packagingId;\n let packagingName = data.value;\n let packagingList = this.state.packaging.packagingList;\n\n for (let i = 0; i < packagingList.length; i++) {\n let currPackaging = packagingList[i];\n if (currPackaging.value == packagingName) {\n packagingId = currPackaging.key;\n break;\n }\n }\n\n let newPackaging = this.state.packaging;\n newPackaging.itemPackaging = { id: packagingId, name: packagingName };\n\n this.setState({\n packaging: newPackaging\n });\n }", "initializeList(listOfIds) {\n let currentObjectivesCount = parseInt(getValue('cmi.object._count'));\n if (currentObjectivesCount) {\n DEBUG.log('objectives already initialized');\n return;\n } else {\n listOfIds.forEach(obj => this.addObjective(obj));\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checkbox with no label (say, has to fit vertically & horizontally) helper
isThisCheckboxLabeless() { return this.type==='checkbox' && typeof this.label==="undefined"; }
[ "function renderCheckbox(val) {\n var checkedImg = '/bundles/netresearchtimetracker/js/ext-js/resources/themes/images/default/menu/checked.gif';\n var uncheckedImg = '/bundles/netresearchtimetracker/js/ext-js/resources/themes/images/default/menu/unchecked.gif';\n var result = '<div style=\"text-align:center;height:13px;overflow:visible\"><img style=\"vertical-align:-3px\" src=\"'\n + (val ? checkedImg : uncheckedImg)\n + '\" /></div>';\n\n return result;\n}", "checkBox(x, y, label, value) {\n return this.appendChild(new CheckBox(x, y, label, value));\n }", "function Checkbox(label, v) {\r\n if (Array.isArray(v)) {\r\n return bind.Checkbox(label, v);\r\n }\r\n else {\r\n const ref_v = [v()];\r\n const ret = bind.Checkbox(label, ref_v);\r\n v(ref_v[0]);\r\n return ret;\r\n }\r\n }", "function checkboxTemplate(name, value, label){\n var $tpl=\"<li>\";\n $tpl+=\"<input type='checkbox' name='\"+name+\"' value='\"+value+\"' />\";\n $tpl+=label;\n $tpl+=\"</li>\";\n return $tpl;\n }", "render() {\n const checkboxes = this.props.form.value.contents.map(content => {\n const childPath = this.props.form.path + \".\" + content.value\n content.checked = get(childPath, \"toggle\")\n\n return <div key={childPath}>\n <input\n type=\"checkbox\"\n className=\"k-checkbox\"\n id={childPath}\n defaultChecked={content.checked}\n onClick={(event) => this.props.updateState(childPath, event.target.checked)} />\n <label className=\"k-checkbox-label\" htmlFor={childPath}>{content.text}</label>\n </div>\n })\n\n return <div className=\"k-form-field\">\n <LabelTooltip form={this.props.form} />\n {checkboxes}\n </div>\n }", "createCheckboxes() {\n const checkboxes = [];\n for (const option in this.props.const.option) {\n checkboxes.push(\n <Checkbox\n key={this.props.const.option[option]}\n name={this.props.const.option[option]}\n activeCheckbox={this.state.activeCheckbox}\n onclick={this.checkboxSelection.bind(this)}\n />\n );\n }\n return checkboxes;\n }", "function createCheckBox(createElement, enableRipple = false, options = {}) {\n let wrapper = createElement('div', { className: 'e-checkbox-wrapper e-css' });\n if (options.cssClass) {\n Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"addClass\"])([wrapper], options.cssClass.split(' '));\n }\n if (options.enableRtl) {\n wrapper.classList.add('e-rtl');\n }\n if (enableRipple) {\n let rippleSpan = createElement('span', { className: 'e-ripple-container' });\n Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"rippleEffect\"])(rippleSpan, { isCenterRipple: true, duration: 400 });\n wrapper.appendChild(rippleSpan);\n }\n let frameSpan = createElement('span', { className: 'e-frame e-icons' });\n if (options.checked) {\n frameSpan.classList.add('e-check');\n }\n wrapper.appendChild(frameSpan);\n if (options.label) {\n let labelSpan = createElement('span', { className: 'e-label', innerHTML: options.label });\n wrapper.appendChild(labelSpan);\n }\n return wrapper;\n}", "function NLCheckboxOnChange(fld)\n{\n if (!fld)\n\t\treturn;\n\t// make sure the input and the custom checkbox image on the parent span is in sync\n\tvar span = getNLCheckboxSpan(fld);\n if (span)\n {\n if (fld.checked)\n span.className = span.className.replace('_unck', '_ck');\n else\n span.className = span.className.replace('_ck', '_unck');\n }\n}", "function useCheckbox(props) {\n if (props === void 0) {\n props = {};\n }\n\n var {\n defaultIsChecked,\n isChecked: checkedProp,\n isFocusable,\n isDisabled,\n isReadOnly,\n isRequired,\n onChange,\n isIndeterminate,\n isInvalid,\n name,\n value,\n id\n } = props,\n htmlProps = _objectWithoutPropertiesLoose(props, [\"defaultIsChecked\", \"isChecked\", \"isFocusable\", \"isDisabled\", \"isReadOnly\", \"isRequired\", \"onChange\", \"isIndeterminate\", \"isInvalid\", \"name\", \"value\", \"id\"]);\n\n var [isFocused, setFocused] = (0, _hooks.useBoolean)();\n var [isHovered, setHovered] = (0, _hooks.useBoolean)();\n var [isActive, setActive] = (0, _hooks.useBoolean)();\n var ref = (0, _react.useRef)(null);\n var [checkedState, setCheckedState] = (0, _react.useState)(!!defaultIsChecked);\n var [isControlled, isChecked] = (0, _hooks.useControllableProp)(checkedProp, checkedState);\n var handleChange = (0, _react.useCallback)(event => {\n if (isReadOnly || isDisabled) {\n event.preventDefault();\n return;\n }\n\n if (!isControlled) {\n if (isChecked) {\n setCheckedState(event.target.checked);\n } else {\n setCheckedState(isIndeterminate ? true : event.target.checked);\n }\n }\n\n onChange == null ? void 0 : onChange(event);\n }, [isReadOnly, isDisabled, isChecked, isControlled, isIndeterminate, onChange]);\n (0, _hooks.useSafeLayoutEffect)(() => {\n if (ref.current) {\n ref.current.indeterminate = Boolean(isIndeterminate);\n }\n }, [isIndeterminate]);\n var trulyDisabled = isDisabled && !isFocusable;\n var onKeyDown = (0, _react.useCallback)(event => {\n if (event.key === \" \") {\n setActive.on();\n }\n }, [setActive]);\n var onKeyUp = (0, _react.useCallback)(event => {\n if (event.key === \" \") {\n setActive.off();\n }\n }, [setActive]);\n return {\n state: {\n isInvalid,\n isFocused,\n isChecked,\n isActive,\n isHovered,\n isIndeterminate,\n isDisabled,\n isReadOnly,\n isRequired\n },\n getCheckboxProps: function getCheckboxProps(props, _ref) {\n if (props === void 0) {\n props = {};\n }\n\n if (_ref === void 0) {\n _ref = null;\n }\n\n var onPressDown = event => {\n // On mousedown, the input blurs and returns focus to the `body`,\n // we need to prevent this. Native checkboxes keeps focus on `input`\n event.preventDefault();\n setActive.on();\n };\n\n return _extends({}, props, {\n ref: _ref,\n \"data-active\": (0, _utils.dataAttr)(isActive),\n \"data-hover\": (0, _utils.dataAttr)(isHovered),\n \"data-checked\": (0, _utils.dataAttr)(isChecked),\n \"data-focus\": (0, _utils.dataAttr)(isFocused),\n \"data-indeterminate\": (0, _utils.dataAttr)(isIndeterminate),\n \"data-disabled\": (0, _utils.dataAttr)(isDisabled),\n \"data-invalid\": (0, _utils.dataAttr)(isInvalid),\n \"data-readonly\": (0, _utils.dataAttr)(isReadOnly),\n \"aria-hidden\": true,\n onMouseDown: (0, _utils.callAllHandlers)(props.onMouseDown, onPressDown),\n onMouseUp: (0, _utils.callAllHandlers)(props.onMouseUp, setActive.off),\n onMouseEnter: (0, _utils.callAllHandlers)(props.onMouseEnter, setHovered.on),\n onMouseLeave: (0, _utils.callAllHandlers)(props.onMouseLeave, setHovered.off),\n style: _extends({\n touchAction: \"none\"\n }, props.style)\n });\n },\n getInputProps: function getInputProps(props, inputRef) {\n if (props === void 0) {\n props = {};\n }\n\n if (inputRef === void 0) {\n inputRef = null;\n }\n\n return _extends({}, props, {\n ref: (0, _utils.mergeRefs)(ref, inputRef),\n type: \"checkbox\",\n name,\n value,\n id,\n onChange: (0, _utils.callAllHandlers)(props.onChange, handleChange),\n onBlur: (0, _utils.callAllHandlers)(props.onBlur, setFocused.off),\n onFocus: (0, _utils.callAllHandlers)(props.onFocus, setFocused.on),\n onKeyDown: (0, _utils.callAllHandlers)(props.onKeyDown, onKeyDown),\n onKeyUp: (0, _utils.callAllHandlers)(props.onKeyUp, onKeyUp),\n required: isRequired,\n checked: isChecked,\n disabled: trulyDisabled,\n readOnly: isReadOnly,\n \"aria-invalid\": isInvalid,\n \"aria-disabled\": isDisabled,\n style: _visuallyHidden.visuallyHiddenStyle\n });\n },\n getLabelProps: function getLabelProps(props, ref) {\n if (props === void 0) {\n props = {};\n }\n\n if (ref === void 0) {\n ref = null;\n }\n\n return _extends({}, props, {\n ref,\n onMouseDown: (0, _utils.callAllHandlers)(props.onMouseDown, stopEvent),\n onTouchStart: (0, _utils.callAllHandlers)(props.onTouchState, stopEvent),\n \"data-disabled\": (0, _utils.dataAttr)(isDisabled),\n \"data-checked\": (0, _utils.dataAttr)(isChecked),\n \"data-invalid\": (0, _utils.dataAttr)(isInvalid)\n });\n },\n htmlProps\n };\n}", "static getCheckboxForRow(selected, checkboxHandler, cellType) {\n const CellComponent = `${cellType}`;\n return (\n <CellComponent key='meta-check' className='run-table-container'>\n <div>\n <input type='checkbox' checked={selected} onChange={checkboxHandler} />\n </div>\n </CellComponent>\n );\n }", "function checkbox($this, o){\n \n var $label, $checkbox, isSelected;\n //option firstCheckAll \n //[1=checks all checkboxes] \n //[2=checks only firs checkbox but works like all are checked - default option]\n //[false=normal behavior]\n \n //if option firstCheckAll==1\n if(o.firstCheckAll==1){\n \t\n $checkbox=$this.next(\".\"+o.prefix+\"checklist\").find(\"li:not(:first-child) input[type=checkbox]\");\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child input[type=checkbox]\").change(function() {\n \n if($(this).is(\":checked\")){\n \t\n $this.find('option').each(function(){\n $(this).attr(\"selected\", \"selected\");\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:not(:first-child) input[type=checkbox]\").each(function(){\n $(this).prop(\"checked\", true); \n window.console.log($(this)); \n });\n $label=$this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child\").text();\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html($label);\n isSelected=true;\n } else {\n $this.find('option').each(function(){\n $(this).removeAttr(\"selected\");\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\"input[type=checkbox]\").each(function(){\n $(this).prop(\"checked\", false);\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html(\"\");\n isSelected=false;\n }\n \n\t\t\t//provides a callback for first element click and transports the select selector and a boolean for selected checkbox\n o.first($this, isSelected);\n });\n //else if option firstCheckAll=2\n } else if(o.firstCheckAll==2){\n \n $checkbox=$this.next(\".\"+o.prefix+\"checklist\").find(\"li:not(:first-child) input[type=checkbox]\");\n \n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child input[type=checkbox]\").change(function() {\n isSelected=false;\n if(!$(this).is(\":checked\") && $checkbox.find(\":checked\").length === 0) {\n \n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html(\"\");\n isSelected=false;\n } else {\n $this.find('option:not(:first-child)').each(function(){\n $(this).removeAttr(\"selected\");\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:not(:first-child) input[type=checkbox]\").each(function(){\n $(this).prop(\"checked\", false);\n });\n $label=$this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child\").text();\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html($label);\n isSelected=true;\n }\n //provides a callback for first element click and transports the select selector and a boolean for selected checkbox\n o.first($this, isSelected);\n }); \n // else i define the normal behavior \n } else {\n $checkbox=$this.next(\".\"+o.prefix+\"checklist\").find(\"input[type=checkbox]\");\n }\n \n // for each checkbox created \n $checkbox.each(function(){\n \t// i listen when the checkbox change value\n $(this).change(function(){\n var $selector=$(this);\n var $value=$selector.val();\n \n \n // if the user checked the checkbox \n if($selector.is(\":checked\")){\n $this.find('option[value=\"' + $value + '\"]').attr(\"selected\", \"selected\");\n // if is the first checkbox and the firstCheckAll option is set\n if(o.firstCheckAll==2 || o.firstCheckAll==1) {\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child input[type=checkbox]\").prop(\"checked\", false);\n }\n // else if unchecked the checkbox\n } else {\n $this.find('option[value=\"' + $value + '\"]').removeAttr(\"selected\");\n // if is the first checkbox and the firstCheckAll option is set\n if(o.firstCheckAll==2 || o.firstCheckAll==1) {\n $this.next(\".\"+o.prefix+\"checklist\").find(\"li:first-child input[type=checkbox]\").prop(\"checked\", false);\n }\n }\n \n //if i used some optgroups [does'nt work with the option checkedOnTop set to true]\n if(o.optgroup===true) {\n $label=\"\";\n $this.next().find('input:checked').each(function(){\n if($label!==\"\"){\n $label+=\", \"+$(this).parent().text();\n } else {\n $label+=$(this).parent().text();\n }\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html($label);\n //else if is a plain selectbox\n } else {\n $label=\"\";\n $this.next().find('input:checked').each(function(){\n if($label!==\"\"){\n $label+=\", \"+$(this).parent().text();\n } else {\n $label+=$(this).parent().text();\n }\n });\n $this.next(\".\"+o.prefix+\"checklist\").find(\".\"+o.prefix+\"label\").html($label);\n }\n //provides a callback for the change event, transports the checkbox selector and the checkbox value\n o.change($selector, $value);\n });\n });\n }", "function validateCheckBox(obj, req) {\n\n\tif(req) {\n\n\t\tif(!obj.checked) return 'Please tick ' + ucwords(obj.name);\t\n\n\t\telse return null;\n\n\t} else {\n\n\t\treturn null;\t\n\n\t}\n\n}", "function createMenuLabel(grammarRule, initChecked) {\n const checkboxLabel = document.createElement('label');\n checkboxLabel.classList.add(\"checkbox-label\");\n\n const checkbox = document.createElement('input');\n checkbox.setAttribute('type', 'checkbox');\n checkbox.checked = initChecked;\n CommandIde.addEventListener(checkbox, 'change', () => $ctrl.api.changeDefaultRulePreferences(grammarRule.name, checkbox.checked));\n checkboxLabel.append(checkbox);\n\n const checkmark = document.createElement('span');\n checkmark.classList.add(\"checkmark\");\n checkboxLabel.append(checkmark);\n\n const labelText = document.createElement('span');\n labelText.classList.add(\"label-text\");\n labelText.textContent = grammarRule.descriptiveName;\n checkboxLabel.append(labelText);\n\n return checkboxLabel;\n }", "function createCheck(label) {\r\n if (label.childElementCount > 0) {\r\n label.removeChild(label.childNodes[1]);\r\n }\r\n var node = document.createElement(\"I\")\r\n node.className = \"fas fa-check-circle\";\r\n node.style = \"color:green\";\r\n label.appendChild(node);\r\n}", "function checkCheckBox(cb){\r\n\treturn cb.checked;\r\n}", "function newCheckbox() {\n\tvar checkbox = $(document.createElement(\"INPUT\"));\n\tcheckbox.attr(\"type\", \"checkbox\")\n\tcheckbox.bind(\"change\", function() {\n\t\tcheckbox.parent().toggleClass(\"checked\");\n\t});\n\treturn checkbox;\n}", "function addInputCheckbox(switchLabel, coin) {\n let inptSwtch = $(\"<input>\").attr(\"type\", \"checkbox\");\n addEventToSwitch(inptSwtch, coin);\n inptSwtch.appendTo(switchLabel);\n }", "label(text, size = -1) {\n //TODO\n }", "function toggleBoundingBox(obj) {\n\tobj.checked = !obj.checked;\n\tobj.innerHTML = '&nbsp; bounding box';\n\tif (obj.checked) {\n\t\tobj.innerHTML = '&raquo; bounding box';\n\t}\n\tmyimgmap.config.bounding_box = obj.checked;\n\tmyimgmap.relaxAllAreas();\n\tgui_toggleMore();\n}", "function BinaryBox(x, y, size, isClickable) {\n this.size = size;\n this.isClickable = isClickable;\n\n\n if (size == BoxSize.LARGE) {\n LargeTextBox.call(this, x, y, size, size, \"0\", isClickable);\n \n } else {\n TextBox.call(this, x, y, size, size, \"0\", undefined, isClickable);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handles click on tile FINISH
function handle_click(){ // which tile? var tile = $(this); // don't do anything if just clicked or already matched if (tile.hasClass('active') || tile.hasClass('matched')) { // we're done return false; } // keep track of number of clicks num_clicks++; //activate tile activate_tile(tile); // maybe more here? if (is_two_selected() && is_current_selection_a_match()) { // implement } alert('clicked!'); }
[ "function doTileExit() {\n\tremoveEventListeners();\n\tif (verboseDebugging){\n\t\tconsole.log(\"in doTileExit debugging\");\n\t\tconsole.log(\"this is good\");\n\t}\n\tmessageDiv.style.display = \"none\";\n\tpasswordDiv.style.display = \"none\";\n\n\t//make sure to return repromptPassword flag to default if changes\n\trepromptPassword = false;\n\n\t//send a request to free up the tile for editing again\n\tvar payload = {};\n\tpayload.xcoord = xTile;\n\tpayload.ycoord = yTile;\n\tif (verboseDebugging){\n\t\tconsole.log(\"Payload to freetile\");\n\t\tconsole.log(payload);\n\t}\n\tpostRequest('/freetile',payload,exitCallback,postOnError);\n}", "clickTile(tile) {\n\t\t\n const reply = { \"header\": {}, \"tiles\": [] };\n\n // are we clicking on a mine\n\t\tif (tile.isBomb()) {\n\t\t\tthis.actions++;\n\n reply.header.status = LOST;\n tile.exploded = true;\n\t\t\t//reply.tiles.push({\"action\" : 3, \"index\" : tile.getIndex()}); // mine\n\n } else {\n\t\t\tif (tile.isCovered() && !tile.isFlagged()) { // make sure the tile is clickable\n\t\t\t\tthis.actions++;\n\n\t\t\t\tconst tilesToReveal = [];\n\t\t\t\ttilesToReveal.push(tile);\n\t\t\t\treturn this.reveal(tilesToReveal);\n\t\t\t} else {\n\t\t\t\treply.header.status = IN_PLAY;\n }\n\t\t}\n\t\t\n\t\treturn reply;\n\t\t\n\t\t\n\t}", "function registerClick(e) {\n var desiredResponse = copy.shift();\n var actualResponse = $(e.target).data('tile');\n active = (desiredResponse === actualResponse);\n checkLose();\n }", "function lvCockpitsItemInvoked(e) {\n e.detail.itemPromise.done(function (item) {\n DataExplorer.drawTile(item.data);\n });\n }", "function doTileExitNoFree() {\n\tremoveEventListeners();\n\tif (verboseDebugging){\n\t\tconsole.log(\"in doTileExit debugging\");\n\t\tconsole.log(\"this is good\");\n\t}\n\tmessageDiv.style.display = \"none\";\n\tpasswordDiv.style.display = \"none\";\n\n\t//make sure to return repromptPassword flag to default if changes\n\trepromptPassword = false;\n\n\t//send a request to free up the tile for editing again\n\tvar payload = {};\n\tpayload.xcoord = xTile;\n\tpayload.ycoord = yTile;\n\tif (verboseDebugging){\n\t\tconsole.log(\"Payload to freetile\");\n\t\tconsole.log(payload);\n\t}\n\t// clear out all the current SVG\n\tsvgClearAll();\n\t\n\t// reset drawing tool defaults\n\tsvgResetDefaults();\n\t\n\t// set the mode\n\tpreviousMode = mode;\n\tmode = gameMode;\n\n\t// display correct div\n\tshowDiv(mode); // handles hiding message box div\n\t\n\t// debug message\n\tif (debugging) {\n\t\tconsole.log(\"Exited tile editing screen.\");\n\t}\n\t\n\t// make crafty reload the art assets for this tile\n\tinitAssetRequest(xTile, yTile);\n}", "function handleClickOnTimeline() {\r\n // Find clicked item\r\n var clickedContentItem = getContentItemOnMousePosition();\r\n\r\n // If no item found zoom out\r\n if (clickedContentItem === undefined) {\r\n clickedContentItem = Canvas.Breadcrumbs.decreaseDepthAndGetTheNewContentItem();\r\n }\r\n\r\n // Make sure root is not reached\r\n if (clickedContentItem !== undefined && clickedContentItem.id !== 0) {\r\n handleClickOnContentItem(clickedContentItem);\r\n }\r\n }", "function startClick() {\n\t$$(\"div#maze div.boundary\").each(function (item) {\n\t\titem.removeClassName(\"youlose\");\n\t});\n\tend = true;\n\t$(\"status\").textContent = \"Find the end\";\n}", "onLayerClick() {}", "function handleMapMouseEvent(evt) \n{\n\t//output.text = \"evt.target: \"+evt.target+\", evt.type: \"+evt.type;\n\t\n\tif(evt.type == \"click\")\n\t{\n\t\tvar x = evt.stageX - evt.target.x;\n\t\tvar y = evt.stageY - evt.target.y;\n\t\t\n\t\tvar row = Math.floor(y/24);\n\t\tvar column = Math.floor(x/24);\n\t\t\n\t\t//infoText = \"Tile:(\" + row + \",\" + column + \")\";\n\t\t//updateInfoText();\n\t\t\n\t\tremoveStackSelectionBox();\n\t\t\n\t\tif(selectedObject == null)\n\t\t{\n\t\t\t//nothing is selected\n\t\t\t//select object\n\t\t\tselectObject(row,column);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//something is selected\n\t\t\tif(isUnit(selectedObject) == true)\n\t\t\t{\n\t\t\t\t//if selectedObject is a unit\n\t\t\t\tunitHandler(row,column);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//if selectedObject is not a unit\n\t\t\t\tif(selectedObject.row != row || selectedObject.column != column)\n\t\t\t\t{\n\t\t\t\t\t//if selectedObject is not at (row, column)\n\t\t\t\t\tdeSelectAll();\n\t\t\t\t\tselectObject(row,column);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdeSelectAll();\n\t\t\t\t\tselectObject(row,column);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\tcacheStage();\n\tstage.update();\n}", "finish() {\n this.finishBtn.click();\n }", "flag(tile) {\n\n\t\tthis.actions++;\n\t\ttile.toggleFlag();\n\n }", "function animateTiles(clickedIndex) {\n $(this).fadeOut(70); \n $(this).fadeIn(200); \n }", "function ksfHelp_mainTourEnd()\n{\n\tksfHelp_mainTour.end();\n}", "tileClicked (x, y, value) {\n console.log(this.props.players)\n console.log(\"clicked \", x,y);\n //sent the event to all players\n //TODO: should be done with events\n this.props.players.forEach(player => player.tileClicked({x,y, value}));\n }", "function _iconClickEvent() {\n\n\t\t_toggleVisibility();\n\n\t\t// Turn of file watching when not using it\n\t\tif (false === visible) {\n\t\t\ttailDomain.exec(\"quitTail\")\n\t\t\t\t.done(function () {\n\t\t\t\t\tconsole.log(\"[brackets-tail-node] quitTail done event\");\n\t\t\t\t}).fail(function (err) {\n\t\t\t\t\tconsole.error(\"[brackets-tail-node] quitTail error event\", err);\n\t\t\t\t});\n\t\t}\n\t}", "function onArtistTileClick(divID){\n\n var mbid = O(divID).firstChild; //Get last.fm ID\n var artist = getArtistInfo(mbid.value); //Get the artist\n var teaseDiv = document.createElement(\"div\"); //Div for teaser information\n var teaseCloseBtn = document.createElement(\"div\");\n var teaseContent = document.createElement(\"div\");\n var link = document.createElement(\"a\");\n var headline = document.createElement(\"H4\"); //Artist name\n var para = document.createElement(\"p\"); //Text to put in the teaser div\n\n\n //Setting memberships\n teaseDiv.id = \"teaseDiv\";\n teaseDiv.className = \"teaserP teaserF\";\n link.className = \" btn-default moreInfo\";\n teaseCloseBtn.id = \"btn-closeTeaser\"\n\n //Adding content\n headline.appendChild(document.createTextNode(artist.name));\n para.innerHTML = \"<figure>\";\n para.innerHTML += \"<img src=\" + artist.image_l + \" alt='\" + artist.name + \"'/>\";\n para.innerHTML += \"</figure>\";\n para.innerHTML += artist.bio;\n teaseCloseBtn.innerHTML = \"<a href='javascript:void(0)' onclick='onBlanketClose();'>x</a>\";\n\n link.onclick = function(){\n window.location.href = \"artist.html?mbid=\"+mbid.value;\n };\n link.title = \"More info\";\n link.appendChild(document.createTextNode(\"More info\"));\n\n\n //Adding to document\n teaseContent.appendChild(headline);\n teaseContent.appendChild(para);\n teaseContent.appendChild(link);\n teaseDiv.appendChild(teaseContent);\n teaseDiv.appendChild(teaseCloseBtn);\n O(\"wrapperID\").appendChild(teaseDiv);\n\n O(\"blanket\").className = O(\"blanket\").className + \" enableBlanket\";\n\n}", "function clickHour() {\n let oldSelected = document.querySelector(\".selectedHourTile\");\n if (oldSelected != null) {\n oldSelected.classList.remove(\"selectedHourTile\");\n }\n this.classList.add(\"selectedHourTile\");\n $(\"selectedHour\").textContent = this.textContent + \" \" + $(\"selectedAmpm\").textContent;\n \n // make load button visible\n $(\"loadContainer\").style.display = \"block\";\n\n // duration check \n // for now im too lazy to write a check, just going to reset to 1 every time\n // might be slightly annoying for user\n $(\"selectedDuration\").textContent = \"1 hour(s) long\";\n }", "function handleEndOfGameClick(){\n location.reload()\n\n }", "function performActions() {\n\n // prepare event data\n event_data = $.integrate( entry_data, event_data );\n event_data.content = content_elem;\n event_data.entry = entry_elem;\n delete event_data.actions;\n\n // perform menu entry actions\n if ( entry_data.actions )\n if ( typeof ( entry_data.actions ) === 'function' )\n entry_data.actions( $.clone( event_data ), self );\n else\n entry_data.actions.forEach( action => $.action( action ) );\n\n // perform callback for clicked menu entry\n self.onclick && $.action( [ self.onclick, $.clone( event_data ), self ] );\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clears compvared rows iterating through rows and columns to check whether any 0 is present
function clearRows() { var toBeCleared = []; for (var row = 0; row < grid.length; row++) { var withEmptySpace = false; for (var col = 0; col < grid[row].length; col++) { if (grid[row][col] === 0) { withEmptySpace = true; } } if (!withEmptySpace) { toBeCleared.push(row); } } if (toBeCleared.length == 1) { score += 400; } else if (toBeCleared.length == 2) { score += 1000; } else if (toBeCleared.length == 3) { score += 3000; } else if (toBeCleared.length == 4) { score += 12000; } var clearedRows = clone(toBeCleared.length); for (var toBe = toBeCleared.length - 1; toBe >= 0; toBe--) { grid.splice(toBeCleared[toBe], 1); } while (grid.length < 20) { grid.unshift([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); } return clearedRows; }
[ "function RowClear(_board, _x, _numToCheck)\n{\n for (let i = 0; i < MBS; i++)\n {\n if(_board[_x][i] == _numToCheck)\n {\n return false;\n }\n }\n return true;\n}", "function clearCells() {\n\tfor(i = 0; i < maxRow; i++) {\n\t\tfor(j = 0; j < maxCol; j++) {\n\t\t\tcellID = '#'+j+'_'+i\n\t\t\t$(cellID).remove()\n\t\t}\n\t}\n}", "function clearVirtual(checkRow, checkCol) {\n let sumOfRow = 0;\n let sumOfCol = 0;\n let colArray = [];\n // Clear row if it is full\n virtualBoard[checkRow].forEach (function (element) {\n sumOfRow += element; \n });\n if (sumOfRow == N_SIZE) {\n for (let i = 0; i < N_SIZE; i++) {\n virtualBoard[checkRow][i] = 0;\n };\n }\n // Clear col if it is full \n for (let i = 0; i < N_SIZE; i++) {\n colArray.push(virtualBoard[i][checkCol]);\n };\n colArray.forEach (function (element) {\n sumOfCol += element;\n });\n if (sumOfCol == N_SIZE) {\n for (let i = 0; i < N_SIZE; i++) {\n virtualBoard[i][checkCol] = 0;\n };\n };\n /*\n We will want to creatte a virtual score - as well as the real score \n */\n}", "function viderTable() {\n var numRows = document.getElementById(\"table\").rows.length;\n var numColumns = document.getElementById(\"table\").rows[0].cells.length;\n for (var i = 0; i < numRows; i++) {\n for (var j = 0; j < numColumns; j++) {\n if (document.getElementById(\"table\").rows[i].cells[j].innerHTML != '') {\n document.getElementById(\"table\").rows[i].cells[j].innerHTML = '';\n changerCouleur(i,j);\n }\n }\n }\n}", "function ColumnClear(_board, _y, _numToCheck)\n{\n for (let i = 0; i < MBS; i++)\n {\n if(_board[i][_y] == _numToCheck)\n {\n return false;\n }\n }\n return true;\n}", "function trimLeadingEmptyRows(pxMatrix, limit) {\n for (let i=0; i<limit; i++) {\n if (pxMatrix.length>0 && pxMatrix[0].reduce((a, b) => a+b) == 0) {\n pxMatrix.shift();\n } else {\n break;\n }\n }\n}", "simplifyMat(){\n for(let i = 0; i < this.nRows; i++){\n\n let simplify = false;\n\n for(let j = 0; j < this.nColumns; j++){\n if(this.matrix[i][j] != 0){\n simplify = true;\n }\n }\n\n if(simplify){\n this.simplifyRow(i);\n }\n\n }\n }", "disposeRows() {\n // keep rows still in use, remove the others\n const keepers = [];\n this.rows.forEach((row) => {\n if (row.updateReference === this.updateReference) {\n keepers.push(row);\n } else {\n this.sceneGraph.root.removeChild(row);\n }\n });\n this.rows = keepers;\n }", "function lineClear() {\n\tlet countClearLines = 0;\n\tlet line = 0;\n\tlet lineCount = grid[0].length - 2;\n\tfor (let i = 0; i < grid.length; i++) {\n\t\tfor (let j = 0; j < grid.length; j++) {\n\t\t\tif (grid[j][lineCount] === true) line++;\n\t\t}\n\t\tif (line === grid.length) {\n\t\t\tcountClearLines++;\n\t\t\tctx.clearRect(\n\t\t\t\t0,\n\t\t\t\t(bottom - 1 - i) * squareDimensions,\n\t\t\t\tsquareDimensions * 20,\n\t\t\t\tsquareDimensions\n\t\t\t);\n\t\t\tclearPlacement(lineCount);\n\t\t\tmoveDown((lineCount - 1) * squareDimensions);\n\t\t\tlineCount++;\n\t\t}\n\t\tlineCount--;\n\t\tline = 0;\n\t}\n}", "static EXACT_COVER(sudoku) {\n sudoku.plain.forEach((cell, cellIndex) => {\n // skip if cell is already filled\n if (cell.value === 0) {\n const { row, col, block } = sudoku.getUnitsByPlainIndex(cellIndex);\n const rowCandidates = Sudoku_1.default.getDigitSet(row);\n const colCandidates = Sudoku_1.default.getDigitSet(col);\n const blockCandidates = Sudoku_1.default.getDigitSet(block);\n const candidates = cell.candidates.filter((candidate) => !rowCandidates.includes(candidate) &&\n !colCandidates.includes(candidate) &&\n !blockCandidates.includes(candidate));\n cell.candidates = candidates;\n }\n });\n return sudoku;\n }", "function clearBlock(){\n\tfor(var i = 0; i < 4; i++){\n\t\tif(currentBlock[i].x < 0 || currentBlock[i].y < 0){\n\t\t\tcontinue;\n\t\t}\n\t\tboardGui.rows[currentBlock[i].x].cells[currentBlock[i].y].style.backgroundColor = \"white\"; \n\t}\n}", "function clearSelectedRows() {\n var tblRows = contentTbl.fnGetNodes(),\n\t\ttblRow,\n\t\tnumRows = tblRows.length;\n for (var i = 0; i < numRows; i++) {\n\t\ttblRow = $(tblRows[i]);\n if ($(tblRow).hasClass('selected')) {\n $(tblRow).removeClass('selected');\n }\n }\n}", "function checkFullRow() {\n var fullRows = [];\n\n for (i = 0; i < 20; i++) {\n if (boardStatus[i].includes(0) === false) {\n console.log('Row ' + i + ' is completely full');\n fullRows.push(i);\n }\n }\n return fullRows;\n}", "function rowsChecker(puzzle){\n for(let i=0;i<9;i++){\n if(repeatsChecker(getRow(puzzle,i))===false){\n return false\n }\n }\n return true\n}", "randomFillEmptyColumnsNew() {\n for (var i = 0; i < this.width; ++i) {\n if (this.isColumnEmptyNew(i)) {\n this.tileSet.randomFillColumn(i);\n }\n }\n }", "clearGrid() {\n for (let row = 0; row < this.N; row++) {\n for (let column = 0; column < this.N; column++) {\n this.grid[row][column].element.remove();\n }\n }\n this.grid = null;\n\n this.width = 0;\n this.height = 0;\n this.N = 0;\n\n this.startTile = null;\n this.endTile = null;\n }", "isFull() {\r\n\t\treturn (this.emptyCells.size() == 0);\r\n\t}", "function isRightSideEmpty(col) {\n \tfor (var i = col + 1; i < $scope.columns; i++) {\n if ($scope.stars[$scope.rows - 1][i] > 0) {\n return false;\n }\n }\n \treturn true;\n }", "function firstColumnMatch(){\n\tif(isEmptyRow(\"square0\", \"square3\",\"square6\")){\n\t\tisEqual(\"#square0\", \"#square3\", \"#square6\");\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set size of the tabs container
function setSize(container) { var opts = $.data(container, 'tabs').options; var cc = $(container); if (opts.fit == true){ var p = cc.parent(); opts.width = p.width(); opts.height = p.height(); } cc.width(opts.width).height(opts.height); var header = $('>div.tabs-header', container); if ($.boxModel == true) { var delta = header.outerWidth() - header.width(); // var delta = header.outerWidth(true) - header.width(); header.width(cc.width() - delta); } else { header.width(cc.width()); } setScrollers(container); var panels = $('>div.tabs-panels', container); var height = opts.height; if (!isNaN(height)) { if ($.boxModel == true) { var delta = panels.outerHeight() - panels.height(); panels.css('height', (height - header.outerHeight() - delta) || 'auto'); } else { panels.css('height', height - header.outerHeight()); } } else { panels.height('auto'); } var width = opts.width; if (!isNaN(width)){ if ($.boxModel == true) { var delta = panels.outerWidth() - panels.width(); // var delta = panels.outerWidth(true) - panels.width(); panels.width(width - delta); } else { panels.width(width); } } else { panels.width('auto'); } if ($.parser){ $.parser.parse(container); } // // resize the children tabs container // $('div.tabs-container', container).tabs(); }
[ "resizeTabContents() {\n let change = $(`#pcm-tabbedPandas`).height() - this.tabNavHeight;\n if (change !== 0 && this.tabContentsHeight > 0) { $('#pcm-pandaTabContents .pcm-tabs').height(`${this.tabContentsHeight - change}px`); }\n if (MyPandaUI !== null) MyPandaUI.innerHeight = window.innerHeight;\n this.tabContentsHeight = $('#pcm-pandaTabContents .pcm-tabs:first').height(); this.tabNavHeight = $(`#pcm-tabbedPandas`).height();\n }", "resizePanels () {\n // Retrieve the current window height.\n const windowHeight = window.innerHeight\n\n // Retrieve the top position of the HTML Element containing all the tab\n // panels.\n const panelsTopPosition = this.get('panelsTopPosition')\n\n // Update the height of each panel.\n this.get('panels').each((index, panel) => {\n panel.style.height = (windowHeight - panelsTopPosition) + 'px'\n })\n }", "function fitWindowSize() {\n // fit mainContainer to body size\n document.getElementById(\"mainContainer\").style.height = $('body').height() - 41 + 'px';\n \n //alert($('body').height() + ' ' + document.getElementById('mainContainer').style.height);\n \n // refresh mainTabs\n $('#mainTabs').tabs('resize');\n \n // select the tab again to complete the resizing the tab\n var tab = $('#mainTabs').tabs('getSelected');\n $('#mainTabs').tabs('select', tab.panel('options').title);\n}", "function setupDimensions() {\n\t$('.opt').css('width', width/numtabs+'px');\n\t$('.sub').css('width', width+'px');\n\t$('.sub').css('overflow', 'hidden');\n\t$('.controlgroup').css('width', numtabs*width+'px');\n\t$('#camera').css('margin-top', '1px');\n\t$('#camera').css('margin-bottom', '2px');\n\t$('.controlgroup').css('margin-top', '1px');\n\t$('.controlgroup').css('margin-bottom', '2px');\n\t$('#topbar').height($('#back').height());\n\t$('#topbar').css('padding', 'auto auto auto 10px');\n\t$('#back').css('margin', 'auto 10px auto');\n\t$('#text').css('height', (height-4*($('#enter').height()+10)-($('#topbar').height()+6))+'px');\n\t$('#text').css('width', width*3/4-10+'px');\n\t$('#links').css('height', (height-4*($('#enter').height()+10)-($('#topbar').height()+6))+'px');\n\t$('#links').css('width', width/4-10+'px');\n\t$('.bottom_opt').css('width', width/5+'px');\n}", "function wrapTabs(container) { \n\t\t$(container).addClass('tabs-container'); \n\t\t$(container).wrapInner('<div class=\"tabs-panels\"/>'); \n\t\t$('<div class=\"tabs-header\">' \n\t\t\t\t+ '<div class=\"tabs-scroller-left\"></div>' \n\t\t\t\t+ '<div class=\"tabs-scroller-right\"></div>' \n\t\t\t\t+ '<div class=\"tabs-wrap\">' \n\t\t\t\t+ '<ul class=\"tabs\"></ul>' \n\t\t\t\t+ '</div>' \n\t\t\t\t+ '</div>').prependTo(container); \n\t\t \n\t\tvar header = $('>div.tabs-header', container); \n\t\t \n\t\t$('>div.tabs-panels>div', container).each(function(){ \n\t\t\tif (!$(this).attr('id')) { \n\t\t\t\t$(this).attr('id', 'gen-tabs-panel' + $.fn.tabs.defaults.idSeed++); \n\t\t\t} \n\t\t\t \n\t\t\tvar options = { \n\t\t\t\tid: $(this).attr('id'), \n\t\t\t\ttitle: $(this).attr('title'), \n\t\t\t\tcontent: null, \n\t\t\t\thref: $(this).attr('href'), \n\t\t\t\tclosable: $(this).attr('closable') == 'true', \n\t\t\t\ticon: $(this).attr('icon'), \n\t\t\t\tselected: $(this).attr('selected') == 'true', \n\t\t\t\tcache: $(this).attr('cache') == 'false' ? false : true \n\t\t\t}; \n\t\t\t$(this).attr('title',''); \n\t\t\tcreateTab(container, options); \n\t\t}); \n\t\t \n\t\t$('.tabs-scroller-left, .tabs-scroller-right', header).hover( \n\t\t\tfunction(){$(this).addClass('tabs-scroller-over');}, \n\t\t\tfunction(){$(this).removeClass('tabs-scroller-over');} \n\t\t); \n\t\t$(container).bind('_resize', function(){ \n\t\t\tvar opts = $.data(container, 'tabs').options; \n\t\t\tif (opts.fit == true){ \n\t\t\t\tsetSize(container); \n\t\t\t\tfitContent(container); \n\t\t\t} \n\t\t\treturn false; \n\t\t}); \n\t}", "function adjustSizes() {\n var selectHeight = poemList.length * 15;\n var newHeight = Math.max(350, selectHeight);\n selectBar.setSize(maxWidth, newHeight);\n $(selectBar.canvas).parent().height(\"350px\");\n $(\"poem\").height(maxHeight);\n}", "function i2uiSetTabFillerHeight(id)\r\n{\r\n var filler_obj = document.getElementById(id+\"_filler\");\r\n var tab_table_obj = document.getElementById(id);\r\n if (filler_obj != null && tab_table_obj != null)\r\n {\r\n var container_table_obj = tab_table_obj.parentNode;\r\n while (container_table_obj != null)\r\n {\r\n if (container_table_obj.tagName == 'TABLE')\r\n {\r\n break;\r\n }\r\n container_table_obj = container_table_obj.parentNode;\r\n }\r\n if (container_table_obj != null &&\r\n tab_table_obj != null)\r\n {\r\n //i2uitrace(1,\"container height=\"+container_table_obj.offsetHeight);\r\n //i2uitrace(1,\"tab height=\"+tab_table_obj.offsetHeight);\r\n filler_obj.style.height = container_table_obj.offsetHeight -\r\n tab_table_obj.offsetHeight;\r\n }\r\n }\r\n}", "function setLandingSize() {\r\n\tappContainer_Ls.css({\r\n\t\t'width' : appContainerWidth_Ls,\r\n\t\t'height' : appContainerHeight_Ls,\r\n\t\t'margin-top': appContainer_marginTop_Ls\r\n\t});\r\n}", "_tabStyle() {\n this.$containerEl.find('.te-md-container').removeClass('te-preview-style-vertical');\n this.$containerEl.find('.te-md-container').addClass('te-preview-style-tab');\n }", "function initTabbar() {\n _debug();\n if ($('#tabbar').length) {\n _debug(' #tabbar exists');\n\n // Find current class or 1st page in #jqt & the last stylesheet\n var firstPageID = '#' + ($('#jqt > .current').length === 0 ? $('#jqt > *:first') : $('#jqt > .current:first')).attr('id'),\n sheet = d.styleSheets[d.styleSheets.length - 1];\n\n // Make sure that the tabbar is not visible while its being built\n $('#tabbar').hide();\n $('#tabbar div:first').height($('#tabbar').height());\n _debug(' #tabbar height = ' + $('#tabbar').height() + 'px');\n $('#tabbar a').each(function (index) {\n var $me = $(this),\n mask2x = $me.attr('mask2x'),\n tabIcon = $me.attr('mask'),\n tabZoom = 1,\n parseJS = function(input) {return input.replace(/(\\r\\n|\\n|\\r)/gm,' ').replace(/\\s+/g,' ').replace(/^javascript:\\s*/i,'').replace(/return\\s*[\\(]*\\s*false\\s*[\\)]*[;]*$|return\\s*[\\(]*\\s*true\\s*[\\)]*[;]*$/i,'');};\n\n // PhoneGap integration\n if (typeof (PhoneGap) !== 'undefined' && jQT.barsSettings.phonegap) {\n $('body > #tabbar').css({\n bottom: '20px !important'\n });\n }\n\n // Enummerate the tabbar anchor tags\n $me.attr('id', 'tab_' + index);\n\n // If this is the button for the page with the current class then enable it\n if ($me.attr('href') === firstPageID) {\n $me.addClass('enabled');\n }\n\n // Create css masks from the anchor's mask property\n if (window.devicePixelRatio && window.devicePixelRatio === 2 && typeof (mask2x) !== 'undefined') {\n tabIcon = $(this).attr('mask2x');\n tabZoom = 0.5;\n }\n sheet.insertRule('a#tab_' + index + '::after, a#tab_' + index + '::before {-webkit-mask-image:url(\\'' + tabIcon + '\\');' + ' zoom: ' + tabZoom + ';}', sheet.cssRules.length);\n\n // Put page animation, if any, into data('animation')\n $me.data('animation', $me.attr('animation'));\n\n // Action code or url in href attribute\n if (typeof ($me.attr('href')) !== 'undefined' && $me.attr('href') !== null) {\n if ($me.attr('href').match(/^javascript:\\s*/i) !== null) {\n // Put action code into data('action')...\n $me.data('action', parseJS($me.attr('href')));\n $me.addClass('action');\n } else {\n // Put href target into data('defaultTarget')...\n $me.data('defaultTarget', $me.attr('href'));\n }\n // ...and remove href\n $me.removeAttr('href');\n }\n\n // Action code in onClick event\n if (typeof ($me.attr('onClick')) !== 'undefined' && $me.attr('onClick') !== null) {\n $me.data('action', parseJS($me.attr('onClick')));\n $me.removeAttr('onclick');\n if (typeof ($me.data('defaultTarget')) === 'undefined' || $me.data('defaultTarget') === null) {\n $me.addClass('action');\n }\n }\n\n // Tabbar tap event\n // Action\n if (typeof ($me.data('action')) !== 'undefined' && $me.data('action') !== null) {\n $me.click(function () {\n setTimeout($me.data('action'), 0);\n });\n }\n\n // Navigation\n if (typeof ($me.data('defaultTarget')) !== 'undefined' && $me.data('defaultTarget') !== null) {\n $me.click(function () {\n var $referrerTab = $('#tabbar .enabled'),\n $tabs = $('#tabbar a'),\n $targetTab = $(this),\n animation = animations.indexOf(':' + $me.data('animation') + ':') > -1 ? $me.data('animation') : '',\n i,\n referrerAnimation = animations.indexOf(':' + $referrerTab.data('animation') + ':') > -1 ? $referrerTab.data('animation') : '',\n referrerPage = $referrerTab.data('defaultTarget'),\n target = $me.data('defaultTarget'),\n targetAnimation = animations.indexOf(':' + $targetTab.data('animation') + ':') > -1 ? $targetTab.data('animation') : '',\n targetHist = $targetTab.data('hist'),\n targetPage = $targetTab.data('defaultTarget'),\n thisTab,\n TARDIS = function (anime) {\n var DW;\n if (anime.indexOf('left') > 0) {\n DW = anime.replace(/left/, 'right');\n } else if (anime.indexOf('right') > 0) {\n DW = anime.replace(/right/, 'left');\n } else if (anime.indexOf('up') > 0) {\n DW = anime.replace(/up/, 'down');\n } else if (anime.indexOf('down') > 0) {\n DW = anime.replace(/down/, 'up');\n } else {\n DW = anime;\n }\n return DW;\n };\n\n if (!$targetTab.hasClass('enabled')) {\n for (i = $('#tabbar a').length - 1; i >= 0; --i) {\n thisTab = $tabs.eq(i);\n thisTab.toggleClass('enabled', ($targetTab.get(0) === thisTab.get(0)));\n if ($targetTab.get(0) === thisTab.get(0)) {\n jQT.goTo(target, (targetAnimation === '' ? TARDIS(referrerAnimation) : targetAnimation));\n _debug('tabbbar touch, new tab');\n setPageHeight();\n }\n }\n } else {\n jQT.goTo(target);\n _debug('tabbar touch, same tab');\n setPageHeight();\n }\n });\n }\n });\n\n // Hide tabbar when page has a form or any form element or .hide_tabbar class except when the page's parent div has the .keep_tabbar class.\n // Show tabbar when leaving a form or .hide_tabbar page except when going into a page with a form or .hide_tabbar class\n $('#jqt > div, #jqt > form').each(function () {\n $(this).bind('pageAnimationStart', function (e, data) {\n var $target = $(e.target),\n isForm = function ($page) {\n return $page.has('button, datalist, fieldset, form, keygen, label, legend, meter, optgroup, option, output, progress, select, textarea').length > 0 && !($(':input', $page).length !== $(':input:hidden', $page).length);\n },\n isHide = function ($page) {\n return $page.hasClass('hide_tabbar') || $page.children().hasClass('hide_tabbar');\n },\n isKeep = function ($page) {\n return $page.hasClass('keep_tabbar') || $page.children().hasClass('keep_tabbar');\n };\n\n if (data.direction === 'in') {\n if ((!isForm($target) && !isHide($target)) || isKeep($target)) {\n $('#tabbar').show(function () {\n _debug('Show tabbar');\n setPageHeight();\n });\n } else {\n $('#tabbar').hide(function () {\n _debug('Hide tabbar');\n setPageHeight();\n });\n }\n }\n });\n });\n\n // Resize tabbar & scroll to enabled tab on rotation\n $('#jqt').bind('turn', function (e, data) {\n var $tabbar = $('#tabbar'),\n scroll = $tabbar.data('iscroll');\n if (scroll !== null && typeof (scroll) !== 'undefined') {\n setTimeout(function () {\n $tabbar.width = win.innerWidth;\n if ($('.enabled').offset().left + $('.enabled').width() >= win.innerWidth) {\n scroll.scrollToElement('#' + $('.enabled').attr('id'), 0);\n }\n }, 0);\n }\n });\n\n // Show tabbar now that it's been built, maybe\n if (!$('.current').hasClass('hide_tabbar')) {\n $('#tabbar').show(0, function () {\n _debug('initTabbar hide tabbar');\n setPageHeight();\n setBarWidth();\n });\n } else {\n _debug('initTabbar show tabbar');\n setPageHeight();\n setBarWidth();\n }\n }\n }", "function setScrollers(container) { \n\t\tvar header = $('>div.tabs-header', container); \n\t\tvar tabsWidth = 0; \n\t\t$('ul.tabs li', header).each(function(){ \n\t\t\ttabsWidth += $(this).outerWidth(true); \n\t\t}); \n\t\t \n\t\tif (tabsWidth > header.width()) { \n\t\t\t$('.tabs-scroller-left', header).css('display', 'block'); \n\t\t\t$('.tabs-scroller-right', header).css('display', 'block'); \n\t\t\t$('.tabs-wrap', header).addClass('tabs-scrolling'); \n\t\t\t \n\t\t\tif ($.boxModel == true) { \n\t\t\t\t$('.tabs-wrap', header).css('left',2); \n\t\t\t} else { \n\t\t\t\t$('.tabs-wrap', header).css('left',0); \n\t\t\t} \n\t\t\tvar width = header.width() \n\t\t\t\t- $('.tabs-scroller-left', header).outerWidth() \n\t\t\t\t- $('.tabs-scroller-right', header).outerWidth(); \n\t\t\t$('.tabs-wrap', header).width(width); \n\t\t\t \n\t\t} else { \n\t\t\t$('.tabs-scroller-left', header).css('display', 'none'); \n\t\t\t$('.tabs-scroller-right', header).css('display', 'none'); \n\t\t\t$('.tabs-wrap', header).removeClass('tabs-scrolling').scrollLeft(0); \n\t\t\t$('.tabs-wrap', header).width(header.width()); \n\t\t\t$('.tabs-wrap', header).css('left',0); \n\t\t\t \n\t\t} \n\t}", "function airsliderSetSlidesEditingAreaSizes() {\n var width = parseInt($('.air-admin #air-slider-settings .air-slider-settings-list #air-slider-startWidth').val());\n var height = parseInt($('.air-admin #air-slider-settings .air-slider-settings-list #air-slider-startHeight').val());\n\n $('.air-admin #air-slides .air-slide .air-slide-editing-area').css({\n 'width' : width,\n 'height' : height,\n });\n\n// $('.air-admin').css({\n// 'width' : width,\n// });\n }", "function removePostTabBarWidth()\r\n{\r\n $('.postTabUIFixed').css('width', '');\r\n}", "function wrapTabs(container) {\n\t\t$(container).addClass('tabs-container');\n\t\t$(container).wrapInner('<div class=\"tabs-panels\"/>');\n\t\t$('<div class=\"tabs-header\">' + '<div class=\"tabs-scroller-left\"><div class=\"faceIcon icon-arrow2_left left-arrow\"></div></div>' + '<div class=\"tabs-scroller-right\"><div class=\"faceIcon icon-arrow2_right right-arrow\"></div></div>' + '<div class=\"tabs-wrap\">' + '<ul class=\"tabs\"></ul>' + '</div>' + '</div>').prependTo(container);\n\n\t\tvar header = $('>div.tabs-header', container);\n\n\t\t$('>div.tabs-panels>div', container).each(function () {\n\t\t\tif (!$(this).attr('id')) {\n\t\t\t\t$(this).attr('id', 'gen-tabs-panel' + $.fn.tauitabs.defaults.idSeed++);\n\t\t\t}\n\n\t\t\tvar options = {\n\t\t\t\tid: $(this).attr('id'),\n\t\t\t\ttitle: $(this).attr('title'),\n\t\t\t\tcontent: null,\n\t\t\t\thref: $(this).attr('href'),\n\t\t\t\tclosable: $(this).attr('closable') == 'true',\n\t\t\t\ticon: $(this).attr('icon'),\n\t\t\t\tselected: $(this).attr('selected') !== undefined,\n\t\t\t\tcache: $(this).attr('cache') == 'false' ? false : true,\n\t\t\t\tenable: $(this).attr('enable') == 'false' ? false : true\n\t\t\t};\n\t\t\t$(this).attr('title', '');\n\t\t\tcreateTab(container, options);\n\t\t});\n\n\t\t$('.tabs-scroller-left, .tabs-scroller-right', header).hover(function () {\n\t\t\t$(this).addClass('tabs-scroller-over');\n\t\t}, function () {\n\t\t\t$(this).removeClass('tabs-scroller-over');\n\t\t}).mousedown(function () {\n\t\t\t$(this).addClass('tabs-scroller-mousedown');\n\t\t}).mouseup(function () {\n\t\t\t$(this).removeClass('tabs-scroller-mousedown');\n\t\t});\n\t}", "function SetNextWindowContentSize(size) {\r\n bind.SetNextWindowContentSize(size);\r\n }", "function setFullSize() {\r\n\tappContainer_Fs.css({\r\n\t\t'width' : appContainerWidth_Fs,\r\n\t\t'height' : appContainerHeight_Fs,\r\n\t\t'margin-top': appContainer_marginTop_Fs\r\n\t});\r\n\tappContent.css({\r\n\t\t'width' : appContentWidth,\r\n\t\t'height' : appContentHeight,\r\n\t});\t\r\n}", "function _jsTabControl_draw() {\n\n\t//calculate tabsperstrip\n\tthis.tabsPerStrip = parseInt((window.innerWidth - IMG_BTN_MORE.width - IMG_BTN_LESS.width) / this.tabWidth);\n\n\t//calculate number of strips needed\n\tvar numStrips = Math.ceil(this.tabs.length / this.tabsPerStrip);\n\t\n\t//draw each strip\n\tfor (i=0; i < numStrips; i++)\n\t\tthis.createStrip(0 + (this.tabsPerStrip * i), this.tabsPerStrip + (this.tabsPerStrip * i));\n\n}", "function setScrollers(container) {\n\t\tvar header = $('>div.tabs-header', container);\n\n\t\tvar tabsWidth = 0;\n\t\t$('ul.tabs li', header).each(function () {\n\t\t\ttabsWidth += $(this).outerWidth(true);\n\t\t});\n\t\tif (tabsWidth > header.width()) {\n\t\t\t$('.tabs-scroller-left', header).css('display', 'block');\n\t\t\t$('.tabs-scroller-right', header).css('display', 'block');\n\t\t\t$('.tabs-wrap', header).addClass('tabs-scrolling');\n\n\t\t\t//\t\t\tif ($.boxModel == true) {\n\t\t\t//\t\t\t\t$('.tabs-wrap', header).css('left',2);\n\t\t\t//\t\t\t} else {\n\t\t\t//\t\t\t\t$('.tabs-wrap', header).css('left',0);\n\t\t\t//\t\t\t}\n\t\t\t//\t\t\tvar width = header.width()\n\t\t\t//\t\t\t\t- $('.tabs-scroller-left', header).outerWidth()\n\t\t\t//\t\t\t\t- $('.tabs-scroller-right', header).outerWidth();\n\t\t\t//\t\t\t$('.tabs-wrap', header).width(width);\n\t\t\t//\n\t\t\t//\t\t} else {\n\t\t\t//\t\t\t$('.tabs-scroller-left', header).css('display', 'none');\n\t\t\t//\t\t\t$('.tabs-scroller-right', header).css('display', 'none');\n\t\t\t//\t\t\t$('.tabs-wrap', header).removeClass('tabs-scrolling').scrollLeft(0);\n\t\t\t//\t\t\t$('.tabs-wrap', header).width(header.width());\n\t\t\t//\t\t\t$('.tabs-wrap', header).css('left',0);\n\t\t\t//\n\t\t} else {\n\t\t\t$('.tabs-scroller-left', header).css('display', 'none');\n\t\t\t$('.tabs-scroller-right', header).css('display', 'none');\n\t\t\t$('.tabs-wrap', header).removeClass('tabs-scrolling');\n\t\t}\n\t}", "function adjustFrameContainerSizes () {\n\t\tvar windowHeight = $(window).height();\n\t\tvar windowWidth = $(window).width();\n\t\tvar maxSidePanelWidth = 300;\n\t\tvar maxBottomPanelHeight = 270;\n\n\t\tvar sidePanelWidth = (windowWidth * .3);\n\t\tsidePanelWidth = (sidePanelWidth > maxSidePanelWidth) ? maxSidePanelWidth : sidePanelWidth;\n\n\t\tvar midPanelWidth = windowWidth - sidePanelWidth;\n\n\t\tvar bottomPanelHeight = (windowHeight * .25);\n\t\t//console.log('bottomPanelHeight='+bottomPanelHeight);\n\t\tbottomPanelHeight = (bottomPanelHeight > maxBottomPanelHeight) ? maxBottomPanelHeight : bottomPanelHeight;\n\t\t//console.log('bottomPanelHeight='+bottomPanelHeight);\n\t\tvar midPanelHeight = windowHeight - bottomPanelHeight;\n\n\t\t$('#midPanelContainer').css({\n\t\t\t'height' : midPanelHeight + 'px',\n\t\t\t'width' : midPanelWidth + 'px'\n\t\t});\n\n\t\t$('#bottomPanelContainer').css({\n\t\t\t'height' : bottomPanelHeight + 'px',\n\t\t\t'width' : midPanelWidth + 'px'\n\t\t});\n\n\t\t$('#rightPanelContainer').css({\n\t\t\t'width' : sidePanelWidth + 'px'\n\t\t});\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CINDEX[] Copy the INDEXed element to the top of the stack 0x25
function CINDEX(state) { var stack = state.stack; var k = stack.pop(); if (exports.DEBUG) { console.log(state.step, 'CINDEX[]', k); } // In case of k == 1, it copies the last element after popping // thus stack.length - k. stack.push(stack[stack.length - k]); }
[ "getVariable(index) {\n const depth = this.getLocalDepth(index); // depth of the local in the stack.\n const memoryOffset = this.getMemoryOffset(depth); // actual depth in BF memory.\n const size = this.sizeOfVal(index); // how many byes to copy.\n const type = this.typeOfVal(index);\n\n for (let i = 0; i < size; i++) {\n this.copyByte(memoryOffset, true);\n }\n\n this.stack.push(StackEntry(type, size));\n }", "function IndexedIndirect()\n\t{\n\t\tvar ZeroPageIndex = ReadByte(PC + 1);\n\t\tvar Low = ReadByte((ZeroPageIndex + X) & 0xFF);\n\t\tvar High = ReadByte((ZeroPageIndex + X + 1) & 0xFF);\n\t\tTempAddress = (High << 8) | Low;\n\t\tPC += 2;\n\t\tCycles = 5;\n\t}", "createTargetInArray(nums, indexs) {\n let arr = [];\n for (const i in nums) {\n const before = arr.slice(0, indexs[i]);\n before[indexs[i]] = nums[i];\n arr = before.concat(...arr.slice(indexs[i]));\n }\n return arr;\n }", "indexedIndirect() {\n this.incrementPc();\n let zeroPageAddress = (this.ram[this.cpu.pc] + this.cpu.xr) & 0xff\n let lo = this.ram[zeroPageAddress] & 0xff\n let hi = this.ram[zeroPageAddress + 1] & 0xff\n\n return (hi * 0x0100 + lo) & 0xffff\n }", "function getCloneElement(arr, index) {\n return Object.assign({}, arr[index]);\n}", "function ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}", "visitCoalesce_index_partition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitIndex_expr(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "assignIndex(hash) {\n return hash % this.array.length;\n }", "visitAlter_index(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "resetIndex() {\n this._offset = 0;\n }", "function rebuilding(arr, index1, index2) {\n var newArr = arr.map(function (value) { return value });\n var arg = Array.prototype.slice.call(arguments, 1);\n for (var i=0; i< arr.length; i++){\n newArr[i] = arr[arg[i]];\n }\n return newArr;\n}", "function adjustProjectIndex(index) {\n \n if ( index < 0 ) {\n index = projects.length - 1;\n } else if ( index === projects.length ) {\n index = 0;\n }\n\n return index;\n}", "function trx_addons_options_clone_replace_index(name, idx_new) {\n\t\t\tname = name.replace(/\\[\\d\\]/, '['+idx_new+']');\n\t\t\treturn name;\n\t\t}", "function _registerIndex() {\n if (angular.isUndefined(lumx.parentController)) {\n return;\n }\n\n lumx.parentController.activeItemIndex = $element.index(`.${CSS_PREFIX}-list-item`);\n }", "function initCharCodeToOptimizedIndexMap() {\n if ((0, utils_1.isEmpty)(charCodeToOptimizedIdxMap)) {\n charCodeToOptimizedIdxMap = new Array(65536);\n for (var i = 0; i < 65536; i++) {\n /* tslint:disable */\n charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i;\n /* tslint:enable */\n }\n }\n}", "offsetOf(variable, index) {\n const slot = this.getLocalDepth(variable);\n const depth = this.getMemoryOffset(slot);\n const size = this.sizeOfVal(variable);\n\n if (this.stackTop().size != 1) {\n this.error(\n \"Cannot assign value larger than 1 byte to bus or string index.\"\n );\n } else if (size != 1) {\n this.error(\"cannot index a variable that is not a bus or string.\");\n }\n\n return depth + index + 2; // account for 2 bytes of padding prior.\n }", "visitNew_index_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "get(index){\n // return the value of an element at given index\n return memory.get(index);\n }", "function getBankAtIndex(inIdx) {\n\tlogInfo('Selected bank at index: ' + inIdx);\n\tgBankInfoSelected = objJSON.rows[inIdx].CODE + \"#\" + objJSON.rows[inIdx].SHORT_NAME + \"#\" + objJSON.rows[inIdx].NAME_VN\n\t\t+ \"#\" + objJSON.rows[inIdx].NAME_EN ; //save bank info raw data\n\tnavController.pushToView(\"corp/transfer/trans-input-city\", true);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
oddsSmallerThan(n): receives a number n returns the number of ODD numbers smaller than n e.g. oddsSmallerThan(7) > 3 oddsSmallerThan(15) > 7
function oddsSmallerThan(n) { // Your code here return parseInt(n /2) }
[ "function randomOddSmallers (limit, min, max) {\n function getRandomInt (min, max) {\n min = Math.ceil(min)\n max = Math.floor(max)\n return Math.floor(Math.random() * (max - min + 1)) + min\n }\n var random = getRandomInt(min, max)\n if (random > 40) {\n limit = (limit % 2 === 0) ? (limit + 1) : limit\n for (var i = limit; i <= random; i += 2) console.log(i)\n } else {\n for (var j = limit; j >= random; j--) console.log(j)\n }\n}", "function iqTest(numbers) {\n const inputArray = numbers.split(' ');\n const even = [];\n const odd = []\n\n inputArray.map((elm) => elm % 2 == 0 ? even.push(elm) : odd.push(elm));\n\n return inputArray.indexOf(even.length > odd.length ? odd[0] : even[0]) + 1;\n}", "function findPrimesLessThanOrEqualTo(n) {\n /**\n No primes less than or equal to 2\n **/\n if(n < 2) {\n return [];\n }\n \n /**\n Segmented Sieve:\n 1. Divide the number into segments of length sqrt(n).\n 2. Find primes in first segment using Sieve of Eratosthenes\n 3. For each of the other segments, \n a. Cross off multiples of using primes found so far.\n b. The numbers not crossed off yet are primes, add them to the primes list.\n **/\n const \n delta = Math.floor(Math.sqrt(n)),\n primes = findPrimesBySieve(delta);\n \n let m = delta;\n \n /**\n `m` is the start of the segment.\n Carry on while `m` is less than or equal to given number.\n **/\n while(m <= n) {\n /**\n Find primes between m to m+delta, excluding m.\n **/\n primes.push(...findPrimesBetween(m, Math.min(m+delta, n), primes));\n m+=delta;\n }\n return primes;\n}", "function printOdds(n) { \n if(n%2 != 0)\n console.log(n)\n if(n == 0) return;\n\n printOdds(n-1)\n}", "function oddeven(arr) {\n\treturn arr.filter(x => x % 2 === 0).length * 2 < arr.length;\n}", "function randomPositiveOddNumber() {\n var randomNumber = getRandomIntInclusive(1,1000);\n if(randomNumber % 2 === 0) {\n return randomPositiveOddNumber();\n }\n\n return randomNumber;\n}", "function threeOdds(number1, number2) {\n var count = 0;\n for (i = number1 + 1; i < number2; i++) {\n if (i % 2 !== 0) {\n count++\n }\n }\n if (count > 2) {\n return true;\n } else {\n return false\n }\n}", "function isOdd(n) {if(!isNaN(n)){return n % 2 !== 0}}", "function getNthUglyNo(n)\n {\n return findUgly(n, 1, 1);\n }", "function smallerNubmer(n1, n2, n3) {\n if (n1 < n2 && n1 < n3) {\n return n1;\n } else if (n2 < n1 && n2 < n3) {\n return n2;\n\n } else {\n return n3;\n }\n\n}", "function numberOfWaysToMakeChange(n, denoms) {\n const dp = new Array(n + 1).fill(0);\n dp[0] = 1;\n\n for (const denom of denoms) {\n for (let amount = 1; amount < n + 1; amount++) {\n if (amount >= denom) dp[amount] += dp[amount - denom];\n console.log({denom, amount, dp});\n }\n }\n\n return dp[n];\n}", "function logAtMost5(n) {\n for (let i = 0; i <= Math.min(5, n); i ++){\n // O(1)\n console.log(i)\n }\n}", "function featured(number) {\n if (number > 9876543200) return false;\n let count = number + 1;\n\n\n while(true) {\n if (isOdd(count) && isMultipleOfSeven(count) && isUnique(count)) {\n return count;\n }\n count += 1;\n }\n}", "function usAndNumberBeetweenUs(n1,n2){\n\tif(n1<n2){\n\tvar arr=[];\n\tarr.push(n1);\n\tarr.push(n2);\n\n\tarr.reduce(function (x,y){\n\t for(i=n1;i<n2;i++){\n\t\tif(x<n2){\n\t\t\tarr.push(++x);\n\n\t\t}\n\t\t}\t\n\n\t})\n\tarr.shift();\n\tarr.shift();\n\tarr.unshift(n1);\n}\nif(n1>n2){\n\tvar arr=[];\n\tarr.push(n1);\n\tarr.push(n2);\n\n\tarr.reduce(function (x,y){\n\t for(i=n1;i>n2;i--){\n\t\tif(x>n2){\n\t\t\tarr.push(--x);\n\n\t\t}\n\t\t}\t\n\n\t})\n\tarr.shift();\n\tarr.shift();\n\tarr.unshift(n1);\n}\nreturn arr;\n}", "function multiples(n) {\n var sum = 0;\n for (var i = 0; i < n; i++) {\n if (i%5 === 0 || i%7 === 0) {\n sum = sum + i;\n }\n }\n return sum;\n}", "function evensAndOdds(arr) {\n var evens = 0;\n var odds = 0;\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 === 0) {\n odds = 0;\n evens++;\n if (evens === 3) {\n console.log(\"Even more so!\");\n evens = 0;\n }\n } else {\n evens = 0;\n odds ++;\n if (odds === 3) {\n console.log(\"That's odd!\")\n odds = 0;\n }\n }\n }\n}", "function sumOdds() {\n let n = parseInt(document.getElementById('integer').value);\n let i = 1;\n let sum = 0;\n while (i <= n) {\n sum += i\n i += 2;\n }\n document.getElementById('output').innerHTML = sum;\n}", "function getLeastCoins(n) {\n const coins = [25, 10, 5, 1];\n let res = [];\n\n let remain = n;\n for ( let c = 0; c < coins.length; c++) {\n let quotient = Math.floor(remain / coins[c]);\n remain = remain - quotient * coins[c];\n\n res.push(quotient);\n }\n\n let count = 0;\n for (let i = 0; i < 4; i++) {\n count += res[i];\n }\n\n console.log(res);\n return count;\n}", "function smallestCommons(arr) {\n\n const [min, max] = arr.sort((a, b) => a - b);\n const numberDivisors = max - min + 1;\n\n let upperBound = 1;\n for (let i = min; i <= max; i++) {\n upperBound *= i;\n }\n\n for (let multiple = max; multiple <= upperBound; multiple += max) {\n\n let divisorCount = 0;\n for (let i = min; i <= max; i++) {\n\n if (multiple % i === 0) {\n divisorCount += 1;\n }\n }\n if (divisorCount === numberDivisors) {\n return multiple;\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a image path imgPath, return [ name, ext ].
function pathToNameExt(imgPath) { const typeDelimIndex = imgPath.lastIndexOf(TYPE_DELIM); const ext = imgPath.substr(typeDelimIndex + 1); const name = path.basename(imgPath.substr(0, typeDelimIndex)); return [name, ext]; }
[ "function GetImageExtension(image) {\n var partsOfImageName = image.name.split(\".\");\n var extension = (partsOfImageName.length > 1) ? partsOfImageName[partsOfImageName.length - 1] : \"jpg\";\n return extension;\n}", "function productNameFromImagePath(imagePath) {\n\t// This is the full filename, ex:\n\t// \"Box1_$10.png\"\n\tvar imageFileName = imagePath.match(/[\\w\\$]+\\.\\w+/)[0];\n\n\t// This is the filename without the extension, ex:\n\t// \"Box1_$10\"\n\timageFileName = imageFileName.split('.')[0];\n\n\t// This is the product name, ex:\n\t// \"Box1\"\n\tvar productName = imageFileName.split('_')[0];\n\n\treturn productName;\n}", "function findIMG(desc){\n\tvar indexJPG = desc.indexOf('.jpg');\n\tvar imageUrl;\n\tif (indexJPG === -1) {\n\t\t// if no .jpg is found, finds the first .png\n\t\timageUrl = findPNG(desc);\n\t\treturn imageUrl;\n\t} else {\n\t\tvar descUntilFirstJPG = desc.substring(0, indexJPG);\n\t\tvar indexHTTP = descUntilFirstJPG.lastIndexOf('http');\n\t\tif (indexHTTP === -1) {\n\t\t\timageUrl = '../img/EarthInHand.jpg';\n\t\t\treturn imageUrl;\n\t\t}\n\t\timageUrl = desc.substring(indexHTTP, indexJPG + 4);\n\t\t\n\t\treturn imageUrl;\n\t}\n}", "function extractFilename(path){\n let path_array = path.split('\\\\');\n let last_index = path_array.length - 1;\n return path_array[last_index].replace(/\\-/g, '_');\n}", "function getImagePath(source){\n\tvar urlPath = url.parse(source).path;\n\tvar lastPath = _.last(urlPath.split(\"/\"));\n\tvar savePath = ORGINAL_IMAGE_PATH + lastPath;\n\treturn savePath;\n}", "function getImg(name){\r\n\tlet myList = readFile(\"Members\", name);\r\n\tlet json = myList;\r\n\tfor(let i = 0; i < json.length; i++){\r\n\t\tif(!json[i].endsWith(\".txt\")){\r\n\t\t\treturn json[i];\r\n\t\t}\r\n\t}\r\n\treturn \"none\";\r\n}", "function productPriceFromImagePath(imagePath) {\n\t// This is the full filename, ex:\n\t// \"Box1_$10.png\"\n\tvar imageFileName = imagePath.match(/[\\w\\$]+\\.\\w+/)[0];\n\n\t// This is the filename without the extension, ex:\n\t// \"Box1_$10\"\n\timageFileName = imageFileName.split('.')[0];\n\n\t// This is the price of the product, ex: 10\n\tvar productPrice = Number(imageFileName.split('_')[1].substring(1));\n\n\treturn productPrice;\n}", "function getExt(filename) {\n if (!filename) return \"\";\n var parts = filename.split(\".\");\n if (parts.length === 1 || (parts[0] === \"\" && parts.length === 2)) return \"\";\n return parts.pop().toLowerCase();\n }", "function get_img(i,f){var b,a=__CONF__.img_url+\"/img_new/{0}--{1}-{2}-1\",g=__CONF__.img_url+\"/img_src/{0}\",c=\"d96a3fdeaf68d3e8db170ad5\",d=\"43e2e6f41e3b3ebe22aa6560\",k=\"726a17bd880cff1fb375718c\",j=\"6ea1ff46aab3a42c975dd7ab\";i=i||\"0\";f=f||{};ObjectH.mix(f,{type:\"head\",w:30,h:30,sex:1});if(i!=\"0\"){if(f.type==\"src\"){b=g.format(i);}else{b=a.format(i,f.w,f.h);}}else{if(f.type==\"head\"){if(f.sex==1){b=a.format(c,f.w,f.h);}else{b=a.format(d,f.w,f.h);}}else{if(f.type==\"subject\"){b=a.format(k,f.w,f.h);}else{if(f.type==\"place\"){b=a.format(j,f.w,f.h);}else{b=a.format(\"0\",f.w,f.h);}}}}return b;}", "function getExtension(fileBlob) {\r\n\r\n // string separated by <file description>/<extension>\r\n var contentType = fileBlob.getContentType()\r\n var parsed_content = contentType.split(\"/\")\r\n var extension = parsed_content[1]\r\n \r\n return extension\r\n}", "function getImageDimensions(path) {\r\n // NOTE: Uses a hidden \"img\" element defined in \"main.xml\".\r\n imgSizer.src = path;\r\n\r\n return [imgSizer.srcWidth, imgSizer.srcHeight];\r\n}", "static matchFilename(descs, filename) {\n for (let d of descs)\n if (d.filename && d.filename.test(filename)) return d\n let ext = /\\.([^.]+)$/.exec(filename)\n if (ext)\n for (let d of descs) if (d.extensions.indexOf(ext[1]) > -1) return d\n return null\n }", "function extensionSorter(fileArray){\n var videoArray = [];\n var imageArray = [];\n var videoExt = ['mov', 'mp4', 'avi', 'gif'];\n for (let i = 0; i < fileArray.length; i++) {\n const element = fileArray[i];\n // console.log(element);\n // how do we read the extension of each element in javascript?\n // input => pavans_first_birthday.mov\n // output => .mov\n \n var extension = element.split(\".\")[1];\n // console.log(\"EXTENSION: \", extension);\n // input => mov\n // output => videoArray [\"mov\"]\n if(videoExt.indexOf(extension) !== -1){\n if(videoArray.indexOf(extension) === -1){\n videoArray.push(extension);\n }\n }else{\n imageArray.push(extension);\n }\n }\n console.log(\"VIDEO EXT: \", videoArray)\n console.log(\"IMG EXT: \", imageArray)\n\n}", "function getURLs(imageFile) {\n var full = path.join('images', querystring.escape(imageFile));\n var thumb = path.join('thumbnails', querystring.escape(imageFile));\n return { thumbnail: thumb,\n fullsize: full };\n}", "function getCurrentImages () {\n\t\treturn Array.from(document.getElementsByClassName('img')).map(function(target){\n\t\t\treturn getImgExtension(target);\n\t\t});\n\t}", "function reworkVendorImage(url) {\n if (/(.png|.gif|.jpg|.jpeg|.svg)/.test(url)) {\n return '../images/' + path.basename(url);\n }\n return url;\n}", "function getImg(arr) {\n const elementArr = [];\n for (const element of arr) {\n if (element.match('<img[^>]+src\\\\s*=\\\\s*[\\'\"]([^\\'\"]+)[\\'\"][^>]*>')) {\n elementArr.push(element.split('\"')[1]);\n }\n }\n elementArr.length = 10;\n return elementArr;\n}", "function filesNamesFromXform(xform) {\n var fileNames = [];\n\n traverse(xform).forEach(function (value) {\n var match = RE_MEDIA_FILE.exec(value);\n\n if (match) {\n fileNames.push(match[0]);\n }\n });\n\n return fileNames;\n}", "function findPNG(desc){\n\tvar indexPNG = desc.indexOf('.png');\n\tvar imageUrl;\n\tif (indexPNG === -1) {\n\t\timageUrl = '../img/EarthInHand.jpg';\n\t\treturn imageUrl;\n\t} else {\n\t\tvar descUntilFirstPNG = desc.substring(0, indexPNG);\n\t\tvar indexHTTP = descUntilFirstPNG.lastIndexOf('http');\n\t\t\n\t\tif (indexHTTP === -1) {\n\t\t\t// if no .png is found returns default image\n\t\t\timageUrl = '../img/EarthInHand.jpg';\n\t\t\treturn imageUrl;\n\t\t\n\t\t} else {\n\t\t\t// if .png is found checks whether it is social network icon\n\t\t\timageUrl = desc.substring(indexHTTP, indexPNG + 4);\n\t\t\tvar social = findSocial(imageUrl);\n\t\t\tif (social === true) {\n\t\t\t\timageUrl = '../img/EarthInHand.jpg';\n\t\t\t} else {\n\t\t\t\treturn imageUrl;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn imageUrl;\n\t}\n}", "function importAll(r) {\n var images = [];\n r.keys().map((item) => \n { \n var src = item.replace('./',''); // DRY stuff\n images.push(\n {\n src: src, // E.g. Glasses/glasses1.png\n img: r(item), // The image\n type: src.substr(0,src.indexOf('/')), // e.g. Glasses\n fileName: src.substr(src.indexOf('/')+1,src.length) // E.g. glasses1.png\n }); \n });\n return images;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Responding to the dropdown. The displayed list will contain the queues with the same businessdomain and applicationname.
function selectQueue() { if (vm.selecteditem === null) return; var myitem; for (var i =0 ; i, vm.queues.length ; i++) { if (vm.queues[i].name === vm.selecteditem) { vm.selectedservapp = vm.queues[i].servapplname; vm.selectedbusinessdomain = vm.queues[i].businessdomain; console.log("gottit", vm.selectedservapp, vm.selectedbusinessdomain, vm.queues[i]); break; } } var appobj = {}; console.log("length of filteredlist: ", vm.queuelistFiltered.length); vm.applist = []; console.log(vm.selectedbusinessdomain, vm.selectedservapp); vm.queues.forEach(function (item) { if (item.servapplname === vm.selectedservapp && item.businessdomain === vm.selectedbusinessdomain) { vm.applist.push(item.name); } }); }
[ "getQueueNames() {\n return Object.keys(this.queues);\n }", "get queues() {\n return Object.keys(this._queues).map(name => this._queues[name]);\n }", "updatePublishableBatches()\n {\n while (this.custom_queue.batch_sel.firstChild) {\n this.custom_queue.batch_sel.removeChild(this.custom_queue.batch_sel.firstChild);\n }\n\n this.publishable_batches.forEach(publishable_batch =>{\n var option = document.createElement(\"option\");\n option.textContent = publishable_batch.name;\n option.id = publishable_batch.id;\n\n this.custom_queue.batch_sel.append(option);\n })\n \n this.batches_loaded = true;\n }", "function queryBuoys() {\n server.getBuoys().then(function(res) {\n vm.buoys = res.data.buoys;\n formatBuoys();\n }, function(res) {\n gui.alertBadResponse(res);\n });\n }", "function getRejectReasons()\n{\n\t$.ajax({\n\t\ttype : \"POST\",\n\t\turl : getBaseURL() + \"/EntityLoaderServlet\", // servlet name\n\t\tdata : {\n\t\t\t'entityname' : 'RejectReasons', // request partameters\n\t\t},\n\t\tdataType : 'json',\n\t\tcache : false,\n\t\tsuccess : function(data) {\n\t\t\t\n\t\t\tvar $select = $('#reject_reason_text');\n\t\t\t// Remove the old drop down box datas\n\t\t\t$select.find('option').remove();\n\n\t\t\tif( data.result == \"success\") // success result\n\t\t\t {\n\t\t\t\t\n\t\t\t\t$('<option>').val('').text('--Select Reason--').appendTo(\n\t\t\t\t\t\t$select);\n\t\t\t\t\n\t\t\t\t\t$.each(data, function(key, value) // get the key,value one by one \n\t\t\t\t\t{\n\t\t\t\t\t\tif( value != \"success\") // leave 'result':'success' pair\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$('<option>').val(key).text(value).appendTo(\n\t\t\t\t\t\t\t\t\t$select);\n\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});\n\t\t\t\t\t\n\t\t\t\t\tsortSelectBox('businesscategory');\n\t\t\t\t\t\n\t\t\t\t\t$(\"#businesscategory option:first-child\").attr(\"selected\", true);\n\t\t\t\t\t\n\t\t\t\t\t $('#businesscategory option').prop('disabled', false);\n\t\t\t\t\t\n\t\t\t }\n\t\t\t else // failed result\n\t\t\t {\n\t\t\t\t \n\t\t\t\t $select.find('option').remove();\n\t\t\t\t \n\t\t\t\t $('<option>').val(\"\").text('--N/A--').appendTo(\n\t\t\t\t\t\t\t$select); \n\t\t\t\t \n\t\t\t }\n\t\t\t\n\t\t\t $select.trigger('update');\n\n\t\t},\n\t\terror : function(xhr, textStatus, errorThrown) // other errors\n\t\t{\n\t\t\t\n\t\t}\n\t});\n}", "static async getConsumers(req, res) {\n const queueId = req.params.qid;\n const queueIndex = queues.findIndex((queue) => queue.id === queueId);\n\n res.status(200).json({\n status: \"success\",\n data: queues[queueIndex].consumers,\n message: \"Retrieved All Consumers\",\n });\n }", "function ListQueue(dummy, page) {\n\n if ( typeof page !== 'number' ) page = 0;\n var QueueList = setuptools.lightbox.menu.paginate.state.QueueList.PageList;\n\n if ( page > setuptools.lightbox.menu.paginate.state.QueueList.lastPage ) page = setuptools.lightbox.menu.paginate.state.QueueList.lastPage;\n $('div.QueueList div.customPage input[name=\"customPage\"]').val(page+1);\n\n // determine our boundaries\n var minIndex = setuptools.data.config.accountsPerPage*page;\n var maxIndex = (setuptools.data.config.accountsPerPage*page)+setuptools.data.config.accountsPerPage;\n if ( maxIndex > QueueList.length ) maxIndex = QueueList.length;\n if ( QueueList.length <= setuptools.data.config.accountsPerPage ) {\n minIndex = 0;\n maxIndex = QueueList.length;\n }\n\n // generate the page html\n var html = '';\n for ( var i = minIndex; i < maxIndex; i++ ) html += createRow(i);\n if ( html === '' ) html = ' \\\n <div class=\"flex-container queuetask noselect\" style=\"justify-content: flex-start;\"> \\\n <div style=\"flex-basis: 100%; justify-content: space-between; border: 0;\" class=\"menuStyle buttonStyle neutral textLeft w100 select mr0\">\\\n No accounts in queue \\\n </div> \\\n </div>\\\n ';\n return html;\n\n }", "function GetDropDownList() {\n var typeCodeList = [\"WMSYESNO\", \"WMSRelationShip\", \"INW_LINE_UQ\", \"PickMode\"];\n var dynamicFindAllInput = [];\n\n typeCodeList.map(function (value, key) {\n dynamicFindAllInput[key] = {\n \"FieldName\": \"TypeCode\",\n \"value\": value\n }\n });\n var _input = {\n \"searchInput\": dynamicFindAllInput,\n \"FilterID\": appConfig.Entities.CfxTypes.API.DynamicFindAll.FilterID\n };\n\n apiService.post(\"eAxisAPI\", appConfig.Entities.CfxTypes.API.DynamicFindAll.Url + authService.getUserInfo().AppPK, _input).then(function (response) {\n if (response.data.Response) {\n typeCodeList.map(function (value, key) {\n PickupanddeliverydetailCtrl.ePage.Masters.DropDownMasterList[value] = helperService.metaBase();\n PickupanddeliverydetailCtrl.ePage.Masters.DropDownMasterList[value].ListSource = response.data.Response[value];\n });\n }\n });\n }", "function updateDropDown(){\n const ul = $('ul.dropdown-menu')\n ul.arrive(\"div.active\",{onceOnly: true},() => {\n let ids = $('div.active');\n for ( let elements of ids){\n data = {\n hash : elements.id,\n id : $(elements).attr(\"data\"),\n status : \"start\"\n };\n\n worker.postMessage(data);\n };\n\n $(\"span.control\").on('click',function(){\n change(this);\n });\n\n })\n}", "function jsonq_send()\n\t{\n\t\tif (jsonq_uid > 0 && typeof jsonq_queue['u'+(jsonq_uid-1)] == 'object')\n\t\t{\n\t\t\tvar jobs_to_send = {};\n\t\t\tvar something_to_send = false;\n\t\t\tfor(var uid in jsonq_queue)\n\t\t\t{\n\t\t\t\tvar job = jsonq_queue[uid];\n\n\t\t\t\tif (job.menuaction == 'send') continue;\t// already send to server\n\n\t\t\t\t// if job has a callbeforesend callback, call it to allow it to modify pararmeters\n\t\t\t\tif (typeof job.callbeforesend == 'function')\n\t\t\t\t{\n\t\t\t\t\tjob.callbeforesend.call(job.sender, job.parameters);\n\t\t\t\t}\n\t\t\t\tjobs_to_send[uid] = {\n\t\t\t\t\tmenuaction: job.menuaction,\n\t\t\t\t\tparameters: job.parameters\n\t\t\t\t};\n\t\t\t\tjob.menuaction = 'send';\n\t\t\t\tjob.parameters = null;\n\t\t\t\tsomething_to_send = true;\n\t\t\t}\n\t\t\tif (something_to_send)\n\t\t\t{\n\t\t\t\t// TODO: Passing this to the \"home\" application looks quite ugly\n\t\t\t\tvar request = egw.json('home.queue', jobs_to_send, jsonq_callback, this);\n\t\t\t\trequest.sendRequest(true);\n\t\t\t}\n\t\t}\n\t}", "function renderListComboBoxPhone() {\n\t\tvar url = baseUrl + \"api/supplierlistscombophone\";\n\t\t$.get(url, function(customers){\n\t\t\t$.each(customers, function(index, customer){\n\t\t\t\tvar option = $('<option />');\n\t\t\t\toption.attr('value', this.value).text(customer.phone);\n\t\t\t $('#cboPhone').append(option);\n\t\t\t});\n\t\t});\n\t}", "function initAdminProgramDropdown() {\n\tvar dropdown = document.getElementById(\"programDropdown\");\n\t//if the dropdown box exists\n\tif(dropdown) {\n\t\t//clear the dropdown box\n\t\tdropdown.options.length = 0;\n\t\t\n\t\t//add every program to the dropdown box\n\t\tvar i;\n\t\tfor(i in programs) {\n\t\t\tvar program = programs[i];\n\t\t\tdropdown.add(new Option(program.name), null);\n\t\t}\n\t}\n}", "function showSelectManufacturer() {\n var msg = callAPI(uRLBase + \"Manufacturer\", \"GET\");\n $('#commodity-owner').html('<option value=\"\"> --- Chọn nhà sản xuất ---</option>');\n\n if(msg)\n {\n $.each(msg, function(key, value){\n var newRow = '<option value=\"' + value['$class'] + '#' +value['tradeId'] + '\">' + value['companyName'] + '</option>';\n $('#commodity-owner').append(newRow);\n });\n }\n}", "static async companyJobList(req, res) {\n\t\ttry {\n\t\t\t// save message from service\n\t\t\tlet companyJobList = await MessageService.companyJobList(req.body.params.company_id)\n\t\t\t// response\n\t\t\tres.json(response.success(ka.request_success, companyJobList))\n\t\t} catch (error) {\n\t\t\tres.json(response.error(ka.request_error, {}, error.message))\n\t\t}\n\t}", "function getPlayQueue (pid, range) {\n sendCmd('player/get_queue', {\n pid: '-652946493'\n });\n}", "function populateContactDropDown(contactResource, vm) {\n //contactResource.query(function (data) { // REST API call to get all the companies with company names\n // var listitems = '<option value=-1 selected=\"selected\">---- Select Contact ----</option>';\n // $.each(data, function (index, item) {\n // var firstName = cleanSpaces(item.firstName);\n // var lastName = cleanSpaces(item.lastName);\n // var fulName = (firstName + '_' + lastName);\n // listitems += '<option value=' + fulName + '>' + (item.firstName + ' ' + item.lastName) + '</option>';\n // });\n // $(\"#selectContact option\").remove();\n // $(\"#selectContact\").append(listitems);\n //});\n var apiUrl = 'https://localhost:44302/api/Contact';\n vm.httpService({\n method: \"get\",\n headers: vm.messageHeadersForEnc,\n url: apiUrl,\n }).success(function (data) {\n var listitems = '<option value=-1 selected=\"selected\">---- Select Contact ----</option>';\n $.each(data, function (index, item) {\n var firstName = cleanSpaces(item.firstName);\n var lastName = cleanSpaces(item.lastName);\n var fulName = (firstName + '_' + lastName);\n listitems += '<option value=' + fulName + '>' + (item.firstName + ' ' + item.lastName) + '</option>';\n });\n $(\"#selectContact option\").remove();\n $(\"#selectContact\").append(listitems);\n }\n ).error(function (data) {\n alert('error - web service access') // display error message \n });\n }", "_onApplicationSelect() {\n this._selected = 'appsco-application-add-settings';\n }", "function populateSqdDropdown(){\n var xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n let outputArray = JSON.parse(xhttp.responseText);\n let loopCounter = outputArray.length;\n for(i = 0; i<loopCounter; ++i){\n let squadronName = outputArray[i];\n let html = '<option>'+squadronName+'</option>';\n $(\"#squadronSelect\").append(html);\n }\n }\n };\n xhttp.open(\"GET\", \"scripts/squadronquery.php\", true);\n xhttp.send();\n}", "GetMailingLists(domain, name) {\n let url = `/email/domain/${domain}/mailingList?`;\n const queryParams = new query_params_1.default();\n if (name) {\n queryParams.set('name', name);\n }\n return this.client.request('GET', url + queryParams.toString());\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load model info on airplanes that matches the model ID
function loadAirplaneModelOwnerInfoByModelId(modelId) { var airlineId = activeAirline.id $.ajax({ type: 'GET', url: "airlines/"+ airlineId + "/airplanes/model/" + modelId, contentType: 'application/json; charset=utf-8', dataType: 'json', async: false, success: function(result) { existingInfo = loadedModelsById[modelId] //find the existing info //update the existing info with the newly loaded result var newInfo = result[modelId] if (newInfo) { //then has owned airplanes with this model existingInfo.assignedAirplanes = newInfo.assignedAirplanes existingInfo.assignedAirplanes.sort(sortByProperty('condition')) existingInfo.availableAirplanes = newInfo.availableAirplanes existingInfo.availableAirplanes.sort(sortByProperty('condition')) existingInfo.constructingAirplanes = newInfo.constructingAirplanes existingInfo.totalOwned = existingInfo.assignedAirplanes.length + existingInfo.availableAirplanes.length + existingInfo.constructingAirplanes.length } else { //no longer owned this model existingInfo.assignedAirplanes = [] existingInfo.availableAirplanes = [] existingInfo.constructingAirplanes = [] existingInfo.totalOwned = 0 } existingInfo.isFullLoad = true }, error: function(jqXHR, textStatus, errorThrown) { console.log(JSON.stringify(jqXHR)); console.log("AJAX error: " + textStatus + ' : ' + errorThrown); } }); }
[ "function loadAirplaneModelOwnerInfo() {\r\n\tvar airlineId = activeAirline.id\r\n\tloadedModelsOwnerInfo = []\r\n\t$.ajax({\r\n\t\ttype: 'GET',\r\n\t\turl: \"airlines/\"+ airlineId + \"/airplanes?simpleResult=true&groupedResult=true\",\r\n\t contentType: 'application/json; charset=utf-8',\r\n\t dataType: 'json',\r\n\t async: false,\r\n\t success: function(ownedModels) { //a list of model with airplanes\r\n\t \t//add airplane ownership info to existing model entries\r\n\t \t$.each(loadedModelsById, function(modelId, model) {\r\n\t \t var ownedAirplanesInfo = ownedModels[modelId]\r\n\t \t if (ownedAirplanesInfo) { //then own some airplanes of this model\r\n\t \t model.assignedAirplanes = ownedAirplanesInfo.assignedAirplanes\r\n\t \t model.availableAirplanes = ownedAirplanesInfo.availableAirplanes\r\n\t \t model.constructingAirplanes = ownedAirplanesInfo.constructingAirplanes\r\n\t \t model.assignedAirplanes.sort(sortByProperty('condition'))\r\n model.availableAirplanes.sort(sortByProperty('condition'))\r\n\t \t } else {\r\n\t \t model.assignedAirplanes = []\r\n model.availableAirplanes = []\r\n model.constructingAirplanes = []\r\n\t \t }\r\n model.totalOwned = model.assignedAirplanes.length + model.availableAirplanes.length + model.constructingAirplanes.length\r\n \t\t\tloadedModelsOwnerInfo.push(model)\r\n\t \t})\r\n\t },\r\n\t error: function(jqXHR, textStatus, errorThrown) {\r\n\t console.log(JSON.stringify(jqXHR));\r\n\t console.log(\"AJAX error: \" + textStatus + ' : ' + errorThrown);\r\n\t }\r\n\t});\r\n}", "function showAllAirplaneInventory(modelId) {\r\n if (!loadedModelsOwnerInfo) {\r\n loadAirplaneModelOwnerInfo()\r\n }\r\n\r\n $(\"#allAirplaneInventoryModal .inventoryContainer\").empty()\r\n var info = loadedModelsById[modelId]\r\n if (!info.isFullLoad) {\r\n loadAirplaneModelOwnerInfoByModelId(modelId) //refresh to get the utility rate\r\n }\r\n\r\n $(\"#allAirplaneInventoryModal .modelName\").text(info.name)\r\n var inventoryDiv = $(\"<div style='width : 95%; min-height : 85px;' class='section'></div>\")\r\n var airplanesDiv = $(\"<div style= 'width : 100%; overflow: auto;'></div>\")\r\n var empty = true\r\n\r\n var allAirplanes = $.merge($.merge($.merge([], info.assignedAirplanes), info.availableAirplanes), info.constructingAirplanes)\r\n $.each(allAirplanes, function( key, airplane ) {\r\n var airplaneId = airplane.id\r\n var li = $(\"<div style='float: left;' class='clickable' onclick='loadOwnedAirplaneDetails(\" + airplaneId + \", $(this), refreshAllAirplaneInventoryAfterAirplaneUpdate)'></div>\").appendTo(airplanesDiv)\r\n var airplaneIcon = getAirplaneIcon(airplane, info.badConditionThreshold)\r\n enableAirplaneIconDrag(airplaneIcon, airplaneId)\r\n enableAirplaneIconDrop(airplaneIcon, airplaneId, \"refreshAllAirplaneInventoryAfterAirplaneUpdate\")\r\n li.append(airplaneIcon)\r\n empty = false\r\n });\r\n\r\n if (empty) {\r\n airplanesDiv.append(\"<h4>-</h4>\")\r\n }\r\n\r\n inventoryDiv.append(airplanesDiv)\r\n $(\"#allAirplaneInventoryModal .inventoryContainer\").append(inventoryDiv)\r\n\r\n toggleUtilizationRate($(\"#allAirplaneInventoryModal .inventoryContainer\"), $(\"#allAirplaneInventoryModal .toggleUtilizationRateBox\"))\r\n toggleCondition($(\"#allAirplaneInventoryModal .inventoryContainer\"), $(\"#allAirplaneInventoryModal .toggleConditionBox\"))\r\n\r\n $('#allAirplaneInventoryModal').fadeIn(200)\r\n}", "initGameObjets(){\n\t\tlet modele = this.controller.modele;\n\t\t//Init les objets\n\t\tthis.scene.add(modele.table.model);\n\t\tthis.scene.add(modele.environment.model)\n\t\tthis.scene.add(modele.board.model)\t\t\n\t}", "function load3DPlan(obj) {\n\t\t\tif(plans.getByName(obj.info.content)) return;\n\n\t\t\tvar plan = new DV3D.Plan('data/' + obj.file.path + obj.file.content, 'data/' + obj.info.materialMapPath + obj.info.materialMap, obj.info.scale);\n\t\t\tplan.onComplete = function () {\n\t\t\t\tanimate();\n\t\t\t};\n\t\t\tscene.add(plan);\n\n\t\t\tplan.name = obj.info.content;\n\t\t\tplan.userData.name = obj.info.materialName;\n\t\t\tplan.userData.source = obj.source;\n\t\t\tplan.userData.type = 'plan';\n\n\t\t\tvar entry = new DV3D.PlanEntry(plan);\n\t\t\tplan.entry = entry;\n\t\t\tplans.add(entry);\n\t\t\tconsole.log('Plan', plan);\n\t\t}", "function loadModel(filename) {\n return fetch(filename)\n .then(r => r.json())\n .then(raw_model => {\n // Create and bind the VAO\n let vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n \n // Load the vertex coordinate data onto the GPU and associate with attribute\n let posBuffer = gl.createBuffer(); // create a new buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer); // bind to the new buffer\n gl.bufferData(gl.ARRAY_BUFFER, Float32Array.from(raw_model.vertices), gl.STATIC_DRAW); // load the data into the buffer\n gl.vertexAttribPointer(gl.program.aPosition, 3, gl.FLOAT, false, 0, 0); // associate the buffer with \"aPosition\" as length-3 vectors of floats\n gl.enableVertexAttribArray(gl.program.aPosition); // enable this set of data\n\n // Load the index data onto the GPU\n let indBuffer = gl.createBuffer(); // create a new buffer\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indBuffer); // bind to the new buffer\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, Uint16Array.from(raw_model.indices), gl.STATIC_DRAW); // load the data into the buffer\n \n // Cleanup\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);\n\n // Return the VAO and number of indices\n return [vao, raw_model.indices.length];\n })\n .catch(console.error);\n}", "load(req) {\n let self = this;\n // Default the model type to assembly\n req.type = req.modelType ? req.modelType : 'assembly';\n delete req.modelType;\n // Load the model\n this._loader.load(req, function(err, model) {\n if (err) {\n console.log('CADManager.load error: ' + err);\n } else {\n // Add the model to the list of loaded models\n self._models[req.path] = model;\n self.dispatchEvent({ type: 'model:add', path: req.path });\n // Make sure all the rest of the parts have loaded\n self._loader.runLoadQueue();\n }\n });\n // Get the rest of the files\n this._loader.runLoadQueue();\n }", "split(plane) {\n // extract axes from plane and split when present (only z for now)\n let { z } = plane;\n let m4 = this.mesh.matrix;\n return new Promise((resolve,reject) => {\n let { id, matrix } = this;\n worker.model_split({id, matrix, z}).then(data => {\n let { o1, o2 } = data;\n let model;\n // new model becomes top\n if (o2.length)\n this.group.add(model = new mesh.model({\n file: `${this.file}`,\n mesh: o2\n }).applyMatrix4(m4));\n if (o1.length) {\n // o1 becomes bottom\n this.reload(o1);\n resolve(model);\n } else {\n this.remove();\n resolve(model);\n }\n });\n });\n }", "function selectParcel(parid) {\n\t\tif (parid) {\n\t\t\tvar query = new Query('https://ags.agdmaps.com/arcgis/rest/services/MonongaliaWV/MapServer/' + parcelLayerIDX);\n\t\t\tquery.where = \"dmp = '\" + parid.replace(/^0/,'') + \"'\";\n\t\t\tquery.outFields = ['*'];\n\t\t\tquery.returnGeometry = true;\n\t\t\tquery.outSpatialReference = map.spatialReference;\n\t\t\tvar deferred = parcelLayer.queryFeatures(query, selectionHandler);\n\t\t}\n\t}", "function loadMSALayer(src,type,layerId){\n\t// get remote json\n\td3.json(src, function(error, data) {\n\t\t// if topojson, convert to geojson\n\t\tdata = ifTopoReturnGeo(data);\n\t\t// create msa geojson layer\n\t\tmsaLayer = L.geoJson(data, {\n\t\t\tstyle: msaStyle,\n\t\t onEachFeature: onEachMSAFeature\n\t\t}).addTo(map);\n\t});\n}", "function loadModels() {\r\n\r\n const loader = new THREE.GLTFLoader();\r\n \r\n \r\n const onLoad = ( gltf, position ) => {\r\n \r\n model_tim = gltf.scene;\r\n model_tim.position.copy( position );\r\n //console.log(position)\r\n \r\n //model_tim_skeleton= new THREE.Skeleton(model_tim_bones);\r\n model_tim_skeleton= new THREE.SkeletonHelper(model_tim);\r\n model_tim_head_bone=model_tim_skeleton.bones[5];\r\n console.log(model_tim_head_bone);\r\n //console.log(model_tim_bones);\r\n animation_walk = gltf.animations[0];\r\n \r\n const mixer = new THREE.AnimationMixer( model_tim );\r\n mixers.push( mixer );\r\n \r\n action_walk = mixer.clipAction( animation_walk );\r\n // Uncomment you need to change the scale or position of the model \r\n //model_tim.scale.set(1,1,1);\r\n //model_tim.rotateY(Math.PI) ;\r\n\r\n scene.add( model_tim );\r\n \r\n //model_tim.geometry.computeBoundingBox();\r\n //var bb = model_tim.boundingBox;\r\n var bb = new THREE.Box3().setFromObject(model_tim);\r\n var object3DWidth = bb.max.x - bb.min.x;\r\n var object3DHeight = bb.max.y - bb.min.y;\r\n var object3DDepth = bb.max.z - bb.min.z;\r\n console.log(object3DWidth);\r\n console.log(object3DHeight);\r\n console.log(object3DDepth);\r\n // Uncomment if you want to change the initial camera position\r\n //camera.position.x = 0;\r\n //camera.position.y = 15;\r\n //camera.position.z = 200;\r\n \r\n \r\n };\r\n \r\n \r\n \r\n // the loader will report the loading progress to this function\r\n const onProgress = () => {console.log('Someone is here');};\r\n \r\n // the loader will send any error messages to this function, and we'll log\r\n // them to to console\r\n const onError = ( errorMessage ) => { console.log( errorMessage ); };\r\n \r\n // load the first model. Each model is loaded asynchronously,\r\n // so don't make any assumption about which one will finish loading first\r\n const tim_Position = new THREE.Vector3( 0,0,0 );\r\n loader.load('Timmy_sc_1_stay_in_place.glb', gltf => onLoad( gltf, tim_Position ), onProgress, onError );\r\n \r\n }", "function loadSceneObject( url, Id ) {\n\t\tconsole.log( 'loadSceneObject(' + url + ')' );\n\t\tvar sceneObj = new CubicVR.SceneObject( 'resources/xml/sceneObject2.xml' );\n\t\t//sceneObj.obj.bb = [ [-10, -5, -5],[10, 5, -5] ];\n\t\t//sceneObj.obj.addFace([0, 1, 2, 3]);\n\t\t//sceneObj.obj.calcNormals();\n\t\t//sceneObj.obj.compile();\n\t\tconsole.log( 'loaded xml sceneObj: ' );\n\t\tconsole.log( sceneObj );\n\t\t\n\t\tvar planeCollision = new CubicVR.CollisionMap({\n\t\t\ttype : \"box\",\n\t\t\tsize: [5, 5, 0.01]\n\t\t});\n\t\tvar rigidObj = new CubicVR.RigidBody(sceneObj, {\n\t\t\ttype : \"dynamic\",\n\t\t\tmass : 1,\n\t\t\tcollision : planeCollision\n\t\t});\n\t\tconsole.log( 'created rigidObj' );\n\t\t\n\t\ttry {\n\t\t\tconsole.log('binding sceneObject ' + Id + ' to scene & physics managers');\n\t\t\tscene.bind(sceneObj);\n\t\t\tphysics.bind(rigidObj);\n\t\t} catch( err ) {\n\t\t\tconsole.log('ERROR on Binding: \\t' + err );\n\t\t}\n\t\t\n\t\tsceneObjects.push({\n\t\t\tsceneObj : sceneObj,\n\t\t\tplaneCollision : planeCollision,\n\t\t\tId: Id\n\t\t\t\n\t\t});\n\t\tconsole.log('Finished creating sceneObject ' + Id + '\\n');\n\t}", "function loadExecution(model, resource, jsonld) {\n model.execution.iri = resource['@id'];\n model.pipeline.iri = jsonld.getReference(resource,\n 'http://etl.linkedpipes.com/ontology/pipeline');\n var status = jsonld.getReference(resource,\n 'http://etl.linkedpipes.com/ontology/status');\n model.execution.status.iri = status;\n switch (status) {\n case 'http://etl.linkedpipes.com/resources/status/finished':\n case 'http://etl.linkedpipes.com/resources/status/failed':\n case 'http://etl.linkedpipes.com/resources/status/cancelled':\n model.execution.status.running = false;\n break;\n default:\n model.execution.status.running = true;\n break;\n }\n model.execution.deleteWorkingData = jsonld.getBoolean(resource,\n 'http://linkedpipes.com/ontology/deleteWorkingData');\n }", "function LoadOBJObject() {\r\n var mtlLoader = new THREE.MTLLoader();\r\n mtlLoader.setResourcePath(tempStorePath + lastUploadedObjectName.split(\".\")[0] + '/');\r\n mtlLoader.setPath(tempStorePath + lastUploadedObjectName.split(\".\")[0] + '/');\r\n mtlLoader.load(lastUploadedObjectName.split(\".\")[0] + '.mtl', function (materials) {\r\n materials.preload();\r\n var objLoader = new THREE.OBJLoader();\r\n objLoader.setMaterials(materials);\r\n objLoader.setPath(tempStorePath + lastUploadedObjectName.split(\".\")[0] + '/');\r\n objLoader.load(lastUploadedObjectName, function (object) {\r\n //add object to scene and array\r\n addNewObjectToProject(object, myTypes.importedObject);\r\n //Remove files when object is on scene\r\n removeTempFolder();\r\n });\r\n });\r\n}", "async getModel(brand){\n const modelResponse = await fetch(`https://parallelum.com.br/fipe/api/v1/carros/marcas/${brand}/modelos`);\n const models = await modelResponse.json();\n return models;\n }", "function getHomePlanet(planetData, id) {\n fetch(planetData)\n .then(r => r.json())\n .then(parsedPlanet => {\n document.getElementById(`droid-${id}-homeworld`).innerHTML = parsedPlanet.name;\n });\n}", "function addModels(){\r\n\t//Note: for each model, an appropriate draw function should be included\r\n\tmodel = modelCollection_EmptyModel();\r\n\tmodelCollection_AddModel(model, modelCollection_Tetrahedron); //base = 0, numVertsToDraw = 12\r\n\tmodelCollection_AddModel(model, modelCollection_Torus); //base = 12, numVertsToDraw = 3072\r\n modelCollection_AddModel(model, modelCollection_Sphere); //base = 3084, numVertsToDraw = 5400\r\n modelCollection_AddModel(model, modelCollection_Cube);\t//base = 8484, numVertsToDraw = 36\r\n\r\n}", "function load(req, res, next, id) {\n Adopt.get(id)\n .then((adopt) => {\n req.adopt = adopt; // eslint-disable-line no-param-reassign\n return next();\n })\n .catch(e => next(e));\n}", "function ModelLoader(onLoadedHandler) {\n\n /// List of modules to load in given order\n\n var MODEL_MODULES = [\n// //\"model-browser.js\",\n// //\"model-photo.js\",\n// //\"model-directory.js\",\n// \"model/model-servicelist.js\",\n// \"model/model-sound.js\", // delete by ghl for headphoneinsert interface\n// \"model/model-hisfactory.js\",\n// \"model/model-tvservice.js\",\n// \"model/model-closedcaption.js\",\n// \"model/model-app-setting.js\",\n \"model/model-language.js\",\n \"model/model-parental-lock.js\",\n// \"model/model-softwareupdate.js\",\n// //\"model/model-cec.js\",\n \"model/model-system.js\",\n \"model/model-basic-settings.js\",\n// \"model/model-timer-functions.js\",\n// \"model/model-source.js\",\n \"model/model-network.js\",\n// \"model/model-channelsearch.js\",\n \"model/model-video.js\",\n// \"model/model-miracast.js\",\n \"model/model-picture.js\",\n \"model/model-mpctrl.js\",\n \"model/model-usb.js\",\n \"model/model-volume.js\",\n \"model/model-directory.js\"\n\n ];\n\n /// Number of loaded modules\n var loadedModules = 0;\n\n for (var i = 0; i < MODEL_MODULES.length; i++) {\n var module = MODEL_MODULES[i];\n var script = document.createElement('script');\n script.type = \"text/javascript\";\n script.src = module;\n script.onload = function () {\n loadedModules++;\n if (loadedModules == MODEL_MODULES.length) {\n onLoadedHandler();\n }\n }\n document.head.appendChild(script);\n }\n}", "function nextModel() {\n // Continue processing the next model in _models\n if (_models && _m < _models.length) {\n // Go to next model\n while (++_m < _models.length) {\n _instanceTree = _models[_m].getInstanceTree();\n // Only process the model, if it has a fragment map\n if (_instanceTree) {\n // Get the list of dbIds.\n _dbIds.length = 0;\n _instanceTree.enumNodeChildren(_models[_m].getRootId(), function (dbId) {\n _dbIds.push(dbId);\n }, true);\n // Only process the model if we got some ids\n if (_dbIds.length > 0) {\n // Set the current model and newly loaded dbIds\n _curModel = _models[_m];\n return _curModel;\n }\n }\n }\n }\n\n // Done clear the current model and new loaded dbIds\n _curModel = null;\n\n // End of the models\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows the login page, with a prompt to go Back to the page specified by the given page selector.
function showLoginPage(backPageSelector, retryCallback) { setWindowTitle(Messages.getMessage('reactions_widget__title_signin')); var options = { element: pageContainer(ractive), groupSettings: groupSettings, goBack: function() { setWindowTitle(Messages.getMessage('reactions_widget__title')); goBackToPage(pages, backPageSelector, $rootElement); }, retry: retryCallback }; var page = LoginPage.createPage(options); pages.push(page); // TODO: revisit why we need to use the timeout trick for the confirm page, but not for the defaults page setTimeout(function() { // In order for the positioning animation to work, we need to let the browser render the appended DOM element showPage(page.selector, $rootElement, true); }, 1); }
[ "function gotoLoginPage() {\n var url = $location.$$url;\n if ($location.$$path !== \"/login\") {\n $location.path(\"/login\").search({from: url});\n }\n }", "function browsePage (cat) {\n pref.browse = cat;\n storePref();\n window.location.href = '../pages/browse.html';\n}", "function presentDefaultLoginForm(){\n\t$(\"#loginField\").empty();\n\t$(\"#loginField\").html(\"<a id=\\\"loginButton\\\" href=\\\"/login\\\"><strong>Login</strong></a>\");\n\t$(\"#loginStatus\").html(\"Login:\");\n\t$(\"#loginMessage\").html(\"Fill in the formula and click on the button to log in.\");\n\t$(\"#myform\").removeAttr(\"style\");\n}", "function goBack() {\n\tsignInBtn.style.display = \"inline-block\";\n\tsignUpBtn.style.display = \"inline-block\";\n\tusernameInput.value = \"\";\n\tusernameInput.style.display = \"none\";\n\tpasswordInput.value = \"\";\n\tpasswordInput.style.display = \"none\";\n\tnewUsernameInput.value = \"\";\n\tnewUsernameInput.style.display = \"none\";\n\tnewPasswordInput.value = \"\";\n\tnewPasswordInput.style.display = \"none\";\n\tretypePasswordInput.value = \"\";\n\tretypePasswordInput.style.display = \"none\";\n\n\tbackBtn.style.visibility = \"hidden\";\n\tactSignInBtn.style.display = \"inline-block\";\n\tactSignInBtn.style.visibility = \"hidden\";\n\tactSignUpBtn.style.display = \"inline-block\";\n\tactSignUpBtn.style.visibility = \"hidden\";\n\tsignOutBtn.style.display = \"inline-block\";\n\tactSignUpBtn.style.visibility = \"hidden\";\n\n\tmessage.textContent = \"[message]\"\n\tmessage.style.visibility = \"hidden\";\n}", "function showCorrectLogonPage() {\n if(initializeRewards.urlContainsFlowID()){\n changePageFn('#urlogon');\n } else if (isCustomerUsingToken(ccoTokenKey)) {\n changePageFn('#cco');\n }else if (isCustomerUsingToken(bbTokenKey)) {\n changePageFn('#bb');\n }\n }", "backButtonClicked(){\n // get back to the previous page on the app-main navigator stack\n $('#app-main-navigator').get(0).popPage();\n }", "function goBack() {\n if (pageStack.slice(-1)[0] === 'persons-list') {\n clearPersonList();\n }\n\n window.location.hash = pageStack.slice(-2)[0];\n pageStack = pageStack.slice(0, pageStack.length - 2);\n checkPageNav();\n}", "function redirectAfterLogin() {\n\n var identity = getAuthenticatedIdentity();\n\n if (!identity) {\n spAppError.add('Attempted redirect after signed in');\n\n } else {\n\n if (redirectState && redirectState.toParams.tenant.toLowerCase() === identity.tenant.toLowerCase()) {\n $state.go(redirectState.toState.name, redirectState.toParams);\n } else {\n $state.go('home', { tenant: identity.tenant });\n }\n\n }\n }", "function forgotPassword() {\r\n window.location = \"newPassword.html\"; \r\n}", "function loginView(data) {\n // Reference the logged in nav view\n var loginNavView = new LoginNav();\n\n // change the region upon login, and pass the appropriate user data through\n MyApp.navigationRegion.show(loginNavView, data);\n }", "redirect() {\n Radio.request('utils/Url', 'navigate', {\n trigger : false,\n url : '/notebooks',\n includeProfile : true,\n });\n }", "clickOnSignInLink() {\n safeAction.waitForClickable(homePageLoc.SIGN_LINK, waitTime.MEDIUMWAIT, \"Sign In link in home page\");\n safeAction.safeVisibleClick(homePageLoc.SIGN_LINK, waitTime.MEDIUMWAIT, \"Sign In link in home page\");\n return signInPage;\n }", "function rekeningOpenen() {\n var sNaam = window.prompt('Uw naam ?','');\n if (sNaam !== '' && sNaam !== null) {\n setCookie('klantnaam', sNaam, 100);\n setCookie('saldo', 100, 100);\n window.history.go(0);\n }\n}", "redirectToLogin () {\n window.location.assign('/login')\n }", "function passwordResetDialog() {\n // @FIXME reimplement using dialogify\n app.getForm('requestpassword').clear();\n app.getView({\n ContinueURL: URLUtils.https('Account-PasswordResetDialogForm')\n }).render('account/password/requestpasswordresetdialog');\n}", "function signIn()\n {\n var email = document.getElementById(\"email\");\n var password = document.getElementById(\"password\");\n const promise = auth.signInWithEmailAndPassword(email.value, password.value);\n promise.catch(e => alert(e.message));\n \n if (auth.signInWithEmailAndPassword(email.value, password.value))\n {\n window.location.href=\"MainPage.html\"\n }\n else\n {\n alert(\"Wrong infromation, please try again.\")\n }\n\n }", "function openNewsgroupAccountWizard() {\n window.browsingContext.topChromeWindow.openDialog(\n \"chrome://messenger/content/AccountWizard.xhtml\",\n \"AccountWizard\",\n \"chrome,modal,titlebar,centerscreen\"\n );\n}", "function showInitialPage(){\n\t// other initiations here\n\tformMessageReset();\n\tinitSettingVal(); // initial settings value\n\tinitNodeCompletion(); // initial public node completion list\n\tinitAddressCompletion();\n\n\tif(!settings.has('firstRun') || settings.get('firstRun') !== 0){\n\t\tchangeSection('section-settings');\n\t\tsettings.set('firstRun', 0);\n\t}else{\n\t\tchangeSection('section-welcome');\n\t}\n\n\tlet versionInfo = document.getElementById('walletShellVersion');\n\tif(versionInfo) versionInfo.innerHTML = WS_VERSION;\n\tlet wVersionInfo = document.getElementById('walletVersion');\n\tif(wVersionInfo) wVersionInfo.innerHTML = remote.app.getVersion();\n}", "function mpLogIn() {\n mixpanel.identify(mixpanel.cookie.props.distinct_id)\n mixpanel.people.set({\"last page\":window.location.href});\n mixpanel.people.set_once({\"account created\":Date.now()});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notifies all feature listeners about the addition of a new feature.
notifyFeatureListeners(feature) { this.featureListeners.forEach(function (callback) { callback(feature); }); }
[ "addFeatureListener(callback) {\n this.featureListeners.push(callback);\n }", "processNewFeature(newFeature) {\n //Notify listeners\n this.notifyFeatureListeners(newFeature);\n //Get corresponding old version of the feature\n let oldFeature = this.getFeatureById(newFeature.getId());\n //Check if old version of the feature exists\n if (oldFeature == null) {\n super.addFeature(newFeature);\n return;\n }\n //Get new and old zoom level of the feature\n let newZoom = newFeature.get(\"zoom\");\n let oldZoom = oldFeature.get(\"zoom\");\n //Check if zoom field of new and old feature differ\n if (newZoom != oldZoom) {\n //remove old feature and add the new one\n super.removeFeature(oldFeature);\n super.addFeature(newFeature);\n //Check if a console log about this action is desired\n if (USER_CONFIG.featureUpdateLog) {\n console.log(\"[\" + this.areaTypeName + \"] Updated feature \\\"\" + newFeature.getId() + \"\\\"\");\n }\n }\n }", "function addFeature() {\n\n}", "#registerEventListeners() {\n this.#addOnFocusEventListener();\n this.#addOnHelpIconClickEventListener();\n }", "function addElementListeners() {\n addDarkModeListener();\n addColorSchemeListener();\n addResizeListener();\n addCreateNoteListener();\n addDeleteNoteListener();\n addFilterNoteListener();\n addFilterHashesListener();\n addTitleListener();\n addDownloadListener();\n addCitationButtonListener();\n addModeSwitchListeners();\n addOnCloseListener();\n addOptionsListeners();\n}", "function onEachFeature(feature, layer){\n getPIP(feature, layer);\n layer.bindPopup(feature.properties.label +\n \" crimes: \" + feature.properties.crimes);\n layer.setStyle(style(feature));\n layer.on({\n mouseover: highlightFeature,\n mouseout: resetHighlight,\n });\n\n}", "_addFeatures(features, global) {\n let stageIndex = this.stages.length - 1;\n let stage = this.stages[stageIndex];\n for (let feature of features) {\n if (this.allFeatures[feature] == null) {\n stage.push(feature);\n this.allFeatures[feature] = stageIndex;\n\n if (global) {\n this.globalFeatures[feature] = true;\n }\n }\n }\n }", "function bindDataLayerListeners(dataLayer) {\n dataLayer.addListener('click', selectFeatures);\n dataLayer.addListener('addfeature', refreshGeoJsonFromData);\n dataLayer.addListener('removefeature', refreshGeoJsonFromData);\n dataLayer.addListener('setgeometry', refreshGeoJsonFromData);\n}", "add_change(func) {\n this.add_event(\"change\", func);\n }", "function addFeatures(definitionMap, meta) {\n // e.g. `features: [NgOnChangesFeature]`\n const features = [];\n const providers = meta.providers;\n const viewProviders = meta.viewProviders;\n if (providers || viewProviders) {\n const args = [providers || new o.LiteralArrayExpr([])];\n if (viewProviders) {\n args.push(viewProviders);\n }\n features.push(o.importExpr(R3.ProvidersFeature).callFn(args));\n }\n if (meta.usesInheritance) {\n features.push(o.importExpr(R3.InheritDefinitionFeature));\n }\n if (meta.lifecycle.usesOnChanges) {\n features.push(o.importExpr(R3.NgOnChangesFeature));\n }\n if (features.length) {\n definitionMap.set('features', o.literalArr(features));\n }\n}", "function attachDefaultListeners() {\n\t\tvar listenerDiv = document.getElementById('listener');\n\t\tlistenerDiv.addEventListener('load', moduleDidLoad, true);\n\t\tlistenerDiv.addEventListener('message', handleMessage, true);\n\t\tlistenerDiv.addEventListener('error', handleError, true);\n\t\tlistenerDiv.addEventListener('crash', handleCrash, true);\n\t\tif (typeof window.attachListeners !== 'undefined') {\n\t\t\twindow.attachListeners();\n\t\t}\n\t}", "function addMapEvents(){\n\t\t\t// Add tap event to add shapes for custom links\n\t\t\tmap.addEventListener('tap', initializeOraddPointToPolygon);\n\t\t\t\n\t\t\t// Add mouse-move listner to show polyline \n\t\t\tmap.addEventListener('pointermove', refreshNonFinalizedPolygon);\n\t}", "function addFeaturesToMap(featureList) {\n // concat old feature list with new feature list\n var newFeatureList = map.getSource('symbols')._data.features.concat(featureList);\n // update symbols layer with new feature list\n map.getSource('symbols').setData({\n type: 'FeatureCollection',\n features: newFeatureList\n });\n}", "function MapListeners() { }", "function patchAddEventListener() {\n if (_addEventListenerIsPatched) {\n debugLog('patchAddEventListener: addEventListener is already patched.');\n return;\n }\n\n debugLog('Patching addEventListener.');\n\n var prototypeSplash = getHH(Element.prototype);\n prototypeSplash.oldAddEventListener = Element.prototype.addEventListener;\n\n Element.prototype.addEventListener = function(eventType, listener, useCapture) {\n debugLog('patchAddEventListener: addEventListener called.\\nelement: ', this,\n '\\neventType: ', eventType,\n '\\nlistener: ', listener,\n '\\nuseCapture: ', useCapture);\n\n var thisSplash = getHH(this);\n\n // Register this event on the element itself.\n if (!thisSplash.hasOwnProperty('eventListeners')) {\n thisSplash.eventListeners = {};\n }\n\n if (!thisSplash.eventListeners.hasOwnProperty(eventType)) {\n thisSplash.eventListeners[eventType] = [];\n }\n\n thisSplash.eventListeners[eventType].push(listener);\n\n // Register this event in the registry.\n if (!_elementsWithListeners.hasOwnProperty(eventType)) {\n _elementsWithListeners[eventType] = [];\n }\n\n // TODO: Elements with multiple listeners will be pushed on this\n // list multiple times, but I'm not aware of any more efficient\n // data structure to do this.\n _elementsWithListeners[eventType].push(this)\n\n // Finally, call the patched function.\n args = [eventType, listener, useCapture];\n prototypeSplash.oldAddEventListener.apply(this, args);\n }\n\n _addEventListenerIsPatched = true;\n }", "function addOrUpdateFeature(feature) {\n try {\n var foundFeature = getFeature(feature.category, feature.name);\n foundFeature.value = feature.value;\n }\n catch (err) {\n self.features.push(feature);\n }\n }", "function onUpdate(fromVersion, toVersion) {\n\tconsole.log('Extension has been updated from version ', fromVersion, ' to version ', toVersion);\n}", "function attachTracklistModificationListeners(onTracklistModifiedByExternalSource) {\n let onEvent = (event) => {\n if(!currentlyModifyingAnyTracklist)\n onTracklistModifiedByExternalSource()\n }\n\n for(trackList of getTracklistNodes()) {\n trackList.addEventListener('DOMNodeInserted', onEvent)\n trackList.addEventListener('DOMNodeRemoved', onEvent)\n }\n}", "function favouriteDidAdded(event, fave) {\n // Nothing to do if there is zero comics.\n if (!vm.comics.length) return;\n var model = _.find(vm.comics, {id: fave.id});\n if (model) model.favourite = fave;\n $log.debug('Fave added:', fave);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run nyc and AVA, then generate an lcov.info.
async function runCoverage() { // If cowboyhat is already running skip. if (locked) { return } locked = true // Await coverage and testing. await new Promise((resolve) => { spawn( 'node_modules/.bin/nyc', nycOptions, spawnOptions, ).on('close', resolve) }) // TODO: Find out why this is necessary and document it here. if (runCount) { console.log('\n') } // When the report is done finish up. spinner.stop('\nlcov.info complete.') locked = false runCount += 1 }
[ "function main() {\n console.log(`testing ngtools API...`);\n\n Promise.resolve()\n .then(() => codeGenTest())\n .then(() => i18nTest())\n .then(() => lazyRoutesTest())\n .then(() => {\n console.log('All done!');\n process.exit(0);\n })\n .catch((err) => {\n console.error(err.stack);\n console.error('Test failed');\n process.exit(1);\n });\n}", "static function Main() {\n var today: Date = new Date();\n FiddlerObject.StatusText = \" CustomRules.js was loaded at: \" + today;\n CertMaker.createRootCert();\n //CertMaker.GetRootCertificate().GetPublicKeyString()\n }", "run() {\n const times = Config.codeTimesPerRun;\n const lines = Config.codeLinesPerIteration;\n const stepEnergyCoef = Config.energyStepCoef;\n const world = this.world;\n const mutationPeriod = Config.orgMutationPeriod;\n const orgsAndMols = this.orgsAndMols;\n const orgsAndMolsRef = orgsAndMols.ref();\n const orgs = this.orgs;\n const orgsRef = orgs.ref();\n //\n // Loop X times through population\n //\n for (let time = 0; time < times; time++) {\n //\n // Loop through population\n //\n let o = orgs.items;\n while (--o > -1) {\n const org = orgsRef[o];\n const code = org.code;\n let ax = org.ax;\n let bx = org.bx;\n let line = org.line;\n //\n // Resets value of 'say' command\n //\n if (org.freq) {org.freq = this._freq[org.freq] = 0}\n //\n // Loop through few lines in one organism to\n // support pseudo multi threading\n //\n for (let l = 0; l < lines; l++) {\n const cmd = code[line];\n\n switch (cmd) {\n case CODE_CMD_OFFS: { // toggle\n ++line;\n const tmp = ax;\n ax = bx;\n bx = tmp;\n continue;\n }\n\n case CODE_CMD_OFFS + 1: // shift\n ++line;\n org.ax = ax;\n org.bx = bx;\n org.shift();\n ax = org.ax;\n bx = org.bx;\n continue;\n\n case CODE_CMD_OFFS + 2: // eq\n ++line;\n ax = bx;\n continue;\n\n case CODE_CMD_OFFS + 3: // pop\n ++line;\n ax = org.pop();\n continue;\n\n case CODE_CMD_OFFS + 4: // push\n ++line;\n org.push(ax);\n continue;\n\n case CODE_CMD_OFFS + 5: // nop\n ++line;\n continue;\n\n case CODE_CMD_OFFS + 6: // add\n ++line;\n ax += bx;\n if (!fin(ax)) {ax = MAX}\n continue;\n\n case CODE_CMD_OFFS + 7: // sub\n ++line;\n ax -= bx;\n if (!fin(ax)) {ax = MIN}\n continue;\n\n case CODE_CMD_OFFS + 8: // mul\n ++line;\n ax *= bx;\n if (!fin(ax)) {ax = MAX}\n continue;\n\n case CODE_CMD_OFFS + 9: // div\n ++line;\n ax = round(ax / bx);\n if (!fin(ax)) {ax = MIN}\n continue;\n\n case CODE_CMD_OFFS + 10: // inc\n ++line;\n ax++;\n if (!fin(ax)) {ax = MAX}\n continue;\n\n case CODE_CMD_OFFS + 11: // dec\n ++line;\n ax--;\n if (!fin(ax)) {ax = MIN}\n continue;\n\n case CODE_CMD_OFFS + 12: // rshift\n ++line;\n ax >>= 1;\n continue;\n\n case CODE_CMD_OFFS + 13: // lshift\n ++line;\n ax <<= 1;\n continue;\n\n case CODE_CMD_OFFS + 14: // rand\n ++line;\n ax = ax < 0 ? rand(CODE_MAX_RAND * 2) - CODE_MAX_RAND : rand(ax);\n continue;\n\n case CODE_CMD_OFFS + 15: // ifp\n line = ax > 0 ? line + 1 : org.offs[line];\n continue;\n\n case CODE_CMD_OFFS + 16: // ifn\n line = ax < 0 ? line + 1 : org.offs[line];\n continue;\n\n case CODE_CMD_OFFS + 17: // ifz\n line = ax === 0 ? line + 1 : org.offs[line];\n continue;\n\n case CODE_CMD_OFFS + 18: // ifg\n line = ax > bx ? line + 1 : org.offs[line];\n continue;\n\n case CODE_CMD_OFFS + 19: // ifl\n line = ax < bx ? line + 1 : org.offs[line];\n continue;\n\n case CODE_CMD_OFFS + 20: // ife\n line = ax === bx ? line + 1 : org.offs[line];\n continue;\n\n case CODE_CMD_OFFS + 21: // ifne\n line = ax !== bx ? line + 1 : org.offs[line];\n continue;\n\n case CODE_CMD_OFFS + 22: {// loop\n const loops = org.loops;\n //\n // previous line was \"end\", so this is next iteration cicle\n //\n if (!org.isLoop) {loops[line] = -1}\n org.isLoop = false;\n if (loops[line] < 0 && org.offs[line] > line + 1) {\n loops[line] = ax;\n }\n if (--loops[line] < 0) {\n line = org.offs[line];\n continue;\n }\n ++line;\n continue;\n }\n\n case CODE_CMD_OFFS + 23: {// call\n if (org.fCount === 0) {++line; continue}\n let index = org.stackIndex;\n if (index >= CODE_STACK_SIZE * 3) {index = -1}\n const func = abs(ax) % org.fCount;\n const stack = org.stack;\n const newLine = org.funcs[func];\n if (org.offs[newLine - 1] === newLine) {++line; continue}\n stack[++index] = line + 1;\n stack[++index] = ax;\n stack[++index] = bx;\n line = newLine;\n org.stackIndex = index;\n continue;\n }\n\n case CODE_CMD_OFFS + 24: // func\n line = org.offs[line];\n if (line === 0 && org.stackIndex >= 0) {\n const stack = org.stack;\n bx = stack[2];\n ax = stack[1];\n line = stack[0];\n org.stackIndex = -1;\n }\n continue;\n\n case CODE_CMD_OFFS + 25: {// ret\n const stack = org.stack;\n let index = org.stackIndex;\n if (index < 0) {line = 0; continue}\n bx = stack[index--];\n ax = stack[index--];\n line = stack[index--];\n org.stackIndex = index;\n continue;\n }\n\n case CODE_CMD_OFFS + 26: // end\n switch (code[org.offs[line]]) {\n case CODE_CMD_OFFS + 22: // loop\n line = org.offs[line];\n org.isLoop = true;\n break;\n case CODE_CMD_OFFS + 24: // func\n const stack = org.stack;\n let index = org.stackIndex;\n if (index < 0) {break}\n bx = stack[index--];\n ax = stack[index--];\n line = stack[index--];\n org.stackIndex = index;\n break;\n default:\n ++line;\n break;\n }\n continue;\n\n case CODE_CMD_OFFS + 27: // retax\n ++line;\n ax = org.ret;\n continue;\n\n case CODE_CMD_OFFS + 28: // axret\n ++line;\n org.ret = ax;\n continue;\n\n case CODE_CMD_OFFS + 29: // and\n ++line;\n ax &= bx;\n continue;\n\n case CODE_CMD_OFFS + 30: // or\n ++line;\n ax |= bx;\n continue;\n\n case CODE_CMD_OFFS + 31: // xor\n ++line;\n ax ^= bx;\n continue;\n\n case CODE_CMD_OFFS + 32: // not\n ++line;\n ax = ~ax;\n continue;\n\n case CODE_CMD_OFFS + 33: {// join\n ++line;\n if (org.ret !== 1) {org.ret = RET_ERR; continue}\n const offset = org.offset + DIR[abs(ax) % 8];\n const dot = world.getOrgIdx(offset);\n if (dot < 0) {org.ret = RET_ERR; continue}\n const nearOrg = orgsAndMolsRef[dot];\n if (nearOrg.code.length + code.length > ORG_CODE_MAX_SIZE) {org.ret = RET_ERR; continue}\n code.splice(bx >= code.length || bx < 0 ? code.length : bx, 0, ...nearOrg.code);\n org.energy += (nearOrg.code.length * Config.energyMultiplier);\n this._removeOrg(nearOrg);\n org.ret = RET_OK;\n continue;\n }\n\n case CODE_CMD_OFFS + 34: {// split\n ++line;\n if (orgsAndMols.full) {org.ret = RET_ERR; continue}\n const offset = org.offset + DIR[abs(org.ret) % 8];\n if (offset < 0 || offset > MAX_OFFS) {org.ret = RET_ERR; continue}\n const dot = world.getOrgIdx(offset);\n if (dot > -1) {org.ret = RET_ERR; continue} // organism on the way\n if (ax < 0 || ax > code.length || bx <= ax) {org.ret = RET_ERR; continue}\n const newCode = code.splice(ax, bx - ax);\n if (newCode.length < 1 || org.ret === IS_ORG_ID && orgs.full) {org.ret = RET_ERR; continue}\n const clone = this._createOrg(offset, org, newCode, org.ret === IS_ORG_ID);\n this._db && this._db.put(clone, org);\n const energy = clone.code.length * Config.energyMultiplier;\n clone.energy = energy;\n if (Config.codeMutateEveryClone > 0 && rand(Config.codeMutateEveryClone) === 0 && clone.isOrg) {\n Mutations.mutate(clone);\n }\n if (code.length < 1) {this._removeOrg(org); break}\n org.energy -= energy;\n org.preprocess();\n line = 0;\n org.ret = RET_OK;\n continue;\n }\n\n case CODE_CMD_OFFS + 35: {// step\n ++line;\n org.energy -= Math.floor(code.length * stepEnergyCoef);\n let offset = org.offset + DIR[abs(ax) % 8];\n if (offset < -1) {offset = LINE_OFFS + org.offset}\n else if (offset > MAX_OFFS) {offset = org.offset - LINE_OFFS}\n if (world.getOrgIdx(offset) > -1) {org.ret = RET_ERR; continue}\n world.moveOrg(org, offset);\n org.ret = RET_OK;\n continue;\n }\n\n case CODE_CMD_OFFS + 36: // find\n ++line;\n if (bx < 0) {\n const ret = org.ret;\n const index = code.findIndex((c, i) => i >= ret && ax === c);\n if (index === -1) {\n org.ret = RET_ERR;\n } else {\n org.find0 = org.find1 = ax = index;\n org.ret = RET_OK;\n }\n } else {\n if (bx > ax || ax > code.length || bx > code.length) {org.ret = RET_ERR; continue}\n const len2 = bx - ax;\n const len1 = code.length - (len2 + 1);\n let ret = RET_ERR;\n let j;\n loop: for (let i = org.ret < 0 ? 0 : org.ret; i < len1; i++) {\n for (j = ax; j <= bx; j++) {\n if (code[i + j - ax] !== code[j]) {continue loop}\n }\n org.find0 = ax = i;\n org.find1 = i + len2;\n ret = RET_OK;\n break;\n }\n org.ret = ret;\n }\n continue;\n\n case CODE_CMD_OFFS + 37: {// move\n ++line;\n org.energy -= Config.energyMove;\n const find0 = org.find0;\n const find1 = org.find1;\n if (find1 < find0) {org.ret = RET_ERR; continue}\n const len = find1 - find0 + 1;\n const moveCode = code.slice(find0, find1 + 1);\n if (moveCode.length < 1) {org.ret = RET_ERR; continue}\n const newAx = ax < 0 ? 0 : (ax > code.length ? code.length : ax);\n const offs = newAx > find1 ? newAx - len : (newAx < find0 ? newAx : find0);\n if (find0 === offs) {org.ret = RET_OK; continue}\n code.splice(find0, len);\n code.splice(offs, 0, ...moveCode);\n org.ret = RET_OK;\n continue;\n }\n\n case CODE_CMD_OFFS + 38: // see\n ++line;\n const offset = org.offset + ax;\n if (offset < 0 || offset > MAX_OFFS) {ax = 0; continue}\n const dot = world.getOrgIdx(offset);\n ax = (dot < 0 ? 0 : orgsAndMolsRef[dot].color);\n continue;\n\n case CODE_CMD_OFFS + 39: {// say\n ++line;\n const freq = abs(bx) % Config.worldFrequency;\n this._freq[freq] = ax;\n org.freq = freq;\n continue;\n }\n\n case CODE_CMD_OFFS + 40: // listen\n ++line;\n ax = this._freq[abs(bx) % Config.worldFrequency];\n continue;\n\n case CODE_CMD_OFFS + 41: {// nread\n ++line;\n const offset = org.offset + DIR[abs(ax) % 8];\n const dot = world.getOrgIdx(offset);\n if (dot < 0) {org.ret = RET_ERR; continue}\n const nearOrg = orgsAndMolsRef[dot];\n ax = nearOrg.code[bx] || 0;\n org.ret = RET_OK;\n continue;\n }\n\n case CODE_CMD_OFFS + 42: {// nsplit\n ++line;\n if (org.ret !== 1) {org.ret = RET_ERR; continue}\n if (orgsAndMols.full) {org.ret = RET_ERR; continue}\n const offset = org.offset + DIR[abs(ax) % 8];\n const dOffset = org.offset + DIR[abs(org.ret) % 8];\n if (offset === dOffset) {org.ret = RET_ERR; continue}\n const dot = world.getOrgIdx(offset);\n if (dot < 0) {org.ret = RET_ERR; continue}\n const dDot = world.getOrgIdx(dOffset);\n if (dDot > -1) {org.ret = RET_ERR; continue}\n const nearOrg = orgsAndMolsRef[dot];\n const newCode = nearOrg.code.splice(0, bx);\n if (newCode.length < 1) {org.ret = RET_ERR; continue}\n const cutOrg = this._createOrg(dOffset, nearOrg, newCode);\n this._db && this._db.put(cutOrg, nearOrg);\n if (nearOrg.code.length < 1) {this._removeOrg(nearOrg)}\n const energy = newCode.length * Config.energyMultiplier;\n nearOrg.energy -= energy;\n cutOrg.energy = energy;\n if (code.length < 1) {this._removeOrg(org); break}\n org.ret = RET_OK;\n continue;\n }\n\n case CODE_CMD_OFFS + 43: {// get\n ++line;\n if (org.ret !== 1 || org.packet) {org.ret = RET_ERR; continue}\n const dot = world.getOrgIdx(org.offset + DIR[abs(ax) % 8]);\n if (dot < 0) {org.ret = RET_ERR; continue}\n this._removeOrg(org.packet = orgsAndMolsRef[dot]);\n continue;\n }\n\n case CODE_CMD_OFFS + 44: {// put\n ++line;\n if (!org.packet) {org.ret = RET_ERR; continue}\n if (orgsAndMols.full) {org.ret = RET_ERR; continue}\n const offset = org.offset + DIR[abs(ax) % 8];\n const dot = world.getOrgIdx(offset);\n if (dot > -1 || offset < 0 || offset > MAX_OFFS) {org.ret = RET_ERR; continue}\n this._createOrg(offset, org.packet);\n this._db && this._db.put(org.packet);\n org.packet = null;\n continue;\n }\n\n case CODE_CMD_OFFS + 45: // offs\n ++line;\n ax = org.offset;\n continue;\n\n case CODE_CMD_OFFS + 46: // age\n ++line;\n ax = org.age;\n continue;\n\n case CODE_CMD_OFFS + 47: // line\n ax = line++;\n continue;\n\n case CODE_CMD_OFFS + 48: // len\n line++;\n ax = code.length;\n continue;\n\n case CODE_CMD_OFFS + 49: // color\n line++;\n const newAx = abs(ax);\n org.color = (newAx < ORG_MIN_COLOR ? ORG_MIN_COLOR : newAx) % 0xffffff;\n continue;\n }\n //\n // This is constant value\n //\n if (cmd < CODE_CMD_OFFS && cmd > -CODE_CMD_OFFS) {ax = cmd; ++line; continue}\n //\n // We are on the last code line. Have to jump to the first\n //\n if (line >= code.length) {\n if (org.stackIndex >= 0) {\n const stack = org.stack;\n bx = stack[2];\n ax = stack[1];\n line = stack[0];\n org.stackIndex = -1;\n } else {\n line = 0;\n }\n }\n }\n org.line = line;\n org.ax = ax;\n org.bx = bx;\n //\n // Organism age related updates\n //\n const age = org.age;\n if (age % org.period === 0 && mutationPeriod > 0) {Mutations.mutate(org)}\n if (age > Config.orgMaxAge) {this._mixAtoms(org)}\n if (org.energy < 0) {this._mixAtoms(org)}\n\n org.age++;\n org.energy--;\n this._i += lines;\n }\n //\n // Plugins\n //\n for (let p = 0, pl = this.plugins.length; p < pl; p++) {this.plugins[p].run(this._iteration)}\n this._iteration++;\n }\n //\n // Updates status line at the top of screen\n //\n const ts = Date.now();\n if (ts - this._ts > 1000) {\n const orgAmount = this.orgs.items;\n world.title(`inps:${round(((this._i / orgAmount) / (((ts - this._ts) || 1)) * 1000))} orgs:${orgAmount} gen:${this.population}`);\n this._ts = ts;\n this._i = 0;\n\n if (orgs.items < 1) {this._createOrgs()}\n }\n }", "generateCoA() {\n /*\n * Generate a CoA PDF.\n */\n console.log('Generating CoA...');\n return new Promise((resolve, reject) => {\n const data = {\n\n };\n authRequest(`/api/results/generate_coa?organization_id=${orgId}`, data).then((response) => {\n if (response.error) {\n showNotification('Error getting templates', response.message, { type: 'error' });\n reject(response.error);\n } else {\n resolve(response.data);\n }\n });\n });\n }", "function gatherDiagnostics(options, bazelOpts, program, disabledTsetseRules) {\n // Install extra diagnostic plugins\n if (!bazelOpts.disableStrictDeps) {\n var ignoredFilesPrefixes = [];\n if (bazelOpts.nodeModulesPrefix) {\n // Under Bazel, we exempt external files fetched from npm from strict\n // deps. This is because we allow users to implicitly depend on all the\n // node_modules.\n // TODO(alexeagle): if users opt-in to fine-grained npm dependencies, we\n // should be able to enforce strict deps for them.\n ignoredFilesPrefixes.push(bazelOpts.nodeModulesPrefix);\n if (options.rootDir) {\n ignoredFilesPrefixes.push(path.resolve(options.rootDir, 'node_modules'));\n }\n }\n program = strict_deps_1.PLUGIN.wrap(program, __assign({}, bazelOpts, { rootDir: options.rootDir, ignoredFilesPrefixes: ignoredFilesPrefixes }));\n }\n if (!bazelOpts.isJsTranspilation) {\n var selectedTsetsePlugin = runner_1.PLUGIN;\n program = selectedTsetsePlugin.wrap(program, disabledTsetseRules);\n }\n // TODO(alexeagle): support plugins registered by config\n var diagnostics = [];\n perfTrace.wrap('type checking', function () {\n var e_1, _a;\n // These checks mirror ts.getPreEmitDiagnostics, with the important\n // exception of avoiding b/30708240, which is that if you call\n // program.getDeclarationDiagnostics() it somehow corrupts the emit.\n perfTrace.wrap(\"global diagnostics\", function () {\n diagnostics.push.apply(diagnostics, __spread(program.getOptionsDiagnostics()));\n diagnostics.push.apply(diagnostics, __spread(program.getGlobalDiagnostics()));\n });\n var sourceFilesToCheck;\n if (bazelOpts.typeCheckDependencies) {\n sourceFilesToCheck = program.getSourceFiles();\n }\n else {\n sourceFilesToCheck = program.getSourceFiles().filter(function (f) { return isCompilationTarget(bazelOpts, f); });\n }\n var _loop_1 = function (sf) {\n perfTrace.wrap(\"check \" + sf.fileName, function () {\n diagnostics.push.apply(diagnostics, __spread(program.getSyntacticDiagnostics(sf)));\n diagnostics.push.apply(diagnostics, __spread(program.getSemanticDiagnostics(sf)));\n });\n perfTrace.snapshotMemoryUsage();\n };\n try {\n for (var sourceFilesToCheck_1 = __values(sourceFilesToCheck), sourceFilesToCheck_1_1 = sourceFilesToCheck_1.next(); !sourceFilesToCheck_1_1.done; sourceFilesToCheck_1_1 = sourceFilesToCheck_1.next()) {\n var sf = sourceFilesToCheck_1_1.value;\n _loop_1(sf);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (sourceFilesToCheck_1_1 && !sourceFilesToCheck_1_1.done && (_a = sourceFilesToCheck_1.return)) _a.call(sourceFilesToCheck_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n });\n return diagnostics;\n }", "function main() {\n\n setUp(config.mongoURL);\n\n\n if (config.getSourcesFromDB) {\n PodcastSource.getFromDatabase(startRunning);\n } else {\n _.forEach(\n config.XMLSource,\n function(sourceEntry) {\n if (sourceEntry.saveToDB) {\n sourceEntry.save(\n function(err) {\n //intentionally not using a callback from here, \n //we only care enough about the write to log an error\n if (err) {\n winston.error('Error saving source to database. [' + sourceEntry.source + ']', err);\n }\n }\n );\n winston.info('Saving source to database: ' + sourceEntry.source);\n }\n }\n );\n startRunning(null, config.XMLSource);\n }\n\n function startRunning(err, sourcesList) {\n if (err) {\n winston.error(err);\n throw err;\n }\n\n if (!sourcesList.length) {\n winston.warn(\"No sources defined, exiting program.\" + \"\\n\" +\n config.cmdline_help_text);\n return tearDown();\n }\n\n processing.runOnSource(\n sourcesList,\n /**\n * Called when each source has completed scraping, or on an error.\n * @param {Error} err Error encountered, if any\n */\n function mainComplete(err) {\n if (err) {\n throw err;\n } else {\n tearDown();\n }\n }\n );\n }\n }", "async function run(compiler, { verbose, namespace }) {\n return new Promise((resolve, reject) => {\n compiler.run((error, stats) => {\n if (!webpackOk(error)) {\n throw error;\n }\n\n logBuildStats(stats, { verbose, namespace });\n\n const summary = getBuildSummary(stats, { namespace });\n if (buildOk(stats)) {\n resolve(summary);\n } else {\n reject(summary);\n }\n });\n });\n}", "function yinyang_cps_00_02() {\n call_cc_cps(k => k, (cc) => {\n const yin = ((cc) => {\n process.stdout.write(\"@\");\n return cc;\n })(cc);\n call_cc_cps(k2 => k2, (cc2) => {\n const yang = ((cc2) => {\n process.stdout.write(\"*\");\n return cc2;\n })(cc2);\n yin(yang);\n })\n })\n}", "async function main () {\n // cjs\n await esbuild.build({\n entryPoints: ['src/index.mjs'],\n bundle: false,\n keepNames: true,\n format: 'cjs',\n outfile: path.join('./dist/', 'index.cjs'),\n platform: 'browser'\n })\n\n // esm\n // await esbuild.build({\n // entryPoints: ['src/index.js'],\n // bundle: false,\n // keepNames: true,\n // format: 'esm',\n // outfile: path.join('./dist/', 'index.mjs'),\n // platform: 'browser'\n // })\n}", "async function test() {\n const clamscan = await new NodeClam().init({\n debugMode: false,\n clamdscan: {\n bypassTest: true,\n host: 'localhost',\n port: 3310,\n socket: '/var/run/clamd.scan/clamd.sock',\n },\n });\n\n const passthrough = new PassThrough();\n const source = axios.get(testUrl);\n\n // Fetch fake Eicar virus file and pipe it through to our scan screeam\n source.pipe(passthrough);\n\n try {\n const { isInfected, viruses } = await clamscan.scanStream(passthrough);\n\n // If `isInfected` is TRUE, file is a virus!\n if (isInfected === true) {\n console.log(\n `You've downloaded a virus (${viruses.join(\n ''\n )})! Don't worry, it's only a test one and is not malicious...`\n );\n } else if (isInfected === null) {\n console.log(\"Something didn't work right...\");\n } else if (isInfected === false) {\n console.log(`The file (${testUrl}) you downloaded was just fine... Carry on...`);\n }\n process.exit(0);\n } catch (err) {\n console.error(err);\n process.exit(1);\n }\n}", "enterOrdinaryCompilation(ctx) {\n\t}", "function runReport() {\n checkAnswers();\n calculateTestTime();\n calculateCheckedInputs();\n\n }", "function Main() {\n yamls = initializeBuild()\n\n yamls.forEach(({ tag }) => {\n prepLocation(tag, argv.c)\n prepLocation(tag, argv.d)\n })\n\n // Loop through each yaml that was returned\n yamls.forEach(async ({ file, tag }) => {\n const pathToYAML = path.join(argv.p, file)\n\n const api = await SwaggerParser.validate(pathToYAML)\n const paths = Object.entries(api.paths)\n\n generateContent(tag, paths)\n generateData(tag, paths)\n })\n}", "function checkStatus() {\n\t'use strict';\n\tconsole.log('Checking data coverage for our query period');\n\n\tds.historics.status({\n\t\t'start': startTime,\n\t\t'end': endTime\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Historic status for query period: ' + JSON.stringify(response));\n\t\t\tcompileStream();\n\t\t}\n\t});\n}", "function main() {\n\tconsole.log('Abacus iPad App Generator.');\n console.log('Create flat basic styled app from converted spreadhseet.');\n\tDU.displayTag();\n\n\tif(ops.version){\n\t\tprocess.exit();\n\t}\n\n\tif(!ops.repoPath){\n\t\tconsole.error('Missing argument: --repoPath');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif(!ops.engine){\n\t\tconsole.error('Missing argument: --engine');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif (ops.instance){\n\t\tconfig.instance = S(ops.instance).slugify().s;\n\t}\n\n\tif(ops.language){\n\t\tconfig.language = ops.language;\n\t}\n\n\tif(ops.noExtract){\n\t\tconfig.extractEngine = false;\n\t}\n\n\tif(ops.numeric){\n\t\tconfig.usePageNames = false;\n\t}\n\n\t// mandatory arguments\n\tconfig.repoPath = ops.repoPath;\n\tconfig.engineFile = ops.engine;\n\n\t// call extract, pass in config\n\tAG.generate(config);\n}", "async function process_indel_vcf(f){//filename\n let filename = f.replace(\".sam.vcf\", \"\");\n let vcf = await exactSNP.cat(\"/data/\" + f);\n let lines = vcf.split(/\\r?\\n/);\n let summary = \"\";\n // let depDict = await getDepthAll(\"/data/\" + filename + \".bam\");\n for (let line of lines){\n if (line && !line.includes(\"#\")){\n let ss = line.split(/\\t/);\n if (ss[7].includes(\"MM\")){// SNPs\n let ee = ss[7].split(/;/);\n let DP = ee[0].replace(\"DP=\", \"\"); // WT counts\n // let DP = await getDepth(\"/data/\" + filename + \".bam\", ss[0], ss[1]);\n // let DP = depDict[ss[0]][ss[1]];\n let SR = ee[1].replace(\"MMsum=\", \"\"); // all mut alleles counts\n let SRsingle = ee[2].replace(\"MM=\", \"\"); // \"3,5\" for 2 alt alleles\n let pct = (parseInt(SR) / parseInt(DP) * 100).toFixed(1); // percent of mut\n let size = \"0\"; // all SNPs\n summary += [filename, ss[0], ss[1], ss[3], ss[4], DP, SRsingle, pct, size].join('\\t') + \"\\n\";\n } else { // indels\n let DP = ss[7].replace(\"INDEL;DP=\", \"\").split(\";SR=\"); // DP and SR\n // DP[0] = await getDepth(\"/data/\" + filename + \".bam\", ss[0], ss[1]);\n // DP[0] = depDict[ss[0]][ss[1]];\n let pct = (parseInt(DP[1]) / (parseInt(DP[0])) * 100).toFixed(1); // percent of indels\n let size = String(ss[4].length - ss[3].length);\n summary += [filename, ss[0], ss[1], ss[3], ss[4], parseInt(DP[0]), DP[1], pct, size].join('\\t') + \"\\n\";\n }\n }\n }\n return summary;\n}", "async function script() {\n const PAGINATION_LIMIT = 5;\n\n // TODO: First thing script should do is delete all files from project-stats directory to remove deleted projects\n\n // Get all stats data for newrelic and newrelic-experimental orgs\n const results = await generateStatsForOrgs({\n organizations: ORG_REPOS,\n paginationLimit: PAGINATION_LIMIT,\n });\n log.info(`Total fetched repos: ${results.length}`);\n\n const { missingProjects, projectsWhereNoStatsGenerated } = await generateDiff(\n results\n );\n\n // Just logging this for info ATM\n log.info(\n `Projects with generated stats but no corresponding file in src/data/projects: ${missingProjects.length}`\n );\n log.magenta(\n `\\n -- Stats generated, but no corresponding project json file detected --`\n );\n log.red(missingProjects);\n log.magenta(`-----------------------------------------\\n`);\n\n log.info(\n `Projects exist but no stats were generated: ${projectsWhereNoStatsGenerated.length}`\n );\n log.magenta(`\\n -- Projects missing generated stats files --`);\n log.red(projectsWhereNoStatsGenerated);\n log.magenta(`-----------------------------------------`);\n\n return undefined;\n}", "function seo_suite(){\n console.log(declaration('Commencing SEO Suite'));\n SEO_SUITE_ROBOTS.test_robots_txt(ROBOTS_PATH, success, failure);\n SEO_SUITE_META.test_pages_meta(PAGES_PATH, success, failure);\n SEO_SUITE_SITEMAP.test_sitemap_xml(SITEMAP_PATH, success, failure);\n SEO_SUITE_FOUR_OH_FOUR.test_404_html(FOUR_OH_FOUR_PATH, success, failure);\n console.log(declaration('SEO Suite Complete!'));\n}", "function reportBuildStatus() {\n console.info('----\\n==> ✅ Building production completed (%dms).', (Date.now() - global.BUILD_STARTED));\n process.exit(0);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }