query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Write the trits for the value.
function writeTrits(input, trits, index) { switch (input) { case 0: return 0; default: // eslint-disable-next-line no-case-declarations let abs = Math.floor(input / RADIX); // eslint-disable-next-line no-case-declarations let r = in...
[ "function valueToTrits(input, trits) {\r\n\t var endWrite = writeTrits(input, trits, 0);\r\n\t if (input >= 0) {\r\n\t return endWrite;\r\n\t }\r\n\t for (var i = 0; i < trits.length; i++) {\r\n\t trits[i] = -trits[i];\r\n\t }\r\n\t return endWrite;\r\n\t}", "function writeVals(){\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Class representing a storage of cameraOptions (optional parameters to customize the camera settings) with which camera.getPicture() is called See for cameraOptions description
function Settings() { // Opening options: if ((typeof Camera !== "undefined")) { this.destinationType = Camera.DestinationType.FILE_URI; // cameraOptions: destinationType this.sourceType = Camera.PictureSourceType.PHOTOLIBRARY; // cameraOptions: sourceType this.media...
[ "function setOptions(srcType) {\n var options = {\n // Some common settings are 20, 50, and 100\n quality: 50,\n destinationType: Camera.DestinationType.FILE_URI,\n // In this app, dynamically set the picture source, Camera or photo gallery\n sourceType: srcType,\n encod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch a single Block by it's cid. Adds a `cid` property to each block to make life easier everywhere else. Caches blocks as it gets them and is responsible for the accuracy of the `chainCache` and `blockByCid`.
async fetchBlock(cid) { const block = await lotus.loadSingleBlock(cid); return block; }
[ "async fetchBlock (cid) {\n // found is either the block or a promise of the block.\n const found = this.blockByCid[cid]\n if (found) return found\n\n const fullBlockPromise = api.getJson(`/api/show/block/${cid}`).then(fullBlock => {\n return {\n\t cid: cid,\n header: mapAllBigInts(fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Just generate a test array. Accepts: number of ints to generate. Returns an array of numbers up to 999
function makeArray(n) { let allNums = []; while(n--){ allNums.push(Math.round(Math.random() * 1000)); } return allNums; }
[ "function create_dummy_array(number_n){\n temp_array = []\n for(var i = 0; i < number_n; i++){\n temp_array.push(Math.floor(Math.random() * 9) + 1 )\n }\n return temp_array;\n}", "function create_dummy_array(num){\n\tvar newArr = [];\n\tfor (var i = 0; i < num; i++){\n\t\tnewArr.push(Math.floo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the names and majors of students in a sample spreadsheet:
function listMajors() { gapi.client.sheets.spreadsheets.values.get({ spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms', range: 'A1:50', }).then(function (response) { var range = response.result; if (range.values.length > 0) { appendPre('Name, Major:'); ...
[ "function listMajors() {\n\twindow.alert(\"lm\");\n\tgapi.client.sheets.spreadsheets.values.get({\n\t\tspreadsheetId : '16Fy4uF1MVpAkoW-ads6XabQnuOK2HJQ63mn7FUnNjkE',\n\t\trange : 'Second!F9:F11',\n\t\tmajorDimension : 'COLUMNS',\n\t}).then(function(response) {\n\t\tvar range = response.result;\n\t\tif (range.value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a map of package names to list of packages they provide.
getPackageToProvidedMap() { let mapping = []; this._manifest.forEach( (pkg) => { if('provides' in pkg) { return; } let packageName = pkg.package.value; pkg.provides.value.forEach( (pkgVer...
[ "async getPackages() {\n return [];\n }", "function getPackageNamesSetAndPackagePaths(paths, quiet) {\n\t// this will be a set of package names (from the package.json files)\n\tconst packageNames = new Set();\n\t// this will contain a Map packageName->path\n\tconst packagePathsMap = new Map();\n\tpaths.forEac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set Typegoose's global Options
function setGlobalOptions(options) { if (typeof options !== 'object') { throw new TypeError('"options" argument needs to be an object!'); } logSettings_1.logger.info('"setGlobalOptions" got called with', options); for (const key of Object.keys(options)) { data_1.globalOptions[key] = Obje...
[ "set options(config) {\n this.__config = config;\n }", "static set aotOptions(value) {}", "function setGlobalOptions(options) {\n var self = this;\n self.validationAttrs = options; // save in global\n self.commonObj.setGlobalOptions(options);\n\n return self;\n }", "function setGlob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a new platform instance for the Tado plugin.
function TadoPlatform(log, config, api) { const platform = this; // Saves objects for functions platform.Accessory = api.platformAccessory; platform.Categories = api.hap.Accessory.Categories; platform.Service = api.hap.Service; platform.Characteristic = api.hap.Characteristic; platform.UUID...
[ "function PlatformManager()\n{\n\n}", "function Platform() {\n}", "function createPlatform(injector){if(_platform&&!_platform.destroyed&&!_platform.injector.get(ALLOW_MULTIPLE_PLATFORMS,false)){throw new Error('There can be only one platform. Destroy the previous one to create a new one.');}_platform=injector.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the height (minheight) of all content panels to that of the tallest one. tabContentCol reference to the vtabscontentcolumn element
function equalizeHeights(tabContentCol){ var tallest = getTallestHeight(tabContentCol); //alert("Equalize heights to: " + tallest); setMinHeight(tabContentCol,tallest); }
[ "function setMinHeight(tabContentCol,minHeight){\r\n\t\t\tvar panelHeight = 0;\r\n\t\t\ttabContentCol.children(\"div.vtabs-content-panel\").each(function(i){\r\n\t\t\t\tpanelHeight = $(this).height();\r\n\t\t\t\tif(panelHeight < minHeight){\r\n\t\t\t\t\t$(this).css(\"min-height\",minHeight);\r\n\t\t\t\t\t//$(this)....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set aria labels and apply validators
__setAriaLabelsAndValidator() { this.values = { max: parseFloat(this.max || Infinity), min: parseFloat(this.min || Infinity), step: parseFloat(this.step), }; const ariaAttributes = { 'aria-valuemax': this.values.max, 'aria-valuemin': this.values.min, }; let validators...
[ "__setAriaLabelsAndValidator() {\n const ariaAttributes = {\n 'aria-valuemax': this.values.max,\n 'aria-valuemin': this.values.min,\n };\n\n const minMaxValidators = /** @type {(MaxNumber | MinNumber)[]} */ (\n Object.entries(ariaAttributes)\n .map(([key, val]) => {\n if (val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
jsonifyNotice serializes notice to JSON and truncates params, environment and session keys.
function jsonifyNotice(notice, maxLength) { if (maxLength === void 0) { maxLength = 64000; } var s = ''; try { s = JSON.stringify(notice); } catch (_) { } if (s !== '' && s.length < maxLength) { return s; } if (notice.errors) { for (var i in notice.errors) { ...
[ "function jsonifyNotice(notice, _a) {\r\n var _b = _a === void 0 ? {} : _a, _c = _b.maxLength, maxLength = _c === void 0 ? 64000 : _c, _d = _b.keysBlacklist, keysBlacklist = _d === void 0 ? [] : _d;\r\n if (notice.errors) {\r\n for (var i = 0; i < notice.errors.length; i++) {\r\n var t = new...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all characteristics except those in this sample.
function get_all_characteristics_except(id) { var characteristics = get_all_characteristics(); var fields = sample_characteristic_fields[id]; for (var i = 0; i < fields.length; i++) { var field = fields[i]; var char_id = 'sample_characteristic_' + id + '_' + i; var char = field.children('#' + char_id...
[ "function getUnwanted(members) {\n return members.filter(item => !checkIntensity(getPersonProfile(item.decData[1])));\n }", "getFilteredAttributes() {\n const attributes = this._attributes;\n if (Object.keys(attributes).length) {\n const attr = Object.entries(attributes).\n filter(([key,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isBusted function Used to check if a person has been busted
function isBusted(person) { // Calculate min value assuming Aces are 1. var minVal = (person.aces) + (person.sum); // If busted set the person's NotBusted flag and disable the hit and stick buttons. if (minVal > 21) { person.notbusted = false; if (person.name === "player") { ...
[ "function canAffordBet(){\n refreshTotalBet();\n //if bet doesn't surpass the money, return true\n // NOTE: because of this call, its letting the bet get higher than the money\n return (totalBet <= money);\n}", "isBust(){\n return (this.calculateHand() > 21);\n }", "isOnBlocklist(authorID) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
countdown timer... once timer expires, display player score and leaderboard
function activate_timer() { var countdown_timer = window.setInterval(function() { timer--; document.getElementById("remaining_time").innerHTML = timer; if (timer == 0 ) { clearInterval(countdown_timer); showLeaderboard(); } },1000); }
[ "function countdown() {\n // timeRemaining is incremented down\n timeRemaining --;\n\n // If time runs out, runs gameOver()\n if (timeRemaining <= 0) {\n gameOver();\n }\n\n // Updates the timer element\n timer.text(timeRemaining);\n }", "function set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether there is a connection error
function hasConnectionError() { return settings.connectionError; }
[ "function checkGetConnectionError(err, conn, callback) {\n if (err) {\n if (conn) {\n conn.release(); // release necessary\n }\n\n callback(err, null);\n \n return false;\n } else {\n return true;\n }\n}", "function connectionErrorCheck(error) {\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
disable user editing on admin, same logic as above disable edit
function disableEditingUser(userId){ $('#'+userId+'-email').attr('disabled','disabled'); $('#'+userId+'-save').attr('disabled','disabled'); $('#'+userId+'-edit').show(); $('#'+userId+'-cancel').hide(); }
[ "disableAdminMode() {\n octopus.toggleAdminValue();\n this.editForm.style.display = 'none';\n }", "disableEditing() {}", "function enableEditingUser(userId){\n $('#'+userId+'-email').removeAttr('disabled');\n $('#'+userId+'-save').removeAttr('disabled');\n $('#'+userId+'-edit').hide();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if given value is in a array of allowed values.
function isIn(value, possibleValues) { return !(possibleValues instanceof Array) || possibleValues.some(possibleValue => possibleValue === value); }
[ "function isIn(value, possibleValues) {\n return !(possibleValues instanceof Array) || possibleValues.some(function (possibleValue) { return possibleValue === value; });\n}", "function isIn(value, possibleValues) {\n return !(possibleValues instanceof Array) || possibleValues.some(function (possibleValu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
searches the front of the string looking for a type (int or string) returns boolean
function matchType() { var pattern = /^(int|string|boolean)/; var x = lexString.match(pattern); if(x !== null){ return true; } else { return false; } }
[ "function type(string) {\n return typeof (string) === \"string\"\n}", "function checkFor_Object(str){\n if(str.indexOf(\"type_network\")!=-1){ return false; }\n if(str.indexOf('_daily') >= 0 || str.indexOf('_network') >= 0 || str.indexOf('_device') >= 0){\n return true;\n }\n return false;\n}", "funct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copies resource read by readResource, returns Promise with array of fileNames left to read / copy
function copyResource(promisedArray, path=defaultPath) { let filename = promisedArray[0], data = promisedArray[1], filenameArray = promisedArray[2]; return new Promise((res, rej) => { fs.writeFile(path + "/" + filename, data, (err) => { return err ? rej(err) : res(filenameArray); }...
[ "function readResource(filenameArray) {\n let filename = filenameArray.pop();\n return new Promise((res, rej) => {\n fs.readFile(__dirname + \"/resources/\" + filename, (err, data) => {\n let promisedArray = [filename, data, filenameArray];\n return err ? rej(err) : res(promisedAr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
prepare reply to single tweet
reply(tweet) { const replyTo = tweet.user.screen_name; const replyName = tweet.user.name; const id = tweet.id_str; const text = _.sample(responses); console.log(`Replying to @${replyTo}`); const message = `@${replyTo} Hi ${replyName}! ${text}`; // favorite each tweet so we know which ones ...
[ "function process_tweet(tweet){\n if(tweet.in_reply_to_status_id) {\n console.log(\"Ignoring reply\")\n }\n else if(tweet.retweeted_status) {\n retweet(tweet.retweeted_status);\n }\n else {\n echo_tweet(tweet)\n }\n}", "function process_tweet(tweet) {\n if(tweet.in_reply_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Usage : allPlayersJoined() For : nothing After : returns a obj with a attribute of true if all players are occupied by sockets
function allPlayersJoined() { const lobbyState = GameLobby.countAllPLayers(); // fetch array for(let i =0; i < lobbyState.length; i++){ if(lobbyState[i] === false) { return { alljoined : false, hasnotgamestarted : lobbyState } } } return { alljoined : true, hasnotgamestarted : null } }
[ "socketsEmpty() {\n return this.playerMap.getActivePlayerCount() < 1;\n }", "function allPlayersRegistered() {\n // Initialize our registered variable.\n var registered = true;\n \n // Iterate through all flash objects.\n for( id in flashObjects ) {\n // AND the ready flags together.\n regis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function is called when "save" is clicked after adding an area
function saveAreaButton() { areaData = new Object(); areaData.name = document.getElementById("AreaName").value; //Data checking if(!areaData.name){ document.getElementById("alertMessageText").style.color = "#FFFFFF"; document.getElementById("alertMessageText").style.fontWeight = "bold"; document...
[ "function areaSave() {\n\n mapset = setCenter.shift();\n if (mapset) {\n areasaveStatus = true;\n areaStatus(' Area ' + (Math.pow(scale, 2) - setCenter.length) + '/' + Math.pow(scale, 2));\n init_lat = mapset[0];\n init_lng = mapset[1];\n init_zoom = mapset[2];\n myLa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endregion region Navigation Triggered from GridNavigation when focus is moved to another cell within the grid. Selects the cell unless modifier keys are pressed, in which case it has already been handled
onCellNavigate(me, fromCellSelector, toCellSelector, event, doSelect = true) { // CheckColumn events are handled by the CheckColumn itself. if (me.columns.getById(toCellSelector.columnId) === me.checkboxColumn) { return; } // 1.do not affect selection if focus is returning to the grid f...
[ "onCellNavigate(me, fromCellSelector, toCellSelector, event, doSelect = true) {\n // CheckColumn events are handled by the CheckColumn itself.\n if (me.columns.getById(toCellSelector.columnId) === me.checkboxColumn || me.selectionMode.rowCheckboxSelection) {\n return;\n } // 1.do not affect selection ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A map of string to V extends IUnknown.
function StringIUnknownMap() { _super.call(this, 'StringIUnknownMap'); /** * @property elements * @type {{[key: string]: V}} */ this.elements = {}; }
[ "Initialize(string, IUnknown, string) {\n\n }", "function ChimeiMapType() {\n}", "function getIconNamesMap() {\n const keys = Object.keys(GameIcon).filter((key) => key.startsWith(\"Gi\"));\n const result = new Map();\n for (const key of keys) {\n result.set(key.toLowerCase(), key);\n }\n return resul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create Stack navigator for Created events
function stackNavigatorCreateEvent() { return( <Stack.Navigator style={{backgroundColor: '#2c959e'}}> <Stack.Screen name="Add event" component={Add_Edit_Event} options={{ title: 'Create a new event', headerStyle: { backg...
[ "createNewStack() {\n let stack = new Stack();\n this._stacks.push(stack);\n this._registers.push(null);\n this._callbackUpdateStack(\"register\", \"push\", null);\n this._updateStackGUI();\n return stack;\n }", "handleStacks() {\n this.goldenLayoutInstance.on('stackCreated', stack => {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=====================================================================\ void changeLanguage(radio) \=====================================================================
function changeLanguage(radio) { stopCode(); localStorage.setItem('lan', JSON.stringify(radio.value)); location.reload(); }
[ "_setLanguage(language) {\n strings.setLanguage(global.lang[language].shortform)\n global.languageSelected = global.lang[language].shortform\n Alert.alert(strings.changeLanguage, strings.getString(global.lang[language].longform))\n }", "function toggleLanguage() {\n if (selectedLanguage == LANG_P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Submit form We overwrite it as we want to update Reported obejct, record and url fields to latest values These values can change because our app can be in console and tabs can change
handleSubmit(event){ event.preventDefault(); // stop the form from submitting const fields = event.detail.fields; //Update RecordId, ObjectAPIName based on URL in case URL has changed in console //There is no way to track URL changes as there is no API and component doesn't re-ren...
[ "@api\n handleSubmit() {\n this.template.querySelector(\"lightning-record-edit-form\").submit();\n }", "function submit(){\n\n if (!this.formtitle) return;\n const obj = Program.createWithTitle(this.formtitle).toObject();\n\n if (this.formvideo){\n obj.fields.video = {value: this.formvideo, typ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
constructor for MyForm obj formId specific id of form btnId id of submit button of the form fioName name attribute of the FIO form input emailName name attribute of the EMAIL form input phoneName name attribute of the PHONE form input
function MyForm (formId, btnId, fioName, emailName, phoneName) { var myForm = document.querySelector(formId); var btn = document.querySelector(btnId); var fio = myForm[fioName]; var email = myForm[emailName]; var phone = myForm[phoneName]; var validity = { isValid: false, errorFields : [] }; this.valid...
[ "function MASH_Form(tmpID, tmpName, tmpMethod, tmpEnctype, tmpAction, tmpOnreset, tmpOnsubmit, tmpTarget, tmpInputs) {\n \n this.id = tmpID;\n this.name = tmpName;\n this.method = tmpMethod;\n this.enctype = tmpEnctype;\n this.action = t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Note: For inline images this is not implemented show all background images having the same url as the clicked image.
function backgroundImages(){ // URL of the clicked image var url = "url(\"" + imageSrcUrl + "\")"; // loop through all elements var allelements = document.getElementsByTagName('*'); for (i = 0; i < allelements.length; i++) { var elem = allelements[i]; var prop = window.getComputedStyle(elem, null).getPropertyV...
[ "function showImages() {\n [...document.querySelectorAll('.comment .comment-text .comment-copy a')].forEach(anchor => {\n const href = anchor.href;\n const parent = anchor.parentNode;\n\n if (parent && href && (/i(\\.stack)?\\.imgur\\.com/.test(href))) {\n if (!parent.qu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback : gbViewDidDisappear Called just after the view appears.
function gbViewDidDisappear () { pluginDidDisappear = true; }
[ "function gbViewDidAppear ()\n{\n\tif ( pluginDidDisappear )\n\t\trefresh ();\n}", "deactivateView() {\r\n if (this.currentView.constructor.is) {\r\n this.currentView.dispatchEvent(new CustomEvent('lazy-board-view-exit'));\r\n }\r\n // The current view is hiding.\r\n this.currentView.style.displa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if insertion, try to combine with left insertion (if both have content property)
* tryCombineWithLeft (op) { if ( op != null && op.left != null && op.content != null && op.left[0] === op.id[0] && Y.utils.compareIds(op.left, op.origin) ) { var left = yield* this.getInsertion(op.left) if (left.content != null && left.id[1...
[ "function transformInsertDelete (a, b) {\n if (a.type === DELETE) {\n return transformInsertDelete(b, a)\n }\n // we can assume, that a is an insertion and b is a deletion\n // a is before b\n if (a.pos <= b.pos) {\n b.pos += a.str.length\n // a is after b\n } else if (a.pos >= b.pos + b.str.length) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the local userObj
function load_userObj(data) { userObj.id = data.id; userObj.email = data.email; userObj.nick = data.nick; userObj.name = data.name; userObj.role = data.role; }
[ "function fillUpUserObj() {\n fs.readFile('users.json', function (err, data) {\n if (!err) {\n try {\n userObj = JSON.parse(data);\n } catch (e) {\n console.error(e);\n }\n }\n });\n}", "function loadUserInfo() {\n\tuserInfo = JSON...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
nlNL validation function (Burgerservicenummer (BSN) or Rechtspersonen Samenwerkingsverbanden Informatie Nummer (RSIN), persons/entities respectively) Verify TIN validity by calculating check (last) digit (variant of MOD 11)
function nlNlCheck(tin) { return algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) { return parseInt(a, 10); }), 9) % 11 === parseInt(tin[8], 10); }
[ "function nlNlCheck(tin) {\n return reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) {\n return parseInt(a, 10);\n }), 9) % 11 === parseInt(tin[8], 10);\n}", "function qfs_isInternationalBankAccountNumber(inputObj) {\t\n\n\t// Het is een geldige IBAN als aan de volgende voorwaarden is voldaan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of taxids for the current ideogram Also sets configuration parameters related to taxid(s), whether ideogram is multiorganism, and adjusts chromosomes parameters as needed
function getTaxids(callback) { var taxidInit, ideo = this; taxidInit = 'taxid' in ideo.config; ideo.config.multiorganism = getIsMultiorganism(taxidInit, ideo); if (ideo.config.multiorganism) ideo.coordinateSystem = 'bp'; if ('organism' in ideo.config) { const org = ideo.config.organism; if (ty...
[ "function sortTaxidsByOriginalOrganismOption(ideo) {\n var configOrganisms, sortedTaxids, i;\n configOrganisms = ideo.config.organism;\n sortedTaxids = [];\n if (Array.isArray(configOrganisms)) {\n // Handling multi-organism ideogram\n for (i = 0; i < configOrganisms.length; i++) {\n sortedTaxids.pus...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mouse pointer / ; ; ; fBCxxRead(nAddr) ; ; Read address nAddr in range BC00BFFF ; ;
function fBCxxRead(nAddr){ switch (a = nAddr){ case 0xbde8: return nBDE8; case 0xbde9: return nBDE9; case 0xbdea: return nBDEA; case 0xbffe: return bRAMROM_enable ? aBFFE : a>>8; case 0xbfff: return bRAMROM_enable ? aBFFF : a>>8; } }
[ "function cursor_Grab()\r\n{\r\n cursor('grab');\r\n}", "pointerHighlight()\n {\n this.pointerUpAndDown(2, 10, 250)\n }", "function fngetMouseXY(e) {\r\n\t\t\t// x-y pos.s if browser is IE\r\n\t\t\tif (IE) { \r\n\t\t\t\tvar position=getScrollingPosition();\r\n\t\t\t\tmintXPos = event.clientX + po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disable editing in the textarea (used while an upload is in progress)
disable() { let textarea = this.get('element'); textarea.setAttribute('readonly', 'readonly'); }
[ "disableEditing() {}", "function cancelEditingNoteText() {\r\n editingNoteTextarea = false;\r\n}", "disableEdition() {\n this.contentEditable = false;\n }", "enable() {\n let textarea = this.get('element');\n textarea.removeAttribute('readonly');\n }", "disableEditing() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
our party invite has expired
function party_uninvited(party, inviter){ // TODO: remove any invites from this player from the familiar queue this.party_activity('Your invite from '+utils.escape(inviter.label)+' to join their party has expired'); }
[ "get expired() {\n return this.invokedAt + 1000 * 60 * 15 < Date.now();\n }", "function checkForExpiry (instance, instanceName, res, next) {\n\n if (instance.expiryDate && instance.expiryDate < new Date()) {\n var messsage = {code:'0031' ,message:'Grant has expired. Need to request for Grant aga...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restore the state of the connection to reflect the instance's stored connection state.
function _restoreInstanceConnection(connection, instanceConnection) { (connection.dbs || []).forEach(function (db) { db.checked = !!(app.findBy(instanceConnection.dbs, 'name', db.name) || {}).checked; }); connection.search = instanceConnection.search; ret...
[ "restoreState() {\n this.current = Object.assign({}, this.savedState.current)\n this.waiting = Object.assign({}, this.savedState.waiting)\n this.vdu.cursor.restoreState(this.savedState.cursor)\n }", "restore() {\n\t\t\tthis._r.restore();\n\t\t}", "restore() {\n _.extend(this, this._re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2. Define a static create method to return new icosahedrons
static createMesh( spec = {} ) { // 3. Setup default values or use arguments let { color = '#FF00FF', radius = 1, detail = 0, // greater than 1, it's effectively a sphere. wireframe = true, } = spec; // 4. Use ThreeJS to define a 3D icosahedron var ...
[ "static create( spec = {} ) {\n \n // 3. Setup default values or use arguments\n \n let {\n name = \"icosahedron\",\n x = 0.0,\n y = 0.0,\n z = 0.0,\n mesh = IcosahedronFactory.createMesh( spec ),\n } = spec;\n \n let { geometry, material } = mesh; \n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert data from the DataObserver to barData array
_convertedDataToBarData(data) { let barData = []; // update barData pice by pices for (let n = 0; n < data.length; n++) { barData.push([]); if (typeof data[n].Observations !== 'undefined') { for (let i = 0; i < data[n].Observations.length; i++) { ...
[ "function transformBarData(data) {\n return data.map(function(el) { return [el.x, el.id__count]; });\n}", "function getBarData() {\n \"use strict\";\n //set up chart data\n var data = {}; \n data.labels = pointLabels;\n data.datasets = getDataSet();\n return data;\n}", "function barGraph...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shifts all rows down above row_index
shiftRowsDown(row_index) { // replace each row with row above from bottom to top for (let i = row_index; i > 1; i--) { for (let j = 0; j < this.numCols; j++) { let topCell = this.rows[i - 1][j]; let bottomCell = this.rows[i][j]; bottomCell.bloc...
[ "function shiftUp() {\n var row = d3.select(this);\n var index = row.datum().index;\n var id = row.datum().id;\n moveRow(id, index - 1);\n}", "shiftIndexes(index) {\n\t\tfor (let i = index; i < this.length - 1; i++) {\n\t\t\tthis.data[i] = this.data[i + 1];\n\t\t}\n\t\tdelete this.data[this.length - 1];\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DOM inject the debug logger
function createDebugLogger(){ $('BODY') .prepend( $('<div />') .append( $('<h4 />') .html('Output log event') ) .append( $('<div />') .attr('class','inner') ) .attr('id','logger') ...
[ "function debug(message) {\n if (!message) return;\n var domTest = document.getElementById('dom_test');\n domTest.innerHTML += ('<div class=\"debug\">' + message + '</div>');\n}", "function createDebug(){\n\t\tdebug = document.createElement('div');\n\t\tdebug.id = 'birdview_debug';\n\t\tdebug.innerHTML = 'DEBU...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements the parsing rules in the Fragments section. Corresponds to both FragmentSpread and InlineFragment in the spec. FragmentSpread : ... FragmentName Directives? InlineFragment : ... TypeCondition? Directives? SelectionSet
parseFragment() { const start = this._lexer.token; this.expectToken(TokenKind.SPREAD); const hasTypeCondition = this.expectOptionalKeyword('on'); if (!hasTypeCondition && this.peek(TokenKind.NAME)) { return this.node(start, { kind: Kind.FRAGMENT_SPREAD, name: this.parseFragmentNam...
[ "parseFragmentDefinition() {\n var _this$_options;\n\n const start = this._lexer.token;\n this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes\n // the grammar of FragmentDefinition:\n // - fragment FragmentName VariableDefinitions? on TypeCondition Dire...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to show desktop notification
function showdesktopnotification() { // Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } // Let's check whether notification permissions have already been granted else if (Notification.permission === "gran...
[ "function desktopNotification(name, message) {\n console.log(\"desktopNotification\");\n notifier.notify({\n title: name,\n message: message,\n });\n}", "function showNotification(title , options){\n\t\t\tif ( showNotificationFlag ){\n\t\t\t\tdesktopNotification.show(title, options);\n\t\t\t}\n\t\t}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCIONES / Carga el contexto Canvas
function CargaContextoCanvas(idCanvas){ var elemento = idCanvas; if(elemento && elemento.getContext){ var contexto = elemento.getContext('2d'); if(contexto){ return contexto; } } return false; }
[ "function cargaContextoCanvas(idCanvas){\n var elemento = document.getElementById(idCanvas);\n if(elemento && elemento.getContext){\n var contexto = elemento.getContext('2d');\n if(contexto)\n return contexto;\n }\n return FALSE;\n}", "createCanvasContext() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the validity of a port
function validPort(port) { return port && Number(port) === port && port % 1 === 0 && port > 0; }
[ "function isValidPort(port) {\n return !((typeof port !== ALLOWED_TYPE) || ((port % 1) !== 0) || (port < MIN_PORT));\n}", "function validPort(port) {\n return port &&\n Number(port) === port &&\n port % 1 === 0 &&\n port > 0;\n }", "function isValidPort(port) {\r\n var fromport = 0;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the date of the last entry in unixTime.
function retrieveLastDate(sheet) { var lastRow = sheet.getLastRow(); console.log('Found the last row in the sheet: ' + lastRow); var unixTime = 631152000; // date of 1-1-1990, used if there is no activity available if (lastRow > 1) { var dateCell = sheet.getRange(lastRow, 1); var dateString = dateC...
[ "function dateNowUnix() {\n return moment().unix();\n }", "function unix_timestamp () {\n return Math.floor((new Date).getTime()/1000) ;\n }", "function GetNowUnix(){\n var d = new Date();\n return Math.round((d.getTime() / 1000));\n }", "getLastSearchTime(sid){\n\n l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
startVal: value to start the animation at endVal: value to end the animation at duration: how long (in milliseconds) the animation should last interpolator: function(start, end, t) that interpolates the start and end values given a percentage of duration elapsed thus far valueHandler: function(prevVal, currVal) that pr...
function animate(startVal, endVal, duration, interpolator, valueHandler) { var startTime = Date.now(); var prevVal = interpolator(0, startVal, endVal); function animStep() { var currTime = Date.now(); var t = (currTime - startTime) / duration; var last = t > 1; if (last) t = 1; var currVal = interpol...
[ "function animateValue(id, start, end, duration) {\n\n var range = end - start,\n current = start,\n increment = end > start? 1 : -1,\n stepTime = Math.abs(Math.floor(duration / range)),\n obj = $(id);\n\n var timer = setInterval(func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
runs a test: creates its frame (out of sight), registers first at the frame's page, then at the frame's QUnit to observe the progress and notice when it's finished
function runTest(oTest) { function onLoad() { var oQUnit = oTest.frame.contentWindow.QUnit; oTest.frame.removeEventListener("load", onLoad); // see https://github.com/js-reporters/js-reporters (@since QUnit 2) oQUnit.on("runStart", function (oDetails) { oTest.testCounts = oDetails.testCounts; ...
[ "function runTest(oTest) {\n\t\t\t// finishes the test: sets the CSS according to the status, removes the frame and starts\n\t\t\t// the next test\n\t\t\tfunction finish(bFailed) {\n\t\t\t\toTest.element.firstChild.classList.remove(\"running\");\n\t\t\t\tif (bFailed) {\n\t\t\t\t\toTest.element.firstChild.classList....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
employeeTemplateSidebar Used to display employees in sidebar
function employeeTemplateSidebar(employee) { return ` <!-- start employee --> <div class="list-group-item list-group-item-divider"> <div class="avatar float-right"> <img class="rounded-circle img-fluid d-block mx-auto" src="${employee.profilbilde}" onerror="this.onerror=null;this.sr...
[ "function addToStaffSidebar (map, rc, feature, layer) {\n var $employeeLabel = $('<div class=\"employee-card\"></div>'),\n $employeeMainInfo = $('<div class=\"employee-info\"></div>');\n\n if (feature.properties) {\n if (feature.properties.photo) {\n $employeeLabel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toast next message in toaster stack. Returns child element that was toasted.
function toastNext_(toastEls) { // Get the next message element that needs to be toasted. var toastEl = getFirstWithoutClass(toastEls, 'nc-toasted'); if (toastEl) toastEl.classList.add('nc-toasted'); return toastEl; }
[ "function nextToast() {\n\t\tif(toastQueue.length > 0) {\n\t\t\tsetHTML(toastQueue[0]);\n\t\t\telement.className = '';\n\t\t\twindow.setTimeout(setInivisble, 3000);\n\t\t\twindow.setTimeout(toastShown, 4001);\n\t\t}\n\t}", "displayNextMessage() {\n\t\tif (!this.messageQueue.length) return;\n\n\t\tlet messageNodes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
VIEWING INFO If they wanted to view info, determine what info they wanted to view and invoke the appropriate function to get and display the data...
function directUserFromViewInfo() { if (nextStep == "Departments") { viewDepartments(); } if (nextStep == "Roles") { viewRoles(); } if (nextStep == "Employees") { viewEmployees(); } if (nextStep == "All Information") { ...
[ "function viewMoreInfo(crimid) {\n javascriptMethods.viewInfo(crimid);\n}", "function displayInfo(returnedInfo){\n\t// Print the results to the page:\n\twriteit(returnedInfo,\"trackInfo\");\n}", "function displayInfo(){\n checkRoute();\n showDistanceWalked();\n showSpeed();\n showRemainingDistance(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a character of a given value from the enemies array
function removeFromEnemyPool(value) { for (var index in enemies) { enemyValue = enemies[index].value; if (value == enemyValue) { enemies.splice(index, 1); } } }
[ "function removeEnemyFromArray() {\n\tvar y = parseInt(lastChar);\n\tvar z = availableEnemies.indexOf(y);\n\tavailableEnemies.splice(z, 1);\n\t$(\".currentEnemy\").empty();\n}", "function removeEnemy(e) {\n var i = enemies.indexOf(e);\n enemies.splice(i, 1);\n}", "function removeEnemies() {\n enemies =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Column_DECIMAL extends NumericColumn =============================================================================
function Column_DECIMAL() {}
[ "function Column_NUMERIC() {}", "function NumericColumn() {}", "function Column_FLOAT() {}", "function Column_DOUBLE() {}", "function Numeric (p, precision, scale) {\n return new ConcreteColumnType(SQL_NUMERIC, p, precision, scale)\n }", "function field_decimal(data,editable,config) {\n\tif (typeo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fuzzy search a list of map titles. resolve if one matches, reject if none match.
function FuzzySearchMapTitle(searchTerm, mapList) { return new Promise((resolve, reject) => { const searcher = new FuzzySearch(mapList, [], { sort: true }); const searchResults = searcher.search(searchTerm); // Check for 0 matching map results, reject or resolve. if (searchResults.length < 1) { ...
[ "searchTitleFuzzy(input){\r\n // Fuzzy Search the quiz title\r\n let results = fuzzy.filter(input, this.quizList, {extract: (el) => {\r\n return el.title;\r\n }})\r\n this.searchFuzzy(results);\r\n }", "function mapMatchingTitles(title) {\n const mapping = [];\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns Deployment resource type
static get _TYPE() { return 'deployment'; }
[ "getResourceType() {\n return super.getAsNullableString(\"resource_type\");\n }", "static get RESOURCE_TYPE() {\n return (RESOURCE_TYPE);\n }", "function get_renderable_resource_type(resource_type) {\n // Check for alt_resource_type and skip if found\n var alt_resource_type = window.MODEL_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST Body: "name": "Experiment 20180410193115", "codeType": "QASM2", "qasm": "\n\ninclude \"qelib1.inc\";\nqreg q[5];\ncreg c[5];\nu2(4pi/3,2pi) q[0];\nu2(3pi/2,2pi) q[0];\nu3(pi,0,pi) q[0];\nu3(pi,0,pi/2) q[0];\nu2(pi,pi/2) q[0];\nu3(pi,0,pi/2) q[0];\nmeasure q > c;\n"}
function experiment (name, qasm, shots, device) { let options = { url: _config.url + '/codes/execute?access_token=' + _accessToken + '&shots=' + shots + '&deviceRunType=' + device, headers: {'Content-Type': 'application/json', 'x-qx-client-application': _userAgent} , form: {'name': name, "codeType": "QASM2", "...
[ "function QREncoder() {\n var bitMatrix = qrEncoder.encode(\"HTTPS://QR1.CH/Q/8452D30565044CMP9OI4CC7D47938DF\", 3);\n}", "function generateQR() {\r\n if (address.value==\"\") {\r\n address.focus();\r\n return false;\r\n }\r\n if (amount.value==\"\") {\r\n am...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
O(1) only goes through the loop one time because of the break.
function breakTheLoop() { for (let i = 0; i < 45; i++) { console.log(i); break; } }
[ "function disruptiveBreakStatement() {\n for (let index = 0; index < arrayBreak.length; index++) {\n console.log(\"in the loop\")\n\n if (index === 3) {\n break;\n }\n }\n}", "function f1() {\n for (var k = 0; k < 2; k++) { // Break 1\n var v10 = 0; ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to display Copied Message
function displayCopiedMessage() { let template = `<div class="message"> <h3>Copied</h3> </div>`; var copiedmessage = $("<div>"); copiedmessage.html(template); $("body").append(copiedmessage); setTimeout(() => { copiedmessage.remove(); }, 2000); }
[ "function showCopiedMessage() {\n vm.copyStatus = \"Copied!\\n\";\n }", "function showcopied(current) {\n var en = \"Current position<br>\" + current + \"<br>copied to clipboard.\"\n var ja = \"現局面は<br>\" + current + \"<br>クリップボードにコピーしました。\"\n showmessage({\n en: en,\n ja: ja\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds shared album to family
async addSharedAlbum(familyid, body){ data = { URI:`${FAMILIES}/albums/${familyid}`, method: 'PUT', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: this.buildFormBody(body) } return await this.sendRequest(data) }
[ "async shareAlbum(albumID){\n const token = await GoogleSignin.getTokens();\n data = {\n URI: `https://photoslibrary.googleapis.com/v1/albums/${albumID}:share`,\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Autho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a tweet bubble for the specified tweet
function createTweetBubble(tweet){ var bubble = new TweetBubble(); bubble.user.login = tweet.user.screen_name; bubble.user.name = tweet.user.name; bubble.tweetText = tweet.text; bubble.mood = getMood(bubble.tweetText); bubble.tweetTime = new Date(tweet.created_at).getTime(); var rangeMilliseconds = bubble.getRan...
[ "function buildTweet(tweet) {\r\n var content = '';\r\n content += '<li>';\r\n content += '<a href=\"http://twitter.com/' + tweet['user']['screen_name'] + '\">';\r\n content += formatTweetTime(tweet.created_at);\r\n content += '</a>';\r\n content += ' - ';\r\n content += processTweet(tweet.text...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
navigates to the specific item, by adding it to the path and populating the results.
function navigateTo(activeItem) { var text = $(activeItem).text(); var path = $(activeItem).data("path"); var children = parseInt($(activeItem).data("children")); if (children > 0) { path = path + "\\"; $(idSearchBoxJQ).val(path); populateResults();...
[ "getItemId(item){return this.itemIdPath?this.get(this.itemIdPath,item):item;}", "getItemId(item){return this.itemIdPath?this.get(this.itemIdPath,item):item}", "function drillToItem() {\n /* locate an item in the data tree\n and get it as an object */\n const item = treeData.search(\"name\", \"Item 3-4\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove asset from assetList array then reload asset list dropdown
function removeAssetFromDropdown(aAssetID) { var tempAssetList = []; for (var i=0,len=assetList.length;i<len;i++) { currentAsset = assetList[i]; if (currentAsset.AssetID != aAssetID) { tempAssetList.push(currentAsset); } } assetList = tempAssetList; loadAssetDropDownFromArray(); }
[ "function loadAssetDropDownFromArray() {\n assetDropDown = $('#asset-id-dropdown');\n assetDropDown.empty();\n assetDropDown.append('<option value=\"\" disabled selected hidden>Please Select</option>');\n for (var i = 0,len=assetList.length;i<len;i++) {\n currentAsset = assetList[i];\n var newOptionItem =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Selector Switch 4 Position 2 Extends mxShape.
function mxShapeElectricalSelectorSwitch4Position2(bounds, fill, stroke, strokewidth) { mxShape.call(this); this.bounds = bounds; this.fill = fill; this.stroke = stroke; this.strokewidth = (strokewidth != null) ? strokewidth : 1; }
[ "function mxShapeElectricalSelectorSwitch3Position2(bounds, fill, stroke, strokewidth)\n{\n\tmxShape.call(this);\n\tthis.bounds = bounds;\n\tthis.fill = fill;\n\tthis.stroke = stroke;\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\n}", "function mxShapeElectricalFourPositionSwitch2(bounds, fill, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes app state as arg whatever gets returned will show up as props inside of band list
function mapStateToProps (state) { return { bands: state.bands } }
[ "function mapStateToProps(state){\n\treturn{\n\t\tbands: state.bands\n\t};\n}", "function getDataFromAppState(appState) {\n\n //Whatever we return is put on props\n return {\n message: 'hello from the other side',\n currentValue: appState.currentValue,\n state: appState\n }\n}", "sendProps(){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API call to fetch tickets associated with a player
@action searchTickets(queryParams) { const id = this.selectedPlayerID; this.isLoading = true; fetch(`${config.SERVER_BASE_URL}/v1/player/${id}/ticket-scanner-events${queryParams}`, { method: 'GET', headers: { 'Authorization': `Bearer ${localStorage.getItem...
[ "async userTickets({ response, params }) {\n try {\n StatsD.increment('api.user.ticket.get.all.success')\n const user = await User.query()\n .where('external_id', params.user_id)\n .first()\n\n return response.json(await user.tickets().fetch())\n } catch (e) {\n logger.error(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a skill object, characteristic object, difficulty number and ActorSheetFFG.getData() object and creates the appropriate roll dialog.
static async rollSkillDirect(skill, characteristic, difficulty, sheet, flavorText, sound) { const dicePool = new DicePoolFFG({ ability: Math.max(characteristic.value, skill.rank), boost: skill.boost, setback: skill.setback, force: skill.force, difficulty: difficulty, advantage: s...
[ "rollToolCheck(event) {\n if ( this.type !== \"tool\" ) throw \"Wrong item type!\";\n\n // Prepare roll data\n let rollData = duplicate(this.actor.data.data),\n abl = this.data.data.ability.value || \"int\",\n parts = [`@abilities.${abl}.mod`, \"@proficiency\"],\n title = `${this.name} - Too...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the job uuid from the json report.
function getJobUUID() { const fileName = node_modules_shelljs_shell.exec(`ls ${getWorkspaceDir()} | grep sechub_report`).trim(); lib_core.debug('File name: ' + fileName); const filePath = `${getWorkspaceDir()}/${fileName}`; const json = JSON.parse(external_fs_.readFileSync(filePath, 'utf8')); const ...
[ "_getJobId (job) {\n return this._trialsIds[this._getJobHash(job)];\n }", "static getIdFromJobId(jobId) {\n return \"j\" + jobId;\n }", "static async getJobById(job_id) {\n try {\n const response = await db.one(`select * from dailyjobboard where id = ${job_id}`);\n return re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
write a recursive function called capitalizeWords. Given an array of words, return a new array containing each word capitalized. let words = ['i', 'am', 'learning', 'recursion']; capitalizedWords(words); // ['I', 'AM', 'LEARNING', 'RECURSION']
function capitalizeWords (words) { let newWords = []; //base condition if (words.length === 0) return []; //cap and push to newWords (inital) newWords.push(words[0].toUpperCase()); newWords.push(...capitalizeWords(words.slice(1))); return newWords; }
[ "function capitalizedWords(arr) {\n let solution = [];\n\n if (arr.length === 0) return solution;\n\n solution.push(arr[0].toUpperCase());\n\n solution = solution.concat(capitalizedWords(arr.slice(1)));\n\n return solution;\n}", "function capitalizedWords(arr) {\n let newArr = [];\n\n if (arr.len...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns path without file extension
function pathWithoutExtension( path ) { return path.replace( /\.\w+$/, '' ); }
[ "function getPathWithoutFileName(path) {\n var slash = recognizeSlash(path),\n parts = path.split(slash);\n parts.pop();\n return parts.join(slash);\n}", "function getFilenameWithoutExtension(path) {\n if (!path) {\n return '';\n }\n var filename = path.substring(path.lastIndexOf('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
================= CC Environment ===========
function CCEnvironment() { this.receiver = new cast.receiver.Receiver('$RECEIVER$NAME$', [cast.receiver.RemoteMedia.NAMESPACE], "", 5); this.remoteMedia = new cast.receiver.RemoteMedia(); this.remoteMedia.addChannelFactory(this.receiver.createChannelFactory(cast.receiver.RemoteMedia.NAMESPACE)); t...
[ "function Compilers() {\n\tvar kColiruBaseCommand = \"-std=c++1z -pthread -lboost_context -Wall main.cpp && ./a.out\";\n\tvar kColiruUrl = \"http://coliru.stacked-crooked.com/compile\";\n\t\n\tvar compilerParameters = {}\n\tcompilerParameters[\"clang\"] = {\"compilationCommand\" : \"clang++ \" + kColiruBaseCommand,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the store URL
getURL() { return Meteor.absoluteUrl(`${ UploadFS.config.storesPath }/${ this.name }`, { secure: UploadFS.config.https }); }
[ "getURL() {\n return Meteor.absoluteUrl(UploadFS.config.storesPath + '/' + this.name, {\n secure: UploadFS.config.https\n });\n }", "getStoreLink() {\n const name = this.state.user.store.displayName.split(\" \");\n let n = '';\n for (let i = 0; i < name.length; i++...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Buffer len to serialize this class.
serializeLen() { precondition.ensureNotNull('this.ctxPtr', this.ctxPtr); let proxyResult; proxyResult = Module._vscr_ratchet_message_serialize_len(this.ctxPtr); return proxyResult; }
[ "get length() {\n if (this._buffer) {\n return this._buffer.length;\n } else {\n return 0;\n }\n }", "length() {\n return this._buffer.length;\n }", "size() {\n return this.buf.byteLength;\n }", "size() {\n return this.buf.byteLength;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funcCall: id "(" assign? ("," assign ")") ")"
function ruleFuncCall() { var node = null; var tmp; if (accept("LX_ID") && _lex[0].name == "LX_LPAREN") { node = {name:"LX_FUNCALL", children:[{name:_curr.name, val:_curr.val}]}; shift(); shift(); if ((tmp = ruleAssign())) { node.children.push(tmp); while (accept("LX_COMMA") && shift()) { ...
[ "function AssignmentExpression() {\n}", "function CallExpression() {\n}", "function Assign_Free_Literal() {\r\n}", "function AssignmentOperator(){\nequalAssOP();\naddAssigOp();\nsubAssigOp();\n}", "parseCall(func) {\n const expr = new Token(func, this.parseExpression.bind(this));\n }", "AssignmentOper...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find sass importer recursively until reach top scss directory
function findSassImporter(sass_name, search_dir, files) { if (typeof files == 'undefined') files = []; return fspro.readDir(search_dir).then((contents) => { let relevant_files = contents.filter(file => file.match(/.*\.scss$|.*\.sass/) && file != sass_name); // check files for import let check_promises = ...
[ "function collectSassDeps(file, enc, next) {\n\t\tif (file.isNull()) return next(null, file);\n\t\tvar extname = path.extname(file.path);\n\t\tvar basename = path.basename(file.path, extname);\n\t\tvar dirname = path.dirname(file.path);\n\t\tif (basename[0] === '_') {\n\t\t\tbasename = basename.slice(1);\n\t\t\timp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a revision to the fake data generator that does a random walk.
function generateFakeData(step) { if (isPaused && !step) return; for (var m=0; m < tracks.length; m++) { // Calc the random steps in each direction tracks[m][1] += (Math.round(Math.random()*2)-1) * Math.floor(Math.random()*MAX_STEPSIZE); tracks[m][2] += (Math.round(Math.random()*2)-1) ...
[ "function randomWalk(values) {\n var index;\n return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function randomWalk$(_context9) {\n while (1) {\n switch (_context9.prev = _context9.next) {\n case 0:\n // randomly choose a starting index in the values array\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Geting all possible win positions
function allPossibleWinPositions(size) { let wins = [] let onewin = [] let coords = [] for (let y = 1; y <= size; y++) { for (let x = 1; x <= size; x++) { coords.push(x) coords.push(y) onewin.push(coords) coords = [] } wins.push(one...
[ "function winningPositions(board)\n\t{\n\t\twinPositions = []; //holds positions of the slots forming the winning chain(s)\n\n\t\tfor(var i=0; i < board.length; i++) //check rows\n\t\t{\n\t\t\tif(board[i][0] !== \"E\" && board[i][0] === board[i][1] && board[i][1] === board[i][2])\n\t\t\t\twinPositions.push([[i,0], ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A cell's type determines which adjacent cells need to be tested during each frame of the simulation. This method tests the cell at (row, col), and returns the constant representing which of the 9 different types of cells it is.
function determineCellTypeDev(row, col) { if ((row === 0) && (col === 0)) return TOP_LEFT_DEV; else if ((row === 0) && (col === (gridWidthDev-1))) return TOP_RIGHT_DEV; else if ((row === (gridHeightDev-1)) && (col === 0)) return BOTTOM_LEFT_DEV; ...
[ "function determineCellType(row, col)\n{\n if ((row === 0) && (col === 0)) return TOP_LEFT;\n else if ((row === 0) && (col === (gridWidthDev-1))) return TOP_RIGHT;\n else if ((row === (gridHeightDev-1)) && (col === 0)) return BOTTOM_LEFT;\n el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set graph type methods Set the tickboxes and names for the legend, given the channel names
_setLegend(){ $('#legend-form').empty(); // drop old controllers // Add checkbox for each channel let ticksID = {}; this.channels.forEach((channel, index) => { ticksID[channel.name] = 'ch'.concat(index).concat('-tick'); const inputTag = "<input id='".concat(ticksID[channel.name]).concat("' ...
[ "function configGraphType() {\n\n graph.scaleX.set(35, 2, '');\n switch(controls.graph_type.value) {\n case 'pos':\n box.title = \"Posición vs. Tiempo\";\n graph.scaleY.set(35, -20, '');\n graph.setLabels(\"\", \"Tiempo [s]\", \"Posición [cm]\");\n break;\n case 'vel':\n box.title =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch user resorts data
function displayUserResorts() { fetch("/api/v1/users/userResorts", { method: "GET", headers: { credentials: "include" } }) .then(dataStream => dataStream.json()) .then(dataObj => { render(dataObj.data); }) .catch(err => console.log(err)); }
[ "async getResortsByLiftPass({request}) {\n\n const requestData = request.all();\n const liftPass = requestData.liftPass;\n\n const liftPassID = await Database.table('liftpasses').where(\"Name\", liftPass).select('WixID');\n //console.log(liftPassID);\n const resortIDList = await Database.table('resor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get max_game counts by conf
function get_max_games(conf,double) { var max_games = 0; if (global.has_rule(conf.rule_index, global.MASK_PC10)) { max_games = 10; } if (global.has_rule(conf.rule_index, global.MASK_PC20)) { max_games = 20; } if(double){ max_games *=2; } return max_games; }
[ "getMaximumHouseCountForPlayer(player) {\n if (player.isManagement())\n return 100;\n\n if (player.isVip())\n return 3;\n\n return 1;\n }", "function nonDivisionalMaxCount(team, potentialOpponent){\n let count = 0;\n sameDivisionCheck(team, potentialOpponent, le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
roundComplete() function Here we will have all of the code that needs to be run after each guess is made.
function roundComplete() { // First, log an initial status update in the console // telling us how many wins, losses, and guesses are left. console.log("WinCount: " + winCounter + " | LossCount: " + lossCounter + " | NumGuesses: " + numGuesses); // HTML UPDATES // ============ // Update the HTML to refle...
[ "function roundComplete() {\n // First, log an initial status update in the console\n // telling us how many wins, losses, and guesses are left.\n // HTML UPDATES\n // ============\n // Update the HTML to reflect the new number of guesses.\n document...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function to swap a number in place (that is, without temporary variables).
function numberSwap(a, b) {}
[ "function swapNumber(a, b) {\n\tb = b - a;\n\ta = a + b;\n\tb = a - b;\n}", "function swapTwoNums(a, b){\n a = a+b;\n b= a-b;\n a = a-b;\n console.log(a,b);\n}", "function swapNumb(a, b){\n console.log('before swap: ','a: ', a, 'b: ', b);\n a=b-a;\n b=b-a;\n a=b+a;\n console.log('afte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch restaurants by a cuisine type with proper error handling.
fetchRestaurantByCuisine(cuisine) { // Fetch all restaurants with proper error handling return this.fetchRestaurants().then(restaurants => restaurants.filter(restaurant => restaurant.cuisine_type === cuisine)); }
[ "static fetchRestaurantByCuisine(cuisine) {\n // Fetch all restaurants with proper error handling\n return DBHelper.fetchRestaurants().then(restaurants => {\n if (!restaurants) {\n throw new Error('No Restaurants Found');\n } else {\n // Filter restaurants to have only given cuisine t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle the onClick event on Apply button. When user clicks on Apply, two requests are being triggered: one to fetch column format for table (features) one to fetch the results to populate the table. If URL doesn't contain the "pipeline" param, we will fetch the features for the default pipeline.
handleApplyClick() { // Set loaded true on initial loading const { loaded, searchValue } = this.state; if (!loaded) { this.setState({ 'loaded': true, }); } // To clear search box on click of apply if (searchValue !== '') { this.setState({ 'searchValue': '', ...
[ "function applyClickHandler() {\r\n // construct object for filters\r\n let filters = {};\r\n\r\n // get values for each attribute\r\n for (let attribute of Object.keys(self.attributeSelectDropdowns)) {\r\n let dropdownValue = self.attributeSelectDropdowns[attribute].node().value;\r\n\r\n // a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load_student_list.php returns html option tags containing the students in the session. The form's select element is then refreshed.
function reloadDropdowns() { var ajaxurl = './actions/load_student_list.php', data = "&ajax=" + true; $.post(ajaxurl, data, function (response) { if(response.indexOf("option")>=0){ $('#student_dropdown').append(response); //$('select').formSelect(); //$('#test option').filter(function () { return $(this)....
[ "function loadStudentToOptions() {\r\n var list = $(\"#adminNames\");\r\n list.append(createOptionsString(ADMIN_NAMES));\r\n}", "function loadSelectableInstructors ( )\n\t{\n\t\t$.ajax(\n\t\t{\n\n\t\t\ttype: 'GET',\n\n\t\t\turl: 'data/phps/_php.selectable.instructors.display.php', \n\n\t\t\tdataType: 'json'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert results of statistical test to HTML.
statisticsToHTML (results, legend) { yem.util.check((results !== null) && (legend !== null), `Must have result and legend`) const title = legend._title const header = '<tr><th>Result</th><th>Value</th><th>Explanation</th></tr>' const body = Object.keys(legend).map(key => { if (k...
[ "function generateResultHtml(result)\n\t{\n\n\t\tlet Html = \"\"\n\t\tresult.forEach(function(element) {\n\t\t\tlet difficulty = ''\n\t\t\tswitch(element.LevelOfDifficulty){\n\t\t\t\tcase 1:\n\t\t\t\t\tdifficulty = 'Green'\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tdifficulty = 'Red'\n\t\t\t\t\tbreak;\n\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a message to a webworker
function send(wid, message) { if(wid === 0) { setTimeout(() => { handler(message, wid) }, 0); return; } const worker = workers[wid]; if(worker) { worker.postMessage(message); } }
[ "message(message){\n this.worker.postMessage(message);\n }", "function sendMessageToWorker(e) {\n\tvar data = document.getElementById(\"msg\").value;\n if (myWorker != null) {\n myWorker.postMessage(data);\n } \n }", "send(msg) {\n this.worker.send(msg)\n }", "function sendMessag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert daa into course update modal
function InsertDataIntoCourseUpdateModal(id){ $.ajax({ type: 'GET', contentType: 'application/json; charset=utf-8', url: 'http://localhost:8000/Course/'+id+'/', dataType: 'json', }).then(function(data){ console.log(data); $('#uCourseId').val(data.id); $('#uCourseName').val(data.courseName); ...
[ "function InsertDataIntoCourseUpdateModal(id){\r\n\t$.ajax({\r\n\t\turl: \"http://localhost:8000/Course/\"+id+\"/\"\r\n\t}).then(function(data){\r\n\t\t$('#u_course_id').val(data.id);\r\n\t\t$('#u_course_name').val(data.course_name);\r\n\t\t$('#u_major').val(data.major);\r\n\t});\r\n}", "function onModifyCourse()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts string from either base10, binary, hex, roman and returns the number in base10 or NaN
function convertToBase10(string) { if (parseInt(string, 10)) { return parseInt(string, 10); } else if (string === '0' || string === '1') { return NaN; } else if (string.startsWith('0b') && parseInt(string.substr(2), 2)) { return parseInt(string.substr(2), 2); } else if (roman.par...
[ "function toBase10(number) {\n\n var x = number.toLowerCase();\n Logger.debug(\"x = \" + x)\n\n if (!x.startsWith('0b') && !x.startsWith('0x') && parseInt(x, 10).toString(10) == x.replace(/^0+/, '')) {\n Logger.debug('>>> Base 10: ' + parseInt(x, 10).toString(10) + ' = ' + x);\n return parseInt(x, 10);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Variable hoisting: start easy: Why can't we get the console to log any of the a's?
function foo() { var a = 7; function bar() { // var a is hoisted here (don't write this until after) console.log(a) var a = 3 } bar(); }
[ "function teste() {\n console.log('a =', a)\n var a = 2\n console.log('a =', a)\n}", "function foo() {\n a = 3;\n console.log(a); // 3\n var a; // declaration is \"hoisted\"\n // to the top of `foo()`\n }", "function test() {\n var a;\n function foo() {\n return 2;\n }\n\n console...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable building of pose list with drag & drop, removal of poses.
function initDragDrop() { // pose archive draggable, drop to poselist $('.pose-picker-archive li').draggable({ connectToSortable: '.pose-list', helper: 'clone', revert: 'invalid' }).disableSelection(); // poselist sortable var $poseLlist = $('...
[ "function enablePointSelection(){\r\n\taddPointMode = true;\r\n}", "resetDraggables() {\n const draggables = this.getDraggables();\n\n draggables.forEach((draggable, index) => {\n const paragraph = this.getParagraph(draggable);\n\n paragraph.toggleEffect('over', false);\n paragraph.toggleEffe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
color button if this is already a favorite
function colorButton(recipe){ var favorites = JSON.parse(localStorage.getItem("favorites") || '[]'); var index = favorites.indexOf(recipe) //if it isn't in list, use empty star if(index == -1){ $("img.favorites-button").attr("src", "/images/star-empty.png") } else { $("img.favorites-button").attr("src", "/ima...
[ "static isRestaurantFavorite(btn , restaurant) {\n if (restaurant.is_favorite == 'true') {\n btn.style.color = 'lightgreen';\n btn.setAttribute('aria-label', 'favorite checked')\n } else {\n btn.style.color = 'lightgrey';\n btn.setAttribute('aria-label', 'favorite unchecked')\n }\n }",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes a referer/referrer string and parses it to determine if it contains any search terms. If it does, the search terms are passed to the highlightSearchTerms function so they can be highlighted on the current page.
function highlightGoogleSearchTerms(referrer) { // This function has only been very lightly tested against // typical Google search URLs. If you wanted the Google search // terms to be automatically highlighted on a page, you could // call the function in the onload event of your <body> tag, // like th...
[ "function highlightGoogleSearchTerms(referrer)\n{\n // This function has only been very lightly tested against\n // typical Google search URLs. If you wanted the Google search\n // terms to be automatically highlighted on a page, you could\n // call the function in the onload event of your <body> tag,\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A functional component representing a TextBox
function TextBox(props) { const textInput = useRef(0); const [textInp, setText] = useState(0); /** * handleChange. * Changes our variables information on the box to the user text * @param props = the inputted props from the parent * @param event = the text of the user */ functi...
[ "function MASH_Textbox(tmpID, tmpLeft, tmpTop, tmpWidth, tmpHeight, tmpZIndex, tmpStyle,\n tmpName, tmpValue\n ) {\n \n this.base = MASH_Input;\n this.base(tmpID, tmpLeft, tmpTop, tmpWidth, tmpHeight, tmpZIndex, tmpStyle,\n MASH_Input.TY...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
issuekeys: MSG_ILLEGAL_USE_OF_MODIFIER, MSG_ILLEGAL_USE_OF_MODIFIER, MSG_ILLEGAL_USE_OF_MODIFIER
protected internal function m252() {}
[ "function checkKeyForProblem(newKey)\r{\r var retVal = \"\";\r var problemId = dw.isAProblematicShortcut(newKey);\r var key = newKey.substring(newKey.lastIndexOf(\"+\")+1);\r \r if (problemId)\r {\r if (problemId == 1)\r retVal = createWarningMsg(MSG_DeadKeyInShortcut, key);\r else if (problemId ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Grants s3:PutObject and s3:Abort permissions for this bucket to an IAM principal. If encryption is used, permission to use the key to encrypt the contents of written files will also be granted to the same principal.
grantPut(identity, objectsKeyPattern = '*') { return this.grant(identity, perms.BUCKET_PUT_ACTIONS, perms.KEY_WRITE_ACTIONS, this.arnForObjects(objectsKeyPattern)); }
[ "grantRead(grantee) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_iam_IGrantable(grantee);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.grantRead);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all ip or onion address that can be used to connect to this Casa node.
async function getAddresses() { // Get ip address. const addresses = [ipAddressUtil.getLanIPAddress()]; const currentConfig = await diskLogic.readSettingsFile(); // Check to see if tor is turned on and add onion address if Tor has created a new hidden service. if (process.env.CASA_NODE_HIDDEN_SERVICE &...
[ "function getIPAddresses() \n{\n var ipAddresses = [];\n\n var interfaces = require('os').networkInterfaces();\n for (var devName in interfaces) {\n var iface = interfaces[devName];\n for (var i = 0; i < iface.length; i++) {\n var alias = iface[i];\n if (alias.family === 'IPv4' && alias.address !...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select all rows in the grid
selectAll () { this.$refs.grid.gridOptions.api.selectAllFiltered(); this.grid.hasSelectedRows = true; }
[ "function selectAll() {\n loadedAgGrid.gridOptions.api.forEachNode(function (rowNode, index) {\n rowNode.setSelected(true);\n });\n}", "selectAllRows() {\n const rows = [];\n const dataset = this.getActiveDataset();\n\n for (let i = 0, l = dataset.length; i < l; i++) {\n const idx = thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to make friends. This is a helper function for simplicity in this case. In your project system, you may have a function for proposing friendships, checking friend requests, and accepting. You would also want a requestingUser input parameter (a user should only be able to update their own friend data) The funct...
function makeFriends(userA, userB){ //If one of the user IDs doesn't exist, stop let user, user2; users.forEach(value => { if(value.username == userA) { user = value; } if(value.username == userB) { user2 = value; } }); if(!user || !user2) { return; } let i...
[ "function makeFriendRequest(requester, friend){\n if(!existsUser(requester))\n throw new Meteor.Error(ErrorCode.INTERNAL_ERROR, \"No user exists with _id: \" + requester);\n\n if(!existsUser(friend))\n throw new Meteor.Error(ErrorCode.INTERNAL_ERROR, \"No user exists with _id: \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }