query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Get a random wasteland's neighbor. Returns an object with coords.
function getRandomNeighbor(mapArray) { let availableNeighbors = [], randomVal, neighbors, randomNeightborCoords; // check every empty tile around existing wasteland mapArray.forEach((tileColumn, x) => { tileColumn.forEach((tile , y) => { if (tile.type === TILE_TYPES[1]) { ...
[ "random_neighbor(xy) {\n\tlet d = [[0,1], [0,-1], [1,0], [-1,0]][Math.floor(Math.random() * 4)];\n\treturn [xy[0]+d[0], xy[1]+d[1]];\n }", "function generateNeighbor(board) {\n var indices = [];\n while (uniq(indices).length < 2) {\n indices.push(Math.floor(Math.random() * board.length));\n }\n\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the label for the 'Confirm' button insinde the Prompt Window. Property type: string
get confirmLabel() { return this.nativeElement ? this.nativeElement.confirmLabel : undefined; }
[ "setConfirmButtonText(t){this.confirmButtonText=t}", "setConfirmButtonText(t) {\n this.confirmButtonText = t;\n }", "function quitConfirm() {\n\tshowOverlay();\n\tgetId('quitText').innerHTML = \"Are you sure you<br>want to QUIT?\";\n\tgetId('buttonLeftText').innerHTML = \"Yes\";\n\tgetId('buttonRightText')....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The purpose of the checkSolution function is to check whether the user's solution matches the actual solution of the hanjie puzzle. The function displays all incorrectly clicked cells as red, and counts the number of cells that should be clicked but aren't.
function checkSolution() { allCells = puzzleCells.getElementsByTagName("td"); var checkCount = 0; for(i=0; i < allCells.length; i++) { if(allCells[i].style.backgroundColor == "black" && allCells[i].className != "dark") { allCells[i].style.backgroundColor = "red"; } else if (allC...
[ "function checkSolution() {\n\t\tfor(var i = 0; i < SIZE; i++) {\n\t\t\tfor(var j = 0; j < SIZE; j++) {\n\t\t\t\tvar tileNum = (i * SIZE) + j + 1;\n\t\t\t\tif(document.getElementById(\"cell\" + i + j).hasChildNodes()) {\n\t\t\t\t\tif(document.getElementById(\"cell\" + i + j).firstChild.id !== \"tile\" + tileNum) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Following 4 methods do changes to accounts so that transfer is possible. Change customer email address and call transfer.
function changeEmailandTransfer(source, destination, update) { destination.email = source.email; destination.update = update; DP.execute({type:"apiCustomer", method:"updateEmail", params: destination}).then(function(response) { if (response.message === 'Successful') { Notification....
[ "function transfer(fromAccount, toAccount, transferAmount) {\n if (fromAccount !== \"external\") {\n fromAccount.value -= transferAmount;\n }\n if (toAccount !== \"external\") {\n toAccount.value += transferAmount;\n }\n }", "function transferOwnAccount() {\n transferProvider.transf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the way or its parent relation, whichever has a useful feature type
function getFeatureWithFeatureTypeTagsForWay(way, graph) { if (getFeatureTypeForTags(way.tags) === null) { // if the way doesn't match a feature type, check is parent relations var parentRels = graph.parentRelations(way); for (var i = 0; i < parentRels.length; i++) { ...
[ "function getFeatureWithFeatureTypeTagsForWay(way, graph) {\n\t if (getFeatureType(way, graph) === null) {\n\t // if the way doesn't match a feature type, check its parent relations\n\t var parentRels = graph.parentRelations(way);\n\n\t for (var i = 0; i < parentRels.length; i++) {\n\t var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IE postfix hack, i.e. 123\0 or 123px\9
function isPostfixIeHack(str, offset) { if (offset !== str.length - 2) { return false; } return ( str.charCodeAt(offset) === 0x005C && // U+005C REVERSE SOLIDUS (\) isDigit(str.charCodeAt(offset + 1)) ); }
[ "function isPostfixIeHack(str, offset) {\n\t if (offset !== str.length - 2) {\n\t return false;\n\t }\n\n\t return (\n\t str.charCodeAt(offset) === 0x005C && // U+005C REVERSE SOLIDUS (\\)\n\t isDigit$2(str.charCodeAt(offset + 1))\n\t );\n\t}", "function _appendPX(value){return/^...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
default comparator should be overrided for custom functionality in atom class
get comparator() { return null; }
[ "function atom_idComparer(a, b) {\n return a.id - b.id; // works for numbers...\n}", "function IntegerComparator(){}", "constructor (comp) {\n this.root = null; //Constructor is using one node and sets it as root of list\n this.comparator = comp;\n\n if (this.comparator === undefin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render a Todo component for each element in the `list` props
render() { return ( <div> {this.props.list.map((d, i) => { return <Todo key = {i} status={d.status} priority={d.priority} description={d.description} /> }) } </div> ) }
[ "function TodoList(props, context) {\n\tconst { todos, ui } = props;\n\tconst visibleTodos = ui.visibleTodos();\n\n\tif (todos.length === 0) {\n\t\treturn <p className=\"noItems\">What do you want to do today?</p>\n\t} else if (visibleTodos.length === 0) {\n\t\treturn <p className=\"noItems\">No items are { ui.filt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark owned games as owned || remove owned games from list || remove hidden apps
function showOwnedGames(){ $('.giv-coupon').addClass('animated-coupon'); $('.giv-coupon-link').removeAttr('href'); // Remove Entered Giveaways if (!!settings.hide_entered_giveaways){ $('.tickets-col:not(.checked)').not(':has(.animated-coupon)').remove(); } $('.tickets-col:not(.checked)').each(function(){ le...
[ "function requestOwnedGames() {\n\t\tvar request = $.ajax({\n\t\t\turl: \"steam\",\n\t\t\ttype: \"POST\"\n\t\t}).done(displayGames)\n\t}", "function flushGames() {\r\n ACTIVE_GAMES = ACTIVE_GAMES.filter((g) => g.active);\r\n}", "function forfeitSelectedGames() {\r\n // TODO: make sure this doesn't cra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sumatorio de k terminos usando la formula de poisson
function poisson(k, landa) { exponentialPower = Math.pow(exponential, -landa); // negative power k landaPowerK = Math.pow(landa, k); // Landa elevated k numerator = exponentialPower * landaPowerK; denominator = fact(k); // factorial of k. return numerator / denominator; }
[ "function poisson( k, m)\r\n{\r\n k = k + 1;// \r\n var a = [];\r\n // var d = Math.exp(-m);\r\n // if (k != 0)\r\n var d = gammq(k, m);\r\n \r\n a.push(d);\r\n return a;\r\n}", "function poisson(lambda){ \n\tvar L = Math.exp(-lambda);\n\tvar p = 1.0;\n\tvar k = 0;\n\t \n\tdo {\n\t k+...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function called vowelCount which accepts a string and returns an object with the keys as the vowel and the values as the number of times the vowel appears in the string. This function should be case insensitive so a lowercase letter and uppercase letter should count
function vowelCount(str) { var splitArr = str.toLowerCase().split(""); var vowels = 'aeiou'; var obj = {}; splitArr.forEach(function(letter){ if(vowels.indexOf(letter) !== -1) { if(obj[letter]) { obj[letter]++; } else { obj[letter] = 1; } } }); return obj; }
[ "function vowelCount(str) {\n let obj = {};\n str = str.toLowerCase().split(\"\");\n let vowels = \"aeiou\".split(\"\");\n str.forEach(char => {\n if(vowels.indexOf(char) !== -1) {\n obj[char] = 0;\n }\n })\n str.forEach(char => {\n for(key in obj) {\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updateAmbient() Description: This function is called when change happens in the intensity of ambient, the ambient coefficient of the cube, the ambient coefficient of the surface and changes the property "amb" of cube and surface. Finally, it updates the display by calling the requestAnimationFrame function
function updateAmbient() { if (Date.now() - lastUpdate > mspf) { cube["amb"] = parseFloat(document.getElementById("cubeAmb").value); surface["amb"] = parseFloat(document.getElementById("surfaceAmb").value); intensityAmb = parseFloat(document.getElementById("intensityAmb").value); req...
[ "function updateMaterialAmbient(jscolor) {\n materialAmbient = hex2vec4(jscolor);\n ambientProduct = mult(lightAmbient, materialAmbient);\n}", "initAmbient() {\n this.setGlobalAmbientLight(\n this.graph.globalAmbient[0], this.graph.globalAmbient[1],\n this.graph.globalAmbient[2], this.graph.glo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforming the stars number value to an array
function _getStarRating(stars) { return new Array(stars); }
[ "getRatingsStarsArray(ratingNumber){\n /**\n * Prepare a 5 items array. our stars container\n */\n const stars = new Array(5);\n\n /**\n * Get a whole number version of the reviews, \n * so that later we can extract half value (if exists)\n */\n const intRating = Math.floor(ratingNum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear Batch requester's requests and decoders
clear() { this.requests = []; this.decoders = []; this.accountNextNonces = {}; this.accountUsedNonces = {}; }
[ "clear () {\n for (const [key, cancel] of this.pendingRequest) {\n cancel('Duplicate request: ' + key)\n }\n pendingRequest.clear()\n }", "reset() {\n for (const batch of this.batches) {\n batch.reset();\n }\n }", "Clear() {\n this.batches = [];\n }", "clearAllRe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
7. Write a function called upperCaseAll(array) that takes in an array of strings and returns an array of uppercased strings.
function upperCaseAll(array) { var uppercased = []; for (var i = 0; i < array.length; i++) { uppercased.push(array[i].toUpperCase()); } return uppercased; }
[ "function upperCaseAll (array){\n var casedArray = []\n for (var i = 0; i < array.length; i++){\n casedArray.push(array[i].toUpperCase());\n }\n return casedArray;\n}", "function upperCaseArray (array) {\n\n}", "function upperCaseAll(array) {\n if (Array.isArray(array)) {\n for (var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method submits the request to deactivate a research area to server. It first checks to see that there are no pending changes that need to be persisted, and submits only if so. If there are pending changes then it will simply ask the user to either save or abandon the changes.
function deactivateResearchArea(id) { if (raChanges.moreChangeData()) { if (confirm('You must save (or abandon) all outstanding changes before attempting a deactivation. Do you want to save changes to Research Area Hierarchy?')) { save(); } $j("#researcharea").empty(); r...
[ "function cancel()\n {\n dirtyController.setDirty(false);\n hideWorkflowEditor();\n hideWorkflowUpdateEditor();\n selectWorflow(selectedWorkflow);\n }", "function saveAndExitEditMode()\r\n\t\t{\r\n\t\t\tif (currentEditableAnnotation)\r\n\t\t\t{\r\n\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate an object represnting a job. can be used to generate seed data for db or request.body data
function generateJobData() { return { company: faker.company.companyName(), description: faker.lorem.sentence(), messenger: faker.name.firstName(), comment: faker.lorem.sentence(), pickup: faker.fake("{{address.streetAddress}}, {{address.city}} {{address.state}} {{address.zipCode}}"), dropoff:...
[ "function generateJobData() {\n return {\n companyName: generateCompanyName(),\n companyLocation: generateCompanyLocation(),\n positionTitle: generatePositionTitle(),\n companyType: generateCompanyType(),\n salary: Number(faker.random.number()),\n companyWebsite: generateCompanyWebsite(),\n li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Authenticates the password for a layer.
function authenticate(layer, credential, callback) { var password = process.env[format('LDAP_LAYER_%s_PASSWORD', layer.toUpperCase())]; if ( password && credential === password ) callback(null, password) else callback(new ldap.InvalidCredentialsError("Invalid login for layer " + layer)); }
[ "addPasswordAttempt(password) {}", "async authUserPass() {\n const data = await this.consume();\n if (data[0] != 0x01) {\n this.logger.error('Unsupported auth version: %d', data[0]);\n this.socket.end();\n return true;\n }\n\n const ulen = data[1];\n const uname = data.toString('asci...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the zindexes of the children of the given +_viewId+.
updateZIndexOfChildren(_viewId) { if (!this._updateZIndexOfChildrenBuffer.includes(_viewId)) { this._updateZIndexOfChildrenBuffer.push(_viewId); } else { const _isDefined = typeof _viewId !== 'undefined' && _viewId !== null; const _view = _isDefined && this.__views[_viewId]; const _i...
[ "_flushUpdateZIndexOfChilden() {\n const _this = this;\n // Iterate over a clone:\n const _buffer = this.cloneObject(this._updateZIndexOfChildrenBuffer);\n this._updateZIndexOfChildrenBuffer = [];\n _buffer\n .map(_viewId => {\n const _view = _this.__views[_viewId];\n const _isRoot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updateLockScreenTime() Thread that handles lockscreen time
function updateLockScreenTime() { if ($(".lockscreenopened").length > 0) { // Lockscreen not open? No need to keep track of time here console.log("well bye"); return; } var thedate = new Date(); // Get current date var parsetime = thedate.toTimeString().split(":"); // Parse time into array var parsedate = th...
[ "function _lockDeviceScreen() {\n\n\tcloseModuleDrawer();\n\n\tlockScreen.removeClass(\"lockscreenopened hidden\"); // Show the lockscreen\n\tpasswordInputBox.focus(); // Focus on password box\n\n\tupdateLockScreenTime(); // Start updating time again\n}", "function tickScreen() {\n\t\n\tfor (var i=0;i<task.length...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function related to the YouTube API that makes an ajax call and shows the next page in youtube results
function showNextPage() { var token = $("#next-button").data('token'); var q = $('#next-button').data('query'); $("#videos-view").empty(); $("#buttons").empty(); var params = $.param({ part: 'snippet, id', maxResults: '1', q: keyword, pageToken: token, t...
[ "function nextVideo() {\n $('.js-btn-next-YT').on('click', function() {\n query_string.pageToken = nextPage;\n $.getJSON(youTubeUrl, query_string, displayYouTubeData);\n });\n}", "function showPrevPage() {\n var token = $(\"#prev-button\").data('token');\n var q = $('#prev-button').data('query');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
notifies content script and background page about Data.snippets changes
function notifySnippetDataChanges(){ var msg = {snippetList: Data.snippets}; chrome.tabs.query({}, function(tabs){ var tab; for (var i = 0, len = tabs.length; i < len; i++) { tab = tabs[i]; if(!tab || !tab.id) continue; chrome.tabs.sendMessage(tab.id, msg); } }); chr...
[ "function loadSnippets(){\n var snippetSave = JSON.parse(localStorage.getItem(\"snippetSave\"));\n snippets = JSON.parse(snippetSave.snippets);\n var notes = JSON.parse(snippetSave.notes);\n $(\"#notepad textarea\").val(notes);\n refreshSnippetsList();\n}", "function attach_content_script_listeners(){\n\t// ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
user data getting from firebase
function getUserData() { const userId = localStorage.getItem("userId"); firebase .firestore() .collection("user") .doc(userId) .get() .then(function (snapshot) { const userData = snapshot.data(); document.getElementById("userName").innerHTML = userData.fullname; }); }
[ "getUsersData() {\n const uid = firebase.auth().currentUser.uid;\n firebase.database().ref(`Registration/`).on(\"child_added\", data => {\n let obj = data.val()\n console.log(\"getting--\", obj)\n })\n }", "function getUserData(usr) {\r\n let db_ref = firebase.data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
exportar todos los tramites en general que estan en proceso
function exportAllTramites() { for (var tramite in vm.tramitesProceso) { vm.allTramitesForExport.push({ 'Docente': vm.tramitesProceso[tramite].usuario, 'RFC': vm.tramitesProceso[tramite].rfc, 'Tramite': vm.tramitesProceso[tramite].tramite, 'Fecha': vm.tramitesProces...
[ "function exportMyTramites() {\n for (var tramite in vm.listaTramitesProceso) {\n vm.myTramitesForExport.push({\n 'Docente': vm.listaTramitesProceso[tramite].usuario,\n 'RFC': vm.listaTramitesProceso[tramite].rfc,\n 'Tramite': vm.listaTramitesProceso[tramite].tramite,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the binding for a variable declared using `as`. Note that the order of the keyvalue pair in this declaration is reversed. For example, ``` ngFor="let item of items; index as i" ^^^^^ ^ value key ```
parseAsBinding(value) { if (!this.peekKeywordAs()) { return null; } this.advance(); // consume the 'as' keyword const key = this.expectTemplateBindingKey(); this.consumeStatementTerminator(); const sourceSpan = new AbsoluteSourceSpan(value.span.start, this.cur...
[ "parseAsBinding(value) {\n if (!this.peekKeywordAs()) {\n return null;\n }\n this.advance(); // consume the 'as' keyword\n const key = this.expectTemplateBindingKey();\n this.consumeStatementTerminator();\n const sourceSpan = new Absol...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Le pasamos el nombre de dispositivo ("pc" o "mobile") y nos elimina o crea el logo para el nav mobile
changeLogo(device_name){ let logoClassName = "nav-logo-mobile" let navLogo = document.querySelector("#custom-nav-bar .nav-bar-logo") let checkLogo = document.querySelector("."+logoClassName) let logoClone = navLogo.cloneNode(true) logoClone.className = logoClassName let...
[ "function setLogo() {\n\t\t$('.xs-logo').each(function () {\n\t\t\tvar $this = $(this).children(),\n\t\t\t\tclone = $this.clone(),\n\t\t\t\tholder = $('.nav-brand');\n\t\t\tif ($(window).width() > 991) {\n\t\t\t\tif (holder.children().length > 0) {\n\t\t\t\t\tholder.children().remove();\n\t\t\t\t}\n\t\t\t} else {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the intended solution using O(1) space similar idea to quick sort start with two pointers at the outer edges. there are four cases: (1) they're both even, (2) they're both odd, (3) left is even while right is odd, (4) left is odd while right is even. if (3), both numbers are in a good place, so you move both pointers i...
function solution_2 (A) { let left = 0; let right = A.length - 1; while (left < right) { const L = A[left] % 2; const R = A[right] % 2; if (L && !R) [A[left], A[right]] = [A[right], A[left]]; // case 4 - swap, and both `right` and `left` will move inward because of the next two lines if (L || (!...
[ "function sort0s1s2sUsingPointer(arr) {\n var low = 0, mid = 0;\n var high = arr.length - 1;\n while (mid <= high) {\n if (arr[mid] === 0) {\n swap(arr, low, mid);\n low++;\n mid++;\n } else if (arr[mid] === 1) {\n mid++;\n } else {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Offshoot of the update Activity method which adjusts the class of the appropriate room rectangle based on the state of the sensors in the room. This method changes the class of the sonos SVG to indicate when the speakers are playing vs not
function updateSonos (sensorMapID, sensorStyle) { var sonos = document.getElementById(sensorMapID); sonos.setAttribute("class", "sonos-" + sensorStyle); var sonosarcs = document.querySelectorAll("[id*='living-room-sonos-arc']"); for (i = 0; i < sonosarcs.length; i++) { var arc = sonosarcs[i]; ...
[ "function updateClasses(){\n //Removes text from screen\n svg.selectAll(\"text\").data([]).exit().remove();\n let toUpdate = day0;\n switch(currentDay){\n case(1):\n toUpdate = day1; break;\n case(2):\n toUpdate = day2; break;\n case(3):\n toUpdate =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Crete blob form data
createFormData() { let formData = new FormData() let blobRefs = [] this.files.forEach(function(file, index){ let uuidRef = uuid() blobRefs.push(uuidRef) formData.append(blobRefs[index], file, file.name) }) this.addSdoProptery("blobRefs", blobRefs) formData.append('sdo'...
[ "function createFormData(blob){\r\n var formData = new FormData(document.forms[0]);\r\n formData.append(\"photo\", blob); \r\n formData.append(\"userLat\", userLat);\r\n formData.append(\"userLng\", userLng); \r\n \r\n return formData;\r\n}", "function getFormData(blob, filename, acce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send error message to the registerWebview.
function registerEventError(errorMessage) { registerWebview.emit('error', errorMessage); }
[ "function onRegistrationFailed() {\n $('error-message').textContent =\n loadTimeData.getString('addingErrorMessage');\n setRegisterPage('register-page-error');\n recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_FAILURE);\n }", "function OnError(request, data, status) {\t\t\t\t\n\t\tmessage = \"Network...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
iterate over each distributors to get matching large and medium size images
function get_images(imagesets) { var images = {}; $.each(imagesets, function(){ if (!is_mobile && this.large_image && this.medium_image){ images.large = DDG.toHTTP(this.large_image.url); images.medium = DDG.toHTTP(this.medium_image.url); retu...
[ "function optimalSizeImages ($container, allSizes) {\n var containerWidth = $container.width();\n var chosenImages = [];\n for (var i = 0; i < allSizes.length; i++) {\n \n allSizes[i] = widthInsertSort(allSizes[i]);\n var chosen = selectBest(containerWidth, allSizes[i]);\n chosenImages....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
signal other peer use your own socket implementation to trasport signal data
_signalOtherPeeer() { console.log('Signal other peer'); const propseId = shortid.generate(); this.setRemotePeerId(propseId); SocketService.getInstance().send({ type: SOCKET_MESSAGE_TYPES.PEER_SIGNAL, peerData: { signal: this._rawLocalDescription, toUser: this._u...
[ "socketEmit(signal, data) {\n this.socket.binary(false).emit(signal, data);\n }", "socketEmit(signal, data) {\n this.socket.emit(signal, data);\n }", "sendSignal(targetID, signal) {\n console.log(\"Sending a signal [offer/answer]\");\n if(this.nodeToPath[targetID]){\n var path = this.nodeToPa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Service for getting and caching congestion information from API.Next This object should be created and stored as a singleton to take avantage of it's internal caching. Freshness of congestion information is based on a ttl returned from the API. Congestion information is used by the UI to show a message to users when th...
function CongestionService(config) { this.apiEndpoint = config.apiEndpoint; this.http = config.http; this.clock = config.clock; this.minTtlSeconds = config.minTtlSeconds; this.isRequestingCongestion = false; this.callbacks = []; this.log = config.log; if (...
[ "function getData()\n {\n var currentTime = new Date().getTime();\n var refresh_time = currentSettings.refresh_time;\n\n // The url has an url as a REST API of RESTHeart to retrieve data, which is a REST API server for MongoDB.\n var url = \"http://\";\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this updates the info section with the new gallery info
function changeInfoSection (galleryName) { var infoIndex = galleryIndex * 2 // time two because each section has two infoIndex var infoHeader = document.getElementsByClassName('info-header') var infoBody = document.getElementsByClassName('info-body')[galleryIndex] var headersArray = [infoHeader[infoInd...
[ "function updateDetails() {\n // update the caption\n if (typeof _this.album[_this.currentImageIndex].caption !== 'undefined' &&\n _this.album[_this.currentImageIndex].caption !== '') {\n _this.content.caption = _this.album[_this.currentImageIndex].caption;\n }\n\n // ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: We use a defer procedure as a parameter here, so that feedback loops don't grind the entire page to a halt. However, those loops will still execute forever, so be careful. TODO: Implement resource spaces so that we can provide dynamic acquisition of demand monitors while permitting external observation and extens...
function behDemandMonitor( defer ) { var installedDemanders = []; var createdDemandersPending = false; var installedMonitors = []; function createDemandersPending() { if ( createdDemandersPending ) return; createdDemandersPending = true; _.arrEach(...
[ "_dispense () {\n /**\n * Local variables for ease of reading/writing\n * these don't (shouldn't) change across the execution of this fn\n */\n const numWaitingClients = this._waitingClientsQueue.length\n\n // If there aren't any waiting requests then there is nothing to do\n // so lets shor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function loads and returns the closest beacon
scanBeacon(){ this.scanClosest().then((beacon)=>{ this.beacon=beacon; this.loadData(); }); }
[ "function retrieveBeacon(instance, j) {\n _dbbeacons.get(instance).then(function(doc) {\n _beacon = doc;\n if (j == 0) {\n // This is the CLOSEST beacon\n _b1X = _beacon.x; _b1Y = _beacon.y;\n // console.log(\"(b1X:\"+_b1X+\",b1Y:\"+_b1Y+\")\");\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the Z component of the acceleration, as a floating point number.
function YAccelerometer_get_zValue() { if (this._cacheExpiration <= YAPI.GetTickCount()) { if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) { return Y_ZVALUE_INVALID; } } return this._zValue; }
[ "function YMagnetometer_get_zValue()\n {\n if (this._cacheExpiration <= YAPI.GetTickCount()) {\n if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) {\n return Y_ZVALUE_INVALID;\n }\n }\n return this._zValue;\n }", "function getCombinedAccelera...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds days that are not in the current data with a membersPerDay of 0
function addMissingDays() { membersPerDay.sort(sortMembersPerDay); let length = membersPerDay.length - 1; for(let i = 0; i < length; i++) { membersPerDay[i].key = new Date(membersPerDay[i].key); membersPerDay[i].key.setHours(1); let nextDay = new Date(membersPerDay[i].key); nextDay.setDate(members...
[ "function getMembersPerDay() {\n membersPerDay = d3.nest()\n .key(d => d.date).sortKeys(d3.ascending)\n .key(d => d.year).sortKeys(d3.ascending)\n .rollup(leaves => leaves.length)\n .entries(memberData);\n\n membersPerDay.forEach((e, i, array) => {\n let membersJoined = 0;\n e.values.forEach((e2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set squares to generated colours
function setColours() { for(var i = 0; i < colours.length; i++) { squares[i].style.backgroundColor = colours[i] } }
[ "function setColor(squares){\n squares.each(function(){\n $(this).css( \"backgroundColor\",randomRGB());\n });\n}", "function setColors () {\r\n for (let i = 0; i<squares.length; i++) {\r\n squares[i].style.backgroundColor = colors[i];\r\n}}", "function initSquares(len){\n for(let i=0;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[new] Globalize( locale|cldr )
function Globalize( locale ) { if ( !( this instanceof Globalize ) ) { return new Globalize( locale ); } validateParameterPresence( locale, "locale" ); validateParameterTypeLocale( locale, "locale" ); this.cldr = alwaysCldr( locale ); validateLikelySubtags( this.cldr ); }
[ "function Globalize( locale ) {\n\tif ( !( this instanceof Globalize ) ) {\n\t\treturn new Globalize( locale );\n\t}\n\n\tif ( !locale ) {\n\t\tthrow new Error( \"Missing locale\" );\n\t}\n\n\tthis.cldr = alwaysCldr( locale );\n}", "function getGlobalize(locale) {\n return locale && locale !== i18n_1.defau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nodo hijo tras la jugada
nodoHijo(jugada){ //console.log("Jugadas totales: " + this.hijos.size) let hijo = this.hijos.get(jugada.hash()) //console.log("CONTROL " + hijo.jugada.hash()) if (hijo === undefined){ throw new Error ("No es posible la jugada") } else if (hijo.nodo === null){ ...
[ "function attendreJoueurFinitJouer() {\n //Todo\n}", "function hacerJugada(){\n\n\t// Obtiene el contenido de la celda\n\tvar valor = $(this).text();\n\n\t// Verifica si la celda esta vacia\n\tif ( valor === '' ) {\n\n\t\t// Obtiene el identificador del juego\n\t\tvar idjuego = $('#spanIdJuego').text();\n\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a DIV to display a single sandwich
createSandwichCard(sandwich) { // Destructure const {id, name, bread, ingredients} = sandwich const sandwichCard = document.createElement('div'); sandwichCard.className = cart.selectedSandwich.id === sandwich.id ? 'm-3 card border-primary' : 'm-3 card' sandwichCard.style.cursor...
[ "function createShelterDiv(){\n var newDiv = '<div class=\"panel panel-default\" id=\"shelter-panel\">'+\n '<div class=\"panel-heading\">'+\n '<h3 class=\"panel-title\">Local Animal Shelters</h3>'+\n '</div>...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display an Empty readonly session
displayEmptyReadOnlySession () { if (!this.activated) return this.currentFile = null this.emit('addModel', '', 'text', '_blank', true) }
[ "function displayNoSession(clear) {\n\tif (clear) screen.clear();\n\tscreen.goto(3,1).print('AUCUNE SESSION');\n\tscreen.goto(2,2).print('EN COURS DE VOTE');\n}", "function showSessionView() {\n currentView = 'session';\n const sessionsViewed = document.getElementById(\"defulat-view\").content.cloneNode(true);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Defines an alias for a CSS class name to be used for icon fonts. Creating an matIcon component with the alias as the fontSet input will cause the class name to be applied to the `` element.
registerFontClassAlias(alias, className = alias) { this._fontCssClassesByAlias.set(alias, className); return this; }
[ "classNameForFontAlias(alias) {\n return this._fontCssClassesByAlias.get(alias) || alias;\n }", "function iconClass(iconName) {\n if (iconName == null) {\n return undefined;\n }\n return iconName.indexOf(\"pt-icon-\") === 0 ? iconName : \"pt-icon-\" + iconName;\n}", "addIcon () {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the terrain movement cost at the location specified by x,y. Movement cost is calculated when moving into a given tile.
getTerrainCost(x, y) { return this.getTile(x, y).terrain.cost; }
[ "function tileCost(s, tile, goal, from) {\n var nextTile = (tile.chr === ' ') ? tile : from;\n var lifePenalty = (tile.chr[0] === '$') ? 20 : 0;\n return tile.dist(goal) + tileDanger(s, nextTile, lifePenalty) * 50;\n}", "getTileIndexFromTileCoords(x, y) {\n return x + y * this.width.tiles;\n }", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clear .results field in the html
function clearResults() { $('.results').text(''); }
[ "function clear() {\n\t\t\t//jQuery('div.results').html('');\n\t\t}", "function clearResults(){\n $(settings.results).children().remove();\n }", "function clear_results() {\n $(\"#results\").html( '' );\n}", "function clearResults() {\n $results.children().remove();\n }", "function clea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an OpenLayers marker, move it to a new position (or offset from its current)
function moveMarker({marker, x=0, y=0, r=0, theta=0, pos, lerpTo, lerpAmt}) { let pt = marker.getGeometry() let coord = pos?pos.slice(): pt.getCoordinates() coord[0] += x coord[1] += y coord[0] += r*Math.cos(theta) coord[1] += r*Math.sin(theta) if (lerpTo) { coord[0] = coord[0]*(1-lerpAmt) + lerpAmt*lerpTo[...
[ "function moveMarker(marker) {\n\t// Makes sure new move is inside the grid\n\tvar loc = getNextLocation(marker, DIMS);\n\tmarker.setLocation(loc);\t// set new marker if inside the grid\n\tsetTileMarker(marker); // every iteration gives 1 touch to current tile no matter if it tried to move off the grid or 0\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert table to excel download link dlink: link id
function table2XLS(newW,tlink,dlink){ var datatype="data:application/vnd.ms-excel"; var table_div=newW.document.getElementById(tlink).outerHTML; var url='data:application/vnd.ms-excel,'+encodeURIComponent(table_div); newW.document.getElementById(dlink).href=url; newW.document.getElementById(dlink).download="d...
[ "function table2XLS(newW,tlink,dlink){\r\n\t\tvar datatype=\"data:application/vnd.ms-excel\";\r\n\t\tvar table_div=newW.document.getElementById(tlink).outerHTML;\r\n\t\tvar url='data:application/vnd.ms-excel,'+encodeURIComponent(table_div);\r\n\t\tnewW.document.getElementById(dlink).href=url;\r\n\t\tnewW.document.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the vertical field of view of the camera in radians.
verticalFovInRadians() { return VrMath.degToRad(this.verticalFov()); }
[ "getFieldOfView() {\n return this.camera.fov;\n }", "verticalFov() {\n return this.fov / this.aspect;\n }", "get verticalAngleDegree() {\n const { multiply } = this.operatorSystem;\n return radian2degree(this.verticalAngle, multiply).toString();\n }", "function getCamDir() {\n var camDir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets this web's subwebs
get webs() { return new Webs(this); }
[ "function retrieveSubsites(){ //devuelve el nombre de la url de los subsitios\n \n var enumerator = websColl.getEnumerator();\n while(enumerator.moveNext()){\n var subsite = enumerator.get_current();\n var subsiteSize = 0;\n var objWebs = {Name: subsite.get_title(),Url:subs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hooks things up so that this instance gets notified if/when the editor aborts due to error. Should that happen, a recovery attempt is initiated.
_recoverySetup() { (async () => { await this._editorComplex.bodyClient.when_unrecoverableError(); this._recoverIfPossible(); })(); }
[ "function _onFailedInit() {\n\t\t_settings.onFail();\n\t}", "function __error() {\n\t\tif(__start === true) {\n\t\t\t__wrong = true;\n\t\t\t__start = false;\n\t\t\tobj.prototype.dispatch(\"a.callback.synchronizer.error\", {});\n\t\t\t// The setFail check already it's a function type...\n\t\t\t__fail.apply(this, a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get store selected from dropdown menu
function getSelectedStore(floatingSelect) { var selectedStore = floatingSelect.value; store = "Costco_" + selectedStore; }
[ "selectedSortMenu(store){\n return store.selectedSort\n }", "getCurrentlySelectedOption() {\n let selectElement = document.getElementById(\"locationSelector\");\n return selectElement.options[selectElement.selectedIndex].value;\n }", "function get_selected_option() {\n options ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current cached multivalue for a given directiveIndex within the provided context.
function readCachedMapValue(context, entryIsClassBased, directiveIndex) { var values = context[entryIsClassBased ? 6 /* CachedMultiClasses */ : 7 /* CachedMultiStyles */]; var index = 1 /* ValuesStartPosition */ + directiveIndex * 4 /* Size */; return values[index + 2 /* ValueOffset */] || null; }
[ "getValue (context) {\n if (!context) {\n throw new Error('You can not grab a value from a Tag without context')\n }\n\n if (!context[this.type]) {\n throw new Error('You can not grab a value from a Tag without its provider')\n }\n\n const source = context[this.type]\n const path = this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create FlyingAnimal constructor function that inherit from Animal and has: type favoriteFood currentPlace current place where animal is located in flyOut method that expect place and change current place property of the animal
function FlyingAnimal(type,food,currentPlace,name,age,latinName,legsNo){ Object.setPrototypeOf(this,new Animal(name,age,latinName,legsNo)) this.type=type; this.food=food; this.currentPlace=currentPlace; this.flyOut=(place)=>{ this.currentPlace=place; } }
[ "function AquaticAnimal(typeOfWater,name,age,latinName){\n\nObject.setPrototypeOf(this,new Animal(name,age,latinName,'no'))\n\n this.typeOfWater=typeOfWater;\n this.liveInSaltWater=false;\n this.liveInFreshWater=false;\n this.changeLifeEnvironment=function(typeOfWater){\n if(typeOfWater==='salt')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt for Express template engine. Currently we only support Nunjucks and Jade but it should be trivial to add others if necessary.
templateEngine() { if ( this.options.templateEngine ) { return true; } let done = this.async(); let prompt = [ { type: 'list', name: 'templateEngine', message: 'Select a template engine:', choices: [ 'Non...
[ "function _setTemplateEngine(){\n \tapp.engine('handlebars', handlebars({\n \t\tdefaultLayout: 'main',\n \t\thelpers: helpers,\n \t\tpartialsDir: [\n \t\t\tprocess.cwd() + '/views/partials/'\n \t\t]\n \t}))\n \tapp.set('view engine', 'handlebars')\n\t// Diretorio com as visoes\n\tapp.set('views', process.cwd() + '/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
let allBooks = obj.map(book => book.title); return allBooks; } or
function getTheTitles(obj) { return obj.map(book => book.title); }
[ "static getTitles(...books) {\n return books.map((book) => book.title);\n }", "function listTitles(booksArray) {\n const titleArray = books.map(b => b.title)\n return titleArray;\n}", "function listTitles(booksArray) {\n // create an empty array for 'titles' to be add onto this array\n var arrayTitles =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert a comma decimal (1,25) to decimal
function commadecimal_to_decimal(input) { if (isCommaDecimal(input)) { input = parseFloat(input.toString().replace(",", ".")); if (input === 0 || isNaN(input)) { return false; } else { return input; } } else { alert("Invalid input: " + input); return false; } }
[ "function toNum(x) {return Number(x.replace(\",\", \".\"));}", "function parseFloatFromFieldValue(value) {\n return parseFloat(value.replace(',', '.'));\n }", "function convertComma(str) {\r\n if (str.indexOf(\",\") != -1) {\r\n str = str.replace(\",\",\".\");\r\n }\r\n return Number(str);\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A utility function to find the vertex with minimum key value, from the set of vertices not yet included in MST
function minKey(key,mstSet) { // Initialize min value let min = Number.MAX_VALUE, min_index; for (let v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index; }
[ "minKey(key, mstSet) {\n // Initialize min value\n var min = Number.MAX_SAFE_INTEGER, min_index = -1;\n\n for (var v = 0; v < this.noOfVertices; v++)\n if (mstSet[v] == false && key[v] < min) {\n min = key[v];\n min_index = v;\n }\n\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
signOut Clears the local variables and auth tokens
function signOut() { // Clear Credentials: // updateClientId(""); // updateClientSecret(""); // updateProjectId(""); // Clear Tokens: updateOAuthCode(""); updateAccessToken(""); updateRefreshToken(""); // Clear Devices: clearDevices(); // Signed Out: updateSignedIn(false); }
[ "function signout() {\n resetAuthData();\n localStorageService.remove(AUTH_CONSTANT.DATA_KEY);\n }", "signOut() {\n this.idToken = null;\n this.profile = null;\n this.expiresAt = null;\n }", "function logout() {\n localStorage.removeItem('id_token');\n localStora...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if props have changed, we need to update items selected
componentDidUpdate(prevProps) { if (prevProps !== this.props) this.setState({ selectedItems: new Set() }); return true; }
[ "updateSelectedItem() {\n if (!this.slottedItems)\n return;\n this.slottedItems.forEach((item, index) => {\n // TODO(b/265209253): implement\n // item.itemId = `${this.itemIdPrefix}-${index}`;\n if (this.selectedItem && item === this.selectedItem && this.lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Two random chinese characters with a space between them.
function nonsenseChinesePhrase() { // U0530 - U18B0 all unicode (lots of trains for some reason) // var word = getRandomKatakana() + " " + getRandomKatakana() + " " + getRandomKatakana(); var word = getRandomChineseCharacter() + " " + getRandomChineseCharacter(); word = encodeURIComponent(word); return word; ...
[ "function getRandomChar(){\n const katakana = 12448+95\n return String.fromCharCode(Math.floor(Math.random()*95)+12448)\n}", "function getRandomChineseName()\n{\n var surnameList = [\n '赵','钱','孙','李','周','吴','郑','王',\n '冯','陈','褚','卫','蒋','沈','韩','杨',\n '朱','秦','尤','许','何','吕','施','...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all asteroids locations
function asteroidLocations(asteroidField) { asteroidLocations = [] asteroidField.forEach(function(line, y) { line.forEach(function(space, x) { if (space == '#') asteroidLocations.push([y,x]); }) }); return asteroidLocations; }
[ "function getAllLocations() {\n var spaces = [];\n for (var i = 0; i < gLevel.size; i++) {\n for (var j = 0; j < gLevel.size; j++) {\n var coord = { i: i, j: j };\n if (!gBoard[i][j].isMine) spaces.push(coord);\n }\n }\n return spaces;\n}", "function locationFinder(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to extract classes names from string (assuming correct strings)
function getClassesNames(string) { var salaSubIndexesStart = []; var salaSubIndexesEnd = []; var classesNames = []; // If the string is undefined, return "" if (string == undefined) return ""; // Getting all "Sala" substrings indexes for (var i = 0, j = 0; i < string.length; i++) { if (string.slice...
[ "function get_classname(text) {\r\n // execute the regex statement and return the second group (the classname)\r\n const regex = text.match(/(?:\"classname\" \")(.*?)(?:\")/);\r\n if (!Array.isArray(regex) || !regex.length) {\r\n // array does not exist, is not an array, or is empty\r\n return null;\r\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Arrays Write a function toArray that takes 2 values and returns these values in an array. Example: toArray(5, 9) should return the array [5, 9].
function toArray(a, b) { return [a , b]; }
[ "function toArray(value1, value2) {\n var arr = [];\n arr.push(value1);\n arr.push(value2);\n return arr;\n}", "function toArray(a, b, c) {\n\tvar myArray = [a, b, c];\n\treturn myArray;\n}", "function toArray(arr){\n var out = [];\n for(var i = 0; i < arr.length; i++){\n out.push([arr[i].x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove all selection listeners
function ClearSelectionListeners() { map.off('mousedown'); map.off('mousemove'); map.off('mouseup'); map.off('touchstart'); map.off('touchmove'); map.off('touchend'); map.off('clic...
[ "removeSelectionListeners(){this.document&&this.document.removeEventListener('selectionchange',this.onSelectionChange,!1)}", "removeSelectionListeners(){\n\t\tif(!this.document) {\n\t\t\treturn;\n\t\t}\n\t\tthis.document.removeEventListener(\"selectionchange\", this._onSelectionChange, { passive: true });\n\t\tth...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update all clients with the public list users
function updateClients() { socket.emit('update', [users] ); }
[ "function updateClients(){\n console.log(`Updating clients with new user list...`);\n let message = {\n list: getSystemUserList()\n };\n Object.keys(users).forEach(user =>\n users[user].forEach(connection =>\n connection.emit(UPDATE_CLIENT, message)\n )\n );\n}", "fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a vector composed of the cross product between this and another. Perform cross product between this and another vector, and store the result in 'target'. If target is null, a new vector is created.
crossTarget(v, target) { let crossX = this.y * v.z - v.y * this.z; let crossY = this.z * v.x - v.z * this.x; let crossZ = this.x * v.y - v.x * this.y; target.x = crossX; target.y = crossY; target.z = crossZ; return target; }
[ "cross(outVector, vector1, vector2) {\r\n // @todo\r\n }", "crossTarget( v, target) {\n var crossX = this.y * v.z - v.y * this.z;\n var crossY = this.z * v.x - v.z * this.x;\n var crossZ = this.x * v.y - v.x * this.y;\n\n target.x = crossX;\n target.y = crossY;\n target.z ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
name: _findIndex description: Finds the index for the given target where arr[index 1] < target <= arr[index] within the specified array. parameters: 'target' Float; the target lon or lat value 'metric' String; a string representing which array to search, expects 'lat' or 'lon' returns: Integer; the index of the specifi...
_findIndex(target, metric) { const index = metric === 'lat' ? this._latIndex : this._lonIndex; // check edge cases if (index.length === 0 || index[0][metric] > target) { return 0; } else if (index[index.length - 1][metric] < target) { return index.length; } // modified binary searc...
[ "function binarySearchIndex(array, target) {\n\n}", "static search (arr, goal) {\n let low = 0\n let high = arr.length - 1\n\n while (low != high) {\n let mid = Math.round((low + high) / 2)\n\n if (goal <= arr[mid]) {\n high = mid - 1\n } else {\n low = mid\n }\n }\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Now let's make a subthing.
function subthing2(arg){ thing1.call(this, arg); this.obj2 = 'OBJ2'; }
[ "function SUBTYPE(sup, sub) {\n sub.prototype = new sup();\n sub.prototype.constructor = sub;\n \n}", "function makeSubLink(name, before)\n{\n\tvar link = getMainLink(name);\n\tvar nodBefore = getSubLink(before);\n\taddSubLink(link, nodBefore);\n}", "function addSub() {\n experimentStructure.EXPERIM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function that converts a URL object into an ordinary options object as expected by the http.request API.
function urlToOptions(url) { const options = { serviceName: url.serviceName, conn: url.conn, protocol: url.protocol, hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, hash: url.hash, headers: url.headers, sear...
[ "function urlToOptions(url) {\n const options = {\n protocol: url.protocol,\n hostname:\n typeof url.hostname === 'string' && url.hostname.startsWith('[')\n ? url.hostname.slice(1, -1)\n : url.hostname,\n hash: url.hash,\n search: url.search,\n pathname: url.pathname,\n path: `...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if empty table row then reload if equal to 0
function emptyCheck(){ if($('table tbody tr').length == 1 || dataArray.length == 0){ window.location.reload(); } }
[ "isEmpty(){\n return this.getRows().length == 0;\n }", "function isEmpty() {\n return ( 0 === table.rows().count() );\n }", "function repload_if_no_input(){\n if ($(\".test_empty\").filter(function() { return $(this).val(); }).length === 0) {\n location.reload();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setup next chain script group
function init_script_chain_group() { if (!group || !group.scripts) { chain.push(group = {scripts:[],finished:true}); } }
[ "function init_script_chain_group() {\n if (!group || !group.scripts) {\n chain.push(group = {scripts:[], finished:true});\n }\n }", "function init_script_chain_group() {\n if (!group || !group.scripts) {\n chain.push(gr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns question form Called in main screen in order to addEventListener to said form
function getForm() { return questionForm; }
[ "function setupFormEventListener() {\n}", "function displayQuestion () {\r\n targetQuest(quizContent[0])\r\n}", "showForm() {\n let form = document.createElement(\"form\");\n let input = document.createElement(\"input\");\n // Add input to form\n form.appendChild(input);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Access the WrappedComponent's instance.
getInstance() { if (!WrappedComponent.prototype.isReactComponent) { return this; } const ref = this.instanceRef; return ref.getInstance ? ref.getInstance() : ref; }
[ "get componentInstance() {\n if (this._contentRef && this._contentRef.componentRef) {\n return this._contentRef.componentRef.instance;\n }\n }", "get componentInstance() {\n const nativeElement = this.nativeNode;\n return nativeElement &&\n (getComponent(native...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function Name: blankfunc2 Purpose:Purpose of this function is to validate the form control (For two controls only).
function blankfunc2(id1,id2,check2,id3) { $(check2+'_err1').removeClassName('showElement'); $(check2+'_err1').addClassName('hideElement'); var msg = ""; if($F(id1) == '') { msg += "enter value in field one\n"; $(id1+'_err1').removeClassName('hideElement'); $(id1+'_err1').addClassName('showElement'); //a...
[ "function checkBlanks() {\n\t\tcheckBlank( \"#from\", \"#errorF\" );\n\t\tcheckBlank( \"#to\", \"#errorT\" );\n\t\tcheckBlank( \"#name\", \"#errorN\" );\n\t}", "function disallowBlank(obj) {\r\n var msg;\r\n var dofocus;\r\n if (arguments.length>1) { msg = arguments[1]; }\r\n if (a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pass positions to state
function getPositionsAndSetState() { setFixedPositions({ firstReelStopPosition: { symbolIndex: firstReelSymbol, line: firstReelLine }, secondReelStopPosition: { symbolIndex: secondReelSymbol, line: secondReelLine }, thirdReelStopPosition: { symbo...
[ "function place(state,x,y){\n\tstate.x = x\n\tstate.y = y\n}", "setStartingPositions(ps) {\n this.inactive = this.cs.map(c => { c.active = false; return c; });\n this.bs = new Blocks(this.vs);\n this.bs.forEach((b, i) => b.posn = ps[i]);\n }", "userPos(args){\n this.pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
erase label from label canvas
function eraseMapLabel(label){ if((label === undefined) || (labelMap[label] === undefined)){ return; } var labelObj = labelMap[label]; pushCanvasStack(); indContext.clearRect(0, 0, indCanvas.width, indCanvas.height); /* if (labelObj.coords === undefined){ ...
[ "function clearLabel() {\n}", "removeLabel() {\n this._label = null;\n }", "removeLabel(label) {\n // remove 3d object\n this.remove(label);\n\n // remove dom label\n this.domElements.labels.dom.removeChild(label.content);\n }", "function clear_deleted_text_labels () {\n ut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an instance value, get its apparent primitive type.
function apparentType(val) { switch (typeof val) { case 'boolean': case 'string': case 'undefined': return typeof val; case 'number': if (val % 1 === 0) { return 'integer'; } return 'number'; default: if (val === null) { return 'null'; } if (Array.isArray(val)) { re...
[ "get primitiveType() {\r\n return getPrimitiveType(this.underlyingType);\r\n }", "function getType(value) {\n return ({}).toString.call(value);\n}", "function getObjectType(value) {\n\treturn Object.prototype.toString.call(value)\n}", "getObjectType (value) {\n\t\treturn Object.prototype.toString...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hideDrawingTool(): removes Drawing mode for canvas Inputs: null Returns: null
hideDrawingTool () { this.drawingManager.setDrawingMode(null) this.startedDrawing = false }
[ "function ShowDrawingTools(val) {\n myDrawingManager.setOptions({\n drawingMode: null,\n drawingControl: val\n });\n}", "function ShowDrawingTools(val) {\n myDrawingManager.setOptions({\n drawingMode: null,\n drawingControl: val\n });\n\n}", "disableDrawTool() {\n if (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the next Excel relationship ID
getNextExcelRelationShipID() { return 'rId' + (++this.eRelationShipId); }
[ "getRelationshipId() {}", "getNextChartRelationShipID() {\n return 'rId' + (++this.cRelationShipId);\n }", "findNextID() {\n var maxID = 0;\n\n this.data.forEach( d => {\n if ( d.id > maxID) {\n maxID = d.id;\n }\n });\n \n maxID++;\n var nextID = maxID;\n\n conso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
======================================================== Convert qMatrix to GeoJSON Given the qMatrix Data, it converts it to properly formatted GeoJSON
function buildGeoJSON() { var goodGeoJSON = { type: 'FeatureCollection', features: [] }; qData.qMatrix.map(function (array) { if (typeof array[1].qNum !== 'number' || typeof array[2].qNum !== 'number') return false; var obj = { id: Number(array[0].qNum), lat: Number(a...
[ "function toGeojson (data){\n var features, feature, geojson;\n //Geojson shell format\n geojson = {\n \"type\": \"FeatureCollection\",\n \"features\": []\n };\n\n try {\n //Check Spatial Reference\n if (data.fe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a new authentication strategy under a given name.
register (name, strategy) { // Call the functions a strategy can implement if (typeof strategy.setName === 'function') { strategy.setName(name); } if (typeof strategy.setApplication === 'function') { strategy.setApplication(this.app); } if (typeof strategy.setAuthentication === 'fu...
[ "registerStrategy(name, strategy) {\n this._strategies[name] = strategy;\n }", "function registerOAuth2(providerName, Strategy) {\n registerProvider(providerName, (credentials, passport, authHandler) => {\n passport.use(new Strategy(credentials,\n async(req, accessToken, refreshToken, pro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the tag type in html format of the given element
getTagType(tag) { let el; switch (tag) { case "paragraph": el = "p"; break; case "header": el = "h1"; break; case "order-list": el = "ol"; break; case "unor...
[ "function EZgetTagType(el)\n{\n\tif (!el || !el.childNodes) return '';\n\n\tvar tagName = (el.tagName || '').toLowerCase();\n\tvar tagType = (el.type || '').toLowerCase();\n\n\treturn (/(button|radio|checkbox|text|password|hidden)/i.test(tagType))\n\t\t ? tagType : tagName;\n}", "function elType(elem) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
lattice assumes that max distance to nearest neighbors will never exceed farthest_nearest_neighbor_distance
function IntegerLattice(points, getDistance, farthest_nearest_neighbor_distance){ var lattice = []; var N = 3; var cell_width = 2*farthest_nearest_neighbor_distance; var max_x = Math.max.apply(null, points.map(point => point.x)); var min_x = Math.min.apply(null, points.map(point => point.x)); var range_x = max_...
[ "function IntegerLattice(points, getDistance, farthest_nearest_neighbor_distance){\n var lattice = [];\n var N = 3;\n var cell_width = 2*farthest_nearest_neighbor_distance;\n var max_x = Math.max.apply(null, points.map(point => point.x));\n var min_x = Math.min.apply(null, points.map(point => point.x));\n var range...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the indicated item from the indicated table. If the item has an 'id' property then it will be removed by a query for that id. Otherwise the WHERE clause will be built with all properties of the item.
function delete_item(table, item, callback) { db.transaction(function (tx) { var where; if (typeof(item) == "number") { item = {id: item}; } if (item['id']) { executeSqlLog(tx, "DELETE FROM " + table + " WHERE id = ?", [item['id']], callback); } else { retrieveS...
[ "function removeItemFromDB(id) {\n //TODO\n}", "function deleteOrderItem(tableId, itemId){\n \n for(let index=0; index<tables.length; index++) {\n if(tables[index].tableId == tableId){\n\n for(let itemIndex=0; itemIndex<tables[index].items.length; itemIndex++){\n if( tables...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports a single form from the import queue.
function importForm() { var $processSettings = jQuery( '#frm-importer-process' ), formID = s.importQueue[0], provider = jQuery( 'input[name="slug"]' ).val(), data = { action: 'frm_import_' + provider, form_id: formID, nonce: frmGlobal.nonce }; // Trigger AJAX import for this form. jQuery....
[ "function importForm( $processSettings ) {\n\t\tvar formID = s.importQueue[0],\n\t\t\tprovider = jQuery( '#welcome-panel' ).find( 'input[name=\"slug\"]' ).val(),\n\t\t\tdata = {\n\t\t\t\taction: 'frm_import_' + provider,\n\t\t\t\tform_id: formID,\n\t\t\t\tnonce: frmGlobal.nonce\n\t\t\t};\n\n\t\t// Trigger AJAX impo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the current Device Group name, description and target if needed. Parameters: options : Options impt options of 'project update' command Returns: Promise that resolves when the Project updated successfully or rejects with an error
_updateDeviceGroup(options) { if (options.name || options.description || options.target || options.dut) { return this._deviceGroup._update(options); } return Promise.resolve(); }
[ "update(options) {\n this._checkProjectConfig().\n then(() => this._initDeviceGroup(options)).\n then(() => this._updateDeviceGroup(options)).\n then(() => this._processSourceFiles(options)).\n then(() => this._saveProjectConfig()).\n then(() => this._in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
= Description Sends itself to the back of the given view by changing its ZIndex. Only works on sibling views. = Parameters +_view+:: The view to send to the back of. = Returns +self+
sendToBackOf(_view) { // Ensure the views are siblings if (this.parent.viewId === _view.parent.viewId && this.zOrderDisabled === false) { const _selfIndex = this.zIndex(); if (_selfIndex !== -1) { // removes own index: this.parent.viewsZOrder.splice(_selfIndex, 1); const _oth...
[ "bringToFrontOf(_view) {\n // Ensure the views are siblings:\n if (this.parent.viewId === _view.parent.viewId && this.zOrderDisabled === false) {\n const _selfIndex = this.zIndex();\n if (_selfIndex !== -1) {\n // removes own index:\n this.parent.viewsZOrder.splice(_selfIndex, 1);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The process the adapter is running in
get adapterProcess() { return this._adapterProcess; }
[ "function getCurrentProcess() {\n if (currentProcess !== undefined) {\n return currentProcess.value;\n }\n return undefined;\n }", "get process() {\n const name = this.config.get('process', 'local');\n\n if (!this._process || name !== this._process.name) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function handling going back to main menu from game
function backToMenuFromGame() { resetMatch(); cancelAnimationFrame(requestId); document.getElementById('canvasSpace').style.display = "none"; document.getElementById('menuInGame').style.display = "none"; document.getElementById('settings').style.display = "none"; document.getElementById('menu...
[ "function returnToMainMenu() {\r\n\r\n // Reset the game state. \r\n resetGameState();\r\n\r\n // End game flag.\r\n gameHasStarted = false;\r\n\r\n // Reload main menu.\r\n startUp();\r\n}", "goBackToMenu(){\n this.scene.start(\"Main_Menu\", { configScoreText: this.configScoreText, playe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through values 19 in specific location on board. If one value is a valid move, return the move with the value. Else if no moves are valid, return null.
getValidMove(row, col, digit) { for (let val = digit + 1; val < 9 + 1; val++) { let move = new SudokuMove(row, col, val); if (this.p.isValidMove(move)) { return move; } } ...
[ "function getFirstValidMove(board) {\n let moves = [];\n for (let y = 0; y < board.length; ++y) {\n for (let x = 0; x < 9; ++x) {\n if (board[y][x] != 0) {\n moves.push(...getValidMovesCell(board, x, y));\n if(moves.length != 0)\n return moves...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get: get teacher by username
static async get(username) { const teacher = await db.query( `SELECT username, full_name, email FROM teachers WHERE username = $1`, [username] ); if (!teacher.rows[0]) { throw new ExpressError(`No such user: ${username}`, 404); } const t = teacher.rows[0]; return new Teacher(t.username, t.fu...
[ "function GetTeacher(id) {\n for (var i = 0; i < teachers.length; i++) {\n if (teachers[i].userId == id) {\n return teachers[i]\n }\n }\n}", "function userTeacherGetDetails(userID, teacherID) {\r\n var url = getBaseURL() + \"UserTeachers/\" + userID + \"/\" + teacherID;\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if two cards' suites are of the same color
sameColor(c1, c2) { return c1.suitVal() % 2 == c2.suitVal() % 2; }
[ "isColor() {\r\n const suitedCards = this.getSuitHandArray();\r\n const uniqueSuitedCards = [...new Set(suitedCards)];\r\n return (uniqueSuitedCards.length == 1);\r\n }", "_sameColorCoins(coinA, coinB) {\n\t if (_.isNull(coinA) || _.isNull(coinB)) {\n\t return false;\n\t }\n\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the ship paterns. Then, places the appropriate ship onto the grid.
function initShip() { // ONLY INIT THE SHIP IF ALL THE SHIPS IMAGES ARE LOADED if(imagesLoadedDev === 4) { // 4 IMAGES HAVE BEEN LOADED (ship Up, Right, Down, Left) // Load the patternsDev into the grid // Check which direction the player ship is to be facing and place it there. if (pla...
[ "function loadShip() {\n\tlet ship = new Image()\n\tship.src = data.src.sprites.spaceship.srcs\n\n\tship.onload = function(){\n\t\tdata.src.sprites.spaceship.srcs = ship\n\n\t\tcanvas.width = $(\"#game\").innerWidth()\n\t\tcanvas.height = $(\"#game\").innerWidth()\n\n\t\tlet sc = new CanvasObj(canvas.width/2 - 64, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
\ CardType setCardNumber(cardnumber) return the CardType object. \
function setCardNumber(cardnumber) { this.cardnumber = cardnumber; return this; }
[ "function setCardType(cardtype) \n{\n\tthis.cardtype = cardtype;\n\treturn this;\n}", "function setCardNumber(cardnumber) {\r\nthis.cardnumber = cardnumber;\r\nreturn this;\r\n}", "function setCardType(cardtype) {\r\nthis.cardtype = cardtype;\r\nreturn this;\r\n}", "function typeByNumber(cardNumber) {\r\n\t ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
StreamStack for writing HTTP requests and parsing the response.
function HttpRequestStack(stream) { HttpBaseStack.call(this, stream); }
[ "function HttpResponseStack(stream) {\n HttpBaseStack.call(this, stream);\n}", "function processRequests() {\n return _.pipeline(\n // flatten the incoming array of streams into a single stream\n _.sequence(),\n // Parse JSON out of each stream\n JSONStream.parse(),\n // Do a special transform fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getRomanNumerals_fourthDigitValues() Get the fourth digit (00009000) values for the Roman Numeral system. For example: (nothing; i.e., zero), m (1000), mm (2000), mmm (3000), etc..
function getRomanNumerals_fourthDigitValues() { return [ '', 'm', 'mm', 'mmm', ]; }
[ "function getRomanNumerals_thirdDigitValues() {\n\t\treturn [\n\t\t\t'',\n\t\t\t'c',\n\t\t\t'cc',\n\t\t\t'ccc',\n\t\t\t'cd',\n\t\t\t'd',\n\t\t\t'dc',\n\t\t\t'dcc',\n\t\t\t'dccc',\n\t\t\t'cm',\n\t\t];\n\t}", "function getRomanNumerals_firstDigitValues() {\n\t\treturn [\n\t\t\t'',\n\t\t\t'i',\n\t\t\t'ii',\n\t\t\t'i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================= Crear tabla consecutivo_puertas ==============================================
function crearTablaConsecutivoPuertas(){ db.transaction(function (tx) { tx.executeSql('CREATE TABLE consecutivo_puertas (k_codusuario, k_consecutivo unique, n_inspeccion)'); }, function (error) { console.log('transaction error: ' + error.message); }, function () { console.log('transaction creada ok');...
[ "function crearTablaConsecutivoEscalerasAndenes(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE consecutivo_escaleras (k_codusuario, k_consecutivo unique, n_inspeccion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes this material reference the given [[Coat]] if it is compatible with the referenced [[Shader]]
setCoat(_coat) { if (_coat.constructor != this.shaderType.getCoat()) if (_coat instanceof this.shaderType.getCoat()) FudgeCore.Debug.fudge("Coat is extension of Coat required by shader"); else throw (new Error("Shader and coat don't mat...
[ "createCoatMatchingShader() {\n let coat = new (this.shaderType.getCoat())();\n return coat;\n }", "setShader(_shaderType) {\n this.shaderType = _shaderType;\n let coat = this.createCoatMatchingShader();\n coat.mutate(this.coat.getMutator());\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that allows to get all the oratores (nobles) except the royalty
static async getAllOratores(){ const query = ` SELECT u.firstname, u.lastname, u.mail, u.user_image, sc.social_class, sr.social_rank FROM user u JOIN social_class sc ON sc.id= u.social_class_id JOIN social_rank sr ON sr.id = u.social_rank_id WHERE sc.social_class = "Oratores"...
[ "function getNotOpenPurchaseOrders(req, res) {\n if(!(req && req.user && ( ( req.user.role === \"admin\" ) || ( req.user.role === \"reseller\" ) ) )){\n this.requestUtil.errorResponse(res, { key: \"lic.access.invalid\"});\n return;\n }\n\n this.myds.getNotOpenPurchaseOrders()\n \t.then( fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }