query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Returns manual payment method if supported by the host, null otherwise | getManualPaymentMethod() {
const pm = get(this.props.data, 'Collective.host.settings.paymentMethods.manual');
if (!pm || get(this.state, 'stepDetails.interval')) {
return null;
}
return {
...pm,
instructions: this.props.intl.formatMessage(
{
id: 'host.paymentMethod.manual.instructions',
defaultMessage:
'Instructions to make the payment of {amount} will be sent to your email address {email}. Your order will be pending until the funds have been received by the host ({host}).',
},
{
amount: formatCurrency(get(this.state, 'stepDetails.totalAmount'), this.getCurrency()),
email: get(this.props, 'LoggedInUser.email', ''),
collective: get(this.props, 'loggedInUser.collective.slug', ''),
host: get(this.props.data, 'Collective.host.name'),
TierId: get(this.getTier(), 'id'),
},
),
};
} | [
"RetrieveAvailablePaymentMethod() {\n let url = `/me/payment/availableMethods`;\n return this.client.request('GET', url);\n }",
"function setupPaymentMethods17() {\n const queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('message')) {\n showRedirectErrorMessage(queryParams.get('message'));\n }\n\n $('input[name=\"payment-option\"]').on('change', function(event) {\n\n let selectedPaymentForm = $('#pay-with-' + event.target.id + '-form .adyen-payment');\n\n // Adyen payment method\n if (selectedPaymentForm.length > 0) {\n\n // not local payment method\n if (!('localPaymentMethod' in\n selectedPaymentForm.get(0).dataset)) {\n\n resetPrestaShopPlaceOrderButtonVisibility();\n return;\n }\n\n let selectedAdyenPaymentMethodCode = selectedPaymentForm.get(\n 0).dataset.localPaymentMethod;\n\n if (componentButtonPaymentMethods.includes(selectedAdyenPaymentMethodCode)) {\n prestaShopPlaceOrderButton.hide();\n } else {\n prestaShopPlaceOrderButton.show();\n }\n } else {\n // In 1.7 in case the pay button is hidden and the customer selects a non adyen method\n resetPrestaShopPlaceOrderButtonVisibility();\n }\n });\n }",
"ListAvailablePaymentMethodsInThisNicCountry() {\n let url = `/me/availableAutomaticPaymentMeans`;\n return this.client.request('GET', url);\n }",
"function checkPaymentMethod(paymentMethod) {\n if (paymentMethod === 'credit card') {\n $creditCard.show();\n $paypal.hide();\n $bitcoin.hide();\n $submit.show();\n } else if (paymentMethod === 'paypal') {\n $creditCard.hide();\n $paypal.show();\n $bitcoin.hide();\n $submit.show();\n } else if (paymentMethod === 'bitcoin') {\n $creditCard.hide();\n $paypal.hide();\n $bitcoin.show();\n $submit.show();\n } else {\n $creditCard.hide();\n $paypal.hide();\n $bitcoin.hide();\n $submit.hide();\n }\n return true;\n}",
"paymentMethodOptions() {\n const {settings, invoices, setProp} = this.props;\n const selectedPaymentMethod = invoices.get('paymentMethod');\n const achAvailable = settings.getIn(['achInfo', 'accountNumber']);\n const ccAvailable = settings.get(['ccInfo', 'number']);\n // Determine payment options\n const paymentOptions = [];\n if (achAvailable) {\n paymentOptions.push({value: 'bank-account', name: 'Bank account'});\n // ACH only, select it\n if (!ccAvailable && selectedPaymentMethod === 'credit-card') {\n setProp('bank-account', 'paymentMethod');\n }\n }\n if (settings.get('getCcInfoSuccess')) {\n paymentOptions.push({value: 'credit-card', name: 'Credit card'});\n // CC only, select it\n if (!ccAvailable && selectedPaymentMethod === 'bank-account') {\n setProp('credit-card', 'paymentMethod');\n }\n }\n return Immutable.fromJS(paymentOptions);\n }",
"transformUSPaymentMethodToPaymentMethod(usPaymentMethod) {\n const paymentType = get(usPaymentMethod, 'paymentType', null);\n const paymentStatus = get(usPaymentMethod, 'status', null);\n\n return {\n paymentSubType: get(usPaymentMethod, 'paymentSubType', null),\n icon: {\n name: null,\n data: null,\n },\n status: this.getFullPaymentStatus(paymentStatus, paymentType),\n paymentMethodId: usPaymentMethod.id,\n default: get(usPaymentMethod, 'default', false),\n description: get(usPaymentMethod, 'description', null),\n paymentType: this.getFullPaymentType(paymentType),\n billingContactId: get(usPaymentMethod, 'billingContactId', null),\n creationDate: get(usPaymentMethod, 'creationDate', null),\n lastUpdate: null,\n label: get(usPaymentMethod, 'publicLabel', null),\n original: usPaymentMethod,\n };\n }",
"function buy() { // eslint-disable-line no-unused-vars\n document.getElementById('msg').innerHTML = '';\n\n if (!window.PaymentRequest) {\n print('Web payments are not supported in this browser');\n return;\n }\n\n let details = {\n total: {label: 'Total', amount: {currency: 'USD', value: '0.50'}},\n };\n\n let networks = ['visa', 'mastercard', 'amex', 'discover', 'diners', 'jcb',\n 'unionpay', 'mir'];\n let payment = new PaymentRequest( // eslint-disable-line no-undef\n [\n {\n supportedMethods: ['https://android.com/pay'],\n data: {\n merchantName: 'Web Payments Demo',\n allowedCardNetworks: ['AMEX', 'MASTERCARD', 'VISA', 'DISCOVER'],\n merchantId: '00184145120947117657',\n paymentMethodTokenizationParameters: {\n tokenizationType: 'GATEWAY_TOKEN',\n parameters: {\n 'gateway': 'stripe',\n 'stripe:publishableKey': 'pk_live_lNk21zqKM2BENZENh3rzCUgo',\n 'stripe:version': '2016-07-06',\n },\n },\n },\n },\n {\n supportedMethods: networks,\n },\n {\n supportedMethods: ['basic-card'],\n data: {\n supportedNetworks: networks,\n supportedTypes: ['debit', 'credit', 'prepaid'],\n },\n },\n \n ],\n details,\n {\n requestShipping: true,\n requestPayerName: true,\n requestPayerPhone: true,\n requestPayerEmail: true,\n shippingType: 'shipping',\n });\n\n payment.addEventListener('shippingaddresschange', function(evt) {\n evt.updateWith(new Promise(function(resolve) {\n fetch('/ship', {\n method: 'POST',\n headers: new Headers({'Content-Type': 'application/json'}),\n body: addressToJsonString(payment.shippingAddress),\n })\n .then(function(options) {\n if (options.ok) {\n return options.json();\n }\n cannotShip('Unable to calculate shipping options.', details,\n resolve);\n })\n .then(function(optionsJson) {\n if (optionsJson.status === 'success') {\n canShip(details, optionsJson.shippingOptions, resolve);\n } else {\n cannotShip('Unable to calculate shipping options.', details,\n resolve);\n }\n })\n .catch(function(error) {\n cannotShip('Unable to calculate shipping options. ' + error, details,\n resolve);\n });\n }));\n });\n\n payment.addEventListener('shippingoptionchange', function(evt) {\n evt.updateWith(new Promise(function(resolve) {\n for (let i in details.shippingOptions) {\n if ({}.hasOwnProperty.call(details.shippingOptions, i)) {\n details.shippingOptions[i].selected =\n (details.shippingOptions[i].id === payment.shippingOption);\n }\n }\n\n canShip(details, details.shippingOptions, resolve);\n }));\n });\n\n let paymentTimeout = window.setTimeout(function() {\n window.clearTimeout(paymentTimeout);\n payment.abort().then(function() {\n print('Payment timed out after 20 minutes.');\n }).catch(function() {\n print('Unable to abort, because the user is currently in the process ' +\n 'of paying.');\n });\n }, 20 * 60 * 1000); /* 20 minutes */\n\n payment.show()\n .then(function(instrument) {\n window.clearTimeout(paymentTimeout);\n\n if (instrument.methodName !== 'https://android.com/pay') {\n simulateCreditCardProcessing(instrument);\n return;\n }\n\n let instrumentObject = instrumentToDictionary(instrument);\n instrumentObject.total = details.total;\n let instrumentString = JSON.stringify(instrumentObject, undefined, 2);\n fetch('/buy', {\n method: 'POST',\n headers: new Headers({'Content-Type': 'application/json'}),\n body: instrumentString,\n })\n .then(function(buyResult) {\n if (buyResult.ok) {\n return buyResult.json();\n }\n complete(instrument, 'fail', 'Error sending instrument to server.');\n }).then(function(buyResultJson) {\n print(instrumentString);\n complete(instrument, buyResultJson.status, buyResultJson.message);\n });\n })\n .catch(function(error) {\n print('Could not charge user. ' + error);\n });\n}",
"function getShipmentMethod(currentCart) {\n let cart = currentCart || Cart.findOne();\n if (cart) {\n if (cart.shipping) {\n if (cart.shipping[0].shipmentMethod) {\n return cart.shipping[0].shipmentMethod;\n }\n }\n }\n return undefined;\n}",
"function checkShippingMethod() {\n return $('#shipping-options option:selected').val();\n\n}",
"choosePaymentModule(belopp){\n let betalning = (`.payment_typelist--component div[class=\"${belopp}\"]`);\n switch(belopp){\n case 'FULL_PAYMENT': //hela beloppet\n browser.click(betalning);\n browser.pause(1000);\n break;\n case 'INSTALLMENT_PAYMENT': //delbelopp\n browser.click(betalning);\n browser.pause(10000);\n console.log('nu ska vi betala');\n this.enterAmount();\n break;\n case 'DEPOSIT_PAYMENT': //anmälningsavgift\n browser.click(betalning);\n browser.pause(1000);\n break; \n }\n \n // var type = Math.floor(Math.random() * (6 - 3 + 1)) + 3;\n // this.choosePaymentType(type);\n // browser.click(''); //klicka på gå vidare till betalningsalternativet\n }",
"function payment() {\n // оплатить можно только с непустым заказом\n if (order.length){\n unpayed = false;\n var btn = document.querySelector('.make-order');\n btn.disabled = true;\n btn.innerHTML = 'заказ оплачен';\n }\n }",
"function bouncer_getPlatformForMirror() {\n\tvar a = getArray();\n\tif ( navigator.platform != null ) {\n\t\tif ( navigator.platform.indexOf( \"Win32\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n\t\t} else if ( navigator.platform.indexOf( \"Win64\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n\t\t} else if ( navigator.platform.indexOf( \"Win\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n\t\t} else if ( navigator.platform.indexOf( \"Linux\" ) != -1 ) {\n\t\t\tif ( navigator.userAgent != null ) {\n\t\t\t\tif ( navigator.userAgent.toLowerCase().indexOf( \"debian\" ) != -1 || navigator.userAgent.toLowerCase().indexOf( \"ubuntu\" ) != -1 ) {\n\t\t\t\t\treturn \"linuxinteldeb\";\n\t\t\t\t} else {\n\t\t\t\t\treturn ( a[3] == 'y' ) ? \"linuxintelwjre\" : \"linuxintel\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn ( a[3] == 'y' ) ? \"linuxintelwjre\" : \"linuxintel\";\n\t\t\t}\n\t\t} else if ( navigator.platform.indexOf( \"SunOS i86pc\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"solarisx86wjre\" : \"solarisx86\";\n\t\t} else if ( navigator.platform.indexOf( \"SunOS sun4u\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"solarissparcwjre\" : \"solarissparc\";\n\t\t} else if ( navigator.platform.indexOf( \"SunOS\" ) != -1 ) {\n\t\t\treturn ( a[3] == 'y' ) ? \"solarissparcwjre\" : \"solarissparc\";\n\t\t} else if ( navigator.platform.indexOf( \"Mac\" ) != -1 && navigator.platform.indexOf( \"Intel\" ) != -1 ) {\n\t\t\treturn \"macosxintel\";\n\t\t} else if ( navigator.platform.indexOf( \"Mac\" ) != -1 && navigator.platform.indexOf( \"PPC\" ) != -1 ) {\n\t\t\treturn \"macosxppc\";\n\t\t} else if ( navigator.platform.indexOf( \"Mac\" ) != -1 ) {\n\t\t\treturn \"macosxintel\";\n\t\t} else {\n\t\t\t// return ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n\t\t\treturn navigator.platform;\n\t\t}\n\t}\n\treturn ( a[3] == 'y' ) ? \"winwjre\" : \"win\";\n}",
"get renewable() {\n return !!this.provider && typeof this.provider.renew === 'function';\n }",
"cashCheck(paymentMethod, fare) {\n if (paymentMethod === 'Cash') {\n return fare;\n } else {\n return 0;\n }\n }",
"function DetectPalmOS()\n{\n if (uagent.search(devicePalm) > -1)\n location.href='http://www.kraftechhomes.com/home_mobile.php';\n else\n return false;\n}",
"function setDefaultShippingMethod(){\n nlapiSetFieldValue(\"shipmethod\", \"4774\") // set default shipping method to Freight Other\n}",
"function setupPaymentMethodsObserver16() {\n // Select the node that will be observed for mutations\n const targetNode = document.getElementById('HOOK_PAYMENT');\n\n // In case the targetNode does not exist return early\n if (null === targetNode) {\n return;\n }\n\n // Options for the observer (which mutations to observe)\n const config = {attributes: true, childList: true, subtree: false};\n\n // Callback function to execute when mutations are observed\n const callback = function(mutationsList, observer) {\n // extra check to make sure that we are on 1.6\n if (IS_PRESTA_SHOP_16) {\n // Set which methods have their own button\n componentButtonPaymentMethods = paymentMethodsWithPayButtonFromComponent;\n // Use traditional 'for loops' for IE 11\n for (const mutation of mutationsList) {\n if (mutation.type === 'childList') {\n // The children are being changed so disconnet the observer\n // at first to avoid infinite loop\n observer.disconnect();\n // Render the adyen checkout components\n renderPaymentMethods();\n }\n }\n\n // Connect the observer again in case the checkbox is clicked\n // multiple times\n observer.observe(targetNode, config);\n }\n };\n\n // Create an observer instance linked to the callback function\n const observer = new MutationObserver(callback);\n\n // Start observing the target node for configured mutations\n try {\n observer.observe(targetNode, config);\n } catch (e) {\n // observer exception\n }\n }",
"function updatePaymentInfo () {\n\n switch (document.querySelector(\"#payment\").value) {\n\n case \"credit card\":\n document.querySelector (\"#credit-card\").style.display = \"\";\n document.querySelector (\"#paypal\").style.display = \"none\";\n document.querySelector (\"#bitcoin\").style.display = \"none\";\n break;\n\n case \"paypal\":\n document.querySelector (\"#credit-card\").style.display = \"none\";\n document.querySelector (\"#paypal\").style.display = \"\";\n document.querySelector (\"#bitcoin\").style.display = \"none\";\n break;\n\n case \"bitcoin\":\n document.querySelector (\"#credit-card\").style.display = \"none\";\n document.querySelector (\"#paypal\").style.display = \"none\";\n document.querySelector (\"#bitcoin\").style.display = \"\";\n break;\n\n default: // this should never happen\n alert (\"internal error: no payment option detected\");\n break;\n }\n }",
"isTransactionPayment () {\n return this.state.paymentType === 'transaction'\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
search for a food and use a callback to get the result | search(foodSearchString, callback) {
let searchUrl = this.urlRoot + '&sort=n&max=25&offset=0&q=' + foodSearchString;
// hit the API and give it a callback to get the result
request(searchUrl, (error, response, body) => {
if (error) {
callback(error);
} else {
let parsedResponse = JSON.parse(body);
let searchResults = parsedResponse.list.item;
let cleanedResults = this.parseSearchResults(searchResults);
callback(false, cleanedResults);
}
});
} | [
"searchMeal() {\n // Using fuse.js and defining searching key\n const options = {\n includeScore: true,\n keys: ['fields.strMeal']\n }\n const fuse = new Fuse(this.foodsArray, options)\n // Called createCards func for first initializing\n this.createCards(this.foodsArray)\n // Taking words from input to search meal\n let searchInputDOM = document.querySelector(\".search-input\")\n searchInputDOM.addEventListener(\"input\", (e) => {\n // setTimeout func was added to limit search operation by time for performance\n setTimeout(() => {\n\n let searchValue = e.target.value\n if (searchValue === \"\") {\n // If there is no word in input, it calls createCards func\n this.createCards(this.foodsArray)\n } else if(searchValue != \"\") {\n // If there is some words in input, it calls searchedCards func\n const result = fuse.search(searchValue)\n this.searchedCards(result)\n }\n }, 500)\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 getFood() {\n var name=$(\"#txtSearch\").val();\n $.get(\"/search-food/\", {name: name, day: man_day}, function(data){\n setFood(man_day, data);\n });\n}",
"function searchAPI(recipe_search, food_search) {\n $('p.search_error').empty();\n let search_params = 'default';\n if (recipe_search) {\n //use the recipe search\n search_params = recipe_search;\n } else if (food_search) {\n //Or, use the food search\n search_params = food_search;\n }\n var recipeData = $(this).attr(\"data-name\");\n var ourAPIid = \"4dced6d2\";\n var ourAPIkey = \"1a7e0fea32a0ad94892aaeb51b858b48\";\n\n var queryURL = \"https://api.yummly.com/v1/api/recipes\" +\n \"?_app_id=\" + ourAPIid +\n \"&_app_key=\" + ourAPIkey +\n \"&q=\" + search_params;\n\n // Checks if \"use your diets and allergies\" box is checked and creats an updated queryURL\n if ($(\"#search-restrictions\").is(':checked')) {\n queryURL = queryURL + searchCriteria.queryParams;\n }\n\n $.ajax({\n type: 'GET',\n dataType: 'json',\n url: queryURL,\n }).then(function (result) {\n let results_length = result.matches.length; //saves results as a variable\n\n $('div.column_results').append(`Search Results (${results_length})`);\n result.matches.forEach(showFood);\n });\n}",
"function petfinderCall() {\n var pf = new petfinder.Client({ apiKey: petfinderKey, secret: petfinderSecret });\n\n pf.animal.search({\n location: userSearch,\n type: \"dog\",\n distance: 15,\n limit: 100\n })\n .then(function (response) {\n //// Original array to pull data. \n animalsArr = response.data.animals;\n populateDogCards(animalsArr);\n })\n .catch(function (error) {\n // Handle the error\n console.log(error);\n });\n }",
"async search(){\n let yp = await searchParameters.getYelpParams();\n let yelpReturn = await yelp.search(yp);\n if(yelpReturn.total !== 0){\n return yelpReturn;\n }\n else{\n return -1\n }\n }",
"function searchRestaurant() {\n let search = {\n bounds: map.getBounds(),\n types: [\"restaurant\"],\n };\n places.nearbySearch(search, (results, status) => {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n clearResults();\n clearMarkers();\n\n // Create a marker for each resturant found, and\n // assign a letter of the alphabetic to each marker icon.\n for (let i = 0; i < results.length; i++) {\n let markerLetter = String.fromCharCode(\"A\".charCodeAt(0) + (i % 26));\n let markerIcon = MARKER_PATH + markerLetter + \".png\";\n\n // Use marker animation to drop the icons incrementally on the map.\n markers[i] = new google.maps.Marker({\n position: results[i].geometry.location,\n animation: google.maps.Animation.DROP,\n icon: markerIcon,\n });\n\n // If the user clicks a resturant marker, show the details of that place in an info window\n markers[i].placeResult = results[i];\n google.maps.event.addListener(markers[i], \"click\", showInfoWindow);\n setTimeout(dropMarker(i), i * 100);\n addResult(results[i], i);\n }\n }\n });\n}",
"function SearchForBookshelf(keyword, callback) {\n var bookshelfList = GetAllBookshelves();\n var result = [];\n\n for (x of bookshelfList) {\n var str = x.id.toLowerCase();\n if (str.indexOf(keyword.toLowerCase()) != -1) {\n result.push(x);\n }\n }\n\n return result;\n}",
"function doFuseSearch(query) {\n let results = fuse.search(query);\n return results;\n}",
"function matchFoodToWine(uSearch, indexer){\n var terms = uSearch.split(\" \"); //break the user search into an array of words\n var items = []; //Holds list of all wine matches based on search terms \n var i = terms.length - 1; //Iterator\n \n //Goes through search terms to find if there are paired wines in our matching table\n while(i > -1){\n if(indexer[terms[i]]){\n items = items.concat(indexer[terms[i]]);\n }\n i--;\n }\n\n //If no matches were found take the default wines\n if(items.length === 0){\n items = items.concat(indexer.default);\n }\n items.sort();//sort items by alpha\n items = getMode(items);//get item(s) that appear most frequently\n\n //If there are more than 2 varietals to search then select 2\n //at random. In the future this would be more sophisticated for \n //selection mechanism \n if (items.length > 1){\n items = pickRandom(items); //returns an item from the array to search\n }\n varietalInformation = extractVarietalInfo(items);\n return items;\n }",
"function searchFunc() {\n\t // get the value of the search input field\n\t var searchString = $('#search').val(); //.toLowerCase();\n\t markers.setFilter(showFamily);\n\n\t // here we're simply comparing the 'state' property of each marker\n\t // to the search string, seeing whether the former contains the latter.\n\t function showFamily(feature) {\n\t return (feature.properties.last_name === searchString || feature.properties[\"always-show\"] === true);\n\t }\n\t}",
"function search(name) {\n\tvar queryUrl = \"/sixthadmin/links/name_search.php?name=\" + name;\n\t$.getJSON(queryUrl, function(data) {\n\t\tprocess(data);\n\t});\n}",
"function search(searchTerms) {\r\n //gets JSON data from URL and cycles through each entry\r\n $.getJSON(URL, (jsonItem) => {\r\n let match = 0;\r\n for(let i = 0; i < jsonItem.length; i++) {\r\n //If no match of the search terms in the title, then check for match in the keywords\r\n //If a match in either, add the result to index.html and continue\r\n if (addIfMatch(getKeywords(jsonItem[i].title), searchTerms, jsonItem[i])) {\r\n match++;\r\n continue;\r\n }\r\n else if (addIfMatch(getKeywords(jsonItem[i].keywords), searchTerms, jsonItem[i])){\r\n match++;\r\n continue;\r\n }\r\n }\r\n if (!match) {\r\n $(\"#searchContainer\").append(\"<p>No search results found</p>\");\r\n }\r\n });\r\n}",
"function get_tray_info(rid) {\n var url = 'http://foodbot.ordr.in:8000/TextSearch?rid='+rid+'&target=pizza pie';\n request({\n url: url,\n json: true\n }, function (error, response, body) {\n if (!error && response.statusCode === 200) {\n for(var i=0; i<body.length; i++){\n if(body[i].tray){\n tray = body[i].tray;\n price = body[i].price;\n place_pizza_order(rid,tray,price);\n break;\n }\n }\n }\n else{\n console.log(error);\n }\n });\n\n}",
"function performSearch(srch, srchType, btnIndex){\n //Make the inputs into the URL and call the API\n //Reset variables\n currentFoodResults = [[],[],[],[],[]];\n currentWineResults = [[],[],[],[],[],[],[]];\n varietalInformation = null;\n foodRunFlag = false;\n wineRunFlag = false;\n numResults = 5;\n maxResults = 0;\n\n if(buttonTrigger === false){//Make API call if new search\n\n if(srchType === \"wine\"){ //If searching for a wine\n foodUrl = makeSearchIntoFoodURL(matchFoodToWine(userSearch, varietals)); //find food that pairs for the search\n wineUrl = makeSearchIntoWineURL(userSearch);\n varietalInformation = varietalInfo[userSearch];\n } else { //Otherwise\n foodUrl = makeSearchIntoFoodURL(userSearch); //assume search was for food\n wineUrl = makeSearchIntoWineURL(matchFoodToWine(userSearch, ingredients)); //Get a wine varietal to search\n }\n\n getFoods(foodUrl, extractFoodResults);\n getWines(wineUrl, extractWineResults);\n\n } else if(buttonTrigger === true) {//Skip the API call and reference the cached result\n extractFoodResults(foodResults[btnIndex][1], btnIndex);\n extractWineResults(wineResults[btnIndex][1], btnIndex);\n }\n }",
"function searchspecies(manual)\n{\n\t// Array of entries which match the search term\n\tmatches = [];\n\t\n\t// Get the search term we are using\n\tterm = document.getElementById('search').value;\n\t\n\t// Iterate over the pokedex\n\tfor(key of Object.keys(pokedex))\n\t{\n\t\t// Dereference the key\n\t\tlet dex = pokedex[key];\n\t\t\n\t\t// If the search button was clicked\n\t\tif(manual)\n\t\t{\n\t\t\t// If the search term exactly equals the pokemon's name (case insensitive)\n\t\t\tif(dex.name.toLowerCase() == term.toLowerCase())\n\t\t\t{\n\t\t\t\t// Add the matched name to the list\n\t\t\t\tmatches.push(dex);\n\t\t\t}\n\n\t\t}\n\t\t// Search button was not clicked\n\t\telse\n\t\t{\n\t\t\t// If the term contains the pokemon's name (case insensitive)\n\t\t\tif(dex.name.toLowerCase().includes(term.toLowerCase()))\n\t\t\t{\n\t\t\t\t// Add the matched name to the list\n\t\t\t\tmatches.push(dex);\n\t\t\t}\n\t\t}\n\t}\n\n\t// If there is exactly one match\n\tif(matches.length == 1)\n\t{\n\t\t// Load the pokemon into the tool\n\t\tdocument.active = matches.pop();\n\t\t\n\t\t// Run the weakness calculator\n\t\tpopulatefields();\n\t}\n}",
"function searchByGender(people){\n let typeGender = promptFor(\"Enter 'male' or 'female'\", validateGender);\n let displayPeopleByGender = people.filter(function(el){\n return el.gender == typeGender.toLowerCase();\n });\n alert(\"Total \"+displayPeopleByGender.length+\" persons found based on your search\");\n displayPeople(displayPeopleByGender);\n alert(\"Please enter the Name now:\");\n let personFoundByGender = searchByName(displayPeopleByGender);\n //displayPerson(personFoundByGender);\n mainMenu(personFoundByGender[0], people); //couldn't pass this as object, so did this little trick?Question?\n}",
"async search() {\n if (this.#selected !== \"\") {\n this.#name.value = this.#name.value.trim();\n\n const query = {\n type: this.#selected,\n };\n\n if (this.#rarity.value !== \"\") {\n query.rarity = this.#rarity.value;\n }\n\n let result = await DataBase.search(\"armor\", query, {\n id: \"true\",\n name: \"true\",\n rarity: \"true\",\n defense: {\n base: \"true\",\n },\n \"resistances.fire\": \"true\",\n \"resistances.water\": \"true\",\n \"resistances.ice\": \"true\",\n \"resistances.thunder\": \"true\",\n \"resistances.dragon\": \"true\",\n });\n\n //Matches exist\n if (result !== undefined && result.length !== 0) {\n this.clearSearch();\n\n console.log(result);\n\n result.forEach((record) => {\n if (\n record.name.toLowerCase().includes(this.#name.value.toLowerCase())\n ) {\n let card = this.#createMiniCard(record);\n this.#result.appendChild(card);\n }\n });\n } else {\n this.#result.innerHTML = this.#createWarnCard(\"No results\");\n }\n } else {\n alert(\"Select an armor slot\");\n }\n }",
"function getFoodInfo(meal_id, unirest, callback)\n\t{\n let foodData = {};\n foodData[\"mid\"] = meal_id;\n console.log(`Getting info for ${meal_id}`)\n\t\tunirest.get(`https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/${meal_id}/information?includeNutrition=true`)\n\t\t.header(\"X-RapidAPI-Key\", \"62649045e6msh29f8aefde649a9bp1591edjsnf389cd9bbedf\")\n\t\t.end(function(results) {\n\t\t // Store nutritional info\n for (let nutrient of results.body.nutrition.nutrients)\n {\n if (nutrient.title.toLowerCase() === 'calories')\n foodData[\"calories\"] = Math.round(nutrient.amount);\n if (nutrient.title.toLowerCase() === 'protein')\n foodData[\"protein\"] = Math.round(nutrient.amount);\n if (nutrient.title.toLowerCase() === 'carbohydrates')\n foodData[\"carbs\"] = Math.round(nutrient.amount);\n if (nutrient.title.toLowerCase() === 'fat')\n foodData[\"fats\"] = Math.round(nutrient.amount);\n }\n foodData[\"imagelink\"] = results.body.image;\n foodData[\"title\"] = results.body.title;\n foodData[\"link\"] = results.body.sourceUrl;\n foodData[\"slink\"] = results.body.spoonacularSourceUrl;\n foodData[\"vegetarian\"] = results.body.vegetarian;\n foodData[\"glutenfree\"] = results.body.glutenFree;\n foodData[\"vegan\"] = results.body.vegan;\n foodData[\"dairyfree\"] = results.body.dairyFree;\n foodData[\"ketogenic\"] = results.body.ketogenic;\n\n // Get and store price info\n\t\t let recipeStr = \"\";\n for (let ingredient of results.body.extendedIngredients)\n recipeStr += ingredient.originalString + \"\\n\";\n\n unirest.post(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/visualizePriceEstimator\")\n .header(\"X-RapidAPI-Key\", \"62649045e6msh29f8aefde649a9bp1591edjsnf389cd9bbedf\")\n .header(\"Accept\", \"text/html\")\n .header(\"Content-Type\", \"application/x-www-form-urlencoded\")\n .send(\"defaultCss=true\")\n .send(\"mode=1\")\n .send(\"showBacklink=false\")\n .send(`ingredientList=${recipeStr}`)\n .send(\"servings=1\")\n .end(function(results){\n const priceRegex = /(?:Cost per Serving: )(\\$\\d+\\.\\d\\d)/;\n let res = priceRegex.exec(results.body);\n if (res !== null && typeof res !== 'undefined' && res.length > 1)\n foodData[\"price\"] = res[1];\n else\n {\n foodData[\"price\"] = \"$7.69\";\n console.log(\"ERROR:\\n\");\n console.log(results.body)\n }\n for (let key in foodData) {\n foodData[key] = sqlstr.escape(foodData[key]);\n }\n callback(foodData);\n });\n });\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch function Returns a promise Why this won;t work, objects = the objectArrays return fetch(books_url).then(res => res.json()).then(objects => console.log(objects)) | function fetchBooks(){
return fetch(books_url).then(res => res.json())
// Good practice to write out headers even for get fetch, sometimes it can be html coming back.
// function fetchBooks(){
// // Returns a promise
// return fetch(books_url, {
// headers: {
// "Accept": "application/json"
// }
// })
// .then(res => res.json())
// }
} | [
"function fetchBooks() {\n fetch('https://anapioficeandfire.com/api/books').then(respfrombooks => respfrombooks.json()).then(respfrombooksjson => renderBooks(respfrombooksjson))\n}",
"function getAllBookings() {\n // the URL for the request\n const url = '/bookings';\n // Since this is a GET request, simply call fetch on the URL\n fetch(url)\n .then((res) => {\n if (res.status === 200) {\n // return a promise that resolves with the JSON body\n return res.json();\n } else {\n alert('Could not get bookings');\n }\n })\n .then((json) => { // the resolved promise with the JSON body\n bookingsList = document.querySelector('#allBookingsList');\n bookingsList.innerHTML = '';\n log(json);\n json.bookings.map((b) => {\n addToBookings(b);\n });\n }).catch((error) => {\n log(error);\n });\n}",
"function loadBooks() {\n\t\tAPI.getBooks()\n\t\t\t.then((res) => setBooks(res.data))\n\t\t\t.catch((err) => console.log(err));\n\t}",
"function callBooksAPI() {\n $.ajax({\n url: urlIBN,\n method: \"GET\"\n }).then(function (response) {\n var bibToSearch = '';\n var length = 0;\n if (JSON.parse(response).docs.length <= 3) {\n length = JSON.parse(response).docs.length;\n } else {\n length = 3;\n }\n for (var i = 0; i < length; i++) {\n if (i === 0) {\n bibToSearch = (JSON.parse(response).docs[i].isbn[0]);\n } else {\n bibToSearch = bibToSearch + \",\" + (JSON.parse(response).docs[i].isbn[0]);\n }\n bibkeys.push(JSON.parse(response).docs[i].isbn[0]);\n publishers.push(JSON.parse(response).docs[i].publisher[0]);\n }\n\n for (var i = 0; i < bibkeys.length; i++) {\n var bookOBJ = {};\n var bookImg = \"\";\n var info_url = \"\";\n bookOBJ.bookImg = 'https://covers.openlibrary.org/b/isbn/' + bibkeys[i] + '-S.jpg';\n bookOBJ.info_url = 'https://openlibrary.org/isbn/' + bibkeys[i];\n booksArray.push(bookOBJ);\n\n }\n showBooks(booksArray);\n })\n}",
"async getQuoteAffiliationPendingList() {\n \n let url = API_URL + \"/affilliatepending/affiliatependinglistquotes\";\n return await fetch(url)\n .then(res => res.json())\n .then(response => {\n return response;\n })\n .catch(error => {\n console.log(error);\n return undefined;\n });\n }",
"async function findObjects(argv) {\n let body = {};\n const url = new URL(argv.url);\n url.pathname = '/api/saved_objects/_find';\n url.search = '?per_page=1000';\n for (const type of argv.types) url.search += `&type=${type}`;\n url.search;\n url.search += argv.search ? `&search=${argv.search}` : '';\n\n logger.verbose('url.search: ' + url.search);\n\n const options = {\n method: 'GET',\n headers: {\n 'kbn-xsrf': true,\n },\n };\n\n try {\n const res = await fetch(url, { ...options });\n body = await res.json();\n if (res.status === 200) {\n logger.info(\n `${res.status} ${res.statusText} Found: ${body.saved_objects.length} objects`\n );\n } else {\n logger.error(`${res.status} ${res.statusText} Error: ${body}`);\n }\n } catch (FetchError) {\n logger.error(`${FetchError.message}`);\n }\n return body.saved_objects;\n}",
"function getListOfGenres() {\n // api url info\n type = \"genre/movie/list\";\n let url = apiUrl + type + apiKey;\n let genres = [];\n\n fetch(url).then(function(response) {\n return response.json();\n }).then(function(obj) {\n\n for (let i = 0; i < obj.genres.length; i++) {\n genres.push(obj.genres[i]);\n }\n return genres;\n\n\n }).catch(function(error) {\n console.error(\"Something went wrong\");\n console.error(error);\n })\n return genres;\n\n}",
"function getMoviesViaFetch() {\n return fetch(\n url, {\n method: 'get',\n headers: {\n 'Accept': 'application/json'\n }\n })\n .then(response => response.json())\n .then(movies => writeMovies(movies))\n .catch(error => console.error(error.message))\n }",
"function getAllBooks() {\n return books;\n}",
"function fetchBurgers(){\n fetch(\"http://localhost:3000/burgers\")\n .then(r=>r.json())\n .then(burgers => renderAllBurgers(burgers))\n}",
"async function getBikes() {\n let response = [];\n try {\n const res = await fetch(apiUrl);\n if (! res.ok) throw new Error(res.status);\n response = await res.json();\n } catch (error) {\n console.log(error);\n }\n return response;\n}",
"async function exportObjects(argv) {\n const url = new URL(argv.url);\n url.pathname = '/api/saved_objects/_export';\n\n const options = {\n method: 'GET',\n headers: {\n 'kbn-xsrf': true,\n },\n };\n\n try {\n const res = await fetch(url, { ...options });\n const body = JSON.stringify(await res.json(), null, 2);\n if (res.status === 200) {\n logger.info(`${res.status} ${res.statusText} Response:\\n${body}`);\n } else {\n logger.error(`${res.status} ${res.statusText} Error: ${body}`);\n }\n } catch (FetchError) {\n logger.error(`${FetchError.message}`);\n }\n}",
"function getBooks(request, response) {\n \n\tbookModel.getAllBooksFromDB(function(error, result) {\n\t\t// This is the callback function that will be called when the DB is done.\n\t\t// The job here is just to send it back.\n\n\t\t// Make sure we got the books and send a response back\n\t\tif (error || result == null) {\n\t\t\tresponse.status(500).json({success: false, data: error});\n\t\t} else {\n\t\t\tresponse.json(result);\n\t\t}\n\t});\n}",
"function bookRecommendations () {\n \n fetch(\n 'https://api.nytimes.com/svc/books/v3/lists/current/e-book-fiction.json?api-key=HXMcUKu4hWhoZPQBW99bGZ9An0FdbWEl'\n )\n .then(function(res) {\n return res.json();\n })\n .then(function(res) {\n console.log(res);\n displayRecommendations(res);\n });\n }",
"async function getProductList() {\n\n await fetch('http://52.26.193.201:3000/products/list')\n .then(response => response.json())\n .then(response => setProductList([...response]))\n }",
"function retrievedBooks (account, books) {\n let id = account.id\n let allBooksCheckedOut = [];\n for (let i = 0; i < books.length; i ++) {\n if (books[i].borrows[0].returned === false && books[i].borrows[0].id === id) {\n allBooksCheckedOut.push(books[i])\n }\n }\n return allBooksCheckedOut\n}",
"function getToys() {\n fetch('http://localhost:3000/toys')\n .then(resp => resp.json())\n .then(toys => toys.forEach(toy => createToyCard(toy)))\n}",
"function getSongs() {\n fetch(songsURL)\n .then((response) => response.json())\n .then((songs) => songs.forEach((song) => renderSong(song)));\n}",
"function fb_fetch_all_data(url, cb){\n objects = [];\n function iterator(url){\n fb.get(url, function(err, data){\n if (err){\n cb(err, null);\n return;\n }\n if (data.data.length == 0){\n cb(null, objects);\n return;\n }\n for (var i = 0; i < data.data.length; i++){\n objects.push(data.data[i]);\n }\n iterator(data.paging.next);\n });\n }\n iterator(url);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unbinds a listener from a keyset | static unbind(keys, classRef) {
for (const key of keys) {
for (const i in listeners[key]) {
if (listeners[key][i] === classRef) {
delete listeners[key][i]
}
}
}
} | [
"function removeUiStateSetListener(callback, context) {\n\tvar i;\n\tfor (i = uiStateSetListeners.length - 1; i >= 0; i--) {\n\t\tif ((!callback || uiStateSetListeners[i].callback === callback) && (!context || uiStateSetListeners[i].context === context)) {\n\t\t\tuiStateSetListeners.splice(i, 1);\n\t\t}\n\t}\n}",
"stopListening() {\n this._eventsNames.forEach((eventName) => {\n process.removeListener(eventName, this.handler);\n });\n }",
"static detachListener(cb) {\n firebase.database().ref(BASE).off(\"value\", cb);\n }",
"off(event, handler) {\n const handlers = this._handlers && this._handlers[event];\n if (!handlers) return;\n handlers.forEach((func, index) => {\n if (func !== handler) return;\n handlers.splice(index, 1);\n });\n }",
"removeShortcut(keys) {\n Mousetrap.unbind(keys)\n }",
"off(name, callback, context) {\n var retain, ev, events, names, i, l, j, k;\n if (!this._events || !utils.eventsApi(this, 'off', name, [callback, context])) return this;\n if (!name && !callback && !context) {\n this._events = void 0;\n return this;\n }\n names = name ? [name] : keys(this._events);\n for (i = 0, l = names.length; i < l; i++) {\n name = names[i];\n if (events = this._events[name]) {\n this._events[name] = retain = [];\n if (callback || context) {\n for (j = 0, k = events.length; j < k; j++) {\n ev = events[j];\n if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||\n (context && context !== ev.context)) {\n retain.push(ev);\n }\n }\n }\n if (!retain.length) delete this._events[name];\n }\n }\n\n return this;\n }",
"unbindEvents() {\n const document = this.frame.contentWindow.document;\n if (this.arrayOfEvents !== undefined && Array.isArray(this.arrayOfEvents)) {\n this.arrayOfEvents.forEach((event) => {\n document.removeEventListener(event[0], event[1]);\n });\n }\n }",
"function nickSelected(){\n window.removeEventListener(\"keydown\", handleKeys);\n document.getElementById(\"play\").addEventListener(\"click\", playClick);\n}",
"function deactivateClicks() {\n\t console.log( \"Deactivating cliker\");\n\tArray.from( ptrAnswers ).forEach( function( item ) {\n\t\titem.removeEventListener( \"click\", answerSelected );\n\t})\n}",
"onEventHandlerUnset(room, handler, identifier) {\n delete this.handlers[handler][identifier];\n }",
"unregisterListener(aListener) {\n let idx = this._listeners.indexOf(aListener);\n if (idx >= 0) {\n this._listeners.splice(idx, 1);\n }\n }",
"removeChangeListener(callback) {\n this.removeListener(AppConstants.CHANGE_EVENT, callback);\n }",
"unbind () {\n log.debug(`Removing replica \"${this}\" from the list of replicas`);\n this.pool.unregisterReplica(this);\n this.pool.node.emit('replica', {\n eventType: 'del',\n object: this\n });\n this.pool = null;\n }",
"function unbind_keys() {\n\t$(document).unbind(\"keyup\");\n\t$(document).unbind(\"keydown\");\n}",
"function unregisterInnerHotkeys() {\n $document.unbind(\"keyup\", innerHotkeysListener);\n }",
"undelegate(eventName, selector, listener, uid) {\n\n\t\tif (this.el){\n\t\t\tif (selector){\n\t\t\t\tconst items = [...this.el.querySelectorAll(selector)];\n\t\t\t\tif (items.length > 0 ) items.forEach((item) => item.removeEventListener(eventName, listener) );\n\t\t\t} else {\n\t\t\t\tthis.el.removeEventListener(eventName, listener);\n\t\t\t}\n\t\t}\n\t\t// remove event from array based on uid\n\t\t_.remove(this.delegatedEvents, (event) => {\n\t\t\treturn event.uid === uid;\n\t\t});\n\n\t\treturn this;\n\t}",
"function unbindFollowUnfollowButton(){\n var unfollowButtons = document.getElementsByClassName(\"unfollow\");\n var followButtons = document.getElementsByClassName(\"follow\");\n for(var x = 0; x < unfollowButtons.length; x++){\n unfollowButtons[x].removeEventListener(\"click\", unfollow);\n }\n for(var x = 0; x < followButtons.length; x++){\n followButtons[x].removeEventListener(\"click\", follow);\n\n }\n}",
"function offOnLostFocusListener(selector){\n\tselector.off(\"focusout\");\n}",
"function removeListeners() {\n removeEventListener('pointerup', onPointerUp, listenerOpts);\n removeEventListener('pointercancel', onPointerCancel, listenerOpts);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in the ID of a cryptocurrency and returns the CryptoExchanger object which handles that currency | static getCryptoExchanger(inCoinID) {
for(var i = 0; i < CryptoExchanger.cryptoExchangerArray.length; i++) {
if(CryptoExchanger.cryptoExchangerArray[i].getCoinID() === inCoinID) {
return CryptoExchanger.cryptoExchangerArray[i];
}
}
return null;
} | [
"static getCryptoExchangerByName(inCoinName) {\n for(var i = 0; i < CryptoExchanger.cryptoExchangerArray.length; i++) {\n if(CryptoExchanger.cryptoExchangerArray[i].getCoinName() === inCoinName) {\n return CryptoExchanger.cryptoExchangerArray[i];\n }\n }\n }",
"convert(money, currency) {\n if (money.currency === currency) {\n return new Money(money.amount, money.currency)\n }\n\n const key = money.currency + '->' + currency\n const rate = this.exchangeRates.get(key)\n\n if (rate == null) throw new Error(`Missing exchange rate: ${key}`)\n return new Money(money.amount * rate, currency)\n }",
"function getExchange(id) {\n return fetch(`${url}/exchanges/${id}`)\n .then((res) => res.json())\n .then((res) => res.data);\n}",
"getAmountById(id) {\n return axios.get(API_URL + \"amount/id/\" + id, {\n headers: authHeader(),\n });\n }",
"getInverter(id) {\r\n\t\tlet device = this.getDevice({ id: id });\r\n\t\tlet result;\r\n\t\tif (device) {\r\n\t\t\tresult = device.inverter;\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"function grantCurrency(command, context, callback) {\n if (isMod(context)) {\n if ([\"gold\", \"silver\"].indexOf(command[2])) {\n new Banking.Account(context[\"user-id\"], account => {\n console.log(\"accountExists: \" + account.accountExists);\n let twitch = new Twitch('mjy60l6upiqb62b46kq1hyp6gwodow');\n twitch.getUserID(command[3], response => client.say(target, response));\n account.updateBalance(command[2], command[3]);\n //client.say(target, account.accountExists.toString());\n });\n }\n } else {\n callback(\"You do not have permission\");\n }\n }",
"approveCurrency(currency) {\n this.approveCurrencyForAmount(currency, MAX_VAL)\n }",
"async approveCurrencyForAmount(currency, amount) {\n var { options } = this.props\n \n let market_address = options.contracts.Market.address\n\n if(currency in options.contracts) {\n var contract = options.contracts[currency]\n await contract.approve(market_address, amount)\n }\n }",
"function CurrencyHandler() {\n\t\tthis.type = 'currency';\n\t}",
"function getCurrency(){\n //selected currencies\n fromCurr = selects[0].selectedOptions[0].textContent;\n toCurr = selects[1].selectedOptions[0].textContent;\n \n //get currency code according to currency name\n if(fromCurr !== ''){\n const index = currencies.findIndex((obj) => obj.currency_name == fromCurr);\n base = currencies[index].currency_code;\n }\n\n if(toCurr !== ''){\n const index = currencies.findIndex((obj) => obj.currency_name == toCurr);\n rateKey = currencies[index].currency_code;\n }\n}",
"function findCurrencyInfo (account: EdgeAccount, currencyCode: string): EdgeCurrencyInfo | void {\n for (const pluginName in account.currencyConfig) {\n const { currencyInfo } = account.currencyConfig[pluginName]\n if (currencyInfo.currencyCode.toUpperCase() === currencyCode) {\n return currencyInfo\n }\n }\n}",
"function spongeEconomyDeposit(uuid,value){\n var account = EconomyService.getOrCreateAccount(UUID.fromString(uuid)) //gets Economy Account for the Player.\n var value = new BigDecimal(value) //value in () is value to be deposited.\n var currency = EconomyService.getDefaultCurrency() //gets DefaultCurrency of the Economy Plugin\n var cause = Sponge.getCauseStackManager().getCurrentCause() //gets the Cause Manager from Sponge\n\n account.get().deposit(currency,value,cause) //deposit amount of value into players account.\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 }",
"getCurrency() {\n const tier = this.getTier();\n return get(tier, 'currency', this.props.data.Collective.currency);\n }",
"static createCurrencyWidthIdentifier(identifier){\n\n switch (identifier) {\n case Currency.currencyList.nigeria:\n let nigerianCurrency = new Currency(identifier, 1, 0.0021, 0.0028, 'N');\n return nigerianCurrency;\n break;\n\n case Currency.currencyList.britain:\n let britishCurrency = new Currency(identifier, 477.34, 1, 1.32, '£');\n return britishCurrency;\n break;\n\n default:\n let usaCurrency = new Currency(identifier, 360.50, 0.76, 1, '$');\n\n }\n\n }",
"async function solveExchangeTx(contract, targetAddress, amount, key) {\n return await contract.functions\n .solve(wallet.alice.publicKey, new SignatureTemplate(wallet.alice.privateKey), key)\n .to(targetAddress, amount)\n .withFeePerByte(1)\n .send()\n}",
"function get_currency_code(str) {\n return str.match(/\\((.*?)\\)/)[1];\n}",
"function removeCurrency(id){\r\n\trow = document.getElementById(id);\r\n\t//Remove the index out of the used currencies\r\n\tusedCurrencies = removeFromArray(parseInt(row.value),usedCurrencies);\r\n\t//Remove the row of the currency\r\n\trow.parentNode.removeChild(row);\r\n\t//Add the currency back to the dropdown list for adding\r\n\tupdateAddableCurrencies();\r\n\tupdateValues();\r\n}",
"function spongeEconomyBalance(uuid){\n var account = EconomyService.getOrCreateAccount(UUID.fromString(uuid)) //gets Economy Account for the Player.\n\n account.get().getBalance(currency) //check the amount of a players account.\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SET THE GLOBAL DATE TO THE PREVIOUS YEAR AND REDRAW THE CALENDAR | function setPreviousYear() {
var year = tDoc.calControl.year.value;
if (isFourDigitYear(year) && year > 1000) {
year--;
calDate.setFullYear(year);
tDoc.calControl.year.value = year;
// GENERATE THE CALENDAR SRC
calDocBottom = buildBottomCalFrame();
// DISPLAY THE NEW CALENDAR
writeCalendar(calDocBottom);
}
} | [
"function setNextYear() {\n\n var year = tDoc.calControl.year.value;\n if (isFourDigitYear(year)) {\n year++;\n calDate.setFullYear(year);\n tDoc.calControl.year.value = year;\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n}",
"function setYear() {\n\n // GET THE NEW YEAR VALUE\n var year = tDoc.calControl.year.value;\n\n // IF IT'S A FOUR-DIGIT YEAR THEN CHANGE THE CALENDAR\n if (isFourDigitYear(year)) {\n calDate.setFullYear(year);\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n else {\n // HIGHLIGHT THE YEAR IF THE YEAR IS NOT FOUR DIGITS IN LENGTH\n tDoc.calControl.year.focus();\n tDoc.calControl.year.select();\n }\n}",
"function setPreviousMonth() {\n\n var year = tDoc.calControl.year.value;\n if (isFourDigitYear(year)) {\n var month = tDoc.calControl.month.selectedIndex;\n\n // IF MONTH IS JANUARY, SET MONTH TO DECEMBER AND DECREMENT THE YEAR\n if (month == 0) {\n month = 11;\n if (year > 1000) {\n year--;\n calDate.setFullYear(year);\n tDoc.calControl.year.value = year;\n }\n }\n else {\n month--;\n }\n calDate.setMonth(month);\n tDoc.calControl.month.selectedIndex = month;\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n}",
"function prevYear() {\n\tif (YEAR > 1950) {\n\t\tYEAR--;\n\t}\n\tsetDateContent(MONTH, YEAR);\n}",
"function setToday() {\n\n \n // SET GLOBAL DATE TO TODAY'S DATE\n calDate = new Date();\n\n // SET DAY MONTH AND YEAR TO TODAY'S DATE\n var month = calDate.getMonth();\n var year = calDate.getFullYear();\n\n // SET MONTH IN DROP-DOWN LIST\n tDoc.calControl.month.selectedIndex = month;\n\n // SET YEAR VALUE\n tDoc.calControl.year.value = year;\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n}",
"function setNextMonth() {\n\n var year = tDoc.calControl.year.value;\n\n if (isFourDigitYear(year)) {\n var month = tDoc.calControl.month.selectedIndex;\n\n // IF MONTH IS DECEMBER, SET MONTH TO JANUARY AND INCREMENT THE YEAR\n if (month == 11) {\n month = 0;\n year++;\n calDate.setFullYear(year);\n tDoc.calControl.year.value = year;\n }\n else {\n month++;\n }\n calDate.setMonth(month);\n tDoc.calControl.month.selectedIndex = month;\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n}",
"function _resetCalandarDates()\n{\n if (!IS_FLEET && jsvLastEventYMD && (jsvLastEventEpoch > 0)) {\n if (mapCal_to) {\n var day = jsvLastEventYMD.DD + 1; // next day\n mapCal_to.setDate(jsvLastEventYMD.YYYY, jsvLastEventYMD.MM, day);\n }\n if (mapCal_fr) { \n var day = jsvLastEventYMD.DD; // this day\n mapCal_fr.setDate(jsvLastEventYMD.YYYY, jsvLastEventYMD.MM, day); \n }\n } else\n if (jsvTodayYMD) {\n if (mapCal_to) {\n var day = jsvTodayYMD.DD + 1; // next day\n //alert(\"_resetCalandarDates: YYYY=\"+jsvTodayYMD.YYYY+ \" MM=\"+jsvTodayYMD.MM+ \" DD=\"+day);\n mapCal_to.setDate(jsvTodayYMD.YYYY, jsvTodayYMD.MM, day);\n }\n if (mapCal_fr) { \n var day = jsvTodayYMD.DD; // this day\n mapCal_fr.setDate(jsvTodayYMD.YYYY, jsvTodayYMD.MM, day); \n }\n } else {\n // as a last resort, we could rely on the 'Date' returned by the browser\n // (which may be inaccurate), but for now just leave the calendars as-is.\n }\n}",
"set_date(year, month) {\n if (year == null) {\n var d = new Date(),\n month = d.getMonth(),\n year = d.getFullYear();\n }\n\n var d1 = new Date(year, month + 1, 0);\n this.month = d1.getMonth();\n this.year = d1.getFullYear();\n this.num_days = d1.getDate();\n this.show_date(d1);\n }",
"function setCurrentMonth() {\n\n // GET THE NEWLY SELECTED MONTH AND CHANGE THE CALENDAR ACCORDINGLY\n var month = tDoc.calControl.month.selectedIndex;\n\n calDate.setMonth(month);\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n}",
"function hundYearBack() {\n var date = new Date();\n var yr = date.getFullYear();\n date.setFullYear(yr-100);\n document.write(\"Current year is \"+ yr +\"<br> 100 year ago, it was \"+ date);\n}",
"function previous() {\n // if month equals to the value of 0 so the year will subtracts 1 then month will go to 11 that the value of Dec\n // else just only subtract the month and keep year in the same year\n if (month == 0) {\n year = year - 1;\n month = 11;\n } else {\n month = month - 1;\n }\n showCalendar(month, year);\n}",
"setPrevMonth() {\n let {month, year} = this.getMonth('prev');\n this.setDate(new Date(year, month, 1));\n }",
"function setNewDate() { //modificamos la fecha que ya tenemos, para esteblecer la nueva fecha.\n\tescribirMes(mes,anyo);\n}",
"function btnPreviousYearClick() {\n\t\terase();\n\t\tyearCheck = yearCheck - 1;\n\t\tconsole.log(monthCheck);\n\t\tsetData();\n\t\tsetMonths();\n\t\tsetYears();\n\t}",
"onPrevMonth() {\n const newDate = DateConverters.addMonths(this.visibleDate, -1);\n this.changeDate(newDate);\n }",
"function setYear() {\n\tvar element = document.getElementById(\"selected_year\");\n\tYEAR = element.options[element.selectedIndex].value;\n\tsetDateContent(MONTH, YEAR);\n}",
"changeYear(newYear){\n this.yearReleased = newYear;\n }",
"function setInitialDate() {\n \n // CREATE A NEW DATE OBJECT (WILL GENERALLY PARSE CORRECT DATE EXCEPT WHEN \".\" IS USED AS A DELIMITER)\n // (THIS ROUTINE DOES *NOT* CATCH ALL DATE FORMATS, IF YOU NEED TO PARSE A CUSTOM DATE FORMAT, DO IT HERE)\n calDate = new Date(inDate);\n\n // IF THE INCOMING DATE IS INVALID, USE THE CURRENT DATE\n if (isNaN(calDate) || inDate == \"\" || inDate == null) {\n\n // ADD CUSTOM DATE PARSING HERE\n // IF IT FAILS, SIMPLY CREATE A NEW DATE OBJECT WHICH DEFAULTS TO THE CURRENT DATE\n calDate = new Date();\n }\n\n // KEEP TRACK OF THE CURRENT DAY VALUE\n calDay = calDate.getDate();\n\n // SET DAY VALUE TO 1... TO AVOID JAVASCRIPT DATE CALCULATION ANOMALIES\n // (IF THE MONTH CHANGES TO FEB AND THE DAY IS 30, THE MONTH WOULD CHANGE TO MARCH\n // AND THE DAY WOULD CHANGE TO 2. SETTING THE DAY TO 1 WILL PREVENT THAT)\n calDate.setDate(1);\n}",
"function previousMonth(){\n if(data.calendar.month != 11 || data.calendar.year == 2019){\n data.calendar.month--;\n }\n if(data.calendar.month <= -1){\n data.calendar.month = 11;\n data.calendar.year--;\n }\n fillInCalendar();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter of the href attribute. | set href(aValue) {
this._logger.debug("href[set]");
this._href = aValue;
} | [
"set href(aValue) {\n this._logService.debug(\"gsDiggEvent.href[set]\");\n this._href = aValue;\n }",
"set link(aValue) {\n this._logService.debug(\"gsDiggEvent.link[set]\");\n this._link = aValue;\n\n var uri;\n try {\n uri = this._ioService.newURI(this._link, null, null);\n } catch (e) {\n uri = this._ioService.newURI(\"http://\" + this._link, null, null);\n }\n this._domain = uri.host;\n }",
"set link(aValue) {\n this._logger.debug(\"link[set]\");\n this._link = aValue;\n\n let uri;\n\n try {\n uri = this._ioService.newURI(this._link, null, null);\n } catch (e) {\n uri = this._ioService.newURI(\"http://\" + this._link, null, null);\n }\n\n this._domain = uri.host;\n }",
"function enforceHref(attributes) {\n if (!_.has(attributes, 'href')) {\n attributes.href = '#';\n }\n return attributes;\n}",
"function a_href() {\n let new_args = [];\n\n for (let i = 0, j = arguments.length; i < j; ++i) {\n if (i == 0) {\n new_args.push({\n href: arguments[i]\n });\n } else {\n new_args.push(arguments[i]);\n }\n }\n\n return new_element(\"a\", new_args);\n} // func",
"_getLinkURL() {\n let href = this.context.link.href;\n\n if (href) {\n // Handle SVG links:\n if (typeof href == \"object\" && href.animVal) {\n return this._makeURLAbsolute(this.context.link.baseURI, href.animVal);\n }\n\n return href;\n }\n\n href = this.context.link.getAttribute(\"href\") ||\n this.context.link.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\");\n\n if (!href || !href.match(/\\S/)) {\n // Without this we try to save as the current doc,\n // for example, HTML case also throws if empty\n throw \"Empty href\";\n }\n\n return this._makeURLAbsolute(this.context.link.baseURI, href);\n }",
"function updateLink(value) {\n var item = new Array;\n\n //! Update Link\n item.modified = new Date();\n item.id = 1\n item.link = value;\n Storage.updateLink(item);\n strLink = value;\n}",
"function setDeeplinking(event){\r\n\t\twindow.location.hash = $(event.target).data(\"target\");\r\n\t}",
"function adjustHref(href) {\n\treturn document.quicknavBasePath + \"/\" + href;\n}",
"function updateStatsLink() {\n const statsLink = document.getElementById(\"stats-link\")\n let statsLinkUrl = statsLink.getAttribute(\"href\")\n let query = statsLinkUrl.indexOf('?');\n if (query > 0) {\n var statsLinkUrlNew = statsLinkUrl.substring(0, query);\n } else {\n var statsLinkUrlNew = statsLinkUrl;\n }\n statsLinkUrlNew = statsLinkUrlNew + \"?\" + \"operator_name\" + \"=\" + settings.elements.operator_name.value\n + \"&\" + \"a_digits\" + \"=\" + settings.elements.a_digits.value\n + \"&\" + \"b_digits\" + \"=\" + settings.elements.b_digits.value\n statsLink.setAttribute(\"href\",statsLinkUrlNew)\n}",
"function resolveUrlAttribute ($node, attr) {\n var url = $node.attr(attr);\n if (url === undefined) return '';\n if (isAbsoluteUrl(url)) {\n return url;\n } else {\n return urlUtil.resolve(base, url);\n }\n }",
"function setSrc(element,attribute){element.setAttribute(attribute,element.getAttribute('data-'+attribute));element.removeAttribute('data-'+attribute);}",
"get link() {\n this._logger.debug(\"link[get]\");\n return this._link;\n }",
"function promptLinkAttrs(pm, callback) {\n\t new FieldPrompt(pm, \"Create a link\", {\n\t href: new TextField({\n\t label: \"Link target\",\n\t required: true,\n\t clean: function clean(val) {\n\t if (!/^https?:\\/\\//i.test(val)) val = 'http://' + val;\n\t return val;\n\t }\n\t }),\n\t title: new TextField({ label: \"Title\" })\n\t }).open(callback);\n\t}",
"function lc_update_filter_in_links (_links, _param, _filter)\n{\n\tfor (var a = 0; (a < _links.length); a++) {\n\t\tif (_links[a].href && _links[a].href.match ('^http'))\n\t\t\t\t_links[a].href = appendToUrl (_links[a].href, _param, _filter);\n\t}\n}",
"formatUrls(props) {\n this.href = props.href && typeof props.href === 'object' ? format(props.href) : props.href;\n this.as = props.as && typeof props.as === 'object' ? format(props.as) : props.as;\n }",
"function showLinkDialog_LinkSave(propert_key, url) {\n\tPropertiesService.getDocumentProperties().setProperty(propert_key, url);\n}",
"function setupLinks() {\n $('#channels a').click(function(event){\n var elem = $(event.currentTarget);\n var baseUrl = window.location.href.split('#')[0];\n var newUrl = baseUrl + elem.attr('href');\n location.replace(newUrl);\n location.reload();\n });\n }",
"set imageURL(aValue) {\n this._logger.debug(\"imageURL[set]\");\n this._imageURL = aValue;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the cell's neighbors. A cell's upper neighbor has index 0, the right neighbor has index 1 etc in the array cells[i][j].neighbor | function createNeighbors() {
for(var i = 0; i < cells.length; i++) {
for(var j = 0; j < cells[i].length; j++) {
if(j == cells[i].length - 1)
cells[i][j].neighbors.push(-1);
else
cells[i][j].neighbors.push(cells[i][j+1]);
if(i == cells.length - 1)
cells[i][j].neighbors.push(-1);
else
cells[i][j].neighbors.push(cells[i+1][j]);
if(j == 0)
cells[i][j].neighbors.push(-1);
else
cells[i][j].neighbors.push(cells[i][j-1]);
if(i == 0)
cells[i][j].neighbors.push(-1);
else
cells[i][j].neighbors.push(cells[i-1][j]);
}
}
} | [
"function createNeighborCells(){\n\n var array = new Array();\n var cellPositions = new Array();\n\n // Array the contains fix positions for neighbor cells.\n cellPositions.push(-89.3837279950771);\n cellPositions.push(-142.1328674980365);\n cellPositions.push(-349.87550855851305);\n\n cellPositions.push(-223.32720969134115);\n cellPositions.push(-297.8942624611899);\n cellPositions.push(489.4060068507289);\n\n cellPositions.push(-297.9375904074462);\n cellPositions.push(-179.997998506319);\n cellPositions.push(434.85706179775775);\n\n cellPositions.push(-103.14517395561478);\n cellPositions.push(-224.56336401620294);\n cellPositions.push(-262.54609417884353);\n\n cellPositions.push(-27.395086427601314);\n cellPositions.push(-385.5400787010433);\n cellPositions.push(-352.1989179669081);\n\n cellPositions.push(-360.83258065228586);\n cellPositions.push(-100.64813434224845);\n cellPositions.push(-97.02796592925534);\n\n cellPositions.push(-398.3297307080477);\n cellPositions.push(-66.22930655000425);\n cellPositions.push(-225.59875363251174);\n\n cellPositions.push(405.1131090482779);\n cellPositions.push(143.88113972097028);\n cellPositions.push(310.4022310528064);\n\n cellPositions.push(-264.3245450648799);\n cellPositions.push(-228.868464037242);\n cellPositions.push(0.8838596830101437);\n\n // Array that stores the three different textures for the neighbor cells.\n array.push(\"images/cellTextures/cover1.jpg\");\n array.push(\"images/cellTextures/cover2.jpg\");\n array.push(\"images/cellTextures/cover3.jpg\");\n\n var geometry = new THREE.SphereBufferGeometry(35, 35, 35);\n\n for (var i = 0; i < 27; i = i + 3) {\n\n var random = Math.floor(Math.random() * 3);\n\n let uniforms = {\n cover: {\n type: \"t\",\n value: new THREE.TextureLoader().load(array[random], function(texture){\n\n renderer.render(scene, camera);\n })\n }\n }\n\n var material = new THREE.RawShaderMaterial({\n uniforms: uniforms,\n vertexShader: document.getElementById(\"vertexShader\").textContent,\n fragmentShader: document.getElementById(\"fragShader\").textContent\n\n });\n\n var object = new THREE.Mesh(geometry, material);\n\n // This statements produce random locations for neighbor cells.\n // object.position.x = Math.random() * 900 - 400;\n // object.position.y = Math.random() * 900 - 400;\n // object.position.z = Math.random() * 900 - 400;\n\n object.position.x = cellPositions[i];\n object.position.y = cellPositions[i + 1];\n object.position.z = cellPositions[i + 2];\n\n object.name = \"neighborCell\";\n scene.add(object)\n }\n}",
"function getNeighbors(cell) {\n let neighbors = [];\n\n // A cells neighbors is all vertically, horizontally, and\n // diagonally adjacent cells. To find all neighbors we need to\n // iterate the 3x3 area surrounding the target cell. We can\n // accomplish this by starting our iteration one cell less than\n // the target cell, and end one cell beyond.\n let y = cell.getY() - 1\n let yBoundary = cell.getY() + 1\n\n while (y <= yBoundary) {\n\n // If the starting cell is out of bounds then we need to\n // determine which boundary is being violated. We will treat this\n // as an infinite space so the cell will switch to evaluating\n // the cell on the opposite end of the board.\n\n // If we are within the accepted boundaries then use the position.\n let yPosition = 0\n\n if (y >= 0 && y < config.cellsPerColumn) {\n yPosition = y;\n } else {\n\n // If we are negative then we have stretched beyond the top boundary.\n // Update the position to be at the bottom boundary. Otherwise, we\n // have stretched beyond the bottom boundary so update the position\n // to be at the top boundary.\n if (y < 0) {\n yPosition = config.cellsPerColumn - 1;\n }\n }\n\n let x = cell.getX() - 1\n let xBoundary = cell.getX() + 1\n\n while (x <= xBoundary) {\n\n // Similar to the y boundary, we need to determine if a\n // boundary is being violated, and respond accordingly.\n let xPosition = 0\n\n if (x >= 0 && x < config.cellsPerRow) {\n xPosition = x;\n } else {\n if (x < 0) {\n xPosition = config.cellsPerRow - 1;\n }\n }\n\n // Determine the index of the neighboring cell.\n const cellPosition = new Map()\n .set(Cell.ATTR_POSITION_Y, yPosition)\n .set(Cell.ATTR_POSITION_X, xPosition)\n const neighborIndex = calculateCellIndex(cellPosition)\n\n // Verify this cell is not the same as the target cell.\n // If it's not the same cell then add it to the array of\n // neighboring cells.\n let neighboringCell = cells[neighborIndex];\n\n if (neighboringCell !== cell) {\n neighbors.push(neighboringCell);\n }\n\n // Increment x position\n x++\n }\n\n // Increment y position\n y++\n }\n\n return neighbors;\n }",
"function getAdjacentCells(cell){\n\tvar cellCopy;\n\tif(cell.location.row+1 < mazeSize ){ // down\n\t\tcellCopy = new Cell(maze[cell.location.row+1][cell.location.col].location.row, maze[cell.location.row+1][cell.location.col].location.col,maze[cell.location.row+1][cell.location.col].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n\tif(cell.location.row-1 > -1){ // up\n\t\tcellCopy = new Cell(maze[cell.location.row-1][cell.location.col].location.row, maze[cell.location.row-1][cell.location.col].location.col,maze[cell.location.row-1][cell.location.col].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n\tif(cell.location.col+1 < mazeSize){ // right \n\t\tcellCopy = new Cell(maze[cell.location.row][cell.location.col+1].location.row, maze[cell.location.row][cell.location.col+1].location.col,maze[cell.location.row][cell.location.col+1].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n\tif(cell.location.col-1 > -1){ // left\n\t\tcellCopy = new Cell(maze[cell.location.row][cell.location.col-1].location.row, maze[cell.location.row][cell.location.col-1].location.col,maze[cell.location.row][cell.location.col-1].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n}",
"getNeighbors(col, row){\n var res = [];\n //left border\n if(col > 0){\n this.agentController.ocean.lattice[col-1][row].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //right border\n if(col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //upper border\n if(row > 0){\n this.agentController.ocean.lattice[col][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower border\n if(row < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col][row+1].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //upper left corner\n if(row > 0 && col > 0){\n this.agentController.ocean.lattice[col-1][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //upper right corner\n if(row > 0 && col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower left corner\n if(row < (100/ocean.latticeSize)-1 && col > 0){\n this.agentController.ocean.lattice[col-1][row+1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower right corner\n if(row < (100/ocean.latticeSize)-1 && col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row+1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //own cell\n this.agentController.ocean.lattice[col][row].forEach( (agent) => {\n res.push(agent);\n });\n return res;\n }",
"updateNeighborCounts () {\n // for each cell in the grid\n\t\tfor (var column = 0; column < this.numberOfColumns; column++) {\n for (var row = 0; row < this.numberOfRows; row++) {\n\n\t\t\t\t// reset it's neighbor count to 0\n this.cells[column][row].liveNeighborCount = 0;\n\n\t\t\t\t// get the cell's neighbors\n\t\t\t\tthis.getNeighbors(this.cells[column][row]);\n\n\t\t\t\t// increase liveNeighborCount by 1 for each neighbor that is alive\n\t\t\t\tfor (var i = 0; i < this.getNeighbors(this.cells[column][row]).length; i++){\n\t\t\t\t\tif (this.getNeighbors(this.cells[column][row])[i].isAlive == true){\n\t\t\t\t\t\tthis.cells[column][row].liveNeighborCount += 1;\n\t\t\t\t\t}\n\t\t\t\t}\n }\n }\n\t}",
"setupBoard() {\n for (let i = 0; i < this.columns; i++) {\n this.board[i] = [];\n\n for (let j = 0; j < this.rows; j++) {\n // Create new cell object for each location on board\n this.board[i][j] = new Cell(i * this.w, j * this.w, this.w);\n }\n }\n }",
"function initCellLookup()\n{\n // WE'LL PUT ALL THE VALUES IN HERE\n cellLookup = new Array();\n \n // TOP LEFT\n var topLeftArray = new Array( 1, 0, 1, 1, 0, 1);\n cellLookup[TOP_LEFT] = new CellType(3, topLeftArray);\n \n // TOP RIGHT\n var topRightArray = new Array(-1, 0, -1, 1, 0, 1);\n cellLookup[TOP_RIGHT] = new CellType(3, topRightArray);\n \n // BOTTOM LEFT\n var bottomLeftArray = new Array( 1, 0, 1, -1, 0, -1);\n cellLookup[BOTTOM_LEFT] = new CellType(3, bottomLeftArray);\n \n // BOTTOM RIGHT\n var bottomRightArray = new Array(-1, 0, -1, -1, 0, -1);\n cellLookup[BOTTOM_RIGHT]= new CellType(3, bottomRightArray);\n \n // TOP \n var topArray = new Array(-1, 0, -1, 1, 0, 1, 1, 1, 1, 0);\n cellLookup[TOP] = new CellType(5, topArray);\n \n // BOTTOM\n var bottomArray = new Array(-1, 0, -1, -1, 0, -1, 1, -1, 1, 0);\n cellLookup[BOTTOM] = new CellType(5, bottomArray);\n\n // LEFT\n var leftArray = new Array(0, -1, 1, -1, 1, 0, 1, 1, 0, 1);\n cellLookup[LEFT] = new CellType(5, leftArray);\n\n // RIGHT\n var rightArray = new Array(0, -1, -1, -1, -1, 0, -1, 1, 0, 1);\n cellLookup[RIGHT] = new CellType(5, rightArray);\n \n // CENTER\n var centerArray = new Array(-1, -1, -1, 0, -1, 1, 0, 1, 1, 1, 1, 0, 1, -1, 0, -1);\n cellLookup[CENTER] = new CellType(8, centerArray);\n}",
"GetNeighboringCellsWithWeights(x, y) {\n let output = [];\n let funcs = [ Math.floor, function(x) { return Math.floor(x) + 1; } ];\n\n x -= this.cell_size / 2.0;\n y -= this.cell_size / 2.0;\n\n x = Math.max(0, Math.min(this.window_size - this.cell_size, x));\n y = Math.max(0, Math.min(this.window_size - this.cell_size, y));\n\n for (let i = 0; i < 2; ++i) {\n let y_idx = this.ClipInRange(funcs[i](y / this.cell_size));\n let neighbor_y = y_idx * this.cell_size;\n let wy = 1.0 - Math.abs(y - neighbor_y) / this.cell_size;\n for (let j = 0; j < 2; ++j) {\n let x_idx = this.ClipInRange(funcs[j](x / this.cell_size));\n let neighbor_x = x_idx * this.cell_size;\n let wx = 1.0 - Math.abs(x - neighbor_x) / this.cell_size;\n output.push({x_idx : x_idx, y_idx : y_idx, weight : wx * wy});\n }\n }\n // Ensure that weights are normalized and sum to 1.\n let weight_sum = 0.0;\n for (let i = 0; i < output.length; ++i) {\n weight_sum += output[i].weight;\n }\n console.assert(weight_sum > 0.0);\n for (let i = 0; i < output.length; ++i) {\n output[i].weight /= weight_sum;\n }\n\n return output;\n }",
"static neighbours(q, r) {\n return [[q + 1, r], [q, r + 1], [q - 1, r], [q, r - 1], [q + 1, r - 1], [q - 1, r + 1]];\n }",
"function initCellArray() {\n var gridSize = getGridSize();\n cellArray = []\n for(var i = 0; i < gridSize; i++) {\n var gridRow = []\n for(var j = 0; j < gridSize; j++) {\n gridRow.push({\"free\": true, \"letter\": \"\"})\n }\n cellArray.push(gridRow)\n }\n }",
"function CellList(width, height, cellSize) {\n var api,\n colsNum,\n rowsNum,\n cellsNum,\n cell,\n init = function init() {\n var i;\n colsNum = Math.ceil(width / cellSize);\n rowsNum = Math.ceil(height / cellSize);\n cellsNum = colsNum * rowsNum;\n cell = new Array(cellsNum);\n\n for (i = 0; i < cellsNum; i++) {\n cell[i] = [];\n }\n };\n\n init(); // Public API.\n\n api = {\n reinitialize: function reinitialize(newWidth, newHeight, newCellSize) {\n var change = false;\n\n if (newWidth !== undefined) {\n if (newWidth !== width) {\n width = newWidth;\n change = true;\n }\n }\n\n if (newHeight !== undefined) {\n if (newHeight !== height) {\n height = newHeight;\n change = true;\n }\n }\n\n if (newCellSize !== undefined) {\n if (newCellSize !== cellSize) {\n cellSize = newCellSize;\n change = true;\n }\n }\n\n if (change) init();\n },\n addToCell: function addToCell(atomIdx, x, y) {\n var cellIdx = Math.floor(y / cellSize) * colsNum + Math.floor(x / cellSize);\n cell[cellIdx].push(atomIdx);\n },\n getCell: function getCell(idx) {\n return cell[idx];\n },\n getRowsNum: function getRowsNum() {\n return rowsNum;\n },\n getColsNum: function getColsNum() {\n return colsNum;\n },\n getNeighboringCells: function getNeighboringCells(rowIdx, colIdx) {\n var cellIdx = rowIdx * colsNum + colIdx,\n result = []; // Upper right.\n\n if (colIdx + 1 < colsNum && rowIdx + 1 < rowsNum) result.push(cell[cellIdx + colsNum + 1]); // Right.\n\n if (colIdx + 1 < colsNum) result.push(cell[cellIdx + 1]); // Bottom right.\n\n if (colIdx + 1 < colsNum && rowIdx - 1 >= 0) result.push(cell[cellIdx - colsNum + 1]); // Bottom.\n\n if (rowIdx - 1 >= 0) result.push(cell[cellIdx - colsNum]);\n return result;\n },\n clear: function clear() {\n var i;\n\n for (i = 0; i < cellsNum; i++) {\n cell[i].length = 0;\n }\n }\n };\n return api;\n}",
"function CellRange() {\r\n this.p0 = new Vec2d();\r\n this.p1 = new Vec2d();\r\n this.reset();\r\n}",
"generateCells(){\n for(let row = 0; row<this.rows; row++){\n this.cells[row] = []\n for(let column = 0; column<this.columns; column++){\n this.cells[row][column] = new Cell({column, row, height: this.cellSize, width: this.cellSize})\n this.cells[row][column].showBlocked()\n }\n }\n }",
"function countNeighbors(board){\n var nCount = createEmptyMatrix(board.length);\n\n for(var i = 0; i < board.length; i++) {\n for (var j = 0; j < board.length; j++) {\n //increment all the neighboring indexes within bounds\n if(board[i][j] == 1) {\n\n if (i > 0) {\n if(j > 0) {\n nCount[i - 1][j - 1]++;\n }\n nCount[i - 1][j]++;\n if(j < nCount.length-1) {\n nCount[i - 1][j + 1]++;\n }\n }\n\n if(j > 0) {\n nCount[i][j - 1]++;\n }\n if(j < nCount.length-1) {\n nCount[i][j + 1]++;\n }\n\n if(i < nCount.length-1) {\n if(j > 0) {\n nCount[i + 1][j - 1]++;\n }\n nCount[i + 1][j]++;\n if(j < nCount.length-1) {\n nCount[i + 1][j + 1]++;\n }\n }\n\n\n }\n }\n }\n\n return nCount;\n}",
"findNeighbours(){\n \t// Array of all free directions. Starts with all directions\n\tvar freeDirections = [0,1,2,3,4,5,6,7];\n\t// First, define the eight neighbouring locations\n\tvar neighN = this.pos.copy().add(createVector(0,-1));\n\tvar neighS = this.pos.copy().add(createVector(0, 1));\n\tvar neighE = this.pos.copy().add(createVector( 1,0));\n\tvar neighW = this.pos.copy().add(createVector(-1,0));\n\tvar neighNE = this.pos.copy().add(createVector(1, -1));\n\tvar neighSE = this.pos.copy().add(createVector(1, 1));\n\tvar neighNW = this.pos.copy().add(createVector(-1,-1));\n\tvar neighSW = this.pos.copy().add(createVector(-1,1));\n\t\n\t// Make a dictionary, for translating direction-number into location\n\tvar directionDict ={};\n\tdirectionDict[0] = neighN;\n\tdirectionDict[1] = neighS;\n\tdirectionDict[2] = neighE;\n\tdirectionDict[3] = neighW;\n\tdirectionDict[4] = neighNE;\n\tdirectionDict[5] = neighSE;\n\tdirectionDict[6] = neighNW;\n\tdirectionDict[7] = neighSW;\n\t\n\t// Check if the directions are in the occuPos dictionary\n\t// And remove it from the \"freeDirections\" vector if it is\n\tif (occuPos.hasKey(posToDictKey(neighN.x,neighN.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 0){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\tif (occuPos.hasKey(posToDictKey(neighS.x,neighS.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 1){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighE.x,neighE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 2){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighW.x,neighW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 3){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighNE.x,neighNE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 4){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighSE.x,neighSE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 5){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighNW.x,neighNW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 6){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighSW.x,neighSW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 7){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Return the vector of free directions and the dictionary for translating the vector \n\treturn [freeDirections,directionDict];\n }",
"function updateUnvisitedNeighbors(n, grid) {\n const neighbors = addUnvisitedNeighbors(n, grid)\n for (const neighbor of neighbors) {\n neighbor.distance = n.distance + neighbor.weight\n neighbor.prev = n\n }\n}",
"function setMinesNegsCount(board) {\r\n var currSize = gLevels[gChosenLevelIdx].SIZE;\r\n for (var i = 0; i < currSize; i++) {\r\n for (var j = 0; j < currSize; j++) {\r\n var cell = board[i][j];\r\n var count = calculateNegs(board, i, j)\r\n cell.minesAroundCount = count;\r\n }\r\n }\r\n\r\n\r\n}",
"function make3dIndex(cellSide, xsize, ysize) {\n var index = this;\n \n index.side = cellSide;\n index.xsize = xsize;\n index.ysize = ysize;\n index.ycoeff = 2*index.xsize;\n index.zcoeff = 4*index.xsize*index.ysize;\n index.k = 1/index.side;\n index.cells = {};\n index.objectCache = {};\n index.indexCache = {};\n index.neighbourCache = {};\n index.neighbourhood = new Int32Array([\n 0,0,0,\n 0,0,1,\n 1,0,1,\n -1,0,1,\n 0,1,1,\n 0,-1,1,\n 1,1,1,\n 1,-1,1,\n -1,1,1,\n -1,-1,1,\n 1,0,0,\n -1,0,0,\n 0,1,0,\n 0,-1,0,\n 1,1,0,\n 1,-1,0,\n -1,1,0,\n -1,-1,0,\n 0,0,-1,\n 1,0,-1,\n -1,0,-1,\n 0,1,-1,\n 0,-1,-1,\n 1,1,-1,\n 1,-1,-1,\n -1,1,-1,\n -1,-1,-1\n ]);\n \n return index;\n}",
"function create_cell_list( maze ) {\n\t\tlet result = {\n\t\t\tx_max:Math.floor(maze[0].length /2),\n\t\t\ty_max:Math.floor(maze.length/2),\n\t\t\tdata:[],\n\t\t\t/*\n\t\t\t * Determines if a position of a sprite, which is\n\t\t\t * given by the x,y pair of input parameters is valid.\n\t\t\t * A position is valid if it either positions a sprite\n\t\t\t * entirely in a cell, or if the sprite is positioned \n\t\t\t * in more than one cell, then those cells should not\n\t\t\t * have a border between them according to the cell\n\t\t\t * data. It is assumed that the width and height of\n\t\t\t * the cell is the same as the width and height of\n\t\t\t * the sprite, namely 64.\n\t\t\t *\n\t\t\t * Deterimining is a position is valid works as\n\t\t\t * follows:\n\t\t\t *\n\t\t\t * 1. Find the cell where the x,y position is\n\t\t\t * located:\n\t\t\t * \tcell_x = x div 64\n\t\t\t * \tcell_y = y div 64\n\t\t\t * \tcell = data[ cell_y * x_max + cell_x ]\n\t\t\t * 2. Check if either the x position is at the left hand\n\t\t\t * side of the cell or if it is not that the cell has\n\t\t\t * no right border.\n\t\t\t * x_pos = x mod 64\n\t\t\t * if x_pos != 0:\n\t\t\t * \t!cell.right\n\t\t\t * 3. Check if either y position is at the top of the\n\t\t\t * cell or, if it is not, that the cell has no\n\t\t\t * bottom border.\n\t\t\t * y_pos = y mod 64\n\t\t\t * if y_pos != 0:\n\t\t\t * \t!cell.bottom\n\t\t\t * 4. Return true if both checks (2 and 3 ) pass, and\n\t\t\t * false if at least one of them fails.\n\t\t\t *\n\t\t\t * @param x The x position of the top left corner of the \n\t\t\t * sprite on the screen.\n\t\t\t * @param y The y position of the top left corner of the\n\t\t\t * sprite on the screen.\n\t\t\t *\n\t\t\t * @return True if the position of the sprite is valid \n\t\t\t * according to the above rules, and False, if \n\t\t\t * the position is not valid.\n\t\t\t */ \n\t\t\tis_valid_position:function(x,y) {\n\t\t\t\tlet result = ( x>=0 ) && (y>=0);\n\t\t\t\tif( result ){\n\t\t\t\t\tlet cell_x = Math.floor( x/64);\n\t\t\t\t\tlet cell_y = Math.floor( y/64);\n\t\t\t\t\tlet cur_cell = this.data[ cell_y*this.x_max + cell_x];\n\t\t\t\t\n\t\t\t\t\tlet x_pos = x%64;\n\t\t\t\t\tif( x_pos != 0 ) {\n\t\t\t\t\t\tresult = !cur_cell.right;\n\t\t\t\t\t}\n\t\t\t\t\tif( result ){\n\t\t\t\t\t\tlet y_pos = y%64;\n\t\t\t\t\t\tif( y_pos != 0 ){\n\t\t\t\t\t\t\tresult = !cur_cell.bottom;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t};\n\n\t\tfor( j=0; j<result.y_max; j++ ) {\n\t\t\tfor( i=0; i<result.x_max; i++ ){\n\t\t\t\tresult.data.push( init_cell(create_cell(), i, j, maze) );\n\t\t\t};\n\t\t};\n\t\treturn result;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
home/admin/funfuzz/js/jsfunfuzz/messtokens.js Each input to |cat| should be a token or so, OR a bigger logical piece (such as a call to makeExpr). Smaller than a token is ok too ;) When "torture" is true, it may do any of the following: skip a token skip all the tokens to the left skip all the tokens to the right insert unterminated comments insert line breaks insert entire expressions insert any token Even when not in "torture" mode, it may sneak in extra line breaks. Why did I decide to toString at every step, instead of making larger and larger arrays (or more and more deeply nested arrays?). no particular reason. | function cat(toks)
{
if (rnd(1700) === 0)
return totallyRandom(2, ["x"]);
var torture = (rnd(1700) === 57);
if (torture)
dumpln("Torture!!!");
var s = maybeLineBreak();
for (var i = 0; i < toks.length; ++i) {
// Catch bugs in the fuzzer. An easy mistake is
// return /*foo*/ + ...
// instead of
// return "/*foo*/" + ...
// Unary plus in the first one coerces the string that follows to number!
if (typeof(toks[i]) != "string") {
dumpln("Strange item in the array passed to cat: typeof toks[" + i + "] == " + typeof(toks[i]));
dumpln(cat.caller);
dumpln(cat.caller.caller);
}
if (!(torture && rnd(12) === 0))
s += toks[i];
s += maybeLineBreak();
if (torture) switch(rnd(120)) {
case 0:
case 1:
case 2:
case 3:
case 4:
s += maybeSpace() + totallyRandom(2, ["x"]) + maybeSpace();
break;
case 5:
s = "(" + s + ")"; // randomly parenthesize some *prefix* of it.
break;
case 6:
s = ""; // throw away everything before this point
break;
case 7:
return s; // throw away everything after this point
case 8:
s += UNTERMINATED_COMMENT;
break;
case 9:
s += UNTERMINATED_STRING_LITERAL;
break;
case 10:
if (rnd(2))
s += "(";
s += UNTERMINATED_REGEXP_LITERAL;
break;
default:
}
}
return s;
} | [
"function fuzz () {\n let len = 10\n let alpha = 'abcdfghijk'\n for (let v = 0; v < len; v++) {\n for (let w = 0; w < len; w++) {\n for (let x = 0; x < len; x++) {\n for (let y = 0; y < len; y++) {\n for (let z = 0; z < len; z++) {\n let str = [alpha[v], alpha[w], alpha[x], alpha[y], alpha[z]].join('')\n let tree = STree.create(str)\n testSuffixes(tree, str)\n }\n }\n }\n }\n }\n console.log('all ok')\n}",
"function getTokens(characters){\n var tokenPointer = 0;\n while (tokenPointer < characters.length){\n if (characters[tokenPointer] == \" \") {\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"-\") {\n tokens.push(\"neg\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"*\") {\n tokens.push(\"and\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"V\") {\n tokens.push(\"or\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"(\" || characters[tokenPointer] == \"[\") {\n if (tokenPointer+4<characters.length && characters[tokenPointer+1]==\"U\"\n && characters[tokenPointer+2]==\"Q\" && characters[tokenPointer+3]\n != characters[tokenPointer+3].toUpperCase() && characters[tokenPointer+4] == \")\"){\n tokens.push(\"uq\");\n tokenPointer += 5;\n }\n else if (tokenPointer+4<characters.length && characters[tokenPointer+1]==\"E\"\n && characters[tokenPointer+2]==\"Q\" && characters[tokenPointer+3]\n != characters[tokenPointer+3].toUpperCase() && characters[tokenPointer+4] == \")\"){\n tokens.push(\"eq\");\n tokenPointer += 5;\n }\n else {\n tokens.push(\"lp\")\n tokenPointer+=1\n }\n }\n else if (characters[tokenPointer] == \")\" || characters[tokenPointer] == \"]\") {\n tokens.push(\"rp\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] != characters[tokenPointer].toLowerCase()) {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]\n != characters[tokenPointer+1].toUpperCase()){\n tokens.push(\"pred\");\n tokenPointer += 1;\n while(tokenPointer<characters.length && characters[tokenPointer]\n != characters[tokenPointer].toUpperCase()){\n tokenPointer+=1;\n }\n }\n else {\n tokens.push(\"error\");\n break;\n }\n }\n else if (characters[tokenPointer] != characters[tokenPointer].toUpperCase()){\n tokens.push(\"sentLet\");\n tokenPointer+= 1;\n }\n else if (characters[tokenPointer] == \"<\") {\n if(tokenPointer+2<characters.length && characters[tokenPointer+1]==\"=\"\n && characters[tokenPointer+2]==\">\"){\n tokens.push(\"bicond\");\n tokenPointer += 3;\n }\n }\n else if (characters[tokenPointer] == \"=\") {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]==\">\"){\n tokens.push(\"cond\");\n tokenPointer += 2;\n }\n else {\n tokens.push(\"eqOp\");\n tokenPointer += 1;\n }\n }\n else if (characters[tokenPointer] == \"!\") {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]==\"=\"){\n tokens.push(\"notEqOp\");\n tokenPointer += 2;\n }\n else{\n tokens.push(\"error\");\n break;\n }\n }\n else {\n tokens.push(\"error\");\n break;\n }\n }\n}",
"function gencases( delimiters, maxHighWaterMark ) {\n\n function tc( delimiter, hwm ) {\n return {\n delimiter: delimiter,\n // highWaterMark causes source data buffers to be varying lengths, ensuring\n // that some buffers will have many lines, that some lines will be split across buffers,\n // and for low hwm, single lines will arrive in many separate buffers.\n // Tests that incomplete line chunks are correctly stored until a delimiter arrives.\n sourceOpts: { highWaterMark: hwm }\n }\n }\n\n let cases = [];\n\n delimiters.forEach( function(delimiter) {\n cases.push( tc( delimiter, 1024 * 16 ) );\n if( maxHighWaterMark == 1 ) return;\n cases.push( tc( delimiter, 1000 ));\n for( let i = 1; i < maxHighWaterMark; ++i ) {\n cases.push( tc( delimiter, i ));\n }\n });\n return cases;\n}",
"function makeTestTrials() {\n \n var pr = []; pc = [];\n if (debugging) {\n pr = [0,1,2,3];\n pc = [0];\n pr = shuffleArray(pr);\n } else {\n pr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33];\n pc = [0,1,2,3,4,5,6,7];\n pr = shuffleArray(pr);\n pc = shuffleArray(pc);\n }\n \n // if debugging just have one test trial of each type\n if (debugging) {\n \n // one pattern recognition item with one foil\n patternrecogTarget[pr[0]] = hardtriplets[0]; \n patternrecogFoilsone[pr[0]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogFoilstwo[pr[0]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[0]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n // one pattern recognition item with three foils\n patternrecogTarget[pr[1]] = hardtriplets[1]; \n patternrecogFoilsone[pr[1]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogFoilstwo[pr[1]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogFoilsthree[pr[1]] = [stimset[0], stimset[1], stimset[3]];\n // one item with only pairs, and one other answer option \n patternrecogTarget[pr[2]] = [stimset[1], stimset[2],\"white.jpg\"];\n patternrecogFoilsone[pr[2]] = [stimset[0], stimset[15],\"white.jpg\"];\n patternrecogFoilstwo[pr[2]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[2]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n // now items with only pairs, and three other answer options \n patternrecogTarget[pr[3]] = [stimset[11], stimset[12],\"white.jpg\"];\n patternrecogFoilsone[pr[3]] = [stimset[5], stimset[10],\"white.jpg\"];\n patternrecogFoilstwo[pr[3]] = [stimset[11], stimset[14],\"white.jpg\"];\n patternrecogFoilsthree[pr[3]] = [stimset[8], stimset[3],\"white.jpg\"]; \n // give them names for easy reference (here in debugging these are meaningless)\n for (var i=0; i<pr.length; i++) {\n testitems[pr[i]] = i+1;\n }\n // now a pattern completion item. first item in foils array is always the target\n patterncompletionQuestion[0] = [stimset[0], \"blank.jpg\", stimset[2]];\n patterncompletionFoils[0] = [stimset[1], stimset[12], stimset[8]]\n testitems[pr.length] = 0; \n \n // if not debugging have all test items \n } else {\n // first set up the pattern recognition items with one foil\n patternrecogTarget[pr[0]] = hardtriplets[0]; \n patternrecogFoilsone[pr[0]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogTarget[pr[1]] = hardtriplets[1]; \n patternrecogFoilsone[pr[1]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogTarget[pr[2]] = hardtriplets[2]; \n patternrecogFoilsone[pr[2]] = [stimset[3], stimset[2], stimset[8]];\n patternrecogTarget[pr[3]] = hardtriplets[3]; \n patternrecogFoilsone[pr[3]] = [stimset[6], stimset[0], stimset[2]];\n patternrecogTarget[pr[4]] = easytriplets[0]; \n patternrecogFoilsone[pr[4]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogTarget[pr[5]] = easytriplets[1]; \n patternrecogFoilsone[pr[5]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogTarget[pr[6]] = easytriplets[2]; \n patternrecogFoilsone[pr[6]] = [stimset[13], stimset[5], stimset[9]];\n patternrecogTarget[pr[7]] = easytriplets[3]; \n patternrecogFoilsone[pr[7]] = [stimset[2], stimset[0], stimset[14]];\n patternrecogTarget[pr[8]] = hardtriplets[0]; \n patternrecogFoilsone[pr[8]] = [stimset[14], stimset[0], stimset[3]];\n patternrecogTarget[pr[9]] = hardtriplets[1]; \n patternrecogFoilsone[pr[9]] = [stimset[13], stimset[5], stimset[9]];\n patternrecogTarget[pr[10]] = hardtriplets[2]; \n patternrecogFoilsone[pr[10]] = [stimset[1], stimset[7], stimset[3]];\n patternrecogTarget[pr[11]] = hardtriplets[3]; \n patternrecogFoilsone[pr[11]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogTarget[pr[12]] = easytriplets[0]; \n patternrecogFoilsone[pr[12]] = [stimset[13], stimset[2], stimset[1]];\n patternrecogTarget[pr[13]] = easytriplets[1]; \n patternrecogFoilsone[pr[13]] = [stimset[4], stimset[11], stimset[12]];\n patternrecogTarget[pr[14]] = easytriplets[2]; \n patternrecogFoilsone[pr[14]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogTarget[pr[15]] = easytriplets[3]; \n patternrecogFoilsone[pr[15]] = [stimset[15], stimset[6], stimset[9]];\n for (var i=0; i<16; i++) {\n patternrecogFoilstwo[pr[i]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[i]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n }\n\n // now set up the pattern recognition items with three foils \n patternrecogTarget[pr[16]] = hardtriplets[0]; \n patternrecogFoilsone[pr[16]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogFoilstwo[pr[16]] = [stimset[1], stimset[7], stimset[3]];\n patternrecogFoilsthree[pr[16]] = [stimset[13], stimset[2], stimset[1]];\n patternrecogTarget[pr[17]] = hardtriplets[1]; \n patternrecogFoilsone[pr[17]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogFoilstwo[pr[17]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogFoilsthree[pr[17]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogTarget[pr[18]] = hardtriplets[2]; \n patternrecogFoilsone[pr[18]] = [stimset[15], stimset[6], stimset[9]];\n patternrecogFoilstwo[pr[18]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogFoilsthree[pr[18]] = [stimset[1], stimset[7], stimset[3]];\n patternrecogTarget[pr[19]] = hardtriplets[3]; \n patternrecogFoilsone[pr[19]] = [stimset[4], stimset[11], stimset[12]];\n patternrecogFoilstwo[pr[19]] = [stimset[14], stimset[0], stimset[3]];\n patternrecogFoilsthree[pr[19]] = [stimset[2], stimset[0], stimset[14]];\n patternrecogTarget[pr[20]] = easytriplets[0]; \n patternrecogFoilsone[pr[20]] = [stimset[15], stimset[6], stimset[9]];\n patternrecogFoilstwo[pr[20]] = [stimset[13], stimset[5], stimset[9]];\n patternrecogFoilsthree[pr[20]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogTarget[pr[21]] = easytriplets[1]; \n patternrecogFoilsone[pr[21]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogFoilstwo[pr[21]] = [stimset[3], stimset[2], stimset[8]];\n patternrecogFoilsthree[pr[21]] = [stimset[14], stimset[0], stimset[3]];\n patternrecogTarget[pr[22]] = easytriplets[2]; \n patternrecogFoilsone[pr[22]] = [stimset[13], stimset[2], stimset[1]];\n patternrecogFoilstwo[pr[22]] = [stimset[6], stimset[0], stimset[2]];\n patternrecogFoilsthree[pr[22]] = [stimset[2], stimset[0], stimset[14]];\n patternrecogTarget[pr[23]] = easytriplets[3]; \n patternrecogFoilsone[pr[23]] = [stimset[4], stimset[11], stimset[12]];\n patternrecogFoilstwo[pr[23]] = [stimset[3], stimset[2], stimset[8]];\n patternrecogFoilsthree[pr[23]] = [stimset[6], stimset[0], stimset[2]];\n \n // now items with only pairs, and one other answer option \n patternrecogTarget[pr[24]] = [stimset[1], stimset[2],\"white.jpg\"];\n patternrecogFoilsone[pr[24]] = [stimset[0], stimset[15],\"white.jpg\"];\n patternrecogTarget[pr[25]] = [stimset[0], stimset[3],\"white.jpg\"];\n patternrecogFoilsone[pr[25]] = [stimset[1], stimset[3],\"white.jpg\"];\n patternrecogTarget[pr[26]] = [stimset[2], stimset[0],\"white.jpg\"];\n patternrecogFoilsone[pr[26]] = [stimset[5], stimset[2],\"white.jpg\"];\n patternrecogTarget[pr[27]] = [stimset[3], stimset[1],\"white.jpg\"];\n patternrecogFoilsone[pr[27]] = [stimset[12], stimset[1],\"white.jpg\"];\n patternrecogTarget[pr[28]] = [stimset[5], stimset[6],\"white.jpg\"];\n patternrecogFoilsone[pr[28]] = [stimset[4], stimset[10],\"white.jpg\"];\n patternrecogTarget[pr[29]] = [stimset[7], stimset[8],\"white.jpg\"];\n patternrecogFoilsone[pr[29]] = [stimset[2], stimset[13],\"white.jpg\"];\n for (var i=24; i<30; i++) {\n patternrecogFoilstwo[pr[i]] = [\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[i]] = [\"white.jpg\",\"white.jpg\"];\n } \n \n // now items with only pairs, and three other answer options \n patternrecogTarget[pr[30]] = [stimset[11], stimset[12],\"white.jpg\"];\n patternrecogFoilsone[pr[30]] = [stimset[5], stimset[10],\"white.jpg\"];\n patternrecogFoilstwo[pr[30]] = [stimset[11], stimset[14],\"white.jpg\"];\n patternrecogFoilsthree[pr[30]] = [stimset[8], stimset[3],\"white.jpg\"];\n patternrecogTarget[pr[31]] = [stimset[13], stimset[14],\"white.jpg\"];\n patternrecogFoilsone[pr[31]] = [stimset[7], stimset[9],\"white.jpg\"];\n patternrecogFoilstwo[pr[31]] = [stimset[0], stimset[7],\"white.jpg\"];\n patternrecogFoilsthree[pr[31]] = [stimset[14], stimset[6],\"white.jpg\"];\n patternrecogTarget[pr[32]] = [stimset[0], stimset[1],\"white.jpg\"];\n patternrecogFoilsone[pr[32]] = [stimset[6], stimset[0],\"white.jpg\"];\n patternrecogFoilstwo[pr[32]] = [stimset[2], stimset[13],\"white.jpg\"];\n patternrecogFoilsthree[pr[32]] = [stimset[12], stimset[4],\"white.jpg\"];\n patternrecogTarget[pr[33]] = [stimset[3], stimset[2],\"white.jpg\"];\n patternrecogFoilsone[pr[33]] = [stimset[8], stimset[1],\"white.jpg\"];\n patternrecogFoilstwo[pr[33]] = [stimset[9], stimset[3],\"white.jpg\"];\n patternrecogFoilsthree[pr[33]] = [stimset[15], stimset[11],\"white.jpg\"];\n \n // give them the name as in the paper for easy reference\n for (var i=0; i<pr.length; i++) {\n testitems[pr[i]] = i+1;\n }\n for (var i=0; i<pc.length; i++) {\n testitems[pr.length+pc[i]] = 35+i;\n }\n \n // now the pattern completion items\n patterncompletionQuestion[pc[0]] = [stimset[0], \"blank.jpg\", stimset[2]];\n patterncompletionFoils[pc[0]] = [stimset[1], stimset[12], stimset[8]]\n patterncompletionQuestion[pc[1]] = [stimset[1], stimset[0], \"blank.jpg\"];\n patterncompletionFoils[pc[1]] = [stimset[3], stimset[5], stimset[15]]\n patterncompletionQuestion[pc[2]] = [\"blank.jpg\", stimset[5], stimset[6]];\n patterncompletionFoils[pc[2]] = [stimset[4], stimset[13], stimset[2]]\n patterncompletionQuestion[pc[3]] = [stimset[7], \"blank.jpg\", stimset[9]];\n patterncompletionFoils[pc[3]] = [stimset[8], stimset[14], stimset[3]]\n patterncompletionQuestion[pc[4]] = [stimset[10], \"blank.jpg\", \"white.jpg\"];\n patterncompletionFoils[pc[4]] = [stimset[11], stimset[6], stimset[0]];\n patterncompletionQuestion[pc[5]] = [\"blank.jpg\", stimset[14], \"white.jpg\"];\n patterncompletionFoils[pc[5]] = [stimset[13], stimset[7], stimset[11]];\n patterncompletionQuestion[pc[6]] = [stimset[2], \"blank.jpg\", \"white.jpg\"];\n patterncompletionFoils[pc[6]] = [stimset[0], stimset[1], stimset[4]];\n patterncompletionQuestion[pc[7]] = [\"blank.jpg\", stimset[3], \"white.jpg\"];\n patterncompletionFoils[pc[7]] = [stimset[2], stimset[10], stimset[9]];\n }\n\n}",
"function analyze_js(input, start, argPos) {\r\n\t\t\r\n\t// Set up starting variables\r\n\tvar currentArg\t\t= 1;\t\t\t\t // Only used if extracting argument position\r\n\tvar i\t\t\t\t\t= start;\t\t\t // Current character position\r\n\tvar length\t\t\t= input.length; // Length of document\r\n\tvar end\t\t\t\t= false;\t\t\t // Have we found the end?\r\n\tvar openObjects\t= 0;\t\t\t\t // Number of objects currently open\r\n\tvar openBrackets\t= 0;\t\t\t\t // Number of brackets currently open\r\n\tvar openArrays\t\t= 0;\t\t\t\t // Number of arrays currently open\r\n\t\r\n\t// Loop through input char by char\r\n\twhile ( end === false && i < length ) {\r\n\t\r\n\t\t// Extract current char\r\n\t\tvar currentChar = input.charAt(i);\r\n\t\r\n\t\t// Examine current char\r\n\t\tswitch ( currentChar ) {\r\n\t\t\r\n\t\t\t// String syntax\r\n\t\t\tcase '\"':\r\n\t\t\tcase \"'\":\r\n\t\t\t\r\n\t\t\t\t// Move up to the corresponding end of string position, taking\r\n\t\t\t\t// into account and escaping backslashes\r\n\t\t\t\twhile ( ( i = strpos(input, currentChar, i+1) ) && input.charAt(i-1) == '\\\\' );\r\n\t\t\t\r\n\t\t\t\t// False? Closing string delimiter not found... assume end of document \r\n\t\t\t\t// although technically we've screwed up (or the syntax is invalid)\r\n\t\t\t\tif ( i === false ) {\r\n\t\t\t\t\tend = length;\r\n\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\r\n\t\t\r\n\t\t\t// End of operation\r\n\t\t\tcase ';':\r\n\t\t\t\tend = i;\r\n\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t// Newlines\r\n\t\t\tcase \"\\n\":\r\n\t\t\tcase \"\\r\":\r\n\t\t\t\t\r\n\t\t\t\t// Newlines are ignored if we have an open bracket or array or object\r\n\t\t\t\tif ( openObjects || openBrackets || openArrays || argPos ) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\t// Newlines are also OK if followed by an opening function OR concatenation\r\n\t\t\t\t// e.g. someFunc\\n(params) or someVar \\n + anotherVar\r\n\t\t\t\t// Find next non-whitespace char position\r\n\t\t\t\tvar nextCharPos = i + strspn(input, \" \\t\\r\\n\", i+1) + 1;\r\n\t\t\t\t\r\n\t\t\t\t// And the char that refers to\r\n\t\t\t\tvar nextChar = input.charAt(nextCharPos);\r\n\t\t\t\t\r\n\t\t\t\t// Ensure not end of document and if not, char is allowed\r\n\t\t\t\tif ( nextCharPos <= length && ( nextChar == '(' || nextChar == '+' ) ) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Move up offset to our nextChar position and ignore this newline\r\n\t\t\t\t\ti = nextCharPos;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Still here? Newline not OK, set end to this position\r\n\t\t\t\tend = i;\r\n\t\t\t\tbreak;\r\n\r\n\r\n\t\t\t// Concatenation\r\n\t\t\tcase '+':\r\n\t\t\t\t// Our interest in the + operator is it's use in allowing an expression\r\n\t\t\t\t// to span multiple lines. If we come across a +, move past all whitespace,\r\n\t\t\t\t// including newlines (which would otherwise indicate end of expression).\r\n\t\t\t\ti += strspn(input, \" \\t\\r\\n\", i+1);\r\n\t\t\t\tbreak;\r\n\r\n\r\n\t\t\t// Opening chars (objects, parenthesis and arrays)\r\n\t\t\tcase '{':\r\n\t\t\t\t++openObjects;\r\n\t\t\t\tbreak;\r\n\t\t\tcase '(':\r\n\t\t\t\t++openBrackets;\r\n\t\t\t\tbreak;\r\n\t\t\tcase '[':\r\n\t\t\t\t++openArrays;\r\n\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t// Closing chars - is there a corresponding open char? \r\n\t\t\t// Yes = reduce stored count. No = end of statement.\r\n\t\t\tcase '}':\r\n\t\t\t\topenObjects\t ? --openObjects\t : end = i;\r\n\t\t\t\tbreak;\r\n\t\t\tcase ')':\r\n\t\t\t\topenBrackets ? --openBrackets : end = i;\r\n\t\t\t\tbreak;\r\n\t\t\tcase ']':\r\n\t\t\t\topenArrays\t ? --openArrays\t : end = i;\r\n\t\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t// Comma\r\n\t\t\tcase ',':\r\n\t\t\t\r\n\t\t\t\t// No interest here if not looking for argPos\r\n\t\t\t\tif ( ! argPos ) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Ignore commas inside other functions or whatnot\r\n\t\t\t\tif ( openObjects || openBrackets || openArrays ) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// End now\r\n\t\t\t\tif ( currentArg == argPos ) {\r\n\t\t\t\t\tend = i;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Increase the current argument number\r\n\t\t\t\t++currentArg;\r\n\t\t\t\t\r\n\t\t\t\t// If we're not after the first arg, start now?\r\n\t\t\t\tif ( currentArg == argPos ) {\r\n\t\t\t\t\tvar start = i+1;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t// Any other characters\r\n\t\t\tdefault:\r\n\t\t\t\t// Do nothing\r\n\t\t}\r\n\t\t\r\n\t\t// Increase offset\r\n\t\t++i;\r\n\t\r\n\t}\r\n\t\r\n\t// End not found? Use end of document\r\n\tif ( end === false ) {\r\n\t\tend = length;\r\n\t}\r\n\r\n\t// Return array of start/end if looking for argPos\r\n\tif ( argPos ) {\r\n\t\treturn [start, end];\r\n\t}\r\n\t\r\n\t// Return end\r\n\treturn end;\r\n\t\r\n}",
"function diffuseBomb(input){\n let params = {\n white: ['purple', 'green', 'red', 'orange'],\n red: ['green'],\n black: ['red','black','purple'],\n orange: ['red','black'],\n green: ['orange', 'white'],\n purple: ['black','red']\n };\n function lookAtWire(cut){\n let [current, next] = cut;\n return !next || params[current].includes(next) && diffuseBomb(cut.slice(1));\n }\n return lookAtWire(input.split('\\n')) ? \"Diffused\" : \"Boom\";\n}",
"visitSmall_stmt(ctx) {\r\n console.log(\"visitSmall_stmt\");\r\n if (ctx.expr_stmt() !== null) {\r\n return this.visit(ctx.expr_stmt());\r\n } else if (ctx.del_stmt() !== null) {\r\n return this.visit(ctx.del_stmt());\r\n } else if (ctx.pass_stmt() !== null) {\r\n return this.visit(ctx.pass_stmt());\r\n } else if (ctx.flow_stmt() !== null) {\r\n return this.visit(ctx.flow_stmt());\r\n } else if (ctx.import_stmt() !== null) {\r\n return this.visit(ctx.import_stmt());\r\n } else if (ctx.global_stmt() !== null) {\r\n return this.visit(ctx.global_stmt());\r\n } else if (ctx.nonlocal_stmt() !== null) {\r\n return this.visit(ctx.nonlocal_stmt());\r\n } else if (ctx.assert_stmt() !== null) {\r\n return this.visit(ctx.assert_stmt());\r\n }\r\n }",
"function testClumps() {\n const { parameters } = tests.exercises.find((exercise) => {\n return exercise.name === \"clumps\";\n });\n\n let tc = 0;\n let pass = 0;\n for (const values of parameters[0].values) {\n const functionCall = `clumps(${format(values)})`;\n const expected = staff.clumps(values);\n const actual = student.clumps(values);\n\n if (expected !== actual) {\n console.log(`Test Case ${tc + 1} -- Fail.`);\n console.log(` - call: ${functionCall}`);\n console.log(` - expected: ${expected}`);\n console.log(` - actual: ${actual}\\n`);\n } else {\n pass++;\n }\n\n tc++;\n }\n console.log(`clumps -- passed ${pass} out of ${tc} test cases.`);\n}",
"visitTestlist_star_expr(ctx) {\r\n console.log(\"visitTestlist_star_expr\");\r\n let length = ctx.getChildCount();\r\n if (length === 1) {\r\n if (ctx.test() !== null) {\r\n return this.visit(ctx.test(0));\r\n } else {\r\n return this.visit(ctx.star_expr(0));\r\n }\r\n } else {\r\n let valuelist = [this.visit(ctx.getChild(0))];\r\n for (var i = 1; i < length; i++) {\r\n if (ctx.getChild(i).getText() !== \",\") {\r\n valuelist.push(this.visit(ctx.getChild(i)));\r\n }\r\n }\r\n return { type: \"TestListStarExpression\", value: valuelist };\r\n }\r\n }",
"_generate(ast) {}",
"function test39() {\t\n\t// Example where N is 3 and M is not specified.\n\t\n\t// Universe M Universe of N dimensions \n\t// / \\ ... other dimensions ...\n\t// 1 8 dimension 1 has Two measurements [1, 8]\n\t// / \\ / \\ ... other dimensions ...\n\t// 2 3 9 10 dimension 2 has Four measurements [ [2, 3] [9, 10] ] \n\t// /\\ /\\ /\\ /\\ ... other dimensions ... \n\t// 4 5 6 7 11 12 13 14 dimension 3 has Eight measurements [ [ [4,5] [6, 7] ] [ [11, 12] [13, 14] ] ]\n\t\n\t// This tree has been copyrighted, just kidding.\n\t//\n\n\t// *****First measurments** ***** Last measurements**** \n\t// hop1[0] == 1 hop1[1] == 8\n\t// hop2[0][0] == 2 hop2[1][1] == 10\n\t// hop3[0][0][0] == 4 hop3[1][1][1] == 14\n\t\n\t// treeGator = new TreeGator([hop1, hop2, hop3])\n\t// measure(treeGator[0][0]) == 1\n\t// measure(treeGator[1][0][0]) == 2\n\t// measure(treeGator[2][0][0][0]) == 4\n var div = document.createElement('div');\n div.innerHTML =\t\"<div>Universe M\" + \n\t\" <otherdimension1>\" + \n\t\" <dimension1>1 \" + \n\t\" <otherdimension2>\" + \n\t\"\t <dimension2>2 \" + \n\t\"\t <otherdimension3>\" + \n\t\"\t\t <dimension3>4</dimension3> \" + \n\t\"\t\t <dimension3>5</dimension3>\" + \n\t\"\t\t </otherdimension3>\" + \n\t\"\t\t </dimension2> \" + \n\t\"\t <dimension2>3\" + \n\t\"\t <otherdimension4>\" + \n\t\"\t\t <span dizid=dimension3>6</span>\" + \n\t\"\t\t <span dizid=dimension3>7</span>\" + \n\t\"\t\t </otherdimension4>\" + \n\t\"\t </dimension2>\" + \n\t\"\t </otherdimension2>\" + \n\t\" </dimension1>\" + \n\t\" <dimension1>8 \" + \n\t\"\t <dimension2>9 \" + \n\t\"\t\t <dimension3>11</dimension3> \" + \n\t\"\t\t <dimension3>12</dimension3></dimension2> \" + \n\t\"\t <dimension2>10\" + \n\t\"\t\t <dimension3>13</dimension3>\" + \n\t\"\t\t <dimension3>14</dimension3>\" + \n\t\"\t </dimension2>\" + \n\t\" </dimension1>\" + \n\t\" </otherdimension1>\" + \n\t\"</div>\";\n\tconsole.log(div.innerText); \n\tvar measure = (node) => {\n\t\t const nodes = Array.from(node.childNodes).filter(f => f.nodeName === '#text');\n\t\t return nodes.length ? nodes[0].textContent.trim() : '';\n\t\t}\n var hop1 = new Hop38(div , \"dimension1\",\"dimension1\");\n var hop2 = new Hop38(hop1.html, \"dimension2\",\"dimension2\");\n var hop3 = new Hop38(hop2.html, \"dimension3\",\"dimension3\");\n // *******FIRST MEASUREMENT ************** *******LAST MEASUREMENT ************** \n expect(measure(hop1.html[0])) .toEqual( \"1\" ); expect(measure(hop1.html[1])).toEqual ( \"8\" ); \n expect(measure(hop2.html[0][0])) .toEqual( \"2\" ); expect(measure(hop2.html[1][1])).toEqual ( \"10\" ); \n expect(measure(hop3.html[0][0][0])).toEqual( \"4\" ); expect(measure(hop3.html[1][1][1])).toEqual ( \"14\" ); \n \n // test 40: Can we measure the bottom row?\n //expect(hop3.flatHtml.map(measure).toEqual( [ \"4\", \"5\", '6', '7', '11', '12', '13', '14' ] ); \n\t\n}",
"order(words){cov_25grm4ggn6.f[7]++;cov_25grm4ggn6.s[40]++;if(!words){cov_25grm4ggn6.b[15][0]++;cov_25grm4ggn6.s[41]++;return[];}else{cov_25grm4ggn6.b[15][1]++;}//ensure we have a list of individual words, not phrases, no punctuation, etc.\nlet list=(cov_25grm4ggn6.s[42]++,words.toString().match(/\\w+/g));cov_25grm4ggn6.s[43]++;if(list.length==0){cov_25grm4ggn6.b[16][0]++;cov_25grm4ggn6.s[44]++;return[];}else{cov_25grm4ggn6.b[16][1]++;}cov_25grm4ggn6.s[45]++;return list.sort((a,b)=>{cov_25grm4ggn6.f[8]++;cov_25grm4ggn6.s[46]++;return this.rank(a)<=this.rank(b)?(cov_25grm4ggn6.b[17][0]++,1):(cov_25grm4ggn6.b[17][1]++,-1);});}",
"function primStringConcat(vs) {\n var ts = []; // final string\n var cs = vs.reverse(); // stack of arguments to go through\n\n while (hasLength(cs) && cs.length > 0) {\n var x = cs.pop();\n if (x.tag == \"Value\") { x = x.value; };\n\n switch (x.tag) {\n case \"Lit\":\n if (stringy(x.literal)) { ts += x.literal; continue; }\n else return Complain(\"Invalid_StringConcat_ArgType\",[]);\n case \"Cell\":\n cs.push(x.snd,x.fst); // note push in the right order!\n continue;\n case \"Atom\":\n continue;\n case \"Nil\":\n continue;\n default:\n return Complain(\"Invalid_StringConcat_ArgType\",[]);\n };\n };\n return Use(Lit(ts));\n}",
"function step5a(token) {\n\tvar m = measure(token);\n\n\tif(token.length > 3 && ((m > 1 && token.substr(-1) == 'e') || (m == 1 && !(categorizeChars(token).substr(-4, 3) == 'CVC' && token.match(/[^wxy].$/)))))\n\t\treturn token.replace(/e$/, '');\n\n\treturn token;\n}",
"function generateJavascript(ast, options) {\n\t /* These only indent non-empty lines to avoid trailing whitespace. */\n\t function indent2(code) { return code.replace(/^(.+)$/gm, ' $1'); }\n\t function indent4(code) { return code.replace(/^(.+)$/gm, ' $1'); }\n\t function indent8(code) { return code.replace(/^(.+)$/gm, ' $1'); }\n\t function indent10(code) { return code.replace(/^(.+)$/gm, ' $1'); }\n\n\t function generateTables() {\n\t if (options.optimize === \"size\") {\n\t return [\n\t 'peg$consts = [',\n\t indent2(ast.consts.join(',\\n')),\n\t '],',\n\t '',\n\t 'peg$bytecode = [',\n\t indent2(arrays.map(ast.rules, function(rule) {\n\t return 'peg$decode(\"'\n\t + js.stringEscape(arrays.map(\n\t rule.bytecode,\n\t function(b) { return String.fromCharCode(b + 32); }\n\t ).join(''))\n\t + '\")';\n\t }).join(',\\n')),\n\t '],'\n\t ].join('\\n');\n\t } else {\n\t return arrays.map(\n\t ast.consts,\n\t function(c, i) { return 'peg$c' + i + ' = ' + c + ','; }\n\t ).join('\\n');\n\t }\n\t }\n\n\t function generateRuleHeader(ruleNameCode, ruleIndexCode) {\n\t var parts = [];\n\n\t parts.push('');\n\n\t if (options.trace) {\n\t parts.push([\n\t 'peg$trace({',\n\t ' type: \"rule.enter\",',\n\t ' rule: ' + ruleNameCode,\n\t '});',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t if (options.cache) {\n\t parts.push([\n\t 'var key = peg$currPos * ' + ast.rules.length + ' + ' + ruleIndexCode + ',',\n\t ' cached = peg$cache[key];',\n\t '',\n\t 'if (cached) {',\n\t ' peg$currPos = cached.nextPos;',\n\t '',\n\t ].join('\\n'));\n\n\t if (options.trace) {\n\t parts.push([\n\t 'if (cached.result !== peg$FAILED) {',\n\t ' peg$trace({',\n\t ' type: \"rule.match\",',\n\t ' rule: ' + ruleNameCode + ',',\n\t ' result: cached.result',\n\t ' });',\n\t '} else {',\n\t ' peg$trace({',\n\t ' type: \"rule.fail\",',\n\t ' rule: ' + ruleNameCode,\n\t ' });',\n\t '}',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' return cached.result;',\n\t '}',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t return parts.join('\\n');\n\t }\n\n\t function generateRuleFooter(ruleNameCode, resultCode) {\n\t var parts = [];\n\n\t if (options.cache) {\n\t parts.push([\n\t '',\n\t 'peg$cache[key] = { nextPos: peg$currPos, result: ' + resultCode + ' };'\n\t ].join('\\n'));\n\t }\n\n\t if (options.trace) {\n\t parts.push([\n\t '',\n\t 'if (' + resultCode + ' !== peg$FAILED) {',\n\t ' peg$trace({',\n\t ' type: \"rule.match\",',\n\t ' rule: ' + ruleNameCode + ',',\n\t ' result: ' + resultCode,\n\t ' });',\n\t '} else {',\n\t ' peg$trace({',\n\t ' type: \"rule.fail\",',\n\t ' rule: ' + ruleNameCode,\n\t ' });',\n\t '}'\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t '',\n\t 'return ' + resultCode + ';'\n\t ].join('\\n'));\n\n\t return parts.join('\\n');\n\t }\n\n\t function generateInterpreter() {\n\t var parts = [];\n\n\t function generateCondition(cond, argsLength) {\n\t var baseLength = argsLength + 3,\n\t thenLengthCode = 'bc[ip + ' + (baseLength - 2) + ']',\n\t elseLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';\n\n\t return [\n\t 'ends.push(end);',\n\t 'ips.push(ip + ' + baseLength + ' + ' + thenLengthCode + ' + ' + elseLengthCode + ');',\n\t '',\n\t 'if (' + cond + ') {',\n\t ' end = ip + ' + baseLength + ' + ' + thenLengthCode + ';',\n\t ' ip += ' + baseLength + ';',\n\t '} else {',\n\t ' end = ip + ' + baseLength + ' + ' + thenLengthCode + ' + ' + elseLengthCode + ';',\n\t ' ip += ' + baseLength + ' + ' + thenLengthCode + ';',\n\t '}',\n\t '',\n\t 'break;'\n\t ].join('\\n');\n\t }\n\n\t function generateLoop(cond) {\n\t var baseLength = 2,\n\t bodyLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';\n\n\t return [\n\t 'if (' + cond + ') {',\n\t ' ends.push(end);',\n\t ' ips.push(ip);',\n\t '',\n\t ' end = ip + ' + baseLength + ' + ' + bodyLengthCode + ';',\n\t ' ip += ' + baseLength + ';',\n\t '} else {',\n\t ' ip += ' + baseLength + ' + ' + bodyLengthCode + ';',\n\t '}',\n\t '',\n\t 'break;'\n\t ].join('\\n');\n\t }\n\n\t function generateCall() {\n\t var baseLength = 4,\n\t paramsLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';\n\n\t return [\n\t 'params = bc.slice(ip + ' + baseLength + ', ip + ' + baseLength + ' + ' + paramsLengthCode + ');',\n\t 'for (i = 0; i < ' + paramsLengthCode + '; i++) {',\n\t ' params[i] = stack[stack.length - 1 - params[i]];',\n\t '}',\n\t '',\n\t 'stack.splice(',\n\t ' stack.length - bc[ip + 2],',\n\t ' bc[ip + 2],',\n\t ' peg$consts[bc[ip + 1]].apply(null, params)',\n\t ');',\n\t '',\n\t 'ip += ' + baseLength + ' + ' + paramsLengthCode + ';',\n\t 'break;'\n\t ].join('\\n');\n\t }\n\n\t parts.push([\n\t 'function peg$decode(s) {',\n\t ' var bc = new Array(s.length), i;',\n\t '',\n\t ' for (i = 0; i < s.length; i++) {',\n\t ' bc[i] = s.charCodeAt(i) - 32;',\n\t ' }',\n\t '',\n\t ' return bc;',\n\t '}',\n\t '',\n\t 'function peg$parseRule(index) {',\n\t ' var bc = peg$bytecode[index],',\n\t ' ip = 0,',\n\t ' ips = [],',\n\t ' end = bc.length,',\n\t ' ends = [],',\n\t ' stack = [],',\n\t ' params, i;',\n\t ].join('\\n'));\n\n\t parts.push(indent2(generateRuleHeader('peg$ruleNames[index]', 'index')));\n\n\t parts.push([\n\t /*\n\t * The point of the outer loop and the |ips| & |ends| stacks is to avoid\n\t * recursive calls for interpreting parts of bytecode. In other words, we\n\t * implement the |interpret| operation of the abstract machine without\n\t * function calls. Such calls would likely slow the parser down and more\n\t * importantly cause stack overflows for complex grammars.\n\t */\n\t ' while (true) {',\n\t ' while (ip < end) {',\n\t ' switch (bc[ip]) {',\n\t ' case ' + op.PUSH + ':', // PUSH c\n\t ' stack.push(peg$consts[bc[ip + 1]]);',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_UNDEFINED + ':', // PUSH_UNDEFINED\n\t ' stack.push(void 0);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_NULL + ':', // PUSH_NULL\n\t ' stack.push(null);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_FAILED + ':', // PUSH_FAILED\n\t ' stack.push(peg$FAILED);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_EMPTY_ARRAY + ':', // PUSH_EMPTY_ARRAY\n\t ' stack.push([]);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_CURR_POS + ':', // PUSH_CURR_POS\n\t ' stack.push(peg$currPos);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.POP + ':', // POP\n\t ' stack.pop();',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.POP_CURR_POS + ':', // POP_CURR_POS\n\t ' peg$currPos = stack.pop();',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.POP_N + ':', // POP_N n\n\t ' stack.length -= bc[ip + 1];',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.NIP + ':', // NIP\n\t ' stack.splice(-2, 1);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.APPEND + ':', // APPEND\n\t ' stack[stack.length - 2].push(stack.pop());',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.WRAP + ':', // WRAP n\n\t ' stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1]));',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.TEXT + ':', // TEXT\n\t ' stack.push(input.substring(stack.pop(), peg$currPos));',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.IF + ':', // IF t, f\n\t indent10(generateCondition('stack[stack.length - 1]', 0)),\n\t '',\n\t ' case ' + op.IF_ERROR + ':', // IF_ERROR t, f\n\t indent10(generateCondition(\n\t 'stack[stack.length - 1] === peg$FAILED',\n\t 0\n\t )),\n\t '',\n\t ' case ' + op.IF_NOT_ERROR + ':', // IF_NOT_ERROR t, f\n\t indent10(\n\t generateCondition('stack[stack.length - 1] !== peg$FAILED',\n\t 0\n\t )),\n\t '',\n\t ' case ' + op.WHILE_NOT_ERROR + ':', // WHILE_NOT_ERROR b\n\t indent10(generateLoop('stack[stack.length - 1] !== peg$FAILED')),\n\t '',\n\t ' case ' + op.MATCH_ANY + ':', // MATCH_ANY a, f, ...\n\t indent10(generateCondition('input.length > peg$currPos', 0)),\n\t '',\n\t ' case ' + op.MATCH_STRING + ':', // MATCH_STRING s, a, f, ...\n\t indent10(generateCondition(\n\t 'input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]',\n\t 1\n\t )),\n\t '',\n\t ' case ' + op.MATCH_STRING_IC + ':', // MATCH_STRING_IC s, a, f, ...\n\t indent10(generateCondition(\n\t 'input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]',\n\t 1\n\t )),\n\t '',\n\t ' case ' + op.MATCH_REGEXP + ':', // MATCH_REGEXP r, a, f, ...\n\t indent10(generateCondition(\n\t 'peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))',\n\t 1\n\t )),\n\t '',\n\t ' case ' + op.ACCEPT_N + ':', // ACCEPT_N n\n\t ' stack.push(input.substr(peg$currPos, bc[ip + 1]));',\n\t ' peg$currPos += bc[ip + 1];',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.ACCEPT_STRING + ':', // ACCEPT_STRING s\n\t ' stack.push(peg$consts[bc[ip + 1]]);',\n\t ' peg$currPos += peg$consts[bc[ip + 1]].length;',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.FAIL + ':', // FAIL e\n\t ' stack.push(peg$FAILED);',\n\t ' if (peg$silentFails === 0) {',\n\t ' peg$fail(peg$consts[bc[ip + 1]]);',\n\t ' }',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.REPORT_SAVED_POS + ':', // REPORT_SAVED_POS p\n\t ' peg$reportedPos = stack[stack.length - 1 - bc[ip + 1]];',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.REPORT_CURR_POS + ':', // REPORT_CURR_POS\n\t ' peg$reportedPos = peg$currPos;',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.CALL + ':', // CALL f, n, pc, p1, p2, ..., pN\n\t indent10(generateCall()),\n\t '',\n\t ' case ' + op.RULE + ':', // RULE r\n\t ' stack.push(peg$parseRule(bc[ip + 1]));',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.SILENT_FAILS_ON + ':', // SILENT_FAILS_ON\n\t ' peg$silentFails++;',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.SILENT_FAILS_OFF + ':', // SILENT_FAILS_OFF\n\t ' peg$silentFails--;',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' default:',\n\t ' throw new Error(\"Invalid opcode: \" + bc[ip] + \".\");',\n\t ' }',\n\t ' }',\n\t '',\n\t ' if (ends.length > 0) {',\n\t ' end = ends.pop();',\n\t ' ip = ips.pop();',\n\t ' } else {',\n\t ' break;',\n\t ' }',\n\t ' }'\n\t ].join('\\n'));\n\n\t parts.push(indent2(generateRuleFooter('peg$ruleNames[index]', 'stack[0]')));\n\t parts.push('}');\n\n\t return parts.join('\\n');\n\t }\n\n\t function generateRuleFunction(rule) {\n\t var parts = [], code;\n\n\t function c(i) { return \"peg$c\" + i; } // |consts[i]| of the abstract machine\n\t function s(i) { return \"s\" + i; } // |stack[i]| of the abstract machine\n\n\t var stack = {\n\t sp: -1,\n\t maxSp: -1,\n\n\t push: function(exprCode) {\n\t var code = s(++this.sp) + ' = ' + exprCode + ';';\n\n\t if (this.sp > this.maxSp) { this.maxSp = this.sp; }\n\n\t return code;\n\t },\n\n\t pop: function() {\n\t var n, values;\n\n\t if (arguments.length === 0) {\n\t return s(this.sp--);\n\t } else {\n\t n = arguments[0];\n\t values = arrays.map(arrays.range(this.sp - n + 1, this.sp + 1), s);\n\t this.sp -= n;\n\n\t return values;\n\t }\n\t },\n\n\t top: function() {\n\t return s(this.sp);\n\t },\n\n\t index: function(i) {\n\t return s(this.sp - i);\n\t }\n\t };\n\n\t function compile(bc) {\n\t var ip = 0,\n\t end = bc.length,\n\t parts = [],\n\t value;\n\n\t function compileCondition(cond, argCount) {\n\t var baseLength = argCount + 3,\n\t thenLength = bc[ip + baseLength - 2],\n\t elseLength = bc[ip + baseLength - 1],\n\t baseSp = stack.sp,\n\t thenCode, elseCode, thenSp, elseSp;\n\n\t ip += baseLength;\n\t thenCode = compile(bc.slice(ip, ip + thenLength));\n\t thenSp = stack.sp;\n\t ip += thenLength;\n\n\t if (elseLength > 0) {\n\t stack.sp = baseSp;\n\t elseCode = compile(bc.slice(ip, ip + elseLength));\n\t elseSp = stack.sp;\n\t ip += elseLength;\n\n\t if (thenSp !== elseSp) {\n\t throw new Error(\n\t \"Branches of a condition must move the stack pointer in the same way.\"\n\t );\n\t }\n\t }\n\n\t parts.push('if (' + cond + ') {');\n\t parts.push(indent2(thenCode));\n\t if (elseLength > 0) {\n\t parts.push('} else {');\n\t parts.push(indent2(elseCode));\n\t }\n\t parts.push('}');\n\t }\n\n\t function compileLoop(cond) {\n\t var baseLength = 2,\n\t bodyLength = bc[ip + baseLength - 1],\n\t baseSp = stack.sp,\n\t bodyCode, bodySp;\n\n\t ip += baseLength;\n\t bodyCode = compile(bc.slice(ip, ip + bodyLength));\n\t bodySp = stack.sp;\n\t ip += bodyLength;\n\n\t if (bodySp !== baseSp) {\n\t throw new Error(\"Body of a loop can't move the stack pointer.\");\n\t }\n\n\t parts.push('while (' + cond + ') {');\n\t parts.push(indent2(bodyCode));\n\t parts.push('}');\n\t }\n\n\t function compileCall() {\n\t var baseLength = 4,\n\t paramsLength = bc[ip + baseLength - 1];\n\n\t var value = c(bc[ip + 1]) + '('\n\t + arrays.map(\n\t bc.slice(ip + baseLength, ip + baseLength + paramsLength),\n\t function(p) { return stack.index(p); }\n\t ).join(', ')\n\t + ')';\n\t stack.pop(bc[ip + 2]);\n\t parts.push(stack.push(value));\n\t ip += baseLength + paramsLength;\n\t }\n\n\t while (ip < end) {\n\t switch (bc[ip]) {\n\t case op.PUSH: // PUSH c\n\t parts.push(stack.push(c(bc[ip + 1])));\n\t ip += 2;\n\t break;\n\n\t case op.PUSH_CURR_POS: // PUSH_CURR_POS\n\t parts.push(stack.push('peg$currPos'));\n\t ip++;\n\t break;\n\n\t case op.PUSH_UNDEFINED: // PUSH_UNDEFINED\n\t parts.push(stack.push('void 0'));\n\t ip++;\n\t break;\n\n\t case op.PUSH_NULL: // PUSH_NULL\n\t parts.push(stack.push('null'));\n\t ip++;\n\t break;\n\n\t case op.PUSH_FAILED: // PUSH_FAILED\n\t parts.push(stack.push('peg$FAILED'));\n\t ip++;\n\t break;\n\n\t case op.PUSH_EMPTY_ARRAY: // PUSH_EMPTY_ARRAY\n\t parts.push(stack.push('[]'));\n\t ip++;\n\t break;\n\n\t case op.POP: // POP\n\t stack.pop();\n\t ip++;\n\t break;\n\n\t case op.POP_CURR_POS: // POP_CURR_POS\n\t parts.push('peg$currPos = ' + stack.pop() + ';');\n\t ip++;\n\t break;\n\n\t case op.POP_N: // POP_N n\n\t stack.pop(bc[ip + 1]);\n\t ip += 2;\n\t break;\n\n\t case op.NIP: // NIP\n\t value = stack.pop();\n\t stack.pop();\n\t parts.push(stack.push(value));\n\t ip++;\n\t break;\n\n\t case op.APPEND: // APPEND\n\t value = stack.pop();\n\t parts.push(stack.top() + '.push(' + value + ');');\n\t ip++;\n\t break;\n\n\t case op.WRAP: // WRAP n\n\t parts.push(\n\t stack.push('[' + stack.pop(bc[ip + 1]).join(', ') + ']')\n\t );\n\t ip += 2;\n\t break;\n\n\t case op.TEXT: // TEXT\n\t parts.push(\n\t stack.push('input.substring(' + stack.pop() + ', peg$currPos)')\n\t );\n\t ip++;\n\t break;\n\n\t case op.IF: // IF t, f\n\t compileCondition(stack.top(), 0);\n\t break;\n\n\t case op.IF_ERROR: // IF_ERROR t, f\n\t compileCondition(stack.top() + ' === peg$FAILED', 0);\n\t break;\n\n\t case op.IF_NOT_ERROR: // IF_NOT_ERROR t, f\n\t compileCondition(stack.top() + ' !== peg$FAILED', 0);\n\t break;\n\n\t case op.WHILE_NOT_ERROR: // WHILE_NOT_ERROR b\n\t compileLoop(stack.top() + ' !== peg$FAILED', 0);\n\t break;\n\n\t case op.MATCH_ANY: // MATCH_ANY a, f, ...\n\t compileCondition('input.length > peg$currPos', 0);\n\t break;\n\n\t case op.MATCH_STRING: // MATCH_STRING s, a, f, ...\n\t compileCondition(\n\t eval(ast.consts[bc[ip + 1]]).length > 1\n\t ? 'input.substr(peg$currPos, '\n\t + eval(ast.consts[bc[ip + 1]]).length\n\t + ') === '\n\t + c(bc[ip + 1])\n\t : 'input.charCodeAt(peg$currPos) === '\n\t + eval(ast.consts[bc[ip + 1]]).charCodeAt(0),\n\t 1\n\t );\n\t break;\n\n\t case op.MATCH_STRING_IC: // MATCH_STRING_IC s, a, f, ...\n\t compileCondition(\n\t 'input.substr(peg$currPos, '\n\t + eval(ast.consts[bc[ip + 1]]).length\n\t + ').toLowerCase() === '\n\t + c(bc[ip + 1]),\n\t 1\n\t );\n\t break;\n\n\t case op.MATCH_REGEXP: // MATCH_REGEXP r, a, f, ...\n\t compileCondition(\n\t c(bc[ip + 1]) + '.test(input.charAt(peg$currPos))',\n\t 1\n\t );\n\t break;\n\n\t case op.ACCEPT_N: // ACCEPT_N n\n\t parts.push(stack.push(\n\t bc[ip + 1] > 1\n\t ? 'input.substr(peg$currPos, ' + bc[ip + 1] + ')'\n\t : 'input.charAt(peg$currPos)'\n\t ));\n\t parts.push(\n\t bc[ip + 1] > 1\n\t ? 'peg$currPos += ' + bc[ip + 1] + ';'\n\t : 'peg$currPos++;'\n\t );\n\t ip += 2;\n\t break;\n\n\t case op.ACCEPT_STRING: // ACCEPT_STRING s\n\t parts.push(stack.push(c(bc[ip + 1])));\n\t parts.push(\n\t eval(ast.consts[bc[ip + 1]]).length > 1\n\t ? 'peg$currPos += ' + eval(ast.consts[bc[ip + 1]]).length + ';'\n\t : 'peg$currPos++;'\n\t );\n\t ip += 2;\n\t break;\n\n\t case op.FAIL: // FAIL e\n\t parts.push(stack.push('peg$FAILED'));\n\t parts.push('if (peg$silentFails === 0) { peg$fail(' + c(bc[ip + 1]) + '); }');\n\t ip += 2;\n\t break;\n\n\t case op.REPORT_SAVED_POS: // REPORT_SAVED_POS p\n\t parts.push('peg$reportedPos = ' + stack.index(bc[ip + 1]) + ';');\n\t ip += 2;\n\t break;\n\n\t case op.REPORT_CURR_POS: // REPORT_CURR_POS\n\t parts.push('peg$reportedPos = peg$currPos;');\n\t ip++;\n\t break;\n\n\t case op.CALL: // CALL f, n, pc, p1, p2, ..., pN\n\t compileCall();\n\t break;\n\n\t case op.RULE: // RULE r\n\t parts.push(stack.push(\"peg$parse\" + ast.rules[bc[ip + 1]].name + \"()\"));\n\t ip += 2;\n\t break;\n\n\t case op.SILENT_FAILS_ON: // SILENT_FAILS_ON\n\t parts.push('peg$silentFails++;');\n\t ip++;\n\t break;\n\n\t case op.SILENT_FAILS_OFF: // SILENT_FAILS_OFF\n\t parts.push('peg$silentFails--;');\n\t ip++;\n\t break;\n\n\t default:\n\t throw new Error(\"Invalid opcode: \" + bc[ip] + \".\");\n\t }\n\t }\n\n\t return parts.join('\\n');\n\t }\n\n\t code = compile(rule.bytecode);\n\n\t parts.push([\n\t 'function peg$parse' + rule.name + '() {',\n\t ' var ' + arrays.map(arrays.range(0, stack.maxSp + 1), s).join(', ') + ';',\n\t ].join('\\n'));\n\n\t parts.push(indent2(generateRuleHeader(\n\t '\"' + js.stringEscape(rule.name) + '\"',\n\t asts.indexOfRule(ast, rule.name)\n\t )));\n\t parts.push(indent2(code));\n\t parts.push(indent2(generateRuleFooter(\n\t '\"' + js.stringEscape(rule.name) + '\"',\n\t s(0)\n\t )));\n\n\t parts.push('}');\n\n\t return parts.join('\\n');\n\t }\n\n\t var parts = [],\n\t startRuleIndices, startRuleIndex,\n\t startRuleFunctions, startRuleFunction,\n\t ruleNames;\n\n\t parts.push([\n\t '(function() {',\n\t ' /*',\n\t ' * Generated by PEG.js 0.8.0.',\n\t ' *',\n\t ' * http://pegjs.org/',\n\t ' */',\n\t '',\n\t ' function peg$subclass(child, parent) {',\n\t ' function ctor() { this.constructor = child; }',\n\t ' ctor.prototype = parent.prototype;',\n\t ' child.prototype = new ctor();',\n\t ' }',\n\t '',\n\t ' function peg$SyntaxError(message, expected, found, offset, line, column) {',\n\t ' this.message = message;',\n\t ' this.expected = expected;',\n\t ' this.found = found;',\n\t ' this.offset = offset;',\n\t ' this.line = line;',\n\t ' this.column = column;',\n\t '',\n\t ' this.name = \"SyntaxError\";',\n\t ' }',\n\t '',\n\t ' peg$subclass(peg$SyntaxError, Error);',\n\t ''\n\t ].join('\\n'));\n\n\t if (options.trace) {\n\t parts.push([\n\t ' function peg$DefaultTracer() {',\n\t ' this.indentLevel = 0;',\n\t ' }',\n\t '',\n\t ' peg$DefaultTracer.prototype.trace = function(event) {',\n\t ' var that = this;',\n\t '',\n\t ' function log(event) {',\n\t ' function repeat(string, n) {',\n\t ' var result = \"\", i;',\n\t '',\n\t ' for (i = 0; i < n; i++) {',\n\t ' result += string;',\n\t ' }',\n\t '',\n\t ' return result;',\n\t ' }',\n\t '',\n\t ' function pad(string, length) {',\n\t ' return string + repeat(\" \", length - string.length);',\n\t ' }',\n\t '',\n\t ' console.log(',\n\t ' event.line + \":\" + event.column + \" \"',\n\t ' + pad(event.type, 10) + \" \"',\n\t ' + repeat(\" \", that.indentLevel) + event.rule',\n\t ' );',\n\t ' }',\n\t '',\n\t ' switch (event.type) {',\n\t ' case \"rule.enter\":',\n\t ' log(event);',\n\t ' this.indentLevel++;',\n\t ' break;',\n\t '',\n\t ' case \"rule.match\":',\n\t ' this.indentLevel--;',\n\t ' log(event);',\n\t ' break;',\n\t '',\n\t ' case \"rule.fail\":',\n\t ' this.indentLevel--;',\n\t ' log(event);',\n\t ' break;',\n\t '',\n\t ' default:',\n\t ' throw new Error(\"Invalid event type: \" + event.type + \".\");',\n\t ' }',\n\t ' };',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' function peg$parse(input) {',\n\t ' var options = arguments.length > 1 ? arguments[1] : {},',\n\t ' parser = this,',\n\t '',\n\t ' peg$FAILED = {},',\n\t ''\n\t ].join('\\n'));\n\n\t if (options.optimize === \"size\") {\n\t startRuleIndices = '{ '\n\t + arrays.map(\n\t options.allowedStartRules,\n\t function(r) { return r + ': ' + asts.indexOfRule(ast, r); }\n\t ).join(', ')\n\t + ' }';\n\t startRuleIndex = asts.indexOfRule(ast, options.allowedStartRules[0]);\n\n\t parts.push([\n\t ' peg$startRuleIndices = ' + startRuleIndices + ',',\n\t ' peg$startRuleIndex = ' + startRuleIndex + ','\n\t ].join('\\n'));\n\t } else {\n\t startRuleFunctions = '{ '\n\t + arrays.map(\n\t options.allowedStartRules,\n\t function(r) { return r + ': peg$parse' + r; }\n\t ).join(', ')\n\t + ' }';\n\t startRuleFunction = 'peg$parse' + options.allowedStartRules[0];\n\n\t parts.push([\n\t ' peg$startRuleFunctions = ' + startRuleFunctions + ',',\n\t ' peg$startRuleFunction = ' + startRuleFunction + ','\n\t ].join('\\n'));\n\t }\n\n\t parts.push('');\n\n\t parts.push(indent8(generateTables()));\n\n\t parts.push([\n\t '',\n\t ' peg$currPos = 0,',\n\t ' peg$reportedPos = 0,',\n\t ' peg$cachedPos = 0,',\n\t ' peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },',\n\t ' peg$maxFailPos = 0,',\n\t ' peg$maxFailExpected = [],',\n\t ' peg$silentFails = 0,', // 0 = report failures, > 0 = silence failures\n\t ''\n\t ].join('\\n'));\n\n\t if (options.cache) {\n\t parts.push([\n\t ' peg$cache = {},',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t if (options.trace) {\n\t if (options.optimize === \"size\") {\n\t ruleNames = '['\n\t + arrays.map(\n\t ast.rules,\n\t function(r) { return '\"' + js.stringEscape(r.name) + '\"'; }\n\t ).join(', ')\n\t + ']';\n\n\t parts.push([\n\t ' peg$ruleNames = ' + ruleNames + ',',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' peg$tracer = \"tracer\" in options ? options.tracer : new peg$DefaultTracer(),',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' peg$result;',\n\t ''\n\t ].join('\\n'));\n\n\t if (options.optimize === \"size\") {\n\t parts.push([\n\t ' if (\"startRule\" in options) {',\n\t ' if (!(options.startRule in peg$startRuleIndices)) {',\n\t ' throw new Error(\"Can\\'t start parsing from rule \\\\\"\" + options.startRule + \"\\\\\".\");',\n\t ' }',\n\t '',\n\t ' peg$startRuleIndex = peg$startRuleIndices[options.startRule];',\n\t ' }'\n\t ].join('\\n'));\n\t } else {\n\t parts.push([\n\t ' if (\"startRule\" in options) {',\n\t ' if (!(options.startRule in peg$startRuleFunctions)) {',\n\t ' throw new Error(\"Can\\'t start parsing from rule \\\\\"\" + options.startRule + \"\\\\\".\");',\n\t ' }',\n\t '',\n\t ' peg$startRuleFunction = peg$startRuleFunctions[options.startRule];',\n\t ' }'\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t '',\n\t ' function text() {',\n\t ' return input.substring(peg$reportedPos, peg$currPos);',\n\t ' }',\n\t '',\n\t ' function offset() {',\n\t ' return peg$reportedPos;',\n\t ' }',\n\t '',\n\t ' function line() {',\n\t ' return peg$computePosDetails(peg$reportedPos).line;',\n\t ' }',\n\t '',\n\t ' function column() {',\n\t ' return peg$computePosDetails(peg$reportedPos).column;',\n\t ' }',\n\t '',\n\t ' function expected(description) {',\n\t ' throw peg$buildException(',\n\t ' null,',\n\t ' [{ type: \"other\", description: description }],',\n\t ' peg$reportedPos',\n\t ' );',\n\t ' }',\n\t '',\n\t ' function error(message) {',\n\t ' throw peg$buildException(message, null, peg$reportedPos);',\n\t ' }',\n\t '',\n\t ' function peg$computePosDetails(pos) {',\n\t ' function advance(details, startPos, endPos) {',\n\t ' var p, ch;',\n\t '',\n\t ' for (p = startPos; p < endPos; p++) {',\n\t ' ch = input.charAt(p);',\n\t ' if (ch === \"\\\\n\") {',\n\t ' if (!details.seenCR) { details.line++; }',\n\t ' details.column = 1;',\n\t ' details.seenCR = false;',\n\t ' } else if (ch === \"\\\\r\" || ch === \"\\\\u2028\" || ch === \"\\\\u2029\") {',\n\t ' details.line++;',\n\t ' details.column = 1;',\n\t ' details.seenCR = true;',\n\t ' } else {',\n\t ' details.column++;',\n\t ' details.seenCR = false;',\n\t ' }',\n\t ' }',\n\t ' }',\n\t '',\n\t ' if (peg$cachedPos !== pos) {',\n\t ' if (peg$cachedPos > pos) {',\n\t ' peg$cachedPos = 0;',\n\t ' peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };',\n\t ' }',\n\t ' advance(peg$cachedPosDetails, peg$cachedPos, pos);',\n\t ' peg$cachedPos = pos;',\n\t ' }',\n\t '',\n\t ' return peg$cachedPosDetails;',\n\t ' }',\n\t '',\n\t ' function peg$fail(expected) {',\n\t ' if (peg$currPos < peg$maxFailPos) { return; }',\n\t '',\n\t ' if (peg$currPos > peg$maxFailPos) {',\n\t ' peg$maxFailPos = peg$currPos;',\n\t ' peg$maxFailExpected = [];',\n\t ' }',\n\t '',\n\t ' peg$maxFailExpected.push(expected);',\n\t ' }',\n\t '',\n\t ' function peg$buildException(message, expected, pos) {',\n\t ' function cleanupExpected(expected) {',\n\t ' var i = 1;',\n\t '',\n\t ' expected.sort(function(a, b) {',\n\t ' if (a.description < b.description) {',\n\t ' return -1;',\n\t ' } else if (a.description > b.description) {',\n\t ' return 1;',\n\t ' } else {',\n\t ' return 0;',\n\t ' }',\n\t ' });',\n\t '',\n\t /*\n\t * This works because the bytecode generator guarantees that every\n\t * expectation object exists only once, so it's enough to use |===| instead\n\t * of deeper structural comparison.\n\t */\n\t ' while (i < expected.length) {',\n\t ' if (expected[i - 1] === expected[i]) {',\n\t ' expected.splice(i, 1);',\n\t ' } else {',\n\t ' i++;',\n\t ' }',\n\t ' }',\n\t ' }',\n\t '',\n\t ' function buildMessage(expected, found) {',\n\t ' function stringEscape(s) {',\n\t ' function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }',\n\t '',\n\t /*\n\t * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a string\n\t * literal except for the closing quote character, backslash, carriage\n\t * return, line separator, paragraph separator, and line feed. Any character\n\t * may appear in the form of an escape sequence.\n\t *\n\t * For portability, we also escape all control and non-ASCII characters.\n\t * Note that \"\\0\" and \"\\v\" escape sequences are not used because JSHint does\n\t * not like the first and IE the second.\n\t */\n\t ' return s',\n\t ' .replace(/\\\\\\\\/g, \\'\\\\\\\\\\\\\\\\\\')', // backslash\n\t ' .replace(/\"/g, \\'\\\\\\\\\"\\')', // closing double quote\n\t ' .replace(/\\\\x08/g, \\'\\\\\\\\b\\')', // backspace\n\t ' .replace(/\\\\t/g, \\'\\\\\\\\t\\')', // horizontal tab\n\t ' .replace(/\\\\n/g, \\'\\\\\\\\n\\')', // line feed\n\t ' .replace(/\\\\f/g, \\'\\\\\\\\f\\')', // form feed\n\t ' .replace(/\\\\r/g, \\'\\\\\\\\r\\')', // carriage return\n\t ' .replace(/[\\\\x00-\\\\x07\\\\x0B\\\\x0E\\\\x0F]/g, function(ch) { return \\'\\\\\\\\x0\\' + hex(ch); })',\n\t ' .replace(/[\\\\x10-\\\\x1F\\\\x80-\\\\xFF]/g, function(ch) { return \\'\\\\\\\\x\\' + hex(ch); })',\n\t ' .replace(/[\\\\u0100-\\\\u0FFF]/g, function(ch) { return \\'\\\\\\\\u0\\' + hex(ch); })',\n\t ' .replace(/[\\\\u1000-\\\\uFFFF]/g, function(ch) { return \\'\\\\\\\\u\\' + hex(ch); });',\n\t ' }',\n\t '',\n\t ' var expectedDescs = new Array(expected.length),',\n\t ' expectedDesc, foundDesc, i;',\n\t '',\n\t ' for (i = 0; i < expected.length; i++) {',\n\t ' expectedDescs[i] = expected[i].description;',\n\t ' }',\n\t '',\n\t ' expectedDesc = expected.length > 1',\n\t ' ? expectedDescs.slice(0, -1).join(\", \")',\n\t ' + \" or \"',\n\t ' + expectedDescs[expected.length - 1]',\n\t ' : expectedDescs[0];',\n\t '',\n\t ' foundDesc = found ? \"\\\\\"\" + stringEscape(found) + \"\\\\\"\" : \"end of input\";',\n\t '',\n\t ' return \"Expected \" + expectedDesc + \" but \" + foundDesc + \" found.\";',\n\t ' }',\n\t '',\n\t ' var posDetails = peg$computePosDetails(pos),',\n\t ' found = pos < input.length ? input.charAt(pos) : null;',\n\t '',\n\t ' if (expected !== null) {',\n\t ' cleanupExpected(expected);',\n\t ' }',\n\t '',\n\t ' return new peg$SyntaxError(',\n\t ' message !== null ? message : buildMessage(expected, found),',\n\t ' expected,',\n\t ' found,',\n\t ' pos,',\n\t ' posDetails.line,',\n\t ' posDetails.column',\n\t ' );',\n\t ' }',\n\t ''\n\t ].join('\\n'));\n\n\t if (options.trace) {\n\t parts.push([\n\t ' function peg$trace(event) {',\n\t ' var posDetails = peg$computePosDetails(peg$currPos);',\n\t '',\n\t ' event.offset = peg$currPos;',\n\t ' event.line = posDetails.line;',\n\t ' event.column = posDetails.column;',\n\t '',\n\t ' peg$tracer.trace(event);',\n\t ' }',\n\t '',\n\t ].join('\\n'));\n\t }\n\n\t if (options.optimize === \"size\") {\n\t parts.push(indent4(generateInterpreter()));\n\t parts.push('');\n\t } else {\n\t arrays.each(ast.rules, function(rule) {\n\t parts.push(indent4(generateRuleFunction(rule)));\n\t parts.push('');\n\t });\n\t }\n\n\t if (ast.initializer) {\n\t parts.push(indent4(\"{\" + ast.initializer.code + \"}\"));\n\t parts.push('');\n\t }\n\n\t if (options.optimize === \"size\") {\n\t parts.push(' peg$result = peg$parseRule(peg$startRuleIndex);');\n\t } else {\n\t parts.push(' peg$result = peg$startRuleFunction();');\n\t }\n\n\t parts.push([\n\t '',\n\t ' if (peg$result !== peg$FAILED && peg$currPos === input.length) {',\n\t ' return peg$result;',\n\t ' } else {',\n\t ' if (peg$result !== peg$FAILED && peg$currPos < input.length) {',\n\t ' peg$fail({ type: \"end\", description: \"end of input\" });',\n\t ' }',\n\t '',\n\t ' throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);',\n\t ' }',\n\t ' }',\n\t '',\n\t ' return {',\n\t ].join('\\n'));\n\n\t if (options.trace) {\n\t parts.push([\n\t ' SyntaxError: peg$SyntaxError,',\n\t ' DefaultTracer: peg$DefaultTracer,',\n\t ' parse: peg$parse'\n\t ].join('\\n'));\n\t } else {\n\t parts.push([\n\t ' SyntaxError: peg$SyntaxError,',\n\t ' parse: peg$parse'\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' };',\n\t '})()'\n\t ].join('\\n'));\n\n\t ast.code = parts.join('\\n');\n\t}",
"containsLongRules() {\n return this.productions.find(p => p.right.length > 2) !== undefined;\n }",
"function cubify_answer() {\n\tg_word_stripped = find_and_tidy_selected();\n//\tconsole.log('cubify_answer()'+'word_stripped='+g_word_stripped);\n//\tconsole.log('number='+g_HTU_number);\nvar\tcube = mini_cubes[g_HTU_number];\n//\tconsole.log('cube='+cube);\n//\tconsole.log('cube.direction_A ,_B, _C ='+cube.direction_A+','+cube.direction_B+','+cube.direction_C);\n//\tconsole.log('g_word_stripped ='+g_word_stripped);\n\t/*NOBBLE */\n\t\t//return;\n\tif (cube.direction_A == 'A') {\n//\t\tconsole.log('put_..('+g_word_stripped+','+g_HTU_number+')');\n\t\t/*work out next sequence based on word space */\n\t\tg_word_cube_HTU = find_word_HTU(g_HTU_number , 'A');\n\t\tif(g_word_cube_HTU[0] < 0) {\n\t\t\talert('Error HTU '+g_HTU_number+' not found in list');\n\t\t}\n\t\tput_answer_in_direction_A(g_word_stripped, g_HTU_number);\t\n\t}\n\tif (cube.direction_B == 'B') {\n\t\tconsole.log('put_..('+g_word_stripped+','+g_HTU_number+')');\n\t\t/*work out next sequence based on word space */\n\t\tg_word_cube_HTU = find_word_HTU(g_HTU_number , 'A');\n\t\t//put_answer_in_direction(g_word_stripped, 'A', direction);\t\n/*\t\tif(g_word_cube_HTU[0] < 0) {\n\t\t\talert('Error HTU '+in_HTU+' not found in list');\n\t\t}\n\t\t*/\n\t\tput_answer_in_direction_B(g_word_stripped, g_HTU_number);\t\n\t}\n\tif (cube.direction_C == 'C') {\n\t\tconsole.log('put_..('+g_word_stripped+','+g_HTU_number+')');\n\t\t/*work out next sequence based on word space */\n\t\tg_word_cube_HTU = find_word_HTU(g_HTU_number , 'C');\n\t\t//put_answer_in_direction(g_word_stripped, 'A', direction);\t\n\t\tif(g_word_cube_HTU[0] < 0) {\n\t\t\talert('Error HTU '+in_HTU+' not found in list');\n\t\t}\n\t\tput_answer_in_direction_C(g_word_stripped, g_HTU_number);\t\n\t}\n\t\n}",
"function compile_lit(env, expr) { \n \n if (expr === undefined || expr === null) {\n return JSON.stringify(expr); \n }\n\n if (expr.constructor === Number || expr.constructor == Boolean) {\n return JSON.stringify(expr);\n }\n\n return undefined;\n}",
"function createTriplets() {\n\n hardtriplets[0] = [stimset[0], stimset[1], stimset[2]]; words[0] = hardtriplets[0];\n hardtriplets[1] = [stimset[1], stimset[0], stimset[3]]; words[1] = hardtriplets[1];\n hardtriplets[2] = [stimset[3], stimset[2], stimset[0]]; words[2] = hardtriplets[2];\n hardtriplets[3] = [stimset[2], stimset[3], stimset[1]]; words[3] = hardtriplets[3];\n hard[0] = getLetters(stimset[0]) + '-' + getLetters(stimset[1]) + '-' + getLetters(stimset[2]);\n hard[1] = getLetters(stimset[1]) + '-' + getLetters(stimset[0]) + '-' + getLetters(stimset[3]);\n hard[2] = getLetters(stimset[3]) + '-' + getLetters(stimset[2]) + '-' + getLetters(stimset[0]);\n hard[3] = getLetters(stimset[2]) + '-' + getLetters(stimset[3]) + '-' + getLetters(stimset[1]);\n \n easytriplets[0] = [stimset[4], stimset[5], stimset[6]]; words[4] = easytriplets[0];\n easytriplets[1] = [stimset[7], stimset[8], stimset[9]]; words[5] = easytriplets[1];\n easytriplets[2] = [stimset[10], stimset[11], stimset[12]]; words[6] = easytriplets[2];\n easytriplets[3] = [stimset[13], stimset[14], stimset[15]]; words[7] = easytriplets[3];\n easy[0] = getLetters(stimset[4]) + '-' + getLetters(stimset[5]) + '-' + getLetters(stimset[6]);\n easy[1] = getLetters(stimset[7]) + '-' + getLetters(stimset[8]) + '-' + getLetters(stimset[9]);\n easy[2] = getLetters(stimset[10]) + '-' + getLetters(stimset[11]) + '-' + getLetters(stimset[12]);\n easy[3] = getLetters(stimset[13]) + '-' + getLetters(stimset[14]) + '-' + getLetters(stimset[15]);\n \n}",
"function testcase() {\n var b_num = Array.isArray(42);\n var b_undef = Array.isArray(undefined);\n var b_bool = Array.isArray(true);\n var b_str = Array.isArray(\"abc\");\n var b_obj = Array.isArray({});\n var b_null = Array.isArray(null);\n \n if (b_num === false &&\n b_undef === false &&\n b_bool === false &&\n b_str === false &&\n b_obj === false &&\n b_null === false) {\n return true;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Functia de citire din fisierul second.json DETALII COMENZI | function readSecondJson()
{
return JSON.parse(fs.readFileSync("second.json"))["DetaliiComenzi"];
} | [
"function readProiectJson() \n{\n return JSON.parse(fs.readFileSync(\"proiect.json\"))[\"DetaliiContact\"];\n}",
"function writeProiectJson(content)\n{\n fs.writeFileSync(\n \"proiect.json\",\n JSON.stringify({ DetaliiContact: content }),\n \"utf8\",\n err => {\n if (err) {\n console.log(err);\n }\n }\n);\n}",
"function cargarDatos(){\n\n\tconsole.log(\"Cargando registro...\")\n\tfs.readFile('../personajes/partidas/registros.json', (err, data) => {\n\t\tif (!err){ //fichero existe\n\t\t\tregistro = JSON.parse(data);\n \t }\n\t\n\t});\n\tconsole.log(\"Registro Cargado\");\n\tconsole.log('Cargando personajes...');\n\tfs.readFile('../personajes/partidas/personajes.json', (err, data) => {\n\t\tif (!err){ //fichero existe\n\t\t\tpersonajes = JSON.parse(data);\n \t }\n\t\n\t});\n\tconsole.log('Personajes cargados.');\n\tconsole.log('Cargando posiciones...');\n\tfs.readFile('../personajes/partidas/posPersonajes.json', (err, data) => {\n\t\tif (!err){ //fichero existe\n\t\t\tposicionPersonajes = JSON.parse(data);\n \t }\n\t\n\t});\n\tconsole.log('Posiciones cargadas');\n\tconsole.log('Cargando enemigos...');\n\tfs.readFile('../personajes/partidas/enemigos.json', (err, data) => {\n\t\tif (!err){ //fichero existe\n\t\t\tenemigos = JSON.parse(data);\n \t }\n\t\n\t});\n\tconsole.log('Enemigos cargados.');\n\tconsole.log('Cargando estados...');\n\tfs.readFile('../personajes/partidas/estado.json', (err, data) => {\n\t\tif (!err){ //fichero existe\n\t\t\testado = JSON.parse(data);\n \t }\n\t\n\t});\n\tconsole.log('Estados cargados.');\n}",
"function haeRastiKoodit(joukkue) {\n let rastit = joukkue.rastit.slice();\n for (let i = 0; i < rastit.length; i++) {\n for (let j = 0; j < data.rastit.length; j++) {\n if (rastit[i].rasti == data.rastit[j].id + \"\") {\n rastit[i].koodi = data.rastit[j].koodi;\n }\n }\n if (rastit[i].koodi == undefined) {\n rastit[i].koodi = \"0\";\n }\n }\n joukkue.rastit = rastit;\n return joukkue;\n}",
"async getData() {\n const data = await readFile(this.datafile, \"utf8\");\n return JSON.parse(data).tours;\n }",
"function get_date_json()\n {\n var date_json_file_name;\n var date_json_path;\n for(var k=0;k<edition_json.length;k++)\n {\n if(edition_json[k]['date']==$scope.mydate)\n {\n date_json_file_name=edition_json[k]['file_name'];\n date_json_path=edition_json[k]['path'];\n break;\n }\n }\n //alert(date_json_file_name+\" \"+date_json_path);\n var get_date_json_resource = $resource('/api/date_json');\n //{'date':$scope.mydate,'file_name':date_json_file_name,'path_name':date_json_path}\n get_date_json_resource.query({'date':$scope.mydate,'file_name':date_json_file_name,'path_name':date_json_path},\n function(data) {\n // success handler\n //alert(\"success\");\n date_json=data;\n load_sections();\n load_first_page();\n $scope.download_text=\"Download PDF \";\n\n\n }, function(error) {\n // error handler\n alert(\"Error \");\n alert(error);\n\n });\n }",
"readStudentData(){\r\n let url=\"https://maeyler.github.io/JS/data/Students.txt\";\r\n fetch(url)\r\n .then(res => res.text())\r\n .then(res => this.addStudentsToMap(res,this.students));\r\n }",
"function LoadJson(){}",
"function insertData(){\n var obj = JSON.parse(fs.readFileSync('C:\\\\Users\\\\Tiankun\\\\Downloads\\\\doctors2.json', 'utf8'));\n mdb.collection('gp').insertMany(obj);\n}",
"function mostrarObjetos(json){\n var out=\"----------------------------Estudiantes----------------------------<br>\";\n\n for (var i = 0; i < json.length; i++) {\n out+=\"Nombre: \"+json[i].nombre+\" - \"+\"Codigo: \"+json[i].codigo+ \" - \" +\"Nota: \"+json[i].nota+\" <br> \";\n }\n document.getElementById(\"infoEstudiantes\").innerHTML=out;\n}",
"function downloadJSON() {\r\n\t// Save the data object as a string into a file\r\n\tsaveTextAsFile(2);\r\n}",
"function jsonFileLoader(mindmap){ \n //var mindmap;\n numSphere = 0;\n numLink=100;\n angle=0;\n //mindmap=jsonFileContents;\n sphereLinks=[]; //list of links which have to be created with the JSON file\n let linkexist;\n linkNames =[];\n for(let i=0;i<mindmap[\"spheres\"].length;i++){ //the first for loop to allows to access at all the sphere informations : mindmap[\"spheres\"]= [object1],[object2],...\n for(let k=0;k<mindmap[\"spheres\"][i][1][\"connected sphere(s)\"].length;k++){ //the second for loop allows to access at all the connected spheres informations (name of the sphere and name of the link) like that : mindmap[\"spheres\"][i][1][\"connected sphere(s)\"] = [{sphere name: \"Apple\", link name: \"red\"},{sphere name: \"Blueberry\", link name: \"blue\"}]\n linkexist=1; //at first, we suppose that the link does not already exist in the list sphereLinks\n for(let j=0;j<sphereLinks.length;j++){ //the third for loop allows to know if the link already exist in the sphereLink list. The aim of this loop is to build a list (sphereLinks) which contain the connected spheres only once like this : sphereLinks=[[name sphere1, name sphere2],[name sphere1,name sphere3]]\n if((sphereLinks[j][0]==mindmap[\"spheres\"][i][1][\"connected sphere(s)\"][k][\"sphere name\"]) && (sphereLinks[j][1]==mindmap[\"spheres\"][i][0][\"sphere\"]) && (linkexist==1)){ //condition to know if the link already exist\n linkexist=2; //If a similary links already between two spheres, linkexist value will be 2 to significate that we do not need to push this link in sphereLinks because he already exist in this list.\n }\n }\n if(linkexist==1){ //if linkexist=1, the links does not already exist in sphereLinks. So we can push in sphereLinks informations about the connected spheres to add the link between them\n sphereLinks.push([mindmap[\"spheres\"][i][0][\"sphere\"],mindmap[\"spheres\"][i][1][\"connected sphere(s)\"][k][\"sphere name\"]]);\n linkNames.push(mindmap[\"spheres\"][i][1][\"connected sphere(s)\"][k][\"link name\"]);\n }\n }\n if(i==0){ //this condition allow to empty the world (the entire mindmap) before we add the first object in it. See the 'jsonFileToMindMap' function arguments and if conditions to understand how it work\n jsonFileToMindMap(mindmap[\"spheres\"][i][0],\"beginning\"); //first call to the function jsonFileToMindMap\n }else{\n jsonFileToMindMap(mindmap[\"spheres\"][i][0],\"notthebeginning\"); //other calls to the function jsonFileToMindMap (without empty the mind map)\n } \n }\n jsonCreateLinks(sphereLinks, linkNames); //call to function jsonCreateLinks to add one link between the connected spheres. \n}",
"function readStartingData(){\n readUser = JSON.parse(fs.readFileSync('data/user.json'));\n listDoc = JSON.parse(fs.readFileSync('data/documents.json'));\n}",
"function getJson() {\n axios.get(`${protocol}feeds.ibood.com/nl/nl/offer.json`).then(result => {\n if (isNew(result.data)) {\n currentTitle = result.data.Title;\n\n // try and get the google price\n getGooglePrice(encodeURIComponent(result.data.Title)).then(price => {\n result.data.google = price;\n\n notify(result.data);\n }).catch(err => {\n\n result.data.google = \"n/a\";\n notify(result.data);\n });\n }\n });\n}",
"function get_files_from_server(){\n //link with file containning the files and folders distribution\n fetch(\"https://raw.githubusercontent.com/Eduardo-Filipe-Ferreira/ADS-Files-Repository/main/FilesLocation.json\")\n .then(response => response.json())\n .then(json => handle_server_files(json[0]));\n }",
"function fetchDataPhotographer(){\n fetch('./FishEyeData.json')\n .then(res => res.json())\n .then( function (datas) {\n for( data of datas.photographers){\n allPhotographers.push(data);\n let photographer = new Photographer(data.name, data.id, data.city, data.country, data.portrait, data.tagline, data.price, data.tags);\n createCards(photographer);\n /* eslint-disable */\n photographer.tags.forEach(value => { let brutValue = value;\n value = value.charAt(0).toUpperCase() + value.slice(1);\n value = '<a href=\"index.html?tag=' + brutValue + '\" class=\"card_ul_li\">#<span>'\n + value + '</span></a>';\n tagsArray.includes(value) ? '' : tagsArray.push(value);});\n /* eslint-enable */\n }\n showTagsNav();\n })\n .catch(error => alert ('Erreur : ' + error)); // eslint-disable-line no-alert\n}",
"function handleFile(err, data){\n if(err){\n console.log(err);\n }\n\n obj = JSON.parse(data);\n console.log(\"JSON FILE: \"+ obj.main.temp);\n }",
"function getTweets() {\n\tvar returnString = \"\";\n\tfor(i = 0; i < jsonFileObj.length; i++){\n\t\treturnString = returnString + \"{\\r\\n<br />\" +\n\t\t\t\"\\\"created-at\\\": \\\"\" + jsonFileObj[i].created_at + \"\\\"\\r\\n<br />\" +\n\t\t\t\"\\\"id_str\\\": \\\"\" + jsonFileObj[i].id_str + \"\\\"\\r\\n<br />\" +\n\t\t\t\"\\\"text\\\": \\\"\" + jsonFileObj[i].text + \"\\\"\\r\\n<br />\" +\n\t\t\t\"}\\r\\n<br />\";\n\t}\n\treturn returnString\n}",
"function getEatFlKeys (url){\n fetch(url, {headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'user-key': \"e520bba2bf7f434d5803aa5e81d5ad4a\",\n }}) \n .then( function(response){\n return response.json()\n })\n .then(function (data) {\n eatAt1.textContent = data.best_rated_restaurant[0].restaurant.name\n eatAt2.textContent = data.best_rated_restaurant[1].restaurant.name\n eatAt3.textContent = data.best_rated_restaurant[2].restaurant.name\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exclude invalid node from given list | function excludeInvalidNodes(allNodes, invalidNodes) {
var toReturn = null;
if(allNodes != null) {
if(invalidNodes != null && !invalidNodes.isEmpty()) {
var lenght = allNodes.length;
toReturn = new Packages.java.util.ArrayList();
for (var i = 0; i < lenght; i++) {
var currentNode = allNodes[i];
if(!invalidNodes.contains(currentNode)) {
toReturn.add(currentNode);
}
}
} else {
toReturn = Packages.java.util.Arrays.asList(allNodes);
}
}
return toReturn;
} | [
"function filteredElements(nodeList) {\n var filtered = [];\n for (var i = 0; i < nodeList.length; i++) {\n var node = nodeList[i];\n if (node.nodeType !== 3) { // Don't process text nodes\n var $element = $(node);\n if ( $element.closest('.ant,.ant_indicator,.ant-custom-cta-container').length === 0 ) {\n filtered.push($element);\n }\n }\n }\n return filtered;\n }",
"unblockedNodes () {\n const unblocked = []\n\n for (let node = 0; node < this.n; node++) {\n if (!this.isBlocked(node)) unblocked.push(node)\n }\n\n return unblocked\n }",
"removeNode(value){\n if(this.includes(value)){\n\n let currentNode = this.head;\n while(currentNode.next.value !== value){\n currentNode = currentNode.next;\n }\n currentNode.next = currentNode.next.next;\n }else{\n throw new Error('Value not in list');\n }\n }",
"_findAndRemoveEmptyList() {\n this.wwe.get$Body().find('ul,ol').each((index, node) => {\n if (!(FIND_LI_ELEMENT.test(node.innerHTML))) {\n $(node).remove();\n }\n });\n }",
"function nonFriends(name, list) {\n var holder;\n for(var i = 0; i < list.length; i++) {\n if(name === list[i].name) {\n holder = i;\n }\n }\n var notFriendsList = [];\n for(var j = 0; j < list.length; j++) {\n if(list[j].name !== name) {\n if(!isFriend(list[j].name, list[holder])) notFriendsList.push(list[j].name);\n }\n }\n return notFriendsList;\n}",
"function MODIFIER_NO_VALIDATION$static_(){LinkListBEMEntities.MODIFIER_NO_VALIDATION=( LinkListBEMEntities.BLOCK.createModifier(\"no-validation\"));}",
"function removeNegatives (sList) {\n let current = sList.head;\n let runner; // using a runner to find next non-negative node, rather than breaking and forging links one node at a time\n if (current === null) {\n return null;\n }\n while (current) {\n if (current.next && current.next.value < 0) { // if there is a next node and its value is negative...\n runner = current.next.next; // we start and the next node's next node (which may be null)\n while (runner) { // as long as that next next node exists, we'll iterate until we hit a non-negative node or null\n if (runner.value < 0) {\n runner = runner.next;\n } else {\n break; // if we break, we've found a non-negative node (if runner were null, the while loop doesn't run)\n }\n }\n current.next = runner; // now we skip all of the intervening negative numbers; note current.next could also be set to null if runner reached the end of the list\n }\n current = current.next;\n }\n if (sList.head.value < 0) { // the only situation we haven't addressed is if head is negative, but now we know that the rest of the list consists only of positive nodes (if the rest of the list exists)\n sList.head = sList.head.next; // so, we can just set head to its next. then either head is positive or entire list is null\n }\n return sList;\n}",
"extractLists({ remove = false, ignoreErrors = false } = {}) {\n const lists = {}; // has scalar keys so could be a simple Object\n const onError = ignoreErrors ? (() => true) :\n ((node, message) => { throw new Error(`${node.value} ${message}`); });\n\n // Traverse each list from its tail\n const tails = this.getQuads(null, IRIs[\"default\"].rdf.rest, IRIs[\"default\"].rdf.nil, null);\n const toRemove = remove ? [...tails] : [];\n tails.forEach(tailQuad => {\n const items = []; // the members found as objects of rdf:first quads\n let malformed = false; // signals whether the current list is malformed\n let head; // the head of the list (_:b1 in above example)\n let headPos; // set to subject or object when head is set\n const graph = tailQuad.graph; // make sure list is in exactly one graph\n\n // Traverse the list from tail to end\n let current = tailQuad.subject;\n while (current && !malformed) {\n const objectQuads = this.getQuads(null, null, current, null);\n const subjectQuads = this.getQuads(current, null, null, null);\n let quad, first = null, rest = null, parent = null;\n\n // Find the first and rest of this list node\n for (let i = 0; i < subjectQuads.length && !malformed; i++) {\n quad = subjectQuads[i];\n if (!quad.graph.equals(graph))\n malformed = onError(current, 'not confined to single graph');\n else if (head)\n malformed = onError(current, 'has non-list arcs out');\n\n // one rdf:first\n else if (quad.predicate.value === IRIs[\"default\"].rdf.first) {\n if (first)\n malformed = onError(current, 'has multiple rdf:first arcs');\n else\n toRemove.push(first = quad);\n }\n\n // one rdf:rest\n else if (quad.predicate.value === IRIs[\"default\"].rdf.rest) {\n if (rest)\n malformed = onError(current, 'has multiple rdf:rest arcs');\n else\n toRemove.push(rest = quad);\n }\n\n // alien triple\n else if (objectQuads.length)\n malformed = onError(current, 'can\\'t be subject and object');\n else {\n head = quad; // e.g. { (1 2 3) :p :o }\n headPos = 'subject';\n }\n }\n\n // { :s :p (1 2) } arrives here with no head\n // { (1 2) :p :o } arrives here with head set to the list.\n for (let i = 0; i < objectQuads.length && !malformed; ++i) {\n quad = objectQuads[i];\n if (head)\n malformed = onError(current, 'can\\'t have coreferences');\n // one rdf:rest\n else if (quad.predicate.value === IRIs[\"default\"].rdf.rest) {\n if (parent)\n malformed = onError(current, 'has incoming rdf:rest arcs');\n else\n parent = quad;\n }\n else {\n head = quad; // e.g. { :s :p (1 2) }\n headPos = 'object';\n }\n }\n\n // Store the list item and continue with parent\n if (!first)\n malformed = onError(current, 'has no list head');\n else\n items.unshift(first.object);\n current = parent && parent.subject;\n }\n\n // Don't remove any quads if the list is malformed\n if (malformed)\n remove = false;\n // Store the list under the value of its head\n else if (head)\n lists[head[headPos].value] = items;\n });\n\n // Remove list quads if requested\n if (remove)\n this.removeQuads(toRemove);\n return lists;\n }",
"ignore(count) {\n\t\tfor (var length = this.index + count; this.index < length; ++this.index) {\n\t\t\tthis.get(this.index).dependOn(FALSE_PREDICATE).dispatch();\n\t\t}\n\t}",
"function checkIfRemoveList() {\n\t\tif (!current.length && list > 0) {\n\t\t\tthis.data.pop();\n\t\t\tcurrent = this.data[--list];\n\t\t}\n\t}",
"unassigned() {\n\t\treturn this.minerids.filter(m => !this.minerpool[m]);\n\t\t// var list = [];\n\t\t// if(Object.keys(this.minerpool).length == this.minerids.length) return [];\n\n\t\t// const assigned = Object.keys(this.minerpool);\n\t\t// for(var m of this.minerids) {\n\t\t// \tif(assigned.indexOf(m) == -1) list.push(m);\n\t\t// }\n\n\t\t// return list;\n\t}",
"function remove(items){items=getList(items);for(var i=0;i<items.length;i++){var item=items[i];if(item&&item.parentElement){item.parentNode.removeChild(item);}}}",
"visitNot_test(ctx) {\r\n console.log(\"visitNot_test\");\r\n if (ctx.NOT() !== null) {\r\n return {\r\n type: \"UnaryExpression\",\r\n operator: \"not\",\r\n operand: this.visit(ctx.not_test()),\r\n };\r\n } else {\r\n return this.visit(ctx.comparison());\r\n }\r\n }",
"function remove(xs, pred) /* forall<a> (xs : list<a>, pred : (a) -> bool) -> list<a> */ {\n return filter(xs, function(x /* 23638 */ ) {\n return !((pred(x)));\n });\n}",
"get not() {\n return {\n /**\n * Returns true if all PageElements managed by PageElementMap currently do not exist.\n *\n * @param filterMask can be used to skip the invocation of the `exists` function for some or all managed\n * PageElements\n */\n exists: (filterMask) => {\n return this._node.eachCheck(this._node.$, element => element.currently.not.exists(), filterMask, true);\n },\n /**\n * Returns true if all PageElements managed by PageElementMap are currently not visible.\n *\n * @param filterMask can be used to skip the invocation of the `isVisible` function for some or all managed\n * PageElements\n */\n isVisible: (filterMask) => {\n return this._node.eachCheck(this._node.$, element => element.currently.not.isVisible(), filterMask, true);\n },\n /**\n * Returns true if all PageElements managed by PageElementMap are currently not enabled.\n *\n * @param filterMask can be used to skip the invocation of the `isEnabled` function for some or all managed\n * PageElements\n */\n isEnabled: (filterMask) => {\n return this._node.eachCheck(this._node.$, element => element.currently.not.isEnabled(), filterMask, true);\n },\n /**\n * Returns true if the actual texts of all PageElements managed by PageElementMap currently do not equal the\n * expected texts.\n *\n * @param texts the expected texts supposed not to equal the actual texts\n */\n hasText: (text) => {\n return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.hasText(expected), text);\n },\n /**\n * Returns true if all PageElements managed by PageElementMap currently do not have any text.\n *\n * @param filterMask can be used to skip the invocation of the `hasAnyText` function for some or all managed\n * PageElements\n */\n hasAnyText: (filterMask) => {\n return this._node.eachCheck(this._node.$, (element) => element.currently.not.hasAnyText(), filterMask, true);\n },\n /**\n * Returns true if the actual texts of all PageElements managed by PageElementMap currently do not contain the\n * expected texts.\n *\n * @param texts the expected texts supposed not to be contained in the actual texts\n */\n containsText: (text) => {\n return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.containsText(expected), text);\n },\n /**\n * Returns true if the actual direct texts of all PageElements managed by PageElementMap currently do not equal\n * the expected direct texts.\n *\n * A direct text is a text that resides on the level directly below the selected HTML element.\n * It does not include any text of the HTML element's nested children HTML elements.\n *\n * @param directTexts the expected direct texts supposed not to equal the actual direct texts\n */\n hasDirectText: (directText) => {\n return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.hasDirectText(expected), directText);\n },\n /**\n * Returns true if all PageElements managed by PageElementMap currently do not have any direct text.\n *\n * A direct text is a text that resides on the level directly below the selected HTML element.\n * It does not include any text of the HTML element's nested children HTML elements.\n *\n * @param filterMask can be used to skip the invocation of the `hasAnyDirectText` function for some or all managed\n * PageElements\n */\n hasAnyDirectText: (filterMask) => {\n return this._node.eachCheck(this._node.$, (element) => element.currently.not.hasAnyDirectText(), filterMask, true);\n },\n /**\n * Returns true if the actual direct texts of all PageElements managed by PageElementMap currently do not contain\n * the expected direct texts.\n *\n * A direct text is a text that resides on the level directly below the selected HTML element.\n * It does not include any text of the HTML element's nested children HTML elements.\n *\n * @param directTexts the expected direct texts supposed not to be contained in the actual direct texts\n */\n containsDirectText: (directText) => {\n return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.containsDirectText(expected), directText);\n },\n };\n }",
"function remove (list.bookName) {\nif (list.indexOf(bookName) => 0) {\n\nreturn list.filter(item) => !== bookName);\n}\n}",
"function removeOrphanedChildren(children, unmountOnly) {\n\tfor (var i = children.length; i--;) {\n\t\tif (children[i]) {\n\t\t\trecollectNodeTree(children[i], unmountOnly);\n\t\t}\n\t}\n}",
"function contentEditableFilter (nodes) {\n nodes.forEach((node) => {\n if (!!node.attr('contenteditable')) {\n node.attr('contenteditable', null)\n node.firstChild.unwrap()\n }\n })\n}",
"function clearNodeOptions() {\n var startList = document.getElementById(\"selectStart\");\n var goalList = document.getElementById(\"selectGoal\");\n\n let length = startList.length;\n for (i = length - 1; i >= 1; i--) {\n startList.removeChild(startList.childNodes[i]);\n goalList.removeChild(goalList.childNodes[i]);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply the function to all arguments by batches | function batchCall(fn, args) {
var BATCH_SIZE = 512;
if (args.length > 0) {
var batch = args.slice(0, BATCH_SIZE);
var rest = args.slice(BATCH_SIZE);
for (var i = 0; i < batch.length; i++) fn(batch[i]);
requestAnimationFrame(batchCall.bind(null, fn, rest));
}
} | [
"function for_each(){\n var param_len = arguments[0].length;\n var proc = arguments[0];\n while(!is_empty_list(arguments[1])){\n var params = [];\n for(var j = 1; j < 1+param_len; j++) {\n params.push(head(arguments[j]));\n arguments[j] = tail(arguments[j]);\n }\n proc.apply(proc, params);\n\t}\n}",
"function applyEach(thing, func) {\n var i;\n if (isArray(thing)) {\n for (i = 0; i < thing.length; i += 1) {\n thing[i] = func(thing[i], i);\n }\n } else {\n var keys = Object.keys(thing);\n for (i = 0; i < keys.length; i += 1) {\n var key = keys[i];\n thing[key] = func(thing[key], key);\n }\n }\n}",
"function apply(args, fn) {\n return fn.apply(undefined, args);\n }",
"static iterate(f, first_args, length) {\n let l = length || 0xffff,\n arr = [],\n c = 0;\n\n while (c < l) {\n arr.push((c === 0) ? first_args : f(arr[c - 1]));\n c = c + 1;\n }\n return arr;\n }",
"function spreadForFunctionArgs(){\n multipleParams(1,2,3);\n\n let args = [1,2,3];\n multipleParams(...args);\n}",
"function operate(array, func) {\r\n if (array) {\r\n for (var n=0; n<array.length; n++) {\r\n func(array[n], n);\r\n }\r\n }\r\n return array;\r\n}",
"function apply(context, fn) {\n return fn.apply(context,\n Array.prototype.slice.call(arguments).splice(2)\n );\n}",
"function runBatch() {\n if (visitationFn === \"deterministic\") {\n for (let y = 0; y < gridSize; y++) {\n for (let x = 0; x < gridSize; x++) {\n updateSpin(x, y);\n }\n }\n }\n else if (visitationFn === \"random\") {\n for (let i = 0; i < N; i++) {\n let x = Math.floor(Math.random() * gridSize);\n let y = Math.floor(Math.random() * gridSize);\n updateSpin(x, y);\n }\n }\n drawLattice();\n}",
"forEach(elements, thunk) {\n var index = 0;\n elements.forEach((function(element) {\n thunk(element, this, index++);\n }).bind(this));\n return this;\n }",
"function makeIteratorFunction(f, set) {\n\t\t\treturn function() {\n\t\t\t\tvar result = [];\n\t\t\t\tfor ( var i = 0; i < set.length; i++) {\n\t\t\t\t\tresult.push(set[i][f].apply(set[i][f], arguments));\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t};\n\t\t}",
"function _fast_apply(f, x) /* forall<a,b,e> (f : (a) -> e b, x : a) -> e b */ {\n return f(x);\n}",
"function sumArgs() {\r\n return [].reduce.call(arguments, function(a, b) {\r\n return a + b;\r\n });\r\n}",
"function run() {\n var index = -1;\n var input = slice$1.call(arguments, 0, -1);\n var done = arguments[arguments.length - 1];\n\n if (typeof done !== 'function') {\n throw new Error('Expected function as last argument, not ' + done)\n }\n\n next.apply(null, [null].concat(input));\n\n // Run the next `fn`, if any.\n function next(err) {\n var fn = fns[++index];\n var params = slice$1.call(arguments, 0);\n var values = params.slice(1);\n var length = input.length;\n var pos = -1;\n\n if (err) {\n done(err);\n return\n }\n\n // Copy non-nully input into values.\n while (++pos < length) {\n if (values[pos] === null || values[pos] === undefined) {\n values[pos] = input[pos];\n }\n }\n\n input = values;\n\n // Next or done.\n if (fn) {\n wrap_1(fn, next).apply(null, input);\n } else {\n done.apply(null, [null].concat(input));\n }\n }\n }",
"function OXN_ALift_Apply(async_f, xc, env, args) {\n this.xc = xc;\n this.xc.current = this;\n \n var pars = [bind(this.cont, this)];\n pars = pars.concat(args);\n this.abort_f = async_f.apply(env, pars);\n}",
"function benchmarkN(name, n, f) {\n console.log(name + ':');\n var args = Array.prototype.slice.call(arguments).slice(3);\n var s = Date.now();\n \n for(var i = 0; i < n; i++){\n f.apply(null, args);\n }\n\n var t = Date.now() - s;\n console.log('time = ' + t + 'msec');\n return t;\n}",
"function Apply(/* fexp, aexp1, aexp2, ... */) {\n precondition_arg_list(arguments);\n return new OEN_Apply(arguments[0], slice_args(arguments, 1));\n}",
"function each( a, f ){\n\t\tfor( var i = 0 ; i < a.length ; i ++ ){\n\t\t\tf(a[i])\n\t\t}\n\t}",
"function forEachElement (func) {\n selectors.map((selector, count) => {\n if (!selectMultipleOfElement) {\n func(selector, document.querySelector(selector))\n } else {\n [...document.querySelectorAll(selector)].forEach(element => {\n func(`${selector}_${count}`, element)\n })\n }\n })\n }",
"map(fn, iterable) {\n return (function*() {\n for (let val of iterable) {\n yield fn(val);\n }\n })();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creative feature: Users can create group events that display on multiple users calendars the user is asked what other group members they want in the group event, if they input a user that doesnt exist, they are notifed that the user doesnt exist, but the event is still added for all other valid users and the user themself. | function groupEvent(event) {
event.preventDefault();
const eventtitle = document.getElementById("groupeventtitle").value;
const eventdate = document.getElementById("groupeventdate").value;
const eventtime = document.getElementById("groupeventtime").value;
var eventcategory = document.getElementById("groupeventcategory").value
// event cannot be added if title, date, or time field are empty all are required
if (eventcategory.length == 0) {
eventcategory = "None";
}
if (eventtitle.length == 0 || eventdate.length == 0 || eventtime.length == 0) {
alert(`Add Group Event Failed: title, date, and time are required`);
document.getElementById('groupevents').style.display = 'none';
ischecked();
}
else {
var group = prompt("How many additional group members","");
var group_number= parseInt(group);
for(var i = 0; i < group_number; i++){
var member = prompt("Username of a group member","");
const data = {'eventtitle': eventtitle, 'eventdate': eventdate, 'eventtime': eventtime, 'eventcategory': eventcategory, 'user':member, 'token':session_token};
fetch("group_event.php", {
method: 'POST',
body: JSON.stringify(data),
headers: { 'content-type': 'application/json' }
})
.then(response => response.text())
.then(data => check = data)
.then(()=>{
console.log(check)
if(check.includes("User does not exist")){
alert("One or more users do not exist");
ischecked();
}
});
}
const data = {'eventtitle': eventtitle, 'eventdate': eventdate, 'eventtime': eventtime, 'eventcategory': eventcategory,'token':session_token};
fetch("createevent.php", {
method: 'POST',
body: JSON.stringify(data),
headers: { 'content-type': 'application/json' }
})
.then(response => response.text())
.then(data => check = data)
.then(()=>{
console.log(check)
if(check.includes("Add Success")){
alert("Event Added");
ischecked();
}
});
ischecked();
document.getElementById("addgroupeventsform").reset();
document.getElementById('groupevents').style.display="none";
}
} | [
"async afterAddMembers ({ groupId, newUserIds, reactivatedUserIds }) {\n const zapierTriggers = await ZapierTrigger.forTypeAndGroups('new_member', groupId).fetchAll()\n\n const members = await User.query(q => q.whereIn('id', newUserIds.concat(reactivatedUserIds))).fetchAll()\n\n if (zapierTriggers && zapierTriggers.length > 0) {\n const group = await Group.find(groupId)\n for (const trigger of zapierTriggers) {\n const response = await fetch(trigger.get('target_url'), {\n method: 'post',\n body: JSON.stringify(members.map(m => ({\n id: m.id,\n avatarUrl: m.get('avatar_url'),\n bio: m.get('bio'),\n contactEmail: m.get('contact_email'),\n contactPhone: m.get('contact_phone'),\n facebookUrl: m.get('facebook_url'),\n linkedinUrl: m.get('linkedin_url'),\n location: m.get('location'),\n name: m.get('name'),\n profileUrl: Frontend.Route.profile(m, group),\n tagline: m.get('tagline'),\n twitterName: m.get('twitter_name'),\n url: m.get('url'),\n // Whether this user was previously in the group and is being reactivated\n reactivated: reactivatedUserIds.includes(m.id),\n // Which group were they added to, since the trigger can be for multiple groups\n group: { id: group.id, name: group.get('name'), url: Frontend.Route.group(group) }\n }))),\n headers: { 'Content-Type': 'application/json' }\n })\n // TODO: what to do with the response? check if succeeded or not?\n }\n }\n\n for (const member of members) {\n mixpanel.track(AnalyticsEvents.GROUP_NEW_MEMBER, {\n distinct_id: member.id,\n groupId: [groupId]\n })\n }\n }",
"function AddMemberToGroup(event) {\n\t\t\t\n\t\tvar grp=event.target.name;\n\t\t\n\t\t//alert(\"This is Group id \" + event.target.name + \" : \" + event.target.id);\n\t\t\n\t\t$.ajax({\n\t\t\turl : 'http://localhost:8080/facebook_v01/webapi/groupdetails/addMemberToGroup/'\n\t\t\t\t\t+ event.target.name + '/' + event.target.id,\n\t\t\ttype : 'POST',\n\t\t\tasync:false,\n\t\t\tcomplete : function(request, textStatus, errorThrown){\n\t\t\t\tif(request.status===201){\n\t\t\t\t\t\n\t\t\t\t\t//location.reload();\n\t\t\t\t\n\t\t\t\t\t$('#AddMemberToGrouplist1').empty();\n\t\t\t\t\t$('#AddMemberToGrouplist2').empty();\n\t\t\t\t\taddComponentAddMembersToGroupList(grp);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\twindow.location.href = 'errorpage.html';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}",
"async addMembers (usersOrIds, attrs = {}, { transacting } = {}) {\n const updatedAttribs = Object.assign(\n {},\n {\n active: true,\n role: GroupMembership.Role.DEFAULT,\n settings: {\n sendEmail: true,\n sendPushNotifications: true,\n showJoinForm: false\n }\n },\n pick(omitBy(attrs, isUndefined), GROUP_ATTR_UPDATE_WHITELIST)\n )\n\n const userIds = usersOrIds.map(x => x instanceof User ? x.id : x)\n const existingMemberships = await this.memberships(true)\n .query(q => q.whereIn('user_id', userIds)).fetch({ transacting })\n const reactivatedUserIds = existingMemberships.filter(m => !m.get('active')).map(m => m.get('user_id'))\n const existingUserIds = existingMemberships.pluck('user_id')\n const newUserIds = difference(userIds, existingUserIds)\n const updatedMemberships = await this.updateMembers(existingUserIds, updatedAttribs, { transacting })\n\n const newMemberships = []\n const defaultTagIds = (await GroupTag.defaults(this.id, transacting)).models.map(t => t.get('tag_id'))\n\n for (const id of newUserIds) {\n const membership = await this.memberships().create(\n Object.assign({}, updatedAttribs, {\n user_id: id,\n created_at: new Date()\n }), { transacting })\n newMemberships.push(membership)\n // Subscribe each user to the default tags in the group\n await User.followTags(id, this.id, defaultTagIds, transacting)\n }\n\n // Increment num_members\n // XXX: num_members is updated every 10 minutes via cron, we are doing this here too for the case that someone joins a group and moderator looks immediately at member count after that\n if (newUserIds.length > 0) {\n await this.save({ num_members: this.get('num_members') + newUserIds.length }, { transacting })\n }\n\n Queue.classMethod('Group', 'afterAddMembers', {\n groupId: this.id,\n newUserIds,\n reactivatedUserIds\n })\n\n return updatedMemberships.concat(newMemberships)\n }",
"function createGame() {\n if(document.getElementById('opponent').value && document.getElementById('location').value &&\n document.getElementById('start-date').value && document.getElementById('start-time').value) {\n var email;\n firebase.auth().onAuthStateChanged(function(user) {\n if(user) {\n email = user.email.replace('.', '').replace('@', '');\n console.log(email);\n db.collection(\"users\").where(\"email\", \"==\", email).get().then(function(querySnapshot) {\n querySnapshot.forEach(function(doc) {\n var team = doc.data().team;\n console.log(doc.id);\n db.collection(\"teams\").doc(team).collection(\"schedule\").doc(document.getElementById('start-date').value +\n \" \" + document.getElementById('opponent').value).set({\n title: document.getElementById('opponent').value,\n location: document.getElementById('location').value,\n startDate: document.getElementById('start-date').value,\n startTime: document.getElementById('start-time').value,\n eventType: 'game'\n }).then(function(result) {\n window.location = \"schedule-admin.html\";\n return false;\n });\n });\n });\n }\n });\n }\n else {\n document.getElementById(\"warning\").innerHTML = \"Please fill out all event information!\";\n return false;\n }\n}",
"function addGroup(id, name)\n{\n var newplace = window.document.epersongroup.group_ids.options.length;\n\n\tif (newplace > 0 && window.document.epersongroup.group_ids.options[0].value == \"\")\n {\n newplace = 0;\n }\n\n // First we check to see if group is already there\n for (var i = 0; i < window.document.epersongroup.group_ids.options.length; i++)\n {\n // is it in the list already\n if (window.document.epersongroup.group_ids.options[i].value == id)\n {\n newplace = -1;\n }\n\n // are we trying to add the new group to the new group on an Edit Group page (recursive)\n if (window.document.epersongroup.group_id)\n {\n if (window.document.epersongroup.group_id.value == id)\n {\n newplace = -1;\n }\n }\n }\n\n if (newplace > -1)\n {\n window.document.epersongroup.group_ids.options[newplace] = new Option(name + \" (\" + id + \")\", id);\n }\n}",
"function confirmationSelectionHandler(){\n const header = SheetsLibrary.getHeaderAsObjFromSheet(ActiveSheet, 1);\n const allEvents = SheetsLibrary.getAllRowsAsObjInArr(ActiveSheet, 1);\n const events = SheetsLibrary.getSelectedRowsAsObjInArr(ActiveSheet, 1);\n const selectedEvent = events[0];\n console.log(selectedEvent);\n if( !isReady() ) return\n\n try {\n // Update Jour Fixe Calendar Event\n const jourFixeCal = CAL.getCalendarById(officeHourId);\n const eventInCal = jourFixeCal.getEventById(selectedEvent.id);\n const newTitleForEvent = \"Jour Fixe | \" + selectedEvent.user;\n const start = eventInCal.getStartTime();\n const end = eventInCal.getEndTime();\n \n let calDescription = getSFLinkFromEmail(selectedEvent.Email) ? `Hier ist der Link zu deinen Botschafter-Kampagnen: ` + getSFLinkFromEmail(selectedEvent.Email) : \"\"; \n \n // Create Calendar Event in personal Call\n const myCal = CAL.getCalendarById(myCalId);\n const newCalEvent = myCal.createEvent( newTitleForEvent, start, end);\n eventInCal.setTitle( newTitleForEvent );\n\n if( newCalEvent ){\n // Add the Meet Link to the Description\n // Need to either get the Meet Link, if it is there, or create a Meeting using the Advanced Calendar API\n const meetLink = getMeetLink(newCalEvent.getId()); //Calendar.Events.get(myCalId, newCalEvent.getId());\n if( meetLink )\n calDescription += `\\nHier ist der Link zum Gespräch: ${meetLink}`;\n newCalEvent.setDescription( calDescription );\n eventInCal.setDescription( calDescription );\n \n updateField( selectedEvent.rowNum, header.status, newCalEvent.getId() );\n disableOtherEventsFromThisSubmission(); \n newCalEvent.addGuest( selectedEvent.Email );\n sendConfirmationToBotschafter( {\n email: selectedEvent.Email,\n subject: `Bestätigung Jour-Fixe am ${selectedEvent.Datum}`,\n body: `Hi ${selectedEvent.user},\\nhiermit bestätige ich deinen Jour-Fixe-Termin am ${selectedEvent.Datum} um ${selectedEvent.Uhrzeit}.\\nLiebe Grüße,\\nShari`\n });\n }\n } catch(err) {\n console.error(\"Fehler: \"+err);\n alert(\"Could not create Event: \"+err.message);\n }\n\n // Disable other events from the same submission \n function disableOtherEventsFromThisSubmission( ){\n const eventsFromThisSubmission = allEvents.filter( event => event.submissionId === selectedEvent.submissionId && event.id != selectedEvent.id ) ;\n eventsFromThisSubmission.forEach( event => updateField( event.rowNum, header.status, \"disabled\") );\n }\n \n // Checks to see if event selected is empty and not disabled\n function isReady(){\n if( events.length > 1 ){\n alert(\"Bitte nur eine auswählen\");\n return\n }\n \n if( selectedEvent.status === \"disabled\" ){\n alert(\"Eintrag ist disabled und kann nicht erstellt werden\");\n return\n }\n \n if( selectedEvent.status != \"\" ){\n alert(\"Eintrag hat bereits einen Status und kann deshalb nicht neu erstellt werden.\");\n return\n }\n \n return true\n }\n}",
"function userform_addGroupToUser() {\n\tvar RN = \"userform_addGroupToUser\";\n\tvar su = userform_lookupSelectedUser();\n\tvar agl = document.getElementById('AvailableGroupList');\n\tvar gl = document.getElementById('GroupList');\n\tif (agl && gl) {\n\t\tunHighLightList(\"GroupList\");\n\t\tunHighLightList(\"AccessControlList\");\n\t\tfor (var i = agl.options.length-1 ; i > 0 ; i--) {\n\t\t\tdbg (1, RN + \": move agl/\" + i + \" to gl\");\n\t\t\tif (agl.options[i].selected) {\n\t\t\t\tvar opt = agl.options[i];\n\t\t\t\tif (browserType_IE) agl.options[i] = null;\n\t\t\t\tgl.options[gl.options.length] = opt;\n\t\t\t\tuserhash[su][opt.value] = new Object;\n\t\t\t}\n\t\t}\n\t\tenableList(\"AccessControlList\");\n\t\tDBG_objDump(userhash, \"userhash\");\n\t\tuserform_setAclHash();\n\t\tsortList(\"GroupList\");\n\t\tsortList(\"AvailableGroupList\");\n\t} else {\n\t\tdbg (1, RN + \": cant find AvailableGroupList and/or GroupList object\");\n\t}\n\treturn false;\n}",
"function eventAddChatGroup(data){\n\n\n var time_=jQuery.timeago(data.datetime);/*obtengo el valor del tiempo en texto*/\n var inyectHTML=\"\";\n\n var message=data.message;\n var emoticons = {\n ':)' : '1-feliz.gif',\n ':(' : 'enfadado.gif'\n }, url = \"emoticonos/\";\n // a simple regex to match the characters used in the emoticons\n message = message.replace(/[:\\-)(D]+/g, function (match) {\n return typeof emoticons[match] != 'undefined' ?\n '<img src=\"'+url+emoticons[match]+'\" width=\"20px\"/>' :\n match;\n });\n\n\n\n\n\n if(data.name.email==JSON.parse($.session.get(\"ObjectUser\")).email)\n {\n inyectHTML='<div class=\"mensaje-autor\">'+/*Mensaje del usuario que inició sesión*/\n '<img width=\"50\" src=\"https://desk-cdn.s3.amazonaws.com/unknown.png\" class=\"img-circle\"> '+/*Foto de perfil*/\n '<div class=\"flecha-derecha\"></div>'+/* <!--Mensaje Alineado a la Izquierda-->*/\n '<div class=\"contenido\">'+\n message+ /*<!--Mensaje-->*/\n '</div>'+\n '<div class=\"fecha\">'+time_+'</div>'+/* <!--Hora-->*/\n '</div>';\n }else{\n inyectHTML='<div class=\"mensaje-amigo\">'+ <!--Mensaje de otro contactol-->\n '<div class=\"contenido\">'+\n message+/* <!--Mensaje-->*/\n '</div>'+\n '<div class=\"flecha-izquierda\"></div>'+/* <!--Mensaje Alineado a la Izquierda-->*/\n '<img width=\"50\" src=\"https://desk-cdn.s3.amazonaws.com/unknown.png\" class=\"img-circle\">'+/* <!--Foto de perfil-->*/\n '<div class=\"fecha\">'+time_+' - <span class=\"user-message\" style=\"color: rgb(32, 200, 162);font-weight: bold;\">'+data.name.Name+'</span></div>'/* <!--Hora-->*/\n '</div>';\n }\n\n\n\n $(\".inyect-commit\").append(inyectHTML);\n $(\"#bienvenida\").addClass('hide');\n $(\"#commit-content\").val(\"\");\n\n }",
"function event_create_check(eventCreateForm)\n{\n\t/*++++++++++ first of all check uid ++++++++++*/\n\tvar pid = $(\"#unisalepid\").val();\n\tif ( pid <= 0 || pid == null )\n\t{\n\t\talert(\"请先登陆\");\n\t\treturn false;\n\t}\n\t/*========== first of all check uid ==========*/\n\tvar html = \"<p>hello</p>\";\n\n\tvar url_hash = window.location.hash;\n\tif ( url_hash != '' )\n\t{\n\t\twindow.location.hash = \"\";\n\t}\n\n\tfor ( var i = 0; i < 10; i++ )\n\t{\n\t\t$(\"#ul-errorlist-\"+i).html(\"\");\n\t}\n\n\t/*+++++ check event title +++++*/\n\tvar title = $(\"input[name='event_title']\").val();\n\tif ( (typeof(title) == \"undefined\") || (title == '') )\n\t{\n\t\thtml = \"<li>您必须输入活动名称.</li>\";\n\t\t$(\"#ul-errorlist-1\").html(html);\n\t\t$(\"input[name='event_title']\").focus();\n\t\treturn false;\n\t}\n\t/*===== check event title =====*/\n\n\t/*+++++ check event location +++++*/\n\tvar location_locale \t=\t$(\"input[name='event_location_locale']\").val();\n\tvar location_street \t=\t$(\"input[name='event_location_street']\").val();\n\tvar location_city \t\t=\t$(\"input[name='event_location_city']\").val();\n\tvar location_state\t\t=\t$(\"#flat-ui-event-location-state\").val();\n\tif ( (typeof(location_locale) == \"undefined\") || (location_locale == '') )\n\t{\n\t\thtml = \"<li>您必须输入活动地址.</li>\";\n\t\t$(\"#ul-errorlist-2\").html(html);\n\t\t$(\"input[name='event_location_locale']\").focus();\n\t\treturn false;\n\t}\n\telse if ( (typeof(location_street) == \"undefined\") || (location_street == '') )\n\t{\n\t\thtml = \"<li>请输入街道名, 门牌号.</li>\";\n\t\t$(\"#ul-errorlist-2\").html(html);\n\t\t$(\"input[name='event_location_street']\").focus();\n\t\treturn false;\n\t}\n\telse if ( (typeof(location_city) == \"undefined\") || (location_city == '') )\n\t{\n\t\thtml = \"<li>请输入城市名.</li>\";\n\t\t$(\"#ul-errorlist-2\").html(html);\n\t\t$(\"input[name='event_location_city']\").focus();\n\t\treturn false;\n\t}\n\t// if ( (typeof(location_state) == \"undefined\") || (location_state == '') || (location_state == null) )\n\t// {\n\t// \thtml = \"<li>请选择州.</li>\";\n\t// \t$(\"#ul-errorlist-2\").html(html);\n\t// \t$(\".event_location_state .dropdown-toggle\").focus();\n\t// \treturn false;\n\t// }\n\t/*===== check event location =====*/\n\n\t/*+++++ check event time +++++*/\n\tvar time_start_date\t=\t$(\"#datepicker-01\").val();\n\tvar time_start_hh \t=\t$(\"#flat-ui-event-time-start-hh\").val();\n\tvar time_start_mm \t=\t$(\"#flat-ui-event-time-start-mm\").val();\n\tvar time_end_date\t=\t$(\"#datepicker-02\").val();\n\tvar time_end_hh \t=\t$(\"#flat-ui-event-time-end-hh\").val();\n\tvar time_end_mm \t=\t$(\"#flat-ui-event-time-end-mm\").val();\n\tif ( (typeof(time_start_date) == \"undefined\") || (time_start_date == '') )\n\t{\n\t\thtml = \"<li>请选择活动开始日期.</li>\";\n\t\t$(\"#ul-errorlist-3\").html(html);\n\t\t$(\"#datepicker-01\").focus()\n\t\treturn false;\n\t}\n\telse if ( (typeof(time_start_hh) == \"undefined\") || (time_start_hh == '') || (time_start_hh == null) )\n\t{\n\t\thtml = \"<li>请选择活动开始日期的具体时间.</li>\";\n\t\t$(\"#ul-errorlist-3\").html(html);\n\t\t$(\".input-time-start-hh .dropdown-toggle\").focus();\n\t\treturn false;\n\t}\n\telse if ( (typeof(time_start_mm) == \"undefined\") || (time_start_mm == '') || (time_start_mm == null) )\n\t{\n\t\thtml = \"<li>请选择活动开始日期的具体时间.</li>\";\n\t\t$(\"#ul-errorlist-3\").html(html);\n\t\t$(\".input-time-start-mm .dropdown-toggle\").focus();\n\t\treturn false;\n\t}\n\telse if ( (typeof(time_end_date) == \"undefined\") || (time_end_date == '') )\n\t{\n\t\thtml = \"<li>请选择活动结束日期.</li>\";\n\t\t$(\"#ul-errorlist-3\").html(html);\n\t\t$(\"#datepicker-02\").focus()\n\t\treturn false;\n\t}\n\telse if ( (typeof(time_end_hh) == \"undefined\") || (time_end_hh == '') || (time_end_hh == null) )\n\t{\n\t\thtml = \"<li>请选择活动结束日期的具体时间.</li>\";\n\t\t$(\"#ul-errorlist-3\").html(html);\n\t\t$(\".input-time-end-hh .dropdown-toggle\").focus();\n\t\treturn false;\n\t}\n\telse if ( (typeof(time_end_mm) == \"undefined\") || (time_end_mm == '') || (time_end_mm == null) )\n\t{\n\t\thtml = \"<li>请选择活动结束日期的具体时间.</li>\";\n\t\t$(\"#ul-errorlist-3\").html(html);\n\t\t$(\".input-time-end-mm .dropdown-toggle\").focus();\n\t\treturn false;\n\t}\n\t/*===== check event time =====*/\n\n\t/*+++++ check event logo +++++*/\n\tvar logo_file_value = $(\"#logo-file-id\").val();\n\n\tif ( !(typeof(logo_file_value) == \"undefined\") && (logo_file_value != '') )\n\t{\n\t\tif ( !Check_FileType(logo_file_value) )\n\t\t{\n\t\t\tshow_form_error(\"uploadLogoForm\", \"uploadPhotoTypeError\");\n\t\t\treturn false;\n\t\t}\n\t}\n\telse\n\t{\n\t\thtml = \"<li>请上传活动海报</li>\";\n\t\t$(\"#ul-errorlist-4\").html(html);\n\t\t// $(\"input[name='file']\").focus();\n\t\tdocument.getElementById(\"trigger-go-set-sale-href-id-1\").click();\n\t\treturn false;\n\t}\n\t/*===== check event logo =====*/\n\n\t/*+++++ check event description +++++*/\n\tvar description = $(\"textarea[name='event_description']\").val();\n\tif ( (typeof(description) == \"undefined\") || (description == '') )\n\t{\n\t\thtml = \"<li>请添加活动描述.</li>\";\n\t\t$(\"#ul-errorlist-5\").html(html);\n\t\t$(\"textarea[name='event_description']\").focus();\n\t\treturn false;\n\t}\n\t/*===== check event description =====*/\n\n\t/*+++++ check event sale +++++*/\n\tvar unisalenot = document.getElementById(\"uni-sale-checknot\").checked;\n\n\tif ( !(typeof(unisalenot) == \"undefined\") )\n\t{\n\t\tif ( unisalenot )\n\t\t{\n\t\t\tvar ticket_count = $(\"input[name='ticket_type_nums']\").val();\n\t\t\tvar unisale_count = $(\"input[name='unisalecount']\").val();\n\t\t\tvar event_size_temp = 0;\n\n\t\t\tif ( ticket_count == 0 )\n\t\t\t{\n\t\t\t\tdocument.getElementById(\"trigger-go-set-sale-href-id-2\").click();\n\t\t\t\talert(\"请至少添加一个票种, 否则请取消售票\");\n\n\t\t\t\thtml = \"<li>请至少添加一个票种, 否则请取消售票.</li>\";\n\t\t\t\t$(\"#ul-errorlist-6\").html(html);\n\t\t\t\t\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfor ( var i = 1; i <= unisale_count; i++ )\n\t\t\t{\n\t\t\t\tvar type_val = $(\"input[name='type_\"+i+\"']\").val();\n\t\t\t\t\n\t\t\t\tif ( !(typeof(type_val) == \"undefined\") )\n\t\t\t\t{\n\t\t\t\t\tif ( $(\"input[name='type_\"+i+\"']\").val() == \"\" )\n\t\t\t\t\t{\n\t\t\t\t\t\t$(\"input[name='type_\"+i+\"']\").focus();\n\t\t\t\t\t\thtml = \"<li>票的类型不能为空.</li>\";\n\t\t\t\t\t\t$(\"#ul-errorlist-6\").html(html);\n\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\telse if ( $(\"input[name='volume_\"+i+\"']\").val() == \"\" )\n\t\t\t\t\t{\n\t\t\t\t\t\t$(\"input[name='volume_\"+i+\"']\").focus();\n\t\t\t\t\t\thtml = \"<li>票的数量不能为空.</li>\";\n\t\t\t\t\t\t$(\"#ul-errorlist-6\").html(html);\n\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\telse if ( $(\"input[name='volume_\"+i+\"']\").val() == 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\t$(\"input[name='volume_\"+i+\"']\").focus();\n\t\t\t\t\t\thtml = \"<li>票的数量不能为零.</li>\";\n\t\t\t\t\t\t$(\"#ul-errorlist-6\").html(html);\n\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\telse if ( $(\"input[name='price_\"+i+\"']\").val() == \"\" )\n\t\t\t\t\t{\n\t\t\t\t\t\t$(\"input[name='price_\"+i+\"']\").focus();\n\t\t\t\t\t\thtml = \"<li>票价不能为空.</li>\";\n\t\t\t\t\t\t$(\"#ul-errorlist-6\").html(html);\n\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( $(\"input[name='price_\"+i+\"']\").val() == \"free\" )\n\t\t\t\t\t{\n\t\t\t\t\t\t$(\"input[name='price_\"+i+\"']\").val(0);\n\t\t\t\t\t}\n\t\t\t\t\t// parseInt( $(\"#ticket-type-nums\").val() );\n\n\t\t\t\t\tevent_size_temp += parseInt( $(\"input[name='volume_\"+i+\"']\").val() );\n\t\t\t\t}\n\t\t\t}\n\t\t\t$(\"input[name='event_size']\").val(event_size_temp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/*+++++ check event population +++++*/\n\t\t\tvar population = $(\"input[name='event_size']\").val();\n\t\t\tif ( (typeof(population) == \"undefined\") || (population == '') || (population == null) )\n\t\t\t{\n\t\t\t\t$(\"input[name='event_size']\").focus();\n\t\t\t\thtml = \"<li>若不售票, 请填写活动允许参与人数.</li>\";\n\t\t\t\t$(\"#ul-errorlist-9\").html(html);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t/*===== check event population =====*/\n\t\t}\n\t}\n\t/*===== check event sale =====*/\n\n\t// /*+++++ check event category +++++*/\n\t// var event_category = $(\"#flat-ui-event-category\").val();\n\t// if ( (typeof(event_category) == \"undefined\") || (event_category == '') || (event_category == null) )\n\t// {\n\t// \thtml = \"<li>您必须选择活动类型.</li>\";\n\t// \t$(\"#ul-errorlist-7\").html(html);\n\t// \t$(\".div-event-create-category .dropdown-toggle\").focus();\n\t// \treturn false;\n\t// }\n\t// /*===== check event category =====*/\n\n\t// /*+++++ check event create option +++++*/\n\t// var create_option = $(\"#flat-ui-event-option\").val();\n\t// if ( (typeof(create_option) == \"undefined\") || (create_option == '') || (create_option == null) )\n\t// {\n\t// \thtml = \"<li>请选择创建活动身份.</li>\";\n\t// \t$(\"#ul-errorlist-8\").html(html);\n\t// \t$(\".div-event-create-option .dropdown-toggle\").focus();\n\t// \treturn false;\n\t// }\n\t// /*===== check event create option =====*/\n\n\treturn true;\n\n}",
"function assignTagsToUser(event){\n\tvar userid = [];\n $(\"input[name='profile_chk[]']:checked\").each(function(i){\n \tuserid[i] = $(this).val();\n });\n var grpid = [];\n $(\"input[name='groupChk[]']:checked\").each(function(i){\n \tgrpid[i] = $(this).val();\n });\n\tvar grpsfrm=$(\"form#formManageGroup_\"+event.id).serializeArray();\n\tif(userid.length>0){\n\t\t\n\t\tif(grpid.length>0){\n\t\t\tvar ids = addLoadingImage($(\"[name=saveManageBtn_\"+event.id+\"]\"), \"before\");\n\t\t\t//var ids = addLoadingImage($(\"#saveManageBtn_\"+event.id), \"before\");\n\t\t\tjQuery.ajax({\n\t\t url: \"/\" + PROJECT_NAME + \"links/assign-multiple-tags\",\n\t\t type: \"POST\",\n\t\t dataType: \"json\",\n\t\t data: { \"tags_arr\" : grpsfrm,\"user\" : userid },\n\t\t timeout: 50000,\n\t\t success: function(jsonData) {\n\t\t \t\t$(\"span#\"+ids).remove();\n\t\t \t\tif(jsonData.msg=\"success\"){\n\t\t \t\t\t$(\"#tag-manage-outertags\").fadeToggle('slow');\n\t\t \t\t\t$(\".alert-box\").remove();\n\t\t \t\t\t$(\".alert-box1\").remove();\n\t\t \t\t\t$(\".alert-box2\").remove();\n\t\t \t\t\tshowDefaultMsg( \"Tags assigned.\", 1 );\n\t\t \t\t}\n\t\t \t},\n\t\t error: function(xhr, ajaxOptions, thrownError) {\n\t\t \talert(\"Server Error.\");\n\t\t\t\t}\n\t\t\t });\n\t\t}\n\t\telse{\n\t\t\t$(\".alert-box\").remove();\n\t\t\t$(\".alert-box1\").remove();\n\t\t\t$(\".alert-box2\").remove();\n\t\t\tshowDefaultMsg( \"To assign tag, select at least one.\", 2 );\n\t\t}\n\t}\n\telse{\n\t\t$(\".msg-popup-outer\").fadeToggle();\n\t\t$(\".manage-pop-outer\").fadeToggle();\n\t\t$( \"#dialog_confirm\" ).dialog({\n\t\t modal: true,\n\t\t width: 306,\n\t\t show: {\n\t\t \t effect: \"fade\"\n\t\t \t },\n\t\t\t hide: {\n\t\t\t\t effect: \"fade\"\n\t\t\t\t },\n\t\t buttons: {\n\t\t 'ok': function() {\n\t\t \t$( this ).dialog( \"close\" );\n\t\t }\n\t\t }\n\t\t});\n\t\t$(\".alert-box\").remove();\n\t\t$(\".alert-box1\").remove();\n\t\t$(\".alert-box2\").remove();\n\t\tshowDefaultMsg( \"Please select one user atleast.\", 2 );\n\t}\n}",
"checkUserExistenceInGroup(hub, group, userId, options) {\n const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {});\n return this.client.sendOperationRequest({ hub, group, userId, options: operationOptions }, checkUserExistenceInGroupOperationSpec);\n }",
"function populate(randomUsers){\n // Variable declaration\n const newMembersDiv = document.getElementById('new-members');\n const recentActivityDiv = document.getElementById('recent-activity');\n const membersActivity = [\"posted YourApp's SEO Tips\", \"commented on Facebook's Changes for 2018\", \"liked the post Facebook's Change for 2018\", \"commented on YourApp's SEO Tips\"];\n const activityTime = ['1 day ago', '5 hours ago', '5 hours ago', '4 hours ago'];\n\n // Loop through random users to populate member sections\n for (let i = 0; i < randomUsers.length; i++){\n const member = randomUsers[i];\n\n // Wrapper div for user info\n const memberDiv = document.createElement('div');\n memberDiv.className = 'member-info';\n\n // Image avatar\n const imageDiv = document.createElement('div');\n const img = document.createElement('img');\n img.src = member.picture.thumbnail;\n img.alt = firstUp(member.name.first) + ' ' + firstUp(member.name.last);\n img.className = 'avatar';\n imageDiv.appendChild(img);\n memberDiv.appendChild(imageDiv);\n\n // Use the 4 first users to populate \"New Members\" specific info\n if (i <= 3){\n // Wrapping div\n const detailsDiv = document.createElement('div');\n\n // Name\n const name = document.createElement('p');\n name.className = 'member-name';\n name.innerHTML = firstUp(member.name.first) + ' ' + firstUp(member.name.last);\n detailsDiv.appendChild(name);\n\n // Email\n const email = document.createElement('p');\n email.innerHTML = member.email;\n email.className = 'member-email';\n detailsDiv.appendChild(email);\n memberDiv.appendChild(detailsDiv);\n\n // Signup Date\n const dateDiv = document.createElement('div');\n dateDiv.className = 'flex-item-last';\n const signupDate = document.createElement('p');\n const dateOptions = {month: '2-digit', day: '2-digit', year: '2-digit'};\n signupDate.innerHTML = new Date(member.registered.date).toLocaleDateString('en-US', dateOptions);\n signupDate.className = 'member-signup';\n dateDiv.appendChild(signupDate);\n\n memberDiv.appendChild(dateDiv);\n\n // Line break between members\n newMembersDiv.appendChild(memberDiv);\n if (i < 3){\n const line = document.createElement('hr');\n line.className = \"max-length\";\n newMembersDiv.appendChild(line);\n }\n }\n // The 4 last users populates \"Recent Activity\" specific info\n else {\n // Wrapping div\n const activityDiv = document.createElement('div');\n memberDiv.appendChild(activityDiv);\n\n // Activity\n const activity = document.createElement('p');\n activity.innerHTML = firstUp(member.name.first) + ' ' + firstUp(member.name.last) + membersActivity[i -4];\n activityDiv.appendChild(activity);\n\n // Time\n const time = document.createElement('p');\n time.innerHTML = activityTime[i -4];\n time.className = 'activity-time';\n activityDiv.appendChild(time);\n\n // Signup Date\n const arrowDiv = document.createElement('div');\n arrowDiv.className = 'flex-item-last';\n const arrow = document.createElement('p');\n arrow.innerHTML = '›'\n arrow.className = 'activity-arrow';\n arrowDiv.appendChild(arrow);\n memberDiv.appendChild(arrowDiv);\n\n // Add linebreak if not the last one\n recentActivityDiv.appendChild(memberDiv);\n if (i < 7){\n const line = document.createElement('hr');\n recentActivityDiv.appendChild(line);\n }\n }\n }\n}",
"function addNewGroupButton() {\n var ui = SpreadsheetApp.getUi();\n var response = ui.prompt('Input New Category Group', ui.ButtonSet.OK_CANCEL);\n \n if(response.getSelectedButton() == ui.Button.CANCEL) {\n return;\n }\n \n // Check to see if this group already exists\n var formula2Sheet = SpreadsheetApp.getActive().getSheetByName(\"FORMULAS2\");\n \n // First Get the last row in the groups DB that contains data \n var searchRangeLastRow = formula2Sheet.getLastRow();\n var searchArray = formula2Sheet.getRange(2, 9, searchRangeLastRow).getValues();\n \n for (i = 0; i <= searchArray.length; i++) {\n if(searchArray[i].toString() == \"\") { // searchArray is an array containing multiple arrays, convert each array to a string to expose the empty arrays as emppty strings which can be checked for in the conditional\n var lastRow = i + 2; // Adding 2 to offset for header and the fact that array indexing starts at 0\n \n if(i == 0) { // warn user if DB needs to be initialized\n ui.alert(\"ERROR: Category Groups DB must be initialized with at least one group\");\n return;\n }\n \n break;\n }\n }\n \n var groupDB = formula2Sheet.getRange(2, 9, lastRow-2).getValues();\n \n for (i = 0; i < groupDB.length; i++) {\n if( response.getResponseText() == groupDB[i].toString() ) {\n ui.alert(\"This group already exists\");\n return;\n }\n }\n \n // Now write the user's input to the last row of the DB\n formula2Sheet.getRange(lastRow, 9).setValue(response.getResponseText());\n}",
"function addUserToSharePointGroup(groupID, key) {\n\n\n console.log(groupID + ' : ' + key);\n\n \n\n var siteUrl = '/asaalt/hqdag8/quad';\n\n var clientContext = new SP.ClientContext(siteUrl);\n var collGroup = clientContext.get_web().get_siteGroups();\n var oGroup = collGroup.getById(groupID);\n var userCreationInfo = new SP.UserCreationInformation();\n //userCreationInfo.set_email('david.m.lewandowsky.ctr@mail.mil');\n userCreationInfo.set_loginName(key);\n //userCreationInfo.set_title('MAINTENANCE TEST PILOT');\n this.oUser = oGroup.get_users().add(userCreationInfo);\n \n clientContext.load(oUser);\n clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));\n \n\n}",
"async addVisit(user) {\n const existing = await this.stores.players.findOne({ type: 'userHistory', id: user.id });\n const now = Date.now();\n const instanceId = await this.getInstanceId();\n if (!existing) {\n // create the player\n // TODO: add some form of admin note tool for moderators to leave notes\n // on troublesome players + warnings\n await this.stores.players.insert({\n type: 'userHistory',\n // base brickadia user info\n id: user.id,\n name: user.name,\n // list of names and when they were first used\n nameHistory: [{name: user.name, date: now}],\n // list of ips this player has been on\n ips: [],\n // first time player was seen\n created: now,\n // last time player was seen\n lastSeen: now,\n // last server this player has been on\n lastInstanceId: instanceId,\n // number of status checks this player has observed\n heartbeats: 0,\n // number of sessions (at least an hour apart) this player has had\n sessions: 1,\n // number of instances (times omegga was started) this player has joined\n instances: 1,\n });\n return true;\n } else {\n await this.stores.players.update(\n { _id: existing._id },\n {\n $inc: {\n // increment number of sessions if the player hasn't been seen for an hour\n sessions: existing.lastSeen < now - 60 * 60 * 1000 ? 1 : 0,\n // increment the number of instances this player has joined\n instances: existing.lastInstanceId === instanceId ? 1 : 0,\n },\n\n $set: {\n // update last seen time and user name\n lastSeen: now,\n name: user.name,\n\n // set the last joined instance\n lastInstanceId: instanceId,\n },\n\n // add the name to the history if it was not already in it\n ...(existing.nameHistory.some(h => h.name === user.name) ? {} : {\n $addToSet: { nameHistory: {name: user.name, date: now} },\n }),\n },\n );\n return false;\n }\n }",
"function createParticipantEvent(participant_ids, hangout_id, timestamp) {\n app.service('participant_events').create(\n {\n participants: participant_ids,\n hangout_id: hangout_id,\n timestamp: timestamp\n }, function(error, data) {\n if (error) {\n } else {\n winston.log(\"info\", \"created new participant event for hangout\", hangout_id);\n }\n });\n}",
"async function checkOrAddToArr(){\n try{\n\n const userObjSnapshot = await firestore.collection(\"users\").doc(props.userDoc.uid).get();\n const userObj = userObjSnapshot.data();\n console.log(userObj);\n if(!userObj.dms.some(el => el.convoID === props.match.params.roomName)){\n //add the roomname to the array\n //get the userObj of the other person\n\n const otherUserObjSnapshot = await firestore.collection(\"users\").doc(otherID).get();\n const otherUserObj = otherUserObjSnapshot.data(); \n otherUserObjRef.current = otherUserObj;\n const addition = await firestore.collection(\"users\").doc(props.userDoc.uid).update({\n dms: firebase.firestore.FieldValue.arrayUnion({\n convoID: props.match.params.roomName,\n name: otherUserObj.name,\n photoURL: otherUserObj.photoURL\n })\n })\n }\n\n \n const otherUserObjSnapshot = await firestore.collection(\"users\").doc(otherID).get();\n const otherUserObj = otherUserObjSnapshot.data();\n if(!otherUserObj.dms.some(el => el.convoID === props.match.params.roomName)){\n //add the roomname to the array\n //get the userObj of the other person \n console.log(props.userDoc);\n const addition = await firestore.collection(\"users\").doc(otherID).update({\n dms: firebase.firestore.FieldValue.arrayUnion({\n convoID: props.match.params.roomName,\n name: props.userDoc.name,\n photoURL: props.userDoc.photoURL\n })\n })\n\n console.log(\"addition successful\")\n\n }\n\n }catch(e){\n console.log(e)\n }\n\n }",
"function checkUserToInvite(current_user, invite_user, element) {\n if(!isBlank(invite_user)) {\n\tif(current_user !== invite_user) {\n\t if(checkUserExistence(invite_user)) {\n\t\treturn true;\n\t } else {\n\t\tsetElementBackgroundColor(element, 'red');\n\t\talert('The user you are trying to invite,\\ndoes not exist!\\nPlease, try again ...');\n\t\treturn false;\n\t }\n\t} else {\n\t setElementBackgroundColor(element, 'red');\n\t alert('You cannot invite yourself!\\nPlease, try again ...')\n\t return false;\n\t}\n } else {\n\tsetElementBackgroundColor(element, 'red');\n }\n}",
"function removeadduser(level){\n\tif(level == \"add\"){\n\t\t$('.usernotexist').each(function(){\n\t\t\tif($(this).is(':checked')){\n\t\t\t\tvar did = $(this).attr('did');\n\t\t\t\tif (checkArray(did,userNotExistArray)){\n\t\t\t\t\tvar indx = userNotExistArray.indexOf(did);\n\t\t\t\t\tuserNotExistArray.splice(indx,1);\n\t\t\t\t}\n\t\t\t\tif (!checkArray(did,userExistArray)){\n\t\t\t\t\tuserExistArray.push(did);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}else{\n\t\t$('.userexist').each(function(){\n\t\t\tif($(this).is(':checked')){\n\t\t\t\tvar did = $(this).attr('did');\n\t\t\t\tif (checkArray(did,userExistArray)){\n\t\t\t\t\tvar indx = userExistArray.indexOf(did);\n\t\t\t\t\tuserExistArray.splice(indx,1);\n\t\t\t\t}\n\t\t\t\tif (!checkArray(did,userNotExistArray)){\n\t\t\t\t\tuserNotExistArray.push(did);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t}\n\tcreatetableforinvitation();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Euclidean distance between the current and the prev. feature vectors | function distanceCurPrev(_feature_vec, _prev_feature_vec) {
var _euclidean_dist = sqrt(
sq(_feature_vec[0] - _prev_feature_vec[0]) +
sq(_feature_vec[1] - _prev_feature_vec[1]) +
sq(_feature_vec[2] - _prev_feature_vec[2]) +
sq(_feature_vec[3] - _prev_feature_vec[3]) +
sq(_feature_vec[4] - _prev_feature_vec[4]) +
sq(_feature_vec[5] - _prev_feature_vec[5]) +
sq(_feature_vec[6] - _prev_feature_vec[6]) +
sq(_feature_vec[7] - _prev_feature_vec[7]) +
sq(_feature_vec[8] - _prev_feature_vec[8]));
return _euclidean_dist;
} | [
"function calculateDistance(i){\n var distance = new THREE.Vector2();\n var zero = new THREE.Vector2(0,0);\n distance = zero.distanceTo(allVectors[i]);\n return distance;\n}",
"function distance(v1, v2) {\n\t\treturn Math.sqrt(Math.pow(v2.X - v1.X, 2) + Math.pow(v2.Y - v1.Y, 2));\n\t}",
"getDistance(x, y) {\n return Math.sqrt(Math.pow(this.x - x, 2) + Math.pow(this.y - y, 2));\n }",
"getDistance(){\n\t\tif(this.TargetPlanet!== null){\n\t\t\treturn Math.abs(this.Group.position.y - this.TargetPlanet.y);\n\t\t}\n\t\telse return 0;\n\t}",
"signedDistance(origin, param) {\n return this._edgeSegment.signedDistance(origin, param);\n }",
"get distance(){\n\t\treturn(google.maps.geometry.spherical.computeLength(this._locations))\n\t}",
"subtract(otherVector) {\n return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);\n }",
"function calcSpeed(prev, next) {\n\n var x = Math.abs(prev[1] - next[1]);\n var y = Math.abs(prev[0] - next[0]);\n\n var greatest = x > y ? x : y;\n\n var speedModifier = 0.20;\n\n var speed = Math.ceil(greatest/speedModifier);\n\n //Keep speed at a constant\n if(speed < 3000 || speed > 3000) {\n speed = 3000;\n return speed;\n }\n return speed;\n\n }",
"distanceTo (x, y) { return this.get(x, y).dist }",
"subtractToRef(otherVector, result) {\n result.x = this.x - otherVector.x;\n result.y = this.y - otherVector.y;\n return this;\n }",
"subtract(otherVector) {\n return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);\n }",
"function calcDistance(node1, node2) {\n //could use Math.hypot if it's compliant w/their specs; check\n // return Math.hypot(node1.x-node2.x,node1.y,node2.y)\n var x = node1.x - node2.x;\n var y = node1.y - node2.y;\n return Math.sqrt(x * x + y * y)\n} //calcDistance",
"function totalDistance(points){\n\tvar totalDistance = 0;\n\tfor(var i = 0; i < points.length - 1; i++){\n\t\ttotalDistance += Math.sqrt(Math.pow(points[i+1][0]-points[i][0], 2) + \n\t\t\t\t\t\t\t\t\tMath.pow(points[i+1][1]-points[i][1], 2) + \n\t\t\t\t\t\t\t\t\tMath.pow(points[i+1][2]-points[i][2], 2));\n\t}\n\treturn totalDistance;\n}",
"calculateTravelCost(previous, next) {\n if (next.row !== previous.row && next.col !== previous.col) {\n return 14;\n }\n return 10;\n }",
"function energySpent() {\n // Calculate distance moved since last subtraction.\n var moved = ballBody.position.vsub(lastPos);\n\n // Only return if moved move than one square!\n if (moved.length() >= 0.98) {\n // Also update the path in map scene.\n updateLinePath();\n lastPos.copy(ballBody.position);\n return Math.round(moved.length());\n } else {\n return 0;\n }\n}",
"calculateLookDifferential() {\n const d = [\n this.lookPoint[0] - this.tPoint[0],\n this.lookPoint[1] - this.tPoint[1],\n this.lookPoint[2] - this.tPoint[2]\n ];\n this._lookDifferential = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];\n }",
"get norm () { return Math.sqrt(this.normSquared); }",
"function vecLength(vec){\n return Math.sqrt(vec.x * vec.x + vec.y * vec.y);\n}",
"function distanceTravelledInFeet(startBlock, endBlock) {\n totalBlocks = Math.abs(startBlock-endBlock)\n return totalBlocks * 264\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render is called when a slot is not rendered when the ready event fires | function onRender(event) {
const slot = event.detail.slot;
/* istanbul ignore else */
if (utils.isFunction(slot.display)) {
slot.display();
}
} | [
"onRender() {}",
"_render() {\n if (this._connected && !!this._template) {\n render(this._template(this), this, {eventContext: this});\n }\n }",
"slot$(name,ctx){\n\t\tvar slots_;\n\t\tif (name == '__' && !this.render) {\n\t\t\treturn this;\n\t\t}\t\t\n\t\treturn (slots_ = this.__slots)[name] || (slots_[name] = imba$1.createLiveFragment(0,null,this));\n\t}",
"render() {\n // For example:\n // console.log('The object \"' + this.holder.id + '\" is ready');\n // this.holder.style.backgroundColor = this.options.color;\n // this.holder.innerHTML = 'Hello World!';\n }",
"function maybeStaticRenderLater() {\n if (shinyMode && has_jQuery3()) {\n window.jQuery(window.HTMLWidgets.staticRender);\n } else {\n window.HTMLWidgets.staticRender();\n }\n }",
"render() {\n\t\t\tthis.containerElement.fullCalendar(\"removeEvents\");\n\t\t\tthis.containerElement.fullCalendar(\"addEventSource\", [].concat(this.state.schedule));\n\n\t\t\tthis.setDateItemColor();\n\t\t}",
"wakeUp() {\n const self = this;\n // Only re render VizTool (should be super fast)\n self.render();\n }",
"render(){\n\t\tthis.loadStyle();\n\t\tthis.renderView();\n\t}",
"_checkForSideSlotted() {\n let sideslots = [\n this.shadowRoot.querySelector('#side-nav'),\n this.shadowRoot.querySelector('#side-aside'),\n ];\n let slotsfilled = false;\n sideslots.forEach(\n function (s) {\n slotsfilled = slotsfilled ? slotsfilled : s.assignedNodes()?.length;\n s.addEventListener(\n 'slotchange',\n function (e) {\n this._checkForSideSlotted();\n }.bind(this)\n );\n }.bind(this)\n );\n this.hassidebar = slotsfilled;\n }",
"renderedCallback() {\n if (this.initialRender) {\n if (!this.disableAutoScroll) {\n this.setAutoScroll();\n }\n }\n this.initialRender = false;\n }",
"function renderQuizBox() {\n // renderQuestionCount();\n renderQuestion();\n renderScore();\n }",
"onRender()\n {\n /* var templateResourceType = _.template($('#template-resourcetype_collection_item').html());\n var resourceTypeCollection = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__GLOBAL_RESOURCETYPE_COLLECTION);\n// var html = templateResourceType({url: null, mimetype: 'Auto-detect', extension: 'Rodan will attempt to determine the file type based on the file itself'});\n // this.$el.find('#select-resourcetype').append(html);\n for (var i = 0; i < resourceTypeCollection.length; i++)\n {\n \tvar resourceType = resourceTypeCollection.at(i);\n var html = templateResourceType(resourceType.attributes);\n \tthis.$el.find('#select-resourcetype').append(html);\n }*/\n }",
"_render () {\n if ( this._isRendered ) { return; }\n // set `_isRendered` hatch\n this._isRendered = true;\n // create `SVG` canvas to draw in\n this._createSVGCanvas();\n // set canvas size\n this._setCanvasSize();\n // draw the initial state\n // this._draw();\n // append the canvas to the parent from props\n this._props.parent.appendChild( this._canvas );\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 }",
"function onReady(slotMethods, event) {\n\tconst slot = event.detail.slot;\n\t/* istanbul ignore else */\n\tif (slot.server === 'gpt') {\n\t\tslot.gpt = {};\n\n\t\t// extend the slot with gpt methods\n\t\tutils.extend(slot, slotMethods);\n\n\t\t// setup the gpt configuration the ad\n\t\tgoogletag.cmd.push(() => {\n\t\t\tslot\n\t\t\t\t.defineSlot()\n\t\t\t\t.addServices()\n\t\t\t\t.setCollapseEmpty()\n\t\t\t\t.setTargeting()\n\t\t\t\t.setURL();\n\n\t\t\tif (!slot.defer && slot.hasValidSize()) {\n\t\t\t\tslot.display();\n\t\t\t}\n\t\t});\n\t}\n}",
"_addSlot() {\n if (this[_value]) {\n this[_fillElement].appendChild(this[_slotElement]);\n } else {\n this[_trackElement].appendChild(this[_slotElement]);\n }\n }",
"function spinSlot() {\n\t\tslot.getResults(function(output) { // callback function to retrieve data from the model\n\t\t\tslot.prependRandomSymbols(10,20,6);\n\t\t\tslot.initSlot(output);\n\t\t\tslot.animateReel();\n\t\t});\n\t}",
"didRender() {\n this._super();\n\n this.setHeight();\n\n const elementID = this.get('elementId');\n this.$(window).on(`resize.${elementID}`, () => this.setHeight());\n }",
"function Window_SlotInstruction() {\n this.initialize.apply(this, arguments);\n}",
"function render() {\n\t\tvar timer;\n\t\t\n\t\tfor (timer = 0; timer < renderThese.length; timer++) {\n\t\t\treportTimer(renderThese[timer]);\n\t\t}\n\t\t\n\t\trenderThese.length = 0;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets all the bookmark folders | async function getAllBookmarkFolders() {
const [rootTree] = await browser.bookmarks.getTree();
const livemarksFolders = (await LivemarkStore.getAll()).map(livemark => {
return livemark.id;
});
const folders = [];
const visitChildren = (tree) => {
for (const child of tree) {
if (child.type !== "folder" || !child.id) {
continue;
}
// if the folder belongs to a feed then skip it and its children
if (livemarksFolders.includes(child.id)) {
continue;
}
folders.push(child);
visitChildren(child.children);
}
};
visitChildren(rootTree.children);
return folders;
} | [
"function clearBookmarkFolders() {\n while ($bookmarksList.children.length > 0) {\n $bookmarksList.removeChild($bookmarksList.firstChild);\n }\n }",
"function goToRandomFromAllBookmarks() {\n let bookmarks = [];\n let folderStack = [];\n chrome.bookmarks.getTree(result => {\n let node = result[0];\n\n separateFoldersAndBookmarks(node, bookmarks, folderStack);\n while (folderStack.length > 0) {\n node = folderStack.pop();\n separateFoldersAndBookmarks(node, bookmarks, folderStack);\n }\n\n if (bookmarks.length > 0) {\n const randomIndex = Math.floor(Math.random() * bookmarks.length);\n const randomURL = bookmarks[randomIndex].url;\n chrome.tabs.create({url: randomURL});\n }\n });\n }",
"function separateFoldersAndBookmarks(node, bookmarks, folders) {\n node.children.forEach(c => {\n if (isAFolder(c)) {\n folders.push(c);\n }\n else {\n bookmarks.push(c);\n }\n });\n }",
"function exportBookmarks() {\n\tvar folderName = prompt(chrome.i18n.getMessage(\"editExportPrompt\"));\n\n\t// If the cancel button was pressed\n\tif (folderName === null) {\n\t\tdocument.getElementById(\"export-button\").blur();\n\t\treturn;\n\t}\n\n\t// Default folder name if none is specified\n\tif (folderName === \"\") folderName = \"Tab Loadouts\";\n\n var totalBookmarks = 0;\n LOADOUTS.forEach(function(loadout) {\n if (loadout) totalBookmarks += loadout.links.length;\n });\n\n var folderIndex = 0;\n\tchrome.bookmarks.create({title: folderName}, function(mainFolder) {\n LOADOUTS.forEach(function(loadout, i) {\n if (!loadout) return;\n\n chrome.bookmarks.create({title: loadout.name || String(indexToLoadoutNumber(i)), index: folderIndex++, parentId: mainFolder.id}, function(loadoutFolder) {\n loadout.links.forEach(function(link, j) {\n chrome.bookmarks.create({title: loadout.titles[j], url: link, index: j, parentId: loadoutFolder.id}, function() {\n totalBookmarks--;\n if (totalBookmarks === 0) {\n // Opens a new tab at the chrome bookmarks page\n \t\tchrome.tabs.create({url: \"chrome://bookmarks\"});\n }\n });\n });\n });\n\n });\n\n\t});\n}",
"function getBookmarks() {\n var db = getDatabase();\n var respath=\"\";\n db.transaction(function(tx) {\n var rs = tx.executeSql('SELECT * FROM bookmarks ORDER BY bookmarks.title;');\n for (var i = 0; i < rs.rows.length; i++) {\n // For compatibility reasons with older versions\n if (rs.rows.item(i).agent) modelUrls.append({\"title\" : rs.rows.item(i).title, \"url\" : rs.rows.item(i).url, \"agent\" : rs.rows.item(i).agent});\n else modelUrls.append({\"title\" : rs.rows.item(i).title, \"url\" : rs.rows.item(i).url, \"agent\" : \"Mozilla/5.0 (Maemo; Linux; Jolla; Sailfish; Mobile) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13\"});\n //console.debug(\"Get Bookmarks from db:\" + rs.rows.item(i).title, rs.rows.item(i).url)\n }\n })\n}",
"async getFolders() {\n const matches = await this.client('folders').select('folder');\n return matches.map(match => match.folder);\n }",
"getFolders() {\n return fetch(this.BASE_API + \"/folders\", {\n method: 'GET',\n headers: {\n 'Accept': 'application/json'\n },\n });\n }",
"function loadBookmarks(){\n\tHeadingArray = getBookmarkHeadingArray();\n\tURLArray = getBookmarkURLArray();\n\t//deleting all bookmarks\n\tvar mainBookmarksDisplay = document.getElementById(\"bookmarks\");\n\twhile (mainBookmarksDisplay.hasChildNodes()) {\n mainBookmarksDisplay.removeChild(mainBookmarksDisplay.lastChild);\n }\n\tfor(var i = 0; i<HeadingArray.length; i++){\n\t displayBookmark(HeadingArray[i],URLArray[i]);\n\t}\n}",
"function loadBookmarks()\n{\n\n for (ii = 0; ii < maxChapters; ii++)\n {\n\n for (jj = 0; jj <= maxSections; jj++) //Since there are six sections (include chapter start page)\n {\n var name = chapterIDs[ii][jj];\n var currentChapter;\n\n var returnVisitor = window.localStorage.getItem(name);\n if (returnVisitor === null) //No bookmark has been set for this chapter\n {\n currentChapter = new bookmark(name, ((document.getElementById(name)).innerText), null) //indicate no bookmark is set\n }\n else //There is a previous bookmark we want to use now\n {\n var origText = (document.getElementById(name)).innerText; //Store orginal text for use in replacing bookmark later\n (document.getElementById(name)).innerText = (document.getElementById(name)).innerText + returnVisitor; //Push new bookmark onto page\n currentChapter = new bookmark(name, origText, returnVisitor);\n }\n\n chapterMarks[ii][jj] = currentChapter; //Store it for reference later\n\n }\n\n }\n\n}",
"function bookmarksHtml(bm_node, depth) {\n var html = '';\n \n if (bm_node.children) {\n html = html + '<li class=\"group l_' + depth + '';\n if (bm_node.title == 'Other Bookmarks') {\n html = html + ' other';\n }\n html = html + '\"><ul class=\"folder\"><h3>' + bm_node.title + '</h3></label><div>';\n var child_html = '';\n \n if (bm_node.children.length == 0) {\n child_html = child_html + '<li class=\"empty\"><h4>(empty)</h4></li>';\n } else {\n for (var i = 0; i < bm_node.children.length; i++) {\n child_html = child_html + bookmarksHtml(bm_node.children[i], depth + 1);\n }\n }\n \n html = html + child_html + '</div></ul></li>';\n } else if (bm_node.url) {\n html = html + '<a href=\"' + bm_node.url + '\"><li';\n if (bm_node.url.indexOf('javascript:') != 0) {\n html = html + ' style=\"background-image: url(chrome://favicon/' + bm_node.url + ');\"';\n }\n html = html + '><h4>' + bm_node.title + '</h4></li></a>';\n }\n \n return html;\n}",
"async function getBookmarkFolderId() {\n\t// Read the supposed folder id from our settings.\n\tlet { bookmarkFolderId } = await browser.storage.local.get('bookmarkFolderId');\n\n\t// Check if the folder exists and is indeed a folder.\n\ttry {\n\t\tconst bookmarkFolder = await browser.bookmarks.get(bookmarkFolderId);\n\t\tif (bookmarkFolder.url) throw new Error;\n\t} catch (err) {\n\t\t// Ignore the existing, faulty setting. We will update the stored value further below.\n\t\tbookmarkFolderId = undefined;\n\t}\n\n\tif (bookmarkFolderId === undefined) {\n\t\tconst bookmarkFolderName = browser.i18n.getMessage('bookmarkFolderName');\n\n\t\t// First, try find an existing folder with matching title (perhaps from our previous life).\n\t\tconst foundFolders = await browser.bookmarks.search({ title: bookmarkFolderName });\n\t\tif (foundFolders.length > 0) {\n\t\t\t// Found (at least) one. We use it.\n\t\t\tbookmarkFolderId = foundFolders[0].id;\n\t\t}\n\t\telse {\n\t\t\t// Create a new folder.\n\t\t\tconst bookmarkTree = await browser.bookmarks.getTree();\n\t\t\t// Simply take the root’s first child: probably the main bookmarks menu or bookmarks toolbar.\n\t\t\tconst mainBookmarksFolderId = bookmarkTree[0].children[0].id;\n\t\t\tconst bookmarkFolder = await browser.bookmarks.create({\n\t\t\t\tparentId: mainBookmarksFolderId,\n\t\t\t\ttitle: bookmarkFolderName,\n\t\t\t});\n\t\t\tbookmarkFolderId = bookmarkFolder.id;\n\t\t}\n\n\t\t// Update our settings to remember the folder.\n\t\tawait browser.storage.local.set({ bookmarkFolderId });\n\t}\n\n\treturn bookmarkFolderId;\n}",
"function retrievePaths(){\n\tif (typeof(Storage) !== \"undefined\"){\n\t\tvar paths = JSON.parse(localStorage.getItem(APP_PREFIX))\n\t\tfor (var i = 0; i<paths.length; i++){\n\t\t\tvar current = new Path(paths[i]);\n\t\t\tpathList.push(current);\n\t\t\tpathNames.push(current.title);\n\t\t}\n\t}else{\n\t\tconsole.log(\"ERROR: Local Storage not supported by browser!\")\n\t}\n}",
"function fetchBookmarks(){\n\n if(localStorage.getItem('bookmarks')){\n bookmarks = JSON.parse(localStorage.getItem('bookmarks'));\n }else{\n // Create array and set to lacal storage\n bookmarks = [{\n name:'Mohammad Design',\n url:'test.com'\n }];\n localStorage.setItem('bookmarks',JSON.stringify(bookmarks));\n }\n buildBookmarks();\n}",
"function viewAll () {\n\t// First update the distances (must updateBrain() first)\n\tallBookmarks.forEach (function (b) { b.updateDist() })\n\n\t// Sort by distance\n\tallBookmarks.sort(function (a,b) {return a.dist - b.dist})\n\n\t// Calculate max distance^2 for shading\n\tvar maxDist = 0\n\tallBookmarks.forEach (function(b) { if (b.dist>maxDist) maxDist = b.dist })\n\t\n\t// Remove any previous children under the id=bookmarks node\n\tvar bookmarkshtml = document.getElementById('bookmarks')\n\twhile (bookmarkshtml.hasChildNodes()) {\n\t\tbookmarkshtml.removeChild(bookmarkshtml.lastChild);\n\t}\n\n\t// Make a new child for each bookmark\n\tallBookmarks.forEach (function (b) {\n\t\t// Clone an html subtree for this bookmark\n\t\tvar bhtml = document.getElementById('bookmark').cloneNode(true); // true = deep copy\n\n\t\t// Populate the new html subtree.\n\t\t// These particular classnames are\n\t\t// used just so this code can fish out the <span>'s,\n\t\t// not necessarily for CSS styling\n\t\tbhtml.getElementsByClassName(\"title\")[0].innerHTML = b.title;\n\t\tbhtml.getElementsByClassName(\"time\")[0].innerHTML = moment (b.time).fromNow();\n\t\tbhtml.getElementsByClassName(\"url\")[0].innerHTML = b.url;\n\t\tbhtml.getElementsByClassName(\"selection\")[0].innerHTML = b.selection;\n\t\tif (b.thumb != null) bhtml.getElementsByClassName(\"thumb\")[0].src = b.thumb;\n\n\t\t// Shading based on distance squared,\n\t\t// want \"decrement\" from pure white when you hit maxDist\n\t\tvar decrement = 0.2\t\t\n\t\tvar brightness = Math.floor (255 * (1 - b.dist * (decrement / maxDist)))\n\t\tbhtml.getElementsByClassName(\"bookmarkBackground\")[0].style.backgroundColor =\n\t\t\t\"rgb(\" + brightness + \",\" + brightness + \",\" + brightness + \")\"\n\n\t\t// Make the bar graph\n\t\tvar rect = bhtml.getElementsByClassName(\"bar\")[0]\n\t\trect.y.baseVal.value = 60*(1.-b.interest); // This \"60\" also appears in front.html\n\t\trect.height.baseVal.value = 60*b.interest;\n\n\t\t// Make it not invisible\n\t\tbhtml.style.display=\"inline\";\n\n\t\t// Add it under id=bookmarks node\n\t\tbookmarkshtml.appendChild(bhtml);\n\t})\n}",
"function goToRandomURLFromSet(setName) {\n folderIds = allSets[setName];\n const promises = [];\n let allNodes = [];\n\n folderIds.forEach(id => {\n const promise = chrome.bookmarks.getChildren(id);\n promise\n .then((n) => allNodes = allNodes.concat(n))\n .catch(err => console.error(err)); // An invalid id throws an error that must be caught here\n promises.push(promise);\n });\n\n Promise.all(promises).finally(() => {\n const bookmarks = allNodes.filter(n => !isAFolder(n));\n if (bookmarks.length > 0) {\n const randomIndex = Math.floor(Math.random() * bookmarks.length);\n const randomURL = bookmarks[randomIndex].url;\n chrome.tabs.create({url: randomURL});\n }\n });\n }",
"get folderPaths(){\n return this._folderPaths;\n }",
"function clickFolder(e) {\n const folder = e.target.closest('.bookmark-folder');\n const subFolderBtn = e.target.closest('i.fa-level-down-alt');\n\n if (!folder) {\n return;\n }\n\n if (!!subFolderBtn) {\n if (parseInt(folder.dataset.folders) > 0) {\n setActiveFolderById(folder.dataset.id);\n }\n }\n else { \n toggleFolderSelection(folder);\n }\n }",
"getBookmarkComponents(bookmarks) {\n var components = [];\n bookmarks.map(bookmark => {\n components.push(\n <BookmarkListItem \n key={bookmark.addTime.toString()}\n lang={this.lang}\n bookmark={bookmark}\n waitDelete={this.state.waitDelete}\n getAddTime={this.getAddTime}\n getPercentage={this.getPercentage}\n handleJumpToBookmark={this.props.handleJumpToBookmark}\n handleBookmarkButtonClick={this.props.handleBookmarkButtonClick}\n handleShowDeleteConfirmDialog={this.handleShowDeleteConfirmDialog}\n />\n );\n components.push(\n <div className='bl-item-sep' key={bookmark.addTime.toString()+'sep'}></div>\n );\n });\n if (components.length > 0) {\n components.pop();\n }\n return components;\n }",
"function restoreBookmarksFromSelectors() {\n\t\tStory.bookmarks = [ ];\n\t\tvar selectors = Story.bookmarkSelectors;\n\t\tif ( selectors.length === 0 ) { return };\n\n\t\tjQuery.each( selectors, function( index, selector ) {\n\t\t\tStory.bookmarks.push( Canon.find( selector ) );\n\t\t} );\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get an array of episodes from the most recent season | function getRecentSeason(episodes) {
var recentSeasonId = episodes.pop().season;
return episodes.filter(function (val) {
return val.season === recentSeasonId;
});
} | [
"function getMostViewedEpisodes() {\n let api = \"../api/Episodes\";\n ajaxCall(\"GET\", api, \"\", getSuccessMostViewedEpisodes, errorMostViewedEpisodes);\n}",
"function getSeasonOfEpisodeNumber( epsNumber ){\n\n\tif(epsNumber > 0){\n\t\tfor(var i = 0; i < dkGlobalOverviewTable.arrayOfEpisodesInSeasons.length; i++){\n\t\t\tepsNumber -= dkGlobalOverviewTable.arrayOfEpisodesInSeasons[i];\n\t\t\tif(epsNumber <= 0){\n\t\t\t\treturn i+1;\n\t\t\t}\n\t\t}\n\n\t}\n\treturn null;\n\n\n} //end ",
"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 BrowseSeasons() \n{\n HideListingCriteria();\n movieCriteria = \"All\"\n movieCriteriaValue = \"Seasons\";\n BuildMoviesCache(SEASONS_LISTING_URI)\n startPage = 0;\n FetchTitles(startPage)\n}",
"function list_episodes(playlist, n) {\n return new Promise(function(resolve, reject) {\n\tlet read_buffer = '';\n\tlet cmd = spawn(yt_cmd, \n\t\t\t['https://www.youtube.com/playlist?list=' + playlist, \n\t\t\t '-J', \n\t\t\t '--ignore-errors', \n\t\t\t '--playlist-end=' + n]);\n\t\n\tcmd.stdout.on('data', (data) => {\n\t read_buffer = read_buffer + data;\n\t});\n\tcmd.stderr.on('data', (data) => {\n\t console.log(`stderr: ${data}`);\n\t});\n\tcmd.on('close', (code) => {\n\t console.log(`child process exited with code ${code}`);\n\t try {\n\t\tvar j = JSON.parse(read_buffer);\n\t } catch(e) {\n\t\treject(e);\n\t\treturn;\n\t }\n\t var a = [];\n\t try {\n\t\tvar playlist_title = j.title;\n\t } catch (e) {\n\t\tconsole.log(\"Got error, reject the promise.\")\n\t\treject(e);\n\t\treturn;\n\t }\n\t register_playlist('playlist:' + playlist, {title: playlist_title});\n\t j.entries.forEach(function(e) {\n\t\t// a private episode can be a null value in the array\n\t\t// to test: \n\t\t// curl -X PUT http://localhost:6003/api/playlist/PLATwx1z00HsdanKZcTMQEc-n_Bhu_aZ76\n\t\tif (e != null) {\n\t\t a.push({url: e.id,\n\t\t\t title: e.title,\n\t\t\t upload_date: e.upload_date,\n\t\t\t playlist_title: playlist_title});\n\t\t}\n\t });\n\t resolve(a);\n\t});\n })\n}",
"function getMostPopular() {\n\tmoviesAbove70 = [];\n\t//clears array at the start to ensure no constant addons\n\tfor (movie in movieData) {\n\t\tlet fileName = path.join(\"jsonData/movies/\" + movieData[movie].Title);\n\n\t\tif (fs.existsSync(fileName)) {\n\t\t\tlet data = fs.readFileSync(fileName);\n\t\t\tlet movData = JSON.parse(data);\n\n\t\t\tif (movData.imdbRating > 7) {\n\t\t\t\tmoviesAbove70.push(movieData[movie]);\n\t\t\t}\n\n\t\t} else {\n\t\t\tres.status(404).send(\"Could not find Movie.\");\n\t\t}\n\t}\n}",
"async function getAllPastGames(){\n const now = app_utils.formatDateTime(new Date())\n const past_games = await DButils.execQuery(`SELECT Games.gameid, Games.GameDateTime, Games.HomeTeam, Games.HomeTeamID,\n Games.AwayTeam, Games.AwayTeamID, Games.Stadium, Games.Referee, Games.Result\n FROM Games WHERE GameDateTime <'${now}' ORDER BY GameDateTime `);\n\n return Promise.all(past_games.map(async (game) => {\n // Add the GMT with the time the server returns\n game['GameDateTime'].setTime(game['GameDateTime'].getTime() + game['GameDateTime'].getTimezoneOffset()*60*1000);;\n // Update the datetime to be in the correct format - YY:MM:DD HH:MM:SS.nnnn\n game['GameDateTime'] = app_utils.formatDateTime(game['GameDateTime'])\n\n // Get all the events assign to the game\n let events_ids = await DButils.execQuery(`SELECT eventid FROM GamesEvents WHERE gameid = ${game.gameid}`)\n // Build the list of events ids for the where clause -> (1,2,3,...)\n let query_ids = \"(\"\n events_ids.map(event => query_ids += `${event.eventid},`)\n query_ids = query_ids.replace(/,\\s*$/, \")\");\n\n // Assign the event log for each game. The same as joining the two tables (Games and GamesEvents)\n let events = await DButils.execQuery(`SELECT Events.EventDate, Events.EventTime,\n Events.EventGameTime, Events.EventDesc From Events \n WHERE eventid IN ${query_ids}`)\n Object.assign(game, {event_log: events});\n return game\n }));\n}",
"getBettingEventsBySeasonPromise(season){\n var parameters = {};\n parameters['season']=season;\n return this.GetPromise('/v3/nhl/odds/{format}/BettingEvents/{season}', parameters);\n }",
"function save(snpp, seasons)\n{\n\tvar ii;\n\n\tfor (ii = 0; ii < seasons.length; ii++)\n\t\tsnpp.walkEpisodes(seasons[ii], iterEpisode, iterDone);\n}",
"function getLatest(req, res)\n {\n // Find all SearchQuery objects\n var query = SearchQuery.find({});\n \n // Sort by date\n query.sort( [['_id', -1]] );\n // Limit to 10 searches\n query.limit(10);\n \n query.exec(function(err, obj){\n if(err){\n res.send(err);\n } \n else{\n res.send(obj.map(limitHistory));\n }\n });\n }",
"function getAdminEpisodes(show_id, season_num) {\n ajaxCall(\"GET\", \"../api/Episodes?show_id=\" + show_id + \"&season_num=\" + season_num, \"\", getAdminEpisodes_success, getAdminEpisodes_error);\n}",
"async function GetLatest() {\n try {\n const HistoricalQR = await getDB();\n return await HistoricalQR.findOne().sort({ _id: -1 });\n } catch (err) {}\n}",
"function getExpenditureHistory ()\r\n{\r\n //First get the month\r\n var date = new Date();\r\n var currentMonth = date.getMonth();\r\n var currentYear = date.getYear();\r\n\r\n return Expenditure.filter(getAssetByMonth);\r\n}",
"static async getLatestGame(teamId) {\r\n let latestGame = {};\r\n\r\n const options = await {\r\n method: 'GET',\r\n url: `https://api-nba-v1.p.rapidapi.com/games/teamId/${teamId}`,\r\n headers: {\r\n 'x-rapidapi-key': NBA_API_KEY,\r\n 'x-rapidapi-host': 'api-nba-v1.p.rapidapi.com'\r\n }\r\n };\r\n\r\n await axios.request(options).then(res => {\r\n let games = res.data.api.games;\r\n for (let game of games.reverse()) {\r\n if (game.statusGame === 'Finished') {\r\n latestGame = game;\r\n break;\r\n }\r\n }\r\n });\r\n\r\n return latestGame;\r\n }",
"function getStreamingServicesTvSeason(\n imdbId,\n entertainmentType,\n entertainmentType2,\n seasonNum\n) {\n var movieServicesLookupUrl =\n \"https://api.themoviedb.org/3/\" +\n entertainmentType +\n \"/\" +\n imdbId +\n \"/\" +\n entertainmentType2 +\n \"/\" +\n seasonNum +\n \"providers?api_key=42911e57fe3ba092d02b0df7293493b3\";\n fetch(movieServicesLookupUrl)\n .then(function (response) {\n return response.json();\n })\n .then(function (data) {\n console.log(data);\n // console.log(Object.keys(data.results.US));\n // console.log(Object.keys(data.results.US).includes(\"flatrate\"));\n console.log(Object.keys(data.results));\n services = [];\n obj.services = [];\n if (Object.keys(data.results).length == 0) {\n obj.services[0] = { name: \"No streaming services\" };\n } else if (Object.keys(data.results.US).includes(\"flatrate\")) {\n for (var j = 0; j < data.results.US.flatrate.length; j++) {\n services[j] = data.results.US.flatrate[j].provider_name;\n var logoPath = data.results.US.flatrate[j].logo_path;\n var networkLogo = getNetworkLogo(logoPath);\n switch (services[j]) {\n case \"IMDB TV Amazon Channel\":\n obj.services[j] = { name: services[j], url: imdbUrl, logo: networkLogo };\n break;\n case \"Hulu\":\n obj.services[j] = { name: services[j], url: huluUrl, logo: networkLogo };\n break;\n case \"fuboTV\":\n obj.services[j] = { name: services[j], url: fuboTvUrl, logo: networkLogo };\n break;\n case \"Netflix\":\n obj.services[j] = { name: services[j], url: netflixUrl, logo: networkLogo };\n break;\n case \"Apple TV Plus\":\n obj.services[j] = { name: services[j], url: appleTvPlusUrl, logo: networkLogo };\n break;\n case \"YoutubeTV\":\n obj.services[j] = { name: services[j], url: YoutubeTvUrl, logo: networkLogo };\n break;\n case \"HBO Max\":\n obj.services[j] = { name: services[j], url: HBOMaxUrl, logo: networkLogo };\n break;\n case \"HBO Now\":\n obj.services[j] = { name: services[j], url: HBONowUrl, logo: networkLogo };\n break;\n case \"DIRECTV\":\n obj.services[j] = { name: services[j], url: DirecTvUrl, logo: networkLogo };\n break;\n case \"Disney Plus\":\n obj.services[j] = { name: services[j], url: disneyPlusUrl, logo: networkLogo };\n break;\n case \"TNT\":\n obj.services[j] = { name: services[j], url: tntUrl, logo: networkLogo };\n break;\n case \"TBS\":\n obj.services[j] = { name: services[j], url: tbsUrl, logo: networkLogo };\n break;\n case \"tru TV\":\n obj.services[j] = { name: services[j], url: truTvUrl, logo: networkLogo };\n break;\n case \"Paramount+ Amazon Channel\":\n obj.services[j] = { name: services[j], url: paramountPlusUrl, logo: networkLogo };\n break;\n case \"CBS\":\n obj.services[j] = { name: services[j], url: cbsUrl, logo: networkLogo };\n break; \n case \"Sling TV\":\n obj.services[j] = { name: services[j], url: slingTvUrl, logo: networkLogo };\n break; \n case \"Spectrum On Demand\":\n obj.services[j] = { name: services[j], url: spectrumOnDemandUrl, logo: networkLogo };\n break; \n case \"Peacock Premium\":\n obj.services[j] = { name: services[j], url: peacokPremiumUrl, logo: networkLogo };\n break; \n case \"Funimation Now\":\n obj.services[j] = { name: services[j], url: funimationNowUrl, logo: networkLogo };\n break; \n case \"Adult Swim\":\n obj.services[j] = { name: services[j], url: adultSwimUrl, logo: networkLogo };\n break; \n default:\n obj.services[j] = { name: data.results.US.flatrate[j].provider_name, url: \" \", logo: networkLogo };\n break;\n }\n }\n } else {\n obj.services[0] = { name: \"No streaming services in US\" };\n }\n console.log(services);\n console.log(obj);\n renderMovieCard(obj);\n });\n}",
"function getExpenditureHistoryIndex (index)\r\n{\r\n //First get the month\r\n var date = new Date();\r\n var indexMonth = date.getMonth() - index;\r\n while (indexMonth < 0) {\r\n var currentYear = date.getYear() - 1;\r\n indexMonth += 11;\r\n }\r\n\r\n var temp = Expenditure.filter(getAssetByMonth);\r\n}",
"function filterBySeason(seasonNum, data) {\n // making sure that it is an int to compare\n seasonNum = parseInt(seasonNum, 10)\n return data.filter((current) => current.season == seasonNum)\n}",
"function onlyPossibleEpisodes(files, season, episode, absoluteEpisode) {\n const episodeRegex = (`@${episode}`).slice(-2).replace(/@/g, '0?');\n const absoluteEpisodeRegex = (`@@${absoluteEpisode}`).slice(-3).replace(/@/g, '0?');\n const seasonEpisodeRegex = `${season * 100 + episode}`;\n const fullRegex = new RegExp(`(?:\\\\D|^)(${episodeRegex}|${absoluteEpisodeRegex}|${seasonEpisodeRegex})\\\\D`);\n\n return files.filter((file) => fullRegex.test(file.name));\n}",
"function mostPopularDays(week) {\n\tif (week == null || week.length == 0){\n\t\tconsole.log ('mostPopularDays() - null or empty input');\n\t\treturn null;\n\t}\n\t\n\tvar maxDay = new Weekday(\"\",0);\n\t// first pass -- just try to print max\n\tfor (var i = 0; i < week.length; i++) {\n\t\t// current object is week[i]\n\t\tvar today = week[i];\n\t\t//console.log('item = ' + i + ' name= ' + today.name + ' traffic = ' + today.traffic);\n\t\t// is today the new max?\n\t\tif (today.traffic > maxDay.traffic) {\n\t\t\tmaxDay.traffic = today.traffic;\n\t\t\tmaxDay.name = today.name;\n\t\t}\n\t\n\t}\n\tconsole.log('Most popular is ' + maxDay.name + ' with traffic of ' + maxDay.traffic + ' days');\n\treturn maxDay.name\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
search for all recordings of tour, render a list of recordings | function searchInTour(production, tour) {
// console.log(tour);
// console.log(production);
FinalResults = Results[tour.replaceAll("'", "'")];
for (recording of FinalResults) {
addRecordingExtras(recording);
}
showTourResults(true, true);
} | [
"function showProductionTours(production) {\n Results = {};\n var tours = new Set();\n // var production;\n for (recording of loadedCSV.data) {\n if (recording.production && production && recording.production.toLowerCase().replaceAll(\"'\", \"'\") == production.toLowerCase()) {\n if (!tours.has(recording.tour)) {\n tours.add(recording.tour);\n Results[recording.tour] = [];\n }\n Results[recording.tour].push(recording);\n tours.add(recording.tour);\n }\n }\n if (tours.size <= 0) {\n document.getElementById(\"showResults\").innerHTML = \"No tours found :(\";\n document.getElementById(\"resultsTitle\").innerHTML = \"\";\n return;\n }\n\n tours = Array.from(tours).sort();\n\n var toursHtml = ejs.render(toursTemplate, {\n tours: tours,\n production: production,\n results: Results\n });\n\n var titleHtml = ejs.render(titleTemplate1, {\n production: production\n })\n\n document.getElementById(\"showResults\").innerHTML = toursHtml;\n document.getElementById(\"resultsTitle\").innerHTML = titleHtml;\n}",
"function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}",
"function _drawResults() {\n\n let template = \"\";\n store.state.songs.forEach(song => {\n template += song.SearchTemplate;\n });\n document.getElementById(\"songs\").innerHTML = template;\n}",
"function showAll(request){\n\tnamesDB.getAll(gotNames);\n\tfunction gotNames(names){\n\t\tnamesText = \"\";\n\t\tif (names.length > 0){\n\t\t\tfor (i =0; i < names.length; i++) {\n\t\t\t\t// create a link like: <a href=\"/view/1DlDQu55m85dqNQJ\">Joe</a><br/>\n\t\t\t namesText += '<a href=\"/view/' + names[i]._id + '\">' + names[i].name + \"</a><br/>\";\n\t\t\t}\n\t\t} else {\n\t\t\tnamesText = \"No people in the database yet.\";\n\t\t}\n\t\t\n\t\t//console.log(namesText);\n\t\tvar footerText = '<hr/><p><a href=\"/search\">Search</a>';\n\t\trequest.respond( namesText + footerText);\n\t}\t\n}",
"function displayFilmsData(data) {\r\n cartegoriesCounter = 0;\r\n var listBox = document.getElementById(\"searchResults\");\r\n listBox.innerHTML = \"\";\r\n listBox.innerHTML = \"<p>Title: \" + data.results[0].title + \"</p>\" +\r\n \"<br><p>Episode: \" + data.results[0].episode_id + \"</p><br>\" +\r\n \"<p>Opening Crawl:</p><br><p>\" + data.results[0].opening_crawl +\r\n \"<br><p>Director: \" + data.results[0].director + \"</p><br>\" +\r\n \"<p>Producer(s): \" + data.results[0].producer + \"</p>\";\r\n }",
"function allBy(artist){\n console.log(\"inside function allBy \", artist);\n // - when run, this function should return an array of all records in \"collection\"-\n // - that are by the given artist\n let resultArray = [];\n\n for(let i = 0; i < vinyl_collection.length; i++ ){\n if(vinyl_collection[i].artist === artist ){\n resultArray.push(vinyl_collection[i]);\n }\n }\n return resultArray;\n}",
"function showBookings() {\n var localBookings = loadLocalBookings();\n if (localBookings.length > 0) {\n localBookings.forEach(function (booking) {\n $(\"#bookingList\").append($(\"<li>\").text(booking.name + ': ' + booking.number + ' from ' + booking.checkin + ' to ' + booking.checkout));\n });\n $(\"#currentBookings\").show();\n } else {\n $(\"#currentBookings\").hide();\n }\n }",
"function renderTable() {\n // Set the value of ending index\n var endingIndex = startingIndex + resultsPerPage;\n\n $tbody.innerHTML = \"\";\n // Set the value of ending index\n for (var i = 0; i < filteredAliens.length; i++) {\n // Get the current address object and its fields\n var alien = filteredAliens[i];\n var fields = Object.keys(alien);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell and set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = alien[field];\n };\n };\n}",
"function showRecordings(myCId, myPermissions) {\r\n var myURL = \"RecordingsLister.php?CId=\" + myCId;\r\n if (myPermissions) {\r\n compilationPermissions.isAdmin = myPermissions[\"IsAdmin\"];\r\n compilationPermissions.canUpload = myPermissions[\"CanUpload\"];\r\n compilationPermissions.canAnnotate = myPermissions[\"CanAnnotate\"];\r\n compilationPermissions.canDownload = myPermissions[\"CanDownload\"];\r\n compilationPermissions.canAdd = myPermissions[\"CanAdd\"];\r\n compilationPermissions.canModify = myPermissions[\"CanModify\"];\r\n }\r\n // Reset the looping controls...\r\n autoLoop = 0;\r\n currentTrack = 0;\r\n\r\n // Put the record in the columnLeft div...\r\n clearDiv(\"columnLeft\");\r\n processAjax (myURL, \"columnLeft\");\r\n setBlockVis(\"columnLeft\", \"block\");\r\n return true;\r\n}",
"function searchForShow(elem) {\n const allShows = getAllShows();\n let searchString = elem.target.value.toLowerCase();\n let filteredShows = allShows.filter((episode) => {\n return (\n episode.name.toLowerCase().includes(searchString) ||\n episode.genres.join(\" \").toLowerCase().includes(searchString) || \n (episode.summary && episode.summary.toLowerCase().includes(searchString))\n );\n });\n container.innerHTML = \"\";\n makePageForShows(filteredShows);\n}",
"function showAllInfo(data) {\n $(\".info_section\").empty();\n if (verifyTeleportDataNotEmpty(data)) {\n const firstCity = data._embedded[`city:search-results`][0];\n showTeleportCityInfo(firstCity);\n showWikipediaInfo(firstCity[`matching_full_name`]);\n } \n else {\n displayNoSearchResults();\n }\n }",
"function displayTrailResults(trailResponseJson) {\n $('.js-trail-results').empty();\n let result = trailResponseJson.trails.length;\n if (trailResponseJson.trails.length === 0) {\n $('.js-trail-results').text('No trails found. Please try a different address.');\n } else {\n $('.js-trail-results').append(trailResponseJson.trails.map((trail) => \n `<li><h3>${trail.name}</h3></li>\n <li><i>${trail.summary}</i></li>\n <li>Difficulty: ${trail.difficulty}</li>\n <li>Location: ${trail.location}</li>\n <li>Condition: ${trail.conditionStatus}</li>\n <li>Length: ${trail.length} miles </li>\n <li><a href=\"${trail.url}\" target=\"_blank\">More Details</a></li>`));\n };\n $('.results').text(result);\n}",
"function printSearchResults (result) {\n console.log(`Found ${result.rowCount} by the name ${searchName}`);\n for (let i = 0; i < result.rowCount; i ++) {\n console.log(`- ${i + 1}: ${result.rows[i].first_name} ${result.rows[i].last_name}, born ${returnDateStr(result.rows[i].birthdate)}`)\n }\n}",
"function displaySelectedStationsText() {\n\n var description = '<div class=\"results_title\">Selected stations:</div><div class=\"results_group\">';\n \n Object.keys(selectedFilters['stationStart']).forEach(function(id) {\n if (id == -1) { return; }\n description += Hubway.stations[id]['name'] + '<br>';\n });\n \n description += '</div>'\n \n $(\"#js_description\").html(description); \n}",
"function getBeers() {\n //\n //\n //beers.list(); listBeer\n //\n var req = gapi.client.birra.beers.list();\n req.execute(function(data) {\n $(\"#results\").html('');\n showList(data); \n });\n}",
"function showResults() {\n ipMarkersGroup.eachLayer(function(layer) {\n if (layer.isPopupOpen()) {\n content = layer.getPopup().getContent();\n index = content.indexOf('<ul');\n index2 = content.indexOf('</div>');\n content = content.substr(index, index2);\n latLng = layer.getPopup().getLatLng();\n L.popup({\n maxWidth: 400\n }).setContent(content).setLatLng(latLng).openOn(mymap);\n return;\n }\n });\n\n scrapingMarkersGroup.eachLayer(function(layer) {\n if (layer.isPopupOpen()) {\n content = layer.getPopup().getContent();\n index = content.indexOf('<ul');\n index2 = content.indexOf('</div>');\n content = content.substr(index, index2);\n latLng = layer.getPopup().getLatLng();\n L.popup({\n maxWidth: 400\n }).setContent(content).setLatLng(latLng).openOn(mymap);\n return;\n }\n });\n}",
"function setupParticipantSearch() {\n var searchIndex;\n\n // test for the presence of the participant search form; if present, fetch the \"all people\" index\n // data from the server, and initialize the lunr index with the data.\n document.getElementById(\"participant_search_form\") &&\n fetch(\"/assets/json/all-people-index.json\")\n .then((res) => res.json())\n .then((data) => {\n searchIndex = lunr.Index.load(data);\n });\n\n // submit handler for the participant search form; assumes that the lunr index has been loaded and\n // indexed already per above\n on(\"submit\", \"#participant_search_form\", function (ev) {\n ev.preventDefault();\n var searchResultsCont = document.getElementById(\n \"people_search_results_container\"\n );\n searchResultsCont.classList.remove(\"d-none\");\n var searchResultsEl = document.getElementById(\"people_search_results\");\n if (searchIndex) {\n let queries = [\n ...ev.target.querySelectorAll(\n \"input[name=q], input[name='addl_query']\"\n ),\n ].map((i) => i.value);\n let allResults = queries.map((q) => searchIndex.search(q));\n\n // create hash of result ref and number of queries it shows up in\n let resultCountByRef = {};\n for (let i = 0; i < allResults.length; i++) {\n for (let j = 0; j < allResults[i].length; j++) {\n let ref = allResults[i][j].ref;\n if (!resultCountByRef[ref]) {\n resultCountByRef[ref] = 0;\n }\n resultCountByRef[ref] += 1;\n }\n }\n\n // While looping through the first result set, only add items to results\n // that in are in all result sets.\n let results = [];\n for (let i = 0; i < allResults[0].length; i++) {\n let ref = allResults[0][i].ref;\n if (resultCountByRef[ref] === queries.length) {\n results.push(allResults[0][i]);\n }\n }\n var mostRecentPeopleByName = {};\n var names = results.map((result) => {\n var person = window.allPeople.find((p) => p.id === result.ref);\n if (\n !mostRecentPeopleByName[person.name] ||\n mostRecentPeopleByName[person.name].year < person.year\n ) {\n mostRecentPeopleByName[person.name] = person;\n }\n return person.name;\n });\n var displayedNames = {};\n var resultHtml = names.map((personName) => {\n if (!personName) {\n return \"\";\n }\n var person = mostRecentPeopleByName[personName];\n if (!person || displayedNames[personName]) {\n return \"\";\n }\n displayedNames[personName] = true;\n let website =\n person.website ||\n person.webpage ||\n person.twitter ||\n person.linkedin ||\n person.google_scholar;\n let image = '<div style=\"width: 150px\" class=\"mr-5\"></div>';\n if (person.image) {\n image = `<img loading=\"lazy\" src=\"${person.image}\" alt=\"Image of ${person.name}\" class=\"mr-5 rounded\" width=\"150\">`;\n }\n let name = person.name;\n if (website) {\n name = `<a href=\"${website}\" target=\"_blank\" rel=\"noopener noreferrer\">${name}</a>`;\n }\n return `<div class=\"media mb-5\">\n ${image}\n <div class=\"media-body\">\n <h5 class=\"mt-0 font-weight-bold\">${name}${person.category\n ? ` <span class=\"badge badge-secondary\">${person.category}</span>`\n : \"\"\n }</h5>\n ${person.bio}\n </div>\n </div>`;\n });\n searchResultsEl.innerHTML = resultHtml.join(\" \");\n let zeroResultsEl = document.getElementById(\n \"zero_searches_results_found\"\n );\n let someResultsEl = document.getElementById(\"search_results_listing\");\n if (results.length === 0) {\n zeroResultsEl.classList.remove(\"d-none\");\n someResultsEl.classList.add(\"d-none\");\n } else {\n zeroResultsEl.classList.add(\"d-none\");\n someResultsEl.classList.remove(\"d-none\");\n }\n }\n });\n}",
"function showCorrectStreamers() {\n var search = $('input').val();\n var re = new RegExp('^' + search, 'i');\n var status = $('.notch').parent().attr('id');\n for (var i = 0; i < streamers.length; i++) {\n var $streamer = $('#' + streamers[i]);\n if ($streamer.hasClass(status)) {\n $streamer.show();\n }\n if (!re.test(streamers[i])) {\n $streamer.hide();\n }\n }\n }",
"function displayMatches(){\n const matchArray = findMatches(this.value, cities);\n\n const html = matchArray.map( place => {\n const regex = new RegExp(this.value, 'gi');\n\n const cityName = place.city.replace(regex, `<span class=\"hl\">${this.value}</span>`);\n const stateName = place.state.replace(regex, `<span class=\"hl\">${this.value}</span>`);\n\n return `\n <li>\n <span class=\"name\">${cityName}, ${stateName}</span>\n <span class=\"population\">${numberWithCommas(place.population)}</span>\n </li>\n `;\n }).join('');\n\n let match_txt = (matchArray.length > 1) ? ' matches' : ' match';\n founds.innerHTML = matchArray.length + match_txt + ' found.';\n \n if(this.value == ''){\n founds.style.display = 'none'; \n } else {\n founds.style.display = 'block'; \n }\n\n suggestions.innerHTML = html;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
display widget for uploading photos to cloudinary | showUploadWidget() {
cloudinary.openUploadWidget({
cloudName: 'dvgovtrrs',
uploadPreset: CLOUDINARY_UPLOAD_PRESET,
sources: [
'local',
'url',
'camera',
'image_search',
'facebook',
'dropbox',
'instagram',
],
googleApiKey: '<image_search_google_api_key>',
showAdvancedOptions: true,
cropping: true,
multiple: false,
defaultSource: 'local',
styles: {
palette: {
window: '#FFFFFF',
windowBorder: '#90A0B3',
tabIcon: '#0078FF',
menuIcons: '#5A616A',
textDark: '#000000',
textLight: '#FFFFFF',
link: '#0078FF',
action: '#FF620C',
inactiveTabIcon: '#0E2F5A',
error: '#F44235',
inProgress: '#0078FF',
complete: '#20B832',
sourceBg: '#E4EBF1',
},
fonts: {
default: {
active: true,
},
},
},
}, (err, info) => {
if (!err) {
console.log('Upload Widget event - ', info);
if (info.event === 'success') {
this.setState({
newUrl: info.info.secure_url,
});
}
}
});
} | [
"function displayMediaUpload() {\n\t\t\treturn (\n\t\t\t\t<div\n\t\t\t\t\tclassName=\"content-block-content content-block\"\n\t\t\t\t\tkey=\"two-column-content-upload\"\n\t\t\t\t>\n\t\t\t\t\t<h2>{ __( 'Image Column Area' ) }</h2>\n\t\t\t\t\t{ ! props.attributes.imgID ? (\n\t\t\t\t\t\t<MediaUpload\n\t\t\t\t\t\t\tbuttonProps={ {\n\t\t\t\t\t\t\t\tclassName: 'components-button button button-large',\n\t\t\t\t\t\t\t} }\n\t\t\t\t\t\t\tonSelect={ onSelectImage }\n\t\t\t\t\t\t\ttype=\"image\"\n\t\t\t\t\t\t\tvalue={ props.attributes.imgID }\n\t\t\t\t\t\t\trender={ ( { open } ) => (\n\t\t\t\t\t\t\t\t<Button className=\"button button-large\" onClick={ open }>\n\t\t\t\t\t\t\t\t\t<Dashicon icon=\"format-image\" /> { ! props.attributes.imgID ? __( 'Upload Image' ) : <img src={ props.attributes.imgURL } alt={ props.attributes.imgAlt } /> }\n\t\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t\t) }\n\t\t\t\t\t\t/>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<p className=\"image-wrapper\">\n\t\t\t\t\t\t\t<img\n\t\t\t\t\t\t\t\tsrc={ props.attributes.imgURL }\n\t\t\t\t\t\t\t\talt={ props.attributes.imgAlt }\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\t\tclassName=\"remove-image button button-large\"\n\t\t\t\t\t\t\t\tonClick={ onRemoveImage }\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<Dashicon icon=\"no-alt\" /> { __( 'Remove Image' ) }\n\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t</p>\n\t\t\t\t\t) }\n\t\t\t\t</div>\n\t\t\t);\n\t\t}",
"function PhotosWidget(hydroinst) \n{\n\tHydroWidget.call(this, hydroinst);\n\t\n\tthis.photos = [];\n}",
"function katalogSV () {\n //add image\n var files =new Array();\n $(\"input:file\").each(function() {\n files.push($(this).get(0).files[0]); \n });\n \n // Create a formdata object and add the files\n var filesAdd = new FormData();\n $.each(files, function(key, value){\n filesAdd.append(key, value);\n });\n\n if($('#k_photoTB').val()=='')//upload\n katalogDb('');\n else// ga upload\n katalogUp(filesAdd);\n }",
"function handleRequestUploadImageResponseAction(action, response) {\n var label = action.Metadata.Label || \"Upload Image\"\n response.displayLinkCollection.Sections.push({\n \"SectionID\": 0,\n \"HeaderText\": \"\",\n \"FoldLocation\": 6,\n \"FoldText\": \"Click for more...\",\n \"Links\": [\n {\n \"DisplayText\": label,\n \"TargetType\": \"Image Upload\",\n \"SectionID\": 0,\n \"Metadata\": {\n \"InputText\": \"Yes\",\n \"Source\": {\n \"Origin\": \"responseset\",\n \"UID\": \"91ca2411-1a37-4e1e-88ae-e8ada46afcba\"\n },\n \"DisplayStyle\": \"Default\"\n }\n }\n ]\n });\n }",
"function afiCreateImage( $imageContainer, $deleteImage, $uploadImage, json, inputField){\n\t\t$imageContainer.append( '<img src=\"' + json.url + '\" alt=\"' + json.caption + '\" style=\"max-width: 100%;\" />' );\n\t\tinputField.val( json.url );\n\t\t$deleteImage.removeClass( 'hidden' );\n\t\t$uploadImage.addClass( 'hidden' );\n\t}",
"function fileUploadHandler () {\n const fd = new FormData();\n fd.append('image', photos[0], photos[0].name);\n const getUrls = async (form) =>{\n const result = await axios.post(`https://api.imgbb.com/1/upload?key=${config.imgtoken}`, form)\n let x = thumbs;\n let y = photoUrls;\n x.push(result.data.data.thumb.url);\n y.push(result.data.data.image.url);\n setPhotoUrls(y);\n setThumbs(x);\n }\n getUrls(fd);\n }",
"function generateUploadifyHtml(name, img_url, deleted_url, type)\n{\n deleted_url += \"?type=\" + type + \"&img=\" + name;\n html = '<div class=\"pointer-mouse\" style=\";float:left;margin-right:5px;margin-top:5px;\">';\n html += '<div class=\"img_hover\">';\n html += '<img src=\"' + img_url + name + '\" style=\"width:100px;height:100px\" onclick=\"dozoomer(this)\" />';\n html += '</div>';\n html += '<input type=\"hidden\" name=\"uploaded_image[]\" value=\"' + name + '\" />';\n html += '<input type=\"text\" name=\"image_title[]\" value=\"Title\" />';\n html += '<input class=\"image_radio\" type=\"radio\" name=\"model_image\" value=\"' + name + '\" title=\"Primary image\" alt=\"Primary image\" />';\n html += '<div class=\"clear\"></div>';\n html += '<a href=\"#deltetimage\" onclick=\"deletetimage(this)\">Delete</a>';\n html += '<input type=\"hidden\" name=\"href_path\" value=\"' + deleted_url + '\" />';\n html += '</div>';\n\n return html;\n}",
"function show_image_upload_form() {\n let profile_upload = document.getElementById(\"profile-image-upload-form\");\n profile_upload.style.display = \"\";\n let profile_info = document.getElementById(\"profile-info-form\");\n profile_info.style.display = \"none\";\n}",
"function processNewUpload(fileList) {\n let file = getFile(fileList);\n if (file !== null) {\n \n //displayImg.onload = customImgOnload();\n displayImg.onload = function(){\n if (displayImg.naturalHeight > displayImg.naturalWidth){\n //portrait ratio\n origImgH = containerHeight;\n origImgW = displayImg.naturalWidth * containerHeight / displayImg.naturalHeight;\n dispImgLeft = (containerWidth - origImgW) / 2;\n dispImgTop = 0;\n displayImg.height = origImgH;\n displayImg.width = origImgW;\n } else {\n //landscape (or square) ratio\n if(displayImg.naturalWidth/displayImg.naturalHeight > containerWidth/containerHeight){\n // w/h ratio is larger than that of the frame where the image is dislayed\n origImgH = displayImg.naturalHeight * containerWidth / displayImg.naturalWidth;\n origImgW = containerWidth;\n dispImgTop = (containerHeight - origImgH) / 2;\n dispImgLeft = 0;\n displayImg.height = origImgH;\n displayImg.width = origImgW;\n } else {\n // w/h ratio is smaller than that of the frame where the image is dislayed \n origImgH = containerHeight;\n origImgW = displayImg.naturalWidth * containerHeight / displayImg.naturalHeight;\n dispImgLeft = (containerWidth - origImgW) / 2;\n dispImgTop = 0;\n displayImg.height = origImgH;\n displayImg.width = origImgW;\n }\n }\n //assigns the value of the original display to the display (the one that changes with zoom, rotate and dragging)\n dispImgH = origImgH; \n dispImgW = origImgW;\n dispImgOriginX = origImgW/2;\n dispImgOriginY = origImgH/2;\n \n updateDisplayImageAttributes();\n }\n \n displayImg.src = URL.createObjectURL(file);\n console.log('displayImg', displayImg);\n\n //Saves the image in the imgArray\n imgNames.push({\n \"name\": file.name,\n \"size\": file.size,\n \"type\": file.type,\n \"naturalW\": displayImg.naturalWidth,\n \"naturalH\": displayImg.naturalHeight,\n \"dispOrigW\": origImgW,\n \"dispOrigH\": origImgH,\n\n \"src\": dispImgInfo.loca\n });\n \n //Updates the image list with the name of the recently uploaded image\n lista.insertAdjacentHTML('beforeend',\"<li class='list-item'>\" + imgNames[imgNames.length-1].name + \"</li>\");\n \n //Assigns the IDs of all the elements in the list\n refreshIds();\n\n //Adds, to the newly added list item, the listener to change on click\n lista.lastElementChild.addEventListener('click', (e) => {\n killE(e);\n selectNthChild(e.target.id);\n });\n //Selects the most recently uploaded image's name on the list\n selectNthChild(lista.children.length-1);\n\n checkButtons();\n }\n}",
"function VaadinUpload(params) {\n\tthis.component = $('<vaadin-upload>', {\n\t\t\n\t});\n}",
"function createImageInputWrapper () {\n const wrapper = document.getElementById('image-input-outer-wrapper');\n\n const innerWrapper = document.createElement('div');\n innerWrapper.classList.add('settings-each-input-wrapper');\n\n const inputTitle = document.createElement('span');\n inputTitle.classList.add('general-input-title');\n inputTitle.innerHTML = 'Profile Photo';\n innerWrapper.appendChild(inputTitle);\n \n const imageInputWrapper = document.createElement('label');\n imageInputWrapper.classList.add('general-choose-image-input-text');\n\n const imageSpan = document.createElement('span');\n imageSpan.innerHTML = 'Choose a profile photo';\n imageInputWrapper.appendChild(imageSpan);\n\n const imageInput = document.createElement('input');\n imageInput.classList.add('display-none');\n imageInput.id = 'image-input';\n imageInput.type = 'file';\n imageInput.accept = 'image/*';\n imageInputWrapper.appendChild(imageInput);\n\n innerWrapper.appendChild(imageInputWrapper);\n wrapper.appendChild(innerWrapper);\n wrapper.insertBefore(innerWrapper, innerWrapper.previousElementSibling);\n wrapper.insertBefore(innerWrapper, innerWrapper.previousElementSibling);\n}",
"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 imagebisButtonClick(e, data) {\n\t\t// Wire up the submit button click event handler\n\t\t$(data.popup).find(\"input[type=file]\")\n\t\t\t.unbind(\"change\")\n\t\t\t.bind(\"change\", function(e) {\n\t\t\t\tvar $_this = $(this);\n\n\t\t\t\t// Get the editor\n\t\t\t\tvar editor = data.editor; \n\t\t\t\t$_this.upload(URL_SITE+'ajax:photo/upload/align:'+ $(data.popup).find(\"input:radio[name=align]:checked\").val() +'/', function(res) {\n\t\t\t\t\tvar html = res.image;\n\n\t\t\t\t\t// Insert the html\n\t\t\t\t\tif (res.image) {\n\t\t\t\t\t\teditor.execCommand(data.command, html, null, data.button);\n\t\t\t\t\t\teditor.find( 'img[src=\"'+html+'\"]' ).attr( 'align', $(data.popup).find(\"input:radio[name=align]:checked\").val() );\n\t\t\t\t\t}\n\t\t\t\t}, 'json');\n\n\t\t\t\t// reset popup\n\t\t\t\t$(this).val('');\n\t\t\t\teditor.hidePopups();\n\t\t\t\teditor.focus();\n\t\t\t}\n\t\t);\n\t}",
"function imageUploaded(error, result) {\n $('#recipe-upload-image').prop(\"src\", result[0].secure_url);\n $('#image_upload_url').val(result[0].secure_url);\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 }",
"preUpload(e){\n e.target.closest('.text').querySelector('input[type=\"file\"]').click()\n }",
"function ciniki_writingcatalog_images() {\n this.webFlags = {\n '1':{'name':'Visible'},\n };\n this.init = function() {\n //\n // The panel to display the edit form\n //\n this.edit = new M.panel('Edit Image',\n 'ciniki_writingcatalog_images', 'edit',\n 'mc', 'medium', 'sectioned', 'ciniki.writingcatalog.images.edit');\n this.edit.default_data = {};\n this.edit.data = {};\n this.edit.writingcatalog_id = 0;\n this.edit.sections = {\n '_image':{'label':'Image', 'type':'imageform', 'fields':{\n 'image_id':{'label':'', 'type':'image_id', 'hidelabel':'yes', 'controls':'all', 'history':'no'},\n }},\n 'info':{'label':'Information', 'type':'simpleform', 'fields':{\n 'name':{'label':'Title', 'type':'text', },\n// 'webflags':{'label':'Website', 'type':'flags', 'join':'yes', 'flags':this.webFlags},\n }},\n '_website':{'label':'Website Information', 'fields':{\n 'webflags_1':{'label':'Visible', 'type':'flagtoggle', 'field':'webflags', 'bit':0x01, 'default':'on'},\n }},\n '_description':{'label':'Description', 'type':'simpleform', 'fields':{\n 'description':{'label':'', 'type':'textarea', 'size':'medium', 'hidelabel':'yes'},\n }},\n '_buttons':{'label':'', 'buttons':{\n 'save':{'label':'Save', 'fn':'M.ciniki_writingcatalog_images.saveImage();'},\n 'delete':{'label':'Delete', 'visible':'no', 'fn':'M.ciniki_writingcatalog_images.deleteImage();'},\n }},\n };\n this.edit.fieldValue = function(s, i, d) { \n if( this.data[i] != null ) {\n return this.data[i]; \n } \n return ''; \n };\n this.edit.fieldHistoryArgs = function(s, i) {\n return {'method':'ciniki.writingcatalog.imageHistory',\n 'args':{'tnid':M.curTenantID, \n 'writingcatalog_image_id':M.ciniki_writingcatalog_images.edit.writingcatalog_image_id, 'field':i}};\n };\n this.edit.addDropImage = function(iid) {\n M.ciniki_writingcatalog_images.edit.setFieldValue('image_id', iid, null, null);\n return true;\n };\n this.edit.sectionGuidedTitle = function(s) {\n if( s == '_image' ) {\n if( this.data.image_id != null && this.data.image_id > 0 ) {\n return this.sections[s]['gtitle-edit'];\n } else {\n return this.sections[s]['gtitle-add'];\n }\n }\n if( this.sections[s] != null && this.sections[s].gtitle != null ) { return this.sections[s].gtitle; }\n return null;\n };\n this.edit.sectionGuidedText = function(s) {\n if( s == '_image' ) {\n if( this.data.image_id != null && this.data.image_id > 0 ) {\n return this.sections[s]['gtext-edit'];\n } else {\n return this.sections[s]['gtext-add'];\n }\n }\n if( s == '_buttons' ) {\n if( this.sections[s].buttons.delete.visible == 'yes' ) {\n return this.sections[s]['gtext-edit'];\n } else {\n return this.sections[s]['gtext-add'];\n }\n }\n if( this.sections[s] != null && this.sections[s].gtext != null ) { return this.sections[s].gtext; }\n return null;\n };\n this.edit.sectionGuidedMore = function(s) {\n if( s == '_image' ) {\n if( this.data.image_id != null && this.data.image_id > 0 ) {\n return this.sections[s]['gmore-edit'];\n } else {\n return this.sections[s]['gmore-add'];\n }\n }\n if( s == '_buttons' ) {\n if( this.sections[s].buttons.delete.visible == 'yes' ) {\n return this.sections[s]['gmore-edit'];\n }\n }\n if( this.sections[s] != null && this.sections[s].gmore != null ) { return this.sections[s].gmore; }\n return null;\n };\n this.edit.addButton('save', 'Save', 'M.ciniki_writingcatalog_images.saveImage();');\n this.edit.addClose('Cancel');\n };\n\n this.start = function(cb, appPrefix, aG) {\n args = {};\n if( aG != null ) { args = eval(aG); }\n\n //\n // Create container\n //\n var appContainer = M.createContainer(appPrefix, 'ciniki_writingcatalog_images', 'yes');\n if( appContainer == null ) {\n M.alert('App Error');\n return false;\n }\n\n if( args.add != null && args.add == 'yes' ) {\n this.showEdit(cb, 0, args.writingcatalog_id);\n } else if( args.writingcatalog_image_id != null && args.writingcatalog_image_id > 0 ) {\n this.showEdit(cb, args.writingcatalog_image_id);\n }\n return false;\n }\n\n this.showEdit = function(cb, iid, eid) {\n if( iid != null ) { this.edit.writingcatalog_image_id = iid; }\n if( eid != null ) { this.edit.writingcatalog_id = eid; }\n this.edit.reset();\n if( this.edit.writingcatalog_image_id > 0 ) {\n this.edit.sections._buttons.buttons.delete.visible = 'yes';\n var rsp = M.api.getJSONCb('ciniki.writingcatalog.imageGet', \n {'tnid':M.curTenantID, 'writingcatalog_image_id':this.edit.writingcatalog_image_id}, function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n }\n M.ciniki_writingcatalog_images.edit.data = rsp.image;\n M.ciniki_writingcatalog_images.edit.refresh();\n M.ciniki_writingcatalog_images.edit.show(cb);\n });\n } else {\n this.edit.data = {};\n this.edit.sections._buttons.buttons.delete.visible = 'no';\n this.edit.refresh();\n this.edit.show(cb);\n }\n };\n\n this.saveImage = function() {\n if( this.edit.writingcatalog_image_id > 0 ) {\n var c = this.edit.serializeFormData('no');\n if( c != '' ) {\n var rsp = M.api.postJSONFormData('ciniki.writingcatalog.imageUpdate', \n {'tnid':M.curTenantID, \n 'writingcatalog_image_id':this.edit.writingcatalog_image_id}, c,\n function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n } else {\n M.ciniki_writingcatalog_images.edit.close();\n }\n });\n } else {\n this.edit.close();\n }\n } else {\n var c = this.edit.serializeFormData('yes');\n var rsp = M.api.postJSONFormData('ciniki.writingcatalog.imageAdd', \n {'tnid':M.curTenantID, 'writingcatalog_id':this.edit.writingcatalog_id}, c,\n function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n } else {\n M.ciniki_writingcatalog_images.edit.close();\n }\n });\n }\n };\n\n this.deleteImage = function() {\n M.confirm('Are you sure you want to delete this image?',null,function() {\n var rsp = M.api.getJSONCb('ciniki.writingcatalog.imageDelete', {'tnid':M.curTenantID, \n 'writingcatalog_image_id':M.ciniki_writingcatalog_images.edit.writingcatalog_image_id}, function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n }\n M.ciniki_writingcatalog_images.edit.close();\n });\n });\n };\n}",
"function tag_cloud (data)\n { ftags = format_tags (data.tags, data.nct);\n\n $(\"#tag_cloud\").jQCloud(ftags, {width:640, height:280});\n $(\"#tag_cloud_container\").show();\n }",
"function ongetImageUrlQuerySucceeded() {\n var serverrelativeurl = this.parentWeb.get_serverRelativeUrl();\n var imagepath = this.targetFile.get_serverRelativeUrl();\n var filename = this.targetFile.get_name();\n if (serverrelativeurl && filename && imagepath) {\n appData.ImageLibraryFullPath = imagepath.toLowerCase().replace(serverrelativeurl.toLowerCase(), '').replace(filename.toLowerCase(), '');\n var slashtrimmedstring = appData.ImageLibraryFullPath.trimStart(\"/\").trimEnd(\"/\");\n var firstSlash = slashtrimmedstring.indexOf(\"/\");\n if (firstSlash != -1) {\n appData.ImageLibraryName = slashtrimmedstring.substring(0, firstSlash);\n }\n else {\n appData.ImageLibraryName = slashtrimmedstring;\n }\n\n pictureData.imagesource = pictureSource.SharePoint;\n pictureData.FileName = filename;\n\n processAssetPickerData();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clears highlights from all the fields of the board | clearHighlights(){
for(let i=0;i<this._fields.length;i++){
for(let j=0;j<this._fields.length;j++){
this._fields[i][j].removeHighlight();
}
}
} | [
"clearHighlight () {\n this._vizceral.setHighlightedNode(undefined);\n }",
"function resetDrawingHighlights() {\n abEamTcController.resetDrawingHighlights();\n}",
"function clearHighlightsOnPage()\n{\n\tunhighlight(document.getElementsByTagName('body')[0]);\n\tcssstr = \"\";\n\tupdateStyleNode(cssstr);\n\tlastText = \"\";\n}",
"function removeOldHighlights() {\r\n var i, div;\r\n\r\n // Reset the colors\r\n for (i = 0; i < squaresWithHighlights.length; ++i) {\r\n div = document.getElementById(squaresWithHighlights[i].pos);\r\n div.style.backgroundColor = \r\n chess.board.isWhiteSquare(squaresWithHighlights[i].pos) ? \r\n 'white' : 'black';\r\n }\r\n\r\n // Clear the array\r\n squaresWithHighlights = [];\r\n\r\n // Re-add the currently selected square, if there is one\r\n if (chess.game.selectedPiece) {\r\n highlightSquare(chess.game.selectedPiece.pos, 'selected');\r\n }\r\n }",
"function clearHighlightCanvas() {\n\tvar highlightCanvas = document.getElementById('highlight-points')\n\tvar highlightCtx = highlightCanvas.getContext('2d')\n\thighlightCtx.clearRect(0, 0, highlightCanvas.offsetWidth, highlightCanvas.offsetHeight)\n}",
"function clearReadHighlighting() {\n $(\".show-read\").removeClass(\"show-read\");\n assembly.highlight_read_reg = \"\"\n}",
"function clearWriteHighlighting() {\n $(\".show-write\").removeClass(\"show-write\");\n assembly.highlight_write_reg = \"\";\n}",
"clear_stacks(){\n this.board.forEach(stack=>{\n $(stack.id).empty().css(\"background-color\", \"white\")\n stack.empty()\n })\n }",
"function unselectFeature() {\n if (highlight) {\n highlight.remove();\n }\n }",
"function clearSelectedStates() {\n _scope.ugCustomSelect.selectedCells = [];\n }",
"function resetChair() {\n // color the chair with default color\n resetChairColors();\n view.renderSelectedColors();\n // remove all features\n view.renderFeatures();\n // remove highlight on all options (features)\n view.resetChosenOptions();\n // clear the selected features ul\n view.resetSelectedFeatures();\n}",
"clearSelections () {\n this.editor.setCursorBufferPosition(this.editor.getCursorBufferPosition())\n }",
"function clearColor(){\n for (var i = 0; i < squares.length; i++) {\n squares[i].bgColor = 'white';\n }\n}",
"function unhighlightButton(oButton){\r\n oButton.style.backgroundColor = \"\";\r\n oButton.style.color = \"\";\r\n }",
"clearSelect() {\n const [selection] = this.cm.getDoc().listSelections();\n\n if (selection) {\n this.cm.setCursor(selection.to());\n }\n }",
"removeHighlight(index: number): void {\n var unhighlighter = new RangeUnhighlighter();\n unhighlighter.undo(index);\n if (highlightSubjects && highlightSubjects.length && highlightSubjects[index] != null) {\n var copy = highlightSubjects.slice(0);\n copy[index] = null;\n setHighlightSubjects(copy);\n }\n }",
"function clearAllSelection(){\n ds.clearSelection();\n arrDisp.length=0;\n updateSelDisplay();\n updateCurrSelection('','','startIndex',0);\n updateCurrSelection('','','endIndex',0);\n}",
"function remove_highlight_heatmap() {\r\n\r\n // Hide\r\n document.querySelector('#highlighter_container').style.display = \"none\";\r\n\r\n // Remove all highlighters\r\n node = $('.highlighter');\r\n for(i = 1; i<node.length; i++)\r\n node[i].remove();\r\n}",
"function clearBorderAll(){\n\tvar palette_colours_div = document.getElementById(\"palette_colours\");\n\n\tfor (i=0;i<palette_colours_div.childNodes.length;i++){\n\t\t// get all the colour cells\n\t\tvar colour_cell_div = palette_colours_div.childNodes[i];\n\n\t\t// get current style background by splitting the style property\n\t\tvar currentStyleBackground = colour_cell_div.getAttribute(\"style\").split(\";\")[0];\n\n\t\t//use it to build a new style property with white borders\n\t\tvar newStyle = currentStyleBackground+\";\"+DEFAULT_BORDER;\n\n\t\tcolour_cell_div.setAttribute(\"style\",newStyle);\n\t}\n\n}",
"function clearBlock(){\n\tfor(var i = 0; i < 4; i++){\n\t\tif(currentBlock[i].x < 0 || currentBlock[i].y < 0){\n\t\t\tcontinue;\n\t\t}\n\t\tboardGui.rows[currentBlock[i].x].cells[currentBlock[i].y].style.backgroundColor = \"white\"; \n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to build query for UPDATE actions in "transactions" table values can be a plain object where each keyvalue pair is the field that needs to be updated in the db row filterConfig is supposed to supply the WHERE clause info for the update query this is not very robust at the moment | function transactionsUpdateBuilder(values, filterConfig = { filter: "" }) {
// values should not be undefined, and it should be an object with at least one entry
if (!values || Object.keys(values).length === 0) {
return;
}
// build up the part of the query that sets each field to be updated, e.g. for values of {name: "steve", age: 57}
// should get something resembling => name = "steve", age = 57
let setStatement = "";
let subParam = 1;
const setVals = Object.keys(values);
for (let key of setVals) {
if (key !== "tags") {
// req.body being passed in as the values object - it may include tags as a property to indicate which tags to add or remove
// tags only pertains to tags_transactions table, so it should be ignored when constructing the query to update a row in "transactions"
setStatement += `${key} = $${subParam}, `;
subParam += 1;
}
}
// remove trailing comma in setStatement after generating it
setStatement = setStatement.slice(0, -2);
return `UPDATE transactions SET ${setStatement} WHERE ${filterConfig.filter} = $${subParam};`;
} | [
"function sqlForPartialUpdate(dataToUpdate, jsToSql) {\n // get keys from data to update object\n const keys = Object.keys(dataToUpdate);\n if (keys.length === 0) throw new BadRequestError('No data');\n\n /* get an array of strings where each string is the corresponding db column name for each key\n * set equal to the index-based parameter number for the sql command\n * ex: {firstName: 'Aliya', age: 32} => ['\"first_name\"=$1', '\"age\"=$2'] */\n const cols = keys.map(\n (colName, idx) => `\"${jsToSql[colName] || colName}\"=$${idx + 1}`\n );\n\n /* return object where setCols is the joined string of all col values from above and\n * values is an array of the actual values that correspond to each db parameter\n * being set in the setCol string */\n return {\n setCols: cols.join(', '),\n values: Object.values(dataToUpdate),\n };\n}",
"function sqlForPartialUpdate(dataToUpdate, propertyToColumnNameMap = {}) {\n const keys = Object.keys(dataToUpdate);\n if (keys.length === 0) throw new BadRequestError(\"No data\");\n\n // {firstName: 'Aliya', age: 32} => ['\"first_name\"=$1', '\"age\"=$2']\n const cols = keys.map(\n (dataPropertyName, idx) =>\n `\"${propertyToColumnNameMap[dataPropertyName] || dataPropertyName}\"=$${\n idx + 1\n }`\n );\n\n return {\n setCols: cols.join(\", \"),\n values: Object.values(dataToUpdate),\n };\n}",
"async update(params) {\n try {\n const updateCore_tickData = `UPDATE core_tickData_${params.feed} set symbol='${params.symbol}'\n , date='${params.date}' ,price=${params.price}, volume=${params.volume}\n WHERE id=${params.id} AND ca='${params.ca}' IF EXISTS`;\n return await this._core.DBManager.engine.execute(updateCore_tickData);\n } catch (e) {\n console.log(e);\n }\n }",
"function updActivityDataWithSyncActivityId(syncId){\n console.log(\"updating all rows with sync id : \"+syncId);\n// for(var i=0;i<l_synAllData.length();i++){\n// if(l_synAllData[i].syncStatus==\"OK\"){\n// updSyncAllDetailsInActivityWithActivityId(l_synAllData[i].activityId, l_synAllData[i].syncImmediate, l_synAllData[i].syncImmediateStatus, syncId);\n// }\n// else\n// updSyncAllDetailsInActivityWithActivityId(l_synAllData[i].activityId, l_synAllData[i].syncImmediate, l_synAllData[i].syncImmediateStatus, 0);\n// }\n currentStncAllDataUploadId = 0;\n\n if(l_synAllData[currentStncAllDataUploadId].syncStatus==\"OK\"){\n updSyncAllDetailsInActivityWithActivityId(l_synAllData[currentStncAllDataUploadId].activityId, l_synAllData[currentStncAllDataUploadId].syncImmediate, l_synAllData[currentStncAllDataUploadId].syncImmediateStatus, syncId);\n }\n else\n updSyncAllDetailsInActivityWithActivityId(l_synAllData[currentStncAllDataUploadId].activityId, l_synAllData[currentStncAllDataUploadId].syncImmediate, l_synAllData[currentStncAllDataUploadId].syncImmediateStatus, 0);\n\n}",
"update_reservation(account_id, attraction, old_time, old_date, new_attraction, new_time, new_date) {\n let sql = \"UPDATE reservations SET attractionRideName=$new_attraction, time=$new_time, date=$new_date WHERE attractionRideName=$attraction AND time=$old_time AND date=$old_date AND user=$user\";\n this.db.run(sql, {\n $attraction: attraction,\n $new_attraction: new_attraction,\n $old_time: old_time,\n $old_date: old_date,\n $user: account_id,\n $new_time: new_time,\n $new_date: new_date,\n }, (err) => {\n if(err) {\n throw(err);\n }\n });\n }",
"update(...specs) {\n return resolveTransaction(this, specs, true);\n }",
"function updateItemsAscensorValoresIniciales(n_cliente,n_equipo,n_empresamto,o_tipoaccion,v_capacperson,v_capacpeso,v_paradas,f_fecha,v_codigo,o_consecutivoinsp,ultimo_mto,inicio_servicio,ultima_inspeccion,h_hora,o_tipo_informe, k_codusuario,k_codinspeccion) {\n db.transaction(function (tx) {\n var query = \"UPDATE ascensor_valores_iniciales SET n_cliente = ?,\"+\n \"n_equipo = ?,\"+\n \"n_empresamto = ?,\"+\n \"o_tipoaccion = ?,\"+\n \"v_capacperson = ?,\"+\n \"v_capacpeso = ?,\"+\n \"v_paradas = ?,\"+\n \"f_fecha = ?,\"+\n \"v_codigo = ?,\"+\n \"o_consecutivoinsp = ?,\"+\n \"ultimo_mto = ?,\"+\n \"inicio_servicio = ?,\"+\n \"ultima_inspeccion = ?,\"+\n \"h_hora = ?,\"+\n \"o_tipo_informe = ? \"+\n \"WHERE k_codusuario = ? \"+\n \"AND k_codinspeccion = ?\";\n tx.executeSql(query, [n_cliente,n_equipo,n_empresamto,o_tipoaccion,v_capacperson,v_capacpeso,v_paradas,f_fecha,v_codigo,o_consecutivoinsp,ultimo_mto,inicio_servicio,ultima_inspeccion,h_hora,o_tipo_informe, k_codusuario,k_codinspeccion], function(tx, res) {\n console.log(\"rowsAffected updateItemsAscensorValoresIniciales: \" + res.rowsAffected);\n $('#texto_carga').text(\"Actualizando datos iniciales...Espere\");\n },\n function(tx, error) {\n console.log('UPDATE error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}",
"function updateItemsAscensorValoresFinales(k_codusuario,k_codinspeccion,o_observacion) {\n db.transaction(function (tx) {\n var query = \"UPDATE ascensor_valores_finales SET o_observacion = ?\"+\n \"WHERE k_codusuario = ? \"+\n \"AND k_codinspeccion = ?\"; \n tx.executeSql(query, [o_observacion,k_codusuario,k_codinspeccion], function(tx, res) {\n console.log(\"rowsAffected updateItemsAscensorValoresFinales: \" + res.rowsAffected);\n $('#texto_carga').text(\"Actualizando datos de observación...Espere\");\n },\n function(tx, error) {\n console.log('UPDATE error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}",
"function getSalesforceAccounts(res, accountProvisioningConditions, utcDate, previousDate, callback) {\n var results = [];\n\n var query = \"\";\n var dynamicQuery = \"\";\n var conditions = accountProvisioningConditions.condition;\n var mapping = accountProvisioningConditions.mapping;\n var mappedFields = \"\";\n\n if (conditions.length) {\n\n if (accountProvisioningConditions.filterLogic != \"\") {\n\n for(var k = 0 ; k < conditions.length ; k++)\n {\n var x = k+1;\n var y = \" \" + conditions[k].field + \" \" + conditions[k].operator + \" '\" + conditions[k].value + \"' \";\n dynamicQuery = accountProvisioningConditions.filterLogic.replace(x,y);\n accountProvisioningConditions.filterLogic = dynamicQuery;\n }\n\n }\n else{\n\n query = \" \" +conditions[0].field + \" \" + conditions[0].operator + \" '\" + conditions[0].value + \"' \";\n\n }\n\n console.log(dynamicQuery);\n query = query + dynamicQuery;\n\n\n // for (var i = 0; i < conditions.length; i++) {\n // if (accountProvisioningConditions.filterLogic != \"\") {\n //\n //\n //\n //\n // if (i != conditions.length - 1) {\n // query = query + conditions[i].field + \" \" + conditions[i].operator + \" '\" + conditions[i].value + \"' \" + filterLogic[i] + \" \";\n // }\n // else {\n // query = query + conditions[i].field + \" \" + conditions[i].operator + \" '\" + conditions[i].value + \"'\";\n //\n // }\n // }\n // else {\n // query = query + conditions[i].field + \" \" + conditions[i].operator + \" '\" + conditions[i].value + \"'\";\n //\n // }\n //\n // }\n\n }\n\n mapping.forEach(function (result) {\n if (mappedFields.indexOf(result.salesforceField) == -1) {\n if (result.salesforceField != \"Id\") {\n mappedFields = mappedFields + result.salesforceField + \" ,\";\n }\n\n }\n\n\n });\n mappedFields = mappedFields.substring(0, mappedFields.length - 1);\n\n\n if (query != \"\") {\n var accountQuery = \"select Id,\" + mappedFields + \" from Account where LastModifiedDate <= \" + utcDate;\n accountQuery += \" and LastModifiedDate >= \" + previousDate + \" and ( \" + query + \" )\" ;\n\n }\n else {\n var accountQuery = \"select Id,\" + mappedFields + \" from Account where LastModifiedDate <= \" + utcDate;\n accountQuery += \" and LastModifiedDate >= \" + previousDate;\n\n }\n conn.query(accountQuery, function (err, result) {\n if (err) {\n console.log(\"error\", err);\n res.send(\"some error occured\");\n }\n else {\n\n if (result.totalSize != 0) {\n\n console.log(result.records);\n accountProvisioningConditions.data = result.records;\n callback(null, accountProvisioningConditions);\n\n }\n else {\n res.send(\"no accounts matching\");\n }\n }\n\n });\n\n}",
"function update_filters() {\n //get currently selected (or unselected values for all ids in columns.head)\n for (var i = 0; i < columns.length; i++) {\n columns[i].filter = $('#'+columns[i].cl).val();\n }\n\n // apply filter\n filtered_dataset = full_dataset.filter(filter_function);\n filtered_unique_columns = unique_columns.map(column_filter);\n\n // update display\n update_select_boxes();\n generate_table();\n}",
"function updateItemsAscensorValoresMaquinas(k_codusuario,k_codinspeccion,k_coditem, n_calificacion,v_calificacion,o_observacion) {\n db.transaction(function (tx) {\n var query = \"UPDATE ascensor_valores_maquinas SET n_calificacion = ?,\"+\n \"v_calificacion = ?,\"+\n \"o_observacion = ? \"+\n \"WHERE k_codusuario = ? \"+\n \"AND k_codinspeccion = ? \"+\n \"AND k_coditem = ?\";\n tx.executeSql(query, [n_calificacion,v_calificacion,o_observacion,k_codusuario,k_codinspeccion,k_coditem], function(tx, res) {\n console.log(\"rowsAffected updateItemsAscensorValoresMaquinas: \" + res.rowsAffected);\n $('#texto_carga').text(\"Actualizando datos de maquinas...Espere\");\n },\n function(tx, error) {\n console.log('UPDATE error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}",
"rebuildFilters() {\n log.debug('Rebuilding filters');\n\n const { model } = this.props;\n const { advancedFilters, quickFilters } = this.state;\n const { columns } = model;\n\n const newAdvancedFilters = new Map();\n const newQuickFilters = new Map();\n\n advancedFilters.forEach((value, key) => {\n const { options } = value;\n const column = columns[key];\n const filter = TableUtils.makeAdvancedFilter(column, options);\n newAdvancedFilters.set(key, {\n options,\n filter,\n });\n });\n\n quickFilters.forEach((value, key) => {\n const { text } = value;\n const column = columns[key];\n const filter = TableUtils.makeQuickFilter(column, text);\n newQuickFilters.set(key, {\n text,\n filter,\n });\n });\n\n this.startLoading('Rebuilding filters...', true);\n this.setState({\n quickFilters: newQuickFilters,\n advancedFilters: newAdvancedFilters,\n });\n }",
"function updateItemsAscensorValoresFoso(k_codusuario,k_codinspeccion,k_coditem, n_calificacion,v_calificacion,o_observacion) {\n db.transaction(function (tx) {\n var query = \"UPDATE ascensor_valores_foso SET n_calificacion = ?,\"+\n \"v_calificacion = ?,\"+\n \"o_observacion = ? \"+\n \"WHERE k_codusuario = ? \"+\n \"AND k_codinspeccion = ? \"+\n \"AND k_coditem = ?\";\n tx.executeSql(query, [n_calificacion,v_calificacion,o_observacion,k_codusuario,k_codinspeccion,k_coditem], function(tx, res) {\n console.log(\"rowsAffected ascensor_valores_foso: \" + res.rowsAffected);\n $('#texto_carga').text(\"Actualizando datos de foso...Espere\");\n },\n function(tx, error) {\n console.log('UPDATE error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}",
"function updateItemsAscensorValoresCabina(k_codusuario,k_codinspeccion,k_coditem, n_calificacion,v_calificacion,o_observacion) {\n db.transaction(function (tx) {\n var query = \"UPDATE ascensor_valores_cabina SET n_calificacion = ?,\"+\n \"v_calificacion = ?,\"+\n \"o_observacion = ? \"+\n \"WHERE k_codusuario = ? \"+\n \"AND k_codinspeccion = ? \"+\n \"AND k_coditem = ?\"; \n tx.executeSql(query, [n_calificacion,v_calificacion,o_observacion,k_codusuario,k_codinspeccion,k_coditem], function(tx, res) {\n console.log(\"rowsAffected updateItemsAscensorValoresCabina: \" + res.rowsAffected);\n $('#texto_carga').text(\"Actualizando datos de cabina...Espere\");\n },\n function(tx, error) {\n console.log('UPDATE error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}",
"function buildMutationParams(table, mutationType) {\n let query = `const ${mutationType}${table.type}Mutation = gql\\`${enter}${tab}mutation(`;\n\n let firstLoop = true;\n for (const fieldId in table.fields) {\n // if there's an unique id and creating an update mutation, then take in ID\n if (fieldId === '0' && mutationType === 'update') {\n if (!firstLoop) query += ', ';\n firstLoop = false;\n\n query += `$${table.fields[fieldId].name}: ${table.fields[fieldId].type}!`;\n }\n if (fieldId !== '0') {\n if (!firstLoop) query += ', ';\n firstLoop = false;\n\n query += `$${table.fields[fieldId].name}: ${checkForMultipleValues(table.fields[fieldId].multipleValues, 'front')}`;\n query += `${checkFieldType(table.fields[fieldId].type)}${checkForMultipleValues(table.fields[fieldId].multipleValues, 'back')}`;\n query += `${checkForRequired(table.fields[fieldId].required)}`;\n }\n }\n return query += `) {${enter}${tab}`;\n }",
"visitUpdate_set_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"updateColumn({ commit, state, rootState }, details) {\n const {\n columnData, columnIndex, tableIndex, tagIndex,\n } = details;\n const tableId = state.tagList[tagIndex].tables[tableIndex]._id;\n return axios.patch(\n `${constant.api.enframe}apps/${rootState.application.id}/tables/${tableId}/columns/${columnData._id}`,\n columnData,\n ).then(() => {\n commit('updateColumn', {\n columnData,\n columnIndex,\n });\n }).catch(({ response }) => {\n this.dispatch('snackbar/show', {\n type: constant.snackbarTypes.error,\n title: message.inputOutput.errorUpdatingColumn,\n message: response.data.message,\n });\n });\n }",
"function RefreshDataRows(tblName, update_rows, data_rows, is_update) {\n console.log(\" --- RefreshDataRows ---\");\n // PR2021-01-13 debug: when update_rows = [] then !!update_rows = true. Must add !!update_rows.length\n\n console.log(\"tblName\" , tblName);\n console.log(\"update_rows\" , update_rows);\n console.log(\"data_rows\" , data_rows);\n\n if (update_rows && update_rows.length ) {\n const field_setting = field_settings[tblName];\n console.log(\"field_setting\" , field_setting);\n for (let i = 0, update_dict; update_dict = update_rows[i]; i++) {\n RefreshDatarowItem(tblName, field_setting, update_dict, data_rows);\n }\n } else if (!is_update) {\n // empty the data_rows when update_rows is empty PR2021-01-13 debug forgot to empty data_rows\n // PR2021-03-13 debug. Don't empty de data_rows when is update. Returns [] when no changes made\n data_rows = [];\n }\n } // RefreshDataRows",
"function updateItemsAuditoriaInspeccionesAscensores(k_codusuario,k_codinspeccion,o_consecutivoinsp,o_estado_envio,o_revision,v_item_nocumple,k_codcliente,k_codinforme,k_codusuario_modifica,o_actualizar_inspeccion) {\n db.transaction(function (tx) {\n var query = \"UPDATE auditoria_inspecciones_ascensores SET o_consecutivoinsp = ?,\"+\n \"o_estado_envio = ?,\"+\n \"o_revision = ?,\"+\n \"v_item_nocumple = ?,\"+\n \"k_codcliente = ?,\"+\n \"k_codinforme = ?,\"+\n \"o_actualizar_inspeccion = ?,\"+\n \"k_codusuario_modifica = ? \"+\n \"WHERE k_codusuario = ? \"+\n \"AND k_codinspeccion = ?\";\n tx.executeSql(query, [o_consecutivoinsp,o_estado_envio,o_revision,v_item_nocumple,k_codcliente,k_codinforme,o_actualizar_inspeccion,k_codusuario_modifica,k_codusuario,k_codinspeccion], function(tx, res) {\n console.log(\"rowsAffected updateItemsAuditoriaInspeccionesAscensores: \" + res.rowsAffected);\n $('#texto_carga').text(\"Actualizando datos de auditoria...Espere\");\n },\n function(tx, error) {\n console.log('UPDATE error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SameHeight : Iguala altura de elementos v:2.1.1 | function sameHeight(){
elements = $('.js-same-height');
if (elements !== null){
Array.prototype.forEach.call(elements, function(el, i){
//Reset de altura
var maxHeight = 0;
//Cual es la altura más alta?
elements = el.querySelectorAll('.js-same');
Array.prototype.forEach.call(elements, function(el, i){
el.removeAttribute('style');
maxHeightNew = el.offsetHeight;
if (maxHeight < maxHeightNew){
maxHeight = maxHeightNew;
}
});
Array.prototype.forEach.call(elements, function(el, i){
//Ponemos la altura segun los cortes
if (el.classList.contains('no-xs') && windowWidth < xsBreak ){
el.style.minHeight = 0+'px';
}else if (el.classList.contains('no-sm') && windowWidth < smBreak ){
el.style.minHeight = 0+'px';
}else if (el.classList.contains('no-md') && windowWidth < mdBreak ){
el.style.minHeight = 0+'px';
}else{
el.style.minHeight = maxHeight+'px';
}
});
});
}
} | [
"function equalHeight() {\n\t\t$('.pitch__content h4').matchHeight();\n\t\t$('.why__content h4').matchHeight();\n\t}",
"function matchHeight()\n {\n obj.width(Math.round( obj.outerWidth( ) * \n obj.parent().height()/obj.outerHeight( ) - \n (obj.outerWidth( ) - obj.width())));\n obj.height(Math.round( obj.parent().height() - \n (obj.outerHeight( ) - obj.height()) ));\n }",
"_updateHeight() {\n this._updateSize();\n }",
"function setEqualHeight(columns) {\n\tvar tallestItem = 0;\n\tcolumns.each(function(index, item) {\n\t\tvar itemHeight = $(this).height();\n\t\talert(itemHeight);\n\t\tif(itemHeight > tallestItem){\n\t\t\ttallestItem = itemHeight;\n\t\t}\n\t});\n\n\tcolumns.height(tallestItem);\n}",
"function setHeight(elem1, elem2) {\n\tvar height = elem2.height()\n\telem1.css('height', height); \n}",
"get height() {\n if ( !this.el ) return;\n\n return ~~this.parent.style.height.replace( 'px', '' );\n }",
"function getHeight() {\n return 2;\n }",
"function height1(){\n var h = $( window ).outerHeight(true); // Taille de la fenetre\n $('.titre').css('height', (h*0.18)+'px');\n $('.zone1').css('height', (h*0.41)+'px');\n $('.zone2').css('height', (h*0.41)+'px');\n }",
"function height2(){\n var h = $( window ).outerHeight(true); // Taille de la fenetre\n $('.titre').css('height', 'inherit');\n $('.zone1').css('height', (h/2)+'px');\n $('.zone2').css('height', (h/2)+'px');\n }",
"set requestedHeight(value) {}",
"setHeight() {\n this.$().outerHeight(this.$(window).height() - this.get('fixedHeight'));\n }",
"_hardcodeDimensions() {\n const currentHeight = this._current && this._current.getBoundingClientRect().height || 0;\n let tallestHeight = 0;\n\n // Hardcode the height of each collapse to allow CSS transition\n this._elements.forEach(el => {\n el.classList.remove('is-ready');\n el.style.height = 'auto';\n\n const itemHeight = el.closest('.accordion-list__item').getBoundingClientRect().height;\n const collapseHeight = el.getBoundingClientRect().height;\n\n el.style.height = `${collapseHeight}px`;\n el.classList.add('is-ready');\n tallestHeight = Math.max(tallestHeight, itemHeight);\n });\n\n // Set a min-height on the container to avoid wiggles during transitions\n this._accordion.style.minHeight = 'auto';\n const minHeight = this._accordion.getBoundingClientRect().height - currentHeight + tallestHeight + 18;\n this._accordion.style.minHeight = `${minHeight}px`;\n }",
"function containerHeight() {\n var cnt = scope.data && scope.data.length || 0;\n return cnt * theight;\n }",
"function getHeight(elem)\n{\n if (elem == null)\n return 0;\n else\n return elem.offsetHeight ? elem.offsetHeight : 0;\n}",
"function getElementHeight (element) {\n var clone = element.cloneNode(true)\n clone.style.cssText = 'visibility: hidden; display: block; margin: -999px 0'\n\n var height = (element.parentNode.appendChild(clone)).clientHeight\n element.parentNode.removeChild(clone)\n\n return height\n }",
"function make_two_column_same_size(){\n\n\ttry{\n\t\tvar side_bar_h = $(\".side_bar\").css(\"height\",\"auto\").height();\n\t\tvar page_content_h = $(\".page-content\").css(\"height\",\"auto\").height();\n\n\t\tif($(\".side_bar\").data(\"originalh\") == undefined){\n\t\t\t$(\".side_bar\").data(\"originalh\",side_bar_h);\n\t\t\t$(\".page-content\").data(\"originalh\",page_content_h);\t\t\n\t\t}else{\n\t\t\tvar side_bar_h_s = $(\".side_bar\").data(\"originalh\");\n\t\t\tvar page_content_h_s = $(\".page-content\").data(\"originalh\");\n\t\t\tif(page_content_h_s>=page_content_h && arguments[0]==\"1\" ) { side_bar_h = side_bar_h_s;page_content_h=page_content_h_s; }\n\t\t\t//alert(side_bar_h_s+\"--\"+side_bar_h);\n\t\t\t//if(side_bar_h_s>side_bar_h) { side_bar_h=side_bar_h_s;alert(\"he\"); }\n\t\t}\n\t\t//alert(page_content_h+\"--\"+side_bar_h);\n\t\tif(parseInt(side_bar_h)>parseInt(page_content_h)){\n\t\t\t$(\".page-content\").css(\"height\",(parseInt(side_bar_h)+extra_pixel())+\"px\");\n\t\t}else if(parseInt(side_bar_h)<parseInt(page_content_h)){\n\t\t\t$(\".side_bar\").css(\"height\",(parseInt(page_content_h)+extra_pixel())+\"px\");\n\t\t}\t\n\t}catch(ex){}finally{}\t\n}",
"function saveListSize() {\n var $this = $(this);\n $this.css('min-height', $this.height());\n }",
"function updateDimensions() {\n theight = templateHeight();\n cheight = containerHeight();\n vpheight = viewPortHeight();\n }",
"function recalcHeight() {\n // each child element will normally take up 2/3 units\n var y = -1;\n for (var obj of children) {\n // each child lives in its own coordinate system that was scaled by\n // one-third\n y += obj.getHeight() * ONE_THIRD;\n }\n\n if (y > 1.0) {\n maxy = y;\n }\n else {\n // the height may have decreased below 1.0\n maxy = 1.0;\n }\n\n if (adjustHeight != null) {\n adjustHeight(); // propogate the change back up to our parent\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles rocket bounce sound from shield. | _bounceSound() {
if (this._targetPlanet.name === "blueBig") {
Assets.sounds.bounceL.play();
} else if (this._targetPlanet.name === "redBig") {
Assets.sounds.bounceR.play();
}
} | [
"handleSound() {\n // On the X axis, if the mouse is closer to the center of the shape than it was in the previous frame...\n if (this.distanceFromCenterX > mouseX - this.x) {\n // Change state to say that the breath in sound is not playing and stop the sound\n this.breathInSoundPlaying = false;\n this.breathInSound.stop();\n // If the breath out sound is not playing, play it and change its state so it wont play every frame\n if (!this.breathOutSoundPlaying) {\n this.breathOutSound.play();\n this.breathOutSoundPlaying = true;\n }\n }\n // On the X axis, if the mouse is farther from the center of the shape than it was in the previous frame...\n else if (this.distanceFromCenterX < mouseX - this.x) {\n // Change state to say that the breath out sound is not playing and stop the sound\n this.breathOutSoundPlaying = false;\n this.breathOutSound.stop();\n // If the breath in sound is not playing, play it and change its state so it wont play every frame\n if (!this.breathInSoundPlaying) {\n this.breathInSound.play();\n this.breathInSoundPlaying = true;\n }\n }\n }",
"function watchRacketBounce()\n{\n var overhead = mouseY-pmouseY;\n if((ballX+ballSize/2 > mouseX - (racketWidth/2)) && (ballX - (ballSize/2) < mouseX +(racketWidth/2)))\n {\n if(dist(ballX,ballY,ballX, mouseY)<=(ballSize/2)+abs(overhead))\n {\n makeBounceBottom(mouseY);\n \n ballSpeedHorizon = (ballX -mouseX)/10;\n \n if(overhead<0)\n {\n ballY+=(overhead/2);\n ballSpeedVert+=(overhead/2);\n }\n }\n }\n}",
"function checkBallWallCollision() {\n // Check for collisions with top or bottom...\n if (ball.y < 0 ) {\n // It hit so reverse velocity\n ball.vy = ball.speed;\n // Play our bouncing sound effect by rewinding and then playing\n // beepSFX.currentTime = 0;\n // beepSFX.play();\n }\n else if (ball.y > height){\n // It hit so reverse velocity\n ball.vy = -ball.speed;\n // Play our bouncing sound effect by rewinding and then playing\n // beepSFX.currentTime = 0;\n // beepSFX.play();\n\n }\n}",
"function bombShot() {\n playSound(\"audioBombShot\");\n }",
"function rocketLaunch() {\n playSound(\"audioRocketLaunch\");\n }",
"function rocketExplode() {\n playSound(\"audioRocketExplosion\");\n }",
"function OnReceiveDamage(){}",
"function wallDmg(){\n playerHP -= 1;\n if(playerHP < 0){\n if(!explodeSound.isPlaying()){\n explodeSound.play();\n }\n } else {\n if(!crashSound.isPlaying()){\n crashSound.play();\n }\n }\n}",
"function playOnPlayersChange() {\n beepSound.play();\n}",
"update(canvas, synth, notes) {\n if(this.x + this.radius > canvas.width || this.x - this.radius < 0) {\n this.dx = -this.dx;\n // LOGIC TO PLAY SOUND GOES HERE\n let note = getNote(notes);\n synth.triggerAttackRelease(note, \"32n\");\n }\n this.x += this.dx;\n if(this.y + this.radius > canvas.height || this.y - this.radius < 0) {\n this.dy = -this.dy;\n // LOGIC TO PLAY SOUND GOES HERE\n let note = getNote(notes);\n synth.triggerAttackRelease(note, \"32n\");\n }\n this.y += this.dy;\n }",
"function groundShot() {\n playSound(\"audioCannonShot\");\n }",
"firePhazer() {\n if (this.chargeEmpty === false) {\n let newPhazer = new Phazers();\n player.updateCharge();\n phazers.push(newPhazer);\n laserBlast.play();\n }\n //if the player tries to fire the phaser while charge is empty, play the empty battery sound\n else {\n lowCharge.playMode('untilDone');\n lowCharge.play();\n }\n }",
"handleHealing(firstAid) {\n //Calculate distance from this player to the firstaid kit\n let d2 = dist(this.x, this.y, firstAid.x, firstAid.y);\n //Check if the distance is less than their two radius(an overlap)\n if (d2 < this.radius + firstAid.radius) {\n this.health += this.healthGainPerEat * 5;\n this.health = constrain(this.health, 0, this.maxHealth);\n //Decrease firstaid kit health by the same amount\n firstAid.health -= this.healthGainPerEat * 5;\n }\n //Check if the firstaid kit died and reset it if so\n if (firstAid.health < 2) {\n beepSound.play();\n firstAid.reset();\n }\n }",
"function bombExplode() {\n playSound(\"audioBombExplosion\");\n }",
"function OnTriggerEnter (collided : Collider) {\n if (collided.gameObject.name == 'player' && on == true) {\n sound.Play();\n collided.gameObject.GetComponentInChildren(GunBehavior).ammo += amount;\n turnOff();\n }\n}",
"bounce() {\n\n this.balltween\n .to('#ball', this.time/2, {y: '+=250px', scaleY: 0.7, transformOrigin: \"bottom\", ease: Power2.easeIn,\n onComplete: () => {\n this.checkColor();\n }\n }).to('#ball', this.time/2, {y: '-=250px', scaleY: 1.1, transformOrigin: \"bottom\", ease: Power2.easeOut, \n onStart: () => {\n while(this.prevColor==this.color) {\n this.color = (new Color).getRandomColor();\n }\n this.prevColor = this.color;\n //TweenMax.to('#ball', 0.5, {backgroundColor: this.color});\n $('#ball').removeClass('red')\n .removeClass('yellow')\n .removeClass('purple')\n .addClass((new Color).colorcodeToName(this.color));\n }\n }) \n }",
"function updateSillyMovement(){\n // increment noise\n sillyInc+=sillyFact;\n // apply to velocity\n ball.vy=map(noise(sillyInc), 0, 1, -ball.speed, +ball.speed);\n// prevent the ball from heading straight back into the wall\n// if ball is still close to the wall\n if(ball.y<10*ball.speed&&ball.vy<0){\n ball.vy=abs(ball.vy);\n } else if(ball.y>height-10*ball.speed&&ball.vy>0){\n ball.vy=-abs(ball.vy);\n }\n}",
"function mixedShot() {\n playSound(\"audioMixedShot\");\n }",
"makeSound() {\n // if we wanna call the parent method explicitly we could do it like that\n // super.makeSound();\n // more common is to define our own logic\n return 'and another sound'\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiates a new BaseTexture. Base class of all the textures in babylon. It groups all the common properties the materials, post process, lights... might need in order to make a correct use of the texture. | function BaseTexture(scene){this._hasAlpha=false;/**
* Defines if the alpha value should be determined via the rgb values.
* If true the luminance of the pixel might be used to find the corresponding alpha value.
*/this.getAlphaFromRGB=false;/**
* Intensity or strength of the texture.
* It is commonly used by materials to fine tune the intensity of the texture
*/this.level=1;/**
* Define the UV chanel to use starting from 0 and defaulting to 0.
* This is part of the texture as textures usually maps to one uv set.
*/this.coordinatesIndex=0;this._coordinatesMode=BABYLON.Texture.EXPLICIT_MODE;/**
* | Value | Type | Description |
* | ----- | ------------------ | ----------- |
* | 0 | CLAMP_ADDRESSMODE | |
* | 1 | WRAP_ADDRESSMODE | |
* | 2 | MIRROR_ADDRESSMODE | |
*/this.wrapU=BABYLON.Texture.WRAP_ADDRESSMODE;/**
* | Value | Type | Description |
* | ----- | ------------------ | ----------- |
* | 0 | CLAMP_ADDRESSMODE | |
* | 1 | WRAP_ADDRESSMODE | |
* | 2 | MIRROR_ADDRESSMODE | |
*/this.wrapV=BABYLON.Texture.WRAP_ADDRESSMODE;/**
* | Value | Type | Description |
* | ----- | ------------------ | ----------- |
* | 0 | CLAMP_ADDRESSMODE | |
* | 1 | WRAP_ADDRESSMODE | |
* | 2 | MIRROR_ADDRESSMODE | |
*/this.wrapR=BABYLON.Texture.WRAP_ADDRESSMODE;/**
* With compliant hardware and browser (supporting anisotropic filtering)
* this defines the level of anisotropic filtering in the texture.
* The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
*/this.anisotropicFilteringLevel=BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;/**
* Define if the texture is a cube texture or if false a 2d texture.
*/this.isCube=false;/**
* Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
*/this.is3D=false;/**
* Define if the texture contains data in gamma space (most of the png/jpg aside bump).
* HDR texture are usually stored in linear space.
* This only impacts the PBR and Background materials
*/this.gammaSpace=true;/**
* Is Z inverted in the texture (useful in a cube texture).
*/this.invertZ=false;/**
* @hidden
*/this.lodLevelInAlpha=false;/**
* Define if the texture is a render target.
*/this.isRenderTarget=false;/**
* Define the list of animation attached to the texture.
*/this.animations=new Array();/**
* An event triggered when the texture is disposed.
*/this.onDisposeObservable=new BABYLON.Observable();/**
* Define the current state of the loading sequence when in delayed load mode.
*/this.delayLoadState=BABYLON.Engine.DELAYLOADSTATE_NONE;this._cachedSize=BABYLON.Size.Zero();this._scene=scene||BABYLON.Engine.LastCreatedScene;if(this._scene){this._scene.textures.push(this);this._scene.onNewTextureAddedObservable.notifyObservers(this);}this._uid=null;} | [
"function ProceduralTexture(name,size,fragment,scene,fallbackTexture,generateMipMaps,isCube){if(fallbackTexture===void 0){fallbackTexture=null;}if(generateMipMaps===void 0){generateMipMaps=true;}if(isCube===void 0){isCube=false;}var _this=_super.call(this,null,scene,!generateMipMaps)||this;_this.isCube=isCube;/**\n * Define if the texture is enabled or not (disabled texture will not render)\n */_this.isEnabled=true;/**\n * Define if the texture must be cleared before rendering (default is true)\n */_this.autoClear=true;/**\n * Event raised when the texture is generated\n */_this.onGeneratedObservable=new BABYLON.Observable();/** @hidden */_this._textures={};_this._currentRefreshId=-1;_this._refreshRate=1;_this._vertexBuffers={};_this._uniforms=new Array();_this._samplers=new Array();_this._floats={};_this._ints={};_this._floatsArrays={};_this._colors3={};_this._colors4={};_this._vectors2={};_this._vectors3={};_this._matrices={};_this._fallbackTextureUsed=false;_this._cachedDefines=\"\";_this._contentUpdateId=-1;scene=_this.getScene();var component=scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);if(!component){component=new BABYLON.ProceduralTextureSceneComponent(scene);scene._addComponent(component);}scene.proceduralTextures.push(_this);_this._engine=scene.getEngine();_this.name=name;_this.isRenderTarget=true;_this._size=size;_this._generateMipMaps=generateMipMaps;_this.setFragment(fragment);_this._fallbackTexture=fallbackTexture;if(isCube){_this._texture=_this._engine.createRenderTargetCubeTexture(size,{generateMipMaps:generateMipMaps,generateDepthBuffer:false,generateStencilBuffer:false});_this.setFloat(\"face\",0);}else{_this._texture=_this._engine.createRenderTargetTexture(size,{generateMipMaps:generateMipMaps,generateDepthBuffer:false,generateStencilBuffer:false});}// VBO\nvar vertices=[];vertices.push(1,1);vertices.push(-1,1);vertices.push(-1,-1);vertices.push(1,-1);_this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]=new BABYLON.VertexBuffer(_this._engine,vertices,BABYLON.VertexBuffer.PositionKind,false,false,2);_this._createIndexBuffer();return _this;}",
"function initTextures() {\n floorTexture = gl.createTexture();\n floorTexture.image = new Image();\n floorTexture.image.onload = function () {\n handleTextureLoaded(floorTexture)\n }\n floorTexture.image.src = \"./assets/grass1.jpg\";\n\n cubeTexture = gl.createTexture();\n cubeTexture.image = new Image();\n cubeTexture.image.onload = function() {\n handleTextureLoaded(cubeTexture);\n }; // async loading\n cubeTexture.image.src = \"./assets/gifft.jpg\";\n}",
"function CustomProceduralTexture(name,texturePath,size,scene,fallbackTexture,generateMipMaps){var _this=_super.call(this,name,size,null,scene,fallbackTexture,generateMipMaps)||this;_this._animate=true;_this._time=0;_this._texturePath=texturePath;//Try to load json\n_this._loadJson(texturePath);_this.refreshRate=1;return _this;}",
"function mTexture() {\n texture(...[...arguments]);\n}",
"function RawTexture(data,width,height,/**\n * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)\n */format,scene,generateMipMaps,invertY,samplingMode,type){if(generateMipMaps===void 0){generateMipMaps=true;}if(invertY===void 0){invertY=false;}if(samplingMode===void 0){samplingMode=BABYLON.Texture.TRILINEAR_SAMPLINGMODE;}if(type===void 0){type=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}var _this=_super.call(this,null,scene,!generateMipMaps,invertY)||this;_this.format=format;_this._engine=scene.getEngine();_this._texture=scene.getEngine().createRawTexture(data,width,height,format,generateMipMaps,invertY,samplingMode,null,type);_this.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE;_this.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE;return _this;}",
"setTextureBaseColor(color) {\n //TODO\n }",
"function MirrorTexture(name,size,scene,generateMipMaps,type,samplingMode,generateDepthBuffer){if(type===void 0){type=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}if(samplingMode===void 0){samplingMode=BABYLON.Texture.BILINEAR_SAMPLINGMODE;}if(generateDepthBuffer===void 0){generateDepthBuffer=true;}var _this=_super.call(this,name,size,scene,generateMipMaps,true,type,false,samplingMode,generateDepthBuffer)||this;_this.scene=scene;/**\n * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.\n * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.\n * @see https://doc.babylonjs.com/how_to/reflect#mirrors\n */_this.mirrorPlane=new BABYLON.Plane(0,1,0,1);_this._transformMatrix=BABYLON.Matrix.Zero();_this._mirrorMatrix=BABYLON.Matrix.Zero();_this._adaptiveBlurKernel=0;_this._blurKernelX=0;_this._blurKernelY=0;_this._blurRatio=1.0;_this.ignoreCameraViewport=true;_this._updateGammaSpace();_this._imageProcessingConfigChangeObserver=scene.imageProcessingConfiguration.onUpdateParameters.add(function(){_this._updateGammaSpace;});_this.onBeforeRenderObservable.add(function(){BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane,_this._mirrorMatrix);_this._savedViewMatrix=scene.getViewMatrix();_this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix,_this._transformMatrix);scene.setTransformMatrix(_this._transformMatrix,scene.getProjectionMatrix());scene.clipPlane=_this.mirrorPlane;scene.getEngine().cullBackFaces=false;scene._mirroredCameraPosition=BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition,_this._mirrorMatrix);});_this.onAfterRenderObservable.add(function(){scene.setTransformMatrix(_this._savedViewMatrix,scene.getProjectionMatrix());scene.getEngine().cullBackFaces=true;scene._mirroredCameraPosition=null;delete scene.clipPlane;});return _this;}",
"function RawTexture3D(data,width,height,depth,/** Gets or sets the texture format to use */format,scene,generateMipMaps,invertY,samplingMode,textureType){if(generateMipMaps===void 0){generateMipMaps=true;}if(invertY===void 0){invertY=false;}if(samplingMode===void 0){samplingMode=BABYLON.Texture.TRILINEAR_SAMPLINGMODE;}if(textureType===void 0){textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}var _this=_super.call(this,null,scene,!generateMipMaps,invertY)||this;_this.format=format;_this._engine=scene.getEngine();_this._texture=scene.getEngine().createRawTexture3D(data,width,height,depth,format,generateMipMaps,invertY,samplingMode,undefined,textureType);_this.is3D=true;return _this;}",
"function textureHelper(obj, texUrl) {\n setTexture(obj.name, texUrl);\n}",
"loadMaterials() {\n let materials = []\n\n // Load Textures\n let loader = new THREE.TextureLoader()\n loader.setPath(\"../../resources/textures/blocks/\")\n\n let dirtText = loader.load('dirt.png')\n dirtText.magFilter = THREE.NearestFilter\n\n let stoneText = loader.load('stone.png')\n stoneText.magFilter = THREE.NearestFilter\n\n let bedrockText = loader.load('bedrock.png')\n bedrockText.magFilter = THREE.NearestFilter\n\n let grassTopText = loader.load('grass_block_top.png')\n grassTopText.magFilter = THREE.NearestFilter\n\n let grassSideText = loader.load('grass_block_side.png')\n grassSideText.magFilter = THREE.NearestFilter\n\n let grassBotText = loader.load('dirt.png')\n grassBotText.magFilter = THREE.NearestFilter\n\n\n // Base material for all solid blocks\n let solidMat = new THREE.MeshBasicMaterial({\n side: THREE.DoubleSide\n })\n\n // Create specific materials from base\n let dirt = solidMat.clone()\n dirt.map = dirtText\n\n let stone = solidMat.clone()\n stone.map = stoneText\n\n let bedrock = solidMat.clone()\n bedrock.map = bedrockText\n\n let grassTop = solidMat.clone()\n grassTop.map = grassTopText\n\n let grassSide = solidMat.clone()\n grassSide.map = grassSideText\n\n let grassBot = solidMat.clone()\n grassBot.map = grassBotText\n\n\n // Add material to global array\n materials.push(dirt)\n materials.push(stone)\n materials.push(bedrock)\n materials.push(grassTop)\n materials.push(grassSide)\n materials.push(grassBot)\n\n solidMat.dispose()\n\n return materials\n }",
"updateTexture() {\n let width = 1;\n let height = 1;\n let depth = 1;\n if(this.props.activations){\n this.activations = this.props.activations\n const [b, w, h, c] = this.props.activationShape;\n\n width = w;//sqrtW;\n height = h;//sqrtW;\n depth = c;\n } else{\n this.activations = this.defatultActivations;\n }\n\n //this.activationTexture = new RawTexture(this.activations, width, height,\n // Engine.TEXTUREFORMAT_RED, this.scene, false, false,\n // Texture.BILINEAR_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);\n\n let sz;\n let sizeMatches = false;\n if(this.activationTexture) {\n sz = this.activationTexture.getSize();\n sizeMatches = (sz.width === width && sz.height === height\n && this.lastDepth === depth);\n }\n if(!this.activationTexture || !sizeMatches) {\n if(this.activationTexture){\n this.activationTexture.dispose();\n }\n this.activationTexture = new RawTexture3D(this.activations, width, height,\n depth, Engine.TEXTUREFORMAT_RED, this.scene, false, false,\n Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);\n } else {\n this.activationTexture.update(this.activations);\n }\n\n this.shaderMaterial.setTexture('textureSampler', this.activationTexture);\n this.lastDepth = depth;\n }",
"function HDRCubeTexture(url,scene,size,noMipmap,generateHarmonics,gammaSpace,reserved,onLoad,onError){if(noMipmap===void 0){noMipmap=false;}if(generateHarmonics===void 0){generateHarmonics=true;}if(gammaSpace===void 0){gammaSpace=false;}if(reserved===void 0){reserved=false;}if(onLoad===void 0){onLoad=null;}if(onError===void 0){onError=null;}var _this=_super.call(this,scene)||this;_this._generateHarmonics=true;_this._onLoad=null;_this._onError=null;/**\n * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.\n */_this.coordinatesMode=BABYLON.Texture.CUBIC_MODE;_this._isBlocking=true;_this._rotationY=0;/**\n * Gets or sets the center of the bounding box associated with the cube texture\n * It must define where the camera used to render the texture was set\n */_this.boundingBoxPosition=BABYLON.Vector3.Zero();if(!url){return _this;}_this.name=url;_this.url=url;_this.hasAlpha=false;_this.isCube=true;_this._textureMatrix=BABYLON.Matrix.Identity();_this._onLoad=onLoad;_this._onError=onError;_this.gammaSpace=gammaSpace;_this._noMipmap=noMipmap;_this._size=size;_this._texture=_this._getFromCache(url,_this._noMipmap);if(!_this._texture){if(!scene.useDelayedTextureLoading){_this.loadTexture();}else{_this.delayLoadState=BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;}}return _this;}",
"initTexture(object, url){\n\t\tobject.texture = this.ctx.createTexture();\n\t\tobject.texture.image = new Image();\n\t\tobject.texture.image.crossOrigin = \"anonymous\";\n\t\tobject.texture.image.src = url;\n\t\tvar action = () => {\n\t\t\tthis.handleLoadedTexture(object.texture);\n\t\t\tthis.render();\n\t\t};\n\t\tif (object.texture.image.complete || object.texture.image.width+object.texture.image.height > 0)\n\t\t\taction();\n\t\telse\n\t\t\tobject.texture.image.addEventListener('load', (event) => {action();});\n\t}",
"function BackgroundMaterial(name,scene){var _this=_super.call(this,name,scene)||this;/**\n * Key light Color (multiply against the environement texture)\n */_this.primaryColor=BABYLON.Color3.White();_this._primaryColorShadowLevel=0;_this._primaryColorHighlightLevel=0;/**\n * Reflection Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */_this.reflectionTexture=null;/**\n * Reflection Texture level of blur.\n *\n * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the\n * texture twice.\n */_this.reflectionBlur=0;/**\n * Diffuse Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */_this.diffuseTexture=null;_this._shadowLights=null;/**\n * Specify the list of lights casting shadow on the material.\n * All scene shadow lights will be included if null.\n */_this.shadowLights=null;/**\n * Helps adjusting the shadow to a softer level if required.\n * 0 means black shadows and 1 means no shadows.\n */_this.shadowLevel=0;/**\n * In case of opacity Fresnel or reflection falloff, this is use as a scene center.\n * It is usually zero but might be interesting to modify according to your setup.\n */_this.sceneCenter=BABYLON.Vector3.Zero();/**\n * This helps specifying that the material is falling off to the sky box at grazing angle.\n * This helps ensuring a nice transition when the camera goes under the ground.\n */_this.opacityFresnel=true;/**\n * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.\n * This helps adding a mirror texture on the ground.\n */_this.reflectionFresnel=false;/**\n * This helps specifying the falloff radius off the reflection texture from the sceneCenter.\n * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.\n */_this.reflectionFalloffDistance=0.0;/**\n * This specifies the weight of the reflection against the background in case of reflection Fresnel.\n */_this.reflectionAmount=1.0;/**\n * This specifies the weight of the reflection at grazing angle.\n */_this.reflectionReflectance0=0.05;/**\n * This specifies the weight of the reflection at a perpendicular point of view.\n */_this.reflectionReflectance90=0.5;/**\n * Helps to directly use the maps channels instead of their level.\n */_this.useRGBColor=true;/**\n * This helps reducing the banding effect that could occur on the background.\n */_this.enableNoise=false;_this._fovMultiplier=1.0;/**\n * Enable the FOV adjustment feature controlled by fovMultiplier.\n */_this.useEquirectangularFOV=false;_this._maxSimultaneousLights=4;/**\n * Number of Simultaneous lights allowed on the material.\n */_this.maxSimultaneousLights=4;/**\n * Keep track of the image processing observer to allow dispose and replace.\n */_this._imageProcessingObserver=null;/**\n * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.\n * Setting this flag to true (not done automatically!) will convert it back to RGB.\n */_this.switchToBGR=false;// Temp values kept as cache in the material.\n_this._renderTargets=new BABYLON.SmartArray(16);_this._reflectionControls=BABYLON.Vector4.Zero();_this._white=BABYLON.Color3.White();_this._primaryShadowColor=BABYLON.Color3.Black();_this._primaryHighlightColor=BABYLON.Color3.Black();// Setup the default processing configuration to the scene.\n_this._attachImageProcessingConfiguration(null);_this.getRenderTargetTextures=function(){_this._renderTargets.reset();if(_this._diffuseTexture&&_this._diffuseTexture.isRenderTarget){_this._renderTargets.push(_this._diffuseTexture);}if(_this._reflectionTexture&&_this._reflectionTexture.isRenderTarget){_this._renderTargets.push(_this._reflectionTexture);}return _this._renderTargets;};return _this;}",
"function RenderFrameContext( o )\r\n{\r\n\tthis.width = 0; //0 means the same size as the viewport, negative numbers mean reducing the texture in half N times\r\n\tthis.height = 0; //0 means the same size as the viewport\r\n\tthis.precision = RenderFrameContext.DEFAULT_PRECISION; //LOW_PRECISION uses a byte, MEDIUM uses a half_float, HIGH uses a float, or directly the texture type (p.e gl.UNSIGNED_SHORT_4_4_4_4 )\r\n\tthis.filter_texture = true; //magFilter: in case the texture is shown, do you want to see it pixelated?\r\n\tthis.format = GL.RGB; //how many color channels, or directly the texture internalformat \r\n\tthis.use_depth_texture = true; //store the depth in a texture\r\n\tthis.use_stencil_buffer = false; //add an stencil buffer (cannot be read as a texture in webgl)\r\n\tthis.num_extra_textures = 0; //number of extra textures in case we want to render to several buffers\r\n\tthis.name = null; //if a name is provided all the textures will be stored in the ONE.ResourcesManager\r\n\r\n\tthis.generate_mipmaps = false; //try to generate mipmaps if possible (only when the texture is power of two)\r\n\tthis.adjust_aspect = false; //when the size doesnt match the canvas size it could look distorted, settings this to true will fix the problem\r\n\tthis.clone_after_unbind = false; //clones the textures after unbinding it. Used when the texture will be in the 3D scene\r\n\r\n\tthis._fbo = null;\r\n\tthis._color_texture = null;\r\n\tthis._depth_texture = null;\r\n\tthis._textures = []; //all color textures (the first will be _color_texture)\r\n\tthis._cloned_textures = null; //in case we set the clone_after_unbind to true\r\n\tthis._cloned_depth_texture = null;\r\n\r\n\tthis._version = 1; //to detect changes\r\n\tthis._minFilter = gl.NEAREST;\r\n\r\n\tif(o)\r\n\t\tthis.configure(o);\r\n}",
"function MultiRenderTarget(name,size,count,scene,options){var _this=this;var generateMipMaps=options&&options.generateMipMaps?options.generateMipMaps:false;var generateDepthTexture=options&&options.generateDepthTexture?options.generateDepthTexture:false;var doNotChangeAspectRatio=!options||options.doNotChangeAspectRatio===undefined?true:options.doNotChangeAspectRatio;_this=_super.call(this,name,size,scene,generateMipMaps,doNotChangeAspectRatio)||this;_this._engine=scene.getEngine();if(!_this.isSupported){_this.dispose();return;}var types=[];var samplingModes=[];for(var i=0;i<count;i++){if(options&&options.types&&options.types[i]!==undefined){types.push(options.types[i]);}else{types.push(options&&options.defaultType?options.defaultType:BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);}if(options&&options.samplingModes&&options.samplingModes[i]!==undefined){samplingModes.push(options.samplingModes[i]);}else{samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);}}var generateDepthBuffer=!options||options.generateDepthBuffer===undefined?true:options.generateDepthBuffer;var generateStencilBuffer=!options||options.generateStencilBuffer===undefined?false:options.generateStencilBuffer;_this._size=size;_this._multiRenderTargetOptions={samplingModes:samplingModes,generateMipMaps:generateMipMaps,generateDepthBuffer:generateDepthBuffer,generateStencilBuffer:generateStencilBuffer,generateDepthTexture:generateDepthTexture,types:types,textureCount:count};_this._createInternalTextures();_this._createTextures();return _this;}",
"initializeMeshes () {\r\n this.triangleMesh = new Mesh(this.cyanYellowHypnoMaterial, this.triangleGeometry);\r\n this.quadMesh = new Mesh(this.magentaMaterial, this.quadGeometry);\r\n\r\n // texture code\r\n this.texturedQuadMesh = new Mesh(this.texturedMaterial, this.texturedQuadGeometry);\r\n }",
"function SLTReelSprite() {\n this.initialize.apply(this, arguments);\n}",
"function TextureCube() {\n\n TextureBase.call(this);\n\n this.textureType = WEBGL_TEXTURE_TYPE.TEXTURE_CUBE_MAP;\n\n /**\n * Images data for this texture.\n * @member {HTMLImageElement[]}\n * @default []\n */\n this.images = [];\n\n /**\n * @default false\n */\n this.flipY = false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create each score line and place it in the DOM | displayScores() {
for (let i = 1; i <= this.total; i += 1) {
const data = this.data.get(i);
const div = this.createContent(data.name, data.level, Utils.formatNumber(data.score, ","));
div.className = "highScore";
this.scores.appendChild(div);
}
} | [
"function renderHighScores(){\n\t\n\tvar node = document.getElementById('scores');\n\tnode.innerHTML = '';\n\tnode.innerHTML = '<br/>'\n\tfor(var i = 0; i < highScores.length; i++){\t\n\t\tnode.innerHTML += highScores[i]+'<br/>';\t\n\t}\n}",
"function create_scoreboard( player )\n{\n\tvar section = document.createElement('div');\n\tvar name_section = document.createElement('div');\n\tvar first_section = document.createElement('div');\n\tvar second_section = document.createElement('div');\n\tvar third_section = document.createElement('div');\n\n\t$(section).addClass('scoreboard');\n\t$(name_section).addClass('inner_scoreboard');\n\t$(first_section).addClass('inner_scoreboard');\n\t$(second_section).addClass('inner_scoreboard');\n\t$(third_section).addClass('inner_scoreboard');\n\n\tname_section.textContent = player.name;\n\tfirst_section.textContent = '';\n\tsecond_section.textContent = '';\n\tthird_section.textContent = '';\n\n\tplayer.section = section;\n\tplayer.nameSection = name_section;\n\tplayer.firstSection = first_section;\n\tplayer.secondSection = second_section;\n\tplayer.thirdSection = third_section;\n\n\t$(section).append(name_section);\n\t$(section).append(first_section);\n\t$(section).append(second_section);\n\t$(section).append(third_section);\n\n\t$('.game').append(section);\n\thighlightPlayer(players.players[0]);\n\tdimPlayer(players.players[1]);\n\t\n}",
"function drawScores(gameState) {\n document.querySelectorAll('tr.score').forEach(e => e.remove());\n gameState.scores.forEach(([name, score]) => {\n const tableRow = document.createElement('tr');\n tableRow.innerHTML = `<td>${name}<td>${score}`;\n tableRow.className = 'score';\n tableBody.appendChild(tableRow);\n });\n }",
"function highscoreRender(){\n\tscoreListEl.innerHTML = '';\n\n\tfor (var i = 0; i < userScore.length; i++) {\n\t var userName = userScore[i].name;\n \n\t var li = document.createElement('li');\n\t li.textContent = userName +\":\"+ userScore[i].score;\n\t li.setAttribute('data-index', i);\n\n\t scoreListEl.appendChild(li);\n\t}\n}",
"function buildLine() {\n d3.select(\"#line\").remove();\n var begin = margin.bottom + y(margin.top), final = height;\n var yl = d3.scaleLinear()\n .domain([scoreMax, 0])\n .range([final, 0]);\n\n var score = parseFloat(document.getElementById(\"score\").value) || null;\n \n if(score) {\n var yline = yl(score) + begin;\n\n console.log(yline);\n var svgLine = d3.select(\"#box-line\")\n .append(\"svg\")\n .attr(\"width\", 1260)\n .attr(\"height\", 2)\n .style(\"background\", \"#bc223f\")\n .style(\"opacity\", 1)\n .attr(\"id\", \"line\")\n .attr(\"yl\", yline)\n .attr(\"transform\", \"translate(0,\"+ -yline +\")\");\n }else{\n var allRects = series.selectAll(\"rect\"),\n axisX = d3.selectAll(\".name-courses\")._groups[0];\n axisX.forEach(function(item){\n item.style.opacity = 1\n });\n allRects.style(\"opacity\", 1);\n }\n\n compareCourses();\n\n }",
"function renderHighScores() {\n highScoreEl.style.display = \"none\";\n highScorePage.style.display = \"block\";\n for (var i = 0; i < initials.length; i++) {\n initialsAndHighScore.append(initials[i] + \": \" + highScore[i] + \"\\n\");\n }\n}",
"displayTitles() {\r\n const div = this.createContent(\"name\", \"lvl\", \"score\");\r\n div.className = \"titles\";\r\n this.scores.appendChild(div);\r\n }",
"function displayScores() {\n\tget('js_score').innerHTML = temp.points;\n\tget('js_answered').innerHTML = answered;\n\tget('js_error').innerHTML = temp.errors;\n\tget('js_left').innerHTML = data.length-answered;\n}",
"function ScoreTable() {\n this.player1 = joueur1;\n this.player2 = joueur2;\n\n var tableau = document.createElement(\"table\");\n tableau.setAttribute(\"class\",\"score\");\n tableau.setAttribute(\"id\",\"score\");\n\n var tmp_tr = document.createElement(\"tr\");\n tmp_tr.appendChild(document.createElement(\"th\"));\n tmp_tr.childNodes[0].innerText = \"SCORES\";\n tmp_tr.childNodes[0].setAttribute(\"colspan\",\"2\");\n tableau.appendChild(tmp_tr);\n\n tmp_tr = document.createElement(\"tr\");\n tmp_tr.appendChild(document.createElement(\"th\"));\n tmp_tr.appendChild(document.createElement(\"td\"));\n tmp_tr.childNodes[0].innerText = joueur1.name;\n tmp_tr.childNodes[1].innerText = joueur1.score;\n tableau.appendChild(tmp_tr);\n\n tmp_tr = document.createElement(\"tr\");\n tmp_tr.appendChild(document.createElement(\"th\"));\n tmp_tr.appendChild(document.createElement(\"td\"));\n tmp_tr.childNodes[0].innerText = joueur2.name;\n tmp_tr.childNodes[1].innerText = joueur2.score;\n tableau.appendChild(tmp_tr);\n\n document.getElementById(\"sideinfos\").appendChild(tableau);\n}",
"drawPlayersScore() {\n fill('#BDBDBD');\n textFont('Helvetica', 28);\n text(this.player1.score, 4 * this.lateralPadding, 40);\n text(this.player2.score, canvasWidth - 4 * this.lateralPadding - 10, 40);\n }",
"function displayLeaderboard() { \n hideAll();\n clearTable();\n displayElement(leaderboardPageDiv);\n\n if (leaderboardArr.length > 0) {\n // sorts the leaderboardArr from highest \n // to lowest by score\n leaderboardArr.sort((a, b) => b.score - a.score);\n\n var rank = 1;\n\n // for each element create a new row in leaderboardTable\n for (var i = 0; i < leaderboardArr.length; i++) {\n var curr = leaderboardArr[i];\n // insert row at the bottom of the table\n var row = leaderboardTable.insertRow();\n \n\n // checks if the score is already on the leaderboard so if it \n // is everyone of that score has the same rank\n if (i !== 0 && curr.score !== leaderboardArr[i - 1].score) {\n rank++;\n }\n\n // create cell data for each heading in the table\n createCell(row, rank);\n createCell(row, curr.name);\n createCell(row, curr.score);\n }\n }\n}",
"createElement() {\n console.log(this.line);\n this.$line = $('<div></div>')\n .addClass('Hero-graphic__terminal__line');\n\n if (this.line[0] != '') {\n this.$line.append('<span class=\"pre\">'+this.line[0]+'</span>');\n }\n\n this.$line\n .append('<div id=\"'+this.id+'\" class=\"text\"></div>')\n .append('<div class=\"cursor\" style=\"display: none\"></div>');\n }",
"function initScoreboard() {\n\tvar header = '<h3>Deck Overview</h3>';\n\t$(overview).append(header);\n\tfor (var i = 0; i < myDecks[currentDeck].cards.length; i++) {\n\t\tvar cardOverview = '<li data-index=\"' + i + '\"><span class=\"overview-status\"><i class=\"fa fa-square-o\" aria-hidden=\"true\"></i></span><span class=\"overview-value\">. . .</span></li>';\n\t\t$(overview).append(cardOverview);\n\t}\n}",
"function displayScore(){\n\n // set fill for this entire function\n fill(fgColor-100);\n // divide score into rows (set row length)\n var row=4;\n // check left paddle's score\n for(var i=0; i<leftPaddle.score; i++){\n // for each point, display a ball.\n // determine which row this ball falls into\n var leftScoreRow = floor(i/row);\n // determine x pos depending on score and row size\n var leftScoreX = scoreSize+1.5*i*scoreSize-leftScoreRow*(1.5*row*scoreSize);\n // determine y pos depending on score and row size\n var leftScoreY = scoreSize+leftScoreRow*1.5*scoreSize;\n // display ball\n rect(leftScoreX, leftScoreY,scoreSize,scoreSize);\n }\n // check right paddle's score,\n // and do the same.\n for(var i=0; i<rightPaddle.score; i++){\n var rightScoreRow = floor(i/row);\n var rightScoreX = width-(scoreSize+1.5*i*scoreSize-rightScoreRow*(1.5*row*scoreSize));\n var rightScoreY = scoreSize+rightScoreRow*1.5*scoreSize;\n rect(rightScoreX, rightScoreY,scoreSize,scoreSize);\n }\n\n}",
"function kata21(smplArr){\n let newElement = document.createElement(\"section\");\n newElement.setAttribute(\"id\", \"section3\");\n let headingElement= document.createElement(\"h1\");\n headingElement.className = \"subHeadingClass\";\n headingElement.appendChild(document.createTextNode(\"21--Display 20 solid gray rectangles, each 20px high, with widths in pixels given by the 20 elements of sampleArray.\"));\n \n var destination = document.getElementById(\"mainSection\");\n destination.appendChild(headingElement);\n destination.appendChild(newElement);\n \n destination = document.getElementById(\"section3\");\n let widthDiv;\n for (i=0;i<20;i++){\n let newElement1 = document.createElement(\"div\");\n let newElement2 = document.createElement(\"div\");\n widthDiv=smplArr[i];\n newElement1.style.width = widthDiv+'px';\n newElement1.className = \"drawRect1\";\n newElement2.className=\"spaceClass\";\n destination.appendChild(newElement1);\n destination.appendChild(newElement2);\n }\n \n}",
"function addHighScore(record, node) {\n // Create the name text span\n var name = document.createElementNS(\"http://www.w3.org/2000/svg\", \"tspan\");\n\n // Set the attributes and create the text\n // let text = `${record.name}~${record.score}`; \n name.textContent = `${record.name}`;\n name.setAttribute(\"x\", 100);\n name.setAttribute(\"dy\", 40);\n\n\n // Add the name to the text node\n // name.set = \n\n // Create the score text span\n var score = document.createElementNS(\"http://www.w3.org/2000/svg\", \"tspan\");\n\n // Set the attributes and create the text\n score.textContent = `${record.score}`;\n score.setAttribute(\"x\", 400);\n\n\n // Add the score to the text node\n node.appendChild(name)\n node.appendChild(score)\n\n}",
"function levelAndScoreCount() {\r\n if (level == 0) {\r\n $(\"h2\").hide();\r\n $(\"#play\").hide();\r\n $(\"h1\").css(\"margin-top\", \"38px\")\r\n\r\n $(\"footer\").before('<h2 id=\"level-title\" class=\"score\"></h2>');\r\n $(\".score\").text(\"score: \" + score);\r\n $(\"h1\").text(\"level \" + level);\r\n level++;\r\n\r\n } else {\r\n $(\"h1\").text(\"level \" + level);\r\n level++;\r\n score += 50;\r\n $(\".score\").text(\"score: \" + score);\r\n\r\n }\r\n userPattern = [];\r\n}",
"function drawTable(){\n\n\tvar tableHeaderRowCount = 1;\n\tvar table = document.getElementById(\"scoreTableBody\");\n\t\n\t//i'm lazy and just delete each row one by one\n\tvar rowCount = table.rows.length;\n\tfor(var i = tableHeaderRowCount; i< rowCount; i++){\n\t\tconsole.log(\"delet thsi\");\n\t\ttable.deleteRow(tableHeaderRowCount);\n\t}\n\n\t\n\t//then I draw each row again\n\tfor(var i in scoreBoardHistory){\n\tvar row = table.insertRow(scoreTable.size);\n\tvar cell1 = row.insertCell(0);\n\tvar cell2 = row.insertCell(1);\n\n\tvar x = scoreBoardHistory[i].playerID;\n\tvar y = scoreBoardHistory[i].score;\n\tcell1.innerHTML = x;\n\tcell2.innerHTML = y;\n\t}\n\t\n\n\t//var x = document.getElementById(\"myID\").value;\n\t//var y = document.getElementById(\"myScore\").value;\n\t//cell1.innerHTML = x;\n\t//cell2.innerHTML = y;\n}",
"function drawStats(voteAverage) {\n var averageSpace = document.createElement(\"p\");\n averageSpace.setAttribute(\"class\", \"averageResult\");\n votingContainer.appendChild(averageSpace);\n var averageText = document.createTextNode(\"Average: \" + voteAverage);\n averageSpace.appendChild(averageText);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
counts the number of elements b in a given array a | function count(a, b) {
if (b == undefined) {
var count = a.length;
} else {
var count = 0;
for (var i = 0; i < a.length; ++i) {
if (a[i] == b)
count++;
}
}
return count;
} | [
"function numOfAppear(a, array) {\n var i;\n var n = 0;\n for (i = 0; i < array.length; i++) {\n if (array[i] == a) {\n n++;\n }\n }\n return n;\n}",
"function deepCount(a) {\n var len = a.length;\n for(var i = 0; i < a.length; i++){\n if(Array.isArray(a[i])){\n len+=deepCount(a[i]);\n }\n }\n return len;\n}",
"function neighbouringElements(a) {\n var count = 0;\n for(var i = 0; i < a.length; i++){\n for(var j = 0; j < a[0].length; j++){\n if(a[i][j] == a[i][j+1]) {\n count++;\n }\n if(a[i+1]){\n if(a[i+1][j] == a[i][j]){\n count++;\n }\n }\n }\n }\n return count;\n}",
"function rangeBitCount(a, b) {\n let sumOfOnes = 0;\n for(let i = a; i <= b; i++) {\n let binaryI = i.toString(2);\n for(let j = 0; j < binaryI.length; j++) {\n if(binaryI.charAt(j) == '1') sumOfOnes++;\n }\n }\n return sumOfOnes\n}",
"function countTinyPairs(a, b, k) {\n let revB = b.reverse();\n let tinyCount = 0;\n\n for (let index = 0; index < a.length; index++) {\n const elementA = a[index];\n const elementB = revB[index];\n let concat = elementA + \"\" + elementB;\n concat = parseInt(concat);\n\n if (concat < k){\n tinyCount += 1;\n }\n }\n\n return tinyCount;\n}",
"function countOf(array, element) {\n var x = 0;\n for (var i = 0; i < array.length; i++) {\n if (array[i] == element) {\n x++;\n }\n }\n return x;\n}",
"function commonTwo(a, b) {\n let count = 0;\n let uniq = [];\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n if (a.length < b.length) {\n if (b.includes(a[i]) && !(uniq.includes(a[i]))) {\n count++;\n uniq.push(a[i]);\n }\n } else {\n if (a.includes(b[i]) && !(uniq.includes(b[i]))) {\n count++;\n uniq.push(b[i]);\n }\n }\n }\n return count;\n}",
"function countNum (array) {\n\tvar uniqueArr = [];\n\tfor (i=0; i<=uniqueNumbers.length - 1; i++){\n\t\tvar count = array.filter (function (n) {\n\t\t\treturn n === uniqueNumbers [i];\n\t\t})\n\t\tuniqueArr.push (count.length);\n\t}\n\treturn uniqueArr;\n}",
"function calculatesNumberOFIntegers (array) {\n\nlet result = 0;\n for (let i = 0; i < array.length; i++) {\n\n if(isFinite(array[i]) && typeof array[i] === \"number\" && parseInt(array[i]) === array[i]) {\n\n result++;\n }\n }\n return result;\n}",
"function countCommon(arr1, arr2) {\n var counter = 0;\n arr1.forEach(function(el){\n if (arr2.indexOf(el)!==-1) counter++\n })\n return counter;\n }",
"function countInversion(arr) {\n\tlet count = 0;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tfor (let j = i + 1; j <= arr.length - 1; j++) {\n\t\t\tif (arr[i] > arr[j] && i < j) {\n\t\t\t\t// inversion occurs when a number is greater than its neighbor\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\treturn count;\n}",
"function countIndWithClass(ar, class_name)\n{\n\tvar count = 0;\n\tfor (var i = 0; i < ar.size(); i++)\n\t{\n\t\tif (ar.hasClass(i, class_name))\n\t\t{\n\t\t\tcount++;\n\t\t}\n\t}\n\treturn count;\n}",
"function halveCount(a, b) {\n\tlet x = -1;\n\tfor (let i = 0; a > b; i++) {\n\t\ta /= 2;\n\t\tx++;\n\t}\n\treturn x;\n}",
"function countNormal(arr) {\n // Your code here\n return 0;\n}",
"function appear(a){\n var number = 0;\n var e = 7;\n for (var i = 0; i < a.length; i++){\n if (e === a[i]){\n number++;\n }\n }\n return number;\n}",
"bitCount() {\n let result = 0;\n for(let i = 0; i < this.array.length; i++){\n result += BitSet.countBits(this.array[i]) // Assumes we never have bits set beyond the end\n ;\n }\n return result;\n }",
"function divisibleSumPairs(n, k, ar) {\n\nvar cnt = 0, i = 0, j = 0;\nfor(i=0;i<ar.length-1;i++){\n for(j=i+1;j<ar.length;j++){\n if((ar[i]+ar[j])%k==0){\n cnt++;\n }\n }\n}\nreturn cnt;\n}",
"function countBoomerangs(arr) {\n\tlet start = 0\n\tlet end = 2\n\tlet count=0\n\t\n\twhile(end <= arr.length-1){\n\t\t\n\t\tif(arr[start]===arr[end] && arr[start+1]!== arr[start]){\n\t\t\tcount++\n\t\t}\n\t\tstart++\n\t\tend++\n\t}\n\t\n\treturn count\n}",
"function getRotationCount(arrA){\n var rotme = arrA.slice(); \n var rotSo = arrA.sort((a, b) => { return a - b });\n var rotationC = 0; \n while (JSON.stringify(rotme) != JSON.stringify(rotSo) && rotationC <= arrA.length) {\n // document.writeln('rotationC: ', rotationC);\n rotme.unshift(rotme.pop());\n rotationC = rotationC + 1;\n }\n if(rotationC > arrA.length){\n return null; \n }\n return rotationC; \n}",
"function anagramCounter(arrayOfWords) {\n let sortedWords = arrayOfWords.map(word => word.split('').sort().join(''));\n let numberOfAnagrams = 0;\n\n sortedWords.forEach((word, theIndex) => {\n for (let i = theIndex + 1; i < sortedWords.length; i++) {\n if (word === sortedWords[i]) {\n numberOfAnagrams++\n }\n }\n })\n return numberOfAnagrams\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
END OF: GENERAL TEMPALTE METHODS VIDEO TEMPLATES, used by type "video_seq" Using the Vimeo API to check when a video is complete in order to show the next sequence in the videosequence. Could be a new video or more common a set of questions that leads to new videos or exits the sequence. See example in CaseMaria_Video.js | function addNodeVideoSequence(nodeId) {
var res ="",
seq_type,
myObj;
myObj=contentObj[nodeId].sequences[FS.currentSequence];
seq_type=myObj.type;
if (FS.currentSequence == 0) {res ="<div class='row' id='seqWrapper'>"}
switch (seq_type) {
case "video":
res +="<div class='centered eleven columns'><div class='loading' id='loader_0'><div class='track'></div><div class='spinner'><div class='mask'><div class='maskedCircle'></div></div></div></div>";
res +="<article class='vimeo video videoBg'>";
res +="<iframe id='iframe_"+myObj.sequenceID+"' style='visibility:hidden;' onload='FS.showIframe("+myObj.sequenceID+")' ";
res += "src='" + myObj.url + "?title=0&byline=0&portrait=0&autoplay=1&api=1&player_id=iframe_"+myObj.sequenceID+"' width='500' height='281' frameboder='0' webkitallowfullscreen='' mozallowfullscreen='' allowfullscreen=''>";
res +="</iframe></article></div>";
break;
case "question":
res +="<div class='centered eleven columns'>";
res +="<article class=''>";
res +="<div class='sequenceHeadline'>"+myObj.text +"</div>";
for (var i=0; i<_.size(myObj.answers); i++) {
res +="<div class='sequenceAnswer videoQuestion' onClick='FS.gotoSequence("+myObj.answers[i].gotoID+")'>"+ myObj.answers[i].text +"</div>";
//if(myObj.answers[1]!=undefined) res +="<div class='sequenceAnswer videoQuestion' onClick='FS.gotoSequence("+myObj.answers[1].gotoID+")'>"+ myObj.answers[1].text +"</div>";
}
res +="</article></div>";
break;
case "text":
res +="<div class='centered eleven columns'>";
res +="<article class=''>";
if (myObj.header!=undefined) res +="<div class='sequenceHeadline'>"+myObj.header +"</div>";
if (myObj.content!=undefined) res +="<div class='sequenceText'>"+ myObj.content +"</div>";
res +="</article></div>";
break;
}
if (FS.currentSequence == 0) res+="</div>"
return res;
} | [
"function nextVideo() {\n\t\tindex == 2 ? index = 0 : index++; //loop counter\n\t\tfunctions[index](); //run\n\t\t//loop first before running because first func is to show vid 1\n\t}",
"function nextVideoByVotes()\n { \n var votes = [];\n Object.keys(videoVotes).forEach(function (key) \n { \n var value = videoVotes[key];\n votes.push([key, value]);\n });\n \n // Find highest voted video\n var highestVoted = [\"\", 0];\n for (var i = 0; i < votes.length; i++)\n {\n if (votes[i])\n {\n if (votes[i][1] > highestVoted[1] && votes[i][1] >= videoByVoteThresh)\n {\n highestVoted = votes[i];\n }\n }\n }\n \n if (videoVotes.length == 0 || highestVoted[0].length == 0)\n {\n nextVideo();\n return;\n }\n \n var highestVotedId = highestVoted[0];\n sendVideoChange(highestVotedId);\n }",
"function TEST(vid) {\n\tvar player;\n\t\n\tfunction onYouTubeIframeAPIReady() {\n\t\tplayer = new YT.Player('YTIframe', {\n\t\t\tevents: {\n\t\t\t\t'onReady': function onPlayerReady(event) {\n\t\t\t\t\t$('#v_name').text(event.target.getVideoData().title);\n\t\t\t\t\tconsole.log('loading Player');\n\t\t\t\t\tloadDoc();\n\t\t\t\t},\n\t\t\t\t'onStateChange': onPlayerStateChange\n\t\t\t}\n\t\t});\n\n\t}\n\tfunction onPlayerStateChange() {\n\t\tconsole.log(\"my state changed\");\n\t\tchanged = 1;\n\t}\n\tonYouTubeIframeAPIReady();\n\tfunction loadDoc() {\n\t\tvar xhttp = new XMLHttpRequest();\n\t\tvar parser, xmlDoc;\n\t\txhttp.onreadystatechange = function () {\n\t\t\tif (this.readyState == 4 && this.status == 200) {\n\t\t\t\tvar Data = this.responseText.toString();\n\t\t\t\tif(hide==0)\n\t\t\t\t$('#subs').text('Subtitles Loaded');\n\t\t\t\tfunction Parse(data) {\n\t\t\t\t\tvar subtitles = [];\n\t\t\t\t\tsrt = data.replace(/\\r\\n|\\r|\\n/g, '\\n');\n\t\t\t\t\tvar srt_ = srt.split('\\n');\n\t\t\t\t\tvar prev = 0;\n\t\t\t\t\tvar cont = 0;\n\t\t\t\t\tvar divider = 0;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (s in srt_) {\n\t\t\t\t\t\t\tsrt_[s] = srt_[s].replace(/<\\/?[^>]+(>|$)/g, \"\");\n\t\t\t\t\t\t\tst = srt_[s].split('\\n');\n\t\t\t\t\t\t\tdivider++;\n\t\t\t\t\t\t\tn = st[0];\n\t\t\t\t\t\t\tif (divider == 1) {\n\t\t\t\t\t\t\t\tsubtitles[cont] = {};\n\t\t\t\t\t\t\t\tsubtitles[cont].number = n;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (divider == 2) {\n\t\t\t\t\t\t\t\tvar time = n.split(' --> ');\n\t\t\t\t\t\t\t\tvar mm = time[0].split(':');\n\t\t\t\t\t\t\t\tvar hr = mm[0] * 3600;\n\t\t\t\t\t\t\t\tvar min = mm[1] * 60;\n\t\t\t\t\t\t\t\tvar ss;\n\t\t\t\t\t\t\t\tss = mm[2].split(',')[0];\n\t\t\t\t\t\t\t\tvar sec = parseInt(ss) + parseInt(min) + parseInt(hr);\n\t\t\t\t\t\t\t\tsubtitles[cont].start = sec;\n\t\t\t\t\t\t\t} else if (divider == 3) {\n\t\t\t\t\t\t\t\tsubtitles[cont].text = n;\n\t\t\t\t\t\t\t} else if (divider == 4) {\n\t\t\t\t\t\t\t\tdivider = 0;\n\t\t\t\t\t\t\t\tcont++;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconsole.log('divider error');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.log(subtitles);\n\t\t\t\t\t\tif (subtitles.length <= 2) {\n\t\t\t\t\t\t\t$('#subs').text(\"Subtitles blocked by Youtube due to Copyrights.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvar temp = 0;\n\t\t\t\t\t\ttime_update_interval = setInterval(function () {\n\t\t\t\t\t\t\tupdateTimerDisplay();\n\t\t\t\t\t\t}, 100);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t$('#subs').text(\"Subtitles blocked by Youtube due to Copyrights.\");\n\t\t\t\t\t}\n\t\t\t\t\tfunction updateTimerDisplay() {\n\t\t\t\t\t\tvar t = Math.round(player.getCurrentTime());\n\t\t\t\t\t\tif (changed == 1) {\n\t\t\t\t\t\t\tsubindex = 0;\n\t\t\t\t\t\t\twhile (subtitles[subindex].start < t) {\n\t\t\t\t\t\t\t\tsubindex++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tchanged = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (subtitles[subindex].start < t) {\n\n\n\n\n\t\t\t\t\t\t\tif (mute == 1) {\n\t\t\t\t\t\t\t\tif(hide==0)\n\t\t\t\t\t\t\t\t$('#subs').text(subtitles[subindex].text);\n\t\t\t\t\t\t\t\tsubindex++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (!responsiveVoice.isPlaying()) {\n\t\t\t\t\t\t\t\t\tif(audio==true)\n\t\t\t\t\t\t\t\t\tresponsiveVoice.speak(subtitles[subindex].text, \"Hindi Female\", { rate: 1 });\n\t\t\t\t\t\t\t\t\tif(hide==0)\n\t\t\t\t\t\t\t\t\t\t$('#subs').text(subtitles[subindex].text);\n\t\t\t\t\t\t\t\t\tsubindex++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tParse(Data);\n\t\t\t}\n\t\t};\n\t\txhttp.open(\"GET\", \"http://picword.in/testSubs.php?Youtube=https://www.youtube.com/watch?v=\" + vid + \"&Lang=\"+lang, true);\n\t\txhttp.send();\n\t}\n}",
"function playActorVideo(actor, time) {\n //playVideo(id, time - startTime of video)\n\n}",
"function Emailvideo(t,v,hb,ent)\r\n\t{\r\n\t\tvar videoTitle = t.replace(/'/g, \"‘\");\r\n\t\tvar videoUrl = v;\r\n\t\tif (ent == '1'){\r\n\t\tlaunch('SendVideo',336,535,'http:\\/\\/www.cbsnews.com/htdocs/send_article/entertainment.html?story_headline='+videoTitle+'&story_url=http:\\/\\/www.cbsnews.com/sections/showbuzz_video/main500540.shtml?clip='+videoUrl+'&title='+t.replace(/ /g, \"$@$\")+hb);}\r\n\t\telse {\r\n\t\tlaunch('SendVideo',540,400,'http:\\/\\/www.cbsnews.com/htdocs/send_article/framesource.html?story_headline='+videoTitle+'&story_url=http:\\/\\/www.cbsnews.com/sections/i_video/main500251.shtml?id='+videoUrl);}\r\n\t}",
"function playVideoOnTime(videodata) {\n $.each(getVideos, function(key, value) {\n // See if any video should be played now\n if ((value.startSeconds > 1)) {\n //console.log('Video ID :' + value.videoId + ' at : ' + value.startSeconds);\n domYouTubeContainer.tubeplayer(\"play\", {\n id: value.videoId,\n time: value.startSeconds\n });\n }\n });\n }",
"isVideoTrack() {\n return this.getType() === MediaType.VIDEO;\n }",
"static playVideoOnLoadAsync(element,timeout){return __awaiter$1(this,void 0,void 0,function*(){// if canplay was already fired, we won't know when to play, so just give it a try\nconst isPlaying=yield BrowserCodeReader$1.tryPlayVideo(element);if(isPlaying){return true;}return new Promise((resolve,reject)=>{// waits 3 seconds or rejects.\nconst timeoutId=setTimeout(()=>{if(BrowserCodeReader$1.isVideoPlaying(element)){// if video is playing then we had success, just ignore\nreturn;}reject(false);element.removeEventListener('canplay',videoCanPlayListener);},timeout);/**\n * Should contain the current registered listener for video loaded-metadata,\n * used to unregister that listener when needed.\n */const videoCanPlayListener=()=>{BrowserCodeReader$1.tryPlayVideo(element).then(hasPlayed=>{clearTimeout(timeoutId);element.removeEventListener('canplay',videoCanPlayListener);resolve(hasPlayed);});};// both should be unregistered after called\nelement.addEventListener('canplay',videoCanPlayListener);});});}",
"function runPauseSequence() {\n var time = getVideoTime();\n logVideoEvent('pause', time, VIDEO_EVENT_LOG_URL).\n then(function() {\n pauseVideo();\n });\n}",
"static tryPlayVideo(videoElement){return __awaiter$1(this,void 0,void 0,function*(){if(videoElement===null||videoElement===void 0?void 0:videoElement.ended){console.error('Trying to play video that has ended.');return false;}if(BrowserCodeReader$1.isVideoPlaying(videoElement)){console.warn('Trying to play video that is already playing.');return true;}try{yield videoElement.play();return true;}catch(error){console.warn('It was not possible to play the video.',error);return false;}});}",
"function Video (dataVideo) { \n this.$el = \"\"; // this will hold the video html element\n this.data = dataVideo;\n this.init = function (videoHtmlEL){ //when creating a new Video object we need to define the html element to connect it to\n\n // create the video in html\n var output = '';\n switch(true){\n case (this.data.type == 'html5') :\n output += '<video id=\"catbearsVideo\" width=\"100%\" height=\"100%\" controls=\"\">'\n output += '<source src=\"../video/'\n output += this.data.fileName\n output += '\" type=\"video/mp4\"/>'\n output += 'Your browser does not support HTML5 video.'\n output += '</video>'\n break;\n case (this.data.type == 'youtube') : \n // embed video\n break; \n\n\n } \n // append the video \n $(videoHtmlEL).append(output);\n this.$el = document.getElementById(\"catbearsVideo\");\n }; \n this.play = function (){\n this.$el.play()\n // $el play\n }\n this.pause = function (){\n this.$el.pause()\n }\n this.togglePlayPause = function () { \n if(this.$el.paused){\n this.$el.play();\n }else{ \n this.$el.pause();\n }; \n };\n this.seekTo = function (second){\n this.$el.currentTime = second;\n }\n}",
"function onTimeupdate(){\n //if the video has finished\n if ( this.currentTime >= this.duration ){\n //if we are offering e-mail sharing\n if (configHandler.get('showLocalShare')){\n var vidElem = document.getElementById('videoReview');\n //if we have not shown the e-mail option yet\n if (haveShownShare === false ){\n //remember that we have shown it\n haveShownShare = true;\n //transition in the other UI elements\n var container = document.getElementById('videoReviewContainer');\n container.classList.add('share');\n var btn = document.getElementById('breakButton');\n btn.classList.remove('enabled');\n btn.classList.add('disabled');\n vidElem.muted = true;\n //play the audio after the e-mail option\n // has transitioned in\n if (soundPlayer.exists()){\n soundTimeout = setTimeout(function(){\n soundPlayer.play();\n }, 1000);\n }\n }\n //replay the video\n vidElem.currentTime = 0;\n vidElem.play();\n } else {\n //if we are not offering e-mail sharing\n // just transition to the thank you screen\n window.events.dispatchEvent(new Event('special'));\n }\n }\n }",
"function video_done(e) {\n\tthis.currentTime = 0;\n}",
"function autoAdvanceLaptopVideos() {\n numTicks++;\n\n if (numTicks >= requiredTicks[curVideo - 1] && isElementVerticallyVisible(instructVideoContainer)) {\n numTicks = 0;\n curVideo++;\n\n if (curVideo > requiredTicks.length) {\n curVideo = DEFAULT_VIDEO;\n }\n\n switchToVideo(curVideo);\n }\n}",
"function loadVideo() {\n\t\tvar d = new Date();\n\t\tvar lastYear = d.getFullYear() - 1;\n\t\tvar month = d.getMonth() +1;\n\t\tvar day = d.getDate();\n\t\tvar myKey = \"AIzaSyAr0fnc8B-t96isVPUByudWNPFDKJIugoc\";\n\t\tvar request = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&order=viewCount&publishedAfter='+lastYear+'-'+month+'-'+day+'T00%3A00%3A00Z&q=teaser|trailer -india|game&type=video&videoCaption=any&relevanceLanguage=en&videoCategoryId=24&videoEmbeddable=true&key=' + myKey;\n\t\t$.ajax({\n\t\t\turl: request,\n\t\t\tsuccess: function (data) {\n\t\t\t\tvar id = data.items[0].id.videoId;\n\n\t\t\t\tdata.items.forEach(buildArray);\n\n\t\t\t\tplayVideo();\n\n\t\t\t}\n\t\t});\n\t}",
"function receiveTwo(msg, videos, color){\n console.log(\"videos\");\n console.log(videos);\n var outerDiv = document.createElement(\"div\");\n outerDiv.style.color = color;\n if(videos === undefined){\n outerDiv.style.margin = \"20px 0 0 0 \";\n } else{\n if(videos.length == 0){\n outerDiv.style.margin = \"20px 0 0 0 \";\n }\n }\n var splitMsg = msg.match(/\\S+/g);\n var totalTime = 0;\n var currentVideoIndex = 0;\n splitMsg.forEach(function(token, index){\n if(isEmoticon(token)){\n var thisVideoIndex = currentVideoIndex;\n setTimeout(function(){\n displayVideo(videos[thisVideoIndex], outerDiv);\n }, totalTime);\n totalTime += VIDEO_TIME_INTERVAL;\n currentVideoIndex += 1;\n } else {\n setTimeout(function(){\n displayWord(token, outerDiv);\n }, totalTime);\n totalTime += WORD_TIME_INTERVAL;\n \n };\n });\n document.getElementById(\"receive_two_display\").appendChild(outerDiv);\n}",
"static isVideoPlaying(video){return video.currentTime>0&&!video.paused&&video.readyState>2;}",
"function extractYoutubeVid(url){\n var regExp = /^.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|\\&v=)([^#\\&\\?]*).*/;\n var match = url.match(regExp);\n if (match && match[2].length == 11) {\n return match[2];\n } else {\n return null;\n }\n }",
"function onParticipantVideo(status, resource, event) {\n var scope = event['in'];\n if (event.sender.href == rConversation.href && scope) {\n if (scope.rel == 'localParticipant') {\n switch (event.type) {\n case 'added':\n case 'updated':\n activeModalities.video = true;\n if (isConferencing()) {\n selfParticipant[Internal.sInternal].setMediaSourceId(event);\n updateMediaRoster(selfParticipant, isInMediaRoster(selfParticipant) ? 'update' : 'add');\n // check participants that are already in the conference - we need their msis\n // because we won't receive \"participantVideo added\" events for them.\n participants.each(function (p) {\n if (!isInMediaRoster(p) && p[Internal.sInternal].audioSourceId() != -1)\n updateMediaRoster(p, 'add');\n });\n }\n videoState(Internal.Modality.State.Connected);\n selfParticipant[Internal.sInternal].videoState(Internal.Modality.State.Connected);\n break;\n case 'deleted':\n removeVideo(selfVideoStream, true);\n activeModalities.video = false;\n if (isConferencing()) {\n if (isInMediaRoster(selfParticipant))\n updateMediaRoster(selfParticipant, 'remove');\n selfParticipant[Internal.sInternal].setMediaSourceId(event);\n }\n videoState(Internal.Modality.State.Disconnected);\n selfParticipant[Internal.sInternal].videoState(Internal.Modality.State.Disconnected);\n break;\n default:\n assert(false, 'unexpected event type');\n }\n }\n else if (scope.rel == 'participant') {\n Task.wait(getParticipant(scope.href)).then(function (participant) {\n switch (event.type) {\n case 'added':\n case 'updated':\n if (isConferencing()) {\n participant[Internal.sInternal].setMediaSourceId(event);\n updateMediaRoster(participant, isInMediaRoster(participant) ? 'update' : 'add');\n participant[Internal.sInternal].videoState(Internal.Modality.State.Connected);\n }\n else {\n participant[Internal.sInternal].setVideoStream(mainVideoStream);\n participant[Internal.sInternal].videoState(Internal.Modality.State.Connected);\n }\n break;\n case 'deleted':\n if (isConferencing()) {\n if (isInMediaRoster(participant))\n updateMediaRoster(participant, 'remove');\n participant[Internal.sInternal].setMediaSourceId(event);\n removeParticipantVideo(participant);\n participant[Internal.sInternal].videoState(Internal.Modality.State.Disconnected);\n // if participant video is deleted not because we stopped video\n // subscription explicitly (via isStarted(false)) but because \n // participant left the AV call then we need to reset isStarted.\n participant[Internal.sInternal].setVideoStarted(false);\n }\n else {\n participant[Internal.sInternal].setVideoStream(null);\n participant[Internal.sInternal].videoState(Internal.Modality.State.Disconnected);\n }\n break;\n default:\n assert(false, 'unexpected event type');\n }\n });\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
detectar si el navegador del ciente soporta Gecko / AbstractWindow Constructor / p_xo = Coordenada X en pixels. p_yo = Coordenada Y en pixels. p_to = Timeout en segundos p_hgt = Altura en pixels. p_wth = Ancho X en pixels. | function AbstractWindow(url, p_xo, p_yo, p_wth, p_hgt) {
/* Clase para mostrar la ventana*/
this.classHide = "iwinContainerHide";
/* Clase para ocultar la ventana*/
this.classShow = "iwinContainer";
/* Atributos */
this.xo = p_xo || 0;
this.yo = p_yo || 0;
this.wth = p_wth || 100;
this.hgt = p_hgt || 100;
this.url = url;
this.created = false;
this.visible = false;
/*HTML Atributes */
this.element = null;
/* Methods */
/* This function shows de basedow */
this.show = function() {
this.show_prev();
/* Se crea la ventana */
this.element = document.createElement("div");
this.element.appendChild(this.createContent());
/* Se agrega la ventana al cuerpo de la pagina */
document.body.appendChild(this.element);
this.element.className = this.classShow;
this.locateWindow(this.xo, this.yo, this.wth, this.hgt);
this.visible = true;
this.show_next();
}
/* This function Hides the basedow */
this.hide = function() {
var ret = true;
if (this.onHideStart) eval(this.onHideStart);
if (ret) {
this.hide_prev();
this.element.className = this.classHide;
this.visible = false;
this.hide_next();
if (this.onHideEnd) eval(this.onHideEnd);
}
}
this.locateWindow = function (x, y, w, h) {
this.wth=w;
this.hgt=h;
this.xo=x;
this.yo=y;
this.element.style.left = x + 'px' ;
this.element.style.top = y + 'px';
}
this.determineWidth = function() {
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
return w;
}
this.determineHeight = function() {
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
return h;
}
/****
** Metodos a definir en una clase hijo
*****/
/* Funcion que genera el contenido de la ventana, debe ser redefinida por las clases herederas para cambiar su funcionamiento
* @Abstract
*/
this.createContent = function() { alert("Debe redefinir el metodo 'createContent'"); }
/* Metodos a redefinir en una clase hijo para ejecutar codigo propio antes y despues de la operacion show*/
this.show_prev = function() {}
this.show_next = function() {}
/* Metodos a redefinir en una clase hijo para ejecutar codigo propio antes y despues de la operacion hide */
this.hide_prev = function() {}
this.hide_next = function() {}
/**
* Eventos que el usuario puede definir para obtener control de la ventana
* Si devuelven false, susupende la ejecución del evento.
*/
this.onHideStart = undefined; //Antes de Cerrar (Debe devolver true/false).
this.onHideEnd = undefined; //Despues de Cerrar
} | [
"function SlideWindow(name, url, p_wth, p_hgt, p_to) {\r\n\tthis.base = AbstractWindow;\r\n\tthis.base(url, 0, 0, p_wth, 1);\r\n\t/* Atributes */\r\n\tthis.name = name;\r\n\tthis.timeOut = p_to * 1000 || 15000; //TimeOut\r\n\tthis.yoEnd; //Ending move coordinate\r\n\tthis.xoEnd; //Ending move coordinate\r\n\tthis.process = -1; //Generic process\r\n\t\r\n\tthis.createContent = \tfunction() {\r\n\t\t\t\t\t\t\t\tvar ifrm = document.createElement(\"iframe\");\r\n\t\t\t\t\t\t\t\tifrm.className= this.classShow;\r\n\t\t\t\t\t\t\t\tifrm.setAttribute(\"class\", this.classShow);\r\n\t\t\t\t\t\t\t\tifrm.height = this.hgt;\r\n\t\t\t\t\t\t\t\tifrm.src = this.url;\r\n\t\t\t\t\t\t\t\tifrm.style.scrolling = \"auto\";\r\n\t\t\t\t\t\t\t\treturn ifrm;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\tthis.ultimoElementoActivo = function() {\r\n\t\t\t\t\t\t\t\t\tvar index = slideRegister.length - 1;\r\n\t\t\t\t\t\t\t\t\twhile ((index >= 0) && (slideRegister[index] == undefined)) index--;\r\n\t\t\t\t\t\t\t\t\tvar ret = (slideRegister[index])? slideRegister[index] : undefined;\r\n\t\t\t\t\t\t\t\t\t//Si se acumularon muchas ventanas cerradas y no hay ninguna activa, reinicio el registro.\r\n\t\t\t\t\t\t\t\t\tif ((!ret) && (slideRegister.length > 50)) slideRegister = Array();\r\n\t\t\t\t\t\t\t\t\treturn ret;\r\n\t\t\t\t\t\t\t\t}\r\n\t/* Determina Xo e Yo */\r\n\t//Asume que es la primera ventana.\r\n\tthis.xo = this.determineWidth() - this.wth - 5;\r\n\tthis.yo = this.determineHeight() - 5;\r\n\t//Se posiciona basandose en el slide anterior.\r\n\tvar elem = this.ultimoElementoActivo();\r\n\tif (elem != undefined) {\r\n\t\t//Se supone que la nueva ventana va a estar encima de la ultima mostrada.\r\n\t\tvar xoAux = this.xo;\r\n\t\tthis.xo = elem.xo;\r\n\t\t//Se calcula hasta donde llega, si se sale de la pantalla, lo mueve al costado.\r\n\t\tvar yoAux = elem.yoEnd;\r\n\t\tif ((yoAux - p_hgt) < 0)\r\n\t\t\t//Se va de pantalla.\t\r\n\t\t\tthis.xo = this.xo - this.wth - 5;\r\n\t\telse\r\n\t\t\t//No se va de pantalla.\r\n\t\t\tthis.yo = elem.yoEnd;\r\n\t}\r\n\t/* Determina la posicion final */\r\n\tthis.yoEnd = this.yo - p_hgt - 5;\r\n\tthis.xoEnd = this.xo;\r\n\t/* Se setean los estilos */\r\n\tthis.classShow = \"iwinSlideWindow\";\r\n\t/* Muestra la ventana */\r\n\tthis.show();\r\n\t/* Registra la ventana */\r\n\tslideRegister.push(this); \r\n\tslideNameRegister[this.name] = this;\r\n\t/* Mueve la ventana */\r\n\tiwinMoveIt(slideRegister.length - 1);\r\n\treturn this;\r\n}",
"function MyWindow($opt){//name deve essere uguale al nome della variabile che contiene il nuovo oggetto\n\tthis.opt=$opt;\n\tvar test=$opt['name'];\n\tvar _self=this;\n\t$zindex++;\n\tthis.name=$opt['name'];\n\tthis.chiudi= function(){\n\t\tthis.windows.innerHTML=\"\";\n\t\treturn;\n\t};\n\tthis.hide= function(){\n\t\tthis.windows.style.visibility=\"hidden\";\n\t\treturn;\n\t};\n\tthis.show= function(){\n\t\tthis.windows.style.visibility=\"visible\";\n\t\treturn;\n\t};\n\tthis.centra= function(){\n\t\tvar MyWindowsHeight=this.windows.offsetHeight;\n\t\tvar MyWindowsWidth=this.windows.offsetWidth;\n\t\tvar browserHeight=getTop(document.getElementById('SpaceCalculator'));\n\t\tvar browserWidth=getLeft(document.getElementById('SpaceCalculator'));\n\t\tvar MyTop=(browserHeight-MyWindowsHeight)/2;\n\t\tvar MyLeft=(browserWidth-MyWindowsWidth)/2;\n\n\t\tthis.windows.style.top=MyTop;\n\t\tthis.windows.style.left=MyLeft;\n\t\treturn;\n\t};\n\tthis.fadeOut= function(){\n\t\tthis.windows.style.opacity=0.9;\n\t\treturn;\n\t};\n\tthis.fadeIn=function($to, $time){\n\t\tif($time){//se ho impostato un tempo calcolo quanti cicli servono\n\t\t\tvar $numCicli=Math.round($time/$MyTimer)\n\t\t}else{//se non l'ho impostato allora vuole dire che voglio sia fatto subito\n\t\t\tvar $numCicli=1;\n\t\t}\n\t\tvar $step=$differenza/$numCicli;\n\t\tvar $resta=$to-$step;\n\t\tfor($ciclo=1;$ciclo<=$numCicli;$ciclo++){\n\t\t\t// opacity = (opacity == 100)?99.999:h;\n\t\t\t// IE/Win\n\t\t\t//this.windows.style.filter = \"alpha(opacity:\"+h+\")\";\n\t\t\t// Safari<1.2, Konqueror\n\t\t\t//this.windows.style.KHTMLOpacity = (this.windows.style.KHTMLOpacity+$step/100);\n\t\t\t// Older Mozilla and Firefox\n\t\t\t//this.windows.style.MozOpacity = (this.windows.style.MozOpacity+$step/100);\n\t\t\t// Safari 1.2, newer Firefox and Mozilla, CSS3\n\t\t\t//this.windows.style.opacity = $step*$ciclo;\n\t\t\t//h=h-Conf['DecrementoOpacita'];\n\t\t\t//alert($ciclo+'->'+this.windows.style.opacity);\n\t\t}\n\t\tif(timerID!=''){\n\t\t\tclearTimeout(timerID);\n\t\t}\n\t\tvar timerID=setTimeout(this.fadeIn(),$MyTimer,$resta,$time-$MyTimer)\n\t\treturn;\n\t};\n\tvar $id='MyWindowsID_'+$opt['name'];\n\n\t/*Definisco tutti i tag html che mi serviranno per costruire la mia finestrella*/\n\t//contorno superore\n\tvar MyTopSx= document.createElement(\"td\");\n\tMyTopSx.setAttribute(\"class\",\"TopSx\");\n\t\n\tvar MyTopDx= document.createElement(\"td\");\n\tMyTopDx.setAttribute(\"class\",\"TopDx\");\n\t\n\tvar MyBgTop= document.createElement(\"td\");\n\tMyBgTop.setAttribute(\"class\",\"BgTop\");\n\t\n\tvar MyTopTr=document.createElement(\"tr\");\n\tMyTopTr.appendChild(MyTopSx);\n\tMyTopTr.appendChild(MyBgTop);\n\tMyTopTr.appendChild(MyTopDx);\n\t\n\t//contorno testo\n\tvar MyBgDx= document.createElement(\"td\");\n\tMyBgDx.setAttribute(\"class\",\"BgDx\");\n\t\n\tvar MyBgSx= document.createElement(\"td\");\n\tMyBgSx.setAttribute(\"class\",\"BgSx\");\n\t\n\tvar MyBgMainContainer=document.createElement(\"div\");\n\tMyBgMainContainer.setAttribute(\"class\",\"main\");\n\t\n\tMyBgMainContainer.innerHTML=$opt['txt'];\n\n\t//Eventuale barra del tittolo\n\tif($opt['title']!=null){\n\t\tvar MyTitle=document.createElement(\"div\");\n\t\tMyTitle.setAttribute(\"class\",\"TitleBarTxt\");\n\t\tMyTitle.innerHTML=$opt['title'];\n\t\t\n\t\tvar MyCloseButtonImage=document.createElement(\"img\");\n\t\tMyCloseButtonImage.setAttribute(\"src\",\"./../oLibs/MyWindow/img/chiudi.png\");\n\t\tMyCloseButtonImage.setAttribute(\"alt\",\"X\");\n\t\t\n\t\tvar MyCloseButtonLink=document.createElement(\"a\");\n\t\tMyCloseButtonLink.appendChild(MyCloseButtonImage);\n\t\tif($opt['isPermanent']==true){\n\t\t\tMyCloseButtonLink.onclick=function(){\n\t\t\t\t_self.hide();\n\t\t\t}\n\t\t}else{\n\t\t\tMyCloseButtonLink.onclick=function(){\n\t\t\t\t_self.chiudi();\n\t\t\t}\n\t\t}\n\n\t\tvar MyCloseButton=document.createElement(\"div\");\n\t\tMyCloseButton.appendChild(MyCloseButtonLink);\n\t\tMyCloseButton.setAttribute(\"class\",\"closeButton\");\n\t\t\n\t\tvar MyTitleBar=document.createElement(\"div\");\n\t\tMyTitleBar.setAttribute(\"class\",\"TitleBar\");\n\t\tMyTitleBar.appendChild(MyTitle);\n\t\tMyTitleBar.appendChild(MyCloseButton);\n\t}\n\t//fine barra del titolo continuo con la finestrella\n\tvar MyBgMain= document.createElement(\"td\");\n\tMyBgMain.setAttribute(\"class\",\"mainBG\");\n\tif($opt['title']){\n\t\t//se ho creato la barra del titolo la mostro\n\t\tMyBgMain.appendChild(MyTitleBar);\n\t}\n\tMyBgMain.appendChild(MyBgMainContainer);\n\t\n\tvar MyBgTr=document.createElement(\"tr\");\n\tMyBgTr.appendChild(MyBgSx);\n\tMyBgTr.appendChild(MyBgMain);\n\tMyBgTr.appendChild(MyBgDx);\n\t\n\t//contorno inferiore\n\tvar MyBottomSx= document.createElement(\"td\");\n\tMyBottomSx.setAttribute(\"class\",\"BottomSx\");\n\t\n\tvar MyBottomDx= document.createElement(\"td\");\n\tMyBottomDx.setAttribute(\"class\",\"BottomDx\");\n\t\n\tvar MyBgBottom= document.createElement(\"td\");\n\tMyBgBottom.setAttribute(\"class\",\"BgBottom \");\n\t\n\tvar MyBottomTr=document.createElement(\"tr\");\n\tMyBottomTr.appendChild(MyBottomSx);\n\tMyBottomTr.appendChild(MyBgBottom);\n\tMyBottomTr.appendChild(MyBottomDx);\n\t\n\t//Tabella\n\tvar MyTable=document.createElement(\"table\");\n\tMyTable.setAttribute(\"class\",\"MyTable\");\n\tMyTable.setAttribute(\"cellspacing\",\"0px\");\n\tMyTable.appendChild(MyTopTr);\n\tMyTable.appendChild(MyBgTr);\n\tMyTable.appendChild(MyBottomTr);\n\n\tMyTable.style.zIndex=$zindex;\n\tif($opt['width']){\n\t\tMyTable.width=$opt['width']+'px';\n\t}\n\tif($opt['height']){\n\t\tMyTable.height=$opt['height']+'px';\n\t\tMyTable.style.maxheight=$opt['height']+'px';\n\t}\n\n\t//La aggiungo al body tenendola nascosta\n\tMyTable.style.visibility='hidden';\n\tMyTable.style.top=0;//imposto a zero per evitare sfarfallamenti con la barra di scorrimento su firefox\n\tMyTable.style.left=0;//idem come sopra\n\tdocument.body.appendChild(MyTable);\n\n\t//posiziono la finestrella al centro del browser\n\tvar MyWindowsHeight=MyTable.offsetHeight;\n\tvar MyWindowsWidth=MyTable.offsetWidth;\n\t//se mi sono passato qualche parametro per il posizionamento mi ricavo i dati\n\tif($opt['position']){\n\t\tswitch ($opt['position']){\n\t\t\tcase 'top-left':\n\t\t\t\t$opt['top']=getTop($opt['this']);\n\t\t\t\t$opt['left']=getLeft($opt['this']);\n\t\t\tbreak;\n\t\t\tcase 'top-right':\n\t\t\t\t$opt['top']=getTop($opt['this']);\n\t\t\t\t$opt['left']=getLeft($opt['this'])+$opt['this'].offsetWidth-MyWindowsWidth;\n\t\t\tbreak;\n\t\t\tcase 'bottom-left':\n\t\t\t\t$opt['top']=getTop($opt['this'])+$opt['this'].offsetHeight+MyWindowsHeight;\n\t\t\t\t$opt['left']=getLeft($opt['this']);\n\t\t\tbreak;\n\t\t\tcase 'bottom-right':\n\t\t\t\t$opt['top']=getTop($opt['this'])+$opt['this'].offsetHeight+MyWindowsHeight;\n\t\t\t\t$opt['left']=getLeft($opt['this'])+$opt['this'].offsetWidth-MyWindowsWidth;\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t$opt['top']=getTop($opt['this']);\n\t\t\t\t$opt['left']=getLeft($opt['this']);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(isNaN($opt['top']) || isNaN($opt['left'])){\n\n\t\tvar browserHeight=getTop(document.getElementById('SpaceCalculator'));\n\t\tvar browserWidth=getLeft(document.getElementById('SpaceCalculator'));\n\n\t\tvar MyTop=(browserHeight-MyWindowsHeight)/2;\n\t\tvar MyLeft=(browserWidth-MyWindowsWidth)/2;\n\n\t}else{\n\t\tvar MyTop=$opt['top']-MyWindowsHeight;\n\t\tvar MyLeft=$opt['left'];\n\t}\n/*---------------------------------------------------------------------------*/\n\tif($opt['isTip']){//se si tratta di un tips\n\t\t//MyTop-=18; //Altezza\n\t\t//MyLeft+=54;//larghezza\n\t}\n\tMyTable.style.top=MyTop+'px';\n\tMyTable.style.left=MyLeft+'px';\n\n\t//finito di posizionarla posso finalmente mostrarla\n\tif($opt['isVisible']!=false){\n\t\tMyTable.style.visibility='visible';\n\t}\n\n\tif($opt['title']){//se c'è un titolo e quindi una barra del titolo allora probabilmente voglio che la finestra sia draggabile\n\t\t//aggiongo il drag and drop\n\t\tvar theHandle = MyTitleBar;\n\t\tvar theRoot = MyTable;\n\t\tDrag.init(theHandle, theRoot);\n\t}\n\t//----------------\n\tthis.windows=MyTable;\n\n\tif($opt['autoCloseTime']){\n\t\tthis.timer='';\n\t\t//programmo già una chiusura se non vado sopra col mouse\n\t\t/*\n\t\t$opt['this'].onmouseout=function(){\n\t\t\t\tthis.timer=setTimeout(function(){_self.hide();},$opt['autoCloseTime'])\n\t\t}\n*/\n\t\tthis.windows.onmouseout=function(){\n\t\t\t//var _self=this;\n\t\t\t//if(this.timer==''){\n\t\t\t\t//alert('test');\n\t\t\t\tthis.timer=setTimeout(function(){_self.hide();},$opt['autoCloseTime'])\n\t\t\t//}\n\t\t}\n\t\tthis.windows.onmouseover=function(){\n\t\tif(this.timer){\n\t\t\t\tclearTimeout(this.timer);\n\t\t\t\tthis.timer='';\n\t\t\t}\n\t\t}\n\t\treturn;\n\t};\n\treturn this;\n}",
"function outOfGameWindow(x,y){\n return (x > gameWindow.x + gameWindow.width || x < gameWindow.x) || (y > gameWindow.y + gameWindow.height || y < gameWindow.y);\n}",
"getPosition(width, height) {\n let twidth = window.innerWidth;\n let config = document.getElementById(\"config\");\n const margin = 10;\n if (config !== null) twidth -= config.offsetWidth + margin;\n\n // Make sure that if width > twidth we place it anyway\n twidth = Math.max(this.parent_.offsetLeft + 1, twidth - width);\n let grid_size = 20;\n let divs = [];\n for (let id in this.windows_) {\n if (this.windows_[id].style.display === \"none\") continue;\n divs.push(this.windows_[id]);\n }\n // Loop through a grid of position until we reach an empty spot.\n for (let y = 0;; y += grid_size) {\n for (let x = this.parent_.offsetLeft; x <= twidth; x += grid_size) {\n let free = true;\n for (let div of divs) {\n const box = div.getBoundingClientRect();\n if (box.top >= margin + y + height) continue;\n if (box.bottom + margin <= y) continue;\n if (box.left >= x + width + margin) continue;\n if (box.right + margin <= x) continue;\n free = false;\n break;\n }\n if (free) return {x: x + margin - this.parent_.offsetLeft, y: y + margin};\n }\n // Increase the speed of the search\n if (y > 100 * grid_size) grid_size += margin;\n }\n }",
"function xocPilotaJugador () {\n\n // TODO: Inicia les següents variables,\n // segons la descripció del seu valor\n let pilotaPartInferior = 0 // És la posició top de la pilota més la seva alçada (15)\n let pilotaMeitatX = 0 // És la posició left del jugador més la meitat del seu ample (7.5)\n let jugadorTop = 0 // És la posició top del jugador, segons el CSS (350)\n let jugadorLimitDreta = 0 // És la posició del cantó dret del jugador, on està més el seu ample (100) \n let rst = false\n\n if (pilotaPartInferior >= jugadorTop &&\n pilotaMeitatX >= jugadorLeft && \n pilotaMeitatX <= jugadorLimitDreta) {\n\n rst = true\n }\n \n return rst\n}",
"function pointIsInCanvas(x, y, w, h) {\n return x >= 0 && x <= w && y >= 0 && y <= h;\n}",
"checkWin() {\nif all bgWLand|| or wgBLand\n}",
"function i2uiKeepMenuInWindow(obj, x, y, id, x2)\r\n{\r\n var ExtraSpace = 10;\r\n\r\n var WindowLeftEdge;\r\n var WindowTopEdge;\r\n var WindowWidth;\r\n var WindowHeight;\r\n if (window.innerWidth != null)\r\n {\r\n WindowWidth = window.innerWidth;\r\n WindowHeight = window.innerHeight;\r\n }\r\n else\r\n {\r\n WindowWidth = document.body.clientWidth;\r\n WindowHeight = document.body.clientHeight;\r\n }\r\n if (window.pageXOffset != null)\r\n {\r\n WindowLeftEdge = window.pageXOffset;\r\n WindowTopEdge = window.pageYOffset;\r\n //i2uitrace(1,\"showmenu pageYOffset=\"+WindowTopEdge);\r\n }\r\n else\r\n {\r\n WindowLeftEdge = document.body.scrollLeft;\r\n WindowTopEdge = document.body.scrollTop;\r\n //i2uitrace(1,\"showmenu scrollTop=\"+WindowTopEdge);\r\n }\r\n\r\n\r\n var MenuLeftEdge = x;\r\n var MenuTopEdge = y;\r\n var MenuRightEdge;\r\n var MenuBottomEdge;\r\n if (document.layers)\r\n {\r\n MenuRightEdge = x + obj.clip.width;\r\n MenuBottomEdge = y + obj.clip.height;\r\n }\r\n else\r\n {\r\n // must change visibility in order to compute width !!\r\n i2uiToggleItemVisibility(id,'show');\r\n\r\n MenuRightEdge = x + obj.offsetWidth;\r\n MenuBottomEdge = y + obj.offsetHeight;\r\n }\r\n\r\n //i2uitrace(1,\"showmenu menu l=\"+x+\" t=\"+y);\r\n if (MenuRightEdge > i2uiExtraHSpace && i2uiExtraHSpace > 10)\r\n ExtraSpace = (WindowLeftEdge + WindowWidth) - i2uiExtraHSpace;\r\n var WindowRightEdge = (WindowLeftEdge + WindowWidth) - ExtraSpace;\r\n if (MenuBottomEdge > i2uiExtraVSpace && i2uiExtraVSpace > 10)\r\n ExtraSpace = (WindowTopEdge + WindowHeight) - i2uiExtraVSpace;\r\n var WindowBottomEdge = (WindowTopEdge + WindowHeight) - ExtraSpace;\r\n\r\n //i2uitrace(1,\"showmenu window l=\"+WindowLeftEdge+\" t=\"+WindowTopEdge);\r\n\r\n var dif;\r\n if (MenuRightEdge > WindowRightEdge)\r\n {\r\n if (x2 == null)\r\n {\r\n dif = MenuRightEdge - WindowRightEdge;\r\n }\r\n else\r\n {\r\n dif = MenuRightEdge - x2;\r\n }\r\n x -= dif;\r\n }\r\n if (MenuBottomEdge > WindowBottomEdge)\r\n {\r\n dif = MenuBottomEdge - WindowBottomEdge;\r\n y -= dif;\r\n }\r\n\r\n if (x < WindowLeftEdge)\r\n {\r\n x = 5;\r\n }\r\n\r\n if (y < WindowTopEdge)\r\n {\r\n y = 5;\r\n }\r\n\r\n if (document.layers)\r\n {\r\n obj.moveTo(x,y);\r\n i2uiToggleItemVisibility(id,'show');\r\n }\r\n else\r\n {\r\n obj.style.left = x;\r\n obj.style.top = y;\r\n }\r\n\r\n //fix 2/6/02 to improve placement of menus near right edge of screen\r\n // reset i2uiMenu_x to position of placed menu\r\n if (x2 == null)\r\n i2uiMenu_x = x;\r\n}",
"function SpotBehind() : int\n{\n\tvar newX = robotX;\n\tvar newY = robotY;\n\tswitch (robotFace)\n\t{\n\t\tcase 0: newX--; break;\n\t\tcase 1: newY++; break;\n\t\tcase 2: newX++; break;\n\t\tcase 3: newY--; break;\n\t}\n\t\n\tif (newX > 9 || newX < 0 || newY > 9 || newY < 0)\n\t\treturn 2;\n\t\n\tfor ( box in boxLocations )\n\t{\n\t\tvar i : Point = box;\n\t\tif (i.X == newX && i.Y == newY)\n\t\t\treturn 3;\n\t}\n\t\n\tif (heightMap[robotX, robotY] < heightMap[newX, newY])\n\t\treturn 1;\n\telse if (heightMap[robotX, robotY] == heightMap[newX, newY])\n\t\treturn 0;\n\telse\n\t\treturn -1;\n}",
"checkVisibility () {\n const vTop = window.pageYOffset\n const vHeight = window.innerHeight\n if (vTop + vHeight < this.box.top ||\n this.box.top + this.canvasHeight < vTop) {\n // viewport doesn't include canvas\n this.visible = false\n } else {\n // viewport includes canvas\n this.visible = true\n }\n }",
"function createProcessingWindow(canvas) {\n\n }",
"function setDialogInPos(posEl){\r\n var size = getSize(posEl);\r\n posEl.style.left = x - (size.width/2);\r\n posEl.style.top = y - (size.height);\r\n posEl.classList.add(\"is-shown\")\r\n }",
"NewFrame(time)\n {\n if(this.WantsSaveIniSettings)\n {\n this.WantsSaveIniSettings = false;\n // XXX: save settings to .prefs file/dir\n window.localStorage.setItem(this.IniFilename, this.imgui.SaveIniSettingsToMemory());\n }\n\n this.DisplaySize.x = this.canvas.scrollWidth;\n this.DisplaySize.y = this.canvas.scrollHeight;\n let cbound = this.canvas.getBoundingClientRect();\n if(cbound && cbound.x != undefined)\n {\n // preferred since it's viewport relative, but seems to\n // fail on older android browsers\n this.DisplayOffset.x = cbound.x;\n this.DisplayOffset.y = cbound.y;\n }\n else\n {\n if(this.DisplayOffset.y != this.canvas.offsetTop)\n {\n console.debug(\"bad bounding client rect \" + JSON.stringify(cbound));\n this.DisplayOffset.x = this.canvas.offsetLeft;\n this.DisplayOffset.y = this.canvas.offsetTop;\n }\n }\n\n const dt = time - this.PrevTime;\n this.PrevTime = time;\n this.DeltaTime = dt / 1000;\n if(this.LazyDraw)\n {\n // this experiment currently fails due to the fact that\n // certain imgui behaviors occur over multiple frames.\n // Popups, textinput are among the biggest fails.\n const ddt = time - this.PrevDirtyTime;\n if(ddt > MinimumFrameInterval) \n {\n this.PrevDirtyTime = time;\n this.Dirty++;\n }\n }\n else\n this.Dirty = true; // checked by app.OnLoop/imgui.NewFrame\n\n if (this.WantSetMousePos)\n console.log(\"TODO: MousePos\", this.MousePos.x, this.MousePos.y);\n\n\n if(this.MouseDrawCursor)\n document.body.style.cursor = \"none\";\n else\n {\n let nc;\n switch(this.imgui.GetMouseCursor())\n {\n case MouseCursor.None:\n nc = \"none\";\n break;\n case MouseCursor.TextInput:\n nc = \"text\";\n break;\n case MouseCursor.ResizeAll:\n nc = \"move\";\n break;\n case MouseCursor.ResizeNS:\n nc = \"ns-resize\";\n break;\n case MouseCursor.ResizeEW:\n nc = \"ew-resize\";\n break;\n case MouseCursor.ResizeNESW:\n nc = \"nesw-resize\";\n break;\n case MouseCursor.ResizeNWSE:\n nc = \"nwse-resize\";\n break;\n case MouseCursor.Hand:\n nc = \"move\";\n break;\n case MouseCursor.Arrow:\n default:\n nc = \"default\";\n break;\n }\n if(document.body.style.cursor != nc)\n {\n // console.log(\"new cursor: \" + nc);\n document.body.style.cursor = nc;\n }\n }\n\n this.updateMouseInputs();\n }",
"function BAWindow() { }",
"function atualizaAreaJogo(){\n let x, y;\n for(i = 0; i < obstaculo.length; i++){\n if(personagemObj.bater(obstaculo[i])){\n areaJogo.parar(); \n return;\n }\n} \n areaJogo.limpar();\n areaJogo.frame += 1;\n if (areaJogo.frame == 1 || contarIntervalo(150)){\n x = areaJogo.canvas.width;\n minAltura = 20;\n maxAltura = 200;\n altura = Math.floor(Math.random()*(maxAltura-minAltura+1)+minAltura);\n minVazio = 50;\n maxVazio = 200;\n vazio = Math.floor(Math.random()*(maxVazio-minVazio+1)+minVazio);\n obstaculo.push(new componente('#1B9913',x,0,altura,10));\n obstaculo.push(new componente('#1B9913',x,altura + vazio, x - altura - vazio,10));\n }\n for (i = 0; i < obstaculo.length; i++){\n obstaculo[i].x += -1;\n obstaculo[i].atualiza();\n }\n pontos.texto = \"Pontos:\" + areaJogo.frame;\n pontos.atualiza();\n personagemObj.novaPosicao();\n personagemObj.atualiza();\n }",
"moving() {\n\n let divId = this.piece.id\n this.totalMoves++\n\n if (this.totalMoves > 1) {\n this.currentTile++\n }\n\n //If the token hasn't made a full round, do not allow it into a color zone\n if (this.currentTile > TILE_BEFORE_ROLLEROVER && this.totalMoves <= COMPLETE_ROUND_TILE_COUNT) {\n this.currentTile = 1\n }\n\n //If token moved 51 places, it can now enter it's colored zone\n if (this.totalMoves == TILE_BEFORE_ROLLEROVER) {\n this.currentTile = this.zoneTile\n }\n\n //If token reaches winning tile, put it in the center box and set win, if not, play normal\n if (this.currentTile == (this.endTile + 1)) {\n let classOfWin = this.piece.classList[0]\n this.piece.classList.add('win')\n $('#'+divId).detach().appendTo($('#'+classOfWin))\n this.inPlay = false\n message.textContent = 'You got a token to the end!'\n checkWin()\n } else {\n $('#'+divId).detach().appendTo($('.box[data-tile-number=\"'+ this.currentTile +'\"]'))\n }\n }",
"function onPlatform(p) \n{\n //On top of platform\n if (yMomentum >= 0 && pressedDown == 0 &&\n diver.y >= p.y-4 - diverChangeY && diver.y <= p.y - diverChangeY &&\n diver.x >= p.x - diverChangeX && diver.x <= p.x + PWidth + diverChangeX)\n {\n diver.y = p.y - diverChangeY;\n return true; \n }\n else\n return false; \n}",
"function out_of_screen(){\r\n ax = airplane_pos.worldMatrix[6];\r\n ay = airplane_pos.worldMatrix[7];\r\n if (ax < -30 || ax > width + 30 || ay < -30 || ay > height + 30) return true;\r\n return false;\r\n}",
"function calculateCoordinates(o)\n{\n if (o.x >= virtual.viewx && o.x < virtual.viewx + width &&\n o.y >= virtual.viewy && o.y < virtual.viewy + height)\n {\n return { x : o.x - virtual.viewx, y : o.y - virtual.viewy }\n }\n \n return null;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for postV3ProjectsIdEnvironments | postV3ProjectsIdEnvironments(incomingOptions, cb) {
const Gitlab = require('./dist');
let defaultClient = Gitlab.ApiClient.instance;
// Configure API key authorization: private_token_header
let private_token_header = defaultClient.authentications['private_token_header'];
private_token_header.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_header.apiKeyPrefix = 'Token';
// Configure API key authorization: private_token_query
let private_token_query = defaultClient.authentications['private_token_query'];
private_token_query.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_query.apiKeyPrefix = 'Token';
let apiInstance = new Gitlab.ProjectsApi()
/*let id = "id_example";*/ // String | The project I
/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE |
apiInstance.postV3ProjectsIdEnvironments(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {
if (error) {
cb(error, null)
} else {
cb(null, data)
}
});
} | [
"putV3ProjectsIdEnvironmentsEnvironmentId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let environmentId = 56;*/ // Number | The environment I\n/*let opts = {\n 'UNKNOWN_BASE_TYPE': new Gitlab.UNKNOWN_BASE_TYPE() // UNKNOWN_BASE_TYPE | \n};*/\napiInstance.putV3ProjectsIdEnvironmentsEnvironmentId(incomingOptions.id, incomingOptions.environmentId, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdVariables(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.postV3ProjectsIdVariables(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 }",
"postV3ProjectsIdDeployKeys(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdDeployKeys(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdTriggers(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a project\napiInstance.postV3ProjectsIdTriggers(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRunners(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.postV3ProjectsIdRunners(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 }",
"postV3ProjectsIdKeys(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdKeys(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 }",
"postV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let tagName = \"tagName_example\";*/ // String | The name of the ta\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions.id, incomingOptions.tagName, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdIssues(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssues(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRepositoryBranches(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryBranches(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRepositoryTags(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryTags(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdPipeline(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdPipeline(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 }",
"postV3ProjectsIdLabels(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdLabels(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdBoardsBoardIdLists(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 boardId = 56;*/ // Number | The ID of a boar\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdBoardsBoardIdLists(incomingOptions.id, incomingOptions.boardId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdMembers(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdMembers(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 }",
"postV3ProjectsIdDeployKeysKeyIdEnable(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the projec\n/*let keyId = 56;*/ // Number | The ID of the deploy key\napiInstance.postV3ProjectsIdDeployKeysKeyIdEnable(incomingOptions.id, incomingOptions.keyId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRefReftriggerBuilds(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let ref = \"ref_example\";*/ // String | The commit sha or name of a branch or ta\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRefReftriggerBuilds(incomingOptions.id, incomingOptions.ref, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdHooks(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.postV3ProjectsIdHooks(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 }",
"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 }",
"postV3ProjectsIdSnippets(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdSnippets(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the board (every cell at 0 empty) | initBoard() {
for (let i = 0; i < this.width*this.height; i++) {
this._board.push(0);
}
} | [
"setupBoard() {\n for (let i = 0; i < this.columns; i++) {\n this.board[i] = [];\n\n for (let j = 0; j < this.rows; j++) {\n // Create new cell object for each location on board\n this.board[i][j] = new Cell(i * this.w, j * this.w, this.w);\n }\n }\n }",
"buildEmptyBoard(dimension) {\n for (let i = 0; i < dimension; i++) {\n this.boardArray.push(new Array(dimension).fill(0));\n }\n }",
"constructor (size) {\n\n var i,j;\n var board = [];\n\n //Initialize each space to 0\n for (i=0; i<size; i++) {\n\n var row = [];\n\n for (j=0; j<size; j++) {\n row.push(0);\n }\n\n board.push(row);\n }\n\n this.board = board;\n this.size = size;\n\n }",
"function initBoardArray()\n{\n for(var x = 0; x < boardArraySize; x++){\n boardTiles[x] = [];\n boardTileUsed[x] = [];\n }\n\n boardWidth = -1;\n boardHeight = -1;\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 fillBoard() {\n for (var i = 0; i < 8; i++) {\n game.board[i] = fillRow(i);\n };\n}",
"function setUpBoard(){\n var board = [];\n \n // iterate over each row index\n for (var i = 0; i < 8; i++)\n {\n // create array for each new row\n var newRow = [];\n // iterate over each column index\n for (var x = 0; x < 8; x++)\n {\n // if first three rows\n if (i < 3)\n {\n // every other cell, alternating diagonally\n if ((x + i % 2) % 2 == 0)\n {\n // add value 1 to new row\n newRow.push(1);\n }\n // should be empty\n else\n {\n // add value 0 to new row\n newRow.push(0);\n }\n }\n // if after first five rows (skip 2 rows)\n else if (i > 4)\n {\n // every other cell, alternating diagonally\n if ((x + i % 2) % 2 == 0)\n {\n // add value 3 to new row\n newRow.push(3);\n }\n // should be empty\n else\n {\n // add value 0 to new row\n newRow.push(0);\n }\n }\n // 2 empty rows in middle\n else\n {\n // add value 0 to new row\n newRow.push(0);\n }\n }\n // add new row to the board\n board.push(newRow);\n }\n // return the board\n return board;\n}",
"randomInitTile() {\n let randX = this.getRandomInt()\n let randY = this.getRandomInt()\n while (this.isOccupied(randX, randY)) {\n randX = this.getRandomInt();\n randY = this.getRandomInt();\n }\n this.board[randY][randX] = 2;\n this.append(randX, randY);\n }",
"function resetBoard() {\r\n gameboard.forEach(function(space, index) { \r\n this[index] = null; \r\n }, gameboard)\r\n _render()\r\n }",
"function initCellArray() {\n var gridSize = getGridSize();\n cellArray = []\n for(var i = 0; i < gridSize; i++) {\n var gridRow = []\n for(var j = 0; j < gridSize; j++) {\n gridRow.push({\"free\": true, \"letter\": \"\"})\n }\n cellArray.push(gridRow)\n }\n }",
"init() {\n const squaresCopy = this.board.squares.slice(0);\n this.board.placePlayers(this.players, squaresCopy);\n this.board.placeWeapons(this.weapons, squaresCopy);\n this.board.placeWalls(this.nbOfWalls, squaresCopy);\n }",
"function resetGrids() {\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n grid[i][j] = 0;\n nextGrid[i][j] = 0;\n }\n }\n}",
"initBoard() {\n\n // Create the chess board.\n SHTML.Divs(8, function(index, div) {\n div.classList.add(\"chess-board-row\");\n\n // Create 8 tiles in that row.\n SHTML.Divs(8, function(letterIndex, currDiv, numberIndex) {\n currDiv.classList.add(\"chess-board-tile\");\n currDiv.id = String.fromCharCode(97 + letterIndex) + (8 - numberIndex).toString();\n }, index).forEach(tile => div.appendChild(tile));\n\n }).forEach(row => this.board.appendChild(row));\n\n var pieceCount = 0;\n this.chess.SQUARES.forEach(tileId => {\n var currentPiece = this.chess.get(tileId);\n if (currentPiece !== null) {\n var pieceDiv = document.createElement(\"div\");\n pieceDiv.classList.add(\"chess-piece\");\n pieceDiv.setAttribute(\"position\", tileId);\n pieceDiv.classList.add(ChessUtils.fenToCSSPiece(currentPiece.color, currentPiece.type));\n pieceDiv.style.transform = this.getTransformCSS(tileId);\n pieceDiv.id = `piece-${pieceCount}`;\n pieceDiv.onmousedown = function (event) {\n dragStart(event, pieceDiv);\n }\n pieceCount++;\n this.board.appendChild(pieceDiv);\n }\n })\n }",
"function initializeColorGrid() {\n var i, j;\n colorGrid = new Array(width/BLOCK_SIZE);\n for (i = 0; i < width/BLOCK_SIZE; i++) {\n colorGrid[i] = new Array(height/BLOCK_SIZE);\n for (j = 0; j < height/BLOCK_SIZE; j++) {\n colorGrid[i][j] = 'white';\n }\n }\n }",
"function buildBoard() {\r\n randomMinePos()\r\n var board = [];\r\n for (var i = 0; i < gLevels[gChosenLevelIdx].SIZE; i++) {\r\n board[i] = [];\r\n for (var j = 0; j < gLevels[gChosenLevelIdx].SIZE; j++) {\r\n board[i][j] = createCell(i, j);\r\n\r\n }\r\n }\r\n setMinesNegsCount(board)\r\n return board;\r\n}",
"function initGameBoard() {\n document.querySelector('.title').remove();\n\n document.getElementById('startBtn').remove();\n\n var board = document.querySelector('.gameboard');\n board.setAttribute(\"id\", \"liveBoard\");\n\n console.log(\"game board has been initialized\");\n // This for loop creates 20 rows in the gameboard\n for (i = 0; i < 20; i++) {\n var boardRow = document.createElement(\"div\");\n boardRow.setAttribute(\"class\", \"row boardRow\");\n boardRow.setAttribute(\"id\", \"row\" + i);\n\n\n document.getElementById(\"liveBoard\").appendChild(boardRow);\n boardStatus.push([]);\n\n // This for loop creates 10 cells in each row\n for (j = 0; j < 10; j++) {\n var rowCell = document.createElement(\"div\");\n rowCell.setAttribute(\"class\", \"col-sm\")\n rowCell.setAttribute(\"id\", \"cell\" + i + \"-\" + j);\n\n document.getElementById(\"row\" + i).appendChild(rowCell)\n boardStatus[i].push(0);\n }\n }\n\n var scoreBoard = document.createElement(\"div\");\n scoreBoard.setAttribute(\"class\", \"scoreBoard\");\n document.body.appendChild(scoreBoard);\n document.querySelector('.scoreBoard').innerHTML = '<p class=\"scoreLabel\"> SCORE </p>';\n\n var scoreDisp = document.createElement(\"div\");\n scoreDisp.setAttribute(\"class\", \"score\")\n document.querySelector('.scoreBoard').appendChild(scoreDisp)\n document.querySelector('.score').innerHTML = '0';\n\n}",
"function makeZero() {\n\t\tvar m = arguments[0];\n\t\tvar rows = m.length;\n\t\tvar cols = m[0].length;\n\t\tfor(var r = 0; r < rows; r++) {\n\t\t\tfor(var c = 0; c < cols; c++) {\n\t\t\t\tm[r][c] = 0;\n\t\t\t}\n\t\t}\n\t}",
"function InitBoardVars()\n{\n\t//Initializing history table\n\tfor(let i = 0; i < MAXGAMEMOVES; i++) \n\t{\n\t\tGameBoard.history.push\n\t\t({\n\t\t\tmove: NOMOVE,\n\t\t\tcastlePerm: 0,\n\t\t\tenPas: 0,\n\t\t\tfiftyMove: 0,\n\t\t\tposKey: 0\n\t\t});\n\t}\t\n\t//Initializing Pv Table\n\tfor (let i = 0; i < PVENTRIES; i++)\n\t{\n\t\tGameBoard.PvTable.push\n\t\t({\n\t\t\tmove: NOMOVE,\n\t\t\tposKey: 0\n\t\t});\n\t}\n}",
"function resetBoard() {\n $tileArray.each(function (i, value) {\n var removeGreen = $($tileArray[i]).removeClass(\"green\");\n turnCounter = 0;\n greenTileCount = 0;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The props that `useSpring` recognizes. | function useSpring(props, deps) {
const isFn = _react_spring_shared__WEBPACK_IMPORTED_MODULE_1__["is"].fun(props);
const [[values], update, stop] = useSprings(1, isFn ? props : [props], isFn ? deps || [] : deps);
return isFn || arguments.length == 2 ? [values, update, stop] : values;
} | [
"triggerPropUpdate(newProps) {\n this.getAllSprings().forEach((spring) => {\n if (spring && spring.updateSpringsForProps) spring.updateSpringsForProps(newProps);\n });\n }",
"async getConfigProperties() {\n return super.get_auth(`/config`);\n }",
"static get QUERY_PARAMS_PROPS() {\n return Constants.QUERY_PARAMS_PROPS;\n }",
"_buildPropertyProps(properties = {}) {\n const props = {};\n for (const propertyName in properties) {\n const property = properties[propertyName];\n const propData = NOTION_PAGE_PROPERTIES[property.type];\n\n if (!propData) continue;\n\n props[propertyName] = {\n type: propData.type,\n label: propertyName,\n description: this._buildPropDescription(property.type, propData.example),\n options: propData.options(property),\n optional: true,\n };\n }\n return props;\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 }",
"getWindowProps() {\n return this.getLoadSettings().windowProps || {};\n }",
"_measure() {\n const props = {};\n const bounds = this.element.getBoundingClientRect();\n const computedStyle = getComputedStyle(this.element);\n this.options.properties.forEach((p) => {\n var _a;\n const v = (_a = bounds[p]) !== null && _a !== void 0 ? _a : (!transformProps[p]\n ? computedStyle[p]\n : undefined);\n const asNum = Number(v);\n props[p] = isNaN(asNum) ? String(v) : asNum;\n });\n return props;\n }",
"getProps(){\n let properties = new ValueMap();\n let propWalker = this;\n\n while(propWalker.__type<0x10){\n for(let [k,v] of propWalker.__props){\n properties.set(k,v);\n }\n propWalker = propWalker.getProp(\"__proto__\");\n };\n return properties;\n }",
"function filterDefaultProps(props, defaultProps) {\n let [, resultProps] = (0, _tools.extractInObject)(defaultProps, Object.keys(props));\n return resultProps;\n}",
"cssVariables() {\n const elementStyle = getComputedStyle(this)\n \n this._positionColor = elementStyle.getPropertyValue('--position-color')\n this._positionLineWidth = elementStyle.getPropertyValue('--position-line-width')\n this._positionRadius = elementStyle.getPropertyValue('--position-radius')\n \n this._gridSections = elementStyle.getPropertyValue('--grid-sections')\n this._gridColor = elementStyle.getPropertyValue('--grid-color')\n this._gridLineWidth = elementStyle.getPropertyValue('--grid-line-width')\n }",
"function filterDefaultProps(props, defaultProps) {\n let [, resultProps] = extractInObject(defaultProps, Object.keys(props));\n return resultProps;\n}",
"function Configuration(props) {\n return __assign({ Type: 'AWS::AmazonMQ::Configuration' }, props);\n }",
"prop(prop) {\n return !prop.perNode\n ? this.type.prop(prop)\n : this.props\n ? this.props[prop.id]\n : undefined\n }",
"function extractProps(props, theme, colorModeProps, componentTheme, currentBreakpoint) {\n let newProps = {};\n\n for (let property in props) {\n // If the property exists in theme map then get its value\n if (themePropertyMap[property]) {\n let propValues = extractPropertyFromFunction(property, props, theme, componentTheme);\n\n if (typeof propValues === 'string' || typeof propValues === 'number') {\n newProps[property] = propValues;\n } else if (!isNil(propValues)) {\n for (let nestedProp in propValues) {\n newProps[nestedProp] = get(theme, \"\".concat(themePropertyMap[nestedProp], \".\").concat(propValues[nestedProp]), propValues[nestedProp]);\n }\n } else if (property === 'shadow') {\n let shadowProps = theme[themePropertyMap[property]](colorModeProps)[props[property]];\n\n if (!isNil(shadowProps)) {\n newProps = { ...newProps,\n ...shadowProps\n };\n }\n } else {\n newProps[property] = resolveValueWithBreakpoint(props[property], currentBreakpoint, property);\n }\n } else {\n newProps[property] = resolveValueWithBreakpoint(props[property], currentBreakpoint, property);\n }\n }\n\n return cloneDeep(newProps);\n}",
"get documentPadding() {\n return {\n top: this.viewState.paddingTop,\n bottom: this.viewState.paddingBottom\n }\n }",
"componentDidMount() {\n //You cant access props before the component is mounted, so we can t call this from within the constructor.\n this.getPlacementConfiguration();\n }",
"function useCssVars(getter) {\n if (!inBrowser && !false)\n return;\n var instance = currentInstance;\n if (!instance) {\n warn$2(\"useCssVars is called without current active component instance.\");\n return;\n }\n watchPostEffect(function () {\n var el = instance.$el;\n var vars = getter(instance, instance._setupProxy);\n if (el && el.nodeType === 1) {\n var style = el.style;\n for (var key in vars) {\n style.setProperty(\"--\".concat(key), vars[key]);\n }\n }\n });\n }",
"function propertyDetails (name) {\n return {\n getter: '_get_' + name,\n setter: '_set_' + name,\n processor: '_process_' + name,\n validator: '_validate_' + name,\n defaultValue: '_default_value_' + name,\n value: '_' + name\n };\n }",
"function fruitProperties(fruitName) {\r\n if (typeof fruitName !== 'object' || fruitName === undefined) {\r\n console.error('Your fruit has not been declared');\r\n } else if (fruitName.hasOwnProperty('color') &&\r\n fruitName.hasOwnProperty('shape') &&\r\n fruitName.hasOwnProperty('price')) {\r\n console.log('color: ' + fruitName.color);\r\n console.log('shape: ' + fruitName.shape);\r\n console.log('price: ' + fruitName.price);\r\n } else {\r\n console.log('Your fruit does not have all properties');\r\n }\r\n}",
"function ConfigurationAggregator(props) {\n return __assign({ Type: 'AWS::Config::ConfigurationAggregator' }, props);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TURN GRAY SCALE ON ALL MELEE HEROES | function meleeGrayScaleON(){
var meleeHero = document.getElementsByClassName("melee");
for (var i = 0; i < meleeHero.length; i++) {
meleeHero[i].style.filter = "grayscale(100%)";
}
} | [
"function rangedGrayScaleON(){\n var rangedHero = document.getElementsByClassName(\"ranged\");\n for (var i = 0; i < rangedHero.length; i++) {\n rangedHero[i].style.filter = \"grayscale(100%)\";\n }\n}",
"function meleeGrayScaleOFF(){\n var meleeHero = document.getElementsByClassName(\"melee\");\n for (var i = 0; i < meleeHero.length; i++) {\n meleeHero[i].style.filter = \"grayscale(0%)\";\n }\n}",
"function rangedGrayScaleOFF(){\n var rangedHero = document.getElementsByClassName(\"ranged\");\n for (var i = 0; i < rangedHero.length; i++) {\n rangedHero[i].style.filter = \"grayscale(0%)\";\n }\n}",
"function reduceBg(){\r\n if(bgOpacity < 0.2){\r\n randomBgColor();\r\n bgOpacity = 0.9;\r\n //gather_particles(stage.numChildren);\r\n }\r\n document.getElementById(\"two\").style.opacity = bgOpacity;\r\n bgOpacity = bgOpacity - 0.003;\r\n\r\n\r\n}",
"function redHue() {\n for (var pixel of image.values()) {\n var avg =\n (pixel.getRed() + pixel.getGreen() + pixel.getBlue()) /3;\n if (avg < 128){\n pixel.setRed(2 * avg);\n pixel.setGreen(0);\n pixel.setBlue(0);\n } else {\n pixel.setRed(255);\n pixel.setGreen(2 * avg - 255);\n pixel.setBlue(2 * avg - 255);\n }\n }\n var c2 = document.getElementById(\"c2\");\n var image2 = image;\n image2.drawTo(c2);\n \n \n}",
"blendSide(data, left) {\n let _sideLength = data.data.length\n let _sourceX = left ? 0 : this._imageWidth - BLEND\n let _sourceHeight = this._imageHeight + this._offset\n //let _sourceData = this._ctx.getImageData(0, 0, this._imageWidth, this._imageHeight + this._offset)\n let _sourceData = this._ctx.getImageData(_sourceX, 0, BLEND, _sourceHeight)\n\n let _total = 4 * _sourceHeight * BLEND\n //let _total = 4 * this._imageWidth * BLEND\n let pixels = _total;\n let _weight = 0\n let _wT = BLEND\n /*while (pixels--) {\n _sourceData.data[pixels] = Math.floor(Math.random() * 255) // _currentPixelR + _newPixelR\n //_sourceData.data[_p + 1] = 0 // _currentPixelG + _newPixelG\n //_sourceData.data[_p + 2] = 0 //_currentPixelB + _newPixelB\n //_sourceData.data[_p + 3] = 255 //_currentPixelA + _newPixelA\n }\n this._ctx.putImageData(_sourceData, 0, 0)\n return*/\n\n let i = left ? 0 : _total\n i = 0\n let l = left ? _total : 0\n l = _total\n let _a = left ? 4 : -4\n _a = 4\n for (i; i < l; i += _a) {\n let _weight = 1.\n let _roll = i % _sideLength\n _weight = i % (BLEND * 4) / (BLEND * 4)\n\n if (!left) {\n _weight = 1 - _weight\n //_weight = 0\n }\n\n let _newPixelR = Math.floor(data.data[_roll] * (1 - _weight))\n let _newPixelG = Math.floor(data.data[_roll + 1] * (1 - _weight))\n let _newPixelB = Math.floor(data.data[_roll + 2] * (1 - _weight))\n let _newPixelA = Math.floor(data.data[_roll + 3])\n\n let _currentPixelR = Math.floor(_sourceData.data[i] * _weight)\n let _currentPixelG = Math.floor(_sourceData.data[i + 1] * _weight)\n let _currentPixelB = Math.floor(_sourceData.data[i + 2] * _weight)\n let _currentPixelA = Math.floor(_sourceData.data[i + 3])\n\n _sourceData.data[i] = _newPixelR + _currentPixelR\n _sourceData.data[i + 1] = _newPixelG + _currentPixelG\n _sourceData.data[i + 2] = _newPixelB + _currentPixelB\n _sourceData.data[i + 3] = 255\n }\n /*console.log(_total, _sourceData.data.length);\n for (let i = 0; i < _wT * 4; i += 3) {\n _weight = i / _wT\n for (let j = 0; j < _sourceHeight * 4; j += 4) {\n let _p = i * j\n let _newPixelR = Math.floor(data.data[_p] * (_weight))\n let _newPixelG = Math.floor(data.data[_p + 1] * (_weight))\n let _newPixelB = Math.floor(data.data[_p + 2] * (_weight))\n let _newPixelA = Math.floor(data.data[_p + 3] * (_weight))\n\n let _currentPixelR = Math.floor(_sourceData.data[_p] * (1 - _weight))\n let _currentPixelG = Math.floor(_sourceData.data[_p + 1] * (1 - _weight))\n let _currentPixelB = Math.floor(_sourceData.data[_p + 2] * (1 - _weight))\n let _currentPixelA = Math.floor(_sourceData.data[_p + 3] * (1 - _weight))\n\n\n _sourceData.data[_p] = 255 // _currentPixelR + _newPixelR\n _sourceData.data[_p + 1] = 0 // _currentPixelG + _newPixelG\n _sourceData.data[_p + 2] = 0 //_currentPixelB + _newPixelB\n _sourceData.data[_p + 3] = 255 //_currentPixelA + _newPixelA\n }\n }*/\n this._ctx.putImageData(_sourceData, _sourceX, 0)\n }",
"function colour_scale(x) {\r\n return \"rgb(0,0,\"+((x-min_colour)/(max_colour-min_colour)*256).toString() +\")\"\r\n }",
"ColorUpdate(colors) {\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(127, 127, 127, 255));\n colors.push(vec4(10, 10, 10, 210));\n colors.push(vec4(127, 127, 127, 255));\n\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n \n if (Sky.instance.GlobalTime >= 9 && Sky.instance.GlobalTime < 19){\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 255));\n // StreetLamp Light turn off\n // ColorUpdate => Black\n }\n else {\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 255));\n // StreetLamp Light turn on\n // ColorUpdate => Yell Light\n }\n }",
"function bgSway() {\n var bg = $('#bg');\n TweenMax.to(bg, 12, {x:64, ease:Sine.easeInOut});\n TweenMax.to(bg, 12, {x:-64, ease:Sine.easeInOut, delay: 12, onComplete:bgSway});\n}",
"joinParticlesBg(paraticlesBg) {\r\n particlesBg.forEach(element =>{\r\n let dis = dist(this.x,this.y,element.x,element.y);\r\n if(dis<85) {\r\n var a = random(0,255);\r\n var b = random(0,255);\r\n var c = random(0,255);\r\n stroke(a,b,c);\r\n line(this.x,this.y,element.x,element.y);\r\n }\r\n });\r\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 preColorTwinkles(z,a,delta) {\n SetVar(z,0,time(0.8 * a[__speed]) * PI2);\n SetVar(z,1,time(0.4 * a[__speed]) * PI2);\n}",
"changeImage() {\n if (this.imageCounter < this.bgArray.length - 1) {\n this.imageCounter++;\n } else {\n this.imageCounter = 0;\n }\n\n this.bgSpriteArray.map((sprite, i) => {\n if (i == this.imageCounter) {\n TweenLite.to(sprite, 1, { alpha: 1, ease: Power2.easeInOut });\n } else {\n TweenLite.to(sprite, 1, { alpha: 0, ease: Power2.easeInOut });\n }\n });\n }",
"function blankAndWhite(){\n if(fgImg==null){\n alert(\"Image not loaded\");\n }else{\n for(var pixel of greyImg.values()){\n var avg = (pixel.getRed()+pixel.getBlue()+pixel.getGreen())/3;\n pixel.setRed(avg);\n pixel.setBlue(avg);\n pixel.setGreen(avg);\n }\n greyImg.drawTo(canvas);\n }\n}",
"function max(){return colorScale.domain()[2];}",
"function setupNewColorsMeshs() {\n cubeMeshs.forEach(object => {\n object.children[0].children[0].material[1].color = colorScene;\n object.children[0].children[0].material[1].emissive = colorScene;\n });\n\n torusMesh.forEach(object => {\n switch (countTic > 2) {\n case true:\n object.children[0].material[1].emissive = new THREE.Color(0xffffff);\n object.children[0].material[1].color = new THREE.Color(0xffffff);\n object.children[0].material[4].emissive = colorScene;\n object.children[0].material[4].color = colorScene;\n break;\n case false:\n object.children[0].material[1].emissive = colorScene;\n object.children[0].material[1].color = colorScene;\n object.children[0].material[4].emissive = new THREE.Color(0xffffff);\n object.children[0].material[4].color = new THREE.Color(0xffffff);\n break;\n }\n });\n}",
"function makeNoFaceMouth(){\n var halfSmile = makeNoFaceMask(0x000000);\n halfSmile.scale.set(0.2,0.045,0.075);\n return halfSmile;\n}",
"function colorAlgorithm(){\n\tvar temp = new Array();\n\t\n\tvar tag2 = document.getElementById('gloss').value;\n\tglossiness = tag2;\n\t\n\tvar lightVector = new Vector3([500, 500, 500]);\n\tlightVector.normalize();\n\tvar lightVector2 = new Vector3([0,500,0]);\n\tlightVector2.normalize();\n\t\tfor (var j = 3; j < normies.length; j+=6){\n\t\t\tvar nVector = new Vector3([normies[j],normies[j+1],normies[j+2]]);\n\t\t\tnVector.normalize();\n\t\t\tvar reflect = calcR(nVector,lightVector); //two times dot times normal minus lightdirection\n\t\t\tvar dot = (\n\t\t\t\tnormies[j] * lightVector.elements[0] +\n\t\t\t\tnormies[j+1] * lightVector.elements[1] +\n\t\t\t\tnormies[j+2] * lightVector.elements[2]\n\t\t\t\t);\n\t\t\t\tdot = dot/256; //////color hack\n\n\t\t\tif (pointLight&&lightDir.checked){\t\t\t\t\n\t\t\t\tvar L = new Vector3([\n\t\t\t\t\tlightVector2.elements[0] - normies[j],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+1],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+2]\n\t\t\t\t]);\n\t\t\t\tvar dot2 = (\n\t\t\t\t\tnormies[j] * lightVector2.elements[0] +\n\t\t\t\t\tnormies[j+1] * lightVector2.elements[1] +\n\t\t\t\t\tnormies[j+2] * lightVector2.elements[2]\n\t\t\t\t\t);\n\t\t\t\t\n\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1*dot2) + (1*dot) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + (0*dot) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + (0*dot) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1*dot2) + (1*dot) + Ia.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + (0*dot) + Ia.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + (0*dot) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\t\n\t\t\t\t}\t\t\n\t\t\t} else if (pointLight&&!lightDir.checked){\n\t\t\t\t\n\t\t\t\tvar L = new Vector3([\n\t\t\t\t\tlightVector2.elements[0] - normies[j],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+1],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+2]\n\t\t\t\t]);\n\t\t\t\tvar dot2 = (\n\t\t\t\t\tnormies[j] * lightVector2.elements[0] +\n\t\t\t\t\tnormies[j+1] * lightVector2.elements[1] +\n\t\t\t\t\tnormies[j+2] * lightVector2.elements[2]\n\t\t\t\t\t);\n\t\t\t\t\n\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1*dot2) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1*dot2) + Ia.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + Ia.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\t\n\t\t\t\t}\n\t\t\t} else if (lightDir.checked){\n\t\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1 * dot) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0 * dot) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0 * dot) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1 * dot) + Ia.elements[0];\n\t\t\t\t\tvar g = (0 * dot) + Ia.elements[1];\n\t\t\t\t\tvar b = (0 * dot) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse for (var k = 0; k < 20; k++) temp.push(0.5,0.5,0.5);\n\t\t}\n\t return temp;\n}",
"function greenColor(){\n if(fgImg==null){\n alert(\"Image not loaded\");\n }else{\n for(var pixel of greenImg.values()){\n var avg = (pixel.getRed()+pixel.getBlue()+pixel.getGreen())/3;\n if(avg<128){\n pixel.setRed(0);\n pixel.setGreen(2*avg);\n pixel.setBlue(0);\n }else{\n pixel.setRed(2*avg-255);\n pixel.setBlue(2*avg-255);\n pixel.setGreen(255);\n }\n }\n greenImg.drawTo(canvas);\n}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subtest for test_can_display_providers_in_other_languages. This function simply clicks on the div for displaying account providers in other languages, and ensures that those other providers become visible. | function subtest_can_display_providers_in_other_languages(w) {
wait_for_provider_list_loaded(w);
// Check that the "Other languages" div is hidden
wait_for_element_visible(w, "otherLangDesc");
let otherLanguages = w.window.document.querySelectorAll(".otherLanguage");
for (let element of otherLanguages) {
assert_element_visible(new elib.Elem(element));
}
// Click on the "Other languages" div
mc.click(w.eid("otherLangDesc"));
wait_for_element_invisible(w, "otherLangDesc");
} | [
"function subtest_other_lang_link_hides(w) {\n wait_for_provider_list_loaded(w);\n wait_for_element_invisible(w, \"otherLangDesc\");\n}",
"function subtest_show_tos_privacy_links_for_selected_providers(w) {\n wait_for_provider_list_loaded(w);\n\n // We should be showing the TOS and Privacy links for the selected\n // providers immediately after the providers have been loaded.\n // Those providers should be \"foo\" and \"bar\".\n assert_links_shown(w, [\n \"http://www.example.com/foo-tos\",\n \"http://www.example.com/foo-privacy\",\n \"http://www.example.com/bar-tos\",\n \"http://www.example.com/bar-privacy\",\n ]);\n\n assert_links_not_shown(w, [\n \"http://www.example.com/French-tos\",\n \"http://www.example.com/French-privacy\",\n ]);\n\n // Now click off one of those providers - we shouldn't be displaying\n // and links for that one now.\n let input = w.window.document.querySelector(\n 'input[type=\"checkbox\"][value=\"foo\"]'\n );\n w.click(new elib.Elem(input));\n\n assert_links_not_shown(w, [\n \"http://www.example.com/foo-tos\",\n \"http://www.example.com/foo-privacy\",\n ]);\n\n // Ensure that the \"Other languages\" div is visible\n wait_for_element_visible(w, \"otherLangDesc\");\n // Now show the providers from different locales...\n w.click(w.eid(\"otherLangDesc\"));\n wait_for_element_invisible(w, \"otherLangDesc\");\n\n // And click on one of those providers...\n input = w.window.document.querySelector(\n 'input[type=\"checkbox\"][value=\"French\"]'\n );\n w.click(new elib.Elem(input));\n // We should be showing the French TOS / Privacy links, along\n // with those from the bar provider.\n assert_links_shown(w, [\n \"http://www.example.com/French-tos\",\n \"http://www.example.com/French-privacy\",\n \"http://www.example.com/bar-tos\",\n \"http://www.example.com/bar-privacy\",\n ]);\n\n // The foo provider should still have it's links hidden.\n assert_links_not_shown(w, [\n \"http://www.example.com/foo-tos\",\n \"http://www.example.com/foo-privacy\",\n ]);\n\n // Click on the German provider. It's links should now be\n // shown, along with the French and bar providers.\n input = w.window.document.querySelector(\n 'input[type=\"checkbox\"][value=\"German\"]'\n );\n w.click(new elib.Elem(input));\n assert_links_shown(w, [\n \"http://www.example.com/French-tos\",\n \"http://www.example.com/French-privacy\",\n \"http://www.example.com/bar-tos\",\n \"http://www.example.com/bar-privacy\",\n \"http://www.example.com/German-tos\",\n \"http://www.example.com/German-privacy\",\n ]);\n\n // And the foo links should still be hidden.\n assert_links_not_shown(w, [\n \"http://www.example.com/foo-tos\",\n \"http://www.example.com/foo-privacy\",\n ]);\n}",
"function subtest_provider_language_wildcard(aController) {\n wait_for_provider_list_loaded(aController);\n // Check that the two universal providers are visible.\n wait_for_element_visible(aController, \"universal-check\");\n wait_for_element_visible(aController, \"otherUniversal-check\");\n // The French and German providers should not be visible.\n wait_for_element_invisible(aController, \"french-check\");\n wait_for_element_invisible(aController, \"german-check\");\n close_dialog_immediately(aController);\n}",
"function subtest_incomplete_provider_not_displayed(w) {\n wait_for_provider_list_loaded(w);\n // Make sure that the provider that didn't include the required fields\n // is not displayed.\n let input = w.window.document.querySelectorAll(\n 'input[type=\"checkbox\"][value=\"corrupt\"]'\n );\n Assert.equal(\n 0,\n input.length,\n \"The Corrupt provider should not have been displayed\"\n );\n\n // And check to ensure that at least one other provider is displayed\n input = w.window.document.querySelectorAll(\n 'input[type=\"checkbox\"][value=\"foo\"]'\n );\n Assert.equal(1, input.length, \"The foo provider should have been displayed\");\n}",
"function subtest_search_button_disabled_cases(w) {\n wait_for_provider_list_loaded(w);\n let searchInput = w.eid(\"name\");\n // Case 1: Search input empty, some providers selected.\n\n // Empty any strings in the search input. Select all of the input with\n // Ctrl-A, and then hit backspace.\n searchInput.getNode().focus();\n w.keypress(null, \"a\", { accelKey: true });\n w.keypress(null, \"VK_BACK_SPACE\", {});\n\n // Make sure at least one provider is checked\n let input = w.window.document.querySelector('input[type=\"checkbox\"]:checked');\n w.click(new elib.Elem(input));\n input = w.window.document.querySelector(\n 'input[type=\"checkbox\"][value=\"foo\"]'\n );\n w.click(new elib.Elem(input));\n\n // The search submit button should become disabled\n wait_for_element_enabled(w, w.e(\"searchSubmit\"), false);\n\n // Case 2: Search input has text, some providers selected\n\n // Put something into the search input\n type_in_search_name(w, \"Dexter Morgan\");\n\n // We already have at least one provider checked from the last case, so\n // the search submit button should become enabled\n wait_for_element_enabled(w, w.e(\"searchSubmit\"), true);\n\n // Case 3: Search input has text, no providers selected\n // Make sure no provider checkboxes are checked.\n let inputs = w.window.document.querySelectorAll(\n 'input[type=\"checkbox\"]:checked'\n );\n for (input of inputs) {\n mc.click(new elib.Elem(input));\n }\n\n // The search submit button should now be disabled\n wait_for_element_enabled(w, w.e(\"searchSubmit\"), false);\n\n // We'll turn on a single provider now to enable the search button,\n // so we can ensure that it actually *becomes* disabled for the next\n // case.\n input = w.window.document.querySelector(\n 'input[type=\"checkbox\"][value=\"foo\"]'\n );\n w.click(new elib.Elem(input));\n wait_for_element_enabled(w, w.e(\"searchSubmit\"), true);\n\n // Case 4: Search input has no text, and no providers are\n // selected.\n\n // Clear out the search input\n w.keypress(null, \"a\", { accelKey: true });\n w.keypress(null, \"VK_BACK_SPACE\", {});\n input = w.window.document.querySelector('input[type=\"checkbox\"]:checked');\n w.click(new elib.Elem(input));\n\n wait_for_element_enabled(w, w.e(\"searchSubmit\"), false);\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 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 subtest_search_button_enabled_state_on_init(aController) {\n wait_for_provider_list_loaded(aController);\n\n let enabled = !!aController.e(\"name\").value;\n\n // The search button should be disabled if there's not search input.\n wait_for_element_enabled(aController, aController.e(\"searchSubmit\"), enabled);\n\n close_dialog_immediately(aController);\n}",
"_showAccountCentral() {\n if (!this.displayedFolder && MailServices.accounts.accounts.length > 0) {\n // If we have any accounts set up, but no folder is selected yet,\n // we expect another selection event to come when session restore finishes.\n // Until then, do nothing.\n return;\n }\n document.getElementById(\"accountCentralBox\").collapsed = false;\n document.getElementById(\"threadPaneBox\").collapsed = true;\n\n // Prevent a second load if necessary.\n let loadURL =\n \"chrome://messenger/content/msgAccountCentral.xhtml\" +\n (this.displayedFolder\n ? \"?folderURI=\" + encodeURIComponent(this.displayedFolder.URI)\n : \"\");\n if (window.frames.accountCentralPane.location.href != loadURL) {\n window.frames.accountCentralPane.location.href = loadURL;\n }\n }",
"clickSellOnTakealot() {\n return this\n .waitForElementVisible('@sellOnTakealot')\n .assert.visible('@sellOnTakealot')\n .click('@sellOnTakealot');\n }",
"function subtest_flip_flop_from_provisioner_menuitem(w) {\n // We need to wait for the wizard to be closed, or else\n // it'll try to refocus when we click on the button to\n // open it.\n wait_for_the_wizard_to_be_closed(w);\n plan_for_window_close(w);\n mc.click(new elib.Elem(w.window.document.querySelector(\".existing\")));\n wait_for_window_close();\n}",
"function showCorrectLogonPage() {\n if(initializeRewards.urlContainsFlowID()){\n changePageFn('#urlogon');\n } else if (isCustomerUsingToken(ccoTokenKey)) {\n changePageFn('#cco');\n }else if (isCustomerUsingToken(bbTokenKey)) {\n changePageFn('#bb');\n }\n }",
"function test_get_an_account(aCloseAndRestore) {\n let originalEngine = Services.search.defaultEngine;\n // Open the provisioner - once opened, let subtest_get_an_account run.\n plan_for_modal_dialog(\"AccountCreation\", subtest_get_an_account);\n open_provisioner_window();\n wait_for_modal_dialog(\"AccountCreation\");\n\n // Once we're here, subtest_get_an_account has completed, and we're waiting\n // for a content tab to load for the account order form.\n\n // Make sure the page is loaded.\n wait_for_content_tab_load(undefined, function(aURL) {\n return aURL.host == \"mochi.test\";\n });\n\n let tab = mc.tabmail.currentTabInfo;\n\n if (aCloseAndRestore) {\n // Close the account provisioner tab, and then restore it...\n mc.tabmail.closeTab(mc.tabmail.currentTabInfo);\n mc.tabmail.undoCloseTab();\n // Wait for the page to be loaded again...\n wait_for_content_tab_load(undefined, function(aURL) {\n return aURL.host == \"mochi.test\";\n });\n tab = mc.tabmail.currentTabInfo;\n }\n\n // Record how many accounts we start with.\n gNumAccounts = nAccounts();\n\n // Plan for the account provisioner window to re-open, and then run the\n // controller through subtest_get_an_account_part_2. Since the Account\n // Provisioner dialog is non-modal in the event of success, we use our\n // normal window handlers.\n plan_for_new_window(\"AccountCreation\");\n\n // Click the OK button to order the account.\n let btn = tab.browser.contentWindow.document.querySelector(\n \"input[value=Send]\"\n );\n mc.click(new elib.Elem(btn));\n\n let ac = wait_for_new_window(\"AccountCreation\");\n\n plan_for_window_close(ac);\n subtest_get_an_account_part_2(ac);\n wait_for_window_close();\n\n // Make sure we set the default search engine\n let engine = Services.search.getEngineByName(\"bar\");\n Assert.equal(engine, Services.search.defaultEngine);\n\n // Restore the original search engine.\n Services.search.defaultEngine = originalEngine;\n remove_email_account(\"green@example.com\");\n}",
"function subtest_can_dismiss_account_provisioner(w) {\n plan_for_window_close(w);\n // Click on the \"I think I'll configure my account later\" button.\n mc.click(new elib.Elem(w.window.document.querySelector(\".close\")));\n\n // Ensure that the window has closed.\n wait_for_window_close();\n}",
"function checkLoanAdvance(id)\r\n{\r\n\tvar rc;\r\n\tvar temp;\r\n\r\n\trc = showLoanItem('advance');\r\n\tif (rc == '0'){\r\n\t\ttemp = document.getElementById(id);\r\n\t\ttemp.style.display = 'none';\r\n\t}\r\n}//end checkLoanAdvance",
"async function showExamples(driver) {\n await driver.findElement(by.xpath(\"//button[text() = 'Examples']\")).click();\n await driver.wait(until.elementLocated(by.className(\"dropdown-item\")));\n }",
"function otherLoansShowFeedback() {\n \n // TO DO\n // populate feedback based on the displayed user\n \n document.getElementById('block-other-loans-show-feedback').style.display = \"\";\n \n}",
"showTeamsFilter(){\n let teamsFilter = document.getElementById(\"general_teams_filter\");\n\n if(teamsFilter) {\n if (teamsFilter.style.display === 'block') {\n teamsFilter.style.display = 'none';\n }\n else {\n teamsFilter.style.display = 'block';\n }\n document.addEventListener('click', function (event) {\n var isClickInside = teamsFilter.contains(event.target);\n if (!isClickInside && teamsFilter.style.display === 'block') {\n teamsFilter.style.display = 'none';\n }\n }, true);\n }\n\n }",
"clickLoginButton() {\n this.loginButton.waitForDisplayed()\n this.loginButton.click()\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>Check your work! Your banck_account should have $55 in it. 2. You got a bonus! Your pay is now doubled each week. Write code that will save the sum of all the numbers between 1 100 multiplied by 2. >Check your work! Your banck_account should have $10,100 in it. | function bank_account2(){
var total = 0;
for (let i = 0; i <= 100; i++) {
total += i * 2
};
console.log(total);
} | [
"function workToGetBalance() {\n payBalance += 100;\n}",
"function hireaddbal() {\n sum = 0;\n master.hireitems.forEach(function (item) {\n sum += Math.floor(item.multi * item.quan * master.imp.balmulti);\n });\n addbal(sum);\n}",
"function billTotal(subTotal){\nreturn subTotal + (subTotal * .15) + (subTotal * .095);\n}",
"function depositMoney(account, amount) {\n\n account.money += amount;\n console.log('You have successfully Deposited £' + amount + ' from your ' + account.type + ' account!\\nYou have £' + account.money + ' Left in your ' + account.type + ' account!');\n\n}",
"function makeBill() {\r\n let appleNumber = parseInt(document.querySelector('#apple').value) * 10;\r\n let orangeNumber = parseInt(document.querySelector('#orange').value) * 15;\r\n let bananaNumber = parseInt(document.querySelector('#banana').value) * 7;\r\n let totalBill = parseInt(document.querySelector(\"#bill\").value);\r\n\r\n totalBill = appleNumber + orangeNumber + bananaNumber;\r\n document.querySelector(\"#bill\").value = totalBill;\r\n}",
"function calcCheck(bills) {\n return bills.map(bill =>\n bill >= 50 && bill <= 300\n ? bill * (15 / 100) + bill\n : bill * (20 / 100) + bill\n );\n}",
"function calculateBonus() {\n return .02 * salary;\n}",
"countingBills(input) {\n // Set sum to zero\n let sum = 0;\n // Represent denominations of money\n let bills = [1,5,10,20,50,100];\n // Multiply the first number of bills by 1 and add to sum\n // Multiply the second number of bills by 5 and add to sum\n // Multiply the third number of bills by 10 and add to sum\n // Multiply the fourth number bills by 20 and add to sum\n // Multiply the fifth number bills by 50 and add to sum\n // Multiply the sixth number bills by 100 and add to sum\n for(let i = 0; i < input.length; i++ ){\n sum += input[i] * bills[i];\n }\n \n // Output sum\n return sum; \n }",
"bankSalery(){\n if( this.bankLoan > 0 ){\n let deduction = (this.payBalance * 0.10) \n this.payBalance = this.payBalance - deduction\n if(deduction > this.bankLoan){\n this.bankBalance = this.bankBalance + (deduction - this.bankLoan)\n this.bankLoan = 0\n } else {\n this.bankLoan = this.bankLoan - deduction\n }\n }\n this.bankBalance = this.bankBalance + this.payBalance \n this.payBalance = 0\n }",
"deductBudget() {\n let price = parseInt(costClothing.value, 10);\n runningBudget -= price;\n updateBudget();\n }",
"function loop(){\n var sum = 0;\n for(var i = 1; i <= 1000; i++){\n if(i % 2 == 0){\n sum += i;\n }\n }\n\n for(var i = 1; i <= 500; i++){\n if(i % 2 != 0){\n sum -= i;\n }\n }\n\n sum *= 12.5;\n console.log(sum);\n}",
"function fromBank(){\n money += bank;\n displayMoney(money);\n bank *= 0;\n displayBank(bank);\n}",
"function transferMoney() {\n bankBalance += payBalance;\n payBalance = 0;\n}",
"function Increase(){\n\n if (bankBallance > 0){\n IncreaseBet();\n\n if ( betAmmount > bankBallance){\n canDouble = false;\n }\n }\n}",
"function getMoneyToBank() {\n if (person.pay !== 0) {\n balance.textContent = `${person.balance += person.pay}kr`\n person.pay = 0;\n pay.textContent = `${person.pay} kr`\n }\n}",
"function deposit(){\n fs.appendFile(\"bank.txt\", `, ${number}`, function(error){\n if (error){\n return console.log(error);\n }\n \n //Tells the user what they wrote as the fourth input then tells the user their newly calculated total.\n console.log(`You have deposited: $${number}.00.`)\n total();\n })\n}",
"function tipAmount(bill, service) {\n if (service == 'good') {\n return (bill) + (bill * 0.2);\n }\n else if (service == 'fair') {\n return (bill) + (bill * 0.15);\n }\n else if (service == 'bad') {\n return (bill) + (bill * 0.10);\n }\n else {\n return \"That is not a valid input\";\n }\n }",
"getNumberOfCoins() {\n let numberOfCoins = 120000 + (this.numberOfBlocks) * 100;\n return numberOfCoins;\n }",
"function buy_half_shares() {\n // Makes a fair split of cash and shares with start money for initialization\n var half_cash = cash / 2.0;\n var half_shares = Math.round(half_cash / data[0]);\n cash -= half_shares * data[0];\n shares = half_shares;\n liveSend(get_trade_report('Buy', data[0], half_shares));\n update_portfolio();\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates Roles If role does not exist throw error message | function checkRoles(roles){
var possibleRoles = ["service provider", "device owner", "infrastructure operator", "administrator", "system integrator", "devOps", "user", "superUser"];
for(var i = 0, l = roles.length; i < l; i++){
if(possibleRoles.indexOf(roles[i]) === -1){
return {invalid: true, message: roles[i]};
}
}
return {invalid: false, message: null};
} | [
"function validateRole(role) {\n\tconst schema = {\n\t\ttitle: Joi.string()\n\t\t\t.min(5)\n\t\t\t.max(30)\n\t\t\t.required()\n\t};\n\n\treturn Joi.validate(role, schema);\n}",
"function checkValidRole(role) {\n if (!['owner', 'moderator', 'user'].includes(role)) {\n throw new RequestError('invalid role');\n }\n}",
"function roleExists(roleName){\r\n for (i = 0; i < Z_ROLES.length; i++) {\r\n var z_userrole = Z_ROLES[i].toString().substring(0,25).trim();\r\n\t if(z_userrole.toUpperCase() == roleName.toUpperCase()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}",
"function NoSuchRole (message, role) {\n UnmetDependency.call(this, message);\n this.role = role;\n}",
"function checkRole (role, allowed, options) {\n // Check if the value type passed to view is create or edit \n var temp = allowed.split(',');\n if (temp[role]) { \n return options.fn(this);\n } else {\n return;\n } \n}",
"function manageRoles(cmd){\n try{\n\t//console.log(cmd.message.channel instanceof Discord.DMChannel);\n\t//if (cmd.message.channel instanceof Discord.DMChannel) { sendMessage(cmd, \"This command currently only works in guild chats\"); return \"failure\"; }\n\tconst openRoles = roleNames.openRoles, voidRoles = roleNames.voidRoles;\n const guild = client.guilds.find(\"name\", \"Terra Battle\");\n\tconst guildRoles = guild.roles; //cmd.message.guild.roles;\n\tvar roles = cmd.details.split(\",\"), guildMember = guild.members.get(cmd.message.author.id);\n \n var feedback = \"\";\n\t//console.log(guildMember);\n\t\n\t//Check to make sure the requested role isn't forbidden\n\t//Find role in guild's role collection\n\t//Assign role (or remove role if already in ownership of)\n\t//Append response of what was done to \"feedback\"\n\troles.forEach(function(entry){\n\t\tentry = entry.trim();\n\t\tlowCaseEntry = entry.toLowerCase();\n\t\t\n\t\t//Ignore any attempts to try to get a moderator, admin, companion, bot, or specialty role.\n\t\t//Ignore: metal minion, wiki editor, content creator, pvp extraordinare\n /*voidRoles.forEach(\n function(currentValue){\n \n }\n );*/ //TODO: Manage Void Role rejection more elegantly\n\t\tif (!(voidRoles.some( x => lowCaseEntry.includes(x) )) ){\n\t\t\t\n\t\t\t//run requested role name through the roleName DB\n\t\t\tvar roleCheck = openRoles.get(lowCaseEntry); //TODO: Make a DB that allows for server-specific role name checks\n\t\t\tvar role;\n\t\t\t\n\t\t\ttry{ role = guildRoles.find(\"name\", roleCheck); }\n\t\t\tcatch (err) { \n\t\t\t\t//Role didn't exist\n\t\t\t\tconsole.log(err.message);\n console.log(\"User: \" + cmd.message.author.name);\n\t\t\t}\n\t\t\t\n\t\t\tif( typeof role === 'undefined' || role == null ){ feedback += \"So... role '\" + entry + \"' does not exist\\n\"; }\n\t\t\telse if( guildMember.roles.has(role.id) ) {\n\t\t\t\tguildMember.removeRole(role);\n\t\t\t\tfeedback += \"I removed the role: \" + role.name + \"\\n\"; }\n\t\t\telse {\n\t\t\t\tguildMember.addRole(role);\n\t\t\t\tfeedback += \"I assigned the role: \" + role.name + \"\\n\"; }\n\t\t} else { feedback += \"FYI, I cannot assign '\" + entry + \"' roles\"; }\n\t\t//guildMember = cmd.message.member;\n\t});\n\t//return feedback responses\n\t( feedback.length > 0 ? cmd.message.channel.send(feedback) : \"\" );\n } catch (err) {\n console.log(err.message);\n console.log(\"User: \" + cmd.message.author.name);\n }\n}",
"create(req, res) {\n if (isNullNumberOrWhitespace(req.body.title)\n || isNullNumberOrWhitespace(req.body.description)) {\n res.status(400).send({ message: 'Fields can not be empty or begin with a number' });\n } else if (req.body.title) {\n Role.findOne({\n where: {\n title: req.body.title.toLowerCase(),\n },\n })\n .then((role) => {\n if (role) {\n res.status(409).send({ message: 'Role already exists!' });\n } else {\n Role.create({\n title: req.body.title.toLowerCase(),\n description: req.body.description,\n })\n .then(() => res.status(201).send({ message: 'Role created successfully!' }));\n }\n });\n }\n }",
"static get noRole() { return NO_ROLE; }",
"function addRole() {\n inquirer\n .prompt([\n {\n type: \"input\",\n message: \"What is the name of the new employee role?\",\n name: \"title\"\n },\n {\n type: \"input\",\n message: \"How much is the new salary of the employee's role?\",\n name: \"salary\"\n },\n {\n type: \"list\",\n message: \"In which department is the new role?\",\n name: \"id\",\n choices: showdepartments\n }\n ])\n .then(function (response) {\n \n addEmployeeRole(response);\n })\n }",
"function deleteRole() {\n db.query(`SELECT * FROM role`, (err, data) => {\n if (err) throw err;\n\n const roles = data.map(({\n id,\n title\n }) => ({\n name: title,\n value: id\n }));\n //inquirer prompt that presents a list of roles to choose from\n inquirer.prompt([{\n type: 'list',\n name: 'name',\n message: \"Select a Role to remove\",\n choices: roles\n }])\n .then(event => {\n db.query(`DELETE FROM role WHERE role.id = ${event.name} `, (err, result) => {\n if (err) throw err;\n console.log(\"Role has been removed from the database.\");\n\n initPrompt();\n });\n });\n });\n}",
"function initializeRoles() {\n console.log(\"initializing roles\");\n Role.estimatedDocumentCount((err, count) => {\n console.log(count);\n if (!err && count == 0) {\n new Role({\n name: \"user\",\n }).save((err) => {\n if (err) {\n console.log(\"error : \" + err);\n }\n console.log(\"Role user created\");\n });\n\n new Role({\n name: \"admin\",\n }).save((err) => {\n if (err) {\n console.log(\"error : \" + err);\n }\n console.log(\"Admin role created\");\n });\n\n new Role({\n name: \"creator\",\n }).save((err) => {\n if (err) {\n console.log(\"error : \" + err);\n }\n console.log(\"Creator role created\");\n });\n }\n });\n}",
"async function checkRole (req, res, next) {\n const { user_id, team_id } = req.params;\n const teamId = req.body.team_id;\n\n if(!teamId){\n next();\n } else if (!team_id){\n const member = await teamMembersDB.getTeamMember(user_id, teamId);\n\n if(!member){\n res.status(401).json({ error: 'You are not a Member of this Team'});\n } else {\n next();\n }\n } else {\n const member = await teamMembersDB.getTeamMember(user_id, team_id);\n\n if(!member){\n res.status(401).json({ error: 'You are not a Member of this Team'});\n } else {\n\n if(member.role !== 'team_owner'){\n res.status(401).json({ error: 'Only Team Owners can do this'});\n } else {\n next();\n }\n }\n }\n}",
"getRole (roleId) {\n assert.equal(typeof roleId, 'string', 'roleId must be string')\n return this._apiRequest(`/role/${roleId}`)\n }",
"'addUserRole'(userid, role)\n {\n Roles.addUsersToRoles(userid,role);\n\n\n }",
"function addEmployeeRoles(managers){\n \n console.clear();\n db.loadRoles(addEmployeePrompt, managers);\n}",
"function getUserRole(name, role){\n switch (role) {\n case \"admin\":\n return `${name} is admin with all access`\n break; //this is not neccesary\n\n case \"subadmin\":\n return `${name} is sub-admin acess to delete and create courses`\n break;\n\n case \"testprep\":\n return `${name} is test-prep access with to delete and create tests `\n break;\n case \"user\":\n return `${name} is a user to consume content`\n break;\n \n default:\n return `${name} is admin access with to delete and create tests `\n break;\n }\n}",
"function checkVariables(values, roles, i){ // Take in a role ID and see if it matches any of the IDs in the provided array of values, if it does, return the name, otherwise return undefined\n const result = values.find( ({ id }) => id === roles[i] );\n if (result === undefined) {\n } else { \n return result.name\n }\n }",
"static loadRoles() {\n let roleList = [];\n let dataFile = fs.readFileSync('./data/roles.json', 'utf8');\n if (dataFile === '') return roleList;\n\n let roleData = JSON.parse(dataFile);\n\n roleData.forEach((element) => {\n roleList.push(\n new Role(\n element.roleID,\n element.title,\n element.description,\n element.image,\n element.color,\n element.emote\n )\n );\n });\n\n return roleList;\n }",
"function messageDoesNotExist() {\n let error = Error('ValidationError');\n\n error.validationErrors = [\n {\n \"message\": {\n \"message_id\": \"The specified message does not exist.\",\n \"rule\": \"exists\"\n }\n }\n ];\n\n return error;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PresentationValidationUtility consists of all validation methods related to presentation | function PresentationValidationUtility() {} | [
"function genericFormatValidate(genericFv) {\n $('.' + genericFv.className).each(function() {\n var procEl = $(this);\n var reformat = false;\n \n //Check if element has another class\n var numClasses = 0;\n $.each(fvClasses, function(index, item) {\n if(procEl.hasClass(item.className)) numClasses++;\n });\n if(numClasses > 1) procEl.attr('data-fv-multiple', numClasses);\n \n //Set defaults\n if(genericFv.isRequired == undefined) genericFv.isRequired = false;\n if(genericFv.regex != undefined) genericFv.validationFn = function(value) {\n return (value.match(genericFv.regex));\n };\n \n var params = {};\n if(genericFv.params) {\n if(!(genericFv.params instanceof Array)) genericFv.params = [genericFv.params];\n for(var i = 0; i<genericFv.params.length; i++) {\n genericFv[genericFv.params[i]] = processes.getParam(procEl, genericFv.className, genericFv.params[i]);\n if(genericFv[genericFv.params[i]] == undefined && settings.showConsoleMessages) console.log('FV: #' + procEl.attr('id') + ' : Missing attribute data-' + genericFv.className + '-' + genericFv.params[i]);\n }\n }\n \n procEl.blur(function() {\n //Check for multiple classes\n if(!processes.getParam(procEl, genericFv.className, 'multiple')) {\n //Not multiple, proceed as usual\n processes.removeInvalid(procEl, genericFv.className);\n } else {\n //Mulitple classes. Check if the invalid element is the currently checked class\n if(procEl.hasClass('fvInv'+genericFv.className)) {\n processes.removeInvalid(procEl, genericFv.className);\n }\n } \n \n var cond2 = function(value) {return false;}\n if(!genericFv.isRequired) {\n cond2 = function(value) {return (to.NoWhiteSpace(value) == \"\");};\n }\n if(genericFv.validationFn && processes.isFunction(genericFv.validationFn)) {\n if(genericFv.validationFn(to.NoWhiteSpace(procEl.val())) || cond2(procEl.val())) {\n reformat = true;\n } else {\n processes.invalidElement(procEl, genericFv.className);\n }\n } else {\n reformat = true;\n }\n if(reformat) {\n if(genericFv.formattingFn && processes.isFunction(genericFv.formattingFn) && to.NoWhiteSpace(procEl.val()) != \"\") procEl.val(to.NoWhiteSpace(genericFv.formattingFn(procEl.val())));\n }\n });\n });\n }",
"function validateSlideThree() {\n\tvar motto = document.forms[\"register\"][\"businessmotto\"].value;\n\tvar mottoError = document.getElementById(\"error-businessmotto\");\n\tvar state = document.forms[\"register\"][\"state\"].value;\n\tvar area = document.forms[\"register\"][\"area\"].value;\n\tvar stateError = document.getElementById(\"error-state\");\n\tvar areaError = document.getElementById(\"error-area\");\n\n\t\n\n\t//validates business motto\n\tif (motto == \"\") {\n\t\tmottoError.innerHTML = \"This field is required\";\n\t} else {\n\t\tmottoError.innerHTML = \"\";\n\t}\n\n\tif (state == \"\") {\n\t\tstateError.innerHTML = \"This field is required\";\n\t} else {\n\t\tstateError.innerHTML = \"\";\n\t}\n\n\tif (area == \"\") {\n\t\tareaError.innerHTML = \"This field is required\";\n\t} else {\n\t\tareaError.innerHTML = \"\";\n\t}\n\n\t//if either fails validation remain on current slide else move to next slide\n\n\tif (motto == \"\" || area == \"\" || state == \"\") {\n\t\tcurrentSlide(3);\n\t} else {\n\t\tplusSlides(1);\n\t}\n}",
"function validateSlideTwo() {\n\tvar bizName = document.forms[\"register\"][\"businessname\"].value;\n\tvar bizInfo = document.forms[\"register\"][\"businessinfo\"].value;\n\tvar bizPhone = document.forms[\"register\"][\"businessphone\"].value;\n\tvar bizNameError = document.getElementById(\"error-businessname\");\n\tvar bizInfoError = document.getElementById(\"error-businessinfo\");\n\tvar bizPhoneError = document.getElementById(\"error-businessphone\");\n\tvar bizAddr =document.forms[\"register\"][\"businessaddress\"].value;\n\tvar bizAddrError = document.getElementById(\"error-businessaddress\");\n\t\n\n\n\t//validates business name\n\t\tif (bizName == \"\") {\n\t\tbizNameError.innerHTML = \"This field is required\";\n\t} \n\t else {\n\t\tbizNameError.innerHTML = \"\";\n\t}\n\n\n\t//validates business info\n\tif (bizInfo == \"\") {\n\t\tbizInfoError.innerHTML = \"This field is required\";\n\t} \n\telse {\n\t\tbizInfoError.innerHTML = \"\";\n\t}\n\n\n\t//validates business phone\n\tif (bizPhone == \"\") {\n\t\tbizPhoneError.innerHTML = \"This field is required\";\n\t}\telse if (isNaN(bizPhone)) {\n\t\tbizPhoneError.innerHTML = \"Only numbers allowed\";\n\t}\n\t else if (bizPhone.length != 11){\n\t\tbizPhoneError.innerHTML = \"Number must be 11 characters long\";\n\t} else {\n\t\tbizPhoneError.innerHTML = \"\";\n\t};\n\n\tif (bizAddr == \"\") {\n\t\tbizAddrError.innerHTML = \"This field is required\";\n\t}\n\n\t//if either fails validation remain on current slide else move to next slide\n\tif (bizPhone == \"\" || bizPhone.length != 11 || bizName == \"\" || bizInfo == \"\" || isNaN(bizPhone) || bizAddr == \"\") {\n\t\tcurrentSlide(2);\n\t} else{\n\t\tplusSlides(1);\n\t};\n}",
"function isPropValid()\n{\n\n}",
"function setupCommonAndMaxLengthRangeCheckingValidation(prototype, noun, nouns,\r\n\t\tminProperty, maxProperty, valueProperty, converter, maxLengthProperty) {\r\n\r\n\tif (converter == null)\r\n\t\tconverter = function(value) { return value; };\r\n\r\n\t\t\t// note that laf will be null if a display model was not created\r\n\tprototype.validate = function(instance, laf) {\r\n\r\n\t\tvar properties = instance.properties;\r\n\t\tvar messages = new java.util.ArrayList();\r\n\r\n\t\tvar min = converter(properties[minProperty]);\r\n\t\tvar max = converter(properties[maxProperty]);\r\n\t\tvar value = converter(properties[valueProperty]);\r\n\r\n\t\tif (converter(properties[maxLengthProperty])!= null) {\r\n\t\t\tvar maxLength = converter(properties[maxLengthProperty]);\r\n\t\t\tif ( maxLength < 3 || maxLength > 32 ){\r\n\t\t\t\tmessages.add(createSimpleModelError(instance, maxLengthProperty, \r\n\t\t\t\timplLibraryStrings.getString(\"maxLengthValueError\"), \r\n\t\t\t\t[ maxLength ]));\r\n\t\t\t} else {\r\n\t\t\t\tvar textValue = value.toString();\r\n\t\t\t\tif (textValue.length > maxLength){\r\n\t\t\t\t\tmessages.add(createSimpleModelError(instance, valueProperty,\r\n\t\t\t\t\timplLibraryStrings.getString(\"maxLengthConstraint\"), \r\n\t\t\t\t\t[noun, maxLength ]));\r\n\t\t\t\t}\t\r\n\t\t\t}\r\n\t\t} \r\n\t\t\r\n\t\tif (min > max) {\r\n\t\t\tmessages.add(createSimpleModelError(instance, \r\n\t\t\t\tminProperty, \r\n\t\t\t\timplLibraryStrings.getString(\"minMaxValueError\"), \r\n\t\t\t\t[ noun, nouns, instance.name, min, max ]));\r\n\t\t} \r\n\t\tif (value < min || value > max ) {\r\n\t\t\tmessages.add(createSimpleModelError(instance, \r\n\t\t\t\tvalueProperty, \r\n\t\t\t\timplLibraryStrings.getString(\"valueRangeError\"), \r\n\t\t\t\t[ noun, nouns, instance.name, min, max, value ]));\r\n\t\t}\t\r\n\t\treturn messages;\r\n\t}\r\n\t\r\n\t\t// note that laf will be null if a display model was not created\r\n\tprototype.queryPropertyChange = function(instance, propertyPath,\r\n\t\t\t\t\tnewVal, laf) {\r\n\t\tvar properties = instance.properties;\r\n\t\tvar message = null;\r\n\r\n\t\tnewValue = converter(newVal);\r\n\t\tif (propertyPath == minProperty) {\r\n\t\t\tif (newValue > converter(properties[valueProperty]) ||\r\n\t\t\t\tnewValue >= converter(properties[maxProperty])) {\r\n\t\t\t\tmessage = formatString(implLibraryStrings.getString(\"minValueConstraint\"), noun, nouns );\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (propertyPath == valueProperty) {\r\n\t\t\tif (newValue < converter(properties[minProperty]) ||\r\n\t\t\t newValue > converter(properties[maxProperty])) {\r\n\t\t\t\tmessage = formatString(implLibraryStrings.getString(\"valueConstraint\"), noun, nouns );\r\n\t\t\t}else {\r\n\t\t\t\tif (converter(properties[maxLengthProperty])!= null){\r\n\t\t\t\t\tif (newValue.toString().length() > converter(properties[maxLengthProperty])) {\r\n\t\t\t\t\t\tmessage = formatString(implLibraryStrings.getString(\"maxLengthConstraint\"), noun );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (propertyPath == maxProperty) {\r\n\t\t\tif (newValue <= converter(properties[minProperty]) ||\r\n\t\t\t\tnewValue < converter(properties[valueProperty]))\r\n\t\t\t\tmessage = formatString(implLibraryStrings.getString(\"maxValueConstraint\"), noun, nouns );\r\n\t\t}\r\n\t\treturn message;\t\t\r\n\t}\r\n\r\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 }",
"function toggleValidationPopUp() {\n if (!lodash.isEmpty(ctrl.validationRules)) {\n var popUp = $element.find('.validation-pop-up');\n ctrl.isValidationPopUpShown = !ctrl.isValidationPopUpShown;\n\n if (ctrl.isValidationPopUpShown) {\n $document.on('click', handleDocumentClick);\n\n // in order for the calculation in the function of `$timeout` below to work, the pop up should first\n // be positioned downwards, then it will determine whether it does not have enough room there and\n // will move it upwards in that case.\n ctrl.showPopUpOnTop = false;\n\n $timeout(function () {\n fieldElement.focus();\n ctrl.inputFocused = true;\n ctrl.showPopUpOnTop = $window.innerHeight - popUp.offset().top - popUp.outerHeight() < 0;\n });\n } else {\n $document.off('click', handleDocumentClick);\n }\n }\n }",
"function validator(){\n var o = {\n stringValidator: isUpperCase(\"asdasf\"),\n passwordValidator: isDigit(\"asda564sd\"),\n colorValidator: isHexadecimal(\"asd444\"),\n yearValidator: doesBelong(2020)\n }\n\n return o;\n}",
"function validateAllPanels() \n {\n\n if (validDetails() && validDescription() && validImage() && validAdvanced() && validVendor() && validFulfillment() && validUnitOfMeasure() && validCategory())\n return true;\n else\n return false;\n \n }",
"function PresentationUtility() {\n /*\n A variable maintained to store row index globally on swipe\n Note:It is maintained to delete on swipe till platform fix issue related to segment\n*/\n /**@member {integer} number to maintain index for swipe*/\n this.rowIndexforSwipe = -1;\n /**@member {integer} number to maintain tap gesture enabled or not*/\n this.tapgestureEnabled = true;\n }",
"function validateForm() {\n clientErrorStorage = new Object();\n var summaryTextExistence = new Object();\n var validForm = true;\n\n jQuery.watermark.hideAll();\n pauseTooltipDisplay = true;\n\n if (validateClient) {\n // Turn on this flag to avoid prematurely writing out messages which will cause performance issues if MANY\n // fields have validation errors simultaneously (first we are only checking for errors, not checking and\n // writing simultaneously like normal)\n clientErrorExistsCheck = true;\n\n // Temporarily turn off this flag to avoid traversing unneeded logic (all messages will be shown at the end)\n messageSummariesShown = false;\n\n // Validate the whole form\n validForm = jq(\"#kualiForm\").valid();\n\n // Handle field message bubbling manually, but do not write messages out yet\n jQuery(\"div[data-role='InputField']\").each(function () {\n var id = jQuery(this).attr('id');\n var field = jQuery(\"#\" + id);\n var data = getValidationData(field);\n var parent = field.data(\"parent\");\n handleMessagesAtGroup(parent, id, data, true);\n });\n\n // Toggle the flag back to default\n clientErrorExistsCheck = false;\n\n // Message summaries are going to be shown\n messageSummariesShown = true;\n\n // Finally, write the result of the validation messages\n writeMessagesForPage();\n }\n\n if (!validForm) {\n validForm = false;\n\n //ensure all non-visible controls are visible to the user\n jQuery(\".error:not(:visible)\").each(function () {\n cascadeOpen(jQuery(this));\n });\n\n jumpToTop();\n showClientSideErrorNotification();\n jQuery(\".uif-pageValidationMessages li.uif-errorMessageItem:first > a\").focus();\n }\n\n jq.watermark.showAll();\n pauseTooltipDisplay = false;\n\n return validForm;\n}",
"validateData(){\n\t//todo\n\tvar invalideMessages = [];\n\tvar oPapers = StoreHelper.getPapers();\n\tvar subPages = Object.keys(oPapers)\n\t .reduce((pre,curPaperKey) => {\n\t\tvar curPaper = oPapers[curPaperKey];\n\t\tif(paper.isSubPage(curPaper.paperType)){\n\t\t pre[curPaperKey] = curPaper.key;\n\t\t}\n\t\treturn pre;\n\t },{});\n\n\tvar isValide = !subPages || Object.keys(subPages)\n\t\t.every((subPaperUUID)=>{\n\t\t var hasPaper = Object.keys(oPapers).find((paperKey)=>{\n\t\t\tvar curPaper = oPapers[paperKey];\n\t\t\tif(paper.isSubPage(curPaper)){\n\t\t\t return false;\n\t\t\t}\n\t\t\tif(paper.hasDeviceNumber(curPaper, subPages[subPaperUUID])){\n\t\t\t return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t });\n\t\t if(hasPaper){\n\t\t\treturn true;\n\t\t } else {\n\t\t\tinvalideMessages.push(`子页面${oPapers[subPaperUUID].paperName}绑定设备:${subPages[subPaperUUID]} 不存在`);\n\t\t\treturn false;\n\t\t }\n\t\t});\n\tvar duplicateInfo = this.checkDuplicateInfo(oPapers);\n\tif(duplicateInfo){\n\t isValide = false;\n\t invalideMessages = invalideMessages.concat(duplicateInfo);\n\t}\n\treturn {\n\t isValide: !!isValide,\n\t messages: invalideMessages\n\t};\n }",
"function custPreFormValidation(preChatlableObject, user){\n return true;\n}",
"function EnsureVisual(/*DependencyObject*/ element, /*bool*/ allowNull)\r\n {\r\n if (element == null) \r\n {\r\n if (!allowNull) \r\n { \r\n throw new ArgumentNullException(\"element\");\r\n } \r\n\r\n return;\r\n }\r\n\r\n //\r\n if (!(element instanceof EnsureVisual2())) \r\n { \r\n throw new ArgumentException(SR.Get(SRID.Visual_NotAVisual));\r\n } \r\n\r\n// element.VerifyAccess();\r\n }",
"get validity() {\n return this.elementInternals\n ? this.elementInternals.validity\n : this.proxy.validity;\n }",
"function validaComidasRepresentacion(){\r\n\t\tvar idConceptoComidaRepresentacion = 1;\r\n\t\tvar concepto = buscaConceptoporID(idConceptoComidaRepresentacion);\r\n\t\t\r\n\t\tif(concepto){\r\n\t\t\tasignaRequeridos();\r\n\t\t\tmostrarElemento(\"invitados_table\");\r\n\t\t\tasignaVal(\"agregar_invitado\", \" Agregar Invitado\");\r\n\t\t\tcargartipoInvitados();\r\n\t\t}else{\r\n\t\t\tocultarElemento(\"invitados_table\");\r\n\t\t}\r\n\t}",
"function postValidate(isValid, errMsg, errElm, inputElm) {\n if (!isValid) {\n // Show errMsg on errElm, if provided.\n if (errElm !== undefined && errElm !== null\n && errMsg !== undefined && errMsg !== null) {\n errElm.html(errMsg);\n }\n // Set focus on Input Element for correcting error, if provided.\n if (inputElm !== undefined && inputElm !== null) {\n inputElm.addClass(\"errorBox\"); // Add class for styling\n inputElm.focus();\n }\n } else {\n // Clear previous error message on errElm, if provided.\n if (errElm !== undefined && errElm !== null) {\n errElm.html('');\n }\n if (inputElm !== undefined && inputElm !== null) {\n inputElm.removeClass(\"errorBox\");\n }\n }\n}",
"function FormValidation(formOrContainerID, isValidateAll) {\n // Note: add 'input_label' in data attribute in each element to get the label of the input to be shown in error message e.g = data-fieldLabel='User Name'\n var formID = formOrContainerID || false;\n if (!formID) {\n alert('FormValidation() constructor function needs form id as required parameter');\n return;\n } else {\n formID = '#'+formID+' ';\n }\n this.errors = []; // object to store error details\n this.inputDataAttributes= {'input_label':'Name of input field label'}; // NOTE: name of data attribute which containes label/name of input field\n this.validateInputClass = ['phone','mobile','email','aadhar']; // NOTE: add these class to element for respective validation\n this.exceptionClasses = ['no-validation', 'do-not-validate', 'no-validate']; // NOTE: add class 'no-validation' or 'do-not-validate' or 'no-validate' to element which not to be included in validation\n this.validateAll = isValidateAll || false; // NOTE: if set true then validation will be applied on all element except exceptional class \n this.inputAll = document.querySelectorAll(formID+'input');\n this.selectAll = document.querySelectorAll(formID+'select');\n this.textareaAll = document.querySelectorAll(formID+'textarea');\n this.inputValue = null;\n this.errMessage = false;\n // console.log(this.selectAll);\n}",
"function validateSlideFour() {\n\t\tvar pass = document.forms[\"register\"][\"password\"].value;\n\t\tvar confirmPass = document.forms[\"register\"][\"password_confirmation\"].value;\n\t\tvar passError = document.getElementById(\"error-password\");\n\t\tvar confirmPassError = document.getElementById(\"error-confirm-password\");\n\t\tvar mailFormat = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;\n\n\t\t//validates password\n\t\tif (pass == \"\") {\n\t\t\tpassError.innerHTML = \"This field is required\";\n\t\t\treturn false;\n\t\t} else if (pass.length < 8) {\n\t\t\tpassError.innerHTML = \"Password must be at least 8 characters long\";\n\t\t\treturn false;\n\t\t}\n\t\t else {\n\t\t\tpassError.innerHTML = \"\";\n\t\t}\n\n\t\t//validates confirm password\n\t\tif (confirmPass == \"\") {\n\t\t\tconfirmPassError.innerHTML = \"This field is required\";\n\t\t\treturn false;\n\t\t}else if (pass !== confirmPass && confirmPass != \"\") {\n\t\t\tconfirmPassError.innerHTML = \"Passwords don't match\";\n\t\t\treturn false;\n\t\t}\n\t\t else {\n\t\t\tconfirmPassError.innerHTML = \"\";\n\t\t}\n\t\t//if either fails validation remain on current slide\n\t\tif (pass == \"\" || confirmPass == \"\" || pass !== confirmPass && confirmPass != \"\" ||\tpass.length < 6 ) {\n\t\t\tcurrentSlide(4);\n\t\t}else{\n document.getElementById(\"register\").submit();}; \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the input image to be the image passed into the inputFile element. Reinitilizes the data canvas with the new target data. | function inputFile(){
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function () {
var tempImage = new Image();
tempImage.src = reader.result;
tempImage.onload = function() {
inputImage.width = this.width;
inputImage.height = this.height;
inputImage.src = tempImage.src;
inputImageResWidth = inputImage.width;
inputImageResHeight = inputImage.height;
dataSizeWidth = Math.floor(inputImageResWidth / dataSizeScaleFactor);
dataSizeHeight = Math.floor(inputImageResHeight / dataSizeScaleFactor);
setupDataCanvas();
};
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
inputImage.src = "";
}
} | [
"function setupDataCanvas() {\n\tinputCanvas.width = dataSizeWidth;\n\tinputCanvas.height = dataSizeHeight;\n\tinputContext.drawImage(inputImage, 0, 0, inputImageResWidth, inputImageResHeight, 0, 0, dataSizeWidth, dataSizeHeight);\n\t\n\tvar rescaledImageData = inputContext.getImageData(0, 0, dataSizeWidth, dataSizeHeight).data;\n\t\n\ttargetData = [];\n\tfor (var i = 0; i < dataSizeWidth * dataSizeHeight * 4; i++) {\n\t\ttargetData[i] = rescaledImageData[i];\n\t}\n\t\n\tinputCanvas.width = inputImageResWidth;\n\tinputCanvas.height = inputImageResHeight;\n\toutputCanvas.width = inputImageResWidth;\n\toutputCanvas.height = inputImageResHeight;\n\tinputContext.drawImage(inputImage, 0, 0);\t\n}",
"function Enter_image(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n\n reader.onload = function (e) {\n\t\t\tvar nextEI=$(input).next('.enter_image');\n nextEI.attr('src', e.target.result);\n\t\t\tnextEI.attr('width','50px');\n\t\t\tnextEI.attr('height','50px');\n }\n\n reader.readAsDataURL(input.files[0]);\n }\n}",
"function handleImage(e) {\n var reader = new FileReader();\n reader.onload = function (event) {\n var img = new Image();\n img.onload = function () {\n //Update the canvas when the image file is loaded\n var topText = document.getElementById(\"topText\").value;\n var bottomText = document.getElementById(\"bottomText\").value;\n var fontSize = document.getElementById(\"fontSize\").value;\n var fontFamily = document.getElementById(\"fontFamily\").value;\n showCanvas(topText, bottomText, img, fontSize, fontFamily);\n }\n\n //Set the img element's source to be the image the user chose\n img.src = event.target.result;\n document.getElementById(\"img1\").src = img.src;\n }\n\n //Read the image file as a URL string\n reader.readAsDataURL(e.target.files[0]);\n}",
"constructor(canvas, path){\n this.canvas = canvas;\n this.ctx = canvas.getContext('2d');\n var img = new Image();\n img.onload = e =>{\n this.renderInitial();\n };\n this.img = img;\n img.src = path;\n }",
"onFileChange(event) {\n const file = event.target.files[0];\n this.img = URL.createObjectURL(file);\n }",
"function reset() {\n Caman(\"#canvas\", img, function () {\n this.revert();\n })\n}",
"updateReader() {\n // prevent until loaded\n if (!this.loaded) return;\n\n this.Reader.height = this.height;\n this.Reader.width = this.width;\n this.reader.drawImage(this.Input, 0, 0, this.width, this.height);\n\n // rerender\n this.getColorArray();\n this.draw();\n }",
"function loadImg(img, target_name) {\n if (img.files && img.files[0]) {\n var FR = new FileReader();\n FR.onload = function (e) {\n //e.target.result = base64 format picture\n $('#' + target_name + '_preview').attr(\"src\", e.target.result);\n $('#' + target_name + '_input').val(e.target.result);\n };\n FR.readAsDataURL(img.files[0]);\n }\n}",
"updateImage(){\n this.childCanvas.current.updatePath();\n }",
"function setOriginal() {\n\n let cnv = document.getElementById('imgHtml');\n let cnx = cnv.getContext('2d');\n\n cnx.clearRect(0, 0, cnv.width, cnv.height);\n cnx.beginPath();\n\n cnx.moveTo(0, 0);\n cnx.stroke();\n\n imgNormal(backup.original);\n\n}",
"function updateDiffImage()\n{\n var image = new Image;\n var canvas = document.querySelector(\"canvas#Canvas3\"),\n context = canvas.getContext(\"2d\");\n context.clearRect(0, 0,651,651);\n contextZoom3.clearRect(0, 0,651,651);\n let imageDiff = d3.select(\"#image-diff\").select(\"img\").attr(\"src\");\n image.src = imageDiff;\n image3.src = imageDiff;\n image.onload = load;\n image3.onload = loadZoom3;\n\n function load() {\n\n context.drawImage(this, 0, 0,294,294);\n }\n\n}",
"function cargar_imagen() {\n\t\t\t\n\t\t\tlet input = document.querySelector('.inp_cargar');\n\n\t\t\tinput.onchange = e => {\n\t\t\t\tlet canvas = document.querySelector(\"#canvas\");\n\t\t\t\tlet context = canvas.getContext(\"2d\");\n\n\t\t\t\tlet file = e.target.files[0];\n\t\t\t\tlet reader = new FileReader();\n\t\t\t\treader.readAsDataURL(file); \n\t\n\t\t\t\treader.onload = readerEvent => {\n\t\t\t\t\tlet content = readerEvent.target.result; \n\t\t\t\t\tlet image = new Image();\n\t\t\t\t\timage.src = content;\n\t\n\t\t\t\t\timage.onload = function () {\n\t\t\t\t\t\tlet imageAspectRatio = (1.0 * this.height) / this.width;\n\t\t\t\t\t\tlet imageScaledWidth = canvas.width;\n\t\t\t\t\t\tlet imageScaledHeight = canvas.width * imageAspectRatio;\n\t\t\t\t\t\tlet startWidth = 0;\n\t\t\t\t\t\tlet startHeigh = 0;\n\t\t\t\t\t\tif (this.width < this.height) {\n\t\t\t\t\t\t\timageAspectRatio = (1.0 * this.width) / this.height;\n\t\t\t\t\t\t\timageScaledWidth = canvas.height * imageAspectRatio;\n\t\t\t\t\t\t\timageScaledHeight = canvas.height;\n\t\t\t\t\t\t\tstartWidth = (canvas.width / 2) - (imageScaledWidth / 2);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstartHeigh = (canvas.height / 2) - (imageScaledHeight / 2);\n\t\t\t\t\t\t}\t\n\t\t\t\t\t\tcontext.drawImage(this, startWidth, startHeigh, imageScaledWidth, imageScaledHeight);\t\t\t\t\t\t\n\t\t\t\t\t\tlet imageData = context.getImageData(0, 0, c.width, c.height);\t\t\t\t\t\n\t\t\t\t\t\tctx.putImageData(imageData, 0, 0);\n\t\t\t\t\t\timg_original = ctx.getImageData(0, 0, c.width, c.height);\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t}",
"updateSrcSet(newSrc) {\n if (this.srcValues.length > 0) {\n this.srcValues.forEach(function (src) {\n if (src.name === newSrc.name) {\n src.url = newSrc.url;\n }\n }.bind(this));\n }\n\n this.saveSrcSet();\n this.fredCropper.el.dataset.crop = 'true';\n this.fredCropper.pluginTools.fredConfig.setPluginsData('fredcropper'+this.fredCropper.el.fredEl.elId, 'activated', 'true');\n }",
"function saveImage() {\n var data = canvas.toDataURL();\n $(\"#url\").val(data);\n }",
"async updateImageSource() {\n const source = await this.getThumbnailURL();\n this.getImage().setAttribute('src', source);\n }",
"load()\r\n {\r\n this.image = loadImage(this.imagePath);\r\n }",
"drawImageOnCanvasFromImgUrl(imageURL, setWidthHeight) {\n var img = new Image();\n\n img.src = imageURL;\n img.onload = () => {\n var ctx = this.canvasRef.current.getContext(\"2d\");\n\n //If it's the first time, we need to set the width hand height of canvas based on the image\n if (setWidthHeight) {\n this.canvasRef.current.width = img.width;\n this.canvasRef.current.height = img.height;\n }\n\n ctx.drawImage(img, 0, 0);\n ctx.save();\n }\n }",
"reset(){\n this._input = null;\n this._output = null;\n }",
"function clearCanvas() {\n context.clearRect(0, 0, canvas.width, canvas.height);\n pointCount = 0;\n drawImage();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParsernon_dml_event. | visitNon_dml_event(ctx) {
return this.visitChildren(ctx);
} | [
"visitNon_dml_trigger(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function SqlParserListener() {\n\tantlr4.tree.ParseTreeListener.call(this);\n\treturn this;\n}",
"visitSimple_dml_trigger(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}",
"visitInsert_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDel_stmt(ctx) {\r\n console.log(\"visitSivisitDel_stmt\");\r\n return { type: \"DeleteStatement\", deleted: this.visit(ctx.exprlist()) };\r\n }",
"function sql92Listener() {\n\tantlr4.tree.ParseTreeListener.call(this);\n\treturn this;\n}",
"visitDrop_logfile_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSql_operation(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCursor_manipulation_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function miniPythonParserListener() {\n\tantlr4.tree.ParseTreeListener.call(this);\n\treturn this;\n}",
"visitDml_event_nested_clause(ctx) {\n\t return this.visitChildren(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}",
"visitOn_delete_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function generateStatementList(node)\n\t{\n\t\tfor(var i = 0; i < node.children.length; i++)\n\t\t{\n\t\t\tgenerateStatement(node.children[i]);\n\t\t}\n\t}",
"visitRow_movement_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSelect_only_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSeq_of_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receives a report and saves it to database if new | function addReport(report) {
var deferred = $q.defer();
if (reportCompare(report) == -1) {
reports.push(report);
deferred.resolve('reportHandled');
}
else {
deferred.reject('report already exists');
}
// MongoDB
/*reportAPI.post({reportId: report.processId}, report).$promise.then(
function(data) {
$log.info('ReportService: Successfully posted report: ' + data.processId);
//reports.push(data);
deferred.resolve(data);
}, function(err) {
$log.error('Failed to post report: ' + err);
deferred.reject(err);
}
);*/
return deferred.promise;
} | [
"function processSaveReport(){\n var ContentFrame = findFrame(getTopWindow(),\"metricsReportContent\");\n if (ContentFrame.validateReport()){\n var footerFrame = $bmId('divPageFoot');\n pageControl.setWrapColSize(footerFrame.children[0].WrapColSize.value);\n if(pageControl.getSavedReportName() == \"\" || pageControl.getSavedReportName() == \"open .last\"){\n showModalDialog(\"emxMetricsSaveDialog.jsp\", 400, 225,true);\n }\n else if(pageControl.getOpenedLast())\n {\n showModalDialog(\"emxMetricsSaveDialog.jsp\", 400, 225,true);\n }else{\n if(confirm(STR_METRICS_SAVE_REPORT_MSG))\n {\n var result = saveReport(pageControl.getSavedReportName(),pageControl.getResultsTitle(), \"updateNotes\",\"criteriaUpdate\",pageControl.getSavedReportName());\n var hiddenFrame = findFrame(getTopWindow(),\"metricsReportHidden\");\n hiddenFrame.document.write(result);\n }\n }\n }\n}",
"save() {\n if (this.properties.saveCallback) {\n this.properties.saveCallback();\n } else if (this.properties.localStorageReportKey) {\n if ('localStorage' in window && window['localStorage'] !== null) {\n try {\n let report = this.getReport();\n // console.log(JSON.stringify(report));\n window.localStorage.setItem(this.properties.localStorageReportKey, JSON.stringify(report));\n this.modified = false;\n } catch (e) {}\n }\n }\n this.updateMenuButtons();\n }",
"function storeReport() {\n\t// Create studentReport object\n\tvar studentReport = [];\n\t// collect local storage variables\n\tstorage.get(null, function(result) {\n\t\t// get current reportsArray\n\t\t//if (result.reportsArray == null) {\n\t\t//\tvar loadedReportsArray = new Array();\n\t\t//} else {\n\t\t//\tvar loadedReportsArray = result.reportsArray;\n\t\t//};\n\t\t\t\t\n\t\tvar studentArray = {};\n\t\t\n\t\t// declare variables within the nested array with the unique names\n\t\tstudentArray['studentID'] = result.studentID;\t\n\t\tstudentArray['studentName'] = result.studentName;\n\t\tstudentArray['caretakerName'] = result.caretakerName;\n\t\tstudentArray['currentGrade'] = result.currentGrade;\n\t\tstudentArray['startYear'] = result.startYear;\n\t\tstudentArray['cohortYear'] = result.cohortYear;\n\t\tstudentArray['credits'] = result.credits;\n\t\tstudentArray['contactNumbers'] = result.contactNumbers;\n\t\tstudentArray['gradebook'] = result.gradebook;\n\t\tstudentArray['overdueLessons'] = result.overdueLessons;\n\t\tstudentArray['lastLesson'] = result.lastLesson;\n\t\tstudentArray['lastAssessment'] = result.lastAssessment;\n\t\tstudentArray['postGradPlans'] = result.postGradPlans;\n\t\tstudentArray['daysAbsent'] = result.daysAbsent;\n\t\tstudentArray['missingHours'] = result.missingHours;\n\t\tstudentArray['strengthsPLP'] = result.strengthsPLP;\n\t\tstudentArray['goalsPLP'] = result.goalsPLP;\n\t\tstudentArray['interestsPLP'] = result.interestsPLP;\n\t\t\n\t\t// Values to pull from report.html : reportType, currentMeetingDate, sspGoal, actionPlan, goalProgress, nextSteps, nextMeetingDate, addNotes\n\t\t// get current date\n\t\tstudentArray['currentMeeting'] = formatDate(document.getElementById(\"currentMeetingDate\").value);\n\t\t// get reportType\n\t\tvar initialBox = document.getElementById('initialBox');\n\t\tvar reviewBox = document.getElementById('reviewBox');\n\t\tvar finalBox = document.getElementById('finalBox');\n\t\tif (initialBox.checked == true) { studentArray['meetingType'] = 'Initial'; }\n\t\tif (reviewBox.checked == true) { studentArray['meetingType'] = 'Review'; }\n\t\tif (finalBox.checked == true) { studentArray['meetingType'] = 'Final'; }\n\t\t// get user input for textareas and next meeting date in report\n\t\tstudentArray['sspGoal'] = document.getElementById('goalTA').value;\n\t\tstudentArray['sspPlan'] = document.getElementById('planTA').value;\n\t\tstudentArray['sspProgress'] = document.getElementById('progressTA').value;\n\t\tstudentArray['sspNextSteps'] = document.getElementById('nextStepsTA').value;\n\t\tstudentArray['nextMeeting'] = formatDate(document.getElementById('nextMeetingDate').value);\n\t\tstudentArray['sspNotes'] = document.getElementById('notesTA').value;\n\n\t\tstorage.set({['SSP' + result.studentID + formatDate(document.getElementById('currentMeetingDate').value)] : studentArray});\n\t});\n\t\n\t// Code to get values from sotrage\n\tstorage.get(null, function(variables) {\n\t\tstorage.get(null, function(result) {\n\t\t\tconsole.log(result);\n\t\t});\n\t\t// Attempt to pull from local storage LOOK AT CONSOLE\n\t\tvar reportName = \"SSP\" + variables.studentID + formatDate(document.getElementById(\"currentMeetingDate\").value);\n\t\tstorage.get([reportName], function(result) {\n\t\t\tvar localArray = result;\n\t\t\tconsole.log(localArray);\n\t\t\talert(result[reportName]['studentName'] + \" Report Stored!\");\n\t\t});\n\t\t\n\t});\n\t\n\t// update popup with new student in list\n\t///////\n\t/////// Create New SSP Report\n\t///////\n\t/////// CURRENT REPORTS\n\t/////// \\/ Adam Warniment (123456)\n\t/////// - SSP_INITIAL_123456_8-9-17 X\n\t/////// - SSP_REVIEW_1234568_8-10-17 X\n\t/////// \\/ Bill Braski (9875623)\n\t/////// - SSP_INITIAL_9875623_4-8-17 X\n\t///////\n\t\n\t// Clear local storage\n}",
"function saveDataCreateReport() {\n console.log('Writing data to JSON...');\n const jsonFile = fileName(client,'results/','json');\n fs.writeFileSync(jsonFile, JSON.stringify(AllResults));\n console.log(`Created ${jsonFile}`);\n\n console.log('Creating A11y report...');\n var data = mapReportData(AllResults);\n var report = reportHTML(data, tests, client, runner, standard);\n var dateStamp = dateStamp();\n var name = `${client} Accessibility Audit ${dateStamp}`;\n\n console.log('Writing report to HTML...');\n const htmlFile = fileName(client,'reports/','html');\n fs.writeFileSync(htmlFile, report);\n console.log(`Created ${htmlFile}`);\n\n console.log('Creating Google Doc...');\n googleAPI.createGoogleDoc(name, report);\n }",
"function updateBoardReport(model, reportId) {\n console.assert(model && model.board);\n\n if (reportId === sp.result(model.board, 'boardReport.idP')) {\n return $q.when(model);\n }\n\n model.board.boardReport = reportId;\n return saveBoard(model).then(requestModel);\n }",
"function gotNewReport(report) {\n // if the map has been destroyed, do nothing\n if (!self.map || !self.$element.length || !$.contains(document, self.$element[0])) {\n return;\n }\n\n // successful request, so set timeout for next API call\n nextReqTimer = setTimeout(refreshVisits, config.liveRefreshAfterMs);\n\n // hide loading indicator\n $('.realTimeMap_overlay img').hide();\n $('.realTimeMap_overlay .loading_data').hide();\n\n // store current timestamp\n now = forceNowValue || (new Date().getTime() / 1000);\n\n if (firstRun) { // if we run this the first time, we initialiize the map symbols\n visitSymbols = map.addSymbols({\n data: [],\n type: $K.Bubble,\n /*title: function(d) {\n return visitRadius(d) > 15 && d.actions > 1 ? d.actions : '';\n },\n labelattrs: {\n fill: '#fff',\n 'font-weight': 'bold',\n 'font-size': 11,\n stroke: false,\n cursor: 'pointer'\n },*/\n sortBy: function (r) { return r.lastActionTimestamp; },\n radius: visitRadius,\n location: function (r) { return [r.longitude, r.latitude]; },\n attrs: visitSymbolAttrs,\n tooltip: visitTooltip,\n mouseenter: highlightVisit,\n mouseleave: unhighlightVisit,\n click: function (visit, mapPath, evt) {\n evt.stopPropagation();\n self.$element.trigger('mapClick', [visit, mapPath]);\n }\n });\n\n // clear existing report\n lastVisits = [];\n }\n\n if (report.length) {\n // filter results without location\n report = $.grep(report, function (r) {\n return r.latitude !== null;\n });\n }\n\n // check wether we got any geolocated visits left\n if (!report.length) {\n $('.realTimeMap_overlay .showing_visits_of').hide();\n $('.realTimeMap_overlay .no_data').show();\n return;\n } else {\n $('.realTimeMap_overlay .showing_visits_of').show();\n $('.realTimeMap_overlay .no_data').hide();\n\n if (yesterday === false) {\n yesterday = report[0].lastActionTimestamp - 24 * 60 * 60;\n }\n\n lastVisits = [].concat(report).concat(lastVisits).slice(0, maxVisits);\n oldest = Math.max(lastVisits[lastVisits.length - 1].lastActionTimestamp, yesterday);\n\n // let's try a different strategy\n // remove symbols that are too old\n var _removed = 0;\n if (removeOldVisits) {\n visitSymbols.remove(function (r) {\n if (r.lastActionTimestamp < oldest) _removed++;\n return r.lastActionTimestamp < oldest;\n });\n }\n\n // update symbols that remain\n visitSymbols.update({\n radius: function (d) { return visitSymbolAttrs(d).r; },\n attrs: visitSymbolAttrs\n }, true);\n\n // add new symbols\n var newSymbols = [];\n $.each(report, function (i, r) {\n newSymbols.push(visitSymbols.add(r));\n });\n\n visitSymbols.layout().render();\n\n if (enableAnimation) {\n $.each(newSymbols, function (i, s) {\n if (i > 10) return false;\n\n s.path.hide(); // hide new symbol at first\n var t = setTimeout(function () { animateSymbol(s); },\n 1000 * (s.data.lastActionTimestamp - now) + config.liveRefreshAfterMs);\n symbolFadeInTimer.push(t);\n });\n }\n\n lastTimestamp = report[0].lastActionTimestamp;\n\n // show\n var dur = lastTimestamp - oldest, d;\n if (dur < 60) d = dur + ' ' + _.seconds;\n else if (dur < 3600) d = Math.ceil(dur / 60) + ' ' + _.minutes;\n else d = Math.ceil(dur / 3600) + ' ' + _.hours;\n $('.realTimeMap_timeSpan').html(d);\n\n }\n firstRun = false;\n }",
"function swapReports(newReport) {\n\n var index = reportCompare(newReport);\n\n // Report exists, swap it\n if(index > -1)\n reports[index] = newReport;\n else // Report doesn't exist, add it\n reports.push(newReport);\n\n return true;\n\n }",
"processControllerReport (report) {\n const { data } = report\n this.lastReport = data.buffer\n\n // Interface is unknown\n if (this.state.interface === 'none') {\n if (data.byteLength === 63) {\n this.state.interface = 'usb'\n } else {\n this.state.interface = 'bt'\n this.device.receiveFeatureReport(0x02)\n return\n }\n }\n\n this.state.timestamp = report.timeStamp\n\n // USB Reports\n if (this.state.interface === 'usb' && report.reportId === 0x01) {\n this.updateState(data)\n }\n // Bluetooth Reports\n if (this.state.interface === 'bt' && report.reportId === 0x11) {\n this.updateState(new DataView(data.buffer, 2))\n this.device.receiveFeatureReport(0x02)\n }\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 }",
"function addSingleReportToTable(statsTable, singleReport) {\n if (!singleReport || !singleReport.values || singleReport.values.length == 0)\n return;\n\n var date = Date(singleReport.timestamp);\n updateStatsTableRow(statsTable, 'timestamp', date.toLocaleString());\n for (var i = 0; i < singleReport.values.length - 1; i = i + 2) {\n updateStatsTableRow(statsTable, singleReport.values[i],\n singleReport.values[i + 1]);\n }\n}",
"function refreshReport(event) {\n const refresher = event.target\n actions.loadReport(selectedTripId, true).finally(() => refresher.complete())\n }",
"function doCreateNewRecord() {\n Ext.Ajax.request({\n\t\t\turl: filename,\n\t\t\tmethod: 'GET',\n\t\t\tcallback: function(options, isSuccess, resp) {\n\t\t\t var xml = resp.responseText;\n\t\t\t srchResults = (new DOMParser()).parseFromString(xml, \"text/xml\");\n\t\t\t\tvar currRecord = srchResults.getElementsByTagName('record')[0];\n\t\t\t\tvar recordAsString = (new XMLSerializer().serializeToString(currRecord));\n\t\t\t\tif(bibliosdebug){ console.info('newrecord: got xml: ' + recordAsString);}\n\t\t\t\ttry {\n\t\t\t\tdb.execute('insert into Records (id, xml, status, date_added, date_modified, server, savefile) values (null, ?, ?, date(\"now\", \"localtime\"), date(\"now\", \"localtime\"), ?, null)', [recordAsString, '', 'none']);\n\t\t\t\tif(bibliosdebug == 1 ) {\n\t\t\t\t\tvar title = $('[@tag=\"245\"]/subfield[@code=\"a\"]', srchResults).text();\n\t\t\t\t\tif(bibliosdebug){console.info('inserting record with title: ' + title);}\n\t\t\t\t}\n\t\t\t\t} catch(ex) {\n\t\t\t\tExt.Msg.alert('Error', 'db error: ' + ex.message);\n\t\t\t\t}\n\t\t\t\tvar lastId = getLastRecId();\n\t\t\t\tshowStatusMsg('Opening record...');\n\t\t\t\tvar xml = getLocalXml(lastId);\n\t\t\t\topenRecord(xml);\n\t\t\t\tclearStatusMsg();\n\t\t\t\tcurrOpenRecord = lastId;\n }\n });\n}",
"function save(){\n EWD.sockets.sendMessage({\n type: \"saveLabOrder\",\n params: {\n id: \"1\",\n comment: document.getElementById(\"comment\").value,\n selectedTest: document.getElementById(\"testList\").value,\n collectionType: document.getElementById(\"collectionType\").value ,\n howOften: document.getElementById(\"howOften\").value,\n collectionDate: document.getElementById(\"collectionDate\").value,\n collectionSample: document.getElementById(\"collectionSample\").value,\n specimen: document.getElementById(\"specimen\").value,\n urgency: document.getElementById(\"urgency\").value,\n notifyProviders: document.getElementById(\"selectProvHidden\").value, \n howLong: document.getElementById(\"howLong\").value,\n sender: 'ELOM',\n date: new Date().toUTCString() \n }\n });\n }",
"submitReport() {\n console.log(\"Return Object\", this.state.formData);\n let data = {\n method: 'POST',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer ' + this.props.token,\n },\n body:\n JSON.stringify(\n this.state.formData\n )\n }\n fetch(incidentURLs.reports + 'incidents/' + this.props.id + '/reports', data)\n .then((response) => response.json())\n .then((responseJson) => {\n if (responseJson.location) {\n this.props.navigator.pop();\n Toast.show('Report was created.');\n } else {\n Toast.show('Something went wrong' + responseJson.error);\n }\n }).catch((err) => {\n console.error(\"NewReport submitReport()\", err);\n });\n }",
"_report() {\n const msg = this.schedule.name + ' since ' + moment(this.lastRun).format('YYYY-MM-DD HH:mm')\n + ':\\n'\n + this.reports.map(report => '\\u2022 ' + report.name + \": \" + (this.counts[report.name] || 0)).join('\\n');\n\n this.logger.log(this.schedule.level || 'info', msg);\n\n this.lastRun = Date.now();\n this.counts = {};\n this._schedule();\n }",
"function drawSingleReport(peerConnectionElement, report) {\n var reportType = report.type;\n var reportId = report.id;\n var stats = report.stats;\n if (!stats || !stats.values)\n return;\n\n for (var i = 0; i < stats.values.length - 1; i = i + 2) {\n var rawLabel = stats.values[i];\n // Propagation deltas are handled separately.\n if (rawLabel == RECEIVED_PROPAGATION_DELTA_LABEL) {\n drawReceivedPropagationDelta(\n peerConnectionElement, report, stats.values[i + 1]);\n continue;\n }\n var rawDataSeriesId = reportId + '-' + rawLabel;\n var rawValue = getNumberFromValue(rawLabel, stats.values[i + 1]);\n if (isNaN(rawValue)) {\n // We do not draw non-numerical values, but still want to record it in the\n // data series.\n addDataSeriesPoints(peerConnectionElement,\n rawDataSeriesId,\n rawLabel,\n [stats.timestamp],\n [stats.values[i + 1]]);\n continue;\n }\n\n var finalDataSeriesId = rawDataSeriesId;\n var finalLabel = rawLabel;\n var finalValue = rawValue;\n // We need to convert the value if dataConversionConfig[rawLabel] exists.\n if (dataConversionConfig[rawLabel]) {\n // Updates the original dataSeries before the conversion.\n addDataSeriesPoints(peerConnectionElement,\n rawDataSeriesId,\n rawLabel,\n [stats.timestamp],\n [rawValue]);\n\n // Convert to another value to draw on graph, using the original\n // dataSeries as input.\n finalValue = dataConversionConfig[rawLabel].convertFunction(\n peerConnectionDataStore[peerConnectionElement.id].getDataSeries(\n rawDataSeriesId));\n finalLabel = dataConversionConfig[rawLabel].convertedName;\n finalDataSeriesId = reportId + '-' + finalLabel;\n }\n\n // Updates the final dataSeries to draw.\n addDataSeriesPoints(peerConnectionElement,\n finalDataSeriesId,\n finalLabel,\n [stats.timestamp],\n [finalValue]);\n\n // Updates the graph.\n var graphType = bweCompoundGraphConfig[finalLabel] ?\n 'bweCompound' : finalLabel;\n var graphViewId =\n peerConnectionElement.id + '-' + reportId + '-' + graphType;\n\n if (!graphViews[graphViewId]) {\n graphViews[graphViewId] = createStatsGraphView(peerConnectionElement,\n report,\n graphType);\n var date = new Date(stats.timestamp);\n graphViews[graphViewId].setDateRange(date, date);\n }\n // Adds the new dataSeries to the graphView. We have to do it here to cover\n // both the simple and compound graph cases.\n var dataSeries =\n peerConnectionDataStore[peerConnectionElement.id].getDataSeries(\n finalDataSeriesId);\n if (!graphViews[graphViewId].hasDataSeries(dataSeries))\n graphViews[graphViewId].addDataSeries(dataSeries);\n graphViews[graphViewId].updateEndDate();\n }\n}",
"saveGoal(data) {\n let goal = this.get('store').createRecord('goal', data);\n goal.save()\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}",
"function onReportClick(e) {\n\tcommonFunctions.sendScreenshot();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
2 Use a while loop to build a single string with the numbers 1 through n separated by the number next to the current number. Have it return the new string. eg= 1 2 2 3 3 4 4 5 5 6 6 ... | function string(n){
var i =0;
while(i<n){
i++;
return i," ",n;
}
} | [
"function numberJoinerFancy(startNum, endNum, separator) {\n let newString = ''\n for(let i = startNum; i <= endNum -1; i++) {\n newString += `${i}${separator}`\n }if(i = endNum) {\n newString += `${i}`\n }\n return newString\n}",
"function repeat(input, n){\n var output = ''\n for(var i = 0; i < n; i++){\n output = output + input\n }\n return output\n }",
"function solve(s, n) {\n let sArr = s.split('')\n let strings = []\n for(let i = 0; i < s.length; i+=n){\n strings.push(sArr.slice(i, n+i).join(''))\n console.log(strings)\n }\n return strings\n}",
"function integerTostring(number) {\n let numberArry = [];\n do {\n let remainder = number % 10; //the last number to the array \n number = Math.floor(number / 10); // remove the last number and prepare a new number for next loop\n \n numberArry.push(remainder); //the last number to the array \n \n } while (number > 0);\n \n return numberArry.reverse().join(''); //because of push method, the array needs to be reversed \n}",
"function concat(string, n) {\n n = n || 1;\n var con = '';\n for (var i = 0; i < n; i++) {\n con += string;\n }\n return con;\n}",
"function numberIterator(num) {\n if (num == 0) return '0';\n return numberIterator(num-1) +''+ num;\n}",
"function createString(number, letter) {\n var newString = \"\";\n for (i = 1; i <= number; i++) {\n newString += letter;\n\n }\n return newString;\n}",
"function createString(number,letter){\n let result = \"\"\n for (let i=0; i<number; i++){\n result +=letter\n }\n return result\n}",
"function composeRanges(nums) {\n\n let stringArr = [];\n let firstNum = nums[0];\n let prevNum = nums[0];\n let currStr = `${nums[0]}`;\n\n if(nums.length === 0){\n return [];\n }\n\n for(let x = 1; x < nums.length; x++){\n\n if(nums[x] - 1 === prevNum){\n currStr = `${firstNum}->${nums[x]}`;\n\n } else {\n stringArr.push(currStr);\n currStr = `${nums[x]}`;\n firstNum = nums[x];\n }\n\n prevNum = nums[x];\n }\n\n stringArr.push(currStr);\n\n return stringArr;\n}",
"function listOfNumbers(countTo, countBy) {\n\n var list = \"\";\n\n for (var number = countBy; number <= countTo; number += countBy) {\n list += number;\n if (number + countBy <= countTo) {\n list += \", \";\n }\n }\n return list;\n}",
"function print34to41() {\n const array = []\n for(let i = 34; i < 42; i++) {\n array.push(i);\n }\n return array.map(item => `<p class=\"output\">${item}</p>`).join(\"\");\n}",
"function seperateComma(number) {\n var stringNumber = number.toString().split(\"\");\n var indexOfLastNumber = stringNumber.length;\n\n for (var counter = 3; counter <= indexOfLastNumber ; counter += 3 ) {\n var slices = indexOfLastNumber - counter;\n var numWithCommas = stringNumber.splice(slices, 0 ,\",\");\n var returnToString = numWithCommas.join();\n };\n console.log(stringNumber.join(\"\"));\n}",
"function repeatStringNumTimes(string, times) {\n// Create an empty string to host the repeated string\nvar repeatedString = \"\";\n//Step 2, set the while loop with (times > 0) as the condition to check\nwhile (times > 0) { //as long as times is greater than 0, statement is executed\n repeatedString += string; // repeatedString = repeatedString + string;\n times-- ;\n}\n\n// Step 3 return the repeated String\nreturn repeatedString;\n}",
"function printOddFrom10To1() {\n const array = []\n for(let i = 10 ; 0 < i ; i--) {\n if (i % 2 === 1) {\n array.push(i);\n } \n }\n return array.map(item => `<p class=\"output\">${item}</p>`).join(\"\");\n}",
"function countUpAndDown(num){\n let n = ''\n for(var i = 1; i <= num; i++){\n n += i\n }\n for(var i = num-1 ; i > 0; i--){\n n += i\n }\n console.log(n);\n\n}",
"function collatz(n){\n var result = [n]\n var resultString = '' + n + '-> '\n console.log(resultString)\n while (result[result.length-1] > 1){\n if ( result[result.length-1]%2 !== 0){\n result.push((result[result.length-1]*3)+1)\n resultString += ((result[result.length-1]*3)+1) + '->'\n console.log(resultString)\n } else {\n result.push(result[result.length-1]/2)\n resultString+= (result[result.length-1]/2) +'->'\n }\n// console.log(result)\n// console.log(resultString)\n }\n return result.toString().replace(/,/g, '->')\n}",
"function create(n){\n var n;\n var arr = [];\n for (i=1; i<=n; i++){\n if (i%2==0 && i%3==0 && i%5==0){\n arr.push(\"yu-gi-oh\");\n }else if (i%2==0 && i%3==0){\n arr.push(\"yu-gi\");\n }else if (i%2==0 && i%5==0){\n arr.push(\"yu-oh\");\n } else if (i%3==0 && i%5==0){\n arr.push(\"gi-oh\");\n } else if (i%5==0){\n arr.push(\"oh\");\n } else if (i%3==0){\n arr.push(\"gi\");\n } else if (i%2==0){\n arr.push(\"yu\");\n } \n else{\n arr.push(i);\n }\n console.log(arr);\n }\n return arr;\n }",
"function generatePattern(n) {\n var number = '';\n var asterisks = '';\n \n for (var i = 1; i <= n; i++) {\n // sets number of asterisks for specific row\n for (var j = n - i; j > 0; j--) {\n asterisks += '*';\n }\n // every time through loop another number gets added on\n number += i;\n console.log(number + asterisks);\n // resets asterisks so it can be looped again\n asterisks = '';\n }\n \n}",
"function twelveBarBlues(){\n var string = \"chick\\nboom\\nchick\";\n for(var i = 1; i <= 12; i++){\n console.log(i + \"\\n\" + string);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
v6 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"]) | function v7(v8) {
const v13 = [13.37,1337,1337];
// v13 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
const v14 = [1337,v13,v13,v13,1337,1337,-9007199254740991,"bigint",-9007199254740991];
// v14 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
const v15 = {c:v13,constructor:13.37,d:"bigint",e:1337,length:v14,toString:v13,valueOf:1337};
// v15 = .object(ofGroup: Object, withProperties: ["valueOf", "c", "length", "__proto__", "d", "constructor", "toString", "e"])
function v16(v17,v18,v19,v20,v21) {
}
const v23 = [1337,1337,1337,1337,1337];
// v23 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
function v25(v26,v27) {
const v29 = {get:v26,set:v25};
// v29 = .object(ofGroup: Object, withProperties: ["__proto__"], withMethods: ["get", "set"])
const v31 = Object.defineProperty(v15,"__proto__",v29);
// v31 = .undefined
const v33 = [13.37,13.37];
// v33 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
function v34(v35,v36) {
const v37 = v36 + 1;
// v37 = .primitive
return v33;
}
const v38 = v34(v34,v34);
// v38 = .unknown
let v41 = 13.37;
function v42(v43,v44) {
const v47 = [v38,108978604,108978604,108978604];
// v47 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
let v48 = v47;
const v49 = (10).toLocaleString();
// v49 = .unknown
const v50 = v48.join(v49);
// v50 = .string + .object(ofGroup: String, withProperties: ["constructor", "__proto__", "length"], withMethods: ["padEnd", "split", "charAt", "match", "lastIndexOf", "charCodeAt", "trim", "startsWith", "includes", "repeat", "search", "slice", "endsWith", "matchAll", "indexOf", "concat", "replace", "padStart", "substring", "codePointAt"])
const v51 = eval(v50);
// v51 = .string + .object(ofGroup: String, withProperties: ["constructor", "__proto__", "length"], withMethods: ["padEnd", "split", "charAt", "match", "lastIndexOf", "charCodeAt", "trim", "startsWith", "includes", "repeat", "search", "slice", "endsWith", "matchAll", "indexOf", "concat", "replace", "padStart", "substring", "codePointAt"])
return 1337;
}
const v52 = v42(v42,v41);
// v52 = .unknown
v23[8] = v27;
const v56 = [13.37,13.37,13.37,13.37];
// v56 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
const v58 = [Int16Array,1392904795,v56,13.37,1337];
// v58 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
function v59(v60,v61) {
let v66 = 100;
const v69 = new Int8Array(127);
// v69 = .object(ofGroup: Int8Array, withProperties: ["byteLength", "constructor", "length", "__proto__", "buffer", "byteOffset"], withMethods: ["reduce", "copyWithin", "findIndex", "entries", "lastIndexOf", "map", "set", "includes", "indexOf", "sort", "some", "reverse", "keys", "reduceRight", "values", "filter", "forEach", "slice", "subarray", "join", "fill", "find", "every"])
const v70 = v69.indexOf(v66);
// v70 = .integer
const v73 = "sO0KQ7OSCy".indexOf(0,-65535);
// v73 = .integer
let v74 = v73;
const v76 = typeof v16;
// v76 = .string
const v78 = v76 === "number";
// v78 = .boolean
function v79(v80,v81) {
const v82 = 0;
// v82 = .integer
const v83 = 4;
// v83 = .integer
const v84 = 1;
// v84 = .integer
function v85(v86,v87) {
return v56;
}
const v89 = {constructor:-4294967295};
// v89 = .object(ofGroup: Object, withProperties: ["constructor", "__proto__"])
let v90 = -4294967295;
const v91 = -2285213110;
// v91 = .integer
const v92 = Uint8Array;
// v92 = .constructor([.integer | .object()] => .object(ofGroup: Uint8Array, withProperties: ["byteLength", "byteOffset", "constructor", "length", "buffer", "__proto__"], withMethods: ["includes", "join", "slice", "copyWithin", "filter", "lastIndexOf", "entries", "every", "fill", "reverse", "keys", "map", "subarray", "indexOf", "reduceRight", "forEach", "some", "find", "set", "findIndex", "sort", "reduce", "values"]))
const v93 = v81 instanceof v85;
// v93 = .boolean
for (let v97 = 13.37; v97 < 512; v97 = v97 + 1) {
}
function v98(v99,v100) {
return v81;
}
return v81;
}
function v101(v102,v103) {
const v105 = -506317353;
// v105 = .integer
const v107 = Uint32Array(0);
// v107 = .unknown
const v108 = Uint32Array(0);
// v108 = .unknown
const v111 = Int16Array;
// v111 = .constructor([.integer | .object()] => .object(ofGroup: Int16Array, withProperties: ["buffer", "byteLength", "constructor", "byteOffset", "length", "__proto__"], withMethods: ["some", "includes", "every", "set", "reduce", "reduceRight", "forEach", "join", "lastIndexOf", "values", "filter", "fill", "indexOf", "map", "find", "slice", "subarray", "copyWithin", "reverse", "sort", "entries", "keys", "findIndex"]))
const v113 = [13.37,13.37];
// v113 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
const v114 = [v101,126905259,noFTL,126905259,126905259];
// v114 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
const v115 = v5.map(isNaN);
// v115 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"])
let v117 = 0;
const v118 = v117 + 1;
// v118 = .primitive
v117 = v118;
const v119 = {__proto__:noFTL,b:v114,constructor:noFTL,length:v113};
// v119 = .object(ofGroup: Object, withProperties: ["length", "b", "__proto__"], withMethods: ["constructor", "__proto__"])
for (let v121 = v108; v121 < 100; v121 = v121 + "2147483648") {
}
}
let v122 = 0;
do {
} while (v122 < 5);
}
const v125 = "function".padStart(1337,v25);
// v125 = .string + .object(ofGroup: String, withProperties: ["constructor", "__proto__", "length"], withMethods: ["padEnd", "split", "charAt", "match", "lastIndexOf", "charCodeAt", "trim", "startsWith", "includes", "repeat", "search", "slice", "endsWith", "matchAll", "indexOf", "concat", "replace", "padStart", "substring", "codePointAt"])
const v126 = Function(v125);
// v126 = .unknown
}
const v128 = new Promise(v25);
// v128 = .object(ofGroup: Promise, withProperties: ["__proto__"], withMethods: ["finally", "then", "catch"])
} | [
"function v25(v26,v27) {\n const v29 = {get:v26,set:v25};\n // v29 = .object(ofGroup: Object, withProperties: [\"__proto__\"], withMethods: [\"get\", \"set\"])\n const v31 = Object.defineProperty(v15,\"__proto__\",v29);\n // v31 = .undefined\n const v33 = [13.37,13.37];\n // v33 = .object(ofGroup: Array, withProperties: [\"length\", \"__proto__\", \"constructor\"], withMethods: [\"concat\", \"fill\", \"indexOf\", \"entries\", \"forEach\", \"find\", \"reverse\", \"slice\", \"flat\", \"reduce\", \"join\", \"findIndex\", \"reduceRight\", \"some\", \"copyWithin\", \"toString\", \"pop\", \"filter\", \"map\", \"splice\", \"keys\", \"unshift\", \"sort\", \"includes\", \"flatMap\", \"shift\", \"values\", \"every\", \"toLocaleString\", \"push\", \"lastIndexOf\"])\n function v34(v35,v36) {\n const v37 = v36 + 1;\n // v37 = .primitive\n return v33;\n }\n const v38 = v34(v34,v34);\n // v38 = .unknown\n let v41 = 13.37;\n function v42(v43,v44) {\n const v47 = [v38,108978604,108978604,108978604];\n // v47 = .object(ofGroup: Array, withProperties: [\"length\", \"__proto__\", \"constructor\"], withMethods: [\"concat\", \"fill\", \"indexOf\", \"entries\", \"forEach\", \"find\", \"reverse\", \"slice\", \"flat\", \"reduce\", \"join\", \"findIndex\", \"reduceRight\", \"some\", \"copyWithin\", \"toString\", \"pop\", \"filter\", \"map\", \"splice\", \"keys\", \"unshift\", \"sort\", \"includes\", \"flatMap\", \"shift\", \"values\", \"every\", \"toLocaleString\", \"push\", \"lastIndexOf\"])\n let v48 = v47;\n const v49 = (10).toLocaleString();\n // v49 = .unknown\n const v50 = v48.join(v49);\n // v50 = .string + .object(ofGroup: String, withProperties: [\"constructor\", \"__proto__\", \"length\"], withMethods: [\"padEnd\", \"split\", \"charAt\", \"match\", \"lastIndexOf\", \"charCodeAt\", \"trim\", \"startsWith\", \"includes\", \"repeat\", \"search\", \"slice\", \"endsWith\", \"matchAll\", \"indexOf\", \"concat\", \"replace\", \"padStart\", \"substring\", \"codePointAt\"])\n const v51 = eval(v50);\n // v51 = .string + .object(ofGroup: String, withProperties: [\"constructor\", \"__proto__\", \"length\"], withMethods: [\"padEnd\", \"split\", \"charAt\", \"match\", \"lastIndexOf\", \"charCodeAt\", \"trim\", \"startsWith\", \"includes\", \"repeat\", \"search\", \"slice\", \"endsWith\", \"matchAll\", \"indexOf\", \"concat\", \"replace\", \"padStart\", \"substring\", \"codePointAt\"])\n return 1337;\n }\n const v52 = v42(v42,v41);\n // v52 = .unknown\n v23[8] = v27;\n const v56 = [13.37,13.37,13.37,13.37];\n // v56 = .object(ofGroup: Array, withProperties: [\"length\", \"__proto__\", \"constructor\"], withMethods: [\"concat\", \"fill\", \"indexOf\", \"entries\", \"forEach\", \"find\", \"reverse\", \"slice\", \"flat\", \"reduce\", \"join\", \"findIndex\", \"reduceRight\", \"some\", \"copyWithin\", \"toString\", \"pop\", \"filter\", \"map\", \"splice\", \"keys\", \"unshift\", \"sort\", \"includes\", \"flatMap\", \"shift\", \"values\", \"every\", \"toLocaleString\", \"push\", \"lastIndexOf\"])\n const v58 = [Int16Array,1392904795,v56,13.37,1337];\n // v58 = .object(ofGroup: Array, withProperties: [\"length\", \"__proto__\", \"constructor\"], withMethods: [\"concat\", \"fill\", \"indexOf\", \"entries\", \"forEach\", \"find\", \"reverse\", \"slice\", \"flat\", \"reduce\", \"join\", \"findIndex\", \"reduceRight\", \"some\", \"copyWithin\", \"toString\", \"pop\", \"filter\", \"map\", \"splice\", \"keys\", \"unshift\", \"sort\", \"includes\", \"flatMap\", \"shift\", \"values\", \"every\", \"toLocaleString\", \"push\", \"lastIndexOf\"])\n function v59(v60,v61) {\n let v66 = 100;\n const v69 = new Int8Array(127);\n // v69 = .object(ofGroup: Int8Array, withProperties: [\"byteLength\", \"constructor\", \"length\", \"__proto__\", \"buffer\", \"byteOffset\"], withMethods: [\"reduce\", \"copyWithin\", \"findIndex\", \"entries\", \"lastIndexOf\", \"map\", \"set\", \"includes\", \"indexOf\", \"sort\", \"some\", \"reverse\", \"keys\", \"reduceRight\", \"values\", \"filter\", \"forEach\", \"slice\", \"subarray\", \"join\", \"fill\", \"find\", \"every\"])\n const v70 = v69.indexOf(v66);\n // v70 = .integer\n const v73 = \"sO0KQ7OSCy\".indexOf(0,-65535);\n // v73 = .integer\n let v74 = v73;\n const v76 = typeof v16;\n // v76 = .string\n const v78 = v76 === \"number\";\n // v78 = .boolean\n function v79(v80,v81) {\n const v82 = 0;\n // v82 = .integer\n const v83 = 4;\n // v83 = .integer\n const v84 = 1;\n // v84 = .integer\n function v85(v86,v87) {\n return v56;\n }\n const v89 = {constructor:-4294967295};\n // v89 = .object(ofGroup: Object, withProperties: [\"constructor\", \"__proto__\"])\n let v90 = -4294967295;\n const v91 = -2285213110;\n // v91 = .integer\n const v92 = Uint8Array;\n // v92 = .constructor([.integer | .object()] => .object(ofGroup: Uint8Array, withProperties: [\"byteLength\", \"byteOffset\", \"constructor\", \"length\", \"buffer\", \"__proto__\"], withMethods: [\"includes\", \"join\", \"slice\", \"copyWithin\", \"filter\", \"lastIndexOf\", \"entries\", \"every\", \"fill\", \"reverse\", \"keys\", \"map\", \"subarray\", \"indexOf\", \"reduceRight\", \"forEach\", \"some\", \"find\", \"set\", \"findIndex\", \"sort\", \"reduce\", \"values\"]))\n const v93 = v81 instanceof v85;\n // v93 = .boolean\n for (let v97 = 13.37; v97 < 512; v97 = v97 + 1) {\n }\n function v98(v99,v100) {\n return v81;\n }\n return v81;\n }\n function v101(v102,v103) {\n const v105 = -506317353;\n // v105 = .integer\n const v107 = Uint32Array(0);\n // v107 = .unknown\n const v108 = Uint32Array(0);\n // v108 = .unknown\n const v111 = Int16Array;\n // v111 = .constructor([.integer | .object()] => .object(ofGroup: Int16Array, withProperties: [\"buffer\", \"byteLength\", \"constructor\", \"byteOffset\", \"length\", \"__proto__\"], withMethods: [\"some\", \"includes\", \"every\", \"set\", \"reduce\", \"reduceRight\", \"forEach\", \"join\", \"lastIndexOf\", \"values\", \"filter\", \"fill\", \"indexOf\", \"map\", \"find\", \"slice\", \"subarray\", \"copyWithin\", \"reverse\", \"sort\", \"entries\", \"keys\", \"findIndex\"]))\n const v113 = [13.37,13.37];\n // v113 = .object(ofGroup: Array, withProperties: [\"length\", \"__proto__\", \"constructor\"], withMethods: [\"concat\", \"fill\", \"indexOf\", \"entries\", \"forEach\", \"find\", \"reverse\", \"slice\", \"flat\", \"reduce\", \"join\", \"findIndex\", \"reduceRight\", \"some\", \"copyWithin\", \"toString\", \"pop\", \"filter\", \"map\", \"splice\", \"keys\", \"unshift\", \"sort\", \"includes\", \"flatMap\", \"shift\", \"values\", \"every\", \"toLocaleString\", \"push\", \"lastIndexOf\"])\n const v114 = [v101,126905259,noFTL,126905259,126905259];\n // v114 = .object(ofGroup: Array, withProperties: [\"length\", \"__proto__\", \"constructor\"], withMethods: [\"concat\", \"fill\", \"indexOf\", \"entries\", \"forEach\", \"find\", \"reverse\", \"slice\", \"flat\", \"reduce\", \"join\", \"findIndex\", \"reduceRight\", \"some\", \"copyWithin\", \"toString\", \"pop\", \"filter\", \"map\", \"splice\", \"keys\", \"unshift\", \"sort\", \"includes\", \"flatMap\", \"shift\", \"values\", \"every\", \"toLocaleString\", \"push\", \"lastIndexOf\"])\n const v115 = v5.map(isNaN);\n // v115 = .object(ofGroup: Array, withProperties: [\"length\", \"__proto__\", \"constructor\"], withMethods: [\"concat\", \"fill\", \"indexOf\", \"entries\", \"forEach\", \"find\", \"reverse\", \"slice\", \"flat\", \"reduce\", \"join\", \"findIndex\", \"reduceRight\", \"some\", \"copyWithin\", \"toString\", \"pop\", \"filter\", \"map\", \"splice\", \"keys\", \"unshift\", \"sort\", \"includes\", \"flatMap\", \"shift\", \"values\", \"every\", \"toLocaleString\", \"push\", \"lastIndexOf\"])\n let v117 = 0;\n const v118 = v117 + 1;\n // v118 = .primitive\n v117 = v118;\n const v119 = {__proto__:noFTL,b:v114,constructor:noFTL,length:v113};\n // v119 = .object(ofGroup: Object, withProperties: [\"length\", \"b\", \"__proto__\"], withMethods: [\"constructor\", \"__proto__\"])\n for (let v121 = v108; v121 < 100; v121 = v121 + \"2147483648\") {\n }\n }\n let v122 = 0;\n do {\n } while (v122 < 5);\n }\n const v125 = \"function\".padStart(1337,v25);\n // v125 = .string + .object(ofGroup: String, withProperties: [\"constructor\", \"__proto__\", \"length\"], withMethods: [\"padEnd\", \"split\", \"charAt\", \"match\", \"lastIndexOf\", \"charCodeAt\", \"trim\", \"startsWith\", \"includes\", \"repeat\", \"search\", \"slice\", \"endsWith\", \"matchAll\", \"indexOf\", \"concat\", \"replace\", \"padStart\", \"substring\", \"codePointAt\"])\n const v126 = Function(v125);\n // v126 = .unknown\n }",
"get groupsObject () {\n const result = {}\n for (const [key, val] of this.groups) {\n result[key] = Array.from(val)\n }\n return result\n }",
"static groupBy(f, arr) {\n let result = {};\n arr.forEach(e => {\n if (f(e) in result) {\n result[f(e)].push(e);\n } else {\n result[f(e)] = [e];\n }\n });\n return result;\n }",
"function asObjectFactory(groups) {\n return () => {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const obj = {};\n for (const group of groups) {\n if (isObjectAssignable(group.key)) {\n obj[group.key] = group.items;\n }\n }\n return obj;\n };\n}",
"function asArraysFactory(groups) {\n return () => {\n return groups.map((g) => g.items);\n };\n}",
"function group(items) {\n const by = (key) => {\n // create grouping with resolved keying function\n const keyFn = typeof key === 'function' ? key : (item) => item[key];\n const groups = createGrouping(items, keyFn);\n // return collectors\n return Object.freeze({\n asArrays: (0, as_arrays_js_1.asArraysFactory)(groups),\n asEntries: (0, as_entries_js_1.asEntriesFactory)(groups),\n asMap: (0, as_map_js_1.asMapFactory)(groups),\n asObject: (0, as_object_js_1.asObjectFactory)(groups),\n asTuples: (0, as_tuples_js_1.asTuplesFactory)(groups),\n keys: (0, keys_js_1.keysFactory)(groups)\n });\n };\n return Object.freeze({ by });\n}",
"function classifyingNumbers() {\n let array = [1, 2, 3, 4, 5];\n let object = {...[1, 2, 3, 4, 5]};\n return object;\n}",
"static fromJSON(groups) {\n let result = [];\n \n if (Array.isArray(groups)) {\n groups.forEach((g) => {\n Object.setPrototypeOf(g, GroupBO.prototype);\n result.push(g)\n })\n } else {\n let g = groups;\n Object.setPrototypeOf(g, GroupBO.prototype);\n result.push(g)\n }\n\n return result;\n }",
"function separateGroup(group) {\n var inputs = [];\n var components = [];\n var outputs = [];\n for (var i = 0; i < group.length; i++) {\n var object = group[i];\n if (object instanceof Switch || object instanceof Button || object instanceof Clock)\n inputs.push(object);\n else if (object instanceof LED)\n outputs.push(object);\n else\n components.push(object);\n }\n return {inputs:inputs, components:components, outputs:outputs};\n}",
"function convert(array) {\n return array.reduce((acc, layer) => {\n //console.log(layer.getProperties().group);\n acc.push({\n layer: layer,\n name: layer.getProperties().name,\n title: layer.getProperties().title,\n visibility: layer.getProperties().visible,\n group: layer.getProperties().group\n });\n return acc;\n }, []);\n}",
"function asEntriesFactory(groups) {\n return ((options) => {\n var _a, _b;\n const keyName = (_a = options === null || options === void 0 ? void 0 : options.keyName) !== null && _a !== void 0 ? _a : 'key';\n const itemsName = (_b = options === null || options === void 0 ? void 0 : options.itemsName) !== null && _b !== void 0 ? _b : 'items';\n return groups.map((g) => ({\n [keyName]: g.key,\n [itemsName]: g.items\n }));\n });\n}",
"getCalendarGroups() {\n return Object.keys(this.groupCalendars).map(id => ({ id }));\n }",
"_groupVitamins () {\n let mini, maxi;\n\n this.groups = {};\n this.vitamins.forEach(vit => {\n if (! this.groups[vit.color]) this.groups[vit.color] = { vitamins: [], mini: null, maxi: null };\n\n // Set mini in color group\n mini = this.groups[vit.color].mini;\n if (! mini || vit.size < mini) {\n this.groups[vit.color].mini = vit.size;\n }\n\n // Set maxi in color group\n maxi = this.groups[vit.color].maxi;\n if (! maxi || vit.size > maxi) {\n this.groups[vit.color].maxi = vit.size;\n }\n\n this.groups[vit.color].vitamins.push(vit);\n });\n\n // Create the empty groups with no vitamins\n Object.values(Vitamin.COLORS).forEach(color => {\n if (! this.groups[color]) {\n this.groups[color] = { vitamins: [], mini: null, maxi: null };\n // console.log(Texts.EMPTY_GROUP(color));\n }\n });\n\n //console.log('Grouped by colors:', this.groups);\n }",
"getCommandsByGroup() {\n const groupsToCommand = {\n \"movement\": [],\n \"editing\": [],\n \"selection\": [],\n \"tabs\": [],\n \"formatting\": [],\n \"other\": [],\n };\n\n for (const [key, command] of Object.entries(Commands.commands)) {\n groupsToCommand[command.group].push(key);\n }\n return groupsToCommand;\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 TransformGroup() {\n _classCallCheck(this, TransformGroup);\n\n var _this5 = _possibleConstructorReturn(this, (TransformGroup.__proto__ || Object.getPrototypeOf(TransformGroup)).call(this));\n\n _this5.transforms = [];\n return _this5;\n }",
"function collectGroups(groups) {\n let name = \"\"\n let tags = new Set()\n for (let group of groups) {\n name += `[${group.name}]+`\n collect(tags, group.tags)\n }\n\n name = name.substring(0, name.length - 1)\n \n return new Group(name, tags)\n}",
"facetComplexItems(aItems) {\n let attrKey = this.attrDef.boundName;\n let filter = this.facetDef.filter;\n let idAttr = this.facetDef.groupIdAttr;\n\n let groups = (this.groups = {});\n let groupMap = (this.groupMap = {});\n this.groupCount = 0;\n\n for (let item of aItems) {\n let vals = attrKey in item ? item[attrKey] : null;\n if (vals === Gloda.IGNORE_FACET) {\n continue;\n }\n\n if (vals == null || vals.length == 0) {\n vals = [null];\n }\n for (let val of vals) {\n // skip items the filter tells us to ignore\n if (filter && !filter(val)) {\n continue;\n }\n\n let valId = val == null ? null : val[idAttr];\n // We need to use hasOwnProperty because tag nouns are complex objects\n // with id's that are non-numeric and so can collide with the contents\n // of Object.prototype.\n if (groupMap.hasOwnProperty(valId)) {\n groups[valId].push(item);\n } else {\n groupMap[valId] = val;\n groups[valId] = [item];\n this.groupCount++;\n }\n }\n }\n\n let orderedGroups = Object.keys(groups).map(key => [\n groupMap[key],\n groups[key],\n ]);\n let comparator = this.facetDef.groupComparator;\n function comparatorHelper(a, b) {\n return comparator(a[0], b[0]);\n }\n orderedGroups.sort(comparatorHelper);\n this.orderedGroups = orderedGroups;\n }",
"asArray() {\n return Array.from(this);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies the content from this page to the supplied page instance NOTE: fully overwriting any previous content!! | async copyTo(page, publish = true) {
// we know the method is on the class - but it is protected so not part of the interface
page.setControls(this.getControls());
// copy page properties
if (this._layoutPart.properties) {
if (hOP(this._layoutPart.properties, "topicHeader")) {
page.topicHeader = this._layoutPart.properties.topicHeader;
}
if (hOP(this._layoutPart.properties, "imageSourceType")) {
page._layoutPart.properties.imageSourceType = this._layoutPart.properties.imageSourceType;
}
if (hOP(this._layoutPart.properties, "layoutType")) {
page._layoutPart.properties.layoutType = this._layoutPart.properties.layoutType;
}
if (hOP(this._layoutPart.properties, "textAlignment")) {
page._layoutPart.properties.textAlignment = this._layoutPart.properties.textAlignment;
}
if (hOP(this._layoutPart.properties, "showTopicHeader")) {
page._layoutPart.properties.showTopicHeader = this._layoutPart.properties.showTopicHeader;
}
if (hOP(this._layoutPart.properties, "showPublishDate")) {
page._layoutPart.properties.showPublishDate = this._layoutPart.properties.showPublishDate;
}
if (hOP(this._layoutPart.properties, "enableGradientEffect")) {
page._layoutPart.properties.enableGradientEffect = this._layoutPart.properties.enableGradientEffect;
}
}
// we need to do some work to set the banner image url in the copied page
if (!stringIsNullOrEmpty(this.json.BannerImageUrl)) {
// use a URL to parse things for us
const url = new URL(this.json.BannerImageUrl);
// helper function to translate the guid strings into properly formatted guids with dashes
const makeGuid = (s) => s.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/g, "$1-$2-$3-$4-$5");
// protect against errors because the serverside impl has changed, we'll just skip
if (url.searchParams.has("guidSite") && url.searchParams.has("guidWeb") && url.searchParams.has("guidFile")) {
const guidSite = makeGuid(url.searchParams.get("guidSite"));
const guidWeb = makeGuid(url.searchParams.get("guidWeb"));
const guidFile = makeGuid(url.searchParams.get("guidFile"));
const site = Site(this);
const id = await site.select("Id")();
// the site guid must match the current site's guid or we are unable to set the image
if (id.Id === guidSite) {
const openWeb = await site.openWebById(guidWeb);
const file = await openWeb.web.getFileById(guidFile).select("ServerRelativeUrl")();
const props = {};
if (this._layoutPart.properties) {
if (hOP(this._layoutPart.properties, "translateX")) {
props.translateX = this._layoutPart.properties.translateX;
}
if (hOP(this._layoutPart.properties, "translateY")) {
props.translateY = this._layoutPart.properties.translateY;
}
if (hOP(this._layoutPart.properties, "imageSourceType")) {
props.imageSourceType = this._layoutPart.properties.imageSourceType;
}
if (hOP(this._layoutPart.properties, "altText")) {
props.altText = this._layoutPart.properties.altText;
}
}
page.setBannerImage(file.ServerRelativeUrl, props);
}
}
}
await page.save(publish);
return page;
} | [
"addToPage(page) {\n // Get all of the properties and functions on this component\n const componentProperties = Object.getOwnPropertyNames(this);\n const componentFunctions = Object.getOwnPropertyNames(Object.getPrototypeOf(this));\n const componentPropertiesAndFunctions = componentProperties.concat(componentFunctions);\n\n // Filter out things we don't want to copy\n const ignoreList = ['I', 'constructor', 'create', 'addToPage'];\n const propertiesAndFunctionsToCopy = componentPropertiesAndFunctions.filter(p => !ignoreList.includes(p));\n\n // Copy properties and functions on the component to the page\n propertiesAndFunctionsToCopy.forEach(p => page[p] = this[p]);\n }",
"function saveContentEdit(_data){\n var docu = new DOMParser().parseFromString('<content></content>', \"application/xml\")\n var newCDATA=docu.createCDATASection(_data);\n $(data).find(\"page\").eq(currentPage).find(\"content\").first().empty();\n $(data).find(\"page\").eq(currentPage).find(\"content\").first().append(newCDATA);\n $(data).find(\"page\").eq(currentPage).attr(\"review\", review);\n sendUpdate();\n }",
"function addPage(page) {\n document.querySelector(\"#pages\").innerHTML += `\n <section id=\"${page.slug}\" class=\"page\">\n ${page.content.rendered}\n </section>\n `;\n}",
"function appendPage(pageNode)\n\t\t\t{\n\t\t\t\tvar models = pageNode.getElementsByTagName('mxGraphModel');\n\t\t\t\tvar modelNode = (models.length > 0) ? models[0] : null;\n\t\t\t\tvar clone = pageNode;\n\t\t\t\t\n\t\t\t\tif (modelNode == null && uncompressed)\n\t\t\t\t{\n\t\t\t\t\tvar text = mxUtils.trim(mxUtils.getTextContent(pageNode));\n\t\t\t\t\tclone = pageNode.cloneNode(false);\n\t\t\t\t\t\n\t\t\t\t\tif (text.length > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar tmp = Graph.decompress(text);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (tmp != null && tmp.length > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tclone.appendChild(mxUtils.parseXml(tmp).documentElement);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (modelNode != null && !uncompressed)\n\t\t\t\t{\n\t\t\t\t\tclone = pageNode.cloneNode(false);\n\t\t\t\t\tmxUtils.setTextContent(clone, Graph.compressNode(modelNode));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tclone = pageNode.cloneNode(true);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tnode.appendChild(clone);\n\t\t\t}",
"function addPage(page) {\r\n document.querySelector(\"#pages\").innerHTML += `\r\n <section id=\"${page.slug}\" class=\"page\">\r\n <header class=\"topbar\">\r\n <h2>${page.title.rendered}</h2>\r\n </header>\r\n ${page.content.rendered}\r\n </section>\r\n `;\r\n}",
"constructor(page) {\n // We take page \n // assign it to an interior variable\n this.page = page;\n }",
"function SET_PAGE_DATA(state, value) {\n state.page.data = value;\n}",
"function renderFinalPage(){\n clearPage();\n $(\".noBorder\").append(finalPage());\n}",
"function loadContent() {\n\t\tMassIdea.loadHTML($contentList, URL_LOAD_CONTENT, {\n\t\t\tcategory : _category,\n\t\t\tsection : _section,\n\t\t\tpage : 0\n\t\t});\n\t}",
"processPage() {\n this.logger.debug(`${this}start observing`)\n $('head').appendChild(this.stylesheet)\n this.insertIconInDom()\n this.observePage()\n }",
"clearContent() {\n let titleEl = document.getElementById('pageTitle'),\n contentEl = document.getElementById('pageContent');\n\n titleEl.innerHTML = '';\n contentEl.innerHTML = '';\n }",
"function loadContent(page) {\n\t// Builds an XMLHttpRequest if supported otherwise defaults to an\n\t// ActiveXObject.\n\tvar xmlhttp;\n\tif (window.XMLHttpRequest)\n\t\txmlhttp = new XMLHttpRequest();\n\telse\n\t\txmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n\n\t// Sets a callback that shows the response inside the content section.\n\txmlhttp.onreadystatechange = function() {\n\t\tif ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))\n\t\t\tdocument.getElementById(\"content\").innerHTML = xmlhttp.responseText;\n\t}\n\n\t// Builds the destination URL and sends the AJAX request.\n\tvar page = \"content/\" + page + \".html\";\n\txmlhttp.open(\"GET\", page, true);\n\txmlhttp.send();\n}",
"clone() {\n const copy = Object.create(Document.prototype, {\n [NODE_TYPE]: { value: DOC }\n });\n copy.commentBefore = this.commentBefore;\n copy.comment = this.comment;\n copy.errors = this.errors.slice();\n copy.warnings = this.warnings.slice();\n copy.options = Object.assign({}, this.options);\n if (this.directives)\n copy.directives = this.directives.clone();\n copy.schema = this.schema.clone();\n copy.contents = isNode(this.contents)\n ? this.contents.clone(copy.schema)\n : this.contents;\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }",
"update() {\n view.updateTitle(view.currentPost.title);\n view.updateContent(view.currentPost.content);\n\n view.removeBlogPosts();\n if (view.currentPost.slug === 'blog') {\n // Append blog posts to blog page\n view.loadBlogPosts();\n }\n }",
"function _page2_page() {\n}",
"function editorNewContent(content, container, activity)\n{\n editorDirty = true;\n activity.contents.push(content);\n addContentElement(content, container, activity);\n}",
"async saveAsTemplate(publish = true) {\n const data = await spPost(ClientsidePage(this, `_api/sitepages/pages(${this.json.Id})/SavePageAsTemplate`));\n const page = ClientsidePage(this, null, data);\n page.title = this.title;\n await page.save(publish);\n return page;\n }",
"archivePost() {\n var post = {};\n\n if(document.getElementById(\"title\").value) {\n post.title = document.getElementById(\"title\").value;\n }\n else {\n post.title = \"Untitled post\";\n }\n\n if(document.getElementById(\"post\").value) {\n post.post = document.getElementById(\"post\").value;\n }\n else {\n post.post = \"\";\n }\n\n /*If the current post was previously loaded, updates it*/\n if (this.loadedPost) {\n this.postArray[this.loadedPost].title = post.title;\n this.postArray[this.loadedPost].post = post.post;\n }\n /*Else, the post is stored as a new one*/\n else{\n post.id = this.postId;\n this.postId = this.postId + 1; // Updates the post ID for the next post to be created\n this.postArray.push(post);\n }\n\n /*Clears the text area*/\n this.clearPost();\n }",
"function clone(instance) {\n let p1, p2;\n let body = instance.body;\n\n // don't allow cloning a used body\n if (instance.bodyUsed) {\n throw new Error(\"cannot clone body after it is used\");\n }\n\n // check that body is a stream and not form-data object\n // note: we can't clone the form-data object without having it as a dependency\n if (body instanceof Stream && typeof body.getBoundary !== \"function\") {\n // tee instance body\n p1 = new PassThrough();\n p2 = new PassThrough();\n body.pipe(p1);\n body.pipe(p2);\n // set instance body to teed body and return the other teed body\n instance[INTERNALS].body = p1;\n body = p2;\n }\n\n return body;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method is called when user clicks on Change Office button in courier list table | function changeOfficeBtnClicked(courierId) {
$("#quickBackToCourier").show();
selectedCourierId = courierId;
var lastSavedZipCode = localStorage.getItem("currentZipCode");
if(lastSavedZipCode != null)
getAllOfficesForChangeOffice(lastSavedZipCode, "", "");
else
getAllOfficesForChangeOffice("", "", "");
} | [
"function processChange(value) {\n //console.log(\"Calendar clicked\");\n //If we are working with the start input\n if(cntrl.getStartCal()) {\n cntrl.setSelectedStartDate(value); \n }\n //If we are working with the end input\n else {\n cntrl.setSelectedEndDate(value);\n }\n //Autoclose after selection\n cntrl.updateDateRange();\n }",
"_onOpenDiscountWizard(ev) {\n const orderLines = this.renderer.state.data.order_line.data.filter(line => !line.data.display_type);\n const recordData = ev.target.recordData;\n const isEqualDiscount = orderLines.slice(1).every(line => line.data.discount === recordData.discount);\n if (orderLines.length >= 3 && recordData.sequence === orderLines[0].data.sequence && isEqualDiscount) {\n Dialog.confirm(this, _t(\"Do you want to apply this discount to all order lines?\"), {\n confirm_callback: () => {\n orderLines.slice(1).forEach((line) => {\n this.trigger_up('field_changed', {\n dataPointID: this.renderer.state.id,\n changes: {order_line: {operation: \"UPDATE\", id: line.id, data: {discount: orderLines[0].data.discount}}},\n });\n });\n },\n });\n }\n }",
"function SEC_onButtonClick(event){SpinEditControl.onButtonClick(event)}",
"function handleDoubleClick(componentRec)\n{\n\treturn editCFC();\n}",
"function BocList_OnRowClick(bocList, currentRow, selectorControl)\n{\n if (_bocList_isCommandClick)\n {\n _bocList_isCommandClick = false;\n return;\n } \n \n if (_bocList_isSelectorControlLabelClick)\n {\n _bocList_isSelectorControlLabelClick = false;\n return;\n } \n\n var currentRowBlock = new BocList_RowBlock (currentRow, selectorControl);\n var selectedRows = _bocList_selectedRows[bocList.id];\n var isCtrlKeyPress = window.event.ctrlKey;\n \n if ( selectedRows.Selection == _bocList_rowSelectionUndefined\n || selectedRows.Selection == _bocList_rowSelectionDisabled)\n {\n return;\n }\n \n if (isCtrlKeyPress || _bocList_isSelectorControlClick)\n {\n // Is current row selected?\n if (selectedRows.Rows[selectorControl.id] != null)\n {\n // Remove currentRow from list and unselect it\n BocList_UnselectRow (bocList, currentRowBlock);\n }\n else\n {\n if ( ( selectedRows.Selection == _bocList_rowSelectionSingleCheckBox\n || selectedRows.Selection == _bocList_rowSelectionSingleRadioButton)\n && selectedRows.Length > 0)\n {\n // Unselect all rows and clear the list\n BocList_UnselectAllRows (bocList);\n }\n // Add currentRow to list and select it\n BocList_SelectRow (bocList, currentRowBlock);\n }\n }\n else // cancel previous selection and select a new row\n {\n if (selectedRows.Length > 0)\n {\n // Unselect all rows and clear the list\n BocList_UnselectAllRows (bocList);\n }\n // Add currentRow to list and select it\n BocList_SelectRow (bocList, currentRowBlock);\n }\n try\n {\n selectorControl.focus();\n }\n catch (e)\n {\n } \n _bocList_isSelectorControlClick = false;\n}",
"function historyTableCellClickHandler(field, column, row, rec) {\n if (column === 'edit') {\n $('#history_id').val(rec.id);\n $('#history_memberId').val(currentMemberId);\n $('#history_title').val(rec.title);\n $('#history_started_at').val(rec.started_at);\n $('#history_finished_at').val(rec.finished_at);\n $('#history_memo').val(rec.memo);\n $('#history_dialog_title').text(i18n.messages.memberdetail.history_updatetitle);\n $('#btnMemberHistorySave').removeAttr('disabled');\n $('#memberHistoryDialog').modal('show');\n } else if (column === 'delete') {\n $('#history_id').val(rec.id);\n showConfirmMessage(\"Delete Member History\", \"Do you want to delete the item?\", \"Delete\", historyDeleteHandler)\n }\n}",
"function confirmationSelectionHandler(){\n const header = SheetsLibrary.getHeaderAsObjFromSheet(ActiveSheet, 1);\n const allEvents = SheetsLibrary.getAllRowsAsObjInArr(ActiveSheet, 1);\n const events = SheetsLibrary.getSelectedRowsAsObjInArr(ActiveSheet, 1);\n const selectedEvent = events[0];\n console.log(selectedEvent);\n if( !isReady() ) return\n\n try {\n // Update Jour Fixe Calendar Event\n const jourFixeCal = CAL.getCalendarById(officeHourId);\n const eventInCal = jourFixeCal.getEventById(selectedEvent.id);\n const newTitleForEvent = \"Jour Fixe | \" + selectedEvent.user;\n const start = eventInCal.getStartTime();\n const end = eventInCal.getEndTime();\n \n let calDescription = getSFLinkFromEmail(selectedEvent.Email) ? `Hier ist der Link zu deinen Botschafter-Kampagnen: ` + getSFLinkFromEmail(selectedEvent.Email) : \"\"; \n \n // Create Calendar Event in personal Call\n const myCal = CAL.getCalendarById(myCalId);\n const newCalEvent = myCal.createEvent( newTitleForEvent, start, end);\n eventInCal.setTitle( newTitleForEvent );\n\n if( newCalEvent ){\n // Add the Meet Link to the Description\n // Need to either get the Meet Link, if it is there, or create a Meeting using the Advanced Calendar API\n const meetLink = getMeetLink(newCalEvent.getId()); //Calendar.Events.get(myCalId, newCalEvent.getId());\n if( meetLink )\n calDescription += `\\nHier ist der Link zum Gespräch: ${meetLink}`;\n newCalEvent.setDescription( calDescription );\n eventInCal.setDescription( calDescription );\n \n updateField( selectedEvent.rowNum, header.status, newCalEvent.getId() );\n disableOtherEventsFromThisSubmission(); \n newCalEvent.addGuest( selectedEvent.Email );\n sendConfirmationToBotschafter( {\n email: selectedEvent.Email,\n subject: `Bestätigung Jour-Fixe am ${selectedEvent.Datum}`,\n body: `Hi ${selectedEvent.user},\\nhiermit bestätige ich deinen Jour-Fixe-Termin am ${selectedEvent.Datum} um ${selectedEvent.Uhrzeit}.\\nLiebe Grüße,\\nShari`\n });\n }\n } catch(err) {\n console.error(\"Fehler: \"+err);\n alert(\"Could not create Event: \"+err.message);\n }\n\n // Disable other events from the same submission \n function disableOtherEventsFromThisSubmission( ){\n const eventsFromThisSubmission = allEvents.filter( event => event.submissionId === selectedEvent.submissionId && event.id != selectedEvent.id ) ;\n eventsFromThisSubmission.forEach( event => updateField( event.rowNum, header.status, \"disabled\") );\n }\n \n // Checks to see if event selected is empty and not disabled\n function isReady(){\n if( events.length > 1 ){\n alert(\"Bitte nur eine auswählen\");\n return\n }\n \n if( selectedEvent.status === \"disabled\" ){\n alert(\"Eintrag ist disabled und kann nicht erstellt werden\");\n return\n }\n \n if( selectedEvent.status != \"\" ){\n alert(\"Eintrag hat bereits einen Status und kann deshalb nicht neu erstellt werden.\");\n return\n }\n \n return true\n }\n}",
"function onReadyEditReport(){//on document ready in edit report page\n if ( $( \"#checked-point\" ).length ) {//check if input hidden id #checked-point exist\n var b = $( \"#checked-point\" ).val().split(\" \");//convert #checked-point value into array\n for (var i = 0; i<b.length; i++) {\n // $('#check-' + b[i]).trigger('click');//trigger click on checked point checkbox\n $(\"#need-fixing-\" + b[i]).trigger('click');\n }\n }\n if ( $( \"#disable-point\" ).length ) {//check if input hidden id #disable-point exist\n var b = $( \"#disable-point\" ).val().split(\" \");//convert #disable-point value into array\n for (var i = 0; i<b.length; i++) {\n //trigger click on disabled point\n // $('.edit-exclude-point[data-id=\"'+b[i]+'\"]').trigger('click');\n $(\"#exclude-\" + b[i]).trigger('click');\n }\n }\n $('#new-disable-point').val(\"\");//clear #new-disable-point value\n}",
"handleEditButtonClick() {\n BusinessRulesFunctions.viewBusinessRuleForm(true, this.state.uuid)\n }",
"function EditFoodName() {\n let e = d.Config.enums\n let j = u.GetNumber(event.target.id);\n let cell = u.ID(`t1TableKey${j}`);\n let oldValue = cell.innerText;\n cell.innerHTML = `<input type='text' id='t1TableFoodNameInput${j}' value='${oldValue}'><button id='t1TableFoodNameSave${j}' class='insideCellBtn'>✔</button>`;\n cell.className = \"tableInput\";\n u.ID(`t1TableKey${j}`).removeEventListener(\"click\", EditFoodName);\n u.ID(`t1TableFoodNameSave${j}`).addEventListener(\"click\", function () { ChangeFoodName(j, oldValue); });\n}",
"function changeToNextField(e) {\n $sel = $sel.next(\"td.editable\");\n if($sel.length < 1) {\n $sel = $sel.parent(\"tr.griderRow\").siblings(\"tr:first\").find(\"td.editable:first\");\n }\n setSelectedCell($sel);\n $sel.trigger(\"click\");\n }",
"function OnBeamColumnConnectionInSteelByCables_Change( e )\r\n{\r\n try\r\n {\r\n var newMeasuresOfEmergencyValue = Alloy.Globals.replaceCharAt( current_structural_elements_id * 13 + 2 , Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] , $.widgetAppCheckBoxShedModeFormsDamagesMeasuresOfEmergencyBeamColumnConnectionInSteelByCables.get_value() ) ;\r\n Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] = newMeasuresOfEmergencyValue ;\r\n }\r\n catch( exception )\r\n {\r\n Alloy.Globals.AlertUserAndLogAsync( L( 'generic_exception_msg' ) + exception.message ) ;\r\n }\r\n}",
"function changeCWInputBox(boxid, force) {\r\n\r\n var pO = CurProgObj;\r\n var sO = CurStepObj;\r\n\r\n\r\n // Determine whether this event was called by clicking on and empty area\r\n // in a box (table cell in code window) OR an expression (which is a span\r\n // element). In the latter case, we just return after drawing the \r\n // code window\r\n //\r\n var evt = window.event;\r\n if (!(evt.target instanceof HTMLTableCellElement) && !force) {\r\n\r\n // alert(\"evt.target:\" + evt.target + \r\n // \" edit?\" + evt.target.contentEditable);\r\n // \r\n\r\n if (evt.target.contentEditable == 'true') {\r\n\r\n // Do nothing here. This means a contenteditable entry like\r\n // let name OR function name. Note: the type of contentEditable\r\n // property is a string (not a boolean value)\r\n //\r\n\r\n } else {\r\n // contenteditable not true -- e.g., 'false', 'inherit', etc\r\n //\r\n // If currently editing index, stop it first because we change\r\n // focusBoxId below\r\n //\r\n if ((sO.focusBoxId == CodeBoxId.Index) &&\r\n (boxid != CodeBoxId.Index))\r\n stopIndexEditing();\r\n\r\n sO.focusBoxId = boxid; // focused box \r\n sO.focusBoxExpr = CurStepObj.boxExprs[boxid]; // focused exprdd\r\n drawCodeWindow(CurStepObj); // redraw code window w/ new expr\r\n\r\n //console.log(\"not table cell\");\r\n }\r\n\r\n return;\r\n }\r\n\r\n //console.log(\"table cell\");\r\n\r\n // If the step is currently showing data, stop showing data (beause\r\n // user clicked on a code box to write code (or highlight)\r\n //\r\n if (pO.showData != ShowDataState.None) {\r\n showData(ShowDataState.None);\r\n return;\r\n }\r\n\r\n\r\n // If we are currently editing an index, stop it.\r\n // OR if there an active expression/highlight, remove it first\r\n //\r\n if (sO.focusBoxId == CodeBoxId.Index) {\r\n stopIndexEditing();\r\n } else {\r\n removeExprAndGridHighlight();\r\n }\r\n\r\n // Set the focus (active) expression and box AND set the default space\r\n // at the end of expression\r\n //\r\n sO.focusBoxExpr = CurStepObj.boxExprs[boxid]; // focused expr\r\n sO.focusBoxId = boxid; // focused box \r\n //\r\n setDefaultActiveSpace(sO); // set default space\r\n //\r\n drawCodeWindow(CurStepObj); // redraw code window w/ new expr\r\n //\r\n // Note: drawCodeWindow() sets activeParentExpr by calling getHtmlExprStmt.\r\n // Therefore, the following code must follow the call to\r\n // drawCodeWindow()\r\n //\r\n updateGridHighlight(); // redraw grid with any changed highlights\r\n\r\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 on_piece_select()\n{\n\tupdate_editor();\n}",
"function editPowerLineObjectCallBack(data, options){\n\tvar powerLineId =data.split(\"*\")[1];\n\tvar content = getLineInfoWindowContent(data);\n\tvar color = data.split(\"*\")[9];\n\tvar newLineShape=globalPlList.get(powerLineId.toString());\n\tnewLineShape.setOptions({strokeColor:color});\n\tcurrentLineInfoWindowObject.setContent(content);\n\t$('#editPowerLineObject').click(function() {\n\t\teditPowerLine(powerLineId);\t\t\t\n\t})\n\t// Setting global list of power Line \n\tglobalPlList.set(powerLineId, newLineShape);\n}",
"_onSelectedChanged() {\n if (this._selected !== 'appsco-application-add-search') {\n this.$.addApplicationAction.style.display = 'block';\n this.playAnimation('entry');\n this._addAction = true;\n }\n else {\n this._addAction = false;\n this.playAnimation('exit');\n }\n }",
"modifyLivestockClick() {\r\n if (this.validateAtLeastOne()) {\r\n if (this.state.selectedData.length > 1) {\r\n if (this.checkForSameType()) {\r\n browserHistory.replace('/livestock/livestock-detail/modify-multiple');\r\n }\r\n }\r\n else {\r\n browserHistory.replace('/livestock/livestock-detail/modify');\r\n }\r\n }\r\n }",
"function editEvent(){\n for(var i = 0; i < eventInput.length; i++){\n eventInput[i].addEventListener(\"change\", function(){\n this.previousElementSibling.lastElementChild.previousElementSibling.innerHTML = this.value;\n for(var i = 0; i < currentMonth.days.length; i++){\n if(clickedCell.firstChild.textContent === currentMonth.days[i].cell.firstChild.textContent){\n currentMonth.days[i].events.push(this.value);\n break;\n };\n }\n });\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Class HostEnvironment Stores information about the environment in which the extension is loaded. | function HostEnvironment(appName, appVersion, appLocale, appUILocale, appId, isAppOffline, appSkinInfo)
{
this.appName = appName;
this.appVersion = appVersion;
this.appLocale = appLocale;
this.appUILocale = appUILocale;
this.appId = appId;
this.isAppOffline = isAppOffline;
this.appSkinInfo = appSkinInfo;
} | [
"get environment() {\n if (this._enviornment)\n return Promise.resolve(this._enviornment);\n return fs.readFile(this.environmentPath).then((file) => __awaiter(this, void 0, void 0, function* () {\n let localEnvironment = jsonc.parse(file.toString());\n if (!localEnvironment.names || !Array.isArray(localEnvironment.names)) {\n throw new Error('Local environment.json is not properly configured.');\n }\n this._enviornment = localEnvironment;\n return localEnvironment;\n }));\n }",
"loadEnvironmentHostnames() {\n let hostNames = path.join(this.projectFolder, \"hostnames.json\");\n return this.utils.readJsonFile(hostNames);\n }",
"function ComputeEnvironment(props) {\n return __assign({ Type: 'AWS::Batch::ComputeEnvironment' }, props);\n }",
"function getEnv() {\n env = env || new Benchmine.Env();\n\n return env;\n }",
"function getEnv() {\n\tvar store = JSON.parse(localStorage.getItem(\"AtmosphereEnv\"));\n\tif ((store !== undefined) && (store !== null)) env = store;\n}",
"function BAEnvironment() {\n\t/** debug mode flag\n\t @type Boolean */\n\tthis.debugMode = false;\n\n\t/** document\n\t @type Document @const @private */\n\tvar d = document;\n\t/** document.implementation\n\t @type Object @const @private */\n\tvar di = d.implementation;\n\t/** document.documentElement\n\t @type Node @const @private */\n\tvar de = d.documentElement;\n\t/** navigator.userAgent\n\t @type String @const @private */\n\tvar ua = navigator.userAgent;\n\t/** location.protocol\n\t @type String @const @private */\n\tvar lp = location.protocol;\n\t/** location.hostname\n\t @type String @const @private */\n\tvar lh = location.hostname;\n\n\t/** associative array of urls/paths to frequently used directories.\n\t @type Object @const */\n\tthis.url = {};\n\tthis.url.commonDir = BAGetCommonDir('shared');\n\tthis.url.cssDir = this.url.commonDir + 'css/';\n\tthis.url.jsDir = this.url.commonDir + 'js/';\n\n\t/** associative array of frequently used namespaces.\n\t @type Object @const */\n\tthis.ns = {};\n\tthis.ns.defaultNS = (de && de.namespaceURI) ? de.namespaceURI : (de && de.tagUrn) ? de.tagUrn : null;\n\tthis.ns.xhtml1 = 'http://www.w3.org/1999/xhtml';\n\tthis.ns.xhtml2 = 'http://www.w3.org/2002/06/xhtml2';\n\tthis.ns.bAattrs = 'urn:bA.attrs';\n\n\t/** associative array of frequently used namespace prefixes.\n\t @type Object @const */\n\tthis.prefix = {};\n\tthis.prefix.bAattrs = 'bAattrs:';\n\n\t/** associative array of browser distinction results.\n\t @type Object @const */\n\tthis.ua = {};\n\tthis.ua.isGecko = ua.match(/Gecko\\//);\n\tthis.ua.isSafari = ua.match(/AppleWebKit/);\n\tthis.ua.isOpera = window.opera;\n\tthis.ua.isIE = (d.all && !this.ua.isGecko && !this.ua.isSafari && !this.ua.isOpera);\n\tthis.ua.isIE40 = (this.ua.isIE && ua.match(/MSIE 4\\.0/)); // IE 4.0x\n\tthis.ua.isIE45 = (this.ua.isIE && ua.match(/MSIE 4\\.5/)); // IE 4.5x\n\tthis.ua.isIE50 = (this.ua.isIE && ua.match(/MSIE 5\\.0/)); // IE 5.0x\n\tthis.ua.isIE55 = (this.ua.isIE && ua.match(/MSIE 5\\.5/)); // IE 5.5x\n\tthis.ua.isIE60 = (this.ua.isIE && ua.match(/MSIE 6\\.0/)); // IE 6.0x\n\tthis.ua.isIE70 = (this.ua.isIE && ua.match(/MSIE 7\\.0/)); // IE 7.0x\n\tthis.ua.isIE80 = (this.ua.isIE && ua.match(/MSIE 8\\.0/)); // IE 8.0x\n\tthis.ua.isIE90 = (this.ua.isIE && ua.match(/MSIE 9\\.0/)); // IE 9.0x\n\tthis.ua.isNN4 = d.layers; // NN 4.x\n\tthis.ua.isMac = ua.match(/Mac/);\n\tthis.ua.isWin = ua.match(/Win/);\n\tthis.ua.isWinIE = this.ua.isWin && this.ua.isIE;\n\tthis.ua.isMacIE = this.ua.isMac && this.ua.isIE;\n\tthis.ua.productSub = navigator.productSub;\n\tthis.ua.revision = (this.ua.isIE ) ? parseFloat(ua.match(/MSIE ([\\d\\.]+)/)[1]) :\n\t (this.ua.isGecko ) ? parseFloat(ua.match(/; rv:([\\d\\.]+)/)[1]) :\n\t (this.ua.isSafari) ? parseFloat(ua.match(/AppleWebKit\\/([\\d\\.]+)/)[1]) :\n\t (this.ua.isOpera ) ? parseFloat(ua.match(/Opera.([\\d\\.]+)/)[1]) :\n\t 0;\n\tthis.ua.DOMok = (di) ? di.hasFeature('HTML','1.0') : (this.ua.isIE && de);\n\n\t/** associative array of misc environment values.\n\t @type Object @const */\n\tthis.env = {};\n\tthis.env.online = (lp == 'http:' || lp == 'https:');\n\tthis.env.referer = (typeof document.referrer == 'string') ? document.referrer : '';\n\n\t/** associative array of revise css settings.\n\t @type Object @const */\n\tthis.css = {};\n\tthis.css.revise = {\n//\t\t'Safari' : 'revise_safari.css',\n//\t\t'IE50.Win' : 'revise_winie50.css'\n\t};\n\tthis.css.reviseTitle = '';\n\n\t/** associative array of browser geometries.\n\t @type Object @see Window#BAGetGeometry */\n\tthis.geom = {};\n}",
"function setup_environment() {\n const primitive_function_names =\n map(f => head(f), primitive_functions);\n const primitive_function_values =\n map(f => make_primitive_function(head(tail(f))),\n primitive_functions);\n const primitive_constant_names =\n map(f => head(f), primitive_constants);\n const primitive_constant_values =\n map(f => head(tail(f)),\n primitive_constants);\n return extend_environment(\n append(primitive_function_names,\n primitive_constant_names),\n append(primitive_function_values,\n primitive_constant_values),\n the_empty_environment);\n}",
"function Environment() {\r\n \t\tthis._id = randomUUID();\r\n \t\tthis._schemas = {};\r\n \t\tthis._options = {};\r\n \t\t\r\n \t\tthis.createSchema({}, true, \"urn:jsv:empty-schema#\");\r\n \t}",
"function setup_environment() {\n var initial_env = enclose_by(an_empty_frame,\n the_empty_environment);\n for_each(function(x) {\n define_variable(head(x),\n { tag: \"primitive\",\n implementation: tail(x) },\n initial_env);\n },\n primitive_functions);\n for_each(function(x) {\n define_variable(head(x),\n tail(x),\n initial_env);\n },\n primitive_values);\n return initial_env;\n}",
"loadEnv() {\n let env = dotenvExtended.load({\n silent: false,\n path: path.join(this.getProjectDir(), \".env\"),\n defaults: path.join(this.getProjectDir(), \".env.defaults\")\n });\n\n const options = minimist(process.argv);\n for (let option in options) {\n if (option[0] === \"-\") {\n let value = options[option];\n option = option.slice(1);\n if (option in env) {\n env[option] = value.toString();\n }\n }\n }\n env = dotenvParseVariables(env);\n env = dotenvExpand(env);\n\n this.env = { ...env, project_dir: this.getProjectDir() };\n }",
"function Environment(props) {\n return __assign({ Type: 'AWS::ElasticBeanstalk::Environment' }, props);\n }",
"async _getVirtualHostsPerEnv(token) {\n\t\tthis.log('Loading virtual hosts')\n\t\tconst virtualHostsPerEnvironment = new Map();\n\t\t//get a list of all environments and virtual hosts\n\t\tconst environments = JSON.parse(await this._listEnvironments(token));\n\t\tfor (let env of environments) {\n\t\t\tthis.log(`Processing env ${JSON.stringify(env)}`);\n\t\t\t//get the virtual hosts\n\t\t\tconst virtualHosts = await this._listVirtualHostsForEnvironment(token, env);\n\t\t\tlet vhostDetails = [];\n\t\t\tfor (let vhost of JSON.parse(virtualHosts)) {\n\t\t\t\tlet vHostDetails = await this._listVirtualHostDetailsForEnvironment(token, env, vhost);\n\t\t\t\tvhostDetails.push(JSON.parse(vHostDetails));\n\t\t\t}\n\t\t\tvirtualHostsPerEnvironment.set(env, vhostDetails);\n\t\t}\n\t\treturn virtualHostsPerEnvironment;\n\t}",
"checkEnvironment() {\n if (\n this.system.production &&\n Config.exists(path.join(this.dir, 'config.development.json')) &&\n !Config.exists(path.join(this.dir, 'config.production.json'))\n ) {\n this.ui.log('Running in development mode', 'cyan');\n this.system.setEnvironment(true, true);\n }\n }",
"loadEnvironmentInfo() {\n let infoPath = path.join(this.projectFolder, \"envInfo.json\");\n if (this.utils.fileExists(infoPath)) {\n return this.utils.readJsonFile(infoPath);\n }\n return null;\n }",
"function updateEnv(key, value) {\n\tenv[key] = value;\n\tvar store = JSON.stringify(env);\n\tlocalStorage.setItem(\"AtmosphereEnv\", store);\n}",
"loadEnvVarsForLocal() {\n const defaultEnvVars = {\n IS_LOCAL: 'true',\n };\n\n _.merge(process.env, defaultEnvVars);\n\n // Turn zero or more --env options into an array\n // ...then split --env NAME=value and put into process.env.\n _.concat(this.options.env || []).forEach(itm => {\n const splitItm = _.split(itm, '=');\n process.env[splitItm[0]] = splitItm[1] || '';\n });\n\n return BbPromise.resolve();\n }",
"storeEnvironmentHostnames(envName, hostnames) {\n let hostNames = path.join(this.projectFolder, \"hostnames.json\");\n return this.utils.writeJsonFile(hostNames, hostnames);\n }",
"function setupEnvironmentVariables(args) {\n shell.env['ELIFE_INSTALL_FOLDER'] = shell.pwd()\n let nn = \"0\"\n if(shell.env['ELIFE_NODE_NUM']) nn = shell.env['ELIFE_NODE_NUM']\n if(args['node-num']) nn = args['node-num']\n if(isNaN(parseInt(nn))) {\n shell.echo(`node-num ${nn} is not a valid integer`)\n shell.exit(1)\n }\n shell.env[\"ELIFE_NODE_NUM\"] = nn\n shell.env['COTE_ENV'] = partitionParam()\n shell.env['ELIFE_HOME'] = u.homeLoc()\n\n setup_port_vars_1()\n\n function setup_port_vars_1() {\n process.env[\"SSB_PORT\"] = u.adjustPort(8191)\n process.env[\"SSB_WS_PORT\"] = u.adjustPort(8192)\n process.env[\"QWERT_PORT\"] = u.adjustPort(8193)\n process.env[\"EBRAIN_AIML_PORT\"] = u.adjustPort(8194)\n process.env[\"AIARTIST_PORT\"] = u.adjustPort(8195)\n }\n}",
"storeEnvironmentInfo(environmentInfo) {\n let infoPath = path.join(this.projectFolder, \"envInfo.json\");\n this.utils.writeJsonFile(infoPath, environmentInfo);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Track every click on a given link. Use datatype attribute on the link to define click type. | function trackClick() {
var type = this.getAttribute('data-type');
if (type === 'bookmarks-link') {
ga('send', 'event', {
eventCategory: 'type',
eventAction: 'Open bookmarks'
});
} else if (type === 'share') {
ga('send', 'event', {
eventCategory: 'type',
eventAction: this.getAttribute('title')
});
} else {
ga('send', 'event', {
eventCategory: 'type',
eventAction: this.id,
eventLabel: earthview.app.photo.id
});
}
} | [
"async function onLinkClicked(event) {\r\n let playlistURI;\r\n let trackURI;\r\n let target = event.target;\r\n // Trace backward to element having embeded URIs\r\n while (!playlistURI && target !== document.body) {\r\n playlistURI = target.href;\r\n trackURI = target.dataset.uri;\r\n target = target.parentNode;\r\n }\r\n\r\n if (!playlistURI || !trackURI) return;\r\n\r\n const uriObj = URI.from(playlistURI);\r\n if (!uriObj) return;\r\n\r\n const isChart = \"application\" === uriObj.type && \"chart\" === uriObj.id;\r\n if (\r\n uriObj.type === URI.Type.COLLECTION ||\r\n URI.isPlaylistV1OrV2(uriObj) ||\r\n isChart\r\n ) {\r\n let requestURI = `sp://core-playlist/v1/playlist/${playlistURI}/rows`\r\n \r\n if (!(await getPrefsValue(\"ui.show_unplayable_tracks\"))) {\r\n requestURI += \"?filter=playable%20eq%20true\"\r\n }\r\n\r\n // Search clicked track index in playlist then send message to Playlist app\r\n // to navigate to track's position.\r\n CosmosAPI.resolver.get(\r\n { url: requestURI, body: { policy: { link: true } } },\r\n (err, raw) => {\r\n if (err) return;\r\n var list = raw.getJSONBody();\r\n const index = list.rows.findIndex(item => item.link === trackURI);\r\n if (index === -1) return;\r\n ensureMessage(\"highlight-context-index\", { uri: playlistURI, index });\r\n }\r\n );\r\n return;\r\n }\r\n return;\r\n }",
"function setUpListeners() {\n var i = 0;\n for(i = 0; i < linkIds.length; i++) {\n var anchor = document.getElementById(linkIds[i]);\n $('#'+linkIds[i]).click(function() {\n annotationOnClick(this.id);\n });\n }\n}",
"function onClickTiddlerLink(e)\n{\n\tif (!e) var e = window.event;\n\tvar theTarget = resolveTarget(e);\n\tvar theLink = theTarget;\n\tvar title = null;\n\tdo {\n\t\ttitle = theLink.getAttribute(\"tiddlyLink\");\n\t\ttheLink = theLink.parentNode;\n\t} while(title == null && theLink != null);\n\tif(title)\n\t\t{\n\t\tvar toggling = e.metaKey || e.ctrlKey;\n\t\tif(config.options.chkToggleLinks)\n\t\t\ttoggling = !toggling;\n\t\tvar opening;\n\t\tif(toggling && document.getElementById(\"tiddler\" + title))\n\t\t\tcloseTiddler(title,e.shiftKey || e.altKey);\n\t\telse\n\t\t\tdisplayTiddler(theTarget,title,0,null,null,true,e.shiftKey || e.altKey);\n\t\t}\n\tclearMessage();\n\te.cancelBubble = true;\n\tif (e.stopPropagation) e.stopPropagation();\n\treturn(false);\n}",
"function interceptClickEvent(e) {\n var href;\n var target = e.target || e.srcElement;\n if (target.tagName === 'A') {\n href = target.getAttribute('href');\n\n dd(href, 'href');\n \n exp = href.split('/');\n\n // check if internal domain\n is_internal = false;\n for(i=0; i<exp.length; i++)\n {\n \tif(exp[i].indexOf(punch.base_url) !== -1) is_internal = true;\n }\n\n if(exp[0] == \"\") is_internal = true;\n\n //put your logic here...\n if (is_internal) {\n \tdd('Trigger routing!');\n //tell the browser not to respond to the link click\n e.preventDefault();\n }\n }\n}",
"function globalTracker(event) {\n let tId = event.target.id;\n console.log('eventId=' + tId);\n let setting = dict.get(tId);\n if(setting != undefined) {\n let type = setting.type;\n let el = document.getElementById(setting.targetId);\n\n if(type == 'link') {\n //if the element is 'a' and have element stacks on it, both element need to be registered.\n if(el == undefined)\n return;\n\n let matcher = new RegExp('\\.([a-zA-Z0-9]+)$');\n let matchs = el.href.match(matcher);\n let linkType = 'n/a';\n if(matchs && matchs[1]){\n linkType = matchs[1];\n console.log('finded');\n console.log(matchs);\n }\n console.log(linkType);\n window.snowplow('trackStructEvent', 'link', 'download', el.id, el.href, type);\n console.log(el);\n }else if(type == 'btn') {\n window.snowplow('trackStructEvent', 'button', 'click', el.id, '', '');\n }else if(type == 'video' && el.nodeName == 'video') {\n window.snowplow('trackStructEvent', 'video', el.pause() ? 'pause':'play', el.id, el.src, '');\n }else {\n //unknown type , just ignore it\n console.log(\"error: unknown type \" + type);\n }\n }\n }",
"function handleOutboundAnalytics() {\n var label = this.getAttribute('href'); // Triggered by <a>\n ExtraAnalytics.sendEventAnalytics('Outbound link', 'click', label, false );\n }",
"handleDirectLinkFocus() {\n gaAll('send', 'event', 'query direct link', 'focus');\n }",
"function SetupTitleClickHandler() {\r\n // The protocol-abstract-link class is only applied to the protocol links.\r\n $(\".protocol-abstract-link\").click(function(event) {\r\n ProtocolTitleClickHandler(event);\r\n });\r\n}",
"function markLink( link ) {\r\n\t\t$( link ).addClass( linkCurrentClass );\r\n\t}",
"function confirmAllLinks() {\n for(var i = 0; i < document.links.length; i++) {\n document.links[i].onclick = confirmLink;\n }\n}",
"function clickOnLinks() {\n var selected_link; // url of clicked link\n \n window.addEventListener(\"click\", function(e) {\n // Do this only when ctrl key is pressed\n if(e.ctrlKey) {\n // Get clicked href\n selected_link = e.target.href;\n\n // If there is a link\n if (!!selected_link) {\n if (selected_link.substring(0,24) === \"javascript:window.open('\") {\n selected_link = selected_link.substring(24, selected_link.length-2);\n }\n window.open(selected_link);\n }\n }\n }, false);\n \n window.addEventListener(\"keydown\", function(e) {\n if(e.keyCode == 17) {\n addClass(document.documentElement, \"activate-links\");\n }\n }, false);\n\n window.addEventListener(\"keyup\", function(e) {\n if(e.keyCode == 17) {\n removeClass(document.documentElement, \"activate-links\");\n }\n }, false);\n }",
"function clickLink() {\r\n\t$('.tt_chosen')[0].click();\r\n}",
"function onclick_watched(e, video_id) {\n flixstack_api.mark_as_watched(video_id, function(data, textStatus) {\n update_link(video_id, false);\n }); \n\n e.preventDefault();\n e.stopPropagation();\n return false;\n}",
"function add_ga() {\n\t\t$('a').each(function(){\n\t\t\tif (!$(this).hasClass('ga')) {\n\t\t\t\tvar href = $(this).attr('href');\n\t\t\t\tvar exp_http = /http(s|):\\/\\/(.[^\\/]+)/;\n\t\t\t\tvar exp_tel = /tel:(.[^\\/]+)/;\n\t\t\t\tvar exp_email = /mailto:(.[^\\/]+)/;\n\t\t\t\tif (matches = exp_http.exec(href)) {\t\n\t\t\t\t\t$(this).click(function(){\n\t\t\t\t\t\tvar exp_http2 = /http(s|):\\/\\/(.[^\\/]+)/; // have to duplicate for the click action\n\t\t\t\t\t\tvar lmatches = exp_http2.exec($(this).attr('href'));\n\t\t\t\t\t\tvar domain = lmatches[2];\n\t\t\t\t\t\trecord_ga_event(\"Outbound Traffic\", domain, $(this).attr('href'));\n\t\t\t\t\t});\n\t\t\t\t\t$(this).addClass('ga');\n\t\t\t\t} else if (matches = exp_tel.exec(href)) {\n\t\t\t\t\t$(this).click(function(){\n\t\t\t\t\t\tvar number = $(this).attr('href').replace('tel:','');\n\t\t\t\t\t\tvar link = hist[0];\n\t\t\t\t\t\tif (link.backHref == '') {\n\t\t\t\t\t\t\tlinkHref = '/home/'\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlinkHref = link.backHref;\n\t\t\t\t\t\t}\n\t\t\t\t\t\trecord_ga_event(\"Outbound Calls\", number, linkHref);\n\t\t\t\t\t});\n\t\t\t\t\t$(this).addClass('ga');\n\t\t\t\t} else if (matches = exp_email.exec(href)) {\n\t\t\t\t\t$(this).click(function(){\n\t\t\t\t\t\tvar email = $(this).attr('href').replace('mailto:','');\n\t\t\t\t\t\tvar link = hist[0];\n\t\t\t\t\t\tif (link.backHref == '') {\n\t\t\t\t\t\t\tlinkHref = '/home/'\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlinkHref = link.backHref;\n\t\t\t\t\t\t}\n\t\t\t\t\t\trecord_ga_event(\"Outbound Emails\", email, linkHref);\n\t\t\t\t\t});\n\t\t\t\t\t$(this).addClass('ga');\n\t\t\t\t} else {\n\t\t\t\t\tif ($(this).attr('href') == '#') {\n\t\t\t\t\t\tif ($(this).hasClass('submit')) {\n\t\t\t\t\t\t\tvar action = $(this).parents().map(function() {\n\t\t\t\t\t\t\t\tif (this.tagName == 'FORM') {\n\t\t\t\t\t\t\t\t\treturn this.action;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}).get().join('');\n\t\t\t\t\t\t\trecord_ga_pageview(action);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$(this).click(function(){\n\t\t\t\t\t\t\t\tvar link = hist[1]; // because of timing with how jqtouch handles the history vs. this click you don't want the first entry, you need second entry\n\t\t\t\t\t\t\t\tif (link.backHref == '') {\n\t\t\t\t\t\t\t\t\tlinkHref = '/home/'\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlinkHref = link.backHref;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\trecord_ga_pageview(linkHref);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\t\n\t\t\t\t\t\t$(this).addClass('ga');\n\t\t\t\t\t} else {\t\t\n\t\t\t\t\t\t$(this).click(function(){record_ga_pageview($(this).attr('href'))});\n\t\t\t\t\t\t$(this).addClass('ga');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}",
"function addOnClicks(relevantHtml) {\n var relHTML = relevantHtml.replace(\"<p>\", \"\");\n relHTML = relHTML.replace(\"</p>\", \"\");\n \n var html = $.parseHTML(relHTML);\n //console.log(relevantHtml);\n var links = $(\".lyrics\", html);\n //iterate over links and add onclick and remove href to <a>\n for(i = 0; i < links[0].children.length; i++) {\n if(links[0].children[i].tagName == 'A') {\n links[0].children[i].removeAttribute(\"href\");\n links[0].children[i].id = links[0].children[i].getAttribute(\"data-id\");\n linkIds.push(links[0].children[i].id);\n links[0].children[i].onclick = function() {\n annotationOnClick(this.id);\n };\n }\n }\n return links;\n}",
"_isLinkSaveable(aLink) {\n // We don't do the Right Thing for news/snews yet, so turn them off\n // until we do.\n return this.context.linkProtocol && !(\n this.context.linkProtocol == \"mailto\" ||\n this.context.linkProtocol == \"javascript\" ||\n this.context.linkProtocol == \"news\" ||\n this.context.linkProtocol == \"snews\");\n }",
"function buildOutboundLinkTracking() {\n var _this = this;\n\n $( 'a[href]' ).each( function() {\n if( this.href.indexOf( location.host ) < 0 ) {\n $( this ).on( 'click', function() {\n _this.trackOutbound( this.href );\n } );\n }\n } );\n }",
"function onClickTag(e)\n{\n\tif (!e) var e = window.event;\n\tvar theTarget = resolveTarget(e);\n\tvar popup = createTiddlerPopup(this);\n\tvar tag = this.getAttribute(\"tag\");\n\tvar title = this.getAttribute(\"tiddler\");\n\tif(popup && tag)\n\t\t{\n\t\tvar tagged = store.getTaggedTiddlers(tag);\n\t\tvar c = false;\n\t\tfor(var r=0;r<tagged.length;r++)\n\t\t\tif(tagged[r].title != title)\n\t\t\t\t{\n\t\t\t\tcreateTiddlyLink(popup,tagged[r].title,true);\n\t\t\t\tc = true;\n\t\t\t\t}\n\t\tvar lingo = config.views.wikified.tag;\n\t\tif(c)\n\t\t\t{\n\t\t\tpopup.insertBefore(document.createElement(\"hr\"),popup.firstChild);\n\t\t\tvar openAll = createTiddlyButton(null,lingo.openAllText.format([tag]),lingo.openAllTooltip,onClickTagOpenAll);\n\t\t\topenAll.setAttribute(\"tag\",tag);\n\t\t\tpopup.insertBefore(openAll,popup.firstChild);\n\t\t\t}\n\t\telse\n\t\t\tpopup.appendChild(document.createTextNode(lingo.popupNone.format([tag])));\n\t\t}\n\tscrollToTiddlerPopup(popup,false);\n\te.cancelBubble = true;\n\tif (e.stopPropagation) e.stopPropagation();\n\treturn(false);\n}",
"function clickCounter() {\n if (startTimer) {\n if (timeDifference() > 3) {\n reSetTimer();\n }\n }\n clickCount += 1;\n if (clickCount == 1) {\n startTimer = Date.now();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a key from the store. | remove(key) {
delete this.store[key];
} | [
"remove(key) {\n var item = this.map[key];\n if (!item) return;\n this._removeItem(item);\n }",
"remove(key) {\n if (this._data[key]) {\n this._busyMemory -= this._lifeTime[key].size;\n delete this._data[key];\n }\n }",
"remove(key) {\n let index = Hash.hash(key, this.sizeLimit);\n\n if (\n this.hashTable[index].length === 1 &&\n this.hashTable[index][0][0] === key\n ) {\n delete this.hashTable[index];\n } else {\n for (let i = 0; i < this.hashTable[index].length; i++) {\n if (this.hashTable[index][i][0] === key) {\n delete this.hashTable[index][i];\n }\n }\n }\n }",
"remove(key) {\n if (!_.isString(key)) throw new Error('Parameter \"key\" must be a string!');\n\n const node = this.dictionary[key];\n\n if (!node) return null;\n\n delete this.dictionary[key];\n this.linkedList.removeNode(node);\n\n return node.data;\n }",
"async delete(objectStoreName, key) {\n let store = await this.getStore(objectStoreName, \"readwrite\");\n let request = store.delete(key);\n return this.handleRequest(request);\n }",
"function removeFromSession(key) {\n if (sessionStorage) {\n if (sessionStorage[key]) {\n delete sessionStorage[key];\n }\n }\n else {\n throw Error(\"Session storage not supported\");\n }\n}",
"removeStream( key ) {\n if ( !this.keys.has( key ) ) {\n return false\n }\n\n // Any-key helper\n if ( key === '*' ) {\n this.anyKey.destroy()\n }\n\n this.keys.get( key ).destroy()\n\n delete this.keys.get( key )\n this.keys.delete( key )\n\n return true\n }",
"unset(key = null) {\n // If only argument is an Array, iterate it as array of keys to remove\n if (key instanceof Array) {\n const keys = key;\n\n for (const key of keys) {\n // Delete prop by key\n DotProp.delete(this.__data, key);\n this.__updates.add(key);\n }\n\n return;\n }\n\n // Delete all internal data if provided key is not defined\n if (key == null) {\n // Redefine internal data object\n this.__data = {};\n this.__fullUpdate = true;\n return;\n }\n\n // Delete prop by key\n DotProp.delete(this.__data, key);\n\n // Add change to internal updates set\n this.__updates.add(key);\n }",
"remove(key, val, clearEmpty = true) {\n let set = this.get(key);\n set.delete(val);\n if (clearEmpty && set.size === 0) {\n this.delete(key);\n }\n }",
"function stop(key) {\n data[key] = undefined;\n delete data[key];\n }",
"static removeKeyFromCache(key) {\n if (RCTPrefetch.cache && RCTPrefetch.cache[key]) {\n RCTPrefetch.cache[key].refs--;\n if (RCTPrefetch.cache[key].refs <= 0) {\n RCTPrefetch.cache[key].texture.dispose();\n delete RCTPrefetch.cache[key];\n }\n }\n }",
"function removeNode(node, key, index) {\n Array.isArray(node[key])\n ? node[key].splice(index, 1)\n : delete node[key]\n}",
"remove(eventName) {\n if (this.eventStorage[eventName]) {\n delete this.eventStorage[eventName];\n }\n }",
"function deletePubKey() {\n ctrl.pubKey.$remove(\n {id: ctrl.pubKey.id},\n function() {\n raiseAlert('success',\n '', 'Public key deleted successfully');\n $uibModalInstance.close(ctrl.pubKey.id);\n },\n function(httpResp) {\n raiseAlert('danger',\n httpResp.statusText, httpResp.data.title);\n ctrl.cancel();\n }\n );\n }",
"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 }",
"removeEvent(eventKey) {\n const userId = firebase.auth().currentUser.uid;\n const dbRef = firebase.database().ref(`/users/${userId}/events/${eventKey}`);\n dbRef.remove();\n }",
"removeUserAttribute(key) {\n if (!key || typeof key !== 'string')\n throw new TypeError('Invalid param, Expected String');\n Instabug.removeUserAttribute(key);\n }",
"removeApi(key, cb) {\n this.request('DELETE', '/api/apis/' + key, null, cb)\n }",
"decreaseKey(newVal, obj) {\n let idx = this._storage.indexOf(obj);\n this.set(idx, { val: newVal, obj });\n this.heapifyUp(idx);\n }",
"removeMessage(keyNum){\n this.messages.delete(keyNum)\n return this;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start the part at the given time. | start(time, offset) {
this._part.start(time, offset ? this._indexTime(offset) : offset);
return this;
} | [
"function start(beatsPerMinute) {\n if (playing) stop();\n\n // assume each step is a 16th note\n stepsPerSecond = beatsPerMinute / 60 * 4;\n context = createNewContext();\n synth = Synth(context);\n\n playing = true;\n scheduleSounds(getPosition(0));\n context.resume();\n\n onTick();\n }",
"initStartTime() {\n if (!this.client.emitter.hasListeners(this.eventName) || !this.debug) {\n return;\n }\n this.startTime = process.hrtime();\n }",
"function begin() {\r\n\t//log start time\r\n\tvar date = new Date();\r\n\tvar startDate = [(date.getMonth()+1),date.getDate(),date.getFullYear()];\r\n\tvar startTime = [date.getHours(),date.getMinutes(),date.getSeconds()];\r\n\t//setStartTime(startDate,startTime);\r\n\t\r\n\tprepareData(dataClone); \r\n\t\r\n\t//initialize clicks\r\n\tdocument.getElementById(\"lineBtn\").click();\r\n\tdocument.getElementById(\"zeroBtn\").click();\r\n\tdocument.getElementById(\"removeBtn\").click();\r\n}",
"function start() {\n dbg('start (schedule)');\n wait = $timeout(startAnim, waitDelay);\n }",
"beforeLaunch() {\n this.startTime = Date.now()\n }",
"function startTimer(_timer){\n _timer.start({\n countdown: true,\n startValues: {\n seconds: 60\n }\n });\n}",
"play(startTime, endTime) {\n let { remote, fullScreen, playing } = this.props\n let { vc } = this\n log(`play startTime=${startTime}, endTime=${endTime}, playing=${playing}`)\n\n if (playing) { \n log('play - stop before restarting play')\n this.stop() \n }\n\n if (!isNaN(startTime)) {\n vc.currentTime = startTime\n }\n\n if (fullScreen) this.requestFullScreen()\n\n this.endTime = endTime\n\n let { playbackRate } = remote\n vc.playbackRate = playbackRate || 1.0\n\n this.startupdater()\n remote.playing = true\n //console.log('play!!!')\n this.vc.play()\n }",
"function start() {\n new CronJob(\n '00 * * * * *', // run every minute\n () => {\n const currentTime = new Date();\n // which code to run\n console.log(\n `Running Send Notifications Worker for ${moment(currentTime).format()}`\n );\n notifications.checkAndSendNecessaryNotifications(currentTime);\n },\n null, // don't run anything after finishing the job\n true, // start the timer\n '' // use default timezone\n );\n}",
"function playPatternStepAtTime(pt) {\n for (var k in currentPattern) {\n if (currentPattern[k][currentStep] == '1') {\n dispatcher.trigger('patterngrid:notehit', k, pt);\n }\n dispatcher.trigger('patterngrid:stepchanged', currentStep);\n }\n}",
"start() {\n\n this.isPlaying = true; // set the 'playing' boolean to true\n\n this.playing = 0; // reset to the beginning\n this.playCurrent(); // start playing the current track\n }",
"start(){\n\t\t// Run immediately to avoid having to wait for the first timeout\n\t\tthis.onUpdate();\n\n\t\tvar updater = this.onUpdate.bind(this);\n\t\tthis.interval = setInterval(updater, this.updateInterval);\n\t}",
"function startBattle(client, msg) {\n sample(client, msg, \"start\");\n timeleft(client, msg, \"start\");\n submit(client, msg, \"start\");\n}",
"function clickStart() {\n $('#start').click(function (event) {\n // This starts the game when the start button is clicked\n moleSquare();\n\n // This starts the timer when the start button is clicked\n timer();\n });\n }",
"function startStopWatch() {\n if (!running) {\n startTime = new Date().getTime();\n tableSize++;\n newRow = historyTable.insertRow(tableSize);\n \n newStart = newRow.insertCell(0);\n startLatitude = newRow.insertCell(1);\n startLongitude = newRow.insertCell(2);\n newStop = newRow.insertCell(3);\n stopLatitude = newRow.insertCell(4);\n stopLongitude = newRow.insertCell(5);\n elapsedTime = newRow.insertCell(6);\n newStart.innerHTML = Date(startTime);\n if (\"geolocation\" in navigator){\n navigator.geolocation.getCurrentPosition(startCoor);}\n else {\n startLatitude.innerHTML = \"N/A\";\n startLongitude.innerHTML = \"N/A\";\n }\n timeInterval = setInterval(getDisplayTime, 10);\n running = 1;\n paused = 0;\n saveToLocalStorage();\n }\n}",
"function setTime() {\n setInterval(function() {\n // Checking to see if the current hour matches what the page thinks it is\n if (curHour != parseInt(moment().hour())) {\n // Updating the current hour\n curHour = parseInt(moment().hour());\n //console.log(\"You entered an hour change\")\n // Coloring the page\n colorPage();\n };\n // Logging the minute to make sure the listener functions correctly\n // console.log(\"hour: \" + moment().hour());\n // console.log(\"minute: \" + moment().minute());\n // console.log(\"system hour: \" + curHour);\n }, 60000);\n}",
"function startShotClock () {\n\tif (ISTIMEOUT) {\n\t\t$('#shotclock').text('Timeout');\n\t\tISTIMEOUT = false;\n\t} else {\n\t\t$('#shotclock').text('Shot Clock');\n\t}\n\tvar prevShotClockCycleTime = new Date().getTime();\n\tshotClock = setInterval(function () {\n\t\tvar currentShotClockTime = new Date().getTime();\n\t\tif (currentShotClockTime - prevShotClockCycleTime >= TIME_INTERVAL) {\n\t\t\tCURRENT_SHOT_CLOCK_TIME = CURRENT_SHOT_CLOCK_TIME - TIME_INTERVAL;\n\t\t\tupdateShotClock();\n\t\t\tprevShotClockCycleTime = currentShotClockTime;\n\t\t}\n\t}, 1);\n}",
"function _startTimeBlockTimer(timeBlockArray) {\n\n timeBlockArray.push({\n startTime: (new Date()).getTime(),\n endTime: -1,\n totalTimeSeconds: -1\n });\n\n }",
"static sExplanationStarted(key) {\n Signals.emit(key, \"sExplanationStarted\", {\"startTime\": rooms[key].startTime});\n }",
"function startSPE() {\n\t// initialize object\n\tvar spe = new SPE();\n\tspe.reloadSPE = restartSPE;\n\t// initialize hidden html structure\n\tspe.generateBodyStructure();\n\t// enable loading animation\n\tspe.hideLoading(false);\n\t// as a start load the text instead of animation while loading\n\tspe.generateLoaderMessage(\"Scatter Plot Explorer\");\n\t// timeout allows the repaint to catch a break between preload and init\n\tsetTimeout(function(){\n\t\tspe.preloadData();\n\t}, 1);\n}",
"function start() {\n\tgetCurrentPatch()\n\t.then(getChampionIDs)\n\t.then(startScraping)\n\t.then(() => console.log(\"Done scraping.\"))\n\t.catch(function(err) {\n\t\tconsole.log(\"Error on promise chain: \" + err);\n\t\tconsole.log(\"Restarting...\");\n\t\tsleep(30000)\n\t\t.then(start);\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
based on dbscanAlgorithm customized for grouping of line mid point from | function groupsOf(all_lines, posL, posR, radius) {
let groups = [];
//stores nodes that need to get its distance compared
let pivot_index = [];
//gets a random starting poin
let actualGroup = undefined;
while (all_lines.length > 0) {
//there are no neighbors in range
if (pivot_index.length <= 0) {
if (actualGroup) groups.push(actualGroup);
//pivot_index.push(Math.floor(Math.random() * Math.floor(all_lines.length-1)));
pivot_index.push(0);
actualGroup = { m: { x: 0, y: 0 }, l: [] };
//console.log("Random!!");
}
//get latest pivot node
let current_index = pivot_index.pop();
let pivot_line = all_lines[current_index];
if (!pivot_line) continue; //skip current cicle
//console.log(current_index,pivot_line,all_lines.length,all_lines,pivot_index);
let pivot_media = getMedia(pivot_line, posL, posR);
//remove from lines
all_lines.splice(current_index, 1);
//update media of group
actualGroup.m.x *= actualGroup.l.length / (actualGroup.l.length + 1);
actualGroup.m.x += pivot_media.x / (actualGroup.l.length + 1);
//console.log(actualGroup.m.x,pivot_media.x);
actualGroup.m.y *= actualGroup.l.length / (actualGroup.l.length + 1);
actualGroup.m.y += pivot_media.y / (actualGroup.l.length + 1);
//update actual group
actualGroup.l.push(pivot_line);
//search if next item is close enought
if (
current_index < all_lines.length - 1 &&
getPointDistance(
pivot_media,
getMedia(all_lines[current_index], posL, posR)
) < radius
) {
//console.log("inside top : ",current_index);
console.log();
pivot_index.push(current_index);
}
//search if previous item is close enought
if (
current_index >= 1 &&
getPointDistance(
pivot_media,
getMedia(all_lines[current_index - 1], posL, posR)
) < radius
) {
//console.log("inside bot : ",current_index -1);
//smaler should be removed at last
pivot_index.unshift(current_index - 1);
}
//console.log("continuing");
}
//push last group
if (actualGroup) groups.push(actualGroup);
//console.log(groups.length);
lines.groups = groups;
} | [
"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 }",
"findClusterBreak(start, forward) {\n if (start < 0 || start > this.length)\n throw new RangeError(\"Invalid position given to Line.findClusterBreak\");\n let contextStart, context;\n if (this.content == \"string\") {\n contextStart = this.from;\n context = this.content;\n }\n else {\n contextStart = Math.max(0, start - 256);\n context = this.slice(contextStart, Math.min(this.length, contextStart + 512));\n }\n return (forward ? nextClusterBreak : prevClusterBreak)(context, start - contextStart) + contextStart;\n }",
"groupsStartingIn (other) {\n let list = new GroupList()\n for (let group of this.groups) {\n if (group.offset.compare(other.offset) >= 0 && group.offset.compare(other.end()) < 0) list.groups.push(group)\n }\n return list\n }",
"findClusterBreak(start, forward) {\n if (start < 0 || start > this.length)\n throw new RangeError(\"Invalid position given to Line.findClusterBreak\");\n let contextStart, context;\n if (this.content == \"string\") {\n contextStart = this.from;\n context = this.content;\n }\n else {\n contextStart = Math.max(0, start - 256);\n context = this.slice(contextStart, Math.min(this.length, contextStart + 512));\n }\n return (forward ? nextClusterBreak : prevClusterBreak)(context, start - contextStart) + contextStart;\n }",
"function fixLineSeriesGroupStructure(cGroup) {\r\n // Loop, looking for the group\r\n\tvar gLen = cGroup.groupItems.length;\r\n\tfor (var gNo = gLen - 1; gNo >= 0; gNo--) {\r\n // Hunt through the content group\r\n\t\tvar thisGroup = cGroup.groupItems[gNo];\r\n\t\tif (thisGroup.name === c_itsAllLineSeriesOuterGroup) {\r\n\t\t\t// This 'all-series' group should contain 2 inner groups:\r\n // line-series-group:line\r\n // line-series-group:points\r\n // debugger;\r\n var g2Len = thisGroup.groupItems.length - 1;\r\n for (var g2No = g2Len; g2No >= 0; g2No--) {\r\n var innerGroup = thisGroup.groupItems[g2No];\r\n if (\r\n innerGroup.name.search(':points') > 0 ||\r\n innerGroup.name.search(':line') > 0\r\n ) {\r\n // Target group of individual line or points series groups\r\n // If these have contents, move them up a level\r\n // debugger;\r\n if (innerGroup.groupItems.length > 0) {\r\n innerGroup.move(cGroup, ElementPlacement.PLACEATEND);\r\n } else {\r\n thisGroup.remove();\r\n }\r\n }\r\n }\r\n\t\t}\r\n\t}\r\n}",
"_drawLines(keypoint) {\n if (keypoint.indexLabel < 0) return;\n if (!this._edges.hasOwnProperty(keypoint.indexLabel)) return;\n\n let otherIndices = this._edges[keypoint.indexLabel];\n otherIndices.forEach(i => {\n let k2 = this._labelled[i];\n if (!k2) return;\n\n let edge = [keypoint.indexLabel, i];\n this._drawLine(edge, keypoint, k2);\n });\n }",
"function initPointsBySection(xlower, xhigher, ylower, yhigher, widthPoints, heightPoints, split, splitindex) {\n let w = xhigher - xlower;\n let h = yhigher - ylower;\n let winterval = w / widthPoints;\n let hinterval = h / heightPoints;\n\n let pointArray = [];\n\n //split is the number of sections to divide the picture into.\n // splitindex [0..n] is the section number we are calculating\n // only create pointArray for the section we are looking at\n // need t figure out ycount, yhigher and where to stop\n var sectionSize = Math.floor(heightPoints / split);\n //log('split ',heightPoints,' into ',split,' of ',sectionSize,' with ',sectionSize*widthPoints);\n var ycount = splitindex * sectionSize;\n // need to take into account that sectionSize may be rounded down, so last section needs\n // to mop up the last remaining rows\n var yupper;\n if (split - 1 == splitindex) {\n // we are processing the last section\n yupper = heightPoints;\n } else {\n yupper = ycount + sectionSize;\n }\n\n var j = yhigher - ycount * hinterval;\n\n for (; ycount < yupper; j -= hinterval, ycount++) {\n for (var i = xlower, xcount = 0; xcount < widthPoints; i += winterval, xcount++) {\n pointArray.push(new Point(i, j));\n }\n }\n return pointArray;\n}",
"_arrangeTracksLinear(data, allow_overlap = true) {\n if (allow_overlap) {\n // If overlap is allowed, then all the data can live on a single row\n return [data];\n }\n\n // ASSUMPTION: Data is given to us already sorted by start position to facilitate grouping.\n // We do not sort here because JS \"sort\" is not stable- if there are many intervals that overlap, then we\n // can get different layouts (number/order of rows) on each call to \"render\".\n //\n // At present, we decide how to update the y-axis based on whether current and former number of rows are\n // the same. An unstable sort leads to layout thrashing/too many re-renders. FIXME: don't rely on counts\n const {start_field, end_field} = this.layout;\n\n const grouped_data = [[]]; // Prevent two items from colliding by rendering them to different rows, like genes\n data.forEach((item, index) => {\n for (let i = 0; i < grouped_data.length; i++) {\n // Iterate over all rows of the\n const row_to_test = grouped_data[i];\n const last_item = row_to_test[row_to_test.length - 1];\n // Some programs report open intervals, eg 0-1,1-2,2-3; these points are not considered to overlap (hence the test isn't \"<=\")\n const has_overlap = last_item && (item[start_field] < last_item[end_field]) && (last_item[start_field] < item[end_field]);\n if (!has_overlap) {\n // If there is no overlap, add item to current row, and move on to the next item\n row_to_test.push(item);\n return;\n }\n }\n // If this item would collide on all existing rows, create a new row\n grouped_data.push([item]);\n });\n return grouped_data;\n }",
"function segmentMatch(mr) {\n const { matches, index, groups, input } = mr;\n const segments = [];\n let p = index;\n for (let groupNum = 0; groupNum < matches.length; ++groupNum) {\n const m = matches[groupNum];\n if (!m)\n continue;\n // Look forwards for the next best match.\n const idx0 = input.indexOf(m, p);\n // try looking backwards if forwards does not work.\n const idx = idx0 >= p ? idx0 : input.lastIndexOf(m, p);\n if (idx < 0)\n continue;\n segments.push({ match: m, index: idx, groupNum, groupName: undefined });\n p = idx;\n }\n const textToSeg = new Map(segments.map((s) => [s.match, s]));\n for (const [name, value] of Object.entries(groups)) {\n const s = value && textToSeg.get(value);\n if (!s)\n continue;\n s.groupName = s.groupName\n ? Array.isArray(s.groupName)\n ? s.groupName.concat([name])\n : [s.groupName, name]\n : name;\n }\n return segments;\n}",
"function drawLineBresenham(ctx, startX, startY, endX, endY, color, storeIntersectionForScanlineFill) {\n\n var x = startX;\n var y = startY;\n\n // Abstand\n var dX = endX - startX;\n var dY = endY - startY;\n\n // Beträge\n var dXAbs = Math.abs(dX);\n var dYAbs = Math.abs(dY);\n\n // Start kleiner als Ende\n var dXSign = (dX > 0) ? 1 : -1;\n var dYSign = (dY > 0) ? 1 : -1;\n\n // shortcuts for speedup.\n var dXAbs2 = 2 * dXAbs;\n var dYAbs2 = 2 * dYAbs;\n var dXdYdiff2 = 2 * (dXAbs - dYAbs);\n var dYdXdiff2 = 2 * (dYAbs - dXAbs);\n var err;\n\n if(dXAbs >= dYAbs){\n err = dXAbs - dYAbs2;\n while (x != endX){\n x += dXSign;\n if (err > 0){\n err -= dYAbs2;\n } else {\n y += dYSign;\n err += dXdYdiff2;\n addIntersection(x, y);\n }\n framebuffer.set(x, y, getZ(x,y), color);\n }\n } else {\n err = dYAbs - dXAbs2;\n while (y != endY){\n y += dYSign;\n if(err > 0){\n err -= dXAbs2;\n } else {\n x += dXSign;\n err += dYdXdiff2;\n }\n framebuffer.set(x, y, getZ(x,y), color);\n addIntersection(x, y);\n }\n }\n }",
"getOutline(){\n if(!this.surfaces.length) return null;\n let pointsFromSurfaces = [];\n for(let surface of this.surfaces){\n pointsFromSurfaces = pointsFromSurfaces.concat(surface.points);\n }\n return grahamScan(pointsFromSurfaces);\n }",
"function group_parsing(route, dest){\n d3.text(route, function (csvdata) {\n var groups = {};\n var grouped = {};\n var num = +experimentr.data()['num_pairs'];\n var parsedCSV = d3.csv.parseRows(csvdata);\n for (var j = 1; j < parsedCSV.length; j++) {\n if (!(parsedCSV[j][0] in groups)) {\n groups[parsedCSV[j][0]] = [parsedCSV[j]];\n } else {\n groups[parsedCSV[j][0]] = groups[parsedCSV[j][0]].concat([parsedCSV[j]]);\n }\n }\n var values = Object.keys(groups).map(function (key) {\n return groups[key];\n });\n var raw_binary = values.filter(function (d) {\n return d.length == 2;\n });\n if(experimentr.data()['section']=='mat'){\n n_pair = raw_binary.length;\n }\n if(experimentr.data()['section']=='section2'){\n s2_n_pair = raw_binary.length;\n }\n for(i in groups){\n var t = groups[i][0][groups[i][0].length-1];\n if(!(t in grouped)){\n grouped[t] = [groups[i]];\n }else{\n grouped[t] = grouped[t].concat([groups[i]]);\n }\n }\n data[dest] = [];\n var keys = Object.keys(grouped);\n keys.sort();\n var i, len = keys.length;\n for(i=0;i<len;i++){\n data[dest].push(grouped[keys[i]]);\n }\n data[dest].push([]);\n var answer = [];\n for(var i=0;i<raw_binary.length;i++){\n answer.push(raw_binary[i][0][17]);\n }\n data[dest+'_answer'] = answer;\n experimentr.addData(data);\n });\n}",
"function findSnappedLocation(lineLocation){\n\tvar finalLocation=lineLocation;\n\tvar listSize=globalPlList.size;\n\tfor(var i=1;i<=listSize;i++){\n\t\tvar line = globalPlList.get(i.toString());\n\t\tif(line!=undefined){\n\t\t\tvar startPath=line.getPath().getAt(0);\n\t\t\tvar endPath=line.getPath().getAt(1);\n\t\t\tvar tempCircleStart=new google.maps.Circle({\n\t\t\t\tcenter: startPath,\n\t\t\t\tradius: 10\n\t\t\t});\t\n\t\t\tvar tempCircleEnd=new google.maps.Circle({\n\t\t\t\tcenter: endPath,\n\t\t\t\tradius: 10,\n\t\t\t});\t\n\t\t\tvar isStartPath = google.maps.Circle.prototype.contains(lineLocation, tempCircleStart);\n\t\t\tvar isEndPath = google.maps.Circle.prototype.contains(lineLocation, tempCircleEnd);\n\t\t\tif(isStartPath){\n\t\t\t\tfinalLocation=startPath;\n\t\t\t\treturn finalLocation;\n\t\t\t}\n\t\t\telse if(isEndPath){\n\t\t\t\tfinalLocation=endPath;\n\t\t\t\treturn finalLocation;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tlistSize++; //To increase the size if a number is missing from id seq like 1,2,4,5,7 . Here Ids 3 and 6 are missing\n\t\t}\n\t}\n\treturn finalLocation;\n}",
"function addLinesToAdjust(){\r\n\tfor(var i=0; i< lines3DToAdjust.length;i++){\r\n\t\tif(!lines3d.children[lines3DToAdjust[i].line3dIndex].isConstruction){\r\n\t\tfor (var j = 0; j < groupShapesAssociated.length; j++) {\r\n\t\t\tvar gr = groupShapesAssociated[j];\r\n\t\t\t//Find group shape\r\n\t\t\tfor (var k = 0; k < groupShapes.length; k++) {\r\n\t\t\t\tif(groupShapes[k].group == gr ){\t\t\t\t\t\r\n\t\t\t\t\tif(groupShapes[k].type == 'cntrGroup'){\r\n\t\t\t\t\t\tfor (var n=0; n < groupShapes[k].shapes.length; n++) {\r\n\t\t\t\t\t\t\tvar cntr = groupShapes[k].shapes[n];\r\n\t\t\t\t\t\t\tif((! findShapeInList(lines3DToAdjust, cntr.id, null))&&(! findShapeInList(cntrFound, cntr.id, cntr.group))) {\r\n\t\t\t\t\t\t\t\tvar cntrElem = null;\r\n\t\t\t\t\t\t\t\tif(selected3DLine.tochange == 'x'){\r\n\t\t\t\t\t\t\t if(lines3DToAdjust[i].x1 == cntr.x1 || lines3DToAdjust[i].x1 == cntr.x2) {\r\n\t\t\t\t\t\t\t \t cntrElem = {group:groupShapes[k].group, id:cntr.id, x1:cntr.x1, y1:cntr.y1, z1: cntr.z1, x2:cntr.x2, y2:cntr.y2, z2: cntr.z2, shapeType: cntr.shapeType, line3dIndex : cntr.line3dIndex, parent:groupShapes[k].parentIds[n]};\r\n\t\t\t\t\t\t\t \t \tcntrFound.push(cntrElem);\t\t\t\t\t \t \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 if(selected3DLine.tochange == 'y'){\r\n\t\t\t\t\t\t\t if(lines3DToAdjust[i].y1 == cntr.y1 || lines3DToAdjust[i].y1 == cntr.y2) {\r\n\t\t\t\t\t\t\t \t cntrElem = {group:groupShapes[k].group, id:cntr.id, x1:cntr.x1, y1:cntr.y1, z1: cntr.z1, x2:cntr.x2, y2:cntr.y2, z2: cntr.z2, shapeType: cntr.shapeType, line3dIndex : cntr.line3dIndex ,parent:groupShapes[k].parentIds[n]};\r\n\t\t\t\t\t\t\t\t\t\tcntrFound.push(cntrElem);\r\n\t\t \t }\t\t\t\t\t \t \r\n\t\t\t\t\t\t\t }\r\n\t\t\t\t\t\t\t if(selected3DLine.tochange == 'z'){\r\n\t\t\t\t\t\t\t if(lines3DToAdjust[i].z1 == cntr.z1 || lines3DToAdjust[i].z1 == cntr.z2){\r\n\t\t\t\t\t\t\t \t cntrElem = {group:groupShapes[k].group, id:cntr.id, x1:cntr.x1, y1:cntr.y1, z1: cntr.z1, x2:cntr.x2, y2:cntr.y2, z2: cntr.z2, shapeType: cntr.shapeType, line3dIndex : cntr.line3dIndex , parent:groupShapes[k].parentIds[n]};\r\n\t\t\t\t\t\t\t\t\t\tcntrFound.push(cntrElem);\r\n\t\t \t }\t\t\t\t\t \t \r\n\t\t\t\t\t\t\t }\r\n\t\t\t\t\t\t\t}\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}\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\t\t\r\n\t\t}\r\n\tconsole.log(\"Found these lines to update \");\r\n\tconsole.table(cntrFound);\t\r\n}",
"scanRow(map, x, y, dir, prim, player) {\n // If spot is open\n if (map[y][x].fill == 0) {\n let entity = {\n 'player': player,\n 'dir': dir,\n 'prim': prim\n }\n map[y][x].entityInZone = entity;\n\n switch (dir) {\n case 0:\n // Move south\n if(prim){\n // Sending out secondary scanners east and west\n this.scanRow(map, x-1, y, 2, false, player);\n this.scanRow(map, x+1, y, 3, false, player);\n }\n return this.scanRow(map, x, y + 1, dir, prim, player);\n case 1:\n // Move north\n // Sending out secondary scanners east and west\n if(prim){\n // Sending out secondary scanners east and west\n this.scanRow(map, x-1, y, 2, false, player);\n this.scanRow(map, x+1, y, 3, false, player);\n }\n return this.scanRow(map, x, y - 1, dir, prim, player);\n case 2:\n // Move west\n if(prim){\n // Sending out secondary scanners north and south\n this.scanRow(map, x, y+1, 0, false, player);\n this.scanRow(map, x, y-1, 1, false, player);\n }\n return this.scanRow(map, x - 1, y, dir, prim, player);\n case 3:\n // Move east\n if(prim){\n // Sending out secondary scanners north and south\n this.scanRow(map, x, y+1, 0, false, player);\n this.scanRow(map, x, y-1, 1, false, player);\n }\n return this.scanRow(map, x + 1, y, dir, prim, player);\n\n default:\n break;\n }\n } else {\n // console.log(\"Done recursing.\");\n return true;\n }\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}",
"get mergeIndices() {\n if (this._mergeIndices) return this._mergeIndices;\n let mergeIndices = this.splitLines.map((line, i) => {\n let indices = new Map();\n let start = null;\n line.forEach((cell, j) => {\n try {\n if (cell.startsWith(this.escape)) {\n if (typeof start === \"number\") throw \"double start\";\n if (cell.endsWith(this.escape)) return;\n start = j;\n } else\n if (cell.endsWith(this.escape)) {\n if (typeof start !== \"number\") throw \"double end\";\n indices.set(start, j);\n start = null;\n }\n if (j >= line.length - 1 && typeof start === \"number\") throw \"unfinished end\";\n } catch (e) {\n console.error(Array.from(indices.entries()));\n if (e) throw new SyntaxError(`unbalanced escape character (${e}) on line ${i + 1} column ${j + 1}\\n${line}`);\n }\n });\n return Array.from(indices.entries());\n })\n return this._mergeIndices = mergeIndices;\n}",
"getCenter() {\n const vertices = this.vertices;\n let areaSum = 0;\n let x = 0;\n let y = 0;\n\n vertices.forEach((currVertex, currIndex) => {\n const nextIndex = (currIndex + 1) % vertices.length;\n const nextVertex = vertices[nextIndex];\n\n const areaDiff = currVertex.x * nextVertex.y - nextVertex.x * currVertex.y;\n areaSum += areaDiff;\n\n x += (currVertex.x + nextVertex.x) * areaDiff;\n y += (currVertex.y + nextVertex.y) * areaDiff;\n });\n\n // If this is a straight line\n if (!areaSum) {\n return vertices.reduce((sumVertex, currVertex) => ({\n x: sumVertex.x + (currVertex.x / this.vertices.length),\n y: sumVertex.y + (currVertex.y / this.vertices.length)\n }), {\n x: 0,\n y: 0\n });\n }\n\n const factor = areaSum * 3;\n\n return new Vertex({\n x: x / factor,\n y: y / factor\n });\n }",
"snappingEdgeData(point) {\n // build a list of edges (in RWU) available for snapping\n // deep copy all vertices on the current story\n let snappableEdges = [...this.currentStoryGeometry.edges];\n\n // TODO: conditionally combine this list with edges from the next story down if it is visible\n if (this.previousStoryGeometry) {\n snappableEdges = snappableEdges.concat(this.previousStoryGeometry.edges.map(e => ({\n ...e,\n previous_story: true,\n })));\n }\n\n if (snappableEdges.length === 0) { return []; }\n\n // find the edge closest to the point being tested\n const distyEdges = _.map(\n snappableEdges, (edge) => {\n const\n aStoryGeometry = edge.previous_story ? this.previousStoryGeometry : this.currentStoryGeometry,\n // look up vertices associated with edges\n aV1 = geometryHelpers.vertexForId(edge.v1, aStoryGeometry),\n aV2 = geometryHelpers.vertexForId(edge.v2, aStoryGeometry),\n // project point being tested to each edge\n aProjection = projectionOfPointToLine(point, { p1: aV1, p2: aV2 }),\n\n // look up distance between projection and point being tested\n aDist = distanceBetweenPoints(aProjection, point);\n return {\n ...edge,\n projection: aProjection,\n dist: aDist,\n v1Coords: aV1,\n V2Coords: aV2,\n };\n });\n const nearestEdge = _.minBy(distyEdges, 'dist');\n\n // // look up vertices associated with nearest edge\n // const nearestEdgeStoryGeometry = nearestEdge.previous_story ? this.previousStoryGeometry : this.currentStoryGeometry;\n // const nearestEdgeV1 = geometryHelpers.vertexForId(nearestEdge.v1, nearestEdgeStoryGeometry);\n // const nearestEdgeV2 = geometryHelpers.vertexForId(nearestEdge.v2, nearestEdgeStoryGeometry);\n // // take the projection of the cursor to the edge\n // // check if the angle of the segment defined by the cursor and projection is < the angle snap tolerance\n // const snappableAngles = [-180, -90, 0, 90, 180];\n // // angle between projection and mouse (degrees)\n // const thetaDeg = Math.atan2(point.y - nearestEdge.projection.y, point.x - nearestEdge.projection.x)\n // * (180 / Math.PI);\n\n // // if the original projection is within the snap tolerance of one of the snapping angles\n // // adjust the projection so that it is exactly at the snap angle\n // // snap to -180, -90, 0, 90, 180\n // snappableAngles.some((angle) => {\n // // if the original projection is within the snap tolerance of one of the snapping angles\n // // adjust the projection so that it is exactly at the snap angle\n // if (Math.abs(thetaDeg - angle) < this.$store.getters['project/angleTolerance']) {\n // // infer a line defining the desired projection\n // var adjustedProjectionP1;\n // var adjustedProjectionP2;\n // if (angle === 180 || angle === 0 || angle === -180) {\n // adjustedProjectionP1 = { x: point.x - (2 * nearestEdge.dist), y: point.y }\n // adjustedProjectionP2 = { x: point.x + (2 * nearestEdge.dist), y: point.y }\n // } else if (angle === 90 || angle === -90) {\n // adjustedProjectionP1 = { x: point.x, y: point.y - (2 * nearestEdge.dist) }\n // adjustedProjectionP2 = { x: point.x, y: point.y + (2 * nearestEdge.dist) }\n // }\n // // adjust the projection to be the intersection of the desired projection line and the nearest edge\n // if (geometryHelpers.ptsAreCollinear(adjustedProjectionP1, nearestEdgeV1, adjustedProjectionP2)) {\n // projection = nearestEdgeV1;\n // } else if (geometryHelpers.ptsAreCollinear(adjustedProjectionP1, nearestEdgeV2, adjustedProjectionP2)) {\n // projection = nearestEdgeV2;\n // } else {\n // projection = geometryHelpers.intersectionOfLines(adjustedProjectionP1, adjustedProjectionP2, nearestEdgeV1, nearestEdgeV2);\n // }\n // return true;\n // }\n // return false;\n // });\n\n // return data for the edge if the projection is within the snap tolerance of the point\n if (nearestEdge.dist < this.$store.getters['project/snapTolerance']) {\n return [{\n snappingEdge: nearestEdge,\n dist: nearestEdge.dist,\n type: 'edge',\n // projection and snapping edge vertices translated into grid coordinates (to display snapping point and highlight edges)\n projection: nearestEdge.projection,\n v1GridCoords: nearestEdge.v1Coords,\n v2GridCoords: nearestEdge.V2Coords,\n x: nearestEdge.projection.x,\n y: nearestEdge.projection.y,\n }];\n }\n return [];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a HTML element for a unlockable item in the skill tree | function createSkillItem(item, index) {
// Item div
var itemDiv = document.createElement("div");
itemDiv.classList.add("item");
itemDiv.id = "skill-item-" + index;
itemDiv.setAttribute("tooltip", "");
// Item Picture
var itemPic = document.createElement("div");
itemPic.classList.add("item-pic");
itemPic.style.backgroundImage = "url(\"" + item.sprite + "\")";
// Checkmark shown when the item is unlocked
var checkMark = document.createElement("div");
checkMark.classList.add("check");
// Register an onclick handler
itemDiv.onclick = function(event) {
// If the player's lavel is enough and the player didn't unlock this yet
if (window.game.player.getLevel() >= item.levelNeeded && !window.game.player.unlockedItems.includes(item)) {
// Unlock the item
window.game.player.unlockItem(item);
// Append the checkmark
itemDiv.appendChild(checkMark);
// Flash this element
itemDiv.classList.add("flash-fast");
setTimeout(function() {
itemDiv.classList.remove("flash-fast");
}, 500);
// Go through all fruit trees and check if we can unlock them now
window.game.farm.fruitTrees.forEach(function(fruitTree) {
if (fruitTree.fruit == item && fruitTree.isLocked) {
fruitTree.setLocked(false);
}
})
// Repopulate the store so new items will be buyable
populateStore();
}
}
// Append the picture to the item div
itemDiv.appendChild(itemPic);
// Initially set the check marks on unlocked items
if (window.game.player.unlockedItems.includes(item)) {
itemDiv.appendChild(checkMark);
// Also initially unlock the trees which are unlocked from start
window.game.farm.fruitTrees.forEach(function(fruitTree) {
if (fruitTree.fruit == item && fruitTree.isLocked) {
fruitTree.setLocked(false);
}
})
};
// Return the created div
return itemDiv;
} | [
"function populateSkillTree() {\n // Get the skill tree DOM element and clear it\n var skillTree = document.getElementById(\"skill-tree\");\n skillTree.innerHTML = \"\";\n\n // Initially unlock the apple and the wheat\n if (!window.game.player.unlockedItems.includes(ITEM_APPLE) && !window.game.player.unlockedItems.includes(ITEM_WHEAT)) {\n window.game.player.unlockedItems.push(ITEM_APPLE);\n window.game.player.unlockedItems.push(ITEM_WHEAT);\n }\n\n // Create a row for each skill tree item\n ITEMS_FOR_SKILL.forEach(function(item, index) {\n skillTree.appendChild(createSkillRow(item, index));\n });\n\n // Resetup tooltips\n setupTooltips();\n \n // Repopulate the store\n populateStore();\n}",
"function 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 buildItem(heading, currentLevel, maxLevel) {\n if (currentLevel > maxLevel) { return; }\n\n const item = $('<li class=\"usa-sidenav__item\"></li>');\n const link = $(`<a href=\"#${heading.attr(\"id\")}\">${heading.text()}</a>`);\n item.append(link);\n\n if (!(currentLevel + 1 > maxLevel)) {\n const sublist = buildSublist(heading, currentLevel, maxLevel);\n item.append(sublist);\n }\n\n return item;\n }",
"function addItem(skill) {\r\n const text = `<li class=\"item\">\r\n <p class=\"text\"> ${skill} </p>\r\n <i class=\"far fa-times-circle delete-btn\" func=\"delete\"></i>\r\n </li>\r\n `;\r\n const position = \"beforeend\";\r\n\r\n list.insertAdjacentHTML(position, text);\r\n}",
"function createCapChanger() {\n var levelCapChanger = document.createElement('li');\n\n var levelCapStyle = document.createElement('style');\n levelCapStyle.innerHTML = \"#level_cap_control::after {border-bottom:1px dotted #9b9a9a;bottom:0;content:'';display:block;left:11px;position:absolute;right:11px;}\";\n levelCapChanger.appendChild(levelCapStyle);\n\n var linkCapChanger = document.createElement('a');\n linkCapChanger.id = 'level_cap_control';\n linkCapChanger.innerHTML = 'Level cap';\n linkCapChanger.href = '#';\n linkCapChanger.addEventListener('click', function () {\n setFakeMaxLevel();\n });\n levelCapChanger.appendChild(linkCapChanger);\n\n var signOut = document.getElementById('welcome_box_sign_out');\n var cogList = signOut.parentNode.parentNode;\n cogList.insertBefore(levelCapChanger, signOut.parentNode);\n}",
"function renderSelectedSkills() {\n // Get div\n let selected = document.getElementById(\"selected-skills\");\n \n // Clear old skills\n while (selected.firstChild) {\n selected.removeChild(selected.firstChild);\n }\n\n // Create the skill name text and dropdown selector for each selected skill\n for(let name of Object.keys(selectedSkills)){\n // Create new skill div container\n let newSkill = document.createElement(\"div\");\n newSkill.className = \"skill\";\n let newSkillText = document.createElement(\"p\");\n newSkillText.innerText = name;\n\n // Add level selector dropdown\n let newSkillLevel = document.createElement(\"select\");\n newSkillLevel.className = \"selected-level\";\n newSkillLevel.onchange = function() {updateLevels(this)};\n createLevelRange(newSkillLevel, skillList[name], selectedSkills[name]);\n \n // Append to the skill list\n newSkill.appendChild(newSkillText);\n newSkill.appendChild(newSkillLevel);\n selected.appendChild(newSkill);\n }\n}",
"function addResultToSpecialAbilityInfoBox(description) {\n var el = document.getElementById('special_ability_template_info');\n el.innerHTML=description;\n}",
"function clickItem(number) {\n if(blockInput) \n return; \n // Check if the user has an item in that slot. \n if(!items[number])\n return; \n // Heal the player. \n playerChar.hp += itemHealing; \n if (playerChar.hp > playerMaxHP) \n playerChar.hp = playerMaxHP; \n // Remove the item from that slot. \n items[number] = null; \n $(\"#divCombatButton\" + number).empty();\n}",
"function createLockLevelPopUp(){\n\t\t\t\t\t\t\tvar levelChoose=new lib.levelChooseBoard();\n\t\t\t\t\t\t\tlevelChoose.x=myStage/2-levelChoose.nominalBounds.width/2;\n\t\t\t\t\t\t\tlevelChoose.y=myStage/2-levelChoose.nominalBounds.height/2;\n\t\t\t\t\t\t\tstage.addChild(levelChoose);\n\t\t\t\t\t\t}",
"function showSkill(skill) {\n var content =\n '<p>' + skill.title + '</p>' +\n '<div class=\"w3-light-grey w3-round-xlarge w3-small\" style=\"color:#52B77C;\">' +\n '<div class=\"w3-container w3-center w3-round-xlarge w3-teal\" style=\"width:' + skill.skill_level + '%\">' + skill.skill_level + '%</div>' +\n '</div>'\n $('#skills-list').append(content);\n}",
"function addHeroInventoryItemToPage(listId,listItem){\n // Create a new list element\n let newListItem = document.createElement(\"li\");\n // Set the id attribute for the new inventory item\n newListItem.setAttribute(\"id\", listId);\n // Create the content for the new inventory item\n let newContent = document.createTextNode(listItem);\n // Add the new inventory item to the newly created list element\n newListItem.appendChild(newContent);\n // Add the new inventory item to the document ul element\n heroInventoryId.appendChild(newListItem);\n }",
"createItem() {\n\t\tvar $li = $('<li>')\n\t\t$li.text(this.name)\n\t\tvar _this = this\n\t\t$li.on('click', function() {\n\t\t\tvar $page = _this.createPage()\n\t\t\tvar $view = $('#job-view')\n\t\t\t$view.empty()\n\t\t\t$view.append($page)\n\t\t})\n\t\treturn $li\n\t}",
"function get_skill_level(skill)\n{\n if (skill.firstChild.firstChild.firstChild.firstChild.childNodes[2].firstChild.childNodes.length == 1){\n return 0; // skill is still locked so I am on level 0\n }\n return skill.firstChild.firstChild.firstChild.firstChild.childNodes[2].firstChild.childNodes[1].innerHTML;\n}",
"function levelitem(weapon, index) {\n var oldLevel = 0;\n if (weapon) {\n oldLevel = members[index].weapon.level;\n } else {\n oldLevel = members[index].armor.level;\n }\n var oldForm = 0;\n if (weapon) {\n oldForm = members[index].weapon.iform;\n } else {\n oldForm = members[index].armor.iform;\n }\n var rr = Math.random();\n var tr = 0;\n // Tier\n if (rr < 0.05) {\n tr = 5;\n } else if (rr < 0.15) {\n tr = 4;\n } else if (rr < 0.35) {\n tr = 3;\n } else if (rr < 0.6) {\n tr = 2;\n } else {\n tr = 1;\n }\n\n var rarR = Math.floor(Math.random()*3);\n var matR = Math.floor(Math.random()*3);\n var namR = Math.floor(Math.random()*3);\n var eR = Math.floor(Math.random()*2);\n\n if (weapon) {\n members[index].weapon = new Weapon(oldLevel+1, matR, tr, oldForm, namR, rarR, eR);\n } else {\n members[index].armor = new Armor(oldLevel+1, matR, tr, oldForm, namR, rarR, eR);\n }\n updateMembers();\n}",
"function unlock(items) {\n // product: .... the <product> in the store!\n // walk: .... Esa is able to walk to the <walk> now!\n // selector: maybe don't do this. or we need a genenral one.\n\n for (i = 0; i<items.length; i++ ) {\n if ('product' in items[i]) {\n alert('You just unlocked the ' + items[i].product + ' in the store!');\n var product = $.grep(products, function(e){ return e.item == items[i].product; });\n product[0].enabled = 1;\n } else if ('walk' in items[i]) {\n alert('You can now walk with Esa to the ' + items[i].walk + '!');\n } else if ('selector' in items[i]) {\n alert('You can now.... ' + items[i].something + '! Click here!');\n }\n }\n}",
"logoutItem() {\n if (!(this.props.currentUser === undefined || this.props.currentUser === null ||\n this.props.currentUser === 'Not Logged In')) {\n return (\n <li>\n <a onClick={this.props.logout}>Log Out</a>\n </li>\n );\n }\n }",
"function ListItem(listItemArguments, removalFunction) {\n function createRemovalButton(itemId, removalFunction) {\n var button = document.createElement('button');\n button.textContent = 'Remove';\n button.setAttribute('class', 'delete-button');\n button.addEventListener('click', function(e) {\n e.preventDefault();\n removalFunction(itemId);\n });\n return button;\n }\n\n function createListText(listArguments) {\n var smokerText = listArguments.smoker ? 'Smoker' : 'Non-Smoker';\n var rel = listArguments.rel[0].toUpperCase() + listArguments.rel.slice(1);\n return (rel + ', Age ' + listArguments.age + ', ' + smokerText);\n }\n\n function createListItem(listItemArguments, removalFunction) {\n var li = document.createElement('li');\n var listItemId = listItemArguments.id;\n var removalButton = createRemovalButton(listItemId, removalFunction);\n var contentText = createListText(listItemArguments);\n var span = document.createElement('span');\n\n span.textContent = contentText;\n span.setAttribute('class', 'household-text');\n li.setAttribute('id', listItemId);\n li.setAttribute('class', 'household-list');\n\n li.appendChild(span);\n li.appendChild(removalButton);\n return li;\n }\n return createListItem(listItemArguments, removalFunction);\n}",
"function createItem() {\n\t\tvar clInput = document.querySelector('#cl-item'),\n\t\t\tchecklistText = clInput.value,\n\t\t\tli = generateListitem(checklistText);\n\n\t\toptions.appendChild(li);\n\n\t\tchecklist.push(checklistText);\n\t\tupdateChecklist();\n\n\t\t//reset checklist input value to empty\n\t\tclInput.value = \"\";\n\t}",
"function renderTweetItem(username,tweet){\n $(\"#itemResult\").html(''); // clear previous list elements\n var listElement = createTweetDomContainer(username,tweet,false);\n $(\"#itemResult\").append(listElement);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if this cuboid is overlapped with the other cuboid | isOverlapped(other) {
return (
this._isInRange(other.x - other.w, this.x, this.w) ||
this._isInRange(other.x + other.w, this.x, this.w) ||
this._isInRange(other.y - other.h, this.y, this.h) ||
this._isInRange(other.y + other.h, this.y, this.h) ||
this._isInRange(other.z - other.d, this.z, this.d) ||
this._isInRange(other.z + other.d, this.z, this.d)
)
} | [
"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 }",
"collide(other) {\n // Don't collide if inactive\n if (!this.active || !other.active) {\n return false;\n }\n\n // Standard rectangular overlap check\n if (this.x + this.width > other.x && this.x < other.x + other.width) {\n if (this.y + this.height > other.y && this.y < other.y + other.height) {\n return true;\n }\n }\n return false;\n }",
"getOverlap(topLeft1, bottomRight1, topLeft2, bottomRight2) {\n\t\tif (topLeft1.x > bottomRight2.x || topLeft2.x > bottomRight1.x) {\n\t\t\t// rectangles are to the left/right of eachother \n\t\t\treturn false;\n\t\t}\n\t\telse if (topLeft1.y > bottomRight2.y || topLeft2.y > bottomRight1.y) {\n\t\t\t// rectangles are above/below each other\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}",
"function detect_collision(obj1, obj2) {\r\n\tif ((obj1.x + obj1.width > obj2.x) &&\r\n\t\t(obj1.x < obj2.x + obj2.width) &&\r\n\t\t(obj1.y + obj1.height > obj2.y) &&\r\n\t\t(obj1.y < obj2.y + obj2.height)) {\r\n\t\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}",
"isCollide(potato) {\n\n\n // Helper Function to see if objects overlap\n const overLap = (objectOne, objectTwo) => {\n\n // Check X-axis if they dont overlap\n if (objectOne.left > objectTwo.right || objectOne.right < objectTwo.left) {\n return false;\n }\n // Check y-axis if they dont overlap\n // 100 \n // 200 ObjectTwo Bottom\n // 300 ObjectOne Top\n if (objectOne.top > objectTwo.bottom || objectOne.bottom < objectTwo.top) {\n return false;\n }\n return true;\n }\n\n let collision = false;\n\n this.eachObject((object) => {\n if (overLap(object, potato)) {\n collision = true\n }\n\n });\n\n return collision\n\n\n }",
"isColliding() {\n this.getCorners();\n return Line.isColliding(this.hitboxLines, sceneHitboxLines.filter(line => this.hitboxLines.indexOf(line) === -1));\n }",
"function overlap_rect(o1, o2, buf) {\n\t if (!o1 || !o2) return true;\n\t if (o1.x + o1.w < o2.x - buf || o1.y + o1.h < o2.y - buf || o1.x - buf > o2.x + o2.w || o1.y - buf > o2.y + o2.h) return false;\n\t return true;\n\t }",
"collides(vertices1, axes1, vertices2, axes2, out) {\n projectMinMaxMany(vertices1, axes1, axes2, this.cacheRanges1);\n projectMinMaxMany(vertices2, axes1, axes2, this.cacheRanges2);\n let comparisons = axes1.length + axes2.length;\n let smOverlap = Infinity;\n let smOverlapIdx = -1;\n let smDir = -1;\n for (let i = 0; i < comparisons; i++) {\n let p = this.cacheRanges1[i];\n let q = this.cacheRanges2[i];\n // case 1: OK\n //\t p.x\t\tp.y\t Q.x\t\t Q.y\n // ---+==========+-----+===========+--------\n //\n // case 2: OK\n //\t Q.x\t\tQ.y\t p.x\t\t p.y\n // ---+==========+-----+===========+--------\n //\n // case 3: COLLIDING\n //\t p.x\t\tQ.x\t p.y\t\t Q.y\n // ---+==========+=====+===========+--------\n //\n // case 4: COLLIDING\n //\t Q.x\t\tp.x\t Q.y\t\t p.y\n // ---+==========+=====+===========+--------\n if (p.y < q.x || q.y < p.x) {\n // non-overlap on any axis means safe\n return false;\n }\n // overlap on this axis. track it + direction in case we have\n // a collision and this is the axis w/ smallest amt.\n let diff1 = p.y - q.x;\n let diff2 = q.y - p.x;\n let overlap, direction;\n if (diff1 < diff2) {\n overlap = diff1;\n direction = 1;\n }\n else {\n overlap = diff2;\n direction = -1;\n }\n if (overlap < smOverlap) {\n smOverlap = overlap;\n smOverlapIdx = i;\n smDir = direction;\n }\n }\n // set collision info w/ smallest (kinda gross b/c two arrays...)\n let smAxis = smOverlapIdx < axes1.length ? axes1[smOverlapIdx] : axes2[smOverlapIdx - axes1.length];\n out.axis.copyFrom_(smAxis);\n out.amount = smOverlap * smDir;\n // and return that we did collide\n return true;\n }",
"overlap (other = new Rectangle())\n {\n let olWidth = Math.min(this.position.x + this.width, other.position.x + other.width) - Math.max(this.position.x, other.position.x);\n let olHeight = Math.min(this.position.y + this.height, other.position.y + other.height) - Math.max(this.position.y, other.position.y);\n\n if (olWidth <= 0 || olHeight <= 0) { return new Rectangle(); }\n\n let olX = Math.max(this.position.x, other.position.x);\n let olY = Math.min(this.position.y, other.position.y);\n\n return new Rectangle(new Vector(olX, olY), olWidth, olHeight);\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}",
"intersectsWith(anotherCollider) {\n\n let delta = [\n this.x - anotherCollider.x, \n this.y - anotherCollider.y\n ];\n\n let dist = magnitudeSquared(delta);\n let r = this.radius + anotherCollider.radius;\n \n return dist < r*r;\n }",
"detectCollisions() {\n const sources = this.gameObjects.filter(go => go instanceof Player);\n const targets = this.gameObjects.filter(go => go.options.hasHitbox);\n\n for (const source of sources) {\n for (const target of targets) {\n /* Skip source itself and if source or target is destroyed. */\n if (\n source.uuid === target.uuid ||\n source.isDestroyed ||\n target.isDestroyed\n )\n continue;\n this.checkCollision(source, target);\n }\n }\n }",
"collide(rect) {\n return (this.left < rect.right && this.right > rect.left &&\n this.top < rect.bottom && this.bottom > rect.top);\n }",
"collideOverlaps(overlaps){\n\t\tif(overlaps.length <= 0)\n\t\t\treturn;\n\t\tvar c = this.getCol();\n\t\tfor(var i = 0; i < overlaps.length; i += 1){\n\t\t\tif(overlaps[i].largestSideLength() < 2)\n\t\t\t\tcontinue;\n\t\t\n\t\t\tif(overlaps[i].size.x > overlaps[i].size.y){ //vertical collision\n\t\t\t\tif(c.top() == overlaps[i].top()) // ceiling\n\t\t\t\t\tthis.hitCeiling(overlaps[i].bottom());\n\t\t\t\telse this.hitGround(overlaps[i].top()); //ground\n\t\t\t}\n\t\t\telse{ //horizontal collision\n\t\t\t\tif(c.left() == overlaps[i].left()) //right wall\n\t\t\t\t\tthis.hitLWall(overlaps[i].right());\n\t\t\t\telse this.hitRWall(overlaps[i].left()); // left wall\n\t\t\t}\n\t\t}\n\t}",
"testBoxOverlaps() {\n // Overlapping tests.\n let box2 = new Box(1, 4, 4, 1);\n\n // Corner overlaps.\n assertTrue('NW overlap', boxOverlaps(new Box(0, 2, 2, 0), box2));\n assertTrue('NE overlap', boxOverlaps(new Box(0, 5, 2, 3), box2));\n assertTrue('SE overlap', boxOverlaps(new Box(3, 5, 5, 3), box2));\n assertTrue('SW overlap', boxOverlaps(new Box(3, 2, 5, 0), box2));\n\n // Inside.\n assertTrue('Inside overlap', boxOverlaps(new Box(2, 3, 3, 2), box2));\n\n // Around.\n assertTrue('Outside overlap', boxOverlaps(new Box(0, 5, 5, 0), box2));\n\n // Edge overlaps.\n assertTrue('N overlap', boxOverlaps(new Box(0, 3, 2, 2), box2));\n assertTrue('E overlap', boxOverlaps(new Box(2, 5, 3, 3), box2));\n assertTrue('S overlap', boxOverlaps(new Box(3, 3, 5, 2), box2));\n assertTrue('W overlap', boxOverlaps(new Box(2, 2, 3, 0), box2));\n\n assertTrue('N-in overlap', boxOverlaps(new Box(0, 5, 2, 0), box2));\n assertTrue('E-in overlap', boxOverlaps(new Box(0, 5, 5, 3), box2));\n assertTrue('S-in overlap', boxOverlaps(new Box(3, 5, 5, 0), box2));\n assertTrue('W-in overlap', boxOverlaps(new Box(0, 2, 5, 0), box2));\n\n // Does not overlap.\n box2 = new Box(3, 6, 6, 3);\n\n // Along the edge - shorter.\n assertFalse('N-in no overlap', boxOverlaps(new Box(1, 5, 2, 4), box2));\n assertFalse('E-in no overlap', boxOverlaps(new Box(4, 8, 5, 7), box2));\n assertFalse('S-in no overlap', boxOverlaps(new Box(7, 5, 8, 4), box2));\n assertFalse('N-in no overlap', boxOverlaps(new Box(4, 2, 5, 1), box2));\n\n // By the corner.\n assertFalse('NE no overlap', boxOverlaps(new Box(1, 8, 2, 7), box2));\n assertFalse('SE no overlap', boxOverlaps(new Box(7, 8, 8, 7), box2));\n assertFalse('SW no overlap', boxOverlaps(new Box(7, 2, 8, 1), box2));\n assertFalse('NW no overlap', boxOverlaps(new Box(1, 2, 2, 1), box2));\n\n // Perpendicular to an edge.\n assertFalse('NNE no overlap', boxOverlaps(new Box(1, 7, 2, 5), box2));\n assertFalse('NEE no overlap', boxOverlaps(new Box(2, 8, 4, 7), box2));\n assertFalse('SEE no overlap', boxOverlaps(new Box(5, 8, 7, 7), box2));\n assertFalse('SSE no overlap', boxOverlaps(new Box(7, 7, 8, 5), box2));\n assertFalse('SSW no overlap', boxOverlaps(new Box(7, 4, 8, 2), box2));\n assertFalse('SWW no overlap', boxOverlaps(new Box(5, 2, 7, 1), box2));\n assertFalse('NWW no overlap', boxOverlaps(new Box(2, 2, 4, 1), box2));\n assertFalse('NNW no overlap', boxOverlaps(new Box(1, 4, 2, 2), box2));\n\n // Along the edge - longer.\n assertFalse('N no overlap', boxOverlaps(new Box(0, 7, 1, 2), box2));\n assertFalse('E no overlap', boxOverlaps(new Box(2, 9, 7, 8), box2));\n assertFalse('S no overlap', boxOverlaps(new Box(8, 7, 9, 2), box2));\n assertFalse('W no overlap', boxOverlaps(new Box(2, 1, 7, 0), box2));\n }",
"function isColliding(x1, y1, x2, y2, sr){\n var dx = x2 - x1;\n var dy = y2 - y1;\n var dr = sr + 50;\n\n if(dx === 0 && dy === 0){\n return false;\n } else {\n return (Math.pow(dx, 2) + Math.pow(dy, 2)) < Math.pow(dr, 2);\n }\n}",
"function collision(x1, y1, radius1, x2, y2, radius2) {\n return Math.hypot(x1 - x2, y1 - y2) < radius1 + radius2 ? true : false;\n}",
"function includes(b, p) {\n return p.x >= b.x && p.x <= b.x + b.width && p.y >= b.y && p.y <= b.y + b.height;\n}",
"function equalBoxes(bb1, bb2){\n\treturn (bb1.min.x == bb2.min.x &&\n\t\tbb1.min.y == bb2.min.y && bb1.max.x == bb2.max.x &&\n\t\tbb1.max.y == bb2.max.y);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts the name of a data url like `data:image/jpeg;name=hindenburg.jpg;base64,`..., if any. | function getDataUrlFileName(url) {
var p = url && url.split(';base64,');
var q = p.length ? p[0].split(';').find(function (s) { return s.includes('name='); }) : '';
p = q ? q.split('=') : [];
return p[p.length - 1];
} | [
"function makeDataURI(image) {\n if (image.mime && image.data) {\n image.data = 'data:' + image.mime\n + ';base64,' + image.data;\n }\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}",
"function buildUriSpec(data) {\n var uriSpec = '';\n\n data.uriSpec.parts.forEach(function(part) {\n if (part.variable) {\n if (data[part.value] == undefined && DEFAULTS[part.value]) {\n part.value = DEFAULTS[part.value];\n } else {\n part.value = data[part.value];\n }\n }\n\n uriSpec += part.value;\n });\n\n return uriSpec;\n}",
"getUrl (name) {\n name = name.name ? name.name : name\n return this.urls[name]\n }",
"function toDataURL() {\n var reader = new FileReader(),\n deferred = $.Deferred(),\n file = this;\n reader.onload = function(e){\n deferred.resolve({ filename: file.name, data: e.target.result });\n }\n reader.readAsDataURL(file);\n return deferred.promise();\n }",
"function extractHostname(t) {\n return (t.indexOf(\"//\") > -1 ? t.split(\"/\")[2] : t.split(\"/\")[0]).split(\":\")[0].split(\"?\")[0]\n}",
"function htmlNameOfDataAttribute (attribute) {\n attribute.replace(/([a-z][A-Z])/g, function (match) { \n return match[0] + '-' + match[1].toLowerCase();\n });\n return 'data-' + attribute;\n}",
"function getImageName(category, callBack) {\n\t\t\tif (getImageName.imageName) {\n\t\t\t\tcallBack(getImageName.imageName);\n\t\t\t} else {\n\t\t\t\tsuite.execute('vm image list --json', function (result) {\n\t\t\t\t\tvar imageList = JSON.parse(result.text);\n\n\t\t\t\t\timageList.some(function (image) {\n\t\t\t\t\t\tif (image.category.toLowerCase() === category.toLowerCase()) {\n\t\t\t\t\t\t\tgetImageName.imageName = image.name;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tcallBack(getImageName.imageName);\n\t\t\t\t});\n\t\t\t}\n\t\t}",
"function domainName(url){\n// if url begins with s: followed by wwww\n if (url.includes(\"s:\\//www\")) {\nreturn url.slice(12).split('.')[0]; \n } else if (url.includes(\"p:\\//www\")) {\nreturn url.slice(11).split('.')[0];\n } else if (url.includes(\"ps:\")) {\nreturn url.slice(8).split('.')[0];\n } else if (url.includes(\"ttp:\")) {\nreturn url.slice(7).split('.')[0];\n } else if (url.includes(\"www.\")) {\nreturn url.slice(4).split('.')[0];\n } else {\n \treturn url.slice(0).split('.')[0];\n }\n}",
"getParameterByUrlName(name) {\n\t name = name.replace(/[\\[]/, \"\\\\[\").replace(/[\\]]/, \"\\\\]\");\n\t var regex = new RegExp(\"[\\\\?&]\" + name + \"=([^&#]*)\"),\n\t results = regex.exec(location.search);\n\t return results === null ? \"\" : decodeURIComponent(results[1].replace(/\\+/g, \" \"));\n\n\t // console.log(this.getParameterByUrlName('cotizacion_id')) how work\n\t // https://es.stackoverflow.com/questions/445/c%C3%B3mo-obtener-valores-de-la-url-get-en-javascript\n\t}",
"chooseArtistImage(data) {\n \tvar imgSrc;\n \tif (data.images.length > 3) {\n imgSrc = data.images[2].url;\n } else if (data.images.length > 1) {\n imgSrc = data.images[0].url;\n } else {\n imgSrc = 'http://placehold.it/45x45';\n };\n return imgSrc;\n }",
"function generateCampaignName() {\n var splitURL = window.location.href.split('/');\n return splitURL[3];\n}",
"function imageData2dataURL(imageData){\n var c = document.createElement('canvas');\n c.width = imageData.width;\n c.height = imageData.height;\n var ctx = c.getContext('2d');\n ctx.putImageData(imageData, 0, 0);\n return c.toDataURL('image/png');\n}",
"function findPNG(desc){\n\tvar indexPNG = desc.indexOf('.png');\n\tvar imageUrl;\n\tif (indexPNG === -1) {\n\t\timageUrl = '../img/EarthInHand.jpg';\n\t\treturn imageUrl;\n\t} else {\n\t\tvar descUntilFirstPNG = desc.substring(0, indexPNG);\n\t\tvar indexHTTP = descUntilFirstPNG.lastIndexOf('http');\n\t\t\n\t\tif (indexHTTP === -1) {\n\t\t\t// if no .png is found returns default image\n\t\t\timageUrl = '../img/EarthInHand.jpg';\n\t\t\treturn imageUrl;\n\t\t\n\t\t} else {\n\t\t\t// if .png is found checks whether it is social network icon\n\t\t\timageUrl = desc.substring(indexHTTP, indexPNG + 4);\n\t\t\tvar social = findSocial(imageUrl);\n\t\t\tif (social === true) {\n\t\t\t\timageUrl = '../img/EarthInHand.jpg';\n\t\t\t} else {\n\t\t\t\treturn imageUrl;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn imageUrl;\n\t}\n}",
"static blobToImage(data)\n\t{\n\t\tvar URLObj = window['URL'] || window['webkitURL'];\n\t\tvar src = URLObj.createObjectURL(data);\n\t\tvar img = new Image();\n\t\timg.src = src;\n\t\treturn img;\n\t}",
"function getAttachmentName(mime) {\n if (\"headers\" in mime && mime.headers.has(\"content-disposition\")) {\n let c = mime.headers.get(\"content-disposition\")[0];\n if (/^attachment/i.test(c)) {\n return EnigmailMime.getParameter(c, \"filename\");\n }\n }\n return null;\n}",
"function getDisplayName(generatorName) {\n // Breakdown of regular expression to extract name (group 3 in pattern):\n //\n // Pattern | Meaning\n // -------------------------------------------------------------------\n // (generator-)? | Grp 1; Match \"generator-\"; Optional\n // (polymer-init)? | Grp 2; Match \"polymer-init-\"; Optional\n // ([^:]+) | Grp 3; Match one or more characters != \":\"\n // (:.*)? | Grp 4; Match \":\" followed by anything; Optional\n return generatorName.replace(/(generator-)?(polymer-init-)?([^:]+)(:.*)?/g, '$3');\n}",
"function get_Nature(theURL,mycompstr) {\r\n var theDOI = theURL.substring(mycompstr.length,theURL.length+1);\r\n return theDOI;\r\n}",
"getFetcherName () {\n\t\tconst definition = this.definition;\n\t\tlet fetcherName;\n\n\t\tfetcherName = definition.fetcher;\n\n\t\tif (!fetcherName) {\n\t\t\tconst name = definition.name;\n\t\t\tconst Name = (name.substr(0, 1).toUpperCase() + name.substr(1));\n\n\t\t\tfetcherName = ('fetch' + Name);\n\t\t}\n\n\t\treturn fetcherName;\n\t}",
"function annotationFilename() {\n let url = location.pathname;\n let basename = url.split(\"\\\\\").pop().split(\"/\").pop().split(\".\")[0];\n\n // decker filenames vs. Mario filenames\n let filename;\n if (basename.endsWith(\"-deck\"))\n filename = basename.substring(0, basename.length - 5) + \"-annot.json\";\n else filename = basename + \".json\";\n\n return filename;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get "/tag_types.json" do presenter = ResultSetPresenter.new( FakePaginatedResultSet.new(known_tag_types), url_helper, TagTypePresenter, description: "All tag types" ) presenter.present.to_json end | function tag_types_json_formatter(req, res, db, url_helper) {
tag_types.with_counts(db).
then(tts => tts.map(tt => format(tt, url_helper))).
then(tts => res.json(result_set(tts, "All tag types"))).
catch(err => {
console.log(err);
error_503(res);
});
} // tag_types_json_formatter | [
"async index({ request, response, view }) {\n let tags = await Tag.query().select(['tag', 'id'])\n return tags\n }",
"async index() {\n return Type.all();\n }",
"getAll(req, res, next) {\n\n var\n request = new Request(req),\n response = new Response(request, this.expandsURLMap),\n criteria = this._buildCriteria(request);\n\n this.Model.paginate(criteria, request.options, function(err, paginatedResults, pageCount, itemCount) {\n /* istanbul ignore next */\n if (err) { return next(err); }\n\n response\n .setPaginationParams(pageCount, itemCount)\n .formatOutput(paginatedResults, function(err, output) {\n /* istanbul ignore next */\n if (err) { return next(err); }\n\n res.json(output);\n });\n\n });\n }",
"function getTagsFromPage(callback){\n\t\t\t\t\t\n\t\t\t\t\tconsole.log(request.greeting);\n\t\t\t\t\tvar tags = $(request.greeting);\n\t\t\t\t\tconsole.log(tags);\n\t\t\t\t\tvar tagLength = tags.length;\n\t\t\t\t\tconsole.log(tagLength);\n\n\t\t\t\t\tfor (var i = 0; i < tags.length; i++){\n\t\t\t\t\t\tvar tagObj = $(tags[i]);\n\t\t\t\t\t\ttagList.push(tagObj.html());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcallback();\n\t\t\t}",
"async function getType(url) {\n const response = await axios.get(url);\n const data = await response;\n const namesByTypeArr = [];\n for (let pokemon of data.data.pokemon) {\n namesByTypeArr.push(pokemon.pokemon.name);\n }\n buildNameList(namesByTypeArr);\n}",
"static async apiGetPostits(req, res, next) {\n try {\n const postits = await PostitsDAO.getPostits();\n res.json(postits);\n } catch (e) {\n console.log(`api, ${e}`);\n }\n }",
"getAllInterests() {\n return fetch(\"http://localhost:8088/interests\")\n .then(response => response.json())\n }",
"function getLanguageTypes() {\n personLanguageProficiencyLogic.getLanguageTypes().then(function (response) {\n $scope.languageList = response;\n }, function (err) {\n appLogger.log(err);\n appLogger.error('ERR', err);\n\n });\n\n }",
"async QueryAssetsWithPagination(ctx, queryString, pageSize, bookmark) {\n\n const {iterator, metadata} = await ctx.stub.getQueryResultWithPagination(queryString, pageSize, bookmark);\n const results = await this.GetAllResults(iterator, false);\n\n results.ResponseMetadata = {\n RecordsCount: metadata.fetched_records_count,\n Bookmark: metadata.bookmark,\n };\n\n return JSON.stringify(results);\n }",
"function getDogs() {\n fetch(dogsURL)\n .then(resp => resp.json())\n .then(renderDogs)\n}",
"function getQuestionsByTag(req, res) {\n\n console.log(\"Inside question controllers -> getQuestionsByTag()\");\n // console.log(\"req.params.tag: \" + req.params.tag);\n let tagName = req.params.tag;\n\n // db.getCollection('questions').find({'userTags':'REST'},{'_id':1})\n\n Question.find(\n { userTags: tagName },\n // { _id: 1 }\n )\n .then(dbQuestionData => {\n console.log(dbQuestionData);\n res.status(200).json(dbQuestionData)\n })\n .catch(err => {\n console.log(err);\n res.status(500).json(err);\n });\n\n}",
"function getCompanySpecies() {\r\n return get('/companyspecies/getall').then(function (res) {\r\n return res.data;\r\n }).catch(function (err) {\r\n return err.response.data;\r\n });\r\n}",
"findFormats(req, res) {\n\n let formats = Post.formats().map(format => {\n return {\n name: format,\n title: req.lang(\"post.formats.\" + format)\n }\n });\n\n return res.ok(formats);\n }",
"function loadHoseTypes() {\n $.get(\"/api/general/hoseTypes\"\n ).done(function (data) {\n var hoseType = $(\"#hoseType\");\n $.each(data.hoseTypes, function (index, element) {\n hoseTypes[element.id] = element;\n hoseType.append($(\"<option/>\", {text: element.name, value: element.id}))\n });\n loadHoseEvents();\n });\n}",
"function renderAvailableStudies() {\n\t// some clean up\n\t$('#analysisSpecifications').css('display', 'none');\n\t$('#clearResultsDiv').hide();\n\t\n\t// send the request\n\tvar url = HOME + '/query?action=getStudies';\n\tscanner.GET(url, true, postRenderAvailableStudies, null, null, 0);\n}",
"findAllByType(req, res){\n Event.getAllByType(req.params.typeId, req.params.userId, (err, data) => {\n if (err) {\n if (err.kind === \"not_found\") {\n res.status(404).send({\n message: `Not found event with TypeId ${req.params.typeId}.`\n });\n } else {\n res.status(500).send({\n message:\n err.message || \"Some error occurred while retrieving events by type.\"\n });\n }\n }else {\n res.send(data);\n }\n });\n }",
"function GetDocumentTypes()\n{\n\t$.ajax({\n\t\turl: action_url + 'GetDocumentTypes/' + UserId,\n\t\ttype: \"POST\",\n\t\tsuccess: function(Result)\n\t\t{\n\t\t\t$.each(Result.DocumentTypes, function(index, value)\n\t\t\t{\n\t\t\t\talert(value.id + \", \" + value.type);\n\t\t\t});\n\t\t}\n\t});\n}",
"function loadTagsIntoSelect() {\n dropdown.length = 0;\n \n let defaultOption = document.createElement('option');\n defaultOption.text = 'Add Tags';\n \n dropdown.add(defaultOption);\n dropdown.selectedIndex = 0;\n \n fetch(`${BASEURL}/tags`) \n .then( \n function(response) { \n if (response.status !== 200) { \n console.warn('Looks like there was a problem. Status Code: ' + \n response.status); \n return; \n }\n response.json().then(function(data) { \n let option;\n \n for (let i = 0; i < data.length; i++) {\n option = document.createElement('option');\n option.text = data[i].name;\n option.value = data[i].id;\n option.id = data[i].name\n \n dropdown.add(option);\n } \n }); \n } \n ) \n .catch(function(err) { \n console.error('Fetch Error -', err); \n });\n }",
"getPagesAsArray(URL) {\n const fullURL = `${BASE_REST_URL}${URL}${URL.contains('?') ? '' : '?'}`;\n let allElements = [];\n return fetch(fullURL, this.eloquaOptions)\n .then(res => res.json())\n .then(({ total, pageSize, elements }) => {\n allElements = elements;\n const numPagesToGet = parseInt(total, 10) / parseInt(pageSize, 10);\n if (numPagesToGet > 1) {\n const pagesArray = [];\n for (let i = 1; i < numPagesToGet; i++) {\n pagesArray.push(\n fetch(`${fullURL}&page=${i + 1}`, this.eloquaOptions)\n .then(res => res.json())\n .then(({ elements }) => allElements = allElements.concat(elements))\n );\n }\n return Promise.all(pagesArray).then(() => allElements);\n } else {\n return allElements;\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If 'obj' does not have the property 'attr', initialize 'attr' with 'initval'. | function touch(obj, attr, initval) {
if (!(attr in obj))
obj[attr] = initval;
return obj[attr];
} | [
"defaultAttributes(attributeObj) {\r\n Object.keys(attributeObj).forEach(name => {\r\n let defaultVal = attributeObj[name];\r\n let userVal = this.getAttribute(name);\r\n\r\n if (!userVal) {\r\n this.setAttribute(name, defaultVal);\r\n }\r\n });\r\n }",
"function setProperty (el, propObj) {\n\n\t\t\tif (el && propObj) {\n\n\t\t\t\t_.forOwn(propObj, function (value, key) {\n\n\t\t\t\t\tkey = _.escape(key);\n\n\t\t\t\t\tif (key in el) {\n\t\t\t\t\t\tel[key] = value;\n\t\t\t\t\t} else { \n\t\t\t\t\t\tel.setAttribute(key, value);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}",
"function populate_defaults(obj) {\n\t\tif(!(obj && obj._meta && obj._meta.defaults)) {\n\t\t\treturn;\n\t\t}\n\t\tvar defs = obj._meta.defaults;\n\t\t// FIXME: Unnecessary jquery dependency -- foreach could be implemented depency-free\n\t\t$.each(defs, function(key, value) {\n\t\t\tif(!obj[key]) {\n\t\t\t\tobj[key] = value;\n\t\t\t}\n\t\t});\n\t}",
"function constructor(initialVal, initialCompositor) {\n\t\tvar that = this;\n\n\t\t//Obj to be returned\n\t\tfunction KTAttribute() {\n\n\t\t}\n\n\t\t//Helper functions\n\t\t/**\n\t\t * (Re)compute the value of this object based on any attached constraint functions\n\t\t * and leave the up to date value in _value\n\t\t */\n\t\tfunction computeValue(attr) {\n\t\t\tattr.rawVal = attr._compositor.calculateValue(attr._constraintArray, attr);\n\t\t}\n\n\t\tfunction initializeValue(attr, initialVal) {\n\t\t\tattr.rawVal = initialVal;\n\t\t}\n\n\t\tfunction clearUsedBySet(attr) {\n\t\t\tattr._usedBySet.length = 0;\n\t\t}\n\n\t\t/**\n\t\t * Adds objectUsingValue to the list of attributes using that value\n\t\t */\n\t\tfunction addUsedBy(attr, objectUsingValue) {\n\t\t\tif (objectUsingValue !== undefined && objectUsingValue !== null) {\n\t\t\t\tattr._usedBySet.push(objectUsingValue);\n\t\t\t}\n\t\t}\n\n\t\tfunction clearFlag(attr, mask) {\n\t\t\tattr._flags &= ~mask;\n\t\t}\n\n\t\tfunction setFlag(attr, mask) {\n\t\t\tattr._flags |= mask;\n\t\t}\n\n\t\tfunction flagSet(attr, mask) {\n\t\t\treturn (attr._flags & mask) != 0;\n\t\t}\n\n\t\t//Internal Constants\n\t\tvar MARKED_OOD\t\t= 1;\n\t\tvar HAS_ACTION \t\t= 2;\n\t\tvar INITIAL_FLAGS\t= MARKED_OOD;\n\t\tKTAttribute.MARKED_OOD \t\t= MARKED_OOD;\n\t\tKTAttribute.HAS_ACTION \t\t= HAS_ACTION\n\t\tKTAttribute.INITIAL_FLAGS\t= MARKED_OOD;\n\n\t\t//Internal variables\n\t\t/** Value of this object */\n\t\tKTAttribute._value = null;\n\n\t\t/** \n\t\t * Collection of bits used as binary flags. Used to describe state of\n\t\t * the attribute. Constants provided, giving symbolic name for bit \n\t\t * positions\n\t\t */\n\t\t KTAttribute._flags = KTAttribute.INITIAL_FLAGS;\n\n\t\t /**\n\t\t * The set of attributes which currently use this attribute to compute their values\n\t\t * KTAttribute objects are recorded in this collection when they are passed as params\n\t\t * to useVal()\n\t\t *\n\t\t * This collection is maintained dynamically and is only valid when the value is\n\t\t * up to date (isOOD() = false). When the value is out of date, this set is not \n\t\t * maintained, since out of date traversals cannot pass this value to notify dependants\n\t\t *\n\t\t * Specifically, this set is cleared when the value is marked OOD, and subsequently recreated\n\t\t * based on requests for the value. This allows the set to reflect the actual dynamic\n\t\t * dependencies that are currently in place\n\t\t */\n\t\tKTAttribute._usedBySet = [];\n\n\t\t/**\n\t\t * Array of constraints\n\t\t */\n\t\tKTAttribute._constraintArray = [];\n\t\t\n\t\t/**\n\t\t * Parent object which owns this attribute\n\t\t */\n\t\tKTAttribute._parent = null;\n\n\t\t/**\n\t\t * The compositor object for this attribute\n\t\t */\n\t\tKTAttribute._compositor = null;\n\n\n\t\t/** Value of this attribute */\n\t\tObject.defineProperty(KTAttribute, \"val\", {\n\t\t\tget: function() {\n\t\t\t\treturn KTAttribute.useVal(KTAttribute, null);\n\t\t\t},\n\t\t\tset: function(newVal) {\n\t\t\t\t//Mark as up to date, so that traversal starts here\n\t\t\t\tclearFlag(KTAttribute, MARKED_OOD);\n\n\t\t\t\t//Start OOD traversal\n\t\t\t\tKTAttribute.markOOD(KTAttribute);\n\n\t\t\t\tKTAttribute.rawVal = newVal;\n\n\t\t\t\t//Used to break cycles\n\t\t\t\tclearFlag(KTAttribute, MARKED_OOD);\n\t\t\t}\n\t\t});\n\n\t\t/**\n\t\t * Computes then modifies the rawValue, then adds usingObj to the list\n\t\t * of objects using this attribute\n\t\t */\n\n\t\tObject.defineProperty(KTAttribute, \"rawVal\", {\n\t\t\tget: function() {\n\t\t\t\treturn KTAttribute._value;\n\t\t\t},\n\t\t\tset: function(newVal) {\n\t\t\t\tKTAttribute._value = newVal;\n\t\t\t}\n\t\t});\n\n\t\tObject.defineProperty(KTAttribute, 'compositor', {\n\t\t\tget: function() {\n\t\t\t\treturn KTAttribute._compositor;\n\t\t\t},\n\t\t\tset: function(val) {\n\t\t\t\tKTAttribute._compositor = val;\n\t\t\t\tKTAttribute.markOOD(KTAttribute);\n\t\t\t}\n\t\t});\n\n\t\tObject.defineProperty(KTAttribute, 'parent', {\n\t\t\tget: function() {\n\t\t\t\treturn KTAttribute._parent;\n\t\t\t},\n\t\t\tset: function(val) {\n\t\t\t\tKTAttribute._parent = val;\n\t\t\t}\n\t\t});\n\n\t\tObject.defineProperty(KTAttribute, 'numConstraints', {\n\t\t\tget: function() {\n\t\t\t\treturn KTAttribute._constraintArray.length;\n\t\t\t}\n\t\t});\n\n\t\tObject.defineProperty(KTAttribute, 'flags', {\n\t\t\tget: function() {\n\t\t\t\treturn KTAttribute._flags;\n\t\t\t}\n\t\t});\n\n\t\t//Public methods\n\t\tKTAttribute.isOOD = function() {\n\t\t\treturn flagSet(KTAttribute, MARKED_OOD);\n\t\t};\n\n\t\t/**\n\t\t * Mark dependents out of date if they are not already marked as such\n\t\t */\n\t\tKTAttribute.markOOD = function(fromObj) {\n\t\t\t//Only do stuff if we are not already marked as OOD (prevents cycles)\n\t\t\tif (!flagSet(KTAttribute, MARKED_OOD)) {\n\t\t\t\t//Mark us as OOD, do this first to prevent cycles\n\t\t\t\tsetFlag(KTAttribute, MARKED_OOD);\n\n\t\t\t\t//Loop through all our dependents and mark them as OOD\n\t\t\t\tfor (var i in KTAttribute._usedBySet) {\n\t\t\t\t\tvar dep = KTAttribute._usedBySet[i];\n\t\t\t\t\tdep.markOOD(KTAttribute);\n\t\t\t\t}\n\n\t\t\t\tclearUsedBySet(KTAttribute);\n\t\t\t}\n\t\t};\n\n\t\t/**\n\t\t * Adds a constraint of this attribute\n\t\t */\n\t\tKTAttribute.addConstraint = function(newConstraint) {\n\t\t\tKTAttribute._constraintArray.push(new ConstraintContainer(newConstraint));\n\t\t\tconsole.log('cosntraint added');\n\t\t};\n\n\t\t/**\n\t\t * Mark this attribute as OOD\n\t\t */\n\t\tKTAttribute.modVal = function() {\n\t\t\tvar result = KTAttribute.val;\n\t\t\tKTAttribute.markOOD(KTAttribute);\n\t\t\treturn result;\n\t\t};\n\n\t\t/**\n\t\t * Computes and then modifies the raw value, then adds usingObj to the list\n\t\t * of objects using this attribute.\n\t\t */\n\t\tKTAttribute.useVal = function(usingObj) {\n\t\t\tif (flagSet(KTAttribute, MARKED_OOD)) {\n\t\t\t\t//Unmark OOD first so we can break cyclic dependencies\n\t\t\t\tclearFlag(KTAttribute, MARKED_OOD);\n\n\t\t\t\tcomputeValue(KTAttribute);\n\t\t\t}\n\n\t\t\taddUsedBy(KTAttribute, usingObj);\n\n\t\t\treturn KTAttribute._value;\n\t\t};\n\n\t\t//==== Initialization code =====\n\t\tinitializeValue(KTAttribute, initialVal);\n\n\t\tif (!initialCompositor) {\n\t\t\tKTAttribute._compositor = new FirstItemCompositor();\n\t\t}\n\n\t\treturn KTAttribute;\n\t}",
"ensureProperty(obj, prop, value) {\n if (!(prop in obj)) {\n obj[prop] = value;\n }\n }",
"attrib(attr, val) {\n let attrType = _Util_main_js__WEBPACK_IMPORTED_MODULE_1__.default.getType(attr).toUpperCase();\n let valType = _Util_main_js__WEBPACK_IMPORTED_MODULE_1__.default.getType(val).toUpperCase();\n if (attrType === \"STRING\") {\n if (attrType !== \"UNDEFINED\") {\n this._elem.setAttribute(attr, val);\n return this;\n }\n return this._elem.getAttribute(attr);\n }\n throw new yngwie__WEBPACK_IMPORTED_MODULE_0__.Error(\"Name of attribute must be of type STRING\", attrType);\n }",
"attribs(attribs) {\n if (attribs === undefined) {\n return this._attribs;\n } else {\n if (typeof(attribs) === \"object\") {\n this._attribs = attribs;\n return this;\n }\n throw new _Error_main_js__WEBPACK_IMPORTED_MODULE_2__.default(\"YngwieElement attributes can only be set with OBJECT\", attribs);\n }\n }",
"function setValueIfNotExists(obj, key, val) {\n if (obj === undefined)\n return;\n if (!(key in obj))\n obj[key] = val;\n}",
"static createAttrDataObj(el){\n var res = {};\n DATA_MAP.forEach(function(value, key, map) {\n if(el.hasAttribute(key)){\n \n if(key == \"value\"){\n res[value] = el.value; \n } else if (key == \"data-cell_label\"){\n var refNames = value.split('-');\n var refVals = el.getAttribute(key).split('-');\n res[\"cell.\"+ refNames[0]] = refVals[0];\n res[\"cell.\"+ refNames[1]] = refVals[1];\n } else {\n res[value] = el.getAttribute(key); \n }\n \n }\n });\n return res;\n }",
"function updateShadowAttribute($element, prop, value) {\n prop = 'data-ui-' + _.caseDash(prop)\n if ( value == null ) {\n $element.removeAttr(prop)\n }\n else {\n $element.attr(prop, typeof value == 'object' ?\n JSON.stringify(value) : value\n )\n }\n}",
"function setattr( obj, name, value )\n { obj[name] = value; }",
"function objOrCreate(obj, prop) {\n\tif (!obj.hasOwnProperty(prop)) {\n\t\tobj[prop] = {};\n\t}\n\treturn obj[prop];\n}",
"function setDefaultAttrs(attrs) {\n defaultAttrs = attrs;\n}",
"_setAttributes(elem, dict) {\n for (const [key, value] of Object.entries(dict)) {\n console.log(key, value);\n elem.setAttribute(key, value);\n }\n }",
"function setSrc(element,attribute){element.setAttribute(attribute,element.getAttribute('data-'+attribute));element.removeAttribute('data-'+attribute);}",
"function setBasicAttribs(data, elem) {\n //set token\n elem.find(\".item-token\").text(data.token).attr(\"href\", \"/resolution/editor/\" + data.token);\n\n //id and year only if present in data\n if (data.idYear && data.resolutionId) {\n elem.find(\".item-year\").text(data.idYear);\n elem.find(\".item-id\").text(data.resolutionId);\n }\n\n //set forum and main sponsor\n elem.find(\".item-forum\").text(data.address.forum);\n elem.find(\".item-sponsor\").text(data.address.sponsor.main);\n\n //set age, get delta time in seconds and convert to time text\n elem.find(\".item-age\").text(getTimeText((Date.now() - data.waitTime) / 1000));\n}",
"function addAttributes(node, attrs) {\n for (var name in attrs) {\n var mode = attrModeTable[name];\n if (mode === IS_PROPERTY || mode === IS_EVENT) {\n node[name] = attrs[name];\n }\n else if (mode === IS_ATTRIBUTE) {\n node.setAttribute(name.toLowerCase(), attrs[name]);\n }\n else if (dataRegex.test(name)) {\n node.setAttribute(name, attrs[name]);\n }\n }\n var inlineStyles = attrs.style;\n if (!inlineStyles) {\n return;\n }\n var style = node.style;\n for (var name in inlineStyles) {\n style[name] = inlineStyles[name];\n }\n }",
"function nullobj(obj)\r\n{\r\n\treturn obj || { };\r\n}",
"set (...args) {\n let arity = args.length;\n let mutators = this.mutators();\n let defaults = [v=>v];\n\n let assign = (value, attr) => {\n let [set] = mutators[attr] || defaults;\n this.attrs[attr] = set(value);\n };\n\n if (arity < 1) {\n throw new Error('expected at least one argument');\n }\n if (arity > 2) {\n throw new Error('expected no more than two arguments');\n }\n\n if (arity === 1) {\n each(args[0], assign);\n return;\n }\n\n let [attr, value] = args;\n assign(value, attr);\n }",
"function attrFunction() {\n\t var x = value.apply(this, arguments);\n\t if (x == null) this.removeAttribute(name);\n\t else this.setAttribute(name, x);\n\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the maximum height of the textarea as determined by maxRows. | _setMaxHeight() {
const maxHeight = this.maxRows && this._cachedLineHeight ?
`${this.maxRows * this._cachedLineHeight}px` : null;
if (maxHeight) {
this._textareaElement.style.maxHeight = maxHeight;
}
} | [
"set maxLines(value) {}",
"_updateHeight() {\n this._mirroredTextareaRef.el.value = this.composer.textInputContent;\n this._textareaRef.el.style.height = (this._mirroredTextareaRef.el.scrollHeight) + \"px\";\n }",
"function scaleTextArea() {\n let tx = document.getElementsByTagName('textarea');\n let width = tx[0].style.width;\n let height = 0;\n let i;\n\n //keeps i at starting value for each row of 3\n function setValue() {\n i = (Math.ceil(tx.length/3));\n i += (i-1)*2-1;\n };\n\n //set max height\n setValue();\n for (i; i < tx.length; i++) {\n if (tx[i].scrollHeight > height) {\n height = tx[i].scrollHeight;\n };\n };\n\n //set textarea styling\n setValue();\n for (i; i < tx.length; i++) {\n tx[i].style = `height: ${height}px; overflow-y: hidden; width: ${width};`\n tx[i].addEventListener('input', OnInput, false);\n };\n function OnInput() {\n this.style = 'height: auto; width: auto';\n this.style = `height: ${height}px; overflow-y: hidden; width: ${width};`\n };\n}",
"setDimensions() {\n this.textbox.style.width = '';\n const scrollWidth = this.textbox.scrollWidth;\n const offsetWidth = this.textbox.offsetWidth;\n const width = (scrollWidth === offsetWidth ? offsetWidth - 1 : scrollWidth + 8);\n this.textbox.style.width = `${width}px`;\n\n /* Set the height of the absolute-positioned textarea to its background content's offsetHeight. Since the background\n content autoexpands, this allows the elements to be scrolled simultaneously using the parent element's scrollbars.\n Setting it to textbox.scrollHeight instead of bg.offsetHeight would also work, but that would require us to first\n blank style.height. It would also prevent us from improving seemless scrolling by adding trailing characters to the\n background content (which is done outside this method) before testing its height. Comparing bg.offsetHeight to the\n container's offsetHeight (minus 2 for borders) is done for the sake of IE6, since CSS min-height doesn't work\n there. */\n const height = Math.max(this.bg.offsetHeight, this.field.offsetHeight - 2);\n this.textbox.style.height = `${height}px`;\n }",
"function textareasize(elementId, height, width, formId) {\n textarea = $jq(getElementById(elementId))[0];\n form1 = textarea.form;\n if (textarea && height !== 0 && textarea.rows + height > 5) {\n textarea.rows += height;\n if (form1.rows) {\n form1.rows.value = textarea.rows;\n\t}\n }\n if (textarea && width !== 0 && textarea.cols + width > 10) {\n textarea.cols += width;\n if (form1.cols) {\n form1.cols.value = textarea.cols;\n\t}\n }\n}",
"get maxLines() {}",
"updateMaxHeightState() {\n this.setState(() => ({\n maxHeight: this._refMainContainer.clientHeight - this.state.mainContainerRestHeight,\n }));\n }",
"set requestedHeight(value) {}",
"function autoSizeTextArea() {\n\t$('.auto-size').autosize();\n}",
"function setMenuMaxHeight() {\n \tvar outerHeight = $(pDiv+jq(config.CSS.IDs.divBottomWrapper)).outerHeight(true);\n \tvar docHeight = $(pDiv+ jq(\"divMainJsmol\")).height();//TODO fix\n \t$(pDiv+ jq(config.CSS.IDs.divMenu)).css('max-height',docHeight - outerHeight );\n\t}",
"function resizeTextArea() {\n\n \t// textarea element\n \tvar textarea = $('#task-body'),\n \ttextarea2 = $('#taskBox-body'),\n \t// hidden element\n \tclonedTextarea = $('.hiddendiv'), \n\n \t// init content as null\n \tcontent = null;\n\n \t// evet to get the input and height\n \ttextarea.on('keyup focus keypress cut paste change keydown', function() {\n \t\t// set the new content value\n \t\tcontent = textarea.val();\n \t\t// set the textarea value to the hidden element\n \t\tclonedTextarea.html(content);\n \t\t// set the new textarea height with the height from the hidden element\n \t\ttextarea.css('height', clonedTextarea.height() + 50 + 'px'); \n\n \t});\n\n \ttextarea2.on('keyup focus keypress cut paste change keydown', function() {\n \t\t// set the new content value\n \t\tcontent = textarea2.val();\n \t\t// set the textarea value to the hidden element\n \t\tclonedTextarea.html(content);\n \t\t// set the new textarea height with the height from the hidden element\n \t\ttextarea2.css('height', clonedTextarea.height() + 50 + 'px');\n \t});\n }",
"function getHighestTextArea() {\r\n var textAreaHeight = 0;\r\n sAccTextArea.each(function () {\r\n if ($(this).height() > textAreaHeight) {\r\n textAreaHeight = $(this).outerHeight();\r\n }\r\n });\r\n return textAreaHeight;\r\n }",
"function SetRowHeight() {\n var grid = this.GetGrid();\n var rowHeight = GetRowHeight.call(this);\n var ids = grid.getDataIDs();\n\n for (var i = 0, len = ids.length; i < len; i++) {\n grid.setRowData(ids[i], false, { height: rowHeight });\n }\n }",
"function getHeight() {\n return maxy + 1;\n }",
"updateTextAreaSize(text) {\n var textSettings = this.currentText.getTextSettings();\n\n // Setting the font and size of the text\n this.textAreaElement.css(\"font-size\", textSettings.pixels + \"px\");\n this.textAreaElement.css(\"font-family\", textSettings.fontType);\n\n //TODO: resize text area.\n }",
"function updateTextBoxHeight(textBox) {\n const style = window.getComputedStyle(textBox)\n\n // The height calculated by auto is exclude the value of the padding top.\n // Rest small space.\n textBox.style.height = 'auto'\n textBox.style.height = `${\n textBox.offsetHeight - pixelToInt(style.paddingTop) + 20\n }px`\n } // CONCATENATED MODULE: ./src/lib/Editor/AnnotationData/createTextBox/TextBox/index.js",
"get inputMaxHeight(){\n var {footer, header, maxHeight} = this.props;\n var inputMaxHeight = maxHeight;\n if(footer) inputMaxHeight-=1;\n if(header) inputMaxHeight-=1;\n return inputMaxHeight;\n }",
"static getMaxHeight() { \n var result = Math.max(MainUtil.findAllRooms().map(room => (room.memory.console && room.memory.console.height)));\n return result || 10;\n }",
"function textareaAutoResizer() {\n\n\tvar ta = document.querySelectorAll('textarea.input-title');\n\tautosize(ta);\n}",
"updateEditorHeight() {\n $('#editor').height($('#editor-wrapper').height() - $('#file-tabs').height() - 3);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the given date by first normalizing it and then looking for patterns cMonth (int) : If no month is found, use provided value in stead cDay (str 'start' or 'end') : if no day is found, should it be 1 or end of month | function parse(date, cMonth, cDay) {
// Empty/undefined date is invalid
if (typeof date === "undefined" || !date.length > 1) {
return false;
}
var year = null, month = null, day = null;
date = date.toString();
var parts = normalize(date).split(" ");
// Find the year
for (var i=0; i < parts.length; i++) {
if (isYear(parts[i]) || isShortYear(parts[i])) {
year = parts[i];
if (isShortYear(year)) {
// 2015 + '12 ==> 2012
// 2122 + '92 ==> 2192
var tmp = new Date().getFullYear().toString().slice(0, 2)
year = tmp + parts[i].slice(1)
}
parts.splice(i, 1);
break;
}
}
// Find month by written name
var foundMonth = false;
for (var i=0; i < parts.length; i++) {
if (isNotNumeric(parts[i])) {
month = lookupMonth(parts[i]);
if (month >= 0) {
foundMonth = true;
parts.splice(i, 1);
break;
}
}
}
// Filter all that cannot be day/month nr.
parts = parts.filter(function(p) {
return isInt(p) && +p <= 31;
});
// If the month is found, just pick the first number as the day
if (foundMonth) {
if (parts[0]) {
day = +parts[0];
}
else if (cDay === "end") {
day = endOfMonth(month);
}
else {
day = 1;
}
}
else if (parts.length >= 2) {
month = -1;
// TODO
// Allow option to prefer MM-DD-YYYY over DD-MM-YYYY
// - For now its DD-MM-YYYY
if (isAmbiguousDate(parts[0], parts[1]) || +parts[0] > 12) {
day = parts[0];
month = parts[1];
}
else {
day = parts[1];
month = parts[0];
}
}
// Assumes only a month number is provided
else if (parts.length === 1 && +parts[0] <= 12) {
month = +parts[0];
}
// Date validation
if ((year && year > 1800) && ((!day && !month) || acceptableDayMonthCombo(day, month))) {
// Set default day if nothing found
if (!day) {
day = (cDay === "end") ? endOfMonth(month||cMonth) : 1;
}
// Month is zero based index
var current = new Date(year, (month||cMonth)-1, day);
return current;
}
return false;
} | [
"parseDate(formattedDate) {\n const [monthDayStr, yearStr] = formattedDate.split(', ');\n const [monthStr, dayStr] = monthDayStr.split(' ');\n return {\n month: this.getMonthInt(monthStr),\n day: parseInt(dayStr),\n year: parseInt(yearStr)\n };\n }",
"function parseDate(str) {\n\t if (!str) {\n\t return;\n\t }\n\t\n\t /* RFC6265 S5.1.1:\n\t * 2. Process each date-token sequentially in the order the date-tokens\n\t * appear in the cookie-date\n\t */\n\t var tokens = str.split(DATE_DELIM);\n\t if (!tokens) {\n\t return;\n\t }\n\t\n\t var hour = null;\n\t var minute = null;\n\t var second = null;\n\t var dayOfMonth = null;\n\t var month = null;\n\t var year = null;\n\t\n\t for (var i=0; i<tokens.length; i++) {\n\t var token = tokens[i].trim();\n\t if (!token.length) {\n\t continue;\n\t }\n\t\n\t var result;\n\t\n\t /* 2.1. If the found-time flag is not set and the token matches the time\n\t * production, set the found-time flag and set the hour- value,\n\t * minute-value, and second-value to the numbers denoted by the digits in\n\t * the date-token, respectively. Skip the remaining sub-steps and continue\n\t * to the next date-token.\n\t */\n\t if (second === null) {\n\t result = parseTime(token);\n\t if (result) {\n\t hour = result[0];\n\t minute = result[1];\n\t second = result[2];\n\t continue;\n\t }\n\t }\n\t\n\t /* 2.2. If the found-day-of-month flag is not set and the date-token matches\n\t * the day-of-month production, set the found-day-of- month flag and set\n\t * the day-of-month-value to the number denoted by the date-token. Skip\n\t * the remaining sub-steps and continue to the next date-token.\n\t */\n\t if (dayOfMonth === null) {\n\t // \"day-of-month = 1*2DIGIT ( non-digit *OCTET )\"\n\t result = parseDigits(token, 1, 2, true);\n\t if (result !== null) {\n\t dayOfMonth = result;\n\t continue;\n\t }\n\t }\n\t\n\t /* 2.3. If the found-month flag is not set and the date-token matches the\n\t * month production, set the found-month flag and set the month-value to\n\t * the month denoted by the date-token. Skip the remaining sub-steps and\n\t * continue to the next date-token.\n\t */\n\t if (month === null) {\n\t result = parseMonth(token);\n\t if (result !== null) {\n\t month = result;\n\t continue;\n\t }\n\t }\n\t\n\t /* 2.4. If the found-year flag is not set and the date-token matches the\n\t * year production, set the found-year flag and set the year-value to the\n\t * number denoted by the date-token. Skip the remaining sub-steps and\n\t * continue to the next date-token.\n\t */\n\t if (year === null) {\n\t // \"year = 2*4DIGIT ( non-digit *OCTET )\"\n\t result = parseDigits(token, 2, 4, true);\n\t if (result !== null) {\n\t year = result;\n\t /* From S5.1.1:\n\t * 3. If the year-value is greater than or equal to 70 and less\n\t * than or equal to 99, increment the year-value by 1900.\n\t * 4. If the year-value is greater than or equal to 0 and less\n\t * than or equal to 69, increment the year-value by 2000.\n\t */\n\t if (year >= 70 && year <= 99) {\n\t year += 1900;\n\t } else if (year >= 0 && year <= 69) {\n\t year += 2000;\n\t }\n\t }\n\t }\n\t }\n\t\n\t /* RFC 6265 S5.1.1\n\t * \"5. Abort these steps and fail to parse the cookie-date if:\n\t * * at least one of the found-day-of-month, found-month, found-\n\t * year, or found-time flags is not set,\n\t * * the day-of-month-value is less than 1 or greater than 31,\n\t * * the year-value is less than 1601,\n\t * * the hour-value is greater than 23,\n\t * * the minute-value is greater than 59, or\n\t * * the second-value is greater than 59.\n\t * (Note that leap seconds cannot be represented in this syntax.)\"\n\t *\n\t * So, in order as above:\n\t */\n\t if (\n\t dayOfMonth === null || month === null || year === null || second === null ||\n\t dayOfMonth < 1 || dayOfMonth > 31 ||\n\t year < 1601 ||\n\t hour > 23 ||\n\t minute > 59 ||\n\t second > 59\n\t ) {\n\t return;\n\t }\n\t\n\t return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));\n\t}",
"function DateTimeDayMonth() { }",
"static fromPartialString(v) {\n let match = /^(\\d{4})\\/(\\d{1,2})\\/(\\d{1,2})$/.exec(v);\n if (match) {\n return new NepaliDate(match[1], match[2], match[3]);\n }\n match = /^(\\d{1,2})\\/(\\d{1,2})$/.exec(v);\n if (match) {\n const nd = NepaliDate.today();\n let y = nd.nepaliYear;\n const m = match[1];\n const d = match[2];\n if (m > nd.nepaliMonth || (m === nd.nepaliMonth && d > nd.nepaliDay)) {\n y -= 1;\n }\n return new NepaliDate(y, m, d);\n }\n }",
"function isValidYrMonth(dtStr, FromToCheck){\n\n re = new RegExp(\"/\",\"g\");\n var dtStr = dtStr.replace(re,\"\");\n\n if(!isInteger(dtStr)){\n return false;\n }\n if(dtStr == '000000' && FromToCheck == '1'){\n return false;\n }\n if(dtStr == '999999' && FromToCheck == '2'){\n return false;\n }\n var month;\n var year;\n if(dtStr.length != 6) {\n return false;\n }\n year = dtStr.substring (0, 4);\n month = dtStr.substring (4, 6);\n\n if(year.length != 4 ){\n return false;\n }\n if(month.length != 2 ){\n return false;\n }\n if(month < \"01\" || month > \"12\"){\n return false;\n }\n if(year < \"1000\" || year > \"9999\"){\n return false;\n }\n return true\n}",
"function parseDate(val) {\r\n var preferEuro = (arguments.length == 2) ? arguments[1] : false;\r\n generalFormats = new Array('y-M-d', 'MMM d, y', 'MMM d,y', 'y-MMM-d', 'd-MMM-y', 'MMM d', 'd MMM yyyy', 'dd MMM yyyy');\r\n monthFirst = new Array('M/d/y', 'M-d-y', 'M.d.y', 'MMM-d', 'M/d', 'M-d');\r\n dateFirst = new Array('d/M/y', 'd-M-y', 'd.M.y', 'd-MMM', 'd/M', 'd-M', 'd MM yy', 'd MMM yy', 'dd MM yy', 'd MM yyyy', 'dd M yy', 'dd M yyyy', 'dd MM yyyy');\r\n\r\n var checkList = new Array('generalFormats', !preferEuro ? 'dateFirst' : 'monthFirst', !preferEuro ? 'monthFirst' : 'dateFirst');\r\n var d = null;\r\n for (var i = 0; i < checkList.length; i++) {\r\n var l = window[checkList[i]];\r\n for (var j = 0; j < l.length; j++) {\r\n d = getDateFromFormat(val, l[j]);\r\n if (d != 0) { return new Date(d); }\r\n }\r\n }\r\n return null;\r\n}",
"function isDate(str) {\n\tvar resultStr = \"\";\n\tvar dateObject\n\tvar dateParts\n\tvar thisYear\n\tvar theDay\n\tvar inputYear\n\tvar theMonths\n\tvar theMonthsArray\n\t// Return immediately if an invalid value was passed in\n\tif (str+\"\" == \"undefined\" || str == null) return null;\n\t// Make sure the argument is a string\n\tstr += \"\";\n\tstr = Trim( str )\n\n\tdateObject = new Date() //get todays date\n\tFixDateObject(dateObject)\n\tthisYear = dateObject.getYear()\n\tthisYear = (thisYear < 1000 ? thisYear + 1900 : thisYear);\n\n\ttheMonths =\t\"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec\"\n\ttheMonthsArray = theMonths.split(\",\")\n\t// Get the index of any slash.\n\t// If there is a slash, assume mm/dd/yyyy format\n\tidx = str.indexOf(\"/\");\t\n\tif (idx >= 0) {\n\t\tdateParts = str.split(\"/\")\n\t\tdateParts[0] = Trim( dateParts[0])\n\t\tdateParts[1] = Trim( dateParts[1])\n\t\tdateParts[2] = Trim( dateParts[2])\n\t\tif (dateParts[0] < 1 || dateParts[0] > 12) return null\n\t\tif (dateParts[1] < 1 || dateParts[1] > 31) return null\n\t\tinputYear = parseInt(dateParts[2])\n\t\tif (isNaN(inputYear)) return null\n\t\tinputYear = (inputYear < 1000 ? inputYear + 1900 : inputYear);\n\t\tdateParts[2] = \"\" + inputYear\n\t\tif (dateParts[2] < 1890 || dateParts[2] > thisYear) return null\n\t } else { // assume Month Day, Year format\n\t\tdateParts = str.split(\" \")\n\t\tfor (i=0;i++;i<12) {\n\t\t\tif (theMonthsArray[i].toLowerCase()==dateParts[0].substring(0,3).toLowerCase()) {\n\t\t\t\tdateParts[0] = \"\" + i + 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (i == 12) return null\n\t\tidx = dateParts[1].indexOf(\",\");\t\n\t\tif (idx >= 0) {\n\t\t\t//theDay = \"\" + dateParts[1] //make string\n\t\t\tdateParts[1] = dateParts[1].substring(0,idx)\n\t\t}\n\t\tif (dateParts[1] < 1 || dateParts[1] > 31) return null\n\t\tif (dateParts[2] < 1890 || dateParts[2] > thisYear) return null\n\t }\n\tresultStr = \"\" + theMonthsArray[dateParts[0] - 1] + \" \" + dateParts[1] + \", \" + dateParts[2]\n\treturn resultStr;\n}",
"function getValidMonth(){\r\n\treturn 3;\r\n}",
"function SimpleDateFormat(pattern) {\n this.pattern = pattern;\n this.regex = new RegExp(\"^\" + pattern.replace(\"yyyy\", \"\\\\d{4}\").replace(\"MM\", \"(0\\\\d|1[12])\").replace(\"dd\", \"([0-2]\\\\d|3[0-1])\")\n .replace(\"HH\", \"([0-1]\\\\d|2[0-3])\").replace(\"hh\", \"(0\\\\d|1[0-2])\").replace(\"mm\", \"[0-5]\\\\d\").replace(\"ss\", \"[0-5]\\\\d\") + \"$\");\n this.position = {\n year: pattern.indexOf(\"yyyy\"), month: pattern.indexOf(\"MM\"), day: pattern.indexOf(\"dd\"),\n hour: pattern.toLowerCase().indexOf(\"hh\"), minute: pattern.indexOf(\"mm\"), second: pattern.indexOf(\"ss\")\n };\n this.parse = function (source) {\n if (!this.regex.test(source))\n throw new Error(\"Unparseable date: \\\"\" + source + \"\\\"\");\n var time = {\n year: source.substr(this.position.year, 4),\n month: source.substr(this.position.month, 2),\n day: source.substr(this.position.day, 2)\n };\n if (this.position.hour != -1)\n time.hour = source.substr(this.position.hour, 2);\n if (this.position.minute != -1)\n time.minute = source.substr(this.position.minute, 2);\n if (this.position.second != -1)\n time.second = source.substr(this.position.second, 2);\n var day31 = \"01,03,05,07,08,10,12\";\n if (time.day == 31 && day31.indexOf(time.month) == -1)\n throw new Error(\"Unparseable date: \\\"\" + source + \"\\\"\");\n if (time.month == 2 && time.day == 29 && !(time.year % 4 == 0 && time.year % 100 != 0)\n && !(time.year % 100 == 0 && time.year % 400 == 0)) {\n throw new Error(\"Unparseable date: \\\"\" + source + \"\\\"\");\n }\n var date = new Date();\n date.setFullYear(time.year, time.month - 1, time.day);\n if (time.hour != undefined) date.setHours(time.hour);\n if (time.minute != undefined) date.setMinutes(time.minute);\n if (time.second != undefined) date.setSeconds(time.second);\n return date;\n };\n this.format = function (date) {\n function fmt(v, n) {\n for (var i = n - (v + \"\").length; i > 0; i--) {\n v = \"0\" + v;\n }\n return v;\n }\n var h24 = date.getHours();\n return this.pattern.replace(\"yyyy\", fmt(date.getFullYear(), 4)).replace(\"MM\", fmt(date.getMonth() + 1, 2))\n .replace(\"dd\", fmt(date.getDate(), 2)).replace(\"HH\", fmt(h24, 2)).replace(\"hh\", fmt((h24 - 1) % 12 + 1, 2))\n .replace(\"mm\", fmt(date.getMinutes(), 2)).replace(\"ss\", fmt(date.getSeconds(), 2));\n };\n}",
"static parseDate(dateString){\n return new Date(\n parseInt(dateString.split(\"/\")[2]),\n DateUtilities.getMonthNumber(dateString.split(\"/\")[1]),\n parseInt(dateString.split(\"/\")[0])\n )\n }",
"function parse_months() {\n var raw_months = month_date_textbox.getValue();\n var months_to_list = raw_months.split(\"-\");\n return months_to_list;\n}",
"function dateRangeFromString(s) {\n var now = new Date();\n var regex = '^(?:' + ['(([0-9]{4})(?:-([0-9]{1,2})(?:-([0-9]{1,2}))?)?)', // year-month-day\n '(([0-9]{1,2})-([0-9]{1,2}))', // month-day\n '(([0-9]{4})?(?:[ ]*([a-zA-Z]{3})[ ]*([0-9]{1,2})?)?)', // month name day? year?\n '([1-9]+)[ ]+(day[s]?|week[s]?|month[s]?)[ ]+ago'\n ].join('|') + ')[ ]*$';\n var res = s.match(regex);\n if (res == null) return null;\n\n var start = new Date(now);\n var delta = 0;\n \n if (res[1]) {\n var year = parseInt(res[2]);\n var month = res[3] ? parseInt(res[3]) : null;\n var day = res[4] ? parseInt(res[4]) : null\n\n if (month && ( monty < 1 || month > 12)) return null;\n if (month && day && ( day < 1 || day > 31)) return null;\n \n var d0 = start\n d0.setFullYear(year);\n d0.setMonth(0);\n d0.setDate(1);\n d0.setHours(0);\n d0.setMinutes(0);\n d0.setSeconds(0);\n \n if (month && day) {\n start\n d0.setMonth(month-1);\n d0.setDate(day);\n delta = 24*60*60;\n } else if (month) {\n d0.setMonth(now.getMonth());\n delta = 31*24*60*60;\n } else {\n delta = 365*24*60*60;\n }\n } else if (res[5]) {\n var month = parseInt(res[6]);\n var day = parseInt(res[7]);\n\n if (monty < 1 || month > 12) return null;\n if (day < 1 || day > 31) return null;\n\n var d0 = start;\n d0.setMonth(month-1);\n d0.setDate(day);\n if (month-1 > now.getMonth() || (month-1 == now.getMonth() && day-1 == now.getDate())) {\n d0.setFullYear(now.getFullYear()-1)\n } else {\n d0.setFullYear(now.getFullYear())\n }\n delta = 24*60*60;\n } else if (res[8]) {\n var monthname = res[10] ? res[10].toLowerCase() : null;\n var month = 0;\n var day = res[11] ? parseInt(res[11]) : null;\n var year = res[9] ? parseInt(res[9]) : (res[12] ? parseInt(res[12]) : null);\n \n if (monthname) {\n if (monthname == \"jan\" || monthname == 'january') month = 0;\n else if (monthname == \"feb\" || monthname == 'february') month = 1;\n else if (monthname == \"mar\" || monthname == 'march') month = 2;\n else if (monthname == \"apr\" || monthname == 'april') month = 3;\n else if (monthname == \"may\" || monthname == 'may') month = 4;\n else if (monthname == \"jun\" || monthname == 'june') month = 5;\n else if (monthname == \"jul\" || monthname == 'july') month = 6;\n else if (monthname == \"aug\" || monthname == 'august') month = 7;\n else if (monthname == \"sep\" || monthname == 'september') month = 8;\n else if (monthname == \"oct\" || monthname == 'october') month = 9;\n else if (monthname == \"nov\" || monthname == 'november') month = 10;\n else if (monthname == \"dec\" || monthname == 'december') month = 11;\n else\n return null;\n }\n\n\n if (year != null) {\n start.setFullYear(year);\n if (month != null) {\n start.setMonth(month);\n if (day != null) {\n start.setDate(day);\n delta = 24*60*60;\n } else {\n start.setDate(1);\n delta = 31*24*60*60;\n }\n } else {\n start.setMonth(0);\n delta = 365*24*60*60;\n }\n } else if (month != null) {\n if (now.getMonth() < month || (now.getMonth() == month && day != null && now.getDate() < day))\n start.setFullYear(now.getFullYear()-1);\n else\n start.setFullYear(now.getFullYear());\n start.setMonth(month);\n if (day != null) {\n start.setDate(day);\n delta = 24*60*60;\n } else {\n start.setDate(1);\n delta = 31*24*60*60;\n }\n } else {\n return null;\n }\n \n } else if (res[12]) {\n var diff = parseInt(res[12]);\n var kind = res[13].toLowerCase();\n\n if (kind == 'day' || kind == 'days') {\n delta = 24*60*60;\n start = new Date(now.getTime() - (diff*24*60*60 + delta/2)*1000);\n } else if (kind == 'week' || kind == 'weeks') {\n delta = 7*24*60*60;\n start = new Date(now.getTime() - (diff*delta + delta/2)*1000);\n } else { //if (kind == 'month' || kind == 'months') {\n delta = 31*24*60*60;\n start = new Date(now.getTime() - (diff*24*60*60*31 + delta/2)*1000);\n }\n } else\n return null;\n\n return [ start.getTime(), start.getTime()+delta*1000 ];\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 putMask_YearMonthDate(oElement)\n{\n var lstrValue = oElement.value;\n if(lstrValue == \"\" || !isInteger(lstrValue))\n return;\n\n re = new RegExp(\"/\",\"g\");\n lstrValue = lstrValue.replace(re,\"\");\n if (lstrValue.length == 6) {\n partOne = lstrValue.substring(0,4);\n partTwo = lstrValue.substring(4);\n oElement.value = partOne + \"/\" +partTwo;\n }\n}",
"function validateStandardDate(due){\n var mess = \"\";\n if (due == \"\") {\n return mess;\n }\n var patt = /^20[0-9]{2}\\/[01][0-9]\\/[0-3][0-9]$/;\n var tmp = patt.exec(due);\n if (tmp == \"\") {\n return \"Date must take form YYYY/MM/DD.\";\n }\n return tmp;\n\n var DDcap = new Array();\n DDcap[0] = 31;\n DDcap[1] = 28;\n DDcap[2] = 31;\n DDcap[3] = 30;\n DDcap[4] = 31;\n DDcap[5] = 30;\n DDcap[6] = 31;\n DDcap[7] = 31;\n DDcap[8] = 30;\n DDcap[9] = 31;\n DDcap[10] = 30;\n DDcap[11] = 31;\n var PYY = /^[0-9]{1,4}/;\n var YY = parseInt(PYY.exec(due), 10);\n var PTMM = /\\/[0-9]{1,2}\\//;\n var TMM = PTMM.exec(due);\n var PMM = /[0-9]{1,2}/;\n var MM = parseInt(PMM.exec(TMM), 10);\n var PDD = /[0-9]{1,2}$/;\n var DD = parseInt(PDD.exec(due), 10);\n var t = new Date();\n //var et = (t.getTime() - t.getMilliseconds())/1000 - 1293840000; // time since 0:00:00 on Jan 1, 2011\n var bau = true;\n if(YY < 2013){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(MM > 12 || MM < 1){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(DD > DDcap[MM-1] && !(DD==29 && MM==2 && YY % 4 == 0) || DD == 0){\n mess += \"The date you entered is invalid for the month selected\";\n }\n return mess;\n}",
"function calanderCtrl_update()\r\n{\r\n var mmms = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');\r\n\r\n var first_day_of_month = new Date(calanderCtrl_selectedYear, calanderCtrl_selectedMonth, 1).getDay();\r\n //alert(\"first_day_of_month:\" + first_day_of_month);\r\n\r\n //Get total days in selected month\r\n var days_in_month = new Date(calanderCtrl_selectedYear, calanderCtrl_selectedMonth + 1, 0).getDate();\r\n //alert(\"days_in_month:\" + days_in_month);\r\n\r\n var i;\r\n for (i = 0; i <= 41; i++)\r\n {\r\n\r\n if (i >= first_day_of_month && i < (days_in_month + first_day_of_month))\r\n {\r\n document.getElementById(\"calanderCtrl_date_id_\" + i).innerHTML = i - first_day_of_month + 1;\r\n\r\n if ((i % 7) === 0)\t//sunday?\r\n {\r\n document.getElementById(\"calanderCtrl_date_id_\" + i).className = \"calanderCtrl_valid_day_sunday\";\r\n }\r\n else\r\n {\r\n document.getElementById(\"calanderCtrl_date_id_\" + i).className = \"calanderCtrl_valid_day\";\r\n }\r\n }\r\n else\r\n {\r\n document.getElementById(\"calanderCtrl_date_id_\" + i).innerHTML = \"\";\r\n document.getElementById(\"calanderCtrl_date_id_\" + i).className = \"calanderCtrl_invalid_day\";\r\n }\r\n }\r\n\r\n var fmt_mmm = mmms[calanderCtrl_selectedMonth];\t\t//month change to english\r\n\r\n document.getElementById(\"calanderCtrl_date_month\").innerHTML = fmt_mmm + \", \" + calanderCtrl_selectedYear;\r\n}",
"function GetMonthFromRawDateFunc(date) {\n var date = new Date(date);\n return date.getMonth() + 1;\n }",
"function GetMonthStringFromRawDateFunc(date) {\n var date = new Date(date);\n return GetMonthString(date.getMonth());\n }",
"getMonthNum() {\n\t\treturn this.props.month.substr(5,6);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Activa la carrera cuando se presiona el boton "activar" | function activar() {
let nombreSede = this.dataset.nombre;
let sede = buscarSedePorNombre(nombreSede);
sede[6] = true;
swal({
title: "Activar sede",
text: "¿Está seguro que desea activar esta sede?",
buttons: ["Cancelar", "Aceptar"],
}).then((willDelete) => {
if (willDelete) {
actualizarSede(sede);
mostrarSedesDesactivadas();
}
});
} | [
"function activar(){\n //Se toman todos los items. Ahora para quitar la clase 'activo'\n let opcionesMenu = document.getElementsByClassName('sideBarItem'); \n\n //En este recorrido de todos los items buscamos el que este con clase 'activo'\n for (let i = 0; i < opcionesMenu.length; i++){\n if(opcionesMenu[i].classList.contains('activo')) //Con este if reconocemos el item activo\n opcionesMenu[i].classList.remove('activo'); //Removemos la clase 'activo'\n }\n\n //Aqui se asigna la nueva clase al item (menu) seleccionado\n this.classList.add('activo');\n }",
"sendActiveState_() {\n this.sendToChromeVox_(\n {type: 'activeState', active: this.engineID_.length > 0});\n }",
"activation(active = undefined) {\n if (active === undefined && this.module && typeof this.module.active == \"boolean\") {\n active = !this.module.active;\n }\n if (fs.existsSync(ToxenModule.moduleFolder + \"/\" + this.moduleName + \"/module.json\")) {\n let data = JSON.parse(fs.readFileSync(ToxenModule.moduleFolder + \"/\" + this.moduleName + \"/module.json\", \"utf8\"));\n data.active = active;\n fs.writeFileSync(ToxenModule.moduleFolder + \"/\" + this.moduleName + \"/module.json\", JSON.stringify(data, null, 2));\n }\n else {\n fs.writeFileSync(ToxenModule.moduleFolder + \"/\" + this.moduleName + \"/module.json\", JSON.stringify({\n \"main\": \"index.js\",\n \"active\": active\n }, null, 2));\n }\n }",
"function selectActiveForIndex(index){\n\tlet elm = document.getElementsByClassName('item-active')[index];\n\n\tif(elm){\n\t\t//Identificador del activo\n\t\tlet id_active = elm.getAttribute('data-active');\n\n\t\t//Se actualiza el activo\n\t\tport.postMessage({name:\"update_trading_params\", data:{current_active:id_active}});\n\n\t\tasset_selected = true;\n\t\tbtn_higher.disabled = false;\n\t\tbtn_higher_minimized.disabled = false;\n\t\tbtn_lower.disabled = false;\n\t\tbtn_lower_minimized.disabled = false;\n\n\t\tbtn_higher.classList.remove('disabled');\n\t\tbtn_higher_minimized.classList.remove('disabled');\n\t\tbtn_lower.classList.remove('disabled');\n\t\tbtn_lower_minimized.classList.remove('disabled');\n\n\t\t//Todos los activos de la pantalla\n\t\telm_actives = document.getElementsByClassName('item-active');\n\n\t\tfor(let i = 0; i < elm_actives.length; i++){\n\t\t\telm_actives[i].classList.remove('bg-warning');\n\t\t}\n\n\t\telm.classList.add('bg-warning');\n\n\t\trequestSyncDataTrading();\n\t}\n}",
"function fGuardarA(){\n if(fValidaTodo()==true){\n if(fNavega()==true){\n //FRMPanel.fSetTraStatus(\"UpdateComplete\");\n fDisabled(true);\n FRMListado.fSetDisabled(false);\n }\n }\n }",
"function cargarActividad(){\n\t\n\tmostrarActividad();\n\n\tcomienzo = getActual();\n}",
"function activateButtons(){\n clicked = [];\n $scope.clickMemoryButton = function(button){ // Everytime a button is clicked\n blink(button, 300); //the button blinks\n clicked.push(button.class); // and is pushed into the clicked list\n checkIfWon(clicked, gameList); //Check if the level has been won\n clickNumber+=1;\n };\n }",
"celebrate (state, status) {\n state.celebrating = status\n }",
"function activateAntenna(){\n //turn property active to true\n ship.antenna.active = true;\n}",
"function clickNormal(){\r\n\t\tdineroTotal+=1;\r\n\t\tdineroActual+=1;\r\n\t\tactivo=new Date().getTime()/1000;\r\n\t\tactualizarDinero();\r\n\t}",
"setInFrontier() {\n this.inFocus = false\n this.inFrontier = true\n }",
"changeGenerateStatus() {\n this.generateButton.disabled = canvasScript.robots.size < 2;\n }",
"function fGuardar(){\n if(fValidaTodo()==true){\n if(fNavega()==true){\n //FRMPanel.fSetTraStatus(\"UpdateComplete\");\n fDisabled(true);\n FRMListado.fSetDisabled(false);\n }\n }\n }",
"function activateDeactive(id, status) {\n $.simpleAjax({\n crud: \"Etiquetas\",\n type: \"GET\",\n url:\n $(\"#DATA\").data(\"url\") + `/tags/setStatus/${id}/${status}`,\n form: \"\",\n loadingSelector: \".panel\",\n successCallback: function (data) {\n table.ajax.reload();\n },\n errorCallback: function (data) {\n }\n });\n }",
"function refreshMissionOptions(options, activity) {\n options.find(\"button\").each( (j, e) => {\n if(j == 0) {\n $(e).toggleClass(\"active\", activity.mission_index == null);\n } else {\n $(e).toggleClass(\"active\", (j - 1) == activity.mission_index);\n }\n });\n}",
"function activate() {\n user.registerCb(function(){\n routes.fetch(user.getUser().username)\n .then(function() {});\n });\n\n }",
"function markGoalActive() {\n\t\tprops.markGoalActive(props.goalId);\n\t}",
"function reactivate() {\n enableIntervals();\n dynamicActivity = regularActivityMonitor;\n }",
"function ontoggle() {\n selected = !selected;\n logic.ontoggle(selected);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PBDB Download generator Author: Michael McClennen This code is designed to work with the file download_generator.html to implement a Web application for downloading data from the Paleobiology Database using the database's API. Users can fill in the various form elements to specify the kind of data they wish to download, filter parameters, output options, etc. The application then generates an API URL using those values, and provides a button for carrying out the download. The following function is the constructor for the application controller object. This should be called once, at load time, and provided with the following parameters: data_urlbase URL for the API is_contributortrue if the user is logged in to the database, false otherwise After this object is instantiated, its initApp method should be called to initialize it. It is a good idea to call this after the entire web page is loaded, so that all necessary DOM elements will be in place. | function DownloadGeneratorApp( data_url, is_contributor )
{
"use strict";
// Initialize some private variables.
var done_config1, done_config2;
var params = { base_name: '', interval: '', output_metadata: 1, reftypes: 'taxonomy' };
var param_errors = { };
var visible = { };
var data_type = "occs";
var data_op = "occs/list";
var url_op = "occs/list";
var data_format = ".csv";
var ref_format = "";
var non_ref_format = ".csv";
var form_mode = "simple";
var download_path = "";
var download_params = "";
var output_section = 'none';
var output_order = 'none';
var output_full = { };
var full_checked = { };
var paleoloc_all = 0;
var paleoloc_selected = 0;
var confirm_download = 0;
var taxon_status_save = '';
var no_update = 0;
// Object for holding data cached from the API
var api_data = { };
// Variables for handling object identifiers in the "metadata" section.
var id_param_map = { col: "coll_id", clu: "clust_id",
occ: "occ_id", spm: "spec_id" };
var id_param_index = { col: 0, clu: 1, occ: 2, spm: 3 };
var ref_param = { ref_id : 1, ref_title: 1, pub_title: 1, ref_primary: 1,
ref_author: 1 };
// The following regular expressions are used to validate user input.
var patt_dec_num = /^[+-]?(\d+[.]\d*|\d*[.]\d+|\d+)$/;
var patt_dec_pos = /^(\d+[.]\d*|\d*[.]\d+|\d+)$/;
var patt_int_pos = /^\d+$/;
var patt_name = /^(.+),\s+(.+)/;
var patt_name2 = /^(.+)\s+(.+)/;
var patt_has_digit = /\d/;
var patt_date = /^(\d+[mshdMY]|\d\d\d\d(-\d\d(-\d\d)?)?)$/;
var patt_extid = /^(col|occ|clu|spm)[:]\d+$/;
// If the value of data_url starts with a slash, prefix the origin of the current page to get a full URL.
var short_data_url;
var full_data_url;
// The following function initializes this application controller object. It is exported as
// a method, so that it can be called once the web page is fully loaded. It must make two
// API calls to get a list of country and continent codes, and geological time intervals.
// When both of these calls complete, the "initializing form..." HTML floating element is hidden,
// signaling to the user that the application is ready for use.
function initApp ()
{
// Do various initialization steps
no_update = 1;
initDisplayClasses();
getDBUserNames();
if ( getElementValue("vf1") != "-1" )
showHideSection('f1', 'show');
var sections = { vf2: 'f2', vf3: 'f3', vf4: 'f4', vf5: 'f5', vf6: 'f6', vo1: 'o1', vo2: 'o2' };
var s;
for ( s in sections )
{
if ( getElementValue(s) == "1" )
showHideSection(sections[s], 'show');
}
// Make sure we have a proper URL to use for data service requests.
var origin_match;
short_data_url = data_url;
if ( data_url.match( /^\// ) && window.location.origin )
full_data_url = window.location.origin + data_url;
else
full_data_url = data_url;
// If the form is being reloaded and already has values entered into it, take some steps
// to make sure it is properly set up.
try
{
var record_type = $('input[name="record_type"]:checked').val();
setRecordType(record_type);
var form_mode = $('input[name="form_mode"]:checked').val();
setFormMode(form_mode);
var output_format = $('input[name="output_format"]:checked').val();
setFormat(output_format);
var private_url = $('input[name="private_url"]:checked').val();
console.log("private_url = " + private_url);
setPrivate(private_url);
}
catch (err) { };
no_update = 0;
// Initiate two API calls to fetch necessary data. Each has a callback to handle the data
// that comes back, and a failure callback too.
$.getJSON(data_url + 'config.json?show=all&limit=all')
.done(callbackConfig1)
.fail(badInit);
$.getJSON(data_url + 'intervals/list.json?all_records&limit=all')
.done(callbackConfig2)
.fail(badInit);
}
this.initApp = initApp;
// The following function is called when the first configuration API call returns. Country
// and continent codes and taxonomic ranks are saved as properties of the api_data object.
// These will be used for validating user input.
function callbackConfig1 (response)
{
if ( response.records )
{
api_data.rank_string = { };
api_data.continent_name = { };
api_data.continents = [ ];
api_data.country_code = { };
api_data.country_name = { };
api_data.countries = [ ];
api_data.country_names = [ ];
api_data.aux_continents = [ ];
api_data.lithologies = [ ];
api_data.lith_types = [ ];
api_data.pg_models = [ ];
api_data.pg_menu = [ ];
api_data.pg_desc = [ ];
var lith_uniq = { };
for ( var i=0; i < response.records.length; i++ )
{
var record = response.records[i];
if ( record.cfg == "trn" ) {
api_data.rank_string[record.cod] = record.rnk;
}
else if ( record.cfg == "con" ) {
api_data.continent_name[record.cod] = record.nam;
api_data.continents.push(record.cod, record.nam);
}
else if ( record.cfg == "cou" ) {
var key = record.nam.toLowerCase();
api_data.country_code[key] = record.cod;
api_data.country_name[record.cod] = record.nam;
api_data.country_names.push(record.nam);
}
else if ( record.cfg == "lth" ) {
api_data.lithologies.push( record.lth, record.lth );
if ( ! lith_uniq[record.ltp] )
{
api_data.lith_types.push( record.ltp, record.ltp );
lith_uniq[record.ltp] = 1;
}
}
else if ( record.cfg == "pgm" ) {
api_data.pg_desc.push(record.cod, record.dsc);
api_data.pg_models.push(record.cod);
api_data.pg_menu.push(record.cod, record.lbl);
}
}
api_data.lith_types.push( 'unknown', 'unknown' );
// api_data.continents = api_data.continents.concat(api_data.aux_continents);
api_data.country_names = api_data.country_names.sort();
for ( i=0; i < api_data.country_names.length; i++ )
{
var key = api_data.country_names[i].toLowerCase();
var code = api_data.country_code[key];
api_data.countries.push( code, api_data.country_names[i] + " (" + code + ")" );
}
// If both API calls are complete, finish the initialization process.
done_config1 = 1;
if ( done_config2 ) finishInitApp();
}
// If no results were received, we're in trouble. The application can't be used if the
// API is not working, so there's no point in proceeding further.
else
badInit();
}
// The following function is called when the second configuration API call returns. The names
// of known geological intervals are saved as a property of the api_data object. These will
// be used for validating user input.
function callbackConfig2 (response)
{
if ( response.records )
{
api_data.interval = { };
for ( var i = 0; i < response.records.length; i++ )
{
var record = response.records[i];
var key = record.nam.toLowerCase();
api_data.interval[key] = record.oid;
}
// If both API calls are complete, finish the initialization process.
done_config2 = 1;
if ( done_config1 ) finishInitApp();
}
// If no results were received, we're in trouble. The application can't be used if the
// API is not working, so there's no point in proceeding further.
else
badInit();
}
// This function is called when both configuration API calls are complete. It hides the
// "initializing form, please wait" HTML floating object, and then calls updateFormState to
// initialize the main URL and other form elements.
function finishInitApp ()
{
initFormContents();
var init_box = myGetElement("db_initmsg");
if ( init_box ) init_box.style.display = 'none';
no_update = 1;
try {
checkTaxon();
checkTaxonStatus();
checkInterval();
checkCC();
checkCoords();
checkStrat();
checkEnv();
checkMeta('specs');
checkMeta('occs');
checkMeta('colls');
checkMeta('taxa');
checkMeta('occs');
checkMeta('refs');
}
catch (err) { };
no_update = 0;
updateFormState();
}
// The following method can be called to reset the form back to its initial state. It is tied
// to the "clear form" button in the HTML layout. The options selected in the top section of
// the form (i.e. record type, output format) will be preserved. All others will be reset.
function resetForm ()
{
var keep_type = data_type;
var keep_format = data_format.substring(1);
var keep_private = params.private;
var keep_advanced = form_mode;
var form_elt = myGetElement("download_form");
if ( form_elt ) form_elt.reset();
params = { base_name: '', interval: '', output_metadata: 1, reftypes: 'taxonomy' };
initDisplayClasses();
try
{
no_update = 1;
setRecordType(keep_type);
$('input[name="record_type"][value="' + keep_type + '"]')[0].checked = 1;
setFormat(keep_format);
$('input[name="output_format"][value="' + keep_format + '"]')[0].checked = 1;
setPrivate(keep_private);
$('input[name="private"][value="' + keep_private + '"]')[0].checked = 1;
setFormMode(keep_advanced);
$('input[name="form_mode"][value="' + keep_advanced + '"]')[0].checked = 1;
}
finally
{
no_update = 0;
}
updateFormState();
}
this.resetForm = resetForm;
// This function notifies the user that this application is not able to be used. It is called
// if either of the configuration API calls fail. If the API is not working, there's no point
// in proceeding with this application.
function badInit ( )
{
var init_box = myGetElement("db_initmsg");
if ( init_box ) init_box.innerHTML = "Initialization failed! Please contact admin@paleobiodb.org";
}
// Included in this application is a system to easily hide and show all HTML objects that are
// tagged with particular CSS classes. This subroutine sets up the initial form state.
function initDisplayClasses ()
{
showByClass('type_occs');
showByClass('taxon_reso');
showByClass('advanced');
hideByClass('taxon_mods');
hideByClass('mult_cc3');
hideByClass('mult_cc2');
hideByClass('type_colls');
hideByClass('type_taxa');
hideByClass('type_ops');
hideByClass('type_strata');
hideByClass('type_refs');
hideByClass('help_h1');
hideByClass('help_h2a');
hideByClass('help_h2b');
hideByClass('help_f1');
hideByClass('help_f2');
hideByClass('help_f3');
hideByClass('help_f4');
hideByClass('help_f5');
hideByClass('help_f6');
hideByClass('help_o1');
hideByClass('help_o2');
hideByClass('buffer_rule');
// If the user is currently logged in to the database, show the form element that chooses
// between generating a URL that fetches private data and one that does not. The former
// will only work when the user is logged in, the latter may be distributed publicly.
if ( is_contributor )
{
showByClass('loggedin');
// params.private = 1;
}
else
hideByClass('loggedin');
}
// -----------------------------------------------------------------------------------------
// The following functions generate some of the repetitious HTML necessary for checklists and
// other complex controls. Doing it this way makes the lists easier to change as the API is
// updated, and allows download_generator.html to be much smaller and simpler. These
// functions call convenience routines such as setInnerHTML, which are defined below.
function initFormContents ( )
{
var content = "";
// First generate the controls for selecting output blocks
content = "<tr><td>\n";
// "*full", "full", "Includes all boldface blocks (no need to check them separately)",
content += makeBlockControl( "od_occs",
["*attribution", "attr", "Attribution (author and year) of the accepted name",
"*classification", "class", "Taxonomic classification of the occurrence",
"classification ext.", "classext", "Taxonomic classification including taxon ids",
"genus", "genus", "Use instead of the above if you just want the genus",
"subgenus", "subgenus", "Use with any of the above to include subgenus as well",
"accepted only", "acconly", "Suppress the exact identification of the occurrence, show only accepted name",
"ident components", "ident", "Individual components of the identification, rarely needed",
"phylopic id", "img", "Identifier of a <a href=\"http://phylopic.org/\" target=\"_blank\">phylopic</a>" +
"representing this taxon or the closest containing taxon",
"*plant organs", "plant", "Plant organ(s) identified as part of this occurrence, if any",
"*abundance", "abund", "Abundance of this occurrence in the collection",
"*ecospace", "ecospace", "The ecological space occupied by this organism",
"*taphonomy", "taphonomy", "Taphonomy of this organism",
"eco/taph basis", "etbasis", "Annotation for ecospace and taphonomy as to taxonomic level",
"*preservation", "pres", "Is this occurrence identified as a form taxon, ichnotaxon or regular taxon",
"*collection", "coll", "The name and description of the collection in which this occurrence was found",
"*coordinates", "coords", "Latitude and longitude of this occurrence",
"*location", "loc", "Additional info about the geographic locality",
"*paleolocation", "paleoloc", "Paleogeographic location of this occurrence, all models",
"paleoloc (selected)", "paleoloc2", "Paleogeographic location using the model selected above",
"*protection", "prot", "Indicates whether this occurrence is on protected land, i.e. a national park",
"stratigraphy", "strat", "Basic stratigraphy of the occurrence",
"*stratigraphy ext.", "stratext", "Extended (detailed) stratigraphy of the occurrence",
"lithology", "lith", "Basic lithology of the occurrence",
"*lithology ext.", "lithext", "Extended (detailed) lithology of the occurrence",
"paleoenvironment", "env", "The paleoenvironment associated with this collection",
"*geological context", "geo", "Additional info about the geological context (includes env)",
"time binning", "timebins", "Lists the interval(s) from the international timescale into which each " +
"occurrence falls",
"time comparison", "timecompare", "Shows the time binning for all available timerules, so you can compare them",
"*methods", "methods", "Info about the collection methods used",
"research group", "resgroup", "The research group(s) if any associated with the collection",
"reference", "ref", "The reference from which this occurrence was entered, as formatted text",
"*ref attribution", "refattr", "Author(s) and publication year of the reference",
"enterer ids", "ent", "Identifiers of the people who authorized/entered/modified each record",
"enterer names", "entname", "Names of the people who authorized/entered/modified each record",
"created/modified", "crmod", "Creation and modification timestamps for each record" ]);
content += "</td></tr>\n";
content += makeOutputHelpRow("occs/list");
setInnerHTML("od_occs", content);
content = "<tr><td>\n";
content += makeBlockControl( "od_colls",
["*location", "loc", "Additional info about the geographic locality",
"*paleolocation", "paleoloc", "Paleogeographic location of this collection, all models",
"paleoloc (selected)", "paleoloc2", "Paleogeographic location using the model selected above",
"*protection", "prot", "Indicates whether collection is on protected land",
"time binning", "timebins", "Lists the interval(s) from the international timescale into which each " +
"collection falls",
"time comparison", "timecompare", "Like the above, but shows this information for all available timerules",
"stratigraphy", "strat", "Basic stratigraphy of the occurrence",
"*stratigraphy ext.", "stratext", "Detailed stratigraphy of the occurrence",
"lithology", "lith", "Basic lithology of the occurrence",
"*lithology ext.", "lithext", "Detailed lithology of the occurrence",
"*geological context", "geo", "Additional info about the geological context",
"*methods", "methods", "Info about the collection methods used",
"research group", "resgroup", "The research group(s) if any associated with this collection",
"reference", "ref", "The primary reference associated with this collection, as formatted text",
"*ref attribution", "refattr", "Author(s) and publication year of the reference",
"all references", "secref", "Identifiers of all references associated with this collection",
"enterer ids", "ent", "Identifiers of the people who authorized/entered/modified this record",
"enterer names", "entname", "Names of the people who authorized/entered/modified this record",
"created/modified", "crmod", "Creation and modification timestamps" ]);
content += "</td></tr>\n";
content += makeOutputHelpRow("colls/list");
setInnerHTML("od_colls", content);
content = "<tr><td>\n";
content += makeBlockControl( "od_specs",
["*attribution", "attr", "Attribution (author and year) of the accepted taxonomic name",
"*classification", "class", "Taxonomic classification of the specimen",
"classification ext.", "classext", "Taxonomic classification including taxon ids",
"genus", "genus", "Use instead of the above if you just want the genus",
"subgenus", "subgenus", "Use with any of the above to include subgenus as well",
"*plant organs", "plant", "Plant organ(s) if any",
"*abundance", "abund", "Abundance of the occurrence (if any) in its collection",
"*collection", "coll", "The name and description of the collection in which the occurrence (if any) was found",
"*coordinates", "coords", "Latitude and longitude of the occurrence (if any)",
"*location", "loc", "Additional info about the geographic locality of the occurrence (if any)",
"*paleolocation", "paleoloc", "Paleogeographic location of this collection, all models",
"paleoloc (selected)", "paleoloc2", "Paleogeographic location using the model selected above",
"*protection", "prot", "Indicates whether source of specimen was on protected land (if known)",
"stratigraphy", "strat", "Basic stratigraphy of the occurrence (if any)",
"*stratigraphy ext.", "stratext", "Detailed stratigraphy of the occurrence (if any)",
"lithology", "lith", "Basic lithology of the occurrence (if any)",
"*lithology ext.", "lithext", "Detailed lithology of the occurrence (if any)",
"*geological context", "geo", "Additional info about the geological context (if known)",
"*methods", "methods", "Info about the collection methods used (if known)",
"remarks", "rem", "Additional remarks about the associated collection (if any)",
"resgroup", "resgroup", "The research group(s) if any associated with this collection",
"reference", "ref", "The reference from which this specimen was entered, as formatted text",
"*ref attribution", "refattr", "Author(s) and publication year of the reference",
"enterer ids", "ent", "Identifiers of the people who authorized/entered/modified this record",
"enterer names", "entname", "Names of the people who authorized/entered/modified this record",
"created/modified", "crmod", "Creation and modification timestamps" ]);
content += "</td></tr>\n";
content += makeOutputHelpRow("specs/list");
setInnerHTML("od_specs", content);
content = "<tr><td>\n";
content += makeBlockControl( "od_taxa",
["*attribution", "attr", "Attribution (author and year) of this taxonomic name",
"*common", "common", "Common name (if any)",
"*age range overall", "app", "Ages of first and last appearance among all occurrences in this database",
"age range selected", "occapp", "Ages of first and last appearance among selected occurrences",
"*parent", "parent", "Name and identifier of parent taxon",
"immediate parent", "immparent", "Name and identifier of immediate parent taxon (may be a junior synonym)",
"*size", "size", "Number of subtaxa",
"*classification", "class", "Taxonomic classification: phylum, class, order, family, genus",
"classification ext.", "classext", "Taxonomic classification including taxon ids",
"*subtaxon counts", "subcounts", "Number of genera, families, and orders contained in this taxon",
"*ecospace", "ecospace", "The ecological space occupied by this organism",
"*taphonomy", "taphonomy", "Taphonomy of this organism",
"eco/taph basis", "etbasis", "Annotation for ecospace and taphonomy as to taxonomic level",
"*preservation", "pres", "Is this a form taxon, ichnotaxon or regular taxon",
"sequence numbers", "seq", "The sequence numbers of this taxon in the computed tree",
"phylopic id", "img", "Phylopic identifier",
"reference", "ref", "The reference from which this taxonomic name was entered, as formatted text",
"*ref attribution", "refattr", "Author(s) and publication year of the reference",
"enterer ids", "ent", "Identifiers of the people who authorized/entered/modified this record",
"enterer names", "entname", "Names of the people who authorized/entered/modified this record",
"created/modified", "crmod", "Creation and modification timestamps" ]);
content += "</td></tr>\n";
content += makeOutputHelpRow("taxa/list");
setInnerHTML("od_taxa", content);
content = "<tr><td>\n";
content += makeBlockControl( "od_ops",
["*basis", "basis", "Basis of this opinion, i.e. 'stated with evidence'",
"reference", "ref", "The reference from which this opinion was entered, as formatted text",
"*ref attribution", "refattr", "Author(s) and publication year of the reference",
"enterer ids", "ent", "Identifiers of the people who authorized/entered/modified this record",
"enterer names", "entname", "Names of the people who authorized/entered/modified this record",
"created/modified", "crmod", "Creation and modification timestamps" ]);
content += "</td></tr>\n";
content += makeOutputHelpRow("opinions/list");
setInnerHTML("od_ops", content);
content = "<tr><td>\n";
content += makeBlockControl( "od_strata",
["coordinates", "coords", "Latitude and longitude range of occurrences"])
content += "</td></tr>\n";
content += makeOutputHelpRow("strata/list");
setInnerHTML("od_strata", content);
content = "<tr><td>\n";
content += makeBlockControl( "od_refs",
["associated counts", "counts", "Counts of authorities, opinions, occurrences, " +
"collections associated with this reference",
"formatted", "formatted", "Return a single formatted string instead of individual fields",
"both", "both", "Return a single formatted string AND the individual fields",
"comments", "comments", "Comments entered about this reference, if any",
"enterer ids", "ent", "Identifiers of the people who authorized/entered/modified this record",
"enterer names", "entname", "Names of the people who authorized/entered/modified this record",
"created/modified", "crmod", "Creation and modification timestamps" ]);
content += "</td></tr>\n";
content += makeOutputHelpRow("refs/list");
setInnerHTML("od_refs", content);
// Then the controls for selecting output order
content = makeOptionList( [ '--', 'default', 'earlyage', 'max_ma', 'lateage', 'min_ma',
'taxon', 'taxonomic hierarchy',
'formation', 'geological formation', 'plate', 'tectonic plate',
'created', 'creation date of record',
'modified', 'modification date of record' ] );
setInnerHTML("pm_occs_order", content);
setInnerHTML("pm_colls_order", content);
content = makeOptionList( [ '--', 'default', 'hierarchy', 'taxonomic hierarchy',
'name', 'taxonomic name (alphabetical)',
'ref', 'bibliographic reference',
'firstapp', 'first appearance', 'lastapp', 'last appearance',
'n_occs', 'number of occurrences',
'authpub', 'author of name, year of publication',
'pubauth', 'year of publication, author of name',
'created', 'creation date of record',
'modified', 'modification date of record' ] );
setInnerHTML("pm_taxa_order", content);
content = makeOptionList( [ '--', 'default', 'hierarchy', 'taxonomic hierarchy',
'name', 'taxonomic name (alphabetical)',
'ref', 'bibliographic reference',
'authpub', 'author of opinion, year of publication',
'pubauth', 'year of publication, author of opinion',
'basis', 'basis of opinion',
'created', 'creation date of record',
'modified', 'modification date of record' ] );
setInnerHTML("pm_ops_order", content);
content = makeOptionList( [ '--', 'default', 'authpub', 'author of reference, year of publication',
'pubauth', 'year of publication, author of reference',
'reftitle', 'title of reference',
'pubtitle', 'title of publication',
'created', 'creation date of record',
'modified', 'modification date of record' ] );
setInnerHTML("pm_refs_order", content);
// Then generate various option lists. The names and codes for the continents and
// countries were fetched during initialization via an API call.
var continents = api_data.continents || ['ERROR', 'Continent list is empty'];
content = makeOptionList( [ '--', '--', '**', 'Multiple' ].concat(continents) );
setInnerHTML("pm_continent", content);
content = makeCheckList( "pm_continents", api_data.continents, 'dgapp.checkCC()' );
setInnerHTML("pd_continents", content);
var countries = api_data.countries || ['ERROR', 'Country list is empty'];
content = makeOptionList( ['--', '--', '**', 'Multiple'].concat(countries) );
setInnerHTML("pm_country", content);
content = makeOptionList( api_data.pg_menu );
setInnerHTML("pm_pg_model", content);
content = makeOptionList( ['', '--'].concat(api_data.pg_menu).concat(['all', 'all']) );
params.pg_model = getElementValue("pm_pg_model");
params.pg_select = getElementValue("pm_pg_select");
setInnerHTML("pm_pg_compare", content);
var crmod_options = [ 'created_after', 'entered after',
'created_before', 'entered before',
'modified_after', 'modified after',
'modified_before', 'modified before' ];
content = makeDefinitionList( api_data.pg_desc );
setInnerHTML("doc_pgm", content);
content = makeOptionList( crmod_options );
setInnerHTML("pm_specs_crmod", content);
setInnerHTML("pm_occs_crmod", content);
setInnerHTML("pm_colls_crmod", content);
setInnerHTML("pm_taxa_crmod", content);
setInnerHTML("pm_ops_crmod", content);
setInnerHTML("pm_refs_crmod", content);
var authent_options = [ 'authent_by', 'authorized/entered by',
'authorized_by', 'authorized by',
'entered_by', 'entered by',
'modified_by', 'modified by',
'touched_by', 'touched by' ];
content = makeOptionList( authent_options );
setInnerHTML("pm_specs_authent", content);
setInnerHTML("pm_occs_authent", content);
setInnerHTML("pm_colls_authent", content);
setInnerHTML("pm_taxa_authent", content);
setInnerHTML("pm_ops_authent", content);
setInnerHTML("pm_refs_authent", content);
content = makeCheckList( "pm_lithtype", api_data.lith_types, 'dgapp.checkLith()' );
setInnerHTML("pd_lithtype", content);
var envtype_options = [ 'terr', 'terrestrial',
'marine', 'any marine',
'carbonate', 'carbonate',
'silicic', 'siliciclastic',
'unknown', 'unknown' ];
content = makeCheckList( "pm_envtype", envtype_options, 'dgapp.checkEnv()' );
setInnerHTML("pd_envtype", content);
var envzone_options = [ 'lacust', 'lacustrine', 'fluvial', 'fluvial',
'karst', 'karst', 'terrother', 'terrestrial other',
'marginal', 'marginal marine', 'reef', 'reef',
'stshallow', 'shallow subtidal', 'stdeep', 'deep subtidal',
'offshore', 'offshore', 'slope', 'slope/basin',
'marindet', 'marine indet.' ];
content = makeCheckList( "pm_envzone", envzone_options, 'dgapp.checkEnv()' );
setInnerHTML("pd_envzone", content);
var reftypes = [ '+auth', 'authority references', '+class', 'classification references',
'ops', 'all opinion references', 'occs', 'occurrence references',
'specs', 'specimen references', 'colls', 'collection references' ];
content = makeCheckList( "pm_reftypes", reftypes, 'dgapp.checkRefopts()' );
setInnerHTML("pd_reftypes", content);
var taxon_mods = [ 'nm', 'no modifiers', 'ns', 'n. sp.', 'ng', 'n. (sub)gen', 'af', 'aff.', 'cf', 'cf.',
'sl', 'sensu lato', 'if', 'informal', 'eg', 'ex gr.',
'qm', '?', 'qu', '""' ];
content = makeCheckList( "pm_idgenmod", taxon_mods, 'dgapp.checkTaxonMods()' );
setInnerHTML("pd_idgenmod", content);
content = makeCheckList( "pm_idspcmod", taxon_mods, 'dgapp.checkTaxonMods()' );
setInnerHTML("pd_idspcmod", content);
// We need to execute the following operation here, because the
// spans to which it applies are created by the code above.
hideByClass('help_o1');
}
// The following function generates HTML code for displaying a checklist of output blocks.
// One of these is created for every different data type. As a SIDE EFFECT, produces a
// hash listing every boldfaced block and stores it in a property of the variable 'output_full'.
function makeBlockControl ( section_name, block_list )
{
var content = "";
output_full[section_name] = output_full[section_name] || { };
for ( var i = 0; i < block_list.length; i += 3 )
{
var block_name = block_list[i];
var block_code = block_list[i+1];
var block_doc = block_list[i+2];
var attrs = '';
var asterisked = 0;
if ( block_name.indexOf('*') == 0 )
{
asterisked = 1;
block_name = block_name.slice(1);
output_full[section_name][block_code] = 1;
}
content = content + '<span class="dlBlockLabel"><input type="checkbox" name="' +
section_name + '" value="' + block_code + '" ';
content = content + attrs + ' onClick="dgapp.updateFormState()">';
content += asterisked ? '<b>' + block_name + '</b>' : block_name;
content += '</span><span class="vis_help_o1">' + block_doc + "<br/></span>\n";
}
return content;
}
// The following function generates HTML code for the "help" row at the bottom of a checklist
// of output blocks.
function makeOutputHelpRow ( path )
{
var content = '<tr class="dlHelp vis_help_o1"><td>' + "\n";
content += "<p>You can get more information about these output blocks and fields ";
content += '<a target="_blank" href="' + data_url + path + '#RESPONSE" ';
content += 'style="text-decoration: underline">here</a>.</p>';
content += "\n</td></tr>";
return content;
}
// The following function generates HTML code for displaying a checklist of possible parameter
// values.
function makeCheckList ( list_name, options, ui_action )
{
var content = '';
if ( options == undefined || ! options.length )
{
console.log("ERROR: no options specified for checklist '" + list_name + "'");
return content;
}
for ( var i=0; i < options.length / 2; i++ )
{
var code = options[2*i];
var label = options[2*i+1];
var attrs = '';
var checked = false;
if ( code.substr(0,1) == '+' )
{
code = code.substr(1);
checked = true;
}
content += '<span class="dlCheckBox"><input type="checkbox" name="' + list_name + '" value="' + code + '" ';
if ( checked ) content += 'checked="1" ';
content += attrs + 'onClick="' + ui_action + '">' + label + "</span>\n";
}
return content;
}
// The following function generates HTML code for displaying a dropdown menu of possible
// parameter values.
function makeOptionList ( options )
{
var content = '';
var i;
if ( options == undefined || ! options.length )
{
return '<option value="error">ERROR</option>';
}
for ( i=0; i < options.length / 2; i++ )
{
var code = options[2*i];
var label = options[2*i+1];
content += '<option value="' + code + '">' + label + "</option>\n";
}
return content;
}
// The following function generates HTML code for a definitio list.
function makeDefinitionList ( options )
{
var content = '';
var i;
if ( options == undefined || ! options.length )
{
return '<dt>ERROR</dt>';
}
for ( i=0; i < options.length / 2; i++ )
{
var code = options[2*i];
var description = options[2*i+1];
content += '<dt>' + code + '</dt><dd>' + description + '</dd>';
}
return content;
}
// We don't have to query the API to get the list of database contributor names, because the
// Classic code that generates the application's web page automatically includes the function
// 'entererNames' which returns this list. We go through this list and stash all of the names
// in the api_data object anyway.
function getDBUserNames ( )
{
if ( api_data.user_names ) return;
api_data.user_names = entererNames();
api_data.valid_name = { };
api_data.user_match = [ ];
api_data.user_matchinit = [ ];
// The names might be either in the form "last, first" or "first last". We have to check
// both patterns. We add the object 'valid_name', whose properties include all of the
// valid names in the form "first last" plus all last names.
for ( var i = 0; i < api_data.user_names.length; i++ )
{
var match;
if ( match = api_data.user_names[i].match(patt_name) )
{
api_data.valid_name[match[1]] = 1;
var rebuilt = match[2].substr(0,1) + '. ' + match[1];
api_data.valid_name[rebuilt] = 1;
api_data.user_names[i] = rebuilt;
api_data.user_match[i] = match[1].toLowerCase();
api_data.user_matchinit[i] = match[2].substr(0,1).toLowerCase();
}
else if ( match = api_data.user_names[i].match(patt_name2) )
{
api_data.valid_name[match[2]] = 1;
var rebuilt = match[1].substr(0,1) + '. ' + match[2];
api_data.valid_name[rebuilt] = 1;
api_data.user_names[i] = rebuilt;
api_data.user_match[i] = match[2].toLowerCase();
api_data.user_matchinit[i] = match[1].substr(0,1).toLowerCase();
}
}
}
// -----------------------------------------------------------------------------
// The following convenience methods manipulate DOM objects. We use the javascript object
// 'visible' to keep track of which groups of objects are supposed to be visible and which are
// not. The properties of this object are matched up with CSS classes whose names start with
// 'vis_' or 'inv_'. If an object has CSS classes 'vis_x' and 'vis_y', then it is visible if
// both visible[x] and visible[y] are true, hidden otherwise. Additionally, if an object has
// CSS class 'inv_z', then it is hidden whenever visible[z] is true.
// The following routine sets visible[classname] to false, then adjusts the visibility of all
// DOM objects.
function hideByClass ( classname )
{
// We start by setting the specified property of visible to false.
visible[classname] = 0;
// All objects with class 'vis_' + classname must now be hidden, regardless of any other
// classes they may also have.
var list = document.getElementsByClassName('vis_' + classname);
for ( var i = 0; i < list.length; i++ )
{
list[i].style.display = 'none';
}
// Some objects with class 'inv_' + classname may now be visible, if visible[x] is true for
// each class 'vis_x' that the object has and visible[y] is false for each class 'inv_y'
// that the object has.
list = document.getElementsByClassName('inv_' + classname);
element:
for ( var i = 0; i < list.length; i++ )
{
// For each such object, check all of its classes.
var classes = list[i].classList;
for ( var j = 0; j < classes.length; j++ )
{
var classprefix = classes[j].slice(0,4);
var rest = classes[j].substr(4);
// If it has class 'vis_x' and visible[x] is not true, then setting
// visible[classname] to false does not change its status.
if ( classprefix == "vis_" && ! visible[rest] )
{
continue element;
}
// If it has class 'inv_y' and visible[y] is true, then y != classname because we
// set visible[classname] to false at the top of this function. So this object's
// status doesn't change either.
else if ( classprefix == "inv_" && visible[rest] )
{
continue element;
}
}
// If we get here then the object should be made visible.
list[i].style.display = '';
}
}
// The following routine sets visible[classname] to true, then adjusts the visibility of all
// DOM objects.
function showByClass ( classname )
{
visible[classname] = 1;
// Some objects with class 'vis_' + classname may now be visible, if visible[x] is true for
// each class 'vis_x' that the object has and visible[y] is false for each class 'inv_y'
// that the object has.
var list = document.getElementsByClassName('vis_' + classname);
element:
for ( var i = 0; i < list.length; i++ )
{
// For each such object, check all of its classes.
var classes = list[i].classList;
for ( var j = 0; j < classes.length; j++ )
{
var classprefix = classes[j].slice(0,4);
var rest = classes[j].substr(4);
// If it has class 'vis_x' and visible[x] is not true, then x != classname because
// we set visible[classname] to true at the top of this function. So this
// object's status does not change.
if ( classprefix == "vis_" && ! visible[rest] )
{
continue element;
}
// If it has class 'inv_y' and visible[y] is true, then its status does not change
// because 'inv_' overrides 'vis_'.
else if ( classprefix == "inv_" && visible[rest] )
{
continue element;
}
}
// If we get here then the object should be made visible.
list[i].style.display = '';
}
// All objects with class 'inv_' + classname must now be hidden, regardless of any other
// classes they may also have.
list = document.getElementsByClassName('inv_' + classname);
for ( var i = 0; i < list.length; i++ )
{
list[i].style.display = 'none';
}
}
// The following method expands or collapses the specified section of the application. If
// the value of 'action' is 'show', then it is expanded. Otherwise, its state is
// toggled.
function showHideSection ( section_id, action )
{
// If we are forcing or toggling the section to expanded then execute the necessary steps.
// The triangle marker corresponding to the section has the same name but prefixed with
// 'm'.
if ( ! visible[section_id] || (action && action == 'show') )
{
showElement(section_id);
setElementSrc('m'+section_id, "/JavaScripts/img/open_section.png");
setElementValue('v'+section_id, "1");
var val = getElementValue('v'+section_id);
}
// Otherwise, we must be toggling it to collapsed.
else
{
hideElement(section_id);
setElementSrc('m'+section_id, "/JavaScripts/img/closed_section.png");
setElementValue('v'+section_id, "-1");
var val = getElementValue('v'+section_id);
}
// Update the form state to reflect the new configuration.
updateFormState();
}
this.showHideSection = showHideSection;
// The following method should be called if the user clicks the 'help' button for one of the
// sections. If the section is currently collapsed, it will be expanded. The help text and
// related elements for the section will then be toggled. The event object responsible for
// this action can be passed as the second parameter, or else it will be assumed to be the
// currently executing event.
function helpClick ( section_id, e )
{
if ( ! visible[section_id] && ! visible['help_' + section_id] )
showHideSection(section_id, 'show');
showHideHelp(section_id);
// Stop the event from propagating, because it has now been carried out.
if ( !e ) e = window.event;
e.stopPropagation();
}
this.helpClick = helpClick;
// Adjust the visiblity of the help text for the specified section of the application. If the
// action is 'show', make it visible. If 'hide', make it invisible. Otherwise, toggle it.
// The help button has the same name as the section, but prefixed with 'q'. The help elements
// all have the class 'vis_help_' + the section id.
function showHideHelp ( section_id, action )
{
// If the help text is visible and we're either hiding or toggling, then do so.
if ( visible['help_' + section_id] && ( action == undefined || action == "hide" ) )
{
setElementSrc('q' + section_id, "/JavaScripts/img/hidden_help.png");
hideByClass('help_' + section_id);
}
// If the help text is invisible and we're showing or toggling, then do so.
else if ( action == undefined || action == "show" )
{
setElementSrc('q' + section_id, "/JavaScripts/img/visible_help.png");
showByClass('help_' + section_id);
}
}
// ------------------------------------------------------------------------------------
// The following convenience routines operate on elements one at a time, rather than in
// groups. This is an alternate mechanism for showing and hiding elements, used for elements
// which are singular such as the "initializing application" floater or the elements that
// display error messages. These routines also set the property of the 'visible' object
// corresponding to the identifier of the element being set.
// This function retrieves the DOM object with the specified id, and leaves a reasonable
// message on the console if the program contains a typo and the requested element does not
// exist.
function myGetElement ( id )
{
var elt = document.getElementById(id);
if ( elt == undefined )
{
console.log("ERROR: unknown element '" + id + "'");
return undefined;
}
else return elt;
}
// Hide the DOM element with the specified id.
function hideElement ( id )
{
var elt = myGetElement(id);
if ( elt )
{
elt.style.display = 'none';
visible[id] = 0;
}
}
// Show the DOM elment with the specified id.
function showElement ( id )
{
var elt = myGetElement(id);
if ( elt )
{
elt.style.display = '';
visible[id] = 1;
}
}
// // Show one element from a list, and hide the rest. The list is given by the argument
// // 'values', prefixed by 'prefix'. The value corresponding to 'selected' specifies which
// // element to show; the rest are hidden.
// function showOneElement ( selected, prefix, values )
// {
// for ( var i = 0; i < values.length; i++ )
// {
// var name = values[i].value;
// if ( name == selected )
// showElement(prefix + name);
// else
// hideElement(prefix + name);
// }
// }
// Set the 'innerHTML' property of the specified element. If the specified content is not a
// string, then the property is set to the empty string.
function setInnerHTML ( id, content )
{
var elt = myGetElement(id);
if ( elt )
{
if ( typeof(content) != "string" )
elt.innerHTML = "";
else
elt.innerHTML = content;
}
}
// Set the 'src' property of the specified element.
function setElementSrc ( id, value )
{
var elt = myGetElement(id);
if ( elt && typeof(value) == "string" ) elt.src = value;
}
// Set the 'value' property of the specified element.
function setElementValue ( id, value )
{
var elt = myGetElement(id);
if ( elt && typeof(value) == "string" ) elt.value = value;
}
// Set the 'innerHTML' property of the specified element to a sequence of list items derived
// from the elements of 'messages'. The first argument should be the identifier of a DOM <ul>
// object, and the second should be an array of strings. If the second argument is undefined
// or empty, then the list contents are set to the empty string. This function is used to
// display or clear lists of error messages, in order to inform the application user about
// improper values they have entered or other error conditions.
function setErrorMessage ( id, messages )
{
if ( messages == undefined || messages == "" || messages.length == 0 )
{
setInnerHTML(id, "");
hideElement(id);
}
else if ( typeof(messages) == "string" )
{
setInnerHTML(id, "<li>" + messages + "</li>");
showElement(id);
}
else
{
var err_msg = messages.join("</li><li>") || "Error";
setInnerHTML(id, "<li>" + err_msg + "</li>");
showElement(id);
}
}
// Set the 'disabled' property of the specified DOM object to true or false, according to the
// second argument.
function setDisabled ( id, disabled )
{
var elt = myGetElement(id);
if ( elt ) elt.disabled = disabled;
}
// If the specified DOM object is of type "checkbox", then return the value of its 'checked'
// attribute. Otherwise, return the value of its 'value' attribute.
function getElementValue ( id )
{
var elt = myGetElement(id);
if ( elt && elt.type && elt.type == "checkbox" )
return elt.checked;
else if ( elt )
return elt.value;
else
return "";
}
// If the specified DOM object is of type "checkbox" then set its 'checked' attribute to
// false. Otherwise, set its 'value' attribute to the empty string.
function clearElementValue ( id )
{
var elt = myGetElement(id);
if ( elt && elt.type && elt.type == "checkbox" )
elt.checked = 0;
else if ( elt )
elt.value = "";
}
// The following function returns a list of the values of all checked elements from among
// those with the specified name.
function getCheckList ( list_name )
{
var elts = document.getElementsByName(list_name);
var i;
var selected = [];
for ( i=0; i < elts.length; i++ )
{
if ( elts[i].checked ) selected.push(elts[i].value);
}
return selected.join(',');
}
// ---------------------------------------------------------------------------------
// The following routines check various parts of the user input. They are called from the
// HTML side of this application when various form fields are modified. These routines set
// properties of the javascript object 'params' to indicate good parameter values that should
// be used to generate the main URL, and properties of the javascript object 'param_errors' to
// indicate that the main URL should not be generated because of input errors. Each of these
// routines ends by calling updateFormState to update the main URL.
// The following function is called whenever any of the form elements "pm_base_name",
// "pm_ident", or "pm_pres" in the section "Select by Taxonomy" are changed.
function checkTaxon ( )
{
// Get the current value of each element. The values for 'ident' and 'pres' come from
// dropdown menus and can be stored as-is.
var base_name = getElementValue("pm_base_name");
params.ident = getElementValue("pm_ident");
params.pres = getElementValue("pm_pres");
// Filter out spurious characters from the value of 'base_name'. Turn multiple
// commas/whitespace into a single comma followed by a space, multiple ^ into a single ^
// preceded by a space, and take out any sequence of non-alphabetic characters at the end
// of the string.
base_name = base_name.replace(/[\s,]*,[\s,]*/g, ", ");
base_name = base_name.replace(/\^\s*/g, " ^");
base_name = base_name.replace(/\^[\s^]*/g, "^");
base_name = base_name.replace(/[\s^]*\^,[\s,]*/g, ", ");
base_name = base_name.replace(/[^a-zA-Z:]+$/, "");
// If the result is the same as the stored value of this field, then just call
// 'updateFormState' without changing anything.
if ( base_name == params.base_name )
{
updateFormState();
}
// Otherwise, if the value is empty, then clear the stored value and any error messages
// associated with this field.
else if ( base_name == "" )
{
params.base_name = "";
param_errors.base_name = 0;
setErrorMessage("pe_base_name", "");
updateFormState();
}
// Otherwise, we need to call the API to determine if the value(s) entered in this field
// are actual taxonomic names known to the database.
else
{
params.base_name = base_name;
$.getJSON(data_url + 'taxa/list.json?name=' + base_name).done(callbackBaseName);
}
}
this.checkTaxon = checkTaxon;
// This is called when the API call for a new taxonomic name completes. If the result
// includes any error or warning messages, display them to the user and set the 'base_name'
// property of 'param_errors' to true. Otherwise, we know that the names were good so we
// clear any messages that were previously displayed and set the property to false.
function callbackBaseName ( response )
{
if ( response.warnings )
{
var err_msg = response.warnings.join("</li><li>") || "There is a problem with the API";
setErrorMessage("pe_base_name", err_msg);
param_errors.base_name = 1;
}
else if ( response.errors )
{
var err_msg = response.errors.join("</li><li>") || "There is a problem with the API";
setErrorMessage("pe_base_name", err_msg);
param_errors.base_name = 1;
}
else
{
setErrorMessage("pe_base_name", "");
param_errors.base_name = 0;
}
updateFormState();
}
// This function is called when various fields in the "Select by taxonomy" section are
// modified. The parameter 'changed' indicates which one has changed.
function checkTaxonStatus ( changed )
{
var accepted_box = myGetElement("pm_acc_only");
var status_selector = myGetElement("pm_taxon_status");
var variant_box = myGetElement("pm_taxon_variants");
if ( ! accepted_box || ! status_selector || ! variant_box ) return;
// If the checkbox "show accepted names only" is now checked, then save the previous value
// for the 'status_selector' dropdown and set it to "accepted names". If it is now
// unchecked, then restore the previous dropdown value.
if ( changed == 'accepted' )
{
if ( accepted_box.checked )
{
taxon_status_save = status_selector.value;
status_selector.value = "accepted";
variant_box.checked = false;
}
else
{
status_selector.value = taxon_status_save;
}
}
// If the 'status_selector' dropdown is set to anything but "accepted", or if
// 'variant_box' is checked, then uncheck 'accepted_box'.
else if ( changed == 'selector' )
{
taxon_status_save = status_selector.value;
if ( status_selector.value != "accepted" )
accepted_box.checked = false;
}
else
{
if ( variant_box.checked )
accepted_box.checked = false;
}
updateFormState();
}
this.checkTaxonStatus = checkTaxonStatus;
// This function is called when any of the taxon modifier options are changed.
function checkTaxonMods ( )
{
var idqual = getElementValue("pm_idqual");
if ( idqual == 'any' )
{
params.idqual = '';
params.idgenmod = '';
params.idspcmod = '';
hideByClass('taxon_mods');
}
else if ( idqual == 'custom' )
{
params.idqual = '';
showByClass('taxon_mods');
checkTaxonCustom();
}
else
{
params.idqual = idqual;
params.idgenmod = '';
params.idspcmod = '';
hideByClass('taxon_mods');
}
updateFormState();
}
this.checkTaxonMods = checkTaxonMods;
function checkTaxonCustom ( )
{
var idgenmod = getCheckList("pm_idgenmod");
var idspcmod = getCheckList("pm_idspcmod");
var gen_ex = getElementValue("pm_genmod_ex");
var spc_ex = getElementValue("pm_spcmod_ex");
if ( gen_ex && gen_ex == "exclude" && idgenmod )
idgenmod = "!" + idgenmod;
if ( spc_ex && spc_ex == "exclude" && idspcmod )
idspcmod = "!" + idspcmod;
params.idgenmod = idgenmod;
params.idspcmod = idspcmod;
}
// This function is called when any of the abundance options is changed.
function checkAbund ( )
{
var abund_type = getElementValue("pm_abund_type");
var abund_min = getElementValue("pm_abund_min");
var abund_value = '';
if ( abund_type && abund_type != 'none' )
{
abund_value = abund_type;
if ( abund_min && abund_min != '' )
{
if ( patt_int_pos.test(abund_min) )
{
abund_value += ':' + abund_min;
setErrorMessage("pe_abund_min", "");
param_errors.abundance = 0;
}
else
{
setErrorMessage("pe_abund_min", "Minimum abundance must be a positive integer");
param_errors.abundance = 1;
}
}
params.abundance = abund_value;
}
else
{
params.abundance = "";
}
if ( abund_min == "" )
{
setErrorMessage("pe_abund_min", "");
param_errors.abundance = 0;
}
updateFormState();
}
this.checkAbund = checkAbund;
// This function is called when either of the main text fields in the "Select by time" section
// are modified. The values might either be interval names or millions of years. It is also
// called when the value of "pm_timerule" or "pm_timebuffer" changes. The parameter 'select'
// will be 1 if the first text field was changed, 2 if the second.
function checkInterval ( select )
{
var int_age_1 = getElementValue("pm_interval");
var int_age_2 = getElementValue("pm_interval_2");
var errors = [ ];
params.timerule = getElementValue("pm_timerule");
params.timebuffer = getElementValue("pm_timebuffer");
// First check the value of the first text field. If it is empty, then clear both of the
// corresponding parameter properties.
if ( int_age_1 == "" )
{
params.interval = "";
params.ma_max = "";
}
else
{
// If it is a number, then set the property 'ma_max' and clear 'interval'. If the
// other text field contains an interval name, clear it.
if ( patt_dec_pos.test(int_age_1) )
{
params.ma_max = int_age_1;
params.interval = "";
if ( select && select == 1 && !patt_has_digit.test(int_age_2) )
{
clearElementValue("pm_interval_2");
int_age_2 = "";
}
}
// If it contains a digit but is not a number, then the value is invalid.
else if ( patt_has_digit.test(int_age_1) )
errors.push("The string '" + int_age_1 + "' is not a valid age or interval");
// If it is the name of a known geologic time interval, then set the property
// 'interval' and clear 'ma_max'. If the other text field contains a number, then
// clear it.
else if ( validInterval(int_age_1) )
{
params.ma_max = "";
params.interval = int_age_1;
if ( select && select == 1 && patt_has_digit.test(int_age_2) )
{
clearElementValue("pm_interval_2");
int_age_2 = "";
}
}
// Otherwise, the value is not valid.
else
errors.push("The interval '" + int_age_1 + "' was not found in the database");
}
// Repeat this process for the second text field.
if ( int_age_2 == "" )
{
params.interval2 = "";
params.ma_min = "";
}
else
{
if ( patt_dec_pos.test(int_age_2) )
{
params.ma_min = int_age_2;
params.interval2 = "";
if ( select && select == 2 && !patt_has_digit.test(int_age_1) )
{
clearElementValue("pm_interval");
params.ma_max = "";
params.interval = "";
}
}
else if ( patt_has_digit.test(int_age_2) )
errors.push("The string '" + int_age_2 + "' is not a valid age or interval");
else if ( validInterval(int_age_2) )
{
params.ma_min = "";
params.interval2 = int_age_2;
if ( select && select == 2 && patt_has_digit.test(int_age_1) )
{
clearElementValue("pm_interval");
params.ma_max = "";
params.interval = "";
}
}
else
errors.push("The interval '" + int_age_2 + "' was not found in the database");
}
// If the text field values are numbers, check to make sure they were not entered in the
// wrong order.
if ( params.ma_max && params.ma_min && Number(params.ma_max) < Number(params.ma_min) )
{
errors.push("You must specify the maximum age on the left and the minimum on the right");
}
// If the 'timebuffer' field is visible and has a value, check to make sure that it is a number.
if ( visible.advanced )
{
if ( params.timerule == 'buffer' && params.timebuffer != "" && ! patt_dec_pos.test(params.timebuffer) )
errors.push("invalid value '" + params.timebuffer + "' for timebuffer");
}
// If we have discovered any errors so far, display them and set the appropriate property
// of the 'param_errors' javascript object.
if ( errors.length )
{
param_errors.interval = 1;
setErrorMessage("pe_interval", errors);
}
// Otherwise, clear them both.
else
{
param_errors.interval = 0;
setErrorMessage("pe_interval", "");
}
// Adjust visibility of controls
if ( params.timerule == 'buffer' )
showByClass('buffer_rule');
else
hideByClass('buffer_rule');
// Update the form state
updateFormState();
}
this.checkInterval = checkInterval;
// Check whether the specified interval name is registered as a property of the javascript
// object 'api_data.interval', disregarding case.
function validInterval ( interval_name )
{
if ( typeof interval_name != "string" )
return false;
if ( api_data.interval[interval_name.toLowerCase()] )
return true;
else
return false;
}
// This function is called when any of the fields in the "Select by location" section other
// than the paleocoordinate selectors are modified.
function checkCC ( )
{
// Get the value of the dropdown menus for selecting continents and countries. If the
// value of either is '**', then show the full set of checkboxes for continents and the
// "multiple countries" text field for countries.
var continent_select = getElementValue("pm_continent");
if ( continent_select == '**' ) showByClass('mult_cc3');
else hideByClass('mult_cc3');
var country_select = getElementValue("pm_country");
// multiple_div = document.getElementById("pd_countries");
if ( country_select == '**' ) showByClass('mult_cc2');
else hideByClass('mult_cc2');
var continent_list = '';
var country_list = '';
var errors = [ ];
var cc_ex = getElementValue("pm_ccex");
var cc_mod = getElementValue("pm_ccmod");
// Get the selected continent or continents, if any
if ( continent_select && continent_select != '--' && continent_select != '**' )
continent_list = continent_select;
else if ( continent_select && continent_select == '**' )
{
continent_list = getCheckList("pm_continents");
}
// Get the selected country or countries, if any. If the user selected "minus" for the
// value of pm_ccmod, then put a ^ before each country code.
if ( country_select && country_select != '--' && country_select != '**' )
{
country_list = country_select;
if ( cc_mod == "sub" ) country_list = '^' + country_list;
}
// If the user selected "Multiple", then look at the value of the "multiple countries"
// text field. Split this into words, ignoring commas, spaces, and ^, and check to make
// sure that each word is a valid country code.
else if ( country_select && country_select == '**' )
{
country_list = getElementValue("pm_countries");
if ( country_list != '' )
{
var cc_list = [ ];
var values = country_list.split(/[\s,^]+/);
for ( var i=0; i < values.length; i++ )
{
var canonical = values[i].toUpperCase();
// var key = canonical.replace(/^\^/,'');
// if ( key == '' ) next;
// if ( cc_mod == "sub" ) canonical = "^" + canonical;
if ( api_data.country_name[canonical] )
{
if ( cc_mod == "sub" ) cc_list.push("^" + canonical);
else cc_list.push(canonical);
}
else
errors.push("Unknown country code '" + canonical + "'");
}
country_list = cc_list.join(',');
}
}
params.cc = '';
// If we have found a valid list of continents and/or a valid list of countries, set
// the "cc" property of the javascript object 'params' to the entire list. Add a prefix
// of "!" if the user selected "exclude" instead of "include".
if ( country_list != '' || continent_list != '' )
{
var prefix = '';
if ( cc_ex == "exclude" ) prefix = '!';
if ( continent_list != '' && country_list != '' )
params.cc = prefix + continent_list + ',' + country_list;
else
params.cc = prefix + continent_list + country_list;
}
// If we have detected any errors, display them and set the 'cc' property of the 'param_errors'
// object. Otherwise, clear the error indicator and property.
if ( errors.length )
{
setErrorMessage("pe_cc", errors);
param_errors.cc = 1;
}
else
{
setErrorMessage("pe_cc", "");
param_errors.cc = 0;
}
// Check to see if the user specified any states or counties. If so, add the appropriate parameters.
var state_list = getElementValue("pm_state");
var county_list = getElementValue("pm_county");
var state_ex = getElementValue("pm_state_ex");
var county_ex = getElementValue("pm_county_ex");
var state_errors = [ ];
params.state = '';
params.county = '';
if ( state_list != '' )
{
var prefix = '';
if ( state_ex == 'exclude' ) prefix = '!';
params.state = prefix + state_list.trim();
if ( ! params.cc )
{
state_errors.push("You must select a country.");
}
}
if ( county_list != '' )
{
var prefix = '';
if ( county_ex == 'exclude' ) prefix = '!';
params.county = prefix + county_list.trim();
if ( ! params.cc )
{
state_errors.push("You must select a country.");
}
if ( ! params.state )
{
state_errors.push("You must select a state.");
}
}
if ( state_errors.length )
{
setErrorMessage("pe_state", state_errors);
param_errors.state = 1;
}
else
{
setErrorMessage("pe_state", "");
param_errors.state = 0;
}
updateFormState();
}
this.checkCC = checkCC;
// This function is called whenever any of the paleocoordinate selectors in the Location
// section is modified.
function checkPGM ( )
{
// Check to see if the user specified any tectonic plates. If so, validate the list and
// adjust the objects 'params' and 'param_errors' accordingly.
var plate_list = getElementValue("pm_plate");
var errors = [ ];
if ( plate_list != '' )
{
var values = plate_list.split(/[\s,]+/);
var value_list = [ ];
for ( var i=0; i < values.length; i++ )
{
var value = values[i];
if ( value == '' ) next;
if ( /^[0-9]+$/.test(value) )
value_list.push(value);
else
errors.push("Invalid plate number '" + value + "'");
}
if ( value_list.length )
params.plate = value_list.join(',');
else
params.plate = '';
}
else
params.plate = '';
params.pg_model = getElementValue("pm_pg_model");
params.pg_select = getElementValue("pm_pg_select");
// If a comparison model was selected, override the parameters set immediately above.
var alt_model = getElementValue("pm_pg_compare");
if ( alt_model == 'all' )
params.pg_model = api_data.pg_models.join(',');
else if ( alt_model )
params.pg_model = params.pg_model + ',' + alt_model;
var alt_select = getElementValue("pm_pg_selcomp");
if ( alt_select == 'all' )
params.pg_select = 'early,mid,late';
else if ( alt_select )
params.pg_select = params.pg_select + ',' + alt_select;
// If we discovered any errors, display them. Otherwise, clear any messages that were
// there before.
if ( errors.length )
{
setErrorMessage("pe_plate", errors);
param_errors.plate = 1;
}
else
{
setErrorMessage("pe_plate", "");
param_errors.plate = 0;
}
updateFormState();
}
this.checkPGM = checkPGM;
// This function is called when any of the latitude/longitude fields are modified.
function checkCoords ( )
{
var latmin = getElementValue('pm_latmin');
var latmax = getElementValue('pm_latmax');
var lngmin = getElementValue('pm_lngmin');
var lngmax = getElementValue('pm_lngmax');
var errors = [];
// Check for valid values in the coordinate fields
if ( latmin == '' || validCoord(latmin, 'ns') ) params.latmin = cleanCoord(latmin);
else {
params.latmin = '';
errors.push("invalid value '" + latmin + "' for minimum latitude");
}
if ( latmax == '' || validCoord(latmax, 'ns') ) params.latmax = cleanCoord(latmax);
else {
params.latmax = '';
errors.push("invalid value '" + latmax + "' for maximum latitude");
}
if ( lngmin == '' || validCoord(lngmin, 'ew') ) params.lngmin = cleanCoord(lngmin);
else {
params.lngmin = '';
errors.push("invalid value '" + lngmin + "' for minimum longitude");
}
if ( lngmax == '' || validCoord(lngmax, 'ew') ) params.lngmax = cleanCoord(lngmax);
else {
params.lngmax = '';
errors.push("invalid value '" + lngmax + "' for maximum longitude");
}
// If only one longitude coordinate is filled in, ignore the other one.
if ( lngmin && ! lngmax || lngmax && ! lngmin )
{
errors.push("you must specify both longitude values if you specify one of them");
}
// If any of the parameters are in error, display the message and flag the error condition.
if ( errors.length )
{
setErrorMessage('pe_coords', errors);
param_errors.coords = 1;
}
else
{
// If the longitude coordinates are reversed, note that fact.
if ( params.lngmin != '' && params.lngmax != '' &&
coordsAreReversed(params.lngmin, params.lngmax) )
{
message = [ "Note: the longitude coordinates are reversed. " +
"This will select a strip stretching the long way around the earth." ]
setErrorMessage('pe_coords', message );
}
else setErrorMessage('pe_coords', null);
// Clear the error flag in any case.
param_errors.coords = 0;
}
// Update the main URL to reflect the changed coordinates.
updateFormState();
}
this.checkCoords = checkCoords;
// Check whether the given value is a valid coordinate. The parameter 'dir' must be one of
// 'ns' or 'ew', specifying which direction suffixes will be accepted.
function validCoord ( coord, dir )
{
if ( coord == undefined )
return false;
if ( patt_dec_num.test(coord) )
return true;
if ( dir == 'ns' && /^(\d+[.]\d*|\d*[.]\d+|\d+)[ns]$/i.test(coord) )
return true;
if ( dir === 'ew' && /^(\d+[.]\d*|\d*[.]\d+|\d+)[ew]$/i.test(coord) )
return true;
return false;
}
// Remove directional suffix, if any, and change to a signed number.
function cleanCoord ( coord )
{
if ( coord == undefined || coord == '' )
return '';
if ( /^[+-]?(\d+[.]\d*|\d*[.]\d+|\d+)$/.test(coord) )
return coord;
if ( /^(\d+[.]\d*|\d*[.]\d+|\d+)[sw]$/i.test(coord) )
return '-' + coord.replace(/[nsew]/i, '');
else
return coord.replace(/[nsew]/i, '');
}
// Return true if the given longitude values specify a region stretching more than 180 degrees
// around the earth.
function coordsAreReversed ( min, max )
{
// First convert the coordinates into signed integers.
var imin = Number(min);
var imax = Number(max);
return ( imax - imin > 180 || ( imax - imin < 0 && imax - imin > -180 ));
}
// This function is called when the geological strata input field from "Select by geological
// context" is modified.
function checkStrat ( )
{
var strat = getElementValue("pm_strat");
// If the value contains at least one letter, try to look it up using the API.
if ( strat && /[a-z]/i.test(strat) )
{
params.strat = strat;
$.getJSON(data_url + 'strata/list.json?limit=0&rowcount&name=' + strat).done(callbackStrat);
}
// Otherwise, clear any error messages that may have been displayed previously and clear
// the parameter value.
else
{
params.strat = "";
param_errors.strat = 0;
setErrorMessage("pe_strat", "");
updateFormState();
}
}
this.checkStrat = checkStrat;
// This function is called when the API request to look up strata names returns. If any
// records are returned, assume that at least some of the names are okay. We currently have
// no way to determine which names match known strata and which do not, which is an
// unfortunate limitation.
function callbackStrat ( response )
{
if ( response.records_found )
{
setErrorMessage("pe_strat", null);
param_errors.strat = 0;
}
else
{
setErrorMessage("pe_strat", [ "no matching strata were found in the database" ]);
param_errors.strat = 1;
}
updateFormState();
}
// This function is called when any of the Lithology form elements in the "select by
// geological context" section are modified.
function checkLith ( )
{
var lith_ex = getElementValue("pm_lithex");
var lith_type = getCheckList("pm_lithtype");
if ( lith_ex && lith_ex == "exclude" && lith_type && lith_type != "" )
lith_type = "!" + lith_type;
params.lithtype = lith_type;
updateFormState();
}
this.checkLith = checkLith;
// This function is called when any of the Environment form elements in the "Select by
// geological context" section are modified.
function checkEnv ( )
{
var env_ex = getElementValue("pm_envex");
var env_mod = getElementValue("pm_envmod");
var env_type = getCheckList("pm_envtype");
var env_zone = getCheckList("pm_envzone");
if ( env_ex && env_ex == "exclude" && env_type && env_type != "" )
env_type = "!" + env_type;
if ( env_mod && env_mod == "sub" )
env_zone = "^" + env_zone.replace(/,/g, ',^');
if ( env_zone )
env_type += ',' + env_zone;
params.envtype = env_type;
updateFormState();
}
this.checkEnv = checkEnv;
// This function is called whenever the "created after" or "authorized/entered by" form
// elements in the "Select by metadata" section are modified, or when the corresponding text
// fields are modified. The parameter 'section' indicates which row was modified, because
// there may be more than one depending upon the data type currently selected.
function checkMeta ( section )
{
var errors = [];
// The value of the "..._cmdate" field must match the pattern 'patt_date'.
var crmod_value = getElementValue("pm_" + section + "_crmod");
var cmdate_value = getElementValue("pm_" + section + "_cmdate");
var datetype = section + "_crmod";
var datefield = section + "_cmdate";
if ( cmdate_value && cmdate_value != '' )
{
params[datetype] = crmod_value;
params[datefield] = cmdate_value;
if ( ! patt_date.test(cmdate_value) )
{
param_errors[datefield] = 1;
errors.push("Bad value '" + cmdate_value + "'");
}
else
{
param_errors[datefield] = 0;
}
}
else
{
params[datetype] = crmod_value;
params[datefield] = "";
param_errors[datefield] = 0;
}
// Now we check the value of the "..._aename" field.
var authent_value = getElementValue("pm_" + section + "_authent");
var aename_value = getElementValue("pm_" + section + "_aename").trim();
var nametype = section + "_authent";
var namefield = section + "_aename";
var rebuild = [ ];
var exclude = '';
if ( aename_value && aename_value != '' )
{
param_errors[namefield] = 0;
// If the value starts with !, we have an exclusion. Pull it
// out and save for the end when we are rebuilding the value
// string.
var expr = aename_value.match(/^!\s*(.*)/);
if ( expr )
{
aename_value = expr[1];
exclude = '!';
}
// Split the field value on commas, and check each individual name.
var names = aename_value.split(/,\s*/);
for ( var i = 0; i < names.length; i++ )
{
// Skip empty names, i.e. repeated commas.
if ( ! names[i] ) continue;
// If we cannot find the name, then search through all of
// the known names to try for a match.
if ( ! api_data.valid_name[names[i]] )
{
var check = names[i].toLowerCase().trim();
var init = '';
var subs;
if ( subs = names[i].match(/^(\w)\w*[.]\s*(.*)/) )
{
init = subs[1].toLowerCase();
check = subs[2].toLowerCase();
}
var matches = [];
for ( var j = 0; j < api_data.user_match.length; j++ )
{
if ( check == api_data.user_match[j].substr(0,check.length) )
{
if ( init == '' || init == api_data.user_matchinit[j] )
matches.push(j);
}
}
if ( matches.length == 0 )
{
param_errors[namefield] = 1;
errors.push("Unknown name '" + names[i] + "'");
rebuild.push(names[i]);
}
else if ( matches.length > 1 )
{
param_errors[namefield] = 1;
var result = api_data.user_names[matches[0]];
for ( var k = 1; k < matches.length; k++ )
{
result = result + ", " + api_data.user_names[matches[k]];
}
errors.push("Ambiguous name '" + names[i] + "' matches: " + result);
rebuild.push(names[i]);
}
else
{
rebuild.push(api_data.user_names[matches[0]]);
}
}
else
{
rebuild.push(names[i]);
}
}
params[nametype] = authent_value;
params[namefield] = exclude + rebuild.join(',');
aename_value = exclude + rebuild.join(', ');
}
else
{
params[nametype] = authent_value;
params[namefield] = "";
param_errors[namefield] = 0;
}
// If we detected any errors, display them. Otherwise, clear any errors that were
// displayed previously.
if ( errors.length ) setErrorMessage("pe_meta_" + section, errors);
else setErrorMessage("pe_meta_" + section, "");
updateFormState();
}
this.checkMeta = checkMeta;
// This function is called when one of the free-text fields (currently only 'pm_coll_re') in
// the "Select by metadata" section is modified. It simply stores the value in the
// corresponding property of the 'params' object if it is not empty.
function checkMetaText ( elt_name )
{
var elt_value = getElementValue( 'pm_' + elt_name );
if ( elt_value && elt_value != '' )
params[elt_name] = elt_value;
else
{
params[elt_name] = '';
param_errors[elt_name] = 0;
}
updateFormState();
}
this.checkMetaText = checkMetaText;
// This function is called when one of the fields 'pm_meta_id_list' or 'pm_meta_id_select' is
// modified. The parameter 'selector' indicates which one. The former of the two fields is
// expected to hold one or more PBDB object identifiers, either numeric or extended.
function checkMetaId ( selector )
{
var id_list = getElementValue( 'pm_meta_id_list' );
var id_type = getElementValue( 'pm_meta_id_select' );
var id_param = id_param_map[id_type];
if ( id_type == '' )
{
params["meta_id_list"] = '';
param_errors["meta_id"] = 0;
setErrorMessage("pe_meta_id", "");
}
else
{
// Split the list on commas/whitespace.
var id_strings = id_list.split(/[\s,]+/);
var id_key = { };
var key_list = [ ];
var param_list = [ ];
var errors = [ ];
// Check each identifier individually.
for ( var i=0; i < id_strings.length; i++ )
{
// If it is an extended identifier, keep track of all the different
// three-character prefixes we encounter while traversing the list using the
// object 'id_key' and array 'key_list'.
if ( patt_extid.test( id_strings[i] ) )
{
param_list.push(id_strings[i]);
var key = id_strings[i].substr(0,3);
if ( ! id_key[key] )
{
key_list.push(key);
id_key[key] = 1;
}
}
// If it is a numeric identifier, just add it to the parameter list.
else if ( patt_int_pos.test( id_strings[i] ) )
{
param_list.push(id_strings[i]);
}
// Anything else is an error.
else if ( id_strings[i] != '' )
{
errors.push("invalid identifier '" + id_strings[i] + '"');
}
}
// If we found more than one different identifier prefix, that is an error.
if ( key_list.length > 1 )
{
errors.push("You may not specify identifiers of different types");
}
// If we found any errors, display them.
if ( errors.length )
{
params["meta_id_list"] = '';
param_errors["meta_id"] = 1;
setErrorMessage("pe_meta_id", errors);
}
// Otherwise, construct the proper parameter value by joining all of the identifiers
// we found.
else
{
params["meta_id_list"] = param_list.join(',');
// If we found an extended-identifier prefix, then set the "select" element to the
// corresponding item.
if ( key_list.length == 1 )
{
id_param = id_param_map[key_list[0]];
var select_index = id_param_index[key_list[0]];
var select_elt = myGetElement("pm_meta_id_select");
if ( select_elt )
{
select_elt.selectedIndex = select_index;
}
}
// The variable 'id_param' was set from the selection dropdown, at the top of this
// function. It indicates which parameter name to use, as a function of the
// selected identifier type. For example, if the user selected "Occurrence" or at
// least one of the identifiers started with "occ:", then the parameter name would
// be "occ_id".
if ( id_param )
{
params["meta_id_param"] = id_param;
param_errors["meta_id"] = 0;
setErrorMessage("pe_meta_id", "");
}
// If for some reason we haven't found a proper parameter name, then display an
// error message.
else
{
params["meta_id_param"] = '';
param_errors["meta_id"] = 1;
setErrorMessage("pe_meta_id", ["Unknown identifier type '" + id_param + "'"]);
}
}
}
updateFormState();
}
this.checkMetaId = checkMetaId;
// This function is called when either the 'pm_ref_select' dropdown menu or the value of the
// 'pm_ref_value' field is changed.
function checkRef ( )
{
var ref_select = getElementValue( 'pm_ref_select' );
var ref_value = getElementValue( 'pm_ref_value' );
// If the dropdown menu selection is 'ref_id', then we expect one or more identifiers as a
// comma-separated list.
if ( ref_select && ref_select == "ref_id" )
{
// Split the list on commas/whitespace.
var id_strings = ref_value.split(/[\s,]+/);
var param_list = [ ];
var errors = [ ];
// Check each identifier individually.
for ( var i=0; i < id_strings.length; i++ )
{
// If it is an extended identifier, keep track of all the different
// three-character prefixes we encounter while traversing the list using the
// object 'id_key' and array 'key_list'.
if ( /^ref[:]\d+$/.test( id_strings[i] ) )
{
param_list.push(id_strings[i]);
}
// If it is a numeric identifier, just add it to the parameter list.
else if ( patt_int_pos.test( id_strings[i] ) )
{
param_list.push('ref:' + id_strings[i]);
}
// Anything else is an error.
else if ( id_strings[i] != '' )
{
errors.push("invalid reference identifier '" + id_strings[i] + '"');
}
}
// If we found any errors, display them.
if ( errors.length )
{
params["meta_ref_value"] = '';
params["meta_ref_select"] = '';
param_errors["meta_ref"] = 1;
setErrorMessage("pe_meta_ref", errors);
}
// Otherwise, construct the proper parameter value by joining all of the identifiers
// we found.
else
{
if ( param_list.length )
{
params["meta_ref_value"] = param_list.join(',');
params["meta_ref_select"] = 'ref_id';
}
else
{
params["meta_ref_value"] = '';
params["meta_ref_select"] = '';
}
setErrorMessage("pe_meta_ref", "");
param_errors["meta_ref"] = 0;
}
}
else if ( ref_select && ref_param[ref_select] )
{
if ( ref_value != undefined && ref_value != '' )
{
params["meta_ref_value"] = ref_value;
params["meta_ref_select"] = ref_select;
}
else
{
params["meta_ref_value"] = '';
params["meta_ref_select"] = '';
}
param_errors["meta_ref"] = 0;
setErrorMessage("pe_meta_ref", '');
}
else
{
params["meta_ref_select"] = '';
params["meta_ref_value"] = '';
param_errors["meta_ref"] = 0;
setErrorMessage("pe_meta_ref", "");
}
updateFormState();
// var ref_select = myGetElement("pm_ref_select");
// if ( ref_select )
// {
// var selected = ref_select.value;
// }
}
this.checkRef = checkRef;
// This function is called when the "include metadata" checkbox in the "Choose output options"
// section is modified.
function checkOutputOpts ( )
{
var metadata_elt = myGetElement("pm_output_metadata");
params.output_metadata = metadata_elt.checked;
updateFormState();
}
this.checkOutputOpts = checkOutputOpts;
// This function is called when one of the "Output order" dropdowns in the "Choose output
// options" section is modified. The 'selection' parameter indicates which one. I'm not
// actually sure this does anything useful at this point.
function checkOrder ( selection )
{
if ( selection && selection != 'dir' )
{
var order_elt = myGetElement("pm_order_dir");
if ( order_elt ) order_elt.value = '--';
}
updateFormState();
}
this.checkOrder = checkOrder;
// This function is called if the "include all boldfaced output blocks" element in the "Output
// options" section is modified.
function checkFullOutput ( )
{
var full_value = getElementValue("pm_fulloutput");
var elts = document.getElementsByName(output_section);
var i;
full_checked[output_section] = full_value;
for ( i=0; i<elts.length; i++ )
{
var block_code = elts[i].value;
if ( output_full[output_section][block_code] )
{
if ( full_value ) elts[i].checked = 1;
else elts[i].checked = 0;
}
}
updateFormState();
}
this.checkFullOutput = checkFullOutput;
// This function is called if the "reference types" checkboxes are modified. These are only
// visible for certain record types.
function checkRefopts ( )
{
params.reftypes = getCheckList("pm_reftypes");
if ( params.reftypes == "auth,class" ) params.reftypes = 'taxonomy';
else if ( params.reftypes == "auth,class,ops" ) params.reftypes = 'auth,ops';
else if ( params.reftypes == "auth,class,ops,occs,colls" ) params.reftypes = 'all'
else if ( params.reftypes == "auth,ops,occs,colls" ) params.reftypes = 'all'
updateFormState();
}
this.checkRefopts = checkRefopts;
// This function is called when the "Limit number of records" field in the "Choose output
// options" section is modified.
function checkLimit ( )
{
var limit = getElementValue("pm_limit");
if ( limit == "" )
{
param_errors.limit = 0;
params.offset = '';
params.limit = '';
setErrorMessage("pe_limit", "");
updateFormState();
return;
}
// The value can either be one number, or two separated by commas. In the second case,
// the first will be taken as an offset and the second as a limit.
var matches = limit.match(/^\s*(\d+)(\s*,\s*(\d+))?\s*$/);
if ( matches )
{
param_errors.limit = 0;
setErrorMessage("pe_limit", "");
if ( matches[3] )
{
params.offset = matches[1];
params.limit = matches[3];
}
else
{
params.offset = '';
params.limit = matches[1];
}
}
else
{
param_errors.limit = 1;
params.offset = 'x';
params.limit = 'x';
setErrorMessage("pe_limit", ["Invalid limit '" + limit + "'"]);
}
updateFormState();
}
this.checkLimit = checkLimit;
// This function is called if the "Archive title" field is modified, or if the archive section
// is hidden or shown.
function checkArchive ( )
{
var title = getElementValue("arc_title");
var btn = myGetElement("btn_download");
if ( title && visible.o2 )
{
btn.textContent = "Create Archive";
btn.onclick = archiveMainURL;
}
else
{
btn.textContent = "Download";
btn.onclick = downloadMainURL;
}
}
this.checkArchive = checkArchive;
// This function is called whenever some element changes that could change the overall state
// of the application. The only thing it currently does is to update the main URL, but other
// things could be added later.
function updateFormState ( )
{
if ( ! no_update ) updateMainURL();
}
this.updateFormState = updateFormState;
// The following function provides the core functionality for this application. It is called
// whenever any form element changes, and updates the "main URL" element to reflect the
// changes. This main URL can then be used to download data.
// Many of the form elements are not queried directly. Rather, the properties of the
// javascript object 'parameters' are updated whenever any of these elements change value, and
// these properties are used in the function below to generate the URL. The properties of the
// object 'param_errors' are used to indicate whether any errors were found when the values
// were checked. Only elements requiring no interpretation or checking are queried directly.
// Only the form elements in visible sections are used. Any section that is collapsed (not
// visible) is ignored. However, if it is opened again then this function will be immediately
// called and the values entered there will be applied to the main URL. The properties of the
// javascript object 'visible' keep track of what is visible and what is hidden.
function updateMainURL ( )
{
// The following variable keeps track of the parameters and values that make up the URL.
var param_list = [ ];
// The following variable will be set to true if a "significant parameter" is specified.
// Otherwise, the main URL will not be generated. Such parameters include the taxonomic
// name, time interval, stratum, etc. In other words, some parameter that will
// substantially restrict the result set. The "select all records" checkbox also counts,
// just in case somebody really wants to download all records of a particular type.
var has_main_param = 0;
// The following variable will be set to true if any errors are encountered in association
// with a visible form element. This will prevent the main URL from being generated.
var errors_found = 0;
// The following variables indicate that an occurrence operation or a taxon operation must
// be generated instead of the default operation for the selected record type.
var occs_required = 0;
var taxon_required = 0;
// The following variable indicates that an operation that takes reference parameters must
// be generated instead of the default operation for the selected record type.
var refs_required = 0;
// The following variable indicates that we should use the 'refs/list' operation instead
// of 'taxa/refs'.
var use_ref_list = 0;
// The following variable is set to true if certain form elements are filled in, to
// indicate that the "all_records" parameter must be added in order to satisfy the
// requirements of the API.
var all_required = 0;
// If true, the parameter "pgm" has already been added to the list.
var need_pgm = 0;
// The following variable indicates the API operation (i.e. "occs/list", "taxa/list",
// etc.) to be used. It is set from the default operation for the selected record type,
// but may be modified under certain circumstances.
var my_op = data_op;
// If the "Select by taxonomy" section is visible, then go through the parameters it
// contains. If the "advanced" parameters are visible, then check them too.
if ( visible.f1 )
{
if ( params.base_name && params.base_name != "" ) {
param_list.push("base_name=" + params.base_name);
has_main_param = 1;
taxon_required = 1;
}
if ( param_errors.base_name ) errors_found = 1;
if ( data_type == "occs" || data_type == "specs" || data_type == "meas" ||
data_type == "colls" || data_type == "strata" || data_type == "diversity" )
{
// The "taxonomic resolution" parameter is different for diversity than for the
// other data types.
if ( data_type == "diversity" )
{
var taxonres = getElementValue("pm_div_count");
if ( taxonres && taxonres != "" )
param_list.push("count=" + taxonres);
}
else
{
var taxonres = getElementValue("pm_taxon_reso");
if ( taxonres && taxonres != "" )
param_list.push("taxon_reso=" + taxonres);
}
// The advanced parameters are treated the same for all of these types.
if ( visible.advanced )
{
if ( params.ident && params.ident != 'latest' )
param_list.push("ident=" + params.ident);
if ( params.idqual )
param_list.push("idqual=" + params.idqual);
if ( params.idgenmod || params.idspcmod )
{
if ( params.idgenmod == params.idspcmod )
param_list.push("idmod=" + params.idgenmod);
else
{
if ( params.idgenmod )
param_list.push("idgenmod=" + params.idgenmod);
if ( params.idspcmod )
param_list.push("idspcmod=" + params.idspcmod);
}
}
}
}
else if ( data_type == "taxa" || data_type == "ops" || data_type == "refs" )
{
var taxon_rank = getElementValue("pm_taxon_rank");
if ( taxon_rank && taxon_rank != '--' )
param_list.push("rank=" + taxon_rank);
var taxon_status = getElementValue("pm_taxon_status");
if ( taxon_status )
param_list.push("taxon_status=" + taxon_status);
var taxon_variants = getElementValue("pm_taxon_variants");
if ( visible.advanced && taxon_variants )
param_list.push("variant=all");
}
if ( visible.advanced && params.pres && params.pres != 'all' )
param_list.push("pres=" + params.pres);
}
// If the "Select by time" section is visible, then go through the parameters it
// contains. If the "advanced" parameters are visible, then check them too.
if ( visible.f2 )
{
var intervals = [ ];
var has_time_param;
if ( params.interval && params.interval != "" )
intervals.push(params.interval);
if ( params.interval2 && params.interval2 != "" )
intervals.push(params.interval2);
if ( intervals.length )
{
param_list.push("interval=" + intervals.join(','));
has_main_param = 1;
has_time_param = 1;
occs_required = 1;
}
else
{
if ( params.ma_max )
{
param_list.push("max_ma=" + params.ma_max);
has_main_param = 1;
has_time_param = 1;
occs_required = 1;
}
if ( params.ma_min )
{
param_list.push("min_ma=" + params.ma_min);
has_main_param = 1;
has_time_param = 1;
occs_required = 1;
}
}
if ( param_errors.interval ) errors_found = 1;
if ( data_type == 'diversity' )
{
has_time_param = 1;
var timeres = getElementValue("pm_div_time");
if ( timeres && timeres != "stage" )
param_list.push("time_reso=" + timeres);
var recent = getElementValue("pm_div_recent");
if ( recent )
param_list.push("recent");
}
if ( visible.advanced ) {
if ( params.timerule && params.timerule != 'major' && has_time_param ) {
param_list.push("time_rule=" + params.timerule);
if ( params.timebuffer && params.timerule == 'buffer' )
param_list.push("time_buffer=" + params.timebuffer);
}
}
}
// If the section "Select by location" is visible, then go through the parameters it
// contains. If the "advanced" parameters are visible, then check them too.
if ( visible.f3 )
{
if ( params.cc && params.cc != "" )
{
param_list.push("cc=" + params.cc);
occs_required = 1;
has_main_param = 1;
}
if ( params.state && params.state != "" )
{
param_list.push("state=" + params.state);
occs_required = 1;
has_main_param = 1;
}
if ( params.county && params.county != "" )
{
param_list.push("county=" + params.county);
occs_required = 1;
has_main_param = 1;
}
if ( visible.advanced && params.plate && params.plate != "" )
{
param_list.push("plate=" + params.plate);
occs_required = 1;
has_main_param = 1;
need_pgm = 1;
}
if ( visible.advanced && (param_errors.cc || param_errors.state || param_errors.plate) )
errors_found = 1;
if ( params.latmin || params.latmax || params.lngmin || params.lngmax )
{
if ( params.lngmin ) param_list.push("lngmin=" + params.lngmin);
if ( params.lngmax ) param_list.push("lngmax=" + params.lngmax);
if ( params.latmin ) param_list.push("latmin=" + params.latmin);
if ( params.latmax ) param_list.push("latmax=" + params.latmax);
occs_required = 1;
has_main_param = 1;
}
if ( param_errors.coords ) errors_found = 1;
}
// If the section "Select by geological context" is visible, then go through the
// parameters it contains. If the "advanced" parameters are visible, then check them too.
if ( visible.f4 )
{
if ( params.strat && params.strat != "" ) {
param_list.push("strat=" + params.strat);
occs_required = 1;
has_main_param = 1
}
if ( param_errors.strat ) errors_found = 1;
if ( visible.advanced && params.lithtype && params.lithtype != "" ) {
param_list.push("lithology=" + params.lithtype);
occs_required = 1;
}
if ( visible.advanced && params.envtype && params.envtype != "" ) {
param_list.push("envtype=" + params.envtype);
occs_required = 1;
}
}
// If the section "Select by specimen is visible, then go through the parameters it contains.
if ( visible.f6 )
{
if ( params.abundance )
{
if ( param_errors.abundance ) errors_found = 1;
param_list.push("abundance=" + params.abundance );
occs_required = 1;
}
}
// If the section "Select by metadata" is visible, then go through the parameters it
// contains. Only some of the rows will be visible, depending on the selected record type.
if ( visible.f5 )
{
if ( params.coll_re ) {
param_list.push("coll_re=" + params.coll_re);
occs_required = 1;
has_main_param = 1;
}
if ( param_errors.coll_re ) errors_found = 1;
if ( params.meta_id_list ) {
param_list.push(params.meta_id_param + "=" + params.meta_id_list);
occs_required = 1;
has_main_param = 1;
}
if ( param_errors.meta_id ) errors_found = 1;
if ( params.meta_ref_select ) {
if ( param_list.length == 0 ) use_ref_list = 1;
param_list.push(params.meta_ref_select + '=' + params.meta_ref_value);
refs_required = 1;
has_main_param = 1;
}
if ( param_errors.meta_ref ) errors_found = 1;
if ( visible.meta_specs )
{
if ( params.specs_cmdate ) {
param_list.push("specs_" + params.specs_crmod + "=" + params.specs_cmdate);
occs_required = 1;
all_required = 1;
}
if ( params.specs_aename ) {
param_list.push("specs_" + params.specs_authent + "=" + params.specs_aename);
occs_required = 1
all_required = 1;
}
if ( param_errors.specs_cmdate || param_errors.specs_aename ) errors_found = 1;
}
if ( visible.meta_occs )
{
if ( params.occs_cmdate ) {
param_list.push("occs_" + params.occs_crmod + "=" + params.occs_cmdate);
occs_required = 1;
all_required = 1;
}
if ( params.occs_aename ) {
param_list.push("occs_" + params.occs_authent + "=" + params.occs_aename);
occs_required = 1
all_required = 1;
}
if ( param_errors.occs_cmdate || param_errors.occs_aename ) errors_found = 1;
}
if ( visible.meta_colls )
{
if ( params.colls_cmdate ) {
param_list.push("colls_" + params.colls_crmod + "=" + params.colls_cmdate);
all_required = 1;
}
if ( params.colls_aename ) {
param_list.push("colls_" + params.colls_authent + "=" + params.colls_aename);
all_required = 1;
}
if ( param_errors.colls_cmdate || param_errors.colls_aename ) errors_found = 1;
}
if ( visible.meta_taxa )
{
if ( params.taxa_cmdate ) {
param_list.push("taxa_" + params.taxa_crmod + "=" + params.taxa_cmdate);
all_required = 1;
}
if ( params.taxa_aename ) {
param_list.push("taxa_" + params.taxa_authent + "=" + params.taxa_aename);
all_required = 1;
}
if ( param_errors.taxa_cmdate || param_errors.taxa_aename ) errors_found = 1;
}
if ( visible.meta_ops )
{
if ( params.ops_cmdate ) {
param_list.push("ops_" + params.ops_crmod + "=" + params.ops_cmdate);
all_required = 1;
}
if ( params.ops_aename ) {
param_list.push("ops_" + params.ops_authent + "=" + params.ops_aename);
all_required = 1;
}
if ( param_errors.ops_cmdate || param_errors.ops_aename ) errors_found = 1;
}
if ( visible.meta_refs )
{
if ( params.refs_cmdate ) {
param_list.push("refs_" + params.refs_crmod + "=" + params.refs_cmdate);
all_required = 1;
}
if ( params.refs_aename ) {
param_list.push("refs_" + params.refs_authent + "=" + params.refs_aename);
all_required = 1;
}
if ( param_errors.refs_cmdate || param_errors.refs_aename ) errors_found = 1;
}
}
// If the selected record type is either references or taxa selected by reference or
// opinions, then add the appropriate parameter using the form element that appears just
// above the"Select by taxonomy" section.
if ( data_type == 'refs' || data_type == 'byref' )
{
if ( params.reftypes && params.reftypes != "" && ! use_ref_list ) {
param_list.push("select=" + params.reftypes);
}
}
else if ( data_type == "ops" )
{
var op_select = getElementValue("pm_op_select");
if ( op_select )
param_list.push("op_type=" + op_select);
}
// If "include non-public data" is selected, add the parameter 'private'.
if ( params.private && is_contributor )
{
param_list.push("private");
}
// If the section "output options" is visible, then go through the parameters it contains.
// This includes specifying which output blocks to return using the "show" parameter.
if ( visible.o1 )
{
var output_list = getOutputList();
if ( paleoloc_all || paleoloc_selected )
{
need_pgm = 0;
if ( paleoloc_all )
param_list.push("pgm=" + api_data.pg_models.join(','));
else
param_list.push("pgm=" + params.pg_model);
if ( params.pg_select != "mid" )
param_list.push("pgs=" + params.pg_select);
}
if ( ! occs_required )
output_list = output_list.replace(/occapp,?/, 'app,');
if ( output_list ) param_list.push("show=" + output_list);
var order_expr = getElementValue(output_order);
var order_dir = getElementValue("pm_order_dir");
if ( order_expr && order_expr != '--' )
{
if ( order_expr == 'authpub' )
{
if ( order_dir && order_dir == 'asc' )
param_list.push("order=author,pubyr.asc");
else
param_list.push("order=author,pubyr.desc");
}
else if ( order_expr == 'pubauth' )
{
if ( order_dir && order_dir == 'asc' )
param_list.push("order=pubyr.asc,author");
else
param_list.push("order=pubyr.desc,author");
}
else
{
if ( order_dir && order_dir != '--' )
order_expr = order_expr + '.' + order_dir;
param_list.push("order=" + order_expr);
}
}
if ( params.offset ) param_list.push("offset=" + params.offset);
if ( params.limit ) param_list.push("limit=" + params.limit);
if ( param_errors.limit ) errors_found = 1;
}
// Otherwise, add "show=acconly" if indicated by the "accepted names only" checkbox
// in the "Select by taxonomy" section.
else if ( (data_type == 'occs' || data_type == 'specs' ) && visible.f1)
{
var acc_only = myGetElement("pm_acc_only");
if ( acc_only && acc_only.checked )
param_list.push('show=acconly');
}
// If we still need a "pgm=" parameter, add it now.
if ( need_pgm )
param_list.push("pgm=" + params.pg_model);
// Now alter the operation, if necessary, based on the chosen parameters
if ( occs_required )
{
if ( my_op == 'taxa/list' ) my_op = 'occs/taxa';
else if ( my_op == 'taxa/refs' ) my_op = 'occs/refs';
else if ( my_op == 'taxa/byref' ) my_op = 'occs/taxabyref';
else if ( my_op == 'opinions/list' ) my_op = 'occs/opinions';
}
else if ( taxon_required )
{
if ( my_op == 'opinions/list' ) my_op = 'taxa/opinions';
}
if ( refs_required )
{
if ( my_op == 'occs/list' ) { my_op = 'occs/byref'; all_required = 1; }
else if ( my_op == 'colls/list' ) { my_op = 'colls/byref'; all_required = 1; }
else if ( my_op == 'taxa/list' ) my_op = 'taxa/byref';
else if ( my_op == 'occs/taxa' ) { my_op = 'occs/taxabyref'; all_required = 1; }
else if ( my_op == 'opinions/list' ) { my_op = 'taxa/opinions'; all_required = 1; }
else if ( my_op == 'specs/list' ) { my_op = 'specs/byref'; all_required = 1; }
else if ( my_op == 'strata/list' ) { my_op = 'occs/strata'; all_required = 1; }
else if ( my_op == 'taxa/refs' && use_ref_list ) my_op = 'refs/list';
}
// If no "significant" parameter has been entered, then see if we need to add the
// parameter 'all_records' in order to satisfy the requirements of the API.
if ( all_required || ! has_main_param )
{
var all_records_elt = myGetElement("pm_all_records");
// If 'all_required' is true, then add the parameter. This flag will be true if
// certain of the fields in the "Metadata" section are filled in.
if ( all_required )
{
param_list.push('all_records');
has_main_param = 1;
}
// Do the same if the "select all records" box is checked. In this case,
// Set the 'confirm_download' flag so that a confirmation dialog box will
// be generated before a download is initiated.
else if ( all_records_elt && all_records_elt.checked )
{
param_list.push('all_records');
has_main_param = 1;
confirm_download = 1;
}
}
// Now, if any errors were found, or if no "significant" parameter was entered,
// then display a message for the user.
var url_elt = document.getElementById('mainURL');
if ( errors_found )
{
url_elt.textContent = "Fix the parameter errors below to generate a download URL";
url_elt.href = "";
}
else if ( ! has_main_param )
{
url_elt.textContent = "Enter one or more parameters below to generate a download URL";
url_elt.href = "";
}
// Otherwise, generate the URL and display it.
else
{
var param_string = param_list.join('&');
// Construct the new URL
var new_url = full_data_url + my_op + data_format + '?';
download_path = short_data_url + my_op + data_format;
download_params = '';
if ( params.output_metadata )
download_params = 'datainfo&rowcount&';
download_params += param_string;
new_url += download_params;
url_elt.textContent = new_url;
url_elt.href = new_url;
}
// Adjust metadata subsections according to the selected operation.
url_op = my_op;
// switch ( my_op )
// {
// case 'specs/list':
// selectMetaSub('pd_meta_specs');
// // showElement('pd_meta_occs');
// // showElement('pd_meta_colls');
// case 'occs/list':
// case 'occs/diversity':
// case 'occs/taxa':
// case 'occs/strata':
// selectMetaSub('pd_meta_occs');
// showElement('pd_meta_colls');
// break;
// case 'colls/list':
// selectMetaSub('pd_meta_colls');
// showElement('pd_meta_occs');
// break;
// case 'taxa/list':
// selectMetaSub('pd_meta_taxa');
// break;
// case 'opinions/list':
// selectMetaSub('pd_meta_ops');
// break;
// case 'taxa/opinions':
// selectMetaSub('pd_meta_ops');
// showElement('pd_meta_taxa');
// break;
// case 'refs/list':
// selectMetaSub('pd_meta_refs');
// break;
// case 'occs/refs':
// case 'occs/taxabyref':
// selectMetaSub('pd_meta_occs');
// showElement('pd_meta_refs');
// break;
// case 'taxa/refs':
// case 'taxa/byref':
// selectMetaSub('pd_meta_taxa' );
// showElement('pd_meta_refs');
// break;
// }
}
// Make the named section visible, and hide the others.
function selectMetaSub ( subsection )
{
var subs = { pd_meta_occs: 1, pd_meta_colls: 1, pd_meta_taxa: 1,
pd_meta_ops: 1, pd_meta_refs: 1, pd_meta_specs: 1 };
var s;
for ( s in subs )
{
if ( s == subsection )
{
showElement(s);
visible[s] = 1;
}
else
{
hideElement(s);
visible[s] = 0;
}
}
}
// Return a list of the values that should be passed to the parameter 'show' in order to get
// the output blocks selected on this form. If the checkbox 'pm_acc_only' in the Taxonomy
// section is checked, add 'acconly' to the list.
function getOutputList ( )
{
var elts = document.getElementsByName(output_section);
var full_value = getElementValue("pm_fulloutput");
var i;
var selected = [];
if ( full_value )
selected.push('full');
for ( i=0; i<elts.length; i++ )
{
var value = elts[i].value;
if ( value == "paleoloc" )
{
paleoloc_all = elts[i].checked;
}
else if ( value == "paleoloc2" )
{
paleoloc_selected = elts[i].checked;
value = "paleoloc";
if ( paleoloc_all && paleoloc_selected ) continue;
}
if ( elts[i].checked )
{
if ( ! ( full_value && output_full[output_section][value] ) )
selected.push(value);
}
}
if ( visible.f1 && (data_type == 'occs' || data_type == 'specs'))
{
var acc_only = myGetElement("pm_acc_only");
if ( acc_only && acc_only.checked )
selected.push('acconly');
}
return selected.join(',');
}
// Show or hide the "advanced" form elements.
function setFormMode ( mode )
{
if ( mode == "advanced" )
{
form_mode = "advanced";
showByClass('advanced');
}
else
{
form_mode = "simple";
hideByClass('advanced');
}
updateFormState();
}
this.setFormMode = setFormMode;
// Set or clear the "include non-public data" parameter.
function setPrivate ( flag )
{
if ( flag && flag != "0" )
params.private = 1;
else
params.private = 0;
updateFormState();
}
// Set it to false by default when the App is loaded.
this.setPrivate = setPrivate;
// Select the indicated record type. This specifies the type of record that will be returned
// when a download is initiated. Depending upon the record type, various sections of the form
// will be shown or hidden.
function setRecordType ( type )
{
data_type = type;
var record_label;
var type_sections = [ 'type_occs', 'type_colls', 'type_specs', 'type_strata',
'type_diversity', 'type_taxa', 'taxon_reso', 'taxon_range', 'div_reso',
'type_ops', 'type_refs', 'acc_only', 'meta_specs', 'meta_occs',
'meta_colls', 'meta_taxa', 'meta_ops', 'meta_refs' ];
var show_sections = { };
if ( type == 'occs' )
{
data_op = 'occs/list';
output_section = 'od_occs';
output_order = 'pm_occs_order';
record_label = 'occurrence records';
show_sections = { type_occs: 1, taxon_reso: 1, acc_only: 1, meta_occs: 1,
meta_colls: 1 };
}
else if ( type == 'colls' )
{
data_op = 'colls/list';
output_section = 'od_colls';
output_order = 'pm_colls_order';
record_label = 'collection records';
show_sections = { type_colls: 1, taxon_reso: 1, meta_occs: 1, meta_colls: 1 };
}
else if ( type == 'specs' )
{
data_op = 'specs/list';
output_section = 'od_specs';
output_order = 'pm_occs_order';
record_label = 'specimen records';
show_sections = { type_specs: 1, taxon_reso: 1, acc_only: 1, meta_occs: 1,
meta_specs: 1 };
}
else if ( type == 'meas' )
{
data_op = 'specs/measurements';
output_section = 'od_meas';
output_order = 'pm_occs_order';
record_label = 'measurement records';
show_sections = { type_meas: 1, taxon_reso: 1, meta_occs: 1,
meta_specs: 1 };
}
else if ( type == 'strata' )
{
data_op = 'occs/strata';
output_section = 'od_strata';
output_order = 'pm_strata_order';
record_label = 'stratum records';
show_sections = { type_strata: 1, taxon_reso: 1, meta_occs: 1, meta_colls: 1 };
}
else if ( type == 'diversity' )
{
showHideSection('f2', 'show');
data_op = 'occs/diversity';
output_section = 'od_diversity';
output_order = 'none';
record_label = 'occurrence records';
show_sections = { type_diversity: 1, div_reso: 1, meta_occs: 1 };
}
else if ( type == 'taxa' )
{
data_op = 'taxa/list';
output_section = 'od_taxa';
output_order = 'pm_taxa_order';
record_label = 'taxonomic name records';
show_sections = { type_taxa: 1, taxon_range : 1, acc_only: 1, meta_taxa: 1,
meta_occs: 1 };
}
else if ( type == 'ops' )
{
data_op = 'opinions/list';
output_section = 'od_ops';
output_order = 'pm_ops_order';
record_label = 'taxonomic opinion records';
show_sections = { type_ops: 1, taxon_range: 1, acc_only: 1, meta_taxa: 1,
meta_ops: 1, meta_occs: 1 };
}
else if ( type == 'refs' )
{
data_op = 'taxa/refs';
output_section = 'od_refs';
output_order = 'pm_refs_order';
record_label = 'bibliographic reference records';
show_sections = { type_refs: 1, taxon_range: 1, acc_only: 1, meta_taxa: 1,
meta_occs: 1, meta_refs: 1 };
}
else if ( type == 'byref' )
{
data_op = 'taxa/byref';
output_section = 'od_taxa';
output_order = 'pm_refs_order';
record_label = 'taxonomic name records';
show_sections = { type_refs: 1, taxon_range: 1, acc_only: 1, meta_taxa: 1, meta_refs: 1 };
}
else
{
alert("Error! (" + type + ")");
output_section = 'none';
output_order = 'none';
}
// Set the "include all output blocks" form element according to the saved value.
var full_elt = myGetElement("pm_fulloutput");
if ( full_checked[output_section] ) full_elt.checked = 1;
else full_elt.checked = 0;
// Show the proper form division(s) for this type, and hide the others.
var i;
for ( i=0; i < type_sections.length; i++ )
{
var name = type_sections[i];
if ( show_sections[name] )
showByClass(name);
else
hideByClass(name);
}
// Show the proper output control for this type, and hide the others.
var sections = document.getElementsByClassName("dlOutputSection");
for ( i=0; i < sections.length; i++ )
{
if ( sections[i].id == output_section )
sections[i].style.display = '';
else
sections[i].style.display = 'none';
}
sections = document.getElementsByClassName("dlOutputOrder");
for ( i=0; i < sections.length; i++ )
{
if ( sections[i].id == output_order )
sections[i].style.display = '';
else
sections[i].style.display = 'none';
}
// Set the label on "select all records"
try
{
setInnerHTML("label_all_records", record_label);
}
finally {};
// Show and hide various other controls based on type
try
{
if ( type == 'refs' )
{
setDisabled("rb.ris", 0);
if ( ref_format ) document.getElementById("rb"+ref_format).click();
}
else
{
setDisabled("rb.ris", 1);
if ( data_format == '.ris' ) document.getElementById("rb"+non_ref_format).click();
}
} finally {};
// showElement('pd_meta_coll_re');
// Then store the new type, and update the main URL
updateFormState();
}
this.setRecordType = setRecordType;
// Select the indicated output format. This is the format in which the downloaded
// data will be expressed.
function setFormat ( type )
{
data_format = '.' + type;
if ( data_type != 'refs' && type != 'ris' ) non_ref_format = data_format;
else if ( data_type == 'refs' ) ref_format = data_format;
updateFormState();
}
this.setFormat = setFormat;
// This function is called when the "Test" button is activated. Unless a record limit is
// specified, a limit of 100 will be added. Also, the output format ".csv" will be changed to
// ".txt", which will (in most browsers) cause the result to be displayed in the browser
// window rather than saved to disk.
function testMainURL ( )
{
var url = document.getElementById("mainURL").textContent;
if ( ! url.match(/http/i) ) return;
if ( data_format == '.csv' ) url = url.replace('.csv','.txt');
else url += '&textresult';
if ( ! params.limit && url_op != 'occs/diversity' ) url += '&limit=100';
window.open(url);
}
this.testMainURL = testMainURL;
// This function is called when the "Download" button is activated. If the 'confirm_download'
// flag is true, generate a dialog box before initiating the download.
function downloadMainURL ( )
{
var url = document.getElementById("mainURL").textContent;
if ( ! url.match(/http/i) ) return;
if ( confirm_download )
{
if ( ! confirm("You are about to initiate a download that might exceed 100 MB. Continue?") )
return;
}
window.open(url);
}
this.downloadMainURL = downloadMainURL;
// This function is called when the "Archive" button is activated. This button takes the
// place of the "Download" button when the archive options section is visible and the archive
// title is not empty. If the 'confirm_download' flag is true, generate a dialog box before
// initiating the download.
function archiveMainURL ( )
{
var url = document.getElementById("mainURL").textContent;
if ( ! url.match(/http/i) ) return;
if ( params.private )
{
alert("You must choose the 'Public data only' option in order to create a publicly available archive");
return;
}
if ( confirm_download )
{
if ( ! confirm("You are about to archive a dataset that might exceed 100 MB. Continue?") )
return;
}
// Use jQuery to initiate the archive creation process.
var archive_title = getElementValue('arc_title');
var archive_authors = getElementValue('arc_authors');
var archive_desc = getElementValue('arc_desc');
if ( ! archive_title ) return;
var archive_url = url + '&archive_title=' + encodeURIComponent(archive_title);
if ( archive_authors )
archive_url += '&archive_authors=' + encodeURIComponent(archive_authors);
if ( archive_desc )
archive_url += '&archive_desc=' + encodeURIComponent(archive_desc);
// $.getJSON(...)
// var archive_params = JSON.stringify({
// uri_path: download_path,
// uri_args: download_params,
// title: getElementValue('arc_title'),
// authors: getElementValue('arc_authors'),
// description: getElementValue('arc_desc') });
function onArchiveError(xhr, textStatus, error)
{
var label = xhr.status || error;
if ( xhr.status == '400' )
{
if ( /E_IMMUTABLE/.test(xhr.responseText) )
{
window.alert('You already have an immutable archive with this title.');
}
else if ( /E_EXISTING/.test(xhr.responseText) )
{
var proceed = window.confirm('You have an existing archive with that title. ' +
'Replace its contents?');
if ( proceed )
{
var replace_url = archive_url + '&archive_replace=yes';
requestArchive( replace_url, onArchiveError);
}
}
else
{
window.alert('Request failed due to a parameter error.');
console.log("Error '" + label + "' creating archive:\n" + xhr.responseText);
}
}
else
{
window.alert('Request failed due to a server error.');
console.log("Error '" + label + "' creating archive:\n" + xhr.responseText);
}
}
requestArchive( archive_url, onArchiveError );
}
this.archiveMainURL = archiveMainURL;
function requestArchive ( request_url, error_function )
{
$.ajax({ url: request_url,
type: 'GET',
async: false,
success: function(data) {
var match = /^Created.*dar:(\d+)/.exec(data);
if ( match && match[1] )
{
window.open("/classic/app/archive/edit?id=" + match[1], "_self");
}
else
{
window.alert("Bad response from server");
}
},
error: error_function
});
}
} | [
"function DownloadController(url, form) {\n //build variables\n DownloadController.prototype.frameName = 'downloadFrame';\n DownloadController.prototype.DOWNLOADFLAG = \"DOWNLOADFLAG=true\";\n\n //define function to get Frame document object\n // if needCreate = true, it will be created if not exists\n DownloadController.prototype.getFrameDoc = function (needCreate) {\n //build html iframe\n var $iframe, iframe_doc;\n //create iframe if not exists\n if (($iframe = $('#' + this.frameName)).length === 0) {\n if (!needCreate) return null;//don't need to create, so no doc found\n\n $iframe = $(\"<iframe id='\" + this.frameName + \"' style='display: none' src='about:blank'></iframe>\")\n .appendTo(\"body\");\n }\n //get document of iframe\n iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;\n if (iframe_doc.document) {\n iframe_doc = iframe_doc.document;\n }\n return iframe_doc;\n\n };\n //define call back function of downloading\n DownloadController.prototype.downloadTimerFunc = function () {\n var cookie = getCookie(\"DownloadID\");\n if (cookie != undefined && DownloadController.prototype.downloadCheckTimer != undefined)//cookie found\n {\n clearInterval(DownloadController.prototype.downloadCheckTimer);\n enableAllButtons();\n hideLoading();\n //check return value\n var iframeDoc = DownloadController.prototype.getFrameDoc(false);\n if (null != iframeDoc) {\n var newUrl = new String(iframeDoc.URL);\n if (newUrl.indexOf(DownloadController.prototype.DOWNLOADFLAG) > 0) {\n //html return, so flush current page with returned HTML\n document.body.innerHTML = iframeDoc.body.innerHTML;\n }\n }\n }\n return;\n };\n //init members\n //downloadByIFrame(url, data);\n this.downloadByIFrame = function () {\n //start to build object to get all elements data\n//\t\tvar data = new Object();\n var formletsHTML = \"\";\n if (null != form) {\n for (var iPtr = 0; iPtr < form.elements.length; iPtr++) {\n var eleType = form.elements[iPtr].getAttribute(\"type\");\n if (eleType != \"file\")//ignore file input\n {\n//\t\t\t\t\tdata[form.elements[iPtr].name] = form.elements[iPtr].value;\n if (eleType == \"radio\" || eleType == \"checkbox\") {\n if (!form.elements[iPtr].checked)//for checkbox or radio button, only add checked items\n continue;\n }\n var eleVals = $(form.elements[iPtr]).val();\n if (null == eleVals)\n eleVals = \"\";\n if (!$.isArray(eleVals))//convert it an array for one element\n eleVals = [eleVals];\n for (var iVal = 0; iVal < eleVals.length; iVal++) {\n var val = eleVals[iVal];\n if (val)\n val = val.replace(/'/g, ''');\n formletsHTML += \"<input type='hidden' name='\" + form.elements[iPtr].name + \"' value='\" + val + \"'>\";\n }\n }\n }\n }\n //disable all buttons\n disableAllButtons();\n showLoading();//show loading div\n //build html iframe\n var iframe_doc, iframe_html;\n //get document of iframe\n iframe_doc = this.getFrameDoc(true);\n //append a flag after url\n if (url.indexOf(\"?\") > 0)\n url = url + \"&\";\n else\n url = url + \"?\";\n url = url + DownloadController.prototype.DOWNLOADFLAG;\n\n //build iframe html\n iframe_html = \"<html><head></head><body><form method='POST' action='\" + url + \"'>\" +\n formletsHTML +\n \"</form></body></html>\";\n //iframe_doc.open();\n //iframe_doc.write(iframe_html);\n $(iframe_doc.body).html(iframe_html);\n $(iframe_doc).find('form').submit();\n\n //set timer to check status by cookie\n removeCookie(\"DownloadID\");\n DownloadController.prototype.downloadCheckTimer = setInterval('DownloadController.prototype.downloadTimerFunc();', 1000);\n };\n}",
"function DownloadPublished(el_input) {\n console.log( \" ==== DownloadPublished ====\");\n const tblRow = t_get_tablerow_selected(el_input);\n const pk_int = get_attr_from_el_int(tblRow, \"data-pk\");\n\n const data_dict = get_mapdict_from_datamap_by_id(published_map, tblRow.id);\n const filepath = data_dict.filepath\n const filename = data_dict.filename\n console.log( \"filepath\", filepath);\n console.log( \"filename\", filename);\n\n // window.open = '/ticket?orderId=' + pk_int;\n\n // UploadChanges(upload_dict, urls.url_download_published);\n const upload_dict = { published_pk: pk_int};\n if(!isEmpty(upload_dict)) {\n const parameters = {\"upload\": JSON.stringify (upload_dict)}\n let response = \"\";\n $.ajax({\n type: \"POST\",\n url: urls.url_download_published,\n data: parameters,\n dataType:'json',\n success: function (response) {\n var a = document.createElement('a');\n var url = window.URL.createObjectURL(response);\n a.href = url;\n a.download = 'myfile.pdf';\n document.body.append(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n },\n\n\n /*\n success: function (data) {\n //const a = document.createElement('a');\n //const url = window.URL.createObjectURL(data);\n console.log( \"data\");\n console.log( data);\n /*\n a.href = url;\n a.download = 'myfile.pdf';\n document.body.append(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n */\n /*\n var blob = new Blob(data, { type: 'application/pdf' });\n var a = document.createElement('a');\n a.href = window.URL.createObjectURL(blob);\n a.download = filename;\n a.click();\n window.URL.revokeObjectURL(url);\n\n },\n*/\n\n error: function (xhr, msg) {\n // --- hide loader\n el_loader.classList.add(cls_visible_hide)\n console.log(msg + '\\n' + xhr.responseText);\n } // error: function (xhr, msg) {\n }); // $.ajax({\n } // if(!!row_upload)\n\n\n\n\n\n // PR2021-03-06 from https://stackoverflow.com/questions/1999607/download-and-open-pdf-file-using-ajax\n //$.ajax({\n // url: urls.url_download_published,\n // success: download.bind(true, \"<FILENAME_TO_SAVE_WITH_EXTENSION>\", \"application/pdf\")\n // });\n\n //PR2021-03-07 from https://codepen.io/chrisdpratt/pen/RKxJNo\n //This one works, the demo does at least\n /*\n $.ajax({\n url: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/172905/test.pdf',\n method: 'GET',\n xhrFields: {\n responseType: 'blob'\n },\n success: function (data) {\n var a = document.createElement('a');\n var url = window.URL.createObjectURL(data);\n a.href = url;\n a.download = 'myfile.pdf';\n document.body.append(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n }\n });\n */\n\n }",
"function updateMainURL ( )\n {\n\t// The following variable keeps track of the parameters and values that make up the URL.\n\t\n\tvar param_list = [ ];\n\t\n\t// The following variable will be set to true if a \"significant parameter\" is specified.\n\t// Otherwise, the main URL will not be generated. Such parameters include the taxonomic\n\t// name, time interval, stratum, etc. In other words, some parameter that will\n\t// substantially restrict the result set. The \"select all records\" checkbox also counts,\n\t// just in case somebody really wants to download all records of a particular type.\n\t\n\tvar has_main_param = 0;\n\n\t// The following variable will be set to true if any errors are encountered in association\n\t// with a visible form element. This will prevent the main URL from being generated.\n\t\n\tvar errors_found = 0;\n\n\t// The following variables indicate that an occurrence operation or a taxon operation must\n\t// be generated instead of the default operation for the selected record type.\n\t\n\tvar occs_required = 0;\n\tvar taxon_required = 0;\n\t\n\t// The following variable indicates that an operation that takes reference parameters must\n\t// be generated instead of the default operation for the selected record type.\n\t\n\tvar refs_required = 0;\n\n\t// The following variable indicates that we should use the 'refs/list' operation instead\n\t// of 'taxa/refs'.\n\t\n\tvar use_ref_list = 0;\n\t\n\t// The following variable is set to true if certain form elements are filled in, to\n\t// indicate that the \"all_records\" parameter must be added in order to satisfy the\n\t// requirements of the API.\n\t\n\tvar all_required = 0;\n\t\n\t// If true, the parameter \"pgm\" has already been added to the list.\n\t\n\tvar need_pgm = 0;\n\t\n\t// The following variable indicates the API operation (i.e. \"occs/list\", \"taxa/list\",\n\t// etc.) to be used. It is set from the default operation for the selected record type,\n\t// but may be modified under certain circumstances.\n\t\n\tvar my_op = data_op;\n\t\n\t// If the \"Select by taxonomy\" section is visible, then go through the parameters it\n\t// contains. If the \"advanced\" parameters are visible, then check them too.\n\t\n\tif ( visible.f1 )\n\t{\n\t if ( params.base_name && params.base_name != \"\" ) {\n\t\tparam_list.push(\"base_name=\" + params.base_name);\n\t\thas_main_param = 1;\n\t\ttaxon_required = 1;\n\t }\n\t \n\t if ( param_errors.base_name ) errors_found = 1;\n\t \n\t if ( data_type == \"occs\" || data_type == \"specs\" || data_type == \"meas\" ||\n\t\t data_type == \"colls\" || data_type == \"strata\" || data_type == \"diversity\" )\n\t {\n\t\t// The \"taxonomic resolution\" parameter is different for diversity than for the\n\t\t// other data types.\n\t\t\n\t\tif ( data_type == \"diversity\" )\n\t\t{\n\t \t var taxonres = getElementValue(\"pm_div_count\");\n\t \t if ( taxonres && taxonres != \"\" )\n\t \t\tparam_list.push(\"count=\" + taxonres);\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t var taxonres = getElementValue(\"pm_taxon_reso\");\n\t\t if ( taxonres && taxonres != \"\" )\n\t\t\tparam_list.push(\"taxon_reso=\" + taxonres);\n\t\t}\n\t\t\n\t\t// The advanced parameters are treated the same for all of these types.\n\t\t\n\t\tif ( visible.advanced )\n\t\t{\n\t\t if ( params.ident && params.ident != 'latest' )\n\t\t\tparam_list.push(\"ident=\" + params.ident);\n\t\t \n\t\t if ( params.idqual )\n\t\t\tparam_list.push(\"idqual=\" + params.idqual);\n\t\t \n\t\t if ( params.idgenmod || params.idspcmod )\n\t\t {\n\t\t\tif ( params.idgenmod == params.idspcmod )\n\t\t\t param_list.push(\"idmod=\" + params.idgenmod);\n\t\t\t\n\t\t\telse\n\t\t\t{\n\t\t\t if ( params.idgenmod )\n\t\t\t\tparam_list.push(\"idgenmod=\" + params.idgenmod);\n\t\t\t \n\t\t\t if ( params.idspcmod )\n\t\t\t\tparam_list.push(\"idspcmod=\" + params.idspcmod);\n\t\t\t}\t\t\t\n\t\t }\n\t\t}\n\t }\n\t \n\t else if ( data_type == \"taxa\" || data_type == \"ops\" || data_type == \"refs\" )\n\t {\n\t\tvar taxon_rank = getElementValue(\"pm_taxon_rank\");\n\t\t\n\t\tif ( taxon_rank && taxon_rank != '--' )\n\t\t param_list.push(\"rank=\" + taxon_rank);\n\t\t\n\t\tvar taxon_status = getElementValue(\"pm_taxon_status\");\n\t\t\n\t\tif ( taxon_status )\n\t\t param_list.push(\"taxon_status=\" + taxon_status);\n\t\t\n\t\tvar taxon_variants = getElementValue(\"pm_taxon_variants\");\n\t\t\n\t\tif ( visible.advanced && taxon_variants )\n\t\t param_list.push(\"variant=all\");\n\t }\n\t \n\t if ( visible.advanced && params.pres && params.pres != 'all' )\n\t\tparam_list.push(\"pres=\" + params.pres);\n\t}\n\t\n\t// If the \"Select by time\" section is visible, then go through the parameters it\n\t// contains. If the \"advanced\" parameters are visible, then check them too.\n\t\n\tif ( visible.f2 )\n\t{\n\t var intervals = [ ];\n\t var has_time_param;\n\t \n\t if ( params.interval && params.interval != \"\" )\n\t\tintervals.push(params.interval);\n\t if ( params.interval2 && params.interval2 != \"\" )\n\t\tintervals.push(params.interval2);\n\t \n\t if ( intervals.length )\n\t {\n\t\tparam_list.push(\"interval=\" + intervals.join(','));\n\t\thas_main_param = 1;\n\t\thas_time_param = 1;\n\t\toccs_required = 1;\n\t }\n\t \n\t else\n\t {\n\t\tif ( params.ma_max )\n\t\t{\n\t\t param_list.push(\"max_ma=\" + params.ma_max);\n\t\t has_main_param = 1;\n\t\t has_time_param = 1;\n\t\t occs_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.ma_min )\n\t\t{\n\t\t param_list.push(\"min_ma=\" + params.ma_min);\n\t\t has_main_param = 1;\n\t\t has_time_param = 1;\n\t\t occs_required = 1;\n\t\t}\n\t }\n\t \n\t if ( param_errors.interval ) errors_found = 1;\n\t \n\t if ( data_type == 'diversity' )\n\t {\n\t\thas_time_param = 1;\n\t\t\n\t\tvar timeres = getElementValue(\"pm_div_time\");\n\t\t\n\t\tif ( timeres && timeres != \"stage\" )\n\t\t param_list.push(\"time_reso=\" + timeres);\n\t\t\n\t\tvar recent = getElementValue(\"pm_div_recent\");\n\t\tif ( recent )\n\t\t param_list.push(\"recent\");\n\t }\n\t \n\t if ( visible.advanced ) {\n\t\tif ( params.timerule && params.timerule != 'major' && has_time_param ) {\n\t\t param_list.push(\"time_rule=\" + params.timerule);\n\t\t if ( params.timebuffer && params.timerule == 'buffer' )\n\t\t\tparam_list.push(\"time_buffer=\" + params.timebuffer);\n\t\t}\n\t }\n\t}\n\n\t// If the section \"Select by location\" is visible, then go through the parameters it\n\t// contains. If the \"advanced\" parameters are visible, then check them too.\n\t\n\tif ( visible.f3 )\n\t{\n\t if ( params.cc && params.cc != \"\" )\n\t {\n\t\tparam_list.push(\"cc=\" + params.cc);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\n\t if ( params.state && params.state != \"\" )\n\t {\n\t\tparam_list.push(\"state=\" + params.state);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\n\t if ( params.county && params.county != \"\" )\n\t {\n\t\tparam_list.push(\"county=\" + params.county);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( visible.advanced && params.plate && params.plate != \"\" )\n\t {\n\t\tparam_list.push(\"plate=\" + params.plate);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t\tneed_pgm = 1;\n\t }\n\t \n\t if ( visible.advanced && (param_errors.cc || param_errors.state || param_errors.plate) )\n\t\terrors_found = 1;\n\t \n\t if ( params.latmin || params.latmax || params.lngmin || params.lngmax )\n\t {\n\t\tif ( params.lngmin ) param_list.push(\"lngmin=\" + params.lngmin);\n\t\tif ( params.lngmax ) param_list.push(\"lngmax=\" + params.lngmax);\n\t\tif ( params.latmin ) param_list.push(\"latmin=\" + params.latmin);\n\t\tif ( params.latmax ) param_list.push(\"latmax=\" + params.latmax);\n\t\t\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( param_errors.coords ) errors_found = 1;\n\t}\n\t\n\t// If the section \"Select by geological context\" is visible, then go through the\n\t// parameters it contains. If the \"advanced\" parameters are visible, then check them too.\n\t\n\tif ( visible.f4 )\n\t{\n\t if ( params.strat && params.strat != \"\" ) {\n\t\tparam_list.push(\"strat=\" + params.strat);\n\t\toccs_required = 1;\n\t\thas_main_param = 1\n\t }\n\t \n\t if ( param_errors.strat ) errors_found = 1;\n\t \n\t if ( visible.advanced && params.lithtype && params.lithtype != \"\" ) {\n\t\tparam_list.push(\"lithology=\" + params.lithtype);\n\t\toccs_required = 1;\n\t }\n\t \n\t if ( visible.advanced && params.envtype && params.envtype != \"\" ) {\n\t\tparam_list.push(\"envtype=\" + params.envtype);\n\t\toccs_required = 1;\n\t }\n\t}\n\t\n\t// If the section \"Select by specimen is visible, then go through the parameters it contains.\n\t\n\tif ( visible.f6 )\n\t{\n\t if ( params.abundance )\n\t {\n\t\tif ( param_errors.abundance ) errors_found = 1;\n\t\tparam_list.push(\"abundance=\" + params.abundance );\n\t\toccs_required = 1;\n\t }\n\t}\n\t\n\t// If the section \"Select by metadata\" is visible, then go through the parameters it\n\t// contains. Only some of the rows will be visible, depending on the selected record type.\n\t\n\tif ( visible.f5 )\n\t{\n\t if ( params.coll_re ) {\n\t\tparam_list.push(\"coll_re=\" + params.coll_re);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( param_errors.coll_re ) errors_found = 1;\n\t \n\t if ( params.meta_id_list ) {\n\t\tparam_list.push(params.meta_id_param + \"=\" + params.meta_id_list);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( param_errors.meta_id ) errors_found = 1;\n\t \n\t if ( params.meta_ref_select ) {\n\t\tif ( param_list.length == 0 ) use_ref_list = 1;\n\t\tparam_list.push(params.meta_ref_select + '=' + params.meta_ref_value);\n\t\trefs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( param_errors.meta_ref ) errors_found = 1;\n\t \n\t if ( visible.meta_specs )\n\t {\n\t\tif ( params.specs_cmdate ) {\n\t\t param_list.push(\"specs_\" + params.specs_crmod + \"=\" + params.specs_cmdate);\n\t\t occs_required = 1;\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.specs_aename ) {\n\t\t param_list.push(\"specs_\" + params.specs_authent + \"=\" + params.specs_aename);\n\t\t occs_required = 1\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.specs_cmdate || param_errors.specs_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_occs )\n\t {\n\t\tif ( params.occs_cmdate ) {\n\t\t param_list.push(\"occs_\" + params.occs_crmod + \"=\" + params.occs_cmdate);\n\t\t occs_required = 1;\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.occs_aename ) {\n\t\t param_list.push(\"occs_\" + params.occs_authent + \"=\" + params.occs_aename);\n\t\t occs_required = 1\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.occs_cmdate || param_errors.occs_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_colls )\n\t {\n\t\tif ( params.colls_cmdate ) {\n\t\t param_list.push(\"colls_\" + params.colls_crmod + \"=\" + params.colls_cmdate);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.colls_aename ) {\n\t\t param_list.push(\"colls_\" + params.colls_authent + \"=\" + params.colls_aename);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.colls_cmdate || param_errors.colls_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_taxa )\n\t {\n\t\tif ( params.taxa_cmdate ) {\n\t\t param_list.push(\"taxa_\" + params.taxa_crmod + \"=\" + params.taxa_cmdate);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.taxa_aename ) {\n\t\t param_list.push(\"taxa_\" + params.taxa_authent + \"=\" + params.taxa_aename);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.taxa_cmdate || param_errors.taxa_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_ops )\n\t {\n\t\tif ( params.ops_cmdate ) {\n\t\t param_list.push(\"ops_\" + params.ops_crmod + \"=\" + params.ops_cmdate);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.ops_aename ) {\n\t\t param_list.push(\"ops_\" + params.ops_authent + \"=\" + params.ops_aename);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.ops_cmdate || param_errors.ops_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_refs )\n\t {\n\t\tif ( params.refs_cmdate ) {\n\t\t param_list.push(\"refs_\" + params.refs_crmod + \"=\" + params.refs_cmdate);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.refs_aename ) {\n\t\t param_list.push(\"refs_\" + params.refs_authent + \"=\" + params.refs_aename);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.refs_cmdate || param_errors.refs_aename ) errors_found = 1;\n\t }\n\t}\n\t\n\t// If the selected record type is either references or taxa selected by reference or\n\t// opinions, then add the appropriate parameter using the form element that appears just\n\t// above the\"Select by taxonomy\" section.\n\t\n\tif ( data_type == 'refs' || data_type == 'byref' )\n\t{\n\t if ( params.reftypes && params.reftypes != \"\" && ! use_ref_list ) {\n\t\tparam_list.push(\"select=\" + params.reftypes);\n\t }\n\t}\n\t\n\telse if ( data_type == \"ops\" )\n\t{\n\t var op_select = getElementValue(\"pm_op_select\");\n\t if ( op_select )\n\t\tparam_list.push(\"op_type=\" + op_select);\n\t}\n\n\t// If \"include non-public data\" is selected, add the parameter 'private'.\n\t\n\tif ( params.private && is_contributor )\n\t{\n\t param_list.push(\"private\");\n\t}\n\t\n\t// If the section \"output options\" is visible, then go through the parameters it contains.\n\t// This includes specifying which output blocks to return using the \"show\" parameter.\n\t\n\tif ( visible.o1 )\n\t{\n\t var output_list = getOutputList();\n\t \n\t if ( paleoloc_all || paleoloc_selected )\n\t {\n\t\tneed_pgm = 0;\n\t\t\n\t\tif ( paleoloc_all )\n\t\t param_list.push(\"pgm=\" + api_data.pg_models.join(','));\n\t\t\n\t\telse\n\t\t param_list.push(\"pgm=\" + params.pg_model);\n\t\t\n\t\tif ( params.pg_select != \"mid\" )\n\t\t param_list.push(\"pgs=\" + params.pg_select);\n\t }\n\t \n\t if ( ! occs_required )\n\t\toutput_list = output_list.replace(/occapp,?/, 'app,');\n\t if ( output_list ) param_list.push(\"show=\" + output_list);\n\t \n\t var order_expr = getElementValue(output_order);\n\t var order_dir = getElementValue(\"pm_order_dir\");\n\t \n\t if ( order_expr && order_expr != '--' )\n\t {\n\t\tif ( order_expr == 'authpub' )\n\t\t{\n\t\t if ( order_dir && order_dir == 'asc' )\n\t\t\tparam_list.push(\"order=author,pubyr.asc\");\n\t\t else\n\t\t\tparam_list.push(\"order=author,pubyr.desc\");\n\t\t}\n\t\t\n\t\telse if ( order_expr == 'pubauth' )\n\t\t{\n\t\t if ( order_dir && order_dir == 'asc' )\n\t\t\tparam_list.push(\"order=pubyr.asc,author\");\n\t\t else\n\t\t\tparam_list.push(\"order=pubyr.desc,author\");\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t if ( order_dir && order_dir != '--' )\n\t\t\torder_expr = order_expr + '.' + order_dir;\n\t\t param_list.push(\"order=\" + order_expr);\n\t\t}\n\t }\n\t \n\t if ( params.offset ) param_list.push(\"offset=\" + params.offset);\n\t if ( params.limit ) param_list.push(\"limit=\" + params.limit);\n\n\t if ( param_errors.limit ) errors_found = 1;\n\t}\n\t\n\t// Otherwise, add \"show=acconly\" if indicated by the \"accepted names only\" checkbox\n\t// in the \"Select by taxonomy\" section.\n\t\n\telse if ( (data_type == 'occs' || data_type == 'specs' ) && visible.f1)\n\t{\n\t var acc_only = myGetElement(\"pm_acc_only\");\n\t if ( acc_only && acc_only.checked )\n\t\tparam_list.push('show=acconly');\n\t}\n\t\n\t// If we still need a \"pgm=\" parameter, add it now.\n\t\n\tif ( need_pgm )\n\t param_list.push(\"pgm=\" + params.pg_model);\n\t\n\t// Now alter the operation, if necessary, based on the chosen parameters\n\t\n\tif ( occs_required )\n\t{\n\t if ( my_op == 'taxa/list' ) my_op = 'occs/taxa';\n\t else if ( my_op == 'taxa/refs' ) my_op = 'occs/refs';\n\t else if ( my_op == 'taxa/byref' ) my_op = 'occs/taxabyref';\n\t else if ( my_op == 'opinions/list' ) my_op = 'occs/opinions';\n\t}\n\t\n\telse if ( taxon_required )\n\t{\n\t if ( my_op == 'opinions/list' ) my_op = 'taxa/opinions';\n\t}\n\n\tif ( refs_required )\n\t{\n\t if ( my_op == 'occs/list' ) { my_op = 'occs/byref'; all_required = 1; }\n\t else if ( my_op == 'colls/list' ) { my_op = 'colls/byref'; all_required = 1; }\n\t else if ( my_op == 'taxa/list' ) my_op = 'taxa/byref';\n\t else if ( my_op == 'occs/taxa' ) { my_op = 'occs/taxabyref'; all_required = 1; }\n\t else if ( my_op == 'opinions/list' ) { my_op = 'taxa/opinions'; all_required = 1; }\n\t else if ( my_op == 'specs/list' ) { my_op = 'specs/byref'; all_required = 1; }\n\t else if ( my_op == 'strata/list' ) { my_op = 'occs/strata'; all_required = 1; }\n\t else if ( my_op == 'taxa/refs' && use_ref_list ) my_op = 'refs/list';\n\t}\n\t\n\t// If no \"significant\" parameter has been entered, then see if we need to add the\n\t// parameter 'all_records' in order to satisfy the requirements of the API.\n\t\n\tif ( all_required || ! has_main_param )\n\t{\n\t var all_records_elt = myGetElement(\"pm_all_records\");\n\n\t // If 'all_required' is true, then add the parameter. This flag will be true if\n\t // certain of the fields in the \"Metadata\" section are filled in.\n\t \n\t if ( all_required )\n\t {\n\t\tparam_list.push('all_records');\n\t\thas_main_param = 1;\n\t }\n\t \n\t // Do the same if the \"select all records\" box is checked. In this case,\n\t // Set the 'confirm_download' flag so that a confirmation dialog box will\n\t // be generated before a download is initiated.\n\t \n\t else if ( all_records_elt && all_records_elt.checked )\n\t {\n\t\tparam_list.push('all_records');\n\t\thas_main_param = 1;\n\t\tconfirm_download = 1;\n\t }\n\t}\n\t\n\t// Now, if any errors were found, or if no \"significant\" parameter was entered,\n\t// then display a message for the user.\n\t\n\tvar url_elt = document.getElementById('mainURL');\n\t\n\tif ( errors_found )\n\t{\n\t url_elt.textContent = \"Fix the parameter errors below to generate a download URL\";\n\t url_elt.href = \"\";\n\t}\n\t\n\telse if ( ! has_main_param )\n\t{\n\t url_elt.textContent = \"Enter one or more parameters below to generate a download URL\";\n\t url_elt.href = \"\";\n\t}\n\n\t// Otherwise, generate the URL and display it.\n\t\n\telse\n\t{\n\t \n\t var param_string = param_list.join('&');\n\t \n\t // Construct the new URL\n\t \n\t var new_url = full_data_url + my_op + data_format + '?';\n\n\t download_path = short_data_url + my_op + data_format;\n\t download_params = '';\n\t \n\t if ( params.output_metadata )\n\t\tdownload_params = 'datainfo&rowcount&';\n\n\t download_params += param_string;\n\t \n\t new_url += download_params;\n\t \n\t url_elt.textContent = new_url;\n\t url_elt.href = new_url;\n\t}\n\t\n\t// Adjust metadata subsections according to the selected operation.\n\t\n\turl_op = my_op;\n\t\n\t// switch ( my_op )\n\t// {\n\t// case 'specs/list':\n\t// selectMetaSub('pd_meta_specs');\n\t// // showElement('pd_meta_occs');\n\t// // showElement('pd_meta_colls');\n // case 'occs/list':\n // case 'occs/diversity':\n // case 'occs/taxa':\n\t// case 'occs/strata':\n \t// selectMetaSub('pd_meta_occs');\n\t// showElement('pd_meta_colls');\n \t// break;\n // case 'colls/list':\n \t// selectMetaSub('pd_meta_colls');\n\t// showElement('pd_meta_occs');\n \t// break;\n \t// case 'taxa/list':\n \t// selectMetaSub('pd_meta_taxa');\n \t// break;\n \t// case 'opinions/list':\n \t// selectMetaSub('pd_meta_ops');\n \t// break;\n // case 'taxa/opinions':\n \t// selectMetaSub('pd_meta_ops');\n\t// showElement('pd_meta_taxa');\n \t// break;\n \t// case 'refs/list':\n\t// selectMetaSub('pd_meta_refs');\n\t// break;\n \t// case 'occs/refs':\n\t// case 'occs/taxabyref':\n\t// selectMetaSub('pd_meta_occs');\n\t// showElement('pd_meta_refs');\n\t// break;\n // case 'taxa/refs':\n\t// case 'taxa/byref':\n \t// selectMetaSub('pd_meta_taxa' );\n\t// showElement('pd_meta_refs');\n \t// break;\n\t// }\n }",
"function pdfDownload(){ \n\tvar url = \"https://\"+CURRENT_IP+\"/cgi-bin/NFast_3-0/CGI/RESERVATIONMANAGER/FastConsoleCgi.py?action=configdlpdf&query={'QUERY':[{'username':'\"+globalUserName+\"'}]}\";\n \n\t\twindow.location.href = url + query ;\n}",
"downloadData() {\n let domEl = document.createElement('a');\n domEl.id = \"download\";\n domEl.download = this._options.download.filename || \"grapher_data.csv\";\n domEl.href = URL.createObjectURL(new Blob([Grapher.to_csv(this.data)]));\n domEl.click();\n }",
"ExportApplication(string, string, int) {\n\n }",
"function refreshFrame(index) {\r\n var container = $(\"#page-\" + index);\r\n var templateName = $(\"#page-template-\" + index).val();\r\n var color = $(\"input[name='page-color-\" + index + \"']:checked\").val();\r\n var seed = $(\"#seed\").val();\r\n var fileName = getFileName(index);\r\n\r\n if (pdfMode) { \r\n // Output to blob.\r\n var stream = blobStream();\r\n \r\n // Eventually output the blob into given container.\r\n stream.on('finish', function() {\r\n // Get & remember blob object.\r\n var blob = stream.toBlob('application/pdf');\r\n $(container).data(\"blob\", blob);\r\n \r\n // Clear previous blob URL and remember new one.\r\n var url = $(container).data(\"blobUrl\");\r\n if (url) {\r\n window.URL.revokeObjectURL(url);\r\n }\r\n url = window.URL.createObjectURL(blob);\r\n $(container).data(\"blobUrl\", url);\r\n\r\n // Render blob URL into container.\r\n renderPDF(url, container);\r\n \r\n // Set link attributes.\r\n var index = $(container).data(\"index\");\r\n $(\"#page-download-\" + index)\r\n .attr('href', url)\r\n .attr('target', '_blank')\r\n .attr('download', fileName + '.pdf');\r\n });\r\n\r\n // Generate the PDF.\r\n generatePDF(stream, templates[templateName], scrapedTexts, scrapedImages, {color: color});\r\n \r\n } else {\r\n\r\n // Generate SVG download link URL.\r\n var images = [];\r\n for (var i in scrapedImages) {\r\n images.push(scrapedImages[i].url);\r\n }\r\n var parameters = {\r\n seed: seed,\r\n fields: scrapedTexts,\r\n images: images,\r\n options: {color: color}\r\n };\r\n var url = 'templates/' + templateName + '.pdf'\r\n + \"?parameters=\" + encodeURIComponent(JSON.stringify(parameters));\r\n\r\n // Generate the SVG.\r\n var svg = generateSVG(templates[templateName], scrapedTexts, scrapedImages, {color: color});\r\n\r\n // Render SVG into container.\r\n renderSVG(svg, container);\r\n \r\n // Set link attributes.\r\n var index = $(container).data(\"index\");\r\n $(\"#page-download-\" + index)\r\n .attr('href', url)\r\n .attr('target', '_blank')\r\n .attr('download', fileName + '.pdf');\r\n }\r\n\r\n}",
"downloadModelGLB() {\n\t\tthis.emitWarningMessage(\"Preparing GLTF file...\", 60000);\n\t\tthis.props.loadingToggle(true);\n\t\twindow.LITHO3D.downloadGLTF(1, 1, 1, false, true).then(() => {\n\t\t\tthis.props.loadingToggle(false);\n\t\t\tthis.emitWarningMessage(\"File is ready for download.\", 500);\n\t\t})\n\t\t\t.catch(err => {\n\t\t\t\tthis.props.loadingToggle(false);\n\t\t\t\tthis.emitWarningMessage(err.message);\n\t\t\t});\n\t}",
"function BookmarksPortletData( namespace,\n bookmark_form_newWindow,\n bookmark_form_url,\n bookmark_forms_empty,\n bookmark_forms_error,\n bookmark_reference_url,\n bookmarksTreeAndForm,\n entry_childFolderPrefix,\n entry_edit_cancelLink,\n entry_edit_editLink,\n entry_form_action,\n entry_form_action_editBookmark,\n entry_form_action_editFolder,\n entry_form_action_editCollection,\n entry_form_action_newBookmark,\n entry_form_action_newFolder,\n entry_form_action_newCollection,\n entry_form_folderPath,\n entry_form_folderPathLabel,\n entry_form_idPath,\n entry_form_name,\n entry_form_note,\n entry_imagePrefix,\n entry_reference_folderPath,\n entry_reference_name,\n entry_reference_note,\n folder_forms_empty,\n folder_forms_error,\n folder_image_closed,\n folder_image_open,\n collection_form_url,\n collection_forms_empty,\n collection_forms_error,\n options_form,\n options_showLink,\n messages_folder_create,\n messages_folder_move,\n messages_delete_bookmark_prefix,\n messages_delete_bookmark_suffix,\n messages_delete_folder_prefix,\n messages_delete_folder_suffix,\n messages_delete_collection_prefix,\n messages_delete_collection_suffix) {\n\n this.namespace = namespace;\n\n this.bookmark_form_newWindow = bookmark_form_newWindow;\n this.bookmark_form_url = bookmark_form_url;\n this.bookmark_forms_empty = bookmark_forms_empty;\n this.bookmark_forms_error = bookmark_forms_error;\n this.bookmark_reference_url = bookmark_reference_url;\n this.bookmarksTreeAndForm = bookmarksTreeAndForm;\n this.entry_childFolderPrefix = entry_childFolderPrefix;\n this.entry_edit_cancelLink = entry_edit_cancelLink;\n this.entry_edit_editLink = entry_edit_editLink;\n this.entry_form_action = entry_form_action;\n this.entry_form_action_editBookmark = entry_form_action_editBookmark;\n this.entry_form_action_editFolder = entry_form_action_editFolder;\n this.entry_form_action_editCollection = entry_form_action_editCollection;\n this.entry_form_action_newBookmark = entry_form_action_newBookmark;\n this.entry_form_action_newFolder = entry_form_action_newFolder;\n this.entry_form_action_newCollection = entry_form_action_newCollection;\n this.entry_form_folderPath = entry_form_folderPath;\n this.entry_form_folderPathLabel = entry_form_folderPathLabel;\n this.entry_form_idPath = entry_form_idPath;\n this.entry_form_name = entry_form_name;\n this.entry_form_note = entry_form_note;\n this.entry_imagePrefix = entry_imagePrefix;\n this.entry_reference_folderPath = entry_reference_folderPath;\n this.entry_reference_name = entry_reference_name;\n this.entry_reference_note = entry_reference_note;\n this.collection_form_url = collection_form_url;\n this.collection_forms_empty = collection_forms_empty;\n this.collection_forms_error = collection_forms_error;\n this.folder_forms_empty = folder_forms_empty;\n this.folder_forms_error = folder_forms_error;\n this.folder_image_closed = folder_image_closed;\n this.folder_image_open = folder_image_open;\n this.options_form = options_form;\n this.options_showLink = options_showLink;\n this.messages_folder_create = messages_folder_create;\n this.messages_folder_move = messages_folder_move;\n this.messages_delete_bookmark_prefix = messages_delete_bookmark_prefix;\n this.messages_delete_bookmark_suffix = messages_delete_bookmark_suffix;\n this.messages_delete_folder_prefix = messages_delete_folder_prefix;\n this.messages_delete_folder_suffix = messages_delete_folder_suffix;\n this.messages_delete_collection_prefix = messages_delete_collection_prefix;\n this.messages_delete_collection_suffix = messages_delete_collection_suffix;\n\n\n //Handy function for debugging\n function toString() {\n var stringVal = \"BookmarksPortletData[\";\n var hasProperties = false;\n\n for (var property in this) {\n hasProperties = true;\n\n if ((this[property] + \"\").indexOf(\"function \") != 0) {\n stringVal += property + \"=\" + this[property] + \", \";\n }\n }\n \n\n if (hasProperties) {\n stringVal = stringVal.substring(0, stringVal.length - 2);\n }\n\n stringVal += \"]\";\n\n return stringVal;\n }\n this.toString = toString;\n\n //Object registers itself with the global array of data objects\n bookmarkPortletsData[namespace] = this;\n}",
"downloadCode() {\r\n let data = $('#' + this.mirrorId).val();\r\n\r\n if (!data || data.length === 0) {\r\n toastr.error('No code to download!');\r\n } else {\r\n $('#codeDownload').attr({\r\n 'download': 'code.py',\r\n 'href': 'data:text/plain;charset=UTF-8,' + encodeURIComponent(data)\r\n })\r\n\r\n toastr.success('Code downloaded!');\r\n }\r\n }",
"buildDownloadOptions() {\n // Build all the query strings based on the dataset.\n this.buildQueryStrings();\n\n // Add the base download options menu configurations.\n this._downloadOptions = [\n {\n ...this._downloadOptionsTemplate[this._downloadOptionsTemplateIndex['raw-sequencing-files']],\n query: this._rawSequencingFileQueryString,\n },\n ];\n\n // Build the index of this class's custom download options.\n this._downloadOptionsIndex = buildDownloadOptionsIndex(this._downloadOptions);\n }",
"function downloadCSVFile()\n {\n window.open('/ReportController/downloadCSVFile', '_blank');\n }",
"constructor(isbn, size = 'S', key = 'isbn') {\n this.isbn = isbn;\n this.key = key.toUpperCase() + \":\"; //This sets the key variable to uppercase. This is to create the correct web address\n this.bc = new bookCover(isbn, size, key); //This uses the current details to create a new book class, which included the ISBN, size and key\n /* visit https://openlibrary.org/dev/docs/api/books */\n this.url_a = 'https://openlibrary.org/api/books?bibkeys='; //First part of the web address - part A\n this.url_b = '&format=json&jscmd=data'; //last part of the web address - Part B\n /* 'https://openlibrary.org/api/books?bibkeys=ISBN:0201558025&format=json' */\n this.detail = \"\";\n\n \n }",
"function fn_downloaddoc()\n{\n\tvar filename=$('#activityfilename').val();\n\twindow.open('library/activities/library-activities-download.php?&filename='+filename,'_self');\n\treturn false;\n}",
"function exportDashboard() {\n\t\n\tconsole.log(\"1. Downloading metadata\");\t\t\n\t//Do initial dependency export\n\tvar promises = [\n\t\tdependencyExport(\"dashboard\", currentExport.dashboardIds)\n\t];\n\tQ.all(promises).then(function (results) {\n\t\t\t\t\n\t\t//Get indicators and categoryOptionGroupSets from favourites\n\t\t//Get indicator groups from conf files\n\t\tpromises = [\n\t\t\tindicators(), \n\t\t\tcategoryOptionGroupSetStructure(),\n\t\t\tsaveObject(\"indicatorGroups\", currentExport.indicatorGroupIds),\n\t\t\tuserGroups(),\n\t\t\tusers()\n\t\t];\n\t\tQ.all(promises).then(function (results) {\n\n\t\t\t//Get legends from data elements, indicators and favourites\n\t\t\t//Get indicator types from indicators\n\t\t\tpromises = [\n\t\t\t\tindicatorTypes(), \n\t\t\t\tlegendSets(),\n\t\t\t\tcustomObjects()\n\t\t\t];\n\t\t\tQ.all(promises).then(function (results) {\n\t\t\t\tconsole.log(\"✔ Downloaded metadata successfully\");\n\t\t\t\tprocessDashboard();\n\t\t\t\n\t\t\t});\t\n\t\t\t\n\t\t});\n\t\t\n\t});\n\t\t\t\t\n}",
"createApi(apiData, cb) {\n this.request('POST', '/api/apis', apiData, cb)\n }",
"setupDownloadingUI() {\n this.downloadStatus = document.getElementById(\"downloadStatus\");\n this.downloadStatus.textContent = DownloadUtils.getTransferTotal(\n 0,\n this.update.selectedPatch.size\n );\n this.selectPanel(\"downloading\");\n this.aus.addDownloadListener(this);\n }",
"function DownloadableObject() {\n\t\n\t// Construct object.\n\tthis.Init = function(filepath, url) {\n\t\tthis.filepath = filepath;\n\t\tthis.url = url;\n\t};\n\t\n\t// Check that we can write the target file.\n\tthis.TargetFileExists = function(onComplete) {\n\t\tfs.access(_that.filepath, fs.constants.W_OK, function(err) {\n\t\t\tvar file_exist = !err;\n\t\t\tonComplete(file_exist);\n\t\t});\n\t};\n\t\n\t// Read target file from disk as buffer.\n\tthis.ReadTargetFile = function(onComplete, onError) {\n\t\tfs.readFile(_that.filepath, function (err, data) {\n\t\t\tif (err) {\n\t\t\t\tif (onError) { onError(_that); }\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_that.file_content = data;\n\t\t\t\tonComplete(_that);\n\t\t\t}\n\t\t});\n\t};\n\t\n\t// Download to file (by keeping file fully in memory).\n\t// TODO: pipe directly to disk if file is too big (> 50MB).\n\tthis.DownloadToFile = function(onComplete, onError) {\n\t\t_that.DownloadToMemory(function() {\n\t\t\t_that.SaveToDisk(onComplete, onError);\n\t\t}, onError);\n\t};\n\t\n\t// Download to file but do not save 404 file.\n\tthis.SilentDownloadToFile = function(onComplete, onError) {\n\t\t_that.DownloadToMemory(function() {\n\t\t\t_that.SaveToDisk(onComplete, onError);\n\t\t}, onComplete);\t\t\n\t};\n\n\tthis.DownloadToMemory = function(onComplete, onError) {\n\t\t// If filepath is provided, check if file was already saved.\n\t\tif (_that.filepath) {\t\t\t\n\t\t\t_that.TargetFileExists(function(exists) {\n\t\t\t\tif (exists) {\n\t\t\t\t\t// If file exists, just read it.\n\t\t\t\t\t_that.ReadTargetFile(onComplete, onError);\n\t\t\t\t} else {\n\t\t\t\t\t// If it doesn't, download it.\n\t\t\t\t\t_that.DownloadBuffer(onComplete, onError);\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tconsole.log(\"Caching is disabled for \\\"\" + _that.url + \"\\\" as not filepath as been provided prior to DownloadToMemory.\");\n\t\t\t_that.DownloadBuffer(onComplete, onError);\n\t\t}\n\t};\n\t\n\tthis.DownloadBuffer = function(onComplete, onError) {\n\t\tvar downloader = _that.url.indexOf(\"https://\") == -1 ? http : https;\n\t\tvar chunks = [];\n\t\tdownloader.get(_that.url, function(res) {\n\t\t\tif (res.statusCode == 404) {\n\t\t\t\tonError(_that);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tres.on('data', function(chunk) {\n\t\t\t\tchunks.push(chunk)\n\t\t\t});\n\t\t\tres.on('error', function() {\n\t\t\t\tif (onError) { onError(_that); }\n\t\t\t});\n\t\t\tres.on('end', function() {\n\t\t\t\t_that.file_content = Buffer.concat(chunks);\n\t\t\t\tonComplete(_that);\n\t\t\t});\n\t\t});\n\t};\n\t\n\tthis.PostSoapRequest = function(guid, onComplete, onError) {\n\t\t_that.url = \"https://photosynth.net/photosynthws/photosynthservice.asmx\";\n\t\tvar request_body = '';\n\t\trequest_body += '<?xml version=\"1.0\" encoding=\"utf-8\"?>';\n\t\trequest_body += '<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">';\n\t\trequest_body += ' <soap:Body>';\n\t\trequest_body += ' <GetCollectionData xmlns=\"http://labs.live.com/\">';\n\t\trequest_body += ' <collectionId>'+guid+'</collectionId>';\n\t\trequest_body += ' <incrementEmbedCount>false</incrementEmbedCount>';\n\t\trequest_body += ' </GetCollectionData>';\n\t\trequest_body += ' </soap:Body>';\n\t\trequest_body += '</soap:Envelope>';\n\t\t\n\t\trequest({\n\t\t\turl: _that.url,\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t\"content-type\": \"text/xml; charset=utf8\",\n\t\t\t},\n\t\t\tbody: request_body\n\t\t}, function (error, response, body){\n\t\t\tif (error) {\n\t\t\t\tonError(error);\n\t\t\t} else {\n\t\t\t\t_that.file_content = body;\n\t\t\t\tonComplete(body);\n\t\t\t}\n\t\t});\t\t\n\t};\n\n\t// Save content previously downloaded to disk.\n\tthis.SaveToDisk = function(onComplete, onError) {\n\t\t// Skip saving if file already exists.\n\t\t_that.TargetFileExists(function(exists) {\n\t\t\tif (exists) {\n\t\t\t\tonComplete(_that);\n\t\t\t} else {\n\t\t\t\t// Write to filepath.tmp file.\n\t\t\t\tfs.writeFile(_that.filepath + \".tmp\", _that.file_content, function (err) {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tif (onError) { onError(_that); }\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// Rename filepath.tmp to filepath.\n\t\t\t\t\t\tfs.rename(_that.filepath + \".tmp\", _that.filepath, function(err) {\n\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\tif (onError) { onError(_that); }\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tonComplete();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t};\n\t\n\tthis.ParseJson = function() {\n\t\treturn JSON.parse(_that.file_content);\n\t};\n\t\n\tthis.ParseXml = function(onComplete, onError) {\n\t\tparseString(_that.file_content, function (err, result) {\n\t\t\tif (err) {\n\t\t\t\tif (onError) { onError(_that); }\n\t\t\t} else {\n\t\t\t\tonComplete(result);\n\t\t\t}\n\t\t});\n\t};\n\t\n\tthis.Clear = function() {\n\t\tthis.filepath = \"\";\n\t\tthis.url = \"\";\n\t\tthis.file_content = \"\";\n\t};\n\t\n\tvar _that = this;\n\tthis.filepath;\n\tthis.url;\n\tthis.file_content;\t\n}",
"static get DATABASE_SUBMIT_REVIEW() {\r\n return `http://localhost:${DBHelper.PORT}/reviews`;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an observer to the observer chain, setting up the head/tail/next/prev properties correctly | function addObserver(chain, observer) {
let tail = chain.tail;
if (tail) {
observer.prev = tail;
tail.next = observer;
chain.tail = observer;
} else {
chain.head = observer;
chain.tail = observer;
}
} | [
"addObserver(observer){\n \n this.observers.push(observer)\n }",
"_observeEntries() {\n this.items.forEach((item) => {\n item.elementsList.forEach((element) => {\n this.observer.observe(element);\n });\n });\n }",
"setTail(node) {\n if (!this.tail) {\n this.head = node;\n this.tail = node;\n } else {\n node.prev = this.tail;\n this.tail = node;\n }\n }",
"observePage() {\n if (!this.observer) {\n this.observer = new MutationObserver((mutations) => {\n if (this.handleMutationsTimeout) {\n // Don't handle the mutations yet after all.\n clearTimeout(this.handleMutationsTimeout)\n }\n\n mutations.forEach((mutation) => {\n // Filter mutations to park.\n if (mutation.addedNodes.length) {\n for (const node of mutation.addedNodes) {\n if (!this.walker.skipNode(node)) {\n this.parkedNodes.push(node)\n }\n }\n } else if (!mutation.removedNodes.length && mutation.target) {\n if (!this.walker.skipNode(mutation.target)) {\n this.parkedNodes.push(mutation.target)\n }\n }\n })\n\n // Assuming nothing happens, scan the nodes in 500 ms - after\n // this the page should've been done dealing with the mutations.\n if (this.parkedNodes.length) {\n this.handleMutationsTimeout = setTimeout(this.handleMutations.bind(this), 500)\n }\n })\n }\n\n if (this.observer) {\n this.observer.observe(document.body, {childList: true, subtree: true})\n }\n }",
"function addMutationObserver() {\n const config = {\n childList: true,\n attributes: true,\n subtree: true,\n };\n observer.observe(document, config);\n}",
"observe() {\n if(this.observer) {\n this.unobserve();\n }\n this.observer = jsonPatchObserve(this.didDocument);\n }",
"function _observe(observer, obj, patches) {\r\n if (Object.observe) {\r\n Object.observe(obj, observer);\r\n }\r\n for (var key in obj) {\r\n if (obj.hasOwnProperty(key)) {\r\n var v = obj[key];\r\n if (v && typeof (v) === \"object\") {\r\n _observe(observer, v, patches);\r\n }\r\n }\r\n }\r\n return observer;\r\n }",
"observe( callback ) {\n if ( this.observing ) {\n return\n }\n\n this.listener = e => {\n if ( !this.observing ) {\n return\n }\n // save for back\n this.oldURL = e.oldURL\n\n callback( {\n newSegment: getHash( e.newURL ),\n oldSegment: getHash( e.oldURL ),\n } )\n }\n\n setTimeout( () => {\n window.addEventListener( 'hashchange', this.listener )\n this.observing = true\n }, 0 )\n }",
"initIntersectionObserver() {\n if (this.observer) return;\n // Start loading the image 10px before it appears on screen\n const rootMargin = '10px';\n this.observer = new IntersectionObserver(this.observerCallback, { rootMargin });\n this.observer.observe(this);\n }",
"addToHead(val) {\n // console.log('something')\n\n const node = new Node(val)\n if(this.head === null){\n this.head = node;\n this.tail = node;\n\n } else {\n const temp = this.head;\n this.head = node;\n this.head.next = temp;\n\n }\n\n this.length++\n return this\n }",
"function attachTracklistModificationListeners(onTracklistModifiedByExternalSource) {\n let onEvent = (event) => {\n if(!currentlyModifyingAnyTracklist)\n onTracklistModifiedByExternalSource()\n }\n\n for(trackList of getTracklistNodes()) {\n trackList.addEventListener('DOMNodeInserted', onEvent)\n trackList.addEventListener('DOMNodeRemoved', onEvent)\n }\n}",
"addToTail(value) {\n const newNode = {\n value: value,\n next: null\n };\n\n if (!this.head && !this.tail) {\n this.head = newNode;\n this.tail = newNode;\n return;\n }\n this.tail.next = newNode;\n this.tail = newNode;\n }",
"function runObserver (observer) {\n currentObserver = observer;\n observer();\n}",
"initEndlessScrolling() {\n if (!this.searchEngine.endlessScrollingContainer) {\n return;\n }\n this.observedAdditions = 0;\n const config = {attributes: false, childList: true, subtree: false};\n let firstObservation = true;\n let observedHref = undefined;\n const observer = new MutationObserver(async (mutationsList, observer) => {\n if (firstObservation && this.resultsManager) {\n observedHref = location.href;\n this.observedAdditions = this.resultsManager.searchResults.length;\n firstObservation = false;\n }\n if (observedHref && observedHref != location.href) {\n // Mutation Server was triggered due to loading a new url -> disconnect\n // the observer\n observer.disconnect();\n return;\n }\n this.observedAdditions += mutationsList[0].addedNodes.length;\n if (this.resultsManager &&\n this.resultsManager.searchResults.length < this.observedAdditions) {\n // Initialize a reload of navigation, save local values\n this.options.local.values.lastQueryUrl = location.href;\n this.options.local.values.lastFocusedIndex = this.results.focusedIndex;\n await this.options.local.save();\n this.resultsManager.reloadSearchResults();\n }\n });\n observer.observe(this.searchEngine.endlessScrollingContainer, config);\n }",
"processPage() {\n this.logger.debug(`${this}start observing`)\n $('head').appendChild(this.stylesheet)\n this.insertIconInDom()\n this.observePage()\n }",
"prependData(target, data){\n var node = new DLLNode(data);\n var runner = this.head;\n while(runner){\n if(runner === target){\n node.next = runner;\n node.prev = runner.prev;\n runner.prev.next = node;\n runner.prev = node;\n this.length++;\n if(runner === this.head){\n this.head = node;\n }\n }else{\n runner = runner.next;\n }\n }\n }",
"function addChangesetsObserver() {\n var observer = new MutationObserver(function (mutations) {\n mutations.forEach(function (mutation) {\n if (mutation.type == 'attributes') {\n return;\n }\n searchChangesets();\n });\n });\n\n var config = { attributes: true, childList: true, characterData: true };\n var changesets = document.querySelector('#sidebar_content div.changesets');\n observer.observe(changesets, config);\n}",
"constructor(ref){\n this.ref = ref;\n this.next = null;\n }",
"constructor(element) {\n this.element = element;\n this.next = null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=====| fTwoColumns Function |===== Function for dividing the container row into two columns | function fTwoColumns (rightColumnPercentage) {
//console.log ("fTwoColumns function----------------: ");
/**-*****************************************************-**/
/** When using the default bootstrap's div class = "container", use the ff.
* Otherwise use window.innerWidth.
***********************************************************/
/**----{ Bootstrap class = "container" }----**/
/** Default setting:
* padding-right: 15px
* padding-left: 15px
**********************************/
var padLeftRight = 30;
var containerWidth = (container.width ()) + padLeftRight;
/**-*****************************************************-**/
//windowInnerWidth = window.innerWidth; //Browser window inner width
// }
////console.log ("fTwoColumns windowInnerWidth: ", windowInnerWidth);
var columnRight = containerWidth * (rightColumnPercentage / 100); // (90 / 100) for 90%
var columnLeft = containerWidth - columnRight;
var imageRightColumnWidth = Math.round (columnRight);
colRightWidth = imageRightColumnWidth;
//imgsContainerWidth = imageRightColumnWidth * 3;
/**----( Adjust left columns width )----**/
colLeft.css ({"width": columnLeft});
//colLeftWidth = columnLeft;
/**----( Adjust the right columns )----**/
colRight.css ({"width": columnRight});
//colRightWidth = columnRight;
fAnimateWidth (imgTitle, columnRight);
//console.log ("containerWidth: ", containerWidth);
//console.log ("rightColumnPercentage: ", rightColumnPercentage);
//console.log ("columnLeft: ", Math.round (columnLeft));
//console.log ("columnRight: ", Math.round (columnRight));
//console.log ("imageRightColumnWidth: ", imageRightColumnWidth);
//console.log ("colRightWidth: ", colRightWidth);
////console.log ("imgsContainerWidth: ", imgsContainerWidth);
//console.log ("End fTwoColumns function----------------: ");
} | [
"function make_two_column_same_size(){\n\n\ttry{\n\t\tvar side_bar_h = $(\".side_bar\").css(\"height\",\"auto\").height();\n\t\tvar page_content_h = $(\".page-content\").css(\"height\",\"auto\").height();\n\n\t\tif($(\".side_bar\").data(\"originalh\") == undefined){\n\t\t\t$(\".side_bar\").data(\"originalh\",side_bar_h);\n\t\t\t$(\".page-content\").data(\"originalh\",page_content_h);\t\t\n\t\t}else{\n\t\t\tvar side_bar_h_s = $(\".side_bar\").data(\"originalh\");\n\t\t\tvar page_content_h_s = $(\".page-content\").data(\"originalh\");\n\t\t\tif(page_content_h_s>=page_content_h && arguments[0]==\"1\" ) { side_bar_h = side_bar_h_s;page_content_h=page_content_h_s; }\n\t\t\t//alert(side_bar_h_s+\"--\"+side_bar_h);\n\t\t\t//if(side_bar_h_s>side_bar_h) { side_bar_h=side_bar_h_s;alert(\"he\"); }\n\t\t}\n\t\t//alert(page_content_h+\"--\"+side_bar_h);\n\t\tif(parseInt(side_bar_h)>parseInt(page_content_h)){\n\t\t\t$(\".page-content\").css(\"height\",(parseInt(side_bar_h)+extra_pixel())+\"px\");\n\t\t}else if(parseInt(side_bar_h)<parseInt(page_content_h)){\n\t\t\t$(\".side_bar\").css(\"height\",(parseInt(page_content_h)+extra_pixel())+\"px\");\n\t\t}\t\n\t}catch(ex){}finally{}\t\n}",
"function add2ColElement(elem, value)\n{\n var e = document.createElement(\"div\");\n e.className = \"col-md-3\";\n e.innerHTML = formatValue(value[0]);\n elem.appendChild(e);\n\n e = document.createElement(\"div\");\n e.className = \"col-md-3\";\n e.innerHTML = formatValue(value[1]);\n elem.appendChild(e);\n\n e = document.createElement(\"div\");\n e.className = \"col-md-3\";\n e.innerHTML = \"\";\n elem.appendChild(e);\n\n e = document.createElement(\"div\");\n e.className = \"col-md-3\";\n e.innerHTML = \"\";\n elem.appendChild(e);\n\n return e;\n}",
"getCols() {\r\n let cols = Math.floor(Math.ceil(this.getWidth() / 100) / 2) * 2;\r\n\r\n return cols > 0 ? cols : 1;\r\n }",
"function secondHalfOfArrayIfItIsEven(fruits) {\n if (fruits.length % 2 === 0) {\n return fruits.slice(fruits.length / 2, fruits.length);\n } else {\n return [];\n }\n}",
"function twoHalfsGrid(dice, i) {\n\tdice.dataset.orderId = i;\n\tif (i % 2 == 0) {\n\t\tdice.classList.add('position-split-2', 'is-left');\n\t} else {\n\t\tdice.classList.add('position-split-2', 'is-right');\n\t}\n}",
"updateColumnDisplay() {\n let i = 0;\n while (i < this.columnData.length) {\n let colData = this.columnData[i];\n let colWidth = colData.getValue('widthVal');\n let colSpan = colData.getValue('colspanVal');\n colData.getElement().show();\n if (colSpan > 1) {\n let colspanEndIndex = ((i + colSpan) < this.columnData.length) ? (i + colSpan) : this.columnData.length;\n i++;\n // hide columns within colspan\n while (i < colspanEndIndex) {\n colWidth += this.columnData[i].getValue('widthVal');\n this.columnData[i].getElement().hide();\n i++;\n }\n } else {\n i++;\n }\n colData.setDisplayWidth(colWidth);\n colData.updateDisplay();\n }\n }",
"function add1ColElement(elem, value)\n{\n var e = document.createElement(\"div\");\n e.className = \"col-md-3\";\n e.innerHTML = formatValue(value);\n elem.appendChild(e);\n\n e = document.createElement(\"div\");\n e.className = \"col-md-3\";\n e.innerHTML = \"\";\n elem.appendChild(e);\n\n e = document.createElement(\"div\");\n e.className = \"col-md-3\";\n e.innerHTML = \"\";\n elem.appendChild(e);\n\n e = document.createElement(\"div\");\n e.className = \"col-md-3\";\n e.innerHTML = \"\";\n elem.appendChild(e);\n\n return e;\n}",
"function detailColumns(options) {\n options = object.extend({width: '110px', columns: 2}, options || {})\n var cols = []\n for (var i = 0; i < options.columns; i++) {\n cols.push(template.COL({width: options.width}))\n cols.push(template.COL())\n }\n return template.COLGROUP(cols)\n}",
"function buildFlipCol(x, classNames, inner ) {\n var $col = $('<div></div>');\n \n $col.css({\n width : x.halfwidth,\n height : options.panelHeight,\n position : 'absolute',\n top : 0,\n overflow : 'hidden',\n margin : 0,\n padding : 0\n });\n \n var $inner = addPanelCss('<div></div>');\n $inner.addClass(classNames);\n $inner.html(inner);\n \n $col.html($inner);\n \n return $col;\n }",
"function widenBlock(b,w) {\n return b.map(row=>{\n if ( row.length<w ) {\n let extra = w - row.length;\n let front = Math.floor(extra/2), back = extra - front;\n row = ' '.repeat(front) + row + ' '.repeat(back);\n }\n return row;\n });\n }",
"function columnedWidth() {\n var bd = columnedElement();\n var de = p.page.m.activeFrame.contentDocument.documentElement;\n\n var w = Math.max(bd.scrollWidth, de.scrollWidth);\n\n // Add one because the final column doesn't have right gutter.\n // w += k.GAP;\n\n if (!Monocle.Browser.env.widthsIgnoreTranslate && p.page.m.offset) {\n w += p.page.m.offset;\n }\n return w;\n }",
"function column2(machine)\n {\n nameToken = machine.popToken();\n valueToken = machine.popToken();\n switch( valueToken.type )\n {\n case \"identifier\": machine.pushToken( new identifierColumn( \"\", valueToken.identifier, nameToken.identifier ) ); break;\n case \"expression\": machine.pushToken( new expressionColumn( valueToken.expression, nameToken.identifier ) ); break;\n default : error(\"there is an unexpected error with a column2 production\"); \n }\n }",
"function i2uiResizeMasterColumns(tableid, column1width, headerheight, fixedColumnWidths)\r\n{\r\n var width = 0;\r\n\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n //i2uitrace(1,\"i2uiResizeMasterColumns id=\"+tableid+\" parent is \"+tableitem.parentElement.tagName+\" owner height=\"+tableitem.parentElement.clientHeight);\r\n\r\n var len, i, w1, w2, w3, adjust, len2;\r\n var lastheaderrow = headeritem.rows.length - 1;\r\n len = headeritem.rows[lastheaderrow].cells.length;\r\n len2 = len;\r\n\r\n // if horizontal scrolling and scroller needed\r\n if (scrolleritem2 != null &&\r\n scrolleritem2.clientWidth < headeritem.clientWidth)\r\n {\r\n adjust = 0;\r\n len--;\r\n }\r\n else\r\n {\r\n adjust = headeritem.cellPadding * 2;\r\n // do not alter last column\r\n len--;\r\n }\r\n\r\n //i2uitrace(1,\"adjust=\"+adjust);\r\n if( fixedColumnWidths )\r\n {\r\n i2uiResizeColumnsWithFixedHeaderHeight_new(tableid, headerheight, null, fixedColumnWidths );\r\n }\r\n else if (headerheight != null)\r\n {\r\n\t i2uiResizeColumns(tableid);\r\n i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight);\r\n }\r\n else\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * headeritem.rows[lastheaderrow].cells.length;\r\n\r\n // shrink each column first\r\n // note: this may cause the contents to wrap\r\n // even if nowrap=\"yes\"is specified\r\n //i2uitrace(1,\"pre shrink\");\r\n for (i=0; i<len; i++)\r\n {\r\n //headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n //dataitem.rows[0].cells[i].width = 15;\r\n }\r\n //i2uitrace(1,\"post shrink. adjust=\"+adjust);\r\n\r\n len = headeritem.rows[lastheaderrow].cells.length;\r\n\r\n // resize each column to max width between the tables\r\n // NOTE: the computed max may not equal either of the\r\n // current widths due to the adjustment\r\n for (i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n //i2uitrace(1,\"pre i=\"+i+\" header=\"+w1+\" data=\"+w2+\" max=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n if (w1 != w3)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n }\r\n if (w2 != w3)\r\n {\r\n dataitem.rows[0].cells[i].width = w3;\r\n }\r\n //i2uitrace(1,\"post i=\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n }\r\n //i2uitrace(1,\"end data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check1 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check1 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n }\r\n\r\n if (dataitem.clientWidth > headeritem.clientWidth)\r\n {\r\n headeritem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"header width set to data width\");\r\n }\r\n else\r\n if (dataitem.clientWidth < headeritem.clientWidth)\r\n {\r\n dataitem.style.width = headeritem.clientWidth;\r\n //i2uitrace(1,\"data width set to header width\");\r\n }\r\n\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check2 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check2 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n\r\n if (scrolleritem.clientWidth > dataitem.clientWidth)\r\n {\r\n dataitem.style.width = scrolleritem.clientWidth;\r\n headeritem.style.width = scrolleritem.clientWidth;\r\n //i2uitrace(1,\"both widths set to scroller width\");\r\n }\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check3 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check3 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n // one last alignment\r\n if (!i2uiCheckAlignment(tableid))\r\n for (i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n if (w1 != w3)\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n if (w2 != w3)\r\n dataitem.rows[0].cells[i].width = w3;\r\n //LPMremoved\r\n //if (i2uitracelevel == -1)\r\n // dataitem.rows[0].cells[i].width = w1;\r\n //i2uitrace(1,\"post i=\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n }\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check4 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check4 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"FINAL data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n // if column 1 has a fixed width\r\n if (column1width != null && column1width > 0 && len > 1)\r\n {\r\n // assign both first columns to desired width\r\n headeritem.rows[lastheaderrow].cells[0].width = column1width;\r\n dataitem.rows[0].cells[0].width = column1width;\r\n\r\n // assign both first columns to narrowest\r\n var narrowest = Math.min(dataitem.rows[0].cells[0].clientWidth,\r\n headeritem.rows[lastheaderrow].cells[0].clientWidth);\r\n\r\n headeritem.rows[lastheaderrow].cells[0].width = narrowest;\r\n dataitem.rows[0].cells[0].width = narrowest;\r\n\r\n // determine the width difference between the first columns\r\n var spread = Math.abs(dataitem.rows[0].cells[0].clientWidth -\r\n headeritem.rows[lastheaderrow].cells[0].clientWidth);\r\n\r\n // determine how much each non-first column should gain\r\n spread = Math.ceil(spread/(len-1));\r\n\r\n // spread this difference across all non-first columns\r\n if (spread > 0)\r\n {\r\n for (i=1; i<len; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = headeritem.rows[lastheaderrow].cells[i].clientWidth + spread;\r\n dataitem.rows[0].cells[i].width = dataitem.rows[0].cells[i].clientWidth + spread;\r\n }\r\n }\r\n\r\n // if desiring abolsute narrowest possible\r\n if (column1width == 1)\r\n {\r\n // if not aligned, take difference and put in last column of data table\r\n var diff = dataitem.rows[0].cells[0].clientWidth - headeritem.rows[lastheaderrow].cells[0].clientWidth;\r\n var loop = 0;\r\n // well, one call may not be enough\r\n while (diff > 0)\r\n {\r\n dataitem.rows[0].cells[len-1].width = dataitem.rows[0].cells[len-1].clientWidth + diff;\r\n loop++;\r\n\r\n // only try 4 times then stop\r\n if (loop > 4)\r\n break;\r\n diff = dataitem.rows[0].cells[0].clientWidth - headeritem.rows[lastheaderrow].cells[0].clientWidth;\r\n }\r\n }\r\n }\r\n\r\n width = dataitem.clientWidth;\r\n }\r\n //i2uitrace(1,\"i2uiResizeMasterColumns exit. return width=\"+width);\r\n return width;\r\n}",
"function i2uiResizeColumns(tableid, shrink, copyheader, slave, headerheight)\r\n{\r\n var width = 0;\r\n\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n var lastheaderrow = headeritem.rows.length - 1;\r\n var len = headeritem.rows[lastheaderrow].cells.length;\r\n var len2 = len;\r\n\r\n //i2uitrace(1,\"ResizeColumns entry scroller width=\"+scrolleritem.offsetWidth);\r\n\r\n if (headerheight != null && len > 1)\r\n return i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight, slave);\r\n\r\n // check first if resize needed\r\n //i2uitrace(1,\"check alignment in ResizeColumns\");\r\n if (i2uiCheckAlignment(tableid))\r\n {\r\n //i2uitrace(1,\"skip alignment in ResizeColumns\");\r\n return headeritem.clientWidth;\r\n }\r\n\r\n // insert a new row which is the same as the header row\r\n // forces very nice alignment whenever scrolling rows alone\r\n if (copyheader == null || copyheader == 1)\r\n {\r\n //i2uitrace(1,\"pre copy header into data for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n //i2uitrace(1,\"check for bypass\");\r\n for (var i=0; i<len; i++)\r\n {\r\n if (headeritem.rows[lastheaderrow].cells[i].innerHTML !=\r\n dataitem.rows[dataitem.rows.length-1].cells[i].innerHTML)\r\n break;\r\n }\r\n if (i != len)\r\n {\r\n //i2uitrace(1,\"insert fake row table=[\"+tableid+\"]\");\r\n\t // this is the DOM api approach\r\n\t var newrow = document.createElement('tr');\r\n\t if (newrow != null)\r\n\t {\r\n\t\t dataitem.appendChild(newrow);\r\n\t\t var newcell;\r\n\t\t for (var i=0; i<len; i++)\r\n\t \t {\r\n\t\t newcell = document.createElement('td');\r\n\t\t newrow.appendChild(newcell);\r\n\t\t if (newcell != null)\r\n\t\t {\r\n\t\t\t newcell.innerHTML = headeritem.rows[lastheaderrow].cells[i].innerHTML;\r\n\t\t }\r\n\t\t }\r\n\t }\r\n }\r\n\r\n //i2uitrace(1,\"ResizeColumns post copy scroller width=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"post copy header into data for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n var newwidth;\r\n newwidth = dataitem.scrollWidth;\r\n\r\n //i2uitrace(1,\"assigned width=\"+newwidth);\r\n dataitem.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n headeritem.width = newwidth;\r\n headeritem.style.width = newwidth;\r\n\r\n //i2uitrace(1,\"post static width for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n // if processing master table, delete newly insert row and return\r\n if (scrolleritem2 != null && (slave == null || slave == 0))\r\n {\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check5 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check5 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"delete/hide fake row table=\"+tableid);\r\n var lastrow = dataitem.rows[dataitem.rows.length - 1];\r\n dataitem.deleteRow(dataitem.rows.length - 1);\r\n\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check6 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check6 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n // size header columns to match data columns\r\n for (i=0; i<len; i++)\r\n {\r\n newColWidth=(i==0?dataitem.rows[0].cells[i].clientWidth:dataitem.rows[0].cells[i].clientWidth-12);\r\n headeritem.rows[lastheaderrow].cells[i].style.width = newColWidth;\r\n headeritem.rows[lastheaderrow].cells[i].width = newColWidth;\r\n if(i==0)\r\n {\r\n for(j=0; j<dataitem.rows.length; j++)\r\n {\r\n dataitem.rows[j].cells[0].style.width = newColWidth;\r\n dataitem.rows[j].cells[0].width = newColWidth;\r\n }\r\n }\r\n }\r\n\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check7 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check7 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"post hide width for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n //i2uitrace(1,\"check alignment after ResizeColumns short version=\"+i2uiCheckAlignment(tableid));\r\n return newwidth;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$2 scroller: width=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"id=\"+tableid+\" parent is \"+tableitem.parentNode.tagName+\" owner height=\"+tableitem.parentNode.offsetHeight);\r\n //i2uitrace(1,\"id=\"+tableid+\" parent is \"+tableitem.parentElement.tagName+\" owner height=\"+tableitem.parentElement.clientHeight);\r\n // may need to adjust width of header to accomodate scroller\r\n //i2uitrace(1,\"data height=\"+dataitem.clientHeight+\" scroller height=\"+scrolleritem.clientHeight+\" header height=\"+headeritem.clientHeight);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n // if horizontal scrolling and scroller needed\r\n var adjust;\r\n if ((scrolleritem2 != null &&\r\n scrolleritem2.clientWidth < headeritem.clientWidth) ||\r\n headeritem.rows[lastheaderrow].cells.length < 3)\r\n {\r\n adjust = 0;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"header cellpadding=\"+headeritem.cellPadding);\r\n adjust = headeritem.cellPadding * 2;\r\n\r\n // do not alter last column unless it contains a treecell\r\n if(dataitem.rows[0].cells[len-1].id.indexOf(\"TREECELL_\") == -1)\r\n len--;\r\n }\r\n //i2uitrace(1,\"adjust=\"+adjust+\" len=\"+len+\" headeritem #cols=\"+headeritem.rows[0].cells.length);\r\n\r\n // if window has scroller, must fix header\r\n // but not if scrolling in both directions\r\n //i2uitrace(1,\"resizecolumns scrolleritem.style.overflowY=\"+scrolleritem.style.overflowY);\r\n //i2uitrace(1,\"resizecolumns scrolleritem2=\"+scrolleritem2);\r\n if(scrolleritem.style.overflowY == 'scroll' ||\r\n scrolleritem.style.overflowY == 'hidden')\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n dataitem.width = dataitem.clientWidth;\r\n dataitem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"fixed header and data widths\");\r\n }\r\n else\r\n {\r\n if(scrolleritem2 != null)\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"fixed header2 shrink=\"+shrink+\" copyheader=\"+copyheader);\r\n shrink = 0;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$3 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n if (document.body.clientWidth < headeritem.clientWidth)\r\n {\r\n len++;\r\n adjust = 0;\r\n //i2uitrace(1,\"new adjust=\"+adjust+\" new len=\"+len);\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$4 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // shrink each column first\r\n // note: this may cause the contents to wrap\r\n // even if nowrap=\"yes\"is specified\r\n if (shrink != null && shrink == 1)\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * dataitem.rows[0].cells.length;\r\n\r\n //i2uitrace(1,\"pre shrink\");\r\n for (i=0; i<headeritem.rows[lastheaderrow].cells.length-1; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n dataitem.rows[0].cells[i].width = 15;\r\n }\r\n //i2uitrace(1,\"post shrink\");\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$5 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // resize each column to max width between the tables\r\n // NOTE: the computed max may not equal either of the\r\n // current widths due to the adjustment\r\n len = Math.min(len, headeritem.rows[0].cells.length);\r\n\r\n //i2uitrace(1,\"start data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n var w1, w2, w3;\r\n for (var i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n\r\n //i2uitrace(1,\"pre i=\"+i+\" w1=\"+w1+\" w2=\"+w2+\" w3=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n if (w1 != w3)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n }\r\n if (w2 != w3)\r\n {\r\n dataitem.rows[0].cells[i].width = w3;\r\n }\r\n //i2uitrace(1,\"post i=\"+i+\" w1=\"+headeritem.rows[0].cells[i].clientWidth+\" w2=\"+dataitem.rows[0].cells[i].clientWidth+\" w3=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n // try to handle tables that need window scrollers\r\n if (headeritem.clientWidth != dataitem.clientWidth)\r\n {\r\n //i2uitrace(1,\"whoa things moved. table=\"+tableid+\" i=\"+i+\" len=\"+len);\r\n\r\n // if window has scroller, resize to window unless slave table\r\n if (document.body.scrollWidth != document.body.offsetWidth)\r\n {\r\n //i2uitrace(1,\"window has scroller! slave=\"+slave);\r\n if (slave == null || slave == 0)\r\n {\r\n dataitem.width = document.body.scrollWidth;\r\n dataitem.style.width = document.body.scrollWidth;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n if (headeritem.clientWidth < dataitem.clientWidth)\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n }\r\n else\r\n {\r\n dataitem.width = headeritem.clientWidth;\r\n dataitem.style.width = headeritem.clientWidth;\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"$$$$$$6 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // now delete the fake row\r\n if (copyheader == null || copyheader == 1)\r\n {\r\n //i2uitrace(1,\"pre delete row - data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n if (scrolleritem2 == null && (slave == null || slave == 0))\r\n {\r\n if (document.all)\r\n {\r\n dataitem.deleteRow(dataitem.rows.length-1);\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"post delete row - data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n }\r\n\r\n width = headeritem.clientWidth;\r\n\r\n //i2uitrace(1,\"check alignment after ResizeColumns long version\");\r\n //i2uiCheckAlignment(tableid);\r\n }\r\n //i2uitrace(1,\"WIDTH=\"+width);\r\n return width;\r\n}",
"function columnList2( machine )\n {\n columnToken = machine.popToken();\n machine.checkToken(\",\");\n columnListToken = machine.popToken();\n columnListToken.add(columnToken);\n machine.pushToken(columnListToken);\n }",
"rightMostColumn(){\n let headers = this.props.tableData.headers\n if(headers.fixedLeft<headers.headers.length){\n let windowSize=headers.columns-1-headers.fixedLeft\n return headers.currentLeft+windowSize-1\n }else{\n return headers.headers.length-1\n }\n }",
"function middleColumnMatch(){\n\tif(isEmptyRow(\"square1\", \"square4\",\"square7\")){\n\t\tisEqual(\"#square1\", \"#square4\", \"#square7\");\n\t}\n}",
"function Col(props) {\n const size = props.size\n .split(` `)\n .map(s => `col-${ s}`)\n .join(` `);\n\n return <div className={size}>{props.children}</div>;\n}",
"static ligne2Colonne(tabDeTabs){\n let tab2Col = create2DArray(tabDeTabs.length);\n for (let i = 0; i < tabDeTabs.length; i++){\n for (let j = 0; j < tabDeTabs.length; j++){\n tab2Col[j][i] = tabDeTabs[i][j];\n }\n }\n return tab2Col\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the browser is Edge, returns the version number as a float, otherwise returns 0 | function getEdgeVersion() {
var match = /Edge\/(\d+[,.]\d+)/.exec(navigator.userAgent);
if (match !== null) {
return +match[1];
}
return 0;
} | [
"function getIEVersionNumber() {\n var ua = navigator.userAgent;\n var MSIEOffset = ua.indexOf(\"MSIE \");\n \n if (MSIEOffset == -1) {\n return 0;\n } else {\n return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(\";\", MSIEOffset)));\n }\n}",
"function detectIEEdge() {\n var ua = window.navigator.userAgent;\n\n var msie = ua.indexOf('MSIE ');\n if (msie > 0) {\n // IE 10 or older => return version number\n return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);\n }\n\n var trident = ua.indexOf('Trident/');\n if (trident > 0) {\n // IE 11 => return version number\n var rv = ua.indexOf('rv:');\n return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);\n }\n\n var edge = ua.indexOf('Edge/');\n if (edge > 0) {\n // Edge => return version number\n return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);\n }\n\n // other browser\n return false;\n}",
"function extPart_getVersion(partName)\n{\n var retrievedVersion = parseFloat(dw.getExtDataValue(partName, \"version\"));\n if (isNaN(retrievedVersion))\n retrievedVersion = 0;\n return retrievedVersion;\n}",
"function detectIE() {\n var ua = window.navigator.userAgent;\n\n var trident = ua.indexOf('Trident/');\n if (trident > 0) {\n // IE 11 => return version number\n var rv = ua.indexOf('rv:');\n return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);\n }\n\n // other browser\n return false;\n}",
"function getVersion(page) {\r\n\tif (dbug) console.log(\"wwvf-cs::Getting Version.\");\r\n\tvar rv = null;\r\n\tif (page) {\r\n\t\tvar xVer = /v((\\d+)\\.(\\d+)(?:\\.(\\d+(-?[a-z]\\d+)?))?)(-development|release)?/i;\r\n\t\tif (page != \"\" && page.match(/Web Experience Toolkit/i)) {\r\n\t\t\t/*var vNumRe = /\\* (.*?) v(\\d[\\d\\.a-z]+)/;\r\n\t\t\tvar wet3v = /\\* Version: v(\\d[\\d\\.a-zA-Z\\-]+)/;\r\n\t\t\tvar wet30 = /Web Experience Toolkit/;\r\n\t\t\tvar wet40 = /v((\\d+(\\.|-[a-z]\\d*))+(-development|release)?)/i;*/\r\n\t\t\tvar clf2Theme = /(CLF 2.0 theme|CSS presentation layer) v(\\d+.\\S+)/i;\r\n\t\r\n\t\t\tvar clf2ThemeVer = page.match(clf2Theme);\r\n\t\t\tif (clf2ThemeVer) {\r\n\t\t\t\trv = \"2.x\";\r\n\t\t\t} else {\r\n\t\t\t\t// Can't be WET 2.0.\r\n\t\t\t\tvar totVer = page.match(xVer);\r\n\t\t\t\tif (!totVer) {\r\n\t\t\t\t\tif (page.match(/Web Experience Toolkit|WET/i)) {\r\n\t\t\t\t\t\ttotVer = page.match(/\\* +((\\d+)\\.(\\d+)(?:\\.(\\d+(-?[a-z]\\d+)?))?)(-development|release)?/);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (totVer) {\r\n\t\t\t\t\trv = totVer[1];\r\n\t\t\t\t} else {\r\n\t\t\t\t\trv = \"?\";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn rv;\r\n}",
"function getVersion() {\n var contents = grunt.file.read(\"formulate.meta/Constants.cs\");\n var versionRegex = new RegExp(\"Version = \\\"([0-9.]+)\\\";\", \"gim\");\n return versionRegex.exec(contents)[1];\n }",
"function browserNameVersion(){\n let ua = window.navigator.userAgent, tem,\n M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*(\\d+)/i) || [];\n if(/trident/i.test(M[1])){\n tem = /\\brv[ :]+(\\d+)/g.exec(ua) || [];\n return 'IE '+(tem[1] || '');\n }\n if(M[1]=== 'Chrome'){\n tem = ua.match(/\\b(OPR|Edge)\\/(\\d+)/);\n if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');\n }\n M= M[2]? [M[1], M[2]]: [window.navigator.appName, window.navigator.appVersion, '-?'];\n if((tem = ua.match(/version\\/(\\d+)/i))!= null) M.splice(1, 1, tem[1]);\n return M.join('|');\n }",
"function operaVersion() {\r\n\tagent = navigator.userAgent;\r\n\tidx = agent.indexOf(\"opera\");\t\r\n\tif (idx>-1) {\r\n\t\treturn parseInt(agent.subString(idx+6,idx+7));\r\n\t}\r\n}",
"getServerVersion() {\n if(!_.isUndefined(this.nodeInfo) && !_.isUndefined(this.nodeInfo.server)\n && !_.isUndefined(this.nodeInfo.server.version)) {\n return this.nodeInfo.server.version;\n }\n }",
"version() {\n console.log(\"HSA.version\");\n this._log.debug(\"HSA.version\");\n return this._version;\n }",
"get nodeVersion() {\n return this._cliConfig.get('node-version', process.versions.node);\n }",
"function vh(v) {\n let h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);\n return (v * h) / 100;\n}",
"parseVersion() {\n var version = this.map_['info']['version'];\n var parsed = '';\n if (goog.isString(version)) {\n parsed = parseInt(version, 10);\n if (isNaN(parsed)) parsed = version;\n else parsed = parsed.toString();\n this.version = parsed;\n }\n }",
"function extGroup_getVersion(groupName)\n{\n var retrievedVersion = parseFloat(dw.getExtDataValue(groupName, \"version\"));\n if (isNaN(retrievedVersion))\n retrievedVersion = 0;\n return retrievedVersion;\n}",
"is_edge_or_ie() {\n\t\t//ie11\n\t\tif( !(window.ActiveXObject) && \"ActiveXObject\" in window )\n\t\t\treturn true;\n\t\t//edge\n\t\tif( navigator.userAgent.indexOf('Edge/') != -1 )\n\t\t\treturn true;\n\t\treturn false;\n\t}",
"showBrowserWarning () {\n let showWarning = false\n let version = ''\n\n // check firefox\n if (window.navigator.userAgent.indexOf('Firefox') !== -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 3).replace(/\\./g, ''))\n\n // lower than 19?\n if (version < 19) showWarning = true\n }\n\n // check opera\n if (window.navigator.userAgent.indexOf('OPR') !== -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 1))\n\n // lower than 9?\n if (version < 9) showWarning = true\n }\n\n // check safari, should be webkit when using 1.4\n if (window.navigator.userAgent.indexOf('Safari') !== -1 && window.navigator.userAgent.indexOf('Chrome') === -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 3))\n\n // lower than 1.4?\n if (version < 400) showWarning = true\n }\n\n // check IE\n if (window.navigator.userAgent.indexOf('MSIE') === -1) {\n // get version\n version = parseInt(window.navigator.appVersion.substr(0, 1))\n\n // lower or equal than 6\n if (version <= 6) showWarning = true\n }\n\n // show warning if needed\n if (showWarning) $('#showBrowserWarning').show()\n }",
"findMaxEdgeValue(){\n let heaviestEdgeWeight = 0;\n for (let edge of this.props.edges) {\n if (edge.weight > heaviestEdgeWeight) {\n heaviestEdgeWeight = edge.weight;\n }\n }\n return heaviestEdgeWeight;\n }",
"get serverVersion() {\n\t\tif (!this._devMode) console.log(\"Implement to override the default server version of 10.1\");\n\t\treturn 10.1;\n\t}",
"function getVersionNumberFromTagName(strTag) {\n const match = strTag.match(/^v(\\d+)$/);\n if (match) {\n const versionNumber = Number.parseInt(match[1]);\n if (!(versionNumber.toString().length == strTag.length - 1)) {\n exit(`Sanity check failed. Expected ${versionNumber} to be one character shorter than ${strTag}.`)\n }\n return versionNumber;\n }\n else {\n return null;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Borrar mensajes anteriores. Elimina el contendio del elemento llamado mensaje. | function borrarMensajes() {
let mensaje = document.getElementById("mensaje");
mensaje.innerHTML="";
} | [
"function prevMsgDelete() {\n message.delete([300])\n .then(msg => console.log(`Deleted message from ${msg.author.username}`))\n .catch(console.error);\n }",
"function removeMensagem (mensagem, idCampo) {\n let campoAtrelado = mensagensCampos[idCampo];\n\n if (campoAtrelado.length > 0 && campoAtrelado.indexOf(mensagem) !== -1) {\n campoAtrelado = campoAtrelado.filter(msg => msg !== mensagem);\n }\n\n mensagensCampos[idCampo] = campoAtrelado;\n return renderizaMensagens(containersMensagens[idCampo], campoAtrelado);\n}",
"function clear() {\n messages = [];\n }",
"function clearSomeMessages(){\n for(var i=0;i<10;i++){\n $(DOMelements.botBody+\" div:first-child\").remove();\n }\n messagesNum=0;\n }",
"function remove(message) {\n //Get the index of the message to be removed\n var idx = messages.indexOf(message);\n messages.splice(idx, 1);\n }",
"function cleanupReplies(message, userId) {\n bot.channels.get(curryBotChannel).fetchMessages().then(function(messages) {\n messages.forEach(function (msg) {\n if (msg.author.bot && msg.id !== message.id && msg.mentions.users.first()) {\n if (msg.mentions.users.first().id === userId) {\n msg.delete().then(function() {\n console.log(msg.id + \" deleted.\");\n }).catch(err => console.log(err));\n }\n }\n })\n }).catch(err => console.log(err));\n}",
"function borrarRegistro(){\n \n /*aId.splice(posicion,1);\n aDireccion.splice(posicion,1);\n aLatitud.splice(posicion,1);\n aLongitud.splice(posicion,1);\n */\n\n aContenedor.splice(posicion,1)\n contador--;\n\n\n posicion=0;\n mostrarRegistro(posicion);\n\n}",
"forgetMe(resource) {\n let result = this.searchMessages({modelName: MESSAGE, to: resource, isForgetting: true})\n let batch = []\n let ids = []\n result.forEach((r) => {\n let id = utils.getId(r)\n batch.push({type: 'del', key: id})\n ids.push(id)\n })\n let id = utils.getId(resource)\n ids.push(id)\n batch.push({type: 'del', key: id})\n return db.batch(batch)\n .then(() => {\n ids.forEach((id) => {\n this.deleteMessageFromChat(utils.getId(resource), this._getItem(id))\n delete list[id]\n })\n this.trigger({action: 'messageList', modelName: MESSAGE, to: resource, forgetMeFromCustomer: true})\n return this.meDriverSignAndSend({\n object: { [TYPE]: FORGOT_YOU },\n to: { permalink: resource[ROOT_HASH] }\n })\n })\n .catch((err) => {\n debugger\n })\n }",
"desencolar()\r\n {\r\n if(this.primero === this.final)\r\n {\r\n return null;\r\n } \r\n const info = this.elemento[this.primero];\r\n delete this.elemento[this.primero];\r\n this.primero++;\r\n return info;\r\n }",
"removeAllReaction(req, res) {\n Thought.findOneAndUpdate(\n { _id: req.params.thoughtId },\n { $pull: { reactions: req.body } },\n { new: true, runValidators: true }\n )\n .select('-__v')\n .then(thoughtData => {\n if (!thoughtData) {\n res.status(404).json({ message: 'No reaction found with that ID.' });\n return;\n }\n res.json({ message: 'All reactions removed from this thought.', thoughtData });\n })\n .catch(err => res.status(400).json(err));\n }",
"function clearPlayerOneChat(i) {\n if (i.toLowerCase() == \"clear\") {\n for (var j = 0; j < self.playerOneMessages.length + 1; j++) {\n self.playerOneMessages.$remove(j);\n }\n }\n }",
"removeMessage(keyNum){\n this.messages.delete(keyNum)\n return this;\n }",
"function accionEliminar()\t{\n\t\tvar arr = new Array();\n\t\tarr = listado1.codSeleccionados();\n\t\teliminarFilas(arr,\"DTOEliminarMatricesDescuento\", mipgndo, 'resultadoOperacionMsgPersonalizado(datos)');\n\t}",
"function borrarDatos(parId, parTipTerritorio, parTerritorio) {\n var re = confirm(\"Vas a borrar estos datos: \" + \" - Tipo \" + parTipTerritorio + \" - Territorio \" + parTerritorio + '...' + \" ¿Estas seguro?\");\n if (re == true) {\n db.collection(\"usuarios\").doc(parId).delete()\n .then(function () {\n console.log(\"Usuario borrado correctamente.\");\n }).catch(function (error) {\n console.error(\"Error borrando el usuario: \", error);\n });\n }\n}",
"static async unstarAll() {\n await this.env.services.rpc({\n model: 'mail.message',\n method: 'unstar_all',\n });\n }",
"function alertMessageRemoval() {\n\t\t\talert.css('display', 'none');\n\t\t}",
"function cleanNoResulstMessage(){\n const noResultsParagraph = document.getElementById('noResultsMessage');\n if (noResultsParagraph){\n const parent = noResultsParagraph.parentNode;\n parent.removeChild(noResultsParagraph);\n }\n}",
"function removeAllmsg() {\n alertAdded.style.display = 'none';\n alertAdded.innerHTML = '';\n\n alertRemoved.style.display = 'none';\n alertRemoved.innerHTML = '';\n\n alertModified.style.display = 'none';\n alertModified.innerHTML = '';\n}",
"function deleteMessage(req, res, user) {\n // Get the message ID.\n var messageID = parseInt(req.params.id);\n\n if (!messageID || messageID < 0) {\n res.status(400).json({message: 'invalid id'});\n\n return;\n }\n\n MessageController.getByMID(messageID)\n .then((message) => {\n if (message.recipient != user.userID) {\n res.status(403).json({message: 'not allowed'});\n\n return;\n }\n\n MessageController.deleteByMID(messageID);\n res.json({message: 'success'});\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
2. Divisible by 7 and 5 | function divisible7and5(number){
if((number % 7 === 0) & (number % 5 === 0))
{
console.log(true);
}
else
{
console.log(false);
}
} | [
"function is_odd_or_div_by_7(number)\n{\n\treturn(number % 7 == 0 || number % 2 != 0)\n}",
"function multipleOfFive(num){\n return num%5 === 0 \n}",
"function multipleOf7Or11(n1, n2) {\n if (n1 % 7 === 0 || n1 % 11 === 0 || n2 % 7 === 0 || n2 % 11 === 0) {\n return true;\n } else {\n return false;\n }\n}",
"function multiples(n) {\n var sum = 0;\n for (var i = 0; i < n; i++) {\n if (i%5 === 0 || i%7 === 0) {\n sum = sum + i;\n }\n }\n return sum;\n}",
"function divByFive(num){\n return num/5\n}",
"function divisibleBy3And7() {\n 'use strict';\n var resultContainer = document.getElementById('resultContainer'),\n n = getValue('number'),\n resultStr = '';\n\n if (!isNaN(n)) {\n for (var i = 1; i <= n; i++) {\n if (i > 1) {\n if (i % 3 !== 0 || i % 7 !== 0) {\n resultStr += '<br/>' + i;\n }\n } else {\n resultStr += i;\n }\n }\n } else {\n resultStr = 'The value of your input is NaN';\n }\n\n displayResult(resultContainer, resultStr);\n}",
"function hasDivisableBy5(array) {\n\tvar bool = false;\n\tarray.forEach(function(number) {\n\t\tif(number % 5 === 0) {\n\t\t\tbool = true;\n\t\t} \n\t});\n\treturn bool;\n}",
"function funcNumbers02() {\n var numberN = document.getElementById('num02').value;\n for (var i = 1; i <= numberN; i++) {\n if (i % 3 != 0 || i % 7 != 0) {\n console.log(i);\n }\n }\n}",
"function isDiv (number) {\n var number;\n if (number % 3 === 0 && number % 5 === 0) {\n \treturn \"BOTH\";\n \t} \n\telse if (number % 3 === 0) { \n return \"THREE\";\n \t} \n\telse if (number % 5 === 0){\n return \"FIVE\";\n \t}\n \telse {\n return number;\n }\n}",
"function divisionBy5(num) {\n\treturn (num / 5);\n}",
"function complicatedMath(n1,n2,n3,n4){\n return (n1+n2) % (n3-n4)\n}",
"function divisibleByB(a, b) {\n\treturn a - a % b + b;\n}",
"function evenNumbers(numbers) {\n return numbers % 2 == 0;\n\n}",
"function isEvenHackReactor(num) {\n if (num % 2 === 0){\n return true;\n } else if (num % 3 === 0) {\n return false;\n }\n}",
"function isDivisible(argument1, argument2) {\n if ((argument1/argument2) % 2 === 0){\n return true;\n }\n else {\n return false;\n }\n}",
"function remainderOfFives({ first, second }) {\n if (first === second) return 0;\n if (first % 5 === second % 5) return Math.min(first, second);\n return Math.max(first, second);\n}",
"function divBy4(num){\n return num/4\n\n}",
"function multiplesOfSix() {\n let count = 6\n while (count <= 60000) {\n if (count % 6 == 0) {\n console.log(count)\n }\n count++\n }\n}",
"function dividesEvenly(a, b) {\n\tif (a%b === 0) {\n\t\treturn true;\n\t} else return false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Markdown to HTML with options | function html(markdown) {
// Thanks to @GrahamSH-LLK for helping with this
var converter = new showdown.Converter({
backslashEscapesHTMLTags: true,
simplifiedAutoLink: true,
tables: true
});
// GitHub like markdown
showdown.setFlavor("github");
// Finally actually use markdown
var output = converter.makeHtml(markdown);
return output;
} | [
"function Markdown(text){var parser;return\"undefined\"==typeof arguments.callee.parser?(parser=eval(\"new \"+MARKDOWN_PARSER_CLASS+\"()\"),parser.init(),arguments.callee.parser=parser):parser=arguments.callee.parser,parser.transform(text)}",
"function md(options, cb) {\n var remarkable = new Remarkable();\n // cb(null, remarkable.render(options.fn()));\n options.fn(this, function(err, content) {\n if (err) return cb(err);\n cb(null, remarkable.render(content));\n });\n}",
"function previewMarkdown() {\n $( \"#preview\" ).html(markdown.toHTML($( \"#content\" ).val()));\n}",
"async renderHtml () {\n let html = marked(this.markdown, {\n highlight (code, lang) {\n // Language may be undefined (GH#591)\n if (!lang) {\n return code\n }\n\n if (DIAGRAM_TYPE.includes(lang)) {\n return code\n }\n\n const grammar = Prism.languages[lang]\n if (!grammar) {\n console.warn(`Unable to find grammar for \"${lang}\".`)\n return code\n }\n return Prism.highlight(code, grammar, lang)\n },\n emojiRenderer (emoji) {\n const validate = validEmoji(emoji)\n if (validate) {\n return validate.emoji\n } else {\n return `:${emoji}:`\n }\n },\n mathRenderer (math, displayMode) {\n return katex.renderToString(math, {\n displayMode\n })\n }\n })\n html = sanitize(html, EXPORT_DOMPURIFY_CONFIG)\n const exportContainer = this.exportContainer = document.createElement('div')\n exportContainer.classList.add('ag-render-container')\n exportContainer.innerHTML = html\n document.body.appendChild(exportContainer)\n // render only render the light theme of mermaid and diragram...\n this.renderMermaid()\n await this.renderDiagram()\n let result = exportContainer.innerHTML\n exportContainer.remove()\n // hack to add arrow marker to output html\n const pathes = document.querySelectorAll('path[id^=raphael-marker-]')\n const def = '<defs style=\"-webkit-tap-highlight-color: rgba(0, 0, 0, 0);\">'\n result = result.replace(def, () => {\n let str = ''\n for (const path of pathes) {\n str += path.outerHTML\n }\n return `${def}${str}`\n })\n this.exportContainer = null\n return result\n }",
"function generateMarkdown(readmeData) {\n return `\n # ${readmeData.projectName}\n ${selectBadge(readmeData.license)}\n ## Description\n ${readmeData.description}\n ## Table of Contents\n * [Installation](#installation)\n * [Usage](#usage)\n * [License](#license)\n * [Contributing](#contributors)\n * [Tests](#tests)\n * [Questions](#questions)\n ## Installation\n To install the necessary dependencies, run the following command in your command line: \n ${readmeData.installation}\n ## Usage\n ${readmeData.usage}\n ## License \n This project is covered by ${readmeData.license}.\n ## Contributing\n ${readmeData.userInfo}\n ## Tests\n To run tests, run the following command: \n ${readmeData.test}\n ## Questions\n If you have questions about the project or run into issues, contact me at ${readmeData.email}. You can access more of my work at [${readmeData.github}](https://github.com/${readmeData.github})\n `;\n }",
"function initShowdownExt() {\n var markdownMarkpageExt = function(converter) {\n return [{\n type: 'output',\n filter: function(text) {\n var $ext = $('<div>' + text + '</div>');\n $ext.find('pre').addClass('prettyprint');\n var $root = $('<ul class=\"menu H1\" />');\n var $docmenu = $('.docmenu');\n $docmenu.append($root);\n\n $ext.find('h1,h2,h3,h4').each(function(i, el) {\n var $el = $(el);\n var tagName = $el[0].tagName;\n var tagNum = tagName.replace('H', '');\n var linkHtml = '<a href=\"#' + $el.attr('id') + '\" >' + $el.html() + '</a>';\n var parentTag = [];\n for (var i = 1; i <= tagNum; i++) {\n parentTag.push('.H' + i);\n }\n var $parentUL = $docmenu.find(parentTag.join(',')).last();\n var $li = $('<li />').html(linkHtml);\n $li.append('<ul class=\"H' + (++tagNum) + '\" />');\n $parentUL.append($li);\n });\n return $ext.html();\n }\n }];\n };\n\n // Client-side export\n if (typeof window !== 'undefined' && window.showdown && window.showdown.extensions) {\n window.showdown.extensions.markpage = markdownMarkpageExt;\n }\n }",
"function processSimpleTypeAsMarkdown(diff,showMarkdownDiffCode){\n diff.forEach(function(part){\n // Render as markdown result\n var modifier = part.added ? \"+ \" : part.removed ? \"- \" : \" \";\n showMarkdownDiffCode += modifier + part.value + \"\\n\";\n });\n return showMarkdownDiffCode;\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 }",
"function render(text) {\n // Do some custom replacements.\n text = text.replace(/#kan#/g, '<span class=\"kanji-highlight highlight-kanji\" rel=\"tooltip\" data-original-title=\"Kanji\">');\n text = text.replace(/#\\/kan#/g, '</span>');\n\n text = text.replace(/#rad#/g, '<span class=\"radical-highlight highlight-radical\" rel=\"tooltip\" data-original-title=\"Radical\">');\n text = text.replace(/#\\/rad#/g, '</span>');\n\n text = text.replace(/#read#/g, '<span class=\"reading-highlight highlight-reading\" rel=\"tooltip\" data-original-title=\"Reading\">');\n text = text.replace(/#\\/read#/g, '</span>');\n\n text = text.replace(/#voc#/g, '<span class=\"vocabulary-highlight highlight-vocabulary\" rel=\"tooltip\" data-original-title=\"Vocabulary\">');\n text = text.replace(/#\\/voc#/g, '</span>');\n\n // Render the rest as markdown.\n return (new showdown.Converter()).makeHtml(text);\n }",
"getPandocAst() {\n return tokens && markdownItPandocRenderer(tokens, this.converter.options);\n }",
"render(){\n return(\n <div className=\"container-fluid d:flex\" id=\"main\">\n \n <div id=\"textAreaContainer\">\n <h3 id=\"editor-head\">Markdown Editor</h3>\n <textarea className=\"bg-dark \" id=\"editor\" value={this.state.input} onChange={this.handleChange}/>\n </div>\n\n <div id=\"previewContainer\">\n <h3 id=\"preview-head\">Markdown preview</h3>\n <div id=\"preview\" dangerouslySetInnerHTML={{__html:marked(this.state.input,{breaks:true})}}>\n </div>\n </div>\n\n </div>\n );\n }",
"function getMarkdownItInstance() {\n config = getGustaveConfig()\n let markdownItInstance = null\n if (config.markdownIt) {\n markdownItInstance = config.markdownIt()\n } else {\n markdownItInstance = defaultMarkdownIt()\n }\n if (config.highlight) {\n const hljs = require('highlight.js') // https://highlightjs.org/\n markdownItInstance.options.highlight = function(str, lang) {\n if (lang && hljs.getLanguage(lang)) {\n try {\n return hljs.highlight(lang, str).value\n } catch (__) {}\n }\n return '' // use external default escaping\n }\n }\n return markdownItInstance\n}",
"function markdownRollupPlugin({ cwd, prod, ...opts }) {\n\treturn {\n\t\tname: 'markdown',\n\t\tasync resolveId(id, importer) {\n\t\t\tif (id[0] === '\\0') return;\n\t\t\tif (id.startsWith('markdown:')) id = id.slice(9);\n\t\t\telse if (!id.endsWith('.md')) return;\n\t\t\tif (importer) importer = importer.replace(/^[\\0\\b]\\w+:/g, '');\n\t\t\t// if (!prod) {\n\t\t\t// \ttry {\n\t\t\t// \t\t// const resolved = await this.resolve(id, importer, { skipSelf: true });\n\t\t\t// \t\tconst resolved = path.resolve(cwd || '.', path.dirname(importer), id);\n\t\t\t// \t\tconst html = await processMarkdown(resolved, opts);\n\t\t\t// \t\treturn `data:text/javascript,${encodeURIComponent('export default ' + JSON.stringify(html))}`;\n\t\t\t// \t\t// const code = await p.load.call(this, `\\0markdown:${path.join(path.dirname(importer), id)}`);\n\t\t\t// \t\t// return `data:text/javascript,${encodeURIComponent(code)}`;\n\t\t\t// \t} catch (err) {\n\t\t\t// \t\tconsole.log('failed to resolve: ', err);\n\t\t\t// \t}\n\t\t\t// }\n\t\t\treturn `\\0markdown:${path.join(path.dirname(importer), id)}`;\n\t\t\t// const resolved = await this.resolve(id, importer, { skipSelf: true });\n\t\t\t// if (resolved) return '\\0markdown:' + resolved.id;\n\t\t\t// if (id.endsWith('.md')) return '\\0markdown:' + path.join(path.dirname(importer), id);\n\t\t\t// if (id.endsWith('.md')) {\n\t\t\t// return this.resolve(id + '.js', importer, { skipSelf: true });\n\t\t\t// }\n\t\t},\n\t\tasync load(id) {\n\t\t\t// if (!id.endsWith('.md')) return;\n\t\t\t// if (!id.endsWith('.md.js')) return;\n\t\t\t// id = id.replace(/\\.js$/g, '');\n\t\t\t// const html = marked(await fs.readFile(id, 'utf-8'), opts);\n\t\t\t// return `export default ${JSON.stringify(html)}`;\n\n\t\t\tif (!id.startsWith('\\0markdown:')) return;\n\t\t\tid = path.resolve(cwd || '.', id.slice(10));\n\n\t\t\tthis.addWatchFile(id);\n\t\t\tconst html = await processMarkdown(id, opts);\n\n\t\t\t// if (!prod) {\n\t\t\t// \treturn `export default ${JSON.stringify(html)};`;\n\t\t\t// }\n\n\t\t\t// console.log(path.relative(cwd || '.', id));\n\t\t\tconst fileId = this.emitFile({\n\t\t\t\ttype: 'asset',\n\t\t\t\tname: path.relative(cwd || '.', id),\n\t\t\t\tfileName: path.relative(cwd || '.', id),\n\t\t\t\tsource: html\n\t\t\t});\n\t\t\treturn `export default import.meta.ROLLUP_FILE_URL_${fileId}`;\n\t\t}\n\t\t// transform(code, id) {\n\t\t// \tcode = code.replace(/(\\bimport\\s*\\(\\s*)(.*?)(\\s*\\))/g, (s, b, arg, a) => {\n\t\t// \t\t// arg = arg.replace(/(?:\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*(\\n))/g, '$1');\n\t\t// \t\targ = arg.replace(/\\s*\\/\\*[\\s\\S]*?\\*\\/\\s*/g, '');\n\t\t// \t\tlet scheme;\n\t\t// \t\targ = arg.replace(/^(['\"`])([a-z0-9-]+)\\:(\\.*\\/)/, (s, q, _scheme, start) => {\n\t\t// \t\t\tscheme = _scheme;\n\t\t// \t\t\treturn q + start;\n\t\t// \t\t});\n\t\t// \t\tif (scheme) arg += '+\"?_scheme=' + scheme + '\"';\n\t\t// \t\tconsole.log(b, arg, a);\n\t\t// \t\treturn b + arg + a;\n\t\t// \t\t// return s;\n\t\t// \t});\n\t\t// \treturn { code, map: null };\n\t\t// }\n\t};\n}",
"function renderAsMarkdown(method,oldStr,newStr,options){\n var showMarkdownDiffCode = \"\";\n var diff;\n switch (method) {\n case \"diffChars\":\n options = Object.assign({}, (options || {}),{\"ignoreCase\":false});\n diff = Diff.diffChars(oldStr, newStr,options);\n showMarkdownDiffCode = processSimpleTypeAsMarkdown(diff,showMarkdownDiffCode)\n break; \n case \"diffWords\":\n options = Object.assign({}, (options || {}),{\"ignoreCase\":false});\n diff = Diff.diffWords(oldStr, newStr,options);\n showMarkdownDiffCode = processSimpleTypeAsMarkdown(diff,showMarkdownDiffCode)\n break; \n case \"diffWordsWithSpace\":\n options = Object.assign({}, (options || {}),{\"ignoreCase\":false});\n diff = Diff.diffWordsWithSpace(oldStr, newStr,options);\n showMarkdownDiffCode = processSimpleTypeAsMarkdown(diff,showMarkdownDiffCode)\n break; \n case \"diffLines\":\n options = Object.assign({}, (options || {}),{\"ignoreCase\":false,\"newlineIsToken\":false});\n diff = Diff.diffLines(oldStr, newStr,options);\n showMarkdownDiffCode = processSimpleTypeAsMarkdown(diff,showMarkdownDiffCode)\n break; \n case \"diffTrimmedLines\":\n options = Object.assign({}, (options || {}),{\"ignoreCase\":false,\"newlineIsToken\":false});\n diff = Diff.diffTrimmedLines(oldStr, newStr,options);\n showMarkdownDiffCode = processComplexTypeAsMarkdown(diff,showMarkdownDiffCode)\n break; \n case \"diffSentences\":\n options = Object.assign({}, (options || {}),{\"ignoreCase\":false,\"newlineIsToken\":false});\n diff = Diff.diffSentences(oldStr, newStr,options);\n showMarkdownDiffCode = processComplexTypeAsMarkdown(diff,showMarkdownDiffCode)\n break; \n case \"diffJson\":\n options = Object.assign({}, (options || {}),{\"ignoreCase\":false,\"newlineIsToken\":false});\n if(Object.prototype.toString.call(oldStr) === '[object String]'){\n oldStr = JSON.parse(oldStr);\n }\n if(Object.prototype.toString.call(newStr) === '[object String]'){\n newStr = JSON.parse(newStr);\n }\n diff = Diff.diffJson(oldStr, newStr);\n var diffObj = [];\n diff.forEach(function(part){\n // Render as markdown result\n var modifier = part.added ? \"+ \" : part.removed ? \"- \" : \" \";\n part.value.split(\"\\n\").forEach(function(item){\n if(item){\n if(item == \"{\" || item == \"}\"){\n showMarkdownDiffCode += item + \"\\n\";\n }else{\n showMarkdownDiffCode += modifier + item + \"\\n\";\n }\n }\n });\n });\n break;\n case \"diffArrays\":\n // Render as markdown result\n if(Object.prototype.toString.call(oldStr) === '[object String]'){\n oldStr = JSON.parse(oldStr);\n }\n if(Object.prototype.toString.call(newStr) === '[object String]'){\n newStr = JSON.parse(newStr);\n }\n diff = Diff.diffArrays(oldStr, newStr);\n var diffArr = [];\n diff.forEach(function(part){\n var modifier = part.added ? \"+ \" : part.removed ? \"- \" : \" \";\n part.value.forEach(function(item){\n if(item){\n diffArr.push(modifier + item);\n }\n });\n });\n showMarkdownDiffCode += \"[\\n\";\n diffArr.forEach(function(diffItem){\n showMarkdownDiffCode += diffItem + \"\\n\";\n });\n showMarkdownDiffCode += \"]\";\n break;\n }\n return showMarkdownDiffCode;\n}",
"_createMarkdownCell(model) {\n const rendermime = this.rendermime;\n const contentFactory = this.contentFactory;\n const editorConfig = this.editorConfig.markdown;\n const options = {\n editorConfig,\n model,\n rendermime,\n contentFactory,\n updateEditorOnShow: false,\n placeholder: false\n };\n const cell = this.contentFactory.createMarkdownCell(options, this);\n cell.syncCollapse = true;\n cell.syncEditable = true;\n return cell;\n }",
"function html(note, formatter, done) {\n var formattedResources = {};\n\n if(!done) {\n done = formatter;\n formatter = null;\n }\n\n if(note.resources && formatter) {\n async.each(note.resources,\n function(resource, nextResource) {\n var resourceHash = new Buffer(resource.data.bodyHash).toString('hex');\n formatter(resource, function(err, replacement) {\n formattedResources[resourceHash] = replacement;\n nextResource(err);\n });\n },\n function(err) {\n console.log(formattedResources);\n done(note.content);\n }\n );\n } else {\n console.log('No resources');\n done(note.content);\n }\n\n}",
"_createMarkdownCellOptions(text = '') {\n const contentFactory = this.contentFactory.markdownCellContentFactory;\n const model = new cells_1.MarkdownCellModel({});\n this._disposables.add(model);\n const rendermime = this._rendermime;\n model.value.text = text || '';\n return { model, rendermime, contentFactory };\n }",
"function fetchMarkdown() {\n var di = diNotify('Fetching Markdown...');\n return $http.post('factory/fetch_markdown', {\n name: documentsService.getCurrentDocumentTitle(),\n unmd: documentsService.getCurrentDocumentBody()\n }).success(function(response) {\n if (di.$scope !== null) {\n di.$scope.$close();\n }\n // This is needed to set the right path on the iframe.\n service.type = 'md';\n service.file = response.data;\n return response.data;\n }).error(function(err) {\n return diNotify({\n message: 'An Error occured: ' + err\n });\n });\n }",
"switchToMarkdown() {\n this.$containerEl.removeClass('te-ww-mode');\n this.$containerEl.addClass('te-md-mode');\n }",
"function processComplexTypeAsMarkdown(diff,showMarkdownDiffCode){\n diff.forEach(function(part){\n // Render as markdown result\n var modifier = part.added ? \"+ \" : part.removed ? \"- \" : \" \";\n part.value.split(\"\\n\").forEach(function(item,index){\n if(item){\n showMarkdownDiffCode += modifier + item + \"\\n\";\n }\n });\n });\n return showMarkdownDiffCode;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
define the bookmark class | function BookmarkClass() {
// a variable to store marker data as it is retrieved
this.data = { contributors: [],
organisations: [],
venues: [],
events: [],
works: []
};
} | [
"_setBookmark() {\n const { isLogged, type } = this._props;\n const {\n bookmarkLoggedinTemplate, bookmarkNotLoggedTemplate, bookmarkSavednewsTemplate, cardBookmark,\n } = this._blockElements;\n const bookmarkNode = this._domElement.querySelector(cardBookmark);\n let template;\n\n if (isLogged && type === 'main') {\n template = bookmarkLoggedinTemplate;\n } else if (!isLogged && type === 'main') {\n template = bookmarkNotLoggedTemplate;\n } else if (isLogged && type === 'saved') {\n template = bookmarkSavednewsTemplate;\n }\n\n const bookmarkElement = template.cloneNode(true).content;\n bookmarkNode.appendChild(bookmarkElement);\n }",
"linkBookmarkManager()\n {\n var searchText;\n if (this.state.bookmark.url)\n {\n searchText=this.state.bookmark.url;\n }\n\n else\n {\n searchText=this.state.bookmark.title;\n }\n\n chrome.tabs.create({\n url:`chrome://bookmarks/?q=${encodeURI(searchText)}`,\n active:true\n });\n }",
"Bookmark(SpeechBookmarkOptions, Variant, Variant) {\n\n }",
"function bookmarkCB (div) {\n\tupdateBrain (function () {\n\t\tdoXML (\"sendbookmark&\" + div.getElementsByClassName(\"url\")[0].innerHTML, null)\n\t})\n}",
"function setBookmark(location) {\n setValue('cmi.core.lesson_location', location);\n}",
"importFromBookmarksFile() {}",
"function displayBookmark(myHeading,myURL){\n var mainBookmarksDisplay = document.getElementById(\"bookmarks\");\n var bookmark = document.createElement('div');\n\t\n var bookmarkText = document.createElement('a');\n\tbookmarkText.innerHTML = myHeading;\n\tbookmarkText.setAttribute('name', myHeading);\n\tbookmarkText.setAttribute('id', myURL);\n bookmarkText.setAttribute('onclick', 'onBookmarkClick(this.name,this.id)' );\n \n\t\n\tvar buttonnode= document.createElement('i');\n buttonnode.setAttribute('type','button');\n\tmyURL += \"_B\"; //to give bookmark remove button an id different from its feed div, so specified bookmark or feed div can be deleted. \n buttonnode.id = myURL;\n buttonnode.setAttribute('class','icon-remove');\n buttonnode.setAttribute('onclick', 'delBookmark(this.id)' );\n\t\n\tdivider = document.createElement('li');\n\tdivider.setAttribute('class','divider');\n\t\n\tbookmark.appendChild(buttonnode);\n\tbookmark.appendChild(bookmarkText);\n\tbookmark.appendChild(divider);\n\t\n\tmainBookmarksDisplay.appendChild(bookmark);\n}",
"async addBookmark(bookmark) {\n await this.client('bookmark')\n .insert(bookmark)\n .onConflict('href')\n .merge();\n }",
"toggleBookmark() {\n\t\t\tthis.$log.debug('toggle bookark');\n\t\t\t\n\t\t\t//hide side navigation\n\t\t\tthis.sideNavService.hide();\n\t\t\t\n\t\t\tconst bookmarks = this.localStorageService.get(settings.LOCAL_STORAGE_KEY.BOOKMARKS) || {};\n\t\t\tif(this.isBookmarked){\n\t\t\t\tdelete bookmarks[this.reviewId];\n\t\t\t} else {\n\t\t\t\tbookmarks[this.reviewId] = this.detail;\n\t\t\t}\n\t\t\t//toggle\n\t\t\tthis.isBookmarked = !this.isBookmarked;\n\t\t\t//update local storage\n\t\t\tthis.localStorageService.set(settings.LOCAL_STORAGE_KEY.BOOKMARKS, bookmarks);\n\t\t}",
"function BookmarksPortletData( namespace,\n bookmark_form_newWindow,\n bookmark_form_url,\n bookmark_forms_empty,\n bookmark_forms_error,\n bookmark_reference_url,\n bookmarksTreeAndForm,\n entry_childFolderPrefix,\n entry_edit_cancelLink,\n entry_edit_editLink,\n entry_form_action,\n entry_form_action_editBookmark,\n entry_form_action_editFolder,\n entry_form_action_editCollection,\n entry_form_action_newBookmark,\n entry_form_action_newFolder,\n entry_form_action_newCollection,\n entry_form_folderPath,\n entry_form_folderPathLabel,\n entry_form_idPath,\n entry_form_name,\n entry_form_note,\n entry_imagePrefix,\n entry_reference_folderPath,\n entry_reference_name,\n entry_reference_note,\n folder_forms_empty,\n folder_forms_error,\n folder_image_closed,\n folder_image_open,\n collection_form_url,\n collection_forms_empty,\n collection_forms_error,\n options_form,\n options_showLink,\n messages_folder_create,\n messages_folder_move,\n messages_delete_bookmark_prefix,\n messages_delete_bookmark_suffix,\n messages_delete_folder_prefix,\n messages_delete_folder_suffix,\n messages_delete_collection_prefix,\n messages_delete_collection_suffix) {\n\n this.namespace = namespace;\n\n this.bookmark_form_newWindow = bookmark_form_newWindow;\n this.bookmark_form_url = bookmark_form_url;\n this.bookmark_forms_empty = bookmark_forms_empty;\n this.bookmark_forms_error = bookmark_forms_error;\n this.bookmark_reference_url = bookmark_reference_url;\n this.bookmarksTreeAndForm = bookmarksTreeAndForm;\n this.entry_childFolderPrefix = entry_childFolderPrefix;\n this.entry_edit_cancelLink = entry_edit_cancelLink;\n this.entry_edit_editLink = entry_edit_editLink;\n this.entry_form_action = entry_form_action;\n this.entry_form_action_editBookmark = entry_form_action_editBookmark;\n this.entry_form_action_editFolder = entry_form_action_editFolder;\n this.entry_form_action_editCollection = entry_form_action_editCollection;\n this.entry_form_action_newBookmark = entry_form_action_newBookmark;\n this.entry_form_action_newFolder = entry_form_action_newFolder;\n this.entry_form_action_newCollection = entry_form_action_newCollection;\n this.entry_form_folderPath = entry_form_folderPath;\n this.entry_form_folderPathLabel = entry_form_folderPathLabel;\n this.entry_form_idPath = entry_form_idPath;\n this.entry_form_name = entry_form_name;\n this.entry_form_note = entry_form_note;\n this.entry_imagePrefix = entry_imagePrefix;\n this.entry_reference_folderPath = entry_reference_folderPath;\n this.entry_reference_name = entry_reference_name;\n this.entry_reference_note = entry_reference_note;\n this.collection_form_url = collection_form_url;\n this.collection_forms_empty = collection_forms_empty;\n this.collection_forms_error = collection_forms_error;\n this.folder_forms_empty = folder_forms_empty;\n this.folder_forms_error = folder_forms_error;\n this.folder_image_closed = folder_image_closed;\n this.folder_image_open = folder_image_open;\n this.options_form = options_form;\n this.options_showLink = options_showLink;\n this.messages_folder_create = messages_folder_create;\n this.messages_folder_move = messages_folder_move;\n this.messages_delete_bookmark_prefix = messages_delete_bookmark_prefix;\n this.messages_delete_bookmark_suffix = messages_delete_bookmark_suffix;\n this.messages_delete_folder_prefix = messages_delete_folder_prefix;\n this.messages_delete_folder_suffix = messages_delete_folder_suffix;\n this.messages_delete_collection_prefix = messages_delete_collection_prefix;\n this.messages_delete_collection_suffix = messages_delete_collection_suffix;\n\n\n //Handy function for debugging\n function toString() {\n var stringVal = \"BookmarksPortletData[\";\n var hasProperties = false;\n\n for (var property in this) {\n hasProperties = true;\n\n if ((this[property] + \"\").indexOf(\"function \") != 0) {\n stringVal += property + \"=\" + this[property] + \", \";\n }\n }\n \n\n if (hasProperties) {\n stringVal = stringVal.substring(0, stringVal.length - 2);\n }\n\n stringVal += \"]\";\n\n return stringVal;\n }\n this.toString = toString;\n\n //Object registers itself with the global array of data objects\n bookmarkPortletsData[namespace] = this;\n}",
"function markLink( link ) {\r\n\t\t$( link ).addClass( linkCurrentClass );\r\n\t}",
"function getBookmark() {\n return getValue('cmi.core.lesson_location');\n}",
"handleAddClassItemClick(me, cmd, e){\n\n\t\t//create a new class:\n\t\tvar newClassItm = new ClassItem(me.classIDCounter++);\n\n\t\t//add it to ourself\n\t\tme.addClassItm(newClassItm);\n\n\t}",
"function loadBookmarks()\n{\n\n for (ii = 0; ii < maxChapters; ii++)\n {\n\n for (jj = 0; jj <= maxSections; jj++) //Since there are six sections (include chapter start page)\n {\n var name = chapterIDs[ii][jj];\n var currentChapter;\n\n var returnVisitor = window.localStorage.getItem(name);\n if (returnVisitor === null) //No bookmark has been set for this chapter\n {\n currentChapter = new bookmark(name, ((document.getElementById(name)).innerText), null) //indicate no bookmark is set\n }\n else //There is a previous bookmark we want to use now\n {\n var origText = (document.getElementById(name)).innerText; //Store orginal text for use in replacing bookmark later\n (document.getElementById(name)).innerText = (document.getElementById(name)).innerText + returnVisitor; //Push new bookmark onto page\n currentChapter = new bookmark(name, origText, returnVisitor);\n }\n\n chapterMarks[ii][jj] = currentChapter; //Store it for reference later\n\n }\n\n }\n\n}",
"function buildBookmarks(){\n // Remove all bookmark element\n bookmarksContainer.textContent = '';\n // Build items\n bookmarkUI.forEach((el) => {\n const {name, url} = el;\n const item = document.createElement('div');\n item.classList.add('item');\n const nameEl = document.createElement('div');\n nameEl.classList.add('name');\n nameEl.innerHTML = ` \n <i class=\"fas fa-times-circle\" onclick=\"deleteBookmark('${url}')\" id=\"delete-bookmark\"></i>\n <img src=\"https://s2.googleusercontent.com/s2/favicons?domain=${url}\" alt=\"\">\n <a href=\"${url}\" target=\"_blank\">${name}</a>`;\n item.appendChild(nameEl);\n // console.log(item);\n bookmarksContainer.appendChild(item);\n console.log(url);\n })\n}",
"constructor(dataentry) {\n this.dataentry = dataentry;\n // default to tooltips if not specified otherwise\n this.markStyle = dataentry ? (dataentry.options.markStyle || TOOLTIPS) : TOOLTIPS;\n this.options = _.extend({}, DomDecorator.defaults, dataentry && dataentry.options ? dataentry.options.decoratorOptions : {});\n this._elements = [];\n }",
"function saveCB () {\n\tupdateBrain (function () {\n\t\tdoXML (\"getbookmark\", function (responseText) {\n\t\t\t// Parse the returned data\n\t\t\tvar url = responseText.split(\"\\n\")[0]\n\t\t\tvar title = responseText.split(\"\\n\")[1]\n\t\t\tvar tempfilename = responseText.split(\"\\n\")[2]\n\t\t\tvar selection = responseText.split(\"\\n\").slice(3).reduce (function (a,b) { return a + \"\\n\" + b; }, \"\").slice (0, 200)\n\t\t\tif (selection.trim() == \"\") selection = null;\n\n\t\t\t// Save a bookmark (using current state)\n\t\t\tallBookmarks.push (new Bookmark (url, title, tempfilename, selection))\n\n\t\t\t// Optional: Update bookmarks display\n\t\t\tviewAll();\n\t\t})\n\t})\n}",
"function addBookmark(title,url,agent) {\n var db = getDatabase();\n var res = \"\";\n db.transaction(function(tx) {\n // Remove and readd if url already in bookmarks\n removeBookmark(url);\n //console.debug(\"Adding to bookmarks db:\" + title + \" \" + url);\n\n var rs = tx.executeSql('INSERT OR REPLACE INTO bookmarks VALUES (?,?,?);', [title,url,agent]);\n if (rs.rowsAffected > 0) {\n res = \"OK\";\n console.log (\"Saved to database\");\n } else {\n res = \"Error\";\n console.log (\"Error saving to database\");\n }\n }\n );\n // The function returns “OK” if it was successful, or “Error” if it wasn't\n return res;\n}",
"function FavoriteItem () {\n\tthis._init ();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dibuja una linea en el mapa | function dibujaLineaYActualizaMapa(){
var lngRuta, latRuta;
var posicionRutaAnterior;
var posicionRuta;
navigator.geolocation.getCurrentPosition(function(posicion){
lngRuta = posicion.coords.longitude;
latRuta = posicion.coords.latitude;
posicionRuta = new google.maps.LatLng(latRuta, lngRuta);
posicionRutaAnterior = new google.maps.LatLng(latRutaAnterior, lngRutaAnterior);
lineaRuta =
{
path: [posicionRutaAnterior, posicionRuta],
geodesic: true,
strokeColor: '#666633',
strokeOpacity: 1.0,
strokeWeight: 9
};
posicionRuta = new google.maps.Polyline(lineaRuta);
posicionRuta.setMap(mapa);
lngRutaAnterior = lngRuta;
latRutaAnterior = latRuta;
});
} | [
"function createMapLine(){\n\tvar pointX = portMapInfo[0].X;\n\tvar pointY = portMapInfo[0].Y;\n\tvar pointX2 = portMapInfo[0].X2;\n\tvar pointY2 = portMapInfo[0].Y2;\n\tvar mapLine = new Kinetic.Line({\n\t\tpoints: [pointX, pointY, pointX2, pointY2],\n\t\tstroke: 'black',\n\t\tstrokeWidth: 3,\n\t\tlineCap: 'round',\n\t\tlineJoin: 'round',\n\t\tDestination: portMapInfo[0].Destination,\n\t\tSource: portMapInfo[0].Source\n\t});\n\treturn mapLine;\n}",
"function draw_lines(results){\n\n for(i in results.distances){\n for(j in results.distances[i]){\n var line = results.distances[i][j].line;\n // Construct the polygon\n var poly = new google.maps.Polyline({\n path: google.maps.geometry.encoding.decodePath(line),\n geodesic: true,\n strokeColor: '#FF0000',\n strokeOpacity: 1.0,\n strokeWeight: 2\n });\n poly.setMap(map);\n }\n }\n}",
"function leafletAddLineToMap(pointFrom, pointTo) {\n\n // define coordinates for line\n var latlngs = [\n pointFrom.geometry.coordinates,\n pointTo.geometry.coordinates\n ];\n\n // add a marker to the map\n var line = turf.lineString(latlngs);\n L.geoJson(line, {color:\"red\"}).addTo(map);\n}",
"function dibujarLinea(color, x_inicial, y_inicial, x_final, y_final)\n{\n lienzo.beginPath();\n lienzo.strokeStyle = color;\n lienzo.moveTo(x_inicial, y_inicial);\n lienzo.lineTo(x_final, y_final);\n lienzo.stroke();\n lienzo.closePath();\n}",
"function drawPolyLine() {\n\n\n //Keys of the station objects in order from north to south so that the polyline\n //connects them in the right order. \n //Note: I will draw the branch as a separate polyline.\n var stationOrderMain = [ \"alfcl\", \"davis\", \"portr\", \"harsq\", \"cntsq\", \"knncl\",\n \"chmnl\", \"pktrm\", \"dwnxg\", \"sstat\", \"brdwy\", \"andrw\", \"jfk\",\n \"nqncy\", \"wlsta\", \"qnctr\", \"qamnl\", \"brntn\"\n ];\n \n\n //Get the location of each station so we can draw the line.\n var stationLocations = [];\n for (var i = 0; i < stationOrderMain.length; ++i){\n stationLocations.push( Stations[ stationOrderMain[i]].position);\n\n };\n \n //draw the line\n var lineToDraw = new google.maps.Polyline({\n path: stationLocations,\n geodesic: true,\n strokeColor: '#FF0000',\n strokeOpacity: 1.0,\n strokeWeight: 4\n });\n lineToDraw.setMap(map); //set line to map\n\n //Now do the same as above for the branch that forks from JFK.\n var stationOrderBranch = [ \"jfk\", \"shmnl\", \"fldcr\", \"smmnl\", \"asmnl\"]\n stationLocations = [];\n for (var i = 0; i < stationOrderBranch.length; ++i){\n stationLocations.push( Stations[ stationOrderBranch[i]].position);\n };\n \n \n lineToDraw2 = new google.maps.Polyline({\n path: stationLocations,\n geodesic: true,\n strokeColor: '#FF0000',\n strokeOpacity: 1.0,\n strokeWeight: 4\n });\n lineToDraw2.setMap(map);\n\n}",
"breshnamDrawLine (point0, point1) {\n let x0 = point0.x >> 0;\n let y0 = point0.y >> 0;\n let x1 = point1.x >> 0;\n let y1 = point1.y >> 0;\n let dx = Math.abs(x1 - x0);\n let dy = Math.abs(y1 - y0);\n let color = new BABYLON.Color4(1,1,0,1);\n\n if(dy > dx){\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dx - dy;\n\n for(let y=y0; y!=y1; y=y+sy){\n this.drawPoint(new BABYLON.Vector2(x0, y), color);\n if(err >= 0) {\n x0 += sx ;\n err -= dy;\n }\n err += dx;\n }\n }\n else{\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dy - dx;\n\n for(let x=x0; x!=x1; x=x+sx){\n this.drawPoint(new BABYLON.Vector2(x, y0), color);\n if(err >= 0) {\n y0 += sy ;\n err -= dx;\n }\n err += dy;\n }\n }\n }",
"roadLineDrawtest()\n {\n this.direction.route({\n origin:{lng:-78,lat:39.137},\n destination:{lat:39.281,lng:-76.60},\n travelMode:google.maps.TravelMode.DRIVING\n },(r,s)=>{\n var pathPoints=r.routes[0].overview_path;\n var path=new google.maps.Polyline({\n path:pathPoints\n });\n\n path.setMap(this.map);\n });\n }",
"function setGraticule(map, path){\n //create graticule generator\n var graticule = d3.geoGraticule()\n .step([8, 8]); //place graticule lines every 5 degrees of longitude and latitude\n //create graticule background\n var gratBackground = map.append(\"path\")\n .datum(graticule.outline())//bind graticule background\n .attr(\"class\", \"gratBackground\") //assign class for style\n .attr(\"d\", path); //project graticule\n\n //create graticule lines\n var gratLines = map.selectAll(\".gratLines\") //select graticule elements that will be created\n .data(graticule.lines()) //bind graticule lines to each element that will be created\n .enter()\n .append(\"path\") //append each element to the svg as a path element\n .attr(\"class\", \"gratLines\") //assign class for styling\n .attr(\"d\", path);\n }",
"function filterLines(minYear, maxYear) {\n map.removeLayer(mapLines)\n mapLines = createLineLayers(minYear, maxYear)\n mapLines.addTo(map)\n}",
"function _updateLine(args){\n\t\targs.line.setShape({\n\t\t\tx1 : args.startPoint.x,\n\t y1 : args.startPoint.y,\n\t x2 : args.endPoint.x,\n\t y2 : args.endPoint.y\n\t });\n\t\targs.selectArea.setShape({\n\t\t\tx1 : args.startPoint.x,\n\t y1 : args.startPoint.y,\n\t x2 : args.endPoint.x,\n\t y2 : args.endPoint.y\n\t });\n\t}",
"function drawPoweLineCallBack(data, options){\n\tvar newLineShape = options[\"lineShape\"];\n\tvar path = options[\"path\"];\n\tvar dataArray = data.split(\"!\");\n\tvar powerLineId = dataArray[0];\n\tvar color = dataArray[1];\n\tnewLineShape.setOptions({strokeColor:color,path: path});\n\taddMessageWindow(newLineShape,powerLineId)\n\tglobalPlList.set(powerLineId, newLineShape);\n\tvar powerLineAId = dataArray[2];\n\tvar powerLineBId = dataArray[3];\n\tvar holonObjectColor= dataArray[4];\n\tvar holonObjectId = dataArray[5];\n\tvar isCoordinator = dataArray[6];\n\tvar coordinatorLocation=\"\";\n\tvar coordinatorIcon=\"\";\n\tif(typeof powerLineAId != 'undefined' && typeof powerLineBId != 'undefined' && powerLineAId!= 0) {\n\t\t\n\t\tupdateGlobalPowerLineList(powerLineAId,true);\n\t\tupdateGlobalPowerLineList(powerLineBId,false);\n\t}\n\t\n\tif(typeof holonObjectColor != 'undefined' && typeof holonObjectId != 'undefined' && holonObjectId != \"null\" ){\n\t\t var holonObject= globalHoList.get(holonObjectId);\n\t\t holonObject.setOptions({strokeColor:holonObjectColor,fillColor:holonObjectColor });\n\t\t}\n\tif(typeof isCoordinator != 'undefined' && typeof holonObjectId != 'undefined'){\n\t\tif(isCoordinator==\"Yes\"){\n\t\t\tcreateIconOnMap(holonObjectId);\n\t\t}\n\t\telse{\n\t\t\tvar newCoordinatorIds= dataArray[7].split(\"~\");\n\t\t\tvar oldCoordinatorIds= dataArray[8].split(\"~\");\n\t\t\t\n\t\t\tif(oldCoordinatorIds != undefined)\n\t\t\t\t{\n\t\t\t\t\t\tfor (var i=0;i< oldCoordinatorIds.length-1;i++){\n\t\t\t\t\t\t\tvar oldCoordinatorId= oldCoordinatorIds[i];\n\t\t\t\t\t\t\tremoveIconFromMap(oldCoordinatorId);\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tif(newCoordinatorIds != undefined){\n\t\t\t\tfor(var i=0;i< newCoordinatorIds.length-1; i++){\n\t\t\t\t\tvar newCoordinatorId = newCoordinatorIds[i];\n\t\t\t\t\tcreateIconOnMap(newCoordinatorId);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t}\n\t}\n}",
"function newFlowline(){\n resetFlowline();\n flowline.markers[0].enableEdit(map).startDrawing();\n }",
"function drawLine() {\n let draw = game.add.graphics();\n draw.lineStyle(1, 0xffffff, .3);\n\n draw.moveTo(star1.worldPosition.x + 8, star1.worldPosition.y + 8)\n draw.beginFill();\n draw.lineTo(star2.worldPosition.x + 8, star2.worldPosition.y + 8);\n draw.endFill();\n\n connections.push({\n drawer: draw,\n star1: [star1.worldPosition.x + 8, star1.worldPosition.y + 8],\n star2: [star2.worldPosition.x + 8, star2.worldPosition.y + 8]\n });\n deselectStars();\n }",
"function drawRoad(counter){\n //set background\n background(50);\n //Space between lines\n let space = width / 4;\n //Gap between dashed lines\n let step = height / 10;\n //Line width\n let lineW = 10;\n //Road lines\n //Remove outline on shapes\n noStroke();\n //Dashed lines\n for (i = - 2; i < height; i++) {\n //Yellow lines\n fill(255,i * 25, 0);\n rect(space, step * i + counter, 10, 30);\n rect(space * 3, step * i + counter, 10, 30);\n }\n for(i = 0; i < maxH; i++){\n let val = map(i, 0, maxH, 0, 255);\n stroke(255, val, 0);\n line(0, i, lineW, i);\n \n line(space * 2 - lineW, i, space * 2 - lineW * 2, i);\n line(space * 2 + lineW, i, space * 2 + lineW * 2, i);\n line(maxW - lineW, i, maxW, i); \n }\n}",
"function render_aim_helper_line() {\n var c = {\n x: gamer.x + map.planet_w / 2,\n y: gamer.y + map.planet_h / 2\n };\n\n context.setLineDash([]);\n context.lineWidth = 3;\n context.strokeStyle = '#00ff00';\n context.beginPath();\n context.moveTo(c.x, c.y);\n context.lineTo(c.x + 2 * map.planet_w * Math.cos(deg_to_rad(gamer.angle)), c.y - 2 * map.planet_h * Math.sin(deg_to_rad(gamer.angle)));\n context.stroke();\n }",
"function addAnnotationsLine(g) {\r\n g.append(\"line\")\r\n .attr(\"x1\", x(1) )\r\n .attr(\"x2\", x(3) )\r\n .attr(\"y1\", y(160))\r\n .attr(\"y2\", y(160))\r\n .attr(\"stroke\", \"grey\")\r\n .attr(\"stroke-dasharray\", \"4\")\r\n}",
"function createLine(start, end) {\n\t\t\t//create polyline\n\t\t\tvar polyline = new esri.geometry.Polyline(map.spatialReference);\n\t\t\tpolyline.addPath([start, end]);\n\t\t\t//convert to wgs84 and densify to show shortest great circle path\n\t\t\tvar geodesicGeomGeo = esri.geometry.geodesicDensify(esri.geometry.webMercatorToGeographic(polyline), 100000);\n\t\t\t//convert from wgs84 to web mercator for display\n\t\t\tvar geodesicGeom = esri.geometry.geographicToWebMercator(geodesicGeomGeo);\n\t\t\treturn geodesicGeom;\n\t\t}",
"function drawLine(svg){\t\n\t\t\tsvg.style.strokeOpacity = '0.6';\n\t\t\tvar length = svg.getTotalLength();\n\t\t\t// Clear any previous transition\n\t\t\tsvg.style.transition = svg.style.WebkitTransition ='none';\n\t\t\t// Set up the starting positions\n\t\t\tsvg.style.strokeDasharray = length + ' ' + length;\n\t\t\tsvg.style.strokeDashoffset = length;\n\t\t\t// Trigger a layout so styles are calculated & the browser\n\t\t\t// picks up the starting position before animating\n\t\t\tsvg.getBoundingClientRect();\n\t\t\t// Define our transition\n\t\t\tsvg.style.transition = svg.style.WebkitTransition = 'stroke-dashoffset 2s ease-in-out';\n\t\t\t// Go!\n\t\t\tsvg.style.strokeDashoffset = '0';\n\t\t}",
"function toggleLine(selectedLineData, clickedOn, newThickness) {\n lines = d3.selectAll('polyline')\n for (i = 0; i < lines.length; i++) {\n for (j = 0; j < lines[i].length; j++) {\n if (lines[i][j].__data__['State'] == selectedLineData['State']) {\n if (clickedOn) {\n lines[i][j].style.stroke = mouseOverColor\n } else {\n lines[i][j].style.stroke = getStroke(lines[i][j].__data__)\n }\n lines[i][j].style.strokeWidth = newThickness\n }\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`_loopBy2Keys` executes the callback on given keys of certain entries in index 2 | _loopBy2Keys(index0, key0, key1, callback) {
let index1, index2, key2;
if ((index1 = index0[key0]) && (index2 = index1[key1])) {
for (key2 in index2) callback(key2);
}
} | [
"function caonimabzheshiyigewozijixiedeForEach2(arr, fn){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n newArr.push(fn(arr[i]));\n }\n return newArr;\n}",
"function forEach(thing, func) {\n applyEach(thing, function (value, key) {\n func(value, key);\n return value;\n });\n}",
"function multipleCallbacks (myObject, callback1, callback2){\n var myObject = {status: ['success', 'error']};\n var keyValue = Object.values(myObject.status);\n for (let i=0; i<keyValue.length; i++){\n if (keyValue[i] === 'success'){\n return callback1;\n } else return callback2;\n}\n}",
"function forEach(arr1, func1){\n for(var i=0; i < arr1.length; i++){\n // printName(addressBook[i])\n func1(arr1[i]);\n }\n}",
"function byTwo(array, fun) {\n var len = array.length,\n i;\n for (i = 0; i + 1 < len; i++) {\n fun(array[i], array[i+1]);\n }\n}",
"kvMap( fn ){}",
"_setMembersForKeys (keys, callback) {\n async.map(keys, (roomKey, callback) => {\n let cursor = 0\n const members = []\n\n async.doWhilst(cb => {\n this.redis.sscan(roomKey, cursor, 'COUNT', MEMBERS_SSCAN_COUNT, (err, result) => {\n if (err) return cb(err)\n const [newCursor, newMembers] = result\n cursor = newCursor\n members.push(...newMembers)\n cb()\n })\n }, () => cursor !== '0', err => {\n if (err) return callback(err)\n callback(null, members)\n })\n }, (err, memberGroups) => {\n if (err) return callback(err)\n callback(null, flatten(memberGroups))\n })\n }",
"each(callback, ...names) {\n const {\n stack\n } = this;\n const {\n length\n } = stack;\n let value = getLast(stack);\n\n for (const name of names) {\n value = value[name];\n stack.push(name, value);\n }\n\n for (let i = 0; i < value.length; ++i) {\n if (i in value) {\n stack.push(i, value[i]); // If the callback needs to know the value of i, call\n // path.getName(), assuming path is the parameter name.\n\n callback(this);\n stack.length -= 2;\n }\n }\n\n stack.length = length;\n }",
"forEach(cb) {\n for (var item = this._head; item; item = item.next) {\n cb(item.data);\n }\n }",
"forEachInRange(t, e) {\n const n = this.data.getIteratorFrom(t[0]);\n\n for (; n.hasNext();) {\n const s = n.getNext();\n if (this.comparator(s.key, t[1]) >= 0) return;\n e(s.key);\n }\n }",
"* entries () {\n for (var i = 0; i < this._order.length; i++) {\n var key = this._order[i]\n yield [key, this._entries[key]]\n }\n }",
"function funcLoop1(item, index, array) {\n // console.log(rowNum);\n // console.log(index);\n\n\n // top of grid - only check left, right & down\n if (index === 0) {\n item.forEach(topRowLoop);\n } else if (index === gridsize - 1) {\n item.forEach(bottomRowLoop);\n } else {\n item.forEach(middleRowLoop);\n };\n rowNum ++;\n}",
"function each( a, f ){\n\t\tfor( var i = 0 ; i < a.length ; i ++ ){\n\t\t\tf(a[i])\n\t\t}\n\t}",
"* events() {\n for (let i = 0; i < this.size(); i++) {\n yield this.at(i);\n }\n }",
"function for_each(){\n var param_len = arguments[0].length;\n var proc = arguments[0];\n while(!is_empty_list(arguments[1])){\n var params = [];\n for(var j = 1; j < 1+param_len; j++) {\n params.push(head(arguments[j]));\n arguments[j] = tail(arguments[j]);\n }\n proc.apply(proc, params);\n\t}\n}",
"function applyEach(thing, func) {\n var i;\n if (isArray(thing)) {\n for (i = 0; i < thing.length; i += 1) {\n thing[i] = func(thing[i], i);\n }\n } else {\n var keys = Object.keys(thing);\n for (i = 0; i < keys.length; i += 1) {\n var key = keys[i];\n thing[key] = func(thing[key], key);\n }\n }\n}",
"function foreach_indexed(xs, action) /* forall<a,e> (xs : list<a>, action : (int, a) -> e ()) -> e () */ {\n return _bind_foreach_indexed(xs, action);\n}",
"function iterate(callback){\n let array = [\"dog\", \"cat\", \"squirrel\"]\n array.forEach(callback)\n return array\n}",
"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}",
"_findInIndex(index0, key0, key1, key2, name0, name1, name2, graph, callback, array) {\n let tmp, index1, index2; // Depending on the number of variables, keys or reverse index are faster\n\n const varCount = !key0 + !key1 + !key2,\n entityKeys = varCount > 1 ? Object.keys(this._ids) : this._entities; // If a key is specified, use only that part of index 0.\n\n if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];\n\n for (const value0 in index0) {\n const entity0 = entityKeys[value0];\n\n if (index1 = index0[value0]) {\n // If a key is specified, use only that part of index 1.\n if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];\n\n for (const value1 in index1) {\n const entity1 = entityKeys[value1];\n\n if (index2 = index1[value1]) {\n // If a key is specified, use only that part of index 2, if it exists.\n const values = key2 ? key2 in index2 ? [key2] : [] : Object.keys(index2); // Create quads for all items found in index 2.\n\n for (let l = 0; l < values.length; l++) {\n const parts = {\n subject: null,\n predicate: null,\n object: null\n };\n parts[name0] = (0, _N3DataFactory.termFromId)(entity0, this._factory);\n parts[name1] = (0, _N3DataFactory.termFromId)(entity1, this._factory);\n parts[name2] = (0, _N3DataFactory.termFromId)(entityKeys[values[l]], this._factory);\n\n const quad = this._factory.quad(parts.subject, parts.predicate, parts.object, (0, _N3DataFactory.termFromId)(graph, this._factory));\n\n if (array) array.push(quad);else if (callback(quad)) return true;\n }\n }\n }\n }\n }\n\n return array;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is to check that a to: has been specified in new_message.php, forcing user to pick from dropdown list | function checkTo()
{
var to = document.getElementById('to');
var toFull = document.getElementById('to_full');
if (toFull.value == 'All Students' || toFull.value== 'All Professors' || toFull.value == 'All Your Students' || toFull.value == 'All Users' || toFull.value == 'All on this Case' || toFull.value == 'All on a Case')
{
return true;
}
else
{
if (to.value == '' )
{alert ('The \"to\" line contains an invalid name. Try typing the first three letters of the recipient\'s first or last name in the \"to\" field and then choosing from the drop-down menu.');return false;}
}
return true;
} | [
"selectMessageComingUp() {\n this._aboutToSelectMessage = true;\n }",
"function Assign(messageId) {\n // console.log('Assign # : '+messageId);\n\n // get array of checked ids\n var newContacts = $(\".imapper-contact-box input:checkbox:checked\").map(function(){\n return $(this).val();\n }).get();\n\n // fields for creating a contact\n var prefix = cj(\"#tab2 .prefix\").val();\n var first_name = cj(\"#tab2 .first_name\").val();\n var middle_name = cj(\"#tab2 .middle_name\").val();\n var last_name = cj(\"#tab2 .last_name\").val();\n var suffix = cj(\"#tab2 .suffix\").val();\n var email_address = cj(\"#tab2 .email_address\").val();\n var phone = cj(\"#tab2 .phone\").val();\n var street_address = cj(\"#tab2 .street_address\").val();\n var street_address_2 = cj(\"#tab2 .street_address_2\").val();\n var zip = cj(\"#tab2 .zip\").val();\n var city = cj(\"#tab2 .city\").val();\n var dob = cj(\"#tab2 .form-text.dob\").val();\n var state = cj(\"#tab2 .state\").val();\n\n // if they've selected 1 or more contact, assign the message\n if (newContacts != '') {\n // console.log('Assigning message to existing contact');\n cj.ajax({\n url: '/civicrm/imap/ajax/unmatched/assign',\n data: {\n id: messageId,\n contactId: newContacts.toString()\n },\n success: function(data, status) {\n result = cj.parseJSON(data);\n if (result.is_error) {\n CRM.alert('Could not assign message: '+result.message, '', 'error');\n return false;\n }\n else {\n messages = result.data;\n cj.each(messages, function(id, value) {\n removeRow(messageId);\n CRM.alert(value.message, '', 'success');\n });\n AdditionalEmail.dialog('open');\n cj('#AdditionalEmail-popup #contact').val(newContacts.toString());\n cj(\"#assign-popup\").dialog('close');\n // additional email popup\n }\n }\n });\n }\n else if (first_name || last_name || email_address) {\n // console.log('Assigning message to new contact');\n if ((cj.isNumeric(cj(\"#tab2 .dob .month\").val()) || cj.isNumeric(cj(\"#tab2 .dob .day\").val()) || cj.isNumeric(cj(\"#tab2 .dob .year\").val())) && ( !cj.isNumeric(cj(\"#tab2 .dob .month\").val()) || !cj.isNumeric(cj(\"#tab2 .dob .day\").val()) || !cj.isNumeric(cj(\"#tab2 .dob .year\").val()))) {\n CRM.alert('Please enter a full date of birth', 'Warning', 'warn');\n return false;\n };\n\n cj.ajax({\n url: '/civicrm/imap/ajax/contact/add',\n data: {\n prefix: prefix,\n first_name: first_name,\n middle_name: middle_name,\n last_name: last_name,\n suffix: suffix,\n email_address: email_address,\n phone: phone,\n street_address: street_address,\n street_address_2: street_address_2,\n postal_code: zip,\n city: city,\n state: state,\n dob: dob\n },\n success: function(data, status) {\n result = cj.parseJSON(data);\n if (result.is_error) {\n CRM.alert('Could not create contact: '+result.message, '', 'error');\n return false;\n }\n else {\n contactId = result.data;\n cj.ajax({\n url: '/civicrm/imap/ajax/unmatched/assign',\n data: {\n id: messageId,\n contactId: contactId\n },\n success: function(data, status) {\n result = cj.parseJSON(data);\n if (result.is_error) {\n CRM.alert('Could not assign message: '+result.message, '', 'error');\n return false;\n }\n else {\n messages = result.data;\n AdditionalEmail.dialog('open');\n cj('#AdditionalEmail-popup #contact').val(contactId);\n cj(\"#assign-popup\").dialog('close');\n cj.each(messages, function(id, value) {\n removeRow(messageId);\n CRM.alert('Contact created: '+value.message, '', 'success');\n if (email_address.length > 0) {\n checkForMatch(email_address, contactId);\n }\n });\n }\n }\n });\n }\n }\n });\n return false;\n }\n else {\n // console.log('Please choose a contact');\n CRM.alert('Select a contact to assign message to,<br/> OR create a contact with first name, last name, or email', '', 'warn');\n }\n }",
"function validateMTOForm() {\n if (tcType.value === \"TC\") {\n tcTypeNotification.style.display = \"block\";\n } else if (!isSampleFormatAllowed) {\n sampleNotification.style.display = \"block\";\n } else if (!isInstructionsFormatAllowed) {\n instructionsNotification.style.display = \"block\";\n } else {\n mtoForm.action = \"mto.py\";\n mtoForm.submit();\n sampleNotification.style.display = \"none\";\n instructionsNotification.style.display = \"none\";\n tcTypeNotification.style.display = \"none\";\n }\n}",
"function showSendMail(selected) {\n\tif (selected.indexOf(\"YES\") > -1) {\n\t\tdocument.getElementById(\"sendMailButton\").disabled = false;\n\t} else {\n\t\tdocument.getElementById(\"sendMailButton\").disabled = true;\n\t}\n}",
"isAdding() {\n return Template.instance().uiState.get(\"addChat\") == CANCEL_TXT;\n }",
"function anySelected(act) {\n if (YAHOO.alpine.current.selected <= 0){\n panelAlert('No messages selected to ' + act + '.<p>Select one or more messages by checking the box on the line of each desired message.');\n return false;\n }\n\n return true;\n}",
"function validateMessage()\n{\n//variable contactMessage is set by element id contactMessage from the form\n\tvar contactMessage = document.getElementById(\"contactMessage\").value; \n\t//validation for contactMessage\n\tif(contactMessage.length == 0)\n\t{\n\t\tproducePrompt(\"Message is Required\", \"messagePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tproducePrompt(\"Now press send, you will be contacted shortly. \", \"messagePrompt\", \"green\"); \n\t\treturn true; \n\n}",
"function f_GetSelectionAndSend(select) {\n\tvar myValueSelected = select[select.selectedIndex].text; \t// store text found in the option value selected \n\t// Get the input text HTML element \n\tvar text = $(he_txtToSend);\n\t// Set the input to value previously retrieved\n\ttext.val(myValueSelected);\n\t// Force to simulate a click on a specific HTML element (using jQuery)\n\t$(\"#Btn_send\").click();\n}",
"function validateObserverFormInputs() {\n var observer = $('select[id*=\"ObserverUser\"]'); // get the proper id input\n var messageA = $(observer).val() == '' ? 'You must select an User' : '';\n var messageB = $('#ObserverType').val() == '' ? 'You must select an Type' : '';\n var divider = (messageA != '' && messageB != '') ? '\\r\\n\\r\\n' : '';\n if (messageA != '' || messageB != '') {\n alert(messageA + divider + messageB);\n return false;\n } else {\n return true;\n }\n}",
"function massactionsChangeMessagePoke()\n\t{\n\t\t// Daten sammeln\n\t\tvar group_id \t\t\t= \t$('#selectMessagePokeGroup').val();\n\t\tvar who\t\t\t\t\t=\t$(\"#selectMessagePokeGroup\").find(':selected').attr('group');\n\t\tvar channel\t\t\t\t=\t$('#selectMessagePokeChannel').val();\n\t\tvar group\t\t\t\t=\t'none';\n\t\tvar res \t\t\t\t= \tgroup_id.split(\"-\");\t// res[3]\n\t\t\n\t\tif(who != 'all')\n\t\t{\n\t\t\tgroup\t\t=\tres[3];\n\t\t};\n\t\t\n\t\t// Daten in Funktion übergeben\n\t\tmassactionsMassInfo(who, group, channel, 'msg');\n\t}",
"function showchatUserSelect(){\n if(userChat==null)\n {return;}\n /*eventAddChat(message);*/\n $(\".inyect-commit\").html(\"\");\n $(\"#bienvenida\").hide();\n listOfChat.forEach(function(message){\n if((message.name.id==userChat.id && message.userSend.id==JSON.parse($.session.get(\"ObjectUser\")).id) || (message.name.id==JSON.parse($.session.get(\"ObjectUser\")).id && message.userSend.id==userChat.id)){\n\n eventAddChat(message);\n }\n });\n $(\".inyect-commit\").scrollTo(10000,0)/*mejorar la parte del scroll*/\n }",
"function validateMessage(formname)\n{\n\t\n if(validateForm(formname,'frmSendToIds', 'Select Users', 'R', 'frmMessageType', 'Message Type', 'R', 'frmMessageSubject', 'message Subject', 'R'))\n {\t\n\t\t\n\t\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function msglist_AddGoto( strMessage, strField )\n{\n if( this.p_NumMsg == 0 )\n this.p_msg = strMessage;\n else\n this.p_msg = this.p_msg + \"\\r\" + strMessage;\n\n this.p_NumMsg = this.p_NumMsg + 1;\n\n if (this.p_field == \"\" )\n this.p_field = strField;\n}",
"function openMessageFrame(contactElement){\n\n\t\t\t//get a reference to the view object\n\t\t\tvar msgView = document.getElementById(\"message_view\");\n\n\t\t\tif(activeContact.trim() !== \"\"){\n\t\t\t\t\n\t\t\t\t//Change the color of the current active contact to black\n\t\t\t\tvar currentActiveContact = document.getElementById (activeContact);\n\t\t\t\tcurrentActiveContact.style.color = \"black\";\n\t\t\t\tconsole.log(\"Switch from \"+ activeContact );\n\t\t\t}//if Ends \n\n\t\t\t//remove current user's message content and replace them with that of the new user.\n\t\t\tactiveContact = contactElement.textContent; \n\n\t\t\tmsgView.textContent = \"\";\n\n\t\t\tcontactElement.style.color = \"blue\";\n\n\t\t\tconsole.log(\"Active contact: \"+activeContact);\n\n\t\t\t//TODO:Let the sender know that receiver has view the message that was sent.\n\t\t\t//clear the message notication status count to indicate that user has view the message. \n\t\t document.getElementById(activeContact+\"_msg_notice\").textContent = \"\";\n\t\t}",
"function ValidateViewCheck()\n\t{\n\t\t//Set short message with the error code\t\n\t\tvar ShortMessage=ErChkLstSht002;\n\t\t//set long message as empty\n\t\tvar LongMessage=\"\";\n\t\tLongMessage=CheckDDL(LongMessage);\n\t\t//check textbox [from] check number is empty\n\t\tif(true==IstxtEmpty('txtFrom'))\n\t\t{\n\t\t\t//check long message is empty\n\t\t\tif(\"\"==LongMessage)\n\t\t\t{\n\t\t\t\t//set long message\n\t\t\t\tLongMessage=ErChkLstLng003;\n\t\t\t\t//set focus on [from] check number\n\t\t\t\tdocument.getElementById('txtFrom').focus();\n\t\t\t}\n\t\t\t//if long message is not empty\n\t\t\telse\n\t\t\t{\n\t\t\t\t//set longmessage with newline char and long message code\n\t\t\t\tLongMessage=LongMessage + '\\n' + ErChkLstLng003;\t\t\t\t\n\t\t\t}\t\t\t\n\t\t}\n\t\t\n\t\t//If [from] check number is empty\n\t\tif(false==IstxtEmpty('txtFrom'))\n\t\t{\n\t\t\t//check textbox [from] check number is number\n\t\t\tif(false==IsNumeric(document.getElementById('txtFrom').value))\n\t\t\t{\n\t\t\t\t//check long message is empty\n\t\t\t\tif(\"\"==LongMessage)\n\t\t\t\t{\n\t\t\t\t\t//set long message\n\t\t\t\t\tLongMessage=ErChkLstLng004;\n\t\t\t\t\t//set focus on [from] check number\n\t\t\t\t\tdocument.getElementById('txtFrom').focus();\n\t\t\t\t}\n\t\t\t\t//if long message is not empty\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t//set longmessage with newline char and long message code\n\t\t\t\t\tLongMessage=LongMessage + '\\n' + ErChkLstLng004;\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t\t\n\t\t//check textbox [to] check number is empty\n\t\tif(true==IstxtEmpty('txtTo'))\n\t\t{\n\t\t\t//check long message is empty\n\t\t\tif(\"\"==LongMessage)\n\t\t\t{\n\t\t\t\t//set long message\n\t\t\t\tLongMessage=ErChkLstLng005;\n\t\t\t\t//set focus on [to] check number\n\t\t\t\tdocument.getElementById('txtTo').focus();\n\t\t\t}\n\t\t\t//if long message is not empty\n\t\t\telse\n\t\t\t{\n\t\t\t\t//set longmessage with newline char and long message code\n\t\t\t\tLongMessage=LongMessage + '\\n' + ErChkLstLng005;\t\t\t\t\n\t\t\t}\t\t\t\n\t\t}\n\t\t\n\t\t//If [to] check number is not empty then check\n\t\tif(false==IstxtEmpty('txtTo'))\n\t\t{\n\t\t\t//check textbox [to] check number is number\n\t\t\tif(false==IsNumeric(document.getElementById('txtTo').value))\n\t\t\t{\n\t\t\t\t//check long message is empty\n\t\t\t\tif(\"\"==LongMessage)\n\t\t\t\t{\n\t\t\t\t\t//set long message\n\t\t\t\t\tLongMessage=ErChkLstLng006;\n\t\t\t\t\t//set focus on [to] check number\n\t\t\t\t\tdocument.getElementById('txtTo').focus();\n\t\t\t\t}\n\t\t\t\t//if long message is not empty\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t//set longmessage with newline char and long message code\n\t\t\t\t\tLongMessage=LongMessage + '\\n' + ErChkLstLng006;\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t\t//if long message is empty\n\t\tif(\"\"==LongMessage)\n\t\t{\n\t\t\t//Validation success\n\t\t\treturn true;\n\t\t}\n\t\t//if long message is not empty\n\t\telse\n\t\t{\n\t\t\t//set error message on toppage\n\t\t\tSetErrorMessage(ShortMessage,LongMessage);\n\t\t\t//validation failure\n\t\t\treturn false;\n\t\t}\n\t}",
"function inspectBehavior(upStr){\n var timelineName,menuLength,i;\n var argArray = new Array;\n var found = false;\n\n argArray = extractArgs(upStr); //get args\n if (argArray.length == 2) { //should be exactly 2 args\n timelineName = argArray[1];\n menuLength = document.theForm.menu.options.length;\n for (var i=0; i<menuLength; i++) { //search menu for matching timeline name\n if (document.theForm.menu.options[i].text == timelineName) { //if found\n document.theForm.menu.selectedIndex = i; //make it selected\n found = true;\n break;\n }\n }\n if (!found) alert(errMsg(MSG_TimelineNotFound,timelineName));\n }\n}",
"sendMessage(text) {\n\t\tthis.setTextToInput(text);\n\t\tthis.sendBtn.click();\n\t\tbrowser.waitUntil(function() {\n\t\t\tbrowser.waitForVisible('.message:last-child .body', 5000);\n\t\t\treturn browser.getText('.message:last-child .body') === text;\n\t\t}, 5000);\n\t}",
"function newRecievedMessage(messageText) {\n\n\t// Variable storing the message with the \"\" removed\n\tvar removedQuotes = messageText.replace(/[\"\"]/g,\"\");\n\n\t// update the last message recieved variable for storage in the database\n\tlastRecievedMessage = removedQuotes;\n\n\t// If the message contains a <ar then it is a message\n\t// whose responses are buttons\n\tif (removedQuotes.includes(\"<br\")) \n\t{\n\t\tmultiMessage(removedQuotes);\n\t} \n\n\t// There arent multiple messages to be sent, or message with buttons\n\telse\n\t{\t\n\t\t// Show the typing indicator\n\t\tshowLoading();\n\n\t\t// After 3 seconds call the createNewMessage function\n\t\tsetTimeout(function() {\n\t\t\tcreateNewMessage(removedQuotes);\n\t\t}, DEFAULT_TIME_DELAY);\n\t}\n}",
"function valReason(frm){\n\tvar passed=true;\n\tvar errorCount=0;\n\tvar r= frm.reason.value;\n\t\n\tif(r==\"\" || r==null){\n\t\terrorCount++;\n\t\tdocument.getElementById(\"reason_err\").innerHTML=\"You must select a reason to deny the post.\";\n\t}\n\t\n\t\tif(errorCount !=0)\n\t{\n\t\treturn false;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes a MySQL query to fetch a single specified assignment based on its ID. Returns a Promise that resolves to an object containing the requested assignment. If no assignment with the specified ID exists, the returned Promise will resolve to null. | function getAssignmentById(id) {
return new Promise((resolve, reject) => {
mysqlPool.query(
'SELECT * FROM assignments WHERE id = ?',
[ id ],
(err, results) => {
if (err) {
reject(err);
} else {
resolve(results[0]);
}
}
);
});
} | [
"function getAssignmentsByCourseId(id) {\n return new Promise((resolve, reject) => {\n mysqlPool.query(\n 'SELECT * FROM assignments WHERE courseid = ?',\n [ id ],\n function (err, results) {\n if (err) {\n reject(err);\n } else {\n resolve(results);\n }\n }\n );\n });\n}",
"function getAssignmentsByUserId(id) {\n return new Promise((resolve, reject) => {\n mysqlPool.query(\n 'SELECT * FROM assignments WHERE userid = ?',\n [ id ],\n (err, results) => {\n if (err) {\n reject(err);\n } else {\n resolve(results);\n }\n }\n );\n });\n}",
"function updateAssignmentById(id, assignment) {\n return new Promise((resolve, reject) => {\n assignment = extractValidFields(assignment, AssignmentSchema);\n mysqlPool.query(\n 'UPDATE assignments SET ? WHERE id = ?',\n [ assignment, id ],\n (err, result) => {\n if (err) {\n reject(err);\n } else {\n resolve(result.affectedRows > 0);\n }\n }\n );\n });\n}",
"static getById(id) {\n return db.one(`\n SELECT * FROM results WHERE id = $1`,\n [id]\n )\n .then(result => {\n return new Result(result.id, result.id_resultset, result.id_question, result.correct);\n });\n }",
"function getHITAssignments(HITId) {\n return new Promise((resolve, reject) => {\n mturk.listAssignments(HITId, data => {\n resolve(data);\n });\n });\n}",
"getAssignments(schoolID) {\n return _get('/api/assignments', {school_id: schoolID});\n }",
"async function getOrderById(id) {\n const [ results ] = await mysqlPool.query(\n 'SELECT * FROM orders WHERE id = ?',\n [ id ]\n );\n return results[0];\n}",
"async function getArtistById(id) {\n const [ results ] = await mysqlPool.query(\n 'SELECT * FROM artist WHERE id = ?',\n [ id ]\n );\n return results[0];\n}",
"function getAssignmentFromModal() {\n\tvar name, at_name, at_id, due_date, reminder_date, details, tot_grade, link;\n\tvar date_arr, time_arr;\n\n\t// validate that the tot_grade is an integer value\n\t//TODOTODOTODO\n\n\t// get input from form\n\tname = $('#name').val();\n\tat_name = $('#type option:selected').text()\n\tat_id = $('#type option:selected').val()\n\tdate_arr = $('#due-date').val().split('/');\n\tdue_date = new DueDate(date_arr[2], date_arr[0], date_arr[1]);\n\tdate_arr = $('#reminder-date').val().split('/');\n\thour = $('#am-pm option:selected').val() === 'am' ? parseInt($('#hour option:selected').val()) : parseInt($('#hour option:selected').val()) + 12;\n\tminute = parseInt($('#minute option:selected').val());\n\treminder_date = new ReminderDate(date_arr[2], date_arr[0], date_arr[1], hour, minute);\n\tdetails = $('#details').val();\n\ttot_grade = parseInt($('#total-points').val());\n\tlink = $('#link').val();\n\n\t// create and return Assignment object if valid\n\treturn new Assignment(name, course_id, at_name, at_id, reminder_date, due_date,\tdetails, 0, tot_grade, link, false);\n}",
"static async findMarks(id){\n const result=await pool.query('SELECT * FROM academics WHERE studentid=?',id);\n return result;\n }",
"async function getBootcampersById(id){\n const res = await query(`SELECT * FROM bootcampers WHERE id = $1;`, [id])\n return res\n}",
"async function getRelationOne(per) {\n logger.debug(`* Connection Open: getRelationOne`);\n text = `SELECT * FROM relations WHERE person_id=$1`;\n values = [per];\n res = await psqlQuery(text, values);\n logger.debug(`* Connection Closed: getRelationOne`);\n let decodedResponse = await _decodeRelationsIds(res.rows[0]);\n if (decodedResponse) return returnSuccess(decodedResponse);\n else return returnFailure();\n}",
"function createAssignment(classID, assignObj) {\n // Clean and verify input\n // console.log(`[LOG] assignment-db: ${JSON.stringify(assignObj, null, 2)}`)\n if (isNaN(assignObj.expires) || assignObj.expires < 0){\n return new Promise((res, rej) => {res(null)});\n }\n if (isNaN(assignObj.workload) || assignObj.workload < 0) {\n return new Promise((res, rej) => {res(null)});\n }\n assignObj.expires = parseInt(assignObj.expires);\n assignObj.workload = parseInt(assignObj.workload);\n assignObj.created = Math.floor(Date.now()/1000);\n // Valid input, create doc\n let assignRef = db.collection('classes').doc(classID).collection('assignments');\n let addDoc = assignRef.add(assignObj);\n return addDoc;\n}",
"async getProfileById(id) {\n\t\ttry {\n\t\t\tassert(!_.isEmpty(id), 'id is invalid');\n\t\t\treturn Promise.resolve(this.profiles.find({id})[0]);\n\t\t} catch (error) {\n\t\t\tlogger.error({err: error}, `Error occurred while fetching user ${id} from database`);\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t}",
"function getArtifact(res, mysql, context, id, complete){\r\n var sql = 'SELECT Artifacts.Name, Artifacts.ArtifactID as id, Artifacts.Price, Artifacts.Year, Exhibits.WingName, Exhibits.WingID FROM `Artifacts` INNER JOIN `Exhibits` ON Artifacts.FK_WingID = Exhibits.WingID WHERE Artifacts.ArtifactID = ?;';\r\n var inserts = [id];\r\n mysql.pool.query(sql, inserts, function(error, results, fields){\r\n if(error){\r\n res.write(JSON.stringify(error));\r\n res.end();\r\n }\r\n context.artifactInfo = results[0];\r\n complete();\r\n });\r\n }",
"function getJokeAnswer(id) {\n return new Promise((resolve, reject) => {\n const qry = 'SELECT * FROM jokes WHERE `id`=? LIMIT 1';\n connection.query(qry, [id], (err, result) => {\n if (err) {\n console.log('getJokeAnswer error', err, err.stack);\n reject(err);\n }\n resolve(result);\n });\n });\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 getAssignmentFromExpression(node) {\n\t\tvar assignmentIdentifier = null;\n\n\t\tfor (var i = 0; i < node.tokens.length; i++) {\n\t\t\tif (node.tokens[i].type === TYPE.ASSIGN_OPERATOR) {\n\t\t\t\tif (i + 1 < node.tokens.length && node.tokens[i + 1].type ===\n\t\t\t\t\tTYPE.IDENTIFIER) {\n\t\t\t\t\tassignmentIdentifier = node.tokens[i + 1].value;\n\n\n\t\t\t\t\t// console.log(node.tokens[i+1]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// console.log('assignment', assignmentIdentifier);\n\t\treturn assignmentIdentifier;\n\t}",
"function getProjectById(id) {\n return db(\"projects\")\n .where({ id })\n .first();\n}",
"async function getWork(id) {\n const work = await Work.findById(id);\n if (!work) return;\n return work;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add "active" class to TOC link corresponding to subsection at top of page | function setActiveSubsection(activeHref) {
var tocLinkToActivate = document.querySelector(".toc a[href$='" + activeHref + "']");
var currentActiveTOCLink = document.querySelector(".toc a.active");
if (tocLinkToActivate != null) {
if (currentActiveTOCLink != null && currentActiveTOCLink !== tocLinkToActivate) {
currentActiveTOCLink.classList.remove("active");
}
tocLinkToActivate.classList.add("active");
}
} | [
"function trx_addons_mark_active_toc() {\n\t\tvar items = trx_addons_detect_active_toc();\n\t\ttoc_menu_items.removeClass('toc_menu_item_active');\n\t\tfor (var i=0; i<items.current.length; i++) {\n\t\t\ttoc_menu_items.eq(items.current[i]).addClass('toc_menu_item_active');\n\t\t\t// Comment next line if on your device page jump when scrolling\n\t\t\tif (items.loc!='' && TRX_ADDONS_STORAGE['update_location_from_anchor']==1 && !trx_addons_browser_is_mobile() && !trx_addons_browser_is_ios() && !wheel_busy)\n\t\t\t\ttrx_addons_document_set_location(items.loc);\n\t\t}\n\t\tjQuery(document).trigger('action.toc_menu_item_active', [items.current]);\n\t}",
"function setActiveSubTopic(hash) {\n // Set inactive the previously active topic\n var prevActiveTopic = document.querySelector(\".sub-topics .topic.active\");\n var nextActiveTopic = document.querySelector(\n '.sub-topics a[href=\"' + hash + '\"]'\n ).parentNode;\n\n if (prevActiveTopic !== nextActiveTopic) {\n nextActiveTopic.classList.add(\"active\");\n\n if (prevActiveTopic) {\n prevActiveTopic.classList.remove(\"active\");\n }\n }\n }",
"function SetActiveLink(){\r\n var path = window.location.pathname;\r\n var pathSplit = path.split(\"/\");\r\n var urlEnd = pathSplit[pathSplit.length - 1];\r\n\r\n var activeLinkID = url_navlink_dict[urlEnd];\r\n $(\"#\" + activeLinkID).addClass(\"active\");\r\n}",
"function activeNavigation() {\n var locationUrl = window.location.href;\n var handlerAndAction = locationUrl\n .replace(/(.*\\/\\/vacation.+?\\/)(index.cfm\\/)?/i, '')\n .replace(/\\?.+/, '')\n .split('/');\n var currentHandler = handlerAndAction[0].toLowerCase();\n var currentAction = handlerAndAction[1] || 'index';\n var currentObjectId = handlerAndAction[2];\n\n $('[data-handler=\"' + currentHandler + '\"]').addClass('active');\n\n // breadcrumbs\n buildBradcrumbs(currentHandler, currentAction, currentObjectId);\n}",
"function highlightHashTarget() {\n\t\tif (!location.hash) return;\n\n\t\ttry {\n\t\t\tvar target = document.querySelector(location.hash)\n\t\t\tif(target) {\n\t\t\t\ttarget.scrollIntoView({\n\t\t\t\t\tblock: \"start\"\n\t\t\t\t})\n\t\t\t\tsetHeaderActive(target)\n\t\t\t\tvar tocItem = document.querySelector('.toc a[data-target=\"'+location.hash+'\"]');\n\t\t\t\tif(tocItem) setTOCActive(tocItem)\n\t\t\t}\n\t\t}\n\t\tcatch(e) {}\n\t}",
"function trx_addons_detect_active_toc() {\n\t\tvar items = {\n\t\t\tloc: '',\n\t\t\tcurrent: [],\n\t\t\tprev: -1,\n\t\t\tprevOffset: -1,\n\t\t\tnext: -1,\n\t\t\tnextOffset: -1\n\t\t};\n\t\tvar fixed_rows_height = Math.ceil(trx_addons_fixed_rows_height());\n\t\t\n\t\ttoc_menu_items.each(function(idx) {\n\t\t\tvar id = '#'+jQuery(this).data('id');\n\t\t\tvar pos = id.indexOf('#');\n\t\t\tif (pos < 0 || id.length == 1) return;\n\t\t\tvar href = jQuery(this).find('a').attr('href');\n\t\t\tif (!trx_addons_is_local_link(href) || jQuery(id).length==0) return;\n\t\t\tvar off = jQuery(id).offset().top;\n\t\t\tvar id_next = jQuery(this).next().find('a').attr('href');\n\t\t\tvar off_next = id_next && idx < toc_menu_items.length-1 && jQuery(id_next).length > 0 \n\t\t\t\t\t\t\t\t\t? parseInt(jQuery(id_next).offset().top, 10) \n\t\t\t\t\t\t\t\t\t: 1000000;\n\t\t\tvar scroll_offset = parseInt(jQuery(window).scrollTop(), 10);\n\t\t\tif (off > scroll_offset + fixed_rows_height + 20) {\n\t\t\t\tif (items.next < 0) {\n\t\t\t\t\titems.next = idx;\n\t\t\t\t\titems.nextOffset = off;\n\t\t\t\t}\n\t\t\t} else if (off < scroll_offset - fixed_rows_height - 20) {\n\t\t\t\titems.prev = idx;\n\t\t\t\titems.prevOffset = off;\n\t\t\t}\n\t\t\tif (off < scroll_offset + jQuery(window).height()*0.8 && scroll_offset < off_next - fixed_rows_height) {\n\t\t\t\titems.current.push(idx);\n\t\t\t\tif (items.loc == '') {\n\t\t\t\t\tvar loc = window.location.href;\n\t\t\t\t\tvar loc_pos = loc.indexOf('#');\n\t\t\t\t\tif (loc_pos > 0) loc = loc.substring(0, loc_pos);\n\t\t\t\t\titems.loc = href.indexOf('#')==0 ? loc + id : id;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn items;\n\t}",
"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 }",
"function activateNavDots(name,sectionIndex){if(options.navigation&&$(SECTION_NAV_SEL)[0]!=null){removeClass($(ACTIVE_SEL,$(SECTION_NAV_SEL)[0]),ACTIVE);if(name){addClass($('a[href=\"#'+name+'\"]',$(SECTION_NAV_SEL)[0]),ACTIVE);}else{addClass($('a',$('li',$(SECTION_NAV_SEL)[0])[sectionIndex]),ACTIVE);}}}",
"function changeActiveMenuItemOnScroll() {\r\n\t\tvar scrollPos = $(document).scrollTop();\r\n\t\t$('.header-menu-a').each(function () {\r\n\t\t\t\tvar $currLink = $(this);\r\n\t\t\t\tvar refElement = $($currLink.attr(\"href\"));\r\n\t\t\t\tif (refElement.position().top <= scrollPos && refElement.position().top + refElement.outerHeight(true) > scrollPos) {\r\n\t\t\t\t\t$('.header-menu-a').removeClass(\"header-menu-a_active\");\r\n\t\t\t\t\t$currLink.addClass(\"header-menu-a_active\");\r\n\r\n\t\t\t\t\tpaginationUnderlineTransition(\r\n\t\t\t\t\t\t$(\".header-menu-nav\"),\r\n\t\t\t\t\t\t\".header-pagination-underline\",\r\n\t\t\t\t\t\t$(\".header-menu-a_active\"),\r\n\t\t\t\t\t\t0.99\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t} else {\r\n\t\t\t\t\t$currLink.removeClass(\"header-menu-a_active\");\r\n\t\t\t\t}\r\n\t\t});\r\n\t}",
"function addHeadingToTOC(toc, h, uid, altTitle) {\n const headingID = 'fseNavTo--Heading--' + uid;\n h.classList.add(headingID);\n\n const heading = document.createElement('button');\n heading.appendChild(document.createTextNode(altTitle || h.innerText));\n heading.className = 'fseNavTo--Heading';\n heading.setAttribute('data-heading-id', headingID);\n heading.addEventListener('click', function(e) {\n document.querySelector('.' + e.target.getAttribute('data-heading-id')).scrollIntoView({ behavior: 'smooth' });\n toc.style.display = 'none';\n });\n toc.appendChild(heading);\n }",
"function setChapterActive($chapter, hash) {\n // No chapter and no hash means first chapter\n if (!$chapter && !hash) {\n $chapter = $chapters.first();\n }\n\n // If hash is provided, set as active chapter\n if (!!hash) {\n // Multiple chapters for this file\n if ($chapters.length > 1) {\n $chapter = $chapters\n .filter(function () {\n var titleId = getChapterHash($(this));\n return titleId == hash;\n })\n .first();\n }\n // Only one chapter, no need to search\n else {\n $chapter = $chapters.first();\n }\n }\n\n // Don't update current chapter\n if ($chapter.is($activeChapter)) {\n return;\n }\n\n // Update current active chapter\n $activeChapter = $chapter;\n\n // Add class to selected chapter\n $chapters.removeClass(\"active\");\n $chapter.addClass(\"active\");\n\n // Update history state if needed\n hash = getChapterHash($chapter);\n\n var oldUri = window.location.pathname + window.location.hash,\n uri = window.location.pathname + hash;\n\n if (uri != oldUri) {\n history.replaceState({ path: uri }, null, uri);\n }\n}",
"function activeMenuLink(e) {\n if (conSec.classList[1] === 'dash-page') {\n dashLink.setAttribute(\"style\", \"border-color: #258afe;\");\n }\n if (conSec.classList[1] === 'metrics-page') {\n metricsLink.setAttribute(\"style\", \"border-color: #258afe;\");\n }\n if (conSec.classList[1] === 'alerts-page') {\n alertsLink.setAttribute(\"style\", \"border-color: #258afe;\");\n }\n if (conSec.classList[1] === 'tickets-page') {\n ticketsLink.setAttribute(\"style\", \"border-color: #258afe;\");\n }\n\n}",
"function selectedNav() {\n let pathRoot,\n current\n\n pathRoot = getRootPathname();\n current = get_elem(`.navMain a[href*=\"${pathRoot}\"]`);\n addClass(current, 'selected');\n }",
"function select_side_tabs(page) {\n\n// Get side tabs\n\n var tabs = jQuery('#sideNav li a');\n\n// Cycle through href links and highlight if found\n\n for (var i = 0; i < tabs.length; i++) {\n var href = jQuery(tabs[i]).attr('href');\n if (href == page) {\n jQuery(tabs[i]).addClass('active');\n }\n else\n jQuery(tabs[i]).removeClass('active');\n }\n\n// Cycle through accordion content and activate if found\n\n var found = false;\n var acc = jQuery('#sideNav .accordion');\n var acc_content = jQuery('#sideNav .accordion-content');\n\n for (var i = 0; i < acc.length; i++) {\n jQuery(acc[i]).removeClass('active');\n jQuery(acc_content[i]).removeClass('show');\n }\n\n for (var i = 0; i < acc.length; i++) {\n\n var kids = jQuery(acc_content[i]).children();\n var hrefs = [];\n for (var j = 0; j < kids.length; j++)\n hrefs[j] = jQuery(kids[j]).attr('href');\n if (jQuery.inArray(page, hrefs) != -1 && !found) {\n jQuery(acc[i]).addClass('active');\n jQuery(acc_content[i]).addClass('show');\n console.log(acc[i]);\n found = true;\n }\n }\n\n // for (var i = 0; i < acc.length; i++) {\n // var kids = jQuery(acc_content[i]).children();\n // var hrefs = [];\n // for (var j = 0; j < kids.length; j++)\n // hrefs[j] = jQuery(kids[j]).attr('href');\n // console.log(hrefs);\n // if (jQuery.inArray(page, hrefs) && !found) {\n // jQuery(acc[i]).addClass('active');\n // jQuery(acc_content[i]).addClass('show');\n // console.log(page);\n // // console.log(hrefs);\n // found = true;\n // } else if (!found) {\n // jQuery(acc[i]).removeClass('active');\n // jQuery(acc_content[i]).removeClass('show');\n // }\n // }\n}",
"function highlightCurrent() {\n obj = document.location.hash.match(/comment_item_(\\d+)/);\n if (obj) {\n $('comment_item_'+obj[1]).addClassName('js_highlighted');\n // The above should be enough to dynamicall define CSS styles, but it's not working, so...\n $$('.js_highlighted .comment_header')[0].style.backgroundColor = '#FDF1C6';\n $('comment_item_'+obj[1]).scrollTo();\n }\n}",
"function highlightActiveSidenav() {\n // This events gets triggered on refresh or URL change\n $rootScope.$on('$stateChangeSuccess', function() {\n var state = $state.current.name;\n $timeout(function() {\n angular.element('.navigation-main > li').removeClass('active');\n angular.element('.navigation-main > li[data-for-states~=\"' + state + '\"]').addClass('active');\n });\n });\n }",
"function onScroll(event){\n var scrollPos = $(document).scrollTop();\n $('a.activeOnScroll').each(function () {\n var currLink = $(this);\n var refElement_id = $(this).attr(\"href\");\n var refElement = $(refElement_id);\n if ( (refElement.offset().top <= scrollPos ) && ( refElement.offset().top + refElement.height() > scrollPos ) ) {\n $('a.activeOnScroll').parent().removeClass(\"active\");\n currLink.parent().addClass(\"active\");\n }\n });\n}",
"function ADLTOC()\r\n{\r\n}",
"function select_top_tabs(page) {\n\n// Get top tabs\n\n var tabs = jQuery('#topNav li a');\n var found = false;\n\n// Cycle through tabs and highlight if found\n\n for (var i = 0; i < tabs.length; i++) {\n var href = jQuery(tabs[i]).attr('href');\n if (href == page) {\n jQuery(tabs[i]).addClass('active');\n found = true;\n } else\n jQuery(tabs[i]).removeClass('active');\n }\n\n// If not found, highlight basic settings page\n\n var basic_settings = jQuery('#topNav li a[href=\"basic_settings.php\"]')\n if (!found) jQuery(basic_settings).addClass('active');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a monaco file reference, basically a fancy path | function createFileUri(config, compilerOptions, monaco) {
return monaco.Uri.file(defaultFilePath(config, compilerOptions, monaco));
} | [
"function makeWorkPath() {\r\n\tvar idMk = charIDToTypeID( \"Mk \" );\r\n\t\tvar desc92 = new ActionDescriptor();\r\n\t\tvar idnull = charIDToTypeID( \"null\" );\r\n\t\t\t\tvar ref34 = new ActionReference();\r\n\t\t\t\tvar idPath = charIDToTypeID( \"Path\" );\r\n\t\t\t\tref34.putClass( idPath );\r\n\t\tdesc92.putReference( idnull, ref34 );\r\n\t\tvar idFrom = charIDToTypeID( \"From\" );\r\n\t\t\t\tvar ref35 = new ActionReference();\r\n\t\t\t\tvar idcsel = charIDToTypeID( \"csel\" );\r\n\t\t\t\tvar idfsel = charIDToTypeID( \"fsel\" );\r\n\t\t\t\tref35.putProperty( idcsel, idfsel );\r\n\t\tdesc92.putReference( idFrom, ref35 );\r\n\t\tvar idTlrn = charIDToTypeID( \"Tlrn\" );\r\n\t\tvar idPxl = charIDToTypeID( \"#Pxl\" );\r\n\t\tdesc92.putUnitDouble( idTlrn, idPxl, 2 );\r\n\texecuteAction( idMk, desc92, DialogModes.NO );\r\n}",
"addFileRef(user_id, file_info) {\n logger.log('info', 'add file', {user_id: user_id, file_info: file_info})\n\n return FileReference.create({\n UserID: user_id,\n Info: file_info,\n LastUpdated: new Date(),\n }).then(function (file_ref) {\n logger.log('debug', 'file reference added', file_ref.toJSON())\n return file_ref\n }).catch(function (err) {\n logger.log('error', 'add file reference failed', err)\n return err\n })\n }",
"addFile(fileName, value) {\n if (value) {\n const fo = SpigFiles.createFileObject(fileName, {virtual: true});\n fo.spig = this;\n fo.contents = Buffer.from(value);\n return fo;\n }\n const fo = SpigFiles.createFileObject(fileName);\n fo.spig = this;\n\n return fo;\n }",
"pathRef(editor, path) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var {\n affinity = 'forward'\n } = options;\n var ref = {\n current: path,\n affinity,\n\n unref() {\n var {\n current\n } = ref;\n var pathRefs = Editor.pathRefs(editor);\n pathRefs.delete(ref);\n ref.current = null;\n return current;\n }\n\n };\n var refs = Editor.pathRefs(editor);\n refs.add(ref);\n return ref;\n }",
"async function createSymlink(src, dest, type) {\n if (process.platform === 'win32') {\n if (type === 'exec') {\n await cmdShim(src, dest);\n } else {\n await forceCreate(src, dest, type);\n }\n } else {\n const posixType = type === 'exec' ? 'file' : type;\n const relativeSource = (0, _path.relative)((0, _path.dirname)(dest), src);\n await forceCreate(relativeSource, dest, posixType);\n }\n}",
"setOutputFile(filePath)\r\n { \r\n const vscode = require('vscode');\r\n this.filePath=filePath;\r\n vscode.debug.activeDebugConsole.appendLine(\"OUTPUT FILE PATH \" + this.filePath);\r\n }",
"function getFilePath(fileName) {\n return os.userInfo().homedir + \"\\\\AppData\\\\Roaming\\\\.minecraft\\\\mcpipy\\\\\" + fileName + \".py\";\n}",
"function addFile(file) {\n files.set(file._template, file);\n fileView.appendChild(file.getTemplate());\n}",
"pathToFileUrl(url) {\n const filePrefix = process.platform === \"win32\" ? \"file:///\" : \"file://\";\n return filePrefix + url;\n }",
"function createCompositeXLIFFFile(sourceLanguage, sourceFile, targetLanguage, targetFile, options) {\n\n\n var sourceReactObj = readFileToJSONObject(sourceFile);\n var targetReactObj = readFileToJSONObject(targetFile);\n\n /*\n for key in sourceReactObj\n createTransUnitElement\n createNestedElement for sourceObj, populate\n createNestedElement for targetObj, if present in targetFile populate\n */\n}",
"function getFileObject(filePathOrUrl, cb) {\n getFileBlob(filePathOrUrl, function(blob) { //fn2 //llama a la funcion getFileBlob con el url introducido y una funcion que: \n cb(blobToFile(blob, '' + $$(\"#nuevocodigo\").val() + '.jpg')); //ejecuta nuestro cb (callback) sobre el blob con nombre y fecha cambiada (el nombre sera 'test.jpg')\n });\n }",
"function touchCoffee() {\n\n fs.open( 'main.coffee', 'rs', function( err, fd ) {\n if ( err && err.code == 'ENOENT' ) {\n exec('touch main.coffee',\n function ( error ) {\n if (error !== null) {\n console.log( 'exec error: ' + error );a\n } else {\n // Pass a console message saying that it's been created\n console.log( '\"coffee/main.coffee\" created!\\n' )\n }\n });\n } else {\n // If a folder DOES exists, don't download it\n // Pass a console message saying so and stop the fs process\n console.log( chalk.red( '\"coffee/main.coffee\" exists...don\\'t create it.\\n' ) );\n fs.close( fd );\n }\n })\n\n} // end \"touchCoffee()\"",
"buildFileComponent(file) {\n return React.createElement(FileComponent, { file: file, key: file._meta.token });\n }",
"function gotoFileNew(path, lookupExpression, line, column)\n{\n\tcommand = '\\\nENV[\"TM_BUNDLE_SUPPORT\"] \t\t= \"' + ENV[\"TM_BUNDLE_SUPPORT\"] \t\t+ '\";\\\nENV[\"TM_PROJECT_DIRECTORY\"] = \"' + ENV[\"TM_PROJECT_DIRECTORY\"] \t+ '\";\\\nENV[\"TM_SUPPORT_PATH\"] \t\t= \"' + ENV[\"TM_SUPPORT_PATH\"] \t\t+ '\";\\\nrequire \"#{ENV[\"TM_BUNDLE_SUPPORT\"]}/navigator.rb\";\\\nNavigator.goto_file \"' + path + '\", ' + lookupExpression+', ' + line + ', ' + column + '\\n\\\n';\n\n\tconsole.log(\"Final command\\n\"+command);\n\tcallTMScript(command, null, path, line, column, null, \"showAsHTML\");\n\tconsole.log(\"Execution result status=\"+process.status+\" output=\\n\" +process.outputString+\"errors=\"+process.errorString);\n}",
"createFarmSymLinks() {\n let enabledFarmsPath = path.join(\n commons_constants.TARGET_DISPATCHER_SRC_FOLDER,\n Constants.CONF_DISPATCHER_D,\n Constants.ENABLED_FARMS\n );\n let conversionStep = this.createFarmSymLinksSummaryGenerator();\n let files =\n glob.sync(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_DISPATCHER_D,\n Constants.AVAILABLE_FARMS,\n \"*.farm\"\n )\n ) || [];\n files.forEach((file) => {\n logger.info(\n \"Single File Converter: Creating Farm Symbolic Link in target folder for file : \" +\n file\n );\n // if the symbolic link doesnt exist - lets create it.\n if (\n !fs.existsSync(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_DISPATCHER_D,\n Constants.ENABLED_FARMS,\n path.basename(file)\n )\n )\n ) {\n fs.symlinkSync(\n \"../available_farms/\" + path.basename(file),\n path.join(enabledFarmsPath, path.basename(file))\n );\n logger.info(\n \"Single File Converter: Created Farm Symbolic Link in target folder for file : \" +\n file\n );\n conversionStep.addOperation(\n new ConversionOperation(\n commons_constants.ACTION_ADDED,\n file,\n `Generated SymLink for the file ${path.basename(file)}`\n )\n );\n }\n });\n\n this.conversionSteps.push(conversionStep);\n }",
"function onFileInitialize(model) {\n var string = model.createString();\n string.setText(activeFile.content);\n model.getRoot().set('collabString', string);\n}",
"_writingSampleCode() {\n\n this.fs.copy(\n this.templatePath('sample/src/templates/HelloWorld.hbs'),\n this.destinationPath('src/webparts/templates/HelloWorld.hbs')\n )\n\n }",
"async function addFile(){\n\t\trouter.push(`/files/${filetype}/create${filetype}/${fileFolderID}`)\n\t}",
"function addFileToProject(path, id, icon) {\n\tvar projFolder = air.EncryptedLocalStore.getItem( 'directory' );\n\tvar filename = id + '.png';\n\tvar newPNG = new air.File(path);\n\tvar device = air.EncryptedLocalStore.getItem( 'device' );\n\tif(!device) return;\n\tstr = imageFolder(device, icon) + filename;\n\tvar proj = new air.File( projFolder + str);\n\tnewPNG.copyTo(proj, true);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getText(n): Find all Text nodes at or beneath the node n. Concatenate and return as a string. | function getText(n)
{
var strings = [];
getStrings(n, strings);
return strings.join("");
// Recursive inner function.
function getStrings(n, strings)
{
if(n.nodeType == 3 ) /* node.TEXT_NODE */
strings.push(n.data);
else if (n.nodeType == 1 ) /* node.ELEMENT_NODE */
for(var m=n.firstChild; m!=null; m = m.nextSibling )
{
getStrings(m, strings);
}
}
} | [
"string(node) {\n if (Text.isText(node)) {\n return node.text;\n } else {\n return node.children.map(Node$1.string).join('');\n }\n }",
"function getDocumentText(element) {\n element = $(element) || $(\"body\");\n var params = { \"text\": \"\", \"trim\": true };\n\n // iterate through all children of body element\n if (element.length > 0) {\n var children = element[0].childNodes;\n for (var i = 0; i < children.length; i++) {\n var child = children[i];\n params = iterateText(child, addText, params);\n }\n } else {\n console.log(\"element does not exist. no text retrieved\");\n }\n return params.text;\n}",
"function getTextNode(tableCellObj){\n var iter=tableCellObj.childNodes;\n var counter=0;\n var child=iter.item(counter);\n var retVal=\"\";\n\n while (child) {\n retVal+=getTextNode(child);\n child=iter.item(++counter);\n }\n\n if (tableCellObj.nodeType == Node.TEXT_NODE)\n retVal+=tableCellObj.data;\n\n // Replace white space \n retVal = retVal.replace(/\\s+/gi,' ');\n retVal = retVal.replace(/^\\s+/,'');\n retVal = retVal.replace(/\\s+$/,'');\n\n return retVal;\n}",
"function collectTextNodes($, $el) {\n let textNodes = [];\n $el.contents().each((ii, node) => {\n if (isTextNode(node)) {\n let $node = $(node);\n textNodes.push($node);\n } else {\n textNodes.push(...collectTextNodes($, $(node)));\n }\n });\n return textNodes;\n}",
"function merge(n) {\n if (n.nodeType === Node.TEXT_NODE) {\n if (n.nextSibling && n.nextSibling.nodeType === Node.TEXT_NODE) {\n n.textContent += n.nextSibling.textContent;\n n.nextSibling.parentNode.removeChild(n.nextSibling);\n }\n\n if (n.previousSibling && n.previousSibling.nodeType === Node.TEXT_NODE) {\n n.previousSibling.textContent += n.textContent;\n n.parentNode.removeChild(n);\n }\n }\n}",
"function runText(elem, f)\r\n{\r\n // text node\r\n if (elem.nodeType == 3)\r\n {\r\n return f(elem);\r\n }\r\n\r\n // iterate over children recursively\r\n elem = elem.firstChild;\r\n if (elem)\r\n {\r\n do\r\n {\r\n var ret = runText(elem, f);\r\n if (ret) {\r\n return ret;\r\n }\r\n }\r\n while (elem = elem.nextSibling);\r\n }\r\n return 0;\r\n}",
"get text() {\n return (this._textElement || this._element).textContent;\n }",
"*texts(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n for (var [node, path] of Node$1.nodes(root, options)) {\n if (Text.isText(node)) {\n yield [node, path];\n }\n }\n }",
"function getElementText(parent, elementName) {\n\tvar list = parent.getElementsByTagName(elementName);\n\tif (list == null || list.length == 0) {\n\t\t//Invalid element name\n\t\treturn null;\n\t}\n\tvar e = list[0];\n\tvar txt = \"\";\n\t\n\tfor (var i = 0; i < e.childNodes.length; ++i) {\n\t\tvar n = e.childNodes[i];\n\t\tif (n.nodeType == 3) {\n\t\t\t//This is a text node\n\t\t\ttxt = txt + n.nodeValue;\n\t\t}\n\t}\n\t\n\treturn txt;\n}",
"textNodes(...args) {\n let filter = \"\", i = 0, a = [], recursive = false;\n $sel = $();\n while(arguments[i]){\n if (typeof arguments[i] === \"string\"){\n filter += (filter) ? \"|\" : \"\";\n filter += arguments[i];\n }else if (Array.isArray(arguments[i])){\n\t\t\t\t\tfilter += (filter) ? \"|\" : \"\";\n\t\t\t\t\tfilter += arguments[i].join(\"|\");\n\t\t\t\t}\n i++;\n }\n lastArg = arguments[arguments.length-1];\n if(typeof lastArg === \"boolean\" && lastArg) {recursive = true;}\n that = (recursive) ? this.find(\"*\").addBack() : this;\n that.each(function() {\n $sel = $sel.add($(this).contents());\n });\n $sel.each(function(){\n if(filter){\n reg = new RegExp(filter);\n }\n keep = (this.nodeType === 3 && (!filter || this.textContent.search(filter)+1)) ? true : false;\n if (keep) a.push(this);\n });\n $sel = $(a);\n $sel.prevObject = this;\n $sel.selector = filter;\n return $sel;\n }",
"function CLC_GetTextContent(target){\r\n if (!target){\r\n return \"\";\r\n }\r\n if (target.nodeType == 8){ //Ignore comment nodes\r\n return \"\";\r\n } \r\n var textContentFromRole = CLC_GetTextContentFromRole(target);\r\n if (textContentFromRole){\r\n return textContentFromRole;\r\n }\r\n //Ignore scripts in the body\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"script\"){\r\n return \"\";\r\n } \r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"noscript\"){\r\n return \"\";\r\n } \r\n //Do textarea twice because it may or may not have child nodes\r\n if (target.tagName && target.tagName.toLowerCase() == \"textarea\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText; \r\n }\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"textarea\"){\r\n var labelText = CLC_Content_FindLabelText(target.parentNode);\r\n return labelText; \r\n }\r\n //Same logic as textarea applies for buttons\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"button\"){\r\n var labelText = CLC_Content_FindLabelText(target.parentNode);\r\n return labelText + target.textContent; \r\n }\r\n if (target.tagName && target.tagName.toLowerCase() == \"button\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + target.textContent; \r\n }\r\n //Form controls require special processing\r\n if (target.tagName && target.tagName.toLowerCase() == \"input\"){\r\n if (target.type.toLowerCase() == \"radio\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindRadioButtonDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"checkbox\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindCheckboxDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"text\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindTextBlankDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"password\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindPasswordDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if ( (target.type.toLowerCase() == \"submit\") || (target.type.toLowerCase() == \"reset\") || (target.type.toLowerCase() == \"button\")){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + \" \" + target.value;\r\n }\r\n if (target.type.toLowerCase() == \"image\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + \" \" + target.alt;\r\n }\r\n return \"\";\r\n }\r\n //MathML element - Use the functions in clc_mathml_main.js to handle these\r\n if (target.tagName && target.tagName.toLowerCase() == \"math\"){\r\n return CLC_GetMathMLContent(target);\r\n }\r\n //Images\r\n if (target.tagName && target.tagName.toLowerCase() == \"img\"){\r\n if ( target.hasAttribute(\"alt\") && target.alt == \"\" ){\r\n return \"\";\r\n }\r\n if ( target.hasAttribute(\"alt\") ){\r\n return target.alt;\r\n }\r\n //Treat missing alt as null if the user is in Brief Mode\r\n if (CLC_InfoLang == 3){\r\n return \"\";\r\n }\r\n return target.src;\r\n }\r\n //Select boxes - ignore their textContent, only read out the selected value.\r\n //However, if there is a label, use it.\r\n if (target.tagName && target.tagName.toLowerCase() == \"select\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText;\r\n }\r\n //\"Normal\" elements that are just text content and do not require any special action\r\n if (target.textContent){\r\n return target.textContent;\r\n }\r\n return \"\";\r\n }",
"function getInlineTextValue(node)\n{\n if (( typeof node == 'undefined') || node == null)\n return \"\";\n\n if (isBackend) {\n return node.value;\n } else {\n var textValue = \"\";\n if(node.innerText){ // IE, Chrome, Opera\n textValue = node.innerText;\n } else {\n // Firefox\n // Note: there's no need to check <BR>, <br/> etc. as innerHTML unifies that to <br>\n textValue = node.innerHTML.replace(/<br>/gi, '\\n').replace(/(<([^>]+)>)/gi,\"\");\n }\n return textValue;\n }\n}",
"function $textContent(elem, val){ \n elem = $O(elem);\n var tc = '';\n\n if(typeof elem.textContent !== 'undefined'){\n if(typeof val === 'string'){\n elem.textContent = val;\n }\n tc = elem.textContent;\n }\n else{\n if(typeof val === 'string'){\n elem.innerText = val;\n }\n tc = elem.innerText;\n } \n return tc;\n}",
"toText() {\n // To avoid this, we would subclass documentFragment separately for\n // MathML, but polyfills for subclassing is expensive per PR 1469.\n // $FlowFixMe: Only works for ChildType = MathDomNode.\n const toText = child => child.toText();\n\n return this.children.map(toText).join(\"\");\n }",
"function getTextContent(element) {\r\n\r\n if (window.mozilla) {\r\n return element.textContent;\r\n }\r\n else {\r\n return element.innerText\r\n }\r\n}",
"getHasText(texts) {\n return this._node.eachCompare(this._node.$, (element, expected) => element.currently.hasText(expected), texts);\n }",
"function processText (node, div, queue) {\n const text = node.textContent;\n try {\n Expect(div).is.ok();\n Expect(div.noText).is.not.true();\n Expect(div.break).is.not.true();\n if (div.link) {\n if (!div.linkText) {\n Expect(_.startsWith(text, 'http')).is.true();\n div.linkText = true;\n } else {\n Expect(div.linkSuffix).is.not.true();\n Expect(text.charAt(0)).is.equal(',');\n div.linkSuffix = true;\n }\n }\n } catch(err) {\n console.log(`text: ${text}`);\n console.log(`node: ${Stringify(div)}`);\n let prev = queue.pop();\n console.log(`prevNode: ${prev && Stringify(prev)}`);\n throw err;\n }\n return text;\n}",
"function showNodeChildrenByText(nodeText, nodeType, index) {\n // figure logic in here to check if already expanded. Only perfom following if now already expanded\n if (typeof index == \"undefined\") {\n index = 0;\n }\n\n switch (nodeType) {\n case 'folder':\n return waitTillElementVisible(fileTree.expandCollapseFolderNode(nodeText, index))\n .then(function () {\n return fileTree.expandCollapseFolderNode(nodeText, index).click();\n });\n break;\n case 'document':\n return waitTillElementVisible(fileTree.expandCollapseDocumentNode(nodeText, index))\n .then(function () {\n return fileTree.expandCollapseDocumentNode(nodeText, index).click();\n });\n break;\n }\n\n}",
"function getAllTextNotes(){\n\tvar count = 0;\n\ttext_noteRef.once(\"value\")\n\t .then(function(snapshot) {\n\t\t snapshot.forEach(function(childSnapshot) {\n\t\t \tcount += 1;\n\t\t var eachNote = childSnapshot.val();\n\t\t showTextNote(childSnapshot.key, eachNote.note);\n\t\t });\n\t });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
'saveUserThemeConfig' method is used to call the web method 'SaveUserThemeConfig' to save the user id,themeid through ajax call . | function saveUserThemeConfig(selectedThemeID) {
$.ajax({
type: "POST",
url: opts.serviceUrl + "SaveUserThemeConfig",
data: "{ themeID :'" + selectedThemeID + "'}",
contentType: "application/json",
dataType: "json",
success: function (datap) {
window.location.reload(false);
}
});
} | [
"function getThemeConfigItems(themeListDiv) {\n $.ajax({\n type: \"POST\",\n url: opts.serviceUrl + \"GetThemeItems\",\n data: \"{}\",\n contentType: \"application/json;charset=utf-8\",\n dataType: \"json\",\n success: function (datap) {\n var themeConfigItems = datap.d;\n var themeUl = $(\"<ul class='xp-LifeCycleOuterDiv xp-ThemeLi'/>\");\n /*\n *if theme list contains only one item no need add button\n */\n if (themeConfigItems == 0) {\n \tthemeListDiv.append(\"<li><a class='xp-TabLink xp-FloatLeft xp-HoverCursor xp-MarginLeft-12 '>\" + themeConfigItems[i].m_ThemeName + \"</a></li>\");\n }\n /*\n *if theme items count is greater than one , add button by selecting theme and \n *corresponding preview image in img div and call savethemeconfig ajax call through web method \"SaveUserThemeConfig\"\n */\n else {\n $.each(themeConfigItems, function (i) {\n \tvar themeLi = $(\"<li class='xp-FloatLeft' id='\" + themeConfigItems[i].m_ID + \"'><a class='xp-HoverCursor xp-TabLink xp-FloatLeft xp-MarginLeft-12 '>\" + themeConfigItems[i].m_ThemeName + \"</a></li>\").click(function () {\n /*if li already doesn't contains input button add button or else do nothing and \n *default theme high light and there is no button will add by selecting default theme\n */\n \tif ($(this).has('input').length == 0 && themeConfigItems[i].m_IsSelected == false) {\n \t\t$('li').removeClass(\"xp-Customhighlight\");\n \t\t$(this).addClass(\"xp-Customhighlight\");\n \t\t$(\"#\" + ids.themeSave).remove();\n \t\t$(\".dynamicTriangle\").remove();\n \t\t$(\"#\" + ids.themeImage).html('<img src=\"' + themeConfigItems[i].m_ImageUrl + '\"/>');\n \t\t$(this).append(\"<input autocomplete='off' id='\" + ids.themeSave + \"'class='xp-HoverCursor ui-primarytabclr ui-tabbuttonstyle ui-corner-all xp-FloatRight' type='button' value='Apply'></input>\");\n \t\t$(this).append(\"<span class='dynamicTriangle notch '/><span class='dynamicTriangle notch2'/>\");\n \t\t$(\"#\" + ids.themeSave).click(function () {\n \t\t\t$(\"#\" + ids.themeSave).remove();\n \t\t\tsaveUserThemeConfig(themeConfigItems[i].m_ID);\n \t\t});\n \t}\n else if (themeConfigItems[i].m_IsSelected == true) {\n \t$('li').removeClass(\"xp-Customhighlight\");\n \t$(\".dynamicTriangle\").remove();\n \t$(this).addClass(\"xp-Customhighlight\");\n \t$(this).append(\"<span class='dynamicTriangle notch '/><span class='dynamicTriangle notch2'/>\");\n \t$(\"#\" + ids.themeSave).remove();\n \t$(\"#\" + ids.themeImage).html('<img src=\"' + themeConfigItems[i].m_ImageUrl + '\"/>');\n }\n });\n if (themeConfigItems[i].m_IsSelected == true) {\n \t$(\"#\" + ids.themeImage).html('<img src=\"' + themeConfigItems[i].m_ImageUrl + '\"/>');\n \t$(themeLi).addClass(\"xp-Customhighlight\");\n \t$(themeLi).append(\"<span class='dynamicTriangle notch '/><span class='dynamicTriangle notch2'/>\");\n }\n $(themeUl).append(themeLi);\n $(themeListDiv).append(themeUl);\n });\n }\n }\n });\n return false;\n }",
"function save_theme(e) {\n var theme = e.target.id;\n chrome.storage.sync.set({\"theme\": theme}, function() {\n document.location.reload();\n });\n}",
"function setTheme(event, obj){\n function save(theme){\n storage.set({ 'devtools-theme': theme.value },\n function(){ panel.currentTheme = theme.text; });\n }\n if (event && event.type === 'change'){\n $themeTitle.style.display = 'none';\n var el = event.target || event.srcElement;\n var option = el.options[el.selectedIndex];\n save(option);\n $('.alert')[0].style.display = 'block';\n } else if (event === null && obj){\n save(obj);\n }\n }",
"function saveConfigtoDB(confName,ftype){\n\tfor(var a=0; a< globalMAINCONFIG.length;a++){\n\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Flag = 0;\n\t\tif(globalMAINCONFIG[a].MAINCONFIG[0].PageCanvas == pageCanvas){\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].FileType = $('#saveConfFileTypeDBType > option:selected').html().toString();\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Name = confName;\n\t\t}\n\t}\n\tvar qry = getStringJSON(globalMAINCONFIG[pageCanvas]);\n\t$.ajax({\n\t\turl: getURL(\"ConfigEditor\", \"JSON\"),\n\t\tdata : {\n\t\t\t\"query\": qry,\t\t\t\n\t\t\t\"action\": \"insert\"\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tvar dat = data.replace(/'/g, '\"');\n\t\t\tvar data = $.parseJSON(dat);\n\t\t\tvar result = data.RESULT[0].Result;\n\t\t\tif(result==1){\n\t\t\t\talerts(\"Configuration saved to the database.\",\"todo\", \"graph\");\n\t\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].Flag =1;\n\t\t\t\tFileType =\"\";\n\t\t\t\tvar todo = \"if(globalDeviceType=='Mobile'){\";\n\t\t\t\t\ttodo += \"$('#saveConfig').dialog('destroy');\";\n\t\t\t\t\ttodo +=\t\"}else{\";\n\t\t\t\t\ttodo +=\t\"$('#configPopUp').dialog('destroy');\"\n\t\t\t\t\ttodo += \"}\";\n\t\t\t}else{\n\t\t\t\talerts(\"Something went wrong. \\nConfiguration NOT saved on the database.\");\n\t\t\t}\n\t\t}\n\t});\n}",
"function showConfigUser() {\n\n\tdocument.getElementById('sel_editor_font_size').value = v_editor_font_size;\n\tdocument.getElementById('sel_editor_theme').value = v_theme_id;\n\n\tdocument.getElementById('txt_confirm_new_pwd').value = '';\n\tdocument.getElementById('txt_new_pwd').value = '';\n\n\t$('#div_config_user').show();\n\n}",
"function handleSaveUserPreferences() {\n var language = $('#languagePrefs').find(\":selected\").text();\n var routingLanguage = $('#routingLanguagePrefs').find(\":selected\").text();\n var distanceUnit = $('#unitPrefs').find(\":selected\").text();\n //var baseLayer = $('input[name=layerSwitcherPanel_baseLayers]:checked').val();\n //language: one of list.languages\n language = preferences.reverseTranslate(language);\n //routing language: one of list.routingLanguages\n routingLanguage = preferences.reverseTranslate(routingLanguage);\n //units: one of list.distanceUnitsInPopup\n distanceUnit = distanceUnit.split(' / ');\n for (var i = 0; i < distanceUnit.length; i++) {\n for (var j = 0; j < list.distanceUnitsPreferences.length; j++) {\n if (distanceUnit[i] === list.distanceUnitsPreferences[j]) {\n distanceUnit = list.distanceUnitsPreferences[j];\n i = distanceUnit.length;\n break;\n }\n }\n }\n theInterface.emit('ui:saveUserPreferences', {\n language: language,\n routingLanguage: routingLanguage,\n distanceUnit: distanceUnit\n });\n //hide preferences window\n $('#sitePrefsModal').modal('hide');\n }",
"function savedatainsession(id){\n\tvar addeduser = \"\";\n\tif(userExistArray.length != 0){\n\t\tfor(var t=0; t<userExistArray.length; t++){\n\t\t\tif(t == 0){\n\t\t\t\taddeduser = userExistArray[t];\n\t\t\t}else{\n\t\t\t\taddeduser += \",\"+ userExistArray[t];\n\t\t\t}\n\t\t}\n\t}\n\t$('#'+id).empty();\n\tcloseDialog(id);\n\tvar sessionid = seletedSessionId.split(\"__\");\n\tvar url = getURL('Console') + \"action=putConsoleInvitation&query={'MAINCONFIG': [{'user': '\"+globalUserName+\"','addeduser': '\"+addeduser+\"','sessionid': '\"+sessionid[1]+\"'}]}\";\n $.ajax({\n url: url,\n dataType: 'html',\n method: 'POST',\n proccessData: false,\n async:false,\n success: function(data) {\n \tdata = $.trim(data);\n\t\t\tgetActiveUser();\n\t\t}\n });\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}",
"function updateThemeWithAppSkinInfo(appSkinInfo) {\n // console.log(appSkinInfo)\n var panelBgColor = appSkinInfo.panelBackgroundColor.color;\n var bgdColor = toHex(panelBgColor);\n var fontColor = \"F0F0F0\";\n if (panelBgColor.red > 122) {\n fontColor = \"000000\";\n }\n \n var styleId = \"hostStyle\";\n addRule(styleId, \"body\", \"background-color:\" + \"#\" + bgdColor);\n addRule(styleId, \"body\", \"color:\" + \"#\" + fontColor);\n \n var isLight = appSkinInfo.panelBackgroundColor.color.red >= 127;\n if (isLight) {\n $(\"#theme\").attr(\"href\", \"css/topcoat-desktop-light.css\");\n } else {\n $(\"#theme\").attr(\"href\", \"css/topcoat-desktop-dark.css\");\n }\n }",
"function Save_User_BG_Color (type) {\n if (type === \"save\") {\n body.classList.add(\"userbg_color\")\n var usercolor_llama = document.getElementById(\"llama_clear_user_bgcolorsrc\").value\n document.documentElement.style.setProperty(\"--thememode-user_bgcolor\", usercolor_llama)\n localStorage.setItem(\"llama_user_bgcolorsrc\", usercolor_llama)\n } else if (type === \"reset\") {\n body.classList.remove(\"userbg_color\")\n document.documentElement.style.setProperty(\"--thememode-user_bgcolor\", \"\")\n document.getElementById(\"llama_user_bgcolorsrc\").value = \"\"\n document.documentElement.style.setProperty(\"--thememode-user_bgcolor\", \"\")\n localStorage.setItem(\"llama_user_bgcolorsrc\", \"\")\n } else if (type === \"open\") {\n body.classList.toggle(\"userbg_color\")\n }\n}",
"function dml_Save_Settings_Panel() {\n\tvar myApiCode = jQuery(\"#dmlMapApiCode\").val();\n\tvar myMapHeight = jQuery(\"#dmlMapHeight\").val();\n\tvar myMapType = dmlmyArr[0].dml_fill_color;\n\tvar dmlMapCustomCode;\n\tif (myMapType == 0) {\n\t\tdmlMapCustomCode = jQuery(\"#dmlCustomStyleCode\").val();\n\t} else {\n\t\tdmlMapCustomCode = '.';\n\t}\n\tvar myMapZoom = jQuery(\"#dmlMapZoom\").val();\n\n\tvar dmlTrafficLayerVal = 0;\n\tvar dmlTransportLayerVal = 0;\n\tvar dmlBicycleLayerVal = 0;\n\tvar dmlScrollLockVal = 0;\n\tif (jQuery(\"#dmlTrafficChb\").is(':checked') == true) {\n\t\tdmlTrafficLayerVal = 1;\n\t}\n\tif (jQuery(\"#dmlTransportChb\").is(':checked') == true) {\n\t\tdmlTransportLayerVal = 1;\n\t}\n\tif (jQuery(\"#dmlBcycleChb\").is(':checked') == true) {\n\t\tdmlBicycleLayerVal = 1;\n\t}\n\tif (jQuery(\"#dmlScrollLockChb\").is(':checked') == true) {\n\t\tdmlScrollLockVal = 1;\n\t}\n\t\n\tvar dmlLayerStatusToDb = dmlTrafficLayerVal + '_' + dmlTransportLayerVal + '_' + dmlBicycleLayerVal + '_' + dmlScrollLockVal;\n\n\t// Validating data\n\tif (!myApiCode || !myMapHeight || !myMapZoom || !dmlMapCustomCode) {\n\t\talert(\"All text areas are required\");\n\t} else if (!jQuery.isNumeric(myMapHeight) || !jQuery.isNumeric(myMapZoom)) {\n\t\talert(\"Please enter numeric value for Map Height and Zoom fields.\");\n\t} else {\n\t\tdmlDbStatus = 0; // Map will be reloaded\n\t\tjQuery(\"#dmlSettingsDiv\").modal(\"toggle\");\n\n\t\tvar ajax_data = {\n\t\t\taction: \"dml_call_ajax\",\n\t\t\tdml_backend_function: 3,\n\t\t\tdml_page_link: jQuery(\"#dml_map_list option:selected\").val(),\n\t\t\tdml_post_id: dmlmyArr[0].dml_id,\n\t\t\tdml_api_code: myApiCode,\n\t\t\tdml_height_title: myMapHeight,\n\t\t\tdml_fill_color: dmlmyArr[0].dml_fill_color,\n\t\t\tdml_border_color: dmlMapCustomCode,\n\t\t\tdml_zoom_icon: myMapZoom,\n\t\t\tdml_layers: dmlLayerStatusToDb,\n\t\t}\n\t\tdml_Call_Ajax(ajax_data, 1);\n\t}\n\n}",
"function syncConfigSettingsDataCB(obj){\n \n}",
"saveChartStyle() {\n sessionStorage.saved_style = 1;\n const styleElements = $('.chart-style-wrapper .form-control');\n styleElements.each(function() {\n const id = $(this).attr('id');\n const key = `styles.${id}`;\n const value = $(this).val();\n sessionStorage.setItem(key, value);\n });\n sessionStorage.setItem('switch.bw', $('#dataset_black_and_white').prop('checked'));\n // this.loadData();\n }",
"function handleSaveCreds() {\n /* To show the progress bar */\n showProgressBar();\n var billerCorpId = null, programId = null, billerCorpAccountId = null;\n var strNick = \"\" + $('#nickName').val();\n var nickname = strNick.replace(/[\\<\\>\\;\\&\\/]/g, '').trim();\n var nickNameLabelId = $('#nickNameSec > label:first').attr('id');\n if(nickNameLabelId) {\n\t billerCorpId = nickNameLabelId.split('_')[0];\n\t programId = nickNameLabelId.split('_')[1] === 'null' ? null : nickNameLabelId.split('_')[1];\n\t billerCorpAccountId = nickNameLabelId.split('_')[2] === 'null' ? null : nickNameLabelId.split('_')[2];\n }\n var request = new Object();\n request.userId = eval(getCookie('userId'));\n request.billerCorpId = billerCorpId ;\n if(programId) {\n \trequest.programId = programId;\n }\n if(billerCorpAccountId) {\n \trequest.billerCorpAccountId = billerCorpAccountId;\n }\n request.applicationId = applicationId;\n request.locale = getCookie(\"locale\");\n request.nickname = nickname;\n request.accountCredentials = new Array();\n var credCount = 0;\n for (var billerCredsId in billerCredElements) {\n var elementObj = billerCredElements[billerCredsId];\n var inputElementValue = replaceUnUsedChar(\"element\" + billerCredsId);/*adding element for bug 4932 \n which is disturbed by bug 4944 now fixed*/\n if (inputElementValue) {\n \trequest.accountCredentials[credCount] = new Object();\n request.accountCredentials[credCount].elementId = billerCredsId;\n /* Checking for PHONE and DATE box type and getting only number from the input field */\n if (elementObj.elementType === \"PHONE_BOX\" || elementObj.elementType === \"DATE_BOX\") {\n if (elementObj.securedFlag) {\n if (!/^[\\\\*]*$/.test(inputElementValue)) {\n inputElementValue = getNumberFromString(inputElementValue);\n }\n } else {\n inputElementValue = getNumberFromString(inputElementValue);\n }\n }\n billerCredsId == 21 ? request.accountCredentials[credCount].value = inputElementValue.toUpperCase() \n \t\t: request.accountCredentials[credCount].value = inputElementValue;\n credCount++;\n } else {\n \tif(bpGetCorpAccountMap[billerCredsId]){\n \t\trequest.accountCredentials[credCount] = new Object();\n request.accountCredentials[credCount].elementId = billerCredsId;\n billerCredsId == 21 ? request.accountCredentials[credCount].value = inputElementValue.toUpperCase() \n \t\t: request.accountCredentials[credCount].value = inputElementValue;\n \t\tcredCount++;\n \t}\n }\n }\n var call_bp_save_biller_corp_acct_creds = new bp_save_biller_corp_acct_creds(request);\n call_bp_save_biller_corp_acct_creds.call();\n}",
"function saveConfigtoDBTestbed(confName){\n\tif(globalDeviceType==\"Mobile\"){\n\t\tloading(\"show\");\n\t}\n//\tMainFlag = 0;\n\t//FileType = \"Dynamic\";\n\tfor(var a=0; a< globalMAINCONFIG.length;a++){\n\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Flag = 0;\n\t\tif(globalMAINCONFIG[a].MAINCONFIG[0].PageCanvas == pageCanvas){\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].FileType = $('#saveConfFileTypeDBType > option:selected').html().toString();\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Name = confName;\n\t\t}\n\t}\n\n\tvar qry = getStringJSON(globalMAINCONFIG[pageCanvas]);\n\t$.ajax({\n\t\turl: getURL(\"ConfigEditor\", \"JSON\"),\n\t\tdata : {\n\t\t\t\"action\": \"savetopology\",\n\t\t\t\"query\": qry\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tvar dat=data.replace(/'/g,'\"');\n\t\t\tvar data = $.parseJSON(dat);\n\t\t\tvar result = data.RESULT[0].Result;\n\t\t\tif(result == 1){\n\t\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\t\tloading(\"hide\");\n\t\t\t\t}\n\t\t\t\talerts(\"Configuration saved to the database.\", \"todo\", \"graph\");\n\t\t\t\tMainFlag =1;\n\t\t\t\tFileType =\"\";\n\t\t\t\tvar todo = \"if(globalDeviceType!='Mobile'){\";\n\t\t\t\ttodo +=\t\"$('#deviceMenuPopUp').dialog('destroy');\";\n\t\t\t\ttodo += \"$('#configPopUp').dialog('destroy');\";\n\t\t\t\ttodo += \"}else{\";\n\t\t\t\ttodo +=\t\"$('#saveConfig').dialog('destroy');\";\n\t\t\t\ttodo += \"}\";\n\t\t\t}else{\n\t\t\t\talerts(\"Something went wrong, configuration could not be save.\");\n\t\t\t}\n\t\t}\n\t});\n}",
"function changeTheme(){\n\tvar new_theme = $('#theme').val();\n\teditor.setTheme(\"ace/theme/\"+new_theme);\n}",
"function save_options() {\n\t\n\tchrome.extension.getBackgroundPage().userSettings.ip = document.getElementById('ip').value; \n\tchrome.extension.getBackgroundPage().userSettings.port = document.getElementById('port').value; \n\tchrome.extension.getBackgroundPage().userSettings.username = document.getElementById('username').value; \n\tchrome.extension.getBackgroundPage().userSettings.password = document.getElementById('password').value; \n\n\tconsole.log(\"save_options\");\n\t//console.log(chrome.extension.getBackgroundPage().userSettings.ip);\n\t//console.log(chrome.extension.getBackgroundPage().userSettings.port);\n\t//console.log(chrome.extension.getBackgroundPage().userSettings.username);\n\t//console.log(chrome.extension.getBackgroundPage().userSettings.password);\n\n\tchrome.storage.sync.set({\n\t\tip: chrome.extension.getBackgroundPage().userSettings.ip,\n\t\tport: chrome.extension.getBackgroundPage().userSettings.port,\n\t\tusername: chrome.extension.getBackgroundPage().userSettings.username,\n\t\tpassword: chrome.extension.getBackgroundPage().userSettings.password || \"\",\n\t}, function() {\n\t\t\n\t\tif (chrome.runtime.lastError)\n\t\t{\n\t\t\tconsole.log(chrome.runtime.lastError);\n\t\t}\n\t\telse\n\t\t{\n\t\t// Notify that we saved.\n\t\tconsole.log('Settings saved!!!');\n\t}\n});\n}",
"function saveConfirmUserSetting(event, ui){\n var dontShowAgainOption = $(this).parent().find(\"#perc_show_again_check\").is(':checked');\n if (dontShowAgainOption) {\n var currentUser = $.PercNavigationManager.getUserName();\n var confirmDialogId = $(this).parent().attr('id');\n var cookieKey = \"dontShowAgain-\" + currentUser + \"-\" + confirmDialogId;\n $.cookie(cookieKey, \"true\");\n }\n}",
"function ajaxCallForUpdateBlog(data){\n console.log(\"in Update log \",data);\n $.ajax({\n url:\"/blog/editPost/\"+blogId,\n type: 'POST',\n async: true,\n data: JSON.stringify(data),\n contentType: 'application/json',\n context: this,\n cache: false,\n processData: false,\n success: function(response) {\n console.log('Blog submission succesfull',response);\n if(response.statusCode == 200 ){\n window.location = \"/blog/blogUpdateSummary?status=200\";\n }\n else{\n window.location = \"/blog/blogUpdateSummary\";\n }\n },\n error: function(response) {\n console.log('Error with blog submission ' + response.statusText);\n console.log(\"error page\");\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a bunch of traders from traders_spec returns tuple (n_buyers, n_sellers) optionally shuffles the pack of buyers and the pack of sellers | function populate_market(traders_spec, traders, shuffle, verbose){
function trader_type(robottype, name){
if (robottype === 'GVWY'){
return new Trader_Giveaway('GVWY', name, 0.00, 0);
}else if (robottype === 'ZIC'){
return new Trader_ZIC('ZIC', name, 0.00, 0);
}else if (robottype === 'SHVR'){
return new Trader_Shaver('SHVR', name, 0.00, 0);
}else if (robottype === 'SNPR'){
return new Trader_Sniper('SNPR', name, 0.00, 0);
}else if (robottype === 'ZIP'){
return new Trader_ZIP('ZIP', name, 0.00, 0);
}else{
// sys.exit('FATAL: don\'t know robot type %s\n' % robottype)
}
}
function shuffle_traders(ttype_char, n, traders){
for (var swap=0; swap<n; swap+=1){
var t1 = (n - 1) - swap;
var t2 = int(random(0, t1));
var t1name = ttype_char+t1;
var t2name = ttype_char+t2;
traders[t1name].tid = t2name;
traders[t2name].tid = t1name;
var temp = traders[t1name];
traders[t1name] = traders[t2name];
traders[t2name] = temp;
}
}
var n_buyers = 0
for (var bsIndex=0; bsIndex<Object.keys(traders_spec['buyers']).length; bsIndex+=1){
var ttype = Object.keys(traders_spec['buyers'])[bsIndex];
for (var b=0; b<traders_spec['buyers'][ttype]; b+=1){
var tname = 'B' + n_buyers; // buyer i.d. string
traders[tname] = trader_type(ttype, tname);
n_buyers = n_buyers + 1;
}
}
if (n_buyers < 1){
// sys.exit('FATAL: no buyers specified\n')
}
if (shuffle){ shuffle_traders('B', n_buyers, traders);}
var n_sellers = 0
for (var ssIndex=0; ssIndex<Object.keys(traders_spec['sellers']).length; ssIndex+=1){
var ttype = Object.keys(traders_spec['sellers'])[ssIndex];
for (var s=0; s<traders_spec['sellers'][ttype]; s+=1){
var tname = 'S' + n_sellers; // buyer i.d. string
traders[tname] = trader_type(ttype, tname);
n_sellers = n_sellers + 1;
}
}
if (n_sellers < 1){
// sys.exit('FATAL: no buyers specified\n')
}
if (shuffle){ shuffle_traders('S', n_sellers, traders);}
if (verbose){
for (var t=0; t<n_buyers; t+=1){
var bname = 'B' + t;
}
for (var t=0; t<n_sellers; t+=1){
var bname = 'S' + t;
}
}
return [{'n_buyers':n_buyers, 'n_sellers':n_sellers},traders];
} | [
"function tiers(layers) {\n\t// verify layers has exactly 8 elements\n\tassert.equal(8, layers.length, \"expected 8 layers elements, got \" + layers.length);\n\n\t// pack it\n\tlet result = web3.toBigNumber(0);\n\tfor(let i = 0; i < layers.length; i++) {\n\t\tresult = result.times(256).plus(layers[i]);\n\t}\n\n\treturn result;\n}",
"async init(ctx) {\n // Initialize election\n let election = await this.getOrGenerateElection(ctx);\n await this.generateRegistrars(ctx);\n let voters = [];\n\n let votableItems = await this.generateVotableItems(ctx);\n //generate ballots for all voters\n for (let i = 0; i < voters.length; i++) {\n if (!voters[i].ballot) {\n //give each registered voter a ballot\n await this.generateBallot(ctx, votableItems, election.id, voters[i]);\n } else {\n console.log('these voters already have ballots');\n break;\n }\n }\n return voters;\n }",
"function createStimuliAndTaskSets(nTrials, blockLetter){\n let targetsArr, congruenciesArr, taskArr, stimArr;\n\n // create arrays for target and task based on congruencies\n congruenciesArr = createCongruencyArray(nTrials, blockLetter);\n taskArr = createTaskArray(nTrials, blockLetter);\n targetsArr = createTargetsArr(nTrials, congruenciesArr);\n\n // return zipped task and stim arr into one variable\n return stimTaskPairArr = targetsArr.map((s, i) => [s, taskArr[i]]);\n}",
"function gameLogicSetup() {\n //shuffle the multipliers array. multiplier at index 0 will be safe 1, index 1 safe 2 etc.\n shuffle(multipliers);\n //shuffle the safes then splice the array to get only 4 values\n shuffle(safes);\n selected_safes = safes.slice(0, 4);\n}",
"function assignPlayers(players) {\n const numberInvestor = Math.ceil(players.length / 2)\n return players.map((player, i) => {\n if (i < numberInvestor) {\n return createInvestor(player)\n }\n return createArtist(player)\n })\n}",
"function pizzaFactory() {\n let randomSizeIdx = Math.floor(Math.random() * 3)\n let randomAmtOfToppings = Math.floor(Math.random() * 2) + 1\n let toppings = []\n if(randomAmtOfToppings === 1) {\n let randomToppingIdx = Math.floor(Math.random() * 4)\n toppings.push(toppingAndMutiplier[randomToppingIdx])\n } else {\n let randomToppingIdx1 = Math.floor(Math.random() * 4)\n let randomToppingIdx2 = Math.floor(Math.random() * 4)\n while(randomToppingIdx2 === randomToppingIdx1) {\n randomToppingIdx2 = Math.floor(Math.random() * 4)\n }\n toppings.push(toppingAndMutiplier[randomToppingIdx1], toppingAndMutiplier[randomToppingIdx2])\n }\n \n\n let pizza = sizesAndPrices[randomSizeIdx]\n pizza.toppings = toppings\n\n return pizza\n}",
"function distributeCards() {\n let suspectsWithoutSecret = suspects.filter(function (x) {\n return x !== murderSecret[0];\n });\n let weaponsWithoutSecret = weapons.filter(function (x) {\n return x !== murderSecret[1];\n });\n let roomsWithoutSecret = rooms.filter(function (x) {\n return x !== murderSecret[2];\n });\n\n //remainning cards in the deck when secret triplet is taken out\n let combinedWithoutSecret = suspectsWithoutSecret.concat(weaponsWithoutSecret, roomsWithoutSecret);\n\n //shuffle the array using Fisher-Yates Shuffle Algorithm\n let shuffledWithoutSecret = shuffle(combinedWithoutSecret);\n console.log(\"Cards in deck: \");\n console.log(shuffledWithoutSecret);\n\n //distribute cards into halves\n userCards = shuffledWithoutSecret.slice(0, cardsPerUser);\n compCards = shuffledWithoutSecret.slice(cardsPerUser);\n\n console.log(userCards);\n console.log(compCards);\n\n let filteredSuspects = filterMe(suspects, userCards);\n let filteredWeapons = filterMe(weapons, userCards);\n let filteredRooms = filterMe(rooms, userCards);\n\n console.log(filteredSuspects);\n console.log(filteredWeapons);\n console.log(filteredRooms);\n\n populateMenu('suspects-option', filteredSuspects);\n populateMenu('weapons-option', filteredWeapons);\n populateMenu('rooms-option', filteredRooms);\n}",
"createGems(gems, totalGems){\r\n for (var x = 0; x < totalGems; x++){\r\n let gem = new Gem();\r\n gems.add(gem);\r\n }\r\n }",
"function distribute(gifts,socks){\n let s = socks.map((c,i)=>[c,i,0]).sort((a,b)=>a[0]-b[0]),\n g = gifts.sort((a,b)=>1*b-1*a); \n if (g.length >= s.length){\n let i = 0;\n for (let j = 0; 2*i < s.length - 1; i+=j,j=1-j)\n if (j){s[i][2]=g[i];}\n else{s[s.length-1-i][2] = g[g.length-1-i]}\n if (s.length%2)\n s[i][2]=g[i];\n } else {\n let i = 0;\n for (let j = 0; 2*i < g.length - 1; i+=j,j=1-j)\n if (j){s[i][2]=g[i];}\n else{s[s.length-1-i][2] = g[g.length-1-i]}\n if (g.length%2)\n s[i][2]=g[i];\n }\n return s.reduce((p,c)=>(p[c[1]]=c[2],p),[]);\n}",
"function loadTris(n){\n for(var i = 0; i < n; i++){\n tris[i] = new Triangle(20,60,random(-8,8),random(-8,8));\n }\n}",
"function getDealerCards() {\n for (i = 0; i < 2; i++) {\n const rndIdx = Math.floor(Math.random() * tempDeck.length);\n dealerHand.push(tempDeck.splice(rndIdx, 1)[0]);\n }\n renderDeckInContainer(dealerHand, dealerContainer);\n dealerScore.innerHTML = `dealer has: ${doTheDealerMath()}`;\n check();\n}",
"function make_balance_transport () {\n var targets = []\n\n test_transport.preload = function () {\n this.options({\n transport: {\n balance: {\n makehandle: function () {\n /*\n return function (pat, action) {\n targets.push(action)\n }\n */\n\n return function (actdef) {\n targets.push(actdef.func)\n }\n\n }\n }\n }\n })\n }\n\n return test_transport\n\n function test_transport (options) {\n var seneca = this\n\n var tu = seneca.export('transport/utils')\n\n seneca.add({\n role: 'transport', hook: 'client', type: 'balance'\n }, hook_client_test)\n\n function hook_client_test (args, clientdone) {\n var seneca = this\n var type = args.type\n var client_options = seneca.util.clean(Object.assign({}, options[type], args))\n\n tu.make_client(make_send, client_options, clientdone)\n\n var index = -1\n\n function make_send (spec, topic, send_done) {\n seneca.log.debug('client', 'send', topic + '_res', client_options, seneca)\n\n send_done(null, function (args, done, meta) {\n index = (index + 1) % targets.length\n targets[index].call(this, args, done, meta)\n })\n }\n\n seneca.add('role:seneca,cmd:close', function (close_args, done) {\n var closer = this\n closer.prior(close_args, done)\n })\n }\n }\n}",
"function generateRestaurantData(){\n return {\n name: faker.company.companyName(),\n borough: generateBoroughName(),\n cuisine: generateCuisineType(),\n address:{\n building: faker.address.streetAddress(),\n street: faker.address.streetName(),\n zipcode: faker.address.zipCode()\n },\n grades: [generateGrade(), generateGrade(), generateGrade()]\n };\n}",
"function generateRestaurantData() {\n return {\n name: faker.company.companyName(),\n borough: generateBoroughName(),\n cuisine: generateCuisineType(),\n address: {\n building: faker.address.streetAddress(),\n street: faker.address.streetName(),\n zipcode: faker.address.zipCode()\n },\n grades: [generateGrade(), generateGrade(), generateGrade()]\n };\n}",
"function generator(spectra, options) {\n let options = Object.assign({}, {nComb: 1, threshold: 0.5}, options)\n var weights = new Array(options.nComb);\n var combinations = new Array(options.nComb);\n for (var i = 0; i < options.nComb; i++) {\n var tmp = new Array(spectra[0].length).fill(0);\n var weight = new Array(spectra.length);\n for(var j = 0; j < spectra.length; j++) {\n weight[j] = Math.random();\n if (Math.random() > options.threshold) {\n for (var k = 0; k < spectra[0].length; k++) {\n tmp[k] += spectra[j][k]*weight[j];\n }\n } else weight[j] = 0;\n }\n weights[i] = weight;\n combinations[i] = tmp;\n }\n return {weights: weights, combinations: combinations};\n}",
"async function setupHeavyCommonCoin(tag, broker, reliableBroadcast, reliableReceive, newSecret = () => genSk()) {\n const n = broker.n, f = (n - 1)/3|0\n \n const { Z, G, As, shares:keys }\n = await setupKeygenProposalsStable(tag+'s', broker, reliableBroadcast, reliableReceive, newSecret)\n \n // combine threshold secrets to produce our share of the shared secret assigned to each node.\n const Akeys = arrayOf(n, i => As[i] && ({\n share: add(...As[i].map(j => keys[j].share)),\n pk: add(...As[i].map(j => keys[j].pk)),\n pubShares: arrayOf(n, x => add(...As[i].map(j => keys[j].pubShares[x])))\n }))\n \n function thresholdPRF(i, tag_) {\n const { share, pk } = Akeys[i]\n // we want to produce sk*hashToPoint(id), where sk is the shared secret assigned to i.\n const id = pk.encodeStr()+' '+i+' '+tag.length+tag+tag_\n return chaumPedersenProve(share, id)\n }\n \n function verifyPRFShare(i, tag_, sender, PRFShare) {\n const { pubShares, pk } = Akeys[i]\n const id = pk.encodeStr()+' '+i+' '+tag.length+tag+tag_\n return chaumPedersenVerify(pubShares[sender], id, PRFShare)\n }\n \n // after we've gone through the setup once, we return a much lighter function that can be called\n // with a subtag tag_ to run an individual coin instance.\n return (tag_) => {\n const result = defer()\n \n // produce our share of each node's shared secret for every node in G\n const shares = G.reduce((acc, i) => [...acc, [i, encodeData(thresholdPRF(i, tag_))]], [])\n broker.broadcast(tag+tag_, JSON.stringify(shares))\n \n // acceptedCoinShares[i][j] contains j's coin share of the local coin corresponding to i.\n const acceptedCoinShares = arrayOf(n, () => arrayOf(n))\n let count = 0\n broker.receive(tag+tag_, (i, m) => {\n const verifiedShares = arrayOf(n)\n \n // for each PRFshare i sent us, verify the CP proof on it\n let otherShares\n try {\n otherShares = JSON.parse(m).map(([j, PRFShareRaw]) => {\n // TODO we really only need to check the proofs for nodes in Z.\n decodeData(PRFShareRaw, chaumPedersenDecode, PRFShare => {\n if (verifyPRFShare(j, tag_, i, PRFShare)) verifiedShares[j] = PRFShare[0]\n })\n })\n } catch (e) { return }\n \n // i should have sent us a PRFshare for every node in Z. if not we reject.\n if (Z.every(j => verifiedShares[j])) {\n verifiedShares.forEach((sig, j) => acceptedCoinShares[j][i] = sig)\n count++\n } else return;\n \n if (count >= f+1) {\n // reconstruct all the local coins from nodes in Z and set common coin to 1 iff all\n // local coins didn't land on 0.\n result.resolve(Z.map(j => interpolate(acceptedCoinShares[j]))\n .every(sig => hashToScalar(sig.encodeStr()).val.modn(n+1) !== 0))\n }\n })\n \n return result.promise\n }\n}",
"function trade_stats(expid, traders, time, lob){\n var trader_types = {};\n var n_traders = traders.length;\n for (var tIndex=0; tIndex<traders.length; tIndex+=1){\n var ttype = traders[traders[tIndex]].ttype;\n if (trader_types[ttype]){\n var t_balance = trader_types[ttype]['balance_sum'] + traders[traders[tIndex]].balance;\n var n = trader_types[ttype]['n'] + 1;\n } else{\n var t_balance = traders[traders[tIndex]].balance;\n var n = 1;\n }\n trader_types[ttype] = {'n':n, 'balance_sum':t_balance};\n }\n}",
"function createRandomCatalog(num) {\n let catalog = [];\n for(let i = 0; i < num; i++) {\n let item = createRandomObject();\n let product = {id: i+1, price: item.price, type: item.type};\n \n catalog.push(product);\n }\n return catalog;\n }",
"function random(r) {\n var desks = []\n var firstDesk = Math.floor(Math.random() * r);\n desks[0] = firstDesk;\n console.log('firstDesk: ', firstDesk);\n var secondDesk = Math.floor(Math.random() * r);\n while(firstDesk === secondDesk) {\n secondDesk = Math.floor(Math.random() * r);\n\n }\n desks[1] = secondDesk;\n console.log('secondDesk: ', secondDesk);\n return desks;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get the solar irradiance after a location has been choosen | function getSolar(location, locationType) {
// If latitude & longitude are provided, send to the google API to get the city name
switch (locationType) {
case "lat_long":
parameters = {
lat: location[0],
lon: location[1]
};
// Google API to convert lat/lon to city, region, country
fetch(`/api/google/${JSON.stringify(parameters)}`)
.then(response => response.json())
.then(result => {
document.querySelector(
"#location"
).textContent = `${result[2].short_name}, ${result[4].short_name} ${result[5].short_name}`;
getUsage(result[4].short_name);
});
break;
case "name_string":
default:
document.querySelector("#location").textContent = location;
parameters = {
address: location
};
break;
}
// Calls the api to get the irradiance value for the location
fetch(`/api/solar/${JSON.stringify(parameters)}`)
.then(response => {
return response.json();
})
.then(result => {
// Displays hte irradiance and calculates out the necessary solar panel size for the residence
document.querySelector("#irradiance-result").textContent = result;
panelSize =
parseFloat(document.querySelector("#power").value * 12) /
(result * 365);
document.querySelector(
"#solarPanel"
).textContent = `${panelSize}`.substring(0, 5);
});
} | [
"function getAlt(latAlngA) {\n var elevator = new google.maps.ElevationService;\n elevator.getElevationForLocations({\n 'locations': [latAlngA]\n }, function(results, status) {\n //Checking to see if everything is functional\n if (status === 'OK') {\n // Gets the first result\n if (results[0]) {\n //Returns the elevation based on the coordinates provided\n alt = results[0].elevation;\n alti(alt);\n } \n }\n });\n}",
"function getMapStyleUI() {\n if ($(\"#rad1\")[0].checked) {\n return 'satellite';\n } else if ($(\"#rad2\")[0].checked) {\n return 'hybrid';\n } else if ($(\"#rad3\")[0].checked) {\n return 'terrain';\n } else if ($(\"#rad4\")[0].checked) {\n return 'roadmap';\n } \n }",
"function areaCirculo(radio){\n\nreturn (radio * radio) * PI;\n\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 getWeather() {\n\tif (searchBox.getPlaces().length > 0)\n\t{\n\t\tvar loc = searchBox.getPlaces().pop();\n\t\tvar latLon = loc.geometry.location.lat() + \",\" + loc.geometry.location.lng();\n\t\tgetCity(latLon);\n\t\tgetForecast(latLon);\n\t}\n\telse {\n\t\talert(\"Could not retrieve location. Please enter a new location\");\n\t}\n}",
"function computeLatLng(location) {\n\tlet l = location.levels.length;\n\tlet x = location.x;\n\tlet y = location.y;\n\t\n\tfor (let i=l-1; i>=0; i--) {\n\t\tlet level = +location.levels[i];\n\t\tif (level === 1) {\n\t\t\tx /= 2;\n\t\t\ty = y/2 + 0.5;\n\t\t} else if (level === 2) {\n\t\t\tx /= 2;\n\t\t\ty /= 2;\n\t\t} else if (level === 3) {\n\t\t\tx = x/2 + 0.5;\n\t\t\ty /= 2;\n\t\t} else if (level === 0) {\n\t\t\tx = (1 - x)/2;\n\t\t\ty = (1 - y)/2;\n\t\t}\n// \t\tconsole.log(level, x,y);\n\t}\n\t\n\tx /= 1 - y;\n\tx *= 90;\n\ty *= 90;\n\t\n\tif (location.octant == 0) {\n\t\tx -= 180;\n\t} else if (location.octant == 1) {\n\t\tx -= 90;\n\t} else if (location.octant == 2) {\n\t\tx += 0;\n\t} else if (location.octant == 3) {\n\t\tx += 90;\n\t} else if (location.octant == 4) {\n\t\tx -= 180;\n\t\ty = -y;\n\t} else if (location.octant == 5) {\n\t\tx -= 90;\n\t\ty = -y;\n\t} else if (location.octant == 6) {\n\t\tx += 0;\n\t\ty = -y;\n\t} else if (location.octant == 7) {\n\t\tx += 90;\n\t\ty = -y;\n\t}\n\t\n\tlocation.lat = y;\n\tlocation.lng = x;\n\t\n\treturn location;\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 getRearGear() {\n return bicycle.rearGear;\n}",
"function calcSun() {\n\tvar latitude = getLatitude();\n\tvar longitude = getLongitude();\n\tvar indexRS = solarDateTimeLatLong.mos;\n if (isValidInput(indexRS)) {\n if((latitude >= -90) && (latitude < -89)) {\n alert(\"All latitudes between 89 and 90 S\\n will be set to -89\");\n solarDateTimeLatLong.latDeg = -89;\n latitude = -89;\n }\n if ((latitude <= 90) && (latitude > 89)) {\n alert(\"All latitudes between 89 and 90 N\\n will be set to 89\");\n solarDateTimeLatLong.latDeg = 89;\n latitude = 89;\n }\n // Calculate the time of sunrise\n var JD = calcJD(parseFloat(solarDateTimeLatLong.year), indexRS + 1, parseFloat(solarDateTimeLatLong.day));\n var dow = calcDayOfWeek(JD);\n var doy = calcDayOfYear(indexRS + 1, parseFloat(solarDateTimeLatLong.day), isLeapYear(solarDateTimeLatLong.year));\n var T = calcTimeJulianCent(JD);\n var alpha = calcSunRtAscension(T);\n var theta = calcSunDeclination(T);\n var Etime = calcEquationOfTime(T);\n // solarRiseSet.dbug = doy;\n var eqTime = Etime;\n var solarDec = theta;\n // Calculate sunrise for this date if no sunrise is found, set flag nosunrise\n var nosunrise = false;\n var riseTimeGMT = calcSunriseUTC(JD, latitude, longitude);\n if (!isNumber(riseTimeGMT)) {\n nosunrise = true;\n }\n // Calculate sunset for this date if no sunset is found, set flag nosunset\n var nosunset = false;\n var setTimeGMT = calcSunsetUTC(JD, latitude, longitude);\n if (!isNumber(setTimeGMT)) {\n nosunset = true;\n }\n var daySavings = solarDateTimeLatLong.daySavings; // = 0 (no) or 60 (yes)\n var zone = solarDateTimeLatLong.hrsToGMT;\n if(zone > 12 || zone < -12.5) {\n alert(\"The offset must be between -12.5 and 12. \\n Setting \\\"Off-Set\\\"=0\");\n zone = \"0\";\n solarDateTimeLatLong.hrsToGMT = zone;\n }\n if (!nosunrise) { // Sunrise was found\n var riseTimeLST = riseTimeGMT - (60 * zone) + daySavings; // in minutes\n var riseStr = timeStringShortAMPM(riseTimeLST, JD);\n var utcRiseStr = timeStringDate(riseTimeGMT, JD);\n solarRiseSet.sunrise = riseStr;\n solarRiseSet.utcSunrise = utcRiseStr;\n }\n if (!nosunset) { // Sunset was found\n var setTimeLST = setTimeGMT - (60 * zone) + daySavings;\n var setStr = timeStringShortAMPM(setTimeLST, JD);\n var utcSetStr = timeStringDate(setTimeGMT, JD);\n solarRiseSet.sunset = setStr;\n solarRiseSet.utcSunset = utcSetStr;\n }\n // Calculate solar noon for this date\n var solNoonGMT = calcSolNoonUTC(T, longitude);\n var solNoonLST = solNoonGMT - (60 * zone) + daySavings;\n var solnStr = timeString(solNoonLST);\n var utcSolnStr = timeString(solNoonGMT);\n solarRiseSet.solnoon = solnStr;\n solarRiseSet.utcSolnoon = utcSolnStr;\n var tsnoon = calcTimeJulianCent(calcJDFromJulianCent(T) -0.5 + solNoonGMT/1440.0);\n eqTime = calcEquationOfTime(tsnoon);\n solarDec = calcSunDeclination(tsnoon);\n solarRiseSet.eqTime = (Math.floor(100*eqTime))/100;\n solarRiseSet.solarDec = (Math.floor(100*(solarDec)))/100;\n // Convert lat and long to standard format\n convLatLong();\n // report special cases of no sunrise\n if(nosunrise) {\n solarRiseSet.utcSunrise = \"\";\n // if Northern hemisphere and spring or summer, OR\n // if Southern hemisphere and fall or winter, use\n // previous sunrise and next sunset\n if (((latitude > 66.4) && (doy > 79) && (doy < 267)) || ((latitude < -66.4) && ((doy < 83) || (doy > 263)))) {\n newjd = findRecentSunrise(JD, latitude, longitude);\n newtime = calcSunriseUTC(newjd, latitude, longitude) - (60 * zone) + daySavings;\n if (newtime > 1440) {\n newtime -= 1440;\n newjd += 1.0;\n }\n if (newtime < 0) {\n newtime += 1440;\n newjd -= 1.0;\n }\n solarRiseSet.sunrise = timeStringAMPMDate(newtime, newjd);\n solarRiseSet.utcSunrise = \"prior sunrise\";\n }\n // if Northern hemisphere and fall or winter, OR\n // if Southern hemisphere and spring or summer, use\n // next sunrise and previous sunset\n else if (((latitude > 66.4) && ((doy < 83) || (doy > 263))) || ((latitude < -66.4) && (doy > 79) && (doy < 267))) {\n newjd = findNextSunrise(JD, latitude, longitude);\n newtime = calcSunriseUTC(newjd, latitude, longitude) - (60 * zone) + daySavings;\n if (newtime > 1440) {\n newtime -= 1440;\n newjd += 1.0;\n }\n if (newtime < 0) {\n newtime += 1440;\n newjd -= 1.0;\n }\n solarRiseSet.sunrise = timeStringAMPMDate(newtime, newjd);\n // solarRiseSet.sunrise = calcDayFromJD(newjd) + \" \" + timeStringDate(newtime, newjd);\n solarRiseSet.utcSunrise = \"next sunrise\";\n }\n else {\n alert(\"Cannot Find Sunrise!\");\n }\n // alert(\"Last Sunrise was on day \" + findRecentSunrise(JD, latitude, longitude));\n // alert(\"Next Sunrise will be on day \" + findNextSunrise(JD, latitude, longitude));\n }\n if(nosunset) {\n solarRiseSet.utcSunset = \"\";\n // if Northern hemisphere and spring or summer, OR\n // if Southern hemisphere and fall or winter, use\n // previous sunrise and next sunset\n if (((latitude > 66.4) && (doy > 79) && (doy < 267)) || ((latitude < -66.4) && ((doy < 83) || (doy > 263)))) {\n newjd = findNextSunset(JD, latitude, longitude);\n newtime = calcSunsetUTC(newjd, latitude, longitude) - (60 * zone) + daySavings;\n if (newtime > 1440) {\n newtime -= 1440;\n newjd += 1.0;\n }\n if (newtime < 0) {\n newtime += 1440;\n newjd -= 1.0;\n }\n solarRiseSet.sunset = timeStringAMPMDate(newtime, newjd);\n solarRiseSet.utcSunset = \"next sunset\";\n solarRiseSet.utcSolnoon = \"\";\n }\n // if Northern hemisphere and fall or winter, OR\n // if Southern hemisphere and spring or summer, use\n // next sunrise and last sunset\n else if (((latitude > 66.4) && ((doy < 83) || (doy > 263))) || ((latitude < -66.4) && (doy > 79) && (doy < 267))) {\n \tnewjd = findRecentSunset(JD, latitude, longitude);\n \tnewtime = calcSunsetUTC(newjd, latitude, longitude) - (60 * zone) + daySavings;\n \tif (newtime > 1440) {\n \t\tnewtime -= 1440;\n \t\tnewjd += 1.0;\n \t}\n \tif (newtime < 0) {\n \t\tnewtime += 1440;\n \t\tnewjd -= 1.0;\n \t}\n \tsolarRiseSet.sunset = timeStringAMPMDate(newtime, newjd);\n \tsolarRiseSet.utcSunset = \"prior sunset\";\n \tsolarRiseSet.solnoon = \"N/A\";\n \tsolarRiseSet.utcSolnoon = \"\";\n }\n else {\n alert (\"Cannot Find Sunset!\");\n }\n }\n }\n}",
"function busLocation() {\n var selector = document.getElementById(\"busline\");\n var route_name = selector[selector.selectedIndex].text;\n var xhttp = new XMLHttpRequest();\n\n xhttp.open(\"GET\", \"https://data.foli.fi/siri/vm/\", true);\n xhttp.onreadystatechange = function () {\n if (xhttp.readyState === 4) {\n var obj = JSON.parse(xhttp.responseText);\n buses = obj.result.vehicles;\n\n //step through buses and check if the name is same as selected in drop-down-list\n for (bus in buses) {\n // add all buses from the selected line to map\n if (buses[bus].publishedlinename === route_name) {\n lat = buses[bus].latitude;\n lon = buses[bus].longitude;\n marker = L.marker([lat, lon], {icon: busIcon}).addTo(map);\n }\n }\n }\n\n };\n xhttp.send();\n}",
"function getnearestURACarpark(latinput, longinput)\n{\n var getlatfromuser = latinput;\n var getlongfromuser = longinput;\n\n var token = \"6hf2NfWWja4j12bn3H4z8g62287rha485Fu7ff1F8gVC0R-AbBC-38YT3c856fV3HCZmet2j54+gbCP40u3@Q184ccRQGzcbXefE\";\n var options = {\n url: 'https://www.ura.gov.sg/uraDataService/invokeUraDS?service=Car_Park_Availability',\n headers: {\n 'AccessKey' : '0d5cce33-3002-451b-8f53-31e8c4c54477',\n 'Token' : token\n }\n };\n\n function callback(error, response, body) \n {\n var cv1 = new SVY21();\n //var getlatfromuser = 1.332401;\n //var getlongfromuser = 103.848438;\n var nearestdistance2 = 0;\n var nearestURAcarparklot;\n var nearestURAcarparkcoordinates;\n var nearestURAcarparklotavailability;\n \n // var currentdate = new Date();\n // var httpdate = new Date(response.headers['date']);\n // var httpgetday = httpdate.getDate();\n // console.log(\"HTTP Respond Date : \" +httpdate);\n // console.log(\"HTTP Get Date : \" +httpgetday);\n // console.log(\"Current Date : \" +currentdate); \n\n if (!error && response.statusCode == 200)\n {\n //Parse data\n var jsonobject3 = JSON.parse(body);\n console.log(\"parse data from URA\");\n console.log(util.inspect(body, false, null));\n \n for (var i = 0; i < jsonobject3.Result.length; ++i)\n {\n //Find car park lot availability for cars\n if (jsonobject3.Result[i].lotType == \"C\")\n {\n console.log(\"URA Carpark No : \" + jsonobject3.Result[i].carparkNo);\n console.log(\"URA Carpark Lot Type : \" + jsonobject3.Result[i].lotType);\n console.log(\"URA Carpark Lot Availability : \" + jsonobject3.Result[i].lotsAvailable);\n console.log(\"URA Carpark Coordinates : \" + jsonobject3.Result[i].geometries[0].coordinates);\n var uracoordinates = jsonobject3.Result[i].geometries[0].coordinates;\n var uracoordinatesresult = uracoordinates.split(\",\");\n console.log(\"URA Carpark Coordinates Latitude (SVY21) : \" + uracoordinatesresult[0]);\n console.log(\"URA Carpark Coordinates Longitude (SVY21) : \" + uracoordinatesresult[1]);\n //Convert SVY21 to Lat/Long\n var getlatlong2 = cv1.computeLatLon(uracoordinatesresult[0], uracoordinatesresult[1]);\n var showlat2 = getlatlong2[0];\n var showlong2 = getlatlong2[1];\n console.log(\"URA Carpark Latitude : \" + showlat2);\n console.log(\"URA Carpark Longitude : \" + showlong2);\n //Calculate distance between URA Carpark and user current location\n var showdistance2 = calculatedistance(showlat2, showlong2, getlatfromuser, getlongfromuser, 'K');\n //round to 3 decimal places\n var showdistanceformat2 = Math.round(showdistance2*1000)/1000;\n console.log(\"Distance(in km) : \" + showdistanceformat2);\n\n //Find nearest URA Carpark\n var tempdistance2 = showdistanceformat2;\n if (i == 0)\n {\n nearestdistance2 = tempdistance2;\n nearestURAcarparklot= jsonobject3.Result[i].carparkNo;\n nearestURAcarparklotavailability= jsonobject3.Result[i].lotsAvailable;\n nearestURAcarparkcoordinates = jsonobject3.Result[i].geometries[0].coordinates;\n }\n if (nearestdistance2 > tempdistance2)\n {\n nearestdistance2 = tempdistance2;\n nearestURAcarparklot= jsonobject3.Result[i].carparkNo;\n nearestURAcarparklotavailability= jsonobject3.Result[i].lotsAvailable;\n nearestURAcarparkcoordinates = jsonobject3.Result[i].geometries[0].coordinates;\n }\n\n }\n }\n\n console.log(\"Nearest URA Carpark (Distance) : \" + nearestdistance2);\n console.log(\"Nearest URA Carpark (Lot No) : \" + nearestURAcarparklot);\n console.log(\"Nearest URA Carpark (Lot Availability) : \" + nearestURAcarparklotavailability);\n }\n }\n\n request(options, callback);\n\n}",
"function randomRobot(state) { \n return {direction: randomPick(roadGraph[state.place])};\n}",
"function getIllustration(weatherIcon) {\n let temp = (props.iconCode.temperature);\n let illustrationImg = \"\";\n switch (weatherIcon) {\n case \"01d\":\n if (temp < -1) {\n illustrationImg = ImgCold;\n } else {\n illustrationImg = ImgSunny;\n }\n break;\n case \"01n\":\n if (temp < -1) {\n illustrationImg = ImgCold;\n } else {\n illustrationImg = ImgNight;\n }\n break;\n case \"02d\":\n case \"02n\":\n case \"03d\":\n case \"03n\":\n case \"04d\":\n case \"04n\":\n if (temp < -1) {\n illustrationImg = ImgCold;\n } else {\n illustrationImg = ImgCloudy;\n }\n break;\n case \"09d\":\n case \"09n\":\n case \"10d\":\n case \"10n\":\n illustrationImg = ImgRain;\n break;\n case \"11d\":\n case \"11n\":\n illustrationImg = ImgThunder;\n break;\n case \"13d\":\n case \"13n\":\n illustrationImg = ImgSnow;\n break;\n case \"50d\":\n case \"50n\":\n if (temp < -1) {\n illustrationImg = ImgCold;\n } else {\n illustrationImg = ImgMisty;\n }\n break;\n default: illustrationImg = ImgCloudy;\n }\n return illustrationImg;\n }",
"function getLocationError() {\n alert('we couldn\\'t get your current location :(');\n }",
"function giveSoldierLocationAccordingToLatLong(Soldier) {\n\n if (!Soldier.Latitude || !Soldier.Longitude) {\n return;\n }\n var sLocation = soldierLocation(Soldier);\n socket.emit('updateLocationFilter', { braceletId: Soldier.Bracelet_ID, location: sLocation }); // send request to backEnd via socket to update soldier location in database.\n return sLocation;\n\n}",
"function getCityCurrent(){\n \n}",
"function pizzaArea(r){\n //area=r*r*Pi\n var area=r*r*Math.PI;\n return area;\n}",
"function calculateSolar() {\n \n var dailyUseKw = addMonths('mpc'); // assign first function to a variable\n// console.log(dailyUseKw);\n \n var sunHoursPerDay = sunHours(); // assign second function to a variable\n// console.log(sunHoursPerDay);\n \n var minKwNeeds = dailyUseKw / sunHoursPerDay;\n// console.log(minKwNeeds);\n \n var realKwNeeds = minKwNeeds * 1.25; // increase the minimum need due to factoring in rainy days with less sun, add 25%, do this by multiplying by 1.25\n// console.log(realKwNeeds);\n \n var realWattNeeds = realKwNeeds * 1000; // energy usage is interpreted in Kw while solar pannels are Watts. This converts Kw to W.\n// console.log(realWattNeeds);\n \n // this grabs and ouputs the value and name of the panel choice\n var panelInfo = calculatePanel();\n var panelOutput = panelInfo[0];\n var panelName = panelInfo[1];\n// console.log(panelOutput);\n// console.log(panelName);\n \n var panelsNeeded = Math.ceil(realWattNeeds / panelOutput); // wrap the calculation in Math.ceil() to round up because no one is buying a fraction of a panel, needs to be a whole number\n// console.log(panelsNeeded);\n \n \n // display the calculations to the screen. Math.round() rounds down\n var feedback = \"\";\n feedback += '<p>Based on your average daily use of ' + Math.round(dailyUseKw) + ' kWh, you will need to purchase ' + panelsNeeded + ' ' + panelName + ' solar panels to offset 100% of your electricity bill.</p>';\n feedback += '<h1>Additional Details</h1>';\n feedback += '<p>Your average daily electricity consumption: ' + Math.round(dailyUseKw) + 'Kwh per day.</p>';\n feedback += '<p>Average sunshine hours per day: ' + sunHoursPerDay + ' hours</p>';\n feedback += '<p>Realistic watts needed per hour: ' + Math.round(realWattNeeds) + ' watts/hour.</p>';\n feedback += '<p>The ' + panelName + ' panel you selected generates about ' + panelOutput + ' watts per hour.</p>';\n \n document.getElementById('feedback').innerHTML = feedback;\n\n} // end function",
"function getnearestweather(latinput, longinput)\n{\n // var forecastobj = {\n // BR: \"Mist\",\n // CL: \"Cloudy\",\n // CR: \"Drizzle\",\n // FA: \"Fair(Day)\",\n // FG: \"Fog\",\n // FN: \"Fair(Night)\",\n // FW: \"Fair & Warm\",\n // HG: \"Heavy Thundery Showers with Gusty Winds\",\n // HR: \"Heavy Rain\",\n // HS: \"Heavy Showers\",\n // HT: \"Heavy Thundery Showers\",\n // HZ: \"Hazy\",\n // LH: \"Slightly Hazy\",\n // LR: \"Light Rain\",\n // LS: \"Light Showers\",\n // OC: \"Overcast\",\n // PC: \"Partly Cloudy (Day)\",\n // PN: \"Partly Cloudy (Night)\",\n // PS: \"Passing Showers\",\n // RA: \"Moderate Rain\",\n // SH: \"Showers\",\n // SK: \"Strong Winds,Showers\",\n // SN: \"Snow\",\n // SR: \"Strong Winds, Rain\",\n // SS: \"Snow Showers\",\n // SU: \"Sunny\",\n // SW: \"Strong Winds\",\n // TL: \"Thundery Showers\",\n // WC: \"Windy,Cloudy\",\n // WD: \"Windy\",\n // WF: \"Windy,Fair\",\n // WR: \"Windy,Rain\",\n // WS: \"Windy, Showers\"\n // };\n\n var forecastobj = {\n BR: \"Not Raining\",\n CL: \"Not Raining\",\n CR: \"Raining\",\n FA: \"Not Raining\",\n FG: \"Not Raining\",\n FN: \"Not Raining\",\n FW: \"Not Raining\",\n HG: \"Raining\",\n HR: \"Raining\",\n HS: \"Raining\",\n HT: \"Raining\",\n HZ: \"Not Raining\",\n LH: \"Not Raining\",\n LR: \"Raining\",\n LS: \"Raining\",\n OC: \"Not Raining\",\n PC: \"Not Raining\",\n PN: \"Not Raining\",\n PS: \"Raining\",\n RA: \"Raining\",\n SH: \"Raining\",\n SK: \"Raining\",\n SN: \"Not Raining\",\n SR: \"Raining\",\n SS: \"Not Raining\",\n SU: \"Not Raining\",\n SW: \"Not Raining\",\n TL: \"Raining\",\n WC: \"Not Raining\",\n WD: \"Not Raining\",\n WF: \"Not Raining\",\n WR: \"Raining\",\n WS: \"Raining\"\n };\n\n var getlatfromuser = latinput;\n var getlongfromuser = longinput;\n //var getlatfromuser = 1.332401;\n //var getlongfromuser = 103.848438;\n\n var parser1 = new xml2js.Parser({explicitArray : true, attrkey : 'Child'});\n\n http.get('http://api.nea.gov.sg/api/WebAPI/?dataset=2hr_nowcast&keyref=781CF461BB6606ADC767F3B357E848ED3A27067168AB8007', function(res)\n {\n var response_data = '';\n res.setEncoding('utf8');\n res.on('data', function(chunk)\n {\n response_data += chunk;\n });\n \n res.on('end', function() \n {\n parser1.parseString(response_data, function(err, result) \n {\n if (err) \n {\n console.log('Got error: ' + err.message);\n }\n else \n {\n eyes.inspect(result);\n \n //convert into JSON object\n console.log('Converting to JSON object.');\n var jsonobject2 = JSON.parse(JSON.stringify(result));\n console.log(util.inspect(jsonobject2, false, null));\n\n //read and traverse JSON object\n var nearestdistance1 = 0;\n var showdistanceformat1;\n var showdistance1;\n \n var showlat1;\n var showlong1;\n var nearestForeCast;\n var nearestForeCastName;\n\n console.log(\"name 1: \" + jsonobject2.channel.title);\n console.log(\"name 2: \" + jsonobject2.channel.source);\n console.log(\"date3 : \" +jsonobject2.channel.item[0].forecastIssue[0].Child.date);\n console.log(\"length \"+jsonobject2.channel.item[0].weatherForecast[0].area.length)\n\n for (var i = 0; i < jsonobject2.channel.item[0].weatherForecast[0].area.length; ++i)\n {\n showlat1 = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.lat;\n showlong1 = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.lon;\n showdistance1 = calculatedistance(showlat1, showlong1, getlatfromuser, getlongfromuser, 'K');\n //round to 3 decimal places\n showdistanceformat1 = Math.round(showdistance1*1000)/1000;\n console.log(\"Distance(in km) : \" + showdistanceformat1);\n\n var tempdistance1 = showdistanceformat1;\n if (i == 0)\n {\n nearestdistance1 = tempdistance1;\n nearestForeCast = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.forecast;\n nearestForeCastName = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.name;\n }\n if (nearestdistance1 > tempdistance1)\n {\n nearestdistance1 = tempdistance1;\n nearestForeCast = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.forecast;\n nearestForeCastName = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.name;\n }\n }\n console.log(\"Distance to Nearest Town : \" + nearestdistance1);\n console.log(\"Forecast in Nearest Town : \" + nearestForeCast);\n console.log(\"Nearest Town : \" + nearestForeCastName);\n\n var forecast = forecastobj[nearestForeCast];\n console.log(\"Forecast in Current Location : \" + forecast);\n }\n });\n });\n\n res.on('error', function(err) \n {\n console.log('Got error: ' + err.message);\n });\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name: TimeBasedRecommendor Description: the TimeBasedRecommendor is the engine that computes recommendations from the data | function TimeBasedRecommendor() {
/* Private Member Variables */
// setup some maps so that we can store all the data in memory and then update properly
// Basically the concern is that can't add a rating to a candidate that doesn't exist yet
// So we store everything, then create the candidates, then add the ratings
var candidates = {}; // a map of all candidates (with key equal to its name)
var leafVector = []; // a vector of all candidates with no children
var ratings = []; // a vector of all ratings
var participations = []; // a vector of all partipations
var predictionLinks = {}; // the set of all prediction links
var latestDate = new DateTime(); // the latest date for which we have data about something
var ratingsFilename = "bluejay_ratings.txt";
var inheritancesFilename = "bluejay_inheritances.txt";
/* Public Methods */
/* function prototypes */
// functions to add data
// read the usual files and put their data into the recommendor
this.readFiles = readFiles;
// read a file and put its data into the recommendor
this.readFile = readFile;
// add a Candidate for the engine to track
this.addCandidate = addCandidate;
// add any necessary links between Candidates
this.updateLinks = updateLinks;
// give the previously unseen rating to the engine
this.addRating = addRating;
// restore the previously seen rating and don't write it to a file
this.putRatingInMemory = putRatingInMemory;
// save this rating to a text file
this.writeRating = writeRating;
// give the previously unseen participation to the engine and write it to a file
this.addParticipation = addParticipation;
// restore the previously seen participation and don't write it to a file
this.putParticipationInMemory = putParticipationInMemory;
// save this participation to a text file
this.writeParticipation = writeParticipation;
// give this rating to all the Candidates that need it
this.cascadeRating = cascadeRating;
// give this participation to all the Candidates that need it
this.cascadeParticipation = cascadeParticipation;
// create a PredictionLink to predict one Candidate from another
this.linkCandidates = linkCandidates;
// create a PredictionLink to predict a RatingMovingAverage from a RatingMovingAverage
this.linkAverages = linkAverages;
// inform each Candidate of each of its children and parents
this.updateChildPointers = updateChildPointers;
// create some PredictionLinks to predict some Candidates from others
this.addSomeTestLinks = addSomeTestLinks;
this.updatePredictions = updatePredictions;
// create the necessary files on disk
this.createFiles = createFiles;
// save the given participation to disk
this.writeParticipation = writeParticipation;
// search functions
// returns this Candidate and all its ancestors
this.findAllSuperCategoriesOf = findAllSuperCategoriesOf;
// get the Candidate given the name
this.getCandidateWithName = getCandidateWithName;
// get the link between two MovingAverages
this.getLinkFromMovingAverages = getLinkFromMovingAverages;
// estimate what rating this Candidate would get if it were played at this time
this.rateCandidate = rateCandidate;
// choose the name of the next song to play
this.makeRecommendation = makeRecommendation;
this.addDistributions = addDistributions;
this.averageDistributions = averageDistributions;
// print functions
this.printCandidate = printCandidate;
this.printRating = printRating;
this.printDistribution = printDistribution;
this.printParticipation = printParticipation;
this.message = message;
// functions for testing that it all works
this.test = test;
// updates the structure of the Candidates
// This informs each Candidate of each of children and parents, and
// creates PredictionLinks between some of them
function updateLinks() {
alert("recommendor updating child pointers");
this.updateChildPointers();
alert("recommendor adding test links");
this.addSomeTestLinks();
//alert("recommendor updating predictions");
//this.updatePredictions();
}
// function definitions
// reads all the necessary files and updates the TimeBasedRecommendor accordingly
function readFiles() {
//alert("recommendor reading files");
//this.readFile(inheritancesFilename);
this.createFiles();
this.readFile(ratingsFilename);
this.updateLinks();
this.updatePredictions();
message("recommendor done reading files\r\n");
alert("recommendor done reading files");
}
// reads one file and put its data into the TimeBasedRecommendor
function readFile(fileName) {
//alert("recommendor reading file");
message("opening file " + fileName + "\r\n");
// display a message
var fileContents = FileIO.readFile(fileName);
//message("initializing temporary variables");
var currentChar;
var startTag = new Name();
var endTag = new Name();
var stackCount = 0;
var readingStartTag = false;
var readingValue = false;
var readingEndTag = false;
//message("initializing local candidate");
var candidate = new Candidate();
//message("initializing local name");
var value = new Name();
var objectName = new Name();
//message("initializing local rating");
var rating = new Rating();
var activityType = new Name();
//message("initializing local participation");
var participation = new Participation();
// setup some strings to search for in the file
var candidateIndicator = new Name("Candidate");
var nameIndicator = new Name("Name");
var parentIndicator = new Name("Parent");
var discoveryDateIndicator = new Name("DiscoveryDate");
//message("done initializing some temporary variables");
var ratingIndicator = new Name("Rating");
var ratingActivityIndicator = new Name("Activity");
var ratingDateIndicator = new Name("Date");
var ratingValueIndicator = new Name("Score");
var participationIndicator = new Name("Participation");
var participationActivityIndicator = new Name("Activity");
var participationStartDateIndicator = new Name("StartDate");
var participationEndDateIndicator = new Name("EndDate");
var currentDate = new DateTime();
var characterIndex;
alert("starting to parse file text");
// read until the file is finished
for (characterIndex = -1; characterIndex < fileContents.length; ) {
// Check if this is a new starttag or endtag
characterIndex++;
currentChar = fileContents[characterIndex];
//message(currentChar);
// Check if this is the end of a tag
if (currentChar == '>') {
//message(value.getName());
//message(">\r\n");
characterIndex++;
currentChar = fileContents[characterIndex];
if (readingStartTag) {
if (stackCount == 1) {
// If we get here, then we just read the type of the object that is about to follow
objectName = startTag.makeCopy();
}
//message("start tag = ");
//message(startTag.getName() + ">");
value.clear();
readingValue = true;
}
if (readingEndTag) {
//message("end tag = ");
//message(endTag.getName() + ">\r\n");
if (stackCount == 2) {
// If we get here, then we just read an attribute of the object
// If any of these trigger, then we just read an attribute of a candidate (which is a song, artist, genre or whatever)
if (endTag.equalTo(nameIndicator))
candidate.setName(value);
if (endTag.equalTo(parentIndicator))
candidate.addParentName(value.makeCopy());
//if (endTag.equalTo(discoveryDateIndicator))
// candidate.setDiscoveryDate(new DateTime(value.getName()));
// If any of these trigger, then we just read an attribute of a rating
// Tags associated with ratings
if (endTag.equalTo(ratingActivityIndicator))
rating.setActivity(value);
if (endTag.equalTo(ratingDateIndicator)) {
// keep track of the latest date ever encountered
//message("assigning date to rating\r\n");
currentDate = new DateTime(value.getName());
if (strictlyChronologicallyOrdered(latestDate, currentDate))
latestDate = currentDate;
rating.setDate(currentDate);
//message("done assigning date to rating\r\n");
}
if (endTag.equalTo(ratingValueIndicator)) {
rating.setScore(parseFloat(value.getName()));
}
// If any of these trigger, then we just read an attribute of a participation (an instance of listening)
if (endTag.equalTo(participationStartDateIndicator)) {
// keep track of the latest date ever encountered
currentDate = new DateTime(value.getName());
if (strictlyChronologicallyOrdered(latestDate, currentDate))
latestDate = currentDate;
participation.setStartTime(currentDate);
}
if (endTag.equalTo(participationEndDateIndicator)) {
// keep track of the latest date ever encountered
currentDate = new DateTime(value.getName());
if (strictlyChronologicallyOrdered(latestDate, currentDate))
latestDate = currentDate;
participation.setEndTime(currentDate);
}
if (endTag.equalTo(participationActivityIndicator))
participation.setActivityName(value.makeCopy());
}
if (stackCount == 1) {
//alert("probably read a candidate");
//message("object name = " + objectName.getName());
// If we get here then we just finished reading an object
if (objectName.equalTo(candidateIndicator)) {
// If we get here then we just finished reading a candidate (which is a song, artist, genre or whatever)
// add the candidate to the inheritance hierarchy
//alert("adding candidate");
this.addCandidate(candidate);
candidate = new Candidate();
}
if (objectName.equalTo(ratingIndicator)) {
// If we get here then we just finished reading a rating
// add the rating to the rating set
this.putRatingInMemory(rating);
rating = new Rating();
}
if (objectName.equalTo(participationIndicator)) {
// If we get here then we just finished reading a rating
this.putParticipationInMemory(participation);
participation = new Participation();
}
}
stackCount--;
}
readingStartTag = false;
readingEndTag = false;
}
if (currentChar == '<') {
readingValue = false;
characterIndex++;
currentChar = fileContents[characterIndex];
if (currentChar != '/') {
//message("<");
// If we get here, then it's a start tag
startTag.clear();
stackCount++;
//message("stackCount = " + stackCount);
readingStartTag = true;
} else {
//message(value.getName() + "</");
// If we get here, then it's an end tag
endTag.clear();
readingEndTag = true;
characterIndex++;
currentChar = fileContents[characterIndex];
}
}
//message("start tag = ");
//message(startTag.getName());
// update names accordingly
if (readingStartTag) {
startTag.appendChar(currentChar);
}
if (readingValue) {
value.appendChar(currentChar);
}
if (readingEndTag) {
endTag.appendChar(currentChar);
}
}
alert("done reading file " + fileName + "\r\n");
}
// adds a candidate (also known as a song, genre, or category)
function addCandidate(newCandidate) {
var name = newCandidate.getName().getName();
message("adding candidate named ");
printCandidate(newCandidate);
//message("done printing candidate");
candidates[name] = newCandidate;
//message("done adding candidate\r\n");
}
// adds a rating to the list of ratings
function addRating(newRating) {
writeRating(newRating);
putRatingInMemory(newRating);
}
// saves the rating to the text file
function writeRating(newRating) {
var text = newRating.stringVersion();
message("saving rating " + text);
FileIO.writeFile(ratingsFilename, text + "\r\n", 1);
}
function putRatingInMemory(newRating) {
message("adding rating ");
printRating(newRating);
message("\r\n");
ratings.length += 1;
ratings[ratings.length - 1] = newRating;
}
// adds a rating to the list of participation
function addParticipation(newParticipation) {
writeParticipation(newParticipation);
putParticipationInMemory(newParticipation);
}
// saves the rating to the text file
function writeParticipation(newParticipation) {
var text = newParticipation.stringVersion();
message("saving participation " + text);
FileIO.writeFile(ratingsFilename, text + "\r\n", 1);
}
function putParticipationInMemory(newParticipation) {
message("adding participation");
printParticipation(newParticipation);
participations.length += 1;
participations[participations.length - 1] = newParticipation;
}
// adds the participation to the necessary candidate and all its parents
function cascadeParticipation(newParticipation) {
message("cascading participation " + newParticipation.getActivityName().getName() + "\r\n");
var candidate = getCandidateWithName(newParticipation.getActivityName());
if (candidate) {
var candidatesToUpdate = findAllSuperCategoriesOf(candidate);
var i;
for (i = 0; candidatesToUpdate[i]; i++) {
candidatesToUpdate[i].giveParticipation(newParticipation);
}
}
}
// adds the rating to the necessary candidate and all its parents
function cascadeRating(newRating) {
var candidate = getCandidateWithName(newRating.getActivity());
if (candidate) {
var candidatesToUpdate = findAllSuperCategoriesOf(candidate);
var i, j;
for (i = 0; candidatesToUpdate[i]; i++) {
var currentCandidate = candidatesToUpdate[i];
message("giving rating to candidate " + currentCandidate.getName().getName() + "\r\n");
currentCandidate.giveRating(newRating);
}
}
}
// create the necessary PredictionLink to predict each candidate from the other
function linkCandidates(predictor, predictee) {
message("linking candidates " + predictor.getName().getName() + " and " + predictee.getName().getName() + "\r\n");
var frequencyCountA = predictor.getNumFrequencyEstimators();
var ratingCountA = predictor.getNumRatingEstimators();
var frequencyCountB = predictee.getNumFrequencyEstimators();
var ratingCountB = predictee.getNumRatingEstimators();
var i, j;
// using the frequency of A, try to predict the rating for B
for (i = 0; i < frequencyCountA; i++) {
message("getting frequency estimator\r\n");
var predictorAverage = predictor.getFrequencyEstimatorAtIndex(i);
message("getting actual rating history\r\n");
var predicteeAverage = predictee.getActualRatingHistory();
message("linking averages\r\n");
this.linkAverages(predictorAverage, predicteeAverage);
}
// using the frequency of B, try to predict the rating for A
/*for (j = 0; j < frequencyCountB; j++) {
this.linkAverages(predictee.getFrequencyEstimatorAtIndex(j), predictor.getActualRatingHistory());
}*/
// using the rating for A, try to predict the rating for B
for (i = 0; i < ratingCountA; i++) {
this.linkAverages(predictor.getRatingEstimatorAtIndex(i), predictee.getActualRatingHistory());
}
// using the rating for B, try to predict the rating for A
/*for (j = 0; j < ratingCountB; j++) {
this.linkAverages(predictee.getRatingEstimatorAtIndex(j), predictor.getActualRatingHistory());
}*/
}
// create the necessary PredictionLink to predict the predictee from the predictor
function linkAverages(predictor, predictee) {
message("linking averages ");
message(predictor.getName().getName());
message(" and ");
message(predictee.getName().getName() + "\r\n");
var predicteeName = predictee.getName().getName();
//message("doing dictionary lookup\r\n");
var links = predictionLinks[predicteeName];
//message("checking for undefined value\r\n");
if (links == undefined) {
//message("links was undefined\r\n");
links = {};
}
//message("making new link");
var newLink = new PredictionLink(predictor, predictee);
//message("putting new link in map");
links[predictor.getName().getName()] = newLink;
predictionLinks[predicteeName] = links;
}
// inform each candidate of the categories it directly inherits from
// and the categories that directly inherit from it
function updateChildPointers() {
message("updating child pointers");
// iterate over each candidate
var candidateIterator = Iterator(candidates, true);
var currentCandidate;
var parent;
var i;
for (candidateName in candidateIterator) {
message("candidateName = " + candidateName);
currentCandidate = candidates[candidateName];
message("current candidate = ");
//message(currentCandidate);
message("current candidate is named" + currentCandidate.getName().getName());
//message("checking if update is needed\r\n");
if (currentCandidate.needToUpdateParentPointers()) {
message("update is required\r\n");
// if we get here then this candidate was added recently and its parents need their child pointers updated
var parentNames = currentCandidate.getParentNames();
for (i = 0; parentNames[i]; i++) {
message("parent name = " + parentNames[i].getName() + "\r\n");
parent = getCandidateWithName(parentNames[i]);
message("parent is named " + parent.getName().getName() + "\r\n");
message("adding parent\r\n");
currentCandidate.addParent(parent);
message("adding child\r\n");
parent.addChild(currentCandidate);
message("done adding child\r\n");
}
} else {
message("update was not required\r\n");
}
}
// keep track of all candidates that have no children
leafVector.length = 0;
candidateIterator = Iterator(candidates);
for ([candidateName, currentCandidate] in candidateIterator) {
if (currentCandidate.getChildren().length == 0) {
leafVector.push(currentCandidate);
}
}
}
// creates a bunch of PredictionLinks to predict the ratings of some Candidates from others
function addSomeTestLinks() {
message("adding some test links\r\n");
var iterator1 = Iterator(candidates);
var name1;
var name2;
var candidate1;
var candidate2;
// currently we add all combinations of links
/*for ([name1, candidate1] in iterator1) {
var iterator2 = Iterator(candidates);
for ([name2, candidate2] in iterator2) {
message("name1 = " + name1 + " name2 = " + name2 + "\r\n");
// to prevent double-counting, make sure candidate1 <= candidate2
if (!candidate1.getName().lessThan(candidate2.getName())) {
message("linking candidates\r\n");
this.linkCandidates(candidate1, candidate2);
}
}
}*/
// to make the algorithm run quickly, we currently only predict a song based on itself and supercategories
var parents;
var i;
var currentParent;
for ([name1, candidate1] in iterator1) {
// for speed, only compare against oneself and one's immediate parents
this.linkCandidates(candidate1, candidate1);
parents = candidate1.getParents();
//parents = this.findAllSuperCategoriesOf(candidate1);
for (i = 0; i < parents.length; i++) {
// try to predict the rating of the parent from data about the child
// this.linkCandidates(candidate1, parents[i]);
// try to predict the rating of this candidate from data about the parents
this.linkCandidates(parents[i], candidate1);
}
}
}
// inform everything of any new data that was added recently that it needs to know about
function updatePredictions() {
//alert("Updating predictions. Please wait.\r\n");
message("giving ratings to activities\r\n");
// inform each candidate of the ratings given to it
var ratingIterator = Iterator(ratings, true);
var rating;
var activityName;
var i;
for (i = 0; i < ratings.length; i++) {
this.cascadeRating(ratings[i]);
}
ratings.length = 0;
message("giving participations to activities\r\n");
for (i = 0; i < participations.length; i++) {
this.cascadeParticipation(participations[i]);
}
participations.length = 0;
message("updating PredictionLinks");
// have each PredictionLink update itself with the changes to the appropriate MovingAverage
var mapIterator = Iterator(predictionLinks);
var currentMap;
var currentKey;
var currentPredictionKey;
var currentLink;
var predictionIterator;
var numUpdates = 0;
// for each candidate, get the map of predictions links that have it as the predictor
for ([currentKey, currentMap] in mapIterator) {
message("making iterator out of map " + currentKey + "\r\n");
predictionIterator = Iterator(currentMap);
// iterate over each PredictionLink that shares the predictor
for ([currentPredictionKey, currentLink] in predictionIterator) {
message("updating a PredictionLink " + currentPredictionKey + "\r\n");
currentLink.update(); // update the prediction link within the map
numUpdates++;
}
}
message("num PredictionLinks updated = " + numUpdates + "\r\n");
}
function createFiles() {
FileIO.writeFile(ratingsFilename, "", 1);
//FileIO.writeFile(inheritancesFilename, "", 0);
}
////////////////////////////////// search functions /////////////////////////////////////
function findAllSuperCategoriesOf(candidate) {
message("finding supercategories of " + candidate.getName().getName() + "\r\n");
// setup a set to check for duplicates
var setToUpdate = {};
// setup an array for sequential access
var vectorToUpdate = [];
// initialize the one leaf node
var currentCandidate = candidate;
//message("putting first entry into set\r\n");
setToUpdate[candidate.getName().getName()] = currentCandidate;
//message("putting first entry into vector\r\n");
vectorToUpdate.push(currentCandidate);
// compute the set of all supercategories of this candidate
var busy = true;
var currentParent;
var setIterator;
var parents;
var i, j;
//message("starting loop\r\n");
for (i = 0; i < vectorToUpdate.length; i++) {
currentCandidate = vectorToUpdate[i];
parents = currentCandidate.getParents();
for (j = 0; j < parents.length; j++) {
currentParent = parents[j];
// check whether this candidate is already in the set
if (!setToUpdate[currentParent.getName().getName()]) {
message("adding parent named " + currentParent.getName().getName() + "\r\n");
// if we get here then we found another candidate to add
setToUpdate[currentParent.getName().getName()] = currentParent;
vectorToUpdate.push(currentParent);
}
}
}
//message("done find supercategories\r\n");
return vectorToUpdate;
}
// dictionary lookup
function getCandidateWithName(name) {
return candidates[name.getName()];
}
// given two moving averages, returns the PredictionLink that predicts the predictee from the predictor
function getLinkFromMovingAverages(predictor, predictee) {
var links = predictionLinks[predictee.getName().getName()];
return links[predictor.getName().getName()];
}
////////////////////////////////// Prediction functions ///////////////////////////////////////
// calculate a rating for the given candidate
function rateCandidate(candidate, when) {
message("rating candidate with name: " + candidate.getName().getName());
printCandidate(candidate);
var parents = candidate.getParents();
var guesses = [];
var currentDistribution;
var i;
var currentParent;
// make sure that all of the parents are rated first
for (i = parents.length - 1; i >= 0; i--) {
currentParent = parents[i];
// figure out if the parent was rated recently enough
if (strictlyChronologicallyOrdered(currentParent.getLatestRatingDate(), when)) {
// if we get here then the parent rating needs updating
this.rateCandidate(currentParent, when);
}
}
// Now get the prediction from each relevant link
var shortTermAverageName = candidate.getActualRatingHistory().getName().getName();
var links = predictionLinks[shortTermAverageName];
var mapIterator = Iterator(links);
var predictorName;
var currentLink;
var currentGuess;
var predicteeName = candidate.getName().getName();
// iterate over all relevant prediction links
var childWeight = 0;
for ([predictorName, currentLink] in mapIterator) {
currentLink.update();
message("Predicting " + predicteeName + " from " + predictorName, 0);
currentGuess = currentLink.guess(when);
message(" score: " + currentGuess.getMean() + "\r\n", 0);
//printDistribution(currentGuess);
guesses.push(currentGuess);
childWeight += currentGuess.getWeight();
}
var parentScale;
if (childWeight < 1)
parentScale = 1;
else
parentScale = 1 / childWeight;
for (i = 0; i < parents.length; i++) {
currentGuess = parents[i].getCurrentRating();
guesses.push(new Distribution(currentGuess.getMean(), currentGuess.getStdDev(), currentGuess.getWeight() * parentScale));
}
// In addition to all of the above factors that may use lots of data to predict the rating
// of the song, we should also use some other factors.
// We want to:
// Never forget a song completely
// Avoid playing a song twice in a row without explicit reason to do so
// Believe the user's recent ratings
// We don't want to ever completely forget about a song. So, move it slowly closer to perfection
// Whenever they give it a rating or listen to it, this resets
var remembererDuration = candidate.getIdleDuration(when);
if (remembererDuration < 1)
remembererDuration = 1;
// The goal is to make d = sqrt(t) where d is the duration between listenings and t = num seconds
// Then n = sqrt(t) where n is the number of ratings
// If the user reliably rates a song down, then for calculated distributions, stddev = 1 / n = 1 / sqrt(t) and weight = n = sqrt(t)
// Then it is about ideal for the rememberer to have stddev = 1 / n and weight = d
// If the user only usually rates a song down, then for calculated distributions, stddev = k and weight = n
// Then it is about ideal for the rememberer to have stddev = k and weight = d
// This is mostly equivalent to stddev = d^(-1/3), weight = d^(2/3)
// So we could even make the rememberer stronger than the current stddev = d^(-1/3), weight = d^(1/3)
//double squareRoot = sqrt(remembererDuration);
var cubeRoot = Math.pow(remembererDuration, 1.0/3.0);
//message("building rememberer");
var rememberer = new Distribution(1, 1.0 / cubeRoot, cubeRoot);
guesses.push(rememberer);
// We should also suspect that they don't want to hear the song twice in a row
var spacerDuration = candidate.getDurationSinceLastPlayed(when);
// if they just heard it then they we're pretty sure they don't want to hear it again
// If it's been 10 hours then it's probably okay to play it again
// The spacer has a max weight so it can be overpowered by learned data
var spacerWeight = 20 * (1 - spacerDuration / 36000);
if (spacerWeight > 0) {
guesses.push(new Distribution(0, .05, spacerWeight));
}
// finally, combine all the distributions and return
//message("averaging distributions");
var childRating = this.averageDistributions(guesses);
candidate.setCurrentRating(childRating, when);
message("name: " + candidate.getName().getName() + " score: " + childRating.getMean() + "\r\n", 1);
return childRating;
}
// calculate a rating for the candidate with the given name
function rateCandidateWithName(name, when) {
return this.rateCandidate(getCandidateWithName(name), when);
}
// determines which candidate has the best expected score at the given time
function makeRecommendation(when) {
// default to the current date
if (!when) {
// get the current date
when = new DateTime();
when.setNow();
}
message("\r\nmaking recommendation for date:" + when.stringVersion() + "\r\n", 1);
var candidateIterator = Iterator(candidates);
// make sure that there is at least one candidate to choose from
// setup a map to sort by expected rating
var guesses = [];
var scoreValid = false;
var candidateKey;
var currentCandidate;
var bestScore = -1;
var currentScore = -1;
var bestName = new Name("[no data]");
//for ([candidateKey, currentCandidate] in candidateIterator) {
var i, index;
for (i = 0; i < 8; i++) {
// choose a random candidate
index = Math.floor(Math.random() * leafVector.length);
currentCandidate = leafVector[index];
message("considering candidate" + currentCandidate.getName().getName());
// only bother to rate the candidates that are not categories
if (currentCandidate.getNumChildren() == 0) {
this.rateCandidate(currentCandidate, when);
currentScore = currentCandidate.getCurrentRating().getMean();
message("candidate name = " + currentCandidate.getName().getName());
message("expected rating = " + currentScore + "\r\n");
guesses.push(currentCandidate);
if ((currentScore > bestScore) || !scoreValid) {
bestScore = currentScore;
bestName = currentCandidate.getName();
scoreValid = true;
}
}
}
var i;
for (i = 0; i < guesses.length; i++) {
currentCandidate = guesses[i];
message("candidate name = " + currentCandidate.getName().getName());
message(" expected rating = " + currentCandidate.getCurrentRating().getMean() + "\r\n");
}
/* // print the distributions in order
var distributionIterator = Iterator(guesses, true);
var currentScore;
var currentName;
for ([currentScore, currentName] in distributionIterator) {
message("in the home stretch\r\n");
//currentName = distributionIterator[currentScore];
message("candidate name = " + currentName.getName());
message(" expected rating = " + currentScore);
}
*/
message("best candidate name = " + bestName.getName() + " expected rating = " + bestScore + "\r\n", 1);
flushMessage();
//alert("done making recommendation. Best song name = " + bestName.getName());
return bestName;
}
// compute the distribution that is formed by combining the given distributions
function addDistributions(distributions, average) {
return this.averageDistributions(distributions);
}
// compute the distribution that is formed by combining the given distributions
function averageDistributions(distributions) {
// initialization
var sumY = 0.0;
var sumY2 = 0.0;
var sumWeight = 0.0; // the sum of the weights that we calculate, which we use to normalize
var stdDevIsZero = false;
var sumVariance = 0.0; // variance is another name for standard deviation squared
var outputWeight = 0.0;// the sum of the given weights, which we use to assign a weight to our guess
var count = 0.0; // the number of distributions being used
var weight;
var y;
var stdDev;
message("averaging distributions \r\n");
var i;
var currentDistribution;
// iterate over each distribution and weight them according to their given weights and standard deviations
for (i = 0; i < distributions.length; i++) {
currentDistribution = distributions[i];
message("mean = " + currentDistribution.getMean() + " stdDev = " + currentDistribution.getStdDev() + " weight = " + currentDistribution.getWeight() + "\r\n");
stdDev = currentDistribution.getStdDev();
// only consider nonempty distributions
if (currentDistribution.getWeight() > 0) {
// If the standard deviation of any distribution is zero, then compute the average of only distributions with zero standard deviation
if (stdDev == 0) {
if (!stdDevIsZero) {
stdDevIsZero = true;
sumVariance = 0.0;
sumY = sumY2 = 0.0;
outputWeight = count = sumWeight = 0.0;
}
}
// Figure out whether we care about this distribution or not
if ((stdDev == 0) || (!stdDevIsZero)) {
// get the values from the distribution
y = currentDistribution.getMean();
if (stdDev == 0.0) {
// If stddev is zero, then just use the given weight
weight = currentDistribution.getWeight();
} else {
// If stddev is nonzero then weight based on both the stddev and the given weight
weight = currentDistribution.getWeight() / stdDev;
}
// add to the running totals
sumY += y * weight;
sumY2 += y * y * weight;
sumWeight += weight;
sumVariance += stdDev * stdDev * weight;
outputWeight += currentDistribution.getWeight();
count += 1.0;
}
}
}
var result;
if (sumWeight == 0) {
result = new Distribution(0, 0, 0);
}
else{
// If we did have a distribution to predict from then we can calculate the average and standard deviations
var newAverage = sumY / sumWeight;
var variance1 = (sumY2 - sumY * sumY / sumWeight) / sumWeight;
message("variance1 = ");
message(variance1);
message("\r\n");
var variance2 = sumVariance / sumWeight;
message("variance2 = ");
message(variance2);
message("\r\n");
//stdDev = Math.sqrt(variance1 + variance2);
stdDev = Math.sqrt(variance2);
result = new Distribution(newAverage, stdDev, outputWeight);
}
message("resultant distribution = ");
printDistribution(result);
message("\r\n average of all distributions:" + (sumY / sumWeight) + "\r\n");
return result;
}
// print functions
function printCandidate(candidate) {
//message("printing candidate named " + candidate.getName().getName());
message(candidate.getName().getName() + "\r\n");
var parentNames = candidate.getParentNames();
message("numParents = " + candidate.getParents().length + "\r\n");
message("parent names:\r\n");
var i;
for (i = 0; i < parentNames.length; i++) {
message(parentNames[i].getName() + "\r\n");
}
message("\r\n");
}
function printRating(rating) {
message("name:" + rating.getActivity().getName() + "\r\n");
message("date:" + rating.getDate().stringVersion() + "\r\n");
message("score:" + rating.getScore() + "\r\n");
var now = new DateTime();
now.setNow();
var duration = rating.getDate().timeUntil(now);
message("time since now = " + duration);
}
function printDistribution(distribution) {
message("mean:" + distribution.getMean());
message(" stdDev:" + distribution.getStdDev());
message(" weight:" + distribution.getWeight() + "\r\n");
}
function printParticipation(participation) {
message("song name = " + participation.getActivityName().getName() + "\r\n");
message("start time = " + participation.getStartTime().stringVersion() + "\r\n");
message("end time = " + participation.getEndTime().stringVersion() + "\r\n");
message("intensity = " + participation.getIntensity() + "\r\n");
}
function test() {
//alert("testing");
//this.readFiles();
//message("hi\r\n");
//FileIO.writeFile("appendedFile.txt", "appended data", 1);
/*
var r1 = new Rating();
r1.setActivity("Holding on for a hero");
alert(r1.getActivity());
var dt = new DateTime();
alert("setting date");
r1.setDate(dt);
alert("setting score");
r1.setScore(0);
this.addRating(r1);
*/
/*
var c1 = new Candidate(new Name("name1"));
alert("adding candidate");
this.addCandidate(c1);
*/
/*var m1 = new MovingAverage();
//m1.superFunction();
alert("creating ParticipationMovingAverage");
var p1 = new ParticipationMovingAverage();
alert("p1.superFunction();");
p1.superFunction();
alert("creating RatingMovingAverage");
var r1 = new RatingMovingAverage();
alert("r1.superFunction();");
r1.superFunction();
*/
/*
if (m1.isAParticipationMovingAverage()) {
alert("m1 stores participations");
} else {
alert("m1 does not store participations");
}
message("done creating p1");
if (p1.isAParticipationMovingAverage()) {
alert("p1 stores participations");
} else {
alert("p1 does not store participations");
}
alert("m1 name = " + m1.stringVersion());
alert("p1 name = " + p1.stringVersion());
*/
//var candidate1 = new Candidate(new Name("Sell Me Candy"));
//var candidate1 = new Candidate;
//alert("adding candidate");
//addCandidate(candidate1);
//candidate1.setName("name1");
//message(candidate1.getName().getName());
}
/*function message(text) {
// append the text to the end of the output file
FileIO.writeFile("output.txt", text, 1);
// don't bother showing a blank message
//if (text != "\r\n")
// alert(text);
}*/
// recommend function
function recommend() {
var songName = "Come on Eileen";
alert("selecting song named " + songName);
const properties = Cc["@songbirdnest.com/Songbird/Properties/MutablePropertyArray;1"].createInstance(Ci.sbIMutablePropertyArray);
//properties.appendProperty(SBProperties.artistName, "Dexys Midnight Runners");
properties.appendProperty(SBProperties.trackName, songName);
var tracks = LibraryUtils.mainLibrary.getItemsByProperties(properties);
//var tracks = LibraryUtils.mainLibrary.getItemsByProperty(SBProperties.artistName, "Dexys Midnight Runners");
var gMM = Components.classes["@songbirdnest.com/Songbird/Mediacore/Manager;1"].getService(Components.interfaces.sbIMediacoreManager);
gMM.sequencer.playView(gMM.sequencer.view,gMM.sequencer.view.getIndexForItem(tracks.enumerate().getNext()));
alert("done selecting song");
}
/* Private Methods */
} | [
"function companyBotStrategy(trainingData) {\n let time = 0;\n let correctness = 0;\n trainingData.forEach(data => {\n if (data[1] === 1) {\n time += data[0];\n correctness += data[1];\n }\n });\n\n return time / correctness || 0;\n}",
"calculateUserTrend(userid, userStartingWeight) {\n logger.info(\"calculating user assessment trends\");\n const assessments = assessmentListStore.getUserAssessments(userid);\n if (assessments.length > 0) {\n if (parseFloat(assessments[0].weight) <= parseFloat(userStartingWeight)) {\n assessments[0].trend = true;\n } else {\n assessments[0].trend = false;\n }\n\n for (let i = 1; i < assessments.length; i++) {\n if (\n parseFloat(assessments[i].weight) <=\n parseFloat(assessments[i - 1].weight)\n ) {\n assessments[i].trend = true;\n } else {\n assessments[i].trend = false;\n }\n }\n this.store.save();\n }\n }",
"calcTime() {\n const numIng = this.ingredients.length;\n const periods = Math.ceil(numIng/3);\n this.time = periods * 15;\n }",
"function CombinedTimingViewModel (parameters) {\n var self = this\n self.ontime = parameters[0]\n self.offtime = parameters[1]\n\n // Chart configuration starts here\n self.index = 90\n self.chartElementSelectors = [\n { selector: '.combinedTimingChart', chart: null }\n ]\n self.chartData = [\n createDataSeries(self.ontime.label, self.index, 0, self.ontime.unit()),\n createDataSeries(self.offtime.label, self.index, 0, self.offtime.unit())\n ]\n\n /**\n * Update the data series and redraw the chart\n */\n\n self.updateChart = () => {\n self.index++\n pushToDataSeries(self, 0, self.ontime.value())\n pushToDataSeries(self, 1, self.offtime.value())\n updateChart(self)\n }\n\n /**\n * Start the interval timer once everything is loaded\n */\n\n self.onStartupComplete = () => setInterval(() => self.updateChart(), 100)\n}",
"function futurePremium(timeToRet,netgrowth){\n //current premiums\n var currentPremiumsMonthly=parseFloat($rootScope.yourSavings) + parseFloat($rootScope.empSavings);\n //future Premium Projected to retirement age\n //p((1+G)T-1)/G\n var futurePremium = currentPremiumsMonthly*((Math.pow(1+netgrowth.numberPm,timeToRet.months)-1))/netgrowth.numberPm;\n\n return {\n 'yourSavings':$rootScope.yourSavings,\n 'empSavings':$rootScope.empSavings,\n 'currentPremiumsMonthly':currentPremiumsMonthly,\n 'futurePremium':futurePremium,\n 'growthrateMontly':netgrowth.numberPm,\n 'monthsToRet':netgrowth.numberPm\n }\n}",
"function calculateTeamMotivation() {\n var i, sumMotivation = 0, activeResources = 0, moral,\n listResources = Variable.findByName(gm, 'resources'), worstMoralValue = 100,\n teamMotivation = Variable.findByName(gm, 'teamMotivation').getInstance(self);\n for (i = 0; i < listResources.items.size(); i++) {\n if (listResources.items.get(i).getInstance(self).getActive() == true) {\n moral = parseInt(listResources.items.get(i).getInstance(self).getMoral());\n sumMotivation += moral;\n activeResources++;\n if (moral < worstMoralValue)\n worstMoralValue = moral;\n }\n }\n teamMotivation.value = Math.round(((Math.round(sumMotivation / activeResources) + worstMoralValue) / 2));\n}",
"function genRouletteTimestampName() {\n return 'roulette::last';\n}",
"applyTropism() {\n this.tendTo(this.currentParams.tropism, this.currentParams.elasticity);\n }",
"function calculateRecall(user, recommendations) {\n const visitedPlaces = getVisitedPlaces(user);\n\n let matches = 0;\n\n visitedPlaces.forEach(visitedPlace => {\n if (recommendations.indexOf(visitedPlace) > -1) {\n matches++;\n }\n });\n\n return matches/visitedPlaces.length;\n}",
"function recomputeSchedule1() {\n changeSpecialTaxRate();\n\n computePg3Sc1I1();\n computePg3Sc1I2();\n computePg3Sc1I4();\n computePg3Sc1I7();\n computePg3Sc1I6();\n computePg3Sc1I8();\n computePg3Sc1I12();\n }",
"get railScore() {\n var comfort = this.normalizedUserComfort;\n var efficiency = this.normalizedEfficiency;\n return weightedAverage2(comfort, efficiency, COMFORT_IMPORTANCE);\n }",
"static getRuntimeStatistics() {\n return __awaiter(this, void 0, void 0, function* () {\n //using aggregation pipeline to implement the calculation\n const postsStatistics = yield this.model.aggregate([\n {\n $project: {\n _id: 0,\n function: \"$function\",\n averageRuntime: { $avg: \"$results\" },\n unit: \"miliseconds\"\n }\n }\n ]);\n return postsStatistics;\n });\n }",
"function am_rt30(input){ \n\treturn rt30;\n}",
"function updateRactives() {\n ractiveTitle.update();\n ractiveCategories.update();\n ractiveRisks.update();\n\tractiveGrades.update();\n\tractiveImpacts.update();\n ractiveRiskAssessment.update();\n ractiveSummary.update();\n ractiveResults.update();\n ractiveNotesSetup.update();\n ractiveNotesRisks.update();\n ractiveNotesImpacts.update();\n ractiveNotesRiskAssessment.update();\n ractiveNotesSummary.update();\n ractiveNotesResults.update();\n}",
"loadRecommendedItems() {\n // Get the ids of the current items in the list\n var currItemIds = this.state.listItemIds ? this.state.listItemIds : [];\n var currPrevRec = this.state.prevRecommended ? this.state.prevRecommended : [];\n\n var that = this;\n\n var ref = firebase.database().ref('/recommendations');\n var retItems = ref.once('value').then((snapshot) => {\n var newItems = {};\n var finalItems = [];\n\n // First check the rules\n // If an item is the precedent of a rule, add\n // the antecedent to the list of recommended items\n var ssv = snapshot.val();\n if (ssv) {\n for (var i = 0; i < currItemIds.length; i++) {\n var itemId = currItemIds[i];\n if (itemId in ssv) {\n var items = ssv[itemId];\n for (var newItemId in items) {\n var newItem = items[newItemId];\n if (!currItemIds.includes(newItem)) {\n if (!(newItem in newItems)) {\n newItems[newItem] = 0;\n }\n newItems[newItem] += 1;\n }\n }\n }\n }\n\n // Sort the current recommend items and\n // the list of top items\n var recItems = this.sortObjectByKeys(newItems);\n var topItems = this.sortObjectByKeys(ssv.topItems);\n\n var ids = [];\n var backlog = [];\n\n // Copy the top recommended items to the final list to recommend\n // as well as their ids, upto the maximum length\n for (var i = 0; (i < recItems.length) && (finalItems.length < NUM_REC_ITEMS); i++) {\n var info = globalComps.ItemObj.getInfoFromId(recItems[i][0]);\n var name = (new globalComps.ItemObj(info.name)).getDispName();\n var id = recItems[i][0];\n\n var toAdd = {\n genName: info.name,\n name: name,\n id: id,\n added: false\n };\n\n // Add the item to final items if it is not currently in the\n // user's list and it has not been previosuly recommended.\n // Otherwise, if the item is not in the list, but has been\n // previously recommended, add it to the backlog\n if ((!ids.includes(id)) && (!currPrevRec.includes(id))) {\n finalItems.push(toAdd);\n } else if ((!ids.includes(id)) && (currPrevRec.includes(id))) {\n backlog.push(toAdd);\n }\n\n ids.push(id)\n }\n\n // Fill the remaining space in the list of recommend items\n // with the most popular items\n for (var i = 0; (i < topItems.length) && (finalItems.length < NUM_REC_ITEMS); i++) {\n var id = topItems[i][0];\n if (!currItemIds.includes(id)) {\n var info = globalComps.ItemObj.getInfoFromId(topItems[i][0]);\n var name = (new globalComps.ItemObj(info.name)).getDispName();\n\n var toAdd = {\n genName: info.name,\n name: name,\n id: id,\n added: false\n };\n\n // Same as above\n if ((!ids.includes(id)) && (!currPrevRec.includes(id))) {\n finalItems.push(toAdd);\n } else if ((!ids.includes(id)) && (currPrevRec.includes(id))) {\n backlog.push(toAdd);\n }\n }\n }\n\n // If we're out of items to recommend, reset the backlog and previosuly recommended items\n for (var i = 0; (i < backlog.length) && (finalItems.length < NUM_REC_ITEMS); i++) {\n finalItems.push(backlog[i]);\n currPrevRec = [];\n }\n }\n\n // Save the list of recommended items\n that.setState({\n recommendedItems: finalItems,\n prevRecommended: currPrevRec\n });\n });\n }",
"function Timer(){\n\n var env = model.parseFile(model.currProjectFile);\n\n function _getStartData(args){\n let logData = {},\n task,\n project;\n\n if(args.hasArg('task') || args.hasArg('project')){\n task = args.getArg('task');\n project = args.getArg('project');\n }else{\n let projpos = args.getValuePos('project'),\n taskpos = args.getValuePos('task');\n\n project = projpos > -1 ? args.getPos(projpos + 1) : null;\n task = taskpos > -1 ? args.getPos(taskpos + 1) : null;\n }\n\n if(!_.isEmpty(project)) logData.project = project;\n if(!_.isEmpty(task)) logData.task = task;\n return logData;\n }\n \n function start(args){\n let data = _getStartData(args);\n if(_.isEmpty(data) && !_.isEmpty(env)){\n data = env; \n }\n // putting description here so that I can keep the environment variables but change the description on the fly\n if(args.hasArg('description')){\n data.description = args.getArg('description');\n }\n\n data.startTime = + new Date();\n let ret = model.start(data);\n if(!ret){\n console.log(\"Something went wrong. Couldn't start timer.\");\n }\n return ret;\n }\n\n function stop(args){\n model.stop(args);\n }\n\n function distract(args){\n model.distract(args);\n }\n\n /* \n * check the status of the timer \n * timelog status\n * returns the current project, task, start time, ellapsed time and whether or not we are in distract mode\n */\n function status(){\n if(!_.isEmpty(env)){\n console.log(\"Currently in the following environment:\");\n console.log(columnify(env));\n console.log(\" \"); \n }\n \n var ret = model.checkStatus();\n if(ret === false){\n console.log(\"You currently do not have any timers running\");\n }else{\n console.log(columnify(ret));\n }\n }\n\n\n /* \n * analyze the time we've spent\n * timelog analyze <today | date> - defaults to today\n */\n function analyze(args){\n let passData = {};\n passData.date = new Date();\n \n if(args.hasArg('date')){\n passData.date = new Date(args.getArg('date'));\n }\n \n if(args.hasArg('groupby')){\n passData.groupby = args.getArg('groupby');\n if(args.hasArg('and')){\n passData.and = args.getArg('and');\n }\n }\n\n var data = model.analyze(passData);\n if(_.isEmpty(data)){\n console.log(\"There are no timers for this date\");\n }else{\n\n console.log(columnify(data, {config: { description: {maxWidth: 30}}}));\n }\n }\n\n return {start, stop, distract, status, analyze};\n}",
"run (start, end, options={}) {\n\n let delay = options.delay || 0; // initial delay\n const duration = options.duration;\n let resolution = options.resolution || beat;\n const tonic = options.tonic || start;\n const mode = options.mode;\n const descending = end < start;\n const res = [];\n let allowableNotes = mode && getNotes(tonic, mode).filter((n) => descending ? n <= start && n >= end : n >= start && n <= end);\n const length = mode && allowableNotes.length || Math.abs(end - start) + 1;\n\n if (duration) {\n resolution = Math.floor(duration / length);\n }\n\n if (duration && resolution*length !== duration) {\n console.warn('Run: Your duration is not divisible by the resolution. Adjusting resolution accordingly');\n }\n\n if (!mode) { \n for (let i = start; descending ? i >= end : i <= end; descending ? i-- : i++) {\n\n res.push({ note: i, duration: resolution, delay });\n delay = 0;\n }\n }\n\n if (mode) { \n for (let i = 0; i < allowableNotes.length; i++) {\n\n res.push({ note: allowableNotes[descending ? length - 1 - i : i], duration: resolution, delay });\n delay = 0;\n }\n }\n\n // add any remainder to the duration of the last note\n if (duration % resolution) {\n res[res.length - 1].duration = res[res.length - 1].duration + duration % resolution;\n }\n\n\n // if there are existing notes. add the run to them!\n this.notes = this.notes.concat(res);\n return this;\n }",
"function calculate() \n{\n\tif(timecount < 10000) { // 10 secs limit\n\t\t//calculate note persistence as a function of time\n\t\tvar notepersistence = persistence_increase(timecount);\n\t\t\n\t\t//accumulate weights in each Harmonic Center (HC)\n\t\tfor(i = 0; i < resolution; i++) {\n\t\t\tvar next_index = Math.abs((i-resolution) % resolution);\n\t\t\tvar noteweight = scale(notepersistence, 0., 10000., 0., weights[next_index]);\n\t\t\t\n\t\t\thcindex_mod = (hcindex + i) % resolution;\n\t\t\thcw[hcindex_mod][next_index] += noteweight;\n\t\t}\n\t}\n\telse {\n\t\tlimit = true;\n\t}\t\n}",
"function makeRandomRhythm(lengthLessOne, numBarsLessOne, beatsPer, shortestDuration){\n //shortestDuration === 1/2 for 8th note, 1 for quarter notes, etc. ?\n\n //first, number of rhythmic 'slots' that we can put notes into\n var numSlots = beatsPer * numBarsLessOne / shortestDuration;\n //console.log(numSlots);\n var slots = rangeBetter(0, beatsPer * numBarsLessOne, shortestDuration);\n //console.log(slots);\n var rhythms = [];\n //start on the beat. FIX THIS when we have rests\n rhythms.push(0);\n slots.splice(0, 1);\n for (var i = 1; i < lengthLessOne - 1; i += 1){\n var toAdd = randomChoiceFromArray(slots);\n slots.splice(slots.indexOf(toAdd), 1);\n rhythms.push(toAdd);\n }\n rhythms.sort(function(a,b){\n return a - b;\n });\n \n var unsyncopated = unsyncopate(rhythms, beatsPer, []);\n var durations = convertToDuration(unsyncopated, beatsPer, []);\n //a function to find out where the 'near syncopations' are\n var beats = unsyncopated.map(function(current){\n return current % beatsPer;\n });\n var cantLengthen = longest(durations, beatsPer);\n var cantShorten = shortest(durations, shortestDuration);\n var measures = findMeasures(durations, beatsPer);\n var allMeasures = allMeasuresUsed(measures, numBarsLessOne);\n return {slots: unsyncopated, beatsPer: beatsPer, beats: beats, durations: durations, measures: measures, cantLengthen: cantLengthen,\n cantShorten: cantShorten, shortestDuration: shortestDuration, allMeasures: allMeasures, numBars: numBarsLessOne}\n\n //okay, for now, syncopations are allowed, but the objective function will frown upon them heavily\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes the direction of the rover when commands are left or right | function changeDirection(direction, command) {
if (direction == 'N' && command == 'l') {
myRover.direction = 'W';
}
else if (direction == 'N' && command == 'r') {
myRover.direction = 'E';
}
else if (direction == 'E' && command == 'l') {
myRover.direction = 'N';
}
else if (direction == 'E' && command == 'r') {
myRover.direction = 'S';
}
else if (direction == 'W' && command == 'l') {
myRover.direction = 'S';
}
else if (direction == 'W' && command == 'r') {
myRover.direction = 'N';
}
else if (direction == 'S' && command == 'l') {
myRover.direction = 'E';
}
else {
myRover.direction = 'W';
}
} | [
"function turnRight(rover){\n console.log(rover.name + \": turnRight was called\");\n\n switch(rover.direction){\n case \"N\":\n rover.direction=\"E\";\n break;\n case \"E\":\n rover.direction=\"S\";\n break;\n case \"S\":\n rover.direction=\"W\";\n break;\n case \"W\":\n rover.direction=\"N\";\n break;\n }\n}",
"function changeDirectionObstacle(rover) {\r\n if (myRover.direction == 'N') {\r\n myRover.direction = 'E';\r\n } else if (myRover.direction == 'E') {\r\n myRover.direction = 'S';\r\n } else if (myRover.direction == 'W') {\r\n myRover.direction = 'N';\r\n } else {\r\n myRover.direction = 'W';\r\n }\r\n}",
"function goRight(rover) {\r\n\tswitch(rover.direction) {\r\n\t\tcase 'N': rover.position[1]++;\r\n\t\t\tbreak;\r\n\t\tcase 'E': rover.position[0]++;\r\n\t\t\tbreak;\r\n\t\tcase 'W': rover.position[0]--;\r\n\t\t\tbreak;\r\n\t\tcase 'S': rover.position[1]--;\r\n\t\t\tbreak;\r\n\t}\r\n}",
"function goLeft(rover) {\r\n\tswitch(rover.direction) {\r\n\t\tcase 'N': rover.position[1]--;\r\n\t\t\tbreak;\r\n\t\tcase 'E': rover.position[0]--;\r\n\t\t\tbreak;\r\n\t\tcase 'W': rover.position[0]++;\r\n\t\t\tbreak;\r\n\t\tcase 'S': rover.position[1]++;\r\n\t\t\tbreak;\r\n\t}\r\n}",
"function move(currentorder)\n\n/** \n * Every if of the function, checks the value of the objetct direction(string). First step is check where is looking the Rover.\nSedcond step is depending on where is looking the Rover, the function will ++ or -- a position into the Rover coordinates. \nOr change the value of the object direction.\n */ \n{\n if (Myrover.direction === 'up') {\n\n switch (currentorder) {\n case 'f':\n Myrover.position.x++\n break;\n case 'r':\n Myrover.direction = 'right';\n return;\n break;\n case 'b':\n Myrover.position.x--\n break;\n case 'l':\n Myrover.direction = 'left'\n return;\n break;\n };\n };\n\n\n if (Myrover.direction === 'right') {\n switch (currentorder) {\n case 'f':\n Myrover.position.y++\n break;\n case 'r':\n Myrover.direction = 'down';\n return;\n break;\n case 'b':\n Myrover.position.y--\n break;\n case 'l':\n Myrover.direction = 'up';\n return;\n break;\n };\n };\n\n if (Myrover.direction === 'down') {\n switch (currentorder) {\n case 'f':\n Myrover.position.x--\n break;\n case 'r':\n Myrover.direction = 'left'\n return;\n break;\n case 'b':\n Myrover.position.x++\n break;\n case 'l':\n Myrover.direction = 'right'\n return;\n break;\n };\n };\n\n if (Myrover.direction === 'left') {\n switch (currentorder) {\n case 'f':\n Myrover.position.y--\n break;\n case 'r':\n Myrover.direction = 'up'\n return;\n break;\n case 'b':\n Myrover.position.y++\n break;\n case 'l':\n Myrover.direction = 'down'\n return;\n break;\n };\n };\n}",
"function turnRight(rover) {\n var movement=\"r\";\n switch(rover.direction) {\n case 'N':\n rover.direction = 'E';\n break;\n case 'E':\n rover.direction = 'S';\n break;\n case 'S':\n rover.direction = 'W';\n break;\n case 'W':\n rover.direction = 'N';\n break;\n }\n var report = validations(rover,movement);\n printResult(report,rover,movement);\n}",
"function updateMotion(dir) {\n switch(dir) {\n case \"N\":\n motX=0;motY=-1;\n break;\n case \"S\":\n motX=0;motY=1;\n break\n case \"E\":\n motX=1;motY=0;\n break;\n case \"W\":\n motX=-1;motY=0;\n break;\n }\n}",
"function updateDirection() {\n\n\tvar p2 = {\n\t\tx: state.tree[1],\n\t\ty: state.tree[0]\n\t};\n\n\tvar p1 = {\n\t\tx: state.user.location[1],\n\t\ty: state.user.location[0]\n\t};\n\n\t// angle in degrees\n\tvar angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;\n\tangleDeg -= state.user.heading\n\t$(\"#trees .tree .left .dir\").css(\"transform\", \"rotate(\" + angleDeg + \"deg)\")\n\n\tvar dist = getDistanceFromLatLonInM(state.user.location, state.tree)\n\tdist = dist < 1000 ? dist + \"m\" : (Math.round(dist / 100)) / 10 + \"km\"\n\n\t$(\"#trees .tree .left .dist\").html(dist)\n}",
"function leftWindowToRightLocation() {\n moveForward(15);\n turnRight(90);\n moveForward(50);\n turnRight(90);\n moveForward(7);\n turnRight(90);\n}",
"changeDirection (direction) {\n let newState = Object.assign({}, this.state);\n newState.snake.direction = direction;\n this.setState(newState);\n this.canvasMoveSnake();\n }",
"turnAround() {\n this.left(180);\n }",
"function setNextDirection(event) {\n let keyPressed = event.which;\n\n /* only set the next direction if it is perpendicular to the current direction */\n if (snake.head.direction !== \"left\" && snake.head.direction !== \"right\") {\n if (keyPressed === KEY.LEFT) { snake.head.nextDirection = \"left\"; }\n if (keyPressed === KEY.RIGHT) { snake.head.nextDirection = \"right\"; }\n }\n \n if (snake.head.direction !== \"up\" && snake.head.direction !== \"down\") {\n if (keyPressed === KEY.UP) { snake.head.nextDirection = \"up\"; }\n if (keyPressed === KEY.DOWN) { snake.head.nextDirection = \"down\"; }\n }\n}",
"moveRight() {\n\t\tsuper.moveRight(KEN_SPRITE_POSITION.moveRight, KEN_IDLE_ANIMATION_TIME, false, MOVE_SPEED);\n\t}",
"ghostChangeDirection() {\n let direction = random(4);\n switch(int(direction)) {\n case 0:\n this.currentDirection = \"up\";\n break;\n case 1:\n this.currentDirection = \"down\";\n break;\n case 2:\n this.currentDirection = \"left\";\n break;\n case 3:\n this.currentDirection = \"right\";\n break;\n }\n }",
"function moveToDoorLocation() {\n penUp();\n turnRight(24);\n moveForward(50);\n turnRight(90);\n moveForward(20);\n turnRight(90);\n penDown();\n}",
"moveDown(){\n\t\tthis.aimDir = vec2.down();\n\t}",
"function setTravelDirection() {\n if (elevator.currentFloor() <= getMinFloor(upQueue)) {\n elevator.travelDirection = \"up\";\n // Set up the lights\n if (directionLights) {\n elevator.goingDownIndicator(false);\n elevator.goingUpIndicator(true);\n }\n }\n else if (elevator.currentFloor() >= getMaxFloor(downQueue)) {\n elevator.travelDirection = \"down\";\n if (directionLights) {\n elevator.goingDownIndicator(true);\n elevator.goingUpIndicator(false);\n }\n }\n else {\n elevator.travelDirection = \"down\";\n if (directionLights) {\n elevator.goingDownIndicator(true);\n elevator.goingUpIndicator(false);\n }\n }\n }",
"move() {\n this.change = this.mouthGap == 0 ? -this.change : this.change;\n this.mouthGap = (this.mouthGap + this.change) % (Math.PI / 4) + Math.PI / 64;\n this.x += this.horizontalVelocity;\n this.y += this.verticalVelocity;\n }",
"function execute(rover, commands, turn){\n \n switch(commands[turn]){\n\n case \"f\":\n moveForward(rover);\n break;\n\n case \"b\":\n moveBackward(rover);\n break;\n\n case \"l\":\n turnLeft(rover);\n break;\n\n case \"r\":\n turnRight(rover);\n break;\n\n case undefined:\n //There is not more turns for this rover\n break;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function : onMapClick Channel : dogtracker_marker_position Description : Publishes lat/lon position to server through this pubnub channel and opens the popup for uploading image to server | function onMapClick(e){
popup
.setLatLng(e.latlng)
.setContent('<strong>Current position : '+e.latlng.toString() +'</strong><br/><br/>'+
'<form id="uploadForm" action="/uploadimage" enctype="multipart/form-data" method="POST" target="uploader_iframe">'+
'<input type="file" name="userPhoto" /><br/><br/>'+
'<div class="buttonHolder"><input id="submitImage" type="submit" value="Upload Image" name="submit" disabled></div>'+
'</form>'+
'<iframe id="uploader_iframe" name="uploader_iframe" style="display: none;"></iframe>')
.openOn(map);
$('input:file').change(
function(){
if ($(this).val()) {
$('input:submit').attr('disabled',false);
}
}
);
var channel = 'dogtracker_marker_position';
var message = {"lat":e.latlng.lat.toString(),"lon":e.latlng.lng.toString()}
console.log(message)
pubPublish(channel,message)
} | [
"function onMapClick(e) {\n // Popup example\n popup\n .setLatLng(e.latlng)\n .setContent(\"You clicked the map at \" + e.latlng.toString())\n .openOn(mymap);\n\n last_point_clicked = e.latlng;\n\n var add_point_cbx = document.getElementById('add_marker_CBX');\n if (add_point_cbx.checked) {\n place_marker(e.latlng, true)\n }\n}",
"function changeMarker(location) {\n\tmyMarker.setPosition(location);\n\tmyMap.setCenter(location);\n\t$( \"#user_pos\" ).text( \"User Position: \" + location.toUrlValue() );\n}",
"function geoSuccess(position) {\n var lat = position.coords.latitude;\n var lng = position.coords.longitude;\n window._TRACKER.geo = `${lat}|${lng}`;\n }",
"function addEventListner(marker, markerString){\n google.maps.event.addListener(marker, 'click', function(){\n \tpublicState.infoWindow.close();\n publicState.infoWindow.setContent(markerString);\n publicState.infoWindow.open(publicState.map ,marker);\n }); \n}",
"function initMap() {\n map = new google.maps.Map(document.getElementById('map'), {\n center: {lat: 39.952406, lng: -75.163678},\n zoom: 12,\n disableDoubleClickZoom: true,\n gestureHandling: 'greedy',\n });\n\n messagewindow = new google.maps.InfoWindow({\n content: document.getElementById('message')\n });\n\n marker = new google.maps.Marker({\n map: map,\n draggable: true\n })\n\n // const toolTip = new google.maps.InfoWindow({\n // content: \"Click to submit a new tap\"\n // });\n //\n // google.maps.event.addListener(marker, 'mouseover', function() {\n // toolTip.open(map, marker);\n // });\n //\n\n\n // google.maps.event.addListener(marker, 'mouseout', function() {\n // toolTip.close();\n // });\n\n google.maps.event.addListener(map, 'click', function(event) {\n marker.setMap(map);\n marker.setVisible(true);\n messagewindow.close();\n // placeMarker(event.latLng, map, marker);\n });\n\n getTaps(true);\n getNewTaps();\n\n\n\n // create legend and add legend items\n const legend = document.getElementById('legend');\n const filter = document.getElementById('filter');\n\n \n\n var legendElementMap = phlaskUtils.generateLegend(phlaskData.tapTypes);\n\n for (legendElement in legendElementMap) {\n var element = legendElementMap[legendElement];\n legend.appendChild(element);\n }\n\n var geoLocate = document.querySelector('#geo-locate');\n //geoLocate.style.display = 'none';\n //geoLocate.addListener('click', locateMe());\n google.maps.event.addDomListener(geoLocate, 'click', () => {\n jQuery.post( \"https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDxIuJdCSTm7yDQaShtWq7-sI3KOsrn30w\", function(success) {\n showPosition(success);\n //alert(success.location.lat + \", \" + success.location.lng);\n })\n .fail(function(err) {\n alert(\"Geolocation Failure\");\n });\n });\n\n function showPosition(position) {\n var position = {lat: position.location.lat, lng: position.location.lng};\n // const myLocation = new google.maps.Marker({\n // map: map,\n // position: position,\n // icon: userLocation\n // })\n locationMarker.setPosition(position);\n locationMarker.setMap(map);\n\n map.setZoom(20);\n map.panTo(position);\n }\n\n latLonDiv = document.getElementById('latlon-div');\n filterDiv = document.getElementById('filter-div');\n //latLonDiv.style.display = 'none';\n\n google.maps.event.addListenerOnce(map, 'tilesloaded', function() {\n map.controls[google.maps.ControlPosition.LEFT_TOP].push(latLonDiv);\n latLonDiv.style.display = 'block';\n map.controls[google.maps.ControlPosition.LEFT_TOP].push(filterDiv);\n latLonDiv.style.display = 'block';\n map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(legend);\n legend.style.display = \"block\";\n map.controls[google.maps.ControlPosition.LEFT_TOP].push(filter);\n filter.style.display = \"block\";\n map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(geoLocate);\n //geoLocate.style.display = 'block';\n \n });\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}",
"function addMarker (location, map) {\n if (!mainPosition) {\n mainPosition = new google.maps.Marker({\n position: location,\n label: \"Observer\",\n map: map,\n });\n }\n else {\n mainPosition.setPosition(location);\n }\n \n if (MAIN_DEBUG)\n console.log(location.toJSON());\n // add lat and Lng to the input boxes:(id=satellite-lat and id=satellite-lon)\n $(\"#satellite-lat\").val(location.toJSON()[\"lat\"]);\n $(\"#satellite-lon\").val(location.toJSON()[\"lng\"])\n}",
"function placeMarker(mapElement) {\n // check whether we've made the maker yet. If not, make it.\n var latLng = new google.maps.LatLng(mapElement.location.latitude, mapElement.location.longitude);\n if (!(latLng in latLngDict)) {\n var marker = new google.maps.Marker({\n position: latLng,\n map: map,\n title: mapElement.name\n });\n var contentString = '<div id=\"content\">'+\n mapElement.abbreviation + ' ' + mapElement.name +\n '</div>';\n var infoWindow = new google.maps.InfoWindow({\n content: contentString\n });\n\n // add entry to latLngDict.\n latLngDict[latLng] = {\"marker\":marker, \"infoWindow\":infoWindow};\n google.maps.event.addListener(marker, 'click', function(target) {\n // close all the open info windows.\n closeAllInfoWindows();\n\n var dictEntry = latLngDict[target.latLng];\n dictEntry.infoWindow.open(map, dictEntry.marker);\n }); \n }\n var dictEntry = latLngDict[latLng];\n dictEntry.infoWindow.open(map, dictEntry.marker);\n }",
"function setupMarkerListener() {\n var marker = null;\n\n google.maps.event.addListener(map, 'click', function(e) {\n if (marker == null) {\n marker = new google.maps.Marker({\n\t\tposition: e.latLng,\n\t\tmap: map,\n\t\ttitle: 'Request Location'\n });\n $(\"#create_task_button\").show(); \n }\n else {\n marker.setPosition(e.latLng);\n }\n $(\"#lat\").val(e.latLng.lat());\n $(\"#lng\").val(e.latLng.lng());\n });\n}",
"function handleClickOnMap() {\n $(\"#map_container\").click(function() {\n startMapMode();\n });\n }",
"function onPositionInfo(data) {\n\tif (\"Error\" in data) {\n\t\tonError(data.Error);\n\t} else if (\"Value\" in data) {\n\t\tobj = data.Value;\n\t\t$(\"#track\").text(obj.Track + \"/\" + queueSize);\n\t\t$(\"#track-duration\").text(formatDuration(obj.TrackDuration));\n\t\t$(\"#rel-time\").text(formatDuration(obj.RelTime));\n\t\t$(\"#title\").text(obj.Title);\n\t\t$(\"#album\").text(obj.Album);\n\t\t$(\"#progress-bar\").progressbar(\"value\", 100 * (obj.RelTime / obj.TrackDuration));\n\t\t$(\".progress-label\").text(formatDuration(obj.TrackDuration - obj.RelTime));\n\t\tsetCurrentTrack(obj.Track);\n\t}\n}",
"handleMapClick(event){\n\t\tthis.mapPage.setMapUnClickable();\n\t\tthis.drawPopUpPage(event);\n\t\tthis.drawPopUpTexts();\n\t}",
"function markMap()\n\t{\n\t\tstrResult=req.responseText;\n\n\t\tfltLongitude=getValue(\"<Longitude>\",\"</Longitude>\",11);\n\t\tfltLatitude=getValue(\"<Latitude>\",\"</Latitude>\",10);\n\t\tif( fltLongitude==\"\" || fltLatitude==\"\")\n\t\t{\n\t\t\tshowSearchResultsError('No information found',\"WARNING\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// First Clear any Previous Error Messages \t\n\t\t\tdocument.getElementById(\"divMapErrorBox\").innerHTML=\"\";\n\t\t\tdocument.getElementById(\"divMapErrorBox\").style.visibility=\"visible\";\n\t\t\t\n\t\t\t// Create Html \n\t\t\tstrHtml=\"<table cellspacing=0 cellpadding=0 border=0>\";\n\t\t\tstrHtml=strHtml+\"<tr><td align=right><b>Longitude:</b></td><td width=5></td><td>\"+fltLongitude+\"</td>\";\n\t\t\tstrHtml=strHtml+\"<tr><td align=right><b>Latitude:</b></td><td width=5></td><td>\"+fltLatitude+\"</td>\";\n\t\t\tstrHtml=strHtml+\"</table>\";\n\t\t\t\n\t\t\t// Save Location in Global Variables \n\t\t\t//G_CURRENT_POINT=new YGeoPoint(fltLatitude,fltLongitude);\n\t\t\t\n\t\t\t//Show Marker \n\t \t showMarker(fltLatitude, fltLongitude,13,\"\",strHtml);\n\t \t \n\t \t //document.getElementById('mapContainer').innerHTML=\"Problems ..........\";\n\t\t} \n\t}",
"function dropPizza(map, pos) {\n var pizza = 'images/pizza.png';\n var timestamp = new Date().getTime();\n var marker = new google.maps.Marker({\n position: pos,\n map: map,\n timestamp: timestamp,\n animation: google.maps.Animation.DROP,\n title: 'Itza Pizza!',\n icon: pizza,\n size: 0.25\n });\n}",
"function showCoordinates(evt) {\n //the map is in web mercator but display coordinates in geographic (lat, long)\n var mp = webMercatorUtils.webMercatorToGeographic(evt.mapPoint);\n //display mouse coordinates\n dom.byId(\"info\").innerHTML = mp.x.toFixed(3) + \", \" + mp.y.toFixed(3);\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 placeGoodMarkers() {\n\tGOOD_listener = google.maps.event.addListener(map, 'click', function(event) {\n\t\tplaceGoodMarker(event.latLng);\n\t});\n}",
"function place_marker(latlng, log_point) {\n\n // Add marker to map\n var marker = L.marker(latlng);\n layers['marker_layer'].addLayer(marker);\n\n // Log point to javascript console\n if (log_point) {\n var data = {};\n data[\"lat\"] = latlng.lat.toString();\n data[\"lng\"] = latlng.lng.toString();\n console.log(data);\n }\n\n // Ajax call if logging point to python, stick with this format probably, more standard\n if (log_point) {\n $.ajax({\n type: \"POST\"\n , url: \"{{ url_for('leaflet_test_latlng') }}\"\n , data: JSON.stringify(data, null, '\\t')\n , contentType: 'application/json;charset=UTF-8'\n , success: function (result) { return undefined }\n });\n }\n}",
"function mapLocation(entity, frcInfo) {\n\n var entityType = entity.getType();\n\n var geo_location = frcInfo.geo_locations[entity.key];\n var resultsMap = frcInfo.map;\n\n resultsMap.setCenter(geo_location);\n\n var icon = getMarkerIcon(entity, frcInfo);\n\n var marker = new google.maps.Marker({\n map: resultsMap,\n position: geo_location,\n icon: icon\n });\n if ( !marker ) {\n console.log( \"Error creating marker for \" + entity.key ); \n }\n\n var infoString = \"\";\n \n if (entityType == \"TEAM\") {\n var rookieStr = '';\n if (entity.first_year == frcInfo.lastYear )\n rookieStr = 'Rookie ';\n infoString = 'Hello, we are <b>' + rookieStr + 'Team ' + entity.team_number + '</b>.';\n infoString += '<br>' + 'We are ' + entity.nickname + '.';\n infoString += '<br>' + 'From ' + entity.location + '.';\n if ( entity.website )\n infoString += '<br>' + '<a href=\"' + entity.website + '\">' + entity.website + '</a>';\n infoString += '<br>Years competed: ' + entity.first_year + '-' + entity.last_year;\n }\n\n if (entityType == \"EVENT\") {\n infoString = '<b>' + entity.year + ' ' + entity.name + '</b>';\n infoString += '<br>Location: ' + entity.location;\n infoString += '<br>Event date: ' + entity.start_date;\n infoString += '<br>Event type: ' + entity.event_type_string;\n }\t\t\t\n\n var infoWindow = new google.maps.InfoWindow({ content: infoString });\n\n google.maps.event.addListener(marker, 'click', function () {\n infoWindow.open(map, marker); });\n\n entity.marker = marker;\n entity.geolocation = geo_location;\n entity.marker.setVisible(false);\n entity.infoWindow = infoWindow;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sendDataToApp is call back function TODO:send data in object projectData | function sendDataToApp(req, res) {
res.send(projectData);
} | [
"function sendData (client, method, data) {\n\t\tvar packet = { methodName : method, data : data };\n\t\t\n\t\tclient.fn.send(\"PROJECT\", packet);\n\t}",
"function setAppData(appData) {\n self.LApp.data = appData;\n $log.debug('success storing application data');\n }",
"function sendDataToServer(survey) {\n //var resultAsString = JSON.stringify(survey.data);\n //alert(resultAsString); //send Ajax request to your web server.\n let dataReq = new RequestObj(1, \"/survey\", \"/save/projects/?/context/?\", [projectName, context], [], survey.data);\n userEmail = survey.data.EMAIL1;\n serverSide(dataReq, \"POST\", function () {\n //log.warn(a);\n let asciiMail = \"\";\n for (let i = 0; i < userEmail.length; i++) {\n asciiMail += userEmail[i].charCodeAt(0) + \"-\";\n }\n asciiMail = asciiMail.substring(0, asciiMail.length - 1);\n location.href = window.location.href + \"&userEmail=\" + asciiMail;\n })\n}",
"function addDataToServer(req, res) {\n console.log(\"addDataToServer func. :\" + req.body);\n projectData[\"date\"] =req.body.date;\n projectData[\"temp\"] =req.body.temp;\n projectData[\"content\"] = req.body.userFeeling;\n \n}",
"function getAppData() {\n $log.debug('success retrieving application data');\n return self.LApp.data;\n }",
"function GetMainAccountTaskPerformData(req, callback) {\n\tcontractInfo.getContractInfo(req.params.contractAddress,(err,doc)=>{\n\t\tvar json = [];\n\t\tif(err){\n\t\t\tcallback(null, json);\n\t\t} else if (doc !== null) {\n var obj = {};\n var status = [];\n var abiJson = JSON.parse(doc.abi);\n var Multiply7 = web3.eth.contract(abiJson);\n var multi = Multiply7.at(req.params.contractAddress);\n var updateCount = multi.getstatusupdateCount();\n for (var j = 0; j < updateCount.toString(); j++) {\n var updateInfo = multi.getstatusupdate(j);\n var splitArr = [];\n var arr = updateInfo.toString().split(\",\");\n for (var k = 0; k < arr.length; k++) {\n splitArr.push(arr[k]);\n }\n if (splitArr[1] == req.session.address) {\n status.push(splitArr[3]);\n }\n }\n if (status.length > 0) {\n\t\t\t\tobj.status = common.getstatustext(status[status.length - 1]);\n }\n if (multi.owner() == req.session.address) {\n obj.contractNumber = multi.contractNumber();\n obj.contractAddress = doc.contractAddress;\n obj.ContractDescription = multi.contractDescription();\n obj.ContractOwnedby = multi.contractOwnedby();\n obj.data = \"Rejected Data\";\n obj.isrejected = false;\n json.push(obj);\n }\n var assigneeCount = multi.getassigneeCount();\n for (var i = 0; i < assigneeCount.toString(); i++) {\n var assignee = multi.getassignee(i);\n var assigneeSplitArr = [];\n var assigneeArr = assignee.toString().split(\",\");\n for (var m = 0; m < assigneeArr.length; m++) {\n assigneeSplitArr.push(assigneeArr[m]);\n }\n if (i == 1 && assigneeSplitArr[3] == props.status_rejected) {\n obj.isrejected = true;\n }\n }\n } else {\n callback(null, json);\n }\n\t});\n}",
"function sendCurrentProject( windowId, tabId )\n{\n var p = project[windowId];\n if( undefined === p ) {\n p = '';\n }\n chrome.tabs.sendMessage(\n tabId, \n {\n 'method' : 'returnCurrentProject',\n 'args' : p\n } \n );\n return p;\n}",
"function pushRegistration()\n{\tif(frmUrl.txtBoxAppId.text!==\"\"&&frmUrl.txtBoxSenderID.text!==\"\"&&frmUrl.txtBoxUrl.text!==\"\"){\n KMSPROP.kmsServerUrl=frmUrl.txtBoxUrl.text;\n KMSPROP.appId=frmUrl.txtBoxAppId.text;\n KMSPROP.senderID=frmUrl.txtBoxSenderID.text;\n\t}\n else{\n alert(\"The URL, APPID and SenderId Should not be Empty\");\n return;\n }\n\tkony.print(\"\\n\\n----in pushRegister----\\n\");\n\t//subsFrom=from;\n\tisDeleteAudience=false;\n\tvar devName = kony.os.deviceInfo().name;\n//\talert(\"devName\" + devName);\n\tkony.application.showLoadingScreen(\"sknLoading\",\"please wait..\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true,null);\n\tif(devName==\"android\")\n\t{\n\t\tcallbackAndroidSetCallbacks();\n\t\tcallbackAndroidRegister();\n\t}else if((devName==\"iPhone\")||(devName==\"iPhone Simulator\")||(devName==\"iPad\")||(devName==\"iPad Simulator\"))\n\t{\n\t\tcallbackiPhoneSetCallbacks();\n\t\tcallbackiPhoneRegister();\n\t}\n}",
"function sendToServer() {\n // Url issue is sent to\n const url = 'http://localhost:1234/whap/add-issue?' + 'iss';\n // Data being sent\n var data = {\n name: document.getElementById(\"title\").value,\n des: document.getElementById(\"msg\").value,\n prio: document.getElementById(\"priority\").value,\n os: document.getElementById(\"OS\").value,\n com: document.getElementById(\"component\").value,\n ass: document.getElementById(\"assignee\").value,\n user: window.name\n };\n\n // Posts the data\n var resp = postData('http://localhost:1234/whap/add-issue', data)\n // Tells user they did it\n .then(alert(\"You did it\"));\n}",
"_onProjectItemClicked(projectName) {\n // TODO: give full information on the project and whether the user is a member of it\n let event = new CustomEvent(\"project-selected\", {\n detail: {\n message: \"Selected project in project list.\",\n project: this.getProjectByName(projectName)\n },\n bubbles: true\n });\n this.dispatchEvent(event);\n }",
"function pagerDutyTrigger(){\n if(action_pagerDuty){\n console.log('pager duty trigger');\n\n var pagerDutyObj = {\n service_key: action_pagerduty_service_key,\n incident_key: action_pagerduty_incident_key,\n event_type: action_pagerduty_event_type,\n description: action_pagerduty_description,\n client: action_pagerduty_client,\n client_url: action_pagerduty_client_url,\n details: results_json\n };\n\n var contentType = 'application/json';\n\n var dataString = JSON.stringify(pagerDutyObj);\n\n triggerEmail.httpSend(action_pagerduty_protocol, action_pagerduty_host, action_pagerduty_endpoint, action_pagerduty_method, contentType, dataString);\n }\n}",
"function f_ProcessJSONData_Main(frame){\n\t//\tlog AppID received\t\t\t\n\t//f_RADOME_log(frame.AppID);\n\t//Check AppID and do what fit with that\n\tvar id = parseInt(frame.AppID);\n\tswitch(id) // inspect id found to dispatch the appropriate processing\n\t{\n\t\tcase APP_ID.LIST:\n\t\t\t// load JSON data (into 'frame') to update and fill the select '$(he_SelectRADOMECmds)'\n\t\t\tf_GUI_Update_Select(frame, $(he_SelectRADOMECmds));\t\n\t\t\tbreak;\n\t\t\n\t\tcase APP_ID.VERSION:\n\t\t\t// load data json to populate the angular model \"$scope.versionInfo\" \n\t\t\tf_RADOME_log(\"load data json to populate the angular model $scope.versionInfo\");\n\t\t\tf_GUI_Update_Version(frame);\t\n\t\t\tbreak;\t\n\t\t\t\n\t\t// if process is \"CAN\"\n\t\tcase APP_ID.CAN1:\n\t\tcase APP_ID.CAN2:\n\t\tcase APP_ID.CAN3:\n\t\tcase APP_ID.CAN4:\n\t\tcase APP_ID.CAN5:\n\t\t\t//Update GUI for the 'gauge' element\n\t\t\tf_ProcessJSONData_CAN(frame);\t\n\t\t\t// TO DO : simulate click on concerned tab menu\n\t\t\t//$(\"#menu2\").click();\n\t\t\tbreak;\n\n\t\tcase APP_ID.VIDEO:\n\t\t\t// Update GUI elements concerned \n\t\t\t\n\t\t\t// TO DO : simulate click on concerned tab menu\n\t\t\t//$(\"#menu3\").click();\n\t\t\tbreak;\n\t\t\n\t\tcase APP_ID.AUDIO:\n\t\t\t// Update GUI elements concerned \n\t\t\tf_GUI_Update_Select(frame, $(he_SelectRADOMEAudio));\t\n\t\t\t// TO DO : simulate click on concerned tab menu\n\t\t\t//$(\"#menu4\").click();\n\t\t\tbreak;\n\t\t\n\t\tcase APP_ID.NAVIG:\n\t\t\t// Update GUI elements concerned \n\t\t\t// TO DO : simulate click on concerned tab menu\n\t\t\t//$(\"#menu5\").click();\n\t\t\n\t\t\tf_RADOME_log(\"load data json to populate the angular model $scope.RADOME_NavigInfo\");\n\t\t\tf_GUI_Update_Nav(frame);\t\n\t\t\tbreak;\n\n\t\tcase APP_ID.DEMO:\n\t\t\t// load data json to populate the angular model \"$scope.RADOME_DemoInfo\" \n\t\t\tf_RADOME_log(\"load data json to populate the angular model $scope.RADOME_DemoInfo\");\n\t\t\tf_GUI_Update_Demo(frame);\t\n\t\t\tbreak;\t\n\t\t\t\n\t\tdefault:\n\t\t\t// unknown id\n\t\t\tf_RADOME_log(\"Unknown APP ID found : \" + frame.AppID);\n\t\t\tbreak;\n\t}\n}",
"function ClickToPrepareData(dataMemory,dataTemp) {\n sendRequestOrder = document.getElementById(\"sendOrder\");\n sendRequestOrder.addEventListener(\"click\", function(event) {\n event.preventDefault();\n if (controlForm()) {\n var productTab = [];\n let contact = {\n firstName: document.getElementById(\"prénom\").value,\n lastName: document.getElementById(\"nom\").value,\n address: document.getElementById(\"adresse\").value,\n city: document.getElementById(\"ville\").value,\n email: document.getElementById(\"email\").value\n }\n for (let i = 0 ; i < dataMemory.length; i++) {\n let memoryNav = JSON.parse(dataMemory.getItem(dataMemory.key(i)));\n productTab.push(memoryNav._id);\n }\n if (productTab.length > 0) {\n sendDataServer(contact,productTab,dataMemory,dataTemp);\n } else {\n errorView(\"Vous devez choisir au moins un produit pour effectuer une commande!\");\n }\n } \n });\n}",
"sendPushNotification (apiKey, title, message, payload, filter) {\n\n // check if apiKey is string\n if (typeof apiKey != \"string\" || apiKey.length <= 0)\n {\n this.emit(\"error\", new Error(\"No valid API Key given :'\"+ apiKey +\"'\"));\n }\n\n // check if title is string\n if (title != null && (typeof title != \"string\" || title.length <= 0))\n {\n this.emit(\"error\", new Error(\"No valid title given :'\"+ title +\"'\"));\n }\n\n // check if message is string\n if (typeof message != \"string\" || message.length <= 0)\n {\n this.emit(\"error\", new Error(\"No valid message given :'\"+ message +\"'\"));\n }\n\n // check if payload is object\n if (payload != null && typeof payload != \"object\")\n {\n this.emit(\"error\", new Error(\"No valid payload given :'\"+ payload +\"'\"));\n }\n\n // check if filter is object\n if (filter != null && typeof filter != \"object\" && typeof filter != \"array\")\n {\n this.emit(\"error\", new Error(\"No valid filter given :'\"+ filter +\"'\"));\n }\n\n var requestData = {\n \"restKey\": apiKey,\n \"body\": message\n };\n\n if (title != null)\n {\n requestData.title = title\n }\n\n if (payload != null)\n {\n requestData.payload = payload;\n }\n\n if (filter != null)\n {\n requestData.matchFilters = 1;\n requestData.filters = (typeof filter != \"object\") ? [filter] : filter;\n }\n request({\n method: \"POST\",\n url : 'https://push.appfarms.com/api/notifications',\n json : requestData\n })\n .on('response', (response) => {\n this.emit('success', response);\n })\n .on('error', (err) => {\n\n this.emit('error', err);\n });\n }",
"function pushBusinessDev(projectId,businessDevelopment){\n Project.findById(projectId,function(err,proj){\n proj.businessDevelopment.push(businessDevelopment)\n proj.save();\n })\n}",
"function sendData() {\n\n // Get all PID input data and store to right index of charVal\n for(var i = 1; i <= 18; i++) {\n txCharVal[i] = select(inputMap[i]).value;\n }\n\n // Get all control input data and store to right index of exCharVal\n exCharVal[0] = select('#throttle').value;\n\n // Sending PID data with rxChar over BLE\n writeArrayToChar(txChar, txCharVal)\n .then( () => {\n console.log(\"PID data sent:\", txCharVal);\n\n // Sending throttle data with exChar over BLE\n writeArrayToChar(exChar, exCharVal)\n .then( () => {\n console.log(\"Data sent:\", exCharVal);\n })\n .catch( (error) => {\n console.log('Control data sending failed:', error)\n });\n })\n .catch( (error) => {\n console.log('PID data sending failed:', error)\n });\n}",
"function otpAddDataSave(event, addOtpData, config, client) {\n //console.log(addFormOtp);\n delete addOtpData.province;\n delete addOtpData.Tehsil;\n delete addOtpData.district;\n delete addOtpData.province;\n delete addOtpData.ddHealthHouseOTP;\n delete addOtpData.uc;\n addOtpData.client_id = client;\n addOtpData.username = config.usernameL;\n addOtpData.org_name = config.org_nameL;\n addOtpData.project_name = config.project_nameL;\n const addFormOtp = addOtpData;\n console.log(addFormOtp);\n knex('tblOtpAdd')\n .insert(addFormOtp)\n .then(result => {\n console.log(result + 'OTP addmision added')\n sucMsg(event, '', 'OTP admission added successfully')\n // addOtp.webContents.send(\"resultSentOtpAdd\", {\n // 'msg': 'records added'\n // });\n var interimData = {\n otp_id: addOtpData.otp_id,\n interim_id: _uuid(),\n client_id: imran.client,\n muac: addFormOtp.muac,\n weight: addFormOtp.weight,\n ration1: addFormOtp.ration1,\n quantity1: addFormOtp.quantity1,\n ration2: (addFormOtp.ration2 ? addFormOtp.ration2 : ''),\n quantity2: addFormOtp.quantity2,\n ration3: (addFormOtp.ration3 ? addFormOtp.ration3 : ''),\n quantity3: addFormOtp.quantity3,\n curr_date: localDate(),\n created_at: localDate(),\n status: 'open',\n next_followup: function () {\n var myDate = new Date(addOtpData.reg_date);\n myDate.setDate(myDate.getDate() + (addOtpData.prog_type == 'sfp' ? 14 : 7))\n return toJSONLocal(myDate)\n }()\n }\n console.log(interimData)\n return knex('tblInterimOtp')\n .insert(interimData)\n })\n .then(result => {\n console.log('interim ID: ', result);\n })\n .catch(e => {\n console.log(e)\n console.log(e + 'OTP add error');\n errMsg(event, '', 'OTP Addmision not added, plz try again or contact admin');\n // addOtp.webContents.send(\"resultSentOtpAdd\", {\n // 'err': 'records not added, plz try again'\n // });\n })\n // addFormOtp = null;\n}",
"function addCardAppData(e) {\n\n// const listId =e.target.closest('.oneLists').getAttribute('data-id');\n\n // const listInAppData2 = appData.lists.board.find((list)=> listId === list.id);\n\n //\n // const cardOfAppData = {\n // members: [],\n // text: 'Add new task',\n // id: newCard.getAttribute(\"data-id\"),\n // }\n // listInAppData2.tasks.push(cardOfAppData);\n\n const title = e.target.closest('.oneLists').querySelector('.tagText').textContent\n const id =e.target.closest('.oneLists').getAttribute('data-id');\n\n const listInAppData =returnListReference(id)\n // appData.lists.board.find((bord) => id === bord.id)\n const cardId= e.target.closest('.oneLists').querySelector('.ulForCards li:last-child');\n\n const cardOfAppData = {\n members: [],\n text: 'Add new task',\n id: cardId.getAttribute('data-id'),\n }\n listInAppData.tasks.push(cardOfAppData)\n //pushnigNewCard(listInAppData, cardId);\n\n}",
"function sendDataToPersist() {\n let inputs = memeForm.getElementsByTagName(\"input\");\n let inputname = inputs[\"name\"].value;\n log(\"inputname => \" + inputname);\n if (inputname === \"\") {\n log(\"makePatchRequest\");\n makePatchRequest(inputs);\n } else {\n log(\"makePostRequest\");\n makePostRequest(inputs);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
inverse of the circlePath function, returns a circle object from an svg path | function circleFromPath(path) {
var tokens = path.split(' ');
return { 'x': parseFloat(tokens[1]),
'y': parseFloat(tokens[2]),
'radius': -parseFloat(tokens[4])
};
} | [
"function createSvg(path){\n const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n const pathElement = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n\n attrDict(svg, {\n 'class':'svg-icon',\n 'viewBox': '0 0 20 20'\n })\n\n attrDict(pathElement,{\n 'fill': 'none',\n 'd': path\n })\n svg.appendChild(pathElement);\n return svg;\n}",
"static getPath(shape) {\n throw Error('Not Implemented');\n if (this instanceof circle_js_1.default) {\n throw Error('Not Implemented');\n }\n else if (this instanceof ellipse_js_1.default) {\n throw Error('Not Implemented');\n }\n else if (this instanceof line_js_1.default) {\n throw Error('Not Implemented');\n }\n else if (this instanceof Path) {\n throw Error('Not Implemented');\n }\n else if (this instanceof rectangle_js_1.default) {\n throw Error('Not Implemented');\n }\n }",
"function path() {\n \"use strict\";\n var ret = { animate: \"path\",\n path: null,\n forward: [1, 0, 0],\n delay: 0,\n duration: 0,\n alpha: \"linear\"};\n\n ret.path = arguments[0]; // path\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\n if( arguments.length > 3 ) { // optional\n ret.alpha = arguments[3];\n }\n return ret;\n}",
"get CircleEdge() {}",
"getBoundingCircle() {\n const center = this.getCenter();\n\n const radius = _.chain(this.vertices)\n .map(vertex => new Vector(vertex, center).getLength())\n .max()\n .value();\n\n return new Circle(center, radius);\n }",
"function circle(annotation) {\n const element = rectangle(annotation);\n element.type = 'circle';\n element.radius = Math.max(element.width, element.height) / 2;\n delete element.width;\n delete element.height;\n delete element.rotation;\n delete element.normal;\n return element;\n}",
"removeCircle(circle) {\n return this._circles.get(circle).then(c => {\n c.setMap(null);\n\n this._circles.delete(circle);\n });\n }",
"function createDGCircle() {\r\n dailyCircle = loadCircle(\"#daily-goal-completion\");\r\n}",
"renderCircle() {\r\n\t\tconst x = this.ranges.x(this.data[this.data.length - 1].date);\r\n\t\tconst y = this.ranges.y(this.data[this.data.length - 1].value);\r\n\r\n\t\tthis.point = this.svg.select('.circle')\r\n\t\t\t.interrupt()\r\n\t\t\t.transition()\r\n\t\t\t\t.duration(this.numberGeneratorOptions.interval * 2.5)\r\n\t\t\t\t.attr('transform', `translate(${x}, ${y})`);\r\n\t}",
"function intersectionAreaPath(circles) {\n\t var stats = {};\n\t intersectionArea(circles, stats);\n\t var arcs = stats.arcs;\n\n\t if (arcs.length === 0) {\n\t return \"M 0 0\";\n\t } else if (arcs.length == 1) {\n\t var circle = arcs[0].circle;\n\t return circlePath(circle.x, circle.y, circle.radius);\n\t } else {\n\t // draw path around arcs\n\t var ret = [\"\\nM\", arcs[0].p2.x, arcs[0].p2.y];\n\t for (var i = 0; i < arcs.length; ++i) {\n\t var arc = arcs[i],\n\t r = arc.circle.radius,\n\t wide = arc.width > r;\n\t ret.push(\"\\nA\", r, r, 0, wide ? 1 : 0, 1, arc.p1.x, arc.p1.y);\n\t }\n\t return ret.join(\" \");\n\t }\n\t }",
"function strokedCircle(ctx, x, y, radius) {\r\n ctx.beginPath();\r\n ctx.arc(x, y, radius, 0, 2 * Math.PI, false);\r\n ctx.stroke();\r\n }",
"function pathSolver(path) {\n return path;\n}",
"getCopy() {\n var copyCenter = copyPoints([this.center])[0];\n return new Circle(copyCenter, this.radius);\n }",
"function tangent_circle_center_internal(angle, r0, r1, r2) {\n var x = r2 * (r0 + r1) / (r0 - r1);\n var y = 2*Math.sqrt(r0*r1*r2*(r0-r1-r2)) / (r0-r1);\n\n // translate to rotation coordinate system\n x -= r0;\n\n // rotate\n var rotx = Snap.cos(angle)*x - Snap.sin(angle)*y;\n var roty = Snap.sin(angle)*x + Snap.cos(angle)*y;\n\n // translate back to our coordinate system\n rotx += r0;\n roty += r0;\n\n return [rotx, roty];\n}",
"function loadCircle(element) {\r\n let circle = new ProgressBar.Circle(element, {\r\n color: mainColor,\r\n // This has to be the same size as the maximum width to\r\n // prevent clipping\r\n strokeWidth: 4,\r\n trailWidth: 1,\r\n easing: 'easeInOut',\r\n duration: 1400,\r\n from: {color: '#aaa', width: 2},\r\n to: {color: mainColor, width: 3},\r\n // Set default step function for all animate calls\r\n step: function (state, circle) {\r\n circle.path.setAttribute('stroke', state.color);\r\n circle.path.setAttribute('stroke-width', state.width);\r\n }\r\n });\r\n //make sure only go through circle once\r\n return circle;\r\n}",
"path(x, y) {\n stroke(116, 122, 117);\n strokeWeight(4);\n fill(147, 153, 148);\n for (let i = 0; i < 2; i++) {\n for (let j = 0; j < 2; j++) {\n rect(x - this.pxl * i, y + this.pxl * j, this.pxl, this.pxl);\n }\n }\n }",
"function _getSVGPath(coord, options) {\n let path\n , subpath\n , x\n , y\n , i\n , j\n ;\n\n path = '';\n for (i = 0; i < coord.length; i++) {\n subpath = '';\n for (j = 0; j < coord[i].length; j++) {\n [x, y] = _transform(coord[i][j], options);\n if (subpath === '') {\n subpath = `M${x},${y}`;\n } else {\n subpath += `L${x},${y}`;\n }\n }\n subpath += 'z';\n path += subpath;\n }\n return path;\n }",
"ellipse(x, y, rx, ry, ccw) {\n if (!path) {\n path = '<path d=\"';\n }\n var dx = rx * ELLIPSE_MAGIC;\n var dy = ry * ELLIPSE_MAGIC;\n\n // Since we fill with even-odd, don't worry about cw/ccw\n path += 'M' + transform(x - rx, y) +\n 'C' + transform(x - rx, y - dy) + ' ' +\n transform(x - dx, y - ry) + ' ' +\n transform(x, y - ry) +\n 'C' + transform(x + dx, y - ry) + ' ' +\n transform(x + rx, y - dy) + ' ' +\n transform(x + rx, y) +\n 'C' + transform(x + rx, y + dy) + ' ' +\n transform(x + dx, y + ry) + ' ' +\n transform(x, y + ry) +\n 'C' + transform(x - dx, y + ry) + ' ' +\n transform(x - rx, y + dy) + ' ' +\n transform(x - rx, y) +\n 'Z';\n }",
"function svg_path_to_string(path) {\n var str = '';\n for (var i = 0, n = path.length; i < n; i++) {\n var point = path[i];\n if (point[0] !== 'Z') {\n str += point[0] + point[1] + ',' + point[2];\n } else {\n str += 'Z';\n }\n }\n return str;\n }",
"function renderCircles(svgCircles, newXScale, InitialXAxis, newYScale, InitialYAxis) {\n svgCircles.transition()\n .duration(500)\n .attr(\"cx\", d => newXScale(d[InitialXAxis]))\n .attr(\"cy\", d => newYScale(d[InitialYAxis]));\n return svgCircles;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes a uint24 to a buffer starting at the given offset, returning the offset of the next byte. | function writeUInt24BE(
buffer,
value,
offset
) {
offset = buffer.writeUInt8(value >>> 16, offset); // 3rd byte
offset = buffer.writeUInt8(value >>> 8 & 0xff, offset); // 2nd byte
return buffer.writeUInt8(value & 0xff, offset); // 1st byte
} | [
"static uint24(v) { return n(v, 24); }",
"static bytes24(v) { return b(v, 24); }",
"function shift (buffer, offset) {\r\n validate(buffer);\r\n\r\n for (var channel = 0; channel < buffer.numberOfChannels; channel++) {\r\n var cData = buffer.getChannelData(channel);\r\n if (offset > 0) {\r\n for (var i = cData.length - offset; i--;) {\r\n cData[i + offset] = cData[i];\r\n }\r\n }\r\n else {\r\n for (var i = -offset, l = cData.length - offset; i < l; i++) {\r\n cData[i + offset] = cData[i] || 0;\r\n }\r\n }\r\n }\r\n\r\n return buffer;\r\n}",
"function LEW(arr, off) {\n return arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000\n | arr[off+1]<<8&0xff00 | arr[off]&0xFF;\n } // end of LEW",
"static bytes23(v) { return b(v, 23); }",
"static int24(v) { return n(v, -24); }",
"static bytes21(v) { return b(v, 21); }",
"function indcpaUnpackPrivateKey(packedPrivateKey, paramsK) {\r\n return polyvecFromBytes(packedPrivateKey, paramsK);\r\n}",
"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 }",
"function getBoardCoordFromQuadOffset(quadX, quadY, offset) {\n return (quadX * 3 + Math.floor(offset / 3)) * boardSize + (quadY * 3 + offset % 3);\n}",
"next () {\n // Wrap cursor to the beginning of the next non-empty buffer if at the\n // end of the current buffer\n while (this.buffer_i < this.buffers.length &&\n this.offset >= this.buffers[this.buffer_i].length) {\n this.offset = 0;\n this.buffer_i ++;\n }\n\n if (this.buffer_i < this.buffers.length) {\n let byte = this.buffers[this.buffer_i][this.offset];\n\n // Advance cursor\n this.offset++;\n return byte;\n }\n else {\n throw this.END_OF_DATA;\n }\n }",
"static uint240(v) { return n(v, 240); }",
"browser_timezone_offset(minute_offset) {\n const offset_string = (minute_offset / -60).toString()\n\n var sign;\n var hours;\n\n if (offset_string.includes(\".\")) {\n throw \"Critter4Us doesn't work in timezones a fractional hour away from UTC\";\n }\n\n if (offset_string.slice(0, 1) == \"-\") {\n sign = \"-\";\n hours = offset_string.slice(1);\n } else {\n sign = \"+\";\n hours = offset_string;\n }\n\n if (hours.length == 1) {\n hours = \"0\" + hours;\n }\n\n return sign + hours + \":00\";\n }",
"function findMarker(buf, pos) {\n for (var i = pos; i < buf.length; i++) {\n if (0xff === buf[i ] &&\n 0xe1 === buf[i+1]) {\n return i;\n }\n }\n return -1;\n }",
"readUint16() {\n const value = this._data.getUint16(this.offset, this.littleEndian);\n\n this.offset += 2;\n return value;\n }",
"function BufferView(buffer, offset, length, byteorder) {\n if (arguments.length < 2 || arguments.length > 4) \n fail(\"Wrong number of argments\");\n if (arguments.length === 2) {\n byteorder = offset;\n offset = 0;\n length = buffer.byteLength;\n }\n else if (arguments.length === 3) {\n byteorder = length;\n length = buffer.byteLength - offset;\n }\n \n // XXX Should I support binary strings as well as Array buffers?\n // jDataView does that\n if (!(buffer instanceof ArrayBuffer))\n fail(\"Bad ArrayBuffer\");\n\n // XXX Should negative offsets be measured from the end of the buffer?\n if (offset < 0 || offset > buffer.byteLength)\n fail(\"Illegal offset\");\n if (length < 0 || offset+length > buffer.byteLength)\n fail(\"Illegal length\");\n if (byteorder !== BufferView.LE && byteorder !== BufferView.BE)\n fail(\"Bad byte order\");\n\n // Note that most of these properties are read-only\n Object.defineProperties(this, {\n buffer: { // ArrayBufferView defines this property\n value: buffer,\n enumerable:false, writable: false, configurable: false\n },\n byteOffset: { // ArrayBufferView defines this property\n value: offset,\n enumerable:false, writable: false, configurable: false\n },\n byteLength: { // ArrayBufferView defines this property\n value: length,\n enumerable:false, writable: false, configurable: false\n },\n byteOrder: { // New public read-only property of this type\n value: byteorder,\n enumerable:true, writable: false, configurable: false\n },\n index: { // Public getter/setter for the buffer offset\n get: function() { return this._index; },\n set: function(x) {\n if (x < 0) fail(\"negative index\");\n if (x > this.byteLength) \n fail(\"buffer overflow: index too large\");\n this._index = x;\n },\n enumerable: true, configurable: false\n },\n _index: { // non-public property holds actual offset value\n value: 0,\n enumerable: false, writable: true, configurable: true\n },\n _bytes: { // Raw bytes, non-public\n value: new Uint8Array(buffer, offset, length),\n enumerable:false, writable: false, configurable: false\n },\n _view: { // non-public DataView for getting/setting numbers\n value: new DataView(buffer, offset, length),\n enumerable:false, writable: false, configurable: false\n }\n });\n }",
"static bytes16(v) { return b(v, 16); }",
"offsetOf(variable, index) {\n const slot = this.getLocalDepth(variable);\n const depth = this.getMemoryOffset(slot);\n const size = this.sizeOfVal(variable);\n\n if (this.stackTop().size != 1) {\n this.error(\n \"Cannot assign value larger than 1 byte to bus or string index.\"\n );\n } else if (size != 1) {\n this.error(\"cannot index a variable that is not a bus or string.\");\n }\n\n return depth + index + 2; // account for 2 bytes of padding prior.\n }",
"function getDay(offset) {\n var d = new Date();\n return new Date(d.setDate(d.getDate() + offset)).setHours(0,0,0,0);\n}",
"function offsetToPoint(offset) {\n var index = -1\n var length = indices.length\n\n if (offset < 0) {\n return {}\n }\n\n while (++index < length) {\n if (indices[index] > offset) {\n return {\n line: index + 1,\n column: offset - (indices[index - 1] || 0) + 1,\n offset: offset\n }\n }\n }\n\n return {}\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function adds Heavy Cover number for H_W&F by 1 | function countHcoverHwfPlus() {
instantObj.noOfHcoverHWF = instantObj.noOfHcoverHWF + 1;
countTotalBill();
} | [
"function countHcoverHwfMinus() {\n\t\t\tif(instantObj.noOfHcoverHWF > 0) {\n\t\t\t\tinstantObj.noOfHcoverHWF = instantObj.noOfHcoverHWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}",
"function countHcoverHwiPlus() {\n\t\t\tinstantObj.noOfHcoverHWI = instantObj.noOfHcoverHWI + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function countHcoverHwiMinus() {\n\t\t\tif(instantObj.noOfHcoverHWI > 0) {\n\t\t\t\tinstantObj.noOfHcoverHWI = instantObj.noOfHcoverHWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}",
"function countLcoverHwiPlus() {\n\t\t\tinstantObj.noOfLcoverHWI = instantObj.noOfLcoverHWI + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function criticalCoverHeight (firebrandHt, appliedDownWindCoverHeight) {\n const criticalHt = firebrandHt > 0 ? 2.2 * Math.pow(firebrandHt, 0.337) - 4 : 0\n return Math.max(appliedDownWindCoverHeight, criticalHt)\n}",
"function nm2rgb(h) {\n var wavelength = 380 + h * 400;\n var Gamma = 0.80,\n IntensityMax = 255,\n factor, red, green, blue;\n\n if((wavelength >= 380) && (wavelength < 440)) {\n red = -(wavelength - 440) / (440 - 380);\n green = 0.0;\n blue = 1.0;\n } else if((wavelength >= 440) && (wavelength < 490)) {\n red = 0.0;\n green = (wavelength - 440) / (490 - 440);\n blue = 1.0;\n } else if((wavelength >= 490) && (wavelength < 510)) {\n red = 0.0;\n green = 1.0;\n blue = -(wavelength - 510) / (510 - 490);\n } else if((wavelength >= 510) && (wavelength < 580)) {\n red = (wavelength - 510) / (580 - 510);\n green = 1.0;\n blue = 0.0;\n } else if((wavelength >= 580) && (wavelength < 645)) {\n red = 1.0;\n green = -(wavelength - 645) / (645 - 580);\n blue = 0.0;\n } else if((wavelength >= 645) && (wavelength < 781)) {\n red = 1.0;\n green = 0.0;\n blue = 0.0;\n } else {\n red = 0.0;\n green = 0.0;\n blue = 0.0;\n };\n\n // Let the intensity fall off near the vision limits\n\n if((wavelength >= 380) && (wavelength < 420)){\n factor = 0.3 + 0.7*(wavelength - 380) / (420 - 380);\n } else if((wavelength >= 420) && (wavelength < 701)){\n factor = 1.0;\n } else if((wavelength >= 701) && (wavelength < 781)){\n factor = 0.3 + 0.7*(780 - wavelength) / (780 - 700);\n } else{\n factor = 0.0;\n };\n\n if(red !== 0){\n red = Math.round(IntensityMax * Math.pow(red * factor, Gamma));\n }\n if(green !== 0){\n green = Math.round(IntensityMax * Math.pow(green * factor, Gamma));\n }\n if(blue !== 0){\n blue = Math.round(IntensityMax * Math.pow(blue * factor, Gamma));\n }\n\n return {\n r: red,\n g: green,\n b: blue,\n a: 255\n };\n }",
"function countHandTowelHwfPlus() {\n\t\t\tinstantObj.noOfHandTowelHWF = instantObj.noOfHandTowelHWF + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function renderHeightMarker() {\n var hrfy = canvas.height - yValFromPct( highestRedFlowerPct ); // highest red flower y value currently\n var chmp = 100-pctFromYVal(HeightMarker.y); // current height marker percentage\n if ( Math.floor( highestRedFlowerPct ) > Math.floor(chmp) ) { // initializes animations if new highest red flower\n HeightMarker.y = hrfy; // y value\n HeightMarker.baa = true; // bounce animation active\n HeightMarker.bat = 0; // bounce animation time elapsed\n HeightMarker.laa = true; // line animation active\n HeightMarker.lat = 0; // line animation time elapsed\n $(\"#height_number\").text( Math.floor( highestRedFlowerPct ) );\n renderHeightAnnouncement();\n }\n //new highest height marker bounce animation (size expansion & contraction)\n if ( HeightMarker.baa ) { \n HeightMarker.bat++;\n var a = -0.12; // corresponds to animation duration ( higher value is longer duration; 0 is infinite)\n var b = 2; // extent of expansion ( higher value is greater expansion )\n var x = HeightMarker.bat; \n var y = a*Math.pow(x,2) + b*x; // current marker expansion extent (quadratic formula; y = ax^2 + bx + c)\n HeightMarker.w = canvas.width*0.025 + y;\n if ( y <= 0 ) { HeightMarker.baa = false; HeightMarker.bat = 0; }\n }\n //new highest height line animation\n if ( HeightMarker.laa ) { \n HeightMarker.lat++;\n var lad = 40; // line animation duration\n var o = 1 - HeightMarker.lat/lad; // opacity\n ctx.beginPath();\n ctx.lineWidth = 2;\n var lGrad = ctx.createLinearGradient( HeightMarker.chrfx-canvas.width, HeightMarker.y, HeightMarker.chrfx+canvas.width, HeightMarker.y );\n lGrad.addColorStop(\"0\", \"rgba( 161, 0, 0, 0 )\");\n lGrad.addColorStop(\"0.4\", \"rgba( 161, 0, 0, \" + 0.3*o + \")\");\n lGrad.addColorStop(\"0.5\", \"rgba( 161, 0, 0, \" + 1*o + \")\");\n lGrad.addColorStop(\"0.6\", \"rgba( 161, 0, 0, \" +0.3*o + \")\");\n lGrad.addColorStop(\"1\", \"rgba( 161, 0, 0, 0 )\");\n ctx.strokeStyle = lGrad;\n ctx.moveTo( HeightMarker.chrfx-canvas.width, HeightMarker.y );\n ctx.lineTo( HeightMarker.chrfx+canvas.width, HeightMarker.y );\n ctx.stroke();\n if ( HeightMarker.lat > lad ) { HeightMarker.laa = false; HeightMarker.lat = 0; }\n }\n //draws marker\n if ( highestRedFlowerPct > 0 ) { \n ctx.beginPath(); // top triangle\n ctx.fillStyle = \"#D32100\";\n ctx.moveTo( canvas.width, HeightMarker.y ); \n ctx.lineTo( canvas.width, HeightMarker.y - HeightMarker.h/2 ); \n ctx.lineTo( canvas.width-HeightMarker.w, HeightMarker.y ); \n ctx.fill(); \n ctx.beginPath(); // bottom triangle\n ctx.fillStyle = \"#A10000\";\n ctx.moveTo( canvas.width, HeightMarker.y ); \n ctx.lineTo( canvas.width, HeightMarker.y + HeightMarker.h/2 ); \n ctx.lineTo( canvas.width-HeightMarker.w, HeightMarker.y ); \n ctx.fill();\n }\n}",
"function heatOfPreignition (mc, efhn) {\n const qig = 250.0 + 1116.0 * mc\n return qig * efhn\n}",
"function countHandTowelHwfMinus() {\n\t\t\tif(instantObj.noOfHandTowelHWF > 0) {\n\t\t\t\tinstantObj.noOfHandTowelHWF = instantObj.noOfHandTowelHWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}",
"set smoothness(value) {}",
"function redHue() {\n for (var pixel of image.values()) {\n var avg =\n (pixel.getRed() + pixel.getGreen() + pixel.getBlue()) /3;\n if (avg < 128){\n pixel.setRed(2 * avg);\n pixel.setGreen(0);\n pixel.setBlue(0);\n } else {\n pixel.setRed(255);\n pixel.setGreen(2 * avg - 255);\n pixel.setBlue(2 * avg - 255);\n }\n }\n var c2 = document.getElementById(\"c2\");\n var image2 = image;\n image2.drawTo(c2);\n \n \n}",
"get smoothness() {}",
"function generateSH(hdrImageData, width, height, onComplete, onProgress, options) {\n\t // TODO: Implement as a worker instead of using green threading\n\t options = options || {};\n\t if (options.irradiance === undefined)\n\t options.irradiance = true;\n\t var f32data = hdrImageData instanceof Uint8ClampedArray ? convertToFloats(hdrImageData) : hdrImageData;\n\t var sh = [];\n\t for (var i = 0; i < 9; ++i)\n\t sh[i] = { r: 0, g: 0, b: 0 };\n\t doPart(sh, f32data, width, height, onComplete, onProgress, options, 0, 0);\n\t}",
"ADDHL() {\n const a = regA[0];\n const m = MMU.rb(regHL[0]);\n regA[0] += m;\n regF[0] = (regA[0] < a) ? F_CARRY : 0;\n if (!regA[0]) regF[0] |= F_ZERO;\n if ((regA[0] ^ a ^ m) & 0x10) regF[0] |= F_HCARRY;\n return 8;\n }",
"function drawWaveAndIntensitySS() {\n\tlet canvas = document.getElementById(\"diffraction\");\n\tlet ctx = canvas.getContext(\"2d\");\n\n\tlet alpha, I, sin, b, c;\n\tlet lambda = Number(parseFloat(document.form.lambda.value));\n\tlet colours = wavelengthToColor(lambda);\n\tlet screen = Number(parseFloat(document.form.L.value));\n\n\tlet gap = Number(parseFloat(document.form.gap.value));\n\n\tctx.fillStyle = colours[0];\n\tctx.strokeStyle = colours[0];\n\n\tctx.beginPath();\n\tctx.moveTo(570, 150);\n\tc = 1.5 + (screen * 2 - 100) * 0.5 / 50.;\n\n\tfor (i = 150; i >= 0; i--) {\n\t\tb = 0.18 * (1 - (i - 10) / 140.);\n\t\tsin = b / Math.sqrt(Math.pow(b, 2) + Math.pow(c, 2));\n\t\talpha = sin * Math.PI * gap * 500. / lambda;\n\t\tI = Math.pow(Math.sin(alpha) / alpha, 2);\n\t\tctx.lineTo(sinToCoords(I), i);\n\t\tI = Math.pow(I, 1 / 2);\n\t\tctx.fillStyle = rgbToHex(Math.round(colours[1] * I), Math.round(colours[2] * I), Math.round(colours[3] * I));\n\t\tctx.fillRect(383, i, 57, 1);\n\n\t}\n\n\tctx.stroke();\n\tctx.beginPath();\n\tctx.moveTo(570, 150);\n\n\tfor (i = 149; i <= 300; i++) {\n\t\tb = 0.18 * (1 - (i - 10) / 140.);\n\t\tsin = b / Math.sqrt(Math.pow(b, 2) + Math.pow(c, 2));\n\t\talpha = sin * Math.PI * gap * 500. / lambda;\n\t\tI = Math.pow(Math.sin(alpha) / alpha, 2);\n\n\t\tctx.lineTo(sinToCoords(I), i);\n\t\tI = Math.pow(I, 1 / 2);\n\t\tctx.fillStyle = rgbToHex(Math.round(colours[1] * I), Math.round(colours[2] * I), Math.round(colours[3] * I));\n\t\tctx.fillRect(383, i, 57, 1);\n\t}\n\n\tctx.stroke();\n\tlambda /= 100;\n\tctx.fillStyle = colours[0];\n\n\tfor (i = 4; i < 250 - screen * 2 - 1; i += 8 * lambda)\n\t\tctx.fillRect(i, 100, 2, 100);\n\n\tfor (i = 20; i < 280 - (75 - screen) * 2; i += 8 * lambda) {\n\t\tctx.beginPath();\n\t\tctx.arc(250 - screen * 2, 150 - gap, i, 1.75 * Math.PI, 0.25 * Math.PI);\n\t\tctx.stroke();\n\t\tctx.beginPath();\n\t\tctx.arc(250 - screen * 2, 150 + gap, i, 1.75 * Math.PI, 0.25 * Math.PI);\n\t\tctx.stroke();\n\t}\n}",
"function burningPileFirebrandHeight (flameHt) {\n return Math.max(0.0, 12.2 * flameHt)\n}",
"updateThreshold() {\n\n if (this.suppressed == null) {\n return;\n }\n\n // Do double threshold\n const context = this.canvas.getContext('2d');\n let imgData = context.getImageData(0, 0, 200, 200);\n\n let temp = new Array2D([...this.suppressed.data], this.suppressed.width, this.suppressed.height, this.suppressed.channels);\n\n doubleThreshold(temp, this.state.hiThreshold, this.state.loThreshold);\n fillArray(imgData.data, temp.data, imgData.data.length);\n context.putImageData(imgData, 0, 0);\n }",
"function imgCoverEffect(a,b){\"use strict\";function c(){if(b.watchResize===!0&&requestAnimationFrame(c),j||(j=k?a.width/a.height:a.naturalWidth/a.naturalHeight),g=d.clientWidth,h=d.clientHeight,i=g/h,g!==e||h!==f){if(i>=j?(a.width=g,a.height=a.width/j):(a.width=h*j,a.height=h),e=g,f=h,\"left\"===String(b.alignX).toLowerCase())a.style.left=0;else if(\"center\"===String(b.alignX).toLowerCase())a.style.left=(g-a.width)/2+\"px\";else{if(\"right\"!==String(b.alignX).toLowerCase())throw new Error('From imgCoverEffect(): Unsupported horizontal align value. Property \"alignX\" can only be set to one of the following values: \"left\", \"center\", or \"right\".');a.style.left=g-a.width+\"px\"}if(\"top\"===String(b.alignY).toLowerCase())a.style.top=0;else if(\"center\"===String(b.alignY).toLowerCase())a.style.top=(h-a.height)/2+\"px\";else{if(\"bottom\"!==String(b.alignY).toLowerCase())throw new Error('From imgCoverEffect(): Unsupported vertical align value. Property \"alignY\" can only be set to one of the following values: \"top\", \"center\", or \"bottom\".');a.style.top=h-a.height+\"px\"}}}if(b.watchResize=b.watchResize!==!1,b.alignX=b.alignX||\"left\",b.alignY=b.alignY||\"top\",\"boolean\"!=typeof b.watchResize)throw new Error('From imgCoverEffect(): \"watchResize\" property must be set to a Boolean when the option is specified.');if(!a.parentNode)throw new Error(\"From imgCoverEffect(): passed HTMLImageElement has no parent DOM element.\");var d=a.parentNode,e=0,f=0,g=0,h=0,i=0,j=0,k=void 0===a.naturalWidth;d.style.overflow=\"hidden\",d.style.position=\"relative\",a.style.position=\"absolute\",a.style.top=0,a.style.left=0,a.style.zIndex=-1,!k&&a.naturalWidth&&a.naturalHeight||k&&a.width&&a.height?c():a.addEventListener?a.addEventListener(\"load\",c,!1):a.attachEvent&&a.attachEvent(\"onload\",c)}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return whether or not the current odk json file exists | function odk_json_exists(filename, callback) {
read_git_release_data(REGION_FS_STORAGE, function(files) {
res = false
_.each(files, function(f, i) {
if (basename(f) + ".json" == filename) {
res = true
return
}
});
callback(res)
});
} | [
"fileExists() {\n return fs.pathExists(this.location);\n }",
"exists(objectHash) {\n return objectHash !== undefined\n && fs.existsSync(nodePath.join(Files.gitletPath(), 'objects', objectHash));\n }",
"async ensureExists() {\n if (await this.fileExists()) {\n return;\n }\n await fs.writeJSON(this.location, this.defaults);\n }",
"isInitable() {\n try {\n fs.accessSync(CONFIG_FILE_PATH, fs.constants.F_OK);\n return false;\n } catch (err) {\n return true;\n }\n }",
"function exists(file) {\n\treturn fs.existsSync(file) && file;\n}",
"isValid() {\n try {\n fs.accessSync(CONFIG_FILE_PATH, fs.constants.R_OK | fs.constants.W_OK);\n return true;\n } catch (err) {\n return false;\n }\n }",
"function fileExistInNpm(filePath) {\n return existsSync(path.resolve(__dirname, '../../', filePath));\n}",
"async _AssetExists(ctx, id) {\n const assetJSON = await ctx.stub.getState(id);\n return assetJSON && assetJSON.length > 0;\n }",
"isDirExists() {\t\n\t\ttry\t{\n\t\t\tfs.statSync(this.options.dir);\n\t\t} catch(e) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}",
"function check_file_exist(file){\n\tvar http = new XMLHttpRequest();\n\thttp.open('HEAD',file,false);\n\thttp.send();\n\treturn http.status == 404;\n}",
"function manifestExists() {\n return fs.existsSync(testManifestPath);\n}",
"function tlds() {\n // reading as file will make sure that we read new file upon package renewal\n try {\n return JSON.parse(fs.readFileSync(json_path,'utf8'))\n }catch(err) {}\n return false\n}",
"async exists() {\n return $(this.rootElement).isExisting();\n }",
"function getLockFileExists () {\n const result = {};\n const cwd = process.cwd();\n if (!fs.existsSync(path.join(cwd, 'package.json'))) {\n return result;\n }\n if (fs.existsSync(path.join(cwd, 'yarn.lock'))) {\n result.yarn = true;\n }\n if (fs.existsSync(path.join(cwd, 'package-lock.json'))\n || fs.existsSync(path.join(cwd, 'npm-shrinkwrap.json'))\n ) {\n result.npm = true;\n }\n return result;\n}",
"hasLoadedAnyDataFiles() {\n return this.loadedDataFiles.length > 0;\n }",
"hasLoadedDataFile(fileName) {\n return this.loadedDataFiles.indexOf(fileName) >= 0;\n }",
"function hasPkgEsnext(filepath) {\n const pkgRoot = findRoot(filepath)\n const packageJsonPath = resolve(pkgRoot, 'package.json')\n const packageJsonText = readFileSync(packageJsonPath, { encoding: 'utf-8' })\n const packageJson = JSON.parse(packageJsonText)\n return {}.hasOwnProperty.call(packageJson, PROPKEY_ESNEXT) // (A)\n}",
"loadEnvironmentInfo() {\n let infoPath = path.join(this.projectFolder, \"envInfo.json\");\n if (this.utils.fileExists(infoPath)) {\n return this.utils.readJsonFile(infoPath);\n }\n return null;\n }",
"function existsInDictionary(key){\n if(contents[key] == undefined)\n return false;\n return true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
$commentsMobile is an array of dom elements. commentsMobile[0] && [3] is HEADER commentsMobile[1] && [4] is CONTAINER commentsMobile[2] && [5] is COMMENT BUTTON | function commentsMobile (ev) {
var v = require('./comments_events_vars')
if ($(ev.target).attr('class').indexOf('disagree') !== -1) {
if (disagreeOpened === false || disagreeOpened === undefined) {
$(v.commentsMobile[3]).css('display', 'flex')
$(v.commentsMobile[4]).css('display', 'block')
$(v.commentsMobile[5]).css('display', 'flex')
disagreeOpened = true
} else {
$(v.commentsMobile[3]).css('display', 'none')
$(v.commentsMobile[4]).css('display', 'none')
$(v.commentsMobile[5]).css('display', 'none')
disagreeOpened = false
}
} else {
if (agreeOpened === false || agreeOpened === undefined) {
$(v.commentsMobile[0]).css('display', 'flex')
$(v.commentsMobile[1]).css('display', 'block')
$(v.commentsMobile[2]).css('display', 'flex')
agreeOpened = true
} else {
$(v.commentsMobile[0]).css('display', 'none')
$(v.commentsMobile[1]).css('display', 'none')
$(v.commentsMobile[2]).css('display', 'none')
agreeOpened = false
}
}
} | [
"function initComments() {\n const $comments = $('.comment-item');\n $comments.each((ind, comment) => {\n const $comment = $(comment);\n initComment($comment);\n });\n }",
"parseComments(comments) {\n\t\tconst newComments = [];\n\t\tcomments.forEach((c) => {\n\t\t\tconst tagRegex = /\\[tag=([a-zA-Z ]+)\\]/gi;\n\t\t\tconst userRegex = /\\[to=([a-zA-Z ]+)\\]/gi;\n\t\t\tconst newComment = { ...c };\n\t\t\tnewComment.body = newComment.body.replace(tagRegex, '<b>#$1</b>');\n\t\t\tnewComment.body = newComment.body.replace(userRegex, '<i><b>$1</b></i>')\n\t\t\tnewComments.push(newComment);\n\t\t});\n\t\treturn newComments;\n\t}",
"newCommentDomAvatar(comment){\n return (`<li class=\"comment-list-element\" id=\"comment-${comment._id}\"> \n\n <div class=\"the-comment\">\n \n <div class=\"commentor-dp\">\n <img src=\"${comment.user.avatar }\" alt=\"${ comment.user.name }\">\n \n </div>\n \n <div class=\"comment-content\">\n <div class=\"commentor-name\">\n ${ comment.user.name }\n </div>\n \n <div class=\"comment-content\">\n ${ comment.content }\n </div>\n </div>\n \n \n </div>\n \n \n <!-- delete button only visible to the creater of the comment and the creater of post -->\n <div class=\"delete-button-container\">\n \n <a href=\"/comments/destroy/${ comment._id }\" class=\"delete-comment-button\">\n <span class=\"material-icons-outlined \">\n delete\n </span>\n </a>\n \n </div>\n \n </li>`\n );\n }",
"function add_comment_element_event()\n{\t\n\t$('.add-comment').each(function(){\n\t\tvar order_product = $(this).parent().siblings('.action3');\n\t\tvar product_comments = $(this).next();\n\t\tvar order_product_record_id = $(this).parent().next().data('product_record_id');\n\t\tvar element = $(this);\n\n\t\t/* Unbind previous event */\n\t\telement.unbind();\n\n\t\telement.on('touchend', function () {\n\t\t\tmyApp.prompt('', 'Σχόλια', function(value){\n\t\t\t\torder_product.data('comments', value);\n\n\t\t\t\tif (element.parent().parent().hasClass('update-product'))\n\t\t\t\t{\n\t\t\t\t\t$.ajax({\n\t\t\t\t\t\ttype: 'POST',\n\t\t\t\t\t\turl: '/waiter_new_order/ajax_update_order_product',\n\t\t\t\t\t\tdata: {'order_product_record_id': order_product_record_id, 'comments': value},\n\t\t\t\t\t\tasync: false,\n\t\t\t\t\t\tsuccess: function() {\t\t\n\t\t\t\t\t\t\tproduct_comments.text(value);\n\t\t\t\t\t\t},\n\t\t\t\t\t\terror: function() {\n\t\t\t\t\t\t\talert('failure');\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t$('.modal-text-input').val(product_comments.text());\n\t\t});\n\t});\n}",
"function processComments(data) {\r\n\t\r\n\t\r\n\twindow.content = window.content.map(function(item) {\r\n\t\r\n\tif (data.content.some(function(commentCount) { return commentCount.id == item.contentId; })){\r\n\t\titem.commentCount = data.content.find(function(commentCount) { return commentCount.id == item.contentId; }).count;\r\n\t}\r\n\r\n\telse{\r\n\t\titem.commentCount=0;\r\n\t}\r\n\r\n\t\treturn item;\r\n\t});\r\n\r\n\trenderContent(window.content);\r\n\r\n}",
"createCommentNodes () {\n const comments = this.createComments();\n const nodes = [];\n for (let i = 0; i < this.canvasHeight; i++) {\n nodes[i] = document.createComment(comments[i]);\n }\n return nodes\n }",
"function commentsAvailable2 () {\n var m = document.getElementsByClassName(\"YxbmAc\");\n if(m.length > 0){\n console.log('erasure: %s comments are available.', m.length);\n return true;\n }\n return false;\n}",
"function displayComments (comment) {\n\n\t// create Card\n\tconst cardEl = document.createElement('div');\n\tcardEl.classList.add('card');\n\tcardEl.setAttribute('id', `card-${comment.id}`)\n\tcomments.prepend(cardEl);\n\t\n\tgetKitty(comment.id);\n\n\t// create Card Body\n\tconst bodyEl = document.createElement('div');\n\tbodyEl.classList.add('card__body');\n\tcardEl.appendChild(bodyEl);\n\n\t// create Card Header\n\tconst headerEl = document.createElement('div');\n\theaderEl.classList.add('card__heading');\n\tbodyEl.appendChild(headerEl);\n\n\t// create Card Comment\n\tconst paragraphEl = document.createElement('p');\n\tparagraphEl.classList.add('card__text');\n\tparagraphEl.innerText = comment.comment;\n\tbodyEl.appendChild(paragraphEl);\n\n\t// create Card Name\n\tconst nameEl = document.createElement('p');\n\tnameEl.classList.add('card__text-title');\n\tnameEl.innerText = comment.name;\n\theaderEl.appendChild(nameEl);\n\n\t// create Card Date\n\tconst dateEl = document.createElement('p');\n\tdateEl.classList.add('card__label');\n\tdateEl.innerText = convertTime(comment.timestamp);\n\theaderEl.appendChild(dateEl);\n\tconsole.log(comment.timestamp)\n\n\t// create Card Buttons Wrapper\n\tconst wrapperEl = document.createElement('div');\n\twrapperEl.classList.add('card__button-wrapper');\n\tbodyEl.appendChild(wrapperEl);\n\n\t// create Like Button\n\tconst likeEl = document.createElement('div');\n\tlikeEl.classList.add('like');\n\tlikeEl.setAttribute('id', comment.id);\n\tlikeEl.innerText = comment.likes;\n\twrapperEl.appendChild(likeEl);\n\n\t// create Delete Button\n\tconst deleteEl = document.createElement('div');\n\tdeleteEl.classList.add('delete');\n\tdeleteEl.setAttribute('id', comment.id);\n\tdeleteEl.innerText = \"Delete\"\n\twrapperEl.appendChild(deleteEl);\n}",
"function DisplayMovieComments(comment)\n{\n\tvar DivMovieComments = $(\"#movie_comments\"); \n\tvar articleComment = '<article id=\"comment-id-1\" class=\"comment-item\"><a class=\"pull-left thumb-sm\">'+\n\t\t'<img src=\"images/a0.png\" class=\"img-circle\"></a><section class=\"comment-body m-b\"><header>'+\n\t\t'<strong>'+comment.cinephile+'</strong><span class=\"text-muted text-xs block m-t-xs\">'+\n\t\tcomment.date+ '</span></header><div class=\"m-t-sm\">'+comment.content+'</div></section></article>'; \n\tDivMovieComments.append(articleComment); \n}",
"function buildCommentCard(commentCardTemplate, commentCardData)\n{\n var commentCard = $(commentCardTemplate);\n commentCard.attr('data-comment', commentCardData.comment.commentId);\n\n // Set comment avatar\n if (commentCardData.avatar !== null) {\n commentCard.find('img').attr('src', commentCardData.avatar);\n } else {\n commentCard.find('img').attr('src', cumulusClips.themeUrl + '/images/avatar.gif');\n }\n\n // Set comment author\n commentCard.find('.commentAuthor a')\n .attr('href', cumulusClips.baseUrl + '/members/' + commentCardData.author.username)\n .text(commentCardData.author.username);\n\n // Set comment date\n var commentDate = new Date(commentCardData.comment.dateCreated.split(' ')[0]);\n monthPadding = (String(commentDate.getMonth()+1).length === 1) ? '0' : '';\n datePadding = (String(commentDate.getDate()).length === 1) ? '0' : '';\n commentCard.find('.commentDate').text(monthPadding + (commentDate.getMonth()+1) + '/' + datePadding + commentDate.getDate() + '/' + commentDate.getFullYear());\n\n // Set comment action links\n commentCard.find('.commentAction .reply').text(cumulusClips.replyText);\n commentCard.find('.flag')\n .text(cumulusClips.reportAbuseText)\n .attr('data-id', commentCardData.comment.commentId);\n\n // Set reply to text if apl.\n if (commentCardData.comment.parentId !== 0) {\n commentCard.find('.commentReply').text(cumulusClips.replyToText + ' ');\n // Determine parent comment author's text\n var parentCommentAuthorText;\n parentCommentAuthorText = $('<a>')\n .attr('href', cumulusClips.baseUrl + '/members/' + commentCardData.parentAuthor.username)\n .text(commentCardData.parentAuthor.username);\n commentCard.find('.commentReply').append(parentCommentAuthorText);\n } else {\n commentCard.find('.commentReply').remove();\n }\n\n // Set comment text\n commentCardData.comment.comments = commentCardData.comment.comments.replace(/</g, '<');\n commentCardData.comment.comments = commentCardData.comment.comments.replace(/>/g, '>');\n commentCard.find('> div p:last-child').html(commentCardData.comment.comments.replace(/\\r\\n|\\n|\\r/g, '<br>'));\n\n return commentCard;\n}",
"function ajax_comments_find_element(identifier, tag) {\n var e = $('' + identifier + '');\n\n if(e == null && tag != false) {\n var a = document.getElementsByTagName(tag);\n for(var i=0; i<a.length; i++) {\n if(a[i].className.toLowerCase().indexOf(ajax_comments_list) != -1) {\n return a[i];\n }\n }\n }\n \n return e;\n}",
"_getComments(){\r\n \r\n // JSX\r\n let commentJSX = this.state.commentList.map(comment => {\r\n return(<Comment comment_key={comment.id} \r\n commentdata={comment} \r\n onDelete={this._deleteComment.bind(this)}/>);\r\n /*if(comment.tag)\r\n return(<Comment author={comment.author} comment={comment.body} tags={comment.tag}/>);\r\n else \r\n return(<Comment author={comment.author} comment={comment.body}/>);\r\n */ \r\n });\r\n\r\n // return\r\n return commentJSX;\r\n\r\n }",
"static RemoveExceedComment()\r\n {\r\n const Max = Settings.MaxDisplayComment;\r\n if( Max > 0 )\r\n {\r\n while( $('#CommentArea #Body .Row').length > Max )\r\n {\r\n $('#ViewCommentArea #Body .Row:first-child').remove(); \r\n }\r\n }\r\n }",
"comments(node, { value: text, type }) {\n return type === 'comment2' && bannerRegex.test(text)\n }",
"function setComments(){\n\t\n\tvar nbFinder = parseInt($('#notebook-modal').attr('nbFinder'), 10);\n\tvar photos = notebooks[nbFinder].photoObjects;\n\tvar finder = parseInt($('#pm-photo').attr('finder'), 10);\n\tvar photoObj = photos[finder];\n\t\n\t$('#pm-user').attr('value', user.email);\n\t$('#pm-userFirst').attr('value', user.firstName);\n\t$('#pm-userLast').attr('value', user.lastName);\n\t$('#pm-photoUrl').attr('value', photoObj.url);\n\n\tvar photoComments = photoObj.comments;\n\tvar commentsDynamic = \"\";\n\n\tfor (var i = photoComments.length - 1; i > -1; i--) {\n\t\tvar commentText = photoComments[i];\n\t\tvar comment = allComments.filter(function(commentFilter) {return commentFilter.text == commentText})[0];\n\t\tcommentsDynamic += \"<div class='comment-text-container'><a href='/pro-profile-view/\" + user.email + \"'><p class='comments-name'>\" + comment.firstName + ' ' + comment.lastName + \"</p></a><p class='comments-text'>\" + comment.text.replace(/\\n/g,'<p>') + \"</p></div>\";\n\t}\n\n\tif (photoObj.newCommentHTML) {\n\t\tcommentsDynamic = photoObj.newCommentHTML + commentsDynamic;\n\t}\n\n\t$('#pm-comment-container-inner').html(commentsDynamic)\n}",
"function comment(type, id, element) {\r\r\n if( jQuery(element).siblings('textarea').val().length != 0) {\r\r\n var content = jQuery(element).siblings('textarea').val();\r\r\n jQuery(element).siblings('textarea').val('');\r\r\n jQuery.post(\r\r\n swapchic_ajax.ajax_url,\r\r\n {\r\r\n 'action': 'ajaxComment',\r\r\n 'post_id': id,\r\r\n 'content' : content\r\r\n },\r\r\n function(response){\r\r\n // Append new comment to comment thread\r\r\n jQuery(element).parents('.comment-thread-wrapper').children('.comment-thread').prepend(response);\r\r\n // Increase number of comments\r\r\n var comments = parseInt(jQuery(element).parents('.social').children('.comments').children('span').html()) + 1;\r\r\n jQuery(element).parents('.social').children('.comments').children('span').html(comments);\r\r\n jQuery(element).siblings('textarea').val('');\r\r\n }\r\r\n );\r\r\n }\r\r\n}",
"function writeHtmlComments(num){\n $( \"#commentsDialigDiv\" ).html( ' <div class=\"modal outer-element uib_w_12\" data-uib=\"twitter%20bootstrap/modal\" data-ver=\"1\" data-backdrop=\"true\" data-keyboard=\"true\" id=\"comments\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><button class=\"close\" data-dismiss=\"modal\">x</button><h4 class=\"modal-title\">Comentarios</h4></div><div class=\"modal-body\"><div class=\"col uib_col_'+num+' single-col\" data-uib=\"layout/col\" data-ver=\"0\"><div class=\"widget-container content-area vertical-col\"><div class=\"widget uib_w_13 d-margins\" data-uib=\"media/text\" data-ver=\"0\"><div class=\"widget-container left-receptacle\"></div><div class=\"widget-container right-receptacle\"></div><div><p>Envianos tus comentarios, quejas, sugerencias o el reporte de algun error.</p></div></div><div class=\"table-thing widget uib_w_14 d-margins\" data-uib=\"twitter%20bootstrap/text_area\" data-ver=\"1\"><label class=\"narrow-control\"></label><textarea rows=\"4\" class=\"wide-control form-control\" wrap=\"soft\" id=\"taComment\"></textarea></div><button class=\"btn widget uib_w_15 d-margins btn-danger\" data-uib=\"twitter%20bootstrap/button\" data-ver=\"1\" data-dismiss=\"modal\" onclick=\"sendComment()\">Enviar<i class=\"glyphicon glyphicon-info-sign button-icon-right\" data-position=\"right\"></i></button><span class=\"uib_shim\"></span></div></div></div><div class=\"modal-footer\"></div></div></div></div>' ); \n}",
"function Comment (user, image, href, tags, comment, date, tag_base, sbm) {\r\n this.user = user;\r\n this.image = image;\r\n this.href = href;\r\n this.tags = tags;\r\n this.comment = comment;\r\n this.date = date;\r\n this.tag_base = tag_base;\r\n this.sbm = sbm;\r\n this.ignore = [];\r\n this.ignore[\"hatena\"] = ignore_hatena;\r\n this.ignore[\"delicious\"] = ignore_delicious;\r\n this.ignore[\"livedoor\"] = ignore_livedoor;\r\n this.ignore[\"buzzurl\"] = ignore_buzzurl;\r\n this.ignore[\"pookmark\"] = ignore_pookmark;\r\n this.ignore[\"ldr\"] = ignore_ldr;\r\n Comment.prototype.isNotIgnore = function(){\r\n var res = true;\r\n for(var i=0; i<this.ignore[this.sbm].length; i++){\r\n if(this.ignore[this.sbm][i].toLowerCase() == this.user.toLowerCase()){\r\n res = false;\r\n break;\r\n }\r\n }\r\n return res;\r\n }\r\n Comment.prototype.getHTML = function() {\r\n this.HTML = '';\r\n if(option.show_nocomment || this.comment != '') {\r\n var m = String(this.date.getMonth()+1);\r\n if(m.length == 1){\r\n m = \"0\" + m;\r\n }\r\n var d = String(this.date.getDate());\r\n if(d.length == 1){\r\n d = \"0\" + d;\r\n }\r\n this.HTML = '<li>' + this.date.getFullYear() + \"/\" + m + \"/\" + d\r\n + ' <a href=\"'+ this.href + '\" style=\"' + anchor_css + '\"><img src=\"'\r\n + this.image +'\" width=\"12px\" heigth=\"12px\" border=\"0\"/> ' + this.user +'</a>: ';\r\n if(option.show_tag) {\r\n for(var i=0; i<this.tags.length; i++) {\r\n this.HTML+='<a href=\"' + this.tag_base + encodeURIComponent(this.tags[i]) + '\" style=\"' + anchor_css + '\">' + this.tags[i] + '</a>';\r\n if(i+1<this.tags.length){\r\n this.HTML+=', ';\r\n }else{\r\n this.HTML+=' ';\r\n }\r\n }\r\n }\r\n this.HTML+= this.comment + \"</li>\";\r\n }\r\n return this.HTML;\r\n }\r\n return this;\r\n }",
"updateCommentFormButton() {\n if (cd.g.autoScrollInProgress) return;\n\n if (cd.commentForms.some((commentForm) => !commentForm.$element.cdIsInViewport(true))) {\n this.$commentFormButton.show();\n } else {\n this.$commentFormButton.hide();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ueberprueft, ob ein Objekt einer bestimmten Klasse angehoert (ggfs. per Vererbung) obj: Ein (generisches) Objekt base: Eine Objektklasse (KonstruktorFunktion) return true, wenn der Prototyp rekursiv gefunden werden konnte | function instanceOf(obj, base) {
while (obj !== null) {
if (obj === base.prototype)
return true;
if ((typeof obj) === 'xml') { // Sonderfall mit Selbstbezug
return (base.prototype === XML.prototype);
}
obj = Object.getPrototypeOf(obj);
}
return false;
} | [
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RelationshipLink.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === EipAssociation.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Record.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Backup.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === CustomerGateway.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VirtualMachineResource.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Bot.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Key.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Resolver.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === JavaAppLayer.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === SigningProfilePermission.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DisasterRecoveryConfig.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VirtualMachineScaleSetVM.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === UserGroup.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === EncryptionConfig.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === NotificationRecipientEmail.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ContainerPolicy.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === MountTarget.__pulumiType;\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Snapshot.__pulumiType;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hooks the JWT Strategy. | function hookJWTStrategy(passport) {
var options = {}
options.secretOrKey = config.secret
options.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('Bearer')
passport.use(new JWTStrategy(options, function(JWTPayload, callback) {
db.users.findOne({ _id: JWTPayload._id }, function(err, user) {
if (err) return callback(err, false)
if(user) {
callback(null, user)
return
}
callback(null, false)
})
}))
} | [
"function hookJWTStrategy(passport) {\n // TODO: Set up Passport to use the JWT Strategy.\n const options = {};\n\n options.secretOrKey = config.keys.secret;\n options.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');\n options.ignoreExpiration = false;\n\n passport.use(new JWTStrategy(options, (JWTPayload, callback) => {\n console.log('hookJWTStrategy()');\n db.User.findOne({\n where: { login: JWTPayload.login },\n include: [{ all: true }]\n })\n .then(user => {\n if (!user) {\n callback(null, false);\n return;\n }\n\n callback(null, user);\n return;\n });\n }));\n}",
"async function doJwtAuth() {\n clearStatus();\n writeStatus(\"Requesting JWT from auth server...\");\n\n ably = new Ably.Realtime({ authUrl: \"/ably-jwt\" });\n ably.connection.on((stateChange) => {\n onStateChange(\"Connection\", stateChange);\n });\n}",
"async function doJwtWithCallback() {\n clearStatus();\n writeStatus(`Requesting JWT authentication from server via callback...`);\n ably = new Ably.Realtime({\n authCallback: async ({}, callback) => {\n try {\n const response = await fetch(\"/ably-jwt\");\n const data = await response.json();\n console.log(data);\n callback(null, data);\n } catch (error) {\n writeStatus(\"Error performing JWT authentication via callback...\");\n callback(error, null);\n }\n },\n });\n ably.connection.on((stateChange) => {\n onStateChange(\"Connection\", stateChange);\n });\n}",
"static isAuthenticated(req, res, next) {\n const Authorization = req.get('Authorization');\n\n if (Authorization) {\n const token = Authorization.replace('Bearer ', '');\n try {\n // JWTSECRET=some long secret string\n const payload = jwt.verify(token, process.env.JWTSECRET);\n\n // Attach the signed payload of the token (decrypted of course) to the request.\n req.jwt = {\n payload\n };\n\n next();\n } catch {\n // The JSON Web Token would not verify.\n res.sendStatus(401);\n }\n } else {\n // There was no authorization.\n res.sendStatus(401);\n }\n }",
"function checkForJwt(cb) {\n debug('check for existing jwt');\n\n // See if we have a login token\n if (_.isObject(program.profile.jwt) === false) return cb();\n\n // If force new login, clear out any existing jwt.\n if (options.forceLogin) {\n program.profile.jwt = null;\n return cb();\n }\n\n // If the JWT is expired, force user to login again.\n if (_.isNumber(program.profile.jwt.expires) === false ||\n Date.now() > program.profile.jwt.expires) {\n program.profile.jwt = null;\n }\n\n cb();\n }",
"function allow(request, reply) {\n //JWT includes a recorderID\n if (!request.jwt.recorder_id) {\n reply.fail({\n status: '401',\n detail: 'Auth token is not valid for any recorder',\n });\n return;\n }\n //JWT includes an accountID\n if (!request.jwt.account_id) {\n reply.fail({\n status: '401',\n detail: 'Auth token is not valid for any account',\n });\n return;\n }\n //path param accountID matches JWT's accountID\n if (request.account_id !== request.jwt.account_id) {\n reply.fail({\n status: '403',\n detail: 'Auth token is not valid for account ' + request.account_id,\n });\n return;\n }\n //JWT's recorderID matches the body's recorderID\n if (request.jwt.recorder_id !== request.body.data[0].id) {\n reply.fail({\n status: '403',\n detail: 'Auth token is not valid for recorder ' + request.body.data[0].id,\n });\n return;\n }\n reply.succeed(request);\n}",
"function tokenFunc() {\n\tlet data = {username : process.env.WORDPRESS_USER, password : process.env.WORDPRESS_PASS};\n\treturn new Promise(function(resolve, reject) {\n\t\trequest({\n\t\t\turl: process.env.WORDPRESS_ROOT_PATH + \"/wp-json/jwt-auth/v1/token\",\n\t\t\tContentType : 'application/x-www-form-urlencoded',\n\t\t\tmethod: \"POST\",\n\t\t\tform: data\n\t\t}, function(error, response, body) {\n\t\t\tif(error) {\n\t\t\t\treject(error)\n\t\t\t} else {\n\t\t\t\tlet info = body.substring(body.indexOf(\"{\"));\n\t\t\t\tinfo = JSON.parse(info);\n\t\t\t\tinfo = info.token;\n\t\t\t\tresolve(info);\n\t\t\t\t/*\n\t\t\t\trequest({\n\t\t\t\t\turl: process.env.WORDPRESS_ROOT_PATH + '/wp-json/jwt-auth/v1/token/validate',\n\t\t\t\t\tContentType: 'application/json',\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tauth: {'bearer' : info},\n\t\t\t\t\tjson: true\n\t\t\t\t}, function(error, response, body) {\n\t\t\t\t\tif(error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t\tif(body == undefined) {\n\t\t\t\t\t\treject(\"Not a real postID\");\n\t\t\t\t\t}\n\t\t\t\t\tbody = body.substring(body.indexOf(\"{\"));\n\t\t\t\t\tbody = JSON.parse(body);\n\t\t\t\t\tconsole.log(body);\n\t\t\t\t\tif(body.code == \"jwt_auth_valid_token\") {\n\t\t\t\t\t\tresolve(info);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t*/\n\t\t\t}\n\t\t});\n\t});\n}",
"function authMiddleware(next){\n return function(msg, replier){\n var params = JSON.parse(msg);\n tokenAuthentication(params.token, function(valid){\n if (!valid) {\n return replier(JSON.stringify({ok: false, error: \"invalid_auth\"}));\n } else {\n next(msg, replier);\n }\n });\n }\n}",
"configureSecurityRoutes(router) {\n const secret = '7ad58489-4781-4049-b136-d6b1744b358e';\n router.post('/authenticate', (req, res) => {\n const username = req.body.username;\n const password = req.body.password;\n if (!username || !password) {\n res.json({});\n }\n else {\n user_1.User.findOne({ username: username }, (err, user) => {\n if (err || !user || user.password !== password) {\n return res.json({});\n }\n let token = jwt.sign(user, secret, {\n expiresIn: 1000\n });\n res.json({\n success: true,\n lifeTime: 1000,\n token: token\n });\n });\n }\n });\n // this.express.use((req: Request, res: Response, next: NextFunction) => {\n // let token = req.body.token || req.query.token || req.headers['x-access-token'];\n // debug('token :' + token);\n // if (!token) {\n // if (req.path === '/authenticate') {\n // next();\n // return;\n // }\n // return res.json(403, {\n // success: false,\n // message: 'No token provided.' });\n // } else {\n // jwt.verify(token, secret, function (err, decoded) {\n // if (err) {\n // return res.json({ success: false, message: 'Not authenticated' });\n // }\n // next();\n // });\n // }\n // });\n }",
"createJWT () {\n const token = {\n iat: parseInt(Date.now() / 1000),\n exp: parseInt(Date.now() / 1000) + 20 * 60, // 20 minutes\n aud: this.mqtt.project\n }\n return jwt.sign(token, fs.readFileSync(this.device.key.file), { algorithm: this.device.key.algorithm })\n }",
"function handle_user_auth(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}",
"_registerAuthHandlers () {\n expose('authenticate', this.authenticate.bind(this), {postMessage: this.postMessage})\n expose('createLink', this.createLink.bind(this), {postMessage: this.postMessage})\n }",
"function checkJWT() {\n if ( !isLoggedIn() )\n window.location.replace('/sign-in/?return=/daily-data/');\n}",
"loginUser(token){\n this.setState({jwt: token});\n // @todo save the token to the local storage\n }",
"function setJwtCookie(jwt, response, minutesTilExpire) {\n response.state(_appConfig.settings.get('/JWT/COOKIE/NAME'), jwt, {\n ttl: minutesTilExpire * 60 * 1000, // In milliseconds\n path: _appConfig.settings.get('/JWT/COOKIE/PATH'),\n domain: _appConfig.settings.get('/JWT/COOKIE/DOMAIN')\n });\n}",
"function createToken(payload){\r\n return jwt.sign(payload, SECRET_KEY, {expiresIn})\r\n}",
"localLogin(authResult) {\n this.idToken = authResult.idToken;\n this.profile = authResult.idTokenPayload;\n\n // convert the JWT expiry time from seconds to milliseconds\n this.tokenExpiry = new Date(this.profile.exp * 1000);\n\n // save the access token\n this.accessToken = authResult.accessToken;\n this.accessTokenExpiry = new Date(Date.now() + authResult.expiresIn * 1000);\n\n localStorage.setItem(localStorageKey, \"true\");\n\n this.emit(loginEvent, {\n loggedIn: true,\n profile: this.profile,\n state: authResult.appState || {}\n });\n }",
"function getTwitchAuth() {\n\n var trustProxy = false;\n if (process.env.DYNO) {\n trustProxy = true;\n }\n\n passport.use('twitchNew', new twitchStrategy({\n clientID: process.env.TWITCH_CLIENT_ID,\n clientSecret: process.env.TWITCH_CLIENT_SECRET,\n callbackURL: '/oauth/callback/twitch',\n },\n function(token, tokenSecret, profile, cb) {\n process.env.TWITCH_ACCESS_TOKEN = token;\n process.env.TWITCH_ACCESS_TOKEN_SECRET = tokenSecret;\n return cb(null, profile);\n }));\n}",
"configureRoute(app) {\n const storeIssuer = (req, res, next) => {\n const host = req.headers['x-forwarded-host'] || req.headers.host;\n res.locals.issuer = `${req.protocol}://${host}/auth/${this.loginName}`;\n next();\n };\n // configure username/password route\n var v = this.verify.bind(this);\n this.authLib.log.info('adding route to app');\n const loginRoute = '/auth/' + this.loginName + '/verify';\n app.use(loginRoute, storeIssuer);\n app.post(loginRoute, v);\n\n // configure refreshtoken route\n if(this.verifyRefresh) {\n this.authLib.log.info('configuring refresh token route');\n var vr = this.verifyRefresh.bind(this);\n const refreshRoute = '/auth/' + this.loginName + '/token';\n app.use(refreshRoute, storeIssuer);\n app.post(refreshRoute, vr);\n }\n\n // configure well known routes if signing algorithm is RS256\n if(this.authLib.opts.signAlg === 'RS256') {\n this.authLib.log.info('adding openid + jwks routes');\n app.get(\n '/auth/' + this.loginName + '/.well-known/openid-configuration',\n this.openIDConfiguration.bind(this)\n );\n app.get(\n '/auth/' + this.loginName + '/.well-known/jwks.json',\n this.getKeySet.bind(this)\n );\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
channelId and tabId are optional. If callbackOnLoad is not null then it'll be passed the FavoriteTabCookie object once it's loaded. | function saveNewFavoriteTab(channelId,tabId,callbackOnLoad) {
var url = "/b/gamerprof/list/FavoriteTabService?channel="+ channelId;
if(tabId != null){
url += "&tab="+ tabId;
}
new Ajax.Request(url,
{
method:'get',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
if(response == 'NOT_LOGGED_IN') {
sendUserToLogin();
} else if(callbackOnLoad != null && response.substr(0,7)=='FavTab=') {
var cookieStr = response.substr(7);
callbackOnLoad(cookieStr);
}
},
onFailure: function(){ }
});
} | [
"function checkOwnFavs(){\n if( ! conf.ownFavs || ! tweet.favorited ){\n return checkFinal();\n }\n checkOwnFavourite( tweet.id_str, function( favourited ){\n if( favourited ){\n console.log('Keeping tweet favourited by self');\n return nextTweet();\n }\n checkFinal();\n } );\n }",
"function initializeCookieBanner() {\n let isCookieAccepted = localStorage.getItem(\"cc_isCookieAccepted\");\n if (isCookieAccepted === null) {\n localStorage.clear();\n localStorage.setItem(\"cc_isCookieAccepted\", \"false\");\n showCookieBanner();\n }\n if (isCookieAccepted === \"false\") {\n showCookieBanner();\n }\n}",
"function addConfirmRemoveFavoriteHandler(e) {\r\n e.preventDefault();\r\n e.stopPropagation();\r\n var $el = $(this);\r\n var contentType = $el.attr(\"data-container-content-type\");\r\n var contentId = $el.attr(\"data-content-theme\");\r\n if (contentType && contentId) {\r\n var $contentInstall = $(\".av-content-install[data-content-theme=\" + contentId + \"]\");\r\n if ($contentInstall) {\r\n var $contentItem = $contentInstall.closest(\".av-content-container\");\r\n var $contentImgContainer = $contentItem.find(\".av-content-img-container\");\r\n if ($contentItem) {\r\n var $removeFavoriteBtn = $contentItem.find(\".av-content-favorite-img-active\");\r\n if ($removeFavoriteBtn) {\r\n $el.off(\"click\", addConfirmRemoveFavoriteHandler);\r\n removeThemeElementFromFavorite(contentType, contentId);\r\n $removeFavoriteBtn.removeClass(\"av-content-favorite-img-active\");\r\n $removeFavoriteBtn.hide();\r\n $contentImgContainer.on(\"mouseenter\", showFavoriteImageOnContentHover).on(\"mouseleave\", hideFavoriteImageOnContentHover);\r\n $removeFavoriteBtn.attr('data-original-title', translate(\"options_tabs_item_buttons_favorite\")).tooltip('fixTitle');\r\n $(\"#delete-from-favorite-dialog\").modal('hide');\r\n getFavoriteTabPages(reloadTabPages);\r\n var $contentFavorite = $(\"#available-favorite-themes, #available-favorite-images\").find(\".av-content-install[data-content-theme=\" + contentId + \"]\").closest(\".av-content-container\");\r\n $contentFavorite.fadeOut(600, function () {\r\n $contentFavorite.remove();\r\n if (typeof NAVI == \"object\") NAVI.draw(\"counters\");\r\n });\r\n }\r\n }\r\n }\r\n }\r\n}",
"function onTabShown(event, tabId) {\n if (tabId === tabControl.TABS.EXPLORE) {\n showSpinner();\n UserPreferences.setPreference('method', 'explore');\n setFromUserPreferences();\n $(options.selectors.isochroneSliderContainer).removeClass(options.selectors.hiddenClass);\n clickedExplore();\n } else {\n $(options.selectors.alert).remove();\n mapControl.isochroneControl.clearIsochrone();\n mapControl.isochroneControl.clearDestinations();\n $(options.selectors.isochroneSliderContainer).addClass(options.selectors.hiddenClass);\n }\n }",
"function init(){\n \t \tif (cookie.get() == null) {\n \t \t\tcookie.set('history', cache);\n \t \t}\n \t \telse {\n \t \t\tcache = cookie.get();\n \t \t}\n \t }",
"function addToFavorite()\n{\n\t//Add to favourite the page\n\twindow.external.AddFavorite(location.href, document.title);\n}",
"function tabExists(tabId, onExists, onNotExists) {\n chrome.windows.getAll({\n populate: true\n }, function(windows) {\n for (var i = 0, window; window = windows[i]; i++) {\n for (var j = 0, tab; tab = window.tabs[j]; j++) {\n if (tab.id == tabId) {\n onExists && onExists(tab);\n return;\n }\n }\n }\n onNotExists && onNotExists();\n });\n }",
"function initYouTubeList(){\r\n var tabUrl = window.location.href;\r\n var youTubeListId = getURLParameter(tabUrl, 'list');\r\n if (youTubeListId && youTubeListId != playlistId){\r\n playlistId = youTubeListId;\r\n extractVideosFromYouTubePlaylist(youTubeListId);\r\n }\r\n}",
"function checkFavorites() {\n if (localStorage.getItem(\"favorites\") == null) {\n favoritesArray = [];\n localStorage.setItem(\"favorites\", JSON.stringify(favoritesArray));\n } else {\n favoritesArray = JSON.parse(localStorage.getItem(\"favorites\"));\n }\n }",
"function getOptionsCurentTab(callback) {\r\n BRW_TabsGetCurrentID(function (tabID) {\r\n optionsTabId = tabID;\r\n callback();\r\n });\r\n}",
"function initialiseFavorites(urlBase, textLearn){\r\n\tthis.url = urlBase;\r\n\tthis.learn = textLearn;\r\n}",
"function emptyFavorites () {\n if (savedFavorites == null || savedFavorites == 0) {\n noFavotires.classList.remove('hide');\n } else {\n noFavotires.classList.add('hide');\n }\n}",
"function navigateWebviewAndSetCookie(webview, url, cookie, callback) {\n var messageHandler = Messaging.GetHandler();\n // Handles the response to the request for setting the cookie.\n messageHandler.addHandler(SET_COOKIE_COMPLETE, function(message, portFrom) {\n messageHandler.removeHandler(SET_COOKIE_COMPLETE);\n callback();\n });\n // Navigate and when ready, send the request.\n navigateWebview(webview, url, function() {\n messageHandler.sendMessage(\n new Messaging.Message(SET_COOKIE, {'cookie': cookie}),\n webview.contentWindow);\n });\n}",
"function EMSetEventQueueCallback(onSuccess, onError)\n{\n var __e = __sharedEMA();\n __e.cache.setEventQueueCallback(onSuccess, onError);\n}",
"function checkNumFavs(){\n if( conf.minFavs && tweet.favorited && conf.minFavs <= tweet.favorite_count ){\n console.log('Keeping tweet favourited '+tweet.favorite_count+' times');\n return nextTweet();\n }\n checkTags();\n }",
"function checkFollowedButton() {\n\tvar button = document.getElementById(\"followedButton\");\n\tvar loginCookie = $.cookie(\"stock_auth_token\");\n\tif (loginCookie == undefined || loginCookie.length <= 0) {\n\t\tbutton.style.display = \"none\";\n\t\treturn;\n\t}\n\t$.getJSON(\"/get_following\", function(jsonObj) {\n\t\tif (jsonObj.length > 0) {\n\t\t\tbutton.style.display = \"\";\n\t\t} else {\n\t\t\tbutton.style.display = \"none\";\n\t\t}\n\t});\n}",
"function pluginLoaded(\n/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/\n /**\n * No arguments. */\n)\n/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/\n{\n console.log(2, \"Local Plugin Loaded.\");\n Callcast.localplayer = $(\"object.localplayer\").get(0);\n Callcast.InitGocastPlayer(null, null, function(message) {\n /*\n * Initialization successful. */\n console.log(2, \"Local plugin successfully initialized.\");\n /*\n * Set callback functions to add and remove plugins for other\n * participants. */\n Callcast.setCallbackForAddPlugin(addPlugin);\n Callcast.setCallbackForRemovePlugin(removePlugin); \n initializeLocalPlugin();\n }, function(message) {\n /*\n * Failure to initialize. */\n console.log(4, \"Local plugin failed to initialize.\");\n $(\"#errorMsgPlugin\").empty();\n $(\"#errorMsgPlugin\").append('<h1>Gocast.it plugin failed to initialize</h1><p>Please reload the page. [Ctrl + R]</p>');\n openWindow('#errorMsgPlugin');\n });\n}",
"function mmrpg_fanfare_load(newTrack, resartTrack, playOnce, fadeMusic, onendFunction){\n //console.log('mmrpg_fanfare_load(', newTrack, resartTrack, playOnce, ')');\n var fanfareStream = $('.audio-stream.fanfare', gameMusic);\n //console.log('fanfareStream =', fanfareStream.length, fanfareStream);\n var thisTrack = fanfareStream.attr('data-track');\n var isRestart = typeof resartTrack === 'boolean' ? resartTrack : true;\n var isPlayOnce = typeof playOnce === 'boolean' ? playOnce : true;\n var fadeMusic = typeof fadeMusic === 'boolean' ? fadeMusic : true;\n var onendFunction = typeof onendFunction === 'function' ? onendFunction : mmrpgFanfareEndedDefault;\n if (newTrack == 'last-track'){\n var lastTrack = fanfareStream.attr('data-last-track');\n if (lastTrack.length){ newTrack = lastTrack; }\n }\n if (isRestart == false && newTrack == thisTrack){\n return false;\n }\n if (mmrpgFanfareSound !== false\n && mmrpgFanfareSound.playing()){\n mmrpgFanfareSound.stop();\n }\n fanfareStream.attr('data-track', newTrack);\n fanfareStream.attr('data-last-track', thisTrack);\n // Create a new Howl object and load the new track\n if (fadeMusic){ mmrpg_music_volume(0, false, 300); }\n var fanfareVolume = gameSettings.musicVolume * gameSettings.masterVolume;\n if (!gameSettings.musicVolumeEnabled){ musicBaseVolume = 0; }\n if (mmrpgFanfareSound === false){\n\n mmrpgFanfareSound = new Howl({\n src: [gameSettings.audioBaseHref+'sounds/'+newTrack+'/audio.mp3?'+gameSettings.cacheTime,\n gameSettings.audioBaseHref+'sounds/'+newTrack+'/audio.ogg?'+gameSettings.cacheTime],\n autoplay: false,\n volume: fanfareVolume,\n loop: isPlayOnce ? false : true,\n onend: function(){\n if (fadeMusic){ mmrpg_reset_music_volume(); }\n onendFunction();\n },\n onload: function(){\n this.volume(fanfareVolume);\n }\n });\n mmrpgFanfareSound.once('load', function(){\n this.stop();\n this.volume(fanfareVolume);\n this.play();\n });\n\n } else {\n\n mmrpgFanfareSound.stop();\n mmrpgFanfareSound.volume(fanfareVolume);\n mmrpgFanfareSound.play();\n\n }\n\n}",
"function isFavorite(story) {\n // start with an empty set of favorite story ids\n let favoriteStoryIds = new Set();\n\n if (currentUser) {\n favoriteStoryIds = new Set(\n currentUser.favorites.map((story) => story.storyId)\n );\n }\n isFave = favoriteStoryIds.has(story.storyId);\n // return true or false\n return isFave;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Author: [S.H] Name: _getGroupDataSelector Description: given an item in the list, returns the data object that represents the group that the item belongs to. Params: item Return: data object of each group | function _getGroupDataSelector(item) {
return item.group;
} | [
"function _getGroupKeySelector(item) {\n return item.group.key;\n }",
"function group( item ) {\n\n item [ 'type' ] = TYPE.GROUP;\n item [ 'token' ] = item.uuid;\n item [ 'ts' ] = Service.$tools.getTimestamp( item.updatetime );\n \n return item;\n \n }",
"function createItemGroup(pkg, callback){\n var item = {\n title : pkg.title,\n description : pkg.notes,\n created : pkg.metadata_created,\n url : config.ckan.server+\"/dataset/\"+pkg.name,\n ckan_id : pkg.id,\n updated : pkg.revision_timestamp,\n groups : [],\n resources : pkg.resources ? pkg.resources : [],\n organization : pkg.organization ? pkg.organization.title : \"\",\n extras : {}\n }\n\n // add extras\n if( pkg.extras ) {\n for( var i = 0; i < pkg.extras.length; i++ ) {\n if( pkg.extras[i].state == 'active' ) {\n item.extras[pkg.extras[i].key] = pkg.extras[i].value;\n }\n }\n }\n \n\n if( pkg.groups ) {\n for( var i = 0; i < pkg.groups.length; i++ ) {\n item.groups.push(pkg.groups[i].name);\n }\n }\n\n setTags(item, pkg, callback);\n}",
"function group(items) {\n const by = (key) => {\n // create grouping with resolved keying function\n const keyFn = typeof key === 'function' ? key : (item) => item[key];\n const groups = createGrouping(items, keyFn);\n // return collectors\n return Object.freeze({\n asArrays: (0, as_arrays_js_1.asArraysFactory)(groups),\n asEntries: (0, as_entries_js_1.asEntriesFactory)(groups),\n asMap: (0, as_map_js_1.asMapFactory)(groups),\n asObject: (0, as_object_js_1.asObjectFactory)(groups),\n asTuples: (0, as_tuples_js_1.asTuplesFactory)(groups),\n keys: (0, keys_js_1.keysFactory)(groups)\n });\n };\n return Object.freeze({ by });\n}",
"function createGrouping(items, keyFn) {\n const groups = [];\n let idx = 0;\n for (const item of items) {\n const itemKey = keyFn(item, idx);\n idx++;\n const predicate = (g) => (0, deep_eql_1.default)(g.key, itemKey);\n const construct = () => ({ key: itemKey, items: [] });\n (0, find_or_create_js_1.findOrCreate)(groups, predicate, construct).items.push(item);\n }\n return groups;\n}",
"getList(itemCollection){\n let {groupFunction, groupedByLabel, cellClass} = this.props;\n let CellClass = cellClass || Cell;\n if(groupFunction){\n const itemCollectionByGroup = _.groupBy(itemCollection, groupFunction);\n return _.map(itemCollectionByGroup, (group, groupName) => {\n const uniqueGroupId = _.uniqueId(groupName);\n const groupItems = itemCollectionByGroup[groupName];\n return(\n <div key={uniqueGroupId} className={\"cellGridGroup\"}>\n <h3>{groupedByLabel} {groupName} - Total: {_.size(groupItems)}</h3>\n <div className=\"cellList\">\n {_.map(groupItems, (item, key) => this.getCell(CellClass, key, item))}\n </div>\n </div>\n );\n })\n } else {\n return <div className=\"cellList\">\n {_.map(itemCollection, (item, key) => this.getCell(CellClass, key, item))}\n </div>\n }\n }",
"function GroupItemMetadataProvider(options) {\n var _grid;\n var _defaults = {\n groupCssClass: \"slick-group\",\n totalsCssClass: \"slick-group-totals\",\n groupFocusable: true,\n totalsFocusable: false,\n toggleCssClass: \"slick-group-toggle\",\n toggleExpandedCssClass: \"expanded\",\n toggleCollapsedCssClass: \"collapsed\",\n enableExpandCollapse: true\n };\n\n options = $.extend(true, {}, _defaults, options);\n\n function defaultGroupCellFormatter(row, cell, value, columnDef, item) {\n if (!options.enableExpandCollapse) {\n return item.title;\n }\n\n return \"<span class='\" + options.toggleCssClass + \" \" +\n (item.collapsed ? options.toggleCollapsedCssClass : options.toggleExpandedCssClass) +\n \"'></span>\" + item.title;\n\n }\n\n function defaultTotalsCellFormatter(row, cell, value, columnDef, item) {\n return (columnDef.groupTotalsFormatter && columnDef.groupTotalsFormatter(item, columnDef)) || \"\";\n }\n\n\n function init(grid) {\n _grid = grid;\n _grid.onClick.subscribe(handleGridClick);\n _grid.onKeyDown.subscribe(handleGridKeyDown);\n\n }\n\n function destroy() {\n if (_grid) {\n _grid.onClick.unsubscribe(handleGridClick);\n _grid.onKeyDown.unsubscribe(handleGridKeyDown);\n }\n }\n\n function handleGridClick(e, args) {\n var item = this.getDataItem(args.row);\n if (item && item instanceof Slick.Group && $(e.target).hasClass(options.toggleCssClass)) {\n if (item.collapsed) {\n this.getData().expandGroup(item.value);\n }\n else {\n this.getData().collapseGroup(item.value);\n }\n\n e.stopImmediatePropagation();\n e.preventDefault();\n }\n }\n\n // TODO: add -/+ handling\n function handleGridKeyDown(e, args) {\n if (options.enableExpandCollapse && (e.which == $.ui.keyCode.SPACE)) {\n var activeCell = this.getActiveCell();\n if (activeCell) {\n var item = this.getDataItem(activeCell.row);\n if (item && item instanceof Slick.Group) {\n if (item.collapsed) {\n this.getData().expandGroup(item.value);\n }\n else {\n this.getData().collapseGroup(item.value);\n }\n\n e.stopImmediatePropagation();\n e.preventDefault();\n }\n }\n }\n }\n\n function getGroupRowMetadata(item) {\n return {\n selectable: false,\n focusable: options.groupFocusable,\n cssClasses: options.groupCssClass,\n columns: {\n 0: {\n colspan: \"*\",\n formatter: defaultGroupCellFormatter,\n editor: null\n }\n }\n };\n }\n\n function getTotalsRowMetadata(item) {\n return {\n selectable: false,\n focusable: options.totalsFocusable,\n cssClasses: options.totalsCssClass,\n formatter: defaultTotalsCellFormatter,\n editor: null\n };\n }\n\n\n return {\n \"init\": init,\n \"destroy\": destroy,\n \"getGroupRowMetadata\": getGroupRowMetadata,\n \"getTotalsRowMetadata\": getTotalsRowMetadata\n };\n }",
"group (name) {\n var me = `${this.visualType}-${this.model.uid}`,\n group = this.visualParent.getPaperGroup(me);\n if (name && name !== this.visualType) return this.paper().childGroup(group, name);\n else return group;\n }",
"getGroup (id) {\n assert.equal(typeof id, 'number', 'id must be number')\n return this._apiRequest(`/group/${id}`)\n }",
"function groupItemsByYear(selectItems) {\n var grouped = _.groupBy(selectItems, 'year');\n return _.map(grouped, function(items, key) {\n return {\n year: key,\n items: items\n };\n });\n }",
"function entityGroups() {\n // Define the data object and include needed parameters.\n // Make the groups API call and assign a callback function.\n}",
"selectModelsByGroup(groupName) {\n return this.filterAllByProperty('groupName', groupName)\n }",
"createSelectGroup() {\n let items = [];\n this.state.groups_list.forEach((T) => {\n items.push(<option key={T.group_id} value={T.group_id}>{T.title}</option>);\n })\n return items;\n }",
"facetComplexItems(aItems) {\n let attrKey = this.attrDef.boundName;\n let filter = this.facetDef.filter;\n let idAttr = this.facetDef.groupIdAttr;\n\n let groups = (this.groups = {});\n let groupMap = (this.groupMap = {});\n this.groupCount = 0;\n\n for (let item of aItems) {\n let vals = attrKey in item ? item[attrKey] : null;\n if (vals === Gloda.IGNORE_FACET) {\n continue;\n }\n\n if (vals == null || vals.length == 0) {\n vals = [null];\n }\n for (let val of vals) {\n // skip items the filter tells us to ignore\n if (filter && !filter(val)) {\n continue;\n }\n\n let valId = val == null ? null : val[idAttr];\n // We need to use hasOwnProperty because tag nouns are complex objects\n // with id's that are non-numeric and so can collide with the contents\n // of Object.prototype.\n if (groupMap.hasOwnProperty(valId)) {\n groups[valId].push(item);\n } else {\n groupMap[valId] = val;\n groups[valId] = [item];\n this.groupCount++;\n }\n }\n }\n\n let orderedGroups = Object.keys(groups).map(key => [\n groupMap[key],\n groups[key],\n ]);\n let comparator = this.facetDef.groupComparator;\n function comparatorHelper(a, b) {\n return comparator(a[0], b[0]);\n }\n orderedGroups.sort(comparatorHelper);\n this.orderedGroups = orderedGroups;\n }",
"function getGroupInfo(body){\n\t\treturn new Promise(function(resolve, reject) {\n\t\t\tvar sql = 'SELECT region_id, region_type_id FROM region_groups WHERE id = ?';\n\t\t\tdatabase.mysql.query(sql, [body.group_id], databaseHandler);\n\t\t\tfunction databaseHandler(err, result) {\n\t\t\t\tif(err) {\n\t\t\t\t\treject({message: \"internal database error: \" + err.message});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (result.length == 0){\n\t\t\t\t\treject({message: \"error finding group for id \" + group_id});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbody.region_id = result[0].region_id;\n\t\t\t\tbody.region_type_id = result[0].region_type_id;\n\t\t\t\tresolve(body);\n\t\t\t\treturn;\n\t\t\t}\n\t\t})\n\t}",
"function SplitDataByKey( data, key ){\n\n // nest splits the data by a given key\n var dataGroup = d3.nest().key( function( done ) {\n return done[key];\n } )\n .entries( data );\n\n return dataGroup;\n}",
"parseGroup() {\n const startPos = this.tok.pos;\n this.tok.consume(\"(\");\n let items = [];\n while (true) {\n const next = this.tok.peek();\n if (next == \"(\")\n items.push(this.parseGroup());\n else if (next !== null && /^[A-Z][a-z]*$/.test(next))\n items.push(this.parseElement());\n else if (next == \")\") {\n this.tok.consume(next);\n if (items.length == 0)\n throw new ParseError(\"Empty group\", startPos, this.tok.pos);\n break;\n }\n else\n throw new ParseError(\"Element, group, or closing parenthesis expected\", this.tok.pos);\n }\n return new Group(items, this.parseOptionalNumber());\n }",
"function GroupRenderer(){ \n return creatnGroupList.map((item) =>{\n return ( <GroupMember \n key = {item.id} \n id = {item.id} \n uname = {item.fname} \n handleDelFromList = {handleDelFromList}/>)\n })\n }",
"function showGroup() {\n\tvar ps = document.querySelectorAll('p, nav, section, article');\n\tvar i = 0;\n\twhile(i < ps.length) {\n\t\tgroupLength = ps[i].childNodes.length;\n\t\tif(groupLength > 1) {\n\t\t\tvar groupChild = document.createElement('span');\n\t\t\tgroupChild.classList.add('vasilis-srm-group');\n\t\t\tgroupChild.innerHTML = \" Group \" + groupLength + \" items\";\n\t\t\tps[i].appendChild(groupChild);\n\t\t}\n\t\ti++;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets whether the given module name resolves to a secondary entrypoint. | function isSecondaryEntryPoint(moduleName) {
return getEntryPointSubpath(moduleName) !== '';
} | [
"function isExistingModuleOrLibName(name) {\r\n\r\n var pO = CurProgObj;\r\n\r\n for (var m = 0; m < pO.allModules.length; m++) // search all user modules\r\n if (pO.allModules[m].name == name)\r\n return true;\r\n\r\n for (var m = 0; m < pO.libModules.length; m++) // search all library modules\r\n if (pO.libModules[m].name == name)\r\n return true;\r\n\r\n return false;\r\n}",
"function has_sub_extension(e) {\n\t//if(process.env.DEBUG_MVC) {\n\t//\tdebug.log('has_sub_extension(', e, ')');\n\t//}\n\tdebug.assert(e).is('string');\n\treturn function has_sub_extension_2(p) {\n\t\tvar name = PATH.basename(p, PATH.extname(p));\n\t\treturn PATH.extname(name) === e;\n\t};\n}",
"function procExists(host) {\n return typeof getProc(host) != 'undefined'\n}",
"function has_extension(e) {\n\t//if(process.env.DEBUG_MVC) {\n\t//\tdebug.log('has_extension(', e, ')');\n\t//}\n\tdebug.assert(e).is('string');\n\treturn function has_extension_2(p) {\n\t\treturn PATH.extname(p) === e;\n\t};\n}",
"function getEntryPointSubpath(moduleName) {\n return moduleName.slice(`${metadata.npmPackageName}/`.length);\n }",
"function getEntryPointInfo(pkgPath, entryPoint) {\n var packageJsonPath = path.resolve(entryPoint, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return null;\n }\n var entryPointPackageJson = loadEntryPointPackage(packageJsonPath);\n if (!entryPointPackageJson) {\n return null;\n }\n // If there is `esm2015` then `es2015` will be FESM2015, otherwise ESM2015.\n // If there is `esm5` then `module` will be FESM5, otherwise it will be ESM5.\n var name = entryPointPackageJson.name, modulePath = entryPointPackageJson.module, types = entryPointPackageJson.types, _a = entryPointPackageJson.typings, typings = _a === void 0 ? types : _a, // synonymous\n es2015 = entryPointPackageJson.es2015, _b = entryPointPackageJson.fesm2015, fesm2015 = _b === void 0 ? es2015 : _b, // synonymous\n _c = entryPointPackageJson.fesm5, // synonymous\n fesm5 = _c === void 0 ? modulePath : _c, // synonymous\n esm2015 = entryPointPackageJson.esm2015, esm5 = entryPointPackageJson.esm5, main = entryPointPackageJson.main;\n // Minimum requirement is that we have typings and one of esm2015 or fesm2015 formats.\n if (!typings || !(fesm2015 || esm2015)) {\n return null;\n }\n // Also we need to have a metadata.json file\n var metadataPath = path.resolve(entryPoint, typings.replace(/\\.d\\.ts$/, '') + '.metadata.json');\n if (!fs.existsSync(metadataPath)) {\n return null;\n }\n var entryPointInfo = {\n name: name,\n package: pkgPath,\n path: entryPoint,\n typings: path.resolve(entryPoint, typings),\n };\n if (esm2015) {\n entryPointInfo.esm2015 = path.resolve(entryPoint, esm2015);\n }\n if (fesm2015) {\n entryPointInfo.fesm2015 = path.resolve(entryPoint, fesm2015);\n }\n if (fesm5) {\n entryPointInfo.fesm5 = path.resolve(entryPoint, fesm5);\n }\n if (esm5) {\n entryPointInfo.esm5 = path.resolve(entryPoint, esm5);\n }\n if (main) {\n entryPointInfo.umd = path.resolve(entryPoint, main);\n }\n return entryPointInfo;\n }",
"function function_exists(function_name)\n{\n\tif (typeof function_name === 'string')\n\t\tfunction_name = this.window[function_name];\n\treturn typeof function_name === 'function';\n}",
"function is_predef_app(name) {\n var rule = get_predefined_rules(name);\n\n if(rule.length) {\n rule = rule.split(\"\\x02\");\n if(rule[_category] == CATEGORY_APP) {\n return true;\n }\n }\n return false;\n}",
"function checkIfVersionExists(modulename, version) {\n var moduleObject = require(modulename);\n var classname = \"v\" + version;\n if (moduleObject[classname]) {\n return true;\n }\n else {\n return false;\n }\n}",
"function moduleExists(moduleName) {\n modules.some(function(m) { return m.name === moduleName; });\n }",
"_isLocalAboutURI(aURI, aResolvedURI) {\n if (!aURI.schemeIs(\"about\")) {\n return false;\n }\n\n // Specially handle about:blank as local\n if (aURI.pathQueryRef === \"blank\") {\n return true;\n }\n\n try {\n // Use the passed in resolvedURI if we have one\n const resolvedURI = aResolvedURI || Services.io.newChannelFromURI2(\n aURI,\n null, // loadingNode\n Services.scriptSecurityManager.getSystemPrincipal(), // loadingPrincipal\n null, // triggeringPrincipal\n Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, // securityFlags\n Ci.nsIContentPolicy.TYPE_OTHER // contentPolicyType\n ).URI;\n return resolvedURI.schemeIs(\"jar\") || resolvedURI.schemeIs(\"file\");\n } catch (ex) {\n // aURI might be invalid.\n return false;\n }\n }",
"function isModuleType(type) {\n return ['chat', 'task', 'cal', 'poll'].includes(type);\n}",
"function isDelayEndpoint(pathname) {\n for (let index in delayEndpoints) {\n if (delayEndpoints[index][0] == pathname) {\n return true;\n }\n }\n return false;\n}",
"function entryPointLogic() {\n var lo = topBlock.getLogic();\n var main = lo.findBlock('main');\n if (main == null)\n throw \"'main' block wasn't found!\";\n return main;\n }",
"function skipModule (name) {\n var i, len;\n if (!skipModules) {\n return;\n }\n for (i = 0, len = skipModules.length; i < len; ++i) {\n // Accept a path prefix as well.\n if (name.indexOf(skipModules[i]) === 0) {\n return true;\n }\n }\n }",
"function isOnLearn() {\n return window.location.href.indexOf(\"learn.uwaterloo.ca/d2l\") != -1;\n}",
"isRoot() {\n\n return this.type == 'module';\n }",
"static isLateBoundSymbol(symbol) {\n // eslint-disable-next-line no-bitwise\n if (symbol.flags & ts.SymbolFlags.Transient &&\n symbol.checkFlags === ts.CheckFlags.Late) {\n return true;\n }\n return false;\n }",
"function isHttpEndpoint(pathname) {\n for (let index in httpEndpoints) {\n if (httpEndpoints[index][0] == pathname) {\n return true;\n }\n }\n return false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to assign a MDT role to a computer. | async function assignComputer(
computerName,
computerId,
classroomNumber,
roleName
) {
await sqlQuery(`DELETE FROM Settings WHERE ID=${computerId} AND Type='C'`);
await sqlQuery(
`INSERT INTO Settings (Type,ID,ComputerName,OSDComputerName,OrgName,FullName,JoinWorkgroup) VALUES ('C',${computerId},'${computerName} ','${computerName}','Windows User','Windows User','${classroomNumber}')`
);
await sqlQuery(`DELETE FROM Settings_Roles WHERE ID=${computerId}`);
await sqlQuery(
`INSERT INTO Settings_Roles (Type,ID,Sequence,Role) VALUES ('C',${computerId},1,'Basic Applications')`
);
await sqlQuery(
`INSERT INTO Settings_Roles (Type,ID,Sequence,Role) VALUES ('C',${computerId},2,'${roleName}')`
);
// If the computer is the teachers computer, then add teacher applications.
if (computerName.toLowerCase().includes("teacher")) {
await sqlQuery(
`INSERT INTO Settings_Roles (Type,ID,Sequence,Role) VALUES ('C',${computerId},3,'Teacher Applications')`
);
await sqlQuery(
`INSERT INTO Settings_Roles (Type,ID,Sequence,Role) VALUES ('C',${computerId},4,'${roleName}-Teacher')`
);
}
} | [
"function assignRole(member) {\n // Use the nickname if it exists, otherwise, stick with the username\n let name = (member.nickname != null) ? member.nickname : member.user.username;\n name = name.slice(0,1); // We only want the first letter\n\n let rolesToRemove = [];\n let roleToAdd = '';\n\n for(let i in rolesToAssign){ // For every\n if (rolesToAssign.hasOwnProperty(i)){\n // This block fetches the ID for the role name we have\n let id = member.guild.roles.cache.filter(function(value, key, collection){\n return value.name.toLowerCase() === rolesToAssign[i].toLowerCase()\n }).entries().next().value[0];\n\n if (name.match(i)) { // Check the username against the regex\n roleToAdd = id // Set it as the role to add\n } else {\n rolesToRemove.push(id) // Add it to the list of roles to remove\n }\n\n }\n }\n if(rolesToRemove.length > 0) {\n member.roles.remove(rolesToRemove); // Remove our list of roles\n }\n if(roleToAdd.length > 0) {\n member.roles.add(roleToAdd); // Add our one role\n }\n}",
"function assignRoleTo(correctStudyRole) {\n try {\n if (DEBUG) {\n wom.log(DEBUG_PREFIX + \"executing assignRoleTo function\")\n }\n var assignedOwner = validateCurrentOwner(correctStudyRole, owner);\n if (assignedOwner) {\n this.setQualifiedAttribute(\"owner\", assignedOwner);\n if (DEBUG) {\n wom.log(DEBUG_PREFIX + \"Assigned owner is \" + assignedOwner.lastName);\n }\n }\n } catch (e) {\n wom.log(DEBUG_PREFIX + \"ERROR: \" + e.description);\n throw e;\n }\n }",
"function manageRoles(cmd){\n try{\n\t//console.log(cmd.message.channel instanceof Discord.DMChannel);\n\t//if (cmd.message.channel instanceof Discord.DMChannel) { sendMessage(cmd, \"This command currently only works in guild chats\"); return \"failure\"; }\n\tconst openRoles = roleNames.openRoles, voidRoles = roleNames.voidRoles;\n const guild = client.guilds.find(\"name\", \"Terra Battle\");\n\tconst guildRoles = guild.roles; //cmd.message.guild.roles;\n\tvar roles = cmd.details.split(\",\"), guildMember = guild.members.get(cmd.message.author.id);\n \n var feedback = \"\";\n\t//console.log(guildMember);\n\t\n\t//Check to make sure the requested role isn't forbidden\n\t//Find role in guild's role collection\n\t//Assign role (or remove role if already in ownership of)\n\t//Append response of what was done to \"feedback\"\n\troles.forEach(function(entry){\n\t\tentry = entry.trim();\n\t\tlowCaseEntry = entry.toLowerCase();\n\t\t\n\t\t//Ignore any attempts to try to get a moderator, admin, companion, bot, or specialty role.\n\t\t//Ignore: metal minion, wiki editor, content creator, pvp extraordinare\n /*voidRoles.forEach(\n function(currentValue){\n \n }\n );*/ //TODO: Manage Void Role rejection more elegantly\n\t\tif (!(voidRoles.some( x => lowCaseEntry.includes(x) )) ){\n\t\t\t\n\t\t\t//run requested role name through the roleName DB\n\t\t\tvar roleCheck = openRoles.get(lowCaseEntry); //TODO: Make a DB that allows for server-specific role name checks\n\t\t\tvar role;\n\t\t\t\n\t\t\ttry{ role = guildRoles.find(\"name\", roleCheck); }\n\t\t\tcatch (err) { \n\t\t\t\t//Role didn't exist\n\t\t\t\tconsole.log(err.message);\n console.log(\"User: \" + cmd.message.author.name);\n\t\t\t}\n\t\t\t\n\t\t\tif( typeof role === 'undefined' || role == null ){ feedback += \"So... role '\" + entry + \"' does not exist\\n\"; }\n\t\t\telse if( guildMember.roles.has(role.id) ) {\n\t\t\t\tguildMember.removeRole(role);\n\t\t\t\tfeedback += \"I removed the role: \" + role.name + \"\\n\"; }\n\t\t\telse {\n\t\t\t\tguildMember.addRole(role);\n\t\t\t\tfeedback += \"I assigned the role: \" + role.name + \"\\n\"; }\n\t\t} else { feedback += \"FYI, I cannot assign '\" + entry + \"' roles\"; }\n\t\t//guildMember = cmd.message.member;\n\t});\n\t//return feedback responses\n\t( feedback.length > 0 ? cmd.message.channel.send(feedback) : \"\" );\n } catch (err) {\n console.log(err.message);\n console.log(\"User: \" + cmd.message.author.name);\n }\n}",
"function setRole(characterName, role) {\n var data = {};\n data.characterName = characterName;\n data.role = role;\n\n var promise = $http.post(UtilsSvc.getUrlPrefix() + \"/api/character/role/\", data).then(function(response) {\n return response.data;\n });\n return promise;\n }",
"function promoteToTeacher(id)\r\n{\r\n //Find the participant in the database\r\n participant = getParticipantByID(id);\r\n if(participant != null)\r\n {\r\n if(participant.status == 'Student')\r\n {\r\n participant.status = 'Teacher';\r\n }\r\n }\r\n}",
"addViewingRole({initiator, target, day, role}) {\n const {viewingRole} = this.#status[initiator];\n viewingRole.push({target, day, role})\n this.#actions = [];\n }",
"createRole (roleId, inheritRoleId = undefined, description = undefined) {\n assert.equal(typeof roleId, 'string', 'roleId must be number')\n if (typeof inheritRoleId !== 'undefined') {\n assert.equal(typeof inheritRoleId, 'number', 'inheritRoleId must be number')\n }\n if (typeof description !== 'undefined') {\n assert.equal(typeof description, 'string', 'description must be string')\n }\n return this._apiRequest('/role', 'POST', {\n id: roleId,\n inherit_from_id: inheritRoleId,\n description\n })\n }",
"'addUserRole'(userid, role)\n {\n Roles.addUsersToRoles(userid,role);\n\n\n }",
"function deploy(cb) {\n console.log(\"deploying with the role name 'assigner' in metadata ...\");\n var req = {\n fcn: \"init\",\n args: [],\n metadata: \"assigner\"\n };\n if (networkMode) {\n req.chaincodePath = \"github.com/asset_management_with_roles/\";\n } else {\n req.chaincodeName = \"asset_management_with_roles\";\n }\n var tx = admin.deploy(req);\n tx.on('submitted', function (results) {\n console.log(\"deploy submitted: %j\", results);\n });\n tx.on('complete', function (results) {\n console.log(\"deploy complete: %j\", results);\n chaincodeID = results.chaincodeID;\n return assign(cb);\n });\n tx.on('error', function (err) {\n console.log(\"deploy error: %j\", err.toString());\n return cb(err);\n });\n}",
"function addRole() {\n inquirer\n .prompt([\n {\n type: \"input\",\n message: \"What is the name of the new employee role?\",\n name: \"title\"\n },\n {\n type: \"input\",\n message: \"How much is the new salary of the employee's role?\",\n name: \"salary\"\n },\n {\n type: \"list\",\n message: \"In which department is the new role?\",\n name: \"id\",\n choices: showdepartments\n }\n ])\n .then(function (response) {\n \n addEmployeeRole(response);\n })\n }",
"function attachToRole(req, res) {\n Role.findByIdAndUpdate(req.params.id, res.locals.attachment).catch(function(\n err\n ) {\n console.log(err);\n });\n}",
"function promoteEmployee(id,callback)\n{\n db.run(\"UPDATE Employees SET role='Manager' WHERE rowid=?\",\n [id],\n function(err) { callback(); });\n}",
"attachToRole(role) {\n if (this.roles.find(r => r === role)) {\n return;\n }\n this.roles.push(role);\n }",
"SET_ACTIF_ADMINISTRATOR(state,payload){\n state.administrator = payload;\n }",
"function setRoles(lobby, roles) {\n getGame(lobby).roles = roles;\n}",
"function seperateRole(){\n\n}",
"function setRoleplayInfo(name) {\n alt.emitServer('character:SetRoleplayInfo', name);\n showCursor(false);\n}",
"function assignTask(taskStringId, assigneeStringId) {\n client.tasks.update(taskStringId, {assignee: assigneeStringId});\n}",
"function modifyRoleRoleSel(empl) {\n const employee = empl;\n db.query(\"SELECT id, title FROM role\", function (err, res) {\n inquirer\n .prompt([\n {\n type: \"list\",\n message: \"And what will be their new role be?\",\n name: \"modifyRoleChangedR\",\n choices: function () {\n const choiceArrayRole = [];\n for (let i = 0; i < res.length; i++) {\n choiceArrayRole.push(`${res[i].id} | ${res[i].title}`);\n }\n return choiceArrayRole;\n },\n },\n ])\n .then(function (role) {\n const newRole = parseInt(role.modifyRoleChangedR.slice(0, 5));\n const changingEmpl = role.employee;\n let query = db.query(\n \"UPDATE employee SET role_id = ? WHERE id = ?\",\n [newRole, employee],\n function (err, res) {\n if (err) {\n } else {\n console.log(\"All set!\");\n firstQ();\n }\n }\n );\n });\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
preformat raw data including raw RIS | function preformatRawData(metaData, parser) {
//fix title, year, misc and journal abbreviation
metaData["citation_download"] = metaData["citation_download"].replace(/JO[\t\ ]+[\-]+[\t\ ]+/,"JA - ").replace(/(?:PY|N1)[\t\ ]+[\-]+[\t\ ]+/g,"BIT - ").trim();
} | [
"function changeFormatData(retails) {\n\tlet output = [];\n\t// Put ur code here\n\n\t// loop through the retails array\n\tfor (let i = 0; i < retails.length; i++) {\n\t\tlet row = [];\n\n\t\t// loop through the rows\n\t\tfor (let j = 0; j < retails[i].length; j++) {\n\t\t\tlet temp = '';\n\n\t\t\t// loop through the characters\n\t\t\tfor (let k = 0; k < retails[i][j].length; k++) {\n\t\t\t\t// if '-', push into row and reset temp\n\t\t\t\t// otherwise, put the string into temp\n\t\t\t\tif (retails[i][j][k] === '-') {\n\t\t\t\t\trow.push(temp);\n\t\t\t\t\ttemp = '';\n\t\t\t\t} else {\n\t\t\t\t\ttemp += retails[i][j][k];\n\t\t\t\t}\n\n\t\t\t\t// push the last set of string as a number into the row array\n\t\t\t\tif (k === retails[i][j].length - 1) {\n\t\t\t\t\trow.push(Number(temp));\n\t\t\t\t\ttemp = '';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toutput.push(row);\n\t}\n\treturn output;\n}",
"function prepareData(){\n testData = toDataFormat(Array.from(testData));\n trainData = toDataFormat(Array.from(tData));\n}",
"function parseAllDayData(raw_data) {\n\n var table_data = [],\n date, avrg, min, max, billing_95th;\n\n for(var i = 0; i < raw_data.length; i++) {\n date = raw_data[i]['date_type'];\n avrg = transSpeed(raw_data[i]['ifIn_avrg']) + ' / ' + transSpeed(raw_data[i]['ifOut_avrg']);\n min = transSpeed(raw_data[i]['ifIn_min']) + ' / ' + transSpeed(raw_data[i]['ifOut_min']);\n max = transSpeed(raw_data[i]['ifIn_max']) + ' / ' + transSpeed(raw_data[i]['ifOut_max']);\n billing_95th = transSpeed(raw_data[i]['ifIn_95th']) + ' / ' + transSpeed(raw_data[i]['ifOut_95th']);\n table_data.push([date, billing_95th, avrg, max, min]);\n }\n\n return table_data;\n}",
"function preProcessData(data) {\n\t\t\t// set defaults for values that may be missing from older streams\n\t\t\tsetIfMissing(data, \"rollingCountBadRequests\", 0);\n\t\t\t// assert all the values we need\n\t\t\tvalidateData(data);\n\t\t\t// escape string used in jQuery & d3 selectors\n\t\t\tdata.escapedName = data.name.replace(/([ !\"#$%&'()*+,./:;<=>?@[\\]^`{|}~])/g,'\\\\$1') + '_' + data.index;\n\t\t\t// do math\n\t\t\tconvertAllAvg(data);\n\t\t\tcalcRatePerSecond(data);\n\t\t}",
"getrenDetFormattedData(renewalsData) {\n\n var renewalTransformedDetails = {\n client: {\n type: renewalsData.market,\n renewalLetter: {\n label: \"Renewal Letter\",\n endpoint: \"\"\n },\n aggregatedPremiums: [\n {\n label: \"Medical\",\n content: {\n current: {\n label: \"Current\",\n content: \"$\"+Math.round(renewalsData.currentMedicalRate * 100) / 100\n },\n renewal: {\n label: \"Renewal\",\n content: \"$\"+Math.round(renewalsData.renewalMedicalRate * 100) / 100\n },\n increase: true\n }\n },\n {\n label: \"Dental\",\n content: {\n current: {\n label: \"Current\",\n content: \"\"\n },\n renewal: {\n label: \"Renewal\",\n content: \"\"\n },\n increase: true\n }\n },\n {\n label: \"Vision\",\n content: {\n current: {\n label: \"Current\",\n content: \"\"\n },\n renewal: {\n label: \"Renewal\",\n content: \"\"\n },\n increase: true\n }\n },\n\n ],\n fields: [\n {\n label: \"Client ID\",\n content: \"\"\n },\n {\n label: \"Renewal Date\",\n content: \"\"\n },\n {\n label: \"Market\",\n content: \"\"\n },\n {\n label: \"State\",\n content: \"\"\n },\n {\n label: \"Products\",\n content: \"\"\n },\n {\n label: \"Exchange\",\n content: renewalsData.exchange\n },\n {\n label: \"Rating Area\",\n content:(renewalsData.medicalFutureRatingArea || renewalsData.medicalCurrentRatingArea || renewalsData.dentalFutureRatingArea || renewalsData.dentalCurrentRatingArea || renewalsData.pdFutureRatingArea || renewalsData.pdCurrentRatingArea)\n },\n {\n label: \"Association\",\n content: \"\"\n },\n {\n label: \"SIC\",\n content: \"\"\n },\n {\n label: \"Group Size\",\n content: renewalsData.size\n }\n ]\n },\n plans: ([]).concat(renewalsData.dentalProducts,\n renewalsData.visionProducts, renewalsData.medicalProducts).filter(function( element ) {\n return element !== undefined;\n })\n .map((val, ind)=>{\n return(\n {\n plan: {\n heading: \"Plan \"+(ind+1),\n columns: [\n {\n label: \"\",\n content: [\"Current\", \"Renewals\"]\n },\n {\n label: \"Plan\",\n content: [val.currentProduct.currentContractPlanName, val.renewalProduct.currentContractPlanName]\n },\n {\n label: \"Contract Code\",\n content: [val.currentProduct.currentContractPlanCode, val.renewalProduct.currentContractPlanCode]\n },\n {\n label: \"Premium\",\n content: [\"$\"+Math.round(val.currentProduct.monthlyPremium * 100) / 100,\n \"$\"+Math.round(val.renewalProduct.monthlyPremium * 100) / 100]\n },\n {\n label: \"Subscribers\",\n content: [val.currentProduct.subscribers, val.renewalProduct.subscribers]\n },\n {\n label: \"Subsidy\",\n content: [\"\",\"\"]\n },\n {\n label: \"Dependants Coverage\",\n content: [\"\",\"\"]\n }\n ]\n },\n employees: {\n heading: \"Employees\",\n columns: [\n {\n label: \"Employee\",\n content: val.employees.map((empVal,empInd)=>{\n return((empVal.name).toLowerCase())\n })\n },\n {\n label: \"Coverage\",\n content: val.employees.map((empVal,empInd)=>{\n return(empVal.coverage)\n })\n },\n {\n label: \"Age\",\n content: val.employees.map((empVal,empInd)=>{\n return(empVal.age)\n })\n },\n {\n label: \"Current Rate\",\n content: val.employees.map((empVal,empInd)=>{\n return(\"$\"+ Math.round(empVal.currentRate * 100) / 100)\n })\n },\n {\n label: \"New Rate\",\n content: val.employees.map((empVal,empInd)=>{\n return(empVal.newRate)\n })\n }\n ]\n }\n }\n\n )\n }),\n\n };\n return renewalTransformedDetails;\n}",
"function reformatData(data, vendor){\n let price = data.price.toString();\n let link = data.link.toString();\n return {\"Vendor\":vendor, \"Price\":price, \"Link\":link};\n}",
"function updateData() {\n\tPapa.parse('/data/vatsim-data.txt', {\n\t\tdownload: true,\n\t\tdelimiter: ':',\n\t\tcomments: ';',\n\t\tfastMode: true,\n\t\tcomplete: parseData\n\t});\n}",
"async function flatFileInterpreter(data, columnsToFormat, pool, sql) {\n let rowsArray = data.split(\"\\r\\n\");\n let rowLength = (rowsArray[0].split(\"|\")).length;\n let firstLine = rowsArray[0].split(\"|\");\n let subdividedRowsArray = [];\n let longestInColumn = [];\n let longestItemInColumn = [];\n let easyView = [];\n for (let i = 0; i < rowLength; i++) {\n longestInColumn[i] = 0;\n }\n for (let k = 0; k < (rowsArray.length - 1); k++) {\n if (k != 0) {\n subdividedRowsArray[k - 1] = rowsArray[k].split(\"|\");\n for (let i = 0; i < subdividedRowsArray[k - 1].length; i++) {\n if (subdividedRowsArray[k - 1][i] == \"\") {\n subdividedRowsArray[k - 1][i] = null;\n }\n if (columnsToFormat.indexOf(i) > -1 && subdividedRowsArray[k - 1][i] != null) {\n subdividedRowsArray[k - 1][i] = parseFloat(subdividedRowsArray[k - 1][i]);\n }\n if (subdividedRowsArray[k - 1][i] != null && subdividedRowsArray[k - 1][i].toString().length > longestInColumn[i]) {\n longestInColumn[i] = subdividedRowsArray[k - 1][i].toString().length;\n longestItemInColumn[i] = subdividedRowsArray[k - 1][i];\n }\n }\n }\n }\n for (let i = 0; i < rowLength; i++) {\n easyView[i] = firstLine[i] + \" \" + longestInColumn[i] + \" \" + longestItemInColumn[i];\n }\n console.log(easyView);\n await tableInserter(pool, subdividedRowsArray, sql);\n return true;\n}",
"formatRawSequencingFileQuery() {\n const query = this.buildBasicQuery();\n query.addKeyValue(`${this._fileQueryKey}.output_type`, this._outputType);\n query.addKeyValue(`${this._fileQueryKey}.output_category`, this._outputCategory);\n this._rawSequencingFileQueryString = query.format();\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}",
"function adjustDataFieldNames(data) {\n var adjustedData = [];\n _.each(data, function(rowItem) {\n var adjustedRowItem = adjustFieldNames(rowItem);\n adjustedData.push(adjustedRowItem);\n });\n return adjustedData;\n }",
"convertSourcemap(sourcemap) {\n const newSourcemap = [];\n\n for (const entry of sourcemap) {\n let line = 1;\n let column = 0;\n\n for (let i = 0; i < entry[0]; i++) {\n column++;\n if (this.source[i] === '\\n') {\n line++;\n column = 0;\n }\n }\n\n if (this.smc) {\n const original = this.smc.originalPositionFor({line, column});\n\n if (original) {\n newSourcemap.push({\n original: {\n source: original.source,\n line: original.line,\n column: original.column,\n },\n generated: {\n pos: sourcemap[0][0],\n line,\n column\n },\n length: sourcemap[0][1]\n });\n } else {\n newSourcemap.push({\n original: {\n source: '',\n line,\n column\n },\n generated: {\n pos: sourcemap[0][0],\n line,\n column\n },\n length: sourcemap[0][1]\n });\n }\n } else {\n newSourcemap.push({\n original: {\n source: '',\n line,\n column\n },\n generated: {\n pos: sourcemap[0][0],\n line,\n column\n },\n length: sourcemap[0][1]\n });\n }\n }\n\n return newSourcemap;\n }",
"function normalizer(rawData) {\n const rawCustomerData = get(rawData, 'data.createCustomer.customer', null);\n const firstName = get(rawCustomerData, 'firstname', null);\n const lastName = get(rawCustomerData, 'lastname', null);\n const isSubscribed = get(rawCustomerData, 'is_subscribed', null);\n return {\n account: {\n firstName,\n lastName,\n isSubscribed,\n },\n };\n}",
"function formatData(data){\n //var severityNames = [\"unknown\", \"negligible\", \"low\", \"medium\", \"high\", \"critical\"]\n var severityNames = [\"Critical\", \"High\", \"Medium\", \"Low\"];\n var packageNames = [];\n var blockData = [];\n data = data.sort(function(a, b) { \n return (a.Critical + a.High + a.Medium + a.Low) < (b.Critical + b.High + b.Medium + b.Low);\n //return (b.critical * 3 + b.high * 2 + b.medium * 1 ) - (a.critical * 3 + a.high * 2 + a.medium * 1 );\n });\n\n for(var i = 0; i < data.length; i++){\n var y = 0;\n packageNames.push(data[i].package);\n for(var j = 0; j < severityNames.length; j++){\n var height = parseFloat(data[i][severityNames[j]]);\n var block = {'y0': parseFloat(y),\n 'y1': parseFloat(y) + parseFloat(height),\n 'height': height,\n 'x': data[i].package,\n 'cluster': severityNames[j]};\n y += parseFloat(data[i][severityNames[j]]);\n blockData.push(block);\n }\n }\n\n return {\n blockData: blockData,\n packageNames: packageNames,\n severityNames: severityNames\n };\n\n}",
"convertBodyData(bodyData) { return convertBodyData(bodyData); }",
"function formatData(data) {\n return data.map((el) => {\n return {\n x: new Date(el[0]).toLocaleString().substr(11,9),\n y: el[1].toFixed(2),\n };\n });\n }",
"tgaParse(use_rle, use_pal, header, offset, data) {\n let pixel_data, pixel_size, pixel_total, palettes;\n pixel_size = header.pixel_size >> 3;\n pixel_total = header.width * header.height * pixel_size;\n // Read palettes\n if (use_pal) {\n palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));\n }\n // Read RLE\n if (use_rle) {\n pixel_data = new Uint8Array(pixel_total);\n let c, count, i;\n let shift = 0;\n let pixels = new Uint8Array(pixel_size);\n while (shift < pixel_total) {\n c = data[offset++];\n count = (c & 0x7f) + 1;\n // RLE pixels.\n if (c & 0x80) {\n // Bind pixel tmp array\n for (i = 0; i < pixel_size; ++i) {\n pixels[i] = data[offset++];\n }\n // Copy pixel array\n for (i = 0; i < count; ++i) {\n pixel_data.set(pixels, shift + i * pixel_size);\n }\n shift += pixel_size * count;\n }\n else {\n // Raw pixels.\n count *= pixel_size;\n for (i = 0; i < count; ++i) {\n pixel_data[shift + i] = data[offset++];\n }\n shift += count;\n }\n }\n }\n else {\n // RAW Pixels\n pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));\n }\n return {\n pixel_data: pixel_data,\n palettes: palettes\n };\n }",
"function parsetransData(d){\n \n return{\n geoid_2: +d.geoid_2,\n geography: d.geo_display,\n total_population: +d.HC01_EST_VC01,\n age_group: [\n {'16-19': +d.HC01_EST_VC03},\n {'20-24': +d.HC01_EST_VC04},\n {'25-44': +d.HC01_EST_VC05},\n {'45-54': +d.HC01_EST_VC06},\n {'55-59': +d.HC01_EST_VC07},\n {'60+': +d.HC01_EST_VC08} \n ],\n median_age: +d.HC01_EST_VC10,\n earnings_group: [\n {'1-9999': +d.HC01_EST_VC42},\n {'10000-14999': +d.HC01_EST_VC43},\n {'15000-24999': +d.HC01_EST_VC44},\n {'25000-34999': +d.HC01_EST_VC45},\n {'35000-49999': +d.HC01_EST_VC46},\n {'50000-64999': +d.HC01_EST_VC47},\n {'65000-74999': +d.HC01_EST_VC48},\n {'75000+': +d.HC01_EST_VC49}\n ],\n median_earnings: +d.HC01_EST_VC51,\n industries_group: [\n {'argriculture': +d.HC01_EST_VC69},\n {'construction': +d.HC01_EST_VC70},\n {'manufacturing': +d.HC01_EST_VC71},\n {'wholesale trade': +d.HC01_EST_VC72},\n {'retail trade': +d.HC01_EST_VC73},\n {'transportation&warehouse': +d.HC01_EST_VC74},\n {'information&finance': +d.HC01_EST_VC75},\n {'professional&scientific services': +d.HC01_EST_VC76},\n {'healthcare&educational&social assistance': +d.HC01_EST_VC77},\n {'entertainment&recreation': +d.HC01_EST_VC78},\n {'public administration': +d.HC01_EST_VC80},\n {'armed forces': +d.HC01_EST_VC81},\n {'other services': +d.HC01_EST_VC79} \n ],\n time_group: [{'10': +d.HC01_EST_VC103},\n {'10-14': +d.HC01_EST_VC104},\n {'15-19': +d.HC01_EST_VC105},\n {'20-24': +d.HC01_EST_VC106},\n {'25-29': +d.HC01_EST_VC107},\n {'30-34': +d.HC01_EST_VC108},\n {'35-44': +d.HC01_EST_VC109},\n {'45-59': +d.HC01_EST_VC110},\n {'60+': +d.HC01_EST_VC111} \n ],\n mean_time: +d.HC01_EST_VC112\n\n //backup as follows\n // travel_time_work_10: +d.HC01_EST_VC103,\n // travel_time_work_10_14: +d.HC01_EST_VC104,\n // travel_time_work_15_19: +d.HC01_EST_VC105,\n // travel_time_work_20_24: +d.HC01_EST_VC106,\n // travel_time_work_25_29: +d.HC01_EST_VC107,\n // travel_time_work_30_34: +d.HC01_EST_VC108,\n // travel_time_work_35_44: +d.HC01_EST_VC109,\n // travel_time_work_45_59: +d.HC01_EST_VC110,\n // travel_time_work_60: +d.HC01_EST_VC111, \n \n // age_16_19: +d.HC01_EST_VC03,\n // age_20_24: +d.HC01_EST_VC04,\n // age_25_44: +d.HC01_EST_VC05,\n // age_45_54: +d.HC01_EST_VC06,\n // age_55_59: +d.HC01_EST_VC07,\n // age_60: +d.HC01_EST_VC08,\n \n // earnings_1_9999: +d.HC01_EST_VC42,\n // earnings_10000_14999: +d.HC01_EST_VC43,\n // earnings_15000_24999: +d.HC01_EST_VC44,\n // earnings_25000_34999: +d.HC01_EST_VC45,\n // earnings_35000_49999: +d.HC01_EST_VC46,\n // earnings_50000_64999: +d.HC01_EST_VC47,\n // earnings_65000_74999: +d.HC01_EST_VC48,\n // earnings_75000: +d.HC01_EST_VC49,\n\n // agriculture: +d.HC01_EST_VC69,\n // construction: +d.HC01_EST_VC70,\n // manufacturing: +d.HC01_EST_VC71,\n // wholesale_trade: +d.HC01_EST_VC72,\n // retail_trade: +d.HC01_EST_VC73,\n // transportation_warehouse: +d.HC01_EST_VC74,\n // information_finance_realestate: +d.HC01_EST_VC75,\n // professional_scientific_waste_services: +d.HC01_EST_VC76,\n // educational_healthcare_social_assistance: +d.HC01_EST_VC77,\n // arts_entertainment_recreation_accommodation_food_services: +d.HC01_EST_VC78,\n // other_services_no_public_administration: +d.HC01_EST_VC79,\n // public_administration: +d.HC01_EST_VC80,\n // armed_forces: +d.HC01_EST_VC81,\n \n }\n}",
"read_data_info() {\n this.json.data_info = {};\n this.add_string(this.json.data_info, \"date_and_time\");\n this.add_string(this.json.data_info, \"scan_summary\");\n this.json.data_info.apply_data_calibration = this.ole.read_bool();\n this.add_string(this.json.data_info, \"data_calibration_file\");\n this.add_string(this.json.data_info, \"certificate_file\");\n this.add_string(this.json.data_info, \"system_file\");\n this.add_string(this.json.data_info, \"pre_scan_addon_description\");\n this.add_string(this.json.data_info, \"post_scan_addon_description\");\n this.add_string(this.json.data_info, \"pre_scan_addon_filename\");\n this.add_string(this.json.data_info, \"post_scan_addon_filename\");\n this.add_string(this.json.data_info, \"type_and_units\");\n this.add_string(this.json.data_info, \"type_and_units_code\");\n this.add_string(this.json.data_info, \"auxiliary_type_and_units\");\n this.add_string(this.json.data_info, \"auxiliary_type_and_units_code\");\n this.json.data_info.apply_reference = this.ole.read_bool();\n this.add_string(this.json.data_info, \"reference_type\");\n this.add_string(this.json.data_info, \"reference_file\");\n this.add_string(this.json.data_info, \"reference_parameter\");\n this.json.data_info.file_time = this.ole.read_systemtime();\n\n // Read and discard measurement units and types;\n // these are in the data info as well\n // ar.Read(Buffer, 4*sizeof(int));\n this.ole.skip_uint32(4);\n\n // Right axis settings\n // ar >> TempInt;\n // ar.Read(Buffer, m_nNoOfDataSets*sizeof(int));\n this.ole.skip_uint32();\n this.ole.skip_uint32(this.json.data_set.length);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws lines to other keypoints if they exist | _drawLines(keypoint) {
if (keypoint.indexLabel < 0) return;
if (!this._edges.hasOwnProperty(keypoint.indexLabel)) return;
let otherIndices = this._edges[keypoint.indexLabel];
otherIndices.forEach(i => {
let k2 = this._labelled[i];
if (!k2) return;
let edge = [keypoint.indexLabel, i];
this._drawLine(edge, keypoint, k2);
});
} | [
"function drawKeypoints() {\n // Loop through all the poses detected\n for (let i = 0; i < min(poses.length, 1); i++) {\n // For each pose detected, loop through all the keypoints\n for (let j = 0; j < poses[i].pose.keypoints.length; j++) {\n // A keypoint is an object describing a body part (like rightArm or leftShoulder)\n let keypoint = poses[i].pose.keypoints[j];\n // Only draw an ellipse is the pose probability is bigger than 0.2\n if (keypoint.score > 0.2) {\n if (j == 9) {\n rightWristX = keypoint.position.x;\n rightWristY = keypoint.position.y;\n\n pg.stroke(30, 30, 650);\n pg.strokeWeight(5);\n pg.line(rightWristX-100, rightWristY-90, pRightWristX-100, pRightWristY-90);\n\n pRightWristX = rightWristX;\n pRightWristY = rightWristY;\n }\n }\n }\n }\n}",
"function drawCurve() {\n\tfor(let i=0;i<curvePts.length-1;i++) {\n\t\tlet pt1 = curvePts[i];\n\t\tlet pt2 = curvePts[i+1];\n\t\tdrawLine(pt1.x, pt1.y, pt2.x, pt2.y, 'rgb(0,255,0)');\n\t}\n}",
"breshnamDrawLine (point0, point1) {\n let x0 = point0.x >> 0;\n let y0 = point0.y >> 0;\n let x1 = point1.x >> 0;\n let y1 = point1.y >> 0;\n let dx = Math.abs(x1 - x0);\n let dy = Math.abs(y1 - y0);\n let color = new BABYLON.Color4(1,1,0,1);\n\n if(dy > dx){\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dx - dy;\n\n for(let y=y0; y!=y1; y=y+sy){\n this.drawPoint(new BABYLON.Vector2(x0, y), color);\n if(err >= 0) {\n x0 += sx ;\n err -= dy;\n }\n err += dx;\n }\n }\n else{\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dy - dx;\n\n for(let x=x0; x!=x1; x=x+sx){\n this.drawPoint(new BABYLON.Vector2(x, y0), color);\n if(err >= 0) {\n y0 += sy ;\n err -= dx;\n }\n err += dy;\n }\n }\n }",
"function drawControlLines() {\n\tif(!showControlLines) return;\n\tfor(let i=0; i<controlPts.length; i++) {\n\t\tlet pt = controlPts[i];\n\t\tdrawRectangle(pt.x-dotSize, pt.y-dotSize, 2*dotSize, 2*dotSize, 'rgb(255,0,0)');\n\t}\n\tfor(let i=0; i<controlPts.length-1; i++) {\n\t\tlet pt1 = controlPts[i];\n\t\tlet pt2 = controlPts[i+1];\n\t\tdrawLine(pt1.x, pt1.y, pt2.x, pt2.y, 'rgb(32,32,255)');\n\t}\n\tif(curveType==Hermite) {\n\t\tfor(let i=0; i<controlPts.length; i++) {\n\t\t\tlet pt = controlPts[i];\n\t\t\tdrawCircle(pt.x+pt.dx, pt.y+pt.dy, dotSize, 'rgb(255,160,0)');\n\t\t\tdrawLine(pt.x, pt.y, pt.x+pt.dx, pt.y+pt.dy, 'rgb(255,160,0)');\n\t\t}\t\t\n\t}\n}",
"function drawLine() {\n let draw = game.add.graphics();\n draw.lineStyle(1, 0xffffff, .3);\n\n draw.moveTo(star1.worldPosition.x + 8, star1.worldPosition.y + 8)\n draw.beginFill();\n draw.lineTo(star2.worldPosition.x + 8, star2.worldPosition.y + 8);\n draw.endFill();\n\n connections.push({\n drawer: draw,\n star1: [star1.worldPosition.x + 8, star1.worldPosition.y + 8],\n star2: [star2.worldPosition.x + 8, star2.worldPosition.y + 8]\n });\n deselectStars();\n }",
"function draw_lines_between_gnodes() {\n\n // gnodes is a global var\n gnodes.each( function(d, i) {\n // - for each node/d\n for (i in d.talksto) {\n // - find all they talk to\n d3.selectAll(\"image#\" + d.talksto[i] )\n .each( function(dd, ii) {\n //\n //draw_a_line( d, dd);\n\n //console.log( d.midx, d.midy, dd.midx, dd.midy);\n var cls1 = d.id + \"-\" + dd.id;\n var cls2 = dd.id + \"-\" + d.id;\n\n if (d3.selectAll('line.' + cls1).size() ||\n d3.selectAll('line.' + cls2).size() ) {\n console.log(\"not line: \" + cls1 + \" /or/ \" + cls2 );\n } else {\n classes = [ cls1, cls2, d.system, dd.system ]\n svg.append('line')\n .style(\"stroke\", \"black\") // look up CRYPTO RISK\n .attr(\"x1\", d.midx)\n .attr(\"y1\", d.midy)\n .attr(\"x2\", dd.midx)\n .attr(\"y2\", dd.midy)\n .attr('class', unique(classes).join(\" \") );\n }\n }); //each\n } // NOPE\n });\n }",
"addLineToLinesDrawn() {\n if (!Array.isArray(this._currentLineCoordinates)) throw Error('Line coordinates must be an array')\n this._linesDrawn.push(this._currentLineCoordinates)\n }",
"drawLine() {\r\n line(this.left.x, this.left.y, this.right.x, this.right.y);\r\n }",
"function draw_travels() {\n removeLines();\n for (var i = 0, len = data.length; i < len; i++) {\n drawLine(data[i])\n }\n}",
"function draw_lines(container, PreviousPos, CurrentPos, draw_dummy_lines, allow_horizontal, allow_vertical) {\n\n // default paramtere values\n draw_dummy_lines = typeof draw_dummy_lines !== 'undefined' ? draw_dummy_lines : false;\n allow_horizontal = typeof allow_horizontal !== 'undefined' ? allow_horizontal : true;\n allow_vertical = typeof allow_vertical !== 'undefined' ? allow_vertical : true;\n\n // delete old line first\n delete_old_lines(container);\n\n var time_path = container.find(\"path.time_path\"),\n voltage_path = container.find(\"path.voltage_path\"),\n pathBgEl = container.find(\"rect.voltage_time_path_bg\");\n\n // if Previous Position is already selected then draw line and draw text label\n if (PreviousPos.length != 0) {\n // draw line using previous pos and current pos\n var start_x = PreviousPos[0], start_y = PreviousPos[1], end_x = CurrentPos[0], end_y = CurrentPos[1];\n var x_diff = CurrentPos[0] - PreviousPos[0], y_diff = CurrentPos[1] - PreviousPos[1], buffer = corner_edge;\n\n // For debugging purpose\n // console.log(start_x, start_y, end_x, end_y, x_diff, y_diff);\n\n var horizontal_line = false, vertical_line = false;\n\n // buffer value decides whether horizontal or vertical line to be drawn\n if ((y_diff <= buffer && y_diff >= -buffer) && allow_horizontal) {\n // console.log(\"horizontal\");\n horizontal_line = true;\n\n // y coordinate is fixed for horizontal line\n setHorizontalPathData(time_path, start_x, end_x, start_y, end_y, corner_edge);\n setRectAttrFromPath(pathBgEl, time_path, '');\n\n // set measured time value in text label\n updateTextLabelEl(container, start_x, start_y, end_x, end_y, time_1_second_in_pixels, 0, corner_edge);\n }\n if ((x_diff <= buffer && x_diff >= -buffer) && allow_vertical) {\n // console.log(\"vertical\");\n vertical_line = true;\n\n // x coordinate is fixed for line\n setVerticalPathData(voltage_path, start_x, end_x, start_y, end_y, corner_edge);\n setRectAttrFromPath(pathBgEl, '', voltage_path);\n\n // container.find(\"polyline.polyline\").attr(\"points\", fill_points);\n updateTextLabelEl(container, start_x, start_y, end_x, end_y, 0, current_1_volt_in_pixels, corner_edge);\n\n }\n\n // draw both horizontal and vertical lines if not within buffer\n if (!horizontal_line && !vertical_line) {\n // console.log(\"diagonal\");\n\n // check if horizontal and vertical both lines are allowed then only draw both\n if (allow_horizontal && allow_vertical) {\n setHorizontalPathData(time_path, start_x, end_x, start_y, end_y, corner_edge);\n setVerticalPathData(voltage_path, start_x, end_x, start_y, end_y, corner_edge);\n setRectAttrFromPath(pathBgEl, time_path, voltage_path);\n updateTextLabelEl(container, start_x, start_y, end_x, end_y, time_1_second_in_pixels, current_1_volt_in_pixels, corner_edge);\n if (draw_dummy_lines || mobile_view) {\n var x_adjustment = roundTo(dummy_stroke_width/2,1), y_adjustment = roundTo(dummy_stroke_width/2,1);\n var start_pos = '',\n mid_pos = '',\n end_pos = '';\n // adjusting polyline coordinate so as to avoid click on polyline itself rather than click on ECG Image\n // note that start_pos is everytime from y axis end\n if (end_x>start_x && end_y<start_y) {\n // first quadrant\n start_pos = (start_x - x_adjustment) + ',' + (end_y + y_adjustment);\n mid_pos = (end_x - x_adjustment) + ',' + (end_y + y_adjustment);\n end_pos = (end_x - x_adjustment) + ',' + (start_y + y_adjustment);\n }\n if (end_x<start_x && end_y<start_y) {\n // second quadrant\n start_pos = (start_x + x_adjustment) + ',' + (end_y + y_adjustment);\n mid_pos = (end_x + x_adjustment) + ',' + (end_y + y_adjustment);\n end_pos = (end_x + x_adjustment) + ',' + (start_y + y_adjustment);\n }\n if (end_x<start_x && end_y>start_y) {\n // third quadrant\n start_pos = (start_x + x_adjustment) + ',' + (end_y - y_adjustment);\n mid_pos = (end_x + x_adjustment) + ',' + (end_y - y_adjustment);\n end_pos = (end_x + x_adjustment) + ',' + (start_y - y_adjustment);\n }\n if (end_x>start_x && end_y>start_y) {\n // forth quadrant\n start_pos = (start_x - x_adjustment) + ',' + (end_y - y_adjustment);\n mid_pos = (end_x - x_adjustment) + ',' + (end_y - y_adjustment);\n end_pos = (end_x - x_adjustment) + ',' + (start_y - y_adjustment);\n }\n fill_points = start_pos + ' ' + mid_pos + ' ' + end_pos;\n container.find(\"polyline.dummy_polyline\").attr(\"points\", fill_points);\n }\n } else if (allow_horizontal) {\n // if only horizontal line is allowed\n setHorizontalPathData(time_path, start_x, end_x, start_y, end_y, corner_edge);\n setRectAttrFromPath(pathBgEl, time_path, '');\n updateTextLabelEl(container, start_x, start_y, end_x, end_y, time_1_second_in_pixels, 0, corner_edge);\n } else if (allow_vertical) {\n // if only vertical line is allowed\n setVerticalPathData(voltage_path, start_x, end_x, start_y, end_y, corner_edge);\n setRectAttrFromPath(pathBgEl, '', voltage_path);\n updateTextLabelEl(container, start_x, start_y, end_x, end_y, 0, current_1_volt_in_pixels, corner_edge);\n }\n }\n\n // show right handle\n if (mobile_view) {\n var left_x = start_x-handle_icon_width,\n left_y = start_y-handle_icon_height/2,\n right_x = end_x,\n right_y = end_y-handle_icon_height/2;\n // flip handles based on quadrant in which measurement is being drawn\n // if (end_x < start_x) {\n // left_x = end_x;\n // left_y = end_y-handle_icon_height/2;\n // right_x = start_x+handle_icon_width;\n // right_y = start_y-handle_icon_height/2;\n // }\n if (horizontal_line && !vertical_line) {\n container.find(\"image.left_handle\").removeClass(\"hide\").attr(\"x\", left_x).attr(\"y\", left_y);\n } else {\n // if both lines are drawn then adjust corner_edge size (bevel shape size adjustment)\n left_x -= corner_edge;\n container.find(\"image.left_handle\").removeClass(\"hide\").attr(\"x\", left_x).attr(\"y\", left_y);\n }\n container.find(\"image.right_handle\").removeClass(\"hide\").attr(\"x\", right_x).attr(\"y\", right_y);\n }\n } else {\n // show smallest messurement on first click\n var offset = stroke_width;\n setHorizontalPathData(time_path, CurrentPos[0], CurrentPos[0]+offset, CurrentPos[1], CurrentPos[1], corner_edge);\n setRectAttrFromPath(pathBgEl, time_path, '');\n updateTextLabelEl(container, CurrentPos[0], CurrentPos[1], CurrentPos[0]+offset, CurrentPos[1], 999999999, 0, corner_edge);\n\n // show left handle\n if (mobile_view) {\n // consider current position as left handle position as no previous position has been selected\n container.find(\"image.left_handle\").removeClass(\"hide\").attr(\"x\", CurrentPos[0]-handle_icon_width).attr(\"y\", CurrentPos[1]-handle_icon_height/2);\n }\n }\n }",
"function LetterB_drawHelpLines() {\n\talert(\"letterB: draw help lines\");\n\n\tthis.ctx.lineWidth = this.lineWidth;\n\n\tthis.ctx.beginPath();\n\tthis.ctx.moveTo(this.pt_start_x[0], this.pt_start_y[0]);\n\tthis.ctx.lineTo(this.pt_control_x[0], this.pt_control_y[0]);\n\tthis.ctx.stroke();\n\n\t// curve1\n\tthis.ctx.beginPath();\n\tthis.ctx.moveTo(this.pt_control_x[0], this.pt_control_y[0]);\n\tctx.bezierCurveTo(this.pt_control_x[0] + 100, this.pt_control_y[0],\n\t\t\tthis.pt_control_x[1] + 100, this.pt_control_y[1],\n\t\t\tthis.pt_control_x[1], this.pt_control_y[1]);\n\tthis.ctx.stroke();\n\n\t// curve2\n\tthis.ctx.beginPath();\n\tthis.ctx.moveTo(this.pt_control_x[1], this.pt_control_y[1]);\n\tctx.bezierCurveTo(this.pt_control_x[1] + 100, this.pt_control_y[1],\n\t\t\tthis.pt_end_x[0] + 100, this.pt_end_y[0] + this.radius / 2,\n\t\t\tthis.pt_end_x[0], this.pt_end_y[0] + this.radius / 2);\n\tthis.ctx.stroke();\n}",
"function handleLinesOnDrag(sceneID) {\n if (forwardChoiceMap.has(sceneID)) {\n for (let [toSceneID, value] of forwardChoiceMap.get(sceneID)) {\n let choices = value['choices'];\n let choicesWithNewLines = [];\n\n choices.forEach(element => {\n let oldLine = element['line'];\n if (oldLine) oldLine.remove();\n\n let newLine = new LeaderLine(\n document.getElementById(sceneID), \n document.getElementById(toSceneID), \n {\n endPlug: 'arrow3',\n color: 'rgba(255, 56, 96, 0.5)'\n }\n );\n \n choicesWithNewLines.push({\n choiceID: element['choiceID'],\n line: newLine\n });\n }); \n\n if (getValue(forwardChoiceMap, sceneID, toSceneID)) {\n let prevForwardValue = getValue(forwardChoiceMap, sceneID, toSceneID);\n prevForwardValue['choices'] = choicesWithNewLines;\n setValue(forwardChoiceMap, sceneID, toSceneID, prevForwardValue);\n }\n\n if (getValue(reverseChoiceMap, toSceneID, sceneID)) {\n let prevReverseValue = getValue(reverseChoiceMap, toSceneID, sceneID);\n prevReverseValue['choices'] = choicesWithNewLines;\n setValue(reverseChoiceMap, toSceneID,sceneID, prevReverseValue);\n }\n }\n }\n\n if (reverseChoiceMap.has(sceneID)) {\n for (let [toSceneID, value] of reverseChoiceMap.get(sceneID)) {\n let choices = value['choices'];\n let choicesWithNewLines = [];\n\n choices.forEach(element => {\n let oldLine = element['line'];\n if (oldLine) oldLine.remove();\n\n let newLine = new LeaderLine(\n document.getElementById(toSceneID), \n document.getElementById(sceneID), \n {\n endPlug: 'arrow3',\n color: 'rgba(255, 56, 96, 0.5)'\n }\n );\n \n choicesWithNewLines.push({\n choiceID: element['choiceID'],\n line: newLine\n });\n }); \n\n if (getValue(reverseChoiceMap, sceneID, toSceneID)) {\n let prevReverseValue = getValue(reverseChoiceMap, sceneID, toSceneID);\n prevReverseValue['choices'] = choicesWithNewLines;\n setValue(reverseChoiceMap, sceneID, toSceneID, prevReverseValue);\n }\n \n if (getValue(forwardChoiceMap, toSceneID, sceneID)) {\n let prevForwardValue = getValue(forwardChoiceMap, toSceneID, sceneID);\n prevForwardValue['choices'] = choicesWithNewLines;\n setValue(forwardChoiceMap, toSceneID,sceneID, prevForwardValue);\n }\n }\n }\n}",
"function ls_drawLines(options, initialY, leftPos, rightPos, bundling) {\n curveTightness(0);\n fill(255, 0, 0);\n //draw group data\n\n //seed = 328;\n //draw lines on bundles\n //stores line as with o,t,c,lp,rp\n var redrawLine = undefined;\n lines.groups.forEach(group => {\n //stroke(custom_random()*255,custom_random()*255,custom_random()*255);\n group.l.forEach(line => {\n var extraStroke = line.t.selected || line.o.selected ? 3 : 0;\n\n strokeWeight(Math.max(Math.min(line.a, 14), 1) + extraStroke); //sets size of line\n setLineColor(line, options);\n let newCenter = getMedia(line, leftPos, rightPos);\n\n //interpolates betwen line center and bundle center acording to bundling variable\n newCenter = {\n x: group.m.x * bundling + newCenter.x * (1 - bundling),\n y: group.m.y * bundling + newCenter.y * (1 - bundling),\n };\n if (line.t.selected || line.o.selected) {\n redrawLine = {\n l: line,\n c: newCenter,\n lp: leftPos,\n rp: rightPos,\n };\n }\n //console.log(line.xe,line.ye)\n newCenter.x += line.xe;\n newCenter.y += line.ye;\n ls_drawTreePointLine(\n options,\n line.o,\n line.t,\n newCenter,\n leftPos,\n rightPos\n );\n });\n });\n if (redrawLine) {\n //console.log(\"redrawing\");\n setLineColor(redrawLine.l, options);\n strokeWeight(Math.max(Math.min(line.a, 14), 1) + 2);\n ls_drawTreePointLine(\n options,\n redrawLine.l.o,\n redrawLine.l.t,\n redrawLine.c,\n redrawLine.lp,\n redrawLine.rp\n );\n }\n}",
"function render_aim_helper_line() {\n var c = {\n x: gamer.x + map.planet_w / 2,\n y: gamer.y + map.planet_h / 2\n };\n\n context.setLineDash([]);\n context.lineWidth = 3;\n context.strokeStyle = '#00ff00';\n context.beginPath();\n context.moveTo(c.x, c.y);\n context.lineTo(c.x + 2 * map.planet_w * Math.cos(deg_to_rad(gamer.angle)), c.y - 2 * map.planet_h * Math.sin(deg_to_rad(gamer.angle)));\n context.stroke();\n }",
"function drawWinLine(coordX1, coordY1, coordX2, coordY2) {\n const canvas= document.getElementById('win-lines')\n const c= canvas.getContext('2d');\n let x1= coordX1, y1=coordY1, x2=coordX2, y2=coordY2, x=x1, y=y1;\n\n function animateLineDrawing() {\n const animationLoop=requestAnimationFrame(animateLineDrawing);\n c.clearRect(0,0,608,608)\n c.beginPath();\n c.moveTo(x1,y1)\n c.lineTo(x,y)\n c.lineWidth=10;\n c.strokeStyle='rgba(27, 116, 151, 0.8)';\n c.stroke();\n if (x1 <= x2 && y1 <= y2) {\n if (x<x2) { x+= 10;}\n if (y<y2) { y+=10;}\n if (x >=x2 && y>=y2) {cancelAnimationFrame(animationLoop);}\n }\n if (x1 <=x2 && y1 >= y2) {\n if (x < x2) {x+=10;}\n if (y>y2) {y -=10;}\n if (x >=x2 && y <=y2) {cancelAnimationFrame(animationLoop);}\n }\n }\n\n // clears the win line \n function clear() {\n const animationLoop= requestAnimationFrame(clear);\n c.clearRect(0,0,608,608);\n cancelAnimationFrame(animationLoop);\n }\n disableClick();\n audio('./media/winGame1.mp3');\n animateLineDrawing();\n setTimeout(function () { clear(); resetGame();}, 1000)\n}",
"function init(){\n svg.innerHTML = \"\";\n path = document.createElementNS(\"http://www.w3.org/2000/svg\",'path');\n path.setAttribute('d', `M ${anchors[anchors.length-2]} ${anchors[anchors.length-1]}`);\n path.setAttribute('fill','none');\n path.setAttribute('stroke','black');\n path.setAttribute('stroke-width','6');\n // stroke=\"black\" fill=\"none\"\n svg.appendChild(path);\n layerPoints = Array.from({length:anchors.length/2 });\n for(let i=0;i<layerPoints.length;i++){\n layerPoints[i] = Array.from({length:i+1});\n\n for(let j=0; j<layerPoints[i].length; j++){\n layerPoints[i][j] = { };\n cookSVGobj(layerPoints[i][j]);\n layerPoints[i][j].el = document.createElementNS(\"http://www.w3.org/2000/svg\",'circle');\n layerPoints[i][j].el.setAttribute('fill' ,`rgb(${Math.floor(Math.random()*256)} , ${Math.floor(Math.random()*256)} , ${Math.floor(Math.random()*256)})` );\n layerPoints[i][j].el.setAttribute('r',\"4\");\n svg.appendChild(layerPoints[i][j].el);\n }\n }\n\n layerLines = Array.from({length:anchors.length/2 });\n for(let i=0 ; i<layerLines.length;i++){\n layerLines[i] = Array.from({length:i});\n\n for(let j=0; j<layerLines[i].length;j++){\n layerLines[i][j] = {};\n cookSVGobj(layerLines[i][j]);\n\n layerLines[i][j].el = document.createElementNS(\"http://www.w3.org/2000/svg\",'line');\n layerLines[i][j].el.setAttribute('stroke' , `rgb(${Math.floor(Math.random()*256)} , ${Math.floor(Math.random()*256)} , ${Math.floor(Math.random()*256)})` );\n\n // layerLines[i][j].x1 = layerPoints[i][j].x;\n // layerLines[i][j].y1 = layerPoints[i][j].y;\n // layerLines[i][j].x2 = layerPoints[i][j+1].x;\n // layerLines[i][j].y2 = layerPoints[i][j+1].y;\n\n svg.appendChild(layerLines[i][j].el);\n\n }\n }\n \n}",
"function renderLine () {\n // Render each data point\n ctx.beginPath();\n ctx.strokeStyle = typeof dataset['strokeStyle'] !== 'undefined' ? dataset['strokeStyle'] : '#ffffff';\n ctx.lineWidth = typeof dataset['lineWidth'] !== 'undefined' ? dataset['lineWidth'] : 2;\n ctx.moveTo(points[0].x, points[0].y);\n\n for (var j = 1; j < points.length; j++) {\n ctx.lineTo(points[j].x, points[j].y);\n }\n\n ctx.stroke();\n }",
"function overlayPlotLines(data){\n var possibleTouchpoints = data.ChannelRanking.Touchpoints;\n var numSelectedTouchpoints = 0;\n for (var i = 0; i < possibleTouchpoints.length; i++) {\n if (possibleTouchpoints[i].Selected) {\n numSelectedTouchpoints += 1;\n }\n }\n var plotLines = [];\n for (var i = 0; i < numSelectedTouchpoints; i++) {\n plotLines.push({\n value: i + 0.5,\n color: 'white',\n width: 2,\n zIndex: 5\n })\n }\n return plotLines\n }",
"drawLine(start_x, start_y, end_x, end_y) {\n this.ctx.moveTo(start_x, start_y);\n this.ctx.lineTo(end_x, end_y);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
debugDrawCollisionToggle Creates new html elements for debug controls | function debugControls() {
var div = document.getElementById("dbgCtrls");
var diffLabel = document.createElement("p");
diffLabel.textContent = "DIFFICULTY OVERRIDE";
div.appendChild(diffLabel);
var diffEntry = document.createElement("input");
diffEntry.min = 1;
diffEntry.max = 10;
diffEntry.id = `${div.id}_controlDifficulty`;
diffEntry.onchange = function() {
DIFFICULTY_OVERRIDE = Number.parseFloat(diffEntry.value);
updateDifficulty();
console.log(`DEBUG CONTROLS: Set difficulty to ${DIFFICULTY_OVERRIDE}`);
}
div.appendChild(diffEntry);
// #region Octree Controls
{
let ctrlDiv = document.createElement("div");
ctrlDiv.id = "dbgOctreeControls";
var hdrTxt = document.createElement("h4");
hdrTxt.innerText = "OCTREE CONTROLS:";
ctrlDiv.appendChild(hdrTxt);
var toggleDrawBtn = document.createElement("button");
toggleDrawBtn.id = `${ctrlDiv.id}_toggleDraw`;
ctrlDiv.appendChild(toggleDrawBtn);
toggleDrawBtn.innerText = `TOGGLE DRAW`;
toggleDrawBtn.onclick = function() {
DEBUG_DRAW_OCTREE = !DEBUG_DRAW_OCTREE;
console.debug(`DEBUG CONTROLS: Toggle DEBUG_DRAW_OCTREE to ${DEBUG_DRAW_OCTREE}`);
if (DEBUG_DRAW_OCTREE == false) {
dbgDrawablesPersist["OCTREE"] = [];
}
}
div.appendChild(ctrlDiv);
}
// #endregion Octree Controls
// spawnRandomAsteroid
if (false)
{
var ctrlDiv = document.createElement("div");
ctrlDiv.id = "spawnRandomAsteroid";
{
var hdrTxt = document.createElement("h4");
hdrTxt.innerText = "SPAWN DISPLACED ASTEROID:";
ctrlDiv.appendChild(hdrTxt);
var locTxt = document.createElement("p");
locTxt.innerText = `Location ("x, y, z"):`;
ctrlDiv.appendChild(locTxt);
var locInp = document.createElement("input");
locInp.id = `${ctrlDiv.id}.locInp`;
locInp.value = "0, 0, 0";
ctrlDiv.appendChild(locInp);
var scaleTxt = document.createElement("p");
scaleTxt.innerText = `Scale (universal x,y, and z):`;
ctrlDiv.appendChild(scaleTxt);
var scaleInp = document.createElement("input");
scaleInp.id = `${ctrlDiv.id}.scaleInp`;
scaleInp.value = "1";
ctrlDiv.appendChild(scaleInp);
var noiseSizeTxt = document.createElement("p");
noiseSizeTxt.innerText = `Noise Size (0.001-50):`;
ctrlDiv.appendChild(noiseSizeTxt);
var noiseSizeInp = document.createElement("input");
noiseSizeInp.id = `${ctrlDiv.id}.noiseSizeInp`;
noiseSizeInp.value = "10";
ctrlDiv.appendChild(noiseSizeInp);
var noiseImpactTxt = document.createElement("p");
noiseImpactTxt.innerText = `Noise Impact (0.001-1):`;
ctrlDiv.appendChild(noiseImpactTxt);
var noiseImpactInp = document.createElement("input");
noiseImpactInp.id = `${ctrlDiv.id}.noiseImpactInp`;
noiseImpactInp.value = "0.02";
ctrlDiv.appendChild(noiseImpactInp);
var wireframeColTxt = document.createElement("p");
wireframeColTxt.innerText = `Wireframe Color [r,g,b] [0-1]:`;
ctrlDiv.appendChild(wireframeColTxt);
var wireframeColInp = document.createElement("input");
wireframeColInp.id = `${ctrlDiv.id}.wireframeColInp`;
wireframeColInp.value = "1, 1, 1";
ctrlDiv.appendChild(wireframeColInp);
var wireframeThicknessTxt = document.createElement("p");
wireframeThicknessTxt.innerText = `Wireframe Thickness [0-1]:`;
ctrlDiv.appendChild(wireframeThicknessTxt);
var wireframeThicknessInp = document.createElement("input");
wireframeThicknessInp.id = `${ctrlDiv.id}.wireframeThicknessInp`;
wireframeThicknessInp.value = "0.02";
ctrlDiv.appendChild(wireframeThicknessInp);
var submit = document.createElement("button");
submit.id = `${ctrlDiv.id}.submit`;
submit.innerText = `CREATE 'ROID`;
submit.onclick = function() {
var locSplit = locInp.value.split(",");
var loc = vec3.fromValues(Number.parseFloat(locSplit[0]), Number.parseFloat(locSplit[1]), Number.parseFloat(locSplit[2]));
var scale = Number.parseFloat(scaleInp.value);
var noiseSize = Number.parseFloat(noiseSizeInp.value);
var noiseImpact = Number.parseFloat(noiseImpactInp.value);
var wColSplit = wireframeColInp.value.split(",");
ASTEROID_WIREFRAME_COLOR = [Number.parseFloat(wColSplit[0]), Number.parseFloat(wColSplit[1]), Number.parseFloat(wColSplit[2])];
ASTEROID_WIREFRAME_THICKNESS = Number.parseFloat(wireframeThicknessInp.value);
console.log(`Create asteroid with pos=${loc}, size=${noiseSize}, imp=${noiseImpact}, wC=${ASTEROID_WIREFRAME_COLOR}, wT=${ASTEROID_WIREFRAME_THICKNESS}`);
var roid = generateNoisedRoid(loc, noiseSize, noiseImpact);
roid.transform.scaleVec3 = vec3.fromValues(scale, scale, scale);
}
ctrlDiv.appendChild(submit);
}
div.appendChild(ctrlDiv);
}
// spawnRandomAsteroid
} // debugControls | [
"function drawDebugHitbox(entity) {\n let canvas = document.getElementById('gameWorld');\n let ctx = canvas.getContext('2d');\n ctx.beginPath();\n ctx.strokeStyle = entity.isRecoiling ? 'orange' : 'green';\n ctx.lineWidth = 2;\n ctx.rect(entity.hitbox.x, entity.hitbox.y, entity.hitbox.width, entity.hitbox.height);\n ctx.stroke();\n ctx.closePath();\n}",
"function toggleDynamic()\n{\n\tif (INTERSECTED && readOnly != 1) {\n\t\tif (INTERSECTED.name.dynamic == 1 && INTERSECTED.name.dynamicIdx==-2) {\n\t\t\talert('Cannot change dynamic status of automatically generated bounding boxes');\n\t\t\treturn;\n\t\t}\n\t\tif (INTERSECTED.name.dynamic == 1 && splineCurves[INTERSECTED.name.dynamicSeq]!=undefined){\n\t\t\talert('Cannot change dynamic status of spline control points. Try remove spline at first.');\n\t\t\treturn;\n\t\t}\n\t\tonHoldingSpline = true;\n\t\tINTERSECTED.name.dynamic = 1 - INTERSECTED.name.dynamic;\n\t\tlabels_helper[currentIdx].material.color.setHex(WIREFRAME_COLOR[INTERSECTED.name.dynamic]);\n\t\tif (INTERSECTED.name.dynamic)\n\t\t\tlabels[currentIdx].material.opacity = dynamicopacity;\n\t\telse \n\t\t\tlabels[currentIdx].material.opacity = labelOpacity;\n\t\tdynamicOn = !dynamicOn;\n\t\t// dynamic sequence should always be initialized by toggle dynamic button on an idependent object\n\t\t// i.e. object not belonging to a spline\n\t\tif (INTERSECTED.name.dynamic == 1 ){\n\t\t\tcurrDynamicSeq = currDynamicSeq + 1;\n\t\t\tcurrDynamicIdx = 0;\n\t\t\tINTERSECTED.name.dynamicSeq = currDynamicSeq;\n\t\t\tINTERSECTED.name.dynamicIdx = 0;\n\n\t\t// initialize the sline\n\t\tif (currDynamicIdx == 0 ) {\n\t\t\t\n\t\t\tvar splineGeometry = new THREE.Geometry();\n\t\t\tfor ( var i = 0; i < ARC_SEGMENTS; i ++ ) {\n\t\t\t splineGeometry.vertices.push( new THREE.Vector3() );\n\t\t\t\n\t\t\t}\n\t\t\tvar positions = [];\n\t\t\tpositions.push(INTERSECTED.position);\t\t\n\n\t\t\t// initialize an additional point for onMouseOver\n\t\t\tvar newpos = new THREE.Vector3();\n\t\t\tnewpos.x = INTERSECTED.position.x;\n\t\t\tnewpos.y = INTERSECTED.position.y;\n\t\t\tnewpos.z = INTERSECTED.position.z;\n\t\t\tpositions.push(newpos);\t\t\n var curve = new THREE.CatmullRomCurve3( positions );\n curve.type = 'catmullrom';\n curve.mesh = new THREE.Line( splineGeometry.clone(), new THREE.LineBasicMaterial( {\n color: SPLINE_COLOR[0],\n opacity: 0.35,\n linewidth: 2\n } ) );\n curve.mesh.castShadow = true;\n\t\t\tcurve.mesh.material.depthTest = false;\n\t\t\tscene.add(curve.mesh);\n\t\t\tconsole.log('curve', curve);\n\n\t\t\tsplineCurves.push(curve);\n\t\t\tsplinePositions.push(positions);\n\t\t\tsplineIsAutoBoxed.push(0); \n \t\tupdateSplineOutline(splineCurves[currDynamicSeq]);\n\t\t}\n\n\t\t}\n\t\telse {\n\t\t\tcurrDynamicSeq = currDynamicSeq - 1;\n\t\t\tcurrDynamicIdx = -1;\n\t\t\tINTERSECTED.name.dynamicSeq = -1;\n\t\t\tINTERSECTED.name.dynamicIdx = -1;\n\t\t}\n\t}\n}",
"function ToggleDraw(){\n self.canvas.isDrawingMode = !self.canvas.isDrawingMode;\n }",
"function toggleToCompBoard(evt) {\n gameBoard1.style.display = \"none\";\n gameBoard2.style.display = \"\";\n compHeader.style.display = \"\";\n playerHeader.style.display = \"none\";\n}",
"function showHideTLeditPanel(){\n if(trafficLightControl.isActive){ // close panel\n trafficLightControl.isActive=false; //don't redraw editor panel\n if(drawBackground){ // wipe out existing editor panel\n ctx.drawImage(background,0,0,canvas.width,canvas.height);\n }\n document.getElementById(\"editTLbutton\").innerHTML\n =\"Open traffic-light control panel\";\n }\n else{ // open panel\n trafficLightControl.isActive=true;\n document.getElementById(\"editTLbutton\").innerHTML\n =\"Close traffic-light control panel\";\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 toggleShapes(){\n\tif (shapesOn) {\n\t\tshapesOn = false;\n\t} else {\n\t\tshapesOn = true;\n\t}\n}",
"drawExtraUI() {\n // draw the button for canceling ability if an ability is being used if it has not been used partly\n if (this.situation === \"ability\") {\n if (currentAbility.currentStep === 1) {\n push();\n rectMode(CENTER);\n noStroke();\n // if moused over, it is highlighted\n if (mouseOver === \"cancel\") {\n fill(0);\n } else {\n fill(255,50,0);\n }\n rect(width-width/10, height/2, width/10, height/15);\n // if moused over, it is highlighted\n if (mouseOver === \"cancel\") {\n fill(255, 0, 0);\n } else {\n fill(0);\n }\n textAlign(CENTER, CENTER);\n textSize(width/120+height/120);\n text(\"Cancel Ability\", width-width/10, height/2);\n pop();\n }\n }\n // draw the button to go to the fight mode\n if (this.situation === \"choose\") {\n push();\n rectMode(CENTER);\n noStroke();\n // if moused over, it is highlighted\n if (mouseOver === \"fight\") {\n fill(0);\n } else {\n fill(255,255,0);\n }\n rect(width-width/10, height/2, width/10, height/15);\n // if moused over, it is highlighted\n if (mouseOver === \"fight\") {\n fill(255, 255, 0);\n } else {\n fill(0);\n }\n textAlign(CENTER, CENTER);\n textSize(width/80+height/50);\n text(\"Fight!\", width-width/10, height/2);\n pop();\n }\n }",
"function mapEditorUI(parent, name, scene, w, h, m, r, hide, debug)\n{\n\t// reposition body when screen or body itself resizes\n\t// -----------------------------------------------------------------------------------\n\tvar onBodyResize = function(elem, w, h)\n\t{\n\t\tbody.setPos( (parent.width() - body.width()) / 2, parent.height() - body.height() - m );\n\t}\n\t\t\n\t// constructor\n\t// -----------------------------------------------------------------------------------\n\tvar body = new frame(parent, name, 0, 0, 0, 0, false, false, hide, debug);\n\tif (parent) parent.addEventListener(\"resize\", onBodyResize);\n\tbody.addEventListener(\"resize\", onBodyResize);\n\tbody.addEventListener(\"draw\", function(elem, x, y, w, h)\n\t{\n\t\tscene.getCanvas().getContext(\"2d\").fillStyle = \"rgba(164,164,164,1)\";\n\t\tdrawRoundCornerRectangle(scene, x, y, w, h,r + m);\n\t});\n\t\n\t\n\t// add child buttons and resize body to fit them\n\t// -----------------------------------------------------------------------------------\n\tvar btns = [];\n\tthis.add = function(name, color, onmouseup)\n\t{\n\t\tvar btn = new frame(body, name, m + btns.length * (w + m), m, w, h, false, false, hide, debug);\n\t\tbtn.addEventListener(\"mouseup\", onmouseup);\n\t\tbtn.addEventListener(\"mousedown\", function(elem){ elem.state = true; });\n\t\tbtn.addEventListener(\"mouseup\", function(elem){ elem.state = false; });\n\t\tbtn.addEventListener(\"mouseleave\", function(elem){ elem.state = false; });\n\t\t\n\t\tbtn.addEventListener(\"draw\", function(elem, x, y, w, h)\n\t\t{\n\t\t\tscene.getCanvas().getContext(\"2d\").fillStyle = color;\n\t\t\tif (elem.state) drawRoundCornerRectangle(scene, x + 1, y + 1, w - 2, h - 2, r - 1);\n\t\t\t//if (elem.state) drawRoundCornerRectangle(scene, x + 2, y + 2, w, h, w/2);\n\t\t\telse drawRoundCornerRectangle(scene, x, y, w, h, r);\n\t\t});\n\t\t\n\t\tbtns.push(btn);\n\t\tbody.setSize( btns.length * (w + m) + m, h + m * 2 );\n\t}\n}",
"generateDoors(){\n if(!this.walls.top){\n // make a door to the top\n this.grid[this.getIndex(2, 0)].fg = null;\n this.grid[this.getIndex(3, 0)].fg = null;\n this.grid[this.getIndex(1, 0)].fg = this.getSprite('tilemap', 'cobble-fg-right-0');\n this.grid[this.getIndex(2, 2)].fg = this.getSprite('tilemap', 'stoneplank-0');\n this.grid[this.getIndex(3, 2)].fg = this.getSprite('tilemap', 'stoneplank-1');\n this.grid[this.getIndex(4, 0)].fg = this.getSprite('tilemap', 'cobble-fg-left-0');\n this.grid[this.getIndex(2, 2)].fg.jumpable = true;\n this.grid[this.getIndex(3, 2)].fg.jumpable = true;\n }\n if(!this.walls.right){\n // make a door to the right\n this.grid[this.getIndex(5, 1)].fg = null;\n this.grid[this.getIndex(5, 2)].fg = null;\n this.grid[this.getIndex(5, 3)].fg = null;\n this.grid[this.getIndex(5, 4)].fg = null;\n } else {\n this.grid[this.getIndex(5, 1)].deco = null;\n this.grid[this.getIndex(5, 2)].deco = null;\n this.grid[this.getIndex(5, 3)].deco = null;\n this.grid[this.getIndex(5, 4)].deco = null;\n }\n if(!this.walls.bottom){\n // make a door to the bottom\n this.grid[this.getIndex(1, 5)].fg = this.getSprite('tilemap', 'cobble-fg-right-0');\n this.grid[this.getIndex(2, 5)].fg = this.getSprite('tilemap', 'stoneplank-0');\n this.grid[this.getIndex(3, 5)].fg = this.getSprite('tilemap', 'stoneplank-1');\n this.grid[this.getIndex(4, 5)].fg = this.getSprite('tilemap', 'cobble-fg-left-0');\n this.grid[this.getIndex(2, 5)].fg.jumpable = true;\n this.grid[this.getIndex(3, 5)].fg.jumpable = true;\n }\n if(!this.walls.left){\n // make a door to the left\n this.grid[this.getIndex(0, 1)].fg = null;\n this.grid[this.getIndex(0, 2)].fg = null;\n this.grid[this.getIndex(0, 3)].fg = null;\n this.grid[this.getIndex(0, 4)].fg = null;\n } else {\n this.grid[this.getIndex(0, 1)].deco = null;\n this.grid[this.getIndex(0, 2)].deco = null;\n this.grid[this.getIndex(0, 3)].deco = null;\n this.grid[this.getIndex(0, 4)].deco = null;\n }\n }",
"function showred() {\r\n var o_panel_info = document.getElementById(\"outputpanel\").classList\r\n if(o_panel_info.length > 1){\r\n o_panel_info.remove(\"greenbg\", \"darkbg\", \"lightbg\");\r\n }\r\n o_panel_info.add(\"redbg\");\r\n}",
"function displayStackSelectionBox(row,column)\n{\n\tvar tile = map[row][column];\n\tvar stack = tile.stack;\n\t\n\tvar addMoveButton = 0;\n\tvar index = 0;\n\t//check to see if there's a select square here\n\tfor(var i=0;i<movementSquares.length;i++)\n\t{\n\t\tif(movementSquares[i].row == row && movementSquares[i].column == column)\n\t\t{\n\t\t\taddMoveButton = 1;\n\t\t\t\n\t\t}\n\t}\n\t\n\t//background\n\tvar stackSelectionBox = new createjs.Shape();\n\tstackSelectionBox.graphics.beginFill(\"DarkSlateGray\").drawRect(0, 0, 44, 25*(stack.length+addMoveButton));\n\tstackSelectionBox.x = 24*(column+1);\n\tstackSelectionBox.y = 50+24*row;\n\tstackSelectionBox.name = \"stackSelectionBox\";\n\tstage.addChild(stackSelectionBox);\n\t\n\tfor(var i=0;i<stack.length;i++)\n\t{\n\t\t//add button\n\t\tvar SSBButton = new Button(\"SSBButton\",24*(column+1)+20,52+24*row+24*i,20,20);\n\t\tSSBButton.name = \"SSBButton\"+i;\n\t\tSSBButton.text = \"<\";\n\t\tSSBButton.row = row;\n\t\tSSBButton.column = column;\n\t\tSSBButton.target = stack[i];\n\t\tSSBButton.handleButtonEvent = handleSSBBEvent;\n\t\tSSBButton.onClick = function()\n\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\tdeSelectAll();\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvar tile = map[this.row][this.column]\n\t\t\t\t\t\t\t\tselectedObject = this.target;\n\t\t\t\t\t\t\t\tdisplaySelectBox(this.row,this.column);\n\t\t\t\t\t\t\t\tselectedObject.displayInfo(stage, player);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(isUnit(this.target) == true)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tselectedUnit = this.target;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif(selectedUnit.movementPoints > 0 && selectedUnit.color == player.color && player.onTurn == true)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tdisplayMovementSquares(this.row,this.column);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tselectedUnit = null;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tremoveStackSelectionBox();\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t\tSSBButton.draw();\n\t\t\n\t\t//add image\n\t\tvar objectImage = new Image();\n\t\tobjectImage.src = stack[i].image.src;\n\t\tobjectImage.yOffset = i;\n\t\tobjectImage.onload = function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar SSBImage = new createjs.Bitmap(this);\n\t\t\t\t\t\t\t\tSSBImage.x = 24*(column+1)+2;\n\t\t\t\t\t\t\t\tSSBImage.y = 54 + 24*row+24*this.yOffset;\n\t\t\t\t\t\t\t\tSSBImage.name = \"SSBImage\";\n\t\t\t\t\t\t\t\tstage.addChild(SSBImage);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t\t\n\t\tindex++;\n\t}\n\t\n\tif(addMoveButton == 1)\n\t{\n\t\t//add move here button\n\t\tvar moveHereButton = new Button(\"moveHereButton\",24*(column+1)+20,52+24*row+24*index,20,20);\n\t\tmoveHereButton.name = \"moveHereButton\";\n\t\tmoveHereButton.text = \"<\";\n\t\tmoveHereButton.row = row;\n\t\tmoveHereButton.column = column;\n\t\t\n\t\tvar placeHolder = [];placeHolder.type = \"Move Here\";\n\t\t\n\t\tmoveHereButton.target = placeHolder;\n\t\tmoveHereButton.handleButtonEvent = handleSSBBEvent;\n\t\tmoveHereButton.onClick = function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveSelectedUnit(this.row,this.column);\n\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(selectedUnit.movementPoints > 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdisplayMovementSquares(selectedUnit.row,selectedUnit.column);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tremoveMovementSquares();\n\t\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tremoveStackSelectionBox();\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t\tmoveHereButton.draw();\n\t\t\n\t\t//add image\n\t\tvar moveHereImage = new Image();\n\t\tmoveHereImage.src = \"http://kev1shell.github.io/assets/sprites/other/moveHereSymbol.png\";\n\t\tmoveHereImage.yOffset = index;\n\t\tmoveHereImage.onload = function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar MHImage = new createjs.Bitmap(this);\n\t\t\t\t\t\t\t\tMHImage.x = 24*(column+1)+2;\n\t\t\t\t\t\t\t\tMHImage.y = 54 + 24*row+24*this.yOffset;\n\t\t\t\t\t\t\t\tMHImage.name = \"MHImage\";\n\t\t\t\t\t\t\t\tstage.addChild(MHImage);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t}\n\t\n\tcacheStage();\n\tstage.update();\n\t\n}",
"init_advanced_controls(color_system_name) {\n let that = this;\n if (this.$figure.find(\".visualization-controls-advanced-toggle\").length == 0) {\n /* Add toggle for showing/hiding controls. */\n this.$controls_advanced.before(\n '<h3 class=\"visualization-controls-advanced-toggle\">' +\n '<span class=\"arrow\">▶ </span><span class=\"text\">Advanced controls</span></h3>'\n );\n this.$controls_advanced.hide();\n let $toggle = this.$figure.find(\".visualization-controls-advanced-toggle\");\n $toggle.click(function () {\n if (that.$controls_advanced.is(\":visible\")) {\n $toggle.find(\".arrow\").removeClass(\"arrow-rotated\");\n } else {\n $toggle.find(\".arrow\").addClass(\"arrow-rotated\");\n }\n that.$controls_advanced.toggle(300);\n });\n }\n\n this.$controls_advanced.append(\n '<h3 class=\"visualization-controls-system-header\">' +\n color_system_name +\n '</h3>'\n );\n this.show_only_color_solid_control = new VisualizationControlCheck(\n this.$controls_advanced,\n \"Show the color solid only\"\n );\n this.show_only_color_solid_control.add_listener((event) =>\n that.show_only_color_solid_changed.call(that, event));\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 patchInCollisionMaps(engine, widthAccessor, heightAccessor) {\n var collisionCanvas = document.createElement(\"canvas\");\n collisionCanvas.id = \"collisionCanvas\";\n collisionCanvas.width = widthAccessor();\n collisionCanvas.height = heightAccessor();\n var collisionCtx = collisionCanvas.getContext('2d');\n // DEBUG\n // document.body.appendChild(collisionCanvas);\n var oldUpdate = ex.Engine.prototype[\"update\"];\n ex.Engine.prototype[\"update\"] = function (delta) {\n var width = widthAccessor();\n var height = heightAccessor();\n if (collisionCanvas.width !== width || collisionCanvas.height !== height) {\n collisionCanvas.width = widthAccessor();\n collisionCanvas.height = heightAccessor();\n collisionCtx = collisionCanvas.getContext('2d');\n }\n oldUpdate.apply(this, [delta]);\n };\n var oldDraw = ex.Engine.prototype[\"draw\"];\n ex.Engine.prototype[\"draw\"] = function (delta) {\n var width = widthAccessor();\n var height = heightAccessor();\n collisionCtx.fillStyle = 'white';\n collisionCtx.fillRect(0, 0, width, height);\n oldDraw.apply(this, [delta]);\n };\n ex.Scene.prototype.draw = function (ctx, delta) {\n ctx.save();\n if (this.camera) {\n this.camera.update(ctx, delta);\n }\n var i, len;\n for (i = 0, len = this.children.length; i < len; i++) {\n // only draw actors that are visible\n if (this.children[i].visible) {\n this.children[i].draw(ctx, delta);\n }\n if (this.children[i] instanceof CollisionActor) {\n this.children[i].drawCollisionMap(collisionCtx, delta);\n }\n }\n ctx.restore();\n };\n engine.collisionCtx = collisionCtx;\n }",
"changeGenerateStatus() {\n this.generateButton.disabled = canvasScript.robots.size < 2;\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 toggleShape($li,editable) {\n \t$li.each(function() {\n \t\tvar $parent = $(this);\n \t\tvar index = $('.edit',$parent).attr('data-index');\n \t\tvar isCircle = $('.circle.button',$parent).hasClass('active');\n \t\t\n \t\tif (isCircle) {\n \t\t\tcircles[index].editable = editable;\n \t\t\tcircles[index].draggable = editable;\n \t\t\tcircles[index].setMap(null);\n \t\t\tcircles[index].setMap(maps[index]);\n \t\t} else {\n \t\t\trectangles[index].editable = editable;\n \t\t\trectangles[index].draggable = editable;\n \t\t\trectangles[index].setMap(null);\n \t\t\trectangles[index].setMap(maps[index]);\n \t\t};\n \t});\n }",
"function createButtons() {\n document.getElementById('start-game').classList.add('invisible');\n document.getElementById('shuffle').classList.remove('invisible');\n document.getElementById('show-hide').classList.remove('invisible');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adding click listeners to employee cards | function addEventListenersToCards(){
//After the cards have been rendered, we assign them to the variable $cards
$cards = $('.card');
$cards.on('click', event => {
//Because sometimes the users will click on the image, or some text, we must traverse the DOM to access
//the card element itself
let targetedCard = event.target;
while($.inArray(targetedCard, $cards) == -1){
targetedCard = targetedCard.parentNode;
}
//We find the index of the clicked card in cards, and it is equivalent to the index of the employees in the employee array
const employeeIndex = $.inArray(targetedCard, $cards);
activeEmployee = employeeArray[employeeIndex];
//Creating and rendering the newly created modal window
let modalWindowHhtml = createModalWindowForEmployee(activeEmployee);
$modalContainer.html(modalWindowHhtml);
$('body').append($modalContainer);
//Adding event listeners to the modal window
addEventListenersToModalWindowButtons();
});
} | [
"function employeeClickEventListener() {\n $('li').click(function() {\n let id = $(this).attr('id');\n let idNumber = parseInt(id, 10);\n displayEmployeeModal(idNumber);\n })\n }",
"function clickedCard() {\r\n cardsDeck.addEventListener('click', function (card) {\r\n showCard(card);\r\n });\r\n}",
"function loadTeamCardLinks() {\n cards = document.getElementsByClassName(\"img_link\");\n for (let i of cards) {\n i.addEventListener(\"click\", (e) => { showTeam(e) });\n }\n}",
"addListeners(e){\r\n this.onToCartClick(e);\r\n this.onFromCartClick(e);\r\n }",
"function addEvent() {\nfor (let i = 0; i < card.length; i++) {\n\tcard[i].addEventListener('click', function() {\n\t\tmoveCounter();\n\t\tmatchingTestArr.push(this);\n\t\ttestArr();\n\t\tremoveStars();\n\t\tearnedStars();\n\t});\n }\n}",
"function addGenreListener() {\n document.querySelectorAll('.card').forEach(card => {\n card.addEventListener('click', event => {\n if (event.target.classList.contains('genre-in-card')) {\n const order = Number(event.target.dataset.genre)\n $(`#genre-list li:nth-child(${order}) a`).tab('show')\n } \n })\n })\n }",
"function showEmployeeGalleryCard(i){\n\tlet galleryHTML = '<div id=\"class=\"card-img-container\">';\n\tgalleryHTML += '<img class=\"card-img\" src=\"'+ employeeJSONdata[i].picture.large + '\" alt=\"profile picture\">';\n\tgalleryHTML += '</div>';\n\tgalleryHTML += '<div class=\"card-info-container\">';\n\tgalleryHTML += '<h3 id=' + employeeJSONdata[i].name.first + 'class=\"card-name cap\">' + employeeJSONdata[i].name.first + ' '+ employeeJSONdata[i].name.last + '</h3>';\n\tgalleryHTML += '<p class=\"card-text\">' + employeeJSONdata[i].email + '</p>';\n\tgalleryHTML += '<p class=\"card-text cap\">' + employeeJSONdata[i].location.city +', ' + employeeJSONdata[i].location.state + '</p>';\n\tgalleryHTML += '</div>';\n\tlet userHTML = document.createElement('div');\n\tuserHTML.innerHTML = galleryHTML;\n\tuserHTML.className = 'card';\n\tuserHTML.id = employeeJSONdata[i].email;\n\tdocument.getElementById('gallery').appendChild(userHTML);\n}",
"function generateEmployees(employees) {\n employees.forEach(employee => {\n //Add each employee object to employeeList array.\n employeeList.push(employee);\n const html = `\n <div class=\"card\">\n <div class=\"card-img-container\">\n <img class=\"card-img\" src=\"${employee.picture.large}\" alt=\"profile picture\">\n </div>\n <div class=\"card-info-container\">\n <h3 id=\"name\" class=\"card-name cap\">${employee.name.first} ${employee.name.last}</h3>\n <p class=\"card-text\">${employee.email}</p>\n <p class=\"card-text cap\">${employee.location.country}</p>\n </div>\n </div>\n `\n employeeDiv.insertAdjacentHTML('beforeend', html);\n })\n}",
"function clickTaskCard(event) {\r\n // Display view task\r\n popUpView.style.display = \"block\";\r\n\r\n // get local storage\r\n let LocalStorageTaskArray = getLocalStorage(\"task\");\r\n // Get index of taskcard clicked\r\n let index = LocalStorageTaskArray.findIndex(obj => obj.name === event.target.previousSibling.previousSibling.previousSibling.previousSibling.innerHTML);\r\n let thisTask = getLocalStorage(\"task\")[index];\r\n // Render clicked task in view task\r\n renderTaskCard(thisTask);\r\n}",
"attachEvents() {\n const data = {\n mode: this.drawingMode,\n container: this.canvasDrawer,\n target: this.target\n };\n //When clicking the <label>, fire this event.\n $(this.target).click(data, function () {\n data.container.drawingMode = data.mode;\n data.container.componentSelected(data.target);\n });\n }",
"function attachClickEvent() {\n var listLength = divList.length;\n for (var i = 0; i < listLength; i++) {\n divList[i].addEventListener(\"click\", showLunch);\n }\n}",
"function displayPlayerElectedCircles(e) {\n playerCircle.classList.add('display-player-btn');\n\n // Fill button with corresponding image\n document.querySelector(\n '.btn-player'\n ).lastElementChild.innerHTML = `${e.lastElementChild.innerHTML}`;\n\n // Shines computers the elected new circle\n shinesButton(playerCircle);\n}",
"function enableClickOnCard () {\n\topenCardList[0].click(flipCard);\n}",
"function addShowBookListener() {\n document.addEventListener('click', (event) => {\n if(event.target.className === 'book'){\n const bookId = parseInt(event.target.dataset.id);\n fetchSingleBook(bookId);\n }\n });\n}",
"function setSortCardsListeners() {\n\tconst sortMenuButton = document.getElementById(\"sortMenuButton\");\n\tconst sortByFirstName = document.getElementById(\"sortFirstName\");\n\tconst sortByLastName = document.getElementById(\"sortLastName\");\n\tconst sortByParty = document.getElementById(\"sortParty\");\n\tconst sortByState = document.getElementById(\"sortState\");\n\tconst sortBySeniority = document.getElementById(\"sortSeniority\");\n\tconst sortByVotesWith = document.getElementById(\"sortVotesWith\");\n\tconst sortByVotesAgainst = document.getElementById(\"sortVotesAgainst\");\n\tconst sortByDistrict = document.getElementById(\"sortDistrict\");\n\n\tsortByFirstName.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on first name';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on first name';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.firstName,\n\t\t\t\"firstName\",\n\t\t\tsortByFirstNameAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByFirstName,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByLastName.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on last name';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on last name';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.lastName,\n\t\t\t\"lastName\",\n\t\t\tsortByLastNameAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByLastName,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByParty.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on party';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.party,\n\t\t\t\"party\",\n\t\t\tsortByPartyAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByParty,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByState.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on state';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on state';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.state,\n\t\t\t\"state\",\n\t\t\tsortByStateAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByState,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortBySeniority.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-numeric-up\"></i> Sort on seniority';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on seniority';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.seniority,\n\t\t\t\"seniority\",\n\t\t\tsortBySeniorityAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortBySeniority,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByVotesWith.onclick = () => {\n\t\tlet sortStringAscendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-up\"></i> Sort on votes with party';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on votes with party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.partyVotesWith,\n\t\t\t\"partyVotesWith\",\n\t\t\tsortByVotesWithAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByVotesWith,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByVotesAgainst.onclick = () => {\n\t\tlet sortStringAscendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-up\"></i> Sort on votes against party';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on votes against party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.partyVotesAgainst,\n\t\t\t\"partyVotesAgainst\",\n\t\t\tsortByVotesAgainstAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByVotesAgainst,\n\t\t\tundefined\n\t\t);\n\t};\n}",
"function addClick(recipeTitle, recipeBody, fullRecipeContainer) {\n\trecipeTitle.addEventListener('click', function() {\n\t\trecipeBody.classList.toggle('appear');\n\t\trecipeBody.classList.remove('col-sm-5');\n\t\tfullRecipeContainer.classList.toggle('col-sm-12');\n\t});\n}",
"searchedCards(result) {\n let cardListDOM = document.querySelector(\".card-list\")\n // Cleaning cardList's innerHTML for every calling\n cardListDOM.innerHTML = \"\"\n // Creating cards for searched meals\n result.forEach((food) => {cardListDOM.innerHTML += `\n <div id=${food.item.id} class=\"card\">\n <img src=${food.item.fields.strMealThumb}>\n <h3>${food.item.fields.strMeal}</h3>\n <button id=${food.item.id} class=\"details-button\">See Details</button>\n </div>\n `})\n // Calls openModal func to open modal for selected meal\n let detailsButtonDOM = document.querySelectorAll(\".details-button\")\n detailsButtonDOM.forEach(btn => btn.addEventListener(\"click\", (e) => {\n this.openModals(e.target.id)\n }))\n }",
"function addModalPlayerActions() {\r\n var modalPlayers = Array.from(document.getElementsByClassName('modal-player-sprite-container'));\r\n modalPlayers.forEach(modalPlayer => {\r\n modalPlayer.addEventListener(\"click\", () => {\r\n changePlayer(modalPlayer);\r\n });\r\n });\r\n}",
"function displayEmployeeModal(index) {\n let employee = employees[index];\n let firstName = capitalize(employee.name.first);\n let lastName = capitalize(employee.name.last);\n let address = formatAddress(employee);\n let dob = formatDateOfBirth(employee.dob);\n let modalContent = '<div class=\"modal-content\">';\n modalContent += '<span class=\"close\">×</span>';\n modalContent += '<img src=\"' + employee.picture.large + '\">';\n modalContent += '<p><strong>' + firstName + ' ' + lastName + '</strong><br>';\n modalContent += '<br>' + employee.login.username + '<br>' + employee.email + '<br>';\n modalContent += '<br><hr><br>' + employee.cell + '<br><br>';\n modalContent += address + '<br>';\n modalContent += 'Birthday: ' + dob + '</p>';\n modalContent += '<span class=\"buttons\">';\n modalContent += '<button class=\"back\">Back</button>'\n modalContent += '<button class=\"next\">Next</button></span>';\n modalContent += '</div>';\n $('#employee-modal').append(modalContent);\n $('.modal').css('display', 'block');\n addEventListenersToModal(index);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: $iq Create a Strophe.Builder with an element as the root. Parameters: (Object) attrs The element attributes in object notation. Returns: A new Strophe.Builder object. | function $iq(attrs) { return new Strophe.Builder("iq", attrs); } | [
"static attach(element) {\n return new DomBuilder(element);\n }",
"function MyCreateElement(type, attrs={}) {\n var elem = document.createElement(type);\n for (var key in attrs)\n elem.setAttribute(key, attrs[key]);\n return elem;\n}",
"static get Builder() {\n class Builder {\n withAvailableQuantity(availableQuantity) {\n this.availableQuantity = availableQuantity;\n return this;\n }\n\n withId(id) {\n this.id = id;\n return this;\n }\n\n withProductId(productId) {\n this.productId = productId;\n return this;\n }\n\n build() {\n return new InventoryItem(this);\n }\n }\n return Builder;\n }",
"function createJQObjectNoText(tag, attributes, $parent) {\n var $jQObj = $(tag, attributes);\n $jQObj.appendTo($parent);\n return $jQObj;\n}",
"function createJQObject(tag, attributes, text, $parent) {\n var $jQObj = $(tag, attributes);\n $jQObj.text(text);\n $jQObj.appendTo($parent);\n return $jQObj;\n}",
"function TOCBuilder () {\n\tthis.__toc = new TOC();\n\tthis.__idPrefix = '';\n\tthis.hardCut();\n}",
"makeWidget(els) {\r\n let el = GridStack.getElement(els);\r\n this._prepareElement(el, true);\r\n this._updateContainerHeight();\r\n this._triggerAddEvent();\r\n this._triggerChangeEvent();\r\n return el;\r\n }",
"dom(lastJstComponent, lastJstForm) {\n\n // TEMP protection...\n if (this.tag === \"-deleted-\") {\n console.error(\"Trying to DOM a deleted element\", this);\n return undefined;\n }\n let el = this.el;\n\n if (!el) {\n if (this.ns) {\n el = document.createElementNS(this.ns, this.tag);\n }\n else {\n el = document.createElement(this.tag);\n }\n }\n\n // If the element parameters contains a 'ref' attribute, then fill it in\n if (this.ref && lastJstComponent) {\n lastJstComponent.setRef(this.ref, this);\n }\n\n // Handle forms\n if (lastJstComponent && this.tag === \"form\" && (this.attrs.name || this.attrs.ref || this.attrs.id)) {\n lastJstForm = lastJstComponent.addForm(this);\n }\n else if (lastJstForm &&\n (this.tag === \"input\" ||\n this.tag === \"textarea\" ||\n this.tag === \"select\")) {\n lastJstForm.addInput(this);\n }\n\n if (!this.isDomified) {\n \n this.jstComponent = lastJstComponent;\n\n // Handle all the attributes on this element\n for (let attrName of Object.keys(this.attrs)) {\n let val = this.attrs[attrName];\n\n // Special case for 'class' and 'id' attributes. If their values start with\n // '-' or '--', add the scope to their values\n if (lastJstComponent && (attrName === \"class\" || attrName === \"id\") &&\n val.match && val.match(/(^|\\s)-/)) {\n val = val.replace(/(^|\\s)(--?)/g,\n (m, p1, p2) => p1 +\n (p2 === \"-\" ? lastJstComponent.getClassPrefix() :\n lastJstComponent.getFullPrefix()));\n }\n el.setAttribute(attrName, val);\n }\n\n // Add the properties\n for (let propName of this.props) {\n el[propName] = true;\n }\n\n // Add event listeners\n for (let event of Object.keys(this.events)) {\n // TODO: Add support for options - note that this will require\n // some detection of options support in the browser...\n el.addEventListener(event, this.events[event].listener);\n }\n \n // Now add all the contents of the element\n this._visitContents(\n lastJstComponent,\n // Called per JstElement\n (jstComponent, item) => {\n \n if (item.type === JstElementType.TEXTNODE) {\n if (!item.el) {\n item.el = document.createTextNode(item.value);\n el.appendChild(item.el);\n }\n }\n else if (item.type === JstElementType.JST_ELEMENT) {\n let hasEl = item.value.el;\n let childEl = item.value.dom(jstComponent, lastJstForm);\n if (!hasEl) {\n el.appendChild(childEl);\n }\n else if (childEl.parentNode && childEl.parentNode !== el) {\n childEl.parentNode.removeChild(childEl);\n el.appendChild(childEl);\n }\n }\n else {\n console.error(\"Unexpected contents item type:\", item.type);\n }\n \n },\n // Called per JstComponent\n jstComponent => {\n jstComponent.parentEl = el;\n }\n );\n\n }\n\n this.el = el;\n this.isDomified = true;\n return el;\n\n }",
"function MakeSVGContainer(config) {\n\tthis.node = config.node;\n\tthis.maxWid = config.maxWid;\n\tthis.maxHt = config.maxHt;\n\tthis.id = this.node.attr(\"id\");\n\n\t//create an svg element of the appropriate size and scaling\n\tthis.rootEl = this.node.append(\"svg\").attr(\"viewBox\", \"0 0 \" + this.maxWid + \" \" + this.maxHt)\n\t//makes it scale correctly in narrow-window, single-column or phone layouts\n\t.attr(\"preserveAspectRatio\", \"xMinYMin meet\") //ditto\n\t.attr(\"id\", this.id).style(\"max-width\", this.maxWid + \"px\")\n\t//max width works to make it lay out to scale\n\t.style(\"max-height\", this.maxHt + \"px\");\n\n}",
"createEl(tag = 'div', props = {}, attrs = {}) {\n\t\tprops = assign({\n\t\t\tclassName: 'ntk-dialog'\n\t\t}, props);\n\t\t\n\t\tconst el = super.createEl(tag, props, attrs);\n\t\t\n\t\treturn el;\n\t}",
"function createElements() {\r\n _dom = {};\r\n createElementsForSelf();\r\n if (_opts.placement.popup) {\r\n createElementsForPopup();\r\n }\r\n createElementsForColorWheel();\r\n createElementsForNumbersMode();\r\n createElementsForSamples();\r\n createElementsForControls();\r\n }",
"function BAElement() { }",
"create() {\n this.children = { };\n this.container = document.createElement(\"div\");\n for (var key in this.data) {\n this.children[key] = interfaceUnit(this.data[key], this.container);\n }\n return this.container;\n }",
"createSVGElement(w,h){const svgElement=document.createElementNS(svgNs$1,'svg');svgElement.setAttribute('height',w.toString());svgElement.setAttribute('width',h.toString());return svgElement;}",
"function buildDom(htmlString) {\r\n const div = document.createElement(\"div\");\r\n div.innerHTML = htmlString;\r\n return div.children[0];\r\n}",
"function createNode(type, attributes, props) {\r\n var node = document.createElement(type);\r\n if (attributes) {\r\n for (var attr in attributes) {\r\n if (! attributes.hasOwnProperty(attr)) continue;\r\n node.setAttribute(attr, attributes[attr]);\r\n }\r\n }\r\n if (props) {\r\n for (var prop in props) {\r\n if (! props.hasOwnProperty(prop)) continue;\r\n if (prop in node) node[prop] = props[prop];\r\n }\r\n }\r\n return node;\r\n }",
"_buildDOM() {\n const HTML = this.render();\n if (!HTML) { return }\n this.DOMbuilder.build( HTML );\n }",
"function buildNode(id, name, parent){\n\t\tvar element = $(\"<li><a>\" + name + \"</i></a></li>\");\n\t\t\n\t\t$('a', element).attr('data-remote','true');\n\t\t$('a', element).attr('data-tagname', name);\n\t\t$('a', element).attr('href', window.location.href + '/?tag=' + name);\n\t\tparent.append(element); \n\t\treturn element;\n\t}",
"createHTMLElement(parent){\n let htmlElement=document.createElement(this.htmlTagName);\n this.parent=parent;\n this.parent.appendChild(htmlElement);\n this.htmlElementId=getUniqueId(parent,this.htmlTagName);\n htmlElement.id=this.htmlElementId;\n this.applyStyleToElement();\n widgets[this.htmlElementId]=this;\n }",
"function createPlainElement(name, attributes, children) {\n attributes = Object.freeze(attributes || {});\n const element = new Element('plain', { name: name, attributes: attributes });\n const properties = Memory.getObject(allProperties, element);\n properties.children = getChildElements(element, children);\n return element;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a TLO node to the graph Takes a valid TLO object as input. | function addTlo(tlo) {
if(idCache[tlo.id]) {
console.log("Already added, skipping!", tlo)
} else {
if(typeGroups[tlo.type] === undefined) {
typeGroups[tlo.type] = typeIndex++;
}
tlo.typeGroup = typeGroups[tlo.type];
idCache[tlo.id] = currentGraph.nodes.length; // Edges reference nodes by their array index, so cache the current length. When we add, it will be correct
currentGraph.nodes.push(tlo);
labelGraph.nodes.push({node: tlo}); // Two labels will orbit the node, we display the less crowded one and hide the more crowded one.
labelGraph.nodes.push({node: tlo});
labelGraph.edges.push({
source : (labelGraph.nodes.length - 2),
target : (labelGraph.nodes.length - 1),
weight: 1
});
}
} | [
"addNode(value) {\r\n // create a new node\r\n const node = new Node(value)\r\n // add node to the nodes map\r\n this.nodes.set(node, new Map())\r\n // return the new node\r\n return node;\r\n }",
"add(noodle, container, constr, label, pos, noodleExp) {\n var node = constr(noodle, container, label, pos, noodleExp);\n container.forest.push(node);\n var nodeNoodle = node.noodle || noodle.expr.eval(noodle, node.noodleExp);\n nodeNoodle.node.render(node, container);\n nodeNoodle.graphics.transformable.setActive(nodeNoodle, node.html); //Should this be inside render?\n\n return node;\n }",
"function addNodeAndLink(e, obj) {\n var adornment = obj.part\n var diagram = e.diagram\n diagram.startTransaction('Add State')\n\n // get the node data for which the user clicked the button\n var fromNode = adornment.adornedPart\n var fromData = fromNode.data\n // create a new \"State\" data object, positioned off to the right of the adorned Node\n var toData = { text: 'new' }\n var p = fromNode.location.copy()\n p.x += 200\n toData.loc = GO.Point.stringify(p) // the \"loc\" property is a string, not a Point object\n // add the new node data to the model\n var model = diagram.model\n model.addNodeData(toData)\n\n // create a link data from the old node data to the new node data\n var linkdata = {\n from: model.getKeyForNodeData(fromData), // or just: fromData.id\n to: model.getKeyForNodeData(toData),\n text: 'transition'\n }\n // and add the link data to the model\n model.addLinkData(linkdata)\n\n // select the new Node\n var newnode = diagram.findNodeForData(toData)\n diagram.select(newnode)\n\n diagram.commitTransaction('Add State')\n\n // if the new node is off-screen, scroll the diagram to show the new node\n diagram.scrollToRect(newnode.actualBounds)\n }",
"append(node) {\n\n // Checks if argument is a node:\n if (node instanceof YngwieNode) {\n\n // If given node has parent, detach that node from it's parent:\n if (node._parent) {\n node.detach();\n }\n\n // Set new node as last sibling:\n if (this._first !== undefined) {\n node._prev = this._last; // Sets new last child's previous node to old last node\n this._last._next = node; // Set old last child next element to new last child\n this._last = node; // Set new last child to given node\n } else {\n // If ther are no children, then this node is an only child:\n this._first = node;\n this._last = node;\n }\n\n // Set parent\n node._parent = this;\n\n // Return instance:cosnole\n return this;\n\n }\n\n throw new _Error_main_js__WEBPACK_IMPORTED_MODULE_0__.default(\"Can only apppend YngwieNode to other YngwieNodes\", node);\n\n }",
"addChild(value) {\n const newTreeNode = new Tree(value);\n this.children.push(newTreeNode);\n }",
"function addNode(kind) {\n var node = null;\n\n // must not be in top block scope\n if (currentBlock === topBlock)\n return;\n\n // create node based on kind; it gets a reference to the current block's\n // logic object\n node = createVisual(ctx,kind,currentBlock.getLogic());\n\n if (node != null) {\n modified = true;\n currentBlock.addChild(node);\n drawScreen();\n }\n }",
"function put_to_nodes(node, obj) {\n\t var leaf = isleaf(node, obj);\n\t if (leaf.leaf) node.l.push(obj);else if (leaf.childnode) _put(leaf.childnode, obj);else return;\n\t }",
"async function addNodes() {\n const territoryKeys = Object.keys(territoryGraph);\n let lenTerritories = territoryKeys.length;\n while (lenTerritories) {\n lenTerritories -= 1;\n const territoryKey = territoryKeys[lenTerritories];\n territoryGraphStructure.add(territoryKey);\n }\n}",
"addPerson( args ) {\n let person = new NodePerson( this.idNodes, args );\n this.nodes.add( person );\n this.idNodes += 1;\n }",
"function addLaneEvent(lane) {\n\t\t myDiagram.startTransaction(\"addLane\");\n\t\t if (lane != null && lane.data.category === \"Lane\") {\n\t\t // create a new lane data object\n\t\t var shape = lane.findObject(\"SHAPE\");\n\t\t var size = new go.Size(shape.width, MINBREADTH);\n\t\t //size.height = MINBREADTH;\n\t\t var newlanedata = {\n\t\t category: \"Lane\",\n\t\t text: \"New Lane\",\n\t\t color: \"white\",\n\t\t isGroup: true,\n\t\t loc: go.Point.stringify(new go.Point(lane.location.x, lane.location.y + 1)), // place below selection\n\t\t size: go.Size.stringify(size),\n\t\t group: lane.data.group\n\t\t };\n\t\t // and add it to the model\n\t\t myDiagram.model.addNodeData(newlanedata);\n\t\t }\n\t\t myDiagram.commitTransaction(\"addLane\");\n\t\t }",
"addNode(n) {\n if (!this.getNode(n)) {\n const tempNode = node.create({ name: n });\n const clone = this.nodes.slice(0);\n clone.push(tempNode);\n this.nodes = clone;\n\n return tempNode;\n }\n\n return null;\n }",
"addAdjacent(node) {\n this.adjacents.push(node);\n }",
"addToHead(val) {\n // console.log('something')\n\n const node = new Node(val)\n if(this.head === null){\n this.head = node;\n this.tail = node;\n\n } else {\n const temp = this.head;\n this.head = node;\n this.head.next = temp;\n\n }\n\n this.length++\n return this\n }",
"function parseTLOs(container) {\n var cap = container.length;\n for(var i = 0; i < cap; i++) {\n // So, in theory, each of these should be a TLO. To be sure, we'll check to make sure it has an `id` and `type`. If not, raise an error and ignore it.\n var maybeTlo = container[i];\n if(maybeTlo.id === undefined || maybeTlo.type === undefined) {\n console.error(\"Should this be a TLO???\", maybeTlo)\n } else {\n addTlo(maybeTlo);\n }\n }\n}",
"add(o){\n\t\t\twhile(this.cases[o.getY()][o.getX()][\"TILE\"].getCollide()){\n\t\t\t\t\tvar r = rand(0 ,1);\n\t\t\t\t\tif(r == 0){\n\t\t\t\t\t\to.x++;\n\t\t\t\t\t}else{\n\t\t\t\t\t\to.y++;\n\t\t\t\t\t}\n\t\t\t}\n\t\t\tvar t = this.cases[o.getY()][o.getX()];\n\t\t\tif(o instanceof Objet){\n\t\t\t\tt[\"OBJET\"] = o;\n\t\t\t\tthis.stage.appendChild(o.sprite);\n\t\t\t\to.afficher();\n\t\t\t}\n\t\t\tif(o instanceof Entite){\n\t\t\t\tt[\"ENTITE\"] = o;\n\t\t\t\tthis.stage.appendChild(o.div);\n\t\t\t\to.currentStage = this;\n\t\t\t}\n\t\t\t\n\n\t}",
"function OrionTXNode(config) {\n RED.nodes.createNode(this, config);\n var node = this;\n node.orion_config = RED.nodes.getNode(config.orion_config);\n node.username = node.orion_config.credentials.username;\n node.password = node.orion_config.credentials.password;\n var groupIds = node.orion_config.groupIds.split(',');\n\n node.status({fill: 'yellow', shape: 'dot', text: 'Idle'});\n\n node.on('input', function(msg) {\n var lyreOptions = {\n 'username': node.username,\n 'password': node.password,\n 'groupIds': msg.hasOwnProperty('groupIds') ? msg.groupIds : groupIds,\n 'message': msg.hasOwnProperty('message') ? msg.message : null,\n 'media': msg.hasOwnProperty('media') ? msg.media : null,\n 'target': msg.hasOwnProperty('target') ? msg.target : null,\n };\n node.status({fill: 'green', shape: 'dot', text: 'Transmitting'});\n orion.lyre(lyreOptions);\n node.status({fill: 'yellow', shape: 'dot', text: 'Idle'});\n });\n\n node.on('close', function() {\n return;\n });\n }",
"function addNode(mainType, subType, e) {\n\n // 0. add node info to node list\n // mainType, subType, widgetId, inputs, outputs\n var newNode = initNode(mainType, subType, currentWidgetId, null, null, null)\n // 1. add this node to current widget\n addNodeToWidget(currentWidgetId, newNode)\n\n if (newNode.type == \"widget\") {\n var widgetId = getWidgetIdFromNodeId(newNode.id)\n initWidgetToList(currentWidgetId, newNode.id, widgetId)\n initWidget(widgetId, newNode.widgetType)\n console.log(\"Add new widget-node!!!!!!!!!!!!!!!!!\")\n console.log(widgetList)\n }\n\n\n // offset of cursor\n // TODO: use node width/height to set diffX/diffY\n var diffX = 9 * 16 / 2\n var diffY = 4 * 16 / 2 + 36\n\n var canvasId = getCanvasIdFromWidgetId(currentWidgetId)\n var X = $('#' + canvasId).offset().left + diffX\n var Y = $('#accordion').offset().top + diffY\n\n jsplumbUtils.newNode(window.instance, e.clientX - X, e.pageY - Y, newNode);\n\n // 2. add description/inputs/output at console\n showNodeInfo(newNode)\n\n // 3. set current node is this\n setCurrentNode(newNode.id)\n \n\n console.log(\"current widget is !!!!\")\n console.log(widgetList)\n}",
"pushNode(node) {\n this.stack.push(new Frame(node));\n }",
"addToTail(value) {\n const newNode = {\n value: value,\n next: null\n };\n\n if (!this.head && !this.tail) {\n this.head = newNode;\n this.tail = newNode;\n return;\n }\n this.tail.next = newNode;\n this.tail = newNode;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines whether an API validation error is safe to ignore. It checks for known validation errors in certain API definitions on APIs.guru | function shouldIgnoreError (api, error) {
var safeToIgnore = [
// Swagger 3.0 files aren't supported yet
{ error: 'not a valid Swagger API definition' },
// Many Azure API definitions erroneously reference external files that don't exist
{ api: 'azure.com', error: /Error downloading .*\.json\s+HTTP ERROR 404/ },
// Many Azure API definitions have endpoints with multiple "location" placeholders, which is invalid
{ api: 'azure.com', error: 'has multiple path placeholders named {location}' },
{ api: 'azure.com', error: 'Required property \'location\' does not exist' },
// Stoplight.io's API definition uses multi-type schemas, which isn't allowed by Swagger 2.0
{ api: 'stoplight.io', error: 'invalid response schema type (object,string)' },
// VersionEye's API definition is missing MIME types
{ api: 'versioneye.com', error: 'has a file parameter, so it must consume multipart/form-data or application/x-www-form-urlencoded' },
// Many API definitions have data models with required properties that aren't defined
{ api: 'azure.com:apimanagement-apimdeployment', error: 'Required property \'sku\' does not exist' },
{ api: 'azure.com:compute', error: 'Required property \'name\' does not exist' },
{ api: 'azure.com:recoveryservices-registeredidentities', error: 'Required property \'certificate\' does not exist' },
{ api: 'azure.com:resources', error: 'Required property \'code\' does not exist' },
{ api: 'azure.com:servicefabric', error: 'Required property \'ServiceKind\' does not exist' },
{ api: 'azure.com:timeseriesinsights', error: 'Required property \'dataRetentionTime\' does not exist' },
{ api: 'iqualify.com', error: 'Required property \'contentId\' does not exist' },
];
for (var i = 0; i < safeToIgnore.length; i++) {
var expected = safeToIgnore[i];
var actual = { api: api.name, error: error.message };
if (isMatch(actual, expected)) {
// This error is safe to ignore because it's a known problem with this API definition
return true;
}
}
} | [
"function checkAPIKey() {\n if (mashapeAPIKey == null) {\n console.error('ERROR: API Key must be set!');\n }\n}",
"function checkAPIReturn(response) {\n if (response.status === 201 ||\n response.status === 200 ||\n response.status === 204 ||\n response.status === 205\n ) {\n return response;\n }\n const error = new Error(response.statusText);\n error.response = response;\n throw error;\n}",
"function isRequestValid(req){\n return !(req.body === undefined\n || Object.keys(req.body).length < 4\n || !supportedTypes.includes(req.body.type)\n || !activityFields.every(field => req.body.hasOwnProperty(field)));\n}",
"hasMissingMapping() {\n let isMissing = false;\n\n try {\n this._getAPIDiseases();\n } catch (err) {\n isMissing = true;\n }\n\n try {\n this._getAPIInterventions();\n } catch (err) {\n isMissing = true;\n }\n\n //Phase\n try {\n this._getAPIPhases();\n } catch (err) {\n isMissing = true;\n }\n\n //trialtype\n try {\n this._getAPITrialTypes();\n } catch (err) {\n isMissing = true;\n }\n\n return isMissing;\n }",
"function isIngressValid(o) {\n annotations = o.metadata.annotations;\n Object.keys(definitions).forEach(function(key) {\n if (annotations[key]) {\n filter = definitions[key];\n if (!filter.exec(annotations[key])) {\n deny(\"metadata.annotations[\"+key+\"]\", \"invalid user input, should match: \"+ filter.toString(), annotations[key]);\n }\n }\n });\n}",
"function getValidatedApiConfig(config) {\n if ('url' in config) {\n var valid = new Validator()\n .ofType('string').minLength(1)\n .validate(config.url, 'API url config setting');\n if (!valid)\n delete config.url;\n }\n if ('authToken' in config) {\n var valid = new Validator()\n .ofType('string').minLength(1)\n .validate(config.authToken, 'API authToken config setting');\n if (!valid)\n delete config.authToken;\n }\n return config;\n}",
"static checkParamsValidity (channel) {\n const { clientId, clientSecret, serviceId } = channel\n channel.phoneNumber = channel.phoneNumber.split(' ').join('')\n\n if (!clientId) { throw new BadRequestError('Parameter is missing: Client Id') }\n if (!clientSecret) { throw new BadRequestError('Parameter is missing: Client Secret') }\n if (!serviceId) { throw new BadRequestError('Parameter is missing: Service Id') }\n if (!channel.phoneNumber) { throw new BadRequestError('Parameter is missing: Phone Number') }\n\n return true\n }",
"function checkErrors(data) {\n\tif (data['error'] !== false) {\n\t\tconsole.log(data['error']);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function isMissingPropertyError(validate, type) {\n if (!validate.errors) return false;\n\n return validate.errors.some((err) => {\n return err.params.missingProperty === type;\n });\n}",
"async function validate(model, body) {\n\tconst validationRes = swaggerModel.validateModel(model, body, true, true);\n\tif (validationRes.valid) return;\n\n\tthrow new ValidationError({\n\t\terrors: validationRes.GetErrorMessages(),\n\t});\n}",
"function validatePhoto( req, res, next){\n\treq.checkBody('description', 'Invalid description').notEmpty();\n\treq.checkBody('album_id', 'Invalid album_id').isNumeric();\n// checks whether the validation lib detected any issues with the performed tests\n\tvar errors = req.validationErrors();\n\tif (errors) {\n\t\tvar response = {errors: [] };\n\t\terrors.forEach(function(err){\n\t\t\tresponse.errors.push(err.msg);\n\t\t});\n\n\t\tres.statusCode = 400;\n\t\treturn res.json(response);\n\t}\n\treturn next();\n\t\n}",
"function API_Endpoint_Ok(url){\n // ignore the query string, it will be handled by the targeted controller\n let queryStringMarkerPos = url.indexOf('?');\n if (queryStringMarkerPos > -1)\n url = url.substr(0, queryStringMarkerPos);\n // by convention api endpoint start with /api/...\n if (url.indexOf('/api/') > -1) {\n // extract url componants, array from req.url.split(\"/\") should \n // look like ['','api','{resource name}','{id}]'\n let urlParts = url.split(\"/\");\n // do we have a resource name?\n if (urlParts.length > 2) {\n // by convention controller name -> NameController\n controllerName = capitalizeFirstLetter(urlParts[2]) + 'Controller';\n // do we have an id?\n if (urlParts.length > 3){\n if (urlParts[3] !== '') {\n id = parseInt(urlParts[3]);\n if (isNaN(id)) { \n response.badRequest();\n // bad id\n return false;\n } else\n // we have a valid id\n return true;\n\n } else\n // it is ok to have no id\n return true;\n } else\n // it is ok to have no id\n return true;\n }\n }\n // bad API endpoint\n return false;\n }",
"function apiError() {\n return ApiError;\n\n /**\n * Api error model\n * @param {number} statusCode\n * @param {string} message\n */\n function ApiError(statusCode, message) {\n Object.defineProperty(this, 'StatusCode', {\n value: statusCode,\n enumerable: true,\n writable: false,\n configurable: false\n });\n Object.defineProperty(this, 'Message', {\n value: message,\n configurable: false,\n enumerable: true,\n writable: false\n });\n }\n }",
"isErrorState() {\r\n const gl = this.gl;\r\n return gl === null || gl.getError() !== gl.NO_ERROR;\r\n }",
"function name_check() {\r\n name_warn();\r\n final_validate();\r\n}",
"validate({ getState, action, api }, allow, reject) {\n const state = getState().scenes.codingValidation.coding\n const user = getState().data.user.currentUser\n const isValidation = state.page === 'validation'\n \n // Get the question answer object to be sent to the API\n const questionObj = action.type === types.SAVE_USER_ANSWER_REQUEST\n ? getFinalCodedObject(\n state,\n { ...action, userId: user.id },\n isValidation,\n action.selectedCategoryId\n ) : copyCoderAnswer(\n state,\n { ...action, userId: user.id },\n action.selectedCategoryId\n )\n \n const apiMethods = {\n create: isValidation ? api.answerValidatedQuestion : api.answerCodedQuestion,\n update: isValidation ? api.updateValidatedQuestion : api.updateCodedQuestion\n }\n \n const payloadObject = {\n questionId: action.questionId,\n jurisdictionId: action.jurisdictionId,\n projectId: action.projectId,\n userId: user.id,\n user,\n questionObj,\n queueId: `${action.questionId}-${action.jurisdictionId}-${action.projectId}-${action.selectedCategoryId}`,\n timeQueued: Date.now()\n }\n \n // Check if there's already a POST request in progress for this question.\n if (questionObj.isNewCodedQuestion && questionObj.hasMadePost && !questionObj.hasOwnProperty('id')) {\n // The question hasn't been answered at all before, but a request has been made. Move request to queue to\n // wait for a response.\n reject({ type: types.ADD_REQUEST_TO_QUEUE, payload: { ...payloadObject, inQueue: true } })\n } else {\n // Allows the request to go through without putting it in the queue\n allow({\n ...action,\n payload: {\n ...payloadObject,\n selectedCategoryId: action.selectedCategoryId,\n api: apiMethods,\n create: !questionObj.hasOwnProperty('id'),\n inQueue: false\n }\n })\n }\n }",
"hasControlErrors(name) {\r\n const control = this.get(name);\r\n return !!(control && control.errors);\r\n }",
"static isValidReview(review) {\r\n // {\r\n // \"restaurant_id\": <restaurant_id>,\r\n // \"name\": <reviewer_name>,\r\n // \"rating\": <rating>,\r\n // \"comments\": <comment_text>\r\n // }\r\n let isValid = true;\r\n if (\r\n !review ||\r\n !Number.isInteger(Number(review.restaurant_id)) ||\r\n !Number.isInteger(Number(review.rating)) ||\r\n !(review.rating > 0 && review.rating < 6) ||\r\n !validator.isAlpha(review.name) ||\r\n !validator.isLength(review.comments, { min: 1, max: 140 })\r\n ) {\r\n isValid = false;\r\n }\r\n return isValid;\r\n }",
"function validate(req) {\n req.checkBody('firstName', 'Invalid firstName').notEmpty();\n req.checkBody('lastName', 'Invalid lastName').notEmpty();\n req.checkBody('dob', 'Date of birth must be in the past').isBefore();\n req.checkBody('password', 'Invalid password').notEmpty();\n req.checkBody('passwordRepeat', 'Invalid password').notEmpty();\n req.checkBody('gender', 'Invalid password').notEmpty();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
APP crea un metodo de pago por un usuario | function crearMetodoDePago(metodo) {
return new Promise(async (resolve, reject) => {
try {
if (!metodo) {
return reject(new Error("faltan datos"));
}
const id = await store.crearMetodoDePago(metodo);
return resolve(id);
} catch (error) {
return reject(error);
}
});
} | [
"function carregarFornecedor() {\n apiService.get('/api/fornecedor/perfil', null,\n carregarMembroSucesso,\n carregarMembroFalha);\n }",
"createTipo ({\n commit\n }, tipo) {\n ApiService.postTipo(tipo).then((response) => {\n tipo.idTipo = response.data.idTipo // retorna el nuevo identificador creado por el servidor\n\n commit('ADD_TIPO', tipo)\n }).catch(error => {\n console.log('ERROR:', error.message)\n })\n }",
"async function registrarPedido(parent, args, { usuario, prisma }) {\n\tconst mesa = await prisma.mesa.findOne({\n\t\twhere: { id: parseInt(args.mesa) },\n\t\tselect: { ocupado: true },\n\t});\n\tif (!mesa.ocupado) {\n\t\tconst data = {\n\t\t\tpersonal: { connect: { id: usuario.id } },\n\t\t\tmesa: { connect: { id: parseInt(args.mesa) } },\n\t\t\tproductos: {\n\t\t\t\tcreate: args.productos.map((i) => {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproducto: { connect: { id: parseInt(i.producto) } },\n\t\t\t\t\t\tprecio: parseFloat(i.precio),\n\t\t\t\t\t\tcantidad: parseInt(i.cantidad),\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t},\n\t\t};\n\t\tconst pedidoAgregado = await prisma.pedido\n\t\t\t.create({ data })\n\t\t\t.catch((err) => null);\n\t\tpubsub.publish(PEDIDO_AGREGADO, { pedidoAgregado });\n\t\treturn pedidoAgregado;\n\t} else {\n\t\tthrow new Error(MESA_OCUPADA);\n\t}\n}",
"function Postagem(titulo,mensagem,autor) {\n this.titulo = titulo,\n this.mensagem = mensagem,\n this.autor= autor,\n this.visualizacoes= 0,\n this.comentarios = [],\n this.estaAoVivo= false\n}",
"visitCreate_user(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function create(nomeaula){\n idNovaAula = gerarId();\n let novaAula={id:idNovaAula,nome:nomeaula};\n idNovaAula++;\n return $http.post(urlBase + '/aula/', novaAula);\n }",
"function primeraPagina(){\n\tif(pagina_actual!=1){\n\t\t\n\t\tpagina_actual = 1;\n\t\tconsole.log('Moviendonos a la página '+pagina_actual+\"...\");\n\t\tborrar_recetas_index();\n\t\tlet pagina = pagina_actual-1;\n\t\tpeticionRecetas(\"./rest/receta/?pag=\"+pagina+\"&lpag=6\");\n\t\tModificar_botonera_Index();\n\t}\n}",
"setCreator (user) {\n if (typeof user === 'string') {\n this.creator.path = 'Users/' + user\n } else {\n this.creator.path = 'Users/' + user.key\n }\n }",
"function agregarPeli () {\n\n\t\t//Tomamos los valores de los inputs del titulo, la descripcion y la imagen.\n\t\tvar nuevoTitulo = document.getElementById('titulo').value;\n\t\tvar nuevaDescripcion = document.getElementById('descripcion').value;\n\t\tvar rutaImagen = document.getElementById('imagen').value;\n\n\t\t//Con esos valores, creamos un nuevo objeto \"pelicula\"\n\t\tvar pelicula = {\n\t\t\tid: peliculas.length + 1, //Con esto le damos un id diferente a cada peli que creemos\n\t\t\ttitulo:nuevoTitulo,\n\t\t\tdescripcion:nuevaDescripcion,\n\t\t\timagen:rutaImagen\n\t\t}\n\n\t\t//Finalmente ponemos nuestra pelicula en nuestro array de películas.\n\t\tpeliculas.push(pelicula);\n\t\talert('Película agregada correctamente');\n\t\tconsole.log(peliculas);\n\n\t}",
"function addTodo(user, todo) {\n user.todos.push(todo);\n LocalStorageManager.save();\n }",
"function treinarGrupo() {\n\n \n\n}",
"function loadFormaPagto() {\n apiService.get('/api/fornecedor/formaPagto', null,\n loadFormaPagtoSucesso,\n loadFormaPagtoFailed);\n }",
"function inserirUsuario() {\n if ($scope.novoUsuario.Id > 0) {\n atualizarModelUsuario();\n\n } else {\n inserirModelUsuario();\n }\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 crearObservaciones(data){\n var deferred = $q.defer();\n $http.post(appConstant.LOCAL_SERVICE_ENDPOINT + \"/crearObservaciones\", data).then(function (res) {\n deferred.resolve(res);\n }, function (err) {\n deferred.reject(err);\n console.log(err);\n });\n return deferred.promise;\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}",
"static createInvoiceItem(invoice_id, user_id, role, advanced_price=0) {\n return axios.post(\n liabilities_url + 'invoice_items/',\n {\n invoice_id: invoice_id,\n user_id: user_id,\n role: role,\n advanced_price: advanced_price,\n }\n );\n }",
"function creaList(list, posicion){//crea la lista de datos de la posicion solicitada\n\tvar listHTML = '';\n\t\n\t\tlistHTML += '<ul>';\n\t\tlistHTML += '<li><h2>nombrePelicula: ' + list[posicion].nombrePelicula + '</h2></li>'; //nos entrega el dato del atributo segun la posicion que tenga en el objeto\n\t\tlistHTML += '<li>actor: ' + list[posicion].actor + '</li>';\n\t\tlistHTML += '<li>director: ' + list[posicion].director + '</li>';\n\t\tlistHTML += '<li>genero: ' + list[posicion].genero + '</li>';\n\t\tlistHTML += '<li>sinopsis: ' + list[posicion].sinopsis + '</li>';\n\t\tlistHTML += '<li><a href=' +list[posicion].imagen + ' alt = ' + list[posicion].nombrePelicula + '><img src=' +list[posicion].imagen + '/></a></li>';\n\n\tlistHTML += '</ul> <br>' ;// al final del HTML se agraga un espacio en blaco que diferencia a cada estudiante\n\treturn listHTML; //retorna la lista listo para presentada\n}",
"function selecionarUsuario(usuario) {\n // Quando selecionei o usuario coloquei-o na factory (usuarioFactory)\n usuarioFactory.usuarioSelecionado = usuario;\n $location.path('/details');\n //$scope.usuarioSelecionado = usuarioFactory.usuarioSelecionado;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
from sugested location pick a random location and populate globale variables | function randomLocation(suggestedLocations) {
var obj_keys = Object.keys(suggestedLocations);
var ran_key = obj_keys[Math.floor(Math.random() * obj_keys.length)];
selectedLocation = suggestedLocations[ran_key];
console.log(selectedLocation);
console.log("Selected restaurant latitude is " + selectedLocation.position[0]);
console.log("Selected restaurant longitude is " + selectedLocation.position[1]);
restLat = selectedLocation.position[0];
restLong = selectedLocation.position[1];
restName = selectedLocation.title;
$("#selectedLoc").html(restName);
console.log("restaurant Name is " + restName);
//calling map and lyft function here to populate it with
//chosen restaurant co-ordinates
loadMapAndLyft();
} | [
"function randomLocatePacman(){\n\tif (shape.i != undefined && shape.j != undefined){\n\t\tboard[shape.i][shape.j] = 0;\n\t}\n\n\tlet pacmanCell = findRandomEmptyCell(board);\n\tboard[pacmanCell[0]][pacmanCell[1]] = 2;\n\tshape.i = pacmanCell[0];\n\tshape.j = pacmanCell[1];\n}",
"function randomRobot(state) { \n return {direction: randomPick(roadGraph[state.place])};\n}",
"function tredify(){\n\tvar mountains;\n\tvar pt = gen_points_in_map(map_dimension, square_dim);\n\tfor (var i=0; i<pt.length; i++){\n\t\tfor (var j=0; j<pt[i].length; j++){\n\t\t\n\t\t\tvar point_selected = pt[i][j];\n\t\t\tif (i===0 && j===0)\n\t\t\t\t//Initial point selected of the third coordinate, i declare the initial point.\n\t\t\t\tpoint_selected[2]=1;\n\t\t\telse{\n\t\t\t\tif (i===0) {\n\t\t\t\t\tpoint_selected[2] = randomizer(pt[i][j-1][2], 1.5);\n\t\t\t\t} \n\t\t\t\telse{\n\t\t\t\t\tpoint_selected[2] = randomizer(pt[i-1][j][2], 1.5);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn pt;\n}",
"function obstacleLocY() {\n var number = Math.floor(Math.random() * 5) + 1;\n if (number === 1) {\n return 58;\n } else if (number === 2) {\n return 141;\n } else if (number === 3) {\n return 224;\n } else if (number === 4) {\n return 307;\n } else {\n return 390;\n }\n}",
"function obstacleLocX() {\n var number = Math.floor(Math.random() * 3) + 1;\n if (number === 1) {\n return 200;\n } else if (number === 2) {\n return 300;\n } else {\n return 400;\n }\n}",
"function generateCoordinates () {\n direction = Math.floor(Math.random() * 10) % 2 === 1 ? 'vertical' : 'horizontal'\n locationX = Math.floor(Math.random() * (sizeX - 1))\n locationY = Math.floor(Math.random() * (sizeY - 1))\n if (direction === 'horizontal') {\n if ((locationX + shipSize) >= sizeX) {\n generateCoordinates()\n }\n } else {\n if ((locationY + shipSize) >= sizeY) {\n generateCoordinates()\n }\n }\n }",
"extractRandomRoom(rooms, floor) {\n var result = null;\n var floorLetter = floor.substr(0, 1)\n var roomAvaiable = false;\n for (var i = 0; i < rooms.length; i++) {\n if (rooms[i].Locations.indexOf(floorLetter) >= 0) {\n roomAvaiable = true;\n break;\n }\n }\n if (roomAvaiable) {\n while (result === null) {\n var roomNum = parseInt(Math.random() * rooms.length);\n var room = rooms[roomNum];\n if (room.Locations.indexOf(floorLetter) >= 0) {\n result = room;\n }\n }\n result.floor = floor\n rooms.splice(roomNum, 1)\n }\n return result;\n }",
"function randomMapPos(w,h,ox=0,oy=0){\n\treturn [Math.floor(Math.random()*(w-1))+1, Math.floor(Math.random()*(h-1)+1)];\n}",
"function randomPoint() { return pick(points); }",
"async seed(parent, {count, minLat, maxLat, minLng, maxLng}, ctx, info) {\n return await Promise.all(\n [...Array(count).keys()].map(async coordinates => {\n await ctx.db.mutation.createLocation(\n {\n data: {\n lat: chance.latitude({min: minLat, max: maxLat}),\n lng: chance.longitude({min: minLng, max: maxLng})\n },\n },\n info\n )\n })\n );\n }",
"function newFruitPosition(){\r\n\t\t//fruit_y = Math.round(Math.random()*height);\r\n\t\tfruit_x = getRandomNumber(fruit_size,width - fruit_size);\r\n\t\tfruit_y = getRandomNumber(fruit_size,height - fruit_size);\r\n\t}",
"genPosition(max_x, max_y, seg) {\r\n //make sure if there's still space for the fruit on the map.\r\n if (seg.length < (max_x + 1)*(max_y+1)) {\r\n //if there is still space choosing the random position on x and y from 0 to max width 'x' and max height 'y'\r\n let pos = {x: Math.floor(Math.random() * max_x), y: Math.floor(Math.random() * max_y)};\r\n\r\n let collide = false;\r\n //Checking if the fruit collides with the snake\r\n //some method determines whether the specified callback function returns true for any element of an array.\r\n seg.some((cseg) => {\r\n if(cseg.x == pos.x && cseg.y == pos.y) {\r\n collide = true;\r\n return true;\r\n }\r\n });\r\n\r\n //If varaible collide will be true the fruit position must be cosen again\r\n if(collide) {\r\n this.genPosition(max_x, max_y, seg);\r\n //If not then assign the chosen position to varaibles x and y\r\n } else {\r\n this.x = pos.x;\r\n this.y = pos.y;\r\n //position has been generated so 'g' can be true\r\n this.g = true;\r\n }\r\n\r\n\r\n } else {\r\n this.g = false;\r\n }\r\n \r\n \r\n\r\n }",
"function randomGeo (center, radius) {\n var y0 = center.latitude\n var x0 = center.longitude\n var rd = radius / 111300 // about 111300 meters in one degree\n\n var u = Math.random()\n var v = Math.random()\n\n var w = rd * Math.sqrt(u)\n var t = 2 * Math.PI * v\n var x = w * Math.cos(t)\n var y = w * Math.sin(t)\n\n // Adjust the x-coordinate for the shrinking of the east-west distances\n var xp = x / Math.cos(y0)\n\n var newlat = y + y0\n var newlon = xp + x0\n\n return {\n 'latitude': newlat.toFixed(5),\n 'longitude': newlon.toFixed(5),\n 'distance': distance(center.latitude, center.longitude, newlat, newlon).toFixed(2)\n }\n}",
"function populateMountains() {\n\tmountains = [];\n\tfor (i = 0; i < 3; i++) {\n\t\tmountains[i] = {\n\t\t\tx: random(32),\n\t\t\ty: random(16),\n\t\t\theight: max(random(10), random(10))\n\t\t};\n\t}\n}",
"function setRandomLocation(entity, mapWidth, mapHeight) {\n let padding = 80;\n let isColliding = true;\n entity.x = Math.floor(Math.random() * ((mapWidth - entity.width - padding) - padding + 1)) + padding;\n entity.y = Math.floor(Math.random() * ((mapHeight - entity.height - padding) - padding + 1)) + padding;\n\n if (entity.game.terrain.length === 0) {\n isColliding = false;\n }\n while (isColliding) {\n for (let i = 0; i < entity.game.terrain.length; i++) {\n let other = entity.game.terrain[i];\n isColliding = entity.x < other.x + other.width\n && entity.x + entity.width > other.x\n && entity.y < other.y + other.height\n && entity.y + entity.height > other.y;\n if (isColliding) {\n entity.x = Math.floor(Math.random() * ((mapWidth - entity.width - padding) - padding + 1)) + padding;\n entity.y = Math.floor(Math.random() * ((mapHeight - entity.height - padding) - padding + 1)) + padding;\n }\n\n }\n }\n\n entity.spawnX = entity.x;\n entity.spawnY = entity.y;\n}",
"getRandomBurrow() {\n\t\treturn Phaser.Utils.Array.GetRandom(this.burrowLocations);\n\t}",
"function load_next_planet() {\n gamer.planet.type = gamer.next.type;\n gamer.planet.assigned = false;\n gamer.planet.removed = false;\n gamer.planet.checked = false;\n gamer.planet.x = gamer.x;\n gamer.planet.y = gamer.y;\n\n var sun = random(1,100);\n if(sun <= 3) {\n gamer.next.type = planet_types.sun;\n } else if(gamer.available_planets <= 5) {\n var types = [];\n for(var j = 0; j < map.rows; j++) {\n for(var i = 0; i < map.columns; i++) {\n var planet = map.planets[i][j];\n if(planet.type >= planet_types.mercury\n && planet.type <= planet_types.saturn\n && !planet.removed\n && !planet.assigned) {\n types.push(planet.type);\n }\n }\n }\n gamer.next.type = types[Math.floor(Math.random() * types.length)];\n } else {\n gamer.next.type = random(1,6);\n }\n }",
"function myMap() {\r\nlet allcountries = [[61.92410999999999,25.7481511],[-30.559482,\t22.937506],[15.870032,100.992541]];\r\nlet countryselector = [0,1,2];\r\nlet randomselection = countryselector[Math.floor(Math.random() * countryselector.length)];\r\nlet mapProp= {\r\n center:new google.maps.LatLng(allcountries[(randomselection)][0],allcountries[(randomselection)][1]),\r\n zoom:5,\r\n};\r\nlet map=new google.maps.Map(document.getElementById(\"googleMap\"),mapProp);\r\n}",
"selectRandomPlace(placeIDs) {\r\n const length = placeIDs.length;\r\n if (length === 0) {\r\n return -1;\r\n }\r\n const index = Math.floor((Math.random() * length));\r\n return index;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FunctionName: check_if_query_exists Params: req, queryVal globals: pyArgs purpose: if query variable exists, set the global argument object value to the query variable's value. return: N/A | function check_if_query_exists(req, queryVal){
if(req.query[queryVal] != undefined){
pyArgs[queryVal] = req.query[queryVal];
}
} | [
"_handleExists(callback, exists = true, conj = \"and\") {\r\n if (this._where) this._where += ` ${conj} `;\r\n var query = this._getQueryBy(callback);\r\n this._where += (exists ? \"\" : \"not \") + \"exists (\" + query.sql + \")\";\r\n this._bindings = this._bindings.concat(query._bindings);\r\n return this;\r\n }",
"async existsInDB() {\n let result = {\n dataValues: null\n };\n try {\n const tmpResult = await db.appModel.findOne({\n where: {\n appId: this.appId\n }\n });\n\n if (tmpResult) {\n result = tmpResult;\n this.setApp(result.dataValues);\n return true;\n }\n } catch (err) {\n new ErrorInfo({\n appId: this.appId,\n message: err.message,\n func: this.existsInDB.name,\n file: constants.SRC_FILES_NAMES.APP\n }).addToDB();\n }\n return false;\n }",
"function checkIfMatch(query, UFO){\n\tvar checkResult = true;\n\tquery.forEach(function(ele){\n\t\t// console.log(query);\n\t\tif(checkResult){\n\t\t\tif(ele[0] === \"occurred\" || ele[0] === \"reported\"){\n\t\t\t\tvar date = UFO[ele[0]].split(\" \")[0];\n\t\t\t\tcheckResult = ele[1] === date;\n\t\t\t}else{\n\t\t\t\tcheckResult = ele[1] === (UFO[ele[0]]+\"\").toLowerCase();\n\t\t\t}\n\t\t}\n\t});\n\treturn checkResult;\n}",
"function checkAliasExistSync(alias){\n return new Promise(resolve => {\n db.checkAliasId(alias,function(error,data){\n if(error){\n resolve(false);\n }\n if(data){ \n if(data.message=='FOUND'){\n resolve(true);\n }else{\n resolve(false);\n }\n }\n });\n });\n}",
"function connQueryRunSanity(){\n}",
"function checkID(documentID, databaseID , callback){\n\tvar database = conn.database(databaseID);\n\tdatabase.head(documentID, function(err, opt1, opt2){ \n\t\tif(opt2!='404') {\t\t\t\t\n\t\t\tcallback(true);\n\t\t}else{\n\t\t\t\n\t\t\tcallback(false);\n\t\t}\n\t})\n}",
"static isDefined(input) {\n return typeof (input) !== 'undefined';\n }",
"async function checkIfRefExist(userId) {\n const refs = await db_utils.execQuery(\n \"SELECT userId FROM dbo.Referees\" \n );\n if (refs.find((r) => r.userId === parseInt(userId))){\n return true;\n }\n return false;\n }",
"isQueryOperator (qs = null) {\n return queryOperators.hasOwnProperty(qs) == true;\n }",
"function canCreateBlankQuery() {\n return (currentQueryIndex == pastQueries.length -1 &&\n lastResult.query.trim() === pastQueries[pastQueries.length-1].query.trim() &&\n lastResult.status != newQueryTemplate.status &&\n !cwQueryService.executingQuery.busy);\n }",
"exists() {\n return null !== this._document;\n }",
"function queryExpectOnly(query, expected) {\n print();\n print(\"queryExpectOnly(\" + uneval(query) + \")\");\n var scripts = dbg.findScripts(query);\n var present = allScripts.filter(function (s) { return scripts.indexOf(s) != -1; });\n if (expected) {\n expected = expected.map(script);\n expected.forEach(function (s) {\n if (present.indexOf(s) == -1)\n assertEq(s + \" not present\", \"is present\");\n });\n present.forEach(function (s) {\n if (expected.indexOf(s) == -1)\n assertEq(s + \" is present\", \"not present\");\n });\n } else {\n assertEq(present.length, 0);\n }\n}",
"function DetermineAppID(u_inp) {\n if (NameOrID(u_inp)) {\n if (appIDMap.has(parseInt(u_inp, 10))) {\n appID = u_inp;\n validSearch = true\n } else {\n validSearch = false\n }\n\n } else if (UpCase_NameMap.has(u_inp.toUpperCase())) {\n validSearch = true;\n appID = appMap.get(UpCase_NameMap.get(u_inp.toUpperCase()));\n } else\n validSearch = false;\n\n\n}",
"function checkTitleExists(req, res, next) {\n if (!req.body.title) {\n return res.status(400).json({\n error: \"Params TITLE is required\"\n });\n }\n\n return next();\n}",
"function check_name_exist() {\r\tvar parameters = '/users/checkExist?name=' + encodeURIComponent($.trim($name.val())) + '&id=' + $('#id').val();\r\tcheck_exist($name_error,parameters,'该用户名称已存在!');\r}",
"function useFallbackQuery(queryKey, queryFn, fallback, options) {\n // Setup regular useQuery, but on different failure call the fallback to get returned data\n var result = react_query_1.useQuery(queryKey, queryFn, options);\n // Check if error is throwned or occured\n if (result.isError)\n return __assign(__assign({}, result), { data: fallback({ data: result.data, error: result.error }) });\n // Check if data still is undefined\n if (typeof result.data === \"undefined\")\n return __assign(__assign({}, result), { data: fallback({ data: result.data, error: result.error }) });\n return __assign(__assign({}, result), { data: result.data });\n}",
"async function checkIfMathcExists(game_time,home_team_id, away_team_id){\n let result = await DButils.execQuery(`SELECT gameid FROM Games Where GameDateTime = '${game_time}' AND\n ((HomeTeamID = ${home_team_id} AND AwayTeamID = ${away_team_id}) OR\n (HomeTeamID = ${away_team_id} AND AwayTeamID = ${home_team_id}))`)\n if(result.length > 0)\n return true\n\n return false\n}",
"_query_is_valid() {\n let valid = this._required.reduce((res, key) => {\n return res && this._param_is_set(key);\n }, true);\n\n for (let [parent_key, one_required] of Object.entries(this._one_required)) {\n valid =\n valid &&\n one_required.reduce((res, required_key) => {\n let key = parent_key ? `${parent_key}:${required_key}` : required_key;\n return res || this._param_is_set(key);\n }, false);\n }\n\n return valid;\n }",
"static async exists (name, last_name) {\n name = name.toUpperCase();\n last_name = last_name.toUpperCase();\n const author = await Author.findOne({ where: { name, last_name }});\n if (author) {\n return author.dataValues.id_author;\n } else {\n return null;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
random styles for mock testing | function randomStyler()
{
var zoneStyle = Math.floor((Math.random() * 3) );
console.log('randomZone='+ zoneStyle);
return stylesArray[zoneStyle];
} | [
"function newStyle(element) {\n element.style['color'] = randObj().color;\n element.style['font-size'] = randObj().size;\n element.style.fontFamily = randObj().font;\n element.style.backgroundColor = randObj().backgroundColor;\n element.style.border = randObj().border;\n }",
"function getLineAttributes(rand = true) {\n\n let colors = [\"#8093F1\", \"#F9DC5C\", \"#EA526F\", \"#70F8BA\", \"#1B98E0\", ];\n\n let lineWidth = 10;\n let lineCap = \"round\";\n let strokeStyle = colors[Math.floor(Math.random()*5)];\n if(rand == true) {\n strokeStyle = `rgba(${Math.random() * 255},\n ${Math.random() * 255},\n ${Math.random() * 255}, 1)`;\n }\n return {\n lineWidth: lineWidth,\n lineCap: lineCap,\n strokeStyle: strokeStyle\n }\n }",
"function getColor() {\n randomcolor = Math.floor(Math.random() * colors.length);\n quotesBkg.style.backgroundColor = colors[randomcolor];\n // topbar.style.backgroundColor = colors[randomcolor];\n}",
"static Random() {\n return new Color3(Math.random(), Math.random(), Math.random());\n }",
"function randomColorGenerator() {\n\t\treturn Math.floor(Math.random() * backgroundColors.length);\n}",
"function randomColour() {\r\n pattern.push(colours[Math.floor(Math.random() * 4)]);\r\n animations(pattern);\r\n levelAndScoreCount();\r\n\r\n}",
"function getRandomDesign(card) {\n let qty = parseInt(Math.random() * 3) + 1;\n let style;\n if (standard) {\n style = STYLE[parseInt(Math.random() * 3)];\n } else {\n style = \"solid\";\n }\n\n let shape = SHAPES[parseInt(Math.random() * 3)];\n let color = COLORS[parseInt(Math.random() * 3)];\n let i;\n let cardID = $(style + \"-\" + shape + \"-\" + color + \"-\" + qty);\n if (cardID) {\n card.innerText = \"\";\n getRandomDesign(card);\n } else {\n for (i = 0; i < qty; i++) {\n let shapes = document.createElement(\"img\");\n card.setAttribute(\"id\", style + \"-\" + shape + \"-\" + color + \"-\" + qty);\n shapes.setAttribute(\"src\", \"img/\" + style + \"-\" + shape + \"-\" + color + \".png\");\n shapes.setAttribute(\"alt\", style + \"-\" + shape + \"-\" + color + \".png\");\n card.appendChild(shapes);\n }\n }\n\n }",
"function assignGoalColourNormal(){\r\n var squareSize = squares.length - 3;\r\n var randomSquare = Math.floor((Math.random() * squareSize) + 1) - 1;\r\n var goalColour = squares[randomSquare].style.backgroundColor;\r\n return goalColour;\r\n}",
"cramp() {\n return styles[cramp[this.id]];\n }",
"function randomBackground(value) {\n color =`rgb(${value()}, ${value()}, ${value()})`;\n return color\n }",
"function randomColor(){\n\tlet selectedColor = content[Math.floor(Math.random()*(content.length-1))];\n\tlet line = selectedColor.split(',');\n\tlet hexCode = line[1].trim();\n\t// console.log(hexCode);\n\tlet red = hexCode.slice(1,3);\n\tlet green = hexCode.slice(3,5);\n\tlet blue = hexCode.slice(5);\n\n\t// console.log(red + 'red' + green + 'green' + blue + 'blue');\n\tred = parseInt(\"\"+red, 16);\n\tgreen = parseInt(\"\"+green, 16);\n\tblue = parseInt(\"\"+blue, 16);\n\t// console.log(red + 'red' + green + 'green' + blue + 'blue');\n\n\t// console.log('random hex is ' + hexCode);\n\tlet randomColor = new color(red, green, blue);\n\t// console.log(randomColor);\n\treturn randomColor;\n}",
"function getRandomColor(obj) {\n const keys = Object.keys(obj);\n return obj[keys[Math.floor(keys.length * Math.random())]];\n}",
"function randomBackgroundColor() {\n var currentColor = document.body.style.backgroundColor;\n do { document.body.style.backgroundColor = \"#\"+((1<<24)*Math.random()|0).toString(16); } while (document.body.style.backgroundColor === currentColor);\n}",
"function randomizeColors() {\n for (let i = ORIGINAL_COLORS.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i);\n const temp = ORIGINAL_COLORS[i];\n ORIGINAL_COLORS[i] = ORIGINAL_COLORS[j];\n ORIGINAL_COLORS[j] = temp;\n }\n}",
"randomize(height, width){\n const speedRange = 1.75;\n const sizeRange = 3;\n this.x = Math.floor(Math.random()*width)\n this.y = Math.floor(Math.random()*height);\n this.speed = (Math.random()*speedMax)+speedMin;\n //this.size = (Math.random()*sizeRange)+1;\n }",
"function randomShape(){\n\treturn Math.floor(Math.random()*50);\n}",
"randomWidth()\n{\n let r = this.randomRange(10,80);\n return r;\n}",
"function randomColorPicker(){\n\n\t\t\tvar randomColor = randomColorGenerator();\n\n\t\t\tif(randomColor !== lastColor){\n\t\t\tdocument.getElementById('body').style.background = backgroundColors[randomColor];\n\t\t\tlastColor = randomColor;\n\t\t} else {\n\t\t\trandomColorPicker();\n\t\t}\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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.