query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Fetches all records from position table
function fetchAllPositions(request_data, callback) { console.log('GET url: ' + request_data.originalUrl); var query_string = 'SELECT instrument_id,position FROM position'; connection.query(query_string, function (error, result) { if (result) { return callback(null, result); } else { return cal...
[ "static fetchAll(callback) {\n Department.fetchAll(function(err, data) {\n if(err) { // Basic error handling\n console.error(err);\n callback(null, err);\n throw err;\n }\n\n let departments = data; // Will be out of scope\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts a polar function r=f(theta) to a parametric cartesian function [x,y]=f(p) where theta=p
function polar(rFunctionOfTheta){ return function(parameter){ var theta = parameter; var radius = rFunctionOfTheta(theta); return [radius * Math.cos(theta), radius * Math.sin(theta)]; } }
[ "function polarToCartesian(r, theta) {\n return [r * Math.cos(theta), r * Math.sin(theta)];\n }", "function cartesianToPolar(x,y) {\n var r = scope.radiusScale(x);\n var a = scope.thetaScale(y) - Math.PI/2;\n x = r * Math.cos(a) + size.width/2;\n y = r * Math.sin(a) + size.height/2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function takes the note being played and converts it into a Western Scale frequency
function frequencyFromNoteNumber( note ) { return 440 * Math.pow(2, (note - 69) / 12); }
[ "function convertMidiToFreq(note) {\n return 440 * Math.pow(2, (note - 69) / 12);\n}", "function noteToFreq(note) {\n if (typeof note !== 'string') {\n return note;\n }\n var wholeNotes = { A: 21, B: 23, C: 24, D: 26, E: 28, F: 29, G: 31 };\n var value = wholeNotes[note[0].toUpperCase()];\n var octave = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This idea comes from the Gansner paper: to account for edge labels in our layout we split each rank in half by doubling minlen and halving ranksep. Then we can place labels at these midpoints between nodes. We also add some minimal padding to the width to push the label for the edge away from the edge itself a bit.
function makeSpaceForEdgeLabels(g){var graph=g.graph();graph.ranksep/=2;_.forEach(g.edges(),function(e){var edge=g.edge(e);edge.minlen*=2;if(edge.labelpos.toLowerCase()!=="c"){if(graph.rankdir==="TB"||graph.rankdir==="BT"){edge.width+=edge.labeloffset}else{edge.height+=edge.labeloffset}}})}
[ "function makeSpaceForEdgeLabels(g){var graph=g.graph();graph.ranksep/=2;_.each(g.edges(),function(e){var edge=g.edge(e);edge.minlen*=2;if(edge.labelpos.toLowerCase()!==\"c\"){if(graph.rankdir===\"TB\"||graph.rankdir===\"BT\"){edge.width+=edge.labeloffset;}else{edge.height+=edge.labeloffset;}}});}", "function mak...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to store input operator into an array
function storeOperator(inputOperator){ arrayNumberOpt.push(inputOperator); }
[ "function getOperators(operator) {\n numbers.push(screenContent.join(\"\"));\n numbers.push(operator);\n screenContent = [];\n}", "function pushOperator() {\n\toperator = event.target.value;\n\tcalculation.push(operator);\n\tdisplay.value = operator;\n}", "function getOperator(outputArray) {\n let o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find the required server text channel by name
function findChannel(server, channelName) { //find the muddy points channel let category = server.channels.cache.find( c => c.name == channelName && c.type == "text"); console.log("Channel found in cache: "+channelName); return category; }
[ "function findChannel(name){\r\n\r\n for(i = 0; i < youtubeChannels.length; i++){\r\n for(j = 1; j < youtubeChannels[i].length; j++){\r\n \r\n if(name == youtubeChannels[i][j]) {\r\n console.log('Sending to Discord @ channel ' + youtubeChannels[i][0]);\r\n return youtubeChannels[i][0];\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
log the storage and alarms to the console
function log() { chrome.storage.sync.get(null, function (data) { console.log(data); }); chrome.alarms.getAll(function (alarms) { var print = []; for (alarm in alarms) { date = new Date(alarms[alarm].scheduledTime); print.push([alarms[alarm].name, date.toLocaleDateString()...
[ "function printLogToStorage(data){\n //console.log(data);\n chrome.storage.local.get(function(items){\n //console.log(items);\n if(typeof items.storage_log !== 'undefined') {\n //console.log(\"storage log exists\");\n //console.log(items.storage_log);\n chrome.storage.local.set(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the big highlighted image
function updateHighlightedImage($hlImg) { var $hlImgId = $hlImg.data('id'); var $hlImgExHeight = parseFloat($hlImg.data('xh')); var $hlImgExWidth = parseFloat($hlImg.data('xw')); var $hlImgAspect = parseFloat($hlImg.data('aspect')); var aspectR; /** * Bound image size based on aspect ratio * * For...
[ "function highlight() {\n this.setIcon(selectedIcon);\n}", "updateHighlight() {\n var on = this.hover || this.selected;\n this.highlighted = on;\n if (on) {\n this.material.emissive = this.defaultEmissiveness;\n } else {\n this.material.emissive = this.defaultE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Implement the removeTail method here
removeTail() { if(this.length === 0){ return undefined } let oldTail = this.tail if(this.length === 1){ this.head = null this.tail = null this.length-- return oldTail } let current = this.head while(curre...
[ "removeTail() {\n this.lastTail = this.place.pop();\n }", "removeTail() { // my forLoop was quite off and hard to track. Using aA solution as a start...\n if (!this.head) return undefined; // If there is no head\n // Set the new Tail and current position to be head\n let current = t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort Movies by Title
function sortByTitle(movies) { movies.sort(function(a, b) { return a.title.localeCompare(b.title); }); }
[ "static allByTitle() {\n return movies.sort(function (a, b) {\n if (a.title < b.title) {\n return -1;\n }\n if (a.title > b.title) {\n return 1;\n }\n return 0;\n });\n }", "function sortMoviesByTitle(movies) {\n var x = 0;\n var temp;\n while(x < movies.leng...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setEvent(id , type, funcName) Make life a little easier. Set event handler for given id. Show useful console log on errors return: true if succeed
function setEvent(id , type, funcName) { let elem = document.getElementById(id); if( !elem ) { console.log(` DEBUG WARNING! Eventlistener for #${id} is undefined.`); return false; } elem.addEventListener( type , funcName ); return true; }
[ "set_event_handler(name, callback) {\n this.event_handlers[name] = callback\n }", "function setHandler(obj,eventName,fnCall, optStr) {\n var eventStr,fnName,fnArray=new Array(),i=0;\n eventStr = obj.getAttribute(eventName);\n if (eventStr) { //if event exists\n fnName = fnCall.substring(0,fnCall.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Byteswap an arbitrary buffer, flipping from one endian to the other, returning a new buffer with the resultant data
function byteswap64(buf) { var swap = Buffer.alloc(buf.length); for (var i = 0; i < buf.length; i++) { swap[i] = buf[buf.length -1 - i]; } return swap; }
[ "function byteswap64(buf) {\n var swap = new Buffer(buf.length);\n for (var i = 0; i < buf.length; i++) {\n swap[i] = buf[buf.length -1 - i];\n }\n return swap;\n}", "function to_little_endian(){\n\tbinary_input.reverse();\n\tbinary_key.reverse();\n}", "function _swapEndian(val, length) {\n if (length <...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method to get the nationalnumber part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.
function getNationalNumberGroups(metadata, number, formattingPattern) { if (formattingPattern) { // We format the NSN only, and split that according to the separator. var nationalSignificantNumber = util.getNationalSignificantNumber(number); return util.formatNsnUsingPattern(nationalSignificantNumber, for...
[ "function getNationalNumberGroups$1(metadata, number, formattingPattern) {\n if (formattingPattern) {\n // We format the NSN only, and split that according to the separator.\n var nationalSignificantNumber = util.getNationalSignificantNumber(number);\n return util.formatNsnUsingPattern(nationalSignificant...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Upon starting the periodic timer, this is our initial (oneshot) timer routine. Reset secsRemaining if the round just ended. Regardless, our 'Play or Lobby?' state needs settting up call firstXxxTick()
function firstTick(context) { if (secsRemaining == 0) { secsRemaining = SECS_IN_COMPLETE_CYCLE; } if (secsRemaining <= SECS_IN_LOBBY) { firstLobbyTick(context); } else { firstPlayTick(context); } logNow('firstTick():\ttimer: ' + cur...
[ "function timerTick(context)\n {\n // logNow('timerTick(): \\tsecsRemaining:\\t' + secsRemaining + ' \\t');\n if (secsRemaining >= SECS_IN_LOBBY)\n {\n playTick(context);\n \n if (secsRemaining == SECS_IN_LOBBY)\n {\n firstLobbyTick(context);\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up yeoman generators
function setupGenerators() { const env = yeoman.createEnv(); env.register(path.join(__dirname, '../generators/app'), PREFIX + 'app'); env.register( path.join(__dirname, '../generators/extension'), PREFIX + 'extension', ); env.register( path.join(__dirname, '../generators/controller'), PREFIX +...
[ "function yeoman(argv, options) {\n var env = require('yeoman-generator')([], options);\n var deferred = when.defer();\n\n options = options || {};\n\n ['marionette', 'angular', 'todos', 'ionic']\n .forEach(function (name) {\n env.registerStub(require('./generators/' + name), name);\n });\n // Speci...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns tabids for selected tabs
function getSelectedTabs(){ console.log(gTabList.finderSelect("selected") ); var selectedTabs = gTabList.finderSelect("selected"); var tabIds = []; for(var i=0, n=selectedTabs.length;i<n;i++) { tabIds.push(parseInt(selectedTabs[i].id)); } return tabIds; }
[ "function getTabIds() {\n Reporter_1.Reporter.debug('Get all ids of all open tabs');\n return tryBlock(() => browser.getWindowHandles(), 'Failed to get tab ids');\n }", "function allTabIDs() {\n return $('.tablink').map(function getTabId() {\n return $(this).attr('href');\n }).get();\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pushes a generator descriptor to the stack A descriptor requires a weight and a function that takes an point and returns a value between 0 and 1
generator( params ) { if ( !params ) { throw new Error( 'Heightmap::generator descriptor required' ) } if ( !params.weight || !params.fn ) { throw new Error( 'Heightmap::generator invalid descriptor' ) } this.funcs.push( params ) return this ...
[ "set weight0(value) {}", "set weight1(value) {}", "function build(generator, chart, neuron) {\n var svg = chart.svg();\n var colours = [\"red\", \"blue\"];\n // slide 39 start\n // var example = generator.examples(1);\n // var weights = neuron.step(\n // generator.weights, // w\n // exa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a Promise which will be resolved where there's no scroll event observed during 15 frames. TODO: This function should be written with `scrollend` event.
function waitForScrollEnd(eventTarget) { const MAX_UNCHANGED_FRAMES = 15; return new Promise(resolve => { let unchanged_frames = 0; let lastScrollEventTime; const scrollListener = () => { lastScrollEventTime = document.timeline.currentTime; }; eventTarget.addEventListener('scroll', scrol...
[ "async function waitForScrollStop(doc) {\n const el = doc.documentElement;\n const win = doc.defaultView;\n let lastScrollTop = el.scrollTop;\n let stopFrameCount = 0;\n while (stopFrameCount < 30) {\n // Wait for a frame.\n await new Promise(resolve => win.requestAnimationFrame(resolve));\n\n // Chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a list of keys.
async multiDelete(keys) { return await this.dbOp(async (db) => { let store = this.getStore(db); let promises = []; for(let key of keys) { let request = store.delete(key); promises.push(KeyStorage.awaitRequest(request)); ...
[ "function delMany(keys) {\n var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();\n return customStore('readwrite', function (store) {\n keys.forEach(function (key) {\n return store.delete(key);\n });\n return promisifyRequest(store.transaction);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Write a function "makeBox" which is given a width and height and returns a hollow box of those dimensions. Example: makeBox(6, 4)
function makeBox (width, height) { var i var solid = repeatChar (width,"*") var top = "" var bottom = "" var middle = "" if (height>0){top = solid} if (height>1){bottom = "\n" + solid} for (i=1; i<height-1; i++){ middle = middle + "\n" + "*" + repeatChar(width-2," ") + "*" ...
[ "function makeBox(width, height) {\n let box = '';\n //Create the end caps for the box\n let myTop = '*'.repeat(width) + '\\n';\n let myBottom ='*'.repeat(width);\n let boxMiddle = '';\n //create the middle lines with spaces between\n for (let i = 1; i < width; i++) {\n box = '*' + (' '....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the first video in the playlist.
loadVideo() { if (!this.state.loaded || !this.props.playlist || !this.props.playlist.length) return; else this.setState({ empty: false }); this.state.player.loadVideoById({ 'videoId': this.props.playlist[0].url, 'startSeconds': 0 }); }
[ "playFirstVideo() {\n this.currentPos_ = 0;\n this.reloadCurrentVideo_(this.onFirstVideoReady_.bind(this));\n }", "function playNextVideo() {\n if (firstTime) {\n loadPlaylist();\n firstTime = false;\n } else {\n if (currentVideoIndex >= playlistLength - 1) {\n playlistDone = tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load projects and create elements to use later
function initData() { projects.completed.forEach(function (project) { completedProjectElements.push(makeProjectEl(project)); }); projects.incomplete.forEach(function (project) { incompleteProjectElements.push(makeProjectEl(project)); }); } // append projects to DOM
[ "function populateProjects() {\n const PROJECT_CATEGORIES = Object.keys(PROJECT_DATA.projects);\n const PROJECT_CONTAINER = document.querySelector(\"#projectsContainer\");\n\n for (let cat of PROJECT_CATEGORIES) {\n const PDATA = PROJECT_DATA.projects[cat];\n const MASTER_CONTAINER = createElement(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
THIS IS A FUNCTION CALLED LIMIT CHECK IT LIMITS THE NUMBER OF CHECKBOXES THAT CAN BE CHECKED AT A TIME ONLY 2 BOXES CAN BE CHECKED
function limitCheck(){ var a = document.getElementsByName('variable'); // GET HTML OBJECT var newvar = 0; for(var count=0; count<a.length; count++){ if(a[count].checked==true){ newvar=newvar+1; } } if(newvar>...
[ "function checkboxlimit(checkgroup, limit){\n for (var i=0; i<checkgroup.length; i++){\n checkgroup[i].onclick=function(){\n var checkedcount=0\n for (var i=0; i<checkgroup.length; i++)\n checkedcount+=(checkgroup[i].checked)? 1 : 0\n if (checkedcount>limit)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert new data into collection
function DB_insertNewData(collection, data) { return db.collection(collection).doc(data.id).set(data); }
[ "'entries.insert'(doc){\n\t\t\tEntries.insert(doc);\n\t\t}", "insert() {\n // Prepare collection with bundle schema.\n this.collection.simpleSchema = () => {\n return this.schema;\n };\n return this.collection.insert.apply(this.collection, arguments);\n }", "function insertFood({name,price}){\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
permitira seleccionar o no el footer del producto
function addFooter(card) { let cardFooter; let data; cardFooter = card.querySelector('.card-footer'); if (card.getAttribute('data-selected') == 'true') { data = query.getAttributes(card); cardFooter.classList.remove('bg-info'); card.setAttribute('data-selected', false); r...
[ "function addFooter(card) {\n let cardFooter;\n let data;\n cardFooter = card.querySelector('.card-footer');\n if (card.getAttribute('data-selected') == 'true') {\n data = query.getAttributes(card);\n let product = searchProduct(data.idproduct);\n addClicksQuantity(data.idproduct, \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A class that defines how a scoreboard acts Includes displaying the player score Scoreboard constructor Sets the properties with the provided arguments
function Scoreboard (x,y,size,name,paddle){ this.x = x; this.y = y; this.size = size; this.name = name; this.paddle = paddle; this.score; this.xCenter = this.x + this.size/2; this.character; this.text; }
[ "scoreboard() {\n const that = this;\n const scoreboardObject = {\n players: [],\n scoreboard: document.querySelector('.scoreboard'),\n addPlayer(oPlayer) {\n this.players.push(oPlayer);\n const playerNameDiv = `<div class='player-name'>${...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of live cells in a given array of coordinates. This is used to count the number of live neighbors for a cell, but it can count the number of live cells for any arbitrary array of cell coordinates in a given grid.
function countLiveCells(coords, grid) { let sum = 0; for (let coord of coords) { // `for..of` loop is much faster than `reduce()` sum += grid[coord[0]][coord[1]]; } return sum; }
[ "countLiveNeighbors(x, y, grid) {\n const height = grid.length;\n const width = grid[0].length;\n const size = { width, height };\n let count = 0;\n let row;\n \n let prevY = y - 1;\n let nextY = y + 1;\n let prevX = x - 1;\n let nextX = x + 1;\n \n if (prevY < 0) {\n prevY ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get firstname from fullname
function getFirstName(fullname){ let firstName = fullname.trim(); // If fullname includes a space, firstname is what comes before that first space if (fullname.includes(" ")) { firstName = firstName.substring(0, firstName.indexOf(" ")); firstName = firstName.substring(0,1).toUpperCase() + fi...
[ "function extractFirstName(fullName){\n\tvar fName = fullName.split(' ').slice(0, -1).join(' ');\n\tif(fName == \"\"){\n\t\treturn fullName;\n\t}\n\telse{\n\t\treturn fName;\n\t}\n}", "function getFirstname(student){\r\n \r\n const firstSpace = student.fullname.indexOf(\" \");\r\n const firstName = student.ful...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Port of master/core/src/processing/core/PImage.javaL1250 Optimized code for building the blur kernel. further optimized blur code (approx. 15% for radius=20) bigger speed gains for larger radii (~30%) added support for various image types (ALPHA, RGB, ARGB) [toxi 050728]
function buildBlurKernel(r) { var radius = (r * 3.5)|0; radius = (radius < 1) ? 1 : ((radius < 248) ? radius : 248); if (blurRadius !== radius) { blurRadius = radius; blurKernelSize = 1 + blurRadius<<1; blurKernel = new Int32Array(blurKernelSize); blurMult = new Array(blurKernelSize); for(var...
[ "function buildBlurKernel(r){var radius=r*3.5|0;radius=radius<1?1:radius<248?radius:248;if(blurRadius!==radius){blurRadius=radius;blurKernelSize=1+blurRadius<<1;blurKernel=new Int32Array(blurKernelSize);blurMult=new Array(blurKernelSize);for(var l=0;l<blurKernelSize;l++){blurMult[l]=new Int32Array(256);}var bk,bki;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
singleBarChart is a function called by drawBarChart to draw the chart area for a single bar chart. The function takes in three parameters: data: object with four properties: values, labels, scale, and title (as defined for drawBarChart) options: object with eight properties: width, height, spacing, colour, labelColour,...
function singleBarChart(data, options, element) { // extracts needed information from data var values = data.values; var scale = data.scale; // extracts needed information from options var chartWidth = options.width; var chartHeight = options.height; var space = options.spacing; var colour = options.c...
[ "function singleCharts(array) {\n var wBar, elColor;\n\n // Transforming answers in percentage values for single charts and coloring them\n for( i=0; i<array.length; i++) {\n wBar = array[i]*33.33;\n elColor = assignColor(array[i]);\n $('.result-value[data-answer=\"'+(i+1)+'\"]').find(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if user clicks no, don't add anything but change the pic
function doNotAdd() { if (imgIndex >= 5) { return false; } imgIndex += 1; setNum.innerText = imgIndex; if (imgIndex >= 5) { birdthday.innerText = day; showResult.style.display = 'block'; playAgainBtn.style.display = 'inline-block'; return false; } imgSet.src = imgs[imgInd...
[ "function add(){\r\n\t\t$(\"#OtherChoice\").attr(\"src\", \"Assets/Img/\" + otherChoose + \".jpg\")\r\n\t}", "function postImage(){\n\tcancelImage();\n\tvar update = \"\";\n\tif (document.getElementById(\"sonicbtn\").checked){\n\t\tupdate = \"<p><img src='sonic.png' height='150'></p>\"\n\t}else if (document.getEl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates client area for cell.
updateClientAreaForCell(cell, beforeLayout) { // tslint:disable-next-line:max-line-length let rowWidget = cell.ownerRow; let cellWidget = cell; if (beforeLayout) { this.clientActiveArea.x = this.clientArea.x = cellWidget.x; this.clientActiveArea.y = cellWidget.y; ...
[ "updateClientAreaForTable(tableWidget) {\n this.clientActiveArea.x = this.clientArea.x = tableWidget.x;\n this.clientActiveArea.width = this.clientArea.width = tableWidget.width;\n }", "updateClientAreaLocation(widget, area) {\n widget.x = area.x;\n widget.y = area.y;\n widge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function scrapes the title from the HTML of the Netflix video player
function getNetflixMediaTitle() { console.log("waiting to load video "); setTimeout(() => {chrome.tabs.query({active: true}, function(tabs){ var tab = tabs[0]; chrome.tabs.executeScript(tab.id, { code: 'document.querySelector(".ellipsize-text").textContent' }, function(results){ sendData(results.toString(), ...
[ "function getVideoTitle() {\n return document.querySelector(\".ytp-title-link\").innerText;\n}", "function get_yt_title(ytid, i) {\n $.get('https://gdata.youtube.com/feeds/api/videos/' + ytid + '?v=2', function (xml) {\n var s = $(xml).find('entry').find('title').text();\n document.getElementById('vp-...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private Functions Library: T1.C2.Client.Controls.GridControl
function T1_C2_Shell_Controls_GridControl() { /// <summary> /// Initialises a new instance of the gridControl control /// </summary> /* * Private Members */ var myPublicApi; /* * Private Functions */ /* ...
[ "function GridControl(selName, layerObj)\n{\n // properties\n this.selectName = selName;\n\n if (layerObj)\n {\n this.object = dwscripts.findDOMObject(selName, layerObj);\n }\n else\n {\n this.object = dwscripts.findDOMObject(selName);\n }\n \n this.list = new Array();\n this.valueList = new Array...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update server with player direction+speed input change (ie: joystick status) charID should be the EntityModel.uuid of the character being controlled vecDir should be the direction of movement (will be unitized on server before multiplied by speed) gameTime should be the gameTime the player input happened (so it can be ...
sendInputImpulseChange( charID, vecDir, speed, facing, gameTime ) { this.send("playerImpulse", { charID:charID, vecDir:vecDir.toJson(), speed:speed, facing:facing, gameTime:gameTime }, (data)=>{ if (data.inputDT) { this.avgLagMS = (this.avgLagMS + data.inputDT) / 2 } ...
[ "function updateCharacter()\n {\n player.displayRender();\n\n if (inputDown) deathWasBeforeUserInput = false;\n\n if(inputDown && player.contact)\n {\n player.displayStandingAnim();\n player.stopMoving();\n }\n else if (player.contact)\n {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To initialize AWS Bucket Configurations
function InitAWSConfigurations() { bucketName = $("#hdnBucketName").val(); bucketStartURL = $("#hdnBucketStartURL").val(); AWS.config.update({ accessKeyId: $("#hdnAWSAccessKey").val(), secretAccessKey: $("#hdnAWSSecretKey").val(), region: $("#hdnBucketRegion").val() }); ...
[ "async init() {\n // TODO: This is not SAFE! If cache is not populatd, and DB access\n // takes a long time there is a risk that s3 variable\n // will not be configured!\n AWS.config.update({\n accessKeyId: process.env.AWS_ACCESS_KEY_ID,\n secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Image Slice display slice of part of an image
function ImageSlice(element, data) { this.element = element; if (data) { this.set(data); } }
[ "function createSlices(img) {\n\t\tvar nSlices, s, i;\n\t\tnSlices = p.floor(img.width / sliceSize);\n\t\ts = [];\n\n\t\tfor (i = 0; i < nSlices; i++) {\n\t\t\ts[i] = new Slice(i * sliceSize, sliceSize, img);\n\t\t}\n\n\t\treturn s;\n\t}", "function Slice(x,y,height,width){\n\tthis.x=x;\n\tthis.y=y;\n\tthis.Heigh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new Token Swap
static async createTokenSwap(connection, payer, tokenSwapAccount, authority, tokenAccountA, tokenAccountB, poolToken, mintA, mintB, feeAccount, tokenAccountPool, swapProgramId, tokenProgramId, nonce, tradeFeeNumerator, tradeFeeDenominator, ownerTradeFeeNumerator, ownerTradeFeeDenominator, ownerWithdrawFeeNumerator, own...
[ "create(tokenvm) {\n if(typeof(params) != 'object') {\n let today = new Date().getTime(); \n tokenvm = {\n user_id: tokenvm,\n expire: new Date(today + 2160000000)\n };\n }\n\n return Token.create(tokenvm);\n }", "sa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize Callback functions for the FlickrOAUth wrapper are set here
function init() { FlickrOAuth.setFlickrUpdateCb(function(s, m, d, o){flickrUpdate(s, m, d, o);}); FlickrOAuth.setAuthenticateCb(function(status, oAuthData){authenticateCb(status, oAuthData);}); // load the number of simultanious downloads from the prefs prefs = Services.prefs.getBranch("extensions.FlickrGetSet...
[ "function sidebar_flickr_Init() {\n var iOpacity = 0.3;\n \n // Load the photos using the jquery flickr plugin\n $(\"#flickr\").flickr({\n api_key: \"66d40a71c9038b033d5e80fc1337b6a1\",\n type: \"search\",\n user_id: \"27969974@N08\",\n per_page: 12,\n callback: function() {\n // chang...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append all elements to the DOM
appendElements() { this.appendChild(this.container) }
[ "function appendToDOM(){\n const eventsHTML = generateEventsHTML();\n $('main').html(eventsHTML);\n}", "append(content) {\n if (this.elements.length === 0) return;\n // if (typeof content === 'object' &&\n // !(content instanceof DOMNodeCollection)) {\n // content = domino(content);\n // ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
As Retuns the object if it implements the interface, else null
function as(object, method) { return method in object ? object : null; }
[ "get javaInterface() {}", "function _checkinterface(x,intrfc)\n{ if (x===null || x._interfaces.indexOf(intrfc)>=0) return x;\n throw (new java_lang_ClassCastException())._0()._e; \n}", "function classOrNil(obj) { return (functionOrNil(obj) && (obj.prototype && obj === obj.prototype.constructor) && obj) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the absolute right value of a DOM element.
function getAbsoluteRight(elem) { return elem.getBoundingClientRect().right; }
[ "function getDomValue() {\n\t\t\t\tvar val = elem.val();\n\t\t\t\tif (val === attrs.placeholder) {\n\t\t\t\t\tval = '';\n\t\t\t\t}\n\t\t\t\treturn val;\n\t\t\t}", "function getElementValue(id) { return getElement(id).value; }", "static getElementValue($element) {\n var type = $element.attr('type');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculates gains and loss of a stock
function calculateGainAndLoss(stockDetails) { const name = getNameOfStock(stockDetails.description); const longTermAmount = parseCurrency(stockDetails["LT L/G"]); const shortTermAmount = parseCurrency(stockDetails["ST L/G"]); if (longTermAmount > 0) { uniqueGlobalStocks[name].longTermGain += longTermAmount;...
[ "function computeGainsAndLosses() {\n //Don't refresh now\n updating = true;\n gains = 0;\n losses = 0;\n\n //I know it's ugly, but better do the comparison once than in every loops...\n if(localStorage.getItem('ignoreHidden') === 'true') {\n if(localStorage.getI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
grabs the index of the array of the smallest difference thus finding the most compatible friend
function indexOfSmallest() { index = 0; var value = diffArray[0]; for (var i = 1; i < diffArray.length; i++) { if (diffArray[i] < value) { value = diffArray[i]; index = i; } } matchSelect(); }
[ "function closest (friendCompareArray) {\r\n\r\n\tvar smallestValue = friendCompareArray[0]\r\n\tvar smallestIndex\r\n\r\n\tfor (var i = 0; i < friendCompareArray.length; i++) {\r\n\t\t\r\n\t\tif (friendCompareArray[i] < smallestValue) {\r\n\t\t\tsmallestValue = friendCompareArray[i]\r\n\t\t\tsmallestIndex = i\r\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
qForm Methods define qForm loadFields(); prototype
function _qForm_loadFields(){ var strPackage = _getCookie("qForm_" + this._name + "_" + _c_strName); // there is no form saved if( strPackage == null ) return false; this.setFields(_readCookiePackage(strPackage), null, true); }
[ "function FormView() {\n\t\n\t//oFormFields is JSON Object like: \t\n\t//\t{\n\t//\t\t\"subform_0\": {\n\t//\t\t\t\"cred_id\": \"tm\",\n\t//\t\t\t\"form_ID\": \"91\",\n\t//\n\t//\t\t},\n\t//\t\t\"subform_1\": {\n\t//\t\t\t\"page_num_02\": \"\",\n\t//\t\t\t\"doc_number_01\": \"\",\n\t//\t\t\t\"file_number_01\": \"\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
onPairListDevices is called when a user is adding a device and the 'list_devices' view is called. This should return an array with the data of devices that are available for pairing.
async onPairListDevices() { return [ // Example device data, note that `store` is optional // { // name: 'My Device', // data: { // id: 'my-device', // }, // store: { // address: '127.0.0.1', // }, // }, ]; }
[ "async onPairListDevices()\n {\n console.log(\"Pairing started\");\n\n }", "function onListDevices() {\n let endpoint = \"/enterprises/\" + projectId + \"/devices\";\n deviceAccessRequest('GET', 'listDevices', endpoint);\n}", "function listDevices() {\n return particle.listDevices({ auth: toke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
supports_parallel_query computed: true, optional: false, required: false
get supportsParallelQuery() { return this.getBooleanAttribute('supports_parallel_query'); }
[ "reduceInRelation(className: string, query: any, schema: any): Promise<any> {\n // Search for an in-relation or equal-to-relation\n // Make it sequential for now, not sure of paralleization side effects\n const promises = [];\n if (query['$or']) {\n const ors = query['$or'];\n promises.push(\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::WAFv2::WebACL.SizeConstraintStatement` resource
function cfnWebACLSizeConstraintStatementPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnWebACL_SizeConstraintStatementPropertyValidator(properties).assertSuccess(); return { ComparisonOperator: cdk.stringToCloudFormation(properties.compa...
[ "function CfnWebACL_SizeConstraintStatementPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function that returns the total race time
function totalRace() { return player1Time + player2Time; }
[ "function getTotalRaceTime() {\n return player1Time + player2Time\n}", "function getRaceTime() {\n\t\ttimeEnd = Date.now();\n\t\tisRaceStarted=true;\n\t\treturn (timeEnd - timeStart)/1000;\n\t}", "inputRaceTime(match, racer1Time, racer2Time) {\n if (racer1Time != null) {\n if (match.racer1Time1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Module 8: Organize code using TypeScript namespaces Lab Start / TODO Create LoanPrograms namespace. / TODO Update the calculateInterestOnlyLoanPayment function.
function calculateInterestOnlyLoanPayment(loanTerms) { let payment; payment = loanTerms.principle * calculateInterestRate(loanTerms.interestRate); return 'The interest only loan payment is ' + payment.toFixed(2); }
[ "function calculateInterestOnlyLoanPayment(loan) {\n // Calculates the monthly payment of an interest only loan\n let interest = loan.interestRate / 1200; // Calculates the Monthly Interest Rate of the loan\n let payment;\n payment = loan.principle * interest;\n return \"The interest only loan paymen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Link an element with compiled configuration
function linkElement(compileData, options){ angular.extend(compileData.locals, options); var element = compileData.link(options.scope); // Search for parent at insertion time, if not specified options.eleme...
[ "function linkElement(compileData, options){\n\t angular.extend(compileData.locals, options);\n\t\n\t var element = compileData.link(options.scope);\n\t\n\t // Search for parent at insertion time, if not specified\n\t options.element = element;\n\t options.parent = findP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get localized beta app information for a specific app and locale.
function readBetaAppLocalizationInformation(api, id, query) { return api_1.GET(api, `/betaAppLocalizations/${id}`, { query }) }
[ "function readAppInformationForBetaAppLocalization(api, id, query) {\n return api_1.GET(api, `/betaAppLocalizations/${id}/app`, { query })\n}", "function getAppResourceIDForBetaAppLocalization(api, id) {\n return api_1.GET(api, `/betaAppLocalizations/${id}/relationships/app`)\n}", "function listBetaAppLoc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an array of people objects, return a new array that has filtered out all those who don't belong to the club.
function peopleWhoBelongToTheIlluminati(arr){ var newArr = arr.filter(function(item){ return item.member === true }) console.log(newArr) }
[ "function nonFriends(name, people){\n //find object representing the named person\n //go thru all the people \n //if the current persons name is the same as the name given save that object to a variable\n var out=[];\n var person;\n for (var i=0; i< people.length;i++){\n if (peop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
incidents table population flow
function incidents(callback) { var db = new sql.Database("football.db"); console.log("populating the incidents table"); fluent.create({ table:"incidents", fileName:"results", db:db }).async({ checkTableExists:checkTableExists }, "table", "db").async({ createIncidentsTable:cre...
[ "function fillUpTable() {\r\n\tgetInstantValues();\r\n}", "function povoateTable(){\n if (all_orders != []) {\n all_orders.forEach(_order => {\n appendOrder(_order);\n });\n }\n}", "enterRelational_table(ctx) {\n\t}", "function populateTable(rows) {\n $internation...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extend all selections (pos is an array of selections with length equal the number of selections)
function extendSelections(doc, heads, options) { for (var out = [], i = 0; i < doc.sel.ranges.length; i++) out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); var newSel = normalizeSelection(out, doc.sel.primIndex); setSelection(doc, newSel, options); }
[ "function extendSelections(doc, heads, options) { // 1210\n for (var out = [], i = 0; i < doc.sel.ranges.length; i++) // 1211\n out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register an execution context for executing tasks. The following execution context implementations are registered by default: 'main' Directly executed in the main node instance in which PencilPusher runs as well 'child oneoff' A child process that is started to run a single task only 'child reused' One of multiple chil...
registerExecutionContext(name, executionContext) { return this._taskDispatcher.registerExecutionContext(name, executionContext) }
[ "async function injectExecutionContext({ context, fetcher, temporaryBlobStorage, logger, endpoint, invocationLocation, timezone, invocationToken, sync, }) {\n // Inject all of the primitives into a global we'll access when we execute the pack function.\n const executionContextPrimitives = {\n fetcher: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize the table alignment
serializeTableAlignment(writer, format) { writer.writeStartElement(undefined, 'jc', this.wNamespace); switch (format.tableAlignment) { case 'Right': writer.writeAttributeString('w', 'val', this.wNamespace, 'right'); break; case 'Center': ...
[ "serializeTableIndentation(writer, format) {\n writer.writeStartElement(undefined, 'tblInd', this.wNamespace);\n let tableIndent = Math.round(format.leftIndent * this.twipsInOnePoint);\n writer.writeAttributeString(undefined, 'w', this.wNamespace, tableIndent.toString());\n writer.writeA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the conditions on the server
updateConditions(conditions, cb) { this.session.patch({ url: this.url + '/api/filter/conditions', json: conditions, }, cb); }
[ "function updateConditions() {\n\t// First, reset all condition variables\n\tresetConditions();\n\t\n\t// And set them\n\tif (Z) {\n\t\tEQ = true;\n\t} else {\n\t\tNE = true;\n\t}\n\tif (C) {\n\t\tCS = true;\n\t} else {\n\t\tCC = true;\n\t}\n\tif (N) {\n\t\tMI = true;\n\t} else {\n\t\tPL = true;\n\t}\n\tif (V) {\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the projectLibraries names, potentially filtered by config
getProjectLibNames(framework) { let projectLibraries = []; const frameworkConfig = this.config.stepByStep && this.config.stepByStep[framework.id]; if (frameworkConfig && frameworkConfig.projTypes && frameworkConfig.projTypes.length) { frameworkConfig.projTypes.forEach(x => { ...
[ "getProjectLibraryNames(frameworkId) {\n let projects = [];\n const framework = this.frameworks.find(f => f.id === frameworkId);\n if (framework) {\n projects = framework.projectLibraries.map(x => x.name);\n }\n return projects;\n }", "getLibraries() {}", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get company name from ticker for news search
async function getCompanyName(ticker) { if (!ticker || ticker === '') throw 'You need to provide ticker' // console.log(ticker) try { const nameData = await axios.get('https://api.iextrading.com/1.0/ref-data/symbols') let symbolList = nameData.data // consol...
[ "function getCompanyName (ticker) {\n let companyInfo = `${iexBaseURL}/${ticker}/company?token=${iexApiToken}`;\n \n fetch(companyInfo)\n .then(companyInfo => companyInfo.json())\n .then(companyInfoJson => displayCompanyName(companyInfoJson))\n .catch(err => console.log(err));\n \n}", "function getCo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the Pagination that is currently used by the grid
getCurrentPagination() { return this._currentPagination; }
[ "getCurrentPagination() {\n if (this._gridOptions.enablePagination) {\n if (this._gridOptions && this._gridOptions.backendServiceApi) {\n const backendService = this._gridOptions.backendServiceApi.service;\n if (backendService && backendService.getCurrentPagination) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finalize this query and return the total amount of matching Model instances
async count() { // Call internally stored DB API to return the amount of models matching self query return await this._db.count(this._Model, this); }
[ "async count(Model, query) {\n // Get collection ID of provided Model\n const collectionId = modelCollectionId(Model);\n\n // Return count of Model instances matching provided query\n return await this._plug.count(collectionId, query);\n }", "countAll() {\n let sqlRequest = \"SELECT COUNT(*) A...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the ab...
function LargeObject(i) { this.a = i; this.b = i; this.c = i; this.d = i; this.e = i; this.f = i; this.g = i; this.h = i; this.i = i; this.j = i; this.k = i; this.l = i; this.m = i; this.n = i; this.o = i; this.p = i; this.q = i; this.r = i; this.s = i; this.t...
[ "function wasm_alloc(instance, size) {\n return syscall(instance, /* mmap */ 192, [0, size]);\n}", "function createObject() {\n // This literal has least kMaxRegularHeapObjectSize / 64 number of\n // properties, forcing the backing store to be in large object space.\n return { __proto__:null,\n p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Submits a new jam and brings user to fresh jam page upon completion
function submitJam(jamData) { $.post("/api/jams/", jamData, function() { location.reload(); }); }
[ "function submitProject(Project) {\n $.post('/api/project/new', Project, function() {\n window.location.href = '/projects';\n });\n }", "function go() {\n if(part.locked) {\n return;\n }\n part.submit();\n Numbas.store.save();\n }", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of file paths for the service worker to precache, based on the information provided in the DepsIndex object.
function getPrecachedAssets(depsIndex, project) { let precachedAssets = new Set(project.analyzer.allFragments); precachedAssets.add(project.entrypoint); for (let depImports of depsIndex.fragmentToFullDeps.values()) { depImports.imports.forEach((s) => precachedAssets.add(s)); depImports.scrip...
[ "function precache() {\n return caches.open(CACHE).then(function (cache) {\n return cache.addAll(filesToCache);\n });\n}", "function getBundledPrecachedAssets(project) {\n let precachedAssets = new Set(project.analyzer.allFragments);\n precachedAssets.add(project.entrypoint);\n precachedAsse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
toEither :: (Either m) => a > m a
static toEither (value) { return value == null ? new Left(value) : new Right(value) }
[ "toEither() {\n return this._isSuccess\n ? Right(this.value)\n : Left(this.value);\n }", "function resultToEither(result) {\n if(isFunction(result)) {\n return function(x) {\n var m = result(x)\n\n if(!isSameType(Result, m)) {\n throw new TypeError('resultToEit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expects a canvas with a Minecraft skin drawn in the very top left corner (0,0) Makes the head overlay transparent if it is has no transparent pixels (how Minecraft does it)
function FixHead2(context) { // Front if(HasTransparency(context, 40, 8, 8, 8)) return; // Top, Bottom, Right, Left, Back if(HasTransparency(context, 40, 0, 8, 8)) return; if(HasTransparency(context, 48, 0, 8, 8)) return; if(HasTransparency(context, 32, 8, 8, 8)) return; if(HasTransparency(context, 48, 8, 8, 8...
[ "_makeCurrLayerOnion(canvas){\n canvas.style.opacity = .92; // apply onion skin to current canvas \n canvas.style.zIndex = 0;\n }", "function TRANSPARENT$static_(){LoadMaskSkin.TRANSPARENT=( new LoadMaskSkin(\"transparent\"));}", "function OPAQUE$static_(){LoadMaskSkin.OPAQUE=( new LoadMaskSkin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes store object and returns a record
function storeToRecord(store){ var record = {} shortRecord.forEach(function(prop){ var value = _.get(store,prop); _.set(record,prop,value); }); var keys=["info","materials","command","meta"]; record.pack =_.omit(record.pack,"parsed"); keys.forEach(function(key){ record.pack[key] = _.omit(recor...
[ "function getStore$1(txn, store) {\r\n\t if (txn instanceof SimpleDbTransaction) {\r\n\t return txn.store(store);\r\n\t }\r\n\t else {\r\n\t return fail('Invalid transaction object provided!');\r\n\t }\r\n\t}", "function getStore$1(txn, store) {\n if (txn instanceof SimpleDbTransactio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Depends on singleColumn property on Contentful dataObject
singleColumn() { return this.uiSetting?.dataObject?.singleColumn ?? false; }
[ "function ColumnMeta() {}", "function wddxRecordset_isColumn(name)\n{\n\t// Columns must be objects\n\t// WddxRecordset extensions might use properties prefixed with \n\t// _private_ and these will not be treated as columns\n\treturn (typeof(this[name]) == \"object\" && \n\t\t name.indexOf(\"_private_\") == -1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create mapping variant of function
function mapping(f) { return function () { var rest = toArray(arguments); return function (x) { return map(function (v) { return f.apply(undefined, rest.unshift(v)); }, unit(x)); }; }; }
[ "map(mapFn) {\n return this._sequenceFromGenerator(map, [mapFn]);\n }", "function map(lookup, f) {\n return toLookup(keys(lookup), exports.identity, f);\n}", "function mapper(func){\n return function(x){\n return x.map(func);\n };\n}", "function map(fn) {\n return function(rf) { // <- build...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Marks the hidden siblings of the matched nodes as being not expandable.
function markHiddenSiblingsAsNotExpandable(nodes) { var siblings = nodes.siblings(":hidden"); siblings.addClass("wh_not_expandable"); }
[ "ensureInvisibility() {\n this.nodeVisible = false;\n }", "_hideDescendantItems() {\n Array.from(this._children).forEach(child => {\n child.setAttribute('aria-hidden', 'true');\n });\n }", "_markInvisibleEls() {\n let all = Array.from(this.el.getElementsByTagName(\"*\"));\n all.filte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exercise 25: Converting from Arrays to Trees When information is organized in a tree like a JSON expression, relationships point from parent to child. In relational systems like databases, relationships point from children to their parents. Both ways of organizing information are equivalent, and depending on the circum...
function ex25() { var lists = [ { "id": 5434364, "name": "New Releases" }, { "id": 65456475, "name": "Thrillers" } ], videos = [ { "listId": 5434364, "id": 65432445, "title": "The Chamber" }, { "listId": 5434364, "id": 675465, "title": "Fracture" }, ...
[ "function flattenArr() {\n\tvar movieLists = [\n\t\t{\n\t\t\tname: \"New Releases\",\n\t\t\tvideos: [\n\t\t\t\t{\n\t\t\t\t\t\"id\": 70111470,\n\t\t\t\t\t\"title\": \"Die Hard\",\n\t\t\t\t\t\"boxart\": \"http://cdn-0.nflximg.com/images/2891/DieHard.jpg\",\n\t\t\t\t\t\"uri\": \"http://api.netflix.com/catalog/titles/m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of function Function to locate and generate circle on the clicked position
function generatePosition(event) { var x = event.clientX; var y = event.clientY; var canvas = document.getElementById("canvas"); x = x - canvas.offsetLeft; y = y - canvas.offsetTop; //(x,y) is the center of the circle if(clickCount < 6){ coordinates.push(x); coordinates.push(...
[ "function circle() {\n\t\t\t// idk what's supposed to happen in here\n\t\t}", "function onCircleButtonClick() {\n if(isDeleteMode){\n isDeleteMode = false;\n clearTrackedValues();\n clearSketchFromCanvas();\n }\n\n if (!minX || !minY || !maxX || !maxY)\n return;\n\n let r =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Habilidades especiais do gPersonagem.
function _DependenciasHabilidadesEspeciais() { var especiais_antes = gPersonagem.especiais; var especiais_nivel_classe = []; for (var i = 0; i < gPersonagem.classes.length; ++i) { var entrada_classe = gPersonagem.classes[i]; if (tabelas_classes[entrada_classe.classe].especiais == null) { continue; ...
[ "function GeraPersonagem(modo, submodo) {\n if (!submodo) {\n submodo = 'tabelado';\n }\n var classe_principal = gPersonagem.classes[0];\n if (tabelas_geracao[classe_principal.classe] == null) {\n Mensagem(Traduz('Geração de ') + Traduz(tabelas_classes[gPersonagem.classes[0].classe].nome) + ' ' + Traduz('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cosntructor del objeto Amplifier. Ademas de los atributos comunes recibe la potencia y el tipo
function Amplifier(serialNumber, name = "", price = "", watts = "", type = "transistores") { //Abrimos el seguro para llamar al superconstructor abstractCreateLock = false; Product.call(this, serialNumber, name, price); abstractCreateLock = true; //Controlamos que type no sea vacio y que su valor e...
[ "constructor(type, multiplier){\n verifyType(type, TYPES.number);\n notNegative(multiplier);\n type = parseInt(type);\n switch(type){\n case Stat.PHYS:\n this.name = \"Physical attack\";\n this.type = type;\n this.base = OFFENSE * m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Switch active group to default
function switchActiveGroupToDefault(groupId, tabId) { if(groupId == GROUP_POPULAR_ID) { BRW_dbTransaction(function(tx) { BRW_dbSelect( {//Param tx : tx, from : 'GROUPS', where : { ...
[ "resetIsActiveFlagForGroups(groupObj) {\n groupObj.isActive = false;\n }", "setIsActiveFlagForGroups(groupObj) {\n groupObj.isActive = true;\n }", "function attemptGroupActivation() {\r\n\t\tgroupInView = self.findGroupInView();\r\n\t\tif (groupInView) {\r\n\t\t\tself.updateA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for decrypting encrypted phone numbers from firebase
function decrypt(phone) { let iv = Buffer.from(phone.iv, 'hex'); let encryptedText = Buffer.from(phone.encryptedData, 'hex'); let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv); decipher.setAutoPadding(false); let decrypted = decipher.update(encryptedText); decrypted = Buffer.concat...
[ "function decryptPhoneNumber(password, encryptedPhoneNumber, iv) {\n const key = crypto.scryptSync(password, \"salt\", 24);\n var decipher = crypto.createDecipheriv(\"aes-192-cbc\", key, iv);\n var decryptedPhoneNumber =\n decipher.update(encryptedPhoneNumber, \"hex\", \"utf8\") + decipher.final();\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pause all segment loaders
pauseLoading() { this.mainSegmentLoader_.pause(); if (this.audioPlaylistLoader_) { this.audioSegmentLoader_.pause(); } }
[ "pauseLoading() {\n this.delegateLoaders_('all', ['abort', 'pause']);\n this.stopABRTimer_();\n }", "pause() {\n if (this._playQueued) {\n this.once('play', () => {\n this._activeSegments.forEach((segment) => {\n segment.pause();\n });\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Singleton Logger's subclass instance of which is configured to display its messages to the console. It also provides the support of predefined messages and persists its display level.
function ConsoleLogger() { var formatter = new Formatter(), consoleHandler = new ConsoleHandler(formatter), savedLevel = storage.get(STORAGE_NAMESPACE), utils = new LoggerUtils(this); Logger.call(this, consoleHandler, entryFactory); if (savedLevel) { ...
[ "function Logger() {\n this.transports = [\n new transports.Console({\n level: level,\n timestamp: function () {\n return (new Date()).toISOString();\n }\n })\n ];\n this.logger = null;\n}", "static _loadConsoleLogger() {\n // Default log level for console is \"info\".\n let l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all values of a given column name
getColumnValues(columnName) { var queryResult = jsonQuery('intervalls.'+columnName, {data: this.data}).value; if (queryResult.length == 0){ throw new Error("Column name is not available in Trade Table. Names are case sensitive!"); } return queryResult; }
[ "function getColValues(data, colName) {\n let values = []\n data.map(function(row) { \n Object.keys(row).forEach(function(key){if (key==colName) values.push(row[key])})\n })\n return values\n}", "function returnColValues(ind) {\n\tvar data = [];\n\tif(ind > -1) {\n\t\t$.each(dataTblData, func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove high light for recent uploaded record
function remove_high_light(){ $scope.uploaded_file_id = 0; $('#uploadListTbl tr').removeClass('recent_uploaded_file'); }
[ "function removeUploadedImage() {\n showFrige(false);\n $upImage.removeAttr('style');\n $upload.find('#uploadedFile').val('');\n }", "stripETagsFromValue(recordAvatar){delete recordAvatar.result.eTag;return recordAvatar;}", "removeMedia(media, selectedTile, otherTile) {\n if (media.cr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively collate properties of two objects
function collate(obj1, obj2) { for (var p in obj2) { if ( obj2[p].constructor == Object ) { if (obj1[p]) { collate(obj1[p], obj2[p]); continue; } } if(typeof obj1[p] === 'undefined') { obj1[p] = obj2[p]; } } }
[ "function mergeRecursive (obj1, obj2) {\n for (var p in obj2) {\n try {\n // Property in destination object set; update its value.\n if (obj1[p].constructor == Object && obj2[p].constructor == Object) {\n obj1[p] = mergeRecursive(obj1[p], obj2[p]);\n } else {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To update the cost and selling price alert box:
function updateCostAndPrice() { $("#totalCostCalculated").text(Math.round(totalCostCalculated * Math.pow(10, 2)) / Math.pow(10, 2)); $("#sellingPriceAtSpan").text($("#profitMarginInput").val()); $("#sellingPrice").text((Math.round(sellingPrice * Math.pow(10, 2)) / Math.pow(10, 2))); ...
[ "function updatePrice() {\n\n //assigning various calculated prices to variables\n const baseprice = basePrice();\n const colorprice = colorPrice();\n const quantity = getQuantity();\n const bulkprice = getBulkPrice();\n const totalprice = (((basepr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ACTIVATE MENU ITEMS ON SCROLL
function activateMenuOnScroll(){ waq.$menu.$anchoredSections = $(); for(i=0;i<waq.$menu.$links.length; i++){ var $trigger = waq.$menu.$links.eq(i); var $section = $( '#' + $trigger.parent().attr('class').split(" ")[0] ); if($section.length) waq.$menu.$anchoredSections.push($section[0]); ...
[ "function setMenuActiveOnScroll() {\n for (let section of sectionsList) {\n if (isElementInViewport(section.children[0].children[0])) {\n setSectionActive(section.id);\n setMenuActive(section.id);\n }\n }\n}", "function _navScrollActive(){\r\n $.scrollIt();\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
saves task data to the DOM by its ID
function saveTaskData(id, obj) { const data = $("body").data(); const activeTasks = data.tasks.active; activeTasks[id] = obj; }
[ "function saveEditedEventTask(id) {\n\tvar name = document.getElementById(\"editTaskTableCell2\").firstChild.nodeValue;\n\tvar json = JSON.stringify({name: name});\n\tinteraction.updateEventTask(id, json);\n\t$('#modalOne').modal('hide');\n}", "function saveEditedTimeTask(id) {\n\tvar name = document.getElementBy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attach an event listener to an object. Invokes the handle() callback on every event, and the apply() handler eventually, but with at least 'delay' milliseconds between each invokation.
function addThrottledEventHandler (elem, event, handle, apply, delay) { let nextApply = window.performance.now(); let timerId = null; function invokeApply () { apply(); timerId = null; } elem.addEventListener(event, (ev) => { if (handle !== null) { handle(ev); } let now = window.performance.no...
[ "function bind(element, obj, events, capture) {\n capture = capture ? true : false;\n events = Array.isArray(events) ? events : [events];\n _.each(events, function(event) {\n element.addEventListener(event, obj, capture);\n });\n }", "function trigger(obj, name, args) {\n var prop, cb;\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
captureSwitch is a conditional template switch to show the progress view or the camera snapper based on the loadingCred state variable value
captureSwitch() { if (this.state.loadingCred) { return ( <View style={styles.buttonContainer}> <View style={styles.smallButtonContainer}> <Progress.CircleSnail color={['orange']} /> </View> </View> ); } /*Standard default return view if the loading...
[ "function onCaptureLandScapeTab(cameraObj)\n{\n\tkony.application.showLoadingScreen(\"loadingscreen\",\"Loading...\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true,null);\n\tfrmCamera.imgLandscape.rawBytes = cameraObj.rawBytes;\n\tkony.application.dismissLoadingScreen();\n}", "function onCapturePrivate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
looking for text on the canvas with mouse
function onCanvas(ev) { var textObj = gMeme.existText.find(function (text) { return ( ev.layerX >= text.x && ev.layerX <= text.x + text.xwidth && ev.layerY + text.yheight >= text.y && ev.layerY <= text.y + text.yheight ) }) if (textObj) { ...
[ "function checkMouseOnText(mouseX, mouseY){\n var idx = -1\n\n if (text_list.length == 0){\n idx = -1\n return idx;\n }\n else {\n //check if the mouse is on any text objects\n for(i=0; i<text_list.length; i++){\n var left = text_list[i].x;\n var top = t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description: Lat Lng min max calculator What it does: Calculates the minimum and maximum latitude and longitude coordinates given a distance from a latitude and longitude point. what it returns: Object with latMin, latMax, lngMin, lngMax
function latLngRangeCalc(lat, lng, d) { // Use to convert from degrees to rad var p = Math.PI / 180; // Radius of the Earth var R = 6371; var ans = {latMin:null, latMax:null, lngMin:null, lngMax:null}; // First iteration calculates longitude, second latitude for (i = 1; i < 3; i++) { // Bearing, co...
[ "function getPoint(latinput, loninput, min_longitude, max_longitude, min_latitude, max_latitude, mapwidth, mapheight) {\n \n //convert lat and long into pixel values\n var x = (loninput - min_longitude) / (max_longitude - min_longitude) * mapwidth;\n var y = mapheight - (latinput - min_latitude) / (max_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets if the provided structure is a ParameteredNodeStructure.
static isParametered(structure) { switch (structure.kind) { case StructureKind_1.StructureKind.Constructor: case StructureKind_1.StructureKind.ConstructorOverload: case StructureKind_1.StructureKind.GetAccessor: case StructureKind_1.StructureKind.Method: ...
[ "static isParameter(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.Parameter;\r\n }", "static isParameteredNode(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.Constructor:\r\n case typescript_1.SyntaxKind.GetAccessor:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluates, or attempts to evaluate, a TryStatement
function evaluateTryStatement({ node, evaluate, environment, reporting, statementTraversalStack }) { const executeTry = () => { setInLexicalEnvironment({ env: environment, reporting, newBinding: true, node, path: TRY_SYMBOL, value: true }); // The Block will declare an environment of its own ...
[ "function MyEval(expr)\r\n{\r\n try\r\n {\r\n return eval(expr);\r\n }\r\n catch(ex)\r\n {\r\n LogMsg(\"caught an exception: \" + ex);\r\n LogMsg(\"evaluating \" + expr);\r\n\r\n throw ex;\r\n }\r\n}", "function TryStatement() {\n}", "function TryToCatch( value, exp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reference to the Role Dropdown element, if present
get roleDropdownEl() { return this.element[0].querySelector('.dropdown'); }
[ "get roleDropdownContainerEl() {\n return this.element[0].querySelector('.module-nav-section.role-dropdown');\n }", "function chooseRole(rle) {\n\trole = rle;\n\tdocument.getElementById(\"roledropdown\").classList.toggle(\"show\");\n\tdocument.getElementById(\"role\").innerHTML = role;\n}", "function popula...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
count of people who voted, in object form
function whoVoted(people) { return people.reduce( function (final, vote) { if (vote.voted) { final.didVote++; } else { final.didntVote++; } return final; }, { didVote: 0, didntVote: 0 } ); }
[ "function voteTallyer() {\r\n for (var voter in votes) {\r\n for (var position in voteCount) {\r\n if (voteCount[position].hasOwnProperty(votes[voter][position])) {\r\n voteCount[position][votes[voter][position]] += 1;\r\n }\r\n else {\r\n voteCount[position][votes[voter][position]]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dismisses the current notification
dismiss() { this._updated = false this.notifier.classList.remove('active') }
[ "dismissNotification(notification) {\n this._get(\n \"dismissNotification?user=\" +\n this.state.user +\n \"&notificationid=\" +\n notification.id\n );\n }", "hideNotification() {\n clearTimeout(this.notification.timeout);\n\n this.notification.displa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that converts minutes to milliseconds for use in update_interval function
function min_to_ms(min) { return min*60*1000; }
[ "function minutesToMilliseconds (minutes){\n return minutes * 60000;\n }", "function toMillis(minutes) {\n return minutes * 60000;\n }", "getMillisecondsToNextPoll () {\n let {h, m} = this.getTimerTime()\n let hours = (h * 60 * 60 * 1000)\n let minutes = (m * 60 * 1000)\n return hours + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validation of a userentered instance type, displaying an error message if it's invalid.
function instanceAddCheckType() { var instanceType = $(instanceAddPage.typeFilter).val(); var validInstanceTypes = $(instanceAddPage.typeSelect + ' option').map(function() { return $(this).val(); }); if($.inArray(instanceType, validInstanceTypes) === -1) { instanceAddDisplayErrorMsg("Instance...
[ "checkType(type, instance) {\n let instanceVal;\n let conditionVal;\n if (type === 'styler') {\n instanceVal = instance.styler;\n conditionVal = this.styler;\n } else if (type === 'state') {\n instanceVal = instance.state;\n conditionVal = this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
request available components; the refreshMyNewOrder value here is optional. If provided to true, the functions will get the available components and refresh the myNewOrder object, thus setting all values to 'no' in turn unchecking all checked boxes. Be careful!
function getAvailableOrderComponents(refreshMyNewOrder) { ComponentService.getAvailableComponents('oc') .success(function (orderComponents) { $scope.availableOrderComponents = orderComponents.availableComponents; if (refreshMyNewOrder)...
[ "function getAllAvailable(refreshMyNewOrder) {\n if (refreshMyNewOrder) {\n getAvailableOrderComponents(true);\n getAvailableOmelets(true);\n getAvailableWeeklySpecials(true);\n getAvailableExtras(true);\n } el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
select random planet and play whacamole game
function randomPlanet() { planets.forEach(planet => { planet.classList.remove('landed') }) let randomPlanet = planets[Math.floor(Math.random() * 9)]; randomPlanet.classList.add('landed'); hitPosition = randomPlanet.id; }
[ "maybePlanet(){\n\t\tlet randnum = random(2000);\n\t\tif (randnum < 1){\n\t\t\tthis.makePlanet(random(width - 300));\n\t\t}\n\t}", "static getIdPlanetRandomly() {\n return Math.floor((Math.random() * TOTAL_PLANETS) + 1);\n }", "chooseRandPos(){\n\t\tthis.pos = planets[Math.floor(rand(0, planets.length))].po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CollisionManager class This manager class will check on collisions depending on the set policy
function CollisionManager(policy){ this.policy=policy; this.checkCollision=function(){ if(this.policy==Constants.defaultCollision){ checkCollisionDefault(); } }; /** * Check for collision with the default policy */ checkCollisionDefault=function(){ var user=entityManager.getUser(); ...
[ "_collision() {\n\n // obstacles to player\n this._do_collision(\n this.obstacleModels.slice(0), // don't remove when collision\n this.optionalPlayerModel,\n ObstacleAndPlayerCollisionDetector.INSTANCE,\n this._sounds.get(SOUND_EXPLOSION_PLAYER)\n );\n\n // player shots to enemies\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compile a unary Op.
compileUnary(o) { var op, parts, plusMinus; parts = []; op = this.operator; parts.push([this.makeCode(op)]); if (op === '!' && this.first instanceof Existence) { this.first.negated = !this.first.negated; return this.first.compileToFragments(o); } if (o.level >= LE...
[ "compileUnary(o) {\n var op, parts, plusMinus;\n parts = [];\n op = this.operator;\n parts.push([this.makeCode(op)]);\n if (op === '!' && this.first instanceof Existence) {\n this.first.negated = !this.first.negated;\n return this.first.compileToFragments(o);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }