query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
buildPayload constructs a map ready to be uploaded to the API from the given parameters, respecting the current mode and target GitHub instance version.
function buildPayload(commitOid, ref, analysisKey, analysisName, zippedSarif, workflowRunID, checkoutURI, environment, toolNames, gitHubVersion, mode) { if (mode === "actions") { const payloadObj = { commit_oid: commitOid, ref, analysis_key: analysisKey, analy...
[ "payload({ run, plates, wells, smrtLinkVersion, instrumentType }) {\n // eslint-disable-next-line no-unused-vars\n const { id, ...attributes } = run\n\n return createPayload({ run: attributes, plates, wells, smrtLinkVersion, instrumentType })\n }", "buildImage(buildInfo, volumeMapping) {\n const meth...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show the input fields to allow adding a new revenue
function showNewRevenueInputFields(_line) { $('#revenueDetail-' + _line).append('<tr><td>New</td>' + '<td><input type="text" class="form-control mr-sm-2" data-provide="datepicker" aria-label="operation date" id="inputNewRevenueDate-' + _line + '" /></td>' + '<td><input type="text" class="form-contr...
[ "function showEditRevenueInputFields(_line, _revenueLine) {\n console.log('[debug] edit revenue options menu: ' + _line + ' --> ' + _revenueLine);\n}", "function addRevenueEntry()\n{\n //retrieve the open PO Number and the next Invoice Number\n var nextInvoiceData = loadNextInvoiceData();\n\n $(\"#id\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new post for a course
function newPost(req, res, next){ courseService.newPost(req.body.post, req).then(x => { res.json(x); }) }
[ "function createPost(post){\n console.log(post);\n $http.post(`${server}/posts`, {post: post})\n .then(function(res){\n console.log(res);\n\n $state.go('index')\n });\n }", "newPost(post) {\n\n }", "function createPost() {\n}", "async createPost(_, {body}, context) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invokes callback on every view. This includes views that will be created in the future. Note: for future views, this does not guarantee the view will have representations. Use forEachRepresentation if you are extracting representations.
forEachView(callback) { const pxm = this.proxyManager; pxm.getViews().forEach((view) => callback(view)); this[pxmSubsKey].push( pxm.onProxyRegistrationChange((info) => { if (info.proxyGroup === 'Views' && info.action === 'register') { callback(info.proxy); } ...
[ "function _forEachRenderable(callback) {\n\t var dataSource = this._dataSource;\n\t if (dataSource instanceof Array) {\n\t for (var i = 0, j = dataSource.length; i < j; i++) {\n\t callback(dataSource[i]);\n\t }\n\t } else if (dataSource instanceof ViewSequen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If xhr in progress return 500 else jump to next error middleware.
xhrErrorHandler(err, req, res, next) { if(req.xhr) { res.status(500).send({error: err.stack}); } else { next(err); } }
[ "function erroHandler(err, request, response, next) {\n response.status(500).send(\"Server Error! Please Try again later!!\");\n}", "function failedHandler() {\n return function (req, res, next) {\n res.statusCode = 500;\n res.end();\n };\n }", "function internalServerE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clients should override to be called when a new session is created
newSession() {}
[ "onSessionStarted () {}", "onSessionCreated_() {\n // Anything that must happen after the session is created can now happen\n // since this promise is resolved.\n this.resolveSessionCreatedPromise_();\n }", "_createNewSession () {\n this.id = this._generateSessionId()\n this.store = {}\n this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to call rest service by injecting script tag
function CallRestService(request) { var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("src", request); document.body.appendChild(script); }
[ "function CallRestService(request) {\n\tvar script = document.createElement(\"script\");\n\tscript.setAttribute(\"type\", \"text/javascript\");\n\tscript.setAttribute(\"src\", request);\n\tvar dochead = document.getElementsByTagName(\"head\").item(0);\n\tdochead.appendChild(script);\n}", "function callAPI(api){\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles ()Infinity (or derivative) entered value.
_handleInfinity(initialValidation, programmaticValue, value) { const that = this; let newInputValue, newValue; if (value.charAt(0) === '-') { if (value.charAt(1) === '∞') { newInputValue = '-∞'; } else { newInputValue = '-Inf';...
[ "function Infinity() {}", "function numberPositiveInfinity(){\n /*BEG dynblock*/\n return JSNumber((typeof Number==='undefined'||Number===null?m$3g8.throwexc(m$3g8.Exception(\"Undefined or null reference: Number\"),'32:18-32:23','number.ceylon'):Number).POSITIVE_INFINITY);\n /*END dynblock*/\n}", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
10.4 Hide dialogBacklogStat window
function hideBacklogStat() { backlogStat.destroy(); $("#diaglogBacklogStat").removeClass("show"); setTimeout(function () { $("#diaglogBacklogStat").css("display", "none"); }, 150) }
[ "function HideUI() {\n \n ClearStatusMsg();\n \n //Hide the cloak.\n moCloak.Hide();\n \n //Hide the inline frame.\n\t moThisDialog.style.visibility = \"hidden\";\n\t moThisDialog.style.display = \"none\";\n\t \n }", "function fnhideInformation()\r\n\t\t{\r\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function loads the list from local storage.
function loadList(){ let list = []; // Load the item from localStorage. let newList = localStorage.getItem("list"); // Check to see if the item returned null if (newList == null || newList == undefined){ // If it did, save a new list. saveList(); return list; } else { ...
[ "function loadListFromStorage() {\n var storageList = JSON.parse(localStorage.getItem(\"savedList\"));\n\n if (storageList) {\n savedList = storageList;\n }\n}", "function getList(){\n var savedList = localStorage.List;\n listArray = JSON.parse(savedList);\n}", "function loadLocalStorage() {\n le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
12. Swap Values Write a function that will swap the first and last values of any given array. The default minimum length of the array is 2. (e.g. [1,5,10,2] will become [2,5,10,1]).
function swapVals(arr){ var first = arr[0]; arr[0] = arr[arr.length-1]; arr[arr.length-1] = first; return arr; }
[ "function swapValues(arr) {\n temp = arr[0];\n arr[0] = arr[arr.length - 1];\n arr[arr.length - 1] = temp;\n}", "function swapValues(arr) {\r\n var temp = arr[0];\r\n arr[0] = arr[arr.length - 1];\r\n arr[arr.length - 1] = temp;\r\n return arr;\r\n}", "function swapval(arr){\n var first=arr[0];\n v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets modalInput to value of input in the modal
handleInput(e) { this.setState({ modalInput: e.target.value }); }
[ "function EditTourName(value,name){\n $('#editTourDialogue').modal('toggle');\n $('#editTourDialogue').attr(\"value\",value);\n // console.log($('#editTourDialogue').attr('value'));\n $('#editTourNameField').val(name);\n}", "function ModalAskInput(message, callback, placeholder, selectorModal){\n var modal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple FIFO queue for the results of testBlacklist, cached separately from the main |cache| because the blacklist is updated only once in a while so its entries would be crowding the main cache and reducing its performance (objects with lots of keys are slow to access). We also don't need to autoexpire the entries afte...
function updateBlacklistCache(key, value) { blCache[key] = value; blCacheSize += key.length; if (blCacheSize > MAX_BL_CACHE_LENGTH) { for (const k in blCache) { if (delete blCache[k] && (blCacheSize -= k.length) < MAX_BL_CACHE_LENGTH * 0.75) { // Reduced the cache to 75% so that this function do...
[ "function getCache(maxLen, expire, store, emptySlots, lookup){\n\n var bottomIndex, bottom, topIndex, top;\n var length;\n\n function init(){\n // TODO: to use this possibily faster array allocation, adding new\n // elements has to be done by hand cacheArray = cacheArray ||\n // there'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assessment score and the passed/failed status is updated to the LMS, depending on the course Mastery Score.
function fnSetFinalScore(score) { //alert("fnSetFinalScore : " + score); set_val("cmi.core.score.raw",score); if(score>=SetMasteryScore) { //Send the 'passed' status to the LMS set_val("cmi.core.lesson_status","passed"); } else { //Send the 'failed' status to the LMS set_val("cmi.core.l...
[ "function getScoreStatus() {\n if (correctAnswers >= passingScore) {\n return \"passed\";\n }\n return \"failed\";\n}", "function SaveScore()\r\n{\r\n\tvar score = GetScore();\r\n var scaledscore = score / 100.0;\r\n\r\n\tLMSSetValue(\"cmi.score.raw\", score);\r\n\tLMSSetValue(\"cmi.score.scal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iniciarlizar la conexion con el servidor con el endpoint (del websocket) llamado twitter
function initConn() { ws = new SockJS("/twitter"); client = Stomp.over(ws); var headers = {}; var callback = {}; client.connect(headers, callback); }
[ "function initConn() {\n\tws = new SockJS(\"/twitter\");\n\tclient = Stomp.over(ws);\n\tvar headers = {};\n\n\tvar connect_callback = function() {\n\t\t// called back after the client is connected and authenticated to the\n\t\t// STOMP server\n\t};\n\tvar error_callback = function(error) {\n\t\t// display the error...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function resets the list on the page.
function resetList(){ pageList.innerHTML = ""; }
[ "function resetList()\n{\n\tvar element = document.getElementById('resultslist');\n\telement.innerHTML = \"\";\n}", "function resetSearchList() {\n\t\t$('#itemsList').html('');\n\t}", "function resetStudentList(list) {\r\n\tlet newListItems;\r\n\r\n\tlist.length > 0 ? studentList.innerHTML = '' : studentList.in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count the number of peaks in a array to estimate tempo
function countPeaks(a) { var peaks = 0; for (var i = 2; i < a.length - 2; i++) { // Considered a peak if the value is greater than it's neighbors up to 2 away. if (a[i] > a[i - 1] && a[i] > a[i + 1] && a[i] > a[i - 2] && a[i] > a[i + 2]) { peaks++ } } return peaks; }
[ "findPeaks() {\n this.nbPeaks = 0;\n var i = 2;\n let end = this.magnitudes.length - 2;\n\n while (i < end) {\n let mag = this.magnitudes[i];\n\n if (this.magnitudes[i - 1] >= mag || this.magnitudes[i - 2] >= mag) {\n i++;\n continue;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds a meal to favourites
function addToFavoriteMeals(meal){ // adds new fav meal and Area to the userPreferences object in local storage. If the operation is succesful, // returns true. Otherwise, false. if ( !isInFavouriteMeals(meal.idMeal) ){ userPrefences.favouriteMeals.push(meal); if ( !userPrefences.favouriteAr...
[ "function addMealToFavorites(item) {\n if (localStorage.getItem('mealUrl') === null) {\n localStorage.setItem('mealUrl', '[]');\n }\n const meals = JSON.parse(localStorage.getItem('mealUrl' || '[]'));\n if (!meals.includes(item)) {\n meals.push(item);\n localStorage.setItem('mealUrl', JSON.stringify(me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format all the active space details if not present
function formatActiveSpaces (spaces) { _.forEach(spaces, function (space) { if (!_.has(space, 'details.capacity')) { _.set(space, 'details.capacity', 'NA'); } }); }
[ "status() {\n if (this.spaceSize === 0) {\n console.log(colors.yellow('Parking lot is not created.'));\n } else {\n console.log(colors.underline('Slot No.\\tRegistration No\\t\\tColour'));\n this.space.forEach((space, slotNumber) => {\n if (!space.availability) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the result value:
printResult(value) { if (value === "") { // if value is a string print it document.getElementById("result").innerText = value; return; } else { // if value in not a string, first convert in to string and then print it document.getElementById("result").innerText = this.numToStr(valu...
[ "function printResult(result) {\n\tlet output = document.querySelector('output');\n\toutput.textContent = result;\n}", "printResult() {\n const resultString = document.querySelector(`${this.selector} .calc__result`);\n resultString.innerHTML = addSpace(this.result);\n this.display.action(resu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============== Check Vehicle RegNo Function End =================== Reset Function Begin =================
function reset () { self.vehicle = {}; $('#branch_name_value').val(''); $('#vehicle_type_value').val(''); self.heading = "Master"; fetchAllVehicles(); }
[ "function resetVehicleFormFields() {\n generateVID();\n generateVDID();\n $('#txtBrand').val('');\n $('#txtType').val('');\n $('#txtNoOfPassenger').val('');\n $('#txtTransmissionType').val('');\n $('#txtFuelType').val('');\n $('#txtDailyRate').val('');\n $('#txtMonthlyRate').val('');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To read selected restaurant object from the local storage
function getDataFromLocalStorage(){ let data = JSON.parse(localStorage.getItem('restaurant')) selectedRestaurant(data) }
[ "function selectRestaurant() {\n\t// choose restaurant\n\t// get json to retrive information\n\n}", "function retrive(){\n if (localStorage.getItem('movies')){\n nominationList = JSON.parse(localStorage.getItem('movies'))\n }\n \n}", "function updateStorage () {\n localStorage.setItem('restau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Note: In boolean logic, logical nor or joint denial is a truthfunctional operator which produces a result that is the negation of logical or. That is, a sentence of the form (p NOR q) is true precisely when neither p nor q is true i.e. when both of p and q are false
function logical_Nor(a, b) { if (a != b) { return false; } else { return true; } }
[ "function nor(bool1, bool2) {\n\tif (bool1 === false && bool2 === false) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}", "function nor(blo1, blo2) {\n let and =blo1 || blo2\n return !and\n}", "function nor_(b1,b2){\n return !b1 && !b2;\n}", "function Logical() {\n true && true; //true...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_ESAbstract.Call / global IsCallable 7.3.12. Call ( F, V [ , argumentsList ] )
function Call(F, V /* [, argumentsList] */) { // eslint-disable-line no-unused-vars // 1. If argumentsList is not present, set argumentsList to a new empty List. var argumentsList = arguments.length > 2 ? arguments[2] : []; // 2. If IsCallable(F) is false, throw a TypeError exception. if (IsCallable(F) === fals...
[ "function Call(F, V /* [, argumentsList] */) { // eslint-disable-line no-unused-vars\n // 1. If argumentsList is not present, set argumentsList to a new empty List.\n var argumentsList = arguments.length > 2 ? arguments[2] : [];\n // 2. If IsCallable(F) is false, throw a TypeError exception.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
assigngs a custom attribute to the ID "content" which hides/shows (according to the given parameter hide) by css all child elements which are headers
function hideheaders(hide) { if(hide){ showAllDiv('modul1'); showAllDiv('modul2'); showAllDiv('fach'); document.getElementById("content").setAttribute("data-hideheaders","true"); }else{ document.getElementById("content").setAttribute("data-hideheaders","false"); } redrawFix(); }
[ "function hideContent() {\n\t\t\t\t\tcontent.classList.remove('viewDetail');\n\t\t\t\t\tcontent.classList.add('hideDetail');\n\t\t\t\t}", "function hideuni(hide) {\n\tif(hide){\n\t\tdocument.getElementById(\"content\").setAttribute(\"data-hideuni\",\"true\");\n\t}else{\n\t\tdocument.getElementById(\"content\").se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts text and html and creates an annotated HooverNote.
function annotateAsNote(text, html){ if (!html){ Utils.log(3, "No valid text selected!"); } else { var url = Utils.getCurrentPageURL(); var urlTitle = Utils.getCurrentPageTitle(); hnCtrl.addNewNote(html, false, null, text, url, urlTitle, ANNOTATED_NOTE); } }
[ "function NoteTextTemplate(textToBeInserted)\n{\n return '<form><input type=\"hidden\" name=\"hiddenField\" /></form><pre><p class=\"whodis-note\">' + textToBeInserted + '</p></pre>';\n}", "function createNote() {\n //object for wrapper html for note\n var $note = $(\"<p>\");\n //define input field\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sequence diagrams <script src=" <script src=" <script src=" <script src="
function drawDiagrams() { //alert(document.body.innerHTML); var sequences = document.getElementsByClassName('language-sequence'); //alert(sequences.length); for (var i = 0; i < sequences.length; i++) { var innerHtml = sequences[i].innerHTML; //alert(innerHtml); var statement = innerHtml.replace(/\&g...
[ "function showSource ()\n{\n var tags = document.getElementsByTagName('script');\n var footer = document.getElementById('footer');\n var regexp = new RegExp('^( +)//(.+)', 'gm');\n\n for (var i=0; i<tags.length; ++i) {\n if (tags[i].innerHTML.indexOf('new RGraph.') > 0 && tags[i].innerHTML.inde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets an array containing callbacks list for a given event and it's more specific events. I.e. if given event is foo:bar and there is also foo:bar:abc event registered, this will return callback list of foo:bar and foo:bar:abc (but not foo).
function getCallbacksListsForNamespace( source, eventName ) { const eventNode = getEvents( source )[ eventName ]; if ( !eventNode ) { return []; } let callbacksLists = [ eventNode.callbacks ]; for ( let i = 0; i < eventNode.childEvents.length; i++ ) { const childCallbacksLists = getCallbacksListsForNamespac...
[ "function getCallbacksListsForNamespace(source, eventName) {\n var eventNode = getEvents(source)[eventName];\n\n if (!eventNode) {\n return [];\n }\n\n var callbacksLists = [eventNode.callbacks];\n\n for (var i = 0; i < eventNode.childEvents.length; i++) {\n var childCallbacksLists = getCallbacksListsFor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns total cost for purchase if user has enough coins. returns false if user does not have enough coins.
function totalPurchaseCost(item, quantity, coins){ var storeItems = storeInfo.getItems(); var cost; for (var storeItem in storeItems){ if (storeItem.name == item) cost = storeItem.price; } if (coins >= quantity * cost) return quantity * cost; else return false; }
[ "function makePurchase (priceOfItem){\n if ( priceOfItem <= user.total){\n user.total -= priceOfItem\n } else if (priceOfItem > user.total){\n return \"not enough funds\"\n } \n}", "checkCost(amount){\n\t\tif(this.player.role.title == \"Peasant\")\n\t\t\treturn amount;\n\t\tvar totalCost = (this.cost + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Purpose: to display the appropriate button given user type ("P": participant, "E": experimenter)
function display(user) { if (user == "P") document.getElementById("participant").style.visibility = "visible"; else document.getElementById("experimenter").style.visibility = "visible"; }
[ "function showButton(name, p1, p2) {\n\tvar action = (typeof p1 === 'string')? p1:p2;\n\tvar guessCount = (typeof p1 === 'number')? p1:p2;\n\tvar button = activePlayers[name].el.find('button')\n\t\t.removeClass('hidden')\n\n\tif (action) button.find('.action').text(action);\n\tif (guessCount) button.find('.count')....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new instance of the PnPClientStorage class
function PnPClientStorage(_local, _session) { if (_local === void 0) { _local = null; } if (_session === void 0) { _session = null; } this._local = _local; this._session = _session; }
[ "function PnPClientStorage(_local, _session) {\r\n if (_local === void 0) { _local = null; }\r\n if (_session === void 0) { _session = null; }\r\n this._local = _local;\r\n this._session = _session;\r\n }", "function StorageClient(url, options) {\n var _this = _super.call(thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
$> $<IContent.ContentLength Gets length of the file.
get contentLength() { return this.fileInfo.size; }
[ "get contentLength() {\n return this.getNumberAttribute('content_length');\n }", "get contentLength() {\n return this.originalResponse.contentLength;\n }", "get bytesUploaded() {\n return this.contentLength;\n }", "get contentLength() {\n // undefined means not cached.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a file exists. If it does throw an observable error. Returns an observable
function existsStream(source) { return Rx.Observable.create(function (observable) { fs.access(source, fs.F_OK, function (err) { if (!err) { return observable.error('Already Exists'); } observable.next(); observable.complete(); }) }); }
[ "function ifFileExists (filePath) {\n if (!filePath) return when.reject(new Error('File not specified'))\n\n else return when.promise((resolve, reject) => {\n fs.stat(filePath, function (err, stats) {\n if (err) reject(new Error('File does not exist.'))\n else if (stats.isFile()) resolve(fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize the coordinates to (0, 1) by linear transformation how much do you want to relax the extent of the coordinates so that they don't show up on the border of the dotplot
function normalize(coords) { let relaxCoefficient = 0.8; let xArr = coords.map(x => x.x); let yArr = coords.map(x => x.y); let xExtent = extent(xArr); let xDeviation = deviation(xArr); let yExtent = extent(yArr); let yDeviation = deviation(yArr); xExtent[0] -= relaxCoeffici...
[ "function normalize(point) {\n const oneOverLen = 1 / length(point);\n point.x *= oneOverLen;\n point.y *= oneOverLen;\n }", "toNormalized(){\n let length = this.distance();\n return new Point(this.x/length, this.y/length);\n }", "function normalize(point) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
======================================================= Convert from a list of indices to a list of IDs for multiple choice problems within steps. =======================================================
function getStepMCIDs(indices) { var step = view.curStep(); var choices = step.choices; var out = []; _.each(indices, function(val, idx) { if (val !== 0) out.push(choices[idx].id); }); return out; }
[ "function getIDs(indices)\n\t{\n\t\tvar choices = problem.get('choices');\n\t\tvar out = [];\n\t\t_.each(indices, function(val, idx) {\n\t\t\tif (val !== 0)\n\t\t\t\tout.push(choices[idx].id);\n\t\t});\n\n\t\treturn out;\n\t}", "function _generateIds(arr){\n\t\tfor(var i=0, j=arr.length; i<j; i++){\n\t\t\tarr[i]....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves a new message containing an image in Firebase. This first saves the image in Firebase storage.
function saveImageMessage(file) { // 1 - We add a message with a loading icon that will get updated with the shared image. firebase.firestore().collection('sports').add({ name: getUserName(), imageUrl: LOADING_IMAGE_URL, profilePicUrl: getProfilePicUrl(), timestamp: firebase.firestore.FieldValue.ser...
[ "function saveImageMessage(file) {\n // Posts a new image as a message.\n firebase.firestore().collection('messages').add({\n imageUrl: LOADING_IMAGE_URL,\n }).then(function(messageRef) {\n // 2 - Upload the image to Cloud Storage.\n var filePath = firebase.auth().currentUser.uid + '/' + messageRef.id +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns string of abilities
function getAbils(abils) { let abilities = []; abils.forEach(el => abilities.push(el.ability.name)); return abilities.join(', '); }
[ "function getAbils(abils) {\n let abilities = [];\n abils.forEach(el => abilities.push(el.ability.name));\n return abilities.join(', ');\n }", "get abilities() {\n\n // do we need to unpack the abilities?\n if (this[abilities].length && typeof(this[abilities][0]) == 'string') {\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close (destroy) the toast
function close() { vm.toast.destroy(); }
[ "function close() {\n vm.toast.destroy();\n }", "close() {\n this.nmdToast.close()\n }", "function closeToast(cb) {\n clearTimeout(closeToastTimer);\n if (!$.isFunction(cb)) cb = $.noop;\n if (toastOptions) clearNotification(TOAST, cb);\n else if (toastWin) chromeWindow...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to check the image title and adjust the button text accordingly
function checkImage(){ var imgName = $('img').attr('title'); switch(imgName){ case 'Los Angeles': $("#singlebutton").html(imgName); break; case 'London': $("#singlebutton").html(imgName); break; case 'Paris': $("#singlebutton").html(imgName); ...
[ "confirmA11yImageLabels() {}", "function displayImage(title, image) {\n if(title.includes(\"Phantom\")) {\n image.src=\"./images/phantom.JPG\";\n } else if (title.includes(\"Harry\")) {\n image.src=\"./images/harrypotter.JPG\";\n } else if (title.includes(\"Aladdin\")) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if a square contains a piece
function isSquareOccupied(i, j) { var sq = document.getElementById(String(i) + String(j)); if (sq.querySelector(".piece") != null) { return true; // square occupied } return false; // square empty }
[ "function hasSquarePiece(row, column, pieceColor = '') {\n return _pieces\n .filter(p => p.row == row && p.column == column &&\n (pieceColor == '' || p.color == pieceColor))\n .length > 0\n}", "function piece_inside_board (x, y, r) {\n\tvar mask = piece_mask(p, r)\n\tvar size = mask_si...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updateFrame updates the iframe with the textarea contents
function updateFrame(editor, checkForChange) { var code = editor.$area.val(), options = editor.options, updateFrameCallback = options.updateFrame, $body = $(editor.doc.body); // Check for textarea change to avoid unnecessary firing // of potentially heavy up...
[ "function updateFrame(editor, checkForChange) {\n\n var code = editor.$area.val(),\n options = editor.options,\n updateFrameCallback = options.updateFrame,\n $body = $(editor.doc.body);\n\n // Check for textarea change to avoid unnecessary firing\n // of potentially heavy updateFrame callbac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update ARIA accessibility attributes
updateARIAAttributes() { // Current value of volume bar as a percentage this.el_.setAttribute('aria-valuenow', roundFloat(this.player_.volume()*100, 2)); this.el_.setAttribute('aria-valuetext', roundFloat(this.player_.volume()*100, 2)+'%'); }
[ "_updateAriaAttributes() {\n if (this.isExpanded) {\n this.accordionHeading ? this.accordionHeading.setAttribute('aria-expanded', 'true') : null;\n this.accordionContent ? this.accordionContent.setAttribute('aria-hidden', 'false') : null;\n\n this.panelContent ? this.panelContent.setAttribute('ari...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the rotation direction of the vector
function _getRotateDirection (vector1, vector2) { return vector1.x * vector2.y - vector2.x * vector1.y }
[ "getDirection(){\n let v = this.getVector();\n let dir = v.direction();\n return dir\n }", "getDirectionAngle() {\n return Utils.getAngle(this.position, this.prevPosition);\n }", "decomposeRotation() {\n return rad2deg(Math.atan2(this._v[3], this._v[0]));\n }", "get rotation() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
changeSearchPhraseStyleReverse restore initial style of searchphrase tag.
function changeSearchPhraseStyleReverse() { console.log ("##f()## changeSearchPhraseStyleReverse function execution"); let searchBarInput = document.getElementById('search-phrase-input'); searchBarInput.style.marginBottom = '13px'; searchBarInput.style.order= '0'; searchBarInput.style.marginLef...
[ "function changeSearchPhraseStyle() {\r\n console.log (\"##f()## changeSearchInputStyle function execution\");\r\n let searchBarInput = document.getElementById('search-phrase-input');\r\n searchBarInput.style.marginBottom = '10px';\r\n searchBarInput.style.order= '1';\r\n searchBarInput.style.marginL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Type of the ContentChildren decorator / constructor function.
function ContentChildrenDecorator() {}
[ "function ContentChildrenDecorator(){}", "function ContentChildrenDecorator() { }", "function ContentChildDecorator() {}", "function ContentChildDecorator(){}", "function ContentChildDecorator() { }", "function ViewChildrenDecorator() {}", "function ViewChildrenDecorator(){}", "function ViewChildrenDe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lighting and Material Setup and Functions // Setup for the texture
function setTexture() { programId = initShaders(gl, "vertex-shader", "tex-fragment-shader"); gl.useProgram(programId); var image = document.getElementById("tile-img"); var texture = gl.createTexture(); gl.bindTexture( gl.TEXTURE_2D, texture ); //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); ...
[ "initMaterials(){\n \n this.skinTexture = new CGFtexture(this.scene, 'images/skin.png');\n\n this.skinMaterial = new CGFappearance(this.scene);\n this.skinMaterial.setAmbient(0.7, 0.5, 0.5, 1.0);\n this.skinMaterial.setDiffuse(0.7, 0.5, 0.5, 1.0);\n this.skinMaterial.setSpe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate a swagger document against the 2.0 schema, returning a typed Document object.
function validateDocument(document) { if (!schemaValidator(document)) { return; } return document; }
[ "function validateDocument(document) {\r\n if (!schemaValidator(document)) {\r\n return;\r\n }\r\n return document;\r\n}", "_validate (schema){\n return SwaggerParser.validate(schema);\n }", "validate (){\n const that = this;\n return this\n ._validate(this.swaggerInput)\n .t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
render(state) Highlevel render function for entire playground app state.
function render(state) { return h('.playground', [ hg.partial(header.render, state, state.channels), hg.partial(main, state), hg.partial(footer, state, state.channels) ]); }
[ "render() { }", "function render(state){\n root.innerHTML = `\n ${Content(state)}`;\n\n\n router.updatePageLinks();\n}", "render(state = myStore.state) {\n this.element.html(template(state));\n return this;\n }", "function render () {\n\n\t}", "function render() {\n\n\t\t\t}", "function re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rename some component (change it's id). Response returns the parent index JSON data. NOTE: does not affect client indices... No argument normalization.
renameComponent({ type, path, newId }, fetchParams) { const url = `/api/${type}/${path}/rename`; const postData = { newId }; const errorMessage = `Error changing id of ${type} ${path}`; return this.post(url, postData, fetchParams, errorMessage) .then( response => response.json() ); }
[ "renameComponent({ type, path, newId, indexData }, fetchParams) {\n const url = `/api/oak/${type.toLowerCase()}/rename/${path}`;\n const postData = { newId, indexData };\n const errorMessage = `Error changing id of ${type} ${path}`;\n return this.post(url, postData, fetchParams, errorMessage)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add a parameter cell to the paramTable
function addParamCell() { paramNum++; //create param cell var paraCell = document.createElement("div"); paraCell.className = 'paramCell'; //create parameter selection drop down var selObj = document.createElement("select"); selObj.className = 'drop params'; selObj.id = ('param'+paramNum); //create default ...
[ "function addParamRow(paramKey, paramValue){\n\t\tif(paramKey === undefined)\t\tparamKey=\"\";\n\t\tif(paramValue === undefined)\t\tparamValue=\"\";\n\t\t\n\t\tvar paramButStr = '<tr valign=\"top\">';\n\t\tparamButStr +=\t\t'<td valign=\"center\">';\n\t\tparamButStr +=\t\t\t'<button id=\"paramAcceptBut\" name=\"par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update all volumes of magazine and add all articles to volume
async function addVolumesMagazine(req, res) { try { const { idEditor, urlMagazine } = req.body; const urlsVolumes = await getUrlsVolumes(urlMagazine); const currentUrlvolumes = await User.findOne({ _id: idEditor }, { mg_list_volumes: 1 }) // Retrieve current volumens of the magazine to only add new volume...
[ "function updateArticles() {\n //Get all the local PouchDB documents\n db.allDocs({include_docs: true, descending: true}, function(err, doc) {\n //then redraw the list of articles\n redrawArticleList(doc.rows);\n });\n }", "async function addArticlesByVolume(urlVolume) {\n try {\n const li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a State Machine The transition list is for state transitions that do not conform to the default transition: current_state x alphabet > current_state (null callback). Remember that if you supply an EPSILON transition on a state, it must be the only transition on a given state. Also remember that you cannot sp...
function StateMachine() { this.transitionMap = {}; this.currentState = ""; // Statics related to state change this._tList = {}; this._eventStack = []; this._deepTransition = false; this._stateToTransition = ""; }
[ "function StateMachine() {\n //The default initial state\n this.currentState = constants.STATE_INIT;\n\n //Map of state to transition functions\n this.stateTransitions = {\n [constants.STATE_INIT]: initialise,\n [constants.STATE_PROCESSING]: process,\n [constants.STATE_ERROR]: error...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves a tile from the TileCache
function getTileFromCache(tileName, params) { var item = getItem(tileName, params); var tileKey = getTileKey(item); var tileEntry = tileCache[tileKey]; return tileEntry; }
[ "async load(tileCoords) {\n const tile = await cache.readTile(tileCoords, this.version);\n if (!tile) {\n return this.download(tileCoords);\n }\n return tile;\n }", "getTile(tile) {\n return this.getResource(this.convertToResource(tile));\n }", "function getTi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
assigns stats based on job and level of player according to playerDetails / computes and assigns stats based on job and level
function createStats(job, level) { if(job == jobs.war) { stats.str = 2 + (level * 2); stats.dex = 1 + level; stats.con = 3 + level; stats.intel = 0 + level; stats.will = 0 + level; stats.chari = 0 + level; } else if(job == jobs.hnt) { stats.str = 1 + level; stats.dex = 1 + (level * 2); ...
[ "function calcPlayerStats() {\n stats.playerStats.health.value = (8 * stats.vitality.value) + stats.playerStats.health.base;\n stats.playerStats.stamina.value = (3 * stats.grit.value) + stats.playerStats.stamina.base;\n stats.playerStats.encumbrance.value = (7 * stats.encumbrance.value) + stats.playerStats.encum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Write tests for the row state including the Row.UpdateState hook. Constructor for an object that contains status information for a row.
function RowState() { var oContext = null; var sType = RowType.Standard; var bContentHidden = false; var sTitle = ""; var bExpanded = false; var bExpandable = false; var iLevel = 0; Object.defineProperties(this, { /** @type sap.ui.model.Context */ context: { get: function() { return oContext;...
[ "function _addStatusMethods(row) {\n row.status = false;\n row._setStatus = function (_status, cb) {\n if (_status) {\n this.element.classList.add(opts.activeClass);\n } else {\n this.element.classList.remove(opts.activeClass)\n }\n this.status = _status;\n if (_.isFunct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to build a generic modal container for a class
function buildModal(that, title, mClass) { //ensure there is a mid (modalID) in the class object passed to the function if(!that.mid || that.mid === undefined || that.mid === null) { that.mid = makeid(); } let id = that.mid; let html = `<div id='${id}' class='modal ${mClass}' tabindex='-1' role='dialog'...
[ "static createModal(options) {\r\n function getStyle(styleObj) {\r\n let styleStr = \"\";\r\n if (styleObj) {\r\n for (let key in styleObj) {\r\n if (styleObj.hasOwnProperty(key)) {\r\n styleStr += `${key}:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getRelevantNewsTexts doesn't really need to be implemented as nothing is ever sent to them.
getRelevantNewsTexts(news) { //error? console.log("ERROR: Should not try to send a bot any news!"); }
[ "function getNews() {\n // https://newsapi.org/v1/articles?source=cnn&apiKey=\n // To query articles:\n newsapi.articles({\n source: 'cnn', // required\n sortBy: 'top' // optional\n }).then(articlesResponse => {\n /*\n {\n status: \"ok\",\n source: \"cnn\", // https://newsapi.org/v1/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flushes the metrics to the Statful via UDP.
function flush(self) { var buffer; sendFlushStats(self); if ( (self.aggregatedBuffer.bufferSize + self.nonAggregatedBuffer.bufferSize) > 0) { if (self.dryRun) { if (self.logger) { if (self.nonAggregatedBuffer.bufferSize > 0) { self.logger.debug('Flus...
[ "function sendMetricsByUdpTransport (self) {\n var buffer;\n\n self.logger.debug('Flushing to ' + self.host + ', UDP port: ' + self.port);\n\n if (self.aggregatedBuffer.bufferSize > 0) {\n self.logger.debug(\"Can't flush aggregated metrics using udp transport.\");\n\n self.aggregatedBuffer = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the string is 2D char array using regex
function is2DCharArray(s) { var pattern = /type\s=\schar\s[[0-9]*][[0-9]*]/; return pattern.test(s); }
[ "function is2DArray(s) {\n var pattern = /type\\s=\\s.*\\s[[0-9]*][[0-9]*]/;\n return pattern.test(s);\n}", "__is_1D_array(arr) {\n if ((typeof (arr[0]) == \"number\") || (typeof (arr[0]) == \"string\") || (typeof (arr[0]) == \"boolean\")) {\n return true\n } else {\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handle MinX input data
handleMinX(event) { this.setState({minX: event.target.value, enableX1: true},(response)=>{ this.checkEnableSave() }) if(event.target.value.length < 1){ this.setState({enableX1: false},(response)=>{ this.checkEnableSave() }) } }
[ "function xMinMax() {\n xMin = d3.min(theData, function(d) {\n return parseFloat(d[curX]) * 0.98;\n });\n xMax = d3.max(theData, function(d) {\n return parseFloat(d[curX]) * 1.02;\n });\n }", "function xMinMax() {\r\n xMin = d3.min(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Completely mark an event and its properties as sent
function markAsCompleteSent(event) { var yprops = event.getProps(); for (var key in yprops) { var varObj = yprops[key].varObj; event.propertyMarkAsSent(varObj); } event.markAsSent(); }
[ "function yellMarkEventsAsSent(events) {\n\t// Completely mark an event and its properties as sent\n\tfunction markAsCompleteSent(event) {\n\t\tvar yprops = event.getProps();\n\t\tfor (var key in yprops) {\n\t\t\tvar varObj = yprops[key].varObj;\n\t\t\tevent.propertyMarkAsSent(varObj);\n\t\t}\n\t\tevent.markAsSent(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use fetch Every 3 seconds get time and display in servertime div
function updateClock() { fetch('/servertime').then( function (response) { let timediv = document.getElementById("serverTime"); response.text().then(function(text) { timediv.innerHTML = text; console.log(text) }) } ) .catch(function (err) { console.log('Fetch sux!!') }); }
[ "function getServerTime() {\n $.ajax({\n url: \"/display/ajax/time/\"\n }).done(function (data) {\n flipClock.setTime(moment(data.datetime, 'MM-DD-YYYY HH:mm:ss.SSS').toDate());\n });\n }", "function fetchTimer(){\n jQuery.ajax({\n type: \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save current user profile
function saveUserProfile(userProfile) { self._userProfile = userProfile; localStorage.setItem('userProfile', JSON.stringify(userProfile)); }
[ "function saveProfile() {\n var fName = $('#fName').html();\n var lName = $('#lName').html();\n var pNumber = $('#phoneNumber').html();\n dpd.users.me(function(user) {\n if (user) {\n dpd.users.put(\n user.id, {\n firstName: fName,\n lastName: lName,\n phoneNumber: pNumber\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check subtree, where t1 is much larger than t2
function subtree(n1, n2) { var queue = new Queue(); queue.add(n1); var n1Node; while (!queue.isEmpty()) { var current = queue.remove(); if (current === n2) { n1Node = current; break; } if (current.left) { queue.add(current.left); } if (current.right) { queue.add(c...
[ "function sameBST(arr1, arr2){\n if(arr1.length !== arr2.length){\n return false;\n } if(arr1[0] !== arr2[0]){\n return false;\n } if(arr1.length === 0){\n return true;\n }\n let big1 = [];\n let lil1 = [];\n let big2 = [];\n let lil2 = [];\n for(let i=0; i<arr1.length; i++){\n if(arr1[i] >= ar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
customers() returns all of the customers that live in a particular neighborhood
customers(){ const customersInNeighborhood =[] for(const customer of store.customers){ if(customer.neighborhoodId === this.id){ customersInNeighborhood.push(customer) } } return customersInNeighborhood; }
[ "customers() {\n return store.customers.filter(customer => customer.neighborhoodId === this.id)\n }", "function getCustomers(){\n this.customers = 0;\n this.visitors = 0;\n let customersArray = [];\n let visitorsArray = [];\n for(let i = 0; i < registers.length; i++){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For example, if strArr is: ["(1,2,3,4,5,6,7,8,1)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(1,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)"] then your program should return 1,3,4 since the errors are in quadrants 1, 3 and 4 because of...
function sudokuQuadrantChecker(strArray) { var array = getEmbeddedArray(strArray); var currentCells = []; // array of cells items being checked var errorQuadrants = []; // quadrants with errors in them var i; // variable for iterating in for loops var j; // variable for iterating in for loops var m; // v...
[ "function ArrayMatching(strArr) { \n\tvar array = [];\n\tstrArr.forEach(el => array.push(JSON.parse(el)))\n var answer = [];\n\tfor (var i = 0; i < array[0].length; i++) {\n\t\tif (array[1][i]){\n\t\t\tanswer.push(array[0][i] + array[1][i]);\n\t\t} else {\n\t\t\tanswer.push(array[0][i])\n\t\t}\n\n\t}\n\tif (array[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pretty Print XML from DOM
static ppDOM(theDOM, pres = true) { return Pretty.xml(XMLSerialize.serializeToString(theDOM), pres); }
[ "function renderXMLasXML(/*XML DOM*/dom) {\n\tvar newDiv = document.createElement('div');\n\tprint(dom.documentElement, newDiv, 0);\n\treturn newDiv;\n}", "static prettifyXml(xmlDoc) {\n var xsltDoc = new DOMParser().parseFromString([\n // describes how we want to modify the XML - indent everyth...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to query the things on backend, and list all the triggers
function getListOfTriggers(){ $("#triggersBody").empty(); $.getJSON("http://car.ejvaughan.com/things", function(data){ if(!data.success){pushAlert("Cannot get Things and triggers"); return;} for(var i =0; i < data.things.length; ++i){ things[data.things[i].name] = data.things[i].name...
[ "function queryTriggers() {\n server.getWarningTriggers().then(function(res) {\n triggers.length = 0;\n res.data.warningTriggers.forEach(function(trigger) {\n triggers.push(trigger);\n });\n if (!sensorTypes.length) { querySen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
help, xor key over data
function xorDecode(data, key) { var ret = []; var keyLen = key.length; var i, dd; for(i = 0; i < data.length; i++) { ret.push(data[i] ^ key[i % keyLen]); } return ret; }
[ "function xorEncode(key) {\n \n}", "function XOR(difference, streamkey, array){\n if(difference > 0)\n \tvar bin = streamkey.prga(difference*268);//catch the useless key\n else if(difference < 0)\n\tstreamkey.iprga(difference*(-268));\n for(var j = 0; j < 268; j++)\n\tarray[j] ^= streamkey.prga(1);\n}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function used to match id to recipe's id
function isId(recipe) { return recipe.id === id; }
[ "function matchId(recipe){\n return (recipe.id === id)\n }", "function matchId(recipe){\n return (recipe.id === id)\n }", "function findRecipeId(response) {\n const { results } = response;\n results.forEach(function(recipe) {\n getRecipeInfoById(recipe.id); // ... An...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears all highlights that we have added in the ace editor.
function clearAllHighlightedAceLines (aceEditor) { var session = aceEditor.getSession(); for (var hlClass in lastHighlightMarkerIds) { session.removeMarker(lastHighlightMarkerIds[hlClass]); } lastHighlightMarkerIds = {}; }
[ "function clearAllHighlightedAceLines(aceEditor) {\n var session = aceEditor.getSession();\n for (var hlClass in lastHighlightMarkerIds) {\n session.removeMarker(lastHighlightMarkerIds[hlClass]);\n }\n lastHighlightMarkerIds = {};\n}", "function clearAll() {\n if (activeHighlight && activeHighlight....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loads chromecast playback panel
function loadChromecastPanel() { var $container = $('#videoRowContainer'); $container.append("<div id='playbackPanel' class='container-fluid'></div>"); var $playPanel = $('#playbackPanel'); $playPanel.append("<button id='play' type='button' class='btn btn-default chromecast-panel-element' onclick='playMedia();'><sp...
[ "function play(url, device) {\n chrome.runtime.sendMessage(\n { action: 'play', url: url, deviceName: device.serviceName },\n function(response) {\n console.log(response);\n }\n );\n }", "function play(file){\n console.log(file);\n browser.on('deviceOn', function(device){\n devic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate scrollbar thumb position
function calculateThumbPosition(scrollPosition, scrollMax, trackMax) { return scrollPosition * trackMax / scrollMax; }
[ "function pagePositionForThumbPosition (thumbPosition) {\n return -(thumbPosition - SCROLLBAR_TOP) * ((currentContentHeight - viewHeight) / numberOfScrollablePixels);\n}", "function mouseDownScrollThumb (event) {\n // We add these listeners and remove them later; they're only useful while there is mouse act...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add active to nav list
function addActiveNav(data) { navList.querySelectorAll('li a').forEach(element => { element.classList.remove('active') if (data === element.innerText) { element.classList.add('active') } }); }
[ "function setActiveNav() {\n navItems.forEach(item => {\n if (window.location.pathname.includes(item.name)) {\n item.classList.add(\"nav-custom-item-active\")\n }\n });\n}", "function addactiveclass() {\n $(\"nav ul li a\").each(function () {\n var scrollPos = $(document).sc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: promptBuyer Purpose: will prompt the user for the item_id and quantity of the desired product Parameters: item holds the item_id of the item quantity holds the data from the quantity field querySelect has the mysql base select statement Returns: performs the transaction and updates the database denies the tra...
function promptBuyer() { // Prompt buyer to select an item by id console.log(` ______ (____ \ ____) ) ____ ____ ____ _____ ___ ____ | __ ( / _ | \ / _ (___ ) _ \| _ \ | |__) | ( | | | | ( ( | |/ __/...
[ "function promptUser() {\n\n\t// Prompt the user to select an item\n\tinquirer.prompt([\n\t\t{\n\t\t\ttype: 'input',\n\t\t\tname: 'item_id',\n\t\t\tmessage: 'Please enter the ID of the product you want to purchase.',\n\t\t\tvalidate: validateInput,\n\t\t\tfilter: Number\n\t\t},\n\t\t{\n\t\t\ttype: 'input',\n\t\t\tn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Now every value of r[i]() returns 10. Since each function has the createFunctions() activation object in its scope chain, they are all referring to the same variable, i. The right way shows as follows:
function createFunctions(){ var result = new Array(); for(var i = 0; i < 10; i++){ result[i] = function(num){ return function(){ //The anonymous function is defined and called immediately. return num; }; }(i); } }
[ "function createFunction() { \n\tvar result = new Array(); \n\t\t\n\tfor (var i=0; i < 10; i++){ \n\t\tresult[i] = function(num){\n\t\t\treturn function(){\n\t\t\t\treturn num;\n\t\t\t}\n\t\t}(i); \n\t}\n\treturn result; \n}", "function scopeFunc() {\n\n\tvar result = [];\n\n\tfor (var i = 0; i < 5; i++) {\n\t\tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This should be the API_KEY for GeoCode, this is just to display how it could be done however, in this case it won't work as billing is required for the API to work, you will be able to see the error message in the console.
getCityName() { Geocode.setApiKey("AIzaSyBQTJkuKvUP2y4uRp6kyzSxFm3IJpQMmuc"); Geocode.setLocationType("ROOFTOP"); Geocode.fromLatLng("48.8583701", "2.2922926").then( (response) => { const address = response.results[0].formatted_address; let city, state, country; for (let i = 0;...
[ "function getLocationByKey(cityKey) {\n const API_KEY = 'MQv9yHvhKRzuqis8pW460KHVjOjmE6El';\n const URL = 'https://dataservice.accuweather.com/locations/v1/'+cityKey+'?apikey='+API_KEY;\n fetch(URL)\n .then(response => response.json())\n .then(function (data) {\n console.log('Json object from ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wraps a libdefined event handler and a userdefined event handler, returning a single handler that allows a user to prevent libdefined handlers from firing.
function wrapEvent(theirHandler, ourHandler) { return function (event) { theirHandler && theirHandler(event); if (!event.defaultPrevented) { return ourHandler(event); } }; }
[ "function wrapEvent(theirHandler, ourHandler) {\n return function (event) {\n theirHandler && theirHandler(event);\n\n if (!event.defaultPrevented) {\n return ourHandler(event);\n }\n };\n} // Export types", "function _wrapEventHandler(handler) {\n return function(event) {\n // set process id ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether there is overlap between the two elements in the specified direction.
function isOverlap(element1, element2, direction) { if (direction === Direction.Right) return element2.y < element1.y + element1.height && element2.y + element2.height > element1.y; else if (direction === Direction.Down) return element2.x < element1.x + element1.width && element2.x + element2.wi...
[ "function elementsOverlap(elem1, elem2){\n\tvar pos1 = new objPos(elem1);\n\tvar pos2 = new objPos(elem2);\n\treturn (pos1.right > pos2.left && pos1.left < pos2.right && pos1.bottom > pos2.top && pos1.top < pos2.bottom);\n}", "function isOverlap (element1, element2) {\n var Element1 = {};\n var Element2 = {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the ToRawFixed abstract operation is called with arguments x (which must be a finite nonnegative number), minInteger (which must be an integer between 1 and 21), minFraction, and maxFraction (which must be integers between 0 and 20) the following steps are taken:
function ToRawFixed (x, minInteger, minFraction, maxFraction) { // (or not because Number.toPrototype.toFixed does a lot of it for us) var idx, // We can pick up after the fixed formatted string (m) is created m = Number.prototype.toFixed.call(x, maxFraction), // 4. If [maxFraction] ...
[ "function ToRawFixed(x, minInteger, minFraction, maxFraction) {\r\n\t\t\tvar m;\r\n\t\t\t// if x < 10^21, then we can use the standard built in function.\r\n\t\t\t// Otherwise, Number.toFixed() is going to give us back a value in\r\n\t\t\t// scientific notation, and we have to convert it back to a\r\n\t\t\t// serie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if the search query contains facets selection then automatically preselect after the results are retained
function preselectFacetCheckBox(facetsFromSearch) { var queryParams = angular.copy($location.search()); angular.forEach(queryParams, function(item, key) { if (key.indexOf('f:') > -1) { for (var i = 0; i < queryParams[key].length; i++) { ...
[ "function defaultFacetClick(e) {\n e.preventDefault();\n\n var value = $(this).data('azuresearchFacetName') + '|' + $(this).data('azuresearchFacetValue');\n\n if (ls.facetsSelected.indexOf(value) != -1)\n return;\n\n ls.facetsSelected.push(value);\n ls.facetsApplied.onC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call this every time the current math content could have updated, including initially.
update() { if (this.hasEditor()) { let [mathString, displayMode] = ParseMath.getMathFromEditor(this.editor); if (mathString != null) { this.render(mathString, displayMode); } else { this.clear(); } } }
[ "update(){\n MathJax.Hub.Queue([\"Typeset\",MathJax.Hub]);\n }", "function refreshMathJax() {\n MathJax.Hub.Queue([\"Typeset\", MathJax.Hub, \"extremalBox\"]);\n MathJax.Hub.Queue([\"Typeset\", MathJax.Hub, \"diffBox\"]);\n MathJax.Hub.Queue([\"Typeset\", MathJax.Hub, \"spearmanBox\"]);\n Ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get cart product index by id
getCartProductIndexByID(cart, id) { return cart.findIndex(list => list.product.id === id); }
[ "function getProductIndex(id)\r\n{\r\n for (var i = 0; i < products.length; i++)\r\n\t{\r\n if (products[i].Id == id)\r\n\t\t\treturn i;\r\n }\r\n}", "searchProductIndex(id){\n\t\tfor (var i = this.state.cartProducts.length - 1; i >= 0; i--) {\n\t\t\tif(id === this.state.cartProducts[i].id)\n\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encode special attribute characters to HTML entities in a String.
function encodeAttr(str) { return (str+'').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
[ "function encodeAttribute(value) {\n return encodeHtml(value).replace(/\"/g, \"&quot;\").replace(/'/g, \"&apos;\").replace(/`/g, \"&#96;\");\n }", "function encodeAttr(str) {\n\treturn str.replace(/\"/g, '&quot;');\n}", "function encodeHtmlAttr(value) {\n // https://stackoverflow.com/questi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The (absolute) position directly after the wrapping node at the given level, or the original position when `depth` is `this.depth + 1`.
after(depth) { depth = this.resolveDepth(depth); if (!depth) throw new RangeError("There is no position after the top-level node"); return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize; }
[ "before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position before the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n }", "assignPosition(node, position) { \n // assign the position\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the number of stars displayed for a post.
function updateStarCount(postElement, nbStart) { postElement.getElementsByClassName('star-count')[0].innerText = nbStart; }
[ "function updateStarCount(postRef) {\n postRef.transaction(function(post) {\n if (post) {\n post.starCount = post.stars ? Object.keys(post.stars).length : 0;\n }\n return post;\n });\n}", "setStarCount(count) {\n this.starsCount = count;\n }", "function updateStars() {\n gameStats.stars = g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate a surrogate pair from a code point > 0x10000.
function surrogatePair(n){ n-=0x10000 return [0xD800|(n>>10),0xDC00|(n&0x3FF)]}
[ "function code_point_from_surrogate_pair (s) {\n var high_offset = s.charCodeAt(0) - HIGH_SURROGATE_START\n var low_offset = s.charCodeAt(1) - LOW_SURROGATE_START\n\n return (high_offset << 10) + low_offset + 0x10000\n}", "function surrogateSet(cset){var i=0,l=cset.length,state,c,prev,hi,lo,ret=[],prev_h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the restyled plot's values
function updatePlotly(newdata) { Plotly.restyle("pie", "values", [newdata]); }
[ "function replot() {\n updateBrushData();\n updateYAxis();\n plotContext();\n updateMain();\n }", "function redraw() {\n \n // hide tooltip and hover states\n if (tracker.resetTracker) tracker.resetTracker();\n \n // render the axis\n render();\n \n // mark assoc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expands all the disclosure divs on the page
function expandDisclosures() { jq('img[alt="collapse"]').click(); }
[ "function expandDisclosures() {\n jQuery(\"a[data-role='disclosureLink']\").each(function () {\n var contentId = jQuery(this).attr(\"data-linkfor\");\n if (!jQuery(\"#\" + contentId).data(\"open\")) {\n jQuery(this).click();\n }\n });\n}", "function collapseDisclosures() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get selected trackable from the database and add it to the trackable canvas init design
function selectTrackable(comicID, trackableid, trackableNum) { debug("selectTrackable > comicID = " + comicID + " > trackableid = " + trackableid + " > trackableNum = " + trackableNum); // set curTrackableNum so it can be stored when saving the frame var tNum = trackableNum; setCurTrackableNum(tNum); var t...
[ "function chooseTrack() {\n var id = this.value;\n // entities have the same id as the track in the db. zooms to the corresponding entity\n viewer.zoomTo(viewer.entities.getById(id));\n // iterates over tracklist to find the element with the correct id and saves to elem\n var elem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
billingPeriodPeaks operations [BETA] [See on api.ovh.com](
GetTheCurrenBillingPeriodUsagePeakForEachSubscription(serviceName) { let url = `/saas/csp2/${serviceName}/billingPeriodPeaks`; return this.client.request('GET', url); }
[ "function generateIncrements(start_time, end_time, peak_start, peak_end) {\n // convert selected booking times to decimal\n var newStartTime = start_time.replace(':3', ':5').replace(':', '.');\n var newEndTime = end_time.replace(':3', ':5').replace(':', '.');\n var decimalStart = parseFl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate a map with sequenceID > sourceName pairs
function get_sequence_source_mappings(epvRefseqResultMap) { var resultList = glue.tableToObjects(glue.command(["list","sequence","sequenceID","source.name"])); _.each(resultList,function(resultObj){ //glue.log("INFO", "This result is:", resultObj); var sequenceID = resultObj["sequenceID"]; var sourceName ...
[ "_getMetadataObjectsBySourceNames(sourcemap) {\n if (sourcemap.mappings === undefined) {\n const indexSourceMap = sourcemap;\n const metadataMap = new Map();\n indexSourceMap.sections.forEach(section => {\n const metadataMapForIndexMap = this._getMetadataObjectsBySourceNames(section.map);\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal method that updates oscillator and schedules itself
_updateTone() { if (!this.state.on) { this.gainNode.gain.value = 0; this.state.cycle = 0; return; } this.oscillator.frequency.value = this.state.freq; // If currently in an 'on' cycle, turn off and schedule for low time of // duty cycle if (this.state.cycle % 2) { // Turn...
[ "_update() {\n this.clock.frequency.value = this._calcFreq();\n }", "function updateOscSettings(){\n let t = document.getElementById(\"oscType\").value;\n let p = $( \"input[type=number][name=oscPhase]\" ).val();\n let nP = $( \"input[type=number][name=oscNumPart]\" ).val();\n let dt = $( \"input[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
function median(nums1, nums2) { let res = []; let len = nums1.length + nums2.length; let target = len % 2 === 0 ? len / 2 + 1: (len + 1) / 2; let i = 0, j = 0; while (i < nums1.length) { while (nums1[i] > nums2[j] && j < nums2.length) { res.push(nums2[j]); j++; if (res.length === target...
[ "function findMedianSortedArrays(nums1, nums2) {\n const sortedArr = nums1.concat(nums2).sort((a, b) => a - b);\n\n var half = Math.floor(sortedArr.length / 2);\n\n if (sortedArr.length % 2) return sortedArr[half];\n\n return (sortedArr[half - 1] + sortedArr[half]) / 2.0;\n}", "function FindMedianSortedArrays...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
limit number of stores returned
function limitStores(stores, query, callback) { var limited = [], limit = CONFIG.storeLimit; if (query.limit && 'number' === typeof query.limit) { limit = query.limit; } if (limit > 0) { limited = stores.splice(0, limit); } else { // no limit if 0 limited = stores; } callback(null,...
[ "function limitResults(){\n if(thisBind.dataService.resultsData.length > 4){\n thisBind.dataService.resultsData.shift();\n };\n }", "function limitSupplier(){\n const query = {};\n const limit = 2;\n return supplierModel.find(query).limit(limit);\n }", "async getAllStoresBy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redefines this morph from the given (4cc) name and amount values.
set(name4cc, value) { this.fourCCName = name4cc; return this.amount = value; }
[ "setFromMorph(morph) {\n//-----------\nthis.fourCCName = morph.getName();\nreturn this.amount = morph.getAmount();\n}", "static create(name4cc, value) {\nvar morph;\n//------\nmorph = new CASMorph();\nmorph.set(name4cc, value);\nreturn morph;\n}", "constructor(name, startingValue=0, growth=rateDefaults.growth, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reset path path typeof string
function resetPath(path) { if (/^(\.)?\.\//.test(path)) { var timesArr, n, index = -1, pathName = location.pathname; path = path.replace(/^\.\//, ''); timesArr = path.match(/\.\.\//g) || []; n = timesArr.length + 1; for ...
[ "function resetPath() {\r\n\tminigames[8].vars.click_path = [];\r\n}", "function setPath(value) {\n path = value;\n}", "function resetPath() {\n $(\"#urlView #path\").html(\"<i>Select a resource to view path</i>\");\n }", "setToNotAPath() {\n this._setPathTo('//');\n }", "setAndTrimPa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start scrapping data Do the loop until stopScrapping is true: Open and get data from current page: the result can be SUCCESS or FAILED FAILED: Failed in case: + failed to open the page + cannot get the data + get the data but there are duplicated data if FAILED then try to request some more times if after trying MAX_NB...
async function run() { var current_nb_try = 0, // current number of times trying to get data from one page nb_failed = 0, // number of time failed to get data nb_error = 0, // number of time failed to open the page nb_skipped_urls = 0, // number of urls has been skipped (then will be re-try...
[ "function fetchListings() {\n\n var profitableListings = []; // array of listings from bptf (html strings)\n var completedRequests = 0; // count of bptf page requests that produced responses (to tell when we're done)\n\n // loop to request (numPages) pages of classfield listings from bptf\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a value indicating whether this message requires a reply.
get isReplyRequired(){ return this.isPrimary; }
[ "get isReplyRequired() {\n\t\t\treturn (this.isPrimary) && (this.replyExpected);\n\t\t}", "get isCanReply() {\r\n if (!this.$filled) {\r\n return undefined;\r\n }\r\n return this.payload.can_reply === 1;\r\n }", "get hasReplyMessage() {\r\n return this.replyMessage !== ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a list of object id (dbid) to a list of integers where each integer is an index of the fragment in fragment list that associated with the object id.
function objectIds2FragmentIndices(pfr, ids) { var ret = []; if (!ids) { return ret; } var counts = pfr.getEntryCounts(); var stream = pfr.stream; for (var entry = 0; entry < counts; entry++) { var tse = pfr.seekToEntry(entry); ...
[ "getAllDbIds() {\n\n const {instanceTree} = this.viewer.model.getData()\n\n const {dbIdToIndex} = instanceTree.nodeAccess\n\n return Object.keys(dbIdToIndex).map((dbId) => {\n return parseInt(dbId)\n })\n }", "getAllDbIds() {\n\n\t\tconst { instanceTree } = this.viewer.model.getData()\n\n\t\tcon...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }