query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
update / initialize mcustomscrollbar
function initializeScrollbar() { $(".mcustomScroll").mCustomScrollbar({ theme:"dark-3", axis:"yx", advanced:{ updateOnContentResize: true } }); $(".mcustomScroll.mcustomScrollVerticalOnly").mCustomScrollbar({ ...
[ "function initCustomScrollbar() {\n $('.custom-scroll').mCustomScrollbar({});\n}", "function scrollbar(){\n\n $('.content-slide').mCustomScrollbar({\n scrollInertia: 150,\n axis :\"y\"\n });\n }", "function setScrollbar(){\n\t\t\tvar $appendEl=o.scrollAppendT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setter a list of Customers
setCustomersList(state, payload) { state.customersList = payload; }
[ "set customersList(customersList) {\n\t\treturn this._customersList = customersList;\n\t}", "get customersList() {\n\t\treturn this._customersList;\n\t}", "function setUsers(list) {\n users = list\n }", "list() {\n return customers;\n }", "function updateCustomers(){\n customerFactory.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a speak method to the Person constructor. Whenever speak is called, it should print "Hello!" to the console.
function Person(job, married) { this.job = job; this.married = married; // add a "speak" method to Person! this.speak = function(){ console.log("Hello!") } }
[ "function Person (job,married) {\n this.job = job;\n this.married = married;\n// method `speak`\n this.speak = function (){\n console.log(\"Hello\");\n };\n}", "speak () {\n var message = this.name + \" says hello!\";\n console.log(message);\n }", "speak() {\n\t\tsuper.speak();\t\t\t// C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get data from node at index
getValue(index) { let node = this.findNode(index); let data = node ? node.value : undefined; return data; }
[ "at(index) {\n var current = this.findNode(index);\n if (current) {\n return current.data;\n }\n return undefined;\n }", "getNodeAtIndex(index) {}", "at(index) {\n if (index > this.length || index < 0) { throw new Error('Index out of bounds'); }\n\n let go...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=============================================== Add / remove to Inference Class list inputs.
function addClassInput() { if (classCnt >= 9) { alert('Reached maximum supported inference classes'); return; } classCnt = classCnt + 1; let classInput = []; classInput.push(` <div class="row" id="inference-class-${classCnt}-row">\n`); classInput.push(` <div class="col input-gr...
[ "function classAddRemove(elementClassList, className, flag) {\n if (flag) {\n if (!elementClassList.contains(className)) {\n elementClassList.add(className);\n }\n } else {\n if (elementClassList.contains(className)) {\n elementClassList.remove(className);\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adding food artical and number input for entering food's quantity in tableMyPlate, if food is chosen in drop down menu
function addFood(foodCategory) { let foodCategoryID = foodCategory.id; let foodCategoryValue = document.getElementById(foodCategoryID).value; if (foodCategoryValue !== "") { document.getElementById("tableMyPlate").style.display = "block"; rowInde...
[ "function newFood() {\n //Sets variables to input values\n var meal = document.getElementById(\"meal\").value;\n var protein = Number(document.getElementById(\"protein\").value);\n var carbs = Number(document.getElementById(\"carbs\").value);\n var fats = Number(document.getElementById(\"fats\").value);\n var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the private prefix variable and its config
initConfig() { const configPrivatePrefix = atom.config.get(this._configPathPrivatePrefix); if(configPrivatePrefix) { this._privatePrefix = configPrivatePrefix; } else { atom.config.set(this._configPathPrivatePrefix, '_'); } }
[ "initializePrefix(){\n if(this._sigil && !this._prefix.includes(this._sigil))\n this._prefix = this._sigil + this._prefix;\n }", "init() {\n this._ns = DEFAULT_NAMESPACE;\n }", "initialize() {\n this.nonPrefixRegex = createNonPrefixRegex();\n this.commandHandler.initialize();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
png2rgb_arr("",rotate(times of 90 degree right),callback function)
async png2rgb_arr(path, rotate = 1, callback) { // path = "asset/LED/LED_CHEST/chest1.png" getPixels(path, function (err, pixels) { if (err) { console.log("Bad image path"); return; } let pixels_raw = Array.from(pixels.data); let img_arr = []; let width = pixels.sh...
[ "async png2rgb_arr(path, rotate = 1, callback) {\n // path = \"asset/LED/LED_CHEST/chest1.png\"\n getPixels(path, function (err, pixels) {\n if (err) {\n console.log(\"Bad image path\")\n return\n }\n let pixels_raw = Array.from(pixels.dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load one specific talk
loadedTalk(state) { return (talkId) => { return state.loadedTalks.find((talk) => { return talk.id === talkId }) } }
[ "loadFirstSong() {\n let song = GooPlayer.getSong(0)\n config.audio.src = song.src\n config.audio.load()\n GooPlayer.setSongInfo(song.title, song.artist)\n }", "function C101_KinbakuClub_RopeGroup_LoadHeather() {\n\tActorLoad(\"Heather\", \"ClubRoom1\");\n}", "_loadAudio(index) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate directional arrow to a slope
function dir2slope(direction) { console.log(`Direction is ${direction}`); switch ( direction ) { case "Flat": return(0); case "FortyFiveUp": return(45); case "FortyFiveDown": return(-45); case "SingleUp": return(90); case "SingleDown": return(-90); ...
[ "getTurnPoint(slope) {\n //get angel between the line and x\n let a = Math.atan2(slope.yEnd - slope.yStart, slope.xEnd - slope.xStart);\n //get angel between line and the line(ball center to the start of the line)\n let b = (Math.PI - a) / 2;\n let len = this.r / Math.tan(b);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to insert main img and coins to divs
function insertImages() { 'use strict'; coinImage.src = 'img/coin.png'; coin.appendChild(coinImage); headCoinImage.src = 'img/head-coin.png'; headCoin.appendChild(headCoinImage); tailCoinImage.src = 'img/tail-coin.png'; tailCoin.appendChild(tailCoinImage); }
[ "function addCoinImg() {\n switch (scoreMoney) {\n case 0:\n break;\n case 1:\n $(`<img>`).attr(`src`, `assets/images/coins/coin-1.png`).addClass(`coin coin-1`).appendTo(`.coins`);\n break;\n case 2:\n $(`<img>`).attr(`src`, `assets/images/coins/co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retreive a string from preferences, or the default string value for that key.
static getString(key) { return Preferences.get(key); }
[ "function getPreference(string, def) {\n var pref = nova.config.get(string)\n if (pref == null) {\n console.log(`${string}: ${pref} is null. Returning ${def}`)\n return def\n } else {\n console.log(`${string}: ${pref}`)\n return pref\n }\n}", "static get(key) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RATE : LETTER (STAMPED) This calculates the rate of a stamped letter or deferes the calculation to the "First Class Mail" calculator if the weight is over 3.5 oz.
function rateLetterStamped(weight) { if (weight <= 1.0) { return 0.50; } else if (weight <= 2.0) { return 0.71; } else if (weight <= 3.0) { return 0.92; } else if (weight <= 3.5) { return 1.13; } else { return rateLargeFlat(weight); } }
[ "function letterStampedRate(letterWeight) {\n if (letterWeight <= 1.0) {\n return 0.55;\n } else if (letterWeight <= 2.0) {\n return 0.70;\n } else if (letterWeight <= 3.0) {\n return 0.85;\n } else if (letterWeight <= 3.5) {\n return 1.00;\n } else {\n return large...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
call api customTask(task = "AV_StrokeNumber", delay = 0, sender = 1, rounds = 3) see helperFunctions.js direct call will send only one line
function main(){ DMessage("AV_StrokeNumber Task: Beginning"); let answers = [ [null,"Give me 10 %Crazy% fast strokes",null], [null,"Give me 20 %Crazy% fast strokes",null], [null,"Give me 30 %Crazy% fast strokes",null], [null,"Give me 10 %Crazy% fast strokes",null], [null,"Give me 20 %Crazy% fast ...
[ "function main(){\n\tDMessage(\"AV_StrokeNumberGliter1 Task: Beginning\");\n\tlet answers = [ \n [null,\"Give me 10 %Crazy% fast strokes\",null],\n [null,\"Give me 20 %Crazy% fast strokes\",null],\n [null,\"Give me 30 %Crazy% fast strokes\",null],\n [null,\"Give me 40 %Crazy% fast strokes\",null],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Null$prototype$toString :: Null ~> () > String
function Null$prototype$toString() { return 'null'; }
[ "function nullToString(a) {\n return a === null ? '' : a;\n}", "function _nullCoerce() {\n return '';\n}", "function _str(o) \n{ if (o===null) return \"null\";\n return o.toString_0(); \n}", "function toString(val){\n return val == null ? '' : val.toString();\n }", "function nullToStr(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
log the failed download
function onFailed(error) { console.log(`Download failed: ${error}`); }
[ "function onFileDownloadFail(error, index) {\n\tconsole.log('file not downloaded. Error: ' + JSON.stringify(error));\n\tfileDownloadError = true;\n\tfileDownloadErrorList.push(downloadingArr[index]);\n\n\tdownloadingArr.shift();\n\tunloadProgressDownloader(index);\n\n\t//filesToDownload.shift();\n\t//updateFileDown...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: main Purpose: Control Processes 1) Display Program Directions 2) Get Template File Name 3) Get Output File Name 4) Process Template breakout questions and output skeleton 5) Ask Questions store results in array 6) Write Output file substitute answers in placeholders 7) Close File Stream 8) Clean up local stor...
async function main() { // Process 1) Display Program Directions displayDirections(); // Process 2) Get Template File Name if (argv.length < 3) { // A template file was not passed, verify default is okay to use const answer = await inquirer.prompt([ { type: "input"...
[ "function writeQuestion(){\n\t//All questions and relatived options\t\t\n\tvar questionfile1_question=new Array(\"Aðalbækistöðvar\",\"Aðalréttur\",\"Afsökunarbeiðni\",\"Aðfangadagskvöld\",\"Aðferðafræði\",\"Aðframkominn\",\"Aðgangsharður\",\"Aðgerðaleysi\",\"Aðgöngumiði\",\"Aðhlátursefni\",\"Aðildarumsókn\",\"Aðkom...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loop to move queue if any items still exists
moveQueue() { if (this.localQueue.length > 0) { const currentEntry = this.localQueue[0]; switch (currentEntry[0]) { case "add": addTrie(currentEntry[1]); break; case "remove": removeTrie(currentEntry[1]); break; ...
[ "function advanceQueue () {\n //move the queue if possible\n var index = earliest - 1;\n while (1) {\n\n if (queue[index] === 'pending') {\n break;\n\n } else if (queue[index] === 'failed') {\n log.warn('retry failed ledger:', index);\n getLedger(index);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get selected entity Ids
function selectedEntityIds(scope) { var arr = []; var selectedEntities = getSelectedEntities(scope); if (selectedEntities && selectedEntities.length > 0) { for (var i = 0; i < selectedEntities.length; i++) { if (selectedEntities[i]) { ...
[ "get selectedIds() {\n return this.selected.map(target => target.dataset.id)\n }", "function setSelectedEntityCheckBoxItems() {\n // Return if we don't have the entities\n // or the selected entity ids yet.\n if ($scope.entities.length === 0) {\n $scope.entityCh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Problem: you will be giev an array of several arrays that each contain integers and your goal is tpo write a function that will sum up all the numbers in all the arrays. Solve with and without using reducer(). Answer: we will first loop through the outer array and then through the each inner array adding up all the num...
function sumOfArrays(arr){ // initiat variable to store the final result let sum = 0; //loop through outer array for(let i = 0; i < arr.length; i++){ //loop through inner arrays for(let j = 0; j < arr[i].length; j++){ sum += arr[i][j] } } return sum; }
[ "function sumOfSums(arr) {\n var reducer = (sum, currentEl) => sum + currentEl;\n var newArrSum = 0;\n for (var i = 0; i < arr.length; i++) {\n var currentArr = arr.slice(0, i+1);\n newArrSum += currentArr.reduce(reducer);\n };\n return newArrSum;\n}", "function intermediateSums(arr){\n\n}", "functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks to see if a ship has sunk
checkSink(ship){ if(ship.isSunk() == true){ // adds ships to shipsSunk array this.shipsSunk.push(ship) } }
[ "function isSunk(ship) {\n\t// Return whether or not a ship has been sunk\n\tfor (i = 0; i < ship.pos.length; i++) {\n\t\tif (ship.pos[i] != 2) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}", "checkShipSunk(c) {\n for (let i = 0; i < this.ships.length; i++) {\n if (this.ships[i].isHit(c)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Match existing likes with event sessions before rendering. Also tags days with at least one like to toggle day visibility.
function preRenderEvent() { if (likes.length > 0) { for (var day in scheduleData.days) { if (scheduleData.days.hasOwnProperty(day)) { let sessions = scheduleData.days[day]['sessions']; scheduleData.days[day]['haveSessions'] = false; for (var sess in sessions) { let session...
[ "function addEventsForLikes () {\r\n const spanLikes = document.querySelectorAll('span.likes');\r\n for (let spanLike of spanLikes) {\r\n spanLike.addEventListener('keyup', enterUpdateLikes);\r\n }\r\n const iconLikes = document.querySelectorAll('i.likes');\r\n for (let iconLike of iconLikes) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is Power Of Two / Write a function that returns YES if a number is a power of 2, and NO otherwise.
function isPowerOfTwo(num) { // YOUR CODE HERE if (num && (num & (num - 1)) === 0) return "YES"; else return "NO"; /* explain (num & (num - 1)) : The bitwise AND operator (&) returns a 1 in each bit position for which the corresponding bits of both operands are 1s.(read it at MDN). example (num=5):...
[ "function isPowerOfTwo(n){\r\n //.. should return true or false ..\r\n if (typeof n !== 'number') \r\n return 'Not a number'; \r\n\r\n return n && (n & (n - 1)) === 0;\r\n}", "function isPowerOfTwo(n){\n return Math.log2(n) % 1 === 0;\n}", "function isPowerOfTwo(n){\n //.. should return true or f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if a given instrument id is present in position table
function validateInstrumentId(instrument_id, callback) { var query_string = 'SELECT instrument_id,position FROM position WHERE instrument_id=' + instrument_id; connection.query(query_string, function (error, result) { if (result) { console.log(result); return callback(null, result); } else { ...
[ "function markerExists(id) {\n\tif (typeof markerIndex[id] != \"undefined\" && markerIndex[id].length > 0)\n\t\treturn true;\n\telse\n\t\treturn false;\n}", "exists(id) {\n let sqlRequest = \"SELECT (count(*) > 0) as found FROM equipement WHERE id=$id\";\n let sqlParams = {$id: id};\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the text content of the passed html, stripping all tags
function getContent(html) { return html.replace(/<[^>]*>/g, ''); }
[ "textFromHtml (html) {\n\t\t// attempt to parse out some basics here, but mostly ignore the html\n\t\treturn this.htmlEntities.decode(\n\t\t\thtml\n\t\t\t\t.replace(/<p>(.*?)<\\/p>/ig, (match, text) => { return text + '\\n'; })\n\t\t\t\t.replace(/<div>(.*?)<\\/div>/ig, (match, text) => { return text + '\\n'; })\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Go through all cognito accounts on the user pool, and set the "location" attribute in the corresponding application DB to "custom:location" when "location" is not already defined.
function bulkUpdateLocations() { var bulk = res.models.Application.collection.initializeOrderedBulkOp(); let paginationToken = null; let updateUser = (sub, location) => bulk.find({ 'user.id': sub, "location": { "$exists": false } }).update({ '$set'...
[ "_setupAwsCognitoConfig() {\n // @todo: set retries in a smarter way...\n AWS.config.maxRetries = 3;\n\n let cognitoRegion = Token.getRegionFromIdentityPoolId(this._identityPoolId);\n\n AWS.config.update({\n cognitoidentity: {region: cognitoRegion},\n cognitosync: {region: cognitoRegion},\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets slider to desired speed all requests to change speed funnel through here
function setSlider(slideSpeed) { slideSpeed = parseFloat(slideSpeed); // verify speed is in range slideSpeed = slideSpeed > maxSpeed ? maxSpeed : slideSpeed < minSpeed ? minSpeed : slideSpeed; slider.value = slid...
[ "setSliderSpeed() {\n let sliderSpeed = (this.speed / 1000)%60;\n this.slidertrack.css('transition', `transform ${sliderSpeed}s cubic-bezier(0.645, 0.045, 0.355, 1)`);\n }", "function setSpeed() {}", "changeSpeed() {\n this.speed = document.getElementById('slider').value;\n docume...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the x component of the radius at given y component
function getCircleXFromY(y, circCenterX, circCenterY, radius){ return Math.round(Math.sqrt(Math.pow(radius, 2) - Math.pow(y - circCenterY, 2))) + circCenterX; }
[ "getX(y) {\n let x = ((((y - this.y1) * (this.x2 - this.x1)) / (this.y2 - this.y1)) + this.x1).trim(9);\n if (isNaN(x) || x.isBetween(this.x1, this.x2)) return x;\n }", "function getCircleYFromX(y, circCenterX, circCenterY, radius){\n return Math.round(Math.sqrt(Math.pow(radius, 2) - Math.pow(x - circCe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to create a VML tag
function vml(tag, attr) { return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr); }
[ "function vml(tag, attr) {\n return createEl(\"<\" + tag + ' xmlns=\"urn:schemas-microsoft.com:vml\" class=\"spin-vml\">', attr);\n }", "function vml(tag, attr) {\n\t return createEl('<' + tag + ' xmlns=\"urn:schemas-microsoft.com:vml\" class=\"spin-vml\">', attr)\n\t }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes baseline suffix. By default this is the latest tag or latest commit. If
async function handleBaseline() { let baselineSuffix; if (program.baseline === true) { // regular --baseline that creates a baseline against latest tag, if commit is same try { chilp.config({ output: false, stripLastReturn: true }); const cleanWorkDir = (await chilp.spawn(...
[ "get baseline() {\n return this._baseline\n }", "get suffix() {\n return this._suffix !== undefined ? this._suffix : this._span.suffix;\n }", "get suffix() {\n if (this.children.length) {\n // Everything after the last child\n return this._getSubstring(this.children[th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create function "showNumbers()" Accepts a number as parameter, it will return all the numbers up to that number telling if it is odd or even Example: If we pass to that function 3 as argument, it should return the following. 0 "EVEN" 1 "ODD" 2 "EVEN" 3 "ODD"
function showNumbers(limit) { for (i = 0; i < limit + 1; i++) { if (i % 2 === 0) console.log(i , "EVEN") else console.log(i , "ODD") } }
[ "function showNumbers(number) {\n for (let i = 0; i<=number; i++)\n {\n console.log(i, i % 2 === 0 ? 'EVEN' : 'ODD' );\n }\n}", "function showNumbers(limit) {\n\n for(let jj=0; jj<=limit; jj++) {\n console.log(jj, (jj%2==0) ? \"EVEN\" : \"ODD\");\n }\n}", "function oddNumbersFrom1to20()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Give it the raw typedef options passed to nopt, returns a typical usage help text.
function help(types, shorts, opts) { return new Helper(types, shorts, opts); }
[ "function help_1(option) /* forall<a> (option : option<a>) -> string */ {\n return option.help;\n}", "function cmd_Help() {\n\t\t\n\t}", "async _run_help() {\n this._options.usage();\n }", "_showHelp() {\n const sections = [\n {\n header: 'HMR_ReduxMapper',\n content: 'This is a m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========Track take point and update the input box and click or next button ==============
function TakeAPoint(data) { TakePointSound(); var x = {"X": data.X, "Y":data.Y, "Z": data.Z, "I": data.I, "J": data.J, "K": data.K, "ANGLES": data.ANGLES, "RawPositions" : data.RawPositions}; elem = document.getElementById("pointsTakenId2"); switch(MeasureStep) { case 0: p...
[ "function update_Points() {\n\t\tvar txt_points = document.getElementById(\"txtPoints\");\n\t\tif (loc_visited[current_loc] === 0) {\n\t\t\tpoints += 5;\n\t\t\ttxt_points.value = points;\n\t\t}\n\t}", "_updatePointCounter (points, total, object) {\n setTimeout(function () {\n document.querySelector('#poin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns this effect if environment is on the right, otherwise returns whatever is on the left unmodified. Note that the result is lifted in either.
function onRight(__trace) { return self => (0, _join.joinEither_)((0, _environment.environment)(), self, __trace); }
[ "function right() {\n return self => joinEither_((0, _environment.environment)(), self);\n}", "function left() {\n return self => joinEither_(self, (0, _environment.environment)());\n}", "function onLeft(__trace) {\n return self => (0, _join.joinEither_)(self, (0, _environment.environment)(), __trace);\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rebuilds the haze set's buffers
Rebuild() { // TODO: Rebuild buffers }
[ "function rebuildMaze() {\n clear();\n allCellsGrid.length = 0;\n rowColsNum = boardSizeSelector.value();\n halfWindow = window.innerWidth * 0.5;\n visitedCellsStack = [];\n playable = false;\n w = halfWindow / rowColsNum;\n\n //recreate cells\n for (var j = 0; j < rowColsNum; j++) {\n for (var i = 0; i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
. Number negate :: ValidNumber > ValidNumber . . Negates its argument. . . ```javascript . > S.negate (12.5) . 12.5 . . > S.negate (42) . 42 . ```
function negate(n) { return -n; }
[ "function negateNumber() {\n setIsPositive(!isPositive);\n }", "function invert_negatives(number){\n var result = null;\n if(number > 0){\n result = number * (-1);\n } else if (number){\n result = number;\n } else {\n result = false;}\n return result;\n}", "function oppos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fire eventType on element.
function eventFire( element, eventType ){ if ( element.fireEvent ) { element.fireEvent( 'on' + eventType ); } else { var eventObject = document.createEvent( 'Events' ); eventObject.initEvent( eventType, true, false ); element.dispatchEvent( eventOb...
[ "function eventFire(css, etype, text=\"\", css_sib=\"\", element=false) {\n var el;\n if (typeof(css) == \"string\") {\n if (css_sib !== \"\") {\n el = findElementSibling(css, css_sib, text, element);\n } else if (text !== \"\") {\n el = findElementByText(css, text, element...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the given text on canvas centered on a given point. If limits are done, given limits must be at least minNameSize wide
function writeName(text, drawingResult){ for (var i=0; i < drawingResult.length; i++){ var limit=drawingResult[i]["limit"]; var gravity=drawingResult[i]["gravity"]; if (!limit || (((limit["maxX"]-limit["minX"]) >= minNameSize) && ((limit["maxY"]-limit["minY"]) >= minNameSize)...
[ "function text_at(text, pos, w)\n{\n var text = draw.text(text);\n text.font({'font-size':200}); \n // center text\n var bbox = text.bbox();\n \n text.move(pos[0]-bbox.w/2,pos[1]-bbox.h/2);\n \n text.scale(0.005*w, 0.005*w);\n return text;\n}", "function drawName(x, y, name){\n context.font = \"b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send message to the popup to rerender the whitelist
notifyWhitelistChanged () { chrome.runtime.sendMessage({'whitelistChanged': true}) }
[ "function updatePopup() {\n chrome.runtime.sendMessage({\n msg: \"data_update\",\n data: {\n url: window.location.hostname,\n cookies: cookies,\n storage: storage,\n cors: cors,\n policy: policyResult,\n type: 'update'\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the output window
function clearOutput () { mainView.send('output-clear'); }
[ "function clearOutput() {\n outputDiv.hide().children().remove();\n outputDivOpen = false;\n }", "function clearScreen() {\n $('#output').html('');\n}", "function clearOutput() {\n var output = getOutput();\n output.innerHTML = \"\";\n}", "function _clearWindow () {\n _trace.empty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function add class 'cur' to dot
function chageCur(idx) { var left = 0, nxIdx = 0; $('.slick-dots .dot.cur').removeClass('cur'); if (idx !== undefined) { $($('.slick-dots .dot')[idx]).addClass('cur'); return null; } else { left = Math.abs(ge...
[ "function setDotClass() {\n if (allDots[preIndex].classList.contains(\"currentDot\"))\n allDots[preIndex].classList.remove(\"currentDot\");\n allDots[currentPictureIndex].classList.add(\"currentDot\");\n}", "function addDocActiveClass() {\n $('.carousel__dots li').removeClass('carousel__dot--activ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of prices filtered by a list of restrictions. The restrictions are given in the form of a list of objects which each have a 'key' property and a 'restriction' value. The 'key' property refers to any of the keys on a price object (instanceType, region, zone, type, price). For nonprice restrictions, either ...
getPrices(restrictions = []) { if (!this.prices) { throw new Error('We do not have pricing data yet'); } let prices = this.prices.slice(); return prices.filter(price => { for (let {key, restriction} of restrictions) { if (key === 'minPrice' || key === 'maxPrice' || key === 'price') ...
[ "filterByPrice(properties, price, minFlag) {\n // since max price can only be there if a min is already there, we use min to grab filter and concat lists\n var propertiesToFilter = properties.filter(property => property.rental_rate_min != null);\n var propertiesToConcat = properties.filter(property => prop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Two magic things happen here: through `this.seq` we force dynamic imports to be processed _sequentially_, this is because of we append a timestamp to each import url to manually bust the module cache, this has a nasty drawback: memory leak, cf.
async import(path) { this.seq = this.seq.then(() => { debug(`Importing %s`, path); return import(`${path}?bust=${Date.now()}`); }); return this.seq; }
[ "_createImports() {\n\t\tthis.assets = {\n\t\t\tcss: '',\n\t\t\tjs: ''\n\t\t};\n\n\t\tlet order = [\n\t\t\t'runtime', // Webpack runtime - used only in dev\n\t\t\t'vendor', // All vendor code - used only in dev\n\t\t\t'client' // In prod, all client code but in dev, only our code\n\t\t];\n\n\t\tconst assetsConfig =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function draws an angled line. The angle is cosidered to be clockwise
function lineByAngle (ctxt, x, y, angle, length) { ctxt.arc(x, y, length, angle, angle, false); ctxt.lineTo(x, y); ctxt.arc(x, y, length, angle, angle, false); }
[ "function rotateLine() {\n// center the graphic on the canvas\n translate(405, 282);\n// set rotation\n rotate(rotateBy);\n// draw the line\n line(0, 25, 0, 250);\n// increase rotation angle by 1 for next time\n rotateBy += 1;\n }", "function drawLineAtAngle(r, angle, xOffset, yOffset){\r\n if(angle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears outcomes on this client and returns them.
_clearOutcomes() { const outcomes = this._outcomes; this._outcomes = {}; return Object.keys(outcomes).map(key => { const [reason, category] = key.split(':') ; return { reason, category, quantity: outcomes[key], }; }); }
[ "_clearOutcomes() {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
after a g icon is removed, resets cell lock state, reanimates the insulin key
function screen4_relockCell(){ screen4_killPulses(); exportRoot.screen4.arrow1.visible=false; exportRoot.screen4.arrow2.visible=false; //lock the cell! screen4_cell_locked=true; screen4_cell.gotoAndStop(0); //cell starts at its first state (locked) //anim of insulin key appearing... ...
[ "unflagCell(x, y) {\n this.getCell(x, y).flag = false;\n this.numFlagged--;\n }", "function unselectMarkerAndCell() {\n var oldSelectedEventId = localStorage.getItem('selectedEventId');\n \n if (oldSelectedEventId != null) {\n var oldSelectedMarker = eventIdToMarker[oldSelectedEventId];\n var oldS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the factory information by factory Id.
updateFactory(factoryId) { let promise = this.codenvyAPI.getFactory().fetchFactory(factoryId); promise.then((factory) => { this.factory = factory; this.cheNotification.showInfo('Factory information successfully updated.'); }, (error) => { this.cheNotification.showError(error.data.message ...
[ "updateFactory() {\n this.props.ws.send(JSON.stringify({\n event: \"updateFactory\",\n name: this.state.name,\n uid: this.props.factory.uid\n }))\n }", "getFactoryById(factoryId) {\n return this.factoriesById.get(factoryId);\n }", "setFactoryContent(factoryI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read user data from store
static async read(){ try { //read from store const data = await store.get(UserStore.KEY); //update cahched value _userData = data; return (data); } catch(error){ console.error('Failed to read user data from store.'); throw error; }; }
[ "function getUserData() {\n var storedUserData = JSON.parse(localStorage.getItem(\"myDashUserData\") || \"[]\");\n userData = storedUserData;\n getStockInfo(userData[0].stocks);\n getCurrWeather(userData[0].weatherCity);\n getNewsArticles(userData[0].newsSource, userData[0].newsCat);\n }", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
5)Write a printString function that takes firstName, lastName, and age as parameters and returns a string like the following:
function printString(fName,lName,age){ fName = "Jane "; lName = "Doe "; age = 100 return(fName,lName,age); }
[ "function printString(firstName = \"kat\" ,lastName = \"Stark\" ,age = 40) {\n return \"Hi\" + \" \" + firstName + \" \" + lastName + \" \" + \"how does it feel to be\" + \" \" + age \n \n}", "function printString(first = \"Jane\", last = \"Doe\", age= 100) {\r\n return `Hi ${first} ${last}, how does it...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts the host metadata configuration from the AST metadata object.
function toHostMetadata(metaObj) { if (!metaObj.has('host')) { return { attributes: {}, listeners: {}, properties: {}, specialAttributes: {}, }; } var host = metaObj.getObject('host'); var specialAttr...
[ "function compileHostMetadata(meta) {\n const hostMetadata = new DefinitionMap();\n hostMetadata.set('attributes', toOptionalLiteralMap(meta.attributes, expression => expression));\n hostMetadata.set('listeners', toOptionalLiteralMap(meta.listeners, literal));\n hostMetadata.set('properties', toOptional...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
conditional rendering of number of bathrooms
renderBathrooms () { if (this.props.listing.bathrooms === 1) { return ( <div> <span className='listing-space-detail'>🛀 </span> <span className='listing-space-detail'>{`${this.props.listing.bathrooms} bathroom`}</span> </div> ) } else { return ( <di...
[ "renderBeds () {\n if (this.props.listing.beds === 1) {\n return (\n <div>\n <span className='listing-space-detail'>🛌 </span> \n <span className='listing-space-detail'>{`${this.props.listing.beds} bed`}</span>\n </div>\n )\n } else {\n return (\n <div>\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=================================================================== from functions/fs/DirExists.java =================================================================== Needed early: Builtin Instruction Needed late: System_fs ArcObject ASYNC PORT NOTE: This had to be converted to an asynchronous design.
function DirExists() { }
[ "function dirExistsSync( d ) {\n\ttry { fs.statSync( d ).isDirectory() }\n\tcatch( er ) { log(er); return false }\n\t\n\treturn true;\n} // end dirExistsSync()", "function existsDir(path){\n\t return new Promise(function(resolve,reject){\n\t dir(path).then(\n\t function(dirEntry){\n\t reso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the game directory
gameDir() { }
[ "gameDir() {\n return __dirname;\n }", "setGameDir(dir) { }", "get outputDirInServer() {\n return path_1.default.resolve(this.outputDir, './server');\n }", "function getCacheDir() {\n var cacheDir = [Config.cache, 'screenshots'].join('/');\n return fs.realpathSync(cacheDir);\n}", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate and save events to the Feature Document in the database
function iterGeoData(events, done) { events.forEach(function(item, ix, arr) { var len = arr.length - 1; if (len === 0) { done(); } else if (ix < len) { saveGeoData(item, function() { log('Saved') }); } else if (ix === len) { saveGeoData(item, function() { ...
[ "function saveEventPriceArray (req,res) {\n //console.log('POST /api/event')\n //console.log(req.body)\n let docsArray=[];\n for (var key in req.body) {\n let doc=req.body[key]\n let eventPrice = new EventPrice()\n eventPrice.price = doc.price\n eventPrice.discount = doc.discount\n eventPrice.dis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a WMS tile layer to the map.
function addWMSTileLayer({ title = 'wms', url, params, visible = true, base = false, attribution = '', }) { const attributions = [attribution]; const source = new TileWMS({ url, params, attributions, }); const layer = new TileLayer({ title, source, visible, type: base ? 'base' : 'n...
[ "function addWMSLayer(name, url, layersWMS, type, styleId, bbox, isTemp, timeStamp) {\n\tif (name && url && layersWMS) {\t\t\n\t\tvar colorPanel;\n\t\tfor (var i=0; i<mapLayers.length; i++) {\n\t\t\tif (mapLayers[i].name == name) {\n\t\t\t\tbbox = mapLayers[i].imageBbox;\n\t\t\t\tcolorPanel = mapLayers[i].icon;\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inject resource list into document
function injectResourceList(resourceListHTMLString) { return $("#resource-list").html(resourceListHTMLString); }
[ "function addListReference(listRef){if(listRef.id){listReferences.byId[listRef.id]=listRef;}listReferences.byApiNames[`${listRef.objectApiName}:${listRef.listViewApiName}`]=listRef;}", "function addNewResource(res) {\n //add the predefined resource to the history resource list\n if (resource...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IMPOSTA E MOSTRA IL MODAL PER LE NOTIFICHE REQUEST
function notificaRequest() { //imposta il contenuto del modal $('#modalHeader').html('Nuova richiesta di intervento'); $('#modalBody').html('<p>Un utente richiede il tuo preventivo. Vuoi visualizzare la sua richiesta?</p>'); $('#modalFooter').html('<a href="javascript:accendiSeNotifica()" class="btn" data-dismiss="...
[ "showModalAfterRequest(data, element) {\n let that = this;\n that.request(data.location).then(res => {\n that.response(res).then(() => {\n let options = that.jsonFilter(Object.assign(data, {\n width: res.sets.width || data.width || undefined,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MySQL AJAX Reload MySQL Database without reloading the webpage
function refreshMySQL($str="") { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { ...
[ "function reloadBusinessTable(){\n tblBusiness.ajax.reload();\n}", "function lib_data_html_update_db()\r\n{\r\n if (window.XMLHttpRequest)\r\n {// code for IE7+, Firefox, Chrome, Opera, Safari\r\n var xhr = new XMLHttpRequest();\r\n }\r\n else\r\n {// code for IE6, IE5\r\n var xhr = new ActiveXObjec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lazily makes an instance of the token redis provider
makeTokenRedisProvider(config) { if (!this.application.container.hasBinding('Adonis/Addons/Redis')) { throw new utils_1.Exception('"@adonisjs/redis" is required to use the "redis" token provider'); } const Redis = this.application.container.use('Adonis/Addons/Redis'); return ...
[ "_createRealRedis() {\n this.redis = redis.createClient(config.get('redis.option'));\n this.redis.getAsync = promisify(this.redis.get);\n this.redis.setAsync = promisify(this.redis.set);\n this.redis.delAsync = promisify(this.redis.del);\n this.redis.publishAsync = promisify(this.redis.publish);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepares the data to be plotted by sorting and filtering for the top 10 values the data is sent to the following functions: buildHBar & buildBubble.
function sortFilterData(d){ var sample_values = d['sample_values'] var otu_ids = d['otu_ids'] var otu_labels= d['otu_labels'] sample_values = sample_values.sort((a, b) => b - a).slice(0,10); otu_ids = otu_ids.sort((a, b) => b - a).slice(0,10); otu_labels = otu_labels.sort((a, b) => b - a).slice...
[ "function dataUpdate() {\n if(filterData[0]) {\n data = [\n {\n text: \"be easy to use when placing an order\",\n value1: parseInt(\n filterData[0][\"Top1_IDS 5 - … easy to use\"].slice(0, -1)\n ),\n value2: filterData[0][\"PreviousTop1EasyToUse\"]=== undefined?0:filt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggles the superscript formatting of selected contents.
toggleSuperscript() { if (!this.owner.isReadOnlyMode) { let value = this.selection.characterFormat.baselineAlignment === 'Superscript' ? 'Normal' : 'Superscript'; this.selection.characterFormat.baselineAlignment = value; } }
[ "toggleSuperscript() {\n if (this.owner.editor) {\n this.owner.editor.toggleSuperscript();\n }\n }", "function toggleSuperscript(editor) {\n execCommand_1.default(editor, \"superscript\" /* Superscript */);\n}", "toggleSubscript() {\n if (!this.owner.isReadOnlyMode) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to build a list of entities from a collection of objects
function buildEntitiesFromMapAndCollection(type, map, collection) { var promise = new Util.Promise(); var entities = []; function nextObject(i) { if (i < collection.length) { buildEntityFromTypeMapAndObject(type, map, collection[i]) .d...
[ "addEntities(objs) {\n const ret = []\n for (let i = 0; i < objs.length; ++i) {\n const entity = this._constructEntity(objs[i])\n ret.push(entity)\n }\n for (let j = 0; j < objs.length; ++j) {\n this._initializeEntity(ret[j], objs[j])\n }\n return ret\n }", "static hydrateMany (m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
aadhar validation for dose 1
function validateaadhar() { let aadhar = document.getElementById('txtadhaar'); if (!isvalidaadhar(aadhar.value.trim())) { onerror(aadhar, "aadhar must be 12 numbers"); return false; } else { onsuccess(aadhar); document.queryselector('#check-success').style.display = "blo...
[ "function validateTaoBV() {\n var tieude = document.forms[\"taobv\"][\"tieude\"].value;\n var id_khoahoc = document.forms[\"taobv\"][\"id_khoahoc\"].value;\n \n if(tieude == \"\" || tieude.length < 5){\n document.getElementById(\"demo\").innerHTML = \" Không được để trống , dữ liệu phải trên 5 kí tự !!!\";\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the closest asset contract address for a given entering player position
function find_closest_asset_address(player_enter_x, player_enter_z) { var closest_distance = 9999999; var closet_coor = null; // for each coordinate our coordinate map for (var i = 0; i < coordinate_map.length; i++) { var coor = coordinate_map[i] // determine the distance from that co...
[ "function closestO(shipp){\n let ans=999;\n let val;\n for(const player of game.players.values()) {\n if(player.id!==me.id){\n if(gameMap.calculateDistance(shipp.position,player.shipyard.position)<ans){\n ans=gameMap.calculateDistance(player.shipyard.position,shipp.position);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Only output interactive flags if we have selections defined somewhere in our model hierarchy.
function interactiveFlag(model) { if (!model.component.selection) return null; var unitCount = keys(model.component.selection).length; var parentCount = unitCount; var parent = model.parent; while (parent && parentCount === 0) { parentCount = keys(parent.component.selection).length; par...
[ "function interactiveFlag(model) {\n if (!model.component.selection) return null;\n const unitCount = keys(model.component.selection).length;\n let parentCount = unitCount;\n let parent = model.parent;\n while (parent && parentCount === 0) {\n parentCount = keys(parent.component.selection).lengt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the chord progression and tweet message KEEP IN MIND THAT NUMBERS ARE ONE LESS THAN ACTUAL MUSICAL INTERVAL OR NOTE (INCLUDING KEY)
function generateProgression() { //console.log('Main function runs'); //Every whole note in the musical scale. var notes = ["A","B","C","D","E","F","G"]; var romanNumerals = ["I","ii","iii","IV","V","vi","vii"]; //Picks a random key 1-7. Corresponds to notes var keyNum = Math.floor(Math.random() * 7); var keyN...
[ "detectChords(recTrack) {\n let beatLength = 60000 / metronome.getTempo();\n if (recTrack.getNotes().length == 0) return;\n let endOfChord = undefined;\n let tempChord;\n\n recTrack.getNotes().forEach((item, i) => {\n //loops through the notes\n if (endOfChord === undefined) {\n //fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register service instance in Consul using the Consul API > return a promise
function consulRegister(fullSvcName, svcAddress, svcPort, svcTags, svcId) { return new Promise((resolve, reject) => { /* Options ======================================================================== name (String): service name port (Integer, opti...
[ "async register(opts) {\n if (typeof opts === \"string\") {\n opts = { name: opts };\n }\n\n opts = utils.normalizeKeys(opts);\n opts = utils.defaults(opts, this.consul._defaults);\n\n const req = {\n name: \"agent.service.register\",\n path: \"/agent/service/register\",\n type: \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
limits the source hash to only have keys found in the valves hash (if present)
function restrict(source, valves){ if(!valves) return source; const result = {}; for(const k in valves){ result[k] = source[k]; } return result; }
[ "function _mergerIf(key, target, source) {\n if (!isValidKey(key)) {\n return;\n }\n var tval = target[key];\n var sval = source[key];\n if (isObject(tval) && isObject(sval)) {\n mergeIf(tval, sval);\n } else if (!Object.prototype.hasOwnProperty.call(target, key)) {\n target[key] = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize keyspace sets the ipns record for the given key to point to an empty directory
initializeKeyspace(privKey, value, callback) { this.publisher.publish(privKey, value, callback); }
[ "async initializeKeyspace (privKey, value) { // eslint-disable-line require-await\n return this.publish(privKey, value, IpnsPublisher.defaultRecordLifetime)\n }", "async initialiseKeys() {}", "static initCacheKey(key)\n\t{\n\t\t// Basically creating directory in which cache key will be stored\n\t\treturn ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a datamanager using Dummy Data for running tests.
static newWithData(dummyGlobal, dummyPacks) { const manager = new DataManager(); manager.globalDataInternal = dummyGlobal || manager.globalDataInternal; Object.assign(manager.packDataComplete, dummyPacks); return manager; }
[ "function DataManager() {}", "function DataManager () {\n\tthis._dataDictionary = {};\n}", "function createTestData () {\n\n self.testData = [];\n var i, max;\n\n for (i = 0, max = 10; i < max; i += 1) {\n\n var rec = i + 1;\n\n self.testData.push(\n {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a path is the parent of another.
isParent(path, another) { return path.length + 1 === another.length && Path.compare(path, another) === 0; }
[ "isParentOf(otherPath) {\n const other = otherPath instanceof PathInfo ? otherPath : new PathInfo(otherPath);\n if (other.path === '') {\n return false;\n } // If the other path is the root, this path cannot be its parent\n return this.equals(other.parent);\n }", "functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if there's a cached package, and if so whether it's the latest available
function checkCachedPackage(db, packageName, callback, errback) { var transaction = db.transaction([METADATA_STORE_NAME], IDB_RO); var metadata = transaction.objectStore(METADATA_STORE_NAME); var getRequest = metadata.get('metadata/' + packageName); getRequest.onsuccess = functio...
[ "function checkCachedPackage(db, packageName, callback, errback) {\n var transaction = db.transaction([METADATA_STORE_NAME], IDB_RO);\n var metadata = transaction.objectStore(METADATA_STORE_NAME);\n\n var getRequest = metadata.get(\"metadata/\" + packageName);\n getRequest.onsuccess = fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the car angle in relation to the arm1 horizontal angle
getCarAngle() { let deltaX = this.vehicle.carLocation[0] - this.craneX; let deltaY = this.vehicle.carLocation[1] - this.craneZ; let angle = Math.atan(deltaX / deltaY); let finalAngle = angle - this.arm1HorizontalAngle; this.carInitialAngle = this.arm1HorizontalAngle - finalAngle...
[ "function calculateOrientationAngle(acceleration) {\n return ((Math.acos(acceleration) * 2 / Math.PI) - 1);\n}", "calculateAngle() {\n const normalizedData = this.gameOver ? ((this.time / -this.terminalVelocity) / 2) + 0.5 : this.time / -this.terminalVelocity;\n this.angle = this.gameOver ? normali...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a scalar 's1' and a vector 'v1', returns 'v1' scaled by 's1'.
function scale( s, v1 ) { return [ s * v1[0], s * v1[1], s * v1[2] ]; }
[ "function scaleVector(v, s) {\n v[0] *= s;\n v[1] *= s;\n return v;\n }", "function scaling(s0, s1) {\n let v2 = angle(s0, s1) / 2,\n tanv2 = tan(v2);\n return sqrt(tanv2 * tanv2 + 1)\n }", "static scale(v, s){\n\t\t\treturn new Vector(v.x*s, v.y*s, v.z*s);\n\n\t}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funcion que valida segun la edad
function validarEdad(){ var valEdad = recopilarinfotextbox("txtEdad"); if (valEdad>=12){ //alert(valEdad+" edad mayor de 12"); desactivarelementoFormulario("ceo"); document.getElementById("ceo").value = "no aplica"; }else{ //alert(valEdad+" edad menor de 12"); desactivarelementoFormulario("co...
[ "function validaced(){\n \n\n \n /**\n * Algoritmo para validar cedulas de Ecuador\n * @Author : Victor Diaz De La Gasca.\n * @Fecha : Quito, 15 de Marzo del 2013 \n * @Email : vicmandlagasca@gmail.com\n * @Pasos del algoritmo\n * 1.- Se debe validar que tenga 10 numeros\n * 2.- Se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if an evaluation has passed all fence questions in the form
function passesFences() { var fenceRadioButtonNames = $("input[name*='fence_'][value=1]"); var passesFences = true; // iterate through all fence radio button groups and find out if any of them are fenceRadioButtonNames.each(function() { passesFences = passesFences && aquireRadioValue...
[ "function isExpressionProblemAnsweredAll() {\n\t\tvar result = true;\n\n\t\t// make sure all correct answers are chosen\n\t\t$$(\".expressionanswer\").each(function(element) {\n\t\t\tif (result) {\n\t\t\t\tif (element.value !== \"\") { // looks for non-empty value\n\t\t\t\t\tresult = false;\n\t\t\t\t}\n\t\t\t}\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets an RDF property as a string
function getRDFProperty(aDs, aResource, aProperty) { return getRDFValue(aDs.GetTarget(aResource, EM_R(aProperty), true)); }
[ "function toString(property) {\n if(typeof property === 'string') {\n return property;\n }\n if(property.hasOwnProperty(\"name\")) {\n return property[\"name\"];\n }\n else if(property.hasOwnProperty(\"schema:name\")) {\n return property[\"schema:name\"];\n }\n return '';\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Input: _id from the user's user document. Returns full list of user's list of buried job documents Or returns an empty array if the user has no buried jobs
async function getBuriedJobs(userIdIn) { /*var db = await MongoClient.connect(process.env.PROD_MONGODB); var userDoc = await db.collection('users').find( { _id: new ObjectID(userIdIn) } ).limit(1).next(); var buriedJobs = []; if (!userDoc.buriedJobs) { return buriedJobs; } for (var i = 0; i < userDoc.b...
[ "async function getAppliedJobs(userIdIn) {\n var db = await MongoClient.connect(process.env.PROD_MONGODB);\n var userDoc = await db.collection('users').find( { _id: new ObjectID(userIdIn) } ).project({appliedJobs: 1}).limit(1).next();\n var appliedJobs = [];\n if (!userDoc.appliedJobs) {\n return appliedJob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create small cubes with arrow pointing out on each side. by defining the position of the cube, the position of the arrows are set such that the arrows on two neighbour side of two cubes won't overlap each other by set innerArr = fault, the arrow can be removed
function cubeAndArrow(x,y,z,color,color1,innerArr1 = true,innerArr2 = true,innerArr3 = true,innerArr4 = true,innerArr5 = true,innerArr6 = true){ Cubes = [] cube = new Cube(x,y,z,0.5,0.5,0.5); Cubes.push(cube.gObject(color1, white , 0.8)); if (innerArr1){ if (x>0){ arr1 = ne...
[ "generateCubeVertices() {\n \n function vecs_of_flat_arr(arr, n) {\n\t\t\tlet ret = [];\n\t\t\tfor (let i = 0; i < arr.length / n; i++) {\n\t\t\t\tlet vec = [];\n\t\t\t\tfor (let j = 0; j < n; j++) {\n\t\t\t\t\tvec.push(arr[i*n + j]);\n\t\t\t\t}\n\t\t\t\tret.push(vec);\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes any references to selectors from the `ui` object before restoring it back to the original string selectors.
unbindUIElements() { if (!this.ui || !this._uiBindings) { return; } // delete all of the existing ui bindings _.each(this.ui, function($el, name) { delete this.ui[name]; }, this); // reset the ui element to the original bindings configuration this.ui = this._uiB...
[ "removeHighlights() {\n document.getElementById(\"input-highlighter\").innerHTML = \"\";\n document.getElementById(\"output-highlighter\").innerHTML = \"\";\n document.getElementById(\"input-selection-info\").innerHTML = \"\";\n document.getElementById(\"output-selection-info\").innerHTM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Help the teacher figure out how many words the boy has read by calculating the number of words in the text he has read, no longer than maxLength. Formally, a word is a substring consisting of English letters, such that characters to the left of the leftmost letter and to the right of the rightmost letter are not letter...
function timedReading(maxLength, text) { // modify text to contain only the alphabetical chars (filtered out punctuation) text = text.split(' ').map(word => word.split('').filter(char => /[a-z]|[A-Z]/.test(char)).join('')); // text contains no words if(text[0] === '') return 0; ret...
[ "function timedReading(maxLength, text) {\n //coding and coding..\n let newArr = text.match(/\\w+/ig)\n\n let count = 0;\n\n newArr && newArr.forEach(element => {\n if (maxLength >= element.length) {\n count++\n }\n })\n return count\n}", "function longWordCount(string)\n{\n\tvar noOfWords = 0;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve relay board state based on systemState.json file. Board address is required. Output example: 0b11010001
function getRelayBoardState(i2cBoardAddr){ var relayBoardState = 0; for(var dev in jsonSystemState){ if(jsonSystemState[dev].i2cBoardAddr === i2cBoardAddr){ var relayID = jsonSystemState[dev].relayID; var switchValue = jsonSystemState[dev].switchValue; relayBoar...
[ "getState() {\n // TODO return obj with the board's properties\n }", "function loadSystemState(jsonFileName){\n // This json will be loaded only if there doesn't exist an systemState.json file.\n // i.e. if it is the first time running the script, or if systemState.json was previewsly deleted.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Play the snare on click
function playSnare(){ $('#snare').click(function(){ loadSnare(); changePadColor('#snare', 'lime', 'linen'); }); }
[ "function click() {\n\tclickSound.play();\n}", "function onClickPlay () {\n\t\tthis.state.start('play');\n\t}", "playClickSound() {\n this.clickSound.play();\n }", "play() {\n\t\tthis.trigger('play', this);\n\t}", "play() {\n this.snake.moveHead(this.action);\n }", "function playGlass(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
class FilterQuery Filters the incoming solutions, only letting through those where filterFunction(solution) returns true
function FilterQuery(input, filterFunction) { this.source = input.source; this.input = input; this.filterFunction = filterFunction; }
[ "function FilterQuery(input, filterFunction) {\r\n this.source = input.source;\r\n this.input = input;\r\n this.filterFunction = filterFunction;\r\n}", "filter(f,q){\n return this.changeFilter(f,q);\n }", "applyQuery(collection, query) {\n // extract filtering conditions - {propertyName, Reg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method: fireInitialEvents Fire a change event with origin=device for each node present in store. This is so apps don't need to add event handlers and initially request listings to fill their views.
function fireInitialEvents() { logger.info('fire initial events'); function iter(path) { if(util.isDir(path)) { return getNode(path).then(function(node) { if(node.data) { var keys = Object.keys(node.data); var next = function() { if(keys.length > 0)...
[ "triggerDeviceAddedObserver() {\n this.observables_.trigger(ON_UPDATE_LIST_CHANGED);\n }", "function changeListener(device) {\n // refreshData()\n }", "fireDeviceInfoChanged_() {\n this.pageDiv.dispatchEvent(new CustomEvent('infochanged', {\n bubbles: true,\n detail: {\n info...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
4. iterator and callback spies
function iterator(item, cb){ cb(); }
[ "onIteration() {}", "each(cb) {\n var it = this.iterator(), data;\n while ((data = it.next()) !== null) {\n cb(data);\n }\n }", "reach(cb) {\n var it = this.iterator(), data;\n while ((data = it.prev()) !== null) {\n cb(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reads the random.txt file uses the information in to run spotifyReadCommand function
function randomCommand() { fs.readFile("random.txt", "utf8", function(err, data) { if (!err) { var output = data.split(','); outputRead = output[1]; spotifyReadCommand(outputRead); } else { console.log("Error has occurred" + err); } }); }
[ "function readRandom() {\n fs.readFile(\"random.txt\", \"utf8\", function(error, data) {\n // log any errors to the console\n if (error) {\n return console.log(error);\n }\n var dataArr = data.split(\",\")\n var parameter = (dataArr[1]);\n var commandText = da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle changes to the selection in the project pick list.
function onProjectSelectChange() { var selectedIndex = projectSelect.selectedIndex; if (selectedIndex) selectedProjectName = projectSelect[selectedIndex].value; }
[ "function projectSelectHandler() {\n\n }", "function onProjectSelect() {\n\t\tthat.projectIdList = [];\n\t\tthat.projectIdList = [that.selectedProject.id];\n\t}", "function handleProjectChange(e) {\n\tvar project_selection = Element.extend(e.element());\n\tvar c = new Cookies();\n\tc.set('deploygo_project_se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate the Room select
function populateRoom() { // Clean select and add the first option roomsSelect.options.length = 0; // Populate the room select for (var key in jsonInstitutions.institutions) { if (jsonInstitutions.institutions[key].id == institutionsSelect.value) { // Check if rooms array is empty if (jsonInstitutions.inst...
[ "function populateRoom() {\n\n\t// Clean select and add the first option\n\troomsSelect.options.length = 0;\n\n\t// Populate the room select\n\tfor (var key in jsonInstitutions.institutions) {\n\n\t\tif (jsonInstitutions.institutions[key].id == institutionsSelect.value) {\n\n\t\t\t// Check if rooms array is empty\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ Public Methods ] Pure function. Returns the "char code" from a DOM event.
function getCharCode(e) { return (typeof e.which === "number") ? e.which : e.keyCode; }
[ "function getChar(event){\r\n\tvar code = getCode(event);\r\n\tvar actualChar = String.fromCharCode(code);\r\n\treturn actualChar;\r\n}", "function charCodeFromKeyboardEvent(event)\n{\n return String.fromCharCode(event.keyCode);\n}", "function getCharCode(event)\n{\n\tif (event.which == null)\n\t{\n\t\treturn ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implement the logic in the alphabits function that return the characters in alphabetical order, and outputs the result in the DOM, below the text input.
function alphabits(string) { var alph = document.getElementById("alpha"); alph.innerHTML = string.split('').sort(); }
[ "function alphabits() {\n outputArea.innerHTML = input.value.split(\"\").sort(this).join(\"\");\n}", "function alphabits(text){\n\tvar charAlph = \"\";\n\tcharAlph += testString.split(\"\").sort().join(\"\");\n\talphabetical.innerHTML = `<p>These are the characters of your text in alphabetical order: ` + charA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stores dateAsMilliseconds as String in an array in local storage
function storeDate() { var dateArray = null; var dateString = localStorage.localStoredDates; if(!dateString) { dateArray = []; } else { dateArray = JSON.parse(dateString); } dateArray.push(getDateInMil()); localStorage.localStoredDates = JSON.stringify(dateArray); }
[ "function saveBusyDates(array) {\n localStorage.setItem(\"busyDatesArray\", JSON.stringify(array));\n}", "function getTime() {\n var time = new Array;\n var time_str = localStorage.getItem('timelist');\n if (time_str !== null) {\n time = JSON.parse(time_str);\n }\n return time;\n}", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the Title font
function setTitleFont(font, weight, size) { if (weight.length > 3) $('#main-article h1').css("font-style", "italic"); else $('#main-article h1').css("font-style", "normal"); weight = parseInt(weight); $('#title').html("<h2>" + font + "</h2>"); $('#title').css("font-family", font); $('#title').css("fon...
[ "setTitleFont(font)\n{\n this.titleFont = font;\n}", "function setHeadTitleStyle() {\n doc.setFontSize(20);\n doc.setFontType(\"bold\");\n doc.setTextColor(255, 0, 0);\n}", "function di_changeTitleFontSize(uid,val)\n{\n\tvar chartObj = di_getChartObject(uid);\n\tvar styleObj = di_getChartTitleStyle(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is for removing the email address that was associated with the Facebook account.
function deleteFacebookEmail(msg,data) { for (var i=0,len=data.length;i<len;i++) { if (data[i].primary === false) { currEmail = data[i].emailAddress; } } membership.deleteData({ authorization:authcode.get(), contentType:"application/json", messages:{ success:"membership...
[ "function delNonVerEmail(email, callback){\n Account.find({'email': email, 'verified': false}).remove().exec();\n}", "function remove(email) {\n var foundIndex = getContactIndex(contactList, email);\n if(foundIndex != -1) {\n console.log(contactList[foundIndex].name + \" was removed!\");\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper; get data for IP
function getIpData(ip) { log('Get data for IP:', ip); return new Promise(function(resolve, reject) { if(!ip || ip == undefined) return resolve('(no data)'); if(isLocalIp(ip)) ip = process.env.EXTERNAL_IP; // use local external IP if local IP return dnsLookup(ip).then(function(ip) { return getCoor...
[ "function getAsData(ip) {\n Request({\n url: \"http://whois.cymru.com/cgi-bin/whois.cgi\",\n content: {\n action: 'do_whois',\n bulk_paste: ip,\n //family:'ipv4',\n method_whois:'whois',\n flag_prefix: 'prefix',\n submit_paste:'Submi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new item of the given productId
add(type, id) { let key = this.getKey(type) // First see if product is already present let item = this.getItem(type, id) if (!item) { this.items[key].push(id) } this.update(); }
[ "function addToBasket( productId ) {\n var product = Yum.products.getProduct( productId );\n Yum.basket.add( product );\n renderPageSections();\n}", "function addItem(product) {\n var existingItem = basket.find(p => p.id == product.id);\n if (existingItem != undefined) {\n var newQuantity = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for generating occupancy Meaningful occupancy data can only be generated if there's at least 100 occupied households
generateHousingOccupancy() { if (this._occupiedHouses <= 99) { this._hv = [0, 0, 0, 0, 0, 0, 0, 0]; return; } else { // Generate tiny fluctuations for the housing weights, but only do so if // the number of occupied houses is above 100 let wVector = this.HOUSING_WEIGHTS; // C...
[ "addOccupants(nHouses) {\n if (nHouses > 0 && nHouses > this.VacantHouses)\n // Adding health but the healthbar is close to max health\n this._occupiedHouses = this._totalHouses;\n else if (nHouses < 0 && (this._occupiedHouses + nHouses) < 0)\n // Removing health but the healthbar is close to 0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
example: findMissingLetter("abcdf") returns "e"
function findMissingLetter(str) { str = str.toLowerCase(); let foundLetter = undefined; const letters = "abcdefghijklmnopqrstuvwxyz"; const letterArray = letters.split(""); const startingLetter = str[0]; let startingIndex = 0; for (var i = 0; i < letterArray.length; i++) { if (letterAr...
[ "function findMissingLetter(str) {\n let checker = str.charCodeAt(0);\n for (let i=0;i<str.length;i++) {\n if (str.charCodeAt(i) - checker === 0 || str.charCodeAt(i) - checker === 1) {\n checker = str.charCodeAt(i);\n } else {\n return String.fromCharCode(str.charCodeAt(i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method to render a date in a common way.
renderDate(value) { 'use strict'; if (value) { return `<span title="${value.full}">${value.shortest}</span>`; } return '-'; }
[ "render() {\n return <date>{ this.formatDate }</date>;\n }", "render() {\n const formattedDate = getFormattedDate(this.props.date);\n return (\n <div className=\"formatted-date\">\n <h3 className=\"formatted-date-text\">{formattedDate}</h3>\n </div>\n );\n }", "function getFormatt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrap column content in where neccesary
function wrapContent() { canvas.find('.column').each(function() { var col = $(this); var contents = $(); col.children().each(function() { var child = $(this); if (child.is('.row, .ge-tools-drawer, .ge-content')) { ...
[ "function columnWrap(value) {\r\n\t\tif (value)\r\n\t\t\treturn '<div style=\"white-space:normal !important;\">' + value + '</div>';\r\n\t\telse\r\n\t\t\treturn \"\";\r\n\t}", "function columnWrap(value) {\r\n\t\tif (value)\r\n\t\t\treturn '<div style=\"white-space:normal !important;word-wrap: break-word;\">' + v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }