query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
PUBLIC Adds a port to this network element.
function addPortToNe(port) { port.setNetworkElement(this); this.ports.add(port, true); }
[ "function addPort() {\n functionDiagram.startTransaction(\"addPort\");\n functionDiagram.selection.each(function (node) {\n // skip any selected Links\n if (!(node instanceof go.Node)) return;\n // compute the next available index number for the side\n var i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
default config for an image button
get imageButton() { return { type: "rich-text-editor-image", }; }
[ "function setImage(){\n\t\tbtn.backgroundImage = btn.value ? btn.imageOn : btn.imageOff;\n\t}", "get imageButton() {\n return {\n ...super.imageButton,\n label: this.t.imageButton,\n };\n }", "function MASH_ImageButton(tmpID, tmpLeft, tmpTop, tmpWidth, tmpHeight, tmpZIndex, tmpStyle,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the list of files referenced by this scope that are actually loaded in the program. Excludes files from ancestor scopes
getOwnFiles() { //source scope only inherits files from global, so just return all files. This function mostly exists to assist XmlScope return this.getAllFiles(); }
[ "getUnreferencedFiles() {\n let result = [];\n for (let filePath in this.files) {\n let file = this.files[filePath];\n if (!this.fileIsIncludedInAnyScope(file)) {\n //no scopes reference this file. add it to the list\n result.push(file);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if all the currently visible lines are justified, shows the problem/next line button and updates the instructions html
function checkVisibleLines () { if (allVisibleLinesJustified()) { $('#problemButton').show(); $('#ruleInstructionsPartial').html('Correct! Click \'Next Line\' to continue.'); } }
[ "function allVisibleLinesJustified () {\n\tfor (var i in currentProblem.steps) {\n\t\tif (!currentProblem.steps[i].justified && !currentProblem.steps[i].ishidden) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}", "function showInstructions() {\n\t\t\tclear();\n\t\t\tdiv.update('<span style=\"color: grey; fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables the 'show notes' button if notes are available
function enableShowNotesButton() { var needed = false; for (let i = 0; i < activeQuestion.clues.length; i++) { note = activeQuestion.clues[i].r; if (note !== "") { needed = true; } } if (needed) { document.getElementById("notes-button").classList.add("control-button-active"); } }
[ "function showNotes() {\n const infoButton = document.getElementById(\"infoButton\");\n const notesButton = document.getElementById(\"notesButton\");\n infoButton.classList.remove('selected');\n notesButton.classList.add('selected');\n\n const infoSection = document.getElementById(\"infoSection\");\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the flag that the user pasted the value. The reason for this is that the onpaste event that is passed does not have consistent behaviour with respect to event.target.value it is sometimes undefined. The onchange event always gets fired after this to we can set the flag and then check for it in that event.
handlePaste() { this._pasting = true; }
[ "validationOnPaste(event, $element, ngModelCtrl, options) {\n if (options.maskRe) {\n var regExp = new RegExp(options.maskRe, this.flags);\n var pasteData = event.originalEvent.clipboardData.getData('text');\n var valueDataPaste = this.getTextValue($element, pasteData, option...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets 5 newest updates from authenticated user's friends.
function api_get_newest_friend_messages(req, res) { var username = req.user; if (username !== req.param('name')) { res.json(403, {message : 'User ' + username + ' doesnt have rights.'}); } User.findOne({user : username}, 'friends', function(err, user) { if (!err && user) { console.log(user.friends); ...
[ "function updateFriends() {\n friendsFactory.getFriends(function (friends) {\n self.friends = friends;\n socket.emit('get online friends', friends);\n });\n\n }", "function getFriends (T, screenName, interval = 5 * 62 * 1000, friends = [], cursor = -1) {\n return new Promise((resolve, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SEND YES OR NO BUTTONS
function sendYesOrNoButton(recipientId, callback) { var messageData = { recipient: { id: recipientId }, message: { attachment: { type: "template", payload: { template_type: "button", text: "Did yo...
[ "function yesOrNoButtons(title) {\n var message = {\n \"attachment\":{\n \"type\":\"template\",\n \"payload\":{\n \"template_type\":\"button\",\n \"text\":title,\n \"buttons\":[\n {\n \"type\":\"postback\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a from a given base to base 10.
toBase10(value, b = 62) { const limit = value.length; let result = base.indexOf(value[0]); for (let i = 1; i < limit; i++) { result = b * result + base.indexOf(value[i]); } return result; }
[ "function baseConverter(num, b) {\n if (num === 0) return \"\";\n\n const digits = '0123456789abcdef'.split('');\n\n return baseConverter(Math.floor(num/b), b) + digits[num % b];\n}", "function baseConverter(num, b) {\n\n}", "function baseConverter(decNumber, base) {\n let remStack = new Stack()\n let ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
animate: used to handle each update... basically, recompute the solution, update the solution curve geometry, and adjust the viewpoint
function animate () { // From mozilla.org... the window.requestAnimationFrame() method tells the // browser that you wish to perform an animation and requests that the browser // calls a specified function to update an animation before the next repaint. // The method takes a callback as an argument ...
[ "function animate ()\n{\n // From mozilla.org... the window.requestAnimationFrame() method tells the \n // browser that you wish to perform an animation and requests that the browser \n // calls a specified function to update an animation before the next repaint. \n // The method takes a callback as an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maybefantasyland/reduce :: Maybe a ~> ((b, a) > b, b) > b . . `reduce (f) (x) (Nothing)` is equivalent to `x` . `reduce (f) (x) (Just (y))` is equivalent to `f (x) (y)` . . ```javascript . > S.reduce (S.concat) ('abc') (Nothing) . 'abc' . . > S.reduce (S.concat) ('abc') (Just ('xyz')) . 'abcxyz' . ```
function Nothing$prototype$reduce(f, x) { return x; }
[ "function reduceCallback(c){\n if (c == undefined){;return}\n if (typeof c === 'function') {return [c,[]];}\n if (Array.isArray(c) && c.length>0){\n var f = c[0];\n c.shift();\n return [f,c]\n }\n}", "function OrReduce(accumulator, value) {\n return accumulator || value;\n }", "function L...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test Read HTML FileTemplate (when logged in)
function read_html_filetemplate(err, res, body) { var query = querystring.stringify({ catalogName: "dbo.Empleado", controlType: "fileTemplate", filters: "'id=1'", output: "html" }) frisby.create('Read HTML FileTemplate') .addHeader('Cookie', session_cookie) // Pass session cookie with each request ....
[ "_getTemplateFile(htmlFilePath) {\n const filePath = path.join(config.reports.templates_folder, htmlFilePath);\n return fs.readFileSync(filePath);\n }", "function readTemplate(titles, response) {\n fs.readFile('./template.html', function(err, data) {\n if (err) {\n return had...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handleGuess() check if the button is the corret answer
function handleGuess() { // clear the timer clearTimeout(timer); // if correct if ($(this).text() === correctAnimal) { // remove buttons $(".guess").remove(); // say a praise before starting a new round timer = setTimeout(newRound, saySomething(0)); // update score score += 1; update...
[ "function handleGuess() {\n // If the button they clicked on has the same label as the correct button, it must be the right answer...\n if ($(this).text() === $correctButton.text()) {\n // Highlight the correct answer in blue during 3 seconds\n $correctButton.effect(\"highlight\", {color: \"#66ffff\"}, 3000...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets scope from element
function getScope(element) { var path = []; var value = element.getAttribute("scope")// || element.getAttribute("loop"); if(value) { // if(value.indexOf("window.") != -1) return undefined; if(value[0] == ".") return undefined; path = [value] } var element = element.parentNode; ...
[ "scope(el) {\n\t\t\tdeb(\"xx.scope()\", el);\n\t\t\tconst elChain = new Set;\n\t\t\twhile (elChain.add(el), el = el.parentNode);\n\n\t\t\treturn find(this.tree).scope;\n\n\t\t\tfunction find(xxFoo) {\n\t\t\t\tfor (const n of xxFoo.chld) if (n.chld) {\n\t\t\t\t\tconst r = find(n);\n\t\t\t\t\tif (r) return r;\n\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete overlays when display mode changes to HMD mode Draw overlays when mode is in desktop
function onDisplayModeChanged(isHMDMode) { if (isHMDMode) { deleteStatusOverlays(); } else { drawStatusOverlays(); } }
[ "function deleteStatusOverlays() {\n if (rectangleOverlay) {\n Overlays.deleteOverlay(rectangleOverlay);\n rectangleOverlay = false;\n }\n if (desktopOverlay) {\n Overlays.deleteOverlay(desktopOverlay);\n desktopOverlay = false;\n }\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export selected area on the map as a json encoded geoJson standard file, no backend calls simple HTML5 trick ;)
function exportToGeoJSON(element, content) { // HTML5 features has been used here var geoJsonData = 'data:application/json;charset=utf-8,' + encodeURIComponent(content); // TODO: replace closest() by using persistence id for templates, template id prefixed by unique id(i.e leaflet_id) var fileName = $(...
[ "function export_geojson(){\n datalayer.toGeoJson(function (data) {\n download(JSON.stringify(data, null, 2), \"MissionPlaner.json\", \"text/plain\");\n });\n}", "function exportToGeoJSON(link, content) {\n // HTML5 features has been used here\n var geoJsonData = 'data:application/json;charset=utf-8,' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this is to load the boid array of boids
function loadboid(numboid){ for(i=50; i < numboid; i++){ var loc = createVector(random(width), random(height)); var vel = createVector(random(-3,3), random(-3,3)); var radius=random(10,10); var col= color(random(1, 255), random(1, 255), random(1, 255)); boids.push(new boid(loc, vel, radius...
[ "function loadBoids(){\n\tfor(var i = 0; i < 50; i++){\n var loc = createVector(i* width, height);\n boids[i]= new Boid(random(width), random(height),random(-10,10),random(-10,10));\n }\n\n}", "function loadBoids(numboids){\n for(var i = 0; i < numboids; i++){\n var loc = createVector(random(width), ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the session button
function addSessionBtn(session) { var quizSessions = document.querySelector("#"+_this.id + " .sessions-saved"); console.log("caching " + quizSessions); var sessionBtn = document.createElement("div"); var resumeBtn = createEl("button", "resumeBtn", session.timeStamp ); var deleteBtn = createEl("butto...
[ "function newSessionButtons(session) {\n document.getElementById(\"start-video\").disabled = true;\n document.getElementById(\"disconnect-video\").disabled = false;\n document.getElementById('screen-share').disabled = false;\n document.getElementById('archive-video').disabled = false;\n document.getE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates a the Google Function Rank in column three of the sheet Ranking Table
function rankString() { var lastRowNumer = rankingSheet.getLastRow(); for (var i = 2; i < lastRowNumer; i ++) { var sheetPosition = i + 1; var name = ('=RANK(D'+ sheetPosition + ', D1:D' + lastRowNumer + ')'); rankingSheet.getRange(sheetPosition, 3).setValue(name); } }
[ "function rankUser(array) {\n\n if (rankingSheet == null) {\n rankingSheet = ss.insertSheet().setName('rankingTable')\n }\n else {\n rankingSheet.getDataRange().clear();\n }\n\n for (name in array) {\n var tempSheet = ss.getSheetByName(array[name]);\n\n if (tempSheet == null) {\n continue;\n }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exported functions: getAssociations invalidateAssociations action creators
function requestAssociations() { return { type: actionTypes.REQUEST_ASSOCIATIONS, }; }
[ "function updateAssociations() {\n console.log('updating associations');\n associations = mirror.listAssociations().map(function(guid) {\n return assocWrapper(guid);\n });\n }", "get associations() { return associations; }", "async _invalidations() {\n let schema = await this.schema(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the answer to a get_clean_summary message
function parseCleaningSummary(response) { response = response.result; return { clean_time: response[0], // in seconds total_area: response[1], // in cm^2 num_cleanups: response[2], cleaning_record_ids: response[3], // number[] }; }
[ "function fillSummary(message) {\n if (message.content) {\n message.summary = message.content.replace(/(^|[\\n\\r]+)\\s*>[^\\n\\r]*/g, '').trim();\n if (message.summary.length > 140) {\n message.summary = message.summary.substr(0, 137) + '...';\n }\n }\n }", "function pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether `node` is of given `type`. For better performance, use this instead of `is[Type]` when `type` is unknown. Optionally, pass `skipAliasCheck` to directly compare `node.type` with `type`.
function is(type, node, opts, skipAliasCheck) { if (!node) return false; var matches = isType(node.type, type); if (!matches) return false; if (typeof opts === "undefined") { return true; } else { return t.shallowEqual(node, opts); } }
[ "function is(type, node, opts, skipAliasCheck) {\n if (!node) return false;\n\n var matches = isType(node.type, type);\n if (!matches) return false;\n\n if (typeof opts === \"undefined\") {\n return true;\n } else {\n return t.shallowEqual(node, opts);\n }\n}", "function is(type,node,opts,skipAliasChe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
close event function (fadeout)
function close() { fadeOutEffect(DOMstrings.divCalQ, remove); }
[ "function qbclose(){\n\t jQuery('#qb-overlay').fadeOut();\n}", "close() {\n this.stopSlideVideo(this.activeSlide)\n addClass(this.modal, 'glightbox-closing')\n animateElement(this.overlay, this.settings.cssEfects.fade.out)\n animateElement(this.activeSlide, this.settings.cssEfects.zoom...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hides the message panel with a sliding effect, and adapts the visibility of the message panel control links
function hideMessagePanel() { $("#showMessagesLink").show(); $("#hideMessagesLink").hide(); $("#messages").slideUp(); return false; }
[ "function showMessagePanel() {\r\n $(\"#showMessagesLink\").hide();\r\n $(\"#hideMessagesLink\").show();\r\n $(\"#messages\").hide();\r\n $(\"#messages\").slideDown();\r\n return false;\r\n}", "function hidePanel(){\n\t//165 => 20 pc_title + 120 item + margins\n\t$pc_panel.css({\n\t\t'right'\t: -wi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that is used to collect a list of the disliked posts based on their id
function retrieveDislikedPosts(){ let disliked_posts = []; for(let i =0; i<disliked_posts_id.length; i++){ let j=0; while (j < posts.length){ if(disliked_posts_id[i] == posts[j].id){ disliked_posts.push(posts[j]); break; } else { j++; } } } displayDisikedPo...
[ "function dislikepost() {\n setUnlike(true);\n const value = allpost;\n const updatedarray2 = value.filter(post => {\n const temp = {userId:post.userId,\n title:post.title,\n body:post.body};\n if(JSON.stringify(temp) !== JSON.stringify(user)){\n return post;\n }else {\n post.dislike...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
= Description The _makeElem method does the ELEM.make call to create the element of the component. It assigns the elemId. It's a separate method to ease creating component that require other element types. ++
_makeElem(_parentElemId) { this.elemId = ELEM.make(_parentElemId, this.cellTagName); ELEM.setAttr(this.elemId, 'view_id', this.viewId, true); ELEM.setAttr(this.elemId, 'elem_id', this.elemId, true); Object.entries(this.cellTagAttrs).forEach(([key, value]) => { ELEM.setAttr(this.elemId, key, value,...
[ "add_element( elem )\n {\n\n if ( !elem.type )\n {\n elem.type = 'circle';\n }\n\n if ( !elem.material )\n {\n elem.material = 'basic';\n }\n\n var curent_element = eval(\"new \" + elem.type + \"()\");\n\n curent_element = Object.assign( curent_element, elem);\n\n curent_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::CodeDeploy::DeploymentGroup.BlueGreenDeploymentConfiguration` resource
function cfnDeploymentGroupBlueGreenDeploymentConfigurationPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnDeploymentGroup_BlueGreenDeploymentConfigurationPropertyValidator(properties).assertSuccess(); return { DeploymentReadyOption: cfnD...
[ "function CfnDeploymentGroup_BlueGreenDeploymentConfigurationPropertyValidator(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.ValidationRe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through the elemnts looking for links and if the anchor text or the target matches the cleaned title, then we emit an alias for that target pointing to the title.
function handle_ambiguous_page(title,json) { var title_name = (title.charAt(0)=='(' ? title : title.replace(/\s*\(.+\)/,'')); for(var i=0, len = json.length; i < len; ++i) { var elem = json[i]; if (typeof(elem) != 'string' && elem.type == 'internal_link') { if ((elem.anchor_text && elem.anchor_text.in...
[ "function tweaklinks(doc)\n{\n // Do not touch these link titles\n let ignoreTitles=[\"Lägg till\",\"Ta Bort\"];\n let mapfixedlinks = [\n { href: 'https://www.avanza.se/hall-koll/min-borsskarm.html', name: 'borsskarm' },\n { href: 'https://www.avanza.se/min-ekonomi/oversikt.html', name: 'oversikt' }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify that user selected a result item
onResultSelected() { const result = document.activeElement; if (this.ux.results !== result.parentElement) return; this.publish("selectresult", JSON.parse(result.dataset.d)); }
[ "dispatchSelectionResult() {\n let eventName = this.fieldName\n ? \"valueChanged\"\n : \"recordselected\";\n let payload = {\n canceled: this.selectedRecord ? true : false,\n recordId: this.selectedRe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if supplied setting exists and valid and constructs the query string part of the API URL accordingly.
resolveSettings(key, setting) { if (!setting) { return ""; } return `${key}=${setting}&`; }
[ "buildURL(query) { return CONFIG.apiRootURL; }", "function constructUrl() {\n if (laborPreference.size) {\n let labor = ([...laborPreference]).join(',');\n return `${baseEndpoint}?q=${currentQuery}&start=${currentStart}&limit=${currentLimit}&laborTypes=${labor}`;\n }\n // when no preferences (n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define a setter for `a`
set a(val) { this._a_ = val * 2; }
[ "set a(val){\n this.a = val;\n }", "set a(val) {\n\t\tthis._a_ = val;\n\t}", "set aa(a) {\n this.a = a;\n }", "set a(val) {\n\t\tthis._a_ = val * 2;\n\t}", "set a(val) {\r\n\t\t\tthis._a_ = val * 2;\r\n\t\t}", "function setA(anio)\n {\n this.anio=anio;\n }", "set anaerobic(ana...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DEMO SCHEDULING This pops off the track and pattern positions for the next part, and uses it to set the next part to occur when the music reaches that point. (The Senior Dads Music player class allows to set a "breakpoint" so that a function is executed when a tracker module gets to a certain position.)
function scheduleNextPart() { if ((currentPos+1) < schedule.length) { // If we're not at the end of schedule... SeniorDads.Music.SetBreakPoint( // Set the next part to execute at the next music breakpoint. schedule[currentPos+1].trackPos, schedule[currentPos+1].patternPos, ...
[ "function mainDemo() {\n \t// DEMO SCHEDULE:\n \t//\n \t// This a large JSON array of the form:\n \t// var schedule = [\n \t//\t\t{ trackPos: [module track position], patternPos: [module pattern position], \n \t//\t\t\tlayers: { effect1: [...], effect2: [...]\n \t//\t\t}, \n \t//\n \t//\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to colorize the resources
function resourceColorizer() { return 'rgb(0,255,20)'; }
[ "function getColorsets() {\n var colorsetDir = appPath + 'resources/colorsets/';\n var files = fs.readdirSync(colorsetDir);\n var sets = [];\n\n // List all files, only add directories\n for(var i in files) {\n if (fs.statSync(colorsetDir + files[i]).isDirectory()) {\n sets.push(files[i]);\n }\n }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the failure entries in the thrown or returned error object.
function check_failures (e) { expect(e.failures).to.be.an('array'); expect(e.failures[0].error).to.be.instanceof(Error); expect(e.failures[0].moduleName).to.equal('nothere'); expect(e.failures[0].module).to.be.null; expect(e.failures[1].error).to.be.instanceof(Error); exp...
[ "function verifyErros(){\r\n let foudError = false\r\n\r\n for(let error in field.validity){\r\n // se não for customErro\r\n // então verifica se é verdadeira\r\n // Caso seja possui um erro\r\n if(error != \"customError\" && field.validity[error]){\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the mouse is clicked the background changes to the position of the mouse and a random number from 0 255
function mouseClicked() { colorBg.r = map(mouseX, 0, windowWidth, 0, 255); colorBg.g = map(mouseY, 0, windowHeight, 0, 255); colorBg.b = floor(random(0, 255)); background(colorBg.r, colorBg.g, colorBg.b); }
[ "function mouseClicked() {\n bgColor = color(random(255), random(255), random(255));\n fillColor = color(random(255), random(255), random(255));\n}", "function mouseClicked() {\n background(250, 250, 100)\n}", "function mouseClicked() {\n bgimg = random(imgs);\n}", "function mousePressed() {\r\n r = rand...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
addresslist = (address ("," address)) / obsaddrlist
function addressList() { return wrap('address-list', or( and( address, star(and(literal(','), address)) ), obsAddrList )()); }
[ "function addressList() {\n return wrap('address-list', or(and(address, star(and(literal(','), address))), obsAddrList)());\n }", "function obsAddrList() {\n return opts.strict ? null : wrap('obs-addr-list', and(star(and(invis(opt(cfws)), literal(','))), address, star(and(literal(',')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a function named setValueByName The function should accept 2 parameters: name and value The function should select the element with the given name Assume there is only 1 element with the given name on the page The function should set the element's value to be the given value
function setValueByName (name, value) { return document.getElementsByName(name)[0].value = value; }
[ "function setValueByName(name, value) {\n document.getElementsByName(name)[0].value = value;\n}", "function setValueByName (name, value) {\n\n}", "function setValueByName (name, value) {\nreturn $('[name=\"' + name + '\"]').val(\"\" +value);\n}", "function setValue(name, value) {\n var nameSelect = \"[nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the list of Groups and attaches event listeners
function renderGroups (groups) { var _groupsUl = $U('#group-container'); _groupsUl.innerHTML = ''; var groupsUsers = $storage.get('groupsUsers') || {}; groups.forEach(function (group) { var _li = _document.createElement('li'); _li.innerHTML = group.name; _li.setAttribute('data-modal-...
[ "function drawStudentGroup(group) {\n // groups are in array form for the instructor's screen.\n group = group[0];\n\n // Set the title for the student group\n $(\"#student-group-title\").text(\"You are in \" + group['name']);\n\n // Clear the container...\n $(\"#group_div_container\").empty();\n\n // Add ea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets camera to default transformation
function resetCamera() { mainCamera.setAttribute("rotation", "0 0 0"); mainCamera.setAttribute("position", "0 1.6 0"); }
[ "function resetCamera() {\n xPos.value = camXDefaultPos;\n yPos.value = camYDefaultPos;\n}", "function reset() {\n cameraRotation = {\n elevation: Math.PI / 3,\n azimuth: Math.PI / 3\n };\n camera.position.set(3, 4, 5);\n lookAtPosition = new THREE.Vector3(0, 0, 0);\n objectMana...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes one of the two main hal properties, that is _links or _embedded. Each subproperty is turned into a single element array if it isn't already an array. processingFunction is applied to each array element.
function parseHalProperty(property, processingFunction, validation, path) { if (property == null) { return property } // create a shallow copy of the _links/_embedded object var copy = {} // normalize each link/each embedded object and put it into our copy Object.keys(property).forEach(function(key) {...
[ "function parseHalProperty(property, processingFunction, validation, path) {\n if (property == null) {\n return property;\n }\n\n // create a shallow copy of the _links/_embedded object\n var copy = {};\n\n // normalize each link/each embedded object and put it into our copy\n Object.keys(property).forEach...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normal approach iterating from 1 to n, to find the nth ugly number
function getNthUglyNumber(n) { // time - O(n), space - O(n) const uglyNumbers = []; let i2 = 0; let i3 = 0; let i5 = 0; let nextMultipleOf2 = 2; let nextMultipleOf3 = 3; let nextMultipleOf5 = 5; uglyNumbers[0] = 1; let nextUglyNumber = 1; let i = 1; while (i < n) { i += 1; nextUglyN...
[ "function getNthUglyNo(n) {\n let ugly=[]; // To store ugly numbers\n let i2 = 0, i3 = 0, i5 = 0;\n let next_multiple_of_2 = 2;\n let next_multiple_of_3 = 3;\n let next_multiple_of_5 = 5;\n let next_ugly_no = 1;\n\n ugly[0] = 1;\n for (let i=1; i<n; i++) {\n next_ugly_no = Math.min(nex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the given properties match those of a `CookiesProperty`
function CfnWebACL_CookiesPropertyValidator(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: ' + J...
[ "function CfnWebACL_CookieMatchPatternPropertyValidator(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 objec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a Tile ArcGIS MapServer layer to the map.
function addTileArcGISMapServerLayer({ title = 'arcgis-tile', url, params, visible = true, base = false, attribution = '', }) { const attributions = [attribution]; const source = new TileArcGISRest({ url, params, attributions, }); const layer = new TileLayer({ title, source, visible, ...
[ "addTileLayer() {\n L.tileLayer(MAP_TILES_URL, {\n maxZoom: 18,\n attribution: 'Maps &copy; <a href=\"https://www.thunderforest.com\">Thunderforest</a> | Data &copy; <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap contributors</a>'\n }).addTo(this.map);\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move ALL tiles downward
function moveTilesDown() { for (var column = 3; column >= 0; column--) { for (var row = 2; row >= 0; row--) { if (checkBelow(row, column) && tileArray[row][column] != null) { moveTileDown(row, column); } } } }
[ "function moveTilesDown() {\n var moved = false\n var captured = false\n for (var column = 0; column < grid_size; column++) {\n var row = grid_size\n while (row--) {\n if (grid_size - row > 1) {\n var ind = index(row,column)\n if (tiles[ind] != null) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is called when the value of the answer text box is updated
function onCurrentAnswerUpdated(event) { //Set the current answer to the text in the answer text box Session.set("currentAnswer", event.target.value.trim().toLowerCase()); //If the Enter key was pressed, the application will behave as if the Answer button was clicked if(event.keyCode === 13) { an...
[ "function updateQuestion() {\r\n let input = document.getElementById(\"AI_textbox\").value;\r\n if(input.trim() === \"\")\r\n return;\r\n myTextObject = new myText(input);\r\n myTextObject.findAnswer();\r\n}", "function updateAnswer(value) {\n storedAnswer = value;\n output.setID(\"lastAn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add time entry to a specific user inside a specific task.
async addTaskTimeEntry(input = { taskId: '0' }) { return await this.request({ name: 'task.time.add', args: [input.taskId], params: { 'time-entry': input['time-entry'] } }); }
[ "function addUserToTask(req, res, next){\n\n // Add the User ID and save...\n req.currentTask.users.push(req.currentUser._id);\n req.currentTask.save();\n\n // Create Log entry\n var newLog = new Log({\n parent: req.currentTask._id,\n user: req.user._id,\n created: {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a properly sorted mark set from null, a single mark, or an unsorted array of marks.
static setFrom(marks) { if (!marks || Array.isArray(marks) && marks.length == 0) return Mark.none; if (marks instanceof Mark) return [marks]; let copy2 = marks.slice(); copy2.sort((a, b) => a.type.rank - b.type.rank); return copy2; }
[ "ensureMarks(marks) {\n if (!Mark$1.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n this.setStoredMarks(marks);\n return this;\n }", "marks() {\n let parent = this.parent, index = this.index();\n if (parent.content.size == 0)\n return Mark$1.none;\n if (this.textOffse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set load language indicator
[consts.LANGS_LOADING_INDICATOR](state, val) { state.langsLoading = val; }
[ "function init_lang() {\n // if a language needs to load, the script is injected and loaded\n // first. once this loads, or doesn't, the initialization begins\n let lang = SETUP.ln ? SETUP.ln[0] : sdb.getItem('kiri-lang') || kiri.lang.get();\n // inject language script if not english\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print s string t times.
function printy(s, t) { for(var i=0, _s=""; i<t; i++) { _s += s; } return _s; }
[ "function echo(string, numTimes) {\n for (var i=0; i < numTimes; i++) {\n console.log(string + \" \" + i);\n }\n}", "trace(s) {\n if (typeof s === \"number\") {\n s = s.toString();\n }\n this.print(s, 0, 0, 12);\n }", "function echo(message, nbTimes) {\n for(va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that if the suggestion button is clicked, call ComputerPlays(true)
function suggestions(){ computerPlays(true); }
[ "function gamePlay() {\n questionSelection();\n }", "function goClicked () {\n // TODO: fill this out\n var userChoice= $(\"#mood\").val();\n searchTracks(userChoice);\n updateJumboTron(userChoice);\n}", "function playGame() {\n setComputerChoice();\n compare();\n}", "function clickFunc() {\n if (!...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the function that copys the converted sentence (to a clipboard)
function copySentence() { let convertedOutput = document.getElementById('convertedOutput') convertedOutput.select() convertedOutput.setSelectionRange(0, 99999) document.execCommand("copy"); console.log(convertedOutput.value) }
[ "function ClipBoard(){\n var copyText = document.getElementById(\"copytext\").innerText;\n document.getElementById(\"holdtext\").innerText = copyText;\n Copied = document.getElementById(\"holdtext\").createTextRange();\n Copied.execCommand(\"Copy\");\n}", "function copyToClipboard( text ){\n\tdocument...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Part 2: Make the unhideLightbox function run when a picture is clicked on. Calls unhideLightbox with the id of the first lightbox
function unhideLightbox1() { unhideLightbox("d1") }
[ "function unhideLightbox1() {\n\t// TODO: Look in q2.html to see what the id for the lightbox div for the first picture, and call unhideLightbox\n\tunhideLightbox(\"sam1\");\n}", "function unhideLightbox1() {\n\t// TODO: Look in q2.html to see what the id for the lightbox div for the first picture, and call unhid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Appends the current buffer into the blocks array and starts a new buffer.
closeAndStartNewBuffer_() { this.blocks_.push(new Uint8Array(this.currentBuffer_)); this.currentBuffer_ = []; }
[ "perform_forging(){\n let data = \"a new block\";\n let block = this.generateNextBlock(data);\n console.log('New block with hash: %s, current chain length: %d, generated by nodeId: %d', block.getHash().substr(0, 6),\n this.getChainLength(), this.node.id);\n this.addBlock(block...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
3. Write a recursive function to determine whether all digits of the number are odd or not.
function checkDigOdd(n) { if (n < 10) { if (n % 2 === 0) { return false; } return true; } return (checkDigOdd(n % 10) && checkDigOdd(Math.floor(n / 10))); }
[ "function areAllDigitsOdd2(n) {\r\n \r\n if(!( n % 2)) {\r\n return false;\r\n }\r\n \r\n let flag = false;\r\n \r\n if(Math.abs(n) < 10) {\r\n flag = true;\r\n }\r\n\r\n if(!flag) {\r\n return isAllDigitsOdd2( Math.floor(n / 10) );\r\n }\r\n \r\n return true...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if the stock passes all the A Tests
function allTests(stock, stockRangePctB, stockAwayPctB) { if (rangeTestB(stock, stockRangePctB) && betweenTestB(stock, stockAwayPctB)) { return true; } }
[ "function allTests(stock, stocksAlert, cfg) {\n if (volTestE(stock)) {\n return true;\n }\n }", "function allTests(stock, stocksAlert, cfg) {\n console.log(stock);\n if (priorDayCandle(stock)) {\n return true;\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setTimeout around node.focus, with some safety checks
function timeoutFocus(node) { window.setTimeout(function () { if (node && window.document.body.contains(node)) { node.focus(); } }); }
[ "_focusNode(node) {\n node.focus();\n }", "function focus_with_timeout(obj) {\n setTimeout(function() { obj.focus(); }, 50);\n }", "function focus(element){\n setTimeout(function(){ $(element).focus(); }, 200); \n }", "function focusNode(node) {\n if(focusedNode != node) { \n p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load configs for tasks
function loadConfigs() { grunt.file.expandMapping(settings.configs, '', { flatten: true, ext: '' }).forEach(function(configFile) { var config = {}; config[configFile.dest] = grunt.file.readJSON(configFile.src[0]); grunt.config.merge(config); }); }
[ "function loadTasks() {\n Entry.setContext(CONTEXT);\n var paths = (this.config.path instanceof Array ? this.config.path : [this.config.path]);\n var valid = 0,\n self = this;\n _.forEach(paths, function(sPath) {\n var taskDir = Component.appPath(sPath);\n try {\n var list = crux.util.readDirector...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes the next collection in the collections array. If we have finished processing all of the collections, it triggers the callback.
function processNextCollection() { if (i < collections.length) { var collection = collections[i]; i++; // Use myself as a callback. resetCollection(db, collection, processNextCollection); } else { cb(); } }
[ "function processNextCollection() {\n if (i < collections.length) {\n var collection = collections[i];\n i++;\n // Use myself as a callback.\n resetCollection(db, collection, processNextCollection);\n } else {\n addIndexes(db, cb);\n }\n }", "function next() {\n\t\tidx += 1;\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the date range display
function setDateRangeDisplay(start, end, selectedDateRangeLabel) { // Set the daterange display $(dateRangeId + ' span').html(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD')); // Save the start and end dates to check on the route to filter the model self.set('dateRangeStartD...
[ "function setRenderRangeText() {\n var renderRange = document.getElementById('renderRange');\n var options = cal.getOptions();\n var viewName = cal.getViewName();\n var html = [];\n if (\n viewName === 'month' &&\n (!options.month.visibleWeeksCount || options.month.visibleWeeksCount > 4)\n ) {\n html...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function Select Teamspeak Server
function teamspeakServerInit() { navigationInit("teamspeakServer", "web_teamspeak_server"); }
[ "function pickServer() {\n\tswitch(randomInt(0, 7)) {\n\t\tcase 0:\n\t\t\treturn 'wss://catbag.frankerfacez.com/';\n\t\tcase 1:\n\t\tcase 2:\n\t\t\treturn 'wss://andknuckles.frankerfacez.com/';\n\t\tcase 3:\n\t\tcase 4:\n\t\t\treturn 'wss://tuturu.frankerfacez.com/';\n\t\tcase 5:\n\t\tcase 6:\n\t\t\treturn 'wss://l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This func is async and updates the model every 5 second.
async __updateModels() { while (true) { this.__clientController.getAllModels(); await sleep(5000); } }
[ "setTimeInterval() {\n if (this.timeinterval) {\n return;\n }\n this.timeinterval = setInterval(() => {\n const currentTime = new Date();\n this.onModelUpdate(currentTime);\n }, 1000);\n }", "await() {\n this.model.await = true;\n }", "async fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sends post message to server with the data of the new recipe and dislpays green chekmark once pressed
function updateButton(){ var post = new XMLHttpRequest(); post.open("POST", "/recipes/"); var jsonRecipe = {"name": recipe.name, "duration": document.getElementById("duration").value, "ingredients": [document.getElementById("ingredients").value], "directions": [document.getElementById("direction...
[ "function saveRecipe(e) {\n\n // Get the identifier of the recipe to save in the db\n const spoonacular_id = e.target.id.split(\"-\")[1];\n\n const request = new XMLHttpRequest();\n request.open('POST', '/save_recipe');\n\n // Callback function for when request completes\n request.onload = () => {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback gets the current tabs info
function currentTabs(tabs) { var loc = tbr.localSession_; consoleDebugLog('Latest local tabs:\n' + tabsToString(tabs)); // Accept the new set of tabs loc.tabs = tabs; // Proceed with updated tabs in place. contFunc(); }
[ "function getTabInfo(callback) {\n var queryInfo = {\n active: true,\n currentWindow: true\n };\n\n chrome.tabs.query(queryInfo, function(tabs) {\n var tab = tabs[0];\n callback(tab);\n });\n}", "function getTabDetails() {\n\n}", "function getTabDetails(){\n\n}", "function getCurrentTabUrl(cal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getCoords is going to return either real coordinates, or fake ones if I'm computer
function getCoords() { // use real coords in the future // in the future use this -> navigator.geolocation.getCurrentPosition(function(geo) { }) return { latitude: '' + 33.501 + parseInt(Math.random() * 1000), longitude: '' + -82.51 + parseInt(Math.random() * 1000) } }
[ "function ensureRealPoint(coords){\n\tvar lat;\n\tvar lng\n\tif(coords[0] < -90){\n\t\t// We have wrapped around the south pole!\n\t\tlat = -90 + ( Math.abs( coords[0] ) - 90 )\n\t} else if(coords[0] > 90){\n\t\t// We have wrapped around the north pole!\n\t\tlat = 90 - (coords[0] - 90)\n\t} else {\n\t\tlat = coords...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: Get Currency ID Takes a currency abbreviation ('BTC', 'ETH', etc.) as a string Returns a promise that resolves with the currency ID from the currencies table in the database.
function getCurrencyID(currency) { return new Promise((resolve, reject) => { knex.select('currency_id').from('currencies').where({ currency_name: currency }).first() .then((data) => { let currencyID = data.currency_id; resolve(currencyID); }) .catch((err) => { reject(err); }); })...
[ "async function getCurrency(currencyName) {\n const c = requestConfig.Currencies[currencyName];\n if (typeof c === \"undefined\") return Promise.reject(ErrorUtil.errorWrap(requestErrors.CurrencyNotRegistered));\n return Promise.resolve(c)\n}", "function getCoinMarketCapId(cryptoName, cb) {\n var url =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Asynchronously load the DFP library. Calls ready event when fully loaded.
function loadLibrary() { if ( loaded ) { return onLibraryLoaded(); } var googletag, gads, useSSL, node, readyStateLoaded = false ; window.googletag = window.googletag || {}; window.googletag.cmd = window.googl...
[ "ready() {\n this.isReady = true;\n if (this.onLoad) {\n this.onLoad.call();\n }\n }", "async function documentReady() {\n if (document.readyState === 'loading') {\n await new Promise(function(resolve) {\n document.addEventListener('DOMContentLoaded', resolv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates new Pilet API extensions for supporting simplified data feed connections.
function createFeedsApi(config) { if (config === void 0) { config = {}; } return function (context) { context.defineActions(actions); context.dispatch(function (state) { return (tslib_1.__assign(tslib_1.__assign({}, state), { feeds: {} })); }); return function (_, target) { v...
[ "function DataApi() {}", "function DataApi() { }", "extend(data = {}) {\n let extended = new ResourceAdapterConfig(this);\n return Object.assign(extended, data);\n }", "function ApiDataAdapter() {\n \"use strict\";\n\n DataAdapter.call(this);\n}", "function StandardImportPmApi() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Giving Player and Dealer their initial Cards and score
function assignCards() { playerCards.push(playingDeck[0]); playerScore += getCardNumericValue(playingDeck[0]); document.getElementById('player-score').innerText = "Player Score: " + playerScore playerCardAdder(playingDeck[0].value, playingDeck[0].suit); playingDeck.shift(0); dealerCards.push(pl...
[ "getScoreCard(){\n this.playerScore.minValue = this.getTotalNormalCardValues(\"player\") + this.getMinACardsValue(\"player\");\n this.playerScore.maxValue = this.getTotalNormalCardValues(\"player\") + this.getMaxACardsValue(\"player\");\n this.delearScore.minValue = this.getTotalNormalCardVal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=========================================================================== Flux Data Class Constructor Fieldname : String, the name of the fieldname for this fluxdata values: [Array]. array of values, one for each year Source: string, this is the fieldname of the Fluc Source (Resource) Target: string, this is the fiel...
function FluxData(FieldName, values, Source, Target) { // The fieldname coming from web service foir this flux data this.Fieldname = FieldName; // The array of Values (should be an array) may be just a single value this.Values = values; // the Resource Fieldname this.Resource = Source; ...
[ "function FluxData(FieldName, values, Source, Target) {\n // The fieldname coming from web service foir this flux data\n this.Fieldname = FieldName;\n // The array of Values (should be an array) may be just a single value\n this.Values = values;\n // the Resource Fieldname\n this.Resource = Source...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Offsets into this.listing that could be used as targets for branches or jumps are represented as numeric Literal nodes. This representation has the amazingly convenient benefit of allowing the exact value of the location to be determined at any time, even after generating code that refers to the location.
function loc() { return t.numericLiteral(-1); } // Sets the exact value of the given location to the offset of the next
[ "function loc() {\n return t.numericLiteral(-1);\n} // Sets the exact value of the given location to the offset of the next", "function loc() {\n\t var lit = b.literal(-1);\n\t // A little hacky, but mark is as a location object so we can do\n\t // some quick checking later (see resolveEmptyJumps)\n\t lit._l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Task 2.18 Function ageSort(people) get array of object people with property age and sort this array by age property and output array.
function ageSort(){ return function(people){ people.sort(function(a,b){ return a.age - b.age; }); console.log(people); }; }
[ "function byAge(arr){\r\n return arr.sort((a, b) => a.age - b.age)\r\n }", "function byAge(arr){\n return arr.sort(function(a, b){\n return a.age - b.age;\n });\n}", "function sortByAge(arr) {\n arr.sort((a, b) => a.age > b.age ? 1 : -1);\n}", "sortPeopleBetter(arr) {\n return arr.sort((a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a function named navbarfunction, which expects to get data it will store inside the variable "language_data"
function navbarfunction(language_data) { /*Hides the OLD html code from navbar*/ /*$(document.getElementById('nav')).hide(); */ /*Creates an empty unsorted list (will add the navbar in here)*/ let ul_sv = $('<ul/>').attr('class', 'navbar-nav'); let ul_en = $('<ul/>').attr('class', 'navbar-nav'); ...
[ "function NavData() {\n }", "function makeLanguageMenu(data) {\n return `\n <div class=\"fields\" id=\"${data.id}\">\n <select name=\"select\">\n <option value=\"\">Select Language...</option>\n ${optionsList(data)};\n </select>\n </div>`;\n}", "function addNavbar(target) {\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when a user mouses over an agenda item
function myAgendaMouseoverHandler(eventObj){ var agendaId = eventObj.data.agendaId; var agendaItem = jfcalplugin.getAgendaItemById("#mycal",agendaId); //alert("You moused over agenda item " + agendaItem.title + " at location (X=" + eventObj.pageX + ", Y=" + eventObj.pageY + ")"); }
[ "function myAgendaMouseoverHandler(eventObj) {\n var agendaId = eventObj.data.agendaId;\n var agendaItem = jfcalplugin.getAgendaItemById(\"#mycal\", agendaId);\n //alert(\"You moused over agenda item \" + agendaItem.title + \" at location (X=\" + eventObj.pageX + \", Y=\" + eventObj.pageY + \")\");\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function for initialising the bct plugin
function iniBctWrappers(){ //find all bct wrappers on the screen and initialise them with the bct plugin $('.bct-wrapper').not('.initialised').each(function(){ bctInit(this); }); //add class to the body to indicate that we have initialised the bct plugin $('body').addClass('bct'); }
[ "pluginConstructor() {}", "function _init() {}", "initPlugins() {}", "function _init() {\n }", "function SamplePlugin(){}", "init() {\n\t\t\t// Should be implemented\n\t\t}", "function CharbaJsPluginHelper() {}", "function initPlugin() {\n initUI();\n\n// Setup logging using our handler\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Conditionally runs optional middleware or skips middleware
optional(condition, optionalMiddleware) { return this.use(getOptionalMiddleware(condition, optionalMiddleware)); }
[ "function myMiddleware2(config = {}) {\n return (req, res, next) => {\n // middleware logic\n if(config.foo) {\n // ...\n } else {\n // ...\n }\n // call the next middleware/route\n next();\n }\n}", "function maybeMiddleware() {\n // First, check if we are running tests inside the w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
warn that username is already taken
function userDuplicate() { $('.userwarn').html('Username already taken'); }
[ "function usernameAlreadyExists(username){\n return false;\n }", "function userDuplicate() {\n $(\".userwarn\").html(\" Username already taken\");\n}", "function usernameExists(user) {\n accounts[`${user.value}`] ? showError(user, 'Username already exists') : checks.usernameExists = true;\n}", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to build out HTML elements. Pass in the type of element to be created and an object literal of the attributes/values.
function buildElements(type,obj) { const element = document.createElement(type); for (let prop in obj) { element[prop] = obj[prop]; } return element; }
[ "function buildElement(tag, innerText, attributes){\n var newEl = document.createElement(tag);\n var newText = document.createTextNode(innerText);\n for (var i = 0; i < attributes.length; i++) {\n newEl[attributes[i][0]] = attributes[i][1]; \n };\n newEl.appendChild(newText);\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MODAL PLAY AGAIN FUNCTIONALITY
function playAgain(){ modal.classList.remove("show"); buildDeck(); }
[ "function replay(){\n toggleModal();\n restart();\n}", "function wantPlayAgain() {\n $('.fa-play-circle').on('click', function() {\n $modal.fadeOut();\n $('.restart').removeClass('invisible');\n playingGameAgain();\n console.log('....... ~ PLAY AGAIN! ~');\n });\n}", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
global window, document, isNumber Alignment.js Alignment Class Version 0.1
function Alignment(obj){ this.vertical = ('vertical' in obj) ? obj.vertical : 'top'; // top || center || bottom this.horizontal = ('horizontal' in obj) ? obj.horizontal : 'left'; // left || center || right this.registration = ('registration' in obj) ? obj.registration : 'inside'; // inside || fixed || outside. If ta...
[ "function addNumberAlignment(_this) {\n\tvar numberAlignment = _this.context.options.numberAlignment ? _this.context.options.numberAlignment.get(\"value\") : \"inherit\";\n\tif(numberAlignment == \"inherit\"){\n\t\tnumberAlignment = getInheritedProperty(_this,\"numberAlignment\") ? getInheritedProperty(_this,\"numb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a fetch favicon command to Background (when we are a private window) a_msg = an array ["", bnId, url, options.enableCookies]
function sendAddonMsgGetFavicon (a_msg) { browser.runtime.sendMessage( {source: "sidebar:"+myWindowId, content: "getFavicon", postMsg: a_msg } ).then(handleMsgResponse, handleMsgError); }
[ "function sendAddonMsgFavicon (bnId, uri) {\r\n browser.runtime.sendMessage(\r\n\t{source: \"background\",\r\n\t content: \"asyncFavicon\",\r\n\t bnId: bnId,\r\n\t uri: uri\r\n\t}\r\n ).then(handleMsgResponse, handleMsgError);\r\n}", "function menuRefreshFav (BN_id) {\n let BN = curBNList[BN_id];\n\n // Trigg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inform listeners that new time is selected.
function fireSelectedTimeChanged(time, listeners) { // Because time change is proposed from outside. // Also, make sure animation is updated accordingly. _currentTime = time instanceof Date ? time.getTime() : time; MyController.events.triggerEvent("timechanged", { ...
[ "timeSelection(e, time) {\n this.selectedTime = time;\n }", "_onSelectTime() {\n store.setTimeSelectedFlag(true);\n this._setYmdHis();\n }", "onChangeTime() {}", "setTime(time) {\n this._time = time\n this.notifyTimeChanged()\n }", "function selectNewTimestamp()\n{\n\tconso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rotates a point about the origin theta radians and returns the rotated point
function rotatePoint(point, theta) { var x = point[0] * Math.cos(theta) - point[1] * Math.sin(theta); var y = point[0] * Math.sin(theta) + point[1] * Math.cos(theta); return [x, y]; }
[ "Rotate(theta) {\n\t\tconst newX = (p.X * Math.cos(theta)) - (p.Y * Math.sin(theta))\n\t\tconst newY = (p.Y * Math.cos(theta)) + (p.X * Math.sin(theta))\n\t\treturn Point(newX, newY)\n\t}", "function rotatePoint(angle, p) {\n if (!angle) return;\n angle *= ParticleUtils.DEG_TO_RADS;\n var s = Math.sin(an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Randomly place the 3 possible door contents
function randomChoreDoorGenerator(){ doors = ['bot','beach','space']; //Randomizes the location inside the array for (let i=0;i<doors.length;i++){ y=Math.floor(Math.random()*doors.length); x=Math.floor(Math.random()*doors.length); temp = doors[x]; doors[x]=doors[y] do...
[ "function getRandomDoor (a,b) {\n\treturn a + Math.floor(Math.random() * (b - a + 1));\n}", "function initGame( ) {\n \tdoors = [ 'Goat' , 'Goat' , 'Goat'];\n\tvar carDoor = Math.ceil( Math.random( ) * 3 ); // 1 - 3 \n\tdoors[ carDoor - 1 ] = 'Car';\n}", "function RandomRoomSpot(room)\n{\n\n var FinalX = 0;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute a new timestamp from a previous one, regarding bi value
function computeTimestampFromBi(buffer, baseTimestamp, bi) { if (bi > BR_HUFF_MAX_INDEX_TABLE) { return buffer.getNextSample(ST_U32) } if (bi > 0) { return computeTimestampFromPositiveBi(buffer, baseTimestamp, bi) } return baseTimestamp }
[ "function computeTimestampFromPositiveBi(buffer, baseTimestamp, bi) {\n return buffer.getNextSample(ST_U32, bi) + baseTimestamp + Math.pow(2, bi) - 1\n}", "dateOrLastValueNew(ts) {\n const [mdate] = this.lastPoint();\n let t0 = (mdate.unix() < ts) ? mdate.unix() : ts;\n // let tminus1 = moment(t0).subtr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns authorized Account ID.
getAccountId() { return this._authData.accountId || ''; }
[ "async ClientAccountID(ctx) {\n // check contract options are already set first to execute the function\n await this.CheckInitialized(ctx);\n\n // Get ID of submitting client identity\n const clientAccountID = ctx.clientIdentity.getID();\n return clientAccountID;\n }", "async...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to set Conversation Data in Session
function SetValue(tConData) { $.ajax({ url : "/WebServices/SetConversationDataInSession", type : 'GET', async : false, data : { sConvData : tConData }, success : function(response) { } }); }
[ "function session_set(data, callback) {\n\tif(sessionid !== null && sessionid !== \"\") {\n\t\tsessionLiveData = \"\";\n\t\tsharedSessionLiveData = Date.now() + \"~\" + username + \"~\" + data;\n\t\t//var http = new XMLHttpRequest();\n\t\t//http.onreadystatechange = function() {\n\t\t//\tif (http.readyState == XMLH...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PROTECTED Allocates the network element's ports at the correct postions.
function allocateNePorts() { var topPortList = new List(); var leftPortList = new List(); var rightPortList = new List(); var bottomPortList = new List(); for (var i = 0; i < this.ports.getLength(); i++) { var port = this.ports.get(i); port.calculateCoords(); if (port.side == TOP) { topPortList.a...
[ "function createPorts() {\n\tlist = [\n\t//[isrc, jsrc, idest, jdest],\t\n\t\t[14, 79, 14, 00],\n\t\t[15, 79, 15, 00],\n\t\t[16, 79, 16, 00],\n\t\t[17, 79, 17, 00],\n\t\t[18, 79, 18, 00],\n\t];\n\treturn list;\n}", "function allocatePort(numberOfPortsAtSameSide, position) {\n\t\tvar n = eval(numberOfPortsAtSameSi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts num random words to the trie
randomTrie(num) { if (num > 993) num = 993 let allWords = words['words'] let upper = 0 let lower = num * 2 + 10 let elements = new Set() for (let i = 0; i < num; i++) { let value = Math.floor(Math.random() * (upper - lower + 1)) + lower while (elements.has(value) || value > 993) { value = ...
[ "insert(word) {\n let node = this;\n\n for (let i = 0; i < word.length; i++) {\n const letter = word[i];\n node.children[letter] = node.children[letter] || new TrieNode();\n node = node.children[letter];\n }\n\n // Mark the end of the word.\n node.word = word;\n }", "insert(word) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches for an area instance.
async findAreaByName(name, transaction) { let found = true; if (!this.instance) { found = await this.load(); } if (!found) { this.logger('error', `Location ${this.id} not found when trying to find an area.`); return null; } const { Area...
[ "function findPlaceInArea() {\n\t\tvar service = new google.maps.places.PlacesService(map);\n\t\tservice.nearbySearch({\n\t\t\tlocation: addressLatLng,\n\t\t\tradius: 400,\n\t\t\ttype: ['park']\n\t\t}, getPlaceArray);\n\t}", "function findAreaById(id) {\r\n for (var i = 0; i < $scope.areas.length; ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a new instance of Recipe
createRecipeObject() { this.recipe = new Recipe(); }
[ "function JAFTING_Recipe() { this.initialize(...arguments); }", "function makeFullRecipe(recipe) {\n const {\n id,\n title,\n readyInMinutes,\n aggregateLikes,\n vegetarian,\n vegan,\n glutenFree,\n image,\n servings,\n } = recipe;\n\n let arrInstruction = [];\n //check if instarcti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the available sports to the nav
renderSports() { return _.reduce(this.state.sports, (all, sport) => { const isActive = this.state.sport === sport.code.toLowerCase(); const title = App.Intl(`sport.name.${sport.code.toLowerCase()}`); if (!(sport.code.indexOf(' ') > -1)) { all.push( <li key={sport.code} className=...
[ "function activities_ShowSports(catName) {\n\t$('#msl-activities-content').html('');\n\t$.each(activities_SportList(catName), function(i, item) {\n\t\t$('#msl-activities-content').first().append(\n\t\t\tactivites_MakeSport(catName, item.name, activites_Left(item.desc, 70), item.logo, item.link)\n\t\t);\n\t});\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show delete account view
function showDeleteAccount(){ resetSettingsForms(); $('change_password_btn').removeClassName('selected'); // remove clicked effect from change password button $('change_password').hide(); // hide change password view $('delete_account_btn').addClassName('selected'); // add...
[ "function getDelete(req, res, next) {\n // do not handle the route when REST is active\n if (config.rest) return next();\n\n // custom or built-in view\n var view = cfg.views.remove || join('get-delete-account');\n\n res.render(view, {\n title: 'Delete account',\n basedir: req.app.get('view...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter out balance items that are zero
function filterNonZeroBalance(balances) { var filteredSymbols = Object.keys(balances).filter(function (symbol) { return balances[symbol].available !== "0.00000000" || balances[symbol].onOrder !== "0.00000000"; }); var filteredMap = {}; filteredSymbols.forEach(function (symbol) { filteredMap[symbol...
[ "removeZeroConsumptionCountries() {\n let vis = this;\n\n let filteredCountries = [];\n for (let country of vis.forceGraph.nodes) {\n if (vis.countryTotalConsumption.get(country.id) == 0) continue;\n filteredCountries.push(country);\n }\n vis.forceGraph.nodes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a deeplink to our documentation based on the user's OS and the Platform they're trying to build.
function doclink(section, path, hashOrOverrides) { const url = new URL('https://reactnative.dev/'); // Overrides const isObj = typeof hashOrOverrides === 'object'; const hash = isObj ? hashOrOverrides.hash : hashOrOverrides; const version = isObj && hashOrOverrides.version ? hashOrOverrides.version : _versio...
[ "_build_link(){\n\n\t\tconst link_data = [\n\t\t\tthis.opts.link_version,\n\t\t\tthis.opts.link_random_data,\n\t\t\tbtoa(this.names.flat().join(\"/\") + \"|\" + this.mapping.join(\"/\"))\n\t\t].join(\".\")\n\n\t\treturn `${this.opts.link_root}${link_data}`\n\t}", "function CreateFinderLink(deviceName){\n var f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements the list notifications rpc function
function list(call, callback) { winston.log('info', 'rpc method list request: ' + JSON.stringify(call.request)); if (!call.request.team || !call.request.username || !call.request.timeStamp) { _error('list', 'missing parameter', callback); } else { db.listNotifications(call.request.username, ...
[ "function listNotifications(params, cb) {\n\n params.resourcePath = config.addURIParams(constants.NOTIFICATIONS_BASE_PATH, params);\n params.method = 'GET';\n params.data = params.data || {};\n mbaasRequest.admin(params, cb);\n}", "NotificationsList() {\n return this.endpoint.get(this.path('/notificati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select a category and open the add/modify category modal
async editCategory(category) { this.setState({ selectedCategory: category, isOpenCategoryModal: true }); }
[ "function showEditCategoryForm(category) {\r\n\t$(\".edit-category-name\").val(category.categoryName);\r\n\t$(\".edit-category-id\").val(category.categoryId);\r\n\t$(\".edit-category-modal\").modal(\"open\");\r\n}", "async editCategory() {\n let list = document.getElementById(\"categorieslist\");\n let cate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" Output: ["mee","aqq"] / FUNC checkWord(word, pattern): FOR char in word: IF current and previous letter of pattern and current and previous of word does not match: RETURN false RETURN true FUNC (words, pattern): solutions = [] FOR word in words: edge...
function checkWord(word, pattern) { if (word.length === 1 && word === pattern) { return true; } if ( word[0] !== word[word.length - 1] && pattern[0] === pattern[word.length - 1] ) { return false; } if ( word[0] === word[word.length - 1] && pattern[0] !== pattern[word.length - 1] ...
[ "function wordPattern(pattern, str) {\n let strArray = str.split(' ');\n if (pattern.length !== strArray.length) {\n return false;\n }\n let patternObj = {};\n for (let idx = 0; idx < strArray.length; idx++) {\n if (!patternObj[pattern[idx]]) {\n if(Object.values(patternObj).includes(strArray[idx]))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process query args into Javascript object
function processQueryArgs(r) { var decodedQueryString = querystring.decode(r.variables.query_string); // For dash.js-cmcd version differences var cmcdKey; if (r.variables.query_string.includes('Common-Media-Client-Data')) cmcdKey = 'Common-Media-Client-Data'; else cmcdKey = 'CMCD'; var...
[ "function parseArgs() {\n var args = {};\n var query = document.location.search.substring(1);\n var pairs = query.split('&');\n for (var i = 0; i < pairs.length; i++) {\n pos = pairs[i].indexOf('=');\n if (pos == -1) continue;\n var argname = pair...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter : Adjust luminosity
function filter_luminosity(dict) { const l = dict['intensity'] || 1.2; return function (img) { const H = filter_getHSLChannel({ c: 'h' })(img); const S = filter_getHSLChannel({ c: 's' })(img); const L = filter_getHSLChannel({ c: 'l' })(img); const Lp = L.map((e, i) => (i % 4 === 3) ? 255 : Math.min(255, l ...
[ "function applyLoFi() \n{ \n var filter = 'contrast(1.4) brightness(0.9) sepia(0.05)';\n setFilter(filter);\n}", "static Luminosity(color, l) {\n if (l < 0)\n l = 0;\n if (l > 100)\n l = 100;\n color.l = l;\n return color;\n }", "function applyWalden(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the default attributes for an SVG element to be used as an icon.
_setSvgAttributes(svg, options) { svg.setAttribute('fit', ''); svg.setAttribute('height', '100%'); svg.setAttribute('width', '100%'); svg.setAttribute('preserveAspectRatio', 'xMidYMid meet'); svg.setAttribute('focusable', 'false'); // Disable IE11 default behavior to make SVGs fo...
[ "_loadDefaultSvgIcon() {\n if (!document.getElementById('tui-image-editor-svg-default-icons')) {\n const parser = new DOMParser();\n const dom = parser.parseFromString(icon, 'text/xml');\n\n document.body.appendChild(dom.documentElement);\n }\n }", "set icon(value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }