query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Routes a pathname to its corresponding handler, or attempts to render it as a resource.
function route(handle, pathname, response, request) { if (typeof handle[pathname] === 'function') { handle[pathname](response, request); } else { var resource = pathname.substring(1, pathname.length); fs.exists(resource, function(exists) { if (exists) { handlers.render(resource, response);...
[ "function fileRouter(parsedUrl, res) {\n\tvar code;\n\tvar page;\n\tvar filePath = './' + parsedUrl.pathname;\n\tif (fs.existsSync(filePath)) {\n\t\t// We found the page, read it and set the code\n\t\tcode = 200;\n\t\tpage = fs.readFileSync(filePath);\n\t}\n\telse {\n\t\t// We didn't find the requested page, so rea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets API based on search term. If search isn't given, then it will return full list returns an array of companies
function getAllCompaniesFromAPI(search) { return async function (dispatch) { const res = await JoblyApi.request('companies', { search }, 'get'); let companies = res.companies; dispatch(gotAllCompanies(companies)); }; }
[ "function getIndustries() {\n\t var MIN_CHARS = 3;\n\t var searchTerm = self.industry;\n\t \n\t if (searchTerm && searchTerm.length >= MIN_CHARS) {\n\t blueEconomics.search(searchTerm || '')\n\t .then(function(data) {\n\t self.searchResults = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Express middleware has no access to the req.params, but sometimes we still need the orgId in the middleware. Pass in req.originalUrl, and we will try to get the OrgId
function unsafelyGetOrgId(originalUrl) { const params = originalUrl.split('/'); if (params.length === 0) { return null; } return params[1]; }
[ "static getRequestorOrg(ctx) {\n\t\t//Return requestor MSP value\n\t\treturn ctx.clientIdentity.getMSPID();\n\t}", "function getNetid(req) {\n if (req.session.netid) {\n return req.session.netid;\n }\n else {\n return null\n }\n}", "function isRouteOwner(req, res, next) {\n if (!req.p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Similar to Object.entries but without using polyfill
function getEntries (obj) { return Object.keys(obj).map(function (key) { return [key, obj[key]]; }); }
[ "parseEntries() {}", "function objectKeys(object) { Object.keys(object) }", "objectValues(obj) {\n if (obj instanceof Object) {\n return (function*() {\n for (let key in obj) {\n yield obj[key];\n }\n })();\n } else {\n return [];\n }\n }", "objectKeys(obj) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a create contact request for the email & auth_token provided. The contact is described in xml.
function add_google_contact_create_contact(email_address, auth_token, xml) { url = 'http://www.google.com/m8/feeds/contacts/' + escape(email_address) + "/base"; return add_google_contact_send_request("POST", url, xml, auth_token, "application/atom+xml"); }
[ "function createContact() {\n var contacts = new Appworks.AWContacts();\n\n // Gather properties from your form\n var name = document.getElementById(\"contact-name\").value;\n var number = document.getElementById(\"contact-number\").value;\n\n // Create a new contacts object\n var contact = new Contact();\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers a callback called whenever the user makes a change to the editor content. The change is represented by a delta object.
onDelta(callback) { this._onDelta = callback; }
[ "add_change(func) {\n this.add_event(\"change\", func);\n }", "emitter(editor, data, value) {\n // Emit code change to socket\n socket.emit('code change', value); \n }", "function onDidCreateEditor(listener) {\n return standaloneServices_js_1.StaticServices.codeEditorService.get().onCod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates progress bar, level, and percent correct called when answer submitted or the operator changes
function updateProgress(showOverlay) { // update progress bar var correctThisLevel = state.numCorrect % correctPerLevel; $progressBarFill.width(correctThisLevel * progressBarWidthPerCorrect); // update percent correct var percent = state.numCorrect / (state.numCorrect + state.numWrong) * 100; pe...
[ "function handleGameProgress(correct) {\n //If answer is correct\n if(correct) {\n //Increse score by 10\n score += 10;\n //Increse item correct by one\n itemCorrect += 1;\n //If the max items for level is reached\n if(itemCorrect == fetchMaxItems()){\n //If level is equal to nuber of level...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluates whether this point is a counter
static evalIsCounter(dict) { return dict.IsCounter === 'X'; }
[ "static validateIsCounter(binding) {\n if (binding.hasOwnProperty('IsCounter')) {\n return binding.IsCounter === 'X';\n } else {\n return binding.MeasuringPoint.IsCounter === 'X';\n }\n }", "static evalIsCounterOverflow(dict) {\n return dict.IsCounterOverflow =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serializes the specified object with the specified DataView, or a new DataView if unspecified
static serialize(obj, view, offset = 0, countBytes = false) { if (arguments.length < 1) { throw 'missing arguments'; } if (typeof obj === 'undefined') { if (!countBytes) view.setUint8(offset, Cobton.UndefinedValue); offset++; ...
[ "function BufferView(buffer, offset, length, byteorder) {\n if (arguments.length < 2 || arguments.length > 4) \n fail(\"Wrong number of argments\");\n if (arguments.length === 2) {\n byteorder = offset;\n offset = 0;\n length = buffer.byteLength;\n }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: findPreferedType DESCRIPTION: Search the global variable MM.rsTypes for a rs type that has as prefered type the SBRecordset.name ARGUMENTS: SBRecordset the SBRecordset object RETURNS: the position count of the rs element, 1 otherwise
function recordsetDialog_findPreferedType(SBRecordset) { for (ii = 0; ii < MM.rsTypes.length;ii++) { if (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[ii].serverModel) { if ((SBRecordset.name) && (MM.rsTypes[ii].preferedName == SBRecordset.name.replace(/safe/i, ''))) { return ii; } ...
[ "function recordsetDialog_searchByType(stype) {\r\n\tfor (ii = 0; ii < MM.rsTypes.length;ii++) {\r\n\t\tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[ii].serverModel) {\r\n\t\t\tif (MM.rsTypes[ii].type == stype) {\r\n\t\t\t\treturn ii;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}", "functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SoftwareButtonManager manages a home button for devides without physical home buttons. The software home button will display at the bottom of the screen and is meant to function in the same way as a hardware home button.
function SoftwareButtonManager() { this.isMobile = ScreenLayout.getCurrentLayout('tiny'); this.isOnRealDevice = ScreenLayout.isOnRealDevice(); this.hasHardwareHomeButton = ScreenLayout.getCurrentLayout('hardwareHomeButton'); // enabled is true on mobile that has no hardware home button this.en...
[ "static set toolbarButton(value) {}", "function setupBottomNav() {\n\t$(\"#about-button\").empty();\n\t$(\"#media-button\").empty();\n\tfillBottomButton(\"about-button\", \"About\");\n\taddAboutEvent();\n\tfillBottomButton(\"media-button\", \"Media\");\n\taddMediaEvent();\n}", "function enableMainPageButtons() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This imports the stored SQL file, then seeds it with required data
function seed() { process.env.ENVIRONMENT = 'test'; const test = require('./config/db'); const db = require('./db'); return shared.importDB(test, sql_file).then(() => { // various deleting commands const seed = require('./seed') || []; // various seeding commands return Promise.all(seed.map((cm...
[ "function runImportSQLDatabase(){\n g.mockDataSource = 'sqlMockData';\n //Just recreate the worksheet using the SQL database source\n createSampleTable(g.mockDataSource); \n}", "async import(data) {\n const { database: { name, version }, remove = {}, insert = {} } = data\n\n if (name !== this.dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the minimum balance for the account to be rent exempt
static async getMinBalanceRentForExemptAccount( connection: Connection, ): Promise<number> { return await connection.getMinimumBalanceForRentExemption( AccountLayout.span, ); }
[ "static async getMinBalanceRentForExemptMint(\n connection: Connection,\n ): Promise<number> {\n return await connection.getMinimumBalanceForRentExemption(MintLayout.span);\n }", "function lowest_balance() {\n var smallest_balance = accounts[0].amount;\n for (var i in accounts) {\n if (accounts[i].am...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calling add new item to list on enter
function addToListOnEnter(e) { if (inputLength() > 0 && e.keyCode === 13) { add_to_list({ id: items.length, name: input.value.trim(), bought: false }); } }
[ "addNewItem() {\n // we remove whitespace from both sides of the string saved in newItem\n this.newItem = this.newItem.trim();\n if (this.isInputValid(this.newItem)) {\n // if the user input is valid, we add the user input to the todo-list\n this.todos....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a filtered list of all the people who are old enough to see The Matrix (younger than 18)
function ofAge(arr){ return arr.filter(num => num.age >= 18) }
[ "function filterByNoOfAwardsxTeamxAge(awardwontimes, teamname, ageofplayer) {\n let list = [];\n players.filter(details => {\n if (details.team === teamname && details.age < ageofplayer && details.awards.length >= awardwontimes) {\n list.push(details);\n }\n });\n return list;\n}", "function getHir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hide the WYSIWYG buttons
function hide_wysiwyg_button(cell) { cell.element.find(".wysiwyg-toggle").hide(); cell.element.find(".wysiwyg-done").hide(); }
[ "ensureButtonsHidden() {\n // TODO(fanlan1210)\n }", "function show_wysiwyg_button(cell) {\n cell.element.find(\".wysiwyg-toggle\").show();\n cell.element.find(\".wysiwyg-done\").show();\n }", "function hideStopEditingBtn() {\n $('#stopEditBtn')[0].className += ' hidden';\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update our location based on landmarkObjects
update() { let landmark = landmarks[party.landmarkIndex]; if (landmarks[++party.landmarkIndex]) { party.milesToNextMark = landmarks[party.landmarkIndex].distance; this.nextLandMark = landmarks[party.landmarkIndex].name; this.initialDistance = landmarks[party.landmarkIndex].distance; } if (landmark.gene...
[ "function updatePlacesLocationInformation() {\n\tupdatePlacesLocationInformationFromCategory(\"\", \"All Categories\");\n}", "function updatePlaceResultObject(tobeupdated,update){\n\ttobeupdated.geometry= update.geometry;\n\ttobeupdated.icon=update.icon;\n\ttobeupdated.name=update.name;\n\ttobeupdated.vicinity=up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a default project name only if user has not entered any data
generateProjectName(firstInit) { // name has not been modified by the user if (firstInit || (this.projectInformationForm['deskname'].$pristine && this.projectInformationForm.name.$pristine)) { // generate a name // starts with project var name = 'project'; // type selected if (t...
[ "function createProject() {\n const projectName = helpers.toTitleCase(app.getArgument('projectName'));\n app.ask(`Creating Project - ${projectName} now, please confirm`);\n }", "function generateProject() {\n const user = faker.random.arrayElement(user_data);\n const project = {\n pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Small restaurant image URL.
static smallImageUrlForRestaurant(restaurant) { return (`/img/small/${restaurant.photograph}.jpg`); }
[ "static imageSrcUrlForRestaurant(restaurant) {\r\n return (`/img2/${restaurant.id}` + `-300_small.webp`);\r\n }", "static imageSrcSetUrlForRestaurant(restaurant) {\r\n return (`/img2/${restaurant.id}` + `-300_small.webp 300w, ` + `/img/${restaurant.id}` + `.webp 600w`);\r\n }", "function mapUrlLink(ph...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return HTML of an event with the info.
function renderSingleEvent(info) { return ('<div class="event_block animate-fadein">' + '<div class="event_start_info">' + '<div class="event_start_dt">starts at</div>' + '<div class="event_start_time">' + '<div class="time_h">' + info.acf.hour + '</div>' + '<div class="time_min_hold">' + '<div class="t...
[ "function renderEventBody(eventData) {\n let htmlResult= `<ul class=\"event-details-list\">\n <li>Crowd Count: ${eventData.crowdCount}</li>\n </ul>`;\n $('div.eventBody').html(htmlResult);\n}", "function createEvent(event){\n\n\t// Event Object: Type, Subtype, Description, StartTimeDate, Fresh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the function myPow that gets 2 params: base, exp and returns the power
function myPow(base, exp) { var num = 1; for (var i = 0; i < exp; i++) { num *= base; } return num; }
[ "function pow(i, exp) /* (i : int, exp : int) -> int */ {\n return _int_pow(i,exp);\n}", "function pow (baseNum, power){\n var answer = 1;\n\n for(var i = 0; i < (power) ; i++){\n answer *= multiply(baseNum, 1);\n console.log(answer);\n }\n console.log(answer);\n return answer;\n\n}", "function fin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds `.min` the to filename
function addMin(path) { path.basename += '.min' }
[ "function min_and_rename() {\n return src(\"./css/final.css\")\n .pipe(pleeease())\n .pipe(\n rename({\n suffix: \".min\",\n extname: \".css\"\n })\n )\n .pipe(dest(\"./css/\"));\n}", "function updateFileExtenstion (fileName) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get unspect transfer of a wallet
getUnspectTransfer(address) { return new Promise(async (resolve, reject) => { try { const res = await fetch(this.explorerUrl + "/api/addr/" + address + "/utxo"); const data = await res.json(); resolve(data); }catch(err) { ...
[ "static async getEthTransactions() {\n const walletAddress = await this.getWallet().then(wallet =>\n wallet.getAddressString(),\n );\n\n return fetch(\n `https://api.ethplorer.io/getAddressTransactions/${walletAddress}?apiKey=freekey`,\n )\n .then(response => response.json())\n .then...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the XML file and customise the application with the new types
function loadXML(e) { var url = e.parameter.url; var xml = UrlFetchApp.fetch(url).getContentText(); var document = XmlService.parse(xml); var entries = document.getRootElement().getChildren(); var all_types = new Array(); for (var i = 0; i < entries.length; i++) { all_types[i] = new Object(); al...
[ "function ProcessableXML() {\n\n}", "function uploadXML(){\n\tvar fileInput = document.getElementById('fileInput');\n\tvar file = fileInput.files[0];\n\tvar textType = /xml.*/;\n\n\t//get extension of filename and store it in global variable\n\tvar fileTypeValue=$(\"#fileInput\").val();\n\tvar newfilename = fileT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When converted to a WWA priority, priorityOfWinjsJob should equal priorityOfPlatformJob.
function test(priorityOfWinjsJob, priorityOfPlatformJob) { var platformJobQueued = false; var signal = new WinJS._Signal(); return withMSAppHooks({ isTaskScheduledAtPriorityOrHigher: function (origFn, args, priority) { return platformJobQueued && ...
[ "function test(priorityOfWinjsJob, priorityOfPlatformJob) {\n var platformJobQueued = false;\n var signal = new WinJS._Signal();\n\n return withMSAppHooks({\n isTaskScheduledAtPriorityOrHigher: function (origFn, args, priority) {\n return platformJo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reload the parent page
function refresh_parent(url) { // disable all links $("a").attr('href',"javascript:").click(function(){}); if(url && typeof url == "string") { window.parent.location = site_url(url); } else { // forcibly reload the page window.parent.location.reload(true); } }
[ "function reLoadParent ()\n{\n self.opener.document.reLoad.submit();\n setTimeout(\"self.close()\", 500);\n}", "function updateWidget() {\n window.location.reload();\n}", "function refreshPage() {\r\n var url = location.href;\r\n // Strip of information after the \"?\"\r\n if (url.indexOf('?')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show a Task based on ID in a modal
function showTask(id) { return $modal.open({ templateUrl: apps_url + 'assets/sync_manager/templates/taskDetail.html', controller: 'taskDetailController', resolve: { id: function () { return id; } ...
[ "function showTaskStatus(status) {\n return $modal.open({\n templateUrl: apps_url + 'assets/sync_manager/templates/task_status.html',\n controller: 'taskStatusController',\n resolve: {\n status: function () {\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
just returns original location abbr if location is unknown
function parseLocationInfo(location) { for (const key in LOCATIONS) { const abbr = location.substring(0, key.length) if (key.toLowerCase() == abbr.toLowerCase()) { const room = location.substring(key.length).trim() const { name, num } = LOCATIONS[key] return `(${num}) ${location} - ${name}, ...
[ "function getLocationName() {}", "function getLocation(name){\n var location = _.detect(locations, function(location){\n return name.match(location.re);\n });\n return location ? location.address : '';\n }", "function zoneinfo(loc){\r\n switch (map[loc].environ){\r\n case 0:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function figures out which recipe we want to delete and then calls deleterecipe
function handleRecipeDelete() { var currentRow = $(this); var currentRecipe = currentRow.parent().data("recipe"); if (currentRecipe == undefined) { var currentRecipe = currentRow.parent().parent().data("recipe"); } deleteRecipe(currentRecipe,currentRow.parent().parent()); }
[ "deleteMultiple() {}", "function deleteResource(idx) {\n\t\t\tresources.splice(idx, 1);\n\t\t\treturn $q.when(resources);\n\t\t}", "function krnDiskDelete(fileName, callBack)\n{\n _KernelInterruptQueue.enqueue(new Interrupt(DISK_IRQ,\n [FS_OPS.DELETE, fileName, null, callBack ? callBack : krnPutAndDro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
copies all rdf extracted from the document to a temporary graph
async function setupTempGraphFromDoc(document) { const node = document.getTopDomNode(); const dom = document.getDom(); // Store session in temporary graph const sessionNode = findFirstNodeOfType( node, "http://data.vlaanderen.be/ns/besluit#Zitting" ); const tmpGraphName = `http://notule-importer.mu/${uuid()}...
[ "function generateNamedGraph(gconf) {\n\n var targetFileBaseName = targetDir + \"/\" + gconf.graph;\n\n var mdFilePath = targetFileBaseName + \"-meta.json\";\n\n var lastDumpMetadata;\n if (fs.exists(mdFilePath)) {\n lastDumpMetadata = JSON.parse(fs.read(mdFilePath));\n if (lastDumpMetadat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
openCheckout() Closes the Checkout component and opens a WebView with given cart
openCheckout() { // TODO: Remove the need for a parameter in this function this.props.handleCartClose(false) this.props.navigation.navigate('WebCheckoutScreen', { webUrl: this.props.checkout.webUrl, }); ('WebCheckoutScreen') }
[ "function gotToCheckout() {\n\tlocation.href = \"checkout.php\";\n}", "async navigateToCart() {\n const cartButtonLocator = await this.components.cartLink()\n await cartButtonLocator.click()\n }", "function goToCart() {\n // Get shopping cart\n messagejson = getCartList();\n if (messag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getValue: Returns: the selected value for a combo box
function getValue(comboid) { return $('#' + comboid + ' option:selected').val(); }
[ "get select_value() {\n return (this.select == undefined) ? this.select_config.default : this.select.selectedOption;\n }", "getValue() {\n const { form, path } = this.props\n if (form && path) return form.getValue(path)\n return this.props.value\n }", "getSelectedItem(key)\n {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
__________GET LIST OF STORAGE ACCOUNT KEYS IN SUBSTRIPTION_____________
function getStorageKeyList(){ storageClient.storageAccounts.listKeys(resourceGroupName, 'saketsa', function (err, result, request, response) { if (err) { console.error('\nERROR:' + err); } else{ // fs.writeFileSync('./result.json', util.inspect(result) , 'utf-8'); ...
[ "async function storageAccountListAccountSas() {\n const subscriptionId = process.env[\"STORAGE_SUBSCRIPTION_ID\"] || \"{subscription-id}\";\n const resourceGroupName = process.env[\"STORAGE_RESOURCE_GROUP\"] || \"res7985\";\n const accountName = \"sto8588\";\n const parameters = {\n keyToSign: \"key1\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by Java9ParserelementValuePair.
enterElementValuePair(ctx) { }
[ "enterElementValuePairList(ctx) {\n\t}", "enterElementValueList(ctx) {\n\t}", "fillElements() {\n this.replaceTokens(this.tags, CD.params());\n }", "function ExpressionParser() {\n \t\tthis.parse = function() {\n\t \t\treturn Statement(); \n\t \t}\n \t\t\n//\t\tStatement := Assignment | Expr\t\n\t\tthis.S...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler to navigate back to trips section
function handleBackToTrips() { $('main').on('click', '.back-button', function(event) { getTrips(); }) }
[ "function goBack() {\n if (pageStack.slice(-1)[0] === 'persons-list') {\n clearPersonList();\n }\n\n window.location.hash = pageStack.slice(-2)[0];\n pageStack = pageStack.slice(0, pageStack.length - 2);\n checkPageNav();\n}", "function goBack() {\n pop();\n\n if(typeof last() === 'undef...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invoke the handler and launch a completer.
invoke() { messaging_1.MessageLoop.sendMessage(this, CompletionHandler.Msg.InvokeRequest); }
[ "function runHandler(plugin, handler, cancel) {\n return function runHandlerDelegate(data) {\n if (!data) {\n return Promise.resolve();\n }\n\n return Promise\n .resolve(handler.handler(data, plugin, cancel))\n .then(function(result) {\n return data.configure(result);\n });\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
does what it says on the tin, checks url's. specifically pulls together a nice subreddit list.
function checkurl() { var sub = window.location.hash, //gets the hash varible we built up earlyer subreddits = sub.replace('#', ' ').trimLeft(),//removes the hash and trims it up url; console.log(subreddits);//logging dis bitch if (localStorage.getItem("includepics") === 'true') { if (window.location.hash) { ...
[ "function getSubreddits(callback) {\n // Load reddit.com/subreddits.json and call back with an array of subreddits\n}", "function redditSearch() {\n\t\tlet searchQuery = $('input[name=\"query\"]').val();\n\t\tlet URL = \"https://www.reddit.com/search.json?q=\" + searchQuery + \"&sort=relevance&t=all\";\n\t\t$.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new ComAdobeGraniteTranslationConnectorMsftCoreImplMicrosoftTranslationServiceFactoryImplProperties.
constructor() { ComAdobeGraniteTranslationConnectorMsftCoreImplMicrosoftTranslationServiceFactoryImplProperties.initialize(this); }
[ "constructor() { \n \n ComDayCqWcmCoreImplLanguageManagerImplProperties.initialize(this);\n }", "function FTLTranslator() {\r\n // FTL RegEx globals.\r\n this.trimPattern = /<#t>/g;\r\n this.titlePattern = /\\${TITLE_START}(.*?)\\${TITLE_END}/g;\r\n this.sectionPattern = /\\${SECTION_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Highlights the content of the given container. Returns true on success, false otherwise.
function highlightContent(containerId) { try { if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerId)); range.select().createTextRange(); return true; } else if (window.getSel...
[ "checkFeatureForHighlight(feature) {\n //Sanity check\n if ((this.highlightLocation == null) || (feature == null)) {\n return;\n }\n //Get geometry of feature\n let geometry = feature.getGeometry();\n //Chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given the long id of a role (such as internal/role/governanceadministrator), return the user ids of the auth members of that role
function getUserIdsFromRoleId(role_id) { var membershipProperties = openidm.read('config/commons').membershipProperties; if (!membershipProperties) { __.requestError('commons.json configuration for membershipProperties cannot be read.', 400) } var userIds = []; // Determine reverseProps based on common...
[ "function getUserIdsFromCertifierIds(certifier_ids) {\n var user_ids = [];\n certifier_ids.forEach(function(certifier_id) {\n if (isLongUserId(certifier_id)) {\n user_ids.push(certifier_id);\n }\n else if (isLongRoleId(certifier_id)) {\n var auth_member_ids = getUserIdsFromRoleId(certifier_id);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rebuild the DOM List of items
updateList(){ //create an empty div to add the items to var listItemsDOM = $('<div class="listItems"></div>'); var top = this.listDOM.scrollTop(); //loop over our styles and update the dom list for(var i=0; i<this.styles.length; i++){ //loop over all our items var item = this.styles[i]; //add a ...
[ "function redrawList() {\r\n console.log('Redrawing the list');\r\n let todoUL = document.getElementById('todoUL');\r\n todoUL.innerHTML = '';\r\n todoList.forEach(entry => appendULItem(entry));\r\n}", "updateDistractionList() {\n const content = document.getElementsByClassName('distItem');\n le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare two posits for sorting by the `value` field. Unsure why `positCompare` is written the way it is.
function positCompareByValue(posit1, posit2) { return posit1.value-posit2.value; }
[ "function compareValues(val1, val2){\r\n\tif (val1 > val2) {\r\n\t\treturn -1;\r\n\t} else if(val2 > val1) {\r\n\t\treturn 1;\r\n\t} else {\r\n\t\treturn 0;\r\n\t}\r\n}", "function _ascendingCompare(first, second) {\n return first.position - second.position;\n }", "static pseudo_cmp(a, b) {\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a BreakPoint, given a name and a media query.
function BreakPoint(name, media) { this.name = name this.media = media this.matches = null }
[ "function createMediaQueries(breakpoints) {\n /**\n * Get the non-number breakpoint keys from the provided breakpoints\n */\n var keys = Object.keys(breakpoints);\n /**\n * Use only the keys matching the official breakpoints names, and sort them in\n * largest to smallest order\n */\n\n var sorted = _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
7 Create a function called multiOf that takes 3 parameters, and return the first number mutiple by (the second one ^ the third number) Important: dont use Ex: multiOf(4,10,3); => 4000 Ex: multiOf(6,3,2); => 54 Ex: multiOf(6,2,3); => 48
function multiOf(num , num2 ,num3) { if(num3 != 0) { return num2*multiOf(num , num2 , num3-1); } return num; }
[ "function multiFourAndReturn(n1,n2,n3,n4){\n return n1*n2*n3*n4\n}", "function solution(number) {\n const multipleOfThree = [];\n const multipleOfFive = [];\n const multipleOfThreeAndFive = [];\n\n for (let i = 1; i < number; i++) {\n if (i % 3 === 0 && i % 5 !== 0) multipleOfThree.push(i);\n if (i % 5...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create shot based on UID of tank
function recivedShot(UID){ //tank have if(UID==GameObjs.Player.UID){ createShot(0,0,GameObjs.Player,GameObjs.Player.shotColor); return ; } for (var i = GameObjs.TANKs.length - 1; i >= 0; i--) { if(UID==GameObjs.TANKs[i].UID){ createShot(0,0,GameObjs.TANKs[i],GameObjs.TANKs[i].shotColor); ...
[ "function CreateOrUpdateTank(name,teamID,health,KillCount,x,z,UID,delta_server){\n if(UID==GameObjs.Player.UID){\n GameObjs.Player.x = x;\n GameObjs.Player.z = z;\n GameObjs.Player.health = health;\n \n GameObjs.Player.KillCount = KillCount;\n return ;\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the given properties match those of a `CfnAccessPointProps`
function CfnAccessPointPropsValidator(properties) { if (!cdk.canInspect(properties)) { return cdk.VALIDATION_SUCCESS; } const errors = new cdk.ValidationResults(); if (typeof properties !== 'object') { errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.st...
[ "function CfnAccessPointPolicyPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but rece...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if a piece was captured and return the destination square as the target
function capture(piece, target) { var currentTarget = target; if(performEnPassant(piece, target)) return currentTarget; if(containsClass(target.className, "chessMan1")) { currentTarget = target.parentElement; target.remove(); document.getElementsByClassName('bucketOfChess1')[...
[ "function canBeCaptured(testRow, testCol, epCol)\r\n\r\n{\r\n\r\n\t/* DESIGN NOTE: this function is designed only with CAPTURE checking in mind and should \r\n\r\n\t\tnot be used for other purposes, e.g. if there is no piece (or a king) on the give square */\r\n\r\n\t/* Both normal captures and en passant captures ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the translate function receives as parameters a string and an object the function throws exceptions if the types are not the required ones (message is "InvalidType") the dictionary object has in its keys the inital values and in its values the translation of the key the values in the dictionary are strings the function...
function translate(text, dictionary){ // TODO: implementați funcția // TODO: implement the function }
[ "function translate(text, dictionary){\n\t// TODO: implementați funcția\n\t// TODO: implement the function\n\t\n\t\n\t\tif (typeof text !== 'string'){\n\t\t\tthrow new Error(\"InvalidType\")\n\t\t}\n\t\tif (typeof dictionary !== 'object' || !dictionary){\n\t\t\tthrow new Error(\"InvalidType\")\n\t\t}\n\t\t// for (l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
padding blankHTML if node is empty (for cursor position)
function paddingBlankHTML(node) { if (!isVoid(node) && !nodeLength(node)) { node.innerHTML = blankHTML; } }
[ "function paddingBlankHTML(node){if(!isVoid(node)&&!nodeLength(node)){node.innerHTML=blankHTML;}}", "preprocessNodes(node) {\n let cleanedNode = node.cloneNode();\n if (node.nodeType === Node.ELEMENT_NODE) {\n const tag = tagName(node);\n // If we have to replace the tagname we create another node...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the request library needed for the given url
static getLib (url) { let urlo = URL.parse(url); let lib; switch (urlo.protocol) { case 'http:': return HTTP; case 'https:': return HTTPS; } throw new Error(`Unknown protocol ${urlo.protocol}.`); }
[ "static Request(url) {\n\t\tvar d = Core.Defer();\n\t\tvar xhttp = new XMLHttpRequest();\n\t\t\n\t\txhttp.onreadystatechange = function() {\n\t\t\tif (this.readyState != 4) return;\n\t\t\n\t\t\t// TODO : Switched to this.response, check if it breaks anything\n\t\t\tif (this.status == 200) d.Resolve(this.response);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Passes the current goal's id upwards to ProgressController to initiate marking a specific goal as active (approved). Triggered on user selecting the 'Edit Goal' option from a goal's dropdown menu. Available only to service provider users.
function markGoalActive() { props.markGoalActive(props.goalId); }
[ "function editGoal() {\n\t\tprops.editTask(props.goalId);\n\t}", "function markGoalComplete() {\n\t\tprops.markGoalComplete(props.goalId);\n }", "function progressForApproveBulkOnboard(goApprove, bulkOnboardId) {\n if (goApprove === true) {\n // progess for approve\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
disables the remove button
function disableRemove() { $("#removeButton").attr("disabled", "disabled"); }
[ "function disable_button() {\n allow_add = false;\n}", "function disableAdd() {\n\t$(\"#addButton\").attr(\"disabled\", \"disabled\");\n}", "function tryToEnableRemove(){\n\tif (removeNameOk){\n\t\t$(\"#removeButton\").removeAttr(\"disabled\", \"disabled\");\n\t}\n}", "function addButtonAvail() {\n var hi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Partition a list in two lists where the first list contains those elements that satisfy the given predicate `pred`. For example: `partition([1,2,3],odd?) == ([1,3],[2])`
function partition(xs, pred) /* forall<a> (xs : list<a>, pred : (a) -> bool) -> (list<a>, list<a>) */ { return partition_acc(xs, pred, Nil, Nil); }
[ "function partition (pred, arr) {\n// create two blank arrays\nconst success = [];\nconst failure = [];\n// iterate through array given, if something satisfies the predicate, push into array 1; otherwise add to array2\narr.forEach(el => {\n if (pred(el)) {\n success.push(el);\n } else {\n failur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the default block type for a block container
function defaultBlockType(container) { return acceptedBlocks(container)[0]; }
[ "function getBlockType(name) {\n return blockTypes[name] || false;\n }", "function acceptedBlocks(container) {\n return CONTAINERS[container.type || container.object];\n}", "setType(block) {\n const type = block.type === 'customBlock' ? block.fields.type : block.type;\n block.type = type;\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exported bindings Construct a Blip instance, which emits a single `data` event followed by `end` and `close` events. Blip instances are in turn instances of `stream.Stream`. The `data` argument must be a string or buffer to emit as data. Blip instances always start out paused, because there is no point in having them s...
function Blip(data, options) { if (typ.isDefined(data) && !typ.isString(data) && !typ.isBuffer(data)) { throw new Error("Data not a string or buffer."); } options = opts.validate(options, OPTIONS); if (typ.isString(data)) { // The `incomingEncoding` specifies an immediate transform of the // `data...
[ "createPipe(addr) {\n const pipeProps = {\n onNotified: (action) => {\n if (__IS_SERVER__ && action.type === SOCKET_CONNECT_TO_DST) {\n const [addr, callback] = action.payload;\n return this.connect(addr, () => {\n this._isHandshakeDone = true;\n callback();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send response to client. options statusCode is an integer HTTP status code (default 200) body is a string (assumed JSON format). If not provided, this is generated from the status code and message. headers is a optional hash of headers for the response. This will overwrite any existing headers. message is an optional e...
function sendResponse(req, res, options) { if (options && options.headers) { _.each(options.headers, function(value, key) { res.setHeader(key, value); }); } res.setHeader('Pragma', "no-cache"); res.setHeader('Cache-Control',"no-cache, no-store, max-age=0, must-revalidate"); res.setHeader('Expire...
[ "function sendCode(code,response,message) {\n response.status(code);\n response.send(message);\n}", "function writeStatus(status, headers) {\n if (!headers) headers = {};\n this.logType = headers['Content-Type'] = 'text/plain';\n this.logLength = headers['Content-Length'] = http.STATUS_CODES[status].length;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update Folder documents status
function updateall(folder, userid, activeStatus) { Folder.find({ parentid: folder._id }).exec(function (err, folders) { if (folders.length > 0) { //for inside folder ,documents (RESTORE/DELETE); Folder.update({ parentid: folder._id, active: !activeStatus }, { active: activeStatus }, { multi: true }).exec(f...
[ "onUpdateFolder() {\n this.store.query(\"folder\", {})\n .then((results) => {\n // Rebuild the tree\n this.send('buildTree', { folders: results });\n })\n .catch(() => {\n this.growl.error('Error', 'Erro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalizes a json api document into the formate the records reducer uses for its state object.
function normalizeDocument(jsonDocument) { var state = makeArray(jsonDocument.data).reduce(addRecordToState, {}) return makeArray(jsonDocument.included).reduce(addRecordToState, state) }
[ "function normalizeJSON(arr){\n return arr.map(r=> {\n return Object.entries(r).map(kv=> {\n let obj = {};\n let key = kv[0]?.replace(/#/g,'number')?.replace(/%/g,'percent')?.replace(/-/g,'to')?.replace(/\\W+/g,'_')?.replace(/^\\b(?=\\d)/,'_')?.replace(/_$/,'')?.toLowerCase();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert to either %f float or %e exponential notation, depending on magnitude if the exponent is >= 4 and "1.23e+03" (but: %e precision controls the number of decimals) Also, leading zeroes in very small numbers are ok, ie .00123456 => "0.00123456" and not 1.23456e03. NOTE: could maybe convert %g with v.toPrecision(pre...
function convertFloatG( width, padChar, rightPad, signChar, v, precision, eSym ) { if (v < 0) { signChar = "-"; v = -v } if (precision === 0) precision = 1; // pre-round v for magnitude test to know when to convert as a float. // Since rouding is expensive, only round if likely to be needed var rou...
[ "function show_fixed(d, precision) /* (d : double, precision : ?int) -> string */ {\n var _precision_17876 = (precision !== undefined) ? precision : -2;\n var dabs = Math.abs(d);\n var _x27 = (((dabs < (1.0e-15))) || ((dabs > (1.0e21))));\n if (_x27) {\n return show_exp(d, _precision_17876);\n }\n else {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
use to block popup background
function blockPopupBackground() { $("#background-main-div").removeClass("hidden"); }
[ "function unblockPopupBackground() {\n $(\"#background-main-div\").addClass(\"hidden\"); \n}", "function revealPopupBackground(systemPopup) {\n var settings = systemPopup.data(\"popup-settings\");\n var extra = systemPopup.data(\"popup-extra\");\n // Checks fade\n if (settings.wi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finishStateChange performs the repetitive tasks for a state update. INPUTS: si = stateinfo object to update c = command name
function finishStateChange(si,c) { //----------------------------------------------------------------------- // if the current state is in-progress, change to READY, and vice-versa //----------------------------------------------------------------------- var params = { cmd: c, records: [...
[ "function finishProcessing(id,percent,state,error){\n\t\tvar stateBar = getStateBarElement(id);\n\t\tvar btnStart = getBtnStartElement(id);\n\t\tvar btnDownlaod=getBtnDownloadElement(id);\n\t\t\n\t\tstateBar.innerHTML=state;\n\t\tif(error){\n\t\t\tupdateProgressBar (id, 0);\n\t\t\tresetColorsProgressBar (id);\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
call the constructor with the db name for embedded use and without it for inmemory use
constructor(dbFilePath) { if (dbFilePath) { //embedded this.db = new Datastore({ filename: dbFilePath, autoload: true }); } else { //in memory this.db = new Datastore(); } }
[ "constructor(DBPath){\n this.db = level(DBPath);\n }", "function initDb() {\n\n\t\tif(fs.existsSync(path.join(cloudDir ,dbName))){\n\t\t\t//TODO: catch errors\n\t\t\tfs.createReadStream(path.join(cloudDir ,dbName))\n\t\t\t\t.pipe(fs.createWriteStream(path.join(tempDir, dbName)));\n\t\t\n\t\t}\n\t\n\t}", "fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert subplot form data to wellordened JavaScript structure
function subplotForm2js(subplotFormId) { // Parse using form2js, see https://github.com/maxatwork/form2js var formData = form2js(subplotFormId); // Read HTML hidden fields. var maxCols = formData['_maxCols']; var maxRows = formData['_maxRows']; var maxCurves = formData['_maxCurves']; var r...
[ "function onSubplotFormSubmit(subplotFormId) {\n // Parse form data.\n var d = subplotForm2js(subplotFormId);\n // Report form errors.\n var error_report_items = $(\"#velocitySubplotForm ul\").empty();\n $.each(d.errors, function(idx,error_string) {\n error_report_items.append('<li>'+error_str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
makes the learn more about bleaching button
function makeBleachingButton() { // Create the clickable object bleachingButton = new Clickable(); bleachingButton.text = "What is bleaching?"; bleachingButton.textColor = "#365673"; bleachingButton.textSize = 25; bleachingButton.color = "#8FD9CB"; // set width + height to image size bleachingBu...
[ "function click_b() {\r\n \r\n\t\"use strict\";\r\n\t\r\n convert(Harvester.config.cost.b, {\"b\": 1});\r\n \r\n}", "function _btnWeight() {\n //Working\n console.log(\"doing something\");\n }", "function makeWhaleSharkButton() {\n\n // Create the clickable object\n whale...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the FB user tokens from auth0
function getFacebookUsersfromAuth0() { return new Promise(function(resolve, reject) { prequest('https://' + config.auth0.domain + '/api/v2/users', { 'auth': { 'bearer': config.auth0.clientToken } }).then(function(data) { resolve(data || []); }).catch(function(err)...
[ "static list_user_tokens({ organizationId, userId, page, count }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Action that saves the corresponding comment, turns off edit mode, and refetches the mentions.
save() { let component = this; let comment = get(this, 'comment'); comment.save().then((comment) => { component.set('isEditing', false); this._fetchMentions(comment); }); }
[ "function comment_edit_click(e) {\n\tvar comment_id = e.target.getAttribute('data-comment-id');\n\tconsole.log('editing comment ID #'+comment_id);\n\tvar comment = document.getElementById('comment-' + comment_id);\n\tvar edit_comment_form = document.getElementById('edit-comment-'+comment_id);\n\t//console.log(comme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function we call internally to generate a callback. It invokes `_.iteratee` if overridden, otherwise `baseIteratee`.
function cb(value, context, argCount) { if (_.iteratee !== iteratee) return _.iteratee(value, context); return baseIteratee(value, context, argCount); }
[ "function iterate(callback){\n let array = [\"dog\", \"cat\", \"squirrel\"]\n array.forEach(callback)\n return array\n}", "runGenerator (it, callback = (lastVal) => {}) {\n it = util.typeOf(it) === 'generator' ? it : it()\n ;(function iterate (val) { // asynchronously iterate over generator\n const ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update thoughts by ID
updateThoughts({ params, body }, res) { Thoughts.findOneAndUpdate({ _id: params.id }, body, { new: true, runValidators: true }) .then(dbThoughtsData => { if (!dbThoughtsData) { res.status(404).json({ message: 'No thoughts with this ID. ' }); return; } res.json(dbTho...
[ "updateThought({ params, body }, res) {\n Thought.findOneAndUpdate({ _id: params.id }, body, { new: true, runValidators: true })\n .select('-__v')\n .then(thoughtData => {\n if (!thoughtData) {\n res.status(404).json({ message: 'No Thought found with th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
displays a select of all the users apart from the sender it then emits the person to be dmed to the server
function renderModalAndEmitData(socket, userlist) { console.log(userlist, 'server list') const template = Handlebars.compile(document.querySelector("#put-users").innerHTML); const users = template({"users": userlist}); const select = document.querySelector("#users-select") select.innerHTML = users $("#dm-...
[ "sendUserlist() {\n this.print('Current Users');\n this.print(JSON.stringify(this.users, null, 2));\n this.namespace.emit('username list', this.getUsernames());\n }", "function showchatUserSelect(){\n if(userChat==null)\n {return;}\n /*eventAddChat(message);*/\n $(\".inyect-c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
You've just recently been hired to calculate scores for a Dart Board game! Scoring specifications: 0 points radius above 10 5 points radius between 5 and 10 inclusive 10 points radius less than 5 If all radii are less than 5, award 100 BONUS POINTS! Write a function that accepts an array of radii (can be integers and/o...
function scoreThrows(radii){ let score = 0; let bonus = true; if(radii.length == 0){ return 0; }; radii.map(val => { if(val > 4){ bonus = false; }; if(val >= 5 && val <= 10){ score += 5; }; if(val < 5){ score += 10; }; }); return bonus ? score...
[ "getScore() {\n\n let points = 0;\n\n\t\tfor(let i = 0; i < this.hand.length; i++){\n\t\t\tif(i == 0) points = this.hand[i].getValue(0);\n\t\t\telse points += this.hand[i].getValue(points);\n\t\t}\n\n\t\treturn points;\n\n\t}", "function sumOfSquares(array){\n let squaresArray=array.map(i=>Math.pow(i,2)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 175 Create a function that returns the mean of all digits.
function mean(num) { return [...num.toString()].reduce((x, i) => (Number(x) + Number(i))) / num.toString().length; }
[ "function arithmeticMean(num1, num2, num3, num4) {\n return (num1 + num2 + num3 + num4) / 4;\n}", "function avg(v){\n s = 0.0;\n for(var i=0; i<v.length; i++)\n s += v[i];\n return s/v.length;\n}", "function avg(num1, num2, num3){\n return (num1 + num2 + num3)/3;\n}", "function averageNumbers(array)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports all necessary Prism source styling and JS into the including app. This function is a public hook for addons that wish to use emberprism within their own components.
function importPrismSources(app, givenOptions) { var options = givenOptions || {}; //import theme based on options if (options.theme){ // allow ability to specify no css if we want to provide our own if (options.theme !== 'none'){ app.import(app.bowerDirectory + '/prism/themes/prism-' + options.the...
[ "initPrism() {\n // NOT used anymore, always use javascript\n // const options = {\n // ...this.options,\n // insideFences: markdownConversionSvc.defaultOptions.insideFences,\n // this.prismGrammars = markdownGrammarSvc.makeGrammars(options);\n // };\n }", "addLayoutScriptsAndStyles() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Missing Character Given a nonempty string and an integer, return a new string where the character at the specified index has been removed. The specified index will be a valid index of in the original string.
function missingCharacter(str, n) { var front = str.substring(0, n); var back = str.slice(n + 1); return front + back; }
[ "function remove(string, number) {\n // A place to store the number of times we're going to remove an !\n let timesWeRemove = number;\n\n // A Place to store our new string.\n let newString = \"\";\n\n // Iterate over string, and every time we find an ! and the number of !'s we're going to remove isn't 0, remo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an array of elements that have event listeners for the specified eventName, e.g. 'click'.
function findElementsWithListener(eventName) { var registeredListeners; var attributeListeners; // Check the registry for listeners. if (_elementsWithListeners.hasOwnProperty(eventName)) { registeredListeners = _elementsWithListeners[eventName]; } else { ...
[ "function bindListenerToNodes(elemList, eventName, callback) {\n\t\tfor (let elem of elemList) {\n\t\t\telem.addEventListener(eventName, callback);\n\t\t}\n\t}", "getAllEvents(objectInstance) {\n if (!objectInstance) {\n return [];\n }\n let prototype = Object.getPrototypeOf(object...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add listener for lecture stud count when closed
function lectureStudentCountListener(){ dbRef.child("lectures/" + sessionStorage.currentSubject + "/" + sessionStorage.lectureDate+ "/viewers").on("child_removed", function(snapshot){ incrementStudCountLecture(-1) }) }
[ "function lectureStudentCountListener(){\n dbRef.child(\"lectures/\" + sessionStorage.currentSubject + \"/\" + sessionStorage.lectureDate+\"/viewers\").on(\"child_added\", function(snapshot){\n incrementStudCountLecture(1)\n })\n}", "function closeRoll() {\n let countSelected = 0\n\t\tfor(let i = 0 ; ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state.
function SetNextItemOpen(is_open, cond = 0) { bind.SetNextItemOpen(is_open, cond); }
[ "SetNextTreeNodeOpen(is_open, cond)\n {\n let g = this.guictx;\n if (g.CurrentWindow.SkipItems)\n return;\n g.NextTreeNodeOpenVal = is_open;\n g.NextTreeNodeOpenCond = cond ? cond : CondFlags.Always;\n }", "function setOpenNodes(openNode) \r\n{\r\n\tfor (i=0; i<TreeNod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gives a random charactor
randomCharactor() { let str = '!@#$%^&*()_+?' return str[this.random(str.length)] }
[ "function makeChar() {\n\tvar probability=points(0,\"\")/hardness;//according to hardness of game\n\tif(typeof alphabets === 'undefined' || alphabets === \"\"){\n\t\tvar index=Math.floor(Math.random() * 5)+2;\n\t\talphabets=words[index][Math.floor(Math.random() * words[index].length)];\n\t\tif(points(0,\"\")===0){\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SWAP SLIDE PROGRESS /!SWAP SLIDE
function swapSlideProgress(container,opt) { container.trigger('revolution.slide.onbeforeswap'); opt.transition = 1; opt.videoplaying = false; //konsole.log("VideoPlay set to False due swapSlideProgress"); try{ var actli = container.find('>ul:first-child >li:eq('+opt.act+')'); } catch(e) { ...
[ "function swapSlide(container,opt) {\r\n\r\n\r\n\t\t\topt.transition = 1;\r\n\t\t\topt.videoplaying = false;\r\n\r\n\t\t\ttry{\r\n\t\t\t\tvar actli = container.find('>ul:first-child >li:eq('+opt.act+')');\r\n\t\t\t} catch(e) {\r\n\t\t\t\tvar actli=container.find('>ul:first-child >li:eq(1)');\r\n\t\t\t}\r\n\r\n\r\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add wait without Text
function addWaitWithoutText(dom) { $(dom).attr("disabled", "disabled"); string = '<i class="m-loader"></i>'; $(dom).html(string); }
[ "async function wait() {\n await driver.wait(until.elementIsEnabled(elCommand), 5000, \"CLI still not enabled after 5s\");\n }", "function ImportaddWaitWithoutText(dom) {\n $(dom).attr(\"disabled\", \"disabled\");\n string = '<i class=\"m-loader\">Importing</i>';\n $(dom).html(string);\n}", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Implement function to properly order the texture coordinates from the OBJ files. Hint: look at the console log for the toroid or sphere objects.
function getOrderedTextureCoordsFromObj(obj_object) { var texCoordsOrderedWithVertices = []; let position_indices = obj_object.i_verts; let tex_indices = obj_object.i_uvt; let tex_values = obj_object.c_uvt; for (let i = 0; i < position_indices.length; i++) { let aim = position_indices[i]; ...
[ "function parseObj() {\r\n // parse data\r\n\t\r\n\tvertexNum = 0;\r\n faceNum = 0;\r\n\t\r\n\tvar filename = \"teapot.obj\";\r\n var file = new XMLHttpRequest();\r\n var allText=[];\r\n\t\r\n file.open(\"GET\", filename, false);\r\n\t\r\n\tfile.onreadystatechange = function() {\r\n\t\t\r\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
INITIALIZES THE WEATHER WIDGET.
function init(){ console.log( 'AjaxWeatherWidget.init()'); //find the target element in the DOM containerElement = document.getElementById( elementId ); var seperator = ( containerElement.className.length > 0) ? '' : ''; containerElement.className += se...
[ "initAndPosition() {\n // Append the info panel to the body.\n $(\"body\").append(this.$el);\n }", "init() {\n this._createShadowRoot()\n this._attachStyles()\n this._createElements()\n }", "function init(){\n buildToolbar();\n initEditor();\n }", "function setupWidgets...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Implement function to properly order the normals from the OBJ files. Hint: look at the console log for the toroid or sphere objects.
function getOrderedNormalsFromObj(obj_object) { var normalsOrderedWithVertices = []; let position_indices = obj_object.i_verts; let norm_indices = obj_object.i_norms; let norm_values = obj_object.c_norms; for (let i = 0; i < position_indices.length; i++) { let aim = position_indices[i]; ...
[ "function calculateSurfaceNormals() {\n const len = segments.length;\n for(var i = 0; i < len; i++) {\n var points = segments[i];\n var normalVector = surfaceNormal(points);\n surfaceNormals.push(normalVector);\n }\n}", "function setNormals(mesh) {\n gl.bindBuffer(gl.ARRAY_BUFFER,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure we don't have two subtitle tracks with the same label Labels each track by language, eg 'German', 'English', 'English 2', ...
function relabelSubtitles (subtitles) { const counts = {} subtitles.tracks.forEach(track => { const lang = track.language counts[lang] = (counts[lang] || 0) + 1 track.label = counts[lang] > 1 ? (lang + ' ' + counts[lang]) : lang }) }
[ "labelCurrentTrack() {\n\t\tlet labl = 'empty';\n\t\tif (this.trks[tpos].usedInstruments.length === 1) {\n\t\t\tif (this.trks[tpos].hasPercussion) {\n\t\t\t\tlabl = 'Percussion';\n\t\t\t} else {\n\t\t\t\tlabl = getInstrumentLabel(this.trks[tpos].usedInstruments[0]);\n\t\t\t}\n\t\t} else if (this.trks[tpos].usedInst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Created an async renderApp func to render its ingredients when app is initialized
async renderApp() { // Assigning data from localstorage to favouriteFoods array if localstorage has data this.favouriteFoods = JSON.parse(localStorage.getItem("favFoods")) || [] // Taking user data await this.getUserInformation() // Taking meals data await this.getFoods()...
[ "function initializeApp(){\n renderAllStaff(staff) ;\n}", "constructor() {\n // An array for data which are taken api\n this.foodsArray = []\n // An array for favourite meals\n this.favouriteFoods = []\n this.renderApp()\n }", "function _initApp() {\n\n this.containers....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns position of the element corresponding to the specified ID.
posById(id){ let slot = this._index[id]; return slot ? slot[1] : -1 }
[ "function getOrderIdxById(id) {\n\tif (isNaN(id)) {\n\t\tthrow NaN;\n\t} else {\n\t\tid = Number(id);\n\t}\n\tvar idx = undefined;\n\tfor (var i = 0; i < orders.length; i++) {\n\t\tif (orders[i].id === id) {\n\t\t\tidx = i;\n\t\t}\n\t}\n\treturn idx;\n}", "function extractPositionFromId(id,type) {\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Questions By Class Id
function getQuestionByClassId(id) { return db("questions").where("questions.classId", id); }
[ "function getQuestionByQuestionId(id) {\n return db(\"questions\").where(\"questions.id\", id);\n}", "static getByQuestion(qID, returnAllData=true) {\n if (returnAllData) {\n return db.any(`\n SELECT * FROM results WHERE id_question = $1`,\n [qID]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Establish a channel to communicate with edX when the application is used inside a JSInput and hosted completely on a different domain.
function createChannel() { var channel, msg = 'The application is not embedded in an iframe. ' + 'A channel could not be established'; // Establish a channel only if this application is embedded in an iframe. // This will let the parent window communicate with the ...
[ "function setupChannel() {\n // Join the general channel\n generalChannel.join().then(function(channel) {\n print('Joined channel as <span class=\"me\">' + username + '</span>.', username, new Date());\n });\n\n // Listen for new messages sent to the channel\n generalChannel.on('messageAdded', f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the Unit in this Tile
setUnit(unit) { this.unit = unit; }
[ "createUnit(mapX, mapY, unitType, player) {\r\n let u = new Unit(this, this.tiles[mapY][mapX], unitType, player)\r\n this.units.push(u);\r\n player.units.push(u);\r\n }", "function update_tile_unit(punit)\n{\n if (punit == null) return;\n \n var found = false;\n var ptile = index_to_tile(punit['tile...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a cursor of documents that will be archived
function findDocumentsToArchive(collection, query, limit) { return collection.find(query).limit(limit); }
[ "async function nextDocumentsFromCursor(cursor, limit) {\n let docsToArchive = [], docIds = [], hasNext = true;\n while (docsToArchive.length < limit) {\n const doc = await cursor.next()\n .then(doc => {\n return doc;\n })\n .catch(err => {\n console.error(`Failed to find documents: ${err}`)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the POSITIVE y value of a point on the edge of the ellipse given an xvalue
function yValuePositive(x) { var x = x - (apertureCenterX); //Bring it back to the (0,0) center to calculate accurately (ignore the y-coordinate because it is not necessary for calculation) return verticalAxis * Math.sqrt(1 - (Math.pow(x, 2) / Math.pow(horizontalAxis, 2))) + apertureCenterY; //Calculated the po...
[ "function yValueNegative(x) {\r\n\t\t\tvar x = x - (apertureCenterX); //Bring it back to the (0,0) center to calculate accurately (ignore the y-coordinate because it is not necessary for calculation)\r\n\t\t\treturn -verticalAxis * Math.sqrt(1 - (Math.pow(x, 2) / Math.pow(horizontalAxis, 2))) + apertureCenterY; //C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs when the user presses the "Read" button on a measuring point We allow one local reading per point, so decide if this is a create doc or update doc for the current point Save some state variables to be used later Run the nav action to the screen
static measurementDocumentCreateUpdateNav(pageClientAPI) { let point = libCom.getTargetPathValue(pageClientAPI, '#Property:Point'); //Read from measurment documents looking for a modified row matching this point return pageClientAPI.read( '/SAPAssetManager/Services/AssetManager.servi...
[ "function readData()\r{\r var pages = docData.selectedDocument.pages;\r $.writeln('# of pages: ' + pages.length);\r for (var x = 0; x < pages.length; x++){\r page = pages.item(x); \r pageName = page.name;\r $.writeln(\"Page: \" + pageName);\r pageTagToAdd = addPage(pageName);\r ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Desmarca todos os checked box.
function desmarcar(){ $('.linha_exame_lista_input').each( function(){ if ($(this).prop( "checked")){ $(this).prop("checked", false); $('.lista_exames_check_all').prop("checked", false); } } ); }
[ "unCheck(){\n //let { $input, $label } = PRIVATE.get(this);\n\n PRIVATE.get(this).$input.checked = false;\n markChoiceField.call(this);\n //domRemoveClass($label, CSS_MS_IS_CHECKED);\n }", "function uncheckAll(name) {\r\n\tsetCheckboxState(name, false);\r\n}", "cleanCheckboxSelect...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders a page with user's favorite Internet Archive videos
static favorites() { $.getJSON( 'https://archive.org/bookmarks.php?output=json', (faves) => { let vids = '' if (!faves.length) { TVA.alert( 'Make some Favorites!', 'Open a browser with https://archive.org, login, and start making some favorite and they ...
[ "function BrowseMovies() \n{\n HideListingCriteria();\n movieCriteria = \"All\"\n movieCriteriaValue = \"Movies\";\n BuildMoviesCache(MOVIE_LISTING_URI)\n startPage = 0;\n FetchTitles(startPage)\n}", "function BrowseSeasons() \n{\n HideListingCriteria();\n movieCriteria = \"All\"\n movi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
+++++++++++++++++++++++++ START OF ADDED STUFF If the map has not already been zoomed in, this function will help do so when a marker is clicked.
function setZoomOnMarkerClick(){ const currentZoom = map.getZoom(); if (currentZoom < 12){ map.setZoom(17); } }
[ "function zoom_to_marker() {\n maxZoom = map.mapTypes[map.mapTypeId].maxZoom;\n map.panTo(openMarker.position);\n map.setZoom(maxZoom);\n}", "function handleClickOnMap() {\n $(\"#map_container\").click(function() {\n startMapMode();\n });\n }", "function zoom() {\n airbnbNodeMap.zoom();\n m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initiate an abrupt close and destruction of the QuicSocket. Existing QuicClientSession and QuicServerSession instances will be immediately closed. If error is specified, it will be forwarded to each of the session instances. When the session instances are closed, an attempt to send a final CONNECTION_CLOSE will be made...
destroy(error) { // If the QuicSocket is already destroyed, do nothing if (this.#state === kSocketDestroyed) return; // Mark the QuicSocket as being destroyed. this.#state = kSocketDestroyed; // Immediately close any sessions that may be remaining. // If the udp socket is in a state wher...
[ "destroy(error) {\n // Destroy can only be called once. Multiple calls will be ignored\n if (this.#destroyed)\n return;\n this.#destroyed = true;\n this.#closing = false;\n\n if (typeof error === 'number' ||\n (error != null &&\n typeof error === 'object' &&\n !(error inst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
first, sort the sock array n log(n) iterate once and count the pairs n Time Complexity: n + n log(n) ~ n log(n)
function sockMerchant(n, ar) { const socks = ar.sort(); let sockCount = 0; let currentSock = null; let prevSock = null; let pairs = 0; for (let i = 0; i < socks.length; i++) { prevSock = currentSock; currentSock = socks[i]; if (currentSock === prevSock) { if (sockCount >= 2) { ...
[ "function numberOfPairs(gloves) {\n gloves = gloves.sort();\n let count = 0;\n for (let i = 0; i < gloves.length; i++) {\n if (gloves[i] === gloves[i+1]) {\n count += 1;\n i++;\n }\n }\n return count;\n}", "function neighbouringElements(a) {\n var count = 0;\n for(var i = 0; i < a.lengt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is passed in an array of X values and returns an array of predicted Y values based on the current values of a, b and c weights
function predict(x) { return a .mul(x.square()) .add(b.mul(x)) .add(c); }
[ "function predict(input) {\n return dl.tidy(() => {\n\n const hidden = input.matMul(weights).add(biases).relu();\n const hidden2 = hidden.matMul(weights2).add(biases2).relu();\n const out = hidden2.matMul(outWeights).add(outBias).sigmoid().as1D();\n\n return out;\n });\n}", "calculateCoefficients ()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
stringLimitDots method is used to restrict the string if its morethan length parameter its shorten to given length and ... will be appended.
function stringLimitDots(input,length){ if(input!=undefined){ if(input.length>length) return input.substring(0,length)+'...'; return input; } else return ''; }
[ "function trimStringToMaxLength(string) {\n return string.length > config.maxlength ?\n string.substring(0, config.maxlength - 3) + \"...\" :\n string;\n}", "function truncateString(str, length) {\n if(length >= str.length) return str\n else if(length <= 3) return str.slice(0, length) + '.....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort tasks by uncomplete and complete
get sorted() { let uncomplete = []; let complete = []; for (let task in this.state.tasks) { if(this.state.tasks[task]) { if (this.state.tasks[task].completed) { complete.push(this.state.tasks[task]); } else { uncomplete.push(this.state.tasks[tas...
[ "sortProject(){\n this._tasks.sort((a,b)=>\n {if(a.complete==true&&b.complete==false){\n return 1\n }\n else if(a.complete==false&&b.complete==true){\n return -1\n }\n else{\n if(a.priority==true&&b.priority==false){\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a single tweet by id and render it to itemResult div.
function renderTweetItem(username,tweet){ $("#itemResult").html(''); // clear previous list elements var listElement = createTweetDomContainer(username,tweet,false); $("#itemResult").append(listElement); }
[ "function handleSingleTweet(response, tweetid){\n\tvar tweet = findTweet(tweetid);\n\tresponse.writeHead(200);\n\tif(tweet){\n\t\tresponse.write(\"Info on tweet with id=\" + tweetid + \":<br />\\r\\n\" + JSON.stringify(tweet))\n\t}\n\telse{\n\t\tresponse.write(\"No such tweet with id=\" + tweetid + \" found.\");\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }