query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Write a function, maxNonAdjacentSum(nums), that takes in an array of nonnegative numbers. The function should return the maximum sum of elements in the array we can get if we cannot take adjacent elements into the sum. Solve this problem with tabulation. Once you're done, come back and try to solve it with memoization....
function maxNonAdjacentSum(nums) { let table = new Array(nums.length).fill(0); table[0] = nums[0]; table[1] = Math.max(nums[0], nums[1]); for (let i = 2; i < table.length; i++) { table[i] = Math.max((nums[i] + nums[i - 2]), nums[i - 1]); } return table[nums.length - 1]; }
[ "function miniMaxSum(arr) {\n const results = arr.reduce((acc, curr, i, arr) => {\n if (acc.min >= curr) {\n acc.min = curr\n }\n if (acc.max <= curr) {\n acc.max = curr\n }\n acc.sum += curr\n return acc\n }, {\n min: 1000000000,\n max: 0,\n sum: 0\n })\n console.log(result...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rendering the imgs gallery
function renderGallery() { var imgs = getImgs() var strHtmls = imgs.map(img => { return `<img onclick="onImageClick(this)" id="${img.id}" src="${img.url}" alt="${img.keywords}"> ` }) document.querySelector('.gallery-container').innerHTML = strHtmls.join('') }
[ "function renderImages() {\n\t\t$('.landing-page').addClass('hidden');\n\t\t$('.img-round').removeClass('hidden');\n\t\tupdateSrcs();\n\t\tcurrentOffset+=100;\n\t}", "galleryItems() {\n return this.items.map((i) => <img key={i} src={i} alt=\"productimage+i\" id=\"responsive-gallery-image\"></img>)\n }", "_r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the ids of results at the requested layer
function getIdsAtLayer(results, layer) { return results.filter(result => result.layer === layer).map(_.property('source_id')); }
[ "function getLayersURL(layers, resultLayers, id) {\n var layer\n for (var i = 0; i < layers.length; i++) {\n layer = layers[i]\n // console.log(layer);\n if (layer.type == 'group') {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update font list for Label and Burg Editors
function updateFontOptions() { styleSelectFont.innerHTML = ""; for (let i = 0; i < fonts.length; i++) { const opt = document.createElement("option"); opt.value = i; const font = fonts[i].split(":")[0].replace(/\+/g, " "); opt.style.fontFamily = opt.innerHTML = font; styleSelectFont.add(opt); }...
[ "_listenFontSelectionChange() {\n var self = this;\n BB.comBroker.listenWithNamespace(BB.EVENTS.FONT_SELECTION_CHANGED, self, function (e) {\n if (!self.m_selected || e.caller !== self.m_labelFontSelector) {\n return;\n }\n var config = e.edata;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change timeformat from seconds to mm:ss
function changeTimeFormat(sec) { seconds = Math.round(sec); min = Math.floor(sec / 60); minutes = (min >= 10) ? min : "0" + min; seconds = Math.floor(seconds % 60); seconds = (seconds >= 10) ? seconds : "0" + seconds; return minutes + ":" + seconds; }
[ "function secConverter(min)\n{\n return min*60;\n}", "function secondsToTimeString(timeSeconds) {\n timeSeconds = Math.round(timeSeconds);\n var seconds = timeSeconds % 60;\n timeSeconds = Math.floor(timeSeconds / 60);\n var minutes = timeSeconds % 60;\n timeSeconds = Math.floor(timeSeconds / 60);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
listen to mongo db events
_setupDBEvents() { this.db.on('connected', ()=>{ this._status='connected'; this.logger.info(`DB connected.`); }); this.db.on('error', (err)=>{ this.lastError=err; this.logger.error('DB error', err); }); this.db.on('reconnected', ()=>{ this._status='connected'; t...
[ "function listenCollection(collection, listener) {\n collection.forEach(function listenModel(model) {\n listen(model, listener);\n });\n\n collection.on('add', function onAdd(model) {\n listen(model, listener);\n listener();\n });\n}", "pushRefreshedDatas() {\n var tt = thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform wiki data into timeline json format See format here:
async function transformToTLJson() { var timelineJson = {} timelineJson.events = []; // list of slide objects (each slide is an event) //wikiDate is in iso-8601 format function parseDate(wikiDate) { var wdate = new Date(wikiDate); return { year: wdate.getUTCFullYear(),...
[ "formatWikiData(response) {\n let len = response[1].length;\n let data = [];\n for (let m = 0; m < len; m++) {\n data.push({});\n }\n for(let index = 0; index < response.length; index++) {\n let section = response[index];\n switch (index) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create new item and add to existing order
function addNewItem(product) { var item = orderItemType.createInstance(); item.order = this; item.product = product; this.orderItems.push(item); return item; }
[ "function addItem(item) {\n item.order = this;\n var items = this.orderItems;\n if (items.indexOf(item) == -1) {\n items.push(item);\n }\n }", "addItemOnPress() {\n var receipt = this.state.receipt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
> Pipeline take a message from a channel as input parse it and save it in db send it to bot url save bot replies in dbs send bot replies back to channel
static async pipeMessage (channelId, message, opts) { const { chatId } = opts return MessagesController.findOrCreateConversation(channelId, chatId) .then(conversation => MessagesController.parseChannelMessage(conversation, message, opts)) .then(MessagesController.saveMessage) .then(WebhooksCo...
[ "async processSingleMessage(message) {\n\n }", "function message_compose (meta = {}, opts = {}, cb) {\n if(!meta.type) throw new Error('message must have type')\n\n if('function' === typeof cb) {\n if('function' === typeof opts) {\n opts = {prepublish: opts}\n }\n }\n opts.prepublish...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raw Tags are "foo" or "fooBar", which means one string which does not include a colon.
get rawTags() { return lazyInitTags( this, 'rawTags', /^[^:]+$/ ); }
[ "_formatTag() {\n this.originalTag = this.originalTag.replace('\\n', ' ')\n let hedTagString = this.canonicalTag.trim()\n if (hedTagString.startsWith('\"')) {\n hedTagString = hedTagString.slice(1)\n }\n if (hedTagString.endsWith('\"')) {\n hedTagString = hedTagString.slice(0, -1)\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The AWS::CodeDeploy::DeploymentGroup resource creates an AWS CodeDeploy deployment group that specifies which instances your application revisions are deployed to, along with other deployment options. For more information, see CreateDeploymentGroup in the AWS CodeDeploy API Reference. Documentation:
function DeploymentGroup(props) { return __assign({ Type: 'AWS::CodeDeploy::DeploymentGroup' }, props); }
[ "function Deployment(props) {\n return __assign({ Type: 'AWS::ApiGateway::Deployment' }, props);\n }", "function ResourceGroup(props) {\n return __assign({ Type: 'AWS::Inspector::ResourceGroup' }, props);\n }", "function createDeployment_() {\r\n progress = c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export macros selected by the checkboxes. For each macro it calls an AJAX request to GTM to get the data. During processing the response, it already formulates it in a way that will be easily imported. Currently supported macros: CUSTOM_VAR COOKIE AUTO_EVENT_VAR CONSTANT EVENT ARBITRARY_JAVASCRIPT DOM_ELEMENT REFERRER ...
function exportSelectedMacros() { var checkboxes = $('#ID-macroTable .cb_export:checked'); prepareExport('macros', checkboxes.length); checkboxes.each(function(index, element) { $.ajax({ type : 'POST', async : checkboxes.length < PARAL...
[ "function exportSelectedTags() {\r\n\r\n var checkboxes = $('#ID-tagTable .cb_export:checked');\r\n prepareExport('tags', checkboxes.length);\r\n\r\n checkboxes.each(function(index, element) {\r\n $.ajax({\r\n type : 'POST',\r\n async : checkboxes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an Scenario by the unique ID using model.findById()
show(req, res) { Scenario.findById(req.params.id) .then(function (scenario) { res.status(200).json(scenario); }) .catch(function (error) { res.status(500).json(error); }); }
[ "findById(id) {\n return request.get(`/api/flows/${id}`);\n }", "static async findById(id) {\n // Ensure model is registered before finding by ID\n assert.instanceOf(this.__db, DbApi, 'Model must be registered.');\n\n // Return model found by ID\n return await this.__db.findById(this, id);\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
run through all of the rockets and calculate fitness
evaluate(){ let fastest = lifespan; for(let i = 0; i < this.popsize; i++){ this.rockets[i].calcFitness(); if(this.rockets[i].framesToFinish < fastest){ fastest = this.rockets[i].framesToFinish } console.log(fastest) fastestRocke...
[ "evaluatePopulationFitness() {\n\t\tfor (let i = 0; i < this.chromosomes.length; i++) {\n\t\t\tthis.updateFitness(this.chromosomes[i]);\n\t\t}\n\t}", "normalizeFitness() {\n let sum = 0;\n this.chromosomes.forEach(chromosome => (sum += chromosome.fitness));\n this.chromosomes.forEach(chromosome => (chrom...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: _fnVisbleColumns Purpose: Get the number of visible columns Returns: int:i the number of visible columns Inputs: object:oS dataTables settings object
function _fnVisbleColumns( oS ) { var iVis = 0; for ( var i=0 ; i<oS.aoColumns.length ; i++ ) { if ( oS.aoColumns[i].bVisible === true ) { iVis++; } } return iVis; }
[ "function getNumCols () {\n if (typeof settings.cols === 'function') {\n return settings.cols($win.width());\n }\n else if (typeof settings.cols === 'number') {\n return settings.cols;\n }\n else {\n return base.length;\n }\n }", "function getTableColumns() { ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the day for the given date and appends it to the given week
function createDay(week, date) { //TODO: remove week from parameters var daySchedule = Parser.getSchedule(date); //TODO repeated code from Parser.getSchedule() var dateString = date.getMonth().valueOf()+1 + "/" + date.getDate().valueOf() + "/" + date.getFullYear().toString().substr(-2); var col = week.insertCel...
[ "function fillWeekDays(week) {\r\n\tangular.forEach(ref, function(refDay) {\r\n\t\taddIfNotExists(week, refDay);\r\n\t});\r\n}", "function handleWeekEvents(parameter){\n\n if(parameter.date == ''){\n let today = new Date();\n let next = new Date();\n\n next.setDate(next.getDate() + 7);\n\n let dd = t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether an update comprised of the given data and mergeStrategy would be a noop.
static isNoOpUpdate(data, mergeStrategy) { return ( Object.keys(data).length === 0 && mergeStrategy === SHALLOW_MERGE_STRATEGY ); }
[ "maybeMerge()\n {\n if ( this.options.merge ) {\n try {\n this[ isMerging ] = true;\n\n const data = JSON.parse(fs.readFileSync(this.getOutputPath()));\n\n for ( const key in data ) {\n if ( ! this.has(key) ) {\n this.set(key, data[ key ]);\n }\n }\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts price in string format back to numeric value eg. '$99.99 AUD' > 99.99
function convertPriceStringToNumber(price){ return Number(price.replace(/[^0-9\.]+/g,"")); }
[ "static amountPriceParser(amount) {\n //delete decimals\n let amountWithoutDecimals = parseInt(amount);\n let amountString = amountWithoutDecimals.toString();\n const regx = /(\\d+)(\\d{3})/;\n while (regx.test(amountString)) {\n amountString = amountString.replace(regx, `$1.$2`);\n }\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
drawCard function that takes 1 card from playerPile and 1 card from compPile and displays them. also compares and displays who won the hand
function drawCard() { render(); checkWin(); if(warActive === false) { currCard.player = pile.player[0]; currCard.comp = pile.comp[0]; // display computers card crdDisplay.comp.up.src = "./images/cards/" + currCard.comp + ".svg"; crdDisplay.comp.up.style.visibility = "...
[ "function drawCPUHand()\n {\n if (Game.counter < 11 || Game.counter == 421)\n {\n if (Game.CPUHand.cards[0] != null)\n {\n Game.CPUHand.cards[0].drawCard(50, CPU_HAND_Y);\n\n if (Game.CPUHand.cards[1] != null)\n {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find and render the filtered data results. Arguments are: filters our global variable the object with arrays about what we are searching for. products an object with the full products list (from product.json).
function renderFilterResults(filters, products) { // This array contains all the possible filter criteria. var criteria = ['maquillaje', 'CuidadoPiel', 'CuidadoCabello', 'CuidadoCuerpo'], results = [], isFiltered = false; // Uncheck all the checkboxes. // We will be checking them again one by one. ...
[ "function getProduct(identifier, filter) {\n var productsFiltered = [];\n $(\".productlist\").empty();\n\n//uit 'products' worden de key en de value gehaald (key = 1 record en value de waarden die erin zitten)\n//als de array met de meegegeven 'soort' gelijk is aan de filter 'soortnaam' wordt de decorateProdu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the altitude to target while intercepting a vertically aligned course
_calculateTargetedAltitudeToInterceptGlidepath() { // GENERALIZED CODE // const glideDatum = this.mcp.nav1Datum; // const distanceFromDatum_nm = this.positionModel.distanceToPosition(glideDatum); // const slope = Math.tan(degreesToRadians(3)); // const distanceFromDatum_ft = dist...
[ "_calculateTargetedAltitude() {\n if (this.mcp.autopilotMode !== MCP_MODE.AUTOPILOT.ON) {\n return;\n }\n\n if (this.flightPhase === FLIGHT_PHASE.LANDING) {\n return this._calculateTargetedAltitudeDuringLanding();\n }\n\n switch (this.mcp.altitudeMode) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates through the calldata blocks, starting from the root block, to construct calldata as a hex string. If the `optimize` flag is set then this calldata will be condensed, to save gas. If the `annotate` flag is set then this will return humanreadable calldata. If the `annotate` flag is not set then this will return ...
toString() { // Sanity check: root block must be set if (this._root === undefined) { throw new Error('expected root'); } // Optimize, if flag set if (this._rules.shouldOptimize) { this._optimize(); } // Set offsets const iterator = ...
[ "_toHumanReadableCallData() {\n // Sanity check: must have a root block.\n if (this._root === undefined) {\n throw new Error('expected root');\n }\n // Constants for constructing annotated string\n const offsetPadding = 10;\n const valuePadding = 74;\n con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if data.path exist
function isDataExist(path) { return getKeyData(defFields.data, path) !== undefined }
[ "fileExists() {\n return fs.pathExists(this.location);\n }", "function checkIfDataExistsLocalStorage(key) {\n let data = localStorage.getItem(key);\n if (data) {\n if (data !== null && data !== \"undefined\" && data !== \"\") {\n return true;\n }\n }\n else {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches multiple objects from GCS onebyone and calls the given callback with a map from the oject name to its fetched data.
function fetchGcsObjects(bucket, objectNames, responseHandler) { if (!objectNames.length) { responseHandler({}); return; } fetchGcsObject(bucket, objectNames[0], function(response) { fetchGcsObjects(bucket, objectNames.slice(1), function(responses) { responses[objectNames[0]] = response; r...
[ "getItemsInBucket(arg = {bucket: null, callback: (bucketItem)=>{}}){\n if(arg.bucket != null && arg.bucket.contents != null){\n let contents = arg.bucket.contents\n if(!Array.isArray(contents)){\n contents = [contents];\n }\n for(let i = 0; i < conte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that calculates the largest multiplication of 4 numbers from a given origin with the directions that are specified (up, down, diagonal, left, right)
function largestMult(x,y,grid,directions){ let largest = 0 directions.forEach((e)=>{ let localRes = mult(x,y,grid,e[0],e[1]) // console.log(localRes) if (localRes>largest){ largest = localRes } }) return largest }
[ "function mult(x,y,g, dirx, diry){\n let a = x\n let b = y\n let res = 1\n let index = 0\n\n while(index<4){\n res *= parseInt(g[a][b])\n a+=dirx\n b+=diry\n index+=1\n }\n return res\n}", "static Maximize(left, right) {\n const max = new Vector4(left.x, left.y, l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an array of unassigned tasks and assigns a designer to each task.
function randomAssigner(unassignedTasks) { let shuffledDesigners = shuffleArray(config.designers); let numDesigners = shuffledDesigners.length; // We will use an interval to control how quickly requests are sent // in order to avoid being rate limited. The interval uses the // const delay, which determines ho...
[ "function settasks() {\n\tvar nodeactivetasks = document.getElementById(\"main_middle_activetasks\");\n\tvar nodecompletedtasks = document.getElementById(\"main_middle_completedtasks\");\n\tremovechildren(nodeactivetasks);\n\tremovechildren(nodecompletedtasks);\n\n\tlistactivetasks.forEach(function(element) {\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Menu items start Get the message alert context menu item object
function getMsgAlertContextMenuObject() { return ({ '': { title: 'reload this application', icon: './images/icon/refresh_16x16.png', onclick: function() { location.reload(); } ...
[ "function AddCustomMenuItems(menu) {\r\n menu.AddItem(strHelp, 0, OnMenuClicked);\r\n}", "function setupContextMenu(){\n chrome.contextMenus.create({\n \"title\": \"Add to Quotsy\",\n \"contexts\": [\"selection\"],\n \"onclick\": QuoteManager.addQuote\n })\n}", "function getContextMe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Default no filter / p5.js library automatically executes the `preload()` function. Basically, it is used to load external files. In our case, we'll use it to load the images for our filters and assign them to separate variables for later use.
function preload() { // Spiderman Mask Filter asset imgSpidermanMask = loadImage("https://i.ibb.co/9HB2sSv/spiderman-mask-1.png"); // Dog Face Filter assets imgDogEarRight = loadImage("https://i.ibb.co/bFJf33z/dog-ear-right.png"); imgDogEarLeft = loadImage("https://i.ibb.co/dggwZ1q/dog-ear-left.png");...
[ "function preload() {\n\tkernelImg = loadImage(\"assets/kernel.png\");\n\tpopcornImg = loadImage(\"assets/popcorn.png\");\n\tburntImg = loadImage(\"assets/burnt.png\");\n}", "function preload()\n{\n\tpaperImage = loadImage(\"paperImage.png\")\n\tdustbinImage = loadImage(\"dustbinWHJ.png\")\n\n}", "function prel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the collision manifold between a polygon and a circle.
function b2CollidePolygonAndCircle(manifold, polygonA, xfA, circleB, xfB) { manifold.pointCount = 0; // Compute circle position in the frame of the polygon. var c = b2Mul_t_v2(xfB, circleB.m_p); var cLocal = b2MulT_t_v2(xfA, c); // Find the min separating edge. var normalIndex = 0; var sepa...
[ "function calculateCircle(points) {\n var solVector, a, b, c, circleProp = {};\n \n if (points.length !== 3) {\n return null;\n }\n \n /* Consider the general conic equation:\n *\n * Ax**2 + Bxy + Cy**2 + Dx + Ey + F = 0\n *\n * Fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normally we don't log exceptions but instead let them bubble out the top level where the embedding environment (e.g. the browser) can handle them. However under v8 and node we sometimes exit the process direcly in which case its up to use us to log the exception before exiting. If we fix this may no longer be needed un...
function logExceptionOnExit(e) { if (e instanceof ExitStatus) return; let toLog = e; if (e && typeof e == 'object' && e.stack) { toLog = [e, e.stack]; } err('exiting due to exception: ' + toLog); }
[ "function exceptionHandler (err) {\n console.log (err.stack);\n var stack = stackWalk ();\n if (stack.length) {\n console.log (\"Tame 'stack' trace:\");\n console.log (stack.join (\"\\n\"));\n }\n}", "function dist_logException(state, exception, context) {\n let handler = state.face...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets all next elements matching the passed selector.
function nextAll(item,selector){return untilAll(item,selector,'nextElementSibling');}
[ "function query(selector) {\n return Array.prototype.slice.call(document.querySelectorAll(selector));\n }", "function children(selector) {\n var nodes = [];\n each(this, function(element) {\n each(element.children, function(child) {\n if (!selector || (selector && matches(child, select...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method: buildColormap 1. initializes network 2. trains it 3. removes misconceptions 4. builds colorindex
function buildColormap() { init(); learn(); unbiasnet(); inxbuild(); }
[ "function getColormap() {\n var map = [];\n var index = [];\n\n for (var i = 0; i < netsize; i++) {\n index[network[i][3]] = i;\n }var k = 0;\n for (var l = 0; l < netsize; l++) {\n var j = index[l];\n map[k++] = network[j][0];\n map[k++] = network[j][1];\n map[k++] = network...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get online HAC list
function getOnlineHacs(){ var sql = "SELECT * FROM info_hac where state = 1"; var hacs = []; executeSql(sql, null, function(rows){ if(rows) hacs.push(rows); }, function(err){ console.log("Error: failed when get online HAC list, " + err); } ); return hacs; }
[ "function getOfflineHacs(){\n\tvar sql = \"SELECT * FROM info_hac where state <> 1\";\n\tvar hacs = [];\n\texecuteSql(sql, null, \n\t\tfunction(rows){\n\t\t\tif(rows) hacs.push(rows);\n\t\t}, \n\t\tfunction(err){\n\t\t\tconsole.log(\"Error: failed when get offline HAC list, \" + err);\n\t\t}\n\t);\n\treturn hacs;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a should be in merged with comma ','. field name is merged with comma divis should be the id of that div where the error message is displayed
function validate_form_div(a,divid) { var z=a.split(','); num_data = z.length; var msg = 'Error! The following fields are empty<br>'; var err=0; //alert(a); for(var i=0; i<num_data; i++) { //alert(z[i]); if(document.getElementById(z[i]).value=='') { msg=msg+z[i]+'<br>'; err++; ...
[ "function createErrorDiv(nombre,div_error,msg)\n{\n\tnew Insertion.Before(nombre,div_error);\n\tif(msg == \"\")\n\t\t$(\"msg_\"+nombre).update(\"&darr;&nbsp;Campo Obligatorio&nbsp;&darr;\");\n\telse\n\t\t$(\"msg_\"+nombre).update(\"&darr;&nbsp;\"+ msg +\"&nbsp;&darr;\");\n\n\n\t$(nombre).focus();\n\treturn false;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle a 'comm_msg' kernel message.
_handleCommMsg(msg) { return __awaiter(this, void 0, void 0, function* () { this._assertCurrentMessage(msg); let content = msg.content; let comm = this._comms.get(content.comm_id); if (!comm) { return; } let onMsg = comm.onM...
[ "function _onMessage(chan, msg) {\n if (chan != _chan) {\n return;\n }\n\n if (msg._redis_source == _client_id) {\n return;\n }\n\n var res = {end:function(){}, error:function(){}};\n var req = msg;\n\n io.handle (req, res, function(err, result)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trigger the "dom:refresh" event and corresponding "onDomRefresh" method
function triggerDOMRefresh() { if (view._isShown && view._isRendered && Marionette.isNodeAttached(view.el)) { if (_.isFunction(view.triggerMethod)) { view.triggerMethod('dom:refresh'); } } }
[ "function clickedRefresh(event) {\n console.log(\"refresh\")\n window.location.reload();\n}", "function refresh_content() {\n $('.refresh').on('click', function() {\n show_content();\n });\n }", "function scheduleRefresh() {\r\n if (refreshEvent) {\r\n clearTimeout(refreshEve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing WebAppDiagnosticLogsConfiguration resource's state with the given name, ID, and optional extra properties used to qualify the lookup.
static get(name, id, opts) { return new WebAppDiagnosticLogsConfiguration(name, undefined, Object.assign(Object.assign({}, opts), { id: id })); }
[ "static get(name, id, opts) {\n return new DisasterRecoveryConfig(name, undefined, Object.assign(Object.assign({}, opts), { id: id }));\n }", "constructor(name, args, opts) {\n let inputs = {};\n opts = opts || {};\n if (!opts.id) {\n if ((!args || args.name === undefined...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
resize the cache when the lengthCalculator changes.
set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.len...
[ "function recache() {\n // cache the viewport dimensions\n cache.viewport = {\n width: window.innerWidth,\n height: window.innerHeight };\n\n\n cache.document = {\n height: main.scrollHeight,\n width: main.scrollWidth };\n\n\n cache.node = tapeBody.getBoundingClientRect();\n\n scrollCheck();\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reducer creator: bind a handler with an action type and an optional initialState
function bindAction (type, handler, initialState) { return typeof initialState === 'undefined' ? handler ? function (state, action) { if (typeof state === 'undefined') { state = null } return action && action.type === type ? handler(state, action) : state } : function (state) { // an...
[ "function bindActions (types, handler, initialState) {\n if (!types || !types.length || !handler) { // supplement an empty handler.\n handler = nopReducer(initialState)\n }\n var actions = {}\n for (var i = 0; i < types.length; i++) {\n actions[types[i]] = handler\n }\n return combineActions(actions, in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a KalturaScheduleResource object by ID.
static get(scheduleResourceId){ let kparams = {}; kparams.scheduleResourceId = scheduleResourceId; return new kaltura.RequestBuilder('schedule_scheduleresource', 'get', kparams); }
[ "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('scheduledtask_scheduledtaskprofile', 'get', kparams);\n\t}", "function startResourceGet(id) {\n return { type: START_RESOURCE_GET,\n id: id};\n}", "getById(id) {\n return spPost(TimeZones(this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate a check box input
function validateCheckBox(obj, req) { if(req) { if(!obj.checked) return 'Please tick ' + ucwords(obj.name); else return null; } else { return null; } }
[ "function checkBoxValidation(){\n\t\tvar noDietry = document.getElementById(\"NO\");\n\t\tvar glutenFree = document.getElementById(\"GF\");\n\t\tvar soyFree = document.getElementById(\"Soy\");\n\t\tvar dairyFree = document.getElementById(\"Dairy\");\n\t\n\t\t\n\t\tif (soyFree.checked || glutenFree.checked || dairyF...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
multiplies the number at the end of string one to the power of the number at the start of string two and merges the result returning a new expression string
function exp(str1, str2) { var end = endNumber(str1); var start = startNumber(str2); var exp = Math.pow(end.value, start.value); if (isNaN(exp)) { throw new Error("malformed expression"); } return end.remainder + exp.toString() + start.remainder; }
[ "function multiply(str1, str2) {\n var end = endNumber(str1);\n var start = startNumber(str2);\n //if missing a value evaluation is impossible\n if(start.value === undefined || end.value === undefined) {\n throw new Error(\"malformed expression\");\n }\n\n var product = end.value * start.valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Capture all event types in array and define color domain as well as event type order.
function handleEventTypes() { var _this = this; this.allEventTypes = d3 .set( this.initial_data.map(function(d) { return d[_this.config.event_col]; }) ) .values() .sort(); this.currentEventTypes ...
[ "handlers(event_type, arr_funs) {\n // find the event type (the string)\n let type = ''\n if (typeof event_type === \"string\") {\n type = event_type\n } else if (typeof event_type === \"object\" && event_type.event) {\n type = event_type.event\n }\n\n if (warn(!type, \"C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates grid of coordinates based on input pattern
function populateGrid(coords) { let patternedGrid = makeGrid(width, height); coords.forEach((coord) => { let [x, y] = coord; patternedGrid[x][y] = true; }); setGrid(patternedGrid); }
[ "function createChessGrid() {\n var color = \"w\";\n for (var j = 0; j < 8; j++) {\n let line = [];\n for (var i = 0; i < 8; i++) {\n var tile = createTile(j * WIDTH + 20, i * HEIGHT + 20, color);\n tile.placedPiece = \"\";\n line.push(tile);\n if (color == \"w\")\n color = \"b\";...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts the metadata necessary to construct an `ngBaseDef` from a class.
function extractBaseDefMetadata(type) { var propMetadata = getReflect().ownPropMetadata(type); var viewQueries = extractQueriesMetadata(type, propMetadata, isViewQuery); var queries = extractQueriesMetadata(type, propMetadata, isContentQuery); var inputs; var outputs; // We only need to know whe...
[ "function _createMetadata(prototype) {\n let basePrototype = Object.getPrototypeOf(prototype);\n\n let metadata = Object.create(Metadata).init();\n // manually copy properties from the prototypes metadata\n if (basePrototype._espDecoratorMetadata) {\n for (let e of basePrototype._espDecoratorMeta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show notification that to set/remove password user must be moderator.
notifyModeratorRequired () { if (dialog) return; let closeCallback = function () { dialog = null; }; if (password) { dialog = APP.UI.messageHandler .openMessageDialog(null, "dialog.passwordError", ...
[ "function notifyPasswordNotSupported () {\n console.warn('room passwords not supported');\n APP.UI.messageHandler.showError(\n \"dialog.warning\", \"dialog.passwordNotSupported\");\n}", "function showPass() {\n const password = document.getElementById('password');\n const rePassword = document.getE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Task 2 Find a maximum value of all the elements in the array
function findMaximumValue(array) { }
[ "function findMaxProduct(array) {\n\n}", "function max_subarray(A){\n let max_ending_here = A[0]\n let max_so_far = A[0]\n\n for (let i = 1; i < A.length; i++){\n max_ending_here = Math.max(A[i], max_ending_here + A[i])\n // console.log(max_ending_here)\n max_so_far = Math.max(max_so...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
apply tagOpen/tagClose to selection in textarea, use sampleText instead of selection if there is none
function insertTagsInner(id, txtarea, tagOpen, tagClose, sampleText) { var selText, isSample = false; tagOpen = tagOpen.replace(/&quote;/gi, '\"'); tagClose = tagClose.replace(/&quote;/gi, '\"'); tagOpen = tagOpen.replace(/_newline_/gi, '\n'); tagOpen = tagOpen.replace(/newline/gi, '\n'); tagCl...
[ "function wrapText(textArea, openTag, closeTag){\n\t\tvar len \t= textArea.val().length;\n\t\tvar start\t= textArea[0].selectionStart;\n\t\tvar end \t= textArea[0].selectionEnd;\n\t\tvar selectedText \t= textArea.val().substring(start, end);\n\t\tvar replacement \t= openTag + selectedText + closeTag;\n\t\ttextArea....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to add a button to toggle viewing of a loan's graphs Arguments: loan [Loan]: Loan object representing the desired loan
function addLoanMenuButton(loan) { const loanNavButton = ` <button class="btn btn-primary loan-button" onclick="displayGraph('${ loan.name }')">${loan.name.replace("_", " ")}</button> `; const $loanNavMenu = $("#loanNavMenu"); $loanNavMenu.append(loanNavButton); }
[ "function displayGraph(loanName) {\n let visuals = $(\".uiVisualizer\");\n visuals.each(function(index) {\n visuals[index].style.display = \"none\";\n });\n\n let prefix = null;\n switch (LoanM8.activeComponent) {\n case \"loanPaymentsGraphs\":\n prefix = \"payments-graph-\";\n break;\n case...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ReadStream add PassThrough, when ReadStream emit error, proxy error to PassThrough
function readStreamAddPassThrough(readStream) { const passThrough = new PassThrough(); readStream.on('error', err => passThrough.emit('error', err)); return readStream.pipe(passThrough); }
[ "function wrap(stream) {\n stream.on('error', error => {\n gutil.log(gutil.colors.red(error.message));\n gutil.log(error.stack);\n if (watching) {\n gutil.log(gutil.colors.yellow('[aborting]'));\n stream.end();\n } else {\n gutil.log(gutil.colors.yellow('[exiting]'));\n process.exit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Safely assert whether the given value is a Blob. In some execution environments Blob is not defined.
function isBlob(value) { return typeof Blob !== 'undefined' && value instanceof Blob; }
[ "function isXHR2WithBlobSupported() {\n if (!window.hasOwnProperty('ProgressEvent') || !window.hasOwnProperty('FormData')) {\n return false;\n }\n let xhr = new XMLHttpRequest();\n if (typeof xhr.responseType === 'string') {\n try {\n xhr.responseType = 'blob';\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API call to the rental data and then creating a bar graph
function rentalAPI(areaCategory , input){ // API Key was free and the same for all users var redline = d3.select("#Redline").html("").append("h4").attr("class","well").text('The red line represents the median household income divided by 12(for months) and then divided by 3, because a good rule of thumb is to n...
[ "function apiCall(input) {\n\n // WHY IS THIS HERE???\n d3.json(`/sqlsearch/${input}`).then(function(data){\n var info = data\n });\n\n // API Key was free and the same for all users \n var url = `https://www.quandl.com/api/v3/datasets/ZILLOW/${areaCategory}${input}_${indicatorCodePrice}?start...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the cleanup function itself in LView.cleanupInstances. This is necessary for functions that are wrapped with their contexts, like in renderer2 listeners. On the first template pass, the index of the cleanup function is saved in TView.
function storeCleanupFn(view, cleanupFn) { getCleanup(view).push(cleanupFn); if (view[TVIEW].firstTemplatePass) { getTViewCleanup(view).push(view[CLEANUP].length - 1, null); } }
[ "function cleanup() {\n if (global.gc) {\n global.gc();\n }\n}", "destroy() {\n delete this.el[`pattern-${this.name}`];\n }", "destroy() {\n\t\tthis.directives.forEach(\n\t\t\tbinding => Reflex.unobserve(this, null, null, {tags:['#directive', binding]})\n\t\t);\n\t\tif (this.dataBlockScript && gl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Appends logical next/prev month text to the buttons ex: Next Month, January 2015 Previous Month, November 2014
function appendOffscreenMonthText(button) { var buttonText; var isNext = $(button).hasClass('ui-datepicker-next'); var months = [ 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', ...
[ "function btnNextMonthClick() {\n\t\terase();\n\t\tmonthCheck = monthCheck + 1;\n\t\tif (monthCheck > 11) {\n\t\t\tmonthCheck = 0;\n\t\t\tyearCheck = yearCheck + 1;\n\t\t}\n\t\tconsole.log(monthCheck);\n\t\tsetData();\n\t\tsetMonths();\n\t\tsetYears();\n\t}", "function btnNextYearClick() {\n\t\terase();\n\t\tyear...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method that locks cards to the matched state
function lockCards(card1, card2){ card1.addClass("match"); card2.addClass("match"); //reset the opened cards list openedCards = []; }
[ "function checkMatch( )\n{\n let cardOneType = openCards[openCardCount].children[0].classList[1]; // class for first card to match\n let cardTwoType = openCards[openCardCount + 1].children[0].classList[1]; // class for second card to match\n\n //==If the two cards are the same, lock cards in open position=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Marks current view and all ancestors dirty
function markViewDirty(view) { var currentView = view; while (currentView.parent != null) { currentView.flags |= 4 /* Dirty */; currentView = currentView.parent; } currentView.flags |= 4 /* Dirty */; ngDevMode && assertNotNull(currentView.context, 'rootContext'); scheduleTick(cur...
[ "dirty() {\n this.signal();\n }", "_checkIfDirty(){\n if (this._isDirty === true){\n this._isDirty = false;\n this._refresh();\n }\n }", "setTransformDirty () {\n this._transformDirty = true;\n }", "function markUnmodified(root_node) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the command_array_creator function takes an array of strings and returns an array of commands
function command_array_creator(arr){ let new_arr = []; arr.forEach(str => { new_arr.push(command_extractor(str)); }) return new_arr; //if ['turn off 812,389 through 865,874', 'toggle 205,417 through 703,826'] was given as input //the function would return [ [ 'turnoff', [ 812, 389 ], [ 865, 874 ] ], [ '...
[ "function command_executor(arr, light_constructor){\n command_array = command_array_creator(arr);\n light_array = light_array_creator(light_constructor);\n command_array.forEach( command => {\n cmd = command[0],\n [x1, y1] = command[1],\n [x2, y2] = command[2];\n\n for( i = x1; i <= x2; i++){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CORE FUNCTIONS // increment holdReleaseCurrent until it hits the target, then allow document ready
function holdRelease() { holdReleaseCurrent++; if (holdReleaseCurrent >= holdReleaseTarget) { $.holdReady( false ); } }
[ "function finishToggleMode()\n{\n if (stylesToLoad != 0 && Date.now() < limit) {\n\n setTimeout(finishToggleMode, 100);\t// Wait some more\n\n } else if (stylesToLoad == 0 && Date.now() < limit) {\n\n limit = 0;\n setTimeout(finishToggleMode, 100);\t// Wait 100ms for styles to apply\n\n } else {\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filter the arrivals array by the selected values for line, station, and direction
function filterArrivals(arvlArray, filterLine, filterStn, filterDir) { if (filterLine !== "ALL") {arvlArray = arvlArray.filter(arr => arr.LINE === filterLine)}; if (filterStn !== "ALL") {arvlArray = arvlArray.filter(arr => arr.STATION === filterStn)}; if (filterDir !== "ALL") {arvlArray = arvlArray.filter(arr => ...
[ "function filterReceivers(selected) {\n // clear the desiredRec array and the div that holds the receiver arc chart\n desiredRec = [];\n $('#receiver-arcs').html('');\n\n // iterate over the original data, creating a new season object and pushing\n // it to the desiredRec array\n for (let i = 0; i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update playercount from database
updateCount(count){ //playerCount refers to the database counts whereas count refers to make a change to the original playerCount database.ref("/").update({playerCount:count}); }
[ "function updateNumberOfPlayers(){\n\n // this is the real number of players\n numberOfPlayers = inPlayerId - 1;\n}", "function updateUserCount(count) {\n database.ref('players/count').set(count);\n}", "updateCoinCount(){\n\t\t$(`#coinCount${this.playerId}`).text(`${this.coinCount}`);\n\t}", "getCoun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new prompt that asks the user to upload one or more attachments.
function createAttachmentPrompt(validator) { return { prompt: function prompt(context, prompt, speak) { const msg = typeof prompt === 'string' ? { type: 'message', text: prompt } : Object.assign({}, prompt); if (speak) { msg.speak = speak; } if...
[ "function NewFilePrompt() {\n $(\"div#overlay-header\").html(\"New File\");\n $(\"div#overlay-body\").html($(\"div#overlay-templates div.overlay-new-file\").html());\n $(\"div#force-overlay\").css(\"display\", \"block\");\n}", "function showInsertLinkDialog(list) {\n var itemList = [];\n ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log(isPositive(1)) console.log(isPositive(2)) console.log(isPositive(3)) 3. create a function that determine's t/f where the number is a multiple of 5
function multipleOfFive(num){ return num%5 === 0 }
[ "function under50(num) {\n return num < 50;\n}", "function isPositive(input) {\n return input > 0;\n}", "function hasDivisableBy5(array) {\n\tvar bool = false;\n\tarray.forEach(function(number) {\n\t\tif(number % 5 === 0) {\n\t\t\tbool = true;\n\t\t} \n\t});\n\treturn bool;\n}", "function divisible7and5(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The nested component just passes any messages sent to it via props and passes on down to multiple nested child components so we have no component state to track
render() { return ( <div className={'nested-component'}> <p className={'comp-name'}>{this.props.component_name}</p> <p>{this.props.msg}</p> {/*Now render some nested child components and let props pass on down any messages received by parent*/} ...
[ "outChildComponents() {\n if(Array.isArray(this.props.loopedComponents)) {\n this.props.loopedComponents.forEach((component) => {\n if(Array.isArray(component.renderedComponents)) {\n Array.from(component.renderedComponents).forEach(comp => {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reposition the UI elements on a UI change, scroll, resize, etc.
function positionUIElementsOnChange() { setCurrentViewPortScroll(); setCurrentViewPortSize(); _positionUIElementsOnChangeCB.call(this, _currentViewPortSize, _currentViewPortScroll); }
[ "function resetUiBounds()\n {\n // if ui is off the page, relocate it\n var lastPosition = getLastPosition();\n var lastSize = getLastSize();\n var windowWidth = $window.width();\n var windowHeight = $window.height();\n\n // resize alme window...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public function `emptyObject`. Returns true if `data` is an empty object, false otherwise.
function emptyObject (data) { return object(data) && Object.keys(data).length === 0; }
[ "function isEmpty(obj) {\n\treturn Object.entries(obj).length === 0 && obj.constructor === Object\n}", "function isEmptyCollection(obj){\n\treturn isCollection(obj) && (\t\t\t\t\t//if it is a non-nullable object AND\n\t\t(Array.isArray(obj) && obj.length == 0) ||\t//it is an empty array, OR\n\t\tjQuery.isEmptyObj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserkey_compression.
visitKey_compression(ctx) { return this.visitChildren(ctx); }
[ "visitPrimary_key_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitLob_compression_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitNon_reserved_keywords_pre12c(ctx) {\n\t return this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function topScore will compare the values of the elements with the ID of "score" and "topscore". If score is bigger than topscore it will change the value of topscore and match it with the score value.
function topScore() { var oldScore = parseInt(document.getElementById("score").innerText); var topScore = parseInt(document.getElementById("top-score").innerText); if (topScore < oldScore) { topScore = oldScore; } document.getElementById("top-score").innerHTML = topScore; }
[ "function scoreSort(a, b){\n return b.score-a.score;\n}", "isHighScore(score){\n\t\t// Check if we have enough high scores\n\t\tif(this.scores.length < this.max_scores){\n\t\t\treturn true;\n\t\t}\n\t\t// Compare score to existing high scores\n\t\tfor(var i = 0; i < this.scores.length; i++ ){\n\t\t\tif(this.sc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks any three cells to see if they match the given marker
function CheckThree(marker, c1, c2, c3, state){ var b; if(state) b = state; else b = this.board; return (b[c1] == marker && b[c2] == marker && b[c3] == marker); }
[ "function match3Column() {\n console.log('Checking column matches')\n for (let i = 0; i < width ** 2; i++) {\n if (i >= width ** 2 - width * 2) {\n // console.log(`ignoring i ${i}`)\n } else {\n const first = cells[i].classList[0]\n const second = cells[i + width].classList[0]\n const th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve Multiple Record using Xrm.WebApi
function RetrieveMultipleRecords() { try { var entityName = "new_organization"; //Entity Logical Name var query = "?$select=new_organizationname, new_noofemployees, new_revenue&$top=3"; //Columns to Retrieve Xrm.WebApi.retrieveMultipleRecords(entityName, query).then( function suc...
[ "function RetrieveRecord() {\n try {\n var entityName = \"new_organization\"; //Entity Logical Name\n var recordId = \"919F28C4-F9BB-E911-A977-000D3AF04F8C\"; //Guid of the Record\n var columnsToRetrieve = \"$select=new_organizationname, new_noofemployees, new_revenue\"; //Columns to Retriev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dashrath code end /Added by Dashrath setPostTabBarWidth function start
function setPostTabBarWidth() { // var isLeftMenu1 = getCookie('is_left_menu'); // if(isLeftMenu1=='1') // { // var subWidth = '-=375px'; // } // else // { // var subWidth = '-=597px'; // } // $('.postTabUIFixed').css('width', screen.width).css('width', subWidth); if($('#lef...
[ "function removePostTabBarWidth()\r\n{\r\n $('.postTabUIFixed').css('width', '');\r\n}", "resizeTabContents() {\n let change = $(`#pcm-tabbedPandas`).height() - this.tabNavHeight;\n if (change !== 0 && this.tabContentsHeight > 0) { $('#pcm-pandaTabContents .pcm-tabs').height(`${this.tabContentsHeight - cha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send a image from canvas.
function sendImage(e) { var uri = '', data = {}; if (!isAndroid && cv.toDataURL) { uri = cv.toDataURL(); } else { uri = (Canvas2Image.saveAsBMP(cv, true, cWidth, cHeight)).src; } data.imageData = uri; $.a...
[ "handleSave() {\n const can = document.getElementById('paint');\n const img = new Image();\n\n /**\n * If the state of the default canvas is the same that\n * the canvas after click on save we show an error instead\n * send the image in png to the father component\n */\n if (can.toDataUR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Posts entries to new section on the page
function postEntries(entries){ var display = document.getElementById("display"); var newSection = document.createElement("section"); var header = document.createElement("h2"); var deleteButton = document.createElement("button"); deleteButton.innerHTML = "X"; deleteButton.setAttribute("class", "close"); newSectio...
[ "function createNewPostPage(e){\n\t\te.preventDefault();\n\t\t// If the user clicked the button with id newPost, then display the posting page on the right part of the screen.\n\t\tif (e.target.id == 'newPost'){\n\t\t\tmainContent.innerHTML = `\n\t\t\t\t<form>\n\t\t\t\t\t<p class=\"newPostPageText\">Title: </p> <te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all sections within the Layout.
deleteAllSections() { while (this.sections.length) { let section = this.sections[this.sections.length - 1] this.deleteSection(section) } }
[ "resetSections() {\n $sectionWithBackLink?.detach();\n this.$currentSection.empty();\n currentSection = null;\n }", "function hideEmptySections() {\n\t$('.w-dyn-empty').parents('.section').each(function(){\n\t $(this).hide();\n\t console.log(\"Empty collections have been hidden.\");\n\t});\n}", "funct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates all of our meshes
initializeMeshes () { this.triangleMesh = new Mesh(this.cyanYellowHypnoMaterial, this.triangleGeometry); this.quadMesh = new Mesh(this.magentaMaterial, this.quadGeometry); // texture code this.texturedQuadMesh = new Mesh(this.texturedMaterial, this.texturedQuadGeometry); }
[ "generate() {\n\n\t\t\tlet level, scale, geometry, material;\n\n\t\t\t// Clean up.\n\t\t\tif(this.previousResolution !== this.resolution) {\n\n\t\t\t\t// Make new geoemtries and delete the old ones.\n\t\t\t\tif(this.centerGeometry !== null) { this.centerGeometry.dispose(); }\n\t\t\t\tif(this.surroundingGeometry !==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Orders an array using specific `ordering` function and returns index of the `value`.
function getSortedIndex(array, ordering, value) { var start = 0; var end = array.length; var found = false; while (start < end) { // TODO is this faster/slower than using Math.floor ? var pivot = (start + end) >> 1; var order = ordering(value, array[pivot]); // less ...
[ "function getIndex(array, index, key, order) {\n var value = array[index][key],\n tempIndex = index;\n for (var i = index + 1; i < array.length; i++) {\n if (order === \"asc\" && array[i][key] < value || order === \"desc\" && array[i][key] > value) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write JS to yield the current thread if warp mode is disabled.
yieldNotWarp() { if (!this.isWarp) { this.source += 'yield;\n'; this.yielded(); } }
[ "run() {\n if (!this.Wasm) {\n errorMessage(`${this.libraryName} is still loading. Try again in a few seconds.`);\n return;\n }\n this.hasRun = true;\n this._render();\n const canvas = this._resetCanvas();\n\n try {\n let f = new Function(this.libraryName, 'canvas', // actual params...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update a specific hour's local storage data
function update(hour, data) { planData["hour" + hour] = data; localStorage.setItem("planData", JSON.stringify(planData)); }
[ "function SaveHourInfo(hour, data){\n localStorage.setItem(hour, data);\n}", "function setSchedule(hour){\n localStorage.setItem(hour, $(\"#hour\"+hour).val());\n}", "function updateHour() {\n\t\t\tdocument.documentElement.setAttribute(\"stylish-hour\", (new Date()).getHours())\n\t\t}", "onIncreaseHour(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds button for creating new player
function createNewPlayer(){ let newPlayerButton = document.querySelector('#playername-submit'); newPlayerButton.addEventListener("click", getNewPlayer); }
[ "function onPlayerAddOrRemove() {\n showHideVisibleColorOptions();\n enableOrDisablePlayerAddButton();\n enableOrDisableStartGameButton();\n}", "function createButton(){\n javamonDiv = document.getElementById('javamon-div');\n javamon.forEach(function(e, i){\n newButton = document.createElem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserpartition_by_clause.
visitPartition_by_clause(ctx) { return this.visitChildren(ctx); }
[ "visitQuery_partition_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitTable_partitioning_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitIndex_partitioning_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSubpartition_by_list(ctx) {\n\t return this.visitChildre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define a search tracker class
function SearchTrackerClass() { // keep a track of search terms for ease of comparison this.history_log = []; // keep a track of the search result counts this.contributor_count = 0; this.event_count = 0; }
[ "function RouteSearchResultCollector() {\n\n}", "function perform_search() {\n if (lastSearchType == \"D\") {\n searchHistory();\n } else if (lastSearchType == \"E\") {\n searchEpg();\n }\n }", "function handle_bp_biller_corp_search(req, startTime, apiName) {\n this.req = req; this.sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a fresh property descriptor that is guaranteed to be complete (i.e. contain all the standard attributes). Additionally, any nonstandard enumerable properties of attributes are copied over to the fresh descriptor. If attributes is undefined, returns undefined. See also:
function normalizeAndCompletePropertyDescriptor(attributes) { if (attributes === undefined) { return undefined; } var desc = toCompletePropertyDescriptor(attributes); // Note: no need to call FromPropertyDescriptor(desc), as we represent // "internal" property descriptors as proper Objects from the start for ...
[ "static get observedAttributes() {\n // note: piggy backing on this to ensure we're finalized.\n this.finalize();\n const attributes = [];\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n this._classProperties...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ ajax_update_user() / query for the user details so that / the user can change attributes
function ajax_update_user(){ var user_list = document.getElementById('user_list'); var uname = user_list.options[user_list.selectedIndex].innerHTML; var uid = user_list.options[user_list.selectedIndex].id; // cleanup fields before repopulating // with new data cleanup(); document.getElementById('button1').value ...
[ "function updateUser(user_id) {\n user = {\n Id: user_id,\n First_name: prevName.innerHTML,\n Last_name: prevLast.innerHTML,\n Password: prevPassword.innerHTML,\n IsAdmin: previsAdminCB.checked\n }\n ajaxCall(\"PUT\", \"../api/Users\", JSON.stringify(user), updateUser_suc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a player to a lobby (member function) May throw errors
function addPlayer(username) { // Check that this player isn't in a lobby already if (lobbies.some(lobby => lobby.players.some(player => player.username == username ) )) { throw 'This player is already in a lobby.'; } // Create the new player ...
[ "setPlayerLobby(player) {\n var game = this;\n //If lobby count is 0, creates a lobby and puts the player in it\n if (game._lobbies.length == 0) {\n var lobby = game.createLobby();\n\n lobby.addPlayer(player);\n } else {\n var playerJoinedFreeLobby = fals...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes Ono from the stack, so that the stack starts at the original error location
function popStack(stack) { if (stack) { let lines = stack.split(newline); // Find the Ono call(s) in the stack, and remove them let onoStart; for (let i = 0; i < lines.length; i++) { let line = lines[i]; if (onoCall.test(line)) { if (onoStart =...
[ "restore_stack(stuff){\n const v = stuff.stack;\n const s = v.length;\n for(var i=0; i<s; i++){\n this.stack[i] = v[i];\n }\n this.last_refer = stuff.last_refer;\n this.call_stack = [...stuff.call_stack];\n this.tco_counter = [...stuff.tco_counter];\n return s;\n }", "function cleanS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that will heal the pilot
function heal() { if (pilot.total_health_packs == 0) { //The pilot can't do anything if they don't have health packs console.log("Can't heal,; no more health packs!"); } else { if (pilot.health == 100) { //Can't have more than 100 health console.log("Can't use health pack; Pilot has max health!"); } els...
[ "function UsePotion() {\n if (currentTime<parent.next_pot) return false;\n\n // default health potions heal 200\n if (character.hp < 100) {\n parent.use('hp');\n Sleep(UsePotion, 500);\n } else if (character.mp < 100) {\n parent.use('mp');\n Sleep(UsePotion, 500);\n } else if (character.max_hp - ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends request to check authentication.
_checkAuthenticationStatus() { // First, check if we have the appropriate authentication data. If we do, check it. // If we don't, trigger an event to inform of login require. if (this._token.value === '') { Radio.channel('rodan').trigger(RODAN_EVENTS.EVENT__AUTHENTICATIO...
[ "authenticate() {\n this.set('hasResponseMessage', null);\n const {\n formatUsername,\n password,\n api,\n selectedEnvironemnt\n } = this.getProperties('formatUsername', 'password', 'api', 'selectedEnvironemnt');\n return this.get('session').authenticate('authenticato...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to set the proxy, call with a proxy argument (once) to get the previously set proxy, call without an argument
proxy(aProxy = undefined) { if (!this._proxy) { assert(!this._runPromise); // do not create agents after run() assert(arguments.length === 1); // do not ask before setting assert(aProxy); this._proxy = aProxy; } else { assert(arguments.length =...
[ "function setProxyUrl(url) {\n proxyUrl = url;\n }", "async function recreateProxy (serviceName, listenPort, proxyToPort) {\n try {\n await rp.delete({\n url: `${toxicli.host}/proxies/${serviceName}`\n })\n } catch (err) {}\n\n const proxy = await toxicli.createProxy({\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_____________________________________________________________________// This function computes the partitioning of FSS composing the linguistic variable _____________________________________________________________________
function partitioningComputing() { var i, j, h, x, dx, a, b, c, d; var msg = new Array(); //post("LV_partitioning\n"); //MODIFICATION 31-07-08// if (fuzzySubsetNumber > 0) { dx = dataMax-dataMin; //post("partitionMethod = ", this.myPartitioningMethod, "\n"); switch(myPartitioningMethod) { case CLASSICA...
[ "function partitioningMethod(x)\n{\n\tvar err;\n\t//post(\"Partitioning\", x, \"\\n\");\n\terr = parsePartitioningMethod(x);\n\tif (myPartitioningMethod == CLASSICALPARTITIONING)\n\t{\n\t\tinduceBoundariesFromData();\n\t\tpartitioningComputing();\n\t}\n\t//displaysGlobalVariables();\n}", "function partition(sll, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Right operand (y) is already a string.
function STRING_ADD_RIGHT(y) { var x = this; if (!IS_STRING(x)) { if (IS_STRING_WRAPPER(x) && %_IsStringWrapperSafeForDefaultValueOf(x)) { x = %_ValueOf(x); } else { x = IS_NUMBER(x) ? %_NumberToString(x) : %ToString(%ToPrimitive(x, NO_HINT)); } } return %_StringAdd(x...
[ "function checkForOneVar(str) {\n for(var i=0;i<str.length;i++){\n if(isOperator(str[i]) || isBrackets(str[i])){\n printError(\"invalid left hand side expression !\");\n return 0;\n }\n }\n return 1;\n}", "isString(expression) {\n doCheck(\n this.typesAreEquiva...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Table Ruler by Christian Heilmann modified by Stephen Robinson, so that it restores old row class name on mouse out.
function tableruler(){ var selectBug=false; // firefox 1.5.0.1. bug if(navigator.userAgent.indexOf("Firefox")!=-1){ var userAgentBits=navigator.userAgent.split("Firefox/"); var userAgentBits2=userAgentBits[1].split(" "); var ffNumber=userAgentBits2[0]; var ffNumberArray=ffNumber.split("."); var realNumber= ...
[ "function setRowColorClassTableSummary(doc)\r\n{\r\n\tvar elements = getElementsByClassName(doc, \"summaryTable\");\r\n\tvar table = elements[0];\r\n if (table){\r\n var rowNum = 0;\r\n for (var i = 1,len = table.rows.length; i < len; i++)\r\n {\r\n if(table.rows[i].style.display....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function returning char at given position in the editableDiv, given as parameter pos is indexed from 0
function getCharAtPosInDiv(editableDiv, pos) { // var text = getClearTextFromDiv(editableDiv); var text = editableDiv.textContent; return text.charAt(pos); }
[ "getChar(pos) {\n return this.document.getText(new vscode.Range(pos, pos.translate(0, 1)));\n }", "function getWordOnPosition(pos) {\n\tvar editableDiv = document.getElementById(\"inputTextarea\");\n\tvar curPos = getCaretPositionInDiv(editableDiv);\n\tsetCaretPositionInDiv(editableDiv, pos);\n\tvar wor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
append a single value to a specific trial in c.datasets
function append_trial_data(tix,tdat) { var queue = c.data.datasets[tix].data; if(queue.length > c.samples) queue.shift(); queue[queue.length] = parseInt(tdat); }
[ "function newTrain(t, d, ft, fr) {\n\n // Whatever will be in this variable will be \"pushed\" to a new reference,\n // instead of replacing an old reference.\n var train = database.ref().push();\n\n // sets the following parameters.\n // The parameter names is the name on the left of the colon.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ checkbox media type movies/tv shows ]
function media_type() { $('.switch-container label').on('click', function() { if (app.param.checked == true) { app.param.checkbox.prop('checked', false); $('label').removeClass('switch'); app.param.checked = false; get_data('movies'); return 'movies'; ...
[ "_changeVideoType(event) {\n let type = $(event.currentTarget).val();\n $('[data-video-type]', this.$el).closest('.form-group').hide();\n $('[data-video-type=\"'+ type +'\"]', this.$el).closest('.form-group').show();\n }", "function validateChannel() {\r\n let selection = document.getEl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MEMBROS numero de membros da banda
function numMembros(b) { var banda = docXML.getElementsByTagName("banda")[b].getElementsByTagName("membros")[0]; return banda.getElementsByTagName("membro").length; }
[ "function numFuncMembro(b, m) {\n var banda = docXML.getElementsByTagName(\"banda\")[b].getElementsByTagName(\"membros\")[0];\n var membro = banda.getElementsByTagName(\"membro\")[m];\n return membro.getElementsByTagName(\"funcao\").length;\n}", "get MINECOUNT(){ return this.mineCount }", "function num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Language: Ruby Description: Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. Website:
function ruby(hljs) { const RUBY_METHOD_RE = '([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)'; const RUBY_KEYWORDS = { keyword: 'and then defined module in return redo if BEGIN retry end for self when ' + 'next until do begin unless END rescue else break undef not...
[ "function swift(hljs) {\n const WHITESPACE = {\n match: /\\s+/,\n relevance: 0\n };\n // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID411\n const BLOCK_COMMENT = hljs.COMMENT(\n '/\\\\*',\n '\\\\*/',\n {\n contains: [ 'self' ]\n }\n );\n const COMMENTS = [\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GmailGreasemonkey API ( Implementation Reimplementation of getActiveViewType
function winActiveViewType() { var body = $('iframe#canvas_frame', parent.document).contents().find('div.nH.q0CeU.z'); if (body.is("*")) { return 'tl'; } else { return 'na'; } }
[ "function onViewType(e)\n{\n\tvar viewtype = $F($('viewtype')); // 0: autodetect, 1:table;\n\tclickTree(oidview._oid, oidview._idx, viewtype, column_names);\n}", "function getViews() {\r\n var sections = document.querySelectorAll(\".view\"),\r\n cList = [];\r\n for (var i = 0; i < section...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the function call string for a function call expression
function getFuncCallStr(fexpr) { assert(fexpr.isFuncCall()); // TODO: add args (with data types) // return (fexpr.str); }
[ "function getCallExpressionLog( callExpression ){\n var callee = callExpression.callee;\n var args = callExpression.arguments;\n\n if ( callee.type == 'MemberExpression' ){\n var objName = callee.object.name;\n var funcName = callee.property.name;\n return getLogCallFunc( objName + '.'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a boolean star or not star, and a record containing contig, position, reference, alternates, and sample_name, set 'annotations:starred' to star for the record with the matching contig, position, etc attributes. Notifies listening componenets once done.
function setLocalStarAndNotify(star, record) { var recordConditions = _.pick( record, 'contig', 'position', 'reference', 'alternates', 'sample_name'); record = _.findWhere(records, recordConditions); record['annotations:starred'] = star; notifyChange(); }
[ "function starGenotype(star, record) {\n var data = {\n starred: star,\n contig: record.contig,\n position: record.position,\n reference: record.reference,\n alternates: record.alternates,\n sampleName: record.sample_name\n },\n url = '/api/runs/' + record.vcf_id + '/genot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refresh the position and size of the monitor preview box.
refreshZoomPreview() { // Instead of moving the image around inside the monitor, scale the box to the size // of the preview "monitor", and scale/translate it around to show how the image would // fit inside it. let { animation, scaledWidth, scaledHeight, previewWidth, previewHeight ...
[ "updateDisplay()\n {\n // clip window position\n this.position.x = clamp(\n this.position.x, 0,\n this.window.innerWidth - this.element.clientWidth\n )\n this.position.y = clamp(\n this.position.y, 0,\n this.window.innerHeight - this.element...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to construct Purchase Order composite key
static getPOKey(ctx, buyerCRN, drugName) { return ctx.stub.createCompositeKey(pharmaNamespaces.PurchaseOrder, [buyerCRN,drugName]); }
[ "static getCompanyKey(ctx, companyCRN, companyName) {\n\t\treturn ctx.stub.createCompositeKey(pharmaNamespaces.Company, [companyCRN,companyName]);\n\t}", "function seed2key(pk, c){ return hex2hexKey(hash256(pk+c)); }", "static getShipmentKey(ctx, buyerCRN, drugName) {\n\t\treturn ctx.stub.createCompositeKey(pha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }