query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Create a split layout for the given panel options.
function createLayout(options) { return options.layout || new splitlayout_1.SplitLayout({ renderer: options.renderer || SplitPanel.defaultRenderer, orientation: options.orientation, alignment: options.alignment, spacing: options.spacing }); }
[ "function createLayout(options){return options.layout||new SplitLayout({renderer:options.renderer||SplitPanel.defaultRenderer,orientation:options.orientation,alignment:options.alignment,spacing:options.spacing});}", "function createLayout(options) {\n return options.layout || new SplitLayout({\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
renderTable renders the filteredAddresses to the tbody
function renderTable() { $tbody.innerHTML = ""; // Set the value of endingIndex to startingIndex + resultsPerPage var endingIndex = startingIndex + resultsPerPage; // Get a section of the addressData array to render var addressSubset = filteredAddresses.slice(startingIndex, endingIndex); for (var i = 0; ...
[ "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredAddresses.length; i++) {\n // Get get the current address object and its fields\n var address = filteredAddresses[i];\n var fields = Object.keys(address);\n // Create a new row in the tbody, set the index to be i + star...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes alwayShow fields that aren't in the schema.properties and warns on console.
fixAlwaysShow(schema) { const alwaysShow = schema.alwaysShow; schema.alwaysShow = alwaysShow.filter(key => { if (schema.properties[key]) { return true; } else { console.warn(`${key} is configured as alwaysShow but it is not in ${JSON.st...
[ "fixAlwaysShowRegExp(schema) {\n if (!schema.alwaysShow) {\n schema.alwaysShow = [];\n }\n Object.keys(schema.properties)\n .forEach(key => {\n // pass alwaysShowRegExp down to apply it recursively.\n const subSchema = schema.properties[key];\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Note: the `n` parameter used in calls to this are generally found by either trialanderror or by studying the source. If tests are failing, find the failing assertions, set `n` to about 10 on the preceding call to `waitCycles`, then drop them down incrementally until it fails. The last one to succeed is the one you want...
function waitCycles(n) { n = Math.max(n, 1) return new Promise(function(resolve) { return loop() function loop() { if (n === 0) resolve() else { n--; setTimeout(loop, 4) } } }) }
[ "function testAll(n) {\n console.log(n);\n let index = [];// indexes of breakable links\n let stop = false;\n let links = [];// One chain to analyse\n\n // Initialize results\n loggerInfo.set(n, { meanCollisionNb: 0, meanMonomereNb: 0, meanDimereNb: 0, meanTrimereNb: 0, meanOligoNb: 0, details: []...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this is the fuction used takes table and an array of data to insert it to the table on first row
function addTR(table, arrayOfData){ //takes the first row of the table var row =table.tBodies[0].insertRow(0); //looping through the data and creating as many TD and give them the data for(var i=0;i<arrayOfData.length;i++){ row.insertCell(i).innerHTML=arrayOfData[i]; } }
[ "function fillInTable(data){\n for (index = 0; index < data.length; ++index) {\n addRowToTable(data[index]);\n }\n\n }", "function tableRowInsert(a,b,c,d,e){\n arr = [];\n arr.push(a,b,c,d,e)\n table.push(arr);\n}", "function insertFirstData_Tablet( dbId )\n{\n\tvar insertTa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of schools based on the county provided.
function returnArrayOfSchools( county ) { switch (county) { case "Carlow": return ["Borris Vocational School, Borris","Carlow Vocational School, Carlow", "Coláiste Eoin, Hacketstown","Gaelcholáiste Cheatharlach, Easca", "Presentation / De La Salle College, Muine Bheag","Presentation College, Carl...
[ "function getSchoolsList(topojson) {\n schools = [];\n topojson.objects.counties.geometries.forEach(function(d) {\n var keys = [];\n for (var k in d.properties.schools) {\n keys.push(k)\n }\n\n keys.forEach(function(d) {\n if (schools.indexOf(d) < 0) {\n schools.push(d);\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================ / Password Confirmation Code Modified From / / By Sirus Doma / / ============================================ / Validates a password input against a paired password confirmation input / DO NOT: / assign the 'validate' class to the password confirmation input / DO: / assign t...
function pWordValidation(pWordInput, pWordConfInput) { // Prefix with # to create an id selector pWordInput = "#" + pWordInput; // Create label element selector let pWordConfLabel = `label[for="${pWordConfInput}"]`; // Prefix with # to create an id selector pWordConfInput = "#" + pWordConfInpu...
[ "function confirmPass() {\n if (pInput.value !== cpInput.value) {\n cpField.classList.add(\"error\");\n cpField.classList.remove(\"valid\");\n let passError = cpField.querySelector(\".error-txt\");\n pInput.value !== cpInput.value\n ? (passError.innerText =\n \"Confirm passw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
N = number of counters A = array of numbers
function maxCounters(N, A) { let countersArr = [0, 0, 0, 0, 0] arr.map((item) => { if (item > N) { const maxValue = Math.max(countersArr) for (i = 1; ) } else { countersArr[item-1] = countersArr[item-1] + 1 } }) return 'test' }
[ "function solution(N, A) {\n // N: number of counters, A: operations\n // 1. Create N length counter and set all values to 0\n // 2. Loop through an array A and check condition\n // 2-1. If A[K] = X(1 <= X <= N), increase X by 1\n // 2-2. If If A[K] = N + 1, set all counters to max\n // 3. Return counter arra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createCartItemView() / createCartModel() Creates a model for the shopping cart. This uses the ListModel as the prototype, but adds a few specific methods. The config parameter can contain the following properties: items (array of objects) initial items for the cart (optional)
function createCartModel(config) { var model = createListModel(config); model.getSubtotalPrice = function() { var idx; var subtotalPrice = 0; for (idx = 0; idx < this.items.length; ++idx) { subtotalPrice += this.items[idx].price; } return subtotalPrice.t...
[ "function createCartModel(config) {\n\tvar model = createListModel(config); //creates new ListModel instance\n\n\t//Loop over model's items array to add up prices.\n\tmodel.getTotalPrice = function() {\n\t\tvar i;\n\t\tvar totalPrice = 0;\n\t\tfor (i = 0; i < this.items.length; i++) {\n\t\t\ttotalPrice += this.item...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API test for 'ChangeDDnsClientHostname', Change hostname for DDNS client
function Test_ChangeDDnsClientHostname() { return __awaiter(this, void 0, void 0, function () { var in_rpc_test, out_rpc_test; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log("Begin: Test_ChangeDDnsClientHostname"); ...
[ "function updateHostname(){\n const serverName = $$.server.name.val();\n const hostname = serverName+DOMAIN_NAME;\n // set the hostname\n $$.server.hostname.val(hostname);\n\n isValidServerNameRegex() ? setInputCssValid($$.server.name) : setInputCssInvalid($$.server.name);\n }"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function Name: initChangePassword Description: Binding Events to change password Author: JoonChul Kim
function initChangePassword() { $('#txt_change_pasword_back').click(function() { hidePopup(); }); // Try sign up when click "change" button or press "Enter" key. $('#txt_change_pasword_square').click(function() { tryChangePassword(); }); enterKeyBind('#txt_change_pasword_curren...
[ "function updatePasswordEventHandler() {\n\t$('#login_dive').delegate('#pw_chg', 'click', function() { \n\t\tvar fflag=0;\n\t\tcloseOpenDialogs();\n\t\tchangePassword(fflag);\n\t});\n}", "changePassword(event) {\n var newState = this.mergeWithCurrentState({\n password: event.target.value\n });\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor with phrase parameter, converted to all lower case.
constructor(phrase){ this.phrase = phrase.toLowerCase(); }
[ "constructor(phrase)\r\n {\r\n // set phrase string to lowercase letters\r\n\r\n this.phrase = phrase.toLowerCase();\r\n }", "constructor(phrase){\n this.phrase = phrase.toLowerCase();\n }", "constructor(phrase) {\n this.phrase = phrase.toLowerCase();\n }", "constructo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send to client the last messages when subscribe to channel's update
function sendLast(subscr, channels) { this.db.getLastMsgs(channels) .then(function(data) { this.connection.notify(subscr, { notifications: data }); }.bind(this)); }
[ "function updateChannel() {\n tc.loadMessages();\n updateLastUpdate();\n }", "lastChannel() {\n this.playChannel(this.lastChannelNumber);\n }", "notify() {\n this.subscribers.forEach(subscriber => {\n subscriber.update();\n });\n }", "function sendLatestMessageToCl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether to hide options which have unused/empty values
function hideOptionUnusedValue(localStorage) { var value = localStorage["camelHideOptionUnusedValue"]; return Core.parseBooleanValue(value, Camel.defaultHideOptionUnusedValue); }
[ "function filterEmpty(opt) {\n return opt.option !== '';\n }", "get _emptyOptionsList() {\n\t\t\treturn !this._optionsLoading && !this._filteredOptions.length;\n\t\t}", "function getExcludedOptions() {\n ignoreConjunctions = chkConjunctions.checked;\n ignorePronouns = chkPronouns.checked; \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
componentWillMount runs once when component loads fetches all highlights from the database first sets an interval for fetching highlight count to 5s creates an interval object to later clear if needed sets the first numberOfVideosToShowPerPage highlights to be shown on the page
componentWillMount() { this.updateAllHighlights(); var updateInterval = setInterval(this.updateHighlightCount, timeBetweenNewHighlightsCheck); this.setState({interval: updateInterval}); }
[ "componentDidMount() {\n this.setVideos(this.state.currentIndex);\n setInterval(this.getCurrentTime, 1000);\n }", "componentDidMount() {\n if (this.props.colorsFiltered !== this.state.colorsFiltered) {\n this.setState({ colorsFiltered: this.props.colorsFiltered })\n setTimeout(_ => {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs DOM manipulation to show fight screen w/ friendly and enemy pokemon's data.
function enterFightMode(enemyType) { inFight = true; // Generate a random Pokemon var pokemonIndex = 0; if (enemyType === "wild") { pokemonIndex = (Math.round(Math.random() * 3) + 3); } else if (enemyType === "trainer") { pokemonIndex = Math.round(Math.random() * 6); } ranPok...
[ "displayFight() {\n //Delete boxes where players can move\n this.displayBoxToMove(this._player1, false);\n this.displayBoxToMove(this._player2, false);\n //Display the 2 boxes where are the players\n $(\"#c\" + this._player1.getX() + \"r\" + this._player1.getY()).css(\"backgroundC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(void)fillText:(NSString )text x:(float)x y:(float)y;
fillText(text, x, y) { CanvasManager.fillText(findNodeHandle(this), text, x, y) }
[ "text(text, x, y)\n\t{\n\t\tthis.pen.fillText(text, x, y + this.textBaseLinePosition())\n\t}", "function DrawText (text, x, y)\r\n{\r\n\tctx.fillText(text, (0.5 + x) | 0, (0.5 + y) | 0);\r\n}", "function DrawText (text, x, y)\n{\n\tctx.fillText(text, (0.5 + x) | 0, (0.5 + y) | 0);\n}", "function draw_text(x, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to clean the search
function cleanSearch() { setOrigin(null); setDestination(null); setSearchAvailable(false); setSearchPending(false); setSearchResults(null); setSearchError(false); }
[ "function cleanData(){\r\n\t_searchText =\"\";\r\n\t_searchType=\"\"; \r\n\t_startIndex = 0;\r\n\t_previousIndex = 0;\r\n}", "function _clearSearchString(){\r\n\t\tcriteriaChngFlds=new Array();\r\n\t \toprs=new Array();\r\n\t \tvalues=new Array(); \t \r\n\t\tsrchStr=\"\";\r\n\t\tinsideCrteria=false;\r\n\t\toper=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens an SQLite connection to `file`, caches the connection, and upgrades the database schema if necessary.
function openConnectionTo(file) { let connection = connections.get(file.path); if (!connection) { connection = Services.storage.openDatabase(file); switch (connection.schemaVersion) { case 0: connection.executeSimpleSQL("PRAGMA journal_mode=WAL"); connection.executeSimpleSQL( ...
[ "function openConnectionTo(file) {\n const CURRENT_VERSION = 3;\n\n let connection = connections.get(file.path);\n if (!connection) {\n connection = Services.storage.openDatabase(file);\n let fileVersion = connection.schemaVersion;\n\n // If we're upgrading the version, first create a backup.\n if (f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1. This function is responsible for fetching the top stories from the api 2. The api returns the id of all the top stories as an array 3. On successful response we update the topStories in our redux store
fetchTopStories(){ var self = this; axios.get('https://hacker-news.firebaseio.com/v0/topstories.json') .then(function (response) { self.props.setLoaderText('Fetching stories'); // This is done because, once the top stories are fetched, the individual stories have to be fetched again,...
[ "function topStories() {\n //fetch the top stories by hacker news api\n fetch('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')\n .then(function (response) {\n return response.json();\n })\n .then(function (fetchedIds) {\n //call the function to display the stories\n lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to render direction buttons
function renderDirectionButtons() { let isPrevBtnActive = activeQstnIdx > 0; let isNextBtnActive = activeQstnIdx < totalQstnsCount - 1; return ( <> <BasicButton key={0} text="Prev" customStyle={isPrevBtnActiv...
[ "displaySortDirection() {\n switch (this.currentSortDir) {\n case \"asc\":\n return \"▲\";\n case \"desc\":\n return \"▼\";\n }\n }", "function directionalButtons() {\r\n if ($(\".gallery__panel--active\").prev().length == 0) {\r\n $(\".gallery__contr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override's native Array methods that manipulate the array
function ObservableArray$_overrideNativeMethods() { this["copyWithin"] = ObservableArray$copyWithin; this["fill"] = ObservableArray$fill; this["pop"] = ObservableArray$pop; this["push"] = ObservableArray$push; this["reverse"] = ObservableArray$reverse; this["shift"] = ObservableArray$shift; ...
[ "function AugmentedArray(callback, settings) {\n var methods = 'pop push reverse shift sort splice unshift'.split(' ');\n forEach(methods, function eachArrayMethod(method) {\n this[method] = function augmentedMethod() {\n // flag that we're about to change (used later in bind...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Driver factory which takes a configuration object and returns a driver. This drivers runs live query on a repository fetching data about bounded contexts. The configuration object maps a context to a function which receives a query and returns a stream of data matching that query.
function makeDomainQueryDriver(repository, config) { return function (sink) { // not used, this is a read-only driver void sink; return { getCurrent: function query(context, payload) { __WEBPACK_IMPORTED_MODULE_2__contracts_src_index__["a" /* assertContract */](__WEBPACK_IMPORTED_MODULE_1_r...
[ "function makeDomainQueryDriver(repository, config) {\n return function (sink) {\n // not used, this is a read-only driver\n void sink;\n\n return {\n getCurrent: function query(context, payload) {\n (0, _index.assertContract)((0, _ramda.complement)(_ramda.isNil), [config[context]], 'makeDomai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the given link is relevant for the extension
static isLinkRelevant(link) { // exclude file protocol links -> they are not working with the office URI protocols if (link.startsWith('file://')) { return false; } if (LinkUtil.isWopiFrameLink(link)) { // check if the file ending is relevant let linkInfo = LinkUtil.getLinkInfo(link);...
[ "static isLinkRelevant(link) {\n // exclude file protocol links -> they are not working with the office URI protocols\n if (link.startsWith('file://')) {\n return false;\n }\n\n if (LinkUtil.isWopiFrameLink(link)) {\n return true;\n }\n // only consider segment after last slash\n cons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resizes the terminal instance to fit its parent container. Once the new dimensions are established, the calculated columns and rows are passed to the pseudoterminal (pty) to remain consistent.
_didResize() { // Resize Terminal to Container this.terminal.fit(); // Update Pseudoterminal Process w/New Dimensions this.pty.resize(this.terminal.cols, this.terminal.rows); }
[ "@bind\n onTerminalResize({ cols, rows }) {\n this.shell.resize(cols, rows)\n }", "_resizeTerminal() {\n fit_1.fit(this._term);\n if (this._offsetWidth === -1) {\n this._offsetWidth = this.node.offsetWidth;\n }\n if (this._offsetHeight === -1) {\n this._offse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a string describing the type / value of the provided input.
function valueDescription(input) { if (input === undefined) { return 'undefined'; } else if (input === null) { return 'null'; } else if (typeof input === 'string') { if (input.length > 20) { input = input.substring(0, 20) + "..."; } return JSON.string...
[ "function valueDescription(input) {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = input.substring(0, 20) + \"...\";\n }\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Looping dengan mengalikan dengan angka sebelumnya dengan selisih paramater kedua Sample Input : totalLompat(12, 5) Output : 12 7 2 = 168
function totalLompat (number, dif) { var total = 1; for (var i = number; i >= 1; i -= dif) { total *= i; } return total; }
[ "function totalLompat (number, dif) {\n // Cek apakah ini angka terakhir / terkecil yang ingin ikut dihitung\n if (number == 1) {\n // Jika kembalikan nilainya\n return 1;\n // Cek kembali, apakah 'number' lebih besar dari dif (pembeda / selisih ke angka selanjutnya)\n } else if (number > dif) {\n // J...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO Problem / Explicit Requirements: INPUT = 2 arrays containing list of numbers OUTPUT = 1 new array containing the products of all combinations of number pairs existing between the two arrays. And this array should be sorted in ascending order. RULES = neither argument will be empty. Implicit Requirements: Questions...
function multiplyAllPairs(array1, array2) { let resultArray = []; array1.forEach(array1Element => { array2.forEach(array2Element => { resultArray.push(array1Element * array2Element); }) }) return resultArray.sort((a, b) => a - b); }
[ "function multiplyAllPairs(arr1, arr2) {\n var products = [];\n\n arr1.forEach(function (num1) {\n arr2.forEach(function(num2) {\n products.push(num1 * num2);\n });\n });\n\n return products.sort(function (a, b) {\n return a - b;\n });\n}", "function multiplyAllPairs(inputArr1, inputArr2) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions sets the table with the torrents Sets torrentTable
function setTorrentTable(){ return torrentTable = document.getElementsByTagName("table")[8]; }
[ "function setTorrentTable(){ \n \treturn torrentTable = document.getElementsByTagName(\"table\")[8];\n}", "function setTable() {\n console.log('setting Table: ', current_table);\n setQueryParam('table', current_table);\n\n\n events = cache['events'];\n users = cache['users'];\n projects = cache['pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper to load the state from localStorage with the STORAGE_KEY as the key
function loadState () { var state = localStorage.getItem(STORAGE_KEY); if (!state) { state = DEFAULT_STATE; saveState(state); } else { state = JSON.parse(state); } return state; }
[ "load() {\n this.state_ =\n JSON.parse(localStorage.getItem(this.key_)) || this.defaultState_;\n }", "function loadState(state = {}) {\n for (let i = 0; i < localStorage.length; i++) {\n const prop = localStorage.key(i)\n const value = JSON.parse(localStorage.getItem(prop) || 'null')\n if (!!...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It returns the page object either extended by a /Annots field, if this did not exist yet or with the annots field replaced by a rerference pointer to an array if the page object contains the list of annotations directly ptr : Pointer to the page object annot_array_reference : The reference to the annotation array
adaptPageObject(page, annot_array_reference) { if (!page.object_id) throw Error("Page without object id"); let ret = []; let lookupTable = this.parser.documentHistory.createObjectLookupTable(); let page_ptr = lookupTable[page.object_id.obj]; if (page_ptr.compressed) {...
[ "static replaceAnnotsFieldInPageObject(data, page, page_ptr, annot_array_reference) {\n let ptr_objend = util_1.Util.locateSequence(util_1.Util.ENDOBJ, data, page_ptr, true);\n let complete_page_object_data = data.slice(page_ptr, ptr_objend + util_1.Util.ENDOBJ.length);\n let ret = [];\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to check if uid exists in array
function checkForUid(arr, uid){ var duplicate = false; for (var i = 0; i < arr.length; i++) { if(arr[i].$value === uid) { arr.$remove(arr[i]); duplicate = true; } }; return duplicate; }
[ "function arrayContains(array, uID){\n\tfor(var i = 0; i < array.length; i++){\n\t\tif(array[i].userId == uID){\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function isContactAlreadyInList(uid, list) {\n return jQuery.inArray(uid, list);\n}", "hasSubUserIds() {\n let nUid = 0;\n for (let i in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Goodreads Constructor Function Wrapper for Goodreads API:
function Goodreads() { this.ApiRoot = 'https://www.goodreads.com/'; }
[ "constructor(name, age, numBooksRead) {\n this.name = name;\n this.age = age;\n this.numBooksRead = numBooksRead;\n }", "function Goods (name, barcode, sellPrice, buyPrice) {\n this.name = name;\n this.barcode = barcode;\n this.sellPrice = sellPrice;\n this.buyPrice = buyPrice;\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
utility function to check whether the content displayed is present or not inputMsg any string in response object return empty string if input is undefined and returns the string if present
function checkMessage(inputMsg) { if(inputMsg == undefined){ return ""; } else{ return inputMsg; } }
[ "checkString(inputString) {\n let outputText = inputString\n if (inputString === undefined) {\n outputText = \"no details\"\n }\n if (inputString == null) {\n outputText = \"no details\"\n }\n return outputText\n }", "getDisplayMessage() {\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Goes through an array of results and adds a score field to each one. The score field be set to how well the text in each result's searchField matches with each word in the query.
function scoreResults(query, searchField, results) { results.forEach(function (result) { result.score = scoreString(query.toLowerCase(), result[searchField].toLowerCase()); }); }
[ "function rankResults(matches, query) {\n query = query || '';\n matches = matches || [];\n\n // We replace dashes with underscores so dashes aren't treated\n // as word boundaries.\n var queryParts = query.toLowerCase().replace(/-/g, '_').match(/\\w+/g) || [''];\n\n for (var i = 0; i < matches.length; i++) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the root to a binary tree, create a list of all the nodes at each level
BTreeLevelToList(root){ let result = []; let currLevel = []; let parents; if(root != null){ currLevel.push(root); } while(currLevel.length != 0){ result.push(currLevel); // add previous level parents = currLevel; currLevel =...
[ "function treeToLevelList(root, level){\n var children = root['nodes'] || [];\n children = children.slice();\n delete root['nodes'];\n root.level = level;\n list = [root];\n children.forEach(function(child){\n list = list.concat(treeTo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether a prop name is a valid `MotionProp` key.
function isValidMotionProp(key) { return validMotionProps.has(key); }
[ "function isValidMotionProp(key){return validMotionProps.has(key);}", "function isValidMotionProp(key) {\n return validMotionProps.has(key);\n}", "function isValidMotionProp(key) {\n return (key.startsWith(\"while\") ||\n (key.startsWith(\"drag\") && key !== \"draggable\") ||\n key.startsWith(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calcExcelSerial1900 Perform calculation starting with an Excel 1900 serial date
function calcExcelSerial1900() { var d = new Number(document.excelserial1900.day.value); /* Idiot Kode Kiddies didn't twig to the fact (proclaimed in 1582) that 1900 wasn't a leap year, so every Excel day number in every database on Earth which represents a date subsequent to February 28, 1900 is off...
[ "function calcExcelSerial1900()\n{\n var d = new Number(document.excelserial1900.day.value);\n\n /* Idiot Kode Kiddies didn't twig to the fact\n (proclaimed in 1582) that 1900 wasn't a leap year,\n so every Excel day number in every database on Earth\n which represents a date subsequent to F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process the latency test result
processResult() { this.test.result.latency = { status: this.status, progress: 0 }; if (this.status <= STATUS.WAITING) return; const durationFromInit = Date.now() - this.initDate; const progress = durationFromInit / this.test.config.latency.duration; this.test.result.latency.progress...
[ "processResult() {\n this.test.result[this.step] = {\n status: this.status,\n progress: 0\n };\n if (this.status <= STATUS.WAITING) return;\n\n const durationFromInit = Date.now() - this.initDate;\n const durationFromStart = Date.now() - this.startDate;\n const progress = durationFromIni...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of build resource IDs associated with a specific app.
function getAllBuildIDsForApp(api, id, query) { return api_1.GET(api, `/apps/${id}/relationships/builds`, { query }) }
[ "function getAppResourceIDForBuild(api, id) {\n return api_1.GET(api, `/builds/${id}/relationships/app`)\n}", "function listAllBuildsForApp(api, id, query) {\n return api_1.GET(api, `/apps/${id}/builds`, { query })\n}", "getIdsForApps({ user_id, app_secret, app, page, access_token, }) {\n return th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
data structures a set implementation with ordering
function OrderedSet(initial_values, cmp_fn) { cmp_fn = def(cmp_fn, cmp); // @member values var values = []; this._findIndex = function (value) { if (values.length === 0) return 0; else if (cmp_fn(values[values.length - 1], value) === -1) return values.length; else // linear search...
[ "function SortedSet() {\n this.items = [];\n this.hash = {};\n this.values = {};\n this.OPEN = 1;\n this.CLOSE = 2;\n }", "function mySet(){\n //holde the set\n let collection=[];\n //if the item is not in the collection will return -1\n this.has = function(element){...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the connection protocol.
getProtocol() { return super.getAsString("protocol"); }
[ "getProtocol() {\r\n return this._protocol;\r\n }", "get protocol() {\n this._logService.debug(\"CMMethod.get protocol\");\n\n return this._protocol;\n }", "type() {\n return this.protocol[Object.keys(this.protocol)[0]].protocol\n }", "function YSerialPort_get_protocol()\n {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
eCSStender::isInheritedProperty() tests whether the given property is inherited
function isInheritedProperty( obj, prop ) { var c = obj.constructor; if ( c && c.prototype ) { return obj[prop] === c.prototype[prop]; } return true; }
[ "function isPropertyInClassDerivedFrom(prop, baseClass) {\n return forEachProperty(prop, function (sp) {\n var sourceClass = getDeclaringClass(sp);\n return sourceClass ? hasBaseType(sourceClass, baseClass) : false;\n });\n }", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In this challenge, we learn about strings and exceptions. Check out the attached tutorials for more details. Task Complete the reverseString function; it has one parameter, s. You must perform the following actions: Try to reverse string using the split, reverse, and join methods. If an exception is thrown, catch it an...
function reverseString(s) { try{ s = s.split("").reverse().join("") } catch(c){ console.log(c.message) } finally{ console.log(s) return } }
[ "function reverseString(s) {\n //code block\n try {\n console.log(s.split('').reverse().join(''));\n } catch (e) {\n console.log(e.message);\n console.log(s);\n }\n}", "function reverseString(s) {\n\ttry{\n s = s.split('').reverse().join('');\n }catch(ex){\n conso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a country filter
function removeCountryFilter(country) { var match = matchVoiceToDataCase(data, columnIndex, country); activeSheet.applyFilterAsync( "Country / Region", match, tableau.FilterUpdateType.REMOVE); }
[ "function removeCountryFilter() {\n if (countryFilter.length !== 0) {\n const selectedCountry = countryFilter[0];\n countryFilter = countryFilter.filter(f => f !== selectedCountry);\n chordChart.highlightActiveCountry(selectedCountry);\n mapChart.highlightActiveCountry(selectedCountry...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using constructor here to set state initially with user email
constructor(props) { super(props); this.state = { editing: false, email: this.props.user.email, first_name: this.props.user.first_name, last_name: this.props.user.last_name, }; }
[ "constructor(props) {\n super(props);\n this.state = {\n // isLoggedIn is false because a user is not logged in and there is no username or email so they're null\n isLoggedIn: false,\n username: null,\n email: null,\n };\n }", "constructor(props)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force 'name' env variable to have value of 'value'.
setEnvVar(name, value) { // Set variable both as env var and as step variable, which might be re-used in subseqeunt steps. process.env[name] = value; this.baseLib.setVariable(name, value); this.baseLib.debug(`Set variable and the env variable '${name}' to value '${value}'.`); }
[ "env(name, value) {\n this._env[name] = value;\n }", "setEnvVar(name, value, callback) {\n this.query('SET @' + name + ' = ' + this.escape(value), [], (results, error) => {\n callback(results, error);\n });\n }", "function setEnvVar (name, value) {\n return new Promise((resolve, reject) =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the list of validators that may contain both functions as well as classes, return the list of validator functions (convert validator classes into validator functions). This is needed to have consistent structure in validators list before composing them.
function normalizeValidators(validators) { return validators.map(function (validator) { return isValidatorFn(validator) ? validator : function (c) { return validator.validate(c); }; }); }
[ "function normalizeValidators(validators) {\n return validators.map(function (validator) {\n return isValidatorFn(validator) ? validator : function (c) {\n return validator.validate(c);\n };\n });\n }", "function normalizeValidators(validators) {\n return validators.map(functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update a parent variable with the selected radio button value.
function updateParent(radio,parentVar) { var val = getSelectedRadio(radio); parentVar.value = val; self.close(); }
[ "function set_radiobutton_value(thisName, value) {\n\t\t$(\"input[name=\"+thisName+\"][value=\" + value + \"]\").attr('checked', 'checked').change();\n\t}", "updateValue() {\r\n this.getParent().setValue(this.state.value);\r\n }", "function select_parent_radio(p_radio_obj, p_checkbox_obj, v_parent_id)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AWEI_nsh: 4 (G SWIR1) (0.25 NIR + 2.75 SWIR2)
function AWEI_nsh(image) { var awei_nsh = image.expression( "4 * (G - SWIR1) - (0.25 * NIR + 2.75 * SWIR2)", { "G": image.select("B3"), "NIR": image.select("B5"), "SWIR1": image.select("B6"), "SWIR2": image.select("B7") } ); return image.addBands(awei_nsh.rename("AWEI_nsh")); }
[ "function AWEI_nshs2(image) {\n var awei_nsh = image.expression(\n \"4 * (G - SWIR1) - (0.25 * NIR + 2.75 * SWIR2)\",\n {\n \"G\": image.select(\"B3\"),\n \"NIR\": image.select(\"B8\"),\n \"SWIR1\": image.select(\"B11\"),\n \"SWIR2\": image.select(\"B12\")\n }\n );\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
color of the answers when you click submit. Of course when you click next the borders should all change back to black. modify the function below! I am proud of you! <3
function submit(){ console.log("click"); if(document.getElementById('Submit').innerHTML=="Submit"){ //Make the 3 incorrect answers red border, and the correct one green. Just assume that the // correct one is the 3rd one for now. // ---- // ---- document.getE...
[ "function answerColor(correct) {\n //Green\n if (correct) {\n $(\"body\").attr(\"class\", \"correct-body\");\n $(\"#quiz-form\").attr(\"class\", \"correct-form\");\n $(\"#continue\").attr(\"class\", \"correct\");\n }\n //Red\n else {\n $(\"body\").attr(\"class\", \"incorrect-body\");\n $(\"#qui...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggles the status between PAUSED and PLAYING and plays/pauses the audio
function toggleStatus() { if (audioRef.current) { if (status === 'PAUSED') { audioRef.current.play() setStatus('PLAYING') } else { audioRef.current.pause() setStatus('PAUSED') } } }
[ "togglePlayback () {\n let state = this.$data._player.getState()\n\n switch (state) {\n case window.ya.music.Audio.STATE_PLAYING:\n this.$data._player.pause()\n break\n\n case window.ya.music.Audio.STATE_PAUSED:\n this.$data._player.resume()\n break\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the sprites names
function getSpriteArray(s) { for (var i = 0; i < s.length; i++){ sprites.push(s[i].objName); } return sprites; }
[ "listSprites() {\n const sprites = [];\n this.listSpritesRecursive(this.owner, sprites);\n return sprites;\n }", "listSprites() {\n\t\t\tconst sprites = [];\n\t\t\tthis.listSpritesRecursive(this.owner, sprites);\n\t\t\treturn sprites;\n\t\t}", "function listFrames(sprites){\n\t// Gets the fram...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
value associated with the given key in subtree rooted at x; null if no such key
function get(x, key) { while (x != null && x != undefined) { var cmp = key.localeCompare(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.value; } return null; }
[ "get(key) {\n let cmp;\n let node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ List of networks as of the last scan.
function list() { return networks; }
[ "function getNetworks(){\n\t//gets the local simulation//\n\tvar local_session = get_local_session();\n\t//gets the configuration map of the current simulation on the users side\n\tvar map = local_session.config_map;\n\t// a list of all of the networks in the simulation\n\tvar list = []; \n\t//populates list\n\tfor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compile the command to disable foreign key constraints.
compileDisableForeignKeyConstraints() { return 'SET FOREIGN_KEY_CHECKS=0;'; }
[ "enterDisable_constraint(ctx) {\n\t}", "exitDisable_constraint(ctx) {\n\t}", "dropForeign(columns, indexName) {\n indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('foreign', this.tableNameRaw, columns);\n this.pushQuery(`alter table ${this.tableName()} drop foreign key ${indexNa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes all ordered lists of type loweralpha to the bullet style given
function apply_list_style(style) { $('ol[style]').filter(function () { return (/list-style-type:\s*lower-alpha/).test($(this).attr('style')); }).attr('style', 'list-style-type: ' + style + ';'); }
[ "function convertBullets(str, color) {\n var s = color ? '{inverse}' : '<b>',\n e = color ? '{/inverse}' : '</b>';\n return str.replace(letterBullets, '$1'+s+'$2'+e+'$3')\n .replace(numberBullets, '$1'+s+'$2'+e+'$3')\n .replace(symbolBullets, '$1'+s+'$2'+e+'$3');\n}", "function Bullet...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a new atom
addNewAtom(curAtom, atoms, changes, x, y) { var newAtom = new Atom(new Coord(x, y, 0), curAtom.atom.atomicSymbol, curAtom.atom.elementName, curAtom.atom.atomicRadius, curAtom.atom.atomColor, null, new Set()); atoms.add(newAtom); changes.push({type:"atom", payLoad:newAtom, action:"added", overwri...
[ "async addAtom(data) {\n\t\tthrow this.exception[1]()\n\t}", "function addAtom(AtomicNum, x, y, z, cysid) {\n\n // Declare local variables\n var i;\n var numatoms;\n var molecule = Mol();\n var bonds = BondMatrix();\n\n // Create/fill molecular array\n molecule[0].numatoms++;\n numatoms = molecule[0].numa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find unused ID for new assignment
function assignmentsGetNewId() { var maxId = 0; for (var i=0; i<assignments.length; i++) if (assignments[i].id > maxId) maxId = assignments[i].id; return maxId+1; }
[ "checkForReleasedIds(){\n for(let i = 0; i < this[usedIds].length; i++){\n let id = this[usedIds][i];\n if(id.Available === 1){\n this[usedIds].splice(i, 1);//remove from usedlist\n this[unusedIds].push(id);\n }\n }\n this.Amount = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
boolean updatelist ( void ) Provides the functionality to update the loggedinlist element with the logged in users names and logout links.
function updatelist() { // get the #logged-in-list element var list_element = document.getElementById('logged-in-list'); // check the element exists if (list_element) { // get the #logged-in element var list_container_element = document.getElementById('logged-in'); // check the element exists and...
[ "function updateUserList()\n{\n\t// Get the user list.\n\tvar e_list = document.getElementById(\"db_userlist\");\n\t\n\t// If there's no list, early out...\n\tif (!e_list)\n\t{\n\t\treturn;\n\t}\n\t\n\t// Set up a variable to store the html.\n\tvar d_html = \"\";\n\t\n\t// Set the room prefix.\n\td_html += \"#\" + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to get current Dice Array
function currentDiceArray() { let choosenDicesArr = []; for (let i = 1; i <= 5; i++) { let curDice = "dice" + i; let diceValue = document.getElementById(curDice).src; diceValue = diceValue.slice(diceValue.length - 5, diceValue.length - 4); choosenDicesArr.push(Number(diceVa...
[ "function diceValues (noOfDice) { \r\n for (i=0 ; i < noOfDice ; i++ )\r\n dice[i] = roll() \r\n return dice\r\n}", "function getPlayersDice() {\n let dices = [];\n for (let i = 0; i < 3; i++) {\n dices.push(randomDice());\n };\n return dices;\n}", "function getValues() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear all modals/modal elements on screen
function clearModals(){ $('#updateFailed').css('display', 'none'); $('#updateComplete').css('display', 'none'); $('#portWarningMessage').css('display', 'none'); $('#configWarningMessage').css('display', 'none'); $('#updateModalFooter [data-dismiss="modal"]').css('display', 'none'); $('#warningMo...
[ "function clearModals() {\n $('.modal.in').remove();\n $('.modal-backdrop').remove();\n this.next();\n}", "function clearModals() {\n $('body').removeClass('modal-open');\n $('.suggestions').removeClass('modal');\n}", "function modalpurge(){\n $('#modaltitle').empty();\n $('#modalbody').empty();\n $...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
button style when clicked
clickStyle() { this.normalStyle(); }
[ "actionOnClick(){\n continueButton.setStyle({ color: '#ff0'});\n }", "activate() {\r\n this.setTextColor(ACTIVE_BUTTON_TEXT_COLOR);\r\n }", "function colorThemOwn() {\n button.style.background = buttonValue;\n }", "function buttonSelect(button, on) {\n if (!on && butto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
google sign out function
function googleSignOut() { var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { console.log('User signed out.'); }); }
[ "function googleAuthSignOut(){\n\tvar auth2 = gapi.auth2.getAuthInstance();\n auth2.signOut().then(function () {\n \tauth2.disconnect();\n });\n}", "function signOutGoogle() {\n var auth2 = gapi.auth2.getAuthInstance();\n auth2.signOut().then(function () {\n console.log('User signed out.');\n });\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
custom features example / This simply displays the results of another query (as specified in the config with the name 'exampleQuery') The idea is that the query is already loaded
featureEXAMPLE(config,data) { if(data.additional && data.additional.exampleQuery) { //the query key in the config set to "exampleQuery" return { value: `${data.additional.exampleQuery[0].apps} apps reporting`, tooltip: `There could be even more detail here`} } }
[ "query( string = false ) {\n \n // Get the blacklist of features.\n const blacklist = self.blacklist;\n \n // Get the features.\n const features = self.features.reduce((object, feature) => { \n \n // Handle feature data in o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gallons per liter Converts a given mpg value to kpl
function mpg2kpl(mpg) { return mpg * KPM * GPL }
[ "function mpg2lp100km(mpg){\n var lp100k = ((100 * 3.785411784) / (1.609344 * mpg)).toFixed(2);\n\t\n\treturn lp100k[lp100k.length - 1] === 0 ? lp100k.toFixed(1) : lp100k;\n}", "function mpg2lp100km(x){\n return +(378.5411784 / x / 1.609344).toFixed(2);\n}", "function converter (mpg) {\n //code to convert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a single url to an Uploadcare file object wrapped in a promiselike object. Group urls that get passed here were not a part of a complete and untouched group, so they'll be uploaded as new images (only way to do it).
function getFile(url) { const groupPattern = /~\d+\/nth\/\d+\//; const uploaded = url.startsWith(CDN_BASE_URL) && !groupPattern.test(url); return _uploadcareWidget.default.fileFrom(uploaded ? 'uploaded' : 'url', url); }
[ "addImageResourceFromUrl (itemId, owner, filename, url) {\n return fetchImageAsBlob(url)\n .then((blob) => {\n // upload as a resources\n return this.uploadResource(itemId, owner, blob, filename);\n });\n }", "function loadImagesFromUrlAsync(url) {\n\treturn fetch(url)\n\t\t.then(resp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Has it moved offscreen?
offscreen() { if (this.x < -this.w) { return true; } else { return false; } }
[ "isOffScreen() {\n if (this.x > 923 || this.x < 0 || this.y > 480 || this.y < 465) {\n return true;\n }\n return false;\n }", "offscreen() {\n if (this.x < -this.w) {\n return true;\n } else {\n return false;\n }\n }", "isOffScreen() {\n if (this.x > width || this.x < 0 || ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count the number of hosts based on a subnet mask
function hostCount(aMask) { var bits = 32 - octet2cidr(aMask); // get # of addresses in network and subtract 2 return Math.pow(2,bits) -2; }
[ "function hostCount(aMask) {\n if (octet2cidr(aMask) == -1) {\n return 1;\n } else if (octet2cidr(aMask) == 31) {\n /* here we manage the RFC3021 */\n return 3;\n } else {\n var bits = 32 - octet2cidr(aMask);\n // get # of addresses in network and subtract 2\n return Math.pow(2, bits) - 2;\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Challenge 4: Write a function that will remove the last item in the buyList, and put it in the fridge.
function moveDown() { //your code const fromBuyList = buyList.pop(); if (fromBuyList) { fridge.push(fromBuyList); updateDisplay(); } else { return; } }
[ "function moveDown(){\n //your code\n if (buyList.length != 0){\n var counterBuyList = buyList.length - 1;\n fridge.push(buyList[counterBuyList]);\n buyList.pop();\n display();\n }\n}", "function moveUp(){\n //your code\n if (fridge.length != 0){\n var counterFrid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redux Thunk that fetches the data for related Metrics
function fetchRelatedMetricData() { return (dispatch, getState) => { const store = getState(); const { primaryMetricId, filters, granularity, currentStart, currentEnd, compareMode } = store.primaryMetric; const offset = COMPARE_MODE_MAPPING[compareMode] || 1; ...
[ "async getMetrics() {\n try {\n const { data } = await this._httpClient.get(`${url}/metrics`, config)\n return data\n }\n catch (err) {\n console.error({ \"Error\": err.message })\n }\n }", "function getMetrics(type) {\n $.ajax({\n url : prefix + \"/proxy/metrics/by-type/\" + type,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the OSM Map as a layer
function osmMapLayer() { var layer = new ol.layer.Tile({ source: new ol.source.OSM() }); return layer; }
[ "function getOsmGraph() {\n\t\tconsole.log(\"[*] OSM Graph Map\");\n\t\t\n\t\t// Setup our two layer objects\n\t\tmap_layer = new OpenLayers.Layer.OSM({isBaseLayer: true});\n\t\t\n\t\tmap.addLayers([map_layer,]);\n\t\treturn;\n\t}", "function getMap() {\n var layer = m_this.layer();\n if (!layer) {\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make attack point draggable
function makeIconAttackPointDraggable(){ //Let the item to be draggable $( '#ui_icon_attack_point' ).draggable({ cursor: "move", revert: true, start: function(event, ui){ //$(this).children( '.item_info' ).css('display', 'none'); }, stop: function(event, ui){ //$(this).parent().css('z-index', 'auto'...
[ "function draggable(){\r\n interact('.draggable')\r\n\t.draggable({\r\n\t // enable inertial throwing\r\n\t inertia: true,\r\n\t // keep the element within the area of it's parent\r\n\t restrict: {\r\n\t\trestriction: \"parent\",\r\n\t\tendOnly: true\r\n\t },\r\n \r\n\t // call this function on every dragmo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Emit a custom "chart" event when the transition completes and drawing is done. Report the event immediately if we're not called on a transition Note that we dont't take into account any subsequnet
function drawCompleteNotify(transition, node) { if (transition.ease) { transition.each("end", report); } else { report(); } function report() { var eventInfo = {detail: {drawComplete:true}, bubbles:true}; node.dispatchEvent(new CustomEvent("chart", eventInfo)); } }
[ "transitionCompleted() {\n // implement if needed\n }", "drawGraph() {\n logger.debug(`${logContext}.drawGraph<${SpeakingTime.graphType}>: entered`);\n const chart = this.chart;\n\n const chartData = this.getGraphData();\n\n chart.data = chartData;\n\n // Is th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DESC: 0 session id
function xqserver_msgadd_0sessionid(){ setup(g_qwUserId); engine.MsgAdd(0,++l_dwSequence,QWORD2CHARCODES(g_qwUserId),1,g_dwAllowDuplicatesQType,g_bstrAllowDuplicatesQTypeData,g_dwAllowDuplicatesQTypeDataSize); engine.MsgList(l_dwSessionID,++l_dwSequence,g_qwUserId.dwHi,g_qwUserId.dwLo,g_dwAllowDuplicatesQType,g_q...
[ "function getSessionId() {\n\t return defaultSessionId;\n\t}", "function generateSessionId () {\n\tvar id = Math.random().toString(36);\n\twhile (typeof active_sessions[id] !== 'undefined')\n\t\tid = Math.random().toString(36);\n\treturn id;\n}", "function clearSessionID() {\n\t// we have a hardcoded timeout...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setter for the data property (will set the data passed to the tableview)
set data(arr) { this.wrapper.setData(arr); this._tableData = arr; }
[ "setData() {\n\t\tthis.data = this.getData()\n\t}", "set data(val) {\n this._data = val;\n }", "setData(data) {\n this.data = data;\n }", "setData(data) {\n this.data = this.addDefaultData(data);\n this.resetCache();\n }", "set data(data) {\n this.dataService.data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should be called every frame. Updates camera controls and polls gamepad state.
update(){ this.cameraControl.update(); // Need to poll for gamepads. Because Chrome. this.checkGamepads(); for (var j in this.controllers) { if(!(j in this.gpBtnCallbacks)){ continue; } var controller = this.controller...
[ "function updateCamera() {\r\n realityBuilder.camera().update(cameraDataFromControls());\r\n }", "updateCamera() {\n //this.camera = this.cameras[this.selectView];\n //this.interface.setActiveCamera(this.camera);\n this.gameOrchestrator.cameraAnimationTime = null;\n this.game...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solution 2 External function deals only with passengerArray and returned function deals with specific name
function makeTorpedoAssigner(passengerArray) { // only pass in external function return function (name) { // internal function deals with specific name for (var i = 0; i < passengerArray.length; i++) { // since loop is inside the returned function, i will come directly from that local scope ...
[ "function makeTorpedAssigner (passengerArray){ //\n\t return function (name){\n\t\t for(var i = 0; i < passengerArray.length; i++){ //this \n\t\t \talert(\"Ahoy, \" + name + \"!\\n\" + \n\t\t\t\t\t\"Man your post at Torpedo #\" + (i + 1) + \"1\"\n\t\t }\n\t };\n}\n}", "function nonFriends(name, array) {\n\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculating Occupancy for Residential building types
function residentialType() { var calcBedrooms = function () { // Taking input var result = document.getElementById('bedroomNumber-residential').valueAsNumber; return result; }; var calcOcc = function () { if (calcBedrooms() > 0 && calcBedrooms() < 2) { var positi...
[ "function calculateTotalBuildingCount(numConstructed, numLost, type) {\n const initialQuantity = INITIAL_BUILDING_QUANTITIES[type] || 0\n return initialQuantity + numConstructed - numLost\n}", "static calculateHitsRequired(crateType) {\n const crate = CRATE_DATA[crateType];\n const guild = ServerH...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called whenever we receive an update to the contestant score topic. This will be either when the game starts and we're getting caught up with the current data or if there is an arbitrary update to a contestant's score sent out by an admin.
function handleContestantScore(topic, data) { data = JSON.parse(data); if (data instanceof Array) { for (var i in data) { updateContestantScore(data[i].name, data[i].score); } return; } updateContestantScore(data.name, data.score); ...
[ "function updateScore() {\n scoreboard.updateScore();\n scoreboard.checkWin(gameOver);\n scoreboard.server();\n}", "onUpdateCountdownScore(playerObj) {\n const player = this.getPlayerByID(playerObj.id);\n player.updateCountdownText();\n\n // Show a notification that a player's score has gone down.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MAX[] MAXimum of top two stack elements 0x8B
function MAX(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'MAX[]', e2, e1); stack.push(Math.max(e1, e2)); }
[ "function MAX(state) {\n\t var stack = state.stack;\n\t var e2 = stack.pop();\n\t var e1 = stack.pop();\n\n\t if (exports.DEBUG) { console.log(state.step, 'MAX[]', e2, e1); }\n\n\t stack.push(Math.max(e1, e2));\n\t}", "function MAX(state) {\n var stack = state.stack;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function defaultPopupDims() Description: Helper Function for centeredPopup(), called when user doesn't specify a width and height for the new window. In: Nothing Out: dimensions in object form obj.width=width, obj.height=height
function defaultPopupDims() { //first set an absolute fallback value, in case the object sniffing breaks due to weird //browsers var dims = new Object(); dims.width = 580; dims.height = 400; //work out the width and height of Netscape 4.x, Mozilla, & Opera 7.x Browser if( !isNaN( window.innerWidth) && window....
[ "function _getCenterDimensions(optionsArray, popupObject, properties) {\r\n\tvar width = 640; //these are default values used only when centering a popup without defined dimensions\r\n\tvar height = 480;\r\n\tvar centerPropertiesArray = new Object;\r\n\tvar checkproperties = (typeof properties != 'undefined');\r\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listingo Appointent Tabs Navigation
function listingo_appointment_tabs(current) { //Tab Items jQuery('.tg-navdocappointment li').removeClass('active'); var _navitems = jQuery(".tg-navdocappointment li"); _navitems.each(function (index, li) { if (parseInt(index) < parseInt(current)) { jQuery(this).addClass('active'); ...
[ "function mainNavigationAction(){\n\t\t\t\tvar $activeLinks = $links.filter('.active');\n\t\t\t\tif ( $activeLinks.length > 0 ){\n\t\t\t\t\t$activeLinks.each(function(){\n\t\t\t\t\t\tvar $this = $(this);\n\t\t\t\t\t\tvar page = $this.data().page;\n\t\t\t\t\t\tvar $contentWrapper = $this.closest('.the1panel-tabconte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ButtonWidget :: String a Create a button widget.
function ButtonWidget(text,value) { ClickWidget.apply(this,[INPUT({type:'button',value:text}),value]); }
[ "function makeAButton() {\n var button = $(\"<button>\")\n button.text(\"Here's a button!\");\n $(\"#put-button-here\").append(button);\n }", "function generateButton(buttonClass, text) {\n return `<button class=\"${buttonClass}\">${text}</button>`;\n}", "function createButton(buttonTex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to send forum join request
function joinRequest() { var deferred = $q.defer(); var id = $rootScope.currentUser.userId; var forumId = $routeParams.id; $http.post(BASE_URL + '/forum/request/' + id, forumId) .then ( ...
[ "function joinRequest() {\n \n var deferred = $q.defer();\n var id = user.id;\n var forumId = $routeParams.id;\n $http.post(url + '/forum/request/' + id, forumId)\n .then (\n function(response) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the CL description.
getDescription() { return this.cl_.getDescription(); }
[ "function getDescription(){\n\t\tvar str = \"Draw Tool\";\n\n\t\treturn str;\n\t}", "function getDescription(){\n\t\tvar str = \"Move Tool\";\n\n\t\treturn str;\n\t}", "get description() {\n return this.sysInfo.description;\n }", "function get_description() {\n\treturn \"Description Goes here\";\n}"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SDB[] Set Delta Base in the graphics state 0x5E
function SDB(state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'SDB[]', n); state.deltaBase = n; }
[ "function DELTAP123(b,state){var stack=state.stack;var n=stack.pop();var fv=state.fv;var pv=state.pv;var ppem=state.ppem;var base=state.deltaBase+(b-1)*16;var ds=state.deltaShift;var z0=state.z0;if(DEBUG)console.log(state.step,'DELTAP['+b+']',n,stack);for(var i=0;i<n;i++){var pi=stack.pop();var arg=stack.pop();var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ipython has inconsistent behavior here. seems to be doing runCellAndInsertBelow if executed on the lowermost cell.
function runCellAndSelectBelow(_) { _.selectedCell.execute(function () { return selectNextCell(_); }); return false; }
[ "function insertAbove(notebook) {\r\n if (!notebook.model || !notebook.activeCell) {\r\n return;\r\n }\r\n const state = Private.getState(notebook);\r\n const model = notebook.model;\r\n const cell = model.contentFactory.createCodeCell({});\r\n const active = not...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decodes a message using PKCS1 v1.5 padding.
function _decodePkcs1_v1_5(em, key, pub, ml) { // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); /* It is an error if any of the following conditions occurs: 1. The encryption block EB cannot be parsed unambiguously. 2. The padding string PS consists of fewer than ...
[ "function _decodePkcs1_v1_5(em, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n /* It is an error if any of the following conditions occurs:\n 1. The encryption block EB cannot be parsed unambiguously.\n 2. The padding string PS consists of fewer t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If this tab were to have an inspector paired with it, this would be the url
function getInspectorUrl(tab) { return chrome.extension.getURL('html/main-view.html') + '?tab=' + tab.id; }
[ "getCurrentTabUrl({tab}) { return tab.url; }", "function getUrl(){\n\t\treturn document.navigation.href;\t\t\t\t\t\t\t\t\t//RETURNING CURRENT TAB URL\n\t}", "function getCurrentTabUrl(callback) {\n\n}", "function getLink(tab) {\n let tabLink = '#' + tab;\n return EC2_BASE_LINK + '?' + tabLink;\n}", "g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HELPER CODE Traverse over the hierarchy and process each instance with the endConditionCallback. When the endConditionCallback returns a value, the traversal stops and that value is returned.
function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) { if (!hierarchy) { return; } const parentCounts = hierarchy.parentCounts; const parentIds = hierarchy.parentIds; if (parentIds) { return endConditionCallback(hierarchy, instanceIndex); } if (parentCounts > 0) { return...
[ "traverse(callback) {\n for (const child of lodash_1.toArray(this.children)) {\n if (callback(child, abstract_1.TraverseProperty.Children) === false) {\n return;\n }\n }\n }", "iterateDescendants(callback) {\n for (const childName in this.children) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Log a user out, broadcast a flash message, and redirect them
function logout(){ $rootScope.$broadcast('flashMessage', { type: 'warning', content: 'Come back soon!' }); $auth.logout(); $state.go('craveIndex'); }
[ "function logoutUser() {\n sendLogout();\n }", "logOut() {\n if ( this.socket ) this.socket.disconnect();\n window.location.href = ROUTE_PREFIX ? `/${ROUTE_PREFIX}/join` : \"/join\";\n }", "function logoutUser() {\n logout();\n }", "function logOut() {\r\n location.href = '/admin?l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal helper that adds an extra paramater to an axios configuration.
function addParameterToAxiosConfig(axiosConfig, parameterName, parameterValue) { // FIXME: the parameters can also be a URLSearchParams axiosConfig.params = assign({}, axiosConfig.params, {[parameterName]: parameterValue}); // remove from URL auth parameters if any, to avoid possible duplication axiosCo...
[ "function attachExtraParams(extra, http)\n{\n if (extra)\n {\n for (let param in extra)\n {\n if (!Object.prototype.hasOwnProperty.call(extra, param))\n {\n continue;\n }\n\n http[param] = extra[param];\n }\n }\n}", "function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to reduce indeterminism of browser requests by only returning fetch requests. Filter out preflight CORS, fetching stylesheets, page icons, etc. that can occur during tests
function filterNonFetchRequests(requests) { return requests.filter(request => { return (request.resourceType() === 'fetch'); }); }
[ "function filterNonFetchRequests(requests) {\n return requests.filter((request) => {\n return request.resourceType() === 'fetch';\n });\n}", "function fetchMocking (fetchMockResponses) {\n window.origFetch = window.fetch.bind(window)\n window.fetch = async (...args) => {\n const url = args[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A simple check to verify that the value is an integer. Uses `isNumber` and a simple modulo check.
function isInteger(value) { return isNumber(value) && value % 1 === 0; }
[ "isInteger(value) {\n return this.isNumber(value) && value % 1 === 0;\n }", "function isInt() {\n\treturn (Number(value) === parseInt(value, 10));\n}", "function isInt(value) \r\n{\r\n return !isNaN(value) && parseInt(value) == value;\r\n}", "function is_int(i)\r\n{\r\n\tif(typeof i !== 'number')\r\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
take apart underscore strings and make camelCase and return fixed array
function formatString(arr) { const camelArr = []; for (const str of arr) { const wordArr = str.split("_"); const camelWord = []; for (const s of wordArr) { if (s === wordArr[0]) { camelWord.push(s); } else { camelWord.push(s[0].toUpperCase() + s.slice(1)); } } ...
[ "function UnderscoreToCamelCase(underscore) {\r\n return underscore.length > 1\r\n ? (function (s) { return s.substr(0, 1).toLowerCase() + s.substr(1); })(underscore\r\n .split('_')\r\n .map(function (s) { return s.substr(0, 1).toUpperCase() + s.substr(1).toLowerCase(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Completed: implement traceRoute command:
function traceRoute(url) { var hostname = url.hostname; var myRequest = new Request("http://cos432-assn3.cs.princeton.edu/traceroute?q=" + hostname); fetch(myRequest).then(function(response) { return response.text(); }).then(function(response) { var ips = response.split(","); console.log(hostname + " goes ...
[ "function StartWaypointRoute() {\n\t//Set up RunWaypointRoute script\n\tvar replayScript = gameObject.AddComponent(RunWaypointRoute);\n\treplayScript.enabled = false;\n\tyield replayScript.OpenLogs(inputFilename);\n\tyield replayScript.GetTrialInfo(); //Even if we don't want to keepCalibration, we need the level na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2 Return the number of surviving passengers. A passenger survived if their survived property is "Yes". Return a number.
function getSurvivorCount(data) { const survived = data.filter(passenger => passenger.fields.survived === 'Yes') console.log('PASSENGERS THAT SURVIVED', survived.length) return survived.length }
[ "function getSurvivorCount(data) {\n\tconst survivors = data.filter((passenger) => {\n\t\treturn passenger.fields.survived === 'Yes'\n\t});\n\n\treturn survivors.length\n}", "function getSurvivorCount(data) {\n\tconst survivors = data.filter( p => p.fields.survived == \"Yes\")\n\treturn survivors.length\n}", "f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an array of tags combine the ones with the same name averaging the confidence values
function combineTagsArray(tags){ //move all the tags name to lower case for(let t of tags){ t['name'] = t['name'].toLowerCase(); } // sort by name tags.sort((a, b) => { if(a['name']>b['name']) return 1; else if(a['name']==b['name']) return 0; ...
[ "function calcAvgTip(arrayOfTips){\n let sum = 0;\n for(let i=0; i<arrayOfTips.length; i++){\n sum += arrayOfTips[i]; \n }\n return (sum / arrayOfTips.length);\n}", "function combineLandmarksArray(landmarks){\n let landmarks_combine = []; // combine multiple occurences by averaging the confidence scores...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
iterates through each of the list items and sets the order number to the .ordernumber div
function orderNumber() { $(".resultsList li").each(function (i) { let position = i++; $(this).find(".orderNumber").html(position + 1); }) }
[ "function reorder_list_items()\n {\n $('.list-item').each(function(index, object) {\n\n $(this).find('.number').html(\"\"+(index + 1));\n\n });\n }", "function reorder_list_items() {\n $('.list-item', '.editable-list').each(function (index, object) {\n\n var $this = $(this);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }