query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
sumUntil([1, 2, 3, 4, 5], 2) > 6 sumUntil([1, 2, 4], 1) > 3 Write a function called subtractReverse that takes an array of numbers as a parameter and returns the subtraction of every number beginning at the last element of the input array and ending at the first element of the input array (in reverse).
function subtractReverse(array) { //Write your code here }
[ "function subtract(arr) {\n let result = arr.length === 0 ? 0 :arr[0];\n for(let i = 1; i < arr.length; i++) {\n result -= arr[i];\n }\n return result;\n}", "function sumUntil(array, index) {\n //Write your code here\n}", "function countingDownTo(startFrom, endAt) {\n let descendingArr= [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a string of words separated by spaces and adds them as keys with the value of the first argument 'style'
function define(style, string) { var split = string.split(' '); for (var i = 0; i < split.length; i++) { words[split[i]] = style; } }
[ "function define(style, string) {\n\t var split = string.split(' ');\n\t for (var i = 0; i < split.length; i++) {\n\t words[split[i]] = style;\n\t }\n\t }", "function define(style, string, context) {\n if (context) {\n var split = string.split(' ');\n for (var i = 0; i < split.le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the modal overlay
createModalOverlay() { const modalOverlay = document.createElement('div') modalOverlay.classList.add('modal__overlay') modalOverlay.addEventListener('click', () => { this.destroyModal() }) return modalOverlay }
[ "function createOverlay() {\n\t\t\tvar $overlay = $('<div class=\"repository-browser-modal-overlay\" style=\"z-index: ' + BASE_ZINDEX + ';\"></div>');\n\t\t\t$('body').append($overlay);\n\t\t\t$overlay.click(function () {\n\t\t\t\t$.each(instances, function (i, browser) {\n\t\t\t\t\tbrowser.close();\n\t\t\t\t});\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[re]connect to the Lattice. This should be done frequently to ensure the expected wallet UID is still the one active in the Lattice. This will handle SafeCard insertion/removal events. updateData true if you want to overwrite walletUID and accounts in the event that we find we are not synced. If left false and we notic...
_connect(updateData) { return new Promise((resolve, reject) => { this.sdkSession.connect(this.creds.deviceID, (err) => { if (err) return reject(err); // Save the current wallet UID const activeWallet = this.sdkSession.getActiveWallet(); if (!activeWallet || !activeWal...
[ "async function refreshAccountData() {\n\n // If any current data is displayed when\n // the user is switching acounts in the wallet\n // immediate hide this data\n document.querySelector(\"#connected\").style.display = \"none\";\n document.querySelector(\"#prepare\").style.display = \"block\";\n\n // Disable...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
goToCrate when landed on square 10
function goToCrate(){ if (dogOne.currentStep == 10) { boardMsg(dogOne.name + " was a bad boy! Go to Crate!!!") $dogOne.css({transform: 'translate(730px, -740px)'}); setTimeout(function(){ $dogOne.css({transform: 'translate(0px, -5px)'}); }, 3000); dogOne.currentSt...
[ "function drawCage(size){\n var squareSize = cs/size\n goto(-cs/2,cs/2)\n right(180)\n width(2)\n for (let i = 0; i < size; i++) {\n forward(cs)\n left(90)\n forward(squareSize)\n left(90)\n forward(cs)\n left(90)\n forward(squareSize)\n left(18...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the kittens array to a JSON string then Saves the string to localstorage at the key kittens
function saveKittens() { //save kittens to local storage window.localStorage.setItem("kittens", JSON.stringify(kittens)); }
[ "function saveKittens() {\nwindow.localStorage.setItem(\"kittens\", JSON.stringify(kittens))\n}", "function saveKittens() {\r\n window.localStorage.setItem('kittens', JSON.stringify(kittens));\r\n}", "function saveKittens() {\r\n window.localStorage.setItem(\"kittens\", JSON.stringify(kittens))\r\n}", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RANDOM QUOTE FUNCTION Creates getRandomQuote function Creates a empty variable names quote which will be used to store the final message Generates a random number and stores in randomNum variable Checks that variable against a previous one If they are the same it generates a new random number and then checks again Once...
function getRandomQuote() { let quote; let randomNumber = randomNumGen(quotes.length); if (randomNumber === previousNumber) { randomNumber = randomNumGen(quotes.length); } else { previousNumber = randomNumber; quote = quotes[randomNumber]; } return quote; }
[ "function getRandomQuote() {\n do {\n randomNumber = Math.floor(Math.random() * quotes.length);\n } while (randomNumber === previousNumber);\n previousNumber = randomNumber\n return quotes[randomNumber];\n}", "function getQuote() \n{\t// Generate a random number from 0 - QUOTE.length - 1.\n\tlet num = Math...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
! INGREDIENT SELECT CHECK This is the function that runs to check ingredient select
function checkSelectIngredient(num){ layoutGameInstruction.visible=false; if(ingredients_arr[num].name == orderList_arr[orderListNum]){ addBurgerIngredient(num, gameBurgerContainer); $.marks[orderListNum].visible = true; orderListNum--; updateOrderIndicator(); } if(orderListNum==-1){ //add bun wh...
[ "function validateIngredients(){\r\n\t\r\n\t// Add Ingredients Form\r\n var itemTypeSelect = document.getElementById(\"item\").value;\r\n var measureTypeSelect = document.getElementById(\"measure\").value;\r\n var quantity = document.getElementById(\"quantity\").value;\r\n \r\n if ( (itemTypeSelect =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets all the coordinates for all the cities
function getListOfPoints() { var coordinates = [] GeoCities.forEach(function(city) { coordinates.push(city.location.reverse()) }) return coordinates; }
[ "getCityPoints(citys) {\n var features = [];\n // For each city create a marker / feature point\n $.each(citys, function (i, val) {\n features.push(createMapPoint(val));\n })\n return features;\n }", "function setCityLocs() {\n $.each(cities, function(ke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes a reaction from thought's reactions array by reactionId endpoint: /api/thoughts/:thoughtId/reactions/:reactionId
removeReaction({ params }, res) { Thought.findOneAndUpdate({ _id: params.thoughtId }, { $pull: { reactions: { reactionId: params.reactionId } } }, { new: true }) .then(dbThoughtData => { if (!dbThoughtData) { res.status(404).json({ msg: `No thought with this ID found` }); return; ...
[ "deleteReaction(req, res){\n Thought.findOneAndUpdate(\n {_id: req.params.thoughtId},\n {$pull: {reactions: {_id: req.params.reactionId}}},\n {new: true},\n ).then((thought)=>{\n if(!thought){\n res.status(404).json({message: \"Cannot find any...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates and returns defs element
defs() { if (!this.isRoot()) return this.root().defs(); return adopt(this.node.querySelector('defs')) || this.put(new Defs_Defs()); }
[ "defs(){if(!this.isRoot())return this.root().defs();return adopt(this.node.querySelector(\"defs\"))||this.put(new Defs)}", "init() {\n var i = 0,\n child = null,\n docElement = document.createElementNS(this.xmlns, 'defs');\n this._docElementNS = docElement;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
devuelve el tope, null si la pila es vacia
tope() { if (!this.vacia()) { return this.element[this.cant - 1]; } else { return null; } }
[ "res_Puntos(punto_1) {\n let punto = new Punto(this.coordenada_X - punto_1.coordenada_X, this.coordenada_Y - punto_1.coordenada_Y);\n return punto;\n }", "getPlayerPlace() {\n //Genera un array con las llaves del objeto players y luego\n //busca la primera llave cuyo valor este null...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears the move log.
clearMoveLog() { $('#movesList').text(''); }
[ "clear() {\n this._log = [];\n }", "function clearLogs () {\n log = [];\n}", "function clearMove() {\n if (!trueIfTurn()) return; //Only permit this functionality if it is the user's turn.\n\n if (moveOrigin != null) {\n moveOrigin = null;\n moveDestination = null;\n\n let log =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the starred status of the post.
function updateStarredByCurrentUser(postElement, starred) { if (starred) { postElement.getElementsByClassName('starred')[0].style.display = 'inline-block'; postElement.getElementsByClassName('not-starred')[0].style.display = 'none'; } else { postElement.getElementsByClassName('starred')[0].style.display...
[ "function updateStarredByCurrentUser(postElement, starred) {\n\tif (starred) {\n\t\tpostElement.getElementsByClassName('starred')[0].style.display = 'inline-block';\n\t\tpostElement.getElementsByClassName('not-starred')[0].style.display = 'none';\n\t}\n\telse {\n\t\tpostElement.getElementsByClassName('starred')[0]....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name: positionPanel Desc: Uses functions from the dynweb libraries also in this file to position panels. NOTE: This is not working so well in i.e., needs to be refactored. Params: e the event from which the position will be determined (typically onClick) o the object to position offx horizontal offset (in pixels) for n...
function positionPanel(e, o, offX, offY) { var x=0, y=0; viewport.getAll(); x = e.pageX? e.pageX: e.clientX + viewport.scrollX; y = e.pageY? e.pageY: e.clientY + viewport.scrollY; if ( x + o.offsetWidth + offX > viewport.width + viewport.scrollX ) x = x - o.offsetWidth - offX; else x = x + offX; if ...
[ "function positionPanel() {\n $(\"#ad-hoc-panel\").position({\n my: \"left+10 top\",\n at: \"right top\",\n of: model.selectedAnchor,\n collision: \"flipfit fit\"\n })\n}", "function showPanel(e, theInstance, x, y) {\n var offx = (x)? x - 0 : 20;\n var offy= (y)? y - 0 : 20;\n v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
user_info call for dispatcher
function userinfo_dispatcher_routines() { }
[ "function userinfo_requester_routines() {\n\n}", "getUserDetails() {\n this.makeGETRequest('getuserinfo','userinfoloaded','userInfo');\n }", "function getInfo() {\n Admin.getInfo().then(function (data) {\n app.user = data.data.user;\n });\n }", "async func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new KycQuestionsStepView.
constructor() { KycQuestionsStepView.initialize(this); }
[ "function GuideStepView(appendTarget) {\n this.appendTarget = getViewElem(appendTarget);\n \n // state whether it is loading\n this.loading = false;\n}", "constructor(){\n console.log(\"Constructing Template Quiz\");\n\n // Passive Properties ---------------------\n //Set of all availabl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates a level that already exists in the database
update(id, level) { // CRUD - Create, Read, Update, Delete }
[ "function updateLevels(req, res, next) {\n if (req == null || req.body == null) {\n return utils.res(res, 400, 'Bad Request');\n }\n\n if (req.user_id == null) {\n return utils.res(res, 401, 'Invalid Token');\n }\n\n const levelName = req.body.level_name;\n if (levelName == null || l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new `div` element
function div() { return document.createElement('div'); }
[ "function div() {\n return document.createElement('div');\n }", "function make_div_element(class_name, div_to_append_to) {\n const new_div = document.createElement(\"div\");\n new_div.className = class_name;\n\n div_to_append_to.appendChild(new_div);\n\n return new_div;\n}", "function createDiv(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add the selected new toy to user's boxes backend API will automatically update user Happiness & pollution score when a new box is added
handleNewToy(e) { let item_id = e.target.getAttribute('data-key'); let user_id = this.props.user.id; this.props.actions.addBox('/api/boxes', {active: true, item_id: item_id, user_id: user_id}).then( ()=>{ this.props.actions.fetchUsers('/api/users').then(()=>{ this.setState({addToy: false}); }); }...
[ "function addBallotBoxesAction(event) {\n\n\t// Initializes values\n\tvar fieldValue = event.data.field.val();\n\tvar bbSize = data.ballotBoxes.length;\n\n\t// Creates the ballot box\n\tvar dataBit = {\n\t\t\"password\":\tpassword,\n\t\t\"field\": [\"ballotBoxes\",bbSize],\n\t\t\"value\": {\n\t\t\t\"name\":fieldVal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uploads all chunks from array Calls passCallback(path) Calls failCallback(null)
function uploadLoop(cookie, passCallback, failCallback) { //console.log("length:", chunks.length); for (var i = 0; i < chunks.length; i++) { var chunk = chunks[i]; if (i == (chunks.length - 1)) { //console.log("uploading last chunk"); //last one uploadchunk(chunk, cookie, i, function () { /...
[ "function startChunkUploads( inputItem, progressItem, onFinish )\n{\n return function ( initResults )\n {\n // check and fire up the actual upload\n var blob = inputItem.files[0];\n // lol, const.\n var BYTES_PER_CHUNK = 2 * 1024 * 1024; // 2MB chunk sizes.\n var SIZE = blob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove restaurants by type
function removeRestaurantsByType (type) { for(var i in sampleData) { if(sampleData[i].type == type) { markers_arr[i].setMap(null); markers_arr[i] = null; sampleData[i] = null; count--; i--; } } sampleData = sampleData.filter(n => n)...
[ "function removeRestaurantMarkers(restaurant) {\n for (var j = 0; j < markers.length; j++) {\n if (markers[j].place_id === restaurant.getAttribute(\"place_id\")) {\n markers[j].setMap(null);\n }\n }\n}", "function getRestaurantsByType (type) {\n var request = {\n location: selectedCoords,\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
enable Custom checkboxes for fix crap releases
function enableFixCrapCustom(){ var inputs = document.getElementsByName('fix_crap_opt'); if (inputs[2].checked == true) { var checks = document.getElementsByName('fix_crap[]') for (var t = 0; t < checks.length; t ++) { checks[t].disabled = false; checks[t].readonly = fals...
[ "function putCheckboxesInCustomMode() {\n var currentCheckbox,\n currentPreference,\n defaultPreferences = window.extensions.KJSLINT.Panels.Options.Controller.getDefaultPreferences(),\n i, \n numberOfCheckboxes = elements.checkboxes.length;\n \n updat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the ArticleList that is the parent to ArticleItem, in AI we made ID nest links. for that to work, we want to make a folder called article under pages, and then another folder called [id], [id] folder needs to match what we named in articleItem Finally we make a index.js file in id to link up the nested pages.
function ArticleList({ articles }) { return ( <div className={articleStyles.grid}> {articles.map((article) => ( <ArticleItem article={article} /> ))} </div> ); }
[ "function displayArticles(articles, listId) {\n\n $$.each(articles, function (i) {\n $$(listId).append(`\n <li>\n <a href=\"#\" class=\"item-link item-content\">\n <div class=\"item-media\"><img src=\"${articles[i].urlToImage}\" width=\"100\"></div>\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
lodash //sort the groups and then how many in each //Creates an array of values by running each element in collection thru iteratee. //The iteratee is invoked with three arguments: //(value, index|key, collection).
function howManyAgeGroup(){ let groups = _.groupBy(peopleData, (obj) => { return Math.floor(obj.age / 10); }); let result = _.mapValues(groups, (value) => { console.log("value is:", value); return value.length; }); return result }
[ "_countBy() {\n var numsArr = [3,4,6,7,8,9,3,4,5,6,4,2,5,6,7,4,3,2,3,4,5,6,7]\n\n var result = _.countBy(this.state.courses, 'category')\n console.log('count by property', result)\n\n var groupingCriteria = function(value) {\n if(value % 2 == 0)\n {\n return 'divisble'\n }\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Basic action factory Usage: actionFactory(action)(data)
function actionFactory(action) { return function(data) { return { type: action, payload: data } } }
[ "function actionCreator() {return action}", "function actionCreator(action) {\n return action;\n}", "function actionCreator() {\n return action\n}", "function actionCreator() {\n return action\n}", "function actionCreator() {\n return action;\n}", "function actionCreator() {\n return action;\n}"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
intersectScene has been modified determines a list of objects in the scene to give to intersectObjectList
function intersectScene(ray, scene) { var pair = intersectKD(ray, scene); var list = pair[0]; var length = pair[1]; return intersectObjectList(ray, list, scene.objects, length); }
[ "intersectObjects() {\n // Do not highlight when already selected\n //if (controller.userData.selected !== undefined) {\n //controller.userData.selected.material.color.setHex( controller.userData.currentHex );\n //return;\n //}\n this.updateRaycaster();\n const inter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms in a tree upon our box before then calculating how to project it into our desired viewportrelative box This is the final nested loop within updateLayoutDelta for future refactoring
function applyTreeDeltas(box, treeScale, treePath) { var treeLength = treePath.length; if (!treeLength) return; // Reset the treeScale treeScale.x = treeScale.y = 1; var node; var delta; for (var i = 0; i < treeLength; i++) { node = treePath[i]; delta = node.getLayout...
[ "function applyTreeDeltas(box, treeScale, treePath) {\n\t var treeLength = treePath.length;\n\t if (!treeLength)\n\t return;\n\t // Reset the treeScale\n\t treeScale.x = treeScale.y = 1;\n\t var node;\n\t var delta;\n\t for (var i = 0; i < treeLength; i++) {\n\t node = treePath[i]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculates the rating of a single field
function getSingleRating(hospital,ratingField){ sort(ratingField["field"],ratingField["order"]); var position = getPosition(tempActualLocation,hospital); var singleRating = position/actualLocation.length*ratingField["weight"]*10; //alert(position/actualLocation.length); return singleRating; }
[ "calculateRating(user) {\n const {ratings} = user;\n if (ratings.length === 0) {\n return 3;\n }\n let sum = 0;\n\n ratings.forEach(function (rating) {\n sum += rating.rating;\n });\n\n return Math.round(sum/ratings.length);\n }", "averageRating = function(){\n return products.p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function: Build a group subtree. Called as part of the recursive function buildTree().
function buildGroupSubtree(node, groupName, groupApiData) { let apiData = apiMakeData(groupName, groupApiData); let groupNode = makeGroupNode(groupName); node.children.push(groupNode); console.log(`DEBUG: buildTree: GROUP ${groupNode.apiName}, API ${apiData.name}`); buildTree(groupNode, apiData); }
[ "function buildChildGroupsSubtree(node, groupApiData) {\n\tlet definedChildren = getDefinedChildren(node);\n\tif (no(definedChildren)) {\n\t\treturn false;\n\t}\n\tdefinedChildren.forEach(kidName => buildGroupSubtree(node, kidName, groupApiData));\n\treturn true;\n}", "BuildGroups() {\n if (tp.IsEmpty(this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Como obtener la informacion del local storage
function obtener_localstorage(){ if(localStorage.getItem("nombre")){ // se que exiate el nombre en el local storage // para obtener atributo let nombre = localStorage.getItem("nombre"); // para obtener string //let nombre = localStorage.getItem("persona"); // ...
[ "function infoLocalStorage(){\n let cursos;\n // Revisamos los valoes de local storage\n if(localStorage.getItem('curso') === null) {\n cursos = []; \n } else {\n cursos = JSON.parse(localStorage.getItem('curso') );\n }\n return cursos;\n}", "function recuperaLocal() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the proper buttons in the problem type selection
function display_proper_buttons(select) { var value= select.val(); if(value=='') { select.parent().find(".editpt").hide(); select.parent().find(".deletept").hide(); } else { select.parent().find(".editpt").show(); select.parent().find(".deletept").show(); } }
[ "function changeSettingsView() {\n // customize X problem types span\n const customizeProblemTypesEl = document.querySelector(\"#customizeProblemTypes\");\n\n // hide all the checkbox lists\n problemTypes.querySelectorAll(\"#problemTypes ul\").forEach(el => el.classList.add(\"hide\"));\n \n // cha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a range based on the place where this position and the given position diverge around block content. If both point into the same textblock, for example, a range around that textblock will be returned. If they point into different blocks, the range around those blocks in their shared ancestor is returned. You can...
blockRange(other = this, pred) { if (other.pos < this.pos) return other.blockRange(this); for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) return new NodeRange(this, other, d); ...
[ "findFirstOverflowingNodeRange() {\n const foundNode = this.nodes.find((node) => {\n const rect = this.rectFilter.get(node);\n return rect.bottom > (this.rootRect.bottom - this.bottomSpace);\n });\n\n if (!foundNode || foundNode.nodeType === Node.TEXT_NODE || foundNode === this.firstNode) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a search request for the given product name to the server
function search() { var search_key = document.getElementsByName("search")[0].value; var result_area = document.getElementById("search_results"); // TODO add function to search by price const uri = getLink("SearchProductByName") + search_key; var xhr = createRequest("GET", uri); xhr.onload = function() { if(xh...
[ "function searchProduct(req, res, next) {\n productService\n .search(req.params.name)\n .then((result) => res.status(200).json(result))\n .catch((err) => next(err))\n }", "function searchByName(name, callback) {\n client.search({\n index: 'products',\n type: '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws and returns an svg text (align is 'start', 'middle' or 'end')
function drawText (x, y, size, align, color, text){ return svg.append("text") .text(text) .attr("x", x) .attr("y", y) .attr("font-family", "Verdana") .attr("font-size", size+"px") .attr("fill", color) .attr("text-anchor", align); }
[ "function createCDBSVGText(textx, texty, textclass, textcontent) {\n return '<text x=\"' + textx + '\" y=\"' + texty + '\" class=\"' + textclass + '\">' + textcontent + '</text>';\n}", "createSvgText(x, y, color, fontSize, text) {\n const t = document.createElementNS(this.svgNS, \"text\");\n t.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
END: misc. helper / END OF FILE _resources/js/lib/core.js / START OF FILE _resources/js/lib/module.breadcrumb.js Cummins' new web appearance script Copyright (c) 20072010 Cummins AG module breadcrumb author virtual identity AG / $LastChangedDate: 20100202 13:30:40 +0100 (Di, 02 Feb 2010) $
function init_breadcrumb() { if ($("breadcrumb")) { var item_y = null; var isInFollowingLine = false; $A($("breadcrumb").getElementsByTagName("dd")).each(function(item) { item = $(item); //calculate the y-offset position of the current breadcrumb item if(item_y == null) { item_y = Position.cumula...
[ "function VipBreadcrumb() { }", "function alterBreadcrumb() {\n try {\n /* If there are 4 total, AND we're inside a course AND we're not in a group tab */\n if (document.querySelectorAll('#breadcrumbs li').length === 4 && /\\.com\\/courses\\/\\d+\\/(?!groups)/i.test(window...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This sample demonstrates how to Update a VM scale set.
async function virtualMachineScaleSetsUpdateMinimumSetGen() { const credential = new DefaultAzureCredential(); const client = createComputeManagementClient(credential); const subscriptionId = ""; const resourceGroupName = "rgcompute"; const vmScaleSetName = "aaaaaaaaaaaaaa"; const options = { body: {}, ...
[ "async function virtualMachineScaleSetsUpdateMaximumSetGen() {\n const credential = new DefaultAzureCredential();\n const client = createComputeManagementClient(credential);\n const subscriptionId = \"\";\n const resourceGroupName = \"rgcompute\";\n const vmScaleSetName = \"aaaaaaaaaaaaa\";\n const options = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
todo move users orders to UserOrders component todo move user data to UserData component
function UserPanel(props) { const userData = useSelector((state) => state.userReducer); const [user, setUser] = useState(userData); const [userOrders, setUserOrders] = useState([]); const [dbStatus, setDbStatus] = useState(true); const dispatch = useDispatch(); const fetchUserData = () => { userServic...
[ "renderOrder() {\n return this.props.user.order.map((value, index) => {\n return <OrderList loggedUser={this.props.loggedUser} orderItem={value} key={index} />\n });\n }", "function getOrders(orders) {\n //* Order have not loaded yet\n if (!orders) {\n return <></>\n }\n //* If the user has no ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inlines the contents of the document returned by the script tag's src URL into the script tag content and removes the src attribute.
_inlineNonModuleScript(scriptTag) { return __awaiter(this, void 0, void 0, function* () { const scriptHref = dom5.getAttribute(scriptTag, 'src'); const resolvedImportUrl = this.bundler.analyzer.urlResolver.resolve(this.document.parsedDocument.baseUrl, scriptHref); if (resolve...
[ "function remove_script_tags(){\n html = html.replace(/<script[^>]*>.*?<\\/script>/g, function(str){\n if (str.match(/ type=/) && ! str.match(/text\\/javascript/)) { return str; }\n else if (str.match(/src=['\"]?(https?)/)) { return str; }\n else if (str.match(/src=['\"]?\\/\\//)) { return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instance methods // Create individual dog span in DogBar
formatSpan() { let span = document.createElement('span') span.id = `span${this.id}` let p = document.createElement('p') p.id = `name${this.id}` p.innerText = this.name span.appendChild(p) dogBar().appendChild(span) }
[ "function addDogToDogBar(dog) {\n const span = document.createElement(\"span\")\n span.innerText = dog.name\n span.setAttribute(\"data-id\", dog.id)\n span.addEventListener(\"click\", showDogInfo)\n dogBar.append(span)\n }", "function addDog (dog) {\n const spanEl = document.crea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecryptRCTicket: Calls into the SAF Encryption/Decryption API to decrypt RCTicket
function DecryptRCTicket() { try { if(false == g_bPasswordSet) { // // Get the password // g_szPassword = PasswordBox.value; // // Use g_szPassword to decrypt the g_szRCTicketEncrypted. // g_szRCTicket = g_oEncryption.DecryptString( g_szPassword, g_szRCTicketEncrypted ); //alert("Dec...
[ "function DecryptRCTicket()\n{\n\tTraceFunctEnter(\"DecryptRCTicket\");\n\ttry\n\t{\n\t\tif(false == g_bPasswordSet)\n\t\t{\n\t\t\t//\n\t\t\t// Get the password\n\t\t\t//\n\t\t\tif (g_IsIM)\n\t\t\t g_szPassword = PasswordBox_IM.value;\n\t\t\telse\n\t\t\t g_szPassword = PasswordBox.value;\n\n\t\t\tDebugTrace(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Acabamos con la actual instancia del preInversor
function acabarPreInversion (){ realizandoInversion = false }
[ "function realizarInversion() {\n \n rangos = rango.getRango()\n // Ya estamos haciendo una/s inversion/es\n if (realizandoInversion == true){}\n \n // Podemos realizar inversiones\n else {\n \n realizandoInversion = true\n\n // Hacemos algunas comprobaciones\n // TO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs the build command
function runBuild () { execSync('yarn build'); }
[ "function build() {\n const start = Date.now();\n let fullBuildDir = path.join('/tmp/app', BUILD_DIR);\n console.log('Executing build');\n cmd(BUILD_CMD, {\n cwd: fullBuildDir\n });\n\n console.log(`Build completed in ${Date.now() - start}ms`);\n}", "function runBuild () {\n // first, backup the proje...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Confirms that the `connection` field extracted from the fat query at `parentName` > `connectionName` is actually a connection.
function validateConnection(parentName, connectionName, connection) { __webpack_require__(10)(connection.isConnection(), 'RelayMutationQuery: Expected field `%s`%s to be a connection.', connectionName, parentName ? ' on `' + parentName + '`' : ''); }
[ "function validateConnection(parentName, connectionName, connection) {\n\t !connection.isConnection() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'RelayMutationQuery: Expected field `%s`%s to be a connection.', connectionName, parentName ? ' on `' + parentName + '`' : '') : invariant(false) : undefi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST add a new chore
function makeChore(newChore) { console.log('in makeChore', newChore); // ajax call to server to get chore table $.ajax({ type: 'POST', url: '/chores', data: newChore }).then(function (response) { console.log('Response from server.', response); getChores(); }).catch(function (error) { c...
[ "async createChore(e) {\n\n // Prevent automatic reload onSubmit\n e.preventDefault();\n\n // Variables for ease of use\n const content = this.state.choreName;\n const chorePrice = this.state.chorePrice;\n const daysToComplete = this.state.daysToComplete;\n var account = \"\";\n await this.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Event Handler for Clear Console button
function processClear (e) { e.preventDefault(); console.clear(); }
[ "function testConsoleClearBtnClicked() {\n document.getElementById('console').value = 'testing testing testing';\n ndebug.AppGuiManager.consoleClearBtnClicked();\n assertTrue(document.getElementById('console').value.length == 0);\n}", "clear() {\n myself.consoleView.clear();\n }", "function clearCo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds user selected restaurants to final_tour_table
function addTour(){ //html checkbox parent id search result table . var e = event.target.parentNode.parentNode.id; var row_item=document.getElementById(e); //Reference the CheckBox in Table. var active_checkbox = row_item.getElementsByTagName("INPUT"); //find target fina...
[ "function selectRestaurant() {\n\t// choose restaurant\n\t// get json to retrive information\n\n}", "function addNewRestaurant() {\n // create new restaurant object based on user input\n let restName, selRestAddress, restTelephone, restWebsite, nrRating, nrTotalRatings, nrReviews, nrIcon...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates new instance of the browser Catberry's bootstrapper.
function Bootstrapper() { BootstrapperBase.call(this, Catberry); }
[ "function Bootstrapper() {\n this._shell = null;\n this._container = null;\n this._pluginList = null;\n }", "function KclBootstrapper() {\n}", "function bootstrap() {\n var url = window.location.href,\n tmp_constructor,\n root_gadget,\n d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes an array as input and extract a column as a return array
function splitArray(input, column) { var output = []; for (i = 1; i < input.length; i++) { output.push(input[i][1]); } // console.log(output); return output; }
[ "function getColumn(array, column) {\n\tlet arrayCol = [array.length];\n\n\tfor(let i = 0; i < array.length; i++) {\n\t\tarrayCol[i] = array[i][column];\n\t}\n\n\treturn arrayCol;\n}", "arrayColumn(arr, n){\n return arr.map(a => a[n]);\n }", "function getBeatColumn(arr, col) {\n return arr.map(function(r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=============================== FUNCTIONs =============================== log an input error to console
function logInputErr(err) { console.log(chalk.red(err)); }
[ "function getInputError() {\n console.log(`> Hey ${process.env['USERNAME']}, make sure your input is one of the following: \"${userArgs.twitter}\", \"${userArgs.spotify}\", \"${userArgs.omdb}\", \"${userArgs.do}\".`);\n space();\n read.close();\n}", "function seeError(command, input){\n logMsg(\"You'v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A timer showing the current day and time
function timer() { let currentTimeAndDate = moment(); $("#currentTime").text(currentTimeAndDate.format("LTS")); $("#currentDay").text(currentTimeAndDate.format("dddd, MMMM Do, YYYY")); }
[ "function timer(){\r\n const now = new Date();\r\n const hours = now.getHours();\r\n const minutes = now.getMinutes();\r\n const seconds = now.getSeconds();\r\n \r\n timerDisplay.textContent = `${hours}:${minutes < 10 ? '0': ''}${minutes}:${seconds < 10 ? '0': ''}${seconds}`;\r\n \r\n}", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return plugin associated with an address or null if doesn't exist peerAddr: string
getAccount(peerAddr) { let accts = globalState.get('000-reputation-accounts'); for (let pa of Object.keys(accts)) { if (pa === peerAddr) { return accts[peerAddr]; } } return null; }
[ "function getPeer (peerArg) {\n for (let i=0; i<peers.length; i++) {\n if (peers[i].host === peerArg || peers[i].index === peerArg) return peers[i];\n }\n return null;\n}", "_getPeerInfo (peer, callback) {\n let p\n // PeerInfo\n if (PeerInfo.isPeerInfo(peer)) {\n p = peer\n // Mu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to parse the execution string sent over the web socket to this server. The client will send a string containing a db command and the query object used to execute that db command. The query object will be in JSON form and will need to be reconstituted (parsed) before being used to execute the command.
async function parseDBString (socket, dbString) { // Local Variable Declaration let querryObj = undefined; let reqResult = "", dbCommand = "", usrName = ""; let dbStringTokens = []; // Split db string up over the expected delimiters dbStringTokens = dbString.split("|"); // Get the...
[ "function sqlParser(){ \n\tthis.insertPtn = /^INSERT\\s{1,}INTO\\s.*[)]\\s*VALUES\\s*[(].*$/i;\n \tthis.commandInsertHeadPtn=/^INSERT\\sINTO\\s*/i;\n\tthis.tableNamePtn=/^[^,]+[(]/g;\n\tthis.commandMidValuesPtn = /[)]\\s*VALUES\\s*[(]/gi;\n\tthis.commandEndPtn = /[)][;]\\s*$/g;\n\n\tthis.id=0;\n\tthis.nextId = fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API REQUESTS /////////////////////////////////////////// Send tasks to API
function submitTasks() { GetAllTasksAndRes(function(tasks, resources) { // <visualization> $.each(tasks, function(index, task) { console.dir(JSON.stringify(task)); }); // </visualization> // @Anand: here you can make the AJAX request to the API }); }
[ "getTasks() {\n var self = this;\n\n // Get data from server\n getAPITasks(self);\n }", "function requesttasks(){\n\tvar oReq = new XMLHttpRequest();\n\tif(tasks.length > 0){\n\t\tmaxID = tasks[tasks.length-1].rowid;\n\t}else{\n\t\tmaxID = 0;\n\t}\n\toReq.open(\"GET\", \"/api/tasks?latest=\" + maxID)\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RSLite by Brent Ashley Simple nonconcurrent remote scripting calls. send one string, receive one string 1) use this include 2) in body_onload(), set the RSLite var: RSLite = new RSLiteObject(); 3) before using, set callback and failure functions if you want more than an alert 4) set interval and attempts for retries if...
function RSLiteObject(){ this.interval = 100; this.attempts = 60; this.image = new Image(); this.call = function ( page, parm ){ parm = (parm != null)? parm : ''; var d = new Date(); document.cookie = 'RSLite=x; expires=Fri, 31 Dec 1999 23:59:59 GMT;'; this.image.src = page + '?u=' + d.g...
[ "function RemoteScriptingCall(callID)\n{\n\tthis.id = callID;\n\tthis.busy = true;\n\tthis.callback = null;\n\tthis.error_callback = null;\n\n\tswitch (RS.browser)\n\t{\n\t\tcase 'IE':\n\t\t\tdocument.body.insertAdjacentHTML(\"afterBegin\", '<span id = \"SPAN' + callID + '\"></span>');\n\t\t\tvar span = document.al...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls onDestroy hooks for this view
function executeOnDestroys(view){var tView=view[TVIEW];var destroyHooks;if(tView!=null&&(destroyHooks=tView.destroyHooks)!=null){callHooks(view,destroyHooks);}}
[ "onDestroy() {\n // Stop listening to model events when view is destroyed.\n this.model.off('change:filter', this.render);\n this.model.off('todos:add', this.onTodosAdd);\n this.model.off('todos:remove', this.removeTodo);\n this.model.off('todos:change', this.onTodosChange);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dependiendo del tipo de nave creo un objeto y otro.
crearNave(ejercito, cantidad, tipo) { for (let index = 1; index <= cantidad; index++) { let empiezanave; switch (tipo) { case "Nave1": empiezanave = new Nave1(); break; case "Nave2": empiezanave = new Nave2(); break; case "Nave3": ...
[ "function imprimir(tipo){\n console.log(tipo.obtenerDetalles());\n if(tipo instanceof Gerente){//verifica de que tipo es\n console.log(\"Es un objeto de tipo Gerente\")\n }\n else if(tipo instanceof Empleado){//verifica de que tipo es\n console.log(\"Es un objeto de tipo Empleado\")\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads up a single Story. ( ) > any = result of Story.read call.
async read(){ this.core.logger.debug("I'm gonna tell you a Story about... " + this.protocol.href); this.info.started_at = new Date(); this.core.logger.debug("started_at: " + this.info.started_at.toString()); /* handles all situations from story. */ this.result = await this.story.read(this.premise, ...
[ "function readStory(text,value_ms){\r\n\ttarget = 'story';\r\n\tif (text === undefined) {text = default_text;}\r\n\tif (value_ms === undefined) {value_ms = 50;}\r\n\tcurr_dialog = '';\r\n\tsetStory(curr_dialog);\r\n\trenderTextEffect(text,value_ms,'story');\r\n}", "function loadStory() {\n story = {};\n\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the difference in length between two arrays. A `null` argument is considered an empty list. The return value will be positive if `a` is longer than `b`, negative if the opposite is true, and zero if their lengths are equal.
function arrayLengthCompare(a, b) { if (a === void 0) { a = []; } if (b === void 0) { b = []; } return a.length - b.length; }
[ "function arrayLengthCompare(a, b) {\n if (a === void 0) {\n a = [];\n }\n if (b === void 0) {\n b = [];\n }\n return a.length - b.length;\n}", "function length(a, b) {\n return Math.sqrt(\n (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1])\n );\n}", "function diffA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a checkbox to a specified parent node. Emits a "check" event whenever the checkbox is checked or unchecked by the user.
function makeCheckbox(aParentNode, aOptions) { let checkbox = aParentNode.ownerDocument.createElement("checkbox"); checkbox.setAttribute("tooltiptext", aOptions.checkboxTooltip); if (aOptions.checkboxState) { checkbox.setAttribute("checked", true); } else { checkbox.removeAttribute("checked"); } /...
[ "function createCheckBox(parent, name, id, checked, onclickfn, label, lblClass){\n\tvar elem = createElementNode('input', id);\n\telem.type='checkbox';\n\t/*setId(elem, id);*/\n\tif(name && name!=''){\n\t\telem.setAttribute('name', name);\n\t}\n\telem.checked = checked;\n\telem.defaultChecked = checked;\n\tif(oncl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the function to load the active student
function loadActiveStudent() { var loadedStudent = localStorage.getItem('activeUser'); var parsedStudent = JSON.parse(loadedStudent); return parsedStudent; }
[ "function loadStudents() {\r\n StudentModule.getStudents(setupStudentsTable);\r\n}", "function loadStudents() {\n API.getStudents()\n .then(res => \n setStudents(res.data)\n )\n .catch(err => console.log(err));\n }", "function loadStudents () {\n $scope.students = S...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
!! : you never define the variable add1 !! : this function is the same as buttonDisable
function button2Disable() { add1.setAttribute("disabled", ""); }
[ "function addButtonAvail() {\n var highlighted = get_Highlight_Text_No_Remove();\n var avail = highlighted === \"\";\n var addBtns = document.getElementsByClassName(\"add-but\");\n for (var i = 0; i < addBtns.length; i++) {\n addBtns[i].disabled = avail;\n }\n}", "function enable()\n{\n if(input.value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates the html element with count of how many vertices are currently selected
function setHtmlUi() { // sets the count element document.getElementById("count").innerHTML = index + " of " + vCount + " Vertices selected"; }
[ "function updateSelectedCount() {\n const selectedSeats = document.querySelectorAll(\".row .seat.selected\");\n const selectedSeatCount = selectedSeats.length;\n\n count.innerText = selectedSeatCount;\n total.innerText = selectedSeatCount * ticketPrice;\n}", "function changePointCount() {\n\tdocument.getEleme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the dialog for signing a key
signKey(win, userId, keyId) { const inputObj = { keyId, userId, }; const resultObj = { refresh: false, }; win.openDialog( "chrome://openpgp/content/ui/enigmailSignKeyDlg.xhtml", "", "dialog,modal,centerscreen,resizable", inputObj, resultObj ); ...
[ "function sign() {\n\n\t// Block the UI while we perform the signature\n\t$.blockUI();\n\n\t// Get the value attribute of the option selected on the dropdown. Since we placed the \"thumbprint\"\n\t// property on the value attribute of each item (see function loadCertificates above), we're actually\n\t// retrieving ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
obtaining all email addresses and storing them in localStorage will be used to check if email entered is already in use
function checkEmail() { // sending xml request let xml = new XMLHttpRequest; // function that is called when reply received from server xml.onreadystatechange = () => { if ((xml.readyState == 4) && (xml.status == 200)) { let result = JSON.parse(xml.responseText...
[ "addEmail(email) {\n if (email.length > 0) {\n // 1. Split email addresses if needed (if we get list of emails)\n var mas = email.split(/,|;/g);\n //console.log(mas);\n // 2. Add each email in the splited list\n for (var i = 0; i ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a unduplicated cell id randomly.
function getRandomCellId(){ var length = cellIds.length; if ( length == 0 ){ window.clearInterval(intervalId); return ""; } var randomNumber = Math.floor(Math.random() * length); var id = cellIds[randomNumber]; cellIds.splice(randomNumber, 1); return id; }
[ "function generateId() {\n return Math.random * 99999;\n}", "function getRandomId(){\n return Math.floor((Math.random()*1000000000000000)+1);\n }", "function createID() {\n return Math.floor(Math.random() * 10000000000);\n}", "function generateUniqueId() {\r\n\t\t\tvar characters = 'ABCDEFGHIJ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Contains a request payload Has content and type Converts Object and Array content to JSON strings
function Payload(content, type) { var default_type = type; if (_.isArray(content)) { var real = []; for (var item in content) { if (ContentType.isJSON(content[item])) { real.push(JSON.parse(content[item])); } else { real.push(content[item])...
[ "static fromData(content) {\n const requestBody = new RequestBody();\n requestBody.objectData = content;\n return requestBody;\n }", "function parsePayload(payload) {\n let parsed;\n if (typeof payload == 'string') {\n parsed = payload;\n } else if (payload instanceof...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build the recall timer.
function buildRecallTimer() { return setTimeout(switchRecall, MEMORIZE_SEC * S_TO_MS); }
[ "function buildResultTimer() {\n return setTimeout(switchResult, RECALL_SEC * S_TO_MS);\n}", "function CountDown(){\n //setTimeout(function, msec)\n //after a predetermined time, the following function is performed\n //in this case, it sets up updating time of this timer\n timerId = setTimeout(functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Measure memory against a previously set mark
measure(measureName, againstMarkName, saveAsMark = null) { const againstMark = this.marks[againstMarkName] // Validate that the mark exists if (!againstMark) throw new Error(`Mark ${againstMarkName} does not exist`) const mark = new Mark() if (saveAsMark) { this.marks[saveAsMark] = mark ...
[ "function _saveMemory () {\n memory = total;\n }", "function saveMemory(){\n console.log('2.js SM: Total->Memory Storing!!','M:',memory,'<= T:',total);\n memory = total;\n }", "analyzeWithMemory() {\n var similarNotes = 0;\n // Return if no notes are found\n if (this.final_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
verify if d.value is positive or negative. If it's positive, adds a "+" in front of this value
function positiveVal(value){ if (value >0){return "+"+value} else return value; }
[ "function positiveVal(value){\n if (value >0){return \"+\"+value}\n else return value;\n }", "function showPlus(x) {\n\tif (x > -1) \n\t\treturn \"+\" + x;\n\telse\n\t\treturn x;\n}", "function addIfPositive(a, b) {\n\n\tif (b > 0) {\n\t\treturn a + b;\n\t}\n\n\treturn a;\n\n}", "get sign() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a specific beta group.
function readBetaGroupInformation(api, id, query) { return api_1.GET(api, `/betaGroups/${id}`, { query }) }
[ "function createBetaGroup(api, body) {\n return api_1.POST(api, `/betaGroups`, { body })\n}", "function getGroup() { return group; }", "function deleteBetaGroup(api, id) {\n return api_1.DELETE(api, `/betaGroups/${id}`)\n}", "function modifyBetaGroup(api, id, body) {\n return api_1.PATCH(api, `/betaG...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get recipe name by the meal id stored in the Meal Plan DB the recipe will be either the recipe form theMealDB API, or from DIY recipes
async function getRecNameByIdInMealPlan(mealId) { let mealRecipe; if (mealId[0] === "d") { mealRecipe = await getDiyRecById(mealId.substring(2)); return mealRecipe.name; } else { mealRecipe = await getRecipeById(mealId); return mealRecipe.strMeal; } }
[ "function findIngredientName(ingredientId) {\n let ingrName = ingredientsData.find(ingr => {\n if (ingredientId === ingr.id) {\n return ingr;\n }\n });\n return ingrName.name;\n}", "static async getRecipeById(id) {\n\t\tconst res = await this.request(`recipe/${id}`);\n\t\treturn res.recipe;\n\t}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pans and zooms to the current hex if you are playing with mobile friendly turned on
zoomToHex(assocHex, hexesToAverage = []){ if(!this.board.game.gameData.mobileFriendly){ return; } var boardRef = this.board; var cam = this.board.game.cameras.main; var targetPos = {x: assocHex.getOffSetPos().x, y: assocHex.getOffSetPos().y}; var offset = cam.originX - ...
[ "function ScaleToPhysicalPixels() {\n\tdocument.body.style.setProperty('--bg-size', (512 / window.devicePixelRatio) + 'px');\n}", "function screenZoom() {\r\n var el = document.getElementById(\"container\"),\r\n screenWidth = window.innerWidth,\r\n screenHeight = window.in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute plugins. Since plugins are meant to be called only once we empty out the array after first call
executePlugins() { if (this.executedPlugins) { this.plugins.forEach(({ fn, options }) => { if (options && options.recurring) { fn(this, false, options); } }); } else { this.executedPlugins = true; ...
[ "initPlugins() {\n pluginsToInit.forEach(plugin => this.initPlugin(plugin));\n pluginsToInit = [];\n }", "destroyAllPlugins() {\n Object.keys(this.initialisedPluginList).forEach(name =>\n this.destroyPlugin(name)\n );\n }", "_initPlugin(){\r\n this.plugins.for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tracks last set of fonts loaded Load set of custom font faces `fonts` is an object where the key is a font family name, and the value is one or more font face definitions. The value can be either a single object, or an array of such objects. If the special string value 'external' is used, it indicates the the font will...
loadFonts (fonts) { let same = (JSON.stringify(fonts) === this.last_loaded); if (fonts && !same) { let queue = []; for (let family in fonts) { if (Array.isArray(fonts[family])) { fonts[family].forEach(face => queue.push(this.loadFontFace(family...
[ "function loadFonts() {\n var list = document.fonts.values();\n var item = list.next();\n while (! item.done) {\n item.value.load();\n item = list.next();\n }\n }", "loadFonts() {\n const roboto = new FontFaceObserver('Roboto');\n const robotoCondensed = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to send a message to the Pebble using AppMessage API
function sendMessage() { //Pebble.sendAppMessage({"status": 0}); //testRequest(); //testRequestTime(); // PRO TIP: If you are sending more than one message, or a complex set of messages, // it is important that you setup an ackHandler and a nackHandler and call // Pebble.sendAppMessage({ /* Message here */ ...
[ "function sendMessage() {\r\n\tPebble.sendAppMessage({\"status\": 1}, messageSuccessHandler, messageFailureHandler);\r\n}", "function sendMessage() {\n changeLight();\n\tPebble.sendAppMessage({\"status\": 0});\n\t\n\t// PRO TIP: If you are sending more than one message, or a complex set of messages, \n\t// it is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates posted form fields.
validateFormFields() { const excludeNames = [ `redirect`, `ip_address`, `ipAddress`, `ip`, `system` ]; for (const [fieldName, fieldSettings] of Object.entries( this.formConfig.fields )) { let fieldValue ...
[ "validateFields() {\n // verificar se as informações foram preenchidas, se os campos estão vazios ou não\n const {description, amount, date} = Form.getValues()\n\n if( description.trim() === \"\" || // verificando se o description esta vazio ou\n amount.trim() === \"\" || // se o amo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This portion is to get the live price of ETH
function getLiveETHRate() { var result; var request = new XMLHttpRequest(); request.open('GET', 'https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD&api_key=45419ed9fb65b31861ccb009765d97bb619e9eccedc722044457d066cbfb0a8b', false) request.send(null); result = JSON.parse(request.responseText); ...
[ "async ethPrice() {\n\n const response = await this.ctx.curl('https://api.coinmarketcap.com/v1/ticker/ethereum/', {\n dataType: 'json',\n timeout: 1000 * 60 \n });\n const data = response.data;\n const price = data[0] && data[0].price_usd || ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disables Angular 2 tools.
function disableDebugTools() { delete context.ng; }
[ "function disableDebugTools() {\n delete context.ng;\n}", "function disableDebugTools() {\n\t delete context.ng;\n\t}", "function disableDebugTools() {\r\n\t delete context.ng;\r\n\t}", "function disableDebugTools() {\n\t delete context.ng;\n\t}", "function deactivateExtension() {\n Privly.options....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if we need to do something with sticky header
function check() { //if first heder is NOT hidden if (getTop(headers[0]) > 0) { //reset sticky header reset(); } else { //check if we need to change something change(); } }
[ "isStickyHeader() {\n return false\n }", "function checkHeader() {\n\n //y = bottom position of the original header\n var h = $(\"header\")[0].getBoundingClientRect();\n var y = h.height + h.top;\n\n //if the bottom of the original header is <50 pixels from the top,\n //then show the sticky...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plays the notification sound
function playNotificationSound() { var sound = new Audio('sound/sound.mp3'); sound.play(); }
[ "function playNotificationSound() {\n\t\t\t$('#chatAudio')[0].play();\n\t\t}", "function notification_sound(sound)\n{\n\tvar notification = new Audio('assets/sounds/'+sound+'.mp3');\n\tnotification.play();\n}", "playSoundNotification() {\n }", "function play_notification() {\n if (localStorage.comment...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback for the server list.
function getServerList(callback) { canStart = false; var xhr = new XMLHttpRequest(); xhr.open("GET", window.location.href + '/getServers', true); xhr.withCredentials = true; xhr.send(); xhr.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { ...
[ "function listServers() { \n\tlet serverItems = document.getElementsByClassName(\"serverListItem\");\n\n\twhile(serverItems.length > 0) {\n\t\tserverItems[0].parentNode.removeChild(serverItems[0]); // remove the available servers from the list each time the function is called\n\t}\n\t\n\tfor (let servers in serverL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
|hexString| must be a string of hexadecimal characters with no whitespace, whose length is a multiple of two. Returns a string spanning multiple lines, with the hexadecimal characters from |hexString| on the left, in groups of two, and their corresponding ASCII characters on the right. |asciiCharsPerLine| specifies how...
function formatHexString(hexString, asciiCharsPerLine) { // Number of transferred bytes in a line of output. Length of a // line is roughly 4 times larger. var hexCharsPerLine = 2 * asciiCharsPerLine; var out = []; for (var i = 0; i < hexString.length; i += hexCharsPerLine) { var hexLine = ''; var as...
[ "function hex_ascii(hex_string){\n\treturn split_text(2,hex_string).reduce(function(string, ele){\n\t\treturn string + String.fromCharCode(parseInt(ele, 16))\n\t},\"\")\n\n}", "function hexToHex(hexString) {\n // validate hex\n if (hexString.length < 6 ) {\n // make it 6 by double it\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FRUSTUM CULLING (DRAW CHECK) Find the intersection point by adding a vector starting from a corner till we reach the near plane params:
_getIntersection(refPoint, secondPoint) { // direction vector to add let direction = secondPoint.clone().sub(refPoint); // copy our corner refpoint let intersection = refPoint.clone(); // iterate till we reach near plane while(intersection.z > -1) { intersect...
[ "function findPlaneIntersect(mouseX, mouseY, mvPickMatrix, near, aspect, fov, type) {\n\n \tvar centered_x, centered_y, unit_x, unit_y, near_height, near_width, i, j;\n \n\tcentered_y = gl.viewportHeight - mouseY - gl.viewportHeight/2.0;\n\tcentered_x = mouseX - gl.viewportWidth/2.0;\n\tunit_x = centered_x/(gl....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates all packages to current versions.
function updatePackages() { var dataDir = getDataDirectory(); fs.readdir(dataDir, function(err, files) { files.forEach(function(file) { var name = path.basename(file, '.json'); var infoFilePath = path.join(dataDir, file); fs.readFile(infoFilePath, 'utf8', function(err, data) { if (err) { log('er...
[ "function updateAllPackages(newVersion) {\n // Update wcs-angular package\n updatePackage('./angular/projects/wcs-angular', newVersion, false);\n updateDependencyFor('./angular/projects/wcs-angular/package.json', 'wcs-core', newVersion, true);\n\n // Update wcs-formly package\n updatePackage('./angul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to validate the type of salary
function salaryCheck (salary){ if (salary === 'undefined') { alert('Please input a salary'); return false; } else if (salary <= 0 || salary > 99999999) { alert('Please input a salary from 0 until $99,999,999'); return false; } else if (isNaN(salary)){ alert('Please input a rational number'); ...
[ "validateSalary(salary) {\n return this.database.validateDecimal(salary, 8, 2)\n }", "static isValidSalary(salary) {\n const s = parseInt(salary, 10)\n if (s != salary || s < DEFAULTSCHEMA.minsalary) {\n return false\n }\n return true\n }", "function SalaryLogic() {}", "function getSalar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
3970 3971 // 3972 The picker constructor that creates a blank picker. // 3973 3974
function PickerConstructor( ELEMENT, NAME, COMPONENT, OPTIONS ) { // 3975 // 3976 // If there’s no element, return the picker constructor. ...
[ "function PickerConstructor( ELEMENT, NAME, COMPONENT, OPTIONS ) {\n\n // If there’s no element, return the picker constructor.\n if ( !ELEMENT ) return PickerConstructor\n\n\n var\n // The state of the picker.\n STATE = {\n id: Math.abs( ~~( Math.random() * 1e9 ) )\n },\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds all abundant numbers up to specified maximum.
function findAbundantNumbers(max) { const abundant = []; for (let number = 1; number < max; number++) { const properDivisors = []; const sqrt = Math.sqrt(number); for (let divisor = 1; divisor <= sqrt; divisor++) { if (number % divisor === 0) { properDivisors....
[ "function abundantNumbers(max) {\n var abundant = [];\n for (var i = 1; i <= max; i++) {\n if (Number.divisors(i).sum() > i) {\n abundant.push(i);\n }\n }\n return abundant;\n}", "function nonAbundantSums(arr, max) {\n var numbers = function() {\n var empty = [];\n for (var i = 1; i < max; ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the readable stream assembled from all the data in the internal buffers.
getReadableStream() { return new BuffersStream(this.buffers, this.size); }
[ "function bufferToStream(buffer) {\n const readableInstanceStream = new Readable({\n read() {\n this.push(buffer)\n this.push(null)\n },\n })\n return readableInstanceStream\n}", "function bufferToStream(buffer) {\n const readable = new Readable();\n \n readable._read = () => {};\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
move() Update the position of the kid based on the predicted tile
move() { //Move the kid to the determined location this.x = this.nextMoveX; this.y = this.nextMoveY; //Check in case the kid touches the edges of the map, // if so, prevent them from leaving. this.handleConstraints(); }
[ "move() {\n if (mouseX > this.x * TILESIZE + distX + TILESIZE) {\n this.x += 1;\n this.movement -= 5;\n }\n if (mouseX < this.x * TILESIZE + distX) {\n this.x -= 1;\n this.movement -= 5;\n }\n if (mouseY > this.y * TILESIZE + distY + TILESIZE) {\n this.y += 1;\n this.mov...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
; unique constraints during create; //////////////////////////////////////////////////////////////////////////////;
function creating_documents_dealing_with_unique_constraintsSuite () { let cn = `UnitTestsCollectionIndexes`; return { setUp: function() { db._create(cn, { waitForSync: true }); }, tearDown: function() { db._drop( cn); }, test_rolls_back_in_case_of_violation__array_index_w_o_dedupli...
[ "enterUniqueKeyColumnConstraint(ctx) {\n\t}", "enterUniqueKeyTableConstraint(ctx) {\n\t}", "visitUniqueKeyTableConstraint(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitUniqueKeyColumnConstraint(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "addUniqueConstraint(constraintName, columns) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print winner and increase player score
function printWinner() { alert(game.players[counter].symbol + ' is winner!'); if (counter === 0) { playerX++; // console.log("X: " + playerX); // console.log("O: " + playerO); updateScoreboard(); } else { playerO++; console.log("X: " + playerX); cons...
[ "function showWinner(winner) {\n\t\tif (winner == 'player') {\n\t\t\tplayerPoints++;\n\t\t\tgameResult.innerText = nameInput.value + \" + 1 point\";\n\t\t\tplayerPointsHeader.innerText = playerPoints;\n\t\t} else if (winner == 'computer') {\n\t\t\tcomputerPoints++;\n\t\t\tgameResult.innerText = \"computer + 1 point...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In "3d" mode sets positions of carousel items in relation to the active slide.
_handle3dMode(newIndex) { const that = this, itemsCount = that.dataSource.length; if (that.disabled || !itemsCount || that.displayMode !== '3d') { return; } newIndex = newIndex || 0; for (let i = 0; i < itemsCount; i++) { const currentPositi...
[ "_handle3dMode(newIndex) {\n const that = this,\n itemsCount = that.dataSource.length;\n\n if (that.disabled || !itemsCount || that.displayMode !== '3d') {\n return;\n }\n\n newIndex = newIndex || 0;\n\n for (let i = 0; i < itemsCount; i++) {\n con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
opens a dialog for filtering a string column
function openStringFilter(column, $header) { var bak = column.getFilter() || '', bakMissing = bak === __WEBPACK_IMPORTED_MODULE_0__model_StringColumn__["a" /* default */].FILTER_MISSING; if (bakMissing) { bak = ''; } var $popup = makePopup($header, 'Filter', "<input type=\"text\" placeholder=\"c...
[ "function openStringFilter(column, $header) {\n\t var bak = column.getFilter() || '', bakMissing = bak === model.StringColumn.FILTER_MISSING;\n\t if (bakMissing) {\n\t bak = '';\n\t }\n\t var $popup = makePopup($header, 'Filter', \"<input type=\\\"text\\\" placeholder=\\\"containing...\\\" autofo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gobbles a list of arguments within the context of a function call or array literal. This function also assumes that the opening character `(` or `[` has already been gobbled, and gobbles expressions and commas until the terminator character `)` or `]` is encountered. e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
function _gobbleArguments(context, termination, identifiersOnly) { var expr = context.expr; var length = expr.length; var ch_i, args = [], node, closed = false; var separator_count = 0; while (context.index < length) { _gobbleSpaces(context); ch_i = ...
[ "parseFuncCallArgsList(inst) {\n const exps = []\n let code_inst = inst\n let max_args = 20\n\n let exp = syntax.parseExpression(code_inst)\n if(exp) {\n exps.push(exp.parsed)\n\n while(max_args--) {\n code_inst = exp.remain\n if(!/^(\\s*,\\s*)/.test(code_inst))\n bre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This code is responsible for taking the screenshot in case of error and attaching it to the report
afterStep(uri, feature, scenario) { if (scenario.error) { driver.takeScreenshot(); } }
[ "attachScreenShotToReport(message, name){\n var screenShot =browser.saveScreenshot('./screenShot/'+name+'.png')\n addAttachment(message, new Buffer.from(screenShot, 'base64'), 'img/png')\n }", "function takeScreenShot(){\n\tdocument.getElementById(\"adfab-toolbar\").style.display = \"none\";\n\tv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serves the "GET /favicon.ico" route.
function favicon(req, res, next) { var img = gravatar('nathan@tootallnate.net', { s: 32 }); var url = photon(img, { filter: 'grayscale' }); debug('serving "/favicon.ico" -> %o', url); res.redirect(url); }
[ "function favicon(response) {\n console.log(\"Request handler 'favicon' was called.\");\n var img = fs.readFileSync('./favicon/favicon.ico');\n response.writeHead(200, {\"Content-Type\": \"image/x-icon\"});\n response.end(img, 'binary');\n}", "function favicon(req, res, next) {\n var url = gravatar('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refreshes jsp scroller on the modal body
function dialogRefreshScroller(dialogId) { var $dbody = $('#' + dialogId + ' .modal-body'); /*if (!$dbody.data('jsp')) { $dbody.jScrollPane(); } else { $dbody.data('jsp').reinitialise(); }*/ // active tab /*if($dbody.has($('.tab-content')).length) { var $active = $('...
[ "_refreshScrollerPosition() {\n this.__carouselScrollerWidth = qx.bom.element.Dimension.getWidth(\n this.__carouselScroller.getContentElement()\n );\n\n this._scrollToPage(this.getCurrentIndex());\n }", "function scrollRefresh() {\n // Method [4]\n $('.pane').not($('.scroll-applied')).w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks whether db tag number s is active
function dbIsActive (s) { s = s.replace(/[ ]+/gm,''); var s2 = "," + s + ","; var tagList = gv_Debug.tagList.replace(/[ ]+/gm,''); tagList = "," + tagList + ","; if (tagList==",," || s2==",,") return false; if (tagList.indexOf(s2)<0) return false; return true; }
[ "function tagInDB(tag){\n return false; // returns false for now. TODO: implement properly\n}", "isActive(tag) {\n return this.state.activeTags.indexOf(tag) !== -1;\n }", "tagged(tag) {\n return this._tag[tag] === true;\n }", "validTag(tag) {\n for (let i = 0; i < Strophe.XHTML.tags.leng...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endregion endregion region SHOWSELECTEDOFFER NEXT PREVIOUS Showing only one offer fromList tells whether we show this offer out of a list of offers or as a standalone offer
function showOneOffer(app, offer, sentence, fromList = false) { var body = offer.Description.slice(0, 250).replace("\n", " ") + "..." let parameters = {}; parameters[CONTEXT_PARAMETER_OfferPresented] = offer; app.setContext(CONTEXT_OfferDetail, 2, parameters) if (fromList) { let parameter...
[ "function showSelectedOffer(app) {\n let offersPresented = app.getContextArgument(CONTEXT_ListOffers, CONTEXT_PARAMETER_OffersPresented).value;\n var titlesPresented = offersPresented.map(offer => {\n return offer.Poste;\n })\n let titleSelected = app.getSelectedOption();\n\n if (titleSelected...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }