query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Used for /prs now. Unfortunately, because Hipchat's room notifications api is case sensitive and because the res object here stores the room name as all lower case, I have to use the room ID to send notifications. This is the reason for the weird object structure.
function annoyEveryoneWithResponse(res) { var target = res.message.room.toLowerCase(); roomAssociations.forEach(function (association, i, associations) { association.rooms.forEach(function (room, j, rooms) { if (room.name.toLowerCase() == target || (room.old_name && room.old_name.toLowerCase() == target)) { buildHTML(association.repos, function(err, html) { if (err) { res.send("There was a problem..." + "\n" + err); } else if (html) { messageHipchatRoom(room.id, html); } else { res.send("There are no pull requests! (pizzadance)"); } }); } }); }); }
[ "function send_to_ppnr_notif(p,message, message2 = \"None\"){\n var dict = {type : \"notification\", value : message, value2: message2};\n var json_message = JSON.stringify(dict);\n console.log(json_message);\n connection_ppnr = ppnr_dict[\"client_id\"][p];\n connection_ppnr.send(json_message);\n}", "functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create high Score Page template
function createHighScorePageTemplate() { let highScorePageContainer = createDomElement('div', 'high-score-page-container'); let highScoreContainer = createDomElement('div', 'highscore-container'); let highScoreTitle = createDomElement('div', 'highscore-title'); highScoreTitle.innerHTML = 'Highscore'; let homePageBtn = createDomElement('div', 'go-home-btn-container'); homePageBtn.innerHTML = 'Go Home'; homePageBtn.setAttribute('onclick', 'clearPageAndDisplayHomePage("high-score-page-container")'); highScoreContainer.append(highScoreTitle, getHighScoreForUsers(), homePageBtn); highScorePageContainer.append(highScoreContainer); document.body.append(highScorePageContainer); }
[ "function createHomePageTemplate() {\r\n let homePageContainer = createDomElement('div', 'home-page-container');\r\n let homePageContent = createDomElement('div', 'home-page-content');\r\n\r\n let homePageTitleContainer = createDomElement('div', 'home-page-title-container');\r\n homePageTitleContainer.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes all addOnButtons from this input group
function clearAddOnButtons(addOnButtons) { }
[ "function clearAddOns() {\r\n}", "function removeDeleteButtons() {\n\tYUI().use('node', function (Y) {\n\t\tvar allButtons = Y.all('.lfr-ddm-repeatable-delete-button');\n\t\tallButtons.remove();\n\t});\n}", "function clearButtons() {\n const div = document.querySelector('.question__div');\n while (div.fir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a list and tell how many students have more than 20 marks. For checking if the number is greater than 20 or not you will write one more function named isGreaterThen20 and compare and give the result.
function isGreaterThan20(num){ if(num>20){ return true } }
[ "function under50(num) {\n return num < 50;\n}", "function countStudents(arrayOfStudents) {\n const counts = {\n Gryffindor: 0,\n Slytherin: 0,\n Hufflepuff: 0,\n Ravenclaw: 0\n };\n arrayOfStudents.forEach(student => {\n counts[student.house]++;\n document.querySelector(\".gryffindorenliste...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
see readme.txt in parent directory for details dbugScripts will include noncompressed versions of this code if "jsdebug=true" is in the url of this page, otherwise it will execute this code. example: dbugScripts("/the/location/of/my/scripts/",["script1.js","script2.js","etc"]) returns true if scripts are included, otherwise false.
function dbugScripts(G,E){var D=document.cookie.match("(?:^|;)\\s*jsdebug=([^;]*)");var C=D?unescape(D[1]):false;if(window.location.href.indexOf("basePath=this")>0){var F=G.substring(G.substring(7,G.length).indexOf("/")+8,G.length);var A=window.location.href;G=A.substring(A.substring(7,A.length).indexOf("/")+8,A.length)}if(window.location.href.indexOf("jsdebug=true")>0||window.location.href.indexOf("jsdebugCookie=true")>0||C=="true"){for(var B=0;B<E.length;B++){document.write('<script src="'+G+E[B]+'" type="text/javascript"><\/script>')}return true}return false}
[ "function coreScript(src) {\n\t\tvar i;\n\t\tvar coreScriptLocations = [\"WebResource.axd\", \"_layouts\"];\n\t\tfor(i=0; i < coreScriptLocations.length; i++) {\n\t\t\tif(src.indexOf(coreScriptLocations[i]) > -1) {\n\t\t\t\treturn true;\t\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t} // End of function coreScript", "fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The AWS::GuardDuty::Detector resource creates a single Amazon GuardDuty detector. A detector is an object that represents the GuardDuty service. You must create a detector for GuardDuty to become operational. Documentation:
function Detector(props) { return __assign({ Type: 'AWS::GuardDuty::Detector' }, props); }
[ "constructor() { \n \n DetectionDetailsResponse.initialize(this);\n }", "function HitDetector() {\r\n this.xOverlap = [0, 0];\r\n this.yOverlap = [0, 0];\r\n this.overlap = [0, 0, null]; // start, end, axis if any\r\n}", "constructor() { \n \n MachineDetectionConfiguration.init...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a function that is called on the mouseout that turns the text black
function mouseOut(){ document.getElementById("rb").style.color="black"; }
[ "function mouseOut() {\r\n document.getElementsByTagName(\"strong\").style.backgroundColor = \"black\";\r\n}", "function mouseout() {\n d3.select(this).select('text')\n .transition().duration(200)\n .style({opacity: 0.0});\n sizeNodes('artist', node);\n }", "function mouseOutAuthor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A layer blender that uses linear interpolation to merge the results of two layers.
function LayerLerpBlender() { this._blendWeight = null; this._layerA = null; this._layerB = null; }
[ "function linear_interpolate(x, x0, x1, y0, y1){\n return y0 + ((y1 - y0)*((x-x0) / (x1-x0)));\n}", "interpolateTextureBaseColors(val1, val2, alpha = 0.5)\n {\n //TODO\n }", "function interpolate(surfaceLevel, P1, P2, V1, V2){\n let limit = 0.0001;\n if(Math.abs(surfaceLevel-V1)<limit){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to display a chart of a top property topProperty the property to display position the position of the county/city for that property index if it is the 1 or 2 property
function displayChartTopProperty1(topProperty, position, index,chartWidth,chartHeight,fontSize,notePosition) { var props = indicators[topProperty]; //console.log(topProperty); var data = new google.visualization.DataTable(); data.addColumn('string', 'Location'); data.addColumn('number', 'value'/*props[0].proplabel*/); data.addColumn('number', 'value'/*props[0].proplabel*/); data.addColumn('number', 'value'/*props[0].proplabel*/); data.addRows(props.length); for (var i=0; i<props.length; i++) { data.setValue(i, 0, props[i].geolabel); if (props[i].geo == locationURI) data.setValue(i, 3, parseFloat(props[i].val)); else if (props[i].geo == 'Average') data.setValue(i, 2, parseFloat(props[i].val)); else data.setValue(i, 1, parseFloat(props[i].val)); } $('#top-1-position').html("# " + position +"&nbsp;&nbsp;"); $('#top-1-position-description').html("<ul><li>" + props[0].top1label + "<\/li><ul><li>" + props[0].top2label + "</li><ul><li>" + props[0].proplabel + "<\/li><\/ul><\/ul><\/ul>"); var legend = "<div style=\"float:left; font-family: 'Tienne', serif; font-size: 14px;\"><div style=\"width: 15px; height: 15px; background: #736F6E; float:left;\">&nbsp;</div>&nbsp;All counties/cities&nbsp;&nbsp;</div>" + "<div style=\"float:left; font-family: 'Tienne', serif; font-size: 14px;\"><div style=\"width: 15px; height: 15px; background: #382D2C; float:left;\">&nbsp;</div>&nbsp;Average&nbsp;&nbsp;</div> " + "<div style=\"float:left; font-family: 'Tienne', serif; font-size: 14px;\"><div style=\"width: 15px; height: 15px; background: #306754; float:left;\">&nbsp;</div>&nbsp;Current County/City&nbsp;&nbsp;</div>"; $('#top-1-chart-legend-container').html(legend); var barsVisualization = new google.visualization.ColumnChart(document.getElementById('chart_div_top_'+index)); barsVisualization.draw(data, { /*chartArea: {left:25,top:10,width:"75%",height:"70%"},*/ width: chartWidth, height: chartHeight, colors:['#736F6E','#382D2C','#306754'], legend:'none', isStacked:'true', backgroundColor: '#F7F7F7', hAxis:{textStyle: {color: "black", fontName: "sans-serif", fontSize: fontSize} } }); //, vAxis: {title:'hola', titleTextStyle:'', color: '#FF0000' } $('#top-1-chart-notes-description').css("top",""+notePosition+"px"); $('#top-1-chart-notes-description').html("Place your mouse over each bar to get more information."); }
[ "function displayChartTopProperty2(topProperty, position, index,chartWidth,chartHeight,fontSize,notePosition) {\n\t\tvar props = indicators[topProperty];\n\t\t//console.log(topProperty);\n\n\t\tvar data = new google.visualization.DataTable();\n data.addColumn('string', 'Location');\n data.addColumn('n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
implementing the HTML template for the tooltip will display: name, university, count, years coauthored and instruction
function constructTooltipHTML(d){ var name = d.name; var count = d.count; var university = d.university; var years = d.dates.toString(); var find =','; var re = new RegExp(find,'g'); var fYears = years.replace(re,', '); var html = '<div class="panel panel-primary">' + '<div class="panel-heading">' + name + '</div>' + '<div class="panel-body">' + '<p><strong class="tooltip-body-title">University: </strong>' + university + '</p><p><strong class="tooltip-body-title">Number of times coauthored: </strong>' + count + '</p><p><strong class="tooltip-body-title">Years Co-Authored: </strong>' + fYears + '</p>' + '<p>Double-Click to go to ' + name + '\'s</p>'+ '</div></div>'; return html; }
[ "generateToolTip() {\n //Order the data array\n let data = formatArray.collectionToBottom(this.data, ['Database IDs', 'Comment']);\n\n if (!(data) || data.length === 0) {\n return generate.noDataWarning(this.name);\n }\n\n //Ensure name is not blank\n this.validateName();\n\n if (!(this.da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function to register `ReplaceHandler`.
function registerReplaceHandler(keyword, handler) { replaceHandlers[keyword] = handler; }
[ "function makeReplaceFunction(values) {\n return function(match, id) {\n values.push(id);\n return '';\n };\n }", "use(pattern, fn) {\n this.handlerChain = this.handlerChain.concat([{ pattern, fn }]);\n this.setMiddlewares();\n }", "function registerBlockAndReloadHandlers() {\n // Unreg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a straight line segment. (2d)
function generateStraightLineSegment(startPoint, endPoint, howManyPoints) { if (howManyPoints === void 0) { howManyPoints = 100; } // y = kx + b var k = (endPoint[1] - startPoint[1]) / (endPoint[0] - startPoint[0]), b = endPoint[1] - k * endPoint[0]; var fn = function (x) { return k * x + b; }; var step = Math.abs(startPoint[0] - endPoint[0]) / howManyPoints; // if (step < 0.001 || step === NaN) { // throw `[generateStraightLineSegment] Too many points for this line segment. step=${step}` // } var cx = startPoint[0], res = []; for (var i = 0; i < howManyPoints; i++) { res.push([cx, fn(cx)]); cx += step; } return res; }
[ "function lineSegment(x, y, w, h) {\r\n fill(255, 234, 0);\r\n rect(x, y - 4, w, h);\r\n}", "function drawLineSegment(x1, y1, x2, y2, color, width) {\n if (color == undefined) color = colors[0];\n if (width == undefined) width = LINE_WIDTH;\n\n\tif(x1 != NaN && y1 != NaN && x1 != NaN && y2 != NaN && math....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The AWS::ECS::Cluster resource creates an Amazon Elastic Container Service (Amazon ECS) cluster. This resource has no properties; use the Amazon ECS container agent to connect to the cluster. For more information, see Amazon ECS Container Agent in the Amazon Elastic Container Service Developer Guide. Documentation:
function Cluster(props) { return __assign({ Type: 'AWS::ECS::Cluster' }, props); }
[ "function Cluster(props) {\n return __assign({ Type: 'AWS::EMR::Cluster' }, props);\n }", "function CacheCluster(props) {\n return __assign({ Type: 'AWS::ElastiCache::CacheCluster' }, props);\n }", "function Cluster(props) {\n return __assign({ Type: 'AWS::DAX::Clu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
bind doubleclick event to hard block
function doubleClick() { var hardBlock = document.getElementsByClassName('m-textblock--hard'); var hBLength = hardBlock.length; var block; var clickCount = 0; var singleClickTimer; function singleClicked() { selectBlock(block); blockCounter.count('states'); } function doubleClicked() { if (!block.classList.contains('m-textblock--hard--red')) { block.classList.add('m-textblock--hard--red'); block.classList.remove('m-textblock--hard--green'); } else { block.classList.remove('m-textblock--hard--red'); block.classList.add('m-textblock--hard--green'); } blockCounter.count('type'); blockCounter.count('states'); } for(var i = 0; i < hBLength; i++) { hardBlock[i].addEventListener('click', function() { block = this; clickCount++; if (clickCount === 1) { singleClickTimer = setTimeout(function() { clickCount = 0; singleClicked(); }, 250); } else if (clickCount === 2) { clearTimeout(singleClickTimer); clickCount = 0; doubleClicked(); } }) } }
[ "function jsDblClick() {\n if (!clicked) {\n clicked = true;\n return true;\n }\n else {\n return false;\n }\n }", "function doubleClick(e) {\n edit_reservation($(this));\n}", "function handleDoubleClick(componentRec)\n{\n\treturn editCFC();\n}", "_onDayDblTap() {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tell client to render landing
function renderLanding() { socket.emit('renderlanding'); }
[ "function renderStartPage() {\n updateView(['.js-start-page']);\n}", "render(config, _caller) {\n this.routingService.go(config);\n }", "function Landing (props) {\n return (\n <div className=\"intro-full ms-hero-img-robots ms-hero-bg-primary color-white ms-bg-fixed\" style={{height: '100%'}}>\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Old XML output from Literature (some others may of used it) May have to turn the passedData into XML to see it nice and cleanly in the console.
function reportCleanXML(passedData){ console.trace(passedData); }
[ "function ProcessableXML() {\n\n}", "function eltreeToXmlString(data) {\n var tag = data.tag;\n var el = '<' + tag + '>';\n\n if(data.text && data.text.trim()) {\n el += data.text.trim();\n } else {\n _.each(data.getchildren(), function (child) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ele is a must param if val not exit, and style_obj is a string ,then get style of ele if val not exit, and style_obj is a obj ,then set style of ele getComputeStyle(ele,null)
function css(ele,style_obj){ if(ele === null || style_obj === null){ return ""; } if(typeof style_obj === "string"){ return ele.style.style_obj; } }
[ "function _getstylevalue(el) {\n if(typeof prop == \"string\"){\n var styleValue;\n var computedStyle = window.getComputedStyle(el).getPropertyValue(prop);\n var stylePropValue = el.style[prop];\n\n if (typeof stylePropValue == \"undefined\" || stylePropValue == \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the set union of two matchplaceholders or null if there is a conflict.
function mergeMatch(match1, match2) { var res = {placeholders:{}}; // Some matches may not have placeholders; this is OK if (!match1.placeholders && !match2.placeholders) { return res; } else if (!match1.placeholders) { return match2; } else if (!match2.placeholders) { return match1; } // Placeholders with the same key must match exactly for (var key in match1.placeholders) { res.placeholders[key] = match1.placeholders[key]; if (match2.placeholders.hasOwnProperty(key)) { if (!_exactMatch(match1.placeholders[key], match2.placeholders[key] )) { return null; } } } for (var key in match2.placeholders) { res.placeholders[key] = match2.placeholders[key]; } return res; }
[ "function findOverlap(word1, word2) {\n\t\t\tif(!canMatchBegin(word1, word2) || !canMatchEnd(word1, word2) || !canMatchLength(word1, word2)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tlet [word1Pattern, word2Pattern] = [wordPattern(word1), wordPattern(word2)]; \n\t\t\tfor(let i = 0, wordMatch; i < word1Pattern.length;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Region Dashboard Response to GET region page
function regionDashboard(req, res){ getAllRegions(function(err, result){ //callback for getting all regions console.log(""+err); if(result.rowCount>=1){ regions = result.rows; sendRegionLayout(req, res, regions ); }else{ sendRegionLayout(req, res, []); } }); }
[ "function showRegion(region) {\n if (region === 'default') {\n regionString = '';\n } else {\n regionString = region;\n }\n if (basicDataLoaded) {\n updateFilter();\n } else {\n console.log('basic data not loaded yet');\n }\n}", "getRegion(region) {\n if (region) {\n return this.promise....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes an indented block of decorator code, wrapped in opening and closing brackets.
writeDecoratorCodeBlock(decoratorName, contents) { this.writeLine(`@${decoratorName}({`); this.increaseIndent(); if (contents) contents(this); this.decreaseIndent(); this.writeLine('})'); return this; }
[ "function syntaxIndentation(cx, ast, pos) {\n return indentFrom(\n ast.resolveInner(pos).enterUnfinishedNodesBefore(pos),\n pos,\n cx\n )\n }", "printBlock(node, parent) {\n let isBlock = t.isBlockStatement(node);\n if (!isBlock) this.indent();\n if (t.isEmptyStatement(n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
text formatting for corpus flag tooltips
function generate_flag_html(index) { var topic_words = reverse_topic_indices[index].replace(/_/g, "<br>"); var text = ""; text += "<span class='flag_title'>Topic " + index + ": "; text += "<br></span>"; text += topic_words; return text; }
[ "static set boldLabel(value) {}", "function toolTipHTML(data) {\n var tip = '',\n i = 0;\n for (var key in data.data) {\n \n // if value is a number, format it as a percentage\n //var value = (!isNaN(parseFloat(data.data[key]))) ? percentFormat(data.data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates radio using model property. Used in modelLoadedCallback. Make sure that this function is only called when: a) model is loaded, b) radio is bound to some property.
function updateRadio() { if (component.property !== undefined) { var value = model.get(component.property); for (var i = 0, len = options.length; i < len; i++) { if (options[i].value === value) { $inputs[i].attr("checked", true); $options[i].addClass('checked'); } else { $inputs[i].removeAttr("checked"); $options[i].removeClass('checked'); } } } }
[ "static set radioButton(value) {}", "syncMarkupWithModel() {\n this.#syncLabel()\n this.#syncWidget()\n }", "static get radioButton() {}", "onModelChange(value) {\n this.newValue = value\n }", "resetRadio() {\n for(var i = 0; i < this.radios.length; i++) {\n this.radios[i].c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hide transparent mobile user icon
function hideMobileIcon () { $('.loader').parent().removeClass('bg--none'); }
[ "function hideAppIcon() {\n if (app.dock) app.dock.hide();\n}", "showToScreenReader() {\n this.adapter_.removeAttr(_constants.strings.ARIA_HIDDEN);\n }", "function showIcon() {\n const user = User.getUser();\n const profileImage = [...document.getElementsByClassName('user-image')];\n profileImage.forEac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes the transformations for the Camera's Top View
function camera_top_view() { camera.rotation.x += Math.PI/2; camera.position.y = 3.4; }
[ "goToTopView() {\n this._camera.position.set(0, 1.5, 0);\n }", "setTopView() {\n\t\t'use strict';\n\t\tvar ratio = 6;\n\t\tvar camera = new THREE.OrthographicCamera(window.innerWidth / - ratio, window.innerWidth / ratio, window.innerHeight / ratio, window.innerHeight / - ratio);\n\n\t\tcamera.position.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
alerts a list of people
function displayPeople(people) { alert(people.map(function (person) { return person.firstName + " " + person.lastName; }).join("\n")); }
[ "function printBadges (names) {\n for (let i = 0; i < names.length; i++) {\n console.log(`Welcome ${names[i]}! You are employee #${i + 1}.`);\n }\n return names;\n}", "function greetPeople(names) {\n\tconst a = [];\n\tfor (let i = 0; i < names.length; i++) {\n\t\ta.push(\"Hello \" + names[i]);\n\t}\n\tretur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
after the component Mounts, it will fetch the preferences and set it to the state selector will parse the res to into the correct format
componentDidMount() { this.initGeolocation(); //should only fetch preferences if the user is logged in and when someone refreshes if(this.props.currentUserId){ this.props.fetchPreference().then(res => { this.setState({categories: Selector.getPreference(res.preference)}) }) } }
[ "_setConfig() {\n this.setState({ config: AuthStore.notifications });\n }", "function loadPreferences() {\n var deferred = $.Deferred();\n\n preferences_resolver.fetch({\n \tstorage: \"user\",\n \tsuccess: function(prefs) {\n \t\tdeferred.resolve(pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to validate admin_email
function ssw_js_validate_email() { var email_regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/; var email = document.getElementById('ssw-steps').admin_email.value; if (!email_regex.test(email)) { document.getElementById("ssw-validate-email-error-label").innerHTML=ssw_email_invalid_msg; document.getElementById("ssw-validate-email-error").style.display="block"; return false; } else { document.getElementById("ssw-validate-email-error").style.display="none"; return true; } }
[ "function email_check() {\r\n email_warn(email_validate());\r\n final_validate();\r\n}", "function setupEmail() {\n var short = $attrs['checkEmail'];\n var shorts = short ? short.split('|') : [];\n var message = nls._(shorts[0] || $attrs['checkEmailMe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Each time this is called, session variable emailAddressId is incremented and then returned. The first id returned will be 5, so 04 can be used for special purposes (such as dummy objects).
function getId() { var nextId = Session.get("emailAddressId") || 4; Session.set("emailAddressId",++nextId); return nextId; }
[ "function uniqueId() {\n return id++;\n }", "#nextId() {\n const nextId = \"id_\" + this.#currentId;\n this.#currentId++;\n return nextId;\n }", "_requestUniqueId() {\n if (uniqueRequestId >= MAX_REQUEST_ID) {\n uniqueRequestId = 0;\n }\n return uniqueRequestId++;\n }"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Navigate to les 7 Page Oef 6.1
function changeLes7Oef61Page() { $.mobile.navigate( "#les7Oef61", { transition: 'slide'} ); }// End function changeLes7Oef61Page()
[ "function changeLes8OefPage() {\n $.mobile.navigate( \"#les8home\", { transition: 'slide'} );\n }// End function changeLes8OefPage()", "function goToPage(pageNr){\r\n\r\n}", "function changeLes7Page() {\n $.mobile.navigate( \"#les7Page\", { transition: 'slide'} );\n }// End function changeLe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read new events from stream
readStream(){ redis.consumeFromQueue(config.EVENTS_STREAM_CONSUMER_GROUP_NAME, this.consumerId, 1, config.EVENTS_STREAM_NAME, false, (err, messages) => { if (err) { this.logger.warn(`Failed to read events. ${err.message}`); } if (messages){ this.logger.log('Received message from event stream.'); this.processMessages(messages); } setTimeout(()=>{ this.readStream(); }, 1000); }); }
[ "function readFilePolling(filename) {\n const stream = createReadStream(filename);\n\n stream.on('readable', () => {\n let data;\n while ((data = stream.read()) !== null) {\n console.log(data);\n }\n });\n}", "parseEvent() {\n\t\tlet addr = ppos;\n\t\tlet delta = this.parseDeltaTime();\n\t\ttrack...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
INITIALISATION DES MODES Reinitialiser_mode_joueur Initialisation_mode_manuel_joueur Application_choix_mode_joueur
function Reinitialiser_mode_joueur(ID) { document.querySelector('.optimisation_' + ID).dataset.mode_opti = 'manuel'; var lignes = document.querySelectorAll('.optimisation_' + ID + ' tr'); Nettoyer_tableau(ID); Initialisation_mode_manuel_joueur(ID); Actualisation_floods(true); }
[ "inicializa(){\n globais.placar = criarPlacar();\n }", "inicializa(){\n globais.flappyBird = criarFlappyBird();\n globais.canos = criarCanos();\n globais.chao = criarChao();\n }", "function User_Insert_Conditionnements_Conditionnements0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function will get entire data entry with a specific shortURL.
function searchByShortUrl(db, shortURL, cb) { let query = { "shortURL": shortURL }; db.collection("urls").findOne(query, cb); }
[ "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('shortlink_shortlink', 'get', kparams);\n\t}", "function readURL(id, callback) {\n \n console.log(\"Attempting database query against id: \" + id);\n \n db.collection(DB_COLLECTION_NAME).findOne({ \"short_url_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a relative fret number to an absolute fret number (single char) (0 never changes)
static rel2abs (relFret, startingFret) { return Chord.fret2char(relFret ? relFret + startingFret - 1 : relFret) }
[ "function _toAbsLength(base, value) {\n\tif (typeof value == 'string' && value.charAt(value.length - 1) == '%') {\n\t\tvar s = value.substring(0, value.length - 1);\n\t\treturn base * Number(s) / 100;\n\t}\n\treturn Number(value);\n}", "function reverseNumber(n) {\n let num = parseFloat(n.toString().split('').rev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns set of all possible actions (i, j) available on the board.
actions(board) { let actions = new Set(); //[]; //let board_arr = [...board]; for (let i = 0; i < 9; i++) { if (board[i] === null) actions.add(i); // changed from tuple to array } return [...actions]; // changed from a set }
[ "getActions() {\n return Object.keys(this.actions)\n .map(a => this.actions[a]);\n }", "getAllLegalMoves(board) {\n\t\t// get i locations of all possible moves, ignoring check\n\t\tlet moveOptions = this.getMoveOptions(board)\n\t\tlet i1 = this.i\n\t\tlet p1 = this.player\n\t\t// console.log(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the post ID selected in postSelector and loads the post into the editor
loadPost() { var id = document.getElementById("postSelector").value; if(id){ this.loadedPost = id; document.getElementById("title").value = this.postArray[id].title; document.getElementById("post").value = this.postArray[id].post; this.setState({value: this.postArray[id].post}); } else{ console.log("Invalid post selected"); } }
[ "listenLoadEditForm() {\n editor.clearMenus();\n const slugs = h.getAfterHash(this.href),\n post = model.getPostBySlugs(slugs);\n\n editor.currentPost = post;\n editor.currentPostType = post.type;\n\n if (editor.currentPostType !== 'settings') {\n view.currentPost = post;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add/remove change event to the element
add_change(func) { this.add_event("change", func); }
[ "on_change(ev){\r\n\t\tthis.val = this.get_value();\r\n\t\t// hack to get around change events not bubbling through the shadow dom\r\n\t\tthis.dispatchEvent(new CustomEvent('pion_change', { \r\n\t\t\tbubbles: true,\r\n\t\t\tcomposed: true\r\n\t\t}));\r\n\t\t\r\n\t\tif(!this.hasAttribute(\"noupdate\")){ //Send valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a tangle payload for a GitHub release.
function tangleRelease(config, progress) { return __awaiter(this, void 0, void 0, function* () { progress("Connecting to GitHub"); let release; try { const octokit = github_1.getOctokit(config.githubToken); release = yield octokit.repos.getReleaseByTag({ owner: config.owner, repo: config.repository, tag: config.releaseTag.replace("refs/tags/", "") }); if (!release) { throw new Error("Unable to retrieve release"); } } catch (err) { if (!err.toString().includes("Not Found")) { throw err; } } if (!release) { throw new Error(`Can not find the release https://github.com/${config.owner}/${config.repository}/releases/tag/${config.releaseTag}`); } progress("Downloading tarball"); const tarBallHash = yield crypto_1.downloadAndHash(release.data.tarball_url, config.githubToken); progress("Downloading zipball"); const zipBallHash = yield crypto_1.downloadAndHash(release.data.zipball_url, config.githubToken); progress("Constructing payload"); const payload = { owner: config.owner || "", repo: config.repository || "", tag_name: release.data.tag_name, name: release.data.name, comment: config.comment, body: release.data.body, tarball_url: release.data.tarball_url, tarball_sig: tarBallHash, zipball_url: release.data.zipball_url, zipball_sig: zipBallHash, assets: undefined }; progress("Processing assets"); if (release.data.assets && release.data.assets.length > 0) { payload.assets = []; for (let i = 0; i < release.data.assets.length; i++) { const assetHash = yield crypto_1.downloadAndHash(release.data.assets[i].browser_download_url, config.githubToken); payload.assets.push({ name: release.data.assets[i].name, size: release.data.assets[i].size, url: release.data.assets[i].browser_download_url, sig: assetHash }); } } progress("Attaching to tangle"); const txHash = yield iota_1.attachToTangle(config.node, config.depth, config.mwm, config.seed, config.addressIndex, config.transactionTag, payload, progress); return { hash: txHash, url: config.explorerUrl.replace(":hash", txHash) }; }); }
[ "function release() {\n /* get commits and make release note */\n githubHelper\n .getTags()\n .then(tags => githubHelper.getTagRange(tags))\n .then(_getCommitLogs)\n .then(_getCommitsWithExistingGroup)\n .then(_makeReleaseNote)\n .then(releaseNote => githubHelper.publishReleaseNote(releaseNote))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an li element representing a line, return which line number it represents.
function getLineNum(element) { while (element && element.tagName !== "LI") { element = element.parentNode; } var lineNum = element && element.className.match(/L(\d+)/)[1]; if (!lineNum) { return; } return parseInt(lineNum, 10); }
[ "getLineNumber(element) {\n if (element &&\n element.nodeName === 'SPAN' &&\n element.getAttribute('class') &&\n element.getAttribute('class').indexOf('os-line-number') > -1) {\n return +element.getAttribute('data-line-number');\n }\n }", "function line...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Random Function to generate process
function GenerateRandomProcess() { let random_process = Math.floor((Math.random() * (process_limit_input)) + 0); return random_process; }
[ "function generateNum() {\n\n /*TODO 2: implement the body of the function here to return a random number between 0 and 1*/\n\n}", "generateSysPres()\r\n {\r\n var sp = Math.floor((Math.random() * 150) + 1)\r\n console.log(sp)\r\n }", "generateTimeSlept()\r\n {\r\n var time = Math...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders circle on latest value
renderCircle() { const x = this.ranges.x(this.data[this.data.length - 1].date); const y = this.ranges.y(this.data[this.data.length - 1].value); this.point = this.svg.select('.circle') .interrupt() .transition() .duration(this.numberGeneratorOptions.interval * 2.5) .attr('transform', `translate(${x}, ${y})`); }
[ "updateCircle() {\n const obj = this.newPos(); // Returns the random values as an object\n // Updates the circles css styling\n this.div.style.left = `${obj.posX}px`;\n this.div.style.bottom = `${obj.posY}px`;\n this.div.style.width = `${obj.radius}rem`;\n this.div.style.he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
call update price function for each fruit
function updatePrice() { for (i=0;i<fruitList.length;i++){ object = $('.fruits').eq(i).data(); object.marketPrice = generateRandomPrice(object.marketPrice); $('.fruits').eq(i).data(object); $('.fruits').eq(i).find('.market-price').text(object.marketPrice); } }
[ "async price_update() {}", "function updateAislePrice(item1, item2, item3, item4) {\n updateItemPrice(item1);\n updateItemPrice(item2);\n updateItemPrice(item3);\n updateItemPrice(item4);\n}", "function priceChange() {\n\tfor (var i = 0; i < fruits.length; i++) {\n\t\tvar randomPrice = randomNumbe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts private & public part of given key to PKCS8 Hex String.
function _rsapem_privateKeyToPkcs8HexString(rsaKey) { var zeroInteger = "020100"; var encodedIdentifier = "06092A864886F70D010101"; var encodedNull = "0500"; var headerSequence = "300D" + encodedIdentifier + encodedNull; var keySequence = _rsapem_privateKeyToPkcs1HexString(rsaKey); var keyOctetString = "04" + _rsapem_encodeLength(keySequence.length / 2) + keySequence; var mainSequence = zeroInteger + headerSequence + keyOctetString; return "30" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence; }
[ "getPrivKey() {\n var output = PrivKeyAsn1.encode({\n d: this.key.priv.toString(10),\n }, \"der\")\n return output.toString('hex')\n }", "encodeKey(key) {\n return `${key.hostname}+${key.rrtype}`\n }", "function pubKey2pubKeyHash(k){ return bytes2hex(Bitcoin.Util.sha256rip...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
class Spark extends Object
function Spark() { }
[ "addSpark(spark){\n if(!spark){\n return;\n }\n this.sparks = [...this.sparks, spark];\n }", "function VaporObject(name) {\n if (typeof name === \"undefined\") { name = \"VaporObject\"; }\n this.Name = name;\n }", "function CSInterface()\n{\n}", "removeSpark(spark){...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace elements inside of coding lines to prevent the display of duplicate empty lines
convertLineBreaksToNonBreaking() { for (const breakEl of document.querySelectorAll('.coding-line br')) { const parentNode = breakEl.parentNode; if (parentNode.childNodes.length === 1) { parentNode.innerHTML = '&nbsp;'; } else { breakEl.remove(); } } }
[ "function fixPerLine(item)\n{\n if( item.value.match(/\\r\\n/) )\n {\n var strings = item.value.split(\"\\r\\n\");\n\n item.value = '';\n\n for( var i = 0; i < strings.length; i++ )\n {\n if( strings[i] != '' )\n {\n strings[i] = strings[i].repl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Busca todos os eventos de um dentista recebe o hash do usuario clinica e o range de datas
function getEventosByDentista(hash, dataInicio, dataFim) { return ApiService .listaTodasEntidades_two_id(entidades.evento, entidades.dentista, hash, {'dataInicio': dataInicio, 'dataFim': dataFim}) .then(function(dados) { return AgendaService.buildEventos(dados); },function(error){ return null; }); }
[ "function buildAccountDataFromListOfEvents (user: User) {\n const account = buildEventsTree(SystemStreamsSerializer.getAccountStreamsConfig(), user.events, {});\n Object.keys(account).forEach(param => {\n user[param] = account[param];\n });\n}", "function getAll() {\r\n var i = 0;\r\n var trans = db....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function stores the data needed to create a slider. Sliders cannot be created unless these two conditions hold true: 1. The page is loaded 2. All the handles and tracks are visible rootPanelId id of the div that encompasses all these divs handleId id of the div that contains the draggable image trackId id of the div that contains the track on which the handle moves initialValue value to which the slider will be initialized maxValue the upper bound of the slider's range increment amount by which the slider can be incremented. The minimum increment that this script currently supports is 0.1 inputElement The element that contains the input which will be bound to the slider
function addFactorSliderData(rootPanelId, handleId, trackId, sampleSpanId, indicatorId, initialValue, minValue, maxValue, increment, inputElement) { // alert('adding factor for ' + handleId + ', ' + trackId + ', ' + initialValue + ', ' + maxValue + ', ' + increment + ', ' + inputElement); var newSliderData = { rootPanelId: rootPanelId, handleId: handleId, trackId: trackId, sampleSpanId: sampleSpanId, indicatorId: indicatorId, initialValue: initialValue, minValue: minValue, maxValue: maxValue, increment: increment, inputElement: inputElement }; factorSliderData[numFactorSliders] = newSliderData; numFactorSliders++; }
[ "function addIndicatorSliderData(rootPanelId, handleId, trackId, initialValue, inputElement, indicator, subPanelId) {\n // alert('adding indicator for ' + handleId + ', ' + trackId + ', ' + initialValue + ', ' + inputElement + ', ' + indicator + ', ' + subPanelId);\n var newSliderData = {};\n newSliderD...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Auto open the popup closest to the user's position from a given layer
function openClosestPopup(layer) { // Max distance to from map center to open popup (in meters) const maxSearchDistance = 2; const closestPointSearch = leafletKnn(layer).nearest(myMap.getCenter(), 1, maxSearchDistance); // If a point was found within the search distance if (closestPointSearch.length > 0) { const closestPoint = closestPointSearch[0].layer; closestPoint.openPopup(); } }
[ "function showPopup(step) {\n //activate Tether\n positionPopup(step);\n\n //nudge the screen to ensure that Tether is positioned properly\n $window.scrollTo($window.scrollX, $window.scrollY + 1);\n\n //wait until next digest\n $timeout(() => {\n //show the popup...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removeResult is to trigger nextQuestion function after 3 sec with incremented trivia.currentSet so it can display next question and answerOptions. removeResult function is executed 3 seconds after timer runs out or if user clicked answerBtn to clean up the unncessary previous game info before next question.
function removeResult() { // increase currentSet trivia.currentSet++ // remove previous result $(".results").text(""); // remove previous answeroption -- does not need it here since the answerBtn should be removed when the timer reaches 0 // $(".answerBtn").remove(); // remove previous gifs $(".result_gif").remove(); // run nextQuestion nextQuestion(); }
[ "function nextQuestion(){\n deleteButton(buttonDiv);\n deleteButton(questionTitle);\n if (q !== questions.length - 1){\n q++;\n showNextQA();\n } else {\n finalScore();\n deleteButton(buttonDiv);\n deleteButton(questionTitle);\n }\n}", "function endQuiz(){\n cle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`peek()` returns the next token without advancing `position`.
function peek() { return tokens[position]; }
[ "peek(){\n\n if(!this.top){\n return 'Stack is empty.';\n\n }\n try{\n return this.top.value;\n } \n catch(err){\n return 'Stack is empty.';\n }\n }", "future() {\n if (this.stack.length === 0) {\n this.pushToken(this.le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove us from `form.fields` on unmount.
componentWillUnmount() { const { form } = this.props if (form) delete form.fields[this.id] }
[ "unregisterForm(form) {\n this.formArray.splice(this.formArray.indexOf(form), 1);\n super.hasUnsavedChanges = this.isAnyFormDirty();\n this.shellCommunicationService.notifyShellAboutUnsavedChanges(this.isAnyFormDirty());\n }", "function clear_form(){\n $(form_fields.all).val('');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
recursively uses all programs in the loop, binding the appropriate textures and setting the appropriate uniforms; the user should only have to call [[draw]] on [[Merger]] and never this function directly
run(gl, tex, framebuffer, uniformLocs, last, defaultUniforms, outerLoop) { let savedTexture; if (this.loopInfo.target !== undefined && // if there is a target switch: (outerLoop === null || outerLoop === void 0 ? void 0 : outerLoop.loopInfo.target) !== this.loopInfo.target) { // swap out the back texture for the channel texture if this loop has // an alternate render target savedTexture = tex.back; if (this.loopInfo.target !== -1) { tex.back = tex.bufTextures[this.loopInfo.target]; } else { if (tex.scene === undefined) { throw new Error("tried to target -1 but scene texture was undefined"); } tex.back = tex.scene; } tex.bufTextures[this.loopInfo.target] = savedTexture; if (settings_1.settings.verbosity > 99) console.log("saved texture: " + savedTexture.name); } // setup for program leaf if (this.programElement instanceof WebGLProgramLeaf) { // bind the scene texture if needed if (this.programElement.totalNeeds.sceneBuffer) { if (tex.scene === undefined) { throw new Error("needs scene buffer, but scene texture is somehow undefined"); } gl.activeTexture(gl.TEXTURE1 + settings_1.settings.offset); if (this.loopInfo.target === -1) { gl.bindTexture(gl.TEXTURE_2D, savedTexture.tex); } else { gl.bindTexture(gl.TEXTURE_2D, tex.scene.tex); } } // bind all extra channel textures if needed for (const n of this.programElement.totalNeeds.extraBuffers) { gl.activeTexture(gl.TEXTURE2 + n + settings_1.settings.offset); gl.bindTexture(gl.TEXTURE_2D, tex.bufTextures[n].tex); } // use the current program gl.useProgram(this.programElement.program); // apply all uniforms for (const effect of this.programElement.effects) { effect.applyUniforms(gl, uniformLocs); } // set time uniform if needed if (this.programElement.totalNeeds.timeUniform) { if (this.timeLoc === undefined || defaultUniforms.timeVal === undefined) { throw new Error("time or location is undefined"); } gl.uniform1f(this.timeLoc, defaultUniforms.timeVal); } // set mouse uniforms if needed if (this.programElement.totalNeeds.mouseUniform) { if (this.mouseLoc === undefined || defaultUniforms.mouseX === undefined || defaultUniforms.mouseY === undefined) { throw new Error("mouse uniform or location is undefined"); } gl.uniform2f(this.mouseLoc, defaultUniforms.mouseX, defaultUniforms.mouseY); } // set count uniform if needed if (this.programElement.totalNeeds.passCount && outerLoop !== undefined) { if (this.countLoc === undefined) { throw new Error("count location is undefined"); } if (outerLoop !== undefined) { gl.uniform1i(this.countLoc, outerLoop.counter); } this.counter++; const mod = outerLoop === undefined ? 1 : outerLoop.loopInfo.num; this.counter %= mod; } } for (let i = 0; i < this.loopInfo.num; i++) { const newLast = i === this.loopInfo.num - 1; if (this.programElement instanceof WebGLProgramLeaf) { if (newLast && last && this.last) { // we are on the final pass of the final loop, so draw screen by // setting to the default framebuffer gl.bindFramebuffer(gl.FRAMEBUFFER, null); } else { // we have to bounce between two textures gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); // use the framebuffer to write to front texture gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex.front.tex, 0); } // allows us to read from `texBack` // default sampler is 0, so `uSampler` uniform will always sample from texture 0 gl.activeTexture(gl.TEXTURE0 + settings_1.settings.offset); gl.bindTexture(gl.TEXTURE_2D, tex.back.tex); // use our last program as the draw program gl.drawArrays(gl.TRIANGLES, 0, 6); if (settings_1.settings.verbosity > 99) { console.log("intermediate back", tex.back.name); console.log("intermediate front", tex.front.name); } // swap back and front [tex.back, tex.front] = [tex.front, tex.back]; // deactivate and unbind all the channel textures needed for (const n of this.programElement.totalNeeds.extraBuffers) { gl.activeTexture(gl.TEXTURE2 + n + settings_1.settings.offset); gl.bindTexture(gl.TEXTURE_2D, null); } gl.activeTexture(gl.TEXTURE1 + settings_1.settings.offset); gl.bindTexture(gl.TEXTURE_2D, null); } else { if (this.loopInfo.func !== undefined) { this.loopInfo.func(i); } for (const p of this.programElement) { p.run(gl, tex, framebuffer, uniformLocs, newLast, defaultUniforms, this // this is now the outer loop ); } } } // swap the textures back if we were temporarily using a channel texture if (savedTexture !== undefined) { const target = this.loopInfo.target; if (settings_1.settings.verbosity > 99) { console.log("pre final back", tex.back.name); console.log("pre final front", tex.front.name); } // back texture is really the front texture because it was just swapped if (this.loopInfo.target !== -1) { tex.bufTextures[target] = tex.back; } else { if (tex.scene === undefined) { throw new Error("tried to replace -1 but scene texture was undefined"); } tex.scene = tex.back; } tex.back = savedTexture; if (settings_1.settings.verbosity > 99) { console.log("post final back", tex.back.name); console.log("post final front", tex.front.name); console.log("channel texture", tex.bufTextures[target].name); } } }
[ "render(program, renderParameters, textures){\n //renders the media source to the WebGL context using the pased program\n let overriddenElement;\n for (let i = 0; i < this.mediaSourceListeners.length; i++) {\n if (typeof this.mediaSourceListeners[i].render === 'function'){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
link to main server, get other nodes' address(for test, address+port), connect with them. If there isn't any node, create genesis block
getNodes() { this.privKey = tools.createPrivKey(); this.publicKey = tools.getPublicKey(this.privKey); const serverSocket = io_cli.connect(config.mainServer, { query: { "link_type":"miner", "port":this.port,//for test "publickey":this.publicKey } }); serverSocket.on('connect', () => { console.log('bootstrapServer is connected'); serverSocket.emit('allNodes'); }) serverSocket.on('disconnect', () => { console.log("bootstrapServer is disconnected.") }) serverSocket.on('allNodes_response', (nodes) => {//addresses of nodes var isNodes = false; for(var each of nodes) { if(each == null || each == this.address) continue; isNodes = true; ((each) => { if(this.nodeRoom[each.address]) return; var eachSocket = io_cli.connect(each.address, { query: { "link_type":"miner", "port":this.port,//for test "publickey":this.publicKey } }); eachSocket.on('connect', () => { console.log(each.address+" is connected."); this.nodeRoom[each.address] = {socket: eachSocket, publicKey: each.publickey}; this.setNodeSocketListener(eachSocket, each.address, each.publickey); eachSocket.on('disconnect', () => { console.log(each.address+" disconnected"); delete this.nodeRoom[each.address]; delete this.sendBlockchainNode[each.address]; eachSocket.removeAllListeners(); }) }) })(each) } if(isNodes == false && this.blockchain.length == 0) { this.createGenesisBlock(); } else { this.getBlockchain(); } console.log('blockchainState:'+this.blockchainState); }) }
[ "function initializeServer(){\n // these are the credentials to use to connect to the Hyperledger Fabric\n let participantId = config.get('participantId');\n let participantPwd = config.get('participantPwd');\n // physial connection details (eg port numbers) are held in a profile\n let connectionProf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gcd(b,s) :: BigNat > Int > Int
function h$ghcjsbn_gcd_bs(b, s) { throw new Error("h$ghcjsbn_gcd_bs not implemented"); }
[ "function coprime(a, b)\n{\n if (__gcd(a, b) === 1)\n console.log(\"1\");\n else\n console.log(\"0\"); \n}", "function greatestCommonDevisor(a, b){\n if (!b) return a;\n\n return greatestCommonDevisor(b, a % b)\n\n}", "function randBigInt_(b,n,s) {\r\n var i,a;\r\n for (i=0;i<b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
You can modify and use this source freely only for the development of application related Live2D. (c) Live2D Inc. All rights reserved. ============================================================ ============================================================ class L2DPhysics ============================================================ ============================================================
function L2DPhysics() { this.physicsList = new Array(); //ArrayList<PhysicsHair> this.startTimeMSec = _live2d.UtSystem.getUserTimeMSec(); }
[ "function setupPhysics(world){\n var fixDef = new b2FixtureDef;\n fixDef.density = DENSITY;\n fixDef.friction = this.isGround ? GROUND_FRICTION : FRICTION;\n fixDef.restitution = RESTITUTION;\n\n var bodyDef = new b2BodyDef;\n bodyDef.type = b2Body.b2_staticBody;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets the default cursor
_setDefault(){ this.defaultCursor = "default"; // this.hOverCursor = "pointer"; }
[ "function changeCursor(cursor) {\n document.body.style.cursor = cursor; \n}", "function setCursor(canvas, image, defaultCursor) {\n canvas.style.cursor = (isIE() ? 'url(images/' + image + '.cur)' :\n 'url(images/' + image + '.svg) ' + + ' ' + curAnnotationXY + ' ' + curAnnotationXY) +\n ', '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
> <toggle state of addanswerfieldbutton and toggle checkbox
function toggleState(qid_length) { //toggle #add-answer-field-button state and text depending on checkboxes' statuses if(qid_length) { $('#add-answer-field-button:button').attr("disabled", false); $('#add-answer-field-button:button').prop('value', 'Select answer field for selected questions'); } else { $('#add-answer-field-button:button').attr("disabled", true); $('#add-answer-field-button:button').prop('value', 'Select questions first...'); } //toggle #toggle checkbox state depending on checkboxes' statuses if(s_qid_len === checkbox_total) //if all questions are checked { $('#toggle').prop('checked', true); //check toggle checkbox } else { $('#toggle').prop('checked', false);//uncheck toggle checkbox } }
[ "function toggleTranscript(dpEntryId){\r\n if($('#iws2_subc_ctnr_isTranscript_op_' + dpEntryId).find('input:checkbox:checked').length == 1){\r\n // $('#iws2_subc_ctnr_isTranscript_op_' + dpEntryId).find('input:checkbox').attr('checked', true);\r\n /*\n var totalDataFields = \r\n for (var i=0;...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write `value` as a 32bit floating number and move pointer forward by 4 bytes.
writeFloat32(value) { this.ensureAvailable(4); this._data.setFloat32(this.offset, value, this.littleEndian); this.offset += 4; this._updateLastWrittenByte(); return this; }
[ "writeValue(buffer, value) {\n assert.isBuffer(buffer);\n const convertedValue = str_to_num_1.default(value);\n if (convertedValue !== undefined)\n value = convertedValue;\n assert.instanceOf(value, Number);\n const byteBuffer = new ArrayBuffer(4);\n new DataView...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Seperator char, usually =
get seperator() { return this._seperator }
[ "function getDelimiter (){\n\t\treturn prompt.delimiter;\n\t}", "set surround_seperator(string){ \n this.seperator_prefix = string\n this.seperator_suffix = string\n }", "function nqfParseChar() {\n if (escape) {\n value += curCh;\n escape = false;\n } else if (curCh =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
speed() changes the playback speed for all or individual playlist~ objects speed all followed by a value impacts the speed of all playlist~ objects speed, file number, and a value impacts an individual playlist~ object
function speed() { if(arguments[0] == "all") { for(i = 0; i < play_num; i++){ pl[i].message("speed", arguments[1]); } } else if (typeof arguments[0] == "number") { pl[(arguments[0]-1)].message("speed", arguments[1]); } }
[ "incrementSpeed() {\n\t\t\tswitch (this.speed)\n\t\t\t{\n\t\t\t\tcase 1000:\n\t\t\t\t\tthis.speed = 2000;\n\t\t\t\tbreak;\n\t\t\t\tcase 2000:\n\t\t\t\t\tthis.speed = 5000;\n\t\t\t\tbreak;\n\t\t\t\tcase 5000:\n\t\t\t\t\tthis.speed = 10000;\n\t\t\t\tbreak;\n\t\t\t\tcase 10000:\n\t\t\t\t\tthis.speed = 20000;\n\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Items are emitted fast, but we only care about the value at periodic intervals.
function emitAndSample() { return Rx.Observable.interval(100) // emit items every 100 ms .sample(500) // only emit one every 500 ms .take(5); // emit up to a max count }
[ "static periodic (n) {\n let id\n\n return new Signal(emit => {\n id = setInterval(() => emit.next(), n)\n return () => clearInterval(id)\n })\n }", "set PreserveSampleRate(value) {}", "stream(value) {\n let out = 0;\n this.filter.pop();\n this.filter.unshift(value);\n\n for (let...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a callback that executes when a remote cursor is added. The underlying event emitter event name is 'remotecursoradd'.
onRemoteCursorAdd(cb) { this.on('remote-cursor-add', cb) }
[ "onRemoteCursorRemove(cb) {\n this.on('remote-cursor-remove', cb)\n }", "onRemoteCursorChangeName(cb) {\n this.on('remote-cursor-change-name', cb)\n }", "function add (callback) {\n multicast.push(callback);\n return callback;\n }", "register(namespace, callback) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Island Count Given a string representation of a 2d map, return the number of islands in the map. Land spaces are denoted by a zero, while water is denoted by a dot. Two land spaces are considered connected if they are adjacent (but not diagonal). (!!!) NOTICE: Newline characters in the inputs have been replaced with tags to make the value easier to read. In other words, when you see a break, it's actually a \n character. Check your console when submitting to see the input for yourself.
function countIslands (mapStr) { var mapArr = mapStr.split('\n').map(function(row) {return row.split("");}); var count = 0; for (var i = 0; i < mapArr.length; i++) { for (var j = 0; j < mapArr[i].length; j++) { if (isLand(mapArr[i][j])) { count += 1; sinkLand(mapArr, i, j); } } } return count }
[ "function getLayerCounts(input, area) {\n const layers = [];\n for (const layer of getLayers(input, area)) {\n const map = {};\n for (let char of layer) {\n map[char] = (map[char] || 0) + 1;\n }\n layers.push(map);\n }\n return layers;\n}", "function countNeighbors(board){\n var nCount = c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the incoming List Alert Request into a common object
function parseListRequest(req){ var reqObj = {}; reqObj.originalUrl = req.originalUrl; reqObj.uid = req.params.guid; reqObj.env = req.params.environment; reqObj.domain = req.params.domain; return reqObj; }
[ "function parseUpdateAlertRequest(req){\n var reqObj = {};\n reqObj.originalUrl = req.originalUrl;\n reqObj.alertName = req.body.alertName;\n reqObj.emails = req.body.emails.split(',');\n reqObj.eventCategories = req.body.eventCategories.split(',');\n reqObj.eventNames = req.body.eventNames.split(',');\n req...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updateDate: Fill the 'Select' with all the dates in the schedule with the data from the database schedule : all the dates from the database
function updateDate(schedule) { var option; if(schedule.length != 0) { $('#date').empty(); $.each(schedule, function(i, week) { option = '<option value="' + week.date + '" data-season="' + week.season + '" data-week="' + week.week + '" >'; option += week.date; option += '</option>'; $('#date').append(option); GAMES[i] = new Array(); for(var j = 0; j < week.games.length; j++) { GAMES[i].push(week.games[j]); } }); } }
[ "function fillDates() {\n\t$.getJSON(\n\t\t'/getScheduleByYear',\n\t\tfunction(data) {\n\t\t\tupdateDate(data);\n\t\t\t$('#season').val($('#date option:selected').data('season'));\n\t\t\t$('#week').val($('#date option:selected').data('week'));\n\t\t\tupdateTimes();\n\t\t\tchangeTeams();\n\t\t\tfillTeamPlayers(true)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given annual income, calculates how much money earned per second.
function calcSalaryPerSecond(income) { return income / SECONDS; }
[ "function calculateInterest(startSaving, years, interest) {\n let endSaving = startSaving;\n\n for (let ix = 1; ix <= years; ix++) {\n endSaving = endSaving * (1 + interest / 100);\n }\n return Math.round(endSaving * 10000) / 10000;\n}", "function calcMoney(rate) {\n // number of seconds since...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit a parse tree produced by KotlinParsertryExpression.
exitTryExpression(ctx) { }
[ "exitJumpExpression(ctx) {\n\t}", "exitBlockLevelExpression(ctx) {\n\t}", "visitExit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "exitConditionalOrExpression(ctx) {\n\t}", "exitElvisExpression(ctx) {\n\t}", "exitIfExpression(ctx) {\n\t}", "exitParenthesizedType(ctx) {\n\t}", "exitStat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wraps an error to be an innererror of our system
static wrap (e, ...args) { if (Errors.hasOwnProperty(e.name)) { return e } if (e.code && Errors.hasOwnProperty(e.code)) { return new Errors[e.code](e) } if (e && typeof e.error === 'object' && Errors.hasOwnProperty(e.error.code)) { return new Errors[e.error.code](e.error) } return new SystemModuleError(e, ...args) }
[ "function wrapError(error, name) {\n if (!TRANSACTION_ERROR_CODES.includes(name)) return Error(`Passed error name ${name} is not valid.`)\n error.code = name\n return error\n}", "handleExecutorError (error) {\n const priv = privs.get(this)\n if (priv.state === State.Done) return\n priv.state = S...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handlers Handler called if user changes the discount field in the sale order line. The wizard will open only if (1) Sale order line is 3 or more (2) First sale order line is changed to discount (3) Discount is the same in all sale order line
_onOpenDiscountWizard(ev) { const orderLines = this.renderer.state.data.order_line.data.filter(line => !line.data.display_type); const recordData = ev.target.recordData; const isEqualDiscount = orderLines.slice(1).every(line => line.data.discount === recordData.discount); if (orderLines.length >= 3 && recordData.sequence === orderLines[0].data.sequence && isEqualDiscount) { Dialog.confirm(this, _t("Do you want to apply this discount to all order lines?"), { confirm_callback: () => { orderLines.slice(1).forEach((line) => { this.trigger_up('field_changed', { dataPointID: this.renderer.state.id, changes: {order_line: {operation: "UPDATE", id: line.id, data: {discount: orderLines[0].data.discount}}}, }); }); }, }); } }
[ "calcDiscount() {\n if (this.discount != 0 || this.discount != null) {\n this.discPrice = (1 - this.discount / 100) * this.totalPrice;\n }\n }", "onAddDiscount() {\n const promotionDiscountRepository = this.repositoryFactory.create(\n this.discounts.entity,\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reflector constructor. See PairMapBase. Additional restriction: every character must be accounted for.
constructor(pairs) { super(pairs, "Reflector"); const s = Object.keys(this.map).length; if (s !== 26) { throw new OperationError("Reflector must have exactly 13 pairs covering every letter"); } const optMap = new Array(26); for (const x of Object.keys(this.map)) { optMap[x] = this.map[x]; } this.map = optMap; }
[ "function Keymap(){\r\n this.map = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\r\n 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'backspace', 'enter', 'shift', 'delete'];\r\n }", "constructor(pairs) {\n super(pairs, \"Plugboard\");\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load a htpasswd file & return it as a map
function load (file) { var map = {}; // read the file synchronously, this isn't a server var content = fs.readFileSync(file, encodingOptions); // split out the lines var lines = content && content.split(/[\r\n]+/g); if (lines) { // For every line lines.forEach(function (line) { // parse out the user & the hash var tokens = line && line.split(/: ?/); // if the line had a : separated string pair, if (tokens.length === 2) { var user = tokens[0]; var hash = tokens[1]; // update the map with the user/hash combination map[user] = hash; } }); } // return the hash object return map; }
[ "function save (map, file) {\n // get the users as an array\n var users = Object.keys(map || {});\n // return if the map was empty or null\n if (users.length === 0) {\n return;\n }\n\n var lines = [];\n // for every user\n users.forEach(function (user) {\n var hash = map[user];\n // generate the : ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This creates the slider with the model values it's called on startup and if the model value changes
function createSlider() { //the value that we'll give the slider - if it's a range, we store our value as a comma separated val but this slider expects an array var sliderVal = null; //configure the model value based on if range is enabled or not if ($scope.model.config.enableRange == true) { //If no value saved yet - then use default value //If it contains a single value - then also create a new array value if (!$scope.model.value || $scope.model.value.indexOf(",") == -1) { var i1 = parseFloat($scope.model.config.initVal1); var i2 = parseFloat($scope.model.config.initVal2); sliderVal = [ isNaN(i1) ? $scope.model.config.minVal : (i1 >= $scope.model.config.minVal ? i1 : $scope.model.config.minVal), isNaN(i2) ? $scope.model.config.maxVal : (i2 > i1 ? (i2 <= $scope.model.config.maxVal ? i2 : $scope.model.config.maxVal) : $scope.model.config.maxVal) ]; } else { //this will mean it's a delimited value stored in the db, convert it to an array sliderVal = _.map($scope.model.value.split(','), function (item) { return parseFloat(item); }); } } else { //If no value saved yet - then use default value if ($scope.model.value) { sliderVal = parseFloat($scope.model.value); } else { sliderVal = $scope.model.config.initVal1; } } // Initialise model value if not set if (!$scope.model.value) { setModelValueFromSlider(sliderVal); } //initiate slider, add event handler and get the instance reference (stored in data) var slider = $element.find('.slider-item').bootstrapSlider({ max: $scope.model.config.maxVal, min: $scope.model.config.minVal, orientation: $scope.model.config.orientation, selection: $scope.model.config.reversed ? "after" : "before", step: $scope.model.config.step, precision: $scope.model.config.precision, tooltip: $scope.model.config.tooltip, tooltip_split: $scope.model.config.tooltipSplit, tooltip_position: $scope.model.config.tooltipPosition, handle: $scope.model.config.handle, reversed: $scope.model.config.reversed, ticks: $scope.model.config.ticks, ticks_positions: $scope.model.config.ticksPositions, ticks_labels: $scope.model.config.ticksLabels, ticks_snap_bounds: $scope.model.config.ticksSnapBounds, formatter: $scope.model.config.formatter, range: $scope.model.config.enableRange, //set the slider val - we cannot do this with data- attributes when using ranges value: sliderVal }).on('slideStop', function (e) { var value = e.value; angularHelper.safeApply($scope, function () { setModelValueFromSlider(value); }); }).data('slider'); }
[ "onSliderValueChanged() {\n this.setBase();\n const label = `${this.name}: ${JSON.stringify(this.value)}`;\n ChromeGA.event(ChromeGA.EVENT.SLIDER_VALUE, label);\n }", "function updateSliderValues() {\n\t$('.slider_min').text(CLUB.lowValue);\n\t$('.slider_max').text(CLUB.highValue);\n}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will throw an error if the protocol wasn't included in the host string
vaidateProtocol(host){ let protocols = ['https://', 'http://']; if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host throw new Error('Host String must include http:// or https://') }
[ "function isValidSchemeUrl(url) {\n // If the scheme is 'javascript:' or 'vbscript:', these link\n // types can be dangerous. Don't link them.\n if (invalidSchemeRe.test(url)) {\n return false;\n }\n var schemeMatch = url.match(schemeUrlRe);\n if (!schemeMatch) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the chat message and sets out the message behavior
_renderChatMessage(message, html, _data) { if (html.find('.narrator-span').length) { html.find('.message-sender').text(''); html.find('.message-metadata')[0].style.display = 'none'; html[0].classList.add('narrator-chat'); if (html.find('.narration').length) { html[0].classList.add('narrator-narrative'); const timestamp = new Date().getTime(); if (message.data.timestamp + 2000 > timestamp) { const content = $(message.data.content)[0].textContent; let duration = this.messageDuration(content.length); clearTimeout(this._timeouts.narrationCloses); this.elements.content[0].style.opacity = '0'; this._timeouts.narrationOpens = setTimeout(this._narrationOpen.bind(this, content, duration), 500); this._timeouts.narrationCloses = setTimeout(this._narrationClose.bind(this), duration); } } else { html[0].classList.add('narrator-description'); } } }
[ "renderChatPage () {\n this.clearShadowRoot()\n this.shadowRoot.appendChild(chatLayoutTemp.content.cloneNode(true))\n this.getElement('#chatUsernameP').textContent = this.username\n\n this.socket.addEventListener('message', this.boundGetMsgFromServer)\n this.getElement('form').addEventListener('submi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fleet Prod type Shortage Update Clond Input fields Indexes
function UpdateIndexFleetShortage(table) { // get every tr element except the header table.find("tr:gt(0)").each(function (i, row) { $(row).find("td:first").html(i + 1); var id = i + 1; $(row).find('.ProdType').parent().attr('for', 'ID' + id + 'ProdType'); $(row).find('.Quantity').parent().attr('for', 'ID' + id + 'Quantity'); $(row).find('.Type').parent().attr('for', 'ID' + id + 'Type'); $(row).find('.Amount').parent().attr('for', 'ID' + id + 'Amount'); $(row).find('.ProdType').attr('id', 'ID' + id + 'ProdType'); $(row).find('.Quantity').attr('id', 'ID' + id + 'Quantity'); $(row).find('.Type').attr('id', 'ID' + id + 'Type'); $(row).find('.Amount').attr('id', 'ID' + id + 'Amount'); $(row).find('.ProdType').attr('name', 'ShortageDamageList[' + id + '].ProdType'); $(row).find('.Quantity').attr('name', 'ShortageDamageList[' + id + '].Quantity'); $(row).find('.Type').attr('name', 'ShortageDamageList[' + id + '].Type'); $(row).find('.Amount').attr('name', 'ShortageDamageList[' + id + '].Amount'); ; $(row).attr('id', 'entryShortDamage' + id); // get every input and select elements $(row).find('input, select').each(function (j, input) { // check whether the id-attribute is of type _[index]__ var id = input.name.match(/\d+/); // if it is an element necessary for the ModelBinder => update the name attribute if (id != null && id.length && id.length == 1) { var attr = $(input).attr("name"); // replace the old index of the name attribute with the calculated index var newName = attr.replace(attr.match(/\d+/), i); $(input).attr("name", newName); } }); }); }
[ "onUpdateInput (e, isSub = false, field = null, index = -1, valueType = null) {\n const { challenge: oldChallenge } = this.state\n const newChallenge = { ...oldChallenge }\n if (!isSub) {\n switch (e.target.name) {\n case 'reviewCost':\n case 'copilotFee':\n newChallenge[e.targe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show the current count of employees
function showCount() { count.textContent = 'Showing '+ employees.length + ' employees'; }
[ "displayLifeCount() {\n\t $('.life-count-txt').text(this.lives);\n\t }", "countEpiniacReports() {\n return this.r.table('epiniac').count().run();\n }", "function recordCount(numRows, $pager) {\n var span = document.createElement(\"span\");\n span.setAttribute(\"class\", \"epic-ui-recordCount...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the entity applicable to whole of current selection. An entity can not span multiple blocks.
getSelectionEntity(editorState) { let entity; const selection = editorState.getSelection(); let start = selection.getStartOffset(); let end = selection.getEndOffset(); if (start === end && start === 0) { end = 1; } else if (start === end) { start -= 1; } const block = this.getSelectedBlock(editorState); for (let i = start; i < end; i += 1) { const currentEntity = block.getEntityAt(i); if (!currentEntity) { entity = undefined; break; } if (i === start) { entity = currentEntity; } else if (entity !== currentEntity) { entity = undefined; break; } } return entity; }
[ "asSingle() {\n return this.ranges.length == 1 ? this : new EditorSelection([this.primary]);\n }", "asSingle() {\n return this.ranges.length == 1 ? this : new EditorSelection([this.primary]);\n }", "asSingle() {\n return this.ranges.length == 1\n ? this\n : new E...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform Delete Operation in Jquery Datatable
function DeleteJDTRow(id, event, TableId, Jsonurl) { if (confirm("Are you sure you want to delete this record...?")) { //var row = $(this).closest("tr"); oTable = $('#' + TableId).DataTable(); //var parent = $(this).parent('td').parent('tr'); var parent = $(event).parents('tr'); $.ajax({ type: "POST", url: Jsonurl, data: '{id: ' + id + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { if (data == "Deleted") { alert("Record Deleted !"); $('#' + TableId).DataTable().row(parent).remove().draw(false); } else { alert("Something Went Wrong!"); } } }); } }
[ "function deleteData() {\r\n var table = $('#delete_table').DataTable();\r\n var selectedCells = table.rows('.selected').data();\r\n var deletionIDs = [];\r\n for (var i = 0; i < selectedCells.length; i++)\r\n deletionIDs.push(selectedCells[i][1]);\r\n if (confirm(\"Are you sure you'd like to ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the index of the currently shown path
getStepIndex(){ var currentPath = this.state.path; return this.findStepIndex(currentPath); }
[ "function getLocationIndex() {\n // Let's see if this works\n if (viewModel.outingState.pathIndex < 0) {\n return 0;\n }\n return state.historyIndex;\n }", "function getBlockIndex() {\n log.debug(\"CALL: getBlockIndex()\");\n for (var index = 0; inde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
baynote_removeHtml(raw) Clean up a string by removing any HTML or patial HTML, new lines, and spaces from both ends. Parameter raw String The raw string to be cleaned. Returns String The cleaned input string
function baynote_removeHtml(raw) { if (!raw) return; raw = raw.replace(/\<[^>]*\>/g, ""); raw = raw.replace(/\<.*/, ""); raw = raw.replace(/\&nbsp;/g, " "); raw = raw.replace(/^\s+/, ""); raw = raw.replace(/\s+$/, ""); raw = raw.replace(/\n/g, " "); return raw; }
[ "cleanupHTML(html) {\n const parser = new DOMParser();\n const document = parser.parseFromString(html, \"text/html\");\n const rootNode = document.body;\n const preprocessedNode = this.preprocessNodes(rootNode);\n const cleanedHtml = DomPurify.sanitize(preprocessedNode.innerHTML, {ALLOWED_TAGS: this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compare two linked lists
function compare(head1, head2){ let curr1 = head1, curr2 = head2 while(curr1 !== null){ if(curr1.data !== curr2.data){ return false } curr1 = curr1.next curr2 = curr2.next } return true }
[ "function deepUnorderedEquals(list1, list2) {\n // recursion base: not lists\n if (!Array.isArray(list1) ||\n !Array.isArray(list2))\n return list1 == list2;\n\n // Unequal length, trivially unequal\n if (list1.length != list2.length)\n return false;\n\n // Try to match up every element in list1 wit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To initialize a new priority queue use: var pq = new buckets.PriorityQueue(compareImportance)
function PQueueInit() { return new buckets.PriorityQueue(); }
[ "function Priority() {\n _classCallCheck(this, Priority);\n\n Priority.initialize(this);\n }", "createQueue(name) {\n const queue = new PriorityQueue(name);\n this.queues[queue.getName()] = queue;\n }", "function PriorityQueue() {\n this.queue = [];\n // Push empty value to fill first slot -...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
imageScaleToSize (iw, ih, scale_w) function for scaling images dinamically based on screen width iw: actual image width, ih: actual image height, scale_w: scale ratio of the image width. if scale_w is 50, then the returned value for width would be 50% of the screen width returns:
function scaleDimsFromWidth(iw, ih, scale_w) { const sw = (scale_w / 100.0) * screen_width; const sh = ih * (sw / iw); return { width: sw, height: sh }; }
[ "function calculateScale(width, height, upperLeftX, upperLeftY, numRows, numCols, squareSize) {\r\n var width0 = upperLeftX + numCols * squareSize + 70 + squareSize + 20 + 3 * squareSize / 2; // formula for total width of the image if no rescaling is done\r\n var height0 = Math.max(upp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Let's define a javascript class for our Musician. The constructor accepts an instrument autodetermind its uuid at every iteration
function Musician(instrumentName) { this.uuid = uuidv4(); this.instrumentName = instrumentName; this.instrumentSound = correspondingSound(this.instrumentName); /* * We will simulate instrument changes on a regular basis. That is something that * we implement in a class method (via the prototype) */ // eslint-disable-next-line func-names Musician.prototype.update = function () { /* * Let's create the measure as a dynamic javascript object, * add the 2 properties (uuid and instrument), auditor will handle activeSince * and serialize the object to a JSON string */ const musicianInfo = { uuid: this.uuid, sound: this.instrumentSound, }; const payload = JSON.stringify(musicianInfo); /* * Finally, let's encapsulate the payload in a UDP datagram, which we publish on * the multicast address. All subscribers to this address will receive the message. */ const message = Buffer.from(payload); s.send(message, 0, message.length, protocol.PROTOCOL_PORT, protocol.PROTOCOL_MULTICAST_ADDRESS, () => { console.log(`Sending payload: ${payload} via port ${s.address().port}`); }); }; /* * Let's take and send a measure every 1 s (1000 ms) */ setInterval(this.update.bind(this), 1000); }
[ "function Instrument (options) {\n\tvar i, waveForm, array, mod;\n\toptions = options || {};\n\n\tif (options.context) {\n\t\tthis.context = options.context;\n\t} else if (options.destination) {\n\t\tthis.context = options.destination.context;\n\t} else {\n\t\tthis.context = new AudioContext();\n\t}\n\tthis.mainGai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Timer function checking the current session state
_onCheckSessionTimer() { const { sessionId } = getProperties(this, 'sessionId'); if (!sessionId) { return; } // debounce: do not run if destroyed if (this.isDestroyed) { return; } debounce(this, this._onCheckSessionTimer, ROOTCAUSE_SESSION_TIMER_INTERVAL); if (!sessionId) { return; } this._checkSession(); }
[ "function idleTimer() {\n if ( isLoggedIn() ) {\n window.sessionStorage.setItem(\"idle-timer\", \"true\");\n idleTimeout(() => {\n window.sessionStorage.clear();\n window.location.replace(`/sign-in/`);\n },\n {\n element: document,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }