query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
BottomSheet class to apply bottomsheet behavior to an element
function BottomSheet(element, parent) { var deregister = $mdGesture.register(parent, 'drag', { horizontal: false }); parent.on('$md.dragstart', onDragStart) .on('$md.drag', onDrag) .on('$md.dragend', onDragEnd); return { element: element, cleanup: function cleanup() { ...
[ "function bottomSheet(thisTarget){\n eltar = document.querySelector('[data-bottomsheetid=' + thisTarget.getAttribute('data-bottomsheet') + ']');\n\n if(eltar !== null){\n bstarget = eltar.querySelector('.mat-bottomsheet');\n\n // prepend overlay\n var bsOverlayBack...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if deals are saved, show the text with the number of saved deals
function showSavedButton() { var numberSavedDeals = savedDealsArray.length; if (numberSavedDeals > 0) { revealSaved.style.display="block"; revealSaved.innerHTML= "View " + numberSavedDeals + " saved deals"; } else {revealSaved.style.display="none";} }
[ "function save(){\n saveEl.textContent += count + \" - \";\n count = 0;\n countEl.textContent = count;\n}", "function updaterecord(){\n $(\"#recordcount\").html( localStorage.getItem(\"recordcount\") );\n }", "function save() {\n console.log(Count + 1);\n let countResult = `${count}, `;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
on change of lead status if it is anything except arrived, then show the token element on change of lead status to Closing, then show the closing input select elements
function lstatusflip(value) { value === "" ? value = "Arrived" : null; value !== "Arrived" ? $('.modal-token-container').show() : ( $('.modal-token-container').hide(), $('#token-input').val('') ); value === "Not Arrived" ? ( $('.modal-token-container').hide(), ...
[ "function switchClosed() {\n\t$(\".theBox\").addClass(\"hidden\");\n\tvar status = $(\"#select1\").find(\":selected\").attr(\"data-net-status\");\n\t\n\tif ( status == 0 ) { \n\t\t$(\"#closelog\").val(\"Close Net\"); \n\t} else {\n\t\t$(\"#closelog\").val(\"Net Closed\");\n\t} \n}", "showWordTokenDialog()\n {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the scoped slots from `node` template children. Templates for default slots are processed as regular children in `processNode`.
function slotsToData (node, h, doc) { const data = {} const children = node.children || [] children.forEach((child) => { // Regular children and default templates are processed inside `processNode`. if (!isTemplate(child) || isDefaultTemplate(child)) { return } // Non-default templates are converted...
[ "function slotsToData(node,h,doc){const data={};const children=node.children||[];children.forEach(child=>{// Regular children and default templates are processed inside `processNode`.\nif(!isTemplate(child)||isDefaultTemplate(child)){return;}// Non-default templates are converted into slots.\ndata.scopedSlots=data....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
What mark should be next?
function getNewCurrentMark() { return currentMark === FIRST_PLAYER_MARK ? SECOND_PLAYER_MARK : FIRST_PLAYER_MARK; }
[ "function nextMark(ignore) {\n if (!ignore) ignore = {};\n for (var i = curIndex; i < marks.length; i++) {\n var mark = marks[i];\n if (mark.e === \"m\" || ignore[mark.e]) continue;\n return {i: i, m: mark};\n }\n return {i: marks.length, m: null};\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function for setting up the mortality slider, required by JQueryUI to attach handlers
function setMortalitySlider() { var handleA = $(".mortality-rate-slider.lower-handle"); var handleB = $(".mortality-rate-slider.upper-handle"); $('.mortality-slider').slider({ create: function (e, ui) { handleA.text(0); handleB.text(250); }, slide: function (...
[ "function setupSlider(){\n var handle = $( \"#custom-handle\" );\n $( \"#slider\" ).slider({\n max: 0,\n step: 5,\n min: -50,\n value: 0,\n range: \"max\",\n create: function() {\n handle.text( \"(-5,0)s\" );\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function makes the widget display whatever is inside the sensors array
function updateSensorWidgets(sensorArr){ for(var n = 0; n < sensorArr.length; n++){ for(var i = 0; i < sensorArr[n].triggers.length; i++){ updateThreshold(n,i,sensorArr[n].triggers[i].level); var res = document.getElementById('response' + n + '_' + i) res.value = String(sensorArr[n].triggers[i].response...
[ "function DisplaySensors( iType )\r\n{\r\n var iSensors = cSensor.GetCount( iType );\r\n\r\n for( var iSensor = 0; iSensor < iSensors; iSensor++ )\r\n {\r\n System.Console.WriteLine( \" {0} Sensor {1}:\", GetSensorType( iType ), iSensor );\r\n System.Console.WriteLine( \"\" );\r\n Sys...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if a rectangle intersects with this actor
intersects_rect(rect) { console.log("hitbox",hb_rect(this,0)); console.log("rectpos",rect[0]); if ((hb_rect(rect,0) >= hb_rect(this,0) && hb_rect(rect,0) <= hb_rect(this,2)) || (hb_rect(rect,2) >= hb_rect(this,0) && hb_rect(rect,2) <= hb_rect(this,2))) { ...
[ "intersects(rect) {\n return this.x <= rect.x + rect.width && rect.x <= this.x + this.width && this.y <= rect.y + rect.height && rect.y <= this.y + this.height;\n }", "intersects(otherRectangle: _Rectangle): boolean {\n return !(\n this.right < otherRectangle.left ||\n this.bottom < otherRectangl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable the submit inputs in a given form
function enableSubmitButtons(form) { form.find('input[type="submit"]').removeAttr('disabled'); form.find('button[type="submit"]').removeAttr('disabled'); }
[ "enable () {\n var els = this.formEls,\n i,\n submitButton = this.getSubmitButtonInstance();\n this.setPropertyAll('disabled', false);\n // remove disabled css classes\n for (i = 0; i < els.length; i++) {\n els[i].classList.remove('disabled');\n }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverses all .tiles > img in the DOM and checks for a duplicate of nextImage in their src attribute
function checkForDuplicate(nextImage){ var duplicate = false; $(tileArticle + '.randomize > img').map(function (index) { if (nextImage == $(this).attr('src')) { duplicate = true; } }); return (duplicate === true ? true : false); }
[ "function checkNextImg(direction, addrs){\n console.log(currentImg)\n if (imgs[currentImg + 1]) {\n currentImg++\n addrs.src = imgs[currentImg]\n getExif()\n }\n}", "nonTiledImagedMatch(prevNonTiledImages) {\n const { nonTiledImages } = this.props;\n if (nonTiledImages.length =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
closes the desktop search classes
function closeDesktopSearch() { document.getElementsByClassName('search-form-desktop')[0].setAttribute('class', 'search-form'); document.getElementsByClassName('search-form-icon-desktop-active')[0].style.cssText = 'display: none;'; document.getElementsByClassName('search-form-icon-desktop')[0].style.cssText = 'di...
[ "function tycheesCommon_openSearchWindow() {\n\tsea001_mw000_show();\n}", "function close_adv_search(){ \n}", "closeSearchResults() {\n this._removeAllSearchResults();\n this.inputElement.setValue('');\n this.searchResults.removeClass('open');\n setTimeout(function() {\n this.searchResults.hid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for nodes by making all unmatched nodes temporarily transparent.
function searchNodes() { var term = document.getElementById('searchTerm').value; var selected = container.selectAll('.node').filter(function (d, i) { return d.name.toLowerCase().search(term.toLowerCase()) == -1; }); selected.style('opacity', '0'); var link = container.selectAll('.link'); link.style('stroke-opac...
[ "function _highlightNeighbors(/*nodes*/)\r\n{\r\n\t/*\r\n\tif (nodes == null)\r\n\t{\r\n\t\tnodes = _vis.selected(\"nodes\");\r\n\t}\r\n\t*/\r\n\t\r\n\tvar nodes = _vis.selected(\"nodes\");\r\n\t\r\n\tif (nodes != null && nodes.length > 0)\r\n\t{\r\n\t\tvar fn = _vis.firstNeighbors(nodes, true);\r\n\t\tvar neighbor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a list of all available formats for a given timeframe.
async fetchFormats(timeframe, useMonotype = false) { const urlBuilder = this.createUrlBuilder(); urlBuilder.setTimeframe(timeframe); if (useMonotype) { urlBuilder.setSubPath("monotype" /* MONOTYPE */); } const url = urlBuilder.build(); return formats_1.parseFo...
[ "function allFormats() {\n return formats;\n}", "function loadStageFormatList() {\n\tLookup.all({where: {'lookup_type':'STAGE_FORMAT'}}, function(err, lookups){\n\t this.stage_format_list = lookups;\n\t next(); // process the next tick. If you don't put it here, it will stuck at this point.\n\t}.bind(this));\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets access token from Spotify using authorization code.
function fetchAccessToken(code) { let body = "grant_type=authorization_code"; body += "&code=" + code; body += "&redirect_uri=" + encodeURI(redirectUri); body += "&client_id=" + clientId; body += "&client_secret=" + clientSec; callAuthorizationApi(body); }
[ "getAccessToken() {}", "function getAuthorizationCode(){\r\n\t\t\r\n\t\t// save current URL, before we redirect\r\n\t\tlocalStorage.returnURL = window.location.href;\r\n\t\t\r\n\t\tvar newURL = '';\r\n\t\tnewURL += 'https://accounts.spotify.com/authorize?client_id='+$localStorage.Spotify.ClientID;\r\n\t\tnewURL +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns if a seat is both valid and free.
isSeatFree(row, column) { // Check if the seat is valid, then if it is set to reservationType.NONE return (this.isSeatValid(row, column) && this.allSeats[row-1][column-1] === reservationType.NONE); }
[ "isSeatValid(row, column)\n {\n // Check if the row is invalid, then if the column is invalid\n return (this.allSeats[row-1] != reservationType.INVALID && this.allSeats[row-1][column-1] != reservationType.INVALID);\n }", "canBuyFromReserve(){\n for(let i=0; i<this.reservedCards.length; i++){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize UI for vacation reply form.
function initReplyForm() { gui.rubik_reply_filename = $("#message-form input[name=reply-filename]"); gui.rubik_reply_text = $("#message-form textarea[name=reply-text]"); // fill edit data if any if ('rubik_reply' in env) { const reply = env.rubik_reply; gui.rubi...
[ "function initVacationForm() {\n gui.vacation_start = $(\"#vacation-form input[name=date-start]\");\n gui.vacation_end = $(\"#vacation-form input[name=date-end]\");\n gui.vacation_name = $(\"#vacation-form input[name=vacation-name]\");\n gui.vacation_selected_reply = $(\"#vacation-form s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decide how to format data labels based on the attribute.
function formatDataLabel(attr, val) { switch (attr) { case "population": return (val / 1000).toLocaleString("en-US") + "K"; case "illiteracy": default: return val + "%"; } }
[ "get labelFormat() {\n return this._label;\n }", "function ApexDataLabels() { }", "get labelFormat() {\n return this.i.d9;\n }", "function setLabel(props){\r\n \r\n var tempLabelName;\r\n var tempValue = props[expressed];\r\n \r\n if (expressed == attributeArr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the reminder dictionary
static getRemindersDict(reminderArray) { //var reminderArray = getReminders(dir); var dict = {}; var reminder; for(var i = 0; i < reminderArray.length; i++) { reminder = reminderArray[i]; if(reminder.date in dict) dict[reminder.date].push(reminder); else dict[reminder.date] = [reminder]; } retur...
[ "function getEventReminder() {\n createEventLogic.getEventReminder().then(function (response) {\n //appLogger.log(\"reminders\" + JSON.stringify(response));\n $scope.eventReminders = response;\n }, function (err) {\n appLogger.error('ERR', err);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
League object used to modelize the league infos.
function League() {}
[ "async function getLeagueDetails() {\r\n const league = (await axios.get(\r\n `${api_domain}/leagues/${LEAGUE_ID}`, {\r\n params: {\r\n include: \"season\",\r\n api_token: process.env.api_token,\r\n },\r\n }\r\n )).data.data;\r\n // In case ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Delete Datasource API
deleteSource () { console.log(this.state.delIndex) const id = this.props.datasources[this.state.delIndex].id console.log(id) postData(`/jobs/delete/${id}`).then(function (json) { console.log(json) this.deleteSuccessfully() }.bind(this), function (error) { console.error('error', err...
[ "function deleteSource() {\n\tds.source.delete({\n\t\t\t\"id\": sourceDetails.id\n\t\t}, function(err, response) {\n\t\t\tif (err) \n\t\t\t\tconsole.log(err);\n\t\t\telse\n\t\t\t{\n\t\t\t\tconsole.log(\"Source deleted.\");\n\t\t\t}\n\t\t});\n}", "remove() {\n if (!this.group) {\n throw new Error('Missing ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Measurement can be split in two steps, the setup work that applies to the whole line, and the measurement of the actual character. Functions like coordsChar, that need to do a lot of measurements in a row, can thus ensure that the setup work is only done once.
function prepareMeasureForLine(cm, line) { var lineN = lineNo(line); var view = findViewForLine(cm, lineN); if (view && !view.text) { view = null; } else if (view && view.changes) { updateLineForChanges(cm, view, lineN, getDimensions(cm)); cm.curOp.forceUpdate = true; ...
[ "function prepareMeasureForLine(cm, line) { // 1683\n var lineN = lineNo(line); // 1684\n var view = findViewForLine(cm, lineN); ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts ref to reactive.
function toReactive(objectRef) { if (!(0,vue__WEBPACK_IMPORTED_MODULE_0__.isRef)(objectRef)) return (0,vue__WEBPACK_IMPORTED_MODULE_0__.reactive)(objectRef); var proxy = new Proxy({}, { get: function get(_, p, receiver) { return Reflect.get(objectRef.value, p, receiver); }, set: function set(_, p,...
[ "reactive(value) {\n return createReactiveProperty(value);\n }", "get ref() { return this._ref; }", "function ref() {\n }", "function shallowReactive(target){return createReactiveObject(target,false,shallowReactiveHandlers,shallowCollectionHandlers,shallowReactiveMap);}", "ref() {\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redondea temperatura y solo permite un decimal.
redondearTemp(temp) { return Math.round(temp * 10) / 10; }
[ "function redondeo(numero, decimales)\n{\nvar flotante = parseFloat(numero);\nvar resultado = Math.round(flotante*Math.pow(10,decimales))/Math.pow(10,decimales);\nreturn resultado;\n}", "function peso_p_mulher(paciente){\n\t return parseFloat(45.5 + 0.91 * (paciente.altura -152.4));\n\t}", "function tempNoDec ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the labels for the xaxis and yaxis
createLabels(x_label, y_label) { let oldText = this.texts.selectAll('text'); oldText.remove(); this.texts.append('text') .attr('x', this.offset.x + this.cell_size * this.numCols / 2 - this.cell_size) .attr('y', this.offset.y + (this.cell_size * this.numRows) + this.cell_size) .attr('font-family', '...
[ "function buildAxisLabels() {\n\t\t\tg_pc1Label = \"Axis \"+xAxisIndex\n\t\t\tg_pc2Label = \"Axis \"+yAxisIndex\n\t\t\tg_pc3Label = \"Axis \"+zAxisIndex\n\n\t\t\t//build axis labels\n\t\t\tvar axislabelhtml = \"\";\n\t\t\tvar xcoords = toScreenXY(new THREE.Vector3(g_xMaximumValue, g_yMinimumValue, g_zMinimumValue),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the various light SVG object with the 6 arcs Followed guidance provided here
function initLights() { var lightsgaragearc1 = document.getElementById('lights-garage-outside-arc-1'); lightsgaragearc1.setAttribute("d", describeArc(170, 724, 7, 135, 225)); var lightsgaragearc2 = document.getElementById('lights-garage-outside-arc-2'); lightsgaragearc2.setAttribute("d", describeArc(170...
[ "initLights() {\n\n // Array for lights' UI\n this.lightSwitches = [];\n\n // Setup lights with XML values\n this.graph.lights.forEach((value, key) => {\n var light = value;\n var i = light[0];\n\n this.lights[i].setPosition(light[3][0], light[3][1], ligh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PVector v; String command;
constructor(command, v) { this.v = v; this.command = command; }
[ "PP(point1, point2){\n let vec = new Vector(point1, point2)\n this.PV(point1, vec)\n }", "function printVector(v)\n{\n console.log(v.x + \", \" + v.y + \", \" + v.z)\n}", "constructor(p,s,t){\n if(arguments.length == 2) {\n this.pos=new Vector(s);\n \n this.size=new Vector(p.size);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the active stack ID. In the context of iontabs, it means the active tab.
getActiveStackId() { return this.stackCtrl.getActiveStackId(); }
[ "function getCurrentTabButtonId() {\n return $('#navbar .current').attr('id');\n }", "get stackId() {\n return this.getStringAttribute('stack_id');\n }", "function get_current_tab_hash()\n {\n\tvar as = $(\"ul#class-dropdown a.active\");\n\tif (as.length == 1)\n\t{\n\t return as[0].hash;\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_sh_switch_workspace_tween_completed: void When animation during switching workspace done, removes tweens from it.
function _sh_switch_workspace_tween_completed( ){ Tweener.removeTweens( this ); }
[ "function undoAnimationDone() {\n isUndoing = false;\n tiles.splice(tiles.length - 1, 1);\n removeNode(tilesContainer.lastElementChild);\n updateTileVisibility(numTilesShown);\n lastBlacklistedTile.elem.removeEventListener(\n 'webkitTransitionEnd', undoAnimationDone);\n}", "finishAnimation() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getPolicy Get list of policies and update the content of the list
function updatePolicyList(data) { var i = 0, m = 0, pol = null, that = $('select[name=todPolicy]'), newPolicies = data.data; that.find('option').remove(); // clean the list for (m = newPolicies.length; i < m; i += 1) { pol = newPolicies[i]; that.append($('<option>').val(pol.id).attr('s...
[ "function fetchPolicyList() {\n const request = lookup('service:request');\n return request.promiseRequest({\n modelName: 'policy',\n method: 'fetchPolicyList',\n query: {}\n });\n}", "getSubscritionPolicyList() {\n return this.client.then((client) => {\n return client.apis['Subscrip...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens a sidebar in the sheet containing the addon's user interface for configuring the notifications this addon will produce.
function showConfigurationSidebar() { var ui = HtmlService.createHtmlOutputFromFile('ConfigurationSidebar') .setTitle('Add-on configuration'); SpreadsheetApp.getUi().showSidebar(ui); }
[ "function onOpen(e) {\n SpreadsheetApp.getUi().createAddonMenu()\n .addItem('Start', 'showSidebar')\n .addToUi();\n}", "function onOpen(e) {\n SpreadsheetApp.getUi().createAddonMenu().addItem('Start', 'showSidebar').addToUi();\n}", "function showSidebar() {\n var ui = HtmlService.createHtmlOu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get current tab with promise, because getSelected was too logical in Chromeland
function getCurrentTab () { return new Promise((resolve, reject) => { chrome.tabs.query({active: true, currentWindow: true}, tabs => { let tab = tabs[0]; if (!tab || typeof tab.id === 'undefined' || (tab.url || '').startsWith('chrome://')) { reject('notAllowed'); } resolve(tab); ...
[ "function getCurrentTabPromise() {\n\n return new Promise(function (resolve, reject) {\n\n var currentTabQuery = {\n \"active\": true,\n \"currentWindow\": true\n };\n chrome.tabs.query(currentTabQuery, function (tab) {\n\n if (tab.length !== 1) {\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
displays a line from the journal at a time.
function writeLine() { var log = journal.shift(); if (!log) { return; } var line = log.entry; // use a buffer for the 'scroll' effect if (5 === displayBuffer.length) { displayBuffer.shift(); } displayBuffer.push(line); // render the buffer c.font = '36px Papyrus, fantasy'; ...
[ "function render() {\n var log = journal.shift();\n if (!log) { return; }\n\n c.font = '36px Papyrus, fantasy';\n c.fillStyle = '#001f3f';\n c.fillRect(0, 0, a.width, a.height);\n c.fillStyle = '#01FF70'\n\n // use a buffer for the 'scroll' effect\n displayBuffer.shift();\n displayBuffer....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if mouse is over a resize handle (virtual). If so, highlight.
checkResizeHandles(event) { const me = this, target = me.targetSelector ? DomHelper.up(event.target, me.targetSelector) : event.target; // mouse over a target element and allowed to resize? if (target && (!me.allowResize || me.allowResize(event.target, event))) { me.currentElement = me.handleCo...
[ "checkResizeHandles(event) {\n const me = this,\n target = me.targetSelector ? DomHelper.up(event.target, me.targetSelector) : event.target; // mouse over a target element and allowed to resize?\n\n if (target && (!me.allowResize || me.allowResize(event.target, event))) {\n me.currentElement = m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the htmlEntities randomly
function getRandomHtmlEntities(len){ var htmlEntitiesCodes = [38, 39, 169, 174]; // [ & ' &copy; &reg;] // define a list of all supported html entities, maybe the list of code values return getRandomCharsFromCodes(len, htmlEntitiesCodes); }
[ "function randHTMLEnt(len) {\n var str = '';\n for (var i = 0; i < len; i++) {\n str += '&#' + rand(256) + ';';\n }\n return str;\n}", "function randomHtml() {\n return lorem.ipsum(\"lorem_p10\");\n}", "function randomSpecialCharacters(){\n var specialCharacter = \"!#$%&'()*+,-./:;<=>?@...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
File: ThreeJsScene.js Copyright (c) 2013 VoodooJs Authors The ThreeJs scene graph where objects may be added or removed.
function ThreeJsScene_() { log_.information_('Creating ThreeJs Scene'); this.scene_ = new THREE.Scene(); }
[ "function Scene() {\n\tObject3D.call( this );\n\n}", "function Scene() {}", "function ThreeJsSceneFactory_() {\n log_.info_('Creating ThreeJs Scene Factory');\n\n this.scene_ = new THREE.Scene();\n}", "addToScene(scene) {\n this.mScene = scene;\n // There is no default mObject3D\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maptimize.Proxy.GoogleMapremoveEventListener(handle) > undefined handle (Object): handle get by addEventListener. Removes a handler that was installed by addEventListener.
function removeEventListener(handle) { GEvent.removeListener(handle); }
[ "function xRemoveEventListener(e,eT,eL,cap)\r\n{\r\n if(!(e=xGetElementById(e)))return;\r\n eT=eT.toLowerCase();\r\n if(e.removeEventListener)e.removeEventListener(eT,eL,cap||false);\r\n else if(e.detachEvent)e.detachEvent('on'+eT,eL);\r\n else e['on'+eT]=null;\r\n}", "_unsubscribe(eventType, eventHandler) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
listen for submit bookmark
function handleSubmitBookmark() { $('main').on('submit', '#add-bookmark-form', (e) => { e.preventDefault(); const formData = new FormData(e.target); let newBookmark = serializeJson(formData); api.addBookmark(newBookmark) .then((res) => { res.json().then(data => { ...
[ "function handleNewBookmarkSubmit() {\n $('#js-add-bookmark-form').submit(function(event) {\n event.preventDefault();\n\n //use my JQuery extended function from above to create an object w/ correct format\n const newBookmarkData = $(event.target).serializeJson();\n\n //run create bookmark fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
curve recorder to store coordinates
function CurveRecorder() { this.recorder = []; var capacity = 1000; var frame; // begin a new recording frame this.beginRecord = function() { frame = []; }; // add a new point to the current frame this.addPoint = function(pt, track) { track = track || 0; frame[track] = pt; }; // end ...
[ "function savePoint () {\n if (t > 150) return; // Abbruch, falls Punkt außerhalb des Diagramms\n var n = xyDiagram.length; // Bisherige Zahl der Messwertpaare \n xyDiagram[n] = { // Neues Messwertpaar\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete the keyvalue pair with the maximum key rooted at h
function deleteMax(h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null || h.right == undefined) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); ...
[ "remove(key) {\r\n const hash = this.calculateHash(key);\r\n if(this.values.hasOwnProperty(hash) && this.values[hash].hasOwnProperty(key)) {\r\n delete this.values[hash][key];\r\n this.numberOfValues--;\r\n }\r\n }", "remove(key) {\n if(this.storage.length === 0) return undefined;\n let ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import an existing Application Load Balancer
static fromApplicationLoadBalancerAttributes(scope, id, attrs) { try { jsiiDeprecationWarnings.aws_cdk_lib_aws_elasticloadbalancingv2_ApplicationLoadBalancerAttributes(attrs); } catch (error) { if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") { ...
[ "attachToClassicLB(loadBalancer) {\n this.loadBalancerNames.push(loadBalancer.loadBalancerName);\n }", "attachToClassicLB(loadBalancer) {\n if (this.taskDefinition.networkMode === task_definition_1.NetworkMode.Bridge) {\n throw new Error(\"Cannot use a Classic Load Balancer if NetworkM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getTestFiles. If no functions provided, returns all files
function getFilePaths(funcs) { return new BbPromise(function(resolve, reject) { var paths = []; if (funcs && (funcs.length > 0)) { funcs.forEach(function(val, idx) { paths.push(testFilePath(val)); }); return resolve(paths); } // No...
[ "function getTestFiles() {\n let f = null\n if (f = fs.readdirSync('test/')) {\n return f.length == 0 ? null : f\n }\n}", "function getTestFiles(args, options) {\n\n // default files to ./**/*.{feature,js,coffee}\n var files = [];\n args = args.length > 0 ? args : ['.'];\n args.forEach...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================ StereoAudioRecorderHelper.js source code from:
function StereoAudioRecorderHelper(mediaStream, root) { // variables var deviceSampleRate = 44100; // range: 22050 to 96000 if (!ObjectStore.AudioContextConstructor) { ObjectStore.AudioContextConstructor = new ObjectStore.AudioContext(); } // check device sample rate deviceSampleR...
[ "function StereoAudioRecorderHelper(mediaStream, root) {\n\n // variables \n var deviceSampleRate = 44100; // range: 22050 to 96000\n\n if (!ObjectStore.AudioContextConstructor) {\n ObjectStore.AudioContextConstructor = new ObjectStore.AudioContext();\n }\n\n // chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HTML number encode (&number_entity;)
function htmlNumberEncode(input) { var i = 0; var c = 0; var string = ""; for (i = 0; i < input.length; i++) { c = input.charCodeAt(i); string += "&#" + c + ";"; } return string; }
[ "function decimalToSymbol(htmlEntity) {\n var dec = htmlEntity.replace(/[&#;]/g, '');\n if (!(/^[0-9]+$/).test(dec) || (dec >= 0xD800 && dec <= 0xDFFF) || dec > 0x10FFFF) { // Invalid input\n return htmlEntity;\n }\n\n var res = '';\n if (dec > 0xFFFF) {\n de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make it work with hover over td not img Baljinder Benipal Creates a hover effect with each of the profile pictures for the About page
function hover(element) { // Stores the id corresponding to which member is hovered over var childElement = element.firstChild; // Changes image source depending on 'name' to display appropriate executive childElement.setAttribute('src', 'wolfpackExecutives/' + childElement + '.jpg'); // Sets border-radius to...
[ "function personHoverImage(){\n\n\t\tvar $elem = $('.csc-slideOutContent .csc-header');\n\t\tvar $personPic = $('.csc-slideOutContent .csc-default .csc-textpic-imagewrap');\n\n\t\t$elem.hover(function(){\n\t\t\t$(this).parent().find($personPic).stop().fadeIn();\n\t\t}, function(){\n\t\t\t$(this).parent().find($pers...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function madeFirst to begain showing call stack
function madeFirst() { //will print 'This is the start' console.log('This is the start, in madeFirst'); //calling madeSecond before it is made madeSecond(); // will print 'This is second and in madeFirst' console.log('This is second and in madeFirst'); }
[ "function first_frame(env) {\n return head(env);\n}", "_showPrevStack() {\n const stacks = Array.from(this._idToStack.values());\n\n let nextIndex = stacks.indexOf(this._visibleStack) - 1;\n\n if (!stacks[nextIndex]) {\n nextIndex = stacks.length - 1;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a function that takes three arguments prob, prize, pay and returns true if prob prize > pay; otherwise return false.
function profitableGamble(prob, prize, pay) { if (prob * prize > pay) { return true; } return false; }
[ "function prob(prob, prize, pay) {\n value = prob * prize;\n if (value > pay) {\n console.log(true);\n } else {\n console.log(false);\n }\n}", "function profitableGamble(prob, prize, pay) \r\n{\r\n if((prob*prize) > pay)\r\n {\r\n return true;\r\n }\r\n else{\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fitting words Build a function that takes in a string and an array of strings. The function should output an array of strings that contain the same letters as the single input string. Write a function that takes two parameters Parameter 1 A string Parameter 2 An array of strings The function should output all the words...
function fittingWords(str,myArray){ return myArray.filter(arrayStr => { for(let i = 0; i < str.length; i++){ if(arrayStr.indexOf(str[i]) === -1){ return false; } } return true; }) }
[ "function fittingWords(string, array) {\n var letterArray = string.split('');\n var wordArray = [];\n for (var outer = 0; outer < array.length; outer++) {\n var counter = 0;\n for (var inner = 0; inner < array.length; inner++) {\n if (array[outer].includes(letterArray[inner])){\n counter++;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to send notification to clients. for name changes, data is the listId and data2 is the name, for items data is itemId and data2 is listId.
function _notifyConnectedClientsTwoParts(type, data, data2) { let message = { type, data, data2 }; console.log(JSON.stringify(message)); connection.invoke("SendMessageToAllAsync", JSON.stringify(message)) .catch(function (err) { return console.erro...
[ "function updateNotification(data){\n \n if(data.notification[0]['new'].length)\n {\n //console.log(' send notification receive status to server',data);\n data.action_flag = 'update';\n data.submitted = 1;\n delete data.initial_flag;\n socket...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the current visibility for each feature type in the Spots Feature Layer
function setCurrentTypeVisibility(map) { map.getLayers().forEach(function (layer) { if (layer.get('name') === 'featureLayer') { layer.getLayers().forEach(function (typeLayer) { var type = typeLayer.get('title').split(' (')[0]; typeVisibility[type] = typeLayer.get('visible...
[ "function saveLayerVisibility(layer) {\n const title = layer.get('title');\n if (title) {\n const itemName = `farmOS.map.layers.${title}.visible`;\n const visible = JSON.stringify(layer.get('visible'));\n localStorage.setItem(itemName, visible);\n }\n}", "function updateLayerVisibility(){\n visi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears the stored bounds information which was used for the initial display of a specific result.
function clearBounds() { latlngBounds = new google.maps.LatLngBounds(); }
[ "clearCurrentBounds() {\n this._currentBoundsLabel.innerText = \"None\";\n this._currentBoundsGoTo.disabled = true;\n this._currentBoundsUpdate.disabled = true;\n this._currentBoundsReset.disabled = true;\n }", "clearDefaultBounds() {\n this._defaultBoundsLabel.innerText = \"None\";...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2D Point Generation Functions // generates the position points for the bezier curves
function generateBezierCurve() { //create the position matrix, from the current position of the control points var controlP1 = mat4(positions[0],positions[2],positions[4],positions[6], positions[1],positions[3],positions[5],positions[7], 1,1,1,1, 1,1,1...
[ "function bezierPoints(connector,startPoint,point1,point2,endPoint,i,max){var pt={x:0,y:0};var t=i/max;var x=(1-t)*(1-t)*(1-t)*startPoint.x+3*t*(1-t)*(1-t)*point1.x+3*t*t*(1-t)*point2.x+t*t*t*endPoint.x;pt.x=x;var y=(1-t)*(1-t)*(1-t)*startPoint.y+3*t*(1-t)*(1-t)*point1.y+3*t*t*(1-t)*point2.y+t*t*t*endPoint.y;pt.y=y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Similar to Array.prototype.reduce(), however the reducing callback may return a Promise, in which case reduction will continue after each promise resolves. If the callback does not return a Promise, then this function will also not return a Promise.
function promiseReduce(values, callback, initialValue) { return values.reduce(function (previous, value) { return (0, _isPromise.default)(previous) ? previous.then(function (resolved) { return callback(resolved, value); }) : callback(previous, value); }, initialValue); }
[ "function promiseReduce(values, callbackFn, initialValue) {\n let accumulator = initialValue;\n for (const value of values) {\n accumulator = (0, _isPromise.isPromise)(accumulator) ? accumulator.then(resolved => callbackFn(resolved, value)) : callbackFn(accumulator, value);\n }\n return accumulator;\n}", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup routes for the application
setupRoutes() { let expressRouter = express.Router(); for (let route of this.router) { let methods; let middleware; if (typeof route[1] === 'string') { methods = route[1].toLowerCase().split(','); middleware = route.slice(2); } else { methods = ['get']; m...
[ "static setupRoutes() {\n // this is a route. the asterisk denotes that the route applies to \n // all incoming path requests.\n //\n // *** IMPORTANT ***\n //\n // it's very *important* the order in which routes are added, since \n // an incoming request will be ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function : translator_translateDirective Purpose : apply translation rules to the specified directive
function translator_translateDirective(code, offset, part, type, openTag, closeTag, attributes, display, lockAttributes) { offset += this.offsetAdj; // begin for stored procedures if (part == "script") { if (type.length == 0 && openTag.length == 0 && closeTag.length == 0 && attributes.length==0 && ...
[ "translate (...params) {\n return this._getInstance().translate(...params)\n }", "function wlTranslateMe($filter) {\n return {\n restrict: \"A\",\n transclude: false,\n link: function(scope, element, attrs) {\n var originalText = element.text();\n var newText = $f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initXuaEvent This function adds XUA methods and properties to event objects. Prototype: Event initXuaEvent(Event e) Arguments: e ... The event object that will be initialized Results: The initialized event object.
function initXuaEvent(e) { if (! e) return null; e.src = null; e.pos = null; e.btn = null; // Let e.src be the literal target of event e. if (ie) { e.src = e.srcElement; } else { // XXX Perhaps we should recursively look up the hierarchy for a parent // with nodeType 1. if (...
[ "function eObj(e) {\r\n return initXuaEvent(ie && e == null ? self.event : e);\r\n}", "function EventInit() {}", "function xAddEventListener2(e,eT,eL,cap) // original implementation\r\n{\r\n if(!(e=xGetElementById(e))) return;\r\n eT=eT.toLowerCase();\r\n if (e==window && !e.opera && !document.all) { // sim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds all direct and indirect child fields of `node` with the given field name.
function findDescendantFields(rootNode, fieldName) { var fields = []; function traverse(node) { if (node instanceof __webpack_require__(213).Field) { if (node.getSchemaName() === fieldName) { fields.push(node); return; } } if (node === rootNode || node instanceof __w...
[ "function findDescendantFields(rootNode, fieldName) {\n\t var fields = [];\n\t function traverse(node) {\n\t if (node instanceof __webpack_require__(147).Field) {\n\t if (node.getSchemaName() === fieldName) {\n\t fields.push(node);\n\t return;\n\t }\n\t }\n\t if (node === rootNode...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure Oracle resources released before handing response back to caller
function releaseReturn() { if ( cn ) { odb.releaseConnection( cn, function( err, result ) { if ( err ) { log.e( 'Failed to release Oracle Connection back to Pool' + err ); return cb( err ); } else { log.d( ' Response : Error: ' + response.error + ' Re...
[ "function releaseReturn() {\n\n if ( cn ) {\n\n odb.releaseConnection( cn, \n function( err, result ) {\n \n if ( err ) {\n\n log.e( 'Failed to release Oracle Connection back to Pool' );\n return cb( err );\n\n } else {\n\n log.d( ' Response Error: ' + response.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs an add operation against the LDAP server. Allows you to add an entry (which is just a plain JS object), and as always, controls are optional.
create(dn, entry, callback) { this.ldapClient.add(dn, entry, callback); }
[ "addMember (dn) {\n return new ldap.Change({\n operation: 'add',\n modification: {\n member: dn\n }\n })\n }", "add(entry) {\n this.entries.push(entry);\n this.validateEntries();\n }", "addControl (control) {\n debug(' ... Found control: %s', control.key);\n thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the enemies with the info received from the server
updateServerEnemies(serverEnemies){ for(var i = 0; i < serverEnemies.enemies.length; i++){ var enemy = serverEnemies.enemies[i]; this.enemies[enemy.enemyID].position.x = enemy.posX; this.enemies[enemy.enemyID].position.y = enemy.posY; this.enemies[enemy.enemyID].rotation = enemy.rotation; }...
[ "function updateEnemies() {\n enemies.forEach(function(e) {\n e.move();\n });\n enemiesHit();\n enemiesOutOfBounds();\n enemies.forEach(function(e) {\n e.draw(ctx);\n });\n }", "updateOtherEnemiesWithCurrentInfo(){\n\t\tfor(var i = 0; i < this.enemies.length; i++){\t\n\t\t\tthis.enemi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
forum context hook Responsible for Create, Update, and Delete operations pertaining to the forum posts
function ForumCrud() { _s(); const [open, setOpen] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(true); const { addForum } = Object(_context_ForumContext__WEBPACK_IMPORTED_MODULE_3__["useForum"])(); const inputStyle = { padding: "5px", fontFamily: "Martel", fontWeight: "bold" }; ...
[ "function processPosts(context = document) {\n processQuotes(context)\n processMentions(context)\n processTopicIgnoredPosts(context)\n }", "function Forum(props) {\r\n const user = props.user;\r\n const [post, setPost] = useState(\"\");\r\n const [posts, setPosts] = useState(null);\r\n const [newPos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send text data over serial
function serialWriteTextData(textData) { if (serial.isOpen()) { // console.log("Writing to serial: ", textData); serial.writeLine(textData); } }
[ "function sendToSerial(data) {\n console.log(\"sending to serial: \" + data);\n port.write(data);\n}", "function sendToSerial(data) {\n console.log(\"Sending to serial: \" + data);\n myPort.write(data);\n}", "function sendToSerial(data) {\n logger(\"SerialPort\",\"Sending to serial port: \" + data);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retrieves latest images from 500px
function FetchImages(){ var fiveHundred = "https://api.500px.com/v1/photos?feature=fresh_day&sdk_key=7131207245727241ad25174950e82fc41cb572f3"; $.ajax({ type:"GET", url: fiveHundred, }) .done(function(result){ for(var i = 0; i <result.photos.length; i++) { imageArray.push(result.photos[i].image_url);...
[ "function getLatest(request, response) {\n response.end(lastImage.substring(6));\n}", "function getLatestImage() {\n ws.send(prepPayload('getLatestImage',true))\n updateImage()\n}", "function getImages() {\n var url;\n if (lastRequest) {\n url = '/api/image?from=' + lastRequest;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Safely moves to the next entry and returns true if there is one. Note: Will throw ObjectDisposedException if this has faulted or manually disposed.
moveNext() { const _ = this; _._assertBadState(); try { switch (_._state) { case 0 /* Before */: _._yielder = _._yielder || yielder(); _._state = 1 /* Active */; const initializer = _._initializer; ...
[ "function HasNextWaypoint() : boolean {\n return (HasWaypointWithID(currentWaypoint + 1));\n}", "isNext() {\n return performance.now() > this.nextCursorTime;\n }", "nextRecord() {\n\t\tif (!this.hasNext()) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.currentRow++;\n\t\tthis.loadRow(this.rows[this.currentRow])...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get list of hover colors for charts
function GetColorHoverList() { return ['#1edab5', '#47d583', '#51a7e0', '#a971c0', '#405a74', '#1abe9e', '#2dca6f', '#3293d2', '#9e56bd', '#384f66']; }
[ "get hoverTextColor() {\n return brushToString(this.i.ds);\n }", "get hoverBackgroundColor() {\n return brushToString(this.i.s7);\n }", "get hoverTextColor() {\n return brushToString(this.i.db);\n }", "get hoverTextColor() {\n return brushToString(this.i.s8);\n }", "g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
user/1/transactions | /user/1/transaction/1 | /user/1/category/1 | /categories | /category/food
function handleGetRequest(res, route) { if (matcher = route.match(/^\/user\/(\d+)\/transactions$/)) { sendResponseForGetRequest(res, `SELECT * FROM restdb.transactions WHERE id_user = ${db.escape(matcher[1])}`); } else if (matcher = route.match(/^\/user\/(\d+)\/transactionid\/(\d+)$/)) { sendRes...
[ "routes (cat = this.category.singularName) {\n return ['latest', 'page', 'submit', 'edit'].reduce(function (routes, action) {\n routes[action] = cat + '.' + action;\n return routes;\n }, {});\n }", "build_paths() {\n return {\n items: {\n list: { ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets the top and left css style of the element based on the absolute position of the caretElements caret,
function setElementPositionBasedOnCaret(element, caretElement, offset, margin, detectBoundary, returnOnly) { if (offset === void 0) { offset = { top: 0, left: 0 }; } if (margin === void 0) { margin = 2; } if (detectBoundary === void 0) { detectBoundary = true; } if (returnOnly === void 0...
[ "_position_autocomplete() {\n const editor = this._expression_editor;\n const last_span = this._expression_editor._edit_area.lastChild;\n\n if (editor.offsetWidth === 250) {\n this._autocomplete._container.removeAttribute(\"style\");\n this._autocomplete._container.classLi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A search has been done and now the note is being displayed
function fnPluginTaskSearch_afterDisplay() { /*<!-- build:debug -->*/ if (marknotes.settings.debug) { console.log(" Plugin Page html - Search - A note has been displayed"); } /*<!-- endbuild -->*/ if ($.isFunction($.fn.highlight)) { // Get the searched keywords. // Apply the restriction on the size. var...
[ "function handleSearchReturn () {\n var search_txt = (''+search_el.val()).toLowerCase();\n if (!search_txt) { return; }\n\n // Look for a pre-existing match, bail if found.\n var exists = false;\n $.each(notes, function (idx, item) {\n if (search_txt == item.label.toLowerCase()) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add new activity to activities array on '+' click (doesn't post directly to DB)
onActivityClick(e) { e.preventDefault(); var listOfActivities = this.state.activities; var activityObject = { activityName: this.state.activityName, activityDescription: this.state.activityDescription, activityCost: this.state.activityCost }; listOfActivities.push(activityObject...
[ "function insertActivity(event) {\n event.preventDefault();\n var activity = {\n text: $newItemInput.val().trim(),\n complete: false\n };\n \n $.post(\"/api/active\", activity, getActivity);\n $newItemInput.val(\"\");\n }", "pushActivity(userAct) {\r\n this.activi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
findRotationCount([7, 9, 11, 12, 5]) // 4 findRotationCount([7, 9, 11, 12, 15]) //0
function findRotationCount(arr) { if (arr === undefined || arr.length === 0) { return 0; } let leftIdx = 0; let rightIdx = arr.length - 1; while (leftIdx <= rightIdx) { let mIdx = Math.floor((leftIdx + rightIdx) / 2); let mVal = arr[mIdx]; if (mIdx === arr.length - 1) { if (mVal < arr...
[ "function numberOfRotation(arr) {\n let left = 0;\n let right = arr.length - 1;\n\n while (left < right) {\n let mid = Math.floor((right + left) / 2)\n if (arr[mid] > arr[mid + 1]) {\n left = mid + 1\n } else {\n right = mid\n }\n }\n return left\n}",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check to see if the target has a class [cName]
function hasClass(target, cName) { var regex = new RegExp("(?:^|\\s)" + cName + "(?!\\S)"); return target.className.match(regex); }
[ "function containsTarget(obj) {\n return classExist(obj, TARGETCLASS);\n}", "function hasClass( target, className ) \n{\n //return new RegExp('(\\\\s|^)' + className + '(\\\\s|$)').test(target.className);\n return target.classList.contains(className);\n}", "function hasClass(node, name) {\n return classRe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scrolls the carousel to the next item.
function scrollCarouselNext() { var currentId = getCarouselIdFromUrl(); var nextId = currentId+1; loadCarouselPage(nextId); }
[ "function nextSlide() {\n if (currentIndex < totalSlides - 1) {\n scrollTo(currentIndex + 1);\n }\n }", "function nextItem() {\n hideItems();\n currentIndex = currentIndex < slidesLength - 1 ? currentIndex + 1 : 0;\n updateIndexes();\n showItems(); ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines if the binding value should be used (or if the value is 'undefined' and hence priority resolution should be used.)
function isStylingValuePresent(value) { // Currently only `undefined` value is considered non-binding. That is `undefined` says I don't // have an opinion as to what this binding should be and you should consult other bindings by // priority to determine the valid value. // This is extra...
[ "function isStylingValuePresent(value) {\n // Currently only `undefined` value is considered non-binding. That is `undefined` says I don't\n // have an opinion as to what this binding should be and you should consult other bindings by\n // priority to determine the valid value.\n // This is extr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: dwscripts.getServerModel DESCRIPTION: Returns the server model folder name for the given document. If no DOM is provided, the current document is used. ARGUMENTS: dom DOM object (optional) the dom to get the server model for. RETURNS: String the server model of the current document, or empty string if not ser...
function dwscripts_getServerModel(dom) { var theDOM = (dom) ? dom:dw.getDocumentDOM(); var retVal = theDOM.serverModel.getFolderName(); return retVal; }
[ "function dwscripts_hasServerModel(dom)\n{\n var theDOM = (dom) ? dom:dw.getDocumentDOM();\n \n var retVal = (theDOM.serverModel.getFolderName() != \"\");\n \n return retVal;\n}", "function dwscripts_getServerImplObject()\n{\n var retVal = null;\n var dom = dw.getDocumentDOM();\n \n if (dom)\n {\n va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get count for all felder
getFeldCount() { const count = { a: 0, b: 0, c: 0 }; Object.entries(this.fachstunden).forEach((fach) => { const feld = c.faecher[fach[0]].feld; if (feld === 'a') { count.a += 1; } else if (feld === 'b') { count.b += 1; } else if (feld === 'c') { count.c += 1; ...
[ "count() {\n let num = 0;\n for (let key of Object.keys(this.dataStore)) {\n num++;\n }\n return num;\n }", "function count(){\n\tvar n = 0;\n\tfor(key in this.dataStore){\n\t\t++n\n\t}\n\n\treturn n;\n}", "static getUseCountForAll() {\n\t\treturn db.query('SELECT COUNT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate an archive ID
_generateID() { this._getWestley().execute( Inigo.create(Inigo.Command.ArchiveID) .addArgument(encoding.getUniqueID()) .generateCommand(), false // prepend to history ); }
[ "function generateID() {\n\t_docID += 1;\n\treturn 'XML' + _docID.toString();\n}", "function makeId() {\n return \"_\" + (\"\" + Math.random()).slice(2, 10);\n }", "function getID() {\n var id = 'bzm' + (new Date()).getTime();\n\n return id;\n }", "function makeID() {\n function trash() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
produce the HTML code for a month calendar
function getMonth() { // determine which font size to use for dates. var fontsize=1; if (document.CalendarSettings.fontsize[0].checked) fontsize=1; if (document.CalendarSettings.fontsize[1].checked) fontsize=3; if (document.CalendarSettings.fontsize[2].checked) fontsize=5; if (document.CalendarS...
[ "function renderMonthlyCalendar() {\n renderControls('monthly');\n var firstDay = GetDayNameIndex(selectedYear, selectedMonth - 1, 1);\n var daysInPreviousMonth = new Date(selectedYear, selectedMonth - 1, 0).getDate();\n var daysInSelectedMonth = new Date(selectedYear, selectedMonth, 0)....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function edits the html to display the names of the champions, instead of the champion id Also it's important to note that id: 0 doesn't correspond to a specific champion, it means the combined ranked stats for all champions
function insertChampionName(old_text, champ_id){ //console.log('champ_id = ' + champ_id); getChampionName(function(name){ //console.log(name); name = '<strong>' + name + '</strong>'; var content = $('#stats').html(); content = content.replace(old_text, name); content = content.replace('id: 0', '<strong>All...
[ "function championInfo() {\n $(\"#championInfo\").html(\"\");\n $(\"#championInfo\").html(\"Name: \" + champions[userIndex].name + \"<br>Gold: \" + gold + \"<br>Attack: \" + userAttack + \"<br>Magic: \" + userMagic + \"<br>Armor: \" + userArmor + \"<br>Magic Resist: \" + userMagicResist + \"<br>Health: \" + u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fact Counter For Achivement Counting
function factCounter() { if ($('.fact-counter').length) { $('.fact-counter .count.animated').each(function() { var $t = $(this), n = $t.find(".count-num").attr("data-stop"), r = parseInt($t.find(".count-num").attr("data-speed"), 10); ...
[ "function factCounter() {\n\t\tif($('.fact-counter').length){\n\t\t\t$('.fact-counter .achievement.animated').each(function() {\n\t\t\t\tvar $t = $(this),\n\t\t\t\t\tn = $t.find(\".counting\").attr(\"data-stop\"),\n\t\t\t\t\tr = parseInt($t.find(\".counting\").attr(\"data-speed\"), 10);\n\n\t\t\t\tif (!$t.hasClass(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CHECK FOR LOGGED IN USER ERROR
function _loggedInCheckError(error) { console.log(error); }
[ "function isNotLoggedUser() {\n if (getToken()) {\n console.error('WARN: You\\'re already logged. Please logout'.yellow);\n process.exit(1);\n }\n}", "function onUserLogoutError( result )\r\n{\r\n debug( 'user-logout-error: ' + JSON.stringify( result ) );\r\n}", "function userValidation() {\n var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will create a separate bounding box that will be used for damage purposes. This bounding box is invisible and follows the tank everytime it moves. Whenever a cannon ball hit this bounding box, the tank health will be decreased. This is a bounding box that is built just for hit purposes and has no collisio...
createHitBoundingBox() { var scene = this.scene; /** * Extract the bounding box parameters. The dimension of the bounding box may not be * 100% accurate. This may depend from several factors: the way meshes are defined * into the imported model, their hierarchical structu...
[ "createBoundingBox() {\n\n var scene = this.scene;\n\n\n\n /**\n * Extract the bounding box parameters. The dimension of the bounding box may not be\n * 100% accurate. This may depend from several factors: the way meshes are defined \n * into the imported model, their hierarchi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a row in the sync table for the call to a method for a model.
function addSyncForModel(method, model, opt) { var DB = new SQLite('_alloy_'); var mId = String(model.id); var mTable = model.config.adapter.collection_name; // Insert the new sync call DB.table(exports.config.syncTableName) .insert({ timestamp: Util.now(), m_id: mId, m_table: mTable, method: method, m...
[ "function addRow(){\n insertData();\n createRow();\n editTable();\n}", "function addRow() {\n doAjaxCall(\"GET\", \"addrow\", {id: myid}, nullFcn);\n}", "function addRow() {\n rows++;\n refreshTable();\n}", "function callAddPlanetRow() {\n return addPlanetRow();\n}", "function addMutationRo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies custom exponential format.
applyCustomExponentialFormat(number, textParts, numericProcessor) { const that = this; let format = textParts.main, result; const thousandsSeparator = format.indexOf(',') !== -1; // format validation - start format = format.replace(/[^0#.eE+-]/g, ''); const ...
[ "function formatExponential(options) {\r\n if (options === void 0) { options = {}; }\r\n var digits = options.digits;\r\n var missing = options.missing || '';\r\n return function (_a) {\r\n var value = _a.value;\r\n if (value === null || value === undefined) {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process whole current file.
function process () { if (!processed) { var editor = EditorManager.getCurrentFullEditor(); var currentDocument = editor.document; var originalText = currentDocument.getText(); var processedText = Processor.process(originalText); var cursorPos = editor.getCursorPos(); var scrollPo...
[ "function handleFile(fileName) {\n\tconsole.log('cmain : About to process ', fileName);\n\tvar hFeedFile = new CumulativeFeedFileProcessor(pathToProcess.concat('\\\\').concat(fileName), feedDelimiter, cumObjList);\n\thFeedFile.on(\"completedProcess\", updateObjectList);\n\thFeedFile.on('invalidFeedItem', logInvalid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Route middleware Validate all routes exclude validation on all routes with auth, status and public Otherwise verify and decode auth token and append user to request
validate(req, res, next) { // check header or url parameters or post parameters for token let token = req.headers['x-access-token']; let url = req.url.split('/'); // console.log('headers => ',req.headers); // console.log('url = ',req.url); /** * Exclude validation on all routes with auth,...
[ "function secureApiRoutes(req, response, next) {\n var decoded;\n const token = req.header('x-auth');\n if (!token) {\n return response.status(200).json({\n accessNotAllowed: \"Not allowed\"\n });\n }\n try {\n decoded = jwt.verify(token, config.secret);\n User.findOne({_id: decoded._id}, (err...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
make embeddable html from activity (checkbox)
function make_checkbox(activity, index){ return "<input class=form-check-input type=checkbox value='' id=input" + index + ">\ <label class='form-check-label' for='input'" + index + ">" + activity + "</label><br>"; }
[ "function formatCheckbox(value){\n\tif(value=='on'){return '<div style=\"text-align:center\"><img align=\"center\" width=\"15\" height=\"15\" src=\"images/checkedIcon.gif\" /></div>';}\n\tif(value=='false'){return '<div style=\"text-align:center\"><img align=\"center\" width=\"15\" height=\"15\" src=\"images/nochec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getter and setter for PhoneNo
get phoneNo() { return this._phoneNo; }
[ "set phone(value) {\n this._phone = value;\n }", "get phoneNumber() {\n return this._phoneNumber;\n }", "get phoneNumber(){return this._phoneNumber;}", "setPhoneNumber(number)\n {\n this.phone=number;\n }", "set phone(phone) {\n if (typeof phone === 'number' && phone > 0 && phone...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if a Discord member already has a Simbit shop account
function checkAcc(memberObj){ if(getShopUser(memberObj) != null){ return true; } return false; }
[ "checkUsername() {\n var wizard = document.querySelector(\"wizard\");\n var name = accountWizard.getUsername();\n var duplicateWarning = document.getElementById(\"duplicateAccount\");\n if (!name) {\n wizard.canAdvance = false;\n duplicateWarning.hidden = true;\n return;\n }\n\n var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
on google places scraper socket client connection
async function psSocketConnection(socket) { var username = ""; var browser = await openBrowser(); var isBrowserRunning = true; socket.emit("log", {type:"success" ,content:`Tarayıcı açıldı`}); browser.on('disconnected', ()=> isBrowserRunning = false ); console.info(`Socket ${socket.id} has connected.`); onlin...
[ "function handleGoogleRequest(json, socket, protocol) {\n\tlogger.logInfo(\"Google Home hat sich verbunden!\");\n\tsession.vaIP = helper.getIP(socket.remoteAddress);\n session.vaName = \"Google Home\";\n\tif(\"Koppeln\" == json.result.metadata.intentName) {\n\t\tlogger.logInfo(\"Google Home möchte sich mit einem C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given dom target is in whitespace, else false.
function _isWorkspaceWhitespace(elem) { var clicked = $(elem); // anything but a descendent of column class return $.contains(document.documentElement, elem) && (clicked.hasClass(COLUMN_CLASS) || !clicked.parents().hasClass(COLUMN_CLASS) || clicked.hasClass('clusterExpanded')); }
[ "function isWhitespaceNode(node) {\n if (!node || node.nodeType != 3) {\n return false;\n }\n var text = node.data;\n if (text == \"\") {\n return true;\n }\n var parent = node.parentNode;\n if (!parent || parent.nodeType != 1) {\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
take the name of manuscript and return an example of possible full page
function getexamplePage(manu) { var examplePage; for(i=0;i<manuList.length;i++){ if(manuList[i]==manu){ examplePage=fullpageList[i]; break; } } return examplePage; }
[ "function pageSpecific() {\n const url = window.location.href;\n\n let msg = \"\";\n if (url.includes(\"artstation\")) {\n msg = document.querySelector(\".name a\").text.replace(\" \", \"-\");\n } else if (url.includes(\"instagram\")) {\n msg = document\n .querySelector(\"header a\")\n .href.rep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove an accommodation from local storage
function removeDetails(id) { var storedAccommodation = getAllAccommodation() || []; var newStoredAccommodation = []; storedAccommodation.forEach(function(currAccommodation) { if(currAccommodation.id != id) { newStoredAccommodation.push(currAccommodation); } }); localStorage.removeItem('acc...
[ "function delete_calories_aubergine() {\n\n let aubergine_number = parseInt(localStorage.getItem('aubergine_no'));\n if (aubergine_number > 0) {\n\n // Get the calories value of the item\n let aubergine_calories = Number(localStorage.getItem('aubergine'));\n\n aubergine_number = aubergine...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the total price of the list items
totalPrice() { var total = 0; for (var i = 0; i < this.listItems.length; i++) { total += parseFloat(this.listItems[i].price); } return total.toFixed(2); }
[ "function updateTotal(listItems){\n \t\tvar total = 0;\n \t\tlistItems.forEach(function(item){\n \t\t\t\n \t\t\tif(item.selected == true){\n \t\t\t\ttotal = total + Number(item.price);\n \t\t\t}\n \t\t\t\n \t\t})\n // for each thing in listItems\n // if(item.selected == true) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the tank properties. All the properties are selected by the client, but validated server side.
setProperties(properties){ for(let prop of properties){ switch(prop.type){ case TankProperties.CHASSIS: // 10 health means 5 frames cooldown this.stats.health = prop.value; this[DefaultCooldownSetter](PrivateActions.move, Math.floor(prop.value / 2)); break; case TankProperties.ARMOR: ...
[ "function setProperties() {\n setObjectMovementProperties();\n setImagePositionProperties();\n}", "setSlotProperties ({ commit, state, dispatch }, { index, properties }) {\n if (properties.module === null) {\n properties.techTier = null\n properties.isRefit = false\n properties.sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the median average value of the input array.
function median(array) { if (array.length === 0) { return Number.NaN; } const sortedArray = array.sort((a, b) => a - b); if (sortedArray.length % 2 === 0) { return Math.floor(average([sortedArray[(sortedArray.length / 2) - 1], sortedArray[(sortedArray.length / 2)]])); } return Math.floor(sortedAr...
[ "function getMedianValue( arr ) {\n\t\tarr.sort( function( a, b ){\n\t\t\treturn a - b;\n\t\t} );\n\t\treturn arr[Math.floor( arr.length / 2 )];\n\t}", "function median(arr) {\n var sorted = arr.sort(function(a, b){ return a-b })\n var length = arr.length\n var median = Math.floor((length - 1) / 2)\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if any dishes have a quantity of zero or less
function allQuantitiesGreaterThanZero(req, res, next) { const dishes = res.locals.dishes dishes.forEach((dish) => { if (dish.quantity <= 0){ const index = dishes.indexOf(dish) next({ status: 400, message: `Dish ${index} must have a quantity that is...
[ "function allDishesHaveQuantities(req, res, next) {\n const dishes = res.locals.dishes\n dishes.forEach((dish) => {\n if (!dish.quantity){\n const index = dishes.indexOf(dish)\n next({\n status: 400,\n message: `Dish ${index} must have a quantity that...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return only numbers > min and < max
between(min, max) { return this.filter((val) => { let num = parse(val).num return num > min && num < max }) }
[ "function numberBoundaries (num, min, max) {\n return num > max ? max : (num < min ? min : num);\n }", "between(min, max) {\n return this.filter((val) => {\n let num = parse(val).num;\n return num > min && num < max\n })\n }", "function between(min, max, num) {\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the Hex version of a color stored as rgb value
function getHexColor(color) { return getHexValue(color.r) + getHexValue(color.g) + getHexValue(color.b); }
[ "function RGBtoHex(R,G,B) {return \"#\"+toHex(R)+toHex(G)+toHex(B)}", "function Color_GetHexString()\n{\n var String_R = parseInt(this.R * 255, 10).toString(16);\n var String_B = parseInt(this.B * 255, 10).toString(16);\n var String_G = parseInt(this.G * 255, 10).toString(16);\n \n if(String_R.length == 1)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a function called hockeyGame that takes a score as a callback and returns the homescore and awayscore in the form of an object
function hockeyGame(scoreCB){ return { Home: scoreCB(), Away: scoreCB() } }
[ "function hockeyGame(scorecb){\n return {\n Home: scorecb(),\n Away: scorecb()\n }\n }", "function totalGameScore(scorecb, gamecb){\n // first step \n const totalScore = [];\n // I'm going to create some variables that will be updated \n let homeScore = 0;\n let awayScore = 0;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1 appel ajax pour afficher les employes
function affiche_employes(){ // 2 je creer l'objet AJAX if( window.XMLHttpRequest) r = new XMLHttpRequest(); else r=new ActiveXObject('Microsoft.XMLHTTP'); // c est le nom de l'objet ajax pour IE // 2 je mets, si besoin, des parametres associés à cet objet AJAX: var p...
[ "function listadoAsignaturas() {\n\t\n\tconst componente = COMPONENTES[0];\n\t\n\tlet url = \"componentes/\"+componente.id+\".jsp\";\n\t\n\t$.post(url, function (data) {\n\t\t$(\"#\"+componente.id).html(data);\n\t\tlinkAjax();\n\t});\n}", "function loadDataToAddParcel() {\n\n $.ajax({\n type: 'G...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delay determines the time between calling the next frame /Special Function animateCount() This function contains the animation loop. Recursive function
function animateCount() { if (currentLoopIndex > cycleLoop.length - 1) { return;//Stops the loop } else if(currentLoopIndex >= 10) { ctx_count.clearRect(0, 0, canvas_count.width, canvas_count.height); drawNumberDouble(1,0); } else { ctx_count.clearRect(0, 0, canvas_count.width, canvas_count.height); d...
[ "function delay(d, i) { return i * 50 }", "frameCount() {\n\t\tthis.frame++;\n\t\tsetTimeout(this.frameCount, 500);\n\n\t\t// this.frame += (1/30);\n\t\t// setTimeout(this.frameCount, 1000/60)\n\t}", "function animateN(n) {\n var cur_frame = 0\n function animate() {\n if (cur_frame < n) {\n Runner.tic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }