query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
currently inverts functions that are linear binary trees with arithmetic operations, constant leaves, and one variable leaf
function invertReturnValue(returnValue) { var currentNode; try { currentNode = math.parse(returnValue); } catch (e) { if (!(e instanceof SyntaxError)) { console.log(e); } return; } var symbolNode = new math.e...
[ "function checkForScalarLinearExpression(tree, variables, inverseTree, components = []) {\n if ((typeof tree === \"string\") && variables.includes(tree)) {\n let mappings = {};\n let template = \"x\" + components.join('_');\n mappings[template] = { result: me.fromAst(inverseTree).simplify(), components: c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates through all items in array and calls `fn` function for each of them.
function each(array, fn) { var length = array.length; for (var i = 0; i < length; ++i) { fn(array[i], i); } }
[ "function operate(array, func) {\r\n if (array) {\r\n for (var n=0; n<array.length; n++) {\r\n func(array[n], n);\r\n }\r\n }\r\n return array;\r\n}", "function each( a, f ){\n\t\tfor( var i = 0 ; i < a.length ; i ++ ){\n\t\t\tf(a[i])\n\t\t}\n\t}", "function caonimabzheshiyigew...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is special handling for the Pocket audio file. It stitches together the intro and outro for the clients. concat intro + body upload stitched file resolve stitched file ... then the rest can be done after the promise resolves fire xcode request to sqs handle db writes upload intro & body separately for Alexa.
processPocketAudio(introFile, articleFile, article_id, locale) { return new Promise(resolve => { polly_tts .concatAudio([introFile, articleFile], uuidgen.generate()) .then(function(audio_file) { return polly_tts.uploadFile(audio_file); }) .then(function(audio_url) { ...
[ "synthesizeSpeechFile(parts, voiceType) {\n return new Promise(resolve => {\n let audio_file = uuidgen.generate();\n let promArray = [];\n for (var i = 0; i < parts.length; i++) {\n promArray.push(this.getPollyChunk(parts[i], i, audio_file, voiceType));\n }\n\n Promise.all(promArr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transition to a stacked area graph
function transition_stack_area(data,svg,player, type){ var y_scale = d3.scale.linear() .range([h-padding*2, 5]); var y_axis = d3.svg.axis() .scale(y_scale) .orient("left") .ticks(8); var stack = d3.layout.stack(); var x_scale = d3.scale.linear() .range([padding*2,width-padding]); var x_axis = d...
[ "function triggerStackedAreaChart() {\r\n\t$(\"#map\"+app.m).html(\"\");\r\n\r\n\tvar zm = 1;\r\n\tif (!isAllzIntervalsEqual()) return;\r\n\t\r\n\tvar dataGlobal = [];\r\n\tfor (var i=0; i<app.m; i++) {\r\n\t\tvar mapN = \"map\" + i;\r\n\t\t//var row = {date: new Date(app.years[i], 1, 1)};\r\n\t\tvar row = {mapId: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that takes number of rows as argument creates square of rows and asterisks as output first row contains 1 and (n1) asterisks second row contains 1, 2 and (n2) asterisks etc // Logic set rows equal to numArg set row = 1 set currentRow = [] for loop if i <= row add i to currentRow else add to currentRow add 1 to...
function generatePattern(rows) { for (i = 1; i <= rows; i++) { rowArray = []; for (j = 1; j <= rows; j++) { if (j <= i) { rowArray.push(j); } else { rowArray.push('*'); } } console.log(rowArray.join('')); } }
[ "function generatePattern(n) {\n var number = '';\n var asterisks = '';\n \n for (var i = 1; i <= n; i++) {\n // sets number of asterisks for specific row\n for (var j = n - i; j > 0; j--) {\n asterisks += '*';\n }\n // every time through loop another number gets added on\n number += i;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
b. Feet to CM should take the number of feet and convert it to the equal number of centimeters
function feetToCm(feet) { let feetConverter = feet / 0.032808; // console.log(feetConverter + " " + "centimeters"); return feetConverter + " " + "centimeters"; }
[ "function convertToCM(valueInFeet){\n valueInCM = valueInFeet / 30.48;\n return(valueInCM);\n }", "function inchesToCentimetres(){\r\n\t\r\n}", "function ConvertInchesToCentimeters(){\n\tvar inches = parseInt(document.calculator.setInches.value);\n\tvar inchesPerCentimeters= 2.54;\n\n\t\tcentimeters = in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description: parseTweets 1. Gather tweets with hashtag runkeeper. 2. Create an array of object Tweet (defined in tweet.ts) 3. Filter for written text only .writtenText (defined in tweet.ts) Source: Author: Malcolm Treacy
function parseTweets(runkeeper_tweets) { //Do not proceed if no tweets loaded if(runkeeper_tweets === undefined) { window.alert('No tweets returned'); return; } tweet_array = runkeeper_tweets.map(function(tweet) { return new Tweet(tweet.text, tweet.created_at); }); written_tweets = tweet_array.filter(twe...
[ "function twitter_parser(tweets){\n $.each(tweets, function(i,tweet){\n if(tweet.full_text !== undefined) {\n var tweettext = tweet.full_text,\n tweetapi;\n if(options._isSearch){\n\n tweetapi = {\n '{tweetdate}' : twitter_re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
===== Project Slider Two
function projectSliderTwo() { $('.project-slider-two').slick({ infinite: true, dots: false, arrows: true, prevArrow: '<button type="button" class="slick-arrow slick-prev"><i class="far fa-angle-left"></i></button>', nextArrow: '<button type="button" cl...
[ "function projectSliderOne() {\n $('.project-slider-one').slick({\n infinite: true,\n dots: false,\n arrows: false,\n speed: 500,\n slidesToShow: 5,\n slidesToScroll: 1,\n autoplay: true,\n autoplaySpeed: 5000,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
look up a screensaver by key, and return it
getByKey(key) { key = this.normalizePath(key); var result = this.loadedScreensavers.find((obj) => { return obj.key === key; }); return result; }
[ "function getGame(key) {\n console.log(\"in getGame...\");\n\n var game = vm.games.$getRecord(key);\n\n return game;\n }", "function StoreScreen() {\n prevVal = $('#screen').text();\n }", "function keyPressed() {\r\n if (key == 'x') {\r\n save(\"screenshotART_151_\" + saveCount + \".png\");\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pad a string to be even
function padToEven(a) { return a.length % 2 ? "0" + a : a; }
[ "function padToEven(a){return a.length%2?\"0\"+a:a;}", "function padEnd(str,num, pad){\n if (num < str.length) return str;\n if (str.length < num){\n if (arguments.length === 3){\n let diff = Math.ceil((num-str.length)/pad.length);\n for (let i = 0; i < diff; i++){\n str += pad;\n }\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function: replace "search" with "replace" in element.className. "search" has to fully match one of the space separated strings in className.
function replaceClass(element, search, replace) { if(element.className) { if(replace && new RegExp("(^|\\s)" + replace + "(\\s|$)").test(element.className)) { replace = '' } var subject = element.className, searchRE = new RegExp("(^|\\s+)" + search + "(\\s+|$)", "g"), m = searchRE....
[ "function alterClass(action, element,class1, class2){\r\n\t //create a switch case for each action swap/check/replace/remove etc\r\n\t switch (action){\r\n\t \r\n\t case 'swap':\r\n\t\t //Swaps one class with another\r\n\t\t //First check if class1 exists. If it does not, use class1 to replace class 2.\r\n\t\t //If...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders a page asking for Internet Archive account password
static password() { const doc = navigationDocument.documents[navigationDocument.documents.length - 1] const e = doc.getElementsByTagName('textField').item(0) const val = e.getFeature('Keyboard').text TVA.render(` <document> <formTemplate> <banner> <img src="https://archive.org/images/glogo....
[ "showPasswordView() {\n const view = new Passphrase({model: this.collection.get('privateKey')});\n Radio.request('Layout', 'show', {view, region: 'modal'});\n }", "function showPass() {\n const password = document.getElementById('password');\n const rePassword = document.getElementById('masterR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles responses to an ajax request: finds the right dataType (mediates between contenttype and expected dataType) returns the corresponding response
function ajaxHandleResponses(s,jqXHR,responses){var ct,type,finalDataType,firstDataType,contents=s.contents,dataTypes=s.dataTypes;// Remove auto dataType and get content-type in the process while(dataTypes[0]==="*"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader("Content-Type");}}// Check i...
[ "function ajaxHandleResponses(s,jqXHR,responses){var contents=s.contents,dataTypes=s.dataTypes,responseFields=s.responseFields,ct,type,finalDataType,firstDataType;// Fill responseXXX fields\nfor(type in responseFields){if(type in responses){jqXHR[responseFields[type]]=responses[type];}}// Remove auto dataType and g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
prepareRegex by JoeSimmons used to take a string and ready it for use in new RegExp()
function prepareRegex(string) { return string.replace(/([\[\]\^\&\$\.\(\)\?\/\\\+\{\}\|])/g, '\\$1'); }
[ "function prepareRe(initials) {\n var myReStr = \"\";\n for (var i = 0; i < initials.length; i++) {\n\tmyReStr += \"\\\\w+\\\\s\";\n };\n myReStr = \"(\" + myReStr + \")\" + \"\\\\(\" + initials + \"\\\\)\";\n var myRe = new RegExp(myReStr, \"g\");\n return myRe;\n}", "function regexpFrom(string...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Here is the test for sumArray(); uncomment it to run it testSumArray(testArray); Once you get the test passing, do an acp cycle and synchronize the code between GitHub and your laptop. Don't forget to create a new branch for your work on the next question! /////////////////////////////////// / Problem 5 Write a functio...
function multiplyArray(testArray) { //eslint-disable-line //establish a counter var product = 1; // * all the #'s in the array // use a for loop to set boundaries // use multiply() to replace counter = counter * array[i] for (var i = 0 ; i < testArray.length ; i++) { product = multiply(product, testA...
[ "function productContents(array) {\r\n\tlet product = 1;\r\n\tfor (let i = 0; i < array.length; ++i)\r\n\t{\r\n\t\tproduct *= array[i];\r\n\t}\r\n\treturn product;\r\n}", "function sumMultiplier(array, targetSum) {\n // initialize variable to avoid mutating original\n let arr = array\n // sort in ascending ord...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets or sets the brush to use for needle element.
get needleBrush() { return brushToString(this.i.hx); }
[ "get needleOutline() {\n return brushToString(this.i.hy);\n }", "function needleOutline(svg, chartHeight, offset, needleColor, outerRadius, centralLabel, outerNeedle, needleStartValue) {\n var needleValue = needleStartValue;\n var needle = new needle_interface_1.Needle(svg, needleValue, centralLab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
User clicks on one of the sliders, starts volumeBarInterval timer
function volumeBarClickedDown(changeVolume) { volumeBarInterval = setInterval(changeVolume, 100); }
[ "volumeBtnPress(e) {\n const spinner = e.target;\n const [ height, width, x, y ] = [spinner.clientHeight, spinner.clientWidth, \n spinner.offsetLeft, spinner.offsetTop];\n const center = [x + width / 2, y + height / 2];\n\n const move = (e) => {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes everything required to complete the strip phase of a round. Makes the losing player strip or start their forfeit. May also end the game if only one player remains.
function completeStripPhase () { /* strip the player with the lowest hand */ stripPlayer(recentLoser); updateAllGameVisuals(); }
[ "function completeContinuePhase () {\n\t/* show the player removing an article of clothing */\n\tprepareToStripPlayer(recentLoser);\n updateAllGameVisuals();\n\t\n\t$mainButton.html(\"Strip\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}", "fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a string, compute recursively (no loops) a new string where all appearances of "pi" have been replaced by "3.14".
function changePi(str){ let s = str.indexOf("pi"); if (s == -1) return str; return changePi(str.substring(0,s) + "3.14" + str.substring(s + 2)); }
[ "function replaceString(str, findTok, replaceTok, isOne) {\n\n pos = str.indexOf(findTok);\n valueRet = \"\";\n if (pos == -1) {\n return str;\n }\n valueRet += str.substring(0,pos) + replaceTok;\n if (!isOne && ( pos + findTok.length < str.length)) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The following code turns the selected article and podcast titles white or gold
function selectArticle1() { document.getElementById("article1").style.color = 'gold'; }
[ "function changeColor(){\n\ttitle.style.color = color.value;\n\ttitle1.style.color = color.value;\n\ttitle2.style.color = color.value;\n\ttitle3.style.color = color.value;\n\t\n\tdescription.style.color = color.value;\n\tdescription1.style.color = color.value;\n\tdescription2.style.color = color.value;\n\tdescripti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The user has begun using an IME input system. Switching to `composite` mode allows handling composition input and disables other edit behavior.
function editOnCompositionStart() { this.setRenderGuard(); this.setMode('composite'); this.update(EditorState.set(this.props.editorState, { inCompositionMode: true })); }
[ "function loadComposition( _composition )\n{\n\ttemplate = _composition\n\ttoggleButtonsTemplate()\n\tif( _composition == 'new' )\n\t{\n\t\tfor(var i = 0; i < composition.pieces.length; i++)\n\t\t\tcomposition.scene.removeObject(composition.pieces[0].object)\n\t\tcomposition.pieces = []\n\t\tmode = 'edit'\n\t\ttogg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A subclass of `Type` which has a static `ngDirectiveDef`:`DirectiveDef` field making it consumable for rendering.
function DirectiveType() { }
[ "static define() {\n return new AnnotationType()\n }", "visitType_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function getInjectorDef(type) {\r\n return type && type.hasOwnProperty(NG_INJECTOR_DEF) ? type[NG_INJECTOR_DEF] : null;\r\n }", "static directi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show active coins in Modal
function showActiveCoinsInModalWindow() { $("#activeModalCoins").empty(); for (item of state.activeCoins) { createDivCoinMain(item, $("#activeModalCoins")); } }
[ "function addActiveCoin(inptSwtch, coin) {\n inptSwtch\n .unbind(\"click\")\n .bind(\"click\", () => removeActiveCoin(inptSwtch, coin));\n coin.checked = true;\n\n //save in state active coins\n state.activeCoins.push(coin);\n let activeListFull = checkIfTheActiveListFull();\n\n if (acti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mock a field type
function mockTypeFields(type) { const fieldsData = {}; return type.fieldsArray.reduce((data, field) => { field.resolve(); if (field.parent !== field.resolvedType) { if (field.repeated) { data[field.name] = [mockField(field)]; } else { data[field.name] = mockField(field); ...
[ "function interpretMockViaFieldName(fieldName) {\n const fieldNameLower = fieldName.toLowerCase();\n\n if (fieldNameLower.startsWith('id') || fieldNameLower.endsWith('id')) {\n return uuid.v4();\n }\n\n return 'Hello';\n}", "getFieldType() {\n return this._fieldTypeId\n }", "function test_can_access_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set args from config.json file, this should be applied last so that defaults can be applied.
function setConfig (argv) { var configLookup = {} // expand defaults/aliases, in-case any happen to reference // the config.json file. applyDefaultsAndAliases(configLookup, aliases, defaults) Object.keys(flags.configs).forEach(function (configKey) { var config...
[ "function parseArguments(args) {\n var defaultConfig = {\n stateKey: 'instances',\n instanceKey: 'id'\n };\n\n if (typeof args[0] === 'function') {\n return {\n callback: args[0],\n config: defaultConfig\n };\n } else {\n return {\n cal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Construct an anonymous font family, i.e., a composite font that is created / programatically instead of referenced by name or URI.
public FontFamily() { _familyIdentifier = new FontFamilyIdentifier(null, null); _firstFontFamily = new CompositeFontFamily(); }
[ "public FontFamily(string familyName) : this(null, familyName)\r\n {}", "public FontFamily(Uri baseUri, string familyName)\r\n { \r\n if (familyName == null)\r\n throw new ArgumentNullException(\"familyName\"); \r\n \r\n if (baseUri != null && !baseUri.IsAbsolute...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ content ready to display ]
function ready_content() { app.param.generate.addClass('ready'); $('.generate-container .thumb').html('<i class="fa fa-check fa-2x" aria-hidden="true"></i>'); (!app.param.checkbox.prop('checked') ? media = 'Movie' : media = '<br>TV Show'); $('.generate-container .header').html('See Random ' + me...
[ "function loadContent() {\n\t\tMassIdea.loadHTML($contentList, URL_LOAD_CONTENT, {\n\t\t\tcategory : _category,\n\t\t\tsection : _section,\n\t\t\tpage : 0\n\t\t});\n\t}", "function initContentmanagment()\r\n{\r\n\t_carouselResponseId = 0;\r\n\t_emptyBreadcrumbContent = $(BREADCRUM_ID).html()\r\n}", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show weight logs in a date range
getWeightsRange(date1, date2){ let temp = []; let progress = 0; let start = new Date(date1); let end = new Date(date2); for(var i=0; i< this.weightLog.length; i++){ if(this.weightLog[i].date >= start && this.weightLog[i].date <=end){ temp.push(this.wei...
[ "getWeightsWeek(){\n let temp = [];\n let today = new Date();\n let progress = 0;\n let lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);\n for(var i=0; i< this.weightLog.length; i++){\n if(this.weightLog[i].date >= lastWeek && this.weight...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply default values for new patrons during initial registration prs is shorthand for patronSvc
function set_new_patron_defaults(prs) { if (!$scope.patron.passwd) { // passsword may originate from staged user. $scope.generate_password(); } $scope.hold_notify_type.phone = true; $scope.hold_notify_type.email = true; $scope.hold_notify_type.sms = false;...
[ "function setDefault() {\n if (ctrl.rrule.bymonthday || ctrl.rrule.byweekday) return\n ctrl.rrule.bymonthday = ctrl.startTime.getDate()\n }", "function init() {\n angular.forEach(railsBindings, function(value, key) {\n railsData[key] = toResource(value);\n });\n }", "function handle_user_init...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the UI to reflect a specified nanite deployment state.
function updateDeployedState(state) { $deploymentStateParent.attr('class', 'list-group-item'); if (state === 'deploy') { $deploymentState.text('Deploying'); $deploymentCompletion.text(0); $deploymentStateParent.addClass('list-group-item-warning'); $deploy.addClass('disabled').prop('dis...
[ "function watchDeployment() {\n let percentDone = 0;\n\n const updateCompletion = () => {\n // give completion a 20% chance to increse.\n if (randInt(4) === 0) {\n percentDone += 1;\n $deploymentCompletion.text(percentDone);\n }\n };\n\n progressInterval = setInterval(functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return an array of 'yyyymmdd' format days from giving Date object
function getMDays ( d ) { var dateArr = []; var date = d.toJSON().split("T")[0].split("-"); var dateStr; var days = new Date(d.getUTCFullYear(),d.getUTCMonth()+1,0).getDate(); for(var i=1;i<days+1;i++) { var t = i; if(i<10) {t = "0" + i;} date[2] = t; dateStr = date.join(''); dateArr....
[ "function BuildDates(date){\n\tvar array = new Array();\n\tarray['day'] = (date.getDate() < 10) ? \n\t\t\t\t\t\t'0' + date.getDate().toString() : \n\t\t\t\t\t\tdate.getDate().toString();\n\t\t\t\t\t\t\n\tarray['month'] = (date.getMonth() < 9) ? \n\t\t\t\t\t\t'0' + (date.getMonth()+1).toString() : \n\t\t\t\t\t\t(dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
each order should have a car image logo. each order should have car Order Details ( Customer Name, Car Model, Car Price ) the car price will be a random number between 1000 10000. As a user, I would like to view all of the Orders that I already added. Whenever you add an order using the form, you should use the local s...
function Order(custName,carModel,carPrice,carImage){ this.custName = custName; this.carModel = carModel; this.carPrice = carPrice; this.carImage = carImage; all_orders.push(this); }
[ "function listOrders()\n{\n let options = {};\n // get the users email address\n options.id = $('#buyer').find(':selected').text();\n // get their password from the server. This is clearly not something we would do in production, but enables us to demo more easily\n // $.when($.post('/fabric/admin/ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assuming this iterable is sorted, removes duplicates from it by applying comparator(prev, current) to sibling iterable values. Comparator function is expected to return 0 when items are equal, similar to Array.prototype.sort() argument. If comparator is not set, uses strict === comparison
deduplicateSorted(comparator) { return new GatsbyIterable(() => deduplicateSorted(this, comparator)); }
[ "relativeComplement(otherSet) {\n let newSet = new BetterSet();\n this.forEach(item => {\n if (!otherSet.has(item)) {\n newSet.add(item);\n }\n });\n return newSet;\n }", "function merge_in_place(lists, cmp_fn, dup_fn) {\n cmp_fn = cmp_fn || cmp\n\n if (!lists) return [];\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start subpipeline span for algorithm
_startSubPipelineSpan(subPipelineName, subPipelineId) { try { const name = `subpipeline ${subPipelineName} start invoked`; const spanOptions = { name, id: subPipelineId, tags: { subPipelineId, jobId: ...
[ "visitStart_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "_finishSubPipelineSpan(subPipelineId, status, error) {\n const topSpan = tracer.topSpan(subPipelineId);\n if (topSpan) {\n topSpan.addTag({ status });\n if (status === pipelineStatuses.STOPPED) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rotate model by specified angle around axis angle: angle to rotate in degree (not radian) axis: rotation axis, origin (0,0,0)
function ModelRotate(orig, angle, axis, dest) { // orig to dest with complex relation, copy first var c_orig = new Float32Array(orig); var a_rad = angle / 180 * Math.PI; DivVec(axis, CalcEV(axis)); var rot_s = Math.sin(a_rad); var rot_c = Math.cos(a_rad); var mat_a = [ axis[0] * axis[0], axis[0] * axi...
[ "rotate(axis, angle) {\n var state = this.cam.state;\n if(angle) {\n var new_rotation = Rotation.create({axis:axis, angle:angle});\n Rotation.applyToRotation(state.rotation, new_rotation, state.rotation);\n }\n }", "rotateAroundWorldAxis(obj, axis, radians) {\n let rotWorldMatrix = new ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the Homepage.html failed to load
function error() { $(".content").html("Failed to load content!"); }
[ "onWebViewErrorOccurred(details) {\n this.fire('error');\n this.loadingError_ = true;\n }", "function errorPage(req, res, err) {\n\tres.type(\"text/html\");\n\tres.charset = \"utf-8\";\n\tres.write(header(req));\n\tres.write(`\n\t<div class=\"infobox\">\n\t\t<h2><i class=\"fas fa-exclamation-triangle\"> </...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detach given track from the DOM.
function detachTrack(track) { track.detach().forEach(function(element) { element.remove(); }); }
[ "function detachTracks(tracks) {\n tracks.forEach(function(track) {\n console.log(track);\n track.detach().forEach(function(detachedElement) {\n detachedElement.remove();\n });\n });\n }", "function detachParticipantTracks(participant) {\n console.log(participant);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggles the drive root visibility when the `driveEnabled` preference is updated.
toggleDriveRootOnPreferencesUpdate_() { if (this.driveEnabled_) { const driveFakeRoot = new FakeEntryImpl( str('DRIVE_DIRECTORY_LABEL'), VolumeManagerCommon.RootType.DRIVE_FAKE_ROOT); if (!this.fakeDriveItem_) { this.fakeDriveItem_ = new NavigationModelFakeItem( s...
[ "function handleDriveClick(event) {\n document.getElementById(\"drive\").style.display = 'block';\n document.getElementById(\"home\").style.display = \"none\";\n AnalyticsManager.clickedDrive();\n}", "setIsRemovable() {\n this.isRemovable = true;\n }", "function toggleSwitch(number) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to hide xml text
function hideXML(){ document.getElementById("hiddenText").hidden = true; document.getElementById("hiddenBtn").hidden = true ; }
[ "function hideTipShowText() {\n tipElement.style.opacity = '0'\n nodeElement.style.opacity = '1'\n nodeTitleElement.textContent = title\n }", "function hideSensorTagConfigFile() {\n\t// Hide the file data \n\tdocument.getElementById('sensortagConfigFileData').innerHTML = ''\n\t//Change the buttons to sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
trackScrollDepth Used to track scroll depth events in google analytics.
trackScrollDepth($depth) { ga('send', 'event', 'scroll-depth', $depth, { nonInteraction: true }); }
[ "function updateMaxRelativeScrollDepth() {\n /* Don't measure scroll depth if:\n * * The page doesn't have the user's attention\n * * Scroll depth measurement doesn't wait on attention and the page load is too recent\n * * Scroll depth measurement does wait on attention and eith...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
lex function that supports token stacks
function tokenStackLex() { var token; token = tstack.pop() || lexer.lex() || EOF; // if token isn't its numeric value, convert if (typeof token !== 'number') { if (token instanceof Array) { tstack = token; token = tstack.pop(); } token = self.symbols_[toke...
[ "function pushlex(type, info) {\n var result = function(){\n lexical = new CSharpLexical(indented, column, type, null, lexical, info)\n };\n result.lex = true;\n return result;\n }", "function getTokens(characters){\n var tokenPointer = 0;\n while (tokenPointer < characters.lengt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deletePlaysRow This function deletes a given item from the plays table. It is a modified version of the deleteTableRow function, which was necessary because the plays table uses two primary keys instead of one and therefore needs to be passed two id values. Arguments: id1: the drummer ID of the element that is being de...
function deletePlaysRow(id1, id2) { //Create a new HTTP request var req = new XMLHttpRequest(); //Contruct a URL that sends a GET request to /delete with the id value var url = "http://flip2.engr.oregonstate.edu:" + port + "/delete-plays" + "?drummer_id=" + id1 + "&kit_id=" + id2; //Make the call ...
[ "'comparison.deleteRow' (rowId) {\n check(rowId, String);\n\n Row.remove(rowId);\n }", "function DeleteIngredientsRow(){\n let i = u.GetNumber(event.target.id)+1;\n u.ID(\"ingredientTable\").deleteRow(i);\n // renumber the ids of all the rows below the deleted row\n let len = u.ID(\"i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the minimum price variant id
function lowPrice(variants) { let minID = 0; for (let i = 0; i < variants.length; i++) { if (Math.round(variants[i].prices.regular) < Math.round(variants[minID].prices.regular)) minID = i } return minID }
[ "selectMinDFromVS(){\n var minVex = null;\n\n for (var i in this.VS){\n if (minVex == null){\n minVex = i;\n }\n \n else{\n if (typeof this.D[i] != \"number\") {\n this.D[i] = parseInt(this.D[i]);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draft spec: probably would need ATK (for binarual decode at least), more uptodate SC etc than current... Return a bus for BFormat Ambisonics. If a bus with the given name already exists, that will be used. No argument for name will use a default "AmbiMaster" bus. TODO: maybe use SynthDef naming convention __ambi_ and m...
function AmbiBus(name = "AmbiMaster") { //review... main decode is ordered before everything. //currently only using one decode, still quite like the idea of other fx //! but not important priority ! const b = SynthBus(name, 4); const g = b.group; g.order(naddTail(rootAmb...
[ "function OFBus() {\n EventEmitter.call(this);\n}", "function createAMO(name, vb, nb, ub, ib, jb, wb, animation) {\n // Header\n let AMO = \"#Generated by editamo\\n\";\n AMO += `ao ${name}\\n\\n`;\n\n // Vertexbuffer aka v\n for(let i = 0; i < vb.count; i++) {\n AMO += `v ${vb.data[i*3]}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that intializes and adds the mesh for the windowpane to the scene.
function createWindowPane(){ windowPane = new THREE.Mesh( new THREE.PlaneGeometry(plane_width/3, plane_height/3, segments_w, segments_h), shaderMaterial ); // set default position to (0,0,-100) windowPane.position.x = 0; windowPane.position.y = 0; windowPane.position.z = 0;//-plane_width/2; // update matrix window...
[ "function createMeshes() {\r\n mesh_lantern1 = createLantern ();\r\n scene.add(mesh_lantern1);\r\n\r\n mesh_lantern2 = mesh_lantern1.clone();\r\n mesh_lantern2.translateX(15.0);\r\n scene.add(mesh_lantern2);\r\n\r\n mesh_lantern3 = mesh_lantern1.clone();\r\n mesh_lantern3.translateZ(-20.0);\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to assign the proper initial colors to each district included in the geojson. Called on startup.
function assignStyle(geojson) { for (let e in geojson.features) { let d = geojson.features[e].properties['DIST']; let color; switch(parseInt(d)) { case 1: color = "#800000"; break; case 2: color = "#808000"; ...
[ "function setNeighborhoodColors() {\n console.log(\"setNeighborhoodColors()\");\n map.data.forEach( function( feature ) {\n // The name is the key in the quickLookup hash\n var key = feature.getProperty( 'NAME' );\n if ( quickLookup[ key ] ) {\n localCrime = quickLookup[ key ].crime;\n localRen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Service call api get service by id
function getService(name, id) { var deferred = $q.defer(); $http.get(BASE_URL + "invoice/getService/name=" + name + "&id=" + id) .then( function (response) { console.log("getService" + response.data); deferred.resolve(response.data); ...
[ "retrieveHotel(id){\n return axios.get(`${CONST_API_URL}/showHotelDetails/${id}`);\n }", "function getService(serviceId) {\n $.getJSON(`/api/services/${serviceId}`, function (service) {\n $('#cardImg').attr('src', 'img/' + service.Image );\n $('#cardImg').attr('alt', service.ServiceName...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
renderFavs() renders a miniature favorite image in the Favorites section and also adds attributes which will later be used by showFavorites()
function renderFavs(imgData) { var favImg = $("<img>"); // miniature still gif favImg.attr("src", imgData.images.fixed_height_small_still.url); favImg.attr("alt", imgData.title); favImg.attr("giphy-img-id", imgData.id); favImg.attr("img-state", "still"); favImg.attr("img-fixed-width", imgData.images.fixe...
[ "function generateFavorites() {\n // empty out the list\n $favoritedStories.empty();\n //\n if (currentUser.favorites.length === 0) {\n $favoritedStories.append(\"<p>No favorites added!</p>\");\n } else {\n for (let story of currentUser.favorites) {\n // render each story in the list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
JS task (concat + minify) + obfuscate
function jsTask() { return src(paths.srcJS) .pipe( plugins.obfuscate({ replaceMethod: plugins.obfuscate.LOOK_OF_DISAPPROVAL, }), ) .pipe(plugins.sourcemaps.init()) .pipe(plugins.concat("app.js")) .pipe(plugins.terser()) .pipe(plugins.sourcemaps.write(".")) .pipe(dest(pa...
[ "function jsTask(){\n return src(files.jsToBuild)\n .pipe(concat('all.min.js'))\n .pipe(uglify())\n .pipe(dest(files.distToDistJs))\n}", "function jsTask() {\n return src(files.jsPath)\n .pipe(concat(\"all.js\"))\n .pipe(minify())\n .pipe(dest(\"dist\"));\n}", "function jsCompile() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
callback for ice candidate
function iceCandidateCallback(e) { if(e.candidate != null) { if(scope.onIceCandidate) { scope.onIceCandidate(scope,JSON.stringify({'ice': e.candidate})); } } }
[ "function handleICECandidateEvent(event) {\n if (event.candidate) {\n\n log(\"*** Outgoing ICE candidate: \" + event.candidate.candidate);\n sendToServer({\n type: \"new-ice-candidate\",\n candidate: event.candidate\n });\n }\n\n}", "function ViewClient(recipient) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save the base64 canvas image to localStorage
function saveCanvasToStorage() { localStorage.setItem('canvas', getCanvas().toDataURL()); }
[ "function saveImage() {\n var data = canvas.toDataURL();\n $(\"#url\").val(data);\n }", "function saveLastDrawing() {\n lastImage.src = canvas.toDataURL('image/png');\n }", "handleSave() {\n const can = document.getElementById('paint');\n const img = new Image();\n\n /**\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
building the row for the county selected
function buildRow(countySelection) { for (let j = 0; j < database.length; j++ ) { if(database[j].content.$t.includes(countySelection) && database[j].gs$cell.col == 1) { let sameRow = database[j].gs$cell.row //will iterate through the 26 columns fo...
[ "function populateResultsTable_by_country() {\n\n\t\t\tvar selectedStates = $(\"#statesListbox_by_country\").val() || [];\n\t\t\tvar HSarray = selected_HS6_Codes\n\n\t\t\timportResultsTable_by_country = searchDBByAbbr(importDestinationDB, selectedStates);\n\t\t\texportResultsTable_by_country = searchDBByAbbr(export...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AND RelatedToId="+req.query.Id + " AND RelatedToObject="+req.query.Object method to fetching all the task list related to lead
taskList(req, res) { console.log('req.query>>>>>>>>>>>>>>>>>>>>.',req.query); con.query("SELECT * FROM `object_query_31` where ActiveStatus=? AND RelatedToId=? AND RelatedToObject=?",[1,req.query.Id,req.query.Object],function(err, result) { if (err) throw err; else { console.log('res...
[ "async function fetchTasksFromSource(objTaskSource) {\n\n var objReturn = new Object();\n objReturn.retStatus = 0;\n objReturn.retMessage = null;\n objReturn.retObject = undefined;\n\n self.endpointAddress = objTaskSource.epTaskListApi;\n var ep = RestHelper.get(self.endpointAddress);\n\n var o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The AWS::WAF::XssMatchSet resource specifies the parts of web requests that you want AWS WAF to inspect for crosssite scripting attacks and the name of the header to inspect. For more information, see XssMatchSet in the AWS WAF API Reference. Documentation:
function XssMatchSet(props) { return __assign({ Type: 'AWS::WAF::XssMatchSet' }, props); }
[ "function SqlInjectionMatchSet(props) {\n return __assign({ Type: 'AWS::WAF::SqlInjectionMatchSet' }, props);\n }", "function ByteMatchSet(props) {\n return __assign({ Type: 'AWS::WAF::ByteMatchSet' }, props);\n }", "function ByteMatchSet(props) {\n return __assign...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PRIVATE: NotifyCtrl: Controlador del mdDialog de notificaciones. //
function NotifyCtrl($scope, data, $mdDialog) { $scope.data = data; //Evaluacion de estados $scope.isVoid = function() { return (data.esta === 'V'); } $scope.isAuto = function() { return (data.esta === 'O'); } $scope.isInfo = function() { return (data.esta === 'I'); } //Traducción de estados $scope.t...
[ "function showNotify(notf) {\n\t\treturn $mdDialog.show({\n\t\t\t\t\tlocals:{data: notf},\n\t\t\t\t\tcontroller: NotifyCtrl,\n\t\t\t\t\ttemplateUrl: 'pages/core/notify.html?v.1.01.04',\n\t\t\t\t\tparent: angular.element(document.body),\n\t\t\t\t\t//targetEvent: ev,\n\t\t\t\t\tclickOutsideToClose:true,\n\t\t\t\t\tfu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if value is a real ES class in Native / Node code. See:
function isNativeClass(component) { return typeof component === 'function' && /^\s*class\s+/.test(component.toString()); }
[ "static getType(val) {\n\n if (val instanceof Node) {\n return \"NODE\";\n }\n\n if (typeof(val) === \"string\") {\n return \"STRING\";\n }\n\n if (val instanceof _Node_main_js__WEBPACK_IMPORTED_MODULE_2__.default) {\n return \"YNGWIE\";\n }\n\n return undefined;\n\n }", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a row value based on row and column name
function get_row_val(row, colname) { var found = 0; var numcols = L_column_names.length; for (var col=0; col<numcols; col++) { if (L_field_names[col]==colname) { return L_trows[row][col]; } } return null; }
[ "function getCell(row, col) {\n return document.getElementById(`cell-${row}-${col}`);\n }", "function getRowText(row,col) {\r\n\treturn installRows[row].children[col].textContent;\r\n}", "function row(table, column, match, val_column) {\n for (var i = 0; i < table.data.length; i++) {\n var uc = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
resetNextUnitOfWork mutates the current priority context. It is reset after after the workLoop exits, so never call resetNextUnitOfWork from outside the work loop.
function resetNextUnitOfWork() { // Clear out roots with no more work on them, or if they have uncaught errors while (nextScheduledRoot !== null && nextScheduledRoot.current.pendingWorkPriority === NoWork$2) { // Unschedule this root. nextScheduledRoot.isScheduled = false; // Read the next poi...
[ "function clearStepOrders() {\n var steps = $steps();\n\n $steps().each(function(idx) {\n setStepOrder($(this), idx + 1);\n });\n }", "function resetChain() {\n\t\t\tchain = {};\n\t\t}", "resetUserPayment() {\n Object.keys(this._paidMoney).forEach(key => (this._paidMone...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Syncs an LView instance with its blueprint if they have gotten out of sync. Typically, blueprints and their view instances should always be in sync, so the loop here will be skipped. However, consider this case of two components sidebyside: App template: ``` ``` The following will happen: 1. App template begins process...
function syncViewWithBlueprint(tView, lView) { for (let i = lView.length; i < tView.blueprint.length; i++) { lView.push(tView.blueprint[i]); } }
[ "attachView(viewRef) {\n (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();\n const view = viewRef;\n this._views.push(view);\n view.attachToAppRef(this);\n }", "function notifyObservers() {\n _.each(views, function (aView) {\n aView.update();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the object containing each armor piece sorted by which armor skills it contains Called once when the first search is made
function setABS(){ // Create a blank version of the skillList let newObj = Object.assign({}, skillList); for(let key of Object.keys(newObj)){ newObj[key] = [] } armorsBySkill = { "head": newObj }; armorsBySkill["chest"] = JSON.parse(JSON.stringify(newObj)); armorsBySkill["arms"] = JSON.parse(JSO...
[ "function getMatchingPieces(){\n let ret = {\n \"head\": new Set(),\n \"chest\": new Set(),\n \"arms\": new Set(),\n \"waist\": new Set(),\n \"legs\": new Set()\n }\n \n // Add each required skill's pieces to the set by name\n // For each armor type (head, chest, ...)\n let realSearch = false;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the given properties match those of a `PrefixLevelStorageMetricsProperty`
function CfnStorageLens_PrefixLevelStorageMetricsPropertyValidator(properties) { if (!cdk.canInspect(properties)) { return cdk.VALIDATION_SUCCESS; } const errors = new cdk.ValidationResults(); if (typeof properties !== 'object') { errors.collect(new cdk.ValidationResult('Expected an obje...
[ "function CfnStorageLens_PrefixLevelPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the debt to finished on the current date in the database
function updateDebtFinished(token, debtID) { try { var userData = validateToken(token); var userEmail = userData.email; var updateQuery = 'UPDATE Debts SET dateFinished=CURDATE(), lastUpdated=CURRENT_TIMESTAMP WHERE email=? AND debtID=?;'; var parameters = [userEmail, debtID]; executeManipulationQ...
[ "function updateDebtTotalPaid(token, debtID, newTotalPaid) {\n try {\n var userData = validateToken(token);\n var userEmail = userData.email;\n var updateQuery = 'UPDATE Debts SET totalPaid=?, lastUpdated=CURRENT_TIMESTAMP WHERE email=? AND debtID=?;';\n var parameters = [newTotalPaid, userEmail, debtI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get own property names from Node prototype, but only the first time `Node` is instantiated
function lazyKeys() { if (!ownNames) { ownNames = Object.getOwnPropertyNames(Node.prototype); } }
[ "getProps(){\n let properties = new ValueMap();\n let propWalker = this;\n\n while(propWalker.__type<0x10){\n for(let [k,v] of propWalker.__props){\n properties.set(k,v);\n }\n propWalker = propWalker.getProp(\"__proto__\");\n };\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions to access fragments: superclass for Document and Doc (from Group), not supposed to be created directly
function WithFragments() {}
[ "getHTML() {\n return getHTMLFromFragment(this.state.doc.content, this.schema);\n }", "function myExtractContents(range) {\n // \"Let frag be a new DocumentFragment whose ownerDocument is the same as\n // the ownerDocument of the context object's start node.\"\n var ownerDoc = range.startContai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the meta data by model and id
function data(model, id) { if (!metaData || !metaData[model] || !metaData[model][id]) { return false; } return metaData[model][id]; }
[ "function refreshMetaData(model, id, callback) {\n function successHandler(response) {\n if (!metaData[model]) {\n metaData[model] = {};\n }\n\n metaData[model][id] = response;\n }\n\n if (!id) {\n id = ids[model].join(',');\n }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publishes the current draft (backend) and redirects to its view URL.
async publish(draftLinks) { return this.apiClient.publishDraft(draftLinks); }
[ "async publish(req, draft, options = {}) {\n const m = self.getManager(draft.type);\n return m.publish(req, draft, options);\n }", "function forwardDraft(id) {\n try {\n \n //Logger.log(\"\\n\"+\"Pre Get draft\"+\"\\n\");\n var message = GmailApp.getDraft(id);\n //Logger.log(\"\\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch a blob using ajax. This reveals bugs in Chrome < 43. For details on all this junk:
function _blobAjax(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function() { if (xhr....
[ "function getFileBlob(url, cb) {\n var xhr = new XMLHttpRequest() //creo una nueva instancia de XMLHttpRequest\n xhr.open('GET', url) //inicializo una peticion asincronica del url al server\n xhr.responseType = \"blob\" // declaro que el valor del tipo de respuesta es blob (para luego usarlo mas adel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
bundle lambda project to zip
function bundle(lambdaPackagePath, outputZip, opts) { if (outputZip === void 0) { outputZip = './build.zip'; } return __awaiter(this, void 0, void 0, function () { var lambdaConfigPathSrc, lambdaConfigPathDst, lambdaConfig, buildPath; return __generator(this, function (_a) { if (!val...
[ "function archive() {\n var time = dateFormat(new Date(), \"yyyy-mm-dd_HH-MM\");\n var pkg = JSON.parse(fs.readFileSync(\"./package.json\"));\n var title = pkg.name + \"_\" + time + \".zip\";\n\n return gulp\n .src(PATHS.package)\n .pipe($.zip(title))\n .pipe(gulp.dest(\"packaged\"));\n}", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns compiled LLL code.
eth_compileLLL(code) { return this.request("eth_compileLLL", Array.from(arguments)); }
[ "function compile_lit(env, expr) { \n \n if (expr === undefined || expr === null) {\n return JSON.stringify(expr); \n }\n\n if (expr.constructor === Number || expr.constructor == Boolean) {\n return JSON.stringify(expr);\n }\n\n return undefined;\n}", "function compile(code, output...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates over the arrows collection repositionating each arrow
positionate () { foreach(arrow => arrow.positionate(), this.arrows) }
[ "function initArrows() {\n\n\t\tvar arrowNumber = $scope.round.arrowNumber,\n\t\t\tendNumber = $scope.round.endNumber;\n\n\t\tfor (var i = 0, j = 0;\n\t\t\ti < endNumber && j < arrowNumber;\n\t\t\tj++, i = (j === arrowNumber) ? i + 1 : i, j = (j === arrowNumber) ? j = 0 : j)\n\t\t{\n\n\t\t\tif (j === 0) {\n\n\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
do two rectangles overlap ?
function overlap_rect(o1, o2, buf) { if (!o1 || !o2) return true; if (o1.x + o1.w < o2.x - buf || o1.y + o1.h < o2.y - buf || o1.x - buf > o2.x + o2.w || o1.y - buf > o2.y + o2.h) return false; return true; }
[ "overlap (other = new Rectangle())\n {\n let olWidth = Math.min(this.position.x + this.width, other.position.x + other.width) - Math.max(this.position.x, other.position.x);\n let olHeight = Math.min(this.position.y + this.height, other.position.y + other.height) - Math.max(this.position.y, other.po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Manages a process's execution for the given amount of time Processes that have had their states changed should not be affected Once a process has received the alloted time, it needs to be dequeue'd and then handled accordingly, depending on whether it has finished executing or not
manageTimeSlice(currentProcess, time) { // manageTimeSlice() is only for handling a running process. If blocking process, handle it differently if (currentProcess.isStateChanged()) { this.quantumClock = 0; // so that the next process that gets dequeued starts off with its full time. return; } ...
[ "doBlockingWork(time) {\n const process = this.peek();\n process.executeBlockingProcess(time);\n this.manageTimeSlice(process, time);\n }", "doCPUWork(time) {\n const process = this.peek();\n process.executeProcess(time);\n this.manageTimeSlice(process, time);\n }", "run() {\n // Executes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts OpenTelemetry SpanAttributes and SpanStatus to Zipkin Tags format.
function _toZipkinTags(attributes, status, statusCodeTagName, statusDescriptionTagName, resource) { const tags = {}; for (const key of Object.keys(attributes)) { tags[key] = String(attributes[key]); } tags[statusCodeTagName] = String(api.SpanStatusCode[status.code]); if (status.message) { ...
[ "function toZipkinSpan(span, serviceName, statusCodeTagName, statusDescriptionTagName) {\n const zipkinSpan = {\n traceId: span.spanContext.traceId,\n parentId: span.parentSpanId,\n name: span.name,\n id: span.spanContext.spanId,\n kind: ZIPKIN_SPAN_KIND_MAPPING[span.kind],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the specified valid_elements string and adds to the current rules This function is a bit hard to read since it's heavily optimized for speed
function addValidElements(valid_elements) { var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, key, value, elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)\...
[ "function applyRules( languageNode, contextNode, sString, parsedCodeNode)\n{\n\tvar regExp, arr,sRegExp;\n\tvar ruleNode,newNode, newCDATANode;\n\n\t// building regExp \n\tsRegExp=contextNode.attributes.getNamedItem(\"regexp\").value;\n\tvar regExp = new RegExp( sRegExp, \"m\" );\n\n\twhile (sString.length > 0)\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates unique and duplicate hashes for bnodes
function hashBlankNodes(unnamed) { var nextUnnamed = []; var duplicates = {}; var unique = {}; // hash quads for each unnamed bnode jsonld.setImmediate(function() {hashUnnamed(0);}); function hashUnnamed(i) { if(i === unnamed.length) { // done, name blank nodes return name...
[ "@computed get uniqueKey(): string {\n const hash = this.block == null ? 'undefined' : this.block.Hash;\n return `${this.txid}-${this.state}-${hash}`;\n }", "function NewHash() {\n return blakejs_1[\"default\"].blake2bInit(32, null);\n}", "function HashAll() {\n var args = [];\n for (var _i = 0;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches a URL using the SP.RequestExecutor library.
fetch(url, options) { if (typeof SP === "undefined" || typeof SP.RequestExecutor === "undefined") { throw new SPRequestExecutorUndefinedException(); } const addinWebUrl = url.substring(0, url.indexOf("/_api")), executor = new SP.RequestExecutor(addinWebUrl); let headers ...
[ "static Request(url) {\n\t\tvar d = Core.Defer();\n\t\tvar xhttp = new XMLHttpRequest();\n\t\t\n\t\txhttp.onreadystatechange = function() {\n\t\t\tif (this.readyState != 4) return;\n\t\t\n\t\t\t// TODO : Switched to this.response, check if it breaks anything\n\t\t\tif (this.status == 200) d.Resolve(this.response);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[[Cell, ...] ...] > Board Create a Board object from the given JSON representation.
function jsonToBoard(boardSpec) { let workerList = []; let initBoard = []; if (boardSpec.length < constants.BOARD_HEIGHT) { let initHeight = boardSpec.length; for (let i = 0; i < constants.BOARD_HEIGHT - initHeight; i++) { boardSpec.push([0,0,0,0,0,0]); } } boardSpec.forEach((r) => { i...
[ "static parse(boardJson)\n {\n // create a new board instance from jsonData\n var board = new Board(boardJson.id,boardJson.name, null);\n var cards = [];\n \n // Parse all cards\n boardJson.cards.forEach(cardJson => {\n\n var card = Card.parse(cardJson)\n cards.push(card)\n });\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new route with two new places and when the operation is done, recall handler.
function create_new_route(newPlace, handler){ newStart = newPlace[0]; newDest = newPlace[1]; /*Create an array with all the places to visit.*/ var places = placesVisited.slice(); places.push(newStart); places.push(newDest); /*Create the request for matrix distances service.*/ var reque...
[ "function route2Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::AppMesh::GatewayRoute.GrpcGatewayRoute` resource
function cfnGatewayRouteGrpcGatewayRoutePropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnGatewayRoute_GrpcGatewayRoutePropertyValidator(properties).assertSuccess(); return { Action: cfnGatewayRouteGrpcGatewayRouteActionPropertyToCloudForma...
[ "function cfnRouteGrpcRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnRouteGrpcRouteActionPropertyToCloudFormation(properties.action),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select iradio as input source
selectInputSourceIradio() { this._selectInputSource("i_iradio"); }
[ "static set radioButton(value) {}", "static get radioButton() {}", "radioSelectedHandler(e) {\r\n this.radioSelect = e.detail;\r\n }", "function radioClickEvent(name){\n\n\tradioButtonControl(name);\n\t$('input[name='+name+']').click(function() {radioButtonControl(name);});\n\t\n}", "selectInputSo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper to create a window with a canvas Returns the canvas directly.
createWindowWithCanvas(name, options = {}) { let canvas = document.createElement('canvas'); return this.createWindow(canvas, name, options); }
[ "function createProcessingWindow(canvas) {\n\n }", "_createCanvas(props) {\n let canvas = props.canvas; // TODO EventManager should accept element id\n\n if (typeof canvas === 'string') {\n canvas = document.getElementById(canvas);\n Object(_utils_assert__WEBPACK_IMPORTED_MODULE_16__[\"default\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the name and description of an element, using a default value for the name if none is given.
getNameDescription(instance, element, defaultValue='') { instance.name = this.v(element, 'meta.title', defaultValue); instance.description = this.v(element, 'meta.description', ''); instance.nameSourcemap = this.s(element, 'meta.title'); instance.descriptionSourcemap = this.s(element, 'meta.description...
[ "static getByName(name) {\n var elt = elts['elements'];\n var number = -1;\n for (var i = 0; i < elt.length; i++) {\n if (elt[i].name.split(' ')[0].toLowerCase() === name.toLowerCase()) {\n number = i + 1;\n }\n }\n\n if (number > 0) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add donate me button
function addDonateToMeButton( idForm ) { // Donate me button var pos = $( idForm ).children( "center" ); var donateMe = $( "<input type='submit' id='donateMe' value='Donate me' />" ); pos.append( donateMe ); var id; var link = $( "#userName" ).attr( "href" ); var split = link.split( "?id=" ); ...
[ "function donateClick(e) {\n\tupdateTrophy(1); // donate10\n}", "function addGooglePayButton() {\n var paymentsClient = getGooglePaymentsClient();\n var button = paymentsClient.createButton({\n onClick: onGooglePaymentButtonClicked,\n buttonColor: \"black\",\n buttonType: \"short\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is called when Rollup finds an error on the build process. It just logs an error message.
_onError(target, event, fatal = false) { const message = fatal ? 'The Rollup build can\'t be created' : 'There was a problem while creating the Rollup build'; this.appLogger.error(message); if (event.error) { this.appLogger.error(event.error); } if (fatal) { process.exit(1); ...
[ "errorHandler(err, invokeErr) {\n const message = err.message && err.message.toLowerCase() || '';\n if (message.includes('organization slug is required') || message.includes('project slug is required')) {\n // eslint-disable-next-line no-console\n console.log('Sentry ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
angular.module('transportista.controller', ['transportista.service','ui.bootstrap', 'cuenta.service']); transportistaCrtl
function transportistaCrtl(transportistaService) { var vm = this ; vm.tr_activos = 0 ; vm.tr_inactivos = 0 transportistaService.get_countTransp().then( function(response){ console.log(response) ; if (!res...
[ "function FCCtrl($filter, $location, FCService) {\n\n\t\t\t\tvar vm = this;\n\n\t\t\t\t//Storage of array fund clusters\n\t\t\t\tvm.fcs = [];\n\t\t\t\t//Parameters for smart-table\n\t\t\t\tvm.itemsToDisplay = [];\n\t\t\t\tvm.itemsPerPage = 0;\n\n\t\t\t\t//Function for getting all the fund cluster data from server v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: getSelectedNode DESCRIPTION: Get pointer to the node that should be highlighted when the SB instance is selected in the SBI. ARGUMENTS: none RETURNS: node pointer
function ServerBehavior_getSelectedNode() { return this.selectedNode; }
[ "function getSelected() {\n\t\t\tif (!activeElement) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tvar elem = document,\n\t\t\t\tpath = JSON.parse(activeElement.getAttribute('data-js-path'));\n\n\t\t\tif (path[0] !== \"\") {\n\t\t\t\tfor (var i = 0, len = path.length; i < len; ++i) {\n\t\t\t\t\telem = elem.childNodes[p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turn object into Data Reportfriendly object for excel sheet takes original excel row returns new (calculated) excel row
function makeDataReportRow(obj) { return { 'Rijlabels': obj.Land, 'Budget spent': parseFloat(obj.AmountSpent.toFixed(2)), 'Impressions': obj.Impressions, 'Website Clicks': obj.WebsiteClicks, 'Website Visits': obj.WebsiteContentViews, 'Purchases [28 Days PC]': obj.Purc...
[ "function constructItemRow(rowObject) {\n // Convert to array.\n var rowDataToAppend = constructArrayFromObject(MERGED_SHEET_HEADERS, rowObject); \n // Add the formulas for columns that don't contain static data.\n rowDataToAppend[ORDER_FULFILLED_COLUMN_INDEX] = \" \";\n rowDataToAppend = addOrderDate(rowDataT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces the active nonterminal using the target production.
function applyProduction($target) { var nonterminal = $activeNonterminal_.html(); var replacementIndex = parseInt($target.attr('cfg-replacement')); var replacement = productions_[nonterminal][replacementIndex]; $('#undo-button').prop('disabled', false); $activeNonterminal_.replaceWith(describeProductionReplac...
[ "function reapplyNonterminalClickEvent() {\n $('#cfg-equation .nonterminal').unbind('click');\n //https://stackoverflow.com/a/44753671\n $('#cfg-equation .nonterminal').on('click', function(event) {\n setActiveNonterminal($(event.target));\n $('#selection-popup').css({left: event.pageX});\n $('#selectio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Purpose: Removes an item from your wishlist
function RemoveFromWishlist( appid ) { $.AsyncWebRequest( 'https://steamcommunity.com/actions/RemoveFromWishlist', { type: 'POST', data: { sessionid: g_sessionID, appid: appid }, error: function() { alert( "Failed to remove this item from your wishlist. Please try again later." ); }, s...
[ "removeItem(item) {\n Items.remove(item._id)\n }", "function removeElementFromList(){\n\n\t\tif(window.confirm(\"By clicking yes you are allowing the almighty Lord to remove this taint!\")){\n\t\t\tvar parentNode = buttons.parentNode;\n\t\t\tthis.parentNode.remove(this);\n\t\t}\n\t}", "function remove...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in a black white run and an array of expected ratios. Returns the average size of the run as well as the "error" that is the amount the run diverges from the expected ratio
function scoreBlackWhiteRun(sequence, ratios) { var averageSize = sum(sequence) / sum(ratios); var error = 0; ratios.forEach(function (ratio, i) { error += Math.pow((sequence[i] - ratio * averageSize), 2); }); return { averageSize: averageSize, error: error }; }
[ "function isAvgWhole(arr) {\n\tlet a = 0;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\ta += arr[i];\n\t}\n\t\n\treturn Number.isInteger(a / arr.length);\n}", "#rms(array) {\n const squares = array.map((value) => value * value);\n const sum = squares.reduce((accumulator, value) => accumulator + value);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a string itself or null
function stringOrNil(obj) { return (toString.apply(obj) === "[object String]" && obj) || null; }
[ "function string_4(ms) /* (ms : maybe<string>) -> string */ {\n return (ms == null) ? \"\" : ms.value;\n}", "function toBlank( str ) {\r\n\tif( str == undefined || str == null ) {\r\n\t\treturn \"\";\r\n\t} else {\t\t\r\n\t\treturn str;\r\n\t}\r\n}", "function SysFmtNullOrEmptyToString(){}", "function Strin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Progression 8: Change all chocolates of ____ color to ____ color and return [countOfChangedColor, chocolates]
function changeChocolateColorAllOfxCount(chocolates, color, finalColor) { var number = 0; // If change color of the color are same then error message show if (color == finalColor) { return "Can't replace the same chocolates"; } // change color instead of intial color and count of finalColo...
[ "function chooseFinalColor(){\n //code colors at the beggiing has value -1 which mean not find\n var white = -1;\n var orange = -1;\n var red = -1;\n var blue = -1;\n var yellow = -1;\n //array to put code colors from all ingredients\n var colorCode = [];\n //putting code colors in array\n for(var i =0; i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorates an object with destroy logic (implementing the DestroyRef interface) and returns the enhanced object.
function addDestroyable(obj) { var destroyFn = null; obj.destroyed = false; obj.destroy = function () { destroyFn && destroyFn.forEach(function (fn) { return fn(); }); this.destroyed = true; }; obj.onDestroy = function (fn) { return (destroyFn || (destroyFn = [])).push(fn); }; re...
[ "destroy() {\n if (this._destroyed) {\n throw new RuntimeError(406 /* RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED */, ngDevMode && 'This instance of the `ApplicationRef` has already been destroyed.');\n }\n const injector = this._injector;\n // Check that this injector ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test: createQueryFromJson(jsonQuery) Creating query for: CORRELATION
function testCreateQueryFromJsonCorrelation() { // Call the function to test var generatedOutput = createQueryFromJson(jsonQueryCorrelation); var expectedOutput = 'Correlation between Unit Cost and Total for each Item'; // Checking if generated output is same as expected output assertEquals(expectedOu...
[ "function testCreateQueryFromJsonTrend() {\n // Call the function to test\n var generatedOutput = createQueryFromJson(jsonQueryTrend);\n var expectedOutput = \n 'Monthly trend of Sum of Units where Item is In Binder, Pencil, Pen' +\n ' from OrderDate 2019-01-06 to 2019-07-12';\n \n // Checking if generat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CommentCard: Presentational component that is passed a handleDelete function to dispatch a delete comment action Parent: CommentList
function CommentCard({id, text, handleDeleteComment}) { const handleDelete = evt => { handleDeleteComment(id); } return ( <div className="comment-card"> <p className="comment-text">{text}</p> <button onClick={handleDelete} className="comment-delete-button">X</button> </div>); }
[ "onDeleteClick(id){\r\n\t\tthis.props.removePost(id)\r\n\t}", "_getComments(){\r\n \r\n // JSX\r\n let commentJSX = this.state.commentList.map(comment => {\r\n return(<Comment comment_key={comment.id} \r\n commentdata={comment} \r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by Python3Parsersmall_stmt.
visitSmall_stmt(ctx) { console.log("visitSmall_stmt"); if (ctx.expr_stmt() !== null) { return this.visit(ctx.expr_stmt()); } else if (ctx.del_stmt() !== null) { return this.visit(ctx.del_stmt()); } else if (ctx.pass_stmt() !== null) { return thi...
[ "visitCompound_stmt(ctx) {\r\n console.log(\"visitCompound_stmt\");\r\n if (ctx.if_stmt() !== null) {\r\n return this.visit(ctx.if_stmt());\r\n } else if (ctx.while_stmt() !== null) {\r\n return this.visit(ctx.while_stmt());\r\n } else if (ctx.for_stmt() !== null) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
THE FOLLOWING FUNCTIONS ARE NOT PUBLIC. DO NOT CALL THEM DIRECTLY. / MM_FlashLatestPluginRevision() look up latest Flash Player plugin revision for this platform Synopsis: MM_FlashLatestPluginRevision(playerVersion) Arguments: playerVersionplugin version to look up revision of Returns: The latest available revision of ...
function MM_FlashLatestPluginRevision(playerVersion) { var latestRevision; var platform; if (navigator.appVersion.indexOf("Win") != -1) platform = "Windows"; else if (navigator.appVersion.indexOf("Macintosh") != -1) platform = "Macintosh"; else if (navigator.appVersion.indexOf("X11") != ...
[ "async function getLatestRevision() {\n const result = await getFileRevision({ accessToken, path });\n return result;\n }", "function MM_FlashCanPlay(contentVersion, requireLatestRevision)\r\n{\r\n var canPlay;\r\n\r\n if (this.version)\r\n {\r\n\tcanPlay = (parseInt(contentVersion) <= this.versio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete pending accountlinks OnComplete
function DeletePendingAccountLinksOnComplete() { isajaxrunning = false; //Hide spinner and reset margin $('#modal-account-pending-guestaccounts-remove-spin').css('display', 'none'); $('#modal-account-pending-guestaccounts-remove-spin').prev().css('margin-left', ''); //Enable su...
[ "function DeletePendingAccountLinksOnBegin() {\n isajaxrunning = true;\n\n //Show spinner and add margin to submit button text\n $('#modal-account-pending-guestaccounts-remove-spin').css('display', '');\n $('#modal-account-pending-guestaccounts-remove-spin').prev().css('margin-left', '17...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a string describing the textbook and the sources of its elements
function describeTextbook() { var textbookString = brackets.currentTextbook.name; textbookString += " by " + brackets.currentTextbook.author + "\n"; var numberOfElements = brackets.currentTextbook.elements.length; for (var i = 0; i < length; i++) { textbookString += "\n" + i + ": "; switch(brackets.currentTextb...
[ "function gotHamletTestamentData () {\n // Join the two texts together into a single string\n let allText = hamletText + ' ' + oldTestamentText;\n // Create a Markov chain generator\n markov = new RiMarkov(4);\n // Load the string of both books into the Markov generator\n markov.loadText(allText);\n // Gener...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a text function and width function, truncates the text if necessary to fit within the given width.
function truncateText(text, width) { return function(d, i) { var t = this.textContent = text(d, i), w = width(d, i); if (this.getComputedTextLength() < w) return t; this.textContent = "…" + t; var lo = 0, hi = t.length + 1, x; while (lo < hi) { var...
[ "function truncateWords (longText, numWords) {\n\t// 1. Use the split() function to split the String into an Array\n\tvar arrayOfText = longText.split(\" \");\n\t// 2. Use the length attribut to find the number of words in the Array\t\n\tvar lengthOfArray = arrayOfText.length;\n\t// 3. Determine how many words shou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }