query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
This is the placePicker function that does all the work!
function placePicker (whoComes, howMuch, whatDo) { //This is the big honkin' array that houses the choices var choiceList = [ { "placeName": "Broad St Diner", "numPeople": "me", "pricePoint": "low", "activityType": "dinner" }, { "placeName": "Midtown III", "numPeople": "me", "pricePoint": "low", "activityType": "dinner" }, { "placeName": "Oregon Diner", "numPeople": "me", "pricePoint": "low", "activityType": "dinner" }, { "placeName": "Teri's", "numPeople": "we", "pricePoint": "low", "activityType": "dinner" }, { "placeName": "Silk City", "numPeople": "we", "pricePoint": "low", "activityType": "dinner" }, { "placeName": "Tom Jones Restaurant", "numPeople": "we", "pricePoint": "low", "activityType": "dinner" }, { "placeName": "South Street Diner", "numPeople": "us", "pricePoint": "low", "activityType": "dinner" }, { "placeName": "Melrose Diner", "numPeople": "us", "pricePoint": "low", "activityType": "dinner" }, { "placeName": "West Chester Diner", "numPeople": "us", "pricePoint": "low", "activityType": "dinner" }, { "placeName": "Penrose Diner", "numPeople": "me", "pricePoint": "mid", "activityType": "dinner" }, { "placeName": "Darling's Diner", "numPeople": "me", "pricePoint": "mid", "activityType": "dinner" }, { "placeName": "Aki", "numPeople": "me", "pricePoint": "mid", "activityType": "dinner" }, { "placeName": "The Continental", "numPeople": "we", "pricePoint": "mid", "activityType": "dinner" }, { "placeName": "The Cantina", "numPeople": "we", "pricePoint": "mid", "activityType": "dinner" }, { "placeName": "El Rey", "numPeople": "we", "pricePoint": "mid", "activityType": "dinner" }, { "placeName": "SideCar", "numPeople": "us", "pricePoint": "mid", "activityType": "dinner" }, { "placeName": "Trolley Car Cafe", "numPeople": "us", "pricePoint": "mid", "activityType": "dinner" }, { "placeName": "Marathon", "numPeople": "us", "pricePoint": "mid", "activityType": "dinner" }, { "placeName": "Morimoto", "numPeople": "me", "pricePoint": "high", "activityType": "dinner" }, { "placeName": "Parc", "numPeople": "me", "pricePoint": "high", "activityType": "dinner" }, { "placeName": "Fork", "numPeople": "me", "pricePoint": "high", "activityType": "dinner" }, { "placeName": "Le Bec Fin", "numPeople": "we", "pricePoint": "high", "activityType": "dinner" }, { "placeName": "LaCroix", "numPeople": "we", "pricePoint": "high", "activityType": "dinner" }, { "placeName": "Los Catrines Tequilas", "numPeople": "we", "pricePoint": "high", "activityType": "dinner" }, { "placeName": "Koo Zee Doo", "numPeople": "us", "pricePoint": "high", "activityType": "dinner" }, { "placeName": "Chima Brazilian Steakhouse", "numPeople": "us", "pricePoint": "high", "activityType": "dinner" }, { "placeName": "Butcher and Singer", "numPeople": "us", "pricePoint": "high", "activityType": "dinner" }, { "placeName": "El Bar", "numPeople": "me", "pricePoint": "low", "activityType": "drinks" }, { "placeName": "Locust Bar", "numPeople": "me", "pricePoint": "low", "activityType": "drinks" }, { "placeName": "The Druid's Keep", "numPeople": "me", "pricePoint": "low", "activityType": "drinks" }, { "placeName": "The Dive Bar", "numPeople": "we", "pricePoint": "low", "activityType": "drinks" }, { "placeName": "McGillin's", "numPeople": "we", "pricePoint": "low", "activityType": "drinks" }, { "placeName": "Paddy's", "numPeople": "we", "pricePoint": "low", "activityType": "drinks" }, { "placeName": "Kung Fu Necktie", "numPeople": "us", "pricePoint": "low", "activityType": "drinks" }, { "placeName": "Tattoed Mom", "numPeople": "us", "pricePoint": "low", "activityType": "drinks" }, { "placeName": "JR's South Philly", "numPeople": "us", "pricePoint": "low", "activityType": "drinks" }, { "placeName": "Graffiti Bar", "numPeople": "me", "pricePoint": "mid", "activityType": "drinks" }, { "placeName": "Eulogy", "numPeople": "me", "pricePoint": "mid", "activityType": "drinks" }, { "placeName": "Fergie's", "numPeople": "me", "pricePoint": "mid", "activityType": "drinks" }, { "placeName": "Tria", "numPeople": "we", "pricePoint": "mid", "activityType": "drinks" }, { "placeName": "National Mechanics", "numPeople": "we", "pricePoint": "mid", "activityType": "drinks" }, { "placeName": "P.O.P.E.", "numPeople": "we", "pricePoint": "mid", "activityType": "drinks" }, { "placeName": "Prohibition", "numPeople": "us", "pricePoint": "mid", "activityType": "drinks" }, { "placeName": "Monk's", "numPeople": "us", "pricePoint": "mid", "activityType": "drinks" }, { "placeName": "Good Dog", "numPeople": "us", "pricePoint": "mid", "activityType": "drinks" }, { "placeName": "Emmanuelle", "numPeople": "me", "pricePoint": "high", "activityType": "drinks" }, { "placeName": "Jamonera", "numPeople": "me", "pricePoint": "high", "activityType": "drinks" }, { "placeName": "Tinto", "numPeople": "me", "pricePoint": "high", "activityType": "drinks" }, { "placeName": "The Ranstead Room", "numPeople": "we", "pricePoint": "high", "activityType": "drinks" }, { "placeName": "Bar Ferdinand", "numPeople": "we", "pricePoint": "high", "activityType": "drinks" }, { "placeName": "XIX", "numPeople": "we", "pricePoint": "high", "activityType": "drinks" }, { "placeName": "Voltage Cafe", "numPeople": "us", "pricePoint": "high", "activityType": "drinks" }, { "placeName": "Xochitl", "numPeople": "us", "pricePoint": "high", "activityType": "drinks" }, { "placeName": "Cuba Libre", "numPeople": "us", "pricePoint": "high", "activityType": "drinks" }, { "placeName": "Union Transfer", "numPeople": "me", "pricePoint": "low", "activityType": "activity" }, { "placeName": "Johnny Brenda's", "numPeople": "me", "pricePoint": "low", "activityType": "activity" }, { "placeName": "The Rusty Nail", "numPeople": "me", "pricePoint": "low", "activityType": "activity" }, { "placeName": "Magic Gardens", "numPeople": "we", "pricePoint": "low", "activityType": "activity" }, { "placeName": "Philly Improv Theater", "numPeople": "we", "pricePoint": "low", "activityType": "activity" }, { "placeName": "ComedySportz", "numPeople": "we", "pricePoint": "low", "activityType": "activity" }, { "placeName": "The Legendary Dobbs", "numPeople": "us", "pricePoint": "low", "activityType": "activity" }, { "placeName": "Danger Danger", "numPeople": "us", "pricePoint": "low", "activityType": "activity" }, { "placeName": "The Grape Room", "numPeople": "us", "pricePoint": "low", "activityType": "activity" }, { "placeName": "The Tin Angel", "numPeople": "me", "pricePoint": "mid", "activityType": "activity" }, { "placeName": "The Troc", "numPeople": "me", "pricePoint": "mid", "activityType": "activity" }, { "placeName": "Ritz Bourse", "numPeople": "me", "pricePoint": "mid", "activityType": "activity" }, { "placeName": "Lucky Strike", "numPeople": "we", "pricePoint": "mid", "activityType": "activity" }, { "placeName": "World Cafe Live", "numPeople": "we", "pricePoint": "mid", "activityType": "activity" }, { "placeName": "Club Polaris", "numPeople": "we", "pricePoint": "mid", "activityType": "activity" }, { "placeName": "Shampoo/Nocturne", "numPeople": "us", "pricePoint": "mid", "activityType": "activity" }, { "placeName": "North Bowl", "numPeople": "us", "pricePoint": "mid", "activityType": "activity" }, { "placeName": "Barcade", "numPeople": "us", "pricePoint": "mid", "activityType": "activity" }, { "placeName": "The Actor's Center", "numPeople": "me", "pricePoint": "high", "activityType": "activity" }, { "placeName": "Tower Theatre", "numPeople": "me", "pricePoint": "high", "activityType": "activity" }, { "placeName": "Stay Home and Burn Money", "numPeople": "me", "pricePoint": "high", "activityType": "activity" }, { "placeName": "Rumor", "numPeople": "we", "pricePoint": "high", "activityType": "activity" }, { "placeName": "Kimmel Center", "numPeople": "we", "pricePoint": "high", "activityType": "activity" }, { "placeName": "Opera Philadelphia", "numPeople": "we", "pricePoint": "high", "activityType": "activity" }, { "placeName": "Skirmish Paintball", "numPeople": "us", "pricePoint": "high", "activityType": "activity" }, { "placeName": "Laser Pink Floyd", "numPeople": "us", "pricePoint": "high", "activityType": "activity" }, { "placeName": "Get in the Van! We're going to Burning Man!", "numPeople": "us", "pricePoint": "high", "activityType": "activity" } ]; //This is the area that choices get pushed to //This is also what resets the array, because it lives inside the function var deciderArray = []; //This is how for loops work var i = 0; for (i=0; i < choiceList.length; i++) { //This takes the passed variables and passes them through this big fat equation if ((choiceList[i].numPeople == whoComes) && (choiceList[i].pricePoint == howMuch) && (choiceList[i].activityType == whatDo)) { //This is the array that gets populated by the previous equation deciderArray.push(choiceList[i].placeName); } } //console.log(deciderArray); //This randomizes your decisions for you var decision = deciderArray[Math.floor(Math.random() * deciderArray.length)]; //This returns your decision! //console.log(decision); $("<p>" + decision + "</p>").appendTo("#decisionDiv"); }
[ "function handleEditPlace() {\n\t$('main').on('click','.edit-place-button', function(event) {\n\t\tconst placeId = $(this).data('id');\n\t\tconst tripId = $(this).data('trip');\n\t\tshowPlaceDetailsToEdit(tripId, placeId);\n\t})\n}", "function autoCompleteForPickupLocation(element){\r\t\tvar inputPickupLocation = element;\r\t\t//var inputDropoffLocation = element;\r\t\t\r\t\t//Autocomplete for pickup location \r\t\tvar mapForPickupLocation = new google.maps.Map(inputPickupLocation, {\r\t\t\tcenter: {lat: 37.1, lng: -95.7},\r\t\t\tzoom: 13\r\t\t});\r\r\t\tvar autoCompleteForPickupLocation = new google.maps.places.Autocomplete(inputPickupLocation);\r\t\tautoCompleteForPickupLocation.bindTo('bounds', mapForPickupLocation);\r\t\tautoCompleteForPickupLocation.setComponentRestrictions({country: \"us\"});\r\t\t\r\t\t\r\t\t//Autocomplete for Dropoff location \r\t\t/* var mapForDropoffLocation = new google.maps.Map(inputDropoffLocation, {\r\t\t\tcenter: {lat: 37.1, lng: -95.7},\r\t\t\tzoom: 13\r\t\t});\r\r\t\tvar autoCompleteForDropoffLocation = new google.maps.places.Autocomplete(inputDropoffLocation);\r\t\tautoCompleteForDropoffLocation.bindTo('bounds', mapForDropoffLocation);\r\t\tautoCompleteForDropoffLocation.setComponentRestrictions({country: \"us\"}); */\r\t}", "function createMarker(place, map) {\n var infowindow = new google.maps.InfoWindow();\n const newrequest = {\n placeId: place.place_id,\n fields: [\"name\", \"formatted_address\", \"place_id\", \"geometry\",\"website\",\"opening_hours\",\"formatted_phone_number\",\"business_status\"],\n };\n const newservice = new google.maps.places.PlacesService(map);\n \n\n const bounds = new google.maps.LatLngBounds();\n const placesList = document.getElementById(\"places\");\n \n const image = {\n url: \"http://maps.google.com/mapfiles/ms/micons/restaurant.png\",\n size: new google.maps.Size(71, 71),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(17, 34),\n scaledSize: new google.maps.Size(25, 25),\n };\n\n const marker =new google.maps.Marker({\n map,\n icon: image,\n title: place.name,\n position: place.geometry.location,\n });\n\n \n\n marker.addListener(\"click\", () => {\n map.setZoom(17);\n map.setCenter(marker.getPosition());\n\n newservice.getDetails(newrequest, (newplace, newstatus) => {\n if (newstatus === google.maps.places.PlacesServiceStatus.OK) {\n google.maps.event.addListener(marker, \"click\", function () {\n infowindow.setContent(\n \"<div><strong>\" +\n newplace.name +\n \"</strong><br><br>\" +\n \"Business Status: \" +\n newplace.business_status +\n \"<br>\" +\n \"<br>\" +\n newplace.formatted_address +\n \"</div><br>\"+\n \"Opening Hours: \" +\n newplace.opening_hours.weekday_text +\n \"<br>\" +\n \"<br>\" +\n \"Phone: \" +\n newplace.formatted_phone_number +\n \"<br>\"+\n \"<br>\" +\n \"<a href =\" +newplace.website +\" >Check Us Out Online</a>\"+\n \"<br>\" \n );\n \n infowindow.open(map, this);\n });\n }\n });\n\n });\n\n //Places Buttons\n const placesbutton = document.createElement(\"button\");\n placesbutton.textContent = place.name;\n placesbutton.setAttribute(\"class\", \"m-1 btn btn-warning\");\n placesbutton.onclick = function(){\n map.setZoom(17);\n map.setCenter(marker.getPosition());\n infowindowpopup(newservice, newrequest, infowindow, map, marker);\n \n };\n placesList.appendChild(placesbutton);\n bounds.extend(place.geometry.location);\n\n}", "function searchPlace(){\n var search = new google.maps.places.PlacesService(map);\n var request = {\n keyword: [searchType],\n location: map.getCenter(),\n rankBy: google.maps.places.RankBy.DISTANCE\n }\n search.nearbySearch(request, function(data, status){\n if(status == google.maps.places.PlacesServiceStatus.OK){\n loc = data[0].name;\n add = data[0].vicinity;\n rating = data[0].rating;\n latitude = data[0].geometry.location.k;\n longitude = data[0].geometry.location.D;\n\n var placeLoc = data[0].geometry.location;\n var marker = new google.maps.Marker({ map: map, position: data[0].geometry.location});\n google.maps.event.addListener(marker, 'click', function() {\n infowindow.setContent(data[0].name);\n infowindow.open(map, this); //google\n });\n // var loc = data[0].place_id;\n\n }\n });\n\n}", "function initAutocomplete() {\n const map = new google.maps.Map(document.getElementById(\"map\"), {\n center: { lat: -33.8688, lng: 151.2195 },\n zoom: 13,\n mapTypeId: \"roadmap\",\n });\n // Create the search box and link it to the UI element.\n const input = document.getElementById(\"pac-input\");\n const searchBox = new google.maps.places.SearchBox(input);\n \n map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);\n // Bias the SearchBox results towards current map's viewport.\n map.addListener(\"bounds_changed\", () => {\n searchBox.setBounds(map.getBounds());\n });\n \n let markers = [];\n \n // Listen for the event fired when the user selects a prediction and retrieve\n // more details for that place.\n searchBox.addListener(\"places_changed\", () => {\n const places = searchBox.getPlaces();\n \n if (places.length == 0) {\n return;\n }\n \n // Clear out the old markers.\n markers.forEach((marker) => {\n marker.setMap(null);\n });\n markers = [];\n \n // For each place, get the icon, name and location.\n const bounds = new google.maps.LatLngBounds();\n \n places.forEach((place) => {\n if (!place.geometry || !place.geometry.location) {\n console.log(\"Returned place contains no geometry\");\n return;\n }\n \n const icon = {\n url: place.icon,\n size: new google.maps.Size(71, 71),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(17, 34),\n scaledSize: new google.maps.Size(25, 25),\n };\n \n // Create a marker for each place.\n markers.push(\n new google.maps.Marker({\n map,\n icon,\n title: place.name,\n position: place.geometry.location,\n })\n );\n if (place.geometry.viewport) {\n // Only geocodes have viewport.\n bounds.union(place.geometry.viewport);\n } else {\n bounds.extend(place.geometry.location);\n }\n });\n map.fitBounds(bounds);\n });\n }", "selectPlace() {\n let objectPlace = map.arrayMap[randomNb(0, (mapWidth * mapHeight) - 1)];\n //Verify if there is not player/weapon/wall/potion on selected place\n if ((objectPlace.navigable === false) ||\n (objectPlace.player.active === true) ||\n (objectPlace.weapon.active === true) ||\n (objectPlace.potion.active === true)) {\n this.selectPlace();\n } else {\n this.coordX = objectPlace.coordX;\n this.coordY = objectPlace.coordY;\n }\n }", "_placeChange() {\n if (DEBUG) {\n console.log('[*] ' + _name + ':_placeChange ---');\n }\n\n // Store place in LocalStoreApi\n LocalStoreApi.setItem('place', getPlaceState());\n\n this.setState({\n place: getPlaceState()\n });\n }", "function afterButtonPress(data)\n{\n\t// Initialising blank strings as the output and outputCities variables\n\tlet output = \"\";\n\tlet outputCities = \"\";\n\n\t//Code to alert the user if they choose a country with only one airport\n\tif(data.length == 1)\n\t{\n\t\talert(\"This country only has one airport, try another\");\n\t\tlocation.reload();\n\t}\n\n\t//Puts the airport ID and name into the relevant arrays\n\tfor (let i = 0; i < data.length; i++)\n { \n\t\tcitiesArray.push(data[i].name);\n\t\tcitiesIdArray.push(data[i].airportId);\n\t}\n\t\n\t// For the length of the cities array, the following code will run\n\tfor(let i = 0; i < citiesArray.length; i++)\n\t{\n\t\t// An option for the city will be added to the dropdown list \n\t\toutputCities += `<option value = \"${citiesArray[i]}\">`\n\t}\n\n\t// Defining the output\n\toutput = `<div>\n\t\t\t\t<p style = font-size:15px>Type Your City Below</p>\n\t\t\t\t<input list = \"cities\" name = \"citiesName\" id = \"citiesId\">\n\t\t\t\t<datalist id = \"cities\">\n\t\t\t\t\t<div id = citiesDropdown></div>\n\t\t\t\t\t${outputCities}\n\t\t\t\t</datalist>\n\t\t\t</div>\n\t\t\t<br>\n\t\t\t<div>\n\t\t\t\t<button class=\"mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect\" style = \"color:black;\" id = \"startPlanTrip\" onclick = \"toSelectingLocations()\">\n\t\t\t\t\tStart Planning Trip\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t\t<br>\n\t\t\t<div>\n\t\t\t\t<button class=\"mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect\" style = \"color:black;\" onclick = \"cancel()\">\n\t\t\t\t\tCancel\n\t\t\t\t</button>\n\t\t\t</div>`;\n\n\tdocument.getElementById(\"replaceOnPress\").innerHTML = output;\n}", "function handleUpdatePlace() {\n\t$('main').on('submit','.edit-place-form', function(event) {\n\t\tevent.preventDefault();\n\t\tconst placeId = $(this).data('id');\n\t\tconst tripId = $(this).data('trip');\n\t\tconst toUpdateData = {\n\t\t\tid: placeId,\n\t\t\tname: $('.place-name-entry').val(),\n\t\t\tdate: $('.form-place-date').val(),\n\t\t\tdescription: $('#place-desc').val()\n\t\t}\n\t\tupdatePlace(tripId, toUpdateData);\n\t})\n}", "function getGooglePlacesData2(results, status) {\n //\n if (status == google.maps.places.PlacesServiceStatus.OK) {\n //\n for (var i = 0, l = results.length; i < l; i++) {\n //\n placesObj = {\n id: \"\",\n name: \"\",\n status: \"\",\n openNow: \"\",\n rating: \"\",\n userRatingTotal: \"\",\n priceLevel: \"\",\n photos: [],\n types: [],\n };\n //\n // Place data\n //\n placesObj.id = results[i].place_id;\n placesObj.name = results[i].name;\n placesObj.status = results[i].business_status;\n // placesObj.openNow = results[i].opening_hours.isOpen;\n placesObj.rating = results[i].rating;\n placesObj.userRatingTotal = results[i].user_ratings_total;\n placesObj.priceLevel = results[i].price_level;\n //\n // Photos\n //\n for (var j = 0, m = results[i].photos.length; j < m; j++) {\n //\n photoObj = {\n url: \"\",\n };\n //\n photoObj.url = results[i].photos[j].html_attributions[0];\n //\n placesObj.photos.push(photoObj);\n //\n }\n //\n // Types\n //\n for (var k = 0, n = results[i].types.length; k < n; k++) {\n //\n typeObj = {\n name: \"\",\n };\n //\n typeObj.name = results[i].types[k];\n //\n placesObj.types.push(typeObj);\n //\n }\n //\n places.push(placesObj);\n //\n }\n //\n renderGooglePlacesData();\n //\n }\n //\n}", "function populateOrigin() {\n\n var selectedCode = getCountryCode();\n\n\t$(\"#vocationPlannerOriginDropDown\").empty(); \n\n\t//Added for AC-226\n var k=1;\n\tif(customOrgAdded){\n\t\tfor(var i=0; i<orgNameSet.length; i++){\n $(\"#vocationPlannerOriginDropDown\").append('<li class=\"origin-dd-row\" data-value=' + orgCodeSet[i] + '>' + '<a href=\"javascript:\" aria-label=\"' +orgNameSet[i] +' '+k+' of '+ orgNameSet.length +'\">' + orgNameSet[i] + '</a>' + '</li>');\n\t\t\tk++;\n\t\t}\n\t} else {\n\t\tif(preferredOriginCodes != null && preferredOriginCodes != undefined && preferredOriginNames != null && preferredOriginNames != undefined){\n var preferredOriginCodesArr = preferredOriginCodes.split(\",\");\n var preferredOriginNamesArr = preferredOriginNames.split(\",\");\n if(preferredOriginCodesArr.length == preferredOriginNamesArr.length){\n for(var i=0; i<preferredOriginCodesArr.length; i++) {\n //Added for AC-226\n $(\"#vocationPlannerOriginDropDown\").append('<li class=\"origin-dd-row\" data-value=' + preferredOriginCodesArr[i] + '>' + '<a href=\"javascript:\" aria-label=\"'+ preferredOriginNamesArr[i].replace(/-/g, \",\") +' '+k+' of '+ preferredOriginNamesArr.length+'\">' + preferredOriginNamesArr[i].replace(/-/g, \",\") + '</a>' + '</li>');\n k++;\n //End: AC-226\n }\n }\n }\n\t}\n\t$(\"#vocationPlannerOriginDropDown li a\").on(\"click\", function() {\n\n var currentOrigin = getOriginCookie() || defaultOriginCode;\n \n origVal = $(this).text();\n var selectedOriginCode = $(this).parent().attr('data-value');\n \n //destVal = $('#vocationPlannerDestSelection').text();\n //alignDD(origVal,destVal);\n $(orgSeletion).text(origVal);\n \n if (browser.indexOf(\"chrome\") > 0 || browser.indexOf(\"mobile\") > 0) {\n $(orgDD).addClass('hide-element');\n }\n //Added for AC-226\n $(\"#vocationPlannerOrigButton\").attr(\"aria-expanded\", false);\n $(\"#updateselect\").html('You have selected '+origVal);\t\n //End: AC-226\n \n if (!customOrgAdded && currentOrigin != selectedOriginCode) {\n \n $(\".countryName\").text(origVal);\n\t\t\tneworgCity = origVal;\n \n $(\".countryName\").attr(\"data-org-code\", selectedOriginValue);\n \n writeOriginCookie(selectedOriginCode);\n\n\n $(document).trigger(\"originChange\", [selectedOriginCode]);\n \n \n } else if(customOrgAdded){\n onPageLoad = true; \n initVacPlanner(selectedOriginCode);\n }\n // getData();\n });\n}", "function newPlaceSuccess(data){\n $('#newPlaceForm input').val('');\n allNeighborhoods.forEach(function (neighborhood){\n if(neighborhood._id === neighborhoodId){\n neighborhood.places.push(data);\n }\n });\n\n renderSpecificNeighborhood();\n }", "function randomLocation(suggestedLocations) {\n var obj_keys = Object.keys(suggestedLocations);\n var ran_key = obj_keys[Math.floor(Math.random() * obj_keys.length)];\n selectedLocation = suggestedLocations[ran_key];\n console.log(selectedLocation);\n console.log(\"Selected restaurant latitude is \" + selectedLocation.position[0]);\n console.log(\"Selected restaurant longitude is \" + selectedLocation.position[1]);\n restLat = selectedLocation.position[0];\n restLong = selectedLocation.position[1];\n restName = selectedLocation.title;\n $(\"#selectedLoc\").html(restName);\n console.log(\"restaurant Name is \" + restName);\n //calling map and lyft function here to populate it with\n //chosen restaurant co-ordinates\n loadMapAndLyft();\n }", "function selectLocation(){\r\n currentlySelectedGridId = getRiskAddtlExposureListGrid();\r\n var xmlData = getXMLDataForGridName(currentlySelectedGridId);\r\n var addtlExpAddrId = xmlData.recordset(\"CADDRESSID\").value;\r\n if(isEmpty(addtlExpAddrId)){\r\n addtlExpAddrId = -1;\r\n }\r\n var selAddrUrl = getAppPath() + \"/policymgr/selectAddress.do?\" + commonGetMenuQueryString() + \"&type=RISK\"\r\n + \"&entityId=\" + xmlData.recordset(\"CRISKENTITYID\").value\r\n + \"&riskBaseRecordId=\" + xmlData.recordset(\"CRISKBASERECORDID\").value\r\n + \"&riskStatus=\" + xmlData.recordset(\"CRISKSTATUS\").value\r\n + \"&isFromExposure=Y&addtlExpAddrId=\"+addtlExpAddrId;\r\n var divPopupId = getOpenCtxOfDivPopUp().openDivPopup(\"\", selAddrUrl, true, true, \"\", \"\", 600, 500, \"\", \"\", \"\", false);\r\n}", "function placeSearch(lat, lng) {\n var query = \"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\" + lat + \",\" + lng + \"&radius=50000&type=park&keyword=kyak&key=AIzaSyDAhGg64lKOYPK-6jEMFKqQlc2TSTHTI2M\";\n\n $.ajax({\n url: query,\n method: \"GET\"\n }).done(function(response) {\n console.log(response);\n var placeId = response.results[0].place_id;\n console.log(placeId);\n\n placeDetail(placeId);\n });\n}", "function displayRestaurantInfo(place) {\n $('#review-window').show();\n $('#add-review-button').show();\n restaurantInfoContainer.show();\n $('#name').text(place.name);\n $('#address').text(place.vicinity);\n $('#telephone').text(place.formatted_phone_number);\n\n var reviewsDiv = $('#reviews');\n var reviewHTML = '';\n reviewsDiv.html(reviewHTML);\n if (place.reviews) {\n if (place.reviews.length > 0) {\n for (var i = 0; i < place.reviews.length; i += 1) {\n var review = place.reviews[i];\n var avatar;\n if (place.reviews[i].profile_photo_url) {\n avatar = place.reviews[i].profile_photo_url;\n } else {\n avatar = 'img/avatar.svg';\n }\n reviewHTML += `<div class=\"restaurant-reviews\">\n <h3 class=\"review-title\">\n <span class=\"user-avatar\" style=\"background-image: url('${avatar}')\"></span>`;\n if (place.rating) {\n reviewHTML += `<span id=\"review-rating\" class=\"rating\">${placeRating(review)}</span>`;\n }\n reviewHTML += ` <h3>${place.reviews[i].author_name}</h3>\n </h3>\n <p> ${place.reviews[i].text} </p>\n </div>`;\n reviewsDiv.html(reviewHTML);\n }\n }\n }\n\n /********** Street view using Google API **********/\n\n /*** Add Street View ***/\n var streetView = new google.maps.StreetViewService();\n streetView.getPanorama({\n location: place.geometry.location,\n radius: 50\n }, processStreetViewData);\n\n var streetViewWindow = $('#street-view-window');\n var photoContainer = $('#photo');\n var photoWindow = $('#see-photo');\n var seeStreetView = $('#see-street-view');\n photoContainer.empty();\n photoContainer.append('<img class=\"place-api-photo\" ' + 'src=\"' + createPhoto(place) + '\"/>');\n\n streetViewWindow.show();\n if (photo) {\n photoWindow.show();\n } else {\n photoWindow.hide();\n }\n\n function processStreetViewData(data, status) {\n if (status === 'OK') {\n var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'));\n panorama.setPano(data.location.pano);\n panorama.setPov({\n heading: 440,\n pitch: 0\n });\n panorama.setVisible(true);\n\n } else {\n photoWindow.hide();\n streetViewWindow.hide();\n photoContainer.show();\n }\n }\n }", "function handleDeletePlace() {\n\t$('main').on('click','.delete-place-button', function(event) {\n\t\tconst placeId = $(this).data('id');\n\t\tconst tripId = $(this).data('trip');\n\t\tdeletePlace(tripId, placeId);\n\t})\n}", "function callNearBySearchAPI() {\n //\n city = new google.maps.LatLng(coordinates.lat, coordinates.long);\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: city,\n zoom: 15,\n });\n //\n request = {\n location: city,\n radius: \"5000\", // meters\n type: [\"restaurant\"],\n // openNow: true,\n fields: [\n \"name\",\n \"business_status\",\n \"icon\",\n \"types\",\n \"rating\",\n \"reviews\",\n \"formatted_phone_number\",\n \"address_component\",\n \"opening_hours\",\n \"geometry\",\n \"vicinity\",\n \"website\",\n \"url\",\n \"address_components\",\n \"price_level\",\n \"reviews\",\n ],\n };\n //\n service = new google.maps.places.PlacesService(map);\n service.nearbySearch(request, getGooglePlacesData);\n //\n}", "initSearchBox()\n {\n var startInput = document.getElementById('source');\n var destinationInput = document.getElementById('destination');\n start = new google.maps.places.SearchBox(startInput);\n destination = new google.maps.places.SearchBox(destinationInput);\n start.setBounds(map.getBounds());\n destination.setBounds(map.getBounds());\n // Bias the SearchBox results towards current map's viewport.\n map.addListener('bounds_changed', function() {\n start.setBounds(map.getBounds());\n destination.setBounds(map.getBounds());\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if the given tiles are neighbors
function isNeighbors(tile1, tile2) { var left1 = parseInt(window.getComputedStyle(tile1).left); var top1 = parseInt(window.getComputedStyle(tile1).top); var left2 = parseInt(window.getComputedStyle(tile2).left); var top2 = parseInt(window.getComputedStyle(tile2).top); if (Math.abs(left1 + top1 - left2 - top2) == 100) { return true; } else { return false; } }
[ "isNeighbor(tile1, tile2) {\n if (tile1 == tile2) { return false; } //a tile cannot be a neighbor to itself\n if (tile1.y == tile2.y && tile1.x == tile2.x-1) { return this.NEIGHBOR_RIGHT; }\n if (tile1.y == tile2.y && tile1.x == tile2.x+1) { return this.NEIGHBOR_LEFT; }\n\n let odd = tile1.y % 2;\n if (tile1.y == tile2.y+1 && tile1.x == tile2.x+1-odd) { return this.NEIGHBOR_UPLEFT; } // upper left\n if (tile1.y == tile2.y+1 && tile1.x == tile2.x -odd) { return this.NEIGHBOR_UPRIGHT; } // upper right\n if (tile1.y == tile2.y-1 && tile1.x == tile2.x+1-odd) { return this.NEIGHBOR_DOWNLEFT; } // lower left\n if (tile1.y == tile2.y-1 && tile1.x == tile2.x -odd) { return this.NEIGHBOR_DOWNRIGHT; } // lower right\n //any other tile is not a neighbor\n return false;\n }", "function checkAdjacentTiles(x1, y1) {\n if((x1>=0)&&(y1>=0)&&(x1<columns)&&(y1<rows)) //Verify if coordinates do not fall outside of the gridMatrix.\n return gridMatrix[x1+y1*columns];\n}", "__hasOccupiedNeighbours(colour, x, y){\n if (x - 1 > -1) {\n if(this.board.get(x-1, y) === colour){\n return true;\n }\n }\n if (y - 1 > -1) {\n if(this.board.get(x, y-1) === colour){\n return true;\n }\n }\n if (x + 1 < this.size) {\n if(this.board.get(x+1, y) === colour){\n return true;\n }\n }\n if (y + 1 < this.size) {\n if(this.board.get(x, y+1) === colour){\n return true;\n }\n }\n return false;\n }", "isValidMoveNew(row, column) {\n if (!isInBoundaries(row, column)) {\n return false;\n }\n if (!this.tileSet.hasTileAt(row, column)) {\n return false;\n }\n var dx = [1, 0, -1, 0];\n var dy = [0, 1, 0, -1];\n let thisTile = this.tileSet.getTileAt(row, column);\n for (var i = 0; i < 4; ++i) {\n // if the given cell's i'th neighbour has the same color as this\n // cell, then this move is valid\n var neighbourTile = this.tileSet.getTileAt(row + dx[i], column + dy[i]);\n if (thisTile.equalTo(neighbourTile)) {\n return true;\n }\n }\n // if we have not found any neighbours with the same color, then the\n // move is not valid\n return false;\n }", "function conway(cell, neighbors) {\n if (numberOfLiveNeighbors(neighbors) >= 2\n){\n return true;\n }\n return false;\n}", "tilesAreEqual(tile1, tile2) {\n return tile1 && tile2 && tile1.x == tile2.x && tile1.y == tile2.y;\n }", "areDiagonallyAdjacent(tile1, tile2) {\r\n // Dos tiles son diagonalmente adyacentes si están separados por una distancia de una\r\n // unidad en ambos ejes. Si la distancia en cualquiera de los ejes fuera 0 ya no sería\r\n // una adyacencia diagonal, y si la distancia fuera más de 1 ya no sería una adyacencia.\r\n return Math.abs(tile1.x - tile2.x) == 1 && Math.abs(tile1.y - tile2.y) == 1;\r\n }", "function isNeighbour(cell){\n\tvar neighbourArr = [emptyCell+4, emptyCell-4, emptyCell+1,emptyCell-1];\n\tif(contains(cell,neighbourArr))\n\t\treturn true;\n\telse\n\t\treturn false;\n}", "function is_next_to_blank(tile) {\n var isAdjacent = false;\n if (is_below_blank(tile) || is_above_blank(tile) || is_to_the_left_of_blank(tile) || is_to_the_right_of_blank(tile))\n {\n isAdjacent = true;\n }\n return isAdjacent;\n}", "function canPass(xTile, yTile) {\n\tif (xTile < 0 || yTile < 0 || xTile >= gridWidth || yTile >= gridHeight) return false;\n\treturn !grid[xTile + yTile * gridWidth].blocks;\n}", "function isAt(x, y){\n for(var i = 0; i < tileArray.length; i++){\n if(tileArray[i]._x == x && tileArray[i]._y == y){\n return true;\n }\n }\n return false;\n }", "hasReachedDestination() {\r\n\t\tvar destinationTiles = this.levelGrid.getDestination();\r\n\t\tfor (var i = 0; i < destinationTiles.length; i++) {\r\n\t\t\tvar destinationRow = destinationTiles[i].row;\r\n\t\t\tvar destinationColumn = destinationTiles[i].column;\r\n\t\t\tif ( this.currentTileRow === destinationRow\r\n\t\t\t\t && this.currentTileColumn === destinationColumn ) {\r\n\t\t\t\tthis.speed = 0;\r\n\t\t\t\treturn true;\r\n\t\t\t} \t\t\r\n\t\t}\r\n\t\treturn false;\r\n\t}", "function validTile(x, y) {\n if (x > (xmax - 1) || (x < 0)) {\n return false;\n }\n\n if (y > (ymax - 1) || (y < 0)) {\n return false;\n }\n return true;\n}", "function checkSurroundingTiles (tileStats) {\n var stats;\n\n tileStats.surroundingTiles.forEach(function (coordinates) {\n if (false === $('#' + coordinates).hasClass('empty')\n && false === $('#' + coordinates).hasClass('flagged')\n && -1 === $('#' + coordinates).attr('class').indexOf('surrounding')) {\n\n stats = analyzeTile(document.getElementById(coordinates));\n\n if (false === stats.isMine && 0 < stats.surroundingMines.length) {\n // If the tile is not a mine and there are surrounding mines set a number\n $('#' + coordinates).addClass('empty surrounding-' + stats.surroundingMines.length + '-mines');\n } else if (false === stats.isMine && 0 === stats.surroundingMines.length) {\n // If the tile is not a mine and there are no surrounding mines set it empty\n // and check surrounding tiles to continue cascade\n $('#' + coordinates).addClass('empty');\n checkSurroundingTiles(stats);\n } else {\n // It's a mine!!!\n $('#' + coordinates).addClass('mine');\n }\n }\n });\n }", "function areAdjacent(squareOne, squareTwo) { \n if (squareOne.x < squareTwo.x + 2 &&\n squareOne.x > squareTwo.x - 2 &&\n squareOne.y < squareTwo.y + 2 &&\n squareOne.y > squareTwo.y - 2) {\n return true;\n } else {\n return false;\n }\n}", "equals(grid) {\n if (this.height !== grid.height) { return false; }\n if (this.width !== grid.width) { return false; }\n\n let ans = true;\n for (let r = 0; r < this.height; r++) {\n for (let c = 0; c < this.width; c++) {\n if (this.get(r,c) !== grid.get(r,c)) { ans = false; }\n }\n }\n return ans;\n }", "function checkGrid(rover) {\r\n\tif ( \trover.position[0] < 0 || rover.position[0] > 9 ) {\r\n if (rover.position[0] < 0) {\r\n myRover.position[0]++;\r\n }\r\n if (rover.position[0] > 9) {\r\n myRover.position[0]--;\r\n }\r\n\t\treturn true;\r\n\t}\r\n\telse if (rover.position[1] < 0 || rover.position[1] > 9) {\r\n if (rover.position[1] < 0) {\r\n myRover.position[1]++;\r\n }\r\n if (rover.position[1] > 9) {\r\n myRover.position[1]--;\r\n }\r\n\t\treturn true;\r\n\t}\r\n\telse {\r\n\t\treturn false;\r\n\t}\r\n}", "function checkGrid(board, y, x, num) {\n\tconst baseX = 3 * Math.floor(x / 3);\n\tconst baseY = 3 * Math.floor(y / 3);\n\n\tfor (let i = 0; i < 3; i++) {\n\t\tfor (let j = 0; j < 3; j++) {\n\t\t\tif (!(j + baseY == y && i + baseX == x) && board[j + baseY][i + baseX] == num) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}", "function isMovable(tile) {\n var currentX = tile.style.left;\n var currentY = tile.style.top;\n if (currentX == emptyX && Math.abs(parseInt(currentY) - parseInt(emptyY)) == SIZE ||\n currentY == emptyY && Math.abs(parseInt(currentX) - parseInt(emptyX)) == SIZE){\n return true;\n } else {\n return false;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stores debugging data for this property binding on first template pass. This enables features like DebugElement.properties.
function savePropertyDebugData(tNode, lView, propName, tData, nativeOnly) { var lastBindingIndex = lView[BINDING_INDEX] - 1; // Bind/interpolation functions save binding metadata in the last binding index, // but leave the property name blank. If the interpolation delimiter is at the 0 // index, we know that this is our first pass and the property name still needs to // be set. var bindingMetadata = tData[lastBindingIndex]; if (bindingMetadata[0] == INTERPOLATION_DELIMITER) { tData[lastBindingIndex] = propName + bindingMetadata; // We don't want to store indices for host bindings because they are stored in a // different part of LView (the expando section). if (!nativeOnly) { if (tNode.propertyMetadataStartIndex == -1) { tNode.propertyMetadataStartIndex = lastBindingIndex; } tNode.propertyMetadataEndIndex = lastBindingIndex + 1; } } }
[ "getPropertyDetail() {\n return {\n propertyData: PropertyDataStore.currentPropertyDetail\n };\n }", "function init() {\n angular.forEach(railsBindings, function(value, key) {\n railsData[key] = toResource(value);\n });\n }", "track() {\n const snapShot = () => {\n return JSON.stringify(this.fields.reduce((obj, key) => {\n obj[key] = this.ctx[key];\n return obj;\n }, {}))\n }\n\n const changeListener = () => {\n this.hasFieldChanges = this.oldState !== snapShot();\n }\n\n this.oldState = snapShot();\n changeListener();\n observe(this.ctx, changeListener);\n }", "function storeOriginalDisabledProperty(element) {\n //capture original disabled property value\n if (element.data('original-disabled') === undefined) {\n element.data(\"original-disabled\", element.prop(\"disabled\"));\n }\n}", "function setupDebug(){\n debug = new DEBUGTOOL(false,null,[8,8,16]);\n}", "refreshEvidenceObjBinding () {\n let temp = this.evidence;\n this.evidence = {};\n this.evidence = temp;\n }", "_setData() {\n this._global[this._namespace] = this._data;\n }", "setProps(props) {\n if ('debug' in props) {\n this._debug = props.debug;\n } // A way for apps to add data to context that can be accessed in layers\n\n\n if ('userData' in props) {\n this.context.userData = props.userData;\n } // New layers will be processed in `updateLayers` in the next update cycle\n\n\n if ('layers' in props) {\n this._nextLayers = props.layers;\n }\n\n if ('onError' in props) {\n this.context.onError = props.onError;\n }\n }", "Dump() {\n console.log(\"Turtle params:\", this.currentParams);\n }", "function DebugController($scope, $localStorage)\n{\n $scope.debugEnabled = angular.isDefined($localStorage.debugEnabled);\n}", "function updateDom (isTemplate) {\n addLog('updateDom() was triggered');\n _.forEach(scope.dataBoundNodes, function (node) {\n //find the matching object and set the node value\n node.value = setGetObjPath(false, node.attributes['data-bind'].value);\n });\n }", "_setDataToUI() {\n const data = this._data;\n if (data === undefined) return;\n console.log('View#_setDataToUI', this);\n\n if (data instanceof Object) {\n eachEntry(data, ([name, val]) => this._setFieldValue(name, val));\n } else {\n this._setVal(this.el, data);\n }\n }", "reloadVariables() {\n this.firstTime = this.firstTimeCopy;\n this.userString = this.userStringCopy;\n this.sepString = this.sepStringCopy;\n this.running = this.runningCopy;\n this.compareDisplay = this.compareDisplayCopy;\n this.compToPref = this.compToPrefCopy;\n this.speed = this.speedCopy;\n }", "function checkBindings () {\n addLog('checkBindings() was Triggered');\n // if dataBoundNodes has elements in it, loop through each one and\n // see if there's a variable for it\n scope.dataBoundNodes = _.chain(scope.dataBoundNodes)\n .filter(function (node) {\n var found,\n path = node.attributes['data-bind'].value;\n\n found = setGetObjPath(false, path);\n\n return typeof found !== 'undefined';\n })\n .value();\n }", "init() {\n let localStore = model.getLocalStore();\n if (_.isNull(localStore)) {\n localStorage.setItem('vanillaPress', JSON.stringify(jsonData));\n localStore = model.getLocalStore();\n }\n }", "debug(entry) {\n this.write(entry, 'DEBUG');\n }", "function formFieldPopulation(){\n\t\tvar detailsObject = JSON.parse(localStorage.getItem('details'));\n\t\tif(detailsObject != null){\n\t\t\tconsole.log(detailsObject.firstname);\n\t\t\t$('#firstname').val(detailsObject.firstname);\n\t\t\t$('#lastname').val(detailsObject.lastname);\n\t\t\t$('#email').val(detailsObject.email);\n\t\t\t$('#phone').val(detailsObject.phone);\n\t\t\tconsole.log(detailsObject);\n\t\t}\n\t}", "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 }", "constructor() {\n\t\tthis._prettyJson = false;\n\t}", "function storeInitTouchData(event){\n\t\t\n\t\tvar mousePos = g_functions.getMousePosition(event);\n\t\t\n\t\tg_temp.startMouseX = mousePos.pageX;\n\t\t\n\t\t//debugLine(\"startx:\" + g_temp.startMouseX, true, true);\n\t\t\n\t\tg_temp.startMouseY = mousePos.pageY;\n\t\t\n\t\tg_temp.lastMouseX = g_temp.startMouseX;\n\t\tg_temp.lastMouseY = g_temp.startMouseY;\n\t\tg_temp.startTime = jQuery.now();\n\t\t\n\t\tvar arrTouches = g_functions.getArrTouches(event);\t\t\n\t\tg_temp.startArrTouches = g_functions.getArrTouchPositions(arrTouches);\n\t\t\n\t\tvar objPos = g_functions.getElementSize(g_objInner);\n\t\t\n\t\tg_temp.startPosx = objPos.left;\n\t\t\n\t\tg_temp.isInitDataValid = true;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An exception class to be instantiated when a provided index is out of bounds
function IndexOutOfBoundsException(index){ this.value = index; this.message = 'is out of bounds.'; this.toString = function(){ return this.value + ' ' + this.message; }; }
[ "function checkIndex(inputs, index) {\n if (!isValidIndex(inputs, index))\n throw new Error(`Expected an array index < ${inputs.length}, got ${index}`);\n}", "function offsetShouldThrowOnInvalidElement() {\n expect(() => {\n element.offset(\"invalid\")\n }).toThrow(\n new TypeError(\"Invalid element: 'invalid'\"))\n}", "function CHOOSE(index) {\n\n // Return `#NA!` if index or items are not provided.\n if (!index || arguments.length - 1 === 0) {\n return error$2.na;\n }\n\n // Return `#VALUE!` if index is less than 1 or greater than 254.\n if (index < 1 || index > 254) {\n return error$2.value;\n }\n\n // Return `#VALUE!` if number of items is less than index.\n if (arguments.length - 1 < index) {\n return error$2.value;\n }\n\n // Return the item.\n return arguments.length <= index - 1 + 1 ? undefined : arguments[index - 1 + 1];\n}", "function sizeShouldThrowOnInvalidElement() {\n expect(() => {\n element.size(\"invalid\")\n }).toThrow(\n new TypeError(\"Invalid element: 'invalid'\"))\n}", "handleOffsetOutOfRangeError() {\n const offsetInstance = new Kafka.Offset(this.kafkaClient);\n let latestOffset;\n offsetInstance.fetchLatestOffsets([this.topicName], (error, offsets) => {\n if (error) {\n throw new errors_1.InternalServerError(error.message, error.stack || '');\n }\n latestOffset = offsets[this.topicName][this.partitionNumber];\n });\n this.consumer.setOffset(this.topicName, this.partitionNumber, latestOffset);\n }", "function at(v, index) /* forall<a> (v : vector<a>, index : int) -> maybe<a> */ {\n var idx = $std_core._int_to_int32(index);\n var _x2 = (((idx < 0)) || (((((v).length)) <= idx)));\n if (_x2) {\n return Nothing;\n }\n else {\n return Just((v)[idx]);\n }\n}", "function $f3ca2f81d086a59c11fe377edef4f$var$isValidArrayIndex(val) {\n var n = parseFloat(String(val));\n return n >= 0 && Math.floor(n) === n && isFinite(val);\n }", "getAt(idx) {\n try {\n if (idx >= this.length || idx < 0) throw new Error('Index is invalid!');\n return this._getNode(idx).val;\n } catch (e) {\n console.warn(e);\n }\n }", "function outOfBounds(neighborRow, neighborCol) {\n return neighborRow < 0 ||\n neighborRow > board.length - 1 ||\n neighborCol < 0 ||\n neighborCol > board[0].length - 1\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}", "chk_underflow(n) {\n\t\tn = n || 1;\n\t\tif (this.stack.length < n) {\n\t\t\tthrow new Error('Stack underflow' + (n === 1 ? '.'\n\t\t\t\t\t: `, expected at least ${n} elements.`));\n\t\t}\n\t}", "function nth(arr,num) {\n//Check to see if array is not too short \n if(arr.length <= 2){\n //If array is too short, return null \n return null; \n }\n //If array is long enough, return value of the proposed index\n return arr[arr.length-num]\n}", "function outOfBounds(i, j) {\n return (i < 0 || i >= gridHeight) || (j < 0 || j >= gridWidth);\n}", "function Exception(message){if(message===void 0){message=undefined;}var _this=_super.call(this,message)||this;_this.message=message;return _this;}", "function checkTheIndexes(arr, index, result){\n\t//arr[[minusElement, index],[-2,2]]\n\tvar i;\n\tvar j;\n\tfor(i = 0; i < arr.length; i++){\n\t\tfor(j = 0; j < arr.length; j++){\n\t\t\tif(arr[i][1] === index){\n\t\t\t\treturn arr[i][0]\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}", "function HamburgerException(errorMessage) {\r\n this.errorMessage = errorMessage;\r\n}", "function parseIdx(p, n){ // PathPoints, number for index\n var len = p.length;\n if( p.parent.closed ){\n return n >= 0 ? n % len : len - Math.abs(n % len);\n } else {\n return (n < 0 || n > len - 1) ? -1 : n;\n }\n }", "findIndex(pos, end, side = end * Far, startAt = 0) {\n if (pos <= 0)\n return startAt;\n let arr = end < 0 ? this.to : this.from;\n for (let lo = startAt, hi = arr.length;;) {\n if (lo == hi)\n return lo;\n let mid = (lo + hi) >> 1;\n let diff = arr[mid] - pos || (end < 0 ? this.value[mid].startSide : this.value[mid].endSide) - side;\n if (mid == lo)\n return diff >= 0 ? lo : hi;\n if (diff >= 0)\n hi = mid;\n else\n lo = mid + 1;\n }\n }", "findInvalidSlot(addr) {\n var entries = this.sets[addr.idx];\n\n for(var i = 0; i < entries.length; i++) {\n if(entries[i].valid == false) {\n return i;\n }\n }\n\n return null;\n }", "function wrap(index) {\n return (index >= imgCount) ? (index - imgCount) : (index < 0) ? index + imgCount : index;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Actual update of content. Doesn't fade out old content because that's done in the displayNextPerson function which then calls this in a callback from that fadeOut method
function displayUpdate() { var person = peopleArray[index]; var newXposition = Math.random() * (document.documentElement.clientWidth - 360); var newYposition = Math.random() * (document.documentElement.clientHeight - 300); $content = $('.container').add('#speechArrow'); $($content).hide(); $('.container').html("<p class=\"shoutout\">\"" + person.shoutout + "\"</p><p class=\"name\"> -- " + person.name + "</p>"); $('.container').css('left', newXposition); $('.container').css('top', newYposition); $('#speechArrow').css('left', newXposition + 40); $('#speechArrow').css('top', newYposition - 0); $($content).fadeIn({ queue: false }); }
[ "function displayNextPerson(next) {\n // console.log('displayNextPerson called with index', index);\n\n if (next) { // update index to next person in the array\n // if we're at the end of the array, loop back around to the front\n if (index == peopleArray.length - 1) {\n index = 0;\n } else {\n index++;\n }\n } else { // update index to previous person in the array\n // if we're at the beginning of the array, loop back around to the end\n if (index === 0) {\n index = peopleArray.length - 1;\n } else {\n index--;\n }\n }\n\n var person = peopleArray[index];\n\n // fade out the content, then call the displayUpdate function to update the content and fade it in \n $('.container').add('#speechArrow').fadeOut({\n queue: false,\n complete: displayUpdate\n });\n\n // empty the #trackingDiv, then add the appropriate data\n $('#trackingDiv').html(\"<p class=\\\"trackingP\\\">\" + (index + 1) + \"/\" + peopleArray.length + \"</p>\");\n\n // call the timeout function, so that the carousel will update if another button isn't clicked within 10 seconds\n setTimeout(carouselTimeOut, 10000);\n}", "function updateDisplay(){\n\t\t// Update any changes the Hero element\n\t\t$(\".hero\").html(\n\t\t\t\t\"<p>\" + hero.name + \"</p>\" +\n\t\t\t\t\"<img src='\" + hero.img + \"' >\" +\n\t\t\t\t\"<p> HP: \" + hero.hitPoints + \"</p>\"\n\t\t);\n\t\t// Update any changes the Defender element\n\t\t$(\".defender\").html(\n\t\t\t\t\"<p>\" + defender.name + \"</p>\" +\n\t\t\t\t\"<img src='\" + defender.img + \"' >\" +\n\t\t\t\t\"<p> HP: \" + defender.hitPoints + \"</p>\"\n\t\t);\n\t}", "onAfterShow(msg) {\r\n super.onAfterShow(msg);\r\n this.parent.update();\r\n }", "function revealEnd() {\n this.index = this.items.length;\n for (var i=0; i<this.items.length; i++) {\n var para = this.items[i];\n para.style.visibility = \"visible\";\n }\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 displayLoadedFlixerContent(response) {\r\n if (typeof (response['newAvailableContentList']) != \"undefined\") {\r\n var $flixelBackgrounds = $(\"#available-flixel-backgrounds\");\r\n var $loadMoreButtonCountainer = $(\"#load-more-content-container\");\r\n \r\n var currentContent = {\r\n \"currentImage\": response.currentImage\r\n , \"currentImageResolution\": response.currentImageResolution\r\n , \"currentVideo\": response.currentVideo\r\n , \"currentVideoResolution\": response.currentVideoResolution\r\n , \"currentTheme\": response.currentThemeId\r\n , \"videoContentAvailableResolutions\": response.videoContentAvailableResolutions\r\n , \"flixelContentAvailableResolutions\": response.flixelContentAvailableResolutions\r\n };\r\n var favoriteThemes = getFavoriteThemesObject();\r\n for (var i in response.newAvailableContentList) {\r\n var flixelTheme = response.newAvailableContentList[i];\r\n flixelTheme['installed'] = false;\r\n flixelTheme['hasDownloadedImage'] = false;\r\n flixelTheme['hasDownloadedVideo'] = false;\r\n flixelTheme['favorite'] = checkThemeIsFavorite(flixelTheme, favoriteThemes);\r\n addAvailableContentToList($flixelBackgrounds, flixelTheme, flixelBackgroundType, currentContent);\r\n }\r\n if (getFlixelContentCurrentPage() < (getFlixelTotalPagesCount() - 1)) {\r\n if (response.newAvailableContentList.length) {\r\n var $icon = $loadMoreButtonCountainer.find(\".glyphicon\");\r\n if ($icon && $icon.hasClass(\"rotating\")) $icon.removeClass(\"rotating\");\r\n $loadMoreButtonCountainer.on(\"click\", loadMoreFlixelContentButtonHandler);\r\n }\r\n else{\r\n hideMoreButton(response);\r\n }\r\n }\r\n else{\r\n hideMoreButton(response);\r\n }\r\n }\r\n}", "slideNext() {\n super.slideNext();\n this.slides[this.lastSlide].style.opacity = 0;\n this.slides[this._index].style.opacity = 1;\n }", "function fadeInMsg(msg) {\n\t//fade in message with Jquery action\t\n\t$(\"#preview p:first\").css(\"opacity\", 0);\n\t$(\"#preview p:first\").delay(400);\n \t$(\"#preview p:first\").html(msg);\n \t$(\"#preview p:first\").animate({\n \t\topacity: 1\n \t\t\t}, 400);\t\n \t$(\"#directions\").hide();\n \t\t\t\n}", "function displayNextProfile(){\r\n \r\n //We need to iterate with profiles.next().value as the profile variable is init(set) to the iterator ;so we need to call next here for the current profile:\r\n const currentProfile = profiles.next().value;\r\n console.log(currentProfile);\r\n///Display next profile data\r\nif(currentProfile !== undefined){\r\n //Display Data (except Image)\r\n document.getElementById('profileDisplay').innerHTML = `\r\n <ul class=\"list-group\">\r\n <li class=\"list-group-item\">Name: ${currentProfile.name}</li>\r\n <li class=\"list-group-item\">Age: ${currentProfile.age}</li>\r\n <li class=\"list-group-item\">Gender: ${currentProfile.gender}</li>\r\n <li class=\"list-group-item\">Preference: ${currentProfile.gender} looking for ${currentProfile.lookingfor}</li>\r\n <li class=\"list-group-item\"> Location: ${currentProfile.location}</li>\r\n </ul>\r\n `;\r\n //Display Image\r\n document.getElementById('imageDisplay').innerHTML = `<img src=\"${currentProfile.image}\">`\r\n}else{\r\n////If No more profiles\r\nwindow.location.reload(); ///reload the page to start again\r\n}\r\n\r\n}", "function afterChange() {\n\n\t\t\t// Make current page inactive\n\t\t\tcurrentContentPage.classList.remove('active');\n\t\t\thelper.setData(currentContentPage, 'currentcontent', false);\n\n\t\t\t// Set the title\n\t\t\telems.dashboardContentTitle.innerHTML = helper.getData(newPage, 'title');\n\n\t\t\tdocument.title = `${pageTitleBase} - ${helper.getData(newPage, 'title')}`;\n\t\t\tcallback();\n\t\t}", "function initAboutContent() {\n aboutMeJson.age = getExactAge().toFixed(10);\n $(\"#aboutMeJson\").html(JSON.stringify(aboutMeJson, undefined, 2));\n\n if (currentPage == \"about\") {\n setTimeout(function () {\n initAboutContent();\n }, 10);\n }\n}", "function tasklistFadeOutResultText(){\n \n $( \"#tableWrapper\" ).animate({\n opacity: 1\n }, 1000, function() {\n if (!tasksFetched)\n tasklistFadeInResultText();\n });\n}", "function displayFinalSentence() {\n enableMainButtons(100);\n setTimeout(() => {\n finalSentence.classList.add('final-fade-in'); // Fade-in final sentence\n gameWrapper.classList.add('game-fade-in'); // Fade-in the game UI\n btnRules.classList.add('display-btn-rules');\n }, FINAL_SENTENCE_APPARITION_DELAY);\n}", "function update_user_elements() {\n $('.echo-item-authorName, .echo-item-avatar').each( function() {\n if(!$(this).hasClass('initialized')) {\n var container = $(this).parents('.echo-item-container');\n \n var userName = container.find('.echo-item-authorName').text();\n var userID = container.find('.echo-item-metadata-userID .echo-item-metadata-value').text();\n \n var url = '/echo2-users.php?user_id=' + UrlEncoderTool.encode(userID) + '&d=' + new Date().getTime();\n \n $(this).html($('<a></a>').attr('href',url).attr('title', 'user page: ' + userName).addClass('echo-linkColor').html($(this).html()));\n $(this).find('img').removeAttr('height');\n $(this).addClass('initialized');\n }\n });\n }", "function yesBtnFade() {\n clickedRestart = true;\n let fadeThirdContent = setInterval(function () {\n if (thirdContent.style.opacity > 0) {\n thirdContent.style.opacity -= 0.04;\n } else {\n clearInterval(fadeThirdContent);\n thirdContentOpacity = 0;\n thirdContent.style.display = \"none\";\n }\n }, 30);\n setTimeout(readTimer, 1500);\n}", "function updateGuessedDisplay() {\n $('#guessed0').html(currentGuess[0]);\n $('#guessed1').html(currentGuess[1]);\n $('#guessed2').html(currentGuess[2]);\n $('#guessed3').html(currentGuess[3]);\n updateDisplay();\n }", "function _updateElement() {\n\t\tself.observer.disconnect();\n\t\tself.element.innerHTML = self.history[self.index];\n\t\tself.observer.observe(self.element, OBSERVER_CFG);\n\t}", "function reinitializeAppropriateDisplay() {\n updateEventVars(getNow());\n displayOnPage();\n }", "updateVisibility() {\n const {\n fadeStages,\n currentLifetime: time,\n opacityAmountPerFrame: amount,\n } = this\n\n if (time >= fadeStages.invisible) {\n this.graphics.alpha = 0\n return\n }\n\n if (time >= fadeStages.fadeIn) {\n this.graphics.alpha += amount\n return\n }\n\n if (time <= fadeStages.fadeOut) {\n this.graphics.alpha -= amount\n return\n }\n\n this.graphics.alpha = constants.PARTICLE_OPACITY\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the profiler row
getProfilerRow(request) { return this.application.profiler.create('http:request', { request_id: request.id(), url: request.url(), method: request.method(), }); }
[ "get row() {\n return INDEX2ROW(getTop()) + 1;\n }", "function row(numRow) {\n return numRow * ROW + ROW_OFFSET;\n}", "profilerData() {\n return {\n type: this.relation.type,\n model: this.relation.model.name,\n pivotTable: this.relation.pivotTable,\n relatedModel: this.relation.relatedModel().name,\n };\n }", "getTipp(row, column, tippHolder){\r\n\t\treturn tippHolder.filter((tipp)=> tipp.row == row && tipp.column == column)[0];\r\n\t}", "get rowIndex() {\n return INDEX2ROW(getTop());\n }", "get userProfile() {\n return spPost(ProfileLoaderFactory(this, \"getuserprofile\"));\n }", "function row(matrix, i) {\n return matrix[i]\n}", "getRow(row, returnAsObject = false) {\n if (returnAsObject) {\n return this.cells[row].map(obj => obj);\n } else {\n return this.cells[row].map(obj => obj.value);\n }\n }", "function get_datadict_from_tblRow(tblRow) {\n //console.log( \" ==== get_datadict_from_tblRow ====\");\n //console.log( \"tblRow\", tblRow);\n\n// get student_pk and studsubj_pk from tr_clicked.id\n const pk_int = get_attr_from_el_int(tblRow, \"data-pk\");\n const [middle_index, found_dict, compare] = b_recursive_integer_lookup(student_rows, \"id\", pk_int);\n const data_dict = (!isEmpty(found_dict)) ? found_dict : null;\n\n return data_dict;\n } // get_datadict_from_tblRow", "visitPipe_row_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "getRowObject(i) {\n const row = this.rows[i];\n const obj = {};\n for (const i in this.fieldNames) {\n const fieldName = this.fieldNames[i];\n const fieldValue = row[i];\n obj[fieldName] = fieldValue;\n }\n return obj;\n }", "function insightFromRow (row) {\n return {\n id: row.iid,\n title: row.title,\n url: row.url,\n author: row.author,\n creator_id: row.creator_id,\n type: row.type,\n date: row.date,\n active: row.active,\n tags: row.tid ? [tagFromRow(row)] : []\n };\n}", "getRowIndex(): number {\n const { table, row } = this;\n const rows = table.nodes;\n\n return rows.findIndex(x => x === row);\n }", "function dataForTable(response) {\n return response;\n }", "function getLastRecordData() {\n\n var conn = new mssql.ConnectionPool(dbconfig);\n var result = [];\n var requst = new mssql.Request(conn);\n conn.connect(function (err) {\n if (err) {\n console.log(err);\n return;\n }\n requst.query(\"SELECT TOP 1 * FROM Suppliers ORDER BY SupplierID DESC\", function (err, records) {\n if (err) {\n console.log(err);\n return;\n }\n else {\n for (var id in records.recordset) {\n result.push({\n SupplierID: records.recordset[id].SupplierID,\n });\n\n }\n }\n conn.close();\n });\n });\n return result;\n}", "function index_to_row(i) { return Math.floor(i / cache_row_size); }", "drawToolRow() {\n let $Div = $('<div />').attr({ id: 'top-row'});\n let $MineCount = $('<input/>').attr({ type: 'text', id: 'mine-count', name: 'mine-count', readonly: true}).val(25);\n let $Timer = $('<input/>').attr({ type: 'text', id: 'timer', name: 'timer', readonly: true}).val('0000');\n let $GridSize = $('<input/>').attr({ type: 'text', id: 'grid-size', name: 'grid-size'}).val(15); // value is the size of the grid. Always a square\n let $Reset = $('<input />').attr({ type: 'button', id: 'reset-button'}).val('Reset').addClass('reset-button');\n let $Music= $('<input />').attr({ type: 'button', id: 'music-button'}).val('Music').addClass('music-button');\n let $gameScreen = $('#game-screen');\n\n $Div.append($MineCount).append($Timer).append($GridSize).append($Reset).append($Music);\n $gameScreen.prepend($Div);\n \n }", "function getColumnaMedio(){\n let opcionesaux = getOpciones();\n let auxCol = getBetter(opcionesaux);\n return auxCol\n}", "function getStatementRows() {\n var rows = [];\n for (const statement of state.statements) {\n rows.push({\n id: statement.Id,\n statementName: statement.StatementName, \n status: statement.Status,\n createdAt: simpleDateString(statement.CreatedAt),\n updatedAt: simpleDateString(statement.UpdatedAt),\n sql: statement.QueryString\n });\n }\n return rows;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read programmed reminder info
function handleReadRoutineReminderInfo() { // Payload base var localBasePayload = fbBasePayload; var senderID = getSenderID(); var reminderURL = routine; return admin.database().ref('pazienti/' + senderID + '/promemoria/routine/').once('value').then((snapshot) => { let reminders = snapshot.val(); console.log('snapshot.val() : ' + JSON.stringify(reminders)); if(reminders !== null) { let i; let elements = []; for (i=0; i < reminders.length; i++) { let thDescription = snapshot.child(i.toString() + '/descrizione').val(); let thRipetizione = snapshot.child(i.toString() + '/ripetizione').val(); let thTime = function () { let time = snapshot.child(i.toString() + '/orario').val(); return time.slice(11, 13); }; let giorni = snapshot.child(i.toString() + '/giorni').val(); let title = thDescription + ': ' + thRipetizione + ' volte a settimana'; let subtitle = 'Giorni: ' + giorni + '\n' + 'Alle ore ' + thTime(); elements[i] = element(title, reminderURL, subtitle); localBasePayload.facebook.attachment.payload.elements[i] = elements[i]; } agent.add(new Payload('FACEBOOK', localBasePayload, {rawPayload: true, sendAsMessage: true})); } else { let question = 'Non mi hai parlato delle tue routine. Vuoi aggiungerle?'; let suggestions = [ "Routine", 'Più tardi', "No grazie", "Cancella" ]; setSuggestions(question, suggestions, senderID); } }); }
[ "function checkReminder(){\n\tfor (i = 0; i < timesAdvices.length; i++) {\n\t\t\tif (currentTime >= timesAdvices[i] && currentTime >= herinneringsTijd && currentTime < timesAdvices[i+1] && dietAdviceValues[i] == false && herinnering == true) {\n\t\t\t\t\n\t\t\t\tif (dietAdviceNames[i] == advies) {\n\t\t\t\t\t//set today active again\n\t\t\t\t\tchangeDay(0);\t\n \n\t\t\t\t\tfindMostSuitableMessage(\"reminder\", moments[i]);\n\t\t\t\t\t//console.log(currentTime, herinneringsTijd, i);\n\t\t\t\t\t//console.log(\"reminder send\");\n\t\t\t\t}\n\t\t\t\telse { //het is tijd voor een nieuw onderdeel in het dieet, dus de reminder wordt uitgezet\n\t\t\t\t\therinnering = false;\n\t\t\t\t\tcheckNotification();\n\t\t\t\t}\n\t\t\t}\n\t}\n}", "function startUnreadAlarm(){\n\n\tconsole.log(\"[UNREAD UPDATE] Creating alarm\");\n\tvar alarm = chrome.alarms.create(\"unreadAlarm\", {\n\t\twhen:0,\n\t\tperiodInMinutes: 5\n\t});\n\n\tconsole.log(\"[ALARMS] Adding event to alarm\");\n\tchrome.alarms.onAlarm.addListener(function(alarm) {\n\t\tif(alarm.name == \"unreadAlarm\"){\n\t\t\tcheckUnread();\n\t\t}\n\n\t\tif(alarm.name == \"updateAlarm\"){\n\t\t\tupdateFeeds();\n\t\t}\n\t});\n\tlistAlarms();\n}", "get recurrenceInfo()\n\t{\n\n\t\tif (this._newRecurrenceInfo !== undefined) {\n\t\t\treturn this._newRecurrenceInfo;\n\t\t}\n\n\t\tif (this._recurrenceInfo !== undefined) {\n\t\t\treturn this._recurrenceInfo;\n\t\t}\n\n\t\treturn this._calEvent.recurrenceInfo;\n\t}", "function runAddReminder() {\n var reminderString = getReminderInput();\n var reminderItem = createReminderItem(reminderString);\n addReminderItemToList(reminderItem);\n clearReminderInput();\n}", "_loadNotifications() {\n try {\n this.currentNotifications = fs.readJSONSync(path.join(this.dataDir, 'notifications.json'));\n } catch (e) {\n // at first start its normal, that we cannot read notifications, so just an info\n this.log.debug(`${this.logPrefix} Could not read notifications.json: ${e.message}`);\n }\n }", "function today () {\n const filePath = util.currentLogPath();\n return io.read(filePath).then(chunks => {\n const dataObjs = binary.parseChunks(chunks);\n return dataObjs.map(dataObj => parseData(dataObj));\n });\n}", "function GetDataReminder() {\r\n var req = GetXmlHttp();\r\n req.onreadystatechange = function() { \r\n if (req.readyState == 4) { \r\n if(req.status == 200) {\r\n var json = JSON.parse(req.responseText);\r\n SetDataReminder(json);\r\n }\r\n else { notif(req.status ? req.statusText : 'Запрос не удался', 'Ошибка', 'warning'); return;}\r\n }\r\n }\r\n var json_string = JSON.stringify({'function':'get_list_reminder'});\r\n SendRequest(req, json_string);\r\n}", "get reminderDueBy()\n\t{\n\t\treturn this._reminderDueBy;\n\t}", "function getPatientInfo(qr) {\n setQr(qr);\n alert(\"The patient: \" + qr + \" has been scanned and added into the system\");\n }", "function MidiFile(data) {\n function readChunk(stream) {\n var id = stream.read(4);\n var length = stream.readInt32();\n return {\n 'id': id,\n 'length': length,\n 'data': stream.read(length)\n };\n }\n \n var lastEventTypeByte;\n \n function readEvent(stream) {\n var event = {};\n event.deltaTime = stream.readVarInt();\n var eventTypeByte = stream.readInt8();\n if ((eventTypeByte & 0xf0) == 0xf0) {\n /* system / meta event */\n if (eventTypeByte == 0xff) {\n /* meta event */\n event.type = 'meta';\n var subtypeByte = stream.readInt8();\n var length = stream.readVarInt();\n switch(subtypeByte) {\n case 0x00:\n event.subtype = 'sequenceNumber';\n if (length != 2) throw \"Expected length for sequenceNumber event is 2, got \" + length;\n event.number = stream.readInt16();\n return event;\n case 0x01:\n event.subtype = 'text';\n event.text = stream.read(length);\n return event;\n case 0x02:\n event.subtype = 'copyrightNotice';\n event.text = stream.read(length);\n return event;\n case 0x03:\n event.subtype = 'trackName';\n event.text = stream.read(length);\n return event;\n case 0x04:\n event.subtype = 'instrumentName';\n event.text = stream.read(length);\n return event;\n case 0x05:\n event.subtype = 'lyrics';\n event.text = stream.read(length);\n return event;\n case 0x06:\n event.subtype = 'marker';\n event.text = stream.read(length);\n return event;\n case 0x07:\n event.subtype = 'cuePoint';\n event.text = stream.read(length);\n return event;\n case 0x20:\n event.subtype = 'midiChannelPrefix';\n if (length != 1) throw \"Expected length for midiChannelPrefix event is 1, got \" + length;\n event.channel = stream.readInt8();\n return event;\n case 0x2f:\n event.subtype = 'endOfTrack';\n if (length != 0) throw \"Expected length for endOfTrack event is 0, got \" + length;\n return event;\n case 0x51:\n event.subtype = 'setTempo';\n if (length != 3) throw \"Expected length for setTempo event is 3, got \" + length;\n event.microsecondsPerBeat = (\n (stream.readInt8() << 16)\n + (stream.readInt8() << 8)\n + stream.readInt8()\n )\n return event;\n case 0x54:\n event.subtype = 'smpteOffset';\n if (length != 5) throw \"Expected length for smpteOffset event is 5, got \" + length;\n var hourByte = stream.readInt8();\n event.frameRate = {\n 0x00: 24, 0x20: 25, 0x40: 29, 0x60: 30\n }[hourByte & 0x60];\n event.hour = hourByte & 0x1f;\n event.min = stream.readInt8();\n event.sec = stream.readInt8();\n event.frame = stream.readInt8();\n event.subframe = stream.readInt8();\n return event;\n case 0x58:\n event.subtype = 'timeSignature';\n if (length != 4) throw \"Expected length for timeSignature event is 4, got \" + length;\n event.numerator = stream.readInt8();\n event.denominator = Math.pow(2, stream.readInt8());\n event.metronome = stream.readInt8();\n event.thirtyseconds = stream.readInt8();\n return event;\n case 0x59:\n event.subtype = 'keySignature';\n if (length != 2) throw \"Expected length for keySignature event is 2, got \" + length;\n event.key = stream.readInt8(true);\n event.scale = stream.readInt8();\n return event;\n case 0x7f:\n event.subtype = 'sequencerSpecific';\n event.data = stream.read(length);\n return event;\n default:\n // console.log(\"Unrecognised meta event subtype: \" + subtypeByte);\n event.subtype = 'unknown'\n event.data = stream.read(length);\n return event;\n }\n event.data = stream.read(length);\n return event;\n } else if (eventTypeByte == 0xf0) {\n event.type = 'sysEx';\n var length = stream.readVarInt();\n event.data = stream.read(length);\n return event;\n } else if (eventTypeByte == 0xf7) {\n event.type = 'dividedSysEx';\n var length = stream.readVarInt();\n event.data = stream.read(length);\n return event;\n } else {\n throw \"Unrecognised MIDI event type byte: \" + eventTypeByte;\n }\n } else {\n /* channel event */\n var param1;\n if ((eventTypeByte & 0x80) == 0) {\n /* running status - reuse lastEventTypeByte as the event type.\n eventTypeByte is actually the first parameter\n */\n param1 = eventTypeByte;\n eventTypeByte = lastEventTypeByte;\n } else {\n param1 = stream.readInt8();\n lastEventTypeByte = eventTypeByte;\n }\n var eventType = eventTypeByte >> 4;\n event.channel = eventTypeByte & 0x0f;\n event.type = 'channel';\n switch (eventType) {\n case 0x08:\n event.subtype = 'noteOff';\n event.noteNumber = param1;\n event.velocity = stream.readInt8();\n return event;\n case 0x09:\n event.noteNumber = param1;\n event.velocity = stream.readInt8();\n if (event.velocity == 0) {\n event.subtype = 'noteOff';\n } else {\n event.subtype = 'noteOn';\n }\n return event;\n case 0x0a:\n event.subtype = 'noteAftertouch';\n event.noteNumber = param1;\n event.amount = stream.readInt8();\n return event;\n case 0x0b:\n event.subtype = 'controller';\n event.controllerType = param1;\n event.value = stream.readInt8();\n return event;\n case 0x0c:\n event.subtype = 'programChange';\n event.programNumber = param1;\n return event;\n case 0x0d:\n event.subtype = 'channelAftertouch';\n event.amount = param1;\n return event;\n case 0x0e:\n event.subtype = 'pitchBend';\n event.value = param1 + (stream.readInt8() << 7);\n return event;\n default:\n throw \"Unrecognised MIDI event type: \" + eventType\n /* \n console.log(\"Unrecognised MIDI event type: \" + eventType);\n stream.readInt8();\n event.subtype = 'unknown';\n return event;\n */\n }\n }\n }\n \n stream = Stream(data);\n var headerChunk = readChunk(stream);\n if (headerChunk.id != 'MThd' || headerChunk.length != 6) {\n throw \"Bad .mid file - header not found\";\n }\n var headerStream = Stream(headerChunk.data);\n var formatType = headerStream.readInt16();\n var trackCount = headerStream.readInt16();\n var timeDivision = headerStream.readInt16();\n \n if (timeDivision & 0x8000) {\n throw \"Expressing time division in SMTPE frames is not supported yet\"\n } else {\n ticksPerBeat = timeDivision;\n }\n \n var header = {\n 'formatType': formatType,\n 'trackCount': trackCount,\n 'ticksPerBeat': ticksPerBeat\n }\n var tracks = [];\n for (var i = 0; i < header.trackCount; i++) {\n tracks[i] = [];\n var trackChunk = readChunk(stream);\n if (trackChunk.id != 'MTrk') {\n throw \"Unexpected chunk - expected MTrk, got \"+ trackChunk.id;\n }\n var trackStream = Stream(trackChunk.data);\n while (!trackStream.eof()) {\n var event = readEvent(trackStream);\n tracks[i].push(event);\n //console.log(event);\n }\n }\n \n return {\n 'header': header,\n 'tracks': tracks\n }\n}", "function calculateReminder(reminder_id) {\n let query1 = \"SELECT * FROM reminders join users on reminders.user_id = users.id where reminders.id = \"+reminder_id;\n conn.query(query1, (err, reminderData) => {\n if (err) throw err;\n // console.log(reminderData[0])\n var is_weekend = reminderData[0].repeats == \"weekend\" || reminderData[0].repeats == \"all\";\n var repeatDay = is_weekend ? [6,7] : reminderData[0].repeats == \"weekday\" ? [1, 2,3,4,5] : [1, 2,3,4,5,6,7];\n\n let sql =\n \"SELECT * FROM daily_schedules join trips on schedules.trip_id = trips.id where trips.bus_id = \" +\n reminderData[0].bus_id +\n \" and direction = '\" +\n reminderData[0].direction +\n \"' and is_weekend = \" +\n is_weekend +\n \" and stop_id = \" +\n reminderData[0].stop_id +\n \" and time_arrival < '\" +\n reminderData[0].interval_stop +\n \"' and time_arrival > '\" +\n reminderData[0].interval_start +\n \"' \";\n\n console.log(\"SQL: \", sql);\n\n conn.query(sql, (err, results) => {\n if (err) throw err;\n\n console.log(\"RESULTS: \", results);\n\n // kurangin si schedule dengan time_before_arrival\n let dataWithReminderTime = results.map(item => {\n let calculation = calculateReminderTime(\n item.time_arrival,\n reminderData[0].time_before_arrival\n );\n return calculation.remindTime;\n });\n\n let reminderTimeList = [];\n repeatDay.map(day => {\n dataWithReminderTime.map(time => {\n reminderTimeList.push({ day: day, time: time });\n });\n });\n\n console.log(\"REMINDER LIST: \", reminderTimeList);\n dropNotification(reminder_id, addNotification(reminderData[0].reminder_id, token_id, reminderTimeList));\n return dataWithReminderTime;\n });\n });\n}", "ReadFileDates() {\n\n }", "async function BTTloadDBLReminders() {\n let result = await callBTT('get_string_variable', {\n variable_name: 'DBLReminders'\n });\n // debug this, see if it works\n // if BTT save reminders don't exit\n if (result == null) {\n createDefaultReminders();\n } else {\n // convert string text to javascript object for global reminders\n reminders = JSON.parse(result);\n // update UI elements based on loaded reminders\n updateElements();\n };\n\n}", "function readProperties() {\r\n\tlocalStorage.setItem(\"reloaded\", false);\r\n\t$.getJSON(\"manifest.webapp\", function( json ) {\r\n\t\tbaseUrl = json.activities.dhis.href;\r\n\t\t//TODO Update to new version when current DHIS version = 30!\t\t\r\n\t\tapiBaseUrl = baseUrl + \"/api/26\";\t\t\t\t\t\r\n\t})\r\n\t.done(function(){\r\n\t\tqueryUserRoles();\r\n\t});\t\t\r\n}", "function eventInfoPrepper(body){\n var event_id = (body.event_id) ? body.event_id : null;\n var user = (body.user_id) ? body.user_id : null;\n var start = (body.start_datetime) ? body.start_datetime : null;\n var end = (body.end_datetime) ? body.end_datetime : start;\n var title = (body.title) ? body.title : null;\n var notes = (body.notes) ? body.notes : null;\n var isFullDay = (body.isFullDay) ? body.isFullDay : false;\n var stop_date = (body.rep_stop_date) ? body.rep_stop_date : null;\n var day_month = (body.rep_day_month) ? body.rep_day_month : null;\n var day_week = (body.rep_day_week) ? body.rep_day_week : null;\n var event_type = (body.event_type) ? body.event_type : null;\n var amount = (body.amount) ? body.amount : 0;\n var job_id = (body.job_id) ? body.job_id : null;\n\n return {\n event_id : event_id,\n user : user,\n start : start,\n end : end,\n title : title,\n notes : notes,\n all_day : isFullDay,\n stop_date : stop_date,\n day_month : day_month,\n day_week : day_week,\n event_type : event_type,\n amount : amount,\n job_id : job_id\n };\n}", "function extract(addr, userId, callback) {\n \n var addr = decodeURIComponent(addr.trim().replace(\"http://\",\"\").\n replace(\"nusmods.com/timetable/\",\"\"));\n year = addr.substring(0,9),\n sem = addr.substring(13,14);\n semStart = moment(semesterStart(year,sem)),\n tempURL = \"http://api.nusmods.com/\"+year+\"/\"\n +sem+'/modules/CS1010.json',\n tempModCode = \"CS1010\",\n eventInfo = [],\n tempSem = semStart.toDate(); \n modInfos = convert(addr.substring(15).split(\"&\"));\n Calendar.create({\n name: \"NUS \"+year+\"/\"+sem,\n user: userId,\n events: []\n }, function (err,calendar) {\n if(err) { callback(err); }\n async.each(modInfos, function (modInfo, callback){\n tempURL = tempURL.replace(tempModCode,modInfo.ModuleCode); \n tempModCode = modInfo.ModuleCode;\n request({ url: tempURL, json: true}, function (err, res, body) {\n if(err) { callback(err); }\n var modJSON = res.body,\n exam = false;\n for(var y in modJSON.Timetable) {\n semStart = moment(tempSem);\n var lessonType = checkLessonTaken(modJSON.Timetable[y], \n modInfo, modJSON.ModuleCode);\n if(!lessonType)\n continue;\n else{\n calendar.events.push(buildNUSEvent(modJSON,semStart,y));\n }\n if(modJSON.ExamDate !== undefined && exam == false) {\n calendar.events.push(buildNUSExam(modJSON,semStart));\n exam = true;\n }\n }\n callback();\n });\n }, function(err) {\n calendar.save(function (err,calendar) {\n if(err) { callback(err); }\n else callback(null, calendar); \n });\n });\n });\n}", "async getNotes() {\n\t\ttry {\n\t\t\tconst notes = await readFileAsync(\"db/db.json\", \"utf8\");\n\t\t\treturn JSON.parse(notes);\n\t\t} catch (err) {\n\t\t\tthrow err;\n\t\t}\n\t}", "function run_test() {\n let storageCal = getStorageCal();\n\n let item = createEventFromIcalString(\"BEGIN:VEVENT\\r\\n\" +\n \"CREATED:20090603T171401Z\\r\\n\" +\n \"LAST-MODIFIED:20090617T080410Z\\r\\n\" +\n \"DTSTAMP:20090617T080410Z\\r\\n\" +\n \"UID:c1a6cfe7-7fbb-4bfb-a00d-861e07c649a5\\r\\n\" +\n \"SUMMARY:Test\\r\\n\" +\n \"DTSTART:20090603T073000Z\\r\\n\" +\n \"DTEND:20090603T091500Z\\r\\n\" +\n \"RRULE:FREQ=DAILY;COUNT=5\\r\\n\" +\n \"RELATED-TO:RELTYPE=SIBLING:<foo@example.org>\\r\\n\" +\n \"ATTACH:http://www.example.org/\\r\\n\" +\n \"BEGIN:VALARM\\r\\n\" +\n \"ACTION:DISPLAY\\r\\n\" +\n \"TRIGGER;VALUE=DURATION:-PT10M\\r\\n\" +\n \"DESCRIPTION:Mozilla Alarm: Test\\r\\n\" +\n \"END:VALARM\\r\\n\" +\n \"END:VEVENT\");\n // There should be one alarm, one relation and one attachment\n do_check_eq(item.getAlarms({}).length, 1);\n\n // Change the occurrence to another day\n let occ = item.recurrenceInfo.getOccurrenceFor(cal.createDateTime(\"20090604T073000Z\"));\n occ.startDate = cal.createDateTime(\"20090618T073000Z\");\n item.recurrenceInfo.modifyException(occ, true);\n\n // There should still be one alarm, one relation and one attachment\n do_check_eq(item.getAlarms({}).length, 1);\n do_check_eq(item.getRelations({}).length, 1);\n do_check_eq(item.getAttachments({}).length, 1);\n\n // Add the item to the storage calendar and retrieve it again\n storageCal.adoptItem(item, null);\n let retrievedItem;\n storageCal.getItem(\"c1a6cfe7-7fbb-4bfb-a00d-861e07c649a5\", {\n onGetResult: function onGetResult(cal, stat, type, detail, count, items) {\n retrievedItem = items[0];\n },\n onOperationComplete: function() {}\n });\n\n // There should still be one alarm, one relation and one attachment\n do_check_eq(item.getAlarms({}).length, 1);\n do_check_eq(item.getRelations({}).length, 1);\n do_check_eq(item.getAttachments({}).length, 1);\n}", "function getRemindersFromlocalStorage(){\n let reminders\n if(localStorage.getItem('reminders')=== null){\n reminders = []\n }else{\n reminders = JSON.parse(localStorage.getItem('reminders'))\n }\n\n return orderReminders(reminders)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check current state of TuneGenie player
function checkTuneGeniePlayerState(e) { if (e === true) { log('TuneGenie Player is streaming.'); me.start(); return true; } log('TuneGenie Player has stopped.'); me.stop(); return false; }
[ "function is_playing() {\n return player.getPlayerState() == 1;\n}", "function checkGame(){\n\t\tif(victoryCondition){console.log(\"You Won!\");}else{ console.log(\"You lose!\");}\n\t}", "checkKingsStatus(player){\n\t\tlet tile = this.boardMatrix[player.figureList.King[0].positionY][player.figureList.King[0].positionX];\n\t\tfor(let threat of tile.threatenedBy){\n\t\t\tif(player.number !== threat.team) return true;\n\t\t}\n\t\treturn false;\n\t}", "checkGameStatus() {\n if(this.props.player.health <= 0 || this.props.game.level >= 6) {\n this.props.actions.gameOver()\n }\n\n if(this.props.player.xp >= (this.props.game.level * 50)) {\n this.levelUp();\n }\n }", "checkNextGame (){\n\n }", "function choosePlayerState(player) {\n player.state = PLAYER_STATE_RUN\n\n if (player.speedY < -3) {\n player.state = PLAYER_STATE_JUMPING\n } else if (player.speedY > 3) {\n player.state = PLAYER_STATE_FALLING\n }\n\n if (player.isDead) {\n player.state = PLAYER_STATE_DEAD\n }\n}", "playerWins(){ // i2 - put inline\n\t\tif (this.player === activePlayer && playing === false) {\n\t\t\treturn true;\n\t\t}\t}", "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 hasPlayed(id, instance) {\n if (instance.players[id].readyCard === 0){\n return false;\n }\n return true\n}", "function C006_Isolation_Yuki_CheckToEat() {\n\t\n\t// Yuki forces the player if she has the egg\n\tif (C006_Isolation_Yuki_EggInside) {\n\t\tOverridenIntroText = GetText(\"LickEgg\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n\t// Yuki forces the player if she's dominant\n\tif (ActorGetValue(ActorSubmission) <= -3) {\n\t\tOverridenIntroText = GetText(\"LickSub\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n}", "function isGamePaused() : boolean \n{\n\treturn gamePaused;\n}", "function isGameActive(game){\n return (game.ending - new Date() > 0 && game.isEnded===false);\n }", "function checkstatus(t) {\n\tturnonlist = [];\n\tfor (f = 0; f < 10; f++) {\t\n\t\tfor (var key in buildingSnapshots[t][f]){\n\t\t\tvar obj = buildingSnapshots[t][f][key];\n\t\t\tfor (var prop in obj){\n\t\t\t\tif (obj[prop] === true) {\n\t\t\t\t\tturnonlist.push(key);\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t}\n\t//these are the rooms in the current time interval that need to be turned on\n\t//console.log(turnonlist);\n\tclearrooms();\n\tupdaterooms(turnonlist);\n}", "function checkIfMyTurn() {\n console.log(\"in checkIfMyTurn...\");\n if (vm.currentGame.gameInProgress) {\n if ((vm.playerTeam === \"x\") && (vm.currentGame.turn) && (vm.playerName === vm.currentGame.player1) ||\n (vm.playerTeam === \"o\") && (!vm.currentGame.turn) && (vm.playerName === vm.currentGame.player2)){\n return true;\n }\n }\n return false;\n }", "turnOn(){\n this._vehicleEngineStatus = true;\n const vehicleEngineStatus = \"The engine is running\";\n return vehicleEngineStatus;\n }", "function switchPlayerToTheaterMode() {\n\tif ($(\"div#page\").hasClass(\"watch-non-stage-mode\"))\n\t\t$(\"button.ytp-size-button, div.ytp-size-toggle-large\").click();\n}", "function hasWon(){\n\n //check all the lites to check if they're green. if so add one to the greentilecounter\n $tileArray.each(function (i, value) {\n if($($tileArray[i]).attr('class') === \"green\"){\n greenTileCount ++;\n }\n });\n\n tilesToGo = greenTileCount;\n\n //log valueof greentielcounter at start\n console.log(greenTileCount + \" at start of function\")\n\n // if number of green tiles = the array length then youve won.\n if(greenTileCount == $tileArray.length) {\n $('#welcome').delay(400).fadeIn();\n player1score = turnCounter;\n resetBoard();\n\n addToScoreBoard();\n\n $gridSizeSelector.hide();\n // $welcomeMsg.hide();\n $gridSizeSelector.show(); \n\n $tileArray.each(function(i, value){\n $(this).css({\"background-color\":\"rgba(41,242,44,0.8)\"});\n $(this).delay(1000).fadeOut();\n })\n $p1score.html(\"you've won, big ups! choose next level to play\");\n return true;\n }\n greenTileCount = 0;\n }", "function getGameOpponentFlag(){\n\tif(localStorage.gameFlag == 0){\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "function playerReady(num) {\n let player = `.p${parseInt(num) + 1}`;\n document.querySelector(`${player} .ready`).classList.toggle('active');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alters the query string used by the presentlydisplayed page so that it is suitable for use by the next or previous record in the result set. This will typically be by advancing or reducing the start value of the query, though special considerations apply when the first or last record is reached.
function buildSolrQueryLinkString(direction, querystring, position, total, rows){ var offset = jQuery(document).getUrlParam("start") / 1; position = position / 1; total = total / 1; rows = rows / 1; var new_offset = offset; var new_position = position; if(direction == "next"){ if(position + 1 == total){ new_rows = 2; } else{ new_rows = 3; } new_position += 1; if(position != 0) new_offset += 1; } else{ // i.e., if direction = "prev" if(position - 1 == 0){ new_rows = 2; new_offset = 0; } else{ new_offset -= 1; new_rows = 3; } new_position -= 1; } var reOffset = new RegExp("start=" + offset); var reRows = new RegExp("rows=" + rows); querystring = querystring.replace(reOffset, "start=" + new_offset); querystring = querystring.replace(reRows, "rows=" + new_rows); querystring = querystring + "&p=" + new_position; querystring = querystring + "&t=" + jQuery(document).getUrlParam("t"); querystring = querystring.replace(/[&]?q=\*:\*/, ""); if(jQuery(document).getUrlParam("q") != null && jQuery(document).getUrlParam("q") != ""){ querystring = querystring + "&q=" + jQuery(document).getUrlParam("q"); } return querystring; }
[ "function updateQueryString() {\n\tsessionStorage[\"query\"] = \"start=\" + sessionStorage[\"start\"] + \"&end=\" + sessionStorage[\"end\"] + \"&pipeline=\" + sessionStorage[\"pipeline\"] + \"&datacen=\" + sessionStorage[\"datacen\"] + \"&network=\" + sessionStorage[\"network\"] + \"&farm=\" + sessionStorage[\"farm\"];\n\twindow.location.search = sessionStorage[\"query\"];\n}", "onEventsChange(current, next) {\n // Page 1 of a new query\n if (next.sourceQuery.cursor === \"\") {\n this.setState({ pageCursors: [\"\"] });\n return;\n }\n // Next page of current query\n if (next.sourceQuery.cursor === current.cursor) {\n this.setState({ pageCursors: this.state.pageCursors.concat(next.sourceQuery.cursor) });\n return;\n }\n // Previous page of current query\n const pageIndex = this.state.pageCursors.indexOf(next.sourceQuery.cursor);\n if (pageIndex >= 0) {\n this.setState({ pageCursors: this.state.pageCursors.slice(0, pageIndex + 1) });\n return;\n }\n // Recover from unexpected state\n this.submitQuery(next.sourceQuery.search_text, \"\");\n }", "updatePage(increment) {\n // get rid of the first character of the hash (#)\n const queryString = window.location.hash.slice(1);\n // turn search params into string of key/value pairs (URLSearchParams returns URL input as string)\n const searchParams = new URLSearchParams(queryString);\n // set \"page\" key with value of this.state.page + increment (increment passed into function as argument)\n searchParams.set('page', this.state.page + increment);\n // change window location by assigning hash to string of incremented search params\n window.location.hash = searchParams.toString();\n }", "function changeNav(total,startpage) {\r\n\tif (total > noi) {//results does not fit into one page\r\n\t\tvar html = \"\";\r\n\t\tvar startNum = cachePageNum-Math.floor(nop/2);\r\n\t\tvar totalPage = Math.ceil(total/noi);\r\n var displayTargetPage=\"\";\r\n if(document.getElementById('live_updateArea'))\r\n displayTargetPage=\"result-cached.html\";\r\n else\r\n displayTargetPage=\"result-offline.html\";\r\n\r\n\t\tif (startNum < 1)\r\n\t\t\tstartNum = 1;\r\n\t\tfor (var i = startNum; i < Math.min(nop+startNum,totalPage+1); i++) {\r\n\t\t\tif (i != cachePageNum)\r\n\t\t\t\thtml += ' <a href=\"'+displayTargetPage+'?cp='+i+'&lp='+livePageNum+'&s='+searchString+'\">'+i+'</a> ';\r\n\t\t\telse\r\n\t\t\t\thtml += ' '+i+' ';\r\n\t\t}\r\n\t\tif (cachePageNum != 1)\r\n\t\t\thtml='<a href=\"'+displayTargetPage+'?cp='+(cachePageNum-1)+'&lp='+livePageNum+'&s='+searchString+'\">Previous</a> &nbsp; &nbsp; &nbsp; &nbsp; '+html;\r\n\t\tif (cachePageNum != totalPage)\r\n\t\t\thtml += '&nbsp; &nbsp; &nbsp; &nbsp; <a href=\"'+displayTargetPage+'?cp='+(cachePageNum+1)+'&lp='+livePageNum+'&s='+searchString+'\">Next</a>';\r\n\t\tdocument.getElementById('nav').innerHTML=html;\r\n\t}\r\n}", "_applyLimit() {\n if (!this._page.limit) {\n return;\n }\n var offset;\n if (this._page.offset) {\n offset = this._page.offset;\n } else {\n var page = this._page.page ? this._page.page : 1;\n offset = (page - 1) * this._page.limit;\n }\n this.statement().limit(this._page.limit, offset);\n }", "function GetRecordsNext(){\n CleanTable('available_records_table');\n GetRecords(records.next_page);\n}", "function processQueryParameters() {\n\tvar thisUrl = window.location.href;\n\tif (thisUrl.indexOf('?') != -1) {\n\t\tvar queryString = thisUrl.substr(thisUrl.indexOf('?') + 1);\n\t\tvar parmList = queryString.split('&');\n\t\tfor (var i=0; i<parmList.length; i++) {\n\t\t\tvar nvpString = parmList[i];\n\t\t\tif (nvpString.indexOf('=') != -1) {\n\t\t\t\tvar nvp = parmList[i].split('=');\n\t\t\t\tvar name = nvp[0];\n\t\t\t\tvar value = '';\n\t\t\t\tif (nvp.length > 1) {\n\t\t\t\t\tvalue = nvp[1];\n\t\t\t\t}\n\t\t\t\tqueryParameters[name] = value;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (queryParameters.ss > '') {\n\t\tdocument.getElementById('csslink').setAttribute('href', queryParameters.ss);\n\t}\n}", "get start_results(){\n return this.page_number * this.size + 1;\n }", "function addPaginationLinks(request, prettyJson, resList, successFunctionName) {\n // adding \"...\" link for pagination :\n // NB. everything is already encoded\n if (!successFunctionName) {\n successFunctionName = 'null';\n }\n var start = 0;\n var limit = dcConf.queryDefaultLimit; // from conf\n var query = '';\n if (request._query) {\n // at least must get actual limit to know whether there might be more data\n // but it's easier to also get start and build query at the same time\n var splitQuery = request._query.split('&');\n for (var critInd in splitQuery) {\n var criteria = splitQuery[critInd];\n if (criteria.indexOf('start=') !== -1) {\n start = parseInt(criteria.substring(criteria.indexOf('=') + 1), 10);\n } else if (criteria.indexOf('limit=') !== -1) {\n limit = parseInt(criteria.substring(criteria.indexOf('=') + 1), 10);\n } else {\n query += '&' + criteria;\n }\n }\n }\n\n if (start !== 0) {\n var previousStart = Math.max(0, start - limit);\n var relativeUrl = request.path + '?start=' + previousStart + '&limit=' + limit + query;\n var headers = {};\n for (var hInd in request._headers) {\n if (hInd === 'Accept' || hInd.indexOf('X-Datacore-') === 0) {\n headers[hInd] = request._headers[hInd]; // Accept for RDF, else 'X-Datacore-View'...\n }\n }\n prettyJson = '<a href=\"' + relativeUrl + '\" class=\"dclink\" onclick=\"'\n + 'javascript:return findDataByType($(this).attr(\\'href\\'), ' + successFunctionName + ', null, null, null, '\n + stringifyForAttribute(headers) + ');'\n + '\">...</a>' + lineBreak(0) + prettyJson;\n }\n if (!resList || typeof resList === 'string' // RDF case : always display\n || resList.length === limit) {\n var nextStart = start + limit;\n var relativeUrl = request.path + '?start=' + nextStart + '&limit=' + limit + query;\n var headers = {};\n for (var hInd in request._headers) {\n if (hInd === 'Accept' || hInd.indexOf('X-Datacore-') === 0) {\n headers[hInd] = request._headers[hInd]; // Accept for RDF, else 'X-Datacore-View'...\n }\n }\n prettyJson += lineBreak(0) + '<a href=\"' + relativeUrl + '\" class=\"dclink\" onclick=\"'\n + 'javascript:return findDataByType($(this).attr(\\'href\\'), ' + successFunctionName + ', null, null, null, '\n + stringifyForAttribute(headers) + ');'\n + '\">...</a>';\n }\n return prettyJson;\n}", "function addQueryToURL(query){\n var uri = new URI(window.location.href);\n uri.hash('?q=' + query.replace(/ /g, '+'));\n window.location.href = uri.toString();\n}", "setPaginationData(data)\n {\n if (data.length) {\n var lastValue = data[data.length-1][this.model.key];\n }\n\n // The Response object takes care of this.\n this.request.pagination = {\n count: data.length,\n limit: this.limit,\n total: this.total,\n filter: this.filter,\n sort: this.querySort(),\n url: this.total > this.limit\n ? new Buffer(lastValue.toString()).toString('base64')\n : null\n }\n }", "paginate({ unlimited = false } = {}) {\r\n const { page: qPage, limit: qLimit, skip: qskip } = this.queryObj;\r\n\r\n const page = qPage * 1 || 1;\r\n let limit = unlimited ? undefined : defaultRecordPerQuery;\r\n if (qLimit)\r\n limit = qLimit * 1 > maxRecordsPerQuery ? maxRecordsPerQuery : qLimit * 1;\r\n const skip = qskip\r\n ? qskip * 1\r\n : (page - 1) * (limit || defaultRecordPerQuery);\r\n\r\n this.query.skip = skip;\r\n this.query.take = limit;\r\n return this;\r\n }", "function resetPage(searchValue) {\r\n\tconst currentDataList = filterData(searchValue);\r\n\tshowPage(currentDataList,1);\r\n\taddPagination(currentDataList);\r\n\t// Change the activeData (global scope) so other\r\n\t// parts of program can access it\r\n\tactiveData = currentDataList;\r\n\treturn;\r\n}", "_updateUrl() {\n const { pathname } = window.document.location,\n { id } = this._presentQuote,\n existingParams = qs.parse(window.location.search),\n newParams = { ...existingParams, q: id };\n history.pushState(undefined, document.title, `${pathname}?${qs.stringify(newParams)}`);\n return this;\n }", "function generateURLQuery()\n{\n var url=window.default_query + \"&xml=1&order_by=log_id\";\n if (window.last_log_id != -1)\n\turl += \"&log_id_op=>&log_id=\"+window.last_log_id;\n else\n\turl += \"&date_from=\"+window.start_date+\"&date_from_unit=gregorian\";\n\n if(window.user_id)\n\turl += \"&user_id=\"+window.user_id;\n\n return url;\n}", "function GetRecordsPrevious(){\n CleanTable('available_records_table');\n GetRecords(records.previous_page);\n}", "function pageNaviByDropDown()\r\n\t{\r\n \tvar current_page = getElemnt(\"current_page\");\r\n \tvar nextRecordKey = current_page.value;\r\n \tpageNavi(nextRecordKey);\r\n\t}", "updateQuery(query) {\n this.setState(() => ({\n cursor: null\n }));\n this.props.queryFilter(query.trim());\n }", "function printQuery (query) {\n 'use strict';\n // restrict max length of printed query to avoid endless printing for\n // very long query strings\n var maxLength = 4096;\n if (query.length > maxLength) {\n stringBuilder.appendLine(section(\"Query string (truncated):\"));\n query = query.substr(0, maxLength / 2) + \" ... \" + query.substr(query.length - maxLength / 2);\n }\n else {\n stringBuilder.appendLine(section(\"Query string:\"));\n }\n stringBuilder.appendLine(\" \" + value(wrap(query, 100).replace(/\\n+/g, \"\\n \", query)));\n stringBuilder.appendLine(); \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate random category Six
function randomCategorySix(myCategories) { let category = myCategories[Math.floor(Math.random() * myCategories.length)]; var element = document.getElementById('game-card-title-5'); element.innerHTML = category.title; var element = document.getElementById('game-card-description-5'); element.innerHTML = category.description; document.querySelector('#x-button-5').style = 'display: inline'; }
[ "function randomCategoryFour(myCategories) {\n let category = myCategories[Math.floor(Math.random() * myCategories.length)];\n\n var element = document.getElementById('game-card-title-3');\n element.innerHTML = category.title;\n var element = document.getElementById('game-card-description-3');\n element.innerHTML = category.description;\n\n document.querySelector('#x-button-3').style = 'display: inline';\n}", "function randomCategoryTwo(myCategories) {\n let category = myCategories[Math.floor(Math.random() * myCategories.length)];\n\n var element = document.getElementById('game-card-title-1');\n element.innerHTML = category.title;\n var element = document.getElementById('game-card-description-1');\n element.innerHTML = category.description;\n\n document.querySelector('#x-button-1').style = 'display: inline';\n}", "function randomTopic()\n{ \n return Math.floor(Math.random()*ribbon_data.length);\n}", "function getRandomWordsForCategory(category, numberOfWords) {\n if (numberOfWords === undefined) {\n numberOfWords = 3;\n }\n\n const categoryFile = getFileForCategory(category);\n if (categoryFile === null) {\n return null;\n }\n const contents = fs.readFileSync(categoryFile, 'utf8');\n const words = contents.split(/\\r?\\n/);\n\n const shuffled = words.sort(() => .5 - Math.random()); // random shuffle\n const categoryWords = shuffled.slice(0, numberOfWords); //get sub-array of first n elements AFTER shuffle\n console.log(\"categoryWords: \" + JSON.stringify(categoryWords));\n return categoryWords;\n }", "function generateCandy() {\n for (let i = 0; i < width; i++) {\n const cell = document.getElementById(`${i}`)\n if (!cell.classList[1]) {\n cell.classList.add(`${colors[Math.floor(Math.random() * Math.floor(4))]}`)\n }\n }\n }", "function randomizeDice(){\n diceRoll[0] = Math.floor( Math.random() * 6 )+1;\n diceRoll[1] = Math.floor( Math.random() * 6 )+1;\n}", "function rand7() {\n return Math.floor(Math.random() * (7 - 1 + 1)) + 1;\n}", "function diamond3() {\n return Math.floor(Math.random() * 11 + 1);\n }", "function randomShape(){\n\treturn Math.floor(Math.random()*50);\n}", "function crystals(min,max){return Math.floor(Math.random()*(max-min))+min;\n}", "generateCalBurnt()\r\n {\r\n var calories = Math.floor((Math.random() * 20) + 1)\r\n console.log(calories)\r\n }", "function randomWeight() {\n return Math.round(Math.random() * 5)\n}", "function diamond4() {\n return Math.floor(Math.random() * 11 + 1);\n }", "function getRandomShortString() {\n return Math.random().toString(36).slice(-11);\n}", "getRandomDishFromCourse(courseName){\n const dishes = this.courses[courseName];\n return dishes[Math.floor(Math.random() * dishes.length)] //Generate random dish\n }", "function getRandomPiece() {\r\n let types = [I,O,L,J,T,S,Z];\r\n return new types[Math.floor(Math.random() * types.length)]();\r\n}", "function rand10() {\n return rand5() + rand5() - 3;\n}", "function getRandomNumCrystals() {\n // Crystals object.\nreturn { \n red: {\n points: Math.floor(Math.random()*12) + 1,\n imageUrl: \"assets/images/red.png\"\n },\n blue: {\n points: Math.floor(Math.random()*12) + 1,\n imageUrl: \"assets/images/blue.jpeg\"\n },\n yellow: {\n points: Math.floor(Math.random()*12) + 1,\n imageUrl: \"assets/images/yellow.jpg\"\n },\n green: {\n points: Math.floor(Math.random()*12) + 1,\n imageUrl: \"assets/images/green.jpg\"\n },\n\n }\n}", "function randomIcons(){\n var icons = [\"gallery_icon\",\"channel_icon\",\"video_icon\",\"\",\"\"];\n return icons[Math.floor(Math.random() * icons.length)];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TASK: copyIcons Copies all of the material design icon resources files
function copyIcons() { return gulp.src('app/style/icon_font/*.*') .pipe(getStreamOutput('css', 'icon_font')); }
[ "function copyiOSIcons(dir) {\n console.log('Copying iOS icons ...');\n let copyPromises = [];\n ['', '_2x', '_3x'].forEach((version) => {\n let imageset = (program.color === 'black')? getIcFilename() : getIcFilename(null, program.color);\n let color = (program.color === 'black')? '': '_white';\n let size = (program.size === 24)? '' : `_${program.size}pt`;\n let src = path.join(dir, 'ios', imageset + size + '.imageset', getIcFilename() + color + size + version + '.png');\n let dest = path.join(program.dir, 'Sources\\\\HipMobileUI.iOS\\\\Resources', getIcFilename() + version.replace('_', '@') + '.png');\n copyPromises.push(copyFile(src, dest));\n })\n return Promise.all(copyPromises)\n .then(() => { \n console.log('Copying iOS icons finished.');\n return dir;\n });\n}", "function copyAndroidIcons(dir) {\n console.log('Copying Android icons ...');\n let copyPromises = [];\n ['drawable-hdpi', 'drawable-mdpi', 'drawable-xhdpi', 'drawable-xxhdpi', 'drawable-xxxhdpi'].forEach((drawableDir) => {\n let src = path.join(dir, 'android', drawableDir, getIcFilename('png', program.color, program.size));\n let dest = path.join(program.dir, 'Sources\\\\HipMobileUI.Droid\\\\Resources', drawableDir, getIcFilename('png'));\n copyPromises.push(copyFile(src, dest));\n });\n return Promise.all(copyPromises)\n .then(() => { \n console.log('Copying Android icons finished.'); \n return dir;\n });\n}", "function DoIcons(iTunesArtwork, iconsInfo) {\n try\n {\n if (iTunesArtwork !== null) \n { \n var doc = open(iTunesArtwork, OpenDocumentType.PNG);\n \n if (doc == null)\n {\n throw \"Something is wrong with the file. Make sure it's a valid PNG file.\";\n }\n\n var startState = doc.activeHistoryState; // save for undo\n var initialPrefs = app.preferences.rulerUnits; // will restore at end\n app.preferences.rulerUnits = Units.PIXELS; // use pixels\n\n // Save icons in PNG using Save for Web.\n var sfw = new ExportOptionsSaveForWeb();\n sfw.format = SaveDocumentType.PNG;\n sfw.PNG8 = false; // use PNG-24\n sfw.transparency = true;\n doc.info = null; // delete metadata\n\n var icon;\n for (i = 0; i < iconsInfo.length; i++) \n {\n icon = iconsInfo[i];\n doc.resizeImage(icon.size, icon.size, // width, height\n null, ResampleMethod.BICUBICSHARPER);\n\n checkFolderExist(icon.density);\n\n doc.exportDocument(new File(icon.density + \"/\" + icon.name), ExportType.SAVEFORWEB, sfw);\n doc.activeHistoryState = startState; // undo resize\n }\n }\n }\n catch (exception)\n {\n // Show degbug message and then quit\n if ((exception != null) && (exception != \"\"))\n alert(exception);\n }\n finally\n {\n if (doc != null)\n doc.close(SaveOptions.DONOTSAVECHANGES);\n \n app.preferences.rulerUnits = initialPrefs; // restore prefs\n }\n}", "function copyAssets(done) {\n var assets = {\n js: [\n \"./node_modules/jquery/dist/jquery.js\",\n \"./node_modules/bootstrap/dist/js/bootstrap.bundle.js\",\n \"./node_modules/metismenujs/dist/metismenujs.min.js\",\n \"./node_modules/jquery-slimscroll/jquery.slimscroll.js\",\n \"./node_modules/feather-icons/dist/feather.min.js\",\n ]\n };\n\n var third_party_assets = {\n css_js: [\n {\"name\": \"sortablejs\", \"assets\": [\"./node_modules/sortablejs/Sortable.min.js\"]},\n {\"name\": \"apexcharts\", \"assets\": [\"./node_modules/apexcharts/dist/apexcharts.min.js\"]},\n {\"name\": \"parsleyjs\", \"assets\": [\"./node_modules/parsleyjs/dist/parsley.min.js\"]},\n {\"name\": \"smartwizard\", \"assets\": [\"./node_modules/smartwizard/dist/js/jquery.smartWizard.min.js\", \n \"./node_modules/smartwizard/dist/css/smart_wizard.min.css\", \n \"./node_modules/smartwizard/dist/css/smart_wizard_theme_arrows.min.css\", \n \"./node_modules/smartwizard/dist/css/smart_wizard_theme_circles.min.css\",\n \"./node_modules/smartwizard/dist/css/smart_wizard_theme_dots.min.css\"\n ]},\n {\"name\": \"summernote\", \"assets\": [\"./node_modules/summernote/dist/summernote-bs4.min.js\", \"./node_modules/summernote/dist/summernote-bs4.css\"]},\n {\"name\": \"dropzone\", \"assets\": [\"./node_modules/dropzone/dist/min/dropzone.min.js\", \"./node_modules/dropzone/dist/min/dropzone.min.css\"]},\n {\"name\": \"bootstrap-tagsinput\", \"assets\": [\"./node_modules/@adactive/bootstrap-tagsinput/dist/bootstrap-tagsinput.min.js\", \"./node_modules/@adactive/bootstrap-tagsinput/dist/bootstrap-tagsinput.css\"]},\n {\"name\": \"select2\", \"assets\": [\"./node_modules/select2/dist/js/select2.min.js\", \"./node_modules/select2/dist/css/select2.min.css\"]},\n {\"name\": \"multiselect\", \"assets\": [\"./node_modules/multiselect/js/jquery.multi-select.js\", \"./node_modules/multiselect/css/multi-select.css\"]},\n {\"name\": \"flatpickr\", \"assets\": [\"./node_modules/flatpickr/dist/flatpickr.min.js\", \"./node_modules/flatpickr/dist/flatpickr.min.css\"]},\n {\"name\": \"bootstrap-colorpicker\", \"assets\": [\"./node_modules/bootstrap-colorpicker/dist/js/bootstrap-colorpicker.min.js\", \"./node_modules/bootstrap-colorpicker/dist/css/bootstrap-colorpicker.min.css\"]},\n {\"name\": \"bootstrap-touchspin\", \"assets\": [\"./node_modules/bootstrap-touchspin/dist/jquery.bootstrap-touchspin.min.js\", \"./node_modules/bootstrap-touchspin/dist/jquery.bootstrap-touchspin.css\"] },\n {\n \"name\": \"datatables\", \"assets\": [\"./node_modules/datatables.net/js/jquery.dataTables.min.js\",\n \"./node_modules/datatables.net-bs4/js/dataTables.bootstrap4.min.js\",\n \"./node_modules/datatables.net-responsive/js/dataTables.responsive.min.js\",\n \"./node_modules/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js\",\n \"./node_modules/datatables.net-buttons/js/dataTables.buttons.min.js\",\n \"./node_modules/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js\",\n \"./node_modules/datatables.net-buttons/js/buttons.html5.min.js\",\n \"./node_modules/datatables.net-buttons/js/buttons.flash.min.js\",\n \"./node_modules/datatables.net-buttons/js/buttons.print.min.js\",\n \"./node_modules/datatables.net-keytable/js/dataTables.keyTable.min.js\",\n \"./node_modules/datatables.net-select/js/dataTables.select.min.js\",\n \"./node_modules/datatables.net-bs4/css/dataTables.bootstrap4.min.css\",\n \"./node_modules/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css\",\n \"./node_modules/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css\",\n \"./node_modules/datatables.net-select-bs4/css/select.bootstrap4.min.css\"\n ]\n },\n {\"name\": \"moment\", \"assets\": [\"./node_modules/moment/min/moment.min.js\"]},\n {\"name\": \"fullcalendar-bootstrap\", \"assets\": [\"./node_modules/@fullcalendar/bootstrap/main.min.js\", \n \"./node_modules/@fullcalendar/bootstrap/main.min.css\",\n ]\n },\n {\"name\": \"fullcalendar-core\", \"assets\": [\"./node_modules/@fullcalendar/core/main.min.js\", \n \"./node_modules/@fullcalendar/core/main.min.css\",\n ]\n },\n {\"name\": \"fullcalendar-daygrid\", \"assets\": [\"./node_modules/@fullcalendar/daygrid/main.min.js\", \n \"./node_modules/@fullcalendar/daygrid/main.min.css\"\n ]\n },\n {\"name\": \"fullcalendar-interaction\", \"assets\": [\"./node_modules/@fullcalendar/interaction/main.min.js\"]},\n {\n \"name\": \"fullcalendar-timegrid\", \"assets\": [\"./node_modules/@fullcalendar/timegrid/main.min.js\",\n \"./node_modules/@fullcalendar/timegrid/main.min.css\"]\n },\n {\n \"name\": \"fullcalendar-list\", \"assets\": [\"./node_modules/@fullcalendar/list/main.min.js\",\n \"./node_modules/@fullcalendar/list/main.min.css\"]\n },\n {\"name\": \"list-js\", \"assets\": [\"./node_modules/list.js/dist/list.min.js\"]},\n {\n \"name\": \"jqvmap\", \"assets\": [\"./node_modules/jqvmap/dist/jquery.vmap.min.js\", \n \"./node_modules/jqvmap/dist/jqvmap.min.css\",\n \"./node_modules/jqvmap/dist/maps/jquery.vmap.usa.js\",\n ]\n },\n ]\n };\n\n //copying third party assets\n lodash(third_party_assets).forEach(function (assets, type) {\n if (type == \"css_js\") {\n lodash(assets).forEach(function (plugin) {\n var name = plugin['name'];\n var assetlist = plugin['assets'];\n lodash(assetlist).forEach(function (asset) {\n gulp.src(asset).pipe(gulp.dest(folder.dist_assets + \"libs/\" + name));\n });\n });\n //gulp.src(assets).pipe(gulp.dest(folder.dist_assets + \"css/vendor\"));\n }\n });\n\n //copying required assets\n lodash(assets).forEach(function (assets, type) {\n if (type == \"scss\") {\n gulp\n .src(assets)\n .pipe(\n rename({\n // rename aaa.css to _aaa.scss\n prefix: \"_\",\n extname: \".scss\"\n })\n )\n .pipe(gulp.dest(folder.src + \"scss/vendor\"));\n } else {\n gulp.src(assets).pipe(gulp.dest(folder.src + \"js/vendor\"));\n }\n });\n\n //copying data files\n gulp.src(folder.src + \"data/**\").pipe(gulp.dest(folder.dist_assets + \"/data\"));\n\n done();\n}", "function cargarIconos(){\n // iconos para mostrar puntos\n estilosIcons[\"origen\"] = styles.marcadorInicioRecorrido();\n estilosIcons[\"destino\"] = styles.marcadorFinRecorrido();\n }", "function copyAssets() {\n return gulp\n .src(theme.customizer_assets.src)\n .pipe(changed(theme.customizer_assets.dist))\n .pipe(gulp.dest(theme.customizer_assets.dist))\n}", "function copyVendorFilesFn () {\n var\n asset_group_table = pkgMatrix.xhiVendorAssetGroupTable || [],\n dev_dependency_map = pkgMatrix.devDependencies || {},\n asset_group_count = asset_group_table.length,\n promise_list = [],\n\n idx, asset_group_map, asset_list, asset_count,\n fq_dest_dir_str, dest_ext_str, do_dir_copy,\n\n idj, asset_map, src_asset_name, src_dir_str,\n src_pkg_name, dest_vers_str, dest_name,\n fq_src_path_list, fq_src_path_str,\n fq_dest_path_str, promise_obj\n ;\n\n for ( idx = 0; idx < asset_group_count; idx++ ) {\n asset_group_map = asset_group_table[ idx ] || {};\n\n asset_list = asset_group_map.asset_list || [];\n asset_count = asset_list.length;\n\n dest_ext_str = asset_group_map.dest_ext_str;\n do_dir_copy = asset_group_map.do_dir_copy;\n fq_dest_dir_str = fqProjDirname + '/' + asset_group_map.dest_dir_str;\n\n\n mkdirpFn.sync( fq_dest_dir_str );\n ASSET_MAP: for ( idj = 0; idj < asset_count; idj++ ) {\n asset_map = asset_list[ idj ];\n src_asset_name = asset_map.src_asset_name;\n src_dir_str = asset_map.src_dir_str || '';\n src_pkg_name = asset_map.src_pkg_name;\n\n dest_vers_str = dev_dependency_map[ src_pkg_name ];\n\n if ( ! dest_vers_str ) {\n logFn( 'WARN: package ' + src_pkg_name + ' not found.');\n continue ASSET_MAP;\n }\n dest_name = asset_map.dest_name || src_pkg_name;\n\n fq_dest_path_str = fq_dest_dir_str\n + '/' + dest_name + '-' + dest_vers_str;\n fq_src_path_list = [ fqModuleDirname, src_pkg_name, src_asset_name ];\n if ( src_dir_str ) { fq_src_path_list.splice( 2, 0, src_dir_str ); }\n\n fq_src_path_str = fq_src_path_list.join( '/' );\n\n if ( ! do_dir_copy ) {\n fq_dest_path_str += '.' + dest_ext_str;\n }\n promise_obj = copyPathFn( fq_src_path_str, fq_dest_path_str, do_dir_copy );\n promise_list.push( promise_obj );\n }\n }\n\n promiseObj.all( promise_list )\n .then( function () { eventObj.emit( '04PatchFiles' ); } )\n .catch( abortFn );\n }", "gruntCopy() {\n let assets = [];\n if (this.images.length > 0) {\n assets = assets.concat(this.images);\n }\n if (this.scripts.length > 0) {\n assets = assets.concat(this.scripts);\n }\n if (this.css.length > 0) {\n this.css.forEach((css, index, arry) => {\n if (!css.isAssetReved && !css.isInBundle) {\n assets.push({\n src: css.src,\n dest: css.dest,\n name: css.name,\n type: \"css\",\n });\n }\n });\n }\n if (assets && assets.length > 0) {\n const files = {};\n assets.forEach((asset, index, arry) => {\n files[asset.dest] = asset.src;\n });\n return {\n files: files\n };\n }\n return undefined;\n }", "function iconBuild(cb) {\n \n gulp\n .src(\"./src/icons/*.svg\")\n .pipe(\n iconfontCss({\n // где будет наш scss файл\n targetPath: \"../components/icons.scss\",\n // пути подлючения шрифтов в _icons.scss\n fontPath: \"./fonts/\",\n fontName: fontName\n })\n )\n .pipe(\n iconfont({\n fontName: fontName,\n formats: [\"svg\", \"ttf\", \"eot\", \"woff\", \"woff2\"],\n normalize: true,\n fontHeight: 1001\n })\n )\n .pipe(gulp.dest(\"./src/fonts/\"))\n .pipe(browserSync.reload({ stream: true }));\n\n cb();\n}", "function copyCssAssets () {\n gulp.src('./src/assets/css/*.css')\n .pipe(gulp.dest('./dist/bundles/styles')).on('end', compileScss);\n}", "function copyAssets () {\n return gulp.src(ASSET_SOURCE_PATH + '/**/*')\n .pipe(gulp.dest(BUILD_PATH + '/assets'));\n}", "function copyFiles(options, callback){\n\tlog(warning(\"Copying the required files from Skeletal to our new theme.\"))\n\t// Copy in required templates from Skeletal\n\tshell.cp('-R', `${options.masterTheme}/${options.TEMPLATES}/headers/template.html`,`${options.dest}/${options.TEMPLATES}/headers/`)\n\tshell.cp('-R', `${options.masterTheme}/${options.TEMPLATES}/footers/template.html`,`${options.dest}/${options.TEMPLATES}/footers/`)\n\tshell.cp('-R', `${options.masterTheme}/${options.TEMPLATES}/cms/home.template.html`,`${options.dest}/${options.TEMPLATES}/cms/`)\n\tshell.cp('-R', `${options.masterTheme}/${options.TEMPLATES}/skeletal-netothemeinfo.txt`,`${options.dest}/${options.TEMPLATES}/${options.name}-netothemeinfo.txt`)\n\tif (fs.existsSync(`${options.masterTheme}/${options.LESS}`)) {\n\t\t// Copy in less\n\t\tshell.cp('-R', `${options.masterTheme}/${options.LESS}`,`${options.dest}/${options.CSS}/`)\n\t}else if (fs.existsSync(`${options.masterTheme}/${options.SCSS}`)) {\n\t\t// Copy in sass\n\t\tshell.cp('-R', `${options.masterTheme}/${options.SCSS}`,`${options.dest}/${options.src}/`)\n\t}\n\t// Copy in css\n\tif (fs.existsSync(`${options.masterTheme}/${options.CSS}/app.css`)) {\n\t\tshell.cp('-R', `${options.masterTheme}/${options.CSS}/app.css`,`${options.dest}/${options.CSS}/`)\n\t}\n\tshell.cp('-R', `${options.masterTheme}/${options.CSS}/skeletal-style.css`,`${options.dest}/${options.CSS}/${options.dest}-style.css`)\n\t// Copy other required files\n\tshell.cp('-R', `${options.masterTheme}/.gitignore`,`${options.dest}/`)\n\tshell.cp('-R', `${options.masterTheme}/gulpfile.js`,`${options.dest}/`)\n\tshell.cp('-R', `${options.masterTheme}/package-lock.json`,`${options.dest}/`)\n\tshell.cp('-R', `${options.masterTheme}/package.json`,`${options.dest}/`)\n\tshell.cp('-R', `${options.masterTheme}/README.md`,`${options.dest}/`)\n\tlog(success(\"👍 Copying done!\"))\n\t// Remove temp folder\n\tshell.rm('-rf', options.tempFolder)\n\tcallback()\n}", "function setProductIcons() {\n\tjQuery('.edit_button').button({\n\t\ticons: {\n primary: \"ui-icon-wrench\"\n\t\t}\n\t});\n\tjQuery('.save_button').button({\n\t\ticons: {\n primary: \"ui-icon-check\"\n\t\t}\n\t}).click(function() {\n\t\tjQuery.cookie('redirect','');\n\t\treturn true;\n\t});\n\tjQuery('.remove_button').button({\n\t\t\ticons: {\n\t primary: \"ui-icon-closethick\"\n\t }\n\t});\n\tjQuery('.add_button').button({\n\t\t\ticons: {\n\t primary: \"ui-icon-plusthick\"\n\t }\n\t});\n\tjQuery('.back').button({\n\t\t\ticons: {\n\t primary: \"ui-icon-arrowreturnthick-1-s\"\n\t }\n\t});\n}", "async function copy() {\n for (const outDir of outDirs) {\n const packages = [...defaultPackages]\n if (outDir === 'jest') {\n packages.push(...jestPackages)\n }\n if (outDir === 'jasmine') {\n packages.push(...jasminePackages)\n }\n\n // link node_modules\n for (const packageName of packages) {\n const destination = path.join(__dirname, outDir, 'node_modules', packageName)\n\n const destDir = destination.split(path.sep).slice(0, -1).join(path.sep)\n shelljs.mkdir('-p', destDir)\n shelljs.ln('-s', path.join(ROOT, 'node_modules', packageName), destination)\n }\n\n // link test file\n shelljs.ln('-s', path.join(__dirname, testFile), path.join(__dirname, outDir, testFile))\n\n // copy expect-webdriverio\n const destDir = path.join(__dirname, outDir, 'node_modules', 'expect-webdriverio')\n\n shelljs.mkdir('-p', destDir)\n shelljs.cp('*.d.ts', destDir)\n shelljs.cp('package.json', destDir)\n shelljs.cp('-r', 'types', destDir)\n }\n}", "function copyTargets(buildInfo) {\n buildInfo.builtTargets.forEach(function (target) {\n var isMerged = target.match(/merged\\./),\n isBeauty = target.match(/beauty\\.html$/),\n basename = path.basename(target),\n src = path.join(rootDir, target),\n dst = \"\",\n sub = basename.split(\".\"),\n replaceFiles = [],\n version = (new Date()).getTime();\n \n if(!isMerged && !isBeauty) {\n return true;\n }\n \n if(isBeauty) {\n basename = basename.replace('.beauty',''); \n replaceFiles.push(path.join(rootDir, 'dist', basename));\n }\n \n dst = path.join(rootDir, 'dist', basename);\n \n if(isMerged) {\n basename = basename.replace('.dist','');\n subDir = sub[sub.length-1];\n dst = path.join(rootDir, 'dist/' + subDir, basename);\n \n if(basename.match(/merged\\..*?css$/)) {\n replaceFiles.push(dst);\n }\n }\n\n fse.copySync(src, dst);\n \n // изменение путей к стилям и скриптам\n replaceFiles.forEach(function( file ) {\n fs.readFile(file, function(err, content){\n if(!err) {\n content = content.toString();\n content = content.split(\"../merged/merged.css\").join(\"css/merged.css?v\"+version)\n .split(\"../merged/merged.js\").join(\"js/merged.js?v\"+version) \n .split(\"../../images/\").join(\"img/\")\n .split(\"../../dist/\").join(\"../\")\n .split(\"../../css/\").join(\"css/\")\n .split(\"../../js/\").join(\"js/\");\n \n fs.open(file, \"w\", 0644, function(err, handle) {\n if(!err) {\n fs.write(handle, content);\n }\n })\n }\n });\n });\n \n // копирование шрифтов и js библиотек\n var copyFiles = [\n {\n src : path.join(rootDir, 'fonts'),\n dst : path.join(rootDir, 'dist/fonts')\n },\n {\n src : path.join(rootDir, 'css/fonts.css'),\n dst : path.join(rootDir, 'dist/css/fonts.css')\n },\n {\n src : path.join(rootDir, 'js/libs'),\n dst : path.join(rootDir, 'dist/js/libs')\n },\n {\n src : path.join(rootDir, 'images'),\n dst : path.join(rootDir, 'dist/img')\n }\n ];\n \n copyFiles.forEach( function( copy ){\n fse.copySync(copy.src, copy.dst);\n });\n \n });\n }", "async function copyFiles() {\n for (const file of verbatimFiles) {\n const src = path.join('./', file);\n const dest = path.join(directory, file);\n await fs.copyFile(src, dest);\n }\n}", "async function copyStyles() {\n const paths = await globby(`${source}/**/*.scss`);\n\n paths.forEach(async file => {\n const base = path.parse(file).base;\n const dest = path.parse(file).dir.replace(source, destination);\n\n await fs.ensureDir(dest);\n await fs.copyFile(file, `${dest}/${base}`);\n });\n}", "function updateResourceIcons() {\n if (!currentVesselData) return; // too fast of a page through the history due to call delay of the function\n var resourceList = currentVesselData.Resources.Resources.split(\"|\");\n for (resCount=0; resCount<5; resCount++) { \n if (resCount+resIndex == resourceList.length) break;\n $(\"#resImg\" + resCount).attr(\"src\", resourceList[resCount+resIndex].split(\";\")[0] + \".png\");\n $(\"#resImg\" + resCount).fadeIn();\n $(\"#resTip\" + resCount).html(resourceList[resCount+resIndex].split(\";\")[1]);\n }\n currentVesselData.Resources.HTML = $(\"#dataField8\").html();\n}", "function imagesTask(){\n return src(files.imgToMinify)\n .pipe(image())\n .pipe(dest(files.distToDistImg));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fixValue returns the passed value multiplied by the difficulty setting defined by the currentTab
function fixValue(value) { var multiplyer; if (scope.currentTab == 1) { multiplyer = 1; } if (scope.currentTab == 2) { multiplyer = 1.5; } if (scope.currentTab == 3) { multiplyer = 2; } if (scope.currentTab == 4) { multiplyer = 3; } var retval = Math.round(value * multiplyer); if (retval == 0) { return null; } return retval; }
[ "function performDifficultyAction(){\r\n\tDifficultyValue++;\r\n\tif (DifficultyValue > DifficultyRightValue){\r\n\t\tDifficultyValue = DifficultyLeftValue;\r\n\t}\t\t\r\n}", "set speedVariation(value) {}", "getSettingValue(setting) { return this.settings_().getValue(`limits/${setting}`); }", "attemptNewValue(newValue) {\n const upperbound = this.props.upperBound || 25;\n const lowerbound = this.props.lowerBound || 0;\n if (newValue <= upperbound && newValue >= lowerbound) {\n this.props.setValue(newValue);\n }\n }", "function limitValues() {\n var i, j, value, valueInst, valueDescr, skillsets,\n skillKey, skillValue, listResources = Variable.findByName(gm, 'resources');\n //actions\n valueDescr = Variable.findByName(gm, 'actions')\n valueInst = valueDescr.getInstance(self);\n if (valueInst.getValue() > valueDescr.getMaxValue())\n valueInst.setValue(valueDescr.getMaxValue());\n if (valueInst.getValue() < valueDescr.getMinValue())\n valueInst.setValue(valueDescr.getMinValue());\n //teamMotivation\n valueDescr = Variable.findByName(gm, 'teamMotivation')\n valueInst = valueDescr.getInstance(self);\n if (valueInst.getValue() > valueDescr.getMaxValue())\n valueInst.setValue(valueDescr.getMaxValue());\n if (valueInst.getValue() < valueDescr.getMinValue())\n valueInst.setValue(valueDescr.getMinValue());\n //clientsSatisfaction\n valueDescr = Variable.findByName(gm, 'clientsSatisfaction')\n valueInst = valueDescr.getInstance(self);\n if (valueInst.getValue() > valueDescr.getMaxValue())\n valueInst.setValue(valueDescr.getMaxValue());\n if (valueInst.getValue() < valueDescr.getMinValue())\n valueInst.setValue(valueDescr.getMinValue());\n //ressources\n for (i = 0; i < listResources.items.size(); i++) {\n valueDescr = listResources.items.get(i);\n valueInst = valueDescr.getInstance(self);\n //moral\n value = parseInt(valueInst.getMoral());\n if (value > 100)\n valueInst.setMoral(100);\n if (value < 0)\n valueInst.setMoral(0);\n //moral\n value = parseInt(valueInst.getConfidence());\n if (value > 100)\n valueInst.setConfidence(100);\n if (value < 0)\n valueInst.setConfidence(0);\n //frankness\n value = parseInt(valueInst.getProperty('frankness'));\n if (value > 100)\n valueInst.setProperty('frankness', 100);\n if (value < 0)\n valueInst.setProperty('frankness', 0);\n //lastWorkQuality\n value = parseInt(valueInst.getProperty('lastWorkQuality'));\n if (value > 100)\n valueInst.setProperty('lastWorkQuality', 100);\n if (value < 0)\n valueInst.setProperty('lastWorkQuality', 0);\n //skillset\n skillsets = valueInst.getSkillsets();\n for (j = 0; j < skillsets.size(); j++) {\n skillKey = skillsets.keySet().toArray()[j];\n skillValue = parseInt(skillsets.get(skillKey));\n if (skillValue > 100)\n valueInst.setSkillset(skillKey, 100);\n if (skillValue < 0)\n valueInst.setSkillset(skillKey, 0);\n }\n }\n}", "function updateValue(val, id) {\n var value = validate();\n if (id == \"slope_text\") {\n if(value != INVALID_VALUE) {\n document.getElementById('slope_slider').value = parseFloat(value);\n }\n } else if (id == 'slope_slider') {\n findSmallestFraction(val);\n }\n\n if(value != INVALID_VALUE) {\n turnSatellite(value);\n }\n }", "function assign(value) {\n let newValue = display + value;\n if (display === '0' || didCalculation === true) {\n setDisplay(value);\n setDidCalculation(false);\n setAllRolls('$');\n } else {\n setDisplay(newValue);\n }\n }", "verifyValueMax() {\n this.discount.value = discountHandler.getFixedValue(this.discount.value, this.discount.type);\n }", "function setNumber(value, element)\n {\n var percentage = (value - 1) * 11.2;\n\n element.style.backgroundPosition = percentage + \"% 0\";\n }", "function scoreChangeHandlerSprout(minScore, maxScore, step) {\r\n $('input[type=number]').change(function () {\r\n var value = $(this).val();\r\n \r\n // round the value to the closest step multiplication integer\r\n value = (Math.round((Math.round(value)) / step)) * step;\r\n \r\n // make sure the input stays within allowed range\r\n value = keepInRange(minScore, maxScore, value);\r\n $(this).val(value);\r\n\r\n calculateScoresMaps(RATIOS_SPROUT, CATEGORIES_RATIO_SPROUT, CATEGORIES_SPROUT,\"input[name$=_1][type=number]\", 2, \"total_score_1\");\r\n calculateScoresMaps(RATIOS_SPROUT, CATEGORIES_RATIO_SPROUT, CATEGORIES_SPROUT,\"input[name$=_2][type=number]\", 2, \"total_score_2\");\r\n calculateScoresMaps(RATIOS_SPROUT, CATEGORIES_RATIO_SPROUT, CATEGORIES_SPROUT,\"input[name$=_3][type=number]\", 2, \"total_score_3\");\r\n calculateRatingMean(RATIOS_SPROUT);\r\n });\r\n}", "function factorial(value) {\n var returnVal = checkFactorialArg(value);\n if (value != 0 && (typeof(returnVal) == \"number\")) {\n returnVal = value * factorial(value - 1);\n }\n return returnVal;\n}", "function getItemBuyLimit(value) {\n switch (value){\n //BLINE - Bandos Line\n case \"bh\": return \"1/4\";\n case \"bcp\": return \"1/4\";\n case \"tass\": return \"1/4\";\n case \"bg\": return \"1/4\";\n case \"bb\": return \"1/4\";\n case \"bws\": return \"1/4\";\n //ALINE - Armadyl Line\n case \"ah\": return \"1/4\";\n case \"acp\": return \"1/4\";\n case \"acs\": return \"1/4\";\n case \"ag\": return \"1/4\";\n case \"ab\": return \"1/4\";\n case \"acb\": return \"1/4\";\n case \"oacb\": return \"1/4\";\n case \"buck\": return \"1/4\";\n //SLINE - Subjugation Line\n case \"sh\": return \"1/4\";\n case \"garb\": return \"1/4\";\n case \"gown\": return \"1/4\";\n case \"sg\": return \"1/4\";\n case \"sb\": return \"1/4\";\n case \"ward\": return \"1/4\";\n //T LINE - Tetsu Line\n case \"tth\": return \"2/4\";\n case \"ttb\": return \"2/4\";\n case \"ttl\": return \"2/4\";\n //\"DL LINE - Death Lotus Line\n case \"blh\": return \"2/4\";\n case \"dlcp\": return \"2/4\";\n case \"dlc\": return \"2/4\";\n // SS LINE - Seasinger's Line\n case \"ssh\": return \"2/4\";\n case \"sst\": return \"2/4\";\n case \"ssb\": return \"2/4\";\n //AMULETS - Amulets Line\n case \"hiss\": return \"1/4\";\n case \"murm\": return \"1/4\";\n case \"whisp\": return \"1/4\";\n //MISC LINE - Miscellaneous Line\n case \"sss\": return \"1/4\";\n case \"rhh\": return \"2/4\";\n case \"rb\": return \"2/4\";\n case \"blood\": return \"2/4\";\n //KITES - Kites Line\n case \"male\": return \"1/4\";\n case \"merc\": return \"1/4\";\n case \"veng\": return \"1/4\";\n default: return \"Unknown\";\n }\n}", "function scoreChangeHandler(minScore, highScore, step) {\r\n $('input[type=number]').change(function () {\r\n var value = $(this).val();\r\n \r\n // round the value to the closest step multiplication integer\r\n value = (Math.round((Math.round(value)) / step)) * step;\r\n \r\n // make sure the input stays within allowed range\r\n $(this).val(keepInRange(minScore, highScore, value));\r\n\r\n // calculate all scores for this application\r\n calculateScores();\r\n });\r\n}", "function adjustFumble (luckySign, luckModifier) {\n var adjust = luckModifier * -1;\n if (luckySign.luckySign != undefined && luckySign.luckySign === \"The Broken Star\"){\n adjust = luckModifier * -2;\n }\n\treturn adjust;\n}", "function updateLevels(elem){\n let name = elem.parentElement.getElementsByTagName(\"p\")[0].innerText;\n selectedSkills[name] = parseInt(elem.value);\n}", "function editSlotValue( slot : ParamSlot, slotIndex : int, pos : Rect ){\n\t\tvar oldString : String = editValStr;\n\t\teditValStr = GUI.TextField( pos, editValStr, 3, manager.paramTxtStyle );\n\t\t\n\t\t//Security\n\t\tvar chars : char[] = editValStr.ToCharArray();\n\t\tvar c : char;\n\t\tfor( var i : int = 0; i < chars.Length; i++ ){\n\t\t\tc = chars[i];\n\t\t\tif( !((c >= \"0\"[0] && c <= \"9\"[0]) || (c == \"-\"[0] && i == 0)) )\n\t\t\t\teditValStr = oldString;\n\t\t}\n\t\tif( chars.Length > 0 )\n\t\t\tif( chars[0] != \"-\"[0] && chars.Length > 2 )\n\t\t\t\teditValStr = oldString;\n\t\t\n\t\t//reset the slot's value\n\t\ttry{\n\t\t\tslot.val = int.Parse(editValStr);\n\t\t}catch(err){\n\t\t\tslot.val = 0;\n\t\t}\n\t\t\n\t\tif( (Input.GetButtonDown(\"Fire1\") && !pos.Contains(manager.mousePos)) )\n\t\t{\n\t\t\tmanager.dm.CreateLog(\"CLICK PARAM \" + manager.botVar.botName + \", \" + getIndex() + \", \" + slot.val + \", \" + slotIndex); \n\t\t\teditVal = null;\n\t\t}\n\t\t\n\t}", "function updateA(value) {\n aDisplay.textContent = value;\n aValue = value;\n answer = aValue\n}", "function adjustProblemProbabilities(accuracy)\n{\n\tvar currentProblemMultiplier;\n\tvar relatedProblemMultiplier;\n\tswitch(accuracy){\n\t\tcase 'bullseye':\n\t\t\tcurrentProblemMultiplier = .5; // If you get a bullseye, the problemProbability for the current problem will decrease by a factor of 2\n\t\t\trelatedProblemMultiplier = .8; // and related problem probabilities will decrease by a factor of .2\n\t\t\tbreak;\n\t\tcase 'closeEnough':\n\t\t\tcurrentProblemMultiplier = .75;\n\t\t\trelatedProblemMultiplier = .9;\t\t\t\n\t\t\tbreak;\n\t\tcase 'wrong':\n\t\t\tcurrentProblemMultiplier = 1.6; // If you get a problem wrong, probabilities increase\n\t\t\trelatedProblemMultiplier = 1.3;\n\t\t\tbreak;\n\t}\n\t\n\tvar currentProblemProbability = currentProblem.probability;\n\tvar newProblemProbability = currentProblemProbability * currentProblemMultiplier;\n\tcurrentProblem.probability = Math.min(1,newProblemProbability); // ensures probabilities never get larger than 1\n\t\n\tvar denom = currentProblem.denominator; // changes probabilities for all related problems\n\tfor(var numer = 0; numer <= currentProblem.denominator; numer++){ \n\t\tcurrentProblemProbability = fractionProblems[denom][numer].probability;\n\t\tnewProblemProbability = currentProblemProbability * relatedProblemMultiplier;\n\t\tif(numer != currentProblem.numerator){ // we don't adjust this problem because we already did\n\t\t\tfractionProblems[denom][numer].probability = Math.min(1,newProblemProbability);\n\t\t}\n\t}\n}", "function testTipItemSetGetValue() {\n assertEquals('', why_tip.getValue());\n why_tip.setValue(VALUE);\n assertEquals(VALUE, why_tip.getValue());\n}", "get speedVariation() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset the variables other then the name and department in order to start a new research Check the validty of the name Call the getEstablishments() function of the getEstablishmentsSrv service await for the results before computing the retrieved data
apisCall() { // Reset the variables other then the name and department in order to start a new research $scope.view.establishments.tooMuchResults = false; $scope.view.establishments.searchSuccess = false; $scope.view.establishments.resultsBeforeFiltering = 0; $scope.view.establishments.resultsTable = []; // Call the getEstablishments() function of the getEstablishmentsSrv service // Use what the stringNormalize() function of the stringFormatingSrv service returns as the establishment's name EstablishmentSrv.getAllEstablishments($scope.view.establishments.name, $scope.view.establishments.department) .then( (response) => { $scope.view.establishments.tooMuchResults = response.tooMuchResults; $scope.view.establishments.resultsTable = response.resultsTable; $scope.view.establishments.resultsBeforeFiltering = response.resultsBeforeFiltering; $scope.view.establishments.searchSuccess = true; }, (error) => { $scope.view.errorMsg = error; $scope.view.establishments.searchSuccess = true; $scope.view.establishments.resultsTable = []; }, ); }
[ "establishmentsSearch() {\n $scope.view.errorMsg = '';\n\n // We check the validity of the name\n if ($scope.nameUnvalidity()) {\n return;\n }\n\n // If the current searched establishment name is the same as the previous searched one\n if ($scope.view.establishments.name === $scope.view.establishments.previousSearchedName) {\n // If the current searched department name is different than the previous searched one\n if ($scope.view.establishments.department !== $scope.view.establishments.previousSearchedDepartment) {\n // If the searched department is null\n if (!$scope.view.establishments.department) {\n // We search the establishment by calling the api(s)\n $scope.apisCall();\n } else {\n // We check if the department is valid or not\n if ($scope.departmentUnvalidity()) {\n // If t's not valid we stop the search\n return;\n }\n\n // If there is already enterprises stored into the resultsTable\n if ($scope.view.establishments.resultsTable.length) {\n // We call the fucntion that will filter the resultTable\n $scope.view.establishments.resultsTable = EstablishmentSrv.establishmentsResultsFiltering($scope.view.establishments.resultsTable, $scope.view.establishments.department);\n } else {\n // We send the data to the api(s)\n $scope.apisCall();\n }\n }\n }\n } else {\n if ($scope.view.establishments.department) {\n if ($scope.departmentUnvalidity()) {\n // If t's not valid we stop the search\n return;\n }\n }\n\n // We search the establishment by calling the api(s)\n $scope.apisCall();\n }\n\n // At the end of the establishment search :\n // We update the value of the last establishment searched\n $scope.view.establishments.previousSearchedName = $scope.view.establishments.name;\n\n // We update the value of the last department searched\n $scope.view.establishments.previousSearchedDepartment = $scope.view.establishments.department;\n\n // We reset the value of the department to search\n $scope.view.establishments.department = '';\n }", "function search() {\n vm.showManager = false;\n DeptService\n // we pass contents of vm.searchString to service so that we can search the DB for this string\n .retrieveDeptDB(vm.searchString)\n .then(function (results) {\n // The result returned by the DB contains a data object, which in turn contains the records read\n // from the database\n vm.departments = results.data;\n })\n .catch(function (err) {\n console.log(\"error \" + err);\n });\n }", "function beginTeam() {\n console.log(\"Please build your software engineering team\");\n inquirer.prompt(managerQuestions).then(answers => {\n const manager = new Manager(answers.managerName, answers.managerID, answers.managerEmail, answers.managerOffice);\n teamMembers.push(manager);\n idsArray.push(answers.managerID);\n employees();\n });\n }", "async getAllFacultyInfo() {\n\n try {\n let allParty = await partyEntity.getAllParty();\n let party=[]\n for(let i=0;i<allParty.length;i++){\n let partyRole=await partyRoleEntity.getPartyRoleByPartyId(allParty[i]._id);\n let partyRoleTypeId=partyRole.roleTypeId;\n if(partyRoleTypeId==\"FACULTY\"){\n party.push(allParty[i]);\n }\n }\n let allPartyInfo=[];\n for (let i = 0; i < party.length; i++) {\n\n // let partyContactMech = await partyContactMechEntity.getPartyContactMechByPartyId(party[i]._id);\n // let postalAddress = await postalAddressEntity.getpostalAddressBycontactMechId(partyContactMech.contactMechId);\n let person = await personEntity.getPersonByPartyId(party[i]._id);\n // let telecomNumber = await telecomNumberEntity.getTelecomNumberBycontactMechId(partyContactMech.contactMechId);\n let partyRole = await partyRoleEntity.getPartyRoleByPartyId(party[i]._id);\n // let email = await emailEntity.getEmailByContactMechId(partyContactMech.contactMechId);\n let partyDesignation = await partyDesignationEntity.getPartyDesignationByPartyId(party[i]._id);\n let partyFaculty=await partyFacultyEntity.getPartyFacultyByPartyId(party[i]._id);\n let partyDepartmentSchool=await partyDepartmentSchoolEntity.getPartyDepartmentSchoolByPartyId(party[i]._id);\n partyInfo = {\n party: party[i],\n //partyContactMech: partyContactMech,\n //postalAddress: postalAddress,\n person: person,\n partyFaculty:partyFaculty,\n //telecomNumber: telecomNumber,\n partyRole: partyRole,\n partyDepartmentSchool:partyDepartmentSchool,\n //email: email,\n partyDesignation: partyDesignation,\n }\n allPartyInfo.push(partyInfo);\n }\n // let partyContactMech = await partyContactMechEntity.getAllPartyContactMech();\n // let postalAddress = await postalAddressEntity.getAllpostalAddress();\n // let person = await personEntity.getAllPerson();\n // let telecomNumber = await telecomNumberEntity.getAllTelecomNumber();\n // let partyRole = await partyRoleEntity.getAllPartyRole();\n // let userLogin = await userLoginEntity.getAllUserLogin();\n // let userLoginSecurityGroup = await userLoginSecurityGroupEntity.getAllUserLoginSecurityGroup();\n // let email=await emailEntity.getAllEmail();\n // let partyDesignation = await partyDesignationEntity.getAllPartyDesignation();\n return allPartyInfo;\n }\n catch (e) {\n throw e;\n }\n }", "function searchEstablishments(searchParams) {\n\n return instance.get('/Establishments', {\n params: searchParams\n })\n .then(function (response) {\n return (response);\n })\n .catch(function (error) {\n return (error);\n });\n\n }", "async loadOccupation() {\n let data = await this.httpClient.fetch('/api/occupation-table/occupation.json');\n let loadedData = await data.json();\n this.readFile.getCategoryList(loadedData);\n this.createJobArrays(\"Manual Labor\");\n this.createJobArrays(\"Industry\");\n this.createJobArrays(\"Public Service\");\n this.createJobArrays(\"Management\");\n }", "function fillData(result){\r\n\t\tExt.data.StoreManager.lookup('employeeStore').loadData(result);\r\n\t}", "fetchStudentDetailsByDept(departmentName) {\n this.setState({ studentDetails: [] })\n axios.get(`/xakal/studentdetail/department/${departmentName}`)\n .then((response) => {\n this.setState({ studentDetails: response.data });\n });\n }", "function viewEmployeesByDepartment() {\n db.query(`SELECT * FROM department`, (err, data) => {\n if (err) throw err;\n\n const department = data.map(({\n id,\n name\n\n }) => ({\n name: name,\n value: id\n }));\n inquirer.prompt([{\n name: \"department\",\n type: \"list\",\n message: \"Select A Department:\",\n choices: department\n }]).then(event => {\n const department = event.department;\n db.query(`SELECT CONCAT(first_name, ' ', last_name) AS Employees, department.name AS Department FROM employee JOIN role ON employee.role_id = role.id JOIN department ON role.department_id = department.id WHERE department_id= ${department};`, function (err, results) {\n if (err) throw err\n console.table(results)\n\n initPrompt()\n })\n })\n })\n}", "function addDepartment() {\n\tinquirer.prompt(prompt.insertDepartment).then(function (answer) {\n\t\tvar query = \"INSERT INTO department (name) VALUES ( ? )\";\n\t\tconnection.query(query, answer.department, function (err, res) {\n\t\t\tif (err) throw err;\n\t\t\tconsole.log(\n\t\t\t\t`You have added this department: ${answer.department.toUpperCase()}.`,\n\t\t\t);\n\t\t});\n\t\tconsole.log(\"\\n<<<<<<<<<<<<<<<<<<<< ⛔ >>>>>>>>>>>>>>>>>>>>\\n\");\n\t\tviewAllDepartments();\n\t});\n}", "function getEstablishmentsBasic(params = { pageNumber: null, pageSize: null }) {\n\n var url = '/Establishments/basic/';\n\n //check to see if the request is being made with pageNumber and pageSize params\n if (params.pageNumber && params.pageSize) {\n url = url + `${params.pageNumber}/${params.pageSize}`;\n }\n\n return instance.get(url)\n .then(function (response) {\n return (response);\n })\n .catch(function (error) {\n return (error);\n });\n\n }", "function addDepartment() {\n\tinquirer.prompt(prompt.insertDepartment).then(function (answer) {\n\t\tvar query = \"INSERT INTO department (name) VALUES ( ? )\";\n\t\tconnection.query(query, answer.department, function (err, res) {\n\t\t\tif (err) throw err;\n\t\t\tconsole.log(\n\t\t\t\t`You have added this department: ${answer.department.toUpperCase()}.`,\n\t\t\t);\n\t\t});\n\t\tconsole.log(\"\\n<<<<<<<<<<<<<<<<<<<< ⛔ >>>>>>>>>>>>>>>>>>>>\\n\");\n\t\tviewDepartments();\n\t});\n}", "function startTracker() {\n inquirer\n .prompt(questions)\n .then(function(res, err) {\n if (err) throw err;\n switch (res.what_to_do) {\n case \"View Departments\":\n viewDepartments();\n break;\n case \"View Roles\":\n viewRoles();\n break;\n case \"View All Employees\":\n viewAllEmployees();\n break;\n // case \"View Employees by Manager\":\n // viewEmployeesByManager();\n // break;\n // case \"View Employees by Department\":\n // viewEmployeesByDepartment();\n case \"Add Employee\":\n addEmployee();\n break;\n // case \"Remove an Employee\":\n // removeEmployee();\n // break;\n case \"Add a Department\":\n addDepartments();\n break;\n case \"Add a Role\":\n addRoles();\n break;\n case \"Exit\":\n connection.end();\n break;\n default:\n console.log(\"Error Occured\");\n break;\n }\n })\n .catch(function(err, res) {\n console.log(err);\n });\n}", "function viewEmployeeByDepartment() {\n\tconsole.log(\"View employees by department\\n\");\n\n\tvar query = `SELECT d.id, d.name\n\tFROM employee e\n\tLEFT JOIN role r\n\tON e.role_id = r.id\n\tLEFT JOIN department d\n\tON d.id = r.department_id\n\tGROUP BY d.id, d.name`;\n\n\tconnection.query(query, function (err, res) {\n\t\tif (err) throw err;\n\n\t\t// Select department\n\t\tconst departmentChoices = res.map((data) => ({\n\t\t\tvalue: data.id,\n\t\t\tname: data.name,\n\t\t}));\n\n\t\tinquirer\n\t\t\t.prompt(prompt.departmentPrompt(departmentChoices))\n\t\t\t.then(function (answer) {\n\t\t\t\tvar query = `SELECT e.id, e.first_name, e.last_name, r.title, d.name AS department \n\t\t\tFROM employee e\n\t\t\tJOIN role r\n\t\t\t\tON e.role_id = r.id\n\t\t\tJOIN department d\n\t\t\tON d.id = r.department_id\n\t\t\tWHERE d.id = ?`;\n\n\t\t\t\tconnection.query(query, answer.departmentId, function (err, res) {\n\t\t\t\t\tif (err) throw err;\n\n\t\t\t\t\tconsole.table(\"\\nDepartment Rota: \", res);\n\t\t\t\t\tconsole.log(\"\\n<<<<<<<<<<<<<<<<<<<< ⛔ >>>>>>>>>>>>>>>>>>>>\\n\");\n\n\t\t\t\t\tfirstPrompt();\n\t\t\t\t});\n\t\t\t});\n\t});\n}", "async finalStep(stepContext) {\n // If the child dialog (\"bookingDialog\") was cancelled or the user failed to confirm, the Result here will be null.\n if (stepContext.result) {\n const result = stepContext.result;\n // Now we have all the booking details.\n\n console.log(result);\n\n // This is where calls to the booking AOU service or database would go.\n let msg = 'I wasn\\'t able to find anyone :( Try searching with different specs?'\n var foundPerson = MainDialog.findPeople(result);\n\n console.log(foundPerson);\n\n if (foundPerson) {\n msg = `You should talk to ${foundPerson.name} in Building ${foundPerson.location}!`; \n }\n\n // If the call to the booking service was successful tell the user.\n const timeProperty = new TimexProperty(result.travelDate);\n const travelDateMsg = timeProperty.toNaturalLanguage(new Date(Date.now()));\n await stepContext.context.sendActivity(msg, 'yeet');\n } else {\n await stepContext.context.sendActivity('Thank you.');\n }\n return await stepContext.beginDialog(MAIN_WATERFALL_DIALOG);\n //return await stepContext.endDialog();\n }", "function dataSearchAndSave(){\n\t\t(async() => {\n\t\t\t// headless chrome browser open \n\t\t\tconst browser = await puppeteer.launch({headless: true});\n\t\t\tconst page = await browser.newPage();\n\n await page.goto(pagequery);\n\t\t\tawait page.waitFor(20000);\n\t\t\t\n\t\t\t// subcompare windows close \n const exitSelector = '.ResultsDialog__close__fc';\n\t\t\tawait page.click(exitSelector);\n\n\t\t\t// price part selecting and reading data\n\t\t\tconst resultsPrice = '.FlightResultsList__price__fc';\n\t\t\tawait page.waitForSelector(resultsPrice);\n\n\t\t\tconst linksPrice = await page.evaluate(resultsPrice => {\n\t\t\t\tconst anchors = Array.from(document.querySelectorAll(resultsPrice));\n\t\t\t\treturn anchors.map(anchor => {\n\t\t\t\t\tconst title = anchor.textContent;\n\t\t\t\t\treturn title;\n\t\t\t\t});\n\t\t\t}, resultsPrice);\n\t\n\t\t\t// Carrier company name selecting and reading \n\t\t\tconst resultsCarriername = '.FlightResultsList__carrierName__fc';\n\t\t\tawait page.waitForSelector(resultsCarriername);\n\n\t\t\tconst linksCarriername = await page.evaluate(resultsCarriername => {\n\t\t\t\tconst anchors = Array.from(document.querySelectorAll(resultsCarriername));\n\t\t\t\treturn anchors.map(anchor => {\n\t\t\t\t\tconst title = anchor.textContent;\n\t\t\t\t\treturn title;\n\t\t\t\t});\n\t\t\t}, resultsCarriername);\n\n\t\t\t// leaving and arriving time selecting and reading\n\t\t\tconst resultsTime = '.FlightResultsList__time__fc';\n\t\t\tawait page.waitForSelector(resultsTime);\n\n\t\t\tconst linksTime = await page.evaluate(resultsTime => {\n\t\t\t\tconst anchors = Array.from(document.querySelectorAll(resultsTime));\n\t\t\t\treturn anchors.map(anchor => {\n\t\t\t\t\tconst title = anchor.textContent;\n\t\t\t\t\treturn title;\n\t\t\t\t});\n\t\t\t}, resultsTime);\n\n\t\t\t// depart and destination code selecting and reading\n\t\t\tconst resultsCode = '.FlightResultsList__code__fc';\n\t\t\tawait page.waitForSelector(resultsCode);\n\n\t\t\tconst linksCode = await page.evaluate(resultsCode => {\n\t\t\t\tconst anchors = Array.from(document.querySelectorAll(resultsCode));\n\t\t\t\treturn anchors.map(anchor => {\n\t\t\t\t\tconst title = anchor.textContent;\n\t\t\t\t\treturn title;\n\t\t\t\t});\n\t\t\t}, resultsCode);\n\n\t\t\t// search result saving part in MongoDB\n\t\t\t//MongoDB connecting\n\t\t\tMongoClient.connect(url, function(err, db) {\n\t\t\t\tif (err) throw err;\n\t\t\t\tvar dbo = db.db(\"myflightdb\");\n\n\t\t\t\tfor(var i = 2; i < linksPrice.length; i+=2){\n\t\t\t\t\tvar myobj = { name: \"FlyTickets\", carriername: linksCarriername[i], departtime: linksTime[i*2], departcode: linksCode[i*2], desttime: linksTime[i*2+1], destcode: linksCode[i*2+1], price: linksPrice[i]};\n\t\t\t\t\tvar myobj1 = { name: \"FlyTickets\", carriername: linksCarriername[i+1], departtime: linksTime[i*2+2], departcode: linksCode[i*2+2], desttime: linksTime[i*2+3], destcode: linksCode[i*2+3], price: linksPrice[i+1]};\n\t\t\t\t\t// result input\n\t\t\t\t\tdbo.collection(\"tickets\").insertOne(myobj, function(err, res) {\n\t\t\t\t\t\tif (err) throw err;\n\t\t\t\t\t});\n\t\t\t\t\tdbo.collection(\"tickets\").insertOne(myobj1, function(err, res) {\n\t\t\t\t\t\tif (err) throw err;\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tdb.close();\n\n\t\t\t});\n\t\t\tawait browser.close();\n\t\t})();\n\n\t\treturn true;\n\t}", "function updateSelectedDepartment() {\n\n }", "async defend() {\n this.setState({\n loading: true,\n });\n\n let myDefence;\n\n try{\n myDefence = await this.state.contractFacade.getOwnDefence();\n } catch (error) {\n }\n\n const trainingOpponentSelection = myDefence\n ? myDefence.selection\n : TRAINING_SELECTION;\n\n this.setState({\n mode: Modes.ShipSelection,\n settingDefence: true,\n trainingOpponentSelection,\n trainingCp: this._selectionToCp(trainingOpponentSelection),\n loading: false,\n });\n }", "async function getDeptByName(deptName) {\n //validates number of arguments\n if (arguments.length != 1) {\n throw new Error(\"Wrong number of arguments\");\n }\n //validates arguments type\n if (!deptName || typeof deptName == \"undefined\" || typeof deptName != \"string\" || deptName.length == 0) {\n throw \"Invalid department name is provided for getDeptByName function\";\n }\n const deptCollection = await dept();\n const department = await deptCollection.findOne({ deptName: deptName });\n if (!department) {\n throw `Department not found with name ${deptName}`;\n }\n \n return department;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the state when we're currently in the mention's text chars
function stateMentionTextChar(stateMachine, char) { if (isMentionTextChar(char)) ; else if (alphaNumericAndMarksRe.test(char)) { // Char is invalid for a mention text char, not a valid match. // Note that ascii alphanumeric chars are okay (which are tested // in the previous 'if' statement, but others are not) remove(stateMachines, stateMachine); } else { captureMatchIfValidAndRemove(stateMachine); } }
[ "function isMentionTextChar(char) {\n return mentionTextCharRe.test(char);\n }", "function stateHashtagTextChar(stateMachine, char) {\n if (isHashtagTextChar(char)) ;\n else {\n captureMatchIfValidAndRemove(stateMachine);\n }\n }", "function emojiInputHandler(event) {\n var userInput = event.target.value;\n // var meaning = emojiDictionary[userInput];\n if (userInput in emojiDictionary) {\n setMeaning(emojiDictionary[userInput]);\n } else setMeaning(\"That's a new one! We don't have this in our database\");\n }", "refreshMentions()\n {\n this.mentions = this.messageRaw.match(/<@(?:\\d){13}>/g) === null ? [] : new Array(...this.messageRaw.match(/<@(?:\\d){13}>/g));\n if (this.mentions.includes(`<@${thisUser.id}>`) && !this.msg.classList.contains('mention'))\n {\n $(this.msg).addClass('mention');\n if (document.visibilityState === 'hidden')\n {\n document.title = `${document.title.match(/\\d+/) === null ? 1 : parseInt(document.title.match(/\\d+/)[0]) + 1}🔴 🅱️iscord`;\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible')\n {\n document.title = '🅱️iscord';\n }\n }, { once: true });\n }\n }\n else if (!this.mentions.includes(`<@${thisUser.id}>`) && this.msg.classList.contains('mention'))\n {\n $(this.msg).removeClass('mention');\n document.title = `${document.title.match(/\\d+/) === null ? '' : parseInt(document.title.match(/\\d+/)[0]) - 1 <= 0 ? '' : `${parseInt(document.title.match(/\\d+/)[0]) - 1}🔴 `}🅱️iscord`;\n }\n }", "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}", "textChangeHandler(event) {\n let newConvertedText = \"\"\n let buffer = \"\";\n\n for (let i = 0; i < event.target.value.length; i++) {\n let targetChar = event.target.value.charAt(i);\n\n if (JAPANESE_CHARACTER_REGEX.test(targetChar)) {\n newConvertedText += buffer + targetChar;\n buffer = \"\";\n continue;\n }\n\n buffer += targetChar;\n\n if (buffer in hiragana) {\n newConvertedText += hiragana[buffer];\n buffer = \"\";\n }\n }\n\n newConvertedText += buffer;\n\n this.setState({\n convertedText: newConvertedText,\n isValid: true,\n helperText: \"\"\n });\n }", "displayKey() {\n var keyVal = key;\n //checks if the key prseed is a char\n if (keyVal.toUpperCase() != keyVal.toLowerCase() && keyVal.length == 1) {\n this.lastKey = keyVal.toUpperCase();\n this.isChar = true;\n textAlign(CENTER)\n text(keyVal.toUpperCase(), 219, 180)\n textAlign(LEFT)\n this.counter = 0;\n\n }\n if (keyIsPressed && !keyIsDown(13)){\n this.isChar = false;\n } \n \n //check when the enter key is pressed; when it is it check if the letter is in the phrase or not\n if (keyIsDown(13) && this.counter == 0 && !this.lost && this.isChar) {\n var repeat = false\n var inPhrase = false;\n //checks if the letter is in the phrase or not\n for (var i = 0; i < this.splitedPhrase.length; i++) {\n if (this.splitedPhrase[i] == this.lastKey) {\n this.blanks[i] = this.splitedPhrase[i];\n text(this.blanks[i], (i * 30), 340)\n inPhrase = true;\n }\n }\n for (var j = 0; j <= this.lettersUsed.length; j++) {\n if (this.lastKey != this.lettersUsed[j]) {\n this.counter++;\n } else repeat = true\n }\n if (inPhrase == false && repeat == false) {\n this.numOfWrongs++;\n }\n if (this.counter != 0 && !repeat && !inPhrase) {\n this.lettersUsed.push(this.lastKey);\n }\n }\n //displays the wrong letters\n textSize(20);\n var Ypos = 70;\n var Xpos = 213;\n textAlign(CENTER);\n for (var i = 0; i < this.lettersUsed.length; i++) {\n if (i % 7 == 0 && i != 0) {\n Ypos += 23;\n Xpos -= 175;\n }\n text(this.lettersUsed[i], Xpos + i * 25, Ypos);\n }\n textAlign(LEFT);\n}", "function change_text( player, target_hit )\n{\n\tfor (var i = 0; i < board_sections.length; i++) \n\t{\n\t\tvar section_text = $(board_sections[i]).text();\n\t\tif (target_hit == section_text) \n\t\t{\n\t\t\tif (player.marker == 'X') \n\t\t\t{\n\t\t\t\t$(board_sections[i]).css('color', '#91c46b');\n\t\t\t\t$(board_sections[i]).text('X');\n\n\t\t\t}\n\t\t\telse if (player.marker == 'O')\n\t\t\t{\n\t\t\t\t$(board_sections[i]).css('color', '#d9534f');\n\t\t\t\t$(board_sections[i]).text('O');\n\t\t\t}\n\t\t}\n\t}\n\tcheck_game( player );\n}", "_updateText() {\n const {data, characterSet} = this.props;\n const textBuffer = data.attributes && data.attributes.getText;\n let {getText} = this.props;\n let {startIndices} = data;\n let numInstances;\n\n const autoCharacterSet = characterSet === 'auto' && new Set();\n\n if (textBuffer && startIndices) {\n const {texts, characterCount} = getTextFromBuffer({\n ...(ArrayBuffer.isView(textBuffer) ? {value: textBuffer} : textBuffer),\n length: data.length,\n startIndices,\n characterSet: autoCharacterSet\n });\n numInstances = characterCount;\n getText = (_, {index}) => texts[index];\n } else {\n const {iterable, objectInfo} = createIterable(data);\n startIndices = [0];\n numInstances = 0;\n\n for (const object of iterable) {\n objectInfo.index++;\n // Break into an array of characters\n // When dealing with double-length unicode characters, `str.length` or `str[i]` do not work\n const text = Array.from(getText(object, objectInfo) || '');\n if (autoCharacterSet) {\n text.forEach(autoCharacterSet.add, autoCharacterSet);\n }\n numInstances += text.length;\n startIndices.push(numInstances);\n }\n }\n\n this.setState({\n getText,\n startIndices,\n numInstances,\n characterSet: autoCharacterSet || characterSet\n });\n }", "function setCodeText(e) {\n document.querySelector(\"#language-selected\").innerHTML =\n extensionState.codeLanguage.charAt(0).toUpperCase() +\n extensionState.codeLanguage.slice(1);\n\n e = e || window.event;\n var keepWordList = e && e.shiftKey;\n\n // Change code snippet if shift key is not hit\n if (!keepWordList) {\n currentCode =\n selectedLanguageCodes[\n Math.floor(Math.random() * selectedLanguageCodes.length)\n ];\n }\n\n // Reset progress state\n clearTimeout(timer);\n gameOver = false;\n codeState = {\n firstChar: null,\n lastChar: null,\n currentChar: null,\n currentCharNum: 0,\n cursorLeftOffset: 0,\n cursorTopOffset: 0,\n linesLastCursorPositions: [],\n };\n\n // Reset cursor position\n cursor.classList.remove(\"hidden\");\n updateCursorPosition(0, 0);\n\n return;\n }", "function updateStateChars() {\n const toPassSymbols = document.getElementsByClassName(\"topass\");\n codeState = {\n ...codeState,\n firstChar: toPassSymbols[0],\n currentChar: toPassSymbols[0],\n lastChar: toPassSymbols[toPassSymbols.length - 1],\n };\n }", "insertMarkdownBetween (character) {\n const beforeText = this.state.text.substring(0, this.state.endOfSelection)\n const afterText = this.state.text.substring(this.state.endOfSelection, this.state.text.length)\n\n this.setState({\n text: beforeText + character + afterText\n })\n }", "function nextWordActive(e) {\n const word = document.querySelector('.word.active') || wordsContainer.firstChild\n const wordsLength = wordsContainer.children.length\n\n if (e.keyCode === 32) {\n wordIndex++\n const currentWord = wordsContainer.children[wordIndex]\n currentWord.classList.add('active')\n word.classList.remove('active')\n letterIndex = 0\n slashCoords()\n textarea.value = ''\n\n for (let i = 0; i < word.children.length; ++i) {\n if (word.children[i].classList.contains('incorrect') || word.children[i].classList.contains('extra')) {\n word.classList.add('word__incorrect')\n }\n }\n }\n\n wordsAmount.textContent = `${wordIndex} / ${wordsLength}`\n}", "function chooseEmoji(e) {\n if(e.target.matches(\".emoji\")) {\n textarea.value += e.target.innerHTML\n }\n}", "function italicText() {\n document.execCommand('italic', false, '');\n browser.storage.local.set({\n key: txtArea.innerHTML\n });\n}", "function onMessageActive(newval, oldval) {\n if(!newval && !oldval)\n return;\n\n if(newval && !oldval) {\n $scope.focusTextInput();\n }\n }", "SET_ACTIVE_CHAR(state, char) {\n state.activeChar = char;\n }", "function revealLetter() {\n\t\t\tuserGuessIndex = word.indexOf(userGuess);\n\t\t\tfor (i=0; i < word.length; i++) {\n\t\t\t\tif (word[i] === userGuess) {\n\t\t\t\t\thide = hide.split(\"\");\n\t\t\t\t\thide[i] = userGuess;\n\t\t\t\t\thide = hide.join(\"\");\n\t\t\t\t\ttargetA.innerHTML = hide;\n\n\t\t\t\t}\n\t\t\t}\t\n\t\t}", "function changeEmojiBox()\n{\n console.log('in change Emojii arrived');\n $('#emojis-button').toggle(); \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Funcion para calcular la fecha de primer pago de las comisiones sabiendo cuanto segundos tiene un dia, calcularemos los de 90 y se los aplicaremos a la fecha actual.
function fechaPago() { var fechaActual = new Date(); var dia1 = new Date(2010, 1, 1); var dia2 = new Date(2010, 1, 2); var diferenciaDia = ((dia2 - dia1) * 90); //Laura: tendrás que sumar los milisegundos de 90 días, no se puede mezclar fechas con números var fechaPago = new Date(diferenciaDia - fechaActual); //Laura: el formato es DD/MM/YYYY alert("Fecha de primer pago de comisiones: \n" + fechaPago.toLocaleDateString()); }
[ "function fecha() {\n var a = new Date(2001, 2, 1);//valor1 para calcular el paso de 90 dias\n var b = new Date(2001, 4, 30);//valor2 para calcular el paso de 90 dias \n var x = a.getTime();//valor1 en tiempo transcurrido desde la epoca de unix\n var y = b.getTime();//valor2 en tiempo transcurrido desde la epoca de unix\n var tiempo = y - x;//calculo del tiempo pasado en 90 dias\n var fecha_actual = new Date();//fecha actual\n var hoy = fecha_actual.getTime();//fecha actual en tiempo transcurrido desde la epoca unix\n var comision = hoy + tiempo;//resultado del tiempo que transcurre en 90 dias desde la fecha actual\n var total = new Date(comision);//fecha tras los 90 dias\n //Laura: formato DD/MM/YYYY\n var dia = total.getDate();//dia tras los 90 dias\n var mes = total.getMonth() + 1;//mes tras los 90 dias en formato 1-12\n var ano = total.getFullYear();//año tras los 90 dias en formato 4 digitos\n alert(\"Empezaras a pagar comisiones el: \" + dia + \"/\" + mes + \"/\" + ano);//muestra la fecha tras 90 dias \n\n}", "function ultimaPagina(){\n\tif(pagina_actual!=paginas_totales){\n\t\tpagina_actual=paginas_totales;\n\t\tconsole.log('Moviendonos a la página '+pagina_actual+\"...\");\n\t\tborrar_recetas_index();\n\t\t\n\t\tlet pagina = paginas_totales-1;\n\t\tpeticionRecetas(\"./rest/receta/?pag=\"+pagina+\"&lpag=6\");\n\t\tModificar_botonera_Index();\n\t}\n}", "function extraer_tiempototal(horaini, horaact) {\n var diff;\n\n var fecha1 = horaini.substring(6, horaini.length - 2);\n var fecha2 = horaact.substring(6, horaini.length - 2);\n\n diff = fecha2 - fecha1;\n // calcular la diferencia en segundos\n var diffSegundos = Math.abs(diff / 1000);\n\n\n // calcular la diferencia en minutos\n var diffMinutos = Math.abs(diff / (60 * 1000));\n\n var restominutos = diffMinutos % 60;\n\n // calcular la diferencia en horas\n var diffHoras = (diff / (60 * 60 * 1000));\n\n // calcular la diferencia en dias\n var diffdias = Math.abs(diff / (24 * 60 * 60 * 1000));\n\n //console.log(\"En segundos: \" + diffSegundos + \" segundos.\");\n //console.log(\"En minutos: \" + diffMinutos + \" minutos.\");\n //console.log(\"En horas: \" + diffHoras + \" horas.\");\n //console.log(\"En dias: \" + diffdias + \" dias.\");\n\n var devolver = parseInt(diffHoras) + \"H \" + Math.round(restominutos) + \"m \";\n //console.log(devolver)\n\n var tiempototal = Math.round((parseInt(diffHoras) * 60) + restominutos);\n\n //console.log(tiempototal);\n\n return tiempototal;\n\n}", "function readPerDay(googlePagination) {\n\n tDiffNum = tDiff.split(\" \")[1];\n\n tDiffNum = parseInt(tDiff.split(\" \")[1]);\n googlePagination = parseInt(googlePagination);\n\n var pgesPerDay = Math.round((googlePagination / tDiffNum));\n console.log(\"The reader should read \" + pgesPerDay + \" pages per day\");\n\n $(\"#pagesPerDay\").append(pgesPerDay);\n }", "function calcularProm(filas)\n{\n let promedio = document.getElementById('promedio');\n let max = document.getElementById('precioMaximo');\n let min = document.getElementById('precioMinimo');\n if(filas.length != 0 )\n {\n let celdas = traerColumna(filas,'name','CELDAPRECIO').map((e)=>parseInt(precioDeServer(e.textContent)));\n let precioFinal = celdas.reduce((a,b)=> a + b) / celdas.length;\n let precioMaximo = celdas.reduce((a,b)=> a>=b ? a : b);\n let precioMinimo = celdas.reduce((a,b)=> a>=b ? b : a);\n promedio.value = precioDeForm(precioFinal);\n max.value = precioDeForm(precioMaximo);\n min.value = precioDeForm(precioMinimo);\n }\n else{\n promedio.value = precioDeForm(0);\n max.value = precioDeForm(0);\n min.value = precioDeForm(0);\n }\n porcentajeVacunados(filas);\n}", "function cicloPrincipal(){\r\n\t\tpasado=actual;\r\n\t\tactual=new Date().getTime()/1000;\r\n\t\t//Se actualiza cada segundo (temporal)\r\n\t\tif( Math.floor(actual-tiempo)%300===0 && Math.floor(actual-tiempo) !== 0){\r\n\t\t\tincrementarRacha();\r\n\t\t}\r\n\t\tactualizarDinero();\r\n\t\tgetID(\"tiempo\").innerHTML = \"Tiempo de juego: \" + time(tiempo);\r\n\t\tcpsActual = cps*racha.toFixed(1);\r\n\t\tdineroTotal += cpsActual;\r\n\t\tdineroActual += cpsActual;\r\n\t\tpasado = new Date().getTime()/1000;\r\n\r\n\t\tif( jugadorActivo() === false ){ \r\n\r\n\t\t\tvar resp = confirm(\"Jugador inactivo\");\r\n\r\n\t\t\tif(resp || !resp){\r\n\t\t\t\treinicio();\r\n\t\t\t}\r\n\t\t\t//reiniciar juegoS\r\n\t\t}\r\n\t\t//alert(Math.floor(actual-tiempo));\r\n\r\n\t\tsetTimeout(cicloPrincipal,1000);\r\n\t}", "function primeraPagina(){\n\tif(pagina_actual!=1){\n\t\t\n\t\tpagina_actual = 1;\n\t\tconsole.log('Moviendonos a la página '+pagina_actual+\"...\");\n\t\tborrar_recetas_index();\n\t\tlet pagina = pagina_actual-1;\n\t\tpeticionRecetas(\"./rest/receta/?pag=\"+pagina+\"&lpag=6\");\n\t\tModificar_botonera_Index();\n\t}\n}", "function pronalazenjeDatuma(d) {\n\n let mesec = d.getMonth() + 1;\n if (mesec.toString().length == 1) {\n mesec = \"0\" + mesec.toString();\n }\n let dan = d.getDate();\n if (dan.toString().length == 1) {\n dan = \"0\" + dan.toString();\n }\n let danas = getDatum(dan + \" \" + mesec + \" \" + d.getFullYear());\n var dict = {}; //key = datum, value = pozicija u tabeli\n\n let dat = parseInt(d.getDate());\n\n for (let index = danas; index <= 6; index++) {\n if (mesec == 1 || mesec == 3 || mesec == 5 || mesec == 7 || mesec == 8 || mesec == 10 || mesec == 12) {\n if (dat > 31) {\n dat = 1;\n }\n } else if (mesec == 2) {\n if (dat > 29) {\n dat = 1;\n }\n } else {\n if (dat > 30) {\n dat = 1;\n }\n }\n dict[dat] = index;\n dat++;\n }\n\n let brojac = 0;\n for (let index = danas; index > 0; index--) {\n if (mesec == 1 || mesec == 3 || mesec == 5 || mesec == 7 || mesec == 8 || mesec == 10 || mesec == 12) {\n if (dat > 31) {\n dat = 1;\n }\n } else if (mesec == 2) {\n if (dat > 29) {\n dat = 1;\n }\n } else {\n if (dat > 30) {\n dat = 1;\n }\n }\n dict[d.getDate() - index] = brojac;\n brojac++;\n }\n for (var key in dict) {\n dobavi(key, dict, d);\n }\n}", "function calculateage(yr, mon, day, unit, indecimal)\r\n{\r\n var one_day = 1000*60*60*24;\r\n var one_month = 1000*60*60*24*30;\r\n var one_year = 1000*60*60*24*30*12;\r\n\r\n var today = new Date();\r\n var pastdate = new Date(yr, mon-1, day);\r\n\r\n var countunit = unit;\r\n var decimals = indecimal;\r\n\r\n finalunit = (countunit == \"days\")? one_day : (countunit == \"months\")? one_month : one_year;\r\n decimals = (decimals <= 0)? 1 : decimals*10;\r\n\r\n if (unit != \"years\")\r\n {\r\n return (Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals);\r\n }\r\n else\r\n {\r\n yearspast=today.getFullYear()-yr-1;\r\n tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0;\r\n pastdate.setFullYear(today.getFullYear());\r\n pastdate2=new Date(today.getFullYear()-1, mon-1, day);\r\n tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals;\r\n return (yearspast+tail);\r\n }\r\n}", "function calcularPrecioConDescuento(precio, descuento){\n const porcentajePrecioConDescuento = 100 - descuento;\n const precioConDescuento = (precio * porcentajePrecioConDescuento) / 100;\n\n return precioConDescuento;\n //return (precio * (100 - descuento) ) / 100;\n // esto no es tan legible como lo anterior.\n}", "function Dias_Fevereiro(ano){\n if ( ano%4==0 && ( ano%100!=0 || ano%400==0) ) return 29;\n else return 28; \n}", "function calculateTimeLeft(then){\r\n //this line is getting the current time and date\r\n var now = new Date().getTime();\r\n //this line is getting the difference(gap) between now and the selected holiday\r\n var gap = then - now;\r\n\r\n var seconds = 1000;\r\n var minutes = seconds* 60;\r\n var hours = minutes * 60;\r\n var days = hours * 24;\r\n\r\n var d = Math.floor(gap/(days));\r\n var h = parseInt(Math.floor(gap % (days))/ (hours));\r\n var m = parseInt(Math.floor(gap % (hours))/ (minutes));\r\n var s = parseInt(Math.floor(gap % (minutes))/ (seconds));\r\n\r\n document.getElementById('day').innerText = d;\r\n document.getElementById('hour').innerText = h;\r\n document.getElementById('minute').innerText = m;\r\n document.getElementById('second').innerText = s;\r\n\r\n}", "function PagesPerMinute() {\n // Your code here\n for (i = 1, dep = 20; i <= 6; i++) {\n result = dep * i;\n console.log(result);\n }\n}", "getReportRange(date1,date2){\n let d1= new Date(date1);\n let d2 = new Date(date2);\n let days = (d2.getTime() - d1.getTime()) / (1000*60*60*24)\n let goal = this.gCals() * days;\n let eaten = this.getFoodRange(date1,date2).calories;\n let burned = this.getActivitiesRange(date1,date2).caloriesBurned;\n let calRemaining = goal - eaten + burned;\n return {eaten: eaten, burned: burned, goal: goal, \n remaining: calRemaining};\n }", "function find_pay_period(date) {\n var start_ts,end_ts\n var ts_arr = [false,false]\n //\n if (date instanceof Array) {\n if (date.length < 3) { console.log('Error in date array: ',date); return ts_arr;}\n date = new Date(Number(date[0]),Number(date[1])-1,Number(date[2]));\n }\n else if ((typeof date == 'string') || (date instanceof String)) {\n var date_arr = date.match(/(\\d+).(\\d+).(\\d+)/)\n if (date_arr.length < 4) { console.log('Error in date string: ',date); return ts_arr;}\n date = new Date(Number(date_arr[1]),Number(date_arr[2])-1,Number(date_arr[3]));\n }\n //\n var st_pp = new Date(CONSTANTS.FIRST_BUSINESS_DAY[0],+CONSTANTS.FIRST_BUSINESS_DAY[1]-1,CONSTANTS.FIRST_BUSINESS_DAY[2]);\n var test_date = st_pp;\n ts_arr = [st_pp]\n if (date < st_pp) {\n while (true) {\n ts_arr[1] = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()));\n test_date = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()-14));\n ts_arr[0] = test_date;\n if ((date >= ts_arr[0]) && (date <= ts_arr[1])) {break;}\n if (date >= ts_arr[0]) { break;}\n }\n }\n else {\n while (true) {\n test_date = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()+14));\n ts_arr[1] = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()-1));\n if (test_date >= date) { break;}\n ts_arr = [test_date];\n }\n }\n //\n ts_arr[0] = ts_arr[0].yyyymmdd();\n ts_arr[1] = ts_arr[1].yyyymmdd();\n //\n return ts_arr;\n}", "function sumarDias(dias, fecha){\n\tvar dias = parseInt(dias);\n\tfecha.setDate(fecha.getDate() + dias);\n return fecha;\n}", "function sec() {\n var now = new Date();\n var start = new Date(2020,0,1);\n var dif = now.getTime() - start.getTime();\n \n var Seconds_from_T1_to_T2 = dif / 1000;\n var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);\n document.write(\"On reference date \"+ now +\" <br>\"+ Seconds_Between_Dates +\" seconds had passed since begining of 2020\");\n}", "function yearPercentagesRekenen(){\n YearPercentageGewerkteUren = YearGewerktUren/YearTotaalUren;\n YearPercentageOver100Uren = YearOver100Uren/YearTotaalUren;\n YearPercentageOver125Uren = YearOver125Uren/YearTotaalUren;\n YearPercentageVerlofUren = YearVerlofUren/YearTotaalUren;\n YearPercentageZiekteUren = YearZiekteUren/YearTotaalUren;\n\n \n}", "function diaDeComienzo(){\n let comienzo = new Date(anioCorriente, numeroMes, 1);\n return (comienzo.getDay()) //18'18\" devolver el dia de la semana numero 1\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return K8s descriptor representation.
toDescriptor() { return { apiVersion: 'v1', kind: 'Secret', metadata: this.metadata, data: Object.entries(this.data).reduce((hash, entry) => { const [ key, value ] = entry; if (value !== undefined) hash[key] = toBase64(value); return hash; }, {}) }; }
[ "function cfnAnomalyDetectorJsonFormatDescriptorPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAnomalyDetector_JsonFormatDescriptorPropertyValidator(properties).assertSuccess();\n return {\n Charset: cdk.stringToCloudFormation(properties.charset),\n FileCompression: cdk.stringToCloudFormation(properties.fileCompression),\n };\n}", "function cfnAnomalyDetectorFileFormatDescriptorPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAnomalyDetector_FileFormatDescriptorPropertyValidator(properties).assertSuccess();\n return {\n CsvFormatDescriptor: cfnAnomalyDetectorCsvFormatDescriptorPropertyToCloudFormation(properties.csvFormatDescriptor),\n JsonFormatDescriptor: cfnAnomalyDetectorJsonFormatDescriptorPropertyToCloudFormation(properties.jsonFormatDescriptor),\n };\n}", "getPrivKey() {\n var output = PrivKeyAsn1.encode({\n d: this.key.priv.toString(10),\n }, \"der\")\n return output.toString('hex')\n }", "get invertedDesc() {\n let sections = [];\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n if (ins < 0)\n sections.push(len, ins);\n else\n sections.push(ins, len);\n }\n return new ChangeDesc(sections);\n }", "function cfnVirtualNodeDnsServiceDiscoveryPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_DnsServiceDiscoveryPropertyValidator(properties).assertSuccess();\n return {\n Hostname: cdk.stringToCloudFormation(properties.hostname),\n IpPreference: cdk.stringToCloudFormation(properties.ipPreference),\n ResponseType: cdk.stringToCloudFormation(properties.responseType),\n };\n}", "function cfnAnomalyDetectorCsvFormatDescriptorPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAnomalyDetector_CsvFormatDescriptorPropertyValidator(properties).assertSuccess();\n return {\n Charset: cdk.stringToCloudFormation(properties.charset),\n ContainsHeader: cdk.booleanToCloudFormation(properties.containsHeader),\n Delimiter: cdk.stringToCloudFormation(properties.delimiter),\n FileCompression: cdk.stringToCloudFormation(properties.fileCompression),\n HeaderList: cdk.listMapper(cdk.stringToCloudFormation)(properties.headerList),\n QuoteSymbol: cdk.stringToCloudFormation(properties.quoteSymbol),\n };\n}", "toString() {\n const {name, _schema: schema} = this.constructor;\n return `${ name }<Model> {\\n ${\n Object.keys(schema.attributeIdentities).map(attribute => (\n `${ attribute }: ${ this[attribute] }`\n )).join(',\\n ')\n }\\n}`;\n }", "listDesc() {\n const desc = this.st.lists[t.getKey(this.path.key)];\n return desc || null;\n }", "lookupDescriptor(any) {\n return this.root.lookupType(AnySupport.stripHostName(any.type_url));\n }", "function propertyDescriptors() {\r\n console.log('--------------------- Property Descriptors ---------------------');\r\n\r\n var enber = {\r\n name: {christian: 'Christian', family: 'Bale'},\r\n age: 50\r\n };\r\n\r\n Object.defineProperty(enber, 'fullName', {\r\n get: function getFullName() {\r\n return this.name.family + '; ' + this.name.christian;\r\n },\r\n set: function setFullName(fullName) {\r\n var object = this;\r\n\r\n var names = fullName.split(' '); // ['John', 'Martin', 'Doe'] <<<< 'John Martin Doe'\r\n this.name.family = names.splice(names.length - 1, 1); // 'Doe' <-- ['John', 'Martin', ]\r\n\r\n this.name.christian = names.splice(0, 1);\r\n names.map(function (name) {\r\n object.name.christian = object.name.christian + ' ' + name;\r\n });\r\n }\r\n });\r\n\r\n console.log('enber object\\'s keys:', Object.keys(enber));\r\n console.log('enber object\\'s own property names:', Object.getOwnPropertyNames(enber));\r\n\r\n console.log('full name:', enber.fullName);\r\n console.log('set name...');\r\n enber.fullName = 'Johanns Chrisostomus Wolfgangus Amadeus Mozart';\r\n console.log('full name:', enber.fullName);\r\n }", "function _edgeViz(edge) {\n var viz = {};\n\n // Color\n var color_el = _helpers.getFirstElementByTagNS(edge, '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 // Shape\n var shape_el = _helpers.getFirstElementByTagNS(edge, 'viz', 'shape');\n if (shape_el) viz.shape = shape_el.getAttribute('value');\n\n // Thickness\n var thick_el = _helpers.getFirstElementByTagNS(edge, 'viz', 'thickness');\n if (thick_el) viz.thickness = +thick_el.getAttribute('value');\n\n return viz;\n }", "_serialize() {\n return JSON.stringify([\n this._id,\n this._label,\n this._properties\n ]);\n }", "function typeDescriptorForInstanceId (instanceId) {\n // Locate the instance in the generic collection.\n const instance = payload[referencesName].find (element => element[primaryKey] === instanceId);\n\n if (isPresent (instance)) {\n // We need to relocate this object to a collection of its concrete types,\n // and update this reference.\n\n const concreteModelName = serializer.modelNameFromPayloadKey (instance.type);\n const concreteTypeNames = pluralize (concreteModelName);\n\n (payload[concreteTypeNames] = payload[concreteTypeNames] || []).push (instance);\n\n // Return the type descriptor for this instance.\n return { type: concreteModelName, id: instanceId };\n }\n else {\n // Just return the instance id.\n return instanceId;\n }\n }", "getFieldLabels() {\n return {\n \"name\":t(\"Name\"),\n \"parent\": t(\"Parent Category\")\n }\n }", "clone() {\n const newMetadata = new Metadata(this.options);\n const newInternalRepr = newMetadata.internalRepr;\n for (const [key, value] of this.internalRepr) {\n const clonedValue = value.map(v => {\n if (Buffer.isBuffer(v)) {\n return Buffer.from(v);\n }\n else {\n return v;\n }\n });\n newInternalRepr.set(key, clonedValue);\n }\n return newMetadata;\n }", "toJSON() {\n var _a;\n return {\n name: this.name,\n parent: (_a = this.parent) === null || _a === void 0 ? void 0 : _a.toJSON(),\n symbols: [\n ...new Set([...this.symbolMap.entries()].map(([key, symbols]) => {\n return symbols.map(x => x.name);\n }).flat().sort())\n ]\n };\n }", "async getDescription() {\n const descriptionEl = await this._description();\n return descriptionEl ? descriptionEl.text() : null;\n }", "kv(key: string) {\n const desc = this.kvDesc(key);\n if (!desc) return null;\n\n return desc.value;\n }", "deserialize(any) {\n const desc = this.lookupDescriptor(any);\n let bytes = any.value;\n if (typeof bytes === \"undefined\") {\n bytes = new Buffer(0);\n }\n return desc.decode(bytes);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the classname from the id of the link
function getClassFromId( startId ) { console.log( '...startId', startId ); var arr = startId.split( '-' ); arr.pop(); var startClass = arr.join( '-' ); console.log( '...startClass', startClass ); return startClass; }
[ "function ajax_getClassName( element ) {\r\n if (ie4 && browser != \"Opera\" && ! ie8)\r\n return (element.getAttribute(\"className\"));\r\n else return (element.getAttribute(\"class\"));\r\n}", "function CLASS_SELECTOR(className)\n{\n return \".\" + className;\n}", "function getClassByLearnerId(id) {\n return db(\"class_learners as cl\")\n .join(\"classes as c\", \"cl.classId\", \"c.id\")\n .join(\"teachers as t\", \"c.teacherId\", \"t.id\")\n .where(\"cl.learnerId\", id)\n .select(\"c.className\", \"c.subject\", \"t.prefix\", \"t.teacherLastName\");\n}", "function name_class(klass, id) {\n klass.__classid__ = id;\n}", "function getClass(element, k) {\n return element.attr(\"class\").split(\" \")[k-1];\n}", "function getLinkTarget( link ) {\n return link.href.split( '#' )[ 1 ];\n }", "function goToLinkToId(lid)\r\n{\t\r\n\t$(\"#collapse_all\").click();\r\n\t\r\n \tvar tmpcode = getCodeParentPaths(lid);\r\n \tif(tmpcode!= null)\r\n\t{\r\n\t \tcartegoryname = null;\r\n \t\tfor(var i = 0; i < tmpcode.length ; i++){\r\n \t \t if(i==0)\r\n \t \t{\r\n \t \t \t\t//Click category from navigation\r\n \t \t \t $(\"#category_\"+tmpcode[i].id).click();\r\n \t \t \t categoryname = tmpcode[i].name;\r\n \t \t} else if(i==1)\r\n \t \t{\r\n\t \t \t\t//Click subcategory from navigation\r\n\t \t \t subCategoryClickHandler(tmpcode[i].id,tmpcode[i].name,categoryname,'#iws2_subc_entries');\r\n\t \t} else if(i==2)\r\n \t \t{\r\n \t \t \t\t//Click main code\r\n \t \t \t $(\"#accordionCode_\"+tmpcode[i].id).click();\r\n \t\t\t} else if(i==3)\r\n\t \t{\r\n\t \t \t\t//Click the linked to code\r\n \t \t \t sendValueToDPSection('clicked', tmpcode[i].name , tmpcode[i].description , tmpcode[i].id , tmpcode[i].id , tmpcode[i].id, null,\"\",\"\",\"\");\r\n \t \t \t cartegoryname = null;\r\n\t \t}\r\n \t }\t\r\n\t}\r\n\r\n \treturn false;\r\n}", "getClassNameForCategory(category) {\n\t\tlet className = \"\";\n\n\t\tswitch (category) {\n\t\tcase \"a\": {\n\t\t\tclassName = \"light_brown\";\n\t\t\tbreak;\n\t\t}\n\t\tcase \"b\": {\n\t\t\tclassName = \"light_purple\";\n\t\t\tbreak;\n\t\t}\n\t\tcase \"c\": {\n\t\t\tclassName = \"pink\";\n\t\t\tbreak;\n\t\t}\n\t\tcase \"d\": {\n\t\t\tclassName = \"dark_purple\";\n\t\t\tbreak;\n\t\t}\n\t\tcase \"e\": {\n\t\t\tclassName = \"gray\";\n\t\t\tbreak;\n\t\t}\n\t\tcase \"f\": {\n\t\t\tclassName = \"light_green\";\n\t\t\tbreak;\n\t\t}\n\t\tcase \"g\":\n\t\tdefault:\n\t\t\tclassName = \"\";\n\t\t}\n\n\t\treturn className;\n\t}", "function getClass(){\n\tvar classes = ['barbarian', 'monk', 'fighter', 'paladin', 'rogue', 'ranger',\n\t'bard', 'wizard', 'warlock', 'sorcerer', 'cleric', 'druid'];\n\treturn classes[Math.floor((Math.random() * classes.length) + 1)-1];\n}", "processNamedClass() {\n if (!this.tokens.matches2(tt._class, tt.name)) {\n throw new Error(\"Expected identifier for exported class name.\");\n }\n const name = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);\n this.processClass();\n return name;\n }", "function idOf(word) {\n return \".word_\" + word;\n}", "function selectCssElement ( element, className ){\n\tvar siblings = document.getElementsByClassName(className);\n\tif (typeof siblings == \"object\"){\n\n\t\tfor ( var i in siblings ){\n\t\t\tif(element === siblings[i]){ break; }\n\t\t}\n\n\t\treturn i;\n\t}\n}", "function getIdSelector(elementId) {\n return \"#\" + elementId.replace(/(:|\\.|\\[|\\])/g, \"\\\\$1\");\n}", "function changeClass(elementId, className){\r\n // Get a reference to the element\r\n element = document.getElementById(elementId);\r\n // Make sure the element was on the page\r\n if (element) {\r\n\t\t\t// Update the element's className property\r\n\t\t\telement.className = className;\r\n }\r\n }", "static getClass(itemType)\n\t{\n\t\treturn item_types[itemType];\n\t}", "function getCategoryId(id) {\n\treturn id.replace(/^cat-/, '');\n}", "function getColId(col) {\n var r;\n $.each(col.classList, function () {\n if (this.match(/^col-/)) {\n r = this.replace(/^col-/, '');\n }\n });\n return r;\n }", "function resolveKind(id) {\n \t\t\t\t var k=resolveKindFromSymbolTable(id);\n \t\t\t\t\t\tif (!k) {\n \t\t\t\t\t\t\tif (resolveTypeFromSchemaForClass(id)) {\n \t\t\t\t\t\t\t k=\"CLASS_NAME\";\n \t\t\t\t\t\t } else if (resolveTypeFromSchemaForAttributeAndLink(id)) {\n \t\t\t\t\t\t\t\t k=\"PROPERTY_NAME\";\n \t\t\t\t\t\t\t}\n \t\t\t\t\t }\n \t\t\t\treturn k;\n \t\t }", "function markLink( link ) {\r\n\t\t$( link ).addClass( linkCurrentClass );\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set active state for a bullet
function setActiveBulletClass() { for (var i = 0; i < bullets.length; i++) { if (slides[i].style['transform'] == 'translateX(0px)') { bullets[i].classList.add('active'); } } }
[ "function removeActiveBulletClass() {\n for (var i = 0; i < bullets.length; i++) {\n bullets[i].classList.remove('active');\n }\n }", "function updateBullets() {\n\t\tif (bullet.isActive) {\n\t\t\tbullet.vx += Math.cos(toRadians(bullet.angle)) * bullet.speed;\n\t\t\tbullet.vy += Math.sin(toRadians(bullet.angle)) * bullet.speed;\n\t\t\tbullet.x += bullet.vx;\n\t\t\tbullet.y += bullet.vy;\n\t\t}\n\t}", "function updateActiveLink() {\n\tif (this==activeLink){\n\t\treturn;\n\t}\n\t// loops over all li elements\n\tsliderLinks.forEach((link, index) => {\n\t\t// removes 'active' from each\n\t\tlink.classList.remove('active');\n\t\tsliderStack[index].classList.remove('active');\n\t});\n\t// adds 'active' to clicked item\n\tthis.classList.add('active');\n\tsliderStack[sliderLinks.indexOf(this)].classList.add('active');\n\t// stores clicked item\n\tactiveLink = this;\n\tmoveSlides();\n}", "function markGoalActive() {\n\t\tprops.markGoalActive(props.goalId);\n\t}", "function setCurrentDotActive($dot) {\n $sliderDots.removeClass('active');\n $dot.addClass('slider-dot active');\n}", "function displayBullet(paddle){\n // check if bullet is to be displayed\n if(paddle.bulletOn===true){\n fill(10, 10, 230);\n // draw bullet\n rect(paddle.bulletx, paddle.bullety, paddle.bulletsize, paddle.bulletsize/2);\n}\n}", "function setPrevItemActive() {\n var items = getItems();\n\n var activeItem = document.getElementsByClassName(\"active\")[0];\n var prevElement = activeItem.previousElementSibling;\n\n if (!prevElement) {\n prevElement = items[items.length - 1];\n }\n\n changeActiveState(activeItem, prevElement);\n}", "_setActiveList(list)\n {\n this.activeList = list;\n }", "function setActiveObject() {\n global.console.log(\"**** setActiveObject\");\n var activeObj = canvas.getActiveObject();\n if (tedUtils.isContained(activeObj)) { \n tedUtils.setActiveContainer(activeObj);\n }\n}", "function markActiveItem(objItem) {\n $('.item').removeClass('active-item');\n\n if (objItem == null)\n objItem = getItemObjByNameAndFeed(getFeedObjByName(activeFeed), activeItem);\n\n if (objItem == null)\n objItem = $('.item:first');\n\n if (objItem.length == 0) {\n $('#rules').html('');\n $('#welcome-title').css({'display': 'block'});\n $('#active-item-name').html('');\n }\n else {\n $('#welcome-title').css({'display': 'none'});\n var thisItemName = objItem.find('a').text();\n objItem.addClass('active-item');\n activeItem = thisItemName;\n $('#active-item-name').html(activeItem);\n activeFeed = objItem.parents('.feed').data('feed-name');\n loadActiveItemRules();\n }\n}", "SET_ACTIVE_CHAR(state, char) {\n state.activeChar = char;\n }", "addActiveClass() {\n this.currentInterval = store.get('current-interval');\n const $selectedInterval = this.$intervalsList.find(`li#${this.currentInterval}`);\n this.$intervalsItems.removeClass('selected');\n $selectedInterval.addClass('selected');\n }", "function shoot() {\n\t\tbullet = {x:gun.x, y:gun.y, radius:4, colour:'#000', angle:gun.angle, speed:2, vx:0, vy:0, isActive:true};\n\t\tcreateExplosion(bullet.x, bullet.y, 'shot', 'orange');\n\t}", "setActiveItem() {\n const items = this._items, left = this._activeIndex - 1, right = this._activeIndex + 1;\n // if there is only one carousel-item then there won't be any right or left-item.\n if (items.length === 1) {\n items.eq(0).removeClass('left-item right-item');\n return;\n }\n this._indicators.find('>.active').removeClass('active');\n this._indicators.find('> li').eq((items.length + this._activeIndex) % items.length).addClass('active');\n items.filter('.active').removeClass('active');\n items.addClass('left-item');\n items.eq((items.length + left) % items.length).addClass('left-item').removeClass('right-item');\n items.eq((items.length + this._activeIndex) % items.length).removeClass('left-item right-item').addClass('active');\n items.eq((items.length + right) % items.length).addClass('right-item').removeClass('left-item');\n }", "setActiveToggle(Toggle){\n this._activeToggle = Toggle;\n }", "function changeState(elem) {\n if (elem.classList.contains('active')) {\n elem.classList.remove('active');\n } else if (!elem.classList.contains('active')) {\n elem.classList.add('active');\n }\n}", "function onHit() {\n this.classList.remove(\"active\");\n this.classList.add(\"target\");\n scoreIncrement();\n time = time - 10;\n}", "function moveBullet(paddle){\n // turn bullet on\n if(paddle.bulletOn===true){\n // use paddle.side to determine in which direction to shoot the bullet\n // in this case it's the left paddle's bullet:\n if(paddle.side===0){\n // update speed\n paddle.bulletx+=paddle.bulletvx;\n // turn off once we reach the side\n if(paddle.bulletx>width){\n paddle.bulletOn=false;\n }\n } else {\n // do the same for the other paddle's bullet\n paddle.bulletx-=paddle.bulletvx;\n if(paddle.bulletx<0){\n paddle.bulletOn=false;\n }\n }\n}\n}", "function addActive (array) {\n array = nodeListToArray(array);\n array.forEach(function (item) {\n add(item, 'is-active');\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set async content into component's container and emits the current event.
function setAsyncContent(event) { that._content.innerHTML = event.response; /** * Event emitted when the content change. * @event ch.Content#contentchange * @private */ that.emit('_contentchange'); /** * Event emitted if the content is loaded successfully. * @event ch.Content#contentdone * @ignore */ /** * Event emitted when the content is loading. * @event ch.Content#contentwaiting * @example * // Subscribe to "contentwaiting" event. * component.on('contentwaiting', function (event) { * // Some code here! * }); */ /** * Event emitted if the content isn't loaded successfully. * @event ch.Content#contenterror * @example * // Subscribe to "contenterror" event. * component.on('contenterror', function (event) { * // Some code here! * }); */ that.emit('content' + event.status, event); }
[ "async onBegin() {\n\t}", "contentChanged(prev, next) {\n if (this.proxy instanceof HTMLOptionElement) {\n this.proxy.textContent = this.textContent;\n }\n this.$emit(\"contentchange\", null, { bubbles: true });\n }", "registerEvents() {\n\t\t\tthis.container = this.getContainer();\n\t\t\tthis.registerListEvents();\n\t\t\tthis.registerForm();\n\t\t}", "requestContentUpdate() {\n if (!this.renderer) {\n return;\n }\n\n const model = {\n index: this.index,\n item: this.item,\n focused: this.focused,\n selected: this.selected\n };\n\n this.renderer(this, this._comboBox, model);\n }", "requestContentUpdate() {\n if (!this.renderer) {\n return;\n }\n\n this.renderer(this._card, this);\n }", "emitAsync(signal) {\n if (this._events[signal]) {\n this._events[signal].map((callback) => {\n setTimeout( () => {\n callback.apply(null, args);\n }, 0);\n });\n }\n }", "renderedCallback(){\n if (this._socketIoInitialized) {\n return;\n }\n this._socketIoInitialized = true;\n\n Promise.all([\n loadScript(this, socketScript),\n ])\n .then(() => {\n this.initSocketIo();\n })\n .catch(error => {\n // eslint-disable-next-line no-console\n console.error('loadScript error', error);\n this.error = 'Error loading socket.io';\n });\n }", "updateDivContent() {\n var server = getServer(this.serverKey);\n\n if(this.type == 'status') {\n this.#updateStatusContent(server);\n }\n\n if(this.type == 'queue') {\n this.#updateQueueContent(server);\n }\n\n if(this.type == 'controls') {\n this.#updateControlsContent();\n }\n }", "function eventLoop() {\n\tgetState()\n\tif (++updateCount % 5 == 0) {\n\t\t$.post(\"/browse\", {method: \"get-queue-contents\"}, onQueue, \"json\");\n\t}\n}", "function setHTML(container, content) {\n if (container) {\n // Clear out everything in the container\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n if (content) {\n if (typeof content === 'string') {\n container.innerHTML = content;\n } else {\n container.appendChild(content);\n }\n }\n }\n }", "async init() {\n this.handleEventHandlers()\n await this.model.load().then(\n res => {\n if (res) {\n this.setupView(res)\n }\n }\n )\n }", "emitChange() {\n this.emit(AppConstants.CHANGE_EVENT);\n }", "run() {\n this.setDisplayValue();\n this.bindClickHandlers();\n }", "async getContent() {\n return await this.spider.getContent()\n }", "renderedCallback() {\n if (this.initialRender) {\n if (!this.disableAutoScroll) {\n this.setAutoScroll();\n }\n }\n this.initialRender = false;\n }", "_render() {\n if (this._connected && !!this._template) {\n render(this._template(this), this, {eventContext: this});\n }\n }", "handleUpdateContentId(event) {\n this.setState({ contentId: event.target.value });\n }", "function editorNewContent(content, container, activity)\n{\n editorDirty = true;\n activity.contents.push(content);\n addContentElement(content, container, activity);\n}", "_setDataToUI() {\n const data = this._data;\n if (data === undefined) return;\n console.log('View#_setDataToUI', this);\n\n if (data instanceof Object) {\n eachEntry(data, ([name, val]) => this._setFieldValue(name, val));\n } else {\n this._setVal(this.el, data);\n }\n }", "async function fetchChatContentAsync() {\n try {\n const data = new URLSearchParams();\n data.append('chatversion', chatVersion);\n\n const response = await fetch(CHAT_LIST_URL, {\n method: 'post',\n body: data\n });\n\n const chatData = await response.json();\n\n console.log(\"Server chat version: \" + chatData.version + \", Client chat version: \" + chatVersion);\n if (chatData.version !== chatVersion) {\n chatVersion = chatData.version;\n appendToChatArea(chatData.entries);\n }\n } finally {\n triggerTimeoutRefreshChat();\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
addNextWord() Add next word to be displayed
function addNextWord() { let words = controller.words.split(", "), nextWord = words[controller.currentWordIndex] // Create Points pnts = createPoints(nextWord) // Add Word drawingLetters = new Letter(nextWord, pnts) if (words.length - 1 > controller.currentWordIndex) { controller.currentWordIndex++ } else { controller.currentWordIndex = 0 } }
[ "function nextWord() {\n\n //Agrega la siguiente palabra en un string, seguido por un espacio\n text.text = text.text.concat(line[wordIndex] + \" \");\n\n //Avanza el indice de la palabra\n wordIndex++;\n\n //Si es la ultima palabra...\n if (wordIndex === line.length)\n {\n //Agrega un salto de linea\n text.text = text.text.concat(\"\\n\");\n\n //Obtiene la siguiente linea \n game.time.events.add(lineDelay, nextLine, this);\n }\n\n }", "function addWord () {\n if (guide.choices().length > 0) {\n var choices = guide.choices();\n var choice = choices[Math.floor(Math.random() * choices.length)];\n guide.choose(choice);\n $scope.sentence += ' ' + choice;\n } else {\n $interval.cancel(sentenceInterval);\n if (guide.isComplete()) {\n $scope.sentence += '.'; // if complete, add period.\n }\n }\n }", "function nextWordActive(e) {\n const word = document.querySelector('.word.active') || wordsContainer.firstChild\n const wordsLength = wordsContainer.children.length\n\n if (e.keyCode === 32) {\n wordIndex++\n const currentWord = wordsContainer.children[wordIndex]\n currentWord.classList.add('active')\n word.classList.remove('active')\n letterIndex = 0\n slashCoords()\n textarea.value = ''\n\n for (let i = 0; i < word.children.length; ++i) {\n if (word.children[i].classList.contains('incorrect') || word.children[i].classList.contains('extra')) {\n word.classList.add('word__incorrect')\n }\n }\n }\n\n wordsAmount.textContent = `${wordIndex} / ${wordsLength}`\n}", "function nextWord(){\n currentWord = currentList.pop();\n $('#front').text(currentWord.nativeWord);\n setTimeout(function(){\n $('#back').text(currentWord.foreignWord);\n }, 500);\n $('#next-question').hide();\n $('#quiz-answer').show();\n $('.flashcard').toggleClass('flipped');\n}", "function addSpecifiedWord()\n{\n\tvar text = newWord.value;\n\tif (text == \"\")\n\t{\n\t\talert(\"Cannot add an empty value!\");\n\t\treturn;\n\t}\n\taddWord(text, loadedData.length);\n\tloadedData.push(text);\n\tsave(text);\n\tnewWord.value = \"\";\n\t\n\t// necessary to filter out added word\n\t// if necessary\n\tsearch();\n}", "function displayWord(word) {\n splitWord = word.split(\"\");\n firstLetter = splitWord[0];\n $.each(splitWord, function (index) {\n $(\".word\").append(\n `<div class=\"letter-box b-neon-blue\" id=\"${index}\"></div>`\n );\n });\n }", "function showWord(word) {\n $($playedWords).append($(\"<li>\", { text: word }));\n}", "addNewWord(word) {\n\t\tlet currentNode = this;\n\t\tfor (let i = 0; i < word.length; i++) {\n\t\t\tconst char = word[i];\n\n\t\t\t// Increment the seen counter\n\t\t\tcurrentNode.seen += 1;\n\n\t\t\tif (!currentNode.children[char]) {\n\t\t\t\t// There isn't a word built here yet, so just use the constructor\n\t\t\t\tcurrentNode.children[char] = new Node(word.substr(i + 1));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Move the current node to the next character node\n\t\t\tcurrentNode = currentNode.children[char];\n\t\t}\n\n\t\tif (currentNode) {\n\t\t\tcurrentNode.isEnd = true;\n\t\t}\n\t}", "function setUp() {\n wordGen();\n document.getElementById(\"currentWordLength\").textContent = randomWord.length;\n for (var i = 0; i < randomWord.length; i++) {\n blankWord.push(\"_\");\n }\n document.getElementById(\"currentWord\").textContent = blankWord.join(\" \");\n}", "function addtowords(word){\n if(words.length === 7){\n words.shift();\n }\n words.push(word);\n}", "function addExtraLetter() {\n const word = document.querySelector('.word.active') || wordsContainer.firstChild\n const prevLength = word.children.length\n if (letterIndex >= prevLength) {\n const span = document.createElement('span')\n span.className = 'extra';\n span.innerHTML = textarea.value\n word.appendChild(span)\n }\n\n slashCoords()\n}", "function printWord() {\n $(\"#word\").text(current_word.displayed_word);\n}", "function showCurrentWord() { \n var wordChoiceDiv = document.getElementById(\"wordChoices\");\n wordChoiceDiv.innerHTML = \"<div id=\\\"wordChoices\\\"></div>\"; // Clears the Div tag for each word\n console.log(currentWord); \n for (var i = 0; i < currentWord.length; i++) { // for every letter in the currentWord, type an underscore\n var newSpan = document.createElement(\"span\");\n newSpan.innerHTML= \"_ \";\n newSpan.setAttribute(\"id\",\"letter-\"+i);\n wordChoiceDiv.appendChild(newSpan); \n } \n }", "function displayCurrentWord(){\n\t/** Change the html to the current word status */\n\tdocument.querySelector(\"#correctorGuess\").innerHTML = currentWordArray.join(\" \");\n}", "function showWord(words) {\n const randIndex = Math.floor(Math.random() * words.length);\n currentWord.innerHTML = words[randIndex];\n}", "function nextConspiricy() {\n index++;\n textBox.innerHTML = textGenerator.next();\n}", "function fillDisplayWord (letter) {\n\n}", "function insertAfter(sourceWord, newWord)\n{\n\tif(!newWord.word.match(regexp_is_space)) //if it's not just spaces, insert it\n\t{\n\t\t//insert into words list structure\n\t\tnewWord.nextWord = sourceWord.nextWord;\n\t\tsourceWord.nextWord = newWord;\n\t\t\n\t\tnewWord.previousWord = sourceWord;\n\t\tif(newWord.nextWord)\n\t\t{\n\t\t\tnewWord.nextWord.previousWord = newWord;\n\t\t}\n\t\t\n\t\t//determine the right sentence\n\t\tif(sourceWord.word.match(regexp_contains_eos)) //if the sourceWord is an end of sentence\n\t\t{\n\t\t\tnewWord.sentence = sourceWord.sentence.nextSentence;\n\t\t\tnewWord.sentence.firstWord = newWord;\n\t\t\tif(!newWord.sentence.lastWord) //if the sentence was empty, it's also the last word\n\t\t\t{\n\t\t\t\tnewWord.sentence.lastWord = newWord;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnewWord.sentence = sourceWord.sentence;\n\t\t\tif(sourceWord.sentence.lastWord == sourceWord) //if sourceWord was the last of its sentence\n\t\t\t{\n\t\t\t\tsourceWord.sentence.lastWord = newWord;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//edit the node start and end points if needed\n\t\tif(newWord.node != sourceWord.node) //if not the same node as the previous word, it's the first of its node\n\t\t{\n\t\t\tnewWord.node.firstWord = newWord;\n\t\t}\n\t\tif(!newWord.nextWord || newWord.node != newWord.nextWord.node) \n\t\t{\n\t\t\tnewWord.node.lastWord = newWord;\n\t\t}\n\t\t\n\t\t//update offsets of the following words\n\t\tupdateOffsets(newWord.node, newWord.nextWord, newWord.word.length);\n\t\t\n\t\t//if we just inserted end of sentence punctuation, what follows becomes a new sentence\n\t\tif(newWord.word.match(regexp_contains_eos)) \n\t\t{\n\t\t\tsplitSentenceFrom(newWord);\n\t\t}\n\t\t\n\t\tnewWord.node.parent_text.log.addWord(newWord);\n\t\t\n\t\treturn newWord;\n\t}\n\telse\t//just update the offsets\n\t{\n\t\tupdateOffsets(newWord.node, sourceWord.nextWord, newWord.word.length);\n\t\treturn null;\n\t}\n}", "showWordProgress() {\n console.log(`The word now looks like this: ${this.currWord}`)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the z component of the cross product between vectors BC and BA.
function crossProductZ( pointA, pointB, pointC) { var bX = pointB.x; var bY = pointB.y; return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX)); }
[ "function getZ(x, y) {\n // We assume that the plane equation is up-to-date\n // with the current polygon.\n return -(A * x + B * y + D) / C;\n }", "static Cross(left, right) {\n const result = Vector3.Zero();\n Vector3.CrossToRef(left, right, result);\n return result;\n }", "static zAxis() { return newVec(0.0,0.0,1.0); }", "subtractFromFloats(x, y, z, w) {\n return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);\n }", "function computeBezierSurfacePoint(uVal, wVal) {\r\n let u2, u3, w2, w3;\r\n u2 = uVal * uVal;\r\n u3 = uVal * u2;\r\n w2 = wVal * wVal;\r\n w3 = wVal * w2;\r\n\r\n // Need to note the following regarding THREE.js Matrix4. \r\n // When we set the matrix, we set it in row major order.\r\n // However, when we access the elements of this matrix, these are \r\n // returned in column major order. \r\n let matC = new THREE.Matrix4();\r\n matC.set(-1, 3, -3, 1, 3, -6, 3, 0, -3, 3, 0, 0, 1, 0, 0, 0);\r\n\r\n let matPx = new THREE.Matrix4();\r\n matPx.set(p00x, p10x, p20x, p30x, p01x, p11x, p21x, p31x, p02x, p12x,\r\n p22x, p32x, p03x, p13x, p23x, p33x);\r\n\r\n let matPy = new THREE.Matrix4();\r\n matPy.set(p00y, p10y, p20y, p30y, p01y, p11y, p21y, p31y, p02y, p12y,\r\n p22y, p32y, p03y, p13y, p23y, p33y);\r\n\r\n let matPz = new THREE.Matrix4();\r\n matPz.set(p00z, p10z, p20z, p30z, p01z, p11z, p21z, p31z, p02z, p12z,\r\n p22z, p32z, p03z, p13z, p23z, p33z);\r\n\r\n let mat1x = new THREE.Matrix4();\r\n mat1x.multiplyMatrices(matC, matPx);\r\n\r\n let mat1y = new THREE.Matrix4();\r\n mat1y.multiplyMatrices(matC, matPy);\r\n\r\n let mat1z = new THREE.Matrix4();\r\n mat1z.multiplyMatrices(matC, matPz);\r\n\r\n let mat2x = new THREE.Matrix4();\r\n mat2x.multiplyMatrices(mat1x, matC);\r\n\r\n let mat2y = new THREE.Matrix4();\r\n mat2y.multiplyMatrices(mat1y, matC);\r\n\r\n let mat2z = new THREE.Matrix4();\r\n mat2z.multiplyMatrices(mat1z, matC);\r\n\r\n // We access the matrix elements in column major order. \r\n let ex = mat2x.elements;\r\n let w0x = ex[0] * w3 + ex[4] * w2 + ex[8] * wVal + ex[12];\r\n let w1x = ex[1] * w3 + ex[5] * w2 + ex[9] * wVal + ex[13];\r\n let w2x = ex[2] * w3 + ex[6] * w2 + ex[10] * wVal + ex[14];\r\n let w3x = ex[3] * w3 + ex[7] * w2 + ex[11] * wVal + ex[15];\r\n\r\n let ey = mat2y.elements;\r\n let w0y = ey[0] * w3 + ey[4] * w2 + ey[8] * wVal + ey[12];\r\n let w1y = ey[1] * w3 + ey[5] * w2 + ey[9] * wVal + ey[13];\r\n let w2y = ey[2] * w3 + ey[6] * w2 + ey[10] * wVal + ey[14];\r\n let w3y = ey[3] * w3 + ey[7] * w2 + ey[11] * wVal + ey[15];\r\n\r\n let ez = mat2z.elements;\r\n let w0z = ez[0] * w3 + ez[4] * w2 + ez[8] * wVal + ez[12];\r\n let w1z = ez[1] * w3 + ez[5] * w2 + ez[9] * wVal + ez[13];\r\n let w2z = ez[2] * w3 + ez[6] * w2 + ez[10] * wVal + ez[14];\r\n let w3z = ez[3] * w3 + ez[7] * w2 + ez[11] * wVal + ez[15];\r\n\r\n let qx = u3 * w0x + u2 * w1x + uVal * w2x + w3x;\r\n let qy = u3 * w0y + u2 * w1y + uVal * w2y + w3y;\r\n let qz = u3 * w0z + u2 * w1z + uVal * w2z + w3z;\r\n\r\n return {\r\n xVal: qx,\r\n yVal: qy,\r\n zVal: qz\r\n }\r\n}", "static vSub(a,b) { return newVec(a.x-b.x,a.y-b.y,a.z-b.z); }", "static CrossToRef(left, right, result) {\n const x = left.y * right.z - left.z * right.y;\n const y = left.z * right.x - left.x * right.z;\n const z = left.x * right.y - left.y * right.x;\n result.copyFromFloats(x, y, z);\n }", "function addXyzCross(vertices /*:Vector3[]*/, xyz /*:Num3*/, r /*:number*/) {\n vertices.push(new THREE.Vector3(xyz[0]-r, xyz[1], xyz[2]));\n vertices.push(new THREE.Vector3(xyz[0]+r, xyz[1], xyz[2]));\n vertices.push(new THREE.Vector3(xyz[0], xyz[1]-r, xyz[2]));\n vertices.push(new THREE.Vector3(xyz[0], xyz[1]+r, xyz[2]));\n vertices.push(new THREE.Vector3(xyz[0], xyz[1], xyz[2]-r));\n vertices.push(new THREE.Vector3(xyz[0], xyz[1], xyz[2]+r));\n}", "multiplyByFloats(x, y, z) {\n return new Vector3(this.x * x, this.y * y, this.z * z);\n }", "function crossProduct(p1, p2) {\n return p1.x * p2.y - p1.y * p2.x;\n}", "static vConv(a,b) { return newVec(a.x*b.x,a.y*b.y,a.z*b.z); }", "conjugate() {\n const result = new Quaternion(-this.x, -this.y, -this.z, this.w);\n return result;\n }", "function backsub(\n u, // u[1..m][1..n], the column-orth. matrix from decomp\n w, // w[1..n], the diagonal matrix from decomp\n v, // v[1..n][1..n], the orth. matrix from decomp\n m, // number of rows\n n, // number of columns\n b // b[1..m] is the right hand side (B)\n)\n{\n var s;\n var tmp = new Array();\n var x = new Array();\n \n // Calculate UT * B\n for (var j=1; j<=n; j++)\n {\n s = 0.0;\n \n // Nonzero result only if w[j] is nonzero\n if (w[j] != 0.0)\n {\n for (var i=1; i<=m; i++)\n s += u[i][j]*b[i];\n s /= w[j];\n }\n tmp[j] = s;\n }\n \n // Matrix multiply by V to get answer.\n for (var j=1; j<=n; j++)\n {\n s = 0.0;\n for (var jj=1; jj<=n; jj++)\n s += v[j][jj]*tmp[jj];\n x[j] = s;\n }\n \n return x;\n}", "negate() {\n return new Vector3(-this.x, -this.y, -this.z);\n }", "static Dot(left, right) {\n return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);\n }", "multiplyByFloats(x, y, z, w) {\n return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);\n }", "subtract(otherVector) {\n return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);\n }", "get z() {return this._z;}", "function alpha(va, vb, ba, bb) {\n // (1)-(2);\n // (ba-bb)*(1-a) = va - vb\n // 1 - a = (va-vb)/(ba-bb)\n // 1 - (va-vb)/(ba-bb) = a\n if (ba - bb == 0) return 1;\n return 1 - (va - vb) / (ba - bb);\n}", "static rollPitchYaw(a, b, c) {\n if (!c) {\n return new Vector(\n Vector.normalizeAngle(Vector.find2DAngle(a.z, a.y, b.z, b.y)),\n Vector.normalizeAngle(Vector.find2DAngle(a.z, a.x, b.z, b.x)),\n Vector.normalizeAngle(Vector.find2DAngle(a.x, a.y, b.x, b.y))\n );\n }\n let qb = b.subtract(a);\n let qc = c.subtract(a);\n let n = qb.cross(qc);\n\n let unitZ = n.unit();\n let unitX = qb.unit();\n let unitY = unitZ.cross(unitX);\n\n let beta = Math.asin(unitZ.x) || 0;\n let alpha = Math.atan2(-unitZ.y, unitZ.z) || 0;\n let gamma = Math.atan2(-unitY.x, unitX.x) || 0;\n\n return new Vector(Vector.normalizeAngle(alpha), Vector.normalizeAngle(beta), Vector.normalizeAngle(gamma));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The following scenario will help understanding why links are needed. Component A has a dependency B. (for instance, in a.js there is a require statement to 'b.js'). While importing component A, it knows about the B dependency and it saves it under 'dependencies' directory of A. The problem is that the above require is broken, because 'b.js' is not in the same place where it was originally. This function solves this issue by creating the 'b.js' file in the original location and points to the new location under 'dependencies' of A. It does the link generation in two steps. step 1: "componentsLinks", it generates links to all imported components. target: imported components. source: dependencies. step 2: "dependenciesLinks", it generates links to all dependencies of the imported components. target: dependencies. source: other dependencies. this step is not needed when the imported components don't have dependencies, or when the dependencies were installed as npm/yarn packages.
function getComponentsDependenciesLinks( componentDependencies: ComponentWithDependencies[], consumer: ?Consumer, createNpmLinkFiles: boolean, bitMap: BitMap ): DataToPersist { const componentsDependenciesLinks = new DataToPersist(); const linkedComponents = new BitIds(); const componentsToLink = getComponentsToLink(); addLinksForComponents(); addLinksForDependencies(); return componentsDependenciesLinks; function getComponentsToLink(): ComponentWithDependencies[] { return componentDependencies.reduce((acc, componentWithDeps) => { const component = componentWithDeps.component; const componentMap = bitMap.getComponent(component.id); component.componentMap = componentMap; if (componentMap.origin === COMPONENT_ORIGINS.AUTHORED) { logger.debug( `writeComponentsDependenciesLinks, ignoring a component ${component.id.toString()} as it is an author component` ); return acc; } return acc.concat(componentWithDeps); }, []); } function addLinksForComponents() { componentsToLink.forEach((componentWithDeps: ComponentWithDependencies) => { const component = componentWithDeps.component; if (linkedComponents.has(component.id)) return; // it must be IMPORTED. We don't pass NESTED to this function logger.debug(`writeComponentsDependenciesLinks, generating links for ${component.id.toString()}`); const componentsLinks = getComponentLinks({ consumer, component, dependencies: componentWithDeps.allDependencies, createNpmLinkFiles, bitMap }); componentsDependenciesLinks.merge(componentsLinks); linkedComponents.push(component.id); }); } function addLinksForDependencies() { componentsToLink.forEach((componentWithDeps: ComponentWithDependencies) => { if (!componentWithDeps.component.dependenciesSavedAsComponents) return; componentWithDeps.allDependencies.forEach((dep: Component) => { if (linkedComponents.has(dep.id)) return; // We pass here the componentWithDeps.dependencies again because it contains the full dependencies objects // also the indirect ones // The dep.dependencies contain only an id and relativePaths and not the full object const dependencies = componentWithDeps.allDependencies; dependencies.push(componentWithDeps.component); const dependencyLinks = getComponentLinks({ consumer, component: dep, dependencies, createNpmLinkFiles, bitMap }); componentsDependenciesLinks.merge(dependencyLinks); linkedComponents.push(dep.id); }); }); } }
[ "function getComponentLinks({\n consumer,\n component,\n dependencies,\n createNpmLinkFiles,\n bitMap\n}: {\n consumer: ?Consumer,\n component: Component,\n dependencies: Component[], // Array of the dependencies components (the full component) - used to generate a dist link (with the correct extension)\n createNpmLinkFiles: boolean,\n bitMap: BitMap\n}): DataToPersist {\n const componentMap: ComponentMap = bitMap.getComponent(component.id);\n component.componentMap = componentMap;\n const directDependencies: Dependency[] = _getDirectDependencies(component, componentMap, createNpmLinkFiles);\n const flattenedDependencies: BitIds = _getFlattenedDependencies(component, componentMap, createNpmLinkFiles);\n const links = directDependencies.map((dep: Dependency) => {\n if (!dep.relativePaths || R.isEmpty(dep.relativePaths)) return [];\n const getDependencyIdWithResolvedVersion = (): BitId => {\n // Check if the dependency is latest, if yes we need to resolve if from the flatten dependencies to get the\n // Actual version number, because on the bitmap we have only specific versions\n if (dep.id.getVersion().latest) {\n return flattenedDependencies.resolveVersion(dep.id);\n }\n return dep.id;\n };\n const dependencyId = getDependencyIdWithResolvedVersion();\n const dependencyComponent = _getDependencyComponent(dependencyId, dependencies, component.id);\n\n const dependencyLinks = dep.relativePaths.map((relativePath: RelativePath) => {\n const dependencyFileLinkGenerator = new DependencyFileLinkGenerator({\n consumer,\n bitMap,\n component,\n relativePath,\n dependencyComponent,\n createNpmLinkFiles\n });\n return dependencyFileLinkGenerator.generate();\n });\n return R.flatten(dependencyLinks);\n });\n const dataToPersist = new DataToPersist();\n const internalCustomResolvedLinks = component.customResolvedPaths.length\n ? getInternalCustomResolvedLinks(component, componentMap, createNpmLinkFiles)\n : [];\n const flattenLinks = R.flatten(links).concat(internalCustomResolvedLinks);\n\n const { postInstallLinks, postInstallSymlinks, linksToWrite, symlinks } = groupLinks(flattenLinks);\n const shouldGeneratePostInstallScript = postInstallLinks.length || postInstallSymlinks.length;\n if (shouldGeneratePostInstallScript) {\n const postInstallFile = generatePostInstallScript(component, postInstallLinks, postInstallSymlinks);\n dataToPersist.addFile(postInstallFile);\n }\n const customResolveAliasesAdded = addCustomResolveAliasesToPackageJson(component, flattenLinks);\n if (customResolveAliasesAdded || shouldGeneratePostInstallScript) {\n // $FlowFixMe it has been verified above that component.packageJsonFile is not empty\n const packageJsonFile = component.packageJsonFile.toVinylFile();\n dataToPersist.addFile(packageJsonFile);\n }\n\n if (symlinks.length) {\n dataToPersist.addManySymlinks(symlinks.map(symlink => Symlink.makeInstance(symlink.source, symlink.dest)));\n }\n // $FlowFixMe\n dataToPersist.addManyFiles(linksToWrite.map(linkToWrite => LinkFile.load(linkToWrite)));\n return dataToPersist;\n}", "function getInternalCustomResolvedLinks(\n component: Component,\n componentMap: ComponentMap,\n createNpmLinkFiles: boolean\n): LinkFileType[] {\n const componentDir = component.writtenPath || componentMap.rootDir;\n if (!componentDir) {\n throw new Error(`getInternalCustomResolvedLinks, unable to find the written path of ${component.id.toString()}`);\n }\n const getDestination = (importSource: string) => `node_modules/${importSource}`;\n const invalidImportSources = ['.', '..']; // before v14.1.4 components might have an invalid importSource saved. see #1734\n const isResolvePathsInvalid = customPath => !invalidImportSources.includes(customPath.importSource);\n return component.customResolvedPaths.filter(customPath => isResolvePathsInvalid(customPath)).map((customPath) => {\n const sourceAbs = path.join(componentDir, customPath.destinationPath);\n const dest = getDestination(customPath.importSource);\n const destAbs = path.join(componentDir, dest);\n const destRelative = path.relative(path.dirname(destAbs), sourceAbs);\n const linkContent = getLinkToFileContent(destRelative);\n\n const postInstallSymlink = createNpmLinkFiles && !linkContent;\n const packageName = componentIdToPackageName(component.id, component.bindingPrefix);\n const customResolveMapping = { [customPath.importSource]: `${packageName}/${customPath.destinationPath}` };\n const getSymlink = () => {\n if (linkContent) return undefined;\n if (createNpmLinkFiles) return `${packageName}/${customPath.destinationPath}`;\n return sourceAbs;\n };\n return {\n linkPath: createNpmLinkFiles ? dest : destAbs,\n linkContent,\n postInstallLink: createNpmLinkFiles,\n customResolveMapping,\n symlinkTo: getSymlink(),\n postInstallSymlink\n };\n });\n}", "async writeLinksOnNodeModules() {\n const links = await this.manyComponentsWriter._getAllLinks();\n const nodeModulesLinks = links.filterByPath(filePath => filePath.startsWith('node_modules'));\n await nodeModulesLinks.persistAllToCapsule(this.capsule);\n }", "addLinkComponent(link, component) {\n 'use strict';\n\n let newLink = link;\n let componentString = component;\n\n if (component === undefined || !component) {\n return newLink;\n }\n if (typeof newLink !== 'string') {\n newLink = link.toString();\n }\n\n if (typeof component !== 'string') {\n componentString = component.toString();\n }\n if (newLink.charAt(newLink.length - 1) !== '/' && componentString.charAt(0) !== '/') {\n newLink += '/';\n } else if (newLink.charAt(newLink.length - 1) === '/' && componentString.charAt(0) === '/') {\n componentString = componentString.substring(1);\n }\n newLink += componentString;\n return newLink;\n }", "async createLinkFromRepoToHere () {\n const log = this.log\n log.trace(`${this.constructor.name}.createLinkFromRepoToHere()`)\n\n const context = this.context\n const config = context.config\n\n if (config.configurationName) {\n throw new CliErrorInput('misplaced --config')\n }\n\n const xpack = this.xpack\n const packageJson = this.packageJson\n\n this.manifestIds = new ManifestIds(packageJson, this.policies)\n\n const globalPackagePath = path.join(context.globalConfig.globalFolderPath,\n this.manifestIds.getScopedName())\n\n const globalPackageLinkPath = path.join(globalPackagePath, dotLink)\n let stats\n try {\n // Use `lstat`, since `stat` follows the links.\n stats = await fsPromises.lstat(globalPackageLinkPath)\n } catch (err) {\n // `lstat` failed, the path does not exist; proceed to create the link.\n stats = null\n }\n\n if (stats) {\n if (stats.isSymbolicLink()) {\n try {\n log.trace(`del('${globalPackageLinkPath}')`)\n await deleteAsync(globalPackageLinkPath, { force: true })\n } catch (err) {\n log.trace(util.inspect(err))\n throw new CliError(\n `cannot remove '${globalPackageLinkPath}'`)\n }\n } else {\n throw new CliError(\n `'${globalPackageLinkPath}' is not a symbolic link`)\n }\n }\n\n // Create parent folder, for just in case.\n await makeDir(globalPackagePath)\n\n // fs.symlink(target, path[, type], callback)\n // 'creates the link called path pointing to target'\n log.trace('symlink' +\n `('${xpack.xpackPath}', '${globalPackageLinkPath})'`)\n\n if (os.platform() === 'win32') {\n await fsPromises.symlink(xpack.xpackPath, globalPackageLinkPath,\n 'junction')\n } else {\n await fsPromises.symlink(xpack.xpackPath, globalPackageLinkPath)\n }\n if (log.isVerbose()) {\n log.info('Development references to package ' +\n `'${this.manifestIds.getScopedName()}' will be redirected to folder ` +\n `'${xpack.xpackPath}'.`)\n } else {\n log.info(\n `${this.manifestIds.getScopedName()} -> ` +\n `'${xpack.xpackPath}'`)\n }\n }", "async function linkUserData() {\n let destinationDirectory;\n if (fs.existsSync(path.resolve(sourceDirectory, 'module.json'))) {\n destinationDirectory = 'modules';\n } else {\n throw new Error(`Could not find ${chalk.blueBright('module.json')}`);\n }\n\n const linkDirectory = path.resolve(getDataPath(), destinationDirectory, name);\n\n if (argv.clean || argv.c) {\n console.log(chalk.yellow(`Removing build in ${chalk.blueBright(linkDirectory)}.`));\n\n await fs.remove(linkDirectory);\n } else if (!fs.existsSync(linkDirectory)) {\n console.log(chalk.green(`Linking dist to ${chalk.blueBright(linkDirectory)}.`));\n await fs.ensureDir(path.resolve(linkDirectory, '..'));\n await fs.symlink(path.resolve(distDirectory), linkDirectory);\n }\n}", "function breakCircularDependencies(modules) {\n\n const byName = new Map();\n modules.forEach(mod => byName.set(mod.name, mod));\n \n // Make a list of nodes \n const nodes = Array.from(byName.keys());\n // An Array<Array<number>> array for the edges\n const edges = [];\n\n // Build the adjacencyList\n nodes.forEach((node, index) => {\n const list = [];\n edges[index] = list;\n const entry = byName.get(node); // get the module by name\n // Make a set of deps rather than using the entry.dependencies\n // mapping.\n entry.deps = new Set();\n \n if (entry.dependencies) {\n\n Object.keys(entry.dependencies).forEach(name => {\n\n // Save this in the deps set\n const dependency = byName.get(name);\n if (!dependency) {\n throw new ReferenceError(`# For module ${entry.name} ${entry.version}: for some reason the module for transitive dependency ${name} was not included. Please add it manually to your list of top-level dependencies (rule yarn_modules.deps attribute) .`);\n }\n entry.deps.add(dependency);\n \n // Populate the adjacency list\n const depIndex = nodes.indexOf(name);\n list.push(depIndex);\n \n // Compute referrer backreferences for later use.\n let referrer = dependency.referrer;\n if (!referrer) {\n referrer = dependency.referrer = new Set();\n }\n referrer.add(entry);\n\n });\n }\n });\n\n const clusters = stronglyConnectedComponents(edges);\n\n // Foreach non-trivial cluster in the SCC, create a pseudo-module\n // for the cluster and re-link each entry to point to the cluster\n // rather than the dependency.\n clusters.components.forEach((component, index) => {\n\n if (component.length > 1) {\n // console.log(\"SCC: \", component);\n // component.forEach(element => {\n // console.log(`Component ${index} contains ${nodes[element]} (${element})`);\n // });\n\n // Create a name for the pseudo-module\n const name = '_scc' + index;\n // The dependencies in this cluster component\n const deps = new Set();\n // The pseudo-module for the cluster\n const pseudo = {\n name: name,\n deps: deps\n };\n\n // A list of entries in this component\n const list = [];\n // Last entry in the component can be standalone\n for (let i = 0; i < component.length; i++) {\n list.push(byName.get(nodes[component[i]]) );\n }\n\n // A description for the module\n pseudo.description = \"Strongly connected component containing \" + list.map(e => e.name).join(\", \")\n \n list.forEach(entry => {\n // Add this to the pseudo-module\n deps.add(entry);\n\n // Iterate the set of items that link to this entry. Replace\n // their deps set with the psudo-module rather than the entry\n // itself.\n entry.referrer.forEach(ref => {\n ref.deps.delete(entry);\n\n // Add an entry to the scc component (unless it is a member\n // of it).\n if (!deps.has(ref)) {\n ref.deps.add(pseudo);\n }\n });\n\n // Each entry in the cluster must have no connections to other\n // dependencies in the cluster, or on the cluster pseudo-dep\n pseudo.deps.forEach(circ => entry.deps.delete(circ));\n entry.deps.delete(pseudo);\n });\n\n // Store this new pseudo-module in the modules list\n modules.push(pseudo);\n }\n \n });\n\n}", "function link() {\n console.log('core::link,', 'linking modules');\n var i = 0,\n sorted = [],\n sortedLen = 0,\n parent = new Module(),\n name = '',\n module = null;\n\n // Sort modules in dependency order\n sorted = sort(modules);\n sortedLen = sorted.length;\n\n // Link modules in dependency order\n for (i = 0; i < sortedLen; i += 1) {\n name = sorted[i];\n module = modules[name];\n\n if (module.instance === undefined) {\n\n // Each module should inherit from a generic Module object\n module.def.prototype = parent;\n\n // Execute module code, pass requires, record exports\n modules[name].instance = instantiate(\n module.def,\n createParams(module.def, module.requires)\n );\n\n // Set module name\n modules[name].instance.name = name;\n\n if (typeof modules[name].instance.init === 'function') {\n modules[name].instance.init();\n }\n }\n }\n }", "function replaceMissingDependenciesInChildren(missingDependencies, nodeModulesInThisDir, nodeModulesInherited) {\n Object.keys(missingDependencies).forEach(moduleName => {\n let foundDirectory\n\n if (nodeModulesInThisDir[moduleName]) { // First choice is what is in current directory\n foundDirectory = nodeModulesInThisDir[moduleName]\n }\n else if (nodeModulesInherited && nodeModulesInherited[moduleName]) { // Second choice is what is in the immediate node_modules directory\n foundDirectory = nodeModulesInherited[moduleName]\n }\n else return\n\n missingDependencies[moduleName].forEach(placeThatNeedsDependency => {\n let nodeModuleDirOfPlaceThatNeedsDependency = path.join(placeThatNeedsDependency, 'node_modules')\n fs.ensureDirSync(nodeModuleDirOfPlaceThatNeedsDependency)\n let symlinkDest = path.join(nodeModuleDirOfPlaceThatNeedsDependency, moduleName)\n\n verbose(`${moduleName} - To resolve a dependency, adding ${foundDirectory} as a symlink into ${symlinkDest}`)\n ensureRelativeSymlinkSync(foundDirectory, symlinkDest)\n })\n delete missingDependencies[moduleName]\n })\n\n return missingDependencies\n}", "function copyNpmPackageWithSymlinkedNodeModules(fromPkgDir, toPkgDir) {\n files.mkdir_p(toPkgDir);\n\n let needToHandleNodeModules = false;\n\n files.readdir(fromPkgDir).forEach(item => {\n if (item === \"node_modules\") {\n // We'll link or copy node_modules in a follow-up step.\n needToHandleNodeModules = true;\n return;\n }\n\n files.cp_r(\n files.pathJoin(fromPkgDir, item),\n files.pathJoin(toPkgDir, item)\n );\n });\n\n if (! needToHandleNodeModules) {\n return;\n }\n\n const nodeModulesFromPath = files.pathJoin(fromPkgDir, \"node_modules\");\n const nodeModulesToPath = files.pathJoin(toPkgDir, \"node_modules\");\n\n files.mkdir(nodeModulesToPath);\n\n files.readdir(nodeModulesFromPath).forEach(depPath => {\n if (depPath === \".bin\") {\n // Avoid copying node_modules/.bin because commands like\n // .bin/node-gyp and .bin/node-pre-gyp tend to cause problems.\n return;\n }\n\n const absDepFromPath = files.pathJoin(nodeModulesFromPath, depPath);\n\n if (! files.stat(absDepFromPath).isDirectory()) {\n // Only copy package directories, even though there might be other\n // kinds of files in node_modules.\n return;\n }\n\n const absDepToPath = files.pathJoin(nodeModulesToPath, depPath);\n\n // Try to symlink node_modules dependencies if possible (faster),\n // and fall back to a recursive copy otherwise.\n try {\n files.symlink(absDepFromPath, absDepToPath, \"junction\");\n } catch (e) {\n files.cp_r(absDepFromPath, absDepToPath);\n }\n });\n}", "if (!moduleName.startsWith('.')) {\n return `/${moduleName}`;\n }", "function getModuleDependencyLinksHash(d) {\n let links = getModuleDependencyLinks(d)\n let asString = Object.keys(links).map(l => links[l]).sort().join('\\n')\n return crypto.createHash('md5').update(asString).digest('hex').substring(20)\n}", "function fixMovedSymlinks(d) {\n fs.readdirSync(d).map(f => path.join(d, f)).forEach(f => {\n const stats = fs.lstatSync(f)\n if (stats.isDirectory()) {\n fixMovedSymlinks(f) // recurse\n }\n else if (stats.isSymbolicLink()) {\n let dest = fs.readlinkSync(f)\n let destAbsolute = path.resolve(path.dirname(f), dest)\n if (!fs.existsSync(destAbsolute)) {\n let correctDest = path.join(sharedModules, path.basename(dest))\n\n if (fs.existsSync(correctDest)) {\n verbose(`Fixing symlink ${f} - was ${dest}, now ${correctDest}`)\n fs.unlinkSync(f)\n ensureRelativeSymlinkSync(correctDest, f)\n }\n }\n }\n })\n}", "function build_sym_links() {\n\t\tconst log_folder = t.log_lib.get_log_path();\n\t\tif (!path2file.includes(log_folder)) {\t\t\t\t\t\t\t\t\t\t// test if this file is outside the log folder\n\t\t\tbuild_link(t.path.join(ev.ACTIVITY_TRACKER_PATH, AT_FILENAME));\n\t\t\tbuild_link(t.path.join(ev.ACTIVITY_TRACKER_PATH, AT_FILENAME_ROTATED));\n\t\t}\n\n\t\tfunction build_link(pathToFile) {\n\t\t\tif (t.fs.existsSync(pathToFile)) {\t\t\t\t\t\t\t\t\t\t// build the link if the file exists\n\t\t\t\tconst file_name = t.path.basename(pathToFile);\t\t\t\t\t\t// get the filename from the path\n\t\t\t\ttry {\n\t\t\t\t\tconst path2link = t.path.join(log_folder, file_name);\n\t\t\t\t\tt.fs.symlink(pathToFile, path2link, 'file', err => {\n\t\t\t\t\t\tlogger.debug('[activity tracker] symbolic link created', path2link);\n\t\t\t\t\t});\n\t\t\t\t} catch (e) {\n\t\t\t\t\tlogger.error('[activity tracker] unable to create symbolic link:', pathToFile);\n\t\t\t\t\tlogger.error(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "getPathImportUrl(fromUrl, toUrl) {\n const isPackageNameScoped = this.npmPackageName.startsWith('@');\n const isPackageTypeElement = this.packageType === 'element';\n const isImportFromLocalFile = PackageUrlHandler.isUrlInternalToPackage(fromUrl);\n const isImportToExternalFile = !PackageUrlHandler.isUrlInternalToPackage(toUrl);\n let importUrl = util_1.getRelativeUrl(fromUrl, toUrl);\n // If the import is from the current project:\n if (isImportFromLocalFile && isPackageTypeElement) {\n // Rewrite imports to point to dependencies as if they were siblings.\n if (importUrl.startsWith('./node_modules/')) {\n importUrl = '../' + importUrl.slice('./node_modules/'.length);\n }\n else {\n importUrl = importUrl.replace('node_modules', '..');\n }\n // Account for a npm package name scoping.\n if (isPackageNameScoped && isImportToExternalFile) {\n if (importUrl.startsWith('./')) {\n importUrl = '../' + importUrl.slice('./'.length);\n }\n else {\n importUrl = '../' + importUrl;\n }\n }\n }\n return importUrl;\n }", "importLegacyLinks() {\n const legacyLinks = JSON.parse(localStorage.getItem(\"customCommands\"));\n if (legacyLinks) {\n this.config.links = legacyLinks;\n saveConfig();\n }\n }", "function convertBundleIntoReact(linkify, useClasses, bundle, key) {\n const style = useClasses ? null : createStyle(bundle);\n const className = useClasses ? createClass(bundle) : null;\n if (!linkify) {\n return React.createElement(\"span\", { style, key, className }, bundle.content);\n }\n const content = [];\n const linkRegex = /(\\s+|^)(https?:\\/\\/(?:www\\.|(?!www))[^\\s.]+\\.[^\\s]{2,}|www\\.[^\\s]+\\.[^\\s]{2,})/g;\n let index = 0;\n let match;\n while ((match = linkRegex.exec(bundle.content)) !== null) {\n const [, pre, url] = match;\n const startIndex = match.index + pre.length;\n if (startIndex > index) {\n content.push(bundle.content.substring(index, startIndex));\n }\n // Make sure the href we generate from the link is fully qualified. We assume http\n // if it starts with a www because many sites don't support https\n const href = url.startsWith(\"www.\") ? `http://${url}` : url;\n content.push(React.createElement(\"a\", {\n key: index,\n href,\n target: \"_blank\",\n }, `${url}`));\n index = linkRegex.lastIndex;\n }\n if (index < bundle.content.length) {\n content.push(bundle.content.substring(index));\n }\n return React.createElement(\"span\", { style, key, className }, content);\n }", "async requireX(x, y) {\n assert(typeof x === 'string');\n assert(typeof y === 'string');\n assert(isAbsolute(y));\n\n if (x.length === 0 || y.length === 0)\n return null;\n\n if (x === '.' || x === '..')\n x += '/';\n\n if (CORE_MODULES.has(x))\n return x;\n\n // Allow lookups like `C:\\foobar` on windows.\n if (WINDOWS && isAbsolute(x) && x[0] !== '/') {\n y = x; // Gets set to root below.\n x = unix(x);\n }\n\n if (x[0] === '/')\n y = WINDOWS ? parse(y).root : '/';\n\n if (x[0] === '/' || x.startsWith('./') || x.startsWith('../')) {\n const yx = join(y, x);\n const a = await this.loadAsFile(yx);\n\n if (a)\n return a;\n\n const b = await this.loadAsDirectory(yx);\n\n if (b)\n return b;\n }\n\n // Early exit unless we want `/foo` to\n // be able to resolve to `/node_modules/foo`.\n if (x[0] === '/')\n return null;\n\n // Supposed to do dirname(y), but our\n // nodeModulePaths function is different (?).\n const z = await this.loadNodeModules(x, y);\n\n if (z)\n return z;\n\n return null;\n }", "function linkHookFn () {\n process.chdir( fqProjDirname );\n fsObj.symlink(\n '../../bin/git-hook_pre-commit',\n fqHookFilename,\n function ( error_data ) {\n if ( error_data ) { abortFn( error_data ); }\n process.chdir( fqOrigDirname );\n eventObj.emit( '99FinishRun');\n }\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves all root components associated with a DOM element, directive or component instance. Root components are those which have been bootstrapped by Angular.
function getRootComponents(elementOrDir) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(getRootContext(elementOrDir).components); }
[ "getProvidedComponents() {\n const registeredExternalComponents = this.getRegisteredExternalComponents();\n const providedComponents = [];\n registeredExternalComponents.forEach((appExternalComponents) => {\n Array.from(appExternalComponents.values()).forEach((externalComponent) => {\n providedComponents.push(externalComponent);\n });\n });\n return providedComponents;\n }", "function init(rootModules) {\n if (typeof customElements !== 'undefined' && typeof document !== 'undefined') {\n const container = document.querySelector('[lwr-root]');\n rootModules.forEach(([moduleSpecifier, ctor]) => {\n // Kebab-case the specifier\n const elementName = toKebabCase(moduleSpecifier); // Append the root element to the DOM, if it does not exist\n // this is for SPA like routes (one component at the root level) utilizing the lwr-root directive\n\n let el = document.body.querySelector(elementName);\n\n if (!el) {\n el = initializeWebComponent(elementName, ctor);\n\n if (container) {\n // Append to a node with the \"lwr-root\" attribute\n container.appendChild(el);\n } else {\n // Otherwise, add the root to the <body>\n document.body.appendChild(el);\n }\n } else {\n // We have rendered/ssred an HTML page and we need to reify the components\n // Due to the bug described on the header, for each custom element\n // we collect the attributes and we replace the element with the new synthetic contructor\n const customElements = document.querySelectorAll(elementName);\n customElements.forEach(customElement => {\n const newElement = initializeWebComponent(elementName, ctor);\n\n for (const {\n name,\n value\n } of customElement.attributes) {\n newElement.setAttribute(name, value);\n const prop = getPropFromAttrName(name);\n\n if (prop in newElement) {\n // Set attributes as properties too for reactivity\n newElement[prop] = value;\n }\n } // Move the children\n\n\n while (customElement.childNodes.length > 0) {\n newElement.appendChild(customElement.childNodes[0]);\n }\n\n customElement.parentElement.replaceChild(newElement, customElement);\n\n if (globalThis.performance) {\n const metric = 'lwr-bootstrap-on-app-init';\n globalThis.performance.measure(metric);\n }\n });\n }\n });\n }\n }", "function _expandComponents(components)\n {\n /*jshint validthis:true */\n\n var componentsQueue = components;\n var viewModels = [];\n\n var enqueueComponent = function (c) { componentsQueue.push(c); };\n var matchComponentName = function (cname, c) { return c.name.toLowerCase() == cname.toLowerCase(); };\n while (componentsQueue.length > 0)\n {\n var componentRoot = $(componentsQueue.shift()); // dequeue operation\n\n // Get the instance info\n var componentInstanceInfo = getComponentInstanceInfo(componentRoot);\n\n // Check the component type to make sure it isnt a collection component\n if (componentInstanceInfo.type != 'collection' && componentInstanceInfo.type != 'conditional')\n {\n // Find the component description\n var component = this.components().find(matchComponentName.bind(undefined, componentInstanceInfo.component));\n if (component)\n {\n var viewModel = buildComponent(componentRoot, component);\n\n // Add the view model to the list of view models that were processed\n viewModels.push(viewModel);\n\n // Find any child data-component nodes and push them onto the queue\n var childComponents = findChildComponents(componentRoot);\n childComponents.forEach(enqueueComponent);\n }\n }\n }\n\n return viewModels;\n }", "getSelectedComponents() {\r\n let me = this;\r\n let selectedComps = [];\r\n if (me.selectionRect !== null) {\r\n me.moduleController.activeModule.components.forEach((component) => {\r\n let selectionPosReal = me.getRealCoords({ x: me.selectionRect.x, y: me.selectionRect.y });\r\n let selectionRect = \r\n new createjs.Rectangle(\r\n selectionPosReal.x, \r\n selectionPosReal.y, \r\n me.selectionRect.width, \r\n me.selectionRect.height);\r\n if (component.bounds.intersects(selectionRect)) {\r\n selectedComps.push(component);\r\n }\r\n });\r\n }\r\n return selectedComps;\r\n }", "outChildComponents() {\n if(Array.isArray(this.props.loopedComponents)) {\n this.props.loopedComponents.forEach((component) => {\n if(Array.isArray(component.renderedComponents)) {\n Array.from(component.renderedComponents).forEach(comp => {\n comp.out();\n })\n component.renderedComponents = [];\n }\n })\n }\n if(typeof this.childsObj == \"object\") {\n Object.values(this.childsObj).map((component) => {\n component.out();\n })\n }\n }", "function getElements() {\n // logic\n var domEls = [];\n for (var i = 0; i < classNamesArray.length; i++) {\n domEls.push(document.getElementsByClassName(classNamesArray[i]));\n }\n return domEls;\n}", "function getRoots(bundle, bundles) {\n let roots = [(bundle.root + '/').replace('//', '/')];\n _.forEach(bundle.dependencies, d => {\n let dep = _.find(bundles, b => b.name === d);\n roots = roots.concat(getRoots(dep, bundles));\n });\n return roots;\n}", "static getConsumedComponents(options = {}) {\n const { filter } = options;\n const component = this;\n return {\n *[Symbol.iterator]() {\n for (const name of component.__getConsumedComponents()) {\n const consumedComponent = component.getConsumedComponent(name);\n if (filter !== undefined && !filter(consumedComponent)) {\n continue;\n }\n yield consumedComponent;\n }\n }\n };\n }", "function initializeControllers() {\n let instances = [];\n controllers.forEach(x => {\n instances.push(new x.Controller());\n });\n return instances;\n}", "function vendors() {\n return [\n '@angular/platform-browser',\n '@angular/platform-browser-dynamic',\n '@angular/compiler',\n '@angular/router',\n '@angular/forms',\n '@angular/common',\n '@angular/core',\n '@angular/http',\n ];\n}", "getRootNavs() {\n const navs = [];\n rootNavs.forEach((rootNav) => {\n navs.push(rootNav);\n });\n return navs;\n }", "function allSCComponents(wantClass) {\n var ids = [];\n var d;\n basicColorMenu.forEach(function (item) {\n d = item.elements.map(function (ele) {\n if (wantClass) return `.${ele}`;\n else return ele;\n });\n ids = ids.concat(d);\n });\n idsSet = new Set(ids);\n ids = Array.from(idsSet);\n return ids;\n}", "function getNonTensorBoardComponents() {\n return fs.readdirSync('components')\n .filter(function(file) {\n var prefix = file.slice(0,3);\n return fs.statSync(path.join('components', file)).isDirectory() &&\n prefix !== 'tf-' && prefix !== 'vz-';\n })\n .map(function(dir) { return '/' + dir + '/'; });\n}", "_renderViewportComponents() {\n const {viewports} = this.props;\n\n const children = [];\n\n viewports.forEach((viewportOrDescriptor, i) => {\n const {viewport, component, Component, props = {}} = viewportOrDescriptor;\n\n // Check if this is a descriptor with a component, otherwise ignore\n if (viewport && (component || Component)) {\n\n // TODO - this is too react-map-gl specific\n const newProps = Object.assign({}, props, {\n visible: viewport.isMapSynched(),\n width: viewport.width,\n height: viewport.height\n }, viewport.getMercatorParams());\n\n // Check if we should create or just modify a supplied React component\n const newComponent = component ?\n cloneElement(component, newProps) :\n createElement(Component, newProps);\n\n const style = {\n position: 'absolute',\n left: viewport.x,\n top: viewport.y,\n width: viewport.width,\n height: viewport.height\n };\n\n children.push(createElement('div', {key: `viewport-component-${i}`, style}, newComponent));\n }\n });\n\n return children;\n }", "function elements() {\n return _elements;\n }", "get lettersDOM() {\n return document.querySelectorAll('.letter');\n }", "function iterSplitters(root, cb) {\n var result = cb(root);\n if (result !== void 0) {\n return result;\n }\n for (var i = 0, n = root.count; i < n; ++i) {\n var widget = root.widgetAt(i);\n if (widget instanceof DockSplitter) {\n result = iterSplitters(widget, cb);\n if (result !== void 0) {\n return result;\n }\n }\n }\n }", "function getPackages(cs_Children)\n{\n \n\tvar nPackages = packages.length;\n\tif (nPackages)\n\t{\n\t\tfor (var p=0; p<nPackages; p++)\n\t\t{\n\t\t\tpackages.pop();\n\t\t}\n\t}\n\t\n\tvar start = new Date();\n\n\tvar roots = new Array();\n\tvar cfctreeDOM = getcfctreeDOM(bForceRefresh);\n\n\tif ((cfctreeDOM != null) && (cfctreeDOM.hasChildNodes()))\n\t{\n\t\tif (!parseCFCtree(cfctreeDOM, roots))\n\t\t{\n\t\t\tif (bDoingManualRefresh)\n\t\t\t{\n\t\t\t\t// If we got at least one root then we know that the server is running\n\t\t\t\t// and that there must have been some sort of very specific parsing\n\t\t\t\t// problem or failure within Neo. Go ahead and show the data for\n\t\t\t\t// the roots we got but warn the user that there was a significant\n\t\t\t\t// problem.\n\n\t\t\t\tif (roots.length > 0)\n\t\t\t\t{\n\t\t\t\t\talert(MM.MSG_CFC_PartiallyParsedTree);\n\t\t\t\t}\n\n\t\t\t\t// If we failed to get even a single root then we either suffered a\n\t\t\t\t// massive failure (like the server isn't running) or we encountered\n\t\t\t\t// significant problems parsing the first root we found. In either case\n\t\t\t\t// we can't show anything in the tree. Tell the user why the tree is\n\t\t\t\t// going to be empty.\n\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\talert(MM.MSG_CFC_FailedToParseTree);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if (bDoingManualRefresh)\n\t{\n\t\talert(MM.MSG_CFC_FailedToParseTree);\n\t}\n\t\n\tvar end = new Date();\n\t//alert('parse DOM in: ' + (end - start) + ' ms');\n\n\tif (roots.length)\n\t{\n\t\tvar els2 = 'N/A';\n\t\tvar rootsToExclude = new Array();\n\t\tif( sitePrefix == FILTERING_SITE_ROOT ) {\n\t\t\tparseComponentRoots(getComponentRootsDOM(), rootsToExclude);\n\t\t}\n\t\telse if (sitePrefix != '') {\n\t\t\tels2 = getLocalPackages();\n\t\t}\n\n\t\tfor (var r=0; r<roots.length; r++)\n\t\t{\n\t\t\tvar aRoot = roots[r];\n\t\t\t\n\t\t\tvar exlcudeRoot = false;\n\t\t\t\n\t\t\t//check to see if this root is one we want to exlcude. We exlcude any root that has a prefix. The\n\t\t\t//prefix means it's any additional direcotry added in the CF admin page and not directly related to this site\n\t\t\t//and since we're filtering the site root, we want the cfcs that live in the root (have no prefix)\n\t\t\tfor ( var i = 0 ; i < rootsToExclude.length ; i++ )\n\t\t\t{\n\t\t\t\tvar anExcludedRoot = rootsToExclude[i];\n\t\t\t\tif( ( anExcludedRoot.prefix != '' ) &&\n\t\t\t\t\t( aRoot.physicalPath.indexOf(anExcludedRoot.physicalPath) == 0 ) )\n\t\t\t\t{\n\t\t\t\t\texlcudeRoot = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif( exlcudeRoot ){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif (aRoot.packages.length)\n\t\t\t{\n\t\t\t\tfor (var p=0; p<aRoot.packages.length; p++)\n\t\t\t\t{\n\t\t\t\t\tvar aPackage = aRoot.packages[p];\n\n\t\t\t\t\t// Save the package information so we can easily access it\n\t\t\t\t\t// from any node in the tree.\n\t\t\t\t\tvar tmp = aPackage.name.toString().toLowerCase();\n\n\t\t\t\t\tvar shThis = false;\n\t\t\t\t\tif (sitePrefix == '' || sitePrefix == FILTERING_SITE_ROOT) {\n\t\t\t\t\t\tshThis = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (els2 == 'N/A') {\n//\t\t\t\t\t\t\tif (tmp.indexOf(sitePrefix) == 0) {\n\t\t\t\t\t\t\tif ((tmp == sitePrefix) || (tmp.indexOf(sitePrefix + '.') == 0)) {\n\t\t\t\t\t\t\t\tshThis = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (els2[tmp] == 1) {\n\t\t\t\t\t\t\t\tshThis = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (shThis) {\n\t\t\t\t\t\tpackages.push(aPackage);\n\t\t\t\t\t\tvar packageCompInfo = new ComponentRec((aPackage.name == \"\") ? MM.MSG_CFC_UnnamedPackage : aPackage.name, PACKAGE_FILENAME, (aPackage.CFCs.length > 0), false, \"\");\n\t\t\t\t\t\tpackageCompInfo.objectType = PACKAGE_OBJECT_TYPE;\n\t\t\t\t\t\tpackageCompInfo.aPackage = aPackage;\n\t\t\t\t\t\tpackageCompInfo.detailsText = \"\";\n\t\t\t\t\t\tcs_Children.push(packageCompInfo);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "getElementServicesForProbe (probe) {\n // Retrieve target elements for all models or specified one\n let services = this.app.getElementServices(probe.forecast)\n services = services.filter(service => {\n return probe.elements.reduce((contains, element) => contains || (service.name === probe.forecast + '/' + element), false)\n })\n return services\n }", "_initElements () {\n this.tablist = this.element.querySelector(this.tablistSelector)\n this.tabs = Array.from(this.element.querySelectorAll(this.tabSelector))\n this.panels = Array.from(this.element.querySelectorAll(this.panelSelector))\n\n // The data-rvt-tablist attribute was added in Rivet 2.4.0. To maintain\n // backward compatibility, the code below infers which element is the\n // tablist if the data-rvt-tablist attribute is not present.\n\n if (!this.tablist) {\n this.tablist = this.tabs[0].parentElement\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get url and retuen an array of names thet also have the urls type
async function getType(url) { const response = await axios.get(url); const data = await response; const namesByTypeArr = []; for (let pokemon of data.data.pokemon) { namesByTypeArr.push(pokemon.pokemon.name); } buildNameList(namesByTypeArr); }
[ "getUrl (name) {\n name = name.name ? name.name : name\n return this.urls[name]\n }", "function getUrlReferences(References) {\n return References ? References.filter(ref => ref.startsWith(\"http\")).map(ref => ({type: \"URL\", value: ref})) : [];\n}", "function anchor_type_list()\n{\n var anchor_type_list=[];\n anchor_main_hash=getMainAchorHash();\n var anchor_type=doGetLinkLoad(anchor_main_hash,\"Anchor_Type\");\n\n debug(\"AnchorType:\"+anchor_type);\n for(var j=0;j<anchor_type.length;j++)\n {\n var temp = anchor_type[j].Anchor_Type;\n debug(temp);\n anchor_type_list.push(anchor_type[j].Anchor_Type);\n }\n\n return anchor_type_list.toString();\n}", "function getUrlType() {\n let url = document.location.href\n\n if(url.match(/http(s)?:\\/\\/open\\.spotify\\.com\\/playlist\\/.+/) != null)\n return 'playlist'\n\n if(url.match(/http(s)?:\\/\\/open\\.spotify\\.com\\/album\\/.+/) != null)\n return 'album'\n\n if(url.match(/http(s)?:\\/\\/open\\.spotify\\.com\\/collection\\/tracks/) != null)\n return 'collection'\n\n return 'other' // = Nothing of the above\n}", "get urlsToProcess () {\n return urlsToProcess.slice();\n }", "function URLParamatersToArray(url) {\n\tvar request = [];\n\tvar pairs = url.substring(url.indexOf('?') + 1).split('&');\n\tfor (var i = 0; i < pairs.length; i++) {\n\t\tif(!pairs[i])\n\t\t\tcontinue;\n\t\tvar pair = pairs[i].split('=');\n\t\trequest.push(decodeURIComponent(pair[0]));\n\t}\n\treturn request;\n}", "function getURLs(urls) {\n // split the contents by new line\n const lines = urls.split(/\\r?\\n/);\n\n lines.forEach((line) => {\n axios.get(line).then(function(resp) {\n doSomething(resp, line);\n })\n .catch(err => {\n console.log(`Error with url in file`)\n })\n });\n}", "getDefaultUrlFields() {\n return [\n 'type',\n 'slug'\n ];\n }", "function extractURLs (e) {\n var text = txtArea.value\n\n var urls = ''\n var urlmatcharr\n var urlregex = /\\b((?:[a-z][\\w-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))/gi\n while ((urlmatcharr = urlregex.exec(text)) !== null) {\n var match = urlmatcharr[0]\n urls += match + '\\n'\n }\n\n txtArea.value = urls\n recordOpts({ txt: urls })\n}", "get typeURL() {\n return this._content[0];\n }", "async function getReflections(url) {\n const reflections = await getObject(url)\n // update reflection array\n setReflections(reflections)\n }", "function constructAPIURL(urls) {\n\tvar ids = [];\n\tfor (let url of urls) {\n\t\tlet id;\n\t\tif (url.match(/\\.(io|com|org)\\/([a-z0-9]+)/)) {\n\t\t\tid = url.match(/\\.(?:io|com|org)\\/([a-z0-9]+)/)[1];\n\t\t}\n\t\tif (id) {\n\t\t\tids.push(\"https://api.osf.io/v2/preprints/\" + id + \"/?embed=contributors&embed=provider\");\n\t\t}\n\t}\n\treturn ids;\n}", "function getSceneLinks() {\n var returnData = [];\n\n $('h3.card-info__title a').each(function () {\n var theLink = window.location.origin + $(this).attr('href');\n //console.log(theLink);\n returnData.push(theLink);\n });\n\n return returnData;\n}", "function get_url_vars() {\n var url = document.location.href,\n domain = document.domain,\n extras = url.replace('http://' + domain, ''),\n vars = extras.split('/').map(Number),\n array = $.grep(vars,function(n){\n return n;\n });\n return array;\n }", "function createdURLsFetched(urls){\n\treturn {\n type: CREATED_URLS_FETCHED,\n payload: urls\n\t}\n}", "function getGenreLevel(html) {\n\tvar urls = [];\n\tvar pattern = 'https://itunes.apple.com/us/genre/';\n\tvar $ = cheerio.load(html);\n\n // get all top-level genres\n\t$('#genre-nav a.top-level-genre').each(function () {\n\t\tvar href = $(this).attr('href');\n\t\tif (href.indexOf(pattern) > -1) {\n\t\t\turls.push(href);\n\t\t}\n\t});\n\n\treturn urls;\n}", "function getDomainFilterItems(str) {\n\n let outArr = [];\n let pageHost = window.location.hostname;\n pageHost = pageHost.replace(/www./g, \"\");\n\n let strArr = str.split(\",\");\n for (let i in strArr) {\n\n if (strArr[i].startsWith(\"*\")) {\n\n if (\n pageHost.search(\n strArr[i].replace(\"*.\", \"\").replace(\"*\", \"\")\n ) !== -1\n ){\n\n outArr.push(strArr[i]);\n }\n }\n }\n return outArr;\n}", "_createUrls () {\n\t\tvar urls = {};\n\n\t\t//set up all the urls required\n\t\turls.idea = '/' + this.props.idea.idea_id + '/';\n\t\turls.category = '/';\n\t\turls.status = '/' + window.userInfo.company + '/ideas/?status=' + this.props.idea.status.id;\n\n\t\tconsole.log(\"props...\");\n\t\tconsole.log(this.props.idea);\n\n\t\t//member details are not returned from live search results\n\t\turls.member = '/' + window.userInfo.company + '/member/' + this.props.idea.last_activity.user.id + '/'; \n\t\turls.created_by = '/' + window.userInfo.company + '/member/' + this.props.idea.created_by.id + '/';\t\n\t\t\n\t\t//fall back for no category\n\t\tif( this.props.idea.category_id != null ) {\n\t\t\turls.category = '/' + window.userInfo.company + '/category/' + this.props.idea.category_id + '/';\n\t\t} else {\n\t\t\turls.category = '/';\n\t\t}\n\n\t\treturn urls;\n\t}", "function getAppUrls(mime) {\n\tvar as = [];\n\tif (mime) {\n\t\tvar apps = getSupportingEntries(mime, options.device);\n\t\tif (apps==null)\n\t\t\t// unknown support\n\t\t\tas.push('');\n\t\telse if (apps.length==0) {\n\t\t\t// built-in\n\t\t}\n\t\telse {\n\t\t\tfor (var ai in apps) {\n\t\t\t\tvar app = apps[ai];\n\t\t\t\tif (!app.enclosures)\n\t\t\t\t\tcontinue;\n\t\t\t\tfor (var enci in app.enclosures) {\n\t\t\t\t\tvar appenc = app.enclosures[enci];\n\t\t\t\t\tif (appenc.url) {\n\t\t\t\t\t\tas.push(appenc.url);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (as.length==0) {\n\t\t\t\tconsole.log('Could not find url(s) for apps supporting '+enc.mime);\n\t\t\t\tas.push('');\n\t\t\t}\n\t\t}\n\t}\n\treturn as;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an arbitrarily long ray, starting at the player position, through the specified angle. Check if this ray intersets any walls. If it does, return the point at which it intersects the closest wall. Otherwise, return the point at which it intersects the edge of the stage.
function checkRayIntersection(ctx, angle) { // Create a ray from the light to a point on the circle var ray = new Phaser.Line(globals.player.x, globals.player.y, globals.player.x + Math.cos(angle) * 1000, globals.player.y + Math.sin(angle) * 1000); // Check if the ray intersected any walls var intersect = ctx.getWallIntersection(ray, walls); // Save the intersection or the end of the ray if (intersect) { return intersect; } else { return ray.end; } }
[ "function checkClosestWall(ctx, angle, closestWall) {\n // Create a ray from the light to a point on the circle\n var ray = new Phaser.Line(globals.player.x, globals.player.y,\n globals.player.x + Math.cos(angle) * 1000,\n globals.player.y + Math.sin(angle) * 1000);\n // Check if the ray intersected any walls\n var newWall = ctx.getClosestWall(ray, walls);\n // Save the intersection or the end of the ray\n if (!newWall || !closestWall) { return false; }\n if (newWall.start.x <= closestWall.start.x + 3 &&\n newWall.start.x >= closestWall.start.x - 3 &&\n newWall.start.y <= closestWall.start.y + 3 &&\n newWall.start.y >= closestWall.start.y - 3 &&\n newWall.end.x <= closestWall.end.x + 3 &&\n newWall.end.x >= closestWall.end.x - 3 &&\n newWall.end.y <= closestWall.end.y + 3 &&\n newWall.end.y >= closestWall.end.y - 3) {\n return false;\n } else {\n return newWall;\n }\n }", "function findHoleBridge( hole, outerNode ) {\n \n var p = outerNode,\n hx = hole.x,\n hy = hole.y,\n qx = - Infinity,\n m;\n \n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n do {\n \n if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {\n \n var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );\n if ( x <= hx && x > qx ) {\n \n qx = x;\n if ( x === hx ) {\n \n if ( hy === p.y ) return p;\n if ( hy === p.next.y ) return p.next;\n \n }\n \n m = p.x < p.next.x ? p : p.next;\n \n }\n \n }\n \n p = p.next;\n \n } while ( p !== outerNode );\n \n if ( ! m ) return null;\n \n if ( hx === qx ) return m.prev; // hole touches outer segment; pick lower endpoint\n \n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n \n var stop = m,\n mx = m.x,\n my = m.y,\n tanMin = Infinity,\n tan;\n \n p = m.next;\n \n while ( p !== stop ) {\n \n if ( hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {\n \n tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential\n \n if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {\n \n m = p;\n tanMin = tan;\n \n }\n \n }\n \n p = p.next;\n \n }\n \n return m;\n \n }", "function rayXline(rx, ry, dx, dy, x1, y1, x2, y2, infinite){\n\t\n\tvar lx, ly, d, nx, ny, a, b;\n\tlx = x2 - x1;\n\tly = y2 - y1;\n\td = Math.sqrt(lx * lx + ly * ly);\n\tnx = ly / d;\n\tny = -lx / d;\n\t\n\ta = dx * nx + dy * ny;\n\tb = (x1 - rx) * nx + ( y1 - ry ) * ny;\n\n\tif( a != 0 && ( a > 0 ^ b < 0 ) ){//Check if there is an intersection with the inifinite line\n\t\n\t\tl = b / a;\n\t\tif( infinite )\n\t\t\treturn l;\n\t\telse {\n\t\t\tvar xx = rx + dx * l;\n\t\t\tvar yy = ry + dy * l;\n\t\t\tvar g = ((xx - x1) * lx + (yy - y1) * ly) / (lx * lx + ly * ly);\n\t\t\tif( g >= 0 && g <= 1)\n\t\t\t\treturn l;\n\t\t\telse return null;\n\t\t\t\n\t\t}\n\t} else return null;\n}", "function Ray (\n o = new Point3(),\n d = new Vector3(),\n tMax = Infinity,\n time = 0,\n medium = null\n) {\n this.o = o // Point3\n this.d = d // Vector3\n\n this.tMax = tMax // Number\n this.time = time // Number\n\n this.medium = medium // Medium\n}", "pointerToRay(pointer) {\n\n const camera = this.viewer.navigation.getCamera()\n const pointerVector = new THREE.Vector3()\n const rayCaster = new THREE.Raycaster()\n const pointerDir = new THREE.Vector3()\n const domElement = this.viewer.canvas\n\n const rect = domElement.getBoundingClientRect()\n\n const x = ((pointer.clientX - rect.left) / rect.width) * 2 - 1\n const y = -((pointer.clientY - rect.top) / rect.height) * 2 + 1\n\n if (camera.isPerspective) {\n\n pointerVector.set(x, y, 0.5)\n\n pointerVector.unproject(camera)\n\n rayCaster.set(camera.position,\n pointerVector.sub(\n camera.position).normalize())\n\n } else {\n\n pointerVector.set(x, y, -15)\n\n pointerVector.unproject(camera)\n\n pointerDir.set(0, 0, -1)\n\n rayCaster.set(pointerVector,\n pointerDir.transformDirection(\n camera.matrixWorld))\n }\n\n return rayCaster.ray\n }", "raycastRoot(minx: number, miny: number, maxx: number, maxy: number, p: vec3Like, d: vec3Like, exaggeration: number = 1): ?number {\n const min = [minx, miny, -aabbSkirtPadding];\n const max = [maxx, maxy, this.maximums[0] * exaggeration];\n return aabbRayIntersect(min, max, p, d);\n }", "function closestSafeZone(personLong, personLat){\r\n var targetPoint = turf.point([personLat, personLong])\r\n var points;\r\n var poly = turf.polygon(zones[0])\r\n var line = turf.polygonToLine(poly)\r\n return turf.nearestPointOnLine(line, targetPoint)\r\n}", "function rayXcircle(rx, ry, dx, dy, cx, cy, r, type){\n\n\tvar xx = cx - rx; \n\tvar yy = cy - ry; \n\tvar b = ( xx * dx + yy * dy );\n\tvar c = xx * xx + yy * yy - r * r;\n\tif ( b * b - c > 0 ){\n\t\n\t\tvar q = Math.sqrt( b * b - c );\n\t\t\n\t\tif ( type != 2 )\n\t\t\tif ( b - q >= 0)//Outside of circle\n\t\t\t\treturn b - q;\n\t\t\t\n\t\tif ( type != 1 )\n\t\t\tif ( b + q >= 0)//Inside of circle\n\t\t\t\treturn b + q;\n\t}\n\treturn null;\n}", "function cannonBallsHitEdgeOfCanvas(cannonBall){\n let hadCollision = false;\n if(cannonBall.x - cannonBall.radius < stageX){\n //Left edge collision\n cannonBall.x = stageX + cannonBall.radius;\n cannonBall.vx *= -1;\n hadCollision = true;\n }else if(cannonBall.x + cannonBall.radius > stageX + stageWidth){\n //Right edge collision\n cannonBall.x = (stageX + stageWidth) - cannonBall.radius;\n cannonBall.vx *= -1;\n hadCollision = true;\n }else if(cannonBall.y - cannonBall.radius < stageY){\n //Top edge collision\n cannonBall.y = stageY + cannonBall.radius;\n cannonBall.vy *= -1;\n hadCollision = true;\n }else if(cannonBall.y + cannonBall.radius > stageY + stageHeight){\n //Bottom edge collision\n cannonBall.y = (stageY + stageHeight) - cannonBall.radius;\n cannonBall.vy *= -1;\n hadCollision = true;\n }\n\n if(hadCollision){\n if(!gamePaused && new Date() - lastClink > 50){\n playAudio(clinkSFX, 0.3);\n lastClink = new Date();\n } \n }\n}", "function left_wall_force(pos_x, radius, elastic_constant=constant.elastic) {\r\n let edge_at = pos_x - radius\r\n if (edge_at < 0) {\r\n return Math.abs(edge_at) * elastic_constant\r\n }\r\n return 0\r\n}", "function sweptCircleXline(cx,cy,r,dx,dy,x1,y1,x2,y2){\n\t\n\tif(x2 == x1 && y2 == y1){\n\t\tif( (cx - x1) * (cx - x1) + (cy - y1) * (cy - y1) < r * r){\n\t\t\treturn 0;\n\t\t}else {\n\t\t\treturn rayCircle(cx, cy, dx, dy, x1, y1, r, 1);\n\t\t}\n\t} else {\n\n\t\tvar lx = x2 - x1;\n\t\tvar ly = y2 - y1;\n\t\t\n\t\tvar d = Math.sqrt(lx * lx + ly * ly);\n\t\tvar nx = ly / d;\n\t\tvar ny = -lx / d;\n\t\t\n\t\tif( Math.abs(nx * (cx - x1) + ny * (cy - y1)) > r ){\n\t\t\t\n\t\t\tvar cxo, cyo;\n\n\t\t\tif( (x1 - cx) * nx + ( y1 - cy ) * ny < 0 ) {\n\t\t\t\tcxo = cx - nx * r;\n\t\t\t\tcyo = cy - ny * r;\n\t\t\t} else {\n\t\t\t\tcxo = cx + nx * r;\n\t\t\t\tcyo = cy + ny * r;\n\t\t\t}\n\t\t\t\n\t\t\tvar a = dx * nx + dy * ny;\n\t\t\tvar b = (x1 - cxo) * nx + ( y1 - cyo ) * ny;\n\t\t\t\n\t\t\tif( a != 0 && ( a > 0 ^ b < 0 ) ){\n\t\t\t\n\t\t\t\tvar l = b / a;\n\t\t\t\tvar xx = cxo + dx * l;\n\t\t\t\tvar yy = cyo + dy * l;\n\t\t\t\tvar g = ((xx - x1) * lx + (yy - y1) * ly) / (lx * lx + ly * ly);\n\t\t\t\t\n\t\t\t\tif( g < 0 ){\n\t\t\t\t\treturn rayCircle(cx, cy, dx, dy, x1, y1, r, 1);\n\t\t\t\t}else if( g > 1 ){\n\t\t\t\t\treturn rayCircle(cx, cy, dx, dy, x2, y2, r, 1);\n\t\t\t\t}else {\n\t\t\t\t\treturn l;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\n\t\t\tif( lx * (cx - x1) + ly * (cy - y1) < 0 ){\n\t\t\t\n\t\t\t\tif( (cx - x1) * (cx - x1) + (cy - y1) * (cy - y1) < r * r){\n\t\t\t\t\treturn 0;\n\t\t\t\t}else {\n\t\t\t\t\treturn rayCircle(cx, cy, dx, dy, x1, y1, r, 1);\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t} else if( lx * (cx - x2) + ly * (cy - y2) > 0 ){\n\t\t\t\n\t\t\t\tif( (cx - x2) * (cx - x2) + (cy - y2) * (cy - y2) < r * r){\n\t\t\t\t\treturn 0;\n\t\t\t\t}else {\n\t\t\t\t\treturn rayCircle(cx, cy, dx, dy, x2, y2, r, 1);\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t} else {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n}", "function createWallInView(object) {\n\t\n\tvar wall = new Path();\n wall.strokeColor = 'black';\n\n\t//initialPoint of wall:\n wall.add(new Point(object.initialPoint.x*ratio, object.initialPoint.y*ratio));\n\n //finalPoint of wall:\n wall.add(new Point(object.finalPoint.x*ratio, object.finalPoint.y*ratio));\n\n return wall;\n}", "function getClosestNonWallTile(target){\r\n let min = 1000;\r\n let minIndexj = 0;\r\n let minIndexi = 0;\r\n for(let i=0; i<28; i++){//goes through each tile\r\n for(let j=0; j<31; j++){\r\n if(!originalTiles[j][i].wall){//if it is the current closest target\r\n if(dist(i, j, target.x, target.y)<min){\r\n min = dist(i, j, target.x, target.y);\r\n minIndexj = j;\r\n minIndexi = i;\r\n }\r\n }\r\n }\r\n }return createVector(minIndexi, minIndexj);//returns a PVector to the tile\r\n}", "function intersection(ray, objects, tMin) {\n let closest = null;\n for (let k = 0; k < objects.length; k++) {\n const t = objects[k].intersects(ray);\n // intersects, not behind the eye, and the closest\n if (t != null && t > 0 && t < tMin) {\n closest = objects[k];\n tMin = t;\n }\n }\n return { obj: closest, tVal: tMin };\n}", "function RayHelper(ray){this.ray=ray;}", "find_direction() {\n this.direction = (this.direction + 1) % 4; // CCW 90\n if (!this.is_facing_wall())\n return true;\n this.direction = (this.direction + 3) % 4; // CCW 270\n if (!this.is_facing_wall())\n return true;\n this.direction = (this.direction + 3) % 4; // CCW 270\n if (!this.is_facing_wall())\n return true;\n this.direction = (this.direction + 3) % 4; // CCW 270\n if (!this.is_facing_wall())\n return true;\n // If all four sides have walls\n console.log(\"Oops, an error occurred and the bot thinks it's trapped!\");\n return false;\n }", "function makeWalls( worldPivot, spaceApart, left, up, right, down, material ) {\n\n\tvar object;\n\tvar box;\n\n\t// right\n\tif ( right ) {\n\n\t\tobject = new THREE.Mesh( new THREE.BoxBufferGeometry( spaceApart, WallLength, WallThickness, 4, 4, 4 ), material );\n\t\tobject.position.set( worldPivot.x, 50, worldPivot.z + spaceApart / 2 );\n\t\tscene.add( object );\n\t\twalls.push( object );\n\n\t\tbox = new THREE.Box3();\n\t\tbox.setFromObject( object );\n\t\twallColliders.push( box );\n\n\t}\n\n\t// up\n\tif ( up ) {\n\n\t\tobject = new THREE.Mesh( new THREE.BoxBufferGeometry( spaceApart, WallLength, WallThickness, 4, 4, 4 ), material );\n\t\tobject.position.set( worldPivot.x + spaceApart / 2, 50, worldPivot.z );\n\t\tobject.rotateY( THREE.Math.degToRad( 90 ) );\n\n\t\tscene.add( object );\n\t\twalls.push( object );\n\n\t\tbox = new THREE.Box3();\n\t\tbox.setFromObject( object );\n\t\twallColliders.push( box );\n\n\t}\n\n\t// left\n\tif ( left ) {\n\n\t\tobject = new THREE.Mesh( new THREE.BoxBufferGeometry( spaceApart, WallLength, WallThickness, 4, 4, 4 ), material );\n\t\tobject.position.set( worldPivot.x, 50, worldPivot.z - spaceApart / 2 );\n\t\tscene.add( object );\n\t\twalls.push( object );\n\n\t\tbox = new THREE.Box3();\n\t\tbox.setFromObject( object );\n\t\twallColliders.push( box );\n\n\t}\n\n\t// down\n\tif ( down ) {\n\n\t\tobject = new THREE.Mesh( new THREE.BoxBufferGeometry( spaceApart, WallLength, WallThickness, 4, 4, 4 ), material );\n\t\tobject.position.set( worldPivot.x - spaceApart / 2, 50, worldPivot.z );\n\t\tobject.rotateY( THREE.Math.degToRad( 90 ) );\n\t\tscene.add( object );\n\t\twalls.push( object );\n\n\t\tbox = new THREE.Box3();\n\t\tbox.setFromObject( object );\n\t\twallColliders.push( box );\n\n\t}\n\n}", "function HittingTheWall(){\r\n for(let i = 0; i < curTetromino.length; i++){\r\n let newX = curTetromino[i][0] + startX;\r\n if(newX <= 0 && direction === DIRECTION.LEFT){\r\n return true;\r\n } else if(newX >= 11 && direction === DIRECTION.RIGHT){\r\n return true;\r\n } \r\n }\r\n return false;\r\n}", "function pixelRayDeltaAngle(distance, x, y) {\n\tvar deltas = [];\n\tvar angle = Math.atan2(x - axis.x, -y + axis.y) + Math.PI;\n\tvar spiralOffset = spirality * distance;\n\n\tfor (var ray = 0; ray < rays; ray++) {\n\t\tvar offsetAngle = 2 * Math.PI / rays * ray;\n\n\t\t// Look 3 rounds back and ahead\n\t\tfor (var i = -3; i < 3; i++) {\n\t\t\tvar roundAngle = i * 2 * Math.PI;\n\t\t\tdeltas.push(Math.abs(angle - cmpAngle - offsetAngle - spreadAngle\n\t\t\t\t+ spiralOffset - roundAngle));\n\t\t}\n\t}\n\n\t// Find the ray with the smallest delta angle\n\tvar mindelta = null;\n\tfor (var d in deltas) {\n\t\tif (mindelta === null || deltas[d] < mindelta) mindelta = deltas[d];\n\t}\n\treturn mindelta;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ask the user a question, repeat until all presidents have been asked about
function askQuestion() { inquirer.prompt([ { type: "input", message: questionArray[count].partial, name: "answer" } ]).then(function(resp) { // The answer was correct if (resp.answer.toLowerCase() === questionArray[count].cloze.toLowerCase()) { console.log("Correct"); score++; // Increase score } // The answer was incorrect else { console.log("Incorrect"); console.log("The correct answer was " + questionArray[count].cloze) } count++; // If there are more presidents left, ask another question if (count < questionArray.length) { askQuestion(); } // Otherwise the game is over, display final score else { console.log("Quiz over. You got " + score + "/" + questionArray.length + " correct."); } }) }
[ "function promptAnotherAction() {\n inquirer.prompt([\n // Prompt user for yes or no\n {\n type: \"confirm\",\n message: \"Would you like to perform another action?\",\n name: \"anotherAction\",\n },\n ]).then(function (inquirerResponse) {\n // If yes to prompt\n if (inquirerResponse.anotherAction) {\n console.log();\n // Show products again\n promptSelection();\n } else {\n console.log(\"\\nGoodbye!\\n\");\n\n // End DB connection\n connection.end();\n }\n });\n}", "function promptAnswer() {\n r = printRandQuestion();\n let answer = prompt('Whats the correct answer?');\n\n // Check if player wants to exit\n if (answer !== 'exit') {\n\n // Check answer and display result plus total score, then start again\n questions[r].checkAnswer(parseInt(answer));\n promptAnswer();\n\n }\n }", "function supervisorContinue() {\n inquirer.prompt([\n {\n name: \"stayOn\",\n message: \"Do you want to continue supervising inventory?\",\n type: \"confirm\"\n }\n ])\n .then(answer => {\n if (answer.stayOn) {\n supervisorQuestions();\n } else {\n connection.end();\n process.exit();\n }\n }).catch(error => {\n if (error) {\n console.log(error.message);\n }\n });\n}", "function continueManage() {\n // prompt if another action is needed \n inquirer\n .prompt(\n {\n name: \"confirm\",\n type: \"confirm\",\n message: \"Would you like to do something else?\",\n default: true\n\n })\n .then(function (answer) {\n if (answer.confirm) {\n managerOptions();\n }\n else {\n console.log(\"Thank you! Goodbye.\")\n connection.end();\n }\n });\n}", "function confirmTrip() {\n console.log(\n \"Destination: \" +\n myTrip[0] +\n \" Restaurant: \" +\n myTrip[1] +\n \" Transportation: \" +\n myTrip[2] +\n \" Entertainment \" +\n myTrip[3]\n );\n let userHappinessRequest = prompt(\n \"Are you satisfied with all your random selections?\"\n );\n\n if (userHappinessRequest === \"yes\") {\n console.log(\"Day Trip confirmed! Have fun!\");\n } else {\n newUserChoices();\n }\n}", "_promptLoop() {\n // If there are still projects, ask about the next one\n if (this._sortedProjectList.length) {\n return this._askQuestions(this._sortedProjectList.pop())\n .then((answers) => {\n if (answers) {\n // Save the info into the changefile\n let changeFile = this._changeFileData.get(answers.packageName);\n if (!changeFile) {\n changeFile = {\n changes: [],\n packageName: answers.packageName,\n email: undefined\n };\n this._changeFileData.set(answers.packageName, changeFile);\n }\n changeFile.changes.push(answers);\n }\n // Continue to loop\n return this._promptLoop();\n });\n }\n else {\n this._warnUncommittedChanges();\n // We are done, collect their email\n return this._detectOrAskForEmail().then((email) => {\n this._changeFileData.forEach((changeFile) => {\n changeFile.email = email;\n });\n this._writeChangeFiles();\n });\n }\n }", "function q1to5(){\n alert('Welcome! Question after this would require only (y/n) or (yes/no) as response ');\n //Show prompt until user enter correct answers ;Q1-Q5\n for(i; i<5;i++)\n {\n do{\n response = prompt(questionArray[i]);\n response = response.toLowerCase();\n //if corrent input isn't inserted then shows user a alert\n if(response!=='y'&&response!=='n'&&response!=='yes'&&response!=='no')\n {\n alert('Plese enter either (y/n) or (yes/no) as response');\n }\n }while(response!=='y'&&response!=='n'&&response!=='yes'&&response!=='no');\n //loggin user's response\n console.log('For'+ questionArray[i] + ' User responded: ' + response);\n // to check the reponses from user if submitted response is true or false\n if(i%2===0)\n {\n if(response==='y'||response==='yes')\n {\n alert('Sorry! Incorrect!!');\n }\n else\n {\n alert('Correct');\n correctCount++;\n //tracking the quetions which were correct\n correctAnswer.push(i+1);\n }//end of inner if-else loop\n }\n else\n {\n if(response==='y'||response==='yes')\n {\n alert('Correct!');\n correctCount++;\n }\n else\n {\n alert('Incorrect!!');\n }//end of if-else iner looop\n }//end of if-else outter loop\n }// end of for loop\n//start of 6th Question\n}", "async function prompt(resolve) {\n while (true) {\n const answer = await promptRegion();\n const region = parseInt(answer);\n if (isNaN(region) || region <= 0) {\n stdio.write(`Invalid district '${answer}'\\n`)\n } else {\n stdio.close();\n resolve(region);\n break;\n }\n }\n}", "function confidence() {\r\n\r\n let confidenceLevel = true; // it asks for this in 1b\r\n // i need a while loop to run the questions for low, med, high\r\n while (confidenceLevel == true) {\r\n //I want this inside the loop to continuous be asked this prompt until it is broken with Quit or cancel\r\n let userTextInput = prompt(` Enter: Low / Medium / High : for how you are feeling ${userName} on today OR Enter Q to stop.`);\r\n //This is where we are setting this conditional for what ever string we are entering\r\n // because on line 90 we \r\n if (userTextInput === 'Low' || userTextInput === 'low') {\r\n // console.log(userTextInput); \r\n confidenceLevel = false;\r\n alert(` I'm sorry you feel Low today ${userName} ! `)\r\n\r\n }\r\n else if (userTextInput === 'Medium' || userTextInput === 'medium') {\r\n // console.log(userTextInput);\r\n confidenceLevel = false;\r\n alert(` Okay, you're doing Medium on today ${userName} ! `)\r\n }\r\n else if (userTextInput === 'High' || userTextInput === 'high') {\r\n // console.log(userTextInput);\r\n confidenceLevel = false;\r\n alert(` Awesome , way to feel High today ${userName} ! `)\r\n }\r\n //I want this loop broken when entering Q\r\n //we have to change the userTextInput boolean to fasle to break the loop from true\r\n else if (userTextInput === 'Q' || userTextInput === \"Quit\" || userTextInput === \"quit\" || userTextInput === \"q\") {\r\n console.log(userTextInput);\r\n // console.log('You Quit Your Entry');\r\n prompt(`You Quit Your Entry Attempt ${userName}, are you sure about this? `);\r\n confidenceLevel = false;\r\n }\r\n // If none of the booleans are met, we will get this back in console\r\n else {\r\n prompt(`Error ${userName}, Try AGain`);\r\n console.log(`Reached an Error ${userName}, Try again`);\r\n\r\n }\r\n return userTextInput;\r\n }\r\n\r\n}", "function continueShopping(){\n\n\tinquirer.prompt({\n\n\t\ttype: \"confirm\",\n\t\tname: \"confirm\",\n\t\tmessage: \"Would you like to continue shopping?\"\n\n \t\t}).then(function(answer){\n\n \t\t\tif (answer.confirm === true){\n\n \t\t\tstart();\n\n \t\t}else if(answer.confirm === false){\n\n \t\t\tconsole.log(\"Thank you for shopping\");\n \t\t}\n\t\t});\t\n}", "function initPrompt() {\n inquirer.prompt([{\n type: \"list\",\n message: \"Make a Selection:\",\n name: \"choice\",\n choices: [\n \"View All Departments?\",\n \"View All Roles?\",\n \"View all Employees\",\n \"View Employees by Manager\",\n \"View Employees by Department\",\n \"View Department Budget\",\n \"Add Department?\",\n \"Add Role?\",\n \"Add Employee?\",\n \"Update an Employee's Role?\",\n \"Update an Employee's Manager?\",\n \"Delete Function\",\n \"Exit Application\"\n ]\n }]).then(function (event) {\n switch (event.choice) {\n case \"View All Departments?\":\n viewAllDepartments();\n break;\n\n case \"View All Roles?\":\n viewAllRoles();\n break;\n\n case \"View all Employees\":\n viewAllEmployees();\n break;\n\n case \"View Department Budget\":\n viewDepartmentBudget();\n break;\n\n case \"View Employees by Manager\":\n viewEmployeesByManager();\n break;\n\n case \"View Employees by Department\":\n viewEmployeesByDepartment();\n break;\n\n case \"Add Department?\":\n addDepartment();\n break;\n\n case \"Add Role?\":\n addRole();\n break;\n\n case \"Add Employee?\":\n addEmployee();\n break;\n\n case \"Update an Employee Role?\":\n updateEmployeeRole();\n break;\n\n case \"Update an Employee's Manager?\":\n updateEmployeeManager();\n break;\n\n case \"Delete Function\":\n deleteFunction();\n break;\n\n case \"Exit Application\":\n process.exit();\n }\n })\n}", "function askSports() {\n var sports = prompt(questionsArr[0]).toLowerCase();\n if (sports === 'y' || sports === 'yes') {\n userPoints += 1;\n alertPrefixString = 'Correct! ';\n console.log('The user answered question 1 correctly');\n } else {\n alertPrefixString = 'Sorry! ';\n console.log('The user answered question 1 incorrectly');\n }\n var sportsAlert = alert(alertPrefixString + responsesArr[0]);\n askLikesBacon();\n}", "function initialPrompts() {\n userChoice = window.alert(\n \"Before generating your password, you must select some criteria for your password. Click ok to follow on to the next set of instructions.\"\n );\n userChoice = window.alert(\n \"In the upcoming pop-up, type what set of criteria you may want for your password. The options you may select are: 'capital: for capital letters; special: for special characters; number: for numbers in your password. Click ok to proceed to the typing prompt.'\"\n );\n userChoice = window.prompt(\n \"Type your criteria\",\n \"Capital; Number; Special\"\n );\n /* Converts users input to upper case to minimize input mistakes */\n userChoice = userChoice.toUpperCase();\n /* Prints out what the user has selected in the console for developer to check their choice! Helps to see if code is operational. */\n console.log(\n \"The user has selected \" +\n userChoice +\n \" as their criteria. End of initialPrompts function\"\n );\n\n if (!userChoice) {\n return;\n }\n\n selectCriteria();\n }", "function firstPrompt() {\n inquirer\n .prompt([\n { name: \"item\",\n type: \"input\",\n message: \"\\n What is the Id of the product you want to buy? \",\n validate: function (value) \n {\n if (isNaN(value) === false) \n {\n return true;\n }\n return false;\n }\n },\n {\n name: \"quantity\",\n type: \"input\",\n message: \"\\n How many would you like to buy? \",\n validate: function (value) \n {\n if (isNaN(value) === false)\n {\n return true;\n }\n return false;\n }\n }])\n .then(function (answer) \n { // Query db to confirm that the given item ID exists in the desired quantity\n var queryStr = 'SELECT item_id FROM products WHERE item_id=?';\n\n connection.query(queryStr, [item_id = answer.item], function (err, res) {\n if (err) throw err;\n\n // If the user has selected an invalid item ID, data attay will be empty\n // console.log('data = ' + JSON.stringify(data));\n if (res.length === 0) {\n console.log('ERROR: Invalid Item ID. Please select a valid Item ID.');\n firstPrompt();\n } else {\n var query = \"SELECT price, stock_quantity FROM products WHERE item_id= ? Limit 1\";\n connection.query(query, [answer.item], function (err, res) {\n if (err) { console.log(err) };\n\n if (res[0].stock_quantity >= answer.quantity) {\n console.log(\"Good news your order is in stock!\");\n // console.log(res[0].price);\n console.log(\"All right, your total cost is \" + res[0].price * answer.quantity + \"!\");\n connection.query(\"UPDATE products SET stock_quantity = stock_quantity-\" + answer.quantity + \" WHERE item_id = \" + answer.item);\n shopAgain();\n }\n else {\n console.log(\"We only have \" + res[0].stock_quantity + \" in our stock! \")\n shopAgain();\n\n };\n });\n }\n })\n });\n\n // to continue shopping or exit\n function shopAgain() {\n inquirer\n .prompt({\n name: \"action\",\n type: \"list\",\n message: \"\\n Whould you like to buy something else?\",\n choices: [\n \"Yes\",\n \"No\"\n ]\n })\n .then(function (answer2) {\n switch (answer2.action) {\n case \"Yes\":\n firstPrompt();\n break;\n case \"No\":\n connection.end();\n break;\n }\n });\n }\n}", "function addEmployeePrompt(roles, managers){\n // We get an array of manager objects and an array of role objects\n\n console.clear();\n const mChoice=[];\n const rChoice=[];\n for(m of managers){\n let test={};\n test.value=m.id;\n test.name=m.first_name+\" \"+m.last_name+\", Manager of \"+m.name,\n mChoice.push(test);\n }\n for(r of roles){\n let test={};\n test.value=r.ID;\n test.name=r.Position+\", \"+r.Department+\" Department\",\n rChoice.push(test);\n } \n mChoice.push({name:\"No manager assigned\", value:0});\n rChoice.push({name:\"No role assigned\", value:0});\n inquirer.prompt([\n {\n message:\"Employee first name: \",\n name:\"firstName\",\n type:\"input\",\n validate:function(value){if(value.length>0)return true; else return \"Please enter a string.\"}\n }, \n {\n message:\"Employee Last name: \",\n name:\"lastName\",\n type:\"input\",\n validate:function(value){if(value.length>0)return true; else return \"Please enter a string.\";}\n }, \n {\n message:\"Employee role: \",\n name:\"roleChoice\",\n type:\"list\",\n choices:rChoice\n }, \n {\n message:\"Employee manager: \",\n name:\"managerChoice\",\n type:\"list\",\n choices:mChoice\n }\n \n ]).then(\n (answers)=>{\n // if(answers.managerChoice===0) answers.managerChoice=\"\";\n db.addEmployeeInfo(answers, showEmployees);\n }\n )\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 ask(question, cbk, skip) {\r\n if (skip) {\r\n cbk(skip);\r\n return;\r\n }\r\n self.prompt(question, function(answ) {\r\n if (String(answ.answer).trim() === \"\") {\r\n return ask(question, cbk);\r\n } else {\r\n cbk(answ.answer);\r\n }\r\n });\r\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 purchasePrompt() {\n inquirer.prompt([{\n type: \"confirm\",\n name: \"purchase\",\n message: \"Would you like to make a purchase?\",\n default: true\n\n }]).then (function (user) {\n if (user.purchase === true) {\n itemSelect();\n } else {\n console.log(\"\\n =================================================\\n\");\n console.log(\"Thank you for stopping by. Come back and shop with us anytime!\");\n\n connection.end();\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Switch between displaying help and data, updating button to match.
function toggle_info() { toggle_button = document.getElementById("dialogue_toggle"); if(toggle_button.innerHTML=="Show Help"){ show_help(); toggle_button.innerHTML = "Show Data"; } else { toggle_button.innerHTML = "Show Help"; build_data(); } }
[ "function toggleHelp () {\n if (domClass.contains(\"helpUnderlay\", \"help-isVisible\")) {\n closeHelp();\n } else {\n openHelp();\n }\n }", "function processHelpState() {\n oresult.bhelp = true;\n bok = true;\n sstate = '';\n }", "function toggleHelp() {\n // Toggle the helpscreen's visibility\n if($('#helpscreen').is(':hidden')) {\n $('#helpscreen').show();\n } else {\n $('#helpscreen').hide();\n }\n}", "function updateMainButton() {\n if ($('#main-button').data('state') == 'start') {\n $('#main-button').text('START NEW GAME');\n }\n else if ($('#main-button').data('state') == 'drawing') {\n $('#main-button').text('DRAWING READY');\n }\n else if ($('#main-button').data('state') == 'disabled') {\n $('#main-button').text('PLEASE WAIT');\n }\n else if ($('#main-button').data('state') == 'upload-hiscore') {\n $('#main-button').text('UPLOAD HISCORE');\n }\n }", "function displayHelp() {\n\tlet helpText = require('../html/help.html.js');\n\tcreateDialog('show-dialog', 'Help', helpText['helpDialog'], undefined, true);\n}", "function help_OnClick()\n{\n\ntry {\n\tDVDOpt.ActivateHelp();\n}\n\ncatch(e) {\n //e.description = L_ERRORHelp_TEXT;\n\t//HandleError(e);\n\treturn;\n}\n\n}", "function onProceedClick() {\n setDisplayValue('q1');\n updateLastViewed('q1');\n showHideElements();\n}", "launchHelp() {\n TimeHelpUI.launchTimeHelp();\n }", "showButtonPageDescription(text){\n\t\tthis.buttonPageDescription.setInfoText(text);\n\t\tthis.buttonPageDescription.updatesHimself();\n\t\tthis.buttonPageDescription.showInfoText();\n\t}", "function displayContactForm(){\n if(document.querySelector('#contactBtn').querySelector('h2').textContent === 'About'){\n ui.changeMainDisplayState('about');\n } else{\n ui.changeMainDisplayState('contact');\n }\n\n}", "function showhidehelp() {\n\tif (showhelp == false) {\n\t\tshowhelp = true;\n\t\tdocument.getElementById('helpinfo').style.display = 'block';\n\t} else {\n\t\tshowhelp = false;\n\t\tdocument.getElementById('helpinfo').style.display = 'none';\n\t}\n}", "function displayHelpMsg(msg) {\n\tExt.getCmp('helpIframe').el.update(msg);\n}", "static set helpBox(value) {}", "helpMenu() {\n this.r3a1_help_menu.alpha = 1.0;\n this.r3a1_helpOpen = true;\n }", "function updateBtn() {\n if (btn.textContent === \"Turn On\") {\n btn.textContent = \"Turn Off\";\n msg.textContent = \"This is currently on\";\n } else {\n btn.textContent = \"Turn On\";\n msg.textContent = \"This is currently off\";\n }\n}", "function showHideHelp ( section_id, action )\n {\n\t// If the help text is visible and we're either hiding or toggling, then do so.\n\t\n\tif ( visible['help_' + section_id] && ( action == undefined || action == \"hide\" ) )\n\t{\n\t setElementSrc('q' + section_id, \"/JavaScripts/img/hidden_help.png\");\n\t hideByClass('help_' + section_id);\n\t}\n\t\n\t// If the help text is invisible and we're showing or toggling, then do so.\n\t\n\telse if ( action == undefined || action == \"show\" )\n\t{\n\t setElementSrc('q' + section_id, \"/JavaScripts/img/visible_help.png\");\n\t showByClass('help_' + section_id);\n\t}\n }", "function toggleAnswers_() {\n\n var btn = this,\n content = this.parentNode.parentNode.getElementsByClassName('slide-choices__content')[0],\n img = this.parentNode.parentNode.getElementsByClassName('slide-choices__image')[0],\n icon = this.getElementsByClassName('slide-choices__action-icon')[0],\n text = this.getElementsByClassName('slide-choices__action-text')[0];\n\n icon.classList.toggle('slide-choices__action-icon--clicked');\n\n switch (btn.dataset.status) {\n case 'image':\n text.textContent = 'Показать результаты';\n img.classList.remove('hide', 'fade__in', 'fade__in--up');\n img.classList.add('fade__out--down');\n content.classList.remove('hide', 'fade__in', 'fade__out--down');\n content.classList.add('fade__in--up');\n btn.dataset.status = 'result';\n break;\n case 'result':\n text.textContent = 'Показать изображение';\n img.classList.remove('hide', 'fade__in', 'fade__out--down');\n img.classList.add('fade__in--up');\n content.classList.remove('hide', 'fade__in', 'fade__out--down');\n content.classList.add('fade__out--down');\n btn.dataset.status = 'image';\n break;\n }\n\n content.classList.toggle('fade__in--up', 'fade__out--down');\n\n }", "clickHelp() {\n return this\n .waitForElementVisible('@helpLink')\n .assert.visible('@helpLink')\n .click('@helpLink');\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Class to manage map chunks. Chunks (at this time) are 50 squares tall by 50 squares wide. Whenever a new chunk is generated that is a neighbor of another existing chunk, it will generate boimepoints for all shared edges, so the map is more seamless
constructor(chunkxpos, chunkypos) { if(typeof chunklist[chunkypos] === 'undefined') { console.log('Generating 1d array...'); chunklist = []; chunklist[chunkypos] = []; } if(typeof chunklist[chunkypos][chunkxpos] === 'undefined') { console.log('Generating 2d array...'); chunklist[chunkypos] = []; } chunklist[chunkypos][chunkxpos] = this; this.map = []; for(let y=0; y<chunksize; y++) { this.map[y] = []; for(let x=0; x<chunksize; x++) { this.map[y][x] = new maptile(this, x, y); } } this.biomepoints = []; // Now check to see if there are any neighboring chunks to use for generating biomepoints // start with the top direction if((typeof chunklist[chunkypos-1] != 'undefined') && (typeof chunklist[chunkypos-1][chunkxpos] != 'undefined')) { // At this point, we can assume that chunklist[y-1][x] is another mapchunk. Run across its bottom edge and generate new biomepoints console.log('New chunk has a northern neighbor'); let sourcechunk = chunklist[chunkypos-1][chunkxpos]; let lastcolormatch = -1; let lastpoint = 0; for(let x=0; x<chunksize; x++) { if(sourcechunk.map[chunksize][x].tile == lastcolormatch) { lastpoint.stretchcount++; // Same color as last square. Expand that point's range }else{ if(lastpoint!=0) { // Finished with this biomepoint - but we need to wrap that one up. lastpoint.x = Math.floor(lastpoint.stretchcount/2); lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}]; } lastpoint = new biomepoint(this, x, 0, sourcechunk.map[chunksize][x].tile); this.biomepoints.push(lastpoint); lastpoint.stretchcount = 1; lastcolormatch = lastpoint.c; } } // We will also need to adjust the last new biomepoint lastpoint.x = Math.floor(lastpoint.stretchcount/2); lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}]; } // now do the bottom direction if((typeof chunklist[chunkypos+1] != 'undefined') && (typeof chunklist[chunkypos+1][chunkxpos] != 'undefined')) { console.log('New chunk has a southern neighbor'); let sourcechunk = chunklist[chunkypos+1][chunkxpos]; let lastcolormatch = -1; let lastpoint = 0; for(let x=0; x<chunksize; x++) { if(sourcechunk.map[0][x].tile == lastcolormatch) { lastpoint.stretchcount++; }else{ if(lastpoint!=0) { // adjust the last point lastpoint.x = Math.floor(lastpoint.stretchcount/2); lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}]; } lastpoint = new biomepoint(this, x, chunksize, sourcechunk.map[0][x].tile); this.biomepoints.push(lastpoint); lastpoint.stretchcount = 1; lastcolormatch = lastpoint.c; } } lastpoint.x = Math.floor(lastpoint.stretchcount/2); lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}]; } // left side... we can assume that chunklist[chunkypos] already exists if(typeof chunklist[chunkypos][chunkxpos-1] != 'undefined') { console.log('New chunk has a western neighbor'); let sourcechunk = chunklist[chunkypos][chunkxpos-1]; let lastcolormatch = -1; let lastpoint = 0; for(let y=0; y<chunksize; y++) { if(sourcechunk.map[y][chunksize].tile == lastcolormatch) { lastpoint.stretchcount++; }else{ if(lastpoint!=0) { lastpoint.y = Math.floor(lastpoint.stretchcount/2); lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}]; } lastpoint = new biomepoint(this, 0, y, sourcechunk.map[y][chunksize].tile); this.biomepoints.push(lastpoint); lastpoint.stretchcount = 1; lastcolormatch = lastpoint.c; } } lastpoint.y = Math.floor(lastpoint.stretchcount/2); lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}]; } // right side if(typeof chunklist[chunkypos][chunkxpos+1] != 'undefined') { console.log('New chunk has an eastern neighbor'); let sourcechunk = chunklist[chunkypos][chunkxpos+1]; let lastcolormatch = -1; let lastpoint = 0; for(let y=0; y<chunksize; y++) { if(sourcechunk.map[y][0].tile == lastcolormatch) { lastpoint.stretchcount++; }else{ if(lastpoint!=0) { lastpoint.y = Math.floor(lastpoint.stretchcount/2); lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}]; } lastpoint = new biomepoint(this, chunksize, y, sourcechunk.map[y][0].tile); this.biomepoints.push(lastpoint); lastpoint.stretchcount = 1; lastcolormatch = lastpoint.c; } } lastpoint.y = Math.floor(lastpoint.stretchcount/2); lastpoint.points = [{"x": lastpoint.x, "y": lastpoint.y}]; } // With all the sides considered, we can now generate points for inside the chunk let count = Math.floor(chunksize * chunksize / mapkinddensity); console.log('We have '+ count +' new points to generate'); for(let i=0; i<count; i++) { this.biomepoints.push(new biomepoint(this, Math.floor(Math.random()*(chunksize-2))+1, Math.floor(Math.random()*(chunksize-2))+1, Math.floor(Math.random()*4)+1)); } // With all our biomepoints generated, we can start filling in our area, until they are all finished. while(this.biomepoints.length>0) { for(let i=0; i<this.biomepoints.length; i++) { //console.log('Processing point '+ i +" of "+ this.biomepoints.length); //console.log(this.biomepoints[i].x); if(this.biomepoints[i].advance()==0) { this.biomepoints.splice(i, 1); // This one has no work left. Remove it i--; // Also, back up the iterator, so we will still see the next one in line } } } }
[ "function BlockMap(gameMapWidth, gameMapHeight, blockSize) {\n if (gameMapWidth === undefined || gameMapHeight === undefined || blockSize === undefined)\n throw new Error('Invalid dimensions for block map');\n\n Object.defineProperties(this,\n {gameMapWidth: MiscUtils.makeConstantDescriptor(gameMapWidth),\n gameMapHeight: MiscUtils.makeConstantDescriptor(gameMapHeight),\n width: MiscUtils.makeConstantDescriptor(Math.floor((gameMapWidth + blockSize - 1) / blockSize)),\n height: MiscUtils.makeConstantDescriptor(Math.floor((gameMapHeight + blockSize - 1)/ blockSize)),\n blockSize: MiscUtils.makeConstantDescriptor(blockSize)});\n\n this.data = [];\n this.clear();\n }", "P2PChunk(size){\n this.numP2P += 1\n this.sizeP2P += size\n }", "getChunksInRange(point1, point2)\n {\n var chunks = [];\n \n for(var x = point1.x, xi = 0; x <= point2.x; x += X_CHUNKS_PER_REGION * TILE_SIZE, xi++) // add 32 each iteration\n {\n var addedIndex = false;\n\n for(var y = point1.y; y <= point2.y; y += Y_CHUNKS_PER_REGION * TILE_SIZE) // same here, 32 per iteration\n {\n var chunk = WORLD.getChunk(x, y);\n if(chunk == null)\n continue;\n \n if(!addedIndex)\n {\n addedIndex = true;\n chunks.push(new Array());\n }\n\n chunks[xi].push(chunk);\n }\n }\n return chunks;\n }", "function updateVisible() {\n var \n u, v, w, chunk, hash;\n \n var pos = Forge.Player.getRegion();\n var new_visible_hash = {};\n var old_visible_array;\n var chunks_to_queue = {};\n var update = false;\n\n // Only update visible if the regions have changed\n if ( lastRegion !== undefined ) {\n if ( pos.distanceTo( lastRegion ) === 0 )\n return;\n }\n \n lastRegion = pos;\n \n\n for ( u = pos.x - radiusX; u <= pos.x + radiusX; u++) {\n\t\t\tfor ( v = pos.y - radiusY; v <= pos.y + radiusY; v++) {\n\t\t\t\tfor ( w = pos.z - radiusZ; w <= pos.z + radiusZ; w++) {\n chunk = chunkCache.load(u, v, w);\n hash = Forge._2.hash3(u, v, w);\n\n if ( !exports.isChunkVisible( hash )) {\n // Chunk is not in cache\n // or we are loading the chunk\n // back into view. Need to\n // retrieve it\n chunks_to_queue[ hash ] = 1;\n update = true;\n } else if( chunk === undefined ) {\n // do nothing\n // if we reach this statement,\n // we are waiting for the chunk to load\n }\n else {\n // Loading chunk from cache\n // save in visible object\n hash = chunk.hash;\n visible.addChild( chunk.mesh );\n }\n\n new_visible_hash[ hash ] = 1;\n }\n }\n }\n \n // Remove old chunks\n for ( u = 0, v = visible.children.length, w = 0; u < v; u++ ) {\n chunk = visible.children[w];\n \n if (new_visible_hash[ chunk.hash ] === undefined ) {\n visible.removeChild( chunk );\n //console.log('removing…');\n //scene.removeChild( chunk );\n } else {\n w++;\n }\n }\n \n // Finish updating new visible hash\n visible_hash = new_visible_hash;\n \n // update chunks\n if ( update ) {\n //console.log(\"queue for update: \" + JSON.stringify(pos));\n Forge.ChunkManager.queueForUpdate( chunks_to_queue, pos );\n }\n \n }", "split() {\n\n\t\tconst min = this.min;\n\t\tconst mid = this.getCenter(c);\n\t\tconst halfSize = this.size * 0.5;\n\n\t\tconst children = this.children = [\n\n\t\t\tnull, null,\n\t\t\tnull, null,\n\t\t\tnull, null,\n\t\t\tnull, null\n\n\t\t];\n\n\t\tlet i, combination;\n\n\t\tfor(i = 0; i < 8; ++i) {\n\n\t\t\tcombination = pattern[i];\n\n\t\t\tchildren[i] = new this.constructor(\n\n\t\t\t\tnew Vector3(\n\t\t\t\t\t(combination[0] === 0) ? min.x : mid.x,\n\t\t\t\t\t(combination[1] === 0) ? min.y : mid.y,\n\t\t\t\t\t(combination[2] === 0) ? min.z : mid.z\n\t\t\t\t),\n\n\t\t\t\thalfSize\n\n\t\t\t);\n\n\t\t}\n\n\t}", "function createMapClones() {\n \t var clonemapfirst = setInterval(function() {\n\t\t\t\t\tif (jQuery('#mapgyver_holder').hasClass(\"mapisready\")) {\n\t\t\t\t\t\tsetTimeout(function() {\n\t\t\t\t\t\t\trecreateMapClones();\n\t\t\t\t\t\t\tfoldMapHandler();\n\t\t\t\t\t\t},300)\n\t\t\t\t\t\tclearInterval(clonemapfirst);\n\t\t\t\t\t}\n\t\t },50)\n}", "SetHeightmap(img) {\n const heightmap = new HeightGenerator(\n new Heightmap(this._params.guiParams.heightmap, img),\n new THREE.Vector2(0, 0), 250, 300);\n\n for (let k in this._chunks) {\n this._chunks[k].chunk._params.heightGenerators.unshift(heightmap);\n this._chunks[k].chunk.Rebuild();\n }\n }", "static initCurChunk() {\n let curPos = Player.local.pos;\n let wg = WorldGrid.getInstance();\n let prevChun = GridProcessor.curChunk;\n GridProcessor.curChunk = wg.chunks.at((+curPos.y + Math.abs(WorldGrid.coordsStart.y)) / wg.size)?.at((+curPos.x + Math.abs(WorldGrid.coordsStart.x)) / wg.size)\n || new Chunk({ x: 1, y: 1 }, { x: 1, y: 1 }, 0, 0);\n if (!prevChun)\n emit('enterChunk', GridProcessor.curChunk.name);\n }", "function splitObjectIntoGrid() {\n\n for (let j = 0; j < obj.numRows; j++) {\n for (let i = 0; i < obj.numCols; i++) {\n\n let moleculeCollection = molecules.filter(molecule =>\n molecule.position.x > (i * colWidth) &&\n molecule.position.x < ((i + 1) * colWidth) &&\n molecule.position.y > j * rowHeight &&\n molecule.position.y < (j + 1) * rowHeight\n ).map(molecule => molecule.index);\n\n checkIntersections(moleculeCollection);\n }\n }\n}", "split () {\n\n const subWidth = this.bounds.width / 2\n const subHeight = this.bounds.height / 2\n const x = this.bounds.x\n const y = this.bounds.y\n\n this.nodes[0] = new QuadTree(this.level+1, new Rectangle(x + subWidth, y, subWidth, subHeight) )\n this.nodes[1] = new QuadTree(this.level+1, new Rectangle(x, y, subWidth, subHeight) )\n this.nodes[2] = new QuadTree(this.level+1, new Rectangle(x, y + subHeight, subWidth, subHeight) )\n this.nodes[3] = new QuadTree(this.level+1, new Rectangle(x + subWidth, y + subHeight, subWidth, subHeight) )\n\n }", "function buildMap() {\n var map = [];\n for(var i=0; i<=20; i++) {\n var row = [];\n for(var j=0; j<=20; j++) {\n row.push(new Tile(i,j));\n }\n map.push(row);\n }\n return map;\n}", "function setupMines(map){\n \n // Amount of mines required\n var mines = map.mines;\n \n // Array of fields to add mines to\n var fields = map.fields;\n \n for (var n = 0; n < mines; n++ ) {\n \n // Generate a random number to turn into a mine\n var random = Math.floor(Math.random() * (map.size )) + 0;\n\n // If can't be marked as a mine find another random number\n if(!markAsMine(map, random)){\n n--;\n }\n }\n}", "split_() {\n let nextLevel = this.level_ + 1;\n let subWidth = Math.round(this.bounds_.width / 2);\n let subHeight = Math.round(this.bounds_.height / 2);\n let x = Math.round(this.bounds_.x);\n let y = Math.round(this.bounds_.y);\n\n //top right node\n this.nodes_[0] = new Quadtree(new Rectangle(\n x + subWidth,\n y,\n subWidth,\n subHeight\n ), this.maxObjects_, this.maxLevel_, nextLevel);\n\n //top left node\n this.nodes_[1] = new Quadtree(new Rectangle(\n x,\n y,\n subWidth,\n subHeight\n ), this.maxObjects_, this.maxLevel_, nextLevel);\n\n //bottom left node\n this.nodes_[2] = new Quadtree(new Rectangle(\n x,\n y + subHeight,\n subWidth,\n subHeight\n ), this.maxObjects_, this.maxLevel_, nextLevel);\n\n //bottom right node\n this.nodes_[3] = new Quadtree(new Rectangle(\n x + subWidth,\n y + subHeight,\n subWidth,\n subHeight\n ), this.maxObjects_, this.maxLevel_, nextLevel);\n\n }", "function gridify() {\n let numDivision = ceil(Math.sqrt(obj.numOfMols));\n let spacing = (width - obj.maxMolSize) / numDivision;\n\n molecules.forEach((molecule, index) => {\n\n let colPos = (index % numDivision) * spacing;\n let rowPos = floor(index / numDivision) * spacing;\n //console.log(`The col pos ${colPos} and the row pos ${rowPos}`);\n molecule.position.x = colPos + obj.maxMolSize;\n molecule.position.y = rowPos + obj.maxMolSize;\n\n });\n}", "* pixelMapper() {\n const width = this.mapWidth[1] - this.mapWidth[0];\n const height = this.mapHeight[1] - this.mapHeight[0];\n const dX = width / (this.canvasWidth - 1);\n const dY = height / (this.canvasHeight - 1);\n for (let y=0, curY=this.mapHeight[0]; y < this.canvasHeight; y++, curY+=dY) {\n for (let x=0, curX=this.mapWidth[0]; x < this.canvasWidth; x++, curX+=dX) {\n yield { x: x, y: y, mapX: curX, mapY: curY };\n }\n }\n }", "buildPipePair() {\n const topHeight = Phaser.Math.RND.between(\n 1,\n globals.tilesTall - globals.pipeGapSize - 1\n );\n const bottomHeight = globals.tilesTall - globals.pipeGapSize - topHeight;\n\n this.buildPipe(topHeight, false);\n this.buildPipe(bottomHeight, true);\n }", "function PuplishMap(){}", "function generateGroundBlocks() {\n \n\t// Go through each one of our grid blocks\n\tfor (var i = 0; i < gridSize; i++) {\n\t for (var j = 0; j < gridSize; j++) {\n\t\t \n\t\t // Check if we have a ground block located on this grid (i, j) position\n\t\t if (isGroundBlock(i, j)) {\n\t\t\t\n\t\t\t // Translate our grid coordinates to the scene (x, z) coordinates\n \n\t\t\t var x = getSceneXCoordinate(i);\n\t\t\t var z = getSceneZCoordinate(j);\n \n\t\t\t // Calculate the total block curb width\n\t\t\t var curbWidth = blockSize - roadWidth;\n \n\t\t\t // Check if we have a building block allocated in on our grid (i, j) coordinates\n\t\t\t if (isBuildingBlock(i, j)) {\n \n\t\t\t\t// Generate the building curb mesh and add it to the scene\n \n\t\t\t\tvar buildingCurbMesh = getBoxMesh(\n\t\t\t\t // Geometry parameters\n\t\t\t\t {\n\t\t\t\t\t width: curbWidth,\n\t\t\t\t\t height: curbHeight,\n\t\t\t\t\t depth: curbWidth\n\t\t\t\t },\n\t\t\t\t // Positional parameters\n\t\t\t\t {\n\t\t\t\t\t x: x,\n\t\t\t\t\t y: curbHeight / 2,\n\t\t\t\t\t z: z\n\t\t\t\t }, // Mesh color\n\t\t\t\t colors.DARK_GREY\n\t\t\t\t);\n \n\t\t\t\tscene.add(buildingCurbMesh);\n \n\t\t\t\t// Generate a building / buildings with a random height parameter and add it / them to the scene:\n \n\t\t\t\tvar buildingHeight = getRandomIntBetween(\n\t\t\t\t minBuildingHeight,\n\t\t\t\t maxBuildingHeight\n\t\t\t\t);\n \n\t\t\t\tvar buildingWidth = curbWidth - blockMargin * 2;\n \n\t\t\t\tbuildingGeometryParameters = {\n\t\t\t\t width: buildingWidth,\n\t\t\t\t height: buildingHeight,\n\t\t\t\t depth: buildingWidth\n\t\t\t\t};\n \n\t\t\t\tbuildingPosition = {\n\t\t\t\t x: x,\n\t\t\t\t z: z\n\t\t\t\t};\n \n\t\t\t\tgenerateBuildingBlock(\n\t\t\t\t buildingGeometryParameters,\n\t\t\t\t buildingPosition,\n\t\t\t\t blockSubdivisions,\n\t\t\t\t []\n\t\t\t\t);\n\t\t\t \n\t\t\t } else {\n\t\t\t \n\t\t\t\t// Otherwise, we don't have a building block, so we use a heuristic approach to deciding whether to\n\t\t\t\t// use the block to either construct a park or parking. If the block is surrounded by less than 5\n\t\t\t\t// buildings, we build a park. Otherwise, we build an empty 'parking' lot / block.\n \n\t\t\t\tnumberOfSurroundingBuildings = getSurroundingBuildingNumber(i, j);\n \n\t\t\t\t// If the building block is surrounded by less than 5 buildings, we allocate it to a park:\n\t\t\t\tif (numberOfSurroundingBuildings < 5) {\n\t\t\t\t \n\t\t\t\t // Generate the green park mesh and add it to the scene:\n \n\t\t\t\t var parkMesh = getBoxMesh(\n\t\t\t\t\t // Geometry parameters\n\t\t\t\t\t {\n\t\t\t\t\t\t width: curbWidth,\n\t\t\t\t\t\t height: curbHeight,\n\t\t\t\t\t\t depth: curbWidth\n\t\t\t\t\t },\n\t\t\t\t\t // Positional parameters\n\t\t\t\t\t {\n\t\t\t\t\t\t x: x,\n\t\t\t\t\t\t y: curbHeight / 2,\n\t\t\t\t\t\t z: z\n\t\t\t\t\t }, // Mesh color\n\t\t\t\t\t colors.GREEN\n\t\t\t\t );\n \n\t\t\t\t scene.add(parkMesh);\n \n\t\t\t\t // Generate the trees to add to our park mesh\n \n\t\t\t\t var buildingWidth = curbWidth - blockMargin * 2;\n \n\t\t\t\t generateTrees(x, z, buildingWidth);\n \n\t\t\t\t} else {\n\t\t\t\t \n\t\t\t\t // Otherwise, we assign the block to hold parking, which is essentially an empty curb we add\n\t\t\t\t // to our scene\n \n\t\t\t\t var parkingMesh = getBoxMesh(\n\t\t\t\t\t // Geometry parameters\n\t\t\t\t\t {\n\t\t\t\t\t\t width: curbWidth,\n\t\t\t\t\t\t height: curbHeight,\n\t\t\t\t\t\t depth: curbWidth\n\t\t\t\t\t },\n\t\t\t\t\t // Positional parameters\n\t\t\t\t\t {\n\t\t\t\t\t\t x: x,\n\t\t\t\t\t\t y: curbHeight / 2,\n\t\t\t\t\t\t z: z\n\t\t\t\t\t }, // Mesh color\n\t\t\t\t\t colors.DARK_GREY\n\t\t\t\t );\n \n\t\t\t\t scene.add(parkingMesh);\n \n\t\t\t\t}\n\t\t\t }\n\t\t }\n\t }\n\t}\n }", "function makeDivMap() {\n\t\tvar $squares = $('#container div');\n\t\tvar divMap = {};\n\t\tvar x = 0;\n\t\tvar y = 0;\n\n\t\t$.each($squares, function(idx, el) {\n\t\t\tdivMap[x+\",\"+y] = $(el);\n\t\t\tx += 1;\n\t\t\tif (x === 20) {\n\t\t\t\tx = 0;\n\t\t\t\ty += 1;\n\t\t\t}\n\t\t});\n\t\treturn divMap;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Records headings and keywords inside rendered page into this.headings and this.keywords respectively
collectHeadingsAndKeywords(pageContent) { this.collectHeadingsAndKeywordsInContent(pageContent, null, false, []); }
[ "collectHeadingsAndKeywords() {\n const $ = cheerio.load(fs.readFileSync(this.pageConfig.resultPath));\n this.collectHeadingsAndKeywordsInContent($(`#${CONTENT_WRAPPER_ID}`).html(), null, false, []);\n }", "collectHeadTags() {\n let tags = {};\n let currentHandlerInfos = this.router.targetState.routerJsState.routeInfos;\n currentHandlerInfos.forEach((handlerInfo) => {\n Object.assign(tags, this._extractHeadTagsFromRoute(handlerInfo.route));\n });\n let tagArray = Object.keys(tags).map((id) => tags[id]);\n this.headData.set('headTags', tagArray);\n }", "handleHeading(){\n this.sliceString();\n this.post.value = this.beg + \"# \" + this.selection + this.end;\n }", "_allHeadings() {\n return Array.from(this.querySelectorAll('howto-accordion-heading'));\n }", "transoformMetadataAndCollectHeaders (metadata) {\n delete metadata.description\n delete metadata.examples\n\n this.filterInheritedMembers(metadata)\n\n this.sortByName(metadata.properties)\n this.sortByName(metadata.methods)\n\n // We need to temporarily disbale the vue router link rule since the rendered markdown\n // will be directly inserted via v-html so Vue components won't work\n const vueRouterLinkRule = this.markdown.renderer.rules.link_open\n this.markdown.renderer.rules.link_open = function (tokens, idx, options, env, self) {\n return self.renderToken(tokens, idx, options)\n }\n metadata.summary = this.renderMarkdown(metadata.summary)\n if (metadata.deprecated) {\n metadata.deprecated.notes = this.renderMarkdown(metadata.deprecated.notes)\n }\n this.splitPropertiesAndConstants(metadata)\n this.hasConstants = metadata.constants.length\n this.transformMembersAndCollectHeaders('properties', metadata)\n this.transformMembersAndCollectHeaders('methods', metadata)\n this.transformMembersAndCollectHeaders('events', metadata)\n this.transformMembersAndCollectHeaders('constants', metadata)\n this.markdown.renderer.rules.link_open = vueRouterLinkRule\n }", "function slabTextHeadlines() {\n $(\".home-quote h1\").slabText({\n // Don't slabtext the headers if the viewport is under 479px\n \"viewportBreakpoint\":300\n });\n }", "function tocSetupHeadingClasses() {\n\n\tfunction getDepth(element, currentDepth=0) {\n\t const elemParent = tocGetParent(element);\n\t if (elemParent) {\n\t\treturn getDepth(elemParent, currentDepth + 1);\n\t } else {\n\t\treturn currentDepth;\n\t }\n\t}\n\n\tfor (const elem of document.querySelectorAll('#table-of-contents ul')) {\n\t const depth = getDepth(elem);\n\t elem.classList.add('toc');\n\t elem.classList.add('toc-depth-' + depth);\n\t elem.setAttribute('data-toc-depth', depth);\n\t}\n }", "_firstHeading() {\n const headings = this._allHeadings();\n return headings[0];\n }", "function setMetaKeywords(keywords) {\r\n\t\t\tif (typeof keywords === 'string') {\r\n\t\t\t\tmetaKeywords = keywords;\r\n\t\t\t} else if(keywords instanceof Array && keywords.length) {\r\n\t\t\t\tif (keywords[0] instanceof Object) {\r\n\t\t\t\t\tvar kws = [];\r\n\t\t\t\t\tkeywords.filter(function(item) {\r\n\t\t\t\t\t\tkws.push(item.title);\r\n\t\t\t\t\t});\r\n\t\t\t\t\tmetaKeywords = kws.join(', ');\r\n\t\t\t\t} else {\r\n\t\t\t\t\tmetaKeywords = keywords.join(', ');\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tmetaKeywords = '';\r\n\t\t\t}\r\n\t\t}", "function preparePage() {\n links = [];\n\n $(\".js-scroll-indicator\").each(function(index, link) {\n prepareIndicator( $(link) );\n });\n }", "function addQueryInfo(data) {\n var pageObject = data.query.pages;\n var htmlSnippets = {};\n Object.keys(pageObject).forEach(function(pageKey) {\n item = createThumbnailObject(pageObject[pageKey]);\n if (item.title == CODES.node1.title) {\n code = 0;\n } else {\n code = 1;\n }\n htmlSnippets[code] = makeHTMLSnippet(code, item.thumbnail);\n addImage(item, CODES['node' + (code + 1)].code);\n imageURLs[code] = {'title': item.title,\n 'thumbnail': item.thumbnail};\n });\n return htmlSnippets;\n}", "extractTitle() {\r\n return this._page.getElementById(\"firstHeading\").innerHTML;\r\n }", "function printDefinition() {\n $(\"#dictionaryDisplay\").removeClass(\"hide\");\n $(\"#dictionaryDisplay\").append(\"<p id='noun'> Noun: \" + noun + \"</p>\");\n $(\"#dictionaryDisplay\").append(\"<p id ='verb'> Verb: \" + verb + \"</p>\");\n $(\"#dictionaryDisplay\").append(\n \"<p id ='adverb'> Adverb: \" + adverb + \"</p>\"\n );\n $(\"#dictionaryDisplay\").append(\n \"<p id ='adjective'> Adjective: \" + adjective + \"</p>\"\n );\n }", "process_rendering_result_headers(arg_rendering_result_headers=[]/*, arg_credentials*/)\n\t{\n\t\tthis.debug('process_rendering_result_headers:rendering headers', arg_rendering_result_headers)\n\t\t\n\t\t// TODO\n\n\t\t// arg_rendering_result_headers.forEach(\n\t\t// \t(header)=>{\n\t\t// \t\tconst has_header = false // TODO\n\t\t// \t\t// const e = document.createElement(header)\n\t\t// \t\t// document.head.appendChild(e)// TODO\n\t\t// \t}\n\t\t// )\n\t}", "function appendHTML(header, data, id, originalData) {\n\tlet section = document.getElementById(\"CaseData\");\n\tlet html = '';\n\tif (section.innerHTML == null) section.innerHTML = html;\n\t\n\tuseAltColor1 = !useAltColor1;\n\tvar sectionBg = (useAltColor1 ? 'altColor1' : 'altColor2');\n\t\n\t// Make sure there is actually some data to add.\n\tif (data == null) {\n\t\tconsole.log('appendHTML is returning early for header', header)\n\t\treturn;\n\t}\n\t\n\t// Add the section to the html.\n\thtml += '<tr class=\\\"' + sectionBg + '\\\"><td colspan=2><h3>' + header + '</h3></td></tr>';\n\t\n\t// Add the data to the html.\n\tfor (let key in data) {\n\t\tlet tagID = id + '/' + key\n\t\tconst label = formatWords(key)\n\t\t\n\t\tlet path = headerToColl[header] + '/' + id + '/' + key;\n\t\tconsole.log('path in appendHTML: ' + path);\n\t\t\n\t\tif (data[key].constructor.name !== \"Object\") {\n\t\t\t// When setting the value of the HTML tag, we wrap the text in\n\t\t\t// single quotes so that multiple words can be displayed.\n\t\t\t// However, the text could have single quotes, so we have to\n\t\t\t// convert them to the appropriate HTML entity.\n\t\t\tconst value = escapeSingleQuotes(data[key]);\n\t\t\t// Add this data to the originalData dictionary.\n\t\t\toriginalData[path] = value;\n\n\t\t\t// skip adding the html for redundant listings of the Case ID\n\t\t\tif ((header == \"Case Overview\") || (label != \"Case ID\"))\n\t\t\t\thtml += \"<tr class=\\\"\" + sectionBg + \"\\\"><td>\" + label + \":</td><td><input id='\" + path + \"' value='\" + value + \"' readonly></input></td></tr>\";\n\t\t} else {\n\t\t\thtml += appendSubHtml(label,data[key],key,path,originalData);\n\t\t}\n\t}\n\tsection.innerHTML += html;\n}", "function createKeywords(warscroll) {\n const allKeywordsInputs = document.querySelectorAll('.keyword-add');\n\n allKeywordsInputs.forEach(item => {\n let keywordName = item.children[0].value;\n\n const newKeyword = new Keyword();\n\n newKeyword.name = keywordName;\n\n warscroll.keywords.push(newKeyword);\n });\n}", "loadMainHeader() {\n // Get site name and description from store\n const siteName = model.getPostBySlug('site-name', 'settings'),\n siteDescription = model.getPostBySlug('site-description', 'settings');\n view.updateSiteName(siteName.content);\n view.updateSiteDescription(siteDescription.content);\n }", "function constructHeaderTbl() {\t\n\tprintHeadInnerTable = '<div class=\"page\"><table cellspacing=\"0\" class=\"printDeviceLogTable ContentTable\" style=\"font-size: 15px;height:45%;min-height:700px;max-height:780px;table-layout: fixed; width: 1100px;\" width=\"100%\">'\n\t\t+'<thead><tr><th rowspan=\"2\" width=\"50px\">Article</th>'\n\t\t+'<th rowspan=\"2\" width=\"5px\"></th>'\n\t\t+'<th rowspan=\"2\" class=\"columnDivider\">Description</th>'\n\t\t+'<th colspan=\"3\" class=\"centerValue columnDivider\">Last Received Details</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">OM</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">SOH</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"80px\">Units to Fill</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"100px\">LTO</th>'\n\t\t+'<th rowspan=\"2\" class=\"lastColumn leftValue\" width=\"140px\">Comment</th>'\n\t\t+'</tr><tr class=\"subHeader\">'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Date</th>'\n\t\t+'<th class=\"centerValue columnDivider\" width=\"50px\">Qty.</th>'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Order</th></tr></thead>';\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\n}", "function constructHeaderTbl1() {\t\n\tprintHeadInnerTable = '<div class=\"page\"><table cellspacing=\"0\" class=\"printDeviceLogTable ContentTable\" style=\"font-size: 15px;height:45%;min-height:580px;max-height:580px;table-layout: fixed; width: 1100px;\" width=\"100%\">'\n\t\t+'<thead><tr><th rowspan=\"2\" width=\"50px\">Article</th>'\n\t\t+'<th rowspan=\"2\" width=\"5px\"></th>'\n\t\t+'<th rowspan=\"2\" class=\"columnDivider\">Description</th>'\n\t\t+'<th colspan=\"3\" class=\"centerValue columnDivider\">Last Received Details</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">OM</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">SOH</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"80px\">Units to Fill</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"100px\">LTO</th>'\n\t\t+'<th rowspan=\"2\" class=\"lastColumn leftValue\" width=\"140px\">Comment</th>'\n\t\t+'</tr><tr class=\"subHeader\">'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Date</th>'\n\t\t+'<th class=\"centerValue columnDivider\" width=\"50px\">Qty.</th>'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Order</th></tr></thead>';\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\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a worker to solve an instance using one metaheuristic
_createWorker(text) { if (typeof Worker === "undefined") { this.view.log("Sorry, your browser does not support workers."); return; } var self = this; this.view.log("Executing algorithm..."); this.webWorker = new Worker("js/GAPSolverWorker.js?v=2"); this.webWorker.postMessage(text); this.webWorker.postMessage(this.algorithm); this.webWorker.onmessage = function (event) { self.solution = event.data; Object.setPrototypeOf(self.solution, GAPSolution.prototype); Object.setPrototypeOf(self.solution.getInstance(), GAPInstance.prototype); self.computing = false; if (self.solution.isFeasible()) { self.view.log("Done: solution has cost " + self.solution.getCost()); self.view.log(self.solution); self._updateViewButtons(self.view, false, true); } else { self.view.log("Sorry, could not find a feasible solution!"); self._updateViewButtons(self.view, false, false); } }; }
[ "addWorker(){\r\n if(this.workerPool.length<FATUS_MAX_WORKER){\r\n let worker = new FatusWorker(this);\r\n this.initWorker(worker);\r\n this.workerPool.push(worker);\r\n console.log(MODULE_NAME + ': new worker created %s',worker.name);\r\n worker.run();\r\n }else{\r\n console.log(MODULE_NAME + ': workerpool full, skip adding');\r\n }\r\n }", "async createWorkers () {\n\n let worker;\n if ( !this.fallback ) {\n\n let workerBlob = new Blob( this.functions.dependencies.code.concat( this.workers.code ), { type: 'application/javascript' } );\n let objectURL = window.URL.createObjectURL( workerBlob );\n for ( let i = 0; i < this.workers.instances.length; i ++ ) {\n\n worker = new TaskWorker( i, objectURL );\n this.workers.instances[ i ] = worker;\n\n }\n\n }\n else {\n\n for ( let i = 0; i < this.workers.instances.length; i ++ ) {\n\n worker = new MockedTaskWorker( i, this.functions.init, this.functions.execute );\n this.workers.instances[ i ] = worker;\n\n }\n\n }\n\n }", "initWorker(worker) {\r\n worker.setRetryTime(FATUS_EQ_RETRY_TIME);\r\n worker.setMaxAttempts(FATUS_WRK_RETRY_ATTEMP);\r\n worker.setStackProtection(FATUS_WRK_STACK_TRSHLD);\r\n worker.setReservationTime(FATUS_JOB_RESERV_TIME);\r\n worker.setMaxFails(FATUS_MAX_FAIL);\r\n }", "addPriorityWorker(){\r\n if(this.priorityWorkerPool.length<10) {\r\n console.log(MODULE_NAME + ': adding priority worker');\r\n let worker = new FatusPriorityWorker(this);\r\n this.initWorker(worker);\r\n worker.setStackProtection(3);\r\n this.priorityWorkerPool.push(worker);\r\n worker.run();\r\n }\r\n }", "function generateWorkers(factoryId, quantity){\n console.log(factoryId);\n var query = new Parse.Query(Factory);\n query.get(factoryId, {\n success: function(factory) {\n var query = new Parse.Query(Worker);\n query.equalTo(\"parent\", factory);\n query.find({\n success: function(results) {\n\n for (var i = 0; i < results.length; i++) {\n worker = results[i];\n\n worker.destroy({\n success: function(deletedWorker) {\n io.emit('deletenode', 'worker_' + deletedWorker.id);\n },\n error: function(myObject, error) {\n // The delete failed.\n // error is a Parse.Error with an error code and message.\n }\n });\n }\n //create workers\n for ( x=0; x<quantity; x++ ){\n value = Math.floor((Math.random() * factory.get(\"max\")) + factory.get(\"min\"));\n createWorker(value, factory);\n }\n\n },\n error: function(error) {\n alert(\"Error: \" + error.code + \" \" + error.message);\n }\n });\n\n },\n error: function(object, error) {\n }\n });\n}", "createWorkers() {\n let me = this,\n config = Neo.clone(NeoConfig, true),\n hash = location.hash,\n key, value;\n\n // remove configs which are not relevant for the workers scope\n delete config.cesiumJsToken;\n\n // pass the initial hash value as Neo.configs\n if (hash) {\n config.hash = {\n hash : DomEvents.parseHash(hash.substr(1)),\n hashString: hash.substr(1)\n };\n }\n\n for ([key, value] of Object.entries(me.workers)) {\n if (key === 'canvas' && !config.useCanvasWorker ||\n key === 'vdom' && !config.useVdomWorker\n ) {\n continue;\n }\n\n try {\n value.worker = me.createWorker(value);\n } catch (e) {\n document.body.innerHTML = e;\n me.stopCommunication = true;\n break;\n }\n\n me.sendMessage(key, {\n action: 'registerNeoConfig',\n data : config\n });\n }\n }", "loadAndSolve(instanceSource, instance, algorithm, algoParams) {\n if (this.computing === true) {\n this.view.log(\"Error! Already computing!\");\n return;\n }\n this._updateViewButtons(this.view, true, false);\n this.instanceSource = instanceSource;\n this.instance = instance;\n this.algorithm = algorithm;\n this.computing = true;\n this.loadInstance(instanceSource, instance, (text) => {\n if (this.computing === false) return; //stop if the user pressed stop before instance was load\n this.view.log(\"Data loaded\");\n if (algorithm !== \"SIMPLEX\")\n this._createWorker(text);\n else this._solveWithSimplex(text);\n \n }, error => {\n this.view.log(error);\n this.computing = false;\n this._updateViewButtons(self.view, false, false);\n });\n }", "function createWebWorker(opts) {\n return webWorker_js_1.createWebWorker(standaloneServices_js_1.StaticServices.modelService.get(), opts);\n }", "setupChefWorker() {\n for (let i = this.chefWorkers.length - 1; i >= 0; i--) {\n this.removeChefWorker(this.chefWorkers[i]);\n }\n\n this.addChefWorker();\n this.setupDishWorker();\n }", "function worker_probe() {\n Object.keys(cluster.workers).forEach(function(id) {\n cluster.workers[id].send(['trans']);\n });\n}", "function createWorker(worker) {\n\t if (typeof worker === 'string') {\n\t return new Worker(worker);\n\t }\n\t else {\n\t var blob = new Blob(['self.onmessage = ', worker.toString()], { type: 'text/javascript' });\n\t var url = URL.createObjectURL(blob);\n\t return new Worker(url);\n\t }\n\t}", "pow(message, targetScore) {\n return __awaiter(this, void 0, void 0, function* () {\n const powRelevantData = message.slice(0, -8);\n const powDigest = iota_js_1$1.Blake2b.sum256(powRelevantData);\n const targetZeros = iota_js_1$1.PowHelper.calculateTargetZeros(message, targetScore);\n return new Promise((resolve, reject) => {\n const chunkSize = BigInt(18446744073709551615) / BigInt(this._numCpus);\n const workers = [];\n let hasFinished = false;\n for (let i = 0; i < this._numCpus; i++) {\n const worker = new worker_threads_1$1.Worker(path_1.default.join(__dirname, \"pow-node.js\"), {\n workerData: { powDigest, targetZeros, startIndex: chunkSize * BigInt(i) }\n });\n workers.push(worker);\n worker.on(\"message\", (msg) => __awaiter(this, void 0, void 0, function* () {\n hasFinished = true;\n for (let j = 0; j < workers.length; j++) {\n yield workers[j].terminate();\n }\n resolve(BigInt(msg));\n }));\n worker.on(\"error\", err => {\n reject(err);\n });\n worker.on(\"exit\", code => {\n if (!hasFinished && code !== 0) {\n reject(new Error(`Worker stopped with exit code ${code}`));\n }\n });\n }\n });\n });\n }", "function roomNeedsWorker(room) {\n if (Game.time % RATE != 0) return;\n\n var controller = room.controller;\n if (!controller || !controller.my || controller.level >= 6) {\n setNeedsWorker(room, false);\n return;\n }\n\n var spawns = room.find(FIND_MY_SPAWNS).length;\n var underConstruction = room.find(FIND_CONSTRUCTION_SITES, {\n filter: (site) => site.structureType == STRUCTURE_SPAWN\n }).length;\n // don't send helpers to rooms without at least a spawn construction site\n if (!underConstruction && !spawns) {\n setNeedsWorker(room, false);\n return;\n }\n // how many creeps from higher leveled rooms are in this room\n var fatCreeps = room.find(FIND_MY_CREEPS, {\n filter: creep => creep.memory.cost > room.energyCapacityAvailable\n });\n setNeedsWorker(room, fatCreeps.length < optimize.getMaxCreeps(room.name));\n}", "function makeRunAdviseJob(adviseLaunchInfo) {\n \n var resourceCredentials = adviseLaunchInfo.resourceCredentials,\n eedURL = adviseLaunchInfo.eedURL,\n eedTicket = adviseLaunchInfo.eedTicket,\n decodeJobXML = htmlUnescape(adviseLaunchInfo.encodedJobXML),\n runInfo = adviseLaunchInfo.runInfo,\n affinity = null;\n \n if(typeof adviseLaunchInfo.stationName !== 'undefined' && adviseLaunchInfo.stationName !== null\n && adviseLaunchInfo.stationName !== ''){\n affinity = adviseLaunchInfo.stationName;\n } else if (typeof adviseLaunchInfo.localStationName !== 'undefined' && adviseLaunchInfo.localStationName !== null\n && adviseLaunchInfo.localStationName !== ''){\n affinity = adviseLaunchInfo.localStationName;\n }\n \n decodeJobXML = unescape(encodeURIComponent(decodeJobXML));\n // Private Secure station takes precedence\n if(adviseLaunchInfo.secureStation) {\n \t// Set the affinity to localHost\n affinity = \"{localhost}\";\n // Set the HasLocalHost value to AppData\n var appDataXML = UTILS.loadXml(decodeJobXML);\n var lHostNode = appDataXML.getElementsByTagName('Application')[0].appendChild(\n \t\tappDataXML.createElement('HasLocalHost'));\n lHostNode.appendChild(appDataXML.createTextNode('true'));\n decodeJobXML = UTILS.xmlToString(appDataXML);\n }\n\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_START_SERVANT'),\n setStationNameToSplash(adviseLaunchInfo));\n \n var proxyServerURL = adviseLaunchInfo.proxyServer;\n if(typeof proxyServerURL === 'undefined' || proxyServerURL === null){\n proxyServerURL = '';\n }\n if(proxyServerURL.indexOf('http') !== 0){\n proxyServerURL = '';\n }\n \n var modelxml = \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\"\n + \"<fiper_Model version=\\\"6.216.0\\\" majorFormat=\\\"1\\\" timestamp=\\\"6/5/14\\\" rootComponentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\"\n + \"<Properties modelId=\\\"6a53ba4c-811e-11e2-ae82-e9ce6b18c519\\\" modelName=\\\"AdviseServant\\\" modelVersion=\\\"6.216.0\\\" />\"\n + \"<Component id=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"AdviseServant\\\" type=\\\"com.dassault_systemes.smacomponent.adviseservant\\\">\";\n\n // client\n modelxml += \"<Variable type=\\\"com.engineous.datatype.String\\\" id=\\\"bb27e8af-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"host\\\" role=\\\"Parameter\\\" structure=\\\"Scalar\\\" mode=\\\"Input\\\" dispName=\\\"host\\\" saveToDB=\\\"true\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\"\n + \"<Value><![CDATA[\"+window.location.protocol+'//'+window.location.host+\"]]></Value>\"\n + \"</Variable>\";\n\n // csrf\n modelxml += \"<Variable type=\\\"com.engineous.datatype.String\\\" id=\\\"bc27e8af-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"token\\\" role=\\\"Parameter\\\" structure=\\\"Scalar\\\" mode=\\\"Input\\\" dispName=\\\"token\\\" saveToDB=\\\"true\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\"\n + \"<Value><![CDATA[\"+adviseLaunchInfo.token+\"]]></Value>\"\n + \"</Variable>\";\n \n \n // if a local station was found or if user chose a station, assign affinity to the AdviseServant component\n if(affinity){\n modelxml = modelxml\n + \"<Variable id=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519:affinities\\\" name=\\\"affinities\\\" role=\\\"Property\\\" structure=\\\"Aggregate\\\" mode=\\\"Local\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\" \n + \"<Variable type=\\\"com.engineous.datatype.String\\\" typeWrittenVersion=\\\"2.0.0\\\" id=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519:Host\\\" name=\\\"Host\\\" role=\\\"Property\\\" structure=\\\"Scalar\\\" mode=\\\"Local\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519:affinities\\\">\"\n + \"<Value>\"+affinity+\"</Value>\"\n + \"</Variable>\"\n + \"</Variable>\";\n }\n \n /**\n * This variable sets tells the servant if the data should be \n * saved and read in Essentials format.\n */\n try {\n \tvar essOn = false;\n \tif (localStorage.getItem('_ESSENTIALS_MODE_ON_') === true) {\n \t\tessOn = true;\t\n \t}\n \tmodelxml += \"<Variable type=\\\"com.engineous.datatype.Bool\\\" id=\\\"be27e8af-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"_ESSENTIALS_MODE_ON_\\\" role=\\\"Parameter\\\" structure=\\\"Scalar\\\" mode=\\\"Input\\\" dispName=\\\"_ESSENTIALS_MODE_ON_\\\" saveToDB=\\\"true\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\"\n\t\t\t+ \"<Value>\" + essOn + \"</Value>\"\n\t\t\t+ \"</Variable>\";\n } catch(ex){}\n \n modelxml = modelxml \n + \"</Component>\"\n + \"<Component id=\\\"6a5a22ed-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"Task1\\\" type=\\\"com.dassault_systemes.sma.adapter.Task\\\">\" + \"</Component>\" + \"</fiper_Model>\";\n \n // sd4: used to be \"/execution/run/workflow\"\n var eedRunUrl = eedURL + '/execution/run';\n \n jQuery.support.cors = true;\n jQuery.ajax({ \n url : eedRunUrl,\n type : \"POST\",\n beforeSend : function(request) {\n request.setRequestHeader(\"EEDTicket\", eedTicket);\n request.setRequestHeader(\"Credentials\", \"\");\n\n \n request.setRequestHeader(\"RunInfo\", runInfo);\n \n\n request.setRequestHeader(\"ApplicationData\", decodeJobXML);\n resourceCredentials = resourceCredentials.trim();\n\n request.setRequestHeader(\"ResourceCredentials\", resourceCredentials);\n },\n data : modelxml,\n contentType : \"text/plain\",\n success : function(returndata, status, xhr) {\n var jobIdTxt = $simjq(returndata).find(\"JobID\").text().trim();\n adviseLaunchInfo.jobID = jobIdTxt;\n \n if(adviseLaunchInfo.secureStation) {\n \n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_NOTIFY_SEC_STATION'));\n \n jQuery.ajax({\n url: adviseLaunchInfo.stationAccess+\"/claim?jobids=\"+jobIdTxt,\n type: \"POST\",\n cache:false,\n success: function (returndata, status, xhr) {\n waitForServantStartup(adviseLaunchInfo);\n },\n error: function(jqXHR, textStatus, errorThrown){\n console.error(textStatus);\n console.error(errorThrown);\n //waitForServantStartup(adviseLaunchInfo);\n\t\t\t\t\t\tshowLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR'));\n\t\t\t\t\t\tadviseGoBack(\n\t\t\t\t\t\t\t\tadviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR') + '<br\\>' + err\n\t\t\t\t\t\t);\n }\n });\n } else {\n waitForServantStartup(adviseLaunchInfo);\n }\n },\n error : function(jqXHR, textStatus, err) {\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR'));\n adviseGoBack(\n adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR') + '<br\\>' + err\n );\n }\n });\n}", "bestFirstSearch(){\n var heapOpen = new SortedList(comparer);\n var heapClosed = new SortedList(comparer);\n heapOpen.add(this.frontier);\n while(heapOpen.getCount() > 0){\n ITERATIONS++;\n var V = heapOpen.popFirst();\n MINPRIORITY = V.priority;\n V.generateStates();\n redraw();\n if(V.hash == 87654321){\n this.endPoint = V;\n break;\n }\n for(var i = 0 ; i < V.children.length; i++){\n V.children[i].priority = V.children[i].manhattanHeuristic() + V.children[i].outOfPlaceTilesHeuristic(); \n if(hasBetter(heapOpen,V.children[i].hash, V.children[i].priority)){\n continue;\n }\n if(hasBetter(heapClosed,V.children[i].hash, V.children[i].priority)){\n continue;\n }\n heapOpen.add(V.children[i]);\n }\n heapClosed.add(V);\n }\n heapOpen.clear();\n heapClosed.clear();\n return this.createSolution(this.endPoint);\n }", "handle() {\n for(let name in Game.creeps) {\n const creep = Game.creeps[name];\n const role = creep.memory.role;\n\n if (creep.memory.isBusy && creep.carry.energy === 0 && !requireNoDefaultEnergy.includes(creep.memory.role)){\n creep.memory.isBusy = false;\n } else if (!creep.memory.isBusy && creep.carry.energy === creep.carryCapacity) {\n creep.memory.isBusy = true;\n creep.memory.current = role;\n }\n\n if(creep.memory.isBusy) {\n if(!roles[creep.memory.current].exec(creep)){\n getFallbackTask(creep);\n }\n } else {\n creep.getEnergy();\n }\n }\n }", "async createSelf (initValues = {}) {\n const selfData = {\n type: initValues.type\n }\n\n // Aggregate data from the IPFS adapter.\n selfData.ipfsId = this.adapters.ipfs.ipfsPeerId\n selfData.ipfsMultiaddrs = this.adapters.ipfs.ipfsMultiaddrs\n\n // Aggregate data from the BCH adapter.\n const bchData = await this.adapters.bch.generateBchId()\n selfData.bchAddr = bchData.cashAddress\n selfData.slpAddr = bchData.slpAddress\n selfData.publicKey = bchData.publicKey\n // selfData.mnemonic = this.adapters.bch.mnemonic\n\n // Generate an OrbitDB for other peers to pass messages to this node.\n selfData.orbit = await this.adapters.orbit.createRcvDb(selfData)\n\n const schemaConfig = {\n ipfsId: selfData.ipfsId,\n type: selfData.type,\n ipfsMultiaddrs: selfData.ipfsMultiaddrs,\n isCircuitRelay: this.isCircuitRelay,\n circuitRelayInfo: this.circuitRelayInfo,\n cashAddress: selfData.bchAddr,\n slpAddress: selfData.slpAddr,\n publicKey: selfData.publicKey,\n orbitdbId: selfData.orbit.id,\n // apiInfo: '',\n announceJsonLd: this.announceJsonLd\n }\n selfData.schema = new Schema(schemaConfig)\n\n // console.log('selfData: ', selfData)\n\n // Create the thisNode entity\n const thisNode = new ThisNodeEntity(selfData)\n this.thisNode = thisNode\n\n // Attach ther useCases (which includes adapters and controllers) to the\n // thisNode entity.\n this.thisNode.useCases = this.useCases\n\n return thisNode\n }", "function getAndHandleJob(i) {\n\n //Get job\n var job = clients[i].getJob(workers[i]);\n myLog(\"Got a job.\", i);\n\n //No job\n if (job.noJob != null) {\n myLog(\"No job for me.\", i);\n backoff(i);\n return;\n }\n\n resetWait(i);\n\n //Skip job\n if(job.skipJob != null) {\n myLog(\"Got a skip job.\", i);\n finishJob(i, job);\n return;\n }\n\n //Unknown job type\n if (job.imageJob == null) {\n throw { error: \"UNEXPECTED_ERROR\", log: \"Unknown job type!\" };\n }\n\n //Image job\n myLog(\"Job type is: image job.\", i);\n\n var imageJob = job.imageJob;\n imageJob.result = new graphicsfuzzserver.ImageJobResult();\n imageJob.result.status = graphicsfuzzserver.JobStatus.UNKNOWN;\n imageJob.result.log = \"WebGL worker default log: Nothing to declare\\n\";\n\n myLog(\"Rendering shader '\" + imageJob.name + \"'.\", i);\n document.getElementById(\"rendered_shader\" + i).value = \"Rendered shader: \" + imageJob.name;\n var shaderPng;\n var uniformsInfo = imageJob.uniformsInfo;\n var vertexShaderSource = imageJob.vertexSource == null ? getStandardVertexShaderSource() : imageJob.vertexSource;\n var fragmentShaderSource = imageJob.fragmentSource;\n\n var vertices = imageJob.points;\n if (vertices == null) {\n vertices = [\n -1.0, -1.0, 0.0,\n 1.0, -1.0, 0.0,\n 1.0, 1.0, 0.0,\n -1.0, -1.0, 0.0,\n -1.0, 1.0, 0.0,\n 1.0, 1.0, 0.0\n ];\n }\n var indices = [];\n for (var x = 0; x < vertices.length / 3; x++) {\n indices.push(x);\n }\n\n var verticesBuffer = gls[i].createBuffer();\n gls[i].bindBuffer(gls[i].ARRAY_BUFFER, verticesBuffer);\n gls[i].bufferData(gls[i].ARRAY_BUFFER, new Float32Array(vertices), gls[i].STATIC_DRAW);\n\n var indicesBuffer = gls[i].createBuffer();\n gls[i].bindBuffer(gls[i].ELEMENT_ARRAY_BUFFER, indicesBuffer);\n gls[i].bufferData(gls[i].ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gls[i].STATIC_DRAW);\n checkGLOK(gls[i]);\n\n\n var res = renderPNG(imageJob, vertexShaderSource, fragmentShaderSource, gls[i], \"opengl-canvas\" + i, verticesBuffer, indicesBuffer, indices.length, JSON.parse(uniformsInfo));\n imageJob.result.timingInfo = res.timingInfo;\n\n //Rendering failed\n if(res.result === null) {\n var status;\n var statusString;\n if (res.error === \"COMPILE_ERROR\") {\n status = graphicsfuzzserver.JobStatus.COMPILE_ERROR;\n statusString = \"COMPILE_ERROR\";\n } else if (res.error === \"LINK_ERROR\") {\n status = graphicsfuzzserver.JobStatus.LINK_ERROR;\n statusString = \"LINK_ERROR\";\n } else if (res.error === \"NONDET\") {\n status = graphicsfuzzserver.JobStatus.NONDET;\n statusString = \"NONDET\";\n } else {\n status = graphicsfuzzserver.JobStatus.UNEXPECTED_ERROR;\n statusString = \"UNEXPECTED_ERROR\";\n }\n myLog(\"Image job status is '\" + statusString + \"'.\", i);\n if (statusString === \"UNEXPECTED_ERROR\") {\n myLog(res.log, i);\n }\n imageJob.result.status = status;\n imageJob.result.log = res.error + \"\\n\" + res.log;\n finishJob(i, job);\n return;\n }\n\n //Rendering successful\n shaderPng = res.result;\n myLog(\"Image job status is 'SUCCESS'.\", i);\n imageJob.result.status = graphicsfuzzserver.JobStatus.SUCCESS;\n imageJob.result.PNG = atob(shaderPng.split(',')[1]);\n\n //Return result\n finishJob(i, job);\n}", "function initClient(i) {\n //Only allows next client to be initialised\n //(i.e. if i clients exist, then client i+1 must be initialised next)\n if (i != clients.length) {\n throw \"Attempted to initialise client \" + i + \" when only \" + clients.length + \" exist.\";\n }\n clients.push(new graphicsfuzzserver.FuzzerServiceClient(protocol));\n workers.push(\"\");\n completedJobs.push(0);\n\n //Check URL for workers\n workers[i] = getArg(\"worker\" + i);\n if (i == 0 && workers[i] == undefined) {\n workers[i] = getArg(\"worker\");\n }\n if (workers[i] == undefined) {\n workers[i] = localStorage.getItem(\"worker\" + i);\n }\n myLog(\"Trying worker '\" + workers[i] + \"'.\", i);\n var getWorkerNameResult = clients[i].getWorkerName(platformInfo, workers[i]);\n if (!getWorkerNameResult.workerName) {\n throw \"Worker name rejected: \" + reverseWorkerNameError[getWorkerNameResult.error];\n }\n workers[i] = getWorkerNameResult.workerName;\n\n localStorage.setItem(\"worker\" + i, workers[i]);\n myLog(\"Worker from server '\" + workers[i] + \"'.\", i);\n\n document.getElementById(\"current_worker\" + i).value = \"Current worker: \" + workers[i];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turns the correction mode on and off.
function setCorrectionMode(correctionModeOn) { scoreBoard.correctionModeOn = correctionModeOn; }
[ "deactivateSpellchecker () {\n this.enabled = false\n this.isProviderAvailable = false\n ipcRenderer.invoke('mt::spellchecker-set-enabled', false)\n }", "function toggleHints(){\r\n\tif (GameStateScript.HintsOn()){\r\n\t\tGameStateScript.setHints(false);\r\n\t}else{\r\n\t\tGameStateScript.setHints(true);\r\n\t}\r\n}", "turnOff() {\n\t\tthis.lightMap.makeDarkness();\n\t}", "function activateDrawMode() {\n \"use strict\";\n inDrawMode = true;\n inEraseMode = !inDrawMode;\n console.log(\"activated DrawMode\");\n}", "function toggle_manual_enab() {\n debug_log(\"Toggling manual enable state.\")\n if(document.fullscreenElement){\n man_enab_f = !man_enab_f\n if(man_enab_f) debug_log(\"Set full-screen zoom enabled.\")\n else debug_log(\"Set full-screen zoom disabled.\")\n } else {\n man_enab_n = !man_enab_n\n if(man_enab_n) debug_log(\"Set non-full-screen zoom enabled.\")\n else debug_log(\"Set non-full-screen zoom disabled.\")\n }\n zoom_on_or_off()\n}", "changePlayerMode() {\n this._inPlayerMode = !this._inPlayerMode\n this.reset()\n }", "function resetSpeech() {\n\t// turn off outgoing\n\tcancelSpeaking()\n\t// turn off incoming\n\tspeechRecStop()\n\t// reset all flags\n\tlistening = false\n\tlisteningError = false\n\tquestionState = \"\"\n\tquestionString = \"\"\n\tresetting = true\n\t// tell Twee we've stopped listening (to turn off animation)\n\ttwee.stoppedListening()\n}", "function reset() {\n\t\t\t$double.find('> *').addClass('off').removeClass('on');\n\t\t}", "function switchOff() {\n stopGame(); \n infoscreen.text('Game is switched off'); \n usedPattern = []; //usedPattern array is empty\n gameSwitchedOn = false; //sets var gameSwitchedOn status to false\n strictMode = false; //strict mode is off\n $('.levelButton').css('background-color', 'lightskyblue'); //all level buttons get the same color\n }", "toggleAudioEq() {\r\n this.setAudioEq(!this.audio.useEq);\r\n }", "controlViaOnOff() {\n console.log(\"entrou ONOFF\")\n this.output = this.getTemp() < this.setpoint ? 1023 : 0;\n this.board.pwmWrite(19 , 0, 25, 10, this.output);\n }", "function resetSpellChecker()\r\n{\r\n\twith(currObj);\r\n\tcurrObj.resetAction();\r\n\t\r\n\tcurrObj.objToCheck.value = \"\";\r\n\tcurrObj.objToCheck.style.display = \"block\";\r\n\tcurrObj.objToCheck.disabled = false;\r\n\t\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\tif(spellingSuggestionsDiv)\r\n\t{\r\n\t\tspellingSuggestionsDiv.parentNode.removeChild(spellingSuggestionsDiv);\r\n\t\tspellingSuggestionsDiv = null;\r\n\t}\r\n\tcurrObj.statusSpan.style.display = \"none\";\r\n\t\r\n}", "function sustainOff() {\n echo = \"regular\";\n console.log('sustain off');\n }", "function setMode(mode){\n\t\tif(mode !== undefined){\n\t\t\tcm.setOption('mode', mode);\n\t\t\tCodeMirror.autoLoadMode(cm, mode);\n\t\t\t/*var script = 'lib/codemirror/mode/'+mode+'/'+mode+'.js';\n\n\t\t\t$.getScript(script, function(data, success) {\n\t\t\t\tif(success) cm.setOption('mode', mode);\n\t\t\t\telse cm.setOption('mode', 'clike');\n\t\t\t});*/\n\t\t}else{\n\t\t\tcm.setOption('mode', 'clike');\n\t\t}\n\t}", "function setMode(newMode) {\r\n bTextMode = newMode;\r\n var cont;\r\n if (bTextMode) {\r\n// show html\r\n cleanHtml();\r\n cleanHtml();\r\n cont= Composition.document.body.innerHTML;\r\n Composition.document.body.innerText=cont;\r\n } else {\r\n cont=Composition.document.body.innerText;\r\n Composition.document.body.innerHTML=cont;\r\n }\r\n Composition.focus();\r\n}", "function setTypingMode(_mode) {\n const mode = _mode.toLowerCase();\n\n switch (mode) {\n case \"words (fixed amount)\":\n // Update ui\n document.querySelector(\"#coding-area\").style.display = \"none\";\n document.querySelector(\"#time-count\").style.display = \"none\";\n document.querySelector(\"#language-selected\").style.display = \"none\";\n document.querySelector(\"#typing-area\").style.display = \"inline\";\n document.querySelector(\"#word-count\").style.display = \"inline\";\n\n // Start typing test\n setText();\n showText();\n\n break;\n\n case \"words (against the clock)\":\n // Update ui\n document.querySelector(\"#coding-area\").style.display = \"none\";\n document.querySelector(\"#word-count\").style.display = \"none\";\n document.querySelector(\"#language-selected\").style.display = \"none\";\n document.querySelector(\"#typing-area\").style.display = \"inline\";\n document.querySelector(\"#time-count\").style.display = \"inline\";\n\n // Start typing test\n setText();\n showText();\n\n break;\n\n case \"code snippets\":\n // Update ui\n document.querySelector(\"#typing-area\").style.display = \"none\";\n document.querySelector(\"#word-count\").style.display = \"none\";\n document.querySelector(\"#time-count\").style.display = \"none\";\n document.querySelector(\"#coding-area\").style.display = \"inline\";\n document.querySelector(\"#language-selected\").style.display = \"inline\";\n\n // Start typing test\n setCodeText();\n showCodeText();\n\n break;\n\n default:\n console.error(`Mode ${mode} is undefined`);\n }\n }", "function guessClearResetButtonsOff() {\n guessButton.disabled = false;\n clearButton.disabled = false;\n resetButton.disabled = false;\n }", "function toggleSnap() {\n if (snapping == 'on') {\n snapping = 'off'\n }\n else {\n snapping = 'on'\n }\n}", "function freeFormOn() {\n console.log('freeform');\n disableRatios();\n document.getElementById('freeform').checked = true;\n jcrop_api.setOptions({ aspectRatio: 0 });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates database entry and moves the old file into the archive.
function updateDbEntryAndMove(sFileNameOld, sFileNameNew, fCallback) { // update database entry var sSql = esc("UPDATE datasets SET file_name = %Q WHERE file_name = %Q;", sFileNameNew, sFileNameOld); postgres.query(sSql, function(oErr, oResult) { if(oErr) {fCallback(oErr);} // move old file to the archive fs.rename( path.join(config.app.dataset_root_path, sFileNameOld), path.join(config.app.dataset_root_path, "A", sFileNameOld), function(oErr) { if(oErr) {fCalllback(oErr);} fCallback(); }); }); }
[ "function updateFileData(data) {\n if (data.field === 'name') {\n data.newObj.path = uploadPath + data.newObj.name + data.file.extension;\n dbSrvc.update(fileCollection, data);\n renameFileToSystem(data.file.path, data.newObj.path);\n } else {\n dbSrvc.update(fileCollection, data);\n }\n }", "function migrateOldData() {\n let dl = u.dataLoc()\n let existing = shell.ls(dl)\n if(shell.error()) {\n shell.echo(`Failed checking data directory for migration: ${dl}`)\n shell.exit(1)\n }\n if(existing.length > 0) return\n\n let old = find_old_data_dir_1()\n if(!old) return\n\n\n shell.echo(`\\n\\nMigrating from: ${old} to: ${dl}`)\n let datalist = [\n '__ssb', 'kb', 'stellar', 'level.db', '.luminate-pw', 'cfg.env',\n ]\n for(let i = 0;i < datalist.length;i++) {\n let from = path.join(old, datalist[i])\n if(shell.test(\"-e\", from)) {\n shell.echo(`Moving: ${from} to: ${dl}`)\n shell.mv(from, dl)\n }\n }\n shell.echo(`Migration of existing data done...\\n\\n`)\n\n\n function find_old_data_dir_1() {\n if(shell.test(\"-d\",'/data')) return '/data'\n let d = path.join(shell.pwd().toString(),'../elife.data')\n if(shell.test(\"-d\",d)) return d\n }\n}", "function idbCatalogUpdate() {\n\tif (!idbSupport) return;\n\tvar os = 'catalog';\n\tvar item = {\n\t\tnpidLocal: notepadIdLocal,\n\t\tnpname: catalog[notepadIdLocal][\"npname\"],\n\t\tnphash: catalog[notepadIdLocal][\"nphash\"],\n\t\tnpdesc: catalog[notepadIdLocal][\"npdesc\"],\n\t\tlastEdit: catalog[notepadIdLocal][\"lastEdit\"],\n\t\tlastOpen: catalog[notepadIdLocal][\"lastOpen\"],\n\t\tsynced: catalog[notepadIdLocal][\"synced\"]\n\t};\n\tvar dbPromise = idb.open(idbDB);\n\treturn dbPromise.then(function(db) {\n\t\tvar tx = db.transaction(os, 'readwrite');\n\t\tvar store = tx.objectStore(os);\n\t\tstore.put(item);\n\t\tdb.close();\n\t\treturn tx.complete;\n\t}).then(function() {\n\t\tconsole.log('Notepad details updated to catalog object store:', item);\n\t\treturn item;\n\t});\n}", "function saveToEntry(userID) {\n\tlet\n\t\tsql = 'INSERT INTO Entries SELECT * FROM CurrentEntries WHERE UserID = ?;',\n\t\tvalues = [userID];\n\tlet {err, result} = execSQL(sql, values);\n\tif (err) return {err: err};\n\n\treturn deleteCurrentEntry(userID);\n}", "archiveEntry() {\n this.props.dispatch({\n type: 'SHOW_ACTIVITY_INDICATOR',\n text: 'Archiving entry...'\n });\n\n this.props.dispatch(archiveEntry(this.props.entry, this.props.auth.token));\n this.dismiss();\n }", "function idbNoteUpdate(whichTar) {\n\tif (!idbSupport) return;\n\tvar os = notepadIdLocal;\n\tif (whichTar == \"all\") {\n\t\tvar thisTarget;\n\t\tvar items = [];\n\t\tfor (let n in notepads[os]) {\n\t\t\tthisTarget = { \"idLocal\": Number(n) };\n\t\t\titems.push($.extend({}, thisTarget, notepads[os][n]));\n\t\t}\n\t} else {\n\t\tvar thisTarget = { \"idLocal\": whichTar };\n\t\tvar item = $.extend({}, thisTarget, notepads[os][whichTar]);\n\t}\n\tvar dbPromise = idb.open(idbDB);\n\treturn dbPromise.then(function(db) {\n\t\tvar tx = db.transaction(os, 'readwrite');\n\t\tvar store = tx.objectStore(os);\n\t\tif (whichTar == \"all\") {\n\t\t\titems.forEach(function(item) { store.put(item); });\n\t\t} else {\n\t\t\tstore.put(item);\n\t\t}\n\t\tdb.close();\n\t\treturn tx.complete;\n\t}).then(function() {\n\t\tif (whichTar == \"all\") {\n\t\t\tconsole.log('All notes in object store \"'+ os +'\" updated:', items);\n\t\t\treturn items;\n\t\t} else {\n\t\t\tconsole.log('Note '+ whichTar +' in object store \"'+ os +'\" updated:', item);\n\t\t\treturn item;\n\t\t}\n\t});\n}", "replaceEntry (state, args) {\n const cache = state.cache[args.property]\n const turn = state.turns[cache.turn]\n let position\n\n turn.forEach(function (entry, index) {\n if (entry.entryId == cache.entryId) {\n position = index\n }\n })\n\n turn.splice(position, 1, args.entry)\n }", "function upgradeDB(db) {\n cal.ASSERT(db, \"Database has not been opened!\", true);\n if (!db.tableExists(\"cal_calendar_schema_version\")) {\n cal.LOG(\"Storage: Creating tables from scratch\");\n beginTransaction(db);\n try {\n executeSimpleSQL(db, getAllSql());\n setDbVersionAndCommit(db, DB_SCHEMA_VERSION);\n } catch (e) {\n reportErrorAndRollback(db, e);\n }\n } else {\n let version = getVersion(db);\n if (version < DB_SCHEMA_VERSION) {\n // First, create a backup\n backupDB(db, version);\n\n // Then start the latest upgrader\n cal.LOG(\"Storage: Preparing to upgrade v\" + version +\n \" to v\" + DB_SCHEMA_VERSION);\n upgrade[\"v\" + DB_SCHEMA_VERSION](db, version);\n } else if (version > DB_SCHEMA_VERSION) {\n throw Components.interfaces.calIErrors.STORAGE_UNKNOWN_SCHEMA_ERROR;\n }\n }\n\n ensureUpdatedTimezones(db);\n}", "function _prepDatabaseVersion()\n {\n //set a new version of the database. A random number will\n //do fine here 9,999,999 times out of 10,000,000\n version = Math.random()*10000000\n version -= version % 1\n \n //watch the menus folder. If it changes,\n //reload the menus, and update the version\n fs.watch(menusFolder, function()\n {\n _loadVenders()\n version++\n })\n }", "rollback() {\n while (this._installedFiles.length > 0) {\n let move = this._installedFiles.pop();\n if (move.isMoveTo) {\n move.newFile.moveTo(move.oldDir.parent, move.oldDir.leafName);\n } else if (move.newFile.isDirectory() && !move.newFile.isSymlink()) {\n let oldDir = getFile(move.oldFile.leafName, move.oldFile.parent);\n oldDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);\n } else if (!move.oldFile) {\n // No old file means this was a copied file\n move.newFile.remove(true);\n } else {\n move.newFile.moveTo(move.oldFile.parent, null);\n }\n }\n\n while (this._createdDirs.length > 0)\n recursiveRemove(this._createdDirs.pop());\n }", "addArchiveHeaderImage(uid, archiveId, file) {\n sa.archiveDocumentDbRef(uid, archiveId).update({\n headerImage: file.name\n });\n\n sa.archiveStorageRef(uid, archiveId, file.name)\n .put(file)\n .then(() => {\n console.log(\"Uploaded a blob or file!\");\n });\n }", "process() {\n var dbActivities = await(this.getDbActivities_()),\n uniqueSpheres = this.getUniqueSpheresFromActivities_(dbActivities),\n dbSpheres = await(this.createDbSpheres_(uniqueSpheres)),\n updatedActivities =\n await(this.updateActivities_(dbActivities, dbSpheres));\n\n this.archiveActivities_(updatedActivities);\n this.archiveSpheres_(dbSpheres);\n }", "function setDbVersionAndCommit(db, version) {\n executeSimpleSQL(db, \"DELETE FROM cal_calendar_schema_version;\" +\n \"INSERT INTO cal_calendar_schema_version \" +\n \"(version) VALUES (\" + version + \")\");\n if (db && db.transactionInProgress) {\n commitTransaction(db);\n }\n}", "update ( data ) {\n this.store.update(data);\n }", "function backupDb(mode='copy') {\n // Backup old database\n if (fs.existsSync(config.dbpath)) {\n if (mode == 'copy') {\n fs.copyFile(config.dbpath, `./db/til-${Date.now()}.db`, (err) => { \n if (err) { \n console.log(\"Error Found:\", err); \n }\n });\n } else if (mode == 'rename') {\n fs.renameSync(config.dbpath, `./db/til-${Date.now()}.db`); \n }\n }\n}", "async setBookingFile(event) {\n if (!(bookingTempStore.bookingFile === 'booking/' + event.target.id)) {\n bookingTempStore.bookingFile = 'booking/' + event.target.id;\n bookingTempStore.bookingFileHasChanged = true;\n bookingTempStore.save();\n }\n }", "function editNotesRecord(recordId,editedTDchange,c) {\n\tconsole.log('In function editNotesRecord. recordId = '+ recordId);\nlet noteId = Number(recordId);\n//let editedDate = dateSelect.value;\nconsole.log('noteId = ' + noteId + '. editedTDchange = ' + editedTDchange);\n//noteId = 3. editedDate = 1\nlet transaction = db.transaction([objectStoreName], 'readwrite');\n\nlet objectStore = transaction.objectStore(objectStoreName);\n\nlet request = objectStore.get(noteId);\n//Date:Jan29 DataError: Failed to execute 'get' on 'IDBObjectStore': The parameter is not a valid key.\n//var request = objectStore.get();noteId = 3 and this was deleted in this dB. Have to parse tableArray[i][c] to get the date\nrequest.onerror = function(event) {\n // Handle errors!\n console.log(\"edit failed\");\n};//end request.o error\nrequest.onsuccess = function(event) {\n\t//original note in data variable\n\tvar data = event.target.result;\n\t//create the tools for doing the edit\n\tconsole.log('Will edit item # ' + data.id + '. data.title = ' + data.title + ' ' + data.created + ' , ' + data.body);\n\t//reference editTitle input this works\n\t//changed data.title = editedTDchange to data.title = noteId + '> ' + editedTDchange NO DON'T HAVE data.title is just the title, not id\nif(c===0) {data.title = editedTDchange}\nconsole.log('data.title now = ' + data.title);\nif (c===1) {data.created = editedTDchange}\nif (c===2) {data.body = editedTDchange}\nif (c===3) {data.xtraField = editedTDchange}\n\n\nvar requestUpdate = objectStore.put(data);\n//};//end request.onsuccess ?might have to move to end of function?\n requestUpdate.onerror = function(event) {\n // Do something with the error\n\t editBanner.textContent = 'Whoops! ERROR! Transaction now inactive!'\n };\n requestUpdate.onsuccess = function(event) {\n // Success - the data is updated!\n\t console.log(\"The record is updated!\");\n\t };\n\t \n };//end request.onsuccess ?might have to move to end of function?\n }//end function editNotesDate(i,c) ", "function editEntry(ENTRY){\n // making entry the variable that represents the entry id which includes amount, name,type\n let entry = ENTRY_LIST[ENTRY.id];\n // if the entry type is an input, we are going to update the item name and cost in the input section\n if (entry.type == \"inputs\"){\n itemName.value = entry.title;\n itemCost.value = entry.amount;\n }\n // run the delete entry function again so you can delete the previous entry before you add a new edited entry\n deleteEntry(ENTRY);\n }", "function writeToDB(comic, db) {\n const dbpath = `./database/${db}.database.json`\n const fd = fs.openSync(dbpath, 'rs+')\n const database = fd ? JSON.parse(fs.readFileSync(fd).toString()) : `{}`\n const dbLength = Object.keys(database).length\n if (!database[comic.title]) {\n database[comic.title] = {position: `${dbLength + 1}`, link: comic.link, cover: comic.cover}\n fs.writeFileSync(dbpath, JSON.stringify(database))\n }\n\n return dbLength + 1\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the prefab being used by this pool.
function GetPrefab() : GameObject { return prefab; }
[ "function getPool(name='_default'){\n // pool exists ?\n if (name in _pools){\n return _pools[name];\n }else{\n throw new Error('Unknown pool <' + name + '> requested');\n }\n}", "function getParticleFromPool() {\n for (var i = 0, l = particles.length; i < l; i++) {\n if (!particles[i].attract) return particles[i];\n }\n return false;\n}", "function getSelectedTab(tabs) {\n const childId = window.location.hash.split(\"=\")[1];\n return tabs.find(tab => tab.get(\"actor\").includes(childId));\n}", "function get_selected_piece()\n{\n\tvar index = editor_menu.selectedIndex;\n\treturn piece_set[index];\n}", "get placement() {\n return this.skeleton.placement;\n }", "get task () {\n return this._mem.work === undefined ? null : this._mem.work.task;\n }", "getCachedFindBar(aTab = this.selectedTab) {\n return aTab._findBar;\n }", "function pickSpawnTile() {\n var tilePicked = false;\n var cx;\n var cy;\n while (!tilePicked) {\n var proposedX = Phaser.Math.Between(0, 99);\n var proposedY = Phaser.Math.Between(0, 99);\n if (m.getTileAt(proposedX, proposedY).index in GLOBALS.PLACEMENT_TILES) {\n tilePicked = true;\n cx = proposedX * 16;\n cy = proposedY * 16;\n }\n }\n return {\n x: cx,\n y: cy\n };\n}", "get rank(): string {\n if (!this.cachedRank) {\n this.cachedRank = Config.cardRanks[this.id % Config.cardRanks.length];\n }\n\n return this.cachedRank;\n }", "cramp() {\n return styles[cramp[this.id]];\n }", "function getActiveTool() {\n\t\t\treturn getToolByName($toolbox.find('.active').data('tool'));\n\t\t}", "_getTabIndex() {\n if (this.disabled) {\n return -1;\n }\n return this.useActiveDescendant || !this.listKeyManager.activeItem ? this.enabledTabIndex : -1;\n }", "function getActiveItem()/*:Component*/ {\n com.coremedia.ui.data.dependencies.DependencyTracker.dependOnObservable(this, 'activeItem');\n\n var cardLayout/*:CardLayout*/ = (AS3.as(this.getLayout(), Ext.layout.container.Card));\n return cardLayout ? cardLayout.getActiveItem() : null;\n }", "get tile()\n\t{\n\t\treturn tileMap[this.y / tileSize][this.x / tileSize];\n\t}", "function getCurrentTabId(callback) {\n chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {\n callback(tabs[0].id);\n });\n}", "get actualBaseTheme() {\n return this.i.z;\n }", "function getCurrentTab(callback) {\n var queryInfo = {\n active: true,\n currentWindow: true\n };\n\n chrome.tabs.query(queryInfo, function(tabs) {\n callback(tabs[0]);\n });\n}", "function getCpuDifficulty(lobby) {\n return getGame(lobby).cpus[0];\n}", "async currentAccount() {\n const accounts = await this.web3.eth.getAccounts()\n const defaultAccount = this.web3.eth.defaultAccount\n return defaultAccount || accounts[0]\n }", "open() {\n if (!this.pool) {\n this.pool = new pg_1.Pool({\n host: this.host,\n port: this.port,\n database: this.database,\n user: this.username,\n password: this.password,\n min: this.minPoolSize,\n max: this.maxPoolSize\n });\n }\n return this.pool;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancels an edit operation, blanking out all input values found in editItem, then switching its display w/ dispItem. Uses cbTbl for traversing the DOM
function cancelEditOp(editItem, dispItem, opt_setid) { switchItem2(editItem, dispItem); var editwrapper = document.getElementById(editItem); var inputElems = cbTbl.findNodes(editwrapper, function (node) { return node.nodeName.toLowerCase() == 'input' && (!node.type || node.type.toLowerCase() != 'hidden') && node.value; }); for (var i = 0; i < inputElems.length; ++i) { var inputElem = inputElems[i]; var newVal = ''; if (inputElem.id) { var origElem = document.getElementById(inputElem.id + '.orig'); newVal = (origElem && origElem.value) ? origElem.value : newVal; } inputElems[i].value = newVal; } set_isset(false, opt_setid); }
[ "function cancelEdit() {\n var currentBurger = $(this).data(\"burger\");\n if (currentBurger) {\n $(this).children().hide();\n $(this).children(\"input.edit\").val(currentBurger.text);\n $(this).children(\"span\").show();\n $(this).children(\"button\").show();\n }\n }", "function cancelEdit() {\n\t\n\tdebug('cancelEdit::Start:editing=:'+editState.editing);\n\t\n\t//careful. removing the tag may trigger the onBlur handler..\n\t\n\tvar aSpan;\n\tvar tmpStart, tmpEnd;\n\tvar parentElem;\n\t\n\tif ((tmpStart = getEditNode()) != null) {\n\t\t//clear this so no additional cancels come in\n\t\tclearInputEventHandlers(tmpStart); \n\t\t\n\t\t//if special edit do this\n\t\tif (editState.editType == SPEAKEREDIT_COMMAND) {\n\t\t\t//remove the input element\n\t\t\tparentElem = tmpStart.parentNode;\n\t\t\tparentElem.removeChild(tmpStart);\n\t\t\t//unhide newspeaker\n\t\t\tparentElem.setAttribute(NEWSPEAKER_ATTR, SHOWSPEAKER_TEXT);\n\t\t\t\n\t\t\tif (editState.editing) {\n\t\t\t\t//clear the \"we are editing\" flag\n\t\t\t\teditState.editing = false;\n\t\t\t\tif (!editState.lockRequestPending) {\n\t\t\t\t\t//send the cancel\n\t\t\t\t\tsendCommand(editState.lowerEditRange, editState.upperEditRange, CANCELLOCK_COMMAND, editState.documentVersion, \"\");\n\t\t\t\t} //else handle in the ajax response function\n\t\t\t} \n\t\t} else if (editState.editType == \"\") {\n\t\t\t\n\t\t\t//get 1st span in edit range\n\t\t\taSpan = tmpStart.nextSibling;\n\t\t\t\n\t\t\t//remove the input element\n\t\t\ttmpStart.parentNode.removeChild(tmpStart);\n\t\t\t\n\t\t\t//get the first element of edit group\n\t\t\tif (aSpan != null) {\n\t\t\t\ttmpStart = aSpan.id;\n\t\t\t\ttmpEnd = tmpStart;\n\t\t\t\t\n\t\t\t\t//\"unset\" editing while keeping track of end of range so can use later\n\t\t\t\twhile (aSpan != null) {\n\t\t\t\t\tif (spanIsMarkedEditing(aSpan)) {\n\t\t\t\t\t\tunsetSpanEditingFlag(aSpan);\n\t\t\t\t\t\tunsetSpanEditingStyle(aSpan);\n\t\t\t\t\t\ttmpEnd = aSpan.id;\n\t\t\t\t\t\taSpan = aSpan.nextSibling;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//we reached end of editing range\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (editState.editing) {\n\t\t\t\t\t//clear the \"we are editing\" flag\n\t\t\t\t\teditState.editing = false;\n\t\t\t\t\tif (!editState.lockRequestPending) {\n\t\t\t\t\t\t//send the cancel\n\t\t\t\t\t\tsendCommand(tmpStart, tmpEnd, CANCELLOCK_COMMAND, editState.documentVersion, \"\");\n\t\t\t\t\t} //else handle in the ajax response function\n\t\t\t\t} else {\n\t\t\t\t\t//no longer editing - which means we sent the \n\t\t\t\t\t//edit already and backend is cancelling the edit. No need to cancel lock at this point.\n\t\t\t\t\tdebug(\"canceEdit:: Already sent edit so no unlock command to send.\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t//clear the \"we are editing\" flag (if editing)\n\t\t\t\teditState.editing = false;\n\t\t\t}\n\t\t}\n\t} else if ((editState.editType == RESTORE_COMMAND) || (editState.editType == SPEAKERDELETE_COMMAND) || (editState.editType == PARADELETE_COMMAND) ) {\n\t\t//remove the dialog box and restore\n\t\tremoveDialog1();\n\t\t\n\t\tif (editState.editing) {\n\t\t\t//clear the \"we are editing\" flag\n\t\t\teditState.editing = false;\n\t\t\tif (!editState.lockRequestPending) {\n\t\t\t\t//send the cancel\n\t\t\t\tsendCommand(editState.lowerEditRange, editState.upperEditRange, CANCELLOCK_COMMAND, editState.documentVersion, \"\");\n\t\t\t} //else handle in the ajax response function\n\t\t} \n\t} else {\n\t\tdebug(\"cancelEdit:: NO EDIT in progress.\");\n\t}\n\tdebug(\"cancelEdit::done\");\n}", "revert() {\n this.innerHTML = this.__canceledEdits;\n }", "function editItemOff(event) {\n var input = $(this);\n var span = input.siblings(\"span\");\n\n input.hide();\n span.text(input.val());\n console.log(\"Edited value\" + input.val());\n span.show();\n}", "function editElement(event){\n\t\t\t\t\tclickedItem.innerHTML = textBox.value;\n\t\t\t\t}", "function cancelEquipItem(itemIndex) {\r\n player.items[itemIndex][\"eq\"] = false;\r\n player.equipments[player.items[itemIndex].part] = null;\r\n calculateEquipmentStat();\r\n rebuildItemTable(player.items, controller.itemTableOffset, controller.itemTableLimit);\r\n}", "function handleEditItem() {\n $('.js-shopping-list').on('input', '.js-shopping-item', function(event) {\n let itemIndex = getItemIndexFromElement(event.currentTarget); //assigning the index of the the editted item to itemIndex\n let updatedItem = STORE.items[itemIndex];\n updatedItem.name = event.currentTarget.innerHTML;\n $(event.currentTarget).blur(renderShoppingList())\n //renderShoppingList();\n });\n}", "function callEdit(index) {\r\r\n $(\"#btnSubmitData\").attr(\"indexToEdit\", index);\r\r\n $(\"#btnSubmitData\").val(\"Edit\");\r\r\n if ($(\"#btnSubmitData\").hasClass(\"ui-btn-hidden\")) {\r\r\n $(\"#btnSubmitData\").button(\"refresh\");\r\r\n }\r\r\n}", "clearEditForm() {\n let editTitle = document.getElementById('editTitle'),\n wysiwyg = h.getEditorWysiwyg();\n\n // Set the edit fields blank\n editTitle.value = '';\n editContent.value = '';\n // Remove the wysiwyg editor\n if (!_.isNull(wysiwyg)) {\n wysiwyg.remove();\n }\n }", "function on_edit_button_click(){\n\t\tif ($(this).text()=='Edit'){\n\t\t\t$(\"#middle\").find(\"button.edit\").text('Edit')\n\t\t\t\t.siblings('span').hide()\n\t\t\t\t.siblings('span.value').show();\n\n\t\t\t$(this).siblings('span').show()\n\t\t \t\t\t .siblings('span.value').hide();\n\t\t\t$(this).text('Cancel');\n\t\t} else {\n\t\t\t$(this).siblings('span').hide().siblings('span.value').show();\n\t\t\t$(this).text('Edit');\n\t\t}\n}", "function f_resetAll(){\n fdoc.find('.spEdit').removeAttr('contenteditable').removeClass('spEdit');\n fdoc.find('.targetOutline').removeAttr('contenteditable').removeClass('targetOutline');\n fdoc.find('#ipkMenu').hide();\n fdoc.find('.ipkMenuCopyAnime').removeClass('ipkMenuCopyAnime');\n $('.sp-show-edit-only-place').css('opacity','0.2');\n f_resetHiddenBox();\n }", "cancelModification() {\n this.input.value = this.getFormula();\n }", "function _editTextBlockCancel ( /*[Object] event*/ e ) {\n\t\te.preventDefault();\n\t\tcloseEditTextBar();\n\t\tcnv.discardActiveObject();\n\t\treturn false;\n\t}", "function startEditOp(editItem, dispItem, opt_setid) {\r\n switchItem2(dispItem, editItem);\r\n set_isset(true, opt_setid);\r\n}", "toggleEdit() {\n const { inputValue, value } = this.state;\n \n if (inputValue && (inputValue !== value)) {\n const { updateContactOption, item } = this.props;\n \n this.setState(({editing}) => ({\n editing: !editing,\n value: inputValue\n }), () => {\n updateContactOption({ type: item.type, value: inputValue }); \n });\n } else {\n this.setState(({editing}) => ({\n editing: !editing\n }));\n }\n }", "function cancelNewProm(){\n $('#editprom').remove();\n // If there are no proms, this would show the placeholder again\n // If there are proms, placeholder would be removed -> no effect\n $('#prom-placeholder').show();\n }", "function DoEditSCWorkItem_clicked(newitemid) {\n ModalWorkItem = new C_WorkLog(null);\n ModalNewWorkItem = newitemid === -1;\n if (newitemid !== -1) {\n ModalWorkItem = BackendHelper.FindWorkItem(newitemid);\n }\n else {\n ModalWorkItem.UserId = OurUser.id;\n ModalWorkItem.Date = C_YMD.Now();\n }\n\n // build a dropdown of users to select from\n let vol = BackendHelper.FindAllVolunteers();\n vol.sort(function (a, b) {\n return a.Name.localeCompare(b.Name);\n });\n\n let usersChoices = [];\n vol.forEach(function (u) {\n let c = { \"text\": u.Name, \"item\" : u.id.toString() };\n usersChoices.push(c);\n });\n\n let userselitem = ModalWorkItem.UserId.toString();\n\n let usersOptions = {\n \"choices\": usersChoices,\n \"selitem\" : userselitem,\n \"dropdownid\" : \"vitasa_dropdown_users\",\n \"buttonid\" : \"vitasa_button_selectuser\"\n };\n usersDropDown = new C_DropdownHelper(usersOptions); // this must be in the global space\n usersDropDown.SetHelper(\"usersDropDown\");\n usersDropDown.CreateDropdown();\n\n BackendHelper.Filter.CalendarDate = ModalWorkItem.Date;\n $('#vitasa_scvolhours_edit_date_i')[0].value = ModalWorkItem.Date.toStringFormat(\"mmm dd, yyyy\");\n $('#vitasa_workitem_hours')[0].value = ModalWorkItem.Hours.toString();\n $('#vitasa_modal_scvolhours_sitename')[0].innerText = OurSite.Name;\n $('#vitasa_modal_title').innerText = \"Work Item\";\n\n DrawSCVolHoursCalendar();\n\n $('#vitasa_modal_scworkitem').modal({});\n\n BackendHelper.SaveFilter()\n .catch(function (error) {\n console.log(error);\n })\n}", "function menuEditClick() {\n Data.Edit.Open = !Data.Edit.Open;\n setEditMenuPosition();\n\n if (Data.Edit.Open) {\n if (Data.Edit.LastMode)\n Data.Edit.Mode = Data.Edit.LastMode;\n } else {\n Data.Edit.LastMode = Data.Edit.Mode;\n Data.Edit.Mode = EditModes.Off;\n }\n updateMenu();\n\n if (Data.Edit.Open && Data.Controls.Open) {\n Data.Controls.Open = false;\n setControlsPosition();\n }\n}", "cleanUpDetailForm(detailEditor) {\n detailEditor.html('');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates days based on seconds.
function calculateDays(seconds) { return Math.floor(seconds / 3600 / 24); }
[ "function getDaysPassed() {\n const oneDayInMilliseconds = 24*60*60*1000; // hours*minutes*seconds*milliseconds\n let firstDateUTC = lastSyncDateInGolfIslandTime;\n let currentDate = new Date();\n let diffDays = Math.floor(Math.abs((firstDateUTC.getTime() - currentDate.getTime())/(oneDayInMilliseconds)));\n return diffDays;\n}", "function SecsToDHMS() {\n\t\t\tDaysLeft = \t\tMath.floor ( OnlySecondsLeft / 86400 );\n\t\t\tHoursLeft = \tMath.floor ( ( OnlySecondsLeft % 86400 ) / 3600);\n\t\t\tMinutesLeft =\tMath.floor ( ( ( OnlySecondsLeft % 86400 ) % 3600 ) / 60);\n\t\t\tSecondsLeft = \tMath.floor ( ( ( ( OnlySecondsLeft % 86400 ) % 3600 ) % 60 ) % 60);\n\t\t}", "addDays(days) {\n this.addSeconds(days * 24 * 60 * 60);\n }", "function countdown() {\n let saleStarts = 'May 30, 2020 00:00:00';\n let startDate = new Date();\n let endDate = new Date(saleStarts);\n\n let startTime = startDate.getTime();\n let endTime = endDate.getTime();\n\n let timeRemaining = endTime - startTime;\n\n let seconds = Math.floor(timeRemaining / 1000);\n let minutes = Math.floor(seconds / 60);\n let hours = Math.floor(minutes / 60);\n let days = Math.floor(hours / 24);\n\n days = Math.floor(days % 30.44);\n hours = hours % 24;\n minutes %= 60;\n seconds %= 60;\n\n days = (days < 10) ? '0' + days : days;\n hours = (hours < 10) ? '0' + hours : hours;\n minutes = (minutes < 10) ? '0' + minutes : minutes;\n seconds = (seconds < 10) ? '0' + seconds : seconds;\n\n document.getElementById('days').innerHTML = days + ' :';\n document.getElementById('hours').innerHTML = hours + ' :';\n document.getElementById('minutes').innerHTML = minutes + ' :';\n document.getElementById('seconds').innerHTML = seconds;\n\n setTimeout(countdown, 1000);\n}", "function calculateHours(seconds) {\n return Math.floor(seconds / 3600) % 24;\n}", "function calculate_days_left(start_date, end_date){\n const seconds_left = extract_date(end_date) - extract_date(start_date);\n return Math.round(seconds_left / 1000 / 60 / 60 / 24);\n}", "function daydif(cd1,cd2)\n{\n var d1 = new Date(cd2str(cd1));\n var d2 = new Date(cd2str(cd2));\n var dtms = d2.getTime() - d1.getTime();\n return toint(dtms / (3600 * 1000 * 24));\n}", "function countdown(secs) {\n const pad = t => (t < 10 ? '0' + t : t);\n return `${Math.floor(secs / 60 / 60 / 24)}d ${pad(\n Math.floor(secs / 60 / 60) % 24\n )}h ${pad(Math.floor(secs / 60) % 60)}m`;\n}", "function sec() {\n var now = new Date();\n var start = new Date(2020,0,1);\n var dif = now.getTime() - start.getTime();\n \n var Seconds_from_T1_to_T2 = dif / 1000;\n var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);\n document.write(\"On reference date \"+ now +\" <br>\"+ Seconds_Between_Dates +\" seconds had passed since begining of 2020\");\n}", "function CalculateDaysFromFirstImage () {\n var todaysDate = new Date();\n var firstImageDate = new Date('1996', '06', '16');\n var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds\n // (First Date - Second Date) / (one day)\n var dateDifference = Math.round(Math.abs((firstImageDate.getTime() - todaysDate.getTime()) / (oneDay)));\n return dateDifference;\n}", "function CalculateDaysFromFirstImage() {\n var todaysDate = new Date();\n var firstImageDate = new Date('1996', '06', '16');\n var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds\n // (First Date - Second Date) / (one day)\n var dateDifference = Math.round(Math.abs((firstImageDate.getTime() - todaysDate.getTime()) / (oneDay)));\n return dateDifference;\n}", "function convertToSecs(minutes, seconds) {\r\r\n return minutes * 60 + seconds * 1;\r\r\n}", "function diffInDays(a, b) {\r\n const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());\r\n const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());\r\n\r\n return Math.floor((utc2 - utc1) / _MS_PER_DAY);\r\n}", "static calculateDuration (duration) {\n let seconds = duration * 15\n let days = Math.floor(seconds / (3600 * 24))\n seconds -= days * 3600 * 24\n let hrs = Math.floor(seconds / 3600)\n seconds -= hrs * 3600\n let mnts = Math.floor(seconds / 60)\n seconds -= mnts * 60\n const response = days + ' days, ' + hrs + ' Hrs, ' + mnts + ' Minutes, ' + seconds + ' Seconds'\n return response\n }", "function updateMillisecondsPerDay() {\n var inputValue = document.getElementById('millisecondsPerDay').value,\n info = document.getElementById('millisecondsPerDayInfo'),\n millisecondsPerDay = parseInt(inputValue, 10),\n secondsPerDay = millisecondsPerDay / 1000,\n html = '1 Earth day = ';\n\n if (secondsPerDay < 1) {\n html += millisecondsPerDay + ' milliseconds';\n }\n else {\n html += (secondsPerDay + ' ') + (secondsPerDay > 1 ? 'seconds' : 'second');\n }\n\n info.innerHTML = html;\n }", "async function getDaysLeft(planId, startDate) {\n \n let currentDate = new Date();\n let result = await getPlanDetailsFromPlanId(planId);\n console.log(\"result \", result);\n let validity = result.validity;\n var Difference_In_Time = currentDate.getTime() - startDate.getTime();\n // To calculate the no. of days between two dates\n var totalDaysused = Difference_In_Time / (1000 * 3600 * 24);\n console.log(\"toal day\" , totalDaysused);\n\n //let totalDaysused = currentDate - startDate\n let totalDaysLeft = validity - totalDaysused.toFixed(0);\n return totalDaysLeft;\n}", "calcTime() {\n const numIng = this.ingredients.length;\n const periods = Math.ceil(numIng/3);\n this.time = periods * 15;\n }", "function dayDiff(dtLeft, dtRight, incrementAtMidnight) {\n if (incrementAtMidnight === void 0) { incrementAtMidnight = false; }\n var daysDiff = (dtLeft.getTime() - dtRight.getTime()) / DateConstants.MILLIS_PER_DAY;\n var dateDiff = (incrementAtMidnight ? Math.floor(daysDiff) : Math.round(daysDiff)); // TODO this does not handle leap years or non-gregorian calendar days\n return dateDiff;\n }", "static convertSecondsToDigitalClock(seconds, trim = false, removeDecimals = false) {\n var milliseconds = seconds * 1000;\n var time = \"\";\n var curNumber = 0;\n // Convert into hours\n while (milliseconds >= 3600000) {\n curNumber++;\n milliseconds -= 3600000;\n }\n if (curNumber < 10) {\n time += \"0\" + (curNumber) + \":\";\n }\n else {\n time += curNumber + \":\";\n }\n curNumber = 0;\n // Convert into minutes\n while (milliseconds >= 60000) {\n curNumber++;\n milliseconds -= 60000;\n }\n if (curNumber < 10) {\n time += \"0\" + (curNumber) + \":\";\n }\n else {\n time += curNumber + \":\";\n }\n curNumber = 0;\n // Convert into seconds\n while (milliseconds >= 1000) {\n curNumber++;\n milliseconds -= 1000;\n }\n if (curNumber < 10) {\n time += \"0\" + (curNumber);\n }\n else {\n time += curNumber;\n }\n curNumber = 0;\n // Use rest as decimal\n if (!removeDecimals) {\n milliseconds = Math.round(milliseconds);\n if (milliseconds >= 100) {\n time += \".\" + milliseconds;\n }\n else if (milliseconds >= 10) {\n time += \".0\" + milliseconds;\n }\n else if (milliseconds < 10) {\n time += \".00\" + milliseconds;\n }\n }\n while (trim == true && time.startsWith(\"00:\")) {\n time = time.substring(3);\n }\n if (trim == true && time.endsWith(\".000\")) {\n time = time.substring(0, time.length - 4);\n }\n return time;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes the Bixi JSON string retrieved and parses it to place the Bixi pins on the map
function LoadBixiePins(data) { $.each(data.stationBeanList, function(index, value) { var pin = generatePinTemplate(value, "Bixie"); pin.extras = value; Microsoft.Maps.Events.addHandler(pin, 'click', displayBixieModal); map.entities.push(pin); }); }
[ "loadFromJSON (digimonObject) {\n\t\t//let digimonObject = JSON.parse(digimonJSON);\n\n\t\tfor (let property in digimonObject) {\n\t\t\tthis[property] = digimonObject[property];\n\t\t}\n\t\t\n\t\tDigimonData.extraMovementDiscount(this.qualityFlags['movementDiscount'], this.stageIndex >= ChampionIndex);\n\n\t\t/*if (Number.isInteger(digimonObject.burstIndex)) {\n\t\t\tthis.burstIndex = 0;\n\t\t\tfor (let i = 0; i < digimonObject.burstIndex; i++) {\n\t\t\t\tthis.modifyBurstIndex(true);\n\t\t\t}\n\t\t}*/\n\t}", "function getBaiduData(location) {\n jQuery.ajax({\n url: 'https://api.map.baidu.com/place/v2/search',\n type: 'GET',\n dataType: 'jsonp',\n data: {\n // query for only attractions\n 'q': '旅游景点',\n 'scope': '2',\n // sort by raiting\n 'filter': 'sort_name:好评|sort_rule:0',\n 'region': location,\n 'output': 'json',\n // ak = acess key\n 'ak': 'oXmLrK2EjxWxZm1qab51f1fmRLm4I4kF',\n // max page_size is 20\n 'page_size': '20',\n 'page_num': '0'\n }\n })\n .done(function(data, textStatus, jqXHR) {\n //store results in locations array\n locations = data.results;\n //create markers for locations returned by Baidu\n createMarkers(locations);\n })\n .fail(function(jqXHR, textStatus, errorThrown) {\n console.log('HTTP Request Failed');\n alert('Baidu search results could not load properly. Please try again in a few minutes.');\n });\n }", "function createCellOnMapFromJSON(cell) {\n\tvar myLatlng = new google.maps.LatLng(cell.latitude, cell.longitude);\n\n\tvar image;\n\tif (cell.techno == \"LTE\") {\n\t\timage = 'img/8_purple.png';\n\t} else if (cell.techno == \"WCDMA\") {\n\t\timage = 'img/8_teal.png';\n\t} else {\n\t\timage = 'img/8_yellow.png';\n\t}\n\n\tvar marker = new google.maps.Marker({\n\t\tposition: myLatlng,\n\t\tmap: map,\n\t\ttitle:cell.cellName,\n\t\ticon: image\n\t});\n\tmarkersArray.push(marker);\n\n\trecordMarker(marker);\n\tcellIndexedByTelecomId[cell.telecomId] = cell;\n\tcellIndexedByName[cell.cellName] = cell;\n}", "function displayBixieModal(pin) {\n savedPin = pin.target;\n var stationInformation = pin.target.extras;\n $(\"#bixieStationID\").text(\"Station ID: \" + stationInformation.id);\n $(\"#bixieStationName\").text(\"Station Name/Address: \" + stationInformation.stationName);\n $(\"#bixieAvailableBikes\").text(stationInformation.availableBikes);\n $(\"#bixieAvailableDocks\").text(stationInformation.availableDocks);\n $(\"#bixieTotalDocks\").text(stationInformation.totalDocks);\n\n $(\"#BixiLat\").val(stationInformation.latitude);\n $(\"#BixiLong\").val(stationInformation.longitude);\n\n $(\"#BixieModal\").modal(\"show\");\n}", "function geoJsonParse(resultArray){\n let results = resultArray.map(function(obj){\n let oneObj = GeoJSON.parse(obj, {Point: ['lat', 'long'], include: ['city']})\n oneObj['properties']= {\n 'id': obj.id, \n 'name': obj.name, \n 'age': obj.age, \n 'gender': obj.gender\n }\n return oneObj\n });\n return results\n}", "function getPointsOfInterest(userZip) {\n\n var mapboxUrl = \"https://api.mapbox.com/geocoding/v5/mapbox.places/\" + userZip + \".json?access_token=pk.eyJ1IjoiYWRhbWJhcnJvbiIsImEiOiJja2d2dm84aW4wMXA0MzBsODltNjZ5ZzFiIn0.W7Kpov0CjgFZQWXRaFlKzg\"\n // fetch coordinates based on zip from map box.\n\n fetch(mapboxUrl).then(function (response) {\n // mapbox API call\n return response.json();\n })\n .then(function (data) {\n var latitude = data.features[0].center[1];\n var longitude = data.features[0].center[0];\n\n // triposo API call\n var triposoUrl = \"https://www.triposo.com/api/20200803/local_highlights.json?latitude=\" + latitude + \"&longitude=\" + longitude + \"&max_distance=3000&poi_fields=all&account=ZCUNOA55&token=8pemze46o1tfvvh58e1tskjo5wegfswp\"\n return fetch(triposoUrl);\n })\n .then(function (response) {\n return response.json();\n })\n .then(function (response) {\n\n // display points of interest\n const pois = response.results[0].pois;\n for (let index = 0; index < pois.length; index++) {\n const poi = pois[index];\n\n const url = poi.content && poi.content.attribution[0] && poi.content.attribution[0].url\n ? poi.content.attribution[0].url\n : \"\";\n const link = url\n ? `<a href=\"${url}\">Visit Website</a>`\n : \"\";\n const imgUrl = poi.images[0]\n ? poi.images[0].source_url\n : \"https://sgl-assets.imgix.net/files/article_hero/how-to-plan-trip-guide-aaa-via-magazine-shutterstock_446918872.jpg?w=1440&h=720&crop=faces,edges\";\n const description = poi.content.sections[0].body\n ? poi.content.sections[0].body\n : \"\";\n\n // template literal\n const poitemplate = `\n <div class=\"card \">\n <div class=\"card-image\">\n <img class=\" responsive-img\" src=\"${imgUrl}\">\n </div>\n <div class=\"card-content\">\n <span class=\"card-title activator grey-text text-darken-4\">${poi.name}<i class=\"material-icons right\">more_vert</i></span>\n <p><a href=\"#\">${link}</a></p>\n </div>\n <div class=\"card-reveal\">\n <span class=\"card-title grey-text text-darken-4\">${poi.name}<i class=\"material-icons right\">close</i></span>\n <p>${description}</p>\n </div>\n </div>\n `;\n document.querySelector(\"#searchResults\").innerHTML += poitemplate\n }\n })\n .catch(function (err) {\n // Modal with error message\n $('.modal').modal(\"open\");\n })\n }", "function proccessResults() {\n // console.log(this);\n var results = JSON.parse(this.responseText);\n if (results.list.length > 0) {\n resetData();\n for (var i = 0; i < results.list.length; i++) {\n geoJSON.features.push(jsonToGeoJson(results.list[i]));\n }\n drawIcons(geoJSON);\n }\n }", "init() {\n this.worldMap.parseMap();\n }", "function setPostal(markerArray) {\n \n markerArray.forEach(function(marker) {\n \n let lat = marker.getPosition().lat();\n \n let lng = marker.getPosition().lng();\n \n \n let url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=';\n url += lat;\n url += ',';\n url += lng;\n url += '&key=AIzaSyA0dTID9kEIw0w2LDUE444_M0Go7YM4apA&result_type=postal_code';\n\n $.ajax({\n url : url,\n dataType: 'json',\n success : function(data){\n marker.postal = data.results[0].address_components[0].short_name;\n \n },\n error: function(request, error) {\n window.alert(\"Request: \" + JSON.stringify(request));\n }\n });\n });\n}", "function addMarkers(map) {\n // create AJAX request\n var xhttp = new XMLHttpRequest();\n\n // define behaviour for a response\n xhttp.onreadystatechange = function() {\n if(this.readyState == 4 && this.status == 200) {\n hotels = JSON.parse(xhttp.responseText);\n for(i=0; i<hotels.length; i++) {\n // convert parts of the hotels address variables and concatenate them\n var address = hotels[i].number + \" \" + hotels[i].street + \", \" + hotels[i].suburb + \", \" + hotels[i].city + \", \" + hotels[i].state + \", \" + hotels[i].country;\n var markerTitle = \"Hotel Name: \" + hotels[i].hotelName + \"\\nPrice: \" + hotels[i].price;\n\n // geocode address variable\n var geocoder = new google.maps.Geocoder();\n geocoder.geocode({\"address\":address}, function(results,status) {\n // if valid location\n if(status = \"OK\") {\n var marker = new google.maps.Marker({\n position: results[0].geometry.location,\n title: markerTitle\n });\n marker.setMap(map)\n }\n });\n }\n } \n }\n\n // initiate connection\n xhttp.open(\"GET\", \"hotels.json\", true);\n\n // send request\n xhttp.send();\n}", "function initializeLatinToBraille() {\n\n\t\tnumberPrefix = languages[braille.language].numberPrefix\n\n\t\tdotMap = languages[braille.language].dotMap\n\t\t\n\t\tif(dotMap == null) {\n\t\t\tthrow new Error('Dot eight map.')\n\t\t}\n\n\t\t// Read in braille description file\n\t\t// latinToBraille.set('a', [1, 2]);\n\t\t// latinToBraille.set('b', [1, 4, 5]);\n\t\tlet brailleJSON = languages[braille.language].latinToBraille\n\t\t\n\t\tfor(let char in brailleJSON) {\n\t\t\tlatinToBraille.set(char, brailleJSON[char])\n\t\t}\n\t}", "jsonParser(photos){\n let farmIds = [];\n let serverIds = [];\n let ids = [];\n let secretIds = [];\n\n photos.forEach(element => {\n farmIds.push(element.farm);\n serverIds.push(element.server);\n ids.push(element.id);\n secretIds.push(element.secret);\n});\n this.imageLinkBuilder(farmIds,serverIds,ids,secretIds);\n }", "function LoadGreenPPins(data) {\n $.each(data.carparks, function(index, value) {\n var pin = generatePinTemplate({ latitude: value.lat, longitude: value.lng }, \"GreenP\");\n pin.extras = value;\n Microsoft.Maps.Events.addHandler(pin, 'click', displayGreenPModal);\n map.entities.push(pin);\n });\n}", "function fetchMarkers(){\n fetch('/markers')\n .then((response) => response.json())\n .then((markers) => {\n markers.forEach((marker,i) => {\n addDisplayMarker(marker.lat, marker.lng, marker.content, marker.landmark, marker.ratings);\n });\n });\n}", "function getIBjson(gdun, callback) {\t\n\n\tvar nineDigitGdun = appendZeros(gdun);\n\n\t// build the URL for the API call \n\tvar url = \"http://pnwreport.bellevuelab.isus.emc.com/api/installs/\" + nineDigitGdun;\t\n\n\t// pull the results from the API call\n\trequest(url, function (error, response, body) {\n\t\tif (error) { \n\t\t\tcallback(err);\t\t\t\n\t\t} else { // install base data was successfully loaded\n\t\t\tcallback(null, body); // this is the callback saying this getIBdata function is complete;\n\t\t}\n\t});\t\t\n}", "updateItineraryAndMapByArray(places){\n let newMarkerPositions = [];\n this.setState({placesForItinerary: places});\n places.map((place) => newMarkerPositions.push(L.latLng(parseFloat(place.latitude), parseFloat(place.longitude))));\n this.setState({markerPositions: newMarkerPositions});\n this.setState({reverseGeocodedMarkerPositions: []});\n }", "function processResponse(str) {\n\tvar data = JSON.parse(str);\n\t\n\t\n\t// We only use this portion of the return from google\n\t// Need to figure out how to tell google to not send us the \n\t// rest of it\n\tvar textAnnotations = data.responses[0].textAnnotations;\n\n\tvar imageTopY = textAnnotations[0].boundingPoly.vertices[0].y;\n\n\tvar imageBottomY = textAnnotations[0].boundingPoly.vertices[2].y;\n\tvar imageLeftX = textAnnotations[0].boundingPoly.vertices[0].x;\n\tvar imageRightX = textAnnotations[0].boundingPoly.vertices[2].x;\n\n\tvar imageWidth = imageRightX - imageLeftX;\n\tvar imageHeight = imageBottomY - imageTopY;\n\n\tvar arrayOfLines = new Array();\n\n\t// Skip the first block (was for the entire image)\n\t// Make the Image();\n\tvar previousMidY;\n\tvar bufferWidth;\n\tvar currLine = new Array(); // Array of Block objects, not a Line object\n\tvar lineList = new Array();\n\n\tfor (var i = 1; i < textAnnotations.length; i++) {\n\t\tlet unprocessedBlock = textAnnotations[i];\n\t\tlet currString = unprocessedBlock.description;\n\t\tlet blockTopY = unprocessedBlock.boundingPoly.vertices[0].y;\n\t\tlet blockLeftX = unprocessedBlock.boundingPoly.vertices[0].x;\n\t\tlet blockRightX = unprocessedBlock.boundingPoly.vertices[2].x;\n\t\tlet blockBottomY = unprocessedBlock.boundingPoly.vertices[2].y;\n\n\t\t// Averages\n\t\tlet blockMidX = (blockLeftX + blockRightX) / 2;\n\t\tlet blockMidY = (blockTopY + blockBottomY) / 2;\n\n\t\t// W&H\n\t\tlet blockWidth = blockRightX - blockLeftX;\n\t\tlet blockHeight = blockBottomY - blockTopY;\n\n\t\tvar block = new Block(currString, blockMidX, blockMidY, blockTopY, blockBottomY, blockLeftX, blockRightX, blockWidth, blockHeight);\n\n\t\t// Just starting out\n\t\tif (previousMidY == undefined) {\n\t\t\tcurrLine.push(block);\n\t\t\tpreviousMidY = blockMidY;\n\t\t\tbufferWidth = blockHeight / 2;\n\t\t} else {\n\t\t\t// Add current Line to lineList if that Line is finished, and make a new Line with the current Block\n\t\t\t// Otherwise, add the current Block to the lineList\n\t\t\t// console.log(currString + \" => block.MidY: \" + blockMidY + \", previousMidY: \" + previousMidY + \", bufferWidth: \" + bufferWidth);\n\t\t\tif (blockMidY < previousMidY + bufferWidth && blockMidY > previousMidY - bufferWidth ) {\n\t\t\t\t// line is not finished\n\t\t\t\tcurrLine.push(block);\n\t\t\t\tpreviousMidY = blockMidY;\n\t\t\t\tbufferWidth = blockHeight / 2;\n\t\t\t} else {\n\t\t\t\t// Line is finished\n\n\t\t\t\tvar completedLine = new Line(sortBlocksBasedOnX(currLine));\n\t\t\t\tlineList.push(completedLine);\n\t\t\t\tcurrLine = new Array();\n\t\t\t\tcurrLine.push(block);\n\t\t\t\tpreviousMidY = blockMidY;\n\t\t\t\tbufferWidth = blockHeight / 2;\n\t\t\t}\n\t\t}\n\t}\n\n\tvar image = new Image(lineList, imageTopY, imageBottomY, imageLeftX, imageRightX);\n\tconsole.log(\"############ MADE IMAGE ###############\");\n\tconsole.log(image.toString());\n\tconsole.log(\"############ DONE IMAGE ###############\");\n\n\tvar returnString = processImageByStoreName(image);\n\n\tdebug(\"Done processing\");\n\tconsole.log(returnString);\n}", "function getData() {\n const key = \"at_zWpPAQSJjFm9Ze0kLLUQ3J1F9OJWT\";\n const ip = input.value;\n fetch(`https://geo.ipify.org/api/v1?apiKey=${key}&ipAddress=${ip}`)\n .then((res) => res.json())\n .then((data) => {\n getLocation(data)\n getMap(data.location.lat, data.location.lng)\n })\n .catch((err) => console.log(err));\n}", "function color_map(json) {\n\tdata_points = json.points;\n\tfor(var i = 0; i < data_points.length; i++) {\n\t\tvar data_point = data_points[i];\n\t\tvar country = data_point[0];\n\t\tvar country_id = get_country_id(country);\n\t\t\n\t\tif(!country_id) {\n\t\t\tconsole.log(\"No id found for: \" + country);\n\t\t} else {\n\t\t\tvar population = Number(data_point[1]);\n\t\t\tvar fill_color = get_fill_color(population);\n\t\t\tchange_color(country_id, fill_color);\n\t\t};\n\t};\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update or create the current fund in infos
async upsertFundInInfos(fund) { const name = 'cgpFund'; const info = await infosDAL.findByName(name); if (info) { await infosDAL.update(info.id, { value: fund, }); } else { await infosDAL.create({ name, value: fund, }); } }
[ "static dynamicIncomeUpdate() {\n let storedIncome = Storage.getIncome()\n let storedExpenses = Storage.getExpenses()\n const incomes = storedIncome\n const expenses = storedExpenses;\n\n updateUI.updateTransaction(incomes, expenses)\n }", "function updateUiData(info){\n const {date , temp , feelings} = info;\n // update the date div \n dateEntry.innerHTML = \"Date: \" + date;\n\n // update the temp div \n tempEntry.innerHTML = \"Temp: \" + temp;\n\n // update the content entry \n content.innerHTML = \"Feelings: \" + feelings ;\n\n}", "async updateEntityInfo(requestData) {\n try{\n const requestUrl = '/api/forge/cost/info';\n const requestBody = {\n 'projectHref': this.projectHref,\n 'costContainerId': this.costContainerId,\n 'costType': this.currentDataType,\n 'requestData': requestData\n };\n return await apiClientAsync( requestUrl, requestBody, 'post');\n }catch(err){\n console.error(err);\n return null;\n }\n }", "function editSelectedFundRow(uniqueRowId) {\n\tvar fundingType = $(\"#\" + uniqueRowId + \" #historyFundRowFundingType\").text();\n\tvar pinNumber = $(\"#\" + uniqueRowId + \" #historyFundRowPin\").text().trim();\n\tvar amount = getFormatedNumber($(\"#\" + uniqueRowId + \" #historyFundRowAmount\").text(), false);\n\teditCashHistoryFundRowId = uniqueRowId;\n\t$(\"#optionsListContainer\").hide(); \t/* Hide select type */\n\t$(\"#cashInfoTxt\").hide();\n\t$(\"#helpCash\").hide();\n\tshowHideAllDeleteButtonOfCash(true); /* Disable all delete buttons */\n\tvar fundingSourceType = fundingType.replace(/[\\s]/g, '');\n\tpinNumber = pinNumber.replace(/[\\s]/g, '');\n\tsetPinNumberInFieldsOnEdit(pinNumber, amount, fundingSourceType);\n\tif(jsonTypeConstant.PRECASH === fundingSourceType) {\n\t\t$(\"#cashPaymentOptionBox1 #cashSelectedFundingSourceImage\").attr(\"src\",\n\t\t\t\tformatMessage(messages[\"checkout.image_fundingSource_URL\"],\tgetImageNameByJsonType(fundingType)));\n\t\t$(\"#cashPaymentOptionBox1\").show();\n\t} else if(jsonTypeConstant.BLACKHAWK == fundingSourceType) {\n\t\t$(\"#cashPaymentOptionBox2 #cashSelectedFundingSourceImage\").attr(\"src\",\n\t\t\t\tformatMessage(messages[\"checkout.image_fundingSource_URL\"], getImageNameByJsonType(fundingType)));\n\t\t$(\"#cashPaymentOptionBox2\").show();\n\t} else if(jsonTypeConstant.INCOMM == fundingSourceType) {\n\t\t$(\"#cashPaymentOptionBox3 #cashSelectedFundingSourceImage\").attr(\"src\",\n\t\t\t\tformatMessage(messages[\"checkout.image_fundingSource_URL\"],\tgetImageNameByJsonType(fundingType)));\n\t\t$(\"#cashPaymentOptionBox3\").show();\n\t}\n\t$(\"#historyFundingSources\").hide(); /* Hide history section */\n\t$(\"#cashSummaryTotalArea\").hide();\n\tclearIntervalApp(submitBtnCreateProfCountdown);\n\tclearIntervalApp(submitBtnAddInfoCountdown);\n\tdeActivateCheckoutPayButton();/* Disable submit button */\n}", "function submitArtInfo(){\n\n if(i == null){\n i = -1;\n }\n i++;\n\n refArtName.child(i).set(artName.value);\n refOwners.child(i).set(owner.value);\n refPricePM.child(i).set(pricePM.value);\n refIncrement.set(i);\n\n}", "static updateFee(pool, feeRate) {\n return makeAdminInstruction(pool, { updateFee: { feeRate } });\n }", "update(newPerson) {\n // condLog(\"Update the Ahnentafel object\", newPerson);\n\n if (newPerson && newPerson._data.Id) {\n this.primaryPerson = newPerson;\n }\n if (this.primaryPerson) {\n // this.PrimaryID = newPerson._data.Id\n this.list = [0, this.primaryPerson._data.Id]; // initialize the Array\n this.listByPerson = new Array(); // initialize the Array\n this.listByPerson[this.primaryPerson._data.Id] = 1; // add the primary person to the list\n\n if (this.primaryPerson._data.Father && this.primaryPerson._data.Father > 0) {\n this.addToAhnenTafel(this.primaryPerson._data.Father, 2);\n }\n if (this.primaryPerson._data.Mother && this.primaryPerson._data.Mother > 0) {\n this.addToAhnenTafel(this.primaryPerson._data.Mother, 3);\n }\n this.listAll(); // sends message to the condLog for validation - this could be commented out and not hurt anything\n }\n }", "function missionDetails(newMission){\n\n\t\thideEdit();\n\t\tshowEdit();\n\n\t\t//create circle with icon if it is given for this misison\n\t\t$('.edit ul.mission-neutral').append($('<li class=\"circle-big\">' + (newMission.icon ? '<img src='+ newMission.icon +'>' : \"\") + '</li>'))\n\n\t\t//creates empty form \n\t\t$('.edit').append(createEmptyForm());\n\n\t\t//if name is given show in the form\n\t\t$('input[name=\"newMissionName\"]').val(newMission.name ? newMission.name : \"\")\n\n\t\t//if points are given (which means it is user mission) show in the form \n\t\tif (newMission.hasOwnProperty('points')){\n\t\t\t$('input[name=\"newMissionPoints\"]').val(newMission.points)\n\t\t\t//for user mission save missionId\n\t\t\t$('.edit li.circle-big').attr('name',newMission.id)\n\t\t\t//for user missions show also days\n\t\t\tnewMission.days.forEach(function(day){\n\t\t\t\t$('input[name=\"newMissionDays\"]').eq(day).trigger('click')\n\t\t\t})\n\n\t\t\t//for user mission show SAVE button\n\t\t\t$('.edit').append($('<button class=\"save\">ZAPISZ ZMIANY</button>'))\n\t\t\t// and FINISH / DELETE button\n\t\t\t$('.edit').append($('<button class=\"left infoFinish\">ZAKOŃCZ</button><button class=\"right infoDelete\">USUŃ</button>'))\n\t\t} else {\n\t\t\t//for NOT user missions show ADD button\n\t\t\t$('.edit').append($('<button class=\"add\">DODAJ</button>'))\n\t\t}\n\t}", "async update ({ params, request, response }) {\n const tarefa = await Tarefa.findOrFail(params.id);\n const dados = request.only([\"descricao\", \"titulo\", \"status\"]);\n \n tarefa.fill({\n id : tarefa.id,\n ...dados\n });\n \n await tarefa.save();\n }", "function updateDebtInterestRate(token, debtID, newInterestRate) {\n try {\n var userData = validateToken(token);\n var userEmail = userData.email;\n var updateQuery = 'UPDATE Debts SET interestRate=?, lastUpdated=CURRENT_TIMESTAMP WHERE email=? AND debtID=?;';\n var parameters = [newInterestRate, userEmail, debtID];\n executeManipulationQuery(updateQuery, parameters);\n return \"Success\";\n }\n catch (err) {\n throw new Error( \"Error modifying debts!\" );\n }\n}", "editCabin(e) {\n\t\t\te.preventDefault();\n\t\n\t\t\tvar self = this;\n\t\t\tvar form = document.getElementById('form');\n\t\t\tvar id = this.props.id;\n\t\t\tvar name = document.getElementById('name').value;\n\t\t\tvar icon = document.getElementById('icon').value;\n\t\t\tvar points = Number(document.getElementById('points').value);\n\t\t\tvar members = document.getElementById('members').value.split(',');\n\t\t\tmembers = members.map(member => member.trim());\n\t\t\tvar data = {\n\t\t\t\tname: name,\n\t\t\t\ticon: icon,\n\t\t\t\tmembers: members,\n\t\t\t\tpoints: points\n\t\t\t};\n\t\t\tHYC.data.cabins.edit(id, data).then(function(res, data){\n \t\t\tself.setState({\n \t\t\t\tmessage: 'Cabin successfully updated',\n \t\t\t\tmessageType: 'success'\n \t\t\t});\n \t\t\tHYC.events.publish('cabinChanged', {});\n \t\t}).catch(function(err){\n \t\t\tself.setState({message: message, messageType: error});\n \t\t});\n\t\t}", "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 }", "async update ({ params, request, response, auth }) {\n const establishment = await Establishment.findOrFail(params.id)\n\n if (establishment.user_id !== auth.user.id) {\n return response.status(401).send({ error: 'Not authorized' })\n }\n\n const data = request.only([\n 'title',\n 'state',\n 'city',\n 'country',\n 'description',\n 'classification',\n 'facebook',\n 'twitter',\n 'instagram',\n 'telephone',\n 'website',\n 'category',\n ])\n\n establishment.merge(data)\n\n await establishment.save()\n\n return establishment\n }", "function editFlightAddAssistant(id, changes) {\n return db(\"flight_info as f\")\n .where({ id })\n .update(changes);\n}", "function editEntry(ENTRY){\n // making entry the variable that represents the entry id which includes amount, name,type\n let entry = ENTRY_LIST[ENTRY.id];\n // if the entry type is an input, we are going to update the item name and cost in the input section\n if (entry.type == \"inputs\"){\n itemName.value = entry.title;\n itemCost.value = entry.amount;\n }\n // run the delete entry function again so you can delete the previous entry before you add a new edited entry\n deleteEntry(ENTRY);\n }", "function saveTransaction(tran, update, errorFunc) {\n // or maybe add a save button for now\n // TODO: return a promise instead of having errorFunc\n for (var key in tran.attrs) {\n if (tran.attrs[key] === null) {\n delete tran.attrs[key];\n }\n }\n if (typeof tran.effective_date == 'object') {\n tran.effective_date = calculate.castDateString(tran.effective_date, $rootScope.settings.shortdate);\n }\n SWBrijj.procm('_ownership.save_transaction',\n JSON.stringify(tran))\n .then(function(new_entries) {\n tran.effective_date = Date.parse(tran.effective_date);\n if (new_entries.length < 1)\n {\n console.log(\"Error: no ledger entries\");\n return;\n }\n // the first item is a fake ledger entry with the correct transaction information\n var transaction = new_entries.splice(0, 1)[0].transaction;\n // splice the existing ledger_entries out of their arrays\n // TODO: I think this logic only makes sense for transactions that aren't splits\n // TODO: check if on a transaction, we're getting back split rows for other transactions\n // if we are, are we handling them correctly?\n var spliced = [];\n for (var new_entry in new_entries)\n {\n if (spliced.indexOf(new_entries[new_entry].transaction) == -1)\n {\n spliced.push(new_entries[new_entry].transaction);\n splice_many_by(captable.ledger_entries, function(el) {\n return el.transaction == new_entries[new_entry].transaction;\n });\n }\n captable.ledger_entries.push(new_entries[new_entry]);\n }\n // check if the transaction is one we already have\n var found = false;\n for (var i in captable.transactions)\n {\n if (captable.transactions[i].transaction == tran.transaction)\n {\n if (tran.transaction === null)\n {\n if ((captable.transactions[i].attrs.investor == tran.attrs.investor) &&\n (captable.transactions[i].attrs.security == tran.attrs.security))\n {//just in case multiple null transactions\n captable.transactions[i].transaction = transaction;\n captable.transactions[i].valid = validateTransaction(tran);\n found = true;\n }\n }\n else\n {\n captable.transactions[i].transaction = transaction;\n captable.transactions[i].valid = validateTransaction(tran);\n found = true;\n }\n }\n }\n tran.transaction = transaction;\n if (!found)\n {\n tran.valid = validateTransaction(tran);\n captable.transactions.push(tran);\n }\n if (update)\n {\n var cells = cellsForLedger(new_entries);\n for (var c in cells)\n {\n updateCell(cells[c]);\n }\n }\n updateDays();\n //captable.ledger_entries.push.apply(captable., new_entries);\n }).except(function(e) {\n console.error(e);\n if (errorFunc)\n {\n errorFunc();\n }\n });\n }", "saveUserInfo(name, about) {\n return fetch(this._baseUrl + \"/users/me\", {\n method: \"PATCH\",\n headers: this._headers,\n body: JSON.stringify({ name: name, about: about }),\n }).then((res) => {\n return this._checkResponse(res);\n });\n }", "function loadCurrentItineraryInfo(){\n console.log('InicioCtr.loadCurrentItineraryInfo');\n //Checks id the DB is already initialized\n debugger;\n // $scope.itinerary =itSalida;\n if( $scope.itinerary != null ){\n console.log('vamos a actualizar el resumen');\n updateSummary();\n\n //Actualiza la pantalla con los datos del scope\n $scope.$apply();\n }else {\n console.log('NO HAY ITINERARIO EN EL SCOPE');\n }\n\n }", "updateInfo(key, newValue) {\n let info = this.props.info;\n info[key] = newValue;\n this.props.updateShipInfo(info);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function gonna return fave in this shape : id > user_id that you're faving fullname > photo > added_at > you_fave > boolean | define if you're faving this profile
function faves({ _doc: {created_at, from: { _id, profile }}}) { return { id: _id, fullname: profile.fullname, photo: profile.photo, added_at: created_at, } }
[ "static filterApptUserData(user) {\n return {\n name: user.name,\n email: user.email,\n phone: user.phone,\n uid: user.uid,\n id: user.id,\n photo: user.photo,\n type: user.type,\n };\n }", "function showOtherUser(){\n removeFollowList();\n removeSearchArea();\n var userId = this.dataset.user; // get the user of the clicked name or image\n showedUser = userId;\n removeWritenFields();\n removeErrorSuccesFields();\n document.getElementById(\"profileSection\").style.display = \"block\";\n document.getElementById(\"messagesSection\").style.display = \"none\";\n hideAllProfileSection();\n document.getElementById(\"showProfile\").style.display = \"block\";\n\n getOtherProfile(userId);\n}", "async function addExtendedInfo (thisUser) {\n if (thisUser.birthday) { // if birthday exists (hasn't been set private and is not empty)\n var birthday = thisUser.birthday\n var cur = new Date()\n thisUser.age = birthdayParser.getAge(birthday, cur) // add age info\n thisUser.zodiac = birthdayParser.getZodiac(birthday) // add zodiac info\n }\n var poster = require('./poster')\n thisUser.cnt_poster = await poster.getPosterCntbyUID(thisUser.uid)\n}", "async updateProfilePicture(id,user, file){\n\n user.profile_img = file;\n return await User.findByIdAndUpdate(id,user,{new: true})\n }", "function currentProfile() {\n return {\n handle: $('#handle').text(),\n email: $('#email').text(),\n keys: [{\n name: 'default',\n signature: $('.signature').first().text()\n }]\n };\n}", "getFavorite(cardId) {\n if(this.user==false)return false;\n for(const card of this.user.savedCards){\n //console.log(card.cardID+\" vs \"+cardId);\n if(card.cardID == cardId)return card.favorited;\n\n }\n return false;\n }", "function get_friends_profile_picture(id, callback){\n var call = '/me?fields=id,friends.uid('+id+').fields(username)';\n call = make_url(call);\n FB.api(url, function(response){\n friend_user_name = response.username;\n\n profile_pic_url = 'https://graph.facebook.com/'+friend_user_name+'/picture';\n //got their usernme\n callback(profile_pic_url);\n });\n}", "function getFriends() {\n var query = \"SELECT uid, name FROM user WHERE uid IN (Select uid2 from friend where uid1 =me())\";\n\n FB.api(\n {\n method: 'fql.query',\n query: query\n },\n function(response) {\n \n console.log(response);\n\n var html = \"\";\n var friend = new Array();\n for (var i=0; i < response.length; i++) {\n console.log(\"There were this many responses \" + response.length + \" and they are \" + response[i]);\n var name = response[i].name;\n var fuid = response[i].uid;\n fbPhoto.insert({username: name, uid: fuid, selected: 0});\n friend[i] = fuid;\n console.log(name + \" is your friend and their id is \" + fuid);\n \n\n \n\n //html += \"<a href='\"+big+\"' target='_blank'><img src='\"+src+\"' /></a>\";\n }\n\n console.log(\"you hit me with ONE \" + fbPhoto.find().count() );\n\n //getLatestPhotos(friend);\n \n\n\n //var container = document.getElementById(\"container\");\n //container.innerHTML = html;\n\n console.log('done');\n\n }\n );\n\n }", "function saveAndPublishUserData(resp) {\n user.name = resp.data.name;\n user.email = resp.data.email;\n user.id = resp.data._id;\n localStorage.setItem('user', JSON.stringify(user)); \n}", "get userProfile() {\n return spPost(ProfileLoaderFactory(this, \"getuserprofile\"));\n }", "function getFacebookUserDetails(access_token, res) {\n\t\tlogger.debug('userapi getFacebookUserDetails started');\n\t\trequest.get('https://graph.facebook.com/me?fields=name,email,gender,age_range,picture,location&access_token=' + access_token, function (error, response, body) {\n\t\t\tif (error) {\n\t\t\t\tlogger.error(error);\n\t\t\t\treturn error;\n\t\t\t}\n\t\t\tif (response.statusCode !== 200) {\n\t\t\t\treturn response.statusCode;\n\t\t\t}\n\t\t\tsaveUser(JSON.parse(body), res);\n\t\t});\n\t\tlogger.debug('userapi getFacebookUserDetails completed');\n\t}", "function getStoredFBProfile() {\n return window.localStorage.getItem(globalValues.facebookUserProfile);\n }", "get ownerUserProfile() {\n return spPost(this.getParent(ProfileLoaderFactory, \"_api/sp.userprofiles.profileloader.getowneruserprofile\"));\n }", "function addProfile(data) {\n let sql = `INSERT INTO \"profile\" (userid, fname, lname) VALUES ('${data.userid}', '${data.fname}','${data.lname}')`;\n return db.query(sql);\n}", "function checkIfProfilePhotoIsShown(){\n if ($scope.selectionPhotoId == $scope.profilePhotoId)\n {$scope.profilePhotoIsShown = true} else\n {$scope.profilePhotoIsShown = false};\n }", "function createProfile(username, password, email, loginType, id, db, done){\n var wallID = (Date.now().toString(36) \n + Math.random().toString(36).substr(2,5))\n .toUpperCase();\n \n bcrypt.hash(password, 8, (err, hash) => {\n if (err) throw err;\n \n var profile = {};\n profile.username = username;\n profile.extID = id;\n profile.loginType = loginType;\n profile.email = email;\n profile.password = hash;\n profile.walls = [{\n wallNum: 1,\n wallID: wallID,\n imageLinks: [],\n lastUpdated: ''\n }];\n \n db.collection('users').insert(profile, (err, result) => {\n if (err) throw err;\n \n if (loginType === \"local\") {\n return done()\n } else {\n db.collection('users').findOne(\n {$and: [{loginType: loginType}, {extID: id}]}, \n (err, user) => {\n if(err) throw err;\n return done(err, user);\n }\n );\n }\n });\n });\n}", "function fillUserProfile() {\n if (!currentUser) return null;\n\n $('#user-profile section')\n .children('#profile-name')\n .append(' ' + currentUser.name);\n\n $('#user-profile section')\n .children('#profile-username')\n .append(' ' + currentUser.username);\n\n const date = convertDate(currentUser.createdAt);\n\n $('#user-profile section')\n .children('#profile-account-date')\n .append(' ' + date);\n }", "saveUserProfile(callback) {\n var url = '/db/users/user/' + this.props.params.user;\n this.profileEdits.user.public = this.state.public === true ? 0 : 1;\n this.profileEdits.user.permission = this.state.permission === true ? 1 : 0;\n console.log(this.profileEdits)\n var data = this.profileEdits;\n data.userInfo = _map(data.userInfo, function(val){return val});\n data.sites = _map(data.sites, function(val){return val});\n RestHandler.Post(url, data, (err, res) => {\n console.log(data);\n if (err) {return err;}\n callback(res);\n });\n }", "saveUserInfo(name, about) {\n return fetch(this._baseUrl + \"/users/me\", {\n method: \"PATCH\",\n headers: this._headers,\n body: JSON.stringify({ name: name, about: about }),\n }).then((res) => {\n return this._checkResponse(res);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load image previews for all uploads.
loadPreviews () { this.files.map(file => { if (!file.previewData && window && window.FileReader && /^image\//.test(file.file.type)) { const reader = new FileReader() reader.onload = e => Object.assign(file, { previewData: e.target.result }) reader.readAsDataURL(file.file) } }) }
[ "function initPreviews()\r\n {\r\n // remove all previous events\r\n removeEventHandlers();\r\n\r\n // attach click events\r\n var $prev = $qtip.find(\".ilPreviewTooltipPrev\");\r\n var $next = $qtip.find(\".ilPreviewTooltipNext\");\r\n var $items = $qtip.find(\".ilPreviewItem\");\r\n var itemCount = $items.length;\r\n\r\n var currentIdx = -1;\r\n var previewSize = self.previewSize + 2; // add 2 because the image has a border\r\n\r\n /**\r\n * Show the preview image at the specified index.\r\n */\r\n function showIndex(index)\r\n {\r\n log(\"Preview.showIndex(): current=%s, idx=%s\", currentIdx, index);\r\n\r\n // same index as before?\r\n if (index == currentIdx)\r\n return;\r\n\r\n log(\"Preview.showIndex(%s)\", index);\r\n\r\n $items.hide();\r\n\r\n $item = $items.eq(index);\r\n var height = $item.children().height();\r\n $item.css(\"margin-top\", ((previewSize - height) / 2) + \"px\");\r\n $item.show();\r\n\r\n // more than one item?\r\n if (itemCount > 1)\r\n {\r\n $tooltip.qtip(\"api\").set(\"content.title\", self.texts.preview + \" \" + (index + 1) + \" / \" + itemCount);\r\n if (index < 1)\r\n $prev.addClass(\"ilPreviewDisabled\");\r\n else\r\n $prev.removeClass(\"ilPreviewDisabled\");\r\n\r\n if (index >= itemCount - 1)\r\n $next.addClass(\"ilPreviewDisabled\");\r\n else\r\n $next.removeClass(\"ilPreviewDisabled\");\r\n }\r\n else\r\n {\r\n $tooltip.qtip(\"api\").set(\"content.title\", self.texts.preview);\r\n }\r\n\r\n currentIdx = index;\r\n }\r\n\r\n /**\r\n * Show the next preview image.\r\n */\r\n function showNext()\r\n {\r\n if (currentIdx < itemCount - 1)\r\n showIndex(currentIdx + 1);\r\n }\r\n\r\n /**\r\n * Show the previous preview image.\r\n */\r\n function showPrevious()\r\n {\r\n if (currentIdx > 0)\r\n showIndex(currentIdx - 1);\r\n }\r\n\r\n /**\r\n * Handles the events when a key was released.\r\n */\r\n function handleKeyUp(e)\r\n {\r\n // key already pressed? only execute once\r\n if (e.type == \"keydown\")\r\n {\r\n if (isKeyPressed)\r\n {\r\n // prevent default if up or down arrow\r\n if (e.which == 38 || e.which == 40)\r\n e.preventDefault();\r\n\r\n return;\r\n }\r\n\r\n isKeyPressed = true;\r\n\r\n // which key was pressed?\r\n switch (e.which)\r\n {\r\n case 38: // up arrow key\r\n e.preventDefault();\r\n showPreviousPreview();\r\n break;\r\n\r\n case 40: // down arrow key\r\n e.preventDefault();\r\n showNextPreview();\r\n break;\r\n }\r\n }\r\n else\r\n {\r\n isKeyPressed = false;\r\n\r\n // which key was pressed?\r\n switch (e.which)\r\n {\r\n case 37: // left arrow key\r\n e.preventDefault();\r\n showPrevious();\r\n break;\r\n\r\n case 39: // right arrow key\r\n e.preventDefault();\r\n showNext();\r\n break;\r\n\r\n case 36: // HOME\r\n e.preventDefault();\r\n showIndex(0);\r\n break;\r\n\r\n case 35: // END\r\n e.preventDefault();\r\n showIndex(itemCount - 1);\r\n break;\r\n\r\n case 27: // ESC\r\n e.preventDefault();\r\n $tooltip.qtip(\"hide\");\r\n hideTooltip();\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Handles the events when the mouse wheel was rotated.\r\n */\r\n function handleMouseWheel(e, delta, deltaX, deltaY)\r\n {\r\n if (deltaY != 0)\r\n {\r\n e.preventDefault();\r\n if (deltaY < 0)\r\n showNext();\r\n else\r\n showPrevious();\r\n }\r\n }\r\n\r\n // more than one item?\r\n if (itemCount > 1)\r\n {\r\n // set number\r\n $items.each(function (index, elem)\r\n {\r\n $(elem).attr(\"data-index\", index);\r\n });\r\n\r\n // click events\r\n $prev.click(showPrevious);\r\n $next.click(showNext);\r\n\r\n $prev.show();\r\n $next.show();\r\n\r\n // attach mouse wheel\r\n // (assign to variable is important that it can be removed later on)\r\n mouseWheelHandler = handleMouseWheel;\r\n $qtip.bind(\"mousewheel\", mouseWheelHandler);\r\n $label.bind(\"mousewheel\", mouseWheelHandler);\r\n }\r\n else\r\n {\r\n $prev.hide();\r\n $next.hide();\r\n }\r\n\r\n // key handlers\r\n // (assign to variable is important that it can be removed later on)\r\n keyHandler = handleKeyUp;\r\n $(document).bind(\"keydown keyup\", keyHandler);\r\n\r\n // hide items and show first\r\n showIndex(0);\r\n }", "function preLoadImages() {\n var args_len = arguments.length;\n for (var i = args_len; i--;) {\n var cacheImage = document.createElement('img');\n cacheImage.src = arguments[i];\n __cache.push(cacheImage);\n }\n }", "function doLazyLoadImages() {\n DomUtil.doLoadLazyImages( self.$scroller, self.$pugs.find( \"pug\" ) );\n }", "function initImgs(){\n for(var i = 1; i <= datas.nbrOfImages; i++) {\n // génère les images dans l'index.html\n $scope.data.items.push({src: \"img/bd/Case\" + i + \".jpg\"});\n }\n }", "displayImages() {\n observeDocument(node => this.displayOriginalImage(node));\n qa('iframe').forEach(iframe => iframe.querySelectorAll('a[href] img[src]').forEach(this.replaceImgSrc));\n }", "function lazyLoadImages(){\n\t\tvar wrappers = document.querySelector('#image_container');\n\t\tvar imgLoad = imagesLoaded( wrappers );\n\t\tfunction onAlways( instance ) {\n\t\t\t//This should only happen once all of the images have finished being loaded\n\t\t\tconsole.log(\"All images loaded\");\n\t\t\tcollage();\n\t\t\t$('.Collage').collageCaption();\n\t\t}\n\t\timgLoad.on( 'always', onAlways );\n\t}", "function loadInitial() {\n var nameContainer = $('#list-recent-title');\n var dateContainer = $('#list-recent-time');\n var imageContainer = $('#list-recent-image');\n\n var vis = visuals[0];\n var id = vis.id;\n var name = vis.name;\n var image = vis.imageall;\n var datecreated = vis.datecreated;\n\n firstImage = name;\n selectedImage = firstImage;\n\n nameContainer.html(name);\n dateContainer.html(datecreated);\n imageContainer.attr('src', 'assets/vis/' + image);\n}", "function preloadImages(code) {\n var re = /SimpleImage\\(\\s*(\"|')(.*?)(\"|')\\s*\\)/g;\n while (ar = re.exec(code)) {\n // Used to screen out data: urls here, but that messed up the .loaded attr, strangely\n var url = ar[2];\n loadImage(url);\n }\n}", "function preload_images() {\n for (var i = 0; i < c_PreloadChunkSize && imageIndex < images.length; i++, imageIndex++) {\n outstandingPreloadCount++;\n var image = images[imageIndex];\n (function(image) {\n $('<img />')\n .attr('alt', image.title)\n .attr('src', image.img + '_n.jpg')\n .one('load', function() {\n var link = $('<a />')\n .attr('href', image.img + '_b.jpg')\n .attr('title', image.title)\n .append($(this));\n gallery.append(link);\n outstandingPreloadCount--;\n })\n .error(function() {\n console.log('Error downloading image: ' + image.img);\n outstandingPreloadCount--;\n });\n })(image);\n }\n }", "function ReLoadImages() {\n $('img[data-lazysrc]').each(function() {\n $(this).attr('src', $(this).attr('data-lazysrc'));\n });\n}", "function renderImages() {\n\t\t$('.landing-page').addClass('hidden');\n\t\t$('.img-round').removeClass('hidden');\n\t\tupdateSrcs();\n\t\tcurrentOffset+=100;\n\t}", "loadImage() {\n this.imagesLoaded++;\n if (this.imagesLoaded >= this.slides.length) {\n this.playSlideshow()\n }\n }", "function preload() {\nfrogImage = loadImage(\"assets/images/Frog.png\");\n}", "async loadImages() {\n const resources = Array.from(this._resources.entries());\n\n console.info(`[ImageManager] Loading ${resources.length} image assets.`);\n\n await Promise.all(resources.map(([iKey, iValue]) => {\n console.info(`[ImageManager] Loading image ${iValue}.`);\n\n const img = new Image();\n img.src = iValue;\n\n return new Promise((resolve) => img.addEventListener('load', () => {\n this._images.set(iKey, img);\n resolve();\n }))\n }));\n\n this._loaded = true;\n\n console.info('[ImageManager] Images loaded.');\n }", "function onImageLoaded() {\r\n\t\t++numImagesLoaded;\r\n\t\t\r\n\t\tif (numImagesLoaded == numImagesRequested) {\r\n\t\t\tnumImagesLoaded = 0;\r\n\t\t\tnumImagesRequested = 0;\r\n\t\t\timagesToLoad = [];\r\n\r\n\t\t\tif (onAllImagesLoadedCallback !== null && onAllImagesLoadedCallback !== undefined) {\r\n\t\t\t\tonAllImagesLoadedCallback();\r\n\t\t\t\tonAllImagesLoadedCallback = null;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function loadZoomInImages(i) {\n\t\tif (i < 77) {\n\t\t\tpicnumstring = ('00000' + i).slice(-5);\n\t\t\tinnerProject = currentProject();\n\t\t\tpicstring = '/sequences/rotate/ZOOMIN/' + innerProject + '/' + innerProject + '_' + picnumstring + '.jpg';\n\t\t\t$('#configurator .inset-0').prepend('<img class=\"hidden sequence-image inner-' + innerProject + '-' + picnumstring + '\" src=\"' + picstring + '\">');\n\n\n\t\t\tanimTimer = setTimeout(function() { loadZoomInImages(i + 1) }, 50);\n\n\t\t\t\n\t\t} else {\n\t\t\tloadedProjects.push(innerProject);\n\t\t}\n\n\t}", "function preload() {\n\tkernelImg = loadImage(\"assets/kernel.png\");\n\tpopcornImg = loadImage(\"assets/popcorn.png\");\n\tburntImg = loadImage(\"assets/burnt.png\");\n}", "function previewOnLoad() {\n pwindow = iframe.contentWindow;\n var p$ = pwindow && pwindow.$; // preview jquery object\n if (!p$ || p$.editorLoaded) return; // not ready || already initialized\n\n var pdoc = pwindow.document;\n\n // handle pane adjust event over preview\n pdoc.addEventListener('dragover', function(e) {\n adjustPanes(e.clientX, e.clientY, true); // handle over preview\n e.preventDefault();\n });\n\n // handle pane adjuster drop event over preview\n // (firefox will try to navigate to the url if text is dropped on it)\n pdoc.addEventListener('drop', function(e) {\n e.preventDefault();\n });\n\n pRef = pwindow.pubRef || {};\n var relPath = pRef.relPath || '';\n\n $css = p$('<link rel=\"stylesheet\" href=\"' + relPath + '/pub/css/pub-preview.css\">');\n p$('head').append($css);\n $css.get(0).disabled = true;\n\n var $script = p$('<script src=\"' + relPath + '/pub/js/pub-preview.js\"></script>');\n p$('body').append($script);\n\n p$.editorLoaded = true;\n clearInterval(previewPoller);\n }", "function imageLoaded() {\n imagesLoaded++\n if (imagesLoaded == totalImages) {\n allImagesLoaded()\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if point is between min and max
function isPointBetween(point, min, max) { if(point > min && point < max) return true; return false; }
[ "function check(min, max, target) {\n if (target > min && target < max) {\n return true;\n \n } else {\n \n return false;\n }\n}", "function between(i, min, max) {//check if int provided is within provided range. https://alvinalexander.com/java/java-method-integer-is-between-a-range\n if (i >= min && i <= max) {\n return true;\n } else {\n return false;\n }\n}", "function valueInBounds(v, [min, max]) {\n return v >= min && (max === undefined || v <= max);\n }", "function controlloRangeNumeri(min, max, number) {\n var result = false;\n if (number >= min && number <= max) {\n result = true;\n }\n return result;\n }", "function isInBounds(point) {\n\t\tif (point >= bounds.sw && point <= bounds.nw) {\n\t\t\tconsole.log(\"point in bounds\");\n\t\t}\n\t}", "function isInBound(x,y){\n\treturn x>-1&&x<9&&y>-1&&y<9;\n}", "inRange (number, start, end) {\n if (end === undefined) {\n end = start\n start = 0\n }\n if (start > end) {\n let temp = end\n end = start\n start = temp\n }\n let isInRange = (number >= start && number < end)\n return isInRange\n }", "function isInRange(pos, start, end) {\n if (typeof pos != 'number') {\n // Assume it is a cursor position. Get the line number.\n pos = pos.line;\n }\n if (start instanceof Array) {\n return inArray(pos, start);\n } else {\n if (end) {\n return pos >= start && pos <= end;\n } else {\n return pos == start;\n }\n }\n }", "intersectsPoint(a, b) {\n if (!b) {\n var x2 = a.x;\n var y2 = a.y;\n } else {\n var x2 = a;\n var y2 = b;\n }\n const x = this.x;\n const y = this.y;\n const w = this.width;\n const h = this.height;\n return x2 >= x && x2 <= x + w && y2 >= y && y2 <= y + h;\n }", "static between(x, a, b, inclusive) {\n let greater = Math.max(a, b);\n let lesser = Math.min(a, b);\n return inclusive ? x >= lesser && x <= greater : x > lesser && x < greater;\n }", "function overlaps(a, b) {\n if (a.x1 >= b.xMax || a.y1 >= b.yMax || a.x2 <= b.xMin || a.y2 <= b.yMin) {\n return false\n } else {\n return true\n }\n }", "function isBetween(a, b, c){\n var crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y);\n if (Math.abs(crossproduct) > 0.2) {return false;}\n var dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y);\n if (dotproduct < 0) {return false;}\n var squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y);\n return (dotproduct <= squaredlengthba);\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 between(v, a, b) {\n\treturn ((v >= a) && (v <= b)) || ((v >= b) && (v <= a))\n}", "function checkRange(input) {\n //checks integer range values for min/max order\n if (input < 0) {\n return true;\n }\n //converts every input into a String\n let stringTest = input.toString();\n // Take their input and split it at the '-' (hyphen mark)\n // numbers variable will then look like this\n // numbers = ['value1', 'value2']\n let numbers = stringTest.split(\"-\");\n //removes empty strings in array (caused by edge case of negative min to max range ex: \"-100-300\")\n let filterednumbers = numbers.filter((item) => item);\n // parseFloat parses argument and returns floating point number, then point numbers are compared using the < (less than) mathematical symbol\n // Because we are using the < in the return, this will only return a true or false based off the values.\n return parseFloat(filterednumbers[0]) < parseFloat(filterednumbers[1]);\n}", "isInBounds(x, y) {\n if(x <= 0 || x >= this.mapWidth || y <= 0 || y >= this.mapHeight) {\n return false;\n }\n return true;\n }", "minMaxConditionsHandler() {\n if (\n (this.min || this.min === 0) &&\n (this.value < this.min || this._previousValue < this.min)\n ) {\n this._value = this.min;\n }\n if (\n this.max &&\n (this.value > this.max || this._previousValue > this.max)\n ) {\n this._value = this.max;\n }\n }", "getBetweenRangesPos(center, minRange, maxRange) {\n let res = [];\n for(let x = center.x - maxRange; x <= center.x + maxRange; x++) {\n let remainingDistance = maxRange - Math.abs(x-center.x);\n for(let y = center.y-remainingDistance; y <= center.y + remainingDistance; y++) {\n let pos = new Position(x, y);\n if(this.isInsideMap(pos) && center.getManDistance(pos) >= minRange) {\n res.push(pos);\n }\n }\n }\n return res;\n }", "includes(range, target) {\n if (Range.isRange(target)) {\n if (Range.includes(range, target.anchor) || Range.includes(range, target.focus)) {\n return true;\n }\n\n var [rs, re] = Range.edges(range);\n var [ts, te] = Range.edges(target);\n return Point.isBefore(rs, ts) && Point.isAfter(re, te);\n }\n\n var [start, end] = Range.edges(range);\n var isAfterStart = false;\n var isBeforeEnd = false;\n\n if (Point.isPoint(target)) {\n isAfterStart = Point.compare(target, start) >= 0;\n isBeforeEnd = Point.compare(target, end) <= 0;\n } else {\n isAfterStart = Path.compare(target, start.path) >= 0;\n isBeforeEnd = Path.compare(target, end.path) <= 0;\n }\n\n return isAfterStart && isBeforeEnd;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the _pako object. TODO: lazyloading this object isn't the best solution but it's the quickest. The best solution is to lazyload the worker list. See also the issue 446.
_createPako() { const params = { raw: true, level: this._pakoOptions.level || -1 // default compression }; this._pako = this._pakoAction === 'Deflate' ? new Deflate(params) : new Inflate(params); this._pako.onData = (data) => { this.push({ data: data, meta: this.meta }); }; }
[ "async createWorkers () {\n\n let worker;\n if ( !this.fallback ) {\n\n let workerBlob = new Blob( this.functions.dependencies.code.concat( this.workers.code ), { type: 'application/javascript' } );\n let objectURL = window.URL.createObjectURL( workerBlob );\n for ( let i = 0; i < this.workers.instances.length; i ++ ) {\n\n worker = new TaskWorker( i, objectURL );\n this.workers.instances[ i ] = worker;\n\n }\n\n }\n else {\n\n for ( let i = 0; i < this.workers.instances.length; i ++ ) {\n\n worker = new MockedTaskWorker( i, this.functions.init, this.functions.execute );\n this.workers.instances[ i ] = worker;\n\n }\n\n }\n\n }", "function PQueueInit() {\n\treturn new buckets.PriorityQueue();\n}", "addWorker(){\r\n if(this.workerPool.length<FATUS_MAX_WORKER){\r\n let worker = new FatusWorker(this);\r\n this.initWorker(worker);\r\n this.workerPool.push(worker);\r\n console.log(MODULE_NAME + ': new worker created %s',worker.name);\r\n worker.run();\r\n }else{\r\n console.log(MODULE_NAME + ': workerpool full, skip adding');\r\n }\r\n }", "createWorkers() {\n let me = this,\n config = Neo.clone(NeoConfig, true),\n hash = location.hash,\n key, value;\n\n // remove configs which are not relevant for the workers scope\n delete config.cesiumJsToken;\n\n // pass the initial hash value as Neo.configs\n if (hash) {\n config.hash = {\n hash : DomEvents.parseHash(hash.substr(1)),\n hashString: hash.substr(1)\n };\n }\n\n for ([key, value] of Object.entries(me.workers)) {\n if (key === 'canvas' && !config.useCanvasWorker ||\n key === 'vdom' && !config.useVdomWorker\n ) {\n continue;\n }\n\n try {\n value.worker = me.createWorker(value);\n } catch (e) {\n document.body.innerHTML = e;\n me.stopCommunication = true;\n break;\n }\n\n me.sendMessage(key, {\n action: 'registerNeoConfig',\n data : config\n });\n }\n }", "function createWorker(worker) {\n\t if (typeof worker === 'string') {\n\t return new Worker(worker);\n\t }\n\t else {\n\t var blob = new Blob(['self.onmessage = ', worker.toString()], { type: 'text/javascript' });\n\t var url = URL.createObjectURL(blob);\n\t return new Worker(url);\n\t }\n\t}", "function getYepnope () {\n var y = yepnope;\n y.loader = {\n load: load,\n i : 0\n };\n return y;\n }", "addPriorityWorker(){\r\n if(this.priorityWorkerPool.length<10) {\r\n console.log(MODULE_NAME + ': adding priority worker');\r\n let worker = new FatusPriorityWorker(this);\r\n this.initWorker(worker);\r\n worker.setStackProtection(3);\r\n this.priorityWorkerPool.push(worker);\r\n worker.run();\r\n }\r\n }", "get _worker() {\n delete this._worker;\n this._worker = new ChromeWorker(\"resource://gre/modules/PageThumbsWorker.js\");\n this._worker.addEventListener(\"message\", this);\n return this._worker;\n }", "constructor() {\n if (TemplateHolder._instance) {\n return TemplateHolder._instance;\n }\n TemplateHolder._instance = this;\n \n this._parts = {};\n }", "_createWorker(text) {\n if (typeof Worker === \"undefined\") {\n this.view.log(\"Sorry, your browser does not support workers.\");\n return;\n }\n var self = this;\n this.view.log(\"Executing algorithm...\");\n this.webWorker = new Worker(\"js/GAPSolverWorker.js?v=2\");\n this.webWorker.postMessage(text);\n this.webWorker.postMessage(this.algorithm);\n this.webWorker.onmessage = function (event) {\n self.solution = event.data;\n Object.setPrototypeOf(self.solution, GAPSolution.prototype);\n Object.setPrototypeOf(self.solution.getInstance(), GAPInstance.prototype);\n self.computing = false;\n if (self.solution.isFeasible()) {\n self.view.log(\"Done: solution has cost \" + self.solution.getCost());\n self.view.log(self.solution);\n self._updateViewButtons(self.view, false, true);\n } else {\n self.view.log(\"Sorry, could not find a feasible solution!\");\n self._updateViewButtons(self.view, false, false);\n }\n \n };\n }", "initWorker(worker) {\r\n worker.setRetryTime(FATUS_EQ_RETRY_TIME);\r\n worker.setMaxAttempts(FATUS_WRK_RETRY_ATTEMP);\r\n worker.setStackProtection(FATUS_WRK_STACK_TRSHLD);\r\n worker.setReservationTime(FATUS_JOB_RESERV_TIME);\r\n worker.setMaxFails(FATUS_MAX_FAIL);\r\n }", "function createWebWorker(opts) {\n return webWorker_js_1.createWebWorker(standaloneServices_js_1.StaticServices.modelService.get(), opts);\n }", "function MoeEngine() \r\n{\r\n\tthis.helpers = new MoeHelpers(this);\r\n\tthis.asyncTemplates = {};\r\n\tthis.syncTemplates = {};\r\n\tthis.shouldPassLocals = false;\r\n}", "function TplBuilder(template, data, domTarget) {\n this.template = template;\n this.data = data;\n this.domTarget = domTarget;\n}", "_decompressWorker() {\n if (this._data instanceof CompressedObject) {\n return this._data.getContentWorker();\n } else if (this._data instanceof GenericWorker) {\n return this._data;\n } else {\n return new DataWorker(this._data);\n }\n }", "function WebWorkerSource(worker){\n this._worker = worker;\n}", "_preload () {\n const preloader = new Preloader();\n\n preloader.run().then(() => { this._start() });\n }", "constructor(name) {\n\t\tconsole.log('creating job queue [' + name + ']')\n\t\tthis.name = name\n\t\tthis.jobs = {}\n\t\t\n\t\tthis.$li = $('<li>')\n\t\tvar $label = $('<span>')\n\t\t$label.text(this.name)\n\t\t$label.css('font-weight', 'bold')\n\t\t\n\t\tthis.$count = $('<span>')\n\t\tthis.$count.addClass('w3-padding w3-badge w3-green w3-small')\n\t\tthis.$count.text('0')\n\t\tthis.$li.append($label, this.$count)\n\t\t\n\t\tthis.$jobs = $('<ul>')\n\t\tthis.$li.append(this.$jobs)\n\t}", "function Workers () {\n if (!(this instanceof Workers)) {\n return new Workers()\n }\n if (!pool) {\n if (!process.browser) {\n pool = workerpool.pool(__dirname + '/worker.js')\n } else {\n pool = workerpool.pool(process.env.DATT_NODE_JS_BASE_URL + process.env.DATT_NODE_JS_WORKER_FILE)\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Async fn always returns a Promise
async function asyncFunc() { return 123; }
[ "async(fn) {\n return (req, res, next) => {\n fn(req, res, next).then(data => {\n // On success, save the result of the Promise in req.data.\n req.data = data\n next()\n }).catch(error => {\n // On error, pass error to the next error middleware.\n next(error)\n })\n }\n }", "function promiseForFn() {\n\n // arguments to array\n const input = _.map(arguments);\n\n // first arg as function\n const fn = input[0];\n\n // rest of arguments\n const args = _.drop(input, 1);\n\n // validate first arg\n if (!_.isFunction(fn)) {\n throw new Error('First argument must be a function.');\n }\n\n // return promise\n return new Promise((resolve, reject) => {\n\n // add callback as last argument\n args.push((err, output) => err ? reject(err) : resolve(output));\n\n // invoke function\n fn.apply(fn, args);\n });\n}", "_ensure_future() {\n let ptrobj = _getPtr(this);\n let resolveHandle;\n let rejectHandle;\n let promise = new Promise((resolve, reject) => {\n resolveHandle = resolve;\n rejectHandle = reject;\n });\n let resolve_handle_id = Module.hiwire.new_value(resolveHandle);\n let reject_handle_id = Module.hiwire.new_value(rejectHandle);\n let errcode;\n try {\n errcode = Module.__pyproxy_ensure_future(\n ptrobj,\n resolve_handle_id,\n reject_handle_id\n );\n } catch (e) {\n Module.fatal_error(e);\n } finally {\n Module.hiwire.decref(reject_handle_id);\n Module.hiwire.decref(resolve_handle_id);\n }\n if (errcode === -1) {\n Module._pythonexc2js();\n }\n return promise;\n }", "async promiseAndThen(p, f) {\n const r = await p;\n if (r.isOk()) {\n const t = r.unwrap();\n return await f(t);\n }\n else {\n return Err(r.unwrapErr());\n }\n }", "async function callwithPromise(){\n const fullName = await call.withPromise('Isai', 'Reyes')\n console.log(fullName);\n }", "function callbackToPromise(fn, url, type, data) {\n var data = !_.isUndefined(data) ? data : null;\n var d = $.Deferred();\n fn(url, type, data, function(response) {\n d.resolve(response);\n }, function() {\n d.reject.call(null, arguments);\n });\n return d;\n}", "function toAsyncHandler(handler) {\n return callback => (0, _bluebird.resolve)().then(() => handler()).then(() => callback(), err => callback(err));\n}", "function ensureSync(value) {\n (0, _invariant.default)(!(0, _fp.is)(Promise, value), 'Unexpected Promise. Passed function should be synchronous.');\n return value;\n}", "function promisize(args) {\n var promise = new Ext.space.Promise();\n\n if (args && (args.onComplete || args.onError)) {\n promise.then(\n typeof args.onComplete == \"function\" ? args.onComplete : undefined,\n typeof args.onError == \"function\" ? args.onError : undefined\n );\n }\n\n return promise;\n }", "runGeneratorPromise (it) {\n return new Promise((resolve, reject) => {\n this.runGenerator(it, resolve)\n })\n }", "async function cobaAsync(){\n try{\n const res=await coba();\n console.log(res);\n }catch(err){\n console.error(err);\n }\n}", "function promisify(f) {\n return function(...args) {\n return new Promise((resolve, reject) => {\n function callback(err, result) {\n if (err) {\n reject(err);\n } else {\n resolve(result);\n }\n }\n args.push(callback);\n f.call(this, ...args);\n });\n }\n}", "function asynchronity() {\n //setTimeout is used, which is an asynchronous function.\n let result = new Promise((resolve, reject) => {\n setTimeout(() => resolve('I am complete!'), 1000);\n });\n\n /*Because of setTimeout, result isn't evaluated yet. Because of JavaScript's\n asynchronity, result is still logged. */\n console.log(result); //Logs Promise { <pending> }\n\n /*JavaScript contains many asynchronous functions, such as setInterval,\n requestAnimationFrame, XMLHttpRequest, WebSocket, Worker, some APIs, and more. */\n}", "function toAsyncWaterfallHandler(handler) {\n return (value, callback) => (0, _bluebird.resolve)().then(() => handler(value)).then(newValue => callback(null, newValue), err => callback(err, value));\n}", "async function generateMessageAsync() {\n\tvar messagePromise = new Promise(function(resolve, reject) {\n\t\tsetTimeout(() => {\n\t\t\tconst newMessage = {\n\t\t\t\thi: \"async\",\n\t\t\t\tid: Math.round(Math.random() * 100)\n\t\t\t};\n\t\t\tresolve(newMessage);\n\t\t}, 300);\n\t});\n\treturn messagePromise;\n}", "function makePromise(arg) {\n return new Promise(function(resolve, reject) {\n setTimeout(resolve(arg), 1000);\n });\n }", "function runAsync(func) {\n window.setTimeout(func, 0);\n}", "async function getGameMatch (gameUUID) {\n try { \n const checkGame = await GameIDCheckMatch(gameUUID);\n return checkGame;\n } catch (error) {\n console.log(error);\n throw new Error();\n }\n}", "function fun(body) {\n return \"async function foo() { \" + body + \" }\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modified version of the Google listEvents from Takes in a feed and the div ID to build an unordered list as a child of the div
function listGcalEvents(root, divId,calName,calHref) { var feed = root.feed; var events = document.getElementById(divId); if (events.childNodes.length > 0) { events.removeChild(events.childNodes[0]); } var eventContent = document.createElement('div'); eventContent.className = 'widget_content widget_cal'; // create a new ordered list var ol = document.createElement('ol'); ol.className = "widget_calItems"; // loop through each event in the feed for (var i = 0; i < feed.entry.length; i++) { var entry = feed.entry[i]; var title = entry.title.$t; var startDate = entry['gd$when'][0].startTime; var endDate = entry['gd$when'][0].endTime; // get the URL to link to the event for (var linki = 0; linki < entry['link'].length; linki++) { if (entry['link'][linki]['type'] == 'text/html' && entry['link'][linki]['rel'] == 'alternate') { var entryLinkHref = entry['link'][linki]['href']; } } //Take link data and build li li = usfDateLi(title, entryLinkHref, formatGCalTime(startDate), formatGCalTime(endDate)); // append the list item onto the unordered list ul.appendChild(li); } var calHeader = document.createElement('h2'); var calHeaderSpan = document.createElement('span'); var calHeaderLink = document.createElement('a'); var loadingElem = document.getElementById('calLoading'); calHeader.className = "widget_name"; var linkText = document.createTextNode(calName); calHeaderLink.href = calHref; calHeaderLink.appendChild(linkText); calHeaderSpan.appendChild(calHeaderLink); calHeader.appendChild(calHeaderSpan); //loadingElem.parentNode.removeChild(loadingElem); events.innerHTML = ''; events.appendChild(calHeader); events.appendChild(eventContent); eventContent.appendChild(ol); }
[ "function usfDateLi(title, entryLinkHref, objStartDate, objEndDate) {\n\t\tvar objStartDateNum = objStartDate.dayNumber();\n\t\tvar objEndDateNum = objEndDate.dayNumber();\n\n\t\tvar li = document.createElement('li');\n\t\tli.className = \"widget_calItem\";\n\t\t\n\t\tvar eventContainer = li;\n\t\t\n\t\t// if we have a link to the event, create an 'a' element\n\t\tif (typeof entryLinkHref != 'undefined') {\n\t\t\tentryLinkHref = entryLinkHref + \"&ctz=America/New_York\";\n\t\t\tvar eventLink = document.createElement('a');\n\t\t\teventLink.className = 'widget_calLink';\n\t\t\teventLink.setAttribute('href', entryLinkHref);\n\t\t\tli.appendChild(eventLink);\n\t\t\teventContainer = eventLink;\n\t\t} \n\n\t\teventIcon = usfEventIcon(objStartDate);\n\n\t\teventContainer.appendChild(eventIcon);\n\t\t\n\t\tvar eventDetails = document.createElement('div');\n\t\teventDetails.className = 'widget_calDetails';\n\t\teventContainer.appendChild(eventDetails);\n\t\t\n\t\tvar eventTitle = document.createElement('p');\n\t\teventTitle.className = 'widget_calTitle';\n\t\teventTitle.appendChild(document.createTextNode(title));\n\t\teventDetails.appendChild(eventTitle);\n\t\t\n\t\tvar eventDateString = usfEventDateString(objStartDate, objEndDate);\n\t\t\n\t\tvar eventDate = document.createElement('p');\n\t\teventDate.className = 'widget_calDate';\n\t\teventDate.appendChild(document.createTextNode(eventDateString));\n\t\teventDetails.appendChild(eventDate);\n\t\t\n\t\tvar eventTimeString = \"\";\n\n\t\tif (objStartDate.Time > \"\") {\n\t\t\teventTimeString += objStartDate.Time;\n\t\t} else {\n\t\t\teventTimeString += (\"12:00 AM\");\n\t\t}\n\t\tif (objEndDate.Time > \"\") {\n\t\t\teventTimeString += (\" - \" + objEndDate.Time);\n\t\t} else {\n\t\t\teventTimeString += (\" - \" + \"11:59 PM\");\n\t\t}\n\t\t\n\t\tvar eventTime = document.createElement('p');\n\t\teventTime.className = 'widget_calTime';\n\t\teventTime.appendChild(document.createTextNode(eventTimeString));\n\t\teventDetails.appendChild(eventTime);\n\n\t\treturn li;\n\t}", "function display() {\n let eventsDiv = document.getElementById(\"eventHistory\")\n listOfEvents = eventList.displayEvent()\n\n // eventsDiv.innerHTML = ''\n eventsDiv.appendChild(listOfEvents)\n }", "function addId(){ //Add ID to events, calendar and list\n var cal = document.getElementsByClassName(\"JScal\");\n var eventList = document.getElementsByClassName(\"JSeventList\");\n\n for (i = 0, length = eventList.length; i < length; i++) { //eventList or cal.lenght\n cal[i].href= \"#JSeventID_\" + (i + 1); //Add link to calendar\n eventList[i].id= \"JSeventID_\" + (i + 1); //Add id to list\n }\n }", "function showFriendsFeedEvent(event){\n\n\t\tvar feedList = $('#friends-live-activity');\n\n\t\tif(feedList.length){\n\n\t\t\tautoScroll = true;\n\n\t\t\t// Agrego el item a la lista\n\t\t\tfeedList.prepend(tmpl('friendlist_item', event));\n\n\t\t\tif(!hoverOnHovercard && !hoverOnList) {\n\t\t\t\tfeedList.scrollTo(0, 500);\n\t\t\t}\n\n\t\t\t// Mantenemos el scroll para evitar sacar de hover el elemento actual\n\t\t\tfeedList[0].scrollTop += 42;\n\n\t\t\t// Hago aparecer lo nuevo con una simple animación\n\t\t\tfeedList.find('.list-item:hidden').fadeIn(400);\n\n\t\t\t// Remuevo los feeds más viejos // -1 debido al índice 0 que es tomado en cuenta\n\t\t\tfeedList.find('.list-item:gt('+(feedsLimit-1)+')').remove();\n\t\t}\n\n\t}", "function displayFeedsUrlList() {\n const message = document.getElementById(\"feedsUrlMessage\");\n const headers = {\"Authorization\": getToken()};\n apiRequest(\"GET\", \"get_feeds_url.php\", null, headers, res => {\n const jsonRes = JSON.parse(res.responseText);\n for (const feed of jsonRes.feeds)\n addFeedUrlToList(feed.id, feed.url);\n message.innerHTML = \"\";\n message.className = \"\";\n }, err => handleRequestError(err.status, \"Erreur lors de la récupération des flux.\", message)\n );\n}", "function renderEventsBlock($wrapper, data) {\n var events = '';\n for (var i = 0; i < data.events.length; i++) {\n events += renderSingleEvent(data.events[i]);\n }\n var html = '<li class=\"events_item stickem-container\">';\n html += renderEventBlockHeader(data['formatted_date']);\n html += (\n '<div class=day_block\">' +\n '<div class=\"event_b_list\">' +\n events +\n '</div>' +\n '</div>'\n );\n html += '</li>';\n $wrapper.before(html);\n}", "function createEventSubList(event) {\n const p = document.createElement('p')\n p.innerHTML = `\n <li>\n <ul>\n <li>${event.uuid}</li>\n <li>${event.date}</li>\n <li>${event.description}</li>\n </ul>\n </li>\n `\n return p\n}", "getEventListWithQuery(\n\t\tquery\t\t// Full URL Query string\n\t) {\n\t\tif( !this.authtoken ) return;\n\t\t\n\t\tif( this.calendarlist.length > 0 )\n\t\t{\n\t\t\tthis.set( \"calendarlist\", [] );\n\t\t\tthis.dispatchEvent( new CustomEvent('calendar-event-list', { bubbles: true, composed: true, detail: [] } ));\n\t\t}\n\t\tthis.nextLink = null;\n\t\tthis.set( \"hasnextpage\", false );\n\n\t\tvar url = LIST_EVENT_URL;\n\t\tif( query && query.length > 0 ) url += query;\n\t\treturn this._getList( url );\n\t}", "function showStravaActivities(){\n var lengthActivities = activities.length;\n if (lengthActivities > 0) {\n var listHTML = '<ul>';\n\n for (var i = 0; i < lengthActivities; ++i) {\n console.log(activities[i].id); \n listHTML += '<li>' + activities[i].name + \" - \" + activities[i].date + \" - \" + activities[i].id + '</li>';\n }\n\n listHTML += '</ul>';\n $( \".listActivities\" ).append( listHTML );\n }\n}", "function fillActivityList() {\n\t$(\"#activitylist\").empty();\n\t\n\tif (activityScroll!=undefined)\n\t\tactivityScroll.refresh();\n\t\t\t\n\tvar appendString;\n\tgetAllActivities(function(result) {\n\t\t/*\n\t\t * Iterate over the results for the database query.\n\t\t */\n\t\t for(var i=0;i<result.length;++i) {\n\t\t\tappendString = addExistingActivityHMTL(result[i]);\n\t\t\t$(\"#activitylist\").append(appendString);\n\t\t}\n\t\t\n\t\tif (activityScroll!=undefined)\n\t\t\tactivityScroll.refresh();\n\t});\n}", "function getEvents() {\n\t/// \\todo add /api/events-since/{index} (and change Traffic Monitor to keep latest\n\tajax(\"/publish/EventLog\", function(r) {\n\t\tconst events = JSON.parse(r).events || [];\n\t\tfor (const event of events.slice(lastEvent+1)) {\n\t\t\tlastEvent = event.index;\n\t\t\tconst row = document.getElementById(\"event-log\").insertRow(0);\n\n\t\t\trow.insertCell(0).textContent = event.name;\n\t\t\trow.insertCell(1).textContent = event.type;\n\n\t\t\tconst cell = row.insertCell(2);\n\t\t\tif(event.isAvailable) {\n\t\t\t\tcell.textContent = \"available\";\n\t\t\t} else {\n\t\t\t\tcell.textContent = \"offline\";\n\t\t\t\trow.classList.add(\"error\");\n\t\t\t}\n\n\t\t\trow.insertCell(3).textContent = event.description;\n\t\t\trow.insertCell(4).textContent = new Date(event.time * 1000).toISOString();\n\t\t}\n\t});\n}", "function fetchFeedItems(url, from, count, callback) {\n\t\tfrom = from || 0;\n\t\tcount = count || 20;\n\t\t\n\t\tvar feed = new google.feeds.Feed(FEED_URL);\n\t\tfeed.setResultFormat(google.feeds.Feed.JSON_FORMAT);\n\t\tfeed.setNumEntries(from + count);\n\t\tfeed.includeHistoricalEntries();\n\t\tlog('From ' + from + ' to ' + (from + count) + '\\n');\n\t\tfeed.load(function(result) {\n\t\t\tif (result.error) {\n\t\t\t\tret = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Set title\n\t\t\t\theader = '<a href=\"' + result.feed.link + '\" rel=\"external\" target=\"_blank\"><h1>' + result.feed.title + '</h1></a>';\n\t\t\t header += '<h2><small>' + result.feed.description + '</small></h2>';\n\t\t\t header += '<hr class=\"soften\">'; \n\t\t\t $('body > div.container-fluid > .title-wrapper').html(header);\n\t\t\t\t\n\t\t\t\tvar max = (count > result['feed'].entries.length) ? count : result['feed'].entries.length;\n\t\t\t\titems = [];\n\t\t\t\tfor (var i = from; i < max; i++) {\n\t\t\t\t\titem = result['feed'].entries[i];\n\t\t\t\t\titem.eid = i;\n\t\t\t\t\tENTRIES[i] = item;\n\t\t\t\t\titems.push(item);\n\t\t\t\t}\n\t\t\t\tret = items;\t\n\t\t\t}\t\n\t\t\t\n\t\t\tif (callback && $.isFunction(callback)) {\n\t\t\t\tcallback(ret);\n\t\t\t}\n\t\t});\n\t}", "function collectAllEvents() {\n // A set for all calendar events displayed on the UI.\n // Each element in this set is a Json string. \n allEventJson = new Set(); \n \n const eventList = document.getElementById('new-event-list');\n \n // Looks at each event card and scrapes the event's name and \n // start and end times from the HTML elements. \n // Add all event information to a set of all Json strings. \n eventList.childNodes.forEach((eventCard) => {\n const eventName = eventCard.childNodes[0].childNodes[0].innerText; \n const startTime = eventCard.childNodes[0].childNodes[1].innerText; \n const endTime = eventCard.childNodes[0].childNodes[2].innerText; \n const event = new CalendarEvent(eventName, startTime, endTime);\n const eventJson = JSON.stringify(event); \n allEventJson.add(eventJson); \n }); \n}", "function EntryList() { }", "function GADGET_RSS_Entry_Open(Entry)\n{\t\n\t//>> Clear Timers\n\tif (Timer_Interval)\n\t\tclearTimeout(Timer_Interval);\n\t\n\tif (Timer_Auto_Scroll)\n\t\tclearTimeout(Timer_Auto_Scroll);\n\n\t//>> Get Variables\n\t\t\n\tvar\tDisplay = \"Browser\";\n\tvar\tEntry_Disp = \"5\";\n\t\t\n\tvar Size = System.Gadget.Settings.read(\"Size\");\n\t\n\tSystem.Gadget.Settings.write(\"Entry_Open\", Entry);\n\t\n\t//>> Reset Current Entry Styles\n\t//var Entry_Count = parseInt(System.Gadget.document.getElementById(\"Entry_Count\").innerHTML);\n\tvar Entry_Count = parseInt(noOfFeeds);\n\tvar Page = System.Gadget.Settings.read(\"Page\");\n\t\n\tvar i = (Page * Entry_Disp) - Entry_Disp;\n\tvar Limit = Page * Entry_Disp;\n\tif (Limit > Entry_Count)\n\t\tLimit = Entry_Count;\n\t\t\n\twhile (i < Limit)\n\t{\n\t\tSystem.Gadget.document.getElementById(\"Feed_Entry_\" + i).className = Size + \"-Feed-Entry\";\n\t\tSystem.Gadget.document.getElementById(\"Feed_Entry_\" + i + \"_Close\").style.display = \"none\";\n\t\ti++;\n\t}\n\t\n\n\t\tvar xURL = System.Gadget.document.getElementById(\"Entry_\" + Entry + \"_Link\").innerHTML;\n\t\t\n\t\tvar\tInterval = 60;\n\t\t\t\n\t\tif (Interval != '' && Interval != \"Off\")\n\t\t{\n\t\t\tInterval = Interval * 60000;\n\t\t\tTimer_Interval = setTimeout(GADGET_RSS_Feed_Start, Interval);\n\t\t}\n\t\t\n\t\tvar Auto_Scroll = System.Gadget.Settings.read(\"Auto_Scroll\");\n\t\tif (Auto_Scroll == '')\n\t\t\tAuto_Scroll = 20;\n\t\t\n\t\tif (Auto_Scroll != '' && Auto_Scroll != \"Off\")\n\t\t{\n\t\t\tAuto_Scroll = Auto_Scroll * 1000;\n\t\t\tTimer_Auto_Scroll = setTimeout(GADGET_RSS_Auto_Scroll, Auto_Scroll);\n\t\t}\n\t\t\n\t\tShell.Run(xURL);\t\t\n\t//}\n}", "function showEntry(list, type, title, amount, id){\n const entry = `<li id = \"${id}\" class = \"${type}\">\n <div class = \"entry\">${title}: $${amount} </div>\n <div id = \"edit\"></div>\n <div id = \"delete\"></div>\n </li>`;\n // make the newest entries appear at the top of list\n const position = \"afterbegin\";\n list.insertAdjacentHTML(position,entry);\n }", "function buildList(countSpan, resultList, foundElements) {\n var result = \"\";\n for (var i = 0; i < foundElements[0].length; ++i) {\n result += '<li>';\n result += '<a href=\"' + foundElements[1][i] + '\">';\n result += foundElements[0][i];\n result += '</a></li>';\n }\n\n if (countSpan) {\n countSpan.innerHTML = \"\" + foundElements[0].length;\n }\n resultList.innerHTML = result;\n}", "function JournalEntryList(elementId, entries, filterCallback = () => {\n}) {\n\n // The element Id containing the list\n this.elementId = elementId;\n\n // The list of journal entries\n this.entries = entries.slice();\n this.entries.sort();\n this.entries.reverse();\n\n // The list entries currently displayed\n this.resultSet = this.entries.slice();\n\n // The containing element for this searchable list\n const elem = document.getElementById(elementId);\n\n // The earliest timestamp in the list\n const minTimestamp = Math.min(...entries.map((entry) => {\n return entry.properties.timestamp;\n }));\n\n // The most recent timestamp in the list\n const maxTimestamp = Math.max(...entries.map((entry) => {\n return entry.properties.timestamp;\n }));\n\n // The search bar\n elem.innerHTML = `<div id=\"journal-search-bar\">\n <form id=\"journal-search-form\" class=\"inline-searchbar\">\n\n <div style=\"width: 50%; display: inline-flex;\">\n <label for=\"journal-search-text\" class=\"sr-only\">Search</label>\n <input type=\"text\" name=\"search-text\" id=\"journal-search-text\" class=\"form-control inline-searchbar-item journal-form-input\" autocomplete=\"off\">\n </div>\n\n <div style=\"width: 50%; display: inline-flex;\">\n <label for=\"journal-search-after\" class=\"sr-only\">After</label>\n <input type=\"date\" name=\"after\" id=\"journal-search-after\" class=\"form-control inline-searchbar-item journal-form-input\">\n \n <label for=\"journal-search-before\" class=\"sr-only\">Before</label>\n <input type=\"date\" name=\"before\" id=\"journal-search-before\" class=\"form-control inline-searchbar-item journal-form-input\">\n </div>\n \n <div style=\"width: 100%; display: inline-flex;\">\n \n <label for=\"sentiment-slider\" class=\"sr-only\">Sentiment Slider</label>\n <input type=\"range\" name=\"sentiment-slider\" id=\"sentiment-slider\" class=\"form-control inline-searchbar-item journal-form-input transparentButton\" min=\"0.0\" max=\"1.0\" step=\"0.01\">\n \n \n <div class=\"form-group\">\n <div class=\"checkbox\">\n <label for=\"sentiment-toggle\" class=\"\">\n <input type=\"checkbox\" name=\"sentiment-toggle\" id=\"sentiment-toggle\" class=\"inline-searchbar-item journal-form-toggle transparentButton\">\n </label>\n </div>\n </div>\n \n <label for=\"timeline-slider\" class=\"sr-only\">Sentiment Slider</label>\n <input type=\"range\" name=\"timeline-slider\" id=\"timeline-slider\" class=\"form-control inline-searchbar-item journal-form-input transparentButton\" min=\"0.0\" max=\"1.0\" step=\"0.01\">\n \n \n <div class=\"checkbox form-group\">\n <label for=\"timeline-toggle\" class=\"\">\n <input type=\"checkbox\" name=\"timeline-toggle\" id=\"timeline-toggle\" class=\"form-check-input inline-searchbar-item journal-form-toggle transparentButton\">\n </label>\n </div>\n \n </div>\n \n </form>\n </div>`;\n\n\n /**\n * Add a new entry to the list\n *\n * @param entry\n */\n this.add = (entry) => {\n\n // TODO: There is the issue of whether the new entry satisfies the current filter\n\n const dc = JSON.parse(JSON.stringify(entry));\n\n this.entries.unshift(dc);\n this.resultSet.unshift(dc);\n };\n\n\n /**\n * Display the entry list in its current state\n */\n this.display = () => {\n\n // Clear the container before displaying\n entryContainer.innerHTML = \"\";\n\n let entryHtml = this.resultSet.map((entry) => {\n\n return `<div class='journal-entry-text partialBorder centerTextContent' id=\"${entry.properties.id}\">\n <p class=\"inferredSubjectList\">${entry.properties.inferredSubjects.join(\", \").replace(new RegExp(\"_\", \"g\"), \" \")}</p>\n <p>${entry.properties.text}</p>\n <div class=\"journal-entry-control-bar\">\n <form class=\"journal-publicity-form control-bar-item\">\n <input type=\"text\" name=\"id\" value=\"${entry.properties.id}\" hidden>\n <input type=\"text\" name=\"public\" value=\"${!entry.properties.public}\" hidden>\n <button type=\"submit\" class=\"transparentButton\" style=\"color: ${entry.properties.public ? \"#78A4FF\" : \"#707073\"};\"><i class=\"fa fa-users\"></i></button>\n </form>\n <form class=\"journal-delete-form control-bar-item\">\n <input type=\"text\" name=\"id\" value=\"${entry.properties.id}\" hidden>\n <button type=\"submit\" class=\"transparentButton journal-delete-button\"><i class=\"fa fa-trash\"></i></button>\n </form>\n <div class=\"journalEntryTimestamp control-bar-item\">${moment(entry.properties.timestamp).format('YYYY-MM-DD HH:mm')}</div>\n </div>\n </div>`;\n });\n\n entryContainer.innerHTML = entryHtml.join(\"\");\n\n // Get a reference to the current JournalEntryList object\n let self = this;\n\n // Handler for deletion\n $('.journal-delete-form').submit(function (e) {\n\n // Prevent the form from clearing\n e.preventDefault();\n\n if (confirm(\"Delete this entry forever?\")) {\n\n // Submit the form asynchronously\n $.ajax({\n method: \"post\",\n url: \"/journal/delete\",\n data: $(this).serialize(),\n dataType: \"json\",\n success: (responseData, textStatus, jqXHR) => {\n if (responseData.payload) {\n self.remove(responseData.payload);\n }\n }\n });\n }\n\n });\n\n // Handler for publicity setting\n $('.journal-publicity-form').submit(function (e) {\n\n // Prevent the form from clearing\n e.preventDefault();\n\n if (confirm(\"Change the publicity of this entry?\")) {\n\n // Submit the form asynchronously\n $.ajax({\n method: \"post\",\n url: \"/journal/publicity\",\n data: $(this).serialize(),\n dataType: \"json\",\n success: (responseData, textStatus, jqXHR) => {\n if (responseData['success'] === true) {\n console.log(responseData);\n // TODO: change publicity on front-end\n }\n }\n });\n }\n\n });\n\n };\n\n\n /**\n * Remove an entry from the list\n *\n * @param entry_id\n */\n this.remove = function (entry_id) {\n\n // Remove element from page\n document.getElementById(entry_id).remove();\n\n // Remove element from entry list\n this.entries = this.entries.filter((entry) => {\n return entry.properties.id !== entry_id;\n });\n\n // Remove element from result set\n this.resultSet = this.resultSet.filter((entry) => {\n return entry.properties.id !== entry_id;\n });\n\n };\n\n\n /**\n * Sort the entries by timestamp\n *\n * @param oldestFirst\n */\n this.sort = function (oldestFirst = false) {\n\n const factor = (oldestFirst === true) ? -1 : 1;\n\n this.resultSet.sort((a, b) => {\n\n return factor * Math.sign(b.properties.timestamp - a.properties.timestamp);\n });\n };\n\n\n /**\n * Find all entries containing a search term\n *\n * @param rawSearchTerm\n */\n const _filterText = (rawSearchTerm) => {\n\n // Ignore case when searching\n const searchTerm = rawSearchTerm.toLowerCase();\n\n this.resultSet = this.resultSet.filter(function (elem) {\n return elem.properties.text.toLowerCase().includes(searchTerm);\n });\n\n // Highlight the search term wherever it is found\n this.resultSet.forEach((elem) => {\n elem.properties.text = elem.properties.text.replace(new RegExp(searchTerm, 'i'), \"<span class='search-highlight'>$&</span>\")\n })\n };\n\n /**\n * Filter journal entries by date\n *\n * @param from\n * @param to\n * @private\n */\n const _filterDates = (from, to) => {\n\n this.resultSet = this.resultSet.filter((elem) => {\n return from <= elem.properties.timestamp && elem.properties.timestamp <= to;\n });\n };\n\n\n /**\n * Find all entries near the given coordinates\n *\n * @param coords The position to compare against\n * @param radius The radius of inclusion\n */\n const _filterNear = (coords, radius) => {\n\n this.resultSet = this.resultSet.filter(function (elem) {\n\n return distance(coords[0], coords[1], elem.geometry.coordinates[0], elem.geometry.coordinates[1]) < radius;\n });\n };\n\n\n const passesFilter = (entry, formData) => {\n\n let passes = true;\n\n formData.forEach((field) => {\n\n if (field.name === 'search-text') {\n\n }\n\n\n });\n\n return passes;\n\n };\n\n /**\n * Filter the journal entries according to the filter form\n *\n * TODO: There is a visual bug caused by map circles being redrawn after they are sorted.\n *\n * TODO: Refactor so that the entry list is only iterated over once\n *\n * @param formData\n */\n this.filter = (formData) => {\n\n // Start with a clean result set - deep copy\n this.resultSet = this.entries.map((entry) => {\n return JSON.parse(JSON.stringify(entry));\n });\n\n let sentimentToggle = false;\n let sentimentSlider = 0.5;\n const sentimentRadius = 0.2;\n\n let timelineToggle = false;\n let timelineSlider = 0.5;\n const timelineRadius = 0.2;\n\n let afterToggle = false;\n let afterDate = 0;\n\n let beforeToggle = false;\n let beforeDate = (new Date()).getTime();\n\n // Apply each of the filters specified in the form\n formData.forEach((field) => {\n\n // Substring search of entry text\n if (field['name'] === 'search-text') {\n\n _filterText(field['value']);\n }\n\n // Proximity search\n else if (field['name'] === 'near-me') {\n _filterNear([0, 0], 100)\n }\n\n // Find entries older than\n else if (field['name'] === 'after') {\n\n if (field['value'] !== \"\") {\n afterToggle = true;\n afterDate = (new Date(field['value'])).getTime();\n }\n }\n\n // Find entries younger than\n else if (field['name'] === 'before') {\n\n if (field['value'] !== \"\") {\n beforeToggle = true;\n beforeDate = (new Date(field['value'])).getTime();\n }\n }\n\n // Record that the sentiment slider should be used\n else if (field['name'] === 'sentiment-toggle' && field['value'] === 'on') {\n\n sentimentToggle = true;\n }\n\n // Get the value of the sentiment slider\n else if (field['name'] === 'sentiment-slider') {\n sentimentSlider = field['value'];\n }\n\n // Record that the timeline slider should be used\n else if (field['name'] === 'timeline-toggle' && field['value'] === 'on') {\n\n timelineToggle = true;\n }\n\n // Get the value of the timeline slider\n else if (field['name'] === 'timeline-slider') {\n timelineSlider = field['value'];\n }\n });\n\n // Filter the entries by the search criteria\n this.resultSet = this.resultSet.filter((entry) => {\n\n // Filter by sentiment value\n if (sentimentToggle === true) {\n\n if (Math.abs(sentimentSlider - entry.properties.sentiment) > sentimentRadius) {\n return false;\n }\n }\n\n // Filter by timeline value\n if (timelineToggle === true) {\n if (Math.abs(timelineSlider - ((entry.properties.timestamp - minTimestamp) / (maxTimestamp - minTimestamp))) > timelineRadius) {\n return false;\n }\n }\n\n if (afterToggle === true) {\n if (entry.properties.timestamp < afterDate) {\n return false;\n }\n }\n\n if (beforeToggle === true) {\n if (entry.properties.timestamp > beforeDate) {\n return false;\n }\n }\n\n // The entry didn't fail any filter test. Include it in the result set\n return true;\n\n });\n\n\n // Pass the updated result set to the callback\n filterCallback(this.resultSet);\n };\n\n // The containing element for the list\n const entryContainer = document.createElement('div');\n elem.append(entryContainer);\n\n // Handlers for checkboxes\n $('.journal-form-toggle').on('change', () => {\n\n const formData = $('#journal-search-form').serializeArray();\n\n this.filter(formData);\n this.sort();\n this.display();\n });\n\n // Handlers for other inputs\n $('.journal-form-input').on('input', () => {\n\n const formData = $('#journal-search-form').serializeArray();\n\n this.filter(formData);\n this.sort();\n this.display();\n });\n\n $('#journal-search-form').submit((event) => {\n event.preventDefault();\n });\n\n // The initial display\n this.sort();\n this.display();\n\n}", "function displayAllEventsAuth(data) {\n $('.my-events-link').removeClass('hidden');\n const events = data.events;\n for (let i = 0; i < events.length; i++) {\n const dates = formatDates(events[i].startDate, events[i].endDate)\n\n let eventImg = '';\n if (events[i].image == undefined) {\n eventImg = 'images/default.jpg';\n }else{\n eventImg = events[i].image;\n }\n\n $('.events').append(\n `\n <article class='js-event ${i}'>\n <img src='${eventImg}' alt='${events[i].name} logo'>\n <p class='id hidden'>${events[i].id}</p>\n <h3><a href='${events[i].website}' target='_blank'>${events[i].name}</a></h3>\n <h3>${dates}</h3>\n <h3>${events[i].location}</h3>\n <button type='button' class='js-guest-list' data-featherlight='#guestauth${i}'>\n Celebrity Guests</button>\n <div class='hidden js-guests-list ${i} 'id='guestauth${i}'>\n <h4>${events[i].name} Celebrity Guests</h4>\n <ul class='${i}'></ul>\n <button type='button' class='add-guests'>Add guests</button>\n <form action='/events' method='post' class='add-guest-form hidden'>\n <p class='id hidden'>${events[i].id}</p>\n <label>\n <textarea rows='4' cols='40' name='new-guests' class='new-guests' placeholder='Enter guest names, separated by commas'></textarea>\n </label>\n <button type='submit' class='submit-guests'>Submit Guests</button>\n </form>\n </div>\n </article>\n `\n )\n for (let a = 0; a < events[i].guests.length; a++) {\n $('.events ul' + '.' + i).append(`<li>${events[i].guests[a]}</li>`);\n }\n if (moment().format('YYYY/MM/DD') > events[i].startDate) {\n $('.events .js-event' + '.' + i).append(`\n <button type='button' class='delete-option' data-featherlight='#delete${i}'>Delete this event</button>\n <div class='delete-confirm hidden' id='delete${i}'>\n <p class='id hidden'>${events[i].id}</p>\n <p class='delete-confirm-p'>Are you sure you want to delete this event?</p>\n <button type='button' class='delete-event'>Permanently delete this event</button>\n </div>\n `)\n }else if (moment().format('YYYY/MM/DD') < events[i].startDate && $('.my-events p').text().indexOf(events[i].id) == -1) {\n $('.events' + ' ' + 'article' + '.' + i).append(`\n <button type='button' class='add-my-events'>Add to My Events</button> \n `)\n }\n } \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate if two courses conflict
function conflicted(course1, course2){ return (shareDays(course1, course2) && (course1.start_time <= course2.end_time && course1.start_time >= course2.start_time || course2.start_time <= course1.end_time && course2.start_time >= course1.start_time || course1.start_time <= course2.start_time && course1.end_time >= course2.end_time || course2.start_time <= course1.start_time && course2.end_time >= course1.end_time)); }
[ "function combineCourse(courses, s_courses) {\n if (courses.length == 0) {\n return false;\n } else if (s_courses.length == 0) {\n return courses;\n } else {\n var result = new Array;\n result = s_courses;\n for ( i = 0; i < courses.length; i++) {\n var f = 0;\n for ( j = 0; j < s_courses.length; j++) {\n if (courses[i] == s_courses[j])\n f = 1;\n }\n if (f == 0)\n result.push(courses[i]);\n }\n return result;\n }\n}", "function getConflictedCourses(schedule = []) {\n const course = {};\n for (let i = 0; i < schedule.length; i += 2) {\n for (let j = 0; j < schedule.length; j += 1) {\n if (\n schedule[i].course_id === schedule[j].course_id &&\n j % 2 === 0\n ) {\n if (course[schedule[i].course_id]) {\n const temp = course[schedule[i].course_id];\n course[schedule[i].course_id] = [\n ...temp,\n schedule[j].course_id\n ];\n } else {\n course[schedule[i].course_id] = [schedule[j].course_id];\n }\n }\n }\n }\n return course;\n}", "function doesSectionConflictWithCurrentSchedule(sSection, iCourseID, iSectionID) {\n if (iCourseID == 0 && iSectionID == 0) return false; // Nothing has been added yet, so the answer is no\n\n for (var i = 0; i < iCourseID; i++) {\n for (var j = 0; j < aCurrentSchedule[i].length; j++) {\n if (doSectionsConflict(sSection, aCurrentSchedule[i][j])) return true;\n }\n }\n\n for (var i = 0; i < iSectionID; i++) {\n if (doSectionsConflict(sSection, aCurrentSchedule[iCourseID][i])) return true;\n }\n\n return false;\n }", "function dbResults(completedCourses = [], registeringTo = []) {\n let counter = 0;\n const preReqNotCompleted = [];\n for (let i = 0; i < registeringTo.length; i += 1) {\n for (let j = 0; j < completedCourses.length; ) {\n if (registeringTo[i].dependencies.pre !== completedCourses[j]) {\n // preReqCompleted[counter] = registeringTo[i];\n // counter += 1;\n counter += 1;\n if (counter >= completedCourses.length) {\n preReqNotCompleted.push(registeringTo[i]);\n }\n } else {\n j += 1;\n }\n }\n }\n return preReqNotCompleted;\n}", "function compGCD(firstRank,secondRank){\n let curBoolean = false;\n let firstCDs = ranksMap.get(firstRank);\n let secondCDs = ranksMap.get(secondRank);\n // console.log(firstRank,secondRank)\n firstCDs.forEach((value) => {\n if(secondCDs.has(value)){\n curBoolean = true;\n }\n })\n return curBoolean\n }", "function shareDays(course1, course2){\n \tvar days1 = parseDays(course1.meeting_days);\n \tvar days2 = parseDays(course2.meeting_days);\n \tfor (var i=0; i < days1.length; i++){\n \t\tfor (var j=0; j < days2.length; j++){\n \t\t\tif (days1[i] == days2[j]){\n \t\t\t\treturn true; // Return true if a shared day exists\n \t\t\t}\n \t\t}\n \t}\n\n \treturn false; // Else return false\n }", "isScoreComplete(){\n // if (this.dscore1 == null){\n // return false;\n // }else if (this.dscore2 ==null){\n // return false;\n // }else if (this.fscore1 == null){\n // return false;\n // }else if (this.fscore2 == null){\n // return false;\n // }else if (this.tscore1 == null){\n // return false;\n // }else if (this.tscore2 == null){\n // return false;\n // } else {\n // return true;\n // }\n \n if (this.dscore1 == 0) {\n return false;\n }else if (this.dscore2 == 0){\n return false;\n }else if (this.fscore1 == 0){\n return false;\n }else if (this.fscore2 == 0){\n return false;\n }else if (this.tscore1 == 0){\n return false;\n }else if (this.tscore2 == 0){\n return false;\n }else if (this.pscore1 == 0){\n return false;\n }else{\n return true;\n }\n }", "removeNonPairableCourses(){\n const courseFrequency = {};\n for (const element of this.studentCourseArr) {\n const studentId = element[0];\n const courseName = element[1];\n\n if (!(courseName in courseFrequency)) {\n courseFrequency[courseName] = [];\n courseFrequency[courseName].push(studentId);\n } else if (courseName in courseFrequency) {\n const studentAlreadyCounted = courseFrequency[courseName].indexOf(studentId) > -1;\n if (!studentAlreadyCounted) {\n courseFrequency[courseName].push(studentId);\n }\n }\n }\n // console.log(courseFrequency)\n\n for (const course in courseFrequency) {\n if (courseFrequency[course].length < 2) {\n delete courseFrequency[course];\n }\n }\n // console.log(courseFrequency)\n\n for (const course in courseFrequency) {\n if (courseFrequency[course] in this.returnObj) {\n this.returnObj[courseFrequency[course]].push(course); // This does not take into account order of student IDs. Need to sort?\n }\n }\n\n // console.log(this.returnObj);\n }", "function check_overlap(student_id){\n var is_overlapping = false;\n var $student = $(\"#classroom-layout .student[data-id='\" + student_id + \"']\");\n if ($student.length === 0)\n return;\n var r1 = {\n left: $student.position().left,\n top: $student.position().top,\n right: $student.position().left + $student.width(),\n bottom: $student.position().top + $student.height()\n };\n var r2 = {};\n var dirty = false;\n $(\"#classroom-layout .student\").each(function(){\n // avoid checking against self\n if ($(this).attr(\"data-id\") == student_id)\n return;\n r2 = {\n left: $(this).position().left,\n top: $(this).position().top,\n right: $(this).position().left + $(this).width(),\n bottom: $(this).position().top + $(this).height()\n };\n if (are_rectangles_overlapping(r1, r2)){\n // same group name\n if (StudentLayout.has_group(student_id, $(this).attr(\"data-group\"))){\n // both are singletons -> create a new group\n if ($(this).attr(\"data-group\") === \"\"){\n var new_group = \"group\" + uid();\n while(group_exists(new_group))\n new_group = \"group\" + uid();\n $(document).trigger(\"student_status_update\", [student_id, {\"type\": \"add_group\", \"value\": new_group }]);\n $(document).trigger(\"student_status_update\", [$(this).attr(\"data-id\"), {\"type\": \"add_group\", \"value\": new_group }]);\n dirty = true;\n }\n // already in the same group, so pass except for initialization\n else {\n $(document).trigger(\"student_status_update\", [student_id, {\"type\": \"add_group\", \"value\": $(this).attr(\"data-group\") }]);\n $(document).trigger(\"student_status_update\", [$(this).attr(\"data-id\"), {\"type\": \"add_group\", \"value\": $(this).attr(\"data-group\") }]);\n dirty = true;\n }\n // different group name\n } else {\n // if checked student has no group\n if ($(this).attr(\"data-group\") === \"\"){\n $(document).trigger(\"student_status_update\", [$(this).attr(\"data-id\"), {\"type\": \"add_group\", \"value\": $student.attr(\"data-group\") }]);\n dirty = true;\n }\n // if dropped student has no group\n else if ($student.attr(\"data-group\") === \"\"){\n $(document).trigger(\"student_status_update\", [student_id, {\"type\": \"add_group\", \"value\": $(this).attr(\"data-group\") }]);\n dirty = true;\n }\n // update student's group info\n else {\n $(document).trigger(\"student_status_update\", [student_id, {\"type\": \"add_group\", \"value\": $(this).attr(\"data-group\") }]);\n dirty = true;\n }\n }\n } else {\n // if previously in the same group, break them\n if (!dirty && StudentLayout.has_group(student_id, $(this).attr(\"data-group\")) && $student.attr(\"data-group\") !== \"\"){\n // two-student groups becoming singletons -> remove the group altogether and update group to None\n if (get_group_count($(this).attr(\"data-group\")) == 2) {\n $(document).trigger(\"student_status_update\", [$(this).attr(\"data-id\"), {\"type\": \"remove_group\", \"value\": $(this).attr(\"data-group\") }]);\n }\n $(document).trigger(\"student_status_update\", [student_id, {\"type\": \"remove_group\", \"value\": $(this).attr(\"data-group\") }]);\n }\n }\n });\n }", "static verifyClues(oldclues, newclues) {\n\n // make sure that each old clue corresponds to a new clue.\n Object.keys(oldclues).forEach((direction) => {\n if (newclues[direction] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n\n Object.keys(newclues[direction]).forEach((number) => {\n if (newclues[direction][number] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n });\n });\n\n // make sure that each new clue corresponds to an old clue.\n Object.keys(newclues).forEach((direction) => {\n if (oldclues[direction] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n Object.keys(newclues[direction]).forEach((number) => {\n if (oldclues[direction][number] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n });\n });\n }", "function courseExists(id) {\n for (i in grades) {\n if (grades[i].courseId == id) {\n return true;\n }\n }\n return false;\n}", "function checkInclusion(s1, s2) {\n let k = s1.length;\n let s1Count = new Map();\n let s2Count = new Map();\n\n for (let i = 0; i < k; i++) {\n if (!s1Count.has(s1[i])) {\n s1Count.set(s1[i], 1);\n } else {\n s1Count.set(s1[i], s1Count.get(s1[i]) + 1);\n }\n }\n\n // sliding window\n let i = 0, j = 0;\n\n while (j < s2.length) {\n if (!s2Count.has(s2[j])) {\n s2Count.set(s2[j], 1);\n } else {\n s2Count.set(s2[j], s2Count.get(s2[j]) + 1);\n }\n\n if (j - i + 1 == k) {\n if (mapsAreEqual(s1Count, s2Count)) {\n return true;\n } else {\n s2Count.set(s2[i], s2Count.get(s2[i]) - 1);\n\n if (s2Count.get(s2[i]) == 0) {\n s2Count.delete(s2[i]);\n }\n\n i++;\n }\n }\n\n j++;\n }\n\n return false;\n}", "function compareByScore(a, b) {\n \"use strict\";\n if ((a.seize && b.seize) || (!a.seize && !b.seize)) {\n i = b.totalScore - a.totalScore;\n return i;\n } else if (a.seize && !b.seize) {\n return -1;\n } else {\n return 1;\n }\n}", "function checkCourseAssignment(req, res, next) {\n mysql.pool.query(\n 'SELECT course_id FROM `assignment` WHERE assignment_id = ' + req.params.a_id,\n function(err, results, fields) {\n if(err) {\n res.send(\"Database error!\");\n next(err);\n } else {\n results = JSON.parse(JSON.stringify(results));\n if (results[0].course_id == req.params.c_id) {\n next();\n } else {\n res.send(\"This page does not exist.\");\n }\n }\n });\n}", "function doSectionsConflict(sSection1, sSection2) {\n if(sSection1 == null || sSection2 == null) return false;\n \n // Iterate over all of sSection1's meetings\n for (var i in sSection1.aMeetings) {\n var mMeeting1 = sSection1.aMeetings[i];\n\n // Given one of sSection1's meetings, iterate over all of sSection2's meetings\n for (var j in sSection2.aMeetings) {\n var mMeeting2 = sSection2.aMeetings[j];\n\n // If these meetings are not during the same term, skip further checking\n if (!doTermsOverlap(mMeeting1.sTerm, mMeeting2.sTerm)) continue;\n\n // If these meetings are on different days, skip further checking\n if (mMeeting1.sDay != mMeeting2.sDay) continue;\n\n // These meetings are on the same day - check for time collision\n if (doTimesConflict(mMeeting1.nStartTime, mMeeting1.nEndTime, mMeeting2.nStartTime, mMeeting2.nEndTime))\n return true; // The times conflict, return true.\n }\n }\n\n // No meetings conflict, return false.\n return false;\n }", "async function checkTwoGamePolicy(team1, team2, seasonId){\n const games = await getTeamsGames(team1, team2, seasonId);\n if(games.length >= 2){\n return false;\n }\n else if(games.length == 1 && team1 === games[0].homeTeam && team2 === games[0].awayTeam){\n return false;\n }\n\n return true;\n}", "function coprime(a, b)\n{\n if (__gcd(a, b) === 1)\n console.log(\"1\");\n else\n console.log(\"0\"); \n}", "function conflictWithCart(currentListId) {\n\tlet conflict = false;\n\tconst ajaxData =`studentid=${publicState.studentId}&\n\t\t\t\t\tsemester=${publicState.semester}`;\n\t$.ajax({\n\t\ttype: 'GET',\n\t\turl: '/search/cart',\n\t\tdata: ajaxData,\n\t\tsuccess: function(data){\n\t\t\tif (conflictWithAlreadyRegisteredOrInCart(currentListId, data.carts)) {\n\t\t\t\tconflict = true;\n\t\t\t}\n\t\t},\n\t\tfailure: function(status){\n\t\t\tconsole.log('Failure', status);\n\t\t}\n\t});\n\treturn conflict;\n}", "function checkIntersections(_collection) {\n for (let a = 0; a < _collection.length; a++) {\n for (let b = a + 1; b < _collection.length; b++) {\n let moleculeA = molecules[_collection[a]];\n let moleculeB = molecules[_collection[b]];\n if (obj.lineState) {\n stroke(125, 100);\n line(moleculeA.position.x, moleculeA.position.y, moleculeB.position.x, moleculeB.position.y);\n };\n moleculeA.isIntersecting(moleculeB) ? (moleculeA.changeColor(), moleculeB.changeColor()) : null;\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers breakpointspecific config. Note that we do do not use the swiper breakpoint config as it does not support changing all swiper options. Instead we reinit the whole swiper when necessary.
registerBreakpointConfig() { // See GalleryFsMobileScroll.registerBreakpointConfig() for an example. }
[ "function handleResponsive() {\n app.ResponsiveBreakpoints.register_event(\n '0-768',\n 'module-0-768',\n self.setup0_768.bind(self) // using es5-shim.js\n )\n\n app.ResponsiveBreakpoints.register_event(\n '768-+',\n 'module-768up',\n self.setup769up.bind(self) // using es5-shim.js\n )\n }", "function checkBreakpoint() {\n\t\t\t// Use an actual media-query-driven property of an element\n\t\t\t// to ensure JS and CSS are synced.\n\t\t\tvars.modelWidth = $(settings.modelSelector + ':first').outerWidth();\n\n\t\t\t// Loop through breakpoints and try to find a match with the model's current width.\n\t\t\tvar foundBreakpoint = false;\n\t\t\t$.each(settings.breakpoints, function(breakpoint, size) {\n\t\t\t\tif (!foundBreakpoint && size == vars.modelWidth) {\n\t\t\t\t\tif (breakpoint !== vars.currentView) {\n\t\t\t\t\t\tif (vars.initial === false) {\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + vars.currentView + ':exit');\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + breakpoint);\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + breakpoint + ':enter');\n\t\t\t\t\t\t\tif (settings.debug) {\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + vars.currentView + ':exit');\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + breakpoint);\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + breakpoint + ':enter');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + breakpoint);\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + breakpoint + ':initial');\n\t\t\t\t\t\t\tif (settings.debug) {\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + breakpoint);\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + breakpoint + ':initial');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvars.initial = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvars.currentView = breakpoint;\n\t\t\t\t\t}\n\t\t\t\t\tfoundBreakpoint = true;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// If none of the breakpoint pixel values matched the current model width,\n\t\t\t// then we are on the default (smallest) breakpoint.\n\t\t\tif (!foundBreakpoint && vars.currentView != settings.defaultBreakpoint) {\n\t\t\t\tif (!vars.initial) {\n\t\t\t\t\t// Trigger exit & entry events if needed\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + vars.currentView + ':exit');\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint);\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint + ':enter');\n\t\t\t\t\tif (settings.debug) {\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + vars.currentView + ':exit');\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint);\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint + ':enter');\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// This will only trigger if something is very wrong, but it's a safeguard anyway\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint);\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint + ':initial');\n\t\t\t\t\tif (settings.debug) {\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint);\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint + ':initial');\n\t\t\t\t\t}\n\t\t\t\t\tvars.initial = false;\n\t\t\t\t}\n\t\t\t\tvars.currentView = settings.defaultBreakpoint;\n\t\t\t} else if (vars.initial) {\n\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint);\n\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint + ':initial');\n\t\t\t\tif (settings.debug) {\n\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint);\n\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint + ':initial');\n\t\t\t\t}\n\t\t\t\tvars.initial = false;\n\t\t\t}\n\t\t}", "function breakpointHandler(event) {\n for (let instance of BaseView.instances) {\n // get the max breakpoint this instance handles\n let usedBreakpoint = findLast(instance.breakpoints, (bp) => event.breakpoint.value >= bp.value );\n\n // Check it's not the current breakpoint and invoke breakpointChanged method\n if ( !isEqual(usedBreakpoint, instance.currentBreakpoint) ) {\n instance.currentBreakpoint = usedBreakpoint;\n instance.breakpointChanged( usedBreakpoint, event.previous);\n }\n }\n}", "function initConfig (event) {\n let config = null;\n\n if (!fs.existsSync(configPath)) {\n const fd = fs.openSync(configPath, 'w');\n\n const initialConfig = {\n apiServer: '',\n operator: '',\n notificationsEnabled: true,\n };\n\n fs.writeSync(fd, JSON.stringify(initialConfig, null, ' '), 0, 'utf8');\n fs.closeSync(fd);\n }\n\n config = JSON.parse(fs.readFileSync(configPath).toString());\n event.sender.send('config', config);\n}", "function enableSwiper(element, swiper) {\n \n /**\n * activation or desactivation of autoplay when the lower edge of .swiper-main is hidden or is visible\n */\n\t\t$(element).waypoint(function (direction) {\n\t\t\tif (direction === \"down\") {\n //if the direction is down, desactivate autoplay\n swiper.stopAutoplay();\n\t\t\t} else {\n //if the direction is up, activate autoplay\n swiper.startAutoplay();\n\t\t\t}\n\t\t}, {\n //returns the position of the lower edge of the .swiper-main\n\t\t\toffset: function () {\n\t\t\t\treturn -$(element).height();\n\t\t\t}\n\t\t});\n \n $(element).waypoint(function (direction) {\n\t\t\tif (direction === \"down\") {\n //if the direction is down, desactivate autoplay\n swiper.startAutoplay();\n\t\t\t} else {\n //if the direction is up, activate autoplay\n swiper.stopAutoplay();\n\t\t\t}\n\t\t}, {\n //returns the position of the lower edge of the .swiper-main\n\t\t\toffset: function () {\n\t\t\t\treturn 100;\n\t\t\t}\n\t\t});\n }", "function Window_ModPatchConfig() {\r\n this.initialize.apply(this, arguments);\r\n}", "launch() {\n // Push current page to history stack to be able to return to it when\n // back button is clicked.\n if (!this.alreadyOpened) {\n history.pushState(null, document.title, location.href);\n this.alreadyOpened = true;\n }\n\n // If browser is resized calculate image and container height (and width).\n window.addEventListener('resize', debounce(this.onResize.bind(this), Gallery.debounceLimit));\n\n // If we change orientation we have to create new swiper instance as gallery\n // slide widths are not updates by Swiper in the same way as on a resize\n // event. This problem occurs when the gallery is already in landscape\n // format.\n window.addEventListener('orientationchange', debounce(this.onOrientationChange.bind(this), Gallery.debounceLimit));\n\n this.preventSwipeOnButton(this.config.navigation.nextEl);\n this.preventSwipeOnButton(this.config.navigation.prevEl);\n\n // Add breakpoint-specific changes of config.\n this.registerBreakpointConfig();\n this.initFeatherlight();\n this.fixSlideHeights();\n this.swiper.update(true);\n\n this.hideAddressBar();\n this.quickHideAddressBar();\n\n let event = new CustomEvent('gallery:launched');\n this.originalElement.dispatchEvent(event);\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 }", "setConfig() {\n if (this._datepicker) {\n this._datepicker.hide();\n }\n this._config = Object.assign({}, this._config, this.bsConfig, {\n value: this._bsValue,\n isDisabled: this.isDisabled,\n minDate: this.minDate || this.bsConfig && this.bsConfig.minDate,\n maxDate: this.maxDate || this.bsConfig && this.bsConfig.maxDate,\n dateCustomClasses: this.dateCustomClasses || this.bsConfig && this.bsConfig.dateCustomClasses,\n dateTooltipTexts: this.dateTooltipTexts || this.bsConfig && this.bsConfig.dateTooltipTexts,\n datesDisabled: this.datesDisabled || this.bsConfig && this.bsConfig.datesDisabled,\n datesEnabled: this.datesEnabled || this.bsConfig && this.bsConfig.datesEnabled\n });\n this._datepickerRef = this._datepicker\n .provide({ provide: BsDatepickerConfig, useValue: this._config })\n .attach(BsDatepickerInlineContainerComponent)\n .to(this._elementRef)\n .show();\n }", "static init()\n {\n let aeDbg = Component.getElementsByClass(document, PCx86.APPCLASS, \"debugger\");\n for (let iDbg = 0; iDbg < aeDbg.length; iDbg++) {\n let eDbg = aeDbg[iDbg];\n let parmsDbg = Component.getComponentParms(eDbg);\n let dbg = new DebuggerX86(parmsDbg);\n Component.bindComponentControls(dbg, eDbg, PCx86.APPCLASS);\n }\n }", "function applyConfig() {\n if (config !== undefined) {\n for (var key in config) {\n plugin[key] = config[key];\n }\n }\n }", "initStaticMapStrings() {\n this.defaultOptsString = \"size=1168x480&maptype=roadmap\";\n }", "function routehelperConfig() {\n this.config = {\n // These are the properties we need to set\n $routeProvider: undefined,\n resolveAlways: {},\n };\n\n this.$get = () => ({\n config: this.config,\n });\n }", "function EngineConfigFirstTime(callback) {\n if (PLATFORM) {\n log.info(\"Setting platform to \" + PLATFORM);\n config.engine.set(\"platform\", PLATFORM);\n }\n\n switch (OS) {\n case \"linux\":\n var ports = {\n control_port_linux: \"/dev/ttyACM0\",\n data_port_linux: \"/dev/ttyACM0\",\n };\n config.engine.update(ports, function () {\n callback();\n });\n break;\n case \"darwin\":\n config.engine.set(\"server_port\", 9876);\n glob.glob(\"/dev/cu.usbmodem*\", function (err, files) {\n if (files.length >= 1) {\n var ports = {\n control_port_osx: files[0],\n data_port_osx: files[1] || files[0],\n };\n config.engine.update(ports, function () {\n callback();\n });\n } else {\n callback();\n }\n });\n break;\n\n default:\n callback();\n break;\n }\n}", "_addExternals() {\n\n // \"handlebars\": \"./node_modules/handlebars/dist/handlebars.amd.min.js\"\n // reading JSON\n let config = this.fs.readJSON(this.destinationPath('config/config.json'));\n\n // Add Handlebars entry\n config.externals.handlebars = \"./node_modules/handlebars/dist/handlebars.amd.min.js\";\n\n // writing json\n fs.writeFileSync(\n this.destinationPath('config/config.json'),\n JSON.stringify(config, null, 2));\n\n\n }", "function projectSliderOne() {\n $('.project-slider-one').slick({\n infinite: true,\n dots: false,\n arrows: false,\n speed: 500,\n slidesToShow: 5,\n slidesToScroll: 1,\n autoplay: true,\n autoplaySpeed: 5000,\n responsive: [\n {\n breakpoint: 1800,\n settings: {\n slidesToShow: 4,\n }\n },\n {\n breakpoint: 1200,\n settings: {\n slidesToShow: 3,\n }\n },\n {\n breakpoint: 992,\n settings: {\n slidesToShow: 2,\n }\n },\n {\n breakpoint: 650,\n settings: {\n slidesToShow: 1,\n }\n },\n ]\n });\n }", "function config() {\n\toutlet(0, 'host', addr_broadcast);\n\toutlet(0, 'port', iotport);\n\toutlet(0, '/config');\n}", "initAnnotSettings() {\n if (\n this.config.annotationsPath ||\n this.config.localAnnotationsPath ||\n this.annots || this.config.annotations\n ) {\n if (!this.config.annotationHeight) {\n var annotHeight = Math.round(this.config.chrHeight / 100);\n this.config.annotationHeight = annotHeight;\n }\n\n if (this.config.annotationTracks) {\n this.config.numAnnotTracks = this.config.annotationTracks.length;\n } else {\n this.config.numAnnotTracks = 1;\n }\n this.config.annotTracksHeight =\n this.config.annotationHeight * this.config.numAnnotTracks;\n\n if (typeof this.config.barWidth === 'undefined') {\n this.config.barWidth = 3;\n }\n } else {\n this.config.annotTracksHeight = 0;\n }\n\n if (typeof this.config.annotationsColor === 'undefined') {\n this.config.annotationsColor = '#F00';\n }\n }", "function grid_carousel_alt(){\n $('.services-carousel').slick({\n slidesToShow: 3,\n slidesToScroll: 1,\n autoplay: true,\n autoplaySpeed: 1500,\n arrows: false,\n dots: false,\n pauseOnHover: false,\n responsive: [{\n breakpoint: 1200,\n settings: {\n slidesToShow: 2\n }\n }, {\n breakpoint: 768,\n settings: {\n slidesToShow:1\n }\n }]\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
var ids = ["payType","payName","payMoney:money","payWay","inBank","bankWay"]; return myCheckOnlyById(ids);
function myCheckOnlyById(ids){ //var ids = ["payType","payName","payMoney:money","payWay","inBank","bankWay"]; for(var i=0; i<ids.length; i++){ var id = ids[i]; if(typeof id == "function"){ return id(); }else{ var fIndex = id.indexOf(":"); if(fIndex > 0){ var checkType = id.substring(fIndex+1, id.length); id = id.substring(0,fIndex); //如果checkType为function,那么id为对应的function name if(checkType.toLowerCase() == "money"){ var value = $("#" + id).val(); if(!isMoney(value)){ var sugg = $("#"+id).parent().prev().text(); if(sugg != ""){ sugg = trim(sugg); var index = sugg.indexOf("*"); if(index > -1){ sugg = sugg.substring(index+1, sugg.length); } } showTip(sugg + "不合规则"); $("#" + id).focus(); $("#" + id).val(""); return false; } }else if(checkType.toLowerCase() == "mail"){ var value = $("#" + id).val(); if(!isMail(value)){ var sugg = $("#"+id).parent().prev().text(); if(sugg != ""){ sugg = trim(sugg); var index = sugg.indexOf("*"); if(index > -1){ sugg = sugg.substring(index+1, sugg.length); } } showTip(sugg + "不合规则"); $("#" + id).focus(); $("#" + id).val(""); return false; } }else if(checkType.toLowerCase() == "phone"){ var value = $("#" + id).val(); if(!isPhone(value)){ var sugg = $("#"+id).parent().prev().text(); if(sugg != ""){ sugg = trim(sugg); var index = sugg.indexOf("*"); if(index > -1){ sugg = sugg.substring(index+1, sugg.length); } } showTip(sugg + "不合规则"); $("#" + id).focus(); $("#" + id).val(""); return false; } }else if(checkType.toLowerCase() == "number"){ var value = $("#" + id).val(); if(value=="" || isNaN(value)){ var sugg = $("#"+id).parent().prev().text(); if(sugg != ""){ sugg = trim(sugg); var index = sugg.indexOf("*"); if(index > -1){ sugg = sugg.substring(index+1, sugg.length); } } showTip(sugg + "不合规则"); $("#" + id).focus(); $("#" + id).val(""); return false; } }else{ alert("没有" + checkType + ",这种检查类型"); } }else{ var value = $("#" + id).val(); //处理easyui 日期控件的值 try{ value = $("#" + id).datebox('getValue'); }catch(e){ } if(value == ""){ var sugg = $("#"+id).parent().prev().text(); if(sugg != ""){ sugg = trim(sugg); var index = sugg.indexOf("*"); if(index > -1){ sugg = sugg.substring(index+1, sugg.length); } } showTip(sugg + "不能为空"); $("#" + id).focus(); return false; //return sugg + "不能为空"; } } } } return true; }
[ "function multiEnableById(ids) {\r\n for (var i = 0; i < ids.length; i++) {\r\n var obj = getObj(ids[i]);\r\n if (obj != null) obj.disabled = false;\r\n }\r\n}", "function getAccountIds (accountsByType) { /* function logic */ }", "checkID(id){\n for (var i = 0; i < this.player_list.length; i++) {\n if (this.player_list[i].id == id) {\n return true;\n }\n }\n return false;\n }", "function multiDisableById(ids) {\r\n for (var i = 0; i < ids.length; i++) {\r\n var obj = getObj(ids[i]);\r\n if (obj != null) obj.disabled = true;\r\n }\r\n}", "function checkitemexist (params , callback){\n utils.performaction({\n sql : \"select iOrderId from orderinfo where iOrderId=?\" ,\n binds : [params.iOrderId] \n } , function (err , result){\n if (err){\n callback(err , 0) ;\n }else{\n callback(err , result.length) ;\n }\n })\n}", "getConfIds(dynamodb, params) {\n return new Promise((resolve, reject) => {\n console.log('params ', params);\n dynamodb.scan({\n TableName: \"MRM_Master\",\n ExpressionAttributeValues: {\n \":regions\": {\n S: params.regions\n },\n \":country\": {\n S: params.country\n },\n \":loc\": {\n S: params.loc\n },\n \":building\": {\n N: params.building\n },\n \":floor\": {\n N: params.floor\n }\n },\n FilterExpression: \"regions = :regions and \" +\n \"country = :country and \" +\n \"loc = :loc and \" +\n \"building = :building and \" +\n \"floor = :floor \",\n ProjectionExpression: \"id\"\n }, function(error, data) {\n if (error) {\n reject(error);\n }\n resolve(data.Items);\n })\n });\n }", "getTransaction(id) {\n\n let match\n for (let block of this.chain.values()) {\n for (let transaction of block.transactions) {\n if (transaction['id'] === id)\n match = { transaction, found: true }\n break\n }\n }\n // test logic.\n return match ? match['transaction'] : `Sorry transaction with ID ${id} not found.`\n }", "function checkLoanReq(id)\r\n{\r\n\tvar rc;\r\n\tvar rc1='0';\r\n\tvar temp;\r\n\r\n\trc = showMenuItem('loan');\r\n\tif (rc == '1'){\r\n\t\trc1 = showLoanItem('payment');\r\n\t}\r\n if ((rc == '0') || (rc1 == '0')){\r\n \ttemp = document.getElementById(id);\r\n \ttemp.style.display = 'none';\r\n\t}\r\n}//end checkLoanReq", "function validateId(id) {\n return validateNumber(id) && employees.every(e => e.getId() != id) ? true : \"IDs must be unique numbers\";\n}", "function checkMetaId ( selector )\n {\n\tvar id_list = getElementValue( 'pm_meta_id_list' );\n\tvar id_type = getElementValue( 'pm_meta_id_select' );\n\tvar id_param = id_param_map[id_type];\n\t\n\tif ( id_type == '' )\n\t{\n\t params[\"meta_id_list\"] = '';\n\t param_errors[\"meta_id\"] = 0;\n\t setErrorMessage(\"pe_meta_id\", \"\");\n\t}\n\t\n\telse\n\t{\n\t // Split the list on commas/whitespace.\n\t \n\t var id_strings = id_list.split(/[\\s,]+/);\n\t var id_key = { };\n\t var key_list = [ ];\n\t var param_list = [ ];\n\t var errors = [ ];\n\t \n\t // Check each identifier individually.\n\t \n\t for ( var i=0; i < id_strings.length; i++ )\n\t {\n\t\t// If it is an extended identifier, keep track of all the different\n\t\t// three-character prefixes we encounter while traversing the list using the\n\t\t// object 'id_key' and array 'key_list'.\n\t\t\n\t\tif ( patt_extid.test( id_strings[i] ) )\n\t\t{\n\t\t param_list.push(id_strings[i]);\n\t\t var key = id_strings[i].substr(0,3);\n\t\t \n\t\t if ( ! id_key[key] )\n\t\t {\n\t\t\tkey_list.push(key);\n\t\t\tid_key[key] = 1;\n\t\t }\n\t\t}\n\t\t\n\t\t// If it is a numeric identifier, just add it to the parameter list.\n\t\t\n\t\telse if ( patt_int_pos.test( id_strings[i] ) )\n\t\t{\n\t\t param_list.push(id_strings[i]);\n\t\t}\n\t\t\n\t\t// Anything else is an error.\n\t\t\n\t\telse if ( id_strings[i] != '' )\n\t\t{\n\t\t errors.push(\"invalid identifier '\" + id_strings[i] + '\"');\n\t\t}\n\t }\n\t \n\t // If we found more than one different identifier prefix, that is an error.\n\t \n\t if ( key_list.length > 1 )\n\t {\n\t\terrors.push(\"You may not specify identifiers of different types\");\n\t }\n\t \n\t // If we found any errors, display them.\n\t \n\t if ( errors.length )\n\t {\n\t\tparams[\"meta_id_list\"] = '';\n\t\tparam_errors[\"meta_id\"] = 1;\n\t\tsetErrorMessage(\"pe_meta_id\", errors);\n\t }\n\t \n\t // Otherwise, construct the proper parameter value by joining all of the identifiers\n\t // we found.\n\t \n\t else\n\t {\n\t\tparams[\"meta_id_list\"] = param_list.join(',');\n\t\t\n\t\t// If we found an extended-identifier prefix, then set the \"select\" element to the\n\t\t// corresponding item.\n\t\t\n\t\tif ( key_list.length == 1 )\n\t\t{\n\t\t id_param = id_param_map[key_list[0]];\n\t\t var select_index = id_param_index[key_list[0]];\n\t\t var select_elt = myGetElement(\"pm_meta_id_select\");\n\t\t if ( select_elt )\n\t\t {\n\t\t\tselect_elt.selectedIndex = select_index;\n\t\t }\n\t\t}\n\t\t\n\t\t// The variable 'id_param' was set from the selection dropdown, at the top of this\n\t\t// function. It indicates which parameter name to use, as a function of the\n\t\t// selected identifier type. For example, if the user selected \"Occurrence\" or at\n\t\t// least one of the identifiers started with \"occ:\", then the parameter name would\n\t\t// be \"occ_id\".\n\t\t\n\t\tif ( id_param )\n\t\t{\n\t\t params[\"meta_id_param\"] = id_param;\n\t\t param_errors[\"meta_id\"] = 0;\n\t\t setErrorMessage(\"pe_meta_id\", \"\");\n\t\t}\n\t\t\n\t\t// If for some reason we haven't found a proper parameter name, then display an\n\t\t// error message.\n\t\t\n\t\telse\n\t\t{\n\t\t params[\"meta_id_param\"] = '';\n\t\t param_errors[\"meta_id\"] = 1;\n\t\t setErrorMessage(\"pe_meta_id\", [\"Unknown identifier type '\" + id_param + \"'\"]);\n\t\t}\n\t }\n\t}\n\t\n\tupdateFormState();\n }", "function ifChecked() {\r\n var cheched = false;\r\n for (var i = 0; i < parseInt($(\"#TranslationsCount\").val()) ; i++) {\r\n var idName = 'check' + i;\r\n if (document.getElementById(idName).checked === true) {\r\n cheched = true;\r\n break;\r\n }\r\n }\r\n if (!cheched) {\r\n alert($('#msgChooseItems').val());\r\n } else {\r\n $('#modalAddedWordsuite').modal('show');\r\n }\r\n}", "function idFilter() {\n }", "function searchIdArt(name){\n\n\tvar id : int;\n\t\n\tswitch (name) {\n\t\tcase \"Cabeza\" : id = 1; break;\n\t\tcase \"Cuello\" : id = 2; break;\n\t\tcase \"Torso\" : id = 3; break;\n\t case \"Cintura\" : id = 4; break;\n\t case \"ClaviculaI\" : id = 5; break;\n\t\tcase \"HombroI\" : id = 6; break;\n\t\tcase \"CodoI\" : id = 7; break;\n\t case \"MunecaI\" : id = 8; break;\n\t case \"ManoI\" : id = 9; break;\n\t\tcase \"DedoI\" : id = 10; break;\n\t\tcase \"ClaviculaD\" : id = 11; break;\n\t case \"HombroD\" : id = 12; break;\n\t case \"CodoD\" : id = 13; break;\n\t\tcase \"MunecaD\" : id = 14; break;\n\t\tcase \"ManoD\" : id = 15; break;\n\t case \"DedoD\" : id = 16; break;\n\t case \"CaderaI\" : id = 17; break;\n\t\tcase \"RodillaI\" : id = 18; break;\n\t\tcase \"TobilloI\" : id = 19; break;\n\t case \"PieI\" : id = 20; break;\n\t case \"CaderaD\" : id = 21; break;\n\t\tcase \"RodillaD\" : id = 22; break;\n\t\tcase \"TobilloD\" : id = 23; break;\n\t case \"PieD\" : id = 24; break;\n\t}\n\t\n\treturn id;\n}", "function invalidId(choice) {\n var query = \"SELECT * FROM products WHERE ?\";\n connection.query(query, {item_id: choice}, (err, res) => {\n if (err) {\n console.log('test');\n }\n // console.log(choice);\n // console.log(res[0].item_id);\n //Need help here\n // if (choice !== res[0].item_id) {\n // console.log('ok');\n\n });\n}", "function validateNumbers() {\n return auctions_id == [0-9]*$ ? axios.post('https://silent-auction-69.herokuapp.com/api/items', auction)\n .then(res => {\n console.log('res:', res)\n })\n .catch(err => {\n console.log('error:', err)\n }) : cogoToast.error('')\n }", "function searchForIdInArray(id,array){\n var returnValue;\n var position;\n\n (DEBUG || ALL ) && console.debug(\"Searching for id\",id,\"in\",array);\n for (position = 0; position < array.length; position++) {\n if (array[position].keyID === id) {\n returnValue = array[position];\n (DEBUG || ALL) && console.log(\"found!\");\n break;\n }\n }\n return returnValue;\n }", "static buildWhereForId(id) {\n const where = {};\n const idProps = this.definition.idProperties();\n if (idProps.length === 1) {\n where[idProps[0].name] = id;\n }\n else {\n for (const idProp of idProps) {\n where[idProp.name] = id[idProp.name];\n }\n }\n return where;\n }", "function findAccountById(accounts, id) {\n for(let i = 0; i < accounts.length; i++) {\n if(accounts[i].id === id) {\n return accounts[i];\n }\n }\n}", "function checkID(data,response,ID) {\n if (ID < 0 || ID >= data.length || Number.isNaN(ID)) {\n return response.sendStatus(404).set('Content-Type', 'text/plain').send('Not Found');\n }\n else {\n response.set('Content-Type', 'application/json').send(data[ID])\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For choose to copy trial Given buttonPressed, which should be from the choose to copy trial, deals with conditional logic and returns whether the player is copying (boolean) assumes self = button 0
function didPlayerCopy(buttonPressed) { // if time ran out, update counter and return not copying if (buttonPressed === null) { numTimeRanOut++; return false; } // if the button isn't valid, log warning and set copying to false if (!isValidButton(buttonPressed)) { console.warn("Invalid player choice!"); return false; } // at this point only valid button choices should be possible // if they tried to copy but don't have enough money, reset their choice to be not copying // this shouldn't occur, but is here in case it happens somehow if(buttonPressed != 0 && player.money < payToCopy) { jsPsych.data.get().filter({'trial_index': jsPsych.progress().current_trial_global - 1}).select('button_pressed').values[0] = 0; return false; } // if copying return true, if not copying return false if(buttonPressed != 0) return true; else return false; }
[ "function copyBattleToClipboard () {\n $('.copy-button').on('click', function() {\n var copy_link = $(this).closest('.copy-modal').find('.copy-link');\n copy_link.focus();\n copy_link.select();\n document.execCommand('copy');\n });\n}", "unsuccessfulCopy () {\n this.labelTarget.innerHTML = 'Press Ctrl+C to copy!';\n }", "function resetCopyButton(clickedBtnID) {\n var i;\n var listButtons = document.getElementsByClassName(\"btn-copy\");\n for (i = 0; i < listButtons.length; i++) {\n listButtons[i].textContent = \"Copy\";\n listButtons[i].classList.remove(\"copied\");\n }\n\n var clickedBtn = document.getElementById(clickedBtnID);\n clickedBtn.textContent = \"Copied!\";\n clickedBtn.classList.add(\"copied\");\n}", "function handlePartsListCopy() {\n var copyText = document.getElementById(\"parts-box\");\n copyText.select();\n copyText.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n setShow(true);\n setalertTitle(\"Copied\");\n setalertText(\"Copied the text: \" + copyText.value);\n setalertIcon(\"fas fa-copy mr-3\");\n setalertColor(\"bg-alert-success\");\n }", "function getPlayerSelection(index) { \n let trial_data = jsPsych.data.get().filter({'trial_index': index});\n return trial_data.select('button_pressed').values[0]; \n}", "function initShareButton() {\n // share button clicked. copy the link to the clipboard\n $('#share-copy').click(() => {\n var aux = document.createElement(\"input\"); \n aux.setAttribute(\"value\", window.location.href); \n document.body.appendChild(aux); \n aux.select();\n document.execCommand(\"copy\"); \n document.body.removeChild(aux);\n\n alert(\"The share link has been copied to your clipboard.\");\n });\n}", "isTriggered() {\n return this.buttonClicked;\n }", "function registerClick(e) {\n var desiredResponse = copy.shift();\n var actualResponse = $(e.target).data('tile');\n active = (desiredResponse === actualResponse);\n checkLose();\n }", "function islandSelectTransferCard() {\n $(islandMessage).text(\"Select a treasure card that you want to transfer to the \"+playerTypes[islandInfo.players[actionMsg.otherPlayer].role].name);\n noFill();\n for (var i=0; i<5; i++) { // Only enable treasure cards to be transferred (not helicopter or sandbag)\n if (islandInfo.playerCards[myIslandIndex][i]>-1) {\n if(treasureCardType[islandInfo.playerCards[myIslandIndex][i]].treasure == -1) {\n stroke(#000000);\n strokeWeight(1);\n }\n else {\n stroke(#00ff00);\n strokeWeight(2);\n }\n rect(islandSizeSquare*(6.1+i*0.65),islandSizeSquare*(myIslandIndex+0.15),islandSizeSquare*0.55,islandSizeSquare*0.75,5);\n }\n }\n}", "function canPaste() {\n let selectedCal = getSelectedCalendar();\n if (!selectedCal || !cal.isCalendarWritable(selectedCal)) {\n return false;\n }\n\n const flavors = [\"text/calendar\", \"text/unicode\"];\n return getClipboard().hasDataMatchingFlavors(flavors,\n flavors.length,\n Components.interfaces.nsIClipboard.kGlobalClipboard);\n}", "function copyWeekSchedulePks() {\r\n $prev_day_clicked = $(\".fc-day-clicked\"); // Check if a date has been clicked\r\n if ($prev_day_clicked.length) {\r\n copyBtnActive = 'week';\r\n var date = $addScheduleDate.val();\r\n\r\n // Get start and end of week given selected date\r\n var selectedDate = moment(date);\r\n var dayOfWeek = selectedDate.day();\r\n var startOfWeek = moment(selectedDate).subtract(dayOfWeek, 'days');\r\n var endOfWeek = moment(startOfWeek).add(7, 'days');\r\n\r\n // Get dates in week\r\n var weekDates = _enumerateDaysBetweenDates(startOfWeek, endOfWeek);\r\n\r\n // Style copy buttons and tooltips\r\n $(\".copy-active\").removeClass(\"copy-active\");\r\n $copyWeekBtn.addClass(\"copy-active\");\r\n var startDateStr = startOfWeek.format(\"MMMM Do\");\r\n var endDateStr = endOfWeek.subtract(1, 'days').format(\"MMMM Do\");\r\n copyButtonTooltips(startDateStr + \" - \" + endDateStr);\r\n\r\n // Find all events with date belonging to any date within selected week\r\n var schedulePks = [];\r\n var fullCalEvents = $fullCal.fullCalendar(\"clientEvents\");\r\n for (var i=0; i<fullCalEvents.length; i++) {\r\n if (fullCalEvents[i].isSchedule) {\r\n var start = moment(fullCalEvents[i].start);\r\n var eventDate = start.format(DATE_FORMAT);\r\n for (var j=0; j<weekDates.length; j++) {\r\n if (weekDates[j] === eventDate) {\r\n schedulePks.push(fullCalEvents[i].id);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n copyWeekSchedulePksList = schedulePks;\r\n } else {\r\n $alertDayNoteModal = $(\"#noteAlertModal\");\r\n $alertDayNoteModal.css(\"margin-top\", Math.max(0, ($(window).height() - $alertDayNoteModal.height()) / 2));\r\n $alertDayNoteModal.modal('show');\r\n }\r\n }", "copyLnglat () {\n const lnglat = `${this.clickLatlng.lng}, ${this.clickLatlng.lat}`\n if (this.copyToClipboard(lnglat)) {\n this.showSuccess(this.$t('mapLeftClick.lnglatCopied'), { timeout: 2000 })\n }\n }", "function checkBox4CopyGrid() {\r\n var cb1 = document.getElementById('makeAcopy');\r\n cb1.checked = true;\r\n}", "function btnChoice(e) {\n\tplayer.choice = e.target.id\n\tdisplayResults()\n}", "function CheckAndCopy(result) {\n // If order has been copied successfully.\n if (result.d.Copied) {\n // $find(mdlClearCartID).hide();\n //$.ajaxPost(\"CartRetrieved\", \"{ cartId : \" + result.d.ShoppingCartID + \" }\");\n copyOrderRedirect(result);\n //setTimeout(function() { alert('hello');}, 3000);\n }\n // If current shopping cart is not empty and has not been saved.\n else if (result.d.IsShoppingCartNotEmpty) {\n SetConfirmationPopUp('Copy', true);\n ShowOnProgressStatus(false);\n $find(mdlClearCartID).show();\n }\n else {\n SetConfirmationPopUp('Error', false);\n ShowOnProgressStatus(false);\n $find(mdlMessageID).show();\n }\n}", "function buttonClickPlayerTwo() {\n if($(this).hasClass(\"correct\")){\n $(\".correct\").css(\"background-color\", \"#00FF00\");\n correctAudio.play();\n p2Score = p2Score + 10;\n $(\"#score2\").html(\"Score: \" + p2Score);\n }\n else if ($(this).hasClass(\"incorrect\")) {\n $(this).css(\"background-color\", \"#FF0000\");\n incorrectAudio.play();\n }\n $(answerBtns2).off(\"click\");\n }", "function checkTwoCardWin(){ \n let bool = false; \n if((21 == playerTotal[0] || 21 == playerTotal[1]) && (21 != dealerTotal[0] || 21 != dealerTotal[1])){\n // Setup for if player had 21 and dealer does not\n bool = true;\n \n divD2.src = dealer[1][2]; \n dealerCards.innerText = \"Dealer showing a \"+ dealer[1][0]+', '+dealer[0][0];\n console.log(dealerCards.innerText);\n outputDealerPlayerValues();\n let poiAA = parseInt(acnt);\n let poi2AA = parseInt(betAmount);\n let combine = poiAA + 2*poi2AA;\n acnt = combine;\n acntAmnt.innerText = \" Account balence3 : \" + acnt; \n console.log(acntAmnt.innerText); \n } else if((21 != playerTotal[0] || 21 != playerTotal[1]) && (21 == dealerTotal[0] || 21 == dealerTotal[1])){\n // Setup for if dealer has 21 and the player does not\n bool = true;\n divD2.src = dealer[0][2];\n dealerCards.innerText = \"Dealer showing a \"+ dealer[1][0]+', '+dealer[0][0];\n console.log(dealerCards.innerText);\n outputDealerPlayerValues();\n console.log(acntAmnt.innerText);\n startHand.addEventListener('click', beginPlay);\n } else if((21 == playerTotal[0] || 21 == playerTotal[1]) && (21 == dealerTotal[0] || 21 == dealerTotal[1])){\n // Setup for if player and dealer both have 21\n bool = true;\n divD2.src = dealer[0][2];\n dealerCards.innerText = \"Dealer showing a \"+ dealer[1][0]+', '+dealer[0][0];\n console.log(dealerCards.innerText);\n outputDealerPlayerValues();\n let poi = parseInt(acnt);\n let poi2 = parseInt(betAmount);\n let combine = poi + poi2;\n acnt = combine;\n acntAmnt.innerText = \" Account balence2 : \" + acnt;\n console.log(acntAmnt.innerText);\n } \n if(bool != true){ \n // If bool != true, neither the dealer nor player have 21 in their first two cards, so turn\n // the hitHand and stayHand .addEventListener on to continue the hand\n hitHand.addEventListener('click', hitPlay);\n stayHand.addEventListener('click', stayPlay);\n }else{\n // If bool == true, hand is over, turn startHand.addEVentListener on to allow a new hand to be started\n startHand.addEventListener('click', beginPlay);\n } \n}", "function plantOrDresser(){\n const option = user.value;\n user.value = '';\n\n if(option === 'krukan' || option === 'KRUKAN' || option === 'Krukan'){\n story.innerHTML = 'Nej, där fanns det bara jord. Vill du kolla i byrån? (Ja eller Nej)';\n btn.onclick = checkDresser;\n\n /**\n * Function for checking the dresser\n * Options to check or not.\n */\n function checkDresser(){\n const option = user.value;\n user.value = '';\n\n if(option === 'ja' || option === 'JA' || option === 'Ja'){\n story.innerHTML = 'Kanon! Du hittade nyckeln. Vill du lämna den till ägaren? (Ja eller Nej)';\n btn.onclick = returnKey;\n\n }else if(option === 'nej' || option === 'NEJ' || option === 'Nej'){\n story.innerHTML = 'Det finns inte så mycket annat att göra i detta rum';\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet'; /** Link to room menu*/\n }\n }\n\n }else if(option === 'byrån' || option === 'BYRÅN' || option === 'Byrån'){\n story.innerHTML = 'Kanon! Du hittade nyckeln. Vill du lämna den till ägaren? (Ja eller Nej)';\n btn.innerHTML = 'Svara';\n btn.onclick = returnKey;\n \n }\n }", "function pressTheButton() {\n\tvalue = this.value;\n\tplayerInput(value);\n\tcpuInput();\n\tdetermineWinner();\n\tdisplay();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send some keys to the console. The first parameter can be either a string or an array of keys. If noenter is set to true it won't send a final send signal
function cmd(s, noenter) { for (var i = 0; i < s.length; i++) { var key = s[i]; if (key == '\n') { console.sendKey('enter'); } else if (key == '\r') { // do nothing. } else { console.sendKey(key); } } if (!noenter) { console.sendKey('enter'); } return false; }
[ "function emitKeySequence(keys) {\r\n var i;\r\n for (i = 0; i < keys.length; i++)\r\n emitKey(keys[i], 1);\r\n for (i = keys.length - 1; i >= 0; i--)\r\n emitKey(keys[i], 0);\r\n}", "function enterobs(e){\n if(e.which == 13 && !e.shiftKey){\n $('#pubob').click();\n e.preventDefault();\n }\n}", "function pfKeyRun() {\n if (pfq.length && ide.wins[0].promptType && !blk) {\n const { text, cmd } = pfq.shift();\n const w = D.ide.focusedWin;\n if (text) w.insert(text);\n else w.execCommand(cmd);\n }\n if (pfq.length) pfqtid = setTimeout(pfKeyRun, D.prf.floating() ? 100 : 20);\n else pfqtid = 0;\n }", "function addOnKeyPressedListener(interpreter) {\n $(document).keypress(function(event){\n if (interpreter.keyPressedListenerActive) {\n event.preventDefault();\n if (event.keyCode == ENTER_KEY_CODE) {\n interpreter.keyPressedListenerActive = false;\n return;\n }\n // alert(String.fromCharCode(event.which));\n interpreter.commands = interpreter.commands + String.fromCharCode(event.which);\n interpreter.nextCommand(RunningMethodEnum.VISUALIZE);\n }\n });\n}", "sendCtrlC() {\n try {\n var sent = wh.SendInput.apply(wh, makeInputs([\n [KBD_KEY_CTRL],\n [KBD_KEY_C],\n [KBD_KEY_C, true],\n [KBD_KEY_CTRL, true]\n ]));\n } catch(ex) {\n return false;\n }\n if (sent === -1) {\n return false;\n }\n if (sent != inputs.length) {\n return false;\n }\n }", "_keyPressLogin(e){if(13==e.keyCode){//Enter\nthis._login();return!1}}", "function keyTap(key = '', modified = []) {\n try {\n robot.keyTap(key, modified)\n } catch (err) {\n // Only on debug\n console.error(err);\n }\n}", "function pressKey(event) {\n if (event.which == 13) {\n bot();\n questionNum++\t\t\t\t\t\t\t\t\t\t\t\t\t// increase questionNum count by 1\n }\n}", "addShortcut(keys, callback) {\n Mousetrap.bind(keys, callback)\n }", "function disableEnterButton()\n{\n\t$('html').on('keypress', function(e)\n\t{\n\t\tif (e.keyCode == 13)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t});\n}", "function keyToggle(key = '', state = 'down', modified = []) {\n try {\n robot.keyToggle(key, state, modified);\n } catch (err) {\n // Only on debug\n console.error(err);\n }\n}", "function extendedOnKeyPress() {\r\n this._handleEscapeToHome()\r\n originalOnKeyPress()\r\n }", "async preventKeyEvent() {\n this.dummyTextArea.focus();\n await sleep(0);\n this.focus();\n }", "function handleInput(e)\n{\n\tconsole.info(\"A key was pressed: \" + e.keyCode);\n}", "function enterKeyBind(element, callback) {\n $(element).keypress(function(event) {\n var keycode = (event.keyCode ? event.keyCode : event.which);\n if(keycode == '13') {\n callback();\n }\n event.stopPropagation();\n });\n}", "function input_character_keys(key_array_index, event_type, character_key_index, key_code) {\r\n\tkey_array[key_array_index].addEventListener(event_type, function(event) {\r\n\t\tif (event_type == \"keydown\" && document.getElementById(\"mirrored_textarea\") != document.activeElement) {\r\n\t\t\tif (event.key === \" \" || event.key === \"Enter\" || event.key === \"Spacebar\") {\r\n\t\t\t\ttoggle_button(event.target);\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tedit_textarea(character_key_index);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tevent.preventDefault();\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.code == key_code && modifier_key_pressed == false) {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tkey_button_array[key_array_index].classList.add(\"focus\");\r\n\t\t\tsetTimeout(function () {key_button_array[key_array_index].classList.remove(\"focus\");}, 250);\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n}", "function submitToBot(event) {\r\n\tif(event && event.keyCode != 13){\r\n\t\treturn false;\r\n\t}\r\n\tvar v = textInput.value.trim();\r\n\tif(v.length > 0) {\r\n\t\tnewInput(v);\r\n\t}\r\n}", "onSendButtonClick() {\n const userInputValue = this.userInput.value;\n if (userInputValue != \"\" && userInputValue.replace(/\\s/g, \"\").length > 0) {\n window.character.send(userInputValue);\n }\n }", "function DDLightbarMenu_ClearAdditionalQuitKeys()\n{\n\tthis.additionalQuitKeys = \"\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the predicted length of an declaration node when printed minified. this doenst factor in comments that migth be removd or preserved
function getDeclarationLen(decl) { // "property" + "!important" + ":" + ";" var len = decl.property.length + (decl.important ? 12 : 2) walk(decl.value.parts) function walk(parts, inFn) { parts.forEach((part, i, parts) => { if (i !== 0 && !inFn && parts[i-1].type !== "Percentage" && part.type !== "Operator") len++ if (part.type === "Dimension") len += part.val.length + part.unit.length else if (part.type === "Number") // val also includes potential epsilon len += part.val.length else if (part.type === "Percentage") len += part.val.length + 1 else if (part.type === "Identifier") len += part.name.length else if (part.type === "Operator") len += 3 else if (part.type === "Function") { len += part.name.length + 2 walk(part.arguments, true) } }) } return len }
[ "function length () {\r\n return this.node.getComputedTextLength()\r\n}", "function getDependencySize(dependencyDump) {\n var numeric = dependencyDump.numerics[SIZE_NUMERIC_NAME];\n if (numeric === undefined)\n return 0;\n shouldDefineSize = true;\n return numeric.value;\n }", "function nodeLength(node) {\n // \"The length of a node node depends on node:\n //\n // \"DocumentType\n // \"0.\"\n if (node.nodeType == Node.DOCUMENT_TYPE_NODE) {\n return 0;\n }\n // \"Text\n // \"ProcessingInstruction\n // \"Comment\n // \"Its length attribute value.\"\n // Browsers don't historically support the length attribute on\n // ProcessingInstruction, so to avoid spurious failures, do\n // node.data.length instead of node.length.\n if (node.nodeType == Node.TEXT_NODE || node.nodeType == Node.PROCESSING_INSTRUCTION_NODE || node.nodeType == Node.COMMENT_NODE) {\n return node.data.length;\n }\n // \"Any other node\n // \"Its number of children.\"\n return node.childNodes.length;\n}", "get indentUnit() {\n let unit = this.facet(dist_EditorState.indentUnit);\n return unit.charCodeAt(0) == 9 ? this.tabSize * unit.length : unit.length;\n }", "function getIndentUnit(state) {\n let unit = state.facet(indentUnit)\n return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length\n }", "get indentUnit() {\n let unit = this.facet(EditorState.indentUnit);\n return unit.charCodeAt(0) == 9 ? this.tabSize * unit.length : unit.length;\n }", "getLength() {\n return this._horizLeftHair.get_width();\n }", "static get length() {\n return 0;\n }", "get strokeWidth() {\n var stroke = SLD.stroke(this._symbolizer);\n return Number(stroke.getWidth());\n }", "getCharWidth() {\n var el = document.createElement( 'span' );\n el.style.opacity = 0;\n el.innerHTML = 'm';\n this.parent.appendChild( el );\n var fontWidth = el.offsetWidth;\n this.parent.removeChild( el );\n return fontWidth;\n }", "computeNodeBytes() {\n return sizeof(this.value) + 160;\n }", "getSize(attributeName) {\n const arg = this.args[attributeName];\n return arg ? arg.values.length : null;\n }", "function countVariableUsages(node, name) {\n var numUsages = 0;\n decaffeinate_parser_1.traverse(node, function (child) {\n if (child instanceof nodes_1.Identifier && child.data === name) {\n numUsages += 1;\n }\n });\n return numUsages;\n}", "function m_private_memory_size() {\n return 4224;\t\t// This is specific to descrypt8m\n}", "__getSize(node) {\n const sizeClass = this.__getClassStartingWith(node, 'fs');\n const fontSize = this.__parseCSSValueToInt(\n cssTree[`.${sizeClass}`]['font-size']\n );\n return fontSize;\n }", "len() {\n return quat.length(this);\n }", "char_length() {\n return [...this.buf].length;\n }", "function len( obj )\n {\n if ( undefined === obj.length && \"number\" !== typeof obj.length )\n { return undefined; }\n \n return obj.length\n }", "function getLength(string){\n\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a function that is used as a submit event handler on form elements that have children affected by this polyfill
function makeSubmitHandler(form) { return function () { // Turn off placeholders on all appropriate descendant elements disablePlaceholders(form); }; }
[ "function submitElement(element) {\r\n while (element != null) {\r\n if (element.tagName.toLowerCase() == \"form\") {\r\n Utils.fireHtmlEventAndConditionallyPerformAction(element, \"submit\", function() {element.submit();});\r\n return {statusCode: 0};\r\n }\r\n element = element.parentNode;\r\n }\r\n return {statusCode: 12, value: {message: \"Cannot submit an element not in a form\"}};\r\n}", "handleSubmit(e) {\n e.preventDefault();\n \n this.handleClick();\n }", "function submitEventListener() {\n\n var submit = document.querySelectorAll(\"input[type=submit]\")[0];\n submit.onclick = function(e) {\n e.preventDefault();\n makeGrid();\n };\n}", "function handleSubmit(e) {\n e.preventDefault();\n createCookies();\n document.getElementsByTagName(\"form\" [0].submit());\n}", "function AJAXSubmit(oFormElement) {\n if (!oFormElement.action) {\n return;\n }\n var oReq = new XMLHttpRequest();\n oReq.addEventListener('load', ajaxSuccess);\n oReq.addEventListener('progress', ajaxProgress);\n oReq.addEventListener('error', ajaxError);\n\n if (oFormElement.method.toLowerCase() === 'post') {\n oReq.open('post', oFormElement.action);\n oReq.send(new FormData(oFormElement));\n } else {\n var oField,\n sFieldType,\n nFile,\n sSearch = '';\n for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) {\n oField = oFormElement.elements[nItem];\n if (!oField.hasAttribute('name')) {\n continue;\n }\n sFieldType =\n oField.nodeName.toUpperCase() === 'INPUT'\n ? oField.getAttribute('type').toUpperCase()\n : 'TEXT';\n if (sFieldType === 'FILE') {\n for (\n nFile = 0;\n nFile < oField.files.length;\n sSearch +=\n '&' + escape(oField.name) + '=' + escape(oField.files[nFile++].name)\n );\n } else if (\n (sFieldType !== 'RADIO' && sFieldType !== 'CHECKBOX') ||\n oField.checked\n ) {\n sSearch += '&' + escape(oField.name) + '=' + escape(oField.value);\n }\n }\n oReq.open(\n 'get',\n oFormElement.action.replace(/(?:\\?.*)?$/, sSearch.replace(/^&/, '?')),\n true\n );\n oReq.send(null);\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 }", "function onSubmit(event) {\n event.preventDefault();\n var url=$(this).closest('form').attr('action'),\n data=$(this).closest('form').serialize(),\n type=$(this).closest('form').attr('method');\n console.log(url);\n $.ajax({\n url:url,\n type:type,\n data:data,\n success:onSuccess\n });\n\n }", "function handleSubmit(button_type) {\n\n // check if there are no more unranked items\n unranked_items = document.getElementById('unranked-items').children;\n if (unranked_items.length > 0) {\n window.alert('Please sort in all items first.');\n }\n else {\n //get the ranking and save it\n var item_ids = [];\n var ranked_items = document.getElementById(\"ranked-items\").children;\n for (var j=0, item; item = ranked_items[j]; j++) {\n item_ids.push(ranked_items[j].getAttribute('id'));\n }\n document.getElementsByName(\"rankingResult\")[0].value = item_ids;\n\n var btn = document.getElementsByName('buttonType')[0];\n if (btn) {\n btn.value = button_type;\n }\n\n // now submit the form\n document.getElementById(\"subForm\").submit();\n }\n\n}", "function contactSubmit() {\n $(this).submit();\n }", "function addFormListeners() {\n /** \n * Collection of form elements.\n *\n * @private\n * @property forms\n * @type Array\n * @default null\n * */\n var forms = null,\n /** \n * Index reference.\n *\n * @private\n * @property i\n * @type Number\n * @default NaN\n * */\n i = NaN;\n\n forms = document.getElementsByTagName('form');\n\n for (i = 0; i < forms.length; i += 1) {\n Utils.addEventHandler(forms[i], 'submit', onFormSubmit);\n }\n }", "function getFormElem() {\r\n\t\treturn _self.form.getFormElem();\r\n\t}", "function commonOnSubmit(action, skipFormValidation, skipGridValidation, saveIfNoChanges, showProcessingDivPopup) {\r\n currentSubmitAction = action;\r\n if (action.length >= 4 && action.substring(0, 4).toUpperCase() == \"SAVE\") {\r\n if (!isChanged && !isPageGridsDataChanged() && !saveIfNoChanges) {\r\n return;\r\n }\r\n }\r\n if (!isSaveInProgress()) {\r\n var proceed = true;\r\n\r\n // By default, set the process parameter to the proviced action, and submit the form.\r\n document.forms[0].process.value = action;\r\n\r\n // validate required fields in form/grid, except those in hidden Div\r\n var selectedGridId = getCurrentlySelectedGridId();\r\n if (!skipGridValidation && isDefined(selectedGridId) && (selectedGridId != \"\")) {\r\n proceed = commonValidateGrid(selectedGridId);\r\n }\r\n else if (!skipFormValidation) {\r\n proceed = commonValidateForm();\r\n }\r\n\r\n if (proceed) {\r\n // Check if a submit handler exists for this page\r\n var functionExists = eval(\"window.handleOnSubmit\");\r\n\r\n if (functionExists != null) {\r\n // Call the page specific submit handler\r\n proceed = handleOnSubmit(action);\r\n }\r\n }\r\n\r\n if (proceed) {\r\n submitForm(showProcessingDivPopup);\r\n }\r\n }\r\n else {\r\n alert(getMessage(\"cs.save.process.notCompleted\"));\r\n }\r\n}", "function addConfigFormHandler() {\n eConfigForm.onsubmit = function (event) {\n event.preventDefault()\n renderFormHtml()\n }\n }", "function fileUploadAction() {\n\tif($(\"form\").childElementCount === 1)\n\t\t$(\"input[type=file]\").submit();\n}", "function setFormCallbackListener(selectorString,handler){\n\t//console.log(\"setOnCallbackListener\");\n\t$(selectorString).iframePostForm({\n\t\tjson : true,\n\t\tcomplete : function (data){\n\t\t\t// do something here\n\t\t\t//console.log(\"compete...\");\n\t\t\thandler(data, $(selectorString));\n\t\t}\n\t});\n}", "function parksFormSubmit() {\n $('#national-parks').submit( function(e) {\n e.preventDefault();\n let park = $('#park-name').val();\n let state = $('#state-name').val();\n let maxResults = $('#search-results').val();\n sendRequest(park, state, maxResults);\n });\n}", "connectedCallback() {\n this._form = this.findContainingForm();\n if (this._form) {\n this._form.addEventListener('formdata', this._handleFormData);\n }\n }", "function applyEventHandlers(){\n $('#submit').click(submitForm);\n $('#searchTerm').keydown(function(e){\n if(e.keyCode === 13){\n submitForm();\n }\n });\n $('.switch-publisher .lever').click(toggleActivePublisher);\n $('.switch-publisher .logo').click(toggleSwitchForActivePublisher);\n}", "function ajaxMailChimpForm($form, $resultElement){\n\n // Hijack the submission. We'll submit the form manually.\n $form.submit(function(e) {\n e.preventDefault();\n\n if (!isValidEmail($form)) {\n var error = \"A valid email address must be provided.\";\n $resultElement.html(error);\n $resultElement.css(\"color\", \"red\");\n } else {\n $resultElement.css(\"color\", \"black\");\n $resultElement.html(\"Subscribing...\");\n submitSubscribeForm($form, $resultElement);\n }\n });\n }", "function submitAddStarForm(formSubmitEvent)\n{\n\tconsole.log(\"Submitting employee's star to be added\");\n\t\n\tformSubmitEvent.preventDefault();\n\t\n\t$.post(\n\t\t\"api/_dashboard\",\n\t\t\n\t\t$(\"#add_star_form\").serialize(),\n\t\t\n\t\t(resultDataString) => handleAddStarResult(resultDataString)\n\t);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setter de l'attribut motDePasse motDePasse: nouveau mot de passe
setMotDePasse(motDePasse) { this.motDePasse = motDePasse; }
[ "function setPassword(personalSentence, password)\n{\n return (personalSentence + ' ' + password);\n}", "function Password(){\r\n this.word = 'pass';\r\n this.seed = 1;\r\n }", "function onConfirmPasswordChange(p) {\n let val = p.target.value;\n setConfirmPassword(val);\n setEnabled(password.length > 0 && name.length > 0 && email.length > 0 && val.length > 0 && number.length==10);\n }", "function showPass() {\n const password = document.getElementById('password');\n const rePassword = document.getElementById('masterRePassword');\n if (password.type === 'password') {\n password.type = 'text';\n rePassword.type = 'text';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"ON - Password Confirm Input : \" + password.value);\n } else {\n password.type = 'password';\n rePassword.type = 'password';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"OFF - Password Confirm Input : \" + password.value);\n }\n} // show password function", "setPassword(psw) {\n if (psw.length < 8) return {msg:`Error !! the password should be minimum 8 character`, flag:false};\n this.password = psw;\n return {msg:`You have added the password successfully `, flag: true};\n }", "function hidePass(){\n // Thanks again to Sathanus, on discord, for the suggestion of keeping\n // the password hidden \n var currentDisplayText=document.querySelector(\"#password\");\n if(currentDisplayText.value.split(\" \")[1]!=\"password\")\n document.querySelector(\"#password\").value=dummyText;\n ny2qX*RH\n}", "function setupPasswords() {\n var short = $attrs['checkPasswords']; // 'pass1id|Введенные пароли отличаются'\n var shorts = short ? short.split('|') : [];\n\n var repeat = shorts[0] || $attrs['checkPasswordsRepeat'];\n\n var message = shorts[1] || $attrs['checkPasswordsMessage'] || nls._('message_passwords');\n\n field.checks.passwords = {\n message: message,\n repeat: repeat,\n active: true\n };\n var condition = shorts[2] || $attrs['checkPasswordsIf'];\n if (condition) {\n $scope.$parent.$watch(condition, function(value){\n field.checks.passwords.active = value;\n });\n }\n }", "function ResetUserFieldValues(){\n\t\t\t\n\t\t\tUserData.UserID_FieldValue=\"NONE\";\n\t\t\tUserData.Password_FieldValue=\"NONE\";\n\t\t\t//alert(\"(DEBUG)ResetUserFieldValues() executed. Values. \\nUserID=\"+UserData.UserID_FieldValue+\"\\nPass=\"+UserData.Password_FieldValue);\t\n\t\t\t\n\t\t}", "set password(v) {\n // Model's data are stored in the _data property.\n this._data.password = bcrypt.hashSync(v);\n }", "function VerificationPwd() {\n const pwd = document.getElementById(\"pwd\");\n const LMINI = 8; // DP LMINI = longueur minimale du mot de passe\n\n //DP si le mot de passe comporte moins de 8 lettres alors erreur\n if (pwd.value.length < LMINI) {\n console.log(\"longueur pwd NOK\", pwd.value.length);\n return false;\n } else {\n console.log(\"longueur pwd OK\", pwd.value.length);\n return true;\n }\n}", "function changePasswordLength(){\n\tconst len = this.value;\n\tgebi('passLengthView').innerHTML = someThing(len, 'символ', 'символа', 'символов');\n\tlet className = '';\n\tif(len > 20){\n\t\tclassName += 'alert-info';\n\t}else if (len<8){\n\t\tclassName += 'alert-warning';\n\t}\n\tgebi('passwordStrength').className = className;\n}", "function setNewPassword() {\n var Customer, resettingCustomer;\n Customer = app.getModel('Customer');\n\n app.getForm('resetpassword').clear();\n resettingCustomer = Customer.getByPasswordResetToken(request.httpParameterMap.Token.getStringValue());\n\n if (empty(resettingCustomer)) {\n \tresponse.redirect(URLUtils.https('Login-Show', 'TokenExpired', 'TokenError'));\n } else {\n app.getView({\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n }\n}", "function setPassword(password, callback){\n webSocket.shh.generateSymKeyFromPassword(password, callback);\n}", "function VerificationConfirmation() {\n const confirmation = document.getElementById(\"confirmation\");\n const pwd = document.getElementById(\"pwd\");\n const LMINI = 8; // DP LMINI = longueur minimale du mot de passe\n\n //DP si le mot de passe comporte moins de 8 lettres et que la confirmation est differente au mot de passe alors erreur\n if ((confirmation.value.length < LMINI) || (confirmation.value !== pwd.value)) {\n console.log(\"longueur confirmation NOK\", pwd.value.length, confirmation.value.length);\n return false;\n } else {\n console.log(\"longueur confirmation OK\", pwd.value.length, confirmation.value.length);\n return true;\n }\n}", "function togglePasswordVisibility() {\n let x = document.getElementById(\"login-password\");\n if (x.type === \"password\") {\n x.type = \"text\";\n } else {\n x.type = \"password\";\n }\n}", "afficherMotIncomplet() {\n var mot = this.mot.toString(false).split('');\n window.conteneurMot.innerHTML = \"Mot : \" + mot.join(' ');\n }", "'resetLostPassword'(email, password) {\n return setNewPassword(email, password, function(error, result){\n if(error) {\n throw new Meteor.Error(error, message);\n } else {\n return true;\n }\n });\n }", "afficherMotComplet() {\n var mot = this.mot.toString(true).split('');\n window.conteneurMot.innerHTML = \"Mot : \" + mot.join(' ');\n }", "function encryption() {\n var DES_key = document.getElementById(\"payment_password\").value;\n if (DES_key.length != 0) {\n var encrypted_des_key = RSA_encryption(DES_key);\n document.getElementById(\"payment_password\").value = encrypted_des_key;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the size of a view and infers what prefix/unit to show. This formatting follows IGV's conventions regarding range display: "1 bp", "101 bp", "1,001 bp", "1,001 kbp", ...
function formatRange(viewSize: number): {prefix: string, unit: string}
[ "function formatFileSize (size)\n{\n var oneKB = 1024;\n var oneMB = (1024 * 1024);\n \n var fileSize = parseFloat(size);\n if(isNaN(fileSize))\n return \"\";\n \n if (fileSize < oneKB)\n return fileSize + \" B\";\n if (fileSize > oneMB)\n return (fileSize / oneMB).toFixed(0) + \" MB\";\n \n return (fileSize / oneKB).toFixed(0) + \" KB\";\n}", "function sizeText(bytes, lpadding, align) {\n var sizeStr;\n\n if (bytes > 999999) {\n sizeStr = '' + Math.round(bytes / 100000) / 10;\n\n if (align && lpadding) {\n if (/\\./.test(sizeStr)) {\n lpadding += 2;\n }\n lpadding -= sizeStr.length;\n lpadding -= 4;\n }\n sizeStr += ' MB';\n } else if (bytes > 999) {\n sizeStr = '' + Math.round(bytes / 100) / 10;\n\n if (align && lpadding) {\n if (/\\./.test(sizeStr)) {\n lpadding += 2;\n }\n lpadding -= sizeStr.length;\n }\n sizeStr += ' kB';\n } else {\n sizeStr = '' + bytes;\n\n if (align && lpadding) {\n lpadding -= sizeStr.length;\n lpadding += 4;\n }\n sizeStr += ' bytes';\n }\n\n if (lpadding) {\n return grunt.util.repeat(Math.max(align ? lpadding : lpadding - sizeStr.length, 0), ' ') + sizeStr;\n } else {\n return sizeStr;\n }\n }", "toMiBString(aSize) {\n return aSize / 1048576 + \" MiB\";\n }", "getHeight() {\r\n let original = this.height; //in decimetres\r\n let meters = original / 10;\r\n let feet = Math.floor(meters * 3.28084); //rounds down to the nearest foot\r\n let inches = (meters * 3.28084 - feet) * 12; //takes the remainder of the foot and converts it to inches\r\n let inchesRounded = Math.round(inches);\r\n if (inchesRounded < 10) {\r\n let format = '0' + inchesRounded;\r\n return `${feet}'${format}\"`;\r\n }\r\n return `${feet}'${inchesRounded}\"`;\r\n }", "function flowFmt(num){\n // --- set number of decimal places for reporting flow values\n if ( FlowUnits == MGD || FlowUnits == CMS ) {\n return num.toFixed(3).padStart(9);\n }\n else {\n return num.toFixed(2).padStart(9);\n }\n}", "function resizeDisplay(answer){\n if (answer.toString().length >= 15) {\n let rounded = Math.round(answer * 100) / 100;\n displayValue.textContent = rounded;\n displayValue.style.cssText = 'font-size: .8em';\n } \n else {\n displayValue.textContent = answer;\n displayValue.style.cssText = 'font-size: 1.3em';\n }\n}", "function fontSize(d) {\n d.fontsize = Math.floor(d.radius/3);\n return d.fontsize + \"px\";\n }", "function withUnits(n) { return formatUserData(n, numberStyle); }", "getPageWith() {\n const dimensions = InvoicePage.dimensions[this.props.pageFormat];\n return `${dimensions.page.width}${dimensions.unit}`;\n }", "function cs_file_size(number){\r\n\t\r\n\tif(number <= 1024){\r\n\t\t\r\n\t\treturn number + 'bytes';\r\n\t\t\r\n\t}else if(number > 1024 && number <= 1048576){\r\n\t\t\r\n\t\treturn (number/1024).toFixed(1) + 'KB';\r\n\t\t\r\n\t}else if(number > 1048576){\r\n\t\t\r\n\t\treturn (number/1048576).toFixed(1) + 'MB';\r\n\t\t\r\n\t}\r\n\t\r\n}", "parseSizeGroup(optional) {\n let res;\n let isBlank = false;\n\n if (!optional && this.nextToken.text !== \"{\") {\n res = this.parseRegexGroup(/^[-+]? *(?:$|\\d+|\\d+\\.\\d*|\\.\\d*) *[a-z]{0,2} *$/, \"size\");\n } else {\n res = this.parseStringGroup(\"size\", optional);\n }\n\n if (!res) {\n return null;\n }\n\n if (!optional && res.text.length === 0) {\n // Because we've tested for what is !optional, this block won't\n // affect \\kern, \\hspace, etc. It will capture the mandatory arguments\n // to \\genfrac and \\above.\n res.text = \"0pt\"; // Enable \\above{}\n\n isBlank = true; // This is here specifically for \\genfrac\n }\n\n const match = /([-+]?) *(\\d+(?:\\.\\d*)?|\\.\\d+) *([a-z]{2})/.exec(res.text);\n\n if (!match) {\n throw new ParseError(\"Invalid size: '\" + res.text + \"'\", res);\n }\n\n const data = {\n number: +(match[1] + match[2]),\n // sign + magnitude, cast to number\n unit: match[3]\n };\n\n if (!validUnit(data)) {\n throw new ParseError(\"Invalid unit: '\" + data.unit + \"'\", res);\n }\n\n return {\n type: \"size\",\n mode: this.mode,\n value: data,\n isBlank\n };\n }", "calcCompFontSize(num) {\n // num is the main display size in digits\n const d1 = 4; // minimum display size\n const d2 = 32; // maximum display size\n const f1 = 10; // minimum font size\n const f2 = 30; // maximum font size\n let f = f1 + (d2 - num) * ((f2 - f1) / (d2 - d1));\n f = f.toFixed(1);\n f = parseFloat(f, 10);\n // store the font size in variable\n runText.fontSizeComp = `${f}px`;\n }", "function printBQ(activity){\n\tif(activity > 1000000) return (activity/1000000).toFixed(3) + ' MBq'\n\telse if(activity > 1000) return (activity/1000).toFixed(3) + ' kBq'\n\telse return (activity).toFixed(3) + ' Bq'\n}", "getFontSize() {\n return (this.props.cellSizeInPx / 2.77) + 'px';\n }", "function format(item){\r\n if(item<10){\r\n return (item = `0${item}`);\r\n }\r\n return item;\r\n }", "function createRangeDescription() {\n if((!dual || single) && incrementTop === 1) {\n return `(range: ${topStart} to ${topEnd})`;\n } else if((!dual || single) && incrementTop !== 1) {\n return `(range: ${topStart} to ${topEnd}(step ${incrementTop}))`;\n } else if((topStart === bottomStart && topEnd === bottomEnd)) {\n return `(range: ${topStart} to ${topEnd}(top step ${incrementTop}, bottom step ${incrementBottom}))`;\n } else if(incrementTop === incrementBottom && (incrementTop !== 1 || incrementBottom !== 1)) {\n return `(ranges: ${topStart} to ${topEnd}(top) ${bottomStart} to ${bottomEnd}(bottom) (step ${incrementTop}))`;\n } else if(incrementTop === incrementBottom){\n return `(ranges: ${topStart} to ${topEnd}(top) ${bottomStart} to ${bottomEnd}(bottom))`;\n } else {\n return `(ranges: ${topStart} to ${topEnd}(top) (step ${incrementTop}) ${bottomStart} to ${bottomEnd}(bottom) (step ${incrementBottom}))`;\n }\n }", "havingSize(size) {\n if (this.size === size && this.textSize === size) {\n return this;\n } else {\n return this.extend({\n style: this.style.text(),\n size: size,\n textSize: size,\n sizeMultiplier: sizeMultipliers[size - 1]\n });\n }\n }", "function get_item_size() {\n var sz = 220;\n return sz;\n}", "function calibrateStepSize(number) {\n var after_dp = new String(number).match(/\\.[0-9]+$/)\n if (after_dp !== null) {\n return 1 / (10 * (after_dp[0].length - 1)) // 0.01 for .xx\n } else {\n return number > 10 ? 2 : 1;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will accept the input div collection & give back the necessary details back.
function getRequiredSwarDetails(inputDivCollection) { /// This object will contain all the required details that are deduced from the UI /// and add them to differenct properties. /* 1. First the Name property. 2. time in milliseconds. 3. delaytime for each note deduced from the UI. */ var requiredSwarDetails = {}; var time = document.getElementsByClassName('time'); //console.info(time[0].getBoundingClientRect().width); //// Get the details for the one input box. var swarDescDiv = getSwarDivDetails(inputDivCollection[0]); var widthOfSingleRuler = time[0].getBoundingClientRect().width; for(var i = 0; i < inputDivCollection.length; i++ ) { requiredSwarDetails["swar"+i] = {}; var currentInputSwar = inputDivCollection[i].getBoundingClientRect(); // Getting the name of the Swar. requiredSwarDetails["swar"+i].name = inputDivCollection[i].textContent; //// How long the swar will be played. requiredSwarDetails["swar"+i].timeOfPlay = Number((currentInputSwar.width / widthOfSingleRuler * 1000).toFixed(2)); ///// The delay of each swar. requiredSwarDetails["swar"+i].delayTime = Number(((currentInputSwar.left - (swarDescDiv.right + 1)) / widthOfSingleRuler * 1000).toFixed(2)); } requiredSwarDetails.length = inputDivCollection.length; return requiredSwarDetails; }
[ "function retrieveSwarsFromUI(inputDivCollection) {\n\tvar notation = {};\n\tvar leftSwarDiv;\n\t//inputDivCollection\n\tfor( var i = 0 ; i < inputDivCollection.length; ++i) {\n\t\tnotation[\"inputDiv\"+(i+1)] = {};\n\t\tnotation[\"inputDiv\"+(i+1)].name = inputDivCollection[i].previousElementSibling.textContent;\n\t\t\n\t\tleftSwarDiv = inputDivCollection[i].previousElementSibling.getBoundingClientRect().right;\n\n\t\tnotation[\"inputDiv\"+(i+1)].width = inputDivCollection[i].clientWidth+\"px\";\n\t\t\n\n\t\tnotation[\"inputDiv\"+(i+1)].children = {};\n\t\tnotation[\"inputDiv\"+(i+1)].children.total = inputDivCollection[i].children.length;\n\n\t\tfor( var j = 0; j < inputDivCollection[i].children.length;++j) {\n\t\t\tvar currentChild = inputDivCollection[i].children[j].getBoundingClientRect();\n\t\t\t\t\n\t\t\tnotation[\"inputDiv\"+(i+1)].children[\"child\"+(j+1)] = {};\n\t\t\tnotation[\"inputDiv\"+(i+1)].children[\"child\"+(j+1)].left = (currentChild.left - leftSwarDiv - 1) + 'px';\n\t\t\tnotation[\"inputDiv\"+(i+1)].children[\"child\"+(j+1)].width = currentChild.width + 'px';\n\t\t\tnotation[\"inputDiv\"+(i+1)].children[\"child\"+(j+1)].height = (currentChild.height - 2) + 'px';\n\t\t\tnotation[\"inputDiv\"+(i+1)].children[\"child\"+(j+1)].name = inputDivCollection[i].children[j].textContent;\n\t\t\tconsole.log(notation[\"inputDiv\"+(i+1)].children[\"child\"+(j+1)].name);\n\t\t\t\n\n\t\t\tnotation[\"inputDiv\"+(i+1)].children[\"child\"+(j+1)].className = inputDivCollection[i].children[j].className;\t \t\t\t\n\t\t} \n\t\t\t\t\n\t}\n\tnotation.total = inputDivCollection.length;\n\treturn notation;\n}", "function getInputFieldsHtml(template_name)\n{\n //variables which change depending on the input type\n var num_input_index=0;\n var str_dynamic_index=0;\n var data = \"\";\n var cls = \"\";\n var input_type=\"\";\n var fieldName=\"\";\n\n var html=\"<div class='\"+template_name+\"-input'>\";\n var endDiv =\"</div>\";\n\n var template = getTemplateByID(template_name);\n var fieldID = template.id;\n\n //loop through all fields for each input type\n\n for(var i=0; i<template.str_fields.length; i++)\n {\n data=\"\";\n cls=\"\";\n input_type=\"\";\n fieldName = template.str_fields[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.num_fields.length; i++)\n {\n input_type = \"-number\";\n num_input_index+=1;\n data = 'data-index=\"'+num_input_index+'\" ';\n cls=\" \"+fieldID+\"-input-field \";\n fieldName = template.num_fields[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.img_fields.length; i++)\n {\n input_type=\"-img\";\n data=\"\";\n cls=\"\";\n fieldName = template.img_fields[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.hero_icon.length; i++)\n {\n input_type=\"-hero\";\n data = 'data-folder=\"hero-icons\" ';\n cls=\"\";\n fieldName = template.hero_icon[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.hero_portrait.length; i++)\n {\n input_type=\"-hero\";\n data = 'data-folder=\"hero-portraits\" ';\n cls=\"\";\n fieldName = template.hero_portrait[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.str_dynamic.length; i++)\n {\n data = 'data-index=\"'+str_dynamic_index+'\" ';\n cls=\"-dynamic-str\";\n input_type=\"\";\n fieldName = template.str_dynamic[i];\n str_dynamic_index+=1;\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.team.length; i++)\n {\n data=\"\";\n cls=\"\";\n fieldName = template.team[i];\n input_type=\"-team\";\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n return html + endDiv;\n}", "function AddSenseInformationToDiv(sense_list, div) {\n if (sense_list.length > 0) {\n div.append(\"&nbsp;\").append(sense_list.join(\"&nbsp;\"));\n }\n }", "function createDivs(problemObject) {\n\n var i, j;\n var div = '';\n for (i = 0; i < problemObject.arguments.length; i++) {\n var argumentID = $('#' + i + 'box');\n div += '<div class =\"row numberDiv\">';\n div += '<div id=\"tens' + i + '\" class=\"col-9 numberDiv\" > ';\n\n div += '<div class=\"row numberDiv-drag\">';\n for (j = 0; j < 5; j++) {\n //should be <div id=2_tens0....9)\n div += '<div class=\"col numberDiv\" id =\"' + i + '_tens' + j + '\"></div>';\n\n }\n div += '</div>';\n\n div += '<div class=\"row numberDiv-drag\">';\n for (j = 5; j < 10; j++) {\n //should be <div id=2_tens0....9)\n div += '<div class=\"col numberDiv\" id =\"' + i + '_tens' + j + '\"></div>';\n\n }\n div += '</div> </div>';\n\n\n\n\n // same for one's \n //except we only need 10 stacked\n div += '<div id=\"ones' + i + '\" class=\"col-3 numberDiv\" > ';\n\n //div += '<div class=\"row numberDiv-drag\">';\n // for (j = 0; j < 5; j++) {\n // //should be <div id=2_tens0....9)\n // div += '<div class=\"col numberDiv\" id =\"' + i + '_ones' + j + '\"></div>';\n\n // }\n //div += '</div>';\n\n // div += '<div class=\"row numberDiv-drag\">';\n // div += '<div class=\"col-8 numverDiv\"> </div>'\n // div += '<div class=\"col-2 hidden numberDiv\" id=\"' + i + '_ones\"> </div>'\n //for (j = 0; j < 10; j++) {\n //should be <div id=2_tens0....9)\n // div += '<div class=\"row numberDiv\" id =\"' + i + '_ones' + j + '\"></div>';\n\n // }\n div += '</div></div> </div>';\n\n argumentID.append(div);\n //now clear div?\n div = '';\n\n //make canvas for ten's\n\n for (j = 0; j < 10; j++) {\n containerDiv = $('#' + i + '_tens' + j);\n var box_width = containerDiv.width() - 5;\n var box_height = containerDiv.height() - 5;\n\n var stage = new Konva.Stage({\n container: i + '_tens' + j,\n width: box_width,//$('#tens_box').innerWidth(),\n height: box_height//box_height//box_height //$('#tens_box').innerHeight()\n });\n\n var layer = new Konva.Layer();\n\n var rectX = stage.getWidth(); // 2 //- 25;\n var rectY = stage.getHeight();// 2// - 30;\n\n console.log(\"this is recy/10 \" + rectY / 10);\n console.log(\"this is rectY \", rectY);\n\n var box1 = new Konva.Rect({\n x: 1,\n y: 0,\n width: (box_width-10),\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box2 = new Konva.Rect({\n x: 1,\n y: 10,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n var box3 = new Konva.Rect({\n x: 1,\n y: 20,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box4 = new Konva.Rect({\n x: 1,\n y: 30,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n var box5 = new Konva.Rect({\n x: 1,\n y: 40,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box6 = new Konva.Rect({\n x: 1,\n y: 50,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n var box7 = new Konva.Rect({\n x: 1,\n y: 60,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box8 = new Konva.Rect({\n x: 1,\n y: 70,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n var box9 = new Konva.Rect({\n x: 1,\n y: 80,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n\n var box10 = new Konva.Rect({\n x: 1,\n y: 90,\n width: box_width-10,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n\n layer.add(box1);\n layer.add(box2);\n layer.add(box3);\n layer.add(box4);\n layer.add(box5);\n layer.add(box6);\n layer.add(box7);\n layer.add(box8);\n layer.add(box9);\n layer.add(box10);\n stage.add(layer);\n /*\n function fitStageIntoParentContainer() {\n var container = i + '_tens' + j; //document.querySelector('#stage-parent');\n \n // now we need to fit stage into parent\n var containerWidth = container.offsetWidth;\n // to do this we need to scale the stage\n var scale = containerWidth / box_width;\n \n \n \n stage.width(stageWidth * scale);\n stage.height(stageHeight * scale);\n stage.scale({ x: scale, y: scale });\n stage.draw();\n box_width = containerDiv.width() - 5;\n }\n \n fitStageIntoParentContainer();\n // adapt the stage on any window resize\n window.addEventListener('resize', fitStageIntoParentContainer ); \n \n */\n\n\n }\n\n //same for one's\n containerDiv = $('#ones' + i);\n var box_width = containerDiv.width() - 5;\n var box_height = containerDiv.height() - 5;\n\n var stage = new Konva.Stage({\n container: 'ones'+i,\n width: box_width,//$('#tens_box').innerWidth(),\n height: box_height//box_height//box_height //$('#tens_box').innerHeight()\n\n });\n onesStages.push(stage);\n onesStagesValues.push(0);\n var layer = new Konva.Layer();\n\n var rectX = stage.getWidth(); // 2 //- 25;\n var rectY = stage.getHeight();// 2// - 30;\n\n console.log(\"this is recy/10 \" + rectY / 10);\n console.log(\"this is rectY \", rectY);\n\n var box1 = new Konva.Rect({\n x: 1,\n y: box_height-30,\n width: box_width/2,\n height: rectY / 10,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 1,\n draggable: false,\n shadowOffsetX: 3,\n shadowOffsetY: 3\n });\n layer.add(box1);\n stage.add(layer);\n\n\n\n\n\n }\n\n\n //iterate through all of the arguments \n //add a tens box\n\n //the konvajs stages\n\n\n\n\n //append divs to screen and build konvajs modal\n //problem_div.append(div);\n\n //now create the canvas \n\n\n\n\n\n}", "function caption_features_for_inputs_modal(obj){\n\n if( obj === null ){\n \n return null;\n\n }else{\n\n var counter_cat_filtros = 0;\n obj.forEach(function(item){\n // console.log(item);\n\n var nombre_categoria = item.name_cat.replace(/ /g, \"\");\n \n jQuery('#modal-results-filters .filter-content').append('<div id=\"control-features-' + counter_cat_filtros + '\" class=\"filtrar-features features-filter ctrl \"><img style=\"width: 30px; margin: auto 10px auto 5px;\" src=\"' + item.img + '\" />' + item.name_cat + '<span class=\"count_features\">' + \"0\" + '</span><span class=\"separation_burbuja\"></span><i class=\"fa fa-minus right coloque_fig\"></i></div>');\n jQuery('#modal-results-filters .filter-content').append('<div id=\"filters-'+ nombre_categoria +'\" class=\"filtrar-features features-filter childs control-features-' + counter_cat_filtros + '\" padre=\"control-features-' + counter_cat_filtros + '\"></div>');\n \n \n /* Construcción de inputs de filtros por categoría */\n jQuery('div#features-fields-compare .adding-element').each(function() {\n \n \n var feature = jQuery(this).attr('feature');\n var display_status = jQuery(this).css(\"display\");\n var texto_label = jQuery(this).children().html();\n // console.log(feature);\n\n item.in_cat.forEach(function(feature_ie){ \n \n var name_feature_finding = feature_ie.replace(/ /g, \"\");\n\n if( name_feature_finding == feature ){\n\n // console.log(name_feature_finding);\n if( display_status == \"none\" ){\n \n var input_adding = ' \\\n <input id=\"' + feature +'\" class=\"input-anadido-js\" type=\"checkbox\" name=\"' + feature + '\" value=\"'+ feature +'\" > \\\n <label class=\"label-anadido-js\" style=\"\" for=\"'+ feature +'\"> <span>' + texto_label + '</span> </label><br></br> \\\n ';\n \n jQuery('#filters-'+ nombre_categoria).append('<div class=\"no-overflow\" style=\"width: 100%;\">' + input_adding + '</div>');\n \n }\n else{\n \n var input_adding = ' \\\n <input id=\"' + feature +'\" class=\"input-anadido-js\" type=\"checkbox\" name=\"' + feature + '\" value=\"'+ feature +'\" checked> \\\n <label class=\"label-anadido-js\" style=\"\" for=\"'+ feature +'\"> <span>' + texto_label + '</span> </label><br></br> \\\n ';\n \n jQuery('#filters-'+ nombre_categoria).append('<div class=\"no-overflow\" style=\"width: 100%;\">' + input_adding + '</div>');\n \n }\n \n }\n \n });\n\n\n });\n /* Fin de constructor de inputs */\n \n \n counter_cat_filtros++;\n \n \n });\n\n }\n \n }", "function getRespondeeDetailsForm(attributes, response) {\n\n var div = document.getElementById('divRespondeeDetails');\n\n response = getRespondeeDetailsContent(div, response);\n}", "function showCardReading(carddiv) {\r\n\t\r\n}", "adaptarHTML(){\r\n debugger;\r\n //let boddy = '<div><form><input type=\"search\"/><input type=\"search\" id=\"BBB\"/></form></div>'; DUMMY\r\n let boddy = this.state.boddy;\r\n \r\n let processedHTML = '';\r\n \r\n let counter = 1;\r\n let $div = $('<div>').html(boddy);\r\n \r\n //busca los input y les agrega un id (si no lo tienen) y el evento onchange\r\n $div.find('input').attr({\"onChange\":\"window.cambioInput(this)\",'id':function(){\r\n if (this.id === null || this.id ===\"\"){\r\n this.id = \"ID-GENERADO-\" + counter;\r\n counter++;\r\n }\r\n }});\r\n processedHTML = $div.html();\r\n if (boddy !== \"\" && this.modificado === false){\r\n \r\n if (counter> 1){\r\n logger.info(\"El HTML fue modificado correctamente.\");\r\n }else{\r\n logger.info(\"El HTML no contiene inputs.\");\r\n }\r\n this.modificado = true;\r\n \r\n }\r\n return processedHTML;\r\n }", "generateEditPage(obj, container, types, gradedLevels, statuses, arr) {\n\n /* function for looping through parsed localstorage objects, and appending the names to select container */\n let loopAndAppend = (items, func, container) => {\n items.forEach(function(item) {\n\n /* if function, for example getStatus() is equal to item name, make item seleceted */\n if (func == item.name) {\n $(container).append(new Option(item.name, item.name, false, true));\n } else {\n $(container).append(new Option(item.name, item.name, false, false));\n }\n });\n }\n\n /* function for handleing saving of card by calling the saveCard method */\n let saveCard = () => { return this.saveCard(obj, arr, types); }\n\n /* function for deleting card by calling the deleteCard method */\n let deleteCard = () => {return this.deleteCard(obj, arr); }\n\n /* variable for holding html code. Formatted for readability */\n /* grabbing information by calling different get methods from the card class */\n let generateForm = `<div class=\"edit-form\">\n <div>\n <!-- preserving UD by having alt text descibing the image -->\n <img class=\"edit-form-img\" src=\"${obj.getImgUrl()}\" alt=\"${obj.getAlt()}\">\n </div>\n <form id=\"edit-form\" action=\"\">\n <div class=\"form-section basic-section\">\n <div class=\"form-group type-group\">\n <label for=\"category-select\">Kategori</label>\n <select class=\"w-1 category-select\" id=\"category-select\">\n <!-- Created by DOM -->\n </select>\n </div>\n <div class=\"form-group title-group\">\n <label for=\"title\">Tittel</label>\n <input class=\"title w-1\" type=\"text\" id=\"title\" placeholder=\"Tittel\" value=\"${obj.getTitle()}\">\n </div>\n <div class=\"form-group desc-group\">\n <label for=\"desc\">Beskrivelse</label>\n <textarea class=\"desc w-1\" id=\"desc\" placeholder=\"Beskrivelse\">${obj.getDesc()}</textarea>\n </div>\n </div>\n \n <div class=\"form-section address-section\">\n <div class=\"form-group street-group\">\n <div class=\"flex w-1\">\n <div class=\"w-4/5 mr-2\">\n <label for=\"streetname\">Gate</label>\n <input class=\"w-1 streetname\" type=\"text\" id=\"streetname\" placeholder=\"Gatenavn\" value=\"${obj.getStreetName()}\">\n </div>\n <div class=\"w-1/5\">\n <label for=\"streetnumber\">Nr</label>\n <input class=\"w-1 streetnumber\" type=\"text\" id=\"streetnumber\" placeholder=\"Nr\" value=\"${obj.getStreetNumber()}\">\n </div>\n </div>\n </div>\n <div class=\"form-group zipplace-group\">\n <div class=\"flex w-1\">\n <div class=\"w-1/2 mr-2\">\n <label for=\"zip\">Postkode</label>\n <input class=\"w-1 zip\" type=\"text\" id=\"zip\" placeholder=\"Postkode\" value=\"${obj.getZip()}\">\n </div>\n <div class=\"w-1/2\">\n <label for=\"place\">Sted</label>\n <input class=\"w-1 place\" type=\"text\" id=\"place\" placeholder=\"Poststed\" value=\"${obj.getPlace()}\">\n </div>\n </div>\n </div>\n <div class=\"form-group\">\n <label for=\"form-address-image\">Bilde</label>\n <img id=\"form-address-image\" class=\"form-address-img\" src=\"${obj.getAddressImg()}\" alt=\"${obj.getAddressImgAlt()}\">\n </div>\n </div>\n <div class=\"form-section\">\n <div class=\"misc-section\">\n <div class=\"form-group grade-group\">\n <label for=\"graded-level-select\">Graderingsnivå</label>\n <select id=\"graded-level-select\" class=\"w-1 graded-level-select\">\n <!-- Options created by DOM -->\n </select>\n </div>\n <div class=\"form-group status-group\">\n <label for=\"status-select\">Status</label>\n <select id=\"status-select\" class=\"w-1 status-select\">\n <!-- Options created by DOM -->\n </select>\n </div>\n </div>\n <div class=\"flex justify-center\">\n <span class=\"form-meta-text\">Opprettet ${obj.getDate()}</span>\n </div>\n </div>\n <div class=\"edit-form-footer\">\n <button type=\"submit\" class=\"edit-form-submit-btn\">Lagre</button>\n </div>\n </form>\n </div>`;\n\n /* append genereateForm variable to container */\n $(container).append(generateForm);\n\n /* add content to selects, and make appropriate option selected */\n loopAndAppend(types, obj.getType(), 'select.category-select');\n loopAndAppend(gradedLevels, obj.getGradedLevel(), 'select.graded-level-select');\n loopAndAppend(statuses, obj.getStatus(), 'select.status-select');\n\n /* event handler for deleting card */\n /* defined as an anchor to redirect after click */\n $('a#delete-card').on('click', function(){\n\n /* prompt user to confirm deletion. If 'yes' is clicked, proceed */\n if (window.confirm(\"Are you sure you want to delete the card?\") == true) { \n deleteCard(); /* run deleteCard function/method */\n }\n });\n\n /* event handler for submitting form */\n $('#edit-form').submit(function() {\n saveCard(); /* run saveCard function/method */\n });\n }", "get inputlist() {\n return this.dom.firstChild.childNodes;\n }", "function parseVendors( vendorArr )\n{\n \n $(\"#ven_search_result\").empty();\n \n for ( var i = 0; i < vendorArr.length; i++) \n {\n \n var vendor = vendorArr[i];\n\n var vendorKey = vendor.companykey;\n \n var vendorName = vendor.companyname;\n\n var venDiv = '<div id=\"ven_'+vendorKey+'\" class=\"filter_comp\">';\n \n venDiv += vendorName +'</div>';\n \n $(\"#ven_search_result\").append( venDiv );\n \n $(\"#ven_search_result\").show();\n \n \n $(\"#ven_\" + vendorKey).on('click', function(event) {\n\n var divid = event.target.id;\n\n var idSplitArr = divid.split(\"_\");\n\n if (idSplitArr.length > 1) \n {\n var vendorKey = idSplitArr[1];\n\n $(\"#selected_ven_key\").val(vendorKey);\n \n $(\"#selected_ven_ids\").val(vendor.companyid);\n \n $(\"#ven_search_result\").hide();\n \n $(\"#to_company\").val( $(\"#\"+divid).text() );\n \n \n // It is used to get the selected suppliers address details\n \n getInvoiceSupplierAddress( vendorKey ); \n \n // Used to fetch the terms and condition for selected company\n getTC( vendorKey,\"PO\" );\n\n }\n\n });\n }\n \n if( vendorArr.length == 0 )\n {\n var venDiv = '<div id=\"ven_empty\" class=\"filter_comp\">';\n \n venDiv += 'No result found</div>';\n \n $(\"#ven_search_result\").append( venDiv );\n \n $(\"#ven_search_result\").show();\n }\n}", "function cargarInfoComidasRepresentacion(){\r\n\t\tvar solicitud = $(\"#solicitud\").val();\r\n\t\tobtenInformacionComidasRepresentacion(solicitud);\r\n\t}", "function convertCollectionToJson()\n{\n var l_json_string;\n var l_col1_arr = document.getElementsByClassName('checkbox');\n var l_col2_arr = document.getElementsByClassName('task_number');\n var l_col3_arr = document.getElementsByClassName('task');\n var l_col4_arr = document.getElementsByClassName('material');\n var l_col5_arr = document.getElementsByClassName('labor');\n var l_col6_arr = document.getElementsByClassName('general');\n var l_col7_arr = document.getElementsByClassName('comments');\n var l_col8_arr = document.getElementsByClassName('estimateid');\n\n l_json_string = '{';\n l_json_string += '\"headers\": {' ;\n l_json_string += '\"Checkbox\":' + '\"\"' + ',';\n l_json_string += '\"Tasknum\":' + '\"' + $('.hdTask_number').html() + '\"' + ',';\n l_json_string += '\"Task\":' + '\"' + $('.hdTask').html() + '\"' + ',';\n l_json_string += '\"Material\":' + '\"' + $('.hdMaterial').html() + '\"' + ',';\n l_json_string += '\"Labor\":' + '\"' + $('.hdLabor').html() + '\"' + ',';\n l_json_string += '\"General\":' + '\"' + $('.hdGeneral').html() + '\"' + ',';\n l_json_string += '\"Comments\":' + '\"' + $('.hdComments').html() + '\"' + ',';\n l_json_string += '\"ID\":' + '\"' + $('.hdEstimateId').html() + '\"';\n\n l_json_string += '},';\n l_json_string += '\"data\": [';\n for (var i=0; i < l_col1_arr.length; i++){\n l_json_string += '{';\n l_json_string += '\"Checkbox\":' + false + ',';\n l_json_string += '\"Tasknum\":' + '\"' + $(l_col2_arr[i]).html() + '\",';\n l_json_string += '\"Task\":' + '\"' + $(l_col3_arr[i]).html() + '\",'; \n l_json_string += '\"Material\":' + '\"' + $(l_col4_arr[i]).html() + '\",';\n l_json_string += '\"Labor\":' + '\"' + $(l_col5_arr[i]).html() + '\",';\n l_json_string += '\"General\":' + '\"' + $(l_col6_arr[i]).html() + '\",'; \n l_json_string += '\"Comments\":' + '\"' + $(l_col7_arr[i]).html() + '\",';\n l_json_string += '\"ID\":' + '\"' + $(l_col8_arr[i]).html() + '\"';\n \n l_json_string += '}';\n if (i < l_col1_arr.length - 1){\n l_json_string += ',';\n }\n }\n l_json_string += ']';\n l_json_string += '}';\n g_handsontable_json = JSON.parse(l_json_string);\n \n $.each(g_handsontable_json.headers, function(key, val) {\n headerData.push(val);\n });\n \n $.each(g_handsontable_json.data, function(key, val) {\n tableDataforSum = [];\n tableDataforSum.push(val.Checkbox, val.Tasknum, val.Task, val.Material, val.Labor, val.General, val.Comments, val.ID);\n tableData2D.push(tableDataforSum); \n });\n \n}", "function cleanResultDiv() {\n\t//remove all divs from results div parent\n\twhile ( resultsDiv.firstChild ) resultsDiv.removeChild( resultsDiv.firstChild );\n}", "function handleResponse(data) {\r\n var parsedResponse = JSON.parse(data.currentTarget.response);\r\n console.log(parsedResponse.items);\r\n var parsedItems = Object.values(parsedResponse.items);\r\n var itemTimeslotArray = buildTimeslotArray(parsedItems);\r\n // pageConstructor(parsedItems, itemTimeslotArray);\r\n console.log(parsedItems);\r\n var currentDate = getDateForm();\r\n var paramForm = getParamForm();\r\n// console.log(currentDate);\r\n htmlConstructor(parsedItems, itemTimeslotArray, currentDate, paramForm);\r\n}", "function collectData(sectionId) {\n console.log('data-manager:' + sectionId)\n let selectElement = '#' + sectionId + ' .input-para'\n let inputFrames = document.querySelectorAll(selectElement)\n for (let inputFrame of inputFrames) {\n let inputFrameId = inputFrame.id\n // Get the parameter name from the id of input frame.\n // Because the id has the prefix 'input-', the substring begin at index 6\n let paraName = inputFrameId.substr(6)\n let inputValue = addDotBeforeAllComma(removeLastComma(inputFrame.value))\n //check input\n if (!checkInput(paraName, inputValue)) {\n console.log('The input is invalidated')\n return\n }\n //set input\n entityModel.setMissileModelValue(paraName, inputValue)\n\n // Set the table value of check-para page\n let trTableId = 'tr-' + paraName\n if (paraName === (entityModel.sweepBack)) {\n let inputSweepBackType = document.querySelector('#' + entityModel.inputTag + entityModel.sweepBackType)\n if (inputSweepBackType.value === '0.') {\n trTableId = 'tr-' + entityModel.angleFrontEdge\n } else {\n trTableId = 'tr-' + entityModel.angleRearEdge\n }\n entityModel.setMissileModelValue(entityModel.sweepBackType, inputSweepBackType.value)\n entityModel.setMissileModelValue(entityModel.sweepBack, inputValue)\n }\n\n document.getElementById(trTableId).children[1].innerHTML = transferParaValueForShow(inputValue)\n }\n //remote.require('./src/main/models/entity-model').setMissileModel(mMissileModel)\n //remote.setMainMissileModel(mMissileModel)\n dialog.showMessageBox({type:'info',message:'该部分参数输入完毕。'})\n}", "function getDetailFormElements(divId) {\r\n var detailElements = new Array();\r\n var detailDiv = getObject(divId);\r\n //to be canceled\r\n var allFormElements = detailDiv.document.forms[0].elements;\r\n var detailIdx = 0;\r\n for (var i = 0; i < allFormElements.length; i++) {\r\n if (isNodeChildOfId(allFormElements[i], divId)) {\r\n detailElements[detailIdx++] = allFormElements[i];\r\n }\r\n }\r\n return detailElements;\r\n}", "_renderContentContainers() {\n // container of all suggestion elements\n this._suggestionContainer = document.createElement('div');\n this._suggestionContainer.classList.add(this.options.classNames.container);\n\n // child elements that will be populated by consumer\n this._header = document.createElement('h4');\n this._header.classList.add(this.options.classNames.header);\n this._setHeader(this.state.header);\n this._suggestionContainer.appendChild(this._header);\n\n this._listContainer = document.createElement('ul');\n this._listContainer.setAttribute('role', 'listbox');\n this._listContainer.classList.add(this.options.classNames.list);\n this._suggestionContainer.appendChild(this._listContainer);\n\n // put the suggestions adjacent to the input element\n // firefox does not support insertAdjacentElement\n if (HTMLElement.prototype.insertAdjacentElement) {\n this._input.insertAdjacentElement('afterend', this._suggestionContainer);\n } else {\n this._input.parentNode.insertBefore(\n this._suggestionContainer,\n this._input.nextSibling,\n );\n }\n }", "function gettingCardInfoForModal(e) {\n // const cardContent = e.target.closest('.card').querySelector('.cardInnerText').textContent;\n const cardId = e.target.closest('.card').getAttribute('data-id');\n const listId = e.target.closest('.oneLists').getAttribute('data-id');\n const cardContent =returnCardReference(cardId, listId)\n\n const inputInModalContent =document.querySelector('#card-text');\n inputInModalContent.textContent = cardContent.text;\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a deep copy of a script coverage.
function cloneScriptCov(scriptCov) { const functions = []; for (const functionCov of scriptCov.functions) { functions.push(cloneFunctionCov(functionCov)); } return { scriptId: scriptCov.scriptId, url: scriptCov.url, functions, }; }
[ "function cloneFunctionCov(functionCov) {\r\n const ranges = [];\r\n for (const rangeCov of functionCov.ranges) {\r\n ranges.push(cloneRangeCov(rangeCov));\r\n }\r\n return {\r\n functionName: functionCov.functionName,\r\n ranges,\r\n isBlockCoverage: functionCov.isBlockCoverage,\r\n };\r\n}", "function cloneProcessCov(processCov) {\r\n const result = [];\r\n for (const scriptCov of processCov.result) {\r\n result.push(cloneScriptCov(scriptCov));\r\n }\r\n return {\r\n result,\r\n };\r\n}", "copy() {\n return new Dino(this.sprites, this.my_map, this.brain, this.online, this.playGame, this.loaded);\n }", "copyLines() {\n const rand = __WEBPACK_IMPORTED_MODULE_1__global_Helper__[\"a\" /* default */].rand;\n const code = this._code;\n const codeLen = code.length;\n const start = rand(codeLen);\n const end = start + rand(codeLen - start);\n //\n // Because we use spread (...) operator stack size is important\n // for amount of parameters and we shouldn't exceed it\n //\n if (end - start > MAX_STACK_SIZE) {\n return;\n }\n //\n // We may insert copied piece before \"start\" (0) or after \"end\" (1)\n //\n if (rand(2) === 0) {\n code.splice(rand(start), 0, ...code.slice(start, end));\n return;\n }\n\n code.splice(end + rand(codeLen - end + 1), 0, ...code.slice(start, end));\n }", "function copy(){\n var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state;\n \n return function copyParser(input){\n lexical = _lexical;\n cc = _cc.concat([]); // copies the array\n column = indented = 0;\n tokens = tokenizeCSharp(input, _tokenState);\n return parser;\n };\n }", "function cloneGlobalScript(axios$$1, identifier, scriptId, versionId, request) {\n return restAuthPost(axios$$1, 'instance/microservice/' + identifier + '/scripting/scripts/' + identifier + '/' + scriptId + '/versions/' + versionId + '/clone', request);\n }", "snapshotCodeDiff() { }", "copy() {\n if (this.era) return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.era, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n else return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n }", "function cloneTenantScript(axios$$1, identifier, tenantToken, scriptId, versionId, request) {\n return restAuthPost(axios$$1, 'instance/microservice/' + identifier + '/tenants/' + tenantToken + '/scripting/scripts/' + scriptId + '/versions/' + versionId + '/clone', request);\n }", "function createTestClip(code, track)\n{\n var name = leftTrim(code);\n var letter = name[0].toUpperCase();\n var leftSpaceLength = code.length - name.length;\n \n // Determine left and right trim from code\n var trim = {\n \"left\": 0,\n \"right\": 0\n };\n var onLeftSide = true;\n for (var i = 0, len = name.length; i < len; i++)\n {\n if (isLowerCaseLetter(name[i]))\n {\n trim[onLeftSide ? 'left' : 'right'] += 1000;\n }\n else\n {\n onLeftSide = false;\n }\n\n }\n\n var testClip = {\n \"_id\": \"test-\" + letter,\n \"asset_id\": \"test-\" + letter,\n \"project_id\": \"test\",\n \"trim\": trim,\n \"tick\": leftSpaceLength * 1000,\n \"length\": name.length * 1000,\n \"track\": track\n };\n\n if (name.indexOf(\"0\") > -1)\n {\n tagAsBlackness(testClip);\n }\n\n return testClip;\n}", "async function runCoverage() {\n // If cowboyhat is already running skip.\n if (locked) {\n return\n }\n locked = true\n\n // Await coverage and testing.\n await new Promise((resolve) => {\n spawn(\n 'node_modules/.bin/nyc',\n nycOptions,\n spawnOptions,\n ).on('close', resolve)\n })\n\n // TODO: Find out why this is necessary and document it here.\n if (runCount) {\n console.log('\\n')\n }\n\n // When the report is done finish up.\n spinner.stop('\\nlcov.info complete.')\n locked = false\n runCount += 1\n }", "copy() {\n const copy = new Grid(this.size);\n copy.grid = copyBoard(this.grid);\n return copy;\n }", "copy() {\n if (this.era) return new $625ad1e1f4c43bc1$export$99faa760c7908e4f(this.calendar, this.era, this.year, this.month, this.day);\n else return new $625ad1e1f4c43bc1$export$99faa760c7908e4f(this.calendar, this.year, this.month, this.day);\n }", "gruntCopy() {\n let assets = [];\n if (this.images.length > 0) {\n assets = assets.concat(this.images);\n }\n if (this.scripts.length > 0) {\n assets = assets.concat(this.scripts);\n }\n if (this.css.length > 0) {\n this.css.forEach((css, index, arry) => {\n if (!css.isAssetReved && !css.isInBundle) {\n assets.push({\n src: css.src,\n dest: css.dest,\n name: css.name,\n type: \"css\",\n });\n }\n });\n }\n if (assets && assets.length > 0) {\n const files = {};\n assets.forEach((asset, index, arry) => {\n files[asset.dest] = asset.src;\n });\n return {\n files: files\n };\n }\n return undefined;\n }", "clone() {\n let stats = {};\n this.forEachStat((name, value) => stats[name] = value)\n return new BirdStats(stats);\n }", "getCopy(){\n\t\t/*Plan:\n\t\t1. Make a new State object\n\t\t2. Copy the points over using the Point constructor and setting endpoint state (leave strands array empty)\n\t\t3. Copy the strands over, using the Strand constructor to refer to newly created points and over/under stuff. Only need to directly set the id state.\n\t\t\t\t-Note: this will update the existing copied points' strands array\n\t\t\t\t-Note: the strand's regions array will be filled up when we copy over the regions\n\t\t4. Copy regions over, using the Region constructor - will update the strands' regions arrays\n\t\t*/\n\t\tlet copy = new State();\n\t\t\n\t\t//copy over points, keeping their strands arrays empty\n\t\tfor(let p=0; p<this.points.length; p++){\n\t\t\tlet new_point = new Point(this.points[p].x, this.points[p].y);\n\t\t\tnew_point.endpoint = this.points[p].endpoint;\n\t\t\t\n\t\t\tcopy.points.push(new_point);\n\t\t}\n\t\t\n\t\t//copy over strands\n\t\tfor(let s=0; s<this.strands.length; s++){\n\t\t\tlet p0_idx = this.points.indexOf(this.strands[s].p0);\n\t\t\tlet p1_idx = this.points.indexOf(this.strands[s].p1);\n\t\t\tlet new_strand = new Strand(copy.points[p0_idx], copy.points[p1_idx], this.strands[s].p0_over, this.strands[s].p1_over);\n\t\t\tnew_strand.id = this.strands[s].id;\n\t\t\tnew_strand.marker = this.strands[s].marker;\n\t\t\tnew_strand.strokeStyle = this.strands[s].strokeStyle;\n\t\t\tnew_strand.state = copy;\n\t\t\t\n\t\t\tcopy.strands.push(new_strand);\n\t\t}\n\t\t\t\t\n\t\t//copy over regions\n\t\tcopy.updateRegions(copy);\n\t\t\n\t\treturn copy;\n\t}", "function createCopyContainers(acediff3) {\n acediff3.copyRightContainer = document.createElement('div');\n acediff3.copyRightContainer.setAttribute('class', acediff3.options.classes.copyRightContainer);\n acediff3.copyLeftContainer = document.createElement('div');\n acediff3.copyLeftContainer.setAttribute('class', acediff3.options.classes.copyLeftContainer);\n\n document.getElementById(acediff3.options.classes.gutter1).appendChild(acediff3.copyRightContainer);\n document.getElementById(acediff3.options.classes.gutter2).appendChild(acediff3.copyLeftContainer);\n}", "clone() {\n const clonedGenome = new Genome();\n this.genes.forEach(function (gene) {\n clonedGenome.genes.push(gene.clone());\n });\n\n clonedGenome.mutationRates = this.getMutationRates();\n\n return clonedGenome;\n }", "copy ()\n {\n return new Rectangle(this.position.copy(), this.width, this.height);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows uploading spinner for replacing media items
function uploadingReplaceMedia() { if (editMediaFormComplete() == true) { $("#uploadingSpinnerContainer").show(); $("#cancelButton").hide(); $("#submitButton").hide(); $("#removeVideoButton").hide(); } }
[ "function addLoading( up, file, $ul )\n\t{\n\t\t$ul.removeClass('hidden').append( \"<li id='\" + file.id + \"'><div class='pi-image-uploading-bar'></div><div id='\" + file.id + \"-throbber' class='pi-image-uploading-status'></div></li>\" );\n\t}", "handleUpload() {\n if (!this.bShowUploadSection) {\n this.bShowUploadSection = true;\n this.sLabelUpload = 'Collapse Upload Section';\n this.uIconName = 'utility:down';\n }\n else {\n this.bShowUploadSection = false;\n this.sLabelUpload = 'Expand Upload Section';\n this.uIconName = 'utility:right';\n }\n }", "function showSpinner() {\n $(options.selectors.placesContent).addClass('hidden');\n $(options.selectors.spinner).removeClass('hidden');\n }", "function uploadFiles() {\n if ($('#queue').find('.fileName').length !== 0) {\n $(this).modal();\n showSpinner('upload-spin');\n\n //upload files via uploadify object\n if (uploadGUID !== -1) {\n $('#file_upload').uploadify('upload', '*');\n }\nconsole.log(\"done uploading files\");\n }\n}", "function _fillContentWithLoadingSpinner() {\n _repositoriesContent.empty()\n .append(HtmlBuilder.div(\"\")\n .addClass(\"loading\")\n .append(HtmlBuilder.img({ src: \"/assets/img/loader.gif\", alt: \"Carregando...\" })))\n }", "function toggleUploadUI( _mode ) {\n\tswitch( _mode )\n\t{\n\t\tcase('uploading'):\n\t\t\t$('#upload-bar').css('width','0%')\n\t\t\t$('#upload-bar-container').css('display','block')\n\t\t\t$('#info-container').css('display','none')\n\t\t\tbreak\n\t\tcase('uploaded'):\n\t\t\t$('#info-container').css('display','block')\n\t\t\t$('#upload-bar-container').css('display','none')\n\t\t\tbreak\n\t\tcase('off'):\n\t\t\t$('#upload-container').css('display','none')\n\t\t\tbreak\n\t\tcase('on'):\n\t\t\t$('#upload-bar-container').css('display','none')\n\t\t\t$('#upload-container').css('display','block')\n\t\t\tbreak\n\t}\n}", "function noSavedSongs() {\n // Run the effect\n $(\"#no-saved-songs\").show(500, callback(\"#no-saved-songs\"));\n}", "removeMedia() {\n\n this.$ui.addButton.show();\n this.$ui.removeButton.hide();\n this.$ui.input.val('');\n\n // Reset preview\n switch ( this.type ) {\n\n case 'image':\n\n this.$ui.imagePreview.attr('src', this.placeholder || '');\n\n break;\n\n default:\n\n this.$ui.mediaPreview.html(this.placeholder || '&nbsp;');\n }\n }", "handleUploadFinished(event) {\n let strFileNames = '';\n // Get the list of uploaded files\n const uploadedFiles = event.detail.files;\n\n let listUploadedFileNames = [];\n for (let i = 0; i < uploadedFiles.length; i++) {\n strFileNames += uploadedFiles[i].name + ', ';\n listUploadedFileNames.push(uploadedFiles[i].name);\n }\n\n //Retrieve the uploaded files along with the urls\n this.getFiles();\n\n this.showToastMessage('Files uploaded', strFileNames + ' Files uploaded Successfully!!!', 'success');\n }", "function initialize()\n{\t\n\t$('#icon-loading').css('visibility','hidden')\n\tholder = document.getElementById('holder')\n\ttests = { //try to create the element in the DOM to check if supported\n\t\tfilereader: typeof FileReader != 'undefined', //browser has a filereader\n\t\tdnd: 'draggable' in document.createElement('span'), //browser supports drag capabilities\n\t\tformdata: !!window.FormData, //browser can create form data\n\t\tprogress: \"upload\" in new XMLHttpRequest //real-time progress status supported\n } \n\tsupport = {\n\t\tfilereader: document.getElementById('filereader'),\n\t\tformdata: document.getElementById('formdata'),\n\t\tprogress: document.getElementById('progress')\n\t}\n\tacceptedTypes = {\n\t\t'image/png': true,\n\t\t'image/jpeg': true,\n\t\t'image/gif': true,\n\t\t'application/octet-stream': true\n\t}\n\tfileupload = document.getElementById('upload')\n\t\n\t\"filereader formdata progress\".split(' ').forEach(function (api) //according to browser supportability show/hide messages\n\t{\n\t\tif (tests[api] === false) \n\t\t{\n\t\t\tsupport[api].className = 'fail';\n\t\t} \n\t\telse \n\t\t{\n\t\t\tsupport[api].className = 'hidden';\n\t\t}\n\t})\n\tif (tests.dnd) \n\t{ \n\t\tholder.ondragover = function () { this.className = 'hover'; return false; }\n\t\tholder.ondragend = function () { this.className = ''; return false; }\n\t\tholder.ondrop = function (e) \n\t\t{\n\t\t\tthis.className = ''\n\t\t\te.preventDefault()\n\t\t\treadfiles(e.dataTransfer.files)\n\t\t}\n\t} \n\telse \n\t{\n\t\tfileupload.className = 'hidden'\n\t\tfileupload.querySelector('input').onchange = function () \n\t\t{\n\t\t\treadfiles(this.files) //this triggers the uploading\n\t\t}\n\t}\n\tmode = 'none'\n\ttemplate = '1'\n\ttoggleButtons()\n}", "function displayFormParts () {\n var value = UploadModalForm.getSelectedChoiceValue();\n\n if (value === 'upload_from_url') {\n $('.media-choice-item').addClass('hidden');\n $('.upload_from_url').parents('.media-choice-item').removeClass('hidden');\n } else if (value === 'upload_from_computer') {\n $('.media-choice-item').addClass('hidden');\n $('.upload_from_computer').parents('.media-choice-item').removeClass('hidden');\n } else if (value === 'choose_from_collection') {\n $('.media-choice-item').addClass('hidden');\n $('.media-gallery-item').removeClass('hidden');\n\n UploadModalForm.displayMediaGallery();\n }\n }", "loadSpinner(display){\n document.querySelector(\".contenido-spinner\").style.display = display;\n document.querySelector(\"#resultado\").style.display = \"none\";\n }", "transitionToUploadContainer() {\n this.hideElement(\n this.homeScreen[\"home-container\"],\n true,\n this.uploadScreen[\"upload-container\"],\n false,\n \"- Upload\"\n )\n }", "function displayFile(file) {\n var li = $(\"<li />\");\n li.data(\"file\", file);\n\n var progress = $(\"<div />\");\n progress.addClass(\"progress\");\n progress.appendTo(li);\n\n var icon = $(\"<img />\");\n icon.attr(\"src\", getIcon(file.name));\n icon.appendTo(li);\n\n var title = $(\"<div />\");\n title.addClass(\"title\");\n title.text(file.name);\n title.appendTo(li);\n\n var remove = $(\"<a />\");\n remove.addClass(\"remove\");\n remove.html(\"&times;\");\n remove.appendTo(li);\n\n remove.click(function() {\n if (uploading) {\n return;\n }\n\n var idx = allFiles.indexOf(file);\n\n if (idx > -1) {\n allFiles.splice(idx, 1);\n }\n\n li.remove();\n updateUpload();\n });\n\n li.appendTo($(\"#files\"));\n updateUpload();\n}", "function upload() {\n\n isCanceled = false;\n indexNumbers = [];\n space = undefined;\n progress = 0;\n let path = $('#file-chooser').val();\n if (validatePath(path) & validateKey.call($('#space-key')) & validateTitle.call($('#space-title'))) {\n space = {\n name: $('#space-title').val(),\n key: $('#space-key').val()\n };\n setUploadMessage(i18n.PREPARING_FOR_UPLOAD, \"generic\");\n createDialog();\n if (AJS.$('#radioButtonUpdate').prop(\"checked\")) {\n\n } else if (AJS.$('#radioButtonClone').prop(\"checked\")) {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, cloneToOldSpace, error);\n } else {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, deleteOldSpace, error);\n }\n\n }\n }", "function handleMediaShare(entry) {\n\t\t\t// need to click the entry before entry_method.media is defined\n\t\t\tentry.enterLinkClick(entry.entry_method);\n\t\t\tmarkEntryLoading(entry);\n\n\t\t\t// and then wait\n\t\t\tvar temp_interval = setInterval(function() {\n\t\t\t\tif(entry.entry_method.media) {\n\t\t\t\t\tvar choices = entry.entry_method.media,\n\t\t\t\t\t\trand_choice = choices[Math.floor(Math.random() * choices.length)];\n\n\t\t\t\t\tclearInterval(temp_interval);\n\t\t\t\t\tentry.entry_method.selected = rand_choice;\n\t\t\t\t\tentry.mediaChoiceContinue(entry.entry_method);\n\t\t\t\t\tmarkEntryCompleted(entry);\n\t\t\t\t}\n\t\t\t}, 500);\n\t\t}", "function show_play_button() {\n stop_spinner();\n var play_button = document.getElementById('tv-play-button');\n play_button.style.display = 'block';\n}", "function rexShowMediaPreview() {\n var value, img_type;\n if($(this).hasClass(\"rex-js-widget-media\"))\n {\n value = $(\"input[type=text]\", this).val();\n img_type = \"rex_mediabutton_preview\";\n }else\n {\n value = $(\"select :selected\", this).text();\n img_type = \"rex_medialistbutton_preview\";\n }\n\n var div = $(\".rex-js-media-preview\", this);\n\n var url;\n var width = 0;\n if('.svg' != value.substr(value.length - 4) && $(this).hasClass(\"rex-js-widget-preview-media-manager\"))\n url = './index.php?rex_media_type='+ img_type +'&rex_media_file='+ value;\n else\n {\n url = '../media/'+ value;\n width = 246;\n }\n\n if(value && value.length != 0 && $.inArray(value.split('.').pop(), rex.imageExtensions))\n {\n // img tag nur einmalig einf�gen, ggf erzeugen wenn nicht vorhanden\n var img = $('img', div);\n if(img.length == 0)\n {\n div.html('<img />');\n img = $('img', div);\n }\n img.attr('src', url);\n if (width != 0)\n img.attr('width', width);\n\n div.stop(true, false).slideDown(\"fast\");\n }\n else\n {\n div.stop(true, false).slideUp(\"fast\");\n }\n }", "showUploadWidget() {\n cloudinary.openUploadWidget({\n cloudName: 'dvgovtrrs',\n uploadPreset: CLOUDINARY_UPLOAD_PRESET,\n sources: [\n 'local',\n 'url',\n 'camera',\n 'image_search',\n 'facebook',\n 'dropbox',\n 'instagram',\n ],\n googleApiKey: '<image_search_google_api_key>',\n showAdvancedOptions: true,\n cropping: true,\n multiple: false,\n defaultSource: 'local',\n styles: {\n palette: {\n window: '#FFFFFF',\n windowBorder: '#90A0B3',\n tabIcon: '#0078FF',\n menuIcons: '#5A616A',\n textDark: '#000000',\n textLight: '#FFFFFF',\n link: '#0078FF',\n action: '#FF620C',\n inactiveTabIcon: '#0E2F5A',\n error: '#F44235',\n inProgress: '#0078FF',\n complete: '#20B832',\n sourceBg: '#E4EBF1',\n },\n fonts: {\n default: {\n active: true,\n },\n },\n },\n }, (err, info) => {\n if (!err) {\n console.log('Upload Widget event - ', info);\n if (info.event === 'success') {\n this.setState({\n newUrl: info.info.secure_url,\n });\n }\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a patch containing only the data changes (and the contact id)
function patchContact(contact) { var patch = { id: contact.id }; if (rnd(-10)) { if (addInPatch(patch, contact, 'firstname', faker.name.firstName())) { addInPatch(patch, contact, 'homeemail', createEmailAddress(contact.firstname, contact.lastname)); addInPatch(patch, contact, 'workemail', createEmailAddress(contact.firstname, contact.lastname, createDomainName(contact.company))); } } else if (rnd(-10)) { addInPatch(patch, contact, 'homeemail', rnd(-3) ? null : createEmailAddress(contact.firstname, contact.lastname)); } if (rnd(-10)) { addInPatch(patch, contact, 'homephone', rnd(-3) ? null : faker.phone.phoneNumber()); } if (rnd(-10)) { addInPatch(patch, contact, 'avatar', rnd(-3) ? null : faker.image.imageUrl()); } if (rnd(-10)) { addInPatch(patch, contact, 'homeaddress', rnd(-3) ? null : createAddress()); } // updates professional data if (rnd(-10)) { var companyName = rnd(-3) ? null : faker.company.companyName(); addInPatch(patch, contact, 'company', companyName); // nullifies the professional data if (companyName === null) { addInPatch(patch, contact, 'workwebsite', null); addInPatch(patch, contact, 'workemail', null); addInPatch(patch, contact, 'workaddress', null); addInPatch(patch, contact, 'workphone', null); } // updates the otherwise else { // builds the domain name var domainname = createDomainName(contact.company); if (addInPatch(patch, contact, 'workwebsite', rnd(-3) ? null : 'www.' + domainname)) { addInPatch(patch, contact, 'workemail', rnd(-3) ? null : createEmailAddress(contact.firstname, contact.lastname, domainname)); } if (rnd(-5)) { addInPatch(patch, contact, 'workaddress', rnd(-3) ? null : createAddress(contact.company)); } if (rnd(-5)) { addInPatch(patch, contact, 'workphone', rnd(-3) ? null : faker.phone.phoneNumber()); } if (rnd(-8)) { addInPatch(patch, contact, 'workaddress', rnd(-3) ? null : createAddress(contact.company)); } } } return patch; }
[ "function sendPatch(patchContent, buttonID) {\n\t\t\n\t{\n\t\tpatchContent = typeof patchContent !== 'undefined' ? patchContent : Date();\n\t}\n\t\n if (gistContents !== 'undefined') {\n \n \tvar tmpContents = gistContents['files']['savedURL.md']['content'];\n \tvar newContents = \"\\n\" + tmpContents + patchContent + \"\\n\\n\";\n \tvar newData = {\n \t\t\t\t\t\"files\": {\n \t\t\t\t\t\t\"savedURL.md\" : {\n \t\t\t\t\t\t\t\"content\": newContents\n \t\t\t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t}\n \t\t\t\t\t};\n \t\n \tgistData = createCORSRequest('PATCH', gistQuery, buttonID);\n colorRed(buttonID);\n \tgistData.send(JSON.stringify(newData));\n }\n}", "function addInPatch(patch, contact, property, newValue) {\n if (JSON.stringify(newValue) !== JSON.stringify(contact[property])) {\n // adds the property:value in the patch\n patch[property] = newValue;\n\n // updates the contact property\n contact[property] = newValue;\n return true;\n }\n\n return false;\n }", "function formatDiffPatch(patch) {\n return patch.split(os_1.EOL)\n .slice(4)\n .map(formatDiffLine)\n .filter(Boolean)\n .join(os_1.EOL);\n}", "_getPatchBody(value) {\n let body = {};\n const patch = this.config.patch;\n value = typeof value !== 'undefined' ? value : this.config.control.value;\n if (IsObject(value)) {\n const val = value;\n body = Object.assign(Object.assign({}, body), val);\n }\n else if (IsArray(value)) {\n body[this.config.patch.field] = value;\n }\n else {\n body[this.config.patch.field] = value;\n if (this.config.empty && !body[this.config.patch.field]) {\n body[this.config.patch.field] = PopTransform(String(value), this.config.empty);\n }\n }\n if (this.config.patch.json)\n body[this.config.patch.field] = JSON.stringify(body[this.config.patch.field]);\n if (patch && patch.metadata) {\n for (const i in patch.metadata) {\n if (!patch.metadata.hasOwnProperty(i))\n continue;\n body[i] = patch.metadata[i];\n }\n }\n return body;\n }", "function utilPatch(orig, diff) /* patched object */ {\n\t\tconst\n\t\t\tkeys = Object.keys(diff || {}),\n\t\t\tpatched = clone(orig);\n\n\t\tfor (let i = 0, klen = keys.length; i < klen; ++i) {\n\t\t\tconst\n\t\t\t\tkey = keys[i],\n\t\t\t\tdiffP = diff[key];\n\n\t\t\tif (diffP === DiffOp.Delete) {\n\t\t\t\tdelete patched[key];\n\t\t\t}\n\t\t\telse if (Array.isArray(diffP)) {\n\t\t\t\tswitch (diffP[0]) {\n\t\t\t\tcase DiffOp.SpliceArray:\n\t\t\t\t\tpatched.splice(diffP[1], 1 + (diffP[2] - diffP[1]));\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase DiffOp.Copy:\n\t\t\t\t\tpatched[key] = clone(diffP[1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase DiffOp.CopyDate:\n\t\t\t\t\tpatched[key] = new Date(diffP[1]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpatched[key] = Util.patch(patched[key], diffP);\n\t\t\t}\n\t\t}\n\n\t\treturn patched;\n\t}", "function getMatchingDiff(fileChangeJSON, data) {\n if ($.isArray(data.diffs) && data.diffs.length) {\n var matchingDiff = _.find(data.diffs, function (diff) {\n if (diff.destination) {\n return diff.destination.toString === new Path(fileChangeJSON.path).toString();\n } else if (fileChangeJSON.srcPath) {\n return diff.source.toString === new Path(fileChangeJSON.srcPath).toString();\n }\n return false;\n }) || data.diffs[0]; //Or the first diff if none were found (this shouldn't happen)\n\n data = _.assign({ diff: matchingDiff }, data, matchingDiff);\n Object.keys(matchingDiff).forEach(function (key) {\n deprecate.prop(data, key, key, 'diff.' + key, '4.5', '5.0');\n });\n\n delete data.diffs;\n }\n return data;\n }", "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 }", "write(patch) {\n if (this[completed]) {\n throw new Error('This response has already completed.');\n }\n\n if (Array.isArray(patch)) {\n this[send]({patch});\n } else {\n this[send]({patch: [patch]});\n }\n }", "function applyPatches(uniDiff, options) {\n\t if (typeof uniDiff === 'string') {\n\t uniDiff = (0, _parse.parsePatch) (uniDiff);\n\t }\n\t\n\t var currentIndex = 0;\n\t function processIndex() {\n\t var index = uniDiff[currentIndex++];\n\t if (!index) {\n\t return options.complete();\n\t }\n\t\n\t options.loadFile(index, function (err, data) {\n\t if (err) {\n\t return options.complete(err);\n\t }\n\t\n\t var updatedContent = applyPatch(data, index, options);\n\t options.patched(index, updatedContent, function (err) {\n\t if (err) {\n\t return options.complete(err);\n\t }\n\t\n\t processIndex();\n\t });\n\t });\n\t }\n\t processIndex();\n\t}", "function _generate(mirror, obj, patches, path) {\r\n if (obj === mirror) {\r\n return;\r\n }\r\n if (typeof obj.toJSON === \"function\") {\r\n obj = obj.toJSON();\r\n }\r\n var newKeys = helpers_1._objectKeys(obj);\r\n var oldKeys = helpers_1._objectKeys(mirror);\r\n var changed = false;\r\n var deleted = false;\r\n //if ever \"move\" operation is implemented here, make sure this test runs OK: \"should not generate the same patch twice (move)\"\r\n for (var t = oldKeys.length - 1; t >= 0; t--) {\r\n var key = oldKeys[t];\r\n var oldVal = mirror[key];\r\n if (helpers_1.hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {\r\n var newVal = obj[key];\r\n if (typeof oldVal == \"object\" && oldVal != null && typeof newVal == \"object\" && newVal != null) {\r\n _generate(oldVal, newVal, patches, path + \"/\" + helpers_1.escapePathComponent(key));\r\n }\r\n else {\r\n if (oldVal !== newVal) {\r\n changed = true;\r\n patches.push({ op: \"replace\", path: path + \"/\" + helpers_1.escapePathComponent(key), value: helpers_1._deepClone(newVal) });\r\n }\r\n }\r\n }\r\n else if (Array.isArray(mirror) === Array.isArray(obj)) {\r\n patches.push({ op: \"remove\", path: path + \"/\" + helpers_1.escapePathComponent(key) });\r\n deleted = true; // property has been deleted\r\n }\r\n else {\r\n patches.push({ op: \"replace\", path: path, value: obj });\r\n changed = true;\r\n }\r\n }\r\n if (!deleted && newKeys.length == oldKeys.length) {\r\n return;\r\n }\r\n for (var t = 0; t < newKeys.length; t++) {\r\n var key = newKeys[t];\r\n if (!helpers_1.hasOwnProperty(mirror, key) && obj[key] !== undefined) {\r\n patches.push({ op: \"add\", path: path + \"/\" + helpers_1.escapePathComponent(key), value: helpers_1._deepClone(obj[key]) });\r\n }\r\n }\r\n}", "patch() {\n\t\tif (!this.component_.element && this.parent_) {\n\t\t\t// If the component has no content but was rendered from another component,\n\t\t\t// we'll need to patch this parent to make sure that any new content will\n\t\t\t// be added in the right place.\n\t\t\tthis.parent_.getRenderer().patch();\n\t\t\treturn;\n\t\t}\n\n\t\tvar tempParent = this.guaranteeParent_();\n\t\tif (tempParent) {\n\t\t\tIncrementalDOM.patch(tempParent, this.renderInsidePatchDontSkip_);\n\t\t\tdom.exitDocument(this.component_.element);\n\t\t\tif (this.component_.element && this.component_.inDocument) {\n\t\t\t\tthis.component_.renderElement_(\n\t\t\t\t\tthis.attachData_.parent,\n\t\t\t\t\tthis.attachData_.sibling\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tvar element = this.component_.element;\n\t\t\tIncrementalDOM.patchOuter(element, this.renderInsidePatchDontSkip_);\n\t\t\tif (!this.component_.element) {\n\t\t\t\tdom.exitDocument(element);\n\t\t\t}\n\t\t}\n\t}", "updateTelecomContacts(formData){\n\t\tvar form = \"{\\\"telecomAddresses\\\":\".concat(JSON.stringify(formData)).concat('}')\n\t\tcontactableService\n\t\t.updateTelecomContacts(this.props.businessId, \n\t\t\t\tthis.state.contactMecId, \n\t\t\t\tJSON.parse(form), this.props.containerId)\n\t\t.then(response => {\n\t\t\tthis.updateTelecomContactsSuccess()\n\t\t})\n\t\t.catch(error => {\n\t\t\ttoast.error('Error occurs updating web contacts')\n\t\t\tconsole.error(error)\n\t\t});\n\t}", "static async patch(url, data = {}, format = 'json', options = {})\n {\n data._method = 'patch';\n\n return Request.post(url, data, format, options);\n }", "function Window_ModPatchCreate() {\r\n this.initialize.apply(this, arguments);\r\n}", "function composeRefs(data) {\n return function () {\n\n var start = new Date().getTime();\n\n _.each(data.sourceObjects, function (obj) {\n\n //Calculate all references and filter to those that contain _sourceId\n //#143 (link entityReferences to refNorms without _sourceId) tracks creating references for non-sourceId references\n var newRefs = _.filter(_calcRefs(obj._props), \"_sourceId\");\n var oldRefs = obj._refs || {};\n\n //Mark all existing references with isOutdated = true. \n //Those references which still hold that label after below processing are in fact outdated. \n _.each(Array.prototype.concat.apply([], _.values(oldRefs)), function (obj) {\n obj.isOutdated = true;\n });\n\n //Check for each ref if it already existed, and if so replace it with the existing one, \n //which might already have a refNormId attached.\n newRefs = _.reduce(_.groupBy(newRefs, \"_path\"), function (out, arr, path) {\n var oldArrForPath = oldRefs[path];\n if (!oldArrForPath) { //no array found for path-key, so stick with the new\n return out.concat(arr);\n }\n return out.concat(_.map(arr, function (ref) {\n var oldRef = _.find(oldArrForPath, _.omit(ref, \"_path\")); //find eixsting ref in array for given path\n if (oldRef) { //if oldRef exists return that...\n delete oldRef.isOutdated;\n return _.extend({}, oldRef, {\n _path: path\n });\n }\n return ref; //.. Otherwise return ref\n }));\n }, []);\n\n //As discussed anove, all existing refs which still have a label isOutdated=true are in fact outdated\n var outdatedRefs = _.reduce(oldRefs, function (out, arrForPath, path) {\n return out.concat(_.map(_.filter(arrForPath, \"isOutdated\"), function (outdatedRef) {\n return _.extend({}, outdatedRef, {\n _path: path\n });\n }));\n }, []);\n\n var refs = data.sourceIdToRefMap[obj.id] = newRefs.concat(outdatedRefs);\n\n //for all refs that don't link to refNorm yet, add them to unlinkedRefsWithSourceId\n _.each(refs, function (refVal) {\n if (!refVal._refNormId) {\n data.unlinkedRefsWithSourceId.push(refVal);\n }\n });\n });\n\n data.time.composeRefs += new Date().getTime() - start;\n\n };\n }", "function getCurrentPatch() {\n\treturn new Promise(function (resolve, reject) { \n\t\thttps.get(patchURL, function(res) {\n\t\t\tvar body = '';\n\t\t\tres.on('data', function(chunk) {\n\t\t\t\tbody += chunk;\n\t\t\t});\n\t\t\tres.on('end', function() {\n\n\n\t\t\t\t//If response code isn't 2XX, there is a problem!\n\t\t\t\tif (res.statusCode < 200 || res.statusCode > 299) {\n\t\t\t\t\treject(\"Failed to get current patch: \" + body);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t//Otherwise, parse the data!\n\t\t\t\tvar data = JSON.parse(body);\n\t\t\t\tcurrentPatch = data[0];\n\t\t\t\tconsole.log(\"Current patch: \" + currentPatch);\n\t\t\t\tresolve();\n\n\t\t\t});\n\t\t}).on('error', function(e) {\n\t\t\treject(\"Error pulling match history for user: \" + userID + \" from Riot API: \" + e);\n\t\t});\n\t});\n}", "_beforePatch() {\n return new Promise((resolve) => {\n const patch = this.config.patch;\n const control = this.config.control;\n control.disable();\n patch.running = true;\n this._clearMessage();\n return resolve(true);\n });\n }", "addNewContact ({ commit, state }, data) {\n commit('saveNewContact', data)\n const letters = getLettersForFilter(state.contacts)\n commit('updateFilterLetters', letters)\n }", "updateContactAddress(data){\n console.log(data);\n let _id = '#' + data.recordId; // card identifier\n let mapIcon = '<i class=\"fas fa-map-marker-alt\" aria-hidden=\"true\"></i> ';\n if(data.contact.length){ //set contact if exists\n let name = data.contact[0].firstName;\n $(_id).find('.customer-name').html(name.slice(0,1).toUpperCase() + name.slice(1));\n }\n if(data.addresses){ //set addresses if exists\n let _addresses = data.addresses;\n let _parcels = [];\n let _addressLinks = this.getAddressLinks(_addresses);\n let _addAddresses = '';\n let _firstAddress = typeof _addresses[0] == 'object' ? _addresses[0].streetAddress : _addresses[0];\n if(data.parcels.length){\n _parcels = data.parcels;\n let _firstParcel = _parcels[0].parcelNumber;\n _firstAddress += ` - ${_firstParcel}`;\n }\n if (_addresses.length > 1) { //generate multi address html\n _addAddresses = this.drawAdditionalAddresses(_addresses, _addressLinks, _parcels);\n }\n if(typeof _firstAddress == 'object') //type validation\n _firstAddress = _firstAddress.streetAddress;\n\n $(_id).find('.address-link').html(mapIcon + _firstAddress);\n $(_id).find('.address-link').attr(\"href\", `http://wsitd03/website/DART/StaffMap/index.html?find=${_firstAddress}`);\n $(_id).find('.information-area').after(_addAddresses);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Webpack configuration that compiles staticrenderpages.js, a Node module that will build HTML pages.
function createWebpackConfigStatic( batfishConfig: BatfishConfiguration ): Promise<webpack$Configuration> { return createWebpackConfigBase(batfishConfig).then(baseConfig => { const staticConfig: webpack$Configuration = { entry: { static: path.join(__dirname, '../webpack/static-render-pages.js') }, output: { filename: './static-render-pages.js', libraryTarget: 'commonjs2' }, target: 'node', externals: { // These modules are required by static-render-pages and don't play // nice when Webpack tries to compile them, or we know they can be // loaded in Node. 'uglify-js': 'uglify-js', mkdirp: 'mkdirp', react: 'react', 'react-dom': 'react-dom' }, plugins: [ // Ensure that all files will be grouped into one file, // even if they would otherwise be split into separate chunks. // Separate chunks serve no purpose in the static build: we need all // the information at once. new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }) ], devtool: 'source-map', node: { console: false, global: false, process: false, __filename: false, __dirname: false, Buffer: false, setImmediate: false } }; if (batfishConfig.webpackStaticIgnore) { _.set(staticConfig, 'module.rules[0]', { test: batfishConfig.webpackStaticIgnore, loader: 'ignore-loader' }); } let config = webpackMerge(baseConfig, staticConfig); if (batfishConfig.webpackConfigStaticTransform) { config = batfishConfig.webpackConfigStaticTransform(config); } return config; }); }
[ "function generateWebpackConfigForCanister(name, info) {\n if (typeof info.frontend !== 'object') {\n return;\n }\n const outputRoot = path.join(__dirname, output, name);\n const inputRoot = __dirname;\n const entry = path.join(inputRoot, info.frontend.entrypoint);\n return {\n mode: \"production\",\n entry,\n devtool: \"source-map\",\n optimization: {\n minimize: true,\n minimizer: [new TerserPlugin()],\n },\n resolve: {\n alias: aliases,\n },\n module: {\n rules: [\n { test: /\\.(js|ts)x?$/, loader: \"ts-loader\" }\n ]\n }, \n output: {\n filename: \"index.js\",\n path: path.join(outputRoot, \"assets\"),\n },\n plugins: [\n ],\n };\n}", "prepareWebpackConfig() {\r\n this.clientConfig = createClientConfig(this.context).toConfig()\r\n this.serverConfig = createServerConfig(this.context).toConfig()\r\n\r\n const userConfig = this.context.siteConfig.configureWebpack\r\n if (userConfig) {\r\n this.clientConfig = applyUserWebpackConfig(\r\n userConfig,\r\n this.clientConfig,\r\n false\r\n )\r\n this.serverConfig = applyUserWebpackConfig(\r\n userConfig,\r\n this.serverConfig,\r\n true\r\n )\r\n }\r\n }", "function webpackServerConfig() {\n let config = webpackBaseConfig.call(this, 'server');\n\n // env object defined in nuxt.config.js\n let env = {};\n _.each(this.options.env, (value, key) => {\n env['process.env.' + key] = ['boolean', 'number'].indexOf(typeof value) !== -1 ? value : JSON.stringify(value);\n });\n\n config = Object.assign(config, {\n target: 'node',\n node: false,\n devtool: 'source-map',\n entry: path.resolve(this.options.buildDir, 'server.js'),\n output: Object.assign({}, config.output, {\n filename: 'server-bundle.js',\n libraryTarget: 'commonjs2'\n }),\n performance: {\n hints: false,\n maxAssetSize: Infinity\n },\n externals: [],\n plugins: (config.plugins || []).concat([new VueSSRServerPlugin({\n filename: 'server-bundle.json'\n }), new webpack.DefinePlugin(Object.assign(env, {\n 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV || (this.options.dev ? 'development' : 'production')),\n 'process.env.VUE_ENV': JSON.stringify('server'),\n 'process.mode': JSON.stringify(this.options.mode),\n 'process.browser': false,\n 'process.client': false,\n 'process.server': true,\n 'process.static': this.isStatic\n }))])\n });\n\n // https://webpack.js.org/configuration/externals/#externals\n // https://github.com/liady/webpack-node-externals\n this.options.modulesDir.forEach(dir => {\n if (fs.existsSync(dir)) {\n config.externals.push(nodeExternals({\n // load non-javascript files with extensions, presumably via loaders\n whitelist: [/es6-promise|\\.(?!(?:js|json)$).{1,5}$/i],\n modulesDir: dir\n }));\n }\n });\n\n // --------------------------------------\n // Production specific config\n // --------------------------------------\n if (!this.options.dev) {}\n\n // Extend config\n if (typeof this.options.build.extend === 'function') {\n const isDev = this.options.dev;\n const extendedConfig = this.options.build.extend.call(this, config, {\n get dev() {\n console.warn('dev has been deprecated in build.extend(), please use isDev'); // eslint-disable-line no-console\n return isDev;\n },\n isDev,\n isServer: true\n });\n // Only overwrite config when something is returned for backwards compatibility\n if (extendedConfig !== undefined) {\n config = extendedConfig;\n }\n }\n\n return config;\n}", "render(opts) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (opts.publicPath && opts.documentFilePath && opts.url !== undefined) {\n const url = new URL(opts.url);\n // Remove leading forward slash.\n const pathname = url.pathname.substring(1);\n const pagePath = resolve(opts.publicPath, pathname, 'index.html');\n if (pagePath !== resolve(opts.documentFilePath)) {\n // View path doesn't match with prerender path.\n let pageExists = this.pageExists.get(pagePath);\n if (pageExists === undefined) {\n pageExists = yield exists(pagePath);\n this.pageExists.set(pagePath, pageExists);\n }\n if (pageExists) {\n // Serve pre-rendered page.\n return readFile(pagePath, 'utf-8');\n }\n }\n }\n // if opts.document dosen't exist then opts.documentFilePath must\n const extraProviders = [\n ...(opts.providers || []),\n ...(this.providers || []),\n ];\n let doc = opts.document;\n if (!doc && opts.documentFilePath) {\n doc = yield this.getDocument(opts.documentFilePath);\n }\n if (doc) {\n extraProviders.push({\n provide: INITIAL_CONFIG,\n useValue: {\n document: opts.inlineCriticalCss\n // Workaround for https://github.com/GoogleChromeLabs/critters/issues/64\n ? doc.replace(/ media=\\\"print\\\" onload=\\\"this\\.media='all'\"><noscript><link .+?><\\/noscript>/g, '>')\n : doc,\n url: opts.url\n }\n });\n }\n const moduleOrFactory = this.moduleOrFactory || opts.bootstrap;\n const factory = yield this.getFactory(moduleOrFactory);\n const html = yield renderModuleFactory(factory, { extraProviders });\n if (!opts.inlineCriticalCss) {\n return html;\n }\n const { content, errors, warnings } = yield this.inlineCriticalCssProcessor.process(html, {\n outputPath: (_a = opts.publicPath) !== null && _a !== void 0 ? _a : (opts.documentFilePath ? dirname(opts.documentFilePath) : undefined),\n });\n // tslint:disable-next-line: no-console\n warnings.forEach(m => console.warn(m));\n // tslint:disable-next-line: no-console\n errors.forEach(m => console.error(m));\n return content;\n });\n }", "function getWebpackConfig(\n options = {\n /**\n * Whether we're compiling any CSS: if so, will add the loaders\n * and plugins needed\n */\n hasCss: true,\n /** Whether we're compiling with source maps (usually for non-production) */\n useSourceMaps: false,\n /** Whether we're compiling with CSS source maps (usually for non-production) */\n useCssSourceMaps: false,\n /** Whether to minimize/uglify (usually for production) */\n minimize: false,\n /** Whether we're building for production (for the Webpack mode) */\n production: false,\n /** Whether to code-split; if false, will limit to single chunk */\n splitChunks: false,\n /**\n * Whether to emit loadable-stats.json for use for server-side rendering after\n * code-splitting\n */\n emitLoadable: false,\n },\n /** Extra configuration keys (e.g., entry, output) to merge */\n extraConfigToMerge = {},\n) {\n const {\n hasCss,\n useSourceMaps,\n useCssSourceMaps,\n minimize,\n production,\n splitChunks,\n emitLoadable,\n } = options;\n\n const commonCssLoaders = [\n { loader: MiniCssExtractPlugin.loader },\n {\n loader: 'css-loader',\n options: {\n importLoaders: 2, // Indicates both post-css and sass-loaders are used before this\n sourceMap: useSourceMaps,\n },\n },\n {\n loader: 'postcss-loader',\n options: {\n ident: 'postcss',\n plugins: [autoprefixer({ browsers: browsersListBrowsers })],\n sourceMap: useSourceMaps,\n map: { inline: true },\n },\n },\n ];\n\n /**\n * Building for browsers requires a slightly different babelrc\n * compared to for node.js\n */\n const buildClientBabelOpts = getBabelRc({\n transformModules: false,\n isBabelRc: false,\n isClient: true,\n });\n\n const webpackConfig = {\n mode: production ? 'production' : 'development',\n ...extraConfigToMerge,\n devtool: useSourceMaps ? 'cheap-module-eval-source-map' : false,\n resolve: {\n extensions: ['.wasm', '.mjs', '.js', '.json', '.ts', '.tsx'],\n },\n node: {\n fs: 'empty',\n },\n module: {\n rules: [\n {\n test: /\\.(js|jsx|mjs|ts|tsx)$/,\n // These libraries uses some ES6 syntax\n exclude: /node_modules\\/(?!quill|copy-text-to-clipboard)/,\n use: [\n {\n loader: 'babel-loader',\n options: {\n ...buildClientBabelOpts,\n cacheDirectory: true,\n },\n },\n ],\n },\n ].concat(\n hasCss\n ? [\n {\n test: /\\.s?css$/,\n use: commonCssLoaders.concat([\n {\n loader: 'sass-loader',\n options: { sourceMap: useSourceMaps },\n },\n ]),\n },\n {\n test: /\\.less$/,\n use: commonCssLoaders.concat([\n {\n loader: 'less-loader',\n options: {\n javascriptEnabled: true,\n sourceMap: useSourceMaps,\n },\n },\n ]),\n },\n ]\n : [],\n ),\n },\n plugins: [\n new webpack.IgnorePlugin(/^\\.\\/locale$/, /moment$/),\n ...(emitLoadable ? [new LoadablePlugin()] : []),\n ],\n optimization: {\n // For mysterious reasons, concatenateModules results in the error\n // \"Object(...) is not a function\" or\n // \"__webpack_require__(...) is not a function\" (pre-minification)\n // as mentioned here: https://github.com/webpack/webpack/issues/6544\n concatenateModules: false,\n minimizer: minimize\n ? [\n new TerserPlugin({\n cache: true,\n parallel: true,\n sourceMap: true,\n }),\n ...(hasCss ? [new OptimizeCSSAssetsPlugin({})] : []),\n ]\n : undefined,\n },\n devServer: {\n /** Enables proxying the root \"/\" path */\n index: '',\n port: 7001,\n /**\n * All compiled .js and .css files are served at this path. Defaults to\n * root (\"/\").\n */\n publicPath: extraConfigToMerge.output.publicPath\n ? extraConfigToMerge.output.publicPath\n : undefined,\n proxy: [\n {\n context: () => true, // Redirect all requests we can't serve\n target: `http://localhost:60987`,\n },\n {\n context: () => true, // Redirect all requests we can't serve\n target: 'ws://localhost:60987',\n ws: true,\n },\n ],\n },\n };\n\n if (hasCss) {\n webpackConfig.plugins.push(\n new MiniCssExtractPlugin({\n filename: '[name].css',\n chunkFilename: '[name]-[id].css',\n sourcemap: false,\n }),\n );\n }\n\n // We don't really use sourcemaps on mobile\n if (useCssSourceMaps && hasCss) {\n // This is to generate sourcemaps for CSS files; workaround from\n // https://github.com/webpack-contrib/mini-css-extract-plugin/issues/29#issuecomment-382424129\n webpackConfig.plugins.push(\n new webpack.SourceMapDevToolPlugin({\n filename: '[file].map',\n exclude: ['/vendor/'],\n }),\n );\n }\n\n if (!splitChunks) {\n webpackConfig.plugins.push(\n new webpack.optimize.LimitChunkCountPlugin({\n maxChunks: 1,\n }),\n );\n }\n\n return webpackConfig;\n}", "async function build({ entry, outDir, initialRoutes, renderPage }) {\n\tawait rimrafPromise(outDir);\n\tawait fs.mkdir(outDir, { recursive: true });\n\n\tconst publicUrl = process.env.PARCEL_PUBLIC_URL || \"/\";\n\n console.log(\"Generating template with Parcel...\");\n\n\tconst bundler = new Parcel([entry], {\n\t\tpublicUrl,\n\t\twatch: false,\n\t\tminify: true,\n\t\tautoInstall: false,\n logLevel: 2,\n\t});\n\n\tawait bundler.bundle();\n\n\t// This should be `entry`, but processed by Parcel.\n\tconst template = await fs.readFile(path.join(outDir, path.basename(entry)));\n\n\tconst visitedRoutes = new Set(initialRoutes);\n\tconst routesToVisit = initialRoutes;\n\n\tconst addRoute = route => {\n\t\tif (!visitedRoutes.has(route)) {\n\t\t\tvisitedRoutes.add(route);\n\t\t\troutesToVisit.push(route);\n\t\t}\n\t};\n\n\twhile (true) {\n\t\tlet route = routesToVisit.pop();\n\n\t\tif (route == null) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet outputPath;\n\n\t\tif (typeof route == \"string\") {\n\t\t\toutputPath = routeToFilePath(route);\n\t\t} else {\n\t\t\toutputPath = route.outputPath;\n\t\t\troute = route.route;\n\t\t}\n\n\t\toutputPath = path.join(outDir, outputPath);\n\n\t\tconsole.log(`Generating route ${ route }`);\n\t\tconst rendered = renderPage(template, route, addRoute);\n\n\t\tconsole.log(`Saving to ${ outputPath }`);\n\t\tawait fs.mkdir(path.dirname(outputPath), { recursive: true });\n\t\tawait fs.writeFile(outputPath, rendered);\n\t}\n\n\tif (IS_GITHUB_PAGES) {\n\t\tif (CNAME != null) {\n\t\t\tconsole.log(\"Writing CNAME file for GitHub Pages\");\n\t\t\tconst cnamePath = path.join(outDir, \"CNAME\");\n\t\t\tawait fs.writeFile(cnamePath, CNAME);\n\t\t}\n\n\t\tconsole.log(\"Writing .nojekyll file for GitHub Pages\");\n\t\tconst noJekyllPath = path.join(outDir, \".nojekyll\");\n\t\tawait fs.writeFile(noJekyllPath, \"\");\n\t}\n}", "function webpackPluginServe(_a) {\n var _this = this;\n var staticPaths = _a.staticPaths, historyApiFallback = _a.historyApiFallback, options = tslib_1.__rest(_a, [\"staticPaths\", \"historyApiFallback\"]);\n if (process.env.STORYBOOK) {\n return {};\n }\n var historyFallback = !!historyApiFallback;\n // You can speed up execution by 20-30% by enabling ramdisk. It's\n // not used as it's possible it runs out of memory on default settings.\n return {\n plugins: [\n new webpack_plugin_serve_1.WebpackPluginServe(tslib_1.__assign({ hmr: \"refresh-on-failure\", progress: \"minimal\", historyFallback: historyFallback, middleware: function (app) {\n return app.use(function (ctx, next) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n ctx.set(\"Access-Control-Allow-Origin\", \"*\");\n return [4 /*yield*/, next()];\n case 1:\n _a.sent();\n return [2 /*return*/];\n }\n });\n }); });\n }, static: staticPaths, waitForBuild: true }, options)),\n ],\n watch: true,\n };\n}", "_addStaticRoutes() {\n const app = this._app;\n\n if (Deployment.shouldServeClientCode()) {\n // Map Quill files into `/static/quill`. This is used for CSS files but\n // not for the JS code; the JS code is included in the overall JS bundle\n // file.\n app.use('/static/quill',\n express.static(path.resolve(Dirs.theOne.CLIENT_DIR, 'node_modules/quill/dist')));\n\n // Use the client bundler (which uses Webpack) to serve JS bundles. The\n // `:name` parameter gets interpreted by the client bundler to select\n // which bundle to serve.\n app.get('/static/js/:name.bundle.js', new ClientBundle().requestHandler);\n }\n\n // Use the configuration point to determine which directories to serve\n // HTML files and other static assets from. This includes (but is not\n // necessarily limited to) the top-level `index.html` and `favicon` files,\n // as well as stuff explicitly under `static/`.\n for (const dir of Deployment.ASSET_DIRS) {\n app.use('/', express.static(dir));\n }\n }", "function configureWebpack(config, options) {\n let { transpile } = options;\n let globs = getEntryFileGlobs(options);\n util_1.addPlugin(config, \"karma-webpack\");\n for (let glob of globs) {\n config.preprocessors = util_1.mergeConfig(config.preprocessors, {\n [glob]: [\"webpack\"],\n });\n }\n config.webpack = util_1.mergeConfig(config.webpack, {\n mode: \"development\",\n devtool: \"inline-source-map\",\n });\n config.webpack.module = util_1.mergeConfig(config.webpack.module, {\n rules: [],\n });\n if (transpile && !util_1.hasWebpackLoader(config.webpack.module.rules, \"babel-loader\")) {\n config.webpack.module.rules.push({\n test: /\\.(js|jsx|mjs)$/,\n use: {\n loader: \"babel-loader\",\n options: {\n presets: [\"@babel/preset-env\"]\n }\n }\n });\n }\n return config;\n}", "function buildRenderer() {\n const config = require('./vite.config')\n\n console.log(chalk.bold.underline('Build renderer process'))\n\n return build({\n ...config,\n mode: process.env.NODE_ENV\n })\n}", "extend(config, ctx) { \n config.module.rules.push(\n {\n test: /\\.md$/,\n loader: \"frontmatter-markdown-loader\",\n include: path.resolve(__dirname, \"content\"),\n options: {\n markdownIt: {\n html: true,\n }\n }\n })\n }", "start() {\n themes.init(() => {\n // Log startup logo.\n logger.logHelper.logLogoBuild();\n\n createIndexes()\n .then(() => {\n if (process.env.indexOnly === 'true') {\n process.exit(0);\n return;\n }\n\n logger.log('');\n\n this.configurator\n .setConfigPath(themes.getConfig())\n .loadThemeConfig();\n\n this.webpackConfig = this.configurator.getConfig();\n this.compiler = webpack(this.webpackConfig);\n\n // Clear previous build.\n rimraf(this.webpackConfig.output.path, () => {\n // Run webpack.\n this.compiler.run(this.handleOutput.bind(this));\n });\n });\n });\n }", "function createPage() {\n\t\t// check to see if the directory exists\n\t\tif (!fs.existsSync(OUTPUT_DIR)) {\n\t\t\t// if it does not, then make it\n\t\t\tfs.mkdirSync(OUTPUT_DIR);\n\t\t}\n\t\t// write the html file using the render(coworkers) data\n\t\tfs.writeFileSync(outputPath, render(coworkers), \"utf-8\");\n\t}", "getOutput() {\n // Assuming it is production\n const output = {\n // Here we create a directory inside the user provided outputPath\n // The name of the directory is the sluggified verion of `name`\n // of this configuration object.\n // Also here we assume, user has passed in the correct `relative`\n // path for `outputPath`. Otherwise this will break.\n // We do not use path.resolve, because we expect outputPath to be\n // relative. @todo: create a test here\n path: this.outputPath,\n filename: `${this.appDir}/${this.isDev ? '[name]' : '[name]-[contenthash:8]'}.js`,\n // leave blank because we would handle with free variable\n // __webpack_public_path__ in runtime.\n publicPath: '',\n // we need different jsonpFunction, it has to\n // be unique for every webpack config, otherwise\n // the later will override the previous\n // having combination of appName and file.name\n // kind of ensures that billions of devs, don't\n // override each other!!!!\n jsonpFunction: `wpackio${this.config.appName}${this.file.name}Jsonp`\n }; // Add the publicPath if it is in devMode\n\n if (this.isDev) {\n // This is calculated by CreateWebpackConfig\n // taking into consideration user's own value.\n // So, if WordPress defaults are changed, then\n // depending on wpackio.server.js, it will still\n // point to the right location. It only makes\n // dynamic import and some on-demand split-chunk\n // work.\n output.publicPath = this.config.publicPathUrl;\n }\n\n return output;\n }", "function buildPanel(panelName) {\n return {\n name: panelName,\n entry: `./dashboard/${panelName}/src/index.ts`,\n output: {\n filename: 'script.js',\n path: `${path.resolve(__dirname)}/dashboard/${panelName}/js/`\n },\n\n ...rootConfig\n }\n}", "function buildExtension() {\n return {\n name: 'extension',\n entry: './server/src/index.ts',\n output: {\n filename: 'extension.js',\n path: path.resolve(__dirname),\n\n // Important; this needs to be a umd library or it won't export a function\n // and nodecg will poop its pants.\n library: {\n type: 'umd',\n }\n },\n\n ...rootConfig\n }\n}", "function configFactory(options, config) {\n // validate the input arguments\n const { error } = optionsSchema.validate(options);\n if (error) throw error;\n\n const { client } = config;\n const rootDir = appRootDir.get();\n // webpack configuration\n return {\n devtool: 'cheap-module-eval-source-map',\n // input entry\n entry: {\n // the vendor dll name\n [client.development.vendorDll.variable]: [\n // dependencies required to bundle into vendor dll\n ...client.development.vendorDll.includes,\n ],\n },\n output: {\n // output path\n path: path.resolve(rootDir, client.outputPath),\n // output filename\n filename: client.development.vendorDll.filename,\n // The name of the global variable which the library's\n // require() function will be assigned to\n library: client.development.vendorDll.variable,\n },\n plugins: [\n // webpack dll plugin\n new webpack.DllPlugin({\n // the output json file\n path: path.resolve(rootDir, client.development.vendorDll.manifest),\n // global variable name\n name: client.development.vendorDll.variable,\n }),\n ],\n };\n}", "function processEntryHtml(pluginConfig, inputConfig) {\n if (\n typeof pluginConfig.indexHTMLString !== 'string' &&\n (typeof inputConfig.input !== 'string' || !inputConfig.input.endsWith('index.html'))\n ) {\n throw createError('Input must be an index.html file, or an indexHTML option must be provided.');\n }\n\n const indexFolder = path.dirname(inputConfig.input);\n const indexHTMLString =\n pluginConfig.indexHTMLString || fs.readFileSync(inputConfig.input, 'utf-8');\n const {\n jsModules,\n inlineModules,\n inlineImportMaps,\n indexHTML: outputIndexHTML,\n } = extractResources(indexHTMLString);\n\n const input = [\n ...jsModules.map(joinTo(indexFolder)),\n ...inlineModules.map(createInlineModule(indexFolder)),\n ];\n\n return {\n outputIndexHTML,\n inlineImportMaps,\n inlineModules,\n rollupOptions: {\n ...inputConfig,\n input,\n },\n };\n}", "getEntry() {\n // First destructure away the stuff we need\n const {\n name,\n entry\n } = this.file; // We intend to pass the entry directly to webpack,\n // but, we need to add the hot-middleware client to the entry\n // else it will simply not work\n\n const normalizedEntry = {}; // Loop over all user defined entries and add to the normalizedEntry\n\n Object.keys(entry).forEach(key => {\n // We have to break and take the value in a separate\n // variable, otherwise typescript says all the weird\n // thing 😢\n const entryPoint = entry[key];\n normalizedEntry[key] = Array.isArray(entryPoint) ? // maybe we can go a step futher and put an entry point which takes\n // care of the __webpack_public_path__\n // like `@wpackio/publicpath?outputPath=${this.config.outputPath}&appName=${this.config.appName}`\n entryPoint : [entryPoint];\n }); // Now, if in dev mode, then add the hot middleware client\n\n if (this.isDev) {\n // Custom overlay and it's styling\n const overlayStyles = {\n zIndex: 999999999,\n fontSize: '14px',\n fontFamily: 'Dank Mono, Operator Mono SSm, Operator Mono, Menlo, Consolas, monospace',\n padding: '32px 16px'\n }; // Define the hot client string\n // Here we need\n // 1. dynamicPublicPath - Because we intend to use __webpack_public_path__\n // we can not know if user is going to use it in development too, but maybe it doesn't need to be?\n // 2. overlay and overlayStypes - To enable overlay on errors, we don't need warnings here\n // 3. path - The output path, We need to make sure both server and client has the same value.\n // 4. name - Because it could be multicompiler\n\n const webpackHotClient = `webpack-hot-middleware/client?path=__wpackio&name=${name}&dynamicPublicPath=true${this.config.errorOverlay ? '&overlay=true' : ''}&reload=true&overlayStyles=${encodeURIComponent(JSON.stringify(overlayStyles))}`; // Now add to each of the entries\n // We don't know if user want to specifically disable for some, but let's\n // not think ahead of ourselves\n\n Object.keys(normalizedEntry).forEach(key => {\n normalizedEntry[key] = [...normalizedEntry[key], // put webpack hot client in the entry\n webpackHotClient];\n });\n } else {\n // Put the publicPath entry point\n Object.keys(normalizedEntry).forEach(key => {\n normalizedEntry[key] = [// We need it before any other entrypoint, otherwise it won't\n `@wpackio/entrypoint/lib/index`, ...normalizedEntry[key]];\n });\n }\n\n return normalizedEntry;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the user language (given by the navigator or as URL search parameter
getUserLanguage( general=true ){ var urlParams = new URLSearchParams(window.location.search) var lang = urlParams.get('lang') if( lang === undefined || lang === null ) lang = window.navigator.language if( general ) lang = lang.split('-')[0] return lang }
[ "function getLanguage(){\n\tvar lang=document.getElementById(\"language\").value;\n\tswitch(lang){\n\t\tcase \"C\":\n\t\t\tlang=1;\n\t\t\tbreak;\n\t\tcase \"C++\":\n\t\t\tlang=2;\n\t\t\tbreak;\n\t\tcase \"Java\":\n\t\t\tlang=3;\n\t\t\tbreak;\n\t\tcase \"Python\":\n\t\t\tlang=5;\n\t\t\tbreak;\n\t}\n\treturn lang;\n}", "function currentLang() {\n if(window.location.pathname.slice(0, 4) == '/fr/') {\n return 'fr';\n } else {\n return 'en';\n }\n}", "static getLanguageName() {\n let twoLetterLangName = global.language.value.toLowerCase().split('-')[0];\n switch (twoLetterLangName) {\n case \"en\":\n return \"english\";\n case \"de\":\n return \"german\";\n case \"es\":\n return \"spanish\";\n case \"fr\":\n return \"french\";\n case \"it\":\n return \"italian\";\n case \"nl\":\n return \"dutch\";\n case \"fi\":\n return \"finnish\";\n case \"sv\":\n return \"swedish\";\n case \"ru\":\n return \"russian\";\n case \"pl\":\n return \"polish\";\n case \"zh\":\n case \"cn\":\n case \"chs\":\n case \"tw\":\n case \"cht\":\n return \"chinese\";\n case \"ja\":\n return \"japanese\";\n case \"ko\":\n return \"korean\";\n case \"is\":\n return \"icelandic\";\n case \"da\":\n return \"danish\";\n case \"no\":\n case \"nb\":\n case \"nn\":\n return \"norwegian\";\n case \"ar\":\n return \"arabic\";\n case \"vi\":\n return \"vietnamese\";\n default:\n return \"english\";\n }\n }", "function getLanguageFromUrl(url) {\r\n\t\t\tvar language = url;\r\n\t\t\tvar parts = null;\r\n\t\t\t// Part without query\r\n\t\t\tparts = language.split('?');\r\n\t\t\tlanguage = parts[0];\r\n\t\t\t// Part after last slash\r\n\t\t\tparts = language.split('/');\r\n\t\t\tif (parts.length >= 1) {\r\n\t\t\t\tlanguage = parts[parts.length-1];\r\n\t\t\t}\r\n\t\t\t// Part after last backslash\r\n\t\t\tparts = language.split('\\\\');\r\n\t\t\tif (parts.length >= 1) {\r\n\t\t\t\tlanguage = parts[parts.length-1];\r\n\t\t\t}\r\n\t\t\t// Part before last period\r\n\t\t\tparts = language.split('.');\r\n\t\t\tlanguage = parts[0];\r\n\t\t\t// Part after last underscore\r\n\t\t\tparts = language.split('_');\r\n\t\t\tif (parts.length >= 2) {\r\n\t\t\t\tlanguage = parts[1];\r\n\t\t\t} else {\r\n\t\t\t\tlanguage = DEFAULT_LANGUAGE;\r\n\t\t\t}\r\n\t\t\treturn language;\r\n\t\t}", "function detectLanguage(){\r\n\tvar langIdentifier = 'notícias';\r\n\tif (gexQuery('#ctl00_ucMenu_lnkStart').text().toLowerCase() == langIdentifier)\r\n\t\t_isPortuguese = 1;\r\n}", "function language_segment_from_url() {\n var path = window.location.pathname;\n var language_regexp = '/((?:' + Object.keys( all_languages ).join( \"|\" ) + ')/)'\n var match = path.match( language_regexp );\n if ( match !== null )\n return match[ 1 ];\n return '';\n }", "function getLocale() {\n try {\n if (Services.prefs.getBoolPref(PREF_MATCH_OS_LOCALE))\n return Services.locale.getLocaleComponentForUserAgent();\n }\n catch (e) { }\n\n try {\n let locale = Services.prefs.getComplexValue(PREF_SELECTED_LOCALE,\n Ci.nsIPrefLocalizedString);\n if (locale)\n return locale;\n }\n catch (e) { }\n\n try {\n return Services.prefs.getCharPref(PREF_SELECTED_LOCALE);\n }\n catch (e) { }\n\n return \"en-US\";\n}", "function getAD_Language(ctx) {\n if (ctx != null) {\n var lang = ctx.getContext(\"#AD_Language\");\n if (lang != null && lang.length > 0)\n return lang;\n }\n return getBaseAD_Language();\n }", "function getLocale () {\n return locale\n}", "function CLC_Content_FindLanguage(targObj){\r\n var lang = CLC_GetClosestAttributeOf(targObj, \"lang\");\r\n if (!lang){\r\n lang = CLC_GetClosestAttributeOf(targObj, \"xml:lang\");\r\n }\r\n if (!lang){\r\n var htmlObj = 0;\r\n var tempLineage = CLC_GetLineage(targObj);\r\n for (var i=0; i<tempLineage.length; i++){\r\n if (tempLineage[i].tagName && (tempLineage[i].tagName.toLowerCase()==\"html\")){\r\n htmlObj = tempLineage[i];\r\n }\r\n }\r\n if (htmlObj){\r\n var metaElementsArray = htmlObj.getElementsByTagName(\"meta\");\r\n for (var i=0; i<metaElementsArray.length; i++){\r\n if (metaElementsArray[i].httpEquiv && (metaElementsArray[i].httpEquiv.toLowerCase() == \"content-language\")){\r\n lang = metaElementsArray[i].content;\r\n }\r\n }\r\n }\r\n }\r\n return lang;\r\n }", "function googleLanguages() {\n return {\n 'Afrikaans (Suid-Afrika)': 'af-ZA',\n 'Bahasa Indonesia (Indonesia)': 'id-ID',\n 'Bahasa Melayu (Malaysia)': 'ms-MY',\n 'Català (Espanya)': 'ca-ES',\n 'Čeština (Česká republika)': 'cs-CZ',\n 'Dansk (Danmark)': 'da-DK',\n 'Deutsch (Deutschland)': 'de-DE',\n 'English (Australia)': 'en-AU',\n 'English (Canada)': 'en-CA',\n 'English (Great Britain)': 'en-GB',\n 'English (India)': 'en-IN',\n 'English (Ireland)': 'en-IE',\n 'English (New Zealand)': 'en-NZ',\n 'English (Philippines)': 'en-PH',\n 'English (South Africa)': 'en-ZA',\n 'English (United States)': 'en-US',\n 'Español (Argentina)': 'es-AR',\n 'Español (Bolivia)': 'es-BO',\n 'Español (Chile)': 'es-CL',\n 'Español (Colombia)': 'es-CO',\n 'Español (Costa Rica)': 'es-CR',\n 'Español (Ecuador)': 'es-EC',\n 'Español (El Salvador)': 'es-SV',\n 'Español (España)': 'es-ES',\n 'Español (Estados Unidos)': 'es-US',\n 'Español (Guatemala)': 'es-GT',\n 'Español (Honduras)': 'es-HN',\n 'Español (México)': 'es-MX',\n 'Español (Nicaragua)': 'es-NI',\n 'Español (Panamá)': 'es-PA',\n 'Español (Paraguay)': 'es-PY',\n 'Español (Perú)': 'es-PE',\n 'Español (Puerto Rico)': 'es-PR',\n 'Español (República Dominicana)': 'es-DO',\n 'Español (Uruguay)': 'es-UY',\n 'Español (Venezuela)': 'es-VE',\n 'Euskara (Espainia)': 'eu-ES',\n 'Filipino (Pilipinas)': 'fil-PH',\n 'Français (France)': 'fr-FR',\n 'Galego (España)': 'gl-ES',\n 'Hrvatski (Hrvatska)': 'hr-HR',\n 'IsiZulu (Ningizimu Afrika)': 'zu-ZA',\n 'Íslenska (Ísland)': 'is-IS',\n 'Italiano (Italia)': 'it-IT',\n 'Lietuvių (Lietuva)': 'lt-LT',\n 'Magyar (Magyarország)': 'hu-HU',\n 'Nederlands (Nederland)': 'nl-NL',\n 'Norsk bokmål (Norge)': 'nb-NO',\n 'Polski (Polska)': 'pl-PL',\n 'Português (Brasil)': 'pt-BR',\n 'Português (Portugal)': 'pt-PT',\n 'Română (România)': 'ro-RO',\n 'Slovenčina (Slovensko)': 'sk-SK',\n 'Slovenščina (Slovenija)': 'sl-SI',\n 'Suomi (Suomi)': 'fi-FI',\n 'Svenska (Sverige)': 'sv-SE',\n 'Tiếng Việt (Việt Nam)': 'vi-VN',\n 'Türkçe (Türkiye)': 'tr-TR',\n 'Thai (Thailand)': 'th-TH',\n 'Ελληνικά (Ελλάδα)': 'el-GR',\n 'Български (България)': 'bg-BG',\n 'Русский (Россия)': 'ru-RU',\n 'Српски (Србија)': 'sr-RS',\n 'Українська (Україна)': 'uk-UA',\n 'עברית (ישראל)': 'he-IL',\n 'العربية (إسرائيل)': 'ar-IL',\n 'العربية (الأردن)': 'ar-JO',\n 'العربية (الإمارات)': 'ar-AE',\n 'العربية (البحرين)': 'ar-BH',\n 'العربية (الجزائر)': 'ar-DZ',\n 'العربية (السعودية)': 'ar-SA',\n 'العربية (العراق)': 'ar-IQ',\n 'العربية (الكويت)': 'ar-KW',\n 'العربية (المغرب)': 'ar-MA',\n 'العربية (تونس)': 'ar-TN',\n 'العربية (عُمان)': 'ar-OM',\n 'العربية (فلسطين)': 'ar-PS',\n 'العربية (قطر)': 'ar-QA',\n 'العربية (لبنان)': 'ar-LB',\n 'العربية (مصر)': 'ar-EG',\n 'فارسی (ایران)': 'fa-IR',\n 'हिन्दी (भारत)': 'hi-IN',\n '한국어 (대한민국)': 'ko-KR',\n '國語 (台灣)': 'cmn-Hant-TW',\n '廣東話 (香港)': 'yue-Hant-HK',\n '日本語(日本)': 'ja-JP',\n '普通話 (香港)': 'cmn-Hans-HK',\n '普通话 (中国大陆)': 'cmn-Hans-CN',\n }\n}", "function menutoshowlang(){\n}", "function getNation( lang ) {\r\n\tif( getCookie( \"natiCd\" ) ) {\r\n\t\treturn getCookie( \"natiCd\" );\r\n\t} else if( lang == \"ko-KR\" ) {\r\n\t\treturn \"KR\";\r\n\t} else {\r\n\t\treturn getLanguage().substr( 3, 2 );\r\n\t}\t\r\n}", "function language (node) {\n let className = node.properties.className || []\n let length = className.length\n let index = -1\n let value\n\n while (++index < length) {\n value = className[index]\n\n if (value === 'no-highlight' || value === 'nohighlight') {\n return false\n }\n\n if (value.slice(0, 5) === 'lang-') {\n return value.slice(5)\n }\n\n if (value.slice(0, 9) === 'language-') {\n return value.slice(9)\n }\n }\n\n return null\n}", "function availableLanguage (site) {\n // Read the language files available\n var locales = fs.readdirSync(__dirname + '/../sites/' + site + '/locales');\n var html = '';\n // See all file and create the html\n for (var i = 0; i < locales.length; i++) {\n html += '<li><a href=\"/locales/' + locales[i].split('.')[0] + '\">' + locales[i].split('.')[0] + '</a></li>';\n } \n return html;\n}", "function _getLocale(name) {\n\treturn _locales[name] || _locales.$def;\n}", "function getLanguage(gist)\n{\n\t//goes through object\n\tvar files = gist.files;\n\tfor (var article in files)\n\t{\n\t\tvar dict = files[article];\n\t\tfor(var item in dict)\n\t\t{\n\t\t\tif(item == \"language\")\n\t\t\t{\n\t\t\t\treturn dict.language;\n\t\t\t}\n\t\t}\n\t}\n\n}", "function get_search_langs() {\n var langs = acre.cache.get('__SEARCH_LANGS__');\n if (langs) {\n return deferred.resolved(langs);\n }\n // freebase.search needs a non-empty query string so just use 'foo'.\n return freebase.search('foo', {'help': 'langs'})\n .then(function(data) {\n try {\n langs = data['result'][0]['output']['langs']['codes'][0];\n } catch (x) {\n return DEFAULT_LANGS_;\n }\n acre.cache.put('__SEARCH_LANGS__', langs);\n return langs;\n }, function(err) {\n return DEFAULT_LANGS_;\n });\n}", "function guessLanguage(request) {\n if (typeof request === 'object') {\n var language_header = request.headers['accept-language'],\n languages = [],\n regions = [];\n request.languages = [defaultLocale];\n request.regions = [defaultLocale];\n request.language = defaultLocale;\n request.region = defaultLocale;\n\n if (language_header) {\n language_header.split(',').forEach(function(l) {\n header = l.split(';', 1)[0];\n lr = header.split('-', 2);\n if (lr[0]) {\n languages.push(lr[0].toLowerCase());\n }\n if (lr[1]) {\n regions.push(lr[1].toLowerCase());\n }\n });\n\n if (languages.length > 0) {\n request.languages = languages;\n request.language = languages[0];\n }\n\n if (regions.length > 0) {\n request.regions = regions;\n request.region = regions[0];\n }\n }\n\n // setting the language by cookie\n if (cookiename && request.cookies[cookiename]) {\n request.language = request.cookies[cookiename];\n }\n\n i18n.setLocale(request, request.language);\n }\n}", "function getSelectedLocale() {\n return _selectedLocale;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether the given month is enabled.
shouldEnableMonth(month) { const activeYear = this.dateAdapter.getYear(this.activeDate); if (month === undefined || month === null || this.isYearAndMonthAfterMaxDate(activeYear, month) || this.isYearAndMonthBeforeMinDate(activeYear, month)) { return false; } if (!this.dateFilter) { return true; } const firstOfMonth = this.dateAdapter.createDate(activeYear, month); // If any date in the month is enabled count the month as enabled. for (let date = firstOfMonth; this.dateAdapter.getMonth(date) === month; date = this.dateAdapter.addCalendarDays(date, 1)) { if (this.dateFilter(date)) { return true; } } return false; }
[ "function calenderMonthIsCurrentMonth(){\n if(data.current_date.year == data.calendar.year && data.current_date.month == data.calendar.month){\n return true;\n } else {\n return false;\n }\n}", "function dateUsed(monthyear, array) {\n for (k = 0; k < array.length; k++) {\n if (monthyear == array[k]){\n return false;}\n }\n\n return true;\n}", "function getValidMonth(){\r\n\treturn 3;\r\n}", "function isMonthSelected() {\n //create a variable that targets the month box\n //give month box class name of not-valid if value not selected\n const monthBox = document.querySelector('.month-box');\n const expMon = document.querySelector('#exp-month');\n monthBox.addEventListener('click', (e) => {\n if(monthBox != null) {\n expMon.classList.remove('error-border');\n monthBox.classList.remove('not-valid');\n monthBox.classList.add('valid');\n return true;\n } else { \n expMon.classList.add('error-border');\n monthBox.classList.add('not-valid');\n monthBox.classList.remove('valid');\n }\n \n });\n }", "function summer(month){\n let summer = ['june','july','august']\n summer.includes(month.toLowerCase()) ? alert(\"YAY\") : alert(\"Booo\")\n}", "function common_crawl_is_month_downloaded(month) {\n\n //\n // Local variables\n //\n var file;\n\n //\n // Determine the file name\n //\n file = path.resolve(__dirname, '../tmp/' + month + '-wet.paths.gz.txt');\n\n //\n // Return the exist status of the file\n //\n return fs.existsSync(file);\n\n}", "function _getMonth(m) {\n\t\tif(mc.os.config.translations) {\n\t\t\treturn mc.os.config.translations.pc.settings.nodes['_constants'].months[m];\n\t\t} else {\n\t\t\treturn $MONTHS[m];\n\t\t}\n\t}", "function _filterByMonth(override) {\n\t\tif(override) _offerModule.filterByMonth(override);\n\t\telse _offerModule.filterByMonth(_activeFilterButton.attr('month'));\n\t}", "function DateTimeDayMonth() { }", "function isBirthday(day, month){\n\treturn month == 7 && day == 24;\n}", "function setMonthYear(date) {\n var month = date.getMonth();\n var year = date.getFullYear();\n\n // update properties if different\n if (month !== that.selectedMonth || year !== that.selectedYear) {\n that.selectedMonth = month;\n that.selectedYear = year;\n\n return true;\n }\n\n return false;\n }", "get shouldNightModeStart() {\n const { score, nightMode } = this;\n const { DISTANCE } = GameScene.CONFIG.NIGHTMODE;\n return score > 0 && score % DISTANCE === 0 && !nightMode.isEnabled;\n }", "function btnNextMonthClick() {\n\t\terase();\n\t\tmonthCheck = monthCheck + 1;\n\t\tif (monthCheck > 11) {\n\t\t\tmonthCheck = 0;\n\t\t\tyearCheck = yearCheck + 1;\n\t\t}\n\t\tconsole.log(monthCheck);\n\t\tsetData();\n\t\tsetMonths();\n\t\tsetYears();\n\t}", "function isDateValid(day,month,year)\n{\n\tvar okay = true;\n\tvar leapYear = isLeapYear(year);\n\n\tif (day > numDays(month, year))\n\t{\n\t\tokay = false;\n\t}\n\n\treturn okay;\n}", "isOnDemandJob(job) {\n let returnValue = true;\n if (angular.isDefined(job.jobcode) && job.jobcode != null && job.jobcode !== \"\" && job.jobcode.trim() !== \"\") {\n returnValue = true;\n } else {\n returnValue = false;\n }\n return returnValue;\n }", "function switch_year_or_month(a){\n global_month_or_year = a;\n var needgroup = false;\n if(global_analysis!=\"case_count\"){\n needgroup = true;\n }\n if(global_month_or_year==\"month\"){\n show_linechart(global_timeline_data,needgroup);\n }\n else if(global_month_or_year==\"quarter\"){\n show_linechart_by_quarter(global_timeline_data);\n }\n else{\n show_linechart_by_year(global_timeline_data);\n }\n}", "function hasProperDaysPerMonth(element){\n\t\n\t\t// months of the year\t\n\t\tvar MONTHS_ARRAY = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \n\t\t\t\"September\", \"October\", \"November\", \"December\"];\n\n\t\t// months with default days per month\t\t\n\t\tvar MONTHS_DAYS = {\n\t\t\t\"January\" : 31, \"February\":28, \"March\": 31, \"April\": 30, \"May\" : 31, \"June\" : 30, \"July\" : 31,\n\t\t\t\"August\" : 31, \"September\" : 30, \"October\" : 31, \"November\" : 30, \"December\" : 31\t\t\n\t\t};\n\t\t\n\t\t// MONTH_ARRAY begins at zero index (months 0-11); user's months are 1-12.\n\t\tvar MONTH_OFFSET = 1; \n\t\n\t\t// trim potential white space from user's input\n\t\tvar date = element.value.trim();\n\t\t\n\t\t// split mm/dd/yyyy string on \"/\" and store in array.\n\t\tvar dateArray = date.split(\"/\");\n\t\t\n\t\t// radix for parseInt\n\t\tvar RADIX = 10;\n\t\t\n\t\t// assign contents of array to variables\n\t\tvar month = parseInt(dateArray[0], RADIX) - MONTH_OFFSET;\t// subtract offset\n\t\tvar day = parseInt(dateArray[1], RADIX);\n\t\tvar year = parseInt(dateArray[2], RADIX);\n\t\t\n\t\t// if leap year increase February to 29 days.\t\t\n\t\tif(isLeapYear(year)){\n\t\t\n\t\t\tMONTHS_DAYS.February = 29;\n\t\t\t\n\t\t}//else do nothing.\n\t\t\n\t\t// check if user's input days exceed number of days the month should have\n\t\tif(day > MONTHS_DAYS[MONTHS_ARRAY[month]]){\n\t\t\n\t\t\t// User input has too many days\n\t\t\talert(MONTHS_ARRAY[month] +\" can't have \" + day + \" days in it, not in \" + year + \", anyway.\");\n\t\t\t\n\t\t\t// shift webpage focus to failed field\n\t\t\telement.focus();\n\t\t\t\n\t\t\t// failed test\n\t\t\treturn false;\n\t\t\t\n\t\t}else{\n\t\t\n\t\t\t// passed test\n\t\t\treturn true;\n\t\t\t\n\t\t}\t\t\n\t}", "get modulesEnabled() {\n return ToxenModule.installedModules.filter(m => m.module.active !== false).length;\n }", "function isInteractive(day, displayMonth, props) {\n var toDate = props.toDate, fromDate = props.fromDate, enableOutsideDaysClick = props.enableOutsideDaysClick, originalProps = props.originalProps;\n var outside = isOutside(day, displayMonth);\n if (props.mode !== 'uncontrolled' && !outside) {\n return true;\n }\n var hasInteractiveProps = 'onDayClick' in originalProps;\n if (props.mode !== 'uncontrolled') {\n return true;\n }\n else if (hasInteractiveProps) {\n return true;\n }\n // The day is NOT interactive if not in the range specified in the `fromDate`\n // and `toDate` (these values are set also by `fromDay/toDay` and\n // `fromYear/toYear` in the main component.)\n var isAfterToDate = Boolean(toDate && isAfter(day, toDate));\n var isBeforeFromDate = Boolean(fromDate && isBefore(day, fromDate));\n var isOutsideInteractive = outside\n ? Boolean(enableOutsideDaysClick)\n : false;\n var interactive = !isAfterToDate && !isBeforeFromDate && isOutsideInteractive;\n return interactive;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by KotlinParserenumClassBody.
enterEnumClassBody(ctx) { }
[ "enterEnumEntries(ctx) {\n\t}", "enterEnumConstantList(ctx) {\n\t}", "constructor(options) {\n /// @internal\n this.typeNames = [\"\"];\n /// @internal\n this.typeIDs = Object.create(null);\n /// @internal\n this.prop = new tree_es[\"c\" /* 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 }", "visitType_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "enterClassLiteral(ctx) {\n\t}", "exitEnumEntry(ctx) {\n\t}", "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 }", "enterNormalClassDeclaration(ctx) {\n\t}", "visitType_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "exitNormalClassDeclaration(ctx) {\n\t}", "function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}", "function parse_IntExpr(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_IntExpr()\" + '\\n';\n\tCSTREE.addNode('IntExpr', 'branch');\n\n\t\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\tif (tempType == 'digit'){\n\t\tmatchSpecChars(tempDesc,parseCounter);\n\t\t\n\t\tparseCounter = parseCounter + 1;\n\t\t\n\t\t\tif (tokenstreamCOPY[parseCounter][0] == '+'){\n\t\t\tdocument.getElementById(\"tree\").value += '\\n';\n\t\t\tparse_intop();\n\t\n\t\t\tparse_Expr();\n\t\n\t\t}\n\t\t\t\t\n\t}\n\t\n\t\n\t\n}", "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}", "enterClassMemberDeclaration(ctx) {\n\t}", "function pushlex(type, info) {\n var result = function(){\n lexical = new CSharpLexical(indented, column, type, null, lexical, info)\n };\n result.lex = true;\n return result;\n }", "consoleParseTypes(input) { return Parser.parse(input, { startRule: 'TYPES' }); }", "enterClassInstanceCreationExpression(ctx) {\n\t}", "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 }", "enterParenthesizedType(ctx) {\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
8) shiftNTimes(array, numShifts) Modify array so it is "left shifted" n times so shiftNTimes(array[6, 2, 5, 3], 1) changes the array argument to [2, 5, 3, 6] and shiftNTimes([6, 2, 5, 3], 2) changes the array argument to [5, 3, 6, 2]. You must modify the array argument by changing the parameter named nums inside method shiftNTimes. A change to nums inside the method shiftNTimes changes the argument. Do not return anything. shiftNTimes([1, 2, 3, 4, 5, 6, 7], 3 ) modifies the array to [4, 5, 6, 7, 1, 2, 3] shiftNTimes( [1, 2, 3], 5) modifies the array to [3, 1, 2] shiftNTimes( [3], 5) modifies the array to (3) Precondition: numShifts > 0 Precondition: integerArray has integers onlt. We do not test for strings or floats.
function shiftNTimes(integerArray, numShifts) { while (numShifts) { var shiftedIndex = integerArray.shift(); integerArray.push(shiftedIndex); numShifts--; } }
[ "shift_args(n, m, s){\n for(var i = n; i >= 0; i--){\n this.index_set(s, i+m+1, this.index(s, i));\n }\n return s-m-1;\n }", "function shift(arr) {\n var len = arr.length;\n if (len === 0) return undefined;\n var out = arr[0];\n\n for (var i = 0; i < len - 1; i++) { arr[i] = arr[i + 1]; }\n arr.length = len - 1;\n return out;\n}", "function shiftLeft(arr){\n var newarr=[];\n for(i=1; i<arr.length; i++){\n newarr.push(arr[i]);\n }\n newarr.push(0);\n return newarr\n}", "function shiftVals(num, array, idx) {\n for (let i = 0; i <= idx; i++) {\n if (i === idx) {\n array[i] = num;\n } else {\n array[i] = array[i + 1];\n }\n }\n}", "rotate_right(elements, shift_amount) {\n for(let i = 0; i < shift_amount; i++)\n elements.unshift(elements.pop());\n return elements;\n }", "function doubleThird(array){\r\n\t//Generating a copy of the array parameter\r\n\tvar array_copy = new Array();\r\n\t//Steps through the array that was the parameter\r\n\tfor(var i =0; i<array.length; i++){\r\n\t\t//Tests if the current location is a multiple of 3 or i+1 for zero indexes\r\n\t\tif((i+1)%3==0){\r\n\t\t\t//If the test passes, double the original into the new location \r\n\t\t\tarray_copy[i]=array[i]*2;\r\n\t\t//Passes all array locations that are not divisible by 3\r\n\t\t}else{\r\n\t\t\t//Copying the old array into the new one\r\n\t\t\tarray_copy[i]=array[i];\r\n\t\t}\r\n\t}\r\n\t//Returns the adjusted copy of the array parameter\r\n\treturn array_copy;\r\n}", "function leftShift_(x,n) {\r\n var i;\r\n var k=Math.floor(n/bpe);\r\n if (k) {\r\n for (i=x.length; i>=k; i--) //left shift x by k elements\r\n x[i]=x[i-k];\r\n for (;i>=0;i--)\r\n x[i]=0;\r\n n%=bpe;\r\n }\r\n if (!n)\r\n return;\r\n for (i=x.length-1;i>0;i--) {\r\n x[i]=mask & ((x[i]<<n) | (x[i-1]>>(bpe-n)));\r\n }\r\n x[i]=mask & (x[i]<<n);\r\n }", "function shiftLeft(value, n) {\n return value << n;\n}", "function moveZeros(nums){\n \n let marker = 0;\n \n for(let i = 0; i < nums.length; i++){\n if(nums[i] !== 0){\n let stored = nums[marker]\n nums[marker] = nums[i]\n nums[i] = stored\n marker++\n }\n }\n return nums\n}", "function modifyArray(nums) {\n return nums.map(s=> s%2==0 ? s*2: s*3 )\n\n\n }", "shift(action, next, nextEnd) {\n let start = this.pos\n if (action & 131072 /* Action.GotoFlag */) {\n this.pushState(action & 65535 /* Action.ValueMask */, this.pos)\n } else if ((action & 262144) /* Action.StayFlag */ == 0) {\n // Regular shift\n let nextState = action,\n { parser } = this.p\n if (nextEnd > this.pos || next <= parser.maxNode) {\n this.pos = nextEnd\n if (!parser.stateFlag(nextState, 1 /* StateFlag.Skipped */))\n this.reducePos = nextEnd\n }\n this.pushState(nextState, start)\n this.shiftContext(next, start)\n if (next <= parser.maxNode) this.buffer.push(next, start, nextEnd, 4)\n } else {\n // Shift-and-stay, which means this is a skipped token\n this.pos = nextEnd\n this.shiftContext(next, start)\n if (next <= this.p.parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4)\n }\n }", "function increment(arr) {\n for (var x = 0; x < arr.length; x++) {\n if (x%2 != 0) {\n arr[x] += 1;\n }\n console.log(arr[x]);\n }\n return arr;\n}", "function CircularShift()\n{\n // 1-D array to store circular shifts of lines from LineStorage\n this.shifts = [];\n \n // Function to perform circular shifts of lines from LineStorage\n this.setup = function(storage)\n {\n var l;\n var w;\n\n // For each line in lines\n for(l=0; l < storage.lines.length; l++)\n {\n // For each word in lines[l]\n for(w=0; w < storage.words[l].length; w++)\n {\n this.shifts.push(storage.words[l].join(' '));\n var word = storage.words[l].shift();\n storage.words[l].push(word);\n }\n }\n };\n \n // Function to return circular shift at index l\n this.getLine = function(l)\n {\n return this.shifts[l];\n };\n \n // Function to return number of circular shifts\n this.getNumLines = function()\n {\n return this.shifts.length; \n };\n \n // Function to output unsorted circular shifts for demonstration purposes\n this.print = function()\n {\n var n;\n var out = '<h3>Circular Shifts: </h3>';\n document.getElementById(\"circularshifts\").innerHTML += out;\n for(n=0; n<this.shifts.length; n++)\n {\n var i = n+1;\n out = '<p>' + i + '. ' + this.shifts[n] + '</p>';\n document.getElementById(\"circularshifts\").innerHTML += out;\n }\n };\n \n}", "function calculateShiftTime(shiftNumber){\n if (shiftNumber == 1) {\n \n // calculate number of seconds since 12 AM Sunday until shift times.\n var timeArray = [(nightshiftParameters.shiftOne.startTime.twentyFourHour * 36) + (nightshiftParameters.secondsInDay * dayNumber),\n (nightshiftParameters.shiftOne.finishTime.twentyFourHour * 36) + (nightshiftParameters.secondsInDay * dayNumber)]\n }\n else if (shiftNumber == 2) {\n var timeArray = [(nightshiftParameters.shiftTwo.startTime.twentyFourHour * 36) + (nightshiftParameters.secondsInDay * dayNumber),\n (nightshiftParameters.shiftTwo.finishTime.twentyFourHour * 36) + (nightshiftParameters.secondsInDay * dayNumber)]\n }\n else console.log(\"Invalid shift number!\")\n \n // returns an array of two times, start and finish, e.g. 93600,148700\n return timeArray\n}", "function x64LeftShift(m, n) {\n\t\tn %= 64\n\t\tif (n === 0) {\n\t\t\treturn m\n\t\t} else if (n < 32) {\n\t\t\treturn [(m[0] << n) | (m[1] >>> (32 - n)), m[1] << n]\n\t\t} else {\n\t\t\treturn [m[1] << (n - 32), 0]\n\t\t}\n\t}", "function mixedNumbers(arr) {\n // change code below this line\n arr.unshift(\"I\", 2, \"three\");\n arr.push(7, \"VIII\", 9);\n // change code above this line\n return arr;\n}", "function times(n) {\n return new Array(n).fill(true).map((_, i) => i);\n}", "function testCopyEvens() {\n console.log();\n console.log(\"copyEvens([3, 2, 4, 5, 8], 2) → [2, 4] \" + \"[\" + copyEvens([3, 2, 4, 5, 8], 2) + \"]\");\n console.log(\"copyEvens([3, 2, 4, 5, 8], 3) → [2, 4, 8] \" + \"[\" + copyEvens([3, 2, 4, 5, 8], 3) + \"]\");\n console.log(\"copyEvens([6, 1, 2, 4, 5, 8], 3) → [6, 2, 4] \" + \"[\" + copyEvens([6, 1, 2, 4, 5, 8], 3) + \"]\");\n console.log(\"copyEvens([6, 1, 2, 4, 5, 8], 4) → [6, 2, 4, 8] \" + \"[\" + copyEvens([6, 1, 2, 4, 5, 8], 4) + \"]\");\n console.log(\"copyEvens([3, 1, 4, 1, 5], 1) → [4] \" + \"[\" + copyEvens([3, 1, 4, 1, 5], 1) + \"]\");\n console.log(\"copyEvens([2], 1) → [2] \" + \"[\" + copyEvens([2], 1) + \"]\");\n console.log(\"copyEvens([6, 2, 4, 8], 2) → [6, 2] \" + \"[\" + copyEvens([6, 2, 4, 8], 2) + \"]\");\n console.log(\"copyEvens([6, 2, 4, 8], 3) → [6, 2, 4] \" + \"[\" + copyEvens([6, 2, 4, 8], 3) + \"]\");\n console.log(\"copyEvens([6, 2, 4, 8], 4) → [6, 2, 4, 8] \" + \"[\" + copyEvens([6, 2, 4, 8], 4) + \"]\");\n console.log(\"copyEvens([1, 8, 4], 1) → [8] \" + \"[\" + copyEvens([1, 8, 4], 1) + \"]\");\n console.log(\"copyEvens([1, 8, 4], 2) → [8, 4] \" + \"[\" + copyEvens([1, 8, 4], 2) + \"]\");\n console.log(\"copyEvens([2, 8, 4], 2) → [2, 8] \" + \"[\" + copyEvens([2, 8, 4], 2) + \"]\");\n}", "function decryptCipherRangeArray(shift) {\r\n var cipherRangeArrArr = [];\r\n for (var i = 0; i < INPUT_RANGE_SIZE; i++) {\r\n var cipherVal = (i - shift) % INPUT_RANGE_SIZE;\r\n // Makes the cipher work for negative shifts.\r\n if (cipherVal < 0) {\r\n cipherVal = INPUT_RANGE_SIZE + cipherVal;\r\n }\r\n cipherRangeArrArr.push(cipherVal);\r\n }\r\n console.log(\"cipherRangeArrArr: \");\r\n console.log(cipherRangeArrArr);\r\n return cipherRangeArrArr;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create philippines VAT Report object and add it to mainPanel
function phpVATReport(params) { if (params) { var VATReportObject = Wtf.getCmp(params.reportID); if (VATReportObject == null) { VATReportObject = new Wtf.account.phpVATReport({ title: Wtf.util.Format.ellipsis(params.title), tabTip: params.titleQtip, id: params.reportID, closable: true, border: false, params: params, layout: 'fit', iconCls: 'accountingbase receivepaymentreport' }); Wtf.getCmp('as').add(VATReportObject); } Wtf.getCmp('as').setActiveTab(VATReportObject); Wtf.getCmp('as').doLayout(); } }
[ "function ciniki_sapos_invoicereports() {\n\n this.taxreport = new M.panel('Tax Report', 'ciniki_sapos_invoicereports', 'taxreport', 'mc', 'large', 'sectioned', 'ciniki.sapos.invoicereports.taxreport');\n this.taxreport.year = null;\n this.taxreport.quarter = 0;\n this.taxreport.data = {};\n this.taxreport.sections = {\n 'quarters':{'label':'', 'type':'simplegrid', 'num_cols':2,\n 'noData':'No taxes found',\n },\n };\n this.taxreport.sectionData = function(s) {\n return this.data[s];\n };\n this.taxreport.headerValue = function(s, i, d) {\n if( i == 0 ) { return 'Quarter'; }\n if( i > 1 && i == (this.sections.quarters.num_cols - 1) ) { return 'Total'; }\n return this.data.taxrates[(i-1)].name;\n };\n this.taxreport.cellValue = function(s, i, j, d) {\n if( j == 0 ) { return d.start_date + ' - ' + d.end_date; }\n if( j > 1 && j == (this.sections.quarters.num_cols - 1) ) { return d.total_amount_display; }\n return d.taxrates[this.data.taxrates[(j-1)].id].amount_display;\n };\n this.taxreport.setup = function() {\n };\n this.taxreport.open = function(cb, report) {\n var method = '';\n switch (report) {\n case 'taxreport': method = 'ciniki.sapos.reportInvoicesTaxes'; break;\n }\n M.api.getJSONCb(method, {'tnid':M.curTenantID}, function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n }\n var p = M.ciniki_sapos_invoicereports[report];\n p.data = rsp;\n if( p.data.taxrates.length > 1 ) {\n p.sections.quarters.num_cols = p.data.taxrates.length + 2;\n } else {\n p.sections.quarters.num_cols = 2;\n }\n p.refresh();\n p.show(cb);\n });\n };\n this.taxreport.addClose('Back');\n\n //\n // Report for Ontario, Canada HST\n //\n this.ontariohst = new M.panel('Ontario HST',\n 'ciniki_sapos_invoicereports', 'ontariohst',\n 'mc', 'large', 'sectioned', 'ciniki.sapos.invoicereports.ontariohst');\n this.ontariohst.year = null;\n this.ontariohst.quarter = 0;\n this.ontariohst.data = {};\n this.ontariohst.sections = {\n 'years':{'label':'', 'type':'paneltabs', 'selected':'', 'tabs':{}},\n 'quarters':{'label':'', 'visible':'no', 'type':'paneltabs', 'selected':'1', 'tabs':{\n '1':{'label':'Jan-Mar', 'fn':'M.ciniki_sapos_invoicereports.showOntarioHST(null,null,1);'},\n '2':{'label':'Apr-Jun', 'fn':'M.ciniki_sapos_invoicereports.showOntarioHST(null,null,2);'},\n '3':{'label':'Jul-Sep', 'fn':'M.ciniki_sapos_invoicereports.showOntarioHST(null,null,3);'},\n '4':{'label':'Oct-Dec', 'fn':'M.ciniki_sapos_invoicereports.showOntarioHST(null,null,4);'},\n }},\n 'taxes':{'label':'', 'type':'simplegrid', 'num_cols':2,\n 'sortable':'yes',\n 'headerValues':['Invoice #', 'Date', 'Customer', 'Amount', 'Status'],\n 'sortTypes':['number', 'date', 'text', 'number', 'text'],\n 'noData':'No Invoices Found',\n },\n };\n this.ontariohst.sectionData = function(s) {\n return this.data[s];\n };\n this.ontariohst.cellValue = function(s, i, j, d) {\n switch(j) {\n case 0: return d.hst_line;\n case 1: return d.hst_value;\n }\n };\n this.ontariohst.addClose('Back');\n\n //\n // Arguments:\n // aG - The arguments to be parsed into args\n //\n this.start = function(cb, appPrefix, aG) {\n args = {};\n if( aG != null ) { args = eval(aG); }\n\n //\n // Create the app container if it doesn't exist, and clear it out\n // if it does exist.\n //\n var appContainer = M.createContainer(appPrefix, 'ciniki_sapos_invoicereports', 'yes');\n if( appContainer == null ) {\n M.alert('App Error');\n return false;\n } \n\n if( args.report != null && args.report != '' ) {\n this.taxreport.open(cb, args.report);\n }\n };\n\n}", "function VistaPreviaReporte() {\r\n ProcesarReporte('view',0);\r\n}", "function createVoucherReport(journal, report, docNumber, rowsToProcess) {\n\n //Each voucher on a new page\n report.addPageBreak();\n\n var date = \"\";\n var doc = \"\"; \n var desc = \"\";\n var totDebit = \"\";\n var totCredit = \"\";\n var line = 0;\n var totTransaction = calculateTotalTransaction(docNumber, journal, report); //Calculate the total value of the transaction\n\n /* Calculate the total number of pages used to print each voucher */\n var totRows = calculateTotalRowsOfTransaction(docNumber, journal, report);\n if (totRows > generalParam.numberOfRows) {\n var totalPages = Banana.SDecimal.divide(totRows, generalParam.numberOfRows);\n totalPages = parseFloat(totalPages);\n totalPages += 0.499999999999999;\n var context = {'decimals' : 0, 'mode' : Banana.SDecimal.HALF_UP}\n totalPages = Banana.SDecimal.round(totalPages, context);\n } else {\n var totalPages = 1;\n }\n\n //Define table info: name and columns\n var tableInfo = report.addTable(\"table_info\");\n var col1 = tableInfo.addColumn(\"col1\");\n var col2 = tableInfo.addColumn(\"col2\");\n var col3 = tableInfo.addColumn(\"col3\");\n var col4 = tableInfo.addColumn(\"col4\");\n var col5 = tableInfo.addColumn(\"col5\");\n var col6 = tableInfo.addColumn(\"col6\");\n var col7 = tableInfo.addColumn(\"col7\");\n var col8 = tableInfo.addColumn(\"col8\");\n var col9 = tableInfo.addColumn(\"col9\");\n var col10 = tableInfo.addColumn(\"col10\");\n var col11 = tableInfo.addColumn(\"col11\");\n\n //Define table transactions: name and columns\n\n if (Banana.document.table('ExchangeRates')) {\n var table = report.addTable(\"table\");\n var ct1 = table.addColumn(\"ct1\");\n var ct2 = table.addColumn(\"ct2\");\n var ct3 = table.addColumn(\"ct3\");\n var ct4 = table.addColumn(\"ct4\");\n var ct5 = table.addColumn(\"ct5\");\n var ct5 = table.addColumn(\"ct6\");\n var cts1 = table.addColumn(\"cts1\");\n var ct4 = table.addColumn(\"ct7\");\n var cts2 = table.addColumn(\"cts2\");\n var ct5 = table.addColumn(\"ct8\");\n var cts3 = table.addColumn(\"cts3\");\n var ct6 = table.addColumn(\"ct9\");\n } else {\n var table = report.addTable(\"table\");\n var c1 = table.addColumn(\"c1\");\n var c2 = table.addColumn(\"c2\");\n var c3 = table.addColumn(\"c3\");\n var cs1 = table.addColumn(\"cs1\");\n var c4 = table.addColumn(\"c4\");\n var cs2 = table.addColumn(\"cs2\");\n var c5 = table.addColumn(\"c5\");\n var cs3 = table.addColumn(\"cs3\");\n var c6 = table.addColumn(\"c6\");\n }\n\n //Define table signatures: name and columns\n var tableSignatures = report.addTable(\"table_signatures\");\n var colSig1 = tableSignatures.addColumn(\"colSig1\");\n var colSig2 = tableSignatures.addColumn(\"colSig2\");\n var colSig3 = tableSignatures.addColumn(\"colSig3\");\n var colSig4 = tableSignatures.addColumn(\"colSig4\");\n var colSig5 = tableSignatures.addColumn(\"colSig5\");\n var colSig6 = tableSignatures.addColumn(\"colSig6\");\n\n //Select from the journal all the given rows, take all the needed data, calculate totals and create the vouchers print\n for (j = 0; j < rowsToProcess.length; j++) {\n for (i = 0; i < journal.rowCount; i++) {\n if (i == rowsToProcess[j]) {\n var tRow = journal.row(i);\n date = tRow.value(\"Date\");\n }\n }\n }\n\n /* 1. Print the date and the voucher number */\n printInfoVoucher(tableInfo, report, docNumber, date, totalPages);\n\n /* 2. Print the all the transactions data */\n printTransactions(table, journal, line, rowsToProcess);\n \n /* 3. Print the total line */\n printTotal(table, totDebit, totCredit, report, totalPages, totTransaction);\n \n /* 4. Print the signatures line */\n printSignatures(tableSignatures, report);\n\n currentPage++;\n}", "function ReportPanelRenderer() {\n this._reports = [];\n this._currReportInd = 0;\n}", "function printReport() {\n\n\tvar report = Banana.Report.newReport(param.reportName);\n\n\treport.addParagraph(param.title, \"heading1\");\n\treport.addParagraph(\" \");\n\treport.addParagraph(param.headerLeft + \" - \" + param.headerRight, \"heading3\");\n\treport.addParagraph(\"Periodo contabile: \" + Banana.Converter.toLocaleDateFormat(param.startDate) + \" - \" + Banana.Converter.toLocaleDateFormat(param.endDate), \"heading4\");\n\treport.addParagraph(\" \");\n\t\n\tvar table = report.addTable(\"table\");\n\ttableRow = table.addRow();\n\ttableRow.addCell(\"ID\", \"bold\", 1);\n\ttableRow.addCell(\"GRUPPO\", \"bold\", 1)\n\ttableRow.addCell(\"DESCRIZIONE\", \"bold\", 1);\n\ttableRow.addCell(\"IMPORTO\", \"bold\", 1);\n\n\tfor (var k = 0; k < form.length; k++) {\n\t\n\tif (form[k].sum) {\n\t\ttableRow = table.addRow();\n\t\ttableRow.addCell(form[k].id, \"bold\", 1);\n\t\ttableRow.addCell(form[k].gr, \"bold\", 1);\n\t\ttableRow.addCell(form[k].description, \"bold\", 1);\n\t\ttableRow.addCell(getBalance(form[k].gr), \"alignRight bold\", 1);\n\t} else {\n\t\ttableRow = table.addRow();\n\t\ttableRow.addCell(form[k].id, \"\", 1);\n\t\ttableRow.addCell(form[k].gr, \"\", 1);\n\t\ttableRow.addCell(form[k].description, \"\", 1);\n\t\ttableRow.addCell(getBalance(form[k].gr), \"alignRight\", 1);\n\t\t}\n\t}\n\n\t//Add the footer to the report\n\taddFooter(report)\n\n\t//Print the report\n\tvar stylesheet = createStyleSheet();\n\tBanana.Report.preview(report, stylesheet);\n}", "createUI() {\n var title = panelTitle;\n this.panel = new PanelClass(this.viewer, title);\n var button1 = new Autodesk.Viewing.UI.Button(panelTitle);\n\n button1.onClick = (e) => {\n if (!this.panel.isVisible()) {\n this.panel.setVisible(true);\n } else {\n this.panel.setVisible(false);\n }\n };\n\n button1.addClass('fa');\n button1.addClass('fa-child');\n button1.addClass('fa-2x');\n button1.setToolTip(onMouseOver);\n\n this.subToolbar = this.viewer.toolbar.getControl(\"spinalcom-sample\");\n if (!this.subToolbar) {\n this.subToolbar = new Autodesk.Viewing.UI.ControlGroup('spinalcom-sample');\n this.viewer.toolbar.addControl(this.subToolbar);\n }\n this.subToolbar.addControl(button1);\n this.initialize();\n }", "function renderViz() {\n\n // Define variables for viz\n var mainVizDiv = $(\"#tableauViz\");\n var mainVizOptions = {\n hideTabs: true,\n hideToolbar: true,\n //toolbarPositon: top, // (or \"bottom\")\n width: 850,\n height: 860,\n onFirstInteractive: function () {\n mainWorkbook = mainViz.getWorkbook();\n }\n };\n // Create viz\n mainViz = new tableauSoftware.Viz(mainVizDiv[0], url, mainVizOptions);\n}", "function generateRoverReport(){\n\t$('div#roverReport').empty();\n\t$('div#roverReport').append(\"<h2>Rover Report:</h2>\");\n\n\tallRoversObjArray.forEach(function(rover) {\n\t\tvar reportWrapper = document.createElement(\"div\");\n\t\treportWrapper.className = 'reportWrapper alert alert-primary col-md-12 col-sm-4';\n\n\t\tvar roverNameHTML = '<h3> Rover Name: ' + rover.name +'</h3>';\n\t\tvar locationHTML = 'Currently Located at ' + rover.x + ',' + rover.y + ' and facing ' + rover.getFacingDirection();\n\n\t\t$('div#roverReport').append(reportWrapper);\n\n\t\t$('div.reportWrapper:last').append(roverNameHTML).append(locationHTML);\n\n\t});\n\n}", "function ProvVis() {\n\t/**Index of the instance in the array of the parent.*/\n\tthis.index = -1;\n\t/**Array of children instances, in case there is more than one graph on a page.*/\n\tthis.array = [];\n\t/**Class handling the visualisation of graph.*/\t\n\tthis.graph = new ProvVisGraph(this);\n\t/**Core function of provvis.*/\n\tthis.core = new ProvVisCore(this);\n\t/**Communication with the Provenance Service at the server-side.*/\n\tthis.comm = new ProvVisComm(this);\n\t/**Layout of the graph.*/\n\tthis.layout = new ProvVisLayout(this);\t\n\t/**Functions for editing the provenance.*/\n\tthis.edit = new ProvVisEdit(this);\t\n\t/**Class for connecting the nodes.*/\n\tthis.jsPlumb = jsPlumb.getInstance();\n\tthis.jsPlumb.reset();\n\tthis.jsPlumb.Defaults.PaintStyle = {\n\t\t\t\tlineWidth : 4,\n\t\t\t\tstrokeStyle : \"#aaa\"\n\t};\n\tthis.jsPlumb.Defaults.Endpoint = [ \"Dot\", {\n\t\t\t\tradius : 10\n\t\t\t}, {\n\t\t\t\tisSource : true,\n\t\t\t\tisTarget : true\n\t} ];\n\tthis.jsPlumb.Defaults.MaxConnections = 10;\n\tthis.jsPlumb.Defaults.Container = $(\"#\" + this.jsPlumb.canvas);\n\t/**Creates an instance of ProvVis and adds it to the array.*/\n\tthis.getProvVis = function(){\n\t\tvar p = new ProvVis();\n\t\tp.index = this.array.length;\n\t\tthis.array.push(p);\n\t\treturn p;\n\t};\n}", "function create_main_obj(){\n chart_container.show();\n var newValues={};\n newValues.pop=population_slider.slider(\"value\");\n newValues.genome=genome_slider.slider(\"value\");\n newValues.mutate=mutation_prob_slider.slider(\"value\");\n newValues.fight=tournament_size_slider.slider(\"value\");\n newValues.gens=generations_slider.slider(\"value\");\n main_evolution_obj = new ea(newValues.pop, newValues.genome, newValues.mutate, newValues.fight);\n }", "function TriageViewStandalone(container, values) {\n // Container is unused (global hardcoded dialog is used)\n this.videoPlayer = null;\n this.container = container;\n\n this.div = document.createElement('div');\n $(this.div).html(' <h2> <span class=\"triageLabel\"> </span> </h2> ' +\n '<br/> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"span4\"> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"triageClipEvidences\" class=\"span4\"> ' +\n '</div> ' +\n '</div> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"triageAdjudicationHeading\" class=\"span4\"> ' +\n '<h4> Adjudication </h4> <br/>' +\n\n '<div class=\"triageAdjudication\" class=\"span4\"> </div>' +\n '</div> ' +\n\n '</div> ' +\n '</div> ' +\n '<div class=\"triageVideo video-container span8\"> ' +\n '</div> ' +\n '</div> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"span12\"> ' +\n '<div class=\"triageTimeLineView\"></div> ' +\n '</div> ' +\n '</div> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"span12\"> ' +\n '<div class=\"triageFilmStripView\"></div> ' +\n '</div> ' +\n '</div> '\n );\n\n $(this.div).appendTo($(this.container));\n this.Init(values);\n this.adjudication = new Adjudication({container : $(this.div).find(\".triageAdjudication\")[0], clip : this.data.clip, display:true, opacity : 0.5});\n $(this.adjudication.div).css(\"position\",\"relative\");\n\n var that = this;\n // TODO: This should be called after results\n $(this.div).find('.triageClipEvidences').on('click', 'div label', function(event) {\n //if (!that.textView || !that.timelineView) {\n // return;\n //}\n\n event.stopPropagation();\n\n // Select current element\n that.textView.selectElement(this);\n var labelObj = $(this);\n\n// console.log('selecting......', labelObj.text());\n\n var timestamps = that.timelineView.select(labelObj.text());\n that.filmstripView.HideAll();\n for(var i=0; i < timestamps.length; i++)\n {\n that.filmstripView.SelectTimestamp(timestamps[i], \"selectframe_text\")\n }\n });\n\n// // Now initialize the timeline\n// $('#myModal').on('shown', function() {\n// if (that.currentClipId === null || that.currentClipId !== that.clip_id) {\n// return;\n// }\n// // Now show it\n// var clipEvidencesObj = $('#clipEvidences');\n// var timelineViewObj = $('#timelineView');\n// var filmstripViewObj = $('#filmstripView');\n//\n// // that.textView = new textView(clipEvidencesObj.get(0), that.data);\n// // that.timelineView = new timelineView(timelineViewObj.get(0), that.data);\n// // that.currentClipId = null;\n//\n// // Get the data\n// //var algorithm = $(\"#algorithms-combo\").find('option:selected').data('algo');\n\n\n //this.updateResults(that.kit_id, that.clip_id);\n\n $('body').on('selectedStandAlone', function(event, name, timestamp, x, y) {\n // that.filmstripView.SelectTime(event, timestamp);\n //alert('' + x+ y);\n that.filmstripView.ClearHighlight();\n that.filmstripView.SelectTimestamp(timestamp, \"selectframe_timeline\");\n that.selectStandalone(name, timestamp);\n });\n\n//\n// $('#myModal').on('hidden', function () {\n// // Clear current rendering\n// that.currentClipId = null;\n// if (that.videoPlayer) {\n// that.videoPlayer.pause();\n// }\n// });\n//\n// //$(this.div).click(function()\n//\n\n // Respond to adjugation buttons\n\n// $(this.div).find(\".triageAdjudication img\").click(function(event) {\n//\n// event.stopPropagation();\n// // TODO: Send the ajax to api\n//\n// switch($(this).attr(\"class\")) {\n// case \"yes\":\n// if ($(this).attr('src') === '/img/carbon-verified.png') {\n// $(this).attr('src', '/img/carbon-verified_on.png')\n// $(this).next().attr('src', '/img/carbon-rejected.png')\n// $(this).next().next().attr('src', '/img/carbon-star2.png')\n// } else {\n// $(this).attr('src', '/img/carbon-verified.png')\n// }\n// break;\n// case \"no\":\n// if ($(this).attr('src') === '/img/carbon-rejected.png') {\n// $(this).attr('src', '/img/carbon-rejected_on.png')\n// $(this).next().attr('src', '/img/carbon-star2.png')\n// $(this).prev().attr('src', '/img/carbon-verified.png')\n// } else {\n// $(this).attr('src', '/img/carbon-rejected.png')\n// }\n// break;\n// case \"star\":\n// if ($(this).attr('src') === '/img/carbon-star2.png') {\n// $(this).attr('src', '/img/carbon-star_on.png')\n// $(this).prev().attr('src', '/img/carbon-rejected.png')\n// $(this).prev().prev().attr('src', '/img/carbon-verified.png')\n// } else {\n// $(this).attr('src', '/img/carbon-star2.png')\n// }\n// break;\n// }\n// });\n//\n// var that = this;\n//\n// $(this.div).find(\".triageAdjudication div\").click(function(event) {\n// event.stopPropagation();\n//\n// // if ($(this).hasClass('btn')) {\n// // $(that.div).find(\".triageAdjudication div\").find('.myLabel').show();\n// // console.log($('#adjudication div').find('input').text());\n// // $(that.div).find(\".triageAdjudication div\").find('label').text($(that.div).find(\".triageAdjudication div\").find('input').val());\n// // $(that.div).find(\".triageAdjudication div\").find('input').addClass(\"disabled\");\n// // }\n// // if ($(this).hasClass('myLabel')) {\n// // $(that.div).find(\".triageAdjudication div\").find('input').val($(this).text());\n// // $(this).hide();\n// // $(that.div).find(\".triageAdjudication div\").find('input').show();\n// // }\n// if ($(event.target).hasClass('input')) {\n// //console.log(\"enabled\");\n// //$(event.target).removeAttr(\"disabled\",\"\");\n// }\n//\n// });\n//\n//$(this.div).find('.triageAdjudication div').find('input').keypress(function(e) {\n// if(e.which == 13) {\n// $(that.div).find(\".triageAdjudication div\").find('.myLabel').show();\n// //console.log($('#adjudication div').find('input').text());\n// //$(that.div).find(\".triageAdjudication div\").find('label').text($(that.div).find(\".triageAdjudication div\").find('input').val());\n// //$(that.div).find(\".triageAdjudication div\").find('input').attr(\"disabled\",\"\");\n// $(that.div).find(\".triageAdjudication div\").find('input').blur();\n// }\n// e.stopPropagation();\n// });\n\n}", "onDemandCreateGUI() {\n \n if (this.internal.parentDomElement===null)\n return;\n \n this.internal.parentDomElement.empty();\n \n let basediv=webutil.creatediv({ parent : this.internal.parentDomElement});\n this.internal.domElement=basediv;\n \n let f1 = new dat.GUI({autoPlace: false});\n basediv.append(f1.domElement);\n\n // Global Properties\n let s1_on_cb=(e) => {\n let ind=this.internal.data.allnames.indexOf(e);\n this.setCurrentGrid(ind);\n };\n\n this.internal.data.allnames=[];\n for (let i=0;i<this.internal.multigrid.getNumGrids();i++) {\n this.internal.data.allnames.push(this.internal.multigrid.getGrid(i).description);\n }\n \n let sl=f1.add(this.internal.data,'currentname',this.internal.data.allnames).name(\"Current Grid\");\n sl.onChange(s1_on_cb);\n\n let dp=f1.add(this.internal.data,'showmode',this.internal.data.allshowmodes).name(\"Grids to Display\");\n let dp_on_cb=() => {\n this.showhidemeshes();\n this.updategui(true);\n };\n dp.onChange(dp_on_cb);\n\n webutil.removedatclose(f1);\n\n \n // --------------------------------------------\n let ldiv=$(\"<H4></H4>\").css({ 'margin':'15px'});\n basediv.append(ldiv);\n\n this.internal.landlabelelement=webutil.createlabel( { type : \"success\",\n name : \"Current Electrode Properties\",\n parent : ldiv,\n });\n let sbar=webutil.creatediv({ parent: basediv});\n let inlineform=webutil.creatediv({ parent: sbar});\n let elem1=webutil.creatediv({ parent : inlineform,\n css : {'margin-top':'20px', 'margin-left':'10px'}});\n \n let elem1_label=$(\"<span>Electrode: </span>\");\n elem1_label.css({'padding':'10px'});\n elem1.append(elem1_label);\n this.internal.currentelectrodeselect=webutil.createselect({parent : elem1,\n values : [ 'none' ],\n callback : (e) => {\n this.selectElectrode(e.target.value,true);\n this.centerOnElectrode();\n },\n });\n\n this.internal.checkbuttons={};\n\n let sbar2=webutil.creatediv({ parent: basediv});\n for (let i=0;i<PROPERTIES.length;i++) {\n this.internal.checkbuttons[PROPERTIES[i]]=\n webutil.createcheckbox({\n name: PROPERTIES[i],\n type: \"info\",\n checked: false,\n parent: sbar2,\n css: { 'margin-left': '5px' ,\n 'margin-right': '5px',\n 'width' : '100px'}\n });\n }\n \n \n \n\n // ----------- Landmark specific stuff\n\n if (this.internal.gridPropertiesGUI===null) {\n const f2 = new dat.GUI({autoPlace: false});\n console.log('F2=',f2,JSON.stringify(this.internal.data));\n \n console.log('Creating modal');\n let modal=webutil.createmodal(\"Grid Properties\",\"modal-sm\");\n this.internal.gridPropertiesGUI=modal.dialog;\n modal.body.append(f2.domElement);\n\n \n console.log('Radius=',this.internal.data.radius);\n \n f2.add(this.internal.data, 'radius',0.5,8.0).name(\"Radius\").step(0.5).onChange(() => {\n let grid=this.internal.multigrid.getGrid(this.internal.currentgridindex);\n grid.radius=this.internal.data.radius;\n this.updateMeshes(true);\n });\n \n console.log('Color=',this.internal.data.color);\n \n f2.addColor(this.internal.data, 'color').name(\"Landmark Color\").onChange(()=> { \n this.updatecolors();\n });\n \n webutil.removedatclose(f2);\n this.internal.folders=[f1, f2];\n } else {\n this.internal.folders[0]=f1;\n }\n // Save self for later\n \n // ---------------\n // rest of gui \n // ---------------\n\n let bbar0=webutil.createbuttonbar({ parent: basediv,\n css : {'margin-top': '20px','margin-bottom': '10px'}});\n\n \n let update_cb=() => { this.updateGridProperties();};\n webutil.createbutton({ type : \"primary\",\n name : \"Display Properties\",\n position : \"bottom\",\n tooltip : \"Click this to set advanced display properties for this set (color,radius)\",\n parent : bbar0,\n callback : update_cb,\n });\n\n let load_cb=(f) => { this.loadMultiGrid(f); };\n webfileutil.createFileButton({ type : \"warning\",\n name : \"Load\",\n position : \"bottom\",\n tooltip : \"Click this to load points from either a .mgrid or a .bisgrid file\",\n parent : bbar0,\n callback : load_cb,\n },{\n filename : '',\n title : 'Select file to load current landmark set from',\n filters : [ { name: 'Landmark Files', extensions: ['bisgrid','land' ]}],\n save : false,\n suffix : \".bisgrid,.mgrid\",\n });\n\n let save_cb=(f) => {\n f=f || 'landmarks.bisgrid';\n console.log('f=',f);\n let suffix=f.split(\".\").pop();\n if (suffix===\"land\")\n return this.exportMultiGrid(f);\n else\n return this.saveMultiGrid(f);\n };\n\n\n \n webfileutil.createFileButton({ type : \"primary\",\n name : \"Save\",\n position : \"bottom\",\n tooltip : \"Click this to save points to a .bisgrid or .mgrid file\",\n parent : bbar0,\n callback : save_cb,\n },\n {\n filename : '',\n title : 'Select file to load current landmark set from',\n filters : [ { name: 'Landmark Files', extensions: ['bisgrid','land' ]}],\n save : true,\n suffix : \".bisgrid,.mgrid\",\n initialCallback : () => { return this.getInitialSaveFilename(); },\n });\n\n \n webutil.createbutton({ type : \"info\",\n name : \"Multisnapshot (Current Grid)\",\n parent : bbar0,\n css : {\n 'margin-top': '20px',\n 'margin-left': '10px'\n },\n callback : () => { this.multisnapshot(false).catch( (e) => { console.log(e);});}\n });\n\n webutil.createbutton({ type : \"danger\",\n name : \"Multisnapshot (All Grids)\",\n parent : bbar0,\n css : {\n 'margin-top': '20px',\n 'margin-left': '10px'\n },\n callback : () => { this.multisnapshot(true).catch( (e) => { console.log(e);});}\n });\n\n \n webutil.tooltip(this.internal.parentDomElement);\n \n // ----------------------------------------\n // Now create modal\n // ----------------------------------------\n\n \n\n }", "function buildUI(thisObj){\n\n\t\t\t// ----- Main Window -----\n\t\t\tvar w = (thisObj instanceof Panel) ? thisObj : new Window(\"palette\", scriptName);\n\t\t\t\tw.alignChildren = ['fill', 'fill'];\n\n\t\t\t\tw.add(\"statictext\", undefined, \"Use the + button to add a project, or use the ? button to access the settings window and import a previous list.\", {multiline: true});\n\n\t\t\t\t// group for panel buttons\n\t\t\t\tvar panelBtns = w.add(\"group\");\n\n\t\t\t\t\t//panel buttons\n\t\t\t\t\tvar addProjBtn = panelBtns.add(\"button\", undefined, \"+\");\n\t\t\t\t\tvar remProjBtn = panelBtns.add(\"button\", undefined, \"-\");\n\t\t\t\t\tvar settingsBtn = panelBtns.add(\"button\", undefined, \"?\");\n\n\t\t\t\t\taddProjBtn.preferredSize = \n\t\t\t\t\tremProjBtn.preferredSize = \n\t\t\t\t\tsettingsBtn.preferredSize = [80, 30] \n\n\t\t\t\t// group for list of projects\n\t\t\t\tvar projsListGroup = w.add(\"group\");\n\t\t\t\t\tprojsListGroup.alignChildren = ['fill', 'fill'];\n\n\t\t\t\t\t// project list\n\t\t\t\t\tvar projList = projsListGroup.add(\"listbox\", undefined, theProjectNames, {scrollable: true});\n\t\t\t\t\t\tprojList.preferredSize = ['', 250]\n\n\t\t\t\t// group for system buttons\n\t\t\t\tvar systemBtns = w.add(\"group\");\n\n\t\t\t\t\t// system buttons\n\t\t\t\t\tvar importBtn = systemBtns.add(\"button\", undefined, \"Import\")\n\t\t\t\t\tvar openBtn = systemBtns.add(\"button\", undefined, \"Open\");\n\t\t\t\t\tvar cancelBtn = systemBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t\timportBtn.preferredSize =\n\t\t\t\t\topenBtn.preferredSize =\n\t\t\t\t\tcancelBtn.preferredSize = [80, 30]\n\n\t\t\t\t\t// ----- Main Window Functionality -----\n\t\t\t\taddProjBtn.onClick = function(){\n\t\t\t\t\taddProject();\n\t\t\t\t}\n\n\t\t\t\tremProjBtn.onClick = function(){\n\n\t\t\t\t\tdelete theList[projList.selection];\n\t\t\t\t\tupdateProjList(getProjectNames(theList));\t\t\t\t\n\n\t\t\t\t}\n\n\t\t\t\tsettingsBtn.onClick = function(){\n\t\t\t\t\tmakeSettingsWindow();\n\t\t\t\t}\n\n\t\t\t\timportBtn.onClick = function(){\n\n\t\t\t\t\tapp.project.importFile(new ImportOptions(File(theList[projList.selection])));\n\t\t\t\t}\n\n\t\t\t\topenBtn.onClick = function(){\n\t\t\t\t\tapp.open(File(theList[projList.selection]));\n\t\t\t\t}\n\n\t\t\t\tcancelBtn.onClick = function(){\n\n\t\t\t\t\tw.close();\n\t\t\t\t}\n\n\t\t\t\tw.onClose = function(){\n\t\t\t\t\tif (checkObjectForEmpty(theList) == false){\n\t\t\t\t\t\twriteListFile(theList); // save the list when closing the panel.\n\t\t\t\t\t } else {\n\t\t\t\t\t\twriteListFile(new Object ())\n\t\t\t\t\t }\t\n\t\t\t\t}\n\n\t\t\t\t// ----- End Main Window Functionality -----\n\n\t\t\t// ----- End Main Window -----\n\n\n\n\n\n\n\n\n\n\t\t\t// ----- Make Add Project Window -----\n\n\t\t\tfunction addProject(){\n\n\t\t\t\tvar addProjWindow = new Window(\"palette\", \"Add Project\");\n\n\t\t\t\t// group for custom project\n\t\t\t\tvar customProjGroup = addProjWindow.add(\"group\");\n\t\t\t\t\tcustomProjGroup.orientation = \"column\";\n\t\t\t\t\tcustomProjGroup.alignChildren = ['left', 'fill']\n\n\t\t\t\t\t// Project name group\n\t\t\t\t\tvar projNameGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojNameGroup.add(\"statictext\", undefined, \"Project Name:\")\n\t\t\t\t\t\t// Project Name\n\t\t\t\t\t\tvar projName = projNameGroup.add(\"edittext\", undefined, \"Project Name\");\n\t\t\t\t\t\t\tprojName.characters = 32;\n\n\t\t\t\t\t// Project location group\n\t\t\t\t\tvar projLocGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojLocGroup.add(\"statictext\", undefined, \"Project Location:\")\n\n\t\t\t\t\t\t// Project Location\n\t\t\t\t\t\tvar projLoc = projLocGroup.add(\"edittext\", undefined, \"Project Location\");\n\t\t\t\t\t\t\tprojLoc.characters = 24;\n\n\t\t\t\t\t\tvar getProjLoc = projLocGroup.add(\"button\", undefined, \"...\");\n\t\t\t\t\t\t\tgetProjLoc.preferredSize = [31, 20];\n\n\t\t\t\t// group for buttons\n\t\t\t\tvar addProjBtns = addProjWindow.add(\"group\");\n\n\t\t\t\t\t// button for current project\n\t\t\t\t\tvar setCurProjBtn = addProjBtns.add(\"button\", undefined, \"Set Current\");\n\n\t\t\t\t\t// button to add the project\n\t\t\t\t\tvar addProjBtn = addProjBtns.add(\"button\", undefined, \"Add Project\");\n\t\t\t\t\t\n\t\t\t\t\t// button to cancel\n\t\t\t\t\tvar cancelAddBtn = addProjBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t// ----- SHOW WINDOW -----\n\t\t\t\taddProjWindow.show();\n\t\t\t\t\n\t\t\t\t// ----- Add Project Window Functionality -----\n\t\t\t\tgetProjLoc.onClick = function(){\n\t\t\t\t\tvar getAEP = File.openDialog(\"Please select the location of an AEP.\");\n\t\t\t\t\tif (getAEP != null){\n\n\t\t\t\t\t\tif (getAEP.fsName.split(\".\").pop() == \"aep\"){\n\n\t\t\t\t\t\t\tprojName.text = getAEP.fsName.split(\"/\").pop();\n\t\t\t\t\t\t\tprojLoc.text = getAEP.fsName;\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(getAEP.name.split(\".\")[0] + \" is a \" + getAEP.fsName.split(\".\").pop() + \" file. Please select an AEP!\")\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Could not open file. Please make sure you selected something!\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsetCurProjBtn.onClick = function(){\n\n\t\t\t\t\tif (app.project){\n\n\t\t\t\t\t\tprojName.text = String(app.project.file).split(\"/\").pop();\n\t\t\t\t\t\tprojLoc.text = app.project.file;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Please open a Project!\");\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\taddProjBtn.onClick = function(){\n\n\t\t\t\t\tif (new File(projLoc.text).exists){\n\t\t\t\t\t\tif(projName.text.length > 0 && projName.text != \"Project Name\"){\n\t\t\t\t\t\t\ttheList[projName.text] = projLoc.text;\n\t\t\t\t\t\t\tupdateProjList(getProjectNames(theList));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(\"The name \\'\" + projName.text + \"\\' is not valid. Please choose a better name.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"File at \" + projLoc.text + \" does not exist. Please double check that you've selected the correct file.\")\n\t\t\t\t\t}\n\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tcancelAddBtn.onClick = function(){\n\n\t\t\t\t\treturn addProjWindow.close();\n\t\t\t\t}\n\n\t\t\t} // ----- End Add Project Window -----\n\n\n\n\n\n\n\n\n\n\t\t\t// ----- Make Settings Window -----\n\n\t\t\tfunction makeSettingsWindow(){\n\n\t\t\t\tvar settingsWindow = new Window(\"palette\", \"Settings\");\n\t\t\t\t\tsettingsWindow.alignChildren = ['fill', 'fill'];\n\n\t\t\t\t\t// group for text (about, etc)\n\t\t\t\t\tvar aboutGroup = settingsWindow.add(\"group\");\n\n\t\t\t\t\t\taboutGroup.add(\"statictext\", undefined, aboutText, {multiline: true});\n\n\t\t\t\t\t// group for importing and exporting lists\n\t\t\t\t\tvar importExportListGroup = settingsWindow.add(\"group\");\n\n\t\t\t\t\t\t// import list\n\t\t\t\t\t\tvar importListBtn = importExportListGroup.add(\"button\", undefined, \"Import List\");\n\t\t\t\t\t\tvar exportListBtn = importExportListGroup.add(\"button\", undefined, \"Export List\");\n\n\t\t\t\t\t// group for settings buttons (OK)\n\t\t\t\t\tvar settingsBtns = settingsWindow.add(\"group\");\n\n\t\t\t\t\t\t// button to close the window\n\t\t\t\t\t\tvar closeSettings = settingsBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t// ----- Show Window -----\n\t\t\t\tsettingsWindow.show();\n\n\t\t\t\t// ----- Settings Window FUNCTIONALITY -----\n\t\t\t\timportListBtn.onClick = function(){\n\t\t\t\t\tvar theNewList = File.openDialog(\"Please select a JSON file created by this script.\");\n\t\t\t\t\tif (theNewList != null){\n\t\t\t\t\t\ttheList = readJSONFile(theNewList);\n\t\t\t\t\t\tupdateProjList(getProjectNames(theList));\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Could not open JSON file. Please try again and ensure a JSON file is selected.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\texportListBtn.onClick = function(){\n\t\t\t\t\tvar saveLoc = Folder.selectDialog(\"Please select a location to save your .JSON file.\");\n\t\t\t\t\tif (saveLoc != null){\n\t\t\t\t\t\texportList(theList, saveLoc);\n\t\t\t\t\t} \n\t\t\t\t}\n\n\t\t\t\tcloseSettings.onClick = function(){\t\t\t\t\n\t\t\t\t\treturn settingsWindow.close();\n\t\t\t\t}\n\n\t\t\t} // ----- End Make Settings Window -----\n\n\n\n\n\n\n\n\n\n\t\t\t// ----- HELPER FUNCTIONS -----\n\t\t\t\n\t\t\tfunction updateProjList(newArrayOfItems){\n\t\t\t\tvar newList = projsListGroup.add(\"listbox\", projList.bounds, newArrayOfItems, {scrolling: true});\n\t\t\t\tprojsListGroup.remove(projList);\n\n\t\t\t\tprojList = newList;\n\t\t\t}\n\n\n\n\n\n\n\n\n\n\n\t\t\t\n\t\t\t// Return window.\n\t\t\tw.layout.layout(true);\n\t\t\treturn w;\n\n\n\t\t} // ----- End Build UI -----", "function addFooter(report) {\n report.getFooter().addClass(\"footer\");\n var versionLine = report.getFooter().addText(param.bananaVersion + \", \" + param.scriptVersion + \", \", \"description\");\n //versionLine.excludeFromTest();\n report.getFooter().addText(\"Pagina \", \"description\");\n report.getFooter().addFieldPageNr();\n}", "constructor() {\n this.nbPartiesAffichees = 0\n this.parties = [];\n \n this.afficher();\n }", "async function generatePokemonPanel(panelToAppendTo, pokemonObject) {\r\n const name = pokemonObject.name;\r\n \r\n const pokemonPanel = document.createElement(\"div\");\r\n pokemonPanel.style.backgroundColor = \"#46ACC2\"\r\n panelToAppendTo.appendChild(pokemonPanel);\r\n pokemonPanel.style.margin = \"50px\";\r\n pokemonPanel.addEventListener(\"click\", displayClickedPokemonDetails);\r\n pokemonPanel.id = name;\r\n\r\n const pokemonPanelPictureElement = document.createElement(\"img\");\r\n const pokemonPanelPictureAddress = \"https://trex-sandwich.com/pokesignment/img/\" + pokemonObject.image;\r\n pokemonPanelPictureElement.src = pokemonPanelPictureAddress;\r\n pokemonPanel.appendChild(pokemonPanelPictureElement);\r\n pokemonPanelPictureElement.id = name;\r\n pokemonPanelPictureElement.setAttribute(\"width\", \"100%\");\r\n\r\n const pokemonPanelNameElement = document.createElement(\"h2\");\r\n const pokemonPanelName = pokemonObject.name;\r\n pokemonPanelNameElement.innerHTML = `<strong id=${name}>${name}</strong>`;\r\n pokemonPanel.appendChild(pokemonPanelNameElement);\r\n pokemonPanelNameElement.style.fontSize = \"medium\";\r\n pokemonPanelNameElement.style.paddingBottom = \"10px\";\r\n pokemonPanelNameElement.id = name;\r\n pokemonPanelNameElement.setAttribute(\"width\", \"100\")\r\n }", "function DebateProjector(dispUrl) {\n //\n // debate-list initialization \n //\n\n // icons used for the markers\n // this.iconswtch = { \"§EVT\": \"./style/marker/waiting.png\",\n // \"§ANO\": \"./style/marker/schreibwaren_web.png\",\n // \"§INI\": \"./style/marker/family.png\",\n // \"§BUI\": \"./style/marker/mine.png\",\n // \"§LOC\": \"./style/marker/home-2.png\"\n // };\n\n // this.stndrIcon = \"./style/marker/text.png\";\n // this.displayUrl = dispUrl;\n\n this.iconswtch = { \n \"§EVT\": nejobaUrl(\"./style/marker/waiting.png\"),\n \"§ANO\": nejobaUrl(\"./style/marker/schreibwaren_web.png\"),\n \"§INI\": nejobaUrl(\"./style/marker/family.png\"),\n \"§BUI\": nejobaUrl(\"./style/marker/mine.png\"),\n \"§LOC\": nejobaUrl(\"./style/marker/home-2.png\")\n };\n\n this.stndrIcon = nejobaUrl(\"./style/marker/text.png\");\n this.displayUrl = nejobaUrl(dispUrl);\n\n this.printTmplt = [ ' <div id=\"Div1\">',\n ' <div class=\"row span12 well\">',\n ' <div class=\"span11\">',\n ' <h5>',\n ' <a href=\"§§URL_LINK_TARGET§§\" target=\"_blank\">§§URL_LINK_TEXT§§</a>',\n ' </h5>',\n ' </div>',\n ' <div class=\"span4\">',\n ' <strong>Ersteller: </strong>§§NICKNAME§§<br />',\n ' <strong>erstellt am: </strong>§§CREATIONTIME§§<br />',\n ' </div>',\n ' <div class=\"span3\">',\n ' <strong>vom: </strong>§§DATE_FROM§§<br />',\n ' <strong>bis: </strong>§§DATE_TILL§§<br />',\n ' </div>',\n ' <div class=\"span3\">',\n ' <strong>Ort: </strong>§§LOCATIONNAME§§<br />',\n ' </div>',\n ' <br />',\n ' </div>',\n ' </div>'].join('\\n');\n\n\n\n /*\n * function DebateProjector.defineItemIcon defines which marker-icon will be used for this item. \n *\n * parameter : dataItem is the item to display\n *\n * 30.06.2013 bervie initial realese\n *\n */\n this.defineDebateIcon = function (dataItm) {\n // console.log('DebateProjector.defineDebateIcon was called');\n if (dataItm.tagZero == undefined) {\n return this.stndrIcon\n }\n\n if (dataItm.tagZero.length > 0) {\n var typ = dataItm.tagZero.split(\"_\")[0];\n var icon = this.iconswtch[typ];\n }\n else {\n var icon = this.stndrIcon;\n }\n\n if (typeof icon === \"undefined\") icon = this.stndrIcon;\n return icon;\n }\n\n\n /*\n * display : this function is called from the ListExtractor. It creates the DIVs with the item-infos and writes it to the destination-DIV\n *\n * parameter : ItemArray \n * the array contains all items that should be displayed. the items are chosen from the ListExtractor\n * this projector-class has no logic for item-selection. it is only a dispaly-idiot\n *\n * 05.06.2013 bervie initial realese\n *\n */\n this.createItemDiv = function (val) {\n \n var rslt = this.printTmplt;\n\n // ´put the data inside the template\n rslt = rslt.replace(\"§§URL_LINK_TARGET§§\", this.displayUrl + val._ID);\n rslt = rslt.replace(\"§§URL_LINK_TEXT§§\", val.subject);\n rslt = rslt.replace(\"§§NICKNAME§§\", val.nickname);\n rslt = rslt.replace(\"§§CREATIONTIME§§\", val.creationTime);\n rslt = rslt.replace(\"§§DATE_FROM§§\", val.from);\n rslt = rslt.replace(\"§§DATE_TILL§§\", val.till);\n rslt = rslt.replace(\"§§LOCATIONNAME§§\", val.locationname);\n\n return rslt;\n }\n\n\n /*\n * display : this function is called from the ListExtractor. It creates the DIVs with the item-infos and writes it to the destination-DIV\n *\n * parameter : ItemArray \n * the array contains all items that should be displayed. the items are chosen from the ListExtractor\n * this projector-class has no logic for item-selection. it is only a dispaly-idiot\n *\n * 05.06.2013 bervie initial realese\n *\n */\n this.display = function (itemArray) {\n\n // console.log('DebateProjector.display was called ');\n var divContent = '';\n\n $.each(itemArray, function (i, val) {\n // console.log('Number ' + String(i) + ' ; Subject : ' + val.subject);\n\n divContent += projector.createItemDiv(val);\n });\n $('#canvasforlist').html(divContent);\n\n\n return;\n }\n\n}", "function setHtmlPanel(){\n\t\t\n\t\t//add panel wrapper\n\t\tg_objWrapper.append(\"<div class='ug-grid-panel'></div>\");\n\t\t\n\t\tg_objPanel = g_objWrapper.children('.ug-grid-panel');\n\t\t\n\t\t//add arrows:\n\t\tif(g_temp.isHorType){\n\t\t\t\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-left-hortype ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-right-hortype ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-left-hortype\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-right-hortype\");\n\t\t}\n\t\telse if(g_options.gridpanel_vertical_scroll == false){\t\t//horizonatl arrows\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-left ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-right ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-left\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-right\");\n\t\t\t\n\t\t}else{\t\t//vertical arrows\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-up ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-down ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-up\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-down\");\n\t\t}\n\t\t\n\t\tg_panelBase.setHtml(g_objPanel);\n\t\t\n\t\t//hide the arrows\n\t\tg_objArrowPrev.fadeTo(0,0);\n\t\tg_objArrowNext.fadeTo(0,0);\n\t\t\n\t\t//init the grid panel\n\t\tg_options.parent_container = g_objPanel;\n\t\tg_gallery.initThumbsPanel(\"grid\", g_options);\n\t\t\n\t\t//get the grid object\n\t\tvar objects = g_gallery.getObjects();\n\t\tg_objGrid = objects.g_objThumbs;\n\t\t\n\t\tsetHtmlProperties();\n\t}", "function pullautoreport(data) {\n phantom.create(function (ph) {\n ph.createPage(function (page) {\n\n var startdate = moment(new Date()).subtract(data.lengthdays,'d').format(\"YYYY-MM-DD\");\n var enddate = moment(new Date()).add(0,'d').format(\"YYYY-MM-DD\");\n\n page.set('viewportSize', {width: 1000, height: 480});\n var url = 'http://localhost:3000/autoreport/'+data.accountid+'/'+data.groupid+'/'+startdate+'/'+enddate;\n page.open(url, function (status) {\n if ( status != 'success' ) {console.log(\"--------- failed ----------\"); ph.exit();};\n page.includeJs(\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\", function() {\n setTimeout(function () {\n page.evaluate(function() {\n\n var accountid = document.data.accountid.value;\n var groupid = document.data.groupid.value;\n var startdate = document.data.start.value;\n var enddate = document.data.end.value;\n var totdailyimport = document.data.totdailyimport.value;\n var totdailyexport = document.data.totdailyexport.value;\n var dailygraph = document.data.dailygraph.value;\n var monthlygraph = document.data.monthlygraph.value;\n\n return {\n accountid:accountid,\n groupid:groupid,\n startdate:startdate,\n enddate:enddate,\n totdailyimport:totdailyimport,\n totdailyexport:totdailyexport,\n dailygraph:dailygraph,\n monthlygraph:monthlygraph\n }\n\n },\n function(result) {\n\n //console.log(result);\n // console.log(result.accountid);\n // console.log(result.groupid);\n // console.log(result.startdate);\n // console.log(result.enddate);\n // console.log(result.totdailyimport);\n // console.log(result.totdailyexport);\n // console.log(result.dailygraph);\n // console.log(result.monthlygraph);\n\n\n // calls the billing report function with the variables\n billingreport(result.accountid,result.groupid,result.startdate,result.enddate,result.totdailyimport,result.totdailyexport,result.dailygraph,result.monthlygraph);\n\n }); // page.evaluate\n\n }, 30000); // set timeout that will allow all of the graphs to load.\n\n }); // page includes\n // page.render('render1.jpeg');\n // console.log('test1');\n \n\n\n }); // page open\n });\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Zero out the top bits in the last 32bit words of the IV
function zeroIVBits(iv) { // "We zero-out the top bit in each of the last two 32-bit words // of the IV before assigning it to Ctr" // — http://web.cs.ucdavis.edu/~rogaway/papers/siv.pdf iv[iv.length - 8] &= 0x7f; iv[iv.length - 4] &= 0x7f; }
[ "function zeroDecipher(key, data) {\n\treturn decompress(sjcl.decrypt(key, data));\n}", "static int256(v) { return n(v, -256); }", "zero () {\n this.#secret.zero()\n }", "static uint192(v) { return n(v, 192); }", "static bytes28(v) { return b(v, 28); }", "static uint248(v) { return n(v, 248); }", "static bytes31(v) { return b(v, 31); }", "static int224(v) { return n(v, -224); }", "static uint208(v) { return n(v, 208); }", "function salsa20_8(B)\n {\n B = B|0;\n var i = 0;\n\n blkcpy8(salsa20_8_x, B, 64);\n for (i = 0; (i|0) < 8; i = i+2|0) {\n /* Operate on columns. */\n xor_rotate(4, 0, 12, 7); xor_rotate(8, 4, 0, 9);\n xor_rotate(12, 8, 4, 13); xor_rotate(0, 12, 8, 18);\n\n xor_rotate(9, 5, 1, 7); xor_rotate(13, 9, 5, 9);\n xor_rotate(1, 13, 9, 13); xor_rotate(5, 1, 13, 18);\n\n xor_rotate(14, 10, 6, 7); xor_rotate(2, 14, 10, 9);\n xor_rotate(6, 2, 14, 13); xor_rotate(10, 6, 2, 18);\n\n xor_rotate(3, 15, 11, 7); xor_rotate(7, 3, 15, 9);\n xor_rotate(11, 7, 3, 13); xor_rotate(15, 11, 7, 18);\n\n /* Operate on rows. */\n xor_rotate(1, 0, 3, 7); xor_rotate(2, 1, 0, 9);\n xor_rotate(3, 2, 1, 13); xor_rotate(0, 3, 2, 18);\n\n xor_rotate(6, 5, 4, 7); xor_rotate(7, 6, 5, 9);\n xor_rotate(4, 7, 6, 13); xor_rotate(5, 4, 7, 18);\n\n xor_rotate(11, 10, 9, 7); xor_rotate(8, 11, 10, 9);\n xor_rotate(9, 8, 11, 13); xor_rotate(10, 9, 8, 18);\n\n xor_rotate(12, 15, 14, 7); xor_rotate(13, 12, 15, 9);\n xor_rotate(14, 13, 12, 13); xor_rotate(15, 14, 13, 18);\n }\n for (i = 0; (i|0) < 16; i=i+1|0)\n set32(B, i, (get32(B, i)|0) + (get32(salsa20_8_x, i)|0) |0);\n }", "static uint256(v) { return n(v, 256); }", "static bytes32(v) { return b(v, 32); }", "static uint112(v) { return n(v, 112); }", "function encrypt_aes_cbc(input, key, iv) {\n var input_u32 = new Uint32Array(input);\n var output_u32 = new Uint32Array(input_u32.length);\n var state_block_u32 = new Uint32Array(AES.block_size_words);\n var prev_cipher_block_u32 = new Uint32Array(AES.block_size_words);\n var w = AES.key_expansion(key);\n\n prev_cipher_block_u32.set(new Uint32Array(iv));\n\n for (var i = 0; i < input_u32.length; i += AES.block_size_words) {\n state_block_u32[0] = input_u32[i+0];\n state_block_u32[1] = input_u32[i+1];\n state_block_u32[2] = input_u32[i+2];\n state_block_u32[3] = input_u32[i+3];\n\n for (var j = 0; j < AES.block_size_words; j++) {\n state_block_u32[j] ^= prev_cipher_block_u32[j];\n }\n\n AES.cipher(state_block_u32, w);\n output_u32.set(state_block_u32, i);\n\n prev_cipher_block_u32.set(state_block_u32);\n }\n\n return output_u32.buffer;\n }", "function ARC4init(key) {\n var i, j, t;\n for (i = 0; i < 256; ++i)\n this.S[i] = i;\n j = 0;\n for (i = 0; i < 256; ++i) {\n j = (j + this.S[i] + key[i % key.length]) & 255;\n t = this.S[i];\n this.S[i] = this.S[j];\n this.S[j] = t;\n }\n this.i = 0;\n this.j = 0;\n }", "static uint240(v) { return n(v, 240); }", "static int128(v) { return n(v, -128); }", "function des (key, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];\n var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];\n var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];\n var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];\n var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];\n var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];\n var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];\n var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];\n\n //create the 16 or 48 subkeys we will need\n var keys = des_createKeys (key);\n var m=0, i, j, temp/*, temp2*/, right1, right2, left, right, looping;\n var cbcleft, cbcleft2, cbcright, cbcright2;\n var endloop, loopinc;\n var len = message.length;\n var chunk = 0;\n //set up the loops for single and triple des\n var iterations = keys.length == 32 ? 3 : 9; //single or triple des\n if (iterations == 3) {looping = encrypt ? [0, 32, 2] : [30, -2, -2];}\n else {looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];}\n\n //pad the message depending on the padding parameter\n if (padding == 2) message += \" \"; //pad the message with spaces\n else if (padding == 1) {temp = 8-(len%8); message += String.fromCharCode (temp,temp,temp,temp,temp,temp,temp,temp); if (temp==8) len+=8;} //PKCS7 padding\n else if (!padding) message += \"\\0\\0\\0\\0\\0\\0\\0\\0\"; //pad the message out with null bytes\n\n //store the result here\n var result = \"\";\n var tempresult = \"\";\n\n if (mode == 1) { //CBC mode\n cbcleft = (iv.charCodeAt(m++) << 24) | (iv.charCodeAt(m++) << 16) | (iv.charCodeAt(m++) << 8) | iv.charCodeAt(m++);\n cbcright = (iv.charCodeAt(m++) << 24) | (iv.charCodeAt(m++) << 16) | (iv.charCodeAt(m++) << 8) | iv.charCodeAt(m+1);\n m=0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message.charCodeAt(m++) << 24) | (message.charCodeAt(m++) << 16) | (message.charCodeAt(m++) << 8) | message.charCodeAt(m++);\n right = (message.charCodeAt(m++) << 24) | (message.charCodeAt(m++) << 16) | (message.charCodeAt(m++) << 8) | message.charCodeAt(m++);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode == 1) {if (encrypt) {left ^= cbcleft; right ^= cbcright;} else {cbcleft2 = cbcleft; cbcright2 = cbcright; cbcleft = left; cbcright = right;}}\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= temp; left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333; left ^= temp; right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j=0; j<iterations; j+=3) {\n endloop = looping[j+1];\n loopinc = looping[j+2];\n //now go through and perform the encryption or decryption\n for (i=looping[j]; i!=endloop; i+=loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i+1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f]\n | spfunction6[(right1 >>> 8) & 0x3f] | spfunction8[right1 & 0x3f]\n | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & 0x3f]\n | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left; left = right; right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333; left ^= temp; right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= temp; left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode == 1) {if (encrypt) {cbcleft = left; cbcright = right;} else {left ^= cbcleft2; right ^= cbcright2;}}\n tempresult += String.fromCharCode ((left>>>24), ((left>>>16) & 0xff), ((left>>>8) & 0xff), (left & 0xff), (right>>>24), ((right>>>16) & 0xff), ((right>>>8) & 0xff), (right & 0xff));\n\n chunk += 8;\n if (chunk == 512) {result += tempresult; tempresult = \"\"; chunk = 0;}\n } //for every 8 characters, or 64 bits in the message\n\n //return the result as an array\n return result + tempresult;\n } //end of des", "static uint32(v) { return n(v, 32); }", "function pkcs_unpad(buffer) {\n var unpadded_length = buffer.byteLength - pkcs_pad_byte_count(buffer);\n\n // HACK: slice missing in older versions of nodejs\n if (!buffer.slice) {\n var padded_bytes = new Uint8Array(buffer);\n var unpadded = new Uint8Array(unpadded_length);\n unpadded.set(padded_bytes.subarray(0, unpadded_length));\n return unpadded.buffer;\n }\n\n return buffer.slice(0, unpadded_length);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper to ensure path1 and path2 are roughly equal
function approximatelyEqual(path1, path2) { // convert to numbers and letters const path1Items = pathToItems(path1); const path2Items = pathToItems(path2); const epsilon = 0.001; if (path1Items.length !== path2Items.length) { return false; } for (let i = 0; i< path1Items.length; i++) { if (typeof path1Items[i] === 'string' && path1Items[i] !== path2Items[i]) { return false; } // otherwise it's a number, check if approximately equal if (Math.abs(path1Items[i] - path2Items[i]) > epsilon) { return false; } } return true; }
[ "equals(path, another) {\n return path.length === another.length && path.every((n, i) => n === another[i]);\n }", "compare(path, another) {\n var min = Math.min(path.length, another.length);\n\n for (var i = 0; i < min; i++) {\n if (path[i] < another[i]) return -1;\n if (path[i] > another[i]) return 1;\n }\n\n return 0;\n }", "function moduleDistance(a, b) {\n\tconsole.assert(a, 'missing first path');\n\tconsole.assert(b, 'missing second path');\n\n\tvar folderA = path.dirname(a);\n\tvar folderB = path.dirname(b);\n\tconsole.assert(folderA, 'could not get dirname from', a);\n\tconsole.assert(folderB, 'could not get dirname from', b);\n\n\tvar relative = path.relative(folderA, b);\n\tif (!relative) {\n\t\treturn 1;\n\t}\n\tvar folders = relative.split('\\\\');\n\tvar distance = folders.length;\n\t// console.log('from', a, 'to', b, 'relative', folders, distance);\n\treturn distance;\n}", "isAfter(path, another) {\n return Path.compare(path, another) === 1;\n }", "endsBefore(path, another) {\n var i = path.length - 1;\n var as = path.slice(0, i);\n var bs = another.slice(0, i);\n var av = path[i];\n var bv = another[i];\n return Path.equals(as, bs) && av < bv;\n }", "endsAt(path, another) {\n var i = path.length;\n var as = path.slice(0, i);\n var bs = another.slice(0, i);\n return Path.equals(as, bs);\n }", "isDescendant(path, another) {\n return path.length > another.length && Path.compare(path, another) === 0;\n }", "endsAfter(path, another) {\n var i = path.length - 1;\n var as = path.slice(0, i);\n var bs = another.slice(0, i);\n var av = path[i];\n var bv = another[i];\n return Path.equals(as, bs) && av > bv;\n }", "function concatPath(a, b) {\n if (NodePath.sep === \"\\\\\") {\n return NodePath.normalize(a + \"/\" + b).replace(/\\\\/g, \"/\");\n }\n else {\n return NodePath.normalize(a + \"/\" + b);\n }\n}", "isParent(path, another) {\n return path.length + 1 === another.length && Path.compare(path, another) === 0;\n }", "function isSamePage(href1, href2) {\n var page1 = href1.substring(href1.lastIndexOf('/')+1,href1.lastIndexOf('.html'));\n var page2 = href2.substring(href2.lastIndexOf('/')+1,href2.lastIndexOf('.html'));\n return (page1 == page2);\n}", "function joinPath(portion1, portion2) {\n\tlet a = [...portion1].filter(x => x.match(/[a-z0-9]/gi));\n\tlet b = [...portion2].filter(x => x.match(/[a-z0-9]/gi));\n\n\ta.push(\"/\");\n\t\n\treturn [...a, ...b].join(\"\");\n}", "function pathsMatch(restrictedPath, path) {\n if (restrictedPath.length !== path.length) {\n return false;\n }\n for(var i = 0; i < restrictedPath.length; i++) {\n if (restrictedPath[i] !== path[i] && restrictedPath[i] !== '*') {\n return false;\n }\n }\n return true;\n }", "isBefore(path, another) {\n return Path.compare(path, another) === -1;\n }", "function isEqualPass(obj1,obj2){\r\n\t var pw1 = obj1.value;\r\n\t var pw2 = obj2.value;\r\n\t \r\n\t if(pw1.length ==0 || pw2.length ==0){\r\n\t\t return true;\r\n\t }\r\n\t if(pw1 == pw2){\r\n\t\t return false;\r\n\t }\r\n\t \r\n\t return true;\r\n }", "isAncestor(path, another) {\n return path.length < another.length && Path.compare(path, another) === 0;\n }", "equalCommands (pathArray) {\r\n var i, il, equalCommands;\r\n\r\n pathArray = new PathArray(pathArray);\r\n\r\n equalCommands = this.length === pathArray.length;\r\n for (i = 0, il = this.length; equalCommands && i < il; i++) {\r\n equalCommands = this[i][0] === pathArray[i][0];\r\n }\r\n\r\n return equalCommands\r\n }", "function checkRelation(node1, node2) {\n if (node1 === node2) return true;\n\n while (node1) {\n if (node1 === node2) return true;\n\n node1 = node1.parentNode;\n }\n\n return false;\n}", "function equivalent(x,y){\n\tif(JSON.stringify(clone(x)) == JSON.stringify(clone(y))){\n\t\treturn true;\n\t}\n\telse{\n\t\treturn false;\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a path DOM element, return a list of path segments
function convert(element) { let segments = [], pathSegList = element.pathSegList let prev = pathSegList[0] for (let i = 1; i < pathSegList.length; i++) { let cur = pathSegList[i] segments.push(converters[cur.pathSegType](prev, cur)) prev = cur } return segments }
[ "pathList(){\n let pathList = []\n let current = this\n while(current){\n if(current.pathId()) pathList.unshift(current.pathId())\n current = current.parent\n }\n return pathList\n }", "function findSubPath (path) {\n var path_length = path.length;\n var subPathList = [];\n var i = 0;\n while (i < path.length - 2) {\n subPathList.push(path.slice(i, i + 3));\n i = i + 2;\n };\n return subPathList;\n}", "function getResourcePathSplits(path) {\n\t\tvar\n\t\t\tparts = path.split('/'),\n\t\t\ti = parts.length,\n\t\t\tsplits = [[path, '']]\n\t\t;\n\t\twhile (--i >= 0) {\n\t\t\tsplits.push([\n\t\t\t\tparts.slice(0, i).join('/'),\n\t\t\t\tparts.slice(i).join('/')\n\t\t\t]);\n\t\t}\n\t\treturn splits;\n\t}", "function getPaths() {\n for (var i = 0; i < sel.length; i++) {\n if (sel[i].typename == \"GroupItem\") {\n getPaths(sel[i].pageItems);\n } else if (sel[i].typename == \"CompoundPathItem\") {\n getPaths(sel[i].pathItems);\n } else if (sel[i].typename == \"PathItem\") {\n paths.push(sel[i]);\n }\n }\n}", "function dividePath(path) {\n var subPaths = null;\n for (var i=0, n=path.length; i < n - 1; i++) { // don't need to check last arc\n subPaths = dividePathAtNode(path, path[i]);\n if (subPaths !== null) {\n return subPaths;\n }\n }\n // indivisible path -- clean it by removing any spikes\n removeSpikesInPath(path);\n return path.length > 0 ? [path] : [];\n }", "function computePath( startingNode, endingNode ) {\n // First edge case: start is the end:\n if (startingNode.id === endingNode.id) {\n return [startingNode];\n }\n\n // Second edge case: two connected nodes\n if ( endingNode.id in startingNode.next ) {\n return [startingNode, endingNode];\n }\n\t\n var path = [];\n var n = endingNode;\n while ( n && n.id !== startingNode.id ) {\n // insert at the beggining\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift\n if ( n.id !== endingNode.id ) {\n path.unshift( n );\n }\n n = n.prev;\n }\n\n if ( path.length ) {\n path.unshift( startingNode );\n path.push( endingNode );\n }\n\n return path;\n}", "function extractPaths(s, pp_length_limit, paths){\n for(var i = 0; i < s.length; i++){\n if(s[i].locked || s[i].hidden){\n continue;\n } else if(s[i].typename == \"PathItem\"){\n if(pp_length_limit\n && s[i].pathPoints.length <= pp_length_limit){\n continue;\n }\n paths.push(s[i]);\n \n } else if(s[i].typename == \"GroupItem\"){\n // search for PathItems in GroupItem, recursively\n extractPaths(s[i].pageItems, pp_length_limit, paths);\n \n } else if(s[i].typename == \"CompoundPathItem\"){\n // searches for pathitems in CompoundPathItem, recursively\n // ( ### Grouped PathItems in CompoundPathItem are ignored ### )\n extractPaths(s[i].pathItems, pp_length_limit , paths);\n }\n }\n}", "function anno_getXpathTo(element) {\n if (element.id !== '') {\n return \"//*[@id='\" + element.id + \"']\";\n }\n if (element === document.body) {\n return \"html/\" + element.tagName.toLowerCase();\n } //added 'html/' to generate a valid Xpath even if parent has no ID.\n var ix = 0;\n var siblings = element.parentNode.childNodes;\n for (var i = 0; i < siblings.length; i++) {\n var sibling = siblings[i];\n if (sibling === element) {\n return anno_getXpathTo(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';\n }\n if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {\n ix++;\n }\n }\n}", "* __pathsGenerator(path, node) {\n const endingSlash =\n (node.children.length > 0 || node.endsWithSlash) ? '/' : '';\n const currentPath = path + node.name + endingSlash;\n if (!node.visited) {\n yield currentPath;\n node.visited = true;\n }\n for (const child of node.children) {\n yield * this.__pathsGenerator(currentPath, child);\n }\n }", "function serializePaths(){\r\n var paths = extractSelectedPaths();\r\n var data = [];\r\n\r\n var MARGIN_TOP = 50;\r\n var MARGIN_LEFT = 25;\r\n \r\n var top_left = getTopLeftOfPaths(paths);\r\n var top = top_left[0] + MARGIN_TOP;\r\n var left = top_left[1] - MARGIN_LEFT;\r\n \r\n for(var i = paths.length - 1; i >= 0; i--){\r\n var r = [\"@\"]; // \"@\" is a mark that means the beginning of a path\r\n var p = paths[i];\r\n \r\n r.push(p.closed ? \"1\" : \"0\");\r\n\r\n r.push([p.filled ? \"1\" : \"0\",\r\n serializeColor(p.fillColor)]);\r\n \r\n r.push([p.stroked && p.strokeColor.typename != \"NoColor\" ? \"1\" : \"0\",\r\n _f2s(p.strokeWidth),\r\n serializeColor(p.strokeColor)]);\r\n\r\n for(var j = 0, jEnd = p.pathPoints.length; j < jEnd; j++){\r\n var ppt = p.pathPoints[j];\r\n var anc = ppt.anchor;\r\n r.push([_f2s(anc[0] - left), _f2s(anc[1] - top),\r\n _f2s(ppt.rightDirection[0] - anc[0]),\r\n _f2s(ppt.rightDirection[1] - anc[1]),\r\n _f2s(ppt.leftDirection[0] - anc[0]),\r\n _f2s(ppt.leftDirection[1] - anc[1])]);\r\n // ignore pointType becauses paper js doesn't have this property\r\n }\r\n \r\n data[data.length] = r;\r\n }\r\n \r\n // \"data\" is passed to callback function as a comma separated string\r\n return data;\r\n}", "GenerateSegments(argument) {\n var result = argument.split(\"/\");\n if (result.length > 0) {\n if (result[0] == \"\") {\n result.shift();\n }\n }\n if (result.length > 0) {\n if (result[result.length - 1] == \"\") {\n result.pop();\n }\n }\n return result;\n }", "function findElementByPath (path, source) {\n let selectedElement = source;\n for (let index of path.split('.')) {\n selectedElement = selectedElement.children[index];\n }\n return {...selectedElement};\n}", "findPaths(fromNavNode, toNavNode) {\r\n\t\tlet walkingPaths = [[fromNavNode]];\r\n\t\tlet rtn = [];\r\n\r\n\t\twhile( walkingPaths.length > 0 ) {\r\n\t\t\tlet curPath = walkingPaths.pop();\r\n\t\t\tlet curNode = curPath[curPath.length-1].node;\r\n\t\t\tlet noRoute = false;\r\n\t\t\twhile( !noRoute && curNode != toNavNode ) {\r\n\t\t\t\tlet connections = curNode.connections.filter( connection => !curPath.includes(connection) );\r\n\t\t\t\tif ( connections.length > 0 ) {\r\n\t\t\t\t\tfor( let i = 1; i < connections.length; i++ ) {\r\n\t\t\t\t\t\tlet newPath = curPath.slice();\r\n\t\t\t\t\t\tnewPath.push(connections[i]);\r\n\t\t\t\t\t\twalkingPaths.push(newPath);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcurPath.push(connections[0]);\r\n\t\t\t\t\tcurNode = connections[0].node;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tnoRoute = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif ( !noRoute ) {\r\n\t\t\t\trtn.push(curPath);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn rtn;\r\n\t}", "first(root, path) {\n var p = path.slice();\n var n = Node$1.get(root, p);\n\n while (n) {\n if (Text.isText(n) || n.children.length === 0) {\n break;\n } else {\n n = n.children[0];\n p.push(0);\n }\n }\n\n return [n, p];\n }", "function convertPath(start, end) {\n var arcIds = [],\n firstNodeId = -1,\n arcStartId;\n\n // Visit each point in the path, up to but not including the last point\n for (var i = start; i < end; i++) {\n if (pointIsArcEndpoint(i)) {\n if (firstNodeId > -1) {\n arcIds.push(addEdge(arcStartId, i));\n } else {\n firstNodeId = i;\n }\n arcStartId = i;\n }\n }\n\n // Identify the final arc in the path\n if (firstNodeId == -1) {\n // Not in an arc, i.e. no nodes have been found...\n // Assuming that path is either an island or is congruent with one or more rings\n arcIds.push(addRing(start, end));\n }\n else if (firstNodeId == start) {\n // path endpoint is a node;\n if (!pointIsArcEndpoint(end)) {\n error(\"Topology error\"); // TODO: better error handling\n }\n arcIds.push(addEdge(arcStartId, i));\n } else {\n // final arc wraps around\n arcIds.push(addSplitEdge(arcStartId, end, start + 1, firstNodeId));\n }\n return arcIds;\n }", "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 }", "ancestors(path) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n reverse = false\n } = options;\n var paths = Path.levels(path, options);\n\n if (reverse) {\n paths = paths.slice(1);\n } else {\n paths = paths.slice(0, -1);\n }\n\n return paths;\n }", "function extractPaths(items, pp_length_limit, paths){ \n for( var i = 0; i < items.length; i++ ){\n if( items[i].locked || items[i].hidden ){\n continue;\n } else if( items[i].typename == \"PathItem\"){\n // ignore guides and clipping paths\n if ((pp_length_limit && items[i].pathPoints.length <= pp_length_limit)\n || items[i].guides || items[i].clipping ){\n continue;\n }\n paths.push( items[i] );\n \n } else if( items[i].typename == \"GroupItem\" ){\n // search PathItems in the GroupItem, recursively\n extractPaths( items[i].pageItems, pp_length_limit, paths );\n \n } else if( items[i].typename == \"CompoundPathItem\" ){\n // search Pathitems in the CompoundPathItem, recursively\n // ( ### Grouped PathItems in CompoundPathItem are ignored ### )\n extractPaths( items[i].pathItems, pp_length_limit , paths );\n }\n }\n }", "function displayPath(){\n var currentCell = endCell;\n while(currentCell != startCell){\n changeClass(currentCell, \"path\");\n currentCell = currentCell.parent;\n }\n changeClass(startCell, \"start\");\n changeClass(endCell, \"end\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
build the quiz by loopng through xml data
function generateQuiz() { quizAnswers = []; quizContent = "<div class=\"main2-banner-title\">Quiz " + currentQuiz + "</div>"; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { myFunction(this); } else { } }; xhttp.open("GET", "data.xml", true); xhttp.send(); function myFunction(xml) { var xmlDoc = xml.responseXML; document.getElementById("Main2-container").innerHTML = ""; //gets the collection of the unit, gets the html element at entry 0 (units are all unique), then gets //collection with all elements in unit with the entry name MultipleChoice //var quizData = xmlDoc.getElementsByTagName("Unit")[currentQuiz-1].getElementsByTagName("MultipleChoice"); //quizData is a html collection var quizData = xmlDoc.getElementsByTagName("Quiz")[0].getElementsByTagName("Unit")[currentQuiz-1].getElementsByTagName("MultipleChoice"); //id will take the from: q0A q0B, etc... //name will take the form: q0 q1 q2...... for (let i = 0; i < quizData.length; i++) { quizContent = quizContent + "<div><p>" + (i + 1) + ". " + quizData[i].getElementsByTagName("Question")[0].childNodes[0].nodeValue + "</p><ul><li>" + "A) <input type=\"radio\" name=\"q" + i + "\" id=\"q" + i + "A\">" + quizData[i].getElementsByTagName("A")[0].childNodes[0].nodeValue + "</li><li>" + "B) <input type=\"radio\" name=\"q" + i + "\" id=\"q" + i + "B\">" + quizData[i].getElementsByTagName("B")[0].childNodes[0].nodeValue + "</li><li>" + "C) <input type=\"radio\" name=\"q" + i + "\" id=\"q" + i + "C\">" + quizData[i].getElementsByTagName("C")[0].childNodes[0].nodeValue + "</li><li>" + "D) <input type=\"radio\" name=\"q" + i + "\" id=\"q" + i + "D\">" + quizData[i].getElementsByTagName("D")[0].childNodes[0].nodeValue + "</li></ul></div>"; quizAnswers[i] = quizData[i].getElementsByTagName("Answer")[0].childNodes[0].nodeValue; } document.getElementById("Main2-container").innerHTML = quizContent; //xmlDoc.getElementsByTagName("bodyParagraph")[1].childNodes[0].nodeValue; //get data of second body paragraph } }
[ "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 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}", "function populatePretestPage(qn) {\r\n\r\n var question = pretestData.questions[qn].question;\r\n var id = pretestData.questions[qn].id;\r\n var optionsStr = '';\r\n var options = pretestData.questions[qn].choices;\r\n var choiceLen = pretestData.questions[qn].correct.length;\r\n $.each(options, function(key, value) {\r\n if(pretestData.questions[qn].multi) {\r\n optionsStr += '<label class=\"radio\"><input value=\"' + key + '\" type=\"checkbox\" name=\"' + id + '\">' + value + '</label>';\r\n } else {\r\n optionsStr += '<label class=\"radio\"><input value=\"' + key + '\" type=\"radio\" name=\"' + id + '\">' + value + '</label>';\r\n }\r\n });\r\n\r\n var qnStr = '<label class=\"control-label\">' + question + '</label>';\r\n $('.pre-test').find('.qn-block').html(qnStr + optionsStr);\r\n $('.pre-test').find('.qn-block').attr('data-id', qn)\r\n $('.pre-test').find('.qn-block').attr('data-multi', pretestData.questions[qn].multi)\r\n\r\n if(pretestData.questions[qn].multi) {\r\n $('.pre-test').find('.qn-block').append('<span><strong>Note:</strong> Select atleast '+choiceLen+' choices</span>')\r\n }\r\n\r\n //Display question number against total questions in the bottom \r\n $(\".postTestNav\").css({ \"display\": \"block\" });\r\n $(\".postTestNav\").text(qn + 1 + \" of \" + pretestData.questions.length);\r\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 setUpHTML() {\n $(\"#question\").empty();\n questionDiv = $(\"<div>\");\n questionDiv.attr(\"id\", \"questionText\");\n $(\"#question\").prepend(questionDiv);\n answersDiv = $(\"<div>\");\n answersDiv.attr(\"id\", \"answers\");\n $(\"#question\").append(answersDiv);\n for (var i = 1; i < 5; i++) {\n var answerButton = $(\"<button>\");\n answerButton\n .attr(\"id\", \"answer\"+i)\n .attr(\"class\", \"answer\")\n .appendTo($(\"#answers\"));\n }\n}", "function generateQuestionElement(currentQuestion) {\n let tempQuestion = STORE.questions[currentQuestion];\n let tempPageNum = STORE.questionNumber + 1;\n return `<section id=\"question set\">\n <div class=\"page\">\n <form id=\"js-form\" name=\"form\">\n <h2>${tempQuestion.question}</h2>\n <input id = 'a' name=\"answer\" type=\"radio\" onclick=\"handleRadioClicked()\" value=\"${tempQuestion.answers[0]}\" required>\n <label for=\"${tempQuestion.answers[0]}\">${tempQuestion.answers[0]}</label><br>\n <input id = 'b' name=\"answer\" type=\"radio\" onclick=\"handleRadioClicked()\" value=\"${tempQuestion.answers[1]}\" >\n <label for=\"${tempQuestion.answers[1]}\">${tempQuestion.answers[1]}</label><br>\n <input id = 'c' name=\"answer\" type=\"radio\" onclick=\"handleRadioClicked()\" value=\"${tempQuestion.answers[2]}\" >\n <label for=\"${tempQuestion.answers[2]}\">${tempQuestion.answers[2]}</label><br>\n <input id = 'd' name=\"answer\" type=\"radio\" onclick=\"handleRadioClicked()\" value=\"${tempQuestion.answers[3]}\" >\n <label for=\"${tempQuestion.answers[3]}\">${tempQuestion.answers[3]}</label><br>\n <button type=\"submit\" id=\"js-submit\" hide>Submit</button>\n </form>\n <h3></h3>\n <p>Question ${tempPageNum} of 5 <br>\n Score: ${STORE.score}</p>\n </div>\n </section>`;\n}", "function createQuestionsPages(questionsData) {//questionsData = {data: [array of 10 question objects at most]}\n const container = document.createElement('container');\n for (let i = 0; i < questionsData.data.length; i++) {\n\n const h3 = document.createElement('h3');\n h3.innerText = questionsData.data[i].question;\n container.appendChild(h3);\n\n if (questionsData.data[i].answer) {//answer is not empty(there is answer)\n const p = document.createElement('p');\n p.innerText = questionsData.data[i].answer;\n container.appendChild(p);\n } else {\n const input = document.createElement('input');\n const br = document.createElement('br');\n input.type = 'text';\n input.classList.add('answer-box');\n input.placeholder = 'Answer here';\n input.id = questionsData.data[i].id;\n container.appendChild(input);\n container.appendChild(br);\n }\n if (i != questionsData.data.length - 1) {\n const hr = document.createElement('hr');\n container.appendChild(hr);\n }\n }\n return container;\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 buildTestAnswers(questionid) {\n\tvar answer1 = new newAnswer(\"other\", \"Yes it does.\");\n\tvar answer2 = new newAnswer(\"other\", \"No it doesn't.\");\n\tallPosts[questionid].answers.push(answer1);\n\tallPosts[questionid].answers.push(answer2);\n}", "function BuildQuiz() {\n // Initialize the variables and setup the elements\n var quizContainerElement = document.getElementById('quizContainer');\n var quizContainerHTML = \"\";\n var translationsContainer = document.getElementById('translationsContainer');\n var questions = [];\n var successfulBuild = \"\";\n var previousBtnVisibility = \"visible\";\n var nextBtnVisibility = \"visible\";\n var gradeQuizBtnDisplay = \"none\";\n\n // Call the function to get the Quiz Questions (translations)\n questions = PopulateQuestionArray();\n\n // Call the functions to hide the translations table and show the quizes container\n ToggleContainerDisplay(\"translationsContainer\", \"hide\", \"display\");\n ToggleContainerDisplay(\"quizContainer\", \"show\", \"display\");\n\n // Verify that the previous step has been completed, upon successful completion, this will help provide success or failure messages of the build\n if(translationsContainer.style.display === \"none\" && quizContainerElement.style.display === \"block\") { \n\n // For loop that builds the <section> tags and HTML within the questionContainer, populates the questions within the fields, and displays the appropriate navigation buttons.\n for (var questionCounter = 1; questionCounter <= questions.length; questionCounter++) {\n quizContainerHTML += \" <section id=\\\"question\" + questionCounter + \"\\\" class=\\\"questionContainer\\\">\\n <p class=\\\"questionContainerNumber\\\">Question \" + (questionCounter) + \"</p>\\n <p id=\\\"translationQuestion\\\" class=\\\"translationQuestion\\\">\" + questions[questionCounter-1] + \"</p>\\n\";\n \n // Determine if the previous button should be displayed or not\n previousBtnVisibility = (questionCounter > 1) ? \"visible\" : \"hidden\";\n // Previous Button\n quizContainerHTML += \" <button id=\\\"previousBtn\\\" name=\\\"previousBtn\\\" onclick=\\\"ToggleContainerDisplay(\\'question\" + (questionCounter - 1) + \"\\',\\'show\\',\\'display\\'); ToggleContainerDisplay(\\'question\" + questionCounter + \"\\',\\'hide\\',\\'display\\'); SetFocus(\\'userAnswer\" + (questionCounter - 1) + \"\\'); SetDotStyle(\" + questionCounter + \"); SetSelectedDot(\" + (questionCounter - 1) + \",\" + questions.length + \");\\\" style=\\\"visibility: \" + previousBtnVisibility + \";\\\">Previous</button>\";\n\n quizContainerHTML += \" <input type=\\\"text\\\" id=\\\"userAnswer\" + questionCounter + \"\\\" placeholder=\\\"Enter your answer here\\\" autocomplete=\\\"off\\\">\";\n\n // Determine if the next button should be displayed or not\n nextBtnVisibility = (questionCounter < questions.length) ? \"visible\" : \"hidden\";\n\n // Set the 2nd from last question's NEXT button to also show the Quiz button for the last question.\n gradeQuizBtnDisplay = (questionCounter === questions.length-1) ? \" ToggleContainerDisplay(\\'gradeQuizBtn\\',\\'show\\',\\'display\\');\" : \"\";\n \n // Next Button\n quizContainerHTML += \" <button id=\\\"nextBtn\\\" name=\\\"nextBtn\\\" onclick=\\\"ToggleContainerDisplay(\\'question\" + (questionCounter + 1) + \"\\',\\'show\\',\\'display\\'); ToggleContainerDisplay(\\'question\" + questionCounter + \"\\',\\'hide\\',\\'display\\'); SetFocus(\\'userAnswer\" + (questionCounter + 1) + \"\\'); SetDotStyle(\" + questionCounter + \"); SetSelectedDot(\" + (questionCounter + 1) + \",\" + questions.length + \");\" + gradeQuizBtnDisplay + \"\\\" style=\\\"visibility: \" + nextBtnVisibility + \";\\\">Next</button>\";\n\n quizContainerHTML += \" </section>\";\n }\n\n // Create question dot placement for each question displaying 1 to 10, but adjusted to show the appropriate array item\n for (var i = 1; i <= questions.length; i++){\n quizContainerHTML += \"<span id=\\\"dot\" + i + \"\\\" class=\\\"emptyDot\\\" style=\\\"display: inline-block;\\\">\" + i + \"</span>\"; \n } \n\n // Display Dot Legend\n quizContainerHTML += \"<span class=\\\"legendBox\\\"><span class=\\\"emptyDot\\\" style=\\\"display: inline-block; border: 1px solid #FF0000;\\\"></span> = Nothing Entered <span class=\\\"emptyDot filledDot\\\" style=\\\"display: inline-block; margin-left: 20px;\\\"></span> = Has Entry <span class=\\\"emptyDot selectedDot\\\" style=\\\"display: inline-block; margin-left: 20px;\\\"></span> = Selected Question</span>\";\n\n // Create the submit quiz button to display the results\n quizContainerHTML += \" <button id=\\\"gradeQuizBtn\\\" name=\\\"submitBtn\\\" onclick=\\\"GradeQuiz();\\\" style=\\\"display: none;\\\">Grade Quiz</button>\";\n\n // Takes the above HTML string and inserts it after the current quizContainer element.\n quizContainerElement.innerHTML += quizContainerHTML;\n successfulBuild = \"Yes\";\n } else {\n successfulBuild = \"No\";\n }\n\n\n // Display the appropriate response if the quiz build was successful or not.\n if (successfulBuild === \"Yes\") {\n ToggleContainerDisplay(\"question1\",\"show\",\"display\");\n SetFocus(\"userAnswer1\");\n SetSelectedDot(1,questions.length);\n //document.getElementById(\"dot1\").style.border = \"15px solid black\";\n } else if (successfulBuild === \"No\") {\n alert(\"We're sorry, the correct sections have not been displayed properly. Please try again later.\");\n } else {\n alert(\"We're sorry, there was an error building your quiz at this time. Please try again later.\");\n }\n\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 createQArray(givenQTable)\n{\n //given Q table is either root Q or sub Q, but doesn't matter.\n //since I#ve assigned 'data-x' and 'data-y' properties to each table.\n //just simply need to access them\n var qArray = [];\n\n\n\n //locate the text, and push the text\n qArray.push(givenQTable.rows[1].cells[1].childNodes[0].value);\n\n //now find the x coordinate and y coordinate, push them\n qArray.push(givenQTable.getAttribute('data-x'));\n qArray.push(givenQTable.getAttribute('data-y'));\n\n //now store the timelimit\n qArray.push(givenQTable.rows[1].cells[2].childNodes[0].value);\n\n\n var answersTable = document.getElementById('ansTable' + givenQTable.getAttribute('data-x')\n + givenQTable.getAttribute('data-y'));\n\n //locate the feedback field, and push the value to the array\n qArray.push(answersTable.rows[0].cells[3].childNodes[0].value);\n\n // return the array\n return qArray;\n\n} // function createQDiv", "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}", "populateExerciseList()\n {\n this.clearExercisesFromDom();\n var exercises = Exercise.get();\n for(let exercise of exercises) {\n this.addExerciseToDom(exercise);\n }\n }", "function setUpTests()\n {\n// var fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n var fullInteractionData;\n if(app.scorm.scormProcessGetValue('cmi.suspend_data') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.suspend_data'));\n }\n else if(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n }\n else{\n console.log('There is a problem with test submission.');\n }\n \n // Inject the CMI DB data into the questionBank on first load\n if (fullInteractionData) {\n $.each(fullInteractionData, function (index, value)\n {\n if (!app.questionBank[index]) {\n app.questionBank[index] = value;\n }\n }); \n }\n \n // Setup the current test's question bank\n if (!app.questionBank[testID]) {\n app.questionBank[testID] = [];\n }\n \n return fullInteractionData;\n }", "function selectAnswer() {\n var choices = undefined;\n //role of forEach is take the father who contain all eelnt who have the same class=answer mean all chooses in the list and loop on the all element by first choice then second then third ---etc SYNTAX = (fathe.forEach((the son)))\n // and we use with forEach arrow function as aconstant syntax ( aparthees for each (for function )) => {}\n answerAll.forEach((answerElement) => {\n if (answerElement.checked) { // if you choose any choice so,, answer=what you choose &&& checked is ready in language\n choices = answerElement.id; // it is reday in language to know id for label &&& any choice=id\n console.log(choices) // you will have not thing bcz you don't write the code of submit at the end when you write code of submit the answer will run in console\n }\n\n })\n\n return choices;\n //if you are not choose any answer the browser will choose anser=undefined so you will not coul go to next slide bcz undefind\n\n\n\n}", "function transformXMLToForm(xmlData) {\r\n\tvar jsObj = parser.parse(xmlData, parserOptions)\r\n\tvar form = new SDCForm()\r\n\r\n\tvar traversalStack = []\r\n\tvar getSection = () => {\r\n\t\tvar section = traversalStack.indexOf(\"Section\")\r\n\t\tif(section == -1)\r\n\t\t\treturn -1\r\n\r\n\t\tif(section < traversalStack.length-1)\r\n\t\t\treturn traversalStack[section+1]\r\n\t\telse\r\n\t\t\treturn -1\r\n\t}\r\n\r\n\t// Top level traversal to cut through to questions\r\n\tvar currentQuestion = -1\r\n\tvar traverse = (name, obj) => {\r\n\t\tif(obj == null) {\r\n\t\t\tconsole.log(name + \" is null\")\r\n\t\t\treturn\r\n\t\t}\r\n\r\n\t\t// Check for new section, do this one level deeper \r\n\t\tif(name == \"Section\") {\r\n\t\t\t// TODO: possible to have only one section? (in which case it may not be array)\r\n\t\t\tfor(let i = 0; i < obj.length; i++) {\r\n\t\t\t\tvar title = \"\"\r\n\t\t\t\tif(hasKeys(obj[i], [\"attr\", \"title\"]))\r\n\t\t\t\t\ttitle = obj[i][\"attr\"][\"title\"]\r\n\t\t\t\tform.sections.push(title)\r\n\t\t\t}\r\n\t\t}\r\n\t\t/*if(traversalStack.length > 0 && traversalStack[traversalStack.length-1] == \"Section\") {\r\n\t\t\tvar title = \"\"\r\n\t\t\tif(hasKeys(obj, [\"attr\", \"title\"]))\r\n\t\t\t\ttitle = obj[\"attr\"][\"title\"]\r\n\t\t\tform.sections.push(title)\r\n\t\t}*/\r\n\t\t// Add a question\r\n\t\telse if(name == \"Question\") {\r\n\t\t\tif(Array.isArray(obj)) {\r\n\t\t\t\tfor(var i = 0; i < obj.length; i++) {\r\n\t\t\t\t\taddQuestion(form, obj[i], getSection())\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\taddQuestion(form, obj, getSection())\r\n\t\t\t}\r\n\t\t\treturn\r\n\t\t} \r\n\t\t// Get form details\r\n\t\telse if(name == \"FormDesign\") {\r\n\t\t\tform.title = obj[\"attr\"][\"formTitle\"]\r\n\t\t}\r\n\r\n\r\n\t\t// Dive deeper\r\n\t\ttraversalStack.push(name)\r\n\t\tif(typeof obj === 'object' && obj != null) {\r\n\t\t\tfor(var key in obj) {\r\n\t\t\t\ttraverse(key, obj[key])\r\n\t\t\t}\r\n\t\t}\r\n\t\ttraversalStack.pop(name)\r\n\t}\r\n\ttraverse(\"root\", jsObj)\r\n\r\n\treturn {json:jsObj, form:form, xml:xmlData}\r\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 createQuestionLayout() {\n var mainDiv = document.getElementsByClassName('display_question');\n var wrapperDiv = document.createElement('div');\n wrapperDiv.className = \"wrapper\";\n mainDiv.appendChild(wrapperDiv);\n for (var j = 0 ; j < 2; j++) {\n var span = document.createElement('span');\n wrapperDiv.appendChild(span);\n }\n span.innerHTML = \"/ \"+quizQuestions.length;\n var ulDdown = document.createElement('ul');\n ulDdown.className = \"dropdown\";\n mainDiv.appendChild(ulDdown);\n var pTag = document.createElement('p');\n pTag.className = \"question\";\n var ulTag = document.createElement('ul');\n mainDiv.appendChild(pTag);\n mainDiv.appendChild(ulTag);\n for (var i = 0 ; i < 4; i++) {\n var liTag = document.createElement('li');\n ulTag.appendChild(liTag);\n var liTag1 = document.createElement('li');\n ulDdown.appendChild(liTag1);\n }\n var button = document.createElement('button');\n button.innerHTML = \"Back\";\n button.className = \"back\";\n //goes back to the table layout when clicked\n button.onclick = finalize;\n mainDiv.appendChild(button);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
eslintenable mod_path_worker_sort_weighted sort 2D path weighted todo: more efficient sort
function sortWeightedPath (path, pathOrder, mergeDistance, orderWeight, sequenceWeight) { if (path.length <= 1) { return path } var newpath = [] if (sequenceWeight > 0) { var x0 = path[0][path[0].length - 1][X] var y0 = path[0][path[0].length - 1][Y] newpath[newpath.length] = path[0] path.splice(0, 1) pathOrder.splice(0, 1) var endpath = path[path.length - 1] path.splice(path.length - 1, 1) pathOrder.splice(pathOrder.length - 1, 1) } else { x0 = path[path.length - 1][path[path.length - 1].length - 1][X] y0 = path[path.length - 1][path[path.length - 1].length - 1][Y] newpath[newpath.length] = path[path.length - 1] path.splice(path.length - 1, 1) pathOrder.splice(pathOrder.length - 1, 1) endpath = path[0] path.splice(0, 1) pathOrder.splice(0, 1) } while (path.length > 0) { var dmin = Number.MAX_VALUE var wmin = Number.MAX_VALUE for (var seg = 0; seg < path.length; ++seg) { var x1 = path[seg][0][0] var y1 = path[seg][0][1] var d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0) var w = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0) + orderWeight * pathOrder[seg] + sequenceWeight * (seg / path.length) if (w < wmin) { wmin = w dmin = d var segmin = seg } } x0 = path[segmin][path[segmin].length - 1][X] y0 = path[segmin][path[segmin].length - 1][Y] if (Math.sqrt(dmin) <= mergeDistance) { newpath[newpath.length - 1] = newpath[newpath.length - 1].concat(path[segmin]) } else { newpath[newpath.length] = path[segmin] } path.splice(segmin, 1) pathOrder.splice(segmin, 1) } newpath[newpath.length] = endpath return newpath }
[ "function sort_by_weight(a,b){ // a and b are lifter id's\n\tvar lift_attempt = state.current.lift + \"_\" + state.current.attempt;\n\tvar lift_attempt_next = state.current.lift + \"_\" + (Number(state.current.attempt)+1);\n\tvar awn = Number(state.lifter_info[a][lift_attempt_next]);\n\tvar bwn = Number(state.lifter_info[b][lift_attempt_next]);\n\tvar as = state.lifter_info[a][lift_attempt + \"_state\"];\n\tvar bs = state.lifter_info[b][lift_attempt + \"_state\"];\n\tvar aw = Number(state.lifter_info[a][lift_attempt]);\n\tvar bw = Number(state.lifter_info[b][lift_attempt]);\n\tvar tie_breaker = (Number(state.lifter_info[a].lot_number) - Number(state.lifter_info[b].lot_number));\n\tif(0 == tie_breaker){\n\t\ttie_breaker = (Number(state.lifter_info[a].weight) - Number(state.lifter_info[b].weight));\n\t}\n\tif(0 == tie_breaker){\n\t\ttie_breaker = ((state.lifter_info[a].name) < (state.lifter_info[b].name)) ? -1 : 1;\n\t}\n\n\t// partition by whether lifter is doing current lift\n\tvar a_doing_this_lift = events_contains(state.lifter_info[a].which_lifts, state.current.lift);\n\tvar b_doing_this_lift = events_contains(state.lifter_info[b].which_lifts, state.current.lift);\n\tif( a_doing_this_lift && !b_doing_this_lift){ return -1; }\n\tif(!a_doing_this_lift && b_doing_this_lift){ return 1; }\n\t\n\t// partition by whether any scratched\n\tvar a_scratched = false;\n\tvar b_scratched = false;\n\tvar a_last_weight = 9999;\n\tvar b_last_weight = 9999;\n\tfor(var i = 0; i < 3; ++i){\n\t\tvar la = state.current.lift + \"_\" + i;\n\t\tif(LIFT_STATE.SCRATCH == state.lifter_info[a][la + \"_state\"]){ a_scratched = true; }\n\t\tif(state.lifter_info[a][la]){ a_last_weight = state.lifter_info[a][la]; }\n\t\tif(LIFT_STATE.SCRATCH == state.lifter_info[b][la + \"_state\"]){ b_scratched = true; }\n\t\tif(state.lifter_info[b][la]){ b_last_weight = state.lifter_info[b][la]; }\n\t}\n\tif(!a_scratched && b_scratched){ return -1; }\n\tif( a_scratched && !b_scratched){ return 1; }\n\t\n\t// partition by whether current lift has been performed\n\tif( lift_state_completed(as) && !lift_state_completed(bs)){ return -1; }\n\tif(!lift_state_completed(as) && lift_state_completed(bs)){ return 1; }\n\t\n\tif(state.lifter_info[a].flight != state.current.flight){\n\t\tif(a_last_weight != b_last_weight){ return a_last_weight - b_last_weight; }\n\t}\n\t\n\tif(!lift_state_completed(as) || (!awn && !bwn)){ // both have yet to complete current lift, or both have no next attempts\n\t\t// put scratches at end\n\t\tif(LIFT_STATE.SCRATCH == as && LIFT_STATE.SCRATCH != bs){\n\t\t\treturn 1;\n\t\t}else if(LIFT_STATE.SCRATCH != as && LIFT_STATE.SCRATCH == bs){\n\t\t\treturn -1;\n\t\t}\n\t\tif(LIFT_STATE.SCRATCH != as){ // both not scratched\n\t\t\tif(aw == bw){ return tie_breaker; }\n\t\t\treturn aw - bw;\n\t\t}else{\n\t\t\treturn tie_breaker;\n\t\t}\n\t}else{ // both have completed current lift\n\t\tvar asn = state.lifter_info[a][lift_attempt_next + \"_state\"];\n\t\tvar bsn = state.lifter_info[b][lift_attempt_next + \"_state\"];\n\t\t// put scratches at end\n\t\tif(LIFT_STATE.SCRATCH == asn && LIFT_STATE.SCRATCH != bsn){\n\t\t\treturn 1;\n\t\t}else if(LIFT_STATE.SCRATCH != asn && LIFT_STATE.SCRATCH == bsn){\n\t\t\treturn -1;\n\t\t}\n\t\t// put those without next attempt later\n\t\tif(awn && !bwn){\n\t\t\treturn -1;\n\t\t}else if(!awn && bwn){\n\t\t\treturn 1;\n\t\t}\n\t\tif(LIFT_STATE.SCRATCH != asn){ // both not scratched\n\t\t\tif(awn == bwn){ return tie_breaker; }\n\t\t\treturn awn - bwn;\n\t\t}else{\n\t\t\treturn tie_breaker;\n\t\t}\n\t}\n}", "function sortPaths(paths){\n\n var output = [];\n //add the first path untouched\n paths[0].isProcessed = true;\n output.push(paths[0]);\n\n var currentPath = paths[0];\n //process all unprocessed paths\n \n while(paths.filter(p=>p.isProcessed).length < paths.length)\n {\n var positionAfterDraw = currentPath.mustBeReversed ? currentPath.startPoint : currentPath.endPoint;\n\n //calculate the distance from current position to start and end points of all unprocessed paths\n var unprocessed = paths.filter(p=> !p.isProcessed);\n unprocessed.forEach(p=>{\n p.startPointDistance = distanceBetween(positionAfterDraw, p.startPoint);\n p.endPointDistance = distanceBetween(positionAfterDraw, p.endPoint);\n });\n\n var pathWithClosestStartPoint = unprocessed.sort((a,b)=> a.startPointDistance > b.startPointDistance)[0];\n var pathWithClosestEndPoint = unprocessed.sort((a,b)=> a.endPointDistance > b.endPointDistance)[0];\n\n if(pathWithClosestEndPoint.endPointDistance < pathWithClosestStartPoint.startPointDistance)\n {\n currentPath = pathWithClosestEndPoint;\n currentPath.mustBeReversed = true;\n }\n else\n {\n currentPath = pathWithClosestStartPoint;\n }\n\n currentPath.isProcessed = true;\n output.push(currentPath);\n\n }\n\n return output;\n}", "function docEdits_sortWeights()\n{\n //var msg=\"presort -------------\\n\";\n //for (i=0; i<docEdits.editList.length; i++) {\n // msg += i+\":\" +docEdits.editList[i].weight+\"=\"+docEdits.editList[i].text+\"\\n\";\n //}\n //alert(msg);\n\n //shift-sort algorithm. Keeps same-weight chunks together\n for (var i=0; i < docEdits.editList.length-1; i++)\n {\n for (var j=i+1; j < docEdits.editList.length; j++)\n {\n var aType = docEdits.editList[i].weightType;\n var bType = docEdits.editList[j].weightType;\n\n var a = docEdits.editList[i].weightNum;\n var b = docEdits.editList[j].weightNum;\n\n if ((aType == bType && a != null && b != null && a > b)\n || (aType == \"belowHTML\" && bType==\"aboveHTML\"))\n {\n var temp = docEdits.editList[j];\n for (var k=j; k>i; k--)\n {\n docEdits.editList[k] = docEdits.editList[k-1];\n }\n docEdits.editList[i] = temp;\n }\n }\n }\n\n //var msg=\"After pre sort:\\n\";\n //for (i=0; i<docEdits.editList.length; i++) {\n // msg += i+\":\" +docEdits.editList[i].weight+\"=\"+docEdits.editList[i].text+\"\\n\";\n //}\n //alert(msg);\n}", "function pathsort(paths, sep, algorithm) {\n sep = sep || '/'\n\n return paths.map(function(el) {\n return el.split(sep)\n }).sort(algorithm || levelSorter).map(function(el) {\n return el.join(sep)\n })\n}", "function getBestWaypoints (args) {\n const routeSortKey = args.routeSortKey || 'distance'\n return getOptimizedRoutes(args).then(function (routeWaypointPairs) {\n return sortRoutesBy({routeWaypointPairs, routeSortKey})[0]\n })\n}", "function sortCoordsByDistance(array) {\n array.sort(function (current, next) {\n let dist_current = distanceBetweenPoints(character.real_x, character.real_y, current.x, current.y);\n let dist_next = distanceBetweenPoints(character.real_x, character.real_y, next.x, next.y);\n if (dist_current < dist_next) return -1; else if (dist_current > dist_next) return 1; else return 0;\n });\n return array;\n}", "sortTotalCostsDescend() {\n this.visitedSquares.sort(function(a,b) {\n return b.total - a.total;\n });\n }", "function sortByDist(trees) {\n\ttrees.forEach(function(tree) {\n\t\ttree.dist = getDistanceFromLatLonInM([tree.lon, tree.lat], state.user.location)\n\t})\n\ttrees.sort(function(a, b) {\n\t\tif (a.dist < b.dist)\n\t\t\treturn -1;\n\t\tif (a.dist > b.dist)\n\t\t\treturn 1;\n\t\treturn 0;\n\t})\n\treturn trees\n}", "sortTrip () {\r\n this.recorded_trip.sort(function (x, y) {\r\n if (x.distance < y.distance) {\r\n return 1 // sorts each trip from highest(y) to lowest(x)\r\n }\r\n if (x.distance > y.distance) {\r\n return -1 // sorts each trip from highest(x) to lowest(y)\r\n } // x must equal to y\r\n return 0 // trip order will remain the same\r\n })\r\n }", "static bubbleSort2D(array) {\n let length = array.length;\n for (let i = 0; i < length - 1; i++) {\n for (let j = 0; j < length - 1 - i; j++) {\n if (array[j + 1][1] > array[j][1]) {\n let t = array[j + 1];\n array[j + 1] = array[j];\n array[j] = t;\n }\n }\n }\n return array;\n }", "function weightedLink(G, i) {\n if (i % cols != cols - 1) G.addEdge(new DirectedEdge(i, i + 1, 1 * weight));\n if (i % cols != 0) G.addEdge(new DirectedEdge(i, i - 1, 1 * weight));\n\n if (i + cols < rows * cols) {\n G.addEdge(new DirectedEdge(i, i + cols, 1 * weight));\n if (i % cols != cols - 1) G.addEdge(new DirectedEdge(i, i + cols + 1, 1.4 * weight));\n if (i % cols != 0) G.addEdge(new DirectedEdge(i, i + cols - 1, 1.4 * weight));\n }\n if (i - cols >= 0) {\n G.addEdge(new DirectedEdge(i, i - cols, 1 * weight));\n if (i % cols != cols - 1) G.addEdge(new DirectedEdge(i, i - cols + 1, 1.4 * weight))\n if (i % cols != 0) G.addEdge(new DirectedEdge(i, i - cols - 1, 1.4 * weight));\n }\n}", "function sortFromHigh(items) {\n\t\"use strict\";\n\tvar temp;\n\tfor (var i = 0; i < items.length - 1; i++) {\n\t\tfor (var j = 0; j < items.length - 1 - i; j++) {\n\t\t\tvar p1 = parseInt(items[j].getElementsByTagName(\"price\")[0].childNodes[0].nodeValue.substring(3));\n\t\t\tvar p2 = parseInt(items[j + 1].getElementsByTagName(\"price\")[0].childNodes[0].nodeValue.substring(3));\n\t\t\tif (p1 <= p2) {\n\t\t\t\ttemp = items[j];\n\t\t\t\titems[j] = items[j + 1];\n\t\t\t\titems[j + 1] = temp;\n\t\t\t}\n\t\t}\n\t}\n\treturn items;\n}", "function shortestReach(n, m, edges, s) {\n\n let d = []; // расстояния (индекс - расстояние от старта до вершины с этим индексом)\n for (let i = 0; i <= n; i++) {\n d[i] = 10 ** 6; // изначально все расстояния большие\n }\n\n d[s] = 0; // а до стартовой вершины расстояние 0\n\n let q = new PriorityQueue();\n\n let g = new Map();\n\n //массив дочерних вершин. граф неориентированный, добавляем в обе стороны\n for (let i = 0; i < m; i++) {\n //ребро в одну сторону\n let vertex_first = edges[i][0];\n let v_edges_first = g.has(vertex_first) ? g.get(vertex_first) : [];\n v_edges_first.push([edges[i][1], edges[i][2]]);\n g.set(vertex_first, v_edges_first);\n\n //ребро в другую сторону\n let vertex_second = edges[i][1];\n let v_edges_second = g.has(vertex_second) ? g.get(vertex_second) : [];\n v_edges_second.push([edges[i][0], edges[i][2]]);\n g.set(vertex_second, v_edges_second);\n }\n\n q.enqueue(s, 0); //идем в старт из старта за стоимость 0.\n\n while (!q.isEmpty()) {\n let c = q.front();\n q.dequeue();\n\n let dst = Math.abs(c.priority);\n let v = c.val;\n\n //для каждого потомка вершины улучшаем расстояние\n let g_v = g.get(v);\n for (let j = 0; j < g_v.length; j++) {\n let to = g_v[j][0]; //куда идем\n let len = g_v[j][1]; // стоимость хода\n let n_dst = dst + len;\n if (n_dst < d[to]) {\n d[to] = n_dst;\n q.enqueue(to, -d[to])\n }\n }\n }\n let result = [];\n for (let i = 1; i <= n; i++) {\n if (i !== s) {\n if (d[i] === 10 ** 6) {\n result.push(-1);\n } else {\n result.push(d[i]);\n }\n }\n }\n\n return result;\n\n}", "compare(path, another) {\n var min = Math.min(path.length, another.length);\n\n for (var i = 0; i < min; i++) {\n if (path[i] < another[i]) return -1;\n if (path[i] > another[i]) return 1;\n }\n\n return 0;\n }", "bestFirstSearch(){\n var heapOpen = new SortedList(comparer);\n var heapClosed = new SortedList(comparer);\n heapOpen.add(this.frontier);\n while(heapOpen.getCount() > 0){\n ITERATIONS++;\n var V = heapOpen.popFirst();\n MINPRIORITY = V.priority;\n V.generateStates();\n redraw();\n if(V.hash == 87654321){\n this.endPoint = V;\n break;\n }\n for(var i = 0 ; i < V.children.length; i++){\n V.children[i].priority = V.children[i].manhattanHeuristic() + V.children[i].outOfPlaceTilesHeuristic(); \n if(hasBetter(heapOpen,V.children[i].hash, V.children[i].priority)){\n continue;\n }\n if(hasBetter(heapClosed,V.children[i].hash, V.children[i].priority)){\n continue;\n }\n heapOpen.add(V.children[i]);\n }\n heapClosed.add(V);\n }\n heapOpen.clear();\n heapClosed.clear();\n return this.createSolution(this.endPoint);\n }", "function cycleSortPriority() {\r\n // We subtract 2 from sortTypes.length so we skip over sortHidden\r\n if (currentSortType == sortTypes.length - 2 || currentSortType == HIDDEN_SORT_TYPE) {\r\n currentSortType = 0;\r\n } else {\r\n currentSortType++;\r\n }\r\n sortTypes[currentSortType]();\r\n }", "function selectionSort(items) {\n // len is the length of the items array\n var len = items.length;\n // min will be some kind of empty variable\n var min;\n\n // iterates this from the very first index of the items array\n for (var i = 0; i < len; i++) {\n // set index of minimum to this position\n min = i;\n //\n // iterates one space up from the first index of array items\n for (var j = i + 1; j < len; j++) {\n // this will check the value of the higher index to the lower index\n // if this higher index holds a lower value than the lower index value from min = i\n // make the new minimum index min i and the higher index of j equal to each other\n if (items[j] < items[min]) {\n min = j;\n }\n }\n // if the current index min i is not equal to the new min index min = j value\n // swap this crap\n if (i !== min) {\n swap(items, i, min);\n }\n }\n\n return items;\n}", "function sortByDistance(jobs){\n \tjobs.sort(function(a,b){\n\t\t\t if(a.distance > b.distance){ return 1}\n\t\t if(a.distance < b.distance){ return -1}\n\t return 0;\n\t\t\t});\n\t\t\treturn jobs;\n\t}", "function top2Optimization(){\n for (var i=0;i<5;i++){\n checkChange(1,0,function(){\n adjustTree(arrIndexMap[1],hierarchy_array[0])\n })\n checkChange(0,1,function(){\n adjustTree(arrIndexMap[0],hierarchy_array[1])\n })\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate the search box with a given $searchterm. This calls /search/, ADD LOADING ... HERE (fix)
function populateSearchBox(searchterm) { var newrow = '<tr ><td id="loading_dots_text" style="text-align: right;" width="60%"></td><td id="loading_dots" style="text-align:left;"></td></tr>'; $('#search-table').append(newrow); dots_id = setInterval(animateDots, 500); $.get("/search/", {query: searchterm}, function(data){ clearInterval(dots_id); fillSearchBox(data); } ); }
[ "function callAjaxSearch() {\n\n searchTerm = $(settings.input).val();\n\n //No term - clear results\n if (searchTerm == \"\") {\n\n clear();\n resetPage();\n updateUI();\n\n\n }\n //Different term than last time - clear everything and start search\n else if (searchTerm != lastTerm) {\n\n clear();\n resetPage();\n search();\n\n }\n //Same term but different page - append content (if infinite scroll is active)\n else if (currentPage != lastPage) {\n\n if (!settings.infiniteScroll) {\n\n clear();\n }\n\n search();\n\n }\n\n\n timer = setTimeout(function(){callAjaxSearch()}, settings.delay);\n }", "function handleSearch(){\n var term = element( RandME.ui.search_textfield ).value;\n if(term.length){\n requestRandomGif( term, true);\n }\n}", "function search() {\n\t\tvar searchVal = searchText.getValue();\n\n\t\tsources.genFood.searchBar({\n\t\t\targuments: [searchVal],\n\t\t\tonSuccess: function(event) {\n\t\t\t\tsources.genFood.setEntityCollection(event.result);\n\t\t\t},\n\t\t\tonError: WAKL.err.handler\n\t\t});\n\t}", "function do_search() {\n var query = input_box.val().toLowerCase();\n\n if (query && query.length) {\n if (selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if (query.length >= settings.minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function () {\n run_search(query);\n }, settings.searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }", "function searchFunction () {\n activateSearch($searchInput, 'input');\n activateSearch($submit, 'click');\n}", "function searchSidebarResults ( term, baseurl, page, sort, search_count ) {\n var new_loc = $specified_loc.split(', ').join(',');\n var data = { what : term, where : new_loc, page_num : page, sortby : sort, count : search_count };\n $.ajax({\n type: \"POST\",\n url: baseurl + \"/api/search.php\",\n dataType: \"JSON\",\n data: data,\n success: function(data){\n if( data.success.results.locations.length > 0 ){\n if(!$.isEmptyObject(data.success.results.locations)){ \n renderSidebarResults(data.success.results.locations); \n }\n }\n }\n });\n }", "function do_search() {\n var query = input_box.val();\n\n if((query && query.length) || !$(input).data(\"settings\").minChars) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= $(input).data(\"settings\").minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, $(input).data(\"settings\").searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }", "function search()\n{\n\tvar searchText = searchInput.value;\n\n\t// if input's empty\n\t// displaying everything\n\tif (searchText == \"\")\n\t{\n\t\tshowAllFilteredWordEntries();\n\t\treturn;\n\t}\n\n\t// hiding everything except the matched words\n\tfor (let i = 0; i < loadedData.length; i++)\n\t{\n\t\tlet entry = getFilteredWordEntry(i);\n\t\tvar regx = new RegExp(searchText);\n\t\tif (regx.test(loadedData[i]))\n\t\t\tentry.hidden = false;\n\t\telse\n\t\t\tentry.hidden = true;\n\t}\n}", "function searchRequest(query_terms)\n{\n $.ajax\n ({\n type: \"GET\",\n url: \"/search/\",\n data: {'q' : query_terms},\n success: paginateResults\n });\n}", "function updateSearchTerm(searchTerm) {\n setSearchTerm(searchTerm);\n setIsLoading(true);\n }", "function do_search() {\n var $form = $('#search-form');\n var option = $form.find('select[name=action] option[selected]').val();\n if (!option) return false;\n var search_terms = $form.find('input[name=q]').val();\n var url = str_concat(option , '?q=' , search_terms);\n adr(url);\n return false;\n }", "function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}", "function searchForMovie(movieTitle) {\n searchBarElem.val(movieTitle);\n searchBarElem.keyup(); // trigger search\n}", "function showSearchMovies(){\n query = moviesSearch.value;\n if (query != \"\"){\n resultsList.innerHTML = \"\";\n customQuery = query;\n resetPageNumbers();\n customPage = 1;\n tmdb.searchMovies(query, customPage).then(data => {\n resultsList.innerHTML = \"\";\n results = data.searchMovies.results;\n totalPages = data.searchMovies.total_pages;\n\n if (results != undefined){\n newMoviesList(results);\n removeMiniNavActive();\n }\n else{\n resetPageNumbers();\n }\n\n loadMore.style.display = (totalPages > 1) ? 'inline' : 'none';\n });\n }\n}", "function call_tracking_input_search(){\n $('.cus-btn-search').on(\"click\",function(){\n //show loading image\n $('.loading_ani_img').show();\n\n var query = change_alias($('#table-search').val());\n //check if fetching classrooms or students\n var isFetchingStudents = window.location.href.includes('students');\n if(isFetchingStudents){\n var classroom_id = $('#classroom_id').val();\n call_search_students(query, classroom_id);\n }else{\n var faculty_id = $('#faculty_id').val();\n call_search_classrooms(query, faculty_id);\n }\n });\n}", "function search(event, searchTerms) {\n if (!searchTerms) {\n return clearSearchInput();\n }\n $(this).trigger(\"search.search\", searchTerms);\n if (typeof options.onfirstsearch === \"function\" && firstSearch) {\n firstSearch = false;\n options.onfirstsearch(searchTerms);\n } else {\n options.onsearch(searchTerms);\n }\n }", "function perform_search() {\n if (lastSearchType == \"D\") {\n searchHistory();\n } else if (lastSearchType == \"E\") {\n searchEpg();\n }\n }", "initializeResults() {\n\t\t$( '.mlp-search-field' ).each( ( index, element ) => this.initializeResult( element ) );\n\t}", "function doSearch(){\n document.SearchCustomer.search.value = true;\n document.SearchCustomer.curpos.value=0;\n submit('SearchCustomer');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function gets the username and password via the DOM passes data to the testAccount function
function validateAccount() { let uName = document.getElementById('username').value; let pword = document.getElementById('password').value; testAccount(uName, pword); }
[ "static login() {\n const doc = navigationDocument.documents[navigationDocument.documents.length - 1]\n const e = doc.getElementsByTagName('textField').item(0)\n const user = encodeURIComponent(e.getAttribute('data-username'))\n const pass = encodeURIComponent(e.getFeature('Keyboard').text)\n\n const dataString = `username=${user}&password=${pass}&remember=CHECKED&action=login&submit=Log+in`\n\n $.post('https://archive.org/account/login.php', dataString, (xhr) => {\n // https://developer.apple.com/documentation/tvmljs/xmlhttprequest\n // TVA.alert(TVA.amp(dataString))\n // TVA.alert(xhr.getAllResponseHeaders())\n if (xhr.status !== 200) {\n TVA.user = {}\n TVA.alert(`server responded with non-success status: ${xhr.status}`)\n return\n }\n\n // if (xhr.responseText.indexOf('Your browser does not appear to support cookies'))\n // return TVA.alert('testcookie set/send problem')\n\n // debugger\n // return TVA.alert(TVA.amp(xhr.responseText).replace(/</g, '&lt;').replace(/>/g, '&gt;'))\n TVA.set_user(TVA.last_week)\n })\n }", "function getCredentials() {\n\tconst user = {\n\t\temail: document.querySelector('[name=\"email\"]').value,\n\t\tpassword: document.querySelector('[name=\"password\"]').value\n\t};\n\n\treturn user;\n}", "function subtest_get_an_account(w) {\n // Make sure we don't have bar as the default engine yet.\n let engine = Services.search.getEngineByName(\"bar\");\n Assert.notEqual(engine, Services.search.defaultEngine);\n\n wait_for_provider_list_loaded(w);\n wait_for_search_ready(w);\n\n // Fill in some data\n type_in_search_name(w, \"Green Llama\");\n\n w.click(w.eid(\"searchSubmit\"));\n wait_for_search_results(w);\n\n // Click on the first address. This reveals the button with the price.\n let address = w.window.document.querySelector(\".address:first-child\");\n w.click(new elib.Elem(address));\n w.waitFor(\n () =>\n w.window.document.querySelectorAll('button.create:not([disabled=\"true\"])')\n .length > 0\n );\n\n // Pick the email address green@example.com\n plan_for_content_tab_load();\n\n // Clicking this button should close the modal dialog.\n let button = w.window.document.querySelector(\n 'button.create[address=\"green@example.com\"]'\n );\n w.click(new elib.Elem(button));\n}", "function doLogin(username, password){\n\thideOrShow(\"register\", false);\n\n\tif(!username || !password)\n\t{\n\t\tusername = document.getElementById(\"loginName\").value.toLowerCase(); //Assign from user field.\n\t\tpassword = document.getElementById(\"loginPassword\").value; //Assign from pass field.\n\t}\n\n\tUSERNAME = username;\n\t//Create JSON body.\n\tlet body = {\n\t\t\"username\": username,\n\t\t\"password\": password\n\t}\n\n\t$.post(urlBase + \"api/login\", body)\n\t\t.done(function(data) {\n\t\t\tif(data.success === false){\n\t\t\t\talert(\"Could not login: \\n\" + data.message );\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconsole.log(data);\n\t\t\t\tif(data.token)\n\t\t\t\t\tdocument.cookie = \"USER=\" + data.token;\n\t\t\t\t\tdocument.cookie = \"USERNAME=\" + username;\n\t\t\t\t\tdocument.cookie = \"PASSWORD=\" + password;\n\t\t\t\thideOrShow(\"Front Page\", false);\n\t\t\t\thideOrShow(\"contactPage\", true);\n\t\t\t\tgetContacts();\n\t\t\t}\n\n\t\t})\n\t\t.fail(function(err) {\n\t\t\tconsole.log(err);\n\t\t\talert(\"Failed to login\");\n\t\t})\n}", "static password() {\n const doc = navigationDocument.documents[navigationDocument.documents.length - 1]\n const e = doc.getElementsByTagName('textField').item(0)\n const val = e.getFeature('Keyboard').text\n\n TVA.render(`\n<document>\n <formTemplate>\n <banner>\n <img src=\"https://archive.org/images/glogo.png\" width=\"79\" height=\"79\"/>\n <description>\n Hello ${val}, enter your Internet Archive account password\n </description>\n </banner>\n <textField data-username=\"${val}\" secure=\"true\" isSecureTextEntry=\"true\">\n password\n </textField>\n <footer>\n <button onselect=\"TVA.login()\">\n <text>Login</text>\n </button>\n </footer>\n </formTemplate>\n</document>`, null)\n }", "function getDomVariables() {\n // the form\n registerFormDiv = document.querySelector('#log-in_form'); // the inputs\n\n usernameInput = document.querySelector('#username');\n emailInput = document.querySelector('#email');\n passwordInput = document.querySelector('#password');\n passwordBisInput = document.querySelector('#password-bis'); // the spans to display errors\n\n usernameErrorSpan = document.querySelector('label[for=\"username\"] span.msg-error');\n emailErrorSpan = document.querySelector('label[for=\"email\"] span.msg-error');\n passwordErrorSpan = document.querySelector('label[for=\"password\"] span.msg-error');\n passwordBisErrorSpan = document.querySelector('label[for=\"password-bis\"] span.msg-error'); // array including inputs and error spans\n\n inputsAndSpans = [['username', usernameInput, usernameErrorSpan], ['email', emailInput, emailErrorSpan], ['password', passwordInput, passwordErrorSpan], ['password-bis', passwordBisInput, passwordBisErrorSpan]]; // the clickable question marks to display input rule helps\n\n usernameQuestionMark = document.querySelector('#username-help');\n passwordQuestionMark = document.querySelector('#password-help');\n passwordBisQuestionMark = document.querySelector('#password-bis-help'); // array including question marks and text to display\n\n helpers = [[usernameQuestionMark, usernameHelp], [passwordQuestionMark, passwordHelp], [passwordBisQuestionMark, passwordBisHelp]];\n} // check the value of the input", "function requestSignup (username, name, email, password) {\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onreadystatechange = function() {\n\t\tif (xhttp.readyState == 4 && xhttp.status == 200){\n\t\t\talert(xhttp.responseText);\n\t\t\twindow.open(\"login.html\", \"_self\");\n\t\t}\n\t};\n\ttry{\n\t\txhttp.open(\"GET\", \"/signup/\" + username + \"/\" + name + \"/\" + email + \"/\" + password, true);\n\t\txhttp.send(null);\n\t}\n\tcatch(e){\n\t\talert(e);\n\t}\n}", "function subtest_get_an_account_part_2(w) {\n // An account should have been added.\n Assert.equal(nAccounts(), gNumAccounts + 1);\n\n // We want this provider to be our default search engine.\n wait_for_element_invisible(w, \"window\");\n wait_for_element_visible(w, \"successful_account\");\n\n // Make sure the search engine is checked\n Assert.ok(w.e(\"search_engine_check\").checked);\n\n // Then click \"Finish\"\n mc.click(w.eid(\"closeWindow\"));\n}", "function logOn(employeeId, password) {\n\n document.getElementById(\"logOnButton\").innerHTML = \"Processing...\";\n document.getElementById(\"alertId\").innerHTML = \"\";\n\n localStorage.clear();\n \n if (employeeId === \"\" ||\n password === \"\") {\n document.getElementById(\"alertId\").innerHTML = \"Please enter an ID and Password\";\n document.getElementById(\"password\").value = \"\";\n document.getElementById(\"logOnButton\").innerHTML = \"Log On\";\n }\n else {\n let webMethod = \"../BPP2.asmx/LogOn\";\n let parameters = \"{\\\"employeeId\\\":\\\"\" + encodeURI(employeeId) + \"\\\",\\\"password\\\":\\\"\" + encodeURI(password) + \"\\\"}\";\n \n $.ajax({\n type: \"POST\",\n url: webMethod,\n data: parameters,\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function (msg) {\n if (msg.d.length > 0) {\n accountArray = msg.d;\n localStorage.setItem(\"employeeId\", accountArray[0].employeeId);\n localStorage.setItem(\"badge\", accountArray[0].badge);\n localStorage.setItem(\"admin\", accountArray[0].admin);\n document.getElementById(\"employeeId\").value = \"\";\n document.getElementById(\"password\").value = \"\";\n window.open(\"../html/main.html\", \"_self\");\n }\n else {\n document.getElementById(\"alertId\").innerHTML = \"Sign in Failed\";\n document.getElementById(\"password\").value = \"\";\n document.getElementById(\"logOnButton\").innerHTML = \"Log On\";\n }\n }\n });\n }\n}", "function loadLoginData () {\n let savedUsername = config.get('username')\n let savedPassword = config.get('password')\n let savedRememberUsername = config.get('rememberUsername')\n let savedRememberPassword = config.get('rememberPassword')\n\n document.querySelector('#login-remember-name').checked = savedRememberUsername\n document.querySelector('#login-remember-password').checked = savedRememberPassword\n\n if (savedUsername) {\n document.querySelector('#login-name').value = savedUsername\n }\n\n if (savedPassword) {\n document.querySelector('#login-password').value = decrypt(savedPassword)\n }\n}", "function test_password_encrypt(){\n var tests, test_case_num, test_case, input_str, input_shift, output_str;\n jQuery.get('password-encrypt-tests.txt', function(data) {\n tests = data.split(\"\\n\");\n for (test_case_num = 0; test_case_num < tests.length; test_case_num++){\n test_case = tests[test_case_num].split(\",\");\n input_str = test_case[0];\n password = test_case[1];\n input_shift = parseInt(test_case[2]);\n output_str = test_case[3];\n assert(password_encryption(input_str, password, \n input_shift) === output_str);\n }\n console.log(\"Javascript password encryption passed\");\n });\n}", "function getEncryptedCredentials(adviseLaunchInfo) {\n \n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_GET_CREDENTIALS'));\n \n var pubKey = adviseLaunchInfo.eedPublicKey,\n ticketURL = adviseLaunchInfo.ticketURL;\n \n jQuery.ajax({ url : ticketURL,\n type : \"GET\",\n cache : false,\n success : function(returndata, status, xhr) {\n var urlL = \"../simulationcentral/smaAdviseEncryptedCredentials.jsp?pubKey=\" + pubKey;\n var myData;\n try {\n try {\n myData = String(returndata.documentElement.childNodes[1].textContent);\n } catch (error) {\n var myData1 = String(returndata);\n var sMyData1 = myData1.split('\\n');\n var ticketStr = sMyData1[0].split(\"ticket=\");\n myData = ticketStr[1];\n adviseLaunchInfo.loginTicket = myData;\n }\n } catch (error) {\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_GET_CRED_ERROR'));\n adviseGoBack(\n adviseLaunchInfo.translator.translate('LAUNCH_GET_LT_ERROR') + '<br\\>' + error \n );\n }\n \n if(adviseLaunchInfo.runAs) {\n \n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_ENC_CREDENTIALS'));\n \n pubKey = adviseLaunchInfo.eedPublicKeyDecoded;\n pubKey = pubKey.replace(/(\\r\\n|\\n|\\r)/gm,'');\n \n var encryptor = document.getElementById('encryptor');\n if (encryptor.encryptCredentials) {\n waitForPolymerAndEncrpytCredentials(adviseLaunchInfo);\n } else {\n /*window.addEventListener('polymer-ready', function(){*/\n \twindow.addEventListener('WebComponentsReady', function(){\n waitForPolymerAndEncrpytCredentials(adviseLaunchInfo);\n });\n console.log('Waiting for Polymer to be ready..')\n }\n \n } else {\n \n jQuery.ajax({ url : urlL,\n type : \"POST\",\n data : { 'loginTicket' : adviseLaunchInfo.loginTicket },\n dataType : \"text\",\n success : function(returndata, status, xhr) {\n returndata = emxUICore.trim(returndata);\n adviseLaunchInfo.resourceCredentials = returndata;\n \n if (adviseLaunchInfo.userSelectedStation.length > 0 && \n \t\tadviseLaunchInfo.userSelectedStation !== '{localhost}'){\n \t\n \t// If the user chose to set affinity to a regular station.\n \tcheckLocalStationAndLaunch(adviseLaunchInfo);\n \t\n }\n else{\n \n \t// If the user set affinity to {localhost} or no affinity was set\n // try to submit to localhost\n \tcheckPrivateStationAndLaunch(adviseLaunchInfo);\n \t\n }\n },\n error : function(jqXHR, textStatus, errorThrown) {\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_ENC_CREDENTIALS_ERROR'));\n adviseGoBack(\n adviseLaunchInfo.translator.translate('LAUNCH_ENC_CREDENTIALS_ERROR') + '<br\\>' + errorThrown \n );\n }\n });\n }\n }\n });\n}", "function login (password) {\n if (password === \"test1234\") {\n return \"Login Success!\";\n }\n}", "function getUserPassword(username) {\n return username;\n}", "function test_password_decrypt(){\n var tests, test_case_num, test_case, input_str, input_shift, output_str;\n jQuery.get('password-decrypt-tests.txt', function(data) {\n tests = data.split(\"\\n\");\n for (test_case_num = 0; test_case_num < tests.length; test_case_num++){\n test_case = tests[test_case_num].split(\",\");\n input_str = test_case[0];\n password = test_case[1];\n input_shift = parseInt(test_case[2]);\n output_str = test_case[3];\n assert(password_decryption(input_str, password, \n input_shift) === output_str);\n }\n console.log(\"Javascript password decryption passed\");\n });\n}", "function showPass() {\n const password = document.getElementById('password');\n const rePassword = document.getElementById('masterRePassword');\n if (password.type === 'password') {\n password.type = 'text';\n rePassword.type = 'text';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"ON - Password Confirm Input : \" + password.value);\n } else {\n password.type = 'password';\n rePassword.type = 'password';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"OFF - Password Confirm Input : \" + password.value);\n }\n} // show password function", "function setAccount() {\n console.log('check setAccount ', cache);\n\n let topbar = document.querySelector('.topbar');\n\n loadingEnd(); // TODO: Check\n // console.log(this.responseText);\n\n const urlParams = new URLSearchParams(window.location.search);\n let id = urlParams.get('id');\n let user\n if (id == null) {\n user = cache['user'];\n } else {\n user = cache['other'];\n }\n\n // Load project\n startProjectLoading();\n if (user['project_id'] != 0) {\n loadProject(user['project_id'], function () {setProject(user)});\n } else {\n setProject(user);\n }\n\n // Setup user bio\n topbar.querySelector('.topbar__name').innerText = user.name;\n let phone = user.phone;\n phone = '+' + phone[0] + ' (' + phone.slice(1, 4) + ') ' + phone.slice(4, 7) + '-' + phone.slice(7);\n topbar.querySelector('.topbar__phone').innerText = phone;\n\n document.querySelector('.team__title').innerText = user.team;\n\n //setup.sh avatar\n if (user.avatar != null && user.avatar != undefined && user.avatar != '') {\n topbar.querySelector('.topbar__avatar').style.backgroundImage = \"url('\" + user.avatar + \"')\";\n }\n\n // Setup user type label\n switch (user['user_type']) {\n case 0: // User\n // pass\n break;\n\n case 1: // Host\n topbar.querySelector('.topbar__type').innerText = 'Moderator';\n break;\n\n case 2: // Admin\n topbar.querySelector('.topbar__type').innerText = 'Admin';\n break;\n }\n\n setCredits();\n}", "async function authenticate(data, page) {\n console.log('Authenticating on CallMultiplier...');\n\n await page.goto(callMultiplier.login);\n await page.waitForSelector(callMultiplier.fields.login.login);\n\n await page.evaluate(({data, callMultiplier}) => {\n document.querySelector(callMultiplier.fields.login.login).value = data.user;\n document.querySelector(callMultiplier.fields.login.password).value = data.password;\n document.querySelector(callMultiplier.fields.login.button).click();\n }, {data, callMultiplier});\n\n await page.waitForSelector(callMultiplier.banner);\n\n console.log('Authenticated!');\n}", "function login(userNameOptional, passwordOptional, useOptionalParameters) {\n\tvar username;\n\tvar password;\n\tif (useOptionalParameters) {\n\t\tusername = userNameOptional;\n\t\tpassword = passwordOptional;\n\t} else {\n\t\tusername = inputLoginUsername.val();\n\t\tpassword = inputLoginPassword.val();\n\t}\n\n\t// if(username.length < 1 || password.length < 1){\n\t// alert(\"invalid username or password\");\n\t// return;\n\t// }\n\t$.ajax({\n\t\ttype : \"POST\",\n\t\turl : loginURL,\n\t\tdata : {\n\t\t\t'username' : username,\n\t\t\t'password' : password\n\t\t}\n\t}).always(function(returnData) {\n\t\t//'cast' to a json object\n\t\tvar json = JSON.parse(returnData);\n\t\tif (json.error) {\n\t\t\tif (json.err_pos === 1) {\n\t\t\t\talert(\"Invalid username or password\");\n\t\t\t} else if (json.err_pos === 2) {\n\t\t\t\talert(\"Invalid username or password\");\n\t\t\t} else if (json.err_pos === 3) {\n\t\t\t\talert(\"Invalid username or password\");\n\t\t\t} else if (json.err_pos === 4) {\n\t\t\t\talert(\"Invalid username or password length\");\n\t\t\t}\n\n\t\t\t//alert(\"invalid username/password :\" + json.err_pos);\n\t\t} else {\n\t\t\tif (json.cookie != null && json.userId != null) {\n\t\t\t\tif (parseInt(json.cookie.length) == 40) {\n\t\t\t\t\tsetCookie(cookieName, json.cookie);\n\t\t\t\t\tsetCookie(userIdCookie, json.userId);\n\t\t\t\t\twindow.location.href = myProfilePage;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\talert(\"cookie null...?\");\n\t\t}\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Server response callback for setting a question active.
function setQuestionActiveCallback(data, status) { if(status == "success"){ var questionID = data.responseJSON.questionId; displayStopButton(questionID); $('[questionid="'+questionID+'"]').find('.playBtnGroup').addClass('active'); $("#presentTab").click(); } }
[ "function setQuestionInactiveCallback(data, status) {\n\tif(status == \"success\"){\n\t\tvar questionID = data.responseJSON.questionId;\n\t\tdisplayPlayButton(questionID);\n\t\t$('[questionid=\"'+questionID+'\"]').find('.playBtnGroup').removeClass('active');\n\n\t\t// FIXME: Need to actually request and update the review tab before showing it\n\t\t\n\t\t//Show results view\n\t\t$(\"#reviewTab\").click();\n\t\t\n\t}\n}", "function respond() {\r\n if (!responded) {\r\n responded = true;\r\n self.callback.apply(null, arguments);\r\n }\r\n }", "function setNextQuestion() {}", "function handleQuestion() {\n $('.js-quiz-next-button').attr('value', 'Check Answer'); // Sets the value of the next button to 'check answer'\n $('.js-quiz-next-button').attr('aria-label', 'Check Answer'); // Set the aria label for the button\n $('.js-quiz-restart-button').prop('disabled', false); // Makes sure the Restart button is enabled\n let position = handleUserPosition(STORE.restart); // Increment user position \n let score = handleUserScore(STORE.answer); // Increment user score\n $('.js-quiz-form').data('form-state', 'factoid'); // Set form state to factoid\n renderPlanetProfile(); // Generate the planet profile\n renderUserInformation(position, score); // Display the new user score information\n renderQuestion(STORE.currentPlanet); // Display the next question\n renderOptions(STORE.currentPlanet); // Display the options for that question\n}", "function completeQuestionnaire(con, aid, qid, callback){\n var sql = \"UPDATE questionnaire_animal SET done = true WHERE aid=\" + aid + \" AND qid=\" + qid;\n con.query(sql, function(err, result){\n if (err) {\n callback({status: 'failure'});\n }\n else {\n callback({status: 'success'});\n }\n console.log(\"Owner of animal \" + aid + \" completed survey \" + survey_id);\n });\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 trackResponse() {\n console.log(`Logged response to question ${currentQuestion}`);\n let response = $(\"input[name='question']:checked\").val()\n responses.push(response)\n}", "function handleAnswer() { \n $(SUBMIT_BUTTON_CLASS).click(function(event) {\n event.preventDefault();\n var userSelection = $('input[name=\"answerButton\"]:checked').val();\n evalAnswer(userSelection);\n layoutForFeedback();\n incrementQuestion();\n });\n}", "submitCurrentResponse(){\n this.imageTaskView.checkAnswersAndUpdateView();\n let imageTaskResponse = this.imageTaskView.getResponse();\n if (imageTaskResponse.questionResponses.length > 0) {\n this.serverComm.submitImageTaskResponse(imageTaskResponse, this);\n }\n }", "function completeSurvey(con, aid, survey_id, callback){\n var sql = \"UPDATE survey_animal SET done = true WHERE aid=\" + aid + \" AND survey_id=\" + survey_id;\n con.query(sql, function(err, result){\n if (err) {\n callback({status: 'failure'});\n }\n else {\n callback({status: 'success'});\n }\n console.log(\"Owner of animal \" + aid + \" completed survey \" + survey_id);\n });\n}", "function setActiveExamType(status)\n{\n activeExamID = -1;\n activeExamType = status;\n renderPageElement(\"exams\");\n}", "function handleNextQuestion() {\n $('#js-next-question').on('click', function(event) {\n processNextQuestion();\n });\n}", "function setQuestion(quest){\n\n\t\t$('#main').append(questionConstructor(quest));\n\t\t//making main scroll to bottom\n\t\tmain.scrollTop = main.scrollHeight;\n\n\t\n\t\t\tvar temp = random_replies[Math.floor( Math.random()*Object.keys(random_replies).length )];\n\t\t\tcallBot(temp);\t\n\t\n\t\t\n\t}", "function handleAnswer(params, callback) {\n\tappAjax(\n\t\t'/tra-loi',\n\t\t'post',\n\t\tparams,\n\t\t'json',\n\t\tfunction(response) {\n\t\t\tcallback(response);\n\t\t\tif (!response.error) {\n\t\t\t\tconsole.log('success');\n\t\t\t} else {\n\t\t\t\tconsole.log('error');\n\t\t\t}\n\t\t}\n\t);\n}", "publishSurvey(event){\n switch(this.state.survey.status){\n case \"active\":\n alert(\"Survey is already active!\");\n break;\n case \"created\":\n let survey = this.state.survey;\n survey.status = \"active\";\n this.setState({ survey: survey });\n this.editSurvey();\n break;\n case \"closed\":\n alert(\"Survey is closed, you can't publish it!\");\n break;\n default:\n }\n }", "function processBotAnswer(answer) {\n if (answer === allQuestions[currentQuestionIndex].correctAnswer) {\n $(\"#answer-response\").html(\"An opponent answered first: \" + allQuestions[currentQuestionIndex].correctAnswer);\n $(\"#answer-response\").removeClass(\"hide\");\n finishQuestion();\n }\n}", "function submitAnswer() {\n let answer = app.form.convertToData('#survey-form');\n answer.answerer = loggedInUser.email;\n answer.survey_id = openSurvey.id;\n if (!answered(openSurvey.id)) {\n newAnswer(answer);\n } else {\n updateAnswer(answer);\n }\n}", "set student_response(newResponse) {\n this._student_response = newResponse;\n setValue(`cmi.interactions.${this.index}.student_response`, newResponse);\n }", "function reportAnswer() {\n axios.put(`/qa/answers/${answer.id}/report`, {})\n .then(() => {\n setReport(true);\n })\n .catch((error) => {\n throw error;\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a function that proxies to the given method name on the globals console object. The proxy will also detect if the console doesn't exist and will appropriately noop. This allows support for IE9, which doesn't have a console if the developer tools are not open.
function consoleProxy(method) { return function () { if (console) { console[method].apply(console, arguments); } }; }
[ "createProxy() {\n const self = this;\n this._proxy = new Proxy(console, {\n get: (target, property) => {\n if ( typeof target[property] === 'function' ) {\n return function(args) {\n self.send(property, args);\n return target[property](args);\n }\n }\n },\n });\n }", "function _defineConsoleLogMethod(name, level) {\n enhancedConsole[name] = function __expoConsoleLog(...data) {\n const originalMethod = originalConsole[name];\n if (typeof originalMethod === 'function') {\n originalMethod.apply(originalConsole, data);\n }\n _enqueueRemoteLog(level, {}, data);\n };\n }", "function consoleMessage()\n{\n\t// Call debugConsole.consoleMessage() with console as \"this\" and all the arguments passed to consoleMessage().\n\tdebugConsole.consoleMessage.apply(debugConsole, arguments);\n}", "static getMethodInfoByName(method_name){\n\t\treturn null;\n\t}", "function TestCallThrow(callTrap) {\n var f = new Proxy(() => {\n ;\n }, {\n apply: callTrap\n });\n\n (() => f(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n }).x(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n })[\"x\"](11))();\n\n \"myexn\";\n\n (() => Function.prototype.call.call(f, {}, 2))();\n\n \"myexn\";\n\n (() => Function.prototype.apply.call(f, {}, [1]))();\n\n \"myexn\";\n var f = Object.freeze(new Proxy(() => {\n ;\n }, {\n apply: callTrap\n }));\n\n (() => f(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n }).x(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n })[\"x\"](11))();\n\n \"myexn\";\n\n (() => Function.prototype.call.call(f, {}, 2))();\n\n \"myexn\";\n\n (() => Function.prototype.apply.call(f, {}, [1]))();\n\n \"myexn\";\n}", "function realMethodWrapperFor(real, methodName, fake) {\n var realMethod = real[methodName];\n\n return function() {\n // Check against arguments\n var args = arrayify(arguments);\n var returnValue = realMethod.apply(real, arguments);\n\n fake.realCalls.push({\n methodName: methodName,\n args: args,\n returnValue: returnValue\n });\n\n return returnValue;\n };\n }", "function createIfDefinedCb(obj, methodName) {\n return function() {\n if (obj && obj[methodName]) {\n return obj[methodName].apply(obj, arguments);\n }\n };\n}", "function debug() {\n // Nothing to test, yay :D\n}", "function setupConsoleLogging() {\n (new goog.debug.Console).setCapturing(true);\n}", "function addBuiltin (name, handler) {\n /* TODO: guard against duplicate builtins */\n builtinHandlers.set(name, handler);\n}", "function overridePrototype(prototype, methodName, func) {\n prototype['_' + methodName] = prototype[methodName];\n prototype[methodName] = func;\n }", "function myDoubleConsoleLog(One, Two) {\n if (typeof(One) === \"function\" && typeof(Two) === \"function\") {\n console.log(One());\n console.log(Two());\n }\n}", "function oosHookJsCode()\n{\n\tfor (var i = 0; i < oosHookJsCodeFunctions.length; i++)\n\t{\n\t\tif (function_exists(oosHookJsCodeFunctions[i]))\n\t\t\tsetTimeout(oosHookJsCodeFunctions[i] + '()', 0);\n\t}\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 }", "function proxy(){\n\n var proxyFactory = function(){\n\n //The wrapped function to call.\n var fnToCall = arguments.length === 2 ? arguments[0][arguments[1]] : arguments[0];\n\n //A counter used to note how many times proxy has been called.\n var xCalled = 0;\n\n //An array whose elements note the context used to calll the wrapped function.\n var contexts = [];\n\n //An array of arrays used to note the arguments that were passed to proxy.\n var argsPassed = [];\n\n //An array whose elements note what the wrapped function returned.\n var returned = [];\n\n ///\n ///Privileged functions used by API\n ///\n\n //Returns the number of times the wrapped function was called.\n var getCalledCount = function(){\n return xCalled;\n };\n\n //If n is within bounds returns the context used on the nth \n //call to the wrapped function, otherwise returns undefined.\n var getContext = function(n){\n if(n >= 0 && n < xCalled){\n return contexts[n];\n }\n };\n\n //If called with 'n' and 'n' is within bounds then returns the \n //array found at argsPassed[n], otherwise returns argsPassed.\n var getArgsPassed = function(){\n if(arguments.length === 1 && arguments[0] >= 0 && arguments[0] < argsPassed.length){\n return argsPassed[arguments[0]];\n }else{\n return argsPassed;\n }\n };\n\n //If called with 'n' and 'n' is within bounds then returns \n //value found at returned[n], otherwise returns returned.\n var getReturned = function(){\n if(arguments.length === 1 && arguments[0] >= 0 && arguments[0] < returned.length){\n return returned[arguments[0]];\n }else{\n return returned;\n }\n };\n\n //If 'n' is within bounds then returns an \n //info object, otherwise returns undefined.\n var getData= function(n){\n if(n >= 0 && n < xCalled){\n var args = getArgsPassed(n);\n var context = getContext(n);\n var ret = getReturned(n);\n var info = {\n count: n + 1,\n argsPassed: args,\n context: context,\n returned: ret\n };\n return info;\n }\n };\n\n //If you just want to know if the wrapped function was called \n //then call wasCalled with no args. If you want to know if the \n //callback was called n times, pass n as an argument.\n var wasCalled = function(){\n return arguments.length === 1 ? arguments[0] === xCalled : xCalled > 0;\n };\n\n //A higher order function - iterates through the collected data and \n //returns the information collected for each invocation of proxy.\n var dataIterator = function(callback){\n for(var i = 0; i < xCalled; i++){\n callback(getData(i));\n }\n };\n\n //The function that is returned to the caller.\n var fn = function(){\n //Note the context that the proxy was called with.\n contexts.push(this);\n //Note the arguments that were passed for this invocation.\n var args = [].slice.call(arguments);\n argsPassed.push(args.length ? args : []);\n //Increment the called count for this invocation.\n xCalled += 1;\n //Call the wrapped function noting what it returns.\n var ret = fnToCall.apply(this, args);\n returned.push(ret);\n //Return what the wrapped function returned to the caller.\n return ret;\n };\n\n ///\n ///Exposed Lovwer level API - see Privileged functions used by API above.\n ///\n\n fn.getCalledCount = getCalledCount;\n\n fn.getContext = getContext;\n\n fn.getArgsPassed = getArgsPassed;\n\n fn.getReturned = getReturned;\n\n fn.getData = getData;\n\n ///\n ///Exposed Higher Order API - see Privileged functions used by API above.\n ///\n \n fn.wasCalled = wasCalled;\n\n fn.dataIterator = dataIterator;\n\n //Replaces object's method property with proxy's fn.\n if(arguments.length === 2){\n arguments[0][arguments[1]] = fn; \n }\n\n //Return fn to the caller.\n return fn;\n };\n\n //Convert arguments to an array, call factory and returns its value to the caller.\n var args = [].slice.call(arguments);\n return proxyFactory.apply(null, args);\n\n }", "function ConsoleEmulator()\n{\n this.OnRead = false;\n this.OnReadChar = false;\n this.rawConsole = false;\n this.inputBuffer = false;\n this.cursor = false;\n var me = this;\n\n this.keyPress = function(e)\n {\n if(!e.key || e.key.length > 1) return;\n\n me.inputBuffer.textContent += e.key;\n if(me.OnReadChar) me.OnReadChar(e.key);\n me.FixFloatingObjects();\n };\n this.keyDown = function(e)\n {\n if(e.keyCode === 8 && me.inputBuffer.textContent.length > 0)\n {\n me.inputBuffer.textContent = me.inputBuffer.textContent.substring(0, \n me.inputBuffer.textContent.length - 1);\n }\n else if(e.keyCode === 13 && me.inputBuffer.textContent.length > 0)\n {\n if(me.OnRead) me.OnRead(me.inputBuffer.textContent);\n me.WriteLine(me.inputBuffer.textContent);\n me.inputBuffer.textContent = \"\";\n }\n };\n}", "function overrideMethod(target, methodName, funcSource) {\n var superFunc = target[methodName] || function() {};\n var superFuncBound = function() {\n return superFunc.apply(target, arguments);\n };\n target[methodName] = funcSource(superFuncBound);\n }", "function registerLine(name, drawFn, drawControlPointsFn, controlPointsFn, dockControlPointFn, pointInFn, force) {\n // Exist\n if (exports.drawLineFns[name] && !force) {\n return false;\n }\n exports.drawLineFns[name] = {\n drawFn: drawFn,\n drawControlPointsFn: drawControlPointsFn,\n controlPointsFn: controlPointsFn,\n dockControlPointFn: dockControlPointFn,\n pointIn: pointInFn\n };\n return true;\n}", "function printConsoleText(text) {\n var console = document.getElementById(\"console\");\n console.innerHTML = text;\n}", "function disableWhiteboardCalculator() {\n var fo = getWhiteboardObject();\n if(fo.disableCalculator) {\n fo.disableCalculator();\n }\n else {\n alert('could not find disableCalculator()');\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find Pets with Customer BY ID
async findOneWithCustomer(req, res, next) { let pet; const { id } = req.params; try { pet = await petFacade.findOneWithCustomer({ where: { id }, include: ["customer"] }); } catch (e) { return next(e); } res.send(pet); }
[ "async findAllWithCustomer(req, res, next) {\n let pets;\n try {\n pets = await petFacade.findAllWithCustomer({\n where: {},\n include: [\"customer\"]\n });\n } catch (e) {\n return next(e);\n }\n res.send(pets);\n }", "async getBagItemsByCustomerId(req, res) {\n const customerId = req.params.customerId;\n\n var { error } = Joi.validate(customerId, Joi.objectId().required());\n\n if (error) {\n return res.status(404).send(error.details[0].message);\n }\n\n const bag = await Bag.find({ customer: customerId })\n .populate(\"customer\")\n .populate({\n path: \"product\",\n populate: {\n path: \"brand\",\n model: \"brands\",\n },\n });\n\n res.send(bag);\n }", "async findCustomer(customerId) {\n return Appointment.findOne({where:{customerId}});\n }", "findById(id) {\n return db.one(`\n SELECT parks.id, parks.name, states.name AS state\n FROM parks\n JOIN states\n ON states.code = parks.state\n WHERE parks.id = $1`, id);\n }", "function getPetById(id) {\n return new Promise((resolve, reject) => {\n mustBeInArray(petsJSON, id)\n .then(pet => resolve(pet))\n .catch(err => reject(err))\n })\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}", "static async findBestCustomers() {\n\t\tconst results = await db.query(\n\t\t\t`\n\t\t\tSELECT c.id, first_name AS \"firstName\", last_name AS \"lastName\",phone,c.notes\n\t\t\tFROM customers c\n\t\t\tJOIN reservations ON c.id = reservations.customer_id\n\t\t\tGROUP BY c.id ORDER BY COUNT(customer_id) DESC LIMIT 10;\n\t\t\t`\n\t\t);\n\t\treturn results.rows.map((c) => new Customer(c));\n\t}", "static async getRestaurantByID(id) {\n try {\n // create a pipeline that matches the restaurants & review collections together\n const pipeline = [\n {\n // first matches the id of a certain restaurant\n $match: {\n _id: new ObjectId(id),\n },\n },\n {\n // second, look up some other items (reviews) to add to the result\n // part of the mongodb aggregation pipeline\n $lookup: {\n // from reviews...\n from: \"reviews\",\n let: {\n id: \"$_id\",\n },\n // create this pipeline thats going to...\n pipeline: [\n {\n // match the restaurant id (find all the reviews that match that restaurant id)...\n $match: {\n $expr: {\n $eq: [\"$restaurant_id\", \"$$id\"],\n },\n },\n },\n {\n $sort: {\n date: -1,\n },\n },\n ],\n // set the results to be 'reviews'...\n as: \"reviews\",\n },\n },\n {\n // add a field called reviews thats going to be a new thing in results...\n $addFields: {\n reviews: \"$reviews\",\n },\n },\n ]\n\n // collect everything and return it\n return await restaurants.aggregate(pipeline).next()\n } catch (e) {\n console.error(`Something went wrong in getRestaurantByID: ${e}`)\n throw e\n }\n }", "findByState(id) {\n return db.many(`\n SELECT parks.id, parks.name, parks.state, states.name AS state\n FROM parks\n JOIN states\n ON states.code = parks.state\n WHERE parks.state = $1`, id);\n }", "function findPerson(id) {\n var foundPerson = null;\n for (var i = 0; i < persons.length; i++) {\n var person = persons[i];\n if (person.id == id) {\n foundPerson = person;\n break;\n }\n }\n\n return foundPerson;\n }", "function getCustomer(id) {\n return $http.get(baseUrl+\"customer/\"+id,{headers:setHeaders()});\n }", "findPallet(id) {\n return this.state.pallets.find(pallet => pallet.id === id);\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}", "async function getCartsByUserId(id) {\n try {\n const { rows: [cart] } = await\n client.query(`\n SELECT * FROM orders\n WHERE status = 'created'\n AND \"userId\" = $1\n `, [ id ])\n\n console.log(\"cartid\", cart)\n\n const { rows: products} = await client.query(`\n SELECT products.*, order_products.id AS \"orderProductId\"\n FROM products\n JOIN order_products ON products.id=order_products.\"productId\"\n WHERE order_products.\"orderId\"=$1;\n `, [id])\n\n cart.products = products\n console.log(\"cart products\", cart)\n return cart\n } catch (error) {\n throw error;\n }\n}", "function GetGiftcardsByChildId(id) {\n return $resource(_URLS.BASE_API + 'childgiftcard/by_child/' + id + _URLS.TOKEN_API + $localStorage.token).get().$promise;\n }", "function addCustomer(){\n var customerArray = [];\n\n transactions.forEach(function(transaction){\n if (transaction.customer !== undefined ){\n var customer = transaction.customer\n customerArray.push(customer)\n }\n });\n var filterArray = [...new Set(customerArray)]\n return (filterArray)\n}", "function getProductByID(productArray, id) {\r\n return productArray.find(function(product){\r\n return product.id == id;\r\n });\r\n}", "function getCardByID(id) {\n //return variable, assigned as null to return null if no card found\n let r = null;\n //for each card\n cards.forEach(card => {\n //if card id is equal to id input\n if (card.cardID === id)\n //assign card to return variable\n r = card;\n });\n return r;\n}", "fetchOrdersByCustomerId(customerId, kioskStationId) {\n AppDispatcher.handleCartAction({\n actionType: ActionConstants.ORDER_REQUEST_DATA,\n customerId: customerId,\n kioskStationId: kioskStationId\n });\n OrderApi.initOrdersDataByCustomerId(customerId, kioskStationId);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds our milestones object
function buildMilestones(actions) { const available = { event: "ui_prompts", handle: "availSurvival", values: [] }; const unavailable = { event: "ui_prompts", handle: "unavailSurvival", values: [] }; const prevent = { event: "ui_prompts", handle: "preventSurvival", values: [] }; actions.forEach((item, index) => { if (item.available) { available.values.push(index + 1); } else if (item.title_tip.includes("prevent")) { prevent.values.push(index + 1); } else { unavailable.values.push(index + 1); } }); const milestones = [available, unavailable, prevent]; return milestones; }
[ "function getMilestones(callBack) {\n\t\tpost('/components/' + config.component + '/root/milestones', {}, function(resultObj) { \n\t\t\tobj.config.milestones = resultObj; // save milestones to the local config obj\n\t\t\tif (typeof callBack == 'function') callBack();\n\t\t});\n\t}", "getPublicMilestones() {\n this.options.path = `${this.path}/Milestones/`;\n this.options.method = 'GET';\n return promiseRequest(this.options).then(res => formatJson(res));\n }", "createIssueListofMilestone() {\n let milestoneIssues = [];\n let milestoneTitle = this.props.data[\"title\"];\n this.props.issueList.forEach(function (issue) {\n if (issue[\"milestone\"] != null) {\n if (issue[\"milestone\"][\"title\"] === milestoneTitle) {\n let object = {\n url: issue[\"url\"],\n html_url: issue[\"html_url\"],\n title: issue[\"issue_title\"],\n };\n milestoneIssues.push(object)\n }\n }\n });\n\n return milestoneIssues;\n }", "function Milestone(github, data) {\n this.github = github;\n this.data = data;\n var url = data.url;\n if (url == null) {\n throw \"Missing required `data.url`\";\n }\n var p = url.indexOf(\"/repos/\");\n if (p >= 0) {\n url = url.substring(p + 1);\n }\n this.apiurl = url;\n }", "async function transferMilestones() {\n inform('Transferring Milestones');\n\n // Get a list of all milestones associated with this project\n let milestones = await gitlabApi.ProjectMilestones.all(\n settings.gitlab.projectId\n );\n\n // sort milestones in ascending order of when they were created (by id)\n milestones = milestones.sort((a, b) => a.id - b.id);\n\n // get a list of the current milestones in the new GitHub repo (likely to be empty)\n const githubMilestones = await githubHelper.getAllGithubMilestones();\n\n // if a GitLab milestone does not exist in GitHub repo, create it.\n for (let milestone of milestones) {\n if (!githubMilestones.find(m => m.title === milestone.title)) {\n console.log('Creating: ' + milestone.title);\n try {\n // process asynchronous code in sequence\n await githubHelper.createMilestone(milestone);\n } catch (err) {\n console.error('Could not create milestone', milestone.title);\n console.error(err);\n }\n } else {\n console.log('Already exists: ' + milestone.title);\n }\n }\n}", "async function getAllGHMilestones(owner, repo) {\n try {\n await sleep(2000);\n // get an array of GitHub milestones for the new repo\n let result = await github.issues.listMilestonesForRepo({owner: owner, repo: repo, state: 'all'});\n\n // extract the milestone number and title and put into a new array\n let milestones = result.data.map(x => ({number: x.number, title: x.title}));\n\n return milestones;\n } catch (err) {\n console.error(\"Could not access all GitHub milestones\");\n console.error(err);\n process.exit(1);\n }\n}", "async function createMilestone(owner, repo, milestone) {\n // convert from GitLab to GitHub\n let ghMilestone = {\n owner: owner,\n repo: repo,\n title: milestone.title,\n description: milestone.description,\n state: (milestone.state === 'active') ? 'open' : 'closed'\n };\n\n if (milestone.due_date) {\n ghMilestone.due_on = milestone.due_date + 'T00:00:00Z';\n }\n\n await sleep(2000);\n\n if (settings.debug) return Promise.resolve();\n // create the GitHub milestone\n return await github.issues.createMilestone(ghMilestone);\n}", "function milestoneTracking()\r\n{\r\n try\r\n {\r\n // ADDED 11/8/2012 RMH: If yesterday was one of the recognized holidays, then we will not execute the script\r\n var holiday = WasYesterdayAHoliday();\r\n if ( !holiday )\r\n {\r\n var searchresults = nlapiSearchRecord('projecttask', 1009, null, null);\r\n if ( searchresults != null )\r\n {\r\n for ( var i=0; i<searchresults.length; i++ )\r\n {\r\n var recordID = searchresults[i].getId();\r\n nlapiLogExecution('DEBUG', 'milestoneTracking()', \"recordID: \" + recordID);\r\n var ptRec = nlapiLoadRecord('projecttask', recordID);\r\n\r\n // NetSuite Bug Found - nlapiGetFieldValues is currently not working so we have to use a String Separating\r\n // Delimiter in order to get the values selected in the Linked Project Tasks multi-select field\r\n var lpt = ptRec.getFieldValue('custevent_linked_project_tasks');\r\n nlapiLogExecution('DEBUG', 'milestoneTracking()', \"lpt: \" + lpt);\r\n nlapiLogExecution('DEBUG', 'milestoneTracking()', \"lpt - escape: \" + escape(lpt));\r\n var linkedProjTasks = new Array();\r\n if ( lpt != null && lpt != '' )\r\n {\r\n var strChar5 = String.fromCharCode(5);\r\n linkedProjTasks = lpt.split(strChar5);\r\n nlapiLogExecution('DEBUG', 'milestoneTracking()', \"linkedProjTasks - length: \" + linkedProjTasks.length);\r\n nlapiLogExecution('DEBUG', 'milestoneTracking()', \"linkedProjTasks - joined: \" + linkedProjTasks.join());\r\n }\r\n else\r\n {\r\n nlapiLogExecution('DEBUG', 'milestoneTracking()', \"linkedProjTasks was null - no splitting needed\");\r\n }\r\n\r\n linkedProjTasks.push(recordID);\r\n\r\n\r\n var newRecData = new Object();\r\n newRecData.currentProjTaskID = recordID;\r\n newRecData.endDateAdjusted = ptRec.getFieldValue('custevent_enddateadjusted');\r\n nlapiLogExecution('DEBUG', 'milestoneTracking()', \"End Date Adjusted: \" + ptRec.getFieldValue('custevent_enddateadjusted'));\r\n newRecData.taskStatus = ptRec.getFieldValue('custevent_taskstatus');\r\n newRecData.numDateMoved = ptRec.getFieldValue('custevent_datemoved');\r\n newRecData.numDateBlown = ptRec.getFieldValue('custevent_dateblown');\r\n newRecData.projectID = ptRec.getFieldValue('company');\r\n newRecData.projectManager = nlapiLookupField('job', newRecData.projectID, 'custentity_primary_project_manager');\r\n newRecData.changeReason = ptRec.getFieldValue('custevent_reasonchangerecord');\r\n\r\n createMilestoneHistoryRecord(linkedProjTasks, newRecData, \"blown\");\r\n\r\n }\r\n }\r\n else\r\n {\r\n nlapiLogExecution('DEBUG', 'milestoneTracking()', \"No Search Results Found\");\r\n }\r\n }\r\n else\r\n {\r\n nlapiLogExecution('DEBUG', 'onAfterSubmit() -- Script will not execute', 'Yesterday was a Holiday: ' + holiday);\r\n }\r\n }\r\n catch(e)\r\n {\r\n var msg = Logger.FormatException(e);\r\n nlapiLogExecution('DEBUG', 'Unexpected Error in milestoneTracking()', msg);\r\n var emailbody = \"Function: milestoneTracking\\nEnvironment: Sandbox\\nError: \" + msg;\r\n Messaging.SendMessage(25846, 'alliant1@exploreconsulting.com', 'Unexpected Error Occurred in EC_Scheduled_ProjectTask.js', emailbody);\r\n }\r\n}", "function buildNav() {\n for (section of sections) {\n target = section.id;\n sectionTitle = section.dataset.nav;\n createMenuItem(target, sectionTitle);\n }\n}", "postV3ProjectsIdMilestones(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdMilestones(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "function updateMilestonePage(sprSheet,milestone,issues) {\n\n var mileSheet=sprSheet.getSheetByName(milestone)\n if ( mileSheet == null ) return\n if ( mileSheet.getMaxRows() == 1 ) return // no PRs, nothing to do\n \n //get the existing sheet information\n var range=mileSheet.getRange(2,1,mileSheet.getMaxRows()-1,6)\n var data=range.getValues()\n // \n \n // otherwise, loop over the data and look for updates\n var foundPRs={}\n for ( var i in issues) { //issues is the new updated information\n var iss = issues[i]\n var pr = iss['prNum']\n var sigInfo=parseSigInfo(iss['labels'])\n var approvedSigs=sigInfo[0]\n var pendingSigs=sigInfo[1]\n var testsPassed=sigInfo[2]\n \n //check this against the info we have from before\n for ( var row in data ) {\n if ( data[row][0] != pr ) {\n continue;\n }\n foundPRs[data[row][0]]=1\n\n //now just update information as needed to match current github state\n if ( data[row][3] != approvedSigs ) {\n mileSheet.getRange(parseInt(row)+2,4).setValue(approvedSigs) //add one for 0->1 and one for the header row\n }\n if ( data[row][4] != pendingSigs ) {\n mileSheet.getRange(parseInt(row)+2,5).setValue(pendingSigs) \n }\n if ( data[row][5] != testsPassed ) {\n mileSheet.getRange(parseInt(row)+2,6).setValue(testsPassed)\n }\n break // no need to keep going\n } \n }\n // done updating old information\n \n // hide rows for PRs that are closed already\n for ( var row in data) {\n if ( foundPRs[data[row][0]] != 1 ) {\n mileSheet.hideRows(parseInt(row)+2)\n }\n }\n \n // now add new rows for new PRs\n var data=[]\n var formulas=[]\n for ( var i in issues ) { //this code must be repeated elsewhere - could be consolidated\n var iss=issues[i]\n var pr=iss['prNum']\n if ( foundPRs[pr] == 1 ) {\n continue\n }\n\n var sigInfo=parseSigInfo(iss['labels'])\n var approvedSigs=sigInfo[0]\n var pendingSigs=sigInfo[1]\n var testsPassed=sigInfo[2]\n var comments=''\n data.push( [ extractDate(iss['date']),iss['title'],approvedSigs,pendingSigs,testsPassed,comments] )\n formulas.push( ['=HYPERLINK(\"http://www.github.com/cms-sw/cmssw/pull/'+pr+'\",\"'+pr+'\")'] )\n }\n \n //in one set of commands, add all the new rows\n var nCols=7\n var nNewRows=data.length\n if ( nNewRows > 0 ) {\n mileSheet.insertRowsAfter(1,nNewRows)\n var rangeD=mileSheet.getRange(2,2,nNewRows,nCols-1)\n var rangeF=mileSheet.getRange(2,1,nNewRows,1)\n rangeD.setValues(data)\n rangeF.setFormulas(formulas)\n }\n \n \n // Protect the active sheet, then remove all other users from the list of editors.\n var protection = mileSheet.protect().setDescription('Protected sheet');\n \n // Ensure the current user is an editor before removing others. Otherwise, if the user's edit\n // permission comes from a group, the script will throw an exception upon removing the group.\n var me = Session.getEffectiveUser();\n protection.addEditor(me);\n protection.removeEditors(protection.getEditors());\n if (protection.canDomainEdit()) {\n protection.setDomainEdit(false);\n }\n\n //redo the formatting with the new rows\n var nRows=mileSheet.getLastRow()\n if ( nRows>1 ) {\n var range=mileSheet.getRange(2,nCols,nRows-1,1)\n protection.setUnprotectedRanges([range])\n }\n mileSheet.getRange(1,1,nRows,nCols).setWrap(true)\n \n}", "_generateIssueCells() {\n var issueCells = [];\n var lanes = {};\n for (let i = 0; i < this.props.chart.issues.length; i++){\n let issue = this.props.chart.issues[i];\n let issueLane = issue.lane;\n let issueLaneKey = issueLane.toString();\n if (! _.has(lanes, issueLaneKey)) {\n lanes[issueLaneKey] = this._generateBlankCells();\n }\n let currLaneCells = lanes[issueLaneKey];\n // let start_idx = Math.ceil(issue.start/this.msIn2Weeks);\n // let end_idx = Math.ceil(issue.end/this.msIn2Weeks);\n var idxs = this._findIndexes(issue.start, issue.end, this.props.chart.sprints);\n var start_idx = idxs.start_idx;\n var end_idx = idxs.end_idx;\n\n for (let j = start_idx; j <= end_idx; j++) {\n let colors = Utils.getColors(issue);\n let textColor = 'FF' + colors.color;\n let backgroundColor = 'FF' + colors.backgroundColor;\n let text = '';\n let leftBorder = false;\n let rightBorder = false;\n if (j == start_idx) {\n leftBorder = true;\n text = issue.name;\n }\n else if (j == end_idx) {\n rightBorder = true\n }\n currLaneCells[j] = this._cell(text, backgroundColor, textColor, leftBorder, rightBorder,false);\n }\n lanes[issueLaneKey] = currLaneCells;\n\n\n }\n for (let k = 0; k < Object.keys(lanes).length; k++) {\n let currLaneCells = lanes[k.toString()];\n issueCells = issueCells.concat([currLaneCells]);\n // issueCells = issueCells.concat([this._generateBlankCells()])\n }\n return issueCells;\n }", "function buildCalendar() {\n var year = that.selectedYear;\n var month = that.selectedMonth;\n\n var firstDateOfMonth = getDate(year, month, 1);\n var firstDayOfMonth = firstDateOfMonth.getDay();\n var firstDayOfWeek = that.options.firstDayOfWeek;\n\n var rowIndex = 0,\n datesInWeek = 0,\n date = 1;\n\n calendarItems = [];\n that.weeks = [];\n\n // if first day of month != firstDayOfWeek then start dates from prior month\n if (firstDayOfWeek != firstDayOfMonth) {\n var daysBefore = getDaysBeforeFirstDayOfMonth(firstDayOfWeek, firstDayOfMonth);\n if (!isUndefinedOrNull(daysBefore)) {\n // 0 is one day prior; 1 is two days prior and so forth\n date = date - daysBefore;\n }\n }\n\n while (date <= getDaysInMonth(year, month)) {\n calendarItems.push(getCellData(getDate(year, month, date++)));\n }\n\n // fill remaining cells with dates from next month\n while ((calendarItems.length % 7) !== 0) {\n calendarItems.push(getCellData(getDate(year, month, date++)));\n }\n\n // populate the that.weeks array. create a 2D array of 7 days per row\n angular.forEach(calendarItems, function (cellData) {\n if ((datesInWeek % 7) === 0) {\n that.weeks.push([]);\n rowIndex = that.weeks.length - 1;\n }\n\n that.weeks[rowIndex].push(cellData);\n\n datesInWeek++;\n });\n\n //raise the callback for each cell data\n raiseRenderDateCallback(calendarItems);\n }", "function milestoneMessage() {\n // Make the message disappear when a game over happens\n if (state === \"GAMEOVER\") {\n return;\n }\n push();\n // Setting the text aesthetics\n textFont(neoFont);\n textSize(64);\n textAlign(CENTER, CENTER);\n fill(255);\n // The message displays nothing at 0 prey eaten\n if (thief.preyEaten === 0) {\n message = \"\";\n }\n // The first message\n if (thief.preyEaten === 4) { // The message will display when 5 prey are eaten\n // Setting the text to be displayed\n message = \"Good start!\";\n milestoneY = 700;\n }\n // The second message\n if (thief.preyEaten === 11) { // The message will display when 12 prey are eaten\n message = \"Doing great!\";\n milestoneY = 700;\n }\n // The third message\n if (thief.preyEaten === 20) { // The message will display when 21 prey are eaten\n message = \"Almost there!\";\n milestoneY = 700;\n }\n // Handling the universal settings for the message display\n // The messages activate as soon as the number of prey eaten reaches 5\n if (thief.preyEaten >= 5) {\n text(message, width / 2, milestoneY);\n milestoneY = milestoneY - 3;\n }\n pop();\n}", "function createIssueLabel(labelName , projName){\n return {\n labelName : labelName,\n projname : projName\n }\n}", "function projectPriorities(priorityTitle, jobsList) {\n this.priority = priorityTitle;\n this.jobs = jobsList;\n}", "function sort_pipeline() {\n $.each(dev_p.data.dev_milestones, function (key, val) {\n $.each(dev_p.data.dev_milestones[key], function (temp_ia) {\n var priority_val = 0;\n var priority_msg = '';\n\n var ia = dev_p.data.dev_milestones[key][temp_ia];\n\n if (dev_p.by_priority) {\n // Priority is higher when:\n // - last activity (especially comment) is by a contributor (non-admin)\n // - last activity happened long ago (the older the activity, the higher the priority)\n if (ia.pr && (ia.pr.status === \"open\")) {\n if (ia.last_comment) {\n priority_val += ia.last_comment.admin? -20 : 20;\n var idle_comment = elapsed_time(ia.last_comment.date);\n if (ia.last_comment.admin) {\n priority_val -= 20;\n priority_val += idle_comment;\n priority_msg += \"- 20 (last comment by admin) \\n+ elapsed time since last comment \\n\";\n } else {\n priority_val += 20;\n priority_val += (2 * idle_comment);\n priority_msg += \"+ 20 (last comment by contributor) \\n+ twice the elapsed time since last comment \\n\";\n }\n } if (ia.last_commit) {\n var idle_commit = elapsed_time(ia.last_commit.date);\n if (ia.last_comment && moment.utc(ia.last_comment.date).isBefore(ia.last_commit.date)) {\n priority_val += (1.5 * idle_commit);\n priority_msg += \"+ 1.5 times the elapsed time since last commit (made after last comment) \\n\";\n } else if ((!ia.last_comment) && (!ia.last_commit.admin)) {\n priority_val += (2 * idle_commit);\n priority_msg += \"+ twice the elapsed time since last commit (there are no comments in the PR) \\n\";\n }\n }\n\n // Priority drops if the PR is on hold\n if (ia.pr && (ia.pr.status === \"open\")) {\n var tags = ia.pr.tags;\n\n $.each(tags, function(idx) {\n var tag = tags[idx];\n if (tag.name.toLowerCase() === \"on hold\") {\n priority_val -= 100;\n priority_msg += \"- 100: the PR is on hold \\n\";\n } else if (tag.name.toLowerCase() === \"priority: high\") {\n priority_val += 20;\n priority_msg += \"+ 20: the PR is high priority \\n\";\n }\n });\n }\n\n // Priority is higher if the user has been mentioned in the last comment\n if (ia.at_mentions && ia.at_mentions.indexOf(dev_p.data.username) !== -1) {\n priority_val += 50;\n priority_msg += \"+ 50: you have been @ mentioned in the last comment \\n\";\n }\n\n // Has a PR, so it still has more priority than IAs which don't have one\n if (priority_val <= 0) {\n priority_val = 1;\n priority_msg += \"final value is 1: there's a PR, so it's higher priority than IAs without a PR \\n\";\n }\n }\n\n dev_p.data.dev_milestones[key][temp_ia].priority = priority_val;\n dev_p.data.dev_milestones[key][temp_ia].priority_msg = priority_msg;\n }\n });\n \n dev_p.data.dev_milestones[key].sort(function (l, r) {\n var a, b;\n if (dev_p.by_priority) {\n a = l.priority;\n b = r.priority;\n } else {\n a = l.last_update? - elapsed_time(l.last_update) : -100;\n b = r.last_update? - elapsed_time(r.last_update) : -100;\n }\n\n if (a > b) {\n return -1;\n } else if (b > a) {\n return 1;\n }\n \n return 0;\n });\n });\n\n dev_p.data.by_priority = dev_p.by_priority;\n var iadp = Handlebars.templates.dev_pipeline(dev_p.data);\n $(\"#dev_pipeline\").html(iadp);\n filterCounts();\n if (dev_p.data.permissions && dev_p.data.permissions.admin) {\n $(\".mentioned, .attention\").addClass(\"dog-ear\");\n }\n }", "function initIssues() {\n\t//ids start at 5 so fill in 0-4 to make retrieval bawed on array index trivial\n\tissues = [0, 0, 0, 0, 0,\n {id:5,\tname:\"Alumni\"},\n\t\t\t{id:6,\tname:\"Animals\"},\n\t\t\t{id:7,\tname:\"Children\"},\n\t\t\t{id:8,\tname:\"Disabilities\"},\n\t\t\t{id:9,\tname:\"Disasters\"},\n\t\t\t{id:10,\tname:\"Education\"},\n\t\t\t{id:11,\tname:\"Elderly\"},\n\t\t\t{id:12,\tname:\"Environment\"},\n\t\t\t{id:13,\tname:\"Female Issues\"},\n\t\t\t{id:14, name:\"Fine Arts\"},\n\t\t\t{id:15,\tname:\"General Service\"},\n\t\t\t{id:16,\tname:\"Health\"},\n\t\t\t{id:17,\tname:\"Male Issues\"},\n\t\t\t{id:18, name:\"Minority Issues\"},\n\t\t\t{id:19,\tname:\"Office\"},\n\t\t\t{id:20,\tname:\"Patriotic\"},\n\t\t\t{id:21,\tname:\"Poverty\"},\n\t\t\t{id:22,\tname:\"PR\"},\n\t\t\t{id:23,\tname:\"Recreation\"},\n\t\t\t{id:24,\tname:\"Religious\"},\n\t\t\t{id:25,\tname:\"Service Leaders\"},\n\t\t\t{id:26,\tname:\"Technology\"}\n\t\t\t];\n}", "buildTree() {\n if (!this.drawnAnnotations.length && !this.annosToBeDrawnAsInsets.size) {\n // Remove all exlisting clusters\n this.areaClusterer.cleanUp(new KeySet());\n return;\n }\n\n // if (this.newAnno) this.tree.load(this.drawnAnnotations);\n\n this.createInsets();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Agrega un Invitado a la listade invitados
function agregarInvitado(){ var tablaLength = obtenTablaLength("invitado_table"); var id = tablaLength+1; var objeto = generaObjetoInvitados(); var renglon = creaRenglonInvitados(objeto, id); agregaRenglon(renglon, "invitado_table"); }
[ "function sendInvites(json, statusText) {\n\t$(\"table.team tr:last\").after(json.members_html);\n for (i = 0; i < json.members_ids.length; i++) {\n\t\t$(\"#member_\"+ json.members_ids[i]).highlightFade({start: '#FFFF99', speed: 2000});\n\t $(\"#member_\"+ json.members_ids[i] +\" a.tip\").link_tips();\n\t};\n\t$(\"div.list-people\").after(\"<div class='invited-sent'><h3>Invites sent!</h3><p>Sent invites to \"+ json.members_names+\". Don&#39;t forget to edit their permissions on the left.</p></div>\");\t \n\tresetInviteQueue();\n\tcloseContactSelect();\n\t$(\"input[name='invites[]']\").remove();\n\tremove_this_after($(\"div.invited-sent\"), 7000);\n}", "invite(userId, invitedId) {\n // use date for sorted set ordering\n return new Promise((resolve, reject) => {\n this.client.zadd(\n `${this.namespace}:user:${invitedId}:${STATE_KEY.invited}`,\n Date.now(),\n userId,\n (err, res) => {\n if (err) { reject(err); }\n debug(`${userId} invited ${invitedId}`);\n return resolve(res);\n });\n });\n }", "function manage_inviteables( inviteable_list ){\r\n\t\t\r\n\t\t$( '#friends_to_invite div.not_invited_yet div, #friends_to_invite div.already_invited div' )\r\n\t\t\t.addClass( 'not_inviteable_del' );\r\n\t\t\r\n\t\t$.each( inviteable_list, function(i, list) {\r\n\t\t\tvar id = parseInt( list.id );\r\n\t\t\tvar name = list.name;\r\n\t\t\tvar invited = list.invited;\r\n\t\t\t\r\n\t\t\tvar act_obj = $( '#inviteable_one_'+id );\r\n\t\t\tif ( typeof act_obj != 'undefined' && act_obj.length > 0 ) {\r\n\t\t\t\tact_obj.removeClass( 'not_inviteable_del' );\r\n\t\t\t\tif ( !invited )\r\n\t\t\t\t\tif ( typeof $( 'div.already_invited div#inviteable_one_'+id ) != 'undefined' && $( 'div.already_invited div#inviteable_one_'+id ).length > 0 ) {\r\n\t\t\t\t\t\tact_obj.fadeOut( 50, function(){\r\n\t\t\t\t\t\t\tact_obj.appendTo( '#friends_to_invite div.not_invited_yet' ).fadeIn( 50 );\r\n\t\t\t\t\t\t} );\r\n\t\t\t\t\t\tact_obj.data( 'invited', false );\r\n\t\t\t\t\t}\r\n\t\t\t} else\r\n\t\t\t\t$( '<div/>' )\r\n\t\t\t\t\t.attr( 'id', 'inviteable_one_'+id )\r\n\t\t\t\t\t.appendTo( '#friends_to_invite div.not_invited_yet' )\r\n\t\t\t\t\t.html( name )\r\n\t\t\t\t\t.data( 'invited', false )\r\n\t\t\t\t\t.click( function(){\r\n\t\t\t\t\t\tvar o_this = $( this );\r\n\t\t\t\t\t\tif (!o_this.data( 'invited' )) {\r\n\t\t\t\t\t\t\to_this.fadeOut( 50, function(){\r\n\t\t\t\t\t\t\t\to_this.appendTo( '#friends_to_invite div.already_invited' ).fadeIn( 50 );\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$.ajax({\r\n\t\t\t\t\t\t\t\ttype: 'POST',\r\n\t\t\t\t\t\t\t\turl: 'send_invite.php',\r\n\t\t\t\t\t\t\t\tdata: {\r\n\t\t\t\t\t\t\t\t\t'id': id\r\n\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\tsuccess: function( data ) {\r\n\t\t\t\t\t\t\t\t\tif ( data!=0 ) {\r\n\t\t\t\t\t\t\t\t\t\t$( '#hv_alert_wrapper' ).hv_alert( 'show_alert', {\r\n\t\t\t\t\t\t\t\t\t\t\t'message': c['error_invite']+' '+data\r\n\t\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\t\to_this.fadeOut( 50 );\r\n\t\t\t\t\t\t\t\t\t} else\r\n\t\t\t\t\t\t\t\t\t\to_this.data( 'invited', true );\r\n\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\terror: function() {\r\n\t\t\t\t\t\t\t\t\t$( '#hv_alert_wrapper' ).hv_alert( 'show_alert', {\r\n\t\t\t\t\t\t\t\t\t\t'message': c['error_invite']+' '+data\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\to_this.fadeOut( 50 );\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t});\r\n\t\t$( '.not_inviteable_del' ).fadeOut( 50, function(){\r\n\t\t\t$( this ).remove();\r\n\t\t} );\r\n\t\t\r\n\t}", "function initInvitationsReceived() {\n var tmpUser, tmpGroup, tmpChannel;\n vm.invitationsReceived = angular.copy(vm.user.pendingInvitations);\n vm.invitationsReceived.forEach(function (invitation) {\n\n // Add some data about the user\n tmpUser = usersFactory.getUserByUsername(invitation.sentBy);\n invitation.givenName = tmpUser.givenName;\n invitation.surname = tmpUser.surname;\n\n // Add some data about the group\n if (invitation.tag == 'group') {\n tmpGroup = groupsFactory.getGroupById(invitation.groupId);\n invitation.groupName = tmpGroup.name;\n }\n\n // Add some data about the channel\n else if (invitation.tag == 'channel') {\n tmpGroup = groupsFactory.getGroupById(invitation.groupId);\n invitation.groupName = tmpGroup.name;\n tmpChannel = groupsFactory.getChannelById(tmpGroup.name, invitation.channelId);\n invitation.channelName = tmpChannel.name;\n }\n });\n }", "async inviteUser () {\n\t\tthis.log('NOTE: Inviting user under one-user-per-org paradigm');\n\t\tconst inviterClass = UserInviter;\n\t\tthis.userInviter = new inviterClass({\n\t\t\trequest: this,\n\t\t\tteam: this.team,\n\t\t\tdelayEmail: this._delayEmail,\n\t\t\tinviteType: this.inviteType,\n\t\t\tuser: this.user,\n\t\t\tdontSendEmail: this.dontSendEmail\n\t\t});\n\n\t\tconst userData = {\n\t\t\temail: this.request.body.email.trim()\n\t\t};\n\t\tthis.invitedUsers = await this.userInviter.inviteUsers([userData]);\n\t\tconst invitedUserData = this.invitedUsers[0];\n\t\tthis.transforms.createdUser = invitedUserData.user;\n\t}", "function obtenInvitados(tramite){\r\n\t\tvar objetoInvitados = obtenDatosInvitados(tramite);\r\n\t\tif(objetoInvitados != null){\r\n\t\t\tfor(var prop in objetoInvitados){\r\n\t\t\t\tvar partida = objetoInvitados[prop];\r\n\t\t\t\tfor(var propPar in partida)\r\n\t\t\t\t\tpartida[propPar] = (partida[propPar] == \"\" || partida[propPar] == null) ? \"N/A\" : partida[propPar];\r\n\t\t\t\t\r\n\t\t\t\tvar id = obtenTablaLength(\"invitado_table\")+1;\r\n\t\t\t\tvar\trenglon = creaRenglonInvitados(objetoInvitados[prop], id);\r\n\t\t\t\tagregaRenglon(renglon, \"invitado_table\");\r\n\t\t\t}\r\n\t\t\tasignaText(\"span_totalInvitados\", id);\r\n\t\t\tasignaVal(\"numInvitados\", id);\r\n\t\t}\r\n\t}", "function sendInvite(newfriendname) {\n\t// post to /addfriend/ where database takes care of sending invite\n\t\n\t\n\t$(\" <div />\" ).attr(\"id\",'confirm_invitation')\n\t.attr(\"title\", 'Confirm Invitation')\n\t.html(\n\t\t'<div id=\"myconfirmationinvitation\">' + \n\t\t'<table width=100%> <tr style=\"text-align: center;\"><td colspan=\"2\" style=\"height: 50px;\">' +\n\t\t'Do you want to send an invitation email? </td></tr>' +\n\t\t'<tr style=\"text-align: center;\">' +\n\t\t'<td style=\"width: 100px;\"> <a id=\"sendInvitebutton\" class=\"btn btn-success\" style=\"width: 60px;\"> <i class=\"icon-ok icon-white\"></i></a> </td>' +\n\t\t'<td style=\"width: 100px\"> <a id=\"nosendInvitebutton\" class=\"btn btn-danger\" style=\"width: 60px;\"> <i class=\"icon-remove icon-white\"></i></a></td> ' +\n\t\t'</tr></table></div>'\n\t\t\n\t)\n\t.appendTo($( \"#boxes\" ));\n\n\t$('#sendInvitebutton').click(\n\t\tfunction() {\n\t\t\tinvite(newfriendname);\n\t\t\t$('#confirm_invitation').dialog('destroy').remove()\n\t\t}\n\t);\n\t$('#nosendInvitebutton').click(\n\t\tfunction() {\n\t\t\t$('#confirm_invitation').dialog('destroy').remove()\n\t\t}\n\t);\n\t\n\t$('#confirm_invitation').dialog( {\n autoOpen: true,\n modal: true\n });\n}", "updatePendingInvites(userInvites){\n for(let i of userInvites){\n if(!this.session.settings.invites.hasOwnProperty(i)){\n this.session.settings.invites[i] = {}\n }\n }\n for (let i of Object.keys(this.session.settings.invites)){\n if(!userInvites.includes(i)){\n delete this.session.settings.invites[i];\n }\n }\n\n this.saveClientSettings(this.session.settings, this.session.privateKey);\n }", "async invite(channelId, users) {\n try {\n const res = await this.client.conversations.invite({\n channel: channelId,\n users,\n });\n } catch (err) {\n console.error(err);\n }\n }", "requestInvite(){\n let ic = new iCrypto()\n ic.createNonce(\"n\")\n .bytesToHex(\"n\", \"nhex\");\n let request = new Message(self.version);\n let myNickNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.nickname,\n this.session.metadata.topicAuthority.publicKey);\n let topicNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.topicName,\n this.session.metadata.topicAuthority.publicKey);\n request.headers.command = \"request_invite\";\n request.headers.pkfpSource = this.session.publicKeyFingerprint;\n request.headers.pkfpDest = this.session.metadata.topicAuthority.pkfp;\n request.body.nickname = myNickNameEncrypted;\n request.body.topicName = topicNameEncrypted;\n request.signMessage(this.session.privateKey);\n this.chatSocket.emit(\"request\", request);\n }", "function generaObjetoInvitados(){\r\n\t\tvar contexto = $(\"#invitados_table\");\r\n\t\t\r\n\t\tvar objetoFormulario = {\r\n\t\t\t\"nombreInvitado\": \t$(\"#nombre\", contexto).val(),\r\n\t\t\t\"puestoInvitado\": \t$(\"#puesto\", contexto).val(),\r\n\t\t\t\"empresaInvitado\": \t$(\"#empresaInvitado\", contexto).val(),\r\n\t\t\t\"tipoInvitado\": \t$(\"#tipoInvitado\", contexto).val()\r\n\t\t}\r\n\t\t\r\n\t\tfor(var prop in objetoFormulario)\r\n\t\t\tobjetoFormulario[prop] = (objetoFormulario[prop] == \"\" || objetoFormulario[prop] == null) ? \"N/A\" : objetoFormulario[prop];\r\n\t\t\r\n\t\treturn objetoFormulario;\r\n\t}", "function addFriend(id) {\n invitedArr.push(id);\n var ufriends = JSON.parse(window.localStorage.getItem(\"uFriends\"));\n for (var i = 0; i < ufriends.length; i++) {\n if (ufriends[i].id == id) {\n $('#friendTags').addTag(ufriends[i].name);\n }\n }\n}", "function dibujarInvaders() {\n for (let i = 0; i < alienInvaders.length; i++) {\n if(!invadersEliminados.includes(i)) {\n cuadrados[alienInvaders[i]].classList.add('invader')\n }\n }\n}", "addEmailToRecipientList(name, email){\n $('.email-to-list ul').append(`<li class=\"email-btn email-to\">\n <span class=\"email-recipient\" title=\"${email}\">${name}</span>\n <span class=\"email-close\"><i class=\"fas fa-times-circle\"></i></span>\n </li>`);\n $('.email-to-list .recipient-count').html($('.email-to-list ul li').length);\n }", "static async inviteUsers(company_id, user_emails) {\n\t\t// find company\n\t\tlet company = await models.Company.findByPk(company_id)\n\t\t// generate random hash\n\t\tlet hash = generator.getRandomString(40)\n\t\t// save hash to db\n\t\tawait models.InviteHash.create({ hash, company_id })\n\n\t\t// send email\n\t\tconst mg = mailgun({ apiKey: 'key-f25a884c247378aa8dd34083fe6e4b28', domain: 'sandbox454409b9d64449f7b661a00c48d6a721.mailgun.org' })\n\t\tconst data = {\n\t\t\tfrom: '<me@samples.mailgun.org>',\n\t\t\tto: user_emails,\n\t\t\tsubject: 'Hello',\n\t\t\ttext: `Dear user you have been invited in ${company.name} <a href=\"http://localhost:3000/company/join/${hash}/\">Join company by hash: ${hash}</a>`\n\t\t}\n\t\tmg.messages().send(data, function(error, body) {\n\t\t\tconsole.log(body)\n\t\t})\n\n\t\treturn true\n\n\t\t// // Generate test SMTP service account from ethereal.email\n\t\t// let testAccount = await nodemailer.createTestAccount()\n\t\t// // create reusable transporter object using the default SMTP transport\n\t\t// let transporter = nodemailer.createTransport({\n\t\t// \thost: 'smtp.ethereal.email',\n\t\t// \tport: 587,\n\t\t// \tsecure: false, // true for 465, false for other ports\n\t\t// \tauth: {\n\t\t// \t\tuser: testAccount.user, // generated ethereal user\n\t\t// \t\tpass: testAccount.pass // generated ethereal password\n\t\t// \t}\n\t\t// })\n\n\t\t// send mail with defined transport object\n\t\t// let info = await transporter.sendMail({\n\t\t// \tfrom: '\"Fred Foo 👻\" <foo@example.com>', // sender address\n\t\t// \tto: user_emails, // list of receivers\n\t\t// \tsubject: `Invitation from ${company.name}`, // Subject line\n\t\t// \ttext: `Dear user you have been invited in ${company.name}`, // plain text body\n\t\t// \thtml: `<a href=\"http://localhost:3000/company/join/${hash}/\">Join company by hash: ${hash}</a>` // html body\n\t\t// })\n\n\t\t// return nodemailer.getTestMessageUrl(info)\n\t}", "function addToInventory() {\n\tconnection.query('SELECT * FROM products', function(err,res) {\n\t\tif(err) throw err;\n\t\tconsole.log(res);\n\t\tinquirer.prompt([\n\t\t\t{\n\t\t\t\ttype: 'input',\n\t\t\t\tmessage: 'enter the Item Id you would like to add more to.',\n\t\t\t\tname: 'addInvId'\n\t\t\t}\n\t\t]).then(function(inquireResponse) {\n\t\t\t\n\t\t\tvar id = inquireResponse.addInvId;\n\t\t\tidValidCheck(id);\n\n\t\t});\n\n\t});\n\t\n}", "function inviteMember(current_user, invite_user, list_id) {\n if(confirmInvite(invite_user)) {\n\tif(list_id) {\n\t var result = null;\n\t var xmlhttp = null;\n\t if (window.XMLHttpRequest) {\n\t\txmlhttp=new XMLHttpRequest();\n\t } else {\n\t\txmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t }\n\t \n\t xmlhttp.onreadystatechange=function() {\n\t\tif (xmlhttp.readyState==4 && xmlhttp.status==200) {\n\t\t result = xmlhttp.responseText;\n\t\t}\n\t }\n\t \n\t var param1 = \"inv=\".concat(invite_user);\n\t var param2 = \"&i=\".concat(list_id); \n\t var params = param1.concat(param2);\n\t xmlhttp.open(\"POST\", \"resources/invite-member.php\", true);\n\t xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\t xmlhttp.send(params);\n\t} else {\n\t //TODO \n\t //: if(targetListId) fails\n\t}\n\tdocument.getElementById('inviteMemberTextField').value='';\n } else {\n\t//DO SOMETHING\n\t//:if(confirmInvite(inviteUser) fails\n }\n}", "list(_, since) {\n let found = false;\n console.log(`${rpad('invoice:', 31)} ${rpad('amount:', 7)} ${rpad('status:', 15)} ${rpad('conf:', 10)} pending:`);\n API.iterInvoices(\n since,\n (invoice, state, callback) => {\n found = true;\n console.log(`${rpad(''+invoice._id, 31)} \\\n${rpad(utils.btcFromSatoshi(invoice.amount), 7)} \\\n${rpad(state.updated || invoice.status, 15)} \\\n${rpad(utils.btcFromSatoshi(state.finalAmount) + ' BTC', 10)} \\\n${utils.btcFromSatoshi(state.pendingAmount)} BTC`[invoice.status === 'paid' ? 'green' : 'red']);\n callback();\n },\n () => {\n if (!found) console.log(' - no invoices found -'.yellow);\n CLI.doneCallback();\n }\n );\n }", "function sendGroupJoinRequests() {\n vm.usersToInvite.forEach(user => {\n massRequest.push({ group_id: vm.group.id, receiver_id: user.id});\n });\n const massRequestObj = {\n mass_requests: massRequest\n };\n Request\n .sendMassRequest(massRequestObj)\n .$promise\n .then(data => {\n $uibModalInstance.close('Requests sent');\n })\n .catch(err => {\n console.log('Something went wrong with the mass request');\n console.log('Error:', err);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts an array of errors and returns the first error message.
function firstMessage(errors) { if (!Array.isArray(errors) || errors.length === 0) return null; var error = errors[0]; if (error.message) { return error.message; } else { return error; } }
[ "function MultiError(errors)\n\t{\n\t\tmod_assertplus.array(errors, 'list of errors');\n\t\tmod_assertplus.ok(errors.length > 0, 'must be at least one error');\n\t\tthis.ase_errors = errors;\n\t\n\t\tVError.call(this, {\n\t\t 'cause': errors[0]\n\t\t}, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's');\n\t}", "function getCommentCreateError(errors) {\n if (errors.content) {\n return \"Content: \" + errors.content[0];\n }\n\n if (errors.event_id) {\n return \"Event: \" + errors.event_id[0];\n }\n\n if (errors.user_id) {\n return \"User: \" + errors.user_id[0];\n }\n}", "getErrorsAsString() {\n\t\tif (!this.items || !this.items.error || this.items.error.length <= 0) {\n\t\t\treturn \"\";\n\t\t}\n\t\tconst str = this.items.error.join(\". \");\n\t\treturn str;\n\t}", "errors() {\n return ys(this.rawErrors, (e) => e.join(`\n`));\n }", "_validateMultiResults (results, callback) {\n const errors = results.map(result => result[0])\n\n if (errors.some(error => !!error)) {\n callback(new Error(`${compact(errors)}`))\n } else {\n callback()\n }\n }", "function getErrorMessage(errorCode) {\n var Error = {};\n Error[errorCode] = 'Please try again';\n Error[errorCode] = 'Please try again';\n Error[errorCode] = 'Database version Error';\n Error[errorCode] = 'Data too large Error';\n Error[errorCode] = 'Data quota Error';\n Error[errorCode] = 'Syntax Error';\n Error[errorCode] = 'User name is already present in the database';\n Error[errorCode] = 'Timeout Error';\n return Error[errorCode];\n }", "function listErrors() {\n\treturn Object.keys(errorCodeMap);\n}", "findErrorMessage(errorCode) {\n return this.errorMessageCollection[this.languageCode][errorCode];\n }", "function checkError(errorCode) {\n switch(errorCode) {\n case 0:\n return 'Geen watertoevoer';\n case 1:\n return 'Temperatuur te laag';\n case 2:\n return 'Koffiebonen op';\n case 3:\n return 'Afvalbak vol';\n case 4:\n return 'Geen druk';\n default:\n return 'Onbekende foutcode';\n }\n}", "function widgetChangeErrors(errors) {\n\t\t\treturn shiftArrayErrorsKeys(errors, {\n\t\t\t\tarrayKey: schema.key,\n\t\t\t\tminIndex: indexToRemove,\n\t\t\t\tshouldRemoveIndex: index => index === indexToRemove,\n\t\t\t\tgetNextIndex: index => index - 1,\n\t\t\t});\n\t\t}", "function getErrorMessage(errorId) {\n switch (errorId) {\n case ID_ERR_VERSIONE:\n if (BAN_EXPM_VERSION) {\n return \"L'estensione richiede come versione minima Banana Contabilità Plus \" + BAN_VERSION + \".\" + BAN_EXPM_VERSION;\n }\n else {\n return \"L'estensione richiede come versione minima Banana Contabilità Plus \" + BAN_VERSION;\n }\n case ID_ERR_GRUPPO_ERRATO:\n return \"colonna <%GRCOLUMN>, valore <%GR> Codice gruppo inserito errato. Modificare il codice gruppo nella tabella Conti.\";\n\n case ID_ERR_GRUPPO_ERRATO_CATEGORIA:\n return \"colonna <%GRCOLUMN>, valore <%GR> Codice gruppo inserito errato. Modificare il codice gruppo nella tabella Categorie.\"; \n \n case ID_ERR_LICENZA_ADVANCED:\n return \"L'estensione richiede il piano Advanced.\";\n\n case ID_ERR_LICENZA_PROFESSIONAL:\n return \"L'estensione richiede il piano Professional.\";\n\n case ID_ERR_ERRORE_QUADRATURA:\n return \"La somma della liquidità iniziale + avanzo/disavanzo non è uguale alla liquidità finale. Importo differenza = \";\n\n case ID_ERR_SALDO_APERTURA_SENZA_PRECEDENTE:\n return \"Saldo colonna Precedente mancante. Il saldo della colonna Apertura deve essere riportato nella colonna Precedente.\";\n\n case ID_ERR_SALDI_APERTURA_PRECEDENTE_DIFFERENTI:\n return \"I saldi delle colonne Apertura e Precedente sono differenti. Modificare i saldi in modo che siano uguali.\";\n\n case ID_ERR_REGISTRAZIONE_NON_CORRETTA:\n return \"Per il Rendiconto di Cassa sono ammesse solo registrazioni con conti della liquidità (Banca e Cassa).\";\n\n case ID_ERR_ACCANTONAMENTO_5XMILLE:\n return \"L'accantonamento registrato è maggiore della differenza 'Importo percepito - Totale spese gruppi 1,2,3,4'\";\n\n case ID_ERR_CODICI_GR1_5XMILLE:\n return \"Il codice %CODEGR1 è stato inserito in più gruppi: %GROUPS. Nelle impostazioni ogni codice deve essere presente in un solo gruppo.\";\n }\n return \"\";\n}", "function transformErrors(selector){\r\n\t\r\n\tvar errors = $(selector);\r\n\r\n\t$(errors).each(function() {\r\n\t\t\r\n\t\tvar prev_el = $(this).prev();\r\n\t\tvar content = [];\r\n\t\t\r\n\t\t$(this).find('li').each(function() {\r\n\t\t\tcontent.push($(this).html());\r\n\t\t })\r\n\t\t\r\n\t\t\t$(prev_el).popover({\r\n\t\t\t\t offset: 10,\r\n\t\t\t placement : 'top',\r\n\t\t\t html: 'true',\r\n\t\t\t content : function(){\r\n\t\t\t \t return getErrorHtml(content);\r\n\t\t\t }\r\n\t\t\t}).popover('show');\r\n\t});\r\n\t\r\n\treturn;\r\n\r\n}", "nextControlErrorKey(name) {\r\n const control = this.get(name);\r\n if (control && control.errors) {\r\n // try client side keys first for correct order\r\n let error = this.registeredValidatorsMap[name] &&\r\n this.registeredValidatorsMap[name].find(validatorKey => control.hasError(validatorKey));\r\n if (!error) {\r\n // fallback to all errors including custom errors set after backend calls\r\n error = Object.keys(control.errors).shift();\r\n }\r\n if (error) {\r\n return error;\r\n }\r\n }\r\n return '';\r\n }", "function transformAjvErrors() {\n\t var errors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n\n\t if (errors === null) {\n\t return [];\n\t }\n\n\t return errors.map(function (e) {\n\t var dataPath = e.dataPath,\n\t keyword = e.keyword,\n\t message = e.message,\n\t params = e.params;\n\n\t var property = \"\" + dataPath;\n\n\t // put data in expected format\n\t return {\n\t name: keyword,\n\t property: property,\n\t message: message,\n\t params: params, // specific to ajv\n\t stack: (property + \" \" + message).trim()\n\t };\n\t });\n\t}", "function bluesnapGetErrorText(errorCode) {\n switch (errorCode) {\n case '001':\n return Drupal.t('Please enter a valid card number.');\n\n case '002':\n return Drupal.t('Please enter a valid CVV/CVC number.');\n\n case '003':\n return Drupal.t('Please enter a valid expiration date.');\n\n case '22013':\n return Drupal.t('The card type is not supported by the merchant.');\n\n case '400':\n return Drupal.t('Session expired. Please refresh the page to continue.');\n\n case '403':\n case '404':\n case '500':\n return Drupal.t('Internal server error. Please try again later.');\n\n default:\n break;\n }\n }", "function printValidationErrors(errors, print) {\n if (print === void 0) { print = console_1.error; }\n print.group(\"Error\" + (errors.length === 1 ? '' : 's') + \":\");\n errors.forEach(function (line) { return print(line); });\n print.groupEnd();\n print();\n print('The expected format for a commit is: ');\n print('<type>(<scope>): <summary>');\n print();\n print('<body>');\n print();\n print(\"BREAKING CHANGE: <breaking change summary>\");\n print();\n print(\"<breaking change description>\");\n print();\n print();\n }", "function mse(errors) {\n let sum = 0;\n for (let errorIdx = 0; errorIdx < errors.length; ++errorIdx) {\n sum += Math.pow(errors[errorIdx], 2);\n }\n return sum / errors.length;\n }", "function createSimpleModelError(instance, propertyId, messageFormat, argList) {\r\n\tvar modelMessage = newModelMessage(IStatus.ERROR, \r\n\t\t\tformatString(messageFormat, argList), \r\n\t\t\tinstance, propertyId, null);\r\n\treturn modelMessage;\r\n}", "function filterExpected(bazelOpts, diagnostics, formatFn) {\n if (formatFn === void 0) { formatFn = uglyFormat; }\n if (!bazelOpts.expectedDiagnostics.length)\n return diagnostics;\n // The regex contains two parts:\n // 1. Optional position: '\\(5,1\\)'\n // 2. Required TS error: 'TS2000: message text.'\n // Need triple escapes because the expected diagnostics that we're matching\n // here are regexes, too.\n var ERROR_RE = /^(?:\\\\\\((\\d*),(\\d*)\\\\\\).*)?TS(\\d+):(.*)/;\n var incorrectErrors = bazelOpts.expectedDiagnostics.filter(function (e) { return !e.match(ERROR_RE); });\n if (incorrectErrors.length) {\n var msg = \"Expected errors must match regex \" + ERROR_RE + \"\\n\\t\" +\n (\"expected errors are \\\"\" + incorrectErrors.join(', ') + \"\\\"\");\n return [{\n file: undefined,\n start: 0,\n length: 0,\n messageText: msg,\n category: ts.DiagnosticCategory.Error,\n code: 0,\n }];\n }\n var expectedDiags = bazelOpts.expectedDiagnostics.map(function (expected) {\n var m = expected.match(/^(?:\\\\\\((\\d*),(\\d*)\\\\\\).*)?TS(\\d+):(.*)$/);\n if (!m) {\n throw new Error('Incorrect expected error, did you forget character escapes in ' +\n expected);\n }\n var _a = __read(m, 5), lineStr = _a[1], columnStr = _a[2], codeStr = _a[3], regexp = _a[4];\n var _b = __read([lineStr, columnStr, codeStr].map(function (str) {\n var i = Number(str);\n if (Number.isNaN(i)) {\n return 0;\n }\n return i;\n }), 3), line = _b[0], column = _b[1], code = _b[2];\n return {\n line: line,\n column: column,\n expected: expected,\n code: code,\n regexp: new RegExp(regexp),\n matched: false,\n };\n });\n var unmatchedDiags = diagnostics.filter(function (diag) {\n var _a, e_1, _b;\n var line = -1;\n var character = -1;\n if (diag.file && diag.start) {\n (_a = ts.getLineAndCharacterOfPosition(diag.file, diag.start), line = _a.line, character = _a.character);\n }\n var matched = false;\n var msg = formatFn(bazelOpts.target, [diag]);\n // checkDiagMatchesExpected checks if the expected diagnostics matches the\n // actual diagnostics.\n var checkDiagMatchesExpected = function (expDiag, diag) {\n if (expDiag.code !== diag.code || msg.search(expDiag.regexp) === -1) {\n return false;\n }\n // line and column are optional fields, only check them if they\n // are explicitly specified.\n // line and character are zero based.\n if (expDiag.line !== 0 && expDiag.line !== line + 1) {\n return false;\n }\n if (expDiag.column !== 0 && expDiag.column !== character + 1) {\n return false;\n }\n return true;\n };\n try {\n for (var expectedDiags_1 = __values(expectedDiags), expectedDiags_1_1 = expectedDiags_1.next(); !expectedDiags_1_1.done; expectedDiags_1_1 = expectedDiags_1.next()) {\n var expDiag = expectedDiags_1_1.value;\n if (checkDiagMatchesExpected(expDiag, diag)) {\n expDiag.matched = true;\n matched = true;\n // continue, one diagnostic may match multiple expected errors.\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (expectedDiags_1_1 && !expectedDiags_1_1.done && (_b = expectedDiags_1.return)) _b.call(expectedDiags_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return !matched;\n });\n var unmatchedErrors = expectedDiags.filter(function (err) { return !err.matched; }).map(function (err) {\n var file = ts.createSourceFile(bazelOpts.target, '/* fake source as marker */', ts.ScriptTarget.Latest);\n var messageText = \"Expected a compilation error matching \" + JSON.stringify(err.expected);\n return {\n file: file,\n start: 0,\n length: 0,\n messageText: messageText,\n category: ts.DiagnosticCategory.Error,\n code: err.code,\n };\n });\n return unmatchedDiags.concat(unmatchedErrors);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
leftPad by timrwood LeftPad created to added leading zeros to pinCode if needed
function leftPad(pinCode, targetLength) { var count = pinCode.length; var output = pinCode; while (count < targetLength) { output = '0' + output; count++; } return output; }
[ "function padPartial(iotaAreaCode) {\r\n let padded = iotaAreaCode;\r\n if (padded.length < 8) {\r\n padded = padded + \"A\".repeat(8 - padded.length);\r\n }\r\n if (padded.length < 9) {\r\n padded = `${padded}9`;\r\n }\r\n return padded;\r\n}", "function zeroPad(val, width) {\n width = width || 2;\n while (String(val).length < 2) {\n val = '0' + String(val);\n }\n return val;\n }", "set NumberPad(value) {}", "get NumberPad() {}", "function leftPadWithWrapping(input, pad, colsAvail)\n{\n // safety-inits, and check for edge cases\n if(pad==null) pad = '';\n if(input==null)\n input = '';\n else\n input = trim(input);\n\n // if colsAvail not longer than pad, we will never get through input.\n // input just gets truncated in this case and we return one line of pad\n if( colsAvail <= pad.length )\n return pad.substring(0,colsAvail);\n\n\n var newlen = pad.length+input.length; // len after padding\n if( newlen <= colsAvail ) { // we need not wrap\n return pad+input;\n }\n else{ // we must wrap\n var i = input.length- (newlen-colsAvail);\n return (pad+input.substring(0,i)) + '\\n' + leftPadWithWrapping(input.substring(i), pad, colsAvail);\n }\n}", "function pad(input, length, padWith)\n{\n var blank = \"\";\n for (var i=0; i<length; i++)\n {\n blank += String(padWith);\n }\n return (blank + String(input)).slice(length * -1);\n}", "function leftPad(string, length, fillCharacter) {\n var newString = \"\";\n if (string.length < length) {\n for (let i = 0; i < (length - string.length); i++) {\n newString += fillCharacter\n }\n return newString + string;\n } else {\n return string\n }\n}", "static pad(x, length, padding, before) {\n while (x.length < length) {\n before ? x = padding + x : x = x + padding;\n }\n return x;\n }", "set PhonePad(value) {}", "function padAmount(lead, amount){\n\t\n\t\tvar pad = \"\"; // no padding\n\t\tvar padamount = lead;\n\t\t\n\t\tswitch(true){\n\t\t\t\n\t\tcase amount > 99999:\n\t\t\tpadamount -= 4;\n\t\t\tbreak;\n\t\t\t\n\t\tcase amount > 9999:\n\t\t\tpadamount -= 3;\n\t\t\tbreak;\n\t\t\t\n\t\tcase amount > 999:\n\t\t\tpadamount -= 2;\n\t\t\tbreak;\n\t\t\t\n\t\tcase amount > 99:\n\t\t\tpadamount -= 1\n\t\t\tbreak;\n\t\t\t\n\t\tcase amount > 9:\n\t\t\tbreak;\n\t\t\t\n\t\tcase amount > 0:\n\t\t\tpadamount += 1;\n\t\t\tbreak;\t\t\t\t\n\t\t\n\t\tcase amount < -99999:\n\t\t\tpadamount -= 5;\n\t\t\tbreak;\n\t\t\t\n\t\tcase amount < -9999:\n\t\t\tpadamount -=4;\n\t\t\tbreak;\n\t\t\t\n\t\tcase amount < -999:\n\t\t\tpadamount -= 3;\n\t\t\tbreak;\n\t\t\t\n\t\tcase amount < -99:\n\t\t\tpadamount -= 2;\n\t\t\tbreak;\n\t\t\t\n\t\tcase amount < -9:\n\t\t\tpadamount -= 1;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tfor(var i = 0; i < padamount; i++){\n\t\t\tpad += \" \";\n\t\t}\n\t\t\n\t\treturn pad;\t\n\t}", "function pad_zero(month_or_day) {\n if (month_or_day < 10) {\n return \"0\" + month_or_day;\n } else {\n return month_or_day;\n }\n}", "function updateKeypadScreen() {\n\tvar l = pin.length;\n\tif (l <= 0) {\n\t\t// Stringa vuota\n\t\tkeypadScreen.textContent = \"PIN\";\n\t} else {\n\t\tvar i, s = \"\";\n\t\tfor (i = 0; i < l; i++) {\n\t\t\ts += \"*\";\n\t\t}\n\t\tkeypadScreen.textContent = s;\n\t}\n}", "function addZerosRight(number) {\n return number.padEnd(8, \"0\");\n}", "function padToEven(a){return a.length%2?\"0\"+a:a;}", "getID() {\r\n return this.id.toString().padStart(3, '0');\r\n }", "function leftCircularShift(num,bits){\nnum = num.toString(2);\nnum = parseInt(num.substr(1,num.length-1)+num.substr(0,1),2);\nnum = parseInt(num,2);\nreturn num;\n}", "function rotateLeft8Bit(value, n) {\n return ((value << n) | (value >> (8 - n))) & 0xFF;\n}", "static padNumber(x, length, first = length) {\n return this.pad(x + '', length, '0', true).substring(0, first);\n }", "function pad (str) {\n \"use strict\";\n var max = 0;\n\n for (var i = 0, l = levels.length; i < l; i++)\n max = Math.max(max, levels[i].length);\n\n if (str.length < max)\n return str + new Array(max - str.length + 1).join(' ');\n\n return str;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For internal use. Encode the blob in format specified
_encodeBlob(blob = iCrypto.pRequired("_encodeBlob"), encoding = iCrypto.pRequired("_encodeBlob")){ let self = this; if (!this.encoders.hasOwnProperty(encoding)){ throw "_encodeBlob: Invalid encoding: " + encoding; } return self.encoders[encoding](blob) }
[ "encodeData(type, value) {\n return this.getEncoder(type)(value);\n }", "function Blob(repository, obj) {\n this.repository = repository;\n _immutable(this, obj).set(\"id\").set(\"data\");\n }", "writeTree(tree) {\n const treeObject = `${Object.keys(tree).map((key) => {\n if (Util.isString(tree[key])) {\n return `blob ${tree[key]} ${key}`;\n }\n return `tree ${Objects.writeTree(tree[key])} ${key}`;\n }).join('\\n')}\\n`;\n\n return Objects.write(treeObject);\n }", "function encodeStorablePoint(p) {\n const bits = p.toBits();\n return sjcl.codec.base64.fromBits(bits);\n}", "function annotationBlob() {\n return new Blob([JSON.stringify(annotationData())], {\n type: \"application/json\",\n });\n }", "function encodeExtensionObject(object, stream) {\n\n if (!object) {\n ec.encodeNodeId(ec.makeNodeId(0), stream);\n stream.writeUInt8(0x00); // no body is encoded\n stream.writeUInt32(0);\n } else {\n ec.encodeNodeId(object.encodingDefaultBinary, stream);\n stream.writeUInt8(0x01); // 0x01 The body is encoded as a ByteString.\n stream.writeUInt32(object.binaryStoreSize());\n object.encode(stream);\n }\n}", "_encodeObject(object) {\n switch (object.termType) {\n case 'Quad':\n return this._encodeQuad(object);\n\n case 'Literal':\n return this._encodeLiteral(object);\n\n default:\n return this._encodeIriOrBlank(object);\n }\n }", "encodeAsGLB(options = {}) {\n // TODO - avoid double array buffer creation\n this._packBinaryChunk();\n\n if (options.magic) {\n console.warn('Custom glTF magic number no longer supported'); // eslint-disable-line\n }\n\n const glb = {\n version: 2,\n json: this.json,\n binary: this.arrayBuffer\n };\n\n // Calculate length and allocate buffer\n const byteLength = encodeGLBSync(glb, null, 0, options);\n const glbArrayBuffer = new ArrayBuffer(byteLength);\n\n // Encode into buffer\n const dataView = new DataView(glbArrayBuffer);\n encodeGLBSync(glb, dataView, 0, options);\n\n return glbArrayBuffer;\n }", "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}", "static saveBlob(blob, fileName)\n {\n var a = document.createElement(\"a\");\n document.body.appendChild(a);\n a.style = \"display: none\";\n \n var url = window.URL.createObjectURL(blob);\n a.href = url;\n a.download = fileName;\n a.click();\n window.URL.revokeObjectURL(url);\n }", "function encode_packet( packet ) {\n var encoded = to_bytes( packet.id );\n encoded += String.fromCodePoint( packet.flags ).toBytes();\n encoded += String.fromCodePoint( packet.codes ).toBytes();\n encoded += to_bytes( packet.qd ); // Questions\n encoded += to_bytes( packet.answers.length ); // Answers\n encoded += to_bytes( packet.authority.length ); // Authority\n encoded += to_bytes( packet.additional.length ); // Additional\n encoded += encode_question(packet);\n packet.answers.forEach( function(answer) {\n encoded += gen_resource_record(packet, answer.name, answer.type, answer.class, answer.ttl, answer.rdata);\n });\n packet.authority.forEach( function(rec) {\n encoded += gen_resource_record(packet, rec.name, rec.type, rec.class, rec.ttl, rec.rdata);\n });\n packet.additional.forEach( function(rec) {\n encoded += gen_resource_record(packet, rec.name, rec.type, rec.class, rec.ttl, rec.rdata);\n });\n return encoded;\n}", "function buildExportBlobUrl(data, name, fileEnding) {\r\n\t\tvar type = {type: 'text/plain'};\r\n var bb = null;\r\n if (window.Blob == null) {\r\n console.log('no blob');\r\n return;\r\n }\t\t\r\n try {\r\n bb = new Blob([data], type);\r\n } catch (e) {\r\n bb = new BlobBuilder();\r\n bb.append(data);\r\n bb = bb.getBlob(\"text/plain\");\r\n };\r\n\t\tvar element = document.createElement('a');\r\n\t\telement.href = fileEnding == 'json' ? window.URL.createObjectURL( bb ) : data;\r\n\t\telement.appendChild(document.createTextNode( name ));\r\n element.className = 'exportA';\r\n\t\telement.setAttribute('download', name+'.'+fileEnding);\r\n\t\telement.setAttribute('title', name+'.'+fileEnding);\r\n\t\treturn element;\r\n\t}", "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 }", "function encodeUint8(num) {\n if (num > 255) {\n throw new Error(\"overflow\");\n }\n var encoded = new Uint8Array(8);\n encoded[0] = num;\n return encoded;\n}", "toBase64() {\n return this._byteString.toBase64();\n }", "writeValue(buffer, value) {\n assert.isBuffer(buffer);\n const convertedValue = str_to_num_1.default(value);\n if (convertedValue !== undefined)\n value = convertedValue;\n assert.instanceOf(value, Number);\n const byteBuffer = new ArrayBuffer(4);\n new DataView(byteBuffer).setFloat32(0, value);\n buffer.addAll(byteBuffer);\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}", "function data_enc( string ) {\n\n //ZIH - works, seems to be the fastest, and doesn't bloat too bad\n return 'utf8,' + string\n .replace( /%/g, '%25' )\n .replace( /&/g, '%26' )\n .replace( /#/g, '%23' )\n //.replace( /\"/g, '%22' )\n .replace( /'/g, '%27' );\n\n //ZIH - works, but it's bloaty\n //return 'utf8,' + encodeURIComponent( string );\n\n //ZIH - works, but it's laggy\n //return 'base64,' + window.btoa( string );\n}", "function sha256_encode_bytes() {\n var j = 0;\n var output = new Array(32);\n for (var i = 0; i < 8; i++) {\n output[j++] = ((ihash[i] >>> 24) & 0xff);\n output[j++] = ((ihash[i] >>> 16) & 0xff);\n output[j++] = ((ihash[i] >>> 8) & 0xff);\n output[j++] = (ihash[i] & 0xff);\n }\n return output;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the recommended portion of food for each dog and add it to the dogs property
function calcRecommendedFood(dogsArr) { dogsArr.forEach(function (dog) { dog.recommendedFood = (dog.weight ** 0.75 * 28).toFixed(2); }); }
[ "totalFood() {\n return this.passengers.reduce((accumulator, passenger) => accumulator + passenger.food, 0)\n \n }", "function calculateFoodData(preferences, restrictions, guestCount) {\n prefPercentage = [];\n var occurences = findOccurences(preferences);\n var uniqueRestrictions = restrictions.getUnique();\n for (var i = 0; i < occurences[0].length; i++) {\n var prefObj = {};\n prefObj.name = occurences[0][i];\n prefObj.pc = (occurences[1][i] / guestCount) * 100;\n prefPercentage.push(prefObj);\n }\n\n for (var i = 0; i < prefPercentage.length; i++) {\n $('#prefacc').append(\"<li>\" + prefPercentage[i].name + \" ------> \" + prefPercentage[i].pc + \" %</li>\");\n }\n\n for (var j = 0; j < uniqueRestrictions.length; j++) {\n $('#foodresacc').append(\"<li> \" + uniqueRestrictions[j] + \"</li>\");\n }\n}", "calcBeliefs() {\n var _this = this;\n var data = this.data;\n\n // Loop through all CATEGORIES\n $.each(data.categories, function(index, category) {\n if (_this.debug) console.log(\"\\nCALC Beliefs - Category: \" + category.name + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n\n var belief_array = [];\n // Loop for each ALTERNATIVE, calculate belief and push to belief_array\n $.each(data.alternatives, function(indexAlt, alternative) {\n var belief_result = category.Malt[indexAlt] / (1 - category.MlH);\n belief_array.push(belief_result);\n });\n category.Beliefs = belief_array;\n if (_this.debug) console.log(\">> category.Beliefs: \" + category.Beliefs);\n });\n }", "function calculateAll(hotel, guests) {\n if (guests.nights > 1) {\n hotel.price.discounted = (hotel.price.discounted/guests.nights);\n hotel.price.actual = (hotel.price.actual/guests.nights);\n }\n hotel.price.showDiscount = Calculate.calculateDiscount(hotel.price.actual, hotel.price.discounted);\n }", "calcAggregatedBeliefs() {\n if (this.debug) console.log(\"\\nCALC Aggregated Beliefs - PROJECT - >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n var _this = this;\n var data = this.data;\n\n var belief_array = [];\n\n // Loop for each ALTERNATIVE to capture criteria data\n $.each(data.alternatives, function(index, alternative) {\n\n var belief_result = (data.Malt[index] / (1 - data.MlH));\n belief_array.push(belief_result);\n });\n data.Beliefs = belief_array;\n if (this.debug) console.log(\"data.Beliefs: \" + data.Beliefs);\n }", "getFoodBetween(cal1,cal2){\n let temp = [];\n let total = 0;\n for(var i = 0; i< this.foodLog.length; i++){\n if(this.foodLog[i].calories >= cal1 && this.foodLog[i].calories <= cal2){\n temp.push(this.foodLog[i]);\n total += this.foodLog[i].calories;\n }\n }\n return {foods: temp, calories: total};\n }", "function omelette(foods) {\n var recipe = {\n egg: 2,\n cheese: 1,\n };\n\n var available = organize(foods);\n\n // if we have enough, take out the corresponding amount and add in an omelette\n // if we don't, don't touch the food\n if (available.egg >= recipe.egg && available.cheese >= recipe.cheese) {\n // remove two eggs from `foods`. loop through once per egg that needs to\n // be removed, find the index of the first egg in the list, then cut it\n // out.\n for (var i = 0; i < recipe.egg; i++) {\n var index = foods.indexOf('egg');\n foods.splice(index, 1);\n }\n // remove one cheese from `foods`. same approach as above.\n for (var i = 0; i < recipe.cheese; i++) {\n var index = foods.indexOf('cheese');\n foods.splice(index, 1);\n }\n\n // add one omelette from `foods`\n foods.push('omelette');\n }\n\n\n // returns new list of foods, minus omelette ingredients, plus an omelette\n return foods;\n}", "scoreSelectedTiles() {\n if (this.lineOfSelectedTiles.length < this.MINIMUM_LINE_LENGTH) return;\n \n //First figure out the unique ingredients from the line of selected tiles.\n const uniqueIngredients = {};\n this.lineOfSelectedTiles.map((tile) => {\n const ingval = tile.value.toString();\n if (!uniqueIngredients[ingval]) {\n uniqueIngredients[ingval] = 1;\n } else {\n uniqueIngredients[ingval]++;\n }\n });\n \n //For each available food order, check if the unique ingredients match all\n //the ingredients of the food order.\n let score = 0;\n this.foodOrders = this.foodOrders.filter((foodOrder) => {\n\n //Check 1: does each (unique) selected ingredient have a corresponding\n //ingredient in the food order recipe?\n let selectedIngredientsOK = true;\n Object.keys(uniqueIngredients).map((ingval) => {\n selectedIngredientsOK =\n selectedIngredientsOK &&\n foodOrder.ingredients.includes(ingval);\n });\n \n //Check 2: does each ingredient in the food order recipe appear in the\n //list of selected ingredients?\n let foodOrderIngredientsOK = true;\n foodOrder.ingredients.map((ingval) => {\n foodOrderIngredientsOK =\n foodOrderIngredientsOK &&\n uniqueIngredients[ingval] > 0\n });\n \n const selectedIngredientsMatchOrder = selectedIngredientsOK && foodOrderIngredientsOK;\n \n //If we get a match, increase the score and remove the food order from the list.\n if (selectedIngredientsMatchOrder) {\n score += this.lineOfSelectedTiles.length;\n return false; //Remove from the list.\n } else {\n return true; //Keep the food order on the list.\n }\n });\n \n //Update the score!\n //If the user made any sort of good match - matching selected ingredients\n //to any food order's ingredients - add to the score.\n //If the user selected ingredients and cooked a meal that nobody wanted, add\n //a penalty to the score.\n score *= this.MAKE_SCORE_LOOK_BIG_FACTOR;\n if (score > 0) {\n this.addMessage(\"+\" + score + \" points!\");\n } else {\n score = this.lineOfSelectedTiles.length * -this.BAD_ORDER_PENALTY * this.MAKE_SCORE_LOOK_BIG_FACTOR;\n this.addMessage(\"Bad recipe! \" + score + \" points...\");\n }\n this.score += score;\n \n //OK, if there are any empty slots for new food orders, let's fill 'em up!\n this.fillFoodOrders();\n \n //Also, count down the number of turns available.\n this.turnsLeft--;\n if (this.turnsLeft === 0) {\n this.setState(GAME_STATE.END_MENU);\n }\n }", "function getFarmersFoodGain() {\n return Math.floor(_varibale.foodGain.farmer * _varibale.other.tf * _varibale.population.farmers);\n} // get food consumed by farmers", "getSumOfDssRatios() {\n let sum = 0;\n for (let disease of this.diseases) {\n sum += this.getDssRatio(disease);\n }\n return sum;\n }", "function dogFeeder(weight, age) {\n if (age >= 1) {\n if (weight <= 5) {\n return weight * 0.05;\n }\n if (weight <= 10) {\n return weight * 0.04;\n }\n if (weight <= 15) {\n return weight * 0.03\n }\n if (weight > 15) {\n return weight * 0.02\n } else if (age <= 1) {\n if (age <= .333) {\n return weight * 0.10;\n }\n if (age <= .58) {\n return weight * 0.05;\n }\n if (age <= 1) {\n return weight * 0.04;\n }\n }\n\n }\n}", "computeDamage (payload) {\n this.hardwareDamage.computeDamage(payload[meetingCategoryDamage.HARDWARE])\n this.softwareDamage.computeDamage(payload[meetingCategoryDamage.SOFTWARE])\n this.journeyDamage.computeDamage(payload[meetingCategoryDamage.JOURNEY])\n\n // Compute the total damage caused by all the components of the meeting thanks to the\n // total damage caused by each category of components.\n this.totalDamage = this.softwareDamage.totalDamage.add(this.hardwareDamage.totalDamage).add(this.journeyDamage.totalDamage)\n }", "getAverageDamage() {\n const avgAttacks = (this.minAttacks + this.maxAttacks) / 2;\n const avgDmg = (this.minDamage + this.maxDamage) / 2 * avgAttacks;\n const critDmg = this.crit / 100 * avgDmg * 2;\n\n return avgDmg + critDmg;\n }", "function fuelRequired(crewArray){\n let massOfCrew = crewMass(crewArray);\n let fuel = (75000+massOfCrew)*9.5;\n for (i=0; i<crewArray.length; i++){\n if (crewArray[i].species === 'dog' || crewArray[i].species === 'cat'){\n fuel += 200;\n } else {\n fuel += 100;\n }\n }\n return Math.ceil(fuel);\n }", "function total_efficiency(patients, prop){\n\tvar total_obs = 0\n\tvar\ttotal_req = 0\n\tvar pr = prop\n\tvar ignored = ['Pool','Exit']\n\tif(prop == \"waits\"){\n\t\tpr = \"waits_arr\"\n\t}\n\tpatients.forEach(function(el){\n\t\tif(el.current_ward.name == \"Exit\"){\n\t\t\t//only include discharged patients\n\t\t\tvar arr = []\n\t\t\t//iterate through observed wards\n\t\t\t//can't just slice as pre-fill patients don't have the same \n\t\t\t//pattern of values that should be ignored\n\t\t\tfor (var i = 0; i < el.observed.wards.length; i++) {\n\t\t\t\tif(ignored.indexOf(el.observed.wards[i]) == -1){\n\t\t\t\t\tarr.push(el.observed[pr][i])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar obs = arr.reduce(function(acc, val) { \n\t\t\t\tval = isNaN(val) ? 0 : val\n\t\t\t\treturn acc + val; \n\t\t\t}, 0)\n\t\t\ttotal_obs += obs\n\n\t\t\t//required amount - always exclude last value\n\t\t\tvar req = el.required[prop].reduce(function(acc, val) { \n\t\t\t\tval = isNaN(val) ? 0 : val\n\t\t\t\treturn acc + val; \n\t\t\t}, 0)\n\t\t\ttotal_req += req\n\n\t\t}\n\t})\n\tvar efficiency = (total_req / total_obs) * 100\n\treturn {'obs':total_obs, 'req': total_req, 'efficiency': efficiency, 'excess': total_obs - total_req}\n}", "hunt() {\n this.food += 2\n }", "function foodAdj(arr1, arr2) {\n let adjectiveOne = foodArray.slice(0, 7);\n let adjectiveTwo = adjectiveArray.slice(0, 7);\n for (let i = 0; i <= arr1.length - 2; i++) {\n if ((arr1[i]).includes('s')) {\n console.log(`${arr1[i]} are ${arr2[i]}`);\n } else {\n console.log(`${adjectiveOne.program} is ${adjectiveTwo}`);\n }\n }\n}", "function choose(mealOptions, goalBudget, goalCalories, count, mealsNotAllowed, preferences){\n return Array.from(mealOptions)\n .filter(function(choice){\n for (let meal of mealsNotAllowed)\n if (meal.mid === choice.mid)\n return false;\n return true;\n })\n .sort(function(c1, c2){\n // Create weights to measure how close food is to target calories/price\n let c1calorieDiff = Math.abs(c1.calories - goalCalories),\n c2calorieDiff = Math.abs(c2.calories - goalCalories),\n c1Weight = (c1calorieDiff / goalCalories) + (parseFloat(c1.price.replace(\"$\",\"\")) / goalBudget),\n c2Weight = (c2calorieDiff / goalCalories) + (parseFloat(c2.price.replace(\"$\",\"\")) / goalBudget);\n\n // Adjust weights based on user preferences\n for (let category of [\"vegetarian\", \"vegan\", \"ketogenic\", \"glutenfree\", \"dairyfree\"])\n {\n if (!!c1[category])\n c1Weight *= preferences[category];\n if (!!c2[category])\n c2Weight *= preferences[category];\n }\n // Return difference in weight\n return c1Weight - c2Weight;\n })\n .slice(0, count);\n }", "crotonWeight(state) {\n var crotonWeight = 0;\n for (var i = 0; i < state.recordsList.length; i++) {\n if (state.recordsList[i].reservoir === \"Croton\") {\n var weight = state.recordsList[i].weight;\n crotonWeight += weight;\n }\n }\n return crotonWeight;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to handle the response from clicking on the 'Create Activity' button Return back to the original form and display the status message
function handleCreateActivityResponse(status) { if (status.errCode === 1){ window.location = '/?methodType=createActivity&errCode=' + status.errCode; } else if (status.errCode === 6){ //missing required parameter var errMsg = 'Error: ' + status.message; if (status.message == 'null time1') { errMsg = 'Error: Null Start Time'; } else if (status.message == 'null time2') { errMsg = 'Error: Null End Time'; } $('#missingParams').html(errMsg); $('#missingParams').show(); $('body').scrollTop(0); //window.location = '/#create_activity_page?errCode=' + status.errCode; } // window.location = '/'; }
[ "function activityAddClicked() {\n\tvar addedActivity = document.getElementById(\"newactivity\").value;\n\t\n\tif (addedActivity==\"\") {\n\t\talert(\"Can't add an empty activity.\");\n\t} else {\n\t\tdoesActivityExist(addedActivity,function(result) {\n\t\t\tif (result) {\n\t\t\t\talert(\"This activity already exists.\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tinsertActivity(addedActivity,function(result) {\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tvar appendString = \taddNewActivityHTML(addedActivity);\n\t\t\t\t\t\t$(\"#activitylist\").append(appendString);\n\n\t\t\t\t\t\t$.mobile.changePage('index.html#activities', {\n\t\t\t\t\t\t\ttransition : \"none\",\n\t\t\t\t\t\t\treverse : false\n\t\t\t\t\t\t}, true, true);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\talert(\"Saving new activity failed. Please try again.\");\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n }", "function MASE_SetInfoboxesAndBtns(response) {\n console.log(\"=== MASE_SetInfoboxesAndBtns =====\") ;\n\n const step = mod_MASE_dict.step;\n const is_response = (!!response);\n\n console.log(\"......................step\", step) ;\n console.log(\"is_response\", is_response) ;\n console.log(\"test_is_ok\", mod_MASE_dict.test_is_ok) ;\n console.log(\"saved_is_ok\", mod_MASE_dict.saved_is_ok) ;\n console.log(\"is_approve_mode\", mod_MASE_dict.is_approve_mode) ;\n console.log(\"verification_is_ok\", mod_MASE_dict.verification_is_ok) ;\n\n // step 0: opening modal\n // step 1 + response : return after check\n // step 1 without response: save clicked approve or request verifcode\n // step 2 + response : return after approve or after email sent\n // step 2 without response: submit Exform wit hverifcode\n // step 3 + response: return from submit Exform\n\n // TODO is_reset\n const is_reset = mod_MASE_dict.is_reset;\n\n// --- info_container, loader, info_verifcode and input_verifcode\n let msg_info_txt = null, show_loader = false;\n let show_info_request_verifcode = false, show_input_verifcode = false;\n let show_delete_btn = false;\n let disable_save_btn = false, save_btn_txt = null;\n\n if (response && response.approve_msg_html) {\n mod_MASE_dict.msg_html = response.approve_msg_html;\n };\n\n console.log(\" >> step:\", step);\n\n if (step === 0) {\n // step 0: when form opens and request to check is sent to server\n // tekst: 'The subjects of the candidates are checked'\n msg_info_txt = loc.MASE_info.checking_exams;\n show_loader = true;\n } else {\n if(mod_MASE_dict.is_approve_mode){\n // --- is approve\n if (step === 1) {\n // response with checked exams\n // msg_info_txt is in response\n show_delete_btn = mod_MASE_dict.has_already_approved;\n if (mod_MASE_dict.test_is_ok){\n save_btn_txt = loc.MASE_info.Approve_exams;\n };\n } else if (step === 2) {\n // clicked on 'Approve'\n msg_info_txt = (is_reset) ? loc.MASE_info.removing_approval_exams : loc.MASE_info.approving_exams;\n show_loader = true;\n } else if (step === 3) {\n // response 'approved'\n // msg_info_txt is in response\n };\n } else {\n // --- is submit\n if (step === 1) {\n // response with checked subjects\n // msg_info_txt is in response\n show_info_request_verifcode = mod_MASE_dict.test_is_ok;\n if (mod_MASE_dict.test_is_ok){\n save_btn_txt = loc.Request_verifcode;\n };\n } else if (step === 2) {\n // clicked on 'Request_verificationcode'\n // tekst: 'AWP is sending an email with the verification code'\n // show textbox with 'You need a 6 digit verification code to submit the Ex form'\n msg_info_txt = loc.MASE_info.sending_verifcode;\n show_loader = true;\n } else if (step === 3) {\n // response 'email sent'\n // msg_info_txt is in response\n show_info_request_verifcode = mod_MASE_dict.test_is_ok;\n show_input_verifcode = true;\n disable_save_btn = !el_MASE_input_verifcode.value;\n save_btn_txt = loc.Publish_exams;\n } else if (step === 4) {\n // clicked on 'Submit Ex form'\n // msg_info_txt is in response\n show_loader = true;\n } else if (step === 5) {\n // response 'Exform submittes'\n // msg_info_txt is in response\n }\n } // if(mod_MASE_dict.is_approve_mode)\n } // if (step === 0)\n\n //console.log(\"msg_info_txt\", msg_info_txt) ;\n\n if (msg_info_txt){\n mod_MASE_dict.msg_html = \"<div class='pt-2 border_bg_transparent'><p class='pb-2'>\" + msg_info_txt + \" ...</p></div>\";\n }\n\n const hide_info_container = (!msg_info_txt || show_loader)\n add_or_remove_class(el_MASE_info_container, cls_hide, hide_info_container)\n\n el_MASE_msg_container.innerHTML = mod_MASE_dict.msg_html;\n add_or_remove_class(el_MASE_msg_container, cls_hide, !mod_MASE_dict.msg_html)\n\n add_or_remove_class(el_MASE_loader, cls_hide, !show_loader)\n\n add_or_remove_class(el_MASE_info_request_verifcode, cls_hide, !show_info_request_verifcode);\n add_or_remove_class(el_MASE_input_verifcode.parentNode, cls_hide, !show_input_verifcode);\n\n if (el_MASE_info_request_msg1){\n el_MASE_info_request_msg1.innerText = loc.MASE_info.need_verifcode +\n ((permit_dict.requsr_role_admin) ? loc.MASE_info.to_publish_exams : \"\");\n };\n\n if (show_input_verifcode){set_focus_on_el_with_timeout(el_MASE_input_verifcode, 150); };\n\n// --- show / hide delete btn\n add_or_remove_class(el_MASE_btn_delete, cls_hide, !show_delete_btn);\n\n console.log(\"save_btn_txt\", save_btn_txt) ;\n// - hide save button when there is no save_btn_txt\n add_or_remove_class(el_MASE_btn_save, cls_hide, !save_btn_txt)\n// --- disable save button till test is finished or input_verifcode has value\n el_MASE_btn_save.disabled = disable_save_btn;;\n// --- set innerText of save_btn\n el_MASE_btn_save.innerText = save_btn_txt;\n\n// --- set innerText of cancel_btn\n el_MASE_btn_cancel.innerText = (step === 0 || !!save_btn_txt) ? loc.Cancel : loc.Close;\n\n } // MASE_SetInfoboxesAndBtns", "function InsertAccountLinkOnSuccess(json) {\n //Blur inputs\n $('.modal-account-guestaccounts-create-input').blur();\n\n //Error\n if (json.message === undefined) {\n $('#modal-account-guestaccounts-create-error-container').find('.alert-danger').html($('#modal-account-guestaccounts-create-form').data(\"error\") + '<i class=\"glyphicon glyphicon-remove pull-right\"></i>');\n $('#modal-account-guestaccounts-create-error-container').css('display', '');\n\n //Enable inputs\n $('.modal-account-guestaccounts-create-input').prop('readonly', false);\n //Enable submit button\n $('#modal-account-guestaccounts-create-submitbtn').prop('disabled', false);\n\n //Set cursor for datepicker button\n $('#account-guestaccount-create-startdate').find('.input-group-addon').css('cursor', 'pointer');\n //Set cursor for datepicker button\n $('#account-guestaccount-create-enddate').find('.input-group-addon').css('cursor', 'pointer');\n\n //Enable datepicker\n $('#account-guestaccount-create-startdate').find(':input').prop('disabled', false);\n $('#account-guestaccount-create-enddate').find(':input').prop('disabled', false);\n $('#account-guestaccount-create-startdate').find(':input').prop('readonly', true);\n $('#account-guestaccount-create-enddate').find(':input').prop('readonly', true);\n $('#account-guestaccount-create-enddate').data().DateTimePicker.date(null);\n $('#account-guestaccount-create-startdate').data().DateTimePicker.date(null);\n\n //Reset form\n $('#modal-account-guestaccounts-create-form').trigger(\"reset\");\n //Reset form validation\n $('#modal-account-guestaccounts-create-form').data('formValidation').resetForm();\n\n //Hide spinner and reset margin\n $('#modal-account-guestaccounts-create-submit-spin').css('display', 'none');\n $('#modal-account-guestaccounts-create-submit-spin').prev().css('margin-left', '');\n\n //Enable select2 input\n $(\"#account-guestaccounts-create-permissions\").select2('enable');\n //Reset select2 value\n $(\"#account-guestaccounts-create-permissions\").select2(\"val\", \"\");\n }\n else {\n if (json.success) {\n $.ajax({\n url: '/Account/UpdateGuestAccountsContent/',\n type: 'GET',\n success: function (data) {\n $('#account-guestaccounts-content').html(data);\n\n mySorted = new SortedTable();\n\n //Reload scripts\n $.getScript('/Scripts/fildela-account-all.js');\n $(\"body\").trigger(\"AccountGuestAccountsReloadScript\");\n\n //Load search table script\n LoadSearchTable();\n\n $('#modal-account-guestaccounts-create-error-container').css('display', 'none');\n\n $('#modal-account-guestaccounts-create-success-container').find('.alert-success').html(json.message + '<i class=\"glyphicon glyphicon-ok pull-right\"></i>');\n $('#modal-account-guestaccounts-create-success-container').css('display', '');\n\n //Enable inputs\n $('.modal-account-guestaccounts-create-input').prop('readonly', false);\n //Enable submit button\n $('#modal-account-guestaccounts-create-submitbtn').prop('disabled', false);\n\n //Enable datepicker\n $('#account-guestaccount-create-startdate').find(':input').prop('disabled', false);\n $('#account-guestaccount-create-enddate').find(':input').prop('disabled', false);\n $('#account-guestaccount-create-startdate').find(':input').prop('readonly', true);\n $('#account-guestaccount-create-enddate').find(':input').prop('readonly', true);\n $('#account-guestaccount-create-enddate').data().DateTimePicker.date(null);\n $('#account-guestaccount-create-startdate').data().DateTimePicker.date(null);\n\n //Set cursor for datepicker button\n $('#account-guestaccount-create-startdate').find('.input-group-addon').css('cursor', 'pointer');\n //Set cursor for datepicker button\n $('#account-guestaccount-create-enddate').find('.input-group-addon').css('cursor', 'pointer');\n\n //Reset form\n $('#modal-account-guestaccounts-create-form').trigger(\"reset\");\n //Reset form validation\n $('#modal-account-guestaccounts-create-form').data('formValidation').resetForm();\n\n //Hide spinner and reset margin\n $('#modal-account-guestaccounts-create-submit-spin').css('display', 'none');\n $('#modal-account-guestaccounts-create-submit-spin').prev().css('margin-left', '');\n\n //Enable select2 input\n $(\"#account-guestaccounts-create-permissions\").select2('enable');\n //Reset select2 value\n $(\"#account-guestaccounts-create-permissions\").select2(\"val\", \"\");\n },\n error: function () {\n InsertAccountLinkOnError();\n\n $('#modal-account-guestaccounts-create-error-container').find('.alert-danger').html($('#modal-account-guestaccounts-remove-form').data(\"error\") + '<i class=\"glyphicon glyphicon-remove pull-right\"></i>');\n $('#modal-account-guestaccounts-create-error-container').css('display', '');\n\n //Enable inputs\n $('.modal-account-guestaccounts-create-input').prop('readonly', false);\n //Enable submit button\n $('#modal-account-guestaccounts-create-submitbtn').prop('disabled', false);\n\n //Set cursor for datepicker button\n $('#account-guestaccount-create-startdate').find('.input-group-addon').css('cursor', 'pointer');\n //Set cursor for datepicker button\n $('#account-guestaccount-create-enddate').find('.input-group-addon').css('cursor', 'pointer');\n\n //Enable datepicker\n $('#account-guestaccount-create-startdate').find(':input').prop('disabled', false);\n $('#account-guestaccount-create-enddate').find(':input').prop('disabled', false);\n $('#account-guestaccount-create-startdate').find(':input').prop('readonly', true);\n $('#account-guestaccount-create-enddate').find(':input').prop('readonly', true);\n $('#account-guestaccount-create-enddate').data().DateTimePicker.date(null);\n $('#account-guestaccount-create-startdate').data().DateTimePicker.date(null);\n\n //Reset form\n $('#modal-account-guestaccounts-create-form').trigger(\"reset\");\n //Reset form validation\n $('#modal-account-guestaccounts-create-form').data('formValidation').resetForm();\n\n //Hide spinner and reset margin\n $('#modal-account-guestaccounts-create-submit-spin').css('display', 'none');\n $('#modal-account-guestaccounts-create-submit-spin').prev().css('margin-left', '');\n\n //Enable select2 input\n $(\"#account-guestaccounts-create-permissions\").select2('enable');\n //Reset select2 value\n $(\"#account-guestaccounts-create-permissions\").select2(\"val\", \"\");\n }\n });\n }\n else {\n $('#modal-account-guestaccounts-create-error-container').find('.alert-danger').html(json.message + '<i class=\"glyphicon glyphicon-remove pull-right\"></i>');\n $('#modal-account-guestaccounts-create-error-container').css('display', '');\n\n //Enable inputs\n $('.modal-account-guestaccounts-create-input').prop('readonly', false);\n //Enable submit button\n $('#modal-account-guestaccounts-create-submitbtn').prop('disabled', false);\n\n //Set cursor for datepicker button\n $('#account-guestaccount-create-startdate').find('.input-group-addon').css('cursor', 'pointer');\n //Set cursor for datepicker button\n $('#account-guestaccount-create-enddate').find('.input-group-addon').css('cursor', 'pointer');\n\n //Enable datepicker\n $('#account-guestaccount-create-startdate').find(':input').prop('disabled', false);\n $('#account-guestaccount-create-enddate').find(':input').prop('disabled', false);\n $('#account-guestaccount-create-startdate').find(':input').prop('readonly', true);\n $('#account-guestaccount-create-enddate').find(':input').prop('readonly', true);\n $('#account-guestaccount-create-enddate').data().DateTimePicker.date(null);\n $('#account-guestaccount-create-startdate').data().DateTimePicker.date(null);\n\n //Reset form\n $('#modal-account-guestaccounts-create-form').trigger(\"reset\");\n //Reset form validation\n $('#modal-account-guestaccounts-create-form').data('formValidation').resetForm();\n\n //Hide spinner and reset margin\n $('#modal-account-guestaccounts-create-submit-spin').css('display', 'none');\n $('#modal-account-guestaccounts-create-submit-spin').prev().css('margin-left', '');\n\n //Enable select2 input\n $(\"#account-guestaccounts-create-permissions\").select2('enable');\n //Reset select2 value\n $(\"#account-guestaccounts-create-permissions\").select2(\"val\", \"\");\n }\n }\n }", "function sdkResponseHandler(status, response) {\n\n if (status != 200 && status != 201) {\n \n alert(\"Verify the data\");\n \n }else{\n \n var form = document.querySelector('#pay');\n\n var card = document.createElement('input');\n card.setAttribute('name',\"card\");\n card.setAttribute('type',\"hidden\");\n card.setAttribute('value',response.id);\n\n form.appendChild(card);\n \n doSubmit=true;\n \n alert(\"card token: \"+response.id);\n \n form.submit();\n }\n }", "function onResponsePageLoad() {\n KASClient.App.registerHardwareBackPressCallback(function(){\n KASClient.App.dismissCurrentScreen();\n }); \n \n KASClient.Form.getFormAsync(function (form, error) { \n if (error != null) { \n KASClient.App.showNativeErrorMessage(\"Error:getFormAsync:\" + error); \n return; \n } \n _form = form; \n \n // Document title would be the form title\n document.getElementById(\"title\").innerHTML = _form.title;\n }); \n }", "function wantsExternalActivity () {\n alert(\"Student wants the external activity\") ;\n // send an InputResponse to the server with YES. callback fn should be processNextProblemResult\n sendNextProblemInputResponse(\"&answer=YES\");\n}", "function handleCreateAccount() {\n\t$('.open-create-account').on('click', event => {\n\t\t$('.Welcome').addClass(\"hidden\");\n\t\t$('.Create-Account-Page').removeClass(\"hidden\");\n\t});\n}", "async finalStep(stepContext) {\n // If the child dialog (\"bookingDialog\") was cancelled or the user failed to confirm, the Result here will be null.\n if (stepContext.result) {\n const result = stepContext.result;\n // Now we have all the booking details.\n\n console.log(result);\n\n // This is where calls to the booking AOU service or database would go.\n let msg = 'I wasn\\'t able to find anyone :( Try searching with different specs?'\n var foundPerson = MainDialog.findPeople(result);\n\n console.log(foundPerson);\n\n if (foundPerson) {\n msg = `You should talk to ${foundPerson.name} in Building ${foundPerson.location}!`; \n }\n\n // If the call to the booking service was successful tell the user.\n const timeProperty = new TimexProperty(result.travelDate);\n const travelDateMsg = timeProperty.toNaturalLanguage(new Date(Date.now()));\n await stepContext.context.sendActivity(msg, 'yeet');\n } else {\n await stepContext.context.sendActivity('Thank you.');\n }\n return await stepContext.beginDialog(MAIN_WATERFALL_DIALOG);\n //return await stepContext.endDialog();\n }", "function add_admin_success_response_function(response)\n {\n show_notification(\"msg_holder\", \"success\", \"Success:\", \"Admin added successfully\");\n fade_out_loader_and_fade_in_form(\"loader\", \"form\"); \n $('#form')[0].reset();\n }", "function CreatePatientMessage(val)\n{\t\n\tif(val == 0)\n\t{\n\t\t$('#Create_Patient_Main_Error').html(\"Patient alreday exist\");\n\t\t$(\"#Create_Patient_Main_Success\").hide();\n\t\t$('#Create_Patient_Main_Error').show();\n\t//\t$(\"#Create_User_user_name_error\").show();\n\t//\tdocument.getElementById('Create_User_user_name_error').innerHTML=\"Username already exists\";\n\t}\n\telse if(val == 1)\n\t{\n\t\t $('#Create_Patient_Main_Success').html(\"New patient has been created\");\n\t\t$(\"#Create_Patient_Main_Success\").show();\n\t\t$('#Create_Patient_Main_Error').hide();\n\t//\tdocument.getElementById('Create_User_error_message').innerHTML=\"User Created Successfully\";\t\t\n\t}\n}", "function _rsvpSuccess() {\n\t\t\t\trf.btnSaved = true;\n\t\t\t\trf.btnSubmitText = _isCreate ? 'Submitted!' : 'Updated!';\n\n\t\t\t\t$rootScope.$broadcast('rsvpSubmitted');\n\n\t\t\t\t// user has submitted an RSVP; update create/edit status in case they edit without refreshing\n\t\t\t\t_isCreate = false;\n\t\t\t\t_isEdit = true;\n\n\t\t\t\t// restart $watch on rf.formModel.attending\n\t\t\t\t_startWatchAttending();\n\n\t\t\t\t$timeout(function() {\n\t\t\t\t\t_btnSubmitReset();\n\t\t\t\t\trf.showModal = false;\n\t\t\t\t}, 1000);\n\t\t\t}", "function buttonAction1(res, tTime, rTime, uName, dTime){\n console.log(\"running test function\")\n const accountSid = 'ACc1bcb5b9402e67ef201df3937f522ebe';\n const authToken = 'ad0278c4e2c2c787cc44616f5b3d9c25';\n const client = require('twilio')(accountSid, authToken);\n client.messages\n .create({\n body: 'Hi ' + uName + ', your journey is going to take about ' + tTime + \" and you want to be there at \" + dTime + \". You will recieve a text when it is time to go.\",\n from: '+12766334501',\n to: '+13053047050'\n })\n .then(message => console.log(message.sid));\n \n \n \n}", "function ok() {\n var carrierToAdd = angular.copy(ctrl.carrier);\n DataService.addCarrier(carrierToAdd, ctrl.editing)\n .then(function (response) {\n 'Back from adding a carrier';\n console.log(response);\n\n })\n .catch(function (error) {\n console.log('There was an error adding');\n console.log(error);\n })\n //We want to communicate whether we edited a current carrier or added a new one so we can respond appropriately.\n if (ctrl.editing) {\n $uibModalInstance.close(ctrl.carrier, true);\n } else {\n $uibModalInstance.close(ctrl.carrier, false);\n }\n }", "function buttonAction1(res, tTime){\r\n console.log(\"running test function\")\r\n const accountSid = 'ACc1bcb5b9402e67ef201df3937f522ebe';\r\n const authToken = 'ad0278c4e2c2c787cc44616f5b3d9c25';\r\n const client = require('twilio')(accountSid, authToken);\r\n client.messages\r\n .create({\r\n body: 'Your journey is going to take about '+tTime,\r\n from: '+12766334501',\r\n to: '+13053047050'\r\n })\r\n .then(message => console.log(message.sid));\r\n}", "function handleVisualFeedback(outcome) {\n\t\t\n\t\tif (outcome === 'pass'){ //Success\n\t\t\trequestButton.innerHTML = \"Submit\";\n\t\t} \n\t\telse if (outcome === 'fail') { //Error\n\t\t\tuserInputCity.value = \"Error Fetching Weather Data ... TRY AGAIN\";\n\t\t\trequestButton.innerHTML = \"TRY AGAIN\";\n\t\t} \n\t\telse if (outcome === 'exception') { //Exception\n\t\t\tuserInputCity.value = \"Exception Thrown ... Please Try Again...\";\n\t\t\trequestButton.innerHTML = \"TRY AGAIN\";\n\t\t\talert(\"Exception Raised creating the API requests, \" +\n\t\t\t\"Page may not display as intended ... See Console for details\");\n\t\t} \n\t}", "function onClickFollow1(){\n if(compnameComparison[0] === undefined){\n notification['warning']({\n message: 'Function Error',\n description:\n 'There is no company selected.',\n });\n }else{\n notification['success']({\n message: 'Operation Success',\n description:\n `${compnameComparison[0]} has been added to the following list. `,\n });\n }\n }", "function onClickFollow2(){\n if(compnameComparison[1] === undefined){\n notification['warning']({\n message: 'Function Error',\n description:\n 'There is no company selected.',\n });\n }else{\n notification['success']({\n message: 'Operation Success',\n description:\n `${compnameComparison[1]} has been added to the following list. `,\n });\n }\n }", "submitCurrentResponse(){\n this.imageTaskView.checkAnswersAndUpdateView();\n let imageTaskResponse = this.imageTaskView.getResponse();\n if (imageTaskResponse.questionResponses.length > 0) {\n this.serverComm.submitImageTaskResponse(imageTaskResponse, this);\n }\n }", "function update_success_response_function(response)\n {\n show_notification(\"msg_holder\", \"success\", \"Success:\", \"Admin updated successfully\");\n fade_out_loader_and_fade_in_form(\"loader\", \"updateform\"); \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
==================== Notify Security ===================
function alertSecurity() { var txt; if (confirm("Are you sure to notify Security?")) { alert("Already notified Security."); } else { alert("Canceled to notify Security!"); } }
[ "notify(number) {\n\n\t\t\tif (Notification.permission == \"granted\") {\n\n\t\t\t\tlet notification = new Notification('InstaCop V2', {\n\t\t\t\t\ticon: this.pidImg,\n\t\t\t\t\tbody: this.config.style + ' stock: ' + number + ' available.'\n\t\t\t\t});\n\n\t\t\t\tnotification.onclick = function() {\n\t\t\t\t\tthis.inventory.atc.mode = \"Auto\";\n\t\t\t\t};\n\n\t\t\t}\n\n\t\t\tlet audio = new Audio('instacop/alert.mp3');\n\t\t\taudio.play();\n\n\t\t}", "_handlePrivacyRequest () {\n const privacyMode = this.preferencesController.getFeatureFlags().privacyMode\n if (!privacyMode) {\n this.platform && this.platform.sendMessage({\n action: 'approve-legacy-provider-request',\n selectedAddress: this.publicConfigStore.getState().selectedAddress,\n }, { active: true })\n this.publicConfigStore.emit('update', this.publicConfigStore.getState())\n }\n }", "function notifyPasswordNotSupported () {\n console.warn('room passwords not supported');\n APP.UI.messageHandler.showError(\n \"dialog.warning\", \"dialog.passwordNotSupported\");\n}", "function welcomeUser(user) {\n user.notify('Welcome ' + user.getName() + '!');\n}", "function Entitlement() {}", "function setKissmetricsUser () {\n _kmq.push(['identify', $rootScope.generalInfo.current_user.email]);\n }", "function notify_risk_type_wrong() {\n if (DEBUG) {\n console.log(\"FUNCTION : notify_risk_type_wrong\");\n }\n $.notify({\n title: \"<strong>risk_type</strong>\",\n message: 'wrong',\n }, {\n type: \"danger\",\n placement: {\n from: \"bottom\",\n align: \"center\"\n }\n });\n}", "notifyMeSection() {\r\n if (this.state.inUser && this.state.inUser.uid !== this.currentUser.uid) {\r\n return (\r\n <div className=\"notify\">\r\n <label>Notify me when vacant:</label>\r\n <input type=\"checkbox\" onChange={ () => { \r\n this.notify = !this.notify;\r\n document.getElementById('alertSound').src = undefined;\r\n document.getElementById('alertSound').play(); \r\n } }/>\r\n </div>\r\n )\r\n }\r\n this.notify = false;\r\n return null;\r\n }", "function handleSecurityError(error){\n\t\t// Stop the communication\n\t\tclearInterval(timerId);\t\n\t\t// If there\tis a securityListener inform the controller of what happened.\n\t\tcontroller.handleSecurityError(error);\n\t}", "function privacyChange(id)\n{\n console.log();\n}", "function noti(notiTitle, notiBody, showAlert) {\n if(typeof(Notification) != \"undefined\" && Notification.permission == \"granted\") {\n new Notification(notiTitle, {icon: \"images/roomicon.png\", body: notiBody});\n } else {\n if(showAlert) {\n alert(notiBody);\n }\n }\n}", "async function handle_new_sub(reg){\n const new_sub=await reg.pushManager.subscribe({userVisibleOnly:true, applicationServerKey:urlBase64ToUint8Array(applicationServerKey)})\n if(new_sub){\n console.log('New Asked Sub')\n return send_sub(new_sub)\n } \n alert('You need to subscribe to be able to use this service well')\n}", "function notifyUsersRequests(number_user_requests) {\n if (window.location.href.split(\"/\").pop() !== \"UserRequests.aspx\") {\n if (number_user_requests !== 0) {\n $.notify({\n message: 'You have ' + number_user_requests + ' pending user requests! Click here to see more details.',\n url: \"UserRequests.aspx\"\n }, {\n type: 'danger',\n url_target: \"\"\n });\n bell.css(\"color\", \"#ffd300\");\n }\n\n }\n}", "function checkUserNotfication(){\n clearInterval(getNotificationInterval);\n getNotificationInterval =\"\";\n\tgetUserNotificationSession();\n\tgetNotificationInterval = setInterval(function(){\n\t\tgetUserNotificationSession();\n\t},60000);\n}", "function recoverSubscription() {\n\n /**\n * we ask the user the password to carry out this operation as there may have some risk\n */\n alertify.prompt(\"Please enter the password for the operation\", \"Default value\",\n function(evt, value ){\n if( value == password_massive_subscription ){\n\n // when the ip is well noted thanks to external API, we record the operator's IP in the base\n if( myip !=null){\n $.ajax({\n url: 'php/Controllers/getData_Monitor_Unsubscription.php',\n method: \"GET\",\n data: {\n please_note_IP: myip\n }\n })\n .done(function () {});\n }\n\n alertify.alert('The operation will last around 3 minutes, please be patient.');\n\n // Disable the button during the repair\n document.getElementById(\"fixnow\").onclick = function(){\n alertify.error(\"The operation is in progress !\");\n };\n\n // We begin the operator by calling out our progress bar\n progressBarRunning(\"progress_bar_recovery\",180);\n\n // Call the API for the recovery and asking for a force update before the operation\n $.ajax({\n url: 'php/Controllers/getData_Monitor_Unsubscription.php',\n method: \"GET\",\n data: {\n unsubscribed_all: false,\n force_update:'true',\n DataType: 'Recovery'\n }\n })\n .done(function () {\n\n console.log(\"Recovery done\");\n\n //Force update after repair\n $.ajax({\n url: 'php/Controllers/getData_Monitor_Unsubscription.php',\n method: \"GET\",\n data: {\n unsubscribed_all: true,\n force_update:'true'\n }\n })\n .done(function () {\n\n set_bar_progress(\"progress_bar_recovery\",100);\n\n alertify.message(\"Operation finished successfully. Updating the display .. \");\n\n refresh_unsubscription_page();\n\n // enable the button again\n document.getElementById(\"fixnow\").onclick = function(){\n recoverSubscription();\n };\n });\n });\n }\n else{\n alertify.error(\"Authentication failed\");\n }\n },\n function(){\n alertify.message('Authentication cancelled');\n })\n ;\n}", "async function notify_unverified_users(){\n var notifications = 0;\n if(configured){\n log(\"Beginning: Notifiying Unverified Users\");\n guild.members.fetch().then((members)=>{\n members.forEach((guildMember)=>{\n if(!guildMember.roles.cache.find( role => role.id === server.roles.Verified)){\n send_user_auth_url(guildMember);\n notifications++;\n }\n });\n log(notifications + \" users notified!\");\n log(\"Ending: Notifiying Unverified Users\");\n })\n \n }else{\n log(\"Can't send verification stuff, configuration not set!\");\n }\n}", "function isnotsu() {\nif(msguser !== superuserid ) {\nconst plaintext = \"<:warn_3:498277726604754946> Sorry, you don't have permissions to use this!\"\nconst embed = new RichEmbed() \n//.setTitle('Title') \n.setColor(0xCC0000) \n.setDescription('only ' + superuser + ' may use this command')\n//.setAuthor(\"Header\")\n.setFooter(\"@\" + msgauthor)\n//.addField(\"Field\");\nmessage.channel.send(plaintext, embed);\n\n\t/*\nreturn message.reply(\"Sorry, you don't have permissions to use this!\")\n*/\nreturn true\n}\nelse\nreturn false;\n}", "notifyModeratorRequired () {\n if (dialog)\n return;\n\n let closeCallback = function () {\n dialog = null;\n };\n\n if (password) {\n dialog = APP.UI.messageHandler\n .openMessageDialog(null, \"dialog.passwordError\",\n null, null, closeCallback);\n } else {\n dialog = APP.UI.messageHandler\n .openMessageDialog(null, \"dialog.passwordError2\",\n null, null, closeCallback);\n }\n }", "allowSentry() {\n storage.setItem('wallet:sentry', true);\n this.updateSentryState();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
addItemToOrder(Name,count,price): IN: Name name of menu item count used for tracking multiples of same item, example burger: 2 price price of the item PURPOSE: add the clicked menu item to the order. create an html element for the item under orderArea. OUT: nothing, however html item element is created in view
function addItemToOrder(Name,count,price){ orderTotal += parseFloat(price); var itemName = Name+'-'+count || Name;//legacy, don't really need || var newItem = document.createElement("p"); newItem.setAttribute('id',itemName); document.getElementById('orderArea').appendChild(newItem); $('#'+itemName).html(Name.toUpperCase() +' $'+price); $('#orderTotal').html('Total: $'+orderTotal.toFixed(2));//force two decimal spots }
[ "function createItem(id,parentDiv,price){\n\tvar nm = id.substring(id.lastIndexOf(ElementId_Spacer)+1);\n\tvar newItem = document.createElement(\"p\");\n\tnewItem.setAttribute('class','item');\n\tnewItem.setAttribute('id',id);\n\tnewItem.setAttribute('value',price);\n\tnewItem.setAttribute('name',nm);\n\tdocument.getElementById(parentDiv).appendChild(newItem);\n\tdocument.getElementById(id).innerHTML = nm.toUpperCase();\n}", "function buildOrderItem(menu_id, size, cost, category, name, toppings) {\n var orderItem = {\n 'id': guid(),\n 'menu_id': menu_id,\n 'size': size,\n 'cost': cost,\n 'category': category,\n 'name': name,\n 'toppings': toppings\n }\n return orderItem;\n\n}", "function addNewItem(product) {\n var item = orderItemType.createInstance();\n item.order = this;\n item.product = product;\n this.orderItems.push(item);\n return item;\n }", "function calculateOrder() {\n var itemOrder = order.getItems();\n // clear orderList \n orderList.innerHTML = '';\n\n itemOrder.forEach(function (item, i) {\n var elem = document.createElement('li');\n elem.classList.add('order__list-item');\n var elemContent = item.name + ' x ' + item.quantity + ', price: ' + parseInt(item.type.price) * parseInt(item.quantity) + ' ' + VALUE_PRICE + ', calories: ' + parseInt(item.type.calories\n ) * parseInt(item.quantity) + ' ' + VALUE_CALORY\n elem.textContent = elemContent\n\n var buttonRemove = document.createElement('button');\n // adding class for future remove handling with event delegation\n buttonRemove.classList.add('js-button-remove');\n // adding data attribute for easy finding element index when removing item\n buttonRemove.setAttribute('data-index', i);\n buttonRemove.textContent = 'X';\n\n elem.appendChild(buttonRemove);\n\n orderList.appendChild(elem);\n });\n}", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n var product = document.getElementsById('items').value;\n // TODO: get the quantity\n var quantity = document.getElementById('quantity').value;\n // TODO: using those, add one item to the Cart\n cart.product = product;\n //cart.items.allProducts = product;\n //cart.product = value;\n //var numberOfProducts = cart.quantity++;\n //numberOfProducts = quantity;\n cart.quantity += quantity;\n}", "function markToBuy (event){\n // Get the element that triggered a specific event\n var selectedItem = event.target;\n // Get element by id\n var targetList = document.getElementById('toBuyItems');\n // Create new item if selected \n newBuyItem = ' <li class=\"list-group-item\"> <div role=\"group\" aria-label=\"Checklist Buttons\"> <button type=\"button\" onClick=\"markPacked(event);\" class=\"btn btn-check checkItem\" data-itemname=\"' + selectedItem.getAttribute(\"data-buyitemname\") + '\">Check</button> </div> ' + selectedItem.getAttribute(\"data-buyitemname\") + '</li>';\n // Where new item should be created\n var currentBuyList = targetList.innerHTML;\n targetList.innerHTML = currentBuyList + newBuyItem;\n // Hide item if selected\n selectedItem.parentElement.parentElement.classList.add('hideItem');\n saveItem('bought', selectedItem.getAttribute(\"data-buyitemname\"));\n }", "function addItem(item) {\n item.order = this;\n var items = this.orderItems;\n if (items.indexOf(item) == -1) {\n items.push(item);\n }\n }", "function insertItemCounter () {\n let newh2 = document.createElement('h2');\n let list = document.getElementsByTagName(\"ul\");\n let listCount = list[0].children.length;\n newh2.innerHTML = 'You have ' + listCount + ' items in your shopping cart';\n let countMessage = document.getElementsByTagName(\"h1\");\n countMessage[0].after(newh2);\n newh2.setAttribute(\"id\", \"item-count\")\n}", "addItemOnPress() {\n var receipt = this.state.receipt;\n receipt.addNewItem(\n this.state.quantityFieldValue,\n this.state.nameFieldValue,\n this.state.pricePerUnitFieldValue\n )\n\n this.setState({\n receipt: receipt\n })\n\n receipt.save()\n }", "function displayHistory() {\r\n\tvar oLength = orderData.length;\r\n\tvar pLength = productData.length;\r\n\t//alert(pLength);\r\n\tvar oInfo = ''; //for adding new order\r\n\tvar n = 0;\r\n\tvar ohl = dom('orderHistoryList');\r\n\tvar tempID = 0;\r\n\tvar proName = '';\r\n\tvar iInfo = ''; //for adding new item in an existing order\r\n\tfor(var i=0;i<oLength;i++){\r\n\t\tif(tempID != orderData[i].order_id){\r\n\t\t\ttempID = orderData[i].order_id;\r\n\t\t\tfor(var t=0;t<pLength;t++){\r\n\t\t\t\tif(orderData[i].product_id == productData[t].product_id){\r\n\t\t\t\t\tproName = productData[t].productname;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tn = i+1;\r\n\t\t\toInfo = \r\n\t\t\t\t'<li class=\"order\" id=\"order_' + n + '\">' +\r\n\t\t\t\t\t'<span class=\"orderID\">' + orderData[i].order_id + '</span>' +\r\n\t\t\t\t\t'<span class=\"orderItems\">' +\r\n\t\t\t\t\t\t'<ul id=\"orderitem_' + tempID +'\">' +\r\n\t\t\t\t\t\t\t'<li>' +\r\n\t\t\t\t\t\t\t\t'<span class=\"itemName\">' + proName + '</span>' +\r\n\t\t\t\t\t\t\t\t'<span class=\"itemAmount\">' + orderData[i].amount + '</span>' +\r\n\t\t\t\t\t\t\t\t'<span class=\"itemTotalPrice\">' + orderData[i].totalprice + ' kr</span>' +\r\n\t\t\t\t\t\t\t'</li>' +\r\n\t\t\t\t\t\t'</ul>' +\r\n\t\t\t\t\t'</span>' +\r\n\t\t\t\t\t'<span class=\"orderTotalPrice\">' + orderData[i].orderprice + ' kr</span>' +\r\n\t\t\t\t\t'<span class=\"timeStamp\">' + orderData[i].timestamp + ' </span>' +\r\n\t\t\t\t\t'<button class=\"cancelOrder\" style=\"visibility:hidden\">Cancel</button>' +\r\n\t\t\t\t'</li>';\r\n\t\t\tohl.innerHTML += oInfo;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tvar itemID = 'orderitem_' + tempID;\r\n\t\t\tvar oi = dom(itemID);\r\n\t\t\tfor(var t=0;t<pLength;t++){\r\n\t\t\t\tif(orderData[i].product_id == productData[t].product_id){\r\n\t\t\t\t\tproName = productData[t].productname;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tiInfo =\r\n\t\t\t\t'<li>' +\r\n\t\t\t\t\t'<span class=\"itemName\">' + proName + '</span>' +\r\n\t\t\t\t\t'<span class=\"itemAmount\">' + orderData[i].amount + '</span>' +\r\n\t\t\t\t\t'<span class=\"itemTotalPrice\">' + orderData[i].totalprice + ' kr</span>' +\r\n\t\t\t\t'</li>';\r\n\t\t\toi.innerHTML += iInfo;\r\n\t\t}\r\n\t}\r\n}", "function addSelectedItemToCart(event) {\n // TODO: suss out the item picked from the select list\n console.log(event.target);\n console.log('QUANTITY VALUE', event.target.quantity.value);\n console.log('ITEM VALUE', event.target.items.value);\n var product = event.target.items.value;\n var quantity = event.target.quantity.value;\n\n // TODO: get the quantity\n // TODO: using those, add one item to the Cart\n cart.addItem(product, quantity);\n}", "function handleAddToCartPress() {\n productID = $(this).attr(\"product-id\");\n console.log(\"cart item id: \" + productID);\n\n productName = $(this).attr(\"name-id\");\n console.log(\"cart product name: \" + productName);\n $(\"#productSelected\").text(productName);\n\n productPrice1 = $(this).attr(\"price-id1\");\n console.log(\"unformatted price: \" + productPrice1);\n\n productPrice2 = $(this).attr(\"price-id2\");\n console.log(\"formatted price: \" + productPrice2);\n\n $(\"#productPrice\").text(productPrice2);\n\n stockQuantity = $(this).attr(\"stock-quantity\");\n console.log(\"stock quantity: \" + stockQuantity);\n\n $(\".view-cart-button-container\").show();\n }", "function addBuyer() {\n\tvar lName = $('#lName').val();\n\tvar fName = $('#fName').val();\n\tvar addr = $('#addr').val();\n\tbuyers[buyersCounter][lName] = lName;\n\tbuyers[buyersCounter][fName] = fName;\n\tbuyers[buyersCounter][addr] = addr;\n\t$('#buyerList').prepend('<li class=\"arrow swipeDelete\"><a class=\"swipeDelete\" href=\"#customerInfo\">' + fName + ' ' + lName + '</a></li>');\n\tdeleteHandler()\n\tjQT.goBack();\n\tbuyersCounter++\n\treturn false;\n}", "function addItem(item){\n basket.push(item);\n return true;\n}", "function purchaseItems() {\n\t// check for atleast one sessionStorage object\n\tif (sessionStorage.itemName) {\n\t\tlet openModal = document.getElementsByClassName('modal')[0]\n\t\topenModal.style.display = 'block'\n\t\tgrandTotal()\n\t} else {\n\t\talert('Please Add An Item To Your Cart.')\n\t\twindow.location.href = '../html/store.html'\n\t}\n}", "function addItemShoppingList(newItem) {\n STORE.items.push({name: newItem, checked: false});\n}", "function addItemToCompare(el){\n console.log(\"add to compare button pressed!\")\n var listingID = el.parentNode.parentNode.id;\n \n console.log(listingID);\n console.log(strippedProductArray[listingID]);\n addUniqueItemToCompareList(strippedProductArray[listingID]);\n //var newCompareListItem = compareList.push();\n \n // var newCompareListItem = compareList.child(strippedProductArray[listingID].name);\n //newCompareListItem.set(strippedProductArray[listingID]); //console.log(productArray[listingID]);\n //compareList\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 }", "function addToInventory(toAdd) {\n inventory.push(toAdd)\n console.log('You have added ' + toAdd)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts new unstyled block. Initially inspired from but changed so that the split + block type reset amounts to only one change in the undo stack.
insertNewUnstyledBlock(editorState) { const selection = editorState.getSelection(); let newContent = Modifier.splitBlock( editorState.getCurrentContent(), selection, ); const blockMap = newContent.getBlockMap(); const blockKey = selection.getStartKey(); const insertedBlockKey = newContent.getKeyAfter(blockKey); const newBlock = blockMap .get(insertedBlockKey) .set('type', BLOCK_TYPE.UNSTYLED); newContent = newContent.merge({ blockMap: blockMap.set(insertedBlockKey, newBlock), }); return EditorState.push(editorState, newContent, 'split-block'); }
[ "resetBlockWithType(editorState, newType, newText) {\n const contentState = editorState.getCurrentContent();\n const selectionState = editorState.getSelection();\n const key = selectionState.getStartKey();\n const blockMap = contentState.getBlockMap();\n const block = blockMap.get(key);\n\n // Maintain persistence in the list while removing chars from the start.\n // https://github.com/facebook/draft-js/blob/788595984da7c1e00d1071ea82b063ff87140be4/src/model/transaction/removeRangeFromContentState.js#L333\n let chars = block.getCharacterList();\n let startOffset = 0;\n const sliceOffset = block.getText().length - newText.length;\n while (startOffset < sliceOffset) {\n chars = chars.shift();\n startOffset++;\n }\n\n const newBlock = block.merge({\n type: newType,\n text: newText,\n characterList: chars,\n data: {},\n });\n const newContentState = contentState.merge({\n blockMap: blockMap.set(key, newBlock),\n });\n const newSelectionState = selectionState.merge({\n anchorOffset: 0,\n focusOffset: 0,\n });\n\n return EditorState.acceptSelection(\n EditorState.set(editorState, {\n currentContent: newContentState,\n }),\n newSelectionState,\n );\n }", "newBlockFromBag(){\n const blockType = this.bag.shift();\n\n this.blocks.currentBlock = new blockType(3, 0);\n this.updateGhostBlock();\n\n if(this.bag.length === 0){\n this.generateNewBag(false);\n }\n\n const event = new CustomEvent('TetrisNewNextBlock', {detail: {nextBlock: this.bag[0]}});\n document.dispatchEvent(event);\n\n if(this.checkCollision(this.blocks.currentBlock)){\n const event = new Event('TetrisGameOver');\n document.dispatchEvent(event);\n }\n }", "removeBlockEntity(editorState, entityKey, blockKey) {\n let newState = editorState;\n\n const content = editorState.getCurrentContent();\n const blockMap = content.getBlockMap();\n const block = blockMap.get(blockKey);\n\n const newBlock = block.merge({\n type: BLOCK_TYPE.UNSTYLED,\n text: '',\n // No text = no character list\n characterList: block.getCharacterList().slice(0, 0),\n data: {},\n });\n\n const newSelection = new SelectionState({\n anchorKey: blockKey,\n focusKey: blockKey,\n anchorOffset: 0,\n focusOffset: 0,\n });\n\n const newContent = content.merge({\n blockMap: blockMap.set(blockKey, newBlock),\n });\n\n newState = EditorState.push(newState, newContent, 'change-block-type');\n newState = EditorState.forceSelection(newState, newSelection);\n\n return newState;\n }", "insertBreak(editor) {\n editor.insertBreak();\n }", "function createNewBlock(name) {\n\t\t\t\tvar node = container, block, clonedNode, caretNode;\n\n\t\t\t\tblock = name || parentBlockName == \"TABLE\" ? dom.create(name || newBlockName) : parentBlock.cloneNode(false);\n\t\t\t\tcaretNode = block;\n\n\t\t\t\t// Clone any parent styles\n\t\t\t\tif (settings.keep_styles !== false) {\n\t\t\t\t\tdo {\n\t\t\t\t\t\tif (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) {\n\t\t\t\t\t\t\t// Never clone a caret containers\n\t\t\t\t\t\t\tif (node.id == '_mce_caret') {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tclonedNode = node.cloneNode(false);\n\t\t\t\t\t\t\tdom.setAttrib(clonedNode, 'id', ''); // Remove ID since it needs to be document unique\n\n\t\t\t\t\t\t\tif (block.hasChildNodes()) {\n\t\t\t\t\t\t\t\tclonedNode.appendChild(block.firstChild);\n\t\t\t\t\t\t\t\tblock.appendChild(clonedNode);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcaretNode = clonedNode;\n\t\t\t\t\t\t\t\tblock.appendChild(clonedNode);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} while ((node = node.parentNode));\n\t\t\t\t}\n\n\t\t\t\t// BR is needed in empty blocks on non IE browsers\n\t\t\t\tif (!isIE) {\n\t\t\t\t\tcaretNode.innerHTML = '<br data-mce-bogus=\"1\">';\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t}", "function addBlock(label) {\n // make sure label is unique identifier\n var newlabel = label;\n var counter = 1;\n var found;\n do {\n found = topBlock.forEachChild(function(child){\n if (child.getLabel() == newlabel) {\n newlabel = label + counter;\n counter += 1;\n return false;\n }\n return true;\n });\n } while (!found);\n label = newlabel;\n\n // create the new block; pass it a handle to the top-level (i.e. its parent)\n // logic block so that it can access other procedures in the program\n var element = new FlowBlockVisual(ctx,label,topBlock.getLogic());\n element.setHeightChangeCallback(resizeCanvas);\n topBlock.addChild(element);\n modified = true;\n drawScreen();\n return element;\n }", "function set_new_block_editor(doc, elem) {\n elem.find('input[name=\"editor_id\"]').val(phila.editor.editor_id);\n elem.find('.editid').text(phila.editor.editor_id);\n elem.find('.edittime').html(String(new Date()))\n}", "insertFragment(editor, fragment) {\n editor.insertFragment(fragment);\n }", "function insertBatteryBlock(full_block_qty)\n{ \n let total_battery_blocks = 10; // amount of blocks needed (each block is 10%)\n let active_block_opacity = 1;\n let inactive_block_opacity = 0.3;\n \n let block_start_y = 272; // starting y coordinate of blocks \n let block_pad = 3; // pixel amount between blocks\n let block_height = 25 + block_pad; \n \n let battery_block;\n \n /* sets the position of each block */\n for(let i = 0; i < total_battery_blocks; i++) \n {\n battery_block = document.getElementById(\"battery-block-\" + i);\n battery_block.y = block_start_y - (i * block_height);\n \n if(i < full_block_qty){\n battery_block.style.opacity = active_block_opacity; // darker shade for active blocks\n }\n else{\n battery_block.style.opacity = inactive_block_opacity; // lighter shade for inactive blocks\n }\n }\n}", "function Plugin_LogicSeparatingBlock()\n\t{\n\t\tthis._tmpPos = new (PhysicsCore.b2Vec2)();\n\t}", "removeBlock(editorState, key) {\n const content = editorState.getCurrentContent();\n const blockMap = content.getBlockMap().remove(key);\n\n return EditorState.set(editorState, {\n currentContent: content.merge({\n blockMap: blockMap,\n }),\n });\n }", "function wrapSelfAndSiblingsInDefaultBlock(container, offset) {\n\t\t\t\tvar newBlock, parentBlock, startNode, node, next, rootBlockName, blockName = newBlockName || 'P';\n\n\t\t\t\t// Not in a block element or in a table cell or caption\n\t\t\t\tparentBlock = dom.getParent(container, dom.isBlock);\n\t\t\t\trootBlockName = editor.getBody().nodeName.toLowerCase();\n\t\t\t\tif (!parentBlock || !canSplitBlock(parentBlock)) {\n\t\t\t\t\tparentBlock = parentBlock || editableRoot;\n\n\t\t\t\t\tif (!parentBlock.hasChildNodes()) {\n\t\t\t\t\t\tnewBlock = dom.create(blockName);\n\t\t\t\t\t\tparentBlock.appendChild(newBlock);\n\t\t\t\t\t\trng.setStart(newBlock, 0);\n\t\t\t\t\t\trng.setEnd(newBlock, 0);\n\t\t\t\t\t\treturn newBlock;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Find parent that is the first child of parentBlock\n\t\t\t\t\tnode = container;\n\t\t\t\t\twhile (node.parentNode != parentBlock) {\n\t\t\t\t\t\tnode = node.parentNode;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Loop left to find start node start wrapping at\n\t\t\t\t\twhile (node && !dom.isBlock(node)) {\n\t\t\t\t\t\tstartNode = node;\n\t\t\t\t\t\tnode = node.previousSibling;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (startNode && schema.isValidChild(rootBlockName, blockName.toLowerCase())) {\n\t\t\t\t\t\tnewBlock = dom.create(blockName);\n\t\t\t\t\t\tstartNode.parentNode.insertBefore(newBlock, startNode);\n\n\t\t\t\t\t\t// Start wrapping until we hit a block\n\t\t\t\t\t\tnode = startNode;\n\t\t\t\t\t\twhile (node && !dom.isBlock(node)) {\n\t\t\t\t\t\t\tnext = node.nextSibling;\n\t\t\t\t\t\t\tnewBlock.appendChild(node);\n\t\t\t\t\t\t\tnode = next;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Restore range to it's past location\n\t\t\t\t\t\trng.setStart(container, offset);\n\t\t\t\t\t\trng.setEnd(container, offset);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn container;\n\t\t\t}", "holdBlock(e){\n const event = new CustomEvent('TetrisNewHoldBlock', {detail: {holdBlock: this.blocks.currentBlock}});\n\n document.dispatchEvent(event);\n\n if(!e.detail.holdBlock){\n this.newBlockFromBag()\n }else{\n this.blocks.currentBlock = e.detail.holdBlock;\n this.blocks.currentBlock.x = 3;\n this.blocks.currentBlock.y = 0;\n this.updateGhostBlock();\n }\n }", "function addCodeblock() {\r\n\r\n // Disable the codeblock buttons so that multiple codeblocks can't be\r\n // added/saved/removed at once.\r\n changeCodeblockButtons(false);\r\n jQuery(\"#codeblock_add\").button(\"option\", \"label\", \"Adding...\");\r\n\r\n // Request that the server adds a new codeblock.\r\n jQuery.post(ajaxurl, {\r\n\r\n action : 'tw-ajax-codeblock-add'\r\n\r\n }, function(response) {\r\n // Re enable the codeblock buttons now that we've gotten a response from\r\n // the server.\r\n changeCodeblockButtons(true);\r\n jQuery(\"#codeblock_add\")\r\n .button(\"option\", \"label\", \"Add New Code Block\");\r\n\r\n // Only update the UI if the addition of the tab was successful.\r\n if (response.success) {\r\n\r\n // Create a new codeblock object and populate it with data from the\r\n // server.\r\n codeblocks[response.block_id] = {\r\n block_name : response.block_name,\r\n block_code : response.block_code,\r\n block_color : response.block_color\r\n };\r\n\r\n // Add a new tab to the UI.\r\n var $codeblock_tabs = jQuery('#codeblock_tabs');\r\n $codeblock_tabs.tabs(\"add\", \"#codeblock_tab_\" + response.block_id,\r\n response.block_name);\r\n\r\n // Select the newly created tab, thus triggering a form update.\r\n $codeblock_tabs.tabs(\"select\", \"#codeblock_tab_\"\r\n + response.block_id);\r\n }\r\n\r\n });\r\n}", "function createInsertIndicator() {\n if (insertIndicatorElement) {\n return;\n }\n\n insertIndicatorScope = scope.$new();\n\n scope.$apply(function () {\n insertIndicatorElement = $compile('<div class=\"tabInsertionIndicatorLine\" />')(insertIndicatorScope);\n if (insertIndicatorElement) {\n body.append(insertIndicatorElement);\n insertIndicatorElement.hide();\n\n currentDropTarget = null;\n currentInsertionIndicatorPosition = null;\n }\n });\n }", "function EndTextBlock() {\n\tif (arguments.length != 0) {\n\t\terror('Error 110: EndTextBlock(); must have empty parentheses.');\n\t}\n\telse if (EDITOR_OBJECT == null ) {\n\t\terror(\t'Error 111: EndTextBlock(); must come after a call to ' +\n\t\t\t\t'StartNewTextBlock(...);');\n\t}\n\telse if ( !(EDITOR_OBJECT instanceof text_block) ) {\n\t\terror(\t'Error 112: EndTextBlock(); must come after a call to ' +\n\t\t\t\t'StartNewTextBlock(...);');\n\t}\n\telse if (!ERROR_FOUND) {\n\t\tvar current_text_block = EDITOR_OBJECT;\n\t\tvar block_html = \t'<span class=\"' + \n\t\t\t\t\t\t\tcurrent_text_block.class + \n\t\t\t\t\t\t\t'\" ' + \n\t\t\t\t\t\t\tcurrent_text_block.html + '\">';\n\n\t\tfor (j = 0; j < current_text_block.content.length; j++) {\n\t\t\tvar item = current_text_block.content[j];\n\t\t\tblock_html += item.html;\n\t\t}\n\n\t\tcurrent_text_block.html = block_html + '</span>';\n\t\tEDITOR_OBJECT = EDITOR_STACK.pop();\n\t\tconsole.log(block_html);\n\t}\n}", "function addCard() {\n displayCard([\"Card Text\", \"STATEMENT\"], true)\n editId = idCounter - 1\n isAddEdit = true\n openEditor()\n markDirty()\n }", "function saveBlock(block) {\n if (typeof block.setIcon == 'undefined')\n // 'block' is not a block visual\n return;\n if (currentBlock.isChildToggled())\n // block has toggled child\n return;\n currentBlock.setIcon(true);\n blockStack.push(currentBlock);\n currentBlock = block;\n block.setIcon(false);\n resizeCanvas(); // this redraws the screen\n }", "async addBlock(block) {\n await this.chain.push(block);\n return block;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combines the binding value and a factory for an animation player. Used to bind a player to an element template binding (currently only `[style]`, `[style.prop]`, `[class]` and `[class.name]` bindings supported). The provided `factoryFn` function will be run once all the associated bindings have been evaluated on the element and is designed to return a player which will then be placed on the element.
function bindPlayerFactory(factoryFn, value) { return new BoundPlayerFactory(factoryFn, value); }
[ "function keyhandlerBindingFactory(keyCode) {\n return {\n init: function(element, valueAccessor, allBindingsAccessor, data, bindingContext) {\n var wrappedHandler, newValueAccessor;\n\n // wrap the handler with a check for the enter key\n wrappedHandler = function(data, event) {\n if (event.keyCode === keyCode) {\n valueAccessor().call(this, data, event);\n }\n };\n\n // create a valueAccessor with the options that we would want to pass to the event binding\n newValueAccessor = function() {\n return {\n keyup: wrappedHandler\n };\n };\n\n // call the real event binding's init function\n ko.bindingHandlers.event.init(element, newValueAccessor, allBindingsAccessor, data, bindingContext);\n }\n };\n }", "function Binding(value){\r\n\t\tthis.value= value;\r\n\t\tif(value){\r\n\t\t\tvalue._binding = this;\r\n\t\t}\r\n\t}", "atEndOfPhase(propertyFactory, phaseName = '', ability) {\n var properties = propertyFactory(AbilityDsl);\n this.game.addEffect(this, Object.assign({ \n duration: 'atEndOfPhase', \n location: 'any', \n phase: phaseName, \n ability: ability \n }, properties));\n }", "function createPlayer() {\n player = new PIXI.AnimatedSprite(playerSheet.walkSouth);\n player.anchor.set(0.5);\n player.animationSpeed = 0.18;\n player.loop = false;\n player.x = app.view.width / 2;\n player.y = app.view.height / 2;\n app.stage.addChild(player);\n player.play();\n}", "function factory () {\n // Just forwards the call to the resolver by setting itself as context.\n function fn (value) {\n return resolver.call(fn, value);\n }\n\n created += 1;\n fn.id = created;\n\n // The state is attached to the function object so it's available to the\n // state-less functions when running under `this.`.\n fn.locks = 0;\n fn.chain = null;\n fn.resolved = [];\n fn.filters = [];\n fn.forks = [];\n\n // Expose the behaviour in the functor\n fn.pause = pause;\n fn.resume = resume;\n fn.filter = filter;\n fn.fork = fork;\n fn.merge = merge;\n fn.completed = completed;\n\n return fn;\n}", "function makeFilterFn$(value$, criteriaFnFactory) {\n return value$\n .map(value => {\n const criteriaFn = criteriaFnFactory(value);\n return function filterStateByCriteria(oldState) {\n const newProjects = oldState.projects.filter(criteriaFn);\n return {...oldState, projects: newProjects};\n };\n })\n .startWith(_.identity); // identity means \"allow anything\"\n}", "function Fader(node, duration){\n \n // fetch the DOM node if a string was supplied\n if (typeof node == 'string') node = document.getElementById(node);\n \n // store the rate\n this.rate = 0.05 / (duration ? duration : 0.5);\n \n // style the node so that panels can be positioned on top of each other\n node.style.position = 'relative';\n \n // initialise the fader width and height\n var width = 0;\n var height = 0;\n \n // initialise the list of panels\n this.panels = [];\n this.target = 0;\n \n // loop over the children of the node\n var child = node.firstChild;\n do{\n \n // check that this is an element node\n if (child.nodeType == 1){\n \n // update the fader width and height\n width = Math.max(width, child.offsetWidth);\n height = Math.max(height, child.offsetHeight);\n \n // position the panel\n child.style.position = 'absolute';\n child.style.top = 0;\n child.style.left = 0;\n \n // add this panel to the list of panels\n this.panels.push(\n {\n node : child,\n opacity : (this.panels.length == 0 ? 1 : 0)\n });\n \n }\n \n }while (child = child.nextSibling);\n \n // set the fader width and height\n node.style.minWidth = width + 'px';\n node.style.minHeight = height + 'px';\n \n // determine whether the opacity or filter properties should be used\n this.useOpacity = 'opacity' in document.documentElement.style;\n \n // initialise the fader\n this.setTarget(0);\n \n // update the opacity ever 50 milliseconds\n var thisObject = this;\n window.setInterval(\n function(){\n thisObject.setPanelOpacity(\n thisObject.target,\n thisObject.panels[thisObject.target].opacity + thisObject.rate);\n },\n 50);\n \n}", "buildPlayer() {\n if (this.player || !this.props.stream) {\n // do not build the player if it already exists or\n // if the stream hasn't been fetched yet\n return;\n }\n\n const { id } = this.props.match.params;\n this.player = flv.createPlayer({\n type: 'flv',\n // the stream name does not necessarily have to be the id of the stream\n // the name should match to the key-name we provide in OBS\n url: `http://localhost:8000/live/${id}.flv`\n });\n this.player.attachMediaElement(this.videoRef.current);\n this.player.load();\n }", "function by() {\n \"use strict\";\n var ret = { animate: \"animateBy\",\n value: null,\n delay: 0,\n duration: 0,\n alpha: \"linear\"};\n\n ret.value = arguments[0]; // property value\n if( arguments.length > 1 ) {\n ret.delay = _numberOrRaise(arguments[1], \"Delay must be a number\");\n }\n if( arguments.length > 2 ) {\n ret.duration = _numberOrRaise(arguments[2], \"Duration must be a number\");\n }\n if( arguments.length > 3 ) { // optional\n ret.alpha = arguments[3];\n }\n return ret;\n}", "function addCustomPlayer() {\r\n var name = $('#custom-player-name').val();\r\n var cleanName = name.toLowerCase().replace(/[^0-9a-z]/gi, '');\r\n var sprite = customSprite;\r\n var container = $('#custom-player-panel');\r\n\r\n var htmlInsert = '<div class=\"modal-player-box\">' +\r\n '<p class=\"modal-player-name\">' + name.replace('<', '&lt;').replace('>', '&gt;') + '</p>' +\r\n '<div class=\"modal-player-sprite-container custom-modal-player-sprite-container\" id=\"custom-player-' + cleanName + '\" data-dismiss=\"modal\" data-name=\"' + name.replace('<', '&lt;').replace('>', '&gt;') + '\" data-sprite=\"' + sprite + '\">' +\r\n '<img src=\"' + sprite + '\" alt=\"' + cleanName + '.png\" class=\"modal-player-sprite\"/>' +\r\n '<div class=\"icon\">+</div>' +\r\n '</div>' +\r\n '</div>';\r\n\r\n container.prepend(htmlInsert);\r\n\r\n var customPlayer = document.getElementById('custom-player-' + cleanName);\r\n customPlayer.addEventListener(\"click\", () => {\r\n changePlayer(customPlayer);\r\n });\r\n}", "setupNewTurn(){\n this.variableValue = null; // reset variableValue property\n updateVariableInDOM(this.variableValue); // sets #random-number-wrapper element content in DOM to ?\n updateActivePlayer.bind(this)(); // update activePlayer property and display active player's name in #current-player-name element\n addClickToPlayEventListener.bind(this)(); // turn on event listener for #random-number-wrapper element\n $('#click-to-play-instruction').text(\"Click to Play!\"); // reset instruction\n\n function addClickToPlayEventListener(){\n $('#random-number-wrapper').click(clickToPlayHandler.bind(this)); // bind 'this' as clickToPlay instance, inside event handler context\n }\n\n function updateActivePlayer(){\n if (this.activePlayer === null || this.activePlayer == 2) {\n this.activePlayer = 1;\n $('#current-player-name').text(this.player1Name);\n } else if (this.activePlayer === 1) {\n this.activePlayer = 2;\n $('#current-player-name').text(this.player2Name);\n }\n }\n\n function updateVariableInDOM(variableValue){\n if (variableValue === null) { // start of turn\n $('#random-number-wrapper').addClass(\"pulse\");\n $('.fas.fa-question').removeClass(\"hide\");\n $('#variable-value').addClass(\"hide\");\n } else { \n $('.fas.fa-question').addClass(\"hide\");\n $('#variable-value').text(variableValue);\n $('#variable-value').removeClass(\"hide\");\n }\n }\n\n // EVENT LISTENER FOR ? ELEMENT\n function clickToPlayHandler(clickEvent) {\n clickEvent.preventDefault();\n clickEvent.stopPropagation();\n $('#random-number-wrapper').off(\"click\"); // remove event listener once player clicks ? element\n // returns value for this.variableValue and animates changing number in DOM by calls to updateVariableInDOM \n this.variableValue = generateVariableValue(this.difficultySetting);\n // delay for completion of animated changing random number\n setTimeout(() => {\n window.gameboard.setupNewTurn(this.variableValue);\n $('#random-number-wrapper').removeClass(\"pulse\"); // stop random number element pulsing\n $('#click-to-play-instruction').text(\"Choose an expression...\"); // update instruction \n }, 2000);\n\n function generateVariableValue(difficultySetting) {\n let finalVariable = numberGenerator(difficultySetting); \n let count = 0;\n // setInterval schedules 10 function calls over 2 seconds. Script execution continues asynchronously.\n let intervalID = setInterval(() => {\n if (count === 9){\n updateVariableInDOM(finalVariable);\n clearInterval(intervalID);\n } else {\n let tempVariable = numberGenerator(difficultySetting);\n updateVariableInDOM(tempVariable);\n count += 1; \n } \n }, 200); \n return finalVariable;\n \n // uses getRandomRange function to produce a random number in required range\n function numberGenerator(difficultySetting){\n var randomVariable;\n if (difficultySetting == \"Easy\") {\n randomVariable = getRandomRange(-1, 5);\n } else { // difficultySetting === \"Hard\"\n randomVariable = getRandomRange(-5, 5);\n }\n return randomVariable;\n }\n }\n }\n }", "static ParseBindingss(bindings) {\n // We start out with a basic config\n const NAME = 'BTooltip';\n let config = {\n delay: getComponentConfig(NAME, 'delay'),\n boundary: String(getComponentConfig(NAME, 'boundary')),\n boundaryPadding: parseInt(getComponentConfig(NAME, 'boundaryPadding'), 10) || 0\n };\n // Process bindings.value\n if (isString(bindings.value)) {\n // Value is tooltip content (html optionally supported)\n config.title = bindings.value;\n }\n else if (isFunction(bindings.value)) {\n // Title generator function\n config.title = bindings.value;\n }\n else if (isObject(bindings.value)) {\n // Value is config object, so merge\n config = Object.assign({}, config, bindings.value);\n }\n // If argument, assume element ID of container element\n if (bindings.arg) {\n // Element ID specified as arg\n // We must prepend '#' to become a CSS selector\n config.container = `#${bindings.arg}`;\n }\n // Process modifiers\n keys(bindings.modifiers).forEach(mod => {\n if (/^html$/.test(mod)) {\n // Title allows HTML\n config.html = true;\n }\n else if (/^nofade$/.test(mod)) {\n // No animation\n config.animation = false;\n }\n else if (/^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$/.test(mod)) {\n // Placement of tooltip\n config.placement = mod;\n }\n else if (/^(window|viewport|scrollParent)$/.test(mod)) {\n // Boundary of tooltip\n config.boundary = mod;\n }\n else if (/^d\\d+$/.test(mod)) {\n // Delay value\n const delay = parseInt(mod.slice(1), 10) || 0;\n if (delay) {\n config.delay = delay;\n }\n }\n else if (/^o-?\\d+$/.test(mod)) {\n // Offset value, negative allowed\n const offset = parseInt(mod.slice(1), 10) || 0;\n if (offset) {\n config.offset = offset;\n }\n }\n });\n // Special handling of event trigger modifiers trigger is\n // a space separated list\n const selectedTriggers = {};\n // Parse current config object trigger\n let triggers = isString(config.trigger) ? config.trigger.trim().split(/\\s+/) : [];\n triggers.forEach(trigger => {\n if (validTriggers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n // Parse modifiers for triggers\n keys(validTriggers).forEach(trigger => {\n if (bindings.modifiers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n // Sanitize triggers\n config.trigger = keys(selectedTriggers).join(' ');\n if (config.trigger === 'blur') {\n // Blur by itself is useless, so convert it to 'focus'\n config.trigger = 'focus';\n }\n if (!config.trigger) {\n // Remove trigger config\n delete config.trigger;\n }\n return config;\n }", "static buildAnimation(st, z, d) {\n // Create\n let anim = Stage.Animation.build({\n base: d.frameBase,\n frames: d.nFrames,\n speed: d.speed,\n playType: d.playType,\n anchor: d.anchor,\n alpha: d.alpha,\n tint: d.tint,\n scale: d.scale,\n }, {\n stageTarget: st,\n z: z,\n });\n anim.visible = false; // will turn on first update\n return anim;\n }", "function createFactory(tag) {\n return createElement.bind(void 0, tag);\n }", "function createInputPlayer(){\n \n for(let i = 0; i < numberOfPlayers; ++i) {\n \n // create input for player name\n var inp = document.createElement(\"input\"); \n inp.setAttribute(\"placeHolder\", `Name of player ${i + 1}`); \n inp.setAttribute(\"class\", \"inPlayerName\")\n inp.setAttribute(\"id\", `inPlayer${i + 1}`); \n nameInputDiv.appendChild(inp); \n }\n}", "function PersonAnimator(){\r\n this.moveRandomly = function(){ /*..*/ };\r\n}", "function init() {\n createjs.Ticker.framerate = animateFps;\n Promise.all([Promise.all(initValueProviders()), Promise.all(initAnimates())]).then(() => {\n Promise.all([initWidgets()]).then(() => {\n resolveValueProviders();\n Object.entries(models).forEach(([, model]) => model.init());\n javascript.onBeforeModelRun.forEach(fn => fn());\n Object.entries(models).forEach(([, model]) => model.play());\n Object.entries(widgets).forEach(([, widget]) => widget.updateComponent());\n spinner.hide();\n });\n });\n}", "domCreation(text) {\n let elt = createTextualElt(\"video\", text, \"video-elt\");\n let srcElt = document.createElement(\"source\");\n srcElt.setAttribute(\"src\", `FishEye_Photos/Video/${this.src}`);\n elt.appendChild(srcElt);\n\n return elt;\n }", "function tweenIteration() {\n var iteration = d3.interpolateNumber(+label.text(), maxIteration);\n return function (t) {\n displayIteration(iteration(t));\n };\n }", "function setSourceVelocityFn(scope) {\n\tsource_velocity = scope.source_velocity_value; /** Setting the source speed based on the slider value */\n\tcircle_centre = 100; /**Resetting the circle radius while changing the slider */\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the total cost of a profession
async function getProfessionTotalCost (url) { let content = await fetch.single(url, { type: 'text' }) let $ = cheerio.load(content) // Get the first defined cost, that's the total cost let html = $('dd').eq(2).html() // Replace and split the icons for gold, silver and copper html = html.replace(/<span.+?<\/span>/g, '###') html = html.split('###') // Get a copper cost and return it return cleanGoldArray(html) }
[ "function calculateTotalCost(pricePerNight, noOfDays) {\n let obj = {}\n obj[\"cents\"] = pricePerNight * noOfDays;\n obj[\"dollars\"] = convertCentsToDollars(pricePerNight * noOfDays);\n return obj;\n}", "function aggregateTotalCost(cost) {\n\n let totalGreenSum = 0;\n let totalGreySum = 0;\n\n Object.values(cost).forEach((item) => {\n totalGreenSum = totalGreenSum + item.greenCost;\n totalGreySum = totalGreySum + item.greyCost;\n })\n\n const greenPercent = totalGreenSum / (totalGreySum + totalGreenSum) * 100;\n const greyPercent = 100 - greenPercent;\n\n return { greenCost: totalGreenSum.toFixed(2), greyCost: totalGreySum.toFixed(2), greenPercent: greenPercent.toFixed(1), greyPercent: greyPercent.toFixed(1) };\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}", "function calcStaff() {\n var num = document.getElementById(\"photognum\");\n var hrs = document.getElementById(\"photoghrs\");\n totalCost -= photographerCost;\n photographerCost = num.value*100*hrs.value;\n totalCost += photographerCost;\n document.getElementById(\"estimate\").innerHTML = \"$\" + totalCost;\n}", "calTotalCharged(){\n this._totalCharged = this._costPerHour * this._hoursParked;\n }", "function _get_total_cost() {\n var camp_iter = (LABEL == \"\") ? AdWordsApp.campaigns().get() :\n AdWordsApp.campaigns()\n .withCondition(\"LabelNames CONTAINS_ANY ['\"+LABEL+\"']\")\n .get();\n \n var tot_cost = 0;\n while(camp_iter.hasNext()) {\n tot_cost += camp_iter.next().getStatsFor(TIMEFRAME).getCost();\n }\n return tot_cost;\n}", "function calculateCost (pizza) {\n var price = 0;\n var sizeCost = pizza.determineSizeCost();\n var cheeseCost = pizza.determineCheeseCost();\n var sauceCost = pizza.determineSauceCost();\n var toppingsCost = pizza.determineToppingsCost();\n var meatsCost = pizza.determineMeatsCost();\n price = sizeCost + cheeseCost + sauceCost + toppingsCost + meatsCost;\n price = price.toFixed(2);\n return price;\n}", "totalFood() {\n return this.passengers.reduce((accumulator, passenger) => accumulator + passenger.food, 0)\n \n }", "function calcBonusMental(){\n\t\tvm.resultadoBonusMental = Math.floor(calculaBonus.retornaValorBonus(configuracao.intervaloMental, configuracao.multiplicadorMental, vm.attMental));\n\t}", "function calculateBonus() {\n return .02 * salary;\n}", "function getCarPrice(numRentalDays, vehicleCost)\n{\n \n let carPrice = numRentalDays * vehicleCost;\n\n return carPrice;\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 shippingCost(order)\n{\n return order.shipping_lines.reduce((total, sl) => total + parseFloat(sl.price), 0);\n}", "function calculateTotalBudget(movieObject){\n let totalBudget = movieObject.reduce((total, movieObject) => total + movieObject.budget, 0);\n console.log(\"1. What is the total budget of the ten most popular movies in the db? $\"+ totalBudget);\n}", "function calcAmount(cost, discount) {\n return cost - discount;\n}", "function sumarIva(precioCosto){\n return (precioCosto + precioCosto * 0.21);\n}", "function calculateReservationCostAndUpdateDOM(adventure, persons) {\n // TODO: MODULE_RESERVATIONS\n // 1. Calculate the cost based on number of persons and update the reservation-cost field\n let costPerHead = adventure.costPerHead;\n let totalReservationCost = costPerHead*persons;\n document.getElementById('reservation-cost').innerHTML = totalReservationCost;\n}", "function calculateTax() {\n return payGrades[getCadre()].taxMultiplier * salary;\n}", "function getCategoryTotalPoints(category){\n let htmlPath = \" > td.possible.points_possible\"; //HTML path to get to the total points within the table data (td)\n return sumTablePortion(htmlPath, category);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FadeInTransition class changes slides by fading in new slide. This class can be removed if effect is not used.
function FadeInTransition() {}
[ "function mFade() {\n\tgetId('t' + currTact).classList.add(\"faded\");\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 Transition() {}", "performSlide() {\n if (this.prevSlide) {\n this.prevSlide.removeClass('prev fade-out')\n }\n\n this.nextSlide.removeClass('next');\n this.prevSlide = this.nextSlide;\n this.prevSlide.addClass('prev');\n\n this.currentIndex++;\n if (this.currentIndex >= this.slides.length) {\n this.currentIndex = 0\n }\n\n this.setNextSlide();\n\n this.prevSlide.addClass('fade-out');\n }", "function transition(){\r\n document.querySelector('#cover').classList.add('disappear');\r\n document.querySelector('.result-wrapper').classList.add('result-appear');\r\n document.querySelector('#next').classList.add('next-appear');\r\n}", "function fadeIn() {\n if (fadingOut == true) {\n sendOSC('/composition/video/fadeout/direction', 1);\n fadingOut = false;\n }\n}", "function BasicTransition() {}", "function reattachFadeIn() {\n\t\tfor (var i = 1; i <= 3; i++) {\n\t\t\tfor (var j = 0; j < 16; j++) {\n\t\t\t\tvar menu_item = \"#\" + i + \"_\" + j;\n\t\t\t\t$(menu_item).addClass(\"fadein\");\n\t\t\t\t$(menu_item + \"copy\").addClass(\"fadein\");\n\t\t\t}\n\t\t}\n\t}", "function teardownFade() {\n fader.removeClass(\"show fadeOut\");\n }", "function TdFadeInOutAnimation(duration) {\n if (duration === void 0) { duration = 150; }\n return _angular_animations.trigger('tdFadeInOut', [\n _angular_animations.state('0', _angular_animations.style({\n opacity: '0',\n display: 'none',\n })),\n _angular_animations.state('1', _angular_animations.style({\n opacity: '*',\n display: '*',\n })),\n _angular_animations.transition('0 => 1', _angular_animations.animate(duration + 'ms ease-in')),\n _angular_animations.transition('1 => 0', _angular_animations.animate(duration + 'ms ease-out')),\n ]);\n}", "function FadeInSection(props) {\n const [isVisible, setVisible] = React.useState(false);\n const domRef = React.useRef();\n React.useEffect(() => {\n const observer = new IntersectionObserver((entries) => {\n entries.forEach((entry) => setVisible(entry.isIntersecting));\n });\n observer.observe(domRef.current);\n }, []);\n return (\n <div\n className={`fade-in-section ${isVisible ? \"is-visible\" : \"\"}`}\n ref={domRef}\n >\n {props.children}\n </div>\n );\n}", "function buttonFade() {\n $(\".open-btn-host\").removeClass(\"display-none\");\n $(\".open-btn-host\").addClass(\"call-fade\");\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 }", "fade (nextState)\n {\n this.nextState = nextState;\n\n const fadeBackground = this.game.add.graphics(0, 0);\n fadeBackground.beginFill(0xFFFFFF, 1);\n fadeBackground.drawRect(0, 0, this.game.width, this.game.height);\n fadeBackground.alpha = 0;\n fadeBackground.endFill();\n\n const backgroundTween = this.game.add.tween(fadeBackground);\n backgroundTween.to({ alpha: 1 }, 500, null);\n backgroundTween.onComplete.add(this.changeState, this);\n backgroundTween.start();\n }", "function removeAllFadeClasses() {\n var id = ['#cexperiencia', '#chome', '#chabilidades', '#cformacao'];\n for(var i = 0; i < id.length; i++) {\n $(id[i]).fadeOut(\"slow\");\n }\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 fadeInFadeOut(currentSentence) {\n let counter = 0;\n let fadeInTimer = setInterval(() => {\n currentSentence.childNodes[counter].classList.add('fade-in');\n counter++;\n if (counter == currentSentence.childNodes.length) {\n clearInterval(fadeInTimer);\n fadeOut(currentSentence); // Fade-out the current sentence\n let nextSentence = currentSentence.nextElementSibling; // Target the next sentence\n startSentence(nextSentence); // Start fade-in the next intro sentence\n }\n }, CHARACTER_INTERVAL); // Timer to fade-in each character of the sentence\n}", "function slideInNav() {\n $mainNavContainer.toggleClass('visible'); \n $contentContainer.toggleClass('main-nav-showing');\n $breadcrumb.toggleClass('push-over');\n }", "function addFadeOutAnimation(ID) {\n removeLoopingVideo(slide5LoopVideo, 4000);\n document.getElementById(ID).classList.add(\"fadeOutAnimation\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
take a start angle in deg, an end angle in deg, and a number and provide an evenly spaced array of radians between the start and end
function tween(start, end, number) { let interval = (end - start) / number const degrees = [] for (let i = 1; i <= number; i++) { degrees.push(start + interval * i) } return degrees.map(d => (d * Math.PI) / 180) }
[ "function createArrayFromNumberSequence ( start, end ) {\n\tvar result;\n\n\tif ( typeof start === 'number' && typeof end === 'number' && start <= end ) {\n\t\tresult = Array.apply(null, { length: ( end - start + 1 ) } )\n\t\t\t.map(Number.call, Number)\n\t\t\t.map( function( i ) { return i + start; } );\n\t} else {\n\t\tresult = [];\n\t}\n\treturn result;\n}", "function lerpAnglesInRadians(i, min, max) {\n if (isNaN(i) || i <= 0.0) {\n return min % TwoPI;\n }\n else if (i >= 1.0) {\n return max % TwoPI;\n }\n const a = (min - max + TwoPI) % TwoPI;\n const b = (max - min + TwoPI) % TwoPI;\n if (a <= b) {\n return (min - a * i + TwoPI) % TwoPI;\n }\n return (min + a * i + TwoPI) % TwoPI;\n}", "function polarAdd(origin, angle, length) {\n const x = origin[0];\n const y = origin[1];\n return [\n x + Math.cos(angle * 2 * Math.PI / 360) * length,\n y + -1.0 * Math.sin(angle * 2 * Math.PI / 360) * length,\n ];\n}", "function calcAngle(startPosition, endPosition) {\n let angle = 0;\n\n if (endPosition < startPosition) {\n angle = PI * 2 - Math.abs(endPosition - startPosition);\n } else if (endPosition > startPosition) {\n angle = endPosition - startPosition;\n }\n\n return angle;\n}", "function linspace(start, stop, n) {\n let arr = [];\n let step = (stop - start) / (n - 1);\n for (let i = 0; i < n; i++) {\n arr.push(start + step * i);\n }\n return arr;\n}", "function rotate(nx, ny , a){\n let x = nx, y =ny\n let t = a* Math.PI / 180.0\n nx = x * Math.cos(t) - y * Math.sin(t)\n ny = x * Math.sin(t) + y * Math.cos(t)\n return [nx, ny]\n}", "function range(start, end, increment) {\n var myArr = [];\n var incr;\n if (increment === undefined) {\n incr = 1;\n } else {incr = increment};\n if (start == end) {\n return myArr;\n } else if (start < end && incr > 0) {\n while (start <= end) {\n myArr.push(start);\n start += incr;\n }} \n return myArr;\n }", "function lerpAnglesInDegrees(i, min, max) {\n if (i <= 0.0) {\n return min % 360.0;\n }\n else if (i >= 1.0) {\n return max % 360.0;\n }\n const a = (min - max + 360.0) % 360.0;\n const b = (max - min + 360.0) % 360.0;\n if (a <= b) {\n return (min - a * i + 360.0) % 360.0;\n }\n return (min + a * i + 360.0) % 360.0;\n}", "getIntervalSteps (start, end, asIndex) {\n\t\tlet totalSteps = this.getTotalStepCount();\n\t\tlet ref = this.tzero;\n\t\tstart -= ref;\n\t\tstart /= (60 * 1000);\n\t\tstart = Math.ceil(start / this.getStepInterval());\n\t\tend -= ref;\n\t\tend /= (60 * 1000);\n\t\tend = Math.floor(end / this.getStepInterval());\n\t\tlet ret = [];\n\t\tfor (let i=start; i<=end; i++) {\n\t\t\tif (asIndex) {\n\t\t\t\tlet index = i;\n\t\t\t\twhile (index < 0)\n\t\t\t\t\tindex += totalSteps;\n\t\t\t\tret.push(index % totalSteps);\n\t\t\t}\n\t\t\telse\n\t\t\t\tret.push(i);\n\t\t}\n\t\treturn ret;\n\t}", "function orderedRegion(start, end) {\n end = typeof end === \"number\" ? end : start;\n return [Math.min(start, end), Math.max(start, end)];\n }", "function calcAngle(a, b) {\n return Math.atan2(b[1] - a[1], b[0] - a[0]) * 180 / Math.PI;\n}", "subtractAngles (rad1, rad2) {\n const PI = Math.PI\n let dr = rad1 - rad2\n if (dr <= -PI) dr += 2 * PI\n if (dr > PI) dr -= 2 * PI\n return dr\n }", "function convertPath(start, end) {\n var arcIds = [],\n firstNodeId = -1,\n arcStartId;\n\n // Visit each point in the path, up to but not including the last point\n for (var i = start; i < end; i++) {\n if (pointIsArcEndpoint(i)) {\n if (firstNodeId > -1) {\n arcIds.push(addEdge(arcStartId, i));\n } else {\n firstNodeId = i;\n }\n arcStartId = i;\n }\n }\n\n // Identify the final arc in the path\n if (firstNodeId == -1) {\n // Not in an arc, i.e. no nodes have been found...\n // Assuming that path is either an island or is congruent with one or more rings\n arcIds.push(addRing(start, end));\n }\n else if (firstNodeId == start) {\n // path endpoint is a node;\n if (!pointIsArcEndpoint(end)) {\n error(\"Topology error\"); // TODO: better error handling\n }\n arcIds.push(addEdge(arcStartId, i));\n } else {\n // final arc wraps around\n arcIds.push(addSplitEdge(arcStartId, end, start + 1, firstNodeId));\n }\n return arcIds;\n }", "function generateOval(center, a, b, howManyPoints) {\n if (howManyPoints === void 0) { howManyPoints = 360; }\n // 参数方程\n var theta = 0.0; // in DEG\n var step = 360 / howManyPoints;\n var res = [];\n for (var i = 0; i < howManyPoints; i++) {\n res.push([a * Math.cos(radians(theta)) + center[0], b * Math.sin(radians(theta)) + center[1]]);\n theta += step;\n }\n return res;\n }", "function clockwise_angle(pt, centre) {\n var recentred = sum(pt, scale(-1., centre));\n var anticlockwise_angle = Math.atan2(recentred[1], recentred[0]);\n return -1 * anticlockwise_angle;\n}", "function ang(t) {\n return {\n x: cos(t),\n y: sin(t),\n };\n }", "static FromRadians(radians) {\n return new Angle(radians);\n }", "function clockwise_arc_length(angle0, angle1) {\n var diff = angle1 - angle0;\n while (diff < 0) {\n diff = diff + 2 * Math.PI;\n }\n return diff;\n}", "function angularCoord(x, y)\n {\n var phi = 0.0;\n\n if (x > 0 && y >= 0) {\n phi = Math.atan(y / x);\n }\n if (x > 0 && y < 0) {\n phi = Math.atan(y / x) + 2 * Math.PI;\n }\n if (x < 0) {\n phi = Math.atan(y / x) + Math.PI;\n }\n if (x = 0 && y > 0) {\n phi = Math.PI / 2;\n }\n if (x = 0 && y < 0) {\n phi = 3 * Math.PI / 2;\n }\n\n return phi;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log(filterProducts('A', arrOfProducts)) console.log(filterProducts('S', arrOfProducts)) No. 4
function printProducts(products){ for(let i = 10; i < 36; i++){ let letter = i.toString(36) letter = letter.toUpperCase() let filteredProducts = filterProducts(letter, products) if (filteredProducts.length > 0) { console.log('===' + letter + '===') for(let j = 0; j < filteredProducts.length; j++){ if (filteredProducts.length - 1 === j){ console.log(filteredProducts[j] + '\n') } else { console.log(filteredProducts[j]) } } } } }
[ "function getProduct(identifier, filter) {\n var productsFiltered = [];\n $(\".productlist\").empty();\n\n//uit 'products' worden de key en de value gehaald (key = 1 record en value de waarden die erin zitten)\n//als de array met de meegegeven 'soort' gelijk is aan de filter 'soortnaam' wordt de decorateProduct functie uitgevoerd\n $.each(products, function(key, val) {\n if(val[identifier] === filter) {\n decorateProduct(productsFiltered, val);\n }\n });\n\n $( \"<ul/>\", {\n \"class\": \"myUL\",\n html: productsFiltered.join(\"\")\n }).appendTo( \"#lijst\" );\n}", "filterShops(prod) {\n if(!prod.length) {\n this.shops = this.shops.map(el => { \n el.active = true;\n return el;\n });\n return this.shops;\n }\n\n const filteredShops = this.shops.filter(el => prod.every(product => el.productsids.find(i => product === i)));\n \n this.shops = this.shops.map(el => {\n if(filteredShops.indexOf(el) === -1) { \n el.active = false;\n return el;\n }\n el.active = true;\n return el;\n });\n return this.shops;\n }", "function nonSelected(products, selectedProducts){\n\n let newArray = products.slice();\n\n newArray.splice(newArray.findIndex(item => item === selectedProducts), 1);\n\n console.log(newArray)\n\n return newArray;\n }", "filterBySize(products, size) {\n // ----Logic\n }", "function onFilterChange () {\n self.prodSelected = false;\n if (self.filterVal === \"All\") {\n self.filteredProducts = [];\n self.filteredProducts = self.products;\n } else if (self.filterVal === \"Less Than $500\") {\n self.filteredProducts = [];\n for (let i = 0; i < self.products.length; i++) {\n if (self.products[i].price < 500) {\n self.filteredProducts.push(self.products[i]);\n }\n }\n } else if (self.filterVal === \"From $500 to $1000\") {\n self.filteredProducts = [];\n for (let i = 0; i < self.products.length; i++) {\n if (self.products[i].price >= 500 && self.products[i].price < 1000) {\n self.filteredProducts.push(self.products[i]);\n }\n }\n } else if (self.filterVal === \"From $1000 to $2000\") {\n self.filteredProducts = [];\n for (let i = 0; i < self.products.length; i++) {\n if (self.products[i].price >= 1000 && self.products[i].price < 2000) {\n self.filteredProducts.push(self.products[i]);\n }\n }\n } else if (self.filterVal === \"$2000 or more\") {\n self.filteredProducts = [];\n for (let i = 0; i < self.products.length; i++) {\n if (self.products[i].price >= 2000) {\n self.filteredProducts.push(self.products[i]);\n }\n }\n }\n }", "function filterPizza(filter) {\n\n if(filter == PizzaType.Any){\n showPizzaList(Pizza_List);\n return Pizza_List.length;\n }\n\n //Масив куди потраплять піци які треба показати\n var pizza_shown = [];\n\n\n Pizza_List.forEach( function(pizza) {\n if(filter in pizza.content){\n pizza_shown.push(pizza);\n }\n });\n\n Pizza_List.forEach( function(pizza) {\n if(!(PizzaType.Meat in pizza.content) && !(PizzaType.Ocean in pizza.content) && filter==PizzaType.Vega){\n pizza_shown.push(pizza);\n }\n });\n \n //Показати відфільтровані піци\n showPizzaList(pizza_shown);\n return pizza_shown.length;\n}", "function searchProductList(searchKey){\n console.log(productLists);\n const searchedList = productLists.filter((product) =>{\n return product.name.toLowerCase().includes(searchKey.toLowerCase())});\n console.log(searchedList);\n return searchedList;\n}", "function getProductsSansIndex(array) {\n var finalAnswer = []; //gonna put each product in here\n var result = array.map(function (currentVal, currentIndex) { //map over the array\n var product = array.filter(function (filteredValue, filteredIndex) { //filter out the index\n return filteredIndex !== currentIndex; //get the values where the current place in the map are not equal to the current place in the filter\n })\n .reduce(function (total, currentValue) { //multiply the array values\n return total * currentValue;\n });\n finalAnswer.push(product); //push the final product to the final answer\n });\n return finalAnswer;\n}", "function renderFilterResults(filters, products) {\n // This array contains all the possible filter criteria.\n var criteria = ['maquillaje', 'CuidadoPiel', 'CuidadoCabello', 'CuidadoCuerpo'],\n results = [],\n isFiltered = false;\n\n // Uncheck all the checkboxes.\n // We will be checking them again one by one.\n checkboxes.prop('checked', false);\n\n\n criteria.forEach(function(elm) {\n // Check if each of the possible filter criteria is actually in the filters object.\n if (filters[elm] && filters[elm].length) {\n // After we've filtered the products once, we want to keep filtering them.\n // That's why we make the object we search in (products) to equal the one with the results.\n // Then the results array is cleared, so it can be filled with the newly filtered data.\n if (isFiltered) {\n products = results;\n results = [];\n }\n\n\n // In these nested 'for loops' we will iterate over the filters and the products\n // and check if they contain the same values (the ones we are filtering by).\n\n // Iterate over the entries inside filters.criteria (remember each criteria contains an array).\n filters[elm].forEach(function(filter) {\n // Iterate over the products.\n products.forEach(function(item) {\n // If the product has the same specification value as the one in the filter\n // push it inside the results array and mark the isFiltered flag true.\n\n if (typeof item.price[elm] === 'number') {\n if (item.price[elm] == filter) {\n results.push(item);\n isFiltered = true;\n }\n }\n\n if (typeof item.condition[elm] === 'string') {\n if (item.condition[elm].toLowerCase().indexOf(filter) !== -1) {\n results.push(item);\n isFiltered = true;\n }\n }\n });\n\n // Here we can make the checkboxes representing the filters true,\n // keeping the app up to date.\n if (elm && filter) {\n $('input[name=' + elm + '][value=' + filter + ']').prop('checked', true);\n }\n });\n }\n });\n\n // Call the renderProductsPage.\n // As it's argument give the object with filtered products.\n renderProductsPage(results);\n}", "function displayProducts(products) {\n for (const product of products) {\n displayProduct(product);\n }\n}", "filter(fn) {\n let newSet = new SpecialSet();\n // copy over elements that pass the filter\n for (let item of this) {\n if (fn(item) === true) {\n newSet.add(item);\n }\n }\n return newSet;\n }", "function filterByFirstName(arr, letter) {\n}", "function getProductByTitle(parent, args) {\n return productList.filter(product => product.title === args.title);\n}", "function tripleAndFilter(arr){\n return arr.map(value=> value * 3).filter(value => value % 5 === 0);\n}", "filter (p) {\n return filter(p, this)\n }", "function getBrandsFromProducts (products) {\n\treturn [...new Set(products.map(product => product.brand))];\n}", "function destroyer(arr) {\n // console.log(arr);\n // [ 1, 2, 3, 1, 2, 3 ]\n\n\n // console.log(arguments);\n // [Arguments] { '0': [ 1, 2, 3, 1, 2, 3 ], '1': 2, '2': 3 }\n\n\n // const argsArr = Array.from(arguments);\n // console.log(argsArr)\n // [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ]\n\n \n // ANOTHER WAY TO DO IT\n // const argsArr = [...arguments]; //this is called spreading. We're separating all the arguments using commas.\n // console.log(argsArr)\n // [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ]\n\n const argsArr = [...arguments].slice(1)\n\n const filteredArr = [];\n for (let i = 0; i < arr.length; i++) {\n if (!argsArr.includes(arr[i])) {\n filteredArr.push(arr[i])\n } \n }\n return filteredArr\n}", "async function _filter_for_sizes (variants, sizes){\n let ret = [];\n \n /*\n * If both sizes aren't defined, return everything (not ideal I know but until\n * we settle down regarding product types this is the least terrible option)\n */\n \n if (!sizes.top || !sizes.bottom){\n return variants;\n }\n \n for (let i = 0; i < variants.length; i++){\n // if a recognised 'top' type\n if (_product_type_tops.includes(variants[i].product_type)){\n // check for multiple sizes in sizes.top\n if (!Array.isArray(sizes.top)){\n // if a single size then push all variants with a size that matches\n if(variants[i].opt2 == sizes.top){\n ret.push(variants[i]);\n }\n }else if (sizes.top.includes(variants[i].opt2)){\n // else if array of sizes then check array for matchinf size and push\n ret.push(variants[i]);\n }\n // else if a recognised 'bottom' type....same again\n }else if (_product_type_bottoms.includes(variants[i].product_type)){\n if (!Array.isArray(sizes.bottom)){\n if(variants[i].opt2 == sizes.bottom){\n ret.push(variants[i]);\n }\n }else if (sizes.bottom.includes(variants[i].opt2)){\n ret.push(variants[i]);\n }\n // else if misc product type e.g hats, accessories etc.\n }else if (_product_type_misc.includes(variants[i].product_type)){\n // if size is One Size Fits All, then push\n if (variants[i].opt2 == 'OSFA'){\n ret.push(variants[i]);\n }\n \n // TODO: need to do better for socks and other misc items - map sizes\n }\n }\n\n return ret;\n}", "function filterItems(arr, query) {\r\n return arr.filter(function(el) {\r\n return el.toLowerCase().indexOf(query.toLowerCase()) !== -1\r\n })\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read global YUI, extract internal modulenames and whitelist them
function readGlobalYUI(callback) { console.log("reading global ENV from yui.js [" + YUIVersion + "]"); http.request({ host : "yui.yahooapis.com", path : "/" + YUIVersion + "/build/yui/yui.js" }, function(resp){ var _yuiRaw = ""; resp.on('data', function(data){ _yuiRaw += data; }); resp.on('end', function(){ whiteList = findYUIAdd(esprima.parse(_yuiRaw, {tokens : true}).body); setTimeout(callback, 1000); }); }).end(); }
[ "function getMyY() {\r\n if (typeof(myY) != \"undefined\" && myY != null) {\r\n //alert('myY was set, returning.');\r\n return myY;\r\n } else {\r\n //alert('no myY, creating and returning.');\r\n // Create global YUI3 instance\r\n myY = YUI({ filter:'raw' });\r\n return myY;\r\n }\r\n}", "function getMyY() {\n if (typeof(myY) != \"undefined\" && myY != null) {\n //alert('myY was set, returning.');\n return myY;\n } else {\n //alert('no myY, creating and returning.');\n // Create global YUI3 instance\n myY = YUI({ filter:'raw' });\n return myY;\n }\n}", "function findLifeSupportModule(){\n \n for(var i = 0; i < availableModules.length; i++){\n if(availableModules[i].name == \"life-support\") {\n availableModules[i].enabled = true; //enable the module first\n loadModule(i); //load module into modules array\n }\n }\n}", "function src(...modules) {\n return filter(...modules).map(d => d.src)\n}", "function loadOptionsAndGlobals() {\r\t\"use strict\";\r\t\r\tvar parentFolder,\r\t\toptionsText,\r\t\tglobalsText,\r\t\ttextStream,\r\t\tskipFilesText;\r\t\r\t//get the parent folder path\r\tparentFolder = new File(module.filename).parent.path;\r\t\r\t//yank in the options\r\ttextStream = new TextStream(parentFolder + \"jslint_options.json\");\r\toptionsText = textStream.read(0);\r\ttextStream.close();\r\tjslint_options = JSON.parse(optionsText);\r\t\r\t//yank in the globals\r\ttextStream = new TextStream(parentFolder + \"jslint_globals.json\");\r\tglobalsText = textStream.read(0);\r\ttextStream.close();\r\tjslint_options.predef = JSON.parse(globalsText);\r\t\r\t//also load the skip files\r\ttextStream = new TextStream(parentFolder + \"skip_files.json\");\r\tskipFilesText = textStream.read(0);\r\ttextStream.close();\r\tskipFiles = JSON.parse(skipFilesText);\r\t\r}", "function getModules() {\n return _modules.concat();\n }", "function extract_all_objs ( mod ) {\n var out = [];\n function extract ( obj ) {\n if ( obj.canonical_name === undefined ) {\n throw 'No canonical name!';\n }\n out.push ( obj );\n if ( obj.objects !== undefined ) {\n obj.objects.forEach ( function ( child ) {\n extract ( child );\n } );\n }\n }\n mod.globals.each_text ( function ( key, glob ) {\n extract ( get_canonical_value ( glob ) );\n } );\n return out;\n }", "loadModCommands(mod) {\n fs.readdirSync(mod.moduleFolder).forEach(file => {\n try {\n const fileLoc = path.resolve(mod.moduleFolder, file);\n\n if (!fs.statSync(fileLoc).isFile()) { return; }\n if (file === 'index.js') { return; }\n\n if (file.startsWith('_')) {\n this.bot.debug(`Skipped command '${mod.id}.${path.parse(file).name}' for preceding underscore`);\n return;\n }\n\n this.loadCommandFile(mod, file, true);\n } catch (error) {\n this.bot.error(`${error}`);\n }\n });\n }", "function buildModules() {\n // loop through modules\n for (var i = 0, l = modules.length; i < l; i++) {\n var options = modules[i].options;\n // process styles\n var styleData;\n // loop through options\n for (var j = 0, m = options.length; j < m; j++) {\n if (options[j].isEnabled && options[j].head && options[j].head.css && (styleData = options[j].head.css) != null) {\n // loop through lines\n for (var k = 0, n = styleData.length; k < n; k++) {\n styles += '\\n ' + styleData[k];\n }\n styles += '\\n';\n }\n }\n\n // process head scripts\n var scriptData,\n fields = {};\n // loop through options\n for (var j = 0, m = options.length; j < m; j++) {\n if (options[j].isEnabled && options[j].head && options[j].head.js && (scriptData = options[j].head.js)) {\n // loop through lines\n for (var k = 0, n = scriptData.length; k < n; k++) {\n headScripts += '\\n ' + scriptData[k];\n }\n headScripts += '\\n';\n }\n if (options[j].fields && options[j].fields.length > 0) {\n // loop through fields\n for (var k = 0, n = options[j].fields.length; k < n; k++) {\n fields[options[j].fields[k].name] = options[j].fields[k].val;\n }\n }\n }\n _min.push(JSON.stringify(fields));\n\n // process body scripts\n var scriptData;\n // loop through options\n for (var j = 0, m = options.length; j < m; j++) {\n if (options[j].isEnabled && options[j].load && (scriptData = options[j].load.js)) {\n // loop through lines\n for (var k = 0, n = scriptData.length; k < n; k++) {\n bodyScripts += '\\n ' + scriptData[k];\n }\n bodyScripts += '\\n';\n }\n }\n\n // populate variables\n bodyScripts = bodyScripts.replace(/_min\\./g, '_min[' + i + '].');\n headScripts = headScripts.replace(/_min\\./g, '_min[' + i + '].');\n while (styles.indexOf('_min.') != -1) {\n styles = styles.replace(styles.substring(styles.indexOf('_min.'), styles.indexOf(' ', styles.indexOf('_min.'))), JSON.parse(_min[i])[styles.substring(styles.indexOf('_min.') + 5, styles.indexOf(' ', styles.indexOf('_min.')))]);\n }\n }\n headScripts = '\\n var _min = [' + _min + '];' + headScripts;\n}", "function getYepnope () {\n var y = yepnope;\n y.loader = {\n load: load,\n i : 0\n };\n return y;\n }", "function getParserList() {\n\n if (parserList === undefined) {\n\n var bundleParsers = [], files, bundlePath;\n\n // Application bundled\n bundlePath = path.resolve(path.join(__dirname, \"parser\"));\n files = fs.readdirSync(bundlePath);\n files.forEach(\n function (fileName) {\n\n var parser, parserPath;\n\n if (path.extname(fileName) === \".js\") {\n\n parserPath = path.join(bundlePath, fileName);\n try {\n parser = require(parserPath);\n } catch(ex) {\n console.error(\"Could not find parser %s. File not found or open error\", ex);\n }\n if (parser !== undefined && parser.disabled !== true && typeof parser.parsePage === \"function\") {\n\n fileName = path.basename(fileName, \".js\");\n parsers[fileName] = parser;\n\n bundleParsers.push(\n {\n name: fileName,\n label: parser.label,\n description: parser.description,\n isBundled: true\n }\n );\n }\n }\n }\n );\n\n // User\n // TODO : Charger les parsers du dossier utilisateur\n\n\n parserList = bundleParsers;\n }\n\n return parserList;\n}", "static GetImporters() {}", "function loaded() {\n var m = null,\n pending = [];\n\n for (m in modules) {\n if (modules.hasOwnProperty(m) && modules[m].name === undefined) {\n pending.push(m);\n }\n }\n\n if (pending.length === 0) {\n console.log('core::loaded,', 'all modules loaded');\n link();\n }\n }", "function filter(...modules) {\n return modules.map(name => DEPENDENCIES[name])\n}", "function loadAPIs(){\n\t\t\n\t\t//load youtube api\n\t\tif(g_temp.isYoutubePresent)\n\t\t\tg_ugYoutubeAPI.loadAPI();\n\t\t\n\t\tif(g_temp.isVimeoPresent)\n\t\t\tg_ugVimeoAPI.loadAPI();\n\t\t\n\t\tif(g_temp.isHtml5VideoPresent)\n\t\t\tg_ugHtml5MediaAPI.loadAPI();\n\t\t\n\t\tif(g_temp.isSoundCloudPresent)\n\t\t\tg_ugSoundCloudAPI.loadAPI();\n\t\t\n\t\tif(g_temp.isWistiaPresent)\n\t\t\tg_ugWistiaAPI.loadAPI();\n\t\t\n\t}", "static get DEFINITION_FILES() {\n return [\n 'core-concepts.js',\n 'layout.js',\n 'flexbox-and-grid.js',\n 'spacing.js',\n 'sizing.js',\n 'typography.js',\n 'backgrounds.js',\n 'borders.js',\n 'effects.js',\n 'filters.js',\n 'tables.js',\n 'transitions-and-animation.js',\n 'transforms.js',\n 'interactivity.js',\n 'svg.js',\n 'accessibility.js',\n ]\n }", "getOwnFiles() {\n return this.cache.getOrAdd('getOwnFiles', () => {\n let result = [\n this.xmlFile\n ];\n let scriptPkgPaths = this.xmlFile.getOwnDependencies();\n for (let scriptPkgPath of scriptPkgPaths) {\n let file = this.program.getFileByPkgPath(scriptPkgPath);\n if (file) {\n result.push(file);\n }\n }\n return result;\n });\n }", "function GruntFilesArrayExt ()\n{}", "function getAvailableModules() {\n var files = fs.readdirSync(__dirname),\n modules = {\n routes: [],\n views: []\n };\n\n files.forEach(function(file) {\n var filePath = path.join(__dirname, file),\n routePath = path.join(filePath, 'routes.js'),\n viewsPath = path.join(filePath, 'views'),\n stat;\n\n stat = fs.statSync(filePath);\n\n if (stat.isDirectory()) { // is a module\n if (fs.existsSync(routePath)) { // routes.js file is required\n modules.routes.push(require(routePath));\n modules.views.push(viewsPath);\n }\n }\n });\n\n return modules;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the conversation state for the given user in the database.
async function __handleFlowUpdateConversationState (flow, recUser) { const database = this.__dep(`database`); let changes; // If we get this far with a basic flow and no prompt, then the conversation flow is finished. if (flow.definition.type === `basic` && !flow.definition.prompt) { changes = { 'conversation.previousStepUri': recUser.conversation.currentStepUri, 'conversation.currentStepUri': null, 'conversation.waitingOnPrompt': false, }; } // Otherwise, update the user record to mark that we're on this flow. else { changes = { 'conversation.previousStepUri': recUser.conversation.currentStepUri, 'conversation.currentStepUri': flow.uri, 'conversation.waitingOnPrompt': Boolean(flow.definition.prompt), }; } await database.update(`User`, recUser, changes); }
[ "setUserUpdateStatus( state, status ){\n state.userUpdateStatus = status;\n }", "updateUserToShell() {\n const user = this.authService.readUserFromSessionStorage();\n this.postMessageToShell(MessageType.user, user);\n }", "SET_USER(state, data) {\n state.user.data = data;\n }", "async updateUserInformations() {\n try{\n this.user = await this.get(\"users/me/\");\n store.dispatch('updateUser', this.user);\n window.sessionStorage.setItem(\"user\", JSON.stringify(this.user));\n } catch(error){\n console.log(\"Error while updating user info \" + error);\n }\n }", "updateConversation(toneAnalyzerPayload) {\n const lastConversationTurn = this.state.conversation.utterances[this.state.conversation.utterances.length - 1];\n const newConversationTurn = this.createConversationTurn(\n lastConversationTurn.id + 1,\n toneAnalyzerPayload.utterances_tone[0],\n lastConversationTurn.user.type === 'agent' ? 'customer' : 'agent',\n 'user',\n 'now',\n );\n\n // push new conversation turn to the conversation state and setState\n const conversation = this.state.conversation;\n const newUtteranceAvatarType = newConversationTurn.user.type === 'agent' ? 'customer_avatar' : 'agent_avatar';\n const newUtterancePlaceholder = newConversationTurn.user.type === 'agent' ? this.state.conversation.agent.handle : this.state.conversation.customer.handle;\n conversation.utterances.push(newConversationTurn);\n this.setState({\n conversaton: conversation,\n newUtterancePlaceholder,\n newUtteranceAvatarType,\n });\n }", "function changeUserRoom(userid, room_name){\n users[userid].roomid = room_name;\n saveState();\n}", "mutateRerollUser() {\n this.mutate((state) => {\n state.previousUserId = state.currentUserId;\n state.currentUserId = this.getNewStudentId();\n });\n }", "function updateUser(user_id) {\n user = {\n Id: user_id,\n First_name: prevName.innerHTML,\n Last_name: prevLast.innerHTML,\n Password: prevPassword.innerHTML,\n IsAdmin: previsAdminCB.checked\n }\n ajaxCall(\"PUT\", \"../api/Users\", JSON.stringify(user), updateUser_success, updateUser_error);\n}", "async changeUserSeatState(seatID, userID) {\n if (userID === this.state.user.id) {\n let userID = this.state.user.id;\n let username = this.state.user.username;\n let newSeats = this.state.user.userSeats;\n if (newSeats.includes(seatID))\n newSeats = newSeats.filter(e => e !== seatID);\n else newSeats.push(seatID);\n await fetch(\n \"http://\" +\n window.location.hostname +\n \":8080/api/users/\" +\n this.state.user.id,\n {\n method: \"PUT\",\n body: JSON.stringify({\n id: this.state.user.id,\n username: this.state.user.username,\n userSeats: newSeats\n }),\n headers: {\n \"Content-type\": \"application/json; charset=UTF-8\"\n }\n }\n );\n this.setState({\n user: {\n id: userID,\n username: username,\n userSeats: newSeats\n }\n });\n }\n }", "function selectUserForEdit(user) {\n setUserData(user)\n }", "function linkUser(User, facebookId, messengerId, promise) {\n User.update({facebook_id: facebookId}, {messenger_id: messengerId})\n .then(updatedUser => promise.resolve(updatedUser[0]))\n .catch(promise.reject);\n}", "async updateUser () {\n\t\tconst email = this.request.body.toEmail;\n\t\tconst op = {\n\t\t\t$set: {\n\t\t\t\temail,\n\t\t\t\tsearchableEmail: email.toLowerCase(),\n\t\t\t\tmodifiedAt: Date.now()\n\t\t\t}\n\t\t};\n\t\tthis.updateOp = await new ModelSaver({\n\t\t\trequest: this,\n\t\t\tcollection: this.data.users,\n\t\t\tid: this.user.id\n\t\t}).save(op);\n\t}", "function activeUser()\r\n{\r\n if(getCurrentUserIDFromLocalStorage() != null)\r\n {\r\n var currentUserID = getCurrentUserIDFromLocalStorage();\r\n\r\n db.collection('ActiveUsers').doc(currentUserID).set({\r\n active: true\r\n }).then(function() {\r\n console.log(\"Active list Update!\");\r\n });\r\n }\r\n}", "function UpdateUser() {\n\n\tvar client = new SpiderDocsClient(SpiderDocsConf);\n\n\tclient.GetUser('administrator', 'Welcome1')\n\t\n .then(function (user) {\n user.name = 'Hyper!'\n\t\tdebugger;\n return client.UpdateUser(user, 'administrator', 'Welcome1');\n })\n .then(function (user) {\n debugger;\n });\n}", "function parseIncomingMSGSession(user_id, messageItem, userObj) {\n\tvar current_state = \"welcome_message\";\n\tif (userObj != null) {\n\t\tcurrent_state = userObj.current_state;\n\t}\n\t// If we recieve any text message, parse and respond accordingly\n\tif (messageItem.message && messageItem.message.text) {\n\t\t// Currently support a static welcome message only\n\t\tsendFacebookGenericMsg(user_id, message_templates.templates[\"welcome_message\"]);\n\t}\n\t// If the user sends us a button click\n\tif (messageItem.postback && messageItem.postback.payload) {\n\t\tvar button_payload_state = messageItem.postback.payload;\n\t\tswitch (button_payload_state) {\n\t\t\tcase \"get_options\":\n\t\t\t\tsendFacebookGenericMsg(user_id, message_templates.templates[\"options_message\"]);\n\t\t\t\tbreak;\n\t\t\tcase \"no_options\":\n\t\t\t\tsendFacbookTextMsg(user_id, \"Ok. There is so much you can do with stateful bots!\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t// Save new user state. If user does not exist in DB, will create a new user.\n\tdb_utils.setUserFieldById(user_id, \"current_state\", \"\");\n}", "function getStatusMessage(user) {\n return Object.assign({ channel: user }, onboarding.welcome, users[user]);\n}", "update(userInfo) {\n const userID = this.findIdBySlug(userInfo.username);\n this._collection.update(userID, { $set: userInfo });\n }", "switchUser() {\n this.currentPlayer = this.currentPlayer == 1 ? 0 : 1;\n this.io.to(this.id).emit('g-startTurn', this.players[this.currentPlayer]);\n }", "givePermission() {\n const { id, userIdsWithPermission, documentCreatedBy } = this.state;\n userIdsWithPermission.map((userId) => {\n Meteor.call('upsertUserDocument', userId, id, documentCreatedBy, (error, result) => {\n if(error) {\n console.log(\"Fail to upsert the user\", error.reason);\n } else {\n console.log(\"Yay upserted successfully\");\n }\n });\n // TODO: Below setState not working properly\n // this.setState({\n // availableUsersForPermission: this.state.availableUsersForPermission\n // .filter( u => u._id !== userId)\n // })\n //TODO: Later, write a function to send emails to all permitted users.\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
muestra la modal para Crear un Usuario
function modalUsuario() { $("#agregarUsuario").modal(); }
[ "function inserirUsuario() {\n if ($scope.novoUsuario.Id > 0) {\n atualizarModelUsuario();\n\n } else {\n inserirModelUsuario();\n }\n }", "function handleCreateAccount() {\n\t$('.open-create-account').on('click', event => {\n\t\t$('.Welcome').addClass(\"hidden\");\n\t\t$('.Create-Account-Page').removeClass(\"hidden\");\n\t});\n}", "function intromodalU(evento) {\n if (evento.keyCode === 13) {\n actualizarU();\n }\n}//fin funcion intro modal actulizar usuario", "function crearFormularioRegistrarse(btnIniciarSesion, btnRegistrarse){\r\n document.getElementById(\"formulario\").removeChild(btnIniciarSesion);\r\n document.getElementById(\"formulario\").removeChild(btnRegistrarse);\r\n\r\n crearBtnAtras();\r\n\r\n //formulario registro\r\n\r\n var pNombre = document.createElement(\"p\");\r\n pNombre.innerHTML = \"Nombre: \";\r\n\r\n var nombre = document.createElement(\"input\");\r\n nombre.setAttribute(\"type\", \"text\");\r\n nombre.setAttribute(\"name\", \"nombre\");\r\n nombre.setAttribute(\"id\", \"nombre\");\r\n nombre.setAttribute(\"placeholder\", \"Nombre\");\r\n nombre.setAttribute(\"required\", true);\r\n\r\n var pApellidos = document.createElement(\"p\");\r\n pApellidos.innerHTML = \"Apellidos: \";\r\n\r\n var apellidos = document.createElement(\"input\");\r\n apellidos.setAttribute(\"type\", \"text\");\r\n apellidos.setAttribute(\"name\", \"apellidos\");\r\n apellidos.setAttribute(\"id\", \"apellidos\");\r\n apellidos.setAttribute(\"placeholder\", \"Apellidos\");\r\n apellidos.setAttribute(\"required\", true);\r\n\r\n var pIdentificador = document.createElement(\"p\");\r\n pIdentificador.innerHTML = \"Usuario: \";\r\n\r\n var identificador = document.createElement(\"input\");\r\n identificador.setAttribute(\"type\", \"text\");\r\n identificador.setAttribute(\"name\", \"identificador\");\r\n identificador.setAttribute(\"id\", \"identificador\");\r\n identificador.setAttribute(\"placeholder\", \"Usuario\");\r\n identificador.setAttribute(\"required\", true);\r\n\r\n var pEmail = document.createElement(\"p\");\r\n pEmail.innerHTML = \"Email: \";\r\n\r\n var email = document.createElement(\"input\");\r\n email.setAttribute(\"type\", \"text\");\r\n email.setAttribute(\"name\", \"email\");\r\n email.setAttribute(\"id\", \"email\");\r\n email.setAttribute(\"placeholder\", \"Email\");\r\n email.setAttribute(\"required\", true);\r\n \r\n \r\n var pContrasenna = document.createElement(\"p\");\r\n pContrasenna.innerHTML = \"Contraseña: \";\r\n\r\n var contrasenna = document.createElement(\"input\");\r\n contrasenna.setAttribute(\"type\", \"password\");\r\n contrasenna.setAttribute(\"name\", \"contrasenna\");\r\n contrasenna.setAttribute(\"id\", \"contrasenna\");\r\n contrasenna.setAttribute(\"placeholder\", \"Contraseña\");\r\n contrasenna.setAttribute(\"required\", true);\r\n\r\n var pContrasenna2 = document.createElement(\"p\");\r\n pContrasenna2.innerHTML = \"Confirme su contraseña: \";\r\n\r\n var contrasenna2 = document.createElement(\"input\");\r\n contrasenna2.setAttribute(\"type\", \"password\");\r\n contrasenna2.setAttribute(\"name\", \"contrasenna2\");\r\n contrasenna2.setAttribute(\"id\", \"contrasenna2\");\r\n contrasenna2.setAttribute(\"placeholder\", \"Confirme su contraseña\");\r\n contrasenna2.setAttribute(\"required\", true);\r\n\r\n var registrarme = document.createElement(\"button\");\r\n registrarme.setAttribute(\"name\", \"registrarme\");\r\n registrarme.setAttribute(\"value\", \"registrarme\");\r\n registrarme.addEventListener(\"click\", function(){\r\n ajaxRegistrarNuevoUsuario(nombre, apellidos, identificador, email, contrasenna, contrasenna2);\r\n }) \r\n registrarme.innerHTML =\"Registrarme\";\r\n\r\n document.getElementById(\"formulario\").appendChild(pNombre);\r\n document.getElementById(\"formulario\").appendChild(nombre);\r\n document.getElementById(\"formulario\").appendChild(pApellidos);\r\n document.getElementById(\"formulario\").appendChild(apellidos);\r\n document.getElementById(\"formulario\").appendChild(pIdentificador);\r\n document.getElementById(\"formulario\").appendChild(identificador);\r\n document.getElementById(\"formulario\").appendChild(pEmail);\r\n document.getElementById(\"formulario\").appendChild(email);\r\n document.getElementById(\"formulario\").appendChild(pContrasenna);\r\n document.getElementById(\"formulario\").appendChild(contrasenna);\r\n document.getElementById(\"formulario\").appendChild(pContrasenna2);\r\n document.getElementById(\"formulario\").appendChild(contrasenna2);\r\n document.getElementById(\"formulario\").appendChild(registrarme);\r\n }", "function openModalNewResponsableMedicion() {\n\tabrirCerrarModal(\"modalAsignaPersonas\");\n\tsetFirstInput();\n}", "async function okCreateLogin() {\n if (userRole === \"Admin\"){\n let loginName = userNameInput.value + \"\";\n let loginPassword = passwordInput.value + \"\";\n let loginRole = loginRoleSelect.value + \"\";\n let response = await adminPOST({loginName, loginPassword, loginRole}, \"api/login/createLogin\");\n createLoginCloseModalAction();\n if (response !== undefined) {\n alert(\"Login blev ikke oprettet. \\n\" + response.body);\n }\n }\n}", "function showCreateForm() {\n setID(\"\");\n setFullName(\"\");\n setEmail(\"\");\n setShowForm(true);\n setShowUpdateForm(false);\n }", "function createUsuario(req, res, next) {\n /* Checking if there's already an user with the provided 'nome' */\n Usuario.findOne({ 'nome': req.body.new.nome }, function(err, userDoc) {\n /* Checking for errors */\n if (err) { return next(err); }\n\n /* Checking if user exists with provided 'nome' */\n if (userDoc) {\n return res.json({\n success: false,\n message: 'Já existe um usuário cadastrado com este nome'\n });\n }\n\n /* Tries to update the user's fields */\n try {\n var userObject = {};\n\n userObject.nome = req.body.new.nome;\n } catch (err) {\n /* There was an error creating the hash */\n return res.json({\n success: false,\n message: 'Confira se todos os campos foram preenchidos corretamente'\n });\n }\n\n /* Sending the create request to the database */\n Usuario.create(userObject, function(err) {\n /* Checking for errors */\n if (err) { return next(err); }\n\n /* Returning the success message */\n return res.json({\n success: true,\n message: userObject.nome + ' cadastrado com sucesso'\n });\n });\n });\n}", "function alertModalPass() {\n getElement('id_bh_modal').className = \"BH_MODAL\";\n getElement('myModal').style.display = \"block\";\n\n getElement('modalTitre').innerHTML = \"Connexion\";\n getElement(\"modalClose\").innerHTML = \"<i class='fa fa-times-circle size-3 close' onclick='closeModal()'></i>\";\n\n //getElement(\"modalText\").innerHTML = \"<h3>Connexion admin ou table [\"+ipLocal+\"]</h3><input type=password name=pass required>\" \n getElement(\"modalText\").innerHTML = \"<h3>Connexion Admin</h3><input type=password name=pass required>\"\n\n $repr = \"<input type=button value=Confirmer onclick='searchStyle();confirmPass();closeModal()'>\";\n $repr += \"&nbsp;&nbsp;&nbsp;&nbsp;<input type=button value=Annuler onclick='closeModal()'>\";\n getElement(\"modalAction\").innerHTML = $repr;\n}", "function mostrarPanelDesdeModal() {\n checarDesdeModal();\n\n setTimeout(function() {\n console.log(privilegio);\n\n if(puesto == privilegio) { //si el puesto es igual, significa que ingresaste bien tu puesto\n if(privilegio == \"Administrador\") { //si el privilegio es Administrador te muestra el panel de admin\n let div = '<div id=\"holder\" class=\"row\" ></div>';\n\n $('#CalendarioUsuario').remove();\n $('#CalendarioAdmin').append(div);\n $('#panel-usuario').hide();\n $('#mainNav').show();\n $(\"title\").html(\"Panel de administrador\");\n $('#panel-admin').show();\n $('#modal').modal('hide');\n }\n if(privilegio == \"Usuario\") { //si el privilegio es Usuario normal te lleva al panel de usuario\n let div = '<div id=\"holder\" class=\"row\" ></div>';\n\n $('#CalendarioAdmin').remove();\n $('#CalendarioUsuario').append(div);\n $('#panel-admin').hide();\n $('#panel-usuario').show();\n $('title').html(\"Panel de usuario\");\n $('#modal').modal('hide');\n }\n }\n else {\n $('#error').html('Tu puesto es incorrecto').show(); //si ingresaste mal el puesto te muestra un error\n setTimeout(function() {\n $('#error').fadeOut(\"slow\").hide();\n }, 2000);\n }\n }, 2000);\n}", "function limparDados() {\n $('#nome').val('');\n $('#ativo').val('N');\n $('#modelo-cadastro').modal('toggle')\n }", "function openUserForm($event) {\n return userFormDialogService.create($event).then(reloadView);\n }", "function construirTemplate(nombre, telefono, registro_id) {\n // crear nombre de contacto\n var tdNombre = document.createElement('TD');\n var textoNombre = document.createTextNode(nombre);\n tdNombre.appendChild(textoNombre);\n \n // crear telefono de contacto\n var tdTelefono = document.createElement('TD');\n var textoTelefono = document.createTextNode(telefono);\n tdTelefono.appendChild(textoTelefono);\n \n // crear enlace para editar\n var nodoBtn = document.createElement('A');\n var textoEnlace = document.createTextNode('Editar');\n nodoBtn.appendChild(textoEnlace);\n nodoBtn.href = 'editar.php?id=' + registro_id;\n \n // agregar el boton al td\n var notoTdEditar = document.createElement('TD');\n notoTdEditar.appendChild(nodoBtn);\n \n // crear checkbox para borrar\n var checkBorrar = document.createElement('INPUT');\n checkBorrar.type = 'checkbox';\n checkBorrar.name = registro_id;\n checkBorrar.classList.add('borrar_contacto');\n \n // agregar td a checkbox\n var tdCheckbox = document.createElement('TD');\n tdCheckbox.classList.add('borrar');\n tdCheckbox.appendChild(checkBorrar);\n \n // agregar al TR\n var trContacto = document.createElement('TR');\n trContacto.setAttribute('id', registro_id);\n trContacto.appendChild(tdNombre);\n trContacto.appendChild(tdTelefono);\n trContacto.appendChild(notoTdEditar);\n trContacto.appendChild(tdCheckbox);\n \n tablaRegistrados.childNodes[3].append(trContacto);\n \n actualizarNumero();\n}", "function cargarModalArea(){\n\n //mostrar modal\n $('#modalArea').modal({'show':true, backdrop: 'static', keyboard: false});\n //set focus\n $('#modalArea').on('shown.bs.modal', function () {\n $('#nombre').trigger('focus')\n });\n $('#modalArea #accion').val(\"insert\");\n //limpiar formulario\n document.getElementById('formArea').reset();\n $(\"#jefeArea\").hide();\n document.getElementById(\"estadoArea\").options[1].selected=true;\n \n }", "create(req, res) {\r\n req.session.reset();\r\n db.get(\"SELECT * FROM users WHERE username_text = ?\", req.body.Username, (err, user) => {\r\n if (err) return res.render('login', {\r\n message: \"Username/Password not found. Please try again.\"\r\n });\r\n if (!user) return res.render('login', {\r\n message: \"Username/Password not found. Please try again.\"\r\n });\r\n if (user.password != req.body.Password) return res.render('login', {\r\n message: \"Username/Password not found. Please try again.\"\r\n });\r\n req.session.user_id = user.userID;\r\n req.user = user;\r\n return res.redirect('/');\r\n });\r\n }", "async criar() {\n this.validar(true);\n const resultado = await TabelaProduto.inserir({\n titulo : this.titulo,\n preco: this.preco,\n estoque : this.estoque,\n fornecedor : this.fornecedor\n });\n this.id = resultado.id;\n this.dataCriacao = resultado.dataCriacao;\n this.dataAtualizacao = resultado.dataAtualizacao;\n this.versao = resultado.versao\n }", "function initModalModificarContacto(){\n\t\tvar $form = $('.form-modificar-contacto #form-modificar-contacto');\n\t\tvar $input = $form.find('input[name=\"nombre\"]');\n\n\t\t$input.bind('input', function(e){\n\t\t\tvar $errori = $form.find('.general-error-tooltip');\n\t\t\tif($errori.length>0){\n\t\t\t\t$input.removeClass('error').removeClass('error-dd');\n\t\t\t\t$errori.remove();\n\t\t\t}\n\t\t});\n\n\t\tmodalModificarContacto = new modalesTelcel($('#modal-modificar-contacto'),{\n\t\t\tonInit : function(){\n\t\t\t\tvalidateForm();\n\t\t\t\tresendFormError($('#modal-modificar-contacto'), $('#form-modificar-contacto'));\n\t\t\t},\n\t\t\tonReset : function(){\n\t\t\t\tremoveGeneralError($('#modal-modificar-contacto'));\n\t\t\t\t//resetModalDesasociarCuentas();\n\t\t\t},\n\t\t\tonOpen : function(){\n\t\t\t\tresetFormModal($('.form-modificar-contacto #form-modificar-contacto'), 'modificarContacto');\n\t\t\t\tsetModalData();\n\t\t\t},\n\t\t\tonClose : function(){\n\n\t\t\t\t//Cuando cierre el modal si quieren hacer refresh hay que descomentar esto\n\t\t\t\t// if(processCompleted)\n\t\t\t\t// \tlocation.reload();\n\t\t\t}\n\t\t});\n\n\t\tfunction setModalData(){\n\t\t\tvar meta = currentModalData,\n\t\t\t$modal = $('#modal-modificar-contacto');\n\n\n\t \t\t\n\t \t\t$modal.find('input[name=\"email\"]').val(meta.correoelectronico);\n\t \t\t$modal.find('input[name=\"nombre\"]').val(meta.nombre);\n\t \t\t$modal.find('input[name=\"apellidos\"]').val(meta.apellido);\n\t \t\t$modal.find('input[name=\"area\"]').val(meta.area);\n\t \t\t$modal.find('input[name=\"puesto\"]').val(meta.puesto);\n\n\t \t\t$modal.find('.lada-value').html(meta.lada);\n\t \t\t$modal.find('.telefono-value').html(meta.numero);\n\t \t\t$modal.find('.extension-value').html(meta.extension);\n\t \t\t$modal.find('.marcacion-value').html(meta.marcacion);\n\n\n\t\t}\n\n\t\tfunction validateForm(){\n\n\t\t\tvar $form = $('.form-modificar-contacto #form-modificar-contacto');\n\n\t\t\tdisableSumbitButton($form, true);\n\t\t\t//checkRequiredElements('#form-modificar-contacto');\n\t\t\n\t\t\tformElementsModales['modificarContacto']['validator'] = $form.validate({\n\t\t\t rules: {\n\t\t\t\tnombre: {\n\t\t\t\t\trequired: true,\n\t\t\t\t\tminlength: 3,\n\t\t\t\t\tgrupoNombre : true,\n\t\t\t \t\tmaxlength: 45\n\t\t\t\t},\n\t\t\t\tapellidos: {\n\t\t\t\t\trequired: true,\n\t\t\t\t\tminlength: 3,\n\t\t\t\t\tgrupoNombre : true,\n\t\t\t \t\tmaxlength: 45\n\t\t\t\t},\n\t\t\t\tarea: {\n\t\t\t\t\trequired: true,\n\t\t\t\t\tminlength: 5,\n\t\t\t\t\tgrupoNombre : true,\n\t\t\t \t\tmaxlength: 45\n\t\t\t\t},\n\t\t\t\tpuesto: {\n\t\t\t\t\trequired: true,\n\t\t\t\t\tminlength: 5,\n\t\t\t\t\tgrupoNombre : true,\n\t\t\t \t\tmaxlength: 45\n\t\t\t\t},\n\t\t\t\temail : {\n\t\t\t\t\trequired: true,\n\t\t\t \t\temail: true\n\t\t\t\t}\n\t\t\t },\n\t\t\t messages: {\n\t\t\t\t nombre: {\n\t\t\t\t required: \"Es necesario ingresar un nombre para el contacto.\",\n\t\t\t\t minlength : \" El nombre debe tener al menos 3 caracteres.\",\n\t\t\t\t grupoNombre : \"El nombre no debe tener caracteres especiales, números y espacio al inicio o final.\",\n\t\t\t\t maxlength : \"El nombre debe tener un máximo de 45 caracteres.\"\n\t\t\t\t },\n\t\t\t\t apellidos: {\n\t\t\t\t required: \"Es necesario ingresar un apellido para el contacto.\",\n\t\t\t\t minlength : \" El apellido debe tener al menos 3 caracteres.\",\n\t\t\t\t grupoNombre : \"El apellido no debe tener caracteres especiales, números y espacio al inicio o final.\",\n\t\t\t\t maxlength : \"El apellido debe tener un máximo de 45 caracteres.\"\n\t\t\t\t },\n\t\t\t\t area: {\n\t\t\t\t required: \"Es necesario ingresar un área para el contacto.\",\n\t\t\t\t minlength : \" El área debe tener al menos 5 caracteres.\",\n\t\t\t\t grupoNombre : \"El área no debe tener caracteres especiales, números y espacio al inicio o final.\",\n\t\t\t\t maxlength : \"El área debe tener un máximo de 45 caracteres.\"\n\t\t\t\t },\n\t\t\t\t puesto: {\n\t\t\t\t required: \"Es necesario ingresar un puesto para el contacto.\",\n\t\t\t\t minlength : \" El puesto debe tener al menos 5 caracteres.\",\n\t\t\t\t grupoNombre : \"El puesto no debe tener caracteres especiales, números y espacio al inicio o final.\",\n\t\t\t\t maxlength : \"El puesto debe tener un máximo de 45 caracteres.\"\n\t\t\t\t },\n\t\t\t\t email: {\n\t\t\t\t \trequired: \"Ingresa tu correo electrónico.\",\n\t\t\t \t\temail: \"Ingresa un correo electrónico válido.\"\n\t\t\t\t }\n\t\t\t },\n\t\t\t errorClass : \"error-dd error\",\n\t\t\t\tsubmitHandler: function(form) {\n\t\t\t\t\tif(!formElementsModales['modificarContacto']['sending']){\n\n\t\t\t\t\t\tformElementsModales['modificarContacto']['sending'] = true;\n\n\t\t\t\t\t\t$(form).find('button[type=\"submit\"]').prop('disabled', true);\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar self = $(form).serialize();\n\t\t\t\t\t\tvar selfArray = $(form).serializeArray();\n\n\t\t\t\t\t\tgeneralLoadingIcon(form, true);\n\n\t\t\t\t\t\tvar urlPOST = ( $(form).prop('action') == '' ? postURL : $(form).prop('action') ) ;\n\n\t\t\t\t\t\t$.post( urlPOST , { data: self, id: currentModalData.id })\n\t\t\t\t\t\t .done(function( json ) {\n\t\t\t\t\t\t \t\n\t\t\t\t\t\t \tServices.redPrivada.modificarContactoSuccessCallback(json, form, updateOnSuccess);\n\t\t\t\t\t\t \t$(form).find('button[type=\"submit\"]').prop('disabled', false);\n\t\t\t\t\t\t \tformElementsModales['modificarContacto']['sending'] = false;\n\t\t\t\t\t\t \tgeneralLoadingIcon(form, false);\n\n\t\t\t\t\t\t })\n\t\t\t\t\t\t .fail(function( jqxhr, textStatus, error ) {\n\t\t\t\t\t\t \t//Mensaje de error del SISTEMA\n\n\t\t\t\t\t\t \tServices.redPrivada.modificarContactoFailCallback(error, form );\n\n\t\t\t\t\t\t \tformElementsModales['modificarContacto']['sending'] = false;\n\t\t\t\t\t\t \tgeneralLoadingIcon(form, false);\n\t\t\t\t\t\t});\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tcheckGeneralValidForm($form);\n\t\t\t\n\n\t\t}\n\n\n\t\tfunction updateOnSuccess(msg){\n\t\t\t$('#modal-modificar-contacto .api-msg-success').html('<p>'+msg+'</p>');\n\n\t\t}\n\n\t}", "function abre_modal_alterar_senha(){\r\n\r\n\t_START('abre_modal_alterar_senha');\r\n\tvar funCallBack\t=\tfunction(data)\r\n\t{\r\n\t\t_START('callbackabre_modal_alterar_senha');\r\n\t\t\r\n\t\t\t$('.modal-content-grid').html(data);\r\n\t\t\t$('.grid_alterar_senha #extraValues').val('');\r\n\t\t\twrs_window_grid_events_tools({btn:btn_window_grid_event_admin});\r\n\t\t\t\r\n\t\t_END('callbackabre_modal_alterar_senha');\t\r\n\t};\r\n\t\r\n\t$('#myModal').modal('show');\r\n\r\n\tgrid_window_modal(\r\n\t\t\t\t{\t\r\n\t\t\t\t\t'wrs_type_grid'\t:\t\t'form',\r\n\t\t\t\t\t'form_event'\t:\t\t'changePassword',\r\n\t\t\t\t\t'extraValues'\t: \t\t'self'\r\n\t\t\t\t},\r\n\t\t\t\tnull,\r\n\t\t\t\tfunCallBack);\r\n\t_END('abre_modal_alterar_senha');\t\r\n\t\r\n}", "function render_modal(titulo, descripcion='', contenido='ENTENDIDO'){\n\n if(contenido=='ENTENDIDO'){\n contenido = `<div id=\"mm-entendido-btn\">ENTENDIDO</div>`\n }\n}", "function guardarUsuario() {\n let nombre = $('#nombre').val();\n let apellidos = $('#apellidos').val();\n let agregarUsuarioEmail = $('#agregarUsuarioEmail').val();\n let agregarUsuarioPuesto = $('#agregarUsuarioPuesto').val();\n var agregarUsuarioContrasena;\n\n if($('#nuevacontrasena').val() == $('#confirmarcontrasena').val()) {\n agregarUsuarioContrasena = $('#nuevacontrasena').val();\n\n firebase.auth().createUserWithEmailAndPassword(agregarUsuarioEmail, agregarUsuarioContrasena)\n .then(function(data) {\n console.log(data);\n let uid = data.uid;\n console.log(uid);\n\n let usuarios = firebase.database().ref('usuarios/'+uid);\n let Usuario = {\n nombre: nombre,\n apellidos: apellidos,\n puesto: agregarUsuarioPuesto\n }\n usuarios.set(Usuario); //metodo set para insertar de Firebase\n\n })\n .catch(function(error) {\n console.log(error);\n });\n $('#agregarUsuario').modal('hide');\n\n logOut();\n }\n else {\n console.log(\"Las contraseñas no coinciden\");\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function should update the custom arrays on page load and on form submission
function updateStorageArrays() { //checking if there is existing previous form data in local storage if (!localStorage.getItem("form-data")) { return; } //clearing the custom array so they can be "refilled" with what is in the local storage siteStorage = JSON.parse(localStorage.getItem("form-data")); customOneArray = []; customTwoArray = []; for (var i = 1; i <= 6; i++) { if (siteStorage["name" + i] !== "" && siteStorage["name" + i] !== undefined) { var pair = []; pair.push(siteStorage["name" + i]); pair.push(siteStorage["url" + i]); if (i < 4) { customOneArray.push(pair); } else { customTwoArray.push(pair); } } } }
[ "function store() {\n customs.push(custom); //stores custom arrays\n custom = {\n name: \"\",\n opt: [] //clears custom array to get new things\n };\n}", "function fillSavedInputs() {\n const getFieldByName = name => $(`#id_${name}`);\n\n for (const fieldName in DOM.orderFieldData) { // Ignore ESLintBear (no-restricted-syntax)\n if ({}.hasOwnProperty.call(DOM.orderFieldData, fieldName)) {\n const $field = getFieldByName(fieldName);\n const savedValue = localStorage.getItem(fieldName);\n\n if ($field && savedValue) {\n $field.val(savedValue);\n }\n }\n }\n }", "function updateArrays() {\n var storedHighScore = JSON.parse(localStorage.getItem(\"highScore\"));\n\n if (storedHighScore !== null) {\n highScore = storedHighScore;\n }\n\n var storedInitials = JSON.parse(localStorage.getItem(\"initials\"));\n\n if (storedInitials !== null) {\n initials = storedInitials;\n }\n}", "function updateDisplayArray() {\n\n\t\t/* First remove the existing data from the arrays */\n\t\twhile (displayArray.length > 0) {\n\t\t\tdisplayArray.shift();\n\t\t\t} \n\n\t\twhile (yearArray.length > 0) {\n\t\t\tyearArray.shift();\n\t\t\t} \n\n\t\twhile (checkArray.length > 0) {\n\t\t\tcheckArray.shift();\n\t\t\t} \n\n\t\twhile (sortArray.length > 0) {\n\t\t\tsortArray.shift();\n\t\t\t} \n\n\t\twhile (sortArray.length > 0) {\n\t\t\tsortArray.shift();\n\t\t\t} \n\n\t\tswitch (displayYear) { \n\t\t\tcase \"2008\":\n\t\t\t\tyearArray = data.year2008.slice(0);\n\t\t\t\tbreak;\n\t\t\tcase \"2009\":\n\t\t\t\tyearArray = data.year2009.slice(0);\n\t\t\t\tbreak;\n\t\t\tcase \"2010\":\n\t\t\t\tyearArray = data.year2010.slice(0);\n\t\t\t\tbreak;\n\t\t\tcase \"2011\":\n\t\t\t\tyearArray = data.year2011.slice(0);\n\t\t\t\tbreak;\n\t\t\tcase \"2012\":\n\t\t\t\tyearArray = data.year2012.slice(0);\n\t\t\t\tbreak; \t\t\t\t\t\t\t\t\t\t\t \n\t\t\tdefault:\n\t\t\t\tyearArray = data.year2012.slice(0);\n\t\t\t\tbreak;\t\t\n\t\t}\n\n\n\t\tfor (var i = 0; i < yearArray.length; i++) { \n\t\t\t\tcheckArray.push({});\n\t\t}\n\n\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\tcheckArray[i].country = yearArray[i].country;\n\t\t\tcheckArray[i].countryCode = yearArray[i].countryCode;\n\t\t\tcheckArray[i].continent = yearArray[i].continent;\n\t\t};\n\n\t\tif (count === \"cc\") {\n\t\t\tswitch (field) {\n\t\t\t\tcase \"all\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].cc;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"phys\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ccPhys;\n\t\t\t\t\t};\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"life\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ccLife;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"earth\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ccEarth;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"chem\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ccChem;\n\t\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].cc;\n\t\t\t\t\t};\t\t\t\t\t\t\t\t\t\t\n\t\t\t}\n\t\t} else if (count === \"ac\"){\n\t\t\tswitch (field) {\n\t\t\t\tcase \"all\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ac;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"phys\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].acPhys;\n\t\t\t\t\t};\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"life\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].acLife;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"earth\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].acEarth;\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"chem\":\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].acChem;\n\t\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\t\t\t\tcheckArray[i].choice = yearArray[i].ac;\n\t\t\t\t\t};\t\t\t\t\t\t\t\t\t\t\n\t\t\t}\n\t\t};\n\n\t\t/*\tFind out if each country is checked and if so copy their\n\t\t\tobject from checkArray into displayArray */\n\t\tfor (var i = 0; i < checkArray.length; i++) {\n\t\t\tvar countryName = checkArray[i].country;\n\n\t\t\tif (d3.select(\".country-select [value=\" + countryName + \"]\").property(\"checked\")) {\n\t\t\t\tdisplayArray.push(checkArray[i]);\n\t\t\t}\n\t\t};\n\n\t\t/*\tSort displayArray into the descending order \n\t\t\tIf the contries happen to have the same value for choice then they are sorted into alphabetical order */\n\t\tdisplayArray.sort(function(a, b) {\n\t\t\t\tif (b.choice < a.choice) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\telse if (b.choice > a.choice) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else if (b.choice === a.choice) {\n\t\t\t\t\treturn a.country < b.country ? -1 : a.country > b.country ? 1 : 0;\n\t\t\t\t}\n\t\t\t})\n\n\t\tupdateBars();\n\t\tupdateHeader();\n\t\tsetupLabel();\n\t}", "function formFieldPopulation(){\n\t\tvar detailsObject = JSON.parse(localStorage.getItem('details'));\n\t\tif(detailsObject != null){\n\t\t\tconsole.log(detailsObject.firstname);\n\t\t\t$('#firstname').val(detailsObject.firstname);\n\t\t\t$('#lastname').val(detailsObject.lastname);\n\t\t\t$('#email').val(detailsObject.email);\n\t\t\t$('#phone').val(detailsObject.phone);\n\t\t\tconsole.log(detailsObject);\n\t\t}\n\t}", "function redefineSavedTablesArray () {\n\tconsole.log(\"In redefineSavedTablesArray functio…did I make it?\");\n\tlet savedTablesArray = [];\n//for (var i = 0; i < recordCounter; i++) {\n\nfor (var i = 0; i < 10; i++) {\n\nsavedTablesArray[i] = new Array(4);\n\n}//number of fields means all fields for savedTablesArray there are 4 fields maybe should change back to numberOfFields????\n\nsavedTablesArray[0] = [\"name\",\"DATE\",\"tel\",\"email\"];\nsavedTablesArray[1] = [\"name2\",\"DATE\",\"tel2\",\"email2\"];\n\nfor (var i = 0; i < 10; i++) {\n//these lines added Mar 21 v\nnewTableFieldsArray.length = 0;\nnumberOfNewTableAddedFields = 0;\ntableIndex = -1;\n//these lines added Mar 21 ^\nnewTableSpecificVariables[i] = [tableIndex, newTableFieldsArray, numberOfNewTableAddedFields];\n\n}//number of fields means all fields for savedTablesArray there are 4 fields maybe should change back to numberOfFields????\n\n\t\n\n\treturn savedTablesArray;\n//return savedTablesArray,newTableSpecificVariables;\n}//end function redefineSavedTablesArray", "function addCustomInfoBoxIfPosibal(formDataArray, headline, bodyText) {\n var didChange = false;\n var firstFeatured = GetFormField(formDataArray, \"profile_showcase[]\", 0); //shoud get the first Featured dropdown field\n if(firstFeatured != null){\n if(firstFeatured.value != \"8\"){\n firstFeatured.value = \"8\"; // set to Custom info box\n didChange = true;\n }\n\n var title = GetFormField(formDataArray, \"rgShowcaseConfig[8][0][title]\");\n if(title != null){\n if(title.value != headline){\n title.value = headline;\n didChange = true;\n }\n }\n var notes = GetFormField(formDataArray, \"rgShowcaseConfig[8][0][notes]\");\n if(notes != null){\n if(notes.value != bodyText){\n notes.value = bodyText;\n didChange = true;\n }\n }\n }\n return didChange; // only call update if there is a chance.\n}", "function addFormData() {\n\t\t\t// console.log(\"called addFormData\");\n\t\t\t$(settings.form).find(':input').each(function(){\n\t\t\t\t// console.log(\"addFormData: \"+$(this).attr('name'));\n\t\t\t\tif ($(this).attr('name') !== undefined) {\n\t\t\t\t\t// exclude .bt_size, need ! in_array()\n\t\t\t\t\tif ($(this).attr('name') !== settings.pageSizeChooser) {\n\t\t\t\t\t\t// console.log(\"adding\");\n\t\t\t\t\t\tdata+= \"&\"+$(this).serialize();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t\t// console.log(data);\n\t\t\t\n\t\t}", "handle_index_table_form(){\n let $form = $(\"#custom-table-parameters\"),\n $form_submit_button = $form.find(\".button-primary\");\n\n $form.on(\"submit\",(e) => {\n e.preventDefault();\n //Disable button\n $form_submit_button.attr(\"disabled\",true);\n //Collect data\n let table_params = {},\n $dataTypes_input = $(\"[data-datatype]\").filter(\":checked\");\n if($dataTypes_input.length > 0){\n $.each($dataTypes_input, function (index,input) {\n let $input = $(input);\n if(typeof table_params[\"\"+$input.data(\"datatype\")+\"\"] === \"undefined\"){\n table_params[\"\"+$input.data(\"datatype\")+\"\"] = [];\n }\n table_params[$input.data(\"datatype\")].push($input.val());\n });\n/* for(let input of $dataTypes_input){\n let $input = $(input);\n if(typeof table_params[\"\"+$input.data(\"datatype\")+\"\"] === \"undefined\"){\n table_params[\"\"+$input.data(\"datatype\")+\"\"] = [];\n }\n table_params[$input.data(\"datatype\")].push($input.val());\n }*/\n }\n //Send ajax requests\n this.handle_index_table_creation(table_params);\n });\n }", "function logInitials(event) {\n event.preventDefault();\n userArray = JSON.parse(localStorage.getItem(\"userArray\"));\n user.initials = InitialsEl.val();\n console.log(InitialsEl.val());\n console.log(user);\n userArray.push(user);\n console.log(userArray);\n localStorage.setItem(\"userArray\", JSON.stringify(userArray));\n displayHighScores();\n}", "function addNewData(){\n \n //Get the Band Name and Band Genre\n $('#band-name').val('');\n $('#band-genre').val('');\n \n //Fire off functions when Submit and Reset buttons are clicked.\n $('#submit').on('click', addData)\n $('#reset').on('click', showData);\n \n //Hide table and show input form.\n $('#band-info').hide();\n $('#data-values').show();\n \n function addData(evt){\n //Holds form data from Band Name and Band Genre input fields.\n var newData = {\n name: $('#band-name').val(),\n genre: $('#band-genre').val()\n };\n \n bandData.push(newData);\n \n evt.preventDefault();\n \n showData();\n }//End of addData\n}//End of addNewData", "function storeFormValsTemporarily()\n{\n var myForm = arguments[0];\n var formElementValues = convertFormElements(myForm);\n pageControl.setConvertedFormElements(formElementValues);\n}", "function updateData(){\n //Re draw the data\n drawDataOptions();\n\n //Fill in data element values when clicking on a data element in select box.\n $('.data-elements option').click( function(e){\n\n $('input.dataKey').attr('disabled','disabled');\n $('input.dataKey').val($(this).attr(\"dataKey\"));\n $('input.dataValue').val($(this).attr(\"dataValue\"));\n $('button.add-data').text(i18n.gettext('Edit Data'));\n e.stopPropagation();\n\n });\n }", "function createGemValues() {\n $(\"#blueGem\").attr('data-gemValueArray', gemValueArray[0]);\n $(\"#greenGem\").attr('data-gemValueArray', gemValueArray[1]);\n $(\"#pinkGem\").attr('data-gemValueArray', gemValueArray[2]);\n $(\"#redGem\").attr('data-gemValueArray', gemValueArray[3]);\n }", "function handleMealDetailsSubmit() {\n $('.meal-details').on('submit', event => {\n event.preventDefault();\n const meal = constructMeal();\n Store.meals.push(meal);\n $('.meal-details-input').val('');\n calculateAverage();\n customerCharges();\n earningsInfo();\n console.log(Store.meals,'Meal Added');\n });\n}", "function populate() {\n for (let i = 0; i < questionList.length; i++) {\n // console.log(i);\n questionArray.push(new Object());\n questionArray[i].question = questionList[i];\n questionArray[i].options = optionsArray[i];\n questionArray[i].answer = answers[i];\n }\n}", "function processOpnFrmData(event) {\r\n\r\n\r\n event.preventDefault();\r\n\r\n let nopBoughgame = \"Never Bought Game\"\r\n // Read and adjust data from the form\r\n const nopOpn = document.getElementById(\"story\").value.trim();\r\n const nopName = document.getElementById(\"name\").value.trim();\r\n const nopEmail = document.getElementById(\"email\").value.trim();\r\n const nopGender = document.getElementById(\"Gender\").value.trim();\r\n const nopDoyoubuygames = document.getElementById(\"Doyoubuygames\").checked;\r\n if (document.getElementById(\"Doyoubuygames\").checked) {\r\n nopBoughgame = document.querySelector('input[name=\"Boughtgame\"]:checked').value;\r\n }\r\n const game = document.querySelector('input[name=\"Typeofgame\"]:checked').value;\r\n const nopWhatgamedoyouplathemost = document.querySelector('input[name=\"Gameplayedthemost\"]:checked').value;\r\n\r\n\r\n // var rates = document.getElementsByName('Boughtgame'); da sa aj takto\r\n // var rate_value;\r\n // for(var i = 0; i < rates.length; i++){\r\n // if(rates[i].checked){\r\n // rate_value = rates[i].value;\r\n // }\r\n // }\r\n\r\n if (nopOpn == \"\" || nopName == \"\" || nopEmail == \"\") {\r\n window.alert(\"Please, enter both your name and opinion\");\r\n return;\r\n }\r\n const newOpinion =\r\n {\r\n Name: nopName,\r\n Email: nopEmail,\r\n Gender: nopGender,\r\n Gameplayedmost: nopWhatgamedoyouplathemost,\r\n Typeofgame: game,\r\n Boughtgame: nopDoyoubuygames,\r\n RadioBoughtgame: nopBoughgame,\r\n Textbox: nopOpn,\r\n Created: new Date()\r\n };\r\n\r\n opinions.push(newOpinion);\r\n localStorage.myTreesComments = JSON.stringify(opinions);\r\n\r\n\r\n // opinionsElm.innerHTML += opinion2html(newOpinion);\r\n\r\n\r\n // window.alert(\"Your opinion has been stored. Look to the console\");\r\n // console.log(\"New opinion added\");\r\n // console.log(opinions);\r\n let myFrmElm = document.getElementById(\"router-view\");\r\n myFrmElm=myFrmElm.getElementsByClassName(\"formenu\")[0];\r\n\r\n myFrmElm.reset(); //resets the form\r\n\r\n\r\n}", "function saveClubChanges() {\n const params = new URLSearchParams(window.location.search);\n\n const newDesc = document.getElementById(\"description\").innerHTML;\n const newWebsite = document.getElementById(\"website-input\").innerText;\n\n var newOfficers = [];\n const officerListElement = document.getElementById('officers-list');\n const officerList = officerListElement.getElementsByTagName('li');\n for (const officer of officerList) {\n newOfficers.push(officer.innerText);\n }\n \n var newLabels = [];\n const labelsListElement = document.getElementById('labels');\n const labelsList = labelsListElement.getElementsByTagName('li');\n for (const label of labelsList) {\n newLabels.push(label.innerText.replace(/\\s+/g, '')); // Get rid of whitespaces\n }\n\n document.getElementById('new-desc').value = newDesc;\n document.getElementById('new-web').value = newWebsite;\n document.getElementById('new-officers').value = newOfficers;\n document.getElementById('new-labels').value = newLabels;\n document.getElementById('new-name').value = params.get('name');\n document.forms['edit-form'].submit();\n alert('Changes submitted!');\n}", "function save_patient_changes(){\n\tpatient_config.max_patients = parseFloat($(\"#patient-creation-limit\").val())\n\tpatient_config.batch_arrival_min = parseFloat($(\"#patient-batch-min\").val())\n\tpatient_config.batch_arrival_max = parseFloat($(\"#patient-batch-max\").val())\n\tpatient_config.batch_arrival_lambda = parseFloat($(\"#patient-batch-lambda\").val())\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modal Action Handler: User
function modal_user_action(action, username) { switch(action) { case "add": if(confirm("ยืนยันการเพิ่มบัญชีผู้ใช้งาน")) { $.post(current_web_location + "/services/user_add.php", { user_name: $("#modal-user-input-username").val(), user_type: $("#modal-user-input-usertype").val(), valid_to: $("#modal-user-input-validuntil").val(), return_type: "TEXT" }, function(data, status) { system_display_dialog(data); if(data.includes("สำเร็จ")) { refresh_user_list(); $("#modal-user").modal("toggle"); } }); } break; case "edit": if(confirm("ยืนยันการแก้ไขบัญชีผู้ใช้งาน")) { $.post(current_web_location + "/services/user_edit.php", { user_name: $("#modal-user-input-username").val(), user_type: $("#modal-user-input-usertype").val(), valid_to: $("#modal-user-input-validuntil").val(), return_type: "TEXT" }, function(data, status) { system_display_dialog(data); if(data.includes("สำเร็จ")) { refresh_user_list(); $("#modal-user").modal("toggle"); } }); } break; case "delete": if(confirm("ยืนยันลบผู้ใช้ " + username)) { $.post(current_web_location + "/services/user_delete.php", { user_name: username, return_type: "TEXT" }, function(data, status) { system_display_dialog(data); if(data.includes("สำเร็จ")) { refresh_user_list(); } }); } break; } }
[ "showModal(user) {\n this.modalContainer.style.display = \"inherit\";\n this.updateModalInfo(user);\n }", "function onUserModify() {\n\talert(\"You try to modify a user\");\n\twindow.location.href = \"#user-list\";\n}", "editUser( id ) {\n fluxUserManagementActions.editUser( id );\n }", "function showUser(){\n\t\t\tdocument.getElementById('user-div').style.display = 'block';\n\t\t\tdocument.getElementById('user-btn').style.backgroundColor = 'white';\n\t\t\tdocument.getElementById('user-btn').style.color = 'black';\n\t\t\tdocument.getElementById('owner-div').style.display = 'none';\n\t\t\tdocument.getElementById('agent-div').style.display = 'none';\n\t\t\t\n\t\t\tgsap.from(\"#u-name\",0.4,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#u-phone\",0.8,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#u-email\",1.2,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\t\n\t\t\tdocument.getElementById('agent-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('agent-btn').style.color = 'white';\n\t\t\tdocument.getElementById('owner-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('owner-btn').style.color = 'white';\n\t\t}", "function showUserPanel() {\n\tlcSendValueAndCallbackHtmlAfterErrorCheckPreserveMessage(\"/user/index\",\n\t\t\t\"#userDiv\", \"#userDiv\", null);\n}", "function getUserBtn(user){\n const btnUser = document.querySelector(\"#btn-user\");\n btnUser.addEventListener(\"click\", function(){\n window.open(user.html_url,'_blank' );\n });\n}", "function viewEmpModalAction() {\n if (userRole === \"Admin\" || userRole === \"Employee\") {\n dropdown_content.style.visibility =\"hidden\";\n viewEmpModal.className += \" visible\";\n employeeSelectViewEmployee.value = \"\";\n startDatePicker.value = \"0000-00-00\";\n toDatePicker.value = \"0000-00-00\";\n empTotalHours.value = \"\";\n }\n}", "updateModalInfo(user) {\n const infoContainer = this.modalContainer.querySelector(\n \".modal-info-container\"\n );\n\n infoContainer.querySelector(\".modal-img\").src = user.picture.medium;\n infoContainer.querySelector(\".modal-name\").innerText = `${\n user.name.first\n } ${user.name.last}`;\n infoContainer.querySelector(\".modal-email\").innerText = user.email;\n infoContainer.querySelector(\".modal-city\").innerText = user.location.city;\n infoContainer.querySelector(\".modal-phone\").innerText = user.phone;\n infoContainer.querySelector(\".modal-location\").innerText = `${\n user.location.street\n }, ${user.location.city}, ${user.location.state} ${user.location.postcode}`;\n infoContainer.querySelector(\".modal-birthday\").innerText = `Birthday: ${\n user.dob.date\n }`;\n }", "function selectUserForEdit(user) {\n setUserData(user)\n }", "function openUserForm($event) {\n return userFormDialogService.create($event).then(reloadView);\n }", "function setUpModalForDeleteFriend(modal, userID, userName) {\n // Update the modal title\n modal.find('.modal-title').text('End friendship');\n\n // Update the modal body\n modal.find('.modal-body').text('Are you sure you want to remove ' + userName + ' from your friends?');\n\n // Update the button name\n modal.find('#modal-confirm-button').text('Remove friend');\n\n // Update the button action\n modal.find('#modal-confirm-button').attr('onclick', 'deleteFriend(' + userID + ')');\n}", "function viewUserHandler(app, auth, res, id){\n\tapp.users.account(id, auth)\n\t.then((data) => {\n \t\tres.send(doMustache(app, 'account', {fn: data.firstName, ln: data.lastName}));\n\t})\n\t.catch(() => res.redirect('../../login'));\n}", "_onProfileBtnClick() {\n // toggle the visibility of authedUser component\n this._componenets.authedUser.hidden = !this._componenets.authedUser.hidden\n }", "function generateConfirmDialog(userLocation) {\n var confirmSpan = document.getElementsByClassName(\"close\")[2];\n var inviteConfirm = document.getElementById('inviteConfirm');\n var inviteDeny = document.getElementById('inviteDeny');\n var confUserName = document.getElementById('confUserName');\n var inviteInfo = document.getElementById('inviteInfo');\n userInput = document.getElementById('userNameInp');\n\n //console.log(userLocation);\n //console.log(userArr[userLocation].userName);\n if (userLocation != -1) {\n confUserName.innerHTML = \"Did you mean to add \\\"\" + userArr[userLocation].name + \"\\\"?\";\n userInviteModal.style.display = \"none\";\n confirmUserModal.style.display = \"block\";\n\n inviteConfirm.onclick = function () {\n inviteUserDB(userArr[userLocation]);\n confirmUserModal.style.display = \"none\";\n userInput.value = \"\";\n inviteInfo.innerHTML = \"\";\n };\n\n inviteDeny.onclick = function () {\n confirmUserModal.style.display = \"none\";\n userInviteModal.style.display = \"block\";\n userInput.value = \"\";\n inviteInfo.innerHTML = \"\";\n };\n\n //close on close\n confirmSpan.onclick = function () {\n confirmUserModal.style.display = \"none\";\n userInput.value = \"\";\n inviteInfo.innerHTML = \"\";\n };\n\n //close on click\n window.onclick = function (event) {\n if (event.target == confirmUserModal) {\n confirmUserModal.style.display = \"none\";\n userInput.value = \"\";\n inviteInfo.innerHTML = \"\";\n }\n }\n } else {\n alert(\"Error finding user, please contact the developer for assistance!\");\n }\n }", "function intromodalU(evento) {\n if (evento.keyCode === 13) {\n actualizarU();\n }\n}//fin funcion intro modal actulizar usuario", "function userLoggedIn() {\n let username = sessionStorage.getItem('username');\n $('#spanMenuLoggedInUser').text(`Welcome, ` + username + '!');\n $('#viewUserHomeHeading').text(`Welcome, ` + username + '!');\n $('.anonymous').hide();\n $('.useronly').show();\n showView('UserHome')\n }", "function alertModalPass() {\n getElement('id_bh_modal').className = \"BH_MODAL\";\n getElement('myModal').style.display = \"block\";\n\n getElement('modalTitre').innerHTML = \"Connexion\";\n getElement(\"modalClose\").innerHTML = \"<i class='fa fa-times-circle size-3 close' onclick='closeModal()'></i>\";\n\n //getElement(\"modalText\").innerHTML = \"<h3>Connexion admin ou table [\"+ipLocal+\"]</h3><input type=password name=pass required>\" \n getElement(\"modalText\").innerHTML = \"<h3>Connexion Admin</h3><input type=password name=pass required>\"\n\n $repr = \"<input type=button value=Confirmer onclick='searchStyle();confirmPass();closeModal()'>\";\n $repr += \"&nbsp;&nbsp;&nbsp;&nbsp;<input type=button value=Annuler onclick='closeModal()'>\";\n getElement(\"modalAction\").innerHTML = $repr;\n}", "function userView(targetid, user){\n apply_template(targetid, \"user-detail-template\", user);\n}", "function showOwner(){\n\t\t\tdocument.getElementById('owner-div').style.display = 'block';\n\t\t\tdocument.getElementById('owner-btn').style.backgroundColor = 'white';\n\t\t\tdocument.getElementById('owner-btn').style.color = 'black';\n\t\t\tdocument.getElementById('user-div').style.display = 'none';\n\t\t\tdocument.getElementById('agent-div').style.display = 'none';\n\n\t\t\tgsap.from(\"#o-name\",0.4,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#o-phone\",0.8,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#o-email\",1.2,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#o-address\",1.6,{opacity:0,ease:Power2.easeInOut,x:-400})\n\n\t\t\tdocument.getElementById('user-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('user-btn').style.color = 'white';\n\t\t\tdocument.getElementById('agent-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('agent-btn').style.color = 'white';\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publish a story to the user's own wall
function publishStory() { FB.ui({ method: 'feed', name: 'Test', caption: 'Restaurant', description: 'Tasty restaurant', link: 'http://apps.facebook.com/mobile-start/', picture: 'http://www.facebookmobileweb.com/hackbook/img/facebook_icon_large.png', actions: [{ name: 'Get Started', link: 'http://apps.facebook.com/mobile-start/' }], }, function(response) { alert('successfully posted to FB page and wall'); }); }
[ "function publishStoryFriend() {\n randNum = Math.floor ( Math.random() * friendIDs.length ); \n\n var friendID = friendIDs[randNum];\n \n console.log('Opening a dialog for friendID: ', friendID);\n \n FB.ui({\n method: 'feed',\n to: friendID,\n name: 'I\\'m using the Hackbook web app',\n caption: 'Hackbook for Mobile Web.',\n description: 'Check out Hackbook for Mobile Web to learn how you can make your web apps social using Facebook Platform.',\n link: 'http://apps.facebook.com/mobile-start/',\n picture: 'http://www.facebookmobileweb.com/hackbook/img/facebook_icon_large.png',\n actions: [{ name: 'Get Started', link: 'http://apps.facebook.com/mobile-start/' }],\n user_message_prompt: 'Tell your friends about building social web apps.'\n }\n , \n function(response) {\n console.log('publishStoryFriend UI response: ', response);\n alert(response.accessToken);\n });\n}", "function publish(user_message, attachment, action_links, target_id, user_message_prompt) {\n\t\t/*var attach = {\n\t\t\t\t'name':'Go grab your free bundle right now!',\n\t\t\t\t'href':'http://www.macheist.com/nano/facebook',\n\t\t\t\t'caption':'Download full copies of six top Mac apps normally costing over $150 totally for free at MacHeist!',\n\t\t\t\t'description':\"There’s something for everyone, whether you’re a gamer, a student, a writer, a twitter addict, or just love Mac apps. Plus as a Facebook user you can also get VirusBarrier X5 ($70) as a bonus. Don’t miss out!\",\n\t\t\t\t'media':[{'type':'image','src':'http://www.macheist.com/static/facebook/facebook_mh.png','href':'http://www.macheist.com/nano/facebook'}]\n\t\t\t}\n\t\t*/\t\n\t\t\n\t\tset_ready();\n\t\t\n\t\tFB.api({\n\t\t\t\tmethod: 'stream.publish', \n\t\t\t\tmessage: user_message, \n\t\t\t\tattachment: attachment, \n\t\t\t\taction_links: action_links, \n\t\t\t\ttarget_id: target_id\n\t\t\t}, function(result) {\n\t\t\t\ttrace(_s.PUBLISHED_POST);\n\n\t\t\t\ttrace(result); \n\n\t\t\t\tdispatchEvent(_s.PUBLISHED_POST, result);\n\t\t});\n\t}", "async function addNewStoryOnPage(evt){\n evt.preventDefault();\n //get input value \n const title = $('#story-title').val();\n const author = $('#story-author').val();\n const url = $('#story-url'). val();\n //updates storyList with new story you want to submit\n await storyList.addStory(currentUser, {title, author, url});\n //callbacks for updating DOM with new story\n putStoriesOnPage();\n updateUIOnSubmitNewStory();\n $submitStoryForm.trigger('reset');\n}", "async storiesSetStoryPublished (socket, data, reply) {\n\n\t\t// Make sure the client passed in safe values.\n\t\tconst itemId = String(data.itemId);\n\t\tconst isPublished = Boolean(data.published);\n\n\t\t// Update the database.\n\t\tawait this.database.update(`Article`, itemId, { isPublished });\n\n\t\treturn reply({ success: true });\n\n\t}", "function postMessage(messageToShare, /*linkToShare,*/ image, pageID, isUserProfile) {\n var imageExist = typeof image != 'undefined'\n\n if (isUserProfile) { // Post on user page\n if (imageExist)\n postImageToFeed(messageToShare, image, pageID, accessToken);\n else\n postTextToFeed(messageToShare, /*linkToShare,*/ pageID, true);\n }\n else { // Else we need an access_token to post on a page\n FB.api(\"/\" + pageID + \"?fields=access_token\",\n function (response) {\n if (!response || response.error) {\n alert(JSON.stringify(response.error));\n } else {\n if (imageExist)\n postImageToFeed(messageToShare, image, pageID, response[\"access_token\"]);\n else\n postTextToFeed(messageToShare, /*linkToShare,*/ pageID, false, response[\"access_token\"])\n }\n }\n );\n }\n\n /*\n * Post to the page feed with the given access_token\n * DEPRECATED: use postToFeedAdvanced\n */\n function postTextToFeed(messageToShare, /*linkToShare,*/ pageID, isUserProfile, accessToken) {\n var data;\n if (isUserProfile) {\n data = {\n message: messageToShare,\n /*link: linkToShare*/\n }\n }\n else {\n data = {\n access_token: accessToken,\n message: messageToShare,\n /*link: linkToShare*/\n }\n }\n\n FB.api(\"/\" + pageID + \"/feed\",\n \"post\", data,\n function (response) {\n if (!response || response.error) {\n alert(JSON.stringify(response.error));\n close_popupWindow();\n } else {\n alert(\"Votre message a été partagé !\");\n close_popupWindow();\n }\n }\n );\n }\n\n \n // https://github.com/lukasz-madon/heroesgenerator/blob/master/script.js\n function postImageToFeed(message, imageData, pageID, authToken) {\n // this is the multipart/form-data boundary we'll use\n var boundary = '----ThisIsTheBoundary1234567890';\n // let's encode our image file, which is contained in the var\n var formData = '--' + boundary + '\\r\\n'\n formData += 'Content-Disposition: form-data; name=\"source\"; filename=\"imageSharepoint\";\\r\\n';\n formData += 'Content-Type: image/png\\r\\n\\r\\n';\n for (var i = 0; i < imageData.length; ++i) {\n formData += String.fromCharCode(imageData[i] & 0xff);\n }\n formData += '\\r\\n';\n formData += '--' + boundary + '\\r\\n';\n formData += 'Content-Disposition: form-data; name=\"message\"\\r\\n\\r\\n';\n message = unescape(encodeURIComponent(message)); //Utf16 to Utf8\n formData += message + '\\r\\n'\n formData += '--' + boundary + '--\\r\\n';\n\n var xhr = new XMLHttpRequest();\n xhr.open('POST', 'https://graph.facebook.com/' + pageID+ '/photos?access_token=' + authToken, true);\n xhr.setRequestHeader(\"Content-Type\", \"multipart/form-data; boundary=\" + boundary);\n var nBytes = formData.length;\n var ui8Data = new Uint8Array(nBytes);\n for (var nIdx = 0; nIdx < nBytes; nIdx++) {\n ui8Data[nIdx] = formData.charCodeAt(nIdx) & 0xff;\n }\n xhr.onload = function (data) {\n alert(\"Votre message a été partagé !\");\n close_popupWindow();\n };\n xhr.onerror = function (shr, status, data) {\n alert(JSON.stringify(shr));\n };\n xhr.send(ui8Data.buffer);\n };\n\n /*\n * OLD one, Don't work for IE...\n */\n //function postImageToFeed(message, image, pageID, accessToken) {\n // var formData = new FormData();\n // formData.append(\"access_token\", accessToken);\n // formData.append(\"message\", message);\n // formData.append(\"file\", image);\n\n // $.ajax({\n // url: \"https://graph.facebook.com/\" + pageID + \"/photos\",\n // data: formData,\n // type: \"POST\",\n // cache: false,\n // processData: false,\n // contentType: false,\n // success: function (data) {\n // alert(\"Votre message a été partagé !\");\n // close_popupWindow();\n // },\n // error: function (shr, status, data) {\n // alert(JSON.stringify(shr));\n // }\n // });\n //}\n}", "async publish(draftLinks) {\n return this.apiClient.publishDraft(draftLinks);\n }", "function mechanicsPublish() {\n\tnextTurn();\n}", "publish() {\n if (Meteor.isServer) {\n // get the AppointmentCollection instance.\n const instance = this;\n /** This subscription publishes only the documents associated with the logged in user */\n Meteor.publish(appointmentPublications.appointment, function publish() {\n if (this.userId) {\n const username = Meteor.users.findOne(this.userId).username;\n return instance._collection.find({ owner: username });\n }\n return this.ready();\n });\n }\n }", "function addStoryToDb(story, callback) {\n var client = (this.client || new pg.Client(connectionString));\n\n client.connect(function (err) {\n if (err) {\n console.log(err);\n callback(err, null);\n }\n var sql = 'INSERT INTO stories (story_title, story_content) VALUES ($1, $2)';\n var query = client.query(\"INSERT INTO stories (story_title, story_content, story_author) VALUES ($1, $2, $3)\", [story.title, story.content, story.author], function (err, result) {\n // we are now done getting the data from the DB, disconnect the client\n client.end(function (err) {\n if (err) throw err;\n });\n\n if (err) {\n console.log(\"Error in query: \");\n console.log(err);\n callback(err, null);\n }\n var status;\n\n callback(null, status);\n });\n });\n}", "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 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 facebook(cancion, artista) {\n fb.publish({\n message : \"Voté en www.laquesigue.com para que Kurt Dyer toque \"+cancion+\".\",\n picture : \"http://www.laquesigue.com/images/album.png\",\n link : \"http://www.laquesigue.com\",\n name : \"La Que Sigue\",\n description : \"Vota en www.laquesigue.com para que Kurt Dyer toque tu cancion favorita. Patrocinado por 77Digital\"\n },function(published){ \n \n if (published)\n //alert(\"publicado!\");\n \t\tnotifica('Se ha realizado tu voto.<br/>'+cancion+'<br/>'+artista);\n else\n //alert(\"No publicado :(, seguramente porque no estas identificado o no diste permisos\");\n \tnotifica(\"Ocurrio un error :(<br/>No se ha publicado.<br/>Posiblemente por no diste permisos.\");\n });\n}", "function drawNewPost(autor, content) {\r\n\t//console.log(\"CurrentAutor: \" + botAction.currentAutor);\r\n\t//console.log(\"paramAutor: \" + autor);\r\n\t\r\n\tif(botAction.lastAutor == autor && autor != \"\"){\t\r\n\t\r\n\t\tvar p = document.createElement('p');\r\n\t\tp.innerHTML = escapeCharacters(content);\r\n\t\t\r\n\t\tchatBox.lastElementChild.appendChild(p);\r\n\t\t\r\n\t} else {\r\n\t\tvar act = botdata.characters[autor];\r\n\t\t\r\n\t\tvar post = document.createElement('div');\r\n\t\tpost.className = \"fbot_mssg bot\";\r\n\t\t\r\n\t\tif (act.avatar){\r\n\t\t\tvar img = document.createElement('img');\r\n\t\t\timg.src = act.avatar;\r\n\t\t}\r\n\t\t\r\n\t\tvar hd = document.createElement('h1');\r\n\t\tvar name = act.name ? act.name : autor;\r\n\t\thd.innerHTML = name;\r\n\t\thd.style.color = act.color;\r\n\t\t\r\n\t\tvar p = document.createElement('p');\r\n\t\tp.innerHTML = escapeCharacters(content);\r\n\t\t\r\n\t\tif (act.avatar){ post.appendChild(img); }\r\n\t\tpost.appendChild(hd);\r\n\t\tpost.appendChild(p);\r\n\t\t\t\r\n\t\tchatBox.appendChild(post);\r\n\t\tbotAction.lastAutor = autor;\r\n\t}\r\n\tscrollToEnd();\r\n}", "story ({storyId}) {\n\t\t\tif (!storyId) {\n\t\t\t\tthrow new Error(\"storyId required\");\n\t\t\t}\n\n\t\t\treturn (\n\t\t\t\tgithubRest.browse(\n\t\t\t\t\t[\"repos\", \"RickWong/react-transmit\", \"stargazers\"],\n\t\t\t\t\t{query: {per_page: 60, page: storyId}}\n\t\t\t\t).then((stargazers) => {\n\t\t\t\t\t/**\n\t\t\t\t\t * Chain a promise that maps GitHub users into likers.\n\t\t\t\t\t */\n\t\t\t\t\treturn Promise.all(\n\t\t\t\t\t\tstargazers.map((stargazer) => Like.getFragment(\"like\", {stargazer}))\n\t\t\t\t\t);\n\t\t\t\t}).then((likes) => {\n\t\t\t\t\t/**\n\t\t\t\t\t * Just the same story everytime but with different likes :)\n\t\t\t\t\t */\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttitle: \"React Transmit\",\n\t\t\t\t\t\ttext: \"Relay-inspired library based on Promises instead of GraphQL.\",\n\t\t\t\t\t\turl: \"https://github.com/RickWong/react-transmit\",\n\t\t\t\t\t\tlikes: likes\n\t\t\t\t\t};\n\t\t\t\t})\n\t\t\t);\n\t\t}", "function publishCopiedContent (id){\n const publishAPIUrl = publishUrl +'/'+id;\n const httpOptions = {\n headers: {\n 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIyZWU4YTgxNDNiZWE0NDU4YjQxMjcyNTU5ZDBhNTczMiJ9.7m4mIUaiPwh_o9cvJuyZuGrOdkfh0Nm0E_25Cl21kxE',\n 'Content-Type': 'application/json'\n }\n };\n const data = {\n request: {\n content: {\n lastPublishedBy: \"system\"\n }\n }\n }\n try {\n axios.post(publishAPIUrl,data,{headers: httpOptions.headers})\n .then((response) => {\n console.log(\"Successfully Uploaded:\"+ response);\n }).catch((error) => {\n console.log(\"Error in Response Publish Content API:\"+error);\n });\n } catch (error) {\n console.log(\"Error in Publish API Fail:\"+error);\n }\n }", "handlePublished() {\n this.setState({ status: 'PUBLISHED' });\n const data = {\n userId: this.props.reduxStore.user.id,\n status: 'PUBLISHED'\n }\n this.props.dispatch({ type: 'FETCH_DASHBOARD', payload: data });\n }", "async publish(req, draft, options = {}) {\n const m = self.getManager(draft.type);\n return m.publish(req, draft, options);\n }", "function likePublish(idPublish,type){\n\tFormaT.app(\"POST\", \"my\", \n\t{\n\t\t\"action\":\"create\",\n\t\t\"like_add\":true,\n\t\t\"type\":type,\n\t\t\"id_ref\":idPublish\n\t}, function(r){\n\t\tconsole.log(r);\n\t\tif(r.error === false){\n\t\t\tif($(\".total-likes-\"+idPublish).length > 0){\n\t\t\t\t$(\".total-likes-\"+idPublish).text(r.stadistics.likes);\n\t\t\t\t$( \".btn-like-\"+idPublish ).attr( \"href\" , \"#\");\n\n\t\t\t\t$.notify(\"Gracias por tu aporte...\", \"success\");\n\t\t\t}\n\t\t}else{\n\t\t\t$.notify(\"Error sumando tu Like...\", \"success\");\n\t\t}\n\t});\n}", "function pushStoryDuration(data) {\n _.at(window,'__dhpwa__.enableClientLogs') && console.log(\"push StoryDuration: \",data.id);\n push(format(_.deepExtend({\n timespent: data.duration,\n pv_activity: 'story_detail',\n wordcount: data.wordCount,\n imagecount: data.imageCount,\n referrer_flow: _.at(window,'__dhpwa__.referrer.flow') || '',\n referrer_flow_id: _.at(window,'__dhpwa__.referrer.flow_id') || '',\n },commonCarddata(data)),'TIMESPENT_PVACTIVITY'),true)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split the gherkin content from TestRail into lines
formatLinesFromTestrail(testcase) { const arr = this.getGherkinFromTestcase(testcase).replace(/[\r]/g, '').split('\n') .map(Function.prototype.call, String.prototype.trim) .map((line) => { // replace ” by " return line.replace(/”/g, '"'); }) .map((line) => { // remove extra spaces // convert the first character to uppercase return line.replace(/^(Given|When|Then|And)\s+(\w)/i, (match, first, second) => { return first.charAt(0).toUpperCase() + first.slice(1) + ' ' + second.toUpperCase(); }); }) .filter((line) => line.length > 0 && line.indexOf('Scenario:') !== 0) // replace line like: |:header1|:header2| by |header1|header2| .map((line) => { if (line[0] !== '|') { return line; } return line.replace(/\|:/g, '|'); }); // insert a blank line before Examples for (let i = arr.length - 1; i > 0; i--) { if (arr[i].indexOf('Examples') === 0) { arr.splice(i, 0, ''); } } return this.replaceMultiPipesTables(arr); }
[ "pushTestCaseToTestRail(testcase, gherkin) {\n const gherkinSteps = gherkin.split('\\n')\n .slice(3)\n .map(Function.prototype.call, String.prototype.trim);\n const customGherkin = this.formatter.replaceTablesByMultiPipesTables(gherkinSteps.join('\\n'));\n if (testcase.custom_steps && testcase.custom_steps.length > 0) {\n return this.testrailClient.updateCase(testcase.case_id, { custom_steps: customGherkin });\n }\n else if (testcase.custom_steps_separated && testcase.custom_steps_separated.length > 0) {\n const stepsSeparated = gherkinSteps.map((s, index) => {\n const step = {\n content: s\n };\n if (index < testcase.custom_steps_separated.length) {\n if (testcase.custom_steps_separated[index].expected) {\n step.expected = testcase.custom_steps_separated[index].expected;\n }\n }\n return step;\n });\n return this.testrailClient.updateCase(testcase.case_id, { custom_steps_separated: stepsSeparated });\n }\n return this.testrailClient.updateCase(testcase.case_id, { custom_gherkin: customGherkin });\n }", "isValidGherkin(gherkin) {\n if (gherkin === null) {\n return false;\n }\n const lines = gherkin.split('\\n')\n .map(Function.prototype.call, String.prototype.trim)\n .filter((line) => line.length > 0 && line.indexOf('Feature:') !== 0 && line.indexOf('Scenario:') !== 0);\n const re = new RegExp('^(Given|When|And|Then|Examples|\\\\||#)', 'i');\n const validLines = lines.filter((line) => re.test(line));\n let numLinesWithData = 0;\n let isData = false;\n for (let i = 0; i < lines.length; i++) {\n if (lines[i].substr(0, 3) === '\"\"\"') {\n numLinesWithData++;\n isData = !isData;\n continue;\n }\n if (isData) {\n numLinesWithData++;\n continue;\n }\n }\n return (lines.length === validLines.length + numLinesWithData);\n }", "function test_parser(testlist) {\n for each (var testgroup in testlist) {\n var tests = testgroup.split(\"#data\\n\");\n tests = [\"#data\\n\" + test for each(test in tests) if (test)];\n for each (var test in tests) {\n yield parseTestcase(test);\n }\n }\n}", "function parseTestcase(testcase) {\n var lines = testcase.split(\"\\n\");\n\n /* check that the first non-empty, non-comment line is #data */\n for each (var line in lines) {\n if (!line || startsWith(line, \"##\")) {\n continue;\n }\n if (line == \"#data\")\n break;\n log(lines);\n throw \"Unknown test format.\"\n }\n\n var input = [];\n var output = [];\n var errors = [];\n var currentList = input;\n for each (var line in lines) {\n if (startsWith(line, \"##todo\")) {\n todo(false, line.substring(6));\n continue;\n }\n // allow blank lines in input\n if (!line && currentList != input) {\n continue;\n }\n if (!(startsWith(line, \"#error\") ||\n startsWith(line, \"#document\") ||\n startsWith(line, \"#data\"))) {\n if (currentList == output && startsWith(line, \"|\")) {\n \tcurrentList.push(line.substring(2));\n } else {\n\t currentList.push(line);\n }\n } else if (line == \"#errors\") {\n currentList = errors;\n } else if (line == \"#document\") {\n currentList = output;\n }\n } \n //logger.log(input.length, output.length, errors.length);\n return [input.join(\"\\n\"), output.join(\"\\n\"), errors];\n}", "getNewLocalTests() {\n return __awaiter(this, void 0, void 0, function* () {\n const re = /@tcid:(\\d+)$/;\n const reScenario = /^\\s*Scenario(?: Outline)?\\s*:(.*?)$/;\n const testcases = [];\n walk.sync(this.config.featuresDir, (filePath) => {\n if (/\\.feature$/.test(filePath)) {\n const fileContent = fs.readFileSync(filePath).toString();\n const ids = fileContent.split('\\n')\n .filter((line) => re.test(line));\n const scenarios = fileContent.split('\\n')\n .filter((line) => reScenario.test(line));\n if (ids.length === 0 && scenarios.length === 1) {\n testcases.push({\n title: reScenario.exec(scenarios[0])[1].trim(),\n file_path: filePath,\n file_content: fileContent,\n custom_gherkin: fileContent\n });\n }\n }\n });\n return testcases;\n });\n }", "function gotHamletTestamentData () {\n // Join the two texts together into a single string\n let allText = hamletText + ' ' + oldTestamentText;\n // Create a Markov chain generator\n markov = new RiMarkov(4);\n // Load the string of both books into the Markov generator\n markov.loadText(allText);\n // Generate a paragraph of text\n generateParagraph();\n console.log('generated');\n}", "function splitMultilineDiffBlock ({added, removed, value}) {\n let lines = value.split('\\n')\n let blocks = []\n// lines = lines.filter(line=>line.length>0)\n lines.forEach((line, index) => {\n blocks.push({added, removed, value: line})\n if (index < lines.length - 1) blocks.push({value: '\\n'})\n })\n\n return blocks\n}", "function processSourceCode(doc) {\n var body = doc.getBody();\n\n var startingTripleTick = body.findText('```');\n if (!startingTripleTick) return;\n var endTripleTick = body.findText('```', startingTripleTick);\n if (!endTripleTick) return;\n\n var firstLine = startingTripleTick.getElement();\n var lastLine = endTripleTick.getElement();\n\n var rangeBuilder = doc.newRange();\n rangeBuilder.addElementsBetween(firstLine, lastLine);\n var range = rangeBuilder.build();\n var lineRanges = range.getRangeElements();\n var lines = [];\n\n var firstLineIndex = body.getChildIndex(lineRanges[0].getElement());\n var code = \"\";\n\n // Don't iterate over 0th and last line because they are the tripleticks\n lineRanges[0].getElement().removeFromParent();\n for (var i = 1; i < lineRanges.length - 1; ++i) {\n code += lineRanges[i].getElement().asText().getText() + '\\n';\n lineRanges[i].getElement().removeFromParent();\n }\n lineRanges[lineRanges.length-1].getElement().removeFromParent();\n\n var cell = body.insertTable(firstLineIndex)\n .setBorderWidth(0)\n .appendTableRow()\n .appendTableCell();\n\n var params = {\n 'code': code.trim(),\n 'lexer': /```(.*)/.exec(firstLine.asText().getText())[1],\n 'style': 'monokai'\n };\n var response = UrlFetchApp.fetch(\n \"http://hilite.me/api\",\n {\n 'method': 'post',\n 'payload': params\n }\n );\n\n var xmlDoc = XmlService.parse(response.getContentText());\n // The XML document is structured as\n // - comment\n // - div\n // - pre\n // - spans\n var divTag = xmlDoc.getAllContent()[1];\n var preTag = divTag.getAllContent()[0];\n var spans_or_texts = preTag.getAllContent();\n var span_ranges = [];\n\n var startCharIdx = 0;\n for (var i = 0; i < spans_or_texts.length; ++i) {\n var span_or_text = spans_or_texts[i];\n if (span_or_text.getType() == XmlService.ContentTypes.ELEMENT) {\n // We are seeing a span (spans are styled while texts are not)\n var span_range = {\n start: startCharIdx,\n endInclusive: startCharIdx + span_or_text.getValue().length - 1,\n span: span_or_text\n };\n span_ranges.push(span_range);\n }\n startCharIdx += span_or_text.getValue().length;\n }\n\n var getTagColor = function (tag) {\n return tag.getAttribute('style').getValue().match(/#[0-9 a-f A-F]{6}/);\n };\n\n cell.setText(preTag.getValue().trim());\n\n var cellText = cell.editAsText();\n for (var i = 0; i < span_ranges.length; ++i) {\n var span_range = span_ranges[i];\n cellText.setForegroundColor(\n span_range.start,\n span_range.endInclusive,\n getTagColor(span_range.span)\n );\n }\n cell.setBackgroundColor(getTagColor(divTag));\n cell.setFontFamily('Consolas');\n\n processSourceCode(doc);\n}", "function splitLines(text) {\n\t return text.split(/\\r?\\n/);\n\t}", "ensureLineGaps(current) {\n let gaps = [];\n // This won't work at all in predominantly right-to-left text.\n if (this.heightOracle.direction != Direction.LTR)\n return gaps;\n this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, line => {\n if (line.length < 10000 /* Margin */)\n return;\n let structure = lineStructure(line.from, line.to, this.state);\n if (structure.total < 10000 /* Margin */)\n return;\n let viewFrom, viewTo;\n if (this.heightOracle.lineWrapping) {\n if (line.from != this.viewport.from)\n viewFrom = line.from;\n else\n viewFrom = findPosition(structure, (this.pixelViewport.top - line.top) / line.height);\n if (line.to != this.viewport.to)\n viewTo = line.to;\n else\n viewTo = findPosition(structure, (this.pixelViewport.bottom - line.top) / line.height);\n }\n else {\n let totalWidth = structure.total * this.heightOracle.charWidth;\n viewFrom = findPosition(structure, this.pixelViewport.left / totalWidth);\n viewTo = findPosition(structure, this.pixelViewport.right / totalWidth);\n }\n let sel = this.state.selection.primary;\n // Make sure the gap doesn't cover a selection end\n if (sel.from <= viewFrom && sel.to >= line.from)\n viewFrom = sel.from;\n if (sel.from <= line.to && sel.to >= viewTo)\n viewTo = sel.to;\n let gapTo = viewFrom - 10000 /* Margin */, gapFrom = viewTo + 10000 /* Margin */;\n if (gapTo > line.from + 5000 /* HalfMargin */)\n gaps.push(find(current, gap => gap.from == line.from && gap.to > gapTo - 5000 /* HalfMargin */ && gap.to < gapTo + 5000 /* HalfMargin */) ||\n new LineGap(line.from, gapTo, this.gapSize(line, gapTo, true, structure)));\n if (gapFrom < line.to - 5000 /* HalfMargin */)\n gaps.push(find(current, gap => gap.to == line.to && gap.from > gapFrom - 5000 /* HalfMargin */ &&\n gap.from < gapFrom + 5000 /* HalfMargin */) ||\n new LineGap(gapFrom, line.to, this.gapSize(line, gapFrom, false, structure)));\n });\n return gaps;\n }", "toText(string) {\n return Text.of(\n string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)\n )\n }", "function splitSentence() {\n var sentences = document.getElementsByClassName('script-line active')\n var x\n for (x of sentences) {\n x.innerHTML = \"<span>\".concat(x.innerHTML)\n x.innerHTML = x.innerHTML.replace(/ /g,\"</span> <span>\")\n x.innerHTML = x.innerHTML.slice(0,-7)\n d3.selectAll('.script-line.active >span').classed('sentence-word',true)\n }\n }", "function reshapeBio(bio){\n let res = bio.split(\"\\r\\n\")\n let i\n let text = \"\"\n for (i = 0; i < res.length; i++) {\n text += res[i] + \"<br />\"\n }\n return text\n}", "#checkLineBeforeBio(line) {\n if (line.startsWith('----')) {\n this.#messages.styleMessages.push('Horizontal rule before Biography');\n this.#style.bioHasStyleIssues = true;\n this.#headingBeforeBiography = true;\n } else {\n if (line.startsWith(Biography.#HEADING_START)) {\n if (!this.#headingBeforeBiography) {\n this.#style.bioHasStyleIssues = true;\n this.#headingBeforeBiography = true;\n this.#messages.styleMessages.push('Heading or subheading before Biography');\n }\n } else {\n // See https://www.wikitree.com/wiki/Help:Recommended_Tags\n // this might be too aggressive\n if ((line.startsWith('[[')) && (line.endsWith(']]'))) {\n this.#unexpectedLines.push(line);\n }\n if ((line.includes('through the import of')) ||\n (line.includes('collaborative work-in-progress'))) {\n this.#unexpectedLines.push(line);\n }\n }\n }\n }", "function getSteps() {\r\n return ['Donating Guidelines', 'Donation Details', 'Post Donation']\r\n}", "function TfLLineStatusList(props) {\n const lines = props.lineStatuses;\n const lineStatusItems = lines.map((status, index) =>\n <div key={index}>\n <h4>{status.statusSeverityDescription}</h4>\n <p>{status.reason}</p>\n <hr/>\n </div>\n );\n\n return (\n <ListGroup>{lineStatusItems}</ListGroup>\n );\n}", "function splitWordsForPDFExport() {\n breadcrumb('[PAPER] [EXPORT] Splitting words');\n $(\".ql-editor\")[0].children.forEach(child => {\n var isChildPageBreak = (child.tagName === \"CRYPTEEPAGEBREAK\");\n var isChildTableData = (child.tagName === \"CRYPTEETABLEDATA\");\n var isChildTable = (child.tagName === \"CRYPTEETABLE\");\n var isChildList = (child.tagName === \"UL\" || child.tagName === \"OL\");\n var isChildKATEX = (child.querySelectorAll(\".ql-formula\").length); \n if (isChildPageBreak || isChildTableData || isChildTable || isChildList || isChildKATEX) { return; }\n \n var walker = document.createTreeWalker(child, NodeFilter.SHOW_TEXT, null, false);\n var textNodes = [];\n while(node = walker.nextNode()) { textNodes.push(node); }\n textNodes.forEach(textNode => { splitWordsOfText(textNode); });\n\n // turn newlines into a word too so we can give them page numbers\n if (child.firstChild) {\n if (child.firstChild.tagName === \"BR\") { child.setAttribute(\"w\", \"\"); }\n }\n });\n breadcrumb('[PAPER] [EXPORT] Splitted words');\n}", "function layoutLines(text, maxWidth, fontAttrs) {\n let userLines = text\n .replace(/ /g, NBSP)\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line) => {\n const words = line.split(NBSP);\n return {\n line,\n runs: createRuns(words),\n };\n });\n\n return wrapLines(userLines, maxWidth, fontAttrs);\n}", "synchronizeCase(testcase, relativePath) {\n return __awaiter(this, void 0, void 0, function* () {\n const basename = this.slugify(testcase.title);\n const exists = (this.testFiles[testcase.case_id] !== undefined);\n let featurePath = path.resolve(this.config.featuresDir + '/' + relativePath, basename + '.feature');\n const stepDefinitionsExtension = this.config.stepDefinitionsTemplate ?\n path.extname(this.config.stepDefinitionsTemplate).substr(1) : '';\n let stepDefinitionsPath = path.resolve(this.config.stepDefinitionsDir + '/' + relativePath, basename + '.' + stepDefinitionsExtension);\n featurePath = yield uniquefilename.get(featurePath, {});\n stepDefinitionsPath = yield uniquefilename.get(stepDefinitionsPath, {});\n // If the testcase is not on the filesystem, create the desired directory structure\n if (!exists) {\n mkdirp.sync(this.config.featuresDir + '/' + relativePath);\n }\n const gherkin = this.formatter.formatLinesFromTestrail(testcase);\n const remoteFileContent = this.getFeatureFileContent(testcase, gherkin);\n if (!exists) {\n fs.writeFileSync(featurePath, remoteFileContent);\n this.debug('Wrote .feature file');\n if (this.config.stepDefinitionsTemplate) {\n const content = this.getTestFileContent(gherkin, this.config.stepDefinitionsTemplate);\n if (content !== null) {\n mkdirp.sync(this.config.stepDefinitionsDir + '/' + relativePath);\n fs.writeFileSync(stepDefinitionsPath, content);\n }\n this.output(' ' + chalk.green(`Creating ${basename}`));\n }\n }\n else {\n featurePath = this.testFiles[testcase.case_id];\n const localFileContent = fs.readFileSync(featurePath).toString().trim();\n const fileChanged = this.hasGherkinContentChanged(localFileContent, remoteFileContent, true);\n const diffDescription = fileChanged ? chalk.underline('is different') + ' than' : 'is the same as';\n this.debug(`Existing .feature file ${diffDescription} the TestRail version`);\n if (!fileChanged) {\n this.skippedCount = this.skippedCount + 1;\n return Promise.resolve();\n }\n else if (this.config.overwrite.local === true) {\n this.output(' ' + chalk.green(`Overwriting ${basename}`));\n fs.writeFileSync(featurePath, remoteFileContent);\n return Promise.resolve();\n }\n else if (this.config.overwrite.local === 'ask') {\n this.showDiff(basename, localFileContent, remoteFileContent);\n if ((yield this.promptForConfirmation('Do you want to overwrite the local version ?')) === true) {\n fs.writeFileSync(featurePath, remoteFileContent);\n this.output(' ' + chalk.green(`Updated ${basename}`));\n }\n else {\n this.output(' ' + chalk.yellow(`Skipping ${basename}`));\n }\n }\n else if (this.config.overwrite.remote === true) {\n this.output(' ' + chalk.green(`Pushing ${basename} to TestRail`));\n yield this.pushTestCaseToTestRail(testcase, localFileContent);\n }\n else if (this.config.overwrite.remote === 'ask') {\n this.showDiff(basename, remoteFileContent, localFileContent);\n if ((yield this.promptForConfirmation('Do you want to override the TestRail version ?')) === true) {\n this.output(' ' + chalk.green(`Pushing ${basename} to TestRail`));\n yield this.pushTestCaseToTestRail(testcase, localFileContent);\n }\n else {\n this.output(' ' + chalk.yellow(`Skipping ${basename}`));\n }\n }\n else {\n this.output(' ' + chalk.yellow(`Skipping ${basename}`));\n return Promise.resolve();\n }\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SC is setcode in decimal. This handles all possible combinations.
function fSetcode(obj, sc) { var val = obj.setcode, hexA = val.toString(16), hexB = sc.toString(16); if (val === sc || parseInt(hexA.substr(hexA.length - 4), 16) === parseInt(hexB, 16) || parseInt(hexA.substr(hexA.length - 2), 16) === parseInt(hexB, 16) || (val >> 16).toString(16) === hexB) { return true; } else { return false; } }
[ "getCategoryIndex(cs, ss) {\n let v, i, o, s = 1 << cs[0] | 1 << cs[1] | 1 << cs[2] | 1 << cs[3] | 1 << cs[4];\n for (i = -1, v = o = 0; i < 5; i++, o = Math.pow(2, cs[i] * 4)) {\n v += o * ((v / o & 15) + 1);\n }\n v = v % 15 - ((s / (s & -s) == 31) || (s == 0x403c) ? 3 : 1);\n v -= Number(ss[0] == (ss[1] | ss[2] | ss[3] | ss[4])) * ((s == 0x7c00) ? -5 : 1);\n return v;\n }", "function CSng(num) {\n var dec=7;\n var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);\n return result;\n}", "function smashFactor(bs, cs) {\n\treturn Math.round(bs / cs * 100) / 100;\n}", "function coinCombo(cents) {\n return 'TODO'\n}", "function fromdecimal(inval, sys){\n //force default system\n if (sys<=1 || sys==undefined){ sys = 2 }\n\n var output = \"\"\n var nextval = inval\n var digit\n\n while (nextval!=0){\n digit = nextval%sys\n if (digit > 9) {\n digit = String.fromCharCode(55 + digit)\n }\n output = digit.toString() + output\n nextval = Math.floor(nextval/sys)\n }\n return output\n}", "function coinCombination(pence){\n//Decalre accunaltor \nvar acc = Number(\"\");\n//declare required value\nvar value = pound;\n// declare counter as factor multibly\nvar counter; \n// code of combination by recursion\n\n\n\nreturn acc;\n}", "ClassChecker(scop){\n\n var equ = {}\n var slotid = \"\"\n var s = \"\";\n for(var i = 1; i < 15; i++){\n slotid = \"slot\".concat(i.toString());\n s = document.getElementById(slotid).value\n if(Object.keys(equ).indexOf(s)!=-1){\n equ[s] = equ[s] + 1;\n } else {\n equ[s] = 1;\n }\n }\n\n if(scop.set>=0 && scop.set<4){\n return(\"DD\")\n }\n if(scop.set>=4 && scop.set<11){\n if(Object.keys(equ).indexOf(\"Heavy_Cruiser_Battery_1\") != -1 || Object.keys(equ).indexOf(\"Heavy_Cruiser_Battery_2\") != -1 || Object.keys(equ).indexOf(\"Heavy_Cruiser_Battery_3\") != -1 || Object.keys(equ).indexOf(\"Heavy_Cruiser_Battery_4\") != -1 || \n Object.keys(equ).indexOf(\"Heavy_Battery_1\") != -1 || Object.keys(equ).indexOf(\"Heavy_Battery_2\") != -1 || Object.keys(equ).indexOf(\"Heavy_Battery_3\") != -1 || Object.keys(equ).indexOf(\"Heavy_Battery_4\") != -1){\n return(\"CA\")\n } else {\n return(\"CL\")\n }\n }\n if(scop.set>=11 && scop.set<17){\n if(Object.keys(equ).indexOf(\"Battlecruiser_Armor_1\") != -1 || Object.keys(equ).indexOf(\"Battlecruiser_Armor_2\") != -1 || Object.keys(equ).indexOf(\"Battlecruiser_Armor_3\") != -1){\n return(\"BC\")\n } else {\n return(\"BB\")\n }\n }\n if(scop.set>=17 && scop.set<22){\n return(\"SS\")\n }\n if(scop.set>=22 && scop.set<27){\n return(\"CV\")\n }\n }", "static get ROUNDING_DIGITS() {return 2;}", "function setCurrencyPrefixNF(cp)\n{\n this.currencyPrefix = cp;\n}", "function setCommasNF(isC)\n{\n this.isCommas = isC;\n}", "function decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n }", "selectInputSourceSatCbl() {\n this._selectInputSource(\"i_sat_cbl\");\n }", "function CCur(num) {\n var dec=4;\n var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);\n return result;\n}", "function checkForDecimal(arr) {\n return arr.length === new Set(arr).size;\n }", "function makeNumIsoH(code, bonds) {\n var valence;\n\n if (code === 15) {\n valence = 0;\n } else if (code === 0) {\n valence = -1;\n } else {\n // num_iso_H should never be negative when valence is set\n valence = Math.max(0, code - bonds);\n }\n\n return [valence, 0, 0, 0];\n }", "function setCurrencyPositionNF(cp)\n{\n\tthis.currencyPosition = cp\n}", "switchCurrencies() {\n [this.selectedFromCurrency, this.selectedToCurrency] = [\n this.selectedToCurrency,\n this.selectedFromCurrency,\n ];\n shake(\"#exchange-calculator\");\n }", "function prefixToBase(c)\n\t{\n\t\tif (c === CP_b || c === CP_B) {\n\t\t\t/* 0b/0B (binary) */\n\t\t\treturn (2);\n\t\t} else if (c === CP_o || c === CP_O) {\n\t\t\t/* 0o/0O (octal) */\n\t\t\treturn (8);\n\t\t} else if (c === CP_t || c === CP_T) {\n\t\t\t/* 0t/0T (decimal) */\n\t\t\treturn (10);\n\t\t} else if (c === CP_x || c === CP_X) {\n\t\t\t/* 0x/0X (hexadecimal) */\n\t\t\treturn (16);\n\t\t} else {\n\t\t\t/* Not a meaningful character */\n\t\t\treturn (-1);\n\t\t}\n\t}", "function setCurrencyPrefixNF(cp)\n{\n\tthis.setCurrencyValue(cp);\n\tthis.setCurrencyPosition(this.LEFT_OUTSIDE);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get recent tracks, possible to switch user and the limit
function getRecentTracks(currentPage = 1, user = 'denniswegereef', limit = 19) { const key = '558413ce30002869acf1d2e2d9c2047b', url = 'http://ws.audioscrobbler.com/2.0/' let currentUser = 'dennis' const totalRequest = `${url}?method=user.getrecenttracks&user=${user}&api_key=${key}&format=json&page=${currentPage}&extended=1&limit=${limit}` let promise = new Promise((resolve, reject) => { fetch(totalRequest) .then(res => res.json()) .then(res => resolve(res)) .catch(err => { reject(err) }) }) return promise }
[ "async retrieveUserTopTracks() {\n let topTracks = await this.spotify.getMyTopTracks();\n const features = await this.getAudioFeatures(topTracks.body.items);\n return features;\n }", "getBoughtTracks () {\n return music.getBoughtTracks().then((response) => {\n return response.data\n })\n }", "getTracks() {\n return new Promise((resolve, reject) => {\n this._get('/tracks').then((response) => { resolve(response) });\n })\n }", "function getPopularTrackCovers(tracks, limit = 4) {\n if (tracks.length > 0) {\n return [...tracks]\n .sort((a, b) => b.popularity - a.popularity)\n .slice(0, limit)\n .map(track => track.image);\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 }", "function TwineToysGetTrackers() {\n return valueTrackers\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}", "async function getAllTracks(req, res) {\n\tvar Alltracks = await mongoConnection.queryFromMongoDB('Tracks', {}, 1000);\n\n\tres.json(Alltracks);\n}", "async function getTracks(id) {\n return redis.hgetallAsync(`playlist:${id}`);\n}", "async getRecommendedTracksAndCreatePlaylist() {\n await spotifyApi.setAccessToken(this.options.access_token);\n\n let usersTopIds = await this.getUsersTopIds();\n let recommendedTracks = [];\n\n if (usersTopIds.seed_artists && usersTopIds.seed_artists.length > 0) {\n const recommendedTracksFromCall = await this.getRecommendedTracks(\n usersTopIds.seed_artists, 'seed_artists');\n recommendedTracks = recommendedTracks.concat(recommendedTracksFromCall);\n }\n\n if (usersTopIds.seed_tracks && usersTopIds.seed_tracks.length > 0) {\n const recommendedTracksFromCall = await this.getRecommendedTracks(\n usersTopIds.seed_tracks, 'seed_tracks');\n recommendedTracks = recommendedTracks.concat(recommendedTracksFromCall);\n }\n\n const recommendedPlaylist = await this.createPlaylist(recommendedTracks);\n return {\n recommendedList: recommendedPlaylist,\n playListId: this.playListId\n }\n }", "function track_api(page) {\n let fmaWsUrl = `https://freemusicarchive.org/api/get/tracks.json?api_key=${FMA_API}&album_id=${\n release_attributes.albumid\n }&limit=20&page=${parseInt(page)}`;\n\n var promise_track_api = $.getJSON(fmaWsUrl, function () {\n LOGGER.debug(`promise_track_api_params [state] in [getJSON] ${promise_track_api.state()}`);\n }).done(function (tracksjson) {\n LOGGER.debug(` >> Track page ${page} > DONE `);\n LOGGER.debug(tracksjson);\n tracks_api_array.push(tracksjson.dataset);\n });\n\n return promise_track_api.promise();\n}", "function getSongs(Query) {\n var spotify = new Spotify(LiriTwitterBOT.spotify);\n if (!Query) {\n Query = \"what's+my+age+again\";\n };\n spotify.search({ type: 'track', query: Query }, function(err, data) {\n if ( err ) {\n console.log('Error occurred: ' + err);\n return;\n }\n console.log(data);\n // Do something with 'data' \n });\n\n // var queryURL = 'https://api.spotfiy.com/v1/search?q=' + query + '&limit=5&type=track';\n // request(queryURL, function(err, response, body) {\n // if (err) {\n // console.log(err);\n // };\n // body = JSON.parse(body);\n // console.log(body);\n // for (var i = 0; i < body.tracks.items.length; i++) {\n // logObject = input + \", \" + query + \", \" + body.tracks.items[i].artists[0].name + \", \" + body.tracks.items[i].name\n // body.tracks.items[i].name + \", \" + body.tracks.items[i].preview_url + \", \" + body.tracks.items[i].album.name + \"\\n\";\n // }; //end of loop\n // writeLog(logObject);\n // });\n}", "function getRecentVideos( age ){\n var videoCollection = new Array();\n // get an array of avalible videos for this age\n if( Object.keys(video_player_data).length > 0 ){\n for (let i = 0; i < Object.keys(video_player_data).length; i++) { //recorre cada lista\n let key = Object.keys(video_player_data)[i];\n \n if( video_player_data[key][\"age\"] == 0 || video_player_data[key][\"age\"] == age ){\n for(let j = 0; j < Object.keys(video_player_data[key][\"type\"]).length; j++) { //recorre cada type\n let type_key = Object.keys(video_player_data[key][\"type\"])[j]\n\n for (let k = 0; k < Object.keys(video_player_data[key][\"type\"][type_key][\"playList\"]).length; k++) { //recorre el playlist\n let list_key = Object.keys(video_player_data[key][\"type\"][type_key][\"playList\"])[k]; \n\n videoCollection.push({\n \"key\": key, \n \"type_key\": type_key, \n \"list_key\": list_key,\n \"date\" : video_player_data[key][\"type\"][type_key][\"playList\"][list_key][\"date\"]\n });\n }\n }\n }\n }\n }\n\n // order the array by dates\n videoCollection.sort((a, b) => {\n let c = new Date(a.date);\n let d = new Date(b.date);\n \n return d - c;\n });\n\n return videoCollection;\n}", "function getTimePlayed(track) {\n /* YOUR CODE HERE */\n}", "function getTrending(dbserver, hostname, limit, cb) {\n var query = \"SELECT * FROM Tracklist t1 WHERE time_stamp = \" + \n \"(SELECT MAX(time_stamp) from Tracklist t2 WHERE t1.post_id = t2.post_id) \";\n\n if (hostname) { query += \"AND hostname = '\" + hostname + \"' \";}\n query += \"ORDER BY note_delta DESC \";\n if (limit) { query += \"LIMIT \" + limit; }\n\n dbserver.query(query, \n function(err, results) {if (err) throw err; \n cb(results);});\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 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 }", "function loadRecent() {\n \n if (paginationOptions.pageFirst > 0) {\n paginationOptions.pageFirst = 0;\n }\n viewsOptions.page = paginationOptions.pageFirst;\n\n return retreiveArticles(viewsOptions);\n }", "function LastFM_top_artists(username = 'paul_r_schaefer') {\n\tLastFM.user.getTopArtists({ user: username }, (err, data) => {\n\t\tif (err) console.error(err)\n\t\telse {\n\t\t\t// console.log(data['artist']);\n\t\t\treturn data;\n\t\t}\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 535 Given a sandwich (as an array), return an array of fillings inside the sandwich. This involves ignoring the first and last elements.
function getFillings(sandwich) { return sandwich.slice(1, -1); }
[ "function makeSandwich(ingredients, flavour) {\n\tconst a = [];\n\tfor (let i = 0; i < ingredients.length; i++) {\n\t\tif (ingredients[i] === flavour) {\n\t\t\ta.push(\"bread\");\t\t\t\n\t\t\ta.push(ingredients[i]);\n\t\t\ta.push(\"bread\");\n\t\t} else {\n\t\t\ta.push(ingredients[i]);\n\t\t}\n\t}\n\treturn a;\n}", "function hailstoneSequence () {\n const res = [];\n // Good luck!\n\n return res;\n}", "function buyFruit(array) {\n return array.map(subArray => {\n return repeat(subArray[0], subArray[1]);\n })\n .reduce((acc, value) => acc.concat(value));\n}", "function towerBuilder(nFloors) {\n // build here\n var lineOfStars = []\n // Creating an empy array to store our result\n for (var i = 0; i < nFloors; i++) {\n lineOfStars.push(\" \".repeat(nFloors-i-1) + \"*\"+\"*\".repeat(i*2) + \" \".repeat(nFloors-i-1))\n \n }\n console.log(lineOfStars);\n return lineOfStars\n }", "function find_possible_implicants(array)\n{\n\tvar implicants = [];\n\timplicants[0] = array.slice();\n\tfor (var x = 0; x < array[0].length; x++)\n\t{\n\t\tremove_duplicates(implicants[x]);\n\t\tvar current_coloumn = implicants[x].slice();\n\t\tvar next_coloumn = [];\n\t\tfor (var i = 0; i < implicants[x].length; i++)\n\t\t{\n\t\t\tfor (var j = i+1; j < implicants[x].length; j++)\n\t\t\t{\n\t\t\t\tremove_duplicates(implicants[x]);\n\t\t\t\tvar implicant = find_implicant(implicants[x][i],implicants[x][j]);\n\t\t\t\tif (implicant)\n\t\t\t\t{\n\t\t\t\t\tremove_item(current_coloumn,implicants[x][i]);\n\t\t\t\t\tremove_item(current_coloumn,implicants[x][j]);\n\t\t\t\t\tnext_coloumn.push(implicant);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tremove_duplicates(next_coloumn);\n\t\timplicants[x] = current_coloumn.slice();\n\t\tif (next_coloumn.length)\n\t\t{\n\t\t\timplicants[x+1] = next_coloumn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn implicants;\n\t\t}\n\t}\n\treturn implicants;\n}", "function menStillStanding(array) {\n let teamA = 11,\n teamB = 11;\n\n if (array.length === 0) {\n return [teamA, teamB];\n }\n\n let cardsArray = [...array];\n\n cardsArray.forEach((item) => {\n let yellowCards = 0;\n let redCards = 0;\n let player = item.substring(0, item.length - 1);\n\n for (let card of cardsArray) {\n card === `${player}Y` ? ++yellowCards : null;\n card === `${player}R` ? ++redCards : null;\n if (teamA < 7 || teamB < 7) {\n break;\n }\n if (redCards === 1 || yellowCards == 2) {\n player.includes('A') ? --teamA : --teamB;\n break;\n }\n\n }\n cardsArray = cardsArray.filter(card => card != item);\n });\n return [teamA, teamB];\n}", "function genMEBands(digestArray, enzymes, seqCount) {\r\n var bands = [];\r\n //loop the digestArray\r\n $.each(digestArray, function (i, d) {\r\n //enzymes are all the cuts for the current plasmid\r\n var cuts = $.grep(enzymes, function (sd, si) {\r\n //return all the cuts in d, array of digesiton enzymes\r\n return $.inArray(sd.name, d) != -1;\r\n })\r\n //sort cuts by the cut position from small to big\r\n cuts.sort(sortByProperty('cut'));\r\n \r\n var hasMethylation = false; //tag for methylation later on\r\n if (cuts.length > 0) {\r\n //-------------------------first ignore the methylation\r\n var curBands = [];\r\n for (var i = 0; i < cuts.length; i++) {\r\n if (cuts[i].methylation == true) {\r\n //tag this to add an extra lane on gel\r\n hasMethylation = true;\r\n }\r\n var obj = {};\r\n obj.label = d.reverse().join(\"-\");\r\n obj.type = \"cut\";\r\n if (i == cuts.length - 1) {\r\n obj.name = cuts[cuts.length - 1].name + '-' + cuts[0].name;\r\n obj.clockwise = cuts[cuts.length - 1].clockwise + '-' + cuts[0].clockwise;\r\n obj.bandRange = cuts[cuts.length - 1].cut == seqCount ? '1-' + cuts[0].cut : cuts[cuts.length - 1].cut + '-' + cuts[0].cut;\r\n obj.Size = cuts[cuts.length - 1].cut == seqCount ? cuts[0].cut : (seqCount - cuts[cuts.length - 1].cut + cuts[0].cut);\r\n obj.Mass = 100;\r\n }\r\n else {\r\n obj.name = cuts[i].name + '-' + cuts[i + 1].name;\r\n obj.clockwise = cuts[i].clockwise + '-' + cuts[i+1].clockwise;\r\n obj.bandRange = cuts[i].cut + '-' + cuts[i + 1].cut;\r\n obj.Size = cuts[i + 1].cut - cuts[i].cut;\r\n obj.Mass = 100;\r\n }\r\n obj.logSize = +Math.log10(obj.Size).toFixed(3);\r\n curBands.push(obj);\r\n }//end of for loop\r\n if (curBands.length > 0) {\r\n bands.push(curBands);\r\n }\r\n\r\n //---------------------------- deal with methylation\r\n if (hasMethylation) {\r\n var methyBands = []; //final return array\r\n //remove all the cuts in cuts that has methylation ==true\r\n var cutsCopy = []; //temp array, for removing completely blocked\r\n cutsCopy = $.grep(cuts, function (v) {\r\n return v.methylation != true;\r\n });\r\n\r\n if (cutsCopy.length === 0) {\r\n //nothing left, generate the circular plasmid\r\n var obj = {};\r\n obj.clockwise = null;\r\n obj.name = d.reverse().join(\"-\") + ':' + 'methy';\r\n obj.label = d.reverse().join(\"-\") + ':' + 'methy';\r\n obj.type = \"cut\";\r\n obj.bandRange = \"0-0\"; //if \"0-0\", then it is circular\r\n obj.Size = seqCount;\r\n obj.Mass = 100;\r\n obj.logSize = +Math.log10(obj.Size).toFixed(3);\r\n methyBands.push(obj);\r\n }\r\n else {\r\n //assume always completely cut\r\n for (var i = 0; i < cutsCopy.length; i++) {\r\n var obj = {};\r\n obj.clockwise = cutsCopy[i].clockwise;\r\n obj.label = d.reverse().join(\"-\") + ':' + 'methy';\r\n obj.type = \"cut\";\r\n if (i == cutsCopy.length - 1) {\r\n obj.name = cuts[cuts.length - 1].name + '-' + cuts[0].name;\r\n obj.clockwise = cuts[cuts.length - 1].clockwise + '-' + cuts[0].clockwise;\r\n obj.bandRange = cutsCopy[cutsCopy.length - 1].cut == seqCount ? '1-' + cutsCopy[0].cut : cutsCopy[cutsCopy.length - 1].cut + '-' + cutsCopy[0].cut;\r\n obj.Size = cutsCopy[cutsCopy.length - 1].cut == seqCount ? cutsCopy[0].cut : (seqCount - cutsCopy[cutsCopy.length - 1].cut + cutsCopy[0].cut);\r\n obj.Mass = 100;\r\n }\r\n else {\r\n obj.name = cuts[i].name + '-' + cuts[i + 1].name;\r\n obj.clockwise = cuts[i].clockwise + '-' + cuts[i + 1].clockwise;\r\n obj.bandRange = cutsCopy[i].cut + '-' + cutsCopy[i + 1].cut;\r\n obj.Size = cutsCopy[i + 1].cut - cutsCopy[i].cut;\r\n obj.Mass = 100;\r\n }\r\n obj.logSize = +Math.log10(obj.Size).toFixed(3);\r\n methyBands.push(obj);\r\n }\r\n }//end of cutsCopy.length\r\n if (methyBands.length > 0) {\r\n bands.push(methyBands);\r\n }\r\n\r\n }//end of hasMethylation\r\n } //end of cuts.length\r\n }) // end of looping digestarray\r\n\r\n return bands;\r\n}", "function indexAlgorithm(){\n\tvar temp = [];\n\tvar offset = 36;\n\tvar totalPoints = (revA.length/3);\n\tvar i = 0;\n\tfor (i = 0; i < totalPoints-offset; i++){\n\t\tif (i != 0 && (i+1) % 36 == 0) {\n\t\t\ttemp.push(i);\n\t\t\ttemp.push(i-35);\n\t\t\ttemp.push(i+offset);\n\t\t\t\n\t\t\ttemp.push(i-35);\n\t\t\ttemp.push(i+offset);\n\t\t\ttemp.push(i-35+offset);\n\t\t} else {\n\t\t\ttemp.push(i);\n\t\t\ttemp.push(i+1);\n\t\t\ttemp.push(i+offset);\n\t\t\t\n\t\t\ttemp.push(i+1);\n\t\t\ttemp.push(i+1+offset);\n\t\t\ttemp.push(i+offset);\n\t\t}\n\t}\n\ttemp.push(i-offset);\n\treturn temp;\n}", "function pickCards(array) {\n let startArr = array;\n let pickedArr = [];\n for (let i = 0; i < 8; i++) {\n let ranNum = (Math.floor(Math.random() * startArr.length));\n pickedArr.push(startArr[ranNum]);\n pickedArr.push(startArr[ranNum]);\n startArr.splice(ranNum, 1);\n }\n return pickedArr;\n}", "function TrappingWater(arr) {\n let area = 0;\n for (let i = 1, m = Math.max(...arr); i < m + 1; i ++) {\n for (let i2 = 0, gate = false; i2 < arr.length; i2 ++) {\n let freeSpace = arr[i2] < i;\n \n if (!freeSpace)\n gate = true;\n else if (gate)\n area ++;\n }\n }\n return area;\n}", "function pyramid(n) {\n let arr = [];\n if (n == 0){\n return arr;\n } else {\n for(var i=0;i<n;i++){\n arr[i] = Array((i+1)).fill(1);\n }\n return arr;\n }\n}", "function crystValues(){\n for (i = 0; i < gemArray.length; i++) {\n gemArray[i] = Math.floor(Math.random() * 12) + 1;\n} \n//prints values of each item\n //console.log(gemArray);\n}", "function generateBombs() {\n bombs = []\n for (i = 0; i < 400; i++) {\n arr[i] = i + 1;\n }\n for (let i = 0; i < numOfBombs; i++) {\n let index = Math.floor(Math.random() * arr.length);\n bombs.push(arr.splice(index, 1)[0]);\n }\n}", "function pipeFix(numbers){\n let y = numbers[0];\n let z = numbers[numbers.length-1];\n \n let x = [];\n for(var i = y; i <= z; i++) {\n x.push(i);\n }\n return x;\n}", "function twenty0neGuns() {\n var crimeColors = [];\n for (var i = 0; i < unique_crime.length; i++) {\n crimeColors.push(color());\n }\n return crimeColors;\n}", "function array6x6() {\n let m = Array.from({length: 6}, e => Array(6).fill({key:true}));\n // let m = Array.from({length: 6}, e => Array(6).fill(0)); \n return m \n }", "function gemstones(arr) {\n let n = arr.length;\n let obj = {};\n let count = 0;\n for(let i = 0; i < n; i++){\n for(let j = 0; j < arr[i].length; j++){\n if((!obj[arr[i][j]] && i == 0) | obj[arr[i][j]] == i) {\n obj[arr[i][j]] = i + 1;\n if(obj[arr[i][j]] == n) count++;\n }\n }\n }\n return count;\n}", "function getPasswordsNotUsedBefore (array) {\n let elements = [];\n for(let i = 0; i < array.length; i++) {\n if(array.slice(0, i).includes(array[i])) {\n elements.push(false);\n } else {\n elements.push(array[i]);\n }\n }\n return elements;\n}", "function shuffle_filler_conc(shuffled_indices) {\n c_list = [];\n for (var i = 0; i < shuffled_indices.length; i++) {\n index = shuffled_indices[i];\n c_list = _.concat(c_list, filler_conclusion[index])\n }\n return c_list;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates a new marker object that consist of the coordinates, the formatted address, and info window
newMarker(addressCoord, addressPretty){ console.log(addressPretty) let contentString = ` <div id="content> <div id="siteNotice"> </div> <h1 id="firstHeading" class="firstHeading">Current Location:</h1> <div id="bodyContent"> ${addressPretty} </div> </div>`; let infowindow = new google.maps.InfoWindow({ content: contentString }); this.markerList.push({ address: addressPretty, location: addressCoord, infoWindow: infowindow }); this.initMap(); }
[ "function createMarker(point, narrative) {\n\t var marker = new GMarker(point,{draggable: false, bouncy: false});\n\t GEvent.addListener(marker, \"click\", function() {\n\t marker.openInfoWindowHtml(narrative);\n\t }); \n\treturn marker;\n}", "function markerFactory(latitude, longitude, title, message) {\n //Generate a json object for location\n var myLatLng = {\n lat: latitude,\n lng: longitude\n };\n //Generate a content string\n var contentString = contentStringFactory(title, message);\n //Create a new info window with the above content\n var infowindow = new google.maps.InfoWindow({\n content: contentString\n });\n //Set a marker with the above location\n var marker = new google.maps.Marker({\n position: myLatLng,\n map: map,\n title: 'Hello World!'\n });\n marker.addListener('click', function () {\n infowindow.open(map, marker);\n });\n marker.setMap(map);\n}", "function markerMaker(point, icono, name) {\r\n\t\tvar om = L.marker([point.lat, point.lon], {\r\n\t\t\ticon: icono\r\n\t\t}).bindPopup(name);\r\n\r\n\t\treturn om;\r\n\r\n\t}", "function addSingleMaker(){\n\tmarker = new google.maps.Marker({\n\t\tposition:{\n\t\t\tlat: -41.295005,\n\t\t\tlng: 174.78362\n\t\t},\n\t\tmap: map,\n\t\tanimation: google.maps.Animation.DROP,\n\t\ticon: \"images/icon.png\",\n\t\ttitle : \"Yoobee School of Design\",\n\t\tdescription: \"Description for Yoobee School of Design\"\n\t})\n}", "function addMarker(coords, content, icon) {\n\n var marker = new google.maps.Marker({ position: coords, map: map, icon: icon });\n\n var infoWindow = new google.maps.InfoWindow({\n content: content\n });\n\n // Opens info box\n marker.addListener(\"click\", function () {\n infoWindow.open(map, marker);\n });\n\n}", "function createStudentMarker(student) {\n\tvar student_latlng = new google.maps.LatLng(student.lat, student.lng);\n \tvar studentContentString = \"login: \" + student.login + \"<br>lat/lng: \" + student.lat +\n \", \" + student.lng + \"<br>timestamp: \" + student.created_at;\n\n \t//creats a marker for them with location\n\tvar marker = new google.maps.Marker({\n\t\tmap: map,\n\t\tposition: student_latlng\n\t});\n\n \t//shows information in infowindow on a click\n\tgoogle.maps.event.addListener(marker, 'click', function() {\n\t \tinfowindow.close();\n\t \tinfowindow.setContent(studentContentString);\n\t \tinfowindow.open(map, this);\n\t});\n}", "function createMarkers(div) {\n div.each(function() {\n j.push({\n type: 'Feature',\n \"geometry\": {\n \"type\": \"Point\",\n // of note: for some reason that lat/long need to be reversed here such that it is long/lat\n \"coordinates\": [this['dataset']['long'], this['dataset']['lat']]\n //[$(this).data('data-long'), $(this).data('data-lat')]\n }, // close geometry\n // This is for a custom marker on the map\n \"properties\": {\n \"title\": \"Here, I realized . . .\",\n \"icon\": {\n \"iconUrl\": this['dataset']['image'],\n \"iconSize\": [50, 50], // size of the icon\n \"iconAnchor\": [25, 25], // point of the icon which will correspond to marker's location\n \"popupAnchor\": [0, -25] // point from which the popup should open relative to the iconAnchor\n },\n // These are the images for the photo display\n // Store the image url and caption in an array\n \"images\": [[this['dataset']['image'], this['dataset']['caption']]]\n }, //close properties\n }); // close push\n }); //close you_images function\n } // end of markers function", "function addMarker(bus){\n\tvar icon = getIcon(bus);\n\tvar marker = new google.maps.Marker({\n\t position: {\n\t \tlat: bus.attributes.latitude, \n\t \tlng: bus.attributes.longitude\n\t },\n\t map: map,\n\t icon: icon,\n\t id: bus.id\n\t});\n\tmarkers.push(marker);\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}", "marker(lat, long, map, icon){\n marker = new google.maps.Marker({\n position: {lat: lat, lng: long},\n map: map,\n icon: icon,\n animation: google.maps.Animation.DROP\n })\n\n ////Call the ShowDetails view and render the details\n google.maps.event.addListener(marker, 'click', () => {\n ShowDetails.renderDetails($('#details'), this)\n })\n return marker\n }", "function populateInfoWindow(marker, infowindow) {\n // Check to make sure the infowindow is not already opened on this marker.\n if (infowindow.marker != marker) {\n infowindow.marker = marker;\n infowindow.setContent('<div>' + marker.title + '</div>');\n infowindow.open(map, marker);\n // Make sure the marker property is cleared if the infowindow is closed.\n infowindow.addListener('closeclick',function(){\n infowindow.setMarker = null;\n });\n }\n\n\n\n /*\n var unida = {lat: -7.901727, lng: 111.490886};\n var marker = new google.maps.Marker({\n position: unida,\n map: map,\n title: 'Universitas Darussalam'\n });\n\n var gontor1 = {lat: -7.928088, lng: 111.498257};\n var marker = new google.maps.Marker({\n position: gontor1,\n map: map,\n title: ' Darussalam Gontor 1'\n });\n\n var gontor2 = {lat: -7.906734, lng: 111.460334};\n var marker = new google.maps.Marker({\n position: gontor2,\n map: map,\n title: ' Darussalam Gontor 2'\n });\n\n var gontor3 = {lat: -7.818782, lng: 112.100732};\n var marker = new google.maps.Marker({\n position: gontor3,\n map: map,\n title: \" Darul-Ma'rifat\"\n });\n\n var gontor5 = {lat: -8.364064, lng: 114.309947};\n var marker = new google.maps.Marker({\n position: gontor5,\n map: map,\n title: \" Darul-Muttaqien\"\n });\n\n var gontor6 = {lat: -7.536011, lng: 110.298138};\n var marker = new google.maps.Marker({\n position: gontor6,\n map: map,\n title: \" Darul-Qiyam\"\n });\n\n var gontor7 = {lat: -4.158685, lng: 122.252755};\n var marker = new google.maps.Marker({\n position: gontor7,\n map: map,\n title: \" Riyadhatul-Mujahidin\"\n });\n\n var gontor8 = {lat: -5.103757, lng: 105.676265};\n var marker = new google.maps.Marker({\n position: gontor8,\n map: map,\n title: \" Darussalam gontor 8\"\n });\n\n var gontor9 = {lat: -5.679273, lng: 105.623594};\n var marker = new google.maps.Marker({\n position: gontor9,\n map: map,\n title: \" Darussalam gontor 9\"\n });\n\n var gontor10 = {lat: 5.365207, lng: 95.618466};\n var marker = new google.maps.Marker({\n position: gontor10,\n map: map,\n title: \" Darul-Amien\"\n });\n\n var gontor11 = {lat: -0.611920, lng: 100.600308};\n var marker = new google.maps.Marker({\n position: gontor11,\n map: map,\n title: \" Darussalam Gontor 11\"\n });\n\n var gontor12 = {lat: -1.257572, lng: 103.805444};\n var marker = new google.maps.Marker({\n position: gontor12,\n map: map,\n title: \" Darussalam Gontor 12\"\n });\n\n var gontor13 = {lat: -1.335754, lng: 120.644935};\n var marker = new google.maps.Marker({\n position: gontor13,\n map: map,\n title: \" Ittihadul-Ummah\"\n });\n\n var gontor14 = {lat: 0.871726, lng: 101.688043};\n var marker = new google.maps.Marker({\n position: gontor14,\n map: map,\n title: \"Darussalam gontor 14\"\n });\n\n var gontor15 = {lat: -7.372894, lng: 111.175173};\n var marker = new google.maps.Marker({\n position: gontor15,\n map: map,\n title: \"Darussalam gontor Female 1\"\n });\n\n var gontor16 = {lat: -7.370894, lng: 111.171899};\n var marker = new google.maps.Marker({\n position: gontor16,\n map: map,\n title: \"Darussalam gontor Female 2\"\n });\n\n var gontor17 = {lat: -7.385967, lng: 111.249172};\n var marker = new google.maps.Marker({\n position: gontor17,\n map: map,\n title: \"Darussalam gontor Female 3\"\n });\n\n var gontor18 = {lat: -4.153652, lng: 122.491300};\n var marker = new google.maps.Marker({\n position: gontor18,\n map: map,\n title: \"Darussalam gontor Female 4\"\n });\n\n var gontor19 = {lat: -7.748927, lng: 112.258033};\n var marker = new google.maps.Marker({\n position: gontor19,\n map: map,\n title: \"Darussalam gontor Female 5\"\n });\n\n var gontor20 = {lat: -1.333141, lng: 120.645247};\n var marker = new google.maps.Marker({\n position: gontor20,\n map: map,\n title: \"Darussalam gontor Female 6\"\n });\n\n var gontor21 = {lat: -0.436215, lng: 101.317802};\n var marker = new google.maps.Marker({\n position: gontor21,\n map: map,\n title: \"Darussalam gontor Female 7\"\n });*/\n\n }", "function addMarker(cityDetail) {\n let shape = {\n coords: [0, 0, 0, 25, 25, 25, 25, 0],\n type: 'poly'\n };\n let marker = new google.maps.Marker({\n position: cityDetail[`latLng`],\n map: MAP ,\n icon: {\n path: google.maps.SymbolPath.CIRCLE,\n strokeColor : \"yellow\",\n scale: 5\n } ,\n shape : shape ,\n title : cityDetail[`fullName`] ,\n });\n \n MARKERS.push(marker);\n\n // When this marker is clicked, get the fullName from cityDetail and present information on the city.\n marker.addListener(\"click\", function() {\n processInput(cityDetail[`fullName`]);\n });\n }", "function openMarkers(){\n infoWindow.setContent(info);\n animation();\n infoWindow.open(map,marker)\n }", "function createMapMarker(placeData) {\n\n\t\t\tplaceData.forEach(function(place) {\n\t\t\t\t// console.log(place);\n\t\t\t\t// The next lines save location data from the search result object to local variables\n\t\t\t\tvar lat = place.geometry.location.lat(); // latitude from the place service\n\t\t\t\tvar lon = place.geometry.location.lng(); // longitude from the place service\n\t\t\t\tvar name = place.name; // name of the place from the place service\n\t\t\t\tvar bounds = window.mapBounds; // current boundaries of the map window\n\t\t\t\t// marker is an object with additional data about the pin for a single location\n\t\t\t\tplace.marker = new google.maps.Marker({\n\t\t\t\t\tmap: map,\n\t\t\t\t\tposition: place.geometry.location,\n\t\t\t\t\ttitle: name\n\t\t\t\t});\n\t\t\t\t// infoWindows are the little helper windows that open when you click\n\t\t\t\t// or hover over a pin on a map. They usually contain more information\n\t\t\t\t// about a location.\n\t\t\t\tplace.infoWindow = new google.maps.InfoWindow({\n\t\t\t\t\tcontent: name\n\t\t\t\t});\n\t\t\t\t// bounds.extend() takes in a map location object\n\t\t\t\tbounds.extend(new google.maps.LatLng(lat, lon));\n\t\t\t\t// fit the map to the new marker\n\t\t\t\tmap.fitBounds(bounds);\n\t\t\t\t// center the map\n\t\t\t\tmap.setCenter(bounds.getCenter());\n\t\t\t});\n\n\t\t\tplaceData.forEach(function(place) {\n\t\t\t\t// add an info window to the markers\n\t\t\t\tgoogle.maps.event.addListener(place.marker, 'click', function() {\n\t\t\t\t\tconsole.log(placeData);\n\t\t\t\t\tplaceData.forEach(function(plc) {\n\t\t\t\t\t\tplc.infoWindow.close();\n\t\t\t\t\t});\n\t\t\t\t\tplace.infoWindow.open(map, place.marker);\n\t\t\t\t});\n\t\t\t});\n\n\t\t}", "function createCharacterMarker(character) {\n\tvar character_latlng = new google.maps.LatLng(character.loc.latitude,\n character.loc.longitude);\n \t//finds image for the character\n\tvar image = \"images/\" + character.name + \".png\";\n \tvar characterContentString = \"name: \" + character.name + \"<br>lat/lng: \" \n + character.loc.latitude + \", \" + character.loc.longitude\n + \"<br>note: \" + character.loc.note;\n\n \t//calculates distance between me and character\n\tdistanceBetweenMeAndCharacter(character.loc);\n\tdistances[distances.length] = distance;\n\tnames[names.length] = character.name;\n \t\n \t//creates marker for character with image\n\tvar marker = new google.maps.Marker({\n\t\tmap: map,\n\t\tposition: character_latlng,\n\t\ticon: image\n\t});\n\n\t//shows info window on click\n\tgoogle.maps.event.addListener(marker, 'click', function() {\n \tinfowindow.close();\n \tinfowindow.setContent(characterContentString);\n \tinfowindow.open(map, this);\n\t});\n\n //creates polyline between me and character\n\tvar polyline = new google.maps.Polyline({\n\t\tpath: [character_latlng, latlng],\n\t \tmap: map,\n \tgeodesic: false,\n\t \tstrokeColor: '#377FD3',\n\t \tstrokeOpacity: 0.7,\n\t \tstrokeWeight: 3\n \t});\n}", "function createMapMarker(placeData) {\n\n // The next lines save location data from the search result object to local variables\n var lat = placeData.geometry.location.lat(); // latitude from the place service\n var lon = placeData.geometry.location.lng(); // longitude from the place service\n var name = placeData.formatted_address; // name of the place from the place service\n var bounds = window.mapBounds; // current boundaries of the map window\n\n // marker is an object with additional data about the pin for a single location\n var marker = new google.maps.Marker({\n map: map,\n position: placeData.geometry.location,\n title: name\n });\n\n // infoWindows are the little helper windows that open when you click\n // or hover over a pin on a map. They usually contain more information\n // about a location.\n var infoWindow = new google.maps.InfoWindow({\n content: name + \": Latitude: \" + lat +\n \"<br>Longitude: \" + lon\n });\n\n google.maps.event.addListener(marker, 'click', function() {\n infoWindow.open(map,marker);\n });\n\n // this is where the pin actually gets added to the map.\n // bounds.extend() takes in a map location object\n bounds.extend(new google.maps.LatLng(lat, lon));\n // fit the map to the new marker\n map.fitBounds(bounds);\n // center the map\n\n map.setCenter(bounds.getCenter());\n }", "function createMarkers(result) {\n // console.log(result); \n for (var i=0; i < result.length; i++) {\n\n var latLng = new google.maps.LatLng (result[i].lot_latitude, result[i].lot_longitude); \n\n var marker = new google.maps.Marker({\n position: myLatlng,\n title: result [i].lot_name,\n customInfo: {\n name: result[i].lot_name,\n address: result[i].lot_address,\n available: result[i].spot_id\n };\n });\n\n// To add the marker to the map, call setMap();\nmarker.setMap(map);\n\ncreateMarkers(result);\n };\n }", "function addMarker(payload, map) {\n var location = {lat: payload.lat*1, lng: payload.lng*1};\n // Add the marker at the clicked location, and add the next-available label\n // from the array of alphabetical characters.\n var marker;\n var name = payload.name;\n var id = payload.id;\n var autoGen = payload.autoGen;\n\n if (!(id in cars)) {\n cars[id] = {};\n if (autoGen == 0)\n {\n cars[id][\"name\"] = name;\n marker = new MarkerWithLabel({\n map: map,\n draggable: false,\n raiseOnDrag: false,\n labelContent: (autoGen == 1) ? \"\" : name,\n labelAnchor: new google.maps.Point(60, -10),\n labelClass: \"labels\", // the CSS class for the label\n labelStyle: {opacity: 0.8},\n optimized: false,\n });\n }\n else\n {\n marker = new google.maps.Marker({\n position: location,\n map: map,\n title: 'Robo car'\n });\n }\n cars[id][\"marker\"] = marker;\n if (autoGen == 1)\n cars[id][\"marker\"].setIcon(autoCarIcon);\n else\n cars[id][\"marker\"].setIcon(humanCarIcon);\n\n // create an info window, and associate with this marker\n cars[id][\"info\"] = new google.maps.InfoWindow();\n google.maps.event.addListener(marker, 'click', function() {\n cars[id][\"info\"].open(map,marker);\n });\n marker.setAnimation(google.maps.Animation.DROP);\n\n } else {\n marker = cars[id][\"marker\"];\n //marker.setAnimation(google.maps.Animation.BOUNCE);\n }\n // already exists... update it!\n marker.setZIndex(curZIndex++);\n marker.setPosition(location);\n if (marker.getOpacity() == 0) { // i.e. had faded out\n marker.setMap(map);\n }\n // make sure it's fully opaque, and update the timestamp\n marker.setOpacity(1.0);\n cars[id][\"timestamp\"] = Date.now();\n\n // NEW: update teh marker based on fault status\n if (payload.fault == \"OK\") {\n if (autoGen == 1)\n cars[id][\"marker\"].setIcon(autoCarIcon);\n else\n cars[id][\"marker\"].setIcon(humanCarIcon);\n }\n else if (payload.fault == \"Flat Front Tire\" || payload.fault == \"Flat Rear Tire\")\n cars[id][\"marker\"].setIcon(tireFaultIcon);\n else if (payload.fault == \"Light Burnt Out\")\n cars[id][\"marker\"].setIcon(lightFaultIcon);\n else // Engine Trouble\n {\n if (name ==\"TonyZ\") {\n cars[id][\"marker\"].setIcon(tz_engineFaultIcon);\n } else {\n cars[id][\"marker\"].setIcon(engineFaultIcon);\n }\n }\n\n cars[id].fault = payload.fault;\n\n // this builds an HTML string for the popup info window when you click on the marker\n var infoContent = '<p><b>Name:</b> '+name+'<br/>';\n infoContent += '<b>ID:</b> '+id+'<br/>';\n infoContent += '<b>Position:</b> '+location[\"lat\"].toFixed(6)+', '+location[\"lng\"].toFixed(6)+'<br/>';\n // add any other fields in the payload besides name, lat, lng\n for (var key in payload) {\n // skip loop if the property is from prototype\n if (!payload.hasOwnProperty(key)) continue;\n if (key == 'name' || key == 'id' || key == 'lat' || key == 'lng') continue; // skip if one of these\n infoContent += '<b>'+key+':</b> '+payload[key]+'<br/>';\n }\n infoContent += '</p>';\n cars[id][\"info\"].setContent(infoContent);\n\n return marker;\n }", "function displaySpots()\n{\n\tvar locations = {};\n\t\n\t// Get lat/long to begin\n\tvar textlat = document.getElementById('textlat');\n\tvar floatlat = parseFloat (textlat.value);\n\t\n\tvar textlong = document.getElementById('textlong');\n\tvar floatlong = parseFloat (textlong.value);\n\t\n\t// Make the 'Here' marker around lat/long\n\tvar here = {\n\t\tmap: map,\n\t\tposition: new google.maps.LatLng(floatlat, floatlong),\n\t\tcontent: 'You are here'\n }\n\t// Clear the old marker\n\tif (typeof imhere !== 'undefined') {\n\t\timhere.setMap(null);\n\t}\n imhere = new google.maps.InfoWindow(here);\n map.setCenter(here.position);\n\t\n\tlocations['location1'] = {\n\t\t//center: new google.maps.LatLng(49.26123, -123.11393)\n\t\tcenter: new google.maps.LatLng(floatlat, floatlong) // Center around the inputed lat/long\n\t};\n\t // Construct the circle for each value in locations.\n\n\tfor (var location in locations) {\n\t\tvar circleOptions = {\n\t\t\tstrokeColor: '#FF0000',\n\t\t\tstrokeOpacity: 0.8,\n\t\t\tstrokeWeight: 2,\n\t\t\tfillColor: '#FF0000',\n\t\t\tfillOpacity: 0.35,\n\t\t\tmap: map,\n\t\t\tcenter: locations[location].center,\n\t\t\tradius: 1000\n\t\t};\n\t\t//remove previous circle\n\t\tif (typeof cityCircle !== 'undefined') {\n\t\t\tcityCircle.setMap(null);\n\t\t}\n\t\t// Add the circle for this city to the map.\n\t\tcityCircle = new google.maps.Circle(circleOptions);\n }\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createTitleScreenBackground function creates a 2D array for holing the background of the title screen, it creates a collum of objects that is an array within an array of rows, thus filling the entire screen. This all happens once at the start of the program (see setup)
function createTitleScreenBackground() { for (var i = 0; i < 10; i++) { titleBackground[i] = []; for (var j = 0; j < 8; j++) { titleBackground[i][j] = new TitleBackground(Math.floor(random(0, width)), Math.floor(random(0, height)), random(1, 5)); } } }
[ "function drawBackground() {\n image(imgBackground, width / 2, height / 2); // dimensions: 100 X 56\n\n // table for tray\n rectMode(CORNER);\n fill(\"#B8F4FA\"); // light blue\n rect(0, height - 30, width, 30);\n\n image(imgTray, trayX, trayY); // tray dimensions: 130 X 78\n\n displayScore();\n drawStacked();\n}", "function draw_bg_tiles() {\n\n // remove previous bg tiles\n bg_tile_ids.forEach(function(bg_tile_id) {\n remove_element(bg_tile_id);\n });\n bg_tile_ids = [];\n\n // add new background tiles\n for (var x = 0; x < grid_size[0]; x++) {\n for (var y = 0; y < grid_size[1]; y++) {\n\n // create bg tile and set classes / ID\n var tile = document.createElement(\"div\");\n tile.className = \"tile\";\n tile.id = \"tile_\" + x + \"_\" + y;\n\n // add click listeners\n tile.setAttribute(\"onmousedown\", \"startDrawErase(id)\");\n tile.setAttribute(\"onmouseup\", \"stopDrag()\");\n\n // set position and z-index\n var pos_x = x * tile_size;\n var pos_y = y * tile_size;\n tile.style = \"left:\" + pos_x + \"px; top:\" + pos_y + \"px; width: \" + tile_size + \"px; height: \" + tile_size + \"px; z-index: 0;\";\n\n // add context menu\n add_context_menu(tile);\n\n // add to grid\n grid.append(tile);\n\n // add id to our list of bg_tile_ids\n bg_tile_ids.push(tile.id);\n }\n }\n}", "function createBackground() {\n var background = this.add.image(256, 256, \"background\");\n background.setScale(2.2, 2.5);\n}", "function draw() {\r\n background(0,5);\r\n // inside draw\r\n\r\nfor(let i = 0;i<particlesBg.length;i++) {\r\n \r\n particlesBg[i].createParticleBg();\r\n particlesBg[i].moveParticleBg();\r\n particlesBg[i].joinParticlesBg(particlesBg.slice(i));\r\n }\r\n}", "function _renderBackground () {\n\t_ctx.fillStyle = _getColor(\"background\");\n _ctx.fillRect(0, 0, _ctx.canvas.clientWidth, _ctx.canvas.clientHeight);\n}", "function _initDebugBackground() {\n if (!this.options.debug) return;\n\n this.containers.forEach(function(containerObj, i) {\n\n var background = new Surface({\n properties: {\n background: 'black',\n border: '1px dashed green',\n zIndex: '-9999999'\n }\n });\n\n containerObj.container.add(background);\n });\n}", "function createBackgroundWindow () {\n backgroundWindow = new BrowserWindow({width: 640, height: 480, show: true})\n backgroundWindow.loadFile('background.html')\n backgroundWindow.on('closed', () => {\n backgroundWindow = null\n })\n}", "function createBoard() {\n\tfor (let i = 0; i < layout.length; i++ ) {\n\t\n\t\tconst square = document.createElement(\"div\");\n\t\tgrid.appendChild(square);\n\t\tsquares.push(square);\n\t\n\n\t\n\tif (layout[i] === 0 ) {\n\t\tsquares[i].classList.add('pac-dot')\n\t} else if (layout[i] === 1 ) {\n\t\tsquares[i].classList.add('wall')\n\t} else if (layout[i] === 2 ) {\n\t\tsquares[i].classList.add('ghosthome')\n\t} else if (layout[i] === 3 ) {\n\t\tsquares[i].classList.add('power-pellet')\n\t}\n\n\t\t\t}\n} // end of createBoard function", "function setANSICanvasSize() {\n var totalDisplayWidth=getTotalDisplayWidth();\n var totalDisplayHeight=getTotalDisplayHeight();\n \n for (var y = 0; y <= totalDisplayHeight; y++) // TODO if really \n { \n var xArray = new Array();\n for (var x = 0; x <= totalDisplayWidth; x++) // TODO if really\n {\n var data = new Array();\n data[0]=32; // ascii code\n data[1]=15; // foreground color\n data[2]=0; // background color\n xArray[x]=data;\n }\n screenCharacterArray[y]=xArray;\n \n //console.log(\"y:\"+y+\" length:\"+screenCharacterArray[y].length);\n }\n\n $('body').attr('onresize', 'resize_canvas();');\n \n }", "function createGrid() {\n for (let i = 0; i < width * height; i++) {\n const cell = document.createElement('div')\n grid.appendChild(cell)\n cells.push(cell)\n }\n for (let i = 2; i < 22; i++) {\n rowArray.push(cells.slice(i * 10, ((i * 10) + 10)))\n }\n for (let i = 0; i < 20; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('top')\n }\n for (let i = 10; i < 20; i++) {\n cells[i].classList.remove('top')\n cells[i].classList.add('topline')\n }\n for (let i = 220; i < 230; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('bottom')\n }\n }", "function createGrid() {\n // set CSS properties\n document.documentElement.style.setProperty('--grid_size', gridSize);\n document.documentElement.style\n .setProperty('--font_size_tile_adaptable', `${6 - gridSize/3}vh`);\n\n // get grid HTML element and empty its content from previous grid\n const grid = document.getElementById('grid');\n grid.innerHTML = '';\n\n for (let iRow = 0; iRow < gridSize; iRow += 1) {\n const row = document.createElement('div');\n row.className = 'row';\n\n for (let iCol = 0; iCol < gridSize; iCol += 1) {\n const tile = document.createElement('button');\n tile.disabled = true;\n tile.className = 'tile';\n tile.id = `tileR${iRow}C${iCol}`;\n tile.addEventListener('click', () => newMove([iRow, iCol]));\n row.appendChild(tile);\n }\n\n grid.appendChild(row);\n }\n\n // make 2D array that holds tile objects\n tiles = new Array(gridSize);\n for (let iRow = 0; iRow < gridSize; iRow++) {\n tiles[iRow] = new Array(gridSize);\n }\n}", "function makeBoard() {\n for (let y = 0; y < HEIGHT; y++) {\n const row = [];\n for (let x = 0; x < WIDTH; x++) {\n const cell = null;\n row.push(cell);\n }\n board.push(row);\n }\n }", "function createGameStageArray(){\n let borderSize = getBoardSize();\n let rows = borderSize[0];\n let cols = borderSize[1];\n for(let row=0;row<rows;row++){\n gameStageArch[row] = [];\n for(let col=0;col<cols;col++){\n gameStageArch[row][col] = false;\n }\n }\n}", "function drawGround() {\n //back layer\n for (let i = 0; i < PLAYING_FIELD_LENGTH; i = i + 2) {\n addBackgroundImage(backgroundImages.ground[0], bg3_ground_x, bg_element_y, i);\n addBackgroundImage(backgroundImages.ground[1], bg3_ground_x, bg_element_y, i + 1);\n }\n //middle layer\n for (let i = 0; i < PLAYING_FIELD_LENGTH; i = i + 2) {\n addBackgroundImage(backgroundImages.ground[2], bg2_ground_x, bg_element_y, i);\n addBackgroundImage(backgroundImages.ground[3], bg2_ground_x, bg_element_y, i + 1);\n }\n //front layer\n for (let i = 0; i < PLAYING_FIELD_LENGTH; i = i + 2) {\n addBackgroundImage(backgroundImages.ground[4], bg1_ground_x, bg_element_y, i);\n addBackgroundImage(backgroundImages.ground[5], bg1_ground_x, bg_element_y, i + 1);\n }\n}", "function createAbstractGrid(){\n for(var i = 0;i < width; i++){\n BoardMethods.grid.push([]);\n BoardMethods.grid2.push([]);\n\n for(var i2 = 0;i2 < height; i2++){\n BoardMethods.grid[i].push(false);\n BoardMethods.grid2[i].push(false);\n }\n }\n }", "function setupHUDelements(){\n\tfor (var i = 0; i < 10; i++){ //Set up bitmaps now so that all we do later is turn them on\n\t\thudElements.eggBitmaps[i] = new createjs.Bitmap(imageEgg);\n\t\thudElements.eggBitmaps[i].sourceRect = new createjs.Rectangle(0,0,20,30);\n\t\thudElements.eggBitmaps[i].x = (thecanvas.width - 20) - (15 * i);\n\t\thudElements.eggBitmaps[i].y = 245;\n\t\thudElements.eggBitmaps[i].scaleX = .5;\n\t\thudElements.eggBitmaps[i].scaleY = .5;\n\t}\n\t\n\thudElements.scoreText = new createjs.Text(\"score: \" + score, \"16px Arial\", \"#fff\");\n\thudElements.scoreText.x = 10;\n\thudElements.scoreText.y = 260;\n\tstage.addChild(hudElements.scoreText);\n\t\n\thudElements.speedText = new createjs.Text(\"speed: \", \"16px Arial\", \"#fff\");\n\thudElements.speedText.x = 150;\n\thudElements.speedText.y = 260;\n\tstage.addChild(hudElements.speedText);\n\t\n hudElements.speedBarG = new createjs.Graphics();\n\thudElements.speedBarG.beginFill(\"#d33\");\n\thudElements.speedBarG.rect(0,0,1, 20);\n\thudElements.speedBarShape = new createjs.Shape(hudElements.speedBarG);\n\thudElements.speedBarShape.x = 200;\n\thudElements.speedBarShape.y = 245;\n\t\n\tstage.addChild(hudElements.speedBarShape);\n\t\n}", "function createChessGrid() {\n var color = \"w\";\n for (var j = 0; j < 8; j++) {\n let line = [];\n for (var i = 0; i < 8; i++) {\n var tile = createTile(j * WIDTH + 20, i * HEIGHT + 20, color);\n tile.placedPiece = \"\";\n line.push(tile);\n if (color == \"w\")\n color = \"b\";\n else {\n color = \"w\";\n }\n }\n if (color == \"w\")\n color = \"b\";\n else {\n color = \"w\";\n }\n grid.push(line);\n }\n}", "function drawVehicles() {\n for (i=0;i<vehicles.length;i++) {\n //Left side, right side+image width, top side, bottom side\n if (vehicles[i][0].pos[0] >= (window.innerWidth/2)-(10*tileSize)/2 && vehicles[i][0].pos[0] <= (window.innerWidth/2)+(10*tileSize)/2-vehicles[i][0].image.width*2 && vehicles[i][0].pos[1] >= (window.innerHeight/2)-(10*tileSize)/2 && vehicles[i][0].pos[1] <= (window.innerHeight/2)+(10*tileSize)/2) {\n vehicles[i][0].draw(vehicles[i][0].pos[0],vehicles[i][0].pos[1],vehicles[i][0].image.width*2,vehicles[i][0].image.height*2);\n } else {\n //If it's outside the grid space, remove it from the array\n vehicles.splice(i,1);\n }\n }\n //Create a car if this random number generator condition is true\n if (Math.random()*1 > 0.999) {\n createVehicle();\n }\n //The movement for the vehicles\n moveVehicles();\n}", "function initTiles() {\n let body = document.getElementsByTagName(\"body\")[0];\n const dimension = (1 / GRID_SIZE) * 100;\n for (let i = 1; i <= noTiles; i++) {\n let newTile = document.createElement(\"div\");\n newTile.classList.add(\"tile\");\n newTile.classList.add(\"tile\" + i);\n newTile.setAttribute(\"style\", \"width: \" + dimension + \"%; height: \" + dimension + \"%; top: \" + (Math.trunc((i - 1) / GRID_SIZE) * dimension + \"%\") + \"; left: \" + (((i - 1) % GRID_SIZE) * dimension + \"%;\"));\n body.appendChild(newTile);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=============================== CHECKING THE CUBE'S COMPLETION
function checkCube() { //=============================== var check = false; // Check each color for(face in colorMap) { // Check each sticker from that color $(".color-"+colorMap[face]).each(function() { // If the sticker isn't on the right face for its color // Then the cube hasn't been solved yet check = $(this).hasClass("pyramid-"+face); return check; }); if(!check) break; } return check; }
[ "function checkUEC(targetBlock) {\n if (targetBlock.id.equals('mekanism:ultimate_energy_cube')) {\n if (!!targetBlock.entityData.EnergyContainers[0]) {\n if (!!targetBlock.entityData.EnergyContainers[0].stored) {\n if (targetBlock.entityData.EnergyContainers[0].stored == 4096000000) {\n return true\n }\n }\n }\n }\n return false\n }", "function checkSetupSuccess() {\n // Conditionals.\n var hasUndefined = false;\n var hasFalse = false;\n // Iterate through global successFactors JSON object.\n for (var key in global.successFactors) {\n if (global.successFactors[key] === undefined) {\n hasUndefined = true;\n break;\n }\n if (global.successFactors[key] === false) {\n console.log('key: ',key);\n hasFalse = true;\n break;\n }\n }\n // If no undefined and no false, print success.\n if (!hasUndefined && !hasFalse) {\n console.log(\"---\\nSetup was a success! Please enjoy MMM-RemoteCompliments!\");\n }\n // If false, let user know and exit.\n if (hasFalse){\n console.log(\"---\\nSomething went wrong with the setup. It is recommended you delete the files created on your Google Drive and try setup again after fixing the above error.\");\n process.exit(1);\n }\n}", "function checkSquareAndCube(arr) {\n\treturn Math.sqrt(arr[0]) === Math.cbrt(arr[1]);\n}", "checkPartecipants(){\n \n }", "checkNextGame (){\n\n }", "function check() {\n // Determine milliseconds elapsed since the color was loaded\n var milliseconds_taken = Date.now() - time_at_load;\n\n // Calculate the percents that the user was off\n var percents = {\n red: (Math.abs(color.red - guess.red)/255)*100,\n green: (Math.abs(color.green - guess.green)/255)*100,\n blue: (Math.abs(color.blue - guess.blue)/255)*100\n };\n\n // Calculate the average (overall) percent off\n var percent_off = (percents.red + percents.green + percents.blue)/3;\n\n // Calculate the turn's score\n var turn_score = ((15 - settings.difficulty - percent_off) /\n (15 - settings.difficulty)) *\n (15000 - milliseconds_taken);\n\n // If positive, round to 2 decimals. If negative, set to 0.\n turn_score = (turn_score > 0) ? (Math.round(turn_score*100)/100) : 0;\n\n // Add the score for the turn to the running total\n total_score += turn_score;\n\t\ttotal_score = (Math.round(total_score*100)/100)\n\n\t\t// decrease the turn count\n turns_remaining--;\n\n\t\t// check if no turns remain\n if(turns_remaining > 0) {\n newColor();\n\n // Display the current statistics\n $('#result').html(\"Last Score: \" + turn_score +\n \"; Total Score: \" + total_score +\n \"; Turns Left: \" + turns_remaining);\n\n } else {\n // create a new div element to display game over info for the user\n // wrapped in a div for easy removing on game reset\n var gameOver = $('<div>').attr('id', 'gameOver');\n\n // Add a header to denote game over\n gameOver.append($(\"<h2>\").text(\"Game Over!\"));\n\n // Show the final score from the game\n gameOver.append($(\"<p>\").text(\"Final Score: \" + total_score));\n\n\t\t\t// Create the input for players to input a name for their high score\n var playerNameInput = $('<input>').attr('placeholder', 'Your name');\n\n\t\t\t// Add the input to the page with an ID for easy value access\n gameOver.append(playerNameInput.attr('id', 'hsName'));\n\n\t\t\t// Create a submit button to send the score to the high scores array\n var submit = $('<button>').text(\"Submit High Score!\");\n submit = submit.attr(\"type\", \"button\").attr(\"id\",\"hsSubmit\");\n\n\t\t\t// Show the button\n gameOver.append(submit.click(submitHighscore));\n\n\t\t\t// Create a try again buton to allow users to restart the game over\n\t\t\tvar againButton = $(\"<button>\").text(\"Try Again!\");\n\n\t\t\t// Show the button\n gameOver.append(againButton.attr(\"type\", \"button\").click(reset));\n\n\t\t\t// Hide the game so they can't keep playing\n gameElement.children().hide();\n\n\t\t\t// Add the game over elements\n gameElement.append(gameOver);\n }\n }", "function checkProblem() {\n // check overspeed\n (function() {\n var distance;\n if (lastGraphic != null) {\n var x1 = lastGraphic.geometry.x;\n var y1 = lastGraphic.geometry.y;\n distance = calDistance(x1, y1, currentX, currentY);\n \n }\n })();\n // check overrange\n // check overpause\n (function () {\n if (isPausing) {\n var currentDate = new Date();\n console.log(currentDate.getTime() - startPauseTime.getTime());\n }\n })();\n // check overworking\n (function () {\n if (isExecuting) {\n var currentDate = new Date();\n console.log(currentDate.getTime() - startWorkTime.getTime());\n }\n })();\n }", "function clockCheck() {\n\n if (clockOnly.checked === true && clockTracker === 0) {\n clockTracker = 1;\n clockOptions.checked = false;\n toolTip.checked = false;\n\n optionsPanel.style.opacity = 0;\n toolTipPanel.style.opacity = 0;\n\n }\n\n else if (clockOptions.checked === true && clockTracker === 1) {\n clockTracker = 0;\n clockOnly.checked = false;\n clockOptions.checked === true;\n\n optionsPanel.style.opacity = 1;\n\n }\n\n else if (toolTip.checked === true && clockTracker === 1) {\n clockTracker = 0;\n clockOnly.checked = false;\n toolTip.checked === true;\n\n toolTipPanel.style.opacity = 1;\n\n };\n\n}", "function checkSauce() {\n const opts = {\n url: `https://${ SAUCE_LABS_USERNAME }:${ SAUCE_LABS_ACCESS_KEY }@saucelabs.com/rest/v1/cct-sauce/js-tests/status`,\n method: 'POST',\n json: {\n 'js tests': sauceTests\n }\n };\n setTimeout( function() {\n request.post( opts, function( err, httpResponse, body ) {\n if ( err ) {\n console.error( 'An error occurred:', err );\n }\n\n let failures = 0;\n\n if ( body.completed ) {\n console.log( 'Tests done.' );\n // TODO: Provide a consistent return value from the function.\n // eslint-disable-next-line consistent-return\n body['js tests'].forEach( test => {\n let errors;\n if ( test.result && test.result.failed > 0 ) {\n // TODO: remove one nested callback.\n // eslint-disable-next-line max-nested-callbacks\n errors = test.result.tests.map( result => result.message );\n failures++;\n return console.log( test.platform.join( ' ' ) + ' failed: ' + errors.join( ' ' ) );\n }\n console.log( test.platform.join( ' ' ) + ' passed.' );\n } );\n if ( failures > 0 ) {\n process.exit( 1 );\n }\n process.exit( 0 );\n } else {\n console.log( 'Tests still running... See status at https://saucelabs.com/u/' + SAUCE_LABS_USERNAME );\n checkSauce();\n }\n } );\n }, 5000 );\n}", "function checkCorner3(cube) {\n if( ((cube[up][0][0] == 'G') && (cube[back][2][0] == 'W') && (cube[left][0][0] == 'O')) || ((cube[up][0][0] == 'W') && (cube[back][2][0] == 'O') && (cube[left][0][0] == 'G')) || ((cube[up][0][0] == 'O') && (cube[back][2][0] == 'G') && (cube[left][0][0] == 'W')) ) return true;\n else return false;\n}", "validate() {\n this.verifTitle();\n this.verifDescription();\n this.verifNote();\n this.verifImg();\n console.log(this.errors);\n console.log(this.test);\n if (this.test !== 0) {\n return false;\n }\n return true;\n }", "checkGameStart(event) {\n\t\tif (this.props.finalizeStartButton !== 'Ready!' && this.props.finalizeEndButton !== 'Ready!') {\n\t\t\talert('You must select and ready both start and end movies')\n\t\t\tevent.preventDefault();\n\t\t} else if (this.props.finalizeStartButton !== 'Ready!') {\n\t\t\talert('You must select and ready a start movie')\n\t\t\tevent.preventDefault();\n\t\t} else if (this.props.finalizeEndButton !== 'Ready!') {\n\t\t\talert('You must select and ready an end movie')\n\t\t\tevent.preventDefault();\n\t\t}\n\t}", "function C101_KinbakuClub_RopeGroup_CassiContinue() {\n\tActorAddOrgasm();\n\tC101_KinbakuClub_RopeGroup_PlayerArousal = C101_KinbakuClub_RopeGroup_PlayerArousal - 200;\n\tC101_KinbakuClub_RopeGroup_ForcingCassi = false;\n\tC101_KinbakuClub_RopeGroup_PressingCassi = false;\n\tC101_KinbakuClub_RopeGroup_CanPressCassi = true;\n\tif (ActorGetValue(ActorLove) <= 2) {\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 686;\n\t\tif (ActorHasInventory(\"Cuffs\")) {\n\t\t\tOverridenIntroText = GetText(\"CassiDoneUnCuff\");\n\t\t\tActorRemoveInventory(\"Cuffs\");\n\t\t} else OverridenIntroText = GetText(\"CassiDone\");\n\t} else {\n\t\tC101_KinbakuClub_RopeGroup_OrgasmCount++\n\t\tif (C101_KinbakuClub_RopeGroup_OrgasmCount >= 2) {\n\t\t\tC101_KinbakuClub_RopeGroup_AnkleGrab = false;\n\t\t\tC101_KinbakuClub_RopeGroup_fingerinsertion = false;\n\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 685;\n\t\t\tOverridenIntroText = GetText(\"CassiAsks\");\n\t\t}\n\t}\n}", "function validateActivities() {\n let checked = 0;\n for (let i = 0; i < checkboxes.length; i++) {\n const checkbox = checkboxes[i];\n if (checkbox.checked) {\n checked += 1;\n }\n }\n if (checked == 0) {\n return false;\n } else {\n return true;\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 alignAvailableYellowCross(cube) {\n if (allYellowAligned(cube)){\n return;\n } else if ((cube[front][1][0] == 'B') && (cube[right][1][0]) == 'R') {\n solveYellowCrossBlueRed(cube);\n } else if ((cube[left][1][0] == 'O') && (cube[front][1][0]) == 'B') {\n solveYellowCrossOrangeBlue(cube);\n } else if ((cube[back][1][0] == 'G') && (cube[left][1][0]) == 'O') {\n solveYellowCrossGreenOrange(cube);\n } else if ((cube[right][1][0] == 'R') && (cube[back][1][0]) == 'G') {\n solveYellowCrossRedGreen(cube);\n } else if ((cube[front][1][0] == 'B') && (cube[back][1][0]) == 'G') {\n solveYellowCrossBlueGreen(cube);\n } else if ((cube[left][1][0] == 'O') && (cube[right][1][0]) == 'R') {\n solveYellowCrossOrangeRed(cube);\n }\n} //alignAvailableYellowCross", "checkLoading() {\n if (this.props.loading.state == 'new') {\n const { centerId, reportingDate } = this.props.params\n this.props.dispatch(loadScoreboard(centerId, reportingDate))\n return false\n }\n return (this.props.loading.state == 'loaded')\n }", "function checkStatus() {\n var allDone = true;\n\n for (var _i2 = 0; _i2 < layers.length; _i2++) {\n if (layers[_i2].loaded === false) {\n allDone = false;\n break;\n }\n }\n\n if (allDone) finish();else setTimeout(checkStatus, 500);\n }", "function checkBoxes() {\n\t\tvar box1 = check[0][0];\n\t\tvar box2 = check[1][0];\n\t\t// This is the main logic. Executes if the boxes are the same.\n\t\tif (check.length == 2) {\n\t\t\t// This is the tricky part which solves the problem when the same box is clicked twice. It is solved by using the ids as identification.\n\t\t\tif (box1 == box2 && check[0][1] != check[1][1]) {\n\t\t\t\t// Allows only one correct answer by checking if it was already submitted. \n\t\t\t\tif (pairs.indexOf(box1) == -1) {\n\t\t\t\t\tpairs.push(box1, box2);\n\t\t\t\t\t// Removes the boxes i.e. sets them to 0. This prevents the closing of a correct pair if it is clicked in the combination with another number AFTER it has been guessed correctly.\n\t\t\t\t\tfor (var i = 0; i < boxes.length; i++) {\n\t\t\t\t\t\tif (boxes[i] == box1) {\n\t\t\t\t\t\t\tboxes.splice(i, 1, 0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcheck = [];\n\t\t\t\t}\n\t\t\t} else { // If they are not the same, reset.\n\t\t\t\t// Time window to memorize the selection.\n\t\t\t\tsetTimeout(closeCheckedBoxes, 300);\n\t\t\t}\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }