query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
wait and find a specific element with it's Selector and return Visible
async isElementVisible(selector) { let isVisible = true; await page .waitForSelector(selector, { visible: true, timeout: timeout }) .catch(() => { isVisible = false; }); return isVisible; }
[ "async waitForElementVisible (selector) {\n var waitFor = this.waitFor.bind(this)\n var findElement = this.findElement.bind(this)\n return new Promise(async resolve => {\n var isVisible = await waitFor(async () => {\n var el = await findElement(selector)\n return el && await el.isVisible()\n })\n resolve(isVisible)\n })\n }", "async waitForElementNotVisible (selector) {\n var waitFor = this.waitFor.bind(this)\n var findElement = this.findElement.bind(this)\n return new Promise(async resolve => {\n var isHidden = await waitFor(async () => {\n var el = await findElement(selector)\n return !el || !await el.isVisible()\n })\n resolve(isHidden)\n })\n }", "async isXPathVisible(selector) {\n\t\tlet isVisible = true;\n\t\tawait page\n\t\t\t.waitForXPath(selector, { visible: true, timeout: timeout })\n\t\t\t.catch(() => {\n\t\t\t\tisVisible = false;\n\t\t\t});\n\t\treturn isVisible;\n\t}", "clickSellOnTakealot() {\n return this\n .waitForElementVisible('@sellOnTakealot')\n .assert.visible('@sellOnTakealot')\n .click('@sellOnTakealot');\n }", "async findElement (selector) {\n return new Promise(resolve => {\n this.page.evaluate((selector) => {\n return document.querySelector(selector)\n },\n selector,\n (err, result) => {\n if (!result) {\n return resolve(null)\n }\n resolve(new Element(this.page, selector))\n })\n })\n }", "function checkElementIsDisplayed(element) {\r\n if (element.tagName.toLowerCase() == \"title\") {\r\n //Always visible\r\n return;\r\n }\r\n if (!Utils.isDisplayed(element)) {\r\n throw {statusCode: 11, value: {message: \"Element was not visible\"}};\r\n }\r\n}", "waitFor_raceMeetingNewsVideo_ContentTitle() {\n if(!this.raceMeetingNewsVideo_ContentTitle.isVisible()){\n this.raceMeetingNewsVideo_ContentTitle.waitForVisible(5000);\n }\n }", "waitFor_raceMeetingNewsVideo_ContentDate() {\n if(!this.raceMeetingNewsVideo_ContentDate.isVisible()){\n this.raceMeetingNewsVideo_ContentDate.waitForVisible(5000);\n }\n }", "function waitAndClick(selector)\n{\n //return promise.\n //resolve -> work done.\n //reject -> error come.\n return new Promise(function(resolve,reject)\n {\n //wait for selector\n let selectorWait = gtab.waitForSelector(selector,{visible:true});\n selectorWait.then(function()\n {\n //click\n selectorClick = gtab.click(selector)\n return selectorClick;\n }).then(function()\n {\n resolve();\n }).catch(function()\n {\n reject(err);\n })\n})\n}", "waitFor_horseProfile_Career_Jumps() {\n if(!this.horseProfile_Career_Jumps.isVisible()){\n this.horseProfile_Career_Jumps.waitForVisible(5000);\n }\n }", "clickTakealotLogo() {\n return this\n .waitForElementVisible('@takealotLogo', 10000, (res) => {\n if (res.value == true) {\n if (res.status !== undefined) {\n this\n .click('@takealotLogo');\n } else {\n this\n .api.execute((selector) => {\n document.querySelector(selector).click();\n }, [this.elements.takealotLogo.selector]);\n }\n } else {\n this\n .assert.ok(false, '[FAIL] - Something went wrong when clicking Takealot Logo in Header');\n }\n }, '[STEP] - Takealot logo should be displayed and clicked');\n }", "async waitAndClickXpath(Selector) {\n\t\tawait page.waitForXPath(Selector);\n\t\tawait page.click(Selector);\n\t}", "function testDeveloperElementsAreVisible(item) {\n testElementsVisibility(item, devElements, true);\n }", "clickRegister() {\n return this\n .waitForElementVisible('@registerBtn')\n .assert.visible('@registerBtn')\n .click('@registerBtn');\n }", "clickOrders() {\n return this\n .waitForElementVisible('@ordersLink', 10000, (res) => {\n if (res.value == true) {\n if (res.status !== undefined) {\n this\n .click('@ordersLink');\n } else {\n this\n .api.execute((selector) => {\n document.evaluate(selector, document, null,\n XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click();\n }, [this.elements.ordersLink.selector]);\n }\n } else {\n this\n .assert.ok(false, '[FAIL] - Something went wrong when clicking Orders link in Header');\n }\n }, '[STEP] - Orders link should be displayed and clicked');\n }", "clickWishlistIcon() {\n return this\n .waitForElementVisible('@wishListBtn')\n .assert.visible('@wishListBtn')\n .click('@wishListBtn');\n }", "function searchVisibleResults(){\n target = $('.list .asked');\n target = target.filter(function () {\n return $(this).css('visibility') == 'visible'\n });\n target = target.filter(function () {\n return $(this).closest('.tldResults').css('display') != 'none'\n });\n return target;\n}", "function isVisible(element) {\n return ((element.offsetWidth > 0) && (element.offsetHeight > 0));\n}", "clickOwnersDropdownButton(){\n this.ownersDropdownButton.waitForExist();\n this.ownersDropdownButton.click();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create all reviews HTML and add them to the webpage.
function fillReviewsHTML(reviews = self.restaurant.reviews) { const container = document.getElementById('reviews-container'); const title = document.createElement('h2'); title.innerHTML = 'Reviews'; title.tabIndex = 0; container.appendChild(title); if (!reviews) { const noReviews = document.createElement('p'); noReviews.innerHTML = 'No reviews yet!'; noReviews.tabIndex = 0; container.appendChild(noReviews); return; } const ul = document.getElementById('reviews-list'); reviews.forEach(review => { ul.appendChild(createReviewHTML(review)); }); container.appendChild(ul); }
[ "function fillReviewsHTML(reviews) {\n if (!reviews) {\n reviews = restaurantInfo.restaurant.reviews;\n }\n\n const container = document.getElementById('reviews-container');\n const title = document.createElement('h2');\n title.innerHTML = 'Reviews';\n container.appendChild(title);\n\n if (!reviews) {\n const noReviews = document.createElement('p');\n noReviews.innerHTML = 'No reviews yet!';\n container.appendChild(noReviews);\n return;\n }\n const ul = document.getElementById('reviews-list');\n reviews.forEach(review => {\n ul.appendChild(createReviewHTML(review));\n });\n container.appendChild(ul);\n}", "function createReviewHTML(review) {\n const li = document.createElement('li');\n const name = document.createElement('p');\n name.innerHTML = review.name;\n li.appendChild(name);\n\n // const date = document.createElement('p');\n // date.innerHTML = review.date;\n // li.appendChild(date);\n\n const rating = document.createElement('p');\n rating.innerHTML = `Rating: ${review.rating}`;\n li.appendChild(rating);\n\n const comments = document.createElement('p');\n comments.innerHTML = review.comments;\n li.appendChild(comments);\n\n return li;\n}", "function createReview(data, title) {\r\n var reviewList = [];\r\n // const regTitle = new RegExp('^' + title, \"i\");\r\n data[\"results\"].forEach(function(currObj) {\r\n // if (regTitle.test(currObj[\"display_title\"])) {\r\n if (currObj[\"display_title\"] == title) {\r\n // console.log(currObj[\"display_title\"]);\r\n let review = new reviewItem;\r\n\r\n review.reviewLink = currObj[\"link\"][\"url\"];\r\n review.title = currObj[\"headline\"];\r\n review.author = currObj[\"byline\"];\r\n\r\n reviewList.push(review);\r\n }\r\n });\r\n\r\n // create the html\r\n let s = \"\";\r\n reviewList.forEach((currReview) => {\r\n s += \"<a href=\\\"\" + currReview.reviewLink + \"\\\" target=\\\"_blank\\\">\";\r\n s += currReview.title;\r\n s += \"</a> by \" + titleCase(currReview.author) + \"<br>\";\r\n });\r\n return s;\r\n}", "function printReviews(data){\n console.log(data);\n\n let output = ``;\n for(let d of data){\n output += `\n <div class=\"review-item\">\n <div class=\"ri-pic\">\n <img src=\"${ url + \"/assets/img/profileUser.png\"}\" alt=\"${d.rooms[0].name}\">\n </div>\n <div class=\"ri-text\">\n <span> ${printDate(d.created_at)}</span>\n\n <h5>${d.user.firstname} ${d.user.lastname}</h5>\n <p>${d.message}</p>\n\n </div>\n </div>`;\n }\n\n $(\"#reviews\").html(output);\n }", "function showReviews() {\n var xmlSource = $(this).parent().find(\"img\").attr('src').replace(\"images\", \"reviews\").replace(\".jpg\", \".xml\");\n var target = $(this).parent().find(\".review\")[0];\n $(target).empty();\n $.ajax({\n type: \"GET\",\n url: xmlSource,\n cache: false,\n success: function(data) {\n parseReviews(data, target);\n },\n error: function(data){\n $(target).append(\"<p>No reviews for this movie.</p>\");\n }\n });\n }", "function getReview(doc) {\n let review = document.createElement(\"div\");\n let restImg = document.createElement(\"img\");\n let body = document.createElement(\"div\");\n let restName = document.createElement(\"p\");\n let restAddress = document.createElement(\"p\");\n let userName = document.createElement(\"h5\");\n let date = document.createElement(\"p\");\n let ul = document.createElement(\"ul\");\n let li = document.createElement(\"li\");\n let userId = doc.data().userId;\n\n db.collection('user').doc(userId).get().then(function (doc) {\n let user = doc.data().name;\n userName.setAttribute(\"class\", \"card-title\");\n userName.textContent = user;\n })\n\n review.setAttribute(\"class\", \"card mt-3\");\n restImg.setAttribute(\"class\", \"card-img-top\");\n body.setAttribute(\"class\", \"card-body\");\n restName.setAttribute(\"class\", \"rest-name\");\n restAddress.setAttribute(\"class\", \"rest-address\");\n date.setAttribute(\"class\", \"card-text\");\n ul.setAttribute(\"class\", \"list-group list-group-flush\");\n li.setAttribute(\"class\", \"list-group-item\");\n review.setAttribute(\"id\", \"review-body\");\n\n date.innerText = doc.data().reviewDate;\n li.innerText = doc.data().userReview;\n restName.innerText = doc.data().restaurantName;\n\n review.appendChild(restImg);\n review.appendChild(body);\n review.appendChild(ul);\n body.appendChild(restName);\n body.appendChild(restAddress);\n body.appendChild(userName);\n body.appendChild(date);\n ul.appendChild(li);\n\n reviewList.appendChild(review);\n}", "function generateQuestionReviewView() {\r\n let question = store.questions[store.questionNumber];\r\n let html = `\r\n <div id=\"question-page\">\r\n <div id=\"question-count\">Question ${store.questionNumber + 1} of ${store.questions.length}</div>\r\n <h2 id=\"question\">${question.question}</h2>\r\n <h3> You got the question ${(question.correctAnswer === store.submittedAnswer) ? 'correct!' : 'wrong!'}</h3>\r\n <ul id=\"answers-results\">`;\r\n //For each answer, check if it's right or wrong and highlight it appriorately\r\n question.answers.forEach(answer => {\r\n //answer right\r\n if(answer === question.correctAnswer) {\r\n html += `<li class=\"correct-answer\">${answer}</li>`;\r\n }\r\n //answer wrong and user selected\r\n else if(answer !== question.correctAnswer && answer === store.submittedAnswer) {\r\n html += `<li class=\"wrong-answer\">${answer}</li>`;\r\n }\r\n //answer wrong\r\n else {\r\n html += `<li>${answer}</li>`;\r\n }\r\n });\r\n html += `\r\n </ul>\r\n <div>\r\n <p id=\"count\">Score: ${store.score} out of ${store.questions.length}</p>\r\n <button id=\"next\">${(store.questionNumber < store.questions.length - 1) ? 'NEXT' : 'FINISH'}</button>\r\n </div>\r\n </div>`;\r\n return html;\r\n}", "function saveReview() {\n // Get the information entered by the user\n const theName = document.getElementById('name');\n const theTitle = document.getElementById('title');\n const theRating = document.getElementById('rating');\n const theReview = document.getElementById('review');\n\n const newReview = {\n reviewer: theName.value,\n title: theTitle.value,\n rating: theRating.value,\n review: theReview.value\n };\n\n reviews.push(newReview);\n\n displayReview(newReview);\n\n showHideForm();\n}", "function parseReviews(data, target) {\n var reviews;\n $(target).empty();\n reviews = $(data).find(\"review\");\n if(reviews.length === 0){\n $(target).append(\"<p>No reviews for this movie.</p>\");\n }else {\n $(data).find(\"review\").each(function () {\n var rating = $(this).find(\"rating\")[0].textContent;\n var user = $(this).find(\"user\")[0].textContent;\n $(target).append(\"<dt>\" + user + \"</dt><dd>\" + rating + \"</dd>\");\n });\n }\n }", "generateHTML() {\n return `<div class='aside-container aside-recent-posts'>\n <h4>${this.recentPostsSection.title}</h4>\n <div class=\"recent-posts\">\n ${this.generateRecentPosts()}\n </div>\n </div>`;\n }", "makeHtml(artwork, userArtwork, genre){\n\n // article\n let article = document.createElement('article');\n article.classList.add('shadow');\n article.classList.add('borderAll');\n\n // figure\n let figure = document.createElement('figure');\n figure.classList.add('hover-caption');\n figure.tabIndex = 0;\n\n // image\n let img = document.createElement('img');\n img.src = artwork.image;\n img.alt = artwork.name;\n\n // span\n let span = document.createElement('span');\n if(userArtwork !== undefined){\n if(this.isUserList){\n \n // form\n span = document.createElement('form');\n span.action = '/set-artwork-list-status';\n span.method = 'post';\n\n // input hidden artwork_id\n let inputSpan = document.createElement('input');\n inputSpan.type = 'hidden';\n inputSpan.name = 'artwork_id';\n inputSpan.value = artwork.id;\n\n // select\n let select = document.createElement('select');\n select.id = 'changeStatusSelect';\n select.name = 'status';\n this.allStatus.forEach( status => {\n let option = new Option(this.lang.status[status], status, status === userArtwork.status, status === userArtwork.status);\n select.append(option);\n });\n\n // append in form\n span.append(inputSpan);\n span.append(select);\n }else{\n if(userArtwork === undefined){\n span.classList.add('none');\n }else{\n span.innerText = this.lang.status[userArtwork.status];\n }\n }\n } else{\n span.classList.add('none');\n }\n span.classList.add('user-status');\n \n // figcaption\n let figcaption = document.createElement('figcaption');\n\n // div\n let div = document.createElement('div');\n\n // title\n let h3 = document.createElement('h3');\n h3.innerText = artwork.name;\n\n // author\n let pAuthor = document.createElement('p');\n pAuthor.innerText = 'Créer par : ' + artwork.author;\n\n // genre\n let pGenre = document.createElement('p');\n pGenre.innerText = 'Genre : ' + genre;\n\n // note\n let pNote = document.createElement('p');\n pNote.innerText = 'Note : ' + artwork.note + '/10';\n\n // button more info\n let a = document.createElement('a');\n a.classList.add('button');\n a.classList.add('block-center');\n a.href = `${this.langName}/${this.type}/info/${artwork.slug}`;\n a.innerText = 'Plus d\\'info';\n\n // append to div\n div.append(h3);\n div.append(pAuthor);\n if (artwork.genre !== '') div.append(pGenre);\n if (artwork.note !== '') div.append(pNote);\n div.append(a);\n\n // form\n let form = document.createElement('form');\n form.action = `${this.langName}/add-artwork-list`;\n form.method = 'post';\n\n // input\n let input = document.createElement('input');\n input.type = 'hidden';\n input.name = 'artwork_id';\n input.value = artwork.id;\n\n // button\n let button;\n if(this.userList.length > 0){\n button = document.createElement('button');\n button.classList.add('artwork-list-button');\n if(userArtwork === undefined){\n button.id = 'addArtworkList';\n button.classList.add('add');\n }else{\n button.id = 'removeArtworkList';\n button.classList.add('remove');\n }\n }\n\n // append to form\n form.append(input);\n if(this.userList.length > 0) form.append(button);\n\n // append to figcaption\n figcaption.append(div);\n figcaption.append(form);\n\n // append to figure\n figure.append(img);\n figure.append(span);\n figure.append(figcaption);\n\n // append to article\n article.append(figure);\n\n return article;\n \n }", "function submitNewReview(e){\n e.preventDefault();\n\n const url = '/userViewable';\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 console.log(\"got user viewable\")\n return res.json()\n }\n else\n {\n console.log(\"Did not get user viewable \")\n return res.json()\n }\n })\n .then((viewUser) => { // the resolved promise with the JSON body\n console.log(viewUser)\n\n const date = new Date();\n\n const currentDate = new Date(date.getFullYear(),date.getMonth(),date.getDate())\n\n const reviewData = {\n _id: album._id,\n name: album.name,\n cover: album.cover,\n user: viewUser,\n dateOfReview:currentDate,\n reviewBody: e.srcElement.elements.reviewbody.value,\n rating: parseInt(currentReviewRating)\n }\n\n let reviewsDivs = recentReviews.getElementsByClassName(\"reviewsDiv\")\n for(let j = reviewsDivs.length - 1; j >=0; j--)\n {\n reviewsDivs[j].remove();\n }\n\n saveReviewToUser(reviewData)\n saveReviewToAlbum(reviewData)\n\n // reseting submission box\n currentReviewRating = 1;\n displayCurrentRating(currentReviewRating);\n reviewBox.reset()\n }).catch((error) => {\n console.log(\"review error\")\n })\n}", "function displayRestaurantInfo(place) {\n $('#review-window').show();\n $('#add-review-button').show();\n restaurantInfoContainer.show();\n $('#name').text(place.name);\n $('#address').text(place.vicinity);\n $('#telephone').text(place.formatted_phone_number);\n\n var reviewsDiv = $('#reviews');\n var reviewHTML = '';\n reviewsDiv.html(reviewHTML);\n if (place.reviews) {\n if (place.reviews.length > 0) {\n for (var i = 0; i < place.reviews.length; i += 1) {\n var review = place.reviews[i];\n var avatar;\n if (place.reviews[i].profile_photo_url) {\n avatar = place.reviews[i].profile_photo_url;\n } else {\n avatar = 'img/avatar.svg';\n }\n reviewHTML += `<div class=\"restaurant-reviews\">\n <h3 class=\"review-title\">\n <span class=\"user-avatar\" style=\"background-image: url('${avatar}')\"></span>`;\n if (place.rating) {\n reviewHTML += `<span id=\"review-rating\" class=\"rating\">${placeRating(review)}</span>`;\n }\n reviewHTML += ` <h3>${place.reviews[i].author_name}</h3>\n </h3>\n <p> ${place.reviews[i].text} </p>\n </div>`;\n reviewsDiv.html(reviewHTML);\n }\n }\n }\n\n /********** Street view using Google API **********/\n\n /*** Add Street View ***/\n var streetView = new google.maps.StreetViewService();\n streetView.getPanorama({\n location: place.geometry.location,\n radius: 50\n }, processStreetViewData);\n\n var streetViewWindow = $('#street-view-window');\n var photoContainer = $('#photo');\n var photoWindow = $('#see-photo');\n var seeStreetView = $('#see-street-view');\n photoContainer.empty();\n photoContainer.append('<img class=\"place-api-photo\" ' + 'src=\"' + createPhoto(place) + '\"/>');\n\n streetViewWindow.show();\n if (photo) {\n photoWindow.show();\n } else {\n photoWindow.hide();\n }\n\n function processStreetViewData(data, status) {\n if (status === 'OK') {\n var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'));\n panorama.setPano(data.location.pano);\n panorama.setPov({\n heading: 440,\n pitch: 0\n });\n panorama.setVisible(true);\n\n } else {\n photoWindow.hide();\n streetViewWindow.hide();\n photoContainer.show();\n }\n }\n }", "buildPage() {\n if (this.compiled == false) {\n var page = \"<h1> Scoring </h1><b><p>Compiler failed with the following output:<p id=\\\"output\\\">\" + this.out + \"</p></b>\";\n fs.writeFileSync('result.html', page, function (err) {\n if (err) throw err;\n console.log('Created result.html page!');\n this.isDone = true;\n });\n } else {\n var page = \"<h1> Scoring </h1><b><p id=\\\"score\\\">\" + this.points + \" / \" + this.maxPoints + \"</p><p id=\\\"output\\\">\" + this.out + \"</p></b>\";\n fs.writeFileSync('result.html', page, function (err) {\n if (err) throw err;\n console.log('Created result.html page!');\n this.isDone = true;\n });\n }\n }", "function storeReviewData() {\n const data = []\n $('.review-button').each(function(index, element) {\n const effect = element.classList.contains('approved') ? element.dataset.effect : 'nochange'\n data.push({ id: element.dataset.id, effect: effect })\n })\n\n $('#review-input').val(JSON.stringify({\n details: getApprovedDetailChanges(),\n content: data,\n }))\n}", "createResultCards(title, poster, date, movieID, rating){\n movieElm.innerHTML += `\n <div class=\"movie\">\n <img src=${poster} alt=\"${title} Poster\">\n <div class=\"movie-info\" data-movieID=\"${movieID}\">\n <div class=\"movie-info-left\">\n <h3 class=\"color-white\">${title}</h3>\n <p class=\"color-white\">${date}</p>\n </div>\n <div class=\"movie-info-right\" style=\"border-color: ${this.getRatingColor(rating)};\">\n <h5 class=\"color-white\">${rating}<h5>\n </div>\n </div>\n </div>\n `;\n }", "async function listReviews (req, res) {\n const data = await ReviewService.listReviews(req.query)\n helper.setPaginationHeaders(req, res, data)\n}", "function addRecipeItemsToBody() {\n\n let htmlCardDisplay = \"\";\n\n for (let j = 0; j < recipeCollection.recipe.length; j++) {\n htmlCardDisplay += addHtmlForm(recipeCollection.recipe[j]);\n }\n \n cardParent.innerHTML = htmlCardDisplay;\n}", "function saveReviews(){\n console.log(\"Generating review data...\");\n\n //split review generation into chunks to try and get around memory pressure issues\n let numReviewFiles = Math.ceil((numRooms * avgReviews) / maxReviewsPerFile);\n let reviewChunk = numRooms / numReviewFiles;\n console.log(numReviewFiles);\n console.log(reviewChunk);\n\n //TBD: create a chain of functions that generate review records and then\n const reviewCallback = function(i) {\n console.log(\"Starting review file \" + i);\n let start = reviewChunk * (i-1);\n let end = reviewChunk * i;\n let reviewArray = generateReviews(start,end);\n if(i < numReviewFiles) {\n saveFile(reviewArray, `review_data_${i}.csv`, ()=>{reviewCallback(i+1)});\n } else {\n saveFile(reviewArray, `review_data_${i}.csv`, saveReservations);\n }\n }\n\n reviewCallback(1);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the initial EncloseCombat board, which is a ROWSxCOLS matrix containing the initial of a certain color.
function getInitialBoard() { var board = []; for (var i = 0; i < gameLogic.ROWS; i++) { board[i] = []; for (var j = 0; j < gameLogic.COLS; j++) { board[i][j] = getRandomColor(); } } while (!CheckMovesAvaiable(board)) { board = getInitialBoard(); } return board; }
[ "function getBoard(){\n\tvar size = 8;\n\tvar board = new Array(size);\n\tfor (var i = 0; i < size; i++) {\n\t\tboard[i] = new Array(size);\n\t\tfor (var j = 0; j < size; j++)\n\t\t\tboard[i][j] = '*';\n\t}\n\tcreateShips(board, size);\n\tboard = flatten(board);\n\treturn board;\n}", "getRandomEmptyBoardPiece() {\n\t\tconst b = this.board;\n\t\tconst s = this.boardSize;\n\t\tconst r = Math.floor(Math.random() * s);\n\t\tconst c = Math.floor(Math.random() * s);\n\t\tif (b[r][c]) return this.getRandomEmptyBoardPiece();\n\t\telse return {r, c}\n\t}", "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}", "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 fillBoard() {\n for (var i = 0; i < 8; i++) {\n game.board[i] = fillRow(i);\n };\n}", "function makeBoard() {\n for (let y = 0; y < HEIGHT; y++) {\n const row = [];\n for (let x = 0; x < WIDTH; x++) {\n const cell = null;\n row.push(cell);\n }\n board.push(row);\n }\n }", "initBoard() {\n for (let i = 0; i < this.width*this.height; i++) {\n this._board.push(0);\n }\n }", "function drawChessboard(rows, columns) {\n return 28\n}", "function infectedGrid(currentBoard, row, column, currentPlayer) {\n\tvar opponent;\n\tif(currentPlayer == 1) {\n\t\topponent = 2;\n\t} \n\telse {\n\t\topponent = 1;\n\t}\n\n\tvar infectedGridList = [];\n\tif(row > 0 && row < length - 1 && column > 0 && column < length - 1) {\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\tif(row > 0 && row < length - 1 && column == 0) {\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\tif(row > 0 && row < length - 1 && column == length - 1) {\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\tif(row == 0 && column > 0 && column < length - 1) {\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\n\t}\n\tif(row == length - 1 && column > 0 && column < length - 1) {\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\treturn infectedGridList;\n\n}", "static ensureBlackboard(ecs, aspect) {\n // create if needed\n if (!aspect.blackboards.has(AISentinel.name)) {\n let position = aspect.get(Component.Position);\n let bb = {\n home: position.p.copy(),\n fsm: new SentinelFSM(ecs, aspect),\n };\n aspect.blackboards.set(AISentinel.name, bb);\n }\n // return it\n return aspect.blackboards.get(AISentinel.name);\n }", "function createBoardModel(boardColumns, boardRows, numOfMines) {\n\n console.log(\"Created model for board.\");\n\n MSBoard = {rows: boardRows, columns: boardColumns, squares: []};\n\n for (var x = 0; x < boardColumns; x++) {\n \tMSBoard.squares[x] = [];\n for (var y = 0; y < boardColumns; y++) {\n MSBoard.squares[x][y] = {open: false, mine: false, flag: false, nearbyMines: 0}\n }\n } \n\n fillBoardWithMines(numOfMines);\n setNearbyMines();\n return MSBoard;\n}", "function setup_clues () {\n game . board . forEach (function (row, x) {\n row . split ('') . forEach (function (char, y) {\n board [id (x, y)] . value = char;\n })\n })\n}", "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 cloneBoard(){\n\t\ttestBoard = [\n\t\t\t\t[\"\",\"\",\"\"],\n\t\t\t\t[\"\",\"\",\"\"],\n\t\t\t\t[\"\",\"\",\"\"]\n\t\t\t];\n\t\tfor(cbi=0; cbi<3; cbi++){\n\t\t\tfor(cbj=0; cbj<3; cbj++){\n\t\t\t\ttestBoard[cbi][cbj] = board[cbi][cbj];\n\t\t\t}\n\t\t}\n\t}", "function startColor () {\n\t\treturn {\n\t\t\tr: 255,\n\t\t\tg: 255 * Math.random(),\n\t\t\tb: 75\n\t\t};\n\t}", "function parseBoard() {\n var result = \"\\n 1 2 3\\na\";\n for (x in board) {\n for (y in board[x]) {\n if ((y + 1) % 3 != 0 || (x + 1 == 1 && y + 1 == 1)) {\n result += board[x][y] + \"|\";\n } else {\n if (y == 2 && x != 2) {\n result += board[x][y] + \"\\n ---|---|---\\n\";\n } else {\n result += board[x][y] + \"\\n\";\n }\n }\n\n if (x == 0 && y == 2) result += \"b\";\n else if (x == 1 && y == 2) result += \"c\"\n }\n }\n\n return result;\n }", "saveInitialBoard() {\n this.initialBoard = this.gameboard.toString()\n }", "function clearBoard() {\n let elements = document.getElementsByClassName(\"cell\");\n console.log(elements);\n for (let i = 0; i < elements.length; i++) {\n elements[i].style.backgroundColor = \"hsl(0,0%,95%)\";\n }\n let grid_size = parseInt(prompt(PROMPT_TEXT));\n setBoard(grid_size);\n let dimText = document.getElementById(\"dimensions\");\n dimText.textContent = `Current Board Dimensions: ${grid_size}x${grid_size}`\n}", "function getRandomCell(winCombs) {\n return winCombs[Math.floor(Math.random() * winCombs.length)];\n}", "function newGrid() {\n for (var i = 0; i < gridCol; i++) {\n grid[i] = [];\n for (var j = 0; j < gridRow; j++) {\n grid[i][j] = gridColor;\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to change the colour of the userPos circle.
function colourChange(){ currentColour++; if(currentColour==colours.length)currentColour = 0; circle(context,halfWidth,halfHeight,step/2,true); }
[ "function drawUserPos() {\n circle(context,halfWidth,halfHeight,step/2,true);\n}", "function circlePos() {\n var color;\n switch (toggle) {\n case 0:\n color = blue;\n break;\n case 1:\n color = red;\n break;\n case 2:\n color = green;\n break;\n }\n var xCoord = map(color, 0, 255, 0, windowWidth);\n var yCoord = random(0, windowHeight);\n ellipse(xCoord, yCoord, circleSize, circleSize);\n}", "function setColour() {\r\n vertices.selectAll(\"circle\")\r\n .style(\"fill\", function (v) {\r\n\r\n // If not connected to any other vertex, set colour to grey\r\n if (!v.degree)\r\n return customColours[2];\r\n\r\n // If general graph, set colour to red\r\n if (selectedAlgorithm == 3)\r\n return customColours[1];\r\n\r\n // If left-hand vertex, set colour to red and if right-hand vertex, set colour to blue\r\n if (v.parity)\r\n return customColours[v.parity % 2];\r\n\r\n // If non-bipartite graph, use one of the standard colours\r\n else\r\n return standardColours(v.id);\r\n\r\n });\r\n}", "function circleColor() {\n red = restrict(red + (random(50) * (round(random()) * 2 - 1)), 0, 255);\n green = restrict(green + (random(50) * (round(random()) * 2 - 1)), 0, 255);\n blue = restrict(blue + (random(50) * (round(random()) * 2 - 1)), 0, 255);\n fill(red, green, blue);\n}", "updateCircle() {\n const obj = this.newPos(); // Returns the random values as an object\n // Updates the circles css styling\n this.div.style.left = `${obj.posX}px`;\n this.div.style.bottom = `${obj.posY}px`;\n this.div.style.width = `${obj.radius}rem`;\n this.div.style.height = `${obj.radius}rem`;\n }", "function checkColor(circle) { \n var circle_label = circle.id.slice(6,7);\n var circle_number = circle.id.slice(7, circle.id.length);\n var basket_label = circleInBasket(circle);\n if (circle_label == basket_label) {\n // make circle color green\n changeCircleColorToGreen(circle_label, circle_number);\n } else {\n // make circle color red\n changeCircleColorToRed(circle_label, circle_number);\n }\n}", "setColorQuiescent(){\n\t this.color = colorQuie;\t \n }", "function changeCircle() {\n dsnGridMouseChange('a', 'override-circle');\n dsnGridMouseChange('.site-header a', 'override-circle-none');\n}", "drawCircle(context, actor){\n\t\tcontext.fillStyle = actor.color;\n\t\tcontext.beginPath(); \n\t\tcontext.arc(actor.x, actor.y, actor.r, 0, 2 * Math.PI, false); \n\t\tcontext.fill(); \n\t}", "changeColor() {\n this.currentColor = this.intersectingColor;\n }", "function setDrawingColor(event) {\n sketchController.color = this.value;\n}", "set CircleEdge(value) {}", "function cycleDrawColour() {\n Data.Edit.Node.style.stroke = cycleColour(Data.Edit.Node.style.stroke);\n hasEdits(true);\n}", "function setPixelColor(event) {\n if (event.type === 'click') {\n event.target.style.backgroundColor = 'red';\n } else if (mousingDown) {\n event.target.style.backgroundColor = 'red';\n }\n }", "getColor(value) {\n if (undefined == value) { return 'lightgrey'; }\n if (value < 0) {\n return this.negativeColorScale(value);\n } else {\n return this.selectedPosColorScale(value);\n }\n }", "_colorUpdate() {\n if(this.value){\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': this.value,\n '--l2t-paper-color-indicator-icon-display': 'block',\n });\n } else {\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': 'transparent',\n '--l2t-paper-color-indicator-icon-display': 'none',\n });\n }\n }", "function drawPt(x, y, color,isFill,radius) {\n \n\tctx.fillStyle = color;\n ctx.beginPath();\n \n\tctx.arc(x, y, radius, 0, 2*Math.PI);\n ctx.closePath();\n ctx.stroke();\n if(isFill)\n {\n \tctx.fill();\n }\n ctx.fillStyle = \"black\";\n}", "function mouseclicks()\n{\n //mouse makes yellow dot\n fill(255,255,0);\n circle(mousex, mousey, d);\n \n}", "drawCircle(cx, cy, radius, name, color, just_fill) {\n // this.ctx.beginPath();\n var previous = this.ctx.fillStyle;\n this.ctx.moveTo(cx + radius, cy);\n this.ctx.fillStyle = color;\n this.ctx.beginPath();\n this.ctx.arc(cx, cy, radius, 0, 2*Math.PI);\n this.ctx.closePath();\n this.ctx.fill();\n this.ctx.fillStyle = previous;\n this.ctx.fillText(name, cx, cy+7);\n if (!just_fill) {\n this.ctx.stroke();\n }\n // this.ctx.closePath();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function I used to have the live error message appear for credit card
function liveCreditCardError(){ //declare then modify creditError's properties (I think they're called properties) let creditError = document.createElement('p'); creditError.style.color = 'red'; creditError.style.fontSize = 'small'; // attaching the credit error message to the parent of ccNum ccNum.parentNode.appendChild(creditError); // hide the message at first creditError.style.display = 'none'; // listener based on focusout added to ccNum for the live message ccNum.addEventListener('focusout', (e) => { //store the length of the ccNum value in cardN // if credit card number is less than 13 but greater than 8 show error message let cardN = ccNum.value.length; if(cardN <= 13 && cardN >= 8){ creditError.textContent = 'Please enter a number that is between 13 and 16 digits long'; creditError.style.display = ''; } else if(cardN == 0){ creditError.textContent = 'Credit Card field is empty'; creditError.style.display = ''; } else { //hide the message otherwise creditError.style.display = 'none'; } }) }
[ "function bluesnapGetErrorText(errorCode) {\n switch (errorCode) {\n case '001':\n return Drupal.t('Please enter a valid card number.');\n\n case '002':\n return Drupal.t('Please enter a valid CVV/CVC number.');\n\n case '003':\n return Drupal.t('Please enter a valid expiration date.');\n\n case '22013':\n return Drupal.t('The card type is not supported by the merchant.');\n\n case '400':\n return Drupal.t('Session expired. Please refresh the page to continue.');\n\n case '403':\n case '404':\n case '500':\n return Drupal.t('Internal server error. Please try again later.');\n\n default:\n break;\n }\n }", "function CheckOverallValidity(card, cardnum){\n card.checkNumValidity(cardnum);\n card.checkLengthValidity();\n card.checkDateValidity();\n \n\n if(card.validNum == false){\n document.getElementById(\"CardNum\").innerHTML = \"Card Number Invalid\"\n document.getElementById(\"CardNum\").style.display = \"block\";\n } if (card.validLength == false){\n document.getElementById(\"CardLength\").innerHTML = \"Card Length Invalid\"\n document.getElementById(\"CardLength\").style.display = \"block\";\n } if (card.validCVC == false){\n document.getElementById(\"CardCVC\").innerHTML = \"CVC Length Invalid\"\n document.getElementById(\"CardCVC\").style.display = \"block\";\n } if (card.validExp == false){\n document.getElementById(\"CardExp\").innerHTML = \"Expired Card\"\n document.getElementById(\"CardExp\").style.display = \"block\";\n } else if (card.validExp == null && card.validCVC == null && card.validLength == null && card.validNum == null ) {\n document.getElementById(\"CardNum\").innerHTML = \"Valid Card!\"\n document.getElementById(\"CardNum\").style.display = \"block\";\n }\n\n}", "function onStripeValidationFailure(error) {\n\n var msg = error.message;\n if (error.type === 'card_error') {\n if (error.code && isFieldAttributableStripeError(error)) {\n msg = 'PLEASE_CORRECT_ERRORS';\n attributeStripeFieldError(error);\n }\n }\n else if (error.type === 'payment_token_error') {\n msg = 'Server error - missing payment configuration key. Please try again later.';\n } else {\n console.error('Stripe validation failed: ' + JSON.stringify(error));\n msg = 'Not able to pre-validate payment at this time.';\n }\n $scope.message = msg;\n $scope.submitIsDisabled = false;\n if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {\n $scope.$apply();\n }\n modal.close();\n }", "function buyCard(){\n \n //receivers email validation\n var emailRegex = /^[a-zA-Z0-9.!#$%&'+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)$/;\n if(!emailRegex.test(receiver.value)){\n receiver.style.background = \"red\";\n receiver.focus();\n return false;\n }\n else\n {\n receiver.style.background = \"white\"; \n }\n \n //Sender's email validation\n var emailRegex2 = /^[a-zA-Z0-9.!#$%&'+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)$/;\n if(!emailRegex2.test(sender.value)){\n sender.style.background = \"red\";\n sender.focus();\n return false;\n }\n else\n {\n sender.style.background = \"white\"; \n }\n \n //Thanks message after ordering gift card\n submitForm.style.display = \"none\";\n hidden.style.display = \"block\";\n hidden.style.fontSize= \"36px\";\n hidden.style.fontStyle = \"bold\";\n return false;//prevent form to submit untill its not validated\n }", "function showApiErrorMessages(apiResult) {\n\n var errorMsg = \"\";\n removePaymentErrors();\n if (apiResult.getErrorType() == PaymentApi.ERROR_NO_PAYMENT_MODE_SELECTED) {\n errorMsg = \"<p>Bitte w&auml;hlen Sie eine Zahlmethode!</p>\";\n } else if (apiResult.getErrorType() == PaymentApi.ERROR_NO_PAYMENT_METHOD_SELECTED) {\n errorMsg = \"<p>Bitte w&auml;hlen Sie eine Zahlmethode (z.B. Kreditkartentyp)!</p>\";\n fillErrorMessage('#payment-api-creditcard-methodCode', 'Bitte w&auml;hlen Sie eine Zahlmethode (z.B. Kreditkartentyp)!');\n }\n\n else if (apiResult.getErrors().length > 0) {\n for (index in apiResult.getErrors()) {\n errorMsg += \"<p>\" + apiResult.getErrors()[index].msg + \"</p>\";\n setPaymentFieldErrors(apiResult.getErrors()[index]);\n }\n }\n\n else {\n errorMsg = \"<p>Ein Fehler trat auf - bitte versuchen Sie es erneut!</p>\";\n }\n\n $(\"#globalMessages\").html('<div class=\"information_message negative\"><span class=\"single\"></span>' + errorMsg + '</div>');\n $(\"html, body\").animate({scrollTop: 0}, 500);\n\n }", "function creditUSRowCallback(res){ \n document.getElementById(\"mCreditUSTableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false;\n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditUSTableDiv').innerHTML = res.value.usHTML;\n errorMessage(res.value.message,\"CreditUS\",\"Message\");\n gOldUSCreditAmt = res.value.usAmt;\n gUSCreditEmailUpdated = res.value.usEmail;\n }\n }\n else{\n document.getElementById('mCreditUSTableDiv').innerHTML = \"\";\n errorMessage(\"Error Crediting Transaction\",\"CreditUS\",\"Error\");\n } \n }", "function validateDebitCard(self, type, charCode) {\n if (!(typeof charCode === 'boolean' || (charCode >= 48 && charCode <= 57))) {\n return false;\n } else if (self.value.length === 6 || !charCode) {\n var cardtype = document.getElementById('cardtype_dc').value;\n if (!charCode) {\n if (cardtype === '') {\n return false;\n } else if (inValidType(self.value.length, type.toLowerCase())) {\n return false;\n }\n }\n document.getElementById('ccnum_dc').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_dc').style.display = 'none';\n document.getElementById('amex_dc').style.display = 'none';\n document.getElementById('visa_dc').style.display = 'none';\n document.getElementById('master_dc').style.display = 'none';\n\n var data = {\n \"bin\" : self.value.substring(0,6),\n \"errorBlock\" : document.getElementById('error-ccnum_dc'),\n \"ccnum\" : document.getElementById('ccnum_dc'),\n \"ccvv\" : document.getElementById('ccvv_dc'),\n \"btn\" : document.getElementById('checkoutprocess_dc'),\n \"amex\" : document.getElementById('amex_dc'),\n \"visa\" : document.getElementById('visa_dc'),\n \"master\" : document.getElementById('master_dc'),\n \"processing\" : document.getElementById('processing_dc'),\n \"cardtype\" : document.getElementById('cardtype_dc'),\n \"errorMsg\" : 'Invalid debit card type!'\n };\n processAjaxRequest(data, type);\n\n return true;\n\n } else {\n if (self.value.length < 6) {\n document.getElementById('ccnum_dc').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_dc').style.display = 'none';\n document.getElementById('amex_dc').style.display = 'none';\n document.getElementById('visa_dc').style.display = 'none';\n document.getElementById('master_dc').style.display = 'none';\n }\n\n return false;\n }\n}", "function creditCARowCallback(res){ \n document.getElementById(\"mCreditCATableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false; \n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditCATableDiv').innerHTML = res.value.caHTML;\n errorMessage(res.value.message,\"CreditCA\",\"Message\");\n gOldCACreditAmt = res.value.caAmt;\n gCACreditEmailUpdated = res.value.caEmail;\n //get new files\n getFiles(false,\"CACredit\");\n //open file\n if (res.value.filePath != null && res.value.filePath != \"\"){\n printPage(\"F\",res.value.filePath);\n }\n }\n }\n else{\n document.getElementById('mCreditCATableDiv').innerHTML = \"\";\n errorMessage(\"Error Crediting Transaction\",\"CreditCA\",\"Error\");\n }\n }", "function removeError(self) {\n var str = document.getElementById(self.parentNode.id).style.border;\n if (self.value !== '' && str.search(\"255\") > -1) {\n var id = self.id;\n var date = new Date();\n var month = date.getMonth();\n var year = date.getFullYear();\n var selector = id.split('_');\n var expmon, expyr, errSel;\n if (selector[0] === 'ccexpyr') {\n selector = 'ccexpmon_' + selector[1];\n errSel = 'error_' + selector;\n expmon = document.getElementById(selector).value;\n expyr = document.getElementById(id).value;\n } else if (selector[0] === 'ccexpmon') {\n selector = 'ccexpyr_' + selector[1];\n errSel = 'error_' + id;\n expmon = document.getElementById(id).value;\n expyr = document.getElementById(selector).value;\n }\n if (expmon !== '' && expyr !== '') {\n if (year == expyr && expmon < month + 1) {\n document.getElementById(errSel).innerHTML = 'Invalid card expiry!';\n document.getElementById(errSel).style.display = 'block';\n document.getElementById(self.parentNode.id).style.border = '1px solid #FF0000';\n } else {\n document.getElementById(errSel).innerHTML = '';\n document.getElementById(errSel).style.display = 'none';\n document.getElementById(self.parentNode.id).style.border = '1px solid #ccc';\n }\n }\n }\n}", "function validateEmiCard(self, type, charCode) {\n if (!(typeof charCode === 'boolean' || (charCode >= 48 && charCode <= 57))) {\n return false;\n } else if (self.value.length === 6 || !charCode) {\n var cardtype = document.getElementById('cardtype_em').value;\n if (!charCode) {\n if (cardtype === '') {\n return false;\n } else if (inValidType(self.value.length, 'em')) {\n return false;\n }\n }\n document.getElementById('ccnum_emi').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_emi').style.display = 'none';\n document.getElementById('amex_emi').style.display = 'none';\n document.getElementById('visa_emi').style.display = 'none';\n document.getElementById('master_emi').style.display = 'none';\n\n var data = {\n \"bin\" : self.value.substring(0,6),\n \"errorBlock\" : document.getElementById('error-ccnum_emi'),\n \"ccnum\" : document.getElementById('ccnum_emi'),\n \"ccvv\" : document.getElementById('ccvv_emi'),\n \"btn\" : document.getElementById('checkoutprocess_emi'),\n \"amex\" : document.getElementById('amex_emi'),\n \"visa\" : document.getElementById('visa_emi'),\n \"master\" : document.getElementById('master_emi'),\n \"processing\" : document.getElementById('processing_emi'),\n \"cardtype\" : document.getElementById('cardtype_em'),\n \"errorMsg\" : 'Invalid credit card type!'\n };\n processAjaxRequest(data, type);\n\n return true;\n } else {\n if (self.value.length < 6) {\n document.getElementById('ccnum_emi').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_emi').style.display = 'none';\n document.getElementById('amex_emi').style.display = 'none';\n document.getElementById('visa_emi').style.display = 'none';\n document.getElementById('master_emi').style.display = 'none';\n }\n\n return false;\n }\n}", "function checkError(errorCode) {\n switch(errorCode) {\n case 0:\n return 'Geen watertoevoer';\n case 1:\n return 'Temperatuur te laag';\n case 2:\n return 'Koffiebonen op';\n case 3:\n return 'Afvalbak vol';\n case 4:\n return 'Geen druk';\n default:\n return 'Onbekende foutcode';\n }\n}", "function stripeResponseHandler(status, response) {\n var errorMessages = {\n incorrect_number: window.__(\"The card number is incorrect\"),\n invalid_number: window.__(\"The card number is not a valid credit card number\"),\n number: window.__(\"The card number is not a valid credit card number\"),\n invalid_expiry_month: window.__(\"The card's expiration month is invalid\"),\n exp_month: window.__(\"The card's expiration month is invalid\"),\n invalid_expiry_year: window.__(\"The card's expiration year is invalid\"),\n exp_year: window.__(\"The card's expiration year is invalid\"),\n expired_card: window.__(\"The card has expired\"),\n cvc: window.__(\"The card's security code is incorrect\"),\n incorrect_zip: window.__(\"The card's zip code failed validation\"),\n card_declined: window.__(\"The card was declined\"),\n missing: window.__(\"There are no card details for a customer that is being charged\"),\n processing_error: window.__(\"An error occurred while processing the card\"),\n rate_limit: window.__(\"An error occurred because of high demand at the moment. Please let us know if you get this error a lot.\"),\n undefined: window.__(\"Invalid params\")\n };\n\n var errorCodes = {\n incorrect_number: 'card_number',\n number: 'card_number',\n invalid_number: 'card_number',\n invalid_expiry_month: 'month',\n exp_month: 'month',\n invalid_expiry_year: 'year',\n exp_year: 'year',\n cvc: 'cvc',\n incorrect_zip: 'zip'\n };\n\n if (response.error) {\n $(addNewCardBtn).removeClass(\"in-progress\");\n\n var errors = {};\n if (!response.error.param) {\n var requiredFields = ['number', 'exp_month', 'exp_year', 'cvc'];\n for (var i = 0; i < requiredFields.length; i++) {\n errors[errorCodes[requiredFields[i]]] = errorMessages[requiredFields[i]];\n }\n } else {\n errors[errorCodes[response.error.param]] = errorMessages[response.error.param];\n }\n\n showErrorsModule.showMessage(errors, \"modal-error\");\n } else {\n // response contains id and card, which contains additional card details\n var cardToken = cardParams(response.id);\n createPayment(cardToken, \"card\");\n }\n }", "function validatecaptcha() {\n var cap = $(\"#captcha\").val();\n var cap_hd = $(\"#hd_cap\").val();\n if (cap != cap_hd) {\n $(\"#captcha\").addClass(\"error\");\n $(\"#captchaInfo\").text(\"Enter a valid security code\\n\");\n $(\"#captchaInfo\").addClass(\"error_message_side\");\n\n return false;\n } else {\n $(\"#captcha\").removeClass(\"error\");\n $(\"#captchaInfo\").text(\"\");\n $(\"#captchaInfo\").removeClass(\"error_message_side\");\n return true;\n }\n\n }", "function quickContactErrorCheck(){\n\tvar errorFlag=0;\n\tclearQuickContactErrors();\n\tif((jQuery(\"#qc-name\").val() == null || jQuery(\"#qc-name\").val() == \"\") ){\n\t\tjQuery(\".olam_name\").fadeIn().html(\"Enter your name\");\n\t\terrorFlag=1;\n\t}\n\tif((jQuery(\"#qc-email\").val() == null || jQuery(\"#qc-email\").val() == \"\") ){\n\t\tjQuery(\".olam_email\").fadeIn().html(\"Enter your email\");\n\t\terrorFlag=1;\n\t}\n\tif((jQuery(\"#qc-message\").val() == null || jQuery(\"#qc-message\").val() == \"\") ){\n\t\tjQuery(\".olam_message\").fadeIn().html(\"Enter your message\");\n\t\terrorFlag=1;\n\t}\n\treturn errorFlag;\n}", "function contactErrorCheck(){\n\tvar errorFlag=0;\n\tclearContactErrors();\n\tif((jQuery(\"#c-name\").val() == null || jQuery(\"#c-name\").val() == \"\") ){\n\t\tjQuery(\".olam-c-name\").fadeIn().html(\"Enter your name\");\n\t\terrorFlag=1;\n\t}\n\tif((jQuery(\"#c-email\").val() == null || jQuery(\"#c-email\").val() == \"\") ){\n\t\tjQuery(\".olam-c-email\").fadeIn().html(\"Enter your email\");\n\t\terrorFlag=1;\n\t}\n\tif((jQuery(\"#c-message\").val() == null || jQuery(\"#c-message\").val() == \"\") ){\n\t\tjQuery(\".olam-c-message\").fadeIn().html(\"Enter your message\");\n\t\terrorFlag=1;\n\t}\n\treturn errorFlag;\n}", "function cvvErrorTest(){\n if(regexCvv.test(cvv.val()) === false){\n cvvError.show();\n return 0;\n }\n else{\n cvvError.hide();\n return 1;\n }\n}", "function removeErrorCvv(self) {\n if (self.value.length === 3 || self.value.length === 4) {\n document.getElementById(self.parentNode.id).style.border = '1px solid #CCC';\n document.getElementById('error_' + self.id).style.display = 'none';\n } else if (self.value.length > 0 && self.value.length < 3) {\n document.getElementById(self.parentNode.id).style.border = '1px solid #FF0000';\n document.getElementById('error_' + self.id).style.display = 'block';\n document.getElementById('error_' + self.id).innerHTML = 'invalid CVV!';\n } else if (self.value.length === 0) {\n document.getElementById(self.parentNode.id).style.border = '1px solid #FF0000';\n document.getElementById('error_' + self.id).style.display = 'none';\n }\n}", "function displayErrorMessage (form, error) {\n form.find('.error-messages').append('<div class=\"message\">' + error + '</div>');\n }", "function error(elementInstance) {\n elementInstance.addEventListener('change', function (event) {\n let err = document.getElementById('stripe-error');\n if (event.error) err.innerHTML = event.error.message;\n else err.innerHTML = '';\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Limits the rate of events emitted by the signal to allow at most one event every `n` milliseconds.
throttle (n) { return throttle(n, this) }
[ "static periodic (n) {\n let id\n\n return new Signal(emit => {\n id = setInterval(() => emit.next(), n)\n return () => clearInterval(id)\n })\n }", "function emitAndSample() {\n return Rx.Observable.interval(100) // emit items every 100 ms\n .sample(500) // only emit one every 500 ms\n .take(5); // emit up to a max count\n}", "static sequential (n, as) {\n let id\n\n return new Signal(emit => {\n id = setInterval(() => {\n emit.next(head(as))\n\n as = tail(as)\n\n if (empty(as)) {\n clearInterval(id)\n emit.complete()\n }\n }, n)\n\n return () => clearInterval(id)\n })\n }", "debounce (n) {\n return debounce(n, this)\n }", "function scheduler (func, n) {\n function delay (ttl, callback) {\n let now = Date.now();\n let curr = Date.now();\n while (curr - now < ttl){\n curr = Date.now();\n }\n callback();\n }\n \n delay(n*1000, func);\n}", "function eventDelay() {\n //Randomly select a value from 0 to 1s\n return Math.floor(Math.random() * 1001);\n }", "function throttleUpdateGauge(func, limit){\n var lastRunTime;\n var lastFunctionCalled;\n return function () {\n // first call\n if (!lastRunTime) {\n func.apply(null)\n lastRunTime = Date.now()\n } else {\n clearInterval(lastFunctionCalled)\n lastFunctionCalled = setTimeout(function(){\n // throttlings\n if ((Date.now() - lastRunTime) >= limit) {\n func.apply(null)\n lastRunTime = Date.now()\n }\n }, limit - (Date.now() - lastRunTime))\n }\n }\n }", "set PreserveSampleRate(value) {}", "set OptimizeSampleRate(value) {}", "_checkRateLimit (ts: number, limit: number, rates: number[]) {\n rates.push(ts)\n let edge = rates.find((d) => ts - 1000 < d)\n if (edge) rates.splice(0, rates.indexOf(edge))\n return rates.length <= limit\n }", "setIndex(millis){\n let i = 0;\n for(let event of this.events){\n if(event.millis >= millis){\n this.index = i;\n break;\n }\n i++;\n }\n //console.log(millis);\n this.beyondLoop = false;\n if(millis > this.song.loopEnd){\n this.beyondLoop = true;\n }\n\n this.scheduledAudioEvents = {};\n }", "function everyinterval(n) {\n if ((myGameArea.frameNo / n) % 1 === 0) {\n return true;\n }\n return false;\n}", "sendSignal() {\n let handler = this.signalHandler;\n if(!handler) return;\n\n // send a signal\n let signalNumber = this.totalSignalCount - (this.signalCount--);\n // console.debug('sendSignal in TaskTimer', this.totalSignalCount, this.signalCount);\n handler(signalNumber);\n\n // calculate how long the wait interval should now be\n // based on how much time is left until the timeout.\n if (!this.isPaused() && this.signalCount>0) {\n let elapsed = Date.now() - this.created;\n let remaining = this.timeoutInterval - elapsed;\n let timeoutValue = remaining / this.signalCount;\n // console.debug('nextSignal in TaskTimer =', timeoutValue, 'from', this.signalCount,\"over\", remaining);\n this.nextSignal = setTimeout(() => this.sendSignal(), timeoutValue);\n }\n }", "function setFrequency(value) {\n var minValue = 40;\n var maxValue = AUDIO.sampleRate / 2;\n var numberOfOctaves = Math.log(maxValue / minValue) / Math.LN2;\n var multiplier = Math.pow(2, numberOfOctaves * (value - 1.0));\n filterNode.frequency.value = maxValue * multiplier;\n}", "lim(n) {\n if (this.mag() > n) {\n this.norm();\n this.mult(n);\n }\n }", "function throttleEnforceEffect_(self, units, duration, costFn, burst = 0) {\n const loop = (tokens, timestamp) => CH.readWith(in_ => CH.unwrap(T.map_(T.zip_(costFn(in_), CL.currentTime), ({\n tuple: [weight, current]\n }) => {\n const elapsed = current - timestamp;\n const cycles = elapsed / duration;\n\n const available = (() => {\n const sum = Math.floor(tokens + cycles * units);\n const max = units + burst < 0 ? Number.MAX_SAFE_INTEGER : units + burst;\n return sum < 0 ? max : Math.min(sum, max);\n })();\n\n if (weight <= available) {\n return CH.zipRight_(CH.write(in_), loop(available - weight, current));\n } else {\n return loop(available, current);\n }\n })), e => CH.fail(e), _ => CH.unit);\n\n return new C.Stream(CH.chain_(CH.fromEffect(CL.currentTime), _ => self.channel[\">>>\"](loop(units, _))));\n}", "function myLoop() {\n\n setTimeout(function() {\n\n // Start and set the frequency and log corresponding details\n osc.start();\n osc.freq(swipeFreqs[freqI]);\n console.log(swipeFreqs[freqI]);\n console.log(thisSentance.charAt(freqI));\n\n // Now add to I to iterate through the loop\n freqI++;\n\n // While I is a value of swipeFreqs keep looping else stopSwipeSound()\n if (freqI < swipeFreqs.length) {\n\n myLoop();\n\n } else {\n\n stopSwipeSound();\n\n }\n\n }, 150)\n\n }", "set OverrideSampleRate(value) {}", "throttle(callback) {\n if (this._queuing < this._concurrency)\n callback();\n else\n this.once('ready', ()=> this.throttle(callback));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a [[IRectangle]] object representing a common rectangle that fits all passed in rectangles in it.
function getCommonRectangle(rectangles) { var length = rectangles.length; if (length !== 0) { var minX = void 0; var minY = void 0; var maxX = void 0; var maxY = void 0; for (var i = 0; i < length; i++) { var rectangle = rectangles[i]; minX = min(rectangle.x, minX); minY = min(rectangle.y, minY); maxX = max(rectangle.x + rectangle.width, maxX); maxY = max(rectangle.y + rectangle.height, maxY); } return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; } }
[ "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 }", "static buildRectangle(dims, cTypes, offset = new Point()) {\n return new CollisionShape([\n new Point(-dims.x / 2, -dims.y / 2),\n new Point(dims.x / 2, -dims.y / 2),\n new Point(dims.x / 2, dims.y / 2),\n new Point(-dims.x / 2, dims.y / 2),\n ], cTypes, Physics.Shape.Rectangle, offset);\n }", "_commonToWorldBounds(commonBounds) {\n const [xMin, yMin, xMax, yMax] = commonBounds;\n const {\n viewport\n } = this.context;\n const bottomLeftWorld = viewport.unprojectPosition([xMin, yMin]);\n const topRightWorld = viewport.unprojectPosition([xMax, yMax]);\n return bottomLeftWorld.slice(0, 2).concat(topRightWorld.slice(0, 2));\n }", "static getBounds(rectangle, matrix, out = null) {\n if (!out) out = new Rectangle()\n\n let minX = Number.MAX_VALUE,\n maxX = -Number.MAX_VALUE\n let minY = Number.MAX_VALUE,\n maxY = -Number.MAX_VALUE\n const positions = RectangleUtil.getPositions(\n rectangle,\n RectangleUtil.sPositions\n )\n\n for (let i = 0; i < 4; ++i) {\n MatrixUtil.transformCoords(\n matrix,\n positions[i].x,\n positions[i].y,\n RectangleUtil.sPoint\n )\n\n if (minX > RectangleUtil.sPoint.x) minX = RectangleUtil.sPoint.x\n if (maxX < RectangleUtil.sPoint.x) maxX = RectangleUtil.sPoint.x\n if (minY > RectangleUtil.sPoint.y) minY = RectangleUtil.sPoint.y\n if (maxY < RectangleUtil.sPoint.y) maxY = RectangleUtil.sPoint.y\n }\n\n out.setTo(minX, minY, maxX - minX, maxY - minY)\n return out\n }", "function getRect(points) {\n var minX, minY, maxX, maxY;\n \n for (var ii = points.length; ii--; ) {\n var xy = points[ii];\n \n // update the min x and min y\n minX = (typeof minX === 'undefined') || xy.x < minX ? xy.x : minX;\n minY = (typeof minY === 'undefined') || xy.y < minY ? xy.y : minY;\n \n // update the max x and max y\n maxX = (typeof maxX === 'undefined') || xy.x > maxX ? xy.x : maxX;\n maxY = (typeof maxY === 'undefined') || xy.y > maxY ? xy.y : maxY;\n } // for\n \n return xyRectTools.init(minX, minY, maxY, maxY); \n }", "function totalSquareArea(rectangles) {\n squares = rectangles.filter(function(rectangle) {\n return rectangle[0] === rectangle[1];\n });\n\n return totalArea(squares);\n}", "function initRects() {\r\n const height3 = canvasHeight / 3;\r\n const row1 = new RectRow(3, 80, canvasWidth, height3, 0);\r\n const row2 = new RectRow(4, 150, canvasWidth, height3, height3);\r\n const row3 = new RectRow(5, 100, canvasWidth, height3, height3*2);\r\n rectRows = [row1, row2, row3];\r\n\r\n // const max = 30;\r\n // for (let i = 0; i < max; i++)\r\n // rectRows.push(new RectRow(i+1, 100, canvasWidth, canvasHeight/max, i * (canvasHeight/max)));\r\n}", "function Rectangle(width, height, color) {\n var _this = _super.call(this) || this;\n _this.width = width;\n _this.height = height;\n _this.color = color;\n // Set default position.\n _this.setPosition(0, 0);\n return _this;\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 findZoneRectangle(circlesInZone,circlesOutZone) {\n\n\tvar pointsInZone = findSufficientPointsInZone(circlesInZone,circlesOutZone);\n\t\n\tif(pointsInZone.length == 0) {\n\t\treturn new Rectangle(0,0,0,0);\n\t}\n\tvar biggestRectangle;\n\tvar biggestArea = 0;\n\tfor (var i = 0; i < pointsInZone.length; i++) {\n\t\tvar rectangle = findRectangle(pointsInZone[i],circlesInZone,circlesOutZone);\n\t\tif(rectangle.width*rectangle.height > biggestArea) {\n\t\t\tbiggestRectangle = rectangle;\n\t\t\tbiggestArea = rectangle.width*rectangle.height;\n\t\t}\n\t}\n\treturn biggestRectangle;\n}", "function Rect(width,height) {\n\tthis.width = width;\n\tthis.height = height;\n}", "_worldToCommonBounds(worldBounds, opts = {}) {\n const {useLayerCoordinateSystem = false} = opts;\n const [minLong, minLat, maxLong, maxLat] = worldBounds;\n const {viewport} = this.context;\n const {textureSize} = this.state;\n\n const size = (textureSize * RESOLUTION) / viewport.scale;\n\n let bottomLeftCommon;\n let topRightCommon;\n\n // Y-axis is flipped between World and Common bounds\n if (useLayerCoordinateSystem) {\n bottomLeftCommon = this.projectPosition([minLong, minLat, 0]);\n topRightCommon = this.projectPosition([maxLong, maxLat, 0]);\n } else {\n bottomLeftCommon = viewport.projectPosition([minLong, minLat, 0]);\n topRightCommon = viewport.projectPosition([maxLong, maxLat, 0]);\n }\n // Ignore z component\n let commonBounds = bottomLeftCommon.slice(0, 2).concat(topRightCommon.slice(0, 2));\n commonBounds = Object(_heatmap_layer_utils__WEBPACK_IMPORTED_MODULE_1__[\"scaleToAspectRatio\"])(commonBounds, size, size);\n return commonBounds;\n }", "function getCornersOfRect(rect) {\n return [\n {x: rect.x, y: rect.y},\n {x: rect.x + rect.width, y: rect.y},\n {x: rect.x + rect.width, y: rect.y + rect.height},\n {x: rect.x, y: rect.y + rect.height},\n ]\n}", "function findZoneRectangles(zoneStrings, circles) {\n\n\tvar zones = zoneFinder(zoneStrings,circles);\n\n\tvar rectangles = [];\n\t\n\t// iterate through the zones, finding the best rectangle for each zone\n\tfor (var i = 0; i < zones.length; i++) {\n\t\tvar circlesInZone = zones[i];\n\t\t\n\t\tvar circlesOutZone = getOutZones(circles, circlesInZone);\n\t\tvar rectangle = findZoneRectangle(circlesInZone,circlesOutZone);\n\n\t\tfor (var j = 0; j < circlesInZone.length; j++){\n\t\t\trectangle.label = rectangle.label + \"\" + circlesInZone[j].label;\n\t\t}\n\n\t\tconsole.log(circlesInZone, circlesOutZone, rectangle);\n\t\trectangles.push(rectangle);\n\t}\n\treturn rectangles;\n}", "static extend(rect, left = 0, right = 0, top = 0, bottom = 0) {\n rect.x -= left\n rect.y -= top\n rect.width += left + right\n rect.height += top + bottom\n }", "merge(box) {\n const x = Math.min(this.x, box.x);\n const y = Math.min(this.y, box.y);\n const width = Math.max(this.x + this.width, box.x + box.width) - x;\n const height = Math.max(this.y + this.height, box.y + box.height) - y;\n return new Box(x, y, width, height);\n }", "getRectSize() {\n\t\treturn {\n\t\t\t'width':this.rectArea.width / this.horizontalPeriod.count - this.rectMargin / 2,\n\t\t\t'height':this.rectArea.height / this.verticalPeriod.count - this.rectMargin / 2\n\t\t}\n\t}", "function EqualClientRectsData(r1, r2)\n{\n if (r1 === undefined || r2 === undefined || r1.length !== r2.length)\n return false;\n \n // Check if width and height of each Rect are identical\n\tfor(var i = 0, n = r1.length; i < n; i++)\n {\n if((r1[i] === undefined && r2[i] !== undefined) || (r1[i] !== undefined && r2[i] === undefined))\n return false;\n if(r1[i] === undefined)\n continue;\n\t\tfor(var j = 0; j < 4; j++)\n if(r1[i][j] !== r2[i][j])\n return false; // Stop iterating asap\n }\n\treturn true;\n\n}", "copy ()\n {\n return new Rectangle(this.position.copy(), this.width, this.height);\n }", "getMaxRect(x, y, aspect) {\n return Rect.getMax(Math.abs(this.locked[0] - x), Math.abs(this.locked[1] - y), aspect)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all of the user's favorited restaurants.
static getFavoriteRestaurants() { return DBHelper.goGet( `${DBHelper.RESTAURANT_DB_URL}/?is_favorite=true`, "❗💩 Error fetching favorite restaurants: " ); }
[ "static getAllRestaurants() {\r\n return DBHelper.goGet(\r\n DBHelper.RESTAURANT_DB_URL,\r\n \"❗💩 Error fetching all restaurants: \"\r\n );\r\n }", "getFavorites() {\n\t\treturn apiFetch(\n\t\t\t{\n\t\t\t\tpath: '/vtblocks/v1/layouts/favorites',\n\t\t\t\tmethod: 'GET',\n\t\t\t}\n\t\t).then(\n\t\t\tfavorite_keys => {\n\t\t\t\tlet favorites = [];\n\n\t\t\t\tObject.values( this.state.all ).forEach( function( item ) {\n\t\t\t\t\tif ( favorite_keys.includes( item.key ) ) {\n\t\t\t\t\t\tfavorites.push( item );\n\t\t\t\t\t}\n\t\t\t\t} );\n\n\t\t\t\treturn favorites;\n\t\t\t}\n\t\t).catch(\n\t\t\terror => console.error( error )\n\t\t);\n\t}", "static fetchRestaurantByfavorite(callback) {\n // Fetch all restaurants\n let open = idb.open(\"restaurants\", 1);\n open.then((db) => {\n let tx = db.transaction('restaurants');\n let keyValStore = tx.objectStore('restaurants', 'readonly');\n let favoriteIndex = keyValStore.index('is_favorite');\n return favoriteIndex.getAll(\"true\");\n }).then((data, error) => {\n if (error) {\n callback(error, null);\n } else {\n callback(null, data);\n }\n }).catch((error) => {\n callback(error, null);\n });\n }", "function getFavoriteMovies() {\n\t\tlet movieId = $('.movie-id').val();\n\n\t\t$.ajax({\n\t\t\turl: \"/favorites/all\",\n\t\t\tmethod: \"GET\",\n\t\t\tcontentType: \"application/json\",\n\t\t\tdataType: 'json',\n\n\t\t\tcomplete : function(data){ \t\n\t\t\t\tjQuery.each(data.responseJSON, function(index, item) {\n\t\t\t\t\t//favoriteMovies(item.movieId, item.user.id);\n\n\t\t\t\t\tif (item.movieId == movieId && item.user.id == myId) {\n\t\t\t\t\t\t$('.add-to-favorite').addClass(\"is-favorite\")\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},fail : function(){\n\t\t\t\tconsole.log(\"Failed getting favorite movies\");\n\t\t\t}\n\t\t});\n\t}", "function fetchrestaurants() {\n var data;\n $.ajax({\n url: 'https://api.foursquare.com/v2/venues/search',\n dataType: 'json',\n data: 'client_id=LEX5UAPSLDFGAG0CAARCTPRC4KUQ0LZ1GZSB4JE0GSSGQW3A&client_secret=0QUGSWLF4DJG5TM2KO3YCUXUB2IJUCHDNSZC0FUUA3PKV0MY&v=20170101&ll=28.613939,77.209021&query=restaurant',\n async: true,\n }).done(function (response) {\n data = response.response.venues;\n data.forEach(function (restaurant) {\n var foursquare = new Foursquare(restaurant, map);\n self.restaurantList.push(foursquare);\n });\n self.restaurantList().forEach(function (restaurant) {\n if (restaurant.map_location()) {\n google.maps.event.addListener(restaurant.marker, 'click', function () {\n self.selectrestaurant(restaurant);\n });\n }\n });\n }).fail(function (response, status, error) {\n\t\t\tself.queryResult('restaurant\\'s could not load...');\n });\n }", "getFavoriteBooks(userId) {\n this.userId = userId;\n // Check if user is in database\n const usersData = readData(usersFile);\n const userIndex = findUser(userId);\n if (userIndex < 0) return { statusCode: '402', message: 'Unauthenticated user' };\n\n // Check if user has favorite books\n if (!usersData.users[userIndex].favorites) return { statusCode: '404', message: 'Favorites not found' };\n\n // Push each favorite book to favorites book array\n const booksData = readData(booksFile);\n const favoritesArray = usersData.users[userIndex].favorites;\n let favoriteBooks = [];\n favoritesArray.forEach((fav) => {\n const bookObject = booksData.books.filter(book => book.id === fav);\n favoriteBooks = [...favoriteBooks, ...bookObject];\n });\n return { statusCode: '200', message: favoriteBooks };\n }", "function getFavorites(success, error){\n let baseUrl = \"/favorites\";\n baseXHRGet(baseUrl, success, error);\n }", "getFavoriteKeys() {\n\t\treturn apiFetch(\n\t\t\t{\n\t\t\t\tpath: '/vtblocks/v1/layouts/favorites',\n\t\t\t\tmethod: 'GET',\n\t\t\t}\n\t\t).then(\n\t\t\tfavorite_keys => {\n\t\t\t\treturn favorite_keys;\n\t\t\t}\n\t\t).catch(\n\t\t\terror => console.error( error )\n\t\t);\n\t}", "async function getOtherUsersFavorites(userId){\n const query = \"SELECT DISTINCT b.bname AS 'Band' FROM Bands b JOIN Favorites f ON f.band_id = b.bid JOIN `User` u ON u.uid = f.uid WHERE u.uid IN (SELECT u.uid FROM `User` u2 JOIN Favorites f2 ON f2.uid = u2.uid JOIN Bands b2 ON b2.bid = f2.band_id WHERE u2.uid != ? AND b2.bname IN (SELECT b2.bname FROM `User` u3 JOIN Favorites f3 ON f3.uid = u3.uid JOIN Bands b3 ON b3.bid = f3.band_id WHERE u3.uid = ?)) AND b.bname NOT IN (SELECT b4.bname FROM `User` u4 JOIN Favorites f4 ON f4.uid = u4.uid JOIN Bands b4 ON b4.bid = f4.band_id WHERE u4.uid = ?);\";\n try {\n const [rows] = await conn.execute(query, [userId, userId, userId]);\n return rows;\n } catch (err) {\n console.error(err);\n return [];\n }\n }", "function getFavorites(username){\n\t$.ajax({\n\t url: Url+'/getfavs?Username='+username,\n\t type: \"GET\",\n\t success: listFavorites,\n\t error: displayError,\n\t})\n}", "static get DATABASE_GET_ALL_FAVORITES() {\r\n return `http://localhost:${DBHelper.PORT}/restaurants/?is_favorite=true`;\r\n }", "function generateFavorites() {\n // empty out the list\n $favoritedStories.empty();\n //\n if (currentUser.favorites.length === 0) {\n $favoritedStories.append(\"<p>No favorites added!</p>\");\n } else {\n for (let story of currentUser.favorites) {\n // render each story in the list\n const storyHTML = generateStoryHTML(story, false);\n $favoritedStories.append(storyHTML);\n }\n }\n }", "function checkForFavs() {\n for(let favStory of $(user.favorites)){\n let favStoryID = favStory.storyId;\n\n $(`#${favStoryID}`).find(\".fa-heart\").toggleClass(\"far fas\");\n }\n }", "getFavorite(cardId) {\n if(this.user==false)return false;\n for(const card of this.user.savedCards){\n //console.log(card.cardID+\" vs \"+cardId);\n if(card.cardID == cardId)return card.favorited;\n\n }\n return false;\n }", "function 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 printFavorites() {\n\t// DONE: clear out favorites section each time\n\t// before displaying new list of favorites\n\tlist.innerHTML = '';\n\n\n\t// TODO: concatenate all the favorites into one string\n\t// - hint: loop through all the favorites\n\t// - this should be stored in a variable named favoritesText\n\t// - each favorite should have an html br element between it (EG: \"<br>\")\n\tvar favoritesText='';\n\t\n\tfavorites.forEach(print);\n\tfunction print(favorite) {\n\t\tfavoritesText += favorite + '<br />';\n\t};\n\n\n\t// DONE: update the list element with the\n\t// new list of favorites\n\tlist.innerHTML = favoritesText;\n}", "static fetchRestaurantReviews(restaurant, callback) {\n\n fetch(DBHelper.REVIEW_URL + \"?restaurant_id=\" + restaurant.id).then((reviewResp) => {\n if (!reviewResp.ok) {\n callback(\"Failed to get the restaurant review json for id: \" + restaurant.id, null);\n } else {\n return reviewResp.json();\n }\n }).then((reviews) => {\n if (reviews) {\n // Creates a full restaurant object before calling a callback.\n restaurant[\"reviews\"] = reviews;\n DBHelper.addReviewsToIDB(reviews);\n callback(null, restaurant);\n // console.log(\"review\", restaurant);\n } else {\n // Has no reviews.\n callback(null, restaurant);\n }\n }).catch(function(error) {\n callback(\"Failed to get the restaurant review json for id: \" + restaurant.id, null);\n });\n\n }", "function filterFavoritesIfAppliable() {\n const favs = $('#favs');\n if (favs.text().localeCompare('My favorites') == 0) {\n const favorites = User.getFavoritesText();\n $('#fixtures tr').filter(function() {\n // The league and teams infos are only on the 3 first tds\n const arrayOfDisplayed = $(this).children('td').slice(0, 3).map(function() { // eslint-disable-line no-invalid-this\n return $(this).text().trim(); // eslint-disable-line no-invalid-this\n }).get();\n $(this).toggle(favorites.some((element) => arrayOfDisplayed.includes(element))); // eslint-disable-line no-invalid-this\n });\n } else {\n $('#fixtures tr').toggle(true);\n }\n}", "function loadRestaurants() {\n\ttry {\n\t\tvar loadString = fs.readFileSync('saveData.json');\n\t\tconsole.log('Loading Restaurants');\n\t\treturn JSON.parse(loadString);\n\t}catch(error) {\n\t\treturn [];\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Like ? in EBNF, a railroad node that either follows its child or an empty branch.
function maybe(child) { // \u25b6 is a right pointing arrowhead that indicates an empty transition. return or(toNode('\u25b6'), toNode(child)); }
[ "function is_node_empty(node, regardBrAsEmpty) {\n if (regardBrAsEmpty === void 0) { regardBrAsEmpty = true; }\n if (!node)\n return false;\n return (node.nodeType == Node.TEXT_NODE && /^[\\s\\r\\n]*$/.test(node.nodeValue)) ||\n (node.nodeType == Node.COMMENT_NODE) ||\n (regardBrAsEmpty && node.nodeName == \"BR\");\n }", "function NilNode() {\n}", "function fill_missing_child_nodes_right_sibling(node)\n{\n if (node === null) \n {\n return;\n }\n \n var numberOfChildren = node.children.length;\n var lastNodeIndex = numberOfChildren - 1;\n \n if (lastNodeIndex >= 0)\n {\n if (node.children[lastNodeIndex].right === null)\n {\n node.children[lastNodeIndex].right = find_right_sibling(node);\n }\n for (var i=0; i < numberOfChildren; i++)\n {\n fill_missing_child_nodes_right_sibling(node.children[i]); \n }\n }\n}", "childExpression(childName) {\n if (\n this.node.$allRecursive ||\n (childName === this.node.$name && this.recursionDepth < this.maxRecursionDepth - 1)\n ) {\n return new RelationExpression(this.node, this.recursionDepth + 1);\n }\n\n const child = this.node[childName];\n\n if (child) {\n return new RelationExpression(child);\n } else {\n return null;\n }\n }", "function create_right_sibling(node)\n{\n if (node === null) \n {\n return;\n }\n \n var numberOfChildren = node.children.length;\n \n var queue = [];\n for (var i=0; i < numberOfChildren ; i++)\n {\n if (node.children[i].right === null && node.children[i+1])\n {\n node.children[i].right = node.children[i+1];\n queue.push(node.children[i]);\n }\n }\n \n for (var j=0; j < queue.length; j++)\n {\n create_right_sibling(queue[j]); \n }\n}", "function isChild(node1, node2){\n\tif (node1 == null || !node1.parentID){\n\t\treturn false;\n\t}\n\tif (node1.parentID.redditID == node2.redditID){\n\t\treturn true;\n\t}\n\treturn isChild(node1.parentID, node2);\n}", "function TrueNode() {\n}", "function followingNonDescendantNode(node) {\n if (node.ownerElement) {\n if (node.ownerElement.firstChild) return node.ownerElement.firstChild;\n node = node.ownerElement;\n }\n do {\n if (node.nextSibling) return node.nextSibling;\n } while (node = node.parentNode);\n return null;\n }", "constructor(value){\n this.value = value;\n this.left = null;\n this.right = null;\n }", "function NodePart(_ref) {\n var node = _ref.node,\n parent = _ref.parent,\n before = _ref.before,\n after = _ref.after;\n classCallCheck(this, NodePart);\n\n this.node = node || emptyNode;\n this.value = noChange;\n\n this.parentNode = parent || node && node.parentNode;\n this.beforeNode = before || node && node.previousSibling;\n this.afterNode = after || node && node.nextSibling;\n }", "breadthFirstTraversal() {\n let queue = [];\n queue.push(this.root);\n while (queue.length){\n let node = queue.shift();\n console.log(node.val);\n if (node.left){queue.push(node.left);}\n if (node.right){queue.push(node.right)};\n }\n }", "function isEmptyStmt(expr) {\r\n\r\n // for a if/elseif or a foreach statement, if only the root expression\r\n // is present without any children, then it is treated as an \r\n // empty stmt. Note: Forever and Else don't need children.\r\n //\r\n if ((expr.isIf() || expr.isElseIf() || expr.isForeach()) &&\r\n (!expr.exprArr || !expr.exprArr.length)) {\r\n return true;\r\n }\r\n\r\n return false;\r\n}", "connectPathLeafToNode(after_if_node_key, connect_jump)\r\n {\r\n var stack_len = this.node_stack[this.current_class][this.current_function].length; \r\n var leaf_key = this.node_stack[this.current_class][this.current_function][stack_len - 1]; // the leaf of the (then/if) branch or last visited node. \r\n var leaf_node = this.cfg_nodes[this.current_class][this.current_function][leaf_key];\r\n if (!this.isBranchingNode(leaf_node)){ \r\n this.cfg_nodes[this.current_class][this.current_function][leaf_key].left = after_if_node_key;\r\n this.cfg_nodes[this.current_class][this.current_function][after_if_node_key].parents.push(leaf_key);\r\n }\r\n }", "levelByLevelOneQueueUsingDelimiter(root) {\n if (root == null) {\n return;\n }\n var q = [];\n q.push(root);\n q.push(null);\n while (q.length > 0) {\n root = q.shift();\n if (root != null) {\n console.log(root.val + \" \");\n if (root.leftChild != null) {\n q.push(root.leftChild);\n }\n if (root.rightChild != null) {\n q.push(root.rightChild);\n }\n } else {\n if (q.length > 0) {\n console.log(\" \");\n q.push(null);\n }\n }\n }\n }", "leaf(root, path) {\n var node = Node$1.get(root, path);\n\n if (!Text.isText(node)) {\n throw new Error(\"Cannot get the leaf node at path [\".concat(path, \"] because it refers to a non-leaf node: \").concat(node));\n }\n\n return node;\n }", "lesx_parseEmptyExpression() {\n var node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);\n return this.finishNodeAt(node, 'LesxEmptyExpression', this.start, this.startLoc);\n }", "endIf() {\n return this._endBlockNode(If, Else)\n }", "function postOrder( node ){\n if( node ){\n postorder( node.left );\n postorder( node.right );\n console.log( node.value ); // print out current node, then traverse\n }\n}", "isPreceding(node) {\n var nodePos, thisPos;\n nodePos = this.treePosition(node);\n thisPos = this.treePosition(this);\n if (nodePos === -1 || thisPos === -1) {\n return false;\n } else {\n return nodePos < thisPos;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if VideoPlayer is supported by calling device
static isVideoPlayerSupported(requestEnvelope) { return requestEnvelope.context.System.device.supportedInterfaces.VideoApp !== undefined; }
[ "function useVideoJs() {\n return !(typeof videojs === \"undefined\");\n }", "static isVideoPlaying(video){return video.currentTime>0&&!video.paused&&video.readyState>2;}", "function isMediaDevicesSuported(){return hasNavigator()&&!!navigator.mediaDevices;}", "function canEnumerateDevices(){return!!(isMediaDevicesSuported()&&navigator.mediaDevices.enumerateDevices);}", "function detect_mode() {\n if (player.getPlaybackQuality() == \"\") {\n player_mode = 'html5';\n }\n else {\n player_mode = 'flash';\n delta = 0.1; // make the video last 0.1 seconds longer... tweak this as necessary\n } \n}", "static mediaStreamIsTorchCompatible(params){const tracks=params.getVideoTracks();for(const track of tracks){if(BrowserCodeReader$1.mediaStreamIsTorchCompatibleTrack(track)){return true;}}return false;}", "isVideoTrack() {\n return this.getType() === MediaType.VIDEO;\n }", "function isPlaying() {\n return (videoEl.currentTime > 0 && !videoEl.paused && !videoEl.ended && videoEl.readyState > 2);\n }", "function checkStatus() {\n if (supportsAvif !== null && supportsWebp !== null) {\n showOverlay();\n return;\n }\n }", "checkVideoStuck() {\n let isVideoStuck = false;\n\n if (this.noVideoTimeout) {\n clearTimeout(this.noVideoTimeout);\n this.noVideoTimeout = null;\n }\n\n if (!this.videoCurrentTimeTimeStamp) {\n this.videoCurrentTimeTimeStamp = Date.now();\n return isVideoStuck;\n }\n\n let dateNow = Date.now();\n\n if (this.videoCurrentTime != this.videoPlayer.videoElement.currentTime) {\n this.videoCurrentTime = this.videoPlayer.videoElement.currentTime;\n this.videoCurrentTimeTimeStamp = dateNow;\n this.onClearVideoStuck();\n if (this.onStuckVideoPlayerTimeout) {\n clearTimeout(this.onStuckVideoPlayerTimeout);\n this.onStuckVideoPlayerTimeout = null;\n }\n }\n else if (dateNow - this.videoCurrentTimeTimeStamp > MAX_RETRY_TIMEOUT) {\n SHOW_LOG && console.error('Falling back because the video player is stuck for more than : ' + MAX_RETRY_TIMEOUT / 1000 + ' s.');\n isVideoStuck = true;\n this.fallback();\n return;\n }\n // video data received from server but player is stuck\n else if (dateNow - this.videoCurrentTimeTimeStamp > VIDEO_STUCK_CHECK_TIMEOUT) {\n this.onStartVideoStuck();\n if (!this.onStuckVideoPlayerTimeout) {\n this.onStuckVideoPlayerTimeout = setTimeout(() => {\n if (this.restartCount >= MAX_RESTARTS_ON_VIDEO_STUCK) {\n SHOW_LOG && console.error('Falling back because the video player has been restarted more than : ' + MAX_RESTARTS_ON_VIDEO_STUCK + ' time(s) for a specific time.');\n this.fallback();\n return;\n } else {\n SHOW_LOG && console.log('Restarting the player because video data received from server but player is stuck');\n this.onRestartStream();\n }\n }, VIDEO_PLAYER_STUCK_TIMEOUT);\n }\n }\n\n this.setWaitingVideoTimeout();\n\n return isVideoStuck;\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 detectCodecIDForStreaming()\n{\n\tvar dom = dw.getDocumentDOM();\n\tvideoObj = dom.getSelectedNode();\n\n\tvar sourceURL = VIDEO_SERVER_URI.value; \n\tif(/\\s*rtmp:\\/\\/([^\\/]+)\\/([^\\/]+\\/[^\\/]+)/i.test(sourceURL) && !((sourceURL.indexOf(\"*\") != -1) || (sourceURL.indexOf(\"?\") != -1) || (sourceURL.indexOf(\"<\") != -1) || (sourceURL.indexOf(\">\") != -1) || (sourceURL.indexOf(\"|\") != -1) || (sourceURL.indexOf(\"\\\"\") != -1)))\n\t{\n\t\tserverName=RegExp.$1;\n\t\tappName=RegExp.$2; \n\t}\n\telse\n\t{\n\t\talert(MSG_EnterValidServerURI);\n\t\treturn;\n\t}\n\tvar streamName = trimString(VIDEO_STREAM.value); \n\n\t//form the video URL from sourceURL + \"/\" + streamName\n\tif (sourceURL.length > 0)\n\t{\n\t\t\t//if the last character is not a slash then append \n\t\t\t//a slash to it\n\t\t if (sourceURL[sourceURL.length - 1] != '/')\n\t\t {\n\t\t\t\tsourceURL += \"/\";\n\t\t }\n\t}\n\n\t// Make sure that streamName does not have .flv at the end\n\tif (/\\.flv$/i.test(streamName) == true)\n\t{\n\t\tstreamName = streamName.replace(/\\.flv$/i, \"\");\n\t}\n\n\t//form the video URL from sourceURL + streamName\n\tvar videoURL = sourceURL + streamName;\n\tif((videoURL != null) && (videoURL.length > 0))\n\t{\n\t\t//load the video URL to get the auto detect the video dimension\n\t\tloadVideo(videoURL);\n\t\t//start the detect poll\n\t\t//we need the below flag to track when the auto detect from\n\t\t//swfloader extension is completed.\n\t\t//we loop 30 times x 500ms (1/2 second)15 seconds\n\t\tMM._LOOPCOUNTER = 0;\n\t\tVIDEO_SIZE_BTN.setAttribute(\"disabled\",\"true\");\n\n\t\t//first call back\n\t\tvar funCallBack = \"isDetectCodecIDDone()\";\n\t\ttimerID = setTimeout(funCallBack,500);\n\t}\n}", "function detectWMP()\r\n{\r\n\tvar wmpInfo = {\r\n\t\tinstalled: false,\r\n\t\tscriptable: false,\r\n\t\ttype: null,\r\n\t\tversionInfo: null\r\n\t};\r\n\tvar wmp64 = \"MediaPlayer.MediaPlayer.1\";\r\n\tvar wmp7 = \"WMPlayer.OCX.7\";\r\n\tif((window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1) || window.GeckoActiveXObject)\r\n\t{\r\n\t\twmpInfo.type = \"ActiveX\";\r\n\t\tvar player = createActiveXObject(wmp7);\r\n\t\tif(player)\r\n\t\t{\r\n\t\t\twmpInfo.installed = true;\r\n\t\t\twmpInfo.scriptable = true;\r\n\t\t\twmpInfo.versionInfo = player.versionInfo;\r\n\t\t\treturn wmpInfo;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tplayer = createActiveXObject(wmp64);\r\n\t\t\tif(player)\r\n\t\t\t{\r\n\t\t\t\twmpInfo.installed = true;\r\n\t\t\t\twmpInfo.scriptable = true;\r\n\t\t\t\twmpInfo.versionInfo = \"6.4\";\r\n\t\t\t\treturn wmpInfo;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\twmpInfo.versionInfo = \"none\";\r\n\t\t\t\treturn wmpInfo;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse if(navigator.mimeTypes)\r\n\t{\r\n\t\twmpInfo.type = \"NetscapePlugin\";\r\n\t\tnumPlugins = navigator.plugins.length;\r\n\t\tfor (i = 0; i < numPlugins; i++)\r\n\t\t{\r\n\t\tplugin = navigator.plugins[i];\r\n\t\t\tif (plugin.name.substring(0,10)==\"Windows Media Player\")\r\n\t\t\t{\r\n\t\t\t\twmpInfo.installed = true;\r\n\t\t\t\t//wmpInfo.scriptable = false;\r\n\t\t\t\twmpInfo.versionInfo = \"PluginVersion\";\r\n\t\t\t\treturn wmpInfo;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/*if(player)\r\n\t\t{\t\r\n\t\t\t\r\n\t\t\talert(\"if netscape and windows media\");\r\n\t\t\twmpInfo.installed = true;\r\n\t\t\twmpInfo.scriptable = false;\r\n\t\t\twmpInfo.versionInfo = \"PluginVersion\";\r\n\t\t\treturn wmpInfo;\r\n\t\t}*/\r\n\t\treturn wmpInfo;\r\n\t}\r\n\t\r\n\t\r\n}", "_getVideoDevices() {\n return from(navigator.mediaDevices.enumerateDevices()).pipe(map(devices => devices.filter(device => device.kind === 'videoinput')));\n }", "static listVideoInputDevices(){return __awaiter$1(this,void 0,void 0,function*(){if(!hasNavigator()){throw new Error('Can\\'t enumerate devices, navigator is not present.');}if(!canEnumerateDevices()){throw new Error('Can\\'t enumerate devices, method not supported.');}const devices=yield navigator.mediaDevices.enumerateDevices();const videoDevices=[];for(const device of devices){const kind=device.kind==='video'?'videoinput':device.kind;if(kind!=='videoinput'){continue;}const deviceId=device.deviceId||device.id;const label=device.label||`Video device ${videoDevices.length+1}`;const groupId=device.groupId;const videoDevice={deviceId,label,kind,groupId};videoDevices.push(videoDevice);}return videoDevices;});}", "function supportsDisplay() {\n var hasDisplay =\n this.event.context &&\n this.event.context.System &&\n this.event.context.System.device &&\n this.event.context.System.device.supportedInterfaces &&\n this.event.context.System.device.supportedInterfaces.Display\n\n return hasDisplay;\n}", "function allVideoIdsReady() {\n if (!useVideoJs()) {\n return (nrOfPlayersReady == videoIds.length); // TODO\n } else {\n for (var i = 0; i < videoIds.length; ++i) {\n if (!videoIdsReady[videoIds[i]]) {\n return false;\n }\n }\n return true;\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;}});}", "load(){\n console.debug(\"Loading\", this.id);\n for (let i = 0; i < this.mediaSourceListeners.length; i++) {\n if(typeof this.mediaSourceListeners[i].load === 'function')this.mediaSourceListeners[i].load(this);\n }\n if (this.element !== undefined) {\n return true;\n }\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
addRandomDot() adds one random dot to the grid
addRandomDot(){ // get random position from our list of free positions let rand_pos = this.free_pos[Math.floor(Math.random() * this.free_pos.length)]; this.addDot(rand_pos.x, rand_pos.y); }
[ "function addNewDot() {\n random(dots).setAlive();\n}", "addRandomDots(n_dots){\n for(let i= 0; i<n_dots;i++){\n this.addRandomDot();\n }\n }", "moveRandomDot(){\n //console.log(\"(moveRandomDot) called:\");\n let taken_pos = this.getTakenPositions();\n let to_remove = taken_pos[Math.floor(Math.random() * taken_pos.length)];\n this.addRandomDot();\n this.free_pos.push(to_remove);\n\n let pos_to_place_dot = this.getTakenPositions();\n //console.log(\"pos_to_place_dot:\"+pos_to_place_dot);\n\n // remove all the dots!\n this.dots.length = 0;\n this.free_pos = this.getAllPossiblePositions();\n\n for (const dot_pos of pos_to_place_dot){\n this.addDot(dot_pos.x,dot_pos.y);\n }\n }", "function setAllDotsToRandom(){\r\n\t\t\tfor(var i = 0; i < nDots; i++){\r\n\t\t\t\tdot = dotArray[i];\r\n\t\t\t\tdot.updateType = 'random direction';\r\n\t\t\t}\r\n\t\t}", "function createDot (left, top) {\n var dot = document.createElement('div')\n dot.className = 'dot'\n dot.style.left = left + 'px'\n dot.style.top = top + 'px'\n dot.style.width = 8 + 'px'\n dot.style.height = 8 + 'px'\n dot.style.borderRadius = 5 + 'px'\n gameboard.appendChild(dot)\n dots.push(dot)\n }", "function addDot() {\n\t\tdiv.innerHTML = div.innerHTML + '. ';\n\t\t//on incrémente dots\n\t\tdots++;\n\t\t//la fonction s'appelle elle même\n\t\tdotLoader();\n\t}", "addDot(x,y){\n\n if (x >= this.lines || y >= this.lines){\n // out of range!!\n //console.log(\"(addDot): index out of range\");\n return;\n }\n\n let empty_pos = this.free_pos.findIndex((element) => (element.x == x && element.y == y));\n if (empty_pos != -1)\n {\n this.free_pos.splice(empty_pos,1);\n }\n else\n {\n //console.log(\"(addDot): spot already taken.\");\n return;\n }\n\n let shift = this.size/4;\n let line_distance = (this.size/this.lines) /2;\n\n let x_pos = x*line_distance+(line_distance/2)-shift;\n\n let y_pos = y*line_distance+(line_distance/2)-shift;\n\n this.dots.push(new Polygon({\n win: this.win,\n name: 'circle',\n size: this.dot_size,\n lineColor: new Color('black'),\n fillColor: new Color('white'),\n edges: 32,\n pos: [x_pos,y_pos]\n }));\n }", "function makeDotArray() {\r\n \t\r\n\t \tvar tempArray = []\r\n\t \t\r\n\t \tfor (var i = 0; i < nDots; i++) {\r\n\r\n\t\t\t\t//Initialize a dot to be modified and inserted into the array\r\n\t\t\t\tvar dot = {\r\n\t\t\t\t\tx: 0, //x coordinate\r\n\t\t\t\t\ty: 0, //y coordinate\r\n\t\t\t\t\tvx: 0, //coherent x jumpsize (if any)\r\n\t\t\t\t\tvy: 0, //coherent y jumpsize (if any)\r\n\t\t\t\t\tvx2: 0, //incoherent (random) x jumpsize (if any)\r\n\t\t\t\t\tvy2: 0, //incoherent (random) y jumpsize (if any)\r\n\t\t\t\t\tlifeCount: Math.floor(randomNumberBetween(0, dotLife)), //Counter for the dot's life. Updates every time it is shown in a frame\r\n\t\t\t\t\tupdateType: \"\", //String to determine how this dot is updated\r\n\t\t\t\t\tcolor: dotColor\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tdot = resetLocation(dot);//randomly set the x and y coordinates\r\n\t\t\t\tdot = setvxvy(dot); //Set the dot's coherent motion\r\n \t\tdot = setvx2vy2(dot); //Set the dot's random direction\r\n\t\t\t\tdot.updateType = \"random direction\"; //Initialize as all being random first\r\n\t\t\t\t\r\n\t\t\t\ttempArray.push(dot);\r\n\t\t\t\t\r\n\t\t\t} //End of for loop\r\n\t\t\t\r\n\t\t\treturn tempArray;\r\n\t\t}", "function generateNumberInRandomCell () {\r\n let randomCell = Math.floor(Math.random() * 15);\r\n if (gameCells[randomCell].innerText != \"\") {\r\n randomCell = Math.floor(Math.random() * 15);\r\n }\r\n let span = document.createElement('span');\r\n span.innerText = '2';\r\n span.classList.add('game-piece');\r\n gameCells[randomCell].appendChild(span);\r\n}", "function drawDots() {\n var circles = dotg.selectAll('circle')\n .data(dots);\n circles.enter()\n .append('circle');\n circles.exit().remove();\n circles\n .transition()\n .duration(200)\n .attr('cx', function(d) { return d.x; })\n .attr('cy', function(d) { return d.y; })\n //Initialize dot color\n .attr('fill', function(d) { return d.group ? d.group.color : '#BDBDBD'; })\n .attr('r', 8);\n}", "function addDot() {\n const dot = document.createElement('div');\n dot.id = 'etave-recorder-dot';\n document.body.appendChild(dot);\n}", "incGhostsDots() {\n if (this.inPen.length > 0) {\n this.inPen[0].increaseDots();\n this.checkDotLimit();\n }\n }", "incDotCounter() {\n if (!this.penType) {\n this.incGhostsDots();\n } else {\n this.incGlobalDots();\n }\n }", "function clearDots(){\r\n\t \t//Loop through the dots one by one and draw them\r\n\t \tfor (var i = 0; i < nDots; i++) {\r\n\t \t\tdot = dotArray[i];\r\n\t \t\tctx.beginPath();\r\n\t \t\tctx.arc(dot.x, dot.y, dotRadius+1, 0, Math.PI * 2);\r\n\t \t\tctx.fillStyle = backgroundColor;\r\n\t \t\tctx.fill();\r\n\t \t}\r\n\t\t}", "insertNumber() {\r\n this.emptySpaces = [];\r\n for (let i = 0; i < this.gridSize; i++) {\r\n for (let j = 0; j < this.gridSize; j++) {\r\n this.board[i][j] == 0 ? this.emptySpaces.push({ \"x\": i, \"y\": j }) : undefined;\r\n }\r\n }\r\n let randObj = this.emptySpaces[this.randomInt(0, this.emptySpaces.length)];\r\n if (this.emptySpaces.length > 0) {\r\n this.board[randObj.x][randObj.y] = Math.random() > 0.5 ? 4 : 2;\r\n }\r\n }", "randomize () {\n\t\tfor (var column = 0; column < this.numberOfColumns; column ++) {\n for (var row = 0; row < this.numberOfRows; row++) {\n this.cells[column][row].setIsAlive(floor(random(2)));\n\t\t\t\tthis.cells[column][row].draw();\n }\n }\n\t}", "function generateDots(n) {\n var dots = [];\n while (dots.length < n) {\n var candidate_dot = [Math.floor(Math.random() * 480) + 10, Math.floor(Math.random() * 480) + 10];\n for (var i=0; i<dots.length; i++) if (euclidianDistance(dots[i], candidate_dot) < 20) break;\n if (i == dots.length) dots.push(candidate_dot);\n }\n return dots;\n}", "incGlobalDots() {\n this.globalDots += 1;\n \n this.inPen.forEach((ghost) => {\n if (this.globalDots === Data.getPenDotsCount(ghost.getID())) {\n if (ghost.getID() <= 2) {\n this.releaseGhostFromPen();\n } else {\n this.penType = false;\n this.globalDots = 0;\n }\n }\n });\n }", "function dimDot (id, dim)\n{\n\tif (dim) ph[id].dot.attr(\"opacity\", 0.15).attr(\"stroke-width\", dotstroke).toFront();\n\telse ph[id].dot.attr(\"opacity\", 1).attr(\"stroke-width\", dotstroke).toFront();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fills a hole with a random stimulus you have to pay attention that "a random stimulus" may be also a clue
function fillHole(stimulus_name, idx) { var el = (stimulus_name === "position") ? 0 : 1; if (block[idx][el] === 0) { block[idx][el] = 1 + Math.floor(Math.random() * 8); if (block[idx - n] && block[idx][el] === block[idx - n][el]) (block[idx][el] < 8) ? block[idx][el]++ : block[idx][el]--; else if (block[idx + n] && block[idx][el] === block[idx + n][el]) (block[idx][el] < 8) ? block[idx][el]++ : block[idx][el]--; } }
[ "function repeatMoles () {\r\n randHoleIdx = Math.floor(Math.random()*(holes.length)+1);\r\n holes[randHoleIdx].classList.toggle(\"mole\");\r\n}", "function setPattern() {\n //zeroArray();\n\n if(difficulty < 12) {\n difficulty = 4 + (p_score/20);\n }\n \n let tiles = 0;\n\n while(tiles < difficulty) {\n let x = Math.round(Math.random() * (gridWidth - 1));\n let y = Math.round(Math.random() * (gridHeight - 1));\n\n if(tileArray[x][y] == 0) {\n tileArray[x][y] = 1;\n tiles++;\n }\n }\n\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 newShape() {\n var id = Math.floor( Math.random() * shapes.length );\n var shape = shapes[ id ]; // maintain id for color filling\n\n current = [];\n for ( var y = 0; y < 4; ++y ) {\n current[ y ] = [];\n for ( var x = 0; x < 4; ++x ) {\n var i = 4 * y + x;\n if ( typeof shape[ i ] != 'undefined' && shape[ i ] ) {\n current[ y ][ x ] = id + 1;\n }\n else {\n current[ y ][ x ] = 0;\n }\n }\n }\n \n // new shape starts to move\n freezed = false;\n var max = COLS - 4;\n // Random X\n var testX = Math.floor(Math.random() * 5) + 2; // check priv and allways move 2-7 right untill max has been met.\n testX = priv + testX;\n testX = testX % max;\n priv = testX;\n\n\n\n // position where the shape will evolve\n currentX = testX;\n currentY = 0;\n}", "function assignMole() {\n\tvar circle = circles[Math.floor(Math.random() * circles.length)];\n\tcircle.style.backgroundImage = \"url(mole.png)\";\n\tcircle.hasMole = true;\n}", "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 randomShape(){\n\treturn Math.floor(Math.random()*50);\n}", "function createBlackHoles() {\n\t// Get 2D coordinates\n\tlet [ground_coord_2D, sky_coord_2D, roof_coord_2D] = computeCoordinates2D();\n\n\t// create a simple square shape. We duplicate the top left and bottom right\n\tlet blackHolesGeometry = new THREE.BufferGeometry();\n\n\tlet [vertices, co_vertices] = fillVertices(ground_coord_2D, sky_coord_2D, roof_coord_2D);\n\n // itemSize = 3 because there are 3 values (components) per vertex\n blackHolesGeometry.setAttribute(\n \"position\",\n new THREE.BufferAttribute(vertices, 3)\n );\n\n let blackHolesMaterial = new THREE.MeshBasicMaterial({\n transparent: true,\n color: 0x0,\n side: THREE.DoubleSide,\n depthWrite: false,\n });\n\n blackHoles = new THREE.Mesh(blackHolesGeometry, blackHolesMaterial);\n\n scene.add(blackHoles);\n\n blackHoles.visible = mode3D;\n}", "function createBlackHoles() {\n\t// Get 2D coordinates\n\tlet [ground_coord_2D, sky_coord_2D] = computeCoordinates2D();\n\n\t// create a simple square shape. We duplicate the top left and bottom right\n\tlet blackHolesGeometry = new THREE.BufferGeometry();\n\n\tlet vertices = fillVertices(ground_coord_2D, sky_coord_2D);\n\n\n\t// itemSize = 3 because there are 3 values (components) per vertex\n\tblackHolesGeometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));\n\n\tlet blackHolesMaterial = new THREE.MeshBasicMaterial({ transparent: true, color: 0x0, side: THREE.DoubleSide, depthWrite: false });\n\n\tblackHoles = new THREE.Mesh(blackHolesGeometry, blackHolesMaterial);\n\n\tscene.add(blackHoles);\n\n\tblackHoles.visible = mode3D;\n}", "function randomCells() {\n generation = 0;\n clear = false;\n for (let y = 0; y < resolution; y++) {\n for (let x = 0; x < resolution; x++) {\n if (clear) cells[x][y] = false;\n else if (Math.random() < 0.5) cells[x][y] = true;\n }\n }\n }", "function diamond4() {\n return Math.floor(Math.random() * 11 + 1);\n }", "plantSeed() {\n\t\tthis.stop();\n\t\tthis.loops = 0;\n\t\tthis.myTree = new FractalTree({x: ground.width/2-100, y: ground.height-20}, this.myDNA);\n\t\tthis.settingsClose();\n\t\tthis.play();\n\t}", "function comet() {\r\n var bodyWidth = $(window).width();\r\n var x = Math.floor((Math.random() * bodyWidth));\r\n\r\n $('.shootingStar').css('left', x);\r\n $(\".shootingStar\").animate({\r\n marginLeft:\"100%\", marginBottom:\"100%\"\r\n }, 800); \r\n }", "function freeze(){\r\n if (current.some(index => squares[currentPosition+index+width].classList.contains('taken'))){\r\n current.forEach(index => squares[currentPosition+index].classList.add('taken'));\r\n // select a new piece \r\n random = nextRandom;\r\n nextRandom = Math.floor(Math.random()*piecesArray.length);\r\n current = piecesArray[random][currentRotation];\r\n currentPosition = 4;\r\n draw();\r\n displayShape();\r\n addScore();\r\n endGame();\r\n }\r\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 createStars() {\n for (var i = 0; i < 150; i += 1) {\n var star = new Star(Math.floor(random(0, width)), Math.floor(random(0, height)), random(1, 5), Math.floor(random(1, 5)));\n stars.push(star);\n }\n}", "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 diamond3() {\n return Math.floor(Math.random() * 11 + 1);\n }", "function plantFractal(colors, dim, max_seeds, fractalObjects) {\n let x_point;\n const wireSeedNum = p5.int(p5.random(1, 8));\n const towerSeedNum = p5.int(p5.random(8, 10));\n //seed a new fractal object, either a wire type or a tower type\n //much of this somewhat messy code is all about making fractals appear\n //tallest in the middle of the canvas, and get smaller towards the edges\n const halfway_max_seeds = max_seeds / 2;\n let this_index; //index of seed adjusted for where it sits in first or second half of total\n //first half of drawing, moving from middle to right, getting shorter as you get to the edge\n if (fractalObjects.length < halfway_max_seeds) {\n //middle to right\n this_index = halfway_max_seeds - fractalObjects.length;\n x_point = dim.w - this_index * (dim.w / 2 / halfway_max_seeds);\n } else {\n this_index =\n halfway_max_seeds - (fractalObjects.length - halfway_max_seeds);\n x_point = this_index * (dim.w / 2 / halfway_max_seeds);\n }\n\n //seed with more wires than towers\n if (p5.int(p5.random(100) < 75))\n seed(\n wireSeedNum,\n x_point,\n this_index,\n halfway_max_seeds,\n colors,\n dim,\n fractalObjects\n );\n else\n seed(\n towerSeedNum,\n x_point,\n this_index,\n halfway_max_seeds,\n colors,\n dim,\n fractalObjects\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Funcion para el Servicio de Mensajes Obtiene el id del frame del contenedor a partir de su flujoId
function obtenerIDContenedor(flujoId) { var contenedorID =null; var contenedora=false; var urlsDesconexionAux=null; var documento=null; var nombrePadre=null; var frame = null; try { try { //Se comprueba si se está en la página contenedora o en el contenedor if (urlsDesconexion!=undefined && urlsDesconexion!=undefined){ contenedora=true; urlsDesconexionAux=urlsDesconexion; documento=document; }else{ contenedora=false; urlsDesconexionAux=parent.urlsDesconexion; documento=parent.document; } }catch (err){ try{ contenedora=false; urlsDesconexionAux=parent.urlsDesconexion; documento=parent.document; }catch (err2){ //Distinto dirbase urlsDesconexionAux=null; } } if (urlsDesconexionAux != undefined && urlsDesconexionAux!=null) { for (var i=0 ; i<urlsDesconexionAux.length ; i++){ //identificador del contenedor var iden_conte = 'frame_'+urlsDesconexionAux[i][0]; //se obtiene el frame del contenedor var window = null; if (documento.getElementById(iden_conte).contentWindow) { window = documento.getElementById(iden_conte).contentWindow; } else { // IE window = documento.frames[iden_conte].window; } //se recupera el flujo var idflujo = null; try{ idflujo = window.document.forms[0].flujo.value; }catch (err){ idflujo = null; } if (idflujo!=null && flujoId==idflujo) { contenedorID=urlsDesconexionAux[i][0]; break; } } } if (contenedorID!=null){ return contenedorID; } try{ if (parent.parent.ventanasEmergentes_Identificadores!=undefined && parent.parent.ventanasEmergentes_Identificadores!=null && parent.parent.ventanasEmergentes_Identificadores.length>0){ ventanasEmergentes_IdentificadoresAux=parent.parent.ventanasEmergentes_Identificadores; documento=parent.parent.document; nombrePadre=parent.name; }else{ if (parent.ventanasEmergentes_Identificadores!=undefined && parent.ventanasEmergentes_Identificadores!=null && parent.ventanasEmergentes_Identificadores.length>0) { ventanasEmergentes_IdentificadoresAux=parent.ventanasEmergentes_Identificadores; documento=parent.document; } else{ ventanasEmergentes_IdentificadoresAux=ventanasEmergentes_Identificadores; documento=document; } } }catch (err){ try{ //recogemos los identificadores que tenga la ventana ventanasEmergentes_IdentificadoresAux=parent.ventanasEmergentes_Identificadores; documento=parent.document; }catch (err2){ //Distinto dominio ventanasEmergentes_IdentificadoresAux=null; } } if (ventanasEmergentes_IdentificadoresAux != undefined && ventanasEmergentes_IdentificadoresAux!=null) { for (var i=0 ; i<ventanasEmergentes_IdentificadoresAux.length ; i++){ //identificador del contenedor var iden_conte = 'iframeinterno_'+ventanasEmergentes_IdentificadoresAux[i]; //se obtiene el frame del contenedor var window = null; try{ if (documento.getElementById(iden_conte).contentWindow) { window = documento.getElementById(iden_conte).contentWindow; } else { // IE window = documento.frames[iden_conte].window; } }catch (err){ window=null; } //se recupera el flujo var idflujo = null; try{ idflujo = window.document.forms[0].flujo.value; }catch (err){ idflujo = null; } if (idflujo!=null && flujoId==idflujo) { contenedorID=ventanasEmergentes_IdentificadoresAux[i]; break; }else if(iden_conte==nombrePadre){ contenedorID=ventanasEmergentes_IdentificadoresAux[i]; break; } } } return contenedorID; } finally { contenedorID =null; contenedora=false; urlsDesconexionAux=null; documento=null; nombrePadre=null; frame = null; } }
[ "function obtenerContenedor(flujoId)\n{\n \n var contenedor =null;\n var contenedora=false;\n var urlsDesconexionAux=null;\n var documento=null;\n var ventanasEmergentes_IdentificadoresAux=null;\n //variable para almacenar el nombre de la ventana padre\n var nombrePadre=null;\n var frame = null;\n \n try{\n \n try {\n //Se comprueba si se está lanzando el mensaje de error desde el contenedor o desde la página contenedora\n if (urlsDesconexion!=undefined && urlsDesconexion!=null){\n //Estoy en la pagina contenedora\n contenedora=true;\n urlsDesconexionAux=urlsDesconexion;\n documento=document;\n }else{\n //Estoy en el contenedor, luego tengo que tomar los datos de la página contenedora\n contenedora=false;\n urlsDesconexionAux=parent.urlsDesconexion;\n documento=parent.document;\n }\n }catch (err){\n try{\n contenedora=false;\n urlsDesconexionAux=parent.urlsDesconexion;\n documento=parent.document;\n }catch (err2){\n //Distinto dirbase\n urlsDesconexionAux=null;\n }\n }\n\n\n if (urlsDesconexionAux != undefined && urlsDesconexionAux!=null)\n {\n \t for (var i=0 ; i<urlsDesconexionAux.length ; i++){\n \t\t //identificador del contenedor\n \t\t var iden_conte = 'frame_'+urlsDesconexionAux[i][0];\n \t\t //se obtiene el frame del contenedor\n\n \t\t \n \t\t if (documento.getElementById(iden_conte).contentWindow)\n \t \t{\n \t frame = documento.getElementById(iden_conte).contentWindow;\n \t \t} else\n \t \t{\n \t // IE\n \t frame = documento.frames[iden_conte].window;\n \t \t}\n \t\t //var frame = getFrameContenedor(iden_conte);\n\n \t\t\t\t//se recupera el flujo\n \t\t var idflujo = null;\n \t\t try{\n \t\t\t idflujo = frame.document.forms[0].flujo.value;\n \t\t }catch (err){\n \t\t\t idflujo = null;\n \t\t }\n \t\t if (idflujo!=null && flujoId==idflujo)\n \t\t {\n \t\t \tcontenedor=frame;\n \t\t \tbreak;\n \t\t\t\t}\n \t\t}\n \t}\n \tif (contenedor!=null){\n \t return contenedor;\n }\n\n try{\n if (parent.parent.ventanasEmergentes_Identificadores!=undefined && parent.parent.ventanasEmergentes_Identificadores!=null && parent.parent.ventanasEmergentes_Identificadores.length>0)\n {\n \t\tventanasEmergentes_IdentificadoresAux=parent.parent.ventanasEmergentes_Identificadores;\n \tdocumento=parent.parent.document;\n\t\t\t\t\tnombrePadre=parent.name;\n\n }\n else if (parent.ventanasEmergentes_Identificadores!=undefined && parent.ventanasEmergentes_Identificadores!=null && parent.ventanasEmergentes_Identificadores.length>0)\n \t{\n \t \tventanasEmergentes_IdentificadoresAux=parent.ventanasEmergentes_Identificadores;\n \tdocumento=parent.document;\n }\n \telse {\n \tventanasEmergentes_IdentificadoresAux=ventanasEmergentes_Identificadores;\n \tdocumento=document;\n }\n }catch (err){\n try{\n\t\t\t\t//recogemos los identificadores que tenga la ventana\n ventanasEmergentes_IdentificadoresAux=parent.ventanasEmergentes_Identificadores;\n documento=parent.document;\n }catch (err2){\n //Distinto dirbase\n ventanasEmergentes_IdentificadoresAux=null;\n }\n }\n\n if (ventanasEmergentes_IdentificadoresAux != undefined && ventanasEmergentes_IdentificadoresAux!=null)\n {\n \t for (var i=0 ; i<ventanasEmergentes_IdentificadoresAux.length ; i++){\n\t\t //identificador del contenedor\n \t\t var iden_conte = 'iframeinterno_'+ventanasEmergentes_IdentificadoresAux[i];\n\t\t //se obtiene el frame del contenedor\n \t\t try{\n\t\t if (documento.getElementById(iden_conte).contentWindow)\n\t \t{\n\t frame = documento.getElementById(iden_conte).contentWindow;\n\t \t} else\n\t \t{\n\t // IE\n\t frame = documento.frames[iden_conte].window;\n\t \t}\n \t }catch (err){\n frame=null;\n }\n\n\t\t\t\t//se recupera el flujo\n\t\t var idflujo = null;\n\t\t try{\n\t\t\t idflujo = frame.document.forms[0].flujo.value;\n\t\t }catch (err){\n\t\t\t idflujo = null;\n\t\t }\n\t\t if (idflujo!=null && flujoId==idflujo)\n\t\t {\n\t\t \tcontenedor=frame;\n\t\t \tbreak;\n\t\t\t\t}\n\t\t\t\t\telse if (iden_conte==nombrePadre){\n\t\t\t\t\t\tcontenedor=frame;\n \t\t \tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn contenedor;\n\t\n\t}finally{\n\t\tcontenedor =null;\n\t\tcontenedora=false;\n\t\turlsDesconexionAux=null;\n\t\tdocumento=null;\n\t\tventanasEmergentes_IdentificadoresAux=null;\n\t\tnombrePadre=null;\n\t\tframe = null;\n\t\t\n\t}\n}", "function sequenceNo(frame) {\n return frame.attr(\"id\");\n}", "function getIdCajero(){\n\treturn idCajeroGlobal;\n}", "getMSID() {\n const streamId = this.getStreamId();\n const trackId = this.getTrackId();\n\n return streamId && trackId ? `${streamId} ${trackId}` : null;\n }", "getMessageId(body){\n this.messageId=JSON.stringify(JSON.parse(body).value[0][\"id\"]);\n }", "function getIdMesero(){\n\treturn idMeseroGlobal;\n}", "function getID(elemento){ return document.getElementById(elemento); }", "morawareJobID() {\n let reg = /(?<=mw-job-id: )\\d*/\n let jobID = this.msg.match(reg)[0]\n return jobID\n }", "id() {\n \n // implementation should be inside the child class, but below implementation\n // if for simplicity in many occasions\n if (typeof this.data.id != 'undefined') return this.data.id;\n\n // no ID\n return null;\n }", "function getSenderID() {\n var array = Object.keys(agent.originalRequest.payload);\n if(array.length > 0) {\n console.log(JSON.stringify(agent.originalRequest.payload));\n if (agent.originalRequest.source === 'telegram')\n return agent.originalRequest.payload.data.from.id;\n else return getFacebookSenderID();\n } else {\n return getDialogflowSenderID();\n }\n }", "get id() {\n this._id = getValue(`cmi.objectives.${this.index}.id`);\n return this._id;\n }", "getNewId() {\n var id = -1;\n\n this.meanlines.leafletLayer.getLayers().forEach((layer) => {\n if (layer.feature.id >= id) {\n id = layer.feature.id + 1;\n }\n });\n\n return id;\n }", "function getDialogflowSenderID() {\n var array = request.body.queryResult.outputContexts;\n if (array.length > 2) {\n return request.body.queryResult.outputContexts[1].parameters.facebook_sender_id;\n } else {\n return request.body.queryResult.outputContexts[0].parameters.facebook_sender_id;\n }\n }", "function getId(dbEntity){\n return dbEntity.entity.key.path[0].id ||\n dbEntity.entity.key.path[0].name;\n}", "static getParentId(el){\n return $(el).parents('div[class^=\"shiny\"]').prop(\"id\");\n }", "setId(id) {\n this.name = id;\n this.client.sendJson(MessageConverter.nameToJson(id));\n return Promise.resolve();\n }", "function _generateFluxId() {\n return next_flux_id++;\n}", "getFrameAuthor(frameIndex) {\r\n return this.meta.current.fsid;\r\n }", "function getVideoId(videojsVideo) {\n if (useVideoJs() && videojsVideo) {\n var id = videojsVideo.Q ? videojsVideo.Q : videojsVideo.U;\n return id;\n } else {\n return videojsVideo;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
9. Create a function called listMovies Your function should take no parameters It should loop over all of the movies in the movieQueue, and return the string: "Here are the current movies: , , "
function listMovies(){ for (var i = 0; i < movieQueue.length; i++) { return "Here are the current movies: "+ movieQueue[0]+"," +" "+ movieQueue[1]+","+" "+movieQueue[2]+", "; } }
[ "function BrowseMovies() \n{\n HideListingCriteria();\n movieCriteria = \"All\"\n movieCriteriaValue = \"Movies\";\n BuildMoviesCache(MOVIE_LISTING_URI)\n startPage = 0;\n FetchTitles(startPage)\n}", "function addMoviesToEnd() {\n var movies = [\"mac\", \"burger\", \"Slash\"];\n for (var i = 0; i < movies.length; i++) {\n addMovieToEnd(movies[i]);\n }\n return movies;\n}", "function addMovieToEnd(movie){\n movieQueue.push(movie);\n return movie;\n }", "function getAllMovieInfo(list){\n\tfor(var i=0;i<list.length;i++){\n\t\tgetMovieInfo(list[i]).then( function(response){\n// \t\t\tconsole.log(': '+ JSON.stringify(response.results[0])+'\\n\\n');\n\t\t\tconsole.log('['+ response.results[0].original_title+']');\n\t\t\tconsole.log(response.results[0].overview+'\\n');\n\t\t});\n\t}\n}", "displayMovieFromLS() {\n const movies = this.getMovieFromLS()\n movies.forEach(movie => {\n this.addMovieToUI(movie)\n })\n }", "function writeMovies(movies) {\n let output = ''\n movies.forEach(function(movie) {\n output += '<article><h1>' + movie.title + '</h1></article>'\n })\n document.getElementById('movies').innerHTML += output\n }", "function changeMovie(index , movie){\n movieQueue[index]=movie;\n return movie;\n \n}", "function showSearchMovies(){\n query = moviesSearch.value;\n if (query != \"\"){\n resultsList.innerHTML = \"\";\n customQuery = query;\n resetPageNumbers();\n customPage = 1;\n tmdb.searchMovies(query, customPage).then(data => {\n resultsList.innerHTML = \"\";\n results = data.searchMovies.results;\n totalPages = data.searchMovies.total_pages;\n\n if (results != undefined){\n newMoviesList(results);\n removeMiniNavActive();\n }\n else{\n resetPageNumbers();\n }\n\n loadMore.style.display = (totalPages > 1) ? 'inline' : 'none';\n });\n }\n}", "function changeList(){\n const sortedMovies = movieDB.movies.sort(); \n\n const promoInteractiveItems = document.querySelectorAll('.promo__interactive-item');\n for(let i = 0; i <= promoInteractiveItems.length - 1 ; i++){\n promoInteractiveItems[i].textContent = (i+1) + '. ' + sortedMovies[i];\n }\n}", "function getMovie(getMovie) {\n if (getMovie < movieQueue.length) {\n return movieQueue[getMovie];\n }\n else {\n return (\"not a valid index\");\n }\n}", "function findMovie(movie) {\n for (var i = 0; i < movieQueue.length; i++) {\n if (movieQueue[i] === movie) {\n return true;\n }\n }\n return false;\n}", "function displayFilteredMovies() {\n featuredResults = originalResults; // reset to original list before filtering\n\n // filter the movies with current selected genre\n // let genre = $(\"#filter-genre\").children(\"option:selected\").val();\n let genre = $(\"#selected-genre\").text();\n console.log(\"Filter movies with Genre:\", genre);\n if (genre != \"Select Genre\") {\n featuredResults = filterMovieByGenre(featuredResults, genre);\n console.log(\"Genre filtered\", featuredResults);\n }\n\n // filter the movie with current selected rating\n // let rating = $(\"#filter-rating\").children(\"option:selected\").val();\n let ratingText = $(\"#selected-rating\").text();\n console.log(\"Selected Rating:\" + ratingText);\n let rating = 0;\n switch (ratingText) {\n case \"Above 3\":\n rating = 3;\n break;\n case \"Above 5\":\n rating = 5;\n break;\n case \"Above 7\":\n rating = 7;\n break;\n default:\n rating = 0;\n }\n console.log(\"Filter Movie with Rating:\", rating);\n\n /*if (rating != \"\") { */\n if (rating != 0) {\n featuredResults = filterMovieByRating(featuredResults, rating);\n console.log(\"Rating filtered\", featuredResults);\n }\n\n $(\"#selected-movie-container\").hide(); // remove the last selected movie detail\n displayAllMovies(featuredResults);\n //displayGenreOptions(featuredResults);\n }", "function displayMovies ( movies ) {\n let table;\n table = \"<table border='1' style='width: 100%'>\";\n table += \"<tr><th>ID</th><th>Name</th><th>Rank</th></tr>\";\n for ( let index = 0; index < movies.length; index ++ ) {\n table += \"<tr>\";\n table += \"<td>\" + movies[ index ].id + \"</td>\";\n table += \"<td>\" + movies[ index ].title + \"</td>\";\n table += \"<td>\" + movies[ index ].rank + \"</td>\";\n table += \"</tr>\";\n }\n// Close the table\n table += \"</table>\";\n document.getElementById ( \"movies-list\" ).innerHTML = table;\n}", "getMovies() {\n console.log('in get movies');\n this.props.dispatch({\n type: 'FETCH_MOVIES'\n }) \n }", "renderNomineeList() {\n return(\n <div>\n <div className=\"section-title\">{`Nominations (${this.state.nominees.length}/${config.MAX_NOMINATIONS})`}</div>\n {this.state.nominees.map((movie) => this.renderMovie(\n `nominee#${movie.imdbID}`, movie, this.renderRemoveButton(movie)\n ))}\n </div>\n );\n }", "function buildMovieList(){\n\n for(let i=0; i < titles.length; i++){\n\n var mov = {\n 'title':titles[i],\n 'src':images[i],\n 'synopsis':synopsis[i],\n 'directors':directors[i],\n 'actors':actors[i],\n 'year':year[i]\n };\n\n //add to each set of info to allMovieInfo Array\n allMovieInfo.push(mov);\n\n }\n\n}", "function setMoviesPage() {\n\n // display movie genres list\n listMovieGenres();\n\n // display movie year list with forwarded range data\n listMovieYears(2000, 2021)\n\n // display popular movies at page startup\n displayPopularMovies();\n}", "function switchList(id){\n errorItem.visible = false\n\n showingNav = false;\n hideNavPanel.start()\n\n if(movieId !== id){\n switch(id)\n {\n case 1:\n movieList.pageTitle = \"New Release\"\n break;\n case 4:\n movieList.pageTitle = \"Coming Soon\"\n break;\n default:\n movieList.pageTitle = \"In Theaters\"\n }\n\n\n movieId = id\n\n if(Storage.lastMovieTime(movieId) == undefined)\n metrics = true;\n else\n metrics = Storage.lastMovieTime(movieId);\n\n Core.checkXML(\"main\",metrics)\n }\n\n //! Stop Loading\n stopIndicator();\n}", "function displaySimilarMovies(movieId) {\n // api url info\n type = \"movie/\" + movieId + \"/similar\";\n let url = apiUrl + type + apiKey;\n\n fetch(url).then(response => response.json()).then(function(obj) {\n const NUMBER_OF_SIMILAR_MOVIES = 4;\n for (let i = 0; i < NUMBER_OF_SIMILAR_MOVIES; i++) {\n let img = imagePathPrefix + obj.results[i].poster_path;\n let title = obj.results[i].title;\n let genre = obj.results[i].genre_ids[0];\n let year = obj.results[i].release_date.substring(0, 4);\n let id = obj.results[i].id;\n document.getElementById(\"similar-movies\").innerHTML += \"<div class=' card mx-auto my-4 text-center col-12 col-sm-12 col-md-5 col-lg-3 col-xl-3' style='max-width: 18rem;'>\" +\n \"<img class='card-img-top mx-auto my-auto' style='max-width:16.5rem; max-height:300px;' src='\" + img + \"' alt='Card image cap'>\" +\n \" <div class='card-body'>\" +\n \"<h5 maxlength = '30' class='card-title'>\" + title + \"</h5>\" +\n \" <a href='#' class='card-link text-muted text-decoration-none'>\" + genre + \"</a>\" +\n \" <a href='#' class='card-link text-muted text-decoration-none'>(\" + year + \")</a>\" +\n \"<a href='#' onclick='previewItem(\" + id + \")' class='btn btn-primary btn-warning my-4 d-block'>View details</a>\" +\n \"</div> </div>\"\n }\n })\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Sheet | Type = Internal Function
function getSheet(sname){ var sheet = SpreadsheetApp.openByUrl(SpreadsheetURL).getSheetByName(sname); return sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues(); }
[ "function articleSheet(){\n if(!articleSheetInstance) articleSheetInstance = sheet(\"articles\")\n return articleSheetInstance\n}", "function getOtherSheet(otherShet){\n switch(otherShet){\n case \"Web\":\n return WSheet; \n break;\n case \"Graphic Design\":\n return GSheet;\n break;\n case \"Media (Photo/Video)\":\n return MedSheet;\n break;\n case \"Editorial and Content Development\":\n return EdSheet;\n break;\n case \"Digital and Database Marketing Projects\":\n return DDSheet; \n break;\n default:\n return GSheet;\n Logger.log(\"Didn't get anything!, or you just didn't make the right sheet :P\");\n break;\n }\n}", "function getTab(spreadsheetId,tabNumber) {\n var tab = tabNumber;\n var id = spreadsheetId;\n var ss = SpreadsheetApp.openById(id);\n var sheet = ss.getSheets()[tab];\n sheet.activate();\n Logger.log(\"readTab: \" + sheet.getName());\n return sheet;\n}", "function SpreadsheetTest(){\n this.sheets = [new SheetTest(\"Sheet1\", this)];\n this.activeSheet = 0;\n}", "function doRetrieveSpreadSheet(app){\n return async function(req, res, next){\n try{\n const {spreadSheetName} = req.params;\n const spreadSheetRes = await app.locals.ssStore.readFormulas(spreadSheetName);\n res.json(spreadSheetRes);\n } catch(err) {\n next(err);\n }\n }\n}", "async function getInfoAboutSpreadSheet() {\n try {\n return googleSheetsDocument.getInfoAsync();\n } catch (error) {\n console.log(\"Get information error\", error);\n }\n}", "function allSheets() {\n console.log('allCans called')\n return db('users_sheets')\n}", "addSheet(sheet) {\n var previousSheetIndex = this.SheetNames.indexOf(sheet.name);\n if (previousSheetIndex == -1) {\n this.SheetNames.push(sheet.name);\n }\n this.Sheets[sheet.name] = sheet;\n }", "function getBonusSheet(auth) {\n return new Promise((resolve, reject) => {\n const drive = google.drive({ version: \"v3\", auth });\n drive.files.export(\n { fileId: bonusSheetID, mimeType: \"text/csv\" },\n (err, response) => {\n if (err) reject(err, err.stack);\n // console.log(response.data);\n resolve(response.data);\n }\n );\n });\n}", "async function getFileSheets() {\n\n const fileId = selectFileSelectBox.value;\n worksheetSelect.innerHTML = defaultOptionSelect;\n\n if (fileId == 'none') { displayErrorMessage(\"Please select a file\");\n return false;\n }\n /* Send A request to get the sheets */\n const res = await fetch(`/getsheets/${fileId}`);\n const excelSheetsData = await res.json();\n if (excelSheetsData.code != 200){\n displayErrorMessage(excelSheetsData.message);\n } else {\n displayOptions(excelSheetsData.data, excelSheetsData.message);\n }\n}", "function SheetName(){\r\n var d = new Date();\r\n //return d.getFullYear().toString() + \"-\" + (d.getMonth() + 1).toString().padStart(2, '0') + \"-\" + LastSunday();\r\n return d.getFullYear().toString().substr(-2) + WeekOfYear();\r\n}", "function createSheet(id, name) {\n try {\n // Create new\n return SpreadsheetApp.openById(id).insertSheet(name);\n } catch (error) {\n console.log(error);\n const sheet = getSheet(id, name);\n // Clear existed\n sheet.clear();\n return sheet;\n }\n}", "function excel_define_sheet_name(excel) {\n var excel = excel || $JExcel.new();\n sheet_name = sheet_name || \"Summary\"\n sheet_number = sheet_number || 0\n excel.set(sheet_number, undefined, undefined, sheet_name);\n return excel\n}", "function load_spreadsheet(gdoc_url, sheet_name, onsuccess, onerror)\n{\n Tabletop.init({\n key: gdoc_url, callback: callback,\n simpleSheet: true, wanted: [sheet_name]\n });\n \n function callback(data, ttop)\n {\n var responses = [];\n \n try {\n if(data.length == 0) {\n return onerror('Zero rows returned', ttop);\n }\n \n if(data[0][GEO_COLUMN] == undefined) {\n return onerror('Missing \"Geographic Area\" column', ttop);\n }\n \n for(var i = 0; i <= data.length; i++) {\n if(data[i]) {\n var fields = data[i],\n feature;\n \n try {\n feature = JSON.parse(fields[GEO_COLUMN]);\n delete fields[GEO_COLUMN];\n\n } catch(error) {\n feature = null;\n }\n \n jQuery( \"body\" ).trigger( \"surveyMessage\", ['Reading reponse'+(i+1)+' of '+data.length+'...'] );\n responses.push(new Response(fields, feature));\n }\n }\n\n } catch(error) {\n return onerror('Caught error: ' + error.message);\n }\n \n onsuccess(responses, 'https://docs.google.com/spreadsheets/d/'+ttop.key+'/pubhtml');\n }\n}", "function gspread_query(range, spreadsheet_id, api_key) {\n api_key = api_key || \"AIzaSyApJBfnH0j3TSugzEABiMFkI_tU_XXeGzg\"\n spreadsheet_id = spreadsheet_id || \"1P0m6nu4CoXVD3nHrCgfm0pEvSpEkLsErjJxTLJLFjp8\"\n range = range || \"Checklists!A1\"\n url = \"https://sheets.googleapis.com/v4/spreadsheets/\" + spreadsheet_id + \"/values/\" + range\n return $.ajax({\n type: \"GET\",\n url: url,\n dataType: 'json',\n async: false,\n data: {\n 'key': api_key\n }\n });\n\n}", "function callScriptFunction(sheet_list) {\n var request = {\n 'function': 'getAllData',\n 'parameters': {\"name\": sheet_list}\n };\n // Make the API request.\n var op = gapi.client.request({\n 'root': 'https://script.googleapis.com',\n 'path': 'v1/scripts/' + SCRIPT_ID + ':run',\n 'method': 'POST',\n 'body': request\n });\n op.execute(function(resp){ \n handleGetDataResponse(resp);\n });\n}", "function createGSheetServices() {\n const gSheetServices = new GSheetServices(\n\n )\n return gSheetServices\n}", "function findStyleSheet(styleSheetId,styleSheetUrl)\r\n{\r\n\tvar styleSheets = dw.getDocumentDOM().browser.getWindow().document.styleSheets;\r\n\tif(styleSheetId > -1)\r\n {\r\n\t\treturn styleSheets[styleSheetId];\r\n\t}\r\n\t\r\n\tfor(var i=0;i<styleSheets.length;i++)\r\n\t{\t\r\n\t\tif(dw.compareURLs(styleSheets[i].href,styleSheetUrl))\r\n\t\t{\r\n\t\t\treturn styleSheets[i];\r\n\t\t}\r\n\t\telse\r\n\t\t{\t\t\t\r\n\t\t\tvar styleSheet = findNestedStyleSheet(styleSheets[i],styleSheetUrl);\r\n\t\t\tif(styleSheet)\r\n\t\t\t\treturn styleSheet;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}", "function makeRecruitSheet(){\nvar sheetname = 'BUILDING - Recruits Sheet'\nvar ss = SpreadsheetApp.getActiveSpreadsheet(), newSheet;\nnewSheet = ss.insertSheet();\nnewSheet.setName(sheetname);\n}", "function findHigherSheet(registry, options) {\n for (var i = 0; i < registry.length; i++) {\n var sheet = registry[i];\n if (\n sheet.attached &&\n sheet.options.index > options.index &&\n sheet.options.insertionPoint === options.insertionPoint\n ) {\n return sheet;\n }\n }\n return null;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a string to a sequence of 16word blocks, stored as an array. Append padding bits and the length, as described in the MD5 standard. MD5 here is not a typo this function is borrowed from the MD5 code.
function str2blks_MD5(str) { var nblk = ((str.length + 8) >> 6) + 1; var blks = new Array(nblk * 16); for(var i = 0; i < nblk * 16; i++) blks[i] = 0; for(i = 0; i < str.length; i++) blks[i >> 2] |= str.charCodeAt(i) << ((i % 4) * 8); blks[i >> 2] |= 0x80 << ((i % 4) * 8); blks[nblk * 16 - 2] = str.length * 8; return blks; }
[ "function binl_md5(x, len) {/* append padding */x[len >> 5] |= 0x80 << ((len) % 32);x[(((len + 64) >>> 9) << 4) + 14] = len;var i, olda, oldb, oldc, oldd,a = 1732584193,b = -271733879,c = -1732584194,d = 271733878;for (i = 0; i < x.length; i += 16) {olda = a;oldb = b;oldc = c;oldd = d;a = md5_ff(a, b, c, d, x[i], 7, -680876936);d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);b = md5_gg(b, c, d, a, x[i], 20, -373897302);a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);d = md5_hh(d, a, b, c, x[i], 11, -358537222);c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);a = md5_ii(a, b, c, d, x[i], 6, -198630844);d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);a = safe_add(a, olda);b = safe_add(b, oldb);c = safe_add(c, oldc);d = safe_add(d, oldd);}return [a, b, c, d];}", "function _split5bytesBy5bits(arr) {\n const len = arr.length;\n //console.log('_split5bytesBy5bits len=', len)\n if (len > 5) {\n console.warn('WARN: _split5bytesBy5bits() more than 5 bytes, cut 5 bytes only')\n }\n const b0 = (len > 0) ? arr[0] : 0;\n const b1 = (len > 1) ? arr[1] : 0;\n const b2 = (len > 2) ? arr[2] : 0;\n const b3 = (len > 3) ? arr[3] : 0;\n const b4 = (len > 4) ? arr[4] : 0;\n\n // ---- split by 5bits --> 8bytes ---\n const r0 = (b0 & 0b11111000) >> 3;\n const r1 = ((b0 & 0b00000111) << 2) | ((b1 & 0b11000000) >> 6);\n const r2 = (b1 & 0b00111110) >> 1;\n const r3 = ((b1 & 0b00000001) << 4) | ((b2 & 0b11110000) >> 4);\n const r4 = ((b2 & 0b00001111) << 1) | ((b3 & 0b10000000) >> 7);\n const r5 = ((b3 & 0b01111100) >> 2);\n const r6 = ((b3 & 0b00000011) << 3) | ((b4 & 0b11100000) >> 5);\n const r7 = (b4 & 0b00011111);\n\n // --- double check with another logic ---\n _dubleCheckSplit(r0, r1, r2, r3, r4, r5, r6, r7, b0, b1, b2, b3, b4);\n\n // --- pack to array ---\n let newArr = null;\n if (len >= 5) {\n newArr = new Uint8Array([r0, r1, r2, r3, r4, r5, r6, r7]);\n }\n else if (len === 4) {\n newArr = new Uint8Array([r0, r1, r2, r3, r4, r5, r6]);\n }\n else if (len === 3) {\n newArr = new Uint8Array([r0, r1, r2, r3, r4]);\n }\n else if (len === 2) {\n newArr = new Uint8Array([r0, r1, r2, r3]);\n }\n else if (len === 1) {\n newArr = new Uint8Array([r0, r1]);\n }\n else {\n newArr = new Uint8Array([]);\n }\n\n return newArr;\n}", "function isMD5Encrypted(inputString) {\r\n return /[a-fA-F0-9]{32}/.test(inputString);\r\n }", "function AlignSHA1(str) {\n\n\t\tvar nblk = ((str.length + 8) >> 6) + 1, blks = new Array(nblk * 16);\n\n\t\tfor (var i = 0; i < nblk * 16; i++)\n\t\t\tblks[i] = 0;\n\n\t\tfor (i = 0; i < str.length; i++)\n\n\t\t\tblks[i >> 2] |= str.charCodeAt(i) << (24 - (i & 3) * 8);\n\n\t\tblks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);\n\n\t\tblks[nblk * 16 - 1] = str.length * 8;\n\n\t\treturn blks;\n\n\t}", "function AlignSHA1(str) {\n\t\t\t\t\t\t\tvar nblk = ((str.length + 8) >> 6) + 1,\n\t\t\t\t\t\t\t\tblks = new Array(nblk * 16);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (var i = 0; i < nblk * 16; i++)\n\t\t\t\t\t\t\t\tblks[i] = 0;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (i = 0; i < str.length; i++)\n\t\t\t\t\t\t\t\tblks[i >> 2] |= str.charCodeAt(i) << (24 - (i & 3) * 8);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tblks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);\n\t\t\t\t\t\t\tblks[nblk * 16 - 1] = str.length * 8;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\treturn blks;\n\t\t\t\t\t\t}", "function md5uri64(strings) {\n\tvar sum = crypto.createHash('md5');\n\tstrings.forEach(function(str) {\n\t\tsum.update(str, 'utf8');\n\t});\n\treturn sum.digest('base64').replace(/[\\+\\/=]/g, function(ch) {\n\t\treturn { '+': 'a', '/': 'b', '=': '' }[ch];\n\t});\n}", "static bytes5(v) { return b(v, 5); }", "function binl(x, len) {\n var T, j, i, l,\n h0 = 0x67452301,\n h1 = 0xefcdab89,\n h2 = 0x98badcfe,\n h3 = 0x10325476,\n h4 = 0xc3d2e1f0,\n A1, B1, C1, D1, E1,\n A2, B2, C2, D2, E2;\n\n /* append padding */\n x[len >> 5] |= 0x80 << (len % 32);\n x[(((len + 64) >>> 9) << 4) + 14] = len;\n l = x.length;\n\n for (i = 0; i < l; i += 16) {\n A1 = A2 = h0;\n B1 = B2 = h1;\n C1 = C2 = h2;\n D1 = D2 = h3;\n E1 = E2 = h4;\n for (j = 0; j <= 79; j += 1) {\n T = safe_add(A1, rmd160_f(j, B1, C1, D1));\n T = safe_add(T, x[i + rmd160_r1[j]]);\n T = safe_add(T, rmd160_K1(j));\n T = safe_add(bit_rol(T, rmd160_s1[j]), E1);\n A1 = E1;\n E1 = D1;\n D1 = bit_rol(C1, 10);\n C1 = B1;\n B1 = T;\n T = safe_add(A2, rmd160_f(79 - j, B2, C2, D2));\n T = safe_add(T, x[i + rmd160_r2[j]]);\n T = safe_add(T, rmd160_K2(j));\n T = safe_add(bit_rol(T, rmd160_s2[j]), E2);\n A2 = E2;\n E2 = D2;\n D2 = bit_rol(C2, 10);\n C2 = B2;\n B2 = T;\n }\n\n T = safe_add(h1, safe_add(C1, D2));\n h1 = safe_add(h2, safe_add(D1, E2));\n h2 = safe_add(h3, safe_add(E1, A2));\n h3 = safe_add(h4, safe_add(A1, B2));\n h4 = safe_add(h0, safe_add(B1, C2));\n h0 = T;\n }\n return [h0, h1, h2, h3, h4];\n }", "function decorateVanillaSparkMD5_md51_array(md51_array) {\n\treturn a => new Uint8Array((new Uint32Array(md51_array(a))).buffer)\n}", "function toDER(r, s) {\n r = r.toArray()\n s = s.toArray()\n \n function constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len)\n return\n }\n \n let octets = 1 + (Math.log(len) / Math.LN2 >>> 3)\n arr.push(octets | 0x80)\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff)\n }\n \n arr.push(len)\n }\n\n function rmPadding(buf) {\n let i = 0\n const len = buf.length - 1\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++\n }\n if (i === 0) {\n return buf\n }\n return buf.slice(i)\n }\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r)\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s)\n\n r = rmPadding(r)\n s = rmPadding(s)\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1)\n }\n \n let arr = [ 0x02 ]\n constructLength(arr, r.length)\n arr = arr.concat(r)\n arr.push(0x02)\n constructLength(arr, s.length)\n const backHalf = arr.concat(s)\n let res = [ 0x30 ]\n constructLength(res, backHalf.length)\n res = res.concat(backHalf)\n return Buffer.from(res).toString('hex')\n }", "function bytePad(binarystr) {\n var padChar = \"0\";\n var pad = new Array(1 + 8).join(padChar);\n return (pad + binarystr).slice(-pad.length);\n}", "function generateChecksum(str) {\n\tvar buff = new buffer.Buffer(str);\n\n\tvar num = 0;\n\n\tfor(var i = 0; i < buff.length; i++) {\n\t\tnum += buff.readUInt8(i);\n\n\t\t// Handle overflow\n\t\tnum = num % 4294967296;\n\t}\n\t\n\treturn (num * 157 + num) % 4294967296;\n}", "static bytes15(v) { return b(v, 15); }", "function _getMessage(buffer /*: Buffer*/) /*: Array<BigInt>*/ {\n const words = [];\n let word = 0n;\n let byteLen = 0n;\n for (const c of buffer) {\n const b = byteLen++ & 0x7n;\n word |= BigInt(c) << (b << 3n);\n if (byteLen % 8n == 0n) {\n words.push(word);\n word = 0n;\n }\n }\n // Store original size (in bits)\n const bitSize = (byteLen << 3n) & U64;\n\n // Pad our message with a byte of 0x1 ala MD4 (Tiger1) padding\n const b = byteLen & 0x7n;\n if (b) {\n word |= 0x1n << (b << 3n);\n words.push(word);\n byteLen += 8n - b;\n } else {\n words.push(0x1n);\n byteLen += 8n;\n }\n\n for (byteLen %= 64n; byteLen < 56n; byteLen += 8n) {\n words.push(0n);\n }\n words.push(bitSize);\n return words;\n}", "static bytes6(v) { return b(v, 6); }", "function b64arrays() {\n var b64s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n b64 = new Array();\n f64 = new Array();\n for (var i = 0; i < b64s.length; i++) {\n b64[i] = b64s.charAt(i);\n f64[b64s.charAt(i)] = i;\n }\n}", "function makeBits(blockToken) {\n return (function (bits, split) {\n // Remove empty strings and strip whitespace.\n for (i = 0; i < split.length; i++) {\n (function (bit) {\n return bit === \"\" ? null : bits.push(bit);\n }(strip(split[i])));\n }\n return bits;\n }([], split(blockToken.replace(OPEN_BLOCK_TAG, \"\")\n .replace(CLOSE_BLOCK_TAG, \"\"),\n /[\\s]+?/)));\n }", "function sumBytesToSha256Uint32Array(bytes) {\n // XXX do doc\n\n // V8 optimized (status 1)\n // `return sumBytesToSha256Uint32Array([0,0,0,0])`\n\n // Note 1: All variables are 32 bit unsigned integers and addition is calculated modulo 232\n // Note 2: For each round, there is one round constant k[i] and one entry in the message schedule array w[i], 0 ≤ i ≤ 63\n // Note 3: The compression function uses 8 working variables, a through h\n // Note 4: Big-endian convention is used when expressing the constants in this pseudocode,\n // and when parsing message block data from bytes to words, for example,\n // the first word of the input message \"abc\" after padding is 0x61626380\n\n // Initialize hash values:\n // (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n var h0 = 0x6a09e667,\n h1 = 0xbb67ae85,\n h2 = 0x3c6ef372,\n h3 = 0xa54ff53a,\n h4 = 0x510e527f,\n h5 = 0x9b05688c,\n h6 = 0x1f83d9ab,\n h7 = 0x5be0cd19,\n\n // Initialize array of round constants:\n // (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311):\n k = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n ],\n\n // Pre-processing:\n // begin with the original message of length L bits\n L = bytes.length * 8,\n K = 512 - ((L + 1 + 64) % 512),\n append = new Array((K + 1) / 8),\n // append a single '1' bit\n // append K '0' bits, where K is the minimum number >= 0 such that L + 1 + K + 64 is a multiple of 512\n mi = 1, w = null,\n i = 0, s0 = 0, s1 = 0,\n a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0,\n maj = 0, ch = 0, temp1 = 0, temp2 = 0;\n append[0] = 0x80;\n for (; mi < append.length; mi += 1) append[mi] = 0x00;\n // append L as a 64-bit big-endian integer, making the total post-processed length a multiple of 512 bits\n bytes = bytes.concat(append.concat(encodeUint64ToBigEndianBytes(L)));\n\n // Process the message in successive 512-bit chunks (64 bytes):\n // break message into 512-bit chunks\n // for each chunk\n for (mi = 0; mi < bytes.length; mi += 64) {\n // create a 64-entry message schedule array w[0..63] of 32-bit words\n w = new Array(64);\n // (The initial values in w[0..63] don't matter, so many implementations zero them here)\n // copy chunk into first 16 words w[0..15] of the message schedule array\n for (i = 0; i < 16; i += 1)\n w[i] = decodeBigEndianBytesToInt32(bytes.slice(mi + (i * 4), mi + (i * 4) + 4));\n\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array:\n // for i from 16 to 63\n for (i = 16; i < 64; i += 1) {\n // s0 := (w[i-15] rightrotate 7) xor (w[i-15] rightrotate 18) xor (w[i-15] rightshift 3)\n s0 = rotateInt32BitsRight(w[i - 15], 7) ^ rotateInt32BitsRight(w[i - 15], 18) ^ (w[i - 15] >>> 3);\n // s1 := (w[i-2] rightrotate 17) xor (w[i-2] rightrotate 19) xor (w[i-2] rightshift 10)\n s1 = rotateInt32BitsRight(w[i - 2], 17) ^ rotateInt32BitsRight(w[i - 2], 19) ^ (w[i - 2] >>> 10);\n // w[i] := w[i-16] + s0 + w[i-7] + s1\n w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;\n }\n // Initialize working variables to current hash value:\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n f = h5;\n g = h6;\n h = h7;\n\n // Compression function main loop:\n // for i from 0 to 63\n for (i = 0; i < 64; i += 1) {\n // S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25)\n s1 = rotateInt32BitsRight(e, 6) ^ rotateInt32BitsRight(e, 11) ^ rotateInt32BitsRight(e, 25);\n // ch := (e and f) xor ((not e) and g)\n ch = (e & f) ^ ((~e) & g);\n // temp1 := h + S1 + ch + k[i] + w[i]\n temp1 = (h + s1 + ch + k[i] + w[i]) >>> 0;\n // S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22)\n s0 = rotateInt32BitsRight(a, 2) ^ rotateInt32BitsRight(a, 13) ^ rotateInt32BitsRight(a, 22);\n // maj := (a and b) xor (a and c) xor (b and c)\n maj = (a & b) ^ (a & c) ^ (b & c);\n\n // temp2 := S0 + maj\n temp2 = (s0 + maj) >>> 0;\n\n h = g;\n g = f;\n f = e;\n e = (d + temp1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (temp1 + temp2) >>> 0;\n }\n // Add the compressed chunk to the current hash value:\n h0 = (h0 + a) >>> 0;\n h1 = (h1 + b) >>> 0;\n h2 = (h2 + c) >>> 0;\n h3 = (h3 + d) >>> 0;\n h4 = (h4 + e) >>> 0;\n h5 = (h5 + f) >>> 0;\n h6 = (h6 + g) >>> 0;\n h7 = (h7 + h) >>> 0;\n }\n // Produce the final hash value (big-endian):\n // digest := hash := h0 append h1 append h2 append h3 append h4 append h5 append h6 append h7\n return [h0, h1, h2, h3, h4, h5, h6, h7];\n //return encodeInt32ToBigEndianBytes(h0)\n // .concat(encodeInt32ToBigEndianBytes(h1))\n // .concat(encodeInt32ToBigEndianBytes(h2))\n // .concat(encodeInt32ToBigEndianBytes(h3))\n // .concat(encodeInt32ToBigEndianBytes(h4))\n // .concat(encodeInt32ToBigEndianBytes(h5))\n // .concat(encodeInt32ToBigEndianBytes(h6))\n // .concat(encodeInt32ToBigEndianBytes(h7));\n }", "function arrayPacking(a) {\n return a.reduceRight((aByte, bByte) => (aByte << 8) + bByte);\n}", "function completeBinary(str) {\n\tlet a = str;\n\twhile (a.length % 8 !== 0) {\n\t\ta = \"0\" + a;\n\t}\n\treturn a;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates delay before next page loading.
function get_load_delay() { var current_delay = options.BASE_INTERPAGE_DELAY + Math.abs(Date.now() - status.ajax.start_time), smooth = status.ajax.load_count < 11 ? 1 - (1/ status.ajax.load_count) : -1.0; if (smooth >= 0 && Math.abs(current_delay - status.ajax.load_delay) < 2000 && current_delay < 4000) { status.ajax.load_delay = Math.ceil((current_delay * smooth + status.ajax.load_delay * (1.0 - smooth))/100)*100; //log('Next delay will be: ' + status.ajax.load_delay + '; real delay: ' + current_delay); } //log(get_document_height() - status.ajax.last_height); return status.ajax.load_delay; }
[ "function animationToLoadNextPage() {\n document.getElementsByTagName('body')[0].style.visibility = 'hidden'; \n document.getElementsByTagName('body')[0].className = 'loader_div';\n\n window.setTimeout(function() {\n window.location.href = \"add-patient-info.html\";\n }, 1000); \n}", "function waitTimes(){\r\n if (times = getTimesFromPage()){\r\n // save the times on this page\r\n saveSetting('waitTimes', times.toString().replace(/,/g, \";\"));\r\n return times;\r\n }\r\n else {\r\n // use known times\r\n times = getSetting('waitTimes', 'times').split(\";\");\r\n if (times != 'times'){\r\n if (getSetting('showTimes', '1') == '1'){\r\n placeTable();\r\n setInterval(countdowns, 1000);\r\n }\r\n return times;\r\n }\r\n else {\r\n checkTimes();\r\n }\r\n }\r\n}", "getDelayTime() {\n if (!this.list.length) return 0;\n return this.getFirstAni().delay;\n }", "function eventDelay() {\n //Randomly select a value from 0 to 1s\n return Math.floor(Math.random() * 1001);\n }", "async function load() {\n for (var page = 0; page < 10; page++) {\n let url = `https://www.newegg.com/p/pl?N=100006740%204814&Page=${page}&PageSize=96&order=BESTSELLING`\n makeRequest(url)\n await timer(500)\n\n }\n}", "function changeDelayBetweenSteps() {\n drawing.delay = stepDelaySlider.value;\n updateStepDelaySliderText(drawing.delay);\n}", "function delayGoToMain() {\n BD18.goToMain.timeoutID = window.setTimeout(goToMain, 3000);\n}", "function calculateDelay(string) {\n // 275 words per minute in milliseconds plus a constant\n var delayPerWord = 218;\n var delay = string.split(\" \").length * delayPerWord;\n delay = (delay < delayPerWord * 3) ? delay + 400 : delay;\n return delay;\n}", "function getNext(){\r\n // Don't do this if the user asked us not to\r\n if (!forward_fill) return;\r\n\r\n debug(d_med, \"We're getting the next 10!\");\r\n\r\n // Here we want to calculate the url of the next 10 reports\r\n\r\n // If we're on the initial report/message page\r\n if (latest_url.indexOf('s=')==-1){\r\n\tdebug(d_low, \"'s=' not found in url; append '?s=10'\");\r\n\tif (latest_url.indexOf('?')!=-1){\r\n\t latest_url += '&s=10';\r\n\t}\r\n\telse {\r\n\t latest_url += '?s=10';\r\n\t}\r\n }\r\n // Else we should extract and incriment that value by 10 to get the next page\r\n else {\r\n\tdebug(d_low, \"'s=' found in url; increment by 10\");\r\n\r\n\t// Strip off any troublesome #'s...\r\n\tif (latest_url.indexOf('#') != -1) latest_url = latest_url.split('#')[0];\r\n\r\n\ta = latest_url.split('s=')[1];\r\n\t// Hack to avoid infinite recursion, just in case...\r\n\tif (parseInt(a) > 300){\r\n\t updateArrows(true);\r\n\t return;\r\n\t}\r\n\tlatest_url = latest_url.split('s=')[0] + 's='+(parseInt(a)+10);\r\n }\r\n\r\n debug(d_low, latest_url);\r\n\r\n GM_xmlhttpRequest({\r\n\t method: 'GET',\r\n\t\turl: latest_url,\r\n\t\theaders: null,\r\n\t\tonload: onNextLoad});\r\n}", "onPageLoad() {\n\t\t// Updates all HTML elements to show stopwatch has no session\n\t\ttimerViews.toggleTimerElements(\n\t\t\tthis.currentlyTiming,\n\t\t\tthis.activeSession,\n\t\t\tthis.selectedCourse\n\t\t);\n\t\tif (this.currentlyTiming) {\n\t\t\t// Starts timer\n\t\t\tthis.start();\n\t\t}\n\t\tif (this.activeSession) {\n\t\t\t// Updates Time in timer\n\t\t\tthis.activeSession.updateTimerText();\n\t\t}\n\t}", "setFontPrefetchTimeout() {\n const TEN_SECONDS = 10000;\n const {\n selectedLanguage: prevLang\n } = this.state;\n\n if (this.prefetchPdfFontsTimeout) {\n clearTimeout(this.prefetchPdfFontsTimeout);\n }\n\n this.prefetchPdfFontsTimeout = setTimeout(() => {\n const {\n selectedLanguage: currLang\n } = this.state;\n\n if (prevLang === currLang) {\n const {\n regular,\n bold\n } = getFontFilenames(currLang);\n\n fetchFont(regular);\n fetchFont(bold);\n }\n }, TEN_SECONDS);\n }", "function runAfterDelay(delay,callback){\n console.log('(Exercise 7).Wait for '+delay+' secs....'); \n callback(delay);\n }", "function logMetrics_delayed(brokenLinks, excludedLinks, totalLinks, duration, preBreak, exit)\n{\n setImmediate(function ()\n {\n logMetrics(brokenLinks, excludedLinks, totalLinks, duration, preBreak, exit);\n });\n}", "function getFirstIntervalDelay () {\n\t\tvar now = Date.now();\n\t\tvar queryInterval = queryForecastFreqHrs * 60 * 60 * 1000;\n\t\tvar sinceLastInterval = now % queryInterval;\n\t\treturn (queryInterval - sinceLastInterval + (config.queryDelaySecs * 1000));\t\t\n\t}", "ms () { return this.now() - this.startMS }", "function pageCountDown() {\n let newPageNumber = pageNumber - 1;\n // console.log(newPageNumber)\n setPageNumber(newPageNumber);\n }", "function initializeLoadMore() {\n\n zeusLoadMore.updateScroll = true;\n window.curPage = 0; // initialize counter for load more\n window.nextSlotId = 1; // initialize nextSlot ID for ads\n window.showLoadMore = true; // begin the load more unless content retrieved is exhausted\n var zeusLoadMoreSettings = zeusLoadMore.drupalSettings();\n var type = zeusLoadMoreSettings['type'];\n var channel = zeusLoadMoreSettings['curChannel'];\n var disqusOnDemand = zeusLoadMoreSettings['disqusOnDemand'];\n // flag for infinite scroll or load more on click\n var loadMoreOnScroll = zeusLoadMoreSettings['loadMoreOnScroll'];\n var initialNid = zeusLoadMoreSettings['initialNid'];\n var initialUrl = zeusLoadMoreSettings['initialUrl'];\n var initialTitle = zeusLoadMoreSettings['initialTitle'];\n var initialHTitle = zeusLoadMoreSettings['initialHTitle'];\n zeusLoadMore.dtm = {};\n zeusLoadMore.pageTitle = {};\n zeusLoadMore.headTitle = {};\n zeusLoadMore.url = {};\n zeusLoadMore.sponsored = {}; //used on content pages\n\n //zeusLoadMore.currPage = 0; //initialize counter for zeus smartqueue load more\n zeusLoadMore.dfp = {}; //used for zeus_smartqueue\n zeusLoadMore.extraData = {}; // used for slideshows\n zeusLoadMore.itemCount = 1;\n zeusLoadMore.itemsContainer = jQuery('#itemsContainer');\n\n // If infinite scroll is enabled\n if (typeof loadMoreOnScroll !== 'undefined' && loadMoreOnScroll === 1) {\n\n window.flagtoload = true;\n window.lastScrollTop = 0;\n /*** based on http://ejohn.org/blog/learning-from-twitter/ **/\n jQuery(window).scroll(function() {\n window.didScroll = true;\n });\n\n setInterval(function() {\n if ( window.didScroll ) {\n window.didScroll = false;\n zeusLoadMore.iScrollHandler();\n }\n }, 500);\n\n if (type === 'zeus_content') {\n if (typeof dataLayer !== 'undefined') {\n zeusLoadMore.dtm[initialNid] = dataLayer;\n }\n zeusLoadMore.url[initialNid] = initialUrl;\n zeusLoadMore.pageTitle[initialNid] = initialTitle;\n zeusLoadMore.headTitle[initialNid] = initialHTitle;\n zeusLoadMore.navPage = 1; // Used when adding more to scroll navigation list\n zeusLoadMore.noMoreData = 0; // Flag to check if there is any more data\n // ajax call to load the settings\n // need it before any load more call\n jQuery.getJSON('/load-more-settings-content/ajax/'+initialNid, function(json, status) {\n if(status === \"success\") {\n zeusLoadMore.dfp[initialNid] = json.dfp;\n }\n });\n\n // Set up the comment count links for iscroll\n // jQuery('.comment-count-wrap a.show-comments').addClass('show-comments-section');\n jQuery('.content-wrapper a.show-comments').addClass('show-comments-section');\n\n if (zeusLoadMoreSettings['comments'] === 'facebook') {\n // facebook\n zeusLoadMore.initializeFbComments();\n\n } else if (disqusOnDemand === 1) {\n // disqus\n zeusLoadMore.initializeDisqus();\n }\n // Outbrain\n zeusLoadMore.initializeOutbrainWidgetIds();\n // Sponsored\n if (jQuery('body').hasClass('sponsored')) {\n zeusLoadMore.sponsored[initialNid] = 1;\n } else {\n zeusLoadMore.sponsored[initialNid] = 0;\n }\n\n } else if (type === 'zeus_smartqueue') {\n window.flagtoload = false;\n // ajax call to load the settings\n // need it before any load more call\n // @todo: right now separator ad does not work without iscroll\n jQuery.getJSON('/load-more-settings/ajax/'+channel, function(json, status) {\n if(status === \"success\") {\n zeusLoadMore.dfp = json.dfp;\n window.flagtoload = true;\n }\n });\n }\n jQuery('.pager-load-more li.pager-next').hide(); // Hide load more button if infinite scroll enabled\n } else {\n // default is load more click\n if (type === 'zeus_smartqueue') {\n jQuery(\".pager-load-more.page_\"+curPage).click(function(event) {\n event.preventDefault();\n zeusLoadMore.loadMoreHandlerZeusSmartqueue();\n });\n }\n }\n}", "function afterTimeout(){\n console.log(next_button.attr('href'));\n window.location = next_button.attr('href');\n }", "function init() {\n getMaxModifedDate(\n function (maxModifiedDate) {\n fetchTransactoinFromSplash(defaultPageIndex, maxModifiedDate)\n }\n );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the position of the closest open (aka nonobstacle) square to the square at the given posn (if the square at the given posn is open, returns the given posn)
closestOpenPosn(posn) { //bfs starting from posn var searchQueue = [posn]; var blacklist = []; while (searchQueue.length > 0) { var searching = searchQueue.pop(); var searchingSquare = this.get(searching); //is it a posn we're looking for? if (searchingSquare && (!searchingSquare.content || !searchingSquare.content.isObstacle)) { return searching; //we found what we're looking for! } //otherwise, add the current posn to blacklist and keep searching blacklist.push(searching); var adjacents = shuffle(this.getExistingAdjacentPosns(searching)); adjacents.forEach(function(p) { //add every posn in adjacents to the searchQueue var posnEqualToCurPos = function(otherPos) { return otherPos.x == p.x && otherPos.y == p.y; } //but only if it's not been blacklisted! if (blacklist.filter(posnEqualToCurPos).length == 0) { searchQueue.unshift(p); } }) } }
[ "get(posn) {\n\t\tif (!this.outOfBounds(posn)) {\n\t\t\treturn this.board[posn.x][posn.y];\n\t\t} else {\n\t\t\t//console.log(\"ERROR: Cannot get value - posn out of bounds: \" + posn.x + \",\" + posn.y);\n\t\t}\n\t\t//return this.board[posn.x % this.width][posn.y % this.height]\n\t}", "function findBestMove(board){\n\tconst centerPos = 4;\n\n\tvar sideX = 'x';\n\tvar sideO = 'o';\n\n var boardsToConsider1 = getNextBoards(board, sideO);\n var boardsToConsider2 = getNextBoards(board, sideX);\n\tvar numBoards = boardsToConsider1.length;\n\n\t// first try to see if we can do a move that\n\t// flat out wins the game\n for (var i=0; i<numBoards; i++){\n\t\tvar currOBoard = boardsToConsider1[i];\n\t\tif (determineWinner(currOBoard, sideO)){\n\t\t\treturn currOBoard;\n\t\t}\n\t}\n\n\t// next try to see if we can do a move that\n\t// blocks opponent from winning\n\tfor (var i=0; i<numBoards; i++){\n\t\tvar currXBoard = boardsToConsider2[i];\n\t\tif (determineWinner(currXBoard, sideX)){\n\t\t\tvar blockingBoard = boardsToConsider1[i];\n\t\t\treturn blockingBoard\n\t\t}\n\t}\n\n\tvar nextBoard;\n\t//otherwise, see if we can place it in the center\n\tif (board[centerPos] == ' '){\n\t\tnextBoard = getNextBoard(board, centerPos, sideO);\n\t}\n\t// if center is taken, then just take an arbitrary slot\n\telse{\n\t\tnextBoard = boardsToConsider1[0];\n\t}\n\treturn nextBoard;\n}", "function solve(n) {\n let currentSquareRoot = 1;\n let previousSquareRoot = 1;\n\n while (currentSquareRoot ** 2 - previousSquareRoot ** 2 < n) {\n if (isPerfectSquare(currentSquareRoot ** 2 + n)) {\n return currentSquareRoot ** 2;\n }\n\n previousSquareRoot = currentSquareRoot;\n currentSquareRoot += 1;\n }\n\n return -1;\n}", "function potentialState(state, pos) {\n // create copy of state\n let nextState = JSON.parse(JSON.stringify(state));\n\n // populate square, then update turn\n nextState.squares[pos] = nextState.xIsNext ? \"X\":\"O\";\n nextState.xIsNext = !nextState.xIsNext;\n nextState.stepNumber++;\n\n return nextState;\n}", "randomPosn() {\n\t\tvar p = new Posn(Math.floor(Math.random() * this.width), Math.floor(Math.random() * this.height));\n\t\treturn p;\n\t}", "function aiFindBestMove(board) {\n let bestMove = {\n value: -Infinity,\n index: -1\n }\n\n // iterate over empty spots\n for (let i = 0; i < 9; i++) {\n if (!board[i]) {\n // have the ai make a move on the empty spot\n board[i] = game.aiTeam;\n\n // get the value of the move\n const moveValue = minimax(board.slice(), 0, false, -Infinity, Infinity);\n if (moveValue > bestMove.value) {\n bestMove.value = moveValue;\n bestMove.index = i;\n }\n // undo the move\n board[i] = null;\n }\n }\n return bestMove.index;\n}", "function squareThatWasJumped(aMove) {\r\n\tlet x = (aMove.from.row + aMove.to.row) / 2;\r\n\tlet y = (aMove.from.col + aMove.to.col) / 2;\r\n\treturn board[x][y];\r\n}", "function nearestElement(n, arr) {\n const nearest = arr.concat().sort((a, b) => Math.abs(n - a) - Math.abs(n - b) || b - a)[0];\n return arr.indexOf(nearest);\n}", "getPlaceInfo(pos) {\n\t\tlet venueID = '';\n\t\tlet lat = pos.lat, lng = pos.lng;\t\t\n\n\t\t//this fetch's purpose is to find the venueID of the given position\n\t\treturn fetch(`https://api.foursquare.com/v2/venues/search?client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&v=${VERSION}&ll=${lat},${lng}`)\n\t\t .then(data => data.json())\n\t\t .then(data => {\n\t\t \tvenueID = data.response.venues[0].id;\n\t\t \treturn this.getPlaceTip(venueID);\n\t\t })\n\t\t .catch(function(e) {\n\t\t console.log(e);\n\t\t return null;\n\t\t });\t \n\t}", "function _getTopLeftOfQuadrant(topLeft, n, quadrant) {\n let adj = Math.pow(2, n - 1);\n if (quadrant === 1) {\n return topLeft;\n }\n else if (quadrant === 2) {\n return new Point(topLeft.x + adj, topLeft.y);\n }\n else if (quadrant === 4) {\n return new Point(topLeft.x, topLeft.y + adj);\n }\n else { // quadrant === 3\n return new Point(topLeft.x + adj, topLeft.y + adj);\n }\n}", "put(square, posn) {\n\t\tif (!this.outOfBounds(posn)) {\n\t\t\tthis.board[posn.x][posn.y] = square;\n\t\t} else {\n\t\t\t//console.log(\"ERROR: Cannot put value - posn out of bounds: \" + posn);\n\t\t}\n\t\t//this.board[posn.x % this.width][posn.y % this.height] = value;\n\t}", "getValidXPosition(pos, dir) {\n // Check is pos is a number or not\n let posNum = Number(pos);\n if (isNaN(posNum)) {\n return this.startXDefault;\n }\n // Bound the coordinate\n if (dir == 0 || dir == 180) {\n posNum = Math.max(posNum, this.height/2 + 3);\n posNum = Math.min(posNum, this.MaxX - this.height/2 - 3);\n } else {\n posNum = Math.max(posNum, this.width/2 + 3);\n posNum = Math.min(posNum, this.MaxX - this.width/2 - 3);\n }\n return posNum\n }", "function _getQuadrantOfPiece(topLeft, n, piece) {\n let xBoundary = topLeft.x + Math.pow(2, n - 1) - 1;\n let yBoundary = topLeft.y + Math.pow(2, n - 1) - 1;\n\n if (piece.x <= xBoundary && piece.y <= yBoundary) {\n return 1;\n }\n else if (piece.x <= xBoundary) {\n return 4;\n }\n else if (piece.y <= yBoundary) {\n return 2;\n }\n else {\n return 3;\n }\n}", "function minCostToClimbStairs(n, price) {\n const dp = new Array(n + 1).fill(0);\n dp[0] = 0;\n dp[1] = price[0];\n\n for (let i = 2; i <= n; i++) {\n dp[i] = price[i-1] + Math.min(dp[i - 1], dp[i - 2]);\n }\n\n return dp[n];\n}", "function getNearestGridPoint(x1, y1) {\n var current_x = parseInt(x1, 10);\n var current_y = parseInt(y1, 10);\n var i = 0;\n var minDist = Math.sqrt(Math.pow(points[i].x - current_x, 2) + Math.pow(points[i].y-current_y, 2));\n var ans = points[0];\n for(var i = 0 ; i < points.length; i ++) {\n var dist = Math.sqrt(Math.pow(points[i].x - current_x, 2) + Math.pow(points[i].y-current_y, 2));\n if(dist < minDist) {\n minDist = dist;\n ans = points[i];\n }\n }\n return ans;\n}", "isNearNest(movingObjPos) {\n return Utils.calculateDist([1.2, 0, 1.08], movingObjPos) <= 1;\n }", "getExistingAdjacentPosns(posn) {\n\t\tvar theWorld = this;\n\t\treturn posn.getAdjacentPosnsWithWraparound(theWorld).filter(function(p) {\n\t\t\treturn !!theWorld.get(p);\n\t\t})\n\t}", "function makeBestMove() {\n\t\t\t// look for winning move\n\t\t\t//then findBestCorner();\n\t}", "function getNearPositions(board, position) {\n var nearPositions = _getNearPositions(getBoardSize(board), Position.getXAndY(position));\n return getPositionsFromBoard(board, nearPositions);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
firstDialog() Generates a dialog box that will start the music and a chain of dialogs
function firstDialog() { // Making a variable for the dialog that appears in the div let $dialog = createDialog(narrations[0]); // Turning the $dialog variable into an actual dialog window $dialog.dialog({ // Adding an option with an anonymous function buttons: { "Let’s get to it!": function() { // The subscriber and month number increases changeScore(10000, 1); // The "Finger Family" scenario is called scenarioDialog(1, "I have to stay fresh…", fingerChoice); // The current dialog closes $(this).dialog('close'); } } }); // Positioning the dialog box using offset() // The parent method is used in order to prevent the text from within the dialog box to move $dialog.parent().offset({ top: 150, left: 950 }); // Removing the "close" corner box $('.ui-dialog-titlebar-close').remove(); // Adding narration for the dialog narrateDialog(narrations[0], 1, 1); // The main theme plays at the time when it becomes dynamic // The volume is lowered in order to prevent ResponsiveVoice from being drowned out mainTheme.volume = 0.2; mainTheme.currentTime = 39; mainTheme.loop = true; mainTheme.play(); }
[ "function startChoice() {\n\n //remove the prompt text and image\n $('.startImage').remove();\n heartSFX.stop;\n\n // set state of the game with this variable, 1 means the actual content of the project\n initiated = 1;\n\n // making the variable to chose the soundtrack 0, which is the ost for the riddles\n musicPlaying = 0;\n\n // call the function which puts in the colors and the music\n currentMusic();\n\n // append the div which contains the popup\n $('body').append(\"<div class = 'startingGame'><div>\");\n console.log(\"First Minigame - Initiated\");\n\n // define the text contained within the dialog window, using .html in order to use <br>, among other things\n $(\".startingGame\").html(\"You are suffocating at the bottom of the abyss, removed from the outside world. You had always known life to be an unwinnable game; a journey without purpose. When thinking of the hand you've been dealt, a single emotion surges forward. You felt... <br> <br> [Contempt] [Fear] [Hopelessness]\");\n\n // use annyang to answer the riddles, if its one of the answers in quotes, do something\n if (annyang) {\n var commands = {\n 'contempt': function() {\n // open the first riddle\n setTimeout(firstRiddle, 5000);\n // initiate responsiveVoice\n responsiveVoice.speak(\"Years of contempt leave you jaded.\", 'UK English Male', options);\n console.log('contempt option chosen');\n // play the sound effect for answers\n answerSFX.play();\n },\n 'fear': function() {\n // open the second riddle\n setTimeout(secondRiddle, 5000);\n // play responsiveVoice\n responsiveVoice.speak(\"Unadultered fear of the unknown cripple you.\", 'UK English Male', options);\n console.log('fear option chosen');\n // play sfx\n answerSFX.play();\n },\n 'hopelessness': function() {\n // open third riddle\n setTimeout(thirdRiddle, 5000);\n // play responsiveVoice\n responsiveVoice.speak(\"The broad expanse of the world weighs heavily upon your mind.\", \"UK English Female\", options);\n console.log('hopeless option chosen');\n //play sfx\n answerSFX.play();\n }\n }\n // annyang functionality\n annyang.addCommands(commands);\n annyang.start();\n\n }\n\n // variables for randomizing location of dialog boxes\n let horizontalOffset = Math.floor(Math.random() * 201) - 100;\n let verticalOffset = Math.floor(Math.random() * 401) - 200;\n\n // defining parameters of the dialog window\n $(\".startingGame\").dialog({\n //position the dialog window in the center of the canvas + a random offset\n position: {\n my: `center`+ verticalOffset,\n at: `center`+ horizontalOffset\n },\n // defining size\n height: 450,\n width: 550,\n // what will happen when clicking the 'x' button\n close: function() {\n // trigger responsiveVoice\n responsiveVoice.speak(\"There is no escape.\", 'UK English Male', options);\n // re-open the dialog window\n setTimeout(startChoice, 5000);\n },\n // removes ability to close window with the escape key\n closeOnEscape: false,\n // title of the window\n title: \"The Abyss - Submerged\"\n});\n}", "function firstTextGame() {\n\n // remove all riddles\n console.log(\"game launched\");\n $(\".riddle1\").remove();\n $(\".riddle2\").remove();\n $(\".riddle3\").remove();\n\n // change the music and colors to match part 2\n musicPlaying = 1;\n // call the function to do the above\n currentMusic();\n\n // append to the body, creating a div tag with a class of game1\n $('body').append(\"<div class = 'game1'><div>\");\n // append generated text to the dialog box\n $('.game1').append(\"<div id = 'content'><div>\");\n // define what will appear, in this case a mishmash of hamlet and the bible\n $('.game1').html(gotHamletTestamentData);\n\n // variables for randomizing location of dialog boxes\n let horizontalOffset = Math.floor(Math.random() * 401) - 200;\n let verticalOffset = Math.floor(Math.random() * 401) - 200;\n\n // annyang functionality, same as usual, if answer matches the ones beneath this line, move on to the next dialog\n if (annyang) {\n var commands = {\n 'hamlet': function() {\n // open next dialog in 3 seconds\n setTimeout(secondTextGame, 3000);\n // flavor text using responsiveVoice\n responsiveVoice.speak(\"A shakespearean classic, of course.\", 'UK English Male');\n console.log('annyang working');\n answerSFX.play();\n },\n 'shakespear': function() {\n setTimeout(secondTextGame, 3000);\n responsiveVoice.speak(\"Good enough.\", 'UK English Female');\n console.log('annyang working');\n answerSFX.play();\n },\n 'old testament': function() {\n setTimeout(secondTextGame, 3000);\n responsiveVoice.speak(\"A holy scripture. Of course you know about it.\", 'UK English Female');\n console.log('annyang working');\n answerSFX.play();\n },\n 'bible': function() {\n setTimeout(secondTextGame, 3000);\n responsiveVoice.speak(\"A little vague, but it does the job.\", 'Spanish Female');\n console.log('annyang working');\n answerSFX.play();\n }\n }\n // annyang functionality\n annyang.addCommands(commands);\n annyang.start();\n }\n\n // create the dialog box\n $(\".game1\").dialog({\n // position the box\n position: {\n my: `center`+ verticalOffset,\n at: `center`+ horizontalOffset\n },\n // size it\n height: 550,\n width: 750,\n // when x is pressed\n close: function() {\n responsiveVoice.speak(\"You know what they say about a good book.\", 'UK English Male', options);\n $(\".game1\").remove();\n setTimeout(firstTextGame, 5000);\n },\n closeOnEscape: false,\n // buttons that are used for this box alone in order to instruct user if they are confused or need help\n buttons: [\n {\n // button text\n text: \"Instructions\",\n // button icon\n icon: \"ui-icon-gear\",\n click: function() {\n // responsiveVoice reads instructions\n responsiveVoice.speak('Identify one of the works of literature above to reconstruct your personality.', 'UK English Male');\n }\n },\n {\n text: \"Resources Available\",\n icon: \"ui-icon-heart\",\n click: function() {\n // responsiveVoice reads advice\n responsiveVoice.speak('When in doubt, a vast electronic sea brimming with information can help.', 'UK English Female');\n }\n }\n ],\n title: \"The Second Layer - Restoration (1)\"\n });\n}", "function thirdTextGame() {\n\n // remove other dialogs\n $('.game2').remove();\n // append new div to body\n $('body').append(\"<div class = 'game3'><div>\");\n // apend content to new div\n $('.game3').append(\"<div id = 'content'><div>\");\n // set content to be the count of monte cristo and le petit prince, specifics done in the named function\n $('.game3').html(gotMontePrinceData);\n\n // variables for randomizing location of dialog boxes\n let horizontalOffset = Math.floor(Math.random() * 401) - 200;\n let verticalOffset = Math.floor(Math.random() * 401) - 200;\n\n // annyang functionality with all possible answers and different flavor texts for all of them\n if (annyang) {\n var commands = {\n 'count of monte cristo': function() {\n // open next part after 3 seconds\n setTimeout(firstQuestion, 3000);\n // responsiveVoice for text\n responsiveVoice.speak(\"Wait and hope; Words you've always gone by.\", 'UK English Male');\n console.log('annyang working');\n lockSFX.play();\n },\n 'monte cristo': function() {\n setTimeout(firstQuestion, 3000);\n responsiveVoice.speak(\"An unimaginable treasure. You wish you had such fortune.\", 'UK English Female');\n console.log('annyang working');\n lockSFX.play();\n },\n 'le petit prince': function() {\n setTimeout(firstQuestion, 3000);\n responsiveVoice.speak(\"Une aventure qui a du coeur. Tu en es jaloux.\", 'French Female');\n console.log('annyang working');\n lockSFX.play();\n },\n 'little prince': function() {\n setTimeout(firstQuestion, 3000);\n responsiveVoice.speak(\"An emotional tale that changed your youth.\", 'UK English Female');\n console.log('annyang working');\n lockSFX.play();\n }\n }\n // annyang functionality\n annyang.addCommands(commands);\n annyang.start();\n }\n // create the dialog\n $(\".game3\").dialog({\n // position it\n position: {\n my: `center`+ verticalOffset,\n at: `center`+ horizontalOffset\n },\n // size it and define what happens when x is clicked\n height: 600,\n width: 850,\n close: function() {\n responsiveVoice.speak(\"Wait and hope, and answer.\", 'UK English Male', options);\n $(\".game3\").remove();\n // opens the same dialog after 5 seconds\n setTimeout(thirdTextGame, 5000);\n },\n closeOnEscape: false,\n title: \"The Second Layer - Restoration (3)\"\n });\n\n}", "function awakenFromDream() {\n\n // remove remnants of part 3 dialogs\n $('.question3').remove();\n $('.question4').remove();\n\n // append the new div tag to the body\n $('body').append(\"<div class = 'awakenPrompt'><div>\");\n\n // set the contents of the dialog box\n $('.awakenPrompt').html(\"You have completely restored yourself and remember your place in the world. Whether or not you can put your doubts behind you can wait another day. For now, you can [Awaken] from your bitter dreams and banish the abyss.\");\n\n // variables for randomizing location of dialog boxes\n let horizontalOffset = Math.floor(Math.random() * 201) - 100;\n let verticalOffset = Math.floor(Math.random() * 401) - 200;\n\n // annyang functionality, simple this time\n if (annyang) {\n var commands = {\n 'awaken': function() {\n // set the project to its final state after 3 seconds\n setTimeout(endingFunction, 3000);\n responsiveVoice.speak(\"You acknowledge yourself. Forward us the only way.\", 'UK English Male');\n console.log('annyang working');\n doorSFX.play();\n }\n }\n // annyang functionality\n annyang.addCommands(commands);\n annyang.start();\n }\n\n// create the dialog box with all its parameters\n $(\".awakenPrompt\").dialog({\n\n position: {\n my: `center`+ verticalOffset,\n at: `center`+ horizontalOffset\n },\n height: 380,\n width: 550,\n close: function() {\n responsiveVoice.speak(\"You must wake up. The nightmare is over.\", 'UK English Male', options);\n $(\".question4\").remove();\n setTimeout(awakenFromDream, 5000);\n },\n closeOnEscape: false,\n title: \"The Third Layer - Resurgeance (3)\"\n });\n}", "function showDialog(){\n debug('Action');\n\n master.show(new Array({name: \"Child\", data:childrenList},\n {name: \"Action\", data:actions},\n {name: 'Shape', data:iceCreamShapes},\n {name: 'Taste', data:iceCreamTastes})\n , onComplete);\n\n document.getElementById('content').style.display = 'none';\n master._container.style.display = 'block';\n}", "function ghostChoice() {\n choiceDialog(1, 1, elsaDialog, 16000);\n}", "showAddExerciseDialog()\n {\n this.addDialog.MaterialDialog.show();\n this.addExerciseName.focus();\n }", "function playFirstSong() {\n\tsetTrack(tempPlaylist[0], tempPlaylist, true);\n}", "function fingerChoice() {\n choiceDialog(0, 0, ghostDialog, 14000);\n}", "showDialog(selectedObject) {\n\n\t\t// Create dialog\n\t\tvar window = this.createDialog(selectedObject)\n\t\tvar alert = window[0]\n\n\t\t// Show dialog window and store the 'response' in a variable\n\t\tvar response = alert.runModal()\n\n\t\t// Get user input and store it in selected object\n\t\tthis.storeDialogInput(response, selectedObject)\n\t}", "function Dialog() {}", "function elsaDialog() {\n scenarioDialog(3, \"Maybe I should give them a break…\", elsaChoice);\n}", "function bcms_promptDirectToSpeedGrader() {\r\n let link = $(\"#assignment-speedgrader-link a\");\r\n if ( !link.length ) return; //return if we're not on an assignment.\r\n \r\n // link.attr('target', '_self'); //target = self, not blank.\r\n let prompt = $('<div id=\"dialog-directToSpeedGrader\" title=\"Open the Speed Grader?\">\\\r\n <p><span class=\"ui-icon ui-icon-extlink\" style=\"float:left; margin:0 0 20px 0;\"></span>Open the assessment screen (i.e., Speed Grader)?</p>\\\r\n </div>');\r\n setTimeout( () => {\r\n prompt.dialog({\r\n resizable: false,\r\n height: \"auto\",\r\n width: 400,\r\n modal: true,\r\n buttons: {\r\n \"Open Assessment\": function() {\r\n $( this ).dialog( \"close\" );\r\n link[0].click();\r\n },\r\n Cancel: function() {\r\n $( this ).dialog( \"close\" );\r\n }\r\n }\r\n });\r\n }, 250)\r\n}", "function initFlashcards(){\n\tinquirer.prompt(initialPrompt).then(function(answers){\n\t\tif(answers.quizOrCreate === 'Create New'){\n\t\t\t//creating flash cards\n\t\t\tinquirer.prompt(flashcardTypeQuestion).then(function(answers){\n\t\t\t\tif (answers.cardType === 'Basic'){\n\t\t\t\t\tcreateBasicQuestion();\n\t\t\t\t} else {\n\t\t\t\t\tcreateClozeQuestion();\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\t//prompts for user input on which type of card they want to quiz on and then executes corresponding quiz \n\t\t\tinquirer.prompt(secondPrompt).then(function(answers){\n\t\t\t\tif(answers.basicOrCloze === 'Basic'){\n\t\t\t\t\texecuteQuiz(\"basicQuestions.json\");\n\t\t\t\t} else {\n\t\t\t\t\texecuteQuiz(\"clozeQuestions.json\");\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n}", "function showSetupDialog() {\n openDialog('/html/setup.html', 500, 660);\n}", "function generalTutorialDialog(name, title, message, width, height) {\n var dialogOptions,\n dialog;\n\n // check if the dialog has already been created\n if (dialog = checkDialogManager(name)) {\n return dialog;\n }\n\n dialogOptions = new GeoJQueryUiWrappers.DialogOptions();\n\n //set up options\n setGenericOptions(dialogOptions);\n setSpecificOptions(dialogOptions, name, title, message, width, height);\n\n //set up contents\n setDialogContents(dialogOptions, classNames.Tutorial, message);\n\n dialogOptions.Type = GeoJQueryUiWrappers.DialogTypes.Tutorial;\n dialog = GeoJQueryUiWrappers.CreateDialog(dialogOptions);\n\n saveDialog(dialog);\n return dialog;\n }", "function showOpenSeed (opts) {\n setTitle(opts.title)\n const selectedPaths = dialog.showOpenDialogSync(windows.main.win, opts)\n resetTitle()\n if (!Array.isArray(selectedPaths)) return\n windows.main.dispatch('showCreateTorrent', selectedPaths)\n}", "_getYesNoDialog(yesEvent, noEvent, header) {\n return new StepDialog(/*actions=*/[\n {\n socketEvent: yesEvent,\n text: LocalizedStrings.YES\n },\n {\n socketEvent: noEvent,\n text: LocalizedStrings.NO\n }],\n /*timeoutFunc=*/undefined,\n /*timeoutMs*/undefined,\n /*header=*/header);\n }", "function openModalNewResponsableMedicion() {\n\tabrirCerrarModal(\"modalAsignaPersonas\");\n\tsetFirstInput();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
answerCanvas is an array which stores one or more canvases that the user will draw an answer on questionCanvas is an array which stores one or more canvases which have a predrawn shape rotationCanvas is an array which stores a rotation canvas with rotation instructions
function Question() { this.answerCanvas = []; this.questionCanvas = []; this.rotationCanvas = []; }
[ "setupCanvas(width, height, rectMargin, rulerSize) {\n\t\tthis.canvas.width = width\n\t\tthis.canvas.height = height\n\t\tthis.rectMargin = rectMargin\n\t\tthis.rulerSize = rulerSize\n\t\tthis.rectArea = {\n\t\t\t'width':this.canvas.width - rulerSize - rectMargin,\n\t\t\t'height':this.canvas.height - rulerSize - rectMargin\n\t\t}\n\t}", "function renderTextInput() {\n canvas.removeEventListener('click', submitCLickListener, false);\n textInput = new CanvasInput({\n canvas: canvas,\n fontSize: 18,\n fontFamily: 'Arial',\n fontColor: '#212121',\n fontWeight: 'bold',\n width: 350,\n height: 30,\n padding: 8,\n borderWidth: 1,\n borderColor: '#000',\n borderRadius: 3,\n boxShadow: '1px 1px 0px #fff',\n innerShadow: '0px 0px 5px rgba(0, 0, 0, 0.5)',\n value: \"\",\n x: canvas.width / 3,\n y: (canvas.height / 2) + 15\n });\n\n textInput.render();\n textInput.focus();\n\n answers.forEach(function (answer) {\n try {\n var t = currentQuestion[answer.number];\n answer.text = t;\n }\n catch (err) {\n\n }\n });\n\n //Draw Submit button\n ctx.fillStyle = submitButton.colour;\n ctx.fillRect(submitButton.left, submitButton.top, submitButton.width, submitButton.height);\n ctx.font = \"24px cymraeg\";\n ctx.textAlign = \"center\";\n ctx.textBaseline = \"top\";\n ctx.fillStyle = submitButton.text_color;\n ctx.fillText(\"Submit\", submitButton.left + 100 / 2, submitButton.top + 5);\n //Add click listener for submit button\n canvas.addEventListener('click', submitCLickListener, false);\n\n}", "function startQuestions() {\n addQuestion('dragarea', 'fa'); \n addQuestion('dragarea', 'sa');\n addQuestion('dragarea', 'tf');\n addQuestion('dragarea', 'fb');\n addQuestion('dragarea', 'mc');\n addQuestion('dragarea', 'img');\n addQuestion('dragarea', 'txt');\n}", "function createSpeakers(){\r\n drawCtx.strokeStyle = \"gray\";\r\n drawCtx.fillStyle = \"black\";\r\n\r\n drawCtx.lineWidth = 5;\r\n\r\n drawCtx.fillRect(50,100, 100,200);\r\n drawCtx.strokeRect(50,100, 100,200);\r\n drawCtx.strokeRect(50,100, 100,50);\r\n\r\n drawCtx.lineWidth = 3;\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(50,100);\r\n drawCtx.lineTo(80,75);\r\n drawCtx.lineTo(180, 75);\r\n drawCtx.lineTo(150,100);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(150,100);\r\n drawCtx.lineTo(180,75);\r\n drawCtx.lineTo(180,275);\r\n drawCtx.lineTo(150, 300);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n \r\n drawCtx.lineWidth = 5;\r\n \r\n drawCtx.fillRect(450,100, 100,200);\r\n drawCtx.strokeRect(450,100, 100,200);\r\n drawCtx.strokeRect(450,100, 100,50);\r\n\r\n drawCtx.lineWidth = 3;\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(550,100);\r\n drawCtx.lineTo(520,75);\r\n drawCtx.lineTo(420, 75);\r\n drawCtx.lineTo(450,100);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(450,100);\r\n drawCtx.lineTo(420,75);\r\n drawCtx.lineTo(420,275);\r\n drawCtx.lineTo(450, 300);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n \r\n drawCtx.lineWidth = 5;\r\n \r\n drawCtx.fillRect(237,85, 125,225);\r\n drawCtx.strokeRect(237,85, 125,225);\r\n drawCtx.strokeRect(237,85, 125,50);\r\n \r\n \r\n drawCtx.lineWidth = 3;\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(237,85);\r\n drawCtx.lineTo(260,55);\r\n drawCtx.lineTo(340, 55);\r\n drawCtx.lineTo(362,85);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n\r\n \r\n}", "function setupCorralCanvas() {\n // Set up the canvas.\n corralWidth = $(\"#corral-canvas-wrapper\").width();\n corralHeight = $(\"#corral-canvas-wrapper\").height();\n corralCanvas = document.getElementById(\"corral-canvas\");\n corralCanvas.width = corralWidth;\n corralCanvas.height = corralHeight;\n\n // Set up the canvas context.\n ctx = corralCanvas.getContext(\"2d\");\n ctx.lineWidth = 12;\n ctx.strokeStyle = \"black\";\n\n // Set the size of corral shapes.\n corralDim = 80;\n\n // Create a place to store click box coordinates.\n boxes = [];\n\n // Set the shape attributes.\n shapeAttributes = [\n [true, \"red\", 1, 1],\n [true, \"blue\", 1, 0.5],\n [true, \"yellow\", 0.5, 1,],\n [false, \"pink\", 0.5, 1],\n [false, \"green\", 1, 0.5],\n [false, \"orange\", 1, 1,]\n ]\n\n // Start with the normal shape colors.\n shapesWhite = false;\n}", "function setNextQuestion() {\n nextButton.classList.add(\"hide\")\n emptyDivEl.innerHTML = \"\"\n if (currentQuestionIndex === 0) {\n questionElement.innerText = questions[0].question;\n btn1El.innerText = questions[0].answers[0].text;\n btn1El.addEventListener(\"click\" , rightAnswer);\n btn2El.innerText = questions[0].answers[1].text;\n btn2El.addEventListener(\"click\" , rightAnswer);\n btn3El.innerText = questions[0].answers[2].text;\n btn3El.addEventListener(\"click\" , rightAnswer);\n btn4El.innerText = questions[0].answers[3].text;\n btn4El.addEventListener(\"click\" , wrongAnswer);\n } else if (currentQuestionIndex === 1) {\n questionElement.innerText = questions[1].question;\n btn1El.innerText = questions[1].answers[0].text;\n btn1El.addEventListener(\"click\" , rightAnswer);\n btn2El.innerText = questions[1].answers[1].text;\n btn2El.addEventListener(\"click\" , rightAnswer);\n btn3El.innerText = questions[1].answers[2].text;\n btn3El.removeEventListener(\"click\" , rightAnswer);\n btn3El.addEventListener(\"click\" , wrongAnswer);\n btn4El.innerText = questions[1].answers[3].text;\n btn4El.removeEventListener(\"click\" , wrongAnswer);\n btn4El.addEventListener(\"click\" , rightAnswer);\n } else if (currentQuestionIndex === 2) {\n questionElement.innerText = questions[2].question;\n btn1El.innerText = questions[2].answers[0].text;\n btn1El.addEventListener(\"click\" , rightAnswer);\n btn2El.innerText = questions[2].answers[1].text;\n btn2El.addEventListener(\"click\" , rightAnswer);\n btn3El.innerText = questions[2].answers[2].text;\n btn3El.removeEventListener(\"click\" , wrongAnswer);\n btn3El.addEventListener(\"click\" , rightAnswer);\n btn4El.innerText = questions[2].answers[3].text;\n btn4El.removeEventListener(\"click\" , rightAnswer);\n btn4El.addEventListener(\"click\" , wrongAnswer);\n } else if (currentQuestionIndex === 3) {\n questionElement.innerText = questions[3].question;\n btn1El.innerText = questions[3].answers[0].text;\n btn1El.removeEventListener(\"click\" , rightAnswer);\n btn1El.addEventListener(\"click\" , wrongAnswer);\n btn2El.innerText = questions[3].answers[1].text;\n btn2El.addEventListener(\"click\" , rightAnswer);\n btn3El.innerText = questions[3].answers[2].text;\n btn3El.addEventListener(\"click\" , rightAnswer);\n btn4El.innerText = questions[3].answers[3].text;\n btn4El.removeEventListener(\"click\" , wrongAnswer);\n btn4El.addEventListener(\"click\" , rightAnswer);\n } else if (currentQuestionIndex > 3) {\n gameOver();\n }\n}", "function drawSound(){\r\n\t//drawCtx.clearRect(0, 0, drawCtx.canvas.width, drawCtx.canvas.height);\r\n\tlet circleWidth = 1;\r\n\tlet circleSpacing = 17.5;\r\n\tlet topSpacing = 130;\r\n\r\n\tlet currentHeight;\r\n\r\n\tfor(let i=0; i<audioData.length;i++){\r\n\t\tif (playButton.dataset.playing == \"yes\") currentHeight = (topSpacing-60) + 256-audioData[i];\r\n\t\telse if (currentHeight < (canvasElement.height - 65)) currentHeight + 5;\r\n\t\telse currentHeight = canvasElement.height - 65;\r\n\t\tdrawCtx.save();\r\n\t\tdrawCtx.beginPath();\r\n\t\tdrawCtx.fillStyle = drawCtx.strokeStyle = makeColor(color.red, color.green, color.blue, color.alpha);\r\n\r\n\t\t// draw appropriete shape\r\n\t\tif(circle){\r\n\t\t\tdrawCtx.arc(i * (circleWidth + circleSpacing),currentHeight + 60, 5, 0, Math.PI * 2, false);\r\n\t\t\tdrawCtx.arc(i * (circleWidth + circleSpacing),currentHeight+30, 5, 0, Math.PI * 2, false);\r\n\t\t\tdrawCtx.arc(i * (circleWidth + circleSpacing),currentHeight, 5, 0, Math.PI * 2, false);\r\n\t\t}\r\n\t\telse if(triangle){\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight + 60);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) - 5,currentHeight + 60 - 10);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) + 5,currentHeight + 60 - 10);\r\n\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight+30);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) - 5,currentHeight+30 - 10);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) + 5,currentHeight+30 - 10);\r\n\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),(currentHeight));\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) - 5,currentHeight - 10);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing) + 5,currentHeight - 10);\r\n\t\t}\r\n\t\telse if(square){\r\n\t\t\tdrawCtx.rect(i * (circleWidth + circleSpacing),currentHeight + 60, 5, 5);\r\n\t\t\tdrawCtx.rect(i * (circleWidth + circleSpacing),currentHeight+30, 5, 5);\r\n\t\t\tdrawCtx.rect(i * (circleWidth + circleSpacing),currentHeight, 5, 5);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight + 60);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing),currentHeight + 70);\r\n\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight+30);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing),currentHeight+40);\r\n\r\n\t\t\tdrawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight);\r\n\t\t\tdrawCtx.lineTo(i * (circleWidth + circleSpacing),currentHeight + 10);\r\n\r\n\t\t\tdrawCtx.stroke();\r\n\t\t}\r\n\t\tdrawCtx.closePath();\r\n\t\tdrawCtx.fill();\r\n\t\tdrawCtx.restore();\r\n\t}\r\n}", "function showCanvas() {\n destroyCanvas();\n if (languageValue === \"\" || phoneValue === \"\") {\n console.log(\"naaaaah, les filtres sont pas remplis!\")\n } else {\n console.log(\"way to go, bro! On crée les canvas!\")\n createCanvas();\n }\n}", "function createPitch() {\n ctx.beginPath();\n ctx.moveTo(boardWidth/2,0);\n ctx.lineTo(boardWidth/2,boardHeight);\n ctx.closePath();\n ctx.lineWidth = 8;\n ctx.strokeStyle = \"white\";\n ctx.stroke();\n\n ctx.beginPath();\n ctx.arc(boardWidth/2,boardHeight/2,2*step,0,Math.PI*2,true);\n ctx.stroke();\n \n function goalArea(x0,x1){\n ctx.beginPath();\n ctx.moveTo(x0,boardHeight/2-2*step);\n ctx.lineTo(x1,boardHeight/2-2*step);\n ctx.lineTo(x1,boardHeight/2+2*step);\n ctx.lineTo(x0,boardHeight/2+2*step);\n ctx.stroke();\n }\n\n goalArea(0,2*step)\n goalArea(boardWidth,boardWidth-2*step)\n\n function goalLine(x0,color){\n ctx.beginPath();\n ctx.moveTo(x0,boardHeight/2);\n ctx.lineTo(x0,boardHeight/2-step);\n ctx.lineTo(x0,boardHeight/2+step);\n ctx.strokeStyle = color;\n ctx.stroke();\n }\n\n goalLine(0,\"green\");\n goalLine(boardWidth,\"red\");\n\n function corners(x0,y0,direction){\n ctx.beginPath();\n ctx.arc(x0,y0,step/2,0,Math.PI*0.5,direction);\n ctx.strokeStyle = \"white\";\n ctx.stroke();\n }\n \n corners(0,0,false)\n corners(boardWidth,0,true)\n corners(0,boardHeight,true)\n corners(boardWidth,boardHeight,true)\n\n function semicircle(x0,direction){\n ctx.beginPath();\n ctx.arc(x0,boardHeight/2,step,Math.PI*0.5,Math.PI*1.5,direction);\n ctx.stroke();\n }\n \n semicircle(2*step,true)\n semicircle(boardWidth-2*step,false)\n }", "function peace(drawCtx,playButton,audioData,speaker,speaker2,disc,canvasElement){\n\t\t\tdrawCtx.save();\n\t\t\tdrawCtx.drawImage(speaker, 10,60,150,100);\n\t\t\tdrawCtx.drawImage(speaker2, canvasElement.width-165,60,150,100);\n\t\t\tlet xPos = 400;\n\t\t\tlet yPos = 400;\n\t\t\tfor(let i = 0; i < 7; i++){ // draw symbols from speakers\n\t\t\t\tdrawCtx.scale(.7,.7);\n\t\t\t\tif(i!=0 && i!=1&&playButton.dataset.playing == \"yes\"){\n\t\t\t\t\tlet moveX1 = audioData[10];\n\t\t\t\t\tdrawCtx.drawImage(disc, xPos, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==2)drawCtx.drawImage(disc, canvasElement.width+900, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==3)drawCtx.drawImage(disc, canvasElement.width+1800, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==4)drawCtx.drawImage(disc, canvasElement.width+3100, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==5)drawCtx.drawImage(disc, canvasElement.width+5000, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==6)drawCtx.drawImage(disc, canvasElement.width+7700, yPos,moveX1,moveX1);\n\t\t\t\t}\n\t\t\t\txPos+=100;\n\t\t\t\tyPos+=150;\n\n\t\t\t\t\n\t\t\t}\n\t\t\tdrawCtx.restore();\n\t\t}", "function initAnswer()\n\t{\n\t\tif (!layout.ansInput)\n\t\t\treturn;\n\n\t\tdrawList.setParam('answerInput', 'type', layout.qType);\n\n\t\tif (layout.qType === 'multi')\n\t\t\tdrawList.setParam('answerInput', 'text', problem.get('a'));\n\t\telse if (layout.qType === 'radio' || layout.qType === 'check')\n\t\t\tdrawList.setParam('answerInput', 'choices', problem.get('choices'));\n\t\telse if (layout.qType === 'graphPlot' || layout.qType === 'graphConst')\n\t\t{\n\t\t\tdrawList.setParam('answerInput', 'eq', problem.get('graphequations'));\n\t\t\tdrawList.setParam('answerInput', 'axis', problem.get('graphparms'));\n\t\t}\n\t\telse if (layout.qType === 'equation')\n\t\t{\n\t\t\tdrawList.setParam('answerInput', 'pre', problem.get('ansPrefix'));\n\t\t\tdrawList.setParam('answerInput', 'post', problem.get('ansSuffix'));\n\t\t}\n\t}", "function draw2Dkeyboard()\n{\n imageMode(CORNER);\n image(keyboard, width/2 - 2.0*PPCM, height/2 - 1.0*PPCM, 4.0*PPCM, 3.0*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"S\" , width/2 - 1.32*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"Q\" , width/2 - 1.74*PPCM, height/2 + 0.10*PPCM);\n text(\"W\" , width/2 - 1.32*PPCM, height/2 + 0.10*PPCM);\n text(\"E\" , width/2 - 0.89*PPCM, height/2 + 0.10*PPCM);\n text(\"A\" , width/2 - 1.74*PPCM, height/2 + 0.60*PPCM);\n text(\"D\" , width/2 - 0.89*PPCM, height/2 + 0.60*PPCM);\n text(\"Z\" , width/2 - 1.74*PPCM, height/2 + 1.08*PPCM);\n text(\"X\" , width/2 - 1.32*PPCM, height/2 + 1.08*PPCM);\n text(\"C\" , width/2 - 0.89*PPCM, height/2 + 1.08*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"G\" , width/2 + 0.0*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"R\" , width/2 - 0.42*PPCM, height/2 + 0.10*PPCM);\n text(\"T\" , width/2 - 0*PPCM, height/2 + 0.10*PPCM);\n text(\"Y\" , width/2 + 0.42*PPCM, height/2 + 0.10*PPCM);\n text(\"H\" , width/2 + 0.42*PPCM, height/2 + 0.60*PPCM);\n text(\"F\" , width/2 - 0.44*PPCM, height/2 + 0.60*PPCM);\n text(\"V\" , width/2 - 0.42*PPCM, height/2 + 1.08*PPCM);\n text(\"B\" , width/2 - 0*PPCM, height/2 + 1.08*PPCM);\n text(\"N\" , width/2 + 0.42*PPCM, height/2 + 1.08*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"K\" , width/2 + 1.30*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"U\" , width/2 + 0.88*PPCM, height/2 + 0.10*PPCM);\n text(\"I\" , width/2 + 1.30*PPCM, height/2 + 0.10*PPCM);\n text(\"O\" , width/2 + 1.72*PPCM, height/2 + 0.10*PPCM);\n text(\"J\" , width/2 + 0.88*PPCM, height/2 + 0.60*PPCM);\n text(\"P\" , width/2 + 1.72*PPCM, height/2 + 0.60*PPCM);\n text(\"M\" , width/2 + 0.88*PPCM, height/2 + 1.08*PPCM);\n text(\"L\" , width/2 + 1.72*PPCM, height/2 + 1.08*PPCM);\n}", "function updateCanvasVariables() {\n poemCanvasLeft = poemCanvas.x-poemCanvas.w/2;\n poemCanvasRight = poemCanvasLeft+poemCanvas.w;\n poemCanvasTop = poemCanvas.y-poemCanvas.h/2;\n poemCanvasBottom = poemCanvasTop+poemCanvas.h;\n}", "function create_matrix(index, global_mode,global_rotation,shapes_tx,shapes_ty,shapes_rotation,shapes_scale){\n var mvMatrix = mat4.create(); // this is the matrix for transforming each shape before draw\n //set into an identity matrix (after create you don't know if there's junk in it)\n // set identity - fresh matrix\n mat4.identity(mvMatrix); \n if(global_mode[index]){\n for(var j = 0; j < global_rotation[index].length; j++){\n mat4.rotate(mvMatrix,degToRad(global_rotation[index][j]),[0,0,1]);\n } \n var scale = [1,1,1];\n scale[0] = scale[1] = scale[2] = global_scale;\n // finish consruct matrix here but haven't set it\n mvMatrix = mat4.scale(mvMatrix, scale);\n }\n var trans = [0,0,0];\n trans[0] = shapes_tx[index]; \n trans[1] = shapes_ty[index];\n trans[2] = 0.0;\n //translate is multiplied to the right side of the mvMatrix \n mvMatrix = mat4.translate(mvMatrix, trans); // move from origin to mouse click\n //2d x-y in 3d x-z rotate around z\n // only accept radian, not degree. so we use degToRad\n mvMatrix = mat4.rotate(mvMatrix, degToRad(shapes_rotation[index]), [0, 0, 1]); // rotate if any \n var scale = [1,1,1];\n scale[0] = scale[1] = scale[2] = shapes_scale[index];\n // finish consruct matrix here but haven't set it\n mvMatrix = mat4.scale(mvMatrix, scale); // scale if any \n //var mvMatrix1 = mat4.inverse(mvMatrix);\n //mvMatrix = mat4.multiply(mvMatrix1,mvMatrix);\n return mvMatrix;\n}", "function BuildQuiz() {\n // Initialize the variables and setup the elements\n var quizContainerElement = document.getElementById('quizContainer');\n var quizContainerHTML = \"\";\n var translationsContainer = document.getElementById('translationsContainer');\n var questions = [];\n var successfulBuild = \"\";\n var previousBtnVisibility = \"visible\";\n var nextBtnVisibility = \"visible\";\n var gradeQuizBtnDisplay = \"none\";\n\n // Call the function to get the Quiz Questions (translations)\n questions = PopulateQuestionArray();\n\n // Call the functions to hide the translations table and show the quizes container\n ToggleContainerDisplay(\"translationsContainer\", \"hide\", \"display\");\n ToggleContainerDisplay(\"quizContainer\", \"show\", \"display\");\n\n // Verify that the previous step has been completed, upon successful completion, this will help provide success or failure messages of the build\n if(translationsContainer.style.display === \"none\" && quizContainerElement.style.display === \"block\") { \n\n // For loop that builds the <section> tags and HTML within the questionContainer, populates the questions within the fields, and displays the appropriate navigation buttons.\n for (var questionCounter = 1; questionCounter <= questions.length; questionCounter++) {\n quizContainerHTML += \" <section id=\\\"question\" + questionCounter + \"\\\" class=\\\"questionContainer\\\">\\n <p class=\\\"questionContainerNumber\\\">Question \" + (questionCounter) + \"</p>\\n <p id=\\\"translationQuestion\\\" class=\\\"translationQuestion\\\">\" + questions[questionCounter-1] + \"</p>\\n\";\n \n // Determine if the previous button should be displayed or not\n previousBtnVisibility = (questionCounter > 1) ? \"visible\" : \"hidden\";\n // Previous Button\n quizContainerHTML += \" <button id=\\\"previousBtn\\\" name=\\\"previousBtn\\\" onclick=\\\"ToggleContainerDisplay(\\'question\" + (questionCounter - 1) + \"\\',\\'show\\',\\'display\\'); ToggleContainerDisplay(\\'question\" + questionCounter + \"\\',\\'hide\\',\\'display\\'); SetFocus(\\'userAnswer\" + (questionCounter - 1) + \"\\'); SetDotStyle(\" + questionCounter + \"); SetSelectedDot(\" + (questionCounter - 1) + \",\" + questions.length + \");\\\" style=\\\"visibility: \" + previousBtnVisibility + \";\\\">Previous</button>\";\n\n quizContainerHTML += \" <input type=\\\"text\\\" id=\\\"userAnswer\" + questionCounter + \"\\\" placeholder=\\\"Enter your answer here\\\" autocomplete=\\\"off\\\">\";\n\n // Determine if the next button should be displayed or not\n nextBtnVisibility = (questionCounter < questions.length) ? \"visible\" : \"hidden\";\n\n // Set the 2nd from last question's NEXT button to also show the Quiz button for the last question.\n gradeQuizBtnDisplay = (questionCounter === questions.length-1) ? \" ToggleContainerDisplay(\\'gradeQuizBtn\\',\\'show\\',\\'display\\');\" : \"\";\n \n // Next Button\n quizContainerHTML += \" <button id=\\\"nextBtn\\\" name=\\\"nextBtn\\\" onclick=\\\"ToggleContainerDisplay(\\'question\" + (questionCounter + 1) + \"\\',\\'show\\',\\'display\\'); ToggleContainerDisplay(\\'question\" + questionCounter + \"\\',\\'hide\\',\\'display\\'); SetFocus(\\'userAnswer\" + (questionCounter + 1) + \"\\'); SetDotStyle(\" + questionCounter + \"); SetSelectedDot(\" + (questionCounter + 1) + \",\" + questions.length + \");\" + gradeQuizBtnDisplay + \"\\\" style=\\\"visibility: \" + nextBtnVisibility + \";\\\">Next</button>\";\n\n quizContainerHTML += \" </section>\";\n }\n\n // Create question dot placement for each question displaying 1 to 10, but adjusted to show the appropriate array item\n for (var i = 1; i <= questions.length; i++){\n quizContainerHTML += \"<span id=\\\"dot\" + i + \"\\\" class=\\\"emptyDot\\\" style=\\\"display: inline-block;\\\">\" + i + \"</span>\"; \n } \n\n // Display Dot Legend\n quizContainerHTML += \"<span class=\\\"legendBox\\\"><span class=\\\"emptyDot\\\" style=\\\"display: inline-block; border: 1px solid #FF0000;\\\"></span> = Nothing Entered <span class=\\\"emptyDot filledDot\\\" style=\\\"display: inline-block; margin-left: 20px;\\\"></span> = Has Entry <span class=\\\"emptyDot selectedDot\\\" style=\\\"display: inline-block; margin-left: 20px;\\\"></span> = Selected Question</span>\";\n\n // Create the submit quiz button to display the results\n quizContainerHTML += \" <button id=\\\"gradeQuizBtn\\\" name=\\\"submitBtn\\\" onclick=\\\"GradeQuiz();\\\" style=\\\"display: none;\\\">Grade Quiz</button>\";\n\n // Takes the above HTML string and inserts it after the current quizContainer element.\n quizContainerElement.innerHTML += quizContainerHTML;\n successfulBuild = \"Yes\";\n } else {\n successfulBuild = \"No\";\n }\n\n\n // Display the appropriate response if the quiz build was successful or not.\n if (successfulBuild === \"Yes\") {\n ToggleContainerDisplay(\"question1\",\"show\",\"display\");\n SetFocus(\"userAnswer1\");\n SetSelectedDot(1,questions.length);\n //document.getElementById(\"dot1\").style.border = \"15px solid black\";\n } else if (successfulBuild === \"No\") {\n alert(\"We're sorry, the correct sections have not been displayed properly. Please try again later.\");\n } else {\n alert(\"We're sorry, there was an error building your quiz at this time. Please try again later.\");\n }\n\n}", "initCanvas() {\n // Create new canvas object.\n this._canvasContainer = document.getElementById(this._canvasId);\n if (!this._canvasContainer)\n throw new Error(`Canvas \"${this._canvasId}\" not found`);\n // Get rendering context.\n this._canvas = this._canvasContainer.getContext('2d');\n // Register canvas interaction event handlers.\n this._canvasContainer.addEventListener('mousedown', (event) => this.canvasMouseDown(event));\n this._canvasContainer.addEventListener('mouseup', (event) => this.canvasMouseUp(event));\n this._canvasContainer.addEventListener('mousemove', (event) => this.canvasMouseMove(event));\n this._canvasContainer.addEventListener('wheel', (event) => this.canvasScrollWheel(event));\n // Get width and height of canvas.\n this._canvasWidth = this._canvasContainer.width;\n this._canvasHeight = this._canvasContainer.height;\n }", "draw () {\r\n this.icon.x = this.x\r\n this.icon.y = this.y\r\n const canvas = document.getElementById('editor')\r\n const ctx = canvas.getContext('2d')\r\n const button = new Path2D()\r\n // ctx.moveTo(this.x,this.y)\r\n button.moveTo(this.x, this.y + 10)\r\n button.lineTo(this.x, this.y + this.size - 10)\r\n button.quadraticCurveTo(this.x, this.y + this.size, this.x + 10, this.y + this.size)\r\n button.lineTo(this.x + this.size - 10, this.y + this.size)\r\n button.quadraticCurveTo(this.x + this.size, this.y + this.size, this.x + this.size, this.y + this.size - 10)\r\n button.lineTo(this.x + this.size, this.y + 10)\r\n button.quadraticCurveTo(this.x + this.size, this.y, this.x + this.size - 10, this.y)\r\n button.lineTo(this.x + 10, this.y)\r\n button.quadraticCurveTo(this.x, this.y, this.x, this.y + 10)\r\n if (this.ischosen !== true) {\r\n ctx.fillstyle = this.chosen()\r\n ctx.fill(button)\r\n ctx.save()\r\n ctx.translate(3, 3)\r\n const shadow = new Path2D(button)\r\n ctx.fillStyle = '#1d232f'\r\n ctx.fill(shadow)\r\n ctx.restore()\r\n ctx.fillStyle = this.chosen()\r\n ctx.fill(button)\r\n this.icon.draw()\r\n } else {\r\n ctx.save()\r\n ctx.translate(2, 2)\r\n ctx.fillStyle = this.chosen()\r\n ctx.fill(button)\r\n this.icon.draw()\r\n ctx.restore()\r\n }\r\n }", "function updateView() {\n // Check for Game Over\n if (questionsKeys.length < 1) {\n stop();\n mkInvisible(\"#questionsContainer\");\n setText(\"#correctAnswersCount\", gameInfo.toatlWin);\n setText(\"#wrongAnswersCount\", gameInfo.totalLost);\n setText(\"#noAnswersCount\", gameInfo.notAnswered);\n mkVisible(\"#gameOverContainer\");\n\n return;\n }\n // Get a rand key ussing splice (splice return a Array)\n let _key = questionsKeys.splice(rand(questionsKeys.length), 1);\n // Get randon object from questionsObjects using splice to void erpetitive questions\n let _obj = questionsObjects[_key[0]];\n // Get string question\n let _question = _obj.question;\n // Set the question\n setText(\"#question\", _question);\n // Get the correct_answer (it will be the return of this function)\n correctAnswer = _obj.correct_answer;\n // Add correct_answer to incorrect_answers array to shuffle\n _obj.incorrect_answers.push(correctAnswer);\n // Get all answer buttons\n let _questionButtons = document.querySelector(\"#btnColumn\").children\n // Random place correct and incorrect answer on the buttons\n for (let _btn of _questionButtons) {\n let _question = _obj.incorrect_answers.splice(rand(_obj.incorrect_answers.length), 1)[0];\n _btn.innerHTML = _question;\n }\n // Get Correct answer gif url\n getCorrectAnswerGIF(`right answer ${correctAnswer}`);\n // Get wronganswer git url\n getWrongAnswerGIF();\n // remove gif animation displayGIF\n mkInvisible(\"#displayGIF\");\n // display timerHearder, question and btnColumn\n mkVisible(\"#timerHearder\", \"#question\", \"#btnColumn\");\n // Stop timer\n stop();\n // Reset counter\n // timerCounter = 30;\n timerCounter = 10; ///////////////////////////////////////////////////////////////\n //Start timer and update each 1 second\n startTimer(updateTimer, 1);\n}", "function loadNextQuestion() {\n var questionHeader = document.getElementById(\"question\"); // Will insert questions into this HTML element\n var answerChoices = allQuestions[questionQueue].choices; // Fetching answers\n var questionLegend = document.getElementById(\"qnum\"); // Displays which question the user is currently viewing\n var inputs = document.getElementsByTagName(\"input\"); // To insert questions\n\n questionLegend.innerHTML = \"Question \" + (questionQueue + 1);\n questionHeader.innerHTML = allQuestions[questionQueue].question; // Inserting question text\n\n for(var i = 0, len = answerChoices.length; i < len; i++) {\n label = document.getElementsByTagName(\"label\")[i];\n label.textContent = answerChoices[i];\n document.forms.quiz.elements.answer[i].checked = false; // Ghetto making sure the radio button isn't checked onload!\n }\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
QueryRecordCallback (nID, brRecordInfo , nUserParam);
function QueryRecord(brPath, QueryRecordCallback, nUserParam) { return pixwin.QueryRecord(brPath, QueryRecordCallback, nUserParam); }
[ "function callOnReadyCallback(err, records, onReadyCallback) {\n\tif (onReadyCallback) {\n\t\tif (err) {\n\t\t\tonReadyCallback(err)\n\t\t} else {\n\t\t\tonReadyCallback(null, generateEncodedRecord(records))\n\t\t}\n\t}\n}", "function executeOnPage_Book(){\r\n\tgetCallButton();\r\n\r\n\tloadValues();\r\n\r\n\tgetsCallSelects();\r\n}", "function showRecordEntry(myRId, myCId) {\r\n if (myRId === null || myCId === null) { \r\n return false; \r\n } else {\r\n clearDiv(\"recordView\");\r\n ohp.myRecordingId = myRId;\r\n var myURL = \"RecordingsEntryForm.php?RId=\" + myRId + \"&CId=\" + myCId;\r\n processAjax (myURL, \"recordView\");\r\n setBlockVis(\"recordView\", \"block\");\r\n return true;\r\n }\r\n}", "function AutoCompleteStatementCallbackWrapper(aCallback,\n aDBConnection)\n{\n this._callback = aCallback;\n this._db = aDBConnection;\n}", "function recordsetDialog_displayTestDialog(sbRecordset)\r\n{\r\n if (!sbRecordset.checkData(true))\r\n {\r\n alert(sbRecordset.getErrorMessage());\r\n return;\r\n }\r\n\r\n var theSQL = sbRecordset.getSQLForTest();\r\n if (theSQL)\r\n {\r\n MMDB.showResultset(sbRecordset.getConnectionName(), theSQL);\r\n }\r\n}", "recordReturnActivity(bookId) {\n return bookLibrary.prototype.recordBookReturned(bookId);\n }", "runSoqlQuery()\n {\n this.setSelectedMapping();\n this.setSelectedAction();\n this.callRetrieveRecordsUsingWrapperApex();\n }", "function handleGetBPAccount(billerCorpId, programId, isMsg) {\n /* To show the progress bar */\n showProgressBar();\n\n /* Hold request parameters and values for request parameters */ \n var request = new Object();\n request.userId = eval(getCookie(\"userId\"));\n request.billerCorpAccountId = billerCorpId;\n request.applicationId = applicationId;\n request.locale = getCookie(\"locale\");\n\n var call_bp_get_corp_account = new bp_get_corp_account(request, programId, isMsg);\n call_bp_get_corp_account.call();\n}", "function recordsetDialog_onClickOK(theWindow, sbRecordset)\r\n{\r\n if (!sbRecordset.checkData(false))\r\n {\r\n alert(sbRecordset.getErrorMessage());\r\n }\r\n else\r\n {\r\n dwscripts.setCommandReturnValue(recordsetDialog.UI_ACTION_OK);\r\n theWindow.close();\r\n }\r\n}", "function showUserEntry(myId) {\r\n if (myId === null) { \r\n return false; \r\n } else {\r\n clearDiv(\"recordView\");\r\n var myURL = \"AdminUsersEntryForm.php?U=\" + myId;\r\n processAjax (myURL, \"recordView\");\r\n setBlockVis(\"recordView\", \"block\");\r\n showRecaptcha();\r\n document.getElementById(\"UserName\").focus();\r\n return true;\r\n }\r\n}", "function ADLObjStatus() \r\n{\r\n}", "function GetRecordsNext(){\n CleanTable('available_records_table');\n GetRecords(records.next_page);\n}", "function RetrieveRecord() {\n try {\n var entityName = \"new_organization\"; //Entity Logical Name\n var recordId = \"919F28C4-F9BB-E911-A977-000D3AF04F8C\"; //Guid of the Record\n var columnsToRetrieve = \"$select=new_organizationname, new_noofemployees, new_revenue\"; //Columns to Retrieve\n Xrm.WebApi.retrieveRecord(entityName, recordId, columnsToRetrieve).then(\n function success(result) {\n Xrm.Utility.alertDialog(\"Success\");\n },\n function (error) {\n Xrm.Utility.alertDialog(\"Error\");\n }\n );\n }\n catch (e) {\n Xrm.Utility.alertDialog(e.message);\n }\n}", "function giveBackData(error , data){\n console.log('inside callback function');\n console.log(data+\"\");\n}", "function testAsyncCB(name,i)\n{\n return function (result, e, profile)\n {\n postResults(name,i, result, e, profile);\n };\n}", "function creditUSRowCallback(res){ \n document.getElementById(\"mCreditUSTableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false;\n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditUSTableDiv').innerHTML = res.value.usHTML;\n errorMessage(res.value.message,\"CreditUS\",\"Message\");\n gOldUSCreditAmt = res.value.usAmt;\n gUSCreditEmailUpdated = res.value.usEmail;\n }\n }\n else{\n document.getElementById('mCreditUSTableDiv').innerHTML = \"\";\n errorMessage(\"Error Crediting Transaction\",\"CreditUS\",\"Error\");\n } \n }", "function receiveCallback(data) {\n receiveIANA(data,session);\n }", "function getAllItemsCallback(response){\n\t\n}", "function attachCallback(req, callback) {\n req.onreadystatechange = function () {\n if (req.readyState == 4) {\n callback(req.status, req.statusText, req.responseText);\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executed on GET of page, Iterates through data set, amends: field names to suit FullCalendar tool, formats date, Renders 'book a resource' page with modelled data
function get(req, res) { const resourceId = req.params.resourceId bookingApi.getResourceBookings(resourceId) .then(function (response) { var i; for (i = 0; i < response.data.length; i++) { response.data[i].title = response.data[i]['name']; delete response.data[i].name; delete response.data[i].description; delete response.data[i].id; delete response.data[i].resourceId; } const dates = response.data const jsonDates = JSON.stringify(dates) const d = new Date() const day = d.toLocaleString('en-us', {day: '2-digit'}) const month = d.toLocaleString('en-us', {month: '2-digit'}) const year = d.toLocaleString('en-us', {year: 'numeric'}) res.render('book-a-resource', { title: 'Book a Resource', day: day, month: month, year: year, dates: jsonDates } ) }) .catch(err => console.error(err)) }
[ "function displayData(date, month, year) {\n\tvar category = {};\n\tvar fistDay = new Date(today.getFullYear(), today.getMonth(), 1);\n\tvar lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0); \n\n\tvar groupby = \"startDate\";\n\n\tfor (var i = 0; i < schedule.length; i++) {\n\t\tif (!category[schedule[i][groupby]])\n\t\t\tcategory[schedule[i][groupby]] = [];\n\t\tif (selectedResourceId == schedule[i][\"resourceId\"]\n\t\t\t\t|| (selectedResourceId == undefined \n\t\t\t\t|| selectedResourceId.trim().length == 0))\n\t\tcategory[schedule[i][groupby]].push(schedule[i]);\n\t}\n\n\tfor (key in category) {\n\t\tif (category.hasOwnProperty(key)) {\n\t\t\tvar dateKey = new Date(key);\n\t\t\tif (category[key].length + \"\\n\") {\n\t\t\t\tfor (var i = 0; i < category[key].length; i++) {\n\t\t\t\t\tif (dateKey.getMonth() == month && dateKey.getFullYear() == year) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar startTime = new Date(category[key][i].startDate).getDate();\n\t\t\t\t\t\tvar endTime = new Date(category[key][i].endDate).getDate();\n\t\t\t\t\t\tvar reservationId = date+'0'+category[key][i].reservationId ;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (date >= startTime && date <= endTime) {\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar dataDisplay = '<span id ='+reservationId +'>'\n\t\t\t\t\t\t\t\t\t+ category[key][i].startTime + \": \"\n\t\t\t\t\t\t\t\t\t+ category[key][i].resourceName + \"; \"\n\t\t\t\t\t\t\t\t\t+ category[key][i].userName;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar dataExisting = document.getElementById(date).innerHTML;\n\t\t\t\t\t\t\tdataExisting = dataExisting + dataDisplay;\n\t\t\t\t\t\t\tvar count = 0;\n\t\t\t\t\t\t\tif (userId == category[key][i].userId || isAdmin) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tdocument.getElementById(date).innerHTML = dataExisting + \n\t\t\t\t\t\t\t\t\"<img id='editico' src='/ResourceScheduler/js/delete.png'\" +\n\t\t\t\t\t\t\t\t\" onclick='getIdForDelete(\"+category[key][i].reservationId+\")'>\"+\n\t\t\t\t\t\t\t\t\"<img id='editico' src='/ResourceScheduler/js/icon.png'\" +\n\t\t\t\t\t\t\t\t\"onclick='getData(\"+category[key][i].reservationId+\")'>\" +\n\t\t\t\t\t\t\t\t\"<img id='editico' src='/ResourceScheduler/js/information.png'\" +\n\t\t\t\t\t\t\t\t\"onclick='show(tooltip\"+reservationId+\")'>\" +\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\"<div id='tooltip\"+reservationId+\"' class='tooltip'>Start: \"+category[key][i].startDate+\n\t\t\t\t\t\t\t\t\" \"+category[key][i].startTime+\n\t\t\t\t\t\t\t\t\"<br/>End: \"+category[key][i].endDate+\" \"+category[key][i].endTime+\n\t\t\t\t\t\t\t\t\"<br/>User Name: \"+category[key][i].userName+\n\t\t\t\t\t\t\t\t\"<br/>Resource Name: \"+category[key][i].resourceName+\n\t\t\t\t\t\t\t\t\"</div>\" +\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\"</span><br/>\";\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tdocument.getElementById(reservationId).style.background = '#8DD6C2';\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tdocument.getElementById(date).innerHTML = dataExisting +\n\t\t\t\t\t\t\t\t\t\t\"<img id='editico' src='/ResourceScheduler/js/information.png'\" +\n\t\t\t\t\t\t\t\t\t\t\"onclick='show(tooltip\"+reservationId+\")'>\"+\n\t\t\t\t\t\t\t\t\t\t\"<div id='tooltip\"+reservationId+\"' class='tooltip'>Start: \"+category[key][i].startDate+\n\t\t\t\t\t\t\t\t\t\t\" \"+category[key][i].startTime+\n\t\t\t\t\t\t\t\t\t\t\"<br/>End Time: \"+category[key][i].endDate+\" \"+category[key][i].endTime+\n\t\t\t\t\t\t\t\t\t\t\"<br/>User Name: \"+category[key][i].userName+\n\t\t\t\t\t\t\t\t\t\t\"<br/>Resource Name: \"+category[key][i].resourceName+\n\t\t\t\t\t\t\t\t\t\t\"</div></span><br/>\";\n\t\t\t\t\t\t\t\tdocument.getElementById(reservationId).style.background = '#95C6E8';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "function populateCalPageEvents() {\n upcomingEvents.reverse();\n \n // Builds the array of Weekly Events that will later have the upcoming events pushed into it.\n // Setting the condition number (i <= 10) will change how many weekly events are added\n // to the cal. Special events will still display if they occur after this cut off.\n for (i = 0; i <= 90; i++) {\n\n var calEndDate = new Date();\n var weeklyCalEntry = calEndDate.setDate(calEndDate.getDate() + i);\n var weeklyCalEntryString = new Date(weeklyCalEntry);\n\n if (weeklyCalEntryString.getDay() === 1) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[0].eventName, 'eventDesc' : weeklyEvents[0].eventDesc, 'eventImgWide' : weeklyEvents[0].eventImgWide, 'eventTime' : weeklyEvents[0].eventTime, 'eventLink' : weeklyEvents[0].eventLink});\n }\n /*\n else if (weeklyCalEntryString.getDay() === 4) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[1].eventName, 'eventDesc' : weeklyEvents[1].eventDesc, 'eventImgWide' : weeklyEvents[1].eventImgWide, 'eventTime' : weeklyEvents[1].eventTime, 'eventLink' : weeklyEvents[1].eventLink});\n }\n */\n else if (weeklyCalEntryString.getDay() === 5) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[2].eventName, 'eventDesc' : weeklyEvents[2].eventDesc, 'eventImgWide' : weeklyEvents[2].eventImgWide, 'eventTime' : weeklyEvents[2].eventTime, 'eventLink' : weeklyEvents[2].eventLink});\n }\n\n else if (weeklyCalEntryString.getDay() === 6) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[3].eventName, 'eventDesc' : weeklyEvents[3].eventDesc, 'eventImgWide' : weeklyEvents[3].eventImgWide, 'eventTime' : weeklyEvents[3].eventTime, 'eventLink' : weeklyEvents[3].eventLink});\n }\n }\n\n // Adds upcoming events to the weekly events\n for (i = 0; i <= upcomingEvents.length - 1; i++) {\n calWeeklyEventsList.push(upcomingEvents[i]);\n }\n\n // Sorts the cal events\n calWeeklyEventsList.sort(function(a,b){var c = new Date(a.eventDate); var d = new Date(b.eventDate); return c-d;});\n\n // Pushes Cal events into the cal page\n function buildCal(a) {\n calendarEvents.innerHTML = a;\n }\n\n // Removes Weekly if a special event is set to overide\n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n \n // If a Special Event is set to Override, remove the previous weekly entry\n if (calWeeklyEventsList[i].eventWklOvrd === 1) {\n calWeeklyEventsList.splice(i-1, 1);\n }\n // Else, Do nothing\n else {\n\n }\n }\n\n // Fixes the Special Event Dates for the cal and builds the Event entry. Push to the buildCal function.\n var formatedDate;\n var formatedTime;\n \n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n\n if (calWeeklyEventsList[i].eventTix !== undefined) {\n \n if (calWeeklyEventsList[i].eventTix != 'none') {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}); \n\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-4-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-4-xs\">REQUEST VIP</a><a href=\"' + calWeeklyEventsList[i].eventTix + '\" onclick=\"trackOutboundLink(' + \"'\" + calWeeklyEventsList[i].eventTix + \"'\" + '); return true;\" class=\"col col-4-xs \">BUY TICKETS</a></div></div><br><br>');\n }\n\n else {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">REQUEST VIP</a></div></div><br><br>');\n }\n }\n\n else {\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + calWeeklyEventsList[i].eventDate + ', ' + calWeeklyEventsList[i].eventTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"A image of ' + calWeeklyEventsList[i].eventName + ', a weekly event at the Necto Nightclub in Ann Arbor, Michigan.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">REQUEST VIP</a></div></div><br><br>');\n }\n }\n \n}", "function populateHomePageShortCalEvents() {\n upcomingEvents.reverse();\n \n // Builds the array of Weekly Events that will later have the upcoming events pushed into it.\n // Setting the condition number (i <= 10) will change how many weekly events are added\n // to the cal. Special events will still display if they occur after this cut off.\n for (i = 0; i <= 14; i++) {\n\n var calEndDate = new Date();\n var weeklyCalEntry = calEndDate.setDate(calEndDate.getDate() + i);\n var weeklyCalEntryString = new Date(weeklyCalEntry);\n\n if (weeklyCalEntryString.getDay() === 1) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[0].eventName, 'eventDesc' : '', 'eventImgWide' : weeklyEvents[0].eventImgWide, 'eventTime' : weeklyEvents[0].eventTime, 'eventLink' : weeklyEvents[0].eventLink});\n }\n /*\n else if (weeklyCalEntryString.getDay() === 4) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[1].eventName, 'eventDesc' : weeklyEvents[1].eventDesc, 'eventImgWide' : weeklyEvents[1].eventImgWide, 'eventTime' : weeklyEvents[1].eventTime, 'eventLink' : weeklyEvents[1].eventLink});\n }\n */\n else if (weeklyCalEntryString.getDay() === 5) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[2].eventName, 'eventDesc' : '', 'eventImgWide' : weeklyEvents[2].eventImgWide, 'eventTime' : weeklyEvents[2].eventTime, 'eventLink' : weeklyEvents[2].eventLink});\n }\n\n else if (weeklyCalEntryString.getDay() === 6) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[3].eventName, 'eventDesc' : '', 'eventImgWide' : weeklyEvents[3].eventImgWide, 'eventTime' : weeklyEvents[3].eventTime, 'eventLink' : weeklyEvents[3].eventLink});\n }\n }\n\n // Adds upcoming events to the weekly events\n for (i = 0; i <= upcomingEvents.length - 1; i++) {\n calWeeklyEventsList.push(upcomingEvents[i]);\n }\n\n // Sorts the cal events\n calWeeklyEventsList.sort(function(a,b){var c = new Date(a.eventDate); var d = new Date(b.eventDate); return c-d;});\n\n // Pushes Cal events into the cal page\n function buildCal(a) {\n calendarEvents.innerHTML = a;\n }\n\n // Removes Weekly if a special event is set to overide\n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n \n // If a Special Event is set to Override, remove the previous weekly entry\n if (calWeeklyEventsList[i].eventWklOvrd === 1) {\n calWeeklyEventsList.splice(i-1, 1);\n }\n // Else, Do nothing\n else {\n\n }\n }\n\n // Fixes the Special Event Dates for the cal and builds the Event entry. Push to the buildCal function.\n var formatedDate;\n var formatedTime;\n \n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n\n if (calWeeklyEventsList[i].eventTix !== undefined) {\n \n if (calWeeklyEventsList[i].eventTix != 'none') {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}); \n\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content col col-3-xs\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventArtist + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-4-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-4-xs\">VIP</a><a href=\"' + calWeeklyEventsList[i].eventTix + '\" onclick=\"trackOutboundLink(' + \"'\" + calWeeklyEventsList[i].eventTix + \"'\" + '); return true;\" class=\"col col-4-xs \">TICKETS</a></div></div><br><br>');\n }\n\n else {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content col col-3-xs\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">VIP</a></div></div><br><br>');\n }\n }\n\n else {\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content col col-3-xs\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + calWeeklyEventsList[i].eventDate + ', ' + calWeeklyEventsList[i].eventTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"A image of ' + calWeeklyEventsList[i].eventName + ', a weekly event at the Necto Nightclub in Ann Arbor, Michigan.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">VIP</a></div></div><br><br>');\n }\n }\n \n}", "function glc_render_ICalReader_for_main_edt_with_detail_hour_top(collection, zone, timeInfo) {\n timeInfo = typeof timeInfo !== 'undefined' ? timeInfo : 7;\n var logo = '<img src=\"img/logos/calendar.png\"/>';\n zone.loadImage(\"img/logos/calendar.png\");\n var title = collection.name;\n var tableau = collection.events;\n var time = timeInfo;\n\n var eventsByDays = transform_in_days(tableau);\n var daysSort = Object.keys(eventsByDays).sort();\n\n for (var idays = 0; idays < daysSort.length; idays++) {\n var days = daysSort[idays];\n var sortObjectStart = function(a, b) {\n return (a.start - b.start);\n };\n\n eventsByDays[days][days].sort(sortObjectStart);\n\n var elementsCollec = eventsByDays[days];\n\n var start = elementsCollec['days'][0];\n var elementsArray = elementsCollec[start];\n\n var listDicoElts = new Array();\n\n var date = get_date_from_timestamp(start);\n var eventsNum = 0;\n\n content = \"<div id='ICalReader' class='main_div_zone1'>\";\n\n if (is_same_date(date, get_current_date()))\n content += \"<div class='calendar_dates_multiple_element_hour_top'>Aujourd'hui</div>\";\n else\n content += \"<div class='calendar_dates_multiple_element_hour_top'>\" + date.day + \" \" + date.month + \"</div>\";\n\n content += \"<div class='calendar_edt_events'>\";\n\n for (var indice = 0; indice < elementsArray.length; indice++) {\n var element = elementsArray[indice];\n var dicoElts = {\"logo\": logo, \"title\": title, \"time\": time};\n var descriptionCalendar = element.description.replace(\"\\n\", \"<br/>\");\n\n if (descriptionCalendar.length >= 100) {\n var descriptionEdt = descriptionCalendar.substring(0, 100) + \" ...\";\n } else\n var descriptionEdt = descriptionCalendar;\n\n if (!pastEvent(element)) {\n eventsNum++;\n if ((eventsNum) % 2 == 0) {\n\n if (inProgress(element)) {\n content += \"<div class='calendar_edt_header inProgress'> \";\n content += \"<span class='calendar_edt_hours inProgress'> \" + render_date_edt(element) + \"</span>\";\n }\n else {\n content += \"<div class='calendar_edt_header'> \";\n content += \"<span class='calendar_edt_hours'> \" + render_date_edt(element) + \"</span>\";\n }\n if (element.location)\n content += \" <span class='calendar_edt_location'>\" + element.location.substring(0, 20) + \"</span>\";\n content += \"</div>\";\n if (inProgress(element))\n content += \"<div class='calendar_edt_summary inProgress'> \" + element.summary;\n else\n content += \"<div class='calendar_edt_summary'> \" + element.summary;\n if (element.description)\n content += \"<div class='calendar_edt_description'> \" + descriptionEdt + \"</div>\";\n content += \"</div>\";\n\n content += \"</div>\";\n content += \"</div>\";\n content += \"<div class='smooth'> </div>\";\n var dico = {\"content\": content, \"logo\": logo, \"title\": title, \"time\": time};\n zone.pushInfo(dico);\n content = \"<div id='ICalReader' class='main_div_zone1'>\";\n if (is_same_date(date, get_current_date()))\n content += \"<div class='calendar_dates_multiple_element_hour_top'>Aujourd'hui, \" + date.day + \" \" + date.month + \"</div>\";\n else\n content += \"<div class='calendar_dates_multiple_element_hour_top'>\" + date.day + \" \" + date.month + \"</div>\";\n content += \"<div class='calendar_edt_events'>\";\n } else {\n\n if (inProgress(element)) {\n content += \"<div class='calendar_edt_header inProgress'> \";\n content += \"<span class='calendar_edt_hours inProgress'> \" + render_date_edt(element) + \"</span>\";\n }\n else {\n content += \"<div class='calendar_edt_header'> \";\n content += \"<span class='calendar_edt_hours'> \" + render_date_edt(element) + \"</span>\";\n }\n if (element.location)\n content += \" <span class='calendar_edt_location'>\" + element.location.substring(0, 20) + \"</span>\";\n content += \"</div>\";\n if (inProgress(element))\n content += \"<div class='calendar_edt_summary inProgress'> \" + element.summary;\n else\n content += \"<div class='calendar_edt_summary'> \" + element.summary;\n if (element.description)\n content += \"<div class='calendar_edt_description'> \" + descriptionEdt + \"</div>\";\n content += \"</div>\";\n }\n if (indice + 1 == elementsArray.length) {\n if ((eventsNum) % 2 != 0) {\n content += \"</div>\";\n content += \"</div>\";\n var dico = {\"content\": content, \"logo\": logo, \"title\": title, \"time\": time};\n zone.pushInfo(dico);\n }\n }\n }\n }\n }\n}", "function get_dates()\n {\n var load_dates_resource = $resource('/api/edition_dates');\n load_dates_resource.query({edition: $scope.myedition}, function (data) {\n // success handler\n edition_json=data;\n list_dates = [];\n for (var x in data) {\n list_dates.push(data[x]['date']);\n }\n $scope.dates = list_dates;\n $scope.mydate = $scope.dates[0];\n get_date_json();//load the main page upon login\n\n }, function (error) {\n alert(\"Error \");\n alert(error);\n // error handler\n });\n }", "function fillDates() {\n\t$.getJSON(\n\t\t'/getScheduleByYear',\n\t\tfunction(data) {\n\t\t\tupdateDate(data);\n\t\t\t$('#season').val($('#date option:selected').data('season'));\n\t\t\t$('#week').val($('#date option:selected').data('week'));\n\t\t\tupdateTimes();\n\t\t\tchangeTeams();\n\t\t\tfillTeamPlayers(true);\n\t\t\tfillTeamPlayers(false);\n\n\t\t\tvar query = getURLParam('success');\n\t\t\tif(query != undefined)\n\t\t\t\tpresetDate();\n\t\t}\n\t);\n}", "function renderTable() {date\r\n $tbody.innerHTML = \"\";\r\n for (var i = 0; i < datetime.length; i++) {\r\n // Get get the current datetime object and its fields\r\n var date = datetime[i];\r\n var fields = Object.keys(date)\r\n // Create a new row in the tbody, set the index to be i + startingIndex\r\n var $row = $tbody.insertRow(i);\r\n for (var j = 0; j < fields.length; j++) {\r\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\r\n var field = fields[j];\r\n var $cell = $row.insertCell(j);\r\n $cell.innerText = date[field];\r\n }\r\n }\r\n}", "function initializePage() {\n\t\t$calendar.datepicker(\"setDate\", \"-1d\");\n\t\tvar dateObj = $calendar.datepicker( \"getDate\" );\n\t\tvar options = {month: '2-digit', day: '2-digit', year: 'numeric'};\n\t\tvar date = dateObj.toLocaleDateString('en-US', options);\n\t\tmonth = date.slice(0,2); // parse out month\n\t\tday = date.slice(3,5); // parse out \n\t\tyear = date.slice(6); // parse out year\n\t\t// console.log(date);\n\t\t// console.log(\"month is \" + month + \"\\nday is \" + day + \"\\nyear is \" + year);\n\t\tpopulateGameButtons(date, month, day, year);\t\t\n\t}", "static async getAllEventsByYear(req, res, next) {\n try {\n const { page, size } = req.query;\n const { limit, offset } = getPagination(page, size);\n\n // Year\n let data = await event.findAndCountAll({\n where: {\n dateEvent: {\n [Op.between]: [moment().startOf(\"year\"), moment().endOf(\"year\")],\n },\n },\n attributes: [\"id\", \"photoEvent\", \"dateEvent\", \"eventTime\", \"title\"],\n include: [\n { model: user, attributes: [\"firstName\"] },\n { model: category, attributes: [\"category\"] },\n ],\n limit,\n offset,\n order: [[\"dateEvent\", \"ASC\"]],\n });\n\n if (data.rows.length === 0) {\n return res.status(404).json({ errors: [\"Events not found\"] });\n }\n\n return res.status(200).json(getPagingData(data, page, limit));\n } catch (error) {\n next(error);\n }\n }", "function generateAlleventsHTML(data) {\n var list = $('.all-events .events-list');\n var theTemplateScript = $('#events-template').html();\n //Compile the template​\n var theTemplate = Handlebars.compile(theTemplateScript);\n list.find('li').remove();\n list.append(theTemplate(data));\n // Each events has a data-index attribute.\n // On click change the url hash to open up a preview for this event only.\n // Remember: every hashchange triggers the render function.\n list.find('li').on('click', function (e) {\n e.preventDefault();\n var eventIndex = $(this).data('index');\n window.location.hash = 'event/' + eventIndex;\n });\n var header = $('header');\n $('.btn-add-event').on('click', function (e) {\n e.preventDefault();\n window.location.hash = 'addEvent';\n });\n $('.userInfo').click(function (e) {\n e.preventDefault();\n window.location.hash = 'user/email=' + $(this).data('user');\n });\n $('.logout').click(function (e) {\n e.preventDefault();\n $.ajax({\n url: $(this).attr('href'),\n type: \"GET\",\n success: function (sessionUser) {\n user = undefined;\n $('.userInfo').hide();\n $('.logout').hide();\n $('.dropdown').show();\n $(window).trigger('hashchange');\n },\n error: function () {\n alert('Something wrong');\n },\n complete: function () {\n }\n });\n });\n }", "function archiveScrapeStories() {\n let archiveEvent = $(this).parent().parent().data();\n archiveEvent.archived = true;\n\n $.ajax({\n method: \"PUT\",\n url: \"/api/archived\",\n data: archiveEvent\n }).then(function(data) {\n if(data.success)\n displayStories();\n });\n }", "function handleResponse(data) {\r\n var parsedResponse = JSON.parse(data.currentTarget.response);\r\n console.log(parsedResponse.items);\r\n var parsedItems = Object.values(parsedResponse.items);\r\n var itemTimeslotArray = buildTimeslotArray(parsedItems);\r\n // pageConstructor(parsedItems, itemTimeslotArray);\r\n console.log(parsedItems);\r\n var currentDate = getDateForm();\r\n var paramForm = getParamForm();\r\n// console.log(currentDate);\r\n htmlConstructor(parsedItems, itemTimeslotArray, currentDate, paramForm);\r\n}", "function listGcalEvents(root, divId,calName,calHref) {\n var feed = root.feed;\n var events = document.getElementById(divId);\n\n if (events.childNodes.length > 0) {\n events.removeChild(events.childNodes[0]);\n }\n\t\t\n\t var eventContent = document.createElement('div');\n\t eventContent.className = 'widget_content widget_cal';\n\n // create a new ordered list\n var ol = document.createElement('ol');\n ol.className = \"widget_calItems\";\n\n // loop through each event in the feed\n for (var i = 0; i < feed.entry.length; i++) {\n var entry = feed.entry[i];\n var title = entry.title.$t;\n var startDate = entry['gd$when'][0].startTime;\n var endDate = entry['gd$when'][0].endTime;\n\n // get the URL to link to the event\n for (var linki = 0; linki < entry['link'].length; linki++) {\n if (entry['link'][linki]['type'] == 'text/html' &&\n entry['link'][linki]['rel'] == 'alternate') {\n var entryLinkHref = entry['link'][linki]['href'];\n }\n }\n //Take link data and build li\n li = usfDateLi(title, entryLinkHref, formatGCalTime(startDate), formatGCalTime(endDate));\n // append the list item onto the unordered list\n ul.appendChild(li);\n }\n var calHeader = document.createElement('h2');\n\t var calHeaderSpan = document.createElement('span');\n var calHeaderLink = document.createElement('a');\n var loadingElem = document.getElementById('calLoading');\n calHeader.className = \"widget_name\"; \n var linkText = document.createTextNode(calName);\n calHeaderLink.href = calHref;\n calHeaderLink.appendChild(linkText);\n\t calHeaderSpan.appendChild(calHeaderLink);\t\n calHeader.appendChild(calHeaderSpan);\n //loadingElem.parentNode.removeChild(loadingElem);\n events.innerHTML = '';\n events.appendChild(calHeader);\n events.appendChild(eventContent);\n\t eventContent.appendChild(ol);\n }", "function displayHomeFixtures(season) {\n\n\n\t// var eventsfound = false;\n\t$.getJSON(homefixturesurl,function(data){\n\n\t\t// Need to accumulate summary data object here \n\t\t// by looping through returned data\n\n\n\t\t// console.log(url);\n\n\t\tvar jsonstring = JSON.stringify(data);\n\n\t\tjsonstring = new String(\"{allHomeFixtures:\"+jsonstring+\"}\");\n\n\t\t// var eventdata = $.parseJSON(jsonstring);\n\t\tvar homefixturedata = eval(\"(\" + jsonstring + \")\");\n\n\t\t// Set the boolean if we have data\n\t\t// if (eventdata.length > 1)\n\t\t//\teventsfound = true;\n\n\n\t\t//Get the HTML from the template in the script tag\n\t var theTemplateScript = $(\"#homefixtures-template\").html(); \n\n\t //Compile the template\n\t var theTemplate = Handlebars.compile (theTemplateScript); \n\t\t// Handlebars.registerPartial(\"description\", $(\"#shoe-description\").html()); \n\t\t$(\"#main\").empty(); \n\t\t$(\"#main\").append (theTemplate(homefixturedata)); \n\n\n\t}); // end of function(data)\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}", "function collectAllEvents() {\n // A set for all calendar events displayed on the UI.\n // Each element in this set is a Json string. \n allEventJson = new Set(); \n \n const eventList = document.getElementById('new-event-list');\n \n // Looks at each event card and scrapes the event's name and \n // start and end times from the HTML elements. \n // Add all event information to a set of all Json strings. \n eventList.childNodes.forEach((eventCard) => {\n const eventName = eventCard.childNodes[0].childNodes[0].innerText; \n const startTime = eventCard.childNodes[0].childNodes[1].innerText; \n const endTime = eventCard.childNodes[0].childNodes[2].innerText; \n const event = new CalendarEvent(eventName, startTime, endTime);\n const eventJson = JSON.stringify(event); \n allEventJson.add(eventJson); \n }); \n}", "function getCalanders() {\n var response = Calendar.CalendarList.list();\n for(i = 0 ; i<response.items.length ; i++){\n Logger.log(\"(\" + response.items[i].summary + ')' + response.items[i].id);\n }\n}", "function displayAllEventsAuth(data) {\n $('.my-events-link').removeClass('hidden');\n const events = data.events;\n for (let i = 0; i < events.length; i++) {\n const dates = formatDates(events[i].startDate, events[i].endDate)\n\n let eventImg = '';\n if (events[i].image == undefined) {\n eventImg = 'images/default.jpg';\n }else{\n eventImg = events[i].image;\n }\n\n $('.events').append(\n `\n <article class='js-event ${i}'>\n <img src='${eventImg}' alt='${events[i].name} logo'>\n <p class='id hidden'>${events[i].id}</p>\n <h3><a href='${events[i].website}' target='_blank'>${events[i].name}</a></h3>\n <h3>${dates}</h3>\n <h3>${events[i].location}</h3>\n <button type='button' class='js-guest-list' data-featherlight='#guestauth${i}'>\n Celebrity Guests</button>\n <div class='hidden js-guests-list ${i} 'id='guestauth${i}'>\n <h4>${events[i].name} Celebrity Guests</h4>\n <ul class='${i}'></ul>\n <button type='button' class='add-guests'>Add guests</button>\n <form action='/events' method='post' class='add-guest-form hidden'>\n <p class='id hidden'>${events[i].id}</p>\n <label>\n <textarea rows='4' cols='40' name='new-guests' class='new-guests' placeholder='Enter guest names, separated by commas'></textarea>\n </label>\n <button type='submit' class='submit-guests'>Submit Guests</button>\n </form>\n </div>\n </article>\n `\n )\n for (let a = 0; a < events[i].guests.length; a++) {\n $('.events ul' + '.' + i).append(`<li>${events[i].guests[a]}</li>`);\n }\n if (moment().format('YYYY/MM/DD') > events[i].startDate) {\n $('.events .js-event' + '.' + i).append(`\n <button type='button' class='delete-option' data-featherlight='#delete${i}'>Delete this event</button>\n <div class='delete-confirm hidden' id='delete${i}'>\n <p class='id hidden'>${events[i].id}</p>\n <p class='delete-confirm-p'>Are you sure you want to delete this event?</p>\n <button type='button' class='delete-event'>Permanently delete this event</button>\n </div>\n `)\n }else if (moment().format('YYYY/MM/DD') < events[i].startDate && $('.my-events p').text().indexOf(events[i].id) == -1) {\n $('.events' + ' ' + 'article' + '.' + i).append(`\n <button type='button' class='add-my-events'>Add to My Events</button> \n `)\n }\n } \n}", "function loadSpendingEditPage (data) {\n mainView.router.loadContent(\n '<!-- Top Navbar-->\\n' + \n '<div class=\"navbar\">\\n' + \n ' <div class=\"navbar-inner\">\\n' + \n ' <div class=\"left\"><a href=\"#\" class=\"back link\"> <i class=\"icon icon-back\"></i><span>Back</span></a></div>\\n' + \n ' <div class=\"center sliding\">Edit Spending</div>\\n' + \n ' <div class=\"right\">\\n' + \n ' <a href=\"#\" class=\"link icon-only open-panel\"> <i class=\"icon icon-bars\"></i></a>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n '</div>\\n' + \n '<div class=\"pages\">\\n' + \n ' <!-- Page, data-page contains page name-->\\n' + \n ' <div data-page=\"spendingAdd\" class=\"page\">\\n' + \n ' <!-- Scrollable page content-->\\n' + \n ' <div class=\"page-content\">\\n' + \n ' <div class=\"content-block\">\\n' + \n ' <div class=\"list-block\">\\n' + \n ' <ul>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Spending date\" readonly id=\"spending_date\" value=\"'+data.spending_date+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Name\" id=\"name\" value=\"'+data.name+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Brand\" id=\"brand\" value=\"'+data.brand+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Where do you buy?\" id=\"location\" value=\"'+data.location+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"text\" placeholder=\"Description\" id=\"descr\" value=\"'+data.descr+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' <li>\\n' + \n ' <div class=\"item-content\">\\n' + \n ' <div class=\"item-inner\">\\n' + \n ' <div class=\"item-input\">\\n' + \n ' <input type=\"tel\" placeholder=\"How much?\" onkeypress=\"return isNumberKey(event);\" onkeyup=\"this.value=numberWithCommas(this.value);\" id=\"spent\" value=\"'+data.spent+'\">\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </li>\\n' + \n ' </ul>\\n' + \n ' </div>\\n' + \n ' <div class=\"row\">\\n' + \n ' <div class=\"col-50\">\\n' + \n ' <a href=\"#\" class=\"button button-big button-fill color-gray\" style=\"background-color:red;\" onclick=\"spendingDel('+data.id+');\">Delete</a>\\n' + \n ' </div>\\n' + \n ' <div class=\"col-50\">\\n' + \n ' <a href=\"#\" class=\"button button-big button-fill color-gray\" style=\"background-color:grey;\" onclick=\"spendingEdit('+data.id+');\">Edit</a>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n ' </div>\\n' + \n '</div>\\n'\n );\n return;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a squad entry, return an object keyed by frame times where each value is a count of number of units attacking at that frame time
getBattleFrames(squadEntry = {}) { if (squadEntry.id === 'X' || squadEntry.id === 'E') { return {}; } const position = squadEntry.position; const { name, moveType, speedType, originalFrames, } = squadEntry.unitData; let frameDelay = ((+squadEntry.bbOrder - 1) * this.sbbFrameDelay) + (moveType === 1 ? movespeedOffsets[speedType][position] : 0); // TODO: add support for SBB frame delay of 1 squadEntry.alias = squadEntry.alias || name; const offsetFrames = {}; originalFrames.forEach(attack => { Object.keys(attack).forEach(frame => { const actualFrame = (+frame + frameDelay); if (!offsetFrames[actualFrame]) { offsetFrames[actualFrame] = { aoe: 0, st: 0, }; } offsetFrames[actualFrame][attack[frame]] += 1; }); }); return offsetFrames; }
[ "function getSongCountByArtist(songs) {\n return songs.reduce((obj, song) => {\n let artist = song.artist;\n artist in obj ? obj[artist]++ : obj[artist] = 1;\n return obj;\n }, {});\n}", "getPlayersCardNums(state) {\n let players = (state || this).players, playerCardNums = {}\n for (let i in players) {\n if (players[i]) {\n playerCardNums[i] = players[i].cards.length\n }\n else {\n playerCardNums[i] = null\n }\n }\n return playerCardNums\n }", "function buildFreqs(digit) {\n let digitStr = digit.toString();\n let frequencies = new Map();\n for (let oneDigit of digitStr) {\n let valCount = frequencies.get(oneDigit) || 0;\n frequencies.set(oneDigit, valCount + 1);\n }\n return frequencies;\n}", "static frequencies(arr) {\n let result = {};\n arr.forEach(e => {\n if (e in result) {\n result[e] += 1;\n } else {\n result[e] = 1;\n }\n });\n return result;\n }", "function appendStats(inputArray){\n var currentStats = {previousMemberArray:[],memberExitsArray:[]}; \n var inputArrayLength = inputArray.length;\n\n for (var index=inputArrayLength-1; index>=0; index--){\n\t//Psuedocode:loop over array from the highest index (oldest) and move forward.\n\t//perform a diff of the current array in inputArray to currentStatsArray; if item in inputArray[i] in currentStatsArray, then increment streakCount in currentStatsArray. If item in inputArray[i] is not in currentStatsArray, then pop/slice element from currentStatsArray and push to old array obj. it's streakCount will be preserved....err that is wrong. if it is in inputArray[i], but not currentStatsArray then we need to tag it as new. \n\t//each loop through need to clear out new and old array; these will be populated based on actions on the current array. \n\n\tArray.prototype.diff = function(a) {\n\t return this.filter(function(i) {return a.indexOf(i.ticker) < 0;});\n\t};\n\tvar currentInputArray = inputArray[index].list;\n\t//Ugg the above diff function works on simple value based arrays but fails when they are objects\n\t//\tvar diffArray = currentInputArray.diff(currentStats.previousMemberArray);\n\t//\tcurrentStats.memberExitsArray=currentStats.previousMemberArray.diff(currentInputArray);\n\t//\tinputArray[index].memberExitsArray=currentStats.memberExitsArray\n\n//get the tickers that left the list\n\t//this seems stupidly inefficient (O(n^2) for each array element)\n\tcurrentStats.previousMemberArray.forEach(function(ele,index,fA) {\n\t var flag = false;\n\t for (var idx=0; idx<currentInputArray.length; idx++){\n\t\t//if we have a match, break...\n\t\tif(flag === true || ele.ticker === currentInputArray[idx].ticker) {\n\t\t flag = true;\n\t\t break;\n\t\t}\n\t\t//..otherwise push the element onto the array as it wasn't found\n\t\t//\t\tcurrentStats.memberExitsArray.push(ele);\n\t }\n\t /*\t currentInputArray.forEach(function(ele_,index_,fA_){\n\n\t\t });*/\n\t if (!flag) {\n\t\tcurrentStats.memberExitsArray.push(ele);\n\t }\n\t});\n\tinputArray[index].memberExitsArray=currentStats.memberExitsArray;\n\tcurrentStats.memberExitsArray=[];\n\n//compute our streakCount\n\t//\tconsole.log(\"cIa:b:\",currentInputArray);\n//\t\tconsole.log(\"cS.pMA:\",currentStats.previousMemberArray);\n\tcurrentInputArray.forEach(function(ele,ind,fA) {\n\t var filterEle = currentStats.previousMemberArray.filter(function(ele_,ind_,fA_) { return ele.ticker === ele_.ticker; } );\n\t //\t console.log(ele.ticker+' '+filterEle.length+' '+filterEle[0].streakCount); \n\t if ( filterEle.length > 0 ) {\n\t\t/*if ( ele.streakCount ) {*/ \n\t\t//\t console.log(ele.ticker+' '+filterEle.length+filterEle[0].streakCount); \n\t\tele.streakCount=filterEle[0].streakCount+1;\n //console.log(fA.length);\n//\t\tconsole.log(\"fE0.i:\"+filterEle[0].index+\" ei:\"+ele.index+\" fE0.rA:\"+filterEle[0].rankAccumulator); \n\n\t ele.rankAccumulator=fA.length+1-ele.index+filterEle[0].rankAccumulator; //fix the rankAccumulator such that higher ranked tickers get more points not less (i.e. #1 gets 20pts for BC20 and #20 gets 1pt; we add 1 such that the last place gets one point otherwise it wouldn't get any. \n\t\t//\t console.log(ele.ticker+' '+filterEle.length+' '+filterEle[0].streakCount+' '+ele.streakCount); \n\t } else { ele.streakCount=1; ele.rankAccumulator=fA.length+1-ele.index; }\n\t //}\n\t \n\t});\n\t//\tconsole.log(\"cIa:a:\",currentInputArray);\n \tcurrentStats.previousMemberArray=currentInputArray;\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}", "static channel_times() {\n return {\n MSNBCW: [\n '4:00pm',\n '5:00pm',\n '6:00pm',\n '7:00pm',\n '8:00pm',\n ],\n CNNW: [\n '5:00pm',\n '6:00pm',\n '7:00pm',\n '8:00pm',\n '9:00pm',\n ],\n FOXNEWSW: [\n '6:00pm',\n '7:00pm',\n '8:00pm',\n '9:00pm',\n ],\n KQED: [\n '6:00pm',\n ],\n BBCNEWS: [\n '5:00pm',\n '6:00pm',\n ],\n }\n }", "function getResponseTimes() {\n return {\n 'foia:ResponseTimeMedianDaysValue': { '$t': 0 },\n 'foia:ResponseTimeAverageDaysValue': { '$t': 0 },\n 'foia:ResponseTimeLowestDaysValue': { '$t': 0 },\n 'foia:ResponseTimeHighestDaysValue': { '$t': 0 },\n }\n}", "function countryKillers(){\n // init country object with country names as jeys\n for(let i = 0; i < countryNames.length; i++){\n let name = countryNames[i];\n countries[name] = {\"victim count\": 0, \"killer count\": 0, \"killer names\": []};\n }\n\n for(let i = 0; i < killerNames.length; i++){\n let name = killerNames[i]\n let info = killersInfo[name];\n\n for(let c of info[\"countries\"]){\n if(!(c in countries)) continue;\n countries[c][\"victim count\"] += info[\"Proven Victims\"];\n countries[c][\"killer count\"] ++;\n countries[c][\"killer names\"].push(name);\n\n }\n }\n\n for(let c of countryNames){\n let v = countries[c][\"victim count\"];\n if(v > maxVictims) maxVictims = v;\n }\n}", "function buildTrackCounts() {\n interactionEvents.sort(function (a, b) {\n return (+a[config.timePointColumn]) - (+b[config.timePointColumn]);\n });\n for (let i = 0, eventCount = interactionEvents.length; i < eventCount; i++) {\n let event = interactionEvents[i];\n let proteinA = event[config.proteinAColumn];\n let proteinB = event[config.proteinBColumn];\n let timePoint = +event[config.timePointColumn];\n addTrackCount(proteinA, proteinB, timePoint);\n addTrackCount(proteinB, proteinA, timePoint);\n }\n\n if (config.removeDuplicateInteractions === \"true\") {\n removeDuplicateInteractions();\n }\n for (let protein in trackCounts) {\n removeSmallerTrackCounts(protein);\n }\n }", "function getCountedObjects(){\n var counted = {};\n for (var i = 0; i < detections.length; i++){\n var lbl = detections[i].label;\n if (!counted[lbl]) counted[lbl] = 0;\n counted[lbl]++;\n }\n return counted;\n}", "count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }", "function getDurationsInSeconds(songs) {\n return songs.map(song => {\n return song.duration.split(\":\")\n .map((num, index) => index < 1 ? +num * 60 : +num)\n .reduce((acc, next) => acc + next);\n })\n}", "function generateScoreFromMatches(matches)\n{\n var wins = 0, losses = 0;\n for (let i = 0; i < matches.length; i++)\n {\n const match = matches[i];\n if (match.win == true)\n {\n wins++;\n }\n else\n {\n losses++;\n }\n }\n\n var scoreObj = {\"wins\": wins, \"losses\": losses};\n return scoreObj;\n}", "get collectiveSongLength() {\n let time = 0;\n SongManager.songList.forEach(s => {\n time += typeof s.details.songLength == \"number\" ? s.details.songLength : 0;\n });\n return time;\n }", "function watchlistedMoviesObject(arr) {\n\n let movieCount = {}\n\n arr.map(movie => {\n\n if (movieCount[movie]) {\n movieCount[movie]++\n } else {\n movieCount[movie] = 1\n }\n })\n\n return movieCount\n\n}", "calculateTimeSpent()\n {\n let timestamps = this.store_.getState('timestamps');\n\n console.log('** timestamps: ' + JSON.stringify(timestamps));\n\n let elapsedSecondsSigma = 0;\n timestamps.forEach(function(element){\n elapsedSecondsSigma += element.elapsedSeconds;\n });\n console.log('** elapsedSecondsSigma: ' + elapsedSecondsSigma);\n\n return elapsedSecondsSigma;\n }", "function calculateFrameTime(){\r\n\t\t\t\r\n\t\t\t//Sum the time for all frames\r\n\t\t\tvar sumFrameTimes = 0;\r\n\t\t\ttempFrameTime.forEach(time => sumFrameTimes += time);\r\n\t\t\t//Divide to get the average Frame time\r\n\t\t\tvar avgFrameTime = sumFrameTimes/tempFrameTime.length;\r\n\t\t\t//Push it into the array to be saved\r\n\t\t\tavgFrameTimeArray.push(avgFrameTime);\r\n\t\t\tconsole.log(\"avgFrameTime: \" + avgFrameTime);\r\n\t\t\t\r\n\t\t\t//Reset the array for the next trial\r\n\t\t\ttempFrameTime = []; \r\n\t\t}", "function getDurations(songs) {\n return songs.map(song => song.duration);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the text font, align and baseline drawing parameters. Obj can be either a canvas context or a DOM element See [reference]( for details. font is a HTML/CSS string like: "9px sansserif" align is left right center start end baseline is top hanging middle alphabetic ideographic bottom
setTextParams (obj, font, align = 'center', baseline = 'middle') { obj.font = font; obj.textAlign = align; obj.textBaseline = baseline }
[ "setFont(font) {\n this.ctx.font = font;\n }", "function drawText(txt,x,y,maxWidth,fontHeight,center) {\n if (center === undefined) {\n center = false;\n }\n\n // we need to scale the coordinate space in order to obtain the correct\n // max width and font height (i.e. sizes)\n var sx = canvas.width / 2;\n var sy = canvas.height / currentBlock.getHeight();\n\n if (center) {\n ctx.textAlign = \"center\";\n }\n else {\n ctx.textAlign = \"start\";\n }\n ctx.textBaseline = \"middle\"; // thank God for this\n\n // scale the context to undo the initial transformations; make sure\n // the scaling doesn't affect the specified text position\n ctx.save();\n ctx.scale(1/sx,1/sy);\n x *= sx; y *= sy;\n maxWidth *= sx; // this value converted to \"scaled pixels\"\n\n // the font is specified in pixels that are scaled; the transformations\n // take the font height from the calling context's coordinate space and\n // transforms it into units of \"scaled pixels\"\n var fontSz = fontHeight * sy;\n ctx.font = fontSz + \"px \" + DEFAULT_FONT;\n ctx.fillText(txt,x,y,maxWidth);\n\n ctx.restore();\n }", "setTextAlignment(value) {\n this.ctx.textAlign = value;\n }", "ctxDrawText (ctx, string, x, y, cssColor) {\n this.setIdentity(ctx)\n ctx.fillStyle = cssColor\n ctx.fillText(string, x, y)\n ctx.restore()\n }", "function styleText(text){ \n\t//console.log(\"style text called\");\n\ttext.style.fontFamily = getFont();\n\ttext.style.color = getColor(0); \n\ttext.style.backgroundColor = getColor(1);\n\tif (border) {\n\t\ttext.style.border = \"solid \"+ getBorder() + \"px\";\n\t\t//console.log(\"solid\"+ getBorder() + \"px\");\n\t\ttext.style.borderColor = getColor(2);\n\t};\n\ttext.style.fontSize = getSize() + \"px\"; \n}", "updateFabricTextObject (feature, changes) {\n\n const canvas = this.get('canvas');\n const fabricObj = canvas.featureFabObjs[feature.get('id')];\n const doesFontSizeChange = Object\n .keys(changes)\n .reduce((acc, key) => {\n canvas.update_texttopath(fabricObj, key, changes[key]);\n return acc || key === 'fontSize';\n }, false);\n\n [ 'top', 'left' ]\n .forEach((attrName) =>\n canvas.update_texttopath(fabricObj, attrName, feature.get(attrName))\n );\n\n const newFabricObj = canvas.replace_texttopath(fabricObj);\n\n if (newFabricObj) {\n canvas.container.offsetObject(newFabricObj);\n }\n\n canvas.setZIndexPosition();\n canvas.render();\n\n if (!doesFontSizeChange) {\n // #bug465\n this.updateFabricTextObject(feature, { 'fontSize': feature.get('fontSize') });\n }\n }", "function drawText() {\n push();\n textAlign(CENTER);\n fill(this.color);\n textSize(this.size);\n text(this.txt, this.x, this.y);\n pop();\n}", "text(...args) {\n let opts = args[args.length - 1];\n\n if (typeof opts !== 'object') {\n opts = {};\n }\n\n if (!opts.lineGap) {\n opts.lineGap = lineGap;\n }\n\n if (opts.font) {\n this.doc.font(opts.font);\n } else {\n this.doc.font(lightFont);\n }\n\n if (opts.color) {\n this.doc.fillColor(opts.color);\n } else {\n this.doc.fillColor('black');\n }\n\n if (opts.size) {\n this.doc.fontSize(opts.size);\n } else {\n this.doc.fontSize(10);\n }\n\n return this.doc.text(...args);\n }", "function Text(attrs) {\n var dflt = {\n content: \"\",\n fill: \"black\",\n font: \"12pt Helvetica\",\n height: 12\n };\n attrs = mergeWithDefault(attrs, dflt);\n Drawable.call(this, attrs);\n\t//constructor code \n this.content=attrs.content;\n this.fill = attrs.fill; \n this.font = attrs.font;\n this.height = attrs.height;\n this.left = attrs.left;\n}", "function canvas_set_font(ctx, size, monospaced) {\n var s = window.getComputedStyle(onscreen_canvas);\n // First set something that we're certain will work. Constructing\n // the font string from the computed style is a bit fragile, so\n // this acts as a fallback.\n ctx.font = `${size}px ` + (monospaced ? \"monospace\" : \"sans-serif\");\n // In CSS Fonts Module Level 4, \"font-stretch\" gets serialised as\n // a percentage, which can't be used in\n // CanvasRenderingContext2d.font, so we omit it.\n ctx.font = `${s.fontStyle} ${s.fontWeight} ${size}px ` +\n (monospaced ? \"monospace\" : s.fontFamily);\n}", "fillTexts(attrs, tarray, clip=null)\n {\n let ctx = this.canvasCtx;\n ctx.save();\n if(clip) this.doClip(ctx, clip);\n ctx.font = attrs[0];\n ctx.fillStyle = attrs[1];\n ctx.textBaseline = attrs[2];\n ctx.textAlign = attrs[3];\n for(let i=0;i<tarray.length;i++)\n {\n let t = tarray[i];\n ctx.fillText(t[0], t[1], t[2]);\n }\n ctx.restore();\n }", "function addCircleText(obj, cssClass, lineHeight) {\n $(\"<span></span>\")\n .appendTo(obj)\n .addClass(cssClass)\n .html(text)\n .prepend(icon)\n .css({\n 'line-height': '160px',\n 'font-size': customSettingsObj.fontsize + 'px'\n });\n }", "function loadFontAndWrite(font,text,x,y) {\r\n document.fonts.load(font).then(function () {\r\n ctx.font = font\r\n ctx.fillText(text, x, y)\r\n });\r\n }", "function changeAlign(align) {\n gMeme.currText.align = align;\n gMeme.currText.x = gFontlocation[align].x\n}", "function getLabelBBox(textWidth, textHeight, align, baseline, angle, margin){\n \n var polygon = getLabelPolygon(textWidth, textHeight, align, baseline, angle, margin);\n var corners = polygon.corners();\n var bbox;\n if(angle === 0){\n var min = corners[2]; // topLeft\n var max = corners[1]; // bottomRight\n \n bbox = new pvc.Rect(min.x, min.y, max.x - min.x, max.y - min.y);\n } else {\n bbox = polygon.bbox();\n }\n \n bbox.sourceCorners = corners;\n bbox.sourceAngle = angle;\n bbox.sourceAlign = align;\n bbox.sourceTextWidth = textWidth;\n \n return bbox;\n }", "constructor(fontImg, fontInfo) {\n fontInfo = JSON.parse(fontInfo).font;\n\n function toInt(str) {\n return parseInt(str, 10);\n }\n\n this.lineHeight = toInt(fontInfo.common.lineHeight);\n this.baseline = toInt(fontInfo.common.base);\n\n // Create glyph map\n this.glyphs = {};\n for (var i=0; i<fontInfo.chars.count; ++i) {\n var cInfo = fontInfo.chars.char[i];\n var glyph = new Glyph(fontImg, cInfo.id, toInt(cInfo.x), toInt(cInfo.y), toInt(cInfo.width), toInt(cInfo.height), toInt(cInfo.xoffset), toInt(cInfo.yoffset), toInt(cInfo.xadvance));\n this.glyphs[glyph.charCode] = glyph;\n }\n }", "_getTextMetrics(text) {\n var textSpan = document.createElement('span');\n textSpan.id = 'content-span';\n textSpan.innerHTML = text;\n\n var block = document.createElement(\"div\");\n block.id = 'content-block';\n block.style.display = 'inline-block';\n block.style.width = '1px';\n block.style.height = '0px';\n\n var div = document.createElement('div');\n div.appendChild(textSpan);\n div.appendChild(block);\n div.style.font = this.fontSize + 'px ' + this.fontName;\n\n var body = document.body;\n body.appendChild(div);\n\n var ascent = -1;\n var descent = -1;\n var height = -1;\n\n try {\n block.style['vertical-align'] = 'baseline';\n ascent = block.offsetTop - textSpan.offsetTop;\n block.style['vertical-align'] = 'bottom';\n height = block.offsetTop - textSpan.offsetTop;\n descent = height - ascent;\n } finally {\n document.body.removeChild(div);\n }\n\n return {\n ascent: ascent,\n descent: descent,\n height: height\n };\n }", "function label(str, x, y, dx, dy) {\n fill(0);\n noStroke();\n if (textRotation) {\n text(str, x + dx, y + dy);\n } else {\n // get screen coordinates for where the text should go\n var x0 = m.screenX(x, y);\n var y0 = m.screenY(x, y);\n m.push();\n // set current transform to the default matrix\n m.set();\n // position text (with offset added)\n text(str, x0 + dx, y0 + dy);\n m.pop();\n }\n}", "key(x, y, squareSize, font) {\n this.ctx.font = font;\n for (let i = 0; i < this.data.length; i++) {\n this.ctx.fillStyle = this.data[i].color;\n this.ctx.textBaseline = \"top\";\n this.ctx.textAlign = \"left\";\n this.ctx.fillRect(x, y + i * squareSize * 1.5, squareSize, squareSize);\n this.ctx.fillText(`${this.data[i].label}, ${this.data[i].unit}`, x + squareSize * 1.5, y + squareSize * i * 1.5);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method : get vector
function getVector() { return this.getName() + ':' + this.value; }
[ "getVector() {\n if (this.parent) {\n let dx = this.parent.loc.x - this.loc.x;\n let dy = this.parent.loc.y - this.loc.y;\n let v = new JSVector(dx, dy);\n return v;\n }\n else return (JSVector(0, 0));\n }", "function getVector(pt1, pt2) {\n\n return {\n x: pt2.x - pt1.x,\n y: pt2.y - pt1.y\n }\n}", "get centre() { return new vector2(this.centrex, this.centrey);}", "copy() {\n return new Vector(this.x, this.y);\n }", "static getVectorEndPoint(startPoint, vec){\n\t\treturn [vec[0] + startPoint[0], vec[1] + startPoint[1]];\n\t}", "static mxVMult(v,m) {\r\n\t\tvar res = new mVec3(); \r\n\t\tres.x = (v.x * m.M[0]) + (v.y * m.M[4]) + (v.z * m.M[8]) + m.M[12];\r\n\t\tres.y = (v.x * m.M[1]) + (v.y * m.M[5]) + (v.z * m.M[9]) + m.M[13];\r\n\t\tres.z = (v.x * m.M[2]) + (v.y * m.M[6]) + (v.z * m.M[10]) + m.M[14];\r\n\t\treturn res; \r\n\t}", "GetVecBetween( fromEntity, toEntity ) { return null; }", "buildFeatureVector() {\n // create empty feature vector\n let featureVector = [];\n // get all partial feature vectors and merge them together\n for (let i in this.nodes) {\n let dataAvailable = this.nodes[i].checkDataAvailability();\n if (dataAvailable == false) {\n console.log(\"Can not be generated!\");\n return [];\n }\n let partialFeatureVector = this.nodes[i].getPartialFeatureVector();\n featureVector = featureVector.concat(partialFeatureVector);\n }\n // return the feature vector\n return featureVector;\n }", "static newVCopy(it) { \r\n\t\tvar res = new mVec3(); \r\n\t\tres.copy(it.x, it.y, it.z); \r\n\t\treturn res; \r\n\t}", "get vectorLayer() {\n return this.#vectorLayer;\n }", "projection(other_vector) {}", "getVelocity() {\n return this.model ? this.model.getVelocity() : null;\n }", "static vRandom(r) { return newVec((Math.random()-0.5)*r, (Math.random()-0.5)*r, (Math.random()-0.5)*r); }", "vector3ToViewerCoords(vector) {\n const vectorClone = vector.clone();\n vectorClone.project(this.viewer.renderer.camera);\n return {\n x: Math.round((vectorClone.x + 1) / 2 * this.state.size.width),\n y: Math.round((1 - vectorClone.y) / 2 * this.state.size.height)\n };\n }", "static translation(v) {\r\n\t\tres = identity(); \t\tres.M[3] = v.x; \r\n\t\tres.M[7] = v.y; \t\tres.M[11] = v.z; \r\n\t\treturn res; \r\n\t}", "ones_vector() {\n\t \n\t return Matrix_ones_vector( this )\n\t}", "static yAxis() { return newVec(0.0,1.0,0.0); }", "static vSub(a,b) { return newVec(a.x-b.x,a.y-b.y,a.z-b.z); }", "_normalVector(v0, vt, va) {\n let normal0;\n let tgl = vt.length();\n if (tgl === 0.0) {\n tgl = 1.0;\n }\n if (va === undefined || va === null) {\n let point;\n if (!Scalar_1.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, types_1.Epsilon)) {\n // search for a point in the plane\n point = new Vector3_1.Vector3(0.0, -1.0, 0.0);\n }\n else if (!Scalar_1.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, types_1.Epsilon)) {\n point = new Vector3_1.Vector3(1.0, 0.0, 0.0);\n }\n else if (!Scalar_1.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, types_1.Epsilon)) {\n point = new Vector3_1.Vector3(0.0, 0.0, 1.0);\n }\n else {\n point = Vector3_1.Vector3.Zero();\n }\n normal0 = Vector3_1.Vector3.Cross(vt, point);\n }\n else {\n normal0 = Vector3_1.Vector3.Cross(vt, va);\n Vector3_1.Vector3.CrossToRef(normal0, vt, normal0);\n }\n normal0.normalize();\n return normal0;\n }", "subtract(otherVector) {\n return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
preload() preload of images and font
function preload() { lemonMilk = loadFont("assets/text/LemonMilk.otf"); catN = loadImage("assets/images/cat.png"); lionN = loadImage("assets/images/lion.png"); jungleN = loadImage("assets/images/jungle.jpg"); catRetro = loadImage("assets/images/catRetro.png"); lionRetro = loadImage("assets/images/lionRetro.png"); jungleRetro = loadImage("assets/images/jungleRetro.jpg"); }
[ "function preload() {\n img = loadImage('./img/body.png');\n}", "function preload(){\n\thelicopterIMG=loadImage(\"helicopter.png\")\n\tpackageIMG=loadImage(\"package.png\")\n}", "function preload()\n{\n\tpaperImage = loadImage(\"paperImage.png\")\n\tdustbinImage = loadImage(\"dustbinWHJ.png\")\n\n}", "function preload() {\n\tkernelImg = loadImage(\"assets/kernel.png\");\n\tpopcornImg = loadImage(\"assets/popcorn.png\");\n\tburntImg = loadImage(\"assets/burnt.png\");\n}", "function preload()\r\n{\r\n // Spiderman Mask Filter asset\r\n imgSpidermanMask = loadImage(\"https://i.ibb.co/9HB2sSv/spiderman-mask-1.png\");\r\n\r\n // Dog Face Filter assets\r\n imgDogEarRight = loadImage(\"https://i.ibb.co/bFJf33z/dog-ear-right.png\");\r\n imgDogEarLeft = loadImage(\"https://i.ibb.co/dggwZ1q/dog-ear-left.png\");\r\n imgDogNose = loadImage(\"https://i.ibb.co/PWYGkw1/dog-nose.png\");\r\n}", "function preload() {\nfrogImage = loadImage(\"assets/images/Frog.png\");\n}", "function preload() {\n game.load.image('chair', 'https://media1.popsugar-assets.com/static/imgs/interview/chair.png');\n}", "function preload(){\n var manifest = [\n {src: \"assets/text.txt\", id: \"txt\"},\n ];\n\n q = new createjs.LoadQueue(true);\n q.on(\"complete\", loadComplete);\n q.loadManifest(manifest);\n}", "preload() {\n this.load.sprite('gun', 'assets/sprites/gun.png');\n }", "function preload() {\r\n\tgame.images.IPiece = loadImage('assets/tetrisI.png');\r\n\tgame.images.JPiece = loadImage('assets/tetrisJ.png');\r\n\tgame.images.LPiece = loadImage('assets/tetrisL.png');\r\n\tgame.images.OPiece = loadImage('assets/tetrisO.png');\r\n\tgame.images.SPiece = loadImage('assets/tetrisS.png');\r\n\tgame.images.TPiece = loadImage('assets/tetrisT.png');\r\n\tgame.images.ZPiece = loadImage('assets/tetrisZ.png');\r\n}", "function Preload() {\n assets = new createjs.LoadQueue(); // asset container\n util.GameConfig.ASSETS = assets; // make a reference to the assets in the global config\n assets.installPlugin(createjs.Sound); // supports sound preloading\n assets.loadManifest(assetManifest); // load assetManifest\n assets.on(\"complete\", Start); // once completed, call start function\n }", "function preloadImages(code) {\n var re = /SimpleImage\\(\\s*(\"|')(.*?)(\"|')\\s*\\)/g;\n while (ar = re.exec(code)) {\n // Used to screen out data: urls here, but that messed up the .loaded attr, strangely\n var url = ar[2];\n loadImage(url);\n }\n}", "_preload () {\n const preloader = new Preloader();\n\n preloader.run().then(() => { this._start() });\n }", "function preloadOptions(game) {\n game.load.image('game-bg', 'assets/bg/blue-bg.png');\n game.load.image(\"screentint\", \"assets/ui/screentint-alpha-50.png\");\n game.load.image(\"screentint75\", \"assets/ui/screentint-alpha-75.png\");\n game.load.image('black', 'assets/ui/black.png');\n\n game.load.image(\"button-back\", \"assets/ui/button-back.png\");\n game.load.image(\"dialogue-option\", \"assets/ui/dialogue-option.png\");\n\n preloadUI(game);\n\n game.load.audio(\"menu-select\", [\"assets/sounds/select01.mp3\"]);\n game.load.audio('menu-accept', ['assets/sounds/accept01.mp3']);\n game.load.audio(\"accept02\", [\"assets/sounds/accept02.mp3\"]);\n}", "function preload_sounds() {\n\tfor (var i = 1; i < allSoundsLen; i++) {\n allSounds[i] = new Howl({src: ['sound/PizzStr/' + allSoundNames[i] + '.mp3']});\n // once this file loads, it will call loadedAudio()\n // the file will be kept by the browser as cache\n allSounds[i].once('load', function(){\n\t\t\tloadedAudio();\n\t\t});\n\t}\n}", "function preLoadImages() {\n var args_len = arguments.length;\n for (var i = args_len; i--;) {\n var cacheImage = document.createElement('img');\n cacheImage.src = arguments[i];\n __cache.push(cacheImage);\n }\n }", "function PreloadImage()\n{\n var appVer=parseInt(navigator.appVersion);\n var isNC=(document.layers && (appVer >= 4));\n var isIE=(document.all && (appVer >= 4));\n if (isNC || isIE)\n {\n if (document.images)\n {\n var imgName = PreloadImage.arguments[0];\n var cnt;\n swImg[imgName] = new Array;\n for (cnt = 1; cnt < PreloadImage.arguments.length; cnt++)\n {\n swImg[imgName][PreloadImage.arguments[cnt]] = new Image();\n swImg[imgName][PreloadImage.arguments[cnt]].src = HpbImgPreload.arguments[cnt];\n }\n }\n }\n}", "preloadMap() {\n\n // Read the previously parsed Tiled map JSON\n this.tilemapJson = this.game.cache.getJSON(this.mapName);\n\n // Load the Tiled map JSON as an actual Tilemap\n this.game.load.tilemap(this.mapName, null, this.tilemapJson, Phaser.Tilemap.TILED_JSON);\n\n // Load the tileset images\n this.loadTilesetImages();\n }", "function preload_images() {\n for (var i = 0; i < c_PreloadChunkSize && imageIndex < images.length; i++, imageIndex++) {\n outstandingPreloadCount++;\n var image = images[imageIndex];\n (function(image) {\n $('<img />')\n .attr('alt', image.title)\n .attr('src', image.img + '_n.jpg')\n .one('load', function() {\n var link = $('<a />')\n .attr('href', image.img + '_b.jpg')\n .attr('title', image.title)\n .append($(this));\n gallery.append(link);\n outstandingPreloadCount--;\n })\n .error(function() {\n console.log('Error downloading image: ' + image.img);\n outstandingPreloadCount--;\n });\n })(image);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the illuminance depending on the time of the day
function illuminance(time, callback) { var lumen, times = SunCalc.getTimes(new Date(), 60.2, 24.9); // Helsinki 60.2, 24.9 //Check Daylight Hours: var sunrise = Number(times.sunrise.getHours() + '.' + times.sunrise.getMinutes()), sunset = Number(times.sunset.getHours() + '.' + times.sunset.getMinutes()), dawn = Number(times.dawn.getHours() + '.' + times.dawn.getMinutes()), dusk = Number(times.dusk.getHours() + '.' + times.dusk.getMinutes()), nauticalDawn = Number(times.nauticalDawn.getHours() + '.' + times.nauticalDawn.getMinutes()) || null, nauticalDusk = Number(times.nauticalDusk.getHours() + '.' + times.nauticalDusk.getMinutes()) || null, night = Number(times.night.getHours() + '.' + times.night.getMinutes()) || null, nightEnd = Number(times.nightEnd.getHours() + '.' + times.nightEnd.getMinutes()) || null; if (time >= sunrise && time < sunset) { lumen = getRandomArbitrary(1000, 10000); } else if ((time >= dawn && time < sunrise) || (time >= sunset && time < dusk)) { lumen = getRandomArbitrary(100, 1000); } else if ((time >= nauticalDawn && time < dawn) || (time >= dusk && time < nauticalDusk) || nauticalDawn == null) { lumen = getRandomArbitrary(10, 100); } else if ((time >= nightEnd && time < nauticalDawn) || (time >= nauticalDusk && time < night) || night == null) { lumen = getRandomArbitrary(1.0, 10); } else { lumen = getRandomArbitrary(0.001, 1.0); } callback(lumen); }
[ "toLuminance() {\n return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;\n }", "function _calculateColorIntensity(arrivalMinutes, maximumMinutes) {\n maximumMinutes = maximumMinutes || 15;\n\n if(arrivalMinutes <= 1) {\n return 1;\n } else if(arrivalMinutes > maximumMinutes) {\n return 0;\n }\n\n return (maximumMinutes - arrivalMinutes) / maximumMinutes;\n}", "function calcGeomMeanAnomalySun(t) {\n var M = 357.52911 + t * (35999.05029 - 0.0001537 * t);\n return M; // in degrees\n}", "function calcGeomMeanLongSun(t) {\n var L0 = 280.46646 + t * (36000.76983 + 0.0003032 * t);\n while(L0 > 360.0) {\n L0 -= 360.0;\n }\n while(L0 < 0.0) {\n L0 += 360.0;\n }\n return L0; // in degrees\n}", "function calc_solar_lum(R, T) {\n return calc_lum(R / 1000, T) / SOLAR_LUMINOSITY;\n}", "function sunrise() {\n\n // we can get the current time and duration\n // of the audio file easily!\n let time = bgMusic.currentTime();\n let duration = bgMusic.duration();\n \n // and use it to change color...\n let pct = map(time, 0,duration, 0,1);\n let dark = color(0,0,30);\n let light = color(135,206,250);\n background(lerpColor(dark, light, pct));\n\n // ...or y position and size too!\n let y = map(time, 0,duration, height+300,height/4);\n let dia = map(time, 0,duration, 600,100);\n fill(255,255,100);\n noStroke();\n circle(width/2,y, dia);\n}", "getAverageImageColor(image) {\n let ctx = document.createElement('canvas').getContext('2d');\n\n ctx.canvas.width = CANVAS_WIDTH;\n ctx.canvas.height = CANVAS_WIDTH * image.height/image.width;\n\n // ctx.canvas.height = ctx.canvas.width * (image.height/image.width);\n ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);\n\n let data = ctx.getImageData(0,0,ctx.canvas.width,ctx.canvas.height),\n color = [0,0,0],\n hex = \"\",\n contrast = 0;\n\n for (let i = 0; i <= data.data.length - 1; i+=4) {\n if (data.data[i+3] != 1) {\n color[0] += data.data[i];\n color[1] += data.data[i+1];\n color[2] += data.data[i+2];\n }\n }\n\n color[0] = Math.round(color[0] / ((data.data.length - 1)/4)) * 2;\n color[1] = Math.round(color[1] / ((data.data.length - 1)/4)) * 2;\n color[2] = Math.round(color[2] / ((data.data.length - 1)/4)) * 2;\n\n let coloring = color.map((colors) => {\n if (colors > 255) return 255;\n return colors;\n });\n\n hex = this.rgbToHex(coloring[0],coloring[1],coloring[2]);\n this.GraphCore.App.Project.settings.startColor = hex;\n\n return hex;\n }", "get_irregular_ema(sample, sample_time) {\n let new_ema = 0;\n\n // if this is not the first time\n if (this.prev_sample) {\n\n const a = (sample_time - this.prev_time) / this.timespan;\n const u = Math.exp(a * -1);\n\n let v = 0;\n if (a) {\n v = (1 - u) / a;\n }\n\n new_ema = (u * this.prev_ema) + ((v - u) * this.prev_sample) + ((1.0 - v) * sample);\n }\n else {\n new_ema = sample;\n }\n\n // set for next time\n this.prev_time = sample_time;\n this.prev_sample = sample;\n this.prev_ema = new_ema;\n\n return new_ema;\n }", "function luminance(color) {\n return (0,_microsoft_fast_colors__WEBPACK_IMPORTED_MODULE_2__.rgbToRelativeLuminance)(parseColorString(color));\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 calculateFill(heightMap, average, x, y){\n var deviationFromAverage = heightMap[x][y] - average;\n var grayscaleValue;\n var rgbValue;\n // higher elevations are darker\n if(deviationFromAverage > 0){\n grayscaleValue = Math.round(127 + deviationFromAverage*10); \n } else {\n // lower elevations are lighter\n grayscaleValue = Math.round(127 - deviationFromAverage*10);\n }\n rgbValue = 'rgb(' + grayscaleValue + ', ' + grayscaleValue + ', ' + grayscaleValue + ')';\n return rgbValue;\n}", "function radiatorEffect(getState, ms_since_update) {\n if (getState().radiator.on) {\n\n var btus = getState().radiator.BTUs;\n var mass = massOfAirInBuilding(getState().building);\n var capacity = /* approx. heat capacity of air, kcal/C */ 0.239\n\n return degreesFChangeOverInterval(btus, ms_since_update, mass, capacity);\n\n } else {\n return 0;\n }\n\n}", "function calculateFrameTime(){\r\n\t\t\t\r\n\t\t\t//Sum the time for all frames\r\n\t\t\tvar sumFrameTimes = 0;\r\n\t\t\ttempFrameTime.forEach(time => sumFrameTimes += time);\r\n\t\t\t//Divide to get the average Frame time\r\n\t\t\tvar avgFrameTime = sumFrameTimes/tempFrameTime.length;\r\n\t\t\t//Push it into the array to be saved\r\n\t\t\tavgFrameTimeArray.push(avgFrameTime);\r\n\t\t\tconsole.log(\"avgFrameTime: \" + avgFrameTime);\r\n\t\t\t\r\n\t\t\t//Reset the array for the next trial\r\n\t\t\ttempFrameTime = []; \r\n\t\t}", "function marsTime() {\n /* MarsTime related vars*/\n /* calculation steps adapted from http://jtauber.github.io/mars-clock/ */\n var tai_offset = 37;\n var d = new Date();\n var millis = d.getTime();\n var jd_ut = 2440587.5 + (millis / 8.64E7);\n var jd_tt = jd_ut + (tai_offset + 32.184) / 86400;\n var j2000 = jd_tt - 2451545.0;\n var msd = (((j2000 - 4.5) / 1.027491252) + 44796.0 - 0.00096);\n var mtc = (24 * msd) % 24;\n var x = mtc * 3600;\n var hh = Math.floor(x / 3600);\n if (hh < 10) hh = \"0\" + hh;\n var y = x % 3600\n var mm = Math.floor(y / 60);\n if (mm < 10) mm = \"0\" + mm;\n var ss = Math.round(y % 60);\n if (ss < 10) ss = \"0\" + ss;\n if (mm < 1 || runtime==0) {\n updateElement('span.digit.hours',hh);\n startDigitAnimation('hours');\n }\n if (ss <= 1 || runtime==0) {\n updateElement('span.digit.minutes',mm);\n startDigitAnimation('minutes');\n }\n updateElement('span.digit.seconds',ss);\n startDigitAnimation('seconds');\n runtime =+1;\n\n /* Interface adapts to time change (after 8pm mars time it will change to dark mode */\n if (hh>20 && nightModeToggled==null) {\n nightModeToggle\n nightModeActive=1;\n }\n\n}", "function calcMeanObliquityOfEcliptic(t) {\n var seconds = 21.448 - t*(46.8150 + t*(0.00059 - t*(0.001813)));\n var e0 = 23.0 + (26.0 + (seconds/60.0))/60.0;\n return e0; // in degrees\n}", "function blackenLow(img){\n const epsilon = 0.002;\n function blacken(img, x, y) {\n let pixel = img.getPixel(x, y);\n if ((pixel[0] - 0.3) < -epsilon) { pixel[0] = 0;}\n if ((pixel[1] - 0.3) < -epsilon) { pixel[1] = 0;}\n if ((pixel[2] - 0.3) < -epsilon) { pixel[2] = 0;}\n return pixel;\n }\n return imageMapXY(img, blacken);\n}", "function getTimeOfDay() {\n\n // time and color variables\n var timeOfDay = {\n \"dawn\": {\n \"hour\": 6,\n \"colorLight\": \"#00EDC4\",\n \"colorDark\": \"#317873\"\n },\n \"day\": {\n \"hour\": 9,\n \"colorLight\": \"#0085FF\",\n \"colorDark\": \"#005CFF\"\n },\n \"afternoon\": {\n \"hour\": 15,\n \"colorLight\": \"#FFA330\",\n \"colorDark\": \"#FF5224\"\n },\n \"dusk\": {\n \"hour\": 18,\n \"colorLight\": \"#00025C\",\n \"colorDark\": \"#000029\"\n }\n };\n\n // get the current time\n var time = new Date();\n var hour = time.getHours();\n\n var light, dark;\n\n // based on local hour, change the colors\n if (hour >= timeOfDay.day.hour && hour <= timeOfDay.afternoon.hour) {\n // day: rich blue colors\n light = timeOfDay.day.colorLight;\n dark = timeOfDay.day.colorDark;\n } else {\n if (hour < timeOfDay.dawn.hour || hour >= timeOfDay.dusk.hour) {\n // dusk: do moon icons and night colors\n light = timeOfDay.dusk.colorLight;\n dark = timeOfDay.dusk.colorDark;\n day = false;\n } else {\n if (hour >= timeOfDay.dawn.hour) {\n // dawn: light green/blue morning colors\n light = timeOfDay.dawn.colorLight;\n dark = timeOfDay.dawn.colorDark;\n }\n if (hour >= timeOfDay.afternoon.hour) {\n // afternoon: yellow afternoon colors\n light = timeOfDay.afternoon.colorLight;\n dark = timeOfDay.afternoon.colorDark;\n }\n }\n }\n // animate color fades via css, apply fixed bg only after change\n $(\"body\").css(\"background\", \"linear-gradient(\" + light + \", \" + dark + \")\");\n $(\"body\").css(\"background-attachment\", \"fixed\");\n }", "function firelineIntensityFromFlameLength (flame) {\n return flame <= 0 ? 0 : Math.pow(flame / 0.45, 1 / 0.46)\n}", "function saturateHigh(img) {\n const epsilon = 0.002;\n function saturate(img, x, y) {\n let pixel = img.getPixel(x, y);\n if ((pixel[0] - 0.7) > epsilon) { pixel[0] = 1;}\n if ((pixel[1] - 0.7) > epsilon) { pixel[1] = 1;}\n if ((pixel[2] - 0.7) > epsilon) { pixel[2] = 1;}\n return pixel;\n }\n return imageMapXY(img, saturate);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a gRPC credential from a Google credential object.
static createFromGoogleCredential(googleCredentials) { return CallCredentials.createFromMetadataGenerator((options, callback) => { let getHeaders; if (isCurrentOauth2Client(googleCredentials)) { getHeaders = googleCredentials.getRequestHeaders(options.service_url); } else { getHeaders = new Promise((resolve, reject) => { googleCredentials.getRequestMetadata(options.service_url, (err, headers) => { if (err) { reject(err); return; } if (!headers) { reject(new Error('Headers not set by metadata plugin')); return; } resolve(headers); }); }); } getHeaders.then(headers => { const metadata = new metadata_1.Metadata(); for (const key of Object.keys(headers)) { metadata.add(key, headers[key]); } callback(null, metadata); }, err => { callback(err); }); }); }
[ "async prepareCredentials() {\n if (this.env[DEFAULT_ENV_SECRET]) {\n const secretmanager = new SecretManager({\n projectId: this.env.GCP_PROJECT,\n });\n const secret = await secretmanager.access(this.env[DEFAULT_ENV_SECRET]);\n if (secret) {\n const secretObj = JSON.parse(secret);\n if (secretObj.token) {\n this.oauthToken = secretObj;\n } else {\n this.serviceAccountKey = secretObj;\n }\n this.logger.info(`Get secret from SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n return;\n }\n this.logger.warn(`Cannot find SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n }\n // To be compatible with previous solution.\n const oauthTokenFile = this.getContentFromEnvVar(DEFAULT_ENV_OAUTH);\n if (oauthTokenFile) {\n this.oauthToken = JSON.parse(oauthTokenFile);\n }\n const serviceAccountKeyFile =\n this.getContentFromEnvVar(DEFAULT_ENV_KEYFILE);\n if (serviceAccountKeyFile) {\n this.serviceAccountKey = JSON.parse(serviceAccountKeyFile);\n }\n }", "function blockGoogleApplicationCredentialEnvironmentVariable(auth) {\n return insertEnvironmentVariableIntoAuth(auth, 'GOOGLE_APPLICATION_CREDENTIALS', null);\n}", "async getCredentials(keyFile) {\n const ext = path.extname(keyFile);\n switch (ext) {\n case '.json': {\n const key = await readFile(keyFile, 'utf8');\n const body = JSON.parse(key);\n const privateKey = body.private_key;\n const clientEmail = body.client_email;\n if (!privateKey || !clientEmail) {\n throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS');\n }\n return { privateKey, clientEmail };\n }\n case '.der':\n case '.crt':\n case '.pem': {\n const privateKey = await readFile(keyFile, 'utf8');\n return { privateKey };\n }\n case '.p12':\n case '.pfx': {\n // NOTE: The loading of `google-p12-pem` is deferred for performance\n // reasons. The `node-forge` npm module in `google-p12-pem` adds a fair\n // bit time to overall module loading, and is likely not frequently\n // used. In a future release, p12 support will be entirely removed.\n if (!getPem) {\n getPem = (await Promise.resolve().then(() => __nccwpck_require__(2119))).getPem;\n }\n const privateKey = await getPem(keyFile);\n return { privateKey };\n }\n default:\n throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' +\n 'Current supported extensions are *.json, *.pem, and *.p12.', 'UNKNOWN_CERTIFICATE_TYPE');\n }\n }", "function getClient() {\n return new googleapis.auth.OAuth2(\n config.clientId,\n config.clientSecret,\n config.redirectUrl\n );\n }", "function authorize(credentials, callback) {\n const {client_secret, client_id, redirect_uris} = credentials.installed;\n const oAuth2Client = new google.auth.OAuth2(\n client_id, client_secret, redirect_uris[0]);\n\n // Check if we have previously stored a token.\n if (!config.get('oauthToken')) {\n setup.getAccessToken(oAuth2Client, callback);\n } else {\n oAuth2Client.setCredentials(config.get('oauthToken'));\n callback(oAuth2Client);\n }\n}", "function googleOAuthDomain_(name,scope) {\n var oAuthConfig = UrlFetchApp.addOAuthService(name);\n oAuthConfig.setRequestTokenUrl(\"https://www.google.com/accounts/OAuthGetRequestToken?scope=\"+scope);\n oAuthConfig.setAuthorizationUrl(\"https://www.google.com/accounts/OAuthAuthorizeToken\");\n oAuthConfig.setAccessTokenUrl(\"https://www.google.com/accounts/OAuthGetAccessToken\");\n var consumerKey = ScriptProperties.getProperty(\"consumerKey\");\n var consumerSecret = ScriptProperties.getProperty(\"consumerSecret\");\n oAuthConfig.setConsumerKey(consumerKey);\n oAuthConfig.setConsumerSecret(consumerSecret);\n return {oAuthServiceName:name, oAuthUseToken:\"always\"};\n}", "newAuthorisedCapability (holder, id, type, location, sphere, validFrom, validTo) {\n const subject = {\n id: 'did:caelum:' + this.did + '#issued-' + (id || 0),\n capability: {\n type: type || 'member',\n sphere: (['over18', 'oidc'].includes(type) ? 'personal' : 'professional')\n }\n }\n if (location) subject.capability.location = location\n const credential = {\n '@context': [\n 'https://www.w3.org/2018/credentials/v1',\n 'https://caelumapp.com/context/v1'\n ],\n id: 'did:caelum:' + this.did + '#issued',\n type: ['VerifiableCredential', 'AuthorisedCapability'],\n issuer: 'did:caelum:' + this.did,\n holder: holder,\n issuanceDate: new Date().toISOString(),\n credentialSubject: subject\n }\n return credential\n }", "drive() {\n const auth = new google.auth.OAuth2();\n auth.setCredentials({\n access_token: this.$auth.oauth_access_token,\n });\n return google.drive({\n version: \"v3\",\n auth,\n });\n }", "function initClient() {\n \n const keys = {\n // fill\n };\n\n return new Gdax.AuthenticatedClient(\n keys[\"API-key\"],\n keys[\"API-secret\"],\n keys[\"Passphrase\"],\n keys[\"Exchange-url\"]\n );\n}", "static createConnectionDetails(credentials) {\n let details = new connection_1.ConnectionDetails();\n details.options['host'] = credentials.host;\n if (credentials.port && details.options['host'].indexOf(',') === -1) {\n details.options['port'] = credentials.port;\n }\n details.options['dbname'] = credentials.dbname;\n details.options['user'] = credentials.user;\n details.options['password'] = credentials.password;\n details.options['hostaddr'] = credentials.hostaddr;\n details.options['connectTimeout'] = credentials.connectTimeout;\n details.options['clientEncoding'] = credentials.clientEncoding;\n details.options['options'] = credentials.options;\n details.options['applicationName'] = credentials.applicationName;\n details.options['sslmode'] = credentials.sslmode;\n details.options['sslcompression'] = credentials.sslcompression;\n details.options['sslcert'] = credentials.sslcert;\n details.options['sslkey'] = credentials.sslkey;\n details.options['sslrootcert'] = credentials.sslrootcert;\n details.options['sslcrl'] = credentials.sslcrl;\n details.options['requirepeer'] = credentials.requirepeer;\n details.options['service'] = credentials.service;\n return details;\n }", "function buildAuthOptions(authOptions) {\n return __assign({ clientCapabilities: [], azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS, skipAuthorityMetadataCache: false }, authOptions);\n }", "changeCredentialsToRefreshCredentials({ refresh_token }) {\n this.credentials = OAuthRefreshCredentials.from(\n this.credentials.credentials.client_id,\n this.credentials.credentials.client_secret,\n refresh_token\n );\n }", "function generateRandomPasswordCreds() {\n const password = generator.generate({\n length: 30,\n numbers: true,\n symbols: true,\n uppercase: true,\n strict: true\n });\n return { password: { value: password }};\n}", "toDescriptor() {\n return {\n apiVersion: 'v1',\n kind: 'Secret',\n metadata: this.metadata,\n data: Object.entries(this.data).reduce((hash, entry) => {\n const [ key, value ] = entry;\n if (value !== undefined) hash[key] = toBase64(value);\n return hash;\n }, {})\n };\n }", "async function getFabricClient (organization) {\n if (!organization) {\n throw new Error ('Organization must be supplied in order to create a fabric client.');\n }\n\n var connectionProfile = getConnectionProfile((organization));\n if (!connectionProfile.certificateAuthorities) {\n throw new Error ('Loaded connection profile is not valid. CA is missing.');\n }\n\n let fabricClient = new FabricClient();\n fabricClient.loadFromConfig(connectionProfile);\n await fabricClient.initCredentialStores();\n\n return fabricClient;\n}", "function getGithubService_() {\n return OAuth2.createService('GitHub')\n .setAuthorizationBaseUrl('https://github.com/login/oauth/authorize')\n .setTokenUrl('https://github.com/login/oauth/access_token')\n .setClientId(CLIENT_ID)\n .setClientSecret(CLIENT_SECRET)\n .setCallbackFunction('authCallback')\n .setPropertyStore(PropertiesService.getUserProperties())\n .setScope('repo'); \n}", "static fromUserPoolClientId(scope, id, userPoolClientId) {\n class Import extends core_1.Resource {\n constructor() {\n super(...arguments);\n this.userPoolClientId = userPoolClientId;\n }\n get userPoolClientSecret() {\n throw new Error('UserPool Client Secret is not available for imported Clients');\n }\n }\n return new Import(scope, id);\n }", "static from(offerCreate) {\n var _a, _b, _c, _d;\n // takerGets and takerPays are required fields\n const takerGetsCurrencyAmount = (_a = offerCreate.getTakerGets()) === null || _a === void 0 ? void 0 : _a.getValue();\n if (!takerGetsCurrencyAmount) {\n throw new __1.XrpError(__1.XrpErrorType.MalformedProtobuf, 'OfferCreate protobuf is missing `takerGets` field.');\n }\n const takerGets = xrp_currency_amount_1.default.from(takerGetsCurrencyAmount);\n const takerPaysCurrencyAmount = (_b = offerCreate.getTakerPays()) === null || _b === void 0 ? void 0 : _b.getValue();\n if (!takerPaysCurrencyAmount) {\n throw new __1.XrpError(__1.XrpErrorType.MalformedProtobuf, 'OfferCreate protobuf is missing `takerPays` field.');\n }\n const takerPays = xrp_currency_amount_1.default.from(takerPaysCurrencyAmount);\n const expiration = (_c = offerCreate.getExpiration()) === null || _c === void 0 ? void 0 : _c.getValue();\n const offerSequence = (_d = offerCreate.getOfferSequence()) === null || _d === void 0 ? void 0 : _d.getValue();\n return new XrpOfferCreate(takerGets, takerPays, expiration, offerSequence);\n }", "function createWithHash(context) {\n if (context.data.hash) {\n // user provided password hash\n context.data.password = context.data.hash;\n delete context.data.hash;\n return Promise.resolve(context);\n }\n else {\n // hash the provided password\n return Local.hooks.hashPassword()(context);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called by Unity Retruns gesture label
function getGestureAsString() { return poseLabel; }
[ "getLabel() { return this.labelP.innerText; }", "getInteraction( label) {\n\t\treturn Ithis.NTERACTIONS[label];\n\t}", "function CLC_Content_FindLabelText(target){\r\n var logicalLineage = CLC_GetLogicalLineage(target);\r\n var labelText = \"\";\r\n for (var i=0; i < logicalLineage.length; i++){\r\n if (logicalLineage[i].tagName && (logicalLineage[i].tagName.toLowerCase() == \"label\")){\r\n labelText = labelText + \" \" + logicalLineage[i].textContent;\r\n }\r\n }\r\n return labelText;\r\n }", "labelCurrentTrack() {\n\t\tlet labl = 'empty';\n\t\tif (this.trks[tpos].usedInstruments.length === 1) {\n\t\t\tif (this.trks[tpos].hasPercussion) {\n\t\t\t\tlabl = 'Percussion';\n\t\t\t} else {\n\t\t\t\tlabl = getInstrumentLabel(this.trks[tpos].usedInstruments[0]);\n\t\t\t}\n\t\t} else if (this.trks[tpos].usedInstruments.length > 1) {\n\t\t\tlabl = 'Mixed Track';\n\t\t}\n\t\tthis.trks[tpos].label = `${labl} ${this.getLabelNumber(labl)}`;\n\t}", "label(attributeName) {\n const arg = this.args[attributeName];\n return arg ? arg.label : null;\n }", "function _getTouchEventName(instance, eventName) {\n \n var settings = instance.data('options');\n \n if (!_isTouchDevice() && settings.emulateTouchEvents) {\n switch (eventName) {\n case 'touchstart' : return 'mousedown';\n case 'touchend' : return 'mouseup';\n case 'touchmove' : return 'mousemove';\n }\n }\n \n return eventName;\n \n }", "getPhaseName() {\n let currentPhase = this.props.phases[this.props.phaseIndex];\n if (currentPhase.title === \"Voting\") {\n return \"Time to Vote!\";\n }\n\n let outputString = (currentPhase.speaker === 1 ? this.props.player1 : this.props.player2);\n outputString += \" - \" + currentPhase.title;\n return outputString;\n }", "setupGestures() {\n // Subclasses may override.\n }", "get URL_GESTURES_HELP() {\n return \"http://firefm.sourceforge.net/help/#gestures\"; }", "function identifyGesture(args) {\n\tif ((args.left - args.right) != 0) {\n\t\t/*\n\t\t * If there's no follow-up gesture within 2.5 seconds, reset state\n\t\t * this prevents actions occuring at varied time intervals being\n\t\t * detected as belonging to the same gesture\n\t\t */\n\t\tclearInterval(inactivityClearer);\n\t\tinactivityClearer = setTimeout(inactivityClear, 2500);\n\t}\n\t\n\t/*\n\t * There is a cool down period between successive gesture identifcation\n\t * If still in the cool down period, ignore samples coming in\n\t */\n\tif (coolDownRemaining > 0) {\n\t\tcoolDownRemaining--;\n\t\treturn;\n\t}\n\n\t/*\n\t * Cool Down done - process the sample if the values exceed the minimum threshold\n\t *\n\t * Thresholds determined by experimentation\n\t */\n\tvar diff = args.left - args.right;\n\n\tvar dir = (diff < 0) ? -1 : ((diff > 0) ? 1 : 0);\n\n\tif ((diff >= 0 && diff <= 1)) {\n\t\treturn;\n\t}\n\n\t/*\n\t * If there is a change in direction, record it and reset thresholds to\n\t * start a new gesture identification window\n\t */\n\tif (dir != dirInCurrentWindow && dir != 0) {\n\t\tdirInCurrentWindow = dir;\n\t\tdirChanges++;\n\t\tresetThresholds();\n\t\treturn;\n\t}\n\n\t/* \n\t * Read continuous same direction samples that meet these criteria\n\t * and use their averages for gesture identification\n\t */\n\taccumDiff += diff;\n\taccumAmp += args.peakAmp;\n\tsampleReadRemaining--;\n\n\tif (sampleReadRemaining == 0) {\n\t\tvar avgDiff = accumDiff / sampleDecisionThreshold;\n\t\tvar avgAmp = accumAmp / sampleDecisionThreshold;\n\n\t\tconsole.log(\"dir: \", dirChanges, \"diff: \", avgDiff, \"amp: \", avgAmp);\n\t\t\n\t\tvar args = { \"avgDiff\" : avgDiff , \"dirChanges\" : dirChanges };\n\t\t\n\t\tif ((dirChanges == 2 && avgDiff >= 12 && avgAmp < 90) || \n\t\t\t(dirChanges == 1 && avgDiff >= 12 && avgAmp < 90) ||\n\t\t\t(dirChanges > 2)) {\n\t\t\t/* \n\t\t\t * Double Tap motion\n\t\t\t */\n\t\t\targs[\"amp\"] = avgAmp;\n\t\t\tchrome.runtime.sendMessage({\"tab\" : currentTabId, \"message\" : \"Tap\", \"args\": args});\n\n\t\t} else {\n\t\t\t\n\t\t\tif (dirInCurrentWindow == -1) {\n\t\t\t\t/*\n\t\t\t\t * Hand movement Right or Down\n\t\t\t\t */\n\t\t\t\tif (avgAmp > 108) {\n\t\t\t\t\t/* Right */\n\t\t\t\t\tchrome.runtime.sendMessage({\"tab\" : currentTabId, \"message\" : \"Right\",\n\t\t\t\t\t\t\"args\" : args});\n\t\t\t\t} else {\n\t\t\t\t\t/* Down */\n\t\t\t\t\tchrome.runtime.sendMessage({\"tab\" : currentTabId, \"message\" : \"Down\",\n\t\t\t\t\t\t\"args\" : args});\n\t\t\t\t}\n\n\t\t\t} else if (dirInCurrentWindow == 1) {\n\t\t\t\t/* \n\t\t\t\t * Hand movement Left or Up\n\t\t\t\t */\n\t\t\t\tif (avgAmp > 108) {\n\t\t\t\t\t/* Left */\n\t\t\t\t\tchrome.runtime.sendMessage({\"tab\" : currentTabId, \"message\" : \"Left\",\n\t\t\t\t\t\t\"args\" : args});\n\t\t\t\t} else {\n\t\t\t\t\t/* Up */\n\t\t\t\t\tchrome.runtime.sendMessage({\"tab\" : currentTabId, \"message\" : \"Up\",\n\t\t\t\t\t\t\"args\" : args});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Reset thresholds on detected actions\n\t\t */\n\t\tresetThresholds();\n\t\tcoolDownRemaining = coolDownDefault;\n\t\tdirInCurrentWindow = 0;\n\t\tdirChanges = 0;\n\t}\n}", "function listenForRestaurantname() {\n chrome.runtime.onMessage.addListener(function (request, sender) {\n if (request.action == \"getName\") {\n restaurantName.innerText = request.source;\n }\n });\n}", "getLabel() {\n const titleElement = this._titles?.get(0)?._elementRef.nativeElement;\n // If there is no explicit title element, the unscoped text content\n // is treated as the list item title.\n const labelEl = titleElement || this._unscopedContent?.nativeElement;\n return labelEl?.textContent || '';\n }", "getCurrentAdventureName() {\n\t\t\treturn currentAdventure.adventure[0].title;\n\t\t}", "takeDamage() {\n return `${this.name} took damage.`;\n }", "function displayEnemyLabel(){\n\n // player1 label\n $(\"#enemy-name1\").text(player1.playerName);\n $(\"#enemy-image1\").attr(\"src\",player1.playerImageAddr);\n $(\"#enemy-health1\").text(player1.healthPoint);\n\n // player2 label\n $(\"#enemy-name2\").text(player2.playerName);\n $(\"#enemy-image2\").attr(\"src\",player2.playerImageAddr);\n $(\"#enemy-health2\").text(player2.healthPoint);\n\n // player3 label\n $(\"#name3\").text(player3.playerName);\n $(\"#enemy-name3\").attr(\"src\",player3.playerImageAddr);\n $(\"#enemy-health3\").text(player3.healthPoint);\n\n // player4 label\n $(\"#enemy-name4\").text(player4.playerName);\n $(\"#enemy-image4\").attr(\"src\",player4.playerImageAddr);\n $(\"#enemy-health4\").text(player4.healthPoint);\n}", "function displayTrackName() {\n\t\ttrackName.textContent = order[0].name;\n\t\tdisplayAnimation();\n\t}", "function handleClick(evt) {\n const id = evt.target.id;\n let [categoryID, clueID] = id.split('-');\n let clue = categories[categoryID].clues[clueID];\n\n let clueText;\n if (clue.showing = false) {\n clueText = clue.question;\n clue.showing = 'showing question';\n } else if(clue.showing === 'showing question'){\n clueText = clue.answer;\n clue.showing = 'showing answer';\n } else {\n return;\n }\n $(`#${categoryID}-${clueID}`).html(clueText)\n}", "function mousePressed() {\n size = 10;\n word = lexicon.randomWord('nn', 3);\n voice.speak(word);\n}", "function TLabel(){}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fix a vue instance Lifecycle to vue 1/2 (just the basic elements, is not a real parser, so this work only if your code is compatible with both) (Waiting for testing)
function VueFixer(vue) { var vue2 = !window.Vue || !window.Vue.partial; var mixin = { computed: { vue2: function vue2() { return !this.$dispatch; } } }; if (!vue2) { //translate vue2 attributes to vue1 if (vue.beforeCreate) { mixin.create = vue.beforeCreate; delete vue.beforeCreate; } if (vue.beforeMount) { vue.beforeCompile = vue.beforeMount; delete vue.beforeMount; } if (vue.mounted) { vue.ready = vue.mounted; delete vue.mounted; } } else { //translate vue1 attributes to vue2 if (vue.beforeCompile) { vue.beforeMount = vue.beforeCompile; delete vue.beforeCompile; } if (vue.compiled) { mixin.compiled = vue.compiled; delete vue.compiled; } if (vue.ready) { vue.mounted = vue.ready; delete vue.ready; } } if (!vue.mixins) { vue.mixins = []; } vue.mixins.unshift(mixin); return vue; }
[ "function resetComponentInstances() {\n Blockly.ComponentInstances = {};\n\n Blockly.ComponentInstances.addInstance = function(name, uid) {\n if (DEBUG) console.log(\"RAM ComponentInstances.addInstance \" + name);\n Blockly.ComponentInstances[name] = {};\n Blockly.ComponentInstances[name].uid = uid;\n Blockly.ComponentInstances[name].blocks = [];\n }\n\n Blockly.ComponentInstances.haveInstance = function(name, uid) {\n return Blockly.ComponentInstances[name] != undefined\n && Blockly.ComponentInstances[name].uid == uid;\n }\n\n Blockly.ComponentInstances.addBlockName = function(name, blockName) {\n Blockly.ComponentInstances[name].blocks.push(blockName);\n }\n\n}", "function normalizeComponent(\nscriptExports,\nrender,\nstaticRenderFns,\nfunctionalTemplate,\ninjectStyles,\nscopeId,\nmoduleIdentifier,/* server only */\nshadowMode/* vue-cli only */)\n{\n// Vue.extend constructor export interop\nvar options=typeof scriptExports==='function'?\nscriptExports.options:\nscriptExports;\n\n// render functions\nif(render){\noptions.render=render;\noptions.staticRenderFns=staticRenderFns;\noptions._compiled=true;\n}\n\n// functional template\nif(functionalTemplate){\noptions.functional=true;\n}\n\n// scopedId\nif(scopeId){\noptions._scopeId='data-v-'+scopeId;\n}\n\nvar hook;\nif(moduleIdentifier){// server build\nhook=function hook(context){\n// 2.3 injection\ncontext=\ncontext||// cached call\nthis.$vnode&&this.$vnode.ssrContext||// stateful\nthis.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext;// functional\n// 2.2 with runInNewContext: true\nif(!context&&typeof __VUE_SSR_CONTEXT__!=='undefined'){\ncontext=__VUE_SSR_CONTEXT__;\n}\n// inject component styles\nif(injectStyles){\ninjectStyles.call(this,context);\n}\n// register component module identifier for async chunk inferrence\nif(context&&context._registeredComponents){\ncontext._registeredComponents.add(moduleIdentifier);\n}\n};\n// used by ssr in case component is cached and beforeCreate\n// never gets called\noptions._ssrRegister=hook;\n}else if(injectStyles){\nhook=shadowMode?\nfunction(){injectStyles.call(this,this.$root.$options.shadowRoot);}:\ninjectStyles;\n}\n\nif(hook){\nif(options.functional){\n// for template-only hot-reload because in that case the render fn doesn't\n// go through the normalizer\noptions._injectStyles=hook;\n// register for functioal component in vue file\nvar originalRender=options.render;\noptions.render=function renderWithStyleInjection(h,context){\nhook.call(context);\nreturn originalRender(h,context);\n};\n}else{\n// inject component registration as beforeCreate hook\nvar existing=options.beforeCreate;\noptions.beforeCreate=existing?\n[].concat(existing,hook):\n[hook];\n}\n}\n\nreturn{\nexports:scriptExports,\noptions:options};\n\n}", "_initElements () {\n this.tablist = this.element.querySelector(this.tablistSelector)\n this.tabs = Array.from(this.element.querySelectorAll(this.tabSelector))\n this.panels = Array.from(this.element.querySelectorAll(this.panelSelector))\n\n // The data-rvt-tablist attribute was added in Rivet 2.4.0. To maintain\n // backward compatibility, the code below infers which element is the\n // tablist if the data-rvt-tablist attribute is not present.\n\n if (!this.tablist) {\n this.tablist = this.tabs[0].parentElement\n }\n }", "function install(Vue) {\n if (install.installed) return;\n install.installed = true;\n Vue.component(\"Segel\", _components_main__WEBPACK_IMPORTED_MODULE_0__[/* default */ \"a\"]);\n}", "constructor() {\n super('App Start', 'core.rosie.trigger.lifecycle');\n }", "function initInstanceElement(el) {\n const visible = $(el).data('visible');\n $(el).addClass('instance')\n .toggleClass('invisible-instance', visible !== true && visible !== 'true')\n .on('click', function(e) {\n e.stopPropagation();\n selectInstance(this);\n })\n .on('blur', function(e) {\n })\n .on('keydown', function(e) {\n if (e.key === 'Escape') {\n exitInlineEditing(this);\n }\n })\n .on('dblclick', function(e) {\n e.stopPropagation();\n enterInlineEditing(this);\n })\n // use mouseover and mouseout for hover styling instead of css :hover\n // to avoid styling parent instance elements\n .on('mouseover', function(e) {\n e.stopPropagation();\n $(this).addClass('hover');\n })\n .on('mouseout', function(e) {\n $(this).removeClass('hover');\n });\n }", "render (h) { return h(App, { props: this.$el.dataset }) }", "function transformOldSlotSyntax(node) {\n if (!node.children) {\n return;\n }\n\n node.children.forEach((child) => {\n if (_.has(child.attribs, 'slot')) {\n const vslotShorthandName = `#${child.attribs.slot}`;\n child.attribs[vslotShorthandName] = '';\n delete child.attribs.slot;\n }\n });\n}", "_initMarkdownAndPreviewSection() {\n this.$mdEditorContainerEl = this.$containerEl.find('.te-md-container .te-editor');\n this.$previewEl = this.$containerEl.find('.te-md-container .te-preview');\n }", "_processNodes(){\n this.shadowRoot\n .querySelector('slot')\n .assignedNodes()\n .forEach((n) => this._processNode(n));\n }", "destroy() {\n\t\tthis.directives.forEach(\n\t\t\tbinding => Reflex.unobserve(this, null, null, {tags:['#directive', binding]})\n\t\t);\n\t\tif (this.dataBlockScript && globalParams.hideDataBlockScript) {\n\t\t\tthis.prepend(this.dataBlockScript);\n\t\t}\n\t}", "constructor() {\n super();\n this.isContainer = false;\n }", "wakeUp() {\n const self = this;\n // Only re render VizTool (should be super fast)\n self.render();\n }", "initHttpMethods () {\n if (Vue.prototype.$api === undefined) {\n Vue.prototype.$api = null;\n Vue.prototype.$get = this.$get.bind(this);\n Vue.prototype.$getJsonp = this.$getJsonp.bind(this);\n Vue.prototype.$post = this.$post.bind(this);\n Vue.prototype.$put = this.$put.bind(this);\n Vue.prototype.$patch = this.$patch.bind(this);\n Vue.prototype.$delete = this.$delete.bind(this);\n Vue.prototype.$api = new ApiService(this.environment, this._token);\n }\n }", "onOptionsChange(options) {\n this.vssue.setOptions(options);\n }", "PromoteUnconfiguredComponents(string, Variant, Variant) {\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}", "_setAuxWeb3Instance() {\n const oThis = this,\n wsProvider = oThis.ic().configStrategy.auxGeth.readOnly.wsProvider;\n\n oThis.web3Instance = web3Provider.getInstance(wsProvider).web3WsProvider;\n }", "init() {\n this.#elemetn = this.getElement(this.UiSelectors.timer);\n }", "function finalizeInitialChildren(newElement, type, props, rootContainerInstance) {\n return newElement.finalizeBeforeMount(type, props, rootContainerInstance);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for conciseness in defining templates How to use call this function with these parameters nodeId : [0,14] id of target node ex. highlightNode(2) only 1 node can highlighted if want more node to be highlighted, contact previous programmer na ja
function highlightNode(nodeId) { var node = myDiagram.findNodeForKey(nodeId++); // console.log(node); if (node !== null) { // make sure the selected node is in the viewport myDiagram.scrollToRect(node.actualBounds); // move the large yellow node behind the selected node to highlight it highlighter.location = new go.Point(node.location.x + 40, node.location.y + 40); // console.log(node.location) // console.log(highlighter.location) } }
[ "function leafContentHighlight(nodeId, treeType, clickId, contentType, viewType, predecessorId)\r\n{\r\n if(nodeId>0)\r\n {\r\n var previousClickId = document.getElementById(\"previousClickId\").value;\r\n var previousLeafContentId = document.getElementById(\"previousLeafContentId\").value; \r\n\r\n if(treeType == 'document')\r\n {\r\n\r\n if(contentType=='seed')\r\n {\r\n var previousContentId = 'divSeed';\r\n var currentContentId = 'divSeed';\r\n\r\n var currentAddClassName = 'nodeBgColorSelect';\r\n var currentRemoveClassName = 'seedBackgroundColorNew'; \r\n var previousAddClassName = 'seedBackgroundColorNew';\r\n var previousRemoveClassName = 'nodeBgColorSelect';\r\n\r\n //used for leaf content highlight remove and add original class\r\n var oppositeClassAdd = 'treeLeafRowStyle';\r\n var oppositeClassRemove = 'nodeBgColorSelect';\r\n var oppositePreviousContentId = 'docLeafContent'+previousLeafContentId;\r\n \r\n }\r\n else\r\n {\r\n var previousContentId = 'docLeafContent'+previousLeafContentId;\r\n var currentContentId = 'docLeafContent'+nodeId;\r\n\r\n var currentAddClassName = 'nodeBgColorSelect';\r\n var currentRemoveClassName = 'treeLeafRowStyle'; \r\n var previousAddClassName = 'treeLeafRowStyle';\r\n var previousRemoveClassName = 'nodeBgColorSelect';\r\n\r\n //used for seed content highlight remove and add original class\r\n var oppositeClassAdd = 'seedBackgroundColorNew';\r\n var oppositeClassRemove = 'nodeBgColorSelect';\r\n var oppositePreviousContentId = 'divSeed';\r\n }\r\n }\r\n else if(treeType == 'discuss')\r\n {\r\n\r\n if(viewType=='real_time')\r\n {\r\n var contentDivId = 'chat_block';\r\n }\r\n else\r\n {\r\n var contentDivId = 'discussLeafContent';\r\n }\r\n\r\n if(contentType=='seed')\r\n {\r\n var previousContentId = 'divSeed';\r\n var currentContentId = 'divSeed';\r\n\r\n var currentAddClassName = 'nodeBgColorSelect';\r\n var currentRemoveClassName = 'seedBackgroundColorNew'; \r\n var previousAddClassName = 'seedBackgroundColorNew';\r\n var previousRemoveClassName = 'nodeBgColorSelect';\r\n\r\n //used for leaf content highlight remove and add original class\r\n var oppositeClassAdd = 'treeLeafRowStyle';\r\n var oppositeClassRemove = 'nodeBgColorSelect';\r\n\r\n var oppositePreviousContentId = contentDivId+previousLeafContentId;\r\n \r\n }\r\n else\r\n {\r\n var previousContentId = contentDivId+previousLeafContentId;\r\n var currentContentId = contentDivId+nodeId;\r\n\r\n var currentAddClassName = 'nodeBgColorSelect';\r\n var currentRemoveClassName = 'treeLeafRowStyle'; \r\n var previousAddClassName = 'treeLeafRowStyle';\r\n var previousRemoveClassName = 'nodeBgColorSelect';\r\n\r\n //used for seed content highlight remove and add original class\r\n var oppositeClassAdd = 'seedBackgroundColorNew';\r\n var oppositeClassRemove = 'nodeBgColorSelect';\r\n var oppositePreviousContentId = 'divSeed';\r\n }\r\n }\r\n else if(treeType == 'task')\r\n {\r\n\r\n var previousPredecessorId = document.getElementById(\"previousPredecessorId\").value;\r\n if(previousPredecessorId>0)\r\n {\r\n $('#taskLeafContent'+previousPredecessorId).removeClass('nodeBgColorSelectNew');\r\n }\r\n\r\n if(predecessorId>0)\r\n {\r\n var contentDivId = 'subTaskLeafContent';\r\n var oppositeContentDivId = 'taskLeafContent'+previousLeafContentId;\r\n $('#'+oppositeContentDivId).removeClass('nodeBgColorSelectNew');\r\n\r\n $('#taskLeafContent'+predecessorId).addClass('nodeBgColorSelectNew');\r\n\r\n document.getElementById(\"previousPredecessorId\").value = predecessorId; \r\n }\r\n else\r\n {\r\n var contentDivId = 'taskLeafContent';\r\n var oppositeContentDivId = 'subTaskLeafContent'+previousLeafContentId;\r\n $('#'+oppositeContentDivId).removeClass('nodeBgColorSelectNew');\r\n\r\n document.getElementById(\"previousPredecessorId\").value = 0;\r\n }\r\n\r\n if(contentType=='seed')\r\n {\r\n var previousContentId = 'divSeed';\r\n var currentContentId = 'divSeed';\r\n\r\n var currentAddClassName = 'nodeBgColorSelect';\r\n var currentRemoveClassName = 'seedBackgroundColorNew'; \r\n var previousAddClassName = 'seedBackgroundColorNew';\r\n var previousRemoveClassName = 'nodeBgColorSelectNew';\r\n\r\n //used for leaf content highlight remove and add original class\r\n var oppositeClassAdd = '';\r\n var oppositeClassRemove = 'nodeBgColorSelectNew';\r\n var oppositePreviousContentId = contentDivId+previousLeafContentId;\r\n \r\n }\r\n else\r\n {\r\n var previousContentId = contentDivId+previousLeafContentId;\r\n var currentContentId = contentDivId+nodeId;\r\n\r\n var currentAddClassName = 'nodeBgColorSelectNew';\r\n var currentRemoveClassName = ''; \r\n var previousAddClassName = '';\r\n var previousRemoveClassName = 'nodeBgColorSelectNew';\r\n\r\n //used for seed content highlight remove and add original class\r\n var oppositeClassAdd = 'seedBackgroundColorNew';\r\n var oppositeClassRemove = 'nodeBgColorSelect';\r\n var oppositePreviousContentId = 'divSeed';\r\n }\r\n }\r\n else if(treeType == 'contact')\r\n {\r\n\r\n if(contentType=='seed')\r\n {\r\n var previousContentId = 'divSeed';\r\n var currentContentId = 'divSeed';\r\n\r\n var currentAddClassName = 'nodeBgColorSelect';\r\n var currentRemoveClassName = 'seedBackgroundColorNew'; \r\n var previousAddClassName = 'seedBackgroundColorNew';\r\n var previousRemoveClassName = 'nodeBgColorSelect';\r\n\r\n //used for leaf content highlight remove and add original class\r\n var oppositeClassAdd = 'seedBackgroundColorNew';\r\n var oppositeClassRemove = 'nodeBgColorSelect';\r\n var oppositePreviousContentId = 'contactLeafContent'+previousLeafContentId;\r\n \r\n }\r\n else\r\n {\r\n var previousContentId = 'contactLeafContent'+previousLeafContentId;\r\n var currentContentId = 'contactLeafContent'+nodeId;\r\n\r\n var currentAddClassName = 'nodeBgColorSelect';\r\n var currentRemoveClassName = 'seedBackgroundColorNew'; \r\n var previousAddClassName = 'seedBackgroundColorNew';\r\n var previousRemoveClassName = 'nodeBgColorSelect';\r\n\r\n //used for seed content highlight remove and add original class\r\n var oppositeClassAdd = 'seedBackgroundColorNew';\r\n var oppositeClassRemove = 'nodeBgColorSelect';\r\n var oppositePreviousContentId = 'divSeed';\r\n }\r\n }\r\n\r\n if(contentType=='seed')\r\n {\r\n $('#'+oppositePreviousContentId).addClass(oppositeClassAdd);\r\n $('#'+oppositePreviousContentId).removeClass(oppositeClassRemove); \r\n }\r\n else\r\n {\r\n $('#'+oppositePreviousContentId).addClass(oppositeClassAdd);\r\n $('#'+oppositePreviousContentId).removeClass(oppositeClassRemove);\r\n }\r\n\r\n if(previousClickId>0)\r\n {\r\n //used for leaf content\r\n $('#'+previousContentId).addClass(previousAddClassName);\r\n $('#'+previousContentId).removeClass(previousRemoveClassName);\r\n\r\n //used for timeline content\r\n $('#timeline_content_'+previousClickId).removeClass('timelineContentDivStyle');\r\n }\r\n\r\n //used for leaf content\r\n $('#'+currentContentId).removeClass(currentRemoveClassName);\r\n $('#'+currentContentId).addClass(currentAddClassName);\r\n\r\n //used for timeline content\r\n $('#timeline_content_'+clickId).addClass('timelineContentDivStyle');\r\n\r\n document.getElementById(\"previousClickId\").value = clickId;\r\n document.getElementById(\"previousLeafContentId\").value = nodeId;\r\n\r\n if($(window).scrollTop() > 130 && contentType!='seed')\r\n {\r\n $(window).scrollTop($('#'+currentContentId).offset().top - $(window).scrollTop());\r\n }\r\n \r\n document.getElementById(currentContentId).focus();\r\n }\r\n}", "function draftLeafContentHighlight(nodeId, clickId)\r\n{\r\n if(nodeId>0)\r\n {\r\n var previousClickId = document.getElementById(\"previousClickId\").value;\r\n var previousLeafContentId = document.getElementById(\"previousLeafContentId\").value; \r\n\r\n if(previousClickId != clickId)\r\n {\r\n //used for leaf content\r\n $('#docLeafContent'+nodeId).removeClass('treeLeafRowStyle');\r\n $('#docLeafContent'+nodeId).addClass('nodeBgColorSelect');\r\n \r\n if(previousClickId>0)\r\n {\r\n //used for leaf content\r\n $('#docLeafContent'+previousLeafContentId).addClass('treeLeafRowStyle');\r\n $('#docLeafContent'+previousLeafContentId).removeClass('nodeBgColorSelect');\r\n\r\n //used for timeline content\r\n $('#draft_leaf_content_'+previousClickId).removeClass('timelineContentDivStyle');\r\n }\r\n \r\n //used for timeline content\r\n $('#draft_leaf_content_'+clickId).addClass('timelineContentDivStyle');\r\n\r\n document.getElementById(\"previousClickId\").value = clickId;\r\n document.getElementById(\"previousLeafContentId\").value = nodeId;\r\n\r\n if($(window).scrollTop() > 130)\r\n {\r\n $(window).scrollTop($('#docLeafContent'+nodeId).offset().top - $(window).scrollTop());\r\n }\r\n \r\n document.getElementById('docLeafContent'+nodeId).focus();\r\n }\r\n }\r\n}", "function highlightNode(d) {\n d3.select(\"#node_\" + d.idx)\n .transition().duration(100)\n .attr(\"r\",sizes[d.idx]*r*1.3)\n .style(\"stroke\",d3.rgb(0,0,0));\n}", "function changeNoteHighlight(id) {\n\n if (id == undefined) { //remove highlighting from currently highlighted element\n var id = findCurrentNote();\n var sourceElement = findNoteElement(id);\n sourceElement.classList.remove('active-note');\n }\n else { //add highlighting to selected element\n if (id == -1) {\n var note = raw_notes[raw_notes.length-1];\n id = note[\"id\"];\n }\n var targetElement = findNoteElement(id);\n targetElement.classList.add('active-note');\n }\n\n}", "function anno_highlight(xpath) {\n //if element is already highlighted\n if (anno_getElementByXpath(xpath).id != \"mark\" || !(anno_getElementByXpath(xpath).id)) {\n // hightlight selected element, calling function\n $j(anno_getElementByXpath(xpath)).wrapInner(\"<span id='mark' style='background:yellow;'></span>\");\n annolet_pushToStack(xpath);\n } else {\n console.log('highlighted already');\n }\n}", "function setTreeViewCurrentNode(treeView, nodeId) {\n var allNodes = [];\n function traverse(nodes) {\n for (var i = 0, len = nodes.length; i < len; i++) {\n if (nodes[i].nodes.length > 0) {\n traverse(nodes[i].nodes);\n }\n allNodes.push(nodes[i]);\n }\n }\n\n traverse(treeView.roots);\n\n for (var i = allNodes.length - 1; i >= 0; i--) {\n if (allNodes[i].bindingContext.id === nodeId) {\n allNodes[i].makeCurrent();\n\n var parent = allNodes[i].parent;\n while (parent !== treeView) {\n parent.expand();\n parent = parent.parent;\n }\n }\n }\n }", "function RenderMainNode(SemTree, i, x, y, Scale) {\n var Html = \"\";\n var X = (SemTree[i].x - XOffset) * Zoom * Scale + x;\n var Y = (SemTree[i].y - YOffset) * Zoom * Scale + y;\n UniqueId += 1;\n if (HighlightNode == i) {\n SVG_SetPen(2);\n } else {\n SVG_SetPen(1);\n }\n if ((HighlightNode == i) || (HighlightNode == -1)) {\n SVG_SetOpacity(1);\n } else {\n SVG_SetOpacity(0.2);\n }\n SVG_SetInk(\"#ff0000\");\n SVG_SetFill(\"#ff0000\");\n Html += SVG_Circle(X, Y, 4);\n SVG_SetInk(\"#000000\");\n if (HighlightNode == i) {\n SVG_SetFill(\"#ffdddd\");\n } else {\n SVG_SetFill(\"#ffffff\");\n }\n Html += SVG_GroupStart(\"noname\" + UniqueId, \"style=\\\"cursor:pointer;\\\" onmousedown=\\\"Highlight(\" + i + \",-1)\\\"\");\n if (HighlightNode == i) {\n Html += SVG_Poly([X, Y, X, Y + 35, X + 100, Y + 35, X + 100, Y + 10, X + 10, Y + 10, X, Y]);\n SVG_SetFontSize(\"18\");\n }\n else {\n Html += SVG_Poly([X, Y, X, Y + 30, X + 100, Y + 30, X + 100, Y + 10, X + 10, Y + 10, X, Y]);\n SVG_SetFontSize(\"15\");\n }\n SVG_SetFont(\"arial\");\n SVG_SetFontRotate(0);\n SVG_SetFontAlign(\"left\");\n Html += SVG_Text(X + 5, Y + 15, SemTree[i].label);\n Html += SVG_GroupClose(\"\");\n return (Html);\n}", "function EntityViewerHighlighter(dm_entity_id, entity_id) {\t\n\t//If a dm_entity_id (used for the title) has been passed...\n\tif (dm_entity_id !== null){\n\t\t//Highlight the title of the current panel in the Entity Viewer\n\t\t//(Could make this a bit more accurate by actually finding the specific panel)\n\t\tvar selectedPanel = $(\"#tabs3 div.ui-tabs-panel[aria-hidden='false']\");\n\t\tselectedPanel.find('h2').effect( \"highlight\", {color:\"#efe8be\"}, 1500 )\n\t}\t\n\t//If an entity_id has been passed...\n\tif (entity_id !== null){\t\n\t\t//Get the entity, get the tree, and send these to the jQTree to highlight (\"select\") the tree node\n\t\tvar $entity = \"entity~\"+entity_id;\n\t\tvar $tree = $('#definitely_tree_'+dm_entity_id);\n\t\tvar node = $tree.tree('getNodeById', $entity);\t\n\t\t$tree.tree('selectNode', node);\n\t}\n}", "function RenderSubNode(SemTree, i, j, x, y, Scale) {\n var Html = \"\";\n var X = (SemTree[i].x - XOffset) * Zoom * Scale + x;\n var Y = (SemTree[i].y - YOffset) * Zoom * Scale + y;\n var XX = (SemTree[i].subnodes[j].x - XOffset) * Zoom * Scale + x;\n var YY = (SemTree[i].subnodes[j].y - YOffset) * Zoom * Scale + y;\n UniqueId += 1;\n SVG_SetInk(\"#ff0000\");\n if ((HighlightNode == i) || (HighlightNode == -1)) {\n SVG_SetOpacity(0.5);\n } else {\n SVG_SetOpacity(0.1);\n }\n Html += SVG_Line(X, Y, XX, YY);\n Html += SVG_GroupStart(\"noname\" + UniqueId, \"style=\\\"cursor:pointer;\\\" onmousedown=\\\"Highlight(\" + i + \",\" + j + \")\\\"\");\n if ((HighlightNode == i) || (HighlightNode == -1)) {\n SVG_SetOpacity(0.7);\n } else {\n SVG_SetOpacity(0.2);\n }\n Html += SVG_Line(XX - 3, YY - 3, XX + 3, YY + 3);\n Html += SVG_Line(XX - 3, YY + 3, XX + 3, YY - 3);\n SVG_SetInk(\"#000000\");\n if ((HighlightNode == i) && (HighlightSubnode == j)) {\n SVG_SetFill(\"#ff9999\");\n }\n else if (MultiNodes[SemTree[i].subnodes[j].label] == \"y\") {\n SVG_SetFill(\"#dddddd\");\n }\n else {\n SVG_SetFill(\"#ffffff\");\n }\n SVG_SetFont(\"arial\");\n SVG_SetFontRotate(0);\n SVG_SetFontAlign(\"left\");\n if (HighlightNode == i) {\n Html += SVG_Poly([XX + 1, YY, XX + 10, YY + 10, XX + 100, YY + 10, XX + 100, YY - 10, XX + 10, YY - 10, XX + 1, YY]);\n SVG_SetFontSize(\"14\");\n Html += SVG_Text(XX + 10, YY - 5, SemTree[i].subnodes[j].label);\n }\n else {\n Html += SVG_Poly([XX + 1, YY, XX + 6, YY + 6, XX + 100, YY + 6, XX + 100, YY - 6, XX + 6, YY - 6, XX + 1, YY]);\n SVG_SetFontSize(\"10\");\n Html += SVG_Text(XX + 5, YY - 3, SemTree[i].subnodes[j].label);\n }\n Html += SVG_GroupClose(\"\");\n return (Html);\n}", "function ServerBehavior_setSelectedNode(node)\n{\n this.selectedNode = node;\n}", "function switchContent() {\n let nodeId= $(clickedNode).attr('id');\n let node = nodeMap.get(nodeId);\n $(clickedNode).children(\".node_inhalt\").toggleClass(\"invis\");\n if($(clickedNode).children(\".node_inhalt\").hasClass(\"invis\")){\n node.toggleToAbstract();\n node.focus(); }\n else{\n node.toggleToDetailed();\n }\n\n}", "function grabNode(id) {\n return nodesData[id];\n }", "function setSelectedNode(node) {\n selected_node = node;\n var selectedNodeLabel = d3.select('#edit-pane');\n // update selected node label\n selectedNodeLabel.html(selected_node ? '<strong>' + selected_node.lbl + ': ' + selected_node.wid + '</strong>' : 'No state selected');\n\n }", "function highlightSolvers(d) {\n var node = \"[\" + d.name.toString() + \"]\";\n var query = '.solver-container table tr[data-node=\"' + node +'\"]';\n\n $('.solver-container table tr').removeClass(\"highlight\");\n $(query).addClass(\"highlight\");\n\n}", "function highlightText(node, params) {\n var currentIndex = params.currentIndex,\n text = node.nodeValue.trim(),\n result = true,\n spaceBuffer = 1,\n nodeIndex = params.nodeIndex;\n\n // track whitespace trimmed, so replaced text node will be identical to existing\n var leftTrimNum = node.nodeValue.indexOf(text);\n var leftTrim = node.nodeValue.substring(0, leftTrimNum);\n var rightTrimNum = node.nodeValue.length - text.length - leftTrimNum;\n var rightTrim = node.nodeValue.substring(node.nodeValue.length - rightTrimNum);\n\n // for first node, do not include space at start of text\n if (currentIndex === 0) {\n spaceBuffer = 0;\n }\n\n var startChar = -1, endChar = -1;\n var nextIndex = currentIndex + text.length + spaceBuffer;\n /*console.log(text.length + \" \" + text);\n console.log(\"current index: \" + currentIndex);\n console.log(\"start index: \" + params.startIndex);\n console.log(\"end index: \" + params.endIndex);\n console.log(\"next index: \" + nextIndex);*/\n // highlight from start of text node\n if (currentIndex >= params.startIndex && currentIndex < params.endIndex) {\n startChar = 0;\n }\n // highlight from middle of text node\n else if (currentIndex < params.startIndex && nextIndex >= params.startIndex) {\n startChar = params.startIndex - currentIndex - spaceBuffer;\n }\n\n // highlight to end of text node\n if (nextIndex >= params.startIndex && nextIndex < params.endIndex) {\n endChar = null;\n }\n // highlight to middle of text node\n else if (currentIndex < params.endIndex && nextIndex >= params.endIndex) {\n endChar = text.length - (nextIndex - params.endIndex);\n // stop iterating when current index is past highlight target\n result = false;\n }\n console.log(\"start: \" + startChar);\n console.log(\"end: \" + endChar);\n currentIndex = nextIndex;\n\n if (startChar !== -1) {\n var leftText = text.substring(0, startChar);\n var rightText = \"\";\n var markText = \"\";\n if (endChar !== null) {\n rightText = text.substring(endChar);\n markText = text.substring(startChar, endChar);\n } else {\n markText = text.substring(startChar);\n }\n\n var tempNode = document.createElement(\"span\");\n tempNode.setAttribute(\"name\", \"twoReceiptHighlight\");\n tempNode.setAttribute(\"data-node-index\", nodeIndex);\n tempNode.innerHTML = leftTrim + leftText +\n \"<mark>\" + markText + \"</mark>\" +\n rightText + rightTrim;\n node.parentNode.insertBefore(tempNode, node);\n node.parentNode.removeChild(node);\n\n nodeIndex++;\n }\n\n return {\n \"startIndex\": params.startIndex,\n \"endIndex\": params.endIndex,\n \"currentIndex\": currentIndex,\n \"nodeIndex\": nodeIndex,\n \"result\": result\n };\n}", "function getSelectedNodeIds() {\n return figma.currentPage.selection.filter(({ type }) => type === \"VECTOR\").map(({ id }) => id);\n}", "function ServerBehavior_getSelectedNode()\n{\n return this.selectedNode;\n}", "function nr_basicRenderNode(node,divid,titleid)\n{\n\tvar div = $('#'+divid);\n\tdiv.empty();\n\tvar title = $('#'+titleid);\n\tvar ttext = su_getNodeShortLabel(node);\n\ttitle.text(ttext);\n\tdocument.title=ttext;\n\n\t// loop over properties\n\tparr = su_getNodePropertyAndDisplayNames(node.type,node);\n\tvar len = parr.length;\n\tvar prop = null;\n\tvar disp = null;\n\tvar val = null;\n\tvar row = null;\n\tvar lc = null;\n\tvar rc = null;\n\tfor(var i=0; i<len; i++)\n\t{\n\t\tprop = parr[i][0];\n\t\tdisp = parr[i][1];\n\t\tval = node[prop];\n\t\tif(isEmpty(val)) val = node[prop.toLowerCase()];\n\t\tif(isEmpty(val)) continue;\n\t\t\n\t\trow = $('<div class=\"w3-row\"></div>');\n\t\tlc = $('<div class=\"w3-col s1 w3-theme-d3 w3-center\"><p>'+disp+'</p></div>');\n\t\trc = $('<div class=\"w3-col s5 w3-theme-l3\"><p>&nbsp;&nbsp;'+val+'</p></div>');\n\t\trow.append(lc);\n\t\trow.append(rc);\n\t\tdiv.append(row);\n\t}\n} // end nr_basicRenderNode", "function highlightTree(\n tree,\n highlighter,\n /**\nAssign styling to a region of the text. Will be called, in order\nof position, for any ranges where more than zero classes apply.\n`classes` is a space separated string of CSS classes.\n*/\n putStyle,\n /**\nThe start of the range to highlight.\n*/\n from = 0,\n /**\nThe end of the range.\n*/\n to = tree.length\n ) {\n let builder = new HighlightBuilder(\n from,\n Array.isArray(highlighter) ? highlighter : [highlighter],\n putStyle\n )\n builder.highlightRange(tree.cursor(), from, to, '', builder.highlighters)\n builder.flush(to)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Based on the parentName, this creates a fully classified name of a property
function getPropertyName(parentName, parent, indexer) { var propertyName = parentName || ""; if (exports.getType(parent) === "array") { if (parentName) { propertyName += "[" + indexer + "]"; } } else { if (parentName) { propertyName += "."; } propertyName += indexer; } return propertyName; }
[ "function createCustomTypeName(type, parent) {\n var parentType = parent ? parent.key : null;\n var words = type.split(/\\W|_|\\-/);\n if (parentType) words.unshift(parentType);\n words = words.map(function (word) {\n return word[0].toUpperCase() + word.slice(1);\n });\n return words.join('') + 'Type';\n}", "function fixStateName(state){\r\n if(state.parent){\r\n state.name = (angular.isObject(state.parent) ? state.parent.name : state.parent) + '.' + state.name;\r\n }\r\n }", "get timezoneName() {\n let parent = this.parent;\n let n = `${this.name}`;\n while (parent) {\n n = `${parent.name}, ${n}`;\n parent = parent.parent;\n }\n return n;\n }", "get parentZoneName() {\n return this.getStringAttribute('parent_zone_name');\n }", "function inheritedChildAlias(childName, parentName, parentAlias, childType) {\n // If the child name has the parent name as a prefix, then we make the assumption that it was\n // constructed from the convention of using `{name}-details` as the name of the child resource. To\n // ensure this is aliased correctly, we must then also replace the parent aliases name in the prefix of\n // the child resource name.\n //\n // For example:\n // * name: \"newapp-function\"\n // * opts.parent.__name: \"newapp\"\n // * parentAlias: \"urn:pulumi:stackname::projectname::awsx:ec2:Vpc::app\"\n // * parentAliasName: \"app\"\n // * aliasName: \"app-function\"\n // * childAlias: \"urn:pulumi:stackname::projectname::aws:s3/bucket:Bucket::app-function\"\n let aliasName = output_1.output(childName);\n if (childName.startsWith(parentName)) {\n aliasName = output_1.output(parentAlias).apply((parentAliasUrn) => {\n const parentAliasName = parentAliasUrn.substring(parentAliasUrn.lastIndexOf(\"::\") + 2);\n return parentAliasName + childName.substring(parentName.length);\n });\n }\n return createUrn(aliasName, childType, parentAlias);\n}", "static concat(parentPath, name) {\n if (parentPath === '/') {\n return `/${name}`;\n }\n\n return `${parentPath}/${name}`;\n }", "function getAggFormNameParents_(parentJson, oldName, newName) {\n var fieldList = [ 'buckets', 'metrics', 'pipelines' ]\n var retVal = {}\n fieldList.forEach(function(aggType) {\n var path = [ \"aggregation_table\", aggType ]\n var jsonArray = Util.getJson(parentJson, path) || []\n jsonArray.forEach(function(json) {\n // If old and new names specified, then mutate names\n if (oldName && (oldName == json.location)) {\n json.location = newName\n }\n var location = json.location || \"automatic\"\n var currArray = retVal[location] || []\n retVal[location] = currArray\n currArray.push(json.name)\n })\n })\n return retVal\n}", "function createUrn(name, type, parent, project, stack) {\n let parentPrefix;\n if (parent) {\n let parentUrn;\n if (Resource.isInstance(parent)) {\n parentUrn = parent.urn;\n }\n else {\n parentUrn = output_1.output(parent);\n }\n parentPrefix = parentUrn.apply((parentUrnString) => {\n const prefix = parentUrnString.substring(0, parentUrnString.lastIndexOf(\"::\")) + \"$\";\n if (prefix.endsWith(\"::pulumi:pulumi:Stack$\")) {\n // Don't prefix the stack type as a parent type\n return `urn:pulumi:${stack || settings_1.getStack()}::${project || settings_1.getProject()}::`;\n }\n return prefix;\n });\n }\n else {\n parentPrefix = output_1.output(`urn:pulumi:${stack || settings_1.getStack()}::${project || settings_1.getProject()}::`);\n }\n return output_1.interpolate `${parentPrefix}${type}::${name}`;\n}", "get parentTitle() {\n if (this.manifest && this.activeItem) {\n let tmpItem = this.manifest.items.find(\n (d) => this.activeItem.parent === d.id\n );\n // shift up 1 if we found something\n if (tmpItem) {\n return tmpItem.title;\n }\n }\n return \"\";\n }", "get propertyName() {}", "buildPageProperties(parentProperties) {\n const filteredProperties = this._filterProps(parentProperties);\n return this._buildNotionPageProperties(filteredProperties);\n }", "get parent() {\n return new Path(this.parentPath);\n }", "function parseClassPropertyName(classContextId) {\n _expression.parsePropertyName.call(void 0, classContextId);\n}", "get ancestorTitle() {\n if (this.manifest && this.activeItem) {\n let tmpItem = this.manifest.items.find(\n (d) => this.activeItem.parent === d.id\n );\n // walk back up to the root\n while (tmpItem && tmpItem.parent != null) {\n // take the parent object of this current item\n tmpItem = this.manifest.items.find((i) => i.id == tmpItem.parent);\n }\n if (tmpItem) {\n return tmpItem.title;\n }\n }\n return \"\";\n }", "get parentId() {\n return this.getStringAttribute('parent_id');\n }", "changeChildsName(name, newName) {\n if (this.hasOwnProperty(name)) {\n this.newName = this.name;\n delete this.name;\n }\n }", "getFieldLabels() {\n return {\n \"name\":t(\"Name\"),\n \"parent\": t(\"Parent Category\")\n }\n }", "function classReplacement(full_name) {\n for (key in cfg_classifications) {\n if (cfg_classifications.hasOwnProperty(key)) {\n if (cfg_classifications[key] == full_name) {\n return ucfirst(key.replace('_', ' '));\n }\n }\n \n }\n}", "get parent() {\n return tag.configure(ContentType(this, \"parent\"), \"ct.parent\");\n }", "async expandProperty(property) {\n // JavaScript requires keys containing colons to be quoted,\n // so prefixed names would need to written as path['foaf:knows'].\n // We thus allow writing path.foaf_knows or path.foaf$knows instead.\n property = property.replace(/^([a-z][a-z0-9]*)[_$]/i, '$1:');\n\n // Expand the property to a full IRI\n const context = await this._context;\n const expandedProperty = context.expandTerm(property, true);\n if (!ContextUtil.isValidIri(expandedProperty))\n throw new Error(`The JSON-LD context cannot expand the '${property}' property`);\n return namedNode(expandedProperty);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2.2 Function to update circles text y position with transition when change axes selection:
function updateYCircleText(circlesText, yScale2, yAxisChoice){ circlesText.transition() .duration(500) .attr('y', d=>yScale2(d[yAxisChoice])); return circlesText; }
[ "function textToCircles(text, xaxis,yaxis,x,y) {\n \n text.transition()\n .duration(1000)\n .attr(\"x\", function(d) { return x(d[xaxis])-5; })\n .attr(\"y\", function(d) { return y(d[yaxis])+2.5; })\n return text;\n\n}", "function updateXCircleText(circlesText, xScale2, xAxisChoice){\n\n circlesText.transition()\n .duration(500)\n .attr('x', d=>xScale2(d[xAxisChoice]));\n \n return circlesText;\n}", "function updateCircularTexts() {\n\t\tsvg_circular.selectAll(\".circular.text\")\n\t\t\t.classed('visible', function(d) {\n\t\t\t\tvar circ = d.circ;\n\t\t\t\treturn (circ.end_angle - circ.start_angle) > Math.PI / 12;\n\t\t\t}); \n\t}", "function updateLabelsText(xy, xPos, labelsText) {\n // setup chosenAxis by xy\n var chosenAxis = (xy === \"x\") ? chosenXAxis : chosenYAxis;\n // change text tag\n var enterlabelsText = null; labelsText.enter()\n .append(\"text\");\n // change text tag\n enterlabelsText = labelsText.enter()\n .append(\"text\")\n .merge(labelsText)\n .attr(\"x\", xPos)\n .attr(\"y\", (d,i) => (i+1)*axisPadding)\n .attr(\"value\", d => d) // value to grab for event listener\n .classed(\"active\", d => (d === chosenAxis) ? true:false)\n .classed(\"inactive\", d => (d === chosenAxis) ? false:true)\n .text(d => labelsTitle[d])\n .on(\"click\", updateChart);\n}", "function renderCircleLabels(circleLabels, newXScale, newYScale, chosenXAxis, chosenYAxis) {\n \n circleLabels = scatterGroup.selectAll(\".stateText\");\n \n circleLabels.transition()\n .duration(1000)\n .attr(\"x\", d => newXScale(d[chosenXAxis]))\n .attr(\"y\", d => newYScale(d[chosenYAxis]))\n .text(function(d) { return d.abbr; });\n \n\n return circleLabels;\n }", "function renderText(circletextGroup, newXScale, newYScale, chosenXAxis, chosenYAxis) {\n circletextGroup.transition()\n .duration(1000)\n .attr(\"x\", d => newXScale(d[chosenXAxis]))\n .attr(\"y\", d => newYScale(d[chosenYAxis]));\n \n return circletextGroup;\n }", "function updateCircleLabels(circleLabels, newXScale, chosenXAxis){\n\n circleLabels.transition()\n .duration(1000)\n .attr(\"x\", d => newXScale(d[chosenXAxis]));\n\n return circleLabels;\n}", "function updateToolTip(InitialXAxis, InitialYAxis, svgCircles, textGroup) {\n\n if (InitialXAxis === \"poverty\") {\n var xLabel = \"Poverty (%)\";\n }\n else if (InitialXAxis === \"age\") {\n var xLabel = \"Age (Median)\";\n }\n else {\n var xLabel = \"Household Income (Median)\";\n }\n if (InitialYAxis === \"healthcare\") {\n var yLabel = \"Lacks Healthcare (%)\";\n }\n else if (InitialYAxis === \"obesity\") {\n var yLabel = \"Obese (%)\";\n }\n else {\n var yLabel = \"Smokes (%)\";\n }\n\n // code to initialize the tooltip\n var toolTip = d3.tip()\n .attr(\"class\", \"tooltip d3-tip\")\n .offset([90, 90])\n .html(function(d) {\n return (`<strong>${d.abbr}</strong><br>${xLabel} ${d[InitialXAxis]}<br>${yLabel} ${d[InitialYAxis]}`);\n });\n// Creating circles tooltip on scatterplot\n svgCircles.call(toolTip);\n svgCircles.on(\"mouseover\", function(data) {\n toolTip.show(data, this);\n })\n// onmouseout event handler\n .on(\"mouseout\", function(data) {\n toolTip.hide(data);\n });\n\n// Text creation tooltip on scatterplot\n textGroup.call(toolTip);\n textGroup.on(\"mouseover\", function(data) {\n toolTip.show(data, this);\n })\n// onmouseout event handler\n .on(\"mouseout\", function(data) {\n toolTip.hide(data);\n });\n return svgCircles;\n }", "function setLabelPosition() {\r\n if (document.getElementById(\"rb1\").checked) {\r\n chart.labelRadius = 30;\r\n chart.labelText = \"[[title]]: [[value]]\";\r\n } else {\r\n chart.labelRadius = -30;\r\n chart.labelText = \"[[percents]]%\";\r\n }\r\n chart.validateNow();\r\n }", "function simTicked(){\n\tlet theCircles = d3.selectAll('.medal')\n\t\n\t//update x && y of each circle\n\ttheCircles.attrs({\n\t\tcx: d => d.x,\n\t\tcy: d => d.y\n\t})\n}", "function updateYPlot() {\r\n y.domain([0,globalymax])\r\n yAxis.transition().duration(1000).call(d3.axisLeft(y))\r\n }", "function textPosition (d) {\n\t\tif (y(d.value) + 16 > settings.hm) {\n\t\t\treturn y(d.value) - 2;\n\t\t}\n\t\treturn y(d.value) + 12;\n\t}", "function textUp() {\n gMeme.currText.y -= 15;\n}", "function positionEllipse(ellipse, cx, cy, width, height) {\n ellipse.transition().attr({\n cx: cx,\n cy: cy,\n rx: width / 2,\n ry: height / 2\n });\n }", "updateCircle() {\n const obj = this.newPos(); // Returns the random values as an object\n // Updates the circles css styling\n this.div.style.left = `${obj.posX}px`;\n this.div.style.bottom = `${obj.posY}px`;\n this.div.style.width = `${obj.radius}rem`;\n this.div.style.height = `${obj.radius}rem`;\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 hiLiteLabel(axis, clicked){\r\n d3.selectAll(\".aText\")\r\n .filter(\".\" + axis)\r\n .filter(\".active\")\r\n .classed(\"inactive\", true)\r\n \r\n clicked.classed(\"inactive\", false).classed(\"active\", true);\r\n}", "function updateAnchor() {\n\t\tif (!labels.selection) return;\n\t\tlabels.selection.each(function(d) {\n\t\t var bbox = this.getBBox(),\n\t\t x = bbox.x + bbox.width / 2,\n\t\t y = bbox.y + bbox.height / 2;\n\t\t \n\t\t d.anchorPos.x = x;\n\t\t d.anchorPos.y = y;\n\t\t \n\t\t // If a label position does not exist, set it to be the anchor position \n\t\t if (d.labelPos.x == null) {\n\t\t\td.labelPos.x = x;\n\t\t\td.labelPos.y = y;\n\t\t }\n\t\t});\n\t }", "function renderText(textGroup, newXScale, InitialXAxis, newYScale, InitialYAxis) {\n textGroup.transition()\n .duration(500)\n .attr(\"x\", d => newXScale(d[InitialXAxis]))\n .attr(\"y\", d => newYScale(d[InitialYAxis]))\n .attr(\"text-anchor\", \"middle\");\n\n return textGroup;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API Function: beginReporting Description: Standard report API, gets called just before report is to be run. We check here to see if file activity is happening. If so, we warn the user and return false indicating we can't run the report right now.
function beginReporting() { if (site.serverActivity()) { alert(MSG_CantRun_FileActivity); return false; } return true; }
[ "function startReportingActivity() {\n var id = Web.setInterval(function () {\n if (self.active()) {\n ucwa.send('POST', { rel: 'reportMyActivity' }, {\n nobatch: true\n }).catch(function (err) {\n // After a long period of inactivity, the connection with UCWA is usually lost.\n // While the connection is being restored, MePerson resends POST /makeMeAvailable.\n // However this periodic timer doesn't know about that logic and keeps sending\n // POST /reportMyActivity as usual. If the timer happens to wake up before the\n // /makeMeAvailable is completed, UCWA will reject this /reportMyActivity with a\n // 409.MakeMeAvailableRequired error.\n if (err && err.code == 'RequestFailed' && err.rsp.status == 409)\n return;\n debug.log('%c reportMyActivity stopped', 'color:red;font-weight:bold', err);\n Web.clearInterval(id);\n self.active(false, err);\n });\n }\n }, 3 * 60 * 1000);\n }", "function runReport() {\n checkAnswers();\n calculateTestTime();\n calculateCheckedInputs();\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 GenerateBuildReport()\r\n{\r\n if (!g_AlreadyCompleted && !PrivateData.objConfig.Options.fRestart)\r\n {\r\n var strTitle;\r\n var strMsg;\r\n var strDuplicated = \"\";\r\n var strElapsed = GetElapsedReport();\r\n\r\n if (!PrivateData.fIsStandalone)\r\n strDuplicated = GetDuplicateReport();\r\n\r\n strTitle = 'Build complete.';\r\n strMsg = PrivateData.objEnviron.LongName + \" \" + PrivateData.objEnviron.Description + ' completed.\\n\\n\\n';\r\n strMsg += strElapsed + '\\n\\n';\r\n strMsg += strDuplicated;\r\n\r\n SendErrorMail(strTitle, strMsg);\r\n g_AlreadyCompleted = true;\r\n }\r\n// <Config xmlns=\"x-schema:config_schema.xml\">\r\n// <LongName>Win64 Check</LongName>\r\n// <Description>Sync and win64 check build, with all post-build options and test-signing</Description>\r\n\r\n\r\n// <Environment xmlns=\"x-schema:enviro_schema.xml\">\r\n// <LongName>AXP64 Checked</LongName>\r\n// <Description>Build on AXP64Chk, NTAXP03, NTAXP04, NTAXP05 AND NTAXP06</Description>\r\n}", "function ActivityStarted(){\n\n\tif (g_bFullScreen) {\n\t\tOnResize(g_ConWidth, g_ConHeight, 2);\n\t\tDVD.CursorType = 0;\n\t}\n\n\tg_bActivityDeclined = false;\n\tUpdateDVDTitle();\n\t//MFBar.MessageBox(\"Activity Started\", \"Status\");\n}", "function processTracker() {\n\n\tvar success = true;\n\tconsole.log(\"\\n2. Validating exported metadata\");\n\t\n\t//Configure sharing and metadata ownership\n\tconfigureSharing();\n\tconfigureOwnership();\n\n\t//Remove users from user groups\n\tclearUserGroups();\n\t\t\n\t//Make sure the \"default defaults\" are used\n\tsetDefaultUid();\n\t\n\t//Make sure we don't include orgunit assigment in datasets or users\n\tclearOrgunitAssignment();\n\t\n\t//Verify that all data elements referred in indicators, validation rules,\n\t//predictors are included\n\tif (!validateDataElementReference()) success = false;\n\n\t//Verify that all program indicators referred to in indicators and predictors are included\n\tif (!validateProgramIndicatorReference()) success = false;\n\n\t//Remove invalid references to data elements or indicators from groups\n\t//Verify that there are no data elements or indicators without groups\n\tif (!validateGroupReferences()) success = false;\t\n\t\n\t//Verify that favourites only use relative orgunits\n\tif (!validateFavoriteOrgunits()) success = false;\n\t\n\t//Verify that favourites only use indicators\n\tif (!validateFavoriteDataItems()) success = false;\n\t\n\t//Verify that no unsupported data dimensions are used\n\tif (!validateFavoriteDataDimension()) success = false;\n\n\t//Verify that data sets with section include all data elements\n\tif (!validationDataSetSections()) success = false;\n\n\n\t/** CUSTOM MODIFICATIONS */\n\tif (currentExport.hasOwnProperty(\"_customFuncs\")) {\n\t\tfor (var customFunc of currentExport._customFuncs) {\n\t\t\tvar func = new Function(\"metaData\", customFunc);\n\t\t\tfunc(metaData); \n\t\t}\n\t}\n\t\n\tif (success) {\n\t\tconsole.log(\"✔ Validation passed\");\n\t\tsaveTracker();\n\t}\n\telse {\n\t\tconsole.log(\"\");\n\t\tvar schema = {\n\t\t\tproperties: {\n\t\t\t\tcontinue: {\n\t\t\t\t\tdescription: \"Validation failed. Continue anyway? (yes/no)\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdefault: \"no\",\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t\tif(args.ignoreerrors)\n\t\t{\n\t\t\tsaveTracker();\n\t\t} else {\n\t\t\tprompt.get(schema, function (err, result) {\t\n\t\t\t\tif (result.continue == \"yes\") saveTracker();\n\t\t\t\telse cancelCurrentExport();\n\t\t\t});\n\t\t}\n\t}\n}", "function checkStatus() {\n\t'use strict';\n\tconsole.log('Checking data coverage for our query period');\n\n\tds.historics.status({\n\t\t'start': startTime,\n\t\t'end': endTime\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Historic status for query period: ' + JSON.stringify(response));\n\t\t\tcompileStream();\n\t\t}\n\t});\n}", "function reportInfo() {\n var args = [\n '-i', files[0].name,\n '-hide_banner'\n ];\n\n var result = ffmpeg_run({\n print: printStdout,\n printErr: printStderr,\n TOTAL_MEMORY: TOTAL_MEMORY,\n arguments: args,\n files: files\n });\n\n postMessage({\n type: 'info',\n metadata: extractInfo(),\n stdout: stdout,\n stderr: stderr\n });\n}", "function gadgetFirstRun(){\r\n \r\n var profileStates = prefs.getArray('profiles');\r\n if(!profileStates || profileStates=='') return true;\r\n else return false;\r\n }", "function reportBuildStatus() {\n console.info('----\\n==> ✅ Building production completed (%dms).', (Date.now() - global.BUILD_STARTED));\n process.exit(0);\n}", "function checkSetupSuccess() {\n // Conditionals.\n var hasUndefined = false;\n var hasFalse = false;\n // Iterate through global successFactors JSON object.\n for (var key in global.successFactors) {\n if (global.successFactors[key] === undefined) {\n hasUndefined = true;\n break;\n }\n if (global.successFactors[key] === false) {\n console.log('key: ',key);\n hasFalse = true;\n break;\n }\n }\n // If no undefined and no false, print success.\n if (!hasUndefined && !hasFalse) {\n console.log(\"---\\nSetup was a success! Please enjoy MMM-RemoteCompliments!\");\n }\n // If false, let user know and exit.\n if (hasFalse){\n console.log(\"---\\nSomething went wrong with the setup. It is recommended you delete the files created on your Google Drive and try setup again after fixing the above error.\");\n process.exit(1);\n }\n}", "async function launchStartScreen() {\n\t\ttry {\n\t\t\t// console.trace();\n\t\t\tlet _tally_meta = await store(\"tally_meta\"),\n\t\t\t\tpageToShow = \"/get-anonyname\";\n\n\t\t\t// don't launch in development\n\t\t\tif (T.options.localhost) return;\n\n\t\t\t// don't launch if !server\n\t\t\tif (!_tally_meta.server.online)\n\t\t\t\treturn console.log(\"🔧 Install.launchStartScreen() 🛑 SERVER OFFLINE\");\n\n\t\t\t// if they are logged in show how to play\n\t\t\tif (_tally_meta.userLoggedIn) {\n\t\t\t\t// return console.log(\"🔧 Install.launchStartScreen() 🛑 ALREADY LOGGED IN\");\n\t\t\t\tconsole.log(\"🔧 Install.launchStartScreen() 🛑 ALREADY LOGGED IN\");\n\t\t\t\t// show how to\n\t\t\t\tpageToShow = \"/how-to-play\";\n\t\t\t}\n\n\t\t\t// get current page\n\t\t\tchrome.tabs.query({\n\t\t\t\tactive: true,\n\t\t\t\tcurrentWindow: true\n\t\t\t}, function (tabs) {\n\t\t\t\tvar tab = tabs[0];\n\t\t\t\t// if (DEBUG) console.log(\"🔧 Install.launchStartScreen() current tab =\", tab);\n\n\t\t\t\t// are we in the process resetting user's data?\n\t\t\t\tif (tab.url !== undefined && (tab.url.includes(\"/dashboard\") ||\n\t\t\t\t\t\ttab.url.includes(\"tallygame.net\") || tab.url.includes(\"tallygame.net\") ||\n\t\t\t\t\t\ttab.url.includes(_tally_meta.website)\n\t\t\t\t\t)) {\n\t\t\t\t\tif (DEBUG) console.log(\"🔧 Install.launchStartScreen() 🛑 ON DASHBOARD\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// keep track of prompts and don't do too many\n\t\t\t\tif (_tally_meta.install.prompts >= 30) {\n\t\t\t\t\tif (DEBUG) console.log(\"🔧 Install.launchStartScreen() 🛑 _tally_meta.install.prompts >=\",\n\t\t\t\t\t\t_tally_meta.install.prompts\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// else launch install page\n\t\t\t\tchrome.tabs.create({\n\t\t\t\t\turl: _tally_meta.website + pageToShow\n\t\t\t\t}, function (newTab) {\n\t\t\t\t\t// increment\n\t\t\t\t\t_tally_meta.install.prompts = _tally_meta.install.prompts + 1;\n\t\t\t\t\tstore(\"tally_meta\", _tally_meta);\n\t\t\t\t\tif (DEBUG) console.log(\"🔧 Install.launchStartScreen() 👍 launching\",\n\t\t\t\t\t\t\"_tally_meta.install.prompts =\", _tally_meta.install.prompts,\n\t\t\t\t\t\t\"newTab =\", newTab\n\t\t\t\t\t);\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tconsole.error(err);\n\t\t}\n\t}", "function ReportLoad(strFilname) {\n if (strFilname != '')\n var m_WindowHandle = window.open(strFilname, 'New', 'location=no, toolbar=no, menubar=yes, resizable=yes, scrollbars=yes');\n try { m_WindowHandle.focus(); } catch (e) { }\n}", "function preventFileActivity()\n{\n\treturn true;\n}", "function checkFormAndPdfDoc( activity, intro ) {\n let\n actId = activity._id.valueOf(),\n noPdfInState = [ 'CREATED', 'VALID', 'CANCELLED', 'DELETED' ],\n attachmentId, attachmentIds = [], formDocs, pdfDocs;\n for ( attachmentId of activity.attachments ) {\n attachmentIds.push( ObjectId( attachmentId ) );\n }\n formDocs = db.documents.find( { _id: { $in: attachmentIds }, type: 'FORM' } );\n pdfDocs = db.documents.find( { _id: { $in: attachmentIds }, type: 'FORM' } );\n /* print( `[i] activity ${activity._id.valueOf()} ${activity.status} with form has ${formDocs.length()} FORM and ${pdfDocs.length()}` ); */\n if ( 0 === formDocs.length() ) {\n print( `[!] ${intro} should have a form but does not, will queue for creation` );\n db.migrationtasks.insertOne( { taskname: 'CREATE_FORM', objId: actId } );\n }\n if ( formDocs.length() > 1 ) {\n print( `[!] ${intro} has more than one FORM document` );\n }\n if ( 0 === pdfDocs.length() && -1 === noPdfInState.indexOf( activity.status ) ) {\n print( `[!] ${intro} should have a form PDF but does not, will queue for creation` );\n db.migrationtasks.insertOne( { taskname: 'CREATE_PDF', objId: actId } );\n }\n if ( formDocs.length() > 1 ) {\n print( `[!] ${intro} has more than one FORMPDF document` );\n }\n}", "function startProgessBar() {\r\n\tgProgressBar = new ProgressBar(\"Applying Simple Dissolve...\",\"Simple Dissolve\",'');\r\n\tgProgressBar.open()\r\n\tdispatchEvent(\"com.adobe.event.createDissolveFile\",\"\")\r\n}", "reportProgress (synced, prog) {\n const page = this.page\n if (synced) {\n page.progress.textContent = '100'\n Doc.hide(page.syncUncheck, page.syncRemainBox, page.syncSpinner)\n Doc.show(page.syncCheck)\n this.progressed = true\n if (this.funded) this.success()\n return\n } else if (prog === 1) {\n Doc.hide(page.syncUncheck)\n Doc.show(page.syncSpinner)\n } else {\n Doc.hide(page.syncSpinner)\n Doc.show(page.syncUncheck)\n }\n page.progress.textContent = Math.round(prog * 100)\n\n // The remaining time estimate must be based on more than one progress\n // report. We'll cache up to the last 20 and look at the difference between\n // the first and last to make the estimate.\n const cacheSize = 20\n const cache = this.progressCache\n cache.push({\n stamp: new Date().getTime(),\n progress: prog\n })\n while (cache.length > cacheSize) cache.shift()\n if (cache.length === 1) return\n Doc.show(page.syncRemainBox)\n const [first, last] = [cache[0], cache[cache.length - 1]]\n const progDelta = last.progress - first.progress\n if (progDelta === 0) {\n page.syncRemain.textContent = '> 1 day'\n return\n }\n const timeDelta = last.stamp - first.stamp\n const progRate = progDelta / timeDelta\n const toGoProg = 1 - last.progress\n const toGoTime = toGoProg / progRate\n page.syncRemain.textContent = Doc.formatDuration(toGoTime)\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 checkFinished () {\n console.log(fileLoadCount+\" files loaded\")\n if (fileLoadCount == fileLoadThreshold) {\n console.log(\"basicFileLoader - callback: \"+cFunc.name);\n cFunc();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds the status object.
build() { const status = {}; if (this.code !== null) { status.code = this.code; } if (this.details !== null) { status.details = this.details; } if (this.metadata !== null) { status.metadata = this.metadata; } return status; }
[ "constructor() { \n \n LastStatusInfo.initialize(this);\n }", "function constructStatus(ref, div) {\n\tvar statusText = document.createElement(\"b\");\n\tstatusText.innerHTML = \"<h3>Status: </h3>\";\n\tdiv.appendChild(statusText);\n\tvar status = document.createElement(\"BUTTON\");\n\tstatus.addEventListener(\"click\", function() { toggleStatus(ref); });\n\tdiv.appendChild(status);\n\tvar flagRef = ref.child(\"STATUS\");\n\tflagRef.on(\"value\", function(snapshot) {\n\t\tif(snapshot.val().FLAG === \"ON\") {\n\t\t\tstatus.innerHTML = \"ONLINE\";\n\t\t\tstatus.style.background = \"#008000\";\n\t\t} else {\n\t\t\tstatus.innerHTML = \"OFFLINE\";\n\t\t\tstatus.style.background = \"#ff0000\";\n\t\t}\n\t});\n}", "function createStatus() {\r\n return $('<span/>', { class: 'status', text: 'available' });\r\n}", "function OrderStatus() {\n _classCallCheck(this, OrderStatus);\n\n OrderStatus.initialize(this);\n }", "function BAStatusMsg() {\n\t/** element node not needed.\n\t @type BAElement @private */\n\tthis.node = window.defaultStatus || '';\n\t/** default message of window.status.\n\t @type String @private */\n\tthis.msg = '';\n\t/** default message of window.status.\n\t @type String @private */\n\tthis.defaultMsg = '';\n\t/** time for delaying (ms).\n\t @type Number @private */\n\tthis.delay = 0;\n\t/** time for sustaining (ms).\n\t @type Number @private */\n\tthis.sustain = 0;\n\t/** store point of delay timeout timer.\n\t @type BASetTimeout @private */\n\tthis.delayTimer = null;\n\t/** store point of sustain timeout timer.\n\t @type BASetTimeout @private */\n\tthis.sustainTimer = null;\n}", "get status() {\n this._status = getValue(`cmi.objectives.${this.index}.status`);\n return this._status;\n }", "buildDerivedStats () {\n\t\tthis.derivedStats['Wound Boxes'] = this.stats.Health + DigimonStages[this.stage].woundBoxes;\n\n\t\tif (Number.isInteger(this.burstIndex)) {\n\t\t\tthis.derivedStats['Wound Boxes'] += this.burstIndex * BurstModifier.woundBoxes;\n\t\t}\n\n\t\tthis.derivedStats['Agility'] = Math.floor((this.stats.Accuracy + this.stats.Dodge) / 2) + this.statMods['Agility'] + DigimonSizes[this.sizeIndex].statBonus['Agility'];\n\t\tthis.derivedStats['Body'] = Math.floor((this.stats.Health + this.stats.Damage + this.stats.Armor)/3) + DigimonSizes[this.sizeIndex].statBonus['Body'] + this.statMods['Body'];\n\t\tthis.derivedStats['Brains'] = Math.floor(this.stats.Accuracy/2) + DigimonStages[this.stage].brains + this.statMods['Brains'];\n\n\t\tthis.specValues['RAM Value'] = Math.floor(this.derivedStats.Agility/10) + DigimonStages[this.stage].specValues + this.statMods['SpecValues'];\n\t\tthis.specValues['CPU Value'] = Math.floor(this.derivedStats.Body/10) + DigimonStages[this.stage].specValues + this.statMods['SpecValues'];\n\t\tthis.specValues['BIT Value'] = Math.floor(this.derivedStats.Brains/10) + DigimonStages[this.stage].specValues + this.statMods['SpecValues'];\n\n\t\tthis.specValues['BIT Value'] = this.handleRestriction(this.specValues['BIT Value'], 'BIT Value');\n\t\tthis.specValues['CPU Value'] = this.handleRestriction(this.specValues['CPU Value'], 'CPU Value');\n\t\tthis.specValues['RAM Value'] = this.handleRestriction(this.specValues['RAM Value'], 'RAM Value');\n\t}", "static updateStatus(id, status){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.status = status;\n\t\treturn new kaltura.RequestBuilder('reach_vendorcatalogitem', 'updateStatus', kparams);\n\t}", "static updateStatus(id, status){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.status = status;\n\t\treturn new kaltura.RequestBuilder('responseprofile', 'updateStatus', kparams);\n\t}", "set status(status) {\n this._cancerProgression.value = lookup.getStatusCodeableConcept(status);\n }", "static apiToModel(data) {\n const res = new KubernetesComponentStatus();\n res.ComponentName = data.metadata.name;\n\n const healthyCondition = _.find(data.conditions, { type: 'Healthy' });\n if (healthyCondition && healthyCondition.status === 'True') {\n res.Healthy = true;\n } else if (healthyCondition && healthyCondition.status === 'False') {\n res.ErrorMessage = healthyCondition.message;\n }\n\n return res;\n }", "async _update(statusData) {\n\t\tconst statusInfo = Object.assign({}, { ...statusData, msgId: (Date.now() + Math.random()).toString() });\n\t\tlet broadcast = false;\n\t\tif (!statusInfo.lastCheck) {\n\t\t\tstatusInfo.lastCheck = Date.now();\n\t\t}\n\t\tif (statusInfo.status == SystemStatuses.notice) {\n\t\t\tthis.statusHistory.unshift(statusInfo);\n\t\t\tthis._broadcastMessage('statusMessage', { ...statusInfo, msgType: 'add' });\n\t\t}\n\t\telse if (statusInfo.watcherId) {\n\t\t\tif (statusInfo.watcherId in this.watcherStatus) {\n\t\t\t\t// console.log(this.watcherStatus);\n\t\t\t\tif (this._watcherStatusChanged(statusInfo)) {\n\t\t\t\t\t// watcher status has changed since the last interval\n\t\t\t\t\tthis.logger.info(`watcher ${statusInfo.watcherId} status has changed - ${statusInfo.message}`, null, statusInfo);\n\t\t\t\t\tthis.statusHistory.unshift(statusInfo);\n\t\t\t\t\tbroadcast = true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// First status report for the watcher\n\t\t\t\tthis.logger.info(`watcher ${statusInfo.watcherId} first status`, null, statusInfo);\n\t\t\t\tthis.statusHistory.unshift(statusInfo);\n\t\t\t\tbroadcast = true;\n\t\t\t}\n\t\t\tthis.watcherStatus[statusInfo.watcherId] = statusInfo;\n\t\t}\n\t\telse {\n\t\t\t// we cannot generate an alert on a watcher that does not exist\n\t\t\tthis.logger.error(`serverStatus._update(): watcherId not specified for status ${statusInfo.status}`);\n\t\t}\n\t\tif (broadcast) {\n\t\t\tthis._broadcastMessage('statusMessage', { ...statusInfo, msgType: 'add' });\n\t\t\tthis.broadcastSystemStatus();\n\t\t\tif (statusData.serviceName) {\n\t\t\t\tthis._broadcastMessage('assetUpdate', { serviceName: statusData.serviceName, fullName: statusData.fullName });\n\t\t\t}\n\t\t}\n\t\t// console.log(\"leaving _update\", statusInfo);\n\t}", "static updateStatus(id, status){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.status = status;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_distributionprofile', 'updateStatus', kparams);\n\t}", "static updateStatus(id, status){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.status = status;\n\t\treturn new kaltura.RequestBuilder('eventnotification_eventnotificationtemplate', 'updateStatus', kparams);\n\t}", "function updateStatus(devices, new_status)\n{\n\tfor (var i in new_status )\t\t\t//for each status\n\t{\n\t\tfor(var j in devices)\t\t\t//look for the match ID\n\t\t{\n\t\t\tif( devices[j].deviceID == new_status[i].deviceID )\n\t\t\t{\n\t\t\t\tvar status = devices[j].status;\t\t//access the status array\t\t\t\n\t\t\t\t//running status\n\t\t\t\tstatus.running = typeof(new_status[i].running) ? new_status[i].running : status.running;\n\t\t\t\t//auto on mode settings\n\t\t\t\tif( typeof(new_status[i].autoOn) != 'undefined' )\n\t\t\t\t{\n\t\t\t\t\tstatus.autoOn.enable = typeof(new_status[i].autoOn.enable) ? new_status[i].autoOn.enable : status.autoOn.enable;\n\t\t\t\t\tstatus.autoOn.time = typeof(new_status[i].autoOn.time) ? new_status[i].autoOn.time : status.autoOn.time;\n\t\t\t\t}\n\t\t\t\t//auto off mode settings\n\t\t\t\tif( typeof(new_status[i].autoOff) != 'undefined' )\n\t\t\t\t{\n\t\t\t\t\tstatus.autoOff.enable = typeof(new_status[i].autoOff.enable) ? new_status[i].autoOff.enable : status.autoOff.enable;\n\t\t\t\t\tstatus.autoOff.time = typeof(new_status[i].autoOff.time) ? new_status[i].autoOff.time : status.autoOff.time;\n\t\t\t\t}\n\t\t\t\t//parameter of the device\n\t\t\t\tif(typeof(new_status[i].parameter)!='undefined')\n\t\t\t\t{\n\t\t\t\t\tvar para = new Array();\n\t\t\t\t\tpara = para.concat(new_status[i].parameter);\n\t\t\t\t\t//console.log(para.length);\n\t\t\t\t\tfor( var k=0; k < para.length; k++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tpara[k] = (para[k] != null) ? para[k] : status.parameter[k] ;\n\t\t\t\t\t}\n\t\t\t\t\tstatus.parameter = para;\n\t\t\t\t\t//console.log(status.parameter);\n\t\t\t\t}\n\t\t\t\tbreak;\t\t//get out of the inner loop\n\t\t\t}\n\t\t}\n\t}\n}", "buildMovement () {\n\t\tvar baseMovement = DigimonStages[this.stage].baseMovement + this.statMods['BaseMovement'];\n\t\tthis.qualityFlags['speedyMax'] = false;\n\t\tvar movement = this.handleRestriction(baseMovement, 'BaseMovement');\n\n\t\tthis.movementDetails = {\n\t\t\t'Movement': movement,\n\t\t\t'Jump Height': Math.floor(movement/2),\n\t\t\t'Jump Length': Math.floor(movement/2),\n\t\t\t'Swim Speed': Math.floor(movement/2)\n\t\t};\n\n\t\tfor (let i in this.extraMovementTypes) {\n\t\t\tvar statMod = this.statMods.hasOwnProperty(this.extraMovementTypes[i]) ? this.statMods[this.extraMovementTypes[i]] : 0;\n\n\t\t\tswitch (this.extraMovementTypes[i]) {\n\t\t\t\tcase 'Flight Speed':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Flight']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Flight']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Digging Speed':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Digger']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Digger']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Swim Speed':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Swimmer']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Swimmer']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Wallclimb Speed':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Wallclimber']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Wallclimber']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Jump Height':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Jumper']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Jumper']] * 5;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Jump Length':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Jumper']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Jumper']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Teleport Distance':\n\t\t\t\t\tstatMod += baseMovement - movement;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t}\n\n\t\t\tthis.movementDetails[this.extraMovementTypes[i]] = movement + statMod;\n\t\t}\n\t}", "function QuestBoard_StatusWindow () {\n this.initialize.apply (this, arguments);\n }", "function _createNewJobStatus(vistaId, domain, pidSite, pid, job, pollerJobId, jobStatusUpdater, log, callback) {\n\tlog.debug('vista-subscribe-request-handler._createNewJobStatus: Entering method. vistaId: %s; pidSite: %s; pid: %j; pollerJobId: %s; job: %j', vistaId, pidSite, pid, pollerJobId, job);\n\tvar patientIdentifier = idUtil.create('pid', pid);\n\tvar record = null;\n\tvar eventUid = null;\n\tvar meta = {\n\t\trootJobId: job.rootJobId,\n\t\tjpid: job.jpid,\n\t\tpriority: job.priority,\n\t\tjobId: pollerJobId\n\t};\n\tvar isHdr = jobUtil.isVistAHdrSubscribeRequestType(job.type);\n\tvar pollerJob;\n\tif (!isHdr) {\n\t\tpollerJob = jobUtil.createVistaPollerDomainRequest(vistaId, domain, patientIdentifier, record, eventUid, meta);\n\t}\n\telse {\n\t\tpollerJob = jobUtil.createVistaHdrPollerDomainRequest(vistaId, domain, patientIdentifier, record, eventUid, meta);\n\t}\n\t// pollerJob.jobId = pollerJobId;\n\tjobStatusUpdater.createJobStatus(pollerJob, function (error, response) {\n\t\t// Note - right now JDS is returning an error 200 if things worked correctly. So\n\t\t// we need to absorb that error.\n\t\t//--------------------------------------------------------------------------------\n\t\tif ((error) && (String(error) === '200')) {\n\t\t\tcallback(null, response);\n\t\t}\n\t\telse {\n\t\t\tcallback(error, response);\n\t\t}\n\t});\n}", "function createDeviceStatus(axios$$1, payload) {\n return restAuthPost(axios$$1, '/statuses', payload);\n }", "static updateStatus(id, status){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.status = status;\n\t\treturn new kaltura.RequestBuilder('cuepoint_cuepoint', 'updateStatus', kparams);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a ProcessLink link.
function ProcessLink(instanceId, linkId, settings) { if (!(this instanceof ProcessLink)) { return new ProcessLink(instanceId, linkId, settings); } this._external = settings.hasOwnProperty('external') ? !!settings.external : false; ProtocolLink.call(this, instanceId, linkId, settings); }
[ "function createLink(idSource, idTarget) {\n var links = JSON.parse(CacheService.getPrivateCache().get(\"links\"));\n if(links[idSource] == undefined) {\n links[idSource] = []; \n } \n var target = {};\n target[\"target\"] = idTarget;\n links[idSource].push(target);\n DocumentApp.getUi().alert('Link created (in the cache)'); \n CacheService.getPrivateCache().put('links', JSON.stringify(links), 3600); \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 onCreateLink() {\n var selection = window.getSelection();\n var inLink = nodeIsInLink(selection.anchorNode);\n if (!isInNode(selection.anchorNode, \"popuptext\") || selection.isCollapsed && !inLink) {\n window.alert(\"To create a link to another page, first select a phrase in the text.\");\n return;\n }\n\n // Are we editing an existing link?\n if (inLink) {\n // Expand the selection to the whole link:\n window.getSelection().removeAllRanges();\n var range = document.createRange();\n range.selectNode(inLink);\n window.getSelection().addRange(range);\n g(\"linkRef\").value = inLink.href;\n } else {\n /*\n // New link. Check if it's the name of another place.\n var phrase = window.getSelection().toString();\n var place = placeFromTitle(phrase);\n if (place) {\n $(\"#linkRef\")[0].value = \"./?place=\" + place;\n }\n */\n }\n\n g(\"linkRemoveOption\").style.display = (inLink ? \"block\" : \"none\");\n var jLinkDialog = g(\"linkDialog\");\n // Hang on to the existing user text selection.\n // The dialog is a convenient place to attach it:\n jLinkDialog.savedSelection = saveSelection();\n jLinkDialog.style.display = \"block\";\n\n // Select the link text in the dialog:\n $(\"#linkRef\").select();\n}", "function ParallelRouteLink() {\n go.Link.call(this);\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 }", "function createLink() {\r\n if (!validateMode()) return;\r\n \r\n var isA = getEl(\"A\",Composition.document.selection.createRange().parentElement());\r\n if(isA==null){\r\n\tvar str=prompt(\"Укажите адрес :\",\"http:\\/\\/\");\r\n\t \r\n\tif ((str!=null) && (str!=\"http://\")) {\r\n\t\tvar sel=Composition.document.selection.createRange();\r\n\t\tif (Composition.document.selection.type==\"None\") {\r\n\t\t\tsel.pasteHTML('<A HREF=\"'+str+'\">'+str+'</A>');\r\n\t\t}else {\r\n\t\t\tsel.execCommand('CreateLink',\"\",str);\r\n\t }\r\n\t\tsel.select();\r\n\t}\r\n } else {\r\n\tvar str=prompt(\"Укажите адрес :\",isA.href);\r\n\r\n\tif ((str!=null) && (str!=\"http://\")) isA.href=str;\r\n\r\n }\r\n\r\nComposition.focus();\r\n}", "function create_links() {\n var ids_to_queue = collect_video_info();\n\n // Get the queued status of the videos for the current user.\n flixstack_api.check_queued(ids_to_queue, function(data, textStatus) {\n for (var video_id in data['ids']) {\n var video = video_map[video_id];\n if (typeof video == \"undefined\") {\n console.log(\"Skipping \" + video_id);\n continue;\n }\n\n // If we have the video, add the links to each of the relevent containers.\n video.is_in_stack = data['ids'][video_id];\n if (typeof video.is_in_stack != 'undefined') {\n for (var i in video.containers) {\n if (!$('.flixstack-wrapper', video.containers[i]).length) {\n $(video.containers[i]).append(make_link(video_id));\n }\n }\n }\n }\n });\n}", "function createItemLinks(key,createLinks){\n\tvar editLink = document.createElement('a');\n\teditLink.href = \"#addidea\";\n\teditLink.key = key;\n\tvar editText = \"Edit Idea\";\n\teditLink.addEventListener(\"click\", editItem);\n\teditLink.innerHTML = editText;\n\tcreateLinks.appendChild(editLink);\n\t//add Line Break\n\tvar breakTag = document.createElement('br');\n\tcreateLinks.appendChild(breakTag);\n\tvar deleteLink = document.createElement('a');\n\tdeleteLink.href = \"#\";\n\tdeleteLink.key = key;\n\tvar deleteText = \"Delete Idea\";\n\tdeleteLink.addEventListener(\"click\", deleteItem);\n\tdeleteLink.innerHTML = deleteText;\n\tcreateLinks.appendChild(deleteLink);\n}", "async createLinkFromRepoToHere () {\n const log = this.log\n log.trace(`${this.constructor.name}.createLinkFromRepoToHere()`)\n\n const context = this.context\n const config = context.config\n\n if (config.configurationName) {\n throw new CliErrorInput('misplaced --config')\n }\n\n const xpack = this.xpack\n const packageJson = this.packageJson\n\n this.manifestIds = new ManifestIds(packageJson, this.policies)\n\n const globalPackagePath = path.join(context.globalConfig.globalFolderPath,\n this.manifestIds.getScopedName())\n\n const globalPackageLinkPath = path.join(globalPackagePath, dotLink)\n let stats\n try {\n // Use `lstat`, since `stat` follows the links.\n stats = await fsPromises.lstat(globalPackageLinkPath)\n } catch (err) {\n // `lstat` failed, the path does not exist; proceed to create the link.\n stats = null\n }\n\n if (stats) {\n if (stats.isSymbolicLink()) {\n try {\n log.trace(`del('${globalPackageLinkPath}')`)\n await deleteAsync(globalPackageLinkPath, { force: true })\n } catch (err) {\n log.trace(util.inspect(err))\n throw new CliError(\n `cannot remove '${globalPackageLinkPath}'`)\n }\n } else {\n throw new CliError(\n `'${globalPackageLinkPath}' is not a symbolic link`)\n }\n }\n\n // Create parent folder, for just in case.\n await makeDir(globalPackagePath)\n\n // fs.symlink(target, path[, type], callback)\n // 'creates the link called path pointing to target'\n log.trace('symlink' +\n `('${xpack.xpackPath}', '${globalPackageLinkPath})'`)\n\n if (os.platform() === 'win32') {\n await fsPromises.symlink(xpack.xpackPath, globalPackageLinkPath,\n 'junction')\n } else {\n await fsPromises.symlink(xpack.xpackPath, globalPackageLinkPath)\n }\n if (log.isVerbose()) {\n log.info('Development references to package ' +\n `'${this.manifestIds.getScopedName()}' will be redirected to folder ` +\n `'${xpack.xpackPath}'.`)\n } else {\n log.info(\n `${this.manifestIds.getScopedName()} -> ` +\n `'${xpack.xpackPath}'`)\n }\n }", "function add_link_line(name, schema){\n\t $(\"#new_contract_menu\").append(\"<li><a href='#'></a></li>\");\n\t $(\"#new_contract_menu > li > a:last\").text(schema.title).click(function() {\n\t app.forms.start_contract(name);\n\t });\n\t}", "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 dmlWriteShapeInfoLink(myLinkText, myLinkUrl) {\n\tvar myResult;\n\tif (myLinkText == '.' || myLinkUrl == '.') {\n\t\tmyResult = '';\n\t} else {\n\t\tmyResult = '<a href=\"' + myLinkUrl + '\" target=\"blank\">' + myLinkText + '</a><br>';\n\t}\n\treturn myResult;\n}", "_addLink(r1, r2) {\n this.elements.push({\n group: \"edges\",\n data: {\n id: `${r1.id}_${r2.id}`,\n source: r1.id,\n target: r2.id\n } \n })\n }", "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}", "function getLink() {\n var instruction = gettext(\"This link will open the interactive with your set productions:\");\n var productions = $(\"#cfg-grammar-input\").val().trim();\n if (productions.length <= 0) {\n $(\"#cfg-grammar-link\").html(\"\");\n return;\n }\n var productionsParameter = percentEncode(productions.replace(/\\n/g, ' '));\n var otherParameters = \"\";\n if ($(\"#examples-checkbox\").prop('checked')){\n var examples = $(\"#cfg-example-input\").val().trim();\n if (examples.length > 0) {\n otherParameters += '&examples=' + percentEncode(examples.replace(/\\n/g, '|'));\n }\n }\n if (!$(\"#generator-checkbox\").prop('checked')){\n otherParameters += '&hide-generator=true';\n if (!$(\"#examples-checkbox\").prop('checked')) {\n otherParameters += '&editable-target=true';\n }\n }\n // When the user switches between generator types a # appears at the end of the url\n // This needs to be removed for the new link, or not added in the first place:\n var basePath = window.location.href.split('?', 1)[0].replace(/\\#+$/g, '');\n var fullUrl = basePath + \"?productions=\" + productionsParameter + otherParameters;\n $(\"#cfg-grammar-link\").html(`${instruction}<br><a target=\"_blank\" href=${fullUrl}>${fullUrl}</a>`);\n}", "createLink(options) {\n 'use strict';\n\n let link;\n let counter;\n\n link = $.otp.contextPath;\n if (options === undefined || !options) {\n return link;\n }\n link = $.otp.addLinkComponent(link, options.controller);\n link = $.otp.addLinkComponent(link, options.action);\n link = $.otp.addLinkComponent(link, options.id);\n\n let parameters;\n if ($.otp.projectName) {\n parameters = $.extend({ [$.otp.projectParameter]: $.otp.projectName }, options.parameters);\n } else {\n parameters = options.parameters;\n }\n if (parameters !== undefined && parameters && Object.keys(parameters).length > 0) {\n link += '?';\n counter = 0;\n\n /* eslint-disable no-restricted-syntax */\n for (const parameter in parameters) {\n if ({}.hasOwnProperty.call(parameters, parameter)) {\n if (counter > 0) {\n link += '&';\n }\n link += `${parameter}=${encodeURIComponent(parameters[parameter])}`;\n counter += 1;\n }\n }\n /* eslint-enable no-restricted-syntax */\n }\n return link;\n }", "static newTagLink(user, tag) {\n return {\n tag: TagsService.newTag(tag),\n assigned_by: user.id,\n created_at: new Date(),\n };\n }", "function AddPageLink(text, page) {\n\tif (arguments.length != 2) {\n\t\terror(\t'Error 120: AddPageLink(text, page); requires two ' +\n\t\t\t\t'values: \"text\" and \"page,\" which must be sentences ' +\n\t\t\t\t'in quotations.');\n\t}\n\telse if ( !isString(text) || !isString(page) ) {\n\t\terror(\t'Error 121: AddPageLink(text, page); requires two ' +\n\t\t\t\t'values: \"text\" and \"page,\" which must be sentences ' +\n\t\t\t\t'in quotations.');\n\t}\n\telse if ( EDITOR_OBJECT == null ) {\n\t\terror( \t'Error 122: AddPageLink(text, page); must come after a ' +\n\t\t\t\t'\"Start\" call.');\n\t}\n\telse if (!ERROR_FOUND) {\n\t\tvar new_link = new link(text, page, null);\n\n\t\tnew_link.html = \t'<a class=\"page-link\" href=\"#' +\n\t\t\t\t\t\t\tpage +\n\t\t\t\t\t\t\t'\" onclick=\"changePage(&quot;' + \n\t\t\t\t\t\t\tpage +\n\t\t\t\t\t\t\t'&quot;);\">' +\n\t\t\t\t\t\t\ttext +\n\t\t\t\t\t\t\t'</a>';\n\t\tEDITOR_OBJECT.content.push(new_link);\n\t}\n}", "function handleGenInstanceURLEvent(err, result) {\n if (err) return displayError(err)\n\n // if the URL was generated successfully, create and append a new element to the HTML containing it.\n let url = getAnchorWithLink(result, \"instance link\");\n\n let textcenter = document.createElement('div');\n textcenter.className = \"text-center\";\n textcenter.id = \"instance_permalink\";\n textcenter.appendChild(url);\n\n $(\"#url-instance-permalink\").empty()\n document.getElementById('url-instance-permalink').appendChild(textcenter);\n $(\"#genInstanceUrl > button\").prop('disabled', true);\n zeroclipboard();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Downloads all listed repositories data
async function downloadData() { const releases = []; for (const source of sourcesOfTruth) { // fetch all repos of a given organizaion/user const allRepos = await fetch( `${baseURL}/users/${source.username}/repos${auth}` ).then(res => res.json()); // fetch releases of every repo for (const repo of allRepos) { const repoName = repo.full_name; const repoReleasesURL = repo.releases_url.replace('{/id}', '') + auth; const repoReleases = await getRepoReleases(repoName, repoReleasesURL); if (repoReleases.length) { releases.push(...repoReleases); } } } // add date information to the data, to be able to show last updated time const data = { date: new Date().toLocaleString(), releases }; return data; }
[ "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 getGithubPerfilRepos() {\n fetch(URL_GITHUB_PROFILE_REPOS)\n .then((response) => response.json())\n .then((data) => {\n data.map((item) => {\n list.innerHTML += `\n <li>${item.name}</li>\n `\n })\n })\n}", "function downloadAllFiles(){\n\twebsites = getAllWebsites();\n\tfor(var i=0;i<websites.length;i++){\n\t\tclickDownloadFiles(websites[i]);\n\t}\n\t\n\tconsole.log(endDate - initDate);\n}", "async function downloadArt(dir) {\n var metaData = await getMeta(dir);\n var shaPath = hashPath + dir + '/roms/';\n var files = await fsw.readdir(shaPath);\n socket.emit('emptymodal');\n for await (var file of files) {\n var fileName = file.replace('.sha1','');\n var fileExtension = path.extname(fileName);\n var name = path.basename(fileName, fileExtension);\n var sha = await fsw.readFile(shaPath + file, 'utf8');\n if (metaData.hasOwnProperty(sha)) {\n if (metaData[sha].hasOwnProperty('ref')) {\n var sha = metaData[sha].ref;\n };\n for await (var variable of metaVariables) {\n if (metaData[sha].hasOwnProperty(variable[0])) {\n await ipfsDownload(metaData[sha][variable[0]], dataRoot + dir + '/' + variable[1] + '/' + name + variable[2], 0) \n };\n };\n if (metaData[sha].hasOwnProperty('video_position')) {\n await fsw.writeFile(dataRoot + dir + '/videos/' + name + '.position', metaData[sha].video_position); \n };\n };\n };\n socket.emit('modaldata', 'Downloaded All Files');\n getRoms(dir);\n }", "function load_orgs() {\n\tif (orgs.length > 0) {\n var org_list = [];\n orgs.forEach(function(item) {\n (item.type === 'repo') ? repos.push(item) : org_list.push(item);\n });\n\n if (org_list.length > 0) {\n org_list.forEach(function(item){\n var t = new Object();\n t.opts = clone(optionsgit);\n t.func = get_repos;\n var org = item.name;\n t.opts = clone(optionsgit);\n t.opts.path = '/' + item.type + 's/' + org + '/repos?per_page=100' + '&access_token=' + gittoken + '&call=get_repos';\n t.source = 'load_orgs';\n throttle(t);\n });\n }\n // start fetching data once the orgs have been enumerated\n monitor = setInterval(function(){\n if ((timer === null) && (timer_db === null) && (repos.length > 0)) {\n fetch_git_data(repos.shift());\n }\n logger.info('Repo Q:', repos.length, 'GitHub Q:',stack.length, 'Cloudant Q:',stack_db.length);\n },2000);\n\t}\n}", "function getRepoLinks(html) {\n let selTool = cheerio.load(html);\n let topicNameElem = selTool(\".h1-mktg\");\n let repolinks = selTool(\"a.text-bold\");\n // console.log(topicNameElem.text());\n let topicName = topicNameElem.text().trim();\n dirCreater(topicName);\n for (let i = 0; i < 8; i++) {\n let repoPageLink = selTool(repolinks[i]).attr(\"href\");\n //console.log(repoPageLink);\n let repoName = repoPageLink.split(\"/\").pop();\n //let repoName = repoPageLink.split(\"/\");\n //console.log(repoName);\n repoName = repoName.trim();\n // console.log(repoName);\n createFile(repoName, topicName);\n let fullRepoLink = \"https://github.com\" + repoPageLink + \"/issues\";\n //console.log(fullRepoLink);\n getIssues(repoName, topicName, fullRepoLink);\n }\n console.log(\"`````````````````````````\");\n}", "async getDatasets({ state, commit }) {\n let qs = queryString.stringify(\n { q: state.host.subDomain || \"md\" },\n { skipNull: true }\n );\n let json = await fetch(\n `${BIO_INDEX_HOST}/api/portal/datasets?${qs}`\n ).then(resp => resp.json());\n\n // set the list of datasets\n commit(\"setDatasets\", json.data);\n }", "function loadLatestDownloads(path) {\n $(document).ready(function () {\n var downloads = new Array();\n fetchData();\n function updateDownloads(data) {\n Array.from(data).forEach(function (item) {\n downloads.push(item);\n });\n }\n function fetchData() {\n $.when(\n $.ajax({\n url: 'https://raw.githubusercontent.com/androidtrackers/realme-updates-tracker/master/data/' + path + '.yml',\n async: true,\n converters: {\n 'text yaml': function (result) {\n return jsyaml.load(result);\n }\n },\n dataType: 'yaml'\n })\n ).done(function (latest) {\n updateDownloads(latest);\n DrawTable(downloads);\n })\n }\n function DrawTable(downloads) {\n $('#downloads').DataTable({\n data: downloads,\n responsive: {\n details: false\n },\n \"pageLength\": 100,\n \"pagingType\": \"full_numbers\",\n \"order\": [[7, \"desc\"]],\n columnDefs: [\n { type: 'file-size', targets: 6 },\n { type: 'date-eu', targets: 7 }\n ],\n columns: [\n { data: 'device', className: \"all\" },\n {\n data: 'codename',\n className: \"min-mobile-l\",\n \"render\": function (data) {\n return '<a href=\"/downloads/latest/' + data + '\" target=\"_blank\">' + data + '</a>';\n }\n },\n {\n data: 'region',\n className: \"all\",\n \"render\": function (data) {\n return '<a href=\"/downloads/latest/' + data + '\" target=\"_blank\">' + data + '</a>';\n }\n },\n { data: 'system', className: \"min-mobile-l\" },\n { data: 'version', className: \"all\" },\n {\n data: 'download',\n className: \"all\",\n \"render\": function (data) {\n return '<a href=\"' + data + '\" target=\"_blank\">Download</a>';\n }\n },\n { data: 'size', className: \"min-mobile-l\" },\n { data: 'date', className: \"min-mobile-l\" }\n ]\n });\n };\n })\n}", "async function getGitHubBranches($userLogin, $reposName) {\n\n\n}", "function GetAllOfflineData() {\n \n CommonService.SelectAllResidents(app.db).then(function (rs) {\n \n vm.Residents = [];\n if (rs.rows.length > 0) {\n for (var i = 0; i < rs.rows.length; i++) {\n vm.Residents.push(rs.rows.item(i));\n \n }\n }\n CommonService.SelectAllResidentPhotos(app.db).then(function (rs) {\n vm.ResidentPhotos = [];\n if (rs.rows.length > 0) {\n for (var i = 0; i < rs.rows.length; i++) {\n vm.ResidentPhotos.push(rs.rows.item(i));\n }\n }\n getAllResidents(); \n $rootScope.$broadcast(\"loader_hide\");\n }, function error(err) {\n toastr.error('An error occurred while retrieving Resident Photos.');\n });\n }, function error(err) {\n toastr.error('An error occurred while retrieving Residents.');\n });\n\n }", "async function fetchGithubUsersInfo ({ data = [], year, accessToken }) {\n if (!data.length) {\n return []\n }\n const logins = data.map((user) => ({\n accessToken,\n login: user.login\n }))\n\n const users = await Promise.resolve(logins).map(fetchGithubUserInfo, {\n concurrency: 5\n })\n return users\n}", "function fetchBranches() {\n\tlog(`Fetching all remote Git branches`);\n\trun(\"git fetch --no-tags --prune --depth=1 origin +refs/heads/*:refs/remotes/origin/*\");\n}", "function getStarredRepos(users) {\n\n let loopEndPoint = users.length;\n let loopCounter = 0;\n let namesOfStarredRepos = [];\n\n// Given an array of github user names\n users.forEach(function(user) {\n // Make an API request\n const options = {\n url: `https://api.github.com/users/${user}/starred`,\n headers : {\n 'User-Agent': 'request',\n 'Authorization': 'token ' + process.env.GITHUB_API_TOKEN\n }\n };\n request(options, function(err, res, body) {\n // Put the results in the container as a JSON object\n // Create object that holds info on all the repos contributors,\n // each item is another object holding info about the contributor.\n let repoListing = JSON.parse(body);\n // console.log(repoListing);\n // Iterate over each item in the object\n for (let starredRepo in repoListing) {\n let theEntry = repoListing[starredRepo];\n // Put the repo names into the array of all starred repos.\n namesOfStarredRepos.push(theEntry.full_name);\n }\n loopCounter += 1;\n\n // Return all of the user's starred repos\n // as an array of repo names as strings.\n\n if (loopCounter >= loopEndPoint) {\n printTopFive(namesOfStarredRepos);\n }\n });\n });\n}", "function getStats() {\n var user = $(\"#username\").val();\n var repository = $(\"#repository\").val();\n\n var url = apiRoot + \"repos/\" + user + \"/\" + repository + \"/releases\";\n $.getJSON(url, showStats).fail(showStats);\n}", "function common_crawl_pop_and_download(months, list, callback) {\n\n //\n // Local variables\n //\n var month, tmp, len; // , list = [];\n var CCStats = {\n emails: 0,\n processed: 0,\n months: {}\n };\n\n len = months.length - 1;\n\n // checks if all links are already processed\n function isResolved() {\n // TODO : sort the list of months\n // console.log('Len \"-1\" counts: ' + len)\n if (!len--) {\n return callback(CCStats);\n }\n\n return;\n }\n\n function downloadAndProcessIt(month, cb) {\n\n // FIX : I need to implement this when I implement the DB (idea)\n if (CCStats.months[month]) {\n\n // If month exists and hasn't been parsed, don't download it\n if (CCStats.months[month].status === 'complete') {\n return isResolved();\n }\n }\n\n common_crawl_month_download_and_process(month, function(err, stream) {\n var data = [],\n urls = '';\n\n stream.on('data', function(chunk) {\n data.push(chunk);\n })\n\n stream.on('end', function() {\n urls += Buffer.concat(data).toString();\n urls = [].concat(urls.split('\\n'));\n\n // Eliminate the first one... It's an empty string\n urls.reverse();\n urls = [].concat(urls.slice(1));\n\n // // Eliminate the last one... It's an empty string\n // urls.pop();\n\n // TODO : Fix this logic later. This should depend of the file\n if (CCStats.months[month]) {\n\n if (CCStats.months[month].status === 'halfway') {\n var ind = urls.indexOf(CCStats.months[month].last);\n\t\t\tconsole.log('found one at ' + ind);\n urls = [].concat(urls.slice(0, ind + 1));\n\t\t\t// console.log(urls.length)\n // urls = [].concat(urls.slice(ind + 1));\n }\n\n } else {\n\n CCStats.emails += urls.length;\n list._list.count += urls.length;\n\n }\n\n // console.log('Got all urls for ' + month + '. ' + urls.length + ' in total... Saving them!!!');\n return cb(month, urls, CCStats);\n // isResolved();\n });\n });\n\n return;\n }\n\n\n function addMonthStatAndURLs(month, urls, CCStats) {\n // console.log('about to add to list ', month)\n common_crawl_add_to_list(month, urls, CCStats, list);\n return isResolved();\n\n // TODO : See how to implement this part later.\n // MonthStat.create({\n // month: month,\n // url_count: urls.length\n // })\n // .then(function(monthStat) {\n // // console.log(monthStat.id);\n // //list.add(urls, month);\n // return common_crawl_add_to_list(urls, month, monthStat.id, isResolved);\n // })\n // .catch(function(err) {\n // console.log(\"Something happened...\")\n // console.log(err)\n // process.exit()\n // });\n }\n\n // Check settings in file\n if (fs.existsSync('./config/commoncrawler_db.js')) {\n CCStats = require('../config/commoncrawler_db.js');\n } else {\n var data = '/* This file is auto-generated */\\r\\nmodule.exports = ' + JSON.stringify(CCStats) + ';'\n fs.writeFileSync('./config/commoncrawler_db.js', data, 'utf8');\n }\n\n months.forEach(function(month) {\n\n // TODO : Implement this part with the DB later\n // MonthStat.find({\n // where: { month: month }\n // })\n // .then(function(result) {\n // if (!result) {\n\n // This works!\n // console.log('Entry for ' + month + ' was not found. Creating one!');\n // downloadAndProcessIt(month, addMonthStatAndURLs);\n // }\n // // isResolved();\n // })\n // .catch(function(err) {\n // isResolved();\n // })\n\n // console.log('Entry for ' + month + ' was not found. Creating one!');\n downloadAndProcessIt(month, addMonthStatAndURLs);\n });\n\n return;\n}", "function updateList(repos) {\n var $ul = $(\"<ul/>\");\n \n // For each repository, create an item that when clicked on is expected\n // to display further information of the repository.\n for (var i in repos) {\n var repo = repos[i];\n\n\n // Give the link a special class for delegating clicks, store the\n // repository as data for the link, and give a defined text string for\n // display.\n var $link = $('<a href=\"#\" class=\"github-alert\"/>').\n data(\"repo\", repo).\n text(repo.owner + \"/\" + repo.name);\n\n // Add the item to the list\n var $li = $('<li/>');\n $li.append($link);\n $ul.append($li);\n }\n\n // Update the results to display the list\n $results.html($ul);\n }", "getV3ProjectsIdRepositoryArchive(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 opts = {\n 'sha': \"sha_example\", // String | The commit sha of the archive to be downloaded\n 'format': \"format_example\" // String | The archive format\n};*/\napiInstance.getV3ProjectsIdRepositoryArchive(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\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}", "showRepos(repos){\r\n let output = ' <h3>Latest Repos</h3>';\r\n console.log(repos);\r\n repos.forEach(repo => {\r\n output +=`\r\n <div class=\"repo-list row\">\r\n <span class=\"repo-name col-md-6\"><a href=\"${repo.html_url}\">${repo.name}</a></span>\r\n <button type=\"button\" class=\"btn btn-primary\">\r\n Stars <span class=\"badge badge-light\">${repo.stargazers_count}</span>\r\n </button>\r\n <button type=\"button\" class=\"btn btn-primary\">\r\n Watchers <span class=\"badge badge-light\">${repo.watchers}</span>\r\n </button>\r\n <button type=\"button\" class=\"btn btn-primary\">\r\n Forks <span class=\"badge badge-light\">${repo.forms}</span>\r\n </button>\r\n </div>\r\n `;\r\n\r\n });\r\n document.querySelector('.repos').innerHTML=output;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks priv key fits description
function privkeycheck() { var privkeycheck = document.getElementById("privatekeyform"); if (privkeycheck.value.length == 64) { document.getElementById("privkeycheckbtn").disabled = false; } else { document.getElementById("privkeycheckbtn").disabled = true; } }
[ "validPrivateKey(privateKey){}", "showPrivateKey() {\n this.showKey(this.privateKey, true);\n }", "function hasValidPrivateField(manifest) {\n return manifest[ManifestFieldNames.Private] === true;\n}", "getPrivKey() {\n var output = PrivKeyAsn1.encode({\n d: this.key.priv.toString(10),\n }, \"der\")\n return output.toString('hex')\n }", "function checkRequirements() {\n if (firstPassword.length < 5) {\n firstInputIssuesTracker.add(\"كلمه المرور اقل من 5 حروف\");\n } else if (firstPassword.length > 15) {\n firstInputIssuesTracker.add(\"كلمه المرور اكبر من 5 حروف\");\n }\n\n \n\n if (!firstPassword.match(/[a-z | A-Z | ا-ي]/g)) {\n firstInputIssuesTracker.add(\"الرجاء استخدام الحروف والارقام\");\n }\n\n \n\n var illegalCharacterGroup = firstPassword.match(/[^A-z0-9أ-ي!\\@\\#\\$\\%\\^\\&\\*]/g)\n if (illegalCharacterGroup) {\n illegalCharacterGroup.forEach(function (illegalChar) {\n firstInputIssuesTracker.add(\"غير مسموح بهذه الرموز: \" + illegalChar);\n });\n }\n }", "function validateModeKey(mode, sideKey) {\r\n if (mode !== \"public\" && mode !== \"private\" && mode !== \"restricted\") {\r\n throw new Error(\"The mode must be public, private or restricted, it is '\" + mode + \"'\");\r\n }\r\n if (mode === \"restricted\") {\r\n if (!sideKey) {\r\n throw new Error(\"You must provide a sideKey for restricted mode\");\r\n }\r\n if (!validators.isTrytes(sideKey)) {\r\n throw new Error(\"The sideKey must be in trytes\");\r\n }\r\n if (sideKey.length > 81) {\r\n throw new Error(\"The sideKey must be maximum length 81 trytes\");\r\n }\r\n }\r\n if (mode !== \"restricted\" && sideKey) {\r\n throw new Error(\"sideKey is only used in restricted mode\");\r\n }\r\n }", "validateKeyFormat(key) {\n if (key.split('-').length !== 3) {\n console.error('Invalid key format. Please try your command again.');\n process.exit(1);\n }\n return;\n }", "function validateKey() {\n if ($(this).val()) {\n if ($(this).val().match(/^[A-Za-z0-9]*$/)) return hideError($(this).parent().children(\".error\"));\n else return validationError($(this).parent().children(\".error\"), i18n.KEY_VALIDATION_MESSAGE)\n }\n else return validationError($(this).parent().children(\".error\"), i18n.EMPTY_KEY_MESSAGE)\n }", "function sanityCheck(){\n if(!passLowerCase && !passUpperCase && !passNumeric && !passSpecial){\n // We can't have a password without anything in it!\n passLowerCase=true;\n document.getElementById(\"include-lowercase\").checked=true;\n }\n if(passLength>maxPassLength){\n // Larger passwords are more secure, but let's set a limit somewhere!\n passLength=maxPassLength;\n document.getElementById(\"length-input\").value=maxPassLength;\n }\n if(passLength<1){\n // We probably shouldn't allow the user to have a one character password\n // But we certainly can't let them have a -5 character password!\n passLength=1;\n document.getElementById(\"length-input\").value=1;\n }\n}", "function passwordEvent(){\n //Find out if password is valid \n if(isPasswordValid()) {\n //Hide hint if valid\n $password.next().hide();\n } else {\n //else show hint\n let msgLen = validLength(8,100, $password, 'password').msg;\n let msgReg = regexCheck($password, 'password').msg;\n let eleLen = `<span>${msgLen}</span>`;\n let eleReg = `<span>${msgReg}</span>`;\n let ele = msgLen?msgReg?eleLen+eleReg:eleLen:eleReg\n\n $('#passwordMsg').html(ele).show();\n }\n}", "function VerCred(cred, sk , ipk ) {\n\t// Validate Input\n\n\t// - parse the credential\n\tlet A = cred.A\n\tlet B = cred.B\n\tlet E = cred.E\n\tlet S = cred.S\n\n\t// - verify that all attribute values are present\n\tfor (i = 0; i < cred.Attrs.length; i++) {\n\t\tif (cred.Attrs[i] == null) {\n\t\t\t//throw Error(\"credential has no value for attribute %s\", ipk.AttributeNames[i])\n\t\t}\n\t}\n\n\t// - verify cryptographic signature on the attributes and the user secret key\n\tlet BPrime = new FP256BN.ECP()\n BPrime.copy(GenG1)\n //BPrime.add(key.Ipk.HSk.mul(sk))\n // BPrime.add(key.Ipk.HRand.mul(S))\n //BPrime.add(Mul2(ipk.HSk,sk,ipk.HRand,S))\n BPrime.add(ipk.HSk.mul2(sk, ipk.HRand, S))\n \n\t// Append attributes\n\t// Use Mul2 instead of Mul as much as possible for efficiency reasones\n\tfor (i = 0; i < Math.floor(cred.Attrs.length/2); i++) {\n\t\tBPrime.add(\n\t\t\t ipk.HAttrs[2*i].mul2(\n\t\t\t\tcred.Attrs[2*i],\n\t\t\t\tipk.HAttrs[2*i+1],\n\t\t\t\tcred.Attrs[2*i+1]\n\t\t\t)\n\t\t)\n }\n \n\t// Check for residue in case len(attrs)%2 is odd\n\tif (cred.Attrs.length % 2 != 0 ){\n\t\tBPrime.add(key.Ipk.HAttrs[cred.Attrs.length-1].mul(cred.Attrs[cred.Attrs.length-1]))\n\t}\n\n\n if (!B.equals(BPrime)) {\n throw Error(\"b-value from credential does not match the attribute values\")\n }\n\n\n\t// Verify BBS+ signature. Namely: e(w \\cdot g_2^e, A) =? e(g_2, B)\n\tlet a = GenG2.mul(E)\n\ta.add(ipk.W)\n\ta.affine()\n\n\tlet left = FP256BN.PAIR.fexp(FP256BN.PAIR.ate(a, A))\n let right = FP256BN.PAIR.fexp(FP256BN.PAIR.ate(GenG2, B))\n \n if (!left.equals(right)) {\n console.log(JSON.stringify(left));\n console.log(JSON.stringify(right));\n throw Error(\"credential is not cryptographically valid\")\n }\n\n\n\n}", "function VerificationPwd() {\n const pwd = document.getElementById(\"pwd\");\n const LMINI = 8; // DP LMINI = longueur minimale du mot de passe\n\n //DP si le mot de passe comporte moins de 8 lettres alors erreur\n if (pwd.value.length < LMINI) {\n console.log(\"longueur pwd NOK\", pwd.value.length);\n return false;\n } else {\n console.log(\"longueur pwd OK\", pwd.value.length);\n return true;\n }\n}", "validPublicKey(publicKey){}", "function isValidImageKey(imageKey) {\n if (imageKey) {\n return true;\n }\n \n return false;\n}", "function testKeys(){\n\t\tvar server_K = $.trim($('#server_K').text()); //DEBUG-ONLY!!\n\t\tvar client_K = $.trim($('#client_K').text());\n\t\tif(server_K != \"\" && client_K != \"\"){\n\t\t\tif(server_K == client_K){\n\t\t\t\t$('#result_test').html(\"Keys are identical. Key exchange was successful.\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$('#result_test').html(\"Keys don't match! Key exchange failed.\");\n\t\t\t}\n\t\t}\n\t}", "function isPrivateRepo() {\n var outlineLabels = document.querySelectorAll(\n \"span.Label.Label--outline.v-align-middle\"\n );\n for (const label of outlineLabels) {\n if (label.innerText == \"Private\") {\n return true;\n }\n }\n return false;\n }", "function lookForPrivateUseUnicode(element) {\n return (hasPrivateUseUnicode(\"before\") || hasPrivateUseUnicode(\"after\"));\n\n function hasPrivateUseUnicode(psuedo) {\n var content = (oldIE) ? \"\" : window.getComputedStyle(element, \":\" + psuedo).content;\n if (content !== \"none\" && content !== \"normal\" && content !== \"counter\" && content !== \"\\\"\\\"\") {//content is not none or empty string\n var unicode;\n //starts at 1 and end at length-1 to ignore the starting and ending double quotes\n for (var i = 1; i < content.length - 1; i++) {\n unicode = content.charCodeAt(i);\n if (unicode >= 57344 && unicode <= 63743) {\n //unicode is in the private use range\n return true;\n }\n }\n }\n return false;\n }\n }", "function inspectAesCbcKey( keyObj, algorithm, usages, reason /* set reason.message to return fail messages */ ) {\n\n var fail = [];\n\n if ( !validation.prop.string( keyObj, \"alg\", \"A\" + algorithm.length + \"CBC\" ) ) {\n fail.push( \"key.alg !== A\" + algorithm.length + \"CBC\" );\n }\n\n if ( !validation.prop.boolean( keyObj, \"ext\", true ) ) {\n fail.push( \"key.ext !== true\" );\n }\n\n if ( !validation.prop.string( keyObj, \"k\", /^([A-Za-z0-9-_]+)$/ /* base64url */ ) ) {\n fail.push( \"key.k not base64url\" );\n }\n\n // k property converts to bytes array of expected length\n var kBytes = msrCrypto.fromBase64( keyObj.k );\n if ( !testShared.isBytes( kBytes, algorithm.length / 8 ) ) {\n fail.push( \"key.k is not bytes\" );\n }\n\n // has key_ops property with expected usages\n if ( Object.prototype.toString.call( keyObj.key_ops ) !== \"[object Array]\" ) {\n fail.push( \"key.key_ops missing or not Array\" );\n }\n\n if ( keyObj.key_ops && !testShared.compareUsages( keyObj.key_ops, usages ) ) {\n fail.push( \"key.key_ops invalid usage(s)\" );\n }\n\n if ( !validation.prop.string( keyObj, \"kty\", \"oct\" ) ) {\n fail.push( \"key.kty !== oct\" );\n }\n\n reason.message = fail.join( \"; \" );\n\n return ( fail.length === 0 );\n}", "function isValidRoomPassword(roomName, pwd) {\n\treturn (roomsInfo[roomName].password === pwd);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets the data associated with a ship data includes a description of ship's ability, as well as images
function shipDetails(shipName, shipIndex) { var index = -1; var descriptions = document.getElementsByClassName('shipDes'); var ships = ['Scrambler', 'Scanner', 'Submarine', 'Defender', 'Cruiser', 'Carrier', 'Executioner', 'Artillery']; if (client.fleet[shipIndex] != shipName || prepWindow.firstSelect[shipIndex]) { prepWindow.images[shipIndex] = shipImages.get(shipName); prepWindow.draw(); index = ships.indexOf(shipName); client.fleet[shipIndex] = shipName var altShipName; if (index % 2 == 0) altShipName = ships[index+1].toLowerCase() + 'Des'; else altShipName = ships[index-1].toLowerCase() + 'Des'; document.getElementById(shipName.toLowerCase() + 'Des').disabled = true; document.getElementById(altShipName).disabled = false; if (prepWindow.currentShipDes != -1) descriptions[prepWindow.currentShipDes].style.display = 'none'; prepWindow.currentShipDes = index; descriptions[index].style.display = 'block'; descriptions[index].style.left = prepWindow.divX + 'px'; descriptions[index].style.top = prepWindow.divY + 'px'; prepWindow.firstSelect[shipIndex] = false; } }
[ "function makeShipRequest() {\n let url = API_URL+ \"?shipName=\" + this.id;\n let currentShip = this;\n fetch(url)\n .then(checkStatus)\n .then(JSON.parse)\n //.then(shipDetail)\n .then(function(response) {\n shipDetail(response, currentShip);\n })\n .catch(console.error);\n }", "function place_ship(ship) {\n for (var i = 0; i < ship.length; i++) {\n spielfeld[ship[i].y][ship[i].x] = true;\n }\n}", "function displayShip(ship){\n startCoordAcross = ship.start.Across;\n startCoordDown = ship.start.Down;\n endCoordAcross = ship.end.Across;\n endCoordDown = ship.end.Down;\n if(startCoordDown > 10 || startCoordDown < 0 || startCoordDown > 10 || startCoordDown < 0 || endCoordAcross > 10 || endCoordAcross < 0 || endCoordDown > 10 || endCoordDown < 0) {\n setDialogBox(\"failed to place ship.\");\n return;\n }\n if(startCoordAcross > 0){\n if(startCoordAcross == endCoordAcross){\n for (i = startCoordDown; i <= endCoordDown; i++) {\n document.getElementById(i+'_'+startCoordAcross).innerHTML = '<img src=\"sprites/ShipSmall.png\" alt=\"\" border=0 height=24 width=24>';\n }\n } else {\n for (i = startCoordAcross; i <= endCoordAcross; i++) {\n document.getElementById(startCoordDown+'_'+i).innerHTML = '<img src=\"sprites/ShipSmall.png\" alt=\"\" border=0 height=24 width=24>';\n }\n }\n }\n}", "getShoe(save) {\n if (save == null)\n return null;\n let shoe = _.cloneDeep(save)\n let base = data.shoes[shoe.id];\n shoe.name = base.name;\n shoe.icon = base.icon\n shoe.legProtection = base.legProtection;\n shoe.modifierText = []\n shoe.flags = [];\n\n // vanity prefixes/suffixes in name\n let prefixes = []\n let suffixes = []\n\n for (let x in shoe.modifiers) {\n let mod = data.modifiers[shoe.modifiers[x].id];\n let values = [];\n\n switch (shoe.modifiers[x].suffix) {\n case false: {\n prefixes.push(mod.prefix)\n break;\n }\n case true: {\n suffixes.push(mod.suffix)\n break;\n }\n }\n\n for (let z in mod.flags) {\n shoe.flags.push(mod.flags[z])\n }\n\n for (let z in mod.statMods) {\n let value = this.getValue(mod, z, shoe.modifiers[x].quality)\n if (mod.statMods[z].percentage != undefined) {\n value *= 100;\n }\n values.push(utils.round(value, 2))\n }\n\n // format header\n let text = mod.description.format(...values)\n // {\"{0} - {1}\".format(mod.name, text)}\n shoe.modifierText.push(<p key={x+1}><b>{mod.name}</b>{\" - \"}{text}{\" ({0}% Quality)\".format(utils.round(shoe.modifiers[x].quality * 100, 0))}</p>)\n // shoe.modifierText.push(<p key={-x}>{\"Quality: {0}%\".format(utils.round(shoe.modifiers[x].quality * 100, 2))}</p>)\n }\n\n let prefixedName = \"\";\n let suffixedName = \"\";\n\n for (let x in prefixes) {\n prefixedName += prefixes[x] + \" \"\n }\n for (let x in suffixes) {\n suffixedName += \" \" + suffixes[x]\n }\n\n shoe.name = prefixedName + shoe.name + suffixedName;\n\n shoe.modifierText.push(<p key={-2000}>{\"Leg Protection: {0}%\".format(utils.round(shoe.legProtection * 100, 2))}</p>)\n\n return shoe;\n }", "function worthAttacking(gameMap, ship, oship) {\n let possibleCollisonPos = oship.position;\n \n //attempt to detect where collision will occur;\n //Usually, the first direction is where it will occur. The times when this won't happen is when there are collisions with friendly ships detected, of which this will be off a little.\n let collisionDirections = gameMap.getUnsafeMoves(ship.position, oship.position);\n if (collisionDirections.length > 0) {\n possibleCollisonPos = ship.position.directionalOffset(collisionDirections[0]);\n }\n\n if(1.5 * ship.haliteAmount < oship.haliteAmount) {\n let shipsNearby = search.numShipsInRadius(gameMap, ship.owner, possibleCollisonPos, 2);\n let friendlyNearby = shipsNearby.friendly;\n if (friendlyNearby >= 2 && friendlyNearby > shipsNearby.enemy){\n logging.info(`Ship-${ship.id} is going to try to collide with at least 2 other friends nearby f:${shipsNearby.friendly}, e:${shipsNearby.enemy} at ${possibleCollisonPos}`)\n return true;\n }\n }\n return false;\n \n}", "generateShipperData(shipperID: string) {\n const shipperInvoices = this.invoices.filter((invoice) => (\n invoice.shipper_id === shipperID\n ));\n\n // TODO: handle cases where no invoices found for shipper;\n if (!shipperInvoices) return null;\n\n // at this point, all invoices are from same shipper so we can grab name\n // from any one of the invoices\n const shipper = getModelRelated(shipperInvoices[0], 'load.shipper');\n const shipperName = shipper.name;\n\n const data = shipperInvoices.reduce((rowData, invoice) => {\n // grab load number\n const load = getModelRelated(invoice, 'load');\n rowData.loadNbrs.push(load.iid);\n\n // grab shipper load number\n rowData.shipperLoadNbr.push(load.shipper_load_number);\n\n // grab origin city and state\n const originCity = getModelRelated(invoice, 'load.lane.originCity');\n const originState = getModelRelated(invoice, 'load.lane.originCity.state');\n rowData.origin.push(`${originCity.name}, ${originState.code}`);\n\n // grab destination city and state\n const destinationCity = getModelRelated(invoice, 'load.lane.destinationCity');\n const destinationState = getModelRelated(invoice, 'load.lane.destinationCity.state');\n rowData.destination.push(`${destinationCity.name}, ${destinationState.code}`);\n\n // grab delivered dates\n const deliveredAt = load.delivered_at;\n rowData.deliveredDates.push(moment(deliveredAt).format('MM/DD/YY'));\n\n // grab invoice numbers\n rowData.invoiceNumbers.push(`${invoice.iid}`);\n\n // grab invoice amounts\n rowData.invoiceAmounts.push(`${invoice.net_payable_cents}`);\n\n return rowData;\n }, {\n shipperName,\n loadNbrs: [],\n shipperLoadNbr: [],\n origin: [],\n destination: [],\n deliveredDates: [],\n invoiceNumbers: [],\n invoiceAmounts: [],\n });\n\n return data;\n }", "function isMaxDamaged( shipObj )\n{\n DEBUG_MODE && console.log( \"Calling isMaxDamaged in ShipBO, shipObj:\" , shipObj );\n if ( shipObj == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: shipObj is undefined\" );\n return undefined;\n }\n\n if ( shipObj.damage == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: shipObj.damage is undefined\" );\n return undefined;\n }\n\n if ( !Number.isInteger( shipObj.damage ) )\n {\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: shipObj.damage is not an integer\" );\n return undefined;\n }\n\n if ( shipObj.shipBluePrint == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: shipObj.shipBluePrint is undefined\" );\n return undefined;\n }\n\n if ( shipObj.shipBluePrint.maxDamage == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: shipBluePrint.maxDamage is undefined\" );\n return undefined;\n }\n\n if ( !Number.isInteger( shipObj.shipBluePrint.maxDamage ) )\n {\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: shipBluePrint.maxDamage is not an integer\" );\n return undefined;\n }\n\n if ( parseInt( shipObj.shipBluePrint.maxDamage ) <= 0 )\n {\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: shipBluePrint.maxDamage must be > 0\" );\n return undefined;\n }\n\n let currentDamage = parseInt( shipObj.damage );\n let maxDamage = parseInt( shipObj.shipBluePrint.maxDamage );\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: current damage is\" , currentDamage );\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: max damage is\" , maxDamage );\n if ( currentDamage >= maxDamage )\n {\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: returning true as ship is damaged to the max\" );\n return true;\n }\n else\n {\n DEBUG_MODE && console.log( \"ShipBO.isMaxDamaged: returning false as ship is not fully damaged\" );\n return false;\n }\n}", "function Ship() {\n this.coords = {};\n this.isHit = isHit;\n this.addPosition = (x,y) => this.coords[x + \",\" + y] = new Coord(x,y);\n this.isSunk = () => Object.keys(this.coords).length === 0;\n}", "fetchDealerDetails(workshopId) {\n let selectedWorkshop = this.workshopList.find(workshop => workshop.Id === workshopId);\n this.parentGroup = selectedWorkshop.Parent_Group__c;\n this.dealerMapCode = selectedWorkshop.Dealer_Map_Code__c;\n this.locationCode = selectedWorkshop.Dealer_Location__c;\n }", "async show(req, res) {\n // Get all oportunities\n const { data } = await pipedrive_api.get();\n // Array to filter which data receive\n const oportunities = [];\n\n if (data.data) {\n data.data.forEach(client => {\n let {\n title,\n value,\n status,\n won_time,\n person_id: { name },\n } = client;\n oportunities.push({ title, value, status, won_time, name });\n });\n }\n return res.json(oportunities);\n }", "function createPlayShips(){\n // playShipOptions.forEach(ship => {\n // createShip(ship)\n // })\n formatPlayShips()\n }", "getData() {\n return PRIVATE.get(this).opt.data;\n }", "function isFull( shipObj )\n{\n DEBUG_MODE && console.log( \"Calling isFull in ShipBO, shipObj:\" , shipObj );\n if ( shipObj == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.isFull: shipObj is undefined\" );\n return undefined;\n }\n\n if ( shipObj.inventory == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.isFull: shipObj.inventory is undefined\" );\n return undefined;\n }\n\n if ( shipObj.shipBluePrint == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.isFull: shipObj.shipBluePrint is undefined\" );\n return undefined;\n }\n\n if ( shipObj.shipBluePrint.maxInventory == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.isFull: shipBluePrint.maxInventory is undefined\" );\n return undefined;\n }\n\n DEBUG_MODE && console.log( \"ShipBO.isFull: calling InventoryModule.isFull\" );\n return inventoryMod.isFull( shipObj.inventory , shipObj.shipBluePrint.maxInventory );\n}", "function saveShip( shipObj, onFinish )\n{\n //create a new ship object\n var protoObj = defaultObj();\n\n //assign each of the properties to the one in shipObj parameter\n for ( var prop in protoObj )\n {\n protoObj[ prop ] = shipObj[ prop ];\n }\n\n //assign the id field of the new ship object to the shipObj parameter id\n protoObj[ ID_KEY ] = shipObj[ ID_KEY ];\n\n shipDAO.updateShip( protoObj , function( err , result )\n {\n onFinish( err , protoObj );\n });\n}", "function generateBadge(data){\n return licenseBadge[data.license]; \n}", "function addDamage( shipObj, addAmount )\n{\n DEBUG_MODE && console.log( \"Calling addDamage in ShipBO, shipObj:\" , shipObj );\n if ( shipObj == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: shipObj is undefined\" );\n return undefined;\n }\n\n if ( addAmount == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: addAmount is undefined\" );\n return undefined;\n }\n\n if ( shipObj.damage == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: shipObj.damage is undefined\" );\n return undefined;\n }\n\n if ( !Number.isInteger( shipObj.damage ) )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: shipObj.damage is not an integer\" );\n return undefined;\n }\n\n if ( shipObj.shipBluePrint == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: shipObj.shipBluePrint is undefined\" );\n return undefined;\n }\n\n if ( shipObj.shipBluePrint.maxDamage == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: shipBluePrint.maxDamage is undefined\" );\n return undefined;\n }\n\n if ( !Number.isInteger( shipObj.shipBluePrint.maxDamage ) )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: shipBluePrint.maxDamage is not an integer\" );\n return undefined;\n }\n\n if ( !Number.isInteger( addAmount ) )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: addAmount is not an integer\" );\n return undefined;\n }\n\n if ( parseInt( addAmount ) <= 0 )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: addAmount must be > 0\" );\n return undefined;\n }\n\n let currentDamage = parseInt( shipObj.damage );\n let maxDamage = parseInt( shipObj.shipBluePrint.maxDamage );\n DEBUG_MODE && console.log( \"ShipBO.addDamage: current damage is\" , currentDamage );\n DEBUG_MODE && console.log( \"ShipBO.addDamage: max damage is\" , maxDamage );\n if ( currentDamage + addAmount > maxDamage )\n {\n DEBUG_MODE && console.log( \"ShipBO.addDamage: cannot damage beyond max damage\" );\n return undefined;\n }\n\n shipObj.damage = currentDamage + addAmount;\n DEBUG_MODE && console.log( \"ShipBO.addDamage: successfully added damage\" );\n return shipObj.damage;\n}", "function createShip( shipObj , onFinish )\n{\n //create a new company object\n var protoObj = defaultObj();\n\n //assign each of the properties to the one in shipObj parameter\n for ( var prop in protoObj )\n {\n protoObj[ prop ] = shipObj[ prop ];\n }\n\n //assign the id field of the new ship object to the shipObj parameter id\n if ( shipObj[ ID_KEY ] )\n {\n protoObj[ ID_KEY ] = shipObj[ ID_KEY ];\n }\n\n shipDAO.createShip( protoObj , onFinish );\n}", "function creditsDetails(data, movieData, item) {\n movieData[item]['cast'] = data.cast;\n movieData[item]['crew'] = data.crew;\n movieData[item]['cast_crew'] = combineLists([data.cast, data.crew]);\n movieData[item]['cast_crew_stats'] = {'cast': {}, 'crew': {}, 'overall': {}};\n\n return movieData\n} // END: creditsDetails", "function hasSpaceForGoods( shipObj, goods )\n{\n DEBUG_MODE && console.log( \"Calling hasSpaceForGoods in ShipBO, goods:\" , goods );\n if ( shipObj == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.hasSpaceForGoods: shipObj is undefined\" );\n return undefined;\n }\n\n if ( goods == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.hasSpaceForGoods: goods is undefined\" );\n return undefined;\n }\n\n if ( shipObj.inventory == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.hasSpaceForGoods: shipObj.inventory is undefined\" );\n return undefined;\n }\n\n if ( shipObj.shipBluePrint == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.hasSpaceForGoods: shipObj.shipBluePrint is undefined\" );\n return undefined;\n }\n\n if ( shipObj.shipBluePrint.maxInventory == undefined )\n {\n DEBUG_MODE && console.log( \"ShipBO.hasSpaceForGoods: shipObj.shipBluePrint.maxInventory is undefined\" );\n return undefined;\n }\n\n DEBUG_MODE && console.log( \"ShipBO.hasSpaceForGoods: returning InventoryModule.hasSpaceForGoods\" );\n return inventoryMod.hasSpaceForGoods( shipObj.inventory, goods, shipObj.shipBluePrint.maxInventory );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Aliases an existing plugin with a new name
function alias(newName, oldPlugin) { const { name } = oldPlugin, plugin = __rest(oldPlugin, ["name"]); return Object.assign({ name: newName }, plugin); }
[ "function substitute(plugin2sub, pluginName) {\n let remappedNames = Object.keys(plugin2sub);\n return remappedNames.includes(pluginName) ? plugin2sub[pluginName] : pluginName;\n}", "function registerRenameProvider(languageId, provider) {\n return __WEBPACK_IMPORTED_MODULE_3__common_modes_js__[\"r\" /* RenameProviderRegistry */].register(languageId, provider);\n}", "registerExternalAnalysisPlugin (pluginName, symbolName, callback) {\n this.analysisPluginMap.set(pluginName, {\n type: SelectionContextMenu.PluginTypeEnum.EXTERNAL_WEBSITE_ANALYSIS,\n symbol: symbolName,\n callback: callback});\n this.refreshAnalysisMenu();\n }", "AliasComponent(string, string, string, string, string) {\n\n }", "function appendNameAliases() {\n for (var i = 0; i < vm.ctrpOrg.name_aliases.length; i++) {\n vm.addedNameAliases.push({\n id: vm.ctrpOrg.name_aliases[i].id,\n name: vm.ctrpOrg.name_aliases[i].name,\n _destroy: false\n });\n }\n }", "function Alias(props) {\n return __assign({ Type: 'AWS::GameLift::Alias' }, props);\n }", "function resolveAlias(name, counter) {\n counter = counter || 0;\n if (counter > 100) {\n throw \"Too many aliases returned by Respec\";\n }\n if (chunkRes[name].aliasOf) {\n return resolveAlias(chunkRes[name].aliasOf, counter + 1);\n }\n else {\n return name;\n }\n }", "function loadPlugin(name, options) {\n return require(resolvePlugin(name, options) || name);\n}", "function procAlias(username) {\n if (Object.keys(userData.alias).indexOf(username) > -1)\n return userData.alias[username];\n\n return username;\n}", "getPlugin(name) {\n return this._plugins[name];\n }", "function resolvePlugin(name, options) {\n var settings = options || {};\n var prefix = settings.prefix;\n var cwd = settings.cwd;\n var filePath;\n var sources;\n var length;\n var index;\n var plugin;\n\n if (cwd && typeof cwd === 'object') {\n sources = cwd.concat();\n } else {\n sources = [cwd || process.cwd()];\n }\n\n /* Non-path. */\n if (name.indexOf(path.sep) === -1 && name.charAt(0) !== '.') {\n if (settings.global == null ? globally : settings.global) {\n sources.push(globals);\n }\n\n /* Unprefix module. */\n if (prefix) {\n prefix = prefix.charAt(prefix.length - 1) === '-' ? prefix : prefix + '-';\n\n if (name.slice(0, prefix.length) !== prefix) {\n plugin = prefix + name;\n }\n }\n }\n\n length = sources.length;\n index = -1;\n\n while (++index < length) {\n cwd = sources[index];\n filePath = (plugin && resolve(cwd, plugin)) || resolve(cwd, name);\n\n if (filePath) {\n return filePath;\n }\n }\n\n return null;\n}", "function trx_addons_options_clone_replace_index(name, idx_new) {\n\t\t\tname = name.replace(/\\[\\d\\]/, '['+idx_new+']');\n\t\t\treturn name;\n\t\t}", "static getName() {\n return 'net.kfalck.' + ServerlessPluginAutoprune.name;\n }", "function expandAliases(unit) {\n\t\tfor (var key in unit) {\n\t\t\tvar alias = unit[key].alias, i = alias.length;\n\t\t\twhile (i--) {\n\t\t\t\tunit[alias[i]] = unit[key];\n\t\t\t}\n\t\t}\n\t}", "function addPluginContribs(type) {\n\treturn es.through(function(data) {\n\t\tif (!/editor\\.main\\.js$/.test(data.path)) {\n\t\t\tthis.emit('data', data);\n\t\t\treturn;\n\t\t}\n\t\tvar contents = data.contents.toString();\n\n\t\t// Rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main'\n\t\tcontents = contents.replace(/\"vs\\/editor\\/editor\\.main\\\"/, '\"vs/editor/edcore.main\"');\n\n\t\tvar extraContent = [];\n\t\tvar allPluginsModuleIds = [];\n\n\t\tmetadata.METADATA.PLUGINS.forEach(function(plugin) {\n\t\t\tallPluginsModuleIds.push(plugin.contrib);\n\t\t\tvar pluginPath = plugin.paths[`npm/${type}`]; // npm/dev or npm/min\n\t\t\tvar contribPath = path.join(__dirname, pluginPath, plugin.contrib.substr(plugin.modulePrefix.length)) + '.js';\n\t\t\tvar contribContents = fs.readFileSync(contribPath).toString();\n\n\t\t\tcontribContents = contribContents.replace(\n\t\t\t\t/define\\((['\"][a-z\\/\\-]+\\/fillers\\/monaco-editor-core['\"]),\\[\\],/,\n\t\t\t\t'define($1,[\\'vs/editor/editor.api\\'],'\n\t\t\t);\n\n\t\t\textraContent.push(contribContents);\n\t\t});\n\n\t\textraContent.push(`define(\"vs/editor/editor.main\", [\"vs/editor/edcore.main\",\"${allPluginsModuleIds.join('\",\"')}\"], function(api) { return api; });`);\n\t\tvar insertIndex = contents.lastIndexOf('//# sourceMappingURL=');\n\t\tif (insertIndex === -1) {\n\t\t\tinsertIndex = contents.length;\n\t\t}\n\t\tcontents = contents.substring(0, insertIndex) + '\\n' + extraContent.join('\\n') + '\\n' + contents.substring(insertIndex);\n\n\t\tdata.contents = Buffer.from(contents);\n\t\tthis.emit('data', data);\n\t});\n}", "function registerPlugin (aPlugin)\n //--------------------------------------------------------------------\n {\n checkParam (aPlugin, \"object\");\n checkParam (aPlugin.id, \"string\");\n\n if (aPlugin.type === \"view\")\n {\n boc.ait.registerView (aPlugin);\n }\n else\n {\n checkParam (aPlugin.load, \"function\");\n boc.ait.pluginList[aPlugin.id] = aPlugin;\n }\n\n return true;\n }", "addCommand(command) {\n this._commands.set(command.name, command);\n if (Array.isArray(command.aliases)) {\n command.aliases.forEach(alias => { this._commands.set(alias, command); });\n }\n }", "function Alias(props) {\n return __assign({ Type: 'AWS::Lambda::Alias' }, props);\n }", "urlAlias(record) {\n return {\n alias: '/slide/' + record.id,\n target: '/slide/' + record.id,\n };\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extract photo IDs from place details object
getPhotoIDs(placeDetails) { let photoIDs = []; if (placeDetails.hasOwnProperty('photos')) { for (var i = 0; i < placeDetails.photos.length; i++) { photoIDs.push(placeDetails.photos[i].photo_reference); } } return photoIDs; }
[ "function loadPhotoIdList() {\n\t\t$.ajax({\n \t\t\turl: \"rest/Image/list\",\n\t\t\tsuccess:function(data) {\n\t\t\t\tconsole.log('rest/Image/list server response: ' + data);\n \t\t\tvar regex = /([\\d]+)/g;\n \t\t\tvar matched = null;\n \t\t\twhile ( matched = regex.exec(data) ) {\n\t\t\t\t\tloadSceneObject( 'rest/Image/' + matched[0] + '.xml', matched[0] );\n\t\t\t\t}\n \t\t} \n\t\t});\n\t}", "async function getPrimaryPhotos() {\n let primaryPhotos = await db.getPool().query(\"SELECT venue_id, photo_filename FROM VenuePhoto WHERE is_primary = 1\");\n let photos = {};\n for (let i = 0; typeof primaryPhotos[i] !== \"undefined\"; i ++) {\n let photo_id = primaryPhotos[i][\"venue_id\"];\n photos[photo_id] = primaryPhotos[i][\"photo_filename\"].substr(2);\n }\n\n\n return photos;\n}", "async function _extract_image_ids (variants){\n if (variants.length == 0 || typeof variants === 'undefined' || variants === null || !Array.isArray(variants)){\n throw new VError(`variants parameter not usable`);\n }\n\n let ids = [];\n\n /*\n * Defaults to plucking the first image. This is fine now but in a future where\n * variants may have multiple images we'll need to do better\n */\n\n for (let i = 0; i < variants.length; i++){\n if (variants[i].image_ids.length > 0){\n ids.push(variants[i].image_ids[0]);\n }\n }\n\n return ids;\n}", "jsonParser(photos){\n let farmIds = [];\n let serverIds = [];\n let ids = [];\n let secretIds = [];\n\n photos.forEach(element => {\n farmIds.push(element.farm);\n serverIds.push(element.server);\n ids.push(element.id);\n secretIds.push(element.secret);\n});\n this.imageLinkBuilder(farmIds,serverIds,ids,secretIds);\n }", "function getExtraDetails(placesMapping, place_id, service) {\n\tservice.getDetails(obj, function(place, status) {\n\t\t\n\t});\n}", "function parseIDs( IDs ) {\r\n var r={ albumID: '0', imageID: '0' };\r\n \r\n var t=IDs.split('/');\r\n if( t.length > 0 ) {\r\n r.albumID=t[0];\r\n if( t.length > 1 ) {\r\n r.imageID=t[1];\r\n }\r\n }\r\n return r;\r\n }", "function findImgId(e) {\n setPicId(e.target.id);\n handleShow();\n }", "static getVenuePhotos(VENUE_ID) {\n\t\treturn Helper.simpleFetch(`/venues/${VENUE_ID}/photos`, \"GET\");\n\t}", "function getPhotoList(){\n\t\tlog(\"getPhotoList()\",\"info\",images_listForInsert);\n\t\treturn images_listForInsert;\n\t}", "function getGooglePlacesData2(results, status) {\n //\n if (status == google.maps.places.PlacesServiceStatus.OK) {\n //\n for (var i = 0, l = results.length; i < l; i++) {\n //\n placesObj = {\n id: \"\",\n name: \"\",\n status: \"\",\n openNow: \"\",\n rating: \"\",\n userRatingTotal: \"\",\n priceLevel: \"\",\n photos: [],\n types: [],\n };\n //\n // Place data\n //\n placesObj.id = results[i].place_id;\n placesObj.name = results[i].name;\n placesObj.status = results[i].business_status;\n // placesObj.openNow = results[i].opening_hours.isOpen;\n placesObj.rating = results[i].rating;\n placesObj.userRatingTotal = results[i].user_ratings_total;\n placesObj.priceLevel = results[i].price_level;\n //\n // Photos\n //\n for (var j = 0, m = results[i].photos.length; j < m; j++) {\n //\n photoObj = {\n url: \"\",\n };\n //\n photoObj.url = results[i].photos[j].html_attributions[0];\n //\n placesObj.photos.push(photoObj);\n //\n }\n //\n // Types\n //\n for (var k = 0, n = results[i].types.length; k < n; k++) {\n //\n typeObj = {\n name: \"\",\n };\n //\n typeObj.name = results[i].types[k];\n //\n placesObj.types.push(typeObj);\n //\n }\n //\n places.push(placesObj);\n //\n }\n //\n renderGooglePlacesData();\n //\n }\n //\n}", "function getBasemapIdTitle(title) {\r\n var bmArray = basemapGallery.basemaps;\r\n for (var i = 0; i < bmArray.length; i++) {\r\n if (bmArray[i].title === title) {\r\n return bmArray[i].id;\r\n }\r\n }\r\n return false;\r\n}", "function getPlaceImage(venue_id) {\n // Foursquare client_id & client_secret\n var client_id = 'SQYRLLQMR5EGIUNYMRXD0GCG5UO0HZOGAD4QUW02CSS0RGBX';\n var client_secret = 'ASBIBJ0LWEKOQBLO1GKT11YPEOSQYECVD4CUDDUHLRGR4RV2';\n\n // Use foursquare api - Get a Venue's Photos\n var foursquareUrl = 'https://api.foursquare.com/v2/venues/' +\n venue_id + '/photos?' + '&v=20171001' +\n '&client_id=' + client_id +\n '&client_secret=' + client_secret;\n\n var innerHTML;\n\n // Send Ajax request. Set async false because this is in for loop.\n $.ajax({\n url: foursquareUrl,\n dataType: \"json\",\n async: false,\n success: function(response) {\n if (response.meta.code == 200) {\n //Get the first picture\n var image = response.response.photos.items[0];\n\n // If there is no picture return default pic.. QUARK!!!\n if (image == null) {\n innerHTML = \"<div class='infowindow-venue-image'>\" +\n '<img class=\"foursquare-img\" src=\"img/default.png\">' +\n \"<div class='duck-talking'>No Image QUARK!!!</div></div>\";\n } else {\n // Get the imgURL\n var prefix = image.prefix;\n var suffix = image.suffix;\n var imgURL = prefix + \"300x300\" + suffix;\n\n innerHTML = \"<div class='infowindow-venue-image'>\" +\n '<img class=\"foursquare-img\" src=\"' + imgURL + '\">' +\n \"</div>\";\n }\n } else {\n innerHTML = \"<div class='infowindow-venue-image'>\" +\n '<img class=\"foursquare-img\" src=\"img/default.png\">' +\n \"<div class='duck-talking'>Failed to get response QUARK!!!</div></div>\"\n }\n }}).fail(function() {\n innerHTML = \"<div class='infowindow-venue-image'>\" +\n '<img class=\"foursquare-img\" src=\"img/default.png\">' +\n \"<div class='duck-talking'>Failed to get response QUARK!!!</div></div>\"\n })\n\n return innerHTML;\n}", "function setPhotos(p){\n\t\t\tfunction setPic(sp){\n\t\t\t\tvar id=\"\";\n\t\t\t\tfor(i in sp){\n\t\t\t\t\tif(i>3)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\n\t\t\t\t\t\tid=\"#photoimg\"+i;\n\t\t\t\t\t\t$(id).css('background-image','url('+sp[i].images[i].source+')');\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif(p.photos==undefined||p.photos==null)\n\t\t\t{\n\t\t\t\t$('#photoimg0').html(\"<h4>NO PHOTOS</h4>\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsetPic(p.photos.data);\n\t\t\t}\n\n\n\t\t}", "getPictures() {\n let pictures = this.props.photoData.map( pic => \n <Photo \n url={`https://live.staticflickr.com/${pic.server}/${pic.id}_${pic.secret}_w.jpg`} \n key={pic.id} \n alt={pic.title}\n />\n );\n\n return pictures;\n }", "findImage (data, id) {\n return data.find(image => image.id === id);\n }", "function getSelectedImagesId() {\n var imageIds = [];\n $( '#sortable > li' ).each( function() {\n imageIds.push( $( this ).attr( 'data-id' ) );\n });\n return imageIds;\n }", "function placeSearch(lat, lng) {\n var query = \"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\" + lat + \",\" + lng + \"&radius=50000&type=park&keyword=kyak&key=AIzaSyDAhGg64lKOYPK-6jEMFKqQlc2TSTHTI2M\";\n\n $.ajax({\n url: query,\n method: \"GET\"\n }).done(function(response) {\n console.log(response);\n var placeId = response.results[0].place_id;\n console.log(placeId);\n\n placeDetail(placeId);\n });\n}", "function populateCommentCount(photoId) {\n\n // loop through the images and find the number of favs for each\n var url = \"https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&photo_id=\" + photoId + \"&format=json&api_key=\"+api_key;\n \n $.ajax({\n url: url,\n jsonp: \"jsoncallback\",\n dataType: \"jsonp\",\n async: false,\n success: function(data){\n $('#' + photoId + \"_comment span\").text(data.photo.comments._content);\n }\n });\n }", "renderDetails(place) {\n // Image\n const source = typeof place.photos[0] !== 'undefined' ?\n place.photos[0].getUrl({maxWidth: 440, maxHeight: 240}) :\n 'https://www.bonque.nl/uploads/plaatje_bij_over_incentro.png';\n\n this.$sidebar.find('.app-sidebar__image').css('background-image', 'url(' + source + ')');\n\n // Intro\n this.$sidebar.find('.feedblock--intro').html(`\n <p>${place.adr_address.substring(0, place.adr_address.lastIndexOf(','))}</p>\n <p>${place.formatted_phone_number}</p>\n <a href=\"${place.url}\">Toon op Google</a>\n `);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns meter target value
getMeterTargetValue(telegram) { let values = telegram.getValues(); return values.has('DATA_RECORD_3_VALUE') ? this.parseMeterValue(values.get('DATA_RECORD_3_VALUE').readUInt32LE()) : null; }
[ "function motorGetSpeed() {\n return currentSpeedRpm;\n}", "get speedVariation() {}", "calculateTurnMeter() {\n this.turnMeter += this.tickRate;\n if (this.turnMeter >= 100) {\n this.turnMeter -= 100;\n this.isTurn = true;\n } \n }", "function getRadiusMeters() {\n return RADIUS_METERS;\n}", "getSpeed() {\n return this.model ? this.model.getCurrentSpeedKmHour() : null;\n }", "_calculateTargetedSpeed() {\n if (this.mcp.autopilotMode !== MCP_MODE.AUTOPILOT.ON) {\n return;\n }\n\n if (this.flightPhase === FLIGHT_PHASE.LANDING) {\n return this._calculateTargetedSpeedDuringLanding();\n }\n\n switch (this.mcp.speedMode) {\n case MCP_MODE.SPEED.OFF:\n return this._calculateLegalSpeed(this.speed);\n\n case MCP_MODE.SPEED.HOLD:\n return this._calculateLegalSpeed(this.mcp.speed);\n\n // future functionality\n // case MCP_MODE.SPEED.LEVEL_CHANGE:\n // return;\n\n case MCP_MODE.SPEED.N1:\n return this._calculateLegalSpeed(this.model.speed.max);\n\n case MCP_MODE.SPEED.VNAV: {\n const vnavSpeed = this._calculateTargetedSpeedVnav();\n\n return this._calculateLegalSpeed(vnavSpeed);\n }\n\n default:\n console.warn('Expected MCP speed mode of \"OFF\", \"HOLD\", \"LEVEL_CHANGE\", \"N1\", or \"VNAV\", but ' +\n `received \"${this.mcp[MCP_MODE_NAME.SPEED]}\"`);\n return this._calculateLegalSpeed(this.speed);\n }\n }", "get WindSpeedMph() {\n return this.windMph;\n }", "function calcTarget(duration, interval, vehicles, capacity) {\r\r\n var time = 60 * 60;\r\r\n var runTime = duration + interval;\r\r\n var full = capacity * vehicles;\r\r\n var target = Math.floor(time / runTime * full);\r\r\n return target;\r\r\n}", "get WindSpeedKmh() {\n return this.windMph;\n }", "getNetEnergy() {\n return this.maxEnergy - this.fatigue\n }", "getSkinTone(){\n\t\treturn this.dataArray[4];\n\t}", "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}", "get target() {\n\t\treturn this.#target;\n\t}", "getEnergyPercent() {\n return this.getNetEnergy() / this.maxEnergy\n }", "get_measuredVoltage()\n {\n return this.liveFunc._measuredVoltage;\n }", "get threshold() {\n return (0, _Conversions.gainToDb)(this._gt.value);\n }", "get PressureMb() {\n return this.pressureMb;\n }", "getDistance() {\n const {origin, destination} = this.props;\n if (app.google && origin && destination) {\n const geometry = app.google.maps.geometry.spherical;\n const meters = geometry.computeDistanceBetween(origin, destination);\n const units = unitsMap[this.state.units];\n const distance = meters * units.value;\n const s = distance === 1 ? '' : 's';\n return `${distance.toFixed(3)} ${units.name}${s}`;\n }\n }", "get KM_PER_AU() {\n return (this.CM_PER_AU / this.CM_PER_KM);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if a request contains a valid jwt cookie with matching username returns error message, or null if authorization is successful
function authorizeRequest(cookies, urlUsername) { // if the request doesn't contain a jwt cookie if (!Object.keys(cookies).includes('jwt')) { return "Unauthorized: request doesn't contain any jwt cookie"; } // try to decode the jsonwebtoken let encodedJWT = cookies.jwt; let secretKey = "C-UFRaksvPKhx1txJYFcut3QGxsafPmwCY6SCly3G6c"; let decodedJWT = null; try { decodedJWT = jsonwebtoken.verify(encodedJWT, secretKey); } catch (err) { // if the jsonwebtoken is expired if (err instanceof jsonwebtoken.TokenExpiredError) { return "Unauthorized: jwt cookie is expired"; } // if we encountered any other errors while decoding the jsonwebtoken else { return "Unauthorized: error verifying jwt cookie"; } } // check the username of the jwt let jwtUsername = decodedJWT.usr; // if the username in jwt does not match the username in the URL if (jwtUsername != urlUsername) { return "Unauthorized: the username in jwt does not match the username in the URL"; } return null; }
[ "function checkCookie(){\n\t// remove jwt\n\tcreateCookie(\"jwt\", \"\", 1);\n\tvar usrName = accessCookie(\"username\");\n\tvar usrPssword = accessCookie(\"usrpassword\");\n\n\tif (usrName!=\"\"){\n\t\tdocument.getElementById('inputUsername').value = usrName;\n\t\tdocument.getElementById('inputPassword').value = usrPssword;\n\t}\n}", "function checkToken(_token, currentUserId) {\n try {\n //ayth6) server decodes token and compares the user's userid with the token's decoded userid\n //ayth6a) if good then can continue with action\n //ayth6b) else ??? return u failed\n const token = _token;\n // next will keep any fields created\n const decodedToken = jwt.verify(token, \"my super duper secret code\");\n if (currentUserId == decodedToken.userId) {\n return true;\n } else {\n return false;\n }\n } catch (error) {\n console.log(error)\n // res.status(401).json({ message: \"You are not authenticated!\" });\n }\n}", "function validateToken(req, res) {\r\n var token = getToken(req);\r\n var user = users.getUserByToken(token);\r\n var isValidToken = user != undefined && user != '';\r\n console.log('[validToken] req=' + req.url);\r\n console.log('[validToken] Is Valid Token=%s User=%s', isValidToken, user);\r\n if (!isValidToken) {\r\n invalidToken(req, res);\r\n }\r\n return token;\r\n}", "async function ensureToken(req, res, next) {\n try {\n var bearerHeader = req.headers['authorization']\n if (typeof bearerHeader == 'undefined') {\n console.log('undefined, gak ada token');\n return res.status(403).send({\n 'message': 'token not provided'\n })\n }\n var bearerToken = bearerHeader.split(' ')\n var tokenBracket = bearerToken[0]\n var tokenProvided = bearerToken[1]\n\n if (tokenBracket !== 'bearer')\n return res.status(403).send({'message': 'worng format header Authorization'})\n\n const user = await jwt.verify(tokenProvided, process.env.SECRET_KEY)\n\n if(user.isActive==false)\n return res.status(403).send({\"message\":\"need activation user.\"})\n \n req.body.user = user\n next()\n } catch (error) {\n console.log(error);\n return res.status(403).send({\n 'message': 'token is not valid'\n })\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 getUsername() {\n let userName = document.getElementById('username_input_field').value;\n\n // if username supplied is invalid, alert user, and return null\n const validUsernameRegExp = new RegExp('^([a-zA-Z0-9_-]{3,16})$');\n if (!validUsernameRegExp.test(userName)) {\n alert('Your username can only contain alphanumeric, '\n + ' underscore, and hyphen characters (a-z A-Z 0-9 _ -). '\n + 'It should be at least 3 characters long.');\n return null;\n }\n\n // store username for next time\n setToLocalStorage(userNameKey, userName);\n\n return userName;\n}", "function getUserId(req) {\n try {\n const token = req.headers['authorization']; //it is UserId in header\n if (!token) {\n console.log(`[E] getUserId - No token found in authorization header`);\n return;\n }\n /*\n family_name:\"Sarosh\"\n given_name:\"Rafat\"\n name:\"Rafat Sarosh\"\n role:\"user\"\n roles:Array(0) []\n length:0\n username:\"rafat.sarosh@axleinfo.com\"\n displayName:\"Rafat Sarosh\"\n iat:1587305018\n id:\"8584\"\n */\n const result = jwt.verify(token, process.env.Session_Key, verifyOptions);\n if (typeof result === 'string') {\n return result;\n }\n else {\n return result.username; //Org header has the full user object\n }\n }\n catch (ex) {\n console.log(`[E] getUserId ${ex.message}`);\n return;\n }\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}", "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 checkJWT() {\n if ( !isLoggedIn() )\n window.location.replace('/sign-in/?return=/daily-data/');\n}", "function isAuthenticatedAs(req, username) {\n if (isAuthenticated(req)) {\n if (getUsername(req) === username) {\n return true;\n } else {\n return false;\n }\n }\n}", "isTokenExpired(token){\n try {\n const decoded = decode(token);\n return (decoded.exp < Date.now() / 1000);\n } catch (err) {\n console.log(\"expired check failed!\");\n return true;\n }\n }", "function validateClaimName (name) {\n\tvar deferred = new Promise(function(resolve, reject) {\n\t\t// validate the characters in the 'name' field\n\t\tif (name.length < 1) {\n\t\t\treject(new NameError(\"You must enter a name for your claim\"));\n\t\t\treturn;\n\t\t}\n\t\tvar invalidCharacters = /[^A-Za-z0-9,-]/g.exec(name);\n\t\tif (invalidCharacters) {\n\t\t\treject(new NameError('\"' + invalidCharacters + '\" is not allowed. Use only the following characters: A-Z, a-z, 0-9, and \"-\"'));\n\t\t\treturn;\n\t\t} \n\t\t// make sure the claim name is still available\n\t\tvar xhttp;\n\t\txhttp = new XMLHttpRequest();\n\t\txhttp.open('GET', '/api/isClaimAvailable/' + name, true);\n\t\txhttp.responseType = 'json';\n\t\txhttp.onreadystatechange = function() {\n\t\t\tif (this.readyState == 4 ) {\n\t\t\t\tif ( this.status == 200) {\n\t\t\t\t\tif (this.response == true) {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject( new NameError(\"That name has already been claimed by spee.ch. Please choose a different name.\"));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treject(\"request to check claim name failed with status:\" + this.status);\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t\txhttp.send();\n\t});\n\treturn deferred;\n}", "_getTokenFromRequest (req) {\n let authorization = req.get ('authorization');\n\n if (authorization) {\n let parts = authorization.split (' ');\n\n if (parts.length !== 2)\n return Promise.reject (new BadRequestError ('invalid_authorization', 'The authorization header is invalid.'));\n\n if (!BEARER_SCHEME_REGEXP.test (parts[0]))\n return Promise.reject (new BadRequestError ('invalid_scheme', 'The authorization scheme is invalid.'));\n\n return Promise.resolve (parts[1]);\n }\n else if (req.body && req.body.access_token) {\n return Promise.resolve (req.body.access_token);\n }\n else if (req.query && req.query.access_token) {\n return Promise.resolve (req.query.access_token);\n }\n else {\n return Promise.reject (new BadRequestError ('missing_token', 'The access token is missing.'));\n }\n }", "function isUsersReal (req, project4webaudio) {\n\tconsole.log(\"checking user\");\n\n\tif (req.user.name !== project4webaudio.username) {\n\n\t\tconsole.log(\"Invalid User\");\n\t\tres.json({ message: 'FAILED' });\n\t\treturn false\n\t}\n\treturn true\n}", "function getUsername(req) {\n if (isAuthenticated(req)) {\n return req.virtuallyNoTag_authenticationInformation.response.username;\n }\n return null;\n}", "function validateAndInitHeader(event) {\n vm.isAuth = TcAuthService.isAuthenticated()\n if (vm.isAuth) {\n initHeaderProps(event)\n } else {\n loadUser().then(function(token) {\n // update auth flag\n vm.isAuth = TcAuthService.isAuthenticated()\n initHeaderProps(event)\n }, function(error) {\n // do nothing, just show non logged in state of navigation bar\n })\n }\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}", "async function checkOreAccessToken(oreAccessToken, req) {\n let errHead = `invalid ore-access-token `\n let errMsg = ''\n try {\n let requestParams = {}\n if (!process.env.VERIFIER_PUBLIC_KEY) {\n errMsg = `verifier public key is missing. Provide a valid verifier public key as environment variable`;\n throw new Error(`${errMsg}`);\n }\n\n const verifierPublicKey = process.env.VERIFIER_PUBLIC_KEY.replace(/\\\\n/g, '\\n')\n\n const payload = await jwt.verify(oreAccessToken, verifierPublicKey, {\n algorithms: [\"ES256\"]\n })\n if (req.query && req.body && Object.keys(req.query).length > 0 && Object.keys(req.body).length > 0) {\n requestParams[\"http-url-params\"] = req.query\n requestParams[\"http-body-params\"] = req.body\n } else if (Object.keys(req.query).length > 0) {\n requestParams = req.query\n } else {\n requestParams = req.body\n }\n\n const isValid = await checkRequestParams(payload.reqParamHash, requestParams)\n return isValid\n } catch (error) {\n if (error.message == 'jwt expired') {\n errMsg = ` Expired ore-access-token. Provide a valid token.`\n }\n\n if (error.message == 'invalid signature') {\n errMsg = ` Invalid signature for ore-access-token. Make sure ore-access-token is signed with a valid key`\n }\n\n if (error.message == 'jwt malformed') {\n errMsg = ` Malformed ore-access-token. Make sure the ore-access-token has the valid right name and voucher.`\n }\n\n logError(\"Error\", `${errHead}:${errMsg}:${error.message}`)\n throw new Error(`${errHead}:${errMsg}:${error.message}`)\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to add a grade into the array
function add(grade) { this.grades.push(grade); }//end add function
[ "addGrades(grade) {\r\n this.grades.push(grade);\r\n this.write();\r\n }", "function updateStudentGrade (studnetId,assignmentId,studentScore,gradebookData){\n gradebookData[studnetId].grades[assignmentId] = studentScore;\n\n}", "function getStudentGrade(){\n\t// Input Object\n var studentDetails = [\n {name:'David',marks:80},\n {name:'Vinoth',marks:77},\n {name:'Divya',marks:88},\n {name:'Ishitha',marks:95},\n {name:'Thomas',marks:68}\n ];\n // Array of students with Grade & Rating.\n const studentsGradeRatingArr = [];\n // Iterating students and adding their grades & Rating according to there marks\n\tstudentDetails.forEach(function(student){\n\t\t// Student object with Grade & Rating.\n\t const studentGradeRatingObj = { \n\t \tname: student.name, \n\t \tgrade: checkGrade(student.marks), \n\t \trating: checkRating(student.marks)\n\t };\n\t studentsGradeRatingArr.push(studentGradeRatingObj);\n\t});\n\treturn studentsGradeRatingArr;\n}", "function createNewAssignment(assignmentName,totalPointValue,assignmentData,gradebookData){\n var assignment = new Assignment(assignmentName,totalPointValue,assignmentData);\n assignmentData.push(assignment);//update the assignmentData array\n //task 9: set the default assignment score\n for (var i=0 ;i< gradebookData.length;i++){\n gradebookData[i].grades[assignment.id]=0;\n }\n}", "assignMarks(maths, english, science) {\n this.marks.push({\n mathMarks: maths,\n englishMarks: english,\n scienceMarks: science\n });\n }", "function addStudent(){\n //consoleOut('addStudent called');\n var enteredName = $('#studentName').val();\n var enteredCourse = $('#course').val();\n var enteredGrade = $('#studentGrade').val();\n var student = {\n name: enteredName,\n course: enteredCourse,\n grade: enteredGrade\n };\n //consoleOut('Student obj ', student);\n student_array.push(student);\n updateData();\n}", "averageAssignmentGrade(grades) {\n // return grades.reduce(function(acc, grade) {\n var avg = grades.reduce(function(acc, grade) {\n return acc + grade.percentage;\n }, 0) / grades.length;\n return Number(avg.toFixed(2));\n // return avg;\n }", "function Grade(student_id, score, confidence){\n\tthis.student_id = student_id\n\tthis.score = score\n\tthis.confidence = confidence\n}", "function createGradeObjects(){\n \n}", "function changeGradeType(ele, initialScore) {\r\n let score = $(ele).text();\r\n\r\n if (gradeType == \"Percent\") {\r\n score = parseInt(score);\r\n !score && score != 0 ? score = \"Average Grade\" : score = score;\r\n // Sorry\r\n if(score <= 100 && score >= 93) score = \"A\";\r\n else if(score <= 92 && score >= 90) score = \"A-\";\r\n else if(score <= 89 && score >= 87) score = \"B+\";\r\n else if(score <= 86 && score >= 83) score = \"B\";\r\n else if(score <= 82 && score >= 80) score = \"B-\";\r\n else if(score <= 79 && score >= 77) score = \"C+\";\r\n else if(score <= 76 && score >= 73) score = \"C\";\r\n else if(score <= 72 && score >= 70) score = \"C-\";\r\n else if(score <= 69 && score >= 67) score = \"D+\";\r\n else if(score <= 66 && score >= 63) score = \"D\";\r\n else if(score <= 62 && score >= 60) score = \"D-\";\r\n else if(score < 60) score = \"F\";\r\n $(ele).text(score);\r\n } else if (gradeType == \"Letter\") {\r\n score = letterToGPA[score];\r\n $(ele).text(score);\r\n } else if (gradeType == \"4.0\") {\r\n $(ele).text(initialScore);\r\n }\r\n}", "function addToScore(points){\r\n\t\tscore += points;\r\n\t\taddLifeRunningTotal += points;\r\n\t}", "function addToRank() {\n rank.push([name, scores]);\n}", "function calculateCollegeGPA() {\n var sum = 0;\n var creditSums = 0;\n var grades = [];\n var credits = [];\n var finalGPA = 0;\n\n var i;\n\n for (i = 1; i < counter + 1; i++) {\n if (document.getElementById(\"grade\" + i).value !== \"\") {\n grades.push(parseFloat(document.getElementById(\"grade\" + i).value));\n }\n\n if (document.getElementById(\"credit\" + i).value !== \"\") {\n credits.push(parseFloat(document.getElementById(\"credit\" + i).value));\n }\n }\n\n for (i = 0; i < credits.length; i++) {\n sum = sum + credits[i];\n creditSums = creditSums + grades[i] * credits[i];\n }\n\n finalGPA = creditSums / sum;\n\n document.getElementById(\"gpa-output\").innerHTML = finalGPA.toFixed(2);\n}", "function giveBonus(studs) {\n var res = studs.map(function(stud){\n var newStud = {name: stud.name, grade: stud.grade+10};\n return newStud;\n });\n return res;\n}", "function addScore() {\n\tvar ref = database.ref('rank');\n\tvar data = {\n\t\tname: userName,\n\t\tvalue: score\n\t}\n\tref.push(data);\n}", "gpaCalc() {\r\n let totalPoints = 0;\r\n let totalUnits = 0;\r\n const macPoints = {\"A+\": 12, \"A\": 11, \"A-\": 10,\r\n \"B+\": 9, \"B\": 8, \"B-\": 7,\r\n \"C+\": 6, \"C\": 5, \"C-\": 4,\r\n \"D+\": 3, \"D\": 2, \"D-\": 1,\r\n \"F\": 0};\r\n\r\n if (this.itemList.length > 0) {\r\n this.itemList.forEach(function(entry) {\r\n let thisCourseGrade;\r\n\r\n if (Object.keys(macPoints).includes(entry.grade)) {\r\n thisCourseGrade = macPoints[entry.grade];\r\n } else {\r\n thisCourseGrade = parseInt(entry.grade);\r\n }\r\n\r\n totalPoints += (thisCourseGrade * entry.units);\r\n totalUnits += entry.units;\r\n })\r\n }\r\n\r\n const totalGPA = totalPoints / totalUnits;\r\n return totalGPA.toFixed(1);\r\n }", "gradeSubmission(student){\n //only python files are allowed\n if (this.file.slice(-2) !== 'py'){\n this.grade = 0;\n student.calculateStudentAverage()\n this.comment = \"Only py files are allowed!\"\n return\n }\n //submission is before the deadline\n if (this.submissionTime > this.deadline){\n this.grade = 0;\n student.calculateStudentAverage()\n this.comment = \"Submission after deadline!\"\n return\n }\n //if formal requirements are met, the submission is evaluated by the judge\n //instance of Student and Weektask are updated\n this.grade = getRandomInt(6);\n student.calculateStudentAverage()\n this.weektask.getWeektaskAverage()\n this.comment = \"Submitted and graded\"\n\n }", "function addGrammarPoint(e) {\n e.preventDefault();\n\n // const point = grammarPoint.value;\n // const grade = level.value;\n // const ques = question.value;\n // const ans = answer.value;\n\n const newGrammarPoint = {\n grammarPoint: grammarPoint.value,\n level: classLevel.value,\n ques: question.value,\n ans: answer.value\n };\n gpDB.push(newGrammarPoint);\n console.log(gpDB);\n}", "function betterThanAverage(classGrades, yourGrade){\n let classAvg = 0;\n for(let i = 0; i < classGrades.length; i++){\n //take each class point\n classAvg += classGrades[i]\n }\n classAvg = classAvg / classGrades.length;\n //return true if your grade is bigget than the class Average\n return yourGrade > classAvg\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format) and BinaryParser( FBX Binary format)
function FBXTree() {}
[ "function infixToBtree(expression)\n{\n var tokens = expression.split(/([\\d\\.]+|[\\*\\+\\-\\/\\(\\)])/).filter(notEmpty);\n var operatorStack = [];\n var lastToken = '';\n var queue = [];\n\n while (tokens.length > 0)\n {\n var currentToken = tokens.shift();\n\n if (isNumber(currentToken)) \n {\n\t queue.push(new bigdecimal.BigDecimal(currentToken));\n }\n\telse if (isUnaryOp(currentToken, lastToken))\n\t{\n\t lastToken = currentToken;\n\t //expect next token to be a number\n\t currentToken = tokens.shift();\n\t //minus is the only unary op supported for now\n\t queue.push(new bigdecimal.BigDecimal(currentToken).negate());\t\n\t}\n else if (isOperator(currentToken)) \n {\n while (getPrecedence(currentToken) <= getPrecedence(operatorStack.last) ) \n {\n\t\tvar newNode = new BinaryTree(queue.pop(), queue.pop(), operatorStack.pop()); \t\t\n\t\tqueue.push(newNode);\n }\n\n operatorStack.push(currentToken);\n\n }\n else if (currentToken == '(')\n {\n operatorStack.push(currentToken);\n }\n else if (currentToken == ')')\n {\n while (operatorStack.last != '(')\n {\n \t if (operatorStack.length == 0)\n \t return \"Error in braces count\";\n\n\t\tvar newNode = new BinaryTree(queue.pop(), queue.pop(), operatorStack.pop()); \t\t\n\t\tqueue.push(newNode);\n }\t\n operatorStack.pop();\t\t\n }\n\tlastToken = currentToken; \n } \n\n while (operatorStack.length != 0)\n {\n if (/^[\\(\\)]$/.test(operatorStack.last))\n\t\treturn \"Error in braces count\";\n \n\tvar newNode = new BinaryTree(queue.pop(), queue.pop(), operatorStack.pop()); \t\t\n\tqueue.push(newNode);\n \n }\n //return Btree root\n return queue[0];\n}", "constructor(){ // Definindo construtor da classe BinaryTree\n this.root = null; // inicializa a raiz da arvore como sendo nula\n }", "function createTree(x) {\n\t// Create the root\n\tvar a = createVector(width / 2, height);\n\tvar b = createVector(width / 2, height - 100);\n\ttree = new Tree(a, b);\n\n\t// Create the branches\n\tcreateXGenerations(x);\n}", "function AABBTree() {}", "initTree() {\n // var format=function(features){features.forEach(p=>{console.log(`{id:${new Number(p.properties.nid)}, x:${new Number(p.geometry.coordinates[1])}, y: ${new Number(p.geometry.coordinates[0])}},`)});}\n this._tree = new KDBush(this._points, p => Math.round(p.x), p => Math.round(p.y), 64, Int32Array);\n }", "breadthFirstTraversal() {\n let queue = [];\n queue.push(this.root);\n while (queue.length){\n let node = queue.shift();\n console.log(node.val);\n if (node.left){queue.push(node.left);}\n if (node.right){queue.push(node.right)};\n }\n }", "function treeToBBCode(node) {\n\t\tvar k, n,\n\t\t\tchecked, start, end,\n\t\t\tbb = [],\n\t\t\tprops = [];\n\n\t\tif (typeof node.item == 'function') {\n\t\t\tfor (k = 0; n = node[k++];) {\n\t\t\t\tbb.push(treeToBBCode(n));\n\t\t\t}\n\t\t\treturn bb.join('');\n\t\t}\n\n\t\tif (node.getAttribute && node.getAttribute('userjsishidden') == 'true') {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (node.nodeType) {\n\t\t\tcase Node.ELEMENT_NODE:\n\t\t\t\tvar nname = node.nodeName.toLowerCase();\n\t\t\t\tvar def = treeToBBCode.defaults[nname];\n\t\t\t\tif (def) {\n\t\t\t\t\t//generic behavior\n\t\t\t\t\tbb.push(def.before || '');\n\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\tbb.push(def.after || '');\n\t\t\t\t} else {\n\t\t\t\t\t//special cases\n\t\t\t\t\tswitch (nname) {\n\t\t\t\t\t\tcase 'a':\n\t\t\t\t\t\t\tif (node.href.indexOf('mailto:') === 0) {\n\t\t\t\t\t\t\t\tbb.push('[email=' + node.href.substring(7) + ']');\n\t\t\t\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\t\t\t\tbb.push('[/email]');\n\t\t\t\t\t\t\t} else if (node.className.indexOf(\"attach\") >= 0) {\n\t\t\t\t\t\t\t\tbb.push('[ATTACH=' + node.href + ']');\n\t\t\t\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\t\t\t\tbb.push('[/ATTACH]');\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbb.push('[url=' + node.href + ']');\n\t\t\t\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\t\t\t\tbb.push('[/url]');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'div':\n\t\t\t\t\t\t\tprops = [{\n\t\t\t\t\t\t\t\t\tname: 'textAlign',\n\t\t\t\t\t\t\t\t\tforceValue: 'left',\n\t\t\t\t\t\t\t\t\tbefore: '[align=left]',\n\t\t\t\t\t\t\t\t\tafter: '[/align]'\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: 'textAlign',\n\t\t\t\t\t\t\t\t\tforceValue: 'right',\n\t\t\t\t\t\t\t\t\tbefore: '[align=right]',\n\t\t\t\t\t\t\t\t\tafter: '[/align]'\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tchecked = checkCSSProps(node, props);\n\n\t\t\t\t\t\t\tbb.push(checked.start);\n\t\t\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\t\t\tbb.push(checked.end);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'img':\n\t\t\t\t\t\t\tvar smileyCode = getSmileyCode(node);\n\t\t\t\t\t\t\tbb.push(smileyCode ? ' ' + smileyCode + ' ' : '[img]' + node.src + '[/img]');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'ul':\n\t\t\t\t\t\t\tprops = [{\n\t\t\t\t\t\t\t\tname: 'listStyleType',\n\t\t\t\t\t\t\t\tforceValue: 'decimal',\n\t\t\t\t\t\t\t\tbefore: '[list type=decimal]',\n\t\t\t\t\t\t\t\tafter: '[/list]'\n\t\t\t\t\t\t\t}, ];\n\t\t\t\t\t\t\tchecked = checkCSSProps(node, props);\n\n\t\t\t\t\t\t\tbb.push((checked.start !== '') ? checked.start : '[list]');\n\t\t\t\t\t\t\tvar li, lis = node.querySelectorAll('li');\n\t\t\t\t\t\t\tfor (k = 0; li = lis[k++];) {\n\t\t\t\t\t\t\t\tbb.push('\\n [*] ' + trim(treeToBBCode(li)));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbb.push('[/list]');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'span':\n\t\t\t\t\t\t\t//check for css properties\n\t\t\t\t\t\t\tprops = [{\n\t\t\t\t\t\t\t\t\tname: 'textDecoration',\n\t\t\t\t\t\t\t\t\tforceValue: 'underline',\n\t\t\t\t\t\t\t\t\tbefore: '[u]',\n\t\t\t\t\t\t\t\t\tafter: '[/u]'\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: 'color',\n\t\t\t\t\t\t\t\t\tbefore: '[color=@value]',\n\t\t\t\t\t\t\t\t\tafter: '[/color]'\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: 'fontFamily',\n\t\t\t\t\t\t\t\t\tbefore: '[font=@value]',\n\t\t\t\t\t\t\t\t\tafter: '[/font]'\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: 'fontSize',\n\t\t\t\t\t\t\t\t\tbefore: '[size=@value]',\n\t\t\t\t\t\t\t\t\tafter: '[/size]',\n\t\t\t\t\t\t\t\t\tvalues: {\n\t\t\t\t\t\t\t\t\t\t'xx-small': 1,\n\t\t\t\t\t\t\t\t\t\t'x-small': 2,\n\t\t\t\t\t\t\t\t\t\t'small': 3,\n\t\t\t\t\t\t\t\t\t\t'medium': 4,\n\t\t\t\t\t\t\t\t\t\t'large': 5,\n\t\t\t\t\t\t\t\t\t\t'x-large': 6,\n\t\t\t\t\t\t\t\t\t\t'xx-large': 7\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];\n\t\t\t\t\t\t\tchecked = checkCSSProps(node, props);\n\t\t\t\t\t\t\tstart = checked.start;\n\t\t\t\t\t\t\tend = checked.end;\n\n\t\t\t\t\t\t\t//check for class attribute\n\t\t\t\t\t\t\tprops = [{\n\t\t\t\t\t\t\t\t\tname: 'centertext',\n\t\t\t\t\t\t\t\t\tbefore: '[align=center]',\n\t\t\t\t\t\t\t\t\tafter: '[/align]'\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: 'bbc_tt',\n\t\t\t\t\t\t\t\t\tbefore: '[tt]',\n\t\t\t\t\t\t\t\t\tafter: '[/tt]'\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\tvar p;\n\t\t\t\t\t\t\tfor (k = 0; p = props[k++];) {\n\t\t\t\t\t\t\t\tif (node.className.indexOf(p.name) >= 0) {\n\t\t\t\t\t\t\t\t\tstart += p.before;\n\t\t\t\t\t\t\t\t\tend += p.after;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbb.push(start);\n\t\t\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\t\t\tbb.push(end);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'p':\n\t\t\t\t\t\t\tvar ns = node.nextElementSibling || node.nextSibling;\n\t\t\t\t\t\t\t//detect quote\n\t\t\t\t\t\t\tif (node.className.indexOf(\"cite\") >= 0 &&\n\t\t\t\t\t\t\t\tns &&\n\t\t\t\t\t\t\t\tns.nodeName.toLowerCase() == 'blockquote' &&\n\t\t\t\t\t\t\t\tns.className.indexOf(\"bbquote\") >= 0) {\n\t\t\t\t\t\t\t\t//TODO: user quote - this will break when the forums get localized !\n\t\t\t\t\t\t\t\tns.__userNameQuoted = node.textContent.replace(/.*originally\\s+posted\\s+by\\s+/i, '').replace(/\\s*\\:$/, '');\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'blockquote':\n\t\t\t\t\t\t\tif (node.className.indexOf(\"bbquote\") >= 0) {\n\t\t\t\t\t\t\t\tbb.push('[QUOTE' + (node.__userNameQuoted ? '=' + node.__userNameQuoted : '') + ']');\n\t\t\t\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\t\t\t\tbb.push('[/QUOTE]');\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase Node.DOCUMENT_NODE: // 9\n\t\t\tcase Node.DOCUMENT_FRAGMENT_NODE: // 11\n\t\t\t\tbb.push(treeToBBCode(node.childNodes));\n\t\t\t\tbreak;\n\t\t\tcase Node.TEXT_NODE: //3\n\t\t\tcase Node.CDATA_SECTION_NODE: // 4\n\t\t\t\tvar text = node.nodeValue;\n\t\t\t\tif (!node.selectSingleNode('ancestor::pre'))\n\t\t\t\t\ttext = text.replace(/\\n[ \\t]+/g, '\\n');\n\t\t\t\tbb.push(text);\n\t\t\t\tbreak;\n\t\t}\n\t\treturn bb.join('');\n\t}", "parseXML(rawText) {\n // TODO: different code paths for XLIFF 1.2 vs. 2.0 (this is the only way to support both)\n // Document.init();\n // Working - just return the Document object from this function\n const deferred = $q.defer();\n const self = this;\n\n // <xliff xmlns=\"urn:oasis:names:tc:xliff:document:2.0\" version=\"2.0\"\n\n const xml = parser.parseFromString(rawText, 'text/xml');\n\n // Parsing error?\n const parserError = xml.querySelector('parsererror');\n // if (parserError !== null) {\n if (xml.documentElement.nodeName == 'parsererror') {\n console.log('Error while parsing XLIFF file');\n $log.error('Error while parsing');\n const errorString = new XMLSerializer().serializeToString(parserError);\n $log.error(errorString);\n\n $log.error(new XMLSerializer().serializeToString(xml));\n self.parsingError = true;\n return;\n } else {\n self.parsingError = false;\n }\n\n const Document = {};\n // Set Document DOM to the parsed result\n Document.DOM = xml;\n // Working - the XLIFF parser returns a Document representation of the XLIFF\n Document.segments = [];\n Document.sourceLang = sourceLang;\n Document.targetLang = targetLang;\n\n Document.segmentStates = [];\n\n const file = xml.querySelector('file');\n const xliffTag = xml.querySelector('xliff');\n\n $log.log('xliff version: ');\n $log.log(xliffTag.getAttribute('version'));\n\n // TODO: fork here, depending on xliff version -- we want to support both 2.0 and 1.2 for the time being\n\n // Read the source and target language - set defaults to English and German\n var sourceLang = file.getAttribute('source-language');\n if (!sourceLang) sourceLang = 'en';\n Document.sourceLang = sourceLang;\n\n var targetLang = file.getAttribute('target-language');\n if (!targetLang) targetLang = 'de';\n Document.targetLang = targetLang;\n\n // Working -- segmentation with <seg-source> and <mrk> tags is Optional\n // add support for pure <source> and <target>\n const sourceSegments = this.getTranslatableSegments(xml);\n\n // for every segment, get its matching target mrk, if it exists - note: it may not exist\n const targetSegments = _.map(sourceSegments,\n (seg) => {\n if (seg.nodeName === 'mrk') {\n return self.getMrkTarget(xml, seg);\n }\n // there's no mrks inside <target>, just a <target> -- TODO: do we require target nodes to exist?\n return seg.parentNode.querySelector('target');\n },\n );\n\n // we can assume that translators will want to translate every segment, so there should be at least an\n // empty target node corresponding to each source node\n const sourceWithTarget = _.zip(sourceSegments, targetSegments);\n _.each(sourceWithTarget,\n (seg) => {\n const sourceText = seg[0].textContent;\n const targetText = seg[1] ? seg[1].textContent : '';\n if (!seg[1]) {\n const mid = seg[0].getAttribute('mid');\n $log.info('Target segment missing: ' + mid);\n seg[1] = self.createNewMrkTarget(Document.DOM, seg[0], '', targetLang);\n }\n\n const segPair = {\n source: seg[0].textContent,\n target: seg[1].textContent,\n sourceDOM: seg[0],\n targetDOM: seg[1],\n // TODO: the segment state should be taken from the XLIFF see XliffTwoParser\n state: 'initial',\n };\n\n // Add the pairs so we can access both sides from a single ngRepeat\n Document.segments.push(segPair);\n\n // TODO: make this useful\n // Document.translatableNodes.push(seg);\n });\n\n // TODO: remove the document-loaded event, and use the result of the resolved promise directly\n // tell the world that the document loaded\n $log.log('Xliff parser returning');\n // $log.log(Document);\n deferred.resolve(Document);\n\n // return Document;\n return deferred.promise;\n }", "function cXparse(src) {\n var frag = new _frag();\n\n // remove bad \\r characters and the prolog\n frag.str = _prolog(src);\n\n // create a root element to contain the document\n var root = new _element();\n root.name = \"ROOT\";\n\n // main recursive function to process the xml\n frag = _compile(frag);\n\n // all done, lets return the root element + index + document\n root.contents = frag.ary;\n root.index = _Xparse_index;\n _Xparse_index = new Array();\n return root;\n}", "buildTree() {\n this.clear();\n\n const columnsCount = this.#sourceSettings.getColumnsCount();\n let columnIndex = 0;\n\n while (columnIndex < columnsCount) {\n const columnSettings = this.#sourceSettings.getHeaderSettings(0, columnIndex);\n const rootNode = new TreeNode();\n\n this.#rootNodes.set(columnIndex, rootNode);\n this.buildLeaves(rootNode, columnIndex, 0, columnSettings.origColspan);\n\n columnIndex += columnSettings.origColspan;\n }\n\n this.rebuildTreeIndex();\n }", "function mapFamily(arr) {\n console.log('FAM'.green, arr);\n var husbands = arr.filter(node => node.tag === 'HUSB'),\n wives = arr.filter(node => node.tag === 'WIFE'),\n parents = [],\n married = extractValue('MARR', arr),\n children = arr.filter(node => node.tag === 'CHIL');\n pino.info('HUSB'.red, husbands);\n\n if (husbands.length > 0) parents.push(husbands[0]);\n if (wives.length > 0) parents.push(wives[0]);\n //\n parents = parents.map(p => p.data);\n\n var events = ['MARR','DIV']\t// what else?\n .map(key => ({\n type: key,\n nodeList: arr.filter(node => node.tag === key)\n }));\n events = events.filter(obj => obj.nodeList.length > 0)\n .map(obj => ({\n id: 'e_' + treeData.eventId++,\n type: obj.type,\n date: Date.parse(extractValue('DATE', obj.nodeList)),\t// to milliseconds\n place: extractValue('PLAC', obj.nodeList)\n }));\n pino.info('EVENT'.rainbow, events);\n\n var marriages = events.filter(e => e.type === \"MARR\");\n var marriageDate = (marriages.length > 0) ? marriages[0].date : \"\";\n\n return {\n parents: parents,\n married: married || \"unknown\",\n marriageDate: marriageDate,\n children: children.length > 0 ? children.map(obj => obj.data) : [],\n events: events,\n notes: []\n };\n}", "get tree() {\n return this.buffer ? null : this._tree._tree\n }", "function readNode( lines, firstline, list ) {\n\n\t\t\tvar node = { name: '', type: '', frames: [] };\n\t\t\tlist.push( node );\n\n\t\t\t// parse node type and name\n\n\t\t\tvar tokens = firstline.split( /[\\s]+/ );\n\n\t\t\tif ( tokens[ 0 ].toUpperCase() === 'END' && tokens[ 1 ].toUpperCase() === 'SITE' ) {\n\n\t\t\t\tnode.type = 'ENDSITE';\n\t\t\t\tnode.name = 'ENDSITE'; // bvh end sites have no name\n\n\t\t\t} else {\n\n\t\t\t\tnode.name = tokens[ 1 ];\n\t\t\t\tnode.type = tokens[ 0 ].toUpperCase();\n\n\t\t\t}\n\n\t\t\tif ( nextLine( lines ) !== '{' ) {\n\n\t\t\t\tconsole.error( 'THREE.BVHLoader: Expected opening { after type & name' );\n\n\t\t\t}\n\n\t\t\t// parse OFFSET\n\n\t\t\ttokens = nextLine( lines ).split( /[\\s]+/ );\n\n\t\t\tif ( tokens[ 0 ] !== 'OFFSET' ) {\n\n\t\t\t\tconsole.error( 'THREE.BVHLoader: Expected OFFSET but got: ' + tokens[ 0 ] );\n\n\t\t\t}\n\n\t\t\tif ( tokens.length !== 4 ) {\n\n\t\t\t\tconsole.error( 'THREE.BVHLoader: Invalid number of values for OFFSET.' );\n\n\t\t\t}\n\n\t\t\tvar offset = new THREE.Vector3(\n\t\t\t\tparseFloat( tokens[ 1 ] ),\n\t\t\t\tparseFloat( tokens[ 2 ] ),\n\t\t\t\tparseFloat( tokens[ 3 ] )\n\t\t\t);\n\n\t\t\tif ( isNaN( offset.x ) || isNaN( offset.y ) || isNaN( offset.z ) ) {\n\n\t\t\t\tconsole.error( 'THREE.BVHLoader: Invalid values of OFFSET.' );\n\n\t\t\t}\n\n\t\t\tnode.offset = offset;\n\n\t\t\t// parse CHANNELS definitions\n\n\t\t\tif ( node.type !== 'ENDSITE' ) {\n\n\t\t\t\ttokens = nextLine( lines ).split( /[\\s]+/ );\n\n\t\t\t\tif ( tokens[ 0 ] !== 'CHANNELS' ) {\n\n\t\t\t\t\tconsole.error( 'THREE.BVHLoader: Expected CHANNELS definition.' );\n\n\t\t\t\t}\n\n\t\t\t\tvar numChannels = parseInt( tokens[ 1 ] );\n\t\t\t\tnode.channels = tokens.splice( 2, numChannels );\n\t\t\t\tnode.children = [];\n\n\t\t\t}\n\n\t\t\t// read children\n\n\t\t\twhile ( true ) {\n\n\t\t\t\tvar line = nextLine( lines );\n\n\t\t\t\tif ( line === '}' ) {\n\n\t\t\t\t\treturn node;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tnode.children.push( readNode( lines, line, list ) );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}", "serialiseTree() {\n\n }", "static parseTypedFiles(callback){\n //klassenvariablen mit Dateinamen im typ ordner\n BinaryBRTypedFile.BR_TYPE_FILES =[\n \"myStruct\"\n // \"fatdumb\"\n //mit komma weitere dateien einhängen...\n ];\n //hier werden rohinformationen der Structs abgelegt\n BinaryBRTypedFile.brStructs = [];\n //zähler für gefundene structs, interne nutzung\n BinaryBRTypedFile.brStructsParsed = 0;\n BinaryBRTypedFile.filesParsed = 0;\n\n var rq = new Array(BinaryBRTypedFile.BR_TYPE_FILES.length);\n\n BinaryBRTypedFile.BR_TYPE_FILES.forEach(function(typ_e, index){ //geht durch alle BR_TYPE_FILES im ordner\n\n rq[index] = new XMLHttpRequest();\n rq[index].responseType=\"text\";\n rq[index].open('GET', '\\\\typ\\\\' + typ_e + '.typ', true);\n rq[index].onload = function(){\n var s=rq[index].response;\n s=s.replace(/\\s/g,''); //entfernt whitespaces\n s=s.replace(/\\(\\*(.*?)\\*\\)/g,'');\t//entfernt kommentare\n s=s.substr(4,s.length - 12);\t//entfernt hauptrahmen TYPE/END_TYPE\n\n while (s.indexOf(\":STRUCT\")!=-1){//alle struct container übernehmen und splitten\n var n=s.substr(0,s.indexOf(\":STRUCT\")); //holt structname\n if (BinaryBRTypedFile.brStructs.find(parsed_structs_e => parsed_structs_e.name==n)!=undefined) {\n alert(\"multiple use of \" + n + \" in B&R structfile: \" + typ_e);\n return 0;\n }else{\n var struct = new BRStructType(n);//erzeugt neue hüllklasse\n s=s.substr(s.indexOf(\":STRUCT\")+7); //entfernt struct header structname\n //alert(s);\n n=s.substr(0,s.indexOf(\"END_STRUCT;\")-1); //extrahiert in neuen string ohne struct tail, -1 für letztes semikolon (split)\n //alert(n);\n s=s.substr(s.indexOf(\"END_STRUCT;\") + 11); //entfernt entnommenen teilstring\n //alert(s.length);\n struct.brRawParse=n.split(\";\"); //kindelemente schon im 2 dimensionalen arry aufbereiten (0-nameStr,1-typStr)[unterelement]\n for (var i=0; i<struct.brRawParse.length;i++){ //alle unterstrukturen\n //pauschal initialisierung z.B. \":=1\" am ende abschneiden\n if (struct.brRawParse[i].indexOf(\":=\")!=-1){\n struct.brRawParse[i]=struct.brRawParse[i].substr(0,struct.brRawParse[i].indexOf(\":=\"));\n //\talert(element);\n }\n var test = struct.brRawParse[i].split(':');\n //alert(test[1]);\n //alert(singleChildStr[0] + \"--\" + singleChildStr[1] + \"--\" + singleChildStr);\n if (test.length!=2) {\n alert(\"child element not formed well: \"+ struct.brRawParse[i] + \" in \" + struct.name);\n return 0;\n }\n struct.brRawParse[i]=[test[0],test[1]];\n }\n //alert (struct.brRawParse[0]);\n }\n BinaryBRTypedFile.brStructs.push(struct); //object\n BinaryBRTypedFile.brStructsParsed++;\n }//end_while\n BinaryBRTypedFile.filesParsed++;\n if (BinaryBRTypedFile.filesParsed === BinaryBRTypedFile.BR_TYPE_FILES.length){\n //alert(callback);\n BinaryBRTypedFile.brStructs.forEach(function(struct_e, index){ //geht durch erzeugte structs und hängt wert für nachkorrektur an\n //alert(BinaryBRTypedFile.getCorrectionOperatorFromRawParse(struct_e.brRawParse));\n BinaryBRTypedFile.brStructs[index].moduloOperatorForOffsetCorrection=BinaryBRTypedFile.getCorrectionOperatorFromRawParse(struct_e.brRawParse);\n });\n\n if (typeof(callback) != \"undefined\") {\n callback();\n }else {\n //alert(BinaryBRTypedFile.filesParsed);\n }\n }\n };\n\n rq[index].send();\n });\n }", "function traverseDeserialize(data) {\n if(index > data.length || data[index] === \"#\") {\n return null;\n }\n var node = new TreeNode(parseInt(data[index]));\n index++;\n node.left = traverseDeserialize(data);\n index++;\n node.right = traverseDeserialize(data);\n return node;\n }", "function parseTree(text, errors, options) {\n if (errors === void 0) { errors = []; }\n var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n var visitor = {\n onObjectBegin: function (offset) {\n currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: function (name, offset, length) {\n currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });\n },\n onObjectEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: function (offset, length) {\n currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: function (value, offset, length) {\n onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: function (sep, offset, length) {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.columnOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: function (error, offset, lngth) {\n errors.push({ error: error, offset: offset, length: lngth });\n }\n };\n visit(text, visitor, options);\n var result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n }", "cvtBST() {\n var arr = [];\n arr.push(this.root.data);\n\n // get array - depth-first\n this.cvtToArray(this.root.left, arr);\n this.cvtToArray(this.root.right, arr);\n\n return arr;\n }", "function parseTree(text, errors, options) {\n if (errors === void 0) { errors = []; }\n var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n var visitor = {\n onObjectBegin: function (offset) {\n currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: function (name, offset, length) {\n currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });\n },\n onObjectEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: function (offset, length) {\n currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: function (value, offset, length) {\n onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: function (sep, offset, length) {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.columnOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: function (error) {\n errors.push({ error: error });\n }\n };\n visit(text, visitor, options);\n var result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}", "function breadthFirstArray(root) {\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function handles the instruction messages that apears when the user hovers over a button. pass in id of element and pass in option 1 to make it apear and 2 to disapear This function is used when the text hover has a fixed position.
function hoverInstructionsFixedPos(id_name,option){ if (option == "2") $(eval(id_name)).hide(); else $(eval(id_name)).show(); }
[ "function callNextToolTip(id){\n\tdestroy(id);\n\twordLablelToolTip();\n}", "function Insfunc() {\n var x = document.getElementById(\"instructions\");\n // if the is no style display assign to block i.e put the text there\n if (x.style.display === \"none\") {\n x.style.display = \"block\";\n }\n // if block or anything else assign to none\n else {\n x.style.display = \"none\"\n }\n }", "function wordLablelToolTip(){\n\t$('#wordLabel').popover();\n\tsetTimeout(function(){\n\t\t$('.label-div').expose();\n\t}, 300);\n\tsetTimeout(function(){\n\t\t$('#wordLabel').popover('show');\n\t\t$('.popover').css('z-index', '9999999');\n\t}, 400);\n}", "function click_hoverElement(id){\n\t$(id).hover(function(){\n\t\t$(this).css(\"border-style\", \"solid\");\n\t\t// $(this).css(\"border-width\", \"5px\");\n\t\t$(this).css(\"border-color\", \"lightblue\");\n\t\t\n\t\t}, function(){\n\t\t\tif (!$(this).hasClass('active1')) {\n\t\t\t\t$(this).css(\"border-style\", \"none\");\n\t\t\t}else{\n\t\t\t\t$(this).css(\"border-color\", \"red\");\n\t\t\t}\n\t});\n\t$(id).click(function(){\n\t\tif ($(this).hasClass('active1')) {\n\t\t\t$(this).removeClass('active1');\n\t\t} else {\n\t\t\t$(this).addClass('active1');\n\t\t\t$(this).css(\"border-color\", \"red\");\n\t\t}\n\t});\n}", "function onTipButtonClick() {\n\tvar tipButton = document.querySelector('.tip-button');\n \ttipsFinishedButton.style.display = 'none';\n\ttipButton.addEventListener('click', function() {\n\t\ttipLimit = tipLimit - 1;\n\t\tif (tipLimit >= 0) {\n\t\t\tgenerateTip();\n\n\t\t\tif (tipLimit === 0) {\n\t\t\t\ttipButton.style.display = 'none';\n \t\ttipsFinishedButton.style.display = 'block';\n\t\t\t}\n\t\t}\n\t});\n}", "function showHoverBox(element, content, condition) {\n element.addEventListener(\"mousemove\", function (e) {\n e.stopPropagation();\n e.preventDefault();\n hover.innerHTML = content;\n if (window.innerHeight <= e.pageY + 80)\n hover.style.top = e.pageY - hover.getBoundingClientRect().height + \"px\";\n else hover.style.top = e.pageY + \"px\";\n var left = e.pageX - 230;\n if (left < 10) left += 230;\n hover.style.left = left + \"px\";\n\n if (condition) {\n if (showClass) hover.style.display = \"block\";\n } else hover.style.display = \"block\";\n });\n element.addEventListener(\"mouseleave\", function (e) {\n e.stopPropagation();\n e.preventDefault();\n hover.style.display = \"none\";\n });\n}", "function showOverlay(id) {\n currentOverlay = id;\n\n if (id === null) {\n document.getElementById('overlay').classList.add('hidden');\n return;\n }\n\n var title, text;\n if (id === 'nocard') {\n title = navigator.mozL10n.get('nocard2-title');\n text = navigator.mozL10n.get('nocard2-text');\n } else {\n title = navigator.mozL10n.get(id + '-title');\n text = navigator.mozL10n.get(id + '-text');\n }\n\n var titleElement = document.getElementById('overlay-title');\n var textElement = document.getElementById('overlay-text');\n\n titleElement.textContent = title;\n titleElement.dataset.l10nId = id + '-title';\n textElement.textContent = text;\n textElement.dataset.l10nId = id + '-text';\n\n document.getElementById('overlay').classList.remove('hidden');\n}", "function showHideLinkMenu(id){\n\tswitch(id){\n\t\tcase \"linkList\":\n\t\t\t$(\"#linkMenu\").hide();\n $(\"#subLink\").show();\n\t\t\tvar bck = '<div id=\"linkBack\" style=\"position:absolute;cursor:pointer;\" onclick=\"linkBackBtn()\"><img src=\"img/backArrow.png\" style=\"width: 20px;margin-left: 3px;margin-top: 6px;\"></div>';\n\t\t\t$('.ui-dialog-titlebar').prepend(bck);\n\t\t\t$('.ui-dialog-title').css({'margin-left': '13px','margin-top': '6px'});\n\t\tbreak;\n\t\tcase \"linkToolsList\":\n\t\t\t$(\"#linkMenu\").hide();\n\t\t\t$(\"#subToolsLink\").show();\n\t\t\tvar bck = '<div id=\"linkBack\" style=\"position:absolute;cursor:pointer;\" onclick=\"linkBackBtn()\"><img src=\"img/backArrow.png\" style=\"width: 20px;margin-left: 3px;margin-top: 6px;\"></div>';\n\t\t\t$('.ui-dialog-titlebar').prepend(bck);\n\t\t\t$('.ui-dialog-title').css({'margin-left': '13px','margin-top': '6px'});\n\t\tbreak;\n\t\tcase \"linkLogsList\":\n\t\t\t$(\"#divAlert\").dialog('destroy');\n\t\t\tlinkConnectivityLogs();\n\t\tbreak;\n\t}\n}", "function displayItemMessage(msg) {\n document.getElementById('warning-mess').innerHTML = msg;\n}", "viewHoverId(idName){\n let hoverDiv=document.getElementById(idName);\n hoverDiv.classList.remove('hide')\n }", "function toggleHelpAbsoluteFrench(obj, a_id) {\n\tvar content = document.getElementById(obj);\n\tvar opener = document.getElementById(a_id);\t\n\t\n\ticonState = opener.lastChild.alt;\n\ticonState = iconState.replace(\"R\\u00E9duire\",\"\");\n\ticonState = iconState.replace(\"D\\u00E9velopper\",\"\");\n\n\t\n\t\tif (content.style.display != \"none\" ) {\n\t\t\tcontent.style.display = 'none';\n\t\t\topener.lastChild.alt = 'D\\u00E9velopper' + iconState;\n\t\t\topener.focus();\n\t\t} else {\n\t\tcontent.style.display = '';\n\t\t\topener.lastChild.alt = 'R\\u00E9duire' + iconState;\n\t\t}\n\t\n\t\n\tif ((content.style.top == '' || content.style.top == 0) \n\t\t&& (content.style.left == '' || content.style.left == 0))\n\t{\n\t\t// need to fixate default size (MSIE problem)\n\t\tcontent.style.width = content.offsetWidth + 'px';\n\t\tcontent.style.height = content.offsetHeight + 'px';\t\t\n\t\n\t\t// if tooltip is too wide, shift left to be within parent \n\t\tposX = 0;\n\t\tposY = 17;\n\t\tif (posX + content.offsetWidth > opener.offsetWidth) posX = opener.offsetWidth - content.offsetWidth;\n\t\tif (posX < 0 ) posX = 0; \n\t\t\n\t\tx = xstooltip_findPosX(opener.lastChild) + posX;\n\t\ty = xstooltip_findPosY(opener.lastChild) + posY;\n\t\t\n\t\tcontent.style.top = y + 'px';\n\t\tcontent.style.left = x + 'px';\n\t\t\n\t\tcontent.style.position = 'absolute';\n\t\tcontent.style.zIndex = 2;\n\t\n\t}\n\t\n\n}", "function destroy(id){\n\t$('#btn-clear').css('z-index', '0');\n\tid = id.replace('-po', '');\n\t$('#' + id).popover('destroy');\n\t$.mask.close();\n\tif(id == \"eng-btn\"){\n\t\tarBtnPopOver();\n\t}\n\telse if(id == \"ar-btn\"){\n\t\tbothBtnPopOver();\n\t}\n\telse if (id == \"both-btn\"){\n\t\tlockLangButtons = false;\n\t}\n}", "function showHideHelp ( section_id, action )\n {\n\t// If the help text is visible and we're either hiding or toggling, then do so.\n\t\n\tif ( visible['help_' + section_id] && ( action == undefined || action == \"hide\" ) )\n\t{\n\t setElementSrc('q' + section_id, \"/JavaScripts/img/hidden_help.png\");\n\t hideByClass('help_' + section_id);\n\t}\n\t\n\t// If the help text is invisible and we're showing or toggling, then do so.\n\t\n\telse if ( action == undefined || action == \"show\" )\n\t{\n\t setElementSrc('q' + section_id, \"/JavaScripts/img/visible_help.png\");\n\t showByClass('help_' + section_id);\n\t}\n }", "function hideParagraph() {\n if (!hovering) {\n\t\t\t$(hoverID).hide();\n }\n }", "function displaySpellIcon(id) {\r\n\t\taddClass($('#spellbook #custom #preview .slide'), 'hide');\r\n\t\tif ($('#spellbook #custom #preview .slide#spell_icon_' + id).length != 0)\r\n\t\t\tremoveClass($('#spellbook #custom #preview .slide#spell_icon_' + id), 'hide');\r\n\t\t$('#main_menu #spellbook #custom .right #icon').value = id;\r\n\t}", "function displayWarning(text) {\n\tvar warning = document.getElementById(\"warning\");\n\t\n\tif(text) warning.style.display = \"block\";\n\telse warning.style.display = \"none\";\n\t\n\twarning.innerHTML = text;\n}", "function OnMessageTimeOut(id) {\n\n\tif (id == DVDMSGTIMER) {\n\t\tMessage.Text = \"\";\n\t\tMessageFull.Text = \"\";\n if (g_LTRReading)\n {\n xCoord = TitleFull.TextWidth;\n }\n else\n {\n xCoord = g_ConWidth - TitleFull.TextWidth - MessageFull.TextWidth - g_nButPosFull[g_nIndexMessage][0];\n }\n yCoord = g_nButPos[g_nIndexMessage][1] - 1000;\n\n\t\tMFBar.SetObjectPosition(\"MessageFull\", xCoord, yCoord,\n\t\t\tMessageFull.TextWidth, g_nButPosFull[g_nIndexMessage][3]);\n\n if (g_LTRReading)\n {\n xCoord = Title.TextWidth;\n }\n else\n {\n xCoord = g_ConWidth - Title.TextWidth - Message.TextWidth - g_nButPos[g_nIndexMessage][0];\n }\n yCoord = g_nButPos[g_nIndexMessage][1];\n\n\t\tMFBar.SetObjectPosition(\"Message\", xCoord, yCoord,\n\t\t\tMessage.TextWidth, g_nButPos[g_nIndexMessage][3]);\n\t}\n\n\telse if (id == FOCUSTIMER) {\n\t\tif (MFBar.ObjectEnabled(g_strFocusObj)) {\n\t\t\tbtn = MFBar.GetObjectUnknown(g_strFocusObj);\n\t\t\tif (!btn.Disable)\n\t\t\t\tMFBar.SetObjectFocus(g_strFocusObj, true);\n\t\t}\n\t\telse {\n\t\t}\n\t}\n}", "showButtonPageDescription(text){\n\t\tthis.buttonPageDescription.setInfoText(text);\n\t\tthis.buttonPageDescription.updatesHimself();\n\t\tthis.buttonPageDescription.showInfoText();\n\t}", "function ganhouShow(id) {\r\n ganhou = true\r\n verificaVitoria = true\r\n document.getElementById(\"ganhou\").style.display = 'flex'\r\n document.getElementById(\"content\").style.display = 'none'\r\n document.getElementById(\"ganhou\").style.opacity = '1'\r\n document.getElementById(\"nomeGanhador\").innerText = `PARABÉNS, ${nomeJogadores[id]}`\r\n document.getElementById(\"textoGanhador\").innerText = `VOCÊ GANHOU O BINGO!!!`\r\n\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets score on LMS. Can be expanded for more complex scoring but Currently takes in a raw score and records it.
set score(rawScore) { this._score.raw = rawScore; setValue(`cmi.objectives.${this.index}.score.raw`, rawScore); }
[ "set score(newScore) {\r\n score = newScore;\r\n _scoreChanged();\r\n }", "set score(val) {\n this._score = val;\n console.log('score updated');\n emitter.emit(G.SCORE_UPDATED);\n }", "setScore() {\n this.#gameScore += this.#rules[this.#gameLevel - 1].score\n document.dispatchEvent(this.#gameScoreEvent)\n }", "function updateScore() {\n\t\t\t// Score rule: pass level n in t seconds get ((100 * n) + (180 - t)) points \n\tlevelScore = (levelTime + 100) + Math.floor(levelTime * (currentLevel-1));\n\t// Set original \"levelScore\" to extraLevelScore for testing purpose\n\tfinalScore += levelScore + extraLevelScore;\t\t\n\t// Add finalTime\n\tfinalTime += startLevelTime - levelTime;\n}", "setScore () {\n var text = document.getElementById(\"marker\");\n text.innerHTML = \"Score: \" + this.score;\n\n //It sets the difficulty\n if (this.difficulty == this.compareDifficulty && this.score >= this.compareScore && this.difficulty < 9) {\n this.model.remove(this.fly[this.difficulty]);\n var loader = new THREE.TextureLoader();\n var texture = loader.load (\"imgs/fuego.jpg\");\n this.fly[this.difficulty] = new FlyObj(new THREE.MeshPhongMaterial ({map: texture}), false);\n this.model.add(this.fly[this.difficulty]);\n\n this.difficulty++;\n this.compareDifficulty++;\n this.compareScore += 10;\n }\n }", "updateScore() {\n this.serverComm.updateScore(this.userId, this);\n }", "function setHomeScore(score) {\n\t\tif(score >= 0) { // teams may not have a score below zero\n\t\t\tsnapshotState();\n\t\t\tscoreBoard.homeScore = score;\n\t\t\tvar update = { homeScore: score };\n\t\t\tsocket.emit('boardUpdate', update);\n\t\t}\n\t}", "addScore (score) {\n this.userScore += (score * 5);\n return `User score is ${this.userScore}`;\n }", "function updateScore() {\n\n}", "function updateScore(){\n scoreText.setText(\"Score: \"+score);\n }", "function getScore()\n {\n return score\n }", "function updateScore() {\n humanScoreSpan.innerHTML = humanScore;\n computerScoreSpan.innerHTML = computerScore;\n return;\n }", "updateScore(){\n this.score += 1;\n this.labelScore.text = this.score;\n }", "function clearScore() {\n currentScore = 0;\n }", "formatScore(leveledScore) {\n return Math.round(leveledScore.score*100)/100;\n }", "function updateScoreOverlay() {\n let one = playerNetscore(team.getT1());\n write(t1Players, one);\n one = team.getT1();\n write(t1Score, one.points);\n\n let two = playerNetscore(team.getT2());\n write(t2Players, two);\n two = team.getT2();\n write(t2Score, two.points);\n}", "function addScore() {\n\tvar ref = database.ref('rank');\n\tvar data = {\n\t\tname: userName,\n\t\tvalue: score\n\t}\n\tref.push(data);\n}", "function scoringLogic(score){\n\n if (score > 20 && score < 40) {\n dropRate = 30\n wallIncreaseSpeed = 0.3\n dropBallSpeed = 3\n }\n else if (score > 40 && score < 60) {\n dropRate = 20\n wallIncreaseSpeed = 0.5\n dropBallSpeed = 4\n }\n else if (score > 60 && score < 80){\n dropRate = 15\n wallIncreaseSpeed = 0.7\n dropBallSpeed = 5\n }\n else if (score > 80 && score < 100){\n dropRate = 15\n wallIncreaseSpeed = 0.8\n dropBallSpeed = 5\n }\n else if (score > 100){\n dropRate = 10\n wallIncreaseSpeed = 1.2\n dropBallSpeed = 5\n }\n}", "function addToScore(points){\r\n\t\tscore += points;\r\n\t\taddLifeRunningTotal += points;\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether the code is running in tests.
_isTestEnv() { const window = this._getWindow(); return window && (window.__karma__ || window.jasmine); }
[ "_is_testing() {\n return this.env != \"production\" && this.env != \"prod\";\n }", "function shouldInstrument () {\n if (process.env.CI) {\n return !!process.env.REPORT_COVERAGE;\n }\n return true;\n}", "get isSetup() {\n return this.system.hasInstance(this);\n }", "isOnServer() {\n return !(typeof window !== 'undefined' && window.document);\n }", "function testBackgroundPage() {\n if (TARGET === \"firefox\" || TARGET === \"chrome\") {\n return backgroundPage.bg.test();\n } else {\n return false;\n }\n}", "isUseCurrentAsBaseRun () {\n return this.isCompletedRunCurrent && (!this.isReadonlyWorksetCurrent || this.isPartialWorkset())\n }", "function assertBrowserEnv() {\r\n return assert(isBrowser, 'This feature is only available in browser environments');\r\n }", "static canParse( testName ) {\n const benchmarkParserKey = Utils.getBenchmarkParserKey(testName);\n if(benchmarkParserKey) {\n return true;\n }\n return false;\n }", "function isCreateReactAppTestCommand(testCommand) {\n return testCommand && createReactAppBinaryNames.some(binary => testCommand.indexOf(binary + ' test') === 0);\n}", "function assertNodeEnv() {\r\n return assert(isNode, 'This feature is only available in NodeJS environments');\r\n }", "function isEnabled() {\n return tray != undefined;\n}", "get isDevContext() {\n if (this.mIsDevContext !== undefined) {\n return this.mIsDevContext;\n }\n return Inspect.isDevContext();\n }", "function isCanvas() {\n return !isHome();\n}", "function getIsSimulating() {\n \t return isSimulating;\n } // getIsSimulating", "function setTestRanTrue() {\n testRan = true;\n}", "async function isSimulatorAppRunningAsync() {\n try {\n const zeroMeansNo = (await osascript.execAsync('tell app \"System Events\" to count processes whose name is \"Simulator\"')).trim();\n if (zeroMeansNo === '0') {\n return false;\n }\n }\n catch (error) {\n if (error.message.includes('Application isn’t running')) {\n return false;\n }\n throw error;\n }\n return true;\n}", "ShouldIncludeInBuild() {}", "function isStandaloneApp() {\n return navigator.standalone;\n }", "function doCheck() {\n if (hasStarted === false) {\n // The test has not started, but the user is typing already -- maybe we should start?\n beginTest(); // Yes, we should -- consider it done!\n }\n}", "get shouldNightModeStart() {\n const { score, nightMode } = this;\n const { DISTANCE } = GameScene.CONFIG.NIGHTMODE;\n return score > 0 && score % DISTANCE === 0 && !nightMode.isEnabled;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace anchor tags with routerlink components to stop page from reloading Original tag: "> New tag:
replaceLinks (text) { text = text.replace(/(<a href)([^.]*?)(>.*)(a>)/g, '<router-link to$2$3router-link>') text = text.replace(/<a xlink:href/, '<router-link to') return text }
[ "function fixAnchors (hook) {\n\n hook.afterEach(function (html, next) {\n\n // find all headings and replace them\n html = html.replace(/<(h\\d).+?<\\/\\1>/g, function (html) {\n\n // create temp node\n const div = document.createElement('div')\n div.innerHTML = html\n\n // get anchor\n const link = div.querySelector('a[href*=\"?id\"]')\n if (!link) {\n return html\n }\n\n // get id\n const matches = link.getAttribute('href').match(/id=(.+)/)\n let id = matches[1]\n\n // clean up ids unless element has `anchor` class (meaning it was manually-entered HTML)\n if (!link.classList.contains('anchor')) {\n id = link.innerText\n .split('(')\n .shift()\n .toLowerCase()\n .replace(/\\W+/g, '-')\n .replace(/^-+|-+$/g, '')\n const href = link.getAttribute('href').replace(/\\?id=.+/, '?id=' + id)\n link.setAttribute('href', href)\n }\n\n // update dom\n link.setAttribute('data-id', id)\n link.parentElement.setAttribute('id', id)\n\n // return html\n return div.innerHTML\n })\n\n // continue\n next(html)\n })\n}", "function preserveWrapperATag(newMarkup) {\r\n var range = scope.editor.getRange();\r\n var anchor = getAnchorElement(range);\r\n if (anchor) {\r\n $(anchor).html(newMarkup);\r\n return anchor.outerHTML;\r\n }\r\n else {\r\n return newMarkup;\r\n }\r\n }", "function fixLinks() {\n for (var a of document.getElementsByTagName(\"a\")) {\n var href = a.href;\n if (href.baseVal) {\n var label = href.baseVal;\n if (label.includes(\"#mjx-eqn\")) {\n label = decodeURIComponent(label.substring(1));\n var eqn = document.getElementById(label);\n if (eqn) {\n var s = eqn.closest(\"section\");\n if (s) {\n a.href.baseVal =\n location.origin + location.pathname + \"#\" + s.id;\n }\n }\n }\n }\n }\n }", "function refreshNamedAnchor() {\r\n\t\tvar i = location.href.lastIndexOf('#');\r\n\t\tif (i >= 0) {\r\n\t\t\tlocation.href = location.href.substring(i);\r\n\t\t}\r\n\t}", "addLinkComponent(link, component) {\n 'use strict';\n\n let newLink = link;\n let componentString = component;\n\n if (component === undefined || !component) {\n return newLink;\n }\n if (typeof newLink !== 'string') {\n newLink = link.toString();\n }\n\n if (typeof component !== 'string') {\n componentString = component.toString();\n }\n if (newLink.charAt(newLink.length - 1) !== '/' && componentString.charAt(0) !== '/') {\n newLink += '/';\n } else if (newLink.charAt(newLink.length - 1) === '/' && componentString.charAt(0) === '/') {\n componentString = componentString.substring(1);\n }\n newLink += componentString;\n return newLink;\n }", "function updateHtml(href) {\n var fragment = generator.fragment$[href];\n if (!fragment) return log('jqueryview cannot find fragment: ' + href);\n var $html = $('[data-render-html=\"' + href + '\"]');\n if (!$html.length) return log('jqueryview cannot update html for fragment: ' + href);\n updateDOM($html, generator.renderHtml(fragment));\n }", "function replaceTag(html, oldtag, newtag){\n\tvar re = new RegExp('(<\\\\/?)('+oldtag+')(>)','g');\n\treturn html.replace(re, \"$1\"+newtag+\"$3\");\n}", "addToNavBar() {\r\n const link = $$(\"<a>\");\r\n link.className = \"nav-item nav-link\";\r\n link.href = \"/money/account/\" + this.model.id;\r\n link.textContent = this.model.name;\r\n $$(\".navbar-nav\").appendChild(link);\r\n }", "function resetLink() {\n var instruction = gettext(\"This link will open the default version of this interactive:\");\n var link = window.location.href.split('?', 1)[0].replace(/^\\/+|\\/+$/g, '');\n $(\"#cfg-grammar-link\").html(`${instruction}<br><a target=\"_blank\" href=${link}>${link}</a>`);\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 }", "takeOverLinks() {\n delegate(window.document, \"click\", \"a\", event => {\n if (\n event.button !== 0 ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey\n ) {\n return;\n }\n const link = event.target.closest(\"a\");\n if (\n link.getAttribute(\"href\").charAt(0) === \"#\" ||\n link.host !== window.location.host\n ) {\n return;\n }\n\n if (\n !event.defaultPrevented &&\n !link.hasAttribute(\"data-remote\") &&\n link.protocol.indexOf(\"http\") === 0\n ) {\n event.preventDefault();\n\n // update sidebar links\n if (link.closest(\"aside\")) {\n this.navigate(updateURL(link.href));\n } else {\n this.navigate(link.href);\n }\n }\n });\n }", "function replacePackUrl(pack) {\r\n\r\n let elements = document.querySelectorAll(pack.query);\r\n [...elements].forEach(node => {\r\n\r\n let link = node.getAttribute(pack.attr);\r\n let data = pack.regex.exec(link);\r\n\r\n if (data) {\r\n\r\n let query = prepareNewLinkQuery(data[3]);\r\n node.setAttribute(pack.attr, link.replace(pack.regex, `${data[1]}/${query}`))\r\n\r\n }\r\n\r\n })\r\n\r\n }", "_onHashChanged() {\n const hash = RB.getLocationHash();\n let selector = null;\n\n if (hash !== '') {\n if (hash.includes('comment')) {\n selector = `a[name=${hash}]`;\n } else {\n selector = `#${hash}`;\n }\n }\n\n if (!selector) {\n return;\n }\n\n /*\n * If trying to link to some anchor in some entry, we'll expand the\n * first entry containing that anchor.\n */\n for (let i = 0; i < this._entryViews.length; i++) {\n const entryView = this._entryViews[i];\n const $anchor = entryView.$(selector);\n\n if ($anchor.length > 0) {\n /*\n * We found the entry containing the specified anchor.\n * Expand it and stop searching the rest of the entries.\n */\n entryView.expand();\n\n /*\n * Scroll down to the particular anchor, now that the entry\n * is expanded.\n */\n RB.scrollManager.scrollToElement($anchor);\n break;\n }\n }\n }", "function makeAnchor(json) {\n var html = escapeHTML(json.Text);\n if (json.Href != \"\") {\n html = \"<a href='\" + escapeHTML(json.Href) + \"'>\" + html + \"</a>\";\n }\n return html;\n}", "function convertToHtml(text, removeAnchors) {\n if (removeAnchors) {\n text = text.replace(/&lt;a.+?&gt;/gi, \"\");\n text = text.replace(/&lt;\\/a&gt;/gi, \"\");\n }\n\n return jQuery(\"<span />\", { html: text }).html();\n}", "function remove(){\n body.querySelectorAll(\"a\").forEach(\n (aTag) => {\n if (aTag.getAttribute(\"href\").startsWith(shouldNotStartWith)){\n body.removeChild(aTag);\n }\n }\n )\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 withMagicLinksReplaced(text) {\n let replaced_text = text\n // ticket id\n .replace(new RegExp(\"ticket[:#]([0-9]{3,6})(?=\\\\b)\", \"ig\"), \"<a href=\\\"https://tickets.agdsn.de/index.pl?Action=AgentTicketZoom;TicketID=$1\\\">$&</a>\")\n // ticket number (YYYYMMDDhhmmss¿¿)\n .replace(new RegExp(\"(?<=\\\\b)(ticket[:#])?([0-9]{16})(?=\\\\b)\", \"ig\"), \"<a href=\\\"https://tickets.agdsn.de/index.pl?Action=AgentTicketZoom;TicketNumber=$2\\\">Ticket#$2</a>\")\n ;\n console.debug(`${text} ⇒ ${replaced_text}`);\n return replaced_text;\n}", "function clear_link(mhc){ \n\t\tvar unlinked = 0;\n\t\tvar aNav = $(mhc);\n\t\tvar a = aNav.getElementsByTagName('a');\n\t\tvar mysplit = window.location.href.split('#')[0];\n\t\tfor(var i=1;i<a.length;i++)\n\t\t\tif(a[i].href == mysplit){\n\t\t\t\tremoveNode(a[i]);\n\n \t\t\tvar unlinked = 1;\n\t\t\t\t}\t\t\t\t\n\t\t\tif (unlinked == 0){\n\t\t\t\tvar newHit = a[0];\n\t\t\t\tnewHit.parentNode.setProperty ('id','active_nav'); \n\t\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy base stats into a new object to be calculated with.
function copy_base_stats() { var ret = {}; // Should be fine as base_stats doesn't have anything fancy in. for (var attr in base_stats) { ret[attr] = base_stats[attr]; } return ret; }
[ "clone() {\n let stats = {};\n this.forEachStat((name, value) => stats[name] = value)\n return new BirdStats(stats);\n }", "buildDerivedStats () {\n\t\tthis.derivedStats['Wound Boxes'] = this.stats.Health + DigimonStages[this.stage].woundBoxes;\n\n\t\tif (Number.isInteger(this.burstIndex)) {\n\t\t\tthis.derivedStats['Wound Boxes'] += this.burstIndex * BurstModifier.woundBoxes;\n\t\t}\n\n\t\tthis.derivedStats['Agility'] = Math.floor((this.stats.Accuracy + this.stats.Dodge) / 2) + this.statMods['Agility'] + DigimonSizes[this.sizeIndex].statBonus['Agility'];\n\t\tthis.derivedStats['Body'] = Math.floor((this.stats.Health + this.stats.Damage + this.stats.Armor)/3) + DigimonSizes[this.sizeIndex].statBonus['Body'] + this.statMods['Body'];\n\t\tthis.derivedStats['Brains'] = Math.floor(this.stats.Accuracy/2) + DigimonStages[this.stage].brains + this.statMods['Brains'];\n\n\t\tthis.specValues['RAM Value'] = Math.floor(this.derivedStats.Agility/10) + DigimonStages[this.stage].specValues + this.statMods['SpecValues'];\n\t\tthis.specValues['CPU Value'] = Math.floor(this.derivedStats.Body/10) + DigimonStages[this.stage].specValues + this.statMods['SpecValues'];\n\t\tthis.specValues['BIT Value'] = Math.floor(this.derivedStats.Brains/10) + DigimonStages[this.stage].specValues + this.statMods['SpecValues'];\n\n\t\tthis.specValues['BIT Value'] = this.handleRestriction(this.specValues['BIT Value'], 'BIT Value');\n\t\tthis.specValues['CPU Value'] = this.handleRestriction(this.specValues['CPU Value'], 'CPU Value');\n\t\tthis.specValues['RAM Value'] = this.handleRestriction(this.specValues['RAM Value'], 'RAM Value');\n\t}", "add(stats) {\n let sum = new BirdStats({});\n this.forEachStat((name, value) => {\n sum[name] = value + stats[name];\n });\n return sum;\n }", "subtract(stats) {\n let diff = new BirdStats({});\n this.forEachStat((name, value) => {\n diff[name] = value - stats[name];\n });\n return diff;\n }", "getStats() {\n return {\n fitness: this.fitness,\n lastFitness: this.lastFitness\n }\n }", "constructor(stats) {\n this.name = stats.name; \n this.level = stats.level;\n this.maxHP = stats.hp;\n this.hp = stats.hp;\n this.attack = stats.attack; \n this.defense = stats.defense;\n this.speed = stats.speed;\n this.dodge = this.calculateDodge();\n this.turnMeter = 0;\n this.isTurn = false;\n this.tickRate = 0;\n }", "scale(scalar) {\n let stats = {};\n this.forEachStat((name, value) => {\n stats[name] = value * scalar;\n })\n return new BirdStats(stats);\n }", "getBase(statEnum){\n verifyType(statEnum, TYPES.number);\n return this.stats.get(statEnum).getBase();\n }", "static zero() {\n let stats = new BirdStats({});\n stats.forEachStat((name, value) => stats[name] = 0)\n return stats;\n }", "function computeStats(){\n return {\n pages: computePageCounts(),\n referrers: computeRefererCounts(),\n activeUsers: getActiveUsers()\n };\n}", "_update() {\n var i, pr, inn=0, mer=0, ban=0, bui=0;\n\n for (i in this.profiles) {\n pr = this.profiles[i];\n bui += pr.builder;\n mer += pr.merchant;\n inn += pr.innovator;\n ban += pr.banker;\n }\n \n /* update the average */\n if (this.profiles.length > 0) {\n this.builder = bui / this.profiles.length;\n this.merchant = mer / this.profiles.length;\n this.innovator = inn / this.profiles.length;\n this.banker = ban / this.profiles.length;\n }\n else {\n this.builder = 0;\n this.merchant = 0\n this.innovator = 0;\n this.banker = 0;\n }\n }", "inheritvars()\n\t{\n\t\tlet context = Object.create(this);\n\t\tcontext.vars = Object.create(this.vars);\n\t\treturn context;\n\t}", "limit(maxStats) {\n let stats = new BirdStats({});\n this.forEachStat((name, value) => {\n if (value > maxStats[name]) {\n stats[name] = maxStats[name];\n } else {\n stats[name] = value;\n }\n });\n return stats;\n }", "function calculateEquipmentStat() {\r\n //init\r\n for(let prop in player.additionalStats){player.additionalStats[prop] = 0};\r\n //calculation\r\n for(let prop in player.equipments){\r\n let d = player.equipments[prop];\r\n if(d !== null){\r\n player.additionalStats.atk += d.atk;\r\n player.additionalStats.def += d.def;\r\n player.additionalStats.spd += d.spd;\r\n }\r\n }\r\n}", "copy() {\n if (this.era) return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.era, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n else return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n }", "function createStatisticsObject() {\n Object.keys(ClusterConsoleConstants.MEMBER_METRIC_NAMES).forEach(function (node) {\n ClusterConsoleConstants.MEMBER_METRIC_NAMES[node].forEach(function (metricName) {\n if (!self.data.hasOwnProperty(metricName)) {\n self.data[metricName] = {};\n }\n\n if (!self.data[metricName].hasOwnProperty(node.toLowerCase())) {\n self.data[metricName][node] = {\n labels: [],\n values: [],\n };\n }\n });\n });\n }", "clone() {\n var clone = new Player();\n clone.brain = this.brain.clone();\n clone.fitness = this.fitness;\n clone.brain.generateNetwork();\n clone.gen = this.gen;\n clone.bestScore = this.score;\n return clone;\n }", "from(sLevelInfo) {\n let raw = JSON.parse(sLevelInfo);\n this.playerDeaths = raw.playerDeaths;\n this.enemiesKilled = raw.enemiesKilled;\n this.destructiblesSmashed = raw.destructibleSmashed;\n this.secretsFound = raw.secretsFound;\n this.startTime = raw.startTime;\n this.sumElapsed = raw.sumElapsed;\n return this;\n }", "function RatingMovingAverage(){\n this.prototype = new MovingAverage(); \n\n\t/* Superclass Function Prototypes */\n // these functions are defined in the superclass and used in the subclass\n\tthis.getCorrelationsFor = this.prototype.getCorrelationsFor;\n\tthis.setName = this.prototype.setName;\n\tthis.getName = this.prototype.getName;\n\t\n\t// the name of the Candidate that this MovingAverage describes\n\tthis.setOwnerName = this.prototype.setOwnerName;\n\tthis.getOwnerName = this.prototype.getOwnerName;\n\tthis.stringVersion = this.prototype.stringVersion;\n\tthis.superFunction = this.prototype.superFunction;\n\tthis.getCurrentValue = this.prototype.getCurrentValue;\n\t\n\t// functions that we are overriding\n\tthis.getValueAt = getValueAt;\n\tthis.prototype.getValueAt = getValueAt;\n\tthis.prototype.subFunction = subFunction;\n\tthis.prototype.isAParticipationMovingAverage = isAParticipationMovingAverage;\n\tthis.isAParticipationMovingAverage = isAParticipationMovingAverage;\n\n // these functions are defined in the subclass\n this.addRating = addRating;\n\tthis.getRatings = getRatings;\n\tthis.getNameRatings = getNumRatings;\n\tthis.getAverageValue = getAverageValue;\n\tthis.getLatestDate = getLatestDate;\n\tthis.subFunction = subFunction;\n\tthis.getIndexForDate = getIndexForDate;\n\n\t\n\t//private functions\n\t\n\t//private variables\n\tvar ratings = [];\n\tvar sumRatings = [];\n\tvar sumSquaredRatings = [];\n\t\n\t//public functions\n\tfunction addRating(rating){\n\n\t\tvar totalScore = 0.0; \n\t\tvar totalWeight = 0.0;\n\t\tvar totalSquaredScore = 0.0;\n\t\t\n\t\tif(sumRatings.length > 0){\n\t\t\tvar lastRating = sumRatings[sumRatings.length - 1];\n\t\t\ttotalScore = lastRating.getScore();\n\t\t\ttotalWeight = lastRating.getWeight();\n\t\t\tvar sumSquaredRating = sumSquaredRatings[sumSquaredRatings.length - 1];\n\t\t\ttotalSquaredScore = sumSquaredRating.getScore();\n\t\t} else {\n\t\t\ttotalScore = totalWeigh = totalSquaredScore = 0;\n\t\t}\n\t\t\n //alert(\"rating moving average adding rating pt2\\r\\n\");\t\n\t\t// compute new running total\n\t\tvar newTotalScore = totalScore + rating.getScore() * rating.getWeight();\n\t\tvar newTotalWeight = totalWeight + rating.getWeight();\n\t\tvar newRating = new Rating();\n\t\tnewRating.setScore(newTotalScore);\n\t\tnewRating.setWeight(newTotalWeight);\n\t\tnewRating.setDate(rating.getDate());\n\t\t\n\t\t// save the new running total\n\t\tsumRatings.push(newRating);\n //alert(\"rating moving average adding rating pt3\\r\\n\");\t\n\t\t\n\t\t// compute new running squared total\n\t\tvar newTotalSquaredScore = totalSquaredScore + rating.getScore() * rating.getScore() * rating.getWeight();\n\t\tvar newSquaredRating = new Rating();\n\t\tnewSquaredRating.setScore(newTotalSquaredScore);\n\t\tnewSquaredRating.setWeight(newTotalWeight);\n\t\tnewSquaredRating.setDate(rating.getDate());\n\t\tsumSquaredRatings.push(newSquaredRating);\n\t\t\n\t\tratings.push(rating);\n //alert(\"rating moving average adding rating pt4\\r\\n\");\t\n\t}\n\t\t\t\n // if strictlyEarlier is true, then it will only use data from strictly before 'when'\n\tfunction getValueAt(when, strictlyEarlier){\n\t\t//alert(\"RatingMovingAverage::getValueAt pt a\\r\\n\");\n\t\tif (sumRatings.length == 0){\n\t\t\treturn [new Distribution(0, 0, 0), -1];\n\t\t}\n\t\t\n\t\t//alert(\"RatingMovingAverage::getValueAt pt b\\r\\n\");\n\t\tvar firstRating = sumRatings[0];\n\t\tif(!strictlyChronologicallyOrdered(firstRating.getDate(), when)) {\n \t\t//alert(\"RatingMovingAverage::getValueAt pt c\\r\\n\");\n\t\t\treturn [new Distribution(0, 0, 0), -1];\n\t\t}\n\t\t//alert(\"RatingMovingAverage::getValueAt pt d\\r\\n\");\n\t\t\n\t\tvar latestRatingIndex = getIndexForDate(when, strictlyEarlier);\n\t\t//alert(\"index = \" + latestRatingIndex);\n\t\tvar latestRatingDate = sumRatings[latestRatingIndex].getDate();\n\t\t//alert(\"calculating duration\");\n\t\tvar duration = latestRatingDate.timeUntil(when);\n\t\t//alert(\"constructing new date\");\n\t\tvar oldestRatingDate = latestRatingDate.datePlusDuration(-duration);\n\t\t//alert(\"getting new index\");\n\t\tvar earliestRatingIndex = getIndexForDate(oldestRatingDate, true);\n\t\t//alert(\"array lookups\");\t\t\n\t\tvar latestSumRating = sumRatings[latestRatingIndex];\n\t\tvar latestSumSquaredRating = sumSquaredRatings[latestRatingIndex];\n\t\tvar earliestSumRating = sumRatings[earliestRatingIndex];\n\t\tvar earliestSumSquaredRating = sumSquaredRatings[earliestRatingIndex];\n\t\t\n\t\tvar sumY = 0.0;\n\t\tvar sumY2 = 0.0;\n\t\tvar sumWeight = 0.0;\n\t\t//alert(\"in the middle of RatingMovingAverage::pt e\\r\\n\");\n\t\t\n\t\tif(strictlyChronologicallyOrdered(oldestRatingDate, sumRatings[0].getDate())){\n\t\t\tsumY = latestSumRating.getScore();\n\t\t\tsumY2 = latestSumSquaredRating.getScore();\n\t\t\tsumWeight = latestSumRating.getWeight();\n\t\t}\n\t\telse{\n\t\t\tsumY = latestSumRating.getScore() - earliestSumRating.getScore();\n\t\t\tsumY2 = latestSumSquaredRating.getScore() - earliestSumSquaredRating.getScore();\n\t\t\tsumWeight = latestSumSquaredRating.getWeight() - earliestSumSquaredRating.getWeight();\n\t\t}\n\t\t\n\t\tvar average = sumY/sumWeight;\n\t\tvar stdDev = Math.sqrt((sumY2 - sumY * sumY/sumWeight)/sumWeight);\n\t\tvar result = new Distribution(average, stdDev, sumWeight);\n\t\t\n\t\t//alert(\"done with RatingMovingAverage::getValueAt\\r\\n\");\n\t\treturn [result, latestRatingIndex];\n\t}\n\t\n\tfunction getRatings(){\n\t\treturn ratings;\n\t}\n\t\n\tfunction getNumRatings(){\n\t\treturn sumRatings.length;\n\t}\n\t\n\tfunction getIndexForDate(when, strictlyEarlier){\n\t\tif(sumRatings.length < 1){\n\t\t\treturn -1;\n\t\t}\n\n //alert(\"RatingMovingAverage::getIndexForDate nonzero\");\n\t\tvar finalDate = sumRatings[sumRatings.length - 1].getDate();\n //alert(\"RatingMovingAverage::getIndexForDate comparing last\");\n\t\tif(strictlyChronologicallyOrdered(finalDate, when)){\n //alert(\"RatingMovingAverage::getIndexForDate was last\");\n\t\t\treturn sumRatings.length - 1;\n\t\t}\n\n //alert(\"RatingMovingAverage::getIndexForDate not last\");\n\t\t\n\t\tvar lowerIndex = 0;\n\t\tvar upperIndex = sumRatings.length - 1;\n\t\tvar middleIndex = 0;\n\t\t\n\t\twhile (upperIndex > lowerIndex + 1)\n\t\t{\n\t\t\tmiddleIndex = Math.floor((lowerIndex + upperIndex) / 2);\n\t\t\t//alert(\"middleIndex = \" + middleIndex);\n\t\t\tif (strictlyChronologicallyOrdered(sumRatings[middleIndex].getDate(), when)){\n\t\t\t\tlowerIndex = middleIndex;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tupperIndex = middleIndex;\n\t\t\t}\n\t\t}\n\t\t\n\t\tvar previousRating = sumRatings[lowerIndex];\n\t\tvar nextRating = sumRatings[upperIndex];\n\t\t\n\t\tif (strictlyEarlier){\n\t\t\treturn lowerIndex;\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t\tif(strictlyChronologicallyOrdered(when, nextRating.getDate())){\n\t\t\t\treturn lowerIndex;\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn upperIndex;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfunction getAverageValue(){\n\t\tif(sumRatings.length < 1){\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\treturn sumRatings[sumRatings.length -1].getScore()/(sumRatings.length);\n\t}\n\t\n\tfunction getLatestDate() {\n\t\tif(sumRatings.length < 1){\n\t\t\treturn DateTime();\n\t\t}\n\t\telse{\n\t\t\treturn sumRatings[sumRatings.length -1].getDate();\n\t\t}\n\t}\n\t\n\tfunction subFunction() {\n\t alert(\"RatingMovingAverage subfunction. This is good.\");\n\t}\n\t\n\tfunction isAParticipationMovingAverage() {\n\t return false;\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the current article Builds HTML elements from a provided JSON file in a specific format
function buildFromJSON(HTMLContainer, jsonObj) { console.log("parsing JSON object"); console.log(jsonObj); var elementToModel = null; for ( var obj in jsonObj ) { console.log("THING: "+ obj); console.log(jsonObj[obj]); switch (obj) { case 'title': var element = document.createElement("title"); element.textContent = jsonObj[obj]; HTMLContainer.appendChild(element); break; case 'body': var body = document.createElement('body'); HTMLContainer.appendChild(body); for( var e in jsonObj[obj]){ buildFromJSON(body, jsonObj[obj][e]); } break; case 'type': switch(jsonObj[obj]){ case 'paragraph': var p = document.createElement('p'); HTMLContainer.appendChild(p); elementToModel = p; break; case 'heading': var h = document.createElement('h1'); HTMLContainer.appendChild(h); elementToModel = h; break; case 'image': var image = document.createElement('img'); HTMLContainer.appendChild(image); elementToModel = image; break; case 'list': var list = document.createElement('ul'); HTMLContainer.appendChild(list); elementToModel = list; break; } break; case 'model': var element; if(elementToModel == null){ console.log("modelling container"); element = HTMLContainer; }else{ console.log("modelling element"); element = elementToModel; } for( var attribute in jsonObj[obj]){ console.log("Attribute " + attribute); if(attribute == 'text'){ element.textContent = jsonObj[obj][attribute]; }else if(attribute == 'url'){ element.setAttribute('src',jsonObj[obj][attribute] ) }else if(attribute == 'items'){ for(var item in jsonObj[obj][attribute]){ var listItem = document.createElement('li'); listItem.textContent = jsonObj[obj][attribute][item]; element.appendChild(listItem); } }else{ element.setAttribute(attribute, jsonObj[obj][attribute]) } } elementToModel = null; break; } } }
[ "async function buildJsonContent(file, primary, secondary, queryparams, baseurl) {\n\tconst filepath = './json/' + file + '.json';\n\tconsole.log(filepath);\n\tconst fileRequest = new Request(filepath);\n\tconst response = await fetch(fileRequest);\n\tconst jsonResponse = await response.json();\n\tlet returnContent = \"\"\n\tconsole.log(`${jsonResponse[0][primary]}`)\n\tfor (let obj in jsonResponse) {\n\t\treturnContent += \"<div class=\\\"bullet\\\" id=\\\"\" + `${jsonResponse[obj][primary]}` + \"\\\">\"\n\t\treturnContent += \"<h2 class=\\\"collapsible\\\">\"\n\t\treturnContent += \"<a href=\\\"\" + baseurl + `${jsonResponse[obj][queryparams]}` + \"\\\" target=\\\"_blank\\\">\"\n\t\treturnContent += `${jsonResponse[obj][primary]}`\n\t\treturnContent += \"</a>\"\n\t\treturnContent += \"</h2>\"\n\t\treturnContent += \"<div>\"\n\t\treturnContent += `${jsonResponse[obj][secondary]}`\n\t\treturnContent += \"</div>\"\n\t\t// returnContent += \"<p>\"\n\t\t// returnContent += `${jsonResponse[obj][description]}`\n\t\t// returnContent += \"</p>\"\n\t\treturnContent += \"</div>\"\n\t}\n\t// 'slide up, clear, and append'\n\t$(\"#content\").slideUp(\"slow\", function() {\n\t\t// start showing the border after one of the menu options is first clicked\n\t\tif (!document.getElementById(\"content\").classList.contains(\"border\")) {\n\t\t\t$(\"#content\").addClass(\"border\")\n\t\t}\n\t\tif (!document.getElementById(\"content\").classList.contains(\"life-list\")) {\n\t\t\t$(\"#content\").addClass(\"life-list\")\n\t\t}\n\t\t$(\"#content\").html(\"\"); // clear content\n\t\t$(\"#content\").html(returnContent).slideDown(); \n\t\t}\n\t); \n\treturn;\n}", "function generateUIForJSON(data){\n return `\n <div class=\"quarter\">\n <div class=\"image\">\n <img src=\"${data.picture}\"/>\n </div>\n <div class=\"info\">\n <h3>${data.name}</h3>\n <h4>${data.gender}</h3>\n <h5>${data.email}</h5>\n </div>\n </div>\n `\n}", "function buildHTML(jsnObj){\n //var jsnObj=JSON.parse(JSONText);\n \n var html=\"\"; \n for(var i in jsnObj.cameras){\n html+=\"<h3>Kamera \"+jsnObj.cameras[i].id+\": \"+jsnObj.cameras[i].ip+\"</h3>\";\n html+=\"<img id=\\\"cam\"+jsnObj.cameras[i].id+\"\\\" src=\\\"\"+\n jsnObj.cameras[i].path+\"\\\" alt=\\\"Bild Kamera \"+\n jsnObj.cameras[i].id+\"\\\" width=\\\"384\\\" height=\\\"216\\\" >\\n<br>\";\n } \n \n $('images').innerHTML=html;\n \n}", "function fillContents(activeContent, subTopic){\n Object.entries(webKnowledge[activeContent][subTopic]).forEach((key, value) => {\n // json \"content\"\n if(key[value] == \"content\"){\n let head = document.createElement(\"h2\");\n let headContent = document.createTextNode(\"Erklärung:\")\n let entry = document.createElement(\"p\");\n let entryContent = document.createTextNode(key[value+1]);\n head.appendChild(headContent)\n entry.appendChild(head);\n entry.appendChild(entryContent);\n contentRoot.appendChild(entry);\n }\n // json \"references\" (is array and needs special treatment)\n else {\n let head = document.createElement(\"small\");\n let headContent = document.createTextNode(\"References: \")\n let entry = document.createElement(\"small\");\n let entryContent = document.createTextNode(key[value]);\n head.appendChild(headContent)\n entry.appendChild(head);\n entry.appendChild(entryContent);\n contentRoot.appendChild(entry);\n }\n\n });\n}", "static generate_settings() {\n // Initialise variables\n var html_content = {}\n var html_heading = {}\n\n // Setup content and heading variables\n for (var item of this.settings_json[\"categories\"]) {\n html_content[item] = \"\"\n\n html_heading[item] = this.html_settings_heading\n .replace(/{{item}}/g, item)\n }\n\n // Loop through setttings JSON and create HTML file\n for (var item of this.settings_json[\"settings\"]) {\n\n var category = item[\"category\"]\n\n // Select correct template based on advanced setting or not\n var temp_out\n if (item[\"advanced\"]) {\n temp_out = this.html_settings_advanced\n } else {\n temp_out = this.html_settings\n }\n\n // Replace variables\n temp_out = temp_out\n .replace(/{{title}}/g, item[\"title\"])\n .replace(/{{id}}/g, item[\"id\"])\n .replace(/{{unit}}/g, item[\"unit\"])\n .replace(/{{help}}/g, item[\"help\"])\n\n // Update main string\n html_content[category] = html_content[category].concat(temp_out)\n }\n\n var temp_html = \"\"\n for (item of this.settings_json[\"categories\"]) {\n temp_html = temp_html\n .concat(html_heading[item])\n .concat(html_content[item])\n }\n\n // Update HMTL on page\n document.querySelector(\"#settings_template_div\").innerHTML = temp_html\n }", "function generateProjectHTML(id) {\n \n var html = '';\n var idString = id.toString();\n var data = sheet2Json('Projects');\n //filter the data to get the project with thr required id\n var projectDataArray = data.filter(function (entry) {\n return entry.id == idString;\n });\n //the above returns an array - you want just the first item\n var projectData = projectDataArray[0];\n \n var bodyClass = 'project-page';\n\n html += '<!DOCTYPE html>' +\n '<html>' +\n '<head>' +\n '<base target=\"_top\">' + \n getContent('head') + \n '<title>' + projectData.title + ' - ToGetThere</title>' +\n '</head>' +\n '<body id=\"page-top\" class=\"' + bodyClass + '\">' +\n getContent('navigation'); \n \n\t\n // Header\n var headerImage_url = projectData.headerImage_url;\n if(!headerImage_url) { headerImage_url = '/images/header.jpg';} \n html += '<header class=\"masthead\" style=\"background-image: url(' + headerImage_url + ')\">' +\n\t\t\t '<div class=\"container\">' +\n\t\t\t\t'<div class=\"intro-text\">' +\n\t\t\t\t\t'<div class=\"intro-lead-in\">' + projectData['headline'] + '</div>' +\n\t\t\t\t\t'<div class=\"intro-heading text-uppercase\">' + projectData['title'] + '</div>' +\n\t\t\t\t\t'<a class=\"btn btn-primary btn-xl text-uppercase js-scroll-trigger\" href=\"#donate\">Give</a>' +\n\t\t\t\t'</div>' +\n\t\t\t '</div>' +\n\t\t\t'</header>';\n\n // Project description - you have 3 rows\n html += '<section id=\"description\">' +\n \t '<div class=\"container\">';\n \n if (projectData.top_row) { \n html += '<div class=\"row\">' +\n '<div class=\"col-lg-12\">' +\n projectData.top_row +\n '</div>' +\n '</div>';\n }\n \n if (projectData.middle_row) { \n html += '<div class=\"row\">' +\n '<div class=\"col-lg-12\">' +\n projectData.middle_row +\n '</div>' +\n '</div>';\n }\n \n\t\n if (projectData.bottom_row) { \n html += '<div class=\"row\">' +\n '<div class=\"col-lg-12\">' +\n projectData.bottom_row +\n '</div>' +\n '</div>';\n }\n\t\n html += '</section>';\n\n\t\n \n // Donate section - up to 3 calls to action\n var colCount = 0;\n if(projectData.money_url) { colCount = colCount+1 }\n if(projectData.equipment_text) { colCount = colCount+1 }\n if(projectData.service_text) { colCount = colCount+1 }\n\t\n if (colCount> 0) {\n var colSize = 12/colCount;\n \n html += '<section id=\"donate\">' +\n '<div class=\"container\">' +\n\t\t\t\t'<div class=\"row text-center\">';\n\t\t\t\t if(projectData.money_url) {\n\t\t\t\t\thtml += '<div class=\"col-md-' + colSize + '\">' +\n\t\t\t\t\t\t\t '<a class=\"cta cta-ask cta-button\" data-toggle=\"modal\" href=\"' + projectData.money_url +'\">' +\n\t\t\t\t\t\t\t\t'<span class=\"fa-stack fa-4x\">' +\n\t\t\t\t\t\t\t\t '<i class=\"fa fa-circle fa-stack-2x text-primary\"></i>' +\n\t\t\t\t\t\t\t\t '<i class=\"fa fa-question fa-stack-1x fa-inverse\"></i>' +\n\t\t\t\t\t\t\t\t'</span>' +\n\t\t\t\t\t\t\t '</a>' +\n\t\t\t\t\t\t\t '<h4 class=\"service-heading\">' +\n\t\t\t\t\t\t\t '<a class=\"cta cta-ask cta-text\" data-toggle=\"modal\" href=\"' + projectData.money_url + '\">Donate</a>' +\n\t\t\t\t\t\t\t '</h4>' +\n\t\t\t\t\t\t\t '<p class=\"text-muted\">' + projectData.money_text + '</p>' +\n\t\t\t\t\t\t\t'</div>';\n\t\t\t\t }\n\t\t\t\t\t\t\n\t\t\t\t if(projectData.equipment_text) {\n\t\t\t\t\tif (!projectData.equipment_url) { projectData.equipment_url = '#give-equipment'}\n\t\t\t\t\t html += '<div class=\"col-md-' + colSize + '\">' +\n\t\t\t\t\t \t\t '<a class=\"cta cta-ask cta-button\" data-toggle=\"modal\" href=\"' + projectData.equipment_url + '\">' +\n\t\t\t\t\t\t\t\t '<span class=\"fa-stack fa-4x\">' +\n\t\t\t\t\t\t\t\t\t'<i class=\"fa fa-circle fa-stack-2x text-primary\"></i>' +\n\t\t\t\t\t\t\t\t\t'<i class=\"fa fa-question fa-stack-1x fa-inverse\"></i>' +\n\t\t\t\t\t\t\t\t '</span>' +\n\t\t\t\t\t\t\t\t'</a>' +\n\t\t\t\t\t\t\t\t'<h4 class=\"service-heading\">' +\n\t\t\t\t\t\t\t\t '<a class=\"cta cta-ask cta-text\" data-toggle=\"modal\" href=\"' + projectData.equipment_url + '\">Give</a>' +\n\t\t\t\t\t\t\t\t'</h4>' +\n\t\t\t\t\t\t\t\t'<p class=\"text-muted\">' + projectData.equipment_text + '</p>' +\n\t\t\t\t\t\t\t '</div>';\n\t\t\t\t }\n\t\t\t\t\t\t\n\t\t\t\t if(projectData.service_text) {\n\t\t\t\t\tif (!projectData.service_url) { projectData.service_url = '#give-service'}\n\t\t\t\t\t html += '<div class=\"col-md-' + colSize + '\">' +\n\t\t\t\t\t\t\t\t'<a class=\"cta cta-ask cta-button\" data-toggle=\"modal\" href=\"' + projectData.service_url + '\">' +\n\t\t\t\t\t \t\t\t '<span class=\"fa-stack fa-4x\">' +\n\t\t\t\t\t\t\t\t\t'<i class=\"fa fa-circle fa-stack-2x text-primary\"></i>' +\n\t\t\t\t\t\t\t\t\t'<i class=\"fa fa-question fa-stack-1x fa-inverse\"></i>' +\n\t\t\t\t\t\t\t\t '</span>' +\n\t\t\t\t\t\t\t\t'</a>' +\n\t\t\t\t\t\t\t\t'<h4 class=\"service-heading\">' +\n\t\t\t\t\t\t\t\t '<a class=\"cta cta-ask cta-text\" data-toggle=\"modal\" href=\"' + projectData.service_url + '\">Give</a>' +\n\t\t\t\t\t\t\t\t'</h4>' +\n\t\t\t\t\t\t\t\t'<p class=\"text-muted\">' + projectData.service_text + '</p>' +\n\t\t\t\t\t\t\t '</div>';\n\t\t\t\t }\n\n\t\t\t\t html += '</div>' +\n\t\t\t\t '</div>' +\n\t\t\t '</section>';\n }\n\t\n // Team - TODO\n if(projectData.has_team) {\n html += '<section class=\"bg-light\" id=\"team\">' +\n\t\t\t'</section>';\n }\n \n // Links - TODO\n var colCount = 0;\n if(projectData.facebook_url) { colCount = colCount+1 }\n if(projectData.twitter_url) { colCount = colCount+1 }\n if(projectData.site_url) { colCount = colCount+1 }\n \n if (colCount> 0) {\n var colSize = 12/colCount;\n \n } \n \n html += getContent('footer') + \n '</body>' +\n '</html>'; \n\n return html;\n\n}", "function displayArticle5(article5) {\n var parsedArticle5 = JSON.parse(article5);\n document.getElementById(\"showArticle\").innerHTML = `\n <h1 class=\"article-title\">${parsedArticle5.title}</h1><br>\n <h2 class=\"article-header\">${parsedArticle5.body[0].model.text}</h2><br>\n <div class=\"row\">\n <div class=\"col-sm-4\">\n <img class=\"article-photo\" src=\"${parsedArticle5.body[1].model.url}\"> <hr>\n <p><strong>${parsedArticle5.body[1].model.altText}</strong></p><hr>\n </div>\n <div class=\"col-sm-4\">\n <p>${parsedArticle5.body[3].model.text}</p>\n </div>\n <div class=\"col-sm-4\">\n <img class=\"article-photo\" src=\"${parsedArticle5.body[2].model.url}\"> <hr>\n <p><strong>${parsedArticle5.body[2].model.altText}</strong></p><hr>\n </div>\n </div>\n `;\n}", "async function scrape() {\n // Declaration of local JSON file\n var jsonFile = fs.readFileSync('genshin.json');\n var genshinJSON = JSON.parse(jsonFile);\n\n // Opens Browser\n const browser = await puppeteer.launch({\n args: ['--no-sandbox', '--disable-setuid-sandbox', '--mute-audio']\n });\n // Opens New Browser Page\n const page = await browser.newPage();\n // Visits MiHoYo Website\n await page.goto('http://genshin.mihoyo.com/en/news/', {\n waitUntil: 'domcontentloaded'\n });\n // Wait for load and select news item\n await page.waitForSelector(\".news__item\")\n\n var news = await page.evaluate(() => {\n var newsList = document.querySelectorAll(\".news__item\")\n var newsLinkArray = [];\n\n // Has the ability to pull all 5 news topics but is currently set to one article\n for (var i = 0; i < 1; i++) {\n\n newsLinkArray[0] = {\n title: newsList[0].childNodes[0].querySelector('H3').innerText,\n image: newsList[0].childNodes[0].querySelector('img').src,\n link: newsList[0].querySelector('a').href,\n };\n }\n\n return newsLinkArray\n });\n\n await page.goto(news[0].link, {\n waitUntil: 'domcontentloaded'\n });\n\n await page.waitForSelector(\".article\")\n\n var article = await page.evaluate(() => {\n // Function to trim down text, remove spacing, and paragraphs\n function cutString(string) {\n var cut = string.indexOf(' ', 450);\n if (cut == -1) return s;\n return string.substring(0, cut).replace(/[\\r\\n]+/gm, \" \").replace(/\\s+/g, ' ').trim()\n }\n\n var articleList = document.querySelector(\".article__content\")\n var articleArray = [];\n\n for (var i = 0; i < 1; i++) {\n\n articleArray[0] = {\n content: cutString(`${articleList.innerText}.`)\n };\n\n }\n return articleArray\n\n })\n\n // Combines both JSON files into one object\n var result = {\n news: news,\n description: article,\n };\n\n // Closes the browser\n await browser.close();\n\n // Loops through the discord webhooks and posts the latest news\n\n var list = \"\";\n\n // Retrieves list of discord webhooks from webserver\n function getItems() {\n fetch('http://genshinnews.com/api')\n .then(response => response.text())\n .then(data => {\n discordHooks = JSON.parse(`[${data}]`)\n webhookLoop(discordHooks)\n });\n }\n\n function webhookLoop(discordWebhook) {\n for (let i = 0; i < discordWebhook.length; i++) {\n list += discordWebhook[i].webhook.url\n try {\n const webhook = require(\"webhook-discord\")\n const hook = new webhook.Webhook(discordWebhook[i].webhook.url)\n const msg = new webhook.MessageBuilder()\n .setAvatar(\"Insert URL for Avatar\")\n .setName(\"Insert Name\")\n .setAuthor('Insert Author')\n .setColor(\"#aabbcc\")\n .setURL(result.news[0].link)\n .setDescription(`${result.description[0].content}\\n\\n More details [here](${result.news[0].link})!`)\n .setImage(result.news[0].image)\n .setTitle(result.news[0].title);\n hook.send(msg)\n } catch (error) {\n delete discordWebhook[i]\n };\n }\n return list\n }\n\n if (result.news[0].title === genshinJSON.news[0].title) {\n noDLCount += 1;\n totalScrapes(); // updates stats.json\n discordSuccessMsg(`No new articles have been detected. This sessions has had ${noDLCount} checks`);\n postStatsJson();\n postArticles();\n totalWebhooks();\n } else {\n DLCount += 1;\n // Write the news inside JSON file\n fs.writeFile(\"genshin.json\", JSON.stringify(result), function(err) {\n if (err) throw err;\n discordSuccessMsg(`This sessions has had ${DLCount} successful downloads`);\n successfullScrape();\n postStatsJson();\n getItems();\n postArticles();\n totalWebhooks();\n });\n }\n}", "_jsonLoaded(jsonString, template) {\n var i,\n dataJSON = JSON.parse(jsonString),\n mediaEntry = {},\n\n // our flat object used for the templates\n parsedJSON = {\n data: []\n },\n\n getVideoUrl = function(mediaContentArray){\n var url, j;\n\n for( j = 0; j < mediaContentArray.length; j++ ){\n if( mediaContentArray[j].plfile$height === 1080 ){\n url = mediaContentArray[j].plfile$url;\n }\n }\n\n return url;\n };\n \n\n\n for(i = 0; i < dataJSON.entries.length; i++){\n\n mediaEntry = {\n name: dataJSON.entries[i].title,\n dataUrl: getVideoUrl(dataJSON.entries[i].media$content),\n cleandescription: dataJSON.entries[i].description === null ? \"\" : dataJSON.entries[i].description.replace(/\\\"/g, '&quote'),\n thumbnailUrl: dataJSON.entries[i].media$thumbnails[0].plfile$url,\n description: dataJSON.entries[i].description\n };\n\n parsedJSON.data.push(mediaEntry);\n }\n \n \n // Add backgroundImg key\n parsedJSON.backgroundImg = this.nativeResourceLoader.urlForResource(this.videosBkg);\n \n console.log(parsedJSON);\n \n // Get the template string from the bundle\n var xml = this.nativeResourceLoader.loadBundleResource(template);\n \n // Render template string\n var rendered = Mustache.render(xml, parsedJSON);\n \n // Parse XML\n rendered = resourceLoader.domParser.parseFromString(rendered, \"application/xml\");\n \n // Replace the loading template with the current template\n var currentDoc = getActiveDocument();\n \n navigationDocument.replaceDocument(rendered, currentDoc);\n \n // Attach the select event handler\n var currentDoc = getActiveDocument();\n \n currentDoc.addEventListener(\"select\", eventHandler.handleEvent);\n }", "function renderArticles(doc){\n let div = document.createElement('div');\n \n let image = document.createElement('img');\n let title = document.createElement('h3');\n let content = document.createElement('p');\n \n\n // var createA = document.createElement('a');\n // createA.setAttribute('href', \"single-blog.html\");\n \n \n\n image.src = doc.data().image;\n title.textContent = doc.data().title;\n content.textContent = doc.data().content;\n\n \n div.setAttribute('data-id', doc.id);\n div.appendChild(image);\n div.appendChild(title);\n //createA.appendChild(title);\n //div.appendChild(createA);\n div.appendChild(content);\n \n\n articlesList.appendChild(div);\n\n \n\n}", "function mapCaseJsonToUi(data){\n\t//\n\t// This gives me ONE object - The root for test cases\n\t// The step tag is the basis for each step in the Steps data array object.\n\t// \n\tvar items = []; \n\tvar xdata = data['step'];\n\tif (!jQuery.isArray(xdata)) xdata = [xdata]; // convert singleton to array\n\n\n\t//console.log(\"xdata =\" + xdata);\n\tkatana.$activeTab.find(\"#tableOfTestStepsForCase\").html(\"\"); // Start with clean slate\n\titems.push('<table class=\"case_configuration_table table-striped\" id=\"Step_table_display\" width=\"100%\" >');\n\titems.push('<thead>');\n\titems.push('<tr id=\"StepRow\"><th>#</th><th>Driver</th><th>Keyword</th><th>Description</th><th>Arguments</th>\\\n\t\t<th>OnError</th><th>Execute</th><th>Run Mode</th><th>Context</th><th>Impact</th><th>Other</th></tr>');\n\titems.push('</thead>');\n\titems.push('<tbody>');\n\tfor (var s=0; s<Object.keys(xdata).length; s++ ) { // for s in xdata\n\t\tvar oneCaseStep = xdata[s]; // for each step in case\n\t\t//console.log(oneCaseStep['path']);\n\t\tvar showID = parseInt(s)+1;\n\t\titems.push('<tr data-sid=\"'+s+'\"><td>'+showID+'</td>'); // ID \n\t\t// -------------------------------------------------------------------------\n\t\t// Validation and default assignments \n\t\t// Create empty elements with defaults if none found. ;-)\n\t\t// -------------------------------------------------------------------------\n\t\tfillStepDefaults(oneCaseStep);\n\t\titems.push('<td>'+oneCaseStep['@Driver'] +'</td>'); \n\t\tvar outstr; \n\t\titems.push('<td>'+oneCaseStep['@Keyword'] + \"<br>TS=\" +oneCaseStep['@TS']+'</td>'); \n\t\toutstr = oneCaseStep['Description'];\n\t\titems.push('<td>'+outstr+'</td>'); \n\n\t\tvar arguments = oneCaseStep['Arguments']['argument'];\n\t\tvar out_array = [] \n\t\tvar ta = 0; \n\t\tfor (xarg in arguments) {\n\n\t\t\tif (!arguments[xarg]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar argvalue = arguments[xarg]['@value'];\n\t\t\tconsole.log(\"argvalue\", argvalue);\n\t\t\t\tif (argvalue) {\n\t\t\t\tif (argvalue.length > 1) {\n\t\t\t\t\tvar xstr = arguments[xarg]['@name']+\" = \"+arguments[xarg]['@value'] + \"<br>\";\n\t\t\t\t\t//console.log(xstr);\n\t\t\t\t\tout_array.push(xstr); \n\t\t\t\t\t}\n\t\t\t\tta = ta + 1; \n\t\t\t\t}\n\t\t\t}\n\t\toutstr = out_array.join(\"\");\n\t\t//console.log(\"Arguments --> \"+outstr);\n\t\titems.push('<td>'+outstr+'</td>'); \n\t\toutstr = oneCaseStep['onError']['@action'] \n\t\t\t//\"Value=\" + oneCaseStep['onError']['@value']+\"<br>\"; \n\t\titems.push('<td>'+oneCaseStep['onError']['@action'] +'</td>'); \n\t\toneCaseStep['Execute']['@ExecType'] = jsUcfirst( oneCaseStep['Execute']['@ExecType']);\n\t\toutstr = \"ExecType=\" + oneCaseStep['Execute']['@ExecType'] + \"<br>\";\n\t\tif (oneCaseStep['Execute']['@ExecType'] == 'If' || oneCaseStep['Execute']['@ExecType'] == 'If Not') {\n\t\t\toutstr = outstr + \"Condition=\"+oneCaseStep['Execute']['Rule']['@Condition']+ \"<br>\" + \n\t\t\t\"Condvalue=\"+oneCaseStep['Execute']['Rule']['@Condvalue']+ \"<br>\" + \n\t\t\t\"Else=\"+oneCaseStep['Execute']['Rule']['@Else']+ \"<br>\" +\n\t\t\t\"Elsevalue=\"+oneCaseStep['Execute']['Rule']['@Elsevalue'];\n\t\t}\n\t\t \n\t\t\t\n\t\titems.push('<td>'+outstr+'</td>'); \n\t\titems.push('<td>'+oneCaseStep['runmode']['@type']+'</td>');\n\t\titems.push('<td>'+oneCaseStep['context']+'</td>');\n\t\titems.push('<td>'+oneCaseStep['impact']+'</td>'); \n\t\tvar bid = \"deleteTestStep-\"+s+\"-id-\"\n\t\titems.push('<td><i title=\"Delete\" class=\"fa fa-trash\" theSid=\"'+s+'\" id=\"'+bid+'\" katana-click=\"deleteCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t\tbid = \"editTestStep-\"+s+\"-id-\";\n\t\titems.push('<i title=\"Edit\" class=\"fa fa-pencil\" theSid=\"'+s+'\" value=\"Edit/Save\" id=\"'+bid+'\" katana-click=\"editCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t\tbid = \"addTestStepAbove-\"+s+\"-id-\";\n\t\titems.push('<i title=\"Insert\" class=\"fa fa-plus\" theSid=\"'+s+'\" value=\"Insert\" id=\"'+bid+'\" katana-click=\"addCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t\tbid = \"dupTestStepAbove-\"+s+\"-id-\";\n\t\titems.push('<i title=\"Insert\" class=\"fa fa-copy\" theSid=\"'+s+'\" value=\"Duplicate\" id=\"'+bid+'\" katana-click=\"duplicateCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t}\n\n\titems.push('</tbody>');\n\titems.push('</table>'); // \n\tkatana.$activeTab.find(\"#tableOfTestStepsForCase\").html( items.join(\"\"));\n\tkatana.$activeTab.find('#Step_table_display tbody').sortable( { stop: testCaseSortEventHandler});\n\t\n\tfillCaseDefaultGoto();\n\tkatana.$activeTab.find('#default_onError').on('change',fillCaseDefaultGoto );\n\n\t/*\n\tif (jsonCaseDetails['Datatype'] == 'Custom') {\n\t\t$(\".arguments-div\").hide();\n\t} else {\n\n\t\t$(\".arguments-div\").show();\n\t}\n\t*/\n\t\n} // end of function ", "function buildThemePage(obj) {\n var data = [];\n var allPages = [];\n var page = {};\n var filePath;\n var theme;\n var recipie;\n var i;\n\n for (i = obj.startIndex; i < obj.endIndex; i++) {\n recipie = obj.allRecipes[i];\n theme = {};\n theme.title = recipie.name.spacedValue;\n theme.img = '.' + recipie.smallImg;\n theme.link = '../themes/' + recipie.name.hyphenedValue + '.html';\n data.push(theme);\n }\n for (i = 0; i < obj.pageLimit; i++) {\n allPages.push(i + 1);\n }\n page.themes = data;\n allPages[obj.currentPage] = {\n current: true,\n number: (obj.currentPage + 1)\n };\n page.pages = allPages;\n filePath = ROOT_DIR + 'index/' + (obj.currentPage + 1) + '.html';\n\n setPageHeadData(page, obj.currentPage, obj.pageLimit);\n\n fs.writeFile(filePath, obj.template(page), function() {\n log.created('Theme index page', filePath);\n });\n}", "makeHtml(artwork, userArtwork, genre){\n\n // article\n let article = document.createElement('article');\n article.classList.add('shadow');\n article.classList.add('borderAll');\n\n // figure\n let figure = document.createElement('figure');\n figure.classList.add('hover-caption');\n figure.tabIndex = 0;\n\n // image\n let img = document.createElement('img');\n img.src = artwork.image;\n img.alt = artwork.name;\n\n // span\n let span = document.createElement('span');\n if(userArtwork !== undefined){\n if(this.isUserList){\n \n // form\n span = document.createElement('form');\n span.action = '/set-artwork-list-status';\n span.method = 'post';\n\n // input hidden artwork_id\n let inputSpan = document.createElement('input');\n inputSpan.type = 'hidden';\n inputSpan.name = 'artwork_id';\n inputSpan.value = artwork.id;\n\n // select\n let select = document.createElement('select');\n select.id = 'changeStatusSelect';\n select.name = 'status';\n this.allStatus.forEach( status => {\n let option = new Option(this.lang.status[status], status, status === userArtwork.status, status === userArtwork.status);\n select.append(option);\n });\n\n // append in form\n span.append(inputSpan);\n span.append(select);\n }else{\n if(userArtwork === undefined){\n span.classList.add('none');\n }else{\n span.innerText = this.lang.status[userArtwork.status];\n }\n }\n } else{\n span.classList.add('none');\n }\n span.classList.add('user-status');\n \n // figcaption\n let figcaption = document.createElement('figcaption');\n\n // div\n let div = document.createElement('div');\n\n // title\n let h3 = document.createElement('h3');\n h3.innerText = artwork.name;\n\n // author\n let pAuthor = document.createElement('p');\n pAuthor.innerText = 'Créer par : ' + artwork.author;\n\n // genre\n let pGenre = document.createElement('p');\n pGenre.innerText = 'Genre : ' + genre;\n\n // note\n let pNote = document.createElement('p');\n pNote.innerText = 'Note : ' + artwork.note + '/10';\n\n // button more info\n let a = document.createElement('a');\n a.classList.add('button');\n a.classList.add('block-center');\n a.href = `${this.langName}/${this.type}/info/${artwork.slug}`;\n a.innerText = 'Plus d\\'info';\n\n // append to div\n div.append(h3);\n div.append(pAuthor);\n if (artwork.genre !== '') div.append(pGenre);\n if (artwork.note !== '') div.append(pNote);\n div.append(a);\n\n // form\n let form = document.createElement('form');\n form.action = `${this.langName}/add-artwork-list`;\n form.method = 'post';\n\n // input\n let input = document.createElement('input');\n input.type = 'hidden';\n input.name = 'artwork_id';\n input.value = artwork.id;\n\n // button\n let button;\n if(this.userList.length > 0){\n button = document.createElement('button');\n button.classList.add('artwork-list-button');\n if(userArtwork === undefined){\n button.id = 'addArtworkList';\n button.classList.add('add');\n }else{\n button.id = 'removeArtworkList';\n button.classList.add('remove');\n }\n }\n\n // append to form\n form.append(input);\n if(this.userList.length > 0) form.append(button);\n\n // append to figcaption\n figcaption.append(div);\n figcaption.append(form);\n\n // append to figure\n figure.append(img);\n figure.append(span);\n figure.append(figcaption);\n\n // append to article\n article.append(figure);\n\n return article;\n \n }", "function createArticle (data) {\n let dest = $('section.places');\n\n data.forEach((place) => {\n dest.append(setHTML(place, users[place.user_id]));\n });\n}", "function renderAnnouncements(doc){\r\n\tlet li = document.createElement('li');\r\n\tlet churchSel = document.createElement('span');\r\n\t//let dioceseSel = document.createElement('span');\r\n\t//let dinarySel = document.createElement('span');\r\n\t//let title = document.createElement('span');\r\n\tlet subject = document.createElement('span');\r\n\tlet myFile = document.createElement('span');\r\n\t\r\n\tli.setAttribute('data-id',doc.id);\r\n\tchurchSel.textContent = doc.data().churchSel;\r\n\t//dioceseSel.textContent = doc.data().dioceseSel;\r\n\t//dinarySel.textContent = doc.data().dinarySel;\r\n\t//title.textContent = doc.data().title;\r\n\tsubject.textContent = doc.data().subject;\r\n\tmyFile.textContent = doc.data().myFile;\r\n\t\r\n\tli.appendChild(churchSel);\r\n\t//li.appendChild(dioceseSel);\r\n\t//li.appendChild(dinarySel);\r\n\t//li.appendChild(title);\r\n\tli.appendChild(subject);\r\n\t//li.appendChild(myFile);\r\n\t\r\n\t//announcementsList.appendChild(li);\r\n\t\r\n}", "function addListToHtml(ul) {\n fetchYaml().then(function(yamlData) {\n for (i in yamlData) {\n // LOCAL VARIABLES\n let label = document.createElement(\"label\");\n let input = document.createElement(\"input\");\n let span = document.createElement(\"span\");\n let img = document.createElement(\"img\");\n let li = document.createElement(\"li\");\n\n // SET ATTRIBUTES\n label.htmlFor = i // <label for={yamlData.pkgName}>\n span.className = \"package-list__label-text\"\n label.className = \"package-list__label\";\n label.title = yamlData[i].description;\n\n input.type = \"checkbox\";\n input.name = \"package-item\";\n input.className = \"label__checkbox\";\n input.value = i\n input.id = i\n img.src = iconSrc + yamlData[i].icoUrl;\n img.className = \"icoImg\";\n span.innerHTML = `<b>${yamlData[i].name}</b> - ${yamlData[i].description}`;\n\n\n li.className = \"package-list__item\";\n\n // WRITE ELEMENTS\n label.appendChild(input); // <div><label><input> <=\n label.appendChild(img);\n label.appendChild(span); // write yamlData.name after checkbox\n li.appendChild(label); // <div><label> <=\n ul.appendChild(li); // li --> label --> input, img\n\n }\n })\n}", "function _process(json, options) {\n // Add the header:\n let s = [\n '<!-- Made with Natural Earth. Free vector and raster map data @ naturalearthdata.com. -->\\n',\n '<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\\n',\n ' <g transform=\"translate(0, 0) scale(1, 1)\">\\n',\n ].join('');\n\n // Add the SVG elements:\n let d;\n if (json.type === 'FeatureCollection') {\n for (let i = 0; i < json.features.length; i++) {\n d = _getSVGPath(json.features[i].geometry.coordinates, options);\n s += ` <path id=\"\" class=\"land\" d=\"${d}\"></path>\\n`;\n }\n } else {\n d = _getSVGPath(json.geometry.coordinates, options);\n s += ` <path id=\"\" class=\"land\" d=\"${d}\"></path>\\n`;\n }\n\n // Append the XML Footer:\n s += ' </g>\\n';\n s += '</svg>\\n';\n\n return s;\n }", "function prepareHTML(source) {\n $(\"#progress\").removeClass('hide');\n var listContainer = $(\"#listContainer\");\n var configs = [\n {\n header : 'Knowledge Articles',\n pattern : /KB\\d{6,7}/g,\n url : origin + '/kb_view.do?sysparm_article=',\n tableName : 'kb_knowledge',\n fields : 'short_description',\n labelsMap : {\n 'short_description' : 'Short description'\n },\n limit : 1\n },\n {\n header : 'Problems',\n pattern : /PRB\\d{6,7}/g,\n url : origin + '/problem.do?sysparm_query=number=',\n tableName : 'problem',\n fields : 'problem_state,description,priority',\n labelsMap : {\n 'problem_state' : 'Problem state',\n 'description' : 'Description',\n 'priority' : 'Priority'\n },\n fieldsMap : {\n 'problem_state' : {\n '-40' : 'New',\n '-42' : 'Investigation',\n '1' : 'Confirmed',\n '2' : 'Work in Progress',\n '9' : 'Testing',\n '3' : 'Closed'\n },\n 'priority' : {\n '0' : 'Critical (Outage)',\n '2' : 'High',\n '3' : 'Moderate',\n '4' : 'Low',\n '5' : 'Planning'\n }\n },\n limit : 1\n },\n {\n header : 'Tasks',\n pattern : /INT\\d{6,7}/g,\n url : origin + '/incident.do?sysparm_query=number=',\n tableName : 'incident',\n fields : 'severity,description',\n labelsMap : {\n 'severity' : 'Severity',\n 'description' : 'Description'\n },\n limit : 1\n },\n {\n header : 'Fix Targets',\n pattern : /FIX\\d{6,7}/g,\n url : origin + '/u_fix_target.do?sysparm_query=number=',\n tableName : 'u_fix_target',\n fields : 'description,state',\n labelsMap : {\n 'state' : 'State',\n 'description' : 'Description'\n },\n fieldsMap : {\n 'state' : {\n '-50' : 'Draft',\n '-51' : 'Awaiting Fix',\n '2' : 'Work in Progress',\n '-7' : 'Ready for Testing',\n '-52' : 'Testing Failed',\n '3' : 'Closed'\n }\n },\n limit : 1\n },\n {\n header : 'Stories',\n pattern : /STRY\\d{6,7}/g,\n url : origin + '/rm_story.do?sysparm_query=number=',\n tableName : 'rm_story',\n fields : 'description,state',\n labelsMap : {\n 'state' : 'State',\n 'description' : 'Description'\n },\n fieldsMap : {\n 'state' : {\n '-6' : 'Draft',\n '1' : 'Ready',\n '2' : 'Work in progress',\n '-7' : 'Ready for testing',\n '-8' : 'Testing',\n '3' : 'Complete',\n '4' : 'Cancelled',\n '6' : 'Accepted',\n '5' : 'Ready for acceptance'\n }\n },\n limit : 1\n }\n ];\n\n for (var i = 0; i < configs.length; i++) {\n var config = configs[i];\n // preparing the list container.\n var itemListContainer = document.createElement('div');\n\n // preparing the unordered list.\n var itemUl = document.createElement('ul');\n itemUl.setAttribute('class', 'collection with-header text-primary');\n itemUl.appendChild(prepareListHeader(config.header));\n\n var items = source.match(config.pattern);\n\n if (items) {\n prepareResultsList(itemUl, items, config);\n itemListContainer.appendChild(itemUl);\n listContainer.append(itemListContainer);\n }\n }\n if (0 === listContainer.children().length) {\n showErrorNotification('No records found on the page', true);\n }\n $(\"#progress\").hide();\n}", "async function transformToTLJson() {\n var timelineJson = {}\n timelineJson.events = [];\n // list of slide objects (each slide is an event)\n\n //wikiDate is in iso-8601 format \n function parseDate(wikiDate) {\n var wdate = new Date(wikiDate);\n\n return {\n year: wdate.getUTCFullYear(),\n month: wdate.getUTCMonth(),\n day: wdate.getUTCDate(),\n hour: wdate.getUTCHours(),\n minute: wdate.getUTCMinutes(),\n second: wdate.getUTCSeconds(),\n display_date: `Date of discovery: ${wdate.getUTCFullYear()}`\n };\n\n }\n\n function newSlide(wikiElement) {\n var slide = {};\n\n if (wikiElement.dateOfDiscovery) {\n if (wikiElement.dateOfDiscovery.startsWith('-')) {\n let year = wikiElement.dateOfDiscovery.match(/(-\\d+)-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z/);\n if (year) {\n slide.start_date = {\n year: year[1]\n };\n } else {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n } else {\n slide.start_date = parseDate(wikiElement.dateOfDiscovery);\n if (isNaN(slide.start_date.year)) {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n }\n } else {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n\n slide.text = {\n headline: ` <a href=\"${wikiElement.elementWikiUrl}\">${wikiElement.elementLabel}</a>`,\n text: createTable(selectTableData(wikiElement))\n };\n\n slide.media = {\n url: wikiElement.elementWikiUrl,\n thumbnail: wikiElement.picture\n };\n slide.unique_id = \"a\" + wikiElement.anum;\n slide.autolink = false;\n return slide;\n }\n\n var wikiData = await getData();\n for (var ekey in wikiData) {\n timelineJson.events.push(newSlide(wikiData[ekey]));\n }\n return timelineJson;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getting remaining hours, real time is a must optional setting, this is just a test for now
function hoursRemain() { var totalHours = dayNumber() * 24; var hour; //added +24 hous for leap and non-leapYear to work logically if (isLeapYear()) { hour = 8808; } else { hour = 8784; } hour -= totalHours; return hour; }
[ "calcRemainingTime() {\n return (Math.round((currentGame.endTime - Date.now()) / 100));\n }", "function get_time_left() {\n return (total_paid / price_per_second) - time_spent;\n}", "function getHoursFromTemplate() {\n var hours = parseInt(scope.hours, 10);\n var valid = ( scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);\n if (!valid) {\n return undefined;\n }\n\n if (scope.showMeridian) {\n if (hours === 12) {\n hours = 0;\n }\n if (scope.meridian === meridians[1]) {\n hours = hours + 12;\n }\n }\n return hours;\n }", "get formattedHours() {\n const _hours = this.hours;\n let hours = _hours;\n if (_hours !== null) {\n hours = this.amPm && _hours > HOURS_OF_NOON\n ? _hours - HOURS_OF_NOON : this.amPm && !_hours ? HOURS_OF_NOON : _hours;\n }\n return this.formattedUnit(hours);\n }", "function getHoursFromTemplate(){var hours=parseInt(scope.hours,10);var valid=scope.showMeridian?hours>0&&hours<13:hours>=0&&hours<24;if(!valid){return undefined;}if(scope.showMeridian){if(hours===12){hours=0;}if(scope.meridian===meridians[1]){hours=hours+12;}}return hours;}", "function calculateTimeLeft(then){\r\n //this line is getting the current time and date\r\n var now = new Date().getTime();\r\n //this line is getting the difference(gap) between now and the selected holiday\r\n var gap = then - now;\r\n\r\n var seconds = 1000;\r\n var minutes = seconds* 60;\r\n var hours = minutes * 60;\r\n var days = hours * 24;\r\n\r\n var d = Math.floor(gap/(days));\r\n var h = parseInt(Math.floor(gap % (days))/ (hours));\r\n var m = parseInt(Math.floor(gap % (hours))/ (minutes));\r\n var s = parseInt(Math.floor(gap % (minutes))/ (seconds));\r\n\r\n document.getElementById('day').innerText = d;\r\n document.getElementById('hour').innerText = h;\r\n document.getElementById('minute').innerText = m;\r\n document.getElementById('second').innerText = s;\r\n\r\n}", "function parseTimeRemaining() {\n\t\tvar seconds = timeRemaining;\n\t\tif (timeRemaining < 0) {\n\t\t\t// Avoid negatives, everything should be 0 at this point\n\t\t\tremainingDays = remainingHours = remainingMinutes = remainingSeconds = 0;\n\t\t} else {\n\t\t\t// Days\n\t\t\tremainingDays = Math.floor(seconds / 86400);\n\t\t\tseconds -= (remainingDays * 86400);\n\t\t\t// Hours\n\t\t\tremainingHours = Math.floor(seconds / 3600);\n\t\t\tseconds -= (remainingHours * 3600);\n\t\t\t// Minutes\n\t\t\tremainingMinutes = Math.floor(seconds / 60);\n\t\t\tseconds -= (remainingMinutes * 60);\n\t\t\t// Seconds\n\t\t\tremainingSeconds = Math.round(seconds);\n\t\t}\n\t}", "getRemainingSecs() {\n return Math.floor(this.getRemaining() / 1000) + 1;\n }", "function extraer_tiempototal(horaini, horaact) {\n var diff;\n\n var fecha1 = horaini.substring(6, horaini.length - 2);\n var fecha2 = horaact.substring(6, horaini.length - 2);\n\n diff = fecha2 - fecha1;\n // calcular la diferencia en segundos\n var diffSegundos = Math.abs(diff / 1000);\n\n\n // calcular la diferencia en minutos\n var diffMinutos = Math.abs(diff / (60 * 1000));\n\n var restominutos = diffMinutos % 60;\n\n // calcular la diferencia en horas\n var diffHoras = (diff / (60 * 60 * 1000));\n\n // calcular la diferencia en dias\n var diffdias = Math.abs(diff / (24 * 60 * 60 * 1000));\n\n //console.log(\"En segundos: \" + diffSegundos + \" segundos.\");\n //console.log(\"En minutos: \" + diffMinutos + \" minutos.\");\n //console.log(\"En horas: \" + diffHoras + \" horas.\");\n //console.log(\"En dias: \" + diffdias + \" dias.\");\n\n var devolver = parseInt(diffHoras) + \"H \" + Math.round(restominutos) + \"m \";\n //console.log(devolver)\n\n var tiempototal = Math.round((parseInt(diffHoras) * 60) + restominutos);\n\n //console.log(tiempototal);\n\n return tiempototal;\n\n}", "function getHours() {\n return theDate.getHours();\n }", "calcTime() {\n const numIng = this.ingredients.length;\n const periods = Math.ceil(numIng/3);\n this.time = periods * 15;\n }", "function remainingTime(seconds) {\n var result = \"\";\n var minutes = \"\";\n var sec = \"\";\n if (!isNaN(seconds)) {\n minutes = \"\" + parseInt(seconds/60);\n if (seconds%60 === 0) {\n sec = \"00\";\n } else {\n var tmpS = seconds - parseInt(minutes)*60;\n if (tmpS < 10) {\n tmpS = \"0\" + tmpS; \n }\n sec = \"\" + tmpS;\n } \n }\n result = minutes + \":\" + sec;\n return result;\n}", "get_respawn_time ()\n {\n let num_nearby = loot.players_in_cells[this.cell.x][this.cell.y].length;\n const adjacent_cells = loot.cell.GetAdjacentCells(this.cell.x, this.cell.y);\n\n // Get number of players near the lootbox\n for (let i = 0; i < adjacent_cells.length; i++)\n {\n num_nearby += loot.players_in_cells[adjacent_cells[i].x][adjacent_cells[i].y].length;\n }\n\n\n return Math.max(loot.config.respawn_times[this.type] / 2, loot.config.respawn_times[this.type] - (num_nearby * this.type * 0.5));\n }", "function getCurrentHour() {\n var currentHour = dayjs().hour(); //day.js\n\n $(\".time-block\").each(function () { //jquery\n var hourOfWorkTime = parseInt($(this).attr(\"id\").split(\"timehour-\")[1]); \n\n if (hourOfWorkTime < currentHour) {\n $(this).addClass(\"past\");\n }\n else if (hourOfWorkTime === currentHour) {\n $(this).removeClass(\"past\");\n $(this).addClass(\"present\");\n }\n else {\n $(this).removeClass(\"past\");\n $(this).removeClass(\"present\");\n $(this).addClass(\"future\");\n }\n })\n }", "getHoursSegment(value) {\n if (this.amPm) {\n if (value === HOURS_OF_NOON && this.isAM()) {\n value = 0;\n }\n if (this.isPM() && value < HOURS_OF_NOON) {\n value += HOURS_OF_NOON;\n }\n }\n return value;\n }", "function calculateTotalTimeSpentToday(){\n\tvar l = Projects.length;\n\tfor(i=0;i<l;i++){\n\t\ttotalTimeSpentToday += Projects[i].timeSpentToday;\n\t\t\n\t\t//Calculate totalOvertimeSpentToday\n\t\tif(Projects[i].timeSpentToday > Projects[i].suggestedAmountToday){\n\t\t\ttotalOvertimeSpentToday += Projects[i].timeSpentToday - Projects[i].suggestedAmountToday;\n\t\t}\n\t}\n\t\n\n\t\n\tvar theDay = today.getDay();\n\tswitch(theDay) {\n\t case 0: var initialCapacity = U.profiles[Profile].workSchedule.su; break;\n\t\tcase 1: var initialCapacity = U.profiles[Profile].workSchedule.mo; break;\n\t\tcase 2: var initialCapacity = U.profiles[Profile].workSchedule.tu; break;\n\t\tcase 3: var initialCapacity = U.profiles[Profile].workSchedule.we; break;\n\t\tcase 4: var initialCapacity = U.profiles[Profile].workSchedule.th; break;\n\t\tcase 5: var initialCapacity = U.profiles[Profile].workSchedule.fr; break;\n\t\tcase 6: var initialCapacity = U.profiles[Profile].workSchedule.sa; break;\n\t default:console.log(\"TIMEPOSITIVE ERROR: Unable to determine initialCapacity.\")\n\t}\n\t\n\tvar timeLeftToday = initialCapacity - totalTimeSpentToday;\n\t//console.log(\"TIME SPENT TODAY: \" + totalTimeSpentToday);\n\t\n\tif(timeLeftToday < 0){\n\t\t//Do something if you have worked extra time today\n\t\tconsole.log(\"You worked bonus time today! Bonus: \" + (timeLeftToday * -1));\n\t}\n}", "function eachHour() {\n var minutesLeft = moment().format('mm');\n var timeLeft = (60 - minutesLeft) * 1000;\n setTimeout(setInterval(checkHour, (1000 * 60 * 60)), timeLeft);\n}", "function calculateHours(seconds) {\n return Math.floor(seconds / 3600) % 24;\n}", "function timeDurationSubtract30(timeString){\t\n\tvar min = parseInt(timeString.substring(timeString.length-3,timeString.length-1));\n\tvar hour = parseInt(timeString.substring(0,timeString.length-4));\n\n\t\tif(!(min==0&hour==0)){\n\t\t\tif(min==0){\n\t\t\t\thour --;\n\t\t\t\tmin = 30;\n\t\t\t} else if (min==30){\n\t\t\t\tmin = \"00\"\n\t\t\t}else{\n\t\t\t\t\n\t\t\t\tif(hour!=0){\n\t\t\t\t\thour = hour - 1;\n\t\t\t\t\tmin = min + 30;\n\t\t\t\t}\n\t\t\t\tmin = \"00\";\n\t\t\t}\n\t\t}\n\n\t\tif(min==0){\n\t\t\tresult = hour+\":00h\";\n\t\t}else {\n\t\t\tresult = hour+\":\"+min+\"h\";\t\n\t\t}\n\treturn result;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancel all scheduled events greater than or equal to the given time
cancel(time) { this._event.cancel(time); return this; }
[ "cancel(time) {\n time = (0, _Defaults.defaultArg)(time, -Infinity);\n const ticks = this.toTicks(time);\n\n this._state.forEachFrom(ticks, event => {\n this.context.transport.clear(event.id);\n });\n\n this._state.cancel(ticks);\n\n return this;\n }", "function Sequence$cancel(){\n\t cancel();\n\t action && action.cancel();\n\t while(it = nextHot()) it.cancel();\n\t }", "cancelCronjob(cronjob) {\n let attrs = ['ebayID', 'shopifyID', 'type', 'time', 'timeZone'];\n let helperComp = (a, b) => {\n for (let i = 0; i < attrs.length; i++) {\n if (a[attrs[i]] != b[attrs[i]]) return false;\n }\n return true;\n };\n let matchedJobs = this.cronjobs.filter((managedCron) => {\n return helperComp(cronjob, managedCron);\n });\n let promises = matchedJobs.map((matchedJob) => {\n return redisClient.delAsync(`cronjob:${matchedJob.ebayID}:${matchedJob.shopifyID}:${matchedJob.type}`).then((res) => {\n matchedJob.job.stop();\n return `cronjob ${matchedJob.type} for ${matchedJob.ebayID} and ${matchedJob.shopifyID} cancelled`;\n })\n });\n return Promise.all(promises)\n .then((msg) => {\n for (let j = this.cronjobs.length - 1; j >= 0; j--) {\n if (helperComp(this.cronjobs[j], cronjob)) this.cronjobs.splice(j, 1);\n }\n return `cronjobs cancelled`;\n })\n }", "function cancelAlarm() {\n chrome.alarms.clear(alarmName);\n chrome.browserAction.setBadgeText({\n text: ''\n });\n chrome.notifications.create('reminder', {\n type: 'basic',\n iconUrl: 'img/icon_128.png',\n title: 'Info:',\n message: 'Die Erinnerungen sind jetzt deaktiviert!'\n }, function(notificationId) {});\n\n document.getElementById('delayInMinutes').value = '';\n }", "function listenForCancel() {\n findCancelButton().addEventListener('click', function() {\n if (queueTicket) {\n queueTicket.cancel();\n } else {\n throw new Error('Cannot cancel queuing while not queued');\n }\n });\n}", "cancel(__preserveTimer) {\n if (this.nextSignal) clearTimeout(this.nextSignal);\n\n if (!this.overrideKickedIn) {\n clearTimeout(this.overrideTrigger);\n if (!__preserveTimer) {\n if (this.signalHandler) this.signalHandler(this.totalSignalCount-1);\n TaskTimer.__forget__(this);\n }\n }\n }", "cancelAutoClose() {\n var button = this.getJQueryObject().find(\".timeout\");\n\n if(this.timeout != null) {\n button.hide();\n clearInterval(this.timeout);\n }\n }", "function handle_bp_cancel_scheduled_payment(req, startTime, apiName, callFrom) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\tthis.callFrom = callFrom;\n}", "deleteAppointment(date,time)\n {\n if (this.map.has(date)) {\n\n for (let i=0; i<this.map.get(date).length; i++)\n {\n if (this.map.get(date)[i].date == date && this.map.get(date)[i].time == time) {\n this.map.get(date).splice(i,1);\n break;\n }\n }\n }\n }", "function cancel(id) {\n\n var execItem = execData[id];\n\n if (execItem && execItem.state == 'waiting') {\n clearTimeout(execItem.timeoutID);\n execItem.timeoutID = 0;\n execItem.state = 'cancelled';\n }\n\n return this;\n }", "cancelScan() {\n if (this.scanCancelled_) {\n return;\n }\n this.scanCancelled_ = true;\n if (this.scanner_) {\n this.scanner_.cancel();\n }\n\n this.onScanFinished_();\n\n this.processNewEntriesQueue_.cancel();\n dispatchSimpleEvent(this, 'scan-cancelled');\n }", "checkStartTimes() {\n if (Object.keys(this.startTimes).length > 0) { // Are there any startTimes to check?\n let thisDate = new Date();\n for (var i=0, keys=Object.keys(this.startTimes); i < keys.length; i++) {\n let startDate = this.startTimes[keys[i]], endDate = this.endTimes[keys[i]];\n if (!this.groupStatus[keys[i]].collecting) { // Is the group already collecting then skip check.\n if (thisDate > startDate && (!endDate || (endDate && startDate < endDate)) ) this.toggle(keys[i]);\n } else { // Group is collecting and has a start time so check end time\n if (!endDate) { delete this.startTimes[keys[i]]; delete this.endTimes[keys[i]]; }\n else if (endDate && endDate < thisDate) { this.toggle(keys[i]); delete this.startTimes[keys[i]]; delete this.endTimes[keys[i]]; }\n }\n startDate = null; endDate = null;\n }\n thisDate = null;\n }\n }", "function cancelQuery() {\n if (cwQueryService.currentQueryRequest != null) {\n var queryInFly = mnPendingQueryKeeper.getQueryInFly(cwQueryService.currentQueryRequest);\n queryInFly && queryInFly.canceler(\"test\");\n\n // prepare cancel request\n var queryIdParam = cwConstantsService.queryIdParam + \"=\" + cwQueryService.currentQueryRequestID;\n var cancelQueryRequest = {\n url: cwConstantsService.canelQueryURL + \"?\" + queryIdParam,\n method: \"DELETE\"\n };\n\n // submit request\n $http(cancelQueryRequest)\n .then(function success(resp) {\n },\n function error(resp) {\n logWorkbenchError(\"Error cancelling query: \" + JSON.stringif(resp));\n });\n }\n }", "cancelFadeAll() {\n\t\tconst _fades = this._fades;\n\t\twhile (_fades.length > 0) {\n\t\t\tconst fade = _fades.shift();\n\t\t\tclearInterval(fade);\n\t\t}\n\t}", "function cancel() {\n if (parentPort) {\n parentPort.postMessage('Email analytics fetch-latest job cancelled before completion');\n parentPort.postMessage('cancelled');\n } else {\n setTimeout(() => {\n process.exit(0);\n }, 1000);\n }\n}", "function auto_remove_sanction() {\n if (timeout != null) client.clearTimeout(timeout);\n db.query(\"SELECT id, serveur_id FROM sanction WHERE date + duration *interval'1 second' < now()\")\n .then( res => {\n // retirer toutes les sanctions terminées\n for (let i=0 ; i<res.rowCount ; i++) {\n let id = res.rows[i].id;\n let guild = client.guilds.get(res.rows[i].serveur_id);\n require('./command/cancel')(['', id], guild, null, null, '!cancel '+id, null, null);\n }\n\n // set timeout before cancel next sanction\n return db.query(\"SELECT EXTRACT(EPOCH FROM date + duration *interval'1 second' -now()) AS delay FROM sanction WHERE duration IS NOT NULL ORDER BY (date + duration *interval'1 second') DESC LIMIT 1;\");\n })\n .then( res => {\n if (res.rowCount == 1)\n timeout = client.setTimeout(auto_remove_sanction, res.rows[0].delay);\n })\n .catch( err => {\n console.log(\"============= TimeOut Error =============\");\n console.log(err);\n timeout = client.setTimeout(auto_remove_sanction, 5000); // on error wait 5 sec and redo it..\n });\n}", "#removeExpiredTimestamps(key) {\n const timestampsArray = this.#apiCallTimeStamps[key]\n const now = Date.now()\n const oneMinuteAgo = now - 1000\n let index = 0\n while (index < timestampsArray.length && timestampsArray[index] <= oneMinuteAgo) {\n index += 1\n }\n\n timestampsArray.splice(0, index)\n }", "function removeSchedule() {\r\n var $clickedEvent = $(\".fc-event-clicked\");\r\n if ($clickedEvent.length) { // Ensure event to remove has been clicked\r\n $removeScheduleBtn.css(\"display\", \"none\");\r\n $removeBtnConfirmContainer.css(\"display\", \"block\");\r\n }\r\n }", "function cancelChallenge() {\n challengesService.getActiveChallengeByCompetitionByPlayer(vm.competitionId, vm.currentUserPlayer._id).then(function (challenge) {\n if (challenge.data) {\n // Allow the challenger to cancel the challenge\n if (challenge.data.challenger._id === vm.currentUserPlayer._id) {\n challengesService.cancelPyramidChallenge(challenge.data).then(function () {\n vm.hasActiveChallenge = false;\n });\n }\n }\n });\n }", "cancel() {\n\t\tthis.reconciling = false;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retrieves the list of Datastreams of all registered Servers
loadDataStreamList() { this._dataStreamList = []; let servers = this.dataModelProxy.getUserConfig().getDashboardConfig().getServerList(); let serverID = 0; for (let server in servers) { if (logging) console.log("Retrieving Datastreams from Server:", servers[server].url); let sID = serverID; let cb = function(a) { this.dataStreamListAvailable(a, sID); }; this.sensorThingsCommunications.getDataStreamList(servers[server].url, cb.bind(this)); serverID++; } }
[ "function getAllStreamers() {\r\n clearElements();\r\n getStreamData(\"all\");\r\n }", "function getOfflineStreamers() {\r\n clearElements();\r\n getStreamData(\"offline\");\r\n }", "listSockets() {\n var list = this.players.map(player => player.socketID);\n list.push(this.hostID);\n return list;\n }", "getSystemStreamsList () {\n if (!SystemStreamsSerializer.systemStreamsList) {\n let systemStreams = [];\n let i;\n const streamKeys = Object.keys(this.systemStreamsSettings);\n\n for (i = 0; i < streamKeys.length; i++) {\n systemStreams.push({\n name: streamKeys[i],\n id: SystemStreamsSerializer.addDotToStreamId(streamKeys[i]),\n parentId: null,\n children: buildSystemStreamsFromSettings(\n this.systemStreamsSettings[streamKeys[i]],\n [],\n SystemStreamsSerializer.addDotToStreamId(streamKeys[i])\n )\n });\n }\n SystemStreamsSerializer.systemStreamsList = systemStreams;\n }\n return SystemStreamsSerializer.systemStreamsList;\n }", "function getAllStreamersData(streamerList, onOfforAll) {\n streamerList.forEach(function(streamer) {\n var url = \"https://wind-bow.glitch.me/twitch-api/streams/\" + streamer;\n var request = new XMLHttpRequest();\n request.onload = function () {\n if (request.status == 200) {\n resultsObject = JSON.parse(request.responseText);\n if (resultsObject.stream == null && onOfforAll != \"onlineOnly\") {\n displayOfflineUsers(resultsObject, streamer);\n } else if (onOfforAll != \"offlineOnly\") {\n displayOnlineStreamers(resultsObject);\n }\n }\n };\n request.open(\"GET\", url);\n request.send(null);\n });\n}", "function getLogsFromServer() {\n if (!$scope.logs) return;\n\n var logs = $scope.logs;\n var len = logs.length;\n for (var i = 0; i < len; i++) {\n getLog(logs[i]);\n }\n }", "getConnects() {\n var result = [];\n for (var i = 0; i < this.connectionList.length; i++) {\n result.push(this.connectionList[i]);\n }\n return result;\n }", "static getAllAccountStreams () {\n if (!SystemStreamsSerializer.allAccountStreams) {\n SystemStreamsSerializer.allAccountStreams = getStreamsNames(SystemStreamsSerializer.getAccountStreamsConfig(), allAccountStreams);\n }\n return SystemStreamsSerializer.allAccountStreams;\n }", "function getOnlineRservers(){\n\tvar sql = \"SELECT rserver_id,ip_address,port,state FROM info_rserver where state = 1\";\n\tvar rservers = [];\n\texecuteSql(sql, null, \n\t\tfunction(rows){\n\t\t\tif(rows) rservers.push(rows);\n\t\t}, \n\t\tfunction(err){\n\t\t\tconsole.log(\"Error: failed when get online rservers, \" + err);\n\t\t}\n\t);\n\treturn rservers;\n}", "getAllSystemStreamsIds () {\n if (!SystemStreamsSerializer.allSystemStreamsIds) {\n let systemStreams = [];\n let i;\n const streamKeys = Object.keys(this.systemStreamsSettings);\n\n for (i = 0; i < streamKeys.length; i++) {\n systemStreams.push(SystemStreamsSerializer.addDotToStreamId(streamKeys[i]));\n _.merge(systemStreams,\n Object.keys(getStreamsNames(this.systemStreamsSettings[streamKeys[i]])))\n }\n SystemStreamsSerializer.allSystemStreamsIds = systemStreams;\n }\n return SystemStreamsSerializer.allSystemStreamsIds;\n }", "function collectstorm(){\n var URL = 'http://138.197.175.19:3000/stats_dfs';\n\n request.get(URL, function(err, resp, body){\n if(!err && resp.statusCode == 200){\n //convert data to json\n var data = JSON.parse(body);\n stormdata.push(data);\n }\n })\n //console.log(stormdata);\n}", "static async listStations(req, res) {\n const stations = await Station.retrieve();\n return res.json(stations);\n }", "function listDatabases() {\n mongoDatabase(function (client) {\n const adminDb = client.db().admin();\n\n adminDb.listDatabases({ nameOnly: false }, function (err, results) {\n console.log(results);\n client.close();\n });\n })\n}", "function getOfflineRservers(){\n\tvar sql = \"SELECT rserver_id,ip_address,port,state FROM info_rserver where state <> 1\";\n\tvar rservers = [];\n\texecuteSql(sql, null, \n\t\tfunction(rows){\n\t\t\tif(rows) rservers.push(rows);\n\t\t}, \n\t\tfunction(err){\n\t\t\tconsole.log(\"Error: failed when get offline rservers, \" + err);\n\t\t}\n\t);\n\treturn rservers;\n}", "function getAllPlayers() {\n var players = [];\n\n Object.keys(io.sockets.connected).forEach(function(socketId) {\n var player = io.sockets.connected[socketId].player;\n\n if (player) {\n players.push(player);\n }\n });\n\n return players;\n}", "function getFlows (socket) {\n\n\treturn (data) => {\n\n\t\tUDPServer.send(JSON.stringify({ event : 'GET_FLOWS_MONITOR', data : [] }), 6000, '127.0.0.1')\n\t}\n}", "broadcastPlayerList() {\n var response = [];\n // prepare the data\n this._players.forEach(p => {\n response.push(p.getPublicInfo());\n });\n // Send to all users\n this.emitToRoom(\"player-list\", response);\n }", "function getStationsToArray() {\n fetch('https://rata.digitraffic.fi/api/v1/metadata/stations')\n .then((response) => response.json())\n .then(function (response) {\n return response.map(function (data) {\n stations.push(data.stationName);\n stationShorts.push(data.stationShortCode);\n })\n })\n .then(renderDatalist)\n}", "getMonitoring(guildId) {\r\n listOfChannels = [];\r\n\r\n for (const key in TIMEOUT_MAP) {\r\n if (TIMEOUT_MAP[key].guildId === message.guild.id) {\r\n listOfChannels.push(TIMEOUT_MAP[KEY].channelName);\r\n }\r\n }\r\n\r\n return listOfChannels;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to hide the popup TBI
function hide_popup() { $('.overlay').hide(); $("#tooltip").toggle(); }
[ "function hidePopup() {\n // get the container which holds the variables\n var topicframe = findFrame(top, 'topic');\n\n if (topicframe != null) {\n if (topicframe.openedpopup != 1) {\n if ((topicframe.openpopupid != '') && (topicframe.popupdocument != null)) {\n var elmt = topicframe.popupdocument.getElementById(topicframe.openpopupid);\n if (elmt != null) {\n elmt.style.visibility = 'hidden';\n }\n openpopupid = '';\n }\n }\n\n openedpopup = 0;\n }\n}", "function close_popup(popup) {\r\n popup.style.display = \"none\";\r\n}", "function hidePopup () {\n $('#popup').css('z-index', -20000);\n $('#popup').hide();\n $('#popup .popup-title').text('');\n $('#popup .popup-content').text('');\n $('.hide-container').hide();\n $('.container').css('background', '#FAFAFA');\n }", "function hidePopup () {\r\n editor.popups.hide('customPlugin.popup');\r\n }", "function closePopUp() {\n document.getElementById(\"loggerModalWrapper\").style.display = \"none\";\n }", "function hideResultModal() {\n\tvar modal = $('#popup-window');\n modal.css('display', 'none');\n}", "function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }", "function _hidePopup(event) {\n if ($reverseNameResolver.css('display') != 'none') {\n $reverseNameResolver.fadeOut(300);\n }\n }", "function CloseBubble()\r\n{\r\n\tdocument.getElementById(\"bubble_main\").style.visibility = \"hidden\";\r\n}", "function hide_global_supplier_settings()\n{\n\t//Empty the html \n\t$(\"#sup_list_view_global\").html(\"\");\n\t//Hide the modal box \n\t$('.overlay').hide(); \n\t$('#setng_supplier_global').hide();\n\t//Nothing else to be done \n}", "function hidePopup() {\n $('#transparented').hide();\n $('#popup').hide();\n $(\"#typebox > textarea\").removeProp(\"disabled\");\n $(\"#typebox > textarea\").focus();\n}", "function hideImagePopup(){\n\tdocument.getElementById('popupImage').style.visibility = \"hidden\";\n}", "function participants_view_hide() {\n\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"rgba(0,0,0,.2)\";\n\tsetTimeout(function() {\n\t\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"transparent\";\n\t\tparticipants_view_visible = false;\n\t\tDOM(\"PARTICIPANTS_VIEW\").style.top = \"-100%\";\n\t\tsetTimeout(function() {\n\t\t\tDOM(\"PARTICIPANTS_VIEW\").style.display = \"none\";\n\t\t}, 500);\n\t}, 50);\n}", "function closeEditGroupPopup(){\n\t$(\".tag-manage-outer\").css(\"display\",\"none\");\n}", "function hideSettings() {\n $(\"#searchOptionsBox\").removeClass(\"visible\");\n zdPage.modalHidden();\n // Re-enable tooltip, unless we have a touch screen\n if (!zdPage.isTouch()) $(\".btnSettings\").tooltipster('enable');\n }", "hideVisit() {\n\t\tthis.modalContainer.classList.remove(\"visible\");\n\t}", "function closeTicket(id) {\n document.getElementById(id).style.display = \"none\";\n\n\n }", "function ViewerToolsHide() {\r\n if( G.VOM.viewerDisplayed ) {\r\n G.VOM.toolbarsDisplayed=false;\r\n ViewerToolsOpacity(0);\r\n }\r\n }", "function hideCreateDialog() {\n if (document.getElementById('editID').value != '-1') {\n $('#rfelement' + document.getElementById('editID').value).show();\n document.getElementById('editID').value = '-1';\n }\n $('#textarea_preview').hide();\n $('#singlechoice_preview').hide();\n $('#multiplechoice_preview').hide();\n $('#matrix_preview').hide();\n $('#grading_preview').hide();\n $('#tendency_preview').hide();\n $('#newquestion').hide();\n $('#text_preview').show();\n //$('#newquestion_button').show();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show traffic plot instead of switch config
handleSetTrafficView(o) { this.trafficPorts = o; this.showTraffic = true; }
[ "function enableChartView() {\n for (let element of defaultViewElements) element.style.display = \"none\";\n for (let element of chartViewElements) element.style.display = \"block\";\n }", "function set_display(value)\n{\n\t//value can be: wireframe, hiddenvis, hiddeninvis, or shade //\n\tenv_stat=document.wm.pwlConfigoptSet('display', value);\n}", "function Network_networkOverview() {\n UCapManager.startScheduler({func:'Network_Overview_householdUsage', scope:\"element\", freq:1000});\n var dataArray = [];\n for (var i in UCapCore.devices)\n { for(var j = 0, k = UCapCore.devices[i].length; j < k; j++){\n var devicename = UCapCore.devices[i][j][1];\n var deviceusage = (UCapCore.devices[i][j][6]/1048576);\n dataArray.push([devicename,deviceusage]);\n }\n }\n UCapViz.drawChart({tar:'chartarea',data:dataArray});\n}", "function visualize() {\n\n visualizer.updatePitchChart(audioProcessor.getPitches(), audioProcessor.getTimestamps());\n visualizer.updateRateChart(audioProcessor.getVibratoRates(), audioProcessor.getTimestamps());\n visualizer.updateWidthChart(audioProcessor.getVibratoWidths(), audioProcessor.getTimestamps());\n calcPitch();\n}", "function drawTrafficFlowPopup(panelId) {\n document.getElementById('traffic_table_' + panelId).style.display = 'block';\n}", "function showViz() {\n viz.show();\n}", "function displayGraph(loanName) {\n let visuals = $(\".uiVisualizer\");\n visuals.each(function(index) {\n visuals[index].style.display = \"none\";\n });\n\n let prefix = null;\n switch (LoanM8.activeComponent) {\n case \"loanPaymentsGraphs\":\n prefix = \"payments-graph-\";\n break;\n case \"loanLifetimeTotalsGraphs\":\n prefix = \"lifetime-totals-graph-\";\n break;\n case \"loanLifetimeTotalsTables\":\n prefix = \"lifetime-totals-table-\";\n break;\n default:\n prefix = \"payments-graph-\";\n break;\n }\n id = prefix + loanName;\n document.getElementById(id).style.display = \"inline-block\";\n LoanM8.activeLoan = loanName;\n}", "function initPingChart() {\n\n smoothie = new SmoothieChart({\n grid: {\n lineWidth: 1,\n millisPerLine: 0,\n verticalSections: 6\n },\n minValue: 0\n });\n\n line = new TimeSeries();\n\n target = \"google.com\";\n\n smoothie.addTimeSeries(line, { lineWidth: 2, strokeStyle: '#00ff00', fillStyle: 'rgba(0,128,0,0.30)' });\n\n smoothie.streamTo(document.getElementById(\"pingCanvas0\"), 500);\n\n // Sending first ping request to back-end\n ipcRenderer.send('asynchronous-message', {\n type: 'ping',\n target: target\n });\n}", "function renderChart() {\n requestAnimationFrame(renderChart);\n\n analyser.getByteFrequencyData(frequencyData);\n\n if(colorToggle == 1){\n //Transition the hexagon colors\n svg.selectAll(\".hexagon\")\n .style(\"fill\", function (d,i) { return colorScaleRainbow(colorInterpolateRainbow(frequencyData[i])); })\n }\n\n if(colorToggle == 2){\n //Transition the hexagon colors\n svg.selectAll(\".hexagon\")\n .style(\"fill\", function (d,i) { return colorScaleGray(colorInterpolateGray(frequencyData[i])); })\n }\n }", "function renderVizMoreOptions() {\n\n // Define variables for viz\n var mainVizDiv = $(\"#tableauViz\");\n var mainVizOptions = {\n hideTabs: false,\n hideToolbar: false,\n //toolbarPositon: top, // (or \"bottom\") \n width: 850,\n height: 860,\n //Filter Category field - note NO spaces between multiple filter values. Just a comma\n Category: \"Office Supplies,Furniture\",\n //Set Top Customers Parameter Value - note wrapping quotes around parameter name since it contains spaces\n \"Top Customers\": 22,\n onFirstInteractive: function () {\n mainWorkbook = mainViz.getWorkbook();\n }\n };\n // Create viz\n mainViz = new tableauSoftware.Viz(mainVizDiv[0], url, mainVizOptions);\n}", "function plot(can,ctx,x,y,xwidth,ywidth,options){\n\n}", "function setSwitch() {\r\n if (document.getElementById(\"rb5\").checked) {\r\n legend.switchType = \"x\";\r\n } else {\r\n legend.switchType = \"v\";\r\n }\r\n legend.validateNow();\r\n }", "function defaultVisualization() {\n const myNode = document.getElementById(\"chart_div\");\n myNode.innerHTML = '<p class=\"h2 m-4\" style=\"color: #cecece; text-align:center;\">Select a dataset / column / OA</p>';\n}", "show() {\n stroke(0);\n push();\n translate(this.pos.x, this.pos.y);\n rotate(this.heading);\n if (this.best == true) {\n image(bestcarImg, -this.w, -this.h / 4);\n } else image(carImg, -this.w, -this.h / 4);\n pop();\n\n if (showSensorsCheckBox.checked && !this.dead) {\n stroke(50);\n for (let i = 0; i < this.sensors.length; i++) {\n line(\n this.frontPos.x,\n this.frontPos.y,\n this.frontPos.x + cos(this.sensors[i] + this.heading) * this.sensorsLength[i],\n this.frontPos.y + sin(this.sensors[i] + this.heading) * this.sensorsLength[i]\n );\n }\n }\n }", "function drawGexpOverview(i) {\n \n //var gexp = getCol(dataPro,1).map(function(d) { return d.value })\n var gexp = getCol(dataPro,i)\n\n var g = document.getElementById('gexp_panel1'),\n\twindowWidth = g.clientWidth,\n\twindowHeight = g.clientHeight;\n\n var margin = {top: 30, right: 0, bottom: 30, left: 30},\n\twidth = windowWidth - margin.left - margin.right,\n\theight = windowHeight - margin.top - margin.bottom;\n \n var chart1;\n chart1 = makeDistroChart({\n\tdata: gexp,\n\txName:'name',\n\tyName:'value',\n//\taxisLabels: {xAxis: 'Gene', yAxis: 'Values'},\n\tselector:\"#gexp-chart-distro1\",\n\tsvg:\"gexp-chart-distro1-svg\", \n\tchartSize:{height:height, width:width},\n\tmargin:margin,\n\tconstrainExtremes:true});\n chart1.renderBoxPlot();\n chart1.renderDataPlots();\n chart1.renderNotchBoxes({showNotchBox:false});\n chart1.renderViolinPlot({showViolinPlot:false});\n\n var pt = document.getElementById(\"gexp_plottype\").value;\n if(pt == \"box_plot\") {\n\tchart1.boxPlots.show({reset:true});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"notched_box_plot\") {\n\tchart1.notchBoxes.show({reset:true});chart1.boxPlots.show({reset:true, showBox:false,showOutliers:true,boxWidth:20,scatterOutliers:true});chart1.violinPlots.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"violin_plot\") {\t \n\tchart1.violinPlots.show({reset:true, resolution:12});chart1.boxPlots.show({reset:true, showWhiskers:false,showOutliers:false,boxWidth:10,lineWidth:15,colors:['#555']});chart1.notchBoxes.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"bean_plot\") {\t \n\tchart1.violinPlots.show({reset:true, width:100, resolution:12});chart1.dataPlots.show({showBeanLines:true,beanWidth:15,showPlot:false,colors:['#555']});chart1.boxPlots.hide();chart1.notchBoxes.hide()\n }\n if(pt == \"beeswam_plot\") {\t \t \n\tchart1.dataPlots.show({showPlot:true, plotType:'beeswarm',showBeanLines:false, colors:null});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.boxPlots.hide();\n }\n if(pt == \"scatter_plot\") {\t \n\tchart1.dataPlots.show({showPlot:true, plotType:40, showBeanLines:false,colors:null});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.boxPlots.hide();\n }\n}", "function optionChanged(value) {\n console.log(value);\n updatePlotly(value);\n}", "function showAxis(axis) {\n g.select('.x.axis')\n .call(axis)\n .transition().duration(500)\n .style('opacity', 1);\n }", "showGrid(){\n this.Grid = true;\n this.Line = false\n \n }", "function plotBattery(options)\n{\n var $mycontainer = $(\".template-chart\").clone();\n $mycontainer.removeAttr(\"style\");\n $mycontainer.removeClass(\"template-chart\");\n options.outerElement.append($mycontainer);\n \n var chart = new Highcharts.Chart({\n\tchart: {\n\t renderTo: $mycontainer[0],\n\t type: 'area',\n\t animation: false,\n\t borderWidth: 1\n\t},\n\tcredits:{enabled:false},\n\tplotOptions: {\n\t column: {\n\t borderWidth :0\n\t }\n\t},\n\ttitle: {\n\t text: 'Battery Graph'\n\t},\n\txAxis: {\n\t type: 'datetime',\n\t dateTimeLabelFormats: {\n\t\thour: '%H:%M'\n\t }\n\t},\n\tyAxis: {\n\t min: 0,\n\t max: 100,\n\t labels:\n\t {\n\t\tenabled: true\n\t },\n\t title:\n\t {\n\t\tenabled: true,\n\t\ttext: 'Battery %'\n\t }\n\t},\n\t\n\tseries: [{\n\t name: 'Battery %',\n\t data: batteryArray\n\t}]\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turn the oscillator on / off
function toggleOsc() { if (oscOn) { osc.stop(); button.html('start'); } else { osc.start(); button.html('stop'); } oscOn = !oscOn; }
[ "controlViaOnOff() {\n console.log(\"entrou ONOFF\")\n this.output = this.getTemp() < this.setpoint ? 1023 : 0;\n this.board.pwmWrite(19 , 0, 25, 10, this.output);\n }", "function initOscillator(gain){\n\tvar o = context.createOscillator();\n\to.type = \"sine\"; // sine wave by default \n\to.connect(gain); \n\to.start(0);\n\treturn o;\n}", "function sustainOff() {\n echo = \"regular\";\n console.log('sustain off');\n }", "function changeWaveform(waveShape){\n oscillators.forEach(osc =>\n osc.type = waveShape)\n}", "toggle() {\n if (this._simulation.started)\n this.stop();\n else\n this.start();\n }", "function sustainOn() {\n echo = \"sustain\";\n console.log('sustain on');\n }", "toggleAudioEq() {\r\n this.setAudioEq(!this.audio.useEq);\r\n }", "startClock() {\r\n // Every millisecond, perform one cpu cycle\r\n this.clock = setInterval(() => this.tick(), 1); // 1 ms delay == 1 KHz clock == 0.000001 GHz\r\n\r\n // Fire interrupt timer at a cycle of once per second\r\n this.interrupt = setInterval(() => this.reg[IS] |= 1, 1000); // every second, set the bit 0 of IS to 1\r\n }", "setUp(options){\n this.setUpDeviceListeners(undefined, this.onOSCMessage);\n this.setUpDevice({ osc: options });\n }", "function powerOff() {\n setVisible(powerOffButton, false);\n setVisible(powerOnButton, true);\n if (fmRadio.isPlaying()) {\n fmRadio.stop();\n }\n saveCurrentStation();\n saveVolume();\n }", "function stubOscillator(service, oscillator) {\n const oscillatorDouble = replace(service, '_createOscillator');\n when(oscillatorDouble()).thenReturn(oscillator);\n}", "function powerOn() {\n sendPowerCommand('on');\n}", "toggle() {\n Mousetrap[(this.paused ? 'unpause' : 'pause')]();\n this.paused = !this.paused;\n }", "constructor () {\r\n this.context = new AudioContext(); //AudioContext for Oscillators to generate tones\r\n this.debug = false;\r\n this.duration = Piano2.DEFAULT_DURATION;\r\n this.toneType = Piano2.DEFAULT_TONE;\r\n }", "function turnOn() {\n transform.GetChild(0).active = true;\n GetComponent(SphereCollider).enabled = true;\n on = true;\n}", "function toggleSwitch(number) {\n setIsEnabled(!isEnabled);\n }", "ecoOn() {\n this._ecoMode(\"eco_on\");\n }", "toggleMusic() {\n this.musicOn = !this.musicOn;\n let w = '', f = '';\n if (this.musicOn) {\n this.playMusic(this.playingMusic);\n w = 'on';\n f = 'On';\n }\n else {\n this.disableMusic();\n w = 'off';\n f = 'Off';\n }\n this.ecs.getSystem(System.GUIManager).runSequence('notification', new Map([['notification', 'music ' + w]]), new Map([['notification', 'HUD/music' + f]]));\n }", "function powerOn(){\n \n if(!ship.powerOn) ship.powerOn = true; \n}", "enable() {\n const eqs = this.equations;\n for (let i = 0; i < eqs.length; i++) {\n eqs[i].enabled = true;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update info card item
updateInfoCard(stepId, action, key, value, index) { var data = {}; data['update_type'] = 'card_item'; data['type'] = 'info-card'; data['_id'] = stepId; data['action'] = action; data['index'] = index; data[key] = value; //console.log(data) this.stepService.update(this.botId, stepId, data).subscribe(res => { if (res.status === 200) { this.getStep(this.block); } else { this._snackBar.open('Thao tác không thành công', 'OK', { duration: 1000 }); } }); }
[ "updateInfo(key, newValue) {\n let info = this.props.info;\n info[key] = newValue;\n this.props.updateShipInfo(info);\n }", "updateFormCard(stepId, action, key, value, index) {\n var data = {};\n data['update_type'] = 'card_item';\n data['type'] = 'form-card';\n data['_id'] = stepId;\n data['action'] = action;\n data['index'] = index;\n data[key] = value;\n this.stepService.update(this.botId, stepId, data).subscribe(res => {\n if (res.status === 200) {\n this.getStep(this.block);\n }\n else {\n this._snackBar.open('Thao tác không thành công', 'OK', {\n duration: 1000\n });\n }\n });\n }", "updateProductCard(stepId, action, key, value, index) {\n var data = {};\n data['update_type'] = 'card_item';\n data['type'] = 'product-card';\n data['_id'] = stepId;\n data['action'] = action;\n data['index'] = index;\n data[key] = value;\n //console.log(data)\n this.stepService.update(this.botId, stepId, data).subscribe(res => {\n if (res.status === 200) {\n this.getStep(this.block);\n }\n else {\n this._snackBar.open('Thao tác không thành công', 'OK', {\n duration: 1000\n });\n }\n });\n }", "function editCard(card_id) {\n // console.log(\"id received\" + card_id);\n loadValues(card_id);\n}", "function editCard({ signal }) {\n const newCard = {\n ...objToModify,\n front: formData.front,\n back: formData.back,\n };\n updateCard(newCard, signal).then(() => updateDecks(signal));\n }", "updateSupportCard(stepId, value) {\n var data = {};\n data['update_type'] = 'card_item';\n data['type'] = 'support-card';\n data['_id'] = stepId;\n data['content'] = value;\n this.stepService.update(this.botId, stepId, data).subscribe(res => {\n if (res.status === 200) {\n this.getStep(this.block);\n }\n else {\n this._snackBar.open('Thao tác không thành công', 'OK', {\n duration: 1000\n });\n }\n });\n }", "updatePhoneCard(stepId, action, key, value) {\n var data = {};\n data['update_type'] = 'card_item';\n data['type'] = 'phone-card';\n data['_id'] = stepId;\n data['action'] = action;\n data[key] = value;\n //console.log(data)\n this.stepService.update(this.botId, stepId, data).subscribe(res => {\n if (res.status === 200) {\n this.getStep(this.block);\n }\n else {\n this._snackBar.open('Thao tác không thành công', 'OK', {\n duration: 1000\n });\n }\n });\n }", "updateImageCard(stepId, action, key, value) {\n var data = {};\n data['update_type'] = 'card_item';\n data['type'] = 'image-card';\n data['_id'] = stepId;\n data['action'] = action;\n data[key] = value;\n //console.log(data)\n this.stepService.update(this.botId, stepId, data).subscribe(res => {\n if (res.status === 200) {\n this.getStep(this.block);\n }\n else {\n this._snackBar.open('Thao tác không thành công', 'OK', {\n duration: 1000\n });\n }\n });\n }", "updateGotoCard(stepId, action, key, value) {\n var data = {};\n data['update_type'] = 'card_item';\n data['type'] = 'go-to-card';\n data['_id'] = stepId;\n data['action'] = action;\n data[key] = value;\n //console.log(data)\n this.stepService.update(this.botId, stepId, data).subscribe(res => {\n if (res.status === 200) {\n this.getStep(this.block);\n }\n else {\n this._snackBar.open('Thao tác không thành công', 'OK', {\n duration: 1000\n });\n }\n });\n }", "updateWeaponPlayerInfo() {\n let playerWeaponInfoImg = $(\"#\"+this.name+\"-weapon-img\");\n let playerWeaponInfoValue = $(\"#\"+this.name+\"-weapon-value\");\n $('#'+playerWeaponInfoImg.attr('id')).removeClass(\"player-infos__\"+this.previousWeapon).addClass(\"player-infos__\"+this.weapon.weapon);\n $('#'+playerWeaponInfoValue.attr('id')).text(this.weapon.name);\n }", "function updateItem(){\n\t//Update itemList total item left information\n\t$('#options-num').text(function() {\n\t\tvar n = $(\".list-container li.sl-item\").length;\n\t\treturn \"n\";\n\t});\n\t$('#template-num').text(function() {\n\t\tvar n = $(\".list-template li.sl-item\").length;\n\t\treturn \"n\";\n\t});\n}", "updateSurveyCard(stepId, action, key, value) {\n var data = {};\n data['update_type'] = 'card_item';\n data['type'] = 'survey-card';\n data['_id'] = stepId;\n data['action'] = action;\n data[key] = value;\n this.stepService.update(this.botId, stepId, data).subscribe(res => {\n if (res.status === 200) {\n this.getStep(this.block);\n }\n else {\n this._snackBar.open('Thao tác không thành công', 'OK', {\n duration: 1000\n });\n }\n });\n }", "function updateCart() {\n\tsaveFormChanges();\n\trenderCart();\n}", "function Update(card) {\n var dfd = $q.defer();\n var token = OrderCloud.Auth.ReadToken();\n var cc = {\n \"buyerID\": OrderCloud.BuyerID.Get(),\n \"orderID\": null,\n \"transactionType\": \"updateCreditCard\",\n \"amount\": null,\n \"cardDetails\": {\n \"paymentID\": null,\n \"cardNumber\": 'XXXX' + card.PartialAccountNumber,\n \"cardholderName\": card.CardholderName,\n \"creditCardID\": card.ID,\n \"cardType\": card.CardType,\n \"expirationDate\": card.ExpMonth + card.ExpYear\n }\n };\n $resource(authorizeneturl, {}, {authorize: {method: 'POST', headers: {'Authorization': 'Bearer ' + token, 'Content-type': 'application/json'}}}).authorize(cc).$promise\n .then(function(response){\n console.log(response);\n if((response.messages && response.messages.resultCode && response.messages.resultCode == 'Error')) {\n toastr.info('Sorry, something went wrong. Please try again');\n } else if(response.Error) {\n toastr.info('Sorry, something went wrong. Please try again');\n }\n else {\n toastr.success('Your card has been updated', 'Success');\n }\n dfd.resolve();\n })\n .catch(function(){\n toastr.info('Sorry, something went wrong. Please try again');\n dfd.resolve();\n });\n return dfd.promise;\n }", "function editEntry(ENTRY){\n // making entry the variable that represents the entry id which includes amount, name,type\n let entry = ENTRY_LIST[ENTRY.id];\n // if the entry type is an input, we are going to update the item name and cost in the input section\n if (entry.type == \"inputs\"){\n itemName.value = entry.title;\n itemCost.value = entry.amount;\n }\n // run the delete entry function again so you can delete the previous entry before you add a new edited entry\n deleteEntry(ENTRY);\n }", "function updateUiData(info){\n const {date , temp , feelings} = info;\n // update the date div \n dateEntry.innerHTML = \"Date: \" + date;\n\n // update the temp div \n tempEntry.innerHTML = \"Temp: \" + temp;\n\n // update the content entry \n content.innerHTML = \"Feelings: \" + feelings ;\n\n}", "updateSaves(id, saveText){\n let cards = this.components.filter((component) => component.constructor.name==\"Card\" && component.card.cardID == id);\n for(const card of cards){\n console.log(card.saveId);\n console.log(saveText);\n $(\"#\"+card.saveId).text(saveText);\n }\n\n }", "function checkCardsUpdated(){\n\n}", "function handle_cm_edit_payment_card(req, startTime, apiName, cardExpandBoxId, index) {\n this.req = req; this.startTime = startTime; this.apiName = apiName; this.cardExpandBoxId = cardExpandBoxId; this.index = index;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert value to signed 16 bit.
function s16(val) { return (val << 16) >> 16; }
[ "function clampToInt16(x) {\n return Math.max(Math.min(x, 32767), -32768);\n}", "static bytes16(v) { return b(v, 16); }", "function parseToSignedByte(value) {\n value = (value & 127) - (value & 128);\n return value;\n}", "function bigInt2hex(i){ return i.toString(16); }", "readUint16() {\n const value = this._data.getUint16(this.offset, this.littleEndian);\n\n this.offset += 2;\n return value;\n }", "function hex2u16(hex) {\r\n return parseInt( hex.substr(2,2)+hex.substr(0,2), 16);\r\n}", "function int16ToFloat32(inputArray) {\n\n let int16arr = new Int16Array(inputArray)\n var output = new Float32Array(int16arr.length);\n for (var i = 0; i < int16arr.length; i++) {\n var int = int16arr[i];\n var float = (int >= 0x8000) ? -(0x10000 - int) / 0x8000 : int / 0x7FFF;\n output[i] = float;\n }\n return output;\n }", "static ToHex(i) {\n const str = i.toString(16);\n if (i <= 15) {\n return ('0' + str).toUpperCase();\n }\n return str.toUpperCase();\n }", "function parseShort(str, base) {\r\n\tvar n = parseInt(str, base);\r\n\treturn (n << 16) >> 16;\r\n}", "static encodeFanSpeed(setvalue) {\n return (setvalue >= 0 && setvalue <= 8) ? (0x1 << setvalue) - 1 : 0;\n }", "function encodeSignedNumber_(num) {\n var sgn_num = num << 1;\n\n if (num < 0) {\n sgn_num = ~(sgn_num);\n }\n\n var encodeString = \"\";\n\n while (sgn_num >= 0x20) {\n encodeString += ALPHABET_.charAt(0x20 | (sgn_num & 0x1f));\n sgn_num >>= 5;\n }\n\n encodeString += ALPHABET_.charAt(sgn_num);\n return encodeString;\n }", "function Hex(n) {\n n=Math.round(n);\n if (n < 0) {\n n = 0xFFFFFFFF + n + 1;\n }\n return n.toString(16).toUpperCase();\n}", "function intToHex(integer){if(integer<0){throw new Error('Invalid integer as argument, must be unsigned!');}var hex=integer.toString(16);return hex.length%2?\"0\"+hex:hex;}", "function limitBitsNumber(value) {\r\n\r\n if (value > 32) {\r\n\r\n return Math.floor(value / 10);\r\n } else {\r\n return value;\r\n }\r\n}", "function UInt32toUInt8(value) {\n console.log(value);\n t = [\n value >> 24,\n (value << 8) >> 24,\n (value << 16) >> 24,\n (value << 24) >> 24\n ];\n console.log(t);\n return t;\n}", "function negbigint2behex(intvalue) {\n if (intvalue >= 0) // ONLY NEGATIVE!\n return null;\n x = intvalue;\n /*\n // https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx\n The BigInteger structure assumes that negative values are stored by using two's complement representation. Because the BigInteger structure represents a numeric value with no fixed length, the BigInteger(Byte[]) constructor always interprets the most significant bit of the last byte in the array as a sign bit. To prevent the BigInteger(Byte[]) constructor from confusing the two's complement representation of a negative value with the sign and magnitude representation of a positive value, positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0. For example, 0xC0 0xBD 0xF0 0xFF is the little-endian hexadecimal representation of either -1,000,000 or 4,293,967,296. Because the most significant bit of the last byte in this array is on, the value of the byte array would be interpreted by the BigInteger(Byte[]) constructor as -1,000,000. To instantiate a BigInteger whose value is positive, a byte array whose elements are 0xC0 0xBD 0xF0 0xFF 0x00 must be passed to the constructor.\n */\n //x=-1000000; // must become (big endian) \"f0bdc0\" => little endian C0 BD F0 (careful with positive 4,293,967,296 that may become negative, need to be C0 BD F0 FF 00)\n // ASSERT (x < 0) !!! x==0 is problematic! equals to 256...\n //x=-1; // ff\n //x=-2; // fe\n //x=-127; // 81\n //x=-255; // \"ff01\" => 01 ff\n //x=-256; // \"ff00\" => 00 ff\n //x=-257; // \"feff\" => ff fe\n //x=-128; // \"ff80\" => 80 ff\n // only for negative integers\n x *= -1; // turn into positive\n // ========================\n // perform two's complement\n // ========================\n // convert to binary\n y = x.toString(2);\n //console.log(\"FIRST BINARY: \"+y);\n // extra padding for limit cases (avoid overflow)\n y = \"0\" + y;\n //guarantee length must be at least 8, or add padding!\n while ((y.length < 8) || (y.length % 8 != 0)) {\n //console.log(\"ADDING PADDING 1!\");\n y = \"0\" + y;\n }\n // invert bits\n y2 = \"\";\n for (i = 0; i < y.length; i++)\n y2 += y[i] == '0' ? '1' : '0';\n //console.log(\"SECOND BINARY: \"+y2);\n // go back to int\n y3 = parseInt(y2, 2);\n //console.log(\"INT is \"+y3);\n // sum 1\n y3 += 1;\n //console.log(\"INT is after sum \"+y3);\n // convert to binary again\n y4 = y3.toString(2);\n //guarantee length must be at least 8, or add padding!\n while (y4.length < 8) {\n //console.log(\"ADDING PADDING!\");\n y4 = \"0\" + y4;\n }\n ///// verify if most important bit in LAST byte would is already set... (NO NEED.. ONLY FOR POSITIVE INTEGERS)\n //index = y4.length-8;\n //if(y4[index]=='0') {\n //console.log(\"CREATING EXTRA BYTE! BUT HOW?\");\n // must create an extra byte just to inform sign...\n //y4=\"10000000\"+y4; // could be 1xxxxxxx I guess, but everyone is just using f0 (which is 11110000)...\n //}\n\n //console.log(\"final binary:\"+y4);\n\n // convert to hex\n y5 = parseInt(y4, 2).toString(16);\n // adjust padding\n\n return revertHexString(y5); // big endian\n}", "static uint160(v) { return n(v, 160); }", "static uint168(v) { return n(v, 168); }", "static bytes15(v) { return b(v, 15); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns names and lengths of chromosomes for an organism's bestknown genome assembly. Gets data from NCBI EUtils web API.
getAssemblyAndChromosomesFromEutils(callback) { var asmAndChrArray, // [assembly_accession, chromosome_objects_array] organism, assemblyAccession, chromosomes, asmSearch, asmUid, asmSummary, rsUid, nuccoreLink, links, ntSummary, results, result, cnIndex, chrName, chrLength, chromosome, type, ideo = this; organism = ideo.config.organism; asmAndChrArray = []; chromosomes = []; asmSearch = ideo.esearch + '&db=assembly' + '&term=%22' + organism + '%22[organism]' + 'AND%20(%22latest%20refseq%22[filter])%20' + 'AND%20(%22chromosome%20level%22[filter]%20' + 'OR%20%22complete%20genome%22[filter])'; var promise = d3.promise.json(asmSearch); promise .then(function(data) { // NCBI Assembly database's internal identifier (uid) for this assembly asmUid = data.esearchresult.idlist[0]; asmSummary = ideo.esummary + '&db=assembly&id=' + asmUid; return d3.promise.json(asmSummary); }) .then(function(data) { // RefSeq UID for this assembly rsUid = data.result[asmUid].rsuid; assemblyAccession = data.result[asmUid].assemblyaccession; asmAndChrArray.push(assemblyAccession); // Get a list of IDs for the chromosomes in this genome. // // This information does not seem to be available from well-known // NCBI databases like Assembly or Nucleotide, so we use GenColl, // a lesser-known NCBI database. var qs = '&db=nuccore&linkname=gencoll_nuccore_chr&from_uid=' + rsUid; nuccoreLink = ideo.elink + qs; return d3.promise.json(nuccoreLink); }) .then(function(data) { links = data.linksets[0].linksetdbs[0].links.join(','); ntSummary = ideo.esummary + '&db=nucleotide&id=' + links; return d3.promise.json(ntSummary); }) .then(function(data) { results = data.result; for (var x in results) { result = results[x]; // omit list of reult uids if (x === 'uids') { continue; } if (result.genome === 'mitochondrion') { if (ideo.config.showNonNuclearChromosomes) { type = result.genome; cnIndex = result.subtype.split('|').indexOf('plasmid'); if (cnIndex === -1) { chrName = 'MT'; } else { // Seen in e.g. rice genome IRGSP-1.0 (GCF_001433935.1), // From https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?retmode=json&db=nucleotide&id=996703432,996703431,996703430,996703429,996703428,996703427,996703426,996703425,996703424,996703423,996703422,996703421,194033210,11466763,7524755 // genome: 'mitochondrion', // subtype: 'cell_line|plasmid', // subname: 'A-58 CMS|B1', chrName = result.subname.split('|')[cnIndex]; } } else { continue; } } else if ( result.genome === 'chloroplast' || result.genome === 'plastid' ) { type = 'chloroplast'; // Plastid encountered with rice genome IRGSP-1.0 (GCF_001433935.1) if (ideo.config.showNonNuclearChromosomes) { chrName = 'CP'; } else { continue; } } else { type = 'nuclear'; cnIndex = result.subtype.split('|').indexOf('chromosome'); chrName = result.subname.split('|')[cnIndex]; if ( typeof chrName !== 'undefined' && chrName.substr(0, 3) === 'chr' ) { // Convert "chr12" to "12", e.g. for banana (GCF_000313855.2) chrName = chrName.substr(3); } } chrLength = result.slen; chromosome = { name: chrName, length: chrLength, type: type }; chromosomes.push(chromosome); } chromosomes = chromosomes.sort(ideo.sortChromosomes); asmAndChrArray.push(chromosomes); ideo.coordinateSystem = 'bp'; return callback(asmAndChrArray); }); }
[ "getProperSpeciesAndBuild(buildInfo) {\n var me = this;\n var matchedSpecies = null;\n var matchedBuild = null;\n\n if (buildInfo != null) {\n // If the bam header provided a species, make sure it matches the\n // selected species name (or latin or binomial name).\n if (buildInfo.species) {\n for (speciesName in me.speciesNameToSpecies) {\n if (!matchedSpecies) {\n var species = me.speciesNameToSpecies[speciesName];\n if (species.name == buildInfo.species || species.binomialName == buildInfo.species || species.latin_name == buildInfo.species ) {\n matchedSpecies = species;\n }\n }\n }\n }\n\n // For now, just default to Human if species can't be determined from file headers\n if (!matchedSpecies) {\n matchedSpecies = me.speciesNameToSpecies[me.DEFAULT_SPECIES];\n }\n\n // Make sure each bam has a build that matches the selected\n // build name or one of its aliases\n if (matchedSpecies) {\n if (buildInfo.build) {\n matchedSpecies.genomeBuilds.forEach(function(build) {\n if (!matchedBuild) {\n if (build.name == buildInfo.build) {\n matchedBuild = build;\n } else {\n build.aliases.forEach(function(gbAlias) {\n if (gbAlias.alias == buildInfo.build) {\n matchedBuild = build;\n } else if (gbAlias.type == me.ALIAS_REFSEQ_ASSEMBLY_ACCESSION_RANGE && buildInfo.build.indexOf(\".\") > 0) {\n // See if we have an assembly in the range.\n // example of alias is GCF_000001405.[13-25]\n var assemblyRoot = buildInfo.build.split(\".\")[0];\n var assemblyVersion = +buildInfo.build.split(\".\")[1];\n\n var aliasRoot = gbAlias.alias.split(\".\")[0];\n if (assemblyRoot == aliasRoot) {\n var aliasRange = gbAlias.alias.split(\".\")[1];\n // Get rid of []\n aliasRange = aliasRange.substring(1, aliasRange.length - 1);\n // Get the numbers between the -\n var rangeLow = +aliasRange.split(\"-\")[0];\n var rangeHigh = +aliasRange.split(\"-\")[1];\n\n if (assemblyVersion >= rangeLow && assemblyVersion <= rangeHigh) {\n matchedBuild = build;\n }\n\n }\n }\n })\n }\n }\n })\n\n } else {\n // If a build wasn't specified, try to match to a genome build based on reference lengths\n matchedSpecies.genomeBuilds.forEach(function(build) {\n if (!matchedBuild) {\n var matchedCount = 0;\n var notMatchedCount = 0;\n var notFoundCount = 0;\n build.references.forEach(function(reference) {\n var refLength = null;\n if (buildInfo.references[reference.name]) {\n refLength = buildInfo.references[reference.name];\n } else if (buildInfo.references[reference.alias]) {\n refLength = buildInfo.references[reference.alias];\n }\n if (refLength && refLength == reference.length) {\n matchedCount++;\n } else if (refLength && refLength == reference.length - 1) {\n matchedCount++;\n } else if (refLength && refLength == reference.length + 1) {\n matchedCount++;\n } else if (refLength && refLength != reference.length) {\n notMatchedCount++;\n } else {\n notFoundCount++;\n }\n });\n if (build.references.length == matchedCount) {\n matchedBuild = build;\n } else if (matchedCount > 0 && notMatchedCount == 0 && (matchedCount + notFoundCount == build.references.length)) {\n matchedBuild = build;\n }\n\n }\n\n })\n\n }\n }\n }\n return {species: matchedSpecies, build: matchedBuild};\n\n\n }", "getChromosomeModel(bands, chromosome, taxid, chrIndex) {\n var chr = {},\n band,\n width, pxStop,\n chrHeight = this.config.chrHeight,\n maxLength = this.maxLength,\n chrLength,\n cs, hasBands;\n\n cs = this.coordinateSystem;\n hasBands = (typeof bands !== 'undefined');\n\n if (hasBands) {\n chr.name = chromosome;\n chr.length = bands[bands.length - 1][cs].stop;\n chr.type = 'nuclear';\n } else {\n chr = chromosome;\n }\n\n chr.chrIndex = chrIndex;\n\n chr.id = 'chr' + chr.name + '-' + taxid;\n\n if (this.config.fullChromosomeLabels === true) {\n var orgName = this.organisms[taxid].scientificNameAbbr;\n chr.name = orgName + ' chr' + chr.name;\n }\n\n chrLength = chr.length;\n\n pxStop = 0;\n\n if (hasBands) {\n for (var i = 0; i < bands.length; i++) {\n band = bands[i];\n var csLength = band[cs].stop - band[cs].start;\n width = chrHeight * chr.length / maxLength[cs] * csLength / chrLength;\n\n bands[i].px = {start: pxStop, stop: pxStop + width, width: width};\n\n pxStop = bands[i].px.stop;\n\n if (hasBands && band.stain === 'acen' && band.name[0] === 'p') {\n chr.pcenIndex = i;\n }\n }\n } else {\n pxStop = chrHeight * chr.length / maxLength[cs];\n }\n\n chr.width = pxStop;\n\n chr.scale = {};\n\n // TODO:\n //\n // A chromosome-level scale property is likely\n // nonsensical for any chromosomes that have cytogenetic band data.\n // Different bands tend to have ratios between number of base pairs\n // and physical length.\n //\n // However, a chromosome-level scale property is likely\n // necessary for chromosomes that do not have band data.\n //\n // This needs further review.\n if (this.config.multiorganism === true) {\n chr.scale.bp = 1;\n // chr.scale.bp = band.iscn.stop / band.bp.stop;\n chr.scale.iscn = chrHeight * chrLength / maxLength.bp;\n } else {\n chr.scale.bp = chrHeight / maxLength.bp;\n if (hasBands) {\n chr.scale.iscn = chrHeight / maxLength.iscn;\n }\n }\n chr.bands = bands;\n\n chr.centromerePosition = '';\n if (\n hasBands && bands[0].name[0] === 'p' && bands[1].name[0] === 'q' &&\n bands[0].bp.stop - bands[0].bp.start < 2E6\n ) {\n // As with almost all mouse chromosome, chimpanzee chr22\n chr.centromerePosition = 'telocentric';\n\n // Remove placeholder pter band\n chr.bands = chr.bands.slice(1);\n }\n\n if (hasBands && chr.bands.length === 1) {\n // Encountered when processing an assembly that has chromosomes with\n // centromere data, but this chromosome does not.\n // Example: chromosome F1 in Felis catus.\n delete chr.bands;\n }\n\n return chr;\n }", "getBands(content, taxid, chromosomes) {\n var lines = {},\n delimiter, tsvLines, columns, line, stain, chr,\n i, init, tsvLinesLength, source,\n start, stop, firstColumn, tmp;\n\n if (content.slice(0, 8) === 'chrBands') {\n source = 'native';\n }\n\n if (\n chromosomes instanceof Array &&\n typeof chromosomes[0] === 'object'\n ) {\n tmp = [];\n for (i = 0; i < chromosomes.length; i++) {\n tmp.push(chromosomes[i].name);\n }\n chromosomes = tmp;\n }\n\n if (typeof chrBands === 'undefined' && source !== 'native') {\n delimiter = /\\t/;\n tsvLines = content.split(/\\r\\n|\\n/);\n init = 1;\n } else {\n delimiter = / /;\n if (source === 'native') {\n tsvLines = eval(content);\n } else {\n tsvLines = content;\n }\n init = 0;\n }\n\n firstColumn = tsvLines[0].split(delimiter)[0];\n if (firstColumn === '#chromosome') {\n source = 'ncbi';\n } else if (firstColumn === '#chrom') {\n source = 'ucsc';\n } else {\n source = 'native';\n }\n\n tsvLinesLength = tsvLines.length;\n\n if (source === 'ncbi' || source === 'native') {\n for (i = init; i < tsvLinesLength; i++) {\n columns = tsvLines[i].split(delimiter);\n\n chr = columns[0];\n\n if (\n // If a specific set of chromosomes has been requested, and\n // the current chromosome\n typeof (chromosomes) !== 'undefined' &&\n chromosomes.indexOf(chr) === -1\n ) {\n continue;\n }\n\n if (chr in lines === false) {\n lines[chr] = [];\n }\n\n stain = columns[7];\n if (columns[8]) {\n // For e.g. acen and gvar, columns[8] (density) is undefined\n stain += columns[8];\n }\n\n line = {\n chr: chr,\n bp: {\n start: parseInt(columns[5], 10),\n stop: parseInt(columns[6], 10)\n },\n iscn: {\n start: parseInt(columns[3], 10),\n stop: parseInt(columns[4], 10)\n },\n px: {\n start: -1,\n stop: -1,\n width: -1\n },\n name: columns[1] + columns[2],\n stain: stain,\n taxid: taxid\n };\n\n lines[chr].push(line);\n }\n } else if (source === 'ucsc') {\n for (i = init; i < tsvLinesLength; i++) {\n // #chrom chromStart chromEnd name gieStain\n // e.g. for fly:\n // chr4\t69508\t108296\t102A1\tn/a\n columns = tsvLines[i].split(delimiter);\n\n if (columns[0] !== 'chr' + chromosomeName) {\n continue;\n }\n\n stain = columns[4];\n if (stain === 'n/a') {\n stain = 'gpos100';\n }\n start = parseInt(columns[1], 10);\n stop = parseInt(columns[2], 10);\n\n line = {\n chr: columns[0].split('chr')[1],\n bp: {\n start: start,\n stop: stop\n },\n iscn: {\n start: start,\n stop: stop\n },\n px: {\n start: -1,\n stop: -1,\n width: -1\n },\n name: columns[3],\n stain: stain,\n taxid: taxid\n };\n\n lines[chr].push(line);\n }\n }\n\n return lines;\n }", "function getSpeciesCount() {\n\t\tvar arrayCount = [];\n\t\tfor (var i = 0; i < data.features.length; i++) {\n\t\t\tfor (var j = 0; j < comNameArr.length; j++) {\n\t\t\t\tif (data.features[i].properties.Common_Name == comNameArr[j]) {\n\t\t\t\t\tarrayCount.push(comNameArr[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar dict = {};\n\t\tfor (var i = 0; i < comNameArr.length; i++) {\n\t\t\tvar getNumCount = arrayCount.reduce(function(n, val) {\n\t\t\t\treturn n + (val === comNameArr[i]);\n\t\t\t}, 0);\n\t\t\tdict[comNameArr[i]] = getNumCount;\n\t\t}\n\t\tfor (var key in dict) {\n\t\t\tvar value = dict[key];\n\t\t}\n\t\tvar props = Object.keys(dict).map(function(key) {\n\t\t\treturn {\n\t\t\t\tkey: key,\n\t\t\t\tvalue: this[key]\n\t\t\t};\n\t\t}, dict);\n\t\tprops.sort(function(p1, p2) {\n\t\t\treturn p2.value - p1.value;\n\t\t});\n\t\tvar topFive = props.slice(0, 5);\n\t\treturn topFive;\n\t}", "getTaxids(callback) {\n var ideo = this,\n taxid, taxids,\n org, orgs, i,\n taxidInit, tmpChrs,\n assembly, chromosomes,\n multiorganism, promise;\n\n taxidInit = 'taxid' in ideo.config;\n\n ideo.config.multiorganism = (\n ('organism' in ideo.config && ideo.config.organism instanceof Array) ||\n (taxidInit && ideo.config.taxid instanceof Array)\n );\n\n multiorganism = ideo.config.multiorganism;\n\n if ('organism' in ideo.config) {\n // Ideogram instance was constructed using common organism name(s)\n if (multiorganism) {\n orgs = ideo.config.organism;\n } else {\n orgs = [ideo.config.organism];\n }\n\n taxids = [];\n tmpChrs = {};\n for (i = 0; i < orgs.length; i++) {\n // Gets a list of taxids from common organism names\n org = orgs[i];\n for (taxid in ideo.organisms) {\n if (ideo.organisms[taxid].commonName.toLowerCase() === org) {\n taxids.push(taxid);\n if (multiorganism) {\n // Adjusts 'chromosomes' configuration parameter to make object\n // keys use taxid instead of common organism name\n tmpChrs[taxid] = ideo.config.chromosomes[org];\n }\n }\n }\n }\n\n if (taxids.length === 0) {\n promise = new Promise(function(resolve) {\n ideo.getTaxidFromEutils(resolve);\n });\n\n promise.then(function(data) {\n var organism = ideo.config.organism,\n dataDir = ideo.config.dataDir,\n urlOrg = organism.replace(' ', '-');\n\n taxid = data;\n taxids.push(taxid);\n\n ideo.config.taxids = taxids;\n ideo.organisms[taxid] = {\n commonName: '',\n scientificName: ideo.config.organism,\n scientificNameAbbr: ''\n };\n\n var fullyBandedTaxids = ['9606', '10090', '10116'];\n if (\n fullyBandedTaxids.indexOf(taxid) !== -1 &&\n ideo.config.showFullyBanded === false\n ) {\n urlOrg += '-no-bands';\n }\n var chromosomesUrl = dataDir + urlOrg + '.js';\n\n var promise = new Promise(function(resolve, reject) {\n d3.request(chromosomesUrl).get(function(error, data) {\n if (error) {\n reject(Error(error));\n }\n resolve(data);\n });\n });\n\n return promise\n .then(\n function(data) {\n // Check if chromosome data exists locally.\n // This is used for pre-processed centromere data,\n // which is not accessible via EUtils. See get_chromosomes.py.\n\n var asmAndChrArray = [],\n chromosomes = [],\n seenChrs = {},\n chr;\n\n eval(data.response);\n\n asmAndChrArray.push('');\n\n for (var i = 0; i < chrBands.length; i++) {\n chr = chrBands[i].split(' ')[0];\n if (chr in seenChrs) {\n continue;\n } else {\n chromosomes.push({name: chr, type: 'nuclear'});\n seenChrs[chr] = 1;\n }\n }\n chromosomes = chromosomes.sort(ideo.sortChromosomes);\n asmAndChrArray.push(chromosomes);\n ideo.coordinateSystem = 'iscn';\n return asmAndChrArray;\n },\n function() {\n return new Promise(function(resolve) {\n ideo.coordinateSystem = 'bp';\n ideo.getAssemblyAndChromosomesFromEutils(resolve);\n });\n }\n );\n })\n .then(function(asmChrArray) {\n assembly = asmChrArray[0];\n chromosomes = asmChrArray[1];\n\n ideo.config.chromosomes = chromosomes;\n ideo.organisms[taxid].assemblies = {\n default: assembly\n };\n\n callback(taxids);\n });\n } else {\n ideo.config.taxids = taxids;\n if (multiorganism) {\n ideo.config.chromosomes = tmpChrs;\n }\n\n callback(taxids);\n }\n } else {\n if (multiorganism) {\n ideo.coordinateSystem = 'bp';\n if (taxidInit) {\n taxids = ideo.config.taxid;\n }\n } else {\n if (taxidInit) {\n taxids = [ideo.config.taxid];\n }\n ideo.config.taxids = taxids;\n }\n\n callback(taxids);\n }\n }", "function getAllCodesAndDescriptions() {\r\n\r\n\t// security measure\r\n\tif(searchArray.length > 15) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tconst queryString = \"http://localhost:3030/medstats_v2/?query=PREFIX+med%3A+%3Chttp%3A%2F%2Fpurl.org%2Fnet%2Fmedstats%3E%0A%0ASELECT+distinct+%3Fdi+%3Fdt+%0AWHERE+%7B%0A++%3Fx+med%3Ajahr+%222000%22+.%0A++%3Fx+med%3Adiagnose_icd+%3Fdi+.%0A++%3Fx+med%3Adiagnose_text+%3Fdt+.%0A%7D\";\r\n\r\n\t$.getJSON(queryString, function (data) {\r\n\t\t$.each(data.results, function (key, val) {\r\n\t\t\t$.each(val, function (m, n) {\r\n\t\t\t\t$.each(n.di, function (dikey, dival) {\r\n\t\t\t\t\tif (dikey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tdi = dival;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.dt, function (dtkey, dtval) {\r\n\t\t\t\t\tif (dtkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tdt = dtval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\t// push data into searchArray\r\n\t\t\t\tsearchArray.push(di);\r\n\t\t\t\tsearchArray.push(dt);\r\n\t\t\t\tallIcdCodes.push({icd_code: di, icd_text: dt});\r\n\t\t\t})\r\n\t\t});\r\n\r\n\t\t// load autocomplete for search function\r\n\t\tsearchHandlers();\r\n\r\n\t});\r\n\r\n}", "function g_listMajors() {\n gapi.client.sheets.spreadsheets.values.get({\n spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',\n range: 'Class Data!A2:E',\n }).then(function(response) {\n var range = response.result;\n if (range.values.length > 0) {\n g_appendPre('Name, Major:');\n for (i = 0; i < range.values.length; i++) {\n var row = range.values[i];\n // Print columns A and E, which correspond to indices 0 and 4.\n g_appendPre(row[0] + ', ' + row[4]);\n }\n } else {\n g_appendPre('No data found.');\n }\n }, function(response) {\n g_appendPre('Error: ' + response.result.error.message);\n });\n}", "function createInitialPopulation() {\n //inits the array\n genomes = [];\n //for a given population size\n for (var i = 0; i < populationSize; i++) {\n //randomly initialize the 7 values that make up a genome\n //these are all weight values that are updated through evolution\n var genome = {\n //unique identifier for a genome\n id: Math.random(),\n //The weight of each row cleared by the given move. the more rows that are cleared, the more this weight increases\n rowsCleared: Math.random() - 0.5,\n //the absolute height of the highest column to the power of 1.5\n //added so that the algorithm can be able to detect if the blocks are stacking too high\n weightedHeight: Math.random() - 0.5,\n //The sum of all the column’s heights\n cumulativeHeight: Math.random() - 0.5,\n //the highest column minus the lowest column\n relativeHeight: Math.random() - 0.5,\n //the sum of all the empty cells that have a block above them (basically, cells that are unable to be filled)\n holes: Math.random() * 0.5,\n // the sum of absolute differences between the height of each column \n //(for example, if all the shapes on the grid lie completely flat, then the roughness would equal 0).\n roughness: Math.random() - 0.5,\n };\n //add them to the array\n genomes.push(genome);\n }\n evaluateNextGenome();\n }", "function buildCbsaMap() {\n\n // Census data list xls file of zips to cbsa info, with relevant parts extracted\n // and converted to a csv file.\n // source: http://www.census.gov/population/metro/files/lists/2015/List1.xls\n // (Now seems to be located at https://www2.census.gov/programs-surveys/metro-micro/geographies/reference-files/2015/delineation-files/list1.xls).\n const rawCbsaData = fs.readFileSync('data/cbsa-data.csv', 'utf8');\n\n // Remove double quotes (Added by .csv format, but they get in the way for what I'm doing)\n let cbsaData = rawCbsaData.replace(/[\"]+/g, \"\");\n\n // Break each line of stationData into an element in an array\n cbsaData = cbsaData.split('\\n');\n\n // Ensure excess white space is trimmed\n cbsaData = cbsaData.map(function(entry) {\n return entry.replace(/\\s+/g, \" \");\n });\n\n // Break each line into its own array, with each comma seperated value being an element.\n let cbsaData2 = [];\n for (let i of cbsaData) {\n cbsaData2.push(i.split(\",\"));\n }\n\n // Some editors add empty line, resulting in last array being empty. Test for this\n // (empty string is falsey), and then remove that element.\n if ( !cbsaData2[cbsaData2.length - 1][0] ) {\n cbsaData2.pop();\n };\n\n // remove space before state name (\" OH\" -> \"OH\").\n for (let arr of cbsaData2) {\n let state = arr[2];\n state = state.trim();\n arr[2] = state;\n }\n\n // Build object and eliminate duplicates\n let cbsaObj = {};\n for (let arr of cbsaData2) {\n let code = arr[0];\n if (cbsaObj[code]) {\n continue;\n } else {\n let area = arr[1];\n let states = arr[2];\n let type = arr[3]; // Currently full name. Consider shortening to metro/micro?\n cbsaObj[code] = {\n \"area\": area,\n \"states\": states,\n \"type\": type\n }\n }\n }\n return cbsaObj;\n}", "agencies(cb) {\n var agencies = [ ];\n\n this._newRequest().query({ command: 'agencyList' }, function(e) {\n switch(e.name) {\n case 'error':\n cb(null, e.data);\n break;\n\n case 'opentag':\n var tag = e.data;\n var attributes = tag.attributes;\n\n if (tag.name === 'agency') {\n agencies.push(attributes);\n }\n break;\n\n case 'end':\n cb(agencies);\n break;\n }\n }.bind(this));\n }", "function locationFinder() {\n\n // initializes an empty array\n var locations = [];\n\n // adds the single location property from bio to the locations array\n locations.push(bio.contacts.location);\n\n // iterates through school locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n education.schools.forEach(function(school){\n locations.push(school.location);\n });\n\n // iterates through work locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n work.jobs.forEach(function(job){\n locations.push(job.location);\n });\n // console.log(locations);\n return locations;\n }", "function formatSeqs(seqData)\n{\n const lociSummary = [];\n let i;\n for(i in seqData)\n lociSummary.push(getLocus(i,seqData));\n return lociSummary;\n}", "async function fetchOSMData(bounds) {\n let response = await axios.get('https://api.openstreetmap.org/api/0.6/map?bbox=' + bounds.bottomLeft.lon + ',' + bounds.bottomLeft.lat + ',' + bounds.topRight.lon + ',' + bounds.topRight.lat);\n let elements = response.data.elements;\n let filteredElements = [];\n\n if (elements) {\n elements.forEach(element => {\n if (element.type === 'node' && element.tags && (element.tags.tourism || element.tags.natural || element.tags.amenity || element.tags.sport)) {\n filteredElements.push({id: element.id, lat: element.lat, lon: element.lon, tags: element.tags});\n }\n });\n }\n\n return filteredElements;\n}", "function locationFinder() {\n\n // initializes an empty array\n let locations = [];\n\n // adds the single location property from bio to the locations array\n locations.push(bio.contacts.location);\n\n // iterates through school locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n education.schools.forEach(function (school) {\n locations.push(school.location);\n });\n\n // iterates through work locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide above.\n work.jobs.forEach(function (job) {\n locations.push(job.location);\n });\n\n return locations;\n }", "function createOrganism() {\n var ret = {};\n var organism = createAsterias();\n //get all properties of form xxxxLevel, \n //where xxxx is the gene name and xxxxLevel is a function\n //returning the level for that gene\n ret = _.filter(_.map(organism,\n function(val,key){ \n var ind = key.search(/Level/)\n if(ind > 0) {\n var ret = {}\n ret[key.substring(0,ind)] = val();\n return [key.substring(0,ind),val()]\n }\n return undefined;\n }),\n function(item) {\n return !_.isNil(item);\n });\n\n //convert the array from above into an object of\n // {geneName: expressionLevel, geneName: expressionLevel}\n // format\n ret = _.reduce(ret,\n function(obj,i,ind) { \n obj[i[0]] =i[1];\n return obj;\n },\n {})\n \n// console.log(ret);\n return ret;\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}", "function getCollaborations(){\n\tvar collaboration = 0;\n\tfor(var i = 0; i < agency.length; i++)\n\t{\n\t\tcollaboration += parseInt(agency[i].agency_collaboration);\n\t}\n\treturn collaboration;\n}", "async getAreas() {\n const areas = await this.service.areas.query({}, ['id', 'name', 'details']);\n this.response(200, areas);\n }", "async function getBusLocations(){\n\tvar url = 'https://api-v3.mbta.com/vehicles?sort=direction_id&include=route&filter%5Broute%5D=1&api_key=5480903a65764e129cf91c942b08de49';\t\n\tvar response = await fetch(url);\n\tvar json = await response.json();\n\treturn json.data;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load list of URLs from a file
function loadUrls(path) { var list = fs.readFileSync(path, { encoding: 'utf8' }); return list.split('\n').map(function(cv) { return cv.trim(); }).filter(function(x) { return x.length > 0; }); }
[ "function getURLs(urls) {\n // split the contents by new line\n const lines = urls.split(/\\r?\\n/);\n\n lines.forEach((line) => {\n axios.get(line).then(function(resp) {\n doSomething(resp, line);\n })\n .catch(err => {\n console.log(`Error with url in file`)\n })\n });\n}", "function readURLs(file) {\n let data = fs.readFileSync(file, 'utf8', function(err, data) {\n if (err) {\n console.log(\"Problem with reading file\");\n process.exit(1)\n }\n })\n return data\n}", "load(url) {\n return __awaiter(this, void 0, void 0, function* () {\n const file = this.files.get(utils_1.parseUrl(url).pathname || '/');\n if (file == null) {\n if (this.fallbackLoader) {\n if (this.fallbackLoader.canLoad(url)) {\n return this.fallbackLoader.load(url);\n }\n throw new Error(`${url} not present in file map and fallback loader can not load.`);\n }\n throw new Error(`${url} not present in file map and no fallback loader.`);\n }\n return streams_1.getFileContents(file);\n });\n }", "function loadBundlesFromFile(listFile) {\n function handleError(err) {\n $log.info([\n \"No external bundles loaded;\",\n \"could not load bundle listing in\",\n listFile,\n \"due to error\",\n err.status,\n err.statusText\n ].join(' '));\n return loadBundlesFromArray([]);\n }\n\n return getJSON(listFile)\n .then(loadBundlesFromArray, handleError);\n }", "load(urls, callback) {\n\t\tvar cScript = document.currentScript.src, loadEntry;\n\n\t\tfor(let x = 0; x<urls.length; x++){\n\t\t\turls[x] = this.getFullPath(urls[x]);\n\t\t}\n\n\t\tif(this.loadEntries.hasOwnProperty(cScript)){\n\t\t\tloadEntry = this.loadEntries[cScript];\n\t\t}else{\n\t\t\tthis.loadEntries[cScript] = loadEntry = {loaded:false,executed:false, url:cScript, dependencies:{}};\n\t\t}\n\t\tloadEntry.callback=callback;\n\n\n\t\t// now lets request all the dependencies that have not been processed yet\n\t\tfor (let i=0;i<urls.length;i++) {\n\t\t\tlet cdep = urls[i];\n\t\t\tif(!this.loadEntries.hasOwnProperty(cdep)){\n\t\t\t\t//This creates a new loadEntry for the dependency and also adds that entry to the current loadEntry's dependencies property.\n\t\t\t\tloadEntry.dependencies[cdep]=this.loadEntries[cdep]={loaded:false,executed:false,url:urls[i],dependencies:{},callback:null};\n\t\t\t\tthis.requestScript(this.loadEntries[cdep]);\n\t\t\t}else{\n\t\t\t\tloadEntry.dependencies[cdep] = this.loadEntries[cdep];\n\t\t\t}\n\t\t}\n\n\t\tthis._callReadyModules();\n\t}", "function getLocalFileList() {\n var fileListPath = 'filelist.txt';\n var localFileURL;\n if (chrome.extension) localFileURL = chrome.extension.getURL(fileListPath);\n var txtFile = new XMLHttpRequest();\n txtFile.open(\"GET\", localFileURL, true);\n txtFile.onreadystatechange = function()\n {\n if (txtFile.readyState === 4) { // document is ready to parse.\n if (txtFile.status === 200) { // file is found\n allText = txtFile.responseText;\n // Convert all slashes to forward slashes\n lines = txtFile.responseText.replace(/\\\\/g,\"/\").split(\"\\n\");\n fileList = lines;\n fileCount = fileList.length - 1\n fileIndex = 0;\n handleLocalFile(fileList[0]);\n }\n }\n }\n txtFile.send(null);\n}", "function loadBatches(){\n let batch_data = fs.readFileSync('./batches.txt');\n batches = JSON.parse(batch_data);\n //console.log(batches);\n}", "async function localLoad() {\r\n console.log('Load urls and domains from local storage');\r\n await chrome.storage.local.get(['urls'], function (result) {\r\n if (result.urls.length == 0)\r\n urls = [];\r\n else {\r\n urls = result.urls;\r\n }\r\n });\r\n //domains in the storage don't have class Domain, so need to be convert to class Domain\r\n await chrome.storage.local.get(['domains'], function (result) {\r\n domains = {};\r\n var domainsInStorage = result.domains;\r\n if (Object.keys(domainsInStorage).length != 0) {\r\n console.log('Load', Object.keys(domainsInStorage).length, 'domains from local storage');\r\n for (domain_name of Object.keys(domainsInStorage)) {\r\n domain = domainsInStorage[domain_name];\r\n domains[domain_name] = new Domain(domain.name, domain.visit, domain.duration, domain.date, domain.weekDay, domain.networkTraffic);\r\n }\r\n }\r\n });\r\n}", "addSetOfURL(URL) {\n for (var i = 0; i < URL.length; ++i) {\n this.addURL(URL[i]);\n }\n }", "function loadHosts() {\n if (noLoadHosts) return;\n\n noLoadHosts = true; // Debounce\n var file = __dirname + \"/\" + hostsFile;\n fs.exists(file, function(exists) {\n\tif (!exists) return;\n\n\thosts = {};\n\tfs.readFile(file, function(err, data) {\n\t _.each(data.toString().split(/[\\n\\r]+/), function(line) {\n\t\tline = line.replace(/\\s*\\#.*$/, '');\n\t\tif (line.match(/^\\s*$/)) return;\n\n\t\tvar parts = line.split(/\\s+/);\n\t\tif (parts && parts.length == 2) {\n\t\t hosts[parts[0]] = parts[1];\n\t\t}\n\t });\n\t if (_.keys(hosts).length > 0) {\n\t\tnoLoadHosts = false;\n\t\tconsole.log('Loaded ' + _.keys(hosts).length + ' hosts from ' + file);\n\t }\n\t});\n });\n}", "function importTrackers(url) {\n try {\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", url, false);\n xhr.send();\n var response = xhr.responseText;\n var jsonResponse = JSON.parse(response);\n for (var i = 0; i < jsonResponse.List.length; i++) {\n allTrackers[jsonResponse.List[i].trackerPattern] = jsonResponse.List[i];\n }\n serverCheck = \"on\";\n } catch (e) {\n serverCheck = \"off\";\n }\n}", "get urlsToProcess () {\n return urlsToProcess.slice();\n }", "loadItems(url) {\n this.indexUrl = url;\n this.getFromServer(url, this.serverParams).then(response => {\n this.totalRecords = response.meta.total;\n this.rows = response.data;\n });\n }", "setUrls(urls) {\n this.wrapped.urls = null;\n if (urls) {\n urls.forEach(url => {\n this.addUrl(url);\n });\n }\n return this;\n }", "async function listSources( config, files ) {\n let buildable = isHTMLFile,\n copyable = isNotHiddenFile;\n // If a list of files to build is specified then expand\n // the list to include dependencies.\n if( files ) {\n // The ste of copyables is any file on the file list.\n let onFileList = lookup( files );\n copyable = path => isNotHiddenFile( path ) && onFileList( path );\n }\n let collections = new Collections( config );\n // Create a function for testing for excluded file paths.\n let exclude = [\n // Exclude files starting with underscore.\n '_*',\n // Exclude files under _site/, in case running in --site mode.\n //'_site/*',\n //'_site/**/*',\n // Exclude configuration files and manifests.\n //'_config.json',\n //'_config.yml',\n 'locomote.json',\n // Exclude dependency files.\n '*.dependencies',\n // Exclude npm stuff.\n 'node_modules/*',\n 'node_modules/**/*',\n 'package.json',\n 'package-lock.json',\n // Exclude webpack stuff.\n 'webpack.config.js'\n ];\n if( Array.isArray( config.exclude ) ) {\n exclude = exclude.concat( config.exclude );\n }\n else if( typeof config.exclude == 'string' ) {\n exclude = exclude.concat( config.exclude.split(/,/g) );\n }\n let patterns = exclude.map( ex => new MM.Minimatch( ex, { dot: true }) );\n let excluded = path => {\n return patterns.reduce( ( ex, p ) => ex || p.match( path ), false );\n };\n // Find source files.\n let paths = await findFiles( source );\n await asyncBatch( paths, ListBatchSize, async path => {\n if( excluded( path ) ) {\n // Don't process excluded files.\n return;\n }\n let collection = collections.getCollectionForPath( path );\n if( buildable( path ) ) {\n let file = Path.join( source, path );\n let { frontmatter, html } = await parseHTMLSource( file );\n if( frontmatter ) {\n // File is an HTML doc with frontmatter.\n let data = collection.getDocumentData( path, frontmatter );\n if( html.length > CacheDocumentHTMLSize ) {\n html = null;\n }\n let doc = new Document( path, data, html );\n collection.addDocument( doc );\n return;\n }\n }\n if( copyable( path ) ) {\n // Add file as static file to be copied.\n collection.addStaticFile( path );\n }\n });\n return collections;\n }", "function loadFiles(files) {\n var file = files.shift();\n\n logStart('open: ' + file.name);\n\n loadFile(file).then(function() {\n logEnd();\n files.length && loadFiles(files);\n });\n}", "async function findAndReplaceAll(directory, urlList){\n const fileList = getFileList(directory)\n for (let urlMap of urlList){\n let processes = []\n for (let fileName of fileList){\n let process = findAndReplace(fileName, urlMap)\n processes.push(process)\n }\n await Promise.all(processes)\n }\n}", "async loadPlaylists(url) {\n\t\tlet response = await utils.apiCall(url, this.props.access_token);\n\t\tthis.setState({ playlists: response.items, nplaylists: response.total, nextURL: response.next,\n\t\t\tprevURL: response.previous });\n\n\t\tplaylists.style.display = 'block';\n\t\tsubtitle.textContent = (response.offset + 1) + '-' + (response.offset + response.items.length) +\n\t\t\t' of ' + response.total + ' playlists\\n';\n\t}", "load() {\n\n this.cars = []\n //readFile(this.fileName).then(function(data){console.log(data)}) //2.We are reading the file because we are using promisify\n readFile(this.fileName, 'utf8')\n //.then(data => console.log(typeof data))\n .then(data => JSON.parse(data)) //3.JSON.parse is converting text into jSON data and push/add the content to the list of cars\n .then(carsList => { //4. then we are looping the array of objects and add each object into the list of cars.\n //console.log('before', this.cars)\n carsList.forEach(car => {\n // this.cars.push(car)\n this.add(new Car(car))\n })\n //console.log('after', this.cars)\n })\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function called product that calculates the product of an array of numbers using a for loop; then, refactor it to use each.
function product(arr) { var total = 1; for (i = 0 ; i = arr.length ; i++) { total *= arr[i]; } return total; }
[ "function multiplyAll(arr) {\n var product = 1;\n \n for (let i =0; i < arr.length; i++){\n for (let j=0; j < arr[i].length; j++){\n product*=arr[i][j]\n }\n }\n \n return product;\n }", "function productContents(array) {\r\n\tlet product = 1;\r\n\tfor (let i = 0; i < array.length; ++i)\r\n\t{\r\n\t\tproduct *= array[i];\r\n\t}\r\n\treturn product;\r\n}", "function multiplyArrValues(array){ \nvar result = 1; \n for( let i = 0; i < array.length; i++) { \n for (let j = 0; j < array[i].length ; j++){\n result *= array[i][j]; \n }\n }\n return result;\n}", "function productOfArray(arr){\n if (arr.length === 1) return arr[0]\n return arr[0] * productOfArray(arr.slice(1))\n}", "function multiplyArray(testArray) { //eslint-disable-line\n\n //establish a counter\n var product = 1;\n\n // * all the #'s in the array\n // use a for loop to set boundaries\n // use multiply() to replace counter = counter * array[i]\n\n for (var i = 0 ; i < testArray.length ; i++) {\n product = multiply(product, testArray[i])[0];\n console.log (product);\n }\n\n var multiplyArrayString = 'The numbers ' + testArray.toString() + ' have a product of ' + product + '.';\n\n console.log('rhi says: ', multiplyArrayString);\n\n return [product, multiplyArrayString];\n}", "function accumulatingProduct(arr) {\n\tconst a = [];\n\tif (arr[0]) a.push(arr[0]);\n\tfor (let i = 1; i < arr.length; i++) {\n\t\ta.push(arr[i] * a[a.length - 1]);\n\t}\n\treturn a;\n}", "function productOfArray(arr) {\n //initialize tracker variable\n let tracker = 1;\n\n //main recursive function\n function recursiveReal(arr) {\n //updates the value of tracker by multiplying tracker by the first element of the updated array\n tracker *= arr[0];\n //base (stopping ) condition\n if (arr.length === 1) return;\n //recursion call\n recursiveReal(arr.slice(1));\n }\n\n //recursive function call\n recursiveReal(arr);\n\n return tracker;\n}", "function product (a, b){\n return a*b;\n}", "function per(n) {\n\n // convert the number to string to know the length and split up by single characters\n let nstring = n.toString();\n\n // if length is 1 then we are done, there is no multiplicative persistence\n if (nstring.length == 1) return [];\n\n // store results in array\n let result = [];\n\n while (nstring.length > 1) {\n // this variable will store the product of the numbers\n let product = 1; \n\n // loop through the number as an array and multiple each number with each other\n nstring.split(\"\").forEach((element, index) => {\n product *= +element;\n });\n \n // add the number to the result array\n result.push(product);\n\n // replace the original number with the new calculated one\n nstring = product.toString();\n }\n\n return result;\n }", "function multiplyby10(arr){\nreturn arr.map(function(elem){\nreturn elem*10;\n});\n}", "function mult(valor){\n let arrayMult = array1.map(function (item){\n return item * valor;\n });\n return console.log(arrayMult);\n}", "function mult(n){\n var mult=0;\n for (var i = 1; i < n; i++) {\n mult =mult+mult*i;\n }\n \n return mult ;\n }", "function inner_product(a,b) {\n\tvar s = 0;\n\tif (typeof a ==='undefined' || typeof b ==='undefined'){\n\t\treturn undefined;\n\t}\n\telse {\n\t\tif (a.length != b.length){\n\t\t\treturn undefined;\n\t\t}\n\t\telse {\n\t\t\tfor (var i=0;i<a.length;i++){\n\t\t\t\t\n\t\t\t\ts = a[i]*b[i] + s;\n\t\t\t\t\n\t\t\t}\n\t\t\treturn s;\n\t\t}\t\n\t}\n}", "function multiplyByOne1() {\n for (i = 0; i < 11; i++) {//sintaxa pentru for: parcurgem loop-ul de la 0-10, acestea fiind valorile contorului i si incrementam pentru fiecare apelare a functiei\n var x = 1;//declaram variabila x, reprezentand numarul cu care vom inmulti contorul nostru si ii assignam valoarea 1\n console.log(x * i);//afisam in consola rezultatul inmultirii celor 2 numere (de tip number)\n }\n}", "function mulRecurse(...num) {\n const array = [...num];\n const array2 = [...array[0]];\n let prod = 1;\n if (array2.length > 0) {\n let n = array2.shift();\n prod = n * mulRecurse(array2);\n }\n return prod;\n}", "function getProductsSansIndex(array) {\n var finalAnswer = []; //gonna put each product in here\n var result = array.map(function (currentVal, currentIndex) { //map over the array\n var product = array.filter(function (filteredValue, filteredIndex) { //filter out the index\n return filteredIndex !== currentIndex; //get the values where the current place in the map are not equal to the current place in the filter\n })\n .reduce(function (total, currentValue) { //multiply the array values\n return total * currentValue;\n });\n finalAnswer.push(product); //push the final product to the final answer\n });\n return finalAnswer;\n}", "function recursiveMultiplier(arr, num){\n\tlet result = [];\n\tfunction helper(index){\n\t\tif(index === arr.length){\n\t\t\treturn;\n\t\t} else {\n\t\t\tresult[index] = arr[index] * 2;\n\t\t\thelper(index + 1);\n\t\t}\n\t}\n\thelper(0);\n\treturn result;\n}", "function MULTIPLY() {\n for (var _len10 = arguments.length, values = Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {\n values[_key10] = arguments[_key10];\n }\n\n // Return `#NA!` if 2 arguments are not provided.\n if (values.length !== 2) {\n return error$2.na;\n }\n\n // decompose values into a and b.\n var a = values[0];\n var b = values[1];\n\n // Return `#VALUE!` if either a or b is not a number.\n\n if (!ISNUMBER(a) || !ISNUMBER(b)) {\n return error$2.value;\n }\n\n // Return the product\n return a * b;\n}", "function productSum(array, depth = 1) {\n\tlet total = 0\n\tfor (const e of array) {\n\t\tif (Array.isArray(e)) total += productSum(e, depth + 1)\n\t\telse total += e\n\t}\n\treturn total * depth\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is used copy the included sources requested in the docs. It parses all the docs files, finds the included sources and copy them under the `sourceDir`. Options: docsDir: the directory containing the docs files sourceDir: the directory that will contain the included sources include: list of patterns to look for doc files pathPrefix: a path prefix to use for reading the sources
async function getIncludedSources(options) { options = { ...defaultOptions, ...options }; const { docsDir, include, sourceDir, pathPrefix } = options; const cleanedSourceDir = sourceDir.replace('./', ''); const includedSourceRe =`\`\`\`[a-z\-]+ \\(${cleanedSourceDir}/([^\\]\\s]+)\\)\n\`\`\``; // first, gather all the docs files const docsFiles = await globby(include, { cwd: docsDir, }); const seen = new Set(); // second, read every file source let sourceFiles = await Promise.all(docsFiles.map(async (source) => { const data = await readFile(`${docsDir}/${source}`); const sourceFiles = []; let group, sourceFile, content; // third, find out if there is a source to be included // there can be multiple sources in the same file const re = new RegExp(includedSourceRe, 'gi'); while ((group = re.exec(data)) !== null) { sourceFile = group[1]; if (seen.has(sourceFile)) { continue; } seen.add(sourceFile); // fourth, read the source file content = await readFile(`${pathPrefix}${sourceFile}`); sourceFiles.push([sourceFile, content]); } return sourceFiles; })); sourceFiles = sourceFiles.flat().filter(pair => pair.length > 0); // finally, write all the source files in the `sourceDir` return await Promise.all(sourceFiles.map(async ([sourceFile, content]) => { return await outputFile(`${sourceDir}/${sourceFile}`, content); })); }
[ "function collectSources(sourceDirectories, tmpDirectory, focusedSourceFiles) {\n for (let i = 0; i < sourceDirectories.length; i++) {\n let src = sourceDirectories[i];\n\n // Identify all files in source dir, recursively.\n let filesSNP = readdir(src).filter(file => /.snp/.test(file));\n let filesAS = readdir(src).filter(file => /.as$/.test(file));\n let files = filesSNP.concat(filesAS); // NOTE: its imporant that snippets go first\n\n files.forEach(file => {\n\n let inputFile = path.resolve(src, file);\n\n // Identify source file.\n let segments = inputFile.match(/([a-zA-Z0-9]+)/g);\n segments.pop();\n let identifier = segments.pop();\n\n // Focus or ignore?\n if(focusedSourceFiles && focusedSourceFiles.indexOf(identifier) === -1) {\n return;\n }\n\n // resolve the includes and write prepared output to tmp directory:\n let content = fs.readFileSync(inputFile, 'UTF-8');\n content = resolveIncludes(content, file, src);\n fs.outputFileSync(path.resolve(tmpDirectory, file), content.replace(/\\r\\n?/g, '\\n'));\n });\n }\n}", "async function listSources( config, files ) {\n let buildable = isHTMLFile,\n copyable = isNotHiddenFile;\n // If a list of files to build is specified then expand\n // the list to include dependencies.\n if( files ) {\n // The ste of copyables is any file on the file list.\n let onFileList = lookup( files );\n copyable = path => isNotHiddenFile( path ) && onFileList( path );\n }\n let collections = new Collections( config );\n // Create a function for testing for excluded file paths.\n let exclude = [\n // Exclude files starting with underscore.\n '_*',\n // Exclude files under _site/, in case running in --site mode.\n //'_site/*',\n //'_site/**/*',\n // Exclude configuration files and manifests.\n //'_config.json',\n //'_config.yml',\n 'locomote.json',\n // Exclude dependency files.\n '*.dependencies',\n // Exclude npm stuff.\n 'node_modules/*',\n 'node_modules/**/*',\n 'package.json',\n 'package-lock.json',\n // Exclude webpack stuff.\n 'webpack.config.js'\n ];\n if( Array.isArray( config.exclude ) ) {\n exclude = exclude.concat( config.exclude );\n }\n else if( typeof config.exclude == 'string' ) {\n exclude = exclude.concat( config.exclude.split(/,/g) );\n }\n let patterns = exclude.map( ex => new MM.Minimatch( ex, { dot: true }) );\n let excluded = path => {\n return patterns.reduce( ( ex, p ) => ex || p.match( path ), false );\n };\n // Find source files.\n let paths = await findFiles( source );\n await asyncBatch( paths, ListBatchSize, async path => {\n if( excluded( path ) ) {\n // Don't process excluded files.\n return;\n }\n let collection = collections.getCollectionForPath( path );\n if( buildable( path ) ) {\n let file = Path.join( source, path );\n let { frontmatter, html } = await parseHTMLSource( file );\n if( frontmatter ) {\n // File is an HTML doc with frontmatter.\n let data = collection.getDocumentData( path, frontmatter );\n if( html.length > CacheDocumentHTMLSize ) {\n html = null;\n }\n let doc = new Document( path, data, html );\n collection.addDocument( doc );\n return;\n }\n }\n if( copyable( path ) ) {\n // Add file as static file to be copied.\n collection.addStaticFile( path );\n }\n });\n return collections;\n }", "collectPluginSources(content) {\n const self = this;\n\n Object.entries(self.pageConfig.plugins)\n .forEach(([pluginName, plugin]) => {\n if (!plugin.getSources) {\n return;\n }\n\n const result = plugin.getSources(content, self.pageConfig.pluginsContext[pluginName] || {},\n self.frontMatter, self.getPluginConfig());\n\n let pageContextSources;\n let domTagSourcesMap;\n\n if (_.isArray(result)) {\n pageContextSources = result;\n } else if (_.isObject(result)) {\n pageContextSources = result.sources;\n domTagSourcesMap = result.tagMap;\n } else {\n logger.warn(`${pluginName} returned unsupported type for ${self.pageConfig.sourcePath}`);\n return;\n }\n\n if (pageContextSources) {\n pageContextSources.forEach((src) => {\n if (src === undefined || src === '' || utils.isUrl(src)) {\n return;\n } else if (path.isAbsolute(src)) {\n self.pluginSourceFiles.add(path.resolve(src));\n return;\n }\n\n // Resolve relative paths from the current page source\n const originalSrcFolder = path.dirname(self.pageConfig.sourcePath);\n const resolvedResourcePath = path.resolve(originalSrcFolder, src);\n\n self.pluginSourceFiles.add(resolvedResourcePath);\n });\n }\n\n if (domTagSourcesMap) {\n const $ = cheerio.load(content);\n\n domTagSourcesMap.forEach(([tagName, attrName]) => {\n if (!_.isString(tagName) || !_.isString(attrName)) {\n logger.warn(`Invalid tag or attribute provided in tagMap by ${pluginName} plugin.`);\n return;\n }\n\n const selector = `${tagName}[${attrName}]`;\n $(selector)\n .each((i, el) => {\n const elem = $(el);\n\n let src = elem.attr(attrName);\n\n src = utils.ensurePosix(src);\n if (src === '' || utils.isUrl(src)) {\n return;\n } else if (path.isAbsolute(src)) {\n self.pluginSourceFiles.add(path.resolve(src));\n return;\n }\n\n // Resolve relative paths from the include page source, or current page source otherwise\n const firstParent = elem.closest('div[data-included-from], span[data-included-from]');\n const originalSrc = firstParent.attr('data-included-from') || self.pageConfig.sourcePath;\n const originalSrcFolder = path.dirname(originalSrc);\n const resolvedResourcePath = path.resolve(originalSrcFolder, src);\n\n self.pluginSourceFiles.add(resolvedResourcePath);\n });\n });\n }\n });\n\n return content;\n }", "function showFiles(container, samplePath, filesGlob) {\n // get current container\n var $ = cheerio.load(container);\n var filesCollection = filesGlob.split(','),\n sampleFiles = [];\n for (var i = 0; i < filesCollection.length; i++) {\n sampleFiles.push(samplePath + '/' + filesCollection[i]);\n }\n var patterString = sampleFiles.toString();\n // get the glob pattern from file arguments\n var globPattern = sampleFiles.length > 1 ? '{' + patterString + '}' : patterString;\n var files = glob.sync(globPattern);\n // append the ul for source tab\n $('.source').html('');\n $('.source').append('<div class=\"ej2-source-tab\"><ul class=\"nav nav-tabs\"></ul></div>');\n var active = 'active',\n hidden = '';\n // create source content for code snippets\n for (var i = 0; i < files.length; i++) {\n var fileName = path.basename(files[i]);\n var fileAttr = fileName.split('.').join('-');\n var fileType = types[path.extname(files[i])]\n var type = fileType ? fileType : 'javascript';\n var hlContent = renderCodeSnippets('```' + type + '\\n' + fs.readFileSync(files[i], 'utf8') + '\\n```');\n if (i > 0) {\n active = '';\n hidden = 'ej2-hidden';\n }\n // append the li to ul element\n var li = '<li class=\"' + active + ' ej2-source-li\" for=\"' + fileAttr + '\"><a data-toggle=\"tab\">' + fileName + '</a></li>';\n $('.ej2-source-tab .nav-tabs').append(li);\n // append the source content with highlight.js format in the container\n $('.ej2-source-tab').append('<div class=\"ej2-source-content ' + hidden + ' ' + fileAttr + '\">' + hlContent + '</div>');\n }\n return $.html();\n}", "function expand(filePath, requiredFiles) {\n requiredFiles = requiredFiles || {};\n\n if(requiredFiles[filePath]) {\n this.lineConcat.add(filePath, '', null, 0);\n return;\n } // just return if already required\n\n requiredFiles[filePath] = true;\n\n var lines = String(fs.readFileSync(filePath)).split(/\\n/);\n\n lines.forEach(function(line, index) {\n var match = line.match(DIRECTIVE_REGEX);\n\n if(match) {\n var dirFiles = getFiles(filePath, match);\n\n dirFiles.forEach(function(dirFile) {\n expand(dirFile, requiredFiles);\n });\n }\n else {\n this.lineConcat.add(filePath, line, null, index);\n }\n });\n this.lineConcat.add(filePath, '', null, lines.length);\n}", "replaceSectionContent(\n filePath,\n sectionHeader,\n includePatternToReplace,\n includePatternToReplaceWith,\n conversionStep\n ) {\n if (fs.existsSync(filePath) && fs.lstatSync(filePath).isFile()) {\n let sectionFlag = false;\n let replacedFlag = false;\n let sectionIndentation = 0;\n\n let fileContentsArray =\n this.fileOpsUtil.getFileContentsArray(filePath);\n let returnContent = \"\";\n\n logger.info(\n \"Single File Converter: Replacing pattern :\" +\n includePatternToReplace +\n \" with pattern :\" +\n includePatternToReplaceWith +\n \" in file:\" +\n filePath\n );\n // iterate over the contents of the file and check for variables to replace\n fileContentsArray.forEach((line) => {\n let trimmedLine = line.trim();\n // remove any contents in the given section\n // and replace with given include statements as applicable\n if (trimmedLine.startsWith(sectionHeader)) {\n sectionIndentation = line.length - trimmedLine.length;\n sectionFlag = true;\n returnContent += line;\n returnContent += os.EOL;\n } else if (sectionFlag) {\n // if section is found, replace the include statements within of the section\n if (\n trimmedLine.startsWith(includePatternToReplace) &&\n !replacedFlag\n ) {\n replacedFlag = true;\n returnContent +=\n line.substring(\n 0,\n line.length - trimmedLine.length\n ) +\n includePatternToReplaceWith +\n os.EOL;\n console.info(\n \"Single File Converter: Replaced include statement \" +\n trimmedLine +\n \" of \" +\n sectionHeader +\n \" section with include statement in file \" +\n filePath\n );\n let conversion_operation = new ConversionOperation(\n commons_constants.ACTION_REPLACED,\n filePath,\n \"Replaced include statement '\" +\n trimmedLine +\n \"' in section '\" +\n sectionHeader +\n \"' with '\" +\n includePatternToReplaceWith +\n \"'\"\n );\n conversionStep.addOperation(conversion_operation);\n } else if (\n trimmedLine === Constants.CLOSE_CURLY_BRACE &&\n line.length - trimmedLine.length === sectionIndentation\n ) {\n sectionFlag = false;\n returnContent += line + os.EOL;\n } else {\n returnContent += line + os.EOL;\n }\n } else {\n returnContent += line + os.EOL;\n }\n });\n fs.writeFileSync(filePath, returnContent);\n }\n }", "async function getSrcFiles() {\n const result = []\n const files = await treeToList(SRC_DIR)\n for (const f of files) {\n if (!f.file) continue\n const isTS = f.file.endsWith('.ts') && !f.file.endsWith('.d.ts')\n const isVUE = f.file.endsWith('.vue')\n if (!isTS && !isVUE) continue\n\n const srcPath = path.join(f.dir, f.file)\n const outDir = path.join(OUTPUT_DIR, f.dir.replace(NORM_SRC_DIR, ''))\n const outFile = isTS ? f.file.slice(0, -3) + '.js' : f.file + '.js'\n const outPath = path.join(outDir, outFile)\n\n result.push({ srcDir: f.dir, srcFile: f.file, srcPath, outDir, outFile, outPath, isTS, isVUE })\n }\n\n return result\n}", "async function copyStyles() {\n const paths = await globby(`${source}/**/*.scss`);\n\n paths.forEach(async file => {\n const base = path.parse(file).base;\n const dest = path.parse(file).dir.replace(source, destination);\n\n await fs.ensureDir(dest);\n await fs.copyFile(file, `${dest}/${base}`);\n });\n}", "function findjQMFiles(jQuerySourceFolder) \n{\n\tvar inCurrentSite = false; // the jQuery files are located within the current site if this is true\n\t\n\tif (jQuerySourceFolder != \"\") {\n\t\t//Add trailing slash if non-existent.\n\t\tif (jQuerySourceFolder[jQuerySourceFolder.length-1] != '/') {\n\t\t\tjQuerySourceFolder += \"/\";\n\t\t}\n\n\t\tif (isInCurrentSite(jQuerySourceFolder)) { // the user selected a folder inside the current site\n\t\t\tsiteRelativePath = dw.absoluteURLToDocRelative(jQuerySourceFolder, dw.getSiteRoot(), jQuerySourceFolder);\n\t\t\tinCurrentSite = true;\n\t\t} else {\n\t\t\tinCurrentSite = false;\n\t\t\tsiteRelativePath = getFolderName(jQuerySourceFolder);\n\t\t}\n\t\t\n\t\tvar i;\n\t\tvar fileMask = \"*.js\";\n\t\tvar jQMJSFile = null;\n\t\tvar jQueryJSFile = null;\n\t\tvar jQMcssFile = null;\n\t\tvar jQMIcons = null;\n\t\t\n\t\t//Arrays to hold file matches.\n\t\tvar jqmFullAssets = [];\n\t\tvar jqmMinAssets = [];\n\t\tvar jqFullAssets = [];\n\t\tvar jqMinAssets = [];\n\t\t\n\t\t//Variables for list element usage.\n\t\tvar listItem, listLen;\n\t\t\n\t\t// look for all *.js files\n\t\tvar list = DWfile.listFolder(jQuerySourceFolder + \"/\" + fileMask, \"files\");\n\t\tif (list) {\n\t\t\tlistLen = list.length;\n\t\t\tfor (i = 0; i < listLen; i++) {\n\t\t\t\tlistItem = list[i];\n\t\t\t\t//Look for minified versions first.\n\t\t\t\tif (validFileName(listItem, 'js', true))\n\t\t\t\t\tjqmMinAssets.push(listItem);\n\t\t\t\telse if (validFileName(listItem, 'js', false))\n\t\t\t\t\tjqmFullAssets.push(listItem);\n\t\t\t\t// match first form jquery.moble(.*).js if we don't find mobile then look for jquery(.*).js\n\t\t\t\telse if (validFileName(listItem, 'jq', true))\n\t\t\t\t\tjqMinAssets.push(listItem);\n\t\t\t\telse if (validFileName(listItem, 'jq', false))\n\t\t\t\t\tjqFullAssets.push(listItem);\n\t\t\t}\n\t\t}\n\t\t\n\t\t//Pick JS files if any.\n\t\tjQMJSFile = pickSourceFile(jQMJSFile, jqmMinAssets, jqmFullAssets);\n\t\tjQueryJSFile = pickSourceFile(jQueryJSFile, jqMinAssets, jqFullAssets);\n\t\t\n\t\t//Reset jqm arrays for reuse.\n\t\tjqmFullAssets = [];\n\t\tjqmMinAssets = [];\n\n\t\t// look for all *.css files to \n\t\tfileMask = \"*.css\";\n\t\tlist = DWfile.listFolder(jQuerySourceFolder + \"/\" + fileMask, \"files\");\n\t\tvar splitCSS = settings.cssType == SPLIT_CSS;\n\t\tif (list) {\n\t\t\tvar cssType;\n\t\t\t\n\t\t\t//Look for structure or single CSS file as main CSS depending on the CSS type.\n\t\t\tif (splitCSS) {\n\t\t\t\tcssType = \"structure\";\n\t\t\t\tvar cssFiles = list;\n\t\t\t} else {\n\t\t\t\tcssType = \"css\";\n\t\t\t}\n\t\t\t\n\t\t\t//Set corresponding preference string.\n\t\t\tsetPrefStrings(settings.cssType);\n\t\t\t\n\t\t\tlistLen = list.length;\n\t\t\tfor (i = 0; i < listLen; i++) {\n\t\t\t\tlistItem = list[i];\n\t\t\t\t//Check for minified over unminified CSS file.\n\t\t\t\tif (validFileName(listItem, cssType, true))\n\t\t\t\t\tjqmMinAssets.push(listItem);\n\t\t\t\telse if (validFileName(listItem, cssType, false))\n\t\t\t\t\tjqmFullAssets.push(listItem);\n\t\t\t}\n\t\t}\n\t\t\n\t\t//Pick CSS file if any.\n\t\tjQMcssFile = pickSourceFile(jQMcssFile, jqmMinAssets, jqmFullAssets);\n\t\t\n\t\t//Copy image folder.\n\t\tfileMask = \"*.png\";\n\t\tlist = DWfile.listFolder(jQuerySourceFolder + localIconDir + fileMask, \"files\");\n\n\t\tif (list != \"\") {\n\t\t\t//Get parent folder of images directory.\n\t\t\tvar dirNames = jQuerySourceFolder.split(\"/\");\n\t\t\tjQMIcons = dirNames[dirNames.length-2] + '/' + localIconDir;\n\t\t}\n\t\t\n\t\t//Did we find all the files?\n\t\tif (jQMJSFile && jQueryJSFile && jQMcssFile) {\n\t\t\tvar confirmDialog = true;\n\t\t\t//Are any of the files in our current site?\n\t\t\tif (!inCurrentSite) {\n\t\t\t\tmessage = getStatusMessage(\"success\", jQMJSFile, jQMcssFile, jQueryJSFile);\n\t\t\t\tmessage += dw.loadString(\"Commands/jQM/files/alert/fileNoExist\") + \"\\n\\n\";\n\t\t\t\t\n\t\t\t\tconfirmDialog = confirm(message);\n\t\t\t}\n\t\t\t\n\t\t\t//Don't update path if user cancels\n\t\t\tif (confirmDialog) {\n\t\t\t\t/** For each of the files, set the corresponding fields to match preference information.\n\t\t\t\t\tAlso, update the input field with file name. */\n\t\t\t\tvar resourcePrefs = jQM.Utils.prefStrings.resourceStrings;\n\t\t\t\t\n\t\t\t\tif (jQMJSFile) {\n\t\t\t\t\tsettings.JQMJS_LOCATION_FIELD.value = siteRelativePath + jQMJSFile;\n\t\t\t\t\tsettings.JQM_JS_DEST = settings.JQMJS_LOCATION_FIELD.value;\n\t\t\t\t\tsettings.JQM_JS_SOURCE = jQuerySourceFolder + jQMJSFile;\n\t\t\t\t\tdw.setPreferenceString(PREF_SECTION, resourcePrefs.jsSrcPref, settings.JQM_JS_SOURCE);\n\t\t\t\t\tdw.setPreferenceString(PREF_SECTION, resourcePrefs.jsDestPref, settings.JQM_JS_DEST);\n\t\t\t\t}\n\t\t\t\tif (jQueryJSFile) {\n\t\t\t\t\tsettings.JQ_LOCATION_FIELD.value = siteRelativePath + jQueryJSFile;\n\t\t\t\t\tsettings.JQ_JS_DEST = settings.JQ_LOCATION_FIELD.value;\n\t\t\t\t\tsettings.JQ_JS_SOURCE = jQuerySourceFolder + jQueryJSFile;\n\t\t\t\t\tdw.setPreferenceString(PREF_SECTION, resourcePrefs.jqSrcPref, settings.JQ_JS_SOURCE);\n\t\t\t\t\tdw.setPreferenceString(PREF_SECTION, resourcePrefs.jqDestPref, settings.JQ_JS_DEST);\n\t\t\t\t}\n\t\t\t\tif (jQMcssFile) {\n\t\t\t\t\tsettings.JQMCSS_LOCATION_FIELD.value = siteRelativePath + jQMcssFile;\n\t\t\t\t\tsettings.JQM_CSS_DEST = settings.JQMCSS_LOCATION_FIELD.value;\n\t\t\t\t\tsettings.JQM_CSS_SOURCE = jQuerySourceFolder + jQMcssFile;\n\t\t\t\t\tdw.setPreferenceString(PREF_SECTION, resourcePrefs.cssSrcPref, settings.JQM_CSS_SOURCE);\n\t\t\t\t\tdw.setPreferenceString(PREF_SECTION, resourcePrefs.cssDestPref, settings.JQM_CSS_DEST);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//Do the same for the library source folder.\n\t\t\t\tsettings.JQ_LIB_SOURCE_FIELD.value = jQuerySourceFolder;\n\t\t\t\tdw.setPreferenceString(PREF_SECTION, resourcePrefs.jqLibSrcPref, settings.JQ_LIB_SOURCE_FIELD.value);\n\t\t\t\t\n\t\t\t\t//Again with the icons to preserve directory name. Throw an alert if not found.\n\t\t\t\tif (jQMIcons) {\n\t\t\t\t\tdw.setPreferenceString(PREF_SECTION, resourcePrefs.jqImgSrcPref, jQMIcons);\n\t\t\t\t} else {\n\t\t\t\t\talert(dw.loadString(\"Commands/jQM/files/alert/imageNoExist\"));\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t//Some files are not found.\n\t\t\tvar ok = dw.loadString(\"Commands/jQM/files/alert/OK\");\n\t\t\tvar notFound = dw.loadString(\"Commands/jQM/files/alert/notFound\");\n\t\t\t\n\t\t\tvar jsError = jQMJSFile ? ok : notFound;\n\t\t\tvar cssError = jQMcssFile ? ok : notFound;\n\t\t\tvar jqError = jQueryJSFile ? ok : notFound;\n\t\t\n\t\t\tmessage = getStatusMessage(\"error\", jsError, cssError, jqError);\n\t\t\talert(message);\n\t\t}\n\t}\n}", "function processSSI() {\n\tvar inputDirectory = paths.html.src;\n\tvar outputDirectory = paths.html.dest;\n\tvar matcher = \"/**/*.html\";\n\n\tvar includes = new ssi(inputDirectory, outputDirectory, matcher, true);\n\tincludes.compile();\n}", "function fileincludeTask(cb) {\n return src(['./src/*.html'])\n .pipe(fileinclude({\n prefix: '@@',\n basepath: '@file'\n }))\n .pipe(gulp.dest('./public'))\n .pipe(browserSync.stream());\n cb();\n}", "function copy_src(){\n return gulp.src(['components/**/*.ts'])\n .pipe(gulp.dest('generated'));\n}", "function loadOptionsAndGlobals() {\r\t\"use strict\";\r\t\r\tvar parentFolder,\r\t\toptionsText,\r\t\tglobalsText,\r\t\ttextStream,\r\t\tskipFilesText;\r\t\r\t//get the parent folder path\r\tparentFolder = new File(module.filename).parent.path;\r\t\r\t//yank in the options\r\ttextStream = new TextStream(parentFolder + \"jslint_options.json\");\r\toptionsText = textStream.read(0);\r\ttextStream.close();\r\tjslint_options = JSON.parse(optionsText);\r\t\r\t//yank in the globals\r\ttextStream = new TextStream(parentFolder + \"jslint_globals.json\");\r\tglobalsText = textStream.read(0);\r\ttextStream.close();\r\tjslint_options.predef = JSON.parse(globalsText);\r\t\r\t//also load the skip files\r\ttextStream = new TextStream(parentFolder + \"skip_files.json\");\r\tskipFilesText = textStream.read(0);\r\ttextStream.close();\r\tskipFiles = JSON.parse(skipFilesText);\r\t\r}", "function generar_docs() {\n return src(\"./scss/styles.scss\")\n .pipe(sassdoc(doc_options));\n}", "processInputDocument(doc) {\n if (!this.documentIsPublishable(doc)) {\n this.unpublishable.push(doc._id)\n }\n const rewritten = prepareDocument(doc)\n if (doc._type == 'lyra.imageAsset' || doc._type == 'lyra.fileAsset') {\n this.filesToCopy.push({\n from: doc.path,\n to: rewritten.path\n })\n }\n const ids = findRefs(rewritten)\n this.queueIds(ids)\n this.output[doc._id] = rewritten\n }", "collectIncludedFiles(dependencies) {\n dependencies.forEach(dependency => this.includedFiles.add(dependency.to));\n }", "async function listSources(appDir, sourcesConfig) {\n const globs = (sourcesConfig || ['**/*']).concat('!node_modules', '!.env');\n return globby_1.sync(globs, { gitignore: true, cwd: appDir });\n}", "function createDistCopyList(args) {\n //var repoDirectory = assert(args.repoDirectory);\n var distTempDirectory = assert(args.distTempDirectory);\n var outputDirectory = assert(args.outputDirectory);\n var res = [];\n\n res = res.concat(getSourceFiles());\n res = res.concat(getConfigFiles(args));\n res = res.concat(getToolsFiles());\n res = res.concat(getDebuggerFiles());\n res = res.concat(getPolyfillsFiles());\n res = res.concat(getExamplesFiles());\n res = res.concat(getExtrasFiles());\n res = res.concat(getToplevelFiles());\n res = res.concat(getLicensesFiles());\n\n // Special files prepared through temp files (absolute paths).\n res.push({\n source: pathJoin(distTempDirectory, 'Makefile.sharedlibrary'),\n target: pathJoin(outputDirectory, 'Makefile.sharedlibrary'),\n ignoreGitCheck: true\n });\n res.push({\n source: pathJoin(distTempDirectory, 'README.rst'),\n target: pathJoin(outputDirectory, 'README.rst'),\n ignoreGitCheck: true\n });\n res.push({\n source: pathJoin(distTempDirectory, 'duk_debug_meta.json'),\n target: pathJoin(outputDirectory, 'debugger', 'duk_debug_meta.json'),\n ignoreGitCheck: true\n });\n\n // Releases metadata is only updated in master. It's not included in the\n // dist to make maintenance fixes easier to make.\n\n return res;\n}", "function loadSources(sources, sourceOptions, excludeSources) {\n\t\tconst includedSources = Object.keys(sources).filter((sourceKey) =>\n\t\t\texcludes(excludeSources, sourceKey),\n\t\t)\n\t\tconst sourceGetters = Array(includedSources.length)\n\t\t// Using `forEachWithBreaks` allows asynchronous sources to complete between synchronous sources\n\t\t// and measure the duration correctly\n\t\tforEachWithBreaks(includedSources, (sourceKey, index) => {\n\t\t\tsourceGetters[index] = loadSource(sources[sourceKey], sourceOptions)\n\t\t})\n\t\treturn async function getComponents() {\n\t\t\t// Add the keys immediately to keep the component keys order the same as the source keys order\n\t\t\tconst components = {}\n\t\t\tfor (const sourceKey of includedSources) {\n\t\t\t\tcomponents[sourceKey] = undefined\n\t\t\t}\n\t\t\tconst componentPromises = Array(includedSources.length)\n\t\t\tfor (;;) {\n\t\t\t\tlet hasAllComponentPromises = true\n\t\t\t\tawait forEachWithBreaks(includedSources, (sourceKey, index) => {\n\t\t\t\t\tif (!componentPromises[index]) {\n\t\t\t\t\t\t// `sourceGetters` may be incomplete at this point of execution because `forEachWithBreaks` is asynchronous\n\t\t\t\t\t\tif (sourceGetters[index]) {\n\t\t\t\t\t\t\tconst componentPromise = sourceGetters[\n\t\t\t\t\t\t\t\tindex\n\t\t\t\t\t\t\t]().then(\n\t\t\t\t\t\t\t\t(component) =>\n\t\t\t\t\t\t\t\t\t(components[sourceKey] = component),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tsuppressUnhandledRejectionWarning(componentPromise)\n\t\t\t\t\t\t\tcomponentPromises[index] = componentPromise\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\thasAllComponentPromises = false\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tif (hasAllComponentPromises) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tawait wait(1) // Lets the source load loop continue\n\t\t\t}\n\t\t\tawait Promise.all(componentPromises)\n\t\t\treturn components\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is called when the user selects the add location button Function: addToCache() Authors: Luke Waldren, Raymond Fu, Taylah Lucas, Abe Lawson. Since: 14/5/2016 Modified: 29/05/2016 Param list: Return list: Description: this function passes all the data that will be stored into the addlocation function. Precondition: must have a valid API key, longitude, latitude and date (in the correct format). Must also have a working internet connection. Postcondition: none. Input : latitude, longitude, nickname, formattedAddress Output: none
function addToCache() { var lat = tempResults[0].geometry.location.lat(); var lng = tempResults[0].geometry.location.lng(); var nickname = document.getElementById("nickname").value; var formattedAddress = tempResults[0].formatted_address if (nickname == "") { nickname = formattedAddress; } var locationCacheInstance = new LocationWeatherCache(); locationCacheInstance.addLocation(lat, lng, nickname); }
[ "function addMarker(cache)\n{\n\ticonOptions.iconUrl = RESOURCES_DIR + cache.kind + \".png\";\n\ticonOptions.shadowUrl = RESOURCES_DIR + (cache.status == \"A\" \n && filters[\"Archived\"]\n && document.getElementById(\"datepicker\").value >= cache.last_log\n ? \"Archived\" : \"Alive\") + \".png\";\n\tvar marker = L.marker([cache.latitude, cache.longitude], {icon: L.icon(iconOptions)});\n markers.push(marker);\n\tmarker\n\t\t.bindPopup(\"<b>Code</b>: \" + cache.code + \"<br />\" +\n \"<b>Owner</b>: \" + cache.owner + \"<br />\" +\n \"<b>Latitude</b>: \" + cache.latitude + \"<br />\" +\n \"<b>Longitude</b>: \" + cache.longitude + \"<br />\" +\n \"<b>Altitute</b>: \" + cache.altitude + \"<br />\" +\n \"<b>Kind</b>: \" + cache.kind + \"<br />\" +\n \"<b>Size</b>: \" + cache.size + \"<br />\" +\n \"<b>Difficulty</b>: \" + cache.difficulty + \"<br />\" +\n \"<b>Terrain</b>: \" + cache.terrain + \"<br />\" +\n \"<b>Favorites</b>: \" + cache.favorites + \"<br />\" +\n \"<b>Founds</b>: \" + cache.founds + \"<br />\" +\n \"<b>Not_Founds</b>: \" + cache.not_founds + \"<br />\" +\n \"<b>State</b>: \" + cache.state + \"<br />\" +\n \"<b>County</b>: \" + cache.county + \"<br />\" +\n \"<b>Publish</b>: \" + cache.publish + \"<br />\" +\n \"<b>Status</b>: \" + cache.status + \"<br />\" +\n \"<b>Last_Log</b>: \" + cache.last_log + \"<br />\")\n\t\t\t.bindTooltip(cache.name)\n\t\t\t\t.addTo(map);\n}", "function addAddressToRoute(){\n\tvar place = autocomplete.getPlace();\n\n\tif(place === undefined) { //Could not find a place associated with provided address.\n\t\t//TODO replace this with something less terrible\n\t\talert(\"Unable to locate provided address\");\n\t\treturn;\n\t}\n\n\tis_new_place = true;\n\tfor(var i = 0; i < route[\"places\"].length; i++){\n\t\tif (route.places[i].place_id == place.place_id) { \n\t\t\tis_new_place = false; \n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (is_new_place){\n\t\troute.places.push(place);\n updateWeather(place.geometry.location.lat(), place.geometry.location.lng());\n\t}\n\n\tupdateRoute();\n\n // Clear the input field.\n $(\"#autocomplete\").val(\"\");\n}", "function addMarker(location, map) {\n // Add the marker at the clicked location, and add the next-available label\n // from the array of alphabetical characters.\n const marker = new google.maps.Marker({\n position: location,\n label: labels[labelIndex++ % labels.length],\n map: map,\n })\n markers.push(marker)\n\n const location_input = locationInput.value\n const issue_input = issueInput.value\n const map_label = labels_form[labelIndexForm++ % labels_form.length]\n\n // Get current time and convert from 24 hours to AM/PM\n const date = new Date()\n const hours = date.getHours()\n const minutes = date.getMinutes()\n const seconds = date.getSeconds()\n let hours_format = \"AM\"\n let hours_non_military = hours\n let time = `${hours_non_military}:${minutes}:${seconds} ${hours_format}`\n if(hours > 12) {\n hours_non_military = hours - 12\n hours_format = 'PM'\n time = `${hours_non_military}:${minutes}:${seconds} ${hours_format}`\n }\n if(hours == 12) {\n hours_format = 'PM'\n time = `${hours_non_military}:${minutes}:${seconds} ${hours_format}`\n }\n if(hours == 0) {\n hours_non_military = 12\n time = `${hours_non_military}:${minutes}:${seconds} ${hours_format}`\n }\n if(seconds < 10) {\n let seconds_leading_zero = \"0\" + seconds\n time = `${hours_non_military}:${minutes}:${seconds_leading_zero} ${hours_format}`\n }\n\n const months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"]\n const date_1 = date.getDate()\n const month = months[date.getMonth()]\n const year = date.getFullYear()\n let date_now = `${date_1} ${month} ${year}`\n\n // Creates new paragraph for form input and assigns id\n const form_display = document.createElement('p')\n form_display.id = `input${inputIndex}`\n // Creates new button and assigns id and class\n const delete_button = document.createElement('button')\n delete_button.id = `input${inputIndex}`\n delete_button.className = '.remove-button'\n\n // Displays form input data in html page\n form_display.innerHTML = `Marker: ${map_label}<br> Date: ${date_now}<br> Time: ${time}<br> Location: ${location_input}<br> Issue: ${issue_input}`\n document.querySelector('#reported-issues').appendChild(form_display)\n // Adds a name to the created button\n delete_button.innerHTML = `Remove`\n document.querySelector('#reported-issues').appendChild(delete_button)\n\n // Displays form input data in feeds page\n const feed_update_display = document.createElement('P')\n feed_update_display.innerHTML = `${time}: A new issue has been reported in ${location_input}!`\n document.querySelector('#feed-updates').appendChild(feed_update_display)\n\n // Increments form_display and delete_button id by 1\n inputIndex++\n}", "function addToMap(address){\n\tgeocoder.geocode({'address': address}, function(results, status) {\n\t\t\tif (status == google.maps.GeocoderStatus.OK) {\n\t\t\t\tactiveCounter++;\n\t\t\t\tvar fullAddress = results[0].formatted_address;\n\t\t\t\tvar addressType = results[0].address_components[0].types[0];\n\t\t\t\tvar addrLat = results[0].geometry.location.lat();\n\t\t\t\tvar addrLong = results[0].geometry.location.lng();\n\t\t\t\taddMarker(fullAddress, addrLat, addrLong);\n\t\t\t} else {\n\t\t\t\talert(\"Could not find location: \" + location);\n\t\t\t}\n\t });\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 updatePlacesLocationInformation() {\n\tupdatePlacesLocationInformationFromCategory(\"\", \"All Categories\");\n}", "function addMarker(rest_add,count){\n var address = rest_add;\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n var marker = new google.maps.Marker({\n map: map,\n position: results[0].geometry.location,\n icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+ (count+1) +'|e74c3c|000000'\n });\n markers.push(marker);\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n\n}", "function addLocation() {\n\n personAwardLogic.addLocation($scope.awardLocation, personReferenceKey).then(function (response) {\n\n var locationId = null;\n if (appConfig.APP_MODE == 'offline') {\n locationId = response.insertId;\n } else {\n\n locationId = response.data.InsertId;\n }\n\n addPersonAward(locationId);\n\n }, function (err) {\n appLogger.error('ERR' + err);\n });\n }", "function saveLocations()\n{\n // We save the locations object to local storage.\n localStorage.setItem(APP_PREFIX + \"-locations\", locationWeatherCache.toJSON())\n}", "function addToCache( distillation ) {\n\n\t\tvar cache = window.localStorage.getItem( \"cache\" );\n\t\tif ( cache == null || cache == \"null\" ) {\n\t\t\tcache = [];\n\t\t}\n\t\telse {\n\t\t\tcache = JSON.parse( cache );\n\t\t\tcache.push( distillation );\n\t\t}\n\n\t\twindow.localStorage.setItem( \"cache\", JSON.stringify( cache ) );\n\t}", "function createMarker(place, map) {\n var infowindow = new google.maps.InfoWindow();\n const newrequest = {\n placeId: place.place_id,\n fields: [\"name\", \"formatted_address\", \"place_id\", \"geometry\",\"website\",\"opening_hours\",\"formatted_phone_number\",\"business_status\"],\n };\n const newservice = new google.maps.places.PlacesService(map);\n \n\n const bounds = new google.maps.LatLngBounds();\n const placesList = document.getElementById(\"places\");\n \n const image = {\n url: \"http://maps.google.com/mapfiles/ms/micons/restaurant.png\",\n size: new google.maps.Size(71, 71),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(17, 34),\n scaledSize: new google.maps.Size(25, 25),\n };\n\n const marker =new google.maps.Marker({\n map,\n icon: image,\n title: place.name,\n position: place.geometry.location,\n });\n\n \n\n marker.addListener(\"click\", () => {\n map.setZoom(17);\n map.setCenter(marker.getPosition());\n\n newservice.getDetails(newrequest, (newplace, newstatus) => {\n if (newstatus === google.maps.places.PlacesServiceStatus.OK) {\n google.maps.event.addListener(marker, \"click\", function () {\n infowindow.setContent(\n \"<div><strong>\" +\n newplace.name +\n \"</strong><br><br>\" +\n \"Business Status: \" +\n newplace.business_status +\n \"<br>\" +\n \"<br>\" +\n newplace.formatted_address +\n \"</div><br>\"+\n \"Opening Hours: \" +\n newplace.opening_hours.weekday_text +\n \"<br>\" +\n \"<br>\" +\n \"Phone: \" +\n newplace.formatted_phone_number +\n \"<br>\"+\n \"<br>\" +\n \"<a href =\" +newplace.website +\" >Check Us Out Online</a>\"+\n \"<br>\" \n );\n \n infowindow.open(map, this);\n });\n }\n });\n\n });\n\n //Places Buttons\n const placesbutton = document.createElement(\"button\");\n placesbutton.textContent = place.name;\n placesbutton.setAttribute(\"class\", \"m-1 btn btn-warning\");\n placesbutton.onclick = function(){\n map.setZoom(17);\n map.setCenter(marker.getPosition());\n infowindowpopup(newservice, newrequest, infowindow, map, marker);\n \n };\n placesList.appendChild(placesbutton);\n bounds.extend(place.geometry.location);\n\n}", "function autoCompleteForPickupLocation(element){\r\t\tvar inputPickupLocation = element;\r\t\t//var inputDropoffLocation = element;\r\t\t\r\t\t//Autocomplete for pickup location \r\t\tvar mapForPickupLocation = new google.maps.Map(inputPickupLocation, {\r\t\t\tcenter: {lat: 37.1, lng: -95.7},\r\t\t\tzoom: 13\r\t\t});\r\r\t\tvar autoCompleteForPickupLocation = new google.maps.places.Autocomplete(inputPickupLocation);\r\t\tautoCompleteForPickupLocation.bindTo('bounds', mapForPickupLocation);\r\t\tautoCompleteForPickupLocation.setComponentRestrictions({country: \"us\"});\r\t\t\r\t\t\r\t\t//Autocomplete for Dropoff location \r\t\t/* var mapForDropoffLocation = new google.maps.Map(inputDropoffLocation, {\r\t\t\tcenter: {lat: 37.1, lng: -95.7},\r\t\t\tzoom: 13\r\t\t});\r\r\t\tvar autoCompleteForDropoffLocation = new google.maps.places.Autocomplete(inputDropoffLocation);\r\t\tautoCompleteForDropoffLocation.bindTo('bounds', mapForDropoffLocation);\r\t\tautoCompleteForDropoffLocation.setComponentRestrictions({country: \"us\"}); */\r\t}", "function processAddress()\n{\n\tvar address = getAddress();\n\n\t//creating a geocoder object\n\tvar geocoder = new google.maps.Geocoder();\n\n\tgeocoder.geocode({'address': address}, function(results, status)\n\t{\n\t\t//If this was successful, then...\n\t\tif (status === 'OK')\n\t\t{\n\t\t\t//get the latitude and longitude: Note this is part of what I would store to the database or session\n\t\t\tvar latitude = results[0].geometry.location.lat();\n\t\t\tvar longitude = results[0].geometry.location.lng();\n\t\t\tsetMarker(results[0].geometry.location);\n\t\t\tsaveUserLocation(address, latitude, longitude);\n\t\t} else if (status==\"ZERO_RESULTS\")\n\t\t{\n\t\t\t//get the latitude and longitude in case when coordinates are provided in the address field and set the marker as well as string to the database or session\n\t\t\tvar location=address.replace(/[()]/g, '').split(',');\n\t\t\tvar latitude = location[0];\n\t\t\tvar longitude = location[1];\n\t\t\tvar new_location = {lat: parseFloat(latitude), lng: parseFloat(longitude)};\n\t\t\tsetMarker(new_location);\n\t\t\tsaveUserLocation(address, latitude, longitude);\n\t\t} else \n\t\t{\n\t\t\tconsole.error('Geocode was not successful for the following reason: ' + status);\n\t\t}\n\t});\n}", "function add(){\n var zip = document.getElementById('zip-input').value;\n //this is some black magic for checking zip codes\n var val_zip = /(^\\d{5}$)|(^\\d{5}-\\d{4}$)/.test(zip.toString());\n if(val_zip){\n if(!setting){\n store_zip(zip,function (err) {\n if(err){\n console.log('Error: unable to save location');\n }\n });\n add_dom(zip);\n hide();\n }\n else{\n forecast_zip(zip, function(err) {\n if(err){\n console.log('Error: unable to save location');\n }\n });\n hide();\n }\n }else{\n console.log(\"Error: Invalid zip code.\");\n alert(\"Invalid zip code!\");\n document.getElementById('zip-input').value = \"\";\n }\n}", "function handleAdd() {\n if (selectedTimeZone) {\n let newTimeZones = [...myTimeZones, selectedTimeZone]\n setMyTimeZones(newTimeZones)\n localStorage.setItem(TIME_ZONE_KEY, JSON.stringify(newTimeZones))\n }\n }", "function addAddressToMap(results, status) {\n //map.clearOverlays();\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n marker = new google.maps.Marker({\n map: map,\n position: results[0].geometry.location\n });\n //reverseGeocode(point.y,point.x);\n var CountryNameCode = \"\";\n var i = 0;\n while(results[0].address_components[i])\n {\n if(results[0].address_components[i].types[0] == \"country\")\n {\n CountryNameCode = results[0].address_components[i].short_name;\n break;\n }\n i++;\n }\n var contentString = results[0].formatted_address + '<br/>' +\n '<b>Country code:</b> ' + CountryNameCode;\n\n var infowindow = new google.maps.InfoWindow({content: contentString});\n infowindow.open(map,marker);\n\n } else {\n alert(\"Sorry, we were unable to geocode that address\");\n }\n return;\n }", "updateContactAddress(data){\n console.log(data);\n let _id = '#' + data.recordId; // card identifier\n let mapIcon = '<i class=\"fas fa-map-marker-alt\" aria-hidden=\"true\"></i> ';\n if(data.contact.length){ //set contact if exists\n let name = data.contact[0].firstName;\n $(_id).find('.customer-name').html(name.slice(0,1).toUpperCase() + name.slice(1));\n }\n if(data.addresses){ //set addresses if exists\n let _addresses = data.addresses;\n let _parcels = [];\n let _addressLinks = this.getAddressLinks(_addresses);\n let _addAddresses = '';\n let _firstAddress = typeof _addresses[0] == 'object' ? _addresses[0].streetAddress : _addresses[0];\n if(data.parcels.length){\n _parcels = data.parcels;\n let _firstParcel = _parcels[0].parcelNumber;\n _firstAddress += ` - ${_firstParcel}`;\n }\n if (_addresses.length > 1) { //generate multi address html\n _addAddresses = this.drawAdditionalAddresses(_addresses, _addressLinks, _parcels);\n }\n if(typeof _firstAddress == 'object') //type validation\n _firstAddress = _firstAddress.streetAddress;\n\n $(_id).find('.address-link').html(mapIcon + _firstAddress);\n $(_id).find('.address-link').attr(\"href\", `http://wsitd03/website/DART/StaffMap/index.html?find=${_firstAddress}`);\n $(_id).find('.information-area').after(_addAddresses);\n }\n }", "function init(){\n const address = localStorage.getItem('address')\n if(address){\n userLocation = JSON.parse(address)\n } else {\n geolocalizeUser() \n }\n loadMap(userLocation)\n}", "addEntry (state, args) {\n const cache = state.cache[args.property]\n const turn = state.turns[state.currentTurn]\n turn.push(args.entry)\n\n cache.turn = state.currentTurn\n cache.entryId = args.entry.entryId\n state.entryId++\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace occurences of v1 slot elements with v0 content elements. This does not yet map named slots to content select clauses.
function polyfillSlotWithContent(template) { [].forEach.call(template.content.querySelectorAll('slot'), function (slotElement) { var contentElement = document.createElement('content'); slotElement.parentNode.replaceChild(contentElement, slotElement); }); }
[ "function transformOldSlotSyntax(node) {\n if (!node.children) {\n return;\n }\n\n node.children.forEach((child) => {\n if (_.has(child.attribs, 'slot')) {\n const vslotShorthandName = `#${child.attribs.slot}`;\n child.attribs[vslotShorthandName] = '';\n delete child.attribs.slot;\n }\n });\n}", "function shiftSlotNodeDeeper(node) {\n if (!node.children) {\n return;\n }\n\n node.children.forEach((child) => {\n const vslotShorthandName = getVslotShorthandName(child);\n if (vslotShorthandName && child.name !== 'template') {\n const newSlotNode = cheerio.parseHTML('<template></template>')[0];\n\n const vslotShorthand = `#${vslotShorthandName}`;\n newSlotNode.attribs[vslotShorthand] = '';\n delete child.attribs[vslotShorthand];\n\n newSlotNode.parent = node;\n child.parent = newSlotNode;\n\n newSlotNode.children.push(child);\n\n // replace the shifted old child node with the new slot node\n node.children.forEach((childNode, idx) => {\n if (childNode === child) {\n node.children[idx] = newSlotNode;\n }\n });\n }\n });\n}", "_processNodes(){\n this.shadowRoot\n .querySelector('slot')\n .assignedNodes()\n .forEach((n) => this._processNode(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}", "fillElements() {\n this.replaceTokens(this.tags, CD.params());\n }", "_addSlot() {\n if (this[_value]) {\n this[_fillElement].appendChild(this[_slotElement]);\n } else {\n this[_trackElement].appendChild(this[_slotElement]);\n }\n }", "function slotsChange(e) {\n\t\tlet i= this.id.substring(this.id.indexOf('.')+1);\n\t\t\n\t\t//Otherwise, they are still treated as strings and will run into trouble in double digits.\n\t\tlet oldSlots= parseInt(aSlots[i]);\n\t\tlet newSlots= parseInt(this.value);\n\t\t\n\t\tif (newSlots < oldSlots) {\n\t\t\t//Need to remove some slots! Start from the top.\n\t\t\tfor (let j = oldSlots-1; j >= newSlots; j--) {\n\t\t\t\t\n\t\t\t\tlet obj= oSkills[i][j];\n\t\t\t\tlet span= obj.parentNode;\n\t\t\t\tlet par= span.parentNode;\n\t\t\t\tpar.removeChild(span);\n\t\t\t\t\n\t\t\t\t//If this was a multiple of 3 -- and thus, the first on a new line -- remove the BRs as well.\n\t\t\t\tif ((j%3) == 0) {\n\t\t\t\t\t//Save the now-last child.\n\t\t\t\t\tlet lastChild= par.children[par.children.length-1];\n\t\t\t\t\t// If the now-last child element is a br...\n\t\t\t\t\tif (lastChild.toString() == \"[object HTMLBRElement]\") {\n\t\t\t\t\t\t//Remove it.\n\t\t\t\t\t\tpar.removeChild(lastChild);\n\t\t\t\t\t}\n\t\t\t\t\t//Remove the second one, too.\n\t\t\t\t\tlastChild= par.children[par.children.length-1];\n\t\t\t\t\t// If the now-last child element is a br...\n\t\t\t\t\tif (lastChild.toString() == \"[object HTMLBRElement]\") {\n\t\t\t\t\t\t//Remove it.\n\t\t\t\t\t\tpar.removeChild(lastChild);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (newSlots > oldSlots) {\n\t\t\t//Need to add some slots!\n\t\t\tfor (let j = oldSlots; j < newSlots; j++) {\n\t\t\t\t//Get the parent object.\n\t\t\t\tlet par= O(`skillboxes.${i}`);\n\t\t\t\t\n\t\t\t\tmakeNewSkill(par,i,j);\n\n\t\t\t}\n\t\t}\n\t\taSlots[i]= this.value;\n\t\t\n\t\t//Check for repeat skills and run the update functions.\n\t\tcheckForRepeatSkills();\n\t\tupdateUnused();\n\t\tupdateSP();\n\t}", "addSlotKeys() {\n\t\t\tthis.$slots.default.forEach((item, index) => {\n\t\t\t\titem.key = item.key!=null?item.key:index;\n\t\t\t});\n\t\t}", "function createSlots(slots, dynamicSlots) {\n for (let i = 0; i < dynamicSlots.length; i++) {\n const slot = dynamicSlots[i];\n // array of dynamic slot generated by <template v-for=\"...\" #[...]>\n if ((0,_vue_shared__WEBPACK_IMPORTED_MODULE_1__.isArray)(slot)) {\n for (let j = 0; j < slot.length; j++) {\n slots[slot[j].name] = slot[j].fn;\n }\n }\n else if (slot) {\n // conditional single slot generated by <template v-if=\"...\" #foo>\n slots[slot.name] = slot.key\n ? (...args) => {\n const res = slot.fn(...args);\n // attach branch key so each conditional branch is considered a\n // different fragment\n if (res)\n res.key = slot.key;\n return res;\n }\n : slot.fn;\n }\n }\n return slots;\n}", "function setSelectionsFromSlotValue() {\n\t\t// $log.log(preDebugMsg + \"setSelectionsFromSlotValue\");\n\t\tvar slotSelections = $scope.gimme(\"InternalSelections\");\n\t\tif(typeof slotSelections === 'string') {\n\t\t\tslotSelections = JSON.parse(slotSelections);\n\t\t}\n\n\t\tif(JSON.stringify(slotSelections) == JSON.stringify(internalSelectionsInternallySetTo)) {\n\t\t\t// $log.log(preDebugMsg + \"setSelectionsFromSlotValue got identical value\");\n\t\t\treturn;\n\t\t}\n\n\t\tif(slotSelections.hasOwnProperty(\"selections\")) {\n\t\t\tvar newSelections = [];\n\n\t\t\tif(unique > 0) {\n\t\t\t\tfor(var sel = 0; sel < slotSelections.selections.length; sel++) {\n\t\t\t\t\tvar newSel = slotSelections.selections[sel];\n\t\t\t\t\tvar X1 = newSel.minX;\n\t\t\t\t\tvar X2 = newSel.maxX;\n\n\t\t\t\t\tif(X2 < limits.minX || X1 > limits.maxX) {\n\t\t\t\t\t\t// completely outside\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tX1 = Math.max(limits.minX, X1);\n\t\t\t\t\tX2 = Math.min(limits.maxX, X2);\n\n\t\t\t\t\tvar x1 = legacyDDSupLib.val2pixelX(X1, unique, drawW, leftMarg, limits.minX, limits.maxX);\n\t\t\t\t\tvar x2 = legacyDDSupLib.val2pixelX(X2, unique, drawW, leftMarg, limits.minX, limits.maxX);\n\t\t\t\t\tif(x2 - x1 > 1) {\n\t\t\t\t\t\tnewSelections.push([X1,X2, x1,x2]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// $log.log(preDebugMsg + \"setSelectionsFromSlotValue ignoring selection because it is too small.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// $log.log(preDebugMsg + \"new selections: \" + JSON.stringify(newSelections));\n\t\t\t\tif(newSelections.length > 0) {\n\t\t\t\t\tselections = newSelections;\n\t\t\t\t\tupdateLocalSelections(false);\n\t\t\t\t\tdrawSelections();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // no data\n\t\t\t\tfor(var sel = 0; sel < slotSelections.selections.length; sel++) {\n\t\t\t\t\tvar newSel = slotSelections.selections[sel];\n\t\t\t\t\tvar X1 = newSel.minX;\n\t\t\t\t\tvar X2 = newSel.maxX;\n\n\t\t\t\t\tnewSelections.push([X1,X2, 0,0]);\n\t\t\t\t}\n\t\t\t\tselections = newSelections;\n\t\t\t}\n\t\t}\n\t\tsaveSelectionsInSlot();\n\t}", "removeAllSlots() {\n var size = this.closet_slots_faces_ids.length;\n for (let i = 0; i < size; i++) {\n this.removeSlot();\n }\n }", "function mySlotChange(eventData) {\n\t\t// $log.log(preDebugMsg + \"mySlotChange() \" + eventData.slotName + \" = \" + JSON.stringify(eventData.slotValue));\n\t\t// $log.log(preDebugMsg + \"mySlotChange() \" + eventData.slotName);\n\t\tswitch(eventData.slotName) {\n\t\t\tcase \"SelectAll\":\n\t\t\t\tif(eventData.slotValue) {\n\t\t\t\t\tselectAll();\n\t\t\t\t\t$scope.set(\"SelectAll\",false);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"InternalSelections\":\n\t\t\t\tif(eventData.slotValue != internalSelectionsInternallySetTo) {\n\t\t\t\t\tsetSelectionsFromSlotValue();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"TreatNullAsUnselected\":\n\t\t\t\tupdateLocalSelections(false);\n\t\t\t\tbreak;\n\t\t\tcase \"UsePercent\":\n\t\t\t\tif(eventData.slotValue) {\n\t\t\t\t\tusePercent = true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tusePercent = false;\n\t\t\t\t}\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"FontSize\":\n\t\t\t\tupdateSize();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"DrawingArea:height\":\n\t\t\t\tupdateSize();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"DrawingArea:width\":\n\t\t\t\tupdateSize();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"root:height\":\n\t\t\t\tupdateSize();\n\t\t\t\tparseSelectionColors();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"root:width\":\n\t\t\t\tupdateSize();\n\t\t\t\tparseSelectionColors();\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"UseGlobalColorGradients\":\n\t\t\t\tif(eventData.slotValue) {\n\t\t\t\t\tuseGlobalGradients = true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tuseGlobalGradients = false;\n\t\t\t\t}\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"PluginName\":\n\t\t\t\t$scope.displayText = eventData.slotValue;\n\t\t\t\tbreak;\n\t\t\tcase \"PluginType\":\n\t\t\t\tif(eventData.slotValue != \"VisualizationPlugin\") {\n\t\t\t\t\t$scope.set(\"PluginType\", \"VisualizationPlugin\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"GlobalSelections\":\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"Highlights\":\n\t\t\t\tupdateGraphics();\n\t\t\t\tbreak;\n\t\t\tcase \"GroupColors\":\n\t\t\t\tcolorPalette = null;\n\t\t\t\tparseSelectionColors();\n\t\t\t\tupdateGraphics();\n\t\t\t\tdrawSelections();\n\t\t\t\tbreak;\n\t\t\tcase \"DataValuesSetFilled\":\n\t\t\t\tparseData();\n\t\t\t\tbreak;\n\t\t}\n\t}", "_findInnerSlotInfos() {\n return Array.from(this._dom.querySelectorAll(\"[slotid]\")).map(s => {\n return {\n context: s,\n id: s.getAttribute('slotid')\n }\n });\n }", "function portSlotContent(){\n\tvar content = \"\";\n\tvar a = conterninfor.num\n\tvar addinfo = conterninfor.str\n\tcontent += \"<table \"+addinfo+\" id='tabs-\"+a+\"-slot\"+GlobalSlotId+\"'\";\n\tcontent += \" class='infoshowhide'>\";\n\tcontent += \"<tr><td style='width: 90px;'>\";\n\tcontent += \"<p>Physical port type: <br></td><td><br>\";\n\tcontent += \"<select id='porttypeinfo\"+a+\"' \";\n\tcontent += \"data-mini='true' style='width: 150px;'>\";\n\tcontent += \"<option value=''>Layer 1</option>\";\n\tcontent += \"<option value=''>Layer 2</option>\"\n\tcontent += \"<option value=''>Open Port</option>\";\n\tcontent += \"<option value=''>Direct connect\";\n\tcontent += \"</option></select>\";\n\tcontent += \"</p><br></td><td><br><p>Media type</p><br></td>\";\n\tcontent += \"<td><br><p><select></select></p><br></td>\";\n\tcontent += \"</tr><tr><td><p>Port name: <br></td><td><br>\";\n\tcontent += \"<input id='portnamenumber\"+a+\"' \";\n\tcontent += \"type='text'/></p><br></td>\";\n\tcontent += \"</tr><tr><td style='width: 90px;'><br>\";\n\tcontent += \"<p>Sub chanel</p></td></tr></table>\";\n\treturn content\n}", "function replaceLayerContent(name, content) {\n\t if (isNav4) {\n\t\t var layer = getLayer(name);\n\t\t layer.document.open();\n\t\t layer.document.writeln(content);\n\t\t layer.document.close();\n\t } else if (isIE) {\n\t\t var str = \"document.all.\" + name + \".innerHTML = '\" + content + \"'\";\n\t\t eval(str);\n\t }\n}", "function extUtils_replaceValuesInNodeSegment(nodeSeg, updatePatterns, paramObj)\n{\n var retVal = '';\n var theNode = nodeSeg.node;\n var theStr = extUtils.convertNodeToString(theNode);\n\n if (typeof theStr == \"string\" && theStr.length && theNode.outerHTML)\n {\n var innerLength = dwscripts.getInnerHTML(theNode).length;\n var closeTagPos = dwscripts.getOuterHTML(theNode).lastIndexOf(\"</\");\n var innerStart = closeTagPos - innerLength;\n var tagStart = theStr.substring(0,innerStart);\n var tagInner = theStr.substring(innerStart,closeTagPos);\n var tagEnd = theStr.substring(closeTagPos);\n for (var i=0; i < updatePatterns.length; i++)\n {\n var limitSearch = updatePatterns[i].limitSearch;\n var newParamValue = paramObj[updatePatterns[i].paramName];\n if (updatePatterns[i].pattern) //if there is a pattern, use it to update\n {\n var pattern = eval(updatePatterns[i].pattern);\n if (!limitSearch || limitSearch == \"tagOnly\")\n {\n tagStart = extUtils.safeReplaceBetweenSubExpressions(tagStart, pattern, newParamValue);\n }\n if (!limitSearch || limitSearch == \"innerOnly\")\n {\n var localBeginOffset = nodeSeg.matchRangeMin - innerStart;\n var localEndOffset = nodeSeg.matchRangeMax - innerStart;\n if (localBeginOffset >= 0 && localBeginOffset < localEndOffset && localEndOffset < innerLength)\n {\n var tinyString = tagInner.substring(localBeginOffset, localEndOffset);\n tinyString = extUtils.safeReplaceBetweenSubExpressions(tinyString, pattern, newParamValue);\n tagInner = tagInner.substring(0,localBeginOffset) + tinyString + tagInner.substring(localEndOffset);\n }\n else\n {\n tagInner = extUtils.safeReplaceBetweenSubExpressions(tagInner, pattern, newParamValue);\n }\n }\n if (!limitSearch)\n {\n tagEnd = extUtils.safeReplaceBetweenSubExpressions(tagEnd , pattern, newParamValue);\n }\n }\n else\n {\n if (limitSearch == \"innerOnly\") //innerOnly update pattern, so blow away inner\n {\n tagInner = newParamValue;\n }\n else if (limitSearch == \"tagOnly\") //tag update pattern, so blow away inner\n {\n tagStart = newParamValue;\n }\n else if (!limitSearch) //no update pattern, so blow away whole thing\n {\n tagStart = newParamValue;\n tagInner = \"\";\n tagEnd = \"\";\n }\n }\n }\n retVal = tagStart + tagInner + tagEnd;\n }\n\n return retVal;\n}", "replaceChild() {\n if (this.el) {\n this.el.innerHTML = \"\";\n }\n\n this.isDomified = false;\n this.contents = [];\n this.atts = [];\n this.props = [];\n\n this.appendChild.apply(this, arguments);\n }", "function replace(v){\n v.visible = false\n v.expanded = true\n v.interactive = false\n for(var i in v.nodes_cctree){\n v.nodes_cctree[i].expanded = true\n v.nodes_cctree[i].visible = true\n v.nodes_cctree[i].interactive = true\n }\n for(var i in graphics_cvTocv){\n first = graphics_nodes[graphics_cvTocv[i].nodes[0]]\n last = graphics_nodes[graphics_cvTocv[i].nodes[1]]\n if(first.expanded && last.expanded)\n graphics_cvTocv[i].setAlpha(0.5)\n }\n}", "function fillBox (box, content) {\n\n box.html(content);\n }", "function setSlotForDragandDrop(device){\n\tvar cnt = 0;\n\tif(device.SLOT == null || device.SLOT == undefined || device.SLOT.length == 0){\n\t\tvar slotpath = device.ObjectPath+ \".\" + \"Slot_\"+cnt;\n\t\tvar slotname = \"Slot_\" + cnt;\n\t\tvar devName = (device.ObjectPath).split(\".\")[0];\n\t\tstoreSlotInformation(\"\",\"\",slotname,slotpath,\"\",\"\",\"\",\"\",\"\",device.ObjectPath,\"\",\"\",\"new\",\"\");\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates list of attendees whenever a checkbox is checked or unchecked
function updateAttendees(event) { var attendee_name = $(this).attr("value"); var attendee_email = ""; var contacts_list = JSON.parse(localStorage.getItem("contacts")); for(var count = 0; count < contacts_list.length; count++) { if(contacts_list[count].name === attendee_name) { attendee_email = contacts_list[count].email; break; } } if($(this).prop("checked")) { for(var count = 0; count < attendees.length; count++) { //make sure you don't add duplicates if(attendees[count].name === attendee_name) { return; } } attendees.push({ name: attendee_name, email: attendee_email }); } else { for(var count = 0; count < attendees.length; count++) { //find contact to be removed if(attendees[count].name === attendee_name) { attendees.splice(count, 1); break; } } } updateRecipientLists(); }
[ "function updateEmailMarkList() {\n\tvar isAllChecked = true;\n var chkBoxId = this.name;\n var partialchkBoxId = chkBoxId.substring(0,chkBoxId.indexOf('_'));\n var emailAllDivs = document.getElementsBySelector(\"span.citation-send\");\n\tfor(var i=0;i<emailAllDivs.length;i++){\n\t\tvar emailAll = emailAllDivs[i].getElementsByTagName(\"INPUT\")[0];\n if (\"sendAllEmailOption\" != emailAll.id) {\n var partialId = emailAll.name.substring(0,emailAll.name.indexOf('_'));\n if (partialchkBoxId == partialId) {\n if (emailAll.checked == false){\n isAllChecked = false;\n break;\n }\n }\n }\n }\n\t$(\"#sendAllEmailOption\").attr('checked', isAllChecked);\n}", "function updateEmailAllMarkList()\t{\n var chkBoxId = this.name;\n var partialchkBoxId = chkBoxId.substring(0,chkBoxId.indexOf('_'));\n // Check for total number of Marked & capture the status of each marked Checkboxes.\n\tvar emailAllDivs = document.getElementsBySelector(\"span.citation-send\");\n\tfor(var i=0;i<emailAllDivs.length;i++){\n\t\tvar emailAll = emailAllDivs[i].getElementsByTagName(\"INPUT\")[0];\n if (\"sendAllEmailOption\" != emailAll.id) {\n var partialId = emailAll.name.substring(0,emailAll.name.indexOf('_'));\n if (partialchkBoxId == partialId) {\n if (this.checked ==true) { // If CheckAll is True, makes all of them as Checked.\n emailAll.checked = true;\n } else {\n emailAll.checked = false;\n }\n }\n }\n }\n}", "function modifyUserExtensionList(){\n // console.log(event)\n // target is supposed to make it so it knows which box is being checked I think\n var target = event.target || event.srcElement;\n // if it's not \"extensionList\", then it's one lf the checkboxes\n if(event.target.id != \"extensionList\"){\n // gets the id of the checkbox (NOT EXTENSION) - same as name I'm pretty sure\n var item = document.getElementById(event.target.id)\n // gets the actual ID of the extension - the big long one that looks like\n // a hash or something\n var extensionID = getExtensionID(event.target.id)\n // checks to see if this extension has been added to our user's list already\n // (this variable is local to this file)\n var extensionIndex = userExtensionList.indexOf(extensionID);\n // if the index is -1, it doesn't exist. add it to the list of checked extensions\n if(item.checked && extensionIndex == -1){\n userExtensionList.push(getExtensionID(event.target.id))\n }\n // if it is already in the list, remove it when it's unchcked\n else if(!item.checked && extensionIndex > -1){\n userExtensionList.splice(extensionIndex,1);\n }\n }\n}", "handleCheckboxChange(friendId, event){\n this.setState({ checkboxChecked: event.target.checked});\n if(event.target.checked)\n this.props.addFriendToInviteList(friendId);\n else\n this.props.removeFriendFromInviteList(friendId);\n }", "function updateSelectedInvitationsInput() {\n // Loop through all the invitation checkbox and get the value\n var selectedInvitations = [];\n if (typeof($inputSelectedInvitations) != 'undefined' && $inputSelectedInvitations != null) {\n $('.checkbox-invitation').each(function (i, obj) {\n if(obj.checked) {\n selectedInvitations.push(obj.value);\n }\n });\n // Set the length into the count container\n var selectedInvitationsCount = selectedInvitations.length;\n $('.selected-invitation-container').each(function() {\n $(this).html(selectedInvitationsCount);\n var $button = $(this).closest('button');\n\n // Enable/disable the button based on the count\n if(selectedInvitationsCount <= 0) {\n $button.prop(\"disabled\", true);\n } else {\n $button.prop(\"disabled\", false);\n }\n });\n \n $inputSelectedInvitations.value = JSON.stringify(selectedInvitations);\n }\n }", "function getActiveAttendees(event) {\n if (!event) {\n return;\n }\n\n var attendees = event.attendees,\n num = attendees && attendees.length,\n activeAttendees = event.activeAttendees;\n\n\n !num && (activeAttendees = event.activeAttendees = false);\t// No attendees, no count\n\n if (activeAttendees || activeAttendees === false) { // Did we run already?\n return activeAttendees;\n }\n\n activeAttendees = [];\n for (var i = 0; i < num; ++i) {\n if (!attendees[i].notifyState || attendees[i].notifyState != \"DELETED\") {\n activeAttendees.push(attendees[i]);\n }\n }\n\n return event.activeAttendees = activeAttendees;\n }", "function visibleAttendees(state) {\n let attendees = state.attendees\n let skillsFilters = state.skillsFilters\n let searchName = state.searchName\n\n if (skillsFilters.length !== 0) {\n attendees = attendees.filter(filterBySkills.bind(this, skillsFilters))\n }\n\n if (searchName !== '') {\n attendees = attendees.filter(searchFirstAndLastName.bind(this, searchName))\n }\n\n return attendees\n}", "updateDevJauge(checklist){\n\tDevJauge.setIn(this.carte)\n}", "handleGrantAdminRole() {\n console.log(\"handleGrantAdminRole:\")\n console.log(JSON_stringify(this.state.group_users_list))\n console.log(\"ELEMENTS:\")\n this.state.group_users_list.filter( (item) => item.isChecked === true).forEach( (T) => {\n this.makeUserAdmin(T.user_name, this.state.group_id_dropdown)\n })\n }", "function attachEmailAllMarkListEvent(){\n\tvar emailAllDivs = document.getElementsBySelector(\"span.citation-send\");\n\tfor(var i=0;i<emailAllDivs.length;i++){\n\t\tvar emailAll = emailAllDivs[i].getElementsByTagName(\"INPUT\")[0];\n if (\"sendAllEmailOption\" == emailAll.id) {\n emailAll.onclick = updateEmailAllMarkList;\n } else {\n emailAll.onclick = updateEmailMarkList;\n }\n }\n}", "function update(box) {\n console.log(\"CLICKED\", box.id, box.checked);\n var request = new XMLHttpRequest();\n request.open('PUT', 'http://localhost:4000/checkboxes/'+box.id, true);\n request.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n request.send(\"value=\"+box.checked)\n }", "function selects() {\r\n var ele = document.getElementsByName('chk');\r\n for (var i = 0; i < ele.length; i++) {\r\n if (ele[i].type == 'checkbox')\r\n ele[i].checked = true;\r\n hide_hobby();\r\n }\r\n document.getElementById(\"checkedit\").checked = false;\r\n}", "function emailSubscription(chkbox){\n\tif(chkbox[\"selectedKeys\"]==null)\n\t\taudienceEmailSubs=false;\n\telse\n\t\taudienceEmailSubs=true;\n}", "function updateStatus() {\n\tfor (let i = 0; i < inputs.length; i++) {\n\t\tif (inputs[i].checked === true) {\n\t\t\tlistItems[i].classList.add('completed');\n\t\t\ttasks[i].completed = true;\n\t\t} else {\n\t\t\tlistItems[i].classList.remove('completed');\n\t\t\ttasks[i].completed = false;\n\t\t}\n\t}\n\n\t// d) Tareas totales. Cada vez que una tarea se marque/desmarque deberíamos actualizar esta información.\n\n\tlet message = document.querySelector('.message');\n\n\tlet completedTasks = document.querySelectorAll('input:checked').length;\n\n\tlet incompleteTasks = parseInt(tasks.length) - parseInt(completedTasks);\n\n\t// Actualizamos mensaje\n\tmessage.innerHTML = `Tienes ${tasks.length} tareas. ${completedTasks} completadas y ${incompleteTasks} por realizar.`;\n}", "function seleccionarTodasInspeccionesPuertas(){\n $(\"#marcarTodos_puertas\").change(function () {\n if ($(this).is(':checked')) {\n //$(\"input[type=checkbox]\").prop('checked', true); //todos los check\n $(\"#tabla_inspeccion_puertas input[type=checkbox]\").prop('checked', true); //solo los del objeto #tabla_inspeccion_puertas\n } else {\n //$(\"input[type=checkbox]\").prop('checked', false);//todos los check\n $(\"#tabla_inspeccion_puertas input[type=checkbox]\").prop('checked', false);//solo los del objeto #tabla_inspeccion_puertas\n }\n });\n}", "function syncCheckboxes() {\n $('input[type=\"checkbox\"]').on('change', function() {\n var $t = $(this),\n checkName = $t.attr('name'),\n playerID = $t.parent().attr('data-id');\n\n $('[data-id=\"'+ playerID +'\"]')\n .find('input[name=\"'+ checkName +'\"]')\n .prop('checked', $t.is(':checked'));\n });\n}", "function checkCheckboxesImportantSubjects() {\r\n\tvar checkboxArrayImportantSubjects = [];\r\n\tcheckboxArrayImportantSubjects = document.getElementsByClassName('checkboxEIS');\r\n\t// door mijn checkboxarray heen loopen om te kijken of die geklikt is\r\n\tfor (checkIndex = 0; checkIndex < checkboxArrayImportantSubjects.length; checkIndex++) {\r\n\t\tif (checkboxArrayImportantSubjects[checkIndex].checked == true) {\r\n\t\t\tvar correctAnswer = answerQuestion[checkIndex];\r\n\t\t\t// door de subjects heen loopen\r\n\t\t\tfor (checkboxInput = 0; checkboxInput < subjects[checkIndex].parties.length; checkboxInput++) {\r\n\t\t\t\tconsole.log(subjects[checkIndex].parties[checkIndex].name);\r\n\t\t\t\t//\r\n\t\t\t\tif (answerQuestion[checkIndex] == subjects[checkIndex].parties[checkboxInput].position) {\r\n\t\t\t\t\tpoints[checkboxInput].value++;\r\n\t\t\t\t\tconsole.log(points[checkboxInput].value);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function markSelectedAsUnread() {\n let newRead = [...readEmails]\n newRead = newRead.filter((id) => !selectedEmails.includes(id));\n setReadEmails(newRead);\n }", "function updateChecklist() {\n\t\tchrome.storage.sync.set({'checklist': checklist }, function() {\n\t\t\tconsole.log('Checklist has been updated');\n\t\t\tchrome.extension.sendMessage({action: 'resetList'});\n\t\t});\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by KotlinParserfunctionValueParameters.
enterFunctionValueParameters(ctx) { }
[ "enterFunctionValueParameter(ctx) {\n\t}", "enterValueArguments(ctx) {\n\t}", "addChildren(valuesAdded) {\n this.children.push(new Node('()' + this.val, 'right'));\n valuesAdded.push('()' + this.val);\n this.children.push(new Node('(' + this.val + ')', 'right'));\n valuesAdded.push('(' + this.val + ')');\n this.children.push(new Node(this.val + '()', 'right'));\n valuesAdded.push(this.val + '()');\n }", "visitTypedargslist(ctx) {\r\n console.log(\"visitTypedargslist\");\r\n // TODO: support *args, **kwargs\r\n let length = ctx.getChildCount();\r\n let returnlist = [];\r\n let comma = [];\r\n let current = -1;\r\n if (ctx.STAR() === null && ctx.POWER() === null) {\r\n for (var i = 0; i < length; i++) {\r\n if (ctx.getChild(i).getText() === \",\") {\r\n comma.push(i);\r\n }\r\n }\r\n comma.push(length);\r\n for (var i = 0; i < comma.length; i++) {\r\n if (comma[i] - current === 2) {\r\n returnlist.push({\r\n type: \"Parameter\",\r\n name: this.visit(ctx.getChild(comma[i] - 1)),\r\n default: null,\r\n });\r\n current = current + 2;\r\n console.log(this.visit(ctx.getChild(comma[i] - 1)));\r\n } else {\r\n returnlist.push({\r\n type: \"Parameter\",\r\n name: this.visit(ctx.getChild(comma[i] - 3)),\r\n default: this.visit(ctx.getChild(comma[i] - 1)),\r\n });\r\n current = current + 4;\r\n }\r\n }\r\n } else {\r\n throw \"*args and **kwargs have not been implemented!\";\r\n }\r\n return returnlist;\r\n }", "enterFunctionLiteral(ctx) {\n\t}", "function parseFuncParam() {\n var params = [];\n var id;\n var valtype;\n\n if (token.type === _tokenizer.tokens.identifier) {\n id = token.value;\n eatToken();\n }\n\n if (token.type === _tokenizer.tokens.valtype) {\n valtype = token.value;\n eatToken();\n params.push({\n id: id,\n valtype: valtype\n });\n /**\n * Shorthand notation for multiple anonymous parameters\n * @see https://webassembly.github.io/spec/core/text/types.html#function-types\n * @see https://github.com/xtuc/webassemblyjs/issues/6\n */\n\n if (id === undefined) {\n while (token.type === _tokenizer.tokens.valtype) {\n valtype = token.value;\n eatToken();\n params.push({\n id: undefined,\n valtype: valtype\n });\n }\n }\n } else {// ignore\n }\n\n return params;\n }", "function functionDeclaration(node, meta, callback) {\n var identifier = meta.identifiers[node.id.name]\n\n // if not identifier then hard mode\n if (!identifier) {\n return typeInferFunctionDeclaration(node, meta, callback)\n }\n\n var type = identifier.jsig\n\n var fMeta = FunctionMeta(meta)\n\n node.params.forEach(function (param, index) {\n if (param.type !== 'Identifier') {\n console.warn('unknown param node', param.type)\n return\n }\n\n var name = param.name\n var paramType = type.args[index]\n\n fMeta.identifiers[name] = {\n type: 'variable',\n jsig: paramType\n }\n })\n\n fMeta.returnValueType = type.result\n\n verify(node.body, fMeta, callback)\n}", "visitFunction_argument(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function lprecurse(tree, fun, pre, post, arg) {\n\tif (!tree.parent) {\n\t\ttree.parent = {};\n\t}\n\tif (tree instanceof Array) {\n\t\tfor (var i = 0; i < tree.length; i++) {\n\t\t\ttree[i].parent = tree.parent; // tree is a list.\n\t\t\ttree[i].arrayindex = i;\n\t\t\ttree[i].property = tree.property;\n\t\t\tlprecurse(tree[i], fun, pre, post, arg);\n\t\t}\n\t} else if (tree.type) {\n\t\tif (!tree.idnum) {\n\t\t\tidnum++;\n\t\t\ttree.idnum = idnum;\n\t\t}\n\t\t// Fill in Parent for unsearch properties\n\t\tif (tree.type == \"FunctionDeclaration\") {\n\t\t\t// Set Parent of\n\t\t\tvar k = tree;\n\t\t\twhile (k.identifier) {\n\t\t\t\tk.identifier.parent = k;\n\t\t\t\tif (k.type == \"FunctionDeclaration\") {\n\t\t\t\t\tk.identifier.property = \"identifier\";\n\t\t\t\t\tk = k.identifier;\n\t\t\t\t} else {\n\t\t\t\t\tk.identifier.property = \"base\";\n\t\t\t\t\tk = k.base;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Do \"before\" work\n\t\tif (pre) {\n\t\t\tpre(tree, arg);\n\t\t}\n\t\t// Do \"here\" work\n\t\tfun(tree, arg);\n\t\t// Find children\n\t\tvar exec = doNormal[tree.type];\n\t\tif (!exec) {\n\t\t\tif (isBottom[tree.type]) {\n\t\t\t} else {\n\t\t\t\timplementation(\"No lprecurse implementation for \" + tree.type);\n\t\t\t}\n\t\t} else {\n\t\t\t// Get \"normal\" properties off of this tree\n\t\t\tfor (var i = 0; i < exec.length; i++) {\n\t\t\t\tvar op = tree[exec[i]];\n\t\t\t\tif (op) {\n\t\t\t\t\top.parent = tree;\n\t\t\t\t\top.property = exec[i];\n\t\t\t\t\tlprecurse(op, fun, pre, post, arg);\n\t\t\t\t} else {\n\t\t\t\t\t// e.g., step\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Do \"after\" work\n\t\tif (post) {\n\t\t\tpost(tree, arg);\n\t\t}\n\t} else {\n\t\tthrow new Error(\"Unexpected object\" + JSON.stringify(tree) + \"received in lprecurse\");\n\t}\n}", "enterLambdaParameter(ctx) {\n\t}", "visitStandard_function(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitVarargslist(ctx) {\r\n console.log(\"visitVarargslist\");\r\n // TODO: support *args, **kwargs\r\n let length = ctx.getChildCount();\r\n let returnlist = [];\r\n let comma = [];\r\n let current = -1;\r\n if (ctx.STAR() === null && ctx.POWER() === null) {\r\n for (var i = 0; i < length; i++) {\r\n if (ctx.getChild(i).getText() === \",\") {\r\n comma.push(i);\r\n }\r\n }\r\n comma.push(length);\r\n for (var i = 0; i < comma.length; i++) {\r\n if (comma[i] - current === 2) {\r\n returnlist.push({\r\n type: \"VarArgument\",\r\n name: this.visit(ctx.getChild(comma[i] - 1)),\r\n default: null,\r\n });\r\n current = current + 2;\r\n console.log(this.visit(ctx.getChild(comma[i] - 1)));\r\n } else {\r\n returnlist.push({\r\n type: \"VarArgument\",\r\n name: this.visit(ctx.getChild(comma[i] - 3)),\r\n default: this.visit(ctx.getChild(comma[i] - 1)),\r\n });\r\n current = current + 4;\r\n }\r\n }\r\n } else {\r\n throw \"*args and **kwargs have not been implemented!\";\r\n }\r\n return returnlist;\r\n }", "function make_function_value(parameters, locals, body, env) {\n return { tag: \"function_value\",\n parameters: parameters,\n locals: locals,\n body: body,\n environment: env,\n // we include a prototype property, initially\n // the empty object. This means, user programs\n // can do: my_function.prototype.m = ...\n prototype: {},\n // another way of calling a function is by\n // invoking it via my_function.call(x,y,z)\n // This is actually an object method application,\n // and thus it becomes\n // (my_function[\"call\"])(my_function,x,y,z)\n // Therefore, we add an argument (let's call it\n // __function__) in front of the parameter list.\n call: { tag: \"function_value\",\n parameters: pair(\"__function__\",\n parameters),\n locals: locals,\n body: body,\n environment: env\n },\n // the property Inherits is available for all functions f\n // in the given program. This means that we can call\n // f.Inherits(...), using object method application\n Inherits: inherits_function_value\n };\n}", "initTree() {\n // var format=function(features){features.forEach(p=>{console.log(`{id:${new Number(p.properties.nid)}, x:${new Number(p.geometry.coordinates[1])}, y: ${new Number(p.geometry.coordinates[0])}},`)});}\n this._tree = new KDBush(this._points, p => Math.round(p.x), p => Math.round(p.y), 64, Int32Array);\n }", "_generate(ast) {}", "constructor(idNode, value) {\n this.idNode = idNode;\n this.value = value;\n // ideally valueNode would be cloned otherwise it can get\n // reset during interpretation of certain node types like while loops \n // the work around for now is to have a value as well as the valueNode\n // this.valueNode = valueNode;\n // this.value = this.valueNode && this.valueNode.getEvaluatedValue();\n }", "enterInferredFormalParameterList(ctx) {\n\t}", "function defParser(node_type, parser, mapper){\n\treturn {\n\t\ttype : node_type,\n\t\tparser : parser = parser.mark().map(x => {\n\t\t\tx.value = mapper(x.value);\n\t\t\treturn createAstNode(node_type, x);\n\t\t}),\n\t};\n}", "visitFunction_argument_modeling(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a child element to the back of the child stack.
sendToBack(element) { return this.changeIndexTo(element, 0, false); if (index > 0) { this._children.splice(index, 1); this._children.splice(0, 0, element); } }
[ "sendBackward(element) {\n return this.changeIndexTo(element, -1, true);\n\n if (index > 0) {\n var temp = this._children[index];\n this._children[index] = this._children[index - 1];\n this._children[index - 1] = temp;\n }\n }", "pop() {\n if (this.currentNode.children.length > 0) return;\n\n let tmp = this.currentNode;\n this.previous();\n tmp.removeFromParent();\n }", "bringToFront(element) {\n return this.changeIndexTo(element, this._children.length, false);\n\n if (element.parent != this) return ;\n var index = this._children.indexOf(element);\n if (index >= 0 && index < this._children.length - 1) {\n this._children.splice(index, 1);\n this._children.push(element);\n }\n }", "push(element) {\r\n //this.stack.push(element);\r\n this.stack.unshift(element);\r\n }", "popValue() {\n let size = this.stack.pop().size;\n this.write(\"[-]<\".repeat(size));\n }", "sendBack(){\n\t\tthis.coinCount -= 3;\n\t\tthis.updateCoinCount();\n\t\tconst spacesToSendBack = Math.floor(Math.random()*3 + 3);\n\t\tthis.opponent.currentPosition -= spacesToSendBack;\n\t\tif(this.opponent.currentPosition === 0){\n\t\t\tthis.opponent.currentPosition = 40;\n\t\t} else {\n\t\t\tthis.opponent.currentPosition = (this.opponent.currentPosition + 40) % 40;\n\t\t}\n\t\t$(`#${this.opponent.iconId}`).parent().remove();\n\t\t$(`#${this.opponent.currentPosition}`).append(this.opponent.charIcon);\n\t\t$('.resultmessage__container').html(`<p>${this.character} threw a banana peel and sent ${this.opponent.character} back to tile [${this.opponent.currentPosition}]!</p>`);\n\t}", "popActive() {\n\t\t\tif(!this._activeStack.length) throw new Error(\"Active stack for \"+this.name+\" is empty and requested pop.\");\n\t\t\tthis._activeStack.pop().becomeActive();\n\t\t}", "add (child) {\n this.contents.push(child);\n child.parent = this;\n }", "childAfter(pos) {\n return this.enterChild(1, pos, 2 /* Side.After */)\n }", "skipChild() {\n\t\tIncrementalDOM.elementVoid(jsxRenderer_.incElementCount);\n\t}", "callChildMethod(){\n this.template.querySelector('c-bubble-event').childMethodCallingFromParent('Parent message passed');\n }", "function addChild(child) {\n if (typeof child.setHeightChangeCallback != \"undefined\")\n child.setHeightChangeCallback(recalcHeight);\n\n var index = getToggledIndex();\n if (index == -1) {\n // insert at end\n children.push(child);\n }\n else {\n // insert (before) selected position\n children.splice(index,0,child);\n if (typeof child.ontoggle != \"undefined\") {\n // untoggle current child and select the new one\n children[index+1].ontoggle(); // must be toggleable\n child.ontoggle();\n }\n }\n ctx.onmodify();\n\n recalcHeight();\n }", "back() {\n this.print(`\\n`);\n return this;\n }", "enQueue(item) {\n // move all items from stack1 to stack2, which reverses order\n this.alternateStacks(this.stack1, this.stack2)\n\n // new item will be at the bottom of stack1 so it will be the last out / last in line\n this.stack1.push(item);\n\n // move items back to stack1, from stack2\n this.alternateStacks(this.stack2, this.stack1)\n }", "push(val) {\n this._stack.push(val);\n }", "function sendParent(event, options) {\n return send$1(event, __assign({}, options, { to: SpecialTargets.Parent }));\n}", "pop() {\r\n return this._msgStack.pop()\r\n }", "function goBack() {\n pop();\n\n if(typeof last() === 'undefined') {\n return;\n }\n var previousView = last();\n $state.go(previousView);\n }", "frame () {\n\t\t// This is to call the parent class's delete method\n\t\tsuper.frame();\n\n\t\tif (this.state === 'swinging') this.swing();\n\t\telse if (this.state === 'pulling' && this.shouldStopPulling()) this.stopPulling();\n\t\telse if (this.state === 'pulling' && this.shouldRemoveLastChain()) this.removeLastChain();\n\t\telse if (this.state === 'throwing' && this.shouldGenerateAnotherChain()) this.generateChain();\n\n\t\tif (this.hookedObject) {\n\t\t\t// Updates the hooked object's position to follow the hook at every frame.\n\t\t\tthis.hookedObject.position = this.position.add(this.hookedObject.offset);\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an error to be thrown when two column definitions have the same name.
function getTableDuplicateColumnNameError(name) { return Error("Duplicate column definition name provided: \"" + name + "\"."); }
[ "columnIndex(name) {\n if (_.isNumber(name) && this.headers[name]) {\n return name;\n }\n const index = this._headers.indexOf(name);\n if (index === -1) {\n throw Error(`Table.columnIndex: no column named ${name}`);\n }\n return index;\n }", "function column1(machine)\n {\n token = machine.popToken();\n switch( token.type )\n {\n case \"identifier\": machine.pushToken( new identifierColumn( \"\", token.identifier, token.identifier ) ); break;\n case \"expression\": machine.pushToken( new expressionColumn( token.expression, \"\" ) ); break;\n case \"*\": machine.pushToken( new everythingColumn() ); break;\n\n default : machine.error(\"there is an unexpected error with a column1 production\");\n }\n }", "static diffCols(colnames){\n let cols = new Set(colnames);\n let hdrs = new Set(CONST.EXPECT_HEADER);\n\n let leftDiff = [...cols].filter(x => !hdrs.has(x));\n return(leftDiff);\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 }", "static diffHeader(colnames){\n let cols = new Set(colnames);\n let hdrs = new Set(CONST.EXPECT_HEADER);\n\n let rightDiff = [...hdrs].filter(x => !cols.has(x));\n return(rightDiff);\n }", "hasColumn(tableName, column){\n this.pushQuery({\n sql: `select i.rdb$field_name as \"Field\" from ` +\n `rdb$relations r join rdb$RELATION_FIELDS i ` +\n `on (i.rdb$relation_name = r.rdb$relation_name) ` +\n `where r.rdb$relation_name = ${this.formatter.wrap(tableName)}`,\n output(resp) {\n return some(resp, (col) => {\n return (\n this.client.wrapIdentifier(col.name.toLowerCase()) ===\n this.client.wrapIdentifier(column.toLowerCase())\n );\n });\n },\n });\n }", "expressionsHaveTheSameType(e1, e2) {\n if (e1 === null || e2 === null) {\n return;\n }\n doCheck(\n this.typesAreEquivalent(e1.type, e2.type),\n `Expression of type ${util.format(\n e1.type\n )} not compatible with expression of type ${util.format(e2.type)}`\n );\n }", "invalidColumnNames(list) {\n return list.find(c => c.search(/[^A-Za-z$_\\d]/) > -1);\n }", "function validateUniqueRecords (records,colNames){\r\n var i = 0, j = 0,equalNum = 0;\r\n if (records && records[0]) {\r\n \tif(colNames == null || colNames.length == 0) {\r\n \t\tcolNames = [];\r\n\t\t\tfor(var k = 0; k < records[0].fields.keys.length;k++){//grid column name\r\n\t\t\t\tif(records[0].fields.keys && records[0].fields.keys[k] != \"id\"){\r\n\t\t\t\t\tcolNames.push(records[0].fields.keys[k]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n \t}\r\n } else {\r\n \treturn true;\r\n }\r\n while (undefined !== records[i]){\r\n j = i + 1;\r\n equalNum = 0;\r\n while(undefined !== records[j]){\r\n \tequalNum = 0;\r\n \tfor(var m = 0;m < colNames.length;m++){ \t\t\r\n\t if (records[i].get(colNames[m]) == records[j].get(colNames[m])) {\r\n\t \tequalNum++;\r\n\t }\r\n \t}\r\n \tif(equalNum == colNames.length){\r\n \t\treturn false;\r\n \t}\r\n ++j;\r\n }\r\n ++i;\r\n }\r\n return true;\r\n}", "SetColumn() {}", "validate() {\n const seenTables = new Map();\n for (const meta of this.values()) {\n if (seenTables.get(meta.tableName)) {\n throw new Error(\n `DB table \"${meta.tableName}\" already exists. Change the collectionName of the related content type.`\n );\n }\n seenTables.set(meta.tableName, true);\n }\n }", "getRealColumnName(column) {\n\n const machineNames = Object.keys(this.labelToColumns);\n\n if (machineNames.includes(column)) {\n return column;\n }\n\n const realColumn = machineNames.reduce((accumulator, currentValue) => {\n const info = this.labelToColumns[currentValue]\n\n if (info.hasOwnProperty('description') &&\n info.description === column) {\n accumulator += currentValue;\n }\n return accumulator;\n }, \"\");\n\n if (realColumn.length > 0) {\n return realColumn;\n }\n\n return \"\"\n }", "function checkColumn() {\r\n\t\tvar i = 0;\r\n\t\tvar colStr = ',';\r\n\t\tfor (i = 0; i < grid.colModel.config.length; i++) {\r\n\t\t\tvar cm = grid.colModel.config[i];\r\n\t\t\t// 判断列标识不为空,并且不是hidden\r\n\t\t\tif (cm.dataIndex != '' && !cm.hidden) {\r\n\t\t\t\t//可以获得 其index,及header 参见 grid的定义;\r\n\t\t\t\tcolStr = colStr + cm.dataIndex + \",\";\r\n\t\t\t}\r\n\t\t}\r\n\t\tdocument.getElementById('exp_column').value = colStr;\r\n\t}", "function columnDefinitions2( machine )\n {\n ident = machine.popToken();\n machine.checkToken(\",\");\n defs = machine.popToken();\n defs.add(ident.identifier);\n machine.pushToken(defs);\n }", "function checkColumn(req,columnName)\n{\n \n return JSON.stringify(req.params.column) === ('\\\"'+columnName+'\\\"')\n}", "hasColumn(tableName, column) {\n this.pushQuery({\n sql: `show columns from ${this.formatter.wrap(tableName)}` +\n ' like ' + this.formatter.parameter(column),\n output(resp) {\n return resp.length > 0;\n }\n });\n }", "function sameValueExact(a, b) { // flag for exaxt? which ignores eg 0\n var type = a.type\n\n if (type === \"Dimension\") {\n if (a.val === b.val && a.unit === b.unit)\n return true\n }\n if (type === \"Number\") { // dont exists, only 0?\n // we know b exists, only prop can give us undefined back, so no need to check if b.unit exists\n if (a.val === b.val)\n return false\n }\n if (type === \"Percentage\") {\n if (a.val === b.val)\n return false\n }\n // need to comapre args too..\n if (type === \"Function\") {\n if (isFunctionSame()) // pass arg?\n return false\n }\n\n // value can be auto - so can be ident?\n if (type === \"Identifier\") { // custom or not, WL, trust user.\n return false\n }\n\n}", "isFirstColumn(): boolean {\n return this.getColumnIndex() === 0;\n }", "function onColumnDefsChange(newVal, oldVal) {\n _.each(oldVal, function (item, index) {\n if (item.selected === undefined) {\n item.selected = false;\n item.visible = typeof item.visible === 'boolean' ? item.visible : true;\n }\n });\n if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {\n logger.info('watch: sitGridOptions.columnDefs', 'column definitions changed, length = ' + ctrl.sitGridOptions.columnDefs.length);\n ctrl.generateCellTemplates(newVal);\n assignGridVisibleCols();\n ctrl.resetGrid(false, false);\n }\n }", "function columnSizeValidation(props, propName, componentName) {\n componentName = componentName || \"ANONYMOUS\";\n\n if (props[propName]) {\n const size = props[propName];\n\n if (typeof size === \"number\") {\n return (size <= 6 && size >= 0)\n ? null\n : new Error(\"Prop \" + propName + \" in \" + componentName + \" is \" + size + \", should be a number between 0 to 6\");\n }\n else {\n return new Error(\"Prop \" + propName + \" in \" + componentName + \" should be a number, not a \" + typeof size);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
What's this? clear all selections and final cursor position becomes head of last selection. editor.clearSelections() does not respect last selection's head, since it merge all selections before clearing.
clearSelections () { this.editor.setCursorBufferPosition(this.editor.getCursorBufferPosition()) }
[ "_clearSavedSelection() {\n this._savedSelection = null;\n }", "function clearAllSelection(){\n ds.clearSelection();\n arrDisp.length=0;\n updateSelDisplay();\n updateCurrSelection('','','startIndex',0);\n updateCurrSelection('','','endIndex',0);\n}", "clearSelect() {\n const [selection] = this.cm.getDoc().listSelections();\n\n if (selection) {\n this.cm.setCursor(selection.to());\n }\n }", "clearSelection() {\n let treeSelection = this.treeSelection; // potentially magic getter\n if (!treeSelection) {\n return;\n }\n treeSelection.clearSelection();\n this.messageDisplay.clearDisplay();\n this._updateContextDisplay();\n }", "function clearSingleSelection() {\n if (current_mode !== mode.fixation) {\n console.log(\"Warning: request to clear single selection when not in fixation mode.\");\n return;\n }\n path.classed(\"dimmed\", false);\n focusOnNode(selected_singleNode, false);\n selected_singleNode = null;\n current_mode = mode.exploration;\n}", "deSelectAll() {\n this.set('isSelecting', false);\n this.deSelectBlocks();\n }", "function clearSelectedStates() {\n _scope.ugCustomSelect.selectedCells = [];\n }", "eraseRectangularSelection() {\n // infer 4 corners of the rectangle based on the two points that have been drawn\n this.clearHighlights();\n d3.selectAll('#grid .point-path').remove();\n\n const payload = {\n points: [\n this.points[0],\n { x: this.points[1].x, y: this.points[0].y },\n this.points[1],\n { x: this.points[0].x, y: this.points[1].y },\n ],\n };\n\n this.$store.dispatch('geometry/eraseSelection', payload);\n\n // clear points from the grid\n this.points = [];\n }", "function clearSelectedStory() {\n if(selectedStoryButton) {\n selectedStoryButton.removeClass(\"active\");\n }\n selectedStoryButton = null;\n loadedStory = null;\n editorDirty = false;\n $(\"#editor-placeholder\").removeClass(\"d-none\");\n $(\"#editor-area-activities\").addClass(\"d-none\");\n $(\"#editor-area-missions\").addClass(\"d-none\");\n}", "clearSourceSelections() {\n this.mappingSelectionsService_.removeSourceProvider(\n this.selectedSourceProviderId);\n }", "function clearSelectedPoints () {\n\tselectedPoints = [];\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 clearSelection() {\n\t\t$(\"#rootPanel\").css(\"background\",\"url('images/servergroup/commander bg.png')\");\n\t\t$(\"#rootPanel\").find(\"div\").css(\"color\", \"#000000\");\n\t\t$(\"#rootPanel\").find(\"img.focus\").hide();\n\t\t$(\".server\").css(\"background\", \"#ffffff\");\n\t\t$(\".server\").find(\"div\").css(\"color\", \"#000000\");\n\t\t$(\".server\").find(\"img.focus\").hide();\n\t\t$(\".group\").css(\"background\", \"url('images/servergroup/group bg.png')\");\n\t\t$(\".group\").find(\"div\").css(\"color\", \"#000000\");\n\t\t$(\".group\").find(\".groupIcon\").removeClass(\"groupIconFocus\");\n\t\t$(\".group\").find(\".groupToggleIconFocus\").hide();\n\t\t$(\".group\").find(\".groupToggleIcon\").show();\n\t}", "_updateSelection() {\n\t\t// If there is no selection - remove DOM and fake selections.\n\t\tif ( this.selection.rangeCount === 0 ) {\n\t\t\tthis._removeDomSelection();\n\t\t\tthis._removeFakeSelection();\n\n\t\t\treturn;\n\t\t}\n\n\t\tconst domRoot = this.domConverter.mapViewToDom( this.selection.editableElement );\n\n\t\t// Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.\n\t\tif ( !this.isFocused || !domRoot ) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Render selection.\n\t\tif ( this.selection.isFake ) {\n\t\t\tthis._updateFakeSelection( domRoot );\n\t\t} else {\n\t\t\tthis._removeFakeSelection();\n\t\t\tthis._updateDomSelection( domRoot );\n\t\t}\n\t}", "function resetCursorPos(element) {\n element.selectionStart = 0;\n element.selectionEnd = 0;\n }", "function clearSelectedPointsCanvas() {\n\tvar selectedPointsCanvas = document.getElementById('select-points')\n\tvar selectedCtx = selectedPointsCanvas.getContext('2d')\n\tselectedCtx.clearRect(0, 0, selectedPointsCanvas.offsetWidth, selectedPointsCanvas.offsetHeight)\n}", "function cleanSelection() {\n $scope.presets = undefined;\n $scope.selectedCategory = undefined;\n $scope.selectedPreset = undefined;\n }", "clearMarkers() {\n\t\tif (this.editor) {\n\t\t\tclearMarkers(this.editor);\n\t\t}\n\t}", "function on_mouse_out_editor()\n{\n\t// deselect things on it\n\teditor_deselect(editor_context);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates emailstores when a response or comment is made userMakingCommentId user ID or null for anonymous survey form model counterField "responseCount" or "commentCount" hashids a dependency
function recordNewResponseOrComment(userMakingCommentId, survey, counterField, hashids) { var userMakingComment = null, emailStoreSurveyItem = null; Promise .all([ new Promise(function (resolve, reject) { if (userMakingCommentId === null) { resolve(); } else { UserModel.findById(userMakingCommentId, function (err, result) { if (err) { reject(); } else { userMakingComment = result; resolve(); } }); } }), new Promise(function (resolve, reject) { UserModel.findById(survey.userid, function (err, result) { if (err) reject(); else resolve(); }); }), new Promise(function (resolve, reject) { EmailStoreModel.findOne({ userid: survey.userid }, function (err, result) { if (err) { reject(); } else if (result) { // If the email store already has data for this question, remove it var qInd = result.questions.findIndex(q => q.formid == survey._id); if (qInd != -1) { emailStoreSurveyItem = result.questions[qInd]; EmailStoreModel.update( {'_id': result._id}, { $pull: { "questions" : { formid: survey._id } } }, function (err, result) { if (err) reject(); else resolve(); } ); } else { // OK as-is: EmailStore exists but EmailStore.questions item does not resolve(); } } else { // Need to create the email store EmailStoreModel.create({ userid: survey.userid, questions: [], community: [], network: [], shared: [] }, function (err, k) { if (err) reject(); else resolve(); }); } }); }), ]) .then(function () { // At this point, the EmailStore exists in DB, but the EmailStore.questions item does not // We will compute the new item then append it to EmailStore.questions in the DB if (!emailStoreSurveyItem) { emailStoreSurveyItem = { formid: survey._id, question: survey.questions[0].body, commentCount: 0, responseCount: 0, link: "https://www.questionsly.com/feed;survey=" + hashids.encodeHex(survey._id), responseProfiles: [], anonymousCount: 0 }; } // Most important part emailStoreSurveyItem[counterField] ++; if (userMakingComment) { var userMakingCommentName = userMakingComment.name.first + " " + userMakingComment.name.last; var profileIndex = emailStoreSurveyItem.responseProfiles.findIndex(i => i.name == userMakingCommentName); if (profileIndex == -1) { emailStoreSurveyItem.responseProfiles.push({ name: userMakingCommentName, profilePic: usersfunctions.getProfilePic(userMakingComment), }); } } else { emailStoreSurveyItem.anonymousCount++; } return new Promise(function (resolve, reject) { EmailStoreModel.update( {userid: survey.userid, "questions.formid" : {$ne : survey._id }}, {$addToSet : {"questions" : emailStoreSurveyItem}}, function (err, result) { if (err) reject(); else resolve(); } ); }); }) .then(function () { }) .catch(err => { console.log("recordNewResponseOrComment failed", err); }); }
[ "function setUserID(){\n if(isNew){\n spCookie = getSpCookie(trackerCookieName);\n getLead(isNew, spCookie, appID);\n }\n }", "function updateTipEventCount(tipObj){\n\t\n\t\t\tconsole.log(tipObj);\n\t\t\tconsole.log(tipObj._id + \" : \" + tipObj.isEvent);\n\t\t\t\n\t\t\tvar placeObj = {};\n\t\t\t\n\t\t\t\n\t\t\t//Get Current Tip Count\n\t\t\tvar promise = Kinvey.DataStore.find('places', tipObj._id , {\n\t\t\t\tsuccess: function(response) {\n\t\t\t\t\t\n\t\t\t\t\tconsole.log(response);\n\t\t\t\t\t\tplaceObj = response;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(tipObj.isEvent == \"true\"){\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t\tconsole.log(\"Event Count : \" + placeObj.eventCount++);\n\t\t\t\t\t\t\n\t\t\t\t\t\tplaceObj.eventCount = placeObj.eventCount++;\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t\tconsole.log(\"Tip Count : \" + placeObj.tipCount++);\n\t\t\t\t\t\tplaceObj.tipCount = placeObj.tipCount++;\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\n\tKinvey.DataStore.save('places', placeObj).then(function() {\n\t\t\tconsole.log(\"place event tip count updated\");\n\t\t\tconsole.log(placeObj);\n \t}, function(error) {\n \t\t doc.trigger('error', error);\n \t}).then(function() {\n\t\t \n\t\t \n\t\t});\t\n}", "function setEmailPromotionSetting(cb){\n if (cb.checked) {\n unsubscribeAll(cb.form);\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 submitAnswer() {\n let answer = app.form.convertToData('#survey-form');\n answer.answerer = loggedInUser.email;\n answer.survey_id = openSurvey.id;\n if (!answered(openSurvey.id)) {\n newAnswer(answer);\n } else {\n updateAnswer(answer);\n }\n}", "applyDisapproval () {\n this.update({\n 'data.class.disapproval': this.data.data.class.disapproval + 1\n })\n }", "'update_userSurvey'(objectID, survey_type)\n {\n\n if (survey_type == 'personal')\n {\n Meteor.users.update(\n {_id: Meteor.userId()},\n {$push:\n {\n \"profile.personal_survey\": objectID\n }\n });\n }\n else if (survey_type == 'employer')\n {\n Meteor.users.update(\n {_id: Meteor.userId()},\n {$push:\n {\n \"profile.employer_survey\": objectID\n }\n });\n }\n\n\n\n }", "markSeenAll () { // mark this comment and all replies 'seen'\n if (!this.seenByMe) {\n this.seenByMe = true\n const token = localStorage.getItem(\"nb.user\");\n const headers = { headers: { Authorization: 'Bearer ' + token }}\n axios.post(`/api/annotations/seen/${this.id}`,{} ,headers)\n }\n for (let child of this.children) {\n child.markSeenAll()\n }\n }", "function setKissmetricsUser () {\n _kmq.push(['identify', $rootScope.generalInfo.current_user.email]);\n }", "function notifyWillResetModelAnd(closure) {\n // Fast path; also required because no callbacks => we never call resetRequest.proceed()\n if (willResetModelCallbacks.length === 0) {\n closure();\n }\n\n var numberOfResponsesRequired = willResetModelCallbacks.length;\n var numberOfProceedResponses = 0;\n var resetWasCanceled = false;\n\n function proceedIfReady() {\n if (!resetWasCanceled && numberOfProceedResponses === numberOfResponsesRequired) {\n closure();\n }\n } // Returns a new \"use once\" object that the willResetModel callback can use to asynchronously\n // allow the reset to proceed or cancel.\n\n\n function makeResetRequest() {\n var wasUsed = false;\n return {\n proceed: function proceed() {\n if (wasUsed) {\n return;\n }\n\n wasUsed = true;\n numberOfProceedResponses++;\n proceedIfReady();\n },\n cancel: function cancel() {\n if (wasUsed) {\n return;\n }\n\n wasUsed = true;\n resetWasCanceled = true;\n }\n };\n }\n\n willResetModelCallbacks.forEach(function (willResetModelCallback) {\n var resetRequest = makeResetRequest(); // willResetModel callbacks that don't return a value (or return a falsy value) without\n // having invoked resetRequest.cancel() should be treated as having requested to proceed.\n\n if (!willResetModelCallback(model, resetRequest)) {\n // remember this has no effect if the callback already called resetRequest.cancel():\n resetRequest.proceed();\n }\n });\n }", "onSavesuppliers(event) {\n event.preventDefault();\n // adding\n if (this.state.suppliersId == \"\") {\n fetch(`${this.url}`, {\n method: 'POST', \n body: JSON.stringify({\n suppliersId: 0, \n name: this.$suppliersName.value,\n phone: this.$suppliersPhone.value,\n email: this.$suppliersEmail.value,\n website: this.$suppliersWebsite.value,\n contactFirstName: this.$suppliersContactFirstName.value,\n contactLastName: this.$suppliersContactLastName.value,\n contactPhone: this.$suppliersContactPhone.value,\n contactEmail: this.$suppliersContactEmail.value,\n note: this.$suppliersNote.value\n }),\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n .then(response => response.json())\n .then(data => { \n // returns the record that we added so the ids should be there \n if (data.suppliersId)\n {\n this.state.suppliersId = data.suppliersId;\n this.state.suppliers = data;\n this.$suppliersId.value = this.state.suppliersId;\n this.fillsuppliersFields();\n this.$suppliersId.readOnly = false;\n this.enableButtons(\"found\");\n alert(\"suppliers was added.\")\n }\n else{\n alert('There was a problem adding suppliers info!'); \n }\n })\n .catch(error => {\n alert('There was a problem adding suppliers info!'); \n });\n }\n // updating\n else {\n // the format of the body has to match the original object exactly \n // so make a copy of it and copy the values from the form\n let suppliers = Object.assign(this.state.suppliers);\n suppliers.name = this.$suppliersName.value;\n suppliers.phone = this.$suppliersPhone.value;\n suppliers.email = this.$suppliersEmail.value;\n suppliers.website = this.$suppliers.Website.value;\n suppliers.contactFirstName = this.$suppliersContactFirstName.value;\n suppliers.contactLastName = this.$suppliersContactLastName.value;\n suppliers.contactPhone = this.$suppliersContactPhone.value;\n suppliers.contactEmail = this.$suppliersContactEmail.value;\n suppliers.note = this.$suppliersNote.value;\n fetch(`${this.url}/${this.state.suppliersId}`, {\n method: 'PUT', \n body: JSON.stringify(suppliers),\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n .then(response => {\n // doesn't return a body just a status code of 204 \n if (response.status == 204)\n {\n this.state.suppliers = Object.assign(suppliers);\n this.fillsuppliersFields();\n this.$suppliersId.readOnly = false;\n this.enableButtons(\"found\");\n alert(\"suppliers was updated.\")\n }\n else{\n alert('There was a problem updating suppliers info!'); \n }\n })\n .catch(error => {\n alert('There was a problem adding suppliers info!'); \n });\n }\n }", "function post_notes_prep_input_trackers()\n{\n\t// we need to track how many Notes we've got\n\tjQuery('#post').append('<input type=\"hidden\" name=\"post_notes_note_count\" id=\"post_notes_note_count\" value=\"'+post_notes_count+'\" />');\n\tjQuery('#post').append('<input type=\"hidden\" name=\"post_notes_max\" id=\"post_notes_max\" value=\"'+post_notes_count+'\" />');\n}", "updateEmergencyPhoneNumber(username,phoneNumber){cov_idmd2e41v.f[15]++;cov_idmd2e41v.s[17]++;Citizen.updateOne({username:username},{phoneNumber:phoneNumber},err=>{cov_idmd2e41v.f[16]++;});}", "function storeAgreeDisagree() {\n explanations = {\n 'agree': [],\n 'disagree': []\n };\n for(var i = 0; i < sortedData.p4.length; i++) {\n explanations.agree.push(sortedData.p4[i] + ': ' + $('#agree-' + i).val());\n }\n for(var i = 0; i < sortedData.n4.length; i++) {\n explanations.disagree.push(sortedData.n4[i] + ': ' + $('#disagree-' + i).val());\n }\n $('.answers').animate({\n opacity: 0\n }, 500, function() {\n $('.answers').remove();\n survey();\n })\n }", "getRespondents(surveyId){\n \n let respondents = 0;\n this.respondents.forEach(element => {\n if(element.surveyId === surveyId){\n respondents = element.completedCounter;\n }\n });\n return respondents;\n }", "setUserAnswer(answer) {\n this.setState((state) => ({\n answersCount: {\n ...state.answersCount,\n [answer]: (state.answersCount[answer] || 0) + 1,\n },\n answer: answer,\n }));\n }", "save(event) {\n let data = {\n agenda: Agenda.file,\n attach: this.props.item.attach,\n initials: document.getElementById(\"comment-initials\").value || User.initials,\n comment: this.state.comment\n };\n\n this.setState({ disabled: true });\n\n Pending.update(\"comment\", data, (pending) => {\n jQuery(\"#comment-form\").modal(\"hide\");\n document.body.classList.remove(\"modal-open\");\n this.setState({ disabled: false });\n Pending.load(pending)\n })\n }", "function post_notes_update_notes_count()\n{\n\t// we're just checking to see how many of OUR textareas have been added...\n\tpost_notes_count = parseInt(jQuery('.post_notes_copy').length);\n\tjQuery('#post_notes_note_count').attr('value',post_notes_count);\n\tif(post_notes_max<post_notes_count)\n\t{\n\t\tpost_notes_max = post_notes_count;\n\t}\n\tjQuery('#post_notes_max').attr('value',post_notes_max);\n}", "function update_anon_count() {\n // Obviously, only do this if we are supposed to show the anonymous user count.\n if ( show_anon_count ) {\n // If there are no anonymous users, hide the block entirely.\n if (muutObj().anon_count == 0 && !anon_count_wrapper.hasClass('hidden')) {\n anon_count_wrapper.addClass('hidden');\n // If we have added an anonymous user, make sure to RE-display the block.\n } else if (muutObj().anon_count > 0 && anon_count_wrapper.hasClass('hidden')) {\n anon_count_wrapper.removeClass('hidden');\n }\n\n // Replace the text (or rather, the count) to the updated number.\n anon_count_wrapper.find('em').text(muutObj().anon_count);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the messages from Watson.
async function parseWatsonMessage(data) { const { output = {} } = data; const { text = [] } = output; text.forEach(x => printMessage(x, "watson")); }
[ "function sendToWatson(cont, inp, callback) {\n\t\t\tvar payload = {\n\t\t\t\tworkspace_id:'0a56c12b-af85-490c-8e1c-eabee681c572',\n\t\t\t\tcontext: cont,\n\t\t\t\tinput: {\n\t\t\t\t\"text\": inp\n\t\t\t\t\t}\n\t\t};\n // Conversation credentials\n\t\tvar conversation = new ConversationV1({\n\t\t\tusername:'dba0c5be-3d44-4477-aa27-7bd047d03f58',\n\t\t\tpassword: 'bTWZpnpyVonp',\n\t\tversion_date: '2017-06-01'\n\t});\n//Conversation Starts\n\t\tconversation.message(payload, function(err, data1) {\n\t\t\tif (err) {\n\t\t\t\tconsole.log(\"err during conversation payload\" + err)\n\t\t\t}\n\t\t\telse{\n\t\t\tcontextw = data1.context; //Updating Context Variable\n\t\t\tvar data = JSON.stringify(data1)\n\t\t\tconsole.log(\"Data is: \\n \"+JSON.stringify(data1.output));\n\t\t\tvar node = data1.output.nodes_visited[0];\n\t\t\t\tcallback(data1);\n\t\n }\n\n\n })\n}", "function massage() {\n console.log(\"****************************************************************\")\n console.log(\"Sorry honey, that service isn't digital\")\n console.log(\"But I'd recommend going to a really nice hotel spa & resort\")\n console.log(\"and request their relaxing massage package\")\n console.log(\"****************************************************************\")\n}", "function showWelcome() {\n\n\tconst welcomeHeader = `\n\n=================================================================\n|| ||\n| Employee Summary Generator |\n|| ||\n=================================================================\n\n`\n\n\tconst welcomeMessage = `\n\nWelcome to the Employee Summary Generator!\nThis application will generate a roster of employee details based on information you provide.\n\n`\n\n\tconsole.clear();\n\n\tconsole.log(colors.brightCyan(welcomeHeader));\n\tconsole.log(colors.brightCyan(welcomeMessage));\n\n}", "function printSentence() {\n if (this[\"isChallenging\"] === true && this[\"isRewarding\"] === true) {\n console.log(`Learning the programming languages: \"${this[\"languages\"].join(\", \")}\" is rewarding and challenging.`);\n } else {\n console.log(\"Hä?\")\n };\n}", "async function printWatch(allAuctions,msg){\n let printStr = `\\`\\`\\`CS\\nTracked Batches: ${listBatches()}\\nLast Updated ${new Date().toLocaleString()}\\n\\`\\`\\``;\n for(let batch of batches){\n if(batch.track){\n printStr += \"**\" + batch.name + \"**\\n\\`\\`\\`CSS\\n\"; //adds batch name in bold\n for(let item_name of batch.items){\n if(checkedItems.includes(item_name)){\n let itemIndex = checkedItems.indexOf(item_name);\n let auction = allAuctions[itemIndex];\n printStr += auction.name + \": \\n\"\n auction.itemArray.sort((a,b) => (a.price-b.price)); //sort itemArray in ascending order by price\n let displayItems = auction.itemArray.slice(0,5); //creates shortened copy of item array for listing(lowest 5 prices)\n for(let item of displayItems){\n printStr += \" \" + item.price.toLocaleString('en');\n try{\n let mojang_url = \"https://api.mojang.com/user/profiles/\" + item.auctioneer + \"/names\";\n let response = await fetch(mojang_url);\n if(response.ok){\n let json = await response.json();\n printStr += \" /ah \" + json[json.length-1].name;\n } \n }catch{\n console.log(\"UUID->Name request failed\");\n }\n printStr += \"\\n\";\n }\n }\n if(printStr.length > 1000){ //Prevents the discord message from exceeding the 2000 character limit.\n console.log(printStr);\n printStr += `\\`\\`\\``\n msg.channel.send(printStr);\n printStr = `\\`\\`\\`CSS\\n`;\n }\n }\n printStr += `\\`\\`\\``;\n }\n }\n if(printStr.length > 0){\n msg.channel.send(printStr);\n } \n}", "async function listMessages() {\n let streamService = new StreamService(process.env.MICRO_API_TOKEN);\n let rsp = await streamService.listMessages({\n channel: \"general\",\n });\n console.log(rsp);\n}", "function printWin() {\n $('#hint').text(userString.winMessage).css(\"color\", \"#000000\");\n}", "function printMessages( /*Array<Object>*/ arr) {\n arr.map(msg => {\n if (msg[1] === 'ALL' || msg[0] === window.username && msg[1] === window.username) {\n print(msg[3], msg[0], msg[2] * 1000);\n\n if (!document.hasFocus()) {\n new Notification(`New Message from ${msg[0]}`, {\n body: msg[3]\n });\n }\n }\n });\n}", "display() {\n console.log(`Title: ${this.title}\\nAuthor: ${this.author}\\nPrice: ${this.price}`);\n }", "function printit(){\r\n frames[\"printPage\"].focus();\r\n frames[\"printPage\"].print();\r\n unloadMessage();\r\n }", "function getMessages(phoneNumber, twilioNumber) {\n $(\"#messages\").html(\"\");\n $.getJSON(\"/api/admin/get_messages\", {\"phone_number\": phoneNumber, \"twilio_number\": twilioNumber}, \n function(messages) {\n for (i in messages) {\n var message = messages[i];\n messageDiv = makeElement(\"message\");\n messageDiv.find(\".to\").text(message.outbound == 0 ? \"Me: \" : \"Them: \");\n messageDiv.find(\".body\").text(message.body);\n $(\"#messages\").append(messageDiv);\n }\n });\n}", "function displayMessage(numb) {\n console.log(\"I am diplaying 1st message, becuase I ate \" + numb + \" apples\");\n }", "printInfo() {\n return `Name: ${this.name}\\n Age: ${this.age}\\n Haircolor: ${this.haircolor}`\n\n }", "function powOutput() {\r\n console.log(\"POW-service : The result of raising <base = \" + powObj.base + \"> to the <power = \" + powObj.exponent + \">\\n\\\r\n EQUALS <\" + powObj.result + \">\");\r\n}", "function rtwDisplayMessage() {\n var docObj = top.rtwreport_document_frame.document;\n var msg = docObj.getElementById(RTW_TraceArgs.instance.fMessage);\n if (!msg) {\n msg = docObj.getElementById(\"rtwMsg_notTraceable\");\n }\n if (msg && msg.style) {\n msg.style.display = \"block\"; // make message visible\n var msgstr = msg.innerHTML;\n if (RTW_TraceArgs.instance.fBlock) {\n // replace '%s' in message with block name\n msgstr = msgstr.replace(\"%s\",RTW_TraceArgs.instance.fBlock);\n }\n msg.innerHTML = msgstr;\n }\n}", "printConsole() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++)\n this.nodes[layer][node].printConsole();\n }\n }", "function printWord() {\n $(\"#word\").text(current_word.displayed_word);\n}", "printBuffers() {\n for (var i = 0; i < this.numVertices; i++) {\n console.log(\"v \", this.positionData[i*3], \" \",\n this.positionData[i*3 + 1], \" \",\n this.positionData[i*3 + 2], \" \");\n }\n for (var i = 0; i < this.numVertices; i++) {\n console.log(\"n \", this.normalData[i*3], \" \",\n this.normalData[i*3 + 1], \" \",\n this.normalData[i*3 + 2], \" \");\n }\n for (var i = 0; i < this.numFaces; i++) {\n console.log(\"f \", this.faceData[i*3], \" \",\n this.faceData[i*3 + 1], \" \",\n this.faceData[i*3 + 2], \" \");\n }\n }", "function printDevMessage(msg, args) {\n\t// Check if developer mode is on\n\tif(dev) {\n\t\t// Print the message\n\t\tserver.print(util.format(msg, args));\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sendPageViewToGoogleAnalytics // ///////////////////////////////// Sends a request to Google Anylytics in order for it to accumulate statistics of report usage. The requst is just an indication that the report is being opened. This replaces the old counter service (for which request used to be sent with sendLiveCounterRequest())
function sendPageViewToGoogleAnalytics(userId) { ga('create', { trackingId: 'UA-142846391-2', storage: 'none' }); ga('set', 'checkProtocolTask', function(){ }); ga('set', 'userId', userId) ga('set', 'dimension1', userId); ga('set', 'page', 'http://www.checkpoint-te-report-fake-url.com'); ga('send', { hitType: 'pageview' }); }
[ "trackCustomPageView($location) {\n ga('send', 'pageview', $location);\n }", "function pageviewTrack() {\n\t\tmyscope.$on('$locationChangeStart', function(e, next, current) {\n\t\t _gaq.push(['_trackPageview', next.replace('http://fairfield.summon.serialssolutions.com','')]);\n\t\t});\n }", "setGlobalData() {\n this.sendDataLayerVariable($('body').data('pagetracking'));\n window.isScroll = document.cookie.indexOf('scroll0') > 0;\n ga('set', $('body').data('pagetracking'));\n ga('set', 'dimension20', window.isScroll);\n }", "trackArticlePage() {\n this.single = true;\n this.sendDataLayerEvent('is_single_page');\n const currentArticleId = $('body').data('current-article');\n const theArticle = $(`#${currentArticleId}`);\n const articleTracking = theArticle.data('tracking');\n articleTracking.dimension19 = this.read_cookie('2018multi'); // AB Testing to GA\n this.setSingleArticleGoogleAnalyticsDimensions(articleTracking);\n this.sendDataLayerVariable({\n location: window.location.href,\n referrer: window.fatherlyDataLayer.referrer,\n page: location.pathname,\n nielsenASN: window.fatherlyDataLayer.nielsen.asn,\n nielsenSegA: window.fatherlyDataLayer.nielsen.segA\n });\n ga('send', 'pageview');\n }", "trackSocialInteraction($data) {\n ga('send', $data);\n }", "function analytics( path ) {\n\tfunction fixHttp( url ) {\n\t\treturn url.replace( /http:\\/\\//, 'http/' ).replace( /mailto:/, 'mailto/' );\n\t}\n\tfunction fixAction( url ) {\n\t\treturn {\n\t\t\t'lookup': 'search_submit',\n\t\t\t'#detailsbox': 'view_detail',\n\t\t\t'#mapbox': 'load_map',\n\t\t\t'#Poll411Gadget': 'find_location'\n\t\t}[url];\n\t}\n\tif( window._ADS_ReportInteraction ) {\n\t\tif( path == 'view' || /^javascript:/.test(path) ) return;\n\t\tvar action = fixAction( path );\n\t\tif( action ) {\n\t\t\t//console.log( 'adaction', action );\n\t\t\t_ADS_ReportInteraction( action );\n\t\t}\n\t\telse {\n\t\t\t//console.log( 'adclick', path );\n\t\t\t_ADS_ReportInteraction( 'destination_url_1', path );\n\t\t}\n\t}\n\telse {\n\t\tif( path.indexOf( 'http://maps.gmodules.com/ig/ifr' ) == 0 ) return;\n\t\t//if( path.indexOf( 'http://maps.google.com/maps?f=d' ) == 0 ) path = '/directions';\n\t\tpath = ( maker ? '/creator/' : pref.onebox ? '/onebox/' : inline ? '/inline/' : '/gadget/' ) + fixHttp(path);\n\t\tpath = '/' + fixHttp(document.referrer) + '/' + path;\n\t\t//console.log( 'analytics', path );\n\t\t_IG_Analytics( 'UA-26399777-1', path );\n\t}\n}", "function startReportingActivity() {\n var id = Web.setInterval(function () {\n if (self.active()) {\n ucwa.send('POST', { rel: 'reportMyActivity' }, {\n nobatch: true\n }).catch(function (err) {\n // After a long period of inactivity, the connection with UCWA is usually lost.\n // While the connection is being restored, MePerson resends POST /makeMeAvailable.\n // However this periodic timer doesn't know about that logic and keeps sending\n // POST /reportMyActivity as usual. If the timer happens to wake up before the\n // /makeMeAvailable is completed, UCWA will reject this /reportMyActivity with a\n // 409.MakeMeAvailableRequired error.\n if (err && err.code == 'RequestFailed' && err.rsp.status == 409)\n return;\n debug.log('%c reportMyActivity stopped', 'color:red;font-weight:bold', err);\n Web.clearInterval(id);\n self.active(false, err);\n });\n }\n }, 3 * 60 * 1000);\n }", "function onReportClick(e) {\n\tcommonFunctions.sendScreenshot();\n}", "function sendStats() {\n if (hostname.indexOf(\"local\") != -1) {\n cleanup();\n return;\n }\n var app = options.app;\n\n // Status Code\n var statusCode = res.statusCode || 'unknown_status';\n\n // Increment\n sendData(\"server-stats.count.\"+app,1,{\n \"node\": hostname,\n \"status-code\":statusCode,\n \"path\":path\n });\n\n\n // Response Time\n var duration = new Date().getTime() - startTime;\n // Duration\n sendData(\"server-stats.response-time.\"+app,duration,{\n \"node\": hostname,\n \"path\":path\n });\n\n cleanup();\n }", "function storePageViewData() {\n storeVisit(itemId, new Visit({\n commentCount,\n maxCommentId,\n time: new Date(),\n }))\n }", "addGoogleAnalytics () {\n (function (i, s, o, g, r, a, m) {\n i['GoogleAnalyticsObject'] = r;\n i[r] = i[r] || function () {\n (i[r].q = i[r].q || []).push(arguments);\n }, i[r].l = 1 * new Date();\n a = s.createElement(o),\n m = s.getElementsByTagName(o)[0];\n a.async = 1;\n a.src = g;\n m.parentNode.insertBefore(a, m);\n })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');\n ga('create', `${this.opts.trackingCode}`, 'auto');\n }", "function googleAnalyticsCall(customDimension) {\n\n try {\n\n // Pick up the version\n var version = MorpheuzUtil.getWithDef(\"version\", \"unknown\");\n\n // Use the custom dimensions supplied to provide extra information\n var cd = \"\";\n try {\n if (customDimension && customDimension.constructor == Array) {\n for (var i = 0; i < customDimension.length; i++) {\n var dimensionIndex = i + 1;\n cd += \"&cd\" + dimensionIndex + \"=\" + customDimension[i];\n }\n }\n } catch (e) {\n console.log(\"googleAnalytics: failed to get custom dimensions\");\n }\n\n // Uniquely identify by account token\n var accountToken = \"unknown\";\n try {\n accountToken = Pebble.getAccountToken();\n } catch (e) {\n console.log(\"googleAnalytics: unable to get accountToken\");\n }\n\n // Pick up as much platform information as possible\n // This will enable decisions on what features to add and what should take\n // priority\n var platform = \"unknown\";\n var model = \"unknown\";\n var language = \"unknown\";\n var depth = \"unknown\";\n var screenres = \"unknown\";\n var firmware = \"unknown\";\n try {\n var wi = Pebble.getActiveWatchInfo();\n if (wi && wi.platform) {\n platform = wi.platform;\n if (platform === \"aplite\") {\n depth = \"bw\";\n } else {\n depth = \"colour\";\n }\n if (platform === \"chalk\") {\n screenres = \"180x180\";\n } else {\n screenres = \"144x168\";\n }\n }\n if (wi && wi.model) {\n model = wi.model;\n }\n if (wi && wi.language) {\n language = wi.language;\n }\n if (wi && wi.firmware && wi.firmware.major && wi.firmware.minor) {\n firmware = \"v\" + wi.firmware.major + \".\" + wi.firmware.minor;\n if (wi.firmware.patch) {\n firmware += \".\" + wi.firmware.patch;\n if (wi.firmware.suffix) {\n firmware += \".\" + wi.firmware.suffix;\n }\n }\n }\n } catch (e) {\n console.log(\"googleAnalytics: unable to get active watch info\");\n }\n\n // User agent\n var userAgent = getUserAgent(model);\n\n // Build the google analytics api\n var msg = \"v=1\" + \n \"&tid=UA-72769045-3\" + \n \"&ds=app\" + \n \"&cid=\" + accountToken + \n \"&t=event\" + \n \"&cd=\" + platform + \n \"&an=Morpheuz\" + \n \"&ec=\" + userAgent + \n \"&ea=\" + platform + \n \"&el=\" + model + \n \"&ul=\" + language + \n \"&av=\" + version + \n \"&sd=\" + depth + \n \"&sr=\" + screenres + \n \"&dh=\" + firmware + \n \"&dt=Morpheuz-\" + version + \n cd;\n\n console.log(\"googleAnalytics: \" + msg);\n\n // Send this across to google\n // Do not wait for a response, but report one if it turns up\n var req = new XMLHttpRequest();\n req.open(\"POST\", \"https://ssl.google-analytics.com/collect\", true);\n req.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n req.onload = function() {\n if (req.readyState === 4 && req.status === 200) {\n console.log(\"googleAnalytics: OK\");\n } else if (req.readyState === 4 && (req.status >= 300 && req.status <= 599)) {\n console.log(\"googleAnalytics: Failed\");\n }\n };\n req.send(msg);\n\n } catch (err) {\n console.log(\"googleAnalyticsCall: Failed to call google Analytics with \" + err);\n }\n\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 tracker_script(rules, key) {\n\tvar rule = find_rule(rules, \"key\", key);\n\tif (rule != null) {\n\t\tvar experiment = rule.experiment;\n\t\tvar uacct = rule.uacct;\n\t\tif(typeof(_gat)!='object')document.write('<sc'+'ript src=\"http'+\n\t\t(document.location.protocol=='https:'?'s://ssl':'://www')+\n\t\t'.google-analytics.com/ga.js\"></sc'+'ript>');\n\n\t\tdocument.write('<sc'+'ript> ' + 'try { var pageTracker=_gat._getTracker(\\\"' + uacct + '\\\"); pageTracker._trackPageview(\\\"/' + experiment + '/test\\\"); }catch(err){} ' + '</sc'+'ript>');\n\t}\n}", "function sendReport(url, body) {\n var isRealNavigator = Object.prototype.toString.call(global && global.navigator) === '[object Navigator]';\n var hasSendBeacon = isRealNavigator && typeof global.navigator.sendBeacon === 'function';\n if (hasSendBeacon) {\n // Prevent illegal invocations - https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch\n var sendBeacon = global.navigator.sendBeacon.bind(global.navigator);\n return sendBeacon(url, body);\n }\n if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.supportsFetch)()) {\n var fetch_1 = getNativeFetchImplementation();\n return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.forget)(fetch_1(url, {\n body: body,\n method: 'POST',\n credentials: 'omit',\n keepalive: true,\n }));\n }\n}", "trackCustomEvent($data, $event) {\n ga('send', 'event', $data, $event);\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 trackGoogle(googlePixelId, customData) {\n if (typeof window.google_trackConversion === \"function\") {\n if (customData) {\n window.google_trackConversion({\n google_conversion_id: googlePixelId,\n google_remarketing_only: false,\n google_custom_params: {\n customData\n }\n });\n } else {\n window.google_trackConversion({\n google_conversion_id: googlePixelId,\n google_remarketing_only: false\n });\n }\n\n } else {\n return false;\n }\n }", "page(rudderElement) {\n logger.debug('=== In Adroll Page ===');\n const { message } = rudderElement;\n const eventsHashmap = getHashFromArray(this.eventsMap);\n let pageFullName;\n if (!message.name && !message.category) {\n pageFullName = `Viewed a Page`;\n } else if (!message.name && message.category) {\n pageFullName = `Viewed ${message.category} Page`;\n } else if (message.name && !message.category) {\n pageFullName = `Viewed ${message.name} Page`;\n } else {\n pageFullName = `Viewed ${message.category} ${message.name} Page`;\n }\n\n const segmentId = eventsHashmap[pageFullName.toLowerCase()];\n if (!segmentId) {\n logger.error(`The event ${pageFullName} is not mapped to any segmentId. Aborting!`);\n return;\n }\n\n window.__adroll.record_user({\n adroll_segments: segmentId,\n name: pageFullName,\n path: window.location.pathname,\n referrer: window.document.referrer,\n search: window.location.search,\n title: window.document.title,\n url: window.location.href,\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw route and vehicles
draw() { var canvas = document.getElementById("CANVAS"); var ctx = canvas.getContext("2d"); var cVehicles = this.getVehicleCount(); ctx.save(); ctx.scale(def.scale, def.scale); this._drawRoute(ctx); for (let iVehicle = 0; iVehicle < cVehicles; iVehicle ++) this._drawVehicle(ctx, route.getVehicle(iVehicle)); ctx.restore(); }
[ "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 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 drawRoute(id, route){\n\n\tfor(var i=0; i<route.length-1; i++){\n\n\t\tdrawSegment(id, route[i], route[i+1]);\n\t}\n}", "function drawLane(x, y, w, h, direction, c) {\r\n noStroke();\r\n fill(c);\r\n //Road Lane\r\n rect(x, y, w, h);\r\n\r\n //Draw 4 cars using random spacing and colour to give effect of cars in motion. In setup, reduced framerate so cars move at a decent pace\r\n let spacings = [10, 15, 18, 13, 20, 21, 14, 8, 6, 3, 12, -3];\r\n let spacing = random(spacings); // select random space\r\n\r\n let colours = [\"red\", \"purple\", \"green\", \"blue\", \"yellow\"];\r\n let colour = random(colours); // select random colour\r\n drawCar(x + 10 + spacing * 4, y, 30, 20, colour, direction);\r\n\r\n drawCar(x + 205 + spacing * 3, y, 30, 20, colour, direction);\r\n drawCar(x + 400 + spacing * 5, y, 30, 20, colour, direction);\r\n drawCar(x + 525 + spacing * 7, y, 30, 20, colour, direction);\r\n\r\n //Draw dotted line to separate lane\r\n dottedLine(x, y);\r\n}", "function drawRoute(map, route, color) {\n for (var i = 0; i < route.length; i++) {\n stop = route[i][0];\n var edge = [];\n edge.push(stop.coords);\n\n /* loop to handle forks */\n for (var j = 0; j < route[i][1].length; j++) {\n edge.push(route[i][1][j].coords)\n var path = new google.maps.Polyline({\n path: edge,\n geodesic: true,\n strokeColor: color,\n strokeOpacity: 1.0,\n strokeWeight: 2\n });\n path.setMap(map);\n edge.pop();\n }\n }\n}", "function drawVehicles() {\n for (i=0;i<vehicles.length;i++) {\n //Left side, right side+image width, top side, bottom side\n if (vehicles[i][0].pos[0] >= (window.innerWidth/2)-(10*tileSize)/2 && vehicles[i][0].pos[0] <= (window.innerWidth/2)+(10*tileSize)/2-vehicles[i][0].image.width*2 && vehicles[i][0].pos[1] >= (window.innerHeight/2)-(10*tileSize)/2 && vehicles[i][0].pos[1] <= (window.innerHeight/2)+(10*tileSize)/2) {\n vehicles[i][0].draw(vehicles[i][0].pos[0],vehicles[i][0].pos[1],vehicles[i][0].image.width*2,vehicles[i][0].image.height*2);\n } else {\n //If it's outside the grid space, remove it from the array\n vehicles.splice(i,1);\n }\n }\n //Create a car if this random number generator condition is true\n if (Math.random()*1 > 0.999) {\n createVehicle();\n }\n //The movement for the vehicles\n moveVehicles();\n}", "function draw_travels() {\n removeLines();\n for (var i = 0, len = data.length; i < len; i++) {\n drawLine(data[i])\n }\n}", "function drawFlights(summary, airportCode) {\n // referenced www.tnoda.com\n\n if (airportCode) {\n summary = summary.filter(item => {\n return (item.arrival === airportCode || item.departure === airportCode)\n });\n }\n\n const flights = groups.flights;\n // flights.attr(\"opacity\", 1);\n\n const path = d3.geoPath(projection);\n const planeScale = d3.scaleSqrt()\n .domain(d3.extent(summary, d => d.flights))\n .range([0.3, 2]);\n\n\n function fly(departure, arrival, flightCount) {\n\n var route = flights.append(\"path\")\n .datum({ type: \"LineString\", coordinates: [departure, arrival] })\n .attr(\"class\", \"route\")\n .attr(\"d\", path);\n\n var plane = flights.append(\"path\")\n .attr(\"class\", \"plane\")\n .attr(\"d\", \"m25.21488,3.93375c-0.44355,0 -0.84275,0.18332 -1.17933,0.51592c-0.33397,0.33267 -0.61055,0.80884 -0.84275,1.40377c-0.45922,1.18911 -0.74362,2.85964 -0.89755,4.86085c-0.15655,1.99729 -0.18263,4.32223 -0.11741,6.81118c-5.51835,2.26427 -16.7116,6.93857 -17.60916,7.98223c-1.19759,1.38937 -0.81143,2.98095 -0.32874,4.03902l18.39971,-3.74549c0.38616,4.88048 0.94192,9.7138 1.42461,13.50099c-1.80032,0.52703 -5.1609,1.56679 -5.85232,2.21255c-0.95496,0.88711 -0.95496,3.75718 -0.95496,3.75718l7.53,-0.61316c0.17743,1.23545 0.28701,1.95767 0.28701,1.95767l0.01304,0.06557l0.06002,0l0.13829,0l0.0574,0l0.01043,-0.06557c0,0 0.11218,-0.72222 0.28961,-1.95767l7.53164,0.61316c0,0 0,-2.87006 -0.95496,-3.75718c-0.69044,-0.64577 -4.05363,-1.68813 -5.85133,-2.21516c0.48009,-3.77545 1.03061,-8.58921 1.42198,-13.45404l18.18207,3.70115c0.48009,-1.05806 0.86881,-2.64965 -0.32617,-4.03902c-0.88969,-1.03062 -11.81147,-5.60054 -17.39409,-7.89352c0.06524,-2.52287 0.04175,-4.88024 -0.1148,-6.89989l0,-0.00476c-0.15655,-1.99844 -0.44094,-3.6683 -0.90277,-4.8561c-0.22699,-0.59493 -0.50356,-1.07111 -0.83754,-1.40377c-0.33658,-0.3326 -0.73578,-0.51592 -1.18194,-0.51592l0,0l-0.00001,0l0,0z\");\n\n transition(plane, route, flightCount);\n }\n\n function transition(plane, route, flightCount) {\n const l = route.node().getTotalLength();\n // console.log(route.node())\n plane.transition()\n .duration(l * 50)\n .attrTween(\"transform\", delta(route.node(), flightCount))\n .on(\"end\", () => { route.remove(); })\n .remove();\n }\n\n function delta(arc, flightCount) {\n var l = arc.getTotalLength();\n\n return function(i) {\n return function(t) {\n\n var p = arc.getPointAtLength(t * l);\n\n var t2 = Math.min(t + 0.05, 1);\n var p2 = arc.getPointAtLength(t2 * l);\n\n var x = p2.x - p.x;\n var y = p2.y - p.y;\n var r = 90 - Math.atan2(-y, x) * 180 / Math.PI;\n var s = Math.min(Math.sin(Math.PI * t) * 0.7, 0.3) * 1.3;\n\n // let s;\n // if (t <= 0.5) {\n // s = (l /300) * ((planeScale(flightCount) / 0.5) * t) + 0.2;\n // } else {\n // s = (l /300) * ((planeScale(flightCount) / 0.5) * (1 - t)) + 0.2;\n // };\n\n return `translate(${p.x}, ${p.y}) scale(${s}) rotate(${r})`;\n }\n }\n }\n\n let i = 0;\n window.refreshIntervalId = setInterval(function() {\n if (i > summary.length - 1) {\n i = 0;\n }\n var pair = summary[i];\n\n // fly(summary);\n fly(pair.departure_coords, pair.arrival_coords, pair.flights);\n\n i++;\n }, 150);\n\n}", "drawJourney(canvas){\n\n //----------------------\n //Set variables\n //----------------------\n let numShapes = 0;\n let numPaths = 0;\n let numEndPoints = 0;\n let eventList = new Map();\n let drawPaths = [];\n let drawnPathItems = new Map();\n\n //----------------------\n //Initialize canvas\n //----------------------\n let canvasWidth = 2560;\n let canvasHeight = 1440;\n canvas.style.width = canvasWidth + \"px\";\n canvas.style.height = canvasHeight + \"px\"; \n\n let scale = window.devicePixelRatio;\n canvas.width = canvasWidth * scale;\n canvas.height = canvasHeight * scale;\n\n // Normalize coordinate system to use css pixels.\n var canvasContext = canvas.getContext(\"2d\");\n canvasContext.scale(scale, scale);\n\n //----------------------\n //Grab spec and start parsing it\n //----------------------\n\n //Entry Events\n let journeyEntry = \"\";\n if (this.jsonSpec.triggers[0] != undefined) {\n journeyEntry = this.jsonSpec.triggers[0];\n }\n\n //All Activities\n let journeyActivities = this.jsonSpec.activities;\n let activitySet = new Set();\n for (const activity of journeyActivities) {\n activitySet.add(activity);\n eventList.set(activity.key, {\"x\": 0, \"y\": 0});\n }\n numShapes = eventList.size;\n\n //Only Non-Exits\n let journeyActivityPoints = new Set();\n for (let activity of activitySet) {\n if (activity.outcomes) {\n journeyActivityPoints.add(activity);\n }\n }\n\n //Only Decisions\n let journeyDecisionPoints = new Set();\n for (let activity of activitySet) {\n if (activity.type.includes(\"Split\") || activity.type.includes(\"Decision\")) {\n journeyDecisionPoints.add(activity);\n numPaths += activity.outcomes.length\n }\n }\n\n //Only Exits\n let journeyEndPoints = new Set();\n for (let activity of activitySet) {\n console.log(activity.outcomes);\n if (!activity.outcomes || !activity.outcomes[0].next) {\n journeyEndPoints.add(activity);\n }\n }\n numEndPoints = journeyEndPoints.size;\n\n //Debug\n console.log(\"Number of total distinct paths: \" + numPaths);\n console.log(\"Number of total distinct ends: \" + numEndPoints);\n console.log(\"Number of distinct events: \" + numShapes);\n\n //Use Exits to work back to fill paths\n for (let exit of journeyEndPoints) {\n\n let pathArray = [];\n let previousEventKey = exit.key;\n let activityArray = Array.from(journeyActivityPoints); \n\n //Find next event in chain by going through outcomes\n for (let i = 0; i < activityArray.length; i++) {\n let outcomes = activityArray[i].outcomes;\n for (let outcome of outcomes) {\n if (outcome.next == previousEventKey) {\n pathArray.push(activityArray[i]);\n previousEventKey = activityArray[i].key;\n i = 0;\n }\n }\n }\n\n //Reverse Array\n pathArray.reverse();\n\n //Add entry and exit activity to the end\n pathArray.unshift(journeyEntry);\n pathArray.push(exit);\n\n //Add entire array to the path\n drawPaths.push(pathArray);\n }\n\n //Debug\n console.log(drawPaths);\n\n //----------------------\n //Start Drawing\n //----------------------\n\n //Set constants\n const top = 0;\n const left = 0;\n const shapeSize = 100;\n const shapeSpacing = 200;\n const shapeRounding = 20;\n const shapePadding = 5;\n\n const fontMarginTop = 10;\n const fontHeader = 'bold 17px Arial'\n const fontBody = '15px Arial'\n const fontColor = '#000';\n\n const connectorColor = \"#666\";\n const connectorWidth = 5;\n const connectorRadius = 12;\n\n const eventEntryColor = '#97cf66';\n const activityEntryColor = '#52c7bc';\n const activityColor = '#52c7bc';\n const decisionColor = '#ec8b23';\n const splitColor = '#97a4b1';\n\n const descriptionWidth = 150;\n const descriptionHeight = 150;\n const descriptionPadding = 5;\n const descriptionLineHeight = 20;\n const descriptionFillColor = '#FFF'\n const descriptionBorderColor = '#BBB'\n\n //----------------------\n //Draw Entry Event\n //----------------------\n \n //Draw Entry Event\n if (journeyEntry != '') { \n let entryEventX = left + shapeSize;\n let entryEventY = top + shapeSize;\n\n canvasContext.beginPath();\n canvasContext.arc(entryEventX, entryEventY, shapeSize / 2, 0, 2 * Math.PI, false);\n canvasContext.closePath();\n canvasContext.fillStyle = eventEntryColor;\n canvasContext.fill();\n canvasContext.font = fontHeader;\n canvasContext.fillStyle = fontColor;\n canvasContext.textAlign = \"center\";\n canvasContext.fillText(\"Entry\", entryEventX, entryEventY + fontMarginTop);\n\n //Draw Entry Event Box\n let entryEventDescriptionX = entryEventX - descriptionWidth / 2;\n let entryEventDescriptionY = entryEventY + descriptionHeight / 2 + descriptionPadding;\n\n canvasContext.beginPath();\n canvasContext.rect(entryEventDescriptionX, entryEventDescriptionY, descriptionWidth, descriptionHeight);\n canvasContext.closePath();\n canvasContext.fillStyle = descriptionFillColor;\n canvasContext.fill();\n canvasContext.lineWidth = 1;\n canvasContext.strokeStyle = descriptionBorderColor;\n canvasContext.stroke();\n\n //Draw Entry Event Text\n let entryEventDescriptionTextX = entryEventDescriptionX + descriptionWidth / 1.9;\n let entryEventDescrtipionTextY = entryEventDescriptionY + descriptionLineHeight;\n\n canvasContext.fillStyle = fontColor;\n canvasContext.textAlign = \"center\";\n canvasContext.font = fontHeader;\n canvasContext.fillText(\"Name:\", entryEventDescriptionTextX, entryEventDescrtipionTextY);\n canvasContext.font = fontBody;\n this.wrapText(canvasContext, journeyEntry.key, entryEventDescriptionTextX, entryEventDescrtipionTextY + descriptionLineHeight, descriptionWidth, descriptionLineHeight);\n canvasContext.font = fontHeader;\n canvasContext.fillText(\"Description:\", entryEventDescriptionTextX, entryEventDescrtipionTextY + descriptionLineHeight * 3);\n canvasContext.font = fontBody;\n this.wrapText(canvasContext, journeyEntry.name, entryEventDescriptionTextX, entryEventDescrtipionTextY + descriptionLineHeight * 4, descriptionWidth, descriptionLineHeight);\n\n //Add to list\n eventList.set(journeyEntry.key, {\"x\": entryEventX, \"y\": entryEventY});\n }\n\n //----------------------\n // Draw All Other Activities\n //----------------------\n\n //Set up Branch\n let branchRightCounter = 0;\n let branchDownCounter = 0;\n\n // For each path defined by a unique end point...\n for (let currentPath of drawPaths) { \n\n //Debug \n //console.log(\"Current Path is \");\n //console.log(currentPath);\n\n //Iterate through each step\n for (let pathStep = 1; pathStep < currentPath.length; pathStep++) {\n\n // Count for right steps as we go\n branchRightCounter = pathStep;\n \n // Determine the current activity type\n let currentActivity = currentPath[pathStep];\n let currentActivityType = currentActivity.type;\n\n //Ensure we're not duplicating efforts, and if we are, move onto the next node\n if (drawnPathItems.has(currentActivity.key)) { \n //console.log(\"Repeating a drawn activity, so skipping\");\n continue; \n }\n\n // Debug\n //console.log(\"Current on branch down \" + branchDownCounter);\n //console.log(\"Evaluating activity at step \" + pathStep + \" and type \" + currentActivityType);\n \n if (currentActivityType.includes(\"Decision\") || currentActivityType.includes(\"Split\")) {\n\n // Debug\n //console.log(\"Drawing decision activity for \" + currentActivity.name);\n \n // Draw Decisions\n let nextEventX = left + shapeSize + (shapeSpacing * branchRightCounter) + shapeSpacing / 4;\n let nextEventY = (top + shapeSize) / 2 + (shapeSpacing + descriptionHeight) * branchDownCounter; \n\n canvasContext.beginPath();\n canvasContext.moveTo(nextEventX, nextEventY);\n canvasContext.lineTo(nextEventX + shapeSize / 2, nextEventY + shapeSize / 2);\n canvasContext.lineTo(nextEventX, nextEventY + shapeSize);\n canvasContext.lineTo(nextEventX - shapeSize / 2, nextEventY + shapeSize / 2);\n canvasContext.closePath();\n\n canvasContext.fillStyle = currentActivityType.includes(\"Split\") ? splitColor : decisionColor;\n canvasContext.fill();\n canvasContext.font = fontHeader;\n canvasContext.fillStyle = fontColor;\n canvasContext.textAlign = \"center\";\n canvasContext.fillText(currentActivityType.includes(\"Split\") ? \"Split\" : \"Decision\", nextEventX, nextEventY + shapeSize / 2 + fontMarginTop / 1.5);\n\n //Draw Decision Box\n let decisionEventDescriptionX = nextEventX - descriptionWidth / 2;\n let decisionEventDescriptionY = nextEventY + descriptionHeight / 1.2 + descriptionPadding;\n\n canvasContext.beginPath();\n canvasContext.rect(decisionEventDescriptionX, decisionEventDescriptionY, descriptionWidth, descriptionHeight);\n canvasContext.closePath();\n canvasContext.fillStyle = descriptionFillColor;\n canvasContext.fill();\n canvasContext.lineWidth = 1;\n canvasContext.strokeStyle = descriptionBorderColor;\n canvasContext.stroke();\n\n //Draw Entry Event Text\n let decisionEventDescriptionTextX = nextEventX;\n let decisionEventDescrtipionTextY = nextEventY + descriptionLineHeight + shapeSize + descriptionPadding * 6;\n\n canvasContext.fillStyle = fontColor;\n canvasContext.textAlign = \"center\";\n canvasContext.font = fontHeader;\n canvasContext.fillText(\"Name:\", decisionEventDescriptionTextX, decisionEventDescrtipionTextY);\n canvasContext.font = fontBody;\n this.wrapText(canvasContext, currentActivity.key, decisionEventDescriptionTextX, decisionEventDescrtipionTextY + descriptionLineHeight, descriptionWidth, descriptionLineHeight);\n canvasContext.font = fontHeader;\n canvasContext.fillText(\"Description:\", decisionEventDescriptionTextX, decisionEventDescrtipionTextY + descriptionLineHeight * 3);\n canvasContext.font = fontBody;\n this.wrapText(canvasContext, currentActivity.name, decisionEventDescriptionTextX, decisionEventDescrtipionTextY + descriptionLineHeight * 4, descriptionWidth, descriptionLineHeight);\n\n //Add to list\n eventList.set(currentActivity.key, {\"x\": nextEventX, \"y\": nextEventY});\n\n //Iterate\n branchRightCounter++;\n\n } else {\n\n // Debug\n //console.log(\"Drawing normal activity for \" + currentActivity.name);\n\n // Draw Activity\n let nextEventX = left + shapeSize + (shapeSpacing * branchRightCounter) ;\n let nextEventY = (top + shapeSize) / 2 + (shapeSpacing + descriptionHeight) * branchDownCounter; \n\n this.roundRect(canvasContext, nextEventX, nextEventY, shapeSize, shapeSize, shapeRounding);\n canvasContext.fillStyle = activityEntryColor;\n canvasContext.fill();\n canvasContext.font = fontHeader;\n canvasContext.fillStyle = fontColor;\n canvasContext.textAlign = \"center\";\n canvasContext.fillText(\"Activity\", nextEventX + shapeSize / 2, nextEventY + shapeSize / 2 + fontMarginTop);\n\n\n //Draw Entry Event Box\n let endpointEventDescriptionX = nextEventX - descriptionWidth / 5;\n let endpointEventDescriptionY = nextEventY + descriptionHeight / 1.2 + descriptionPadding;\n\n canvasContext.beginPath();\n canvasContext.rect(endpointEventDescriptionX, endpointEventDescriptionY, descriptionWidth, descriptionHeight);\n canvasContext.closePath();\n canvasContext.fillStyle = descriptionFillColor;\n canvasContext.fill();\n canvasContext.lineWidth = 1;\n canvasContext.strokeStyle = descriptionBorderColor;\n canvasContext.stroke();\n\n //Draw Entry Event Text\n let endpointEventDescriptionTextX = nextEventX + descriptionWidth / 3;\n let endpointEventDescrtipionTextY = nextEventY + descriptionLineHeight + shapeSize + descriptionPadding * 6;\n\n canvasContext.fillStyle = fontColor;\n canvasContext.textAlign = \"center\";\n canvasContext.font = fontHeader;\n canvasContext.fillText(\"Name:\", endpointEventDescriptionTextX, endpointEventDescrtipionTextY);\n canvasContext.font = fontBody;\n this.wrapText(canvasContext, currentActivity.key, endpointEventDescriptionTextX, endpointEventDescrtipionTextY + descriptionLineHeight, descriptionWidth, descriptionLineHeight);\n canvasContext.font = fontHeader;\n canvasContext.fillText(\"Description:\", endpointEventDescriptionTextX, endpointEventDescrtipionTextY + descriptionLineHeight * 3);\n canvasContext.font = fontBody;\n this.wrapText(canvasContext, currentActivity.name, endpointEventDescriptionTextX, endpointEventDescrtipionTextY + descriptionLineHeight * 4, descriptionWidth, descriptionLineHeight);\n\n //Add to list\n eventList.set(currentActivity.key, {\"x\": nextEventX, \"y\": nextEventY});\n\n //Iterate\n branchRightCounter++;\n\n }\n\n // Mark down that this activity has been drawn\n drawnPathItems.set(currentActivity.key, currentActivity);\n }\n\n //Iterate\n branchDownCounter++;\n }\n\n //----------------------\n // Draw All Connectors\n //----------------------\n\n //Connector type\n let connectorType = \"straight\";\n let currentBranchDown = 0;\n\n //Clear Drawn items\n drawnPathItems.clear();\n\n //For each path...\n for (let currentPath of drawPaths) { \n\n //And each step in each path...\n for (let pathStep = 1; pathStep < currentPath.length; pathStep++) {\n\n // Grab current and previous activity keys\n let currentActivityKey = currentPath[pathStep].key;\n let currentActivityX = eventList.get(currentActivityKey).x;\n let currentyActivityY = eventList.get(currentActivityKey).y;\n\n let previousActivityKey = currentPath[pathStep - 1].key;\n let previousActivityX = eventList.get(previousActivityKey).x;\n let previousActivityY = eventList.get(previousActivityKey).y;\n\n let previousActivityType = currentPath[pathStep - 1].type;\n\n //console.log(drawnPathItems);\n\n //Ensure we're not duplicating efforts, and if we are, move onto the next node\n if (drawnPathItems.has(currentActivityKey)) { \n //console.log(\"Repeating a drawn activity, so skipping\");\n continue; \n } else {\n drawnPathItems.set(currentActivityKey, currentPath[pathStep]);\n }\n\n //Debug\n //console.log (\"Current Activity: \" + currentActivityKey + \" Previous Activity: \" + previousActivityKey);\n\n if (previousActivityType == \"Event\") {\n // Draw Elbow Connector between the two\n let start = { \"x\": currentActivityX + shapeSize / 2 + shapePadding, \"y\": currentyActivityY + shapeSize / 2 };\n let end = { \"x\": previousActivityX, \"y\": previousActivityY };\n this.drawElbow(canvasContext, connectorType, start, end, connectorRadius, connectorColor, connectorWidth );\n continue;\n }\n\n if (currentBranchDown >= 1) {\n // Draw Elbow Connector between the two\n let start = { \"x\": currentActivityX + shapeSize / 2 + shapePadding, \"y\": currentyActivityY + shapeSize / 2 };\n let end = { \"x\": previousActivityX, \"y\": previousActivityY + shapeSize / 2 };\n this.drawElbow(canvasContext, connectorType, start, end, connectorRadius, connectorColor, connectorWidth );\n } else {\n // Draw Elbow Connector between the two\n let start = { \"x\": currentActivityX + shapeSize / 2, \"y\": currentyActivityY + shapeSize / 2};\n let end = { \"x\": previousActivityX, \"y\": previousActivityY + shapeSize / 2 };\n this.drawElbow(canvasContext, connectorType, start, end, connectorRadius, connectorColor, connectorWidth );\n }\n\n \n }\n\n connectorType = \"bottomLeft\";\n currentBranchDown++;\n }\n\n }", "function drawRoad(x1, y1, x2, y2, color) {\n ctx.beginPath();\n if (Math.abs(x1 - x2) > EPS) {\n ctx.moveTo(x1, y1 + 5);\n ctx.lineTo(x2, y2 + 5);\n ctx.lineTo(x2, y2 - 5);\n ctx.lineTo(x1, y1 - 5);\n } else if (y1 > y2) {\n ctx.moveTo(x1 - 4.5, y1 - 5);\n ctx.lineTo(x2 - 4.5, y2 + 5);\n ctx.lineTo(x2 + 4.5, y2 + 5);\n ctx.lineTo(x1 + 4.5, y1 - 5);\n } else if (y2 > y1) {\n ctx.moveTo(x1 - 4.5, y1 + 5);\n ctx.lineTo(x2 - 4.5, y2 - 5);\n ctx.lineTo(x2 + 4.5, y2 - 5);\n ctx.lineTo(x1 + 4.5, y1 + 5);\n }\n ctx.closePath();\n ctx.fillStyle = COLORS[color];\n ctx.fill();\n ctx.stroke();\n }", "function drawCar(x, y, width, height, color, direction) {\r\n //Draw 4 wheels for the car. The wheels are placed more to the back and the front is longer\r\n //to give a sense of direction in which the car is traveling\r\n fill(\"black\");\r\n var frontWheelX = x + 12;\r\n var backWheelX = x + 33;\r\n if (direction === \"west\") {\r\n frontWheelX = frontWheelX + 6;\r\n backWheelX = backWheelX + 6;\r\n }\r\n //Draw 4 cars\r\n rect(frontWheelX, y + 22, width - 18, height - 15);\r\n rect(frontWheelX, y + 43, width - 18, height - 15);\r\n rect(backWheelX, y + 22, width - 18, height - 15);\r\n rect(backWheelX, y + 43, width - 18, height - 15);\r\n\r\n //Fill car color\r\n fill(color);\r\n rect(x + 10, y + 25, width + 13, height);\r\n}", "function route2Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations2.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations2.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations2.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations2.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}", "draw(ctx) {\r\n if (this.isDistanced) {\r\n this.distanceGraph();\r\n }\r\n // draw all nodes and store them in grid array\r\n this.nodeList.forEach(node => {\r\n node.draw(ctx);\r\n storeNodeAt(node, node.x, node.y);\r\n });\r\n\r\n // draw all edges\r\n this.edgeList.forEach(edge => {\r\n edge.draw(ctx);\r\n });\r\n\r\n\r\n }", "function route1Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}", "function drawRoute(coords, color) {\n var routeLine = L.polyline(coords, {\n color: color,\n weight: 7\n });\n\n layers[\"routeLine\"] = new L.LayerGroup();\n layers[\"routeLine\"].addLayer(routeLine);\n layers[\"routeLine\"].addTo(map);\n map.fitBounds(routeLine.getBounds());\n}", "function displayRoute() {\r\n clearOverlays();\r\n var start\r\n var end\r\n if (inputLocation == \"\") { start = currentLocation; end = currentCafeLocation; }\r\n else { start = inputLocation; end = currentCafeLocation; }\r\n\r\n var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get \"DirectionsRendererOptions\" object\r\n directionsDisplay.setMap(map); // map should be already initialized.\r\n\r\n var request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING };\r\n var directionsService = new google.maps.DirectionsService();\r\n directionsService.route(request, function (response, status) {\r\n if (status == google.maps.DirectionsStatus.OK) {\r\n directionsDisplay.setDirections(response);\r\n }\r\n });\r\n markersArray.push(directionsDisplay);\r\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}", "function createWaypoints(result) {\n\n // turn overview path of route into polyline\n var pathPolyline = new google.maps.Polyline({\n path: result.routes[0].overview_path\n });\n\n // get points at intervals of 85% of range along overview path of route\n var points = pathPolyline.GetPointsAtDistance(0.85 * range);\n\n // iterate over these points\n for (var i = 0, n = points.length; i < n; i++) {\n\n // find the closest charging station to that point\n var closeStation = getClosestStation(points[i]);\n\n // create waypoint at that station\n var newWaypoint = {\n location: closeStation.latlng,\n stopover: true\n };\n\n // add it to the waypoints array\n waypoints.push(newWaypoint);\n\n // add station info to station stops array\n stationStops.push(closeStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: closeStation.latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n }\n}", "function resolveMaze(){\n tryMaze(positionFixe);\n traceRoad(chemin_parcouru,\"color2\");\n traceRoad(tabVisite);\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a text cursor. The query is the search string, `from` to / `to` provides the region to search. / / When `normalize` is given, it will be called, on both the query / string and the content it is matched against, before comparing. / You can, for example, create a caseinsensitive search by / passing `s => s.toLowerCase()`. / / Text is always normalized with / [`.normalize("NFKD")`]( / (when supported).
constructor(text, query, from = 0, to = text.length, normalize) { /// The current match (only holds a meaningful value after /// [`next`](#search.SearchCursor.next) has been called and when /// `done` is false). this.value = { from: 0, to: 0 }; /// Whether the end of the iterated region has been reached. this.done = false; this.matches = []; this.buffer = ""; this.bufferPos = 0; this.iter = text.iterRange(from, to); this.bufferStart = from; this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize; this.query = this.normalize(query); }
[ "constructor(text, query, from = 0, to = text.length, normalize) {\n /// The current match (only holds a meaningful value after\n /// [`next`](#search.SearchCursor.next) has been called and when\n /// `done` is false).\n this.value = { from: 0, to: 0 };\n /// Whether the end of the iterated region has been reached.\n this.done = false;\n this.matches = [];\n this.buffer = \"\";\n this.bufferPos = 0;\n this.iter = text.iterRange(from, to);\n this.bufferStart = from;\n this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize;\n this.query = this.normalize(query);\n }", "constructor(text, query, options, from = 0, to = text.length) {\n this.text = text\n this.to = to\n this.curLine = ''\n /**\n Set to `true` when the cursor has reached the end of the search\n range.\n */\n this.done = false\n /**\n Will contain an object with the extent of the match and the\n match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next)\n sucessfully finds a match.\n */\n this.value = empty\n if (/\\\\[sWDnr]|\\n|\\r|\\[\\^/.test(query))\n return new MultilineRegExpCursor(text, query, options, from, to)\n this.re = new RegExp(\n query,\n baseFlags +\n ((\n options === null || options === void 0\n ? void 0\n : options.ignoreCase\n )\n ? 'i'\n : '')\n )\n this.test =\n options === null || options === void 0 ? void 0 : options.test\n this.iter = text.iter()\n let startLine = text.lineAt(from)\n this.curLineStart = startLine.from\n this.matchPos = toCharEnd(text, from)\n this.getLine(this.curLineStart)\n }", "getCursor(state, from = 0, to) {\n let st = state.doc ? state : EditorState.create({ doc: state })\n if (to == null) to = st.doc.length\n return this.regexp\n ? regexpCursor(this, st, from, to)\n : stringCursor(this, st, from, to)\n }", "function insertCompletionText(state, text, from, to) {\n let { main } = state.selection,\n fromOff = from - main.from,\n toOff = to - main.from\n return Object.assign(\n Object.assign(\n {},\n state.changeByRange((range) => {\n if (\n range != main &&\n from != to &&\n state.sliceDoc(range.from + fromOff, range.from + toOff) !=\n state.sliceDoc(from, to)\n )\n return { range }\n return {\n changes: {\n from: range.from + fromOff,\n to: to == main.from ? range.to : range.from + toOff,\n insert: text\n },\n range: EditorSelection.cursor(range.from + fromOff + text.length)\n }\n })\n ),\n { userEvent: 'input.complete' }\n )\n }", "function findNextOccurrence(state, query) {\n let { main, ranges } = state.selection\n let word = state.wordAt(main.head),\n fullWord = word && word.from == main.from && word.to == main.to\n for (\n let cycled = false,\n cursor = new SearchCursor(\n state.doc,\n query,\n ranges[ranges.length - 1].to\n );\n ;\n\n ) {\n cursor.next()\n if (cursor.done) {\n if (cycled) return null\n cursor = new SearchCursor(\n state.doc,\n query,\n 0,\n Math.max(0, ranges[ranges.length - 1].from - 1)\n )\n cycled = true\n } else {\n if (cycled && ranges.some((r) => r.from == cursor.value.from))\n continue\n if (fullWord) {\n let word = state.wordAt(cursor.value.from)\n if (\n !word ||\n word.from != cursor.value.from ||\n word.to != cursor.value.to\n )\n continue\n }\n return cursor.value\n }\n }\n }", "function indentRange(state, from, to) {\n let updated = Object.create(null)\n let context = new IndentContext(state, {\n overrideIndentation: (start) => {\n var _a\n return (_a = updated[start]) !== null && _a !== void 0 ? _a : -1\n }\n })\n let changes = []\n for (let pos = from; pos <= to; ) {\n let line = state.doc.lineAt(pos)\n pos = line.to + 1\n let indent = getIndentation(context, line.from)\n if (indent == null) continue\n if (!/\\S/.test(line.text)) indent = 0\n let cur = /^\\s*/.exec(line.text)[0]\n let norm = indentString(state, indent)\n if (cur != norm) {\n updated[line.from] = indent\n changes.push({\n from: line.from,\n to: line.from + cur.length,\n insert: norm\n })\n }\n }\n return state.changes(changes)\n }", "static spans(sets, from, to, iterator) {\n var _a;\n let cursor = new SpanCursor(sets, null, (_a = iterator.minPointSize) !== null && _a !== void 0 ? _a : -1).goto(from), pos = from;\n let open = cursor.openStart;\n for (;;) {\n let curTo = Math.min(cursor.to, to);\n if (cursor.point) {\n iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open);\n open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0);\n }\n else if (curTo > pos) {\n iterator.span(pos, curTo, cursor.active, open);\n open = cursor.openEnd(curTo);\n }\n if (cursor.to > to)\n break;\n pos = cursor.to;\n cursor.next();\n }\n return open;\n }", "function getLines(doc, from, to) {\n var out = [];\n doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value\n return out\n }", "isRangeCommented(state, range) {\n let textBefore = state.sliceDoc(range.from - SearchMargin, range.from);\n let textAfter = state.sliceDoc(range.to, range.to + SearchMargin);\n let spaceBefore = /\\s*$/.exec(textBefore)[0].length, spaceAfter = /^\\s*/.exec(textAfter)[0].length;\n let beforeOff = textBefore.length - spaceBefore;\n if (textBefore.slice(beforeOff - this.open.length, beforeOff) == this.open &&\n textAfter.slice(spaceAfter, spaceAfter + this.close.length) == this.close) {\n return { open: { pos: range.from - spaceBefore, margin: spaceBefore && 1 },\n close: { pos: range.to + spaceAfter, margin: spaceAfter && 1 } };\n }\n let startText, endText;\n if (range.to - range.from <= 2 * SearchMargin) {\n startText = endText = state.sliceDoc(range.from, range.to);\n }\n else {\n startText = state.sliceDoc(range.from, range.from + SearchMargin);\n endText = state.sliceDoc(range.to - SearchMargin, range.to);\n }\n let startSpace = /^\\s*/.exec(startText)[0].length, endSpace = /\\s*$/.exec(endText)[0].length;\n let endOff = endText.length - endSpace - this.close.length;\n if (startText.slice(startSpace, startSpace + this.open.length) == this.open &&\n endText.slice(endOff, endOff + this.close.length) == this.close) {\n return { open: { pos: range.from + startSpace + this.open.length,\n margin: /\\s/.test(startText.charAt(startSpace + this.open.length)) ? 1 : 0 },\n close: { pos: range.to - endSpace - this.close.length,\n margin: /\\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };\n }\n return null;\n }", "matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos);\n let start = Math.max(line.from, this.pos - 250);\n let str = line.slice(start - line.from, this.pos - line.from);\n let found = str.search(ensureAnchor(expr, false));\n return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };\n }", "isRangeCommented(state, range) {\n let textBefore = state.sliceDoc(range.from - SearchMargin, range.from);\n let textAfter = state.sliceDoc(range.to, range.to + SearchMargin);\n let spaceBefore = /\\s*$/.exec(textBefore)[0].length, spaceAfter = /^\\s*/.exec(textAfter)[0].length;\n let beforeOff = textBefore.length - spaceBefore;\n if (textBefore.slice(beforeOff - this.open.length, beforeOff) == this.open &&\n textAfter.slice(spaceAfter, spaceAfter + this.close.length) == this.close) {\n return { open: { pos: range.from - spaceBefore, margin: spaceBefore && 1 },\n close: { pos: range.to + spaceAfter, margin: spaceAfter && 1 } };\n }\n let startText, endText;\n if (range.to - range.from <= 2 * SearchMargin) {\n startText = endText = state.sliceDoc(range.from, range.to);\n }\n else {\n startText = state.sliceDoc(range.from, range.from + SearchMargin);\n endText = state.sliceDoc(range.to - SearchMargin, range.to);\n }\n let startSpace = /^\\s*/.exec(startText)[0].length, endSpace = /\\s*$/.exec(endText)[0].length;\n let endOff = endText.length - endSpace - this.close.length;\n if (startText.slice(startSpace, startSpace + this.open.length) == this.open &&\n endText.slice(endOff, endOff + this.close.length) == this.close) {\n return { open: { pos: range.from + startSpace + this.open.length,\n margin: /\\s/.test(startText.charAt(startSpace + this.open.length)) ? 1 : 0 },\n close: { pos: range.to - endSpace - this.close.length,\n margin: /\\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };\n }\n return null;\n }", "matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos)\n let start = Math.max(line.from, this.pos - 250)\n let str = line.text.slice(start - line.from, this.pos - line.from)\n let found = str.search(ensureAnchor(expr, false))\n return found < 0\n ? null\n : { from: start + found, to: this.pos, text: str.slice(found) }\n }", "extend(from, to = from) {\n if (from <= this.anchor && to >= this.anchor)\n return EditorSelection.range(from, to)\n let head =\n Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to\n return EditorSelection.range(this.anchor, head)\n }", "function text_search(q, ids, search_index){\n if (!search_index){\n console.log('Warning, no search index, searching manually');\n ids = ids.filter(id => id.match(q));\n } else {\n const results = search_index.query((query) => {\n const {LEADING, TRAILING} = lunr.Query.wildcard;\n q.split(/(\\s+)/).forEach(s => {\n if (s){\n query = query.term(s, {wildcard: LEADING|TRAILING});\n }\n });\n return query;\n });\n const valid_ids = {};\n results.forEach(r => valid_ids[r.ref] = 1);\n ids = ids.filter(id => valid_ids[id]);\n }\n return ids;\n}", "function _offsetFromRange(range, scope, atStart) {\n\t\t//\n\t\tvar dir = atStart ? 'start' : 'end',\n\t\t\tclone = scope.cloneNode(true),\n\t\t\tnode = range[dir+'Container'],\n\t\t\toffset = range[dir+'Offset'],\n\t\t\tpath = _pathToNode(node, scope),\n\t\t\tdupe = _nodeFromPath(path, clone),\n\t\t\trange = doc.createRange(),\n\t\t\trand = _randId(),\n\t\t\tre = new RegExp('<[^<]+'+rand),\n\t\t\tanchorNode = doc.createElement('a');\n\t\t//\n\t\tdocFrag.appendChild(clone); // opera\n\t\t//\n\t\tanchorNode.id = rand;\n\t\t//\n\t\trange.setStart(dupe, offset);\n\t\trange.collapse(true);\n\t\trange.insertNode(anchorNode);\n\t\t//\n\t\tdocFrag.removeChild(clone); // opera\n\t\t// Return the index of the regular expression inside the string or -1.\n\t\treturn clone.innerHTML.search(re);\n\t}", "function srQuery(container, search, replace, caseSensitive, wholeWord) {\r if (search) {\r var args = getArgs(caseSensitive, wholeWord);\r rng = document.body.createTextRange();\r rng.moveToElementText(container);\r clearUndoBuffer();\r while (rng.findText(search, 10000, args)) {\r rng.select();\r rng.scrollIntoView();\r if (confirm(\"Replace?\")) {\r rng.text = replace;\r pushUndoNew(rng, search, replace);\r }\r rng.collapse(false) ;\r } \r }\r}", "function getClickedWord(selRange, node) {\n var nodeText = document.createRange();\n nodeText.selectNode(node);\n\n var str = nodeText.toString();\n var loc = selRange.focusOffset;\n\n return isolateWord(str,loc);\n}", "range(start, end) {\n return new vscode.Range(start, end);\n }", "transform(range, op) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var {\n affinity = 'inward'\n } = options;\n var affinityAnchor;\n var affinityFocus;\n\n if (affinity === 'inward') {\n if (Range.isForward(range)) {\n affinityAnchor = 'forward';\n affinityFocus = 'backward';\n } else {\n affinityAnchor = 'backward';\n affinityFocus = 'forward';\n }\n } else if (affinity === 'outward') {\n if (Range.isForward(range)) {\n affinityAnchor = 'backward';\n affinityFocus = 'forward';\n } else {\n affinityAnchor = 'forward';\n affinityFocus = 'backward';\n }\n } else {\n affinityAnchor = affinity;\n affinityFocus = affinity;\n }\n\n return produce(range, r => {\n var anchor = Point.transform(r.anchor, op, {\n affinity: affinityAnchor\n });\n var focus = Point.transform(r.focus, op, {\n affinity: affinityFocus\n });\n\n if (!anchor || !focus) {\n return null;\n }\n\n r.anchor = anchor;\n r.focus = focus;\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces all Mobilize America event documents in 'collection' with those in 'documents'. First deletes all documents in the collection which have a mobilizeId and whose mobilizeId is not in 'documents'. Then upserts each document in 'documents' based on its mobilizeId.
async function replaceEventsInCollection(documents, collection) { await deleteAllBut(documents, collection); const batches = batchArray(documents, upsertBatchSize); for (batch of batches) { await upsertBatch(batch, collection); } }
[ "async function dropAllDocuments(client, dataBaseName, collectionName) {\n\t\t// Delete collection including all its documents\n\t\tlet result = await client.db(dataBaseName).collection(collectionName).drop();\n\t\t// console.log(\"drop =>\" + result);\n\n\t\t// Re-create a collection again\n\t\t// result = await client.db(dataBaseName).createCollection(collectionName);\n\t\t// console.log(result);\n\t}", "async clearDatabase() {\n const { collections } = mongoose.connection;\n\n for (const key in collections) {\n const collection = collections[key];\n collection.deleteMany();\n }\n }", "function deleteDocuments(collection, ids) {\n return collection.deleteMany({_id: {$in: ids}})\n .then(result => {\n return result;\n })\n .catch(err => {\n console.error(`Delete failed with error: ${err}`);\n throw err;\n });\n}", "async function updateTempAndNullJobs() {\n var tempAndNullJobs = await getTempAndNullJobs();\n MongoClient.connect(process.env.PROD_MONGODB, async function(err, db) {\n for(i = 0; i < tempAndNullJobs.length; i++){\n db.collection('jobs').updateOne(\n {_id: new ObjectID(tempAndNullJobs[i]._id)},\n {$set: {\"jobType\": \"temporary\"}},\n {upsert: false}\n );\n\t}\n\tawait db.close();\n });\n}", "async function createMultipleDocuments(client, dataBaseName, collectionName, collData) {\n\t\t// let collData = [\t{ name: \"Jay\",\t\twins: 5, location: { city: \"Chennai\", country: \"India\"} },\n\t\t// \t\t\t\t\t{ name: \"Sridhar\",\twins: 9, location: { city: \"London\", country: \"UK\"}},\n\t\t// \t\t\t\t\t{ name: \"Sumitha\",\twins: 7, location: { city: \"Didcot\", country: \"America\"}}\n\t\t// ];\n\n\t\t// See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#insertMany for the insertMany() docs\n\t\tconst result = await client.db(dataBaseName).collection(collectionName).insertMany(collData);\n\n\t\tconsole.log(`${result.insertedCount} new listing(s) created with the following id(s):`);\n\t\tconsole.log(result.insertedIds);\n\t}", "function deleteData(datalibrary, doc) {\n for (var i = 0; i < doc.length; i++) {\n datalibrary.findByIdAndDelete(doc[i]._id, function (err) {\n if (err) {\n console.log(err);\n }\n })\n };\n}", "async updateDocuments () {\n\t\t// do a direct update to change the text of our test documents\n\t\tconst regexp = new RegExp(`^${this.randomizer}yes$`);\n\t\tawait this.data.test.updateDirect(\n\t\t\t{ flag: regexp },\n\t\t\t{ $set: { text: 'goodbye'} }\n\t\t);\n\t}", "function refreshIndexes(){\r\n\tvar pubs\r\n\ttry {\r\n\t\tPublication.find({}).then((data) => {\r\n\t\t\tpubs = data\r\n\t\t\tpubs.forEach((pub) => {\r\n\t\t\t\tlet tempPub = indexarPub(pub)\r\n\t\t\t\tPublication.updateOne({\"_id\":pub.id}, tempPub)\r\n\t\t\t})\r\n\t\t})\r\n\t} catch (error) {\r\n\t\tconsole.log(error)\r\n\t}\r\n}", "function deleteAllCollections() {\n return new Promise((resolve, reject) => {\n database.collection('assets').remove({}, (error, response) => {\n if (error) {\n reject(`-- Unable to delete all documents from collection: ${error}`);\n } else {\n resolve('All records deleted from collection.'); \n }\n })\n }).catch(err => new Error(err));\n}", "async function repopulateCountyCollection() {\n const County = mongoose.model(\"County\");\n const CountyTotal = mongoose.model(\"CountyTotal\");\n var fips = 34001;\n for (var i = 0; i < zipcodesNJ.length; i++) {\n await axios\n .get(\n `https://api.covidactnow.org/v2/county/${fips}.json?apiKey=${apiKey}`\n )\n .then((response) => {\n const index = i;\n\n var date = new Date();\n date.setDate(date.getDate() - 2);\n // Insert newest (daily) data into county DB\n County.updateOne(\n { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) },\n {\n $push: {\n [`data.${index}.counties.0.historicData`]: {\n $each: [\n {\n date: date,\n deathCt: response.data.actuals.deaths,\n positiveCt: response.data.actuals.cases,\n },\n ],\n $position: 0,\n },\n },\n },\n (err) => {\n if (err) {\n console.log(err);\n } else {\n console.log(`Added newest data for ${zipcodesNJ[i]}`);\n }\n }\n );\n\n // Delete oldest (daily) data from county DB\n County.updateOne(\n { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) },\n { $pop: { [`data.${index}.counties.0.historicData`]: 1 } },\n (err) => {\n if (err) {\n console.log(err);\n } else {\n console.log(`Deleted oldest data for ${zipcodesNJ[i]}`);\n }\n }\n );\n\n CountyTotal.updateOne(\n { id: fips },\n {\n totalCases: response.data.actuals.cases,\n },\n { upsert: true },\n function (err) {\n if (err) {\n console.log(err);\n } else {\n console.log(`Finished updating county total for FIPS: ${fips}`);\n }\n }\n );\n fips += 2;\n })\n .catch((error) => console.log(error));\n }\n\n await County.findById(\n { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) },\n (err, resp) => {\n var cumulativeRate = 0;\n for (var i = 0; i < localCountiesIndices.length; i++) {\n // daily increase\n var individualRate =\n resp.data[localCountiesIndices[i]].counties[0].historicData[0]\n .positiveCt -\n resp.data[localCountiesIndices[i]].counties[0].historicData[13]\n .positiveCt;\n cumulativeRate += individualRate / 14;\n }\n // rate per 100,000\n cumulativeRate = (cumulativeRate / localCountyPopulation) * 100000;\n\n var date = new Date();\n date.setDate(date.getDate() - 2);\n County.updateOne(\n { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) },\n {\n $push: {\n averages: {\n $each: [{ date: date, caseRate: cumulativeRate }],\n $position: 0,\n },\n },\n },\n (err) => {\n if (err) {\n console.log(err);\n } else {\n console.log(`Added newest data for County Averages`);\n }\n }\n );\n\n County.updateOne(\n { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) },\n { $pop: { averages: 1 } },\n (err) => {\n if (err) {\n console.log(err);\n } else {\n console.log(`Deleted oldest data for County Averages`);\n }\n }\n );\n\n County.updateOne(\n { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) },\n { $set: { pingryCountiesCaseRate: cumulativeRate } },\n (err) => {\n if (err) {\n console.log(err);\n } else {\n console.log(`Updated 7 Day Pingry Counties Case Rate`);\n }\n }\n );\n }\n );\n console.log(\"Finished repopulating county collections.\");\n}", "async changeDocIds(pairs, { keep } = {}) {\n let renamed = 0;\n let kept = 0;\n // Get page paths up front so we can avoid multiple queries when working on path changes\n const pages = await self.apos.doc.db.find({\n path: { $exists: 1 },\n slug: /^\\//\n }).project({\n path: 1\n }).toArray();\n for (const pair of pairs) {\n const [ from, to ] = pair;\n const existing = await self.apos.doc.db.findOne({ _id: from });\n if (!existing) {\n throw self.apos.error('notfound');\n }\n const replacement = klona(existing);\n await self.apos.doc.db.removeOne({ _id: from });\n const oldAposDocId = existing.aposDocId;\n replacement._id = to;\n const parts = to.split(':');\n replacement.aposDocId = parts[0];\n // Watch out for nonlocalized types, don't set aposLocale for them\n if (parts.length > 1) {\n replacement.aposLocale = parts.slice(1).join(':');\n }\n const isPage = self.apos.page.isPage(existing);\n if (isPage) {\n replacement.path = existing.path.replace(existing.aposDocId, replacement.aposDocId);\n }\n try {\n await self.apos.doc.db.insertOne(replacement);\n renamed++;\n } catch (e) {\n // First reinsert old doc to prevent content loss on new doc insert failure\n await self.apos.doc.db.insertOne(existing);\n if (!self.apos.doc.isUniqueError(e)) {\n // We cannot fix this error\n throw e;\n }\n const existingReplacement = await self.apos.doc.db.findOne({ _id: replacement._id });\n if (!existingReplacement) {\n // We don't know the cause of this error\n throw e;\n }\n if (keep === 'new') {\n // New content already exists in new locale, delete old locale\n // and keep new\n await self.apos.doc.db.removeOne({ _id: existing._id });\n kept++;\n } else if (keep === 'old') {\n // We want to keep the old content, but with the new\n // identifiers. Once again we need to remove the old doc first\n // to cut down on conflicts\n try {\n await self.apos.doc.db.deleteOne({ _id: existing._id });\n await self.apos.doc.db.deleteOne({ _id: replacement._id });\n await self.apos.doc.db.insertOne(replacement);\n renamed++;\n } catch (e) {\n // Reinsert old doc to prevent content loss on new doc insert failure\n await self.apos.doc.db.insertOne(existing);\n throw e;\n }\n kept++;\n } else {\n throw self.apos.error('conflict');\n }\n }\n if (isPage) {\n for (const page of pages) {\n if (page.path.includes(oldAposDocId)) {\n await self.apos.doc.db.updateOne({\n _id: page._id\n }, {\n $set: {\n path: page.path.replace(oldAposDocId, replacement.aposDocId)\n }\n });\n }\n }\n }\n if (existing.relatedReverseIds?.length) {\n const relatedDocs = await self.apos.doc.db.find({\n aposDocId: { $in: existing.relatedReverseIds }\n }).toArray();\n for (const doc of relatedDocs) {\n replaceId(doc, oldAposDocId, replacement.aposDocId);\n await self.apos.doc.db.replaceOne({\n _id: doc._id\n }, doc);\n }\n }\n }\n await self.apos.attachment.recomputeAllDocReferences();\n return {\n renamed,\n kept\n };\n function replaceId(obj, oldId, newId) {\n if (obj == null) {\n return;\n }\n if ((typeof obj) !== 'object') {\n return;\n }\n for (const key of Object.keys(obj)) {\n if (obj[key] === oldId) {\n obj[key] = newId;\n } else {\n replaceId(obj[key], oldId, newId);\n }\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 startCleanup(mongo, redis, data) {\n var deferred = q.defer();\n var tasks = [];\n _.each(data, function (docName) {\n tasks.push(function (callback) {\n cleanDoc(mongo, redis, docName, callback);\n });\n });\n async.parallelLimit(tasks, 2, function (err) {\n if (err) {\n deferred.reject(err);\n } else {\n deferred.resolve();\n }\n });\n return deferred.promise;\n}", "applyToLocalDocumentSet(t) {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n this.mutations.forEach(e => {\n const n = t.get(e.key),\n s = n; // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n\n this.applyToLocalView(s), n.isValidDocument() || s.convertToNoDocument(it.min());\n });\n }", "function TrackedDocumentAPI(_db) {\n\n db = _db;\n\n return {\n\n exists: function (id, callback) {\n db.document.get(id, function (err, ret) {\n var hasError = (ret.error === true && ret.code !== 404);\n var exists = ((typeof ret !== 'undefined' || ret !== null) && ret.error !== true);\n callback( (hasError)? -1 : null, exists, ret)\n });\n },\n\n create: function (collection, documents, options, callback) {\n if (!_.isArray(documents)) documents = [documents];\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n options.waitForSync = true;\n var savedArray = [];\n logger('save count: ', documents.length, callback);\n async.forEachSeries(documents,\n function (document, next) {\n\n document = _.cloneDeep(document);\n\n var handle = generateEntityHandle(collection, document);\n\n var afterCheckIfDocumentExists = function (err, exists, ret) {\n\n if (err) return next(err, ret);\n\n var existingDocument = ret;\n\n // check if requires update (any changes to raw_data)\n var diffKeys = _.difference(_.keys(existingDocument), _.keys(document));\n\n // compare documents while skipping the following keys\n var cloneExistingDocument = _.omit(existingDocument, diffKeys);\n var cloneNewDocument = _.omit(document, diffKeys);\n var requiresUpdate = (!_.isEqual(cloneExistingDocument, cloneNewDocument));\n logger('existingDocument', (existingDocument) ? 'yes' : 'no');\n logger('requiresUpdate', requiresUpdate);\n logger('has crawled before? ', (existingDocument && existingDocument._key) ? 'yes, id: ' + existingDocument._key : 'no');\n logger('requires update? ', (existingDocument && requiresUpdate) ? 'yes' : 'no');\n\n // make decision whether to create new document, create revision or do nothing\n if (!exists) {\n\n _saveNewDocument(collection, document, options, function (err, results) {\n if (err) return next(err, results);\n if (!results) return next(new Error('Missing new saved documents results'), null);\n\n savedArray.push(results);\n next(null, results);\n });\n\n } else if (exists && existingDocument && requiresUpdate) {\n\n _saveNewDocumentRevision(collection, document, existingDocument, options, function (err, results) {\n if (err) return next(err, results);\n if (!results) return next(new Error('Missing saved revision documents results'), null);\n\n savedArray.push(results);\n next(null, results);\n });\n\n } else {\n // is an existing document and does not require update\n next(null, null);\n }\n };\n\n this.exists(handle, afterCheckIfDocumentExists);\n\n }.bind(this),\n function (err, results) {\n logger('create', err, ',', savedArray);\n callback(err, savedArray);\n }\n );\n },\n\n get: function (id, options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n return db.document.get(id, options, callback);\n },\n\n put: function (id, data, options, callback) {\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n var idTokens = id.split('/');\n if (!idTokens || idTokens.length !== 2) return callback(-1, {\n error: true,\n errorNum: 1203,\n code: 404\n });\n\n var collection = idTokens[0];\n var key = idTokens[1];\n\n data = _.cloneDeep(data);\n data._key = key;\n\n async.series([\n function getDocument(next) {\n db.document.get(id, options, function (err, results) {\n next(err, results);\n });\n }.bind(this),\n function createIfExists(next) {\n this.create(collection, data, options, next);\n }.bind(this)\n ], function (err, results) {\n callback(err, results[results.length - 1]);\n });\n },\n\n delete: function (id, options, callback) {\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n // TODO: delete edges (but keep history?)\n return db.document.delete(id, options, callback);\n },\n\n list: function (collection, callback) {\n return db.document.list(collection, callback);\n }\n\n };\n}", "async function updateObjsRegions({ model, criteria = {}, regions = [], additionalUpdate }) {\n const $set = {};\n const $unset = {};\n const $update = {};\n\n for (let i = 0; i <= maxRegionLevel; i++) {\n const region = regions[i];\n\n if (region) {\n $set['r' + (Array.isArray(region.parents) ? region.parents.length : 0)] = region.cid;\n } else {\n $unset['r' + i] = 1;\n }\n }\n\n if (Object.keys($set).length) {\n $update.$set = $set;\n }\n\n if (Object.keys($unset).length) {\n $update.$unset = $unset;\n }\n\n if (additionalUpdate) {\n _.merge($update, additionalUpdate);\n }\n\n if (Object.keys($update).length) {\n await model.update(criteria, $update, { multi: true }).exec();\n }\n}", "async function getAllSnaps(){\n \n //timetablesOut.forEach(rt=>{\n\n let {route,direction} = timetablesOut[9];\n\n timetablesOut[9].stops.forEach(async stop=>{\n\n let bestopid = stop.bestopid;\n\n //get snapshots from old db\n let theBusStop = await BusRoute.aggregate([\n {$match: {route:route,direction:direction}},\n {$unwind: '$stops'},\n {$match: {'stops.bestopid':bestopid}},\n {$replaceRoot: { newRoot: \"$stops\" }}\n ])\n\n //avoid errors there's no time for!\n if(theBusStop[0]){\n if(!theBusStop[0].snapshots.length){\n //console.log(\"empty\")\n return;\n }\n \n //here it will be the snapshots array from the old db route.stops[x].snapshots... need to go through each one and add the stopref.\n\n //the stopRef is the _id of the busstop (in the new db), get that first\n let stopRef = await newDBFile.getUnderscoreIdOfStop(route,direction,bestopid);\n\n //add the stop ref as a field in the snapshot\n let newSnapshots = theBusStop[0].snapshots;\n newSnapshots.map(async snap=>{\n snap.stopRef = stopRef;\n\n //save the snapshot\n let fingersCrossed = await newDBFile.saveNewSnap(snap);\n //console.log(fingersCrossed)\n })\n\n }else{\n console.log(route,direction,bestopid + ' no snaps ')\n }\n console.log(\"saving... \", route,direction,stop.name)\n })\n //})\n\n}", "async function removeIntrests(uid,intrests,stores){\n for(let i =0;i<stores.length;i++){\n for(let j=0;j<intrests.length;j++){\n await intreststore.doc(stores[i]).update({\n [`users.${uid}`]:admin.firestore.FieldValue.arrayRemove(intrests[j]),\n }).then(async()=>{\n console.log(`SUCCESS [INTREST REMOVED.]=>${intrests[i]}`);\n await database.child(`users/${uid}`).update({\n [`${collections[1]}`]:{[`${stores[i]}`]:true}\n }); \n }).catch((err)=>{\n console.log(`FAILURE REMOVE [ERROR.]=>${err}`);\n });\n }\n }\n return getUserDetails(uid);\n}", "async function removeSaves(uid,saves,stores){\n for(let i =0;i<stores.length;i++){\n for(let j=0;j<saves.length;j++){\n await savedstore.doc(stores[i]).update({\n [`users.${uid}`]:admin.firestore.FieldValue.arrayRemove(saves[j]),\n }).then(async()=>{\n console.log(`SUCCESS [SAVES REMOVED.]=>${intrests[i]}`);\n await database.child(`users/${uid}`).update({\n [`${collections[2]}`]:{[`${stores[i]}`]:true}\n }); \n }).catch((err)=>{\n console.log(`FAILURE REMOVE [ERROR.]=>${err}`);\n });\n \n }\n }\n return getUserDetails(uid);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if string contains at least one uppercase letter.
function containsUppercaseLetter(string) { return /[A-Z]/.test(string); }
[ "function isUpperCase(str) {\n\n}", "function startsWithUppercase(str) {\n return /^[A-Z]/.test(str);\n}", "function containsLowercaseLetter(string) {\n return /[a-z]/.test(string);\n}", "checkLetter(input) {\r\n return this.phrase\r\n .split(\"\")\r\n .some(letter => letter == input);\r\n }", "function strngFunction (string) {\n if (string.slice(-1).toLowerCase() === endsWith.toLowerCase()){\n return true; \n } else {\n return false;\n }\n }", "function isBalanced(substr){\n if(!substr) return false;\n let seen=new Set(substr);\n\n \n for(let [cur] of seen){\n let lower=cur.slice(0).toLowerCase();\n let upper=cur.slice(0).toUpperCase();\n if(!seen.has(lower) || !seen.has(upper)){ // if either upper or lowercase of the character is missing its not balanced\n return false;\n }\n }\n \n return true;\n }", "function isCorrectSentence(str) {\n return str.match(/^[A-Z].*\\.$/)? true: false\n}", "function is_correct_Sentence(input_str) {\r\n var first_char = input_str[0];\r\n var last_char = input_str[input_str.length - 1];\r\n return /[A-Z]/.test(first_char) && last_char == \".\"\r\n}", "function CheckValueAlphabeticOnly(value) {\n var pattern = new RegExp(\"[a-zA-Z]+\");\n if(pattern.test(value)){\n return true;\n }\n return false;\n}", "function isIsogram(str){\n if(str === '') {\n return true;\n }\n const lowLetters = str.toLowerCase()\n const splitStr = lowLetters.split('');\n return splitStr.every((letter, index) => str.indexOf(letter) === index);\n}", "function isLetter(c) {\n return c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90 ; \n}", "isValid(string) {\n\t\tvar words = string.match(/\\w+/g);\n\t\tif (!words) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (let w of words) {\n\t\t\tif (!this.isMember(w)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "function isSingleCharacter(oneChar){\n if (typeof oneChar !== 'string'){\n console.log(\"Sorry, not a string\");\n return false;\n }\n else if (oneChar.length > 1){\n console.log(\"Sorry, too long\");\n return false;\n }\n else {\n console.log(\"word\");\n return true;\n }\n}", "function isCharAVowel(char){\n char = char.toLowerCase(); //with strings, converting to lower or upper is needed\n return ('aeiouy'.indexOf(char) > -1) // checking string 'aeiouy' for character passed into char argument \n}", "function isSingleCharacter(oneChar){\n if (typeof onChar !== \"string\"){\n return false;\n }\n else if (onChar.length > 1){\n return false;\n }\n else {\n return true;\n }\n}", "function isHorseName(str){\n\tcheck=\"`~!@#$%^*()_+=|{}[];:/<>?\"+\"\\\\\"+\"\\\"\"+\"\\\"\";\n\tf1=1;\n\tfor(j=0;j<str.length;j++){\n\t\tif(check.indexOf(str.charAt(j))!=-1){\n\t\t\tf1=0;}}\n\tif(f1==0){return true;}\n\telse{return false;}\n}", "function guessIsValid(letter) {\n //use regex to determine if letter is in the alphabet and ignore case sensitivty\n const validEntries = /[a-z]/i;\n //if the letter is in the alphabet and the length of the letter is 1\n if (validEntries.test(letter) && letter.length === 1) {\n return letter;\n } else {\n return false;\n }\n }", "function UpperCase() {\n var input = \"Do you need uppercase letters in you password? (y/n)\";\n var passUC = prompt(input);\n passUC = passUC.toLowerCase();\n validateYN(passUC);\n while (valid === \"error\") {\n passUC = prompt(errorMsg + input);\n validateYN(passUC);\n }\n if (valid === \"yes\") {\n criteria.push(\"upper\");\n }\n }", "isStringLengthValid (string) {\n // Check if string is undefined or not\n if (string) {\n // If length is bigger than 0 return true\n if (string.length > 0) {\n return true\n }\n }\n // If not, return false\n return false\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get flavor params output object by ID.
static get(id){ let kparams = {}; kparams.id = id; return new kaltura.RequestBuilder('flavorparamsoutput', 'get', kparams); }
[ "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('thumbparamsoutput', 'get', kparams);\n\t}", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'get', kparams);\n\t}", "static getByEntryId(entryId){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'getByEntryId', kparams);\n\t}", "static update(id, flavorParams){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.flavorParams = flavorParams;\n\t\treturn new kaltura.RequestBuilder('flavorparams', 'update', kparams);\n\t}", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_distributionprofile', 'get', kparams);\n\t}", "static getFlavorAssetsWithParams(entryId){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'getFlavorAssetsWithParams', kparams);\n\t}", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('fileasset', 'get', kparams);\n\t}", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('conversionprofile', 'get', kparams);\n\t}", "static reconvert(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'reconvert', kparams);\n\t}", "tryGetArtifact(id) {\n return this.artifacts.find(a => a.id === id);\n }", "function extractPresetOutput(){\n\toutlet(7, JSON.stringify(output));\n}", "exportToObject(idServerId, entryId, revisionId, variantId) {\n\tconst md = this._metadataStore.__variantMetadata(idServerId, entryId, revisionId, variantId);\n\tif (md) {\n\t return md;\n\t} else {\n\t throw new BurritoError(\"VariantNotFoundInStore\");\n\t}\n }", "static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('flavorparams', 'delete', kparams);\n\t}", "static async get(req, res) {\n if (!req.params.variation_id) {\n return res.error('Invalid id supplied');\n }\n\n const variation = _.find(\n req.product.variations,\n {\n _id: mongoose.Types.ObjectId(req.params.variation_id),\n deleted: false,\n },\n );\n if (!variation) {\n return res.error('Item with id not found', 404);\n }\n\n return res.products_with_additional_prices(variation);\n }", "static convert(entryId, flavorParamsId, priority = 0){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.flavorParamsId = flavorParamsId;\n\t\tkparams.priority = priority;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'convert', kparams);\n\t}", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('metadata_metadata', 'get', kparams);\n\t}", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('accesscontrolprofile', 'get', kparams);\n\t}", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'get', kparams);\n\t}", "createOutput(id) {\n const output = this._form[id];\n function get() {\n return output.value;\n }\n function set(value) {\n output.value = typeof value === \"string\" ? value : value.toString();\n }\n function check() {\n /** does nothing though its an output */\n }\n return { get, set, check };\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the tracker's eventlisteners and binds them to its registered SDK event types. Uses the CastEventType mapping imported from cast_event_types.js.
startTracking() { this.castEventTypes.forEach((eventType) => { if (eventType.owner == EventOwner.PLAYER_MANAGER) { this.playerManager.addEventListener(eventType.event, this.handleEvent.bind(this)); } else if (eventType.owner == EventOwner.CAST_RECEIVER_CONTEXT) { this.context.addEventListener(eventType.event, this.handleEvent.bind(this)); } else { console.error("Unrecognized CastEventType: " + JSON.stringify(eventType)); } }); }
[ "function MapListeners() { }", "_addDefaultEvents () {\n\t\tthis.discord.on('error', console.error);\n\n\t\tthis.discord.on('message', (message) => {\n\t\t\t/* Ignore other bots and self */\n\t\t\tif (message.author.bot) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (const caster of this._casters) {\n\t\t\t\tcaster.dispatchIncoming(\n\t\t\t\t\tnew DiscordMessageContext(caster, message, this.options.id)\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}", "function setupCastReceiver() {\n window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();\n\n window.castReceiverManager.onSenderConnected = function(event) {\n senders = window.castReceiverManager.getSenders();\n printDebugMessage(\"connected senders\", senders);\n }\n\n window.castReceiverManager.onSenderDisconnected = function(event) {\n senders = window.castReceiverManager.getSenders();\n // if the last sender disconnects, then stop the cast session entirely if it\n // was an explicit disconnection\n if ((senders.length === 0) && (event.reason == cast.receiver.system.DisconnectReason.REQUESTED_BY_SENDER)) {\n if (player !== null){\n player.destroy(function(){\n window.castReceiverManager.stop();\n });\n } else {\n window.castReceiverManager.stop();\n } \n }\n }\n\n window.castReceiverManager.onShutdown = function(event) {\n senders = window.castReceiverManager.getSenders();\n }\n }", "createEvents() {\n this.slider.addEventListener(this.deviceEvents.down, this.eventStartAll);\n window.addEventListener('resize', this.eventResize);\n }", "function handleEventTypes() {\n var _this = this;\n\n this.allEventTypes = d3\n .set(\n this.initial_data.map(function(d) {\n return d[_this.config.event_col];\n })\n )\n .values()\n .sort();\n this.currentEventTypes = this.config.event_types || this.allEventTypes.slice();\n this.controls.config.inputs.find(function(input) {\n return input.description === 'Event Type';\n }).start = this.currentEventTypes;\n this.config.color_dom = this.currentEventTypes.concat(\n this.allEventTypes\n .filter(function(eventType) {\n return _this.currentEventTypes.indexOf(eventType) === -1;\n })\n .sort()\n );\n this.config.legend.order = this.config.color_dom.slice();\n }", "function addMapEvents(){\n\t\t\t// Add tap event to add shapes for custom links\n\t\t\tmap.addEventListener('tap', initializeOraddPointToPolygon);\n\t\t\t\n\t\t\t// Add mouse-move listner to show polyline \n\t\t\tmap.addEventListener('pointermove', refreshNonFinalizedPolygon);\n\t}", "function cast(type) {\n var members = [],\n count = app.state[type],\n constructor;\n\n for (var c = 0; c < count; c++) {\n constructor = type.caps().single();\n members.push(new app[constructor]({\n id: self.serial++,\n onDeath: self.remove\n }));\n }\n\n // add to the cast\n self.array = self.array.concat(members);\n\n // assign global name shortcuts\n app[type] = members;\n app[type].each = function(callback) {\n self.select(type, callback);\n };\n\n }", "_createTransportListener () {\n const self = this;\n this._transportListener = new _TransportListener();\n this._transportListener.setOnTransportConnected(function () {\n self._handleTransportConnected();\n });\n this._transportListener.setOnTransportDisconnected(function () {\n });\n this._transportListener.setOnPacketReceived(function (sdlPacket) {\n self._handlePacketReceived(sdlPacket);\n });\n this._transportListener.setOnError(function () {\n });\n }", "function setupEvents() {\n if (typeof window.ontouchstart !== 'undefined') {\n view.addEventListener('touchstart', tap);\n view.addEventListener('touchmove', drag);\n view.addEventListener('touchend', release);\n }\n view.addEventListener('mousedown', tap);\n view.addEventListener('mousemove', drag);\n view.addEventListener('mouseup', release);\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}", "static bind(keys, classRef) {\n for (let key of keys) {\n if (listeners[key]) {\n listeners[key].push(classRef)\n } else {\n listeners[key] = [classRef]\n }\n }\n }", "initializeCastApi() {\n this.context = cast.framework.CastContext.getInstance();\n\n this.context.setOptions({\n receiverApplicationId: this.applicationID,\n autoJoinPolicy: chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED,\n resumeSavedSession: true\n });\n\n // set up a heartbeat to avoid the receiver from shutting down.\n setInterval(() => {\n if (this.session) {\n try {\n this.session.sendMessage(this.namespace, {\"heartbeat\": true});\n } catch (e) {\n // invalid parameter is thrown sometimes, not sure why.\n }\n }\n }, 6000);\n\n // hook up a listener here so we can grab a session if one already exists\n // or if one is started using the chromecast browser button.\n this.context.addEventListener(cast.framework.CastContextEventType.SESSION_STATE_CHANGED,\n (event) => {\n if (event.sessionState === \"SESSION_RESUMED\" || event.sessionState === \"SESSION_STARTED\") {\n this.session = event.session;\n this.onFeedChanged(document.getElementById('ticker').value);\n }\n }\n );\n }", "function createListeners() {\n socket.on('previousMessages', (messages) => {\n for (message of messages) {\n renderMessage(message);\n }\n });\n\n socket.on('receivedMessage', (message) => {\n renderMessage(message);\n });\n\n socket.on('receivedDate', (date) => {\n renderMessage(date, true);\n });\n}", "function bindDataLayerListeners(dataLayer) {\n dataLayer.addListener('click', selectFeatures);\n dataLayer.addListener('addfeature', refreshGeoJsonFromData);\n dataLayer.addListener('removefeature', refreshGeoJsonFromData);\n dataLayer.addListener('setgeometry', refreshGeoJsonFromData);\n}", "function privateInitializeEventHandlers(){\n\t\t/*\n\t\t\tOn time update for the audio element, update visual displays that\n\t\t\trepresent the time on either a visualized element or time display.\n\t\t*/\n\t\tconfig.active_song.addEventListener('timeupdate', privateUpdateTime );\n\n\t\t/*\n\t\t\tWhen the audio element has ended playing, we handle the song\n\t\t\tending. In a single song or multiple modular song instance,\n\t\t\tthis just synchronizes the visuals for time and song time\n\t\t\tvisualization, but for a playlist it determines whether\n\t\t\tit should play the next song or not.\n\t\t*/\n\t\tconfig.active_song.addEventListener('ended', privateHandleSongEnded );\n\n\t\t/*\n\t\t\tBinds handlers for play classes\n\t\t*/\n\t\tvar play_classes = document.getElementsByClassName(\"amplitude-play\");\n\n\t\tfor( var i = 0; i < play_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tplay_classes[i].addEventListener('touchstart', privatePlayClickHandle );\n\t\t\t}else{\n\t\t\t\tplay_classes[i].addEventListener('click', privatePlayClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for pause classes\n\t\t*/\n\t\tvar pause_classes = document.getElementsByClassName(\"amplitude-pause\");\n\n\t\tfor( var i = 0; i < pause_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tpause_classes[i].addEventListener('touchstart', privatePauseClickHandle );\n\t\t\t}else{\n\t\t\t\tpause_classes[i].addEventListener('click', privatePauseClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for stop classes\n\t\t*/\n\t\tvar stop_classes = document.getElementsByClassName(\"amplitude-stop\");\n\n\t\tfor( var i = 0; i < stop_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tstop_classes[i].addEventListener('touchstart', privateStopClickHandle );\n\t\t\t}else{\n\t\t\t\tstop_classes[i].addEventListener('click', privateStopClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for play/pause classes\n\t\t*/\n\t\tvar play_pause_classes = document.getElementsByClassName(\"amplitude-play-pause\");\n\n\t\tfor( var i = 0; i < play_pause_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tplay_pause_classes[i].addEventListener('touchstart', privatePlayPauseClickHandle );\n\t\t\t}else{\n\t\t\t\tplay_pause_classes[i].addEventListener('click', privatePlayPauseClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for mute classes\n\n\t\t\tWARNING: If iOS, we don't do anything because iOS does not allow the\n\t\t\tvolume to be adjusted through anything except the buttons on the side of\n\t\t\tthe device.\n\t\t*/\n\t\tvar mute_classes = document.getElementsByClassName(\"amplitude-mute\");\n\n\t\tfor( var i = 0; i < mute_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\t/*\n\t\t\t\t\tChecks for an iOS device and displays an error message if debugging\n\t\t\t\t\tis turned on.\n\t\t\t\t*/\n\t\t\t\tif( /iPhone|iPad|iPod/i.test(navigator.userAgent) ) {\n\t\t\t\t\tprivateWriteDebugMessage( 'iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4' );\n\t\t\t\t}else{\n\t\t\t\t\tmute_classes[i].addEventListener('touchstart', privateMuteClickHandle );\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tmute_classes[i].addEventListener('click', privateMuteClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for volume up classes\n\n\t\t\tWARNING: If iOS, we don't do anything because iOS does not allow the\n\t\t\tvolume to be adjusted through anything except the buttons on the side of\n\t\t\tthe device.\n\t\t*/\n\t\tvar volume_up_classes = document.getElementsByClassName(\"amplitude-volume-up\");\n\n\t\tfor( var i = 0; i < volume_up_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\t/*\n\t\t\t\t\tChecks for an iOS device and displays an error message if debugging\n\t\t\t\t\tis turned on.\n\t\t\t\t*/\n\t\t\t\tif( /iPhone|iPad|iPod/i.test(navigator.userAgent) ) {\n\t\t\t\t\tprivateWriteDebugMessage( 'iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4' );\n\t\t\t\t}else{\n\t\t\t\t\tvolume_up_classes[i].addEventListener('touchstart', privateVolumeUpClickHandle );\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tvolume_up_classes[i].addEventListener('click', privateVolumeUpClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for volume down classes\n\n\t\t\tWARNING: If iOS, we don't do anything because iOS does not allow the\n\t\t\tvolume to be adjusted through anything except the buttons on the side of\n\t\t\tthe device.\n\t\t*/\n\t\tvar volume_down_classes = document.getElementsByClassName(\"amplitude-volume-down\");\n\t\t\n\t\tfor( var i = 0; i < volume_down_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\t/*\n\t\t\t\t\tChecks for an iOS device and displays an error message if debugging\n\t\t\t\t\tis turned on.\n\t\t\t\t*/\n\t\t\t\tif( /iPhone|iPad|iPod/i.test(navigator.userAgent) ) {\n\t\t\t\t\tprivateWriteDebugMessage( 'iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4' );\n\t\t\t\t}else{\n\t\t\t\t\tvolume_down_classes[i].addEventListener('touchstart', privateVolumeDownClickHandle );\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tvolume_down_classes[i].addEventListener('click', privateVolumeDownClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for song slider classes. The song sliders are HTML 5 \n\t\t\tRange Elements. This event fires everytime a slider has changed.\n\t\t*/\n\t\tvar song_sliders = document.getElementsByClassName(\"amplitude-song-slider\");\n\n\t\tfor( var i = 0; i < song_sliders.length; i++ ){\n\t\t\tsong_sliders[i].addEventListener('input', privateSongStatusBarInputHandle );\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for volume slider classes. The volume sliders are HTML 5\n\t\t\tRange Elements. This event fires everytime a slider has changed.\n\n\t\t\tWARNING: If iOS, we don't do anything because iOS does not allow the\n\t\t\tvolume to be adjusted through anything except the buttons on the side of\n\t\t\tthe device.\n\t\t*/\n\t\tvar volume_sliders = document.getElementsByClassName(\"amplitude-volume-slider\");\n\n\t\tfor( var i = 0; i < volume_sliders.length; i++ ){\n\t\t\t/*\n\t\t\t\tChecks for an iOS device and displays an error message if debugging\n\t\t\t\tis turned on.\n\t\t\t*/\n\t\t\tif( /iPhone|iPad|iPod/i.test(navigator.userAgent) ) {\n\t\t\t\tprivateWriteDebugMessage( 'iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4' );\n\t\t\t}else{\n\t\t\t\tvolume_sliders[i].addEventListener('input', privateVolumeInputHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for next button classes.\n\t\t*/\n\t\tvar next_classes = document.getElementsByClassName(\"amplitude-next\");\n\n\t\tfor( var i = 0; i < next_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tnext_classes[i].addEventListener('touchstart', privateNextClickHandle );\n\t\t\t}else{\n\t\t\t\tnext_classes[i].addEventListener('click', privateNextClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for previous button classes.\n\t\t*/\n\t\tvar prev_classes = document.getElementsByClassName(\"amplitude-prev\");\n\n\t\tfor( var i = 0; i < prev_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tprev_classes[i].addEventListener('touchstart', privatePrevClickHandle );\n\t\t\t}else{\n\t\t\t\tprev_classes[i].addEventListener('click', privatePrevClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for shuffle button classes.\n\t\t*/\n\t\tvar shuffle_classes = document.getElementsByClassName(\"amplitude-shuffle\");\n\n\t\tfor( var i = 0; i < shuffle_classes.length; i++ ){\n\t\t\tshuffle_classes[i].classList.remove('amplitude-shuffle-on');\n\t\t\tshuffle_classes[i].classList.add('amplitude-shuffle-off');\n\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tshuffle_classes[i].addEventListener('touchstart', privateShuffleClickHandle );\n\t\t\t}else{\n\t\t\t\tshuffle_classes[i].addEventListener('click', privateShuffleClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for repeat button classes.\n\t\t*/\n\t\tvar repeat_classes = document.getElementsByClassName(\"amplitude-repeat\");\n\n\t\tfor( var i = 0; i < repeat_classes.length; i++ ){\n\t\t\trepeat_classes[i].classList.remove('amplitude-repeat-on');\n\t\t\trepeat_classes[i].classList.add('amplitude-repeat-off');\n\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\trepeat_classes[i].addEventListener('touchstart', privateRepeatClickHandle );\n\t\t\t}else{\n\t\t\t\trepeat_classes[i].addEventListener('click', privateRepeatClickHandle );\n\t\t\t}\n\t\t}\n\t}", "function playbackEvents () {\n\n\t\tvar play = document.getElementById('play');\n\t\tvar overlayPlay = document.getElementById('overlay-play');\n\t\tvar pause = document.getElementById('pause');\n\t\tvar overlayPause = document.getElementById('overlay-pause');\n\t\tvar previous = document.getElementById('previous');\n\t\tvar next = document.getElementById('next');\n\n\t\tplay.addEventListener('click', emitEvent('play'));\n\t\toverlayPlay.addEventListener('click', emitEvent('play'));\n\t\tpause.addEventListener('click', emitEvent('pause'));\n\t\toverlayPause.addEventListener('click', emitEvent('pause'));\n\t\tprevious.addEventListener('click', emitEvent('previous'));\n\t\tnext.addEventListener('click', emitEvent('next'));\n\n\t}", "function attachDefaultListeners() {\n\t\tvar listenerDiv = document.getElementById('listener');\n\t\tlistenerDiv.addEventListener('load', moduleDidLoad, true);\n\t\tlistenerDiv.addEventListener('message', handleMessage, true);\n\t\tlistenerDiv.addEventListener('error', handleError, true);\n\t\tlistenerDiv.addEventListener('crash', handleCrash, true);\n\t\tif (typeof window.attachListeners !== 'undefined') {\n\t\t\twindow.attachListeners();\n\t\t}\n\t}", "initDomEvents() {\n const me = this;\n\n // Set thisObj and element of the configured listener specs.\n me.scheduledBarEvents.element = me.schedulerEvents.element = me.timeAxisSubGridElement;\n me.scheduledBarEvents.thisObj = me.schedulerEvents.thisObj = me;\n\n // same listener used for different events\n EventHelper.on(me.scheduledBarEvents);\n EventHelper.on(me.schedulerEvents);\n }", "handleEvents() {\n\t\tif (this.events) {\n\t\t\tfor (let event in this.events) {\n\t\t\t\tComponent.pubsub.on(event, (data) => {\n\t\t\t\t\t// We're only interested in events which match this instance's unique identifeir\n\t\t\t\t\tif (data.props.uid === this.uid) {\n\t\t\t\t\t\tthis.events[event](data);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}", "function artistEvents (template, artist) {\n\n\t\tvar plyAll = template.querySelector('.play-all');\n\t\tplyAll.addEventListener('click', emitEvent('artist: play-all', artist));\n\n\t\tvar addAll = template.querySelector('.add-all');\n\t\taddAll.addEventListener('click', emitEvent('artist: add-all', artist));\n\n\t\tvar back = template.querySelector('.back-button');\n\t\tback.addEventListener('click', emitEvent('menu: artists'));\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sendRequest / STATECHANGE FUNCTIONS ======================== Checks the nick availability
function checkNick() { if(request.readyState == READY_STATE_COMPLETE) { if(request.status == 200) { var text = ""; //Remove the previous response (if exists) if(nickChecked.innerHTML){ nickChecked.innerHTML = text; } switch(request.responseText){ //Server response with styles case "-1": text = "<span style='color:red; font-weight:bold'>No se ha recibido el nombre</span>"; break; case "0": text = "<span style='color:green'>✓<span>"; break; case "1": text = "<span style='color:red; font-weight:bold'>Ya existe un usuario con ese nombre</span>"; break; } //Display response nickChecked.innerHTML = text; } else { alert("Ha habido un error, inténtelo más tarde"); } } }
[ "function getServerStatus(){ \n\tvar client;\n\tclient = configureBrowserRequest(client);\t\n\tclient.open(\"POST\", \"?server-state\", true);\n\tclient.send();\n\t\n\tclient.onreadystatechange = function() {\n\t\tif(client.readyState == 4 && client.status == 200) {\n\t\t\tdocument.getElementById(\"server-status\").innerHTML = \"Conectado\";\n\t\t}\n\t\telse\n\t\t\tdocument.getElementById(\"server-status\").innerHTML = \"Desconectado\";\n\t}\n}", "function IMNIsOnlineState(state)\n{\n if (state == 1)\n {\n return false;\n }\n return true;\n}", "function onStatusRequest() {\n var request = new XMLHttpRequest();\n request.open(\"GET\", `${urlHostAPI}?cmd=status&name=${username}`, true);\n request.timeout = 2000;\n request.onload = onStatusResponse;\n request.send();\n}", "function updateOnlineStatus(event) {\n\tconsole.log(\"Network connection status change: \" + event.type + \".\");\n\tnetworkConn = navigator.onLine ? true : false;\n\tif (!networkConn) {// if the network connection has been lost\n\t\tinternetConn = false;\n\t\t$('body').attr('data-internet', 0);\n\t\tsetOfflineState(\"system\", 1);\n\t\tif (!idbSupport) splashHandler(\"doa\");// without either IndexedDB or a network connection, this app can't run\n\t} else {// if the network connection has been re-established\n\t\t$.ajax({\n\t\t\ttype: \"GET\",\n\t\t\tdataType: \"text\",\n\t\t\ttimeout: timeoutInternet,\n\t\t\turl: \"/ajax/is-connected\",\n\t\t\tsuccess: function() {\n\t\t\t\tinternetConn = true;\n\t\t\t\t$('body').attr('data-internet', 1);\n\t\t\t\tsetOfflineState(\"system\", 0);\n\t\t\t},\n\t\t\terror: function(xhr, status, errorThrown) {\n\t\t\t\tinternetConn = false;\n\t\t\t\t$('body').attr('data-internet', 0);\n\t\t\t\tsetOfflineState(\"system\", 1);\n\t\t\t\trecheckInternet(15, 4);\n\t\t\t}\n\t\t});\n\t}\n}", "function changeNickname(name){\r\n\tthisUser.nick=name;\r\n\tsocket.emit('setNickname',thisUser, name);\r\n\t$(\"#NicknameField\").val(name); // sets the change nickname input to requested nickname\r\n}", "function checkUsernameChange(data){\n data.toLowerCase();\n var result = data.match(/\\/nick/i);\n if(result === null || result.length!=1)\n return false;\n else\n return true;\n}", "function sendSwitchPlayerRequest(id)\n{\n\t// There is no use in switching to itself\n\tif(playerId != id)\n\t{\n\t\tconsole.log(\"Requesting to switch player to \" + id);\n\t\tcontrolsAjax.send(\"/cd/game?a=setavatar&id=\" + id);\n\t}\n}", "function sendIdle() {\r\n sendStatus(status = \"idle\");\r\n}", "async function isUsernameAvailable(username) {\n const url = `https://passport.twitch.tv/usernames/${username}?users_service=true`;\n const response = await axios.head(url);\n\n return response.status === 204;\n }", "checkNetwork(network){}", "verifyUserOnline(username, callback) {\n DB_Controller.verifyUserOnline(username, function(err, result) {\n\n callback(err, result);\n });\n }", "function checkConnAndReConn(){\n\t\t\t\n\t\t\t//try to reconnect\n\t\t\tif(mWebSocket.readyState == 3 || mWebSocket.readyState == 2 ){\n\t\t\t\tconsole.log(\"Trying to reconnect\");\n\t\t\t\t//reconnect\n\t\t\t\t mWebSocket = connectToMessenger();\n\t\t\t\t//TODO:add code to see if re-connection succeeded \n\t\t\t}//if ends \n\n\t\t //upon recovery request for message status from the main thread\n\t\t //this requested status will be sent to the server \n\t\t //postMessage(\"MESSAGE\");\n\t\t}", "function IMNGetStatusImage(state, showoffline)\n{\n var img = \"imnblank.gif\";\n showoffline = true ;\n switch (state)\n {\n case 0:\n img = \"imnon.gif\";\n break; \n case 1:\n if (showoffline)\n {\n img = \"imnoff.gif\";\n }\n else\n {\n img = \"imnblank.gif\";\n }\n break; \n case 2:\n img = \"imnaway.gif\";\n break;\n case 3:\n img = \"imnbusy.gif\";\n break;\n case 4:\n img = \"imnaway.gif\";\n break;\n case 5:\n img = \"imnbusy.gif\";\n break;\n case 6:\n img = \"imnaway.gif\";\n break;\n }\n return img;\n}", "updateOnlineStatusForLogin(username, callback) {\n\n DB_Controller.updateOnlineStatusForLogin(username, function(err, numAffected) {\n callback(err, numAffected);\n\n });\n }", "function nickChanged(e) {\n let nickName = document.getElementById(\"nick\").value;\n document.getElementById(\"playername\").innerHTML = nickName;\n}", "function isValid(){\n if((''+pin) === userInput && tries !== 0){\n reset('all');\n triesLeft.innerText = '';\n notifyMatched.display = 'block';\n }\n else if(tries === 0){\n triesLeft.innerText = 'No more tries left';\n reset('all');\n notifyNotMatched.display = 'block';\n }\n else{\n reset();\n notifyNotMatched.display = 'block';\n triesLeft.innerText = `${tries} tries left`;\n }\n}", "checkActionStatus() {\n if (this.state >= SolairesAction.STATUS.DONE)\n return;\n if (this.state == SolairesAction.STATUS.ACK)\n SolairesAction.updateGMAck(false);\n }", "checkServerStatus(){\nreturn this.post(Config.API_URL + Constant.HEALTHCHECK_CHECKSERVERSTATUS);\n}", "static check_connected(data) {\n if (data == \"False\") {\n // Send notification error\n bulmaToast.toast({\n message: \"Could not connect to printer... <a onclick=\\\"COM.reconnect_printer()\\\">Retry?</a>\",\n type: \"is-danger\",\n position: \"bottom-right\",\n dismissible: true,\n closeOnClick: false,\n duration: 99999999,\n animate: { in: \"fadeInRight\", out: \"fadeOutRight\" }\n });\n return\n } else if (data == \"True\") {\n // Send notification success\n bulmaToast.toast({\n message: \"Printer connected successfully!\",\n type: \"is-success\",\n position: \"bottom-right\",\n dismissible: true,\n closeOnClick: false,\n duration: 4000,\n animate: { in: \"fadeInRight\", out: \"fadeOutRight\" }\n });\n return\n }\n\n // If no data, ask backend if grbl is connected\n console.log(\"Checking printer connection...\")\n WS.ws.send(COM.payloader(\"RQV\", \"grbl\"))\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the displayed scoreBoard from the page
function clearScoreBoard() { let scoreBoardEl = document.querySelector(".scoreBoard"); document.body.removeEventListener("click", clearScoreBoard); scoreBoardEl.remove(); }
[ "function clearScores() {\n localStorage.removeItem(\"LastScoreBoard\"); // removes the stringified key/value of the previous ScoreBoard from localStorage\n scoreSubmissiones = []; // clears the scoreboard submissions array containing previous score entries\n scoresTableBody.innerHTML = \"\"; // clears the rendered HTML of the scores table body\n}", "function clearScore() {\n currentScore = 0;\n }", "function removeScore() {\n localStorage.removeItem(\"user\");\n var removeBtn = document.querySelector(\"#removeBtn\");\n var userList = document.querySelector(\"#userList\");\n removeBtn.parentNode.removeChild(removeBtn);\n userList.parentNode.removeChild(userList);\n liMax = 0;\n}", "function resetBoard() {\r\n gameboard.forEach(function(space, index) { \r\n this[index] = null; \r\n }, gameboard)\r\n _render()\r\n }", "function removeWinningMessage() {\n winningMessage.textContent = \"\";\n boardElement.classList.remove(\"hidden\");\n winningMessage.classList.remove(\"visible\");\n winningMessage.classList.add(\"hidden\");\n }", "function clearLeaderboard() {\n leaderboardArr = [];\n localStorage.clear();\n displayLeaderboard();\n}", "function clearGrid() {\n score = 0\n mode = null\n firstMove = false\n moves = 10\n timer = 60\n interval = null\n grid.innerHTML = ''\n }", "function clearScore() {\n localStorage.setItem(\"highscore\", \"\");\n localStorage.setItem(\"highscoreName\", \"\");\n resetGame();\n}", "function clearBoard(){\n\tholdEvent(\"autoupdate\");\n\tresetScore();\n\tassignCharacter(0,\"0\",1,1);\n\tassignCharacter(0,\"0\",1,2);\n\tassignCharacter(0,\"0\",2,1);\n\tassignCharacter(0,\"0\",2,2);\n\t$(\"#sb-pn1,#sb-pn12,#sb-pn2,#sb-pn22\").val(\"\").trigger(\"oninput\");\n\treleaseEvent(\"autoupdate\");\n\ttriggerEvent(\"autoupdate\");\n}", "function clear(){\n localStorage.clear();\n highScores=[];\n highScoreParent.innerHTML=\"\";\n }", "finish() {\n document.querySelector(\".game-page\").style.display = \"none\";\n document.querySelector(\".scores-page\").style.display = \"block\";\n localStorage.setItem(\n \"game\" + Date.now(),\n this.player.name + \",\" + this.player.score\n );\n this.reset();\n _mylib__WEBPACK_IMPORTED_MODULE_3__[\n \"default\"\n ].createHighscoresTable();\n }", "function clearScreen()\n{\n document.body.removeChild( document.getElementById( \"space\" ) );\n document.getElementById( \"messages\" ).removeChild( document.getElementById( \"messages\" ).lastChild );\n}", "function clearSlide() {\n if (!whiteboardActive) return;\n if (confirm(\"Delete notes and board on this slide?\")) {\n let strokes = svg.querySelectorAll(\"svg>path\");\n if (strokes) {\n strokes.forEach((stroke) => {\n stroke.remove();\n });\n needToSave(true);\n }\n\n let grid = svg.querySelector(\"svg>rect\");\n if (grid) {\n grid.remove();\n buttonGrid.dataset.active = false;\n needToSave(true);\n }\n\n setWhiteboardHeight(pageHeight);\n }\n }", "function clearScore(){\n localStorage.setItem('highscore','');\n localStorage.setItem('highscoreName','');\n reset();\n}", "function resetScoreboard(scoreboard)\n{\n // Set all the scoreboard object's values to 0.\n scoreboard.wins = 0;\n scoreboard.losses = 0;\n scoreboard.draws = 0;\n\n // Set the scores on the webpage to 0.\n document.querySelector(\".wins-number\").innerText = \"0\";\n document.querySelector(\".losses-number\").innerText = \"0\";\n document.querySelector(\".draws-number\").innerText = \"0\";\n}", "function removePlayer(){\n\n\tvar exiledPlayer = document.getElementById(\"deletePlayer\").value;\n\nvar i = scoreBoardHistory.length\n\nwhile(i--){\n\tif (scoreBoardHistory[i].playerID == exiledPlayer){\n\t\tscoreBoardHistory.splice(i,1);\n\t}\n}\n//scoreBoardHistory.push({\"playerID\": exiledPlayer, \"score\": -1})\n\n\nfor(var j in scoreAveHistory){\n\tif(scoreAveHistory[j].playerID == exiledPlayer){\n\t\t//scoreAveHistory[j].aveScore = 0;\n\t\t//scoreAveHistory.splice(j,1); \n\t}\n}\n\naveScores();\n\ndrawTable();\ndrawTableAve();\ndocument.getElementById(\"totalNumOfScores\").innerHTML = countScores();\n}", "function handleNewNightTerrorRemoved(scoreSnapshot) {\n var removedScoreRow = htmlForPath[scoreSnapshot.key()];\n removedScoreRow.remove();\n delete htmlForPath[scoreSnapshot.key()];\n}", "removeLife () {\n document.querySelectorAll('#scoreboard img')[this.missed].setAttribute(\"src\", \"images/lostHeart.png\");\n this.missed += 1;\n if (this.missed === 4 && document.querySelector('#hint p').innerHTML !== this.activePhrase.hint) {\n document.getElementById('hint').style.display = \"none\";\n } else if (this.missed === 5) {\n checkSound([\"gameLost\"], \"start\");\n this.end(500, 450, false);\n }\n }", "function clearChildren() {\n while(board.firstChild) {\n board.removeChild(board.firstChild);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
router function will move the result instance variable via all functions to calculate the math problem.
router() { this.result = this.validations(this.mathProblem); this.result = this.multiplicationAndDivision(this.result); this.result = this.clearNegatives(this.result); this.result = this.additionAndSubstraction(this.result); }
[ "function reCalculateRoute(){\n\t\tcalculateRoute(lastRouteURL);\n\t}", "compute() {\n // so to compute we have already settled that both prev and main result must have a value in our operationChoice method\n let computation\n const prev = parseFloat(this.prevResult)\n const main = parseFloat(this.mainResult)\n\n if(isNaN(prev) || isNaN(main)) return\n\n switch(this.operation){\n case '+':\n computation = prev + main\n break\n case '-':\n computation = prev - main\n break\n case '*':\n computation = prev * main\n break\n case '/':\n computation = prev / main\n break\n default:\n return\n }\n //when the equals buttonis clicked, the operand memory is removed..wow! that is by setting operand to undefined\n this.mainResult = computation\n this.operation = undefined \n this.prevResult = ''\n }", "function sendEquation() {\n $.ajax({\n type: 'POST',\n url: '/math',\n data: equation,\n success: function() {\n console.log(\"Data sent!\");\n router();\n }\n });\n }", "divideToRef(otherVector, result) {\n return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);\n }", "updateResult() {\r\n }", "function RouteSearchResultCollector() {\n\n}", "multiplyToRef(otherVector, result) {\n return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);\n }", "function calcRoute() {\n\t// Prepare the API call\n\tvar start = start_location.geometry.location;\n\tvar end = end_location.geometry.location;\n\tvar request = {\n\t\torigin: start,\n\t\tdestination: end,\n\t\ttravelMode: 'DRIVING'\n\t};\n\n\t// Call Google Maps API\n\tdirectionsService.route(request, function (result, status) {\n\t\tconsole.log(result);\n\t\tif (status == 'OK') {\n\t\t\t// Update the map to show the route\n\t\t\tdirectionsDisplay.setDirections(result);\n\n\t\t\t// List out the roads that the route includes\n\t\t\tvar routes = result.routes;\n\n\t\t\tdocument.getElementById(\"routeslist\").innerHTML = '';\n\t\t\tfor (var i = 0; i < routes[0].legs[0].steps.length; i++) {\n\t\t\t\tvar routePath = routes[0].legs[0].steps[i].path;\n\t\t\t\tvar road_location = routePath[Math.floor(routePath.length / 2)];\n\t\t\t\tvar duration = routes[0].legs[0].steps[i].duration.value;\n\t\t\t\tvar distance = routes[0].legs[0].steps[i].distance.value;\n\n\t\t\t\t// speed in miles per hour\n\t\t\t\tvar speed = distance * 0.000621371 / (duration / 3600);\n\n\t\t\t\t\n\t\t\t\t//console.log(\"Speed: \" + speed);\n\n\t\t\t\tspeed = Math.max(20, Math.round(speed/10) * 10);\n\n\t\t\t\t//console.log(\"New Speed: \" + speed);\n\t\t\t\tvar polyline = routes[0].legs[0].steps[i].polyline;\n\n\t\t\t\tprocessStep(road_location, duration, distance, speed, routePath, polyline);\n\t\t\t}\n\t\t}\n\n\n\t});\n}", "divideToRef(otherVector, result) {\n result.x = this.x / otherVector.x;\n result.y = this.y / otherVector.y;\n return this;\n }", "function Playjax(router){\n\n function using( pathFn ){\n const route = pathFn(router.controllers);\n return {\n /**\n * Return the request object\n * @param body optional body of request\n */\n request: function( body ) { return routeToRequest(route, body);},\n /**\n * Fetches the request\n * @param body optional request payload\n */\n fetch: function( body ) { return fetchRequest(route, body); }\n };\n }\n\n function routeToRequest(route, body) {\n const properties = {\n method: route.method,\n redirect: \"follow\",\n credentials: \"same-origin\",\n headers: new Headers()\n };\n\n if ( Playjax_csrfTokenValue ) {\n properties.headers.append(\"Csrf-Token\", Playjax_csrfTokenValue);\n }\n if ( body ) {\n switch (typeof body) {\n case \"string\":\n properties.body = body;\n properties.headers.append(\"Content-Type\", \"text/plain\");\n break;\n case \"object\":\n case \"number\":\n case \"boolean\":\n properties.body = JSON.stringify(body);\n properties.headers.append(\"Content-Type\", \"application/json\");\n break;\n case \"function\":\n throw \"Cannot send function object over HTTP yet\";\n\n }\n }\n\n return new Request(route.url, properties);\n }\n\n function fetchRequest(route, body){\n return fetch(routeToRequest(route, body));\n }\n\n return {\n request:routeToRequest,\n fetch:fetchRequest,\n using:using\n };\n\n}", "function startRouteCalculation() {\n var el = $('#ORS-loading');\n el.show();\n $('#routeError').hide();\n }", "function equationOne() {\n return (30 + 2) * 20;\n}", "function calcBonusDestreza(){\n\t\tvm.resultadoBonusDestreza = Math.floor(calculaBonus.retornaValorBonus(configuracao.intervaloDestreza, configuracao.multiplicadorDestreza, vm.attDestreza));\n\t}", "function calculate() {\n if (operator == 1) {\n currentInput = eval(memory) * eval(currentInput);\n }\n if (operator == 2) {\n currentInput = eval(memory) / eval(currentInput);\n }\n if (currentInput == memory / 0) {\n currentInput = \"ERROR! You can't divide by zero.\";\n }\n if (operator == 3) {\n currentInput = eval(memory) + eval(currentInput);\n }\n if (operator == 4) {\n currentInput = eval(memory) - eval(currentInput);\n }\n if (operator == 5) {\n currentInput = Math.pow(memory, currentInput);\n }\n if (operator == 6) {\n var num = currentInput;\n currentInput = memory * Math.pow(10, currentInput);\n if (num > 15) {\n currentInput = memory + \"e\" + num;\n }\n }\n\n operator = 0; // clear operator\n memory = \"0\"; // clear memory\n displayCurrentInput();\n}", "function calculateAndDisplayRoute(directionsService, directionsDisplay, distance) {\n directionsService.route({\n origin: startValue,\n destination: endValue,\n travelMode: 'DRIVING',\n }, function(response, status) {\n // console.log(response);\n if (status === 'OK') {\n directionsDisplay.setDirections(response);\n\n } else {\n console.log(\"ERROR - \" + status);\n // window.alert('Directions request failed due to ' + status);\n }\n });\n\n distance.getDistanceMatrix({\n origins: [startValue],\n destinations: [endValue],\n travelMode: 'DRIVING',\n }, function(response, status) {\n console.log(response);\n var length = (response.rows[0].elements[0].duration.value);\n\n tripLength = length * 1000;\n console.log(response.rows[0].elements[0].duration.text);\n // console.log(msLength);\n\n });\n // Get current weather there\n getCurrentWeather();\n} // End of function to calculate directions and distance", "addToRef(otherVector, result) {\n return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);\n }", "calculate() {\n if(currentNum !== 0) {\n switch(operator) {\n case \"divide\":\n result = num1 / currentNum;\n break;\n case \"times\":\n result = num1 * currentNum;\n break;\n case \"minus\":\n result = num1 - currentNum;\n break;\n default:\n // adding operands\n result = parseFloat(num1) + parseFloat(currentNum);\n break;\n } \n \n // round result if over 20 places\n if(result.length > 20) {\n result = +result.toFixed(20);\n }\n \n this.setState({\n displayNum: result\n })\n num1 = result;\n currentNum = 0;\n }\n }", "increaseSpeed(speedup){\n return this.speed = this.speed + speedup;\n\n }", "function Processor() {\n console.log('Processor: constructor');\n\n // Initialize state on first construction.\n this.accumulator = '';\n this.operator = '';\n this.value = '';\n this.implied = '';\n this.usedImplied = false;\n this.lastEquals = false;\n\n // Boolean to lock calculator on error, until cleared.\n this.errorLock = false;\n\n // Convenience functions.\n this.clear = function () {\n this.accumulator = '';\n this.operator = '';\n this.value = '';\n this.implied = '';\n this.usedImplied = false;\n this.lastEquals = false;\n\n if (this.errorLock) {\n console.log('Error lock cleared');\n this.errorLock = false;\n }\n };\n\n this.operators = '+-X/';\n this.isOperator = function (text) {\n return this.operators.indexOf(text) != -1\n };\n\n /* Basic math combinations. */\n this.doTheMath = function () {\n var newValue;\n var accumulatorNum;\n var valueNum = parseFloat(this.value);\n\n // If there is nothing in the value, use the implied value.\n if (this.accumulator !== '') {\n accumulatorNum = parseFloat(this.accumulator);\n this.usedImplied = false;\n } else {\n accumulatorNum = parseFloat(this.implied);\n this.usedImplied = true;\n }\n\n /* TODO: Fix up decimal places.\n var digits = 0;\n var pointIndex = this.accumulator.indexOf('.');\n if (pointIndex === -1) {\n accumulatorNum = parseInt(this.accumulator);\n } else {\n accumulatorNum = parseFloat(this.accumulator);\n digits = this.accumulator.length - pointIndex - 1;\n }\n\n pointIndex = this.value.indexOf('.');\n if (pointIndex === -1) {\n valueNum = parseInt(this.value);\n } else {\n valueNum = parseFloat(this.value);\n digits = Math.max(digits, this.value.length - pointIndex - 1);\n }\n */\n\n switch (this.operator) {\n case '+':\n newValue = accumulatorNum + valueNum;\n break;\n case '-':\n newValue = accumulatorNum - valueNum;\n break;\n case 'X':\n newValue = accumulatorNum * valueNum;\n break;\n case '/':\n newValue = accumulatorNum / valueNum;\n break;\n default:\n newValue = 0;\n break;\n }\n\n /* TODO: Fix up decimal places.\n // Strip off trailing zeroes behind the decimal on the result.\n if (newValue != parseInt(newValue)) {\n var valueText = newValue.toFixed(digits).toString();\n while (valueText[valueText.length - 1] === '0') {\n valueText = valueText.substring(0, valueText.length - 1);\n }\n\n if (valueText[valueText.length - 1] === '.') {\n valueText = valueText.substring(0, valueText.length - 1);\n }\n }\n */\n\n return newValue;\n };\n\n /* Main button handler - takes the button and returns an object with accumulator, operator, value strings. */\n this.handleText = function (text) {\n var newValue;\n var logArray = [];\n\n if (text === 'C') {\n // Handle the C (all clear).\n this.clear();\n logArray.push('Clear');\n\n } else if (this.errorLock) {\n // No action except 'C' if we are locked.\n this.value = 'Locked: Clear';\n\n } else if (text === 'CE') {\n // Handle the CE (clear entry).\n this.value = '';\n\n } else if ((text >= '0' && text <= '9') ||\n (text === '-' && this.value.length === 0) ||\n (text === '.' && (this.value.indexOf('.') === -1))) {\n // Add to value: (a) number, (b) leading minus sign, or (c) decimal point if not already in string.\n this.value += text;\n\n } else if (this.isOperator(text)) {\n // Handle operator; if this is premature +X/, ignore it. Minus sign is allowed.\n if (text !== '-' && this.value === '') {\n // If we don't already have an operator, or it is the one we are getting ignore it; else override it.\n if (this.operator === '' || this.operator === text) {\n console.log('Ignoring premature \"' + text + '\"');\n } else {\n console.log('Overriding operator \"' + this.operator + '\" to \"' + text + '\"');\n this.operator = text;\n logArray.push('Replacement: ' + text);\n }\n\n } else if (this.operator !== '' && !this.lastEquals) {\n // We already have an operator, so finish that operation first with the existing operator.\n logArray.push(text);\n logArray.push(this.value);\n newValue = this.doTheMath();\n this.accumulator = newValue.toString();\n this.operator = text;\n this.value = '';\n } else {\n // This is the first operator, so just shift to the accumulator.\n logArray.push(this.value);\n this.accumulator = this.value;\n // If we used this.implied, leave it alone for the next time, otherwise save the value.\n if (!this.usedImplied) {\n this.implied = this.value;\n }\n this.operator = text;\n logArray.push(this.operator);\n this.value = '';\n }\n\n } else if (text === '=') {\n // Handle equal sign.\n if (this.operator === '') {\n // If there is no operation defined, just ignore it.\n console.log('Ignoring \"=\" with no operation.');\n } else {\n if (this.value === '') {\n // If we have no value, re-use the previous value in accumulator, or the implied value.\n if (this.accumulator !== '') {\n this.value = this.accumulator;\n logArray.push(this.accumulator);\n } else {\n this.value = this.implied;\n logArray.push(this.implied);\n }\n }\n logArray.push(this.value);\n\n newValue = this.doTheMath();\n this.accumulator = '';\n // If we used this.implied, leave it alone for the next time, otherwise save the value.\n if (!this.usedImplied) {\n this.implied = this.value;\n }\n this.value = newValue.toString();\n logArray.push('=');\n logArray.push(this.value);\n this.lastEquals = true;\n }\n\n } else {\n // Unknown input.\n console.log('Unexpected input: \"' + text + '\"');\n }\n\n // Set the lastEquals flag based on whether this was an '='.\n this.lastEquals = (text === '=');\n\n // Final check for 'NaN', convert to 'Error'.\n if (this.value === 'NaN' || this.value === 'Infinity') {\n console.log('Error - locking calculator until \\'C\\'');\n this.value = 'Error';\n this.errorLock = true;\n this.accumulator = '';\n this.implied = '';\n logArray.push('Error');\n }\n\n // Return the current settings; the only exception is to display '0' for an empty value in the main display.\n return {\n accumulator: this.accumulator,\n operator: this.operator,\n value: (this.value === '') ? '0' : this.value,\n implied: this.implied,\n logArray: logArray\n }\n };\n\n /* Main self-test routine and validation routine (using the Tester arrays); returns success boolean. */\n this.selfTest = function() {\n var tester = new Tester();\n tester.reset();\n\n // Step through each test in turn.\n var testName = tester.getNextTest();\n while (testName != null) {\n console.log('selfTest: ' + testName);\n\n var testStep = tester.getNextStep();\n while (testStep != null) {\n // console.log('selfTest: ' + testStep.input + ' --> ' + testStep.expected);\n var input = testStep.input;\n var expected = testStep.expected;\n\n var retObj = this.handleText(input);\n if (retObj.value !== expected) {\n console.log('selfTest error on test \"' + testName +\n ': expected \"' + expected + '\", got \"' + retObj.value + '\"');\n return false;\n }\n\n testStep = tester.getNextStep();\n }\n testName = tester.getNextTest();\n }\n\n return true;\n };\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and return an embed containing details about the current song. Returns null if no songs.
async _buildNPEmbed() { const song = this.songs[0] if (song) { const embed = new Discord.MessageEmbed() const lang = this.langCache || Lang.en_us const progress = song.getProgress(this.timeSeconds, this.isPaused) const link = await song.showLink() embed.setDescription(utils.replace(lang.audio.music.prompts.queueNowPlaying, { "song": `[**${Discord.Util.escapeMarkdown(song.title)}**](${link})\n\n${progress}` })) embed.setColor(constants.standard_embed_color) return embed } else return null }
[ "function generateSong(id) {\n return {\n id,\n name: `The song ${id}`,\n artists: [\n {\n name: 'The Artist',\n },\n ],\n };\n}", "static getSong(id) {\n return SongManager.songList.find(s => s.songId == id);\n }", "function createCard(song, songNum){\n let link = document.createElement(\"a\");\n link.setAttribute(\"href\", \"javascript:void(0)\");\n link.setAttribute(\"data-micromodal-trigger\", `modal-${songNum}`);\n let card = document.createElement(\"div\");\n card.className += \"song-card\";\n card.id = song.id;\n\n let cardArtist = document.createElement(\"div\");\n let cardTitle = document.createElement(\"div\");\n let cardAlbum = document.createElement(\"div\");\n let cardArtwork = document.createElement(\"img\");\n\n let artistInfo = document.createTextNode(`Artist: ${song.artist}`);\n let titleInfo = document.createTextNode(`Song: ${song.title}`);\n let albumInfo = document.createTextNode(`Album: ${song.album}`);\n\n cardArtwork.alt = `${song.title} Cover`;\n\n // Fetch and set the artwork\n let artResults = getSpotifyAlbumArt(song.artist);\n artResults.then( (result) => {\n console.log(result);\n cardArtwork.src = result.url;\n // set Modal Info based off of cards\n createModalInfo(song.title, song.artist, song.artistID, song.album, result.url, songNum, song.id);\n })\n\n cardArtist.className += \"card-artist\";\n cardTitle.className += \"card-title\";\n cardAlbum.className += \"card-album\";\n cardArtwork.className += \"card-artwork\";\n\n\n cardArtist.appendChild(artistInfo);\n cardTitle.appendChild(titleInfo);\n cardAlbum.appendChild(albumInfo);\n\n card.appendChild(cardArtwork);\n card.appendChild(cardTitle);\n card.appendChild(cardArtist);\n card.appendChild(cardAlbum);\n\n link.appendChild(card); // makes cards clickable for modals\n\n \n\n return link;\n}", "function playNewSong() {\n\treturn (dispatch, getState) => {\n\t\tconst state = getState()\n\t\tconst {\n\t\t\tsongPlaying,\n\t\t\tisPlaylistPlaying,\n\t\t} = state.playerReducer\n\n\t\tdispatch(setIsSongFetching(true))\n\t\t// dispatch(playSong(songPlaying))\n\n\t\t// if state.appReducer.MASAS_songInfo.SC_ID === state.appReducer.SC_songInfo.id\n\t\tfetch(songPlaying)\n\t\t.then( r => r.json() )\n\t\t.then( MASAS_songInfo => {\n\t\t\t// protect against empty array\n\t\t\tlet state_SC_songInfo = {}\n\t\t\tif(state.playerReducer.SC_songInfo)\n\t\t\t\tstate_SC_songInfo = state.playerReducer.SC_songInfo\n\n\t\t\tif(MASAS_songInfo.SC_ID !== state_SC_songInfo.id || !state_SC_songInfo.id) {\n\t\t\t\tSC.get('/tracks/' + MASAS_songInfo.SC_ID)\n\t\t\t\t.then( SC_songInfo => {\n\t\t\t\t\tupdateJPlayerState(SC_songInfo)\n\n\t\t\t\t\t// update currently playing song state\n\t\t\t\t\tdispatch(updateMASAS_songInfo(MASAS_songInfo))\n\t\t\t\t\tdispatch(updateSC_songInfo(SC_songInfo))\n\n\t\t\t\t\t// add song to discover history if not playing from playlist\n\t\t\t\t\tif(!isPlaylistPlaying)\n\t\t\t\t\t\tdispatch(addSongToDiscoverHistory(MASAS_songInfo, SC_songInfo))\n\n\t\t\t\t\t// update song liked button based on server response (vs optimistic UI)\n\t\t\t\t\tdispatch(updateLikeButton(MASAS_songInfo))\n\n\t\t\t\t\t// end loading state\n\t\t\t\t\tdispatch(setIsSongFetching(false))\n\t\t\t\t})\n\t\t\t\t.catch( e => resetPlayer() )\n\t\t\t} else {\n\t\t\t\t// update song liked button based on server response (vs optimistic UI)\n\t\t\t\tdispatch(updateLikeButton(MASAS_songInfo))\n\n\t\t\t\t// end loading state\n\t\t\t\tdispatch(setIsSongFetching(false))\n\t\t\t}\n\t\t}).catch( e => resetPlayer() )\n\t}\n}", "function getNowPlaying(){\n return fetch(\"https://api.themoviedb.org/3/movie/now_playing?api_key=\"+api_key+\"&language=en-US&page=1\")\n .then(nowPlayingInfo => nowPlayingInfo.json());\n}", "function showSong(song) {\n this.querySelector('span.title').textContent = song.title;\n this.querySelector('span.artist').textContent = song.artist;\n this.querySelector('span.album').textContent = song.album;\n}", "function appendSongs(songs) {\n let htmlTemplate = \"\";\n for (let index = 0; index < 3; index++) {\n let song = _songs[index];\n console.log(song.id);\n console.log(song.artist);\n htmlTemplate += `\n \n <article>\n <h3>${song.title}</h3>\n <p>${song.artist}</p>\n ${song.soundcloud}\n </article>\n \n `;\n\n }\n document.querySelector('#songContent').innerHTML = \"<h1>Newest releases</h1>\" + \"<div class='flexContainer'>\" + htmlTemplate + \"</div>\"\n}", "function addTrack() {\n SC.get('/tracks/' + track).then(function(player) {\n\n trackList.push({\n id: player.id,\n trackName: player.title,\n url: player.stream_url,\n artist: player.user.username\n });\n\n if (trackList.length === 1) {\n $('.picked-songs').empty();\n }\n $('.picked-songs').append('<li class=\"column column-block\"><button class=\"button small picked-song\" data-value=\"' + player.id + '\">' + player.title + '</button></li>');\n })\n $('#songName').attr('placeholder', 'Search for another song or artist!')\n }", "function spotifyCommand(song) {\n if (!song) song = \"The Sign Ace of Base\";\n\n spotify.search({ type: 'track', query: song, limit: 1 }, function(err, data) {\n if (err) {\n return console.log('Error occurred: ' + err);\n }\n\n let trackList = data.tracks.items\n if (trackList.length==0) {\n console.log(`NO MATCH FOUND FOR: ${song}`)\n }\n for (let i=0; i<trackList.length; i++){\n let track = trackList[i]\n\n console.log(\"ARTIST: \"+track.artists[0].name)\n console.log(\"SONG TITLE: \"+track.name)\n \n let preview\n if (track.preview_url) preview = track.preview_url\n else preview = \"unavailable\"\n console.log(\"PREVIEW: \"+preview)\n\n console.log(\"ALBUM NAME: \"+track.album.name)\n console.log()\n }\n });\n\n}", "function buildSpotifyPlayer(trackUri) {\n if(!trackUri) return;\n return '<iframe src=\"https://embed.spotify.com/?uri=' + trackUri + '\" width=\"300\" height=\"380\" frameborder=\"0\" allowtransparency=\"true\"></iframe>';\n }", "updateSong(){\n return new Promise( (resolve, reject) => {\n this.player.getCurrentRemoteMeta( ({result}) => {\n if( result){\n this._cache = result;\n this._cache.cover = this.player.address + \":\"+ this.player.port + result.artwork_url;\n resolve( this._cache );\n }\n else {\n this.player.getAlbum(({result}) => {\n this._cache.album = result;\n this.player.getArtist(({result}) => {\n this._cache.artist = result;\n this.player.getCurrentTitle(({result}) =>{\n this._cache.artist = result;\n resolve( this._cache );\n } );\n } );\n } );\n }\n } );\n } );\n }", "function getSongInfo(songTitle) {\n\n // Calls Spotify API to retrieve a track.\n spotify.search({ type: 'track', query: songTitle }, function (err, data) {\n if (err) {\n logOutput.error(err);\n return\n }\n\n var artistsArray = data.tracks.items[0].album.artists;\n\n // Array to hold artist names, when more than one artist exists for a song.\n var artistsNames = [];\n\n // Pushes artists for track to array.\n for (var i = 0; i < artistsArray.length; i++) {\n artistsNames.push(artistsArray[i].name);\n }\n\n // Converts artists array to string, and makes it pretty.\n var artists = artistsNames.join(\", \");\n\n // Prints the artist(s), track name, preview url, and album name.\n logOutput(\"Artist(s): \" + artists);\n logOutput(\"Song: \" + data.tracks.items[0].name)\n logOutput(\"Spotify Preview URL: \" + data.tracks.items[0].preview_url)\n logOutput(\"Album Name: \" + data.tracks.items[0].album.name);\n });\n\n\n\n}", "function updateCurrSongDiv(song){\n let currTitle = document.getElementById('curr-playing-song-title')\n let currArtist = document.getElementById('curr-playing-song-artist')\n let currImg = document.getElementById('curr-playing-song-img')\n let currSongData = document.getElementById('curr-song-audio-control-con').dataset\n let currSongAudio = document.querySelector('.curr-audio')\n let currHeart = document.getElementById('curr-song-heart')\n\n currTitle.innerText = song.title\n currArtist.innerText = song.artist\n currImg.src = song.img\n currSongData.songid = song.id\n currSongData.songidx = song.idx\n //pll = playlist length\n currSongData.pll = song.pll\n currSongAudio.id = song.id\n currSongAudio.src = `../static/audio/${song.file}`\n currHeart.src = \"../static/img/heart1.png\" \n}", "function createSong(playlist, artist, title, link, youtubeUrl) {\n let song = {\n artist: artist,\n title: title,\n link: link,\n youtubeUrl: youtubeUrl\n }\n playlist.songs.push(song);\n\n saveSong(playlist);\n}", "function updateNextSongDiv(nextSong){\n let nextTitle = document.getElementById('next-playing-song-title')\n let nextArtist = document.getElementById('next-playing-song-artist')\n let nextImg = document.getElementById('next-playing-song-img')\n let nextSongData = document.getElementById('next-playing-con').dataset\n let nextSongAudio = document.querySelector('.next-audio')\n let nextHeart = document.getElementById('next-song-heart')\n let nextDuration = document.getElementById('next-playing-con').dataset \n \n nextTitle.innerText = nextSong.title\n nextArtist.innerText = nextSong.artist\n nextImg.src = nextSong.img\n nextSongData.songid = nextSong.id\n nextSongData.songidx = nextSong.idx\n nextSongData.pll = nextSong.pll\n nextDuration.duration = nextSong.duration\n nextSongAudio.id = nextSong.id\n nextSongAudio.src = `../static/audio/${nextSong.file}`\n nextHeart.src = \"../static/img/heart1.png\"\n}", "function NoCurrentSongAlert() {\n if (displayNoCurrentSongAlert) {\n return (\n <div className={styles.voteOverlay}>\n <Alert variant=\"dark\">\n <Alert.Heading>\n Please add a song before starting a vote.\n </Alert.Heading>\n </Alert>\n </div>\n );\n } else {\n return null;\n }\n }", "function playSong(song, doRecordPrevious) {\n niftyplayer('nplayer').load(song[\"full_path\"]);\n niftyplayer('nplayer').play();\n //set current song variables\n $('#nowArtist').html(song[\"artist_name\"]);$('#nowArtistId').text(song[\"artist_id\"]);\n $('#nowAlbum').html(song[\"album_name\"]);$('#nowAlbumId').text(song[\"album_id\"]);\n $('#nowSong').html(song[\"song_name\"]);$('#nowSongId').text(song[\"song_id\"]);\n //direcet link\n path = \"/direct/\"+song[\"song_id\"]+\"/\"+slug(song[\"artist_name\"]+\" - \"+slug(song[\"song_name\"]));\n $('#nowDirectLink').html(\"<a href=\\\"\"+path+\"\\\"> \"+\"http://\"+document.location.host+path+\" </a>\");\n //title of the page\n $('title').html(song[\"artist_name\"]+\" - \"+song[\"song_name\"]);\n\n if( doRecordPrevious === undefined ) {\n doRecordPrevious = true;\n }\n if( doRecordPrevious )\n recordPrevious(song);\n\n $('#artwork').attr('src', song[\"artwork_path\"]);\n}", "function artistName(song){\n output+= ` <p class=\"author lead d-flex\"><strong>${song.title} </strong>&nbsp; Album by &nbsp;<span> ${song.artist.name}</span> <button class=\"btn btn-success ml-auto\" data-artist =\"${song.artist.name}\" data-songtitle=\"${song.title}\">Get Lyrics</button></p>`;\n }", "function getLyrics(songName, artist){\n lyricsURL=\"https://orion.apiseeds.com/api/music/lyric/\"+artist+\"/\"+songName+\"?\"+lyricsAPI;\n\n $.ajax({\n url: lyricsURL,\n method: \"GET\"\n })\n .then(function(response){\n getYoutube(songName, artist);\n\n var result = response.result;\n //console.log(result);\n var lyrics = result.track.text;\n\n $(\"#lyrics\").html(lyrics);\n currentSong.song_name = result.track.name;\n currentSong.artist_name = result.artist.name;\n currentSong.rawLyrics = lyrics;\n },\n function(){\n //IMPORTANT: please edit this portion of code to style html if lyrics not found\n $(\"#lyrics\").text(\"Lyrics: No Record\");\n $(\"#youtube\").attr(\"src\", 'about:blank');//.empty();\n currentSong.song_name = \"\";\n currentSong.artist_name = \"\";\n currentSong.videoURL = \"\";\n currentSong.thumbnailPicURL = \"\";\n currentSong.rawLyrics = \"\";\n }\n );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reverses trip on map view and on the itinerary
reverseTrip() { let tripList = this.state.placesForItinerary; let markerPosList = this.state.markerPositions; this.setState({placesForItinerary: tripList.reverse()}); this.setState({markerPositions: markerPosList.reverse()}) }
[ "invertRows() {\n // flip \"up\" vector\n // we flip up first because invertColumns update projectio matrices\n this.up.multiplyScalar(-1);\n this.invertColumns();\n\n this._updateDirections();\n }", "function zoneReverseAll() {\r\n\twindow.cnt += 1; // global variable.\r\n\t// alert(window.cnt);\r\n\r\n\t// Step-1:\r\n\t// -------- Collection of existing zone codes from zone map.\r\n\tvar len1 = $(\"#zone option\").length; // length of not selected zone.\r\n\tvar html = '';\r\n\r\n\tif (len1 > 0) {\r\n\t\tvar e1 = document.getElementById(\"zone\"); // contains zone list\r\n\r\n\t\tfor (var i = 0; i < len1; i++) {\r\n\t\t\thtml += '<option value=\"' + e1.options[i].value + '\">'\r\n\t\t\t\t\t+ e1.options[i].text + '</option>';\r\n\t\t}\r\n\t}\r\n\t// Add all of currently selected zones in the zone map.\r\n\tvar len2 = $(\"#selected_zone option\").length; // length of selected_zone\r\n\t// map.\r\n\r\n\tif (len2 > 0) {\r\n\t\tvar e2 = document.getElementById(\"selected_zone\"); // contains\r\n\t\t// selected_zone\r\n\t\t// list.\r\n\r\n\t\tfor (var i = 0; i < len2; i++) {\r\n\t\t\thtml += '<option value=\"' + e2.options[i].value + '\">'\r\n\t\t\t\t\t+ e2.options[i].text + '</option>';\r\n\t\t}\r\n\t}\r\n\thtml += '</option>';\r\n\t$('#zone').html(html); // populate zone map.\r\n\t// ------ End.\r\n\r\n\t// Step-2:\r\n\t// ------ Remove the selected zone from selected_zone map.\r\n\tvar html = '';\r\n\t$('#selected_zone').html(html); // Free selected_zone map.\r\n\t$('#contract').html(html); // Free contract map.\r\n\t$('#selected_contract').html(html); // Free selected_contract map.\r\n\t$('#contract_desc').html(html); // Free contract_desc map.\r\n}", "function revertMap(){\n\tif (sectExpanded){\n\t\tsectExpanded = false;\n\t\treplaceDetailsText(textUnexpanded, true);\n\t\thighlightTable(null);\n\n\t\t// unhide everything\n\t\tfor (var i=0; i<hideableElements.length; i++){\n\t\t\thideableElements[i].attr(\"display\", \"\");\n\t\t};\n\n\t\t// revert expanded section\n\t\tsections.forEach(function(d){\n\t\t\t\n\t\t\tif (d.datum().expanded){\n\t\t\t\trefreshSectionID = null;\n\t\t\t\td.selectAll(\".sectionStadiumStrips\").attr(\"style\", \"\");\n\t\t\t\td.datum().expanded = false;\n\t\t\t\td.transition()\n\t\t\t\t\t.duration(transTime)\n\t\t\t\t\t.ease(\"linear\")\n\t\t\t\t\t.attr(\"transform\", \"\");\n\t\t\t\tgStadium.transition().attr(\"transform\", \"\");\n\t\t\t\t\n\t\t\t\td.selectAll(\".mapTableText\").call(function(tables){\n\t\t\t\t\tvar tables = tables[0];\n\t\t\t\t\tfor (var i=0; i<tables.length; i++){\t\t\t\t\t\t\n\t\t\t\t\t\ttables[i].setAttribute(\"transform\", null);\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}", "shouldReverseDirection(fromRouteId, toRouteId, stationId) {\n return Object.keys(STATIONS_TO_FLIP_DIRECTIONS).some((targetStation) => {\n const triggerStation = STATIONS_TO_FLIP_DIRECTIONS[targetStation];\n return (stationId === targetStation && stations[triggerStation].stops.has(fromRouteId) !== stations[triggerStation].stops.has(toRouteId)) || fromRouteId === 'M' && M_TRAIN_SHUFFLE.includes(stationId);\n })\n return false;\n }", "function route2Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations2.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations2.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations2.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations2.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}", "function additionalPass(result, status) {\n\n // if Maps returns a valid response\n if (status == google.maps.DirectionsStatus.OK) {\n \n // initialize variable for checking if route needs any changes\n var needsCorrection = false;\n\n // iterate over legs of route\n for (var i = 0, n = result.routes[0].legs.length; i < n; i++) {\n\n var legLength = result.routes[0].legs[i].distance.value;\n\n // if leg is longer than range\n if (legLength > range) {\n\n // create new polyline for this leg\n var polyline = new google.maps.Polyline({ path: [] });\n\n // iterate over steps of the leg\n for (var j = 0, m = result.routes[0].legs[i].steps.length; j < m; j++) {\n\n // iterate over segments of step\n for (var k = 0, l = result.routes[0].legs[i].steps[j].path.length; k < l; k++) {\n\n // add segment to polyline\n polyline.getPath().push(result.routes[0].legs[i].steps[j].path[k]);\n }\n }\n \n // find point 75% of range along this line\n var nextPoint = polyline.GetPointAtDistance(0.75 * range);\n\n // get closest station to halfway point\n var newStation = getClosestStation(nextPoint);\n \n // create waypoint at that station\n var newWaypoint = {\n location: newStation.latlng,\n stopover: true\n }\n\n // add to waypoints array\n waypoints.push(newWaypoint);\n\n // add station to station stops array\n stationStops.push(newStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: stationStops[i].latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n\n // indicate that route needs correction\n needsCorrection = true;\n }\n }\n\n // if route needs correction\n if (needsCorrection == true) {\n\n // create new directions request\n var nextRequest = {\n origin: origin,\n destination: destination,\n travelMode: google.maps.TravelMode.DRIVING,\n unitSystem: google.maps.UnitSystem.IMPERIAL,\n waypoints: waypoints,\n optimizeWaypoints: true\n }\n\n // send new directions request\n directionsService.route(nextRequest, function(nextResult, nextStatus) {\n\n // try again\n additionalPass(nextResult, nextStatus)\n });\n }\n\n // otherwise our route is fine as is\n else {\n\n // check for legs longer than 85% of range\n warnLong(result);\n\n // create a clickable info window for each waypoint\n createInfoWindows();\n\n // display route\n directionsDisplay.setDirections(result);\n }\n }\n \n // handle errors returned by the Maps API\n else {\n \n handleErrors(status);\n }\n}", "function handleReorderWaypoints() {\n var j = 1;\n var i = $('.waypoint').length - 1;\n // last waypoint is inserted before first and j is incremented\n // so in the second run last waypoint is inserted before second item etc.\n // this is repeated as long as j is smaller i\n while (j < i) {\n var waypointElement = $('.waypoint').last();\n var swapElement = $('.waypoint').eq(j);\n waypointElement.insertBefore(swapElement);\n // internal ids are updated\n $('.waypoint').each(function(index) {\n if ($(this).attr('id') != 'Draft') {\n $(this).attr('id', index - 1);\n }\n });\n j++;\n }\n // create object with indices\n var indices = {};\n $('.waypoint').each(function(index) {\n if ($(this).attr('id') != 'Draft') {\n indices[index] = index - 1;\n }\n });\n //the waypoint which has been moved up is the first waypoint: hide move up button\n $('#' + 0 + '> .moveUpWaypoint').hide();\n $('#' + 0 + '> .moveDownWaypoint').show();\n //the waypoint which has been moved down is the last waypoint: hide the move down button\n var lastWp = $('.waypoint').length - 2;\n $('#' + lastWp + '> .moveUpWaypoint').show();\n $('#' + lastWp + '> .moveDownWaypoint').hide();\n //adapt marker-IDs, decide about wpType\n theInterface.emit('ui:inverseWaypoints', indices);\n theInterface.emit('ui:routingParamsChanged');\n }", "function refresh() {\n map.remove();\n mapView();\n createRoute();\n busLocation();\n}", "function reCalculateRoute(){\n\t\tcalculateRoute(lastRouteURL);\n\t}", "function zoneReverse(){\r\n\twindow.cnt += 1; // global variable.\r\n\t//alert(window.cnt);\r\n\tvar e = document.getElementById(\"selected_zone\"); // contains selected zone list.\r\n\tvar fromDate = document.getElementById(\"fromDate\").value; // contains fromDate value.\r\n\tvar toDate = document.getElementById(\"toDate\").value; // contains toDate value.\r\n\r\n\tvar zoneCode = e.options[e.selectedIndex].value;\r\n\tvar zoneDesc = e.options[e.selectedIndex].text;\r\n\t//alert(zoneCode + '---' + zoneDesc);\r\n\t\r\n\t// Step-1:\r\n\t// -------- Collection of not selected zone codes from zone map.\r\n\tvar len1 = $(\"#zone option\").length; // length of not selected zone.\r\n\tvar html = '';\r\n\t\r\n\tif (len1 > 0){\r\n\t\tvar e1 = document.getElementById(\"zone\"); // contains zone list\r\n\t\t\r\n\t\tfor (var i=0; i<len1; i++){\r\n\t\t\thtml += '<option value=\"' + e1.options[i].value + '\">'+ e1.options[i].text+ '</option>';\r\n\t\t}\r\n\t}\r\n\t// Add currently selected zone in the zone map.\r\n\thtml += '<option value=\"' + zoneCode + '\">'+ zoneDesc + '</option>';\r\n\thtml += '</option>';\r\n\t\t\r\n\t$('#zone').html(html); // populate zone map.\r\n\t// ------ End.\r\n\t\r\n\t// Step-2:\r\n\t// ------ Remove the selected zone from selected_zone map.\r\n\tvar len2 = $(\"#selected_zone option\").length; // length of zone map.\r\n\tvar html = '';\r\n\tvar zoneCodeAll=\"\";\r\n\t\r\n\tif (len2 > 0){\r\n\t\tvar e2 = document.getElementById(\"selected_zone\"); // contains selected_zone list.\r\n\t\t\r\n\t\tfor (var i=0; i<len2; i++){\r\n\t\t\tif (e2.options[i].value != zoneCode){\r\n\t\t\t\thtml += '<option value=\"' + e2.options[i].value + '\">'+ e2.options[i].text+ '</option>';\r\n\t\t\t\tzoneCodeAll += \"'\"+e2.options[i].value+\"',\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\thtml += '</option>';\r\n\t$('#selected_zone').html(html); // populate selected_zone map after removal of selected zone.\r\n\t\r\n\t// Step-3.\r\n\tif (zoneCodeAll != \"\")\r\n\t{\r\n\t\tzoneCodeAll = zoneCodeAll.substring(0, zoneCodeAll.length - 1);\r\n\t\tzoneCode = \"'\"+ zoneCode + \"'\";\r\n\t\t\r\n\t\t// to remove contract code from already selected_contract map\r\n\t\t// as well as contract map who are under the removed zone code.\r\n\t\t$.ajax({\r\n\t\t\ttype: \"POST\",\r\n\t\t\turl: \"securityDeposit.htm\",\r\n\t\t\tdata : \"zoneCode=\" + zoneCode + \"&fromDate=\" + fromDate + \"&toDate=\" + toDate + \"&_target11=contract\",\r\n\t\t\t// data: \"zoneCode=\"+zoneCode+\"&_target11=contract\",\r\n\t\t\tsuccess: function(response){\r\n\t\t\t\tvar data= $.parseJSON(response);\r\n\t\t\t\tvar html = '';\r\n\t\t\t\t\r\n\t\t\t\t// display of contract code instead of contract desc in the map.\r\n\t\t\t\tvar len = data.length;\r\n\t\t\t\tfor (var i=0; i<len; i++){\r\n\t\t\t\t\tcontcd = data[i].contractCode;\r\n\t\t\t\t\tvar src=document.getElementById('selected_contract');\r\n\t\t\t\t\tfor(var count=0;count<src.options.length;count++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(src.options[count].value ==contcd)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttry{\r\n\t\t\t\t\t\t\t\tsrc.remove(count,null);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcatch(error)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tsrc.remove(count);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcount--;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar dest=document.getElementById('contract');\r\n\t\t\t\t\tfor(var count=0;count<dest.options.length;count++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(dest.options[count].value ==contcd) // if exists, then delete.\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttry{\r\n\t\t\t\t\t\t\t\tdest.remove(count,null);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcatch(error)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tdest.remove(count);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcount--;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tpopulateContract ('selected_contract', 'selected_contract', src, src);\r\n\t\t\t},\r\n\t\t\terror: function(e){\r\n\t\t\t\t// alert('Error: ' + e);\r\n\t\t\t}\r\n\t\t}); // End of data fetching.\r\n\t}\r\n\telse{\r\n\t\t$('#contract').html('');\r\n\t\t$('#selected_contract').html('');\r\n\t\t$('#contract_desc').html(html); // Free contract_desc map.\r\n\t}\r\n\t\t\r\n}", "function resetStreetViews(){\n for (var i = 0; i < svpArray.length; i++) {\n svpArray[i].marker.setMap(null);\n }\n svpArray = [];\n $(\"#loading\").css('visibility', 'visible');\n directionsDisplay.setMap(null);\n }", "function subtractMap(){\n $('#subtractButton').on('click',function() {\n rightMapProperties.map.centerAt([-114,53.5444]);\n $('#subtractButton').hide();\n $('#'+rightMapProperties.mapDivId).height('100%');\n $('#title').text('Compare Accessibility: '+' '+$('#title1').text()+' - '+$('#title2').text());\n $('#title2').hide();\n $('#section1').hide();\n $('#section2').width(\"100%\");\n $('#section2').height(\"95%\");\n\n difference = true;\n var list = {};\n for(var k in leftMapProperties.dataMatrix){\n list[k] = leftMapProperties.dataMatrix[k]-rightMapProperties.dataMatrix[k]\n }\n sort = Object.values(list).sort(function(a, b){return a - b});\n var symbol = new SimpleFillSymbol();\n rightMapProperties.renderer = new ClassBreaksRenderer(symbol, function(feature){\n if(rightMapProperties.check === false){\n return leftMapProperties.dataMatrix[feature.attributes.TAZ_New]-rightMapProperties.dataMatrix[feature.attributes.TAZ_New];\n }\n else{\n return leftMapProperties.reverseDataMatrix[feature.attributes.TAZ_New]-rightMapProperties.reverseDataMatrix[feature.attributes.TAZ_New];\n }\n });\n rightMapProperties.renderer=changeRender(rightMapProperties.renderer);\n rightMapProperties.travelZoneLayer.setRenderer(rightMapProperties.renderer);\n rightMapProperties.travelZoneLayer.redraw();\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 directionsClear() {\n // remove any highlighted trails, POIs, loops, etc. from the map\n highlightsClear();\n\n // remove the line from the map\n // and reposition the start and end markers to nowhere\n if (DIRECTIONS_LINE) MAP.removeLayer(DIRECTIONS_LINE);\n MARKER_FROM.setLatLng([0,0]);\n MARKER_TO.setLatLng([0,0]);\n\n // clear the directions text from the Directions panel\n // and clear/hide the elevation profile image\n $('#directions_list').empty().listview('refresh');\n $('#directions_elevationprofile').prop('src','about:blank').parent().hide();\n\n // on the map panel, hide the Directions button since there are none\n $('#page-map div.map_toolbar a[href=\"#page-directions\"]').closest('td').hide();\n\n // on the Directions panel, show the Map button since we in fact have a line to show\n $('#page-directions div[data-role=\"header\"] a[href=\"#page-map\"]').hide();\n}", "function reverse() {\n\tlogo_animation.reverse();\n\ttriangles_animation.reverse();\n\tpage_titles_animation.reverse();\n}", "reverse() {\n const compareOriginial = this.compare;\n this.compare = (a, b) => compareOriginial(b, a);\n }", "async onPressEndTrip(item) {\n\n this.setState({loadingModal:true})\n let location = await Location.getCurrentPositionAsync({});\n if(location) {\n var diff =((this.state.startTime) - (new Date().getTime())) / 1000;\n diff /= (60 * 1);\n var totalTimeTaken = Math.abs(Math.round(diff));\n \n var pos = {\n latitude: location.coords.latitude,\n longitude: location.coords.longitude,\n };\n\n let startLoc = '\"'+this.state.rideDetails.pickup.lat+', '+this.state.rideDetails.pickup.lng+'\"';\n let destLoc = '\"'+pos.latitude+', '+pos.longitude+'\"';\n\n var resp = await fetch(`https://maps.googleapis.com/maps/api/directions/json?origin=${startLoc}&destination=${destLoc}&key=${ google_map_key }`)\n var respJson = await resp.json();\n //fare calculations\n var fareCalculation = farehelper(respJson.routes[0].legs[0].distance.value,totalTimeTaken,this.state.rateDetails?this.state.rateDetails:1);\n if(fareCalculation) {\n this.finalCostStore(item,fareCalculation.grandTotal,pos,respJson.routes[0].legs[0].distance.value,fareCalculation.convenience_fees)\n \n }\n }\n \n }", "function topping2(someMap){\n if(someMap.has('ice cream')){\n someMap.set('yogurt', someMap.get('ice cream'));\n }\n if(someMap.has('spinach')){\n someMap.set('spinach', 'nuts');\n }\n return someMap;\n}", "function restoreMapView() {\n var map_pos_params = /[#]([0-9]+[\\.][0-9]*)[;]([0-9]+[\\.][0-9]*)[;]([0-9]+)/g.exec(window.location.href);\n if (map_pos_params !== null) {\n map.panTo([map_pos_params[1], map_pos_params[2]]);\n map.setZoom(map_pos_params[3]);\n return true\n }\n return false\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: extPart.getNodeParamName DESCRIPTION: get node param name from ext data ARGUMENTS: partName ext data participant filename RETURNS: node param name
function extPart_getNodeParamName(partName) { return dw.getExtDataValue(partName, "insertText", "nodeParamName"); }
[ "function extPart_extractNodeParam(partName, parameters, node)\n{\n if (extPart.getIsNodeRel(partName))\n {\n var nodeParam = extPart.getNodeParamName(partName);\n\n if (parameters[nodeParam] == null)\n {\n var location = extPart.getLocation(partName);\n if ((location.indexOf(\"firstChildOfNode\") == 0 ||\n location.indexOf(\"lastChildOfNode\") == 0) && nodeParam)\n {\n parameters[nodeParam] = node.parentNode;\n\n //The current parent may not be the right one. Check if nodeParamName is\n //name__tag, name__node, nameTag, or nameNode, and if there is a parent node using that\n //exact name. If so, it's probably a better parent node to use for matching.\n if (parameters[nodeParam] && (nodeParam.search(/tag/i) > 0 || nodeParam.search(/node/i) > 0)) {\n var theTag = nodeParam.substring(0,nodeParam.search(/__tag/i)); //extract tag name from nodeParam\n if (!theTag) theTag = nodeParam.substring(0,nodeParam.search(/__node/i));\n if (!theTag) theTag = nodeParam.substring(0,nodeParam.search(/tag/i));\n if (!theTag) theTag = nodeParam.substring(0,nodeParam.search(/node/i));\n if (theTag) {\n theTag = theTag.toUpperCase();\n if (parameters[nodeParam].tagName && parameters[nodeParam].tagName.toUpperCase() != theTag) { //if current node doesn't match\n var curNode = parameters[nodeParam];\n //ripple upward looking for a parent tag with that exact name\n while (curNode.tagName.toUpperCase() != theTag && curNode.parentNode.nodeType == Node.ELEMENT_NODE) {\n curNode = curNode.parentNode;\n }\n //if exact match was found, switch to using that node\n if (curNode.tagName.toUpperCase() == theTag) {\n //DEBUG alert(\"parent tag \"+(parameters[nodeParam].tagName.toUpperCase())+\" changed to \"+theTag);\n parameters[nodeParam] = curNode;\n }\n }\n }\n }\n\n }\n else if (location.indexOf(\"nodeAttribute\") == 0)\n {\n parameters[nodeParam] = node;\n }\n }\n }\n}", "function extPart_getInsertNode(partName, paramObj)\n{\n var retVal = '';\n var nodeParamName = extPart.getNodeParamName(partName);\n if (extPart.getIsNodeRel(partName)) {\n if (nodeParamName) {\n retVal = paramObj[nodeParamName]; //get node from paramObj.prop\n } else {\n alert(MM.MSG_NoNodeSpecForRelInsert);\n }\n }\n return retVal;\n}", "function extPart_getPartType(groupName, partName)\n{\n var retVal = \"\";\n\n if (groupName)\n {\n retVal = dw.getExtDataValue(groupName, \"groupParticipants\", partName, \"partType\");\n }\n\n return retVal;\n}", "function ServerBehavior_getNamedSBPart(name, node)\n{\n var sbPart = null;\n for (var i=0; i < this.sbParticipants.length && !sbPart; i++) \n {\n if ( this.sbParticipants[i].getName() == name \n && (!node || this.sbParticipants[i].getNodeSegment().node == node)\n ) \n {\n sbPart = this.sbParticipants[i];\n }\n }\n return sbPart;\n}", "function extPart_getWeight(partName, theNode)\n{\n //get the weight information\n var retVal = extPart.getLocation(partName);\n\n //if the insert weight is nodeAttribute, add the position of the matched string\n if (retVal == \"nodeAttribute\")\n {\n //get the node string\n var nodeStr = extUtils.convertNodeToString(theNode);\n\n var foundPos = extUtils.findPatternsInString(nodeStr, extPart.getQuickSearch(partName),\n extPart.getSearchPatterns(partName));\n\n if (foundPos)\n {\n retVal += \"+\" + foundPos[0] + \",\" + foundPos[1];\n }\n }\n\n return retVal;\n}", "function extPart_getQuickSearch(partName)\n{\n return dw.getExtDataValue(partName, \"quickSearch\");\n}", "partName(part) {\n return this.blocks[part].getName('New Block', true);\n }", "getFileCreateParamName(file) {\n return this.fileCreateParamName;\n }", "function extPart_getWhereToSearch(partName)\n{\n return dw.getExtDataValue(partName, \"searchPatterns\", \"whereToSearch\");\n}", "function extPart_getInsertText(partName, paramObj)\n{\n var retVal = extPart.getRawInsertText(partName);\n retVal = extUtils.replaceParamsInStr(retVal, paramObj); //replace any parameters in text\n\n //remove new lines from attributes.\n if (extPart.getLocation(partName).indexOf(\"nodeAttribute\") == 0)\n {\n retVal = retVal.replace(/[\\f\\n\\r]\\s*$/,\"\");\n }\n\n return retVal;\n}", "function extPart_getVersion(partName)\n{\n var retrievedVersion = parseFloat(dw.getExtDataValue(partName, \"version\"));\n if (isNaN(retrievedVersion))\n retrievedVersion = 0;\n return retrievedVersion;\n}", "function extPart_getLocation(partName)\n{\n return dw.getExtDataValue(partName, \"insertText\", \"location\");\n}", "function extPart_parametersMatch(partName, partListA, partListB)\n{\n var retVal = true;\n\n // walk the list of search patterns to determine the parameter names\n var paramNames = new Array();\n var searchPatterns = extPart.getSearchPatterns(partName);\n for (var i=0; i < searchPatterns.length; i++)\n {\n if (searchPatterns[i].paramNames)\n {\n var newParams = searchPatterns[i].paramNames.split(\",\");\n paramNames = paramNames.concat(newParams);\n }\n }\n \n // also need to add the node param if it exists\n var nodeParamName = extPart.getNodeParamName(partName);\n if (nodeParamName)\n {\n paramNames.push(nodeParamName);\n } \n\n // call extUtils.parametersMatch with the specific list of parameter names to check\n\n\t//HACK : to match site relative connection path to doc-relative connection path\n\t//the following parameters\"cname,ext\" are sufficient in the\n\t//match list since in a given site the user tend to use the same connection include file(\"cname.ext) in majority of cases\n\tif ((partName == \"connectionref_statement\") || (partName == \"Connection_include\"))\n\t{\n\t var tempParamNames = paramNames;\n\t\tparamNames = new Array();\n\t\tfor (var i =0 ; i < tempParamNames.length ; i++)\n\t\t{\n\t\t\tvar bIgnoreConnectionParam = ((tempParamNames[i] == \"urlformat\") || (tempParamNames[i] == \"UrlFormat\") || (tempParamNames[i] == \"relpath\") || (tempParamNames[i] == \"ConnectionPath\"));\n\t\t\tif (!bIgnoreConnectionParam)\n\t\t\t{\n\t\t\t\tparamNames.push(tempParamNames[i]);\n\t\t\t}\n\t\t}\n\t}\n retVal = extUtils.parametersMatch(partListA, partListB, paramNames);\n\n return retVal;\n}", "getHintName(levelName, player, hintNr){\n var fields = this.levels[levelName].fields;\n var playerField = null;\n for(var i = 0; i < fields.length; i++){\n if(fields[i].playerName === player){\n playerField = fields[i];\n }\n }\n\n if(playerField === null){\n return \"NA\";\n }\n\n var hint = playerField.hintList[hintNr];\n\n if(hint){\n for(var i = 0; i < playerField.trapList.length; i++){\n var f = playerField.trapList[i];\n if(f){\n if(f.position[0] === hint[0] && f.position[1] === hint[1]){\n return f.name;\n }\n }\n\n }\n }\n\n\n\n return \"NA\";\n }", "get pathPart() {\n return this.getStringAttribute('path_part');\n }", "function isParameter(node) {\n\t return node.kind() == \"Parameter\" && node.RAMLVersion() == \"RAML08\";\n\t}", "_getSurfaceId (node, propertyName, viewName) {\n if (viewName === 'metadata') {\n return `${node.id}.${propertyName}`\n } else {\n let xpath = node.getXpath().toArray()\n let idx = xpath.findIndex(entry => entry.id === 'body')\n let relXpath\n if (idx >= 0) {\n relXpath = xpath.slice(idx)\n } else {\n relXpath = xpath.slice(-1)\n }\n // the 'trace' is concatenated using '/' and the property name appended via '.'\n return relXpath.map(e => e.id).join('/') + '.' + propertyName\n }\n }", "visitParameter_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function extGroup_getDataSourceFileName(groupName)\n{\n return dw.getExtDataValue(groupName, \"dataSource\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of nodes expected in the chain.
function YInputChain_get_expectedNodes() { var res; // int; if (this._cacheExpiration <= YAPI.GetTickCount()) { if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) { return Y_EXPECTEDNODES_INVALID; } } res = this._expectedNodes; return res; }
[ "numDescendants() {\n let num = 1;\n for (const branch of this.branches) {\n num += branch.numDescendants();\n }\n return num;\n }", "getTotalBlocks() {\n return this.chain.length;\n }", "function getSizes(nodes) {\n return nodes.map(function (layer) {\n return layer.length;\n })\n }", "function nodeLength(node) {\n // \"The length of a node node depends on node:\n //\n // \"DocumentType\n // \"0.\"\n if (node.nodeType == Node.DOCUMENT_TYPE_NODE) {\n return 0;\n }\n // \"Text\n // \"ProcessingInstruction\n // \"Comment\n // \"Its length attribute value.\"\n // Browsers don't historically support the length attribute on\n // ProcessingInstruction, so to avoid spurious failures, do\n // node.data.length instead of node.length.\n if (node.nodeType == Node.TEXT_NODE || node.nodeType == Node.PROCESSING_INSTRUCTION_NODE || node.nodeType == Node.COMMENT_NODE) {\n return node.data.length;\n }\n // \"Any other node\n // \"Its number of children.\"\n return node.childNodes.length;\n}", "function numOfTotalEnemies() {\n\tconst totalEnemies = gameState.enemies.getChildren().length;\n return totalEnemies;\n}", "function counter() {\n const leftCounter = document.querySelector(\".leftCounter\");\n const rightCounter = document.querySelector(\".rightCounter\");\n\n const leftBlock = document.querySelector(\".left\");\n const rightBlock = document.querySelector(\".right\");\n\n leftCounter.innerText = `${leftBlock.childNodes.length}`;\n rightCounter.innerText = `${rightBlock.childNodes.length}`;\n}", "async numPrerequisitesLeft(userId) {\n const prerequisiteGroups = await this.prerequisiteGroups().fetch()\n let num = prerequisiteGroups.models.length\n await Promise.map(prerequisiteGroups.models, async (prereq) => {\n const isMemberOfPrereq = await GroupMembership.forPair(userId, prereq.id).fetch()\n if (isMemberOfPrereq) {\n num = num - 1\n }\n })\n return num\n }", "calculateTreeWidth() {\n let leftSubtreeWidth = nodeSize + 2 * nodePadding;\n let rightSubtreeWidth = leftSubtreeWidth;\n if (this.left != null) {\n leftSubtreeWidth = this.left.calculateTreeWidth();\n }\n if (this.right != null) {\n rightSubtreeWidth = this.right.calculateTreeWidth();\n }\n this.width = leftSubtreeWidth + rightSubtreeWidth;\n return this.width;\n }", "function countMatches() {\n\tnumberOfMatches += 1;\n\treturn numberOfMatches;\n}", "function length () {\r\n return this.node.getComputedTextLength()\r\n}", "function countAncestors(person, test) { //count ancestors who pass test\n\tfunction combine(current, fromMother, fromFather){\n\t\tvar thisOneCounts = current != person && test(current);\n\t\treturn fromMother + fromFather + (thisOneCounts ? 1 : 0);\n\t}\n\treturn reduceAncestors(person, combine, 0);\n}", "get depth() {\n let d = 0;\n for (let p = this.parent; p; p = p.parent)\n d++;\n return d;\n }", "count() {\n const values = utils.removeMissingValuesFromArray(this.values);\n return values.length;\n }", "function speciesCount(node, parentNodes) {\n let childrenAmount = node.c.length;\n\n if (childrenAmount > 0 && node.r == 'Genus') {\n //say the node has N species\n node.cumulativeChildren += node.c.length;\n //add species count ot its parents\n parentNodes.forEach(function(familyNode) {\n familyNode.cumulativeChildren += childrenAmount;\n });\n }\n}", "count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }", "computeNodeBytes() {\n return sizeof(this.value) + 160;\n }", "function getNumberOfLayers() {\r\n\tvar desc = getDocumentPropertyDescriptor(TID.numberOfLayers);\r\n\tvar numberOfLayers = desc.getInteger(TID.numberOfLayers);\r\n\treturn numberOfLayers;\r\n}", "function getNumCandidates() {\n return numCandidates;\n } // getNumCandidates", "async replaceChain() {\n let chainLength = this.chain.length;\n let nodeOfLargestChain = null;\n for (const node of this.network) {\n const response = await superagent\n .get(`${node}/get_chain_length`)\n .then(res => res);\n const nodeChain = JSON.parse(response.text);\n if (response.status === 200 && nodeChain.length > chainLength) {\n chainLength = nodeChain.length;\n nodeOfLargestChain = node;\n }\n }\n if (nodeOfLargestChain !== null) {\n const response = await superagent\n .get(`${nodeOfLargestChain}/get_chain`)\n .then(res => res);\n const nodeChain = JSON.parse(response.text).chain;\n this.chain = nodeChain.chain;\n this.contracts = nodeChain.contracts;\n this.pendingTransactions = nodeChain.pendingTransactions;\n this.setContractInstances();\n }\n return nodeOfLargestChain !== null;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
3Change all the numbers in the array to be multiplied by two for even indexes.
function evenIndexesMult(arr) { for (var i = 0; i < arr.length; i++) { if(i % 2 ===0 ){ arr[i] = arr[i] * 2; } } return arr; }
[ "function modifyArray(nums) {\n return nums.map(s=> s%2==0 ? s*2: s*3 )\n\n\n }", "function oddProduct(arr) {\n\tlet a = 1;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif (arr[i] % 2 === 1) {\n\t\t\ta *= arr[i];\n\t\t}\n\t}\n\treturn a;\n}", "function numberIndexEven(array){\r\n \r\n return map(array,function(value, index){\r\n if((typeof(value)==='number')&& (index%2===0)){\r\n return value*2;\r\n }else{ return value}\r\n })\r\n}", "function evenOddTransform(arr, n) {\n\tfor (let i = 0; i < n; i++) {\n\t\tfor (let j = 0; j < arr.length; j++) {\n\t\t\tif (arr[j] % 2 !== 0) {\n\t\t\t\tarr[j] += 2;\n\t\t\t} else if (arr[j] % 2 === 0) {\n\t\t\t\tarr[j] -= 2;\n\t\t\t}\n\t\t}\n\t}\n\treturn arr;\n}", "function processOddNums (arr) {\n // let finalIndex = arr.length -1;\n // let result = [];\n // for (let i = finalIndex; i > 0; i--) {\n // if (i % 2 !== 0) {\n // let num = 2 * arr[i];\n // result.push(num)\n // }\n // }\n // console.log(result.join(\" \"));\n\n console.log(\n (arr.filter((el, index) => index % 2 != 0))\n .map(e => e = 2 * e)\n .reverse()\n .join(\" \"))\n}", "function alternateSqSum(arr){\n let newArr = []\n // happy coding :D\n for(let i = 0;i<arr.length;i++){\n if(i%2){\n newArr.push(arr[i]**2)\n }else{\n newArr.push(arr[i])\n }\n }return newArr.reduce((a,b)=>a+b,0)\n }", "function oddMultLength(arr) {\n const oddFilter = arr.filter(item => item % 2 !== 0);\n const newArr = oddFilter.map(item => item * oddFilter.length);\n console.log(newArr);\n}", "function makeEven(array) {\n //tulislah code kalian disini!\n\n var result = [];\n if (array.length % 2 === 0) {\n for (i = 0; i < array.length; i++) {\n if (i === 1 || i === array.length-2) {\n continue;\n } else {\n result.push(array[i]);\n }\n }\n } else {\n for (i = 0; i < array.length; i++) {\n if (i === Math.round(array.length/2)-1) {\n continue;\n } else {\n result.push(array[i]);\n }\n }\n }\n return result;\n\n}", "function multiplyArrValues(array){ \nvar result = 1; \n for( let i = 0; i < array.length; i++) { \n for (let j = 0; j < array[i].length ; j++){\n result *= array[i][j]; \n }\n }\n return result;\n}", "function doubleThird(array){\r\n\t//Generating a copy of the array parameter\r\n\tvar array_copy = new Array();\r\n\t//Steps through the array that was the parameter\r\n\tfor(var i =0; i<array.length; i++){\r\n\t\t//Tests if the current location is a multiple of 3 or i+1 for zero indexes\r\n\t\tif((i+1)%3==0){\r\n\t\t\t//If the test passes, double the original into the new location \r\n\t\t\tarray_copy[i]=array[i]*2;\r\n\t\t//Passes all array locations that are not divisible by 3\r\n\t\t}else{\r\n\t\t\t//Copying the old array into the new one\r\n\t\t\tarray_copy[i]=array[i];\r\n\t\t}\r\n\t}\r\n\t//Returns the adjusted copy of the array parameter\r\n\treturn array_copy;\r\n}", "function doubleOddNumbers(arr) {\n let oddNumsArr = arr.filter(function(num){\n return num%2 === 1\n })\n let oddNumsDoubledArr = oddNumsArr.map(function(num){\n return num * 2\n })\n return oddNumsDoubledArr\n}", "function evenIndexedOddNumbers(arr) {\n var output = [];\n each(arr, function(e, i) {\n if ((e % 2 !== 0) && (i % 2 === 0)) {\n output.push(e)\n }\n })\n return output;\n}", "function productContents(array) {\r\n\tlet product = 1;\r\n\tfor (let i = 0; i < array.length; ++i)\r\n\t{\r\n\t\tproduct *= array[i];\r\n\t}\r\n\treturn product;\r\n}", "function solution_2 (nums) {\r\n const output = Array(nums.length).fill(1); // we never have to create a new `productsToRight` array\r\n for (let i = nums.length - 2; i >= 0; i--) {\r\n output[i] *= output[i + 1] * nums[i + 1]; // e.g. [24, 12, 4, 1]\r\n }\r\n let productToLeft = 1; // this single `productToLeft` variable starts at 1, and represents the cumulative product\r\n for (let i = 0; i < nums.length; i++) {\r\n output[i] *= productToLeft; // take `output[i]` and multiply through with current `productToLeft`...\r\n productToLeft *= nums[i]; // ...then update `productToLeft` with current `nums[i]`\r\n }\r\n return output;\r\n}", "function increment(arr) {\n for (var x = 0; x < arr.length; x++) {\n if (x%2 != 0) {\n arr[x] += 1;\n }\n console.log(arr[x]);\n }\n return arr;\n}", "function multiplyAll(arr) {\n var product = 1;\n \n for (let i =0; i < arr.length; i++){\n for (let j=0; j < arr[i].length; j++){\n product*=arr[i][j]\n }\n }\n \n return product;\n }", "function recursiveMultiplier(arr, num){\n\tlet result = [];\n\tfunction helper(index){\n\t\tif(index === arr.length){\n\t\t\treturn;\n\t\t} else {\n\t\t\tresult[index] = arr[index] * 2;\n\t\t\thelper(index + 1);\n\t\t}\n\t}\n\thelper(0);\n\treturn result;\n}", "function product(arr) {\n var total = 1;\n for (i = 0 ; i = arr.length ; i++) {\n total *= arr[i];\n }\n return total;\n}", "function alternatingSums(a) {\n let team1 = 0;\n let team2 = 0;\n let weightArr = [];\n for(i = 0; i < a.length; i++){\n if(i % 2 === 0){\n team1 += a[i];\n }else{\n team2 += a[i];\n }\n }\n return weightArr = [team1,team2];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fonction permettant de recuperer la valeur du meilleur score enregistree dans le cookie vraiment tire par les cheuveux pour afficher respectivement mes 2 cookies
function getMeilleurScore (nomCookie){ var valeurMeilleurScore = ''; var indexCookie; if (nomCookie == 'classique'){ indexCookie = document.cookie.indexOf("MeilleurScoreSnakeClassique"); indexCookie = indexCookie + 28; while (true){ valeurMeilleurScore = valeurMeilleurScore + document.cookie[indexCookie]; indexCookie = indexCookie + 1; if((document.cookie[indexCookie] == ';') || (document.cookie[indexCookie] == ' ') || (indexCookie == document.cookie.length)) { break; } } return parseInt(valeurMeilleurScore); } if (nomCookie == 'battle'){ indexCookie = document.cookie.indexOf("MeilleurScoreSnakeBattle"); indexCookie = indexCookie + 25; while (true){ valeurMeilleurScore = valeurMeilleurScore + document.cookie[indexCookie]; indexCookie = indexCookie + 1; if((document.cookie[indexCookie] == ';') || (document.cookie[indexCookie] == ' ') || (indexCookie == document.cookie.length)) { break; } } return valeurMeilleurScore; } else{ document.cookie[indexCookie]; } }
[ "function logHighscore() {\r\n\tif( totalElapse > parseInt(getCookie()) || getCookie() == \"\" ) {\r\n\t\tsetCookie( totalElapse );\r\n\t\tuiHScore.innerHTML = (Math.floor(totalElapse / 100) / 10).toString();\r\n\t}else {\r\n\t\tuiHScore.innerHTML = (Math.floor(getCookie() / 100) / 10).toString();\r\n\t}\r\n}", "function updateGold(){\n //update gold counter\n $(\".cashCounter\").html('');\n $(\".cashCounter\").html(\"$\"+totalGold);\n //update goldcounting cookie to save your progress \n document.cookie = \"gold=\"+totalGold+\"; expires=Thu, 18 Dec 2019 12:00:00 UTC; path=/\";\n }", "function eatCookie() {\n cookiesEaten++;\n cookieInventory--;\n}", "function getScore()\n {\n return score\n }", "function cookieRacesValues() {\r\n\r\n\r\n let cart = document.getElementById(\"spanCart\");\r\n\r\n let result = getCookieValue('carreras');\r\n\r\n //console.log(\"Result Cookie Carreras\", result);\r\n\r\n // If the result is not undefined we can work, else do nothing.\r\n if (result !== undefined) {\r\n\r\n if (result === \"\") {\r\n cart.innerText = \"0\";\r\n } else {\r\n let split = result.split(\",\");\r\n cart.innerText = split.length;\r\n }\r\n\r\n cart.style.visibility = \"visible\";\r\n }\r\n}", "function saveRank() {\n let rowRankString = [];\n for (let pairs of rank) {\n rowRankString.push(pairs.join('@'));\n }\n rowRankString = rowRankString.join('&');\n setCookie('rank', rowRankString, 7)\n}", "function addScores() {\n var inputName = nameEl.value \n localStorage.setItem(\"name\" , inputName)\n localStorage.setItem(\"hiScore\" , totalScore)\n console.log(localStorage.getItem(\"name\"))\n console.log(localStorage.getItem(\"hiScore\"))\n hiScores()\n}", "function logScore() {\n event.preventDefault();\n var user = {\n userInitials: inputName.value,\n userScore: timer\n };\n\n if (user.userInitials === \"\") {\n alert(\"You need to enter your initals\")\n return;\n }\n if ((user.userScore < 1) || (user.userScore === 60)) {\n alert(\"Your score is ZERO and can't be logged... C'MON!!!\")\n inputName.value = \"\";\n return;\n }\n if ((i < 4)) {\n alert(\"You did not finish the quiz... Try harder quiter!!!\")\n return;\n }\n else {\n localStorage.setItem(\"user\", JSON.stringify(user));\n inputName.value = \"\";\n timer = 60;\n timerDisplay.textContent = timer;\n score.textContent = 0\n renderScores();\n }\n}", "function cookieAdvices(numberAdvices, indexAdvice) {\n\tvar oldValue = getCookie(\"advice\"); //get the old value of the cookie\n\tvar newValues = \"\"; //create a new empty cookie value\n\t\n\t//check if the old cookie was empty \n\tif (oldValue == \"\") {\n\t\tvar newValues = \"\";\n\t\tfor (i in Array.from(Array(numberAdvices).keys())) { //fill it with zeroes\n\t\t\tnewValues += 0;\n\t\t\tnewValues += \"%\";\n\t\t}\n\t}\n\t\n\telse {\n\t\tvar newValuesList = oldValue.split(\"%\"); //new value is a list of the values in the old value string\n\t\t\n\t\t//replace the value for the checkboxs of the selected index \n\t\tif (newValuesList[indexAdvice] == 1) {\n\t\t\tnewValuesList[indexAdvice] = 0; \n\t\t} else {\n\t\t\tnewValuesList[indexAdvice] = 1;\n\t\t}\n\t\t\n\t\t//make a string of all values\n\t\tfor (i in Array.from(Array(numberAdvices).keys())) { \n\t\t\tnewValues += newValuesList[i];\n\t\t\tnewValues += \"%\";\n\t\t}\n\t}\n\t\n\tsetCookie(\"advice\", newValues);\n\tconsole.log(\"testing if cookie exists\");\n\tconsole.log(document.cookie);\n}", "function setVisits() {\n var firstVisit = getCookie('FirstVisit');\n var lastVisit = getCookie('LastVisit');\n var visits = getCookie('Visits');\n var date = new Date();\n var newDate = date.getTime();\n // date.toUTCString();\n\n if (firstVisit == '') {\n setCookie('FirstVisit', newDate, 365);\n setCookie('Visits', 1, 365);\n }\n\n var hours = ((newDate - lastVisit) / (1000 * 60 * 60)).toFixed(1);\n\n if (hours > 12) {\n visits = visits + 1;\n setCookie('Visits', visits, 365);\n }\n\n setCookie('LastVisit', newDate, 365);\n}", "function loadUserInfoFromCookie()\n {\n userName = $.cookie(\"perc_userName\");\n isAdmin = $.cookie(\"perc_isAdmin\") == 'true' ? true : false;\n isDesigner = $.cookie(\"perc_isDesigner\") == 'true' ? true : false;\n isAccessibilityUser = $.cookie(\"perc_isAccessibilityUser\") == 'true' ? true : false;\n\t \n $.perc_utils.info(\"UserInfo\", \"userName: \" + userName + \", isAdmin: \" + isAdmin + \", isDesigner: \" + isDesigner + \", isAccessibilityUser: \" + isAccessibilityUser);\n }", "function clic() {\n score = score + nbMultiplicacion;\n mostrarScore();\n}", "function postScoreOnline() {\n //check if user is login\n //check in local storage if user_username and user_id is stored\n\n var a = window.localStorage.getItem(\"user_id\");\n var b = window.localStorage.getItem(\"username\");\n var c = window.localStorage.getItem(\"local-storage-game-over-score\");\n\n if (a == null || a == \"\") {\n //$(\"#game_over_page_msg\").html(\"You need to <button class='my-btn-login btn' value='login'></button>\");\n //alert(\"You should login to post online\");\n //location.href = \"login_page.html\";\n pageWrapper3Down();\n } else if (a == \"no internet connection\") {\n //alert(\"No internet connection\");\n $(\"#game_over_page_msg\").html(\"No internet connection\");\n } else {\n //check if have internet\n $.ajax({\n url: \"http://pmawtrolls.esy.es/pmaw_trolls_quiz_online_files/post_score_online.php\",\n type: \"POST\",\n data: {\n \"user_id\": a,\n \"user_username\": b,\n \"score\": c\n },\n success: function(data) {\n if (data == \"not\") {\n //alert(\"Failed\");\n $(\"#game_over_page_msg\").html(\"Failed\");\n } else if (data == \"success\") {\n\n //alert(\"up\");\n //alert(\"Ok na!. na POST NA BOOOOOOOOOOOOOOOM!\");\n $(\"#game_over_page_msg\").html(\"your score was posted online\");\n $(\".btn-special-post\").hide();\n\n\n } else {\n $(\".btn-special-post\").hide();\n\n $(\"#game_over_page_msg\").html(\"your score was posted online!\");\n\n //alert(data);\n }\n }\n\n });\n }\n}", "function retrogameEnd() {\n questionContainerElement.classList.add('hide')\n userInfo.classList.add('hide')\n \n var retroHighScore = endScore;\n document.getElementById(\"id_high_score\").value = endScore+1;\n //Variable for leaderboard \n document.getElementById(\"scoreform\").style.display = \"block\";\n document.getElementById(\"id_high_score\").value = retroHighScore;\n submitButton.classList.remove('hide')\n roundNum.classList.add('hide')\n logoutButton.classList.add('hide')\n}", "function request_credit_score() {\n\n $.ajax({\n url: credit_amount_url\n }).done(function (data) {\n $('#credit-num').text(data.credit_amount);\n setTimeout(function(){\n request_credit_score();\n }, 5000);\n });\n\n }", "function getHighScoreTable() {\n var table = new Array();\n\n for (var i = 0; i < 10; i++) {\n // Contruct the cookie name\n let name = `player${i}`\n\n // Get the cookie value using the cookie name\n let val = getCookie(name)\n // If the cookie does not exist exit from the for loop\n if (!val) {\n break;\n }\n // Extract the name and score of the player from the cookie value\n var res = val.split(\"~\");\n\n // Add a new score record at the end of the array\n table.push(new ScoreRecord(res[0], parseInt(res[1])))\n }\n\n return table;\n}", "function updateScore() {\n\n}", "function calculateScore() {\n for (var i = 0; i < quizLength; i++){\n if (userAnswers[i][1]) {\n quiz[\"questions\"][i][\"global_correct\"]+=1;\n score++;\n }\n quiz[\"questions\"][i][\"global_total\"]+=1;\n }\n}", "function addScore() {\n\tvar ref = database.ref('rank');\n\tvar data = {\n\t\tname: userName,\n\t\tvalue: score\n\t}\n\tref.push(data);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks for collision with the player's ship and an asteroid will take away a player's life if collision occurs
function playerShipAndAsteroidCollisionDetection(elapsedTime){ if(myShip.getSpecs().invincible == false){ for(var i = 0; i < myAsteroid.getAsteroids().length; i++){ var asteroid = myAsteroid.getAsteroids()[i]; var xDiff = myShip.getSpecs().center.x - asteroid.center.x; var yDiff = myShip.getSpecs().center.y - asteroid.center.y; var distance = Math.sqrt((xDiff * xDiff) + (yDiff*yDiff)); if(distance < myShip.getSpecs().radius-10 + asteroid.ballRadius){ particleGenerator.createShipExplosions(elapsedTime,myShip.getSpecs().center); myShip.getSpecs().hit = true; myShip.getSpecs().center.x = canvas.width+20; myShip.getSpecs().center.y = canvas.height+20; myShip.getSpecs().reset = true; playerShipDestroyedAudio.play(); } } } }
[ "checkCollision(player) {\n // Check if the gear and the player overlap each other\n if (this.rowPos == player.rowPos &&\n this.colPos == player.colPos) {\n // If so, then hide the gear item\n this.hasBeenCollected = true;\n this.rowPos = null;\n this.colPos = null;\n this.x = null;\n this.y = null;\n }\n }", "function playerShipAndEnemyCollisionDetection(elapsedTime){\r\n\t\tvar xDiff = myShip.getSpecs().center.x - enemyShip.getSpecs().center.x;\r\n\t\tvar yDiff = myShip.getSpecs().center.y - enemyShip.getSpecs().center.y;\r\n\t\tvar distance = Math.sqrt((xDiff * xDiff) + (yDiff*yDiff));\r\n\r\n\t\tif(distance < myShip.getSpecs().radius + enemyShip.getSpecs().radius){\r\n\t\t\t\r\n\t\t\tparticleGenerator.createShipExplosions(elapsedTime,myShip.getSpecs().center);\r\n\r\n\t\t\tmyShip.getSpecs().hit = true;\r\n\t\t\tmyShip.getSpecs().center.x = canvas.width+20;\r\n\t\t\tmyShip.getSpecs().center.y = canvas.height+20;\r\n\t\t\tmyShip.getSpecs().reset = true;\r\n\t\t\tplayerShipDestroyedAudio.play();\r\n\t\t}\r\n\t}", "function enemyMissleCollisionDetection(missle,elapsedTime){\r\n\t\tvar xDiff = myShip.getSpecs().center.x - missle.x;\r\n\t\tvar yDiff = myShip.getSpecs().center.y - missle.y;\r\n\t\tvar distance = Math.sqrt((xDiff * xDiff) + (yDiff*yDiff)); \r\n\r\n\t\tif(distance < myShip.getSpecs().radius + missle.radius){\r\n\t\r\n\t\t\tparticleGenerator.createShipExplosions(elapsedTime, myShip.getSpecs().center);\r\n\r\n\t\t\tmissle.collisionWithPlayer = true;\r\n\t\t\tmyShip.getSpecs().hit = true;\r\n\r\n\t\t\tmyShip.getSpecs().center.x = canvas.width+20;\r\n\t\t\tmyShip.getSpecs().center.y = canvas.height+20;\r\n\t\t\tmyShip.getSpecs().reset = true;\r\n\t\t\tplayerShipDestroyedAudio.play();\r\n\t\t\t\r\n\t\t}\r\n\t}", "checkCollisions() {\n console.log(\n \"Collisions not defined for Agent at x=\"\n + this.pos.x + \", y=\" + this.pos.y);\n }", "handleCollisions() {\n //find distance between player and bullet and if close enough, player takes damage\n //and bullet resets\n let d = dist(player.x, player.y, this.x, this.y)\n if ((d < this.exitSize / 2) && this.size >= (this.exitSize - this.exitSize / 6)) {\n //take damage\n player.health -= 20;\n //play sound\n audPlayerHit.play();\n this.explosionHit = 255\n this.reset();\n }\n }", "checkPortalCollision() {\n /*\n If the player steps in a portal:\n 1. Deactivate the player to prevent retriggering portal. \n 2. Trigger transitionRoom(target_room). \n 3. Emit the ROOM_TRANISITION event, passing the room to transition to. \n Note: (the following steps are handled by an event listener for the camera fade finish).\n 4. Jump the player to the specified spawn position. \n 5. Reactivate the player. \n */\n let room = this.scene.rooms[this.scene.curRoomKey];\n room.portalsArr.forEach((portal) => {\n if (Phaser.Geom.Rectangle.Overlaps(this.sprite.getBounds(), portal)) {\n // this.targetSpawn = portal.to_spawn;\n this.setActive(false);\n this.scene.transitionRoom(portal.to_room);\n this.to_spawn = portal.to_spawn;\n this.emitter.emit(events.ROOM_TRANSITION_START, portal.to_room);\n return;\n }\n });\n }", "function checkEnergyCollision() {\r\n energies.forEach(function (e) {\r\n if ((player.X < e.x + energyRadius) &&\r\n (player.X + player.width > e.x) &&\r\n (player.Y < e.y + energyRadius) &&\r\n (player.Y + player.height > e.y)) {\r\n e.onCollide();\r\n //startSound();\r\n }\r\n })\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 }", "function updateCollisions() {\n GeometrySplit.game.physics.arcade.collide(players, blockedLayer);\n GeometrySplit.game.physics.arcade.collide(players, moveableLayer1);\n GeometrySplit.game.physics.arcade.collide(players, moveableLayer2);\n GeometrySplit.game.physics.arcade.collide(players, players, (p1, p2) => {\n if(p1 === p2) {\n return;\n }\n if(Math.abs(p1.width - p2.width) < 1 && Math.abs(p1.y - p2.y) < 1){\n merge(p1, p2);\n } else if(currentPlayer === p1 || currentPlayer === p2) {\n setLocks(p1, p2);\n }\n });\n players.forEach(function (p){\n \thazards.forEach(function (h){\n \t\tif (p.overlap(h))\n \t\t{\n \t\t\tif (p.right > h.left)\n \t\t\t{\n \t\t\t\tif(p.bottom > h.top)\n \t\t\t\t{\n \t\t\t\t\tGeometrySplit.game.state.restart();\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t});\n });\n // maybe remove this part once spawning is improved?\n GeometrySplit.game.physics.arcade.overlap(players, players, (p1, p2) => {\n if(p1 === p2 || !(p1.body.touching.right || p1.body.touching.left)) {\n return;\n }\n if(p1.body.x < p2.body.x) {\n p2.body.x = p1.body.x + p1.width + 1;\n } else {\n p1.body.x = p2.body.x + p2.width + 1;\n }\n });\n}", "function checkCollision(n1, n2){\r\n p1 = getPlayer(n1);\r\n p2 = getPlayer(n2);\r\n if(n1 != n2)\r\n var d0 = Math.sqrt( ((p1.cx - p2.cx)*(p1.cx - p2.cx)) +\r\n ((p1.cy - p2.cy)*(p1.cy - p2.cy)))\r\n\r\n var len = p1.trail.length;\r\n if(n1 === n2) len = len-10;\r\n for(var i = 0; i < len; i++){\r\n var pos = p1.trail[i];\r\n var d = Math.sqrt( ((pos.cx - p2.cx)*(pos.cx - p2.cx)) +\r\n ((pos.cy - p2.cy)*(pos.cy - p2.cy)))\r\n\r\n if(d < 5 || d0 < 5 && p2.dead === false){\r\n\r\n if(p2.dead === false && p2.number < 5) endingSoundEffects[selectedplayers[n2-1]].play();\r\n if(p2.dead === false && p2.number === 5) endingSoundEffects[selectedplayers[0]].play();\r\n p2.halt();\r\n p2.dead = true;\r\n console.log(\"Player \" + n2 + \" hit player \" + n1 + \"'s trail!\");\r\n\r\n }\r\n\r\n }\r\n\r\n}", "function enemyPlayerCollision(player, enemy){\n enemy.kill();\n var live = lives.getFirstAlive();\n \n if (live){\n live.kill();\n }\n if (lives.countLiving()<1){\n endGame();\n }\n }", "function worthAttacking(gameMap, ship, oship) {\n let possibleCollisonPos = oship.position;\n \n //attempt to detect where collision will occur;\n //Usually, the first direction is where it will occur. The times when this won't happen is when there are collisions with friendly ships detected, of which this will be off a little.\n let collisionDirections = gameMap.getUnsafeMoves(ship.position, oship.position);\n if (collisionDirections.length > 0) {\n possibleCollisonPos = ship.position.directionalOffset(collisionDirections[0]);\n }\n\n if(1.5 * ship.haliteAmount < oship.haliteAmount) {\n let shipsNearby = search.numShipsInRadius(gameMap, ship.owner, possibleCollisonPos, 2);\n let friendlyNearby = shipsNearby.friendly;\n if (friendlyNearby >= 2 && friendlyNearby > shipsNearby.enemy){\n logging.info(`Ship-${ship.id} is going to try to collide with at least 2 other friends nearby f:${shipsNearby.friendly}, e:${shipsNearby.enemy} at ${possibleCollisonPos}`)\n return true;\n }\n }\n return false;\n \n}", "function checkBoundries() {\n if (x > 560) { // if ship is more than the right of the screen\n rightMove = false; // stop it moving\n } else if (x < 40) { // if ship is more than the left of the screen\n moveLeft = false; // stop it moving\n }\n if (y > 560) { // if ship is more than the bottom of the screen\n downmove = false; // stop it moving\n } else if (y < 30) { // if ship is more than the top of the screen\n upmove = false; // stop it moving\n }\n}", "manageCollitions () {\n var paramRobot = this.robot.getParameters();\n for (var i = 0; i < this.maxFly; ++i) {\n var paramFly = this.fly[i].getParameters();\n var distance = Math.sqrt(Math.pow((paramFly.x - paramRobot.pos.x),2) + Math.pow((paramFly.y - paramRobot.pos.y),2)\n + Math.pow((paramFly.z - paramRobot.pos.z),2));\n\n if (distance <= (paramRobot.radio + paramFly.radio)) {\n this.fly[i].setCollision();\n this.lastHealth = this.health;\n\n if (!paramFly.behaviour) {\n this.health -= 10;\n if (this.health < 0) this.health = 0;\n } else if (paramFly.behaviour) {\n var scorePlus = Math.floor(Math.random()*(5+1))\n this.health += 5 - scorePlus;\n this.score += scorePlus;\n this.setScore();\n if(this.health > 100) this.health = 100;\n }\n this.manageHUD();\n this.hud.changeSize(this.health);\n this.hudRobot.changeSize(this.health);\n }\n }\n }", "function checkShipPlacement() {\n if (isHorizontal) {\n if (shipLength + col > 10) {\n return false;\n } else {\n return true;\n }\n } else {\n if (shipLength + row > 10) {\n return false;\n } else {\n return true;\n }\n }\n}", "function doObjectsCollide(projectile, ship) {\n var SHIP_SPRITE_OFFSET_Y = 46,\n SHIP_SPRITE_OFFSET_X = 22,\n SHIP_HEIGHT = 13,\n SHIP_WIDTH = 58,\n bulletY = projectile.positionY,\n bulletX = projectile.positionX,\n shipX = ship.x + SHIP_SPRITE_OFFSET_X,\n shipY = ship.y + SHIP_SPRITE_OFFSET_Y,\n doCollide = false,\n isTopHit = null,\n isBottomHit = null,\n isBackHit = null;\n\n isTopHit = (bulletY + projectile.radius) > shipY; // &&\n isBottomHit = (bulletY - projectile.radius) < (shipY + SHIP_HEIGHT); // &&\n isFrontHit = (bulletX + projectile.radius) > shipX; // &&\n isBackHit = (bulletX - projectile.radius) < (shipX + SHIP_WIDTH);\n\n doCollide = isTopHit && isBottomHit && isFrontHit && isBackHit;\n\n return doCollide;\n }", "function detectMovingScoreCollisions(){\n\tif (isMovingEaten == false){\n\t\tlet colsDist = Math.abs(shape.i - movingScore.i);\n\t\tlet rowsDist = Math.abs(shape.j - movingScore.j);\n\t\n\t\tif (colsDist < 1 && rowsDist < 1){\n\t\t\tscore += 50;\n\t\t\tisMovingEaten = true;\n\t\t}\n\t}\n}", "function checkCollisions() {\n\t// check lTraffic\n\tvar numObs = lTraffic.length;\n\tvar i = 0;\n\tfor (i = 0; i < numObs; i++){\n\t\tif (rectOverlap(userCar, lTraffic[i])) {\n\t\t\thandleCollision();\n\t\t}\n\t}\n\t// TODO check rTraffic\n\tnumObs = rTraffic.length;\n\tfor (i = 0; i < numObs; i++) {\n\t\tif (rectOverlap(userCar, rTraffic[i])) {\n\t\t\thandleCollision();\n\t\t}\n\t}\n\t// TODO check bottom peds\n\t// TODO check top peds\n}", "moveIsInPlayableArea(player, dx, dy) {\n\t\t// Left side of player out of bounds or right side of player out of bounds\n\t\tif (player.x+dx < PLAYABLE_LEFT_EDGE || player.x+player.size+dx > PLAYABLE_RIGHT_EDGE) {\n\t\t\treturn false;\n\t\t}\n\t\telse if (player.y+dy < PLAYABLE_TOP_EDGE || player.y+player.size+dy > PLAYABLE_BOTTOM_EDGE) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tfor (var j = 0; j < NUM_OBSTACLES; j++) {\n\t\t\tvar obstacle = this.obstacles[j];\n\t\t\tif(obstacle.playerCollides(player.x + dx, player.y + dy, player.size)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
replaceInfo() END / FUNCTION btnVisibility( type ) Manage button behavior of modal box depending of initiation 1 parameter: type > The type of modal box ("confirm" or "alert")
function btnVisibility( type ) { var btnType = type; if (btnType === "confirm") { fromToClass(bAlert, "is-visible", "is-hidden"); fromToClass(bAccept, "is-hidden", "is-visible"); fromToClass(bDecline, "is-hidden", "is-visible"); } else if (btnType === "alert") { fromToClass(bAlert, "is-hidden", "is-visible"); fromToClass(bAccept, "is-visible", "is-hidden"); fromToClass(bDecline, "is-visible", "is-hidden"); } }
[ "function confirmHide() {\n document.getElementById(\"hideWarning\").style.display = \"none\";\n data[accountGlobal.id].status = 0;\n restartUI();\n changeStory(accountGlobal.id + 1, 1);\n}", "function alertModalPass() {\n getElement('id_bh_modal').className = \"BH_MODAL\";\n getElement('myModal').style.display = \"block\";\n\n getElement('modalTitre').innerHTML = \"Connexion\";\n getElement(\"modalClose\").innerHTML = \"<i class='fa fa-times-circle size-3 close' onclick='closeModal()'></i>\";\n\n //getElement(\"modalText\").innerHTML = \"<h3>Connexion admin ou table [\"+ipLocal+\"]</h3><input type=password name=pass required>\" \n getElement(\"modalText\").innerHTML = \"<h3>Connexion Admin</h3><input type=password name=pass required>\"\n\n $repr = \"<input type=button value=Confirmer onclick='searchStyle();confirmPass();closeModal()'>\";\n $repr += \"&nbsp;&nbsp;&nbsp;&nbsp;<input type=button value=Annuler onclick='closeModal()'>\";\n getElement(\"modalAction\").innerHTML = $repr;\n}", "ensureButtonsHidden() {\n // TODO(fanlan1210)\n }", "function MASE_SetInfoboxesAndBtns(response) {\n console.log(\"=== MASE_SetInfoboxesAndBtns =====\") ;\n\n const step = mod_MASE_dict.step;\n const is_response = (!!response);\n\n console.log(\"......................step\", step) ;\n console.log(\"is_response\", is_response) ;\n console.log(\"test_is_ok\", mod_MASE_dict.test_is_ok) ;\n console.log(\"saved_is_ok\", mod_MASE_dict.saved_is_ok) ;\n console.log(\"is_approve_mode\", mod_MASE_dict.is_approve_mode) ;\n console.log(\"verification_is_ok\", mod_MASE_dict.verification_is_ok) ;\n\n // step 0: opening modal\n // step 1 + response : return after check\n // step 1 without response: save clicked approve or request verifcode\n // step 2 + response : return after approve or after email sent\n // step 2 without response: submit Exform wit hverifcode\n // step 3 + response: return from submit Exform\n\n // TODO is_reset\n const is_reset = mod_MASE_dict.is_reset;\n\n// --- info_container, loader, info_verifcode and input_verifcode\n let msg_info_txt = null, show_loader = false;\n let show_info_request_verifcode = false, show_input_verifcode = false;\n let show_delete_btn = false;\n let disable_save_btn = false, save_btn_txt = null;\n\n if (response && response.approve_msg_html) {\n mod_MASE_dict.msg_html = response.approve_msg_html;\n };\n\n console.log(\" >> step:\", step);\n\n if (step === 0) {\n // step 0: when form opens and request to check is sent to server\n // tekst: 'The subjects of the candidates are checked'\n msg_info_txt = loc.MASE_info.checking_exams;\n show_loader = true;\n } else {\n if(mod_MASE_dict.is_approve_mode){\n // --- is approve\n if (step === 1) {\n // response with checked exams\n // msg_info_txt is in response\n show_delete_btn = mod_MASE_dict.has_already_approved;\n if (mod_MASE_dict.test_is_ok){\n save_btn_txt = loc.MASE_info.Approve_exams;\n };\n } else if (step === 2) {\n // clicked on 'Approve'\n msg_info_txt = (is_reset) ? loc.MASE_info.removing_approval_exams : loc.MASE_info.approving_exams;\n show_loader = true;\n } else if (step === 3) {\n // response 'approved'\n // msg_info_txt is in response\n };\n } else {\n // --- is submit\n if (step === 1) {\n // response with checked subjects\n // msg_info_txt is in response\n show_info_request_verifcode = mod_MASE_dict.test_is_ok;\n if (mod_MASE_dict.test_is_ok){\n save_btn_txt = loc.Request_verifcode;\n };\n } else if (step === 2) {\n // clicked on 'Request_verificationcode'\n // tekst: 'AWP is sending an email with the verification code'\n // show textbox with 'You need a 6 digit verification code to submit the Ex form'\n msg_info_txt = loc.MASE_info.sending_verifcode;\n show_loader = true;\n } else if (step === 3) {\n // response 'email sent'\n // msg_info_txt is in response\n show_info_request_verifcode = mod_MASE_dict.test_is_ok;\n show_input_verifcode = true;\n disable_save_btn = !el_MASE_input_verifcode.value;\n save_btn_txt = loc.Publish_exams;\n } else if (step === 4) {\n // clicked on 'Submit Ex form'\n // msg_info_txt is in response\n show_loader = true;\n } else if (step === 5) {\n // response 'Exform submittes'\n // msg_info_txt is in response\n }\n } // if(mod_MASE_dict.is_approve_mode)\n } // if (step === 0)\n\n //console.log(\"msg_info_txt\", msg_info_txt) ;\n\n if (msg_info_txt){\n mod_MASE_dict.msg_html = \"<div class='pt-2 border_bg_transparent'><p class='pb-2'>\" + msg_info_txt + \" ...</p></div>\";\n }\n\n const hide_info_container = (!msg_info_txt || show_loader)\n add_or_remove_class(el_MASE_info_container, cls_hide, hide_info_container)\n\n el_MASE_msg_container.innerHTML = mod_MASE_dict.msg_html;\n add_or_remove_class(el_MASE_msg_container, cls_hide, !mod_MASE_dict.msg_html)\n\n add_or_remove_class(el_MASE_loader, cls_hide, !show_loader)\n\n add_or_remove_class(el_MASE_info_request_verifcode, cls_hide, !show_info_request_verifcode);\n add_or_remove_class(el_MASE_input_verifcode.parentNode, cls_hide, !show_input_verifcode);\n\n if (el_MASE_info_request_msg1){\n el_MASE_info_request_msg1.innerText = loc.MASE_info.need_verifcode +\n ((permit_dict.requsr_role_admin) ? loc.MASE_info.to_publish_exams : \"\");\n };\n\n if (show_input_verifcode){set_focus_on_el_with_timeout(el_MASE_input_verifcode, 150); };\n\n// --- show / hide delete btn\n add_or_remove_class(el_MASE_btn_delete, cls_hide, !show_delete_btn);\n\n console.log(\"save_btn_txt\", save_btn_txt) ;\n// - hide save button when there is no save_btn_txt\n add_or_remove_class(el_MASE_btn_save, cls_hide, !save_btn_txt)\n// --- disable save button till test is finished or input_verifcode has value\n el_MASE_btn_save.disabled = disable_save_btn;;\n// --- set innerText of save_btn\n el_MASE_btn_save.innerText = save_btn_txt;\n\n// --- set innerText of cancel_btn\n el_MASE_btn_cancel.innerText = (step === 0 || !!save_btn_txt) ? loc.Cancel : loc.Close;\n\n } // MASE_SetInfoboxesAndBtns", "function showLayoutDialog(type) {\n resetLayoutDialog();\n if (document.getElementById('editID').value != '-1') {\n $('#rfelement' + document.getElementById('editID').value).show();\n document.getElementById('editID').value = '-1';\n }\n changeLayoutDialog(type.toString(), false);\n $('#newquestion').hide();\n $('#newlayout').show();\n //$('#newquestion_button').hide();\n}", "function modalConfirm(text, trueFunc, falseFunc) {\n $(\"#custom-modal-header\").text(\"Confirm\");\n $(\"#custom-modal-text\").text(text);\n $(\"#custom-modal\").css(\"display\", \"block\");\n var confirmButton = $(\"<button>\", { class: \"modal-button btn theme accent-3 waves-effect waves-light \" + oldTheme, id: \"custom-modal-confirm-button\" }).text(\"Confirm\");\n var denyButton = $(\"<button>\", { class: \"modal-button btn theme accent-3 waves-effect waves-light \" + oldTheme, id: \"custom-modal-deny-button\" }).text(\"Cancel\");\n confirmButton.attr(\"data-bool\", true);\n denyButton.attr(\"data-bool\", false);\n $(\"#custom-modal-content\").append(confirmButton);\n $(\"#custom-modal-content\").append(denyButton);\n $(\".modal-button\").click(function () {\n if ($(this).attr(\"data-bool\") == \"true\") {\n trueFunc();\n } else {\n falseFunc();\n }\n closeModal();\n })\n}", "function ConfirmEditModule(buttonConfirm, type = 'create') {\r\n editForm = buttonConfirm.parentNode.parentNode;\r\n \r\n var editId = editForm.querySelector('#edit-id').value;\r\n var idModule = editId == '' ? 'NULL' : editId;\r\n\r\n // Получение данных, отправка на сервер изменений, если успешно, продолжить\r\n setData = {}\r\n setData['function'] = 'set_module';\r\n setData['name'] = editForm.querySelector('#edit-name').value;\r\n setData['user'] = editForm.querySelector('#edit-user').value;\r\n setData['id'] = idModule;\r\n setData['ip'] = editForm.querySelector('#edit-ip').value;\r\n setData['type'] = editForm.querySelector('#edit-type').value;\r\n\r\n var left = editForm.querySelector('#edit-left').value;\r\n var top = editForm.querySelector('#edit-top').value;\r\n var color = editForm.querySelector('#edit-color').value;\r\n setData['mapdata'] = left + '|' + top + '|' + color;\r\n\r\n var req = GetXmlHttp();\r\n req.onreadystatechange = function() { \r\n if (req.readyState == 4) { \r\n if(req.status == 200) {\r\n CloseEditBlock(buttonConfirm, type);\r\n // TODO Если несколько открытых панелей, то всё перезагружается\r\n Refresh(); \r\n }\r\n else { notif(req.status ? req.statusText : 'Запрос не удался', 'Ошибка', 'warning'); return;}\r\n }\r\n }\r\n var json_string = JSON.stringify(setData);\r\n SendRequest(req, json_string);\r\n}", "static set popup(value) {}", "function location_detail_change_status (location_detail_type, location_detail_id, location_detail_name, status) {\n\t\t// If status yes, activate. If status no, deactivate\n\t\tif (status==\"yes\") {\n\t\t\tconfirm_info = \"<strong>activate</strong>\";\n\t\t}\n\t\telse if (status==\"no\") {\n\t\t\tconfirm_info = \"<strong>deactive</strong>\";\n\t\t}\n\t\t// Set modal value and show it!\n\t\t$(\"#modal_form\").attr('action', './process.php');\n\t\t$(\"#modal_title\").html(\"Confirmation\");\n\t\t$(\"#modal_content\").html(\"<p class='text-center'>location_detail name : \"+location_detail_name+\" <br>Sure want to \"+confirm_info+\" this location detail?</p><input type='hidden' name='location_detail_id' value='\"+location_detail_id+\"'><input type='hidden' name='location_detail_type' value='\"+location_detail_type+\"'><input type='hidden' name='status' value='\"+status+\"'><input type='hidden' name='action' value='location_detail_change_status'>\");\n\t\t$(\"#modal_footer\").html(\"<button type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button> <button type='submit' class='btn btn-primary'>Yes</button>\");\n\t\t$(\"#modal_dialog\").modal(\"show\");\n\t}", "function confirmerSuppression() {\n let n = new Noty({\n text: 'Confirmer la demande de suppression ',\n layout: 'center', theme: 'sunset', modal: true, type: 'info',\n animation: {\n open: 'animated lightSpeedIn',\n close: 'animated lightSpeedOut'\n },\n buttons: [\n Noty.button('Oui', 'btn btn-sm btn-success marge ', function () {\n supprimer();\n n.close();\n }),\n Noty.button('Non', 'btn btn-sm btn-danger', function () { n.close(); })\n ]\n }).show();\n}", "function initModalBoxes() {\n var newTransModal = document.getElementById('newTransactionPopup');\n var newTransSpan = document.getElementById(\"closeNewTrans\");\n var newTransBtn = document.getElementById('transactionButton');\n var viewTransModal = document.getElementById('viewTransactionPopup');\n var viewTransSpan = document.getElementById('viewTransSpan');\n var viewTransBtn = document.getElementById('viewTransactionsButton');\n var infoPopup = document.getElementById('infoPopup');\n var infoSpan = document.getElementById('infoSpan');\n var infoButton = document.getElementById('viewInfoButton');\n\n infoSpan.onclick = function() {\n infoPopup.style.display = \"none\";\n }\n newTransSpan.onclick = function() {\n newTransModal.style.display = \"none\";\n }\n window.onclick = function(event) {\n if (event.target == newTransModal) {\n newTransModal.style.display = \"none\";\n } else if (event.target == viewTransModal) {\n viewTransModal.style.display = \"none\";\n } else if (event.target == infoPopup) {\n infoPopup.style.display = \"none\";\n }\n }\n newTransBtn.onclick = function() {\n newTransModal.style.display = \"block\";\n }\n viewTransSpan.onclick = function() {\n viewTransModal.style.display = \"none\";\n }\n viewTransBtn.onclick = function() {\n viewTransModal.style.display = \"block\";\n getTable('/transactions', 'transactionsContainer', ['Storage', 'Product', 'Amount', 'Date']);\n }\n viewInfoButton.onclick = function() {\n infoPopup.style.display = \"block\";\n getTable('/productInfo', 'infoContainer', ['Name', 'Id number', 'Price']);\n }\n}", "function modal_funciones_imprimir_lista() {\n\n document.getElementById(\"btn_imprimir_lista\").style.display = \"block\";\n\n $('#modal_funciones_imprimir_lista').modal('show');\n\n}", "function setButtonConfirmEnable(id){\n\t\tvar btnConfirm = document.getElementById(id);\n\t\ttry{\n\t\t\tbtnConfirm.setAttribute(\"class\",'but example1');\n\t\t}catch(e){}\n\t\ttry{\n\t\t\tbtnConfirm.setAttribute(\"className\",'but example1');\n\t\t}catch(e){}\t\n\t\t$(\".example1\").colorbox({inline:true, href:\"#confirm\",scrolling:false});\n\t}", "function toggle_info() {\n toggle_button = document.getElementById(\"dialogue_toggle\");\n if(toggle_button.innerHTML==\"Show Help\"){\n show_help();\n toggle_button.innerHTML = \"Show Data\";\n } else {\n toggle_button.innerHTML = \"Show Help\";\n build_data();\n }\n }", "function bringToStatic() {\n modalState = \"static\";\n // hide form elements\n ingredientsForm.style.display = \"none\";\n preparationForm.style.display = \"none\";\n // show modal elements\n ingredients.style.display = \"block\";\n preparation.style.display = \"block\";\n // reset btn text\n editBtn.textContent = \"Edit\";\n}", "function confirm_dialog( options ) {\n \n //Default settings\n var settings = {\n title: \"Please Confirm\",\n question: \"Do you really want to do this ?\",\n type: \"OK_CANCEL\",\n cancel: function(){},\n success: function(){},\n showAgainCheck: false,\n dontShowAgainAction: null\n };\n \n function genericSuccess(){\n settings.success(); dialog.dialog( \"close\" ); dialog.remove();\n }\n function genericCancel(){\n settings.cancel(); dialog.dialog( \"close\" ); dialog.remove();\n }\n \n $.extend( settings, options );\n var buttons = {};\n if(settings.type == \"YES_NO\")\n {\n buttons = {\n \"Yes\": {\n click: genericSuccess,\n id: \"perc-confirm-generic-yes\"\n },\n \"No\": {\n click: genericCancel,\n id: \"perc-confirm-generic-no\"\n }\n };\n }\n else if(settings.type == \"YES_PREFERRED_NO\")\n {\n buttons = {\n \"Yes Preferred\": {\n click: genericSuccess,\n id: \"perc-confirm-generic-yes\"\n },\n \"No Silver\": {\n click: genericCancel,\n id: \"perc-confirm-generic-no\"\n }\n };\n }\n else if(settings.type == \"YES_NO_PREFERRED\")\n {\n buttons = {\n \"Yes Silver\": {\n click: function() {settings.success(); dialog.remove(); },\n id: \"perc-confirm-generic-yes\"\n },\n \"No\": {\n click: function() {settings.cancel(); dialog.remove(); },\n id: \"perc-confirm-generic-no\"\n }\n };\n }\n else if (settings.type == \"OK\")\n {\n buttons = {\n \"Ok\": {\n click: genericSuccess,\n id: \"perc-confirm-generic-ok\"\n }\n }; \n }\n else if (settings.type == \"OVERRIDE_OK\")\n {\n buttons = {\n \"Ok\": {\n click: genericCancel,\n id: \"perc-confirm-generic-ok\"\n },\n \"Override\": {\n click: genericSuccess,\n id: \"perc-confirm-generic-override\"\n }\n }; \n }\n else if (settings.type == \"SAVE_BEFORE_CONTINUE\")\n {\n buttons = {\n \"Save\": {\n click: function() {\n settings.save(genericSuccess);\n },\n id: \"perc-confirm-generic-save\"\n },\n \"Cancel\": {\n click: genericCancel,\n id: \"perc-confirm-generic-cancel\"\n },\n \"Don't Save\": {\n click: function() {settings.dontSaveCallback(); dialog.dialog( \"close\" ); dialog.remove();},\n id: \"perc-confirm-generic-continue\"\n } \n }\n }\n else if (settings.type == \"CANCEL_CONTINUE\")\n {\n buttons = {\n \"Continue\": {\n click: genericSuccess,\n id: \"perc-confirm-generic-continue\"\n },\n \"Cancel Blue\": {\n click: genericCancel,\n id: \"perc-confirm-generic-cancel\"\n }\n }\n }\n else if (settings.type == \"CANCEL_START\")\n {\n buttons = {\n \"Start\": {\n click: genericSuccess,\n id: \"perc-confirm-generic-start\"\n },\n \"Cancel\": {\n click: genericCancel,\n id: \"perc-confirm-generic-cancel\"\n }\n }\n }\n else\n {\n buttons = {\n \"Ok\": {\n click: genericSuccess,\n id: \"perc-confirm-generic-ok\"\n },\n \"Cancel\": {\n click: genericCancel,\n id: \"perc-confirm-generic-cancel\"\n }\n }; \n }\n var dialog;\n var dlgOptions = {\n \"dialogClass\": \"perc-confirm-dialog\",\n \"title\":settings.title,\n \"modal\":true,\n \"resizable\": false,\n \"percButtons\": buttons,\n \"id\": settings.id\n };\n if(options.height)\n dlgOptions.height = options.height;\n if(options.width)\n dlgOptions.width = options.width;\n\n //Add don't show again functionality\n if(settings.showAgainCheck){\n //Check user setting on show again warning.\n if (dontShowAgain(dlgOptions.id)){\n if (typeof(options.dontShowAgainAction) == \"function\")\n options.dontShowAgainAction();\n else\n options.success();\n return \"\";\n }\n dlgOptions.open = initializeShowAgainCheck;\n dlgOptions.beforeclose = saveConfirmUserSetting;\n }\n\n dialog = $(\"<div/>\").append( settings.question ).perc_dialog(dlgOptions);\n}", "function ConfirmEditPlan(buttonConfirm, type = 'create') {\r\n editForm = buttonConfirm.parentNode.parentNode;\r\n\r\n setData = {}\r\n setData['function'] = 'set_plan';\r\n setData['disc'] = editForm.querySelector('#edit-text-disc').value;\r\n\r\n var editId = editForm.querySelector('#edit-id').value;\r\n var idPlan = editId == '' ? 'NULL' : editId;\r\n setData['id'] = idPlan;\r\n\r\n setData['ip'] = editForm.querySelector('#edit-ip').value;\r\n\r\n var allDaysElement = editForm.querySelectorAll('.cbox-day');\r\n var daysList = [];\r\n for (var i = 0; i < allDaysElement.length; i++) {\r\n if (allDaysElement[i].checked == true) daysList.push(allDaysElement[i].id)\r\n }\r\n setData['days'] = daysList.join(' ');\r\n\r\n var timeList = [];\r\n timeList.push(editForm.querySelector('#edit-time-start').value)\r\n timeList.push(editForm.querySelector('#edit-time-end').value)\r\n setData['time'] = timeList.join(' ');\r\n\r\n var req = GetXmlHttp();\r\n req.onreadystatechange = function() { \r\n if (req.readyState == 4) { \r\n if(req.status == 200) {\r\n CloseEditBlock(buttonConfirm, type);\r\n // TODO Если несколько открытых панелей, то всё перезагружается\r\n Refresh(); \r\n }\r\n else { notif(req.status ? req.statusText : 'Запрос не удался', 'Ошибка', 'warning'); return;}\r\n }\r\n }\r\n var json_string = JSON.stringify(setData);\r\n SendRequest(req, json_string);\r\n}", "function changeLayoutDialog(type, edit) {\n $('#layoutType').val(type);\n\n if(edit){\n $('#rfb-new-element').val(\"Änderungen speichern\");\n }\n else{\n $('#rfb-new-element').val(\"Element hinzufügen\");\n }\n\n switch (type) {\n case \"7\":\n $('#description_preview').show();\n $('#headline_preview').hide();\n $('#jumplabel_preview').hide();\n $('#jumplabel_preview2').hide();\n if(edit){\n $('#layout_headline_left').html(\"Beschreibung bearbeiten\");\n }\n else{\n $('#layout_headline_left').html(\"Neue Beschreibung erstellen\");\n }\n break;\n case \"8\":\n $('#description_preview').hide();\n $('#headline_preview').show();\n $('#jumplabel_preview').hide();\n $('#jumplabel_preview2').hide();\n if(edit){\n $('#layout_headline_left').html(\"Überschrift bearbeiten\");\n }\n else{\n $('#layout_headline_left').html(\"Neue Überschrift erstellen\");\n }\n break;\n case \"9\":\n $('#description_preview').hide();\n $('#headline_preview').hide();\n $('#jumplabel_preview').hide();\n $('#jumplabel_preview2').hide();\n if(edit){\n $('#layout_headline_left').html(\"Seitenumbruch bearbeiten\");\n }\n else{\n $('#layout_headline_left').html(\"Neuen Seitenumbruch erstellen\");\n }\n break;\n case \"10\":\n $('#description_preview').hide();\n $('#headline_preview').hide();\n $('#jumplabel_preview').show();\n $('#jumplabel_preview2').show();\n if(edit){\n $('#layout_headline_left').html(\"Sprungmarke bearbeiten\");\n }\n else{\n $('#layout_headline_left').html(\"Neue Sprungmarke erstellen\");\n }\n break;\n }\n}", "function ConfirmEditReminder(buttonConfirm, type = 'create') {\r\n editForm = buttonConfirm.parentNode.parentNode;\r\n \r\n var editId = editForm.querySelector('#edit-id').value;\r\n var idModule = editId == '' ? 'NULL' : editId;\r\n\r\n // Получение данных, отправка на сервер изменений, если успешно, продолжить\r\n setData = {}\r\n setData['function'] = 'set_reminder';\r\n setData['id'] = idModule;\r\n setData['user'] = editForm.querySelector('#edit-user').value;\r\n setData['disc'] = editForm.querySelector('#edit-disc').value;\r\n setData['list'] = editForm.querySelector('#edit-reminder-list').value.split('\\n').join('[DEL]');\r\n\r\n var req = GetXmlHttp();\r\n req.onreadystatechange = function() { \r\n if (req.readyState == 4) { \r\n if(req.status == 200) {\r\n CloseEditBlock(buttonConfirm, type);\r\n // TODO Если несколько открытых панелей, то всё перезагружается\r\n Refresh(); \r\n }\r\n else { notif(req.status ? req.statusText : 'Запрос не удался', 'Ошибка', 'warning'); return;}\r\n }\r\n }\r\n var json_string = JSON.stringify(setData);\r\n SendRequest(req, json_string);\r\n}", "ensureButtonsShown() {\n // TODO(fanlan1210)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
I don't like saying this: foo !=== undefined because of the doublenegative. I find this: defined(foo) easier to read.
function defined( value ) { return value !== undefined; }
[ "static isDefined(input) {\n return typeof (input) !== 'undefined';\n }", "function isUndefined(){\n return;\n}", "function isNullOrUndefined(variable) { \r\n\treturn variable === null || variable === undefined; \r\n}", "function firstDefined(){\n var undefined, i = -1;\n while (++i < arguments.length) {\n if (arguments[i] !== undefined) {\n return arguments[i];\n }\n }\n return undefined;\n }", "function aValue() {\n if (a === undefined) {\n console.log(\n \"The variable was parsed and stored as UNDEFINED, but is unable to be used until AFTER it is declared a value.\"\n );\n } else {\n console.log(\n \"It is still parsed and stored as UNDEFINED, but the engine does NOT allow it to be used before it is declared lexically (physically).\"\n );\n }\n}", "function checkUndefined(value){\n\tif(value === undefined){\n\t\treturn \"\";\n\t} else{\n\t\treturn value;\n\t}\n}", "function isPresent(obj) {\r\n return obj !== undefined && obj !== null;\r\n}", "function evaluate_var_definition(stmt,env) {\n define_variable(var_definition_variable(stmt),\n evaluate(var_definition_value(stmt),env),\n env);\n return undefined;\n}", "function falsy_QMRK_(a) {\n return ((a === null) || (a === false));\n}", "function hasUndefined(obj) {\r\n\t if (obj === undefined) {\r\n\t return true;\r\n\t }\r\n\t if (obj) {\r\n\t if (Array.isArray(obj)) {\r\n\t for (var i = 0, len = obj.length; i < len; i++) {\r\n\t if (hasUndefined(obj[i])) {\r\n\t return true;\r\n\t }\r\n\t }\r\n\t }\r\n\t else if (typeof obj === \"object\") {\r\n\t var objKeys = _objectKeys(obj);\r\n\t var objKeysLength = objKeys.length;\r\n\t for (var i = 0; i < objKeysLength; i++) {\r\n\t if (hasUndefined(obj[objKeys[i]])) {\r\n\t return true;\r\n\t }\r\n\t }\r\n\t }\r\n\t }\r\n\t return false;\r\n\t}", "function check_undefined(args, names) {\n names.forEach(function (name, i) {\n if (args[i] === undefined) {\n console.error('Argument is undefined: ' + names[i]);\n }\n });\n}", "function notNullish(value) {\n return value !== null && value !== undefined;\n}", "function isExistingName(mO, fO, sO, name) {\r\n\r\n return (isExistingModuleOrLibName(name) ||\r\n isExistingFuncName(mO, name) ||\r\n isExistingGridNameInFunc(fO, name) ||\r\n isExistingLetNameInStep(sO, name) ||\r\n isExistingIndexVarNameInStep(sO, name) ||\r\n isKeyword(name));\r\n\r\n}", "exists(el)\n {\n if(typeof(el) != 'undefined' && el != null) { return true; } // If not undefined or null, then exists.\n return false;\n }", "function isNullOrUndefinedOrEmptyString(variable){\r\n\tif(isNullOrUndefined(variable))return true;\r\n\tvar string = String(variable);\r\n\treturn string.length===0 || !string.trim();\r\n}", "function foo() {\n\t\t\ta = 3;\n\t\t\texpect(a).toBe(3);\n\t\t\tvar a; // declaration is \"hoisted\" to the top of foo()\n\t\t}", "isNotReadOnly(lvalue) {\n doCheck(!lvalue.isReadOnly, \"Assignment to read-only variable\");\n }", "function mustBeTrue (boo){\n\tif (boo === true){\n\t\treturn true;\n\t}\n}", "static evalUpperRangeIsEmpty(dict) {\n return libVal.evalIsEmpty(dict.UpperRange);\n }", "function assertIsTruthy(a){\n return a_is_truthy(a);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies necessary changes to package.json of the example app. It means setting the autolinking config and removing unnecessary dependencies.
async function modifyPackageJson(appPath) { const packageJsonPath = path_1.default.join(appPath, 'package.json'); const packageJson = await fs_extra_1.default.readJson(packageJsonPath); if (!packageJson.expo) { packageJson.expo = {}; } // Set the native modules dir to the root folder, // so that the autolinking can detect and link the module. packageJson.expo.autolinking = { nativeModulesDir: '..', }; // Remove unnecessary dependencies for (const dependencyToRemove of DEPENDENCIES_TO_REMOVE) { delete packageJson.dependencies[dependencyToRemove]; } await fs_extra_1.default.writeJson(packageJsonPath, packageJson, { spaces: 2, }); }
[ "async function changePackages() {\n const packages = await getPackages()\n\n await Promise.all(\n packages.map(async ({ pkg, path: pkgPath }) => {\n // you can transform the package.json contents here\n\n if (\n pkg.files &&\n pkg.files.includes('lib') &&\n pkg.name !== 'babel-plugin-emotion'\n ) {\n pkg.files = pkg.files.map(file => (file === 'lib' ? 'dist' : file))\n }\n\n await writeFile(\n path.resolve(pkgPath, 'package.json'),\n JSON.stringify(pkg, null, 2) + '\\n'\n )\n })\n )\n}", "async function update_package_jsons() {\n const pkg = JSON.parse(fs.readFileSync(\"./package.json\"));\n pkg.version = NEW_VERSION;\n const pkg_json = `${JSON.stringify(pkg, undefined, 4)}\\n`;\n fs.writeFileSync(\"../package.json\", pkg_json);\n const packages = {};\n for (const ws of pkg.workspaces) {\n for (const path of glob(`${ws}/package.json`, {\n sync: true,\n })) {\n const pkg = JSON.parse(fs.readFileSync(path));\n pkg.version = NEW_VERSION;\n packages[pkg.name] = {\n pkg,\n path,\n };\n }\n }\n for (const pkg_name of Object.keys(packages)) {\n const { pkg, path } = packages[pkg_name];\n for (const deptype of [\n \"dependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n ]) {\n if (pkg[deptype]) {\n for (const dep of Object.keys(pkg[deptype])) {\n if (packages[dep] !== undefined) {\n pkg[deptype][dep] = `^${NEW_VERSION}`;\n }\n }\n }\n }\n const pkg_json = `${JSON.stringify(pkg, undefined, 4)}\\n`;\n fs.writeFileSync(path, pkg_json);\n sh`git add ${path}`.runSync();\n }\n}", "function install () {\n if (this.options['skip-install']) {\n return;\n }\n //if version of lark in app is the same as the lark called this generator\n if (this.larkVersion === this.env.larkPkg.version) {\n (copyLark.call(this) && updateLark.call(this)) || (cleanCopy.call(this));\n }\n this.npmInstall(['grunt'], { 'saveDev': true });\n installDenpendencies.call(this);\n}", "function packageModifications(cb){\n var packageConfig = config.packageChanges();\n if(packageConfig){\n mess.load(\"Modifying package.json file\");\n perf.start(\"Package.json changes\");\n package.modify(packageConfig, (success) => {\n mess.stopLoad(true);\n perf.end(\"Package.json changes\");\n if(!success){\n mess.yesOrNo(\"Continue deploying?\",rl,(yes) => {\n if(yes){\n return cb();\n }else{\n return endProcess();\n }\n })\n }else{\n mess.success(\"Finished modifying package.json\");\n return cb();\n }\n })\n }else{\n return cb();\n }\n}", "function launchAutolinkConfig(){\n\t\n\t\n\t\n\t\n}", "async function generatePackageJson() {\n const original = require('../package.json')\n const result = {\n name: original.name,\n author: original.author,\n version: original.version,\n license: original.license,\n description: original.description,\n main: './index.js',\n dependencies: Object.entries(original.dependencies).filter(([name, version]) => original.external.indexOf(name) !== -1).reduce((object, entry) => ({ ...object, [entry[0]]: entry[1] }), {})\n }\n await writeFile('dist/package.json', JSON.stringify(result))\n}", "function amend() {\n\tif (\n\t\tprogram.amend\n\t\t|| process.env.npm_lifecycle_event === 'postversion' && !program.neverAmend\n\t\t|| !program.incrementBuild\n\t) {\n\t\tchild.spawnSync('git', ['add', program.android, program.ios]);\n\t\tchild.execSync('git commit --amend --no-edit');\n\t}\n}", "function applyCocoaPodsModifications(contents) {\n // Ensure installer blocks exist\n let src = addInstallerBlock(contents, 'pre');\n // src = addInstallerBlock(src, \"post\");\n src = addMapboxInstallerBlock(src, 'pre');\n // src = addMapboxInstallerBlock(src, \"post\");\n return src;\n}", "function populateApplicationPackageJSON(\n applicationName,\n convertedAppDir,\n { packagesDir, packagesDirName, packagesThatShouldBeLibs }\n) {\n const appPackageJSON = readJsonSync(\n join(\"..\", \"conversion-data\", applicationName, \"package.json\")\n );\n const appPackageJSONFileLocation = join(convertedAppDir, \"package.json\");\n\n for (const packageDir of readdirSync(packagesDir)) {\n const isNotLib = packagesThatShouldBeLibs.includes(packageDir) === false;\n const isPackage = isPackageDirectory(packagesDir, packageDir);\n\n if (isNotLib && isPackage) {\n appPackageJSON.dependencies[\n packageDir\n ] = `file:../../${packagesDirName}/${packageDir}`;\n }\n }\n\n writeJsonSync(appPackageJSONFileLocation, appPackageJSON, { spaces: 2 });\n}", "function updateLibraryDependencies(targetDependencies, workingDirectory) {\n const angularJson = fs.readJsonSync(\n path.join(workingDirectory, 'angular.json')\n );\n\n const defaultProject = angularJson.defaultProject;\n\n const packageJsonPath = path.join(\n workingDirectory,\n angularJson.projects[defaultProject].root,\n 'package.json'\n );\n const packageJson = fs.readJsonSync(packageJsonPath);\n\n updateLibraryDependencySection(\n 'dependencies',\n packageJson,\n targetDependencies\n );\n\n updateLibraryDependencySection(\n 'peerDependencies',\n packageJson,\n targetDependencies\n );\n\n fs.writeJsonSync(packageJsonPath, packageJson, { spaces: 2 });\n}", "function updateModulesPackages() {\n return through2.obj(function(file, enc, cb) {\n if (file.isNull()) {\n cb(null, file);\n return;\n }\n\n if (file.isStream()) {\n cb(new gulputil.PluginError('convertPackageMain', 'Streaming not supported'));\n return;\n }\n\n const pkg = JSON.parse(file.contents.toString());\n\n // Update package.main to point at babel-renamed files\n if (pkg.main && path.extname(pkg.main) === '.jsx') {\n pkg.main = pkg.main.substr(0, pkg.main.length - 1);\n }\n\n // Update dependencies to load shrine modules locally\n pkg.dependencies = Object.keys(pkg.dependencies || {}).reduce(\n (dependencies, dependencyName) => {\n if (dependencyName.indexOf(`${MODULE_PREFIX}/`) === 0) {\n dependencies[dependencyName] = path.resolve(path.join(MODULES_BUILD_DIR, dependencyName));\n } else {\n dependencies[dependencyName] = pkg.dependencies[dependencyName];\n }\n\n return dependencies;\n },\n {}\n );\n\n file.contents = new Buffer(JSON.stringify(pkg, null, 2));\n this.push(file);\n\n cb();\n });\n}", "function updateVersion(pkg) {\r\n fs.readFile(__dirname + '/../package.json', 'utf8', (err, data) => {\r\n errorOnFail(err, pkg)\r\n\r\n const globalVersion = JSON.parse(data).version\r\n const path = __dirname + '/../packages/' + pkg + '/package.json'\r\n\r\n fs.readFile(path, 'utf8', (err, data) => {\r\n errorOnFail(err, pkg)\r\n\r\n const packageJSON = JSON.parse(data)\r\n packageJSON.version = globalVersion\r\n\r\n if (packageJSON.peerDependencies && packageJSON.peerDependencies.fela) {\r\n packageJSON.peerDependencies.fela = globalVersion\r\n }\r\n\r\n const newPackageJSON = JSON.stringify(packageJSON, null, 2)\r\n\r\n fs.writeFile(path, newPackageJSON, err => {\r\n errorOnFail(err, pkg)\r\n console.log('Successfully updated ' + pkg + ' version to ' + globalVersion + '.')\r\n })\r\n })\r\n })\n}", "function update_package_file_version() {\r\n\tconst package_file_path = library_base_directory + 'package.json';\r\n\tlet package_file_content = CeL.read_file(package_file_path).toString()\r\n\t\t// version stamp\r\n\t\t.replace(/(\"version\"[\\s\\n]*:[\\s\\n]*\")[^\"]*(\")/, function (all, header, footer) {\r\n\t\t\treturn header + CeL.version + footer;\r\n\t\t});\r\n\tCeL.write_file(package_file_path, package_file_content, { changed_only: true });\r\n}", "async writeLinksOnNodeModules() {\n const links = await this.manyComponentsWriter._getAllLinks();\n const nodeModulesLinks = links.filterByPath(filePath => filePath.startsWith('node_modules'));\n await nodeModulesLinks.persistAllToCapsule(this.capsule);\n }", "function merge(cdnjs, microjs, app, cb) {\n var pkgs = [];\n\n microjs = microjs.map(function(pkg) {\n pkg.name = sanitize(pkg.name);\n pkg.origin = 'microjs';\n return pkg;\n });\n\n // merge the two, cdnjs libs takes precedence\n var names = cdnjs.map(function(pkg) {\n pkg.origin = 'cdnjs';\n return sanitize(pkg.name);\n });\n\n microjs = microjs.filter(function(pkg) {\n // filter out any libs already present in cdnjs packages\n return !~names.indexOf(sanitize(pkg.name));\n });\n\n pkgs = pkgs.concat(cdnjs).concat(microjs);\n\n // now, try to standardize...\n pkgs = pkgs.map(function(pkg) {\n var o = {\n name: pkg.name,\n description: pkg.description,\n version: pkg.version || '',\n homepage: pkg.homepage || pkg.url || '',\n keywords: pkg.keywords || pkg.tags,\n repo: guess('repo', pkg),\n branch: guess('branch', pkg),\n source: guess('source', pkg),\n repositories: guess('repositories', pkg),\n origin: pkg.origin\n };\n o[pkg.origin] = true;\n return o;\n });\n\n // filter out any invalid packages, just testing pkg.name\n pkgs = pkgs.filter(function(pkg) { return pkg.name; });\n\n pkgs = pkgs.sort(function(a, b) {\n // todo: true sort\n return a.name < b.name;\n });\n\n fs.writeFile(path.join(app.get('prefix'), 'gimme.json'), JSON.stringify(pkgs, null, 2), cb);\n}", "async function rebuildPackageLocks() {\n const project = new Project(process.cwd());\n\n await removePackageLocks(project);\n console.log('Running npm install...');\n execSync('npm install');\n}", "_addExternals() {\n\n // \"handlebars\": \"./node_modules/handlebars/dist/handlebars.amd.min.js\"\n // reading JSON\n let config = this.fs.readJSON(this.destinationPath('config/config.json'));\n\n // Add Handlebars entry\n config.externals.handlebars = \"./node_modules/handlebars/dist/handlebars.amd.min.js\";\n\n // writing json\n fs.writeFileSync(\n this.destinationPath('config/config.json'),\n JSON.stringify(config, null, 2));\n\n\n }", "updatePersistedMetadata() {\n this.addon.sourceURI = this.sourceURI.spec;\n\n if (this.releaseNotesURI) {\n this.addon.releaseNotesURI = this.releaseNotesURI.spec;\n }\n\n if (this.installTelemetryInfo) {\n this.addon.installTelemetryInfo = this.installTelemetryInfo;\n }\n }", "apply(compiler) {\n compiler.hooks.afterEmit.tap('MoveResourcesPlugin', (compilation)=>{\n let movePath = isProduction\n ? `${projectRootPath}/templates/_auto_generated/production/js_bundle.html`\n : `${projectRootPath}/templates/_auto_generated/development/js_bundle.html`;\n\n fs.rename(\n `${webAssetsDistDir}/js_bundle.html`,\n movePath,\n webpackUtils.moveResourcePluginErrorCallback);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
unwraps the element so we can use its methods freely
function unwrap(elem) { if (elem) { if ( typeof XPCNativeWrapper === 'function' && typeof XPCNativeWrapper.unwrap === 'function' ) { return XPCNativeWrapper.unwrap(elem); } else if (elem.wrappedJSObject) { return elem.wrappedJSObject; } } return elem; }
[ "replace (element) {\r\n element = makeInstance(element);\r\n this.node.parentNode.replaceChild(element.node, this.node);\r\n return element\r\n }", "visitUnpivot_in_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function closeElement(element) {\r\n element.remove();\r\n}", "destroyElement() {\n if (this.dom) {\n this.dom.remove();\n }\n }", "function get_element_to_be_swiped(element)\n{\n if(element.swipe_animtion == null)\n {\n return get_element_to_be_swiped(element.offsetParent);\n }\n return element;\n}", "function BAElement() { }", "function makeInvisible(element) {\n\telement.className = \"invisible\";\n}", "remove() {\n const ownerElement = this.node.ownerElement\n if(ownerElement) {\n ownerElement.removeAttribute(this.name)\n }\n }", "sendToBack(element) {\n return this.changeIndexTo(element, 0, false);\n\n if (index > 0) {\n this._children.splice(index, 1);\n this._children.splice(0, 0, element);\n }\n }", "function $(el){\n\tif ($type(el) == 'string') el = document.getElementById(el);\n\tif ($type(el) == 'element'){\n\t\tif (!el.extend){\n\t\t\tUnload.elements.push(el);\n\t\t\tel.extend = Object.extend;\n\t\t\tel.extend(Element.prototype);\n\t\t}\n\t\treturn el;\n\t} else return false;\n}", "get element() {\n return this.dom;\n }", "function dropPointySubElements(element) {\n\tvar ret = [];\n\telement.each(function (idx, el) {\n\t\tvar jel = $j(el);\n\t\tvar hadOne = false;\n\t\tjel.find(\"em\").each(function (idx2, el2) {\n\t\t\tvar jel2 = $j(el2);\n\t\t\tif (jel2.html() == \"&nbsp;\") {\n\t\t\t\thadOne = true;\n\t\t\t}\n\t\t});\n\t\t\n\t\tif (!hadOne) {\n\t\t\tret.push(el);\n\t\t}\n\t});\n\treturn $j(ret);\n}", "function removeElement(node) {\n\t\tjQuery(node).remove();\n\t}", "function _unwrapCommentBlock(){\n var parent = $(this).parents(\"pre\");\n var unwrappedHTML = parent.html().replace(this.outerHTML, this.innerHTML);\n\n parent.html(unwrappedHTML);\n }", "function removeSiblings() {\n var parent = element.parent();\n parent.find(\"i.custom-icon\").remove();\n parent.find(\"span.help-block\").remove();\n }", "function wrapInner(parent,wrapper){if(typeof wrapper===\"string\"){wrapper=createElementFromHTML(wrapper);}parent.appendChild(wrapper);while(parent.firstChild!==wrapper){wrapper.appendChild(parent.firstChild);}}", "getElement(el) {\n return document.getElementsByClassName(el)[0];\n }", "elem(arg) {\n switch (_Util_main_js__WEBPACK_IMPORTED_MODULE_1__.default.getType(arg)) {\n // Applies view to every modifier function, if there are no modifer functions elem is returned:\n case \"undefined\":\n return this._fns.reduce((view, fn) => {\n return fn(view);\n }, this._elem);\n // Sets _elem to given yngwieElement:\n case \"YngwieElement\":\n this._elem = arg;\n return this;\n // Tries to initalize yngwieElement using given arguments:\n default:\n this._elem = yngwie__WEBPACK_IMPORTED_MODULE_0__.Element.init.apply(null, arguments);\n return this;\n }\n }", "replaceChild() {\n if (this.el) {\n this.el.innerHTML = \"\";\n }\n\n this.isDomified = false;\n this.contents = [];\n this.atts = [];\n this.props = [];\n\n this.appendChild.apply(this, arguments);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is where we visualize the algorithm on the board everytime solved is clicked
visualizeAlgo() { let i = 0; // Enter a loopstep recurisve call, that will act as a setInterval const loopStep = () => { // Base case to allow us to leave the function for a reset, // or exit the recursive call when we reach the last entry in the array if (i === this.orderedTraversal.length) { return; } else if (this.reset === true) { this.reset = false return; } // These are the positions and values that are going to be placed // on the board. They are formatted specifically for this in the // algorithms const nextPos = this.orderedPositions[i].parsePos(); const nextVal = this.orderedTraversal[i]; const [cur_x, cur_y] = this.orderedPositions[i]; setTimeout(() => { const tile = document.getElementById(nextPos); const timer = document.getElementById('time'); const counter = document.getElementById('counter'); // This allows us to change the counter, timer, and inner text // of each element on the board counter.innerText = `Iterations: ${this.count}` timer.innerText = `Time: ${sudokuUtil.timeConversion(this.time)}` if (nextVal === 0) { tile.innerText = ''; } else { tile.innerText = `${nextVal}`; } // Add the cool styling so that each element looks like its // apart of a proper visualizer tile.classList.add('o-red') setTimeout(() => { tile.classList.remove('o-red'); }, 500) // Set the tile value to its proper value this.board.puzzle[cur_x][cur_y].val = nextVal; this.count += 1 this.time += this.speed loopStep(); i++ }, this.speed) } loopStep(); }
[ "function Game(matrix = [], delay = { time: 0 }) {\n\tthis.matrix = matrix;\n\tthis.delay = delay;\n\tthis.solver = false;\n\tthis.board = false;\n\tthis.isSolving = false;\n\tthis.interactions = 0;\n\tthis.events = {};\n\n\tconst newGame = (matrix) => {\n\t\t// Create board\n\t\tthis.board = new Board(matrix);\n\n\t\t// Create solver\n\t\tthis.solver = new Solver(matrix, this);\n\t};\n\n\tconst registerEvents = () => {\n\t\tconst interaction = new Event(\"interaction\");\n\t\tthis.events.interaction = interaction;\n\n\t\tconst resolved = new Event(\"resolved\");\n\t\tthis.events.resolved = resolved;\n\t};\n\n\t// Called once, and then the steps (current interation number) will be passed to the draw function\n\tthis.startSolving = () => {\n\t\t// Algorithm\n\t\tthis.isSolving = true;\n\t\tthis.solver.solve(this.matrix);\n\t};\n\n\tthis.redraw = () => {\n\t\tbackground(0);\n\t\tthis.board.draw();\n\t};\n\n\tthis.interacted = () => {\n\t\tthis.interactions++;\n\t\twindow.interactionsNumber = this.interactions;\n\t\twindow.dispatchEvent(this.events.interaction);\n\n\t\treturn this.interactions;\n\t};\n\n\tthis.done = () => {\n\t\tthis.isSolving = false;\n\t\twindow.dispatchEvent(this.events.resolved);\n\t};\n\n\tthis.countEmptyCells = () => {\n\t\tlet emptyCells = 0;\n\t\tfor (let i = 0; i < this.matrix.length; i++) {\n\t\t\tfor (let j = 0; j < this.matrix[0].length; j++) {\n\t\t\t\tif (this.matrix[i][j] === 0) {\n\t\t\t\t\temptyCells++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn emptyCells;\n\t};\n\n\t// Start\n\tnewGame(this.matrix);\n\tregisterEvents();\n}", "handleSolveClick() {\n const history = this.state.history.slice(0, this.state.currStep + 1);\n const currBoard = this.state.history[this.state.currStep].board.slice();\n const currNotes = JSON.parse(JSON.stringify(this.state.history[this.state.currStep].notes.slice()));\n const startingBoard = this.state.history[0].board.slice();\n\n // handling case when there are errors on the board\n const errorArray = findErrors(currBoard);\n\n for (let i = 0; i < errorArray.length; i++) {\n if (!startingBoard[errorArray[i]]) {\n currBoard[errorArray[i]] = null;\n }\n }\n\n const boardString = this.convertBoardToString(currBoard);\n const solvedString = window.sudoku.solve(boardString);\n if (!solvedString) {\n alert(\"There is no possible solution for the current board.\");\n return;\n }\n const solvedBoard = this.convertStringToBoard(solvedString);\n const numCount = Array(9).fill(9);\n this.setState({\n history: history.concat([{\n board: solvedBoard,\n notes: currNotes,\n }]),\n currStep: this.state.currStep + 1,\n numCount: numCount,\n })\n }", "function drawGridContent(){\n for( var i =0; i<=cw/100; i++){\n for(var j=0; j<=ch/100; j++){\n var cI = i.toString()+'-'+j.toString();\n if( cI in gridContent){\n\tif(gridContent[cI]>=0){\n\t if( pickThis == cI){\n\t /* Mouse motion: puzzle piece follows mouse coordiantes: */\n\t drawPiece(mx, my, 100,100, cI==selectedItem, cI);\n\t\t\t\t//0 + 100*i,21 + 100*j, 100,100);\n\t }else{\n\t //Puzzle piece is static: \n\t drawPiece(0 + 100*i,21 + 100*j, 100,100, cI==selectedItem, cI);\n\t }\n\t //draw(mx, my, 100, 100);\n\t}\n }\n }\n }\n}", "display() {\n for (let i = 0; i < this.columns; i++) {\n for (let j = 0; j < this.rows; j++) {\n this.board[i][j].display();\n }\n }\n }", "function GraphButton() {\n\t\tif(functionInput.value!=\"\"){\n\t\t// Clean the Console. For Debug Purposes\n\t\tconsole.clear(); \n\t\t\n\t\t// Clear Canvas\n\t\twipe(0);\n\t\t\n\t\t// Variables\n\t\tvar x = -1*Math.floor((vLines/2)+1); // Start From Very Left of Canvas\n\t\tvar y; // Declare Y Value variable\n\t\t\n\t\t// Make a \"Re-Formatter\" Function to Make the Function Input Evaluable by eval().\n\t\treformatted = Reformat(functionInput.value); // Reformatted Function Argument\n\t\t//alert(reformatted);\n\t\t\n\t\t// Print function input that the page actually evaluates.\n\t\tconsole.log(\"Graphing: \" + reformatted + \".\");\n\t\t\n\t\t// Locate Extrema\n\t\tfindExtrema();\n\t\tGraph(x,y,reformatted,\"blue\");\n\t\t\n\t\t\n\t\t// If Derivative Boxes Are Checked?\t\n\t\tif(firstDer.checked==true)\n\t\t\tfirstDerivative();\n\t\tif(secondDer.checked==true)\n\t\t\tsecondDerivative();\n\t\t}\n}", "function handleSolveBtnOnClick() {\r\n let numMiles = Number(prompt(NUM_MILES_PROMPT));\r\n let cost = Number(prompt(COST_OF_GASOLINE_PROMPT));\r\n displayDiv.innerHTML = \"\"; // Clear the displayDiv\r\n // Append a paragraph element to the display div for each mpg rating in MPG_RATINS\r\n MPG_RATINGS.forEach(mpgRating => {\r\n displayDiv.append(\r\n createEstimatedCostMessage(mpgRating, numMiles, cost),\r\n document.createElement(\"p\")\r\n );\r\n });\r\n}", "display() {\n push();\n fill(255,0,0);\n ellipse(this.x, this.y, this.size);\n pop();\n // if (x < 0 || x > width || y < 0 || y > height) {\n // var removed = obstacles.splice(this.index, 1);\n // }\n }", "display() {\n this.draw(this.points.length);\n }", "function solutionVisibility(){\n\tif(solutionVisible){\n\t\tsolutionVisible=false;\n\t\tlimitedSight=true;\n\t}else{\n\t\tsolutionVisible=true;\n\t\tlimitedSight=false;\n\t}\n\tdrawMaze();\n}", "function printSolution(analysis) {\n\n function printOneStep(step) {\n var type = step.step.type;\n step.name = type;\n if (type === 'line') { step.name += Ln++; }\n else { step.name += Cn++; }\n var _p, p1_str, p2_str;\n if (step.p1_idx !== -1) { p1_str = analysis.points[step.p1_idx].name; }\n else {\n _p = step.step[type === 'line' ? 'p1' : 'c'];\n p1_str = '(x: ' + _p.x + ', y: ' + _p.y + ')';\n }\n if (step.p2_idx !== -1) { p2_str = analysis.points[step.p2_idx].name; }\n else {\n _p = step.step[type === 'line' ? 'p2' : 'p'];\n p2_str = '(x: ' + _p.x + ', y: ' + _p.y + ')';\n }\n console.log(step_no++ + ': ' + step.name + ' [' + p1_str + ' ---> ' + p2_str + ']');\n }\n\n function printUsedIntersects(idx) {\n for (var j = 0; j < analysis.points.length; j++) {\n var _p = analysis.points[j];\n if (_p.s2_idx === idx) {\n _p.name = 'point' + Pn++;\n console.log(' ... ' + _p.name + ' = ' + analysis.steps[_p.s1_idx].name\n + ' x ' + analysis.steps[idx].name\n + ' (x: ' + _p.p.x + ' , y: ' + _p.p.y + ')');\n }\n }\n }\n\n var i, step_no = 1, Pn = 1, Ln = 1, Cn = 1;\n console.log('\\n\\nSolution found!\\n-----');\n console.log('Initial set of points:\\n-----');\n for (i = 0; i < pointsLength0; i++) {\n var p = analysis.points[i];\n p.name = 'point' + Pn++;\n console.log('# ' + p.name + ' (x: ' + p.p.x + ', y: ' + p.p.y + ')');\n }\n if (stepsLength0) {\n console.log('-----\\nInitial construction:\\n-----');\n for (i = 0; i < stepsLength0; i++) {\n printOneStep(analysis.steps[i]);\n printUsedIntersects(i);\n }\n }\n console.log('-----\\nConstruction:\\n-----');\n for (i = stepsLength0; i < analysis.steps.length; i++) {\n printOneStep(analysis.steps[i]);\n printUsedIntersects(i);\n }\n console.log('-----\\nGoals:\\n-----');\n for (i = 0; i < analysis.goals.length; i++) {\n var _g = analysis.goals[i];\n console.log('# (x: ' + _g.p.x + ', y: ' + _g.p.y + ') === '\n + analysis.steps[_g.s1_idx].name + ' x '\n + analysis.steps[_g.s2_idx].name);\n }\n console.log();\n}", "visualizeBFS() {\n // sr = this.state.START_NODE_ROW;\n // sc = this.state.START_NODE_COL;\n if(this.state.done === true){\n alert(\"Clear the grid First\");\n }else {\n console.log(this.state.START_NODE_ROW);\n const {grid} = this.state;\n const startNode = grid[this.state.START_NODE_ROW][this.state.START_NODE_COL];\n const finishNode = grid[this.state.FINISH_NODE_ROW][this.state.FINISH_NODE_COL];\n const visitedNodesInOrder = bfs(grid,startNode,finishNode);\n const nodesInShortestPathOrder = getNodesInShortestPathOrderBFS(finishNode);\n //console.table(visitedNodesInOrder[0]);\n // alert(\"BFS is going to execute\");\n this.setState({'done' : true});\n this.animate(visitedNodesInOrder,nodesInShortestPathOrder);\n //console.log(visitedNodesInOrder.length);\n }\n }", "drawGrid() {\n const { id, selected } = this.currentWord;\n\n clear();\n this.logger.log(figlet.textSync(wordsearchConstants.GAME_TITLE, { font: 'Mini' }));\n this.logger.log(wordsearchConstants.GAME_INFO);\n this.logger.log(chalk.grey(wordsearchConstants.GAME_INSTRUCTIONS));\n\n this.grid.forEach((row, rowIdx) => {\n // first add all letters in the row (with correct colours)\n const rowData = [];\n row.forEach((item, itemIdx) => {\n if (this.guessedWords.indexOf(item.word) !== -1) {\n rowData.push(chalk.green(item.letter));\n } else if (item.word === id && selected.indexOf(`${rowIdx},${itemIdx}`) !== -1) {\n rowData.push(chalk.black.bgGreen(item.letter));\n } else {\n rowData.push(item.letter);\n }\n });\n let rowStr = rowData.join(' ');\n\n // then add a word from the word list to the right of the grid\n if (this.wordsearchWordList[rowIdx]) {\n rowStr += wordsearchConstants.WORD_SPACING;\n let word = this.wordsearchWordList[rowIdx];\n if (this.guessedWords.indexOf(rowIdx) !== -1) {\n word = chalk.green(word);\n }\n rowStr += word;\n }\n\n this.logger.log(rowStr);\n });\n\n this.setCursorPos();\n }", "function disp_curr_game_state(){\n game_ctx.fillStyle = \"green\" ;\n for (i = 0; i < matrix_side_length; i++){\n for (j = 0; j < matrix_side_length; j++){\n if( matrix[i][j] == 1 ){\n game_ctx.fillRect(i*unit, j*unit, unit, unit); \n }\n }\n } \n}", "function updateView() {\n // For every square on the board.\n console.log(MSBoard.rows);\n\n for (var x = 0; x < MSBoard.columns; x++) {\n for (var y = 0; y < MSBoard.rows; y++) {\n squareId = \"#\" + x + \"-\" + y;\n // Removes the dynamic classes from the squares before adding appropiate ones back to it.\n $(squareId).removeClass(\"closed open flagged warning\");\n\n square = MSBoard.squares[x][y];\n\n // These questions determine how a square should appear.\n // If no other text is put into a square, a &nbsp; is inserted because otherwise it disturbs the grid.\n // If a square is open, it should be themed as so and also display the number of nearby mines.\n if (square.open && !square.mine) {\n $(squareId).addClass(\"open\");\n $(squareId).html(square.nearbyMines);\n } \n // Flags are displayed only if the square is still closed.\n else if (square.flag && !square.open) {\n $(squareId).addClass(\"closed\");\n $(squareId).html(\"<img src='redFlag.png' class='boardImg flag' />&nbsp;\")\n } \n // Mines are displayed either if they're open (Either from opening one and losing or during validating) or while the cheat control is pressed.\n else if (square.mine && (square.open || cheating)) {\n $(squareId).addClass(\"warning\");\n $(squareId).html(\"<img src='mine.png' class='boardImg mine' />&nbsp;\")\n } \n // The HTML is set to a blank space in case there is nothing else to put in the space. \n else if (!square.open && !square.flag) {\n $(squareId).addClass(\"closed\"); \n $(squareId).html(\"&nbsp;\")\n }\n\n }\n }\n\n if (startMenuOn) {\n $(\"#newGameSettings\").css(\"display\", \"block\");\n } else {\n $(\"#newGameSettings\").css(\"display\", \"none\"); \n }\n\n}", "function make_sudoku(id, descr){\n // Obtain the element in which to append the sudoku.\n var container = document.getElementById(id);\n\n // Create the main div for the sudoku.\n var main_div = document.createElement(\"div\");\n main_div.classList.add(\"puzzle\");\n container.append(main_div);\n\n // Create the overlay and underlay images (used for thermos and the likes).\n var overlay = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n overlay.classList.add(\"overlay\");\n overlay.classList.add(\"foreground\");\n\n var underlay = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n underlay.classList.add(\"overlay\");\n underlay.classList.add(\"background\");\n\n // Width and height of the grid.\n var w = descr.width;\n var h = descr.height;\n\n // Initialize the array of cells.\n var cells = new Array(w);\n for(var x = 0; x < w; x++){\n cells[x] = new Array(h);\n\n for(var y = 0; y < h; y++){\n var c = document.createElement(\"td\");\n c.classList.add(\"cell\");\n\n var val = document.createElement(\"span\");\n val.classList.add(\"value\");\n c.append(val);\n\n var center_m = document.createElement(\"span\");\n center_m.classList.add(\"centerMark\");\n c.append(center_m);\n\n var corner_m = document.createElement(\"span\");\n corner_m.classList.add(\"cornerMark\");\n c.append(corner_m);\n\n cells[x][y] = {\n cell: c,\n value: val,\n center_mark: center_m,\n corner_mark: corner_m,\n };\n }\n }\n\n // Construct the grid.\n var grid = document.createElement(\"table\");\n grid.classList.add(\"grid\");\n for(y = 0; y < h; y++){\n var line = document.createElement(\"tr\");\n line.classList.add(\"line\");\n grid.append(line);\n\n for(x = 0; x < w; x++){\n line.append(cells[x][y].cell);\n }\n }\n\n // Put everything in the main div.\n main_div.append(underlay);\n main_div.append(grid);\n main_div.append(overlay);\n\n // For each cell, was it given at the start?\n var given = new Array(w);\n for(var x = 0; x < w; x++){\n given[x] = new Array(h);\n for(var y = 0; y < h; y++){\n given[x][y] = false;\n }\n }\n\n // Add the givens.\n function add_given(g){\n given[g.x][g.y] = true;\n cells[g.x][g.y].value.innerHTML = g.digit;\n cells[g.x][g.y].value.style.color = \"#000000\";\n }\n descr.givens.forEach(add_given);\n\n // Add the regions.\n function add_region(r) {\n var x = r.x;\n var y = r.y;\n var horiz = true;\n\n function add_border(x, y, dir){\n if(x < 0 || w+1 < x || y < 0 || h+1 < y){\n console.log(\"Invalid border (starting at (\", x, \",\", y, \")).\");\n return;\n }\n switch(dir){\n case 0: // east\n if(x == w){\n console.log(\"Invalid border (out of the grid to the east).\");\n return;\n }\n if(y < h){\n cells[x][y].cell.style.borderTop = \"3px solid black\";\n } else {\n // On south grid border.\n cells[x][y-1].cell.style.borderBottom = \"3px solid black\";\n }\n break\n case 1: // south\n if(y == h){\n console.log(\"Invalid border (out of the grid to the south).\");\n return;\n }\n if(x > 0){\n cells[x-1][y].cell.style.borderRight = \"3px solid black\";\n } else {\n // On west grid border.\n cells[x][y].cell.style.borderLeft = \"3px solid black\";\n }\n break\n case 2: // west\n if(x == 0){\n console.log(\"Invalid border (out of the grid to the west).\");\n return;\n }\n if(y < h){\n cells[x-1][y].cell.style.borderTop = \"3px solid black\";\n } else {\n // On south grid border.\n cells[x-1][y-1].cell.style.borderBottom = \"3px solid black\";\n }\n break\n case 3: // north\n if(y == 0){\n console.log(\"Invalid border (out of the grid to the north).\");\n return;\n }\n if(x > 0){\n cells[x-1][y-1].cell.style.borderRight = \"3px solid black\";\n } else {\n // On east grid border.\n cells[x][y-1].cell.style.borderLeft = \"3px solid black\";\n }\n break\n }\n }\n\n for(var i = 0; i < r.path.length; i++){\n var n = r.path[i];\n\n // Compute the direction.\n if(horiz){\n if(n > 0){ // going east\n for(var k = 0; k < n; k++){\n add_border(x, y, 0); x++;\n }\n } else { // going west\n for(var k = 0; k < -n; k++){\n add_border(x, y, 2); x--;\n }\n }\n } else {\n if(n > 0){ // going south\n for(var k = 0; k < n; k++){\n add_border(x, y, 1); y++;\n }\n } else { // going north\n for(var k = 0; k < -n; k++){\n add_border(x, y, 3); y--;\n }\n }\n }\n\n horiz = !horiz;\n }\n }\n descr.regions.forEach(add_region);\n\n // Compute regions.\n var regions = cells_of_regions(descr.width, descr.height, descr.regions);\n\n // Utility function to get the center of a cell.\n function cell_center(x, y){\n var cell_offset = cells[x][y].cell.getBoundingClientRect();\n var grid_offset = grid.getBoundingClientRect();\n\n var cx = cell_offset.left - grid_offset.left + cell_offset.width / 2;\n var cy = cell_offset.top - grid_offset.top + cell_offset.height / 2;\n\n return { x: Math.round(cx), y: Math.round(cy) };\n }\n\n // Paint the thermometers on the underlay.\n function add_thermo(t){\n var c = cell_center(t.bulb.x, t.bulb.y);\n\n var bulb = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n bulb.setAttribute('cx', c.x);\n bulb.setAttribute('cy', c.y);\n bulb.setAttribute('r', 18);\n bulb.setAttribute('fill', \"#C4C4C4\");\n underlay.append(bulb);\n\n if(t.path.length != 0){\n var path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"polyline\");\n path.setAttribute('fill', \"none\");\n path.setAttribute('stroke', \"#C4C4C4\");\n path.setAttribute('stroke-linecap', \"round\");\n path.setAttribute('stroke-width', 16);\n\n var points = c.x + \",\" + c.y;\n function add_point(p){\n var c = cell_center(p.x, p.y);\n points = points + \" \" + c.x + \",\" + c.y;\n }\n t.path.forEach(add_point);\n\n path.setAttribute('points', points);\n underlay.append(path);\n }\n }\n descr.thermos.forEach(add_thermo);\n\n // Compute thermos\n var thermos = cells_of_thermos(descr.thermos);\n\n // Code to light up thermo cells (for debug).\n //thermos.forEach(function(t){\n // t.forEach(function(p){\n // cells[p.x][p.y].cell.style.backgroundColor = \"purple\";\n // });\n //});\n\n // Paint the kropki dots on the overlay.\n function add_dots(dots){\n if(dots.path.length < 2){\n console.log(\"Invalid kropki dot spec.\");\n return;\n }\n\n for(var i = 0; i < dots.path.length - 1; i++){\n var c1 = cell_center(dots.path[i ].x, dots.path[i ].y);\n var c2 = cell_center(dots.path[i+1].x, dots.path[i+1].y);\n var x = (c1.x + c2.x) / 2;\n var y = (c1.y + c2.y) / 2;\n\n var d = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n d.setAttribute('cx', x);\n d.setAttribute('cy', y);\n d.setAttribute('r', 6);\n d.setAttribute('stroke', \"black\");\n d.setAttribute('stroke-width', 2);\n d.setAttribute('fill', dots.kind);\n overlay.append(d);\n }\n }\n descr.kropki_dots.forEach(add_dots);\n\n // Add the cages.\n var offset = 22;\n function add_cage(r) {\n var path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"polygon\");\n path.setAttribute('fill', \"none\");\n path.setAttribute('stroke', \"black\");\n path.setAttribute('stroke-dasharray', \"5,2\");\n path.setAttribute('stroke-width', \"1px\");\n path.setAttribute('shape-rendering', \"crispEdges\");\n path.setAttribute('stroke-linejoin', \"round\");\n\n // Start in the top, left corner of the origin point.\n var o = cell_center(r.x, r.y);\n var points = (o.x - offset) + \",\" + (o.y - offset);\n\n // Variables with the coordinates of the cell holding the previous point.\n var x = r.x;\n var y = r.y;\n\n // In which corner of the cell was the previous point?\n var north_of_cell = true;\n var west_of_cell = true;\n\n // Are we moving horizontally?\n var horiz = true;\n\n for(var i = 0; i < r.path.length - 1; i++){\n var n = r.path[i]; // Size of the current segment (number of cells).\n var m = r.path[i+1]; // Size of the next segment (used for direction).\n\n if(horiz){\n x = x + n - (west_of_cell ? 1 : 0) + (m > 0 ? 0 : 1);\n west_of_cell = !(m > 0);\n } else {\n y = y + n - (north_of_cell ? 1 : 0) + (m > 0 ? 1 : 0);\n north_of_cell = (m > 0);\n }\n\n var c = cell_center(x, y);\n var dx = (west_of_cell ? -offset : offset);\n var dy = (north_of_cell ? -offset : offset);\n points = points + \" \" + (c.x + dx) + \",\" + (c.y + dy);\n horiz = !horiz;\n }\n\n path.setAttribute('points', points);\n underlay.append(path);\n\n // Also add the clue if there is one.\n if(r.value){\n var text = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\n text.setAttribute('x', (o.x - 20) + \"px\");\n text.setAttribute('y', (o.y - 13) + \"px\");\n text.setAttribute('font-size', \"10px\");\n text.textContent = r.value;\n\n underlay.append(text);\n }\n }\n descr.cages.forEach(add_cage);\n\n // How many digits have been entered so far?\n var nb_digits = descr.givens.length;\n\n // Check if the grid is fully filled.\n function check_ready(){\n return (nb_digits == descr.width * descr.height);\n }\n\n // Checking function\n function check_solution(){\n // Check that all digits have been entered.\n if(!check_ready()){\n return \"There are still digits to fill in!\";\n }\n\n var digits = descr.digits.sort().join('');\n\n // Check the lines.\n for(var y = 0; y < descr.height; y++){\n var used = \"\";\n\n for(var x = 0; x < descr.width; x++){\n used = used + cells[x][y].value.innerHTML;\n }\n\n used = used.split('').sort().join('');\n\n if(!(used === digits)){\n return \"There is a duplicated digit in line \" + (y+1) + \"...\";\n }\n }\n\n // Check the columns.\n for(var x = 0; x < descr.width; x++){\n var used = \"\";\n\n for(var y = 0; y < descr.height; y++){\n used = used + cells[x][y].value.innerHTML;\n }\n\n used = used.split('').sort().join('');\n\n if(!(used === digits)){\n return \"There is a duplicated digit in column \" + (x+1) + \"...\";\n }\n }\n\n // Check the regions.\n for(var i = 0; i < regions.length; i++){\n var used = \"\";\n\n for(j = 0; j < regions[i].length; j++){\n var x = regions[i][j].x;\n var y = regions[i][j].y;\n used = used + cells[x][y].value.innerHTML;\n }\n\n used = used.split('').sort().join('');\n\n if(!(used === digits)){\n return \"There is a duplicated digit in box \" + (i+1) + \"...\";\n }\n }\n\n // Check the killer cages.\n // TODO\n\n // Check the thermos.\n for(var i = 0; i < thermos.length; i++){\n for(var j = 0; j < thermos[i].length - 1; j++){\n var p1 = thermos[i][j];\n var p2 = thermos[i][j+1];\n var v1 = parseInt(cells[p1.x][p1.y].value.innerHTML, 10);\n var v2 = parseInt(cells[p2.x][p2.y].value.innerHTML, 10);\n\n if(v1 >= v2){\n return \"There is a problem with a thermometer...\";\n }\n }\n }\n\n // Check the kropki dots.\n for(let dots of descr.kropki_dots){\n for(var i = 0; i < dots.path.length - 1; i++){\n var p1 = dots.path[i];\n var p2 = dots.path[i+1];\n var v1 = parseInt(cells[p1.x][p1.y].value.innerHTML, 10);\n var v2 = parseInt(cells[p2.x][p2.y].value.innerHTML, 10);\n\n if(dots.kind === \"white\" && Math.max(v1, v2) != Math.min(v1, v2) + 1){\n return \"There is a problem with a white kropki dot...\";\n }\n\n if(dots.kind === \"black\" && Math.max(v1, v2) != Math.min(v1, v2) * 2){\n return \"There is a problem with a black kropki dot...\";\n }\n }\n }\n\n return \"Looks good to me!\";\n }\n\n // Return object initialization.\n var retval = {\n is_ready: check_ready,\n do_check: check_solution,\n };\n\n // Selected cells.\n var selected = new Array(w);\n for(var x = 0; x < w; x++){\n selected[x] = new Array(h);\n for(var y = 0; y < h; y++){\n selected[x][y] = false;\n }\n }\n\n // Number of selected cells.\n var selection_size = 0;\n\n // Currently selecting?\n var selecting = false;\n\n // Are we deselection?\n var deselecting = false;\n\n // When ctrl is pressed, add on top of the current selection.\n var ctrl_pressed = false;\n var shift_pressed = false;\n\n function select_cell(x, y){\n if(!selected[x][y] && !deselecting){\n selected[x][y] = true;\n selection_size++;\n cells[x][y].cell.classList.add(\"selected\");\n }\n\n if(selected[x][y] && deselecting){\n selected[x][y] = false;\n selection_size--;\n cells[x][y].cell.classList.remove(\"selected\");\n }\n }\n\n function clear_selection(){\n for(var x = 0; x < w; x++){\n for(var y = 0; y < h; y++){\n if(selected[x][y]){\n selected[x][y] = false;\n cells[x][y].cell.classList.remove(\"selected\");\n }\n }\n }\n selection_size = 0;\n }\n\n function update_selection(){\n for(var x = 0; x < w; x++){\n for(var y = 0; y < h; y++){\n if(selected[x][y]){\n cells[x][y].cell.classList.add(\"selected\");\n } else {\n cells[x][y].cell.classList.remove(\"selected\");\n }\n }\n }\n }\n\n // Temporary selected array used to compute selection move.\n var selected_tmp = new Array(w);\n for(var x = 0; x < w; x++){\n selected_tmp[x] = new Array(h);\n }\n\n function move_selection(dir){\n // If there is no selected cell, just select the center cell.\n if(selection_size == 0){\n deselecting = false;\n select_cell(Math.floor(w / 2), Math.floor(h / 2));\n return;\n }\n\n // Save the selection.\n for(var x = 0; x < w; x++){\n for(var y = 0; y < h; y++){\n selected_tmp[x][y] = selected[x][y];\n }\n }\n\n // Update the selected cells.\n for(var x = 0; x < w; x++){\n for(var y = 0; y < h; y++){\n switch(dir){\n case 0: // east\n selected[x][y] = selected_tmp[(x + w - 1) % w][y];\n break;\n case 1: // south\n selected[x][y] = selected_tmp[x][(y + h - 1) % h];\n break;\n case 2: // west\n selected[x][y] = selected_tmp[(x + 1) % w][y];\n break;\n case 3: // north\n selected[x][y] = selected_tmp[x][(y + 1) % h];\n break;\n }\n }\n }\n\n // Update the displayed selection.\n update_selection();\n }\n\n function set_center_mark(x, y, s){\n if(s === \"\"){\n cells[x][y].center_mark.innerHTML = \"\";\n } else {\n var v = cells[x][y].center_mark.innerHTML;\n if(v.includes(s)){\n v = v.replace(s, '');\n } else {\n v = (v + s).split('').sort().join('');\n }\n cells[x][y].center_mark.innerHTML = v;\n }\n }\n\n function set_corner_mark(x, y, s){\n if(s === \"\"){\n cells[x][y].corner_mark.innerHTML = \"\";\n } else {\n var v = cells[x][y].corner_mark.innerHTML;\n if(v.includes(s)){\n v = v.replace(s, '');\n } else {\n v = (v + s).split('').sort().join('');\n }\n cells[x][y].corner_mark.innerHTML = v;\n }\n }\n\n function set_digit(x, y, s){\n var was_empty = cells[x][y].value.innerHTML === \"\";\n cells[x][y].value.innerHTML = s;\n if(s === \"\"){\n cells[x][y].center_mark.style.visibility = \"visible\";\n cells[x][y].corner_mark.style.visibility = \"visible\";\n if(!was_empty) nb_digits--;\n } else {\n cells[x][y].center_mark.style.visibility = \"hidden\";\n cells[x][y].corner_mark.style.visibility = \"hidden\";\n if(was_empty) nb_digits++;\n }\n }\n\n // Enter digits\n function insert_digit(s){\n for(var x = 0; x < w; x++){\n for(var y = 0; y < h; y++){\n if(selected[x][y] && !given[x][y]){\n if(ctrl_pressed){\n set_center_mark(x, y, s);\n } else if(shift_pressed) {\n set_corner_mark(x, y, s);\n } else {\n set_digit(x, y, s);\n }\n }\n }\n }\n }\n\n function add_cell_handlers(x, y){\n cells[x][y].cell.addEventListener('mousedown', e => {\n if(!ctrl_pressed){\n clear_selection();\n }\n deselecting = selected[x][y];\n selecting = true;\n select_cell(x, y);\n });\n\n cells[x][y].cell.addEventListener('mouseup', e => {\n selecting = false;\n });\n\n cells[x][y].cell.addEventListener('mouseenter', e => {\n if(selecting){\n select_cell(x, y);\n }\n });\n }\n\n for(var x = 0; x < w; x++){\n for(var y = 0; y < h; y++){\n add_cell_handlers(x, y);\n }\n }\n\n // Handle keydown event.\n document.addEventListener('keydown', e => {\n e.preventDefault();\n e.stopPropagation();\n if(e.key == \"Escape\"){\n // Clearing the selection.\n clear_selection();\n } else if(e.code == \"Digit1\"){\n insert_digit(\"1\");\n } else if(e.code == \"Digit2\"){\n insert_digit(\"2\");\n } else if(e.code == \"Digit3\"){\n insert_digit(\"3\");\n } else if(e.code == \"Digit4\"){\n insert_digit(\"4\");\n } else if(e.code == \"Digit5\"){\n insert_digit(\"5\");\n } else if(e.code == \"Digit6\"){\n insert_digit(\"6\");\n } else if(e.code == \"Digit7\"){\n insert_digit(\"7\");\n } else if(e.code == \"Digit8\"){\n insert_digit(\"8\");\n } else if(e.code == \"Digit9\"){\n insert_digit(\"9\");\n } else if(e.key == \"Backspace\" || e.key == \"Delete\"){\n // Clear selection.\n insert_digit(\"\");\n } else if(e.key == \"Control\"){\n // Notify that Control is pressed.\n ctrl_pressed = true;\n } else if(e.key == \"Shift\"){\n // Notify that Shift is pressed.\n shift_pressed = true;\n } else if(e.key == \"ArrowUp\"){\n // Initialize or move (single) selection.\n move_selection(3);\n } else if(e.key == \"ArrowDown\"){\n // Initialize or move (single) selection.\n move_selection(1);\n } else if(e.key == \"ArrowLeft\"){\n // Initialize or move (single) selection.\n move_selection(2);\n } else if(e.key == \"ArrowRight\"){\n // Initialize or move (single) selection.\n move_selection(0);\n }\n });\n\n // Handle keyup event.\n document.addEventListener('keyup', e => {\n e.preventDefault();\n e.stopPropagation();\n if(e.key == \"Control\"){\n // Notify that Control is not pressed any more.\n ctrl_pressed = false;\n } else if(e.key == \"Shift\"){\n // Notify that Shift is not pressed any more.\n shift_pressed = false;\n }\n });\n\n return retval;\n}", "function repaint(){\n\tvar onDisplay = document.getElementById('stateFlag').state,\n\t\tkey, \n\t\tscaleConstant = regionScale(window.region);\n\n\t//repaint full experiment view\n\tif(onDisplay == 0){\n\t\tgenerateDygraph('duringPlot', generateFullProfileCSV(), 'Peak Activity During Experiment', 'Time ['+window.cycleParameters.durationUnit+']', ' '+window.cycleParameters.durationUnit);\n\t//repaint first 3 cycles\n\t} else if(onDisplay == 1){\n\t\tgenerateDygraph('cyclePlot', generateFirst3CyclesCSV(), 'Activity Over First Three Cycles', 'Time ['+window.cycleParameters.cycleUnit+']', ' '+window.cycleParameters.cycleUnit);\n\t//repaint last 3 cycles\n\t}else if(onDisplay == 2){\n\t\tgenerateDygraph('lastCyclesPlot', generateLast3CyclesCSV(), 'Activity Over Last Three Cycles', 'Time ['+window.cycleParameters.cycleUnit+']', ' '+window.cycleParameters.cycleUnit);\n\t//repaint post-experiment decay\n\t} else if(onDisplay == 3){\t\t\n\t\tgenerateDygraph('afterPlot', generatePostExptCSV(), 'Activity After Experiment', 'Time [h]', ' hours');\n\t}\n}", "function resolveMaze(){\n tryMaze(positionFixe);\n traceRoad(chemin_parcouru,\"color2\");\n traceRoad(tabVisite);\n\n}", "function redrawCurStep() {\r\n\r\n\r\n var fO = CurFuncObj;\r\n var sO = CurStepObj;\r\n\r\n // for all grid objects in sO (stepObject)\r\n //\r\n for (var id = 0; id < sO.allGridIds.length; id++) {\r\n\r\n var htmlId = AllHtmlGridIds[id];\r\n var gO = fO.allGrids[sO.allGridIds[id]];\r\n var iO = sO.allIndObjs[id];\r\n\r\n CurHtmlGridId = htmlId;\r\n\r\n drawGrid(gO, iO, htmlId, false);\r\n }\r\n\r\n\r\n // Finally redraw code window\r\n //\r\n drawCodeWindow(sO);\r\n\r\n}", "function drawGrid(cw, ch){\n /*\n Draw the grid. \n */\n var v = 36;\n ctx.globalAlpha = 0.5;\n ctx.lineWidth=1;\n ctx.strokeStyle='blue';\n ctx.setLineDash([5, 15]);\n for( var i=0; i<cw/100; i++){\n drawLine( i * 100, 0+v, i*100, ch+v); ctx.stroke();\n }\n for(var j=0; j<ch/100; j++){\n drawLine(0, j*100+v, cw, j*100+v); ctx.stroke();\n }\n \n /* Randomly initialize puzzle piece elements on the grid (for now).. \n\tChange this later.. \n */\n if( progIter<1){\n for( var i =0; i<=cw/100; i++){\n for(var j=0; j<=ch/100; j++){\n var cI = i.toString()+'-'+j.toString();\n if( cI in gridContent){\n\t\t\t\t//pass\n }else{\n\t\t\t\tif( Math.random()<.4){////if( i%3==0 || j%==0){\n\t\t\t\t\tgridContent[cI]=(nextPuzzlePieceName++);\n\t\t\t\t}else{\n\t\t\t\t\tgridContent[cI]=-1;\n\t\t\t\t}\n }\n }\n }\n }\n ctx.globalAlpha = 1.;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolve input port from requested property.
function resolveInputPort(property, value) { return resolvePort('input', property, value); }
[ "function resolvePort(type, property, value) {\n var availablePorts = type === 'output' ? outputPorts : inputPorts,\n length = availablePorts.length,\n resolvedPorts = [],\n i;\n\n // Go through each port and compare property.\n for (i = 0; i < length; i++) {\n // Check if port has the property and if it matches the request.\n if (availablePorts[i].hasOwnProperty(property) && availablePorts[i][property] === value) {\n resolvedPorts.push(availablePorts[i]);\n }\n }\n\n // Return resolved ports.\n return resolvedPorts;\n}", "function resolvePort(type, property, value) {\n var availablePorts = (type === 'output' ? outputs() : inputs()),\n resolvedPorts = [];\n\n // Go through each port and compare property.\n for (var i = 0; i < availablePorts.length; i++) {\n // Check if port has the property and if it matches the request.\n if (availablePorts[i].hasOwnProperty(property) && availablePorts[i][property] === value) {\n resolvedPorts.push(availablePorts[i]);\n }\n }\n\n // Return resolved ports.\n return resolvedPorts;\n}", "function resolveOutputPort(property, value) {\n return resolvePort('output', property, value);\n}", "function cfnRouteTcpRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_TcpRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Port: cdk.numberToCloudFormation(properties.port),\n };\n}", "function findTargetPort(_x, _x2) {\n var _again = true;\n\n _function: while (_again) {\n var hostname = _x,\n port = _x2;\n route = wildcard = undefined;\n _again = false;\n\n var route = routing.get(hostname);\n if (route) return route[port];\n\n // This will first expand www.hostname.com to *.www.hostname.com,\n // then contract it to *.hostname.com, *.com and finally *.\n var wildcard = hostname.replace(/^(\\*\\.[^.]+(\\.|$))?/, '*.');\n if (wildcard !== '*.') {\n _x = wildcard;\n _x2 = port;\n _again = true;\n continue _function;\n }\n }\n}", "selectInputSourceMxport() {\n this._selectInputSource(\"i_mxport\");\n }", "function CfnVirtualNode_PortMappingPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('port', cdk.requiredValidator)(properties.port));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('protocol', cdk.requiredValidator)(properties.protocol));\n errors.collect(cdk.propertyValidator('protocol', cdk.validateString)(properties.protocol));\n return errors.wrap('supplied properties not correct for \"PortMappingProperty\"');\n}", "function CfnVirtualRouter_PortMappingPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('port', cdk.requiredValidator)(properties.port));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('protocol', cdk.requiredValidator)(properties.protocol));\n errors.collect(cdk.propertyValidator('protocol', cdk.validateString)(properties.protocol));\n return errors.wrap('supplied properties not correct for \"PortMappingProperty\"');\n}", "function getAddrFromInput(input) {\n if (! hasProperty(input, 'name'))\n throw \"Input does not have 'name' property\";\n\n var inputData = input.name.split('_');\n\n if (inputData.length < 1)\n throw \"Invalid input format\";\n\n return inputData[0];\n}", "function cfnVirtualNodePortMappingPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_PortMappingPropertyValidator(properties).assertSuccess();\n return {\n Port: cdk.numberToCloudFormation(properties.port),\n Protocol: cdk.stringToCloudFormation(properties.protocol),\n };\n}", "function cfnVirtualRouterPortMappingPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualRouter_PortMappingPropertyValidator(properties).assertSuccess();\n return {\n Port: cdk.numberToCloudFormation(properties.port),\n Protocol: cdk.stringToCloudFormation(properties.protocol),\n };\n}", "function parseOnePortRule(rule){\n if (validRule(rule)==false ) {\n return \"err\";\n }\n\n rule = rule.split(\"\\x02\");\n\n //------------SOURCE PORT-----------------------\n rule[_src] = rule[_src].split(\"+\"); //tcp+udp\n if(isArray(rule[_src])){\n if(rule[_src].length == 2){\n rule[_src][_TCP] = rule[_src][_TCP].split(\",\"); //TCP\n rule[_src][_UDP] = rule[_src][_UDP].split(\",\"); //UDP\n }else{\n alert(\"1 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'\");\n }\n }else{\n alert(\"2 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'; is not an array??\");return \"err\";\n }\n //------------DESTINATION PORT-----------------------\n rule[_dst] = rule[_dst].split(\"+\"); //tcp+udp\n if(isArray(rule[_dst])){\n if(rule[_dst].length == 2){\n rule[_dst][_TCP] = rule[_dst][_TCP].split(\",\"); //TCP\n rule[_dst][_UDP] = rule[_dst][_UDP].split(\",\"); //UDP\n }else{\n alert(\"1 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'\");return \"err\";\n }\n }else{\n alert(\"2 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'; is not an array??\");return \"err\";\n }\n return rule;\n}", "function getPort(browser) {\n return parseInt(/(?<=:)\\d{1,5}(?=\\/)/.exec(browser.wsEndpoint())[0]);\n}", "function update()\n{\n //set the ouput port to the value of the input port\n outResult.set(inVal.get());\n}", "function cfnVirtualGatewayVirtualGatewayPortMappingPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayPortMappingPropertyValidator(properties).assertSuccess();\n return {\n Port: cdk.numberToCloudFormation(properties.port),\n Protocol: cdk.stringToCloudFormation(properties.protocol),\n };\n}", "function CfnVirtualGateway_VirtualGatewayPortMappingPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('port', cdk.requiredValidator)(properties.port));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('protocol', cdk.requiredValidator)(properties.protocol));\n errors.collect(cdk.propertyValidator('protocol', cdk.validateString)(properties.protocol));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayPortMappingProperty\"');\n}", "function CfnRoute_TcpRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n return errors.wrap('supplied properties not correct for \"TcpRouteMatchProperty\"');\n}", "function findFreePort(beg, ...rest){\n const p = rest.slice(0, rest.length - 1), cb = rest[rest.length - 1];\n let [end, ip, cnt] = Array.from(p);\n let exclude = p.find(arg => Array.isArray(arg) || (arg instanceof Set));\n console.log (p);\n if (!exclude) {\n console.log ('exclude not found');\n } else {\n console.log ('exclude found');\n }\n if (Array.isArray(exclude)) exclude = new Set(exclude);\n if (typeof ip !== 'string') ip = null;\n if (typeof cnt !== 'string' && typeof cnt !== 'number') cnt = null;\n if (typeof end !== 'string' && typeof end !== 'number') end = null;\n if (!ip && end && !/^\\d+$/.test(end)) { // deal with method 3\n ip = end;\n end = 65534;\n } else {\n if (end == null) { end = 65534; }\n }\n if (cnt == null) { cnt = 1; }\n\n const retcb = cb;\n const res = [];\n const getNextPort = function (port) {\n if (exclude) {\n console.log ('exclude', exclude);\n let nextPort = port + 1;\n console.log(nextPort);\n while(nextPort < end && exclude.has(nextPort)) {\n console.log(nextPort);\n nextPort++;\n }\n return nextPort;\n } else {\n return port + 1;\n }\n };\n const probe = function(ip, port, cb){\n const s = net.createConnection({port: port, host: ip})\n s.on('connect', function(){ s.end(); cb(null, getNextPort(port)); });\n s.on('error', err=> { cb(port); }); // can't connect, port is available\n };\n var onprobe = function(port, nextPort){\n if (port) {\n res.push(port);\n if (res.length >= cnt) {\n retcb(null, ...res)\n } else {\n setImmediate(()=> probe(ip, getNextPort(port), onprobe));\n }\n } else {\n if (nextPort>=end) {\n retcb(new Error(\"No available ports\"));\n } else {\n setImmediate(()=> probe(ip, nextPort, onprobe));\n }\n }\n };\n return probe(ip, beg, onprobe);\n}", "function processUrl (inputUrl, port) {\n const parsedUrl = url.parse(inputUrl)\n\n if (parsedUrl.host === TEST_HOSTNAME &&\n parsedUrl.port === TEST_PORT) {\n const path = url.format({\n protocol: 'http',\n hostname: 'localhost',\n port,\n pathname: parsedUrl.pathname,\n search: parsedUrl.search\n })\n return path\n }\n\n return inputUrl\n}", "function\nexplode_port_range(rng)\n{\n\tvar pos = 0;\n\tvar state = 'REST';\n\tvar stack_unit = null;\n\tvar accum = '';\n\tvar out = [];\n\tvar lower = null;\n\n\tvar commit_port = function (name) {\n\t\tvar upto = parseInt(name, 10);\n\t\tvar from = lower === null ? upto : lower;\n\n\t\tfor (var i = from; i <= upto; i++) {\n\t\t\tvar full = '' + i;\n\n\t\t\tif (stack_unit !== null)\n\t\t\t\tfull = stack_unit + '/' + full;\n\n\t\t\tarray_set(out, full, true);\n\t\t}\n\n\t\tlower = null;\n\t};\n\n\tfor (;;) {\n\t\tvar c = rng[pos++];\n\n\t\tswitch (state) {\n\t\tcase 'REST':\n\t\t\tif (c !== undefined && isdigit(c)) {\n\t\t\t\taccum += c;\n\t\t\t\tstate = 'BASIC';\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Currently we treat the empty string as an error.\n\t\t\t */\n\t\t\treturn (null);\n\n\t\t/*\n\t\t * Handle a basic port number; i.e., no stack unit, no\n\t\t * ranges (a-b); e.g., \"24\".\n\t\t */\n\t\tcase 'BASIC':\n\t\t\tif (isdigit(c)) {\n\t\t\t\taccum += c;\n\t\t\t\tcontinue;\n\n\t\t\t} else if (c === '/') {\n\t\t\t\t/*\n\t\t\t\t * It doesn't make sense to change the\n\t\t\t\t * stack-unit value if we're defining a port\n\t\t\t\t * range. For example, it doesn't seem to\n\t\t\t\t * make sense to have \"1/31-2/33\".\n\t\t\t\t */\n\t\t\t\tif (lower !== null) {\n\t\t\t\t\treturn (null);\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Store the stack-unit value (which sticks\n\t\t\t\t * to subsequent port numbers and ranges,\n\t\t\t\t * until explicitly set to a different value).\n\t\t\t\t */\n\t\t\t\tstack_unit = accum;\n\t\t\t\taccum = '';\n\t\t\t\tcontinue;\n\n\t\t\t} else if (c === '-') {\n\t\t\t\tif (lower !== null) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Nonsensical; e.g., \"1-2-3\".\n\t\t\t\t\t */\n\t\t\t\t\treturn (null);\n\t\t\t\t}\n\n\t\t\t\tlower = parseInt(accum, 10);\n\t\t\t\taccum = '';\n\t\t\t\tcontinue;\n\n\t\t\t} else if (c === undefined) {\n\t\t\t\tcommit_port(accum);\n\t\t\t\treturn (out);\n\n\t\t\t} else if (c === ',') {\n\t\t\t\t/*\n\t\t\t\t * Commit this basic entry and start again\n\t\t\t\t * with the next entry after the comma.\n\t\t\t\t */\n\t\t\t\tcommit_port(accum);\n\t\t\t\taccum = '';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn (null);\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse N in type[] where "type" can itself be an array type.
function parseTypeArray (type) { var tmp = type.match(/(.*)\[(.*?)\]$/) if (tmp) { return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10) } return null }
[ "function parseTypeExpressionList() {\n var elements = [];\n elements.push(parseTop());\n\n while (token === Token.COMMA) {\n consume(Token.COMMA);\n elements.push(parseTop());\n }\n\n return elements;\n } // TypeName :=", "consoleParseTypes(input) { return Parser.parse(input, { startRule: 'TYPES' }); }", "function getNumberArraysFromString(string) {\r\n\t let array = [];\r\n\t let re = /\\[(.*?)(?=\\])/g;\r\n\t let matches;\r\n\t do {\r\n\t matches = re.exec(string);\r\n\t if(matches)\r\n\t array.push(matches[1].split(',').map(Number));\r\n\t } while (matches);\r\n\t\r\n\t return array;\r\n\t}", "function dataTypeSeer(array) {\n\tfor (var i = 0; i < array.length; i++) {\n\t\tconsole.log(typeof array[i]);\n\t};\n}", "consoleParsePtypes(input) { return Parser.parse(input, { startRule: 'PTYPES' }); }", "static get parseOptionTypes() {\n return {\n ...super.parseOptionTypes,\n ext: 'Array',\n };\n }", "castToNumArray(value) {\n if (typeof value === 'number') {\n return [value];\n }\n if (typeof value === 'string') {\n return value.split(',').map((one) => Number(one));\n }\n if (Array.isArray(value)) {\n return value.map((prop) => Number(prop));\n }\n return undefined;\n }", "parse(array = [[0, 0]]) {\n var points = []; // if it is an array\n\n if (array instanceof Array) {\n // and it is not flat, there is no need to parse it\n if (array[0] instanceof Array) {\n return array;\n }\n } else {\n // Else, it is considered as a string\n // parse points\n array = array.trim().split(delimiter).map(parseFloat);\n } // validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints\n // Odd number of coordinates is an error. In such cases, drop the last odd coordinate.\n\n\n if (array.length % 2 !== 0) array.pop(); // wrap points in two-tuples\n\n for (var i = 0, len = array.length; i < len; i = i + 2) {\n points.push([array[i], array[i + 1]]);\n }\n\n return points;\n }", "function logArrTypes(num){\n console.log(typeof(num) + \" \" + num)\n}", "static parseTypesFromDexPage(html, typeList) {\n const typeImgs = html.find('.dexdetails>li>img');\n const typeUrls = typeImgs.map((idx, img) => {\n return img.src;\n });\n let types = typeUrls.map((idx, url) =>\n url.substring(url.indexOf('types/')+'types/'.length,\n url.indexOf('.png')));\n types = types.map((idx, type) => type.charAt(0).toUpperCase() + type.substring(1));\n types = types.map((idx, type) => typeList.indexOf(type)); // GLOBALS.TYPE_LIST.indexOf(type));\n return types.toArray();\n }", "function changeTypes(arr) {\n\tconst a = [];\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif(typeof arr[i] === \"number\") (arr[i] % 2 === 0) ? a.push(arr[i] + 1) : a.push(arr[i]);\n\t\tif (typeof arr[i] === \"string\") a.push(arr[i].slice(0, 1).toUpperCase() + arr[i].slice(1) + \"!\");\n\t\tif (typeof arr[i] === \"boolean\") (!arr[i]) ? a.push(true) : a.push(false);\t\n\t}\n\treturn a;\n}", "castToArray(value) {\n if (typeof value === 'number') {\n value = String(value);\n }\n if (typeof value === 'string') {\n return value.split(',').filter((prop) => prop.trim());\n }\n if (Array.isArray(value)) {\n /**\n * This will also convert numeric values to a string. The behavior\n * is same as string flag type.\n */\n return value.map((prop) => String(prop));\n }\n return undefined;\n }", "function sumProperty(arr, type) {\n return arr.reduce((total, obj) => {\n if (typeof obj[type] === \"string\") {\n return total + Number(obj[type]);\n }\n return total + obj[type];\n }, 0);\n}", "function countOfNumStr(arr) {\n const num = arr.filter(item => typeof (item) === \"number\").length;\n const str = arr.filter(item => typeof (item) === \"string\").length;\n console.log(`Numbers: ${num}, String: ${str}`);\n}", "function array (date) {\n return date.split(/\\s+/).map(function (e) { return parseInt(e, 10) });\n}", "function parseTransformArray(model) {\n var first = null;\n var node;\n var previous;\n var lookupCounter = 0;\n function insert(newNode) {\n if (!first) {\n // A parent may be inserted during node construction\n // (e.g., selection FilterNodes may add a TimeUnitNode).\n first = newNode.parent || newNode;\n }\n else if (newNode.parent) {\n previous.insertAsParentOf(newNode);\n }\n else {\n newNode.parent = previous;\n }\n previous = newNode;\n }\n model.transforms.forEach(function (t) {\n if (transform_1.isCalculate(t)) {\n node = new calculate_1.CalculateNode(t);\n }\n else if (transform_1.isFilter(t)) {\n // Automatically add a parse node for filters with filter objects\n var parse = {};\n var filter = t.filter;\n var val = null;\n // For EqualFilter, just use the equal property.\n // For RangeFilter and OneOfFilter, all array members should have\n // the same type, so we only use the first one.\n if (predicate_1.isFieldEqualPredicate(filter)) {\n val = filter.equal;\n }\n else if (predicate_1.isFieldRangePredicate(filter)) {\n val = filter.range[0];\n }\n else if (predicate_1.isFieldOneOfPredicate(filter)) {\n val = (filter.oneOf || filter['in'])[0];\n } // else -- for filter expression, we can't infer anything\n if (val) {\n if (datetime_1.isDateTime(val)) {\n parse[filter['field']] = 'date';\n }\n else if (vega_util_1.isNumber(val)) {\n parse[filter['field']] = 'number';\n }\n else if (vega_util_1.isString(val)) {\n parse[filter['field']] = 'string';\n }\n }\n if (util_1.keys(parse).length > 0) {\n var parseNode = new formatparse_1.ParseNode(parse);\n insert(parseNode);\n }\n node = new filter_1.FilterNode(model, t.filter);\n }\n else if (transform_1.isBin(t)) {\n node = bin_1.BinNode.makeFromTransform(t, model);\n }\n else if (transform_1.isTimeUnit(t)) {\n node = timeunit_1.TimeUnitNode.makeFromTransform(t);\n }\n else if (transform_1.isAggregate(t)) {\n node = aggregate_1.AggregateNode.makeFromTransform(t);\n if (selection_1.requiresSelectionId(model)) {\n insert(node);\n node = new indentifier_1.IdentifierNode();\n }\n }\n else if (transform_1.isLookup(t)) {\n node = lookup_1.LookupNode.make(model, t, lookupCounter++);\n }\n else {\n log.warn(log.message.invalidTransformIgnored(t));\n return;\n }\n insert(node);\n });\n var last = node;\n return { first: first, last: last };\n}", "function arr_type (v) {\n if (Buffer.isBuffer(v)) {\n return 'buf'\n } else if (Array.isArray(v)) {\n return 'arr'\n } else if (ArrayBuffer.isView(v)) {\n return 'view'\n } else {\n return null\n }\n}", "convertArray (array, Type) {\n const Type0 = array.constructor\n // return array if already same Type\n if (Type0 === Type) return array\n // If Type is Array, convert via typedArrayToArray\n if (Type === Array) return this.typedArrayToArray(array)\n return new Type(array) // Use standard TypedArray constructor\n }", "function intArrayFromString(stringy, dontAddNull, length /* optional */) {\n\tvar ret = (new Runtime.UTF8Processor()).processJSString(stringy);\n\tif (length) {\n\t\tret.length = length;\n\t}\n\tif (!dontAddNull) {\n\t\tret.push(0);\n\t}\n\treturn ret;\n}", "function normalizeParameter(array) {\n switch (array.length) {\n case 1:\n return ['', array[0], '', 1];\n case 2:\n return ['', array[0], '', array[1]];\n case 3:\n return [array[0], array[1], array[2], 1];\n case 4:\n return array;\n default:\n throw new Error('wrong length for parameter description');\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return all triples about the given uri and its affiliated objects, stops at objects of the given type, or at the given predicates
recursiveFindAllTriples(uri, type, predicates) { //find all triples for given uri let triples = this.store.getTriplesByIRI(uri, null, null); if (predicates) { triples = triples.filter(t => predicates.indexOf(t.predicate) < 0); } if (type) { triples = triples.filter(t => this.store.getTriplesByIRI(t.object, uris_1.TYPE, type).length == 0); } let subTriples = _.flatMap(triples, t => this.recursiveFindAllTriples(t.object, type, predicates)); return triples.concat(subTriples); }
[ "function discoverTypes () {\n // rdf:type properties of subjects, indexed by URI for the type.\n\n const types = {}\n\n // Get a list of statements that match: ? rdfs:type ?\n // From this we can get a list of subjects and types.\n\n const subjectList = kb.statementsMatching(\n undefined,\n UI.ns.rdf('type'),\n tableClass, // can be undefined OR\n sourceDocument\n ) // can be undefined\n\n // Subjects for later lookup. This is a mapping of type URIs to\n // lists of subjects (it is necessary to record the type of\n // a subject).\n\n const subjects = {}\n\n for (let i = 0; i < subjectList.length; ++i) {\n const type = subjectList[i].object\n\n if (type.termType !== 'NamedNode') {\n // @@ no bnodes?\n continue\n }\n\n const typeObj = getTypeForObject(types, type)\n\n if (!(type.uri in subjects)) {\n subjects[type.uri] = []\n }\n\n subjects[type.uri].push(subjectList[i].subject)\n typeObj.addUse()\n }\n\n return [subjects, types]\n }", "getPredicates(subject, object, graph) {\n const results = [];\n this.forPredicates(p => {\n results.push(p);\n }, subject, object, graph);\n return results;\n }", "hasTriples(subject, predicate, object) {\n throw new Error('hasTriples has not been implemented');\n }", "function createTriple(subject, predicate, object, context) {\n var triple = {\n subject: { value: subject, type: subject[0] !== '_' ? 'IRI' : 'blank node' },\n predicate: { value: predicate, type: predicate[0] !== '_' ? 'IRI' : 'blank node' },\n object: !N3Util.isLiteral(object) ?\n { value: object, type: object[0] !== '_' ? 'IRI' : 'blank node' } :\n { value: N3Util.getLiteralValue(object),\n datatype: N3Util.getLiteralType(object),\n language: N3Util.getLiteralLanguage(object) },\n };\n if (context && this._patternFields.indexOf('context') >= 0) {\n triple = { 'graph': context, 'triple': triple };\n }\n return triple;\n}", "function createFilterUrls()\n\t{\n\t\t$('.fltr-wrapper .fltr-check').each(function(){\n\t\t\tvar elem = $(this);\n\t\t\tvar getQuery = window.location.search.substring(1);\n\t\t\tvar category = elem.parent().data('property');\n\t\t\tif (!elem.hasClass('active')) {\n\t\t\t\tvar filterGetParameter = $.query.set('filter', '1').SET(category+'[]', elem.attr('value')).toString();\n\t\t\t} else {\n\t\t\t\tvar filterGetParameter = $.query.remove(category, elem.attr('value'));\n\t\t\t}\n\t\t\t$(this).attr('href', filterGetParameter);\n\t\t});\n\t}", "function extractPaths(items, pp_length_limit, paths){ \n for( var i = 0; i < items.length; i++ ){\n if( items[i].locked || items[i].hidden ){\n continue;\n } else if( items[i].typename == \"PathItem\"){\n // ignore guides and clipping paths\n if ((pp_length_limit && items[i].pathPoints.length <= pp_length_limit)\n || items[i].guides || items[i].clipping ){\n continue;\n }\n paths.push( items[i] );\n \n } else if( items[i].typename == \"GroupItem\" ){\n // search PathItems in the GroupItem, recursively\n extractPaths( items[i].pageItems, pp_length_limit, paths );\n \n } else if( items[i].typename == \"CompoundPathItem\" ){\n // search Pathitems in the CompoundPathItem, recursively\n // ( ### Grouped PathItems in CompoundPathItem are ignored ### )\n extractPaths( items[i].pathItems, pp_length_limit , paths );\n }\n }\n }", "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 }", "function getRelationships(newSchema){\n\n\tvar newRelationships = [];\n\n\t// first match 1:n relationships\n\t_.each(newSchema, function(r){\n\t\t_.each(r.fields, function(valueOne, keyOne){\n\t\t\tif (valueOne.object){ // 1:n, 1 side, seek n side\n\t\t\t\tvar nSideRelation = _.findWhere(newSchema, { name: valueOne.object });\n\t\t\t\tvar nSideAttribute = null;\n\t\t\t\t_.each(nSideRelation.fields, function(value, key){\n\t\t\t\t\tif (keyOne == value.via && value.collection == r.name){\n\t\t\t\t\t\tvar isCascade = (_.has(value, \"cascade\") && value.cascade) || !_.has(value, \"cascade\");\n\t\t\t\t\t\tnewRelationships.push({ type: \"1:n\", oneRelation: r.name, nRelation: nSideRelation.name, oneAttribute: keyOne, nAttribute: key, isCascade: isCascade });\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t});\n\n\t// match n:n relationships\n\t_.each(newSchema, function(r){\n\t\t_.each(r.fields, function(valueN, keyN){\n\t\t\tif (_.has(valueN, \"collection\")){ // 1:n or n:n, n side, seek other side\n\t\t\t\tvar otherSide = _.findWhere(newRelationships, { nRelation: r.name, nAttribute: keyN });\n\t\t\t\tif (!otherSide){\n\t\t\t\t\totherSide = _.findWhere(newRelationships, { mRelation: r.name, mAttribute: keyN });\n\t\t\t\t}\n\t\t\t\tif (!otherSide){ // other side not created yet. because all 1:n already matched, it is n:n\n\t\t\t\t\tnewRelationships.push({ type: \"n:n\", mRelation: r.name, nRelation: valueN.collection, mAttribute: keyN, nAttribute: valueN.via });\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n\t// console.log(\"getRelationships\", newRelationships);\n\treturn newRelationships;\n}", "_addProperties(node, properties, labels, propMaker) {\n let tag = \"/\";\n for (let label of [...labels].sort()) {\n if (tag !== \"/\") tag += \"-\";\n tag += label;\n }\n\n for (let property in properties) {\n // Predicate\n let propertyNode = propMaker[property + tag];\n this._labelize(propertyNode, property);\n this._addQuad(propertyNode, rdf.type, prec.Property);\n this._addQuad(propertyNode, rdf.type, prec.CreatedProperty);\n this._addQuad(prec.CreatedProperty, rdfs.subClassOf, prec.CreatedVocabulary);\n\n // Object\n if (!Array.isArray(properties[property])) {\n let nodeValue = this._makeNodeForPropertyValue(properties[property]);\n this._addQuad(node, propertyNode, nodeValue);\n } else {\n let listHead = this._makeNodeForPropertyValues(properties[property]);\n this._addQuad(node, propertyNode, listHead);\n }\n }\n }", "*readQuads(subject, predicate, object, graph) {\n // Convert terms to internal string representation\n subject = subject && (0,N3DataFactory/* termToId */.dW)(subject);\n predicate = predicate && (0,N3DataFactory/* termToId */.dW)(predicate);\n object = object && (0,N3DataFactory/* termToId */.dW)(object);\n graph = graph && (0,N3DataFactory/* termToId */.dW)(graph);\n\n const graphs = this._getGraphs(graph), ids = this._ids;\n let content, subjectId, predicateId, objectId;\n\n // Translate IRIs to internal index keys.\n if (isString(subject) && !(subjectId = ids[subject]) ||\n isString(predicate) && !(predicateId = ids[predicate]) ||\n isString(object) && !(objectId = ids[object]))\n return;\n\n for (const graphId in graphs) {\n // Only if the specified graph contains triples, there can be results\n if (content = graphs[graphId]) {\n // Choose the optimal index, based on what fields are present\n if (subjectId) {\n if (objectId)\n // If subject and object are given, the object index will be the fastest\n yield* this._findInIndex(content.objects, objectId, subjectId, predicateId,\n 'object', 'subject', 'predicate', graphId);\n else\n // If only subject and possibly predicate are given, the subject index will be the fastest\n yield* this._findInIndex(content.subjects, subjectId, predicateId, null,\n 'subject', 'predicate', 'object', graphId);\n }\n else if (predicateId)\n // If only predicate and possibly object are given, the predicate index will be the fastest\n yield* this._findInIndex(content.predicates, predicateId, objectId, null,\n 'predicate', 'object', 'subject', graphId);\n else if (objectId)\n // If only object is given, the object index will be the fastest\n yield* this._findInIndex(content.objects, objectId, null, null,\n 'object', 'subject', 'predicate', graphId);\n else\n // If nothing is given, iterate subjects and predicates first\n yield* this._findInIndex(content.subjects, null, null, null,\n 'subject', 'predicate', 'object', graphId);\n }\n }\n }", "function filter_object(data,pcoa_switch){\r\n var returnDictionary = {};\r\n\r\n //debugging command\r\n returnDictionary[\"select_category\"] = function(selector){\r\n console.log(data[\"metadataOverview\"][selector])\r\n }\r\n // given a metadata category and a fitting criterion generate a list of IDs\r\n // which fits to the given filter criterions\r\n returnDictionary[\"generic_filter\"] = function(category,filter_criterion){\r\n filtered_samples = []\r\n switch (category) {\r\n\r\n case \"Age\":\r\n if(filter_criterion === \"all\"){\r\n filtered_samples = data[\"metadataOverview\"]\r\n }\r\n else{\r\n for (i = 0; i < data[\"metadataOverview\"].length; i++){\r\n if(data[\"metadataOverview\"][i][category] >= filter_criterion[0] && data[\"metadataOverview\"][i][category] <= filter_criterion[1]){\r\n filtered_samples.push(data[\"metadataOverview\"][i])\r\n }\r\n }\r\n }\r\n break;\r\n\r\n case \"Sex\":\r\n case \"Nationality\":\r\n case \"BMI_group\":\r\n if(filter_criterion === \"all\"){\r\n filtered_samples = data[\"metadataOverview\"]\r\n }\r\n else{\r\n for (i = 0; i < data[\"metadataOverview\"].length; i++){\r\n if(data[\"metadataOverview\"][i][category] === filter_criterion){\r\n filtered_samples.push(data[\"metadataOverview\"][i])\r\n }\r\n }\r\n }\r\n break;\r\n default:\r\n console.log(\"ERROR WRONG CATEGORY\")\r\n }\r\n return filtered_samples\r\n }\r\n //calculate the intersection of all Id-lists which are contained in the\r\n // id-array\r\n returnDictionary[\"intersection\"] = function(id_array){\r\n var internal_array = id_array\r\n while(internal_array.length > 1){\r\n internal_array[internal_array.length-2] = internal_array[internal_array.length-1].filter(\r\n a => internal_array[internal_array.length-2].some( b => a.SampleID === b.SampleID ) );\r\n internal_array.pop()\r\n }\r\n return internal_array[0]\r\n\r\n }\r\n // as the data-structur is different for the PCoA to different functions\r\n // are used for the dataset Filtering\r\n\r\n if(pcoa_switch){\r\n\r\n //generates an object which contains the filtered dataset for use with the\r\n // pcoa functions\r\n returnDictionary[\"filter_data\"] = function(sample_ids){\r\n var sample_ids = sample_ids;\r\n var data_internal = data[\"dataExploration\"];\r\n var object_internal = {\"dataExploration\":data[\"dataExploration\"],\r\n \"PCsPercentage\":data[\"PCsPercentage\"],\r\n \"metadataOverview\":data[\"metadataOverview\"]};\r\n var out_obj = {}\r\n //out_array = out_array.filter(row => sample_ids.includes(row[\"\"]))\r\n\r\n sample_ids.forEach(function(elem){\r\n out_obj[elem] = data_internal[elem]\r\n }\r\n )\r\n object_internal[\"dataExploration\"] = out_obj\r\n return object_internal\r\n }\r\n }\r\n\r\n else{\r\n // returns the dataExploration dataset filtered for the sample_ids\r\n returnDictionary[\"filter_data\"] = function(sample_ids,bool_arr){\r\n var sample_ids = sample_ids;\r\n var data_internal = data[\"dataExploration\"];\r\n var out_array = []\r\n\r\n\r\n sample_ids.forEach(function(elem){\r\n for(var i = 0; i < data_internal.length; i++){\r\n if(data_internal[i][\"\"] === elem){\r\n out_array.push(filter_from_object(data_internal[i], bool_arr))\r\n break;\r\n }\r\n }\r\n })\r\n\r\n return out_array\r\n }\r\n }\r\n\r\n // returns the metadataOverview dataset filtered for the sampleIds\r\n returnDictionary[\"filter_metadata\"] = function(sample_ids){\r\n var sample_ids = sample_ids;\r\n var metadata_internal = data[\"metadataOverview\"];\r\n var out_array = []\r\n sample_ids.forEach(function(elem){\r\n for(var i = 0; i < metadata_internal.length; i++){\r\n if(metadata_internal[i][\"SampleID\"] === elem){\r\n out_array.push(metadata_internal[i])\r\n break;\r\n }\r\n }\r\n })\r\n\r\n return out_array\r\n }\r\n return returnDictionary\r\n }", "function searchByType ( type ) {\n if (checkType(type)) {\n\t\t// this is a valid type\n return rp( {\n url: 'http://www.thecocktaildb.com/api/json/v1/1/filter.php?c=' + type,\n json: true\n }).then(function (res) {\n return res.drinks;\n }, function (err) {\n return err;\n });\n } else {\n return Promise.resolve(false);\n }\n}", "function divideFeaturesByType(shapes, properties, types) {\n var typeSet = utils.uniq(types);\n var layers = typeSet.map(function(geoType) {\n var p = [],\n s = [],\n dataNulls = 0,\n rec;\n\n for (var i=0, n=shapes.length; i<n; i++) {\n if (types[i] != geoType) continue;\n if (geoType) s.push(shapes[i]);\n rec = properties[i];\n p.push(rec);\n if (!rec) dataNulls++;\n }\n return {\n geometry_type: geoType,\n shapes: s,\n data: dataNulls < p.length ? new DataTable(p) : null\n };\n });\n return layers;\n}", "function typeOfFilms(data){\n var typeslinks = $('.list', data).children('tbody').children('tr').children('td').children('ul').children('li').children('a');\n typeslinks.each(function(i){\n if (i < 5){\n var type = '<a href=\"http://www.kinopoisk.ru' + $(this).attr('href') + \n '\" target=\"_blank\">' + $(this).text() + '</a>';\n $('#searchfirst').append(type + '</br>');\n }\n if (i > 5 && i < 11){\n var type = '<a href=\"http://www.kinopoisk.ru' + $(this).attr('href') + \n '\" target=\"_blank\">' + $(this).text() + '</a>';\n $('#searchsecond').append(type + '</br>');\n }\n if (i > 11 && i < 17){\n var type = '<a href=\"http://www.kinopoisk.ru' + $(this).attr('href') + \n '\" target=\"_blank\">' + $(this).text() + '</a>';\n $('#searchthird').append(type + '</br>');\n }\n });\n}", "function filterFinalDataByType() {\n\n filterString = \"\";\n filteredFinalData = [];\n for(i = 0; i < localFinalData.length; i++) {\n\n let t = localFinalData[i];\n\n if (filterType == \"users\" && t.is_user == false)\n continue;\n\n if (filterType == \"groups\" && t.is_user == true)\n continue;\n\n filteredFinalData.push(t);\n\n }\n\n }", "function filterLinksByType(group) {\n if (selectedItem) {\n unselectItem();\n }\n if (d3.event) {\n d3.event.stopPropagation();\n }\n graph.links = graph.links.filter(function (l) {\n return !(l.source.group === group && l.target.group === group);\n });\n directConnections = {};\n graph.links.forEach(function (d) {\n directConnections[d.source.id + \",\" + d.target.id] = 1;\n });\n link = link.data(graph.links, function (d) {\n return d.source.id + \"-\" + d.target.id;\n });\n link.exit().remove();\n link = link.enter().append(\"line\").merge(link);\n simulation.force(\"link\").links(graph.links);\n simulation.alpha(1).restart();\n }", "function extractPaths(s, pp_length_limit, paths){\n for(var i = 0; i < s.length; i++){\n if(s[i].locked || s[i].hidden){\n continue;\n } else if(s[i].typename == \"PathItem\"){\n if(pp_length_limit\n && s[i].pathPoints.length <= pp_length_limit){\n continue;\n }\n paths.push(s[i]);\n \n } else if(s[i].typename == \"GroupItem\"){\n // search for PathItems in GroupItem, recursively\n extractPaths(s[i].pageItems, pp_length_limit, paths);\n \n } else if(s[i].typename == \"CompoundPathItem\"){\n // searches for pathitems in CompoundPathItem, recursively\n // ( ### Grouped PathItems in CompoundPathItem are ignored ### )\n extractPaths(s[i].pathItems, pp_length_limit , paths);\n }\n }\n}", "function generateOrPredicate(marker) {\n var orPredicate = {$or: []};\n for(var prop in marker) {\n\t var newOrStatement = {};\n if (marker.hasOwnProperty(prop)) {\n\t\tif (marker[prop].toString() == \"[object Object]\") { //if subdocument, then navigate through each subproperty\n for(var subProp in marker[prop]) {\n\t\t\t if (marker[prop].hasOwnProperty(subProp)) {\n\t\t\t\t//console.log('adding '+prop+'.'+subProp+':'+marker[prop][subProp]);\n\t\t\t\tnewOrStatement[prop+'.'+subProp] = marker[prop][subProp];\n\t\t\t }\n\t\t\t}\n } else {\n\t\t //console.log('adding '+prop+':'+marker[prop]);\n\t\t newOrStatement[prop] = marker[prop];\n\t\t}\n }\n\t orPredicate.$or.push(newOrStatement);\n }\n return orPredicate;\n}", "function generateDescriptionChain(length) {\n var descriptions = [];\n for (var i = 1, j; i <= length; i++) {\n var inTriples = [],\n outTriples = [];\n for (j = 1; j <= (i > 1 ? conditionCount : 1); j++)\n inTriples.push('?a' + j + ' ex:' + relation + i + ' ?b' + j + '.');\n outTriples.push('_:request http:methodName \"GET\";');\n outTriples.push(' http:requestURI ?a1;');\n outTriples.push(' http:resp [ http:body ?b1 ].');\n for (j = 1; j <= conditionCount; j++)\n outTriples.push('?a' + j + ' ex:' + relation + (i + 1) + ' ?b' + j + '.');\n if (i === length)\n outTriples.push('?a1 ex:relGoal ?b1.');\n descriptions.push(generateDescription(inTriples, outTriples));\n }\n return descriptions;\n}", "function getMealFromFilter(filterParams, data) {\n\tlet meals = [];\n\tlet restaurantData = [];\n\n\tfor (let key in filterParams) {\n\t\tlet split = key.split(\"-\");\n\t\tif (split[0] == \"meal\") meals.push(split[1]);\n\t}\n\n\tif (meals.length == 0) {\n\t\treturn data;\n\t} else {\n\t\tfor (let meal in meals) {\n\t\t\tfor (let key in data) {\n\t\t\t\tif (data[key].mealType.indexOf(meals[meal]) > -1) {\n\t\t\t\t\trestaurantData.push(data[key]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn restaurantData;\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handle get public URL with given bucketname and filename
function getPublicUrl (bucketName,filename) { return `https://storage.googleapis.com/${bucketName}/${filename}`; }
[ "function fetchGcsObject(bucket, objectName, responseHandler) {\n console.log('Fetching', bucket, '#', objectName);\n if (!isServingAppFromMachine()) {\n gapi.client.storage.objects.get({\n 'bucket': bucket,\n 'object': objectName,\n 'alt': 'media'\n }).then(function(response) {\n responseHandler(response.body);\n }, function(reason) {\n console.log(reason);\n alert('Could not fetch ', objectName, reason.body);\n });\n } else {\n window.fetch('data/' + bucket + '/' + objectName).then(function(response) {\n if (response.ok) {\n return response.text();\n } else {\n console.log(response.statusText);\n alert('Could not fetch \"' + objectName + '\"\\nReason: ' + response.statusText);\n }\n }).then(function(text) {\n responseHandler(text);\n });\n }\n}", "function getS3(callback, key, bucket, callback) {\n var params = {Bucket: bucket, Key: key};\n s3.getObject(params, callback).send();\n}", "function getFileS3(filename, key, bucket, callback) {\n var params = {Bucket: bucket, Key: key};\n var file = require('fs').createWriteStream(filename);\n s3.getObject(params).createReadStream().on(\"finish\", callback).pipe(file);\n}", "function urlStaticS3(userId, baseFolder, subFolder, filename, width, random) {\n\tvar url = pathStaticImageS3(userId, baseFolder, subFolder, filename, width);\n\tif (S3URL) {\n\t\turl = S3URL + url;\n\t}\n\treturn random ? url + '?' + Math.random() : url;\n}", "function get_signed_request(file, ifLast){\n\t\tvar username;\n\t\tif(document.getElementById('username') != null){\n\t\t\tusername = document.getElementById('username').value;\n\t\t}\n\t\telse{\n\t\t\tusername = 'username';\n\t\t}\n\t\t\n\t var xhr = new XMLHttpRequest();\n\t xhr.open(\"GET\", \"/sign_s3?file_name=\"+file.name+\"&file_type=\"+file.type+\"&username=\"+username);\n\t xhr.onreadystatechange = function(){\n\t if(xhr.readyState === 4){\n\t if(xhr.status === 200){\n\t var response = JSON.parse(xhr.responseText);\n\t upload_file(file, response.signed_request, response.url, ifLast);\n\t }\n\t else{\n\t alert(\"Could not get signed URL.\");\n\t }\n\t }\n\t };\n\t xhr.send();\n\t}", "getItemsInBucket(arg = {bucket: null, callback: (bucketItem)=>{}}){\n if(arg.bucket != null && arg.bucket.contents != null){\n let contents = arg.bucket.contents\n if(!Array.isArray(contents)){\n contents = [contents];\n }\n for(let i = 0; i < contents.length; i++){\n let url = `${AWS_BASE_URL}${arg.bucket.name}/${contents[i].Key}`;\n this.makeJSONFetchRequest({url:url, callback:(jsonResponse)=>{\n if(typeof arg.callback === 'function'){\n let data = {\n name: this.jsonFileNameToTitle(contents[i].Key),\n data: jsonResponse\n }\n arg.callback(data);\n }\n }});\n }\n }\n }", "function get_full_url(file) {\n\n //\n // We just concatenate strings. This is to ensure\n // efficient memory use as opposed to storing the\n // entire URLs as arrays\n //\n // return {domain: COMMONCRAWL_DOMAIN, path: '/crawl-data/' + file + '/wet.paths.gz'};\n return COMMONCRAWL_BASE_URL + file + COMMONCRAWL_WET_PATHS;\n\n}", "function fileUrlForFileName(fileName) {\n return ['//', config.get('uploadsBucket'), '/webhook-uploads/', encodeURIComponent(fileName)].join('')\n }", "getUrl (name) {\n name = name.name ? name.name : name\n return this.urls[name]\n }", "getFileUrl(file) {\n return RSVP.resolve(file.link('self').href);\n }", "function file_here (here_url, file_name) {\n\tconst here_file = fileURLToPath(here_url);\n\tconst here = path.dirname(here_file);\n\n\treturn path.join(here, file_name);\n}", "function readURLs(file) {\n let data = fs.readFileSync(file, 'utf8', function(err, data) {\n if (err) {\n console.log(\"Problem with reading file\");\n process.exit(1)\n }\n })\n return data\n}", "function getPageFileUrl(galleryId, fileName) {\n return `${getBaseUrl(cdn.getFullPrefix(galleryId, false))}/galleries/${galleryId}/${fileName}`;\n}", "static getDownloadUrl(id, useCdn = false){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.useCdn = useCdn;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'getDownloadUrl', kparams);\n\t}", "function putFileS3(filename, key, bucket, callback) {\n var body = fs.createReadStream(filename);\n putS3(body, key, bucket, callback);\n}", "function pathStaticImageS3(id, baseFolder, subFolder, filename, width) {\n\tvar prefix = pathStaticS3(id, baseFolder, subFolder);\n\tvar type = baseFolder + '_' + subFolder;\n\tvar suffix = properImageName(type, filename, width);\n\treturn prefix + suffix;\n}", "async function downloadConfigFile(projectId, bucket_name, repo_name, filename) {\n const storage = new Storage({\n projectId: projectId\n });\n\n const bucket = storage.bucket(bucket_name);\n const file = await bucket.file(`${repo_name}/${filename}`).download();\n return yaml.safeLoad(file);\n}", "function buildURL (storeNumber) {\r\n var urlString = \"http://www.spring-market.com/wp-content/uploads/\" + getYearForURL() + \"/\" + getMonthForURL() + \"/\" + storeNumber + \"_\" + createDateString() + \".pdf\";\r\n\r\n console.log( urlString );\r\n\r\n return urlString;\r\n}", "getGitHubURL(fileName) {\n if (!this.gitHubUser ||\n !this.gitHubProject ||\n !this.contains(fileName)) {\n return;\n }\n return [\n `https://${this.gitHubHostname}`,\n this.gitHubUser,\n this.gitHubProject,\n \"blob\",\n this.branch,\n fileName.substr(this.path.length + 1),\n ].join(\"/\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PROCESS SIBYL ends FIX FILE NAME Called from saveAsEPS to remove any number from file name
function fixFileName(fileName) { // I don't need to explicitly remove extension; // Illy seems to cope with that // var fName = fileName.replace('.svg', ''); // Lose number, if any -- e.g.: ' (2)' var fName = fileName.replace(/\s?\(\d\)/,''); return fName; }
[ "function getNewName()\r{\r\tvar ext, docName, newName, saveInFile, docName;\r\tdocName = sourceDoc.name;\r\text = '_AB_nobleed_HR.pdf'; // new extension for pdf file\r\tnewName = \"\";\r\t\t\r\tfor ( var i = 0 ; docName[i] != \".\" ; i++ )\r\t{\r\t\tnewName += docName[i];\r\t}\r\tnewName += ext; // full pdf name of the file\r\t\r\t// Create a file object to save the pdf\r\tsaveInFile = new File( folderPDF + '/' + newName );\r\t\r\r\treturn saveInFile;\r}", "function getNewName()\n{\n\tvar ext, docName, newName, saveInFile, docName;\n\tdocName = sourceDoc.name;\n\text = '.ai'; // new extension for pdf file\n\tnewName = \"\";\n\t\t\n\tfor ( var i = 0 ; docName[i] != \".\" ; i++ )\n\t{\n\t\tnewName += docName[i];\n\t}\n\tnewName += ext; // full pdf name of the file\n\t\n\t// Create a file object to save the pdf\n\tsaveInFile = new File( destFolder + '/' + newName );\n\t\n\n\treturn saveInFile;\n}", "function makeFilename() {\n let result = currentFrameNumber.toString(10);\n while (result.length < recorder.numberOfDigits) {\n result = '0' + result;\n }\n result = recorder.movieName + result;\n return result;\n}", "fileName(playlist) {\n\t\treturn playlist.name.replace(/[^a-z0-9\\- ]/gi, '').replace(/[ ]/gi, '_').toLowerCase();\n\t}", "function dwscripts_getSBFileName()\n{\n var sbName = document.URL;\n var lastSlash = sbName.lastIndexOf(\"/\");\n\n if (lastSlash != -1)\n {\n sbName = sbName.substring(lastSlash+1);\n }\n\n return sbName;\n}", "function getCoScriptFileTitle(iFile){\r\n\tvar fstream = CC[\"@mozilla.org/network/file-input-stream;1\"]\r\n\t\t\t\t\t\t\t.createInstance(CI.nsIFileInputStream)\r\n\tvar sstream = CC[\"@mozilla.org/scriptableinputstream;1\"]\r\n\t\t\t\t\t\t\t.createInstance(CI.nsIScriptableInputStream)\r\n\tfstream.init(iFile, -1, 0, 0)\r\n\tsstream.init(fstream)\r\n\tvar str = sstream.read(200)\r\n\tsstream.close()\r\n\tfstream.close()\r\n\t\r\n\tvar savedPVal = null\r\n\tvar savedPStartIndex = str.indexOf('savedP')\r\n\tif(savedPStartIndex != -1) savedPVal = str.substring(savedPStartIndex+8, savedPStartIndex+13)\r\n\t//debug(\"getCoScriptFileTitle has savedPVal of \" + savedPVal)\r\n\tif(savedPVal == \"false\") return null\r\n\t\r\n\tvar titleEndIndex = str.indexOf(\"{\")\r\n\tvar title = str.substring(0, titleEndIndex)\r\n\treturn title\r\n}", "getDocNameNoExtension(docName) {\n let fileName;\n let documentArray = docName !== '' ? docName.split('.') : [];\n\n if(documentArray.length <= 0)\n return ''\n\n if(documentArray.length > 2)\n {\n let fileNameArray = documentArray[2].split('/');\n fileName = fileNameArray[fileNameArray.length - 1];\n } \n else\n fileName = docName;\n \n return fileName;\n\n }", "function updateFileName() {\r\n var file = $('#pdfbutn').get(0).files[0];\r\n if (file) {\r\n // var fileSize = 0;\r\n // if (file.size > 1024 * 1024) \r\n // fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';\r\n // else \r\n // fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';\r\n $('#filename').val(file.name);\r\n }\r\n}", "function updateFileExtenstion (fileName) {\n return fileName.replace('.plottr', '.pltr')\n}", "function removeFromKillFile(name) {\r\n\tvar curKF = GM_getValue(KILLFILE, \"\").split(KF_DELIMITER);\r\n\tvar newKF = new Array();\r\n\tfor(var i=0; i<curKF.length; i++) {\r\n\t\tif(curKF[i] != name)\r\n\t\t\tnewKF.push(curKF[i]);\r\n\t}\r\n\tGM_setValue(KILLFILE, newKF.join(KF_DELIMITER));\r\n}", "function generateFileName(filetype) {\n return 'msfu_' + (+new Date()) + Math.floor((Math.random() * 100) + 1) + ':' + filetype;\n\n }", "function getFileNameWithoutExtension(fileName)\r{\r var pattern = /(.+)\\.indd/;\r var matchArray = pattern.exec(fileName);\r if (matchArray != null && matchArray.length > 1) {\r return matchArray[1];\r } else {\r return fileName;\r }\r}", "function salvarJPG(nome){\n var doc = app.activeDocument;\n var file = new File(doc.path +'\\\\'+nome+'.jpg');\n var opts = new JPEGSaveOptions();\n opts.quality = 1;\n doc.saveAs(file,opts,true);\n }", "function saveAsEPS(myFile) {\r\n\tvar path = c_outbox + fixFileName(myFile.name);\r\n\tvar newFile = new File(path);\r\n\tvar saveOpts = new EPSSaveOptions();\r\n\tsaveOpts.cmykPostScript = true;\r\n\tsaveOpts.embedAllFonts = true;\r\n\tmyFile.saveAs( newFile, saveOpts );\r\n}", "function getFilePath(journey_id, saveDate){\n\treturn journey_id + '_' + saveDate + '.wav';\n}", "function addToKillFile(name) {\r\n\tvar curKF;\r\n\tif(GM_getValue(KILLFILE, \"\") == \"\") {\r\n\t\tcurKF = new Array();\r\n\t} else {\r\n\t\tcurKF = GM_getValue(KILLFILE, \"\").split(KF_DELIMITER);\r\n\t}\r\n\tfor(var i=0; i<curKF.length; i++) {\r\n\t\tif(name == curKF[i]) return;\r\n\t}\r\n\tcurKF.push(name);\r\n\tGM_setValue(KILLFILE, curKF.join(KF_DELIMITER));\r\n}", "function manipulateString(string) {\n\t//alertrnf(\"from backup in manipulateString(): string received = \" + string);\n\t//alertrnf(\"renamedFileName = \" + renamedFileName);\nif(budgetSheet && !(renamedFileName.includes(\"bs\"))) {\n//restore.bs to filename //if backing up a budgetsheet after edit renamedFileName might already end in .bs\nrenamedFileName = renamedFileName + \".bs\";\n//protocolFileName = renamedFileName + \".bs\";\n//protocolFileName = renamedFileName + \".bs\";\n}//end if(budgetSheet) {\n\tposition = string.indexOf(\"_os\");\n\t//alertrnf(\"position = \" + position);\n\tpart = string.slice(position);\n\t//alertrnf(\"part = \" + part);\n\t//newPartString = \"{\\\"\" + protocolFileName;\n\tnewPartString = \"{\\\"\" + renamedFileName;\n\t//alertrnf(\"newPartString = \" + newPartString);\n\t//string.splice position = 17\n\t//string = \"This is a test of rename db filename!\"\n\tstring = newPartString+part;\n\t//alertrnf(\"Now string = \" + string);\n\t// dbTitle.textContent = renamedFileName;\n\t return string;\n}//end function manipulateString", "saveMIDI(filename) {\n\t\t\tvar buffer = new Buffer(this.buildFile());\n\t\t\tfs.writeFile(filename + '.mid', buffer, function (err) {\n\t\t\t\tif(err) return console.log(err);\n\t\t\t});\n\t\t}", "newFilename() {\n if (this.prevFilename !== this.currentFilename) {\n // Only do that after new file created\n this.prevFilename = this.currentFilename\n this.deleteOldFiles()\n }\n return super.newFilename()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all mapped NFTs which have the specified contract address and token id or FIO Address or hash.
getNfts(options, limit, offset) { const { fioAddress, chainCode, contractAddress, tokenId, hash, } = options; let nftsLookUp; if (fioAddress != null && fioAddress != '') { nftsLookUp = new queries.GetNftsByFioAddress(fioAddress, limit, offset); } if (chainCode != null && chainCode != '' && contractAddress != null && contractAddress != '') { nftsLookUp = new queries.GetNftsByContract(chainCode, contractAddress, tokenId, limit, offset); } if (hash != null && hash != '') { nftsLookUp = new queries.GetNftsByHash(hash, limit, offset); } if (nftsLookUp == null) { throw new Error('At least one of these options should be set: fioAddress, chainCode/contractAddress, hash'); } return nftsLookUp.execute(this.publicKey); }
[ "getFioAddresses(fioPublicKey, limit, offset) {\n const getNames = new queries.GetAddresses(fioPublicKey, limit, offset);\n return getNames.execute(this.publicKey);\n }", "async listTokensFromAddress (addr) {\n try {\n if (!addr) throw new Error('Address not provided')\n\n // Convert to a BCH address.\n addr = _this.bchjs.SLP.Address.toCashAddress(addr)\n // console.log(`addr: ${addr}`)\n\n const utxos = await _this.utxos.getUtxos(addr)\n // console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)\n\n const hydratedUtxos = await _this.utxos.hydrate(utxos)\n // console.log(`hydratedUtxos: ${JSON.stringify(hydratedUtxos, null, 2)}`)\n\n return _this.listTokensFromUtxos(hydratedUtxos)\n } catch (err) {\n console.error('Error in tokens.js/listTokensFromAddress()')\n throw err\n }\n }", "getBlocksByAddress() {\n this.app.get('/stars/address::address', async (req, res) => {\n const { address } = req.params;\n // ensure address is valid\n if (checkAddress(address)) {\n try {\n // search through blockchain, add any blocks with matching address to total.\n const chainData = await this.chain.getFormattedData();\n const blocks = chainData.reduce((total, block) =>\n (block && block.body && block.body.address === address) \n ? [...total, block]\n : total,\n []\n );\n // blocks with address were found\n if (blocks.length > 0) {\n const decodedBlocks = blocks.map(block => decryptStarStory(block));\n return res.json(decodedBlocks);\n }\n throw new Error('No blocks found');\n } catch (error) {\n // no blocks were found\n return res.json({\n status: false,\n message: `Error: Blockchain doesn't have any blocks with address of ${address}.`\n });\n }\n }\n // address is junk or missing\n return res.json(INVALID_REQUEST);\n });\n }", "function inputForAddress (address, allInputs) {\n try {\n const addressUTXO = utxoForAddress(address)\n for (let i = 0; i < allInputs.length; i++) {\n const input = allInputs[i]\n const txId = Buffer.from(input.hash).reverse().toString('hex')\n if (txId === addressUTXO.tx_hash) return i\n }\n throw new Error(`No inputs for address ${address}`)\n } catch (err) {\n console.log(`Error in paymentTxForAddress(): ${err}`)\n throw err\n }\n}", "getStarsByWalletAddress(address) {\n let self = this;\n let stars = [];\n return new Promise(async (resolve, reject) => {\n for (var i = 1; i < self.chain.length; i++) {\n let data;\n await self.chain[i]\n .getBData()\n .then((blockData) => {\n data = blockData;\n })\n .catch((err) => {\n console.log(err);\n console.log(\"The block data is not retrievable\");\n });\n if (data.address === address) {\n let starData = {\n owner: address,\n star: data.star,\n };\n stars.push(starData);\n }\n }\n if (stars.length > 0) {\n resolve(stars);\n } else {\n reject(\"Address doesn't have any stars registered\");\n }\n });\n }", "function getTransactionsByAccount() {\n var account = document.getElementById(\"trxAccount\").value;\n var startBlockNumber = document.getElementById(\"startBlock\").value;\n var endBlockNumber = document.getElementById(\"endBlock\").value;\n \n if (endBlockNumber == \"\") {\n endBlockNumber = web3.eth.blockNumber;\n console.log(\"Using endBlockNumber: \" + endBlockNumber);\n }\n if (startBlockNumber == \"\") {\n startBlockNumber = endBlockNumber - 1000;\n console.log(\"Using startBlockNumber: \" + startBlockNumber);\n }\n console.log(\"Searching for transactions to & from account: \" + account + \" within blocks \" + startBlockNumber + \" & \" + endBlockNumber);\n \n for (var i = startBlockNumber; i <= endBlockNumber; i++) {\n if (i % 1000 == 0) {\n console.log(\"Searching block \" + i);\n }\n var block = web3.eth.getBlock(i, true);\n if (block != null && block.transactions != null) {\n block.transactions.forEach( function(e) {\n if (account == \"*\" || account == e.from || account == e.to) {\n console.log(\" tx hash : \" + e.hash + \"\\n\"\n + \" nonce : \" + e.nonce + \"\\n\"\n + \" blockHash : \" + e.blockHash + \"\\n\"\n + \" blockNumber : \" + e.blockNumber + \"\\n\"\n + \" transactionIndex: \" + e.transactionIndex + \"\\n\"\n + \" from : \" + e.from + \"\\n\" \n + \" to : \" + e.to + \"\\n\"\n + \" value : \" + e.value + \"\\n\"\n + \" time : \" + block.timestamp + \" \" + new Date(block.timestamp * 1000).toGMTString() + \"\\n\"\n + \" gasPrice : \" + e.gasPrice + \"\\n\"\n + \" gas : \" + e.gas + \"\\n\");\n // + \" input : \" + e.input);\n }\n })\n }\n }\n }", "function getUnspents(address, network, callback) {\n var api = new API(network)\n api.addresses.unspents(address, function(err, results) {\n if(err) return callback(err)\n\n var unspents = results.map(function(r) {\n return {\n txId: r.txId,\n vout: r.vout,\n value: r.value\n }\n })\n\n var seen = [], result = [];\n for(var len = unspents.length, i = len-1; i >= 0; i--){\n if(!seen[unspents[i]]){\n seen[unspents[i]] = true;\n result.push(unspents[i]);\n }\n }\n\n callback(null, address, result)\n })\n}", "function getAddressTypes(callback) {\n\n let addressTypeRequest = createRequest('GET', '/addresstypes', 'application/json');\n\n let req = http.get(addressTypeRequest, function (response) {\n let addressResult = '';\n response.on('data', (chunk) => {\n addressResult += chunk;\n });\n response.on('end', () => {\n try {\n switch(response.statusCode) {\n case 200: {\n let addressTypeList = JSON.parse(addressResult).addressTypes;\n addressTypeList.forEach(function (addressType) {\n addressTypes[addressType.addressType] = addressType.id;\n });\n logger.debug('Listed address types successfully.');\n callback();\n break;\n }\n case 401: {\n logger.error('User is unauthorized. Exiting.', addressResult);\n keepAliveAgent.destroy();\n }\n case 500: {\n logger.error('Internal server error. Exiting.', addressResult);\n keepAliveAgent.destroy();\n }\n default: {\n logger.warn('Failed to list address types.', addressResult);\n callback();\n break;\n }\n }\n } catch (e) {\n logger.error('Failed to get address type list. Reason: ', e.message);\n callback();\n }\n });\n }).on('error', (e) => {\n logger.error('Failed to list address types.', e.message);\n });\n}", "getFioNames(fioPublicKey) {\n const getNames = new queries.GetNames(fioPublicKey);\n return getNames.execute(this.publicKey);\n }", "getPublicAddress(fioAddress, chainCode, tokenCode) {\n const publicAddressLookUp = new queries.GetPublicAddress(fioAddress, chainCode, tokenCode);\n return publicAddressLookUp.execute(this.publicKey);\n }", "getPublicAddresses(fioAddress, limit, offset) {\n const publicAddressesLookUp = new queries.GetPublicAddresses(fioAddress, limit, offset);\n return publicAddressesLookUp.execute(this.publicKey);\n }", "getChannelsForToken (tokenAddress) {\n return new Promise((resolve, reject) => {\n this.getTokens()\n .then(response => {\n return response.json();\n })\n .then(dashBoardInfo => {\n dashBoardInfo.tokens.map((token, index) => {\n if (token.address === tokenAddress) {\n resolve(token)\n }\n })\n reject('Not found')\n }).catch(err => reject(err));\n });\n }", "function filterTableOnAddresses(){\n //get current table elements\n var tableBodyChildrenArray = Array.from(tableBody.children);\n //iterate through each element that is currently in the table and check if one of its addresses starts with the search string\n tableBodyChildrenArray.forEach(function(child){\n var contractAddressString = child.querySelector(\".contractAddress\").innerText.trim();\n var payerAddressString = child.querySelector(\".payerAddress\").innerText.trim();\n var recipientAddressString = child.querySelector(\".recipientAddress\").innerText.trim();\n\n if(!contractAddressString.startsWith(String(addressFilter.value.trim()))\n && !payerAddressString.startsWith(String(addressFilter.value.trim()))\n && !recipientAddressString.startsWith(String(addressFilter.value.trim()))){\n child.style.display = 'none';\n }\n else{\n child.style.display = 'table-row';\n }\n });\n}", "function doFuseSearch(query) {\n let results = fuse.search(query);\n return results;\n}", "async getIpv6AddrTable()\n {\n const addressInfo = await getAddressInfo();\n const byIpAddr = addressInfo.byIpAddr;\n\n return Promise.resolve()\n .then(\n () =>\n {\n let ipAddr;\n let promises = [];\n\n // Call `getIpv6AddrEntry` for each IPv6 address, binding the\n // just-retrieved addressInfo so that `getIpAddrEntry` need\n // not re-retrieve it.\n for (ipAddr in byIpAddr.IPv6)\n {\n promises.push(this.getIpv6AddrEntry.bind(addressInfo)(ipAddr));\n }\n\n return Promise.all(promises);\n });\n }", "static async getEthTransactions() {\n const walletAddress = await this.getWallet().then(wallet =>\n wallet.getAddressString(),\n );\n\n return fetch(\n `https://api.ethplorer.io/getAddressTransactions/${walletAddress}?apiKey=freekey`,\n )\n .then(response => response.json())\n .then(transactions =>\n transactions.map(t => ({\n from: t.from,\n timestamp: t.timestamp,\n transactionHash: t.hash,\n value: t.value.toFixed(2),\n })),\n );\n }", "query(protocolMask, serviceMask, maxAddresses = 1000) {\n // XXX inefficient linear scan\n const now = Date.now();\n const addresses = [];\n for (const peerAddressState of this._store.values()) {\n // Never return banned or failed addresses.\n if (peerAddressState.state === PeerAddressState.BANNED\n || peerAddressState.state === PeerAddressState.FAILED) {\n continue;\n }\n\n // Never return seed peers.\n const address = peerAddressState.peerAddress;\n if (address.isSeed()) {\n continue;\n }\n\n // Only return addresses matching the protocol mask.\n if ((address.protocol & protocolMask) === 0) {\n continue;\n }\n\n // Only return addresses matching the service mask.\n if ((address.services & serviceMask) === 0) {\n continue;\n }\n\n // Update timestamp for connected peers.\n if (peerAddressState.state === PeerAddressState.CONNECTED) {\n address.timestamp = now;\n // Also update timestamp for RTC connections\n if (peerAddressState.bestRoute) {\n peerAddressState.bestRoute.timestamp = now;\n }\n }\n\n // Never return addresses that are too old.\n if (this._exceedsAge(address)) {\n continue;\n }\n\n // Return this address.\n addresses.push(address);\n\n // Stop if we have collected maxAddresses.\n if (addresses.length >= maxAddresses) {\n break;\n }\n }\n return addresses;\n }", "async searchBlockchainWalletAddress() {\n\n this.app.get(\"/stars/address::address\", async (req, res) => {\n\n\n try {\n \n console.log(\"Address Block Hit\");\n let blockchain = new Blockchain();\n let val = req.params.address;\n\n if(val == \"\" || val == null) {\n return res.send({\"Error\": \"stars address cannot be empty\"});\n }\n\n console.log(\"HIt\",val);\n let myBlocks = await blockchain.getBlockByWalletAddressAsync(val);\n \n if(myBlocks instanceof Error) {\n res.send({\"Error\": \"Wallet Address not found in database\"});\n } else {\n res.send(myBlocks);\n } \n\n } catch (error) {\n return res.send({\"Error\": \"There is an error in the Request\"});\n }\n\n }); \n }", "function address(digests) {\r\n var sponge = new Curl(27);\r\n sponge.absorb(digests, 0, digests.length);\r\n var addressTrits = new Int8Array(Curl.HASH_LENGTH);\r\n sponge.squeeze(addressTrits, 0, addressTrits.length);\r\n return addressTrits;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }