query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Call the event.persist if event is a react event object.
function wrapReactEventPersist(func) { return function (event) { if (event.nativeEvent instanceof Event && typeof event.persist === 'function') event.persist(); func(event); } }
[ "_persist() {\n\t\tstorage.set(STORAGE_KEY, this.events);\n\t}", "function doPersist(id) {\n var persistence = persists[id],\n mutation = mutations[id];\n if (mutation) {\n // Mutate just to update the timestamp (since we\n // ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to get Journey URL
getJourneyURL(guid, testMode = false) { //If in test mode, return the hard-coded val if (testMode) { return "https://www.google.com"; } //Otherwise, return the real one return 'https://mc.s4.exacttarget.com/cloud/#app/Journey%20Builder/%23' + guid + '/v'; }
[ "function getServerUrl() {\n\n var url = null,\n localServerUrl = window.location.protocol + \"//\" + window.location.host,\n context = getContext();\n\n\n if ( Xrm.Page.context.getClientUrl !== undefined ) {\n // since version SDK 5.0.13\n // http://www.mag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clone and add prefixes for atrule
add(rule, prefix) { let prefixeds = this.prefixeds(rule) if (this.already(rule, prefixeds, prefix)) { return } let cloned = this.clone(rule, { selector: prefixeds[this.name][prefix] }) rule.parent.insertBefore(rule, cloned) }
[ "addPrefixes(prefixes, done) {\n // Ignore prefixes if not supported by the serialization\n if (!this._prefixIRIs) return done && done(); // Write all new prefixes\n\n let hasPrefixes = false;\n\n for (let prefix in prefixes) {\n let iri = prefixes[prefix];\n if (typeof iri !== 'string') iri =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a function for putV3ProjectsIdEnvironmentsEnvironmentId
putV3ProjectsIdEnvironmentsEnvironmentId(incomingOptions, cb) { const Gitlab = require('./dist'); let defaultClient = Gitlab.ApiClient.instance; // Configure API key authorization: private_token_header let private_token_header = defaultClient.authentications['private_token_header']; private_token_header.api...
[ "function pushSeedAid(projectId,seedAid){\n Project.findById(projectId,function(err,proj){\n proj.seedAid.push(seedAid)\n proj.save();\n })\n}", "putV3ProjectsId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copyright (c) 20102012 Turbulenz Limited /global TurbulenzEngine: false /global Utilities: false /global Observer: false SceneNode
function SceneNode() {}
[ "function scene9()\n{}", "function Scene_BattleTS() {\n this.initialize.apply(this, arguments);\n}", "function root(element, name)\r\n{\t\r\n\t/*--------------------------------------------------------------------------------------\r\n\telement is supposed to be a scene but this object does not expect it to ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
important : hobbies[0]=the first hobby hobbies[1]=the second hobby . . hobbies[hobbies.length]=the last hobby nextHobby function
function nextHobby(){ // remove the class active from the current hobby for(i=0 ;i < hobbies.length;i++){ hobbies[i].classList.remove("active"); }; // if we are in the last hobby the variable ind will return to 0 if (ind == hobbies.length-1) { ind = 0; }else{ // if we are...
[ "function showHobbies() {\n const hobbies = db.get('hobbies').value();\n let index = 1;\n hobbies.forEach(hobby => {\n const todoText = `${index++}. ${hobby}`\n console.log(todoText);\n });\n}", "function midIndexHobby() {\n if (favHobby.length >= 20) {\n var halfHobby = favHobby.length /2;\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The JSONRPC constructor Each JSONRPC object created is tied to a particular JSONRPC server URL. This may be inconvenient for server architectures that have many URLs for each JSONRPC server, but this is an odd use case we aren't implementing. The constructed JSONRPC objects consist of three builtin methods: request req...
function JSONRPC(serverURL, options) { // ### The *request* function // is a non-blocking function that takes an arbitrary number of arguments, // where the first argument is the remote method name to execute, the last // argument is the callback function to execute when the server returns its // results, and all ...
[ "function JSONRpcClient()\r\n{\r\n var arg_shift = 0, req, _function, methods, self, name, arg0type= (typeof arguments[0]), doListMethods=true;\r\n\r\n //If a call back is being used grab it\r\n if (arg0type === \"function\")\r\n {\r\n this.readyCB = arguments[0];\r\n arg_shift++;\r\n }\r\n // if it's a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A class to hold information related to a radar plot
function RadarPlot(num) { var radarMode = 1; // 0=teal(static); 1 = average score fill; 2 = score cluster fill var hilite = -1; var nRadar; // Number of dimensions in Radar Plot var scores; var names; var avgScore; nRadar = num; scores = new Array(); names = new Array(); avgScore = 0; for ...
[ "function RadarChart(id, data, options) {\n var cfg = {\n w: 600,\t\t\t\t//Width of the circle\n h: 600,\t\t\t\t//Height of the circle\n margin: { top: 50, right: 50, bottom: 50, left: 50 }, //The margins of the SVG\n levels: 3,\t\t\t\t//How many levels or inner circles should there b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get or create a Component based on the scope and identifier. If called multiple times with the same arguments, it will return the same Component.
pickComponent(scope, identifier) { const identifiers = getOrSet(this.repository, scope, () => new Map()); return getOrSet(identifiers, identifier, () => { return new Component(scope); }); }
[ "generateComponent(scriptName) {\n if (!this._store[scriptName]) {\n return null;\n }\n\n let component = Object.create(this._store[scriptName].prototype);\n component._name = scriptName;\n\n // now we need to assign all the instance properties defined:\n let properties = this._store[scriptNa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a display panel
buildSimpleDisplayPanel(title, single, double, immune) { single = single || [] double = double || [] immune = immune || [] let panel = document.createElement("div"); panel.classList.add("panel"); let label = document.createElement("h3"); label.classList.add("lab...
[ "function createPanel( pw, ph, director ){\n\t\tdashBG = new CAAT.Foundation.ActorContainer().\n\t\t\t\t\tsetPreferredSize( pw, ph ).\n\t\t\t\t\tsetBounds( 0, 0, pw, ph ).\n\t\t\t\t\tsetClip(false);\n\n \n\t\t//create bottom panel\n\t\tfor(var i=0;i<dashBoardEle.length;i++){\n\t\t\tvar oActor = game.__addImage...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CHALLENGE Write a function named every that takes an array and a value and returns true if every element of the array equals the value Example: If you pass [1,1], 1 it should return true If you pass [1,2], 1 it should return false array + value > boolean true if all elements in array === same value, loop, conditional
function every(array, value) { var boolean = true; array.forEach(el => { if (el !== value) { boolean = false } }) return boolean; }
[ "function checkEvery(arr) {\n return arr.every(v => v % 3 == 0 )\n}", "function allSame (arr) {\n\t if (!Array.isArray(arr)) {\n\t return false\n\t }\n\t if (!arr.length) {\n\t return true\n\t }\n\t var first = arr[0]\n\t return arr.every(function (item) {\n\t return item === first\n\t })\n\t}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
we want that every spec is satisfied by the item that passed
isSatisfied(item) { return this.specs.every(x => x.isSatisfied(item)); }
[ "passesFilter(item) {\n //Fetch filter\n let filter = this.props.filter;\n if (filter.rarity === \"0\" || filter.rarity === item.rarity) { //Check if it passes rarity\n if (filter.type === \"0\" || filter.type === item.type) { //Check if item passes type-check\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the role if storage is tampered
static tamper() { del("user").then(() => { localStorage.removeItem("role"); location.reload(); }); }
[ "async function resetRoleInheritance() {\n await spPost(SPQueryable(this, \"resetroleinheritance\"));\n}", "function resetRunningServant(caseID) {\n delete localStorage['smaAnalyticsCase' + caseID];\n}", "vaciarLocalStorage() {\n localStorage.clear();\n }", "deleteAll(req, res) {\n if (process.en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve cached image file path data. See cacheImageFilePaths(media_file_list) function for cache creation.
function getImageFilePathsFromCache() { return $("body").data("image file list"); }
[ "fileListCache() {\n return remote.getGlobal('application').fileListCache;\n }", "function loadFileCache() {\n\tcachedFileInfo = getLocalSetting(\"cachedFileInfo\", {});\n}", "function getCachedImage(path){\n\n\tif(!io.fileExistsSync(path)){\n\t\t// File does not exist so.. doenst really matter\n\t\treturn ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the private key from the subseed.
function privateKeyFromSubseed(subSeed, securityLevel) { var keyLength = securityLevel * PRIVATE_KEY_FRAGMENT_LENGTH; var keyTrits = new Int8Array(keyLength); var actualKeyTrits = new Int8Array(keyLength); var sponge = new Curl(27); sponge.absorb(subSeed, 0, subSeed.length);...
[ "getPrivKey() {\n var output = PrivKeyAsn1.encode({\n d: this.key.priv.toString(10),\n }, \"der\")\n return output.toString('hex')\n }", "function digestFromSubseed(subSeed, securityLevel) {\r\n var curl1 = new Curl(27);\r\n var curl2 = new Curl(27);\r\n var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: loadSubCCText Load the CC text into the CC area for subpages (like popups or contentSwaps) Parameters: textThe text to load into the CC area Dependencies: None Returns: none Change Log: 2013.02.19ALP Initial version
function loadSubCCText(text) { clearCC(); $('#'+shell.caption.textEl).append(text); if (CCIsDim) enableCC(); }
[ "function loadCCText(text) {\n\tclearCC();\n\t//console.log(\"Loading: \"+text);\n\t$('#'+shell.caption.textEl).append(text);\n\tif (CCIsDim) enableCC();\n}", "function loadPageCC() {\n\t// Reset the position of the CC array to zero.\n\tshell.caption.currPosition = 0;\n\tstoreCCData();\n\t// If CC is not timed, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
swapping binary digits in array
function swapBinaryDigits(arr, length) { var tempArr = []; for(var i=0; i<(length/2); i++) // copying original array's first four elements into temporary array tempArr[i] = arr[i]; i = 0; for(i=(length/2),j=0; i<length; i++,j++) // copying original array's last four elements into original array's first four...
[ "function pairwiseSwap(num){\n const even = 0xAAAAAAAA;\n const odd = 0x55555555;\n\n return ((num & even) >> 1) | ((num & odd) << 1);\n}", "function shiftVals(num, array, idx) {\n for (let i = 0; i <= idx; i++) {\n if (i === idx) {\n array[i] = num;\n } else {\n array[i] = array[i + 1];...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update the sim record with the customer
function updateSimRecord() { try { if(custIntID!=0) { simRecord.setFieldValue('custrecord_sim_customer', custIntID); } simIntID = nlapiSubmitRecord(simRecord, true); } catch(e) { errorHandler("updateSimRecord", e); } }
[ "function updateCustomer(customer) {\n\t \tconsole.log(customer);\n\t var deferred = $q.defer();\n\t $http.post(BASE_URL + \"customer/update\", customer)\n\t .then(\n\t function (response) {\n\t deferred.resolve(response.data);\n\t },\n\t f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
verify that the current user token is still active
function isActiveToken () { const url = `${baseURl}/api/user/verifyToken` return localforage.getItem('token').then((jwt) => { return axios.post(url, { params: jwt }) }) }
[ "checkToken() {\n if(localStorage.getItem(\"token_time\") != null) {\n if(new Date().getTime() - new Date(localStorage.getItem(\"token_time\")).getTime() > 60000) {\n localStorage.setItem(\"token_time\", (new Date()).toString());\n console.log(\"update token\");\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show or Hide Location History View Sub Div
function showHideLocationHistoryRoleDiv(){ if(document.getElementById('locationHistoryMenuViewId').checked==true){ document.getElementById('locationHistoryMenuSubTableDivId').style.display = "block"; }else{ document.getElementById('locationHistoryMenuSubTableDivId').style.display = "none"; } }
[ "function openHistoryPage() {\n renderHistory();\n $(\"#start-screen\").addClass(\"hide\");\n $(\"#setup-screen\").addClass(\"hide\");\n $(\"#game-screen\").addClass(\"hide\");\n $(\"#history-screen\").removeClass(\"hide\");\n}", "function openSessionInfo() {\n document.getElementById('session-info-div').st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HELPER FUNCTIONS Print objects in metadata file, with number of items
function metaDataObjects() { for (var object in metaData) { console.log(object + " - " + metaData[object].length); } }
[ "function getObjectLength(object) {\n // YOUR CODE BELOW HERE //\n \n var count = 0 //initialize a variable\n for (var key in object) { //iterate through the given object\n count++; //count each key/value and store the value in count variable\n }\n \n return count //return the number of key/value pairs\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_______________________________________________________ areValidRuns this function checks that all the files have consistent file extensions using regex Return Value is_consistent bool ___________________________________________________________
function areValidRuns(){ // Check consistency of file types var re = /(?:\.([^.]+))?$/; // Regex for file type var ext = re.exec(importPaths.runs)[1]; var is_consistent = true; if (importPaths.runs.length) { for (let i = 0; i < importPaths.runs.length; i++) { let test = re.exec(...
[ "function checkFiles() {\n\t\tpkg.files &&\n\t\t\tpkg.files.forEach(pattern => {\n\t\t\t\t// skip patterns like \"!foo\"\n\t\t\t\tif (!pattern.startsWith('!')) {\n\t\t\t\t\tconst matchedFiles = globby.sync(pattern, {\n\t\t\t\t\t\tcwd: opts.cwd\n\t\t\t\t\t});\n\t\t\t\t\tif (matchedFiles.length === 0) {\n\t\t\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get tje first mark matching a filter criteria
function findBy(filter) { return db('marks') .where(filter) .select() .first(); }
[ "getFirstEntry(name, filter = () => true) {\n return this.getEntries(name)\n .filter(filter)\n .shift();\n }", "function getAfterFormulaFilter () {\n var firstFormula = Preview.dom.querySelector('.formula'),\n firstFragment = Preview.dom.querySelector('.fragment'),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch the entities info
function fetchEntitiesInfo() { server.get('quest') .then((response) => { setHero({ ...response.data.hero }); setMonster(response.data.monster); }); }
[ "function showEntities() {\n db.allDocs({include_docs: true, descending: true}, function(err, doc) {\n redrawEntitiesUI(doc.rows);\n });\n }", "function get_entities (entity_class,callback) { \n $.getJSON(\"/\" + entity_class, null, function(entities) {\n $.app[entity_class] = entities;\n call...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserallocate_extent_clause.
visitAllocate_extent_clause(ctx) { return this.visitChildren(ctx); }
[ "visitExtent_management_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitBounds_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSupplemental_plsql_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitMaxsize_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves node p and all its connected channels to the top layer
function bringNodeToFront(p) { let i, j; p.selection.bringToFront(); for (i = 0; i < p.channels.length; ++i) { for (j = 1; j < p.channels[i].parts.length; ++j) p.channels[i].parts[j].bringToFront(); p.channels[i].node1.bringToFront(); p.channels[i].node2.bringToFront() } p.label.bringToFront(); if (p.del...
[ "function bringComponentToFront(p) {\n\tif (!p || p.class !== 'component') return;\n\n\tlet i, j, limit = components.length;\n\n\t// Move p to the end of the array\n\tfor (i = 0; i < limit; ++i)\n\t\tif (components[i] === p) {\n\t\t\tcomponents.splice(i, 1);\n\t\t\tp.set('index', components.length);\n\t\t\tcomponen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called once by start() to get animateSteps & animateDraws iterating.
animate () { if (this.multiStep) this.animateSteps() this.animateDraws() }
[ "once () { this.step(); this.draw() }", "_startAnimationLoop() {\n\t\t\tconst xTermMaterials = Array.from(this._xTermLayerMap.values());\n\t\t\tconst timeUniforms = this._shaderPasses.filter(pass => {\n\t\t\t\treturn pass.getFullscreenMaterial().uniforms.time !== undefined;\n\t\t\t}).map(pass => {\n\t\t\t\treturn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The key of the catch clause is stored in this.catch_clauses[this.current_class][this.current_function][try_key] The finalizer is added as the continuation of the try statement.
visitTryStatement(node){ var key = this.addToCFG(node); this.node_stack[this.current_class][this.current_function].push(key); this.visit(node.block); this.catch_clauses[this.current_class][this.current_function][key] = this.nodeStr(node.handler); this.visit(node.handler); //...
[ "function simple_try_finally_test() {\n var i = 0;\n try {\n i++;\n }\n finally {\n i += 2;\n }\n i += 3;\n}", "enterCatchBlock(ctx) {\n\t}", "exitTryExpression(ctx) {\n\t}", "function accessErrorThrower(message, key) {\n\treturn function () {\n\t\tthrow {\n\t\t\tmessage: message,\n\t\t\tkey: key\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables users to add a total spending dataset to the chart in order to compare filtered data to total spend.
toggleTotal () { let { chartData } = this.state, total; // checks state of the chart if (!this.state.displayTotal) { if (this.state.displayAnnual) { total = generateMonthlyData(this.props.transactions); total.datasets[0].label = 'Monthly Totals' } else { total = generateD...
[ "function updateTotals(data)\n{\n\tif (data.length != 0) {\n\tvar totalDataLength = totalChart.datasets[0].points.length-1;\n\ttotalChart.datasets[0].points[totalDataLength].value = data[data.length-1].total;\n\tif (totalDataLength-1 > labelLength) {\n\t\tvar label = totalChart.datasets[0].points[totalDataLength].l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
errorMessage(msg) displays error message
function errorMessage(msg) { // console.log(msg); }
[ "function getErrorMessage(errorCode) {\n var Error = {};\n Error[errorCode] = 'Please try again';\n Error[errorCode] = 'Please try again';\n Error[errorCode] = 'Database version Error';\n Error[errorCode] = 'Data too large Error';\n Error[errorCode] = 'Data quota Error';\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array whose members are the last three members of the input array. If the array has less than 3 members returns the array.
function lastThree(arr) { if (arr.length > 3) { for (var i = 0; i < arr.length; i++) { return arr.slice(1); } } else { return arr; } }
[ "function lastNElements(array, n) {\n // TODO: your code here\n if(array.length===0){\n return [];\n }\n else if(array.length<n)\n return array;\n\nelse \nreturn array.slice(array.length-n,array.length);\n}", "function getLastNItems(arr,num){\n \n return (num > 0) ? arr.slice(-num) : [];\n}", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a unit vector with x/y coordinates.
function getUnitVector(x, y) { var d = Math.sqrt(x * x + y * y); x /= d; y /= d; if (x === 1 && y === 0) { return xUnitVector; } else if (x === 0 && y === 1) { return yUnitVector; } else { return new UnitVector(x, y); } }
[ "get centre() { return new vector2(this.centrex, this.centrey);}", "getVector() {\n if (this.parent) {\n let dx = this.parent.loc.x - this.loc.x;\n let dy = this.parent.loc.y - this.loc.y;\n let v = new JSVector(dx, dy);\n return v;\n }\n else retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
include internals with state
fullState() { return Object.assign({}, this.state, this.internals); }
[ "async addState(state) {\n console.log(state.getClass())\n let key = this.ctx.stub.createCompositeKey(state.getClass(), state.getSplitKey())\n let data = State.serialize(state)\n await this.ctx.stub.putState(key, data)\n }", "_transferState(oldLayer) {\n Object(_debug__WEBPACK_IMPORTED_MODULE_7__[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the page changed / user scrolled and updates the dots
function checkIfPageChanged() { if (!isPaperMode()) { return; } var scrollLeftPX = document.getElementsByClassName("ql-editor")[0].scrollLeft || 0; var scrollLeftMM = px2mm(scrollLeftPX); var visiblePageNo = scrollLeftMM / (paper.width + paper.opticalSeparator); visiblePageNo = parseFloat(visi...
[ "function handleScroll() {\n const bottomDiff = document.documentElement.offsetHeight - (window.innerHeight + document.documentElement.scrollTop);\n if (bottomDiff > 300) {\n needToHitApi = true;\n return;\n }\n if (needToHitApi) setPage(page => page+1);\n needToHitApi = false;\n }", "function ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
COnstructor function for CurrencyInput class
constructor() { super('CurrencyInput'); }
[ "function CurrencyHandler() {\n\t\tthis.type = 'currency';\n\t}", "function init() {\n utilsService.addDropdownOptions('from-currency', availableCurrencies);\n document.getElementById('amount').value = defaultAmount;\n getRates(selectedBase);\n}", "constructor(name, amount) {\n this.name = name;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public function `like`. Tests whether `data` 'quacks like a duck'. Returns true if `data` has all of the properties of `archetype` (the 'duck'), false otherwise.
function like (data, archetype) { var name; for (name in archetype) { if (archetype.hasOwnProperty(name)) { if (data.hasOwnProperty(name) === false || typeof data[name] !== typeof archetype[name]) { return false; } if (object(data[name]) && like(data[name], archetype[na...
[ "function like (data, duck) {\n var name;\n\n for (name in duck) {\n if (duck.hasOwnProperty(name)) {\n if (data.hasOwnProperty(name) === false || typeof data[name] !== typeof duck[name]) {\n return false;\n }\n\n if (object(da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Switch the thread to the next block at the current level of the stack. For example, this is used in a standard sequence of blocks, where execution proceeds from one block to the next.
goToNextBlock () { const nextBlockId = this.target.blocks.getNextBlock(this.peekStack()); this.reuseStackForNextBlock(nextBlockId); }
[ "enterSwitchBlock(ctx) {\n\t}", "function breakBlock (state) {\n var block = state.player.lookAtBlock\n if (!block) return\n\n var loc = block.location\n var neighbors = [\n state.world.getVox(loc.x + 1, loc.y, loc.z),\n state.world.getVox(loc.x, loc.y + 1, loc.z),\n state.world.getVox(loc.x - 1, loc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
drawText randomizeArea(): Randomizes the specified area of the virtual display. The area will contain random pixels and colours.
function randomizeArea(line, col, lines, cols) { // const randomByte = () => Math.floor(Math.random() * 256) // // randomize the colour attributes for (let l = line; l < (line + lines) && l < LINES; l++) for (let c = col; c < (col + cols) && c < COLUMNS; c++) displayColour...
[ "function drawRandomDisplay() {\r\n const c = console\r\n c.time(\"drawRandomDisplay()\")\r\n const d = ZXDisplay\r\n //\r\n // randomize the display\r\n c.time(\"randomizeArea()\")\r\n d.randomizeArea(0, 0, d.LINES, d.COLUMNS)\r\n c.timeEnd(\"randomizeArea()\")\r\n //\r\n // draw the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load all named bundles from the array, returned as an array of Bundle objects.
function loadBundlesFromArray(bundleArray) { var bundlePromises = legacyRegistry.list() .concat(bundleArray) .filter(unique) .map(loadBundle); return Promise.all(bundlePromises) .then(filterBundles); ...
[ "function bundles(loader) {\n if (typeof indexOf == 'undefined')\n indexOf = Array.prototype.indexOf;\n\n // bundles support (just like RequireJS)\n // bundle name is module name of bundle itself\n // bundle is array of modules defined by the bundle\n // when a module in the bundle is requested, the bundle ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
searchStationsCall Search items based on identifier, comment fields or tags filt Some text to match. Wildcards at beginning or end are allowed tags comma separated list of keywords (tags). cb callback function to receive the result. The result will be text representation of a HTML table
function searchItems(filt, tags, cb) { var url = server_url + (getLogin() ? 'srv/search_sec?' : 'srv/search?'); call( url + "ajax=true&lang="+language+ (filt!=null && filt != '' ? '&srch='+filt : '') + (tags!=null && filt != '' ? '&tags='+tags : '') + (isMobile==true?"&mobile=true":""), null, c...
[ "function search(searchString, titleSearchBool, tagsSearchBool, commentsSearchBool) {\r\n\tvar theTerms = splitSearchString(searchString);\r\n\tif (theTerms.length == 0) {\r\n\t\tvar allEntries = dataHandler.getAllEntries();\r\n\t\treturn allEntries;\r\n\t}\r\n\t\r\n\tvar positiveMatches = [];\r\n\tvar negativeMatc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates lines when closing a node
function closeNode(node, isRight, options) { //go to a rank and execute updating function removeLinesAndChildrenOf(node); updateNodeLines(node, isRight, options); //console.log(lines); }
[ "exitLineStringContent(ctx) {\n\t}", "function onRemoveLine() {\n removeLine()\n renderMeme()\n}", "close() {\n if(this.added) {\n this.added = false;\n this.getJQueryObject().remove();\n\n // Remove entry from global entries variable\n entries = _.omit(e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
toggleClass("highlight"); 20100722: refreshes the facet values available.. flag is used to determine whether the update is run by itself, or after updating the result list in the first case, we need to block the screen; in the second one, that is managed in 'ajax_update1'
function OLD_updateFacetValues(flag) { if (!flag) var flag = false; var resulttype = what_result_type(); var activefacet = $("#accordion h5.ui-state-active").parent(); // the <LI> element var is_tree_facet = $("#accordion h5.ui-state-active").parent().hasClass('istreefacet') var activefacetid = $("#accordion h5.ui...
[ "function delayUpdateFacetValues(time, flag) {\n\tif (!time) var time = 400;\n\tif (!flag) var flag = false;\n\n\t// this is a hidden field that contains a Flag (set at initial loading time) indicating whether refresh is automatic\n\tif (isFacetedCountActive()) {\n\t\t// hack for IE\n\t\tvar myfun = function() { up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds an array to memory at a given position returns new pos
function create_arr(mem, pos, size) { reserve_mem(mem, pos, 4 + size * 4); let view = new DataView(mem.buffer); // write size view.setUint32(pos, size, true); pos += 4; // initialize to zero let arr_pos = 0; while (arr_pos < size) { view.setUint32(pos, 0, true); pos += 4; ++arr_po...
[ "function pointerInc(){\r\n pointer++;\r\n if(pointer === arr.length){\r\n arr.push(0);\r\n }\r\n \r\n}", "add(element) {\n this._buffer.unshift(element);\n this._buffer = this._buffer.splice(0, this._size);\n }", "function addToEnd(array, item) {\n var index = array.index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turn an object to a Mapnecessary because should.js's equality tests want prototypes to match
function asMap(obj) { return Object.assign(new Map(), obj); }
[ "function objectToMap(o) {\n if (o !== undefined && o !== null) {\n return new Map(objectEntries(o));\n }\n return new Map();\n }", "function ObjectMap(stringify){\n\n\tif(typeof stringify == 'function')\n /**\n \t* Method to find unique string keys for objects.\n \t*/\n \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
replaces "" in schoolName with ""
function getSchoolname(schoolName) { return schoolName.replace("-", "-<br>") }
[ "function filter_course_title (course_title)\n{\n course_title = course_title.replace(/(.*\\S)\\s*/, \"$1\");\t// remove trailing space\n//\n//\tthe '&' in the data causes problems (by repalcing it with \"&amp;\" the semicolon is the problem)\n//\t\tMost notablely is when the & is in the course name.\n//\t\tI do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear canvas, reset the counter and redraw the image
function clearCanvas() { context.clearRect(0, 0, canvas.width, canvas.height); pointCount = 0; drawImage(); }
[ "function reset() {\n Caman(\"#canvas\", img, function () {\n this.revert();\n })\n}", "function resetCanvas() {\n\tcxt.fillStyle = localStorage.fillColor;\n\tcxt.fillRect(0, 0, canvas.width, canvas.height);\n}", "function clear_data_canvas(){\n data_ctx.clearRect(0,0,110,80)\n}", "onResetCanv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simplify but discard any errors
trySimplify(context, value) { const originalRecorder = this.errorRecorder; this.errorRecorder = (error, fileName) => { }; const result = this.simplify(context, value); this.errorRecorder = originalRecorder; return result; }
[ "function finalSimplify(expr) {\n return math.rationalize(expr, {});\n }", "function simplifyPathExpression(graph, p) {\n\n let reduced =\n _(p)\n .groupBy('compositionNode.id') // We group path that go to the same target\n .map(x => // For each of these groups\n ({\n compositionNode: x[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the current value of a name, or `undefined` if there is no value. Note: Do not use `if (namespace.get(...))` to detect whether a macro is defined, as the definition may be the empty string which evaluates to `false` in JavaScript. Use `if (namespace.get(...) != null)` or `if (namespace.has(...))`.
get(name) { if (this.current.hasOwnProperty(name)) { return this.current[name]; } else { return this.builtins[name]; } }
[ "getMacro(name) {\n const len = this.stack.length - 1;\n for (let i = len; i >= 0; i--) {\n const inst = this.stack[i]._getMacro(name);\n if (inst !== null) {\n return inst;\n }\n }\n return null;\n }", "function get_value_for_variable_from_workspace(variable_name){\n var val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the |player| has taken a shot, irrespective of whether it hit anything. When the shot has hit a vehicle rather than a player, and the vehicle is occupied by a driver, then the driver will be tagged as having just taken damage instead.
onPlayerWeaponShot(player, weaponId, hitType, hitId, hitPosition) { const currentTime = server.clock.monotonicallyIncreasingTime(); this.deathmatchWeaponShotTime_.set(player, currentTime); if (hitType === 2 /* BULLET_HIT_TYPE_VEHICLE */) { const vehicleId = server.vehicleManager.ge...
[ "onPlayerTakeDamage(player, issuer) {\n if (!issuer)\n return;\n\n const currentTime = server.clock.monotonicallyIncreasingTime();\n\n this.deathmatchDamageTakenTime_.set(player, currentTime);\n this.deathmatchDamageIssuedTime_.set(issuer, currentTime);\n }", "function zo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a list of uuids that should be Accordion preExpanded'ed Docs:
function preExpandedIds(record) { return record.resourceAccess.reduce((acc, item, index) => { if (item.preExpanded) { acc = acc.concat(createId(record, index)) } return acc }, []) }
[ "_allHeadings() {\n return Array.from(this.querySelectorAll('howto-accordion-heading'));\n }", "function makeInsulaIdsListShortNamesList(){\n\t\tvar currentInsulaId;\n\t\tpompeiiInsulaLayer.eachLayer(function(layer){\n\t\t\tif(layer.feature!=undefined){\n\t\t\t\tcurrentInsulaId=layer.feature.properties.in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the absolute center of the shape.
get_abs_center() { var aabb = this.get_aabb(); return aabb.position.add(aabb.size.multiply_scalar(0.5)); }
[ "center() {\n return this.normal.mulX(this.d);\n }", "get center() {\n\n // Check if the face is bound to a mesh and if not throw an error\n if (!this.mesh) throw new Error(`Cannot compute the face center - the face is not bound to a Mesh`);\n\n // Calculate the center of the face\n return n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
monitorSupportsSecrets returns a promise that when resolved tells you if the resource monitor we are connected to is able to support secrets across its RPC interface. When it does, we marshal outputs marked with the secret bit in a special way.
function monitorSupportsSecrets() { return monitorSupportsFeature("secrets"); }
[ "function monitorSupportsFeature(feature) {\n return __awaiter(this, void 0, void 0, function* () {\n const localStore = state_1.getStore();\n const monitorRef = getMonitor();\n if (!monitorRef) {\n return localStore.settings.featureSupport[feature];\n }\n if (localS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deprecated. This will be deleted in a future version of Formulate. Ensure each cell has a column span. This is done because older versions of Formulate did not have a column span specified for each cell.
function ensureFallbackColumnSpans(rows) { var i, row, cell; for (i = 0; i < rows.length; i++) { row = rows[i]; for (j = 0; j < row.cells.length; j++) { cell = row.cells[j]; if (!cell.columnSpan) { cell.columnSpan = 12 / row.cells.length; } ...
[ "checkCols(){\n\t\tthis.checkBounds();\n\t\tthis.checkBlocks();\n\t}", "updateColumnDisplay() {\n let i = 0;\n while (i < this.columnData.length) {\n let colData = this.columnData[i];\n let colWidth = colData.getValue('widthVal');\n let colSpan = colData.getValue('co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EDGE CASE: empty input `find` UTILITY FUNCTION recursively searches input tree for a node with value matching `key`. if such a node exists, returns an array containing (1) the node, and (2) its parent node, or null if the matching node is the root. if such a node does not exist, returns [null, null]
function find (node, parent = null) { if (key < node.val) { return node.left ? find(node.left, node) : [null, null]; } else if (key > node.val) { return node.right ? find(node.right, node) : [null, null]; } else { return [node, parent]; } }
[ "find(value){\n const go = (value, node, parent, depth) => {\n if(node === null) return [false, null, null, null];\n else if(value === node.value) return [true, node, parent, depth];\n else\n return value < node.value ? go(value, node.left, node, ++depth) : go...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
take all grades and find the average percentage
averageAssignmentGrade(grades) { // return grades.reduce(function(acc, grade) { var avg = grades.reduce(function(acc, grade) { return acc + grade.percentage; }, 0) / grades.length; return Number(avg.toFixed(2)); // return avg; }
[ "function calculateAverage(grades) {\n // grades is an array of numbers\n total = 0\n for(let i = 0; i <grades.length; i++){\n total += grades[i];\n }\n return Math.round(total / grades.length);\n}", "function average() {\n\tvar total = 0;\n\tfor (var i = 0; i < this.grades.length; ++i) {\n\t\ttotal += th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method to return all todo
getAll() { return this.todos; }
[ "async getTodos(userId) {\n return this.internalState.todos[userId];\n }", "listTodos() {\n this.todosParent.innerHTML = null;\n const list = lsModule.readFromLS();\n if (!list) {\n console.log(\"No tasks\");\n renderEmptyList(this.todosParent)\n const btnComplete = utilitiesModule.qs(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 734 Given an array of numbers, create a function which returns the same array but with each element's index in the array added to itself. This means you add 0 to the number at index 0, add 1 to the number at index 1, etc...
function addIndexes(arr) { return arr.map((x, i) => x + i) }
[ "function addOne(inputArray) {\n return inputArray.map(item => item + 1);\n}", "function add1ToEach(array) {\n return array.map (function (value2) { return value2 += 1; })\n}", "function arraySum(array){\n var sum=0;\n var index=0;\n function add(){\n if(index===array.length-1)\n return sum;\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send a dlr to an sms This must be called from an sms object context
function smsDlr(status, callback) { var shortMessage, dlrPduObj, err, sms = this; if (typeof status === 'function') { callback = status; status = undefined; } if (status === undefined || status === true || status === 2 || status === 'true') { status = 2; } else if (defs.consts.MESSAGE_STAT...
[ "function sendTwilioMessage (client,from,to,body){\n client.messages\n .create({\n body: \"your passowrd is:\"+body,\n /*from: '+12074075156',*/\n from:from,\n to:to \n })\n .then(message => console.log(\"here the message id:\"+message.sid));\n}", "async sendMessages({ text,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the unique group corresponding to the provided group key.
function resolveGroupReference(key) { for (var i = 0; i < groupedItems.groups.length; i++) { if (groupedItems.groups.getAt(i).key === key) { return groupedItems.groups.getAt(i); } } }
[ "function _getGroupKeySelector(item) {\n return item.group.key;\n }", "async function getGroupName(group) {\n const result = await db.collection(\"Groups\")\n .findOne({ _id: ObjectId(group) }, { projection: { _id: 0, name: 1 } });\n\n if (result === null) {\n throw new RequestError('group does ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that calls all the export csv functions for the recommender
function csvExportRecommenderData() { csvExportUser() csvExportVideoHistory() csvExportVideoAnalytics() csvExportFavouritedVideos() csvExportSkillsSelectedFreq() }
[ "function handleExportCSV() {\n analyticsService.logEvent('EE Employment Training', 'Clicked', `Export_CSV`)\n GridHelpers.exportDataAsCSV({\n selectedRows: selectAllChecked ? null : selectedRows,\n rowData: employee_training_report_items,\n sortColumn,\n sortDirection,\n searchTerm,\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads temperature sensor library
function loadTempSensorLibrary(pO) { var fM = new ModuleObj("TempSensorLib"); CurModObj = fM; // Create a function object, add a function call expression (header) // var name = "collectSensorData"; var fPI = new FuncObj(true); fPI.funcCallExpr = new ExprObj(false, ExprType.LibFu...
[ "function readTemp() {\r\n\tvar temperature;\r\n\tsensor.read(2, function(err, res) {\r\n\t\tif(err) {\r\n\t\t\tconsole.log(\"readTemp: err: \" + err);\r\n\t\t}\r\n\t\t// console.log(\"readTemp: \" + res);\r\n\t\ttemperature = ((((res[0]<<8) + res[1]) * 175.72) / 65536) - 46.85;\r\n\t\tconsole.log(\"temperature: \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a [probability mass function](
function probability_mass(x, trials, probability) { return factorial(trials) / (factorial(x) * factorial(trials - x)) * (Math.pow(probability, x) * Math.pow(1 - probability, trials - x)); }
[ "function crewMass(arr){\n let mass = 0;\n for (i=0;i<arr.length;i++){\n mass += arr[i].mass;\n }\n return mass;\n }", "function probabilityGenerator(n, probabilities){\n //plan\n // generate a random int between 0 and 100\n // if int is probability[i] + all previous proababil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows aggregate calorie status for the week
getReportWeek(){ let goal = this.gCals() * 7; let eaten = this.getFoodWeek().calories; let burned = this.getActivitiesWeek().caloriesBurned; let calRemaining = goal - eaten + burned; return {eaten: eaten, burned: burned, goal: goal, remaining: calRemaining}; }
[ "getActivitiesWeek(){\n let temp = [];\n let today = new Date();\n let calBurned = 0;\n let lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);\n for(var i=0; i< this.activitiesLog.length; i++){\n if(this.activitiesLog[i].date >= lastWeek &&...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables or disables the new file submenu in the file menu.
toggleSidenavNewFile() { if (this._sidenavExtra.newFile.opened) { this._sidenavExtra.newFile.opened = false; $('#hidden-new-file').hide(); $('#new-file-name').val(''); $('#hidden-new-file-info').empty(); } else { this._sidenavExtra.newFile.opened = true; $('#hidden-new-file'...
[ "function menuHandler(){\n if(command.getChecked()){\n command.setChecked(false);\n prefs.set('enabled',false);\n return;\n }\n command.setChecked(true); \n prefs.set('enabled',true);\n var st = startTabEx();\n }", "function openE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Defines headers for use in the xhr request for a particular segment.
segmentXhrHeaders_(segment) { let headers = {}; if ('byterange' in segment) { headers.Range = this.byterangeStr_(segment.byterange); } return headers; }
[ "function setHeaderWithToken() {\n var cookie = $.cookie(\"accessToken\");\n\n $(document).ajaxSend(function (event, jqxhr, settings) {\n jqxhr.setRequestHeader('Authorization', 'bearer ' + cookie);\n });\n }", "setHeader(key, value) {\n this._headers[key] = value\n }", "funct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new ``bytes9`` type for %%v%%.
static bytes9(v) { return b(v, 9); }
[ "static bytes11(v) { return b(v, 11); }", "static bytes23(v) { return b(v, 23); }", "static bytes10(v) { return b(v, 10); }", "static bytes8(v) { return b(v, 8); }", "static bytes(v) { return new Typed(_gaurd, \"bytes\", v); }", "static bytes25(v) { return b(v, 25); }", "static bytes21(v) { return b(v, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all plugin importers for specfied platform.
static GetImporters() {}
[ "entryPlugins(context) {\n const plugins = this.data.map(({chunk, entry}) => (\n new (Array.isArray(entry) ? MultiEntryPlugin : SingleEntryPlugin)(context, entry, chunk)\n ));\n return {\n apply(compiler) {\n plugins.forEach(plugin => plugin.apply(compiler));\n }\n };\n }", "asy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a javascript object within speedArray that has a similar memberID as the currently active object
function compareSpeed (activeObject) { for (var i = 0; i < speedArray.length; i++) { if (activeObject.member == speedArray[i].id) {return speedArray[i]; } } }
[ "function compareRamp (activeObject) {\n if (activeObject.type == 'onRamp') {\n for (var i = 0; i < onRampArray.length; i++) {\n if (activeObject.member == onRampArray[i].id) {return onRampArray[i]; }\n }\n }\n else if (activeObject.type == 'offRamp') {\n for (var i = 0; i < offRampArray.length; i+...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validation to see if you have initialized the crawl
function crawlStarted() { return ($localStorage.currentCrawl !== undefined); }
[ "_init() {\n try {\n if (!fs.existsSync(LINKS_DIR)) {\n fs.mkdirSync(LINKS_DIR);\n }\n this.links = require(LINKS_PATH);\n\n for (const key in this.links) {\n if (this.links.hasOwnProperty(key)) {\n const url = this.links[key].url;\n\n if (!this._urls[url]) {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns object containing array indexs of all brackets, and array of types of brackets
function findAllBrackets(arr) { let indexArray = []; let bracketType = []; for (let i = 0; i < arr.length; i++) { if (arr[i] == "(" || arr[i] == ')') { indexArray.push(i); bracketType.push(arr[i]); } } return { indexArray: indexArray, bracket...
[ "constructBracketMap() {\n this._bracketMap = {};\n const brackets = [\"{\", \"}\", \"[\", \"]\"];\n for (let i = 0; i < this._code.length; i++) {\n if (brackets.indexOf(this._code[i]) !== -1) {\n let j = getMatchingBracket(i, this._code);\n this._bracke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function determines what to display when someone hits the root of the server
function displayRoot(url, req, res) { var myHTML = "<html>"; myHTML += "<body><h1>Home Page</h1>"; myHTML += "<p>This is my frikkin home page. Welcome.</p>"; myHTML += "<a href='/portfolio'>Portfolio</a><br>"; myHTML += "<a href='/funstuff'>Fun Stuff</a>"; myHTML += "</body></html>"; res.writeHead(200, { "Conten...
[ "function showRoot() {\n var root = DriveApp.getRootFolder();\n Browser.msgBox(root.getName());\n}", "get isRoot() {\n return this.name === '/';\n }", "function isSiteRootSane() {\n\tvar siteRoot = dw.getSiteRoot();\n\tvar folderSane = true;\n\n\t//Is site root defined?\n\tif (siteRoot != \"file:///\") {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Outputs the sequence to JSON file or stdout, optionally formatting it
function outputSequence(sequence, options) { const { output, format } = options; // write the sequence ot the output file if (output) { const outputPath = path.resolve(output); debug(`Writing sequence to file ${outputPath}`); try { let jsonStr; if (format) { jsonStr = JSON.stringi...
[ "setTheJsonOutputFile() {\n const frameworkName = `${process.env.npm_package_name}@${process.env.npm_package_version}`;\n this.outputFormat = ` --format json:${this.outputDirectory}json/${frameworkName}_report_pid_${process.pid}.json`;\n }", "function output(\n value: any,\n argv: any = {},\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For each URL, loop through all of the files doing the find and replace. We can't do all of the find URL's at once without the risk of overwriting changes from the previous findandreplace.
async function findAndReplaceAll(directory, urlList){ const fileList = getFileList(directory) for (let urlMap of urlList){ let processes = [] for (let fileName of fileList){ let process = findAndReplace(fileName, urlMap) processes.push(process) } await Promise.all(processes) } }
[ "function updateFileLinks($group) {\n\tvar remove = !config.linkFiles || config.linkFilesTemplate.length == 0;\n\t$group.find(\"li[data-detect-files]\").each(function(){\n\t\tcreateFileLinks($(this), $(this).find(\".t_string\"), remove);\n\t});\n}", "revReplace() {\n if (this.css.length > 0) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds each marker/brewery location, adds each brewery to map, and sets of brewery details to InfoWindows
function buildBreweries(brewery) { for (var i = 0; i < brewery.length; i++) { brewery[i].current = new google.maps.Marker({ position: new google.maps.LatLng(brewery[i].lat, brewery[i].lng), animation: google.maps.Animation.DROP, map: map, name: brewery[i].name, });...
[ "function passToMap() {\n let startBar = [STORE.brewList[0].longitude, STORE.brewList[0].latitude];\n let otherBars = [];\n STORE.brewList.forEach((bar) => {\n otherBars.push([bar.longitude, bar.latitude, bar.name]);\n });\n removeMarkers();\n recenter(startBar);\n addMarker(otherBars);\n}", "function s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets version of Go based on the output of the command `go version`. Returns null if go is being used from source/tip in which case `go version` will not return release tag like go1.6.3
function getGoVersion() { var goRuntimePath = goPath_1.getGoRuntimePath(); if (!goRuntimePath) { vscode.window.showInformationMessage('Cannot find "go" binary. Update PATH or GOROOT appropriately'); return Promise.resolve(null); } if (goVersion) { return Promise.resolve(goVersion...
[ "function getVersion(page) {\r\n\tif (dbug) console.log(\"wwvf-cs::Getting Version.\");\r\n\tvar rv = null;\r\n\tif (page) {\r\n\t\tvar xVer = /v((\\d+)\\.(\\d+)(?:\\.(\\d+(-?[a-z]\\d+)?))?)(-development|release)?/i;\r\n\t\tif (page != \"\" && page.match(/Web Experience Toolkit/i)) {\r\n\t\t\t/*var vNumRe = /\\* (....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define function to generate table for selected segment
function genTableBySeg() { var selectedItem = pie_chart.getSelection()[0]; if (selectedItem) { // Get segment name var segname = data.getValue(selectedItem.row, 0); if(segname == "Low"){ ...
[ "function generateTable() {\n emptyTable();\n generateRows();\n generateHead();\n generateColumns();\n borderWidth();\n}", "function createLineTable(action,lineId){\n\tvar dv = lineId.split(\"||\");\n\tvar dev1 = dv[0].split(\".\");\n\tvar dev2 = dv[1].split(\".\");\n\tvar deviceDestination = dev1[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output the standard node.js exception, and also the tame exception stack (if such a thing exists).
function exceptionHandler (err) { console.log (err.stack); var stack = stackWalk (); if (stack.length) { console.log ("Tame 'stack' trace:"); console.log (stack.join ("\n")); } }
[ "function show(exn) /* (exn : exception) -> string */ {\n return stack_trace(exn);\n}", "function stackTrace(fn) {\r\n if (!fn) fn = arguments.caller.callee;\r\n var list = [];\r\n while (fn && list.length < 10) {\r\n list.push(fn);\r\n fn = fn.caller;\r\n }\r\n list = list.map(function(fn) {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a template HTML table element, will: On a first call for that template, create a new table from it adding: a header from a template header in the template table and rows from a template row in the template table and place the table in a provided element. On subsequent calls for that template will use the table al...
function RenderTable(template, entries, placein, entry_number, session) { // The Number of players in a team is a special case quite distinct // from the number of teams or number of players in a game. Primarily // because it lives in particular row of the parent table there being // a number of players...
[ "function createTab(battingTeam, bowlingTeam) {\n // Batting info table\n let tabContent = `\n <table class=\"table\" border=\"1\">\n <tr class=\"table-secondary\">\n <th>Batter</th>\n <th>R</th>\n <th>B</th>\n <th>4/6</th>\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the hour/minute/second hands according to the current time
function updateTime() { const datetime = tizen.time.getCurrentDateTime(); const hour = datetime.getHours(); const minute = datetime.getMinutes(); const second = datetime.getSeconds(); const separator = second % 2 === 0 ? ":" : " "; $("#time-text").html(padStart(hour.toS...
[ "function updateTime() {\n let now = new Date();\n let hour = now.getHours();\n let mins = now.getMinutes();\n let sec = now.getSeconds();\n \n syncAnalogClock(hour, mins, sec);\n syncDigitalClock24Hours(hour, mins, sec);\n syncDigitalClock12Hours(hour, mins, sec);\n}", "updateCurrentTime ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save a map as htpasswd file
function save (map, file) { // get the users as an array var users = Object.keys(map || {}); // return if the map was empty or null if (users.length === 0) { return; } var lines = []; // for every user users.forEach(function (user) { var hash = map[user]; // generate the : separated line ...
[ "save() {\n this.init_();\n this.mergeFromMap_();\n Settings.getInstance().set(['map', 'z-order'], this.groups_);\n }", "function passwordManagerSave(aUsername, aPassword) {\n cal.auth.passwordManagerSave(aUsername, aPassword, aUsername, \"Google Calendar\");\n}", "function saveState(){\n writeT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepends a task name with the parent directory for uniqueness.
function _taskName( taskName ){ return directoryName + ':' + taskName; }
[ "static concat(parentPath, name) {\n if (parentPath === '/') {\n return `/${name}`;\n }\n\n return `${parentPath}/${name}`;\n }", "mkParentPath(dir, cb) {\n var segs = dir.split(/[\\\\\\/]/);\n segs.pop();\n if (!segs.length) {\n return cb && cb();\n }\n dir = segs.j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add click function and display music lightbox and slides when album is clicked
function displayMusicLightbox(e) { $(e).click((event)=>{ let albumIndex = $(event.target).attr('data-index'); let index = parseInt(albumIndex, 10); let musicSlides = $('.music-slides'); $('#lightbox-m').show(); musicSlides.eq(index).show(); }); }
[ "function displayMusic(data) {\r\n let musicHTML = '';\r\n $.each( data.albums.items, (i, item)=>{\r\n musicHTML += '<div class=\"column\">';\r\n musicHTML += '<img data-index=\"' + i + '\" src=\"' + item.images[1].url + '\" class=\"hover-shadow music-thumb\">';\r\n musicHTML += '</div>';\r\n });\r\n $...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function provides a template for the PUSH operation for the following memory sections: local, argument, this, that, temp. The process flow is as follows: A = memorySegment+memoryAddress point the address register to the memory segment plus the address offset SP = M push to the stack the contents of the memory regi...
function generateGeneralPUSH(memorySegment, memoryAddress) { memorySegment = getMemoryPointer(memorySegment); return ` @${memoryAddress} D=A ${memorySegment} A=D+A D=M @SP A=M M=D @SP M=M+1 `; }
[ "stackPush(byte) {\n this.writeRam({ address: 0x0100 + this.cpu.sp, value: byte });\n this.decrementRegister('sp');\n }", "function generateConstantPUSH(memoryAddress) {\n return `\n@${memoryAddress}\nD=A\n@SP\nA=M\nM=D\n@SP\nM=M+1\n`;\n}", "push(element) {\r\n //this.stack.push(element);\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Limit a point to not visually go "through" the planet if its too close to the gravity well. Returns a point that at maximum is at the center of the planet. origin: The point without gravity affecting it. affected: The point with gravity effects. planet: The planet with the most gravitational impact on the point.
function limitGravityLine(origin, affected, planet) { let result = { x: affected.x, y: affected.y }; if (origin.x < planet.x && affected.x > planet.x) { result.x = planet.x; } if (origin.x > planet.x && affected.x < planet.x) { result.x = planet.x; } if (origin.y < planet.y && a...
[ "function getGravityStrenghtForPoint(point, planet) {\n let dist = distancePoints(point, planet) - (planet.size / 2);\n return getGravity(dist, planet.gravMaxDist, planet.gravity);\n}", "function applyMinimapGravity(pointWorld, pointVisual, planets, w, h, scale, cameraPos) {\n let visual = { x: pointVisu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IMGUI_API const ImFontGlyphFindGlyph(ImWchar c) const;
FindGlyph(c) { const glyph = this.native.FindGlyph(c); return glyph && new ImFontGlyph(glyph); }
[ "get Glyphs() {\r\n const glyphs = new ImVector();\r\n this.native.IterateGlyphs((glyph) => {\r\n glyphs.push(new ImFontGlyph(glyph)); // TODO: wrap native\r\n });\r\n return glyphs;\r\n }", "function GetFont() {\r\n return new ImFont(bind.G...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AVERAGE computes sum of items divided by number of items
function AVERAGE() { // compute sum all of the items. var sum = SUM.apply(undefined, arguments); // return sum when computed error. if (ISERROR(sum)) { return sum; } // return sum divided by item count return sum / arguments.length; }
[ "function avg(v){\n s = 0.0;\n for(var i=0; i<v.length; i++)\n s += v[i];\n return s/v.length;\n}", "function average(){\n\t\t\tvar sum = 0;\n\t\t\tlist.forEach(function(item){\n\t\t\t\tsum += item.age;\n\t\t\t});\n\n\t\t\treturn sum / list.length;\n\t\t}", "function avgValue(array)\n{\n\tvar sum = 0;\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a progress meter as two nested DIVs, including a rollover tip for actual numbers
function progressMeter(numberDone, totalNumber) { if (totalNumber == 0) return "-"; var pct = Math.round((100.0 * numberDone) / totalNumber); var sb = ""; sb = sb + "<div id='progressMeter' style='border: 1px solid black; width:200px; height:20px; margin-top: 5px;' title='" + Number(numberDone).toLocaleString() +...
[ "function renderProgressBars() {\n $('.message-progress').each(function() {\n $(this).circleProgress({\n animation: false,\n value: $(this).parent().data('time-left') / 600,\n size: 24,\n fill: {\n gradient: [\"#ff9d0e\", \"#ffc46e\"]\n },\n thickness: 2,\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot the displacement against time Calculation of the responses r and theta
function plot_resp() { /** Response of DoF r **/ for (i = 0; i < n; i++) { t[i] = i*dt; r[i] = A1 * Math.cos(omega1 * t[i]) * s11 + A2 * Math.cos(omega2 * t[i]) * s21; r1[i] = -omega1 * A1 * Math.sin(omega1 * t[i]) * s11 - omega2 * A2 * Math.sin(omega2 * t[i]) * s21; r2[i] = -Mat...
[ "function draw_trajectories() {\n\tcancelAnimationFrame(animation_enabled);\n\tblue = 0x4A56FF;\n\tred = 0xFC5656;\n\n\tfor(var i = 0; i < waterpolarity_particles.length; i++) {\n\t\tcharge = waterpolarity_particles[i].charge;\n\t\tmarker_color = (charge == -1.0) ? blue : red;\n\t\tpositions = waterpolarity_positi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Task a: declare a variable called votingAge, console log true if age > 18 (no function required)
function votingAge(age) { if (age > 18) { return true; } return false; }
[ "function isPersonOldEnoughToVote(person) {\n\n if(person.age >= 18){\n return true;\n } else{\n return false;\n }\n}", "function ageChecker(age){\n if (age >= 13 && age <= 19) {\n return \"You are a teenager!\";\n } else if (age < 13) {\n return \"You are a kid\";\n } else {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lis le fichier .xlsx, et add une ligne dans participants.csv pour chaque participant
static convertXlsxToCsv(){ convert.convert(pathXlsxParticipants).then(result => { var index = 2; while(result[index.toString()]!=undefined){ var numeroDossard = result[index.toString()][0]; var nom = result[index.toString()][1]; var prenom ...
[ "static createCsv() {\n //Check if start.csv exist, if not create it\n try {\n fs.statSync(pathCsvStart);\n } catch (error) {\n if(error.code === 'ENOENT') {\n ExcelServices.addStartTime('dossard', 'time');\n }\n }\n //Check if start...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function can be used to getting mandatory cover premium
function getMandatoryCoverPremium(coverCode, premium) { var coverPremium = RatingConstants.RATE_NA; var coverDetails = getCoverPremiumDetails(coverCode, premium); if (angular.isDefined(coverDetails) && !angular.equals({}, coverDetails)) { coverPremium = coverDetails.premium; ...
[ "function getCoverPremiumDetails(coverCode, premium) {\n\t\t\t\t\t\treturn premium.coverDetails[coverCode];\n\t\t\t\t\t}", "function getAdditionalCoverPremium(coverCode, premium) {\n\t\t\t\t\t\tvar coverPremium = RatingConstants.RATE_NA;\n\t\t\t\t\t\tvar coverDetails = isCoverSelected(coverCode);\n\t\t\t\t\t\tif ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the rest endpoint, get all pages and concatenate the elements into a single array
getPagesAsArray(URL) { const fullURL = `${BASE_REST_URL}${URL}${URL.contains('?') ? '' : '?'}`; let allElements = []; return fetch(fullURL, this.eloquaOptions) .then(res => res.json()) .then(({ total, pageSize, elements }) => { allElements = elements; ...
[ "async function getPages() {\n const url = '/api/pages';\n const response = await fetch(url);\n const pageFiles = await response.json();\n\n console.log(\"HUB: Page files have been recieved\");\n generateFileList(\"pagesList\", \"delPagesList\", pageFiles);\n}", "getAll(req, res, next) {\n\n var\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It randomly deploys a fleet on a board. Parameters: a 10x10 board (own_ or enemy_board) and a Ship object array (own_ or enemy_fleet).
function random_fleet_deployment(board, fleet){ var flag = false; //Flag to report the successful deployment of each ship and the entire fleet. do{ //General loop to repeat the fleet build, when there's no more room left on the board. for(let i = 0; i < 10; i++) //In each loop a reboot ...
[ "function own_board_random_deployment(){\r\n \r\n click_sound.play();\r\n \r\n random_fleet_deployment(own_board, own_fleet); //It calls the random fleet distribution function.\r\n\r\n for(let i = 0; i < 15; i++){ //Loop that puts all distributed ships in place.\r\n\r\n if(i < 10){ //For all s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create room and populate with furniture.
function makeRoom(){ var newRoom = new Room(size()); newRoom.populate(); for (var j=0; j<newRoom.contents.length; j++){ var furn = newRoom.contents[j]; furn.populate(); }; return newRoom; }
[ "function createRoom(){\n\t\t\tconsole.log(\"creating room\");\n\t\t\t$scope.rooms.$add({\n\t\t\t\tplayer1: userId,\n\t\t\t\tplayer2: 0,\n\t\t\t\tproblemCode: null,\n\t\t\t\tready1: false,\n\t\t\t\tready2: false,\n\t\t\t\tlang1: \"not set\",\n\t\t\t\tlang2: \"not set\", \n\t\t\t\ttime: 5,\n\t\t\t\tstatus: 0,\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
insert statements /insertStatement1 > insert into identifier selectStatement
function insertStatement1( machine ) { query = machine.popToken(); tablename = machine.popToken(); machine.checkToken("into"); machine.checkToken("insert"); machine.pushToken( new insertStatement(tablename.identifier, query) ); }
[ "visitInsert_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "addStatements(...statement) {\n this.document.addStatements(...statement);\n }", "function selectStatement4( machine )\n {\n order = machine.popToken();\n machine.checkToken(\"by\");\n machine.checkToken(\"o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
end resumeEditing resetAction The resetAction function just resets the status message to the default action of "Check Spelling".
function resetAction() { with(currObj); if(currObj.config['useIcons']) { currObj.actionSpan.innerHTML = "<a class=\"check_spelling\" onclick=\"setCurrentObject(" + currObj.config['varName'] + "); " + currObj.config['varName'] + ".spellCheck();\"><img src=\"" + currObj.config['imagePath'] + "images/spellcheck....
[ "function resetSpellChecker()\r\n{\r\n\twith(currObj);\r\n\tcurrObj.resetAction();\r\n\t\r\n\tcurrObj.objToCheck.value = \"\";\r\n\tcurrObj.objToCheck.style.display = \"block\";\r\n\tcurrObj.objToCheck.disabled = false;\r\n\t\r\n\tif(currObj.spellingResultsDiv)\r\n\t{\r\n\t\tcurrObj.spellingResultsDiv.parentNode.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this is the model for accessing mongo
function MongoModel() { return { // every request is wrapped in this, so we will create the //connection if we need it doIt : function (callback){ // if the connection isn't defined, we need to create it if (db === null) { var uri = 'mongodb://' ...
[ "function mongodbdata() {\n\t\n\tthis.getConnectionString = function (){\n\t\tvar result = \"127.0.0.1:27017/wardleymaps\";\n\t\t\n\t\t// if OPENSHIFT env variables are present, use the available connection info:\n\t\tif(process.env.OPENSHIFT_MONGODB_DB_PASSWORD){\n\t\t result = process.env.OPENSHIFT_MONGODB_DB_US...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find any ODK XML forms starting at the given file system root
function findForms(root, cb) { // XXX: *.xml is an assumption var xmlGlob = path.join(root, '**', '*.xml'); glob(xmlGlob, function (globErr, files) { if (globErr) { logger.error({err: globErr}, 'error globbing "%s"', xmlGlob); return cb(null, []); } async.map(files, function (file, cbMa...
[ "function cXparse(src) {\n var frag = new _frag();\n\n // remove bad \\r characters and the prolog\n frag.str = _prolog(src);\n\n // create a root element to contain the document\n var root = new _element();\n root.name = \"ROOT\";\n\n // main recursive function to process the xml\n frag = _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append font awesome and swift styles
function appendStyles() { let head = document.head, fontAwesome = document.createElement('link'), css = '#swift { max-width: 95%; margin: .5rem 1rem 1rem; background: linear-gradient(0.35turn, #23bcdd, #32ca60); box-shadow: inset 0 .25rem 1rem rgba(0, 0, 0, 0.1); border-radius: 1rem; fon...
[ "function setupFontAwesome() {\r\n\tvar fa = document.createElement('style');\r\n\tfa.type = 'text/css';\r\n\tfa.textContent = '@font-face { font-family: FontAwesome; src: url(\"'\r\n\t\t\t+ chrome.extension.getURL('fa/fonts/fontawesome-webfont.woff?v=4.6.3')\r\n\t\t\t+ '\"); }';\r\n\tdocument.head.appendChild(fa);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to be called when a Student signs up and logs value into the DB PARAMETERS firstName : string First name of student lastName : string Last name of student email : string Student's email check that it ends with ucla.edu sid : string Student UCLA ID 9 digits, number only year : Int Current year at UCLA 1 freshma...
async function signUpStudent(firstName, lastName, email, password, sid, year, gradTerm, major, minor, club, honorStudent, resume, profileImage) { try { // connect to database await client.connect() .catch(error => handleError(error)); console.log("Succesfully connected to DB...") const database = client.db...
[ "async function signUpRecruiter(firstName, lastName, companyName, email, password, profileImage) {\n\ttry {\n\t\t// connect to database\n\t\tawait client.connect()\n\t\t\t.catch(error => handleError(error));\n\t\tconsole.log(\"Succesfully connected to DB...\")\n\n\t\tconst database = client.db(\"test\");\n\t\tconst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }