query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
gzip(data[, options]) > Uint8Array|Array|String data (Uint8Array|Array|String): input data to compress. options (Object): zlib deflate options. The same as [[deflate]], but create gzip wrapper instead of deflate one.
function gzip$1(input, options) { options = options || {}; options.gzip = true; return deflate$3(input, options); }
[ "function gzip(input,options){options=options||{};options.gzip=true;return deflate$1(input,options);}", "function gzip(input,options){options=options||{};options.gzip=true;return deflate(input,options)}", "function gzip(input,options){options = options || {};options.gzip = true;return deflate(input,options);}",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
global Map,Set,Symbol Based on we can sniff out incomplete Map/Set implementations which would otherwise cause our tests to fail. Notably they fail in IE11 and iOS 8.4, which this prevents.
function supportsMapAndSet$1() { if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') { return false; } var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species); return prop && 'get' in prop && Map[Symbol.species] === Map; }
[ "function supportsMapAndSet() {\n\t if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {\n\t return false;\n\t }\n\t var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);\n\t return prop && 'get' in prop && Map[Symbol.species] === Map;\n\t}", "function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tessellate bezier curve adaptively, within given tolerance of error
tessellateAdaptive(tolerance = common_1.EPSILON) { return new common_1.NDArray(BezierCurve.tessBezier(this, tolerance)); }
[ "function FitCubic(d, first, last, tHat1, tHat2, error, DrawBezierCurve)\n // Vector2 *d; /* Array of digitized points */\n // int first, last; /* Indices of first and last pts in region */\n // Vector2 tHat1, tHat2; /* Unit tangent vectors at endpoints */\n // double error; ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================== CREATE GRID FUNCTION ============================================== hexSize = Hexagon Size (px) fill = SVG Attribute to color the hexagon strokeSize = Border width of the hexagon xGrid = number of hexagons to the X axe yGrid = number of hexagons to the Y axe
function createGrid(hexSize, fill, strokeSize, strokeColor, xGrid, yGrid) { // VARIABLE(S) let xmlns = 'http://www.w3.org/2000/svg'; // CREATE SVG let svgElement = document.createElementNS(xmlns, 'svg'); svgElement.setAttribute('width', ( hexSize + strokeSize ) * ( xGrid - 1 ) + 'px' ); svgEle...
[ "_createGrid(size) {\n this.size = size;\n this.rowCount = getRowCount(size);\n const cellOffsetY = 3 / 4 * cellHeight;\n const cellOffsetX = Math.sqrt(3) / 2 * edgeLength;\n const cellWidth = cellOffsetX * 2;\n const padding = 35;\n\n const edgeTransitionMode = this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Should work as well with the types restricted to usable userSim ( we avoid copy past ) type UserSim_= UserSim.Usable; type Evts_ = UserSim.Usable.Evts; type EvtsForSpecificSim_ = UserSim.Usable.Evts.ForSpecificSim;
function buildEvtsForSpecificSimFactory(params) { var createNewInstance = params.createNewInstance; return function buildForSpecificSim(userSimEvts, userSim, keys) { var out = (function () { var out = createNewInstance(); if (keys === undefined) { return out; ...
[ "function Fet_vs_parms_type(type_sign) {\n //alert('in device with type ' + type_sign);\n this.T=27; // Temperature in degrees C\n this.Wscale=1.0; // Scales all the devices\n this.Lg = 30e-7; // Gate length [cm]\n this.dLg= 9e-7; // dLg=L_g-L_c (default 0.3xLg_nom)\n this.C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw a tank on position. We use other draw function because every thing is part of a tank.
drawTank(tank) { const { x, y, size, color, health, maxHealth, level } = tank; // Draw the life and exp bar. this.drawLife(x, y, size, health, maxHealth, level); // Draw canon and bullet of the tank. tank.gun.forEach(canon => { for (let i = 0; i < canon.ammos.length; ...
[ "function drawTank() {\n\ttank.style.opacity = \"100\";\n\ttank.style.left = turret.left + \"px\";\n\ttank.style.top = turret.top + \"px\";\n}", "tanksDraw(tanks) {\n var translateX = -(this.perspective.x - global.screenWidth / 2);\n var translateY = -(this.perspective.y - global.screenHeight / 2);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sliders have bars, progress bars, and an onslide function
constructor(barId, progressId, onSlide, sliderRadius, slideDelay) { //state vars this.barId = barId this.progressId = progressId this.onSlide = onSlide this.sliding = false this.sliderRadius = sliderRadius this.lastSlide = -1000 this.mouseOver = false ...
[ "function updateSlider(){\n\t\tslider.slider(\"value\", mainTimeline.progress() *100);\n\t}", "function dragSlider(values) {\n setProgress(parseInt(values[0]))\n }", "function Slider(prefix,dir,dim,progress,add_px)\n\t{\n\t//get block and asign it with events\n\tthis.scroll_left_button = document.getE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generateJavascript is the highest level function in ScreenToScript. All operations, other than including modules and checking command line arguments, happen with it. It reads the JSON file, interprets them to Puppeteer, where necessary, or just Javascript, and outputs the resulting string.
async function generateJavascript() { //read the Kantu commands into a JSON object from the given json file fs.readFile(fileToParse, 'utf8', function (err, data) { if (err) return console.log(err); //trim and parse to json data = data.trim(); events = JSON.parse(data); ...
[ "function buildJavascript() {\n return buildGenerator('javascript', 'JavaScript');\n}", "_writingGenerateArchetypeUsingJavaScript () {\n trace('Loading maven archetype generate module');\n const mvn = require('generator-alfresco-common').maven_archetype_generate(this);\n trace('Creating context for arch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This routine calculates the next arrival based on the first train of the day and the duration.
function calculateNextArrival(trainSeq) { // Derive the first train time and current date var currentDate = moment().format("YYYY-MM-DD"); var firstTraintoday = currentDate + "T" + trainArrayObj[trainSeq].tfirsttrain + ":00"; var input_date = new Date(firstTraintoday).getTime(); var curr_date = new Dat...
[ "function nextDeparture(nextTrain, frequency) {\n var time = new Date();\n var currentHour = time.getHours();\n var currentMinutes = time.getMinutes();\n var timeSplit = nextTrain.toString().split(\":\");\n var currentTime = (currentHour * 60) + currentMinutes;\n \n //Check to see if the train ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert exclude ranges to include ranges Example: ^by, ['by'] to ["\0a","z\uffff"]
function negate(ranges /*: [Range rg] */) { const MIN_CHAR = '\u0000'; // work around UglifyJS's bug // it will convert unicode escape to raw char // that will cause error in IE // because IE recognize "\uFFFF" in source code as "\uFFFD" const MAX_CHAR = String.fromCharCode(0xffff); ranges = classify(ran...
[ "function invertedRanges(ranges) {\n \n}", "function invert (range) {\r\n var output = [],\r\n lastEnd = -1,\r\n start;\r\n XRegExp.forEach(range, /\\\\u(\\w{4})(?:-\\\\u(\\w{4}))?/, function (m) {\r\n start = dec(m[1]);\r\n if (start > (lastEnd + 1)) {\r\n output.pus...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::Kendra::DataSource.DocumentsMetadataConfiguration` resource
function cfnDataSourceDocumentsMetadataConfigurationPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnDataSource_DocumentsMetadataConfigurationPropertyValidator(properties).assertSuccess(); return { S3Prefix: cdk.stringToCloudFormation(prop...
[ "properties() {\n return this.display.show(\n this._section(\n Text(`Properties accessible from ${this.getSignature()}`),\n this._renderProperties(2, this.metadata.allProperties())\n )\n );\n }", "function cfnIndexDocumentMetadataConfigurationPropertyToCloudFormation(properties) {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize arguments by expanding merged flags into multiple flags. This allows you to have `wl` be the same as `watch lint`.
function normalizeArguments(args) { args = args.slice(); const result = []; for (const arg of Array.from(args)) { let match; if ((match = arg.match(MULTI_FLAG))) { for (const l of Array.from(match[1].split(''))) { result.push(`-${l}`); } } else { result.push(arg); } } return result...
[ "normalizeArgs(args) {\n if (this._optional_args.length < 1) {\n return args;\n }\n const norm = [];\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n // Only short form args like '-x' are targets.\n if (!/^[-][^-]/.test(arg)) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
REPORTER CLASSES / ASSERT_Reporter class Role: reporting the assertion failure Instantiator: ASSERT_Tester /c)class
function ASSERT_Reporter(){ /*m)protected void*/this.setClear=function(){ this.stop = false; this.checked = 0; this.failed = 0; this.overall = 0; this.reported = 0; this.failures = []; this.viewer.setClear(); } //---setClear /*m)protected void*/this.setFailure=function( /*ASSERT_Failure*/failure ){ this.setFailed(fail...
[ "function\nASSERT_Abstract_Failure(){\n/*m)private string*/this.setCaller=function(\n/*a)string*/id\t\t\t//)function name and test comment\n){\nreturn Argument.isUndefined(id) ? '(not specified)' : id.substr(0, id.indexOf(':'));\n}\t//---setCaller\n\n/*m)private string*/this.setComment=function(\n/*a)string*/id\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the frequencies above the threshold
freqsAboveThreshold(){ const threshold = this.thresholdFactor * this.maxAmplitude; let ret = []; this.freqs.forEach((amp, f, map) => { if (amp >= threshold){ ret.push(f); } }); return ret; }
[ "function highFreq(map) {\n\treturn Object.keys(map).filter((key) => {\n\t\treturn map[key] > 5;\n\t});\n}", "function thresholdFrequency(lowFreq, highFreq, freqData, threshold) {\n const samples = sampleData(lowFreq, highFreq, freqData);\n let max = Number.MIN_SAFE_INTEGER;\n for (var i = 0; i < samples.lengt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply an image processing operation to a source image and then put the result image in the result canvas
apply() { // Get the source image and create the result image buffer const source = new ImageDataPixelWrapper(this.source.getImageData(0, 0, 400, 300)); const resultImageData = this.result.createImageData(400, 300) const result = new ImageDataPixelWrapper(resultImageData); // Up...
[ "function processImage(context, currentColorMatrix, x, y, w, h) {\n // if (w>0 && return;\n // if (currentImage.width != canvas.width)\n // canvas.width = currentImage.width;\n // if (currentImage.height != canvas.height)\n // canvas.height = currentImage.height;\n\n // context.clearRect(x,y, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End the current phone call, disconnecting Twilio as well
endCall(oldState) { if (this.conn) { if (oldState == PhoneState.Incoming) { this.conn.reject(); } log("Phone state changed to idle. Disconnecting all calls"); Twilio.Device.disconnectAll(); this.conn = null; } }
[ "endCall(oldState) {\n if (phone.conn) {\n if (oldState == PhoneState.Incoming) {\n phone.conn.reject();\n }\n log(\"Phone state changed to idle. Disconnecting all calls\");\n Twilio.Device.disconnectAll();\n phone.conn = null;\n }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Destroys the view, including the view object. Then, reinstantiates it and renders it. Maintains the same scroll state. TODO: maintain any other usermanipulated state.
function reinitView() { ignoreWindowResize++; freezeContentHeight(); var viewType = currentView.type; var scrollState = currentView.queryScroll(); clearView(); renderView(viewType, scrollState); unfreezeContentHeight(); ignoreWindowResize--; }
[ "function reinitView() {\n\t\tignoreWindowResize++;\n\t\tfreezeContentHeight();\n\n\t\tvar viewType = currentView.type;\n\t\tvar scrollState = currentView.queryScroll();\n\t\tclearView();\n\t\trenderView(viewType, scrollState);\n\n\t\tunfreezeContentHeight();\n\t\tignoreWindowResize--;\n\t}", "function reinitView...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ajax request for receiving metric updates
function getUpdates(metricID) { if(!window.timerangeOn) $.ajax({ type: "post", url: "restAPI/metrics/", beforeSend: function(req) { req.setRequestHeader("Accept", "application/json"); }, contentType: "text/plain", data: metricID, success: updateGraph }); }
[ "function sendUpdateRequest() {\n $.get('/updateCharts', function (data) {\n\n var parsed = JSON.parse(data);\n\n for(var i = 0; i < charts.length; i++)\n charts[i].update(parsed);\n\n // TODO: !!!\n // if(parsed[\"TotalThroughput\"] != undefined) {\n // var time...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to get previous balance
function getPreviousBalance(inputId) { const previousBalance = document.getElementById(inputId); const previousBalanceAmount = parseFloat(previousBalance.innerText); return previousBalanceAmount; }
[ "function getPreviousBalance() {\n const previousBalance = document.getElementById(\"balance-total\");\n const previousBalanceText = previousBalance.innerText;\n const balanceTotal = parseFloat(previousBalanceText);\n return balanceTotal;\n}", "getPreviousBalanceFromTransaction({\n transaction,\n curren...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get screen view port. Provides the view port that is needed for some gestures like swipe etc.
getScreenViewPort() { const rect = this.getScreenActualViewPort(); if (rect && this.isIOS && Object.getOwnPropertyNames(rect).length > 0 && this._args.device.deviceScreenDensity) { return { x: rect.x / this._args.device.deviceScreenDensity,...
[ "getScreenActualViewPort() {\n return (this._args.device.viewportRect || this.imageHelper.options.cropRectangle);\n }", "function getViewPort() {\r\n var screen = '';\r\n if(window.innerWidth)\r\n {\r\n if (window.innerWidth > 1440) { screen = \"Extra wide\"; }\r\n else if (window...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
end of inisalisasi / Prosedur pilihGambar. Saat Prosedur ini dijanakan akan mengambil nilai dari pilihanGambar yang berisi path gambar. Gambar dimuat menggunakan static method fromURL() dan menset posisi gambar ke tengah canvas. Gamabr diberi filter brighness untuk menurunkan kecerahannya dan membuat teks menjadi lebih...
function pilihanGambar_multi() { var gambar = $("#pilihanGambar-multi").val(); fabric.Image.fromURL(gambar, function (img) { img.set({ top: 250, left: 250, }); img.filters.push(filter); img.applyFilters(); canvas_multi.setBackgroundImage( img, canvas_multi.renderAll.bi...
[ "function pilihGambar() {\n var gambar = $(\"#pilihanGambar\").val();\n\n fabric.Image.fromURL(gambar, function (img) {\n img.set({\n // Needed to position backgroundImage at 0/,\n originX: \"left\",\n originY: \"top\",\n });\n\n img.filters.push(filter);\n img.applyFilters();\n\n ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a user social account
function removeUserSocialAccount(provider) { UsersService.removeSocialAccount(provider) .then(onRemoveSocialAccountSuccess) .catch(onRemoveSocialAccountError); }
[ "function removeUserSocialAccount(provider) {\n vm.success = vm.error = null;\n\n $http.delete('/api/users/accounts', {\n params: {\n provider: provider\n }\n }).success(function (response) {\n // If successful show success message and clear form\n vm.success = tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new instance of Combokeys Context
function Context(comboKeys) { if (typeof comboKeys === 'undefined') { throw new Error('CombokeysContext: Constructor requires an instance of Combokeys'); } this._bindings = {}; this._context = null; this._comboKeys = comboKeys; this._plugins = { global: [], contexts: {} }; this._activePlugins = []; this...
[ "createContext() {\n return new CbtContext();\n }", "function useComboboxContext() {\n var _React$useContext10 = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useContext\"])(ComboboxContext),\n isExpanded = _React$useContext10.isExpanded,\n comboboxId = _React$useContext10.comboboxId;\n\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Side preview slide animation (hide)
function hideSidePreview(){ $('#ce-side').animate({ opacity: 0 }, 700, function(){ $('#ce-side').hide(); $('#ce-list').animate({ width: '100%' }, 300); }); }
[ "function hideSidePreview(){\n\t$('#ne-side').animate({\n\t\topacity: 0\n\t}, 700, function(){\n\t\t$('#ne-side').hide();\n\t\t$('#ne-list').animate({\n\t\t\twidth: '100%'\n\t\t}, 300);\n\t});\n}", "hidePreview() {}", "function extendSidePreview(){\n\t$('#sbe-list').animate({\n\t\twidth: '30%'\n\t}, 300, functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
"on" and "emit" like interfaces. The real SocketIO has some nice interfaces, but it's very dated and inefficient. It's got too much crufty code. I replace it with this much more flexible and 100 line piece of code. This is not meant to be compatible with the real socketIO. This takes an object and a corresponding send ...
function createSocketIOObject(sendFunc, warnFunc=null) { // Funcs is the list of "On" callback functions with their // corresponding scope. var funcs = {}; var obj = {}; if(warnFunc) var warn = warnFunc; else var warn = console.log; // Like: socketIO.on('name', function(a...
[ "function createSocketIoMiddleware(socket) {\n\t var option = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];\n\n\t var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];\n\n\t var _ref$eventName = _ref.eventName;\n\t var eventName = _ref$eventName === undef...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that returns the index of the smallest element in an array
function minIndex(arr){ var minimum = arr[0]; var index; for(var i = 1; i < arr.length; i++){ if(arr[i] < minimum){ minimum = arr[i]; index = i }; }; return index; }
[ "function indexOfSmallest(arr){\n let min = 0;\n let len = arr.length;\n\n for (let i = 1; i < len; i++){\n if (arr[i] < arr[min]){\n min = i;\n }\n }\n return min;\n\n}", "function indexOfSmallest(array) {\n if (array.length <= 1) {\n return 0;\n } else {\n var tmpIndex = indexOfSmallest(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the values of Slate's required environment variables
function getSlateEnv() { const env = {}; SLATE_ENV_VARS.forEach(key => { env[key] = process.env[key]; }); return env; }
[ "function getSlateEnv() {\n const env = {};\n\n SLATE_ENV_VARS.forEach((key) => {\n env[key] = process.env[key];\n });\n\n return env;\n}", "function requireEnvironmentVariables() {\n var environmentVariables = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n environmentVariables[_i] = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load userData from DB to fields on page
function loadUserData() { let url = getContextPath() +'/userInfo' $.get({ url: url }).done(function (list) { let json = list[1] let id = json['id'] if (id != null) { document.getElementById("id").value = id; } let name = json['name'] if (na...
[ "function loadUserData(data) {\n\t//fill global user variable\n\tuser = data;\n\t\n\t//display name in header\n\t$(\"#name\").text(data.FirstName + ' ' + data.LastName + ' ⌄');\n}", "function loadData() {\n\n //Users name.\n loadName()\n\n //Users config.\n loadConfig()\n}", "function load_userObj(d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'NORTH' and 'SOUTH' are opposite directions, as are 'EAST' and 'WEST'. Going in one directiosn and coming back in the opposite direction leads to going nowhere. Someone else also has these directiosn to the treasure and you need to get there first. Since the directions are long, you decide to write a program to figure ...
function directionReduction(directions) { for (let i = 0; i < directions.length; i += 1) { if ( (directions[i] === "NORTH" && directions[i + 1] === "SOUTH") || (directions[i] === "SOUTH" && directions[i + 1] === "NORTH") || (directions[i] === "EAST" && directions[i + 1] === "WEST") || (dir...
[ "function simplifyDirections(directionsArray) {\n\n\tvar counts = {\n\t\tnorth: 0,\n\t\tsouth: 0,\n\t\teast: 0,\n\t\twest: 0\n\t};\n\n\tvar simpleDirections = [];\n\n\tdirectionsArray.forEach(direction => {\n\t\tswitch (direction) {\n\t\t\tcase 'North':\n\t\t\t\tcounts.north++;\n\t\t\t\tbreak;\n\t\t\tcase 'South':\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
undoable item does the bulk of the "create object from polygon selection" command work
function UndoableItem(collElem, meshElem) { var clonedColl = collElem.clone(); this._polyCollection = clonedColl.behavior; this._sourceMeshElem = meshElem; this._sourceMesh = meshElem.behavior; this._createdMeshElem = null; this._createdNode = null; var owningSceneNode = this._sourceMeshE...
[ "function UndoableItem(collElem, meshElem) {\r\n\r\n var clonedColl = collElem.clone();\r\n\r\n this._polyCollection = clonedColl.behavior;\r\n this._sourceMeshElem = meshElem;\r\n this._sourceMesh = meshElem.behavior;\r\n this._createdMeshElem = null;\r\n this._createdNode = null;\r\n\r\n var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a new tr dom to show casa information.
function newCasaTr(id, code, name) { return $( '<tr>' + '<td>' + code + '</td>' + '<td>' + name + '</td>' + '<td><button db_id="' + id + '" type="button" class="select_casa_btn btn btn-info btn-xs">Select</button>' + '</td>' + '</tr>' ...
[ "function buildTr(patient) {\r\n /*\r\n \"createElement\" is a method wich creates elements into DOM\r\n new <tr> receives patient class\r\n function \"buildTd\" creates each <td>, receiving the element's value and the class name\r\n */\r\n var patientTr = document.createElement(\"tr\");\r\n pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
query formatted: "(brand1, brand2, brand3, ...) + query"
function getFormattedQuery(brands, query) { let formatted = ''; if(Array.isArray(brands)) { formatted += '('; brands.forEach((brand, index) => { if(index === 0) formatted += brand; else formatted += ',' + brand; }); formatted += ')'; } else { formatted = brands; } ...
[ "function oredSearchQueries (queryTerms, key, equals) {\n\tvar query = '(' + key + equals + queryTerms.join(' or ' + key + equals) + ')';\n\t\n\treturn query;\n}", "formatQuery (query) {\n return query.split(',').join(' + ');\n }", "function buildQueryUrl(list) {\n var queryString = \"?\";\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the suit of a card given its floating point value
function check_suit(value){ var val = (value - Math.floor(value)) / 0.1; if(val - Math.floor(val) > 0.5) return Math.floor(val) + 1; else return Math.floor((value - Math.floor(value)) / 0.1); }
[ "function getCardSuitValue (card) {\n\tvar suit = card.substring(0, 5);\n\t\n\tif (suit == SPADES) {\n\t\treturn 0;\n\t} else if (suit == HEARTS) {\n\t\treturn 1;\n\t} else if (suit == CLUBS) {\n\t\treturn 2;\n\t} else if (suit == DIAMONDS) {\n\t\treturn 3;\n\t} else {\n\t\treturn 4;\n\t}\n}", "function faceValue...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
addFrameStyle Contains settings for varous frame types PARAMETERS: imageView: image identifier style: style of the frame to apply: "default" RETURNS: assigns global variables: titleBarHeight
function addFrameStyle(imageView, style) { switch(style) { default: //default frame style //thin white line around image addFrame(imageView, 0.5, 0.5, allDimensions.framedImageWidth, allDimensions.framedImageHeight, "white"); //black frame offset to...
[ "dropDownAdjustFrame(style) {\n console.log(`frameStyle={width:${style.width}, \n height:${style.height}, top:${style.top}, left:${style.left}}`);\n style.left -= 9;\n style.top += 7;\n style.height -= 70;\n return style;\n }", "_updateStyle(style = {}) {\n let prop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the favorite folders mode.
async function subtest_toggle_favorite_folders(show) { let mode = "favorite"; select_mode_in_menu(mode); if (show) { await assert_mode_selected(mode); // Mode is hierarchical, parent folders are shown. assert_folder_visible(inboxFolder.server.rootFolder); assert_folder_visible(inboxFolder); ...
[ "setFsFavoritesFolder() {\n userPreferences.safeGetItem('filesource').then((obj) => {\n if (obj === 'server') {\n userPreferences.setItem('favoriteFolder', this.favorites);\n }\n });\n }", "function checkFavorites() {\n var itemIds = [];\n\n // Only perform ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Only returns properties that are different but still exist in both objects. Uses obj2's value.
function compareObjectReturnDifferencesFromSecondObject(obj1, obj2) { const differences = {}; for (const [key2, value2] of Object.entries(obj2)) { if (obj1[key2] !== undefined && obj1[key2] !== value2) { differences[key2] = value2; } } return differences; }
[ "function getObjectDiff(obj1, obj2) {\n const diff = Object.keys(obj1).reduce((result, key) => {\n if (!obj2.hasOwnProperty(key)) {\n result.push(key);\n } else if (isEqual(obj1[key], obj2[key])) {\n const resultKeyIndex = result.indexOf(key);\n result.splice(result...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove from map all params with names which are absent in namesOfParamsToFilter
function filterParams(map, namesOfParamsToFilter) { var filteredMap = clone(map); for (var paramName in map) { if (namesOfParamsToFilter.indexOf(paramName) == -1) { delete filteredMap[paramName]; } } return filteredMap; }
[ "function removeParams(map, namesOfParamsToRemove) {\n for (var i in namesOfParamsToRemove) {\n delete map[namesOfParamsToRemove[i]];\n }\n\n return map;\n }", "function removeParamsWithNullValues(map) {\n for (var i in map) {\n if (map[i] == null) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows a confirmation dialog box to confirm the user wants to remove an item from their basket
function confirmRemoveOrderMenuItem(itemId) { bootbox.confirm("Are you sure you want to remove this item?", function (result) { if (result) { removeOrderMenuItem(itemId); } }); }
[ "function removeFromCart(e){\n if (confirm(\"Remove item from Cart?\")) {\n return true;\n } \n else {\n e.preventDefault();\n return false;\n }\n}", "function cart_dialog_delete_item (cart_item_id)\n{\n cart_object.cart_dialog_delete_item (cart_item_id);\n}", "function confir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getTitle() This function returns the user's title. To do so, concatenate the last three letters of their real last name, reversed, and the model of their dream car.
function getTitle() { return lastName.charAt(1) + lastName.charAt(2) + lastName.charAt(3) + favoriteColor; }
[ "function getTitle() {\r\n\r\n dreamCar = readline.question(\"Dream Car : \");\r\n\r\n let reversed = reverseString(lastName.substring(lastName.length - 3, lastName.length));\r\n\r\n return reversed.charAt(0).toUpperCase() + reversed.substring(1, reversed.length) + dreamCar.toLowerCase();\r\n\r\n}", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
schedules when the next clock should fire
function scheduleClock() { var currentTime = audioContext.currentTime; currentTime -= startTime; while (nextClockTime < currentTime + scheduleAheadTime) { if (playPressed) { setTimeout(function() { //send midi clock start only the first beat! //timeo...
[ "function scheduleClock() {\n var currentTime = audioContext.currentTime;\n currentTime -= startTime;\n\n while (nextClockTime < currentTime + scheduleAheadTime) {\n if (playPressed) {\n setTimeout(function() {\n //send midi clock start only the first beat! \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return array of pokemon that haven't fainted
notFainted(){ return this.pokemons.filter(pokemon => { return !pokemon.fainted }) }
[ "get pokemonList() {\n // Filtering out Trainers\n return this.enemyList.filter((enemy) => {\n return !enemy.hasOwnProperty('name');\n }).map((enemy) => {\n // Collapsing DetailedPokemon\n if (typeof enemy === 'string') {\n return enemy;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register events for action buttons related to individual records displayed.
function registerRecordsActionButtonEvents() { var actions = self.settings().actions; for( var action in actions ) { var button = actions[action]; if(!button.perRecord) { continue; } registerActionButtonEvent(button, action); } ...
[ "function registerPageActionButtonEvents() {\n var actions = self.settings().actions;\n for( var action in actions ) {\n var button = actions[action];\n if(button.perRecord) {\n continue;\n }\n registerActionButtonEvent(button, action);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE SPECIFIED CSV FROM THE ROOT DIRECTORY
function deleteCsv(fileName) { const fs = require("fs"); fs.unlink(fileName, function (err) { if (err) throw err; //if no error, file has been deleted console.log("File deleted!"); }) }
[ "static deleteCsv() {\n if(fs.existsSync(pathCsvStart)) {\n fs.unlinkSync(pathCsvStart);\n }\n if(fs.existsSync(pathCsvEnd)) {\n fs.unlinkSync(pathCsvEnd);\n }\n if(fs.existsSync(pathCsvParticipants)) {\n fs.unlinkSync(pathCsvParticipants);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates the size of the Splitter Bars inside the Splitter
_validateBarsSize() { const that = this; //Check if size of the SplitterBar is explicitly set if ((getComputedStyle(that).getPropertyValue('--jqx-splitter-bar-fit-size') + '').trim() !== '100%') { return; } let biggestItem = that._items[0]; const size = 'off...
[ "_validateBarsSize() {\n const that = this;\n\n //Check if size of the SplitterBar is explicitly set\n if ((getComputedStyle(that).getPropertyValue('--smart-splitter-bar-fit-size') + '').trim() !== '100%') {\n return;\n }\n\n let biggestItem = that._items[0];\n c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validations of password (blur event)
function validateBlurPasswordText() { if (passwordInput.value === "" || passwordInput.value === null) { infoDivPassword.style.display = "block" infoDivPassword.style.color = "red" infoDivPassword.innerText = "Password field is empty" return; } if (passwordInput.value.search(...
[ "function validPassword() {\r\n\r\n inputPassword.onblur = () => testPasswordBlur();\r\n\r\n testPasswordFocus();\r\n }", "function validateBlurConfirmPasswordText() {\n\n if (confirmPasswordInput.value === \"\" || confirmPasswordInput.value === null) {\n infoDivConfirmPassw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes an array of all the elements that are in the path to the highlighted element.
function makeTagArr(pathToSelected, result) { var backwardsPath = pathToSelected; var currentTagName = $(result).prop("tagName").toLowerCase(); var siblingIndex = $(result).index(); var documentIndex = $(currentTagName).index(result); var tagArr = []; tagArr.unshift([currentTagName,documentIndex,siblingInde...
[ "function getHighlighted() {\n var highlighted = document.getElementsByClassName(\"highlight1\");\n var copied = [];\n\n // copy it to a NON mutable list.\n for (var i = 0; i < highlighted.length; i++) {\n copied.push(highlighted[i]);\n }\n\n return copied;\n}", "selectedNodes () { return Array.from(this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an obj which contains keyval pairs of matched labels.
matchedLabels(selectorLabels, templateLabels) { let finalResult = {}; if (!selectorLabels || !templateLabels) return finalResult; Object.entries(selectorLabels).forEach(([key, val], index) => { if ( templateLabels.hasOwnProperty(key) && templateLabels[key] === val ) finalResult[key] = val; ...
[ "static labels(labels) {\n const keys = Object.keys(labels).sort();\n const identifier = keys.reduce((result, key) => {\n if (result.length > 2) {\n result += ',';\n }\n return (result += key + ':' + labels[key]);\n }, '|#');\n const sorted...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send message to all current connections with proxies for the same thing, but excluding the given client if provided
function notify(message, client) { var connections = proxies[message.uri]; if (connections) { var notification = JSON.stringify(message); for (var i = 0; i < connections.length; ++i) { var ws = connections[i]; if (client) { if (ws === client) continue; } ...
[ "function broadcast_clients() {\n var tmp_client = []\n clients.forEach(function(client) {\n if (client.connected)\n tmp_client.push(nick[client.sessionId])\n })\n broadcast_msg({'sender': 'server', 'msg': {'clients': tmp_client }})\n}", "function disconnectClient(client) {\n\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show username if it has in cookie
function showUsername() { const cookies = decodeURIComponent(document.cookie).split(';'); if (cookies.length < 1 || cookies[0] === "") { // if theres no cookie, do nothing return; } const username = cookies[0].split('=')[1]; loginButton.hide(); navBar.append(` <li class="na...
[ "function setUserName() {\n\tusername = getUsernameFromCookie();\n \tif ( username != null && username != \"\" && username != \"guest\") {\n\t\tcurrentUser = username;\n\t} else {\n \t\tcurrentUser = \"guest\";\n \t}\n}", "function getNameFromCookies() {\n if (Cookies.get(\"player\") === undefined) {\n doc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filters a previously found list of items to ones with the same property as a given previous match. This function may reduce the size of the previous match.
withSame(prop, asIdx=-1) { if (this.lastResult === false) return this; //do nothing if (!this.workingList || !this.workingList.length) { this.lastResult = false; return this; } if (asIdx < 0) asIdx = this.matchedItems.length + asIdx; let list = this.workingList; let asList = this.matchedItems[asIdx]; ...
[ "filterMatchingItems(item) {\n if (this.state.shelf_life === 'All' && this.state.type === 'All') {\n return true;\n } else if (this.state.shelf_life === 'All' && this.state.type === item.type) {\n return true;\n } else if (this.state.shelf_life === item.shelf_life && this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From the info object provided by the resolver, get the unique identifier of the parent object
function getParentIdentifier(info) { return getIdentifierRecursive(info.path.prev); }
[ "getId() {\n const parent = this.getParent();\n return parent ? `${parent.getId()}/${this.getInternalId()}` : this.getInternalId();\n }", "__getParentId() {\n return this.part ? this.part.parentId : this.__parentId;\n }", "function mapParent (context, parentName) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
map bell indexes to human bell names
function bell_name(index) { if(index === -1) { return "*"; } if(index > -1 && index < 9) { return (index+1).toString(); } if(index === 9) { return '0'; } if(index === 10) { return 'E'; } if(index === 11) { return 'T'; } return index; }
[ "function bell_index(name) {\n if (name >= '1' && name <= '9') {\n return parseInt(name, 10) - 1;\n }\n if (name === '0') {\n return 9;\n }\n if (name === 'E') {\n return 10;\n }\n if (name === 'T') {\n return 11;\n }\n if(name === '*') {\n return -1;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Release the L button
*releaseButtonL() { yield this.sendEvent({ type: 0x01, code: 0x136, value: 0 }); }
[ "function on_mouse_lbtn_up(x, y, mask) {}", "*pressButtonL() {\n yield this.sendEvent({ type: 0x01, code: 0x136, value: 1 });\n }", "*releaseButtonR() {\n yield this.sendEvent({ type: 0x01, code: 0x137, value: 0 });\n }", "function releaseClick(event){\n\t\treleasePoke(event.target.name)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenience method for redis.sub.on('message')
onMessage(callback) { exports.default.sub.on('message', (channel, message) => callback(channel, JSON.parse(message))); }
[ "function onMessage(redisChannel, message){\n var songs = [],\n data;\n Petrucci.getById(common.getIdFromRedisChannel(redisChannel)).then(\n function(petrucci){\n data = JSON.parse(message);\n if (data.hasOwnProperty('song_ids')){\n data.song_ids.map(function...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle the filter form error event.
handleFilterFormErrorEvent() { // TODO should we present this error message? this.listingElement.removeAttribute('aria-busy'); }
[ "handleError (e) {\n const { category, actions, label, value } = this._options\n const val = value.error(this.player, e)\n this.collectEvent(category, actions.error, label, val)\n }", "function errorFilter(pesan) {\n // tampilkan pesan error filter\n $(\"#teks-error-filter\").text(pesan);\n $(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the given properties match those of a `S3OriginProperty`
function CfnStreamingDistribution_S3OriginPropertyValidator(properties) { if (!cdk.canInspect(properties)) { return cdk.VALIDATION_SUCCESS; } const errors = new cdk.ValidationResults(); errors.collect(cdk.propertyValidator('domainName', cdk.requiredValidator)(properties.domainName)); errors....
[ "function CfnDistribution_S3OriginConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('originAccessIdentity', cdk.validateString)(properties.originAcces...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch data from Mopidy
function fetchFromMopidy() { consoleError = console.error.bind(console); // get playlists mopidy.playlists.getPlaylists() .then(processGetPlaylists, consoleError); $("#play_pause").addClass('paused playing'); // get current track if there is one mopidy.playback.getCurrentTrack() .then...
[ "static fetchData(props) {\n props.mutator.loans.reset();\n props.mutator.loans.GET()\n .then(res => {\n const openRequestsQuery = ChangeDueDateDialog.getOpenRequestsQuery(props.loanIds, res);\n if (openRequestsQuery) {\n props.mutator.openRequests.reset();\n props.mutator...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
JS wrapper for the `ffi_prep_cif` function. Returns a Buffer instance representing a `ffi_cif ` instance.
function CIF(rtype, types, abi) { debug('creating `ffi_cif *` instance'); // the return and arg types are expected to be coerced at this point... assert(!!rtype, 'expected a return "type" object as the first argument'); assert(Array.isArray(types), 'expected an Array of arg "type" objects as the second argumen...
[ "function CIF (rtype, types, abi) {\n debug('creating `ffi_cif *` instance')\n\n // the return and arg types are expected to be coerced at this point...\n assert(!!rtype, 'expected a return \"type\" object as the first argument')\n assert(Array.isArray(types), 'expected an Array of arg \"type\" objects as the s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Event: called when document and resources are loaded Initialize Google Analytics
function _onLoad() { // Standard Google Universal Analytics code // noinspection OverlyComplexFunctionJS (function(i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; // noinspection CommaExpressionJS i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments); }, i[r].l = 1 * new Dat...
[ "initialize() {\n if (this.initialized_)\n return;\n this.initialized_ = true;\n const script = document.createElement('script');\n script.src = 'https://www.googletagmanager.com/gtag/js?id=' + ANALYTICS_ID;\n script.defer = true;\n document.head.appendChild(scri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To draw the scoreboard, first remove all the table rows corresponding to scores (these are the elements with the `score` class). This leaves the rows with the table headers intact. Then iterate through the namescore pairs and add new rows to the table. We trust the server to send us the scores in the correct sorted ord...
function drawScores(gameState) { document.querySelectorAll("tr.score").forEach(e => e.remove()); gameState.scores.forEach(([name, score]) => { const tableRow = document.createElement("tr"); tableRow.innerHTML = `<td>${name}<td>${score}`; tableRow.className = "score"; tableBody.appendChil...
[ "function printScores() {\n //Sort highest to lowest\n scoreList.sort(function (a, b) {\n return b.score - a.score;\n })\n //Print labels for name/score\n let scoreRow = document.createElement(\"row\")\n scoreArea.appendChild(scoreRow)\n let nameCol = document.createElement(\"div\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets if the provided structure is a JsxTagNamedNodeStructure.
static isJsxTagNamed(structure) { return structure.kind === StructureKind_1.StructureKind.JsxSelfClosingElement; }
[ "static isJsxTagNamedNode(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.JsxClosingElement:\r\n case typescript_1.SyntaxKind.JsxOpeningElement:\r\n case typescript_1.SyntaxKind.JsxSelfClosingElement:\r\n return true;\r\n defau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
internal function: display allThings Array on this UI (adjustPage.html) => to be replaced when other UI is used
displayAllThings (allThings) { let outputAll = '<h3> Available Things: </h3>'; for (let i = 0; i< allThings.length; i++) { _name = allThings[i].Thing_name _uid = allThings[i].Thing_UID _status = allThings[i].Thing_status outputAll += ` <ul> ...
[ "function renderIdeasInArray() {\n ideaList.forEach(function(idea) {\n idea.renderOnPage()\n });\n}", "function buildPage(){\n addItems('make', make);\n addItems('model', model);\n addItems('keywords', keywords);\n checkAll();\n}", "function display_theory_items() {\n var theory = json_files[cur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the hand object if the pointer is over it. otherwise null
function findClosestHandZone(self, object) { var closestHand = null; var objBounds = object.getBounds(); self.handSnapZones.getChildren().forEach(function (zone) { var zoneBounds = zone.getBounds(); if(Phaser.Geom.Intersects.RectangleToRectangle(objBounds, zoneBounds)) closestHand = hands[zone.playe...
[ "getHighHand() {\n if (!this.highestHand) {\n return false;\n }\n return this.highestHand;\n }", "destinationHand() {\n let hand = undefined;\n if (this.hasOrigin()) {\n if (this.direction == PASS || this.direction == SELF) {\n hand = (this.originHand === RIG...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provides: caml_get_section_table Requires: caml_global_data
function caml_get_section_table () { return caml_global_data.toc; }
[ "function generateTableSection (source, module) {\n let section = module.section(\"table section\");\n let table = source.defaultTable[0];\n\n if (table !== undefined && table.importSource === null) { // If the default table is imported, it's already been defined.\n section\n .byte(\"section.table\", \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if block is empty
function isCollectionInfoBlockEmpty(block) { return block === void 0 || block === null || block.info === null; }
[ "function isBlockEmpty(block) {\n\t if (block === void 0 || block === null) {\n\t return true;\n\t }\n\t const type = block.type;\n\t switch (type) {\n\t case 'collection-info':\n\t return collectionInfo.isCollectionInfoBlockEmpty(block);\n\t case 'collections-filter':\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a fake location
function getFakeLocation(success) { var point = { coords: { longitude: 114.413429, latitude: 30.509033 } }; success(point); }
[ "function getLocation() {\n return findLocation(getStatus());\n}", "function getRandomLocation() {\n\n}", "function findLocation(){\n navigator.geolocation.getCurrentPosition(foundLocation, noLocation);\n}", "function getOwnLocation(){\r\n\tif (navigator.geolocation){\r\n\t\tnavigator.geolocation.getCurre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of links designated as outputs. Following the format of: Returned links must have function getTargetElement() following the format: This new function should return a state
GetOutputLinks(element, opt) { return this; }
[ "static isNodeOutputLinkedToTargetNodes(node, output, targetNodes, links) {\n\t\tlet state = false;\n\t\tlinks.forEach((link) => {\n\t\t\tif (link.srcNodeId === node.id && link.srcNodePortId === output.id && this.isTargetNode(link.trgNodeId, targetNodes)) {\n\t\t\t\tstate = true;\n\t\t\t}\n\t\t});\n\t\treturn state...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize the header part
serializeHeader(header, id, headerFooterPath, headerFooterRelsPath) { this.headerFooter = header; let writer = new XmlWriter(); writer.writeStartElement('w', 'hdr', this.wNamespace); this.writeHFCommonAttributes(writer); let owner = this.blockOwner; this.blockOwner = head...
[ "writeHeader(obj) {\n this.writeUInt8(obj.imageFlags);\n this.writeUInt8(obj.imageVersion);\n this.writeUInt8(constants.TNS_LONG_LENGTH_INDICATOR);\n this.writeUInt32BE(0);\n if (obj._objType.isCollection) {\n this.writeUInt8(1); // length of prefix segment\n this.writeUInt8(1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handleStatusCallback Handles the Status Callback. The status callback is returned for all event updates.
function handleStatusCallback(msg) { IALOG.debug("Enter - handleStatusCallback"); var incidentId = msg.additionalTokens.incident_id; var xmStatus = msg.status; // Create an annotation for xMatters Event status updates. var annotation = ""; annotation = "xMatters incident for BPPM event: " + incidentId + "...
[ "function handleStatus(status) {\n\n\t\t}", "function addStatusCallBack(when, status, callback) {\n console.log('status call back is added: ' + when + status);\n var phrase = when + status;\n status_callback[phrase].push(callback);\n }", "onMediaStatusUpdated(handler) {\n return Event...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To validate user skills
validateSkills(){ if (this.state.profileData.userskills.length > 1) { return (true) } return (false) }
[ "function validateSkills(_skills) {\n const schema = {\n skills: joi.array().items(joi.objectId()),\n };\n return joi.validate(_skills, schema);\n}", "function validateSkills() {\n\tvar formValue = document.getElementById(\"skillForm\");\n\tformValue.action = 'candidate_portfolio_profile.htm';\n\n\tvar inpu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs an `Observable` that, when subscribed, causes the configured `OPTIONS` request to execute on the server. This method allows the client to determine the supported HTTP methods and other capabilities of an endpoint, without implying a resource action. See the individual overloads for details on the return type...
options(url, options = {}) { return this.request('OPTIONS', url, options); }
[ "options(url, opt = {}) {\n opt.method = 'OPTIONS';\n return this.sendRequest(url, opt);\n }", "_getObservableWithOptions(options) {\n let url;\n if (options.url) {\n url = options.url;\n }\n else {\n url = UrlUtil.join(this.apiRoot, this._baseEndpoint, opt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
digitsEnToFa Description: Takes a string made of English digits only, and returns a string that represents the same number but with Persian digits
function digitsEnToFa(str) { if (!str) return; str = str.toString(); for (var i = 0; i < 10; i++) { var replaceEntoFa = new RegExp("" + i, "g"); str = str.toString().replace(replaceEntoFa, faNums[i]); } return str; }
[ "function digitsFaToEn(str) {\n\t\tif (!str) return;\n\n\t\tstr = str.toString();\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\tvar replaceFaToEn = new RegExp(faNums[i], \"g\");\n\t\t\tstr = str.replace(replaceFaToEn, i);\n\t\t}\n\n\t\treturn str;\n\t}", "function digitsEnToFa(str) {\n if (!str) return;\n\n st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that gets statistics for challenge
function getChallengeStats(queryParams) { stats = {} return new Promise((resolve, reject) => { let visitQuery = 'SELECT count(*) as unique_visits, SUM(visit_count) as total_visits FROM ' + table.CHALLENGE_VISITOR + ' WHERE created_date > ? AND updated_date < ? AND challenge_type_id = ?' db.query(visitQu...
[ "static analyzeStatistics() {\n var convertToText = function(index,key) {\n var text = \"\";\n for (var i = 0; i < 3; i++) {\n if (!index.isArray) {\n text = key[index.index];\n } else {\n text += key[index.index[0]] + \"/\";\n index.index.shift();\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Standardize removes capitals, removes spaces, and removes underscores
function standardize(input) { input = input.toLowerCase(); //supposed to remove vowels and spaces input = input.replace(/[\s_]/g, ''); return input; }
[ "lowerSnakeCaseToSpaceCase() {\n return this.str.replace(/_/g, \" \").trim();\n }", "function normalize(str)\n{\n\treturn str.toLowerCase().replace(whiteSpaceRegex, \" \");\n}", "static normalize(cf)\n {\n return cf.replace(/\\s/g, \"\").toUpperCase();\n }", "static getStandardForm(inpu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse speech recognition result
function parseResult() { // recognition system will often append words into phrases. // so hack here is to only use the last word: var mostrecentword = listener.resultString.split(' ').pop(); var resultstring = listener.resultString; spoken_text = mostrecentword; // print(listener.resultJSON['t...
[ "function speechResult() {\n recognition.onresult = function(event) {\n console.log(\"recognition result event!\");\n var transcript = event.results[event.resultIndex][0].transcript;\n var words = transcript.split(\" \");\n var result = words[words.length - 1];\n if (development) {\n var dev = docume...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the native string name of a symbol.
function lisp_symbol_native_string(symbol) { return lisp_string_native_string(lisp_symbol_name(symbol)); }
[ "function lisp_symbol_name(symbol) {\n lisp_assert(lisp_is_instance(symbol, Lisp_Symbol));\n return symbol.lisp_name;\n}", "getName() {\r\n return this.compilerSymbol.getName();\r\n }", "getFullyQualifiedName(symbol) {\r\n return this.compilerObject.getFullyQualifiedName(symbol.compilerSy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loop through all of the charts on the page and zoom them to the same domain.
function zoom(domain) { for(i=0;i<chartset.length;i++) { c = chartset[i]; c.xScale().domain(domain); c.g().select('.axis--x').transition(c.t()).call(c.xAxis()); c.g().select(".primary") .transition(c.t()) .attr("d", c.line() .y(function(d) {return c.yScale()(y...
[ "function drawAllCharts() {\n\tchart_list.forEach(function(json) {\n\t\tloadJSON(json.json_url, function(response) {\n\t\t\tvar chart_data = JSON.parse(response);\n\t\t\tconvertPresshureToMMHG(chart_data);\n\t\t\tjson.charts.forEach(function(chart) {\n\t\t\t\tdrawWeatherChart(chart_data, chart.title, chart.hint, [c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether an elevator is scheduled to stop at the given floor in the given direction
function willAnElevatorStopHere(elevators, curelevator, floorNum, direction) { elevators.forEach(function(elevator) { var includesFloor = elevator.getPressedFloors().includes(floorNum); var sameDir = elevator.dir == direction; var sameElevator = elevator.getPr...
[ "elevatorWillPassFloor (floor, destinationFloor, direction) {\n if (\n (destinationFloor > floor && direction === 'up') ||\n (destinationFloor < floor && direction === 'down')\n ) {\n return true\n }\n return false\n }", "function isFloorWanted(elevator, floor){\n\t\t\tif (elevator.get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find city by ID
function cityById (id) { var i; for (i = 0; i < cities.length; i++) { if (cities[i].cityID === id) { return cities[i] } } return undefined }
[ "function _findCityByID(id) {\n for (var i=0; i<searchedCities.length; i++) {\n if (id == searchedCities[i].id) {\n return searchedCities[i];\n }\n }\n}", "function _findCityByID(id) {\n var index = cities.map(function (city) { return city.objectID; }).indexOf(id);\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get one cart cartId: string, the id of the cart sessionId: string, id of the current session
async function getCartAsync(cartId, sessionId) { return await cartActions.getCartAsync(cartId, sessionId); }
[ "findItemInCart(id) {\n return cart.find(item => item.id === id);\n }", "get cartId() {\r\n\t var _a;\r\n\t return (_a = index$2$1.get('cart.id')) !== null && _a !== void 0 ? _a : '';\r\n\t }", "function getCartaByID(id) {\n return deck[id - 1]\n}", "findInCart(id) {\n if (CAR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compute M/S thresholds from Johnston & Ferreira 1992 ICASSP paper
function vbrpsy_compute_MS_thresholds(eb, thr, cb_mld, ath_cb, athadjust, msfix, n) { var msfix2 = msfix * 2; var athlower = msfix > 0 ? Math.pow(10, athadjust) : 1; var rside, rmid; for (var b = 0; b < n; ++b) { var ebM = eb[2][b]; var ebS = eb[3][b]; ...
[ "function vbrpsy_compute_MS_thresholds(eb,thr,cb_mld,ath_cb,athadjust,msfix,n){var msfix2=msfix*2;var athlower=msfix>0?Math.pow(10,athadjust):1;var rside,rmid;for(var b=0;b<n;++b){var ebM=eb[2][b];var ebS=eb[3][b];var thmL=thr[0][b];var thmR=thr[1][b];var thmM=thr[2][b];var thmS=thr[3][b];/* use this fix if L & R m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The 'xGridRefToGameBoardCoordinate' function will take a main board area x grid reference and will return the corresponding canvas x coordinate
function xGridRefToGameBoardCoordinate (xGridRef) { xCoordinate = 150 + (xGridRef * 25); return xCoordinate; }
[ "function yGridRefToGameBoardCoordinate (yGridRef) {\n yCoordinate = 20 + (yGridRef * 25);\n return yCoordinate;\n}", "function xGridRefToNextPieceCoordinate (xGridRef) {\n xCoordinate = 35 + (xGridRef * 30);\n return xCoordinate;\n}", "gridToCanvasX(x) {\n return this.gridXStart + x * this.gridX...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Concatenate a number of ArrayBuffers into one.
function concatenateArrayBuffers(buffers) { var totalByteLength = 0; buffers.forEach(function (buffer) { totalByteLength += buffer.byteLength; }); var temp = new Uint8Array(totalByteLength); var offset = 0; buffers.forEach(function (buffer) { temp.set(new Uint8Array(buffer), offs...
[ "function concatenateArrayBuffers(buffers) {\n if (buffers.length === 1) {\n return buffers[0];\n }\n var totalByteLength = 0;\n buffers.forEach(function (buffer) {\n totalByteLength += buffer.byteLength;\n });\n var temp = new Uint8Array(totalByteLength);\n var offset = 0;\n buffers.forEach(function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Layout nodes linearly, sorted by group
function linearLayout(nodes) { // sort nodes by group nodes.sort(function(a, b) { return a.group - b.group; }) // used to scale node index to x position var xscale = d3.scale.linear() .domain([0, nodes.length - 1]) .range([radius, width - margin - radius]); // calculate...
[ "function linearLayout(nodes) {\n\t // sort nodes by group\n\t ///*\n\t nodes.sort(function(a,b) {\n\t \t//return Math.floor((Math.random() * 100) + 1);\n\t \treturn a.cluster - b.cluster;\n\t })\n\t\t//*/\n\n\t // used to scale node index to x position\n\t var yscale = d3.scale.linear()\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new convex hull.
constructor() { super(); /** * Whether faces of the convex hull should be merged or not. * @type {Boolean} * @default true */ this.mergeFaces = true; // tolerance value for various (float) compare operations this._tolerance = - 1; // this array represents the vertices which will be enclosed by ...
[ "function createHull() {\n // get the convex hull from the set of points\n conv_hull = convexHull(points);\n // if the hull is not null or undefined... so basically, if there is a hull\n if (conv_hull) {\n // give it some fill color\n fill(255, 50, 150, 50);\n // and a stroke\n stroke(0, 255, 100);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funcion : conjunto de ordenes q puede recibir parametros y pude devolver una salida.
function saludar(parametro){ return parametro; }
[ "function nombreFuncionParametros( parametroEntrada1, parametrosEntrada2 ){\n // CODIGO QUE OCUPA LAS VARIABLES DE ENTRADA Y TRABAJA EN FUNCION A ESOS \n }", "function enviarDadosQuatroParametros(codigoRegistro, descricaoRegistro, codigoAuxiliar, tipoConsulta){\n opener.recuperarDadosQuatroParametros(codig...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Component that checks if there is a current user and returns Sign out button
function SignOut() { return auth.currentUser && ( <button onClick={() => auth.signOut()}>Swim Out</button> ) }
[ "function SignOut() {\n return auth.currentUser && (\n <button className=\"sign-out\" onClick={() => auth.signOut()}>Sign Out</button>\n )\n}", "function SignOut() {\n return auth.currentUser && (\n //signout method used for signing user out\n <button className=\"sign-out\" onClick={() => auth.signOut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
const deck = this.props;
render(props){ const {deck,title,strategy} = this.props; return( <div className = "deck"> <h2>{title}</h2> {deck.map((card,i) => <Card {...this.props} key = {i} i = {i} card = {card}/>)} <h3>Strategy</h3> <p className = "deck-strategy">{strategy}</p> </div> ) }
[ "get card() {\n return this.props.card;\n }", "constructor(props){\n super(props)\n this.state= {\n deck: [],\n pickedCards: []\n }\n }", "produit(){return this.props.produit}", "get deck() {\n const { selectedDeckIdx } = this.state;\n return this.validDecks[selectedDeckIdx...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
refresh all the urls or add urls for the playlist and change the value of playlist, then save the playlist to DB
async function refreshPlaylistUrls(playlist) { var command = '/song/url?id=' for(var i=0;i<playlist.length;i++) { command += playlist[i].id + ',' } command = command.substr(0, command.length-1) url = host + command const res = await req('GET', url, '') let data = processHotSongs(res...
[ "function refreshPlaylist() {\n\trefreshAddRemoveTable();\n\tcurrentPlaylist['playerString'] = getPlayerString(currentPlaylist['songs']);\n\tupdatePlaylistTopBar();\n\tdisplayPlaylist();\n}", "savePlayList() {\n var trackUris = this.state.playlistTracks.map(item => item.uri);\n Spotify.savePlaylist(this.sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Interface used to conveniently type the possible context interfaces for the render row.
function RowContext() {}
[ "function RowContext() { }", "get context() {\n const ctx = {\n $implicit: this.value,\n additionalTemplateContext: this.column.additionalTemplateContext,\n };\n /* Turns the `cell` property from the template context object into lazy-evaluated one.\n * Otherwise ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates the localstorage with new Tasks
function updateTasks(e) { localStorage.setItem('data', JSON.stringify(e)); }
[ "updateTask() {\n const tasks = this.tasksArray\n localStorage.setItem('tasks',JSON.stringify(tasks))\n }", "function storeTasks(){\n localStorage.setItem(value, task);\n }", "function updateLocalStorage() {\n if (TASKS.length == 0) {\n localStorage.clear();\n } else {\n loc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the width of the video, so we can avoid having subtitles in the letterbox area. This works by the assumption that the video will take up 100% height. Then we can Figure out the real width from this and the aspect ratio.
function getVideoRealPixelWidth(videoId) { let video = document.evaluate(`//*[@id="${videoId}"]/video`, document).iterateNext(); if(video) { let aspectRatio = video.videoWidth / video.videoHeight; return video.offsetHeight * aspectRatio; } else { return null; } }
[ "function getVideoRatio(height, width) {\n\tlet ratio = width / height;\n\n\t// This block of code makes the video fit the screen whilst maintaining the original aspect ratio\n\tif (height > wallHeight) {\n\t\tlet width2 = wallHeight * ratio;\n\t\tif (width2 > maxX * 2) {\n\t\t\theight = (maxX * 2) / ratio;\n\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Crude method to add specified files to an archive.
function importFiles(archive, files, cb) { loop( files, (file, next) => { const filePath = fileMap[file]; archive.writeFile(file, fs.readFileSync(filePath), next); }, cb ); }
[ "_addFiles(files) {\n if(!(files instanceof Array)) {\n files = Array.from(files);\n }\n\n files.forEach((file) => {\n this.emit('addedfile',file);\n });\n\n return this;\n }", "add_files(files) {\n \n var i;\n for(i=0; i<files.length; i++) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MUD_Open ========= MUD_Save ============= PR20200802 PR20200815 PR20210630 PR20230404
function MUD_Save() { console.log("=== MUD_Save === "); const new_idnumber = (el_MUD_idnumber.value) ? el_MUD_idnumber.value : null; const new_cribnumber = (el_MUD_cribnumber.value) ? el_MUD_cribnumber.value : null; const new_bankname = (el_MUD_bankname.value) ? el_MUD_bankname.value : ...
[ "function MSTUD_Save(crud_mode) {\n console.log(\" ----- MSTUD_save ----\", crud_mode);\n console.log( \"mod_MSTUD_dict: \", mod_MSTUD_dict);\n\n if (permit_dict.permit_crud){\n\n const is_create = (mod_MSTUD_dict.is_addnew);\n const is_delete = (crud_mode === \"delete\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set a default for the viewport matrix. This may be overwritten. If you do not do anything here, result will be no transformation.
function setViewport() { // Center the scene and scale frustum to the canvas. // See mat4.multiplyVec4 for indices. var w = ctx.width; var h = ctx.height; var w2 = w / 2.0; var h2 = h / 2.0; viewport[0] = w2; viewport[5] = h2; viewport[12] = w2; viewport[13] = h2; //console.log("viewport: w" + w ...
[ "setViewPort() {\n gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);\n }", "function setDefaultView(){\n if (positions.length == 0) centerGrid = ol.proj.transform([-4, 83.5],\"WGS84\", \"EPSG:3413\");\n else centerGrid = activePointFeatures[activePointFeatures.length-1].getProperties().geometry.A;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The 'yGridRefToNextPieceCoordinate' function will take a next piece area y grid reference and will return the corresponding canvas y coordinate
function yGridRefToNextPieceCoordinate (yGridRef) { yCoordinate = 60 + (yGridRef * 30); return yCoordinate; }
[ "function yGridRefToGameBoardCoordinate (yGridRef) {\n yCoordinate = 20 + (yGridRef * 25);\n return yCoordinate;\n}", "function xGridRefToNextPieceCoordinate (xGridRef) {\n xCoordinate = 35 + (xGridRef * 30);\n return xCoordinate;\n}", "locY(piece) {\n switch(piece) {\n case 0: ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
begin simulation (just sets interval)
function launch() { cont=1; t1=setInterval("beginp()",iter); }
[ "startSimulation() {\n this.timeoutInterval = setInterval(() => this.executeNextAction(), this.speed);\n }", "function beginSimulation() {\n\tsimulating = true;\n\tsimulate(true);\n\tif(changes > 0 && !stopSim) {\n \tsetTimeout(beginSimulation, 40);\n\t} else {\n\t\tsimulating = false;\n\t\tstopSim =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Higher Order Functions, Timers, Closures Exercises countdown Write a function called countdown that accepts a number as a parameter and every 1000 milliseconds decrements the value and console.logs it. Once the value is 0 it should log "DONE!" and stop.
function countdown(num){ var timerId = setInterval(function(){ console.log(--num); },1000); setTimeout(function(){ clearTimeout(timerId); console.log("Done!") },3000); }
[ "function countdown(timer) {\n return (function(n) {\n for (var i = n; i >= 0; i--) {\n console.log(i);\n }\n console.log('Done!');\n })(timer);\n}", "function countDown(num) {\n setTimeout(function f(){\n if (num >= 0) {\n console.log(num--);\n setTimeout(f, 1000);\n } else retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove that apple, which is eaten by the snake, from the array
function removeApple(applePos, snakePos) { for (i = 0; i < applePos.length; i++) { if (applePos[i][0] === snakePos[0] && applePos[i][1] === snakePos[1]) { for (j = i; j < applePos.length - 1; j++) { applePos[j] = applePos[j + 1]; } applePos.pop(); ...
[ "EatApple() {\n var x0 = this.snake.segments[0].p0.x;\n var y0 = this.snake.segments[0].p0.y;\n for (var i = 0; i < this.apples.length; i++) {\n var apple = this.apples[i];\n var distance = Math.hypot(apple.x - x0, apple.y - y0);\n if (distance < 10) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function 15 Remove Properties /////////////////////////////////// //////////////////////////////////////////////////////////////////// Should take an object and an array of strings. Should remove any properties on that are listed in for in loop through thhe object check if the object key is included in the array if so ...
function removeProperties(object, array) { for (var key in object){ if (array.includes(key)){ delete object[key]; } } }
[ "function removeProperties(object, array) {\n \n for(var i = 0; i < array.length; i++){\n if(object.hasOwnProperty(array[i]) === true){\n delete object[array[i]];\n }\n } \n}", "function removeProperties(object, array) {\n for (var i = 0; i < array.length; i++) {\n dele...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }