query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
isFeatureAvailable to check the presence of Actions cache service
function isFeatureAvailable() { return !!process.env['ACTIONS_CACHE_URL']; }
[ "actionsAreAvailable() {\n return this.allActions.length > 0\n }", "actionsAreAvailable()\n {\n return this.allActions.length > 0;\n }", "doesActionExist() {\n\t\t\tthis.actionExists = 'undefined' !== typeof W.accelerators.Actions[this.name];\n\t\t\treturn this.actionE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return selected product Id for product summary
function getProductSummaryId() { return $q.when(productSummaryId); }
[ "function getProductId() {\n det = getProductDetail();\n if (typeof det == 'undefined') {\n return \"\";\n } else {\n return det.id;\n }\n}", "function getSelectedProductData() {\n var selected_product;\n var target = klevu.dom.find(\".productQuickView\");\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses tokens from the url.
function parseTokensFromUrl(success, error) { authClient.token.parseFromUrl().then(success).fail(error); }
[ "function parseTokensFromUrl(success, error) {\n authClient.token.parseFromUrl().then(success).fail(error);\n }", "function parseURL(str) {\n console.log(str);\n str = str.split(\"#access_token=\");\n str = str[1].split(\"&token_type\");\n console.log(str[0]);\n return str[0];\n}", "parse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if a given position has a piece on it.
isOccupied(pos) { let spot = (this.getPiece(pos) instanceof Piece); return spot; }
[ "function isPieceAtXY(piece, x, y) {\n\treturn (piece.x == x && piece.y == y);\n}", "function piece_inside_board (x, y, r) {\n\tvar mask = piece_mask(p, r)\n\tvar size = mask_size(mask)\n\tvar w = size.width\n\tvar h = size.height\n\tvar bw = board_size.width\n\tvar bh = board_size.height\n\treturn x >= 0 && y >=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds sliders to page.
addSliders() { this.sliders = this.config.map(function createSlider(obj) { var slider = document.createElement('input'), valueElement = document.createElement('span'); slider.type = 'range'; slider.min = 0; slider.value = 0;...
[ "function addPageSliders(pageName) {\n addDoubleSlider(pageName);\n addLinksSlider();\n}", "function addProductSliders(pageName) {\n addGallerySlider(pageName);\n addLinksSlider();\n}", "addSliders() {\n this.sliders = this.config.map(function createSlider(obj) {\n var slider = doc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create selection range from saved values
function createSelectionRange(savedSel) { var containerEl = document.getElementsByTagName('body')[0]; var charIndex = 0, range = document.createRange(); range.setStart(containerEl, 0); range.collapse(true); var nodeStack = [containerEl], node, foundStart = false, stop = false; while (!stop && (...
[ "function selectRange() {\n var frstSelect = selectedEles[0];\n var lstSelect = selectedEles[selectedEles.length - 1];\n if (cols) {\n var flipStart = flipFlipIdx(Math.min(flipIdx(selectionMinPivot), flipIdx(selectionMaxPivot),\n flipIdx(frstSelect)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download YouTube Video as MP3
function downloadMP3(url) { var video = youtubedl(url, ['--format=bestaudio'], { cwd: __dirname }) video.on('info', function(info) { video.pipe(fs.createWriteStream(info.title + '.mp3')) }) }
[ "function downloadVideo(url) {\n var video = youtubedl(url, ['--format=22/17/18'], {\n cwd: __dirname\n })\n video.on('info', function(info) {\n video.pipe(fs.createWriteStream(info.title + '.mp4'))\n })\n}", "downloadVideo() {\n if (!this.v[0].currentSrc) return alert('No video found!');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The displayStars method sets all spans of stars to be associated with the .stars class. They are then added to the div container.
function displayStars(star){ star.setAttribute("class", "stars"); global.starsDiv.appendChild(star); }
[ "function showStars(starNum) {\n var starDiv = document.getElementsByClassName('starRev')[0];\n\n // reset stars\n while (starDiv.firstChild) {\n starDiv.removeChild(starDiv.firstChild);\n }\n\n var wholeStars = 0;\n var halfStars = 0;\n\n //calculate how many stars are needed for the current review\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
task to copy all htm/html files from app directory to dist directory
function copyhtml(cb) { return gulp.src('app/*.+(htm|html)') .pipe(gulp.dest('dist/')) }
[ "function copyProdHtml(cb){\n copyHtml(config.distHtml, config.build)\n cb();\n}", "function copyHtml(cb){\n src(\"src/views/**/*.html\").pipe(dest(DEST_DIR))\n cb();\n}", "function copyRootFiles() {\n return src([\n paths.src + paths.html,\n paths.src + \"robots.txt\"\n ])\n .pipe(dest...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiate a policy. Mostly just a constructor call, but we also track the message (which was provided as metadata along with the constructor) so that we can expose this later.
function instantiate(Policy) { var policy = Object.create(new Policy()); policy.message = Policy.message; return policy; }
[ "function creatPolicy(policy){\n if(policy.POLICY_ID == 'NONE'){ \n \tvar newPolicy = new Policy(policy.POLICY_ID,\"\",\n\t\t\t \"\",\"\",\"\",\"\",\"\");\n\treturn newPolicy;\n }\n\n var newPolicy = new Policy(policy.POLICY_ID['_'],policy.THINLY_PROVISIONED['_'],\n\t\t\t policy.SLA_LATENCY['_'],p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the 'back up' desire. Deletion is autohandled by iw_observer.
function start_back_up(source="hmi") { add_desire(source + "_back_up", "BackUp", "", 1, 10); }
[ "createUploadBackupList() {\n this._upload.backupList = this._upload.list.slice();\n }", "function createBackup(callback){\n //First, check that the version being backed up isn't a duplicate\n compareVersions(function(newVersion){\n if(newVersion){\n //1. Drop table if exists, CURRICUL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build time rail highlight when intializing the player instance and advancing to the next section/playlist item
buildTimeRailHighlight() { if (this.highlightRail) { const t = this.mejsTimeRailHelper.calculateSegmentT( this.segmentsMap[this.activeSegmentId], this.currentStreamInfo ); // Create our custom time rail highlighter element this.highlightSpanEl = this.mejsTimeRailHelper.creat...
[ "_navigateToNextTimePart() {\n const that = this;\n\n that._highlightTimePartBasedOnIndex(that._highlightedTimePart.index + 1);\n }", "function setTimeColor(item) {\n //Set block to past\n if (item.time < now) {\n return \"past\";\n }\n //Set block to present\n else if (item.t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
4.(skip :))Sort a previously defined array. Place its sorted values into a new array whose values are equivalent to the first array's values multiplied by 2. Input: [ 13, 11, 15, 5, 6, 1, 8, 12 ] Output: [ 2, 10, 12, 16, 22, 24, 26, 30 ]
function sortMultipliedArray (a) { var newArr = []; var ind = 0; for (var i = 0; i < a.length; i++) { var min = Infinity; for (var j = 0; j < a.length; j++) { if (a[j] < min) { min = a[j]; ind = j; } } newArr[i] = a...
[ "function multiplayAndSort(arr) {\n var pom;\n for (var i = 0; i < arr.length; i++) {\n for (var j = i + 1; j < arr.length; j++) {\n if (arr[i] > arr[j]) {\n pom = arr[i];\n arr[i] = arr[j]\n arr[j] = pom;\n\n }\n\n } arr[i] *= 2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createDocument() Creates a SODA document.
createDocument(content, a2) { let options = {}; errors.assertArgCount(arguments, 1, 2); errors.assertParamValue(Buffer.isBuffer(content) || typeof content === 'string' || nodbUtil.isObject(content), 1); if (arguments.length > 1) { errors.assertParamValue(nodbUtil.isObject(a2), 2); o...
[ "function createDocument() {\n\t// var op = {\n\t// \"command\": \"document:create\",\n\t// \"data\": {\n\t// \t \"name\": \"project-1\",\n\t// \t \"user\": \"michael\",\n\t// \t \"rev\": 4,\n\t// \t \"title\": \"A new title\"\n\t// }\n\t// };\n\t// talk.send(op, cb);\n\n\treturn new Substance.Document(ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the user clicks in the curse room
function CurseRoomClick() { if (MouseIn(!CurseRoomThrown ? 250 : 1250, 0, 500, 1000)) CharacterSetCurrent(Player); if (MouseIn(750, 0, 1250-750, 1000-0)) { CharacterSetCurrent(CurseRoomAce); } if (MouseIn(1885, 25, 90, 90)) { CurseRoomThrown = false; CommonSetScreen("Room", "MainHall"); ...
[ "function C101_KinbakuClub_ClubRoom1_Click() {\n\n\t// When the user clicks on any character (screen is divided in 4, 3rd can be the player)\n\tif ((MouseX >= 15) && (MouseX <= 115) && (MouseY >= 520) && (MouseY <= 580)) SetScene(CurrentChapter, \"ClubRoom3\");\n\tif ((MouseX >= 1085) && (MouseX <= 1185) && (MouseY...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
slide: turn on timer to change zindex of pictures direct: the direction pictures will be slided
function slide(direct) { if (timer_Flag == 0) { timer_Flag = 1; if (direct == 0) { if (pics_index == 0) { pics_index = num_pic; } for (var g = 0; g < num_pic; g++) { if (g != (pics_index - 1)) { for (var row = 0; row < num_row; row++) { for (var col = 0; col < num_col; col++) { z_i...
[ "function slideit()\n{\n\tif (navigator.userAgent.toLowerCase().indexOf(\"msie\") != -1)\n\t{\n\t\tslidespeed=(ie)? document.images.slide.filters[0].duration*2000 : 0\n\t}\n\tif (!document.images) return\n\tif (ie) document.images.slide.filters[0].apply()\n\tdocument.images.slide.src=imageholder[whichimage].src\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listen to the mobile controlls
function mobileControllsListener() { const controlls = document.querySelectorAll('.mobile-controls > *'); controlls.forEach(con => { con.addEventListener('click', () => { let n = con.classList[0].split('-'); let key = parseInt(n[1]); setValue(key) }) }) }
[ "function onEvents(callback){if(!callback||typeof(callback)!=='function'){return;}webphone_api.evcb.push(callback);}", "function listenForAlarms() {\n // Starts listening for Chrome alarms.\n chrome.alarms.onAlarm.addListener(trackMoodListener);\n}", "_subscribeEvents() {\n this._twilioDevice.on('ready...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear open cards list list
function resetOpenCardsList() { openCardsList = []; }
[ "function clearOpenCards() {\n openCards = [];\n}", "function clearOpenCards() {\n openCards.length = 0;\n}", "function clearOpenCards() {\n openedCards = [];\n}", "function removeOpenCards() {\n cardOpen = [];\n\n}", "function removeOpenCards() {\n openCards = [];\n}", "function removeOpenCards...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize a node as an HTML string.
function toHTML(node) { const rootNode = tree.createDocumentFragment(); tree.appendChild(rootNode, node); return parser.serialize(rootNode); }
[ "toString() {\n return Strophe.serialize(this.nodeTree);\n }", "function serialize(node, xhtml) {\n\t\tvar nodeType = node.nodeType;\n\t\tif (1 === nodeType) {\n\t\t\tserializeElement(node, node.firstChild, isUnrecognized(node), xhtml);\n\t\t} else if (3 === node.nodeType) {\n\t\t\txhtml.push(encodePcdata(nod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Highlights the current DOM element using the recipe identified by the given recipePath
function makeDish( recipePath ) { var recipeName = getRecipeName(recipePath); var recipe = $.chili.recipes[ recipeName ]; if (! recipe) return; var ingredients = $( this ).text(); if (! ingredients) return; ingredients = fixWhiteSpaceAfterRe...
[ "function renderRecipe(recipes) {\n // Getting access to the recipe view section\n let recipeView = document.getElementById(\"recipe-view\");\n // Updating the HTML to selected recipe\n recipeView.innerHTML = recipeTemplate(recipes[currentRecipeIndex]);\n}", "function highlightPath(path) {\n path.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a PATCH request to the /changeUser/password endpoint on the API server Requires user's auth token
async function password(authToken, oldPassword, newPassword) { // console.log("Password function is getting called!"); let responseData = {}; try { const address = `${apiConfig.URL_SCHEME}://${apiConfig.IP}:${apiConfig.PORT}${apiConfig.EXT}/changeUser/password`; const payload = { oldPassword, ...
[ "async changePassword() {\n \n // .......... authority judge\n \n \n const user = this.ctx.request.body;\n const result = await this.service.users.update(user);\n\n // user doesn't exist\n if (result.code >= 400) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
and replace the existing currency field values and display values with their reference currency equivelents. I used this because ServiceNow wanted to convert currency fields to their display value & display currency, instead of the currency that they were entered in. E.g. entered in USD, but displayed on the Service Po...
function unDisplayCurrencyFields(tableName, dataList) { // Get a list of all of the record sys_id's _debug("dataList: "+typeof(dataList)+" - "+dataList); var sysIDs = []; for (var iRow=0; iRow<dataList.length; iRow++) { var id = dataList[iRow].sys_id; _debug("Next ID:"+id); if (JSUtil.notNil(id)) { sysIDs...
[ "function updateCurrencyInNumberFormat() {\n var curOpt = $('#number-format option[value=c], #number-format option[value=c0]');\n Globalize.culture(_chartLocale).numberFormat.currency.symbol = $('#number-currency option:selected').data('symbol');\n curOpt.each(function(i, el) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function IDfiles() will iterate through the files in a users Drive Account and find the files which have been starred. When the script finds a starred file, it will record the date which it was last modified and its file ID
function IDfiles(){ //Logging start of method Logger.log("running IDfiles()"); //delcaring variables var log = setUp(-1) //return log Spreadsheet Object var user_files = DriveApp.getFiles(); //returns a FileIterator Object var file, lastRow, date, fileName, count, lastCol; //nested loops to ...
[ "function setFileID() {\n // Create a new Deferred object\n var deferred = $.Deferred();\n console.log(\"list files\");\n gapi.client.drive.files.list({\n 'q': '\\'appdata\\' in parents',\n 'maxResults': 10\n }).then(function (response) {\n console...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the authority for the preparsed given URL.
function _parseAuthority(parsed) { // parse authority for unparsed relative network-path reference if(parsed.href.indexOf(':') === -1 && parsed.href.indexOf('//') === 0 && !parsed.host) { // must parse authority from pathname parsed.pathname = parsed.pathname.substr(2); var idx = parsed.pathname.ind...
[ "function getAuthorityFromUrl(url) {\n if (url) {\n var match = /^(?:https:\\/\\/|http:\\/\\/|\\/\\/)([^\\/\\?#]+)(?:\\/|#|$|\\?)/i.exec(url);\n if (match) {\n return match[1];\n }\n }\n return null;\n }", "function parseAuthority(value) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For example: solve(")(") = 2 Because we need to reverse ")" to "(" and "(" to ")". These are 2 reversals. solve("(((())") = 1 We need to reverse just one "(" parenthesis to make it balanced. solve("(((") = 1 Not possible to form balanced parenthesis. Return 1. Parenthesis will be either "(" or ")".
function solve(s){ // We know that it takes one reverse for every two open brackets. // So we want to store only open brackets in the stack(empty array) // and for every close bracket we either remove (pop) the last open bracket in the stack // or count a reverse and push an open bracket, so the stack w...
[ "function solve(s){\n if (s.length % 2 !== 0) return -1;\n\n var openedCount = 0\n var swapped = 0;\n var count;\n\n for (let i = 0; i < s.length; i++) {\n let bracket = s[i];\n if (bracket === \"(\") {\n openedCount++;\n }\n if (bracket === \")\") {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
By clicking on the canvas, you can save an image of the sound profile you've created. Consider it an artifact of the specific circumstances in which you interacted with the program.
function mousePressed() { saveCanvas('pitchRorschach', 'jpg'); return false; }
[ "function saveButtonClicked(){\n\tsaveSound(soundFile, \"Audio Visualizer\");\n}", "function clicked() {\n open().document.write('<img src=\"' + $canvas[0].toDataURL() + '\"/>');\n }", "function takePhoto() {\n // played the sound\n snap.currentTime = 0;\n snap.play();\n\n // take the data out of ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process a UL tag and all its children, to convert to a tree
function processList(ul) { if (!ul.childNodes || ul.childNodes.length == 0) { return; } // Iterate LIs var childNodesLength = ul.childNodes.length; for (var itemi = 0; itemi < childNodesLength; itemi++) { var item = ul.childNodes[itemi]; if (item.nodeName == "LI")...
[ "function processList(ul) {\n if (!ul.childNodes || ul.childNodes.length==0) { return; }\n // Iterate LIs\n var childNodesLength = ul.childNodes.length;\n for (var itemi=0;itemi<childNodesLength;itemi++) {\n var item = ul.childNodes[itemi];\n item = $(item);\n if (item.nodeName == \"LI\") {\n // I...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the function printNumbersInterval (), which sequentially displays in the console numbers from 1 to 20, with an interval between the numbers of 100 ms. Write the function printNumbersInterval (), which sequentially displays in the console numbers from 1 to 20, with an interval between the numbers of 100 ms. Use se...
function printNumbersInterval() { for (let i = 10; i <= 20; i++) { setTimeout(() => { console.log(i); }, 100); } }
[ "function printNumberInterval() {\n let i = 1;\n const timerId = setInterval(() => {\n console.log(i);\n if (i === 20) clearInterval(timerId);\n i++;\n }, 100);\n}", "function printNumbers(from, to) {\n let current = from;\n let number = setInterval(() => {\n console.log(current);\n if (curren...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the font Shadow property
set FontShadow(value) { this._shadow = value; }
[ "changeTextShadow(val){\r\n this.textlogoid.style.textShadow = val;\r\n}", "function changeTextShadow(textLocation) {\n gState.labels[textLocation].textShadow = !gState.labels[textLocation].textShadow;\n drawOnCanvas();\n}", "set shadows(value) {}", "shadow() {\n let options = this.options;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve all data from the developer table
function getAllDevelopers() { self.getAsyncStatement("getAllDevelopers").executeAsync({ handleResult: function(aResults) { let row = null; while (row = aResults.getNextRow()) { let addon_internal_id = row.getResultByName("addon_internal_id"); if (!(addon_interna...
[ "function getDeveloper() {\n DeveloperService.perform().get({id: devId}).$promise\n .then(function (developer) {\n $scope.employee = developer;\n $log.debug(\"Fetched developer\", developer);\n\n getCompany(developer);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether first line fits for cell or not.
isFirstLineFitForCell(bottom, cellWidget) { if (cellWidget.childWidgets.length === 0) { return true; } if (cellWidget.childWidgets[0] instanceof ParagraphWidget) { let paraWidget = cellWidget.childWidgets[0]; return this.isFirstLineFitForPara(bottom - cellWidg...
[ "checkCell(x, y) {\n // if already filled, do nothing\n const flatXY = imaging.flat(x, y, this.imageWidth);\n const pixels = this.pixelOverlay[this.selectedPaletteIndex];\n return pixels.has(flatXY);\n }", "isFirstLineFitForRow(bottom, rowWidget) {\n for (let i = 0; i < rowWi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handler: handleMenuClick calls the onLogout prop if the key id set to logout. This logs the user out.
handleMenuClick({ key }) { if(key === "logout") { this.props.onLogout(); } }
[ "onLogoutClick() {\n logout();\n this.onMenuClose();\n }", "_logout() {\n this._closeMenu();\n AuthActions.logout();\n }", "function onLogout() {\n props.actions.logout(_id, token);\n }", "function onLogoutButtonClicked() {\n let event = new Event(Config.MENU_VIEW.EVENT.LOGOUT_CLI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use the `batch` method to create a ParticleContainer
batch(size = 15000, options = {rotation: true, alpha: true, scale: true, uvs: true}) { let o = new this.ParticleContainer(size, options); return o; }
[ "_generateOneMoreBuffer(container) {\n const batchSize = container._batchSize, dynamicPropertyFlags = container._properties;\n return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize);\n }", "generateBuffers(container) {\n const buffers = [], size = container._maxSize, batchSize = con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints a summary for a single Layer, with connectivity information.
function printLayerSummaryWithConnections(layer, positions, relevantNodes, // tslint:disable-next-line:no-any printFn) { var outputShape; try { outputShape = JSON.stringify(layer.outputShape); } catch (err) { outputShape = 'multiple'; } var connections = []; for (var _i = 0,...
[ "function printLayerSummaryWithConnections(layer, positions, relevantNodes, // tslint:disable-next-line:no-any\nprintFn) {\n var outputShape;\n try {\n outputShape = JSON.stringify(layer.outputShape);\n } catch (err) {\n outputShape = 'multiple';\n }\n var connections = [];\n for (var _i = 0, _a = layer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the text on the slide
function changeSlideText(slideToChange, slideText) { slideToChange.data.text = slideText; runUpdateTimer(); }
[ "function changeText()\n{\n\t$(\"#p3\").html(\"Ye Scurvy dog, focus on the war or you'll walk the plank!\");\n}", "updateText(event) {\n let _this = event.data;\n let id = $('.item.active').data('slide-number');\n $('#carousel-text').html($('#slide-content-'+id).html());\n }", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select all the rows from the indicated table. Invokes callback with an array of all rows converted into objects.
function select_all(table, options, callback) { if (!callback && typeof(options) == "function") { callback = options; options = {}; } options = options || {}; retrieveSchema(table, null, function(schema) { if (schema) { db.transaction(function(tx) { var where = b...
[ "function selectAll(tableName) {\n return function(onSelectReturn) {\n var sql = buildSelectQuery(tableName);\n var queryClient = buildQueryClient(sql);\n queryClient(function(err, tableValues) {\n if (err) {\n return onSelectReturn(new Error(['Select all failed on'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
src/components/NotificationContent.svelte generated by Svelte v3.12.1
function add_css$5(){var style=element("style");style.id="svelte-1xe6894-style";style.textContent="div.svelte-1xe6894{display:flex;flex-flow:column nowrap;justify-content:center;font-size:inherit;font-family:inherit;margin-left:0.75em;max-width:78%}p.svelte-1xe6894{margin:0.5em 0 0 0;opacity:0.7;font-size:0.889em;line-...
[ "function add_css$5(){var style=element(\"style\");style.id=\"svelte-1epeibm-style\";style.textContent=\"div.svelte-1epeibm{display:flex;flex-flow:column nowrap;justify-content:center;font-size:inherit;font-family:inherit;margin:0 1.5rem 0 0.75rem}p.svelte-1epeibm{display:flex;align-items:center;margin:0.5em 0 0 0;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function is reponsible for signing our hash of the transaction to sign any transaction we have to give our public and private key pair We can only spent coins from the wallet whose private key is known to us
signTransaction(signingKey) { if (signingKey.getPublic('hex') != this.fromAddress) { throw new Error("You cannot sign transactions for other valets"); } const hashTx = this.calculateTransactionHash(); //signing hash of our transaction const sig = signingKey.sign(hashT...
[ "signTransaction(signingKey){\r\n //before we sign a transaction, we need to check if the public key = fromAddress\r\n //as we can only spend coins we have from our wallet with the private key\r\n //since private key is linked to public key, hence public key is = to fromAddress from the transac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In order to generate random bytes on Windows without taking a dependency on native node modules which we then need to build xplat and bundle with the extension, download a prebuilt executable which directly consumes BCryptGenRandom in bcrypt.dll and outputs random bytes as hex. This executable is required for trusted n...
async function downloadBCryptGenRandomExecutable() { console.log('Downloading BCryptGenRandom.exe...'); const executableName = 'BCryptGenRandom.exe'; const uri = `https://pvsc.blob.core.windows.net/jupyter-dev-builds/${executableName}`; const srcDestination = path.resolve(path.dirname(__dirname), '..', ...
[ "generateRandomPassword() {\n const buffer = crypto.randomBytes(256);\n return `${buffer.toString('hex').slice(0, 10)}B`;\n }", "generateRandomFilename() {\n // create pseudo random bytes\n const bytes = crypto.pseudoRandomBytes(32);\n\n // create the md5 hash of the random bytes\n const checks...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A chunk is: (1) Match (2) Node (3) Range (4) DocumentFragment (5) Link, Button, or any class that implements a method toNode(Range) (6) String The range parameter should correspond to where the returned node will be inserted in the document, so that chunkAsNode can create a ndoe appropriate to the context..
function chunkAsNode(chunk, range) { if (!chunk) throw Error("null argument passed to chunkAsNode()"); if (typeof chunk == "object") { if (instanceOf(chunk, Match)) { // TODO handle case where Match.range is null // return chunk.range.cloneContents(); return chunk.content; } else if (in...
[ "function chunkAsNode(chunk, range) {\r\n if (!chunk) throw Error(\"null argument passed to chunkAsNode()\");\r\n \r\n if (typeof chunk == \"object\") {\r\n if (instanceOf(chunk, Match)) {\r\n // TODO handle case where Match.range is null\r\n // return chunk.range.cloneContents();\r\n return ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calendar class constructor. Takes in an id for the div which will later be poplated dynamically with calendar HTML by calls to the render method
function Calendar(id) { this.calendar = document.getElementById(id); this.calendar_id = id; }
[ "function Calendar() {\r\n g_Calendar = this;\r\n // some constants needed throughout the program\r\n this.daysOfWeek_eng = new Array(\"Su\", \"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\");\r\n this.months_eng = new Array(\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"A...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets a slot number
get_slot(slotNumber) { return parseInt(this.memory[slotNumber - 1]); }
[ "function getSlotNum(slotid)\r\n{\r\n\treturn slotid.substr(5);\t\r\n}", "getSlotNumber(){return this.currentSlots;}", "set_slot(slotNumber) {\n this.memory.push(this.last());\n\n return parseInt(this.memory[slotNumber - 1]);\n }", "function slot_x(slot) { return slot[0] }", "function addSlot() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reverts the chart back to its original state
_revert() { this.get('_chart').revert(); }
[ "function resetChart() {\n chart.dataProvider = chartData;\n chart.titles[0].text = 'Yearly data';\n\n // remove the \"Go back\" label\n chart.allLabels = [];\n\n chart.validateData();\n chart.animateAgain();\n}", "function resetGraph() {\n …\n displayGraph(bars);\n }", "r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BufferGeometry uses odd numbers as Id
function dn(){Object.defineProperty(this,"id",{value:hn+=2}),this.uuid=bt.generateUUID(),this.name="",this.type="BufferGeometry",this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0}}
[ "function BufferGeometry(){Object.defineProperty(this,'id',{value:bufferGeometryId+=2});this.uuid=_Math.generateUUID();this.name='';this.type='BufferGeometry';this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;this.drawRange={start:0,count:Infini...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validator function Return true if the passed string is a valid tax identification number for the specified locale. Throw an error exception if the locale is not supported.
function isTaxID(str) { var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; (0, _assertString.default)(str); // Copy TIN to avoid replacement if sanitized var strcopy = str.slice(0); if (locale in taxIdFormat) { if (locale in sanitizeRegexes) { strcopy = strcopy...
[ "function isTaxID(str) {\n var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';\n _assertString.default(str); // Copy TIN to avoid replacement if sanitized\n var strcopy = str.slice(0);\n if (locale in taxIdFormat) {\n if (locale in sanitizeRegexes) strcopy = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the offset geometry for the given widget. A resize message will be dispatched to the widget if appropriate.
function setGeometry(widget, left, top, width, height) { var resized = false; var rect = getRect(widget); var style = widget.node.style; if (rect.top !== top) { rect.top = top; style.top = top + 'px'; } if (rect.left !== left) { rect.left = left; style.left = left...
[ "function setGeometry(widget, left, top, width, height) {\r\n\t var resized = false;\r\n\t var style = widget.node.style;\r\n\t var rect = Private.rectProperty.get(widget);\r\n\t if (rect.top !== top) {\r\n\t rect.top = top;\r\n\t style.top = top + \"px\";\r\n\t ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split a URL into server name and path
function splitURL(url) { if (!url) { return false; } var m = url.match(/\w+:\/\/([^\/]*)\/(.*)/); if (!m || !m.length || m.length != 3) { return false; } return { serverName: m[1], serverPath: m[2] }; }
[ "function splitURL(url)\n{\n var baseURL = { protocol: \"\", domain: \"\", resource: \"\" };\n\n if (!url || url.length == 0) return baseURL;\n var components = url.split(\"://\");\n baseURL.protocol = components[0];\n var slashIndex = components[1].indexOf(\"/\");\n if (slashIndex >= 0) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2.3.a. Search search box input bind tables and input for blog stack
function searchTableI(table, input) { if (input.value === "" || input.value === "null"){ deleteQueryStringParameter("search"); } else { setQueryStringParameter("search", input.value); } setCookie("search", input.value, 1); var filter = input.value....
[ "function bindSearchHandlerElements() {\n\t\t\t\tif (options.search == true) {\n\t\t\t\t $('#'+getElementID('search_val')).livequery('keypress', function(e){\n\t\t\t\t var code = (e.keyCode ? e.keyCode : e.which);\n if(code == 13) { //Enter keycode\n do_search();\n return fa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines based on the state of this container, if it can be split vertically.
function getCanSplit() { var split = true; // Need to have a control and parent set if (!scope.parentControl || !scope.control) { split = false; } else { // Check if the type is splittable var...
[ "splitView() {\n // Run this computation every time the viewports are updated\n Session.get('LayoutManagerUpdated');\n\n // Stops here if layout manager is not defined yet\n if (!window.layoutManager) {\n return;\n }\n\n return window.layoutManager.viewportData.l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
4.function to set the count board info
function setCountBoardInfo(level) { $('#count_number p').html('Level:'+level); //computer turn computerTurn(level); }
[ "constructor() {\n this.boardwidth = 5;\n this.boardheight = 5;\n this.onboard = 0;\n }", "getCounts() {\n this.#board.map((row) => {\n row.map((cell) => {\n if (!cell.isMine) {\n const { startX, endX, startY, endY } = this.#findNeighboor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TableRowWidget Get line widget fom row
getLineWidgetRowWidget(widget, point) { for (let i = 0; i < widget.childWidgets.length; i++) { let cellSpacing = 0; cellSpacing = HelperMethods.convertPointToPixel(widget.ownerTable.tableFormat.cellSpacing); let leftCellSpacing = 0; let rightCellSpacing = 0; ...
[ "getLineWidgetCellWidget(widget, point) {\n for (let i = 0; i < widget.childWidgets.length; i++) {\n if (widget.childWidgets[i].y <= point.y\n && (widget.childWidgets[i].y + widget.childWidgets[i].height) >= point.y) {\n if (widget.childWidgets[i] instanceof Paragraph...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds calendar footer listeners.
_addCalendarFooterListeners() { const that = this, footer = that.$.calendarDropDown.$footer; footer.listen('change', that._footerChangeHandler.bind(that)); footer.listen('click', that._footerClickHandler.bind(that)); footer.listen('wheel', that._footerWheelHandler.bind(that)...
[ "addFooterListeners() {\n [...document.querySelectorAll('.container__footer')].forEach((element) => {\n element.addEventListener(\n 'click',\n (event) => {\n event.preventDefault();\n this.addNewCardFormShow(event.target.closest('.cards-column').dataset.group);\n },\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show/hide options tab on type change
function toggleOptionsTab(el) { var array = [3, 4, 5,6,9,8]; var optionsTab = $("#attributes-tabs li")[1]; console.log($(el).val()); // Show options tab when type is dropdown or select if(array.indexOf(parseInt($(el).val())) != -1){ $(optionsTab).show(); ...
[ "function toggleOptionsTab(el)\n {\n var optionsTab = $(\"#tabs-form li\")[1];\n // Show options tab when type is dropdown or select\n if($(el).val() === 3 || $(el).val() === 4 || $(el).val() === 5 || $(el).val() === 6)\n {\n $(optionsTab).show();\n\n $(\".field_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Example 4 :: Future : fetch balance, create stoporder and check open stoporders
async function example4 () { exchange['options']['defaultType'] = 'future'; // very important set future as default type await exchange.loadMarkets (); // fetch future balance const balance = await exchange.fetchBalance (); console.log (balance) // create stop-order const symbol = 'ETH/USD...
[ "async function example1 () {\n exchange['options']['defaultType'] = 'swap'; // very important set swap as default type\n await exchange.loadMarkets ();\n\n const symbol = 'LTC/USDT:USDT';\n const market = exchange.market(symbol);\n \n // fetch swap balance\n const balance = await exchange.fetc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate random EAN like numbers
function genEAN() { var min=5449000000002; var max=5449000900002; return parseInt(Math.random() * (max - min) + min); }
[ "function genRandEmeraldVal() {\n randEmeraldVal = Math.floor((Math.random() * 11) + 1);\n console.log(\"Emerald value \" + randEmeraldVal)\n }", "function randomExponential(expected) {\n return Math.log(Math.random()) / -(1 / expected);\n}", "randomNumber(){\n return Math.floor( Math.rando...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiates a new XFormElem. This is the base class for all other XReportDOM classes.
function XFormElem(type) { var that = this; that.type = type; that.id = that.genUniqueId(); that.scriptAlias = that.id; that.hideFromOutput = false; that.hidden = false; }
[ "getFormElement() {}", "function createFromElement(formElement, id) {\n\tid = id || parseInt(formElement.getAttribute('data-id')) || 0;\n\tvar form = new Form(id, formElement);\n\tforms.push(form);\n\treturn form;\n}", "function XFormObject(xmlNode, isCanonical) {\r\n // If being called by inherits() method, d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createRichTextEditor Code copied from static_src/wagtailadmin/js/hallobootstrap.js Modifications were made to add new form fields to the TableBlock in Wagtail admin and support the rich text editor within table cells. TODO: Refactor this code and submit PR to Wagtail repo.
function _createRichTextEditor( initialValue ) { const id = 'table-block-editor'; const editor = $( '#' + id ).attr( 'value', JSON.stringify( initialValue ) ); window.draftail.initEditor( '#' + id, { entityTypes: [ { type: 'LINK', icon: 'link', ...
[ "function setRichTextEditor() {\n new BloggerRichEditor().make();\n NestlingFormFields();\n var div = document.createElement('div');\n div.id = 'key_commands';\n div.innerHTML = getKeyCommandsHtml();\n RichEdit.editarea.appendChild(div);\n}", "html() {\n const li = document.createElement(this.nodeType);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method generate an alias from an input text, return empty string if no valid character presents.
function GenerateAlias(inputText) { return GenerateAlias(inputText, 250); }
[ "function GenerateAlias(inputText) {\r\n return GenerateAlias(inputText, 250);\r\n}", "function aliasGen(firstName, surname){\n firstName = firstName.toUpperCase();\n surname = surname.toUpperCase();\n var first = {\n A:'Alpha',\n B:'Beta',\n C:'Cache',\n D:'Data',\n E:'Energy',\n F:'Function',\n G:'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns values in the group until "done" is true
next() { if(this.ind===this.group.values.length) { return {value: undefined, done: true} } else { let val = this.group.values[this.ind]; this.ind++; return {value: val, done: false} } }
[ "next() {\r\n\t\tif (this.pos >= this.group.elements.length) {\r\n\t\t\treturn { done: true };\r\n\t\t} else {\r\n\t\t\tlet result = { value: this.group.elements[this.pos], done: false };\r\n\t\t\tthis.pos++;\r\n\t\t\treturn result;\r\n\t\t}\r\n\t}", "function iterationDone(x) { return {value: x, done: true}; }",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through pageStats in the psiResults object and return the total number of bytes to load the website.
function totalBytes(results) { var total = 0; var pageStats = results.pageStats; for(var key in pageStats) { if(key.endsWith('Bytes')) { total += parseInt(pageStats[key], 10); } } return total; }
[ "function totalBytes(results) {\n var result = 0;\n for(var j in results.pageStats) {\n if(j.match(/Bytes/g)) {\n result += Number(results.pageStats[j]); \n }\n }\n return result;\n}", "function totalBytes(results) {\n // Your code goes here!\n var totalBytesResult;\n var a = p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends an AJAX request to delete a ticket from the API. Makes use of the HTTP DELETE method. ONSUCCESS => 1) Show an alert to the user to inform him that deletion was successful 2) Reloads the list of all the users to display ONERROR => Displays a message to the user to inform him that ticket could not be deleted
function delete_ticket(api_url) { $.ajax({ url: api_url, type: 'DELETE' }).done(function (data, textStatus, jqXHR){ if (DEBUG) { console.log ("RECEIVED RESPONSE: data:",data,"; textStatus:",textStatus); } // Inform user that the user has been deleted alert_success("The ticket with has...
[ "function notifyDelete(flightID) {\n let url = \"/api/Flights/\" + flightID;\n $.ajax({ url: url, type: 'DELETE' })\n .fail(function (data) {\n raiseError(\"Fail deleting from the server: \" + data.status)\n })\n\n}", "deleteRentRequest(id) {\n $.ajax({\n url: 'ht...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Appends error message to the conversation
chatAddError(errorMessage, originalText) { // eslint-disable-next-line no-param-reassign errorMessage = UIUtil.escapeHtml(errorMessage); // eslint-disable-next-line no-param-reassign originalText = UIUtil.escapeHtml(originalText); $('#chatconversation').append( `${'<...
[ "sendUserError() {\n this.appendMessages(Constants.SERVER_ERROR_MSG);\n }", "chatAddError (errorMessage, originalText) {\n errorMessage = UIUtil.escapeHtml(errorMessage);\n originalText = UIUtil.escapeHtml(originalText);\n\n $('#chatconversation').append(\n '<div class=\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
// // // // // // // // // // // // // // // // // // // // Functions Never exceed x decimal places
function limitDP(x) { // If the number contains a decimal place // and has more than dp number of decimal places if(x.toString().split('.').length > 1 && x.toString().split('.')[1].length > dp) { x = x.toFixed(dp) } return x }
[ "function precision_method() {\n var x = 12938.3012987376112;\n document.getElementById(\"Precision\").innerHTML = x.toPrecision(10);\n}", "function precision_Method() {\n var x = 12938.3012987376112;\n document.getElementById(\"Precision\").innerHTML= x.toPrecision(10);\n}", "static fStr(x, n) {\nretur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a kbit random integer
function randomBitInt(k) { if (k > 31) throw new Error("Too many bits.") var i = 0, r = 0 var b = Math.floor(k / 8) var mask = (1 << (k % 8)) - 1 if (mask) r = randomByte() & mask for (; i < b; i++) r = (256 * r) + randomByte() return r }
[ "function randomK(k){\n let z = BB.makeBits(k);\n for (let i = 0; i < k; i++){\n if (Math.random() > 0.5){\n z.setBit(i, 1);\n }\n }\n return z;\n }", "integer () {\n return this.rnd() * 0x100000000;// 2^32\n }", "genKey() {\n return Math.floor(Math.random() * 1000);\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to render ingredients as buttons
function renderIngredients(array) { array.forEach(element => { let li = document.createElement('li') let ingredientElem = document.createElement('a') ingredientElem.className = 'button ingredient' ingredientElem.innerHTML = element li.append(ingredientElem) document...
[ "function renderButtons(ingredient){\n\t//making where the buttons get dumped not have duplicates\n\t//starting with an empty div\n\t$('#ingredientView').empty();\n\n\t//dynamic for loop to go through globa var array and get the button info\n\tfor (var i = 0; i < ingredients.length; i++) {\n\t\t//adding button to h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This functions checks if the user has granted location permissions without requesting them. This aligns with Google's recommendation to only 'request geolocation information in response to a user gesture' rather than on page load, which can make users mistrustful or confused.
async function checkLocationPermissions() { if (navigator.geolocation) { const result = await navigator.permissions.query({ name: 'geolocation' }); if (result.state === 'granted') { // Location permissions have already been granted return true; } else { // Permissions either de...
[ "function handlePermission() {\n navigator.permissions.query({ name: 'geolocation' }).then(function (result) {\n if (result.state == 'granted') {\n return getCurrLoc();\n } else if (result.state == 'prompt') {\n return getCurrLoc();\n } else if (result.state == 'denied'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updating cart event handlers
function cartUpdated() { $('.change-cart-item-quantity').on('click', function(evt){ evt.preventDefault(); var $button = $(this); var $item = $button.closest('.cart-item'); var id = $item.data('id'); var quantity = $(`#update-quantity-${id}`).val(); updateItem(id, quantity); renderCart(); ...
[ "handleCartUpdate() {\n // Update Cart Badge\n this.dispatchEvent(\n new CustomEvent(CART_CHANGED_EVT, {\n bubbles: true,\n composed: true\n })\n );\n // Notify any other listeners that the cart items have updated\n fireEvent(thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the roles form after hiding it.
function clear_roles_form () { $.modal.close(); //$('#roles-picker').slideUp('slow', function() { // Clear all the role form fields. $('.roles-row').remove(); //}); }
[ "function clear_roles_form () {\n $.modal.close();\n $('.roles-row').remove();\n}", "function clear_roles_form () {\n $.modal.close();\n //$('#roles-picker').slideUp('slow', function() {\n // Clear all the role form fields.\n $('.roles-row').remove();\n //});\n}", "function resetRoleListbox...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process the URL for any params that we can use.
processURL() { let urlParams = {}; // Get URL params - split em up - loop over them - fill urlParams object window.location.search .replace('?', '') .split('&') .forEach(chunks => { let kv = chunks.split('='); urlParams[kv[0]] = kv[1]; }); // If a command URL is present. if (url...
[ "function processUrlParameters() {\n\tvar params = window.location.hash.substring(1).split('&');\n\tfor (i in params) {\n\t\tvar pair = params[i].split('=');\n\t\tvar handler = parameterMap[pair[0]];\n\t\tif (handler) {\n\t\t\thandler(pair[1]);\n\t\t}\n\t}\n}", "function _processUrl() {\n const parameters = loca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
exported ExplorableNumberlineOrientationMarker / global ExplorableHintedText
function ExplorableNumberlineOrientationMarker(options) { let backgroundColor, coordinates, fontFamily, fontSize, fontWeight, foregroundColor, marker, string, textAnchor, where; marker = this; init(options); return marker; function init(options) { _required(options...
[ "function ExplorableNumberlineTitle(options) {\n let backgroundColor,\n coordinates,\n fontSize,\n fontFamily,\n fontWeight,\n foregroundColor,\n string,\n textAnchor,\n title,\n where;\n\n title = this;\n\n init(options);\n\n return title;\n\n function init(options) {\n\n _requir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assigns the difficulty level to the variable chosenWordArray
function difficultyLevel() { if (chosenLevel === 'EASY') { chosenWordArray = easyLetterWords; } else if (chosenLevel === 'MEDUIM') { chosenWordArray = meduimLetterWords; } else if (chosenLevel === 'HARD') { chosenWordArray = hardLetterWords; } else if (chosenLevel === 'IMPOSSIBLE') { ...
[ "function chooseRandomWord() {\n //store random word\n currentWord = wordLibraryArray[Math.floor(Math.random() * wordLibraryArray.length)];\n currentWordArray = currentWord.split('');\n remainingLetters = currentWord.length;\n displayStatus(currentWord);\n}", "function initializeGame(){\n\n currentWor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
size scrollbar and handle proportionally to scroll distance
function sizeScrollbar() { var remainder = $scrollContent.width() - $scrollPane.width(); var proportion = remainder / $scrollContent.width(); var handleSize = $scrollPane.width() - (proportion * $scrollPane.width()); $scrollbar.find(".ui-slider-handle").css({ ...
[ "function sizeScrollbar() {\n var remainder = scrollContent.width() - scrollPane.width();\n var proportion = remainder / scrollContent.width();\n if (proportion <= 0)\n scrollbar.hide();\n else {\n var handleSize = scrollPane.width() - proportion*scrollPane.width();...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save result to a text file
function ImagetoText(result) { fs.appendFile('result.txt', result, 'utf8', (err) => { if (err) throw err; console.log('The text was appended to the result.txt file!'); process.exit() }) }
[ "function saveResultToFile() {\n let fileFormatter\n let resultOption = downloadOptions.result\n let language = downloadOptions.language\n console.log(downloadOptions)\n if(resultOption === \"XPATH\"){\n fileFormatter = getXpaths()\n } else if (resultOption === \"VAR\"){\n console.log(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch a Document by ID and update title and description fields Return message on successful update
update(req, res) { if (!req.body.title || req.body.title === '' || !req.body.content || req.body.content === '') { res.send({ message: 'Both fields are required' }); } else { Document.findOne({ where: { id: req.params.id } }) .then((document) => { if (!document) { r...
[ "function updateDocument() {\n var id = getObject(\"field-documentId\").value;\n\n var title = getObject(\"field-documentTitle\").value;\n var filename = getObject(\"field-documentFilename\").value;\n\n // Now datetime\n var now = new Date();\n // Put into the following ISO format: yyyy-MM-dd'T'HH:mm:ss.SSSXX...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public: hides element from website element the element to be hidden Examples hideElement($(options)); Hides the element
function hideElement(element) { element.css('visibility', 'hidden'); }
[ "hide(element) { // ch 7 utility functions that will show and hide elements on a page.\n element.style.display = 'none';\n }", "function PCAxis_HideElement(selector) {\n jQuery(selector).hide(0);\n}", "function hideElement(element) {\n\t\tvar answer = element.querySelector('.' + options.aClass);\n\t\tans...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unary ::= Primary | '' Unary
function parseUnary() { let token, expr; token = lexer.peek(); if (matchOp(token, '-') || matchOp(token, '+')) { token = lexer.next(); expr = parseUnary(); return { 'Unary': { operator: token.value, expr...
[ "function parseUnary() {\n var token, expr;\n\n token = lexer.peek();\n if (matchOp(token, '-') || matchOp(token, '+')) {\n token = lexer.next();\n expr = parseUnary();\n return {\n 'Unary': {\n operator: token.value,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
new HitsTracker obj can take an integer for calculating visits X min ago (assigned 5 mins by default) for example, to track website in the past 2 minutes => `let tracker = new HitsTracker(2)`;
constructor(minAgo = 5) { // startPointer will keep track of the time of the least recent hits this.startPointer = null; // hitsCount will keep track of total number of count // as well as a list of number of hits at a given time this.hitsCount = {"totalCount": 0}; this.minsAgo = minAgo; t...
[ "function updateHoursAgo(){\n var hours = parseInt(document.getElementById(\"thehours\").value);\n TagTracker.timeAgoLimit = hours * 60;\n TagTracker.splitTime = TagTracker.timeAgoLimit / TagTracker.buckets;\n if (debug > 2){\n console.log(\"timeAgoLimit now: \" + TagTracker.timeAgoLimit);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
walk the subtree rooted at node, applying 'find(element, data)' function to each element if 'find' returns true for 'element', do not search element's subtree
function findAll(node, find, data) { var e = node.firstElementChild; if (!e) { e = node.firstChild; while (e && e.nodeType !== Node.ELEMENT_NODE) { e = e.nextSibling; } } while (e) { if (find(e, data) !== true) { findAll(e, find, data); } e = e.nextElementSibling; } retur...
[ "function scanTree(element){return scanLevel(element)||(!!scanDeep?scanChildren(element):null);}", "function findAll(node, find, data) {\r\n var e = node.firstElementChild;\r\n if (!e) {\r\n e = node.firstChild;\r\n while (e && e.nodeType !== Node.ELEMENT_NODE) {\r\n e = e.nextSibling;\r\n }\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A registry of Component classes.
function ComponentClassRegistry () { // We delay the creation of the definition of a class till it's requested. // The function that creates the component class is a classExporter. this.classExporter = {}; // Collection of all the component classes we generate for // proper stack traces and proper ...
[ "registerAll(newComponents) {\n newComponents.forEach(component => {\n let {name, dependencies, ctor} = component;\n this.register(name, dependencies, ctor);\n });\n }", "function _registerAll() {\n if (!registerAllCalled) {\n registerAllCalled = true;\n Object.keys(ComponentsHas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
testSave() use Model's function find()/findOne() to search
function testFind(){ UserModel.find(function(err, users){ console.log('find', err, users) }) UserModel.findOne({_id:'5c016964c01b2f04cc7e514d'}, function(err, user){ console.log('findOne', err, user) }) }
[ "findOne() {\n return this.collection.findOne.apply(this.collection, arguments);\n }", "findOne(criteria, callback) {\n this.model.findOne({where: criteria}).then(function (item) {\n callback(null, item);\n }).catch(callback);\n }", "saveModel(skipAfterUpdate) {\n return get(t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
zoto_modal_album_add_photos A modal that allows the user to add/remove photos and customize the order An album id must be specified either before show is called, or by passing an id or album record to the show method.
function zoto_modal_album_add_photos(options) { this.options = options || {}; this.options.in_wizard = this.options.in_wizard || false; this.options.wizard_options = this.options.wizard_options || false; this.$uber(options); this.options.images = this.options.images || []; this.album_images = []; //since we d...
[ "function zoto_modal_album_order_photos(options) {\n\tthis.options = options || {};\n\tthis.options.in_wizard = this.options.in_wizard || false;\n\tthis.options.wizard_options = this.options.wizard_options || {};\n\tthis.$uber(options);\n//\tthis.zoto_modal_window(options);\n\t\n\tthis.data = [];\n\tthis.images = [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to repeat or end program
function endRepeat() { inquirer .prompt([{ type: "list", name: "wish", message: "\nDo you want to perform another operation?", choices: ["Yes", "No"] }]).then( answer => { if (answer.wish === "Yes") { showMenu(); ...
[ "end() {\n var run_json = \"{\\\"cmd\\\":\\\"end\\\"}\"; // advance the simulation until the power on button is pressed \n socket.send(run_json);\n return true;\n }", "function doQuit()\r\n { \r\n doTerminate();\r\n }", "function End() {\n var end = readline.question ('W...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate the state of the drawer children components.
_validateDrawers() { this._start = this._end = null; // Ensure that we have at most one start and one end drawer. this._drawers.forEach((drawer) => { if (drawer.position === 'end') { if (this._end != null) { throw new Error('Duplication drawers at ...
[ "validateTree() {\n this.validate();\n for (const child of this.children) {\n child.validateTree();\n }\n }", "function validateAllPanels() {\n\n if (validGeneral() && validImage () && validParent () )\n return true;\n else\n return false;\n }", "validateS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete photo with id
function deletePhoto(id) { url = "deletePhoto.php?id=" + id; doAjaxCall(url, "updateMain", "GET", true); }
[ "function deletePhoto(id) {\n return photodb('photos').where({ id }).first().delete();\n}", "onDeletePhoto(id) {\n this.props.deletePhoto(id);\n }", "static async delete(id) {\n const result = await db.query(\n `DELETE FROM photos\n WHERE id = $1\n RETURNING id`,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GROUPED RESIDENT: perform two opt with grouped residents
function groupedResidentTwoOpt(hospitals, residents, callback) { addGroupedGhosts(hospitals, residents); var temperature = 100.0; var rate = global.settings.rate; while (temperature > global.settings.threshold) { var ind = getRandomIndices(residents.length); // get random pairs var resA = residents[ind.inde...
[ "function mergeClusterAggs(a, b) {\n // count(*)\n a[\"count(*)\"] += b[\"count(*)\"];\n\n // convex hulls\n for (var i = 0; i < b.convexHull.length; i++)\n a.convexHull.push(b.convexHull[i]);\n if (a.convexHull.length >= 3) a.convexHull = d3.polygonHull(a.convexHull);\n\n // topk\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
attach school change event
function attachEvent() { $el.on("click", "a", function(e) { e.preventDefault(); var newSchool = $(this).data("school"); if (newSchool !== planner.school) { if (planner.school) { $.publish("module:clean"); } else { ...
[ "function setSchool(schl)\n{\n\tthis.school = schl;\n}", "function handleSchoolSelect() {\n API.getTeachersBySchool(schoolRef.current.value)\n .then(res => {\n setTeachersSelect(res.data);\n })\n }", "_recalculate() {\n this._selectedSchools = Math.round(this._a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Forward any additions to the resource policy to the original secret. This is required because a secret can only have a single resource policy. If we do not forward policy additions, a new policy resource is created using the secret attachment ARN. This ends up being rejected by CloudFormation.
addToResourcePolicy(statement) { try { jsiiDeprecationWarnings.aws_cdk_lib_aws_iam_PolicyStatement(statement); } catch (error) { if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") { Error.captureStackTrace(error, this.addToResourcePol...
[ "addThreatProtectionPolicy(policy) {\n //update policy\n if (policy.uuid) {\n console.log(\"update policy: \");\n console.log(policy);\n return this.client.then(\n (client) => {\n return client.apis[\"Update Threat Protection Policy\"]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When mounting the component load versions from the sources passed as properties.
async componentDidMount() { for (const source of this.props.sources) { if (!this.state.computed.sources[source.name]) { if (source.options.versions) { if (Object.keys(source.options.versions).length > 0) { await this.loadVersionsFromSource(source); } } } ...
[ "async loadVersionsFromSource(source) {\n let versionList = [];\n Object.keys(source.options.versions).forEach((version) => {\n versionList.push({\n label: version,\n value: {\n sources: [source.name],\n },\n });\n });\n\n let allVersions = this.state.options.vers...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enumerablepartition([iterator = Prototype.K[, context]]) > [TrueArray, FalseArray] Partitions the elements in two groups: those regarded as true, and those considered false. By default, regular JavaScript boolean equivalence is used, but an iterator can be provided, that computes a boolean representation of the element...
function partition(iterator, context) { iterator = iterator || Prototype.K; var trues = [], falses = []; this.each(function(value, index) { (iterator.call(context, value, index) ? trues : falses).push(value); }); return [trues, falses]; }
[ "function partition(arr, partitioner) {\n let newArr = [];\n let trueArr = [];\n let falseArr = [];\n for (let i = 0; i < arr.length; i++) {\n if (partitioner(arr[i], i, arr) === true) {\n trueArr.push(arr[i])\n } else {\n falseArr.push(arr[i])\n }\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Jump the window view to a specific section sectionName is a string that represents the section id to jump to
function jumpto(sectionName){ //window.location.hash = sectionName; document.getElementById(sectionName).scrollIntoView({behavior: 'smooth'}); $('#dropdown').removeClass('show-dropdown'); $('#dropdown').addClass('hide-dropdown'); }
[ "function go_to_section($section) {\r\n $.scrollTo($section, {\r\n offset: settings.scroll_offset,\r\n duration: settings.scroll_duration\r\n });\r\n }", "function gotoSection(oElement)\r\n{\r\n\ttry{\r\n\t\t//debugger;\r\n\t\t//debugger;\r\n\t\tvar sLabe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return functionZ input values
function getFunctionzValues(quantDec,quantRes){ var funcValues = []; var xvalue = []; var maxOrMin = (($("#max").is(':checked')) ? -1 : 1); for (let i = 1; i <= quantDec; i++ ) { var input = $("input[name='valX"+i+"']").val() if( input.length == 0) { xvalue[i-1] = 0; } else { xvalue[i-1] = parseFl...
[ "function funcThree(z) {console.log('z = '+z)}", "function vector_98(x, y, z)\n{\n return float3_119 // [(Func Float Float Float Float3) | (Func (Array Float) Float3)]\n (x // Float\n ,y // Float\n ,z // Float\n ) // Float3\n ;\n}", "function getPazymiuVidurkis2(x1, x2, x3, x4, x5){\n\nlet pazymys = x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a dummy node to the graph and return v.
function addDummyNode(g,type,attrs,name){var v;do{v=_.uniqueId(name)}while(g.hasNode(v));attrs.dummy=type;g.setNode(v,attrs);return v}
[ "function addDummyNode(g, type, attrs, name) {\n\t var v;\n\t do {\n\t v = _.uniqueId(name);\n\t } while (g.hasNode(v));\n\n\t attrs.dummy = type;\n\t g.setNode(v, attrs);\n\t return v;\n\t}", "function addDummyNode(g,type,attrs,name){var v;do{v=_.uniqueId(name);}while(g.hasNode(v));attrs.dummy=type;g.se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find highest fitness for the population
getMaxFitness() { var record = 0; for (var i = 0; i < this.population.length; i++) { if (this.population[i].getFitness() > record) { record = this.population[i].getFitness(); } } return record; }
[ "getMaxFitness() {\n let record = 0;\n let index = 0;\n for (let i = 0; i < this.population.length; i++) {\n if (this.population[i].getFitness() > record) {\n record = this.population[i].getFitness();\n }\n }\n this.best = this.population[index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Array$prototype$equals :: Array a ~> Array a > Boolean
function Array$prototype$equals(other) { if (other.length !== this.length) return false; for (var idx = 0; idx < this.length; idx += 1) { if (!equals(this[idx], other[idx])) return false; } return true; }
[ "function Array$prototype$equals(other) {\n if (other.length !== this.length) return false;\n for (var idx = 0; idx < this.length; idx += 1) {\n if (!(equals (this[idx], other[idx]))) return false;\n }\n return true;\n }", "function eqArrays (array1,array2) {\n let result = false;\n\n if (arra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Like ``getCode`` but with the return value normalized so that ``NL`` is returned for ``NL_LIKE``.
getCodeNorm() { const c = this.getCode(); return c === NL_LIKE ? NL : c; }
[ "getCodeNorm() {\n const c = this.getCode();\n return c === NL_LIKE ? NL : c;\n }", "getCodeNorm() {\n const c = this.getCode();\n return c === NL_LIKE ? NL : c;\n }", "getCodeName(code) {\n var codes = {\n 1: \"Subnet Mask\",\n 3: \"Default Gateway\",\n 6: \"DNS Server\",\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces all found instance of the $$PATH_ID$$ placeholder in the supplied xml string
function opSetPathId(id, xml) { return xml.replace(/\$\$PATH_ID\$\$/g, id); }
[ "function opSetId(id, xml) {\r\n return xml.replace(/\\$\\$ID\\$\\$/g, id);\r\n}", "function replaceID(string, value, replace = ':id') {\n if(value !== null)\n return string.replace(\":id\",value);\n return string;\n}", "function opSetParentId(id, xml) {\r\n return xml.replace(/\\$\\$PARENT_ID\\$\\$/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create database related policies.
createPolicies() { if (this.app.isBound('gate')) { this.app.make('gate') .policy('http', () => { return this.app.make('config').get('http.enabled', false); }); } }
[ "createPolicies() {\n\t\tif (this.app.isBound('gate')) {\n\t\t\tthis.app.make('gate')\n\t\t\t\t.policy('db', () => {\n\t\t\t\t\tconst config = this.app.make('config');\n\n\t\t\t\t\treturn Boolean(config.get('database.command_namespace', null)) && config.get('database.enabled', false);\n\t\t\t\t});\n\t\t}\n\t}", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert array to line object
toLine() { return { x1: this[0][0], y1: this[0][1], x2: this[1][0], y2: this[1][1] }; }
[ "toLine() {\n return {\n x1: this[0][0],\n y1: this[0][1],\n x2: this[1][0],\n y2: this[1][1]\n }\n }", "toLine() {\n return {\n x1: this[0][0],\n y1: this[0][1],\n x2: this[1][0],\n y2: this[1][1],\n };\n }", "function line(data) {\n return c.line(data.map...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an array of attributes creates an array of cognitoUser attributes
function createUserAttributeList(attributes) { var attributeList = []; for(let i = attributes.length-1; i >= 0; i--) { attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute(attributes[i])); } return attributeList; }
[ "function createSignUpUserAttributeList(name,email,yId,userType=0) {\n\tvar attributeList = [];\n\tattributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({Name : 'name', Value : name}));\n\tattributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({Name : 'email', Value : email}));\n\tattributeLi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
===== ENABLE EXTENSION ICON (UNGRAYSCALE) =====
function setup_extensionIcon() { // Rules for page-matching; tells Chrome when to enable extension icon let rule1 = { conditions: [ // TODO: Make conditions more accurate, like the contextPatterns below new chrome.declarativeContent.PageStateMatcher({ pageUrl: {ho...
[ "function ExtensionLoaded()\n{\n setExtensionIcon();\n}", "function extIcon() {\n\tvar extf = document.getElementById('extIconFile');\n\tvar option = document.getElementById('createDialogFileType').value;\n\tif (option != '.html' && option != '.txt' && option != '.docx' && option != '.doc' && option != '.rtf') {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }