query stringlengths 9 34k | document stringlengths 8 5.39M | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
new comment on post (from single post page) in: post id, logged in user id out: updated post | function comment(req, res) {
var loggedInUser = req.user;
var postId = req.params.postId;
if (!ObjectID.isValid(postId)) {
return res.status(404).send({ text: 'Invalid post id' });
}
var comment = new Object();
comment.text = req.body.text;
comment.author = loggedInUser._id;
co... | [
"function commentPost(req, res, next) {\n Post.findById(req.body.post_id, function (err, post) {\n if (err) {\n console.error(\"Database find post id error: \" + err);\n return next(err);\n }\n\n if (!post) {\n return res.send({errMsg: \"Cannot find post\"});... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
open all nav elements | function globalNavOpen() {
openNav(navBtn);
openNav(navMenu);
} | [
"function openNav(elem, state) {\n\n var buttons = elem.parentNode;\n var setIcon = elem.getElementsByTagName('i')[0];\n var sublist = buttons.nextSibling;\n var sublistClassList = sublist.classList;\n\n if (state) {\n sublistClassList.add('sn-sublistShow');\n setIcon.setAttribute('class', closeIcon);\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for mapping each benefit of membership section | function membershipBenefitsDataMapping(val)
{
var mapping = {
'{benefit}': removeNull(val)
};
return mapping;
} | [
"formatMembers(memb){\n\n\t\t//filter out entries without crp_ids or who aren't in office\n\t\tconst filteredMembers = memb.filter((memb) => memb.crp_id != null && memb.in_office);\n\t\t\n\t\t//format for array:\n\t\t//name: first name + last name (party), state + district, value: crp_id\n\t\treturn filteredMembers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
See if s could be an email address. We don't want to send personal data like email. | function mightBeEmail(s) {
// There's no point trying to validate rfc822 fully, just look for ...@...
return typeof s === 'string' && s.indexOf('@') !== -1;
} | [
"function mightBeEmail(s) {\n // There's no point trying to validate rfc822 fully, just look for ...@...\n return typeof s === 'string' && s.indexOf('@') !== -1;\n }",
"function IsThisAnEmail(email)\n{ \n return /^\\S+@\\S+\\.\\S+$/.test(email)\n}",
"function isEmail (s)\r\n{ if (isEmpty(s))\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
! \fn string calcTen2Zw(digits, num) \brief Umrechnung von Basis 10 ins Zweierkomplement. \param digits int, Anzahl der Stellen in der Basis 29. \param num int, Zahl in der Basis 10. \return string Zahl in der Basis 2 im Zweierkomplement. | function calcTen2Zw(digits, num){
var result = "0";
if(0>num){
result = calcTen2B("2", (Math.abs(num)-1).toString());
result = neg(result);
for(var i = result.length; i < digits; ++i){
result = ("1").concat(result);
}
}
else{
result = calcTen2B("2", num.toString());
}
return result... | [
"function calcZw2Ten(digits, num){\n var result = \"0\";\n if(num.length === digits && num.charAt(0) === \"1\"){ // negative Zahl\n result = neg(num); \n result = calcB2Ten(\"2\", result);\n var num2 = -1 * (parseInt(result)+1);\n result = num2.toString();\n }\n else{\n result = calcB2Ten(\"2\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ignore the scope chain and check the element's parent attribute for a `disabled` attribute (value of attribute is ignored). | function hasDisabledParent(element){
return !!element.parent()[0].attributes.getNamedItem('disabled');
} | [
"function checkCurrentElementIsDisabledorParentIsHidden(node) {\n if (node) {\n if (node.hasAttribute('disabled')) {\n return true;\n }\n\n if (node.tabIndex < 0) {\n return true;\n }\n\n if (Y.Node(node).ancestor('.usaa-hid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
delete Customer controller with ngConfirm A controller that allows the deletion of Customers from the database, under administrator permissions | function DeleteCustomerCtrlCtor(mainAdminServiceHTTP, $ngConfirm, $state,
$scope) {
this.customers = [];
var self = this;
this.success = false;
this.failure = false;
/**
* get all Customers from the DB using adminServiceHTTP service.
*/
var promiseGet = mainAdminServiceHTTP.getAllCustomers();
pro... | [
"function deleteCustomer () {\n // delete customer using modalCustomer object\n DeleteCustomer(modalCustomer.customerID)\n setShowOptionsModal(false)\n getWaitlist()\n }",
"function CustomerEditCtrl($scope, $location, $routeParams, CustomerService, ngDialog) {\n /*jshint validthis: true */\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
draw the head of an arrow (not the main line) ctx: canvas context x,y: coords of arrow point angle_from_north_clockwise: angle of the line of the arrow from horizontal upside: true=above the horizontal, false=below barb_angle: angle between barb and line of the arrow filled: fill the triangle? (true or false) | function drawArrowHead(ctx, x, y, angle_from_horizontal_degrees, upside, //mandatory
barb_length, barb_angle_degrees, filled) { //optional
(barb_length==undefined) && (barb_length=13);
(barb_angle_degrees==undefined) && (barb_angle_degrees = 20);
(filled==undefined... | [
"function drawArrowHead(ctx, x, y, angle_from_horizontal_degrees, upside, //mandatory\r\n\t\t\t\t\t\tbarb_length, barb_angle_degrees, filled) //optional\r\n{\r\n\tif(barb_length==undefined) { barb_length=13; }\r\n\tif(barb_angle_degrees==undefined) { barb_angle_degrees = 20; }\r\n\tif(filled==undefined) { ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop animation interval timer. | function stop () {
window.clearInterval(animationInt);
} | [
"function stopTimer(){ clearInterval(interval)}",
"_stopInterval() {\n this.__timer.stop();\n }",
"function stopAnimation(){\n\t\t\tclearInterval(timerDn);\n\t\t\tclearInterval(timerBt);\n\t\t}",
"function stopAnimation() {\n clearInterval(ballanimated);\n}",
"stop() {\r\n if (this.loo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function determines whether the volunteer prefers a new match request over their current one. For this implementation, pet walking is used as a criteria for switching. The volunteer will switch if they have a pet and this new match request needs their pet walked. Params: > volunteer name of volunteer for whom we a... | function volPrefersNewReq(volunteer, matchReq, newMatchReq) {
// If new match request needs their pet walked and this volunteer has a pet and currently
// has a match request without one, then this new match is preferred.
if (newMatchReq in needsPetWalked && volunteer in hasPet && !(matchReq in needsPetWalked)) {
... | [
"function createMatches(volunteerInput, matchRequestInput) {\n\tvar volunteerArr = inputToArr(volunteerInput);\n\tvar matchRequestArr = inputToArr(matchRequestInput);\n\t// Check that the input are valid and match in length\n\tif (!isValid(volunteerArr) || !isValid(matchRequestArr) || volunteerArr.length !== matchR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
asynchonrously grabs a gmap datum for a given yelp datum and sets appropriately. | function retrieveLandmarkMapDatum(category, yelpDatum, callback) {
var display_address = createAddressFromYelpLocation(yelpDatum.location);
$.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/json?address=" + display_address + "&sensor=true",
cache: false
}).done(function(gmapData){
if(gmapData.results... | [
"function fetchGeo(){\n //fetch(...)\n setTimeout(()=>{radar.setGeo(geo)}, Math.random() * 5000);\n}",
"function use_yelp(loc, color) {\n var auth = { \n consumerKey : \"7MBEG1e9PahKicsLORsPsw\",\n consumerSecret : \"do4Fgu9DHpGo-IlRX1iAoOeLZlc\",\n accessToken : \"82rp9T6IOODTWdg3EFnN0w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same i... | function roundSum(a, b, c) {
var a = round10(a);
var b = round10(b);
var c = round10(c);
return a + b + c;
} | [
"function roundToFive(numbers){\n \n}",
"function calDigitSum(num){\n\n if(num < 1){\n return 0;\n }\n return calDigitSum(Math.floor(num/10))+ num%10; // from every stack get the last element and pass the divide to next operation\n\n}",
"function roundTo(n, digits) \r\n{\r\n\tif (digits === und... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate Compound Bar Chart | function generateCompoundBarChart(inData) {
let subgroups = ["Positive","Negative"];
//console.log(inData)
//transpose the data into layers
let layers = d3.layout.stack()(subgroups.map(
function(tweet) {
return inData.map(function(d) {
return {x: (d.date), y:(d.compou... | [
"function renderBarChart() {\n drawAxisCalibrations();\n var i, j, p, a, x, y, w, h, len;\n\n if (opts.orient === \"horiz\") {\n rotate();\n }\n\n drawAxis();\n\n ctx.lineWidth = opts.stroke || 1;\n ctx.lineJoin = \"miter\";\n\n len = sets[0].length;\n\n // TODO fix right pad\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TODO: complete this function so that it returns all quote objects whose quote text includes the given searchTerm. TODO: bonus points if it works even if the letter case is different (e.g. a search for 'strive' also matches 'Strive') | function findQuotesMatching(quotes, searchTerm){
//TODO: you must complete this function
const result = quotes.filter((each)=>{
if (each.quote.includes(searchTerm.toLowerCase())){
return each.quote
}
})
return result
} | [
"function findQuotesContainingTerm(quotes, term) {\n let matches = [];\n let lowercasedTerm = term.toLowerCase();\n //look at each quote object :\n quotes.forEach((item) => {\n //if author or quote contains term, include it in the result\n if (\n item.quote.toLowerCase().includes(lowercasedTerm) ||\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the Word model with the highest score, according to standard tiebreaking rules | highestScoringWord() {
// TODO: test and implement
return this.at(-1);
} | [
"static highestScoreFrom(words) {\n // Find the maximum score from all the words\n const maximumScore = Math.max(\n ...words.map(word => this.scoreWord(word))\n );\n // Find the words that have the maximum score\n const highestWords = words.filter(\n word => this.scoreWord(word) === maximum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The next section determines the specific conditionals required to win a round. In traditional Connect Four, the goal, of course, is to connect four colors in a straight line, in any direction, be it vertical, hori zontal, or diagonal. The function winningMoves loops through the current gameBoard compares the disc color... | function winningMoves() {
for (let i = 0; i < gameBoard.length; i++) {
let row = gameBoard[i]
for (let j = 0; j < row.length; j++) {
disc = gameBoard[i][j]
if (disc && disc.color) {
//////////////// V E R T I C A L W I N S C E N A R I O ////////////////////
... | [
"checkForWinner(row, col) {\n const playerID = this.turn.id;\n let counter = 0; // number of same color checkers in the row so far\n let rowIndex; // row index to check\n let colIndex; // col index to check\n \n // checks for vertical win\n for (let i = 0; i < 7; i++) {\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the Reading Time element from the page's body. | function remove_element() {
let element = document.getElementById("reading_time_element");
element.parentNode.removeChild(element);
} | [
"function hideRead() {\r\n\ttry {\r\n\t\tmark = getValue('ReadTime');\r\n\t\tvar items = $x(\"//div[contains(@id,'div_story')][contains(@class,'GenericStory')]\");\r\n\t\tfor (var i=0; i<items.snapshotLength; i++) {\r\n\t\t\tvar timestamps = $x('.//span[@class=\"GenericStory_Time\"]', items.snapshotItem(i));\r\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return province abbreviation to match HM axes | function getProvinceAbreviation(province) {
switch(province) {
case "Newfoundland and Labrador" :
return "NL"
break;
case "Prince Edward Island":
return "PE"
break;
case "Nova Scotia":
return "NS"
break;
case "New-Brunswick":
return "NB"
break;
case... | [
"function state_abbr(state_name) {\t\n\tfor(var i in state_fips) {\n\t\tif(state_fips[i].name.toUpperCase() == state_name.toUpperCase()) {\n\t\t\treturn state_fips[i].abbr;\n\t\t}\n\t}\n\treturn \"\";\n}",
"function getStateName(abbrev)\n{\n\tif(abbrev == \"AL\"){ return \"ALABAMA\";}\n\tif(abbrev == \"AK\"){ ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allocate space in i18n Range add create OpCode instruction to crete a text or comment node. | function createTNodeAndAddOpCode(tView, rootTNode, existingTNodes, lView, createOpCodes, text, isICU) {
var i18nNodeIdx = allocExpando(tView, lView, 1, null);
var opCode = i18nNodeIdx << I18nCreateOpCode.SHIFT;
var parentTNode = getCurrentParentTNode();
if (rootTNode === parentTNode) {
... | [
"function createTNodeAndAddOpCode(tView, rootTNode, existingTNodes, lView, createOpCodes, text, isICU) {\n var i18nNodeIdx = allocExpando(tView, lView, 1, null);\n var opCode = i18nNodeIdx << I18nCreateOpCode.SHIFT;\n var parentTNode = getCurrentParentTNode();\n\n if (rootTNode === parentTNode) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get videos by title | function GetVideosByTitle(title) {
return $resource(_URLS.BASE_API + 'get_videos_by_title/' + title + _URLS.TOKEN_API + $localStorage.token).get().$promise;
} | [
"function search(title) {\n\n const options = {\n maxResults: 10,\n type: 'video',\n q: title,\n part: 'snippet',\n };\n\n return youtubeSearch(youtubeKey, options)\n .then(response => {\n const videoIDs = response.items.map((item) => {\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getCandidateInArray Input: 1 <= i, j <= 9 Results: candidates of cell(i,j) in array form. Example: [2, 4, 9] Side Effects: None: | getCandidateInArray(i, j){
const result = [];
for(let n=1; n<=9; n++){
if(this.getCandidate(i, j, n)==true){
result.push(n);
}
}
return result;
} | [
"getN_ListInCell(i, j){\r\n let n_list = [];\r\n for(let n=1; n<=9; n++){\r\n if(this.getCandidate(i, j, n)==true){\r\n n_list.push(n);\r\n }\r\n }\r\n return n_list;\r\n }",
"getCandidate(i, j, n){\r\n const n_bit = 1<<(n-1);\r\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lista com as categorias do chart baseado no id enviado por parametro | function getCategoriesByChart(chart_id){
var categories = null;
if(chart_id != null){
var chart = $('#'+chart_id);
if(chart != null && chart.highcharts() != null){
var highcharts = chart.highcharts();
categories = highcharts.xAxis[0].categories;
}
}
return categories;
} | [
"function buscarCategorias() {\n axios__WEBPACK_IMPORTED_MODULE_1___default().get(_Config_Server__WEBPACK_IMPORTED_MODULE_5__.URL + 'usuario/' + usuario.id + '/categoria', {\n headers: {\n Authorization: 'Bearer ' + JSON.parse(state.token)\n }\n }).then(function (res) {\n setData(_object... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementation of RootPart's `isConnected`. Note that this metod should only be called on `RootPart`s (the `ChildPart` returned from a toplevel `render()` call). It has no effect on nonroot ChildParts. | setConnected(isConnected) {
var _a2;
if (this._$parent === void 0) {
this.__isConnected = isConnected;
(_a2 = this._$notifyConnectionChanged) === null || _a2 === void 0 ? void 0 : _a2.call(this, isConnected);
} else {
throw new Error("part.setConnected() may only be called on a RootPart re... | [
"function shadowTree_isConnected(element) {\n /**\n * An element is connected if its shadow-including root is a document.\n */\n return util_1.Guard.isDocumentNode(TreeAlgorithm_1.tree_rootNode(element, true));\n}",
"_hasWrappedChildren() {\r\n return this._wrappedChildCount > 0;\r\n }",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns reference to vertical FireMeshLine most closely anchored to x | vertLineAt (x) { return this._vert[this.vertIdxAt(x)] } | [
"get_y(x) {\n\tfor (let i in this.pts) {\n\t if (i == 0) {\n\t\tcontinue;\n\t }\n\t if (this.pts[i-1][0] > this.pts[i][0]) {\n\t\tconsole.log(\"Error: line's x coordinates are not increasing\")\n\t }\n\t if (this.pts[i-1][0] <= x && this.pts[i][0] >= x) {\n\t\treturn this.pts[i-1][1] + (this.pts[i][1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the best parameters for the Pade approximant given the matrix norm and desired accuracy. Returns the first acceptable combination in order of increasing computational load. | function findParams(infNorm, eps) {
var maxSearchSize = 30;
for (var k = 0; k < maxSearchSize; k++) {
for (var q = 0; q <= k; q++) {
var j = k - q;
if (errorEstimate(infNorm, q, j) < eps) {
return {
q: q,
j: j
};
}
}
}
th... | [
"function findParams(infNorm, eps) {\n const maxSearchSize = 30;\n\n for (let k = 0; k < maxSearchSize; k++) {\n for (let q = 0; q <= k; q++) {\n const j = k - q;\n\n if (errorEstimate(infNorm, q, j) < eps) {\n return {\n q: q,\n j: j\n };\n }\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
edits the cache, from the perspective of the store (ie positive quantity means store is buying from player). Prevents unnecessary API calls by calculating store stock locally. | editCache(item, quantity) {
this._credits -= (this._costs.get(item) ?? 0) * quantity;
this._inventory.set(item, (this._inventory.get(item) ?? 0) + quantity);
} | [
"function update(cache,payload){\n cache.evict(cache.identify(payload.data.deleteCartItem));\n}",
"function setCart(){\n\t\tstorage.set({ \n\t\t\titems: 0, \n\t\t\tsubtotal: 0\n\t\t}, function(){\n\t\t\tupdateCart();\n\t\t});\n\t}",
"function updateStock() {\n\tconnection.query(\"UPDATE products SET ? WHERE ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
called from selectLayer() when joinSelected is not null | function bJoinSelect(layer) {
if( 'id' in layer && layer.id in borders ) {
joinAnother = layer.id;
$('#j_name2').text(joinAnother);
$('#j_do').css('display', 'block');
}
} | [
"function hasOtherJoinContextSelected(){\n\treturn ( otherContextJoinVariables.length > 0 ) ;\n}",
"function zl_ExplodeShapeLayers_layerSelect(target, status){\n if (target.length == null){\n target.selected = status;\n } else {\n for (var i = 0; i < target.length; i++){\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fetches histogram data for a column or column expression of an active table set isColStatsReady to true once done. | function fetchTblStats(dispatch, activeTableServerRequest) {
// searchRequest
const sreq = Object.assign({}, activeTableServerRequest, {'startIdx': 0, 'pageSize': 1000000});
const req = TableRequest.newInstance({
id:'StatisticsProcessor',
searchRequest: JSON.stringi... | [
"upsertMACD_histogram(baseColumn){\n \n var availableKeys = Object.keys(this.data.intervalls[0]);\n\n if (this.contains(availableKeys,baseColumn) != true){\n throw new Error(\"Column name is not available. Available columns are: \" + availableKeys.toString());\n }else{\n \n\n var inputArray... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the distance hint | function getDistanceHint(distance) {
if (distance < 10) {
return "Boiling Hot!";
} else if (distance < 20) {
return "Really Hot";
} else if (distance < 40) {
return "Hot";
} else if (distance < 80) {
return "Warm";
} else if (distance < 160) {
return "Cold";
... | [
"calculateDistance() {}",
"function calculateDistance() {}",
"*createDistanceConstraints() {\n for (let { source, target, codim, dir } of this.edges) {\n if (codim == 0) {\n continue;\n }\n\n if (codim == 1 && source[0] % 2 == 1) {\n //continue;\n }\n\n yield new Kiwi.C... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search the string for a match starting at the given position | search(string, startPosition, callback) {
if (startPosition == null) {
startPosition = 0;
}
if (typeof startPosition === 'function') {
callback = startPosition;
startPosition = 0;
}
try {
const ret = this.searchSync(string, startPos... | [
"search(string, startPosition, callback) {\r\n if (startPosition == null) {\r\n startPosition = 0;\r\n }\r\n if (typeof startPosition === 'function') {\r\n callback = startPosition;\r\n startPosition = 0;\r\n }\r\n try {\r\n const ret = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
END EVENTS / helper function to display visual warning if the allocation exceed a projects end date | alertProjectEndExceeded(item) {
item.style = item.end > this.groups.get(item.group).end ? "background: rgba(175, 0, 0, 1);" : "";
} | [
"function old_project_warning(warndate_raw){\n var openDate = new Date($('#open_date').text());\n var warnDate = new Date(warndate_raw);\n if(openDate.getTime() < warnDate.getTime()){\n $('#old_project_warning').show();\n $('#old_project_warning').attr('title', 'This project was created before '+warndate_r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
change scale will recalculate center & size \ size handle by child class | setScale(scale) {
this._setCenter(this._collider.center);
} | [
"updateScale() {\n this.scale = this.getDrawingScale();\n }",
"resize() {\n this.setScale();\n }",
"scale() {\n this.p.scale(this._scaleFactor);\n }",
"scale() {\n this.p.scale(this._scaleFactor);\n }",
"_onScaleChanged(scale) {\n _super(this)._onScaleChanged... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the closest MatDialogRef to an element by looking at the DOM. | function getClosestDialog(element, openDialogs) {
var parent = element.nativeElement.parentElement;
while (parent && !parent.classList.contains('mat-dialog-container')) {
parent = parent.parentElement;
}
return parent ? openDialogs.find(function (dialog) {
return di... | [
"function getClosestDialog(element, openDialogs) {\n var parent = element.nativeElement.parentElement;\n while (parent && !parent.classList.contains('mat-dialog-container')) {\n parent = parent.parentElement;\n }\n return parent ? openDialogs.find(function (dialog) { return dialog.id === parent.i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
updates the title of the calendar event and sets the appropriate background | function calendar_helper_updateCalEventTitleAndBackground(cal_event, new_title){
if (cal_event.title != new_title){
cal_event.title = new_title;
$("#calendar").weekCalendar("updateEvent", cal_event);
}
setEventBackground(cal_event);
} | [
"function calendar_helper_setTitleAndBackground(cal_event){\n if (cal_event!=null){\n if (cal_event.is_valid)\n directions_api_addTravelTimeToTitle(cal_event);\n else\n calendar_helper_updateCalEventTitleAndBackground(cal_event, openingHoursToString(cal_event.available_destina... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds necessary HTML code to the page to show new task on the list (task position = i) | function addTaskToPage(i)
{
document.getElementById("tasks-container").innerHTML += `<div id="${'task' + taskArr[i].position}" class="task" onmouseenter="showOptions(event)" onmouseleave="hideOptions(event)">
<p class="task-position">${taskArr[i].position}<p>
<input type="checkbox" id="${'checkboxTask' + ta... | [
"function addTaskToDom ( task ) {\n jqueryMap.$list_box.prepend(\n '<li data-id=\"' + task.id + '\" >' + task.desc + '</li>'\n );\n }",
"function updateTaskPage(tasks) {\n\t\toutput.innerHTML = '';\n\t\tmessage = '<h2>To-Do</h2><ol>';\n for (var i = 0, count = tasks.length; i < coun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
BACKDROP This just calls the generic backdrop code to fling up the backdrop and wobble it about. | function draw_backDrop() {
var backDropChanges = backDrop( backdropInfo, backDropY, backdropCleared );
backDropY = backDropChanges.backDropY;
backdropCleared = backDropChanges.backdropCleared;
} | [
"function backDrop( backdropInfo, backDropY, backdropCleared ) {\n \tif ( defaultFalse( backdropInfo ) ) {\t\t\t// If we're showing the backdrop\n \t\tbackDropScreen.show();\t\t\t\t\t\t\t// ... show it\n \t\tif (backdropInfo.animate) \t\t\t\t\t\t// If We're flinging it in ...\n \t\t\tif (backDropY > 5) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CouchDB Save Function to store the data that is being passed by info object. Create Document Portion CouchDB Part1. | function couchDBSave (info) {
$.couch.db("asdfix").saveDoc(info, {
success: function (info){
console.log(info);
alert("Data Has Been Saved!!");
window.location = $("index.html/#addSchd");
},
error: function (status) {
console.log(status... | [
"function saveInformation () {\n\t\t numOfCreditFun();\n\t\t bestMthContFun();\n\t\t var info = {};\n\t\t \tinfo.major = [\"Major Choice:\", $('#departments').val()];\n\t\t info.cName = [\"Course Name:\", $('#courseName').val()];\n\t\t info.cSection ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure only strings and wrapped expressions are used in JSX attributes. | enforceValidJSXAttributes() {
return this.scanTokens(function(token, i, tokens) {
var next, ref;
if (token.jsxColon) {
next = tokens[i + 1];
if ((ref = next[0]) !== 'STRING_START' && ref !== 'STRING' && ref !== '(') {
throwSyntaxError('expected wrapped or quoted JSX attribut... | [
"enforceValidJSXAttributes() {\n return this.scanTokens(function(token, i, tokens) {\n var next, ref;\n if (token.jsxColon) {\n next = tokens[i + 1];\n if ((ref = next[0]) !== 'STRING_START' && ref !== 'STRING' && ref !== '(') {\n throwSyntaxError('expecte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function load data catalog LoaiHang | function loadDataLoaiHang() {
$scope.loaiHang = [];
if (!tempDataService.tempData('loaiHang')) {
loaiHangService.getAllData().then(function (successRes) {
if (successRes && successRes.status === 200 && successRes.data && successRes.data.Status ... | [
"function loadDataLoaiPhong() {\n $scope.loaiPhong = [];\n if (!tempDataService.tempData('loaiPhong')) {\n loaiPhongService.getAllData().then(function (successRes) {\n if (successRes && successRes.status === 200 && successRes.data && successRes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a child node to this node and propagate the new information. | add_child(node) {
this.add_child_no_propagation(node);
this.propagate_children_count(node.get_total_children_count() + 1)
} | [
"addChild(child) {\n // Inherit some parent properties to child\n child._parent = this;\n child.updateResource(false);\n this.children.set(this.getPlatformAwareName(child.name), child);\n }",
"addChild(child) {\n this.children.push(child);\n child.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the AST tab with a visualization of the structure of the AST generated by the WebBS parser. | updateParseTreeTab (root) {
let html = root.children.map(createParseTreeView).join("");
if (html === "") {
this.disableTab("parse-tree");
}
this.DOMNodes.parseTree.innerHTML = html;
this.enableTab("parse-tree");
} | [
"function AST(){}",
"render(changes) {\n let start = Date.now();\n let newAST = this.parser.parse(this.cm.getValue());\n this.cm.operation(() => {\n // try to patch the AST, and conservatively mark only changed nodes as dirty\n try{\n this.ast = this.ast.patch(s => this.parser.parse(s), ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: newFrame Description: Create a new frameset document and place the existing document into new Frameset. Arguments: inDOM newFSDOM | function newFrame (inDOM, newFSDOM) {
if (!(typeof inDOM.splitFrame == 'function')) {return;} // Function not defined.
if (!dw.getDocumentDOM().canSplitFrame()) {return;} // Not a valid selection.
var frameStr = '';
// Create a new frameset
// Note: Original document refereced below as childNodes[1]
inDO... | [
"function wrapFrame (curDOM, curNode, tfsDOM) {\n var newFrameStr = '';\n var targetSelection = curDOM.nodeToOffsets(curNode);\n var cArr, tArr;\n\n // Target frame specifies the content for the new frame.\n if (!tfsDOM.mm_target) {return;} // Check for no target defined.\n\n // Modify the current frameset to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms. Given your and your friend's arms' lifting capabilities find out if you two are equally strong. | function areEquallyStrong (yourLeft, yourRight, friendsLeft, friendsRight) {
const yourStrongest = Math.max(yourLeft, yourRight)
const yourWeakest = Math.min(yourLeft, yourRight)
const friendsStrongest = Math.max(friendsLeft, friendsRight)
const friendsWeakest = Math.min(friendsLeft, friendsRight)
return you... | [
"function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {\n // check if your strongest arm is equal to your friends strongest arm\n // and same for the weakest arm\n return Math.max(yourLeft, yourRight) === Math.max(friendsLeft, friendsRight) && Math.min(yourLeft, yourRight) === Math.min... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an object of optional props from datatippy attributes | function getDataAttributeProps(reference, plugins) {
var propKeys = plugins ? Object.keys(getExtendedPassedProps(_extends({}, defaultProps, {
plugins: plugins
}))) : defaultKeys;
var props = propKeys.reduce(function (acc, key) {
var valueAsString = (reference.getAttribute("data-tippy-" + key) || '').trim(... | [
"function getDataAttributeProps(reference, plugins) {\n var propKeys = plugins ? Object.keys(getExtendedProps(_extends$n({}, defaultProps, {\n plugins: plugins\n }))) : defaultKeys;\n var props = propKeys.reduce(function (acc, key) {\n var valueAsString = (reference.getAttribute(\"data-tippy-\" +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
overwrite the storage with the provided heartbeats | async overwrite(heartbeatsObject) {
var _a;
const canUseIndexedDB = await this._canUseIndexedDBPromise;
if (!canUseIndexedDB) {
return;
}
else {
const existingHeartbeatsObject = await this.read();
return writeHeartbeatsToIndexedDB(this.... | [
"async overwrite(heartbeatsObject) {\n var _a;\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n }\n else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
when the user clicked "Send" the contents of name and comments should be sent to the service as a POST request | function send(){
let comment = document.getElementById("input").value;
let userName = document.getElementById("name").value;
//let data = [];
if(userName === "" || comment === ""){
alert("Name / Message cannot be empty. Failed");
}
else{
... | [
"function sendCommentButtonPressed() {\n\n // Extract comment parameters, currently displayed document is the reference document\n var refid = getCurrentDocId();\n var title = \"\";\n var tags = \"\";\n var text = document.getElementById('comment_text').value;\n\n // Submit comment as new document... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize Set objects to store names of keys pressed and released; set up event listeners to handle keyboard input. | constructor()
{
// Event listeners add keys to Queues;
// required because of asynchronous event handling.
this.keyDownQueue = new Set();
this.keyUpQueue = new Set();
this.keyPressedSet = new Set();
this.keyPressingSet = new Set();
this.keyReleasedSet = new Set();
let self = this;
this... | [
"function initKeys() {\n allKeys.forEach(key => {\n key.addEventListener('mouseover', () => {\n key.classList.add('hovered');\n })\n key.addEventListener('mouseleave', () => {\n key.classList.remove('hovered');\n })\n key.addEventListener('mousedown', () =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds coordinates to meshVertices, texture coordinates to meshTexCoords, and normal components to meshNormals for the given indices (indices start at 0) | function addTriangleVertexForIndices(vIndex, tIndex, nIndex) {
// add x, y and z coordinates of vIndex into meshVertices
meshVertices.push(vertices[3*vIndex], vertices[3*vIndex+1], vertices[3*vIndex+2]);
// add s and t texture coordinates into meshTexCoords
meshTexCoords.push(textureCoords[2*tIndex], texture... | [
"static buildMesh(positions, uvs, normals, indices, tangents, bitangents, geometries) {\n\n if ((positions.length % 3) != 0) {\n console.log(\"Vertex attribute lengths not a multiple of 3\");\n return null;\n }\n \n let hasTextCoords = uvs.le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For given abs msec time from sequencer start, calc beat info and quantizes as appropriate. | getMusicTimes( globalMsec ){
//Event time in msec rel to sequencer start
var perfMsec = globalMsec - this.startMsec;
//Absolute fractional beat from start of sequencer
//UN-quantized
//var perfBeatRaw = perfMsec / this.musicParams.beatDur;
var perfBeatRaw = this.tempoCha... | [
"function timeToFirstBeat() {\n var beats = sequencer.loopLength() - currentBeat;\n return beats * sequencer.beatLength();\n }",
"get_beat_time()\n {\n return this.get_measure_time()/4.0; // as it's 4 beats to the bar (measure)\n }",
"function ProcessMIDI () {\n\t\tvar musicInfo = GetT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set a profile as active | setProfileAsActive (state, profile) {
for (let p of state) {
p.active = p.id === profile.id
}
} | [
"function setCurrentProfile () {\r\n getAllProfiles();\r\n var currentProfile = _.find(Chi.allProfiles, function (profile) {\r\n return profile.active();\r\n });\r\n if (currentProfile === undefined) {\r\n Chi.Router.navigate('/profiles/new', {trigger: true});\r\n } else {\r\n API.get(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes all the streams. Set all the initProgress flags to false, detach all the streams after stopping them. | function close() {
console.log('(ReachSDK::localstream::close)');
if (mLocalStreamVideo) {
detachMediaStream(mLocalStreamVideo);
mLocalStreamVideo=null;
}
if (streamAudioVideo) {
streamAudioVideo.getTracks().forEach((track)=>{
track.stop();
});
streamAudioVideo=null;
}
if (streamVideo) {
... | [
"dispose() {\n Object.keys(this._streams).forEach((key) => {\n this._streams[key].forEach((stream) => stream.close());\n });\n this._streams = {}\n }",
"_closeFileStreams() {\t\n\t\t//Close the output stream\n\t\tthis.outputFileStream.end();\t\t\n\t}",
"stopAllStreams() {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
delete market by firebase_id | function deleteByMarketId(id){
return db("market")
.where({ 'firebase_id': id })
.del();
} | [
"deleteRide(id) {\n firebase.database().ref('Rides/' + id).remove();\n }",
"travelDelete(key){\n\t\t\tfirebase.database().ref('travels/' + key).remove();\n\t}",
"function favoriteDelete(key) {\n // Delete object from firebase\n let favoriteDBRef = favoritesDBRef.child(key);\n favoriteDBRef.remove()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a list of names of the users in the specific course | async getUsersInCourse() {
let usersInCourse = [];
await firestore.collection('userInfo').get().then(snap => {
for (let userDoc of snap.docs) {
if (userDoc.data().courseIds.includes(this.id)) {
usersInCourse.push(userDoc.data().name)
}
... | [
"async getUsersByCourse(courseArray) {\r\n if(!courseArray) throw 'courses not specified';\r\n\r\n const usersCollection = await users();\r\n const usersByCourse = await usersCollection.find({\"profile.course\": {$all: courseArray}}).toArray();\r\n\r\n if(!usersByCourse) \r\n {\r\n return [];\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this will allocate mines as given mineNo on random | allocateMine(mineNo) {
for (let i = 0; i < mineNo; i++) {
let mine = this.randomNum();
if (!this.mines.includes(mine)) {
this.mines.push(mine);
} else {
i--;
}
}
return this.mines;
} | [
"function generateMines() {\n\tfor (let i = 0; i < mineCount; i++) {\n\t\tlet randomMines = Math.floor(Math.random() * safeCells.length);\n\t\tlet mine = safeCells[randomMines];\n\n\t\tgameboard[mine[0]][mine[1]] = 'mine'; //set mines into gameboard\n\t\trevealedBoard[mine[0]][mine[1]] = 'mine';\n\n\t\tsafeCells.sp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints importing error and dispatches not found method. | _importError() {
console.error('IMPORT ERROR!!');
this._notFound();
} | [
"function caml_raise_not_found () {\n caml_raise_constant(caml_global_data.Not_found); }",
"function noImport () {\n throw new Error('function import is disabled.')\n}",
"function showError() {}",
"static get notFoundError() {\n return getErrorObject('OFFER_NOT_FOUND', 404);\n }",
"function notFound()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SOME EXAMPLE STRINGS, IN ORDER 0 00001 0001 001 001001 00101 0011 0011001 001100101 00110011 001101 00111 01 if you never make a string that ends in the lowest char, then it is always possible to make a string between two strings. this is like how decimals never end in 0. example: between('A', 'AB') ... 'AA' will sort ... | function between (a, b) {
var s = '', i = 0
while (true) {
var _a = chars.indexOf(a[i])
var _b = chars.indexOf(b[i])
if(_a == -1) _a = 0
if(_b == -1) _b = chars.length - 1
i++
var c = chars[
_a + 1 < _b
? Math.round((_a+_b)/2)
: _a
... | [
"function between (a, b) {\n\n var s = '', i = 0\n\n while (true) {\n\n var _a = chars.indexOf(a[i])\n var _b = chars.indexOf(b[i])\n \n if(_a == -1) _a = 0\n if(_b == -1) _b = chars.length - 1\n\n i++\n\n var c = chars[\n _a + 1 < _b \n ? Math.round((_a+_b)/2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate new sentence according to recursion rules: | function generate() {
// With every new sentence we want to make tree branches smaller
leng = 0.5*leng;
// We also want to randomize angle a bit
angle += random(-PI/9, PI/9);
var newSentence = "";
// Every character in sentence we need to change according to recursion rules and
// write it dow to a new se... | [
"generate() {\n this.len *= 0.5; //So the tree becomes denser instead of larger.\n this.branchValue += 1; //To ensure increased thickness of trunk.\n let nextSentence = \"\";\n for (let i = 0; i < this.sentence.length; i++) {\n let current = this.sentence.charAt(i);\n if (current =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
method to create pagination dots | createPagination(totalPageCount) {
let totalNumberOfpageArray = this.populateArray(totalPageCount);
this.paginationDots = totalNumberOfpageArray.map(function (item, index) {
return (
<div class={styles.paginationdots} key={index}></div>
);
});
} | [
"generatePageDots () {\n // Remove all children if there is any.\n while (this.$el.firstChild) {\n this.$el.removeChild(this.$el.firstChild);\n }\n\n // Create new pagination.\n const pagesAmount = Math.ceil(this.itemsAmount / this.itemsOnPage);\n for (let i = 0; i < pagesAmount; i++) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function validates a given email if it is incorrect the field is cleared | function emailValidate(email) {
var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!emailRegex.test(email.value)){
document.getElementById('email').value = "" ;
return false;
}
else{
return true;
}
} | [
"function validateEmailReset() {\n if (checkIfEmpty(email)) return;\n if (!containsCharacters(email, 5)) return;\n if (!CheckFieldInDbReset(email, form_j, dataUrlEmail)) return;\n return true;\n}",
"invalidateEmailField() {\n const $field = this.$self.find('#email')\n if (!invalidateEmptyField($... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create next voucher from AFIP This method combines Afip.getLastVoucher and Afip.createVoucher for create the next voucher | async createNextVoucher(data) {
const lastVoucher = await this.getLastVoucher(data['PtoVta'], data['CbteTipo']);
const voucherNumber = lastVoucher + 1;
data['CbteDesde'] = voucherNumber;
data['CbteHasta'] = voucherNumber;
let res = await this.createVoucher(data);
res['voucherNumber'] = voucherNumb... | [
"async function postVoucher(clientIndex)\n{ \n\t// Gets client info from previously retrieved results\n\tlet client = clients[clientIndex];\n\tlet endpoint = 'http://api-gateway-dev.phorest.com/third-party-api-server/api/business/' + businessId +'/voucher';\n\n\tlet voucherValueString = document.getElementById('vou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for repositoriesWorkspaceRepoSlugPut / Since this endpoint can be used to both update and to create a repository, the request body depends on the intent. | repositoriesWorkspaceRepoSlugPut(incomingOptions, cb) {
const Bitbucket = require('./dist');
let defaultClient = Bitbucket.ApiClient.instance;
// Configure API key authorization: api_key
let api_key = defaultClient.authentications['api_key'];
api_key.apiKey = incomingOptions.apiKey;
// Uncomment... | [
"repositoriesWorkspaceRepoSlugSrcPost(incomingOptions, cb) {\n const Bitbucket = require('./dist');\n let defaultClient = Bitbucket.ApiClient.instance;\n // Configure API key authorization: api_key\n let api_key = defaultClient.authentications['api_key'];\n api_key.apiKey = incomingOptions.apiKey;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the ChangeSetUpsert for new or existing entities of the given entity type | upsert(entityName, entities) {
entities = Array.isArray(entities) ? entities : entities ? [entities] : [];
return { entityName, op: ChangeSetOperation.Upsert, entities };
} | [
"function setEntityType() {\n var new_type = $(this).attr('label')\n var edits = [];\n $(\".entity.ui-selected\").each(function() {\n var eid = this.id;\n edits.push({action:'change_entity_type', id:eid, old_type:entities[eid].type, new_type:new_type});\n });\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add call on submit to the form | _addSubmitCall() {
this._form.submit((e) => {
e.preventDefault();
this._hideErrors();
$.ajax({
method: this._form.attr('method'),
url: this._form.attr('action'),
data: this._form.serialize(),
beforeSend: (jqXHR, ... | [
"function submit() {\n\n \n} //submit function close out",
"onSubmitClicked(){\r\n\t\t\r\n\t}",
"function _eventClickSubmit(){\n\tTi.API.info('SUBMIT BUTTON CLICK');\n\tvalidateSuggestionForm();\n}",
"addSubmitButton() {}",
"addToSubmitForm(callback) {\n this.submitFormCallbacks.push(callback);\n }",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
3 Using the varabile persons Create a function called averageAge that accept an object and return the average age of those persons Ex: averageAge(persons) => 41.2 | function averageAge(persons)
{ var i;
var sum=0;
for(i=0;i<persons.length;i++)
{
sum+= persons[i].age;
}
console.log(sum/i);
} | [
"function avgAge (persons){\nvar sum = persons.reduce((accu, current)=>{\n\treturn accu + current.age;\n},0);\nreturn sum/persons.length;\n}",
"function averageAge (obj) {\n moath = 0;\n for (var i = 0; i < x; i++) {\n var moath = moath + obj[i]['age'];\n }\n return moath / x;\n}",
"function averageAge(p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing for intersection between: 3D Sphere and a 3D ray | function intersect_Sphere_Ray3d (pSphere, pRay) {
var vecQ = Vec3.create();
vecQ.X = pRay.v3fPoint.X - pSphere.v3fCenter.X;
vecQ.Y = pRay.v3fPoint.Y - pSphere.v3fCenter.Y;
vecQ.Z = pRay.v3fPoint.Z - pSphere.v3fCenter.Z;
var c = Vec3.lengthSquare(vecQ) - pSphere.fRadius * pSphere.fRadius;
if (c <... | [
"function raySphereIntersect(ray,sphere,clipVal) {\n try {\n if (!(ray instanceof Array) || !(sphere instanceof Object))\n throw \"RaySphereIntersect: ray or sphere are not formatted well\";\n else if (ray.length != 2)\n throw \"RaySphereIntersect: badly formatted ray\";\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
flush alias module export | flushAliasExport(g, type, file) {
g = g || THINK.CACHES.ALIAS_EXPORT;
file && require.cache[file] && delete require.cache[file];
THINK.cache(g, type, null);
} | [
"flushAliasExport(g, type, file) {\n g = g || THINK.CACHES.ALIAS_EXPORT;\n file && require.cache[file] && delete require.cache[file];\n THINK.loadCache(g, type, null);\n }",
"exit(path, state) {\n if (state.reexport) {\n const source = state.reexport.source;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the index after the given index. Takes looping and the given filterFn into account. | function listNext(list, isLooping, index, filterFn) {
filterFn = filterFn || trueFn;
if (index < 0 || index >= list.length) return -1;
// Keep adding 1 to index, trying to find an index that passes filterFn.
// If we loop through *everything* and get back to our original index, return -1.
// We don't use rec... | [
"function next(index, filterFn) {\n filterFn = filterFn || trueFn;\n if (!self.isInRange(index)) return -1;\n\n // Keep adding 1 to index, trying to find an index that passes filterFn.\n // If we loop through *everything* and get back to our original index, return -1.\n // We don't use recursion here... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines if the value is a real element | function isRealElement(value) {
return value instanceof Element;
} | [
"function isRealElement(value) {\n return value instanceof Element;\n}",
"function isRealValue(obj) {\n return obj && obj !== \"null\" && obj !== \"No Result\" && obj !== \"undefined\" && obj.length !== 0;\n }",
"function isElement (value) {\n return typeof value === 'object' && value != nul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TODO: it's silly and kind of fragile that we look at app config to determine the ios project paths. Overall this function needs to be revamped, just a placeholder for now! Make this more robust when we support applying config at any time (currently it's only applied on eject). | function getIOSPaths(projectRoot) {
const { exp } = config_1.getConfig(projectRoot, { skipSDKVersionRequirement: true });
const projectName = exp.name;
if (!projectName) {
throw new Error('Your project needs a name in app.json/app.config.js.');
}
const iosProjectDirectory = path_1.default.jo... | [
"function resolveConfigFilePath (project_dir, platform, file) {\n let filepath = path.join(project_dir, file);\n let matches;\n\n file = path.normalize(file);\n\n if (file.includes('*')) {\n // handle wildcards in targets using glob.\n matches = modules.glob.sync(path.join(project_dir, '**... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Functions: Process MMC Answer | function processAnswerMMC(answer,mc1,mc2,mc3,mc4,mc5){
var a;
if(answer.search('a')>=0)
var a = '[{"answer_text":"'+mc1+'","answer_weight":100}';
else {
var a = '[{"answer_text":"'+mc1+'","answer_weight":0}';
}
if(answer.search('b')>=0)
a = a+',{"answer_text":"'+m... | [
"function EchoResponse() {\n console.log(\"Running echo response\");\n setCS(0);\n SPI1_Write(0x00); // Send cmd to CR95HF\n SPI1_Write(ECHO);\n setCS(1);\n while(1){\n console.log(\"Waiting for CR95HF to respond\");\n setCS(0);\n SPI1_Write(0x03);\n tmp = SPI1_Read();\n setCS(1);\n\n conso... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes an array of gif objects and creates elements in the HTML in gifarea | function populateGifs(array) {
console.log('populateGifs');
console.log(array);
var gifArea = $('.gif-area');
gifArea.empty();
$.each(array, function(i, val) {
gifArea.append($('<div>', {class: 'gif-container'}).append($('<div>').text("Rating: " + val.rating))
... | [
"function createGifHtml(gifsArry){\n $(\"#gifwrap\").empty()\n\n // loop through the results.data\n for (var i = 0; i < gifsArry.length; i++){\n // create a div\n var div = $(\"<div>\");\n div.addClass(\"gWrap\");\n // create a p tag\n var ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
overloads: strtr(String string, String from, String to): String strtr(String string, Dictionary translations): String | function strtr(aString, aTranslations, aTo, aMapper) {
if (typeof(aTranslations) === 'string') {
var translations = {};
translations[aTranslations] = aTo;
return strtr(aString, translations, aMapper);
}
var mapper = aTo || id;
var keys = Object.keys(aTranslations)
.sort(cmpDescendingLength)
.... | [
"function Tr(s, f, t)\n{\n var o = '';\n \n if (typeof(t) != 'string')\n {\n t = '';\n }\n \n for (var i = 0; i < s.length; i ++)\n {\n var c = s.charAt(i);\n var idx = f.indexOf(c);\n if (idx >= 0)\n {\n if (idx < t.length)\n\t {\n o += t.charAt(idx);\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementation of localStorage API to save filters to local storage. This should get called everytime an onChange() happens in either of filter dropdowns | function saveFiltersToLocalStorage(filters) {
// TODO: MODULE_FILTERS
// 1. Store the filters to localStorage using JSON.stringify()
localStorage.setItem('filters', JSON.stringify({ duration: "", category: [] }))
return true;
} | [
"function setFilters(filterData) {\n localStorage.setItem(\"filters\", JSON.stringify(filterData));\n setFilterState(filterData);\n }",
"function locallyStoreFilters() {\n var filterInstances = Filter.instances;\n // Store string representation of filterInstances list in local storage.\n localStorage.se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
primaryAttack() function to reduce the picked toon's health points and opponent's health points, as well as update the DOM accordingly | function primaryAttack(toonPickedId, oppPickedId)
{
// Hides the Attack Spinner once the attack and counter attack have been performed
$(".spinner-grow").hide();
$("#pl-dmg-taken").empty();
// Increases the attack power of the player's toon after... | [
"updateAttackPoints() {\n const combatPlayerOneDashboard = this.getPlayerGridPosition(0, true);\n const combatPlayerTwoDashboard = this.getPlayerGridPosition(1, true);\n\n combatPlayerOneDashboard.querySelector(\n \"#health\"\n ).innerHTML = this.players[0].health;\n combatPlayerOneDashboard.que... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
eg writeFloat(123.2123, 100) 2 decim | function writeFloat(writer, val, precisionMultiplier) {
StringWriter.writeSafe(writer, '' + Math.round(precisionMultiplier * val) / precisionMultiplier + ' ');
} | [
"writeFloat(value){return this.__writeFloatingPointNumber(value,4),this}",
"writeDouble(value){return this.__writeFloatingPointNumber(value,8),this}",
"writeBinaryFloat(n) {\n this.writeUInt8(4);\n const buf = this.reserveBytes(4);\n buf.writeFloatBE(n);\n if ((buf[0] & 0x80) === 0) {\n buf[0] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get two keypoints, a character bone and minConfidence Animate bone if minimum confidence condition is met | function animateDetectedBone(chaBone, initKeyPt, termKeyPt, minConfidence, skeleton) {
if (initKeyPt.score > minConfidence && termKeyPt.score > minConfidence) {
var chaScale; // relative size ratio between human torso width and fluffy torso width shown on html canvas
chaBone.rotation = chaBone.worldToLocal... | [
"function keypointToSound(results) {\n // Only run through Keypoint mapping from Single Person pose\n for (i = 0; i < results.length; i++) {\n // Control sound from right hand and left hand\n if (results[0].keypoints[9]['score'] && results[0].keypoints[10]['score'] > minThresholdScore) {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clearing search results and input when modal is hidden | _onSearchModalHidden() {
document.getElementById(this.settings.searchInputId).value = '';
const reuslts = document.getElementById(this.settings.searchResultsId);
while (reuslts.firstChild) {
reuslts.removeChild(reuslts.firstChild);
}
} | [
"function clearSearch(){\n $('#data-models').find('.slds-col[aria-label=\"data-model\"]').removeClass('slds-hide');\n $('#data-models').find('.slds-summary-detail').removeClass('slds-hide');\n $('#search-box').val('');\n}",
"function clearSearchResults() {\n $(\".search-results\").empty();\n }",
"f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function calls setEditImages for setting default component values depending on current actionType | didRender(){
this._super(...arguments);
// call setEditImages
this.setEditImages();
} | [
"function editImages(){\n //Show additional edit buttons\n jQuery('.button-remove-image').show();\n jQuery('.isDefault').show();\n }",
"prepareImgForEditArticle(model) {\n\t\tif(model.editArticle){\n\t\t\tif (model.optionSelected.id === this._kConstantFactory.ID_SECCION_IMAGENES)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bind Event Listeners Bind any events that are required on startup. Common events are: 'load', 'deviceready', 'offline', and 'online'. | function bindEvents() {
document.addEventListener('deviceready', onDeviceReady, false);
} | [
"function bindEvents() {\r\n document.addEventListener('deviceready', onDeviceReady, false);\r\n }",
"bindEvents() {\n document.addEventListener('deviceready', this.onDeviceReady.bind(this), false)\n // if run project with `npm start`, there's no 'deviceready' event, we trigger it manually\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
copy image large1 size 1920x654 | function image_large1() {
return gulp
.src(large1.src, { nodir: true })
.pipe(newer(large1.dist + "large"))
.pipe(imageresize({
width: large1.params.width,
height: large1.params.height,
crop: large1.params.crop,
upscale: false
}))
.pipe(imagemin({
progressive: true,
svgo... | [
"function image_large2() {\r\n return gulp\r\n .src(large2.src, { nodir: true })\r\n .pipe(newer(large2.dist + \"large\"))\r\n .pipe(imageresize({\r\n width: large2.params.width,\r\n height: large2.params.height,\r\n crop: large2.params.crop,\r\n upscale: false\r\n }))\r\n .pipe(imagemin({\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load beta1 tutorstatedata.json image | loadStateImage() {
let stateData = path.join(this.cwd, this.USER_DATA, this.TUTORSTATE);
this.state = JSON.parse(fs.readFileSync(stateData));
} | [
"function preload() {\n tarot = loadJSON(`assets/data/tarot_interpretations.json`);\n}",
"function preload() {\n//JSON/////////////////////////////////////////////////////////////////////////\n //load with raw file\n tarotData = loadJSON(`assets/data/tarot_interpretations.json`)\n //Or with a URL\n tarotData... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the stackLetter function should accept the array as the sole argument | function stackLetters (theAlphabetArray) {
var stack = "";
for(var i = 0; i < theAlphabetArray.length; i++) {
if (i % 3 === 0) {
stack += " " + theAlphabetArray[i];
}else{
stack += theAlphabetArray[i];
console.log(stack);
}
}
} | [
"function stackLetters (alphabet) {\n}",
"function stackLetters (array) {\n /*\n Write a `for` loop that iterates over the array argument and\n outputs the letters.\n */\n\tfor (var i=0; i < array.length; i++) {\n\t\tnewAlpha += array[i];\n\t\tif ((newAlpha.length - 3)%4 === 0) {\n\t\t\tnewAlpha ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function will create a new todo object based on the text that was entered in the text input, and push it into the "todoItems array" | function addTodo(text) {
const todo = {
text,
checked : false,
id: Date.now(),
};
todoItems.push(todo);
renderTodo(todo);
} | [
"function createNewToDo() {\n const newToDoText = document.getElementById('newToDoText');\n\n // Guard clause to ensure that there is a value in the input element.\n if (!newToDoText.value) {\n return;\n }\n\n toDos.push({\n title: newToDoText.value,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes an event (either error or message) and sends it to Sentry. This also adds breadcrumbs and context information to the event. However, platform specific meta data (such as the User's IP address) must be added by the SDK implementor. | _processEvent(event, hint, scope) {
const options = this.getOptions();
const { sampleRate } = options;
if (!this._isEnabled()) {
return utils.rejectedSyncPromise(new utils.SentryError('SDK not enabled, will not capture event.', 'log'));
}
const isTransaction = event.type === 'transaction';
... | [
"_processEvent(event, hint, scope) {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.', 'log'));\n }\n\n const isTransaction = isTransactionEvent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an array of the items in the cart | function getItemsInCart(){
return items;
} | [
"get items() {\n\t\treturn this._cart.data\n\t}",
"getCartItems()\r\n\t{\r\n\t\tlet cart = Cookie.get(this.settings.cookie_name);\r\n\r\n\t\treturn (cart) ? cart.items : [];\r\n\t}",
"get cartItems () {\n return JSON.parse(this.storage.getItem(this.CART_KEY));\n }",
"cartItems (state) {\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders a drop down menu for selecting genres displays UI for selecting what type of playlist you want to generate | renderSelectGenre() {
return (
<div className='selectGenre'>
<form onSubmit={this.handleSubmit}>
<p>Select options from the dropdowns and we'll make you an awesome playlist!</p>
<select value={this.state.selectedGenre} onChange={this.handleChange}>
<option value=""... | [
"function showPlaylist(genres) {\r\n $('#' + Object.keys(genres)[0]).show();\r\n $('#playlistsDropdown').value = Object.keys(genres)[0];\r\n\r\n $('#playlistsDropdown').on('change', function () {\r\n $('.playlist').hide();\r\n $('#' + this.value).show();\r\n });\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load and update a message in the imap fake server | function loadImapMessage()
{
let gMessageGenerator = new MessageGenerator();
// create a synthetic message with attachment
let smsg = gMessageGenerator.makeMessage({
attachments: [
{filename: kAttachFileName, body: 'I like cheese!'}
],
});
let ioService = Cc["@mozilla.org/network/io-service;1"]... | [
"function loadImapMessage()\n{\n gIMAPMailbox.addMessage(new imapMessage(specForFileName(gMessage),\n gIMAPMailbox.uidnext++, []));\n gIMAPInbox.updateFolder(null);\n dl('wait for msgAdded notification');\n yield false;\n do_check_eq(1, gIMAPInbox.getTotalMessages(false));\n let msgHd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a promise that will resolve to the battery level | async getBatteryLevel () {
const readCharacteristic = await this._systemService.getCharacteristic(SYSTEM_READ_UUID);
const writeCharacteristic = await this._systemService.getCharacteristic(SYSTEM_WRITE_UUID);
await readCharacteristic.startNotifications();
const data = new Uint8Array([0xb5]).buffer;
... | [
"async getBatteryLevel() {\n const outputReportID = 0x01;\n const subCommand = [0x50];\n const data = [\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n ...subCommand,\n ];\n await this.device.sendReport(outputReportID, new Ui... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a GraphQLSchema for use by client tools. Given the result of a client running the introspection query, creates and returns a GraphQLSchema instance which can be then used with all graphqljs tools, but cannot be used to execute a query, as introspection does not represent the "resolver", "parse" or "serialize" fun... | function buildClientSchema(introspection, options) {
(0, _isObjectLike.default)(introspection) && (0, _isObjectLike.default)(introspection.__schema) || (0, _devAssert.default)(0, "Invalid or incomplete introspection result. Ensure that you are passing \"data\" property of introspection response and no \"errors\" was ... | [
"function buildClientSchema(introspection, options) {\n (0, _isObjectLike.default)(introspection) && (0, _isObjectLike.default)(introspection.__schema) || (0, _devAssert.default)(0, \"Invalid or incomplete introspection result. Ensure that you are passing \\\"data\\\" property of introspection response and no \\\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function for changing the SMTP Authentication Type Onclick event | function authenticationSMTPTypeChange(radioName){
var selValue = radioCheckedValueGet(radioName);
if (!selValue)
return;
switch (parseInt(selValue, 10)) {
case 1: /* None */
fieldStateChangeWr('tf1_tlsSupport tf1_txtSmtpLoginUserName tf1_txtSmtpLoginPwd', '', '', '');
... | [
"function enableAuthenticationPassword(type) {\n\tvar imgObjVal = document.getElementById('tf1_enableAuthPassword').className;\n\tvar imageName = imgObjVal.substring(imgObjVal.lastIndexOf('/') + 1);\n\tif (type == 'off') {\n\t\tfieldStateChangeWr('tf1_authPassword', '', '', '');\n\t\tvidualDisplay('tf1_authPassword... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
aaMeetingArray.push(new enterData(meetingId, stAdd, title, building, rmAdd, wheelchair, notes, weekday, pStartTime, pEndTime, startHour, startMin, endHour, endMin, meetingType, special)); _meetingId, _stAdd, _title, _building, _rmAdd, _wheelchair, _notes, | function enterData(_meetingId, _stAdd, _title, _building, _rmAdd, _wheelchair, _notes, _llCoor, _googAdd, _weekday, _pStartTime, _pEndTime, _startHour, _startMin, _endHour, _endMin, _meetingType, _special) {
var private = {};
private.id = _meetingId;
//private.addresInfo = _aaLocation;
... | [
"function setMeetingData()\n\t\t{\n\t\t\tmeetingData[\"subject\"] = inputSubject.value;\n\t\t\tmeetingData[\"starttime\"] = inputStartDate.value + \"T\" + inputStartTime.value + \":00\";\n\t\t\tmeetingData[\"endtime\"] = inputEndDate.value + \"T\" + inputEndTime.value + \":00\";\n\t\t\tmeetingData[\"passwordrequire... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if current direction is up or down | isUpOrDown() {
return direction === DIRECTIONS.UP || direction === DIRECTIONS.DOWN
} | [
"get isMovingUp() {\n return this.pointers.reduce((previous, pointer) => {\n return previous || pointer.isMovingUp;\n }, false);\n }",
"get isMovingUp () {\n return this.pointers.reduce((previous, pointer) => {return (previous || pointer.isMovingUp)}, false);\n }",
"get isUpArrowKeyDown() {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create zero matrix with dimension rows x cols | function createZeroMatrix(rows, cols) {
var m = [];
for(var r = 0; r < rows; r++) {
var row = [];
for(var c = 0; c < cols; c++) {
row.push(0);
}
m.push(row);
}
return m;
} | [
"static zeros(dims) {\n return Matrix2D.fromDims(dims, 0);\n }",
"function zero_matrix(cols, rows){\n var matrix;\n matrix = Array.apply(void 0, Array(cols)).map(\n function(){\n return(new Float32Array(rows));\n });\n return(matrix);\n }",
"function initBlankMatrix(width, h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builder class for constructing ConnectionCosts object | function ConnectionCostsBuilder() {
this.lines = 0;
this.connection_cost = null;
} | [
"function ConnectionCostsBuilder() {\n\t this.lines = 0;\n\t this.connection_cost = null;\n\t}",
"function CostTce() {\n\tthis.name = \"\";\n\tthis.linkIds = []; // String array\n\tthis.conditions = []; // TceConditon array\n\tthis.tollStructures = []; // TollStructure array\n}",
"function CostObject(taxC... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform an INPUT notes field into TEXTAREA | function transformNotesField(notesField) {
// Do nothing if the field is no INPUT field
if (notesField.nodeName != "INPUT") {
return;
}
// Replace hidden notes field with text area (keep id, name, value)
var newNotesField = document.createElement('textarea');
newNotesField.id = notesField.id;
newNote... | [
"function createTextArea(noteText) {\n let textArea=document.createElement(\"textarea\");\n textArea.setAttribute(\"id\",\"editableNote\");\n textArea.setAttribute(\"type\",\"text\");\n textArea.innerText=noteText;\n textArea.setAttribute(\"value\",noteText);\n textArea.setAttribute(\"cols\",\"25\");\n textA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View all products in stock | function viewProduct() {
var query =
'SELECT item_id, product_name, price, stock_quantity FROM products WHERE stock_quantity > 0';
connection.query(query, function(err, res) {
console.table(res);
reset();
});
} | [
"function viewAllProducts() {\r\n connection.query(\"SELECT * FROM products\", (err, res) => {\r\n if (err) throw err;\r\n console.log(\"\\n======================FULL INVENTORY=======================\\n\");\r\n console.table(res);\r\n managerCommands();\r\n }) \r\n}",
"function viewProductsForSale() {\n\t\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
for "Done adding" button subjects | function addSubject() {
var subjectID = $("#bootbox-subject-id").val();
addSubjectIDtoDataBase(subjectID);
if (subjectsTableData.length !== 0) {
$("#div-import-primary-folder-sub").hide();
}
if (subjectsTableData.length === 2) {
onboardingMetadata("subject");
}
} | [
"function MSTUDSUBJ_AddRemoveSubject(mode) {\n console.log(\"===== MSTUDSUBJ_AddRemoveSubject =====\");\n console.log(\" mode\", mode);\n\n const may_edit = (permit_dict.permit_crud && permit_dict.requsr_same_school);\n if(may_edit){\n\n let must_validate_subjects = false... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is called when the connection fail. | function onConnectionFailed(){
console.error("Connection Failed!")
} | [
"function onConnectionFailed() {\n\t\t\tlog(\"Connection failed\");\n\t\t}",
"onConnectionError() {\n\n }",
"function onConnectionFailed() {\r\n\t\t console.error('Connection Failed!');\r\n\t\t}",
"function onConnectionFailed() {\n console.error('Connection Failed!');\n }",
"handleConnectionError(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the average of all rates with 2 decimals conseguir un array con todos los average => y luego lo sumamos con reduce | function ratesAverage(array){
//arrayRates => array que tiene en cada posición el rate de cada película
var arrayRates = array.map(function(element){
if(isNaN(parseFloat(element.rate))){
//caso por si la propiedad rate es rate: "";
return 0.0;
}
return parseFloat(element.rate);
});... | [
"function ratesAverage(array) {\n const ratesTotal = array.reduce(function(previous, current) {\n return previous + parseFloat(current.rate);\n }, 0);\n console.log(ratesTotal / array.length);\n return ratesTotal / array.length;\n // console.log(ratesTotal / array.length).toFixed(2)));\n}",
"function rate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a promise which resolves to an Array of GroupBOs. Returns the group of the person by person id. | getGroupForPerson(id) {
return this.#fetchAdvanced(this.#getGroupURL(id))
.then((responseJSON) => {
let groupBOs = GroupBO.fromJSON(responseJSON);
return new Promise(function(resolve){
resolve(groupBOs);
})
})
} | [
"getPotentialPersonsForGroup(id) {\n \treturn this.#fetchAdvanced(this.#getPotentialPersonForGroupURL(id))\n .then((responseJSON) => {\n let personBOs = PersonBO.fromJSON(responseJSON);\n return new Promise(function(resolve){\n resolve(personBOs);\n })\n })\n }",
"getMembersO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |