query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
CODING CHALLENGE 392 You will be given an array of drinks, with each drink being an object with two properties: name and price. Create a function that has the drinks array as an argument and return the drinks object sorted by price in ascending order.
function sortDrinkByPrice(drinks) { return drinks.sort((a, b) => a.price - b.price); }
[ "sortBaseHp(items) {\n\n items.sort(function(a, b){\n\n if(a.hp < b.hp){ \n \n return -1;\n }\n if(a.hp > b.hp) {\n \n return 1;\n }\n return 0;\n })\n \n return items;\n \n }", "sortAttack(items) {\n\n items.sort(func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write styles to file and create directory if needed.
function outputStylesToFile( filename: string, styles: string, throwImmediately: boolean = false ) { try { fs.writeFileSync(filename, styles); } catch (error) { if ( !throwImmediately && (error.code === 'ENOENT' || /ENOENT/.test(error.message)) ) { mkdirp.sync(path.dirname(filena...
[ "function writeCssFile() {\n const origin = fs.createReadStream(\"./style.txt\", { flags: \"r\" });\n const destination = fs.createWriteStream(outputpathForcss, {\n flags: \"w+\",\n });\n origin.pipe(destination);\n}", "function saveCustomStyle (fileName)\n{\n\tvar fileOut = \"\\n\";\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute model matrices of the eyes with respect to the head.
function getEyeMatrices( frameData ) { // Compute the matrix for the position of the head based on the pose if ( frameData.pose.orientation ) { poseOrientation.fromArray( frameData.pose.orientation ); headMatrix.makeRotationFromQuaternion( poseOrientation ); } else { headMatrix.identity(); } if...
[ "initGameObjets(){\n\t\tlet modele = this.controller.modele;\n\t\t//Init les objets\n\t\tthis.scene.add(modele.table.model);\n\t\tthis.scene.add(modele.environment.model)\n\t\tthis.scene.add(modele.board.model)\t\t\n\t}", "function geneticAnimStates(model) {\n var stateMgr = new StateManager(genetic_anim_states_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
format date hours:minutes; add AM + PM if want
function formatDate(date) { var minutes = date.getMinutes(), hours = date.getHours() || 12, meridiem = " PM", formatted; if (hours > 12) hours = hours - 12; else if (hours < 12) meridiem = " AM"; // don't want AM & PM, so add line with blank // if want ...
[ "function formatTime(hours, minutes){\n return hours + ':' + format(minutes);\n}", "function convertTime(date){\r\n var hh = date.getHours().toString();\r\n var mm = date.getMinutes().toString().length == 1? \"0\"+date.getMinutes().toString() : date.getMinutes().toString();\r\n return hh+\":\"+mm;\r\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the 2nd display screen (if any) on this machine. If you want to get more displays, use `getAllDisplays`.
getSecondDisplay() { const displays = this.getAllDisplays(); let externalDisplay = null; for (const i in displays) { if (displays[i].bounds.x != 0 || displays[i].bounds.y != 0) { externalDisplay = displays[i]; break; } } ...
[ "getAllDisplays() {\r\n return eltr.screen.getAllDisplays();\r\n }", "_getMonitor() {\n // We are using Gdk in settings prefs which sets the primary monitor to 0\n // The shell can assign a different number (Main.layoutManager.primaryMonitor)\n // This ensures that the indexing in t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the decimal coefficient and exponent of the specified number x with significant digits p, where x is positive and p is in [1, 21] or undefined. For example, formatDecimal(1.23) returns ["123", 0].
function formatDecimal(x, p) { if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity var i, coefficient = x.slice(0, i); // The string returned by toExponential either has the form \d\.\d+e[-+]\d+ // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., ...
[ "function expandDecimal(num) {\n return [...String(num)].reduce((acc, e, i) => {\n // If number is zero, ignore it.\n if (Number(e) === 0) return acc;\n\n // Compute the x/y fractional part.\n // <1>\n return [...acc, `${e}/${10 ** i * 10}`];\n }, [])\n .filter(isNotZero);\n}", "f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 568 Create a function that counts how many characters make up a rectangular shape. You will be given a array of strings.
function countCharacters(arr) { return arr.join("").length; }
[ "function solve(arr){ \n let alpha = \"abcdefghijklmnopqrstuvwxyz\";\n return arr.map(a => a.split(\"\").filter((b,i) => b.toLowerCase() === alpha[i]).length )\n}", "function count_consonants(string){\n for(i=(string.length-1);i>=0;i--){\n \n for(j=0;j<10;j++){\n \n if (s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Section Feature: Filtering / Function: _fnFeatureHtmlTable Purpose: Add any control elements for the table specifically scrolling Returns: node: Node to add to the DOM Inputs: object:oSettings dataTables settings object
function _fnFeatureHtmlTable ( oSettings ) { /* Chack if scrolling is enabled or not - if not then leave the DOM unaltered */ if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" ) { return oSettings.nTable; } /* * The HTML structure that we want to generate in this function is: ...
[ "function createTable() {\n if (config.data.length === 0) {\n console.log(`No data for table at ${tableSelector}`);\n // Remove any order directive to avoid Datatables errors\n delete config['order'];\n return this;\n }\n htTable.DataTable(config);\n dtapi = htTable.D...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
prompts the user whether or not they would like to delete an entity
function deleteEntity(url, entity, entityname) { message = "Are you sure you want to delete this "+entity; if(entityname != null && entityname != ""){ message += " ("+entityname+")"; } message += "? \nYou will lose all data under this "+entity+" if deleted\n" + "Press ok to delete the "+entity+" \n" + ...
[ "function deleteButtonPressed(entity) {\n db.remove(entity);\n }", "function confirmDeleteUser(user_id){\r\n var choice = confirm('Do you really want to delete this user?');\r\n if(choice === true) {\r\n delete_user(user_id);\r\n\t\treturn true;\r\n }\r\n return false;\t\r\n}", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decreases indentation by one toplevel indent. Does nothing when the previous indent is not toplevel.
decreaseTopLevel() { if (last_default()(this.indentTypes) === INDENT_TYPE_TOP_LEVEL) { this.indentTypes.pop(); } }
[ "continue() {\n let parent = this.node.parent\n return parent ? indentFrom(parent, this.pos, this.base) : 0\n }", "function syntaxIndentation(cx, ast, pos) {\n return indentFrom(\n ast.resolveInner(pos).enterUnfinishedNodesBefore(pos),\n pos,\n cx\n )\n }", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a git log info entry, parse out the remote and branch The entry is expect to be in a know format: / Return a wrapper holding the orig info, and the remote/branch pair
function parseBranch(branch_info,callback) { var branch_split_idx = branch_info.indexOf(BRANCH_MARKER); if(branch_split_idx === -1) { return callback("Log entry missing branch marker "+BRANCH_MARKER+ " on log entry "+branch_info); } var branch_split = branch_info.substring(branch_split_idx + BRANCH_MARKER....
[ "function formatCommitInfo( line ) {\n // Result is in format e.g. d748d93 1465819027 committer@email.com A commit message\n // First field is the truncated hash; second field is a unix timestamp (seconds\n // since epoch); third field is the committer email; subject is everything after.\n let fields = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all songs by album id
getAlbumSongs (idAlbum, options) { if (!options){ // Default Order by track options = { order: 'track'} // options.debug = true } return this.Restangular.one('albums', idAlbum).all('songs') .getList(options) .then( response => response ) }
[ "function getAlbum (id) {\n return $http({\n url: 'local.json',\n method: 'GET'\n }).then(function(response) {\n return _.find(response.data, {'id': parseInt(id, 10)});\n });\n }", "function getPlaylistSongs(playlist_id){\n le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private function: Instantiates the fsevents interface path string, path to be watched callback function, called when fsevents is bound and ready Returns new fsevents instance
function createFSEventsInstance(path, callback) { return (new fsevents(path)).on('fsevent', callback).start(); }
[ "function CustomEventDispatcher() { this._init(); }", "_createWatcher() {\n const _watcher = Looper.create({\n immediate: true,\n });\n _watcher.on('tick', () => safeExec(this, 'fetch'));\n\n this.set('_watcher', _watcher);\n }", "function configChangeListner(){\n\tfs.watch(SERV_CONF_PTH, func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
numberOfBeats temporarily in constructor for testing
constructor(offsetY, numberOfBeats) { this.height = 70; this.width = width * 0.6; this.offsetX = width * 0.2; this.offsetY = offsetY; this.numberOfBeats = numberOfBeats; this.beatWidth = this.width / this.numberOfBeats; this.beats = []; for (let i = 0; i < this.numberOfBeats; i++) { ...
[ "totalEnemies()\n {\n this.numberOfEnemies++;\n }", "getNumberOfCoins() {\n let numberOfCoins = 120000 + (this.numberOfBlocks) * 100;\n return numberOfCoins;\n }", "function countSuitsBlazerMwiPlus() {\n\t\t\tinstantObj.noOfSuitsBlazerMWI = instantObj.noOfSuitsBlazerMWI + 1;\n\t\t\tcountTota...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make an error object from a passed set of properties. Accepted properties: `message`: Text of the error message. `filename`: Filename where the error occurred. `index`: Char. index where the error occurred.
function makeError(err) { var einput; var errorTemplate; _.defaults(err, { index: furthest, filename: env.filename, message: 'Parse error.', line: 0, column: -1 }); if (err.filename && that.env.inputs && that.env.input...
[ "function createSimpleModelError(instance, propertyId, messageFormat, argList) {\r\n\tvar modelMessage = newModelMessage(IStatus.ERROR, \r\n\t\t\tformatString(messageFormat, argList), \r\n\t\t\tinstance, propertyId, null);\r\n\treturn modelMessage;\r\n}", "function buildError(code,message){\n return {\n \"s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror handlers to resolve / reject the PersistencePromise as appropriate.
function wrapRequest(request) { return new __WEBPACK_IMPORTED_MODULE_2__persistence_promise__["a" /* PersistencePromise */](function (resolve, reject) { request.onsuccess = function (event) { var result = event.target.result; resolve(result); }; request.onerror = func...
[ "function prom(request) {\n return primquest(request).promise;\n }", "function NativeDeferred() {\n var _this = this;\n /**\n * Is fulfilled tracked status.\n */\n this.isFulfilled = false;\n /**\n * Is pending tracked status.\n */\n this.isPe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return indices of faces in order of farthest face to closest face. This info is used for painter's algorithm.
function getFaceOrder(shape) { var face_order, faceIdx, face, metric, i; face_order = []; for (faceIdx = 0; faceIdx < shape.faces.length; faceIdx++) { face = shape.faces[faceIdx]; metric = 0; for (i = 0; i < face.length; i++) { metric += shape.points[face[i]].z; }...
[ "get index() {\n\n // Check if the face is bound to a mesh and if not throw an error\n if (!this.mesh) throw new Error(`Cannot compute the index - the face is not bound to a Mesh`);\n\n // Return the index of the face in the faces\n return Number(this.mesh.faces.findIndex(face => face.equals(this)));\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method to create an iframe with the passed videoURL
function createIframe(videoURL) { return $('<iframe/>').attr({ src: videoURL, width: '100%', height: '100%' }); }
[ "static createVideoElement(videoThingy){if(videoThingy instanceof HTMLVideoElement){return videoThingy;}if(typeof videoThingy==='string'){return BrowserCodeReader$1.getMediaElement(videoThingy,'video');}if(!videoThingy&&typeof document!=='undefined'){const videoElement=document.createElement('video');videoElement.w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to insert in dom (step 3) the name of version
function insertProjectVersionInDOM() { var oldvalue = "<b><u>Version :</u></b> "; document.getElementById("projectVersion").innerHTML = oldvalue + getSelectedVersionsName(); }
[ "function insertProjectComponentInDOM() {\n var oldvalue = \"<b><u>Composant :</u></b> \";\n document.getElementById(\"componentName\").innerHTML = oldvalue + getSelectedComponentsName();\n}", "function insertProjectNameInDOM() {\n var oldValue = \"<b><u>Nom du Projet :</u></b> \";\n document.getEleme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enters the fullscreen mode
enterFullscreen() { if (!this.isFullscreenEnabled()) { requestFullscreen(this.container); } }
[ "goFullScreen(name) {\r\n if (name && this._windows.has(name)) {\r\n this._windows.get(name).native.setFullScreen(true);\r\n return;\r\n }\r\n this._windows.forEach(win => win.native.setFullScreen(true));\r\n }", "exitFullscreen() {\n if (this.isFullscreenEnabled...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::AppMesh::VirtualGateway.VirtualGatewayListenerTls` resource
function cfnVirtualGatewayVirtualGatewayListenerTlsPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnVirtualGateway_VirtualGatewayListenerTlsPropertyValidator(properties).assertSuccess(); return { Certificate: cfnVirtualGatewayVirtualGatewa...
[ "function cfnVirtualNodeListenerTlsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_ListenerTlsPropertyValidator(properties).assertSuccess();\n return {\n Certificate: cfnVirtualNodeListenerTlsCertificatePropertyToCloudFo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
! pascalcase < Copyright (c) 2015, Jon Schlinkert. Licensed under the MIT License.
function pascalcase(str) { if (typeof str !== 'string') { throw new TypeError('expected a string.'); } str = str.replace(/([A-Z])/g, ' $1'); if (str.length === 1) { return str.toUpperCase(); } str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase(); str = str.charAt(0).toUpperCase() + str.slice(1...
[ "function titleCase(name) {\r\n let nameArr = name.split(\" \");\r\n nameArr.forEach(function(curr, idx, arr) {\r\n arr[idx] = curr.toLowerCase().replace(/\\b[a-z]/g, function(first) {\r\n return first.toUpperCase();\r\n });\r\n });\r\n\r\n name = nameArr.join(\" \");\r\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We need to track the user's responses
function trackResponse() { console.log(`Logged response to question ${currentQuestion}`); let response = $("input[name='question']:checked").val() responses.push(response) }
[ "function almeResponseHandler(response) {\n\t var doScroll = isLastInputVisible();\n\n // adds user input to chat history\n if ( response.maskedInput !== null )\n {\n renderUserInput( response.maskedInput, !doScroll );\n }\n\n // adds alme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls the add mapping service to update rootstock mapping and clears the selections if mapping is updated successfully else shows the error toast.
updateMapping() { this.toastService_.showInfo('Updating mapping ...'); this.addMappingService_ .updateRootstockMappings(this.selectedSourceProviderId, this.selectedTargetProviderId, this.oldMappings_) .then( (response) => { this.toastService_.showInfo( ...
[ "createMapping() {\n this.toastService_.showInfo('Creating mapping ...');\n this.addMappingService_\n .createRootstockMappings(\n this.selectedSourceProviderId, this.selectedTargetProviderId)\n .then(\n (response) => {\n this.toastService_.showInfo(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a function for putV3ProjectsIdServicesAsana
putV3ProjectsIdServicesAsana(incomingOptions, cb) { const Gitlab = require('./dist'); let defaultClient = Gitlab.ApiClient.instance; // Configure API key authorization: private_token_header let private_token_header = defaultClient.authentications['private_token_header']; private_token_header.apiKey = 'YOUR ...
[ "putV3ProjectsIdServicesAssembla(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.ap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hide the NaCl module's embed element. We don't want to hide by default; if we do, it is harder to determine that a plugin failed to load. Instead, call this function inside the example's "moduleDidLoad" function.
function hideModule() { // Setting common.naclModule.style.display = "None" doesn't work; the // module will no longer be able to receive postMessages. common.naclModule.style.height = '0'; }
[ "hide() {\n\t\tthis.element.style.visibility = 'hidden';\n\t}", "function hidePlayer() {\r\n setBlockVis(\"annotations\", \"none\");\r\n setBlockVis(\"btnAnnotate\", \"none\");\r\n if (hideSegmentControls == true) { setBlockVis(\"segmentation\", \"none\"); }\r\n setBlockVis(\"player\", \"none\");\r\n}", "fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the list of calendars and their corresponding IDs.
function getCalanders() { var response = Calendar.CalendarList.list(); for(i = 0 ; i<response.items.length ; i++){ Logger.log("(" + response.items[i].summary + ')' + response.items[i].id); } }
[ "async getCalendars() {\n try {\n // Get the access token silently\n // If the cache contains a non-expired token, this function\n // will just return the cached token. Otherwise, it will\n // make a request to the Azure OAuth endpoint to get a token\n\n this.trashableAccessToken = makeT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endregion region Setters Callback al crear un input
set onInputCreated(callback) { if (typeof(callback) == 'function') { this.callback_on_input_created = callback; } else { console.error(`${this.logprefix} Error setting onInputCreated callback => the argument is not a function`); } }
[ "set CustomProvidedInput(value) {}", "function onInput() {\n\t\t\t\tif ( typeof options.input === 'function' ) {\n\t\t\t\t\toptions.input.call( $input, function( params, callback ){\n\t\t\t\t\t\tbuild( params );\n\t\t\t\t\t} );\n\t\t\t\t}\n\t\t\t}", "function NeonInputBoxGenerator() {\n\tthis.inputTitles = []\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the given date is not within the given range, move it inside. (If it's past the end, make it one millisecond before the end).
function constrainMarkerToRange(date, range) { if (range.start != null && date < range.start) { return range.start; } if (range.end != null && date >= range.end) { return new Date(range.end.valueOf() - 1); } return date; }
[ "function clampTimeRange(range, within) {\n if (within) {\n if (range.overlaps(within)) {\n var start = range.start < within.start ?\n range.start > within.end ?\n within.end :\n within.start : range.start;\n var end = range.end > within.end ?\n range.end < within.start...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the parent function of the current path.
function getFunctionParent() { return this.findParent(function (path) { return path.isFunction() || path.isProgram(); }); }
[ "get parent() {\n return new Path(this.parentPath);\n }", "function parentFrom(window) {\n if (window.parent !== window) return window.parent;\n}", "parent(root, path) {\n var parentPath = Path.parent(path);\n var p = Node$1.get(root, parentPath);\n\n if (Text.isText(p)) {\n throw new...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method fills the navigation panel. When the user navigate into the buildings, that method update the sensors and makes them draggable as well, but not the places.
function changeBuildingPosition() { // clean DOM var $addCaptors = $("#add-captors").empty(); // append building name $addCaptors.append("<div><h2>" + position.name + "</h2></div>"); //We append a link to every room / place we can access from position for (var i = 0; i < buildings.length; i++...
[ "function BuildingMenuFunc (windowID : int) {\r\n \r\n var data:Database = GameObject.Find(\"Database\").GetComponent(\"Database\");\r\n \r\n // Added a scroll bar for when there are multiple buildings; need to find a way to disable the panning of the camera while scrolling\r\n sc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new dialog ref.
_createDialogRef(overlayRef, dialogContainer, config) { const dialogRef = new this._dialogRefConstructor(overlayRef, dialogContainer, config.id); dialogRef.disableClose = config.disableClose; dialogRef.updateSize(config).updatePosition(config.position); return dialogRef; }
[ "function Dialog() {}", "openFromTemplate(template, config) {\n config = this._applyConfigDefaults(config);\n if (config.id && this.getById(config.id) && (typeof ngDevMode === 'undefined' || ngDevMode)) {\n throw Error(`Dialog with id \"${config.id}\" exists already. The dialog id must be...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Most options support both a string or number as well as a function as option value. This function makes sure that the option with the given key in the given options is wrapped in a function
function makeOptionItemFunction(options, key) { if (typeof options[key] !== 'function') { var propertyName = options[key]; options[key] = function(item) { return item[propertyName]; }; } }
[ "function buildSetter(key) {\n if (key === \"cmd\") {\n return function(val) { this.cmd = val; return this; };\n } else {\n return function(val) { this.options[key] = val; return this; };\n }\n }", "function evalOptions( options, labels, series ){\n\n if( options != \"\" ){\n\n try {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
canBeCaptured returns true if the piece at testRow, testCol can be captured
function canBeCaptured(testRow, testCol, epCol) { /* DESIGN NOTE: this function is designed only with CAPTURE checking in mind and should not be used for other purposes, e.g. if there is no piece (or a king) on the give square */ /* Both normal captures and en passant captures are checked. The epCol pa...
[ "function canPass(xTile, yTile) {\n\tif (xTile < 0 || yTile < 0 || xTile >= gridWidth || yTile >= gridHeight) return false;\n\treturn !grid[xTile + yTile * gridWidth].blocks;\n}", "function checkRow(xy, wb) {\n\n var col = xy[1];\n var length = 1; // start at length 1 since player just put down a piece\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function updates the selected page value state
function trkUpdateSelectedPageValue() { try { trkSelectedPageValue = event.target.attributes.value.value; console.log("Page selected: " + trkSelectedPageValue); } catch(err) { document.addEventListener("DOMContentLoaded", trkResetPageSelection); console.log("Page selected: " + trkSelectedPageValue);...
[ "function setSelectedPageData() {\n\tvar selectedData = CLUB.selectedData,\n\t\tselectedDataLength = selectedData.length,\n\t\tpageData = CLUB.pageData,\n\t\tpageSize = pageData.pageSize,\n\t\tstartIndex = pageSize * (pageData.selectedPage - 1),\n\t\tendIndex = Math.min(selectedDataLength, (startIndex + pageSize)),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PRIVATE FUNCTIONS It starts reading the content of the bibtex file which path is in constant BIBTEXT_FILE_URL. When complete, it calls the input function "completionFunction" to handle the content read.
function startReadingBibtexFile(completionFunction) { // Extracting bibtex file content. $.get(BIBTEXT_FILE_URL, completionFunction); }
[ "loadCodebook (callback) {\n console.debug('Reading codebook')\n this.initCodebookStructure(() => {\n this.initCodebookContent(callback)\n })\n }", "function read_text_file_data(file) {\n var rawFile = new XMLHttpRequest();\n rawFile.open(\"GET\", file, false);\n rawFile.onreadystatechange...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by Java9ParserinterfaceMemberDeclaration.
enterInterfaceMemberDeclaration(ctx) { }
[ "enterNormalInterfaceDeclaration(ctx) {\n\t}", "enterAnnotationTypeMemberDeclaration(ctx) {\n\t}", "enterClassMemberDeclaration(ctx) {\n\t}", "enterInterfaceModifier(ctx) {\n\t}", "exitNormalInterfaceDeclaration(ctx) {\n\t}", "extractInterface(name) {\r\n const { constructors, properties, methods, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to start the game. Needs to add deck event listener and start timer.
function start() { // Attach flip on click event listener to check for matches deckEl.addEventListener("click", game); // begin timer timeSet = setInterval(timer, 100); startEl.removeEventListener("click", start); }
[ "function startGame() {\n getDifficulty();\n startTimer();\n addCards();\n $(\"refresh\").addEventListener(\"click\", addCards);\n toggleGame();\n currSetCount = 0;\n $(\"set-count\").innerHTML = currSetCount;\n deselectAll();\n }", "function startGame() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Problem Dan, president of a Large company could use your help. He wants to implement a system that will switch all his devices into offline mode depending on his meeting schedule. When he's at a meeting and somebody texts him, he wants to send an automatic message informing that he's currently unavailable and the t...
function checkAvailability(schedule, currentTime) { for( var i = 0; schedule.length; i++ ) { var arr = schedule[i]; if( arr[0] > currentTime || currentTime >= arr[1] ) { return true; } else if( currentTime > arr[0] && currentTime <= arr[1] ) { return arr[1]; } } return true; }
[ "function meetingRooms(arr) {\n //GOAL is to find overlaping elements\n //1. sort the meeting by starting time\n arr.sort((a, b) => a[0] - b[0]);\n\n //2. need to keep track of our end times\n //assign the end interval to be the first end interval(1st el from arr)\n //while looping it might change\n\n let en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get survey section by section
function GetSurveySection(surveyId, language, respondentValue, transId) { var firstSectionObj = { "SurveyId": surveyId, "Language": language, "MemberId": respondentValue, "RespondentTransId": transId, "RespondentTypeId": 1 } memberDataService.getSurveySection(firstSectionObj).succ...
[ "function getSection( sectionPos ) {\r\n\t\treturn sections.eq( sectionPos );\r\n\t}", "getDisplayedSection(displayedSubsection) {\n /* Returns the section that the user is currently viewing. */\n return this.state.courseSidebar.sections.find((element) => {\n return element.id === displayedSubsection.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates the swagger schema and gives dereferenced swagger object.
validate () { const that = this; return this ._validate(this.swaggerInput) .then((dereferencedSchema) => { that.swaggerObject = dereferencedSchema; return that; }); }
[ "_validate (schema){\n return SwaggerParser.validate(schema, this.options);\n }", "unmerge (dereferenced){\n const refMatchingFunction = (obj) => {\n if (obj.hasOwnProperty('$ref')){\n return true;\n }\n return false;\n };\n\n this.swaggerObject = this._traverseToUnmerge(this.sw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EVENT HANDLER FUNCTIONS These functions handle events (submit, click, etc) This function generates the question page when the start button is clicked
function handleStartQuiz(){ $('.container').on('click', `.push-start`, event =>{ clearPage(); generateQuestionPage(); }) }
[ "function quizStartPageStartButton() {\n $('.js-main').on('click', '.js-start-page-submit', (evt) => {\n evt.preventDefault();\n STORE.quizStarted = true;\n render();\n });\n}", "function handleStartQuiz() {\n\t$(\"main\").on(\"click\", \".startButton\", function(e) {\n\t\tcurScore = 0;\n\t\tcurQuestio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
increment the events array with current time in milliseconds
increment(){ this.events[this.events.length] = Date.now(); }
[ "setIndex(millis){\n let i = 0;\n for(let event of this.events){\n if(event.millis >= millis){\n this.index = i;\n break;\n }\n i++;\n }\n //console.log(millis);\n this.beyondLoop = false;\n if(millis > this.song.loopEnd){\n this.beyondLoop = true;\n }\n\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new database
function createDb() { backupDb('rename'); db.createdb.newDb(); }
[ "function createDb() {\n pluses_db.run(\"CREATE TABLE pluses (nick text, pluses)\", function(err) {\n if (err) {\n console.log(err);\n }\n });\n}", "function createDb(conf) {\n var state = new DbState();\n state.configure(conf);\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split a url string into its parts via an anchor tag
function splitURL(url) { // Let the browser do the work var l = document.createElement("a"); l.href = url; // see .protocol, .hostname, and .pathname of returned object return l }
[ "function textWithUrlsToFragment(str) {\n\t\tvar result = document.createDocumentFragment();\n\t\twhile (str != \"\") {\n\t\t\tvar match = URL_REGEX0.exec(str);\n\t\t\tif (match == null)\n\t\t\t\tmatch = URL_REGEX1.exec(str);\n\t\t\tvar prefixEndIndex = match != null ? match[1].length : str.length;\n\t\t\tif (prefi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate test function for matchs and vars to check equality to
function testMatch(match, vars) { vars = vars || {}; return function() { Object.keys(match).forEach(function(key) { assert.isString(match[key]); if(key === 'suffix') { ...
[ "function testMatch(match, vars) {\n\n vars = vars || {};\n\n return function() {\n Object.keys(match).forEach(function(key) {\n assert.isString(match[key]);\n if(key === 'suffix') {\n assert.eq...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update pins to display when the selected category is changed
updatePinsToDisplay () { // get labels of selected categories let selectedCategories = [] for (let i = 0; i < this.categories.length; i++) { if (this.categories[i].selected === true) { selectedCategories.push(this.categories[i].label) } } // get ids of pins to di...
[ "function updateCat() {\n\tfunction getCatCallback(event) {\n\t\tvar jsonData = JSON.parse(event.target.responseText);\n\t\tfor(var c in jsonData) {\n\t\t\tvar newCatDiv = document.createElement(\"div\");\n\t\t\tvar label = document.createElement(\"label\");\n\t\t\tvar input = document.createElement(\"input\");\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines name to use for schema from previously determined schemaNames and considering not reusing existing names.
function getSchemaName(usedNames, names) { if (!names || typeof names === 'undefined') { throw new Error(`Cannot create data definition without name(s).`); // Cannot create a schema name from only preferred name } else if (Object.keys(names).length === 1 && typeof names.preferred === 'string...
[ "visitSchema_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "schema(schema) {\n if (arguments.length) {\n this._schema = schema;\n return this;\n }\n if (!this._schema) {\n this._schema = this.constructor.definition();\n }\n return this._schema;\n }", "newSchema() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes HTTPS requests to KubeSail API for things like agent disconnection / registration, etc kubesailApiRequest is a simple wrapper around `https.request`. This could probably be replaced by `got` or something modern
function kubesailApiRequest(reqOptions) /*: Promise<{ json: any, status: number }> */ { const { method, path, data, headers = {}, retries = 0, lookup } = reqOptions return new Promise((resolve, reject) => { const options /*: Object */ = { hostname: KubeSailApiTarget, headers: { 'Content-Type': 'appl...
[ "function methodRequest(method) {\n return (uri, headers, body) => {\n const init = {\n body,\n headers: Object.assign({}, DefaultHeaders, headers),\n method\n };\n const url = env.get('mavenlinkApiHostName') + uri;\n return signedFetch.then(fetch => fetch(url, init)).the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deletes message of the user who initiates the nep'd command. Only deletes the message on singular and multinep. DOES NOT DELETE MESSAGES ON OTHER CONDITIONS!
function prevMsgDelete() { message.delete([300]) .then(msg => console.log(`Deleted message from ${msg.author.username}`)) .catch(console.error); }
[ "function cleanupReplies(message, userId) {\n bot.channels.get(curryBotChannel).fetchMessages().then(function(messages) {\n messages.forEach(function (msg) {\n if (msg.author.bot && msg.id !== message.id && msg.mentions.users.first()) {\n if (msg.mentions.users.first().id === use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a string, toSearch, and a substring, toFind, determine the index at which toFind is contained within toSearch
function findSubString(toSearch, toFind) { const sLen = toSearch.length; const fLen = toFind.length; for(let i = 0; i < sLen; i++) { if(toSearch[i] === toFind[0]) { if(toSearch.slice(i, i + fLen) === toFind) { return i; } } } return -1; }
[ "function myIndexOf(string, searchTerm) {}", "function allIndexOf(str, toSearch) {\n var indices = [];\n for (var pos = str.indexOf(toSearch); pos !== -1; pos = str.indexOf(toSearch, pos + 1)) {\n indices.push(pos);\n }\n return indices;\n}", "function getPosition(str,start,needle){\n\tvar index = str.su...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
WHen the mode of the external activity intervention selector is ASK. This will first ask the user if they want to see it. We call back the server with the answer, and only show it if they say yes.
function processExternalActivityAskIntervention (html) { // Asks if they want the external activity. Calls one of the two functions depending on the student answer interventionDialogOpenAsYesNo("Let's try something different!", html, NEXT_PROBLEM_INTERVENTION,wantsExternalActivity,doesNotWantExternalActivity )...
[ "function askLikesBacon() {\n var bacon = prompt(questionsArr[1]).toLowerCase();\n if (bacon === 'y' || bacon === 'yes') {\n userPoints += 1;\n alertPrefixString = 'Correct! ';\n console.log('The user answered question 2 correctly');\n } else {\n alertPrefixString = 'Sorry! ';\n console.log('The u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Intercepts the mouse wheel event and uses it to zoom in/out on SVG (when present).
function wheelEvent(event) { if (modalVisible) { if (event.ctrlKey) event.preventDefault(); return; } event.preventDefault(); if (Data.Action.Active) return; if (Math.abs(event.deltaY) < 0.1) return; Data.Pointer.X = event.clientX; Data.Pointer.Y = event.clientY; applyZoomStep(event.deltaY >...
[ "function mouseWheel(event) {\n rotx = rotx - event.delta/100;\n return false;\n}", "function doScroll(evt){\n if(!zoomAction && !panAction){\n evt.preventDefault(); // prevent default scroll action in chrome\n // console.log(\"client X: \" + evt.clientX);\n // console.log(\"client...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=================================================================== /================================================================== Save step content id_etape : Number of step to save type_retour : reponse : ====================================================================
function save_step(id_etape,type_retour,reponse) { if(typeof(type_retour) == 'undefined') { // Display waiting message generer_msgbox('',get_lib(184),'','wait'); //================================================================== // Recover content of TinyMCE // Protect special digit & and + ...
[ "function del_step(id_etape,resulat_test,reponse)\r\n{\r\n\tif(typeof(reponse) == \"undefined\")\r\n\t{\r\n\r\n\t\t/**==================================================================\r\n\t\t * Vérification ok, suppression possible\r\n\t\t ====================================================================*/\t\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Play single tile animation
static playAnimationOnTile(tile, frames, onDone) { if (tile.sprite.anims.isPlaying) { tile.sprite.stop(); tile.sprite.anims.remove('tile' + tile.tileId); } let key = 'tile' + tile.tileId; tile.sprite.anims.create({ key: key, frames: tile.sp...
[ "function lightUp(tile, index, numberString) {\n setTimeout(function () {\n console.log('tile:', tile);\n tile.style.opacity = 0.5;\n audioPlay(numberString);\n }, index * 1000); // adds delayed affect for tile light up\n\n setTimeout(function () {\n tile.style.opacity = 1;\n }, index * 1300); // re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
toggleFullScreen toggles the full screen state of the video If the browser is currently in fullscreen mode, then it must be exited and vice versa.
function toggleFullScreen() { if (document.fullscreenElement) { document.exitFullscreen(); } else { referrer.that.invokeMethodAsync("onFullscreenRequestButton"); //videoContainer.requestFullscreen(); } updateFullscreenButton(); }
[ "exitFullscreen() {\n if (this.isFullscreenEnabled()) {\n exitFullscreen();\n }\n }", "function fullScreenButton() {\n\t\tlet j = $('[id^=\"fullscreen\"]').on('click', function (e) {\n\t\t\t\tlet i = parent.document.getElementsByTagName(\"iframe\")[0]\n\t\t\t\t\tif (i == null) {\n\t\t\t\t\t\ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
uint16 Returns true iff the flags have the IGNORE bit set.
function isIgnore( flags ) { return (flags & FLAGS.IGNORE) === FLAGS.IGNORE; }
[ "function noFlags(){\n return (typeof(p) == typeof(v));\n}", "readUint16() {\n const value = this._data.getUint16(this.offset, this.littleEndian);\n\n this.offset += 2;\n return value;\n }", "function stillImaginary(mask) {\n for (let i = 0; i < mask.length; i++) {\n if (gpuMult) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete city from list
deleteCity(cityId){ let temp = this.state.list; for (let i = 0, n = temp.length; i < n; i++) { if (temp[i].id == cityId) { temp.splice(i, 1); break; } } let data = JSON.stringify(temp); localStorage.setItem("weatherData", da...
[ "destroy() {\n let cityName = this.name, keys = Object.keys( Country.instances ), i,\n country;\n\n // on delete cascade (if a capital is deleted, then the country is too)\n for (i = 0; i < keys.length; i += 1) {\n if (Country.instances[keys[i]] && this.equals(\n Country.instances[keys[i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Arrow from object B to the space position
function drawDirectionObjB(shapeName, line, xPos, yPos, arrow, scope) { shapeName.cursor = "pointer"; shapeName.on("pressmove", function(evt) { this.x = evt.stageX; this.y = evt.stageY; line.graphics.clear(); if (this.y > final_pos_direction_y) { this.y = final_pos_direction_y; } line.graphics.moveTo(x...
[ "function drawDirectionObjA(shapeName, line, xPos, yPos, arrow, scope) {\n shapeName.cursor = \"pointer\";\n shapeName.name = \"objA\";\n shapeName.on(\"pressmove\", function(evt) {\n this.x = evt.stageX;\n this.y = evt.stageY;\n line.graphics.clear();\n if (this.y > final_pos_direction_y) {\n this.y = final_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log(Allnums()) 5050 Leetcode remove duplicates from sorted array nums = [],
function removeDups(nums) { // place the first index start at one because its always unique var output = 1; // nums.sort(); // console.log(nums); // now we want to run thorugh the array and compare each element with the following element. and we do nums.length - 1 when we compare the second to last value to t...
[ "function findUniques(nums) {\n var newNums = [];\n\n for (var i = 0; i < nums.length; i++) {\n if (newNums.indexOf(nums[i]) < 0 )\n newNums.push(nums[i])\n }\n return newNums \n}", "function remove_duplicates(arr) {\n console.log(\"Duplicates removed from array\");\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Drive the REST API to unwatch the item.
function unwatch(itemNumber) { console.log("Unwatch " + itemNumber); var xhr = new XMLHttpRequest(); xhr.open('DELETE', '/rest/wishlists/' + activeDistributorID + '/' + itemNumber); xhr.send(); }
[ "unfreeze() {\n //call api to unfreeze listing\n api.get(`/listing/unfreeze/${this.props.Item.listing_id}`)\n .then(function (result) {\n console.log(result);\n window.history.go(0);\n });\n\n }", "removeItem(item) {\n Items.remove(item._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copyright 2020 Inrupt Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,...
function getUrl(thing, property) { internal_throwIfNotThing(thing); const namedNodeMatcher = getNamedNodeMatcher(property); const matchingQuad = findOne(thing, namedNodeMatcher); if (matchingQuad === null) { return null; } return matchingQuad.object.value; }
[ "static getReliableURItoLocateTarget (annotation) {\n if (_.has(annotation, 'target[0].source')) {\n const source = annotation.target[0].source\n // The most reliable source is DOI\n if (source.doi) {\n return source.doi\n }\n // The next more reliable URI is the URL, but only if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function adds Heavy Cover number for H_W&I by 1
function countHcoverHwiPlus() { instantObj.noOfHcoverHWI = instantObj.noOfHcoverHWI + 1; countTotalBill(); }
[ "function countHcoverHwiMinus() {\n\t\t\tif(instantObj.noOfHcoverHWI > 0) {\n\t\t\t\tinstantObj.noOfHcoverHWI = instantObj.noOfHcoverHWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countHcoverHwfPlus() {\n\t\t\tinstantObj.noOfHcoverHWF = instantObj.noOfHcoverHWF + 1;\n\t\t\tcountTotalBill();\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CLOSEALLSCREENSHOTS: closes all "view original" screenshots
function closeAllScreenshots() { closeDiv(org1_line); closeDiv(org2_line); closeDiv(org3_line); closeDiv(org4_line); closeDiv(org5_line); closeDiv(org1_bar); closeDiv(org2_bar); closeDiv(org3_bar); closeDiv(org4_bar); closeDiv(org5_bar); }
[ "closeAllWindows() {\n let windows = this.getInterestingWindows();\n for (let i = 0; i < windows.length; i++)\n windows[i].delete(global.get_current_time());\n }", "function closeAllInfoWindows() {\n\tfor (var i=0;i<infoWindows.length;i++) {\n\t\tinfoWindows[i].close();\n\t}\n}", "cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DISTINCT / The distinct function checks whether the items in a list are unique. / Taken from SICP JS section 4.3.2
function distinct(items) { return is_null(items) ? true : is_null(tail(items)) ? true : is_null(member(head(items), tail(items))) ? distinct(tail(items)) : false; }
[ "function uniqMethod() {\n\tvar testarray=[1,2,2,1,2,3,1,1,1,4,4,4,4,3,3,5,6,6,7,7];\n\tvar result=_.uniq(testarray);\n\tconsole.log(result);\n}", "function UNIQUE(array) {\n return array.reduce(function (p, c) {\n if (p.indexOf(c) < 0) p.push(c);\n return p;\n }, []);\n}", "function unique(animals) {//...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build pageRE, a regexp for the use of findPageNameFromHref().
function buildPageRE() { var articlePathParts = mw.config.get( 'wgArticlePath' ).split( '$1' ); var articlePathStartRE = mw.RegExp.escape( articlePathParts[0] ); var articlePathEndRE = mw.RegExp.escape( articlePathParts[1] ); var indexPathRE = mw.RegExp.escape( mw.util.wikiScript( 'index' ) ); return new Reg...
[ "function buildNavigationRouteRegexp() {\n // Build the alternation expression for each of the navigation routes.\n let routeAlternation = Object.entries(NavigationConstants)\n .filter(([k]) => k !== \"LOGIN\" && k !== \"LOGOUT\")\n .map(([_, v]) => escapeRegExp(v))\n .join(\"|\");\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a function getCart that takes no arguments and returns the cart.
function getCart () { return cart }
[ "function getCart(parent, args) {\n if (!userInfo.isUserLoggedIn) {\n throw new Error('Please log in to create a cart.');\n }\n if (!cartInfo.isCartCreated) {\n throw new Error('Please create a cart.');\n }\n return cartInfo.cart;\n}", "function loadCart(cartId) {\n return { type: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
make function for onClick of a videoListEntry
onListItemClick(clickedVideo) { this.setState({ // swap the player to the clicked video player: clickedVideo, }); }
[ "function VideoListItem({video,onVideoClick}){\n //console.log(video.snippet);\n return <li onClick = { () => onVideoClick(video) }\n className=\"list-group-item\">\n <div className=\"video-list video-item media\">\n <div className=\"media-left\">\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SubscribeBluetoothDevice........................................................................ Subscribe means to listen on this UUID, i.e. channel, from the BLE device.
function SubscribeBluetoothDevice() { PrintLog(1, "BT: SubscribeBluetoothDevice()" ); // Version 1.0.2 of the plugin var paramsObj = {"address":btAddr, "service":bridgeServiceUuid, "characteristic":bridgeTxCharacteristicUuid, "isNotification":true}; bluetoothle.subscribe(subscribeSuccess, subsc...
[ "onDeviceConnected(listener) {\n return this.createBluetoothEventSubscription(BluetoothEventType.DEVICE_CONNECTED, listener);\n }", "function subscribe(id) {\n weavy.api.follow(\"item\", id).then(function () {\n updateSubscribers(id);\n });\n }", "subscribeRedis() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define actions like FETCH_A_PATIENT_SIBLINGS
[FETCH_PATIENT_SIBLINGS]({ commit }) { let endpoint = `/api/v1/patient-sibling-b03/`; commit(FETCH_START); apiService(endpoint) .then(response => { commit(SET_PATIENT_SIBLINGS, response); commit(FETCH_END); }) .catch(error => { console.log(error); }); }
[ "static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('accesscontrol', 'list', kparams);\n\t}", "function iglooActions () {\n\t//we should have things like pageTitle, user and revid\n\t//here- and th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that nickName exists and != firstName, and that Middle Name Exists and != middleInitial
function checkNNandMN(formula) { if ( nickName && nickName != "" && nickName != firstName && middleName != "" && middleName != middleInitial ) { emailOutput.push(formula); } }
[ "function validateLastName() {\n return checkPersonalInfo(\"last-name\", \"Last name must have at least 3 characters\");\n}", "function customerHasValidLastName (cust) {\n return typeof cust === 'string' && cust !== '' && cust.length < 501;\n}", "function validateFirstName() {\n return checkPersonalInf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Custom type guard for SchemaString. Returns true if node is instance of SchemaString. Returns false otherwise. Also returns false for super interfaces of SchemaString.
function isSchemaString(node) { return node.kind() == "SchemaString" && node.RAMLVersion() == "RAML10"; }
[ "isString() {\n return (this.type === \"string\");\n }", "function sc_isString(s) { return (s instanceof sc_String); }", "isStringType(type) {\n return this.typesAreEquivalent(type, StringType);\n }", "function isStringType(node) {\n const objectType = typeChecker.getTypeAtLocation(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable the form for creating a playlist.
function enableForm() { $('#playlist-button').attr('disabled', false); }
[ "static add(playlist, updateStats = false){\n\t\tlet kparams = {};\n\t\tkparams.playlist = playlist;\n\t\tkparams.updateStats = updateStats;\n\t\treturn new kaltura.RequestBuilder('playlist', 'add', kparams);\n\t}", "function bindPlaylistToModal(pl, e) {\n var playlistId = pl.id;\n var playlist = document.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines if the given character can be part of the "local part" of an email
function isEmailLocalPartChar(char) { return emailLocalPartCharRegex.test(char); }
[ "function stateEmailLocalPart(stateMachine, char) {\n if (char === '.') {\n stateMachine.state = 23 /* EmailLocalPartDot */;\n }\n else if (char === '@') {\n stateMachine.state = 24 /* EmailAtSign */;\n }\n else if (isEmailLocalPar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an alert of all the states
function getStates(){ var checkbox1 = document.getElementById("button1"); var alertString=""; if(checkbox1.checked){ alertString="Appliance 1 is ON"; }else{ alertString="Appliance 1 is OFF"; } var checkbox2 = document.getElementById("button2"); if(checkbox2.checked){ al...
[ "function Alerts(){\n return(\n [\n 'primary',\n 'secondary',\n 'success',\n 'danger',\n 'warning',\n 'info',\n 'light',\n 'dark',\n ].map((variant, idx) => (\n <Alert key={idx} variant={variant}>\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add emoji to favoriteEmojis array
function addToFavorite(emoji){ favoriteEmojis.unshift(emoji); console.log(favoriteEmojis); favoriteEmojis = favoriteEmojis.filter((emoji, index) => { return favoriteEmojis.indexOf(emoji) == index; }); //saving favoriteEmojis array to localstorage localStorage.setItem("favoriteEmojis", JSON.stringify(favoriteEmo...
[ "function emojiClickEventHandler(emoji){\n\twriteToClipboard(emoji.char);\n\taddToFavorite(emoji);\n}", "function chooseEmoji(e) {\n if(e.target.matches(\".emoji\")) {\n textarea.value += e.target.innerHTML\n }\n}", "async function browseEmojis() {\n const response = await fetch(\"https://unpkg....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update an element (1) Its data in the cy diagram (2) Its style in the cy diagram (3) The realtime correlated items (Remove edges in case not suitable anymore) (4) The real time compatible elements of the cy diagram
update_elem(id, type, data){ //console.log("Data to update: ",data); //first check if it's the Diagram if (id == this.DIAGRAM_GENERAL.data.id) { for (var k_data in data) { if (data[k_data] != -1) { if (k_data == "name") { if (this.DIAGRAM_GENERAL.data.hasOwnProperty(k_dat...
[ "function update() {\r\n\r\n var id_to_index = {},\r\n old_ids = {},\r\n new_ids = {},\r\n index_to_id = {},\r\n index_updates = {},\r\n additions = [],\r\n removals = [];\r\n \r\n //need to add module_ids to any modules that are missing them\r\n var key_fn ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a structure level, return the kind and direction of transition to another step
relativeLevelPosition(level, target){ if(!target){ return ["none", "same", level]; }; var difference = target.indexes[level] - this.indexes[level]; if(difference < -1){ return ["jump", "backwards", "by-" + level]; } else if(difference == -1){ return ["advance", "backwards", "by-" + level]; ...
[ "defineDirection() {\n var posRoad = this.road[this.partRoad];\n if (Number(this.pos.getx()) == Number(posRoad.getx())) {\n if (Number(this.pos.gety()) < Number(posRoad.gety())) {\n return SOUTH;\n } else {\n return NORTH;\n }\n }\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
I toggle the pass / fail status for the given commit in staging.
function toggleStatusInStaging( commit ) { var nextTesting = "active"; var nextStatus = _.cycle( [ "pending", "pass", "fail" ], commit.staging.status ); deploymentService .updateCommitInStaging( deploymentID, commit.hash, nextTesting, nextStatus ) .then( function handleResolve() { $log.info( "St...
[ "function toggleTestingInStaging( commit ) {\n\n\t\tvar nextTesting = _.cycle( [ \"inactive\", \"active\" ], commit.staging.testing );\n\t\tvar nextStatus = commit.staging.status;\n\n\t\t// If the testing got reset, move the status back to a pending state.\n\t\tif ( nextTesting === \"inactive\" ) {\n\n\t\t\tnextSta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET: Get all Journeys
async function getAllJourneys() { const res = await query(`SELECT * FROM journey ORDER BY startDate DESC`); return res.rows; }
[ "function get_all_sucursals(req, res) {\n var sucursal_list = DBController.getData(\"sucursals.json\");\n var sucursals = Object.keys(sucursal_list).map(sucursal_id => ({ \"sucursal_id\": sucursal_id, \"city\": sucursal_list[sucursal_id][\"city\"] }))\n res.send({ \"sucursals\": sucursals });\n}", "getJo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates the checked item count, changes 'select all' 'deselect all' text based on number of items as well as disables it if no items in list
function updateCheckCount() { var checkedCount = $("#itemsList input[type=checkbox]:checked").length; var checkBoxCount = $("#itemsList input[type=checkbox]").length; var selectBtn = $("#selectItemBtn"); if (checkedCount == checkBoxCount && checkBoxCount != 0) { selectBtn.val("Deselect all"); ...
[ "function updateItem(){\n\t//Update itemList total item left information\n\t$('#options-num').text(function() {\n\t\tvar n = $(\".list-container li.sl-item\").length;\n\t\treturn \"n\";\n\t});\n\t$('#template-num').text(function() {\n\t\tvar n = $(\".list-template li.sl-item\").length;\n\t\treturn \"n\";\n\t});\n}"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function handles the rendering of the nondividend stock data
function renderNonDivHtml(stockSymbol, annualGainNonDividend) { // $('.non-dividend-results').html(`<br>Compare that to ${stockSymbol.toUpperCase()}'s non-dividend gains over // the past year (updated today): ${annualGainNonDividend}%`); $('.middle-bar-title').text(`${stockSymbol.toUpperCase()}'s 1-year gain ...
[ "function displayStockList(filter, refresh) {\n if (!!document.getElementById(\"listPlaceholder\")) {\n const newlist = document.createElement('div');\n newlist.innerHTML = ' <div class=\"stock-selection-sect vertical_height margin-top\" id=\"stockHeader\"></div>';\n document.getElementById...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes carets out of the snapshot that haven't been active recently.
async _removeIdleCarets() { this.log.event.idleCheck(); const snapshot = await this.getSnapshot(); // **Note:** We have to wait for the `snapshot` to be ready before getting // the current time. (That is, the following line cannot be moved above the // previous line.) Otherwise, we might produce a...
[ "async discard() {\n const tx = this.database.transaction(\n ['states', 'changes', 'contents'], 'readwrite')\n const states = tx.objectStore('states')\n const changes = tx.objectStore('changes').index('document')\n const contents = tx.objectStore('contents')\n\n await P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The result is a dictionary of the width of the text samples. Heights aren't included because they give no extra entropy and are unstable. The result is very stable in IE 11, Edge 18 and Safari 14. The result changes when the OS pixel density changes in Chromium 87. The real pixel density is required to solve, but seems...
function getFontPreferences() { return withNaturalFonts((document, container) => { const elements = {} const sizes = {} // First create all elements to measure. If the DOM steps below are done in a single cycle, // browser will alternate tree modification and layout reading, that is very slow. for (con...
[ "textLengthData () {\n let t = this\n let bins = t.lengthDimensionGroup.top(Infinity)\n bins.forEach(function (d) {\n d.scaledKey = t.textLengthMin + d.key / NUMBER_LENGTH_BINS * t.textLengthRange\n })\n return bins\n }", "getTextMetrics()\n\t{\n\t\tif (typeof this._textMetrics === \"undefine...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allow drag/drop listener on given element
function allowDragDrop(el, callback) { el.addEventListener('dragenter', function(e) {onDrag(e)}, false); el.addEventListener('dragexit', function(e) {onDrag(e)}, false); el.addEventListener('dragover', function(e) {onDrag(e)}, false); el.addEventListener('drop', function(e) {onDrop(e, callback)}, false); }
[ "function addDragHandlers(elem)\n{\n elem.addEventListener('dragstart', handleDragStart, false);\n elem.addEventListener('dragover', handleDragOver, false);\n elem.addEventListener('drop', handleDrop, false);\n elem.addEventListener('dragleave', handleDragLeave, false);\n\n}", "function mouseDrop(e) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Grabs user location data, then calls displayData to show it in the browser
function getLocData() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(displayData); } }
[ "function getUserCoords(locationID) {\n console.log(\"searching for cordinates for \" + locationID)\n\n //geocoder key (used for getting lat and long from user's location id)\n var locIdCoordURL = \"https://geocoder.api.here.com/6.2/geocode.json?locationid=\" + locationID + \"&jsonattributes=1&gen=9&app_id=\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If itemIds is undefined, returns all ids in the store
_itemIdsOrAll(itemIds) { if (_.isUndefined(itemIds)) { itemIds = this.items.map((item) => item.id); } return itemIds; }
[ "async getItemsById (modelName, itemIds) {\n\n\t\tconst records = await this.database.find(modelName, {\n\t\t\t$or: itemIds.map(id => Object({ _id: id })),\n\t\t});\n\n\t\treturn records || [];\n\n\t}", "function getDocIds(items) {\n\t\tvar docIds = [];\n\t\tfor ( var i in items ) {\n\t\t\tdocIds.push(items[i].i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete all tasks from LS
deleteTasks(){ localStorage.clear(); }
[ "function clearAllTasksFromLocalStorage() {\n\n localStorage.removeItem('tasks');\n\n \n}", "async removeAllTasksForUser (userId) {\n\t\tconst database = this.__dep(`database`);\n\t\tawait database.deleteWhere(`Task`, { _user: userId });\n\t}", "deleteAll() {\n this.forEach(item => {\n this.delete...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save Weight measurement by username
async function postWeightByUsername(req, res) { try { // 1. Check if the child exists const child = await getChildByUsername(req.params.username) if (!child) { // child not found by given username return res.status(400).send(msgChildNotFoundUsername(req.params.username)) ...
[ "async function addWeightHandler(event) {\n const weight = document.querySelector(\"#weight-chart-input\").value.trim();\n\n const response = await fetch('/api/users/weight', {\n method: 'POST',\n body: JSON.stringify({ weight }),\n headers: {\n 'Content-Type': 'application/jso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getNotificationTitle get notification title by notification type
function getNotificationTitleByType(notificationType, OwnerDisplayName) { let title = ""; switch (notificationType) { case likeNotifyType: title = `${OwnerDisplayName} liked your post.`; case commentNotifyType: title = `${OwnerDisplayName} added a comment on your post.`; case followNotifyTy...
[ "function getNotificationType(payload) {\n return payload.type;\n}", "get title() {\n var title_node = document.getElementById(\"status-bar-title\");\n return title_node.innerText || title_node.textContent;\n }", "function get_target_name(req, first_notification) {\n\t\tif (first_notification && first...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Class food product that may return shelf live of the product.
function foodProduct (id, name, type, price, validUntil) { this.constructor(id, name, type, price); this.validUntil = validUntil; Object.defineProperty(this, 'shelfLive', { get: function() { return (releaseDate - validUntil)/36000000/24; } }); }
[ "function pizzaObject(flavour,size,crust)\n {\n this.flavour=flavour;\n this.size=size;\n this.crust=crust;\n this.delivery=delivery;\n this.price=flavour[1]+size[1]+crust[1]+deliverySelect[1];\n \n }", "function Fish(name, species, waterConditions) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Undeploy all deployed sensors and actuators on the canvas
function undeployComponents() { vm.processing = {}; vm.processing.status = true; vm.processing.undeployed = true; vm.processing.finished = false; var undeployPromises = []; $(".jtk-node").each(function(index, element) { var $element = $(element); var ...
[ "onShutdown() {\n this.particleSystems.forEach( e => e.dispose() );\n this.particleSystems.clear();\n }", "removeAll() {\n this.$plugins.forEach((entry) => {\n if (entry && entry.uninstall) {\n entry.uninstall(this);\n }\n });\n this.$plug...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Primary object used to encapsulate all the properties of a merge duplicate record job request. Note that nlobjJobManager.createJobRequest() returns a reference to this object. Use the methods in nlobjDuplicateJobRequest to define the criteria of your merge duplicate request.
function nlobjDuplicateJobRequest() { }
[ "function newRequest(data){\n var request = createNewRequestContainer(data.requestId);\n createNewRequestInfo(request, data);\n }", "function newItemRequest(endpoint, payload) {\n var request = baseRequest;\n request.url = endpoint;\n request.type = \"POST\";\n request.contentTy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a mapping of dataset names to cancer abbreviations
function createCancerMapping(){ // Quick check to ensure all datasets map to a defined cancer _id // after this function has executed function ensureAllDatasetsMapToCancer(){ datasets.forEach(function(db){ if (!datasetToCancer[db]){ console.log("Unknown cancer type: " + db); process.exit(1); ...
[ "function loadbankcode() {\n $scope.bankcodelist = DummyBanklist.getBanklist();\n // applying the filter for making the BANKNAME data title case\n for (var incr = 0; incr < $scope.bankcodelist.length; incr++) {\n $scope.bankcodelist[incr][\"BANKNAME\"] = $filter('uppe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show error in Carousel slide
function showErrorCarouselItem(service_name, elm, bot_message_type) { if(bot_content_type != null) { var carousel_type = ''; switch (service_name) { case 'facebook' : carousel_type = bot_content_type[type_generic]; break; case 'line' : carousel_type = bot_content_type[type_ca...
[ "function showErrorFallr(msg) {\n\tjQuery.fallr('show', {\n\t\tcontent : '<p>'+ msg +'</p>',\n\t\ticon : 'error'\n\t});\n}", "function showExpenditurePeriodicityErrorIfPresent(error) {\n\tif (!isEmpty(error)) {\n\t\t$(\"#expenditurePeriodicityError\").text(error);\n\t}\n}", "function setItemThumbLoadedError(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete Existing PCs Creates inline 'delete' buttons; called by 'Remove PC' button
function removePC () { // To avoid bugs, disallow function if currently editing PCs or if no PCs are being displayed if (editPCbutton.textContent !== 'Edit PC') return false; if (!PCdiv.childNodes.length) return false; // Change text content to 'Cancel' and alter alter event listeners alterButton(removePCbutton, ...
[ "function removeInlineButtons () {\n\tconst pcDivs = PCdiv.children;\n\tfor (let i = 0; i < pcDivs.length; i++) { pcDivs[i].querySelector('button').remove() };\n\n\tif (editPCbutton.textContent === 'Cancel') alterButton(editPCbutton, 'Edit PC', removeInlineButtons, editPC);\n\tif (removePCbutton.textContent === 'Ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the node is an embedded view, traverses up the view tree to return the closest ancestor view that is attached to a component. If it's already a component node, returns itself.
function getClosestComponentAncestor(node) { while (node.type === 2 /* View */) { node = node.view.node; } return node; }
[ "elementFromNode(node) {\n let part = this.nodes2parts[node.uuid];\n // one of many hacks to handle circular constructs, this returns the ID for the initial block\n // which we assume is the circular block itself when given the id for the end cap.\n if (part === Layout.backboneEndCapId) {\n invaria...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns current ICU case. ICU cases are stored as index into the `TIcu.cases`. At times it is necessary to communicate that the ICU case just switched and that next ICU update should update all bindings regardless of the mask. In such a case the we store negative numbers for cases which have just been switched. This fu...
function getCurrentICUCaseIndex(tIcu, lView) { const currentCase = lView[tIcu.currentCaseLViewIndex]; return currentCase === null ? currentCase : (currentCase < 0 ? ~currentCase : currentCase); }
[ "getCurrentStaircase() {\n\t\treturn this.staircases[this.stairIndex].staircase;\n\t}", "switchAfterZero(val) {\n /*\n Override by component\n */\n return val\n }", "function declineSingleCase(caseNumberIndex, patternIndex, word) {\n\tif (patternIndex < 0 || pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
END ADD PHOTO GET PHOTOS LIST
function getPhotoList(){ log("getPhotoList()","info",images_listForInsert); return images_listForInsert; }
[ "function getPicturesques() {\n //\n //\n //Picturesques.list(); listPicturesque\n //\n var req = gapi.client.picturesque.photo.list();\n req.execute(function(data) {\n $(\"#results\").html('');\n showList(data); \n });\n}", "function setPhotos(p){\n\t\t\tfunction setPic(sp){\n\t\t\t\tvar id=\"\";\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to get the current memory address or any upcoming addresses when a lookahead value is supplied
function getMemoryLocation(lookaheadValue) { var currentMemoryLocation = 0 for(; currentMemoryLocation < _ByteCodeList.length; currentMemoryLocation++) { // currentMemoryLocation already being incremented } // If a lookahead value was supplied add it to the memory location if(lookaheadValue) { cu...
[ "indexedIndirect() {\n this.incrementPc();\n let zeroPageAddress = (this.ram[this.cpu.pc] + this.cpu.xr) & 0xff\n let lo = this.ram[zeroPageAddress] & 0xff\n let hi = this.ram[zeroPageAddress + 1] & 0xff\n\n return (hi * 0x0100 + lo) & 0xffff\n }", "function visitStateAddress(callback)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }