query stringlengths 9 34k | document stringlengths 8 5.39M | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Function that shuffles cards based on css order | function shuffle(cards) {
cards.forEach(card => {
let randomize = Math.floor(Math.random() * 10);
card.style.order = randomize;
});
} | [
"function shuffle() {\n cards.forEach(card => {\n let randPos = Math.floor(Math.random() * 12);\n card.style.order = randPos;\n })\n}",
"function shuffleCards() {\n removeCards();\n const shuffleArray = cards.sort(() => Math.random() - 0.5);\n displayCards(shuffleArray);\n styleCards();\n}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sort the deliquents by percentLogged | function percentLoggedDesc(a,b) {
if (a.percentLogged < b.percentLogged) {
return -1;
} else if (a.percentLogged > b.percentLogged) {
return 1;
} else {
return 0;
}
} | [
"function sortChartData() {\n chartData.sort((element1, element2) => {\n return element2.percentUnique - element1.percentUnique;\n });\n }",
"function filterAndSort(langs) {\n return langs.filter(function(e) { return e.language })\n .sort(function(a,b) { return b.percent - a.percent })\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the debug window exists, then close it | function hideDebug() {
if (window.top.debugWindow && ! window.top.debugWindow.closed) {
window.top.debugWindow.close();
window.top.debugWindow = null;
}
} | [
"function closeHelpDesk() {\n window.close();\n}",
"function __zdbCloseWorkWindow(myWindowId){\n if(myWindowId == null) return false;\n application.activeWindow.close();\n application.activateWindow(myWindowId);\n return;\n}",
"function onClose() {\n\tdebug( 'Window closed. Dereferencing window obj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that gets the number input | function getNumber() {
// store the input as an integer in num
num = parseInt(input.value());
} | [
"function getInputNumber(input){\n if(inputNum == undefined){\n inputNum = input;\n }else{\n inputNum = (inputNum * 10) + (input * 1);\n }\n calcDisplay.value = inputNum; \n }",
"function getInputNumber(id){\n const Amount = document.getElementById(id).v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
$g by JoeSimmons. Supports ID, Class, and XPath (full with types) in one query Supports multiple id/class grabs in one query (split by spaces), and the ability to remove all nodes regardless of type See script page for syntax examples: | function $g(que, obj) {
if(!que || !(que=que.replace(/^\s+/,''))) return;
var obj=(obj?obj:({del:false,type:6,node:document})), r,
class_re=/^\.[A-Za-z0-9-_]/, id_re=/^\#[^\s]/, xp_re=/^\.?(\/\/|count|id)\(?[A-Za-z0-9\'\"]/;
if(!que || typeof que!='string' || que=='') return false;
else if(id_re.test(que)) {
var s=que.split(' '), r=new Array();
for(var n=0;n<s.length;n++) r.push(document.getElementById(s[n].substring(1)));
if(r.length==1) r=r[0];
} else if(xp_re.test(que)) {
r = document.evaluate(que,(obj['node']||document),null,(obj['type']||6),null);
switch((obj['type']||6)){case 1:r=r.numberValue;break;case 2: r=r.stringValue;break;case 3:r=r.booleanValue;break;case 8:case 9:r=r.singleNodeValue;break;}
} else if(class_re.test(que)) {
var expr='', s=que.split(' ');
for(var n=0;n<s.length && s[n].indexOf('.')==0;n++) expr+="@class='"+s[n].substring(1)+"' or ";
r = document.evaluate("//*["+expr.replace(/( or )$/,'')+"]",document,null,6,null);
if(r.snapshotLength==1) r=r.snapshotItem(0);
} else return null;
if(obj['del']===true && r) {
if(r.nodeType==1) r.parentNode.removeChild(r);
else if(r.snapshotItem) for(var i=r.snapshotLength-1; (item=r.snapshotItem(i)); i--) item.parentNode.removeChild(item);
else if(!r.snapshotItem) for(var i=r.length-1; i>=0; i--) if(r[i]) r[i].parentNode.removeChild(r[i]);
} else return r;
} | [
"function removeNodes (cssClass) {\n let selector = 'div.' + cssClass;\n let elements = document.querySelectorAll(selector);\n Array.prototype.forEach.call(elements, function (element) {\n document.body.removeChild(element);\n });\n}",
"function $g(que, O) {\r\nif(!que||typeof(que)!='string'||que==''||!(qu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switch to the video to the right in the playlist from the current one. | function shiftRight() {
right_video = current_video - 1;
if(right_video < 1) {
right_video = vid_array.length-1;
}
switchToVideo(right_video);
} | [
"function shiftLeft() {\n\tleft_video = current_video + 1;\n\tif (left_video >= vid_array.length) {\n\t\tleft_video = 1;\n\t}\n\tswitchToVideo(left_video);\n}",
"function forwardButtonTrigger() {\n if (window.currentVideoSelectedForPlayback) {\n setCurrentlyPlaying(false)\n const currentNode = window.curre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find closest panel and scroll to it | function findClosestPanel() {
var differences = [],
lowestDiff = Infinity
if (lowestDiff !== 0) {
// work out closest element
for (var i = 0; i < sections.length; i++) {
var difference = window.scrollY - sections[i].offsetTop
if (difference < 0) {
// turn any negative number into a positive
negativeDiff = true
difference = Math.abs(difference)
}
else {
negativeDiff = false
}
// if less than the last number, compare this with lowestDiff
// if smaller, updated difference and closestPanel
if (difference < lowestDiff) {
lowestDiff = difference
closestPanel = sections[i]
}
// briefly remove scrollInit
window.onscroll = null
scroll()
setTimeout(function(){
scrollInit()
}, 500)
}
}
} | [
"function panelScroll() {\n\t\"use strict\";\n\t$('.panel-group').one('shown.bs.collapse', function () {\n\t\tvar panelExpanded = $(this).find('.in');\n\t\t\n\t\t$('html, body').animate({\n\t\t\tscrollTop: panelExpanded.offset().top - 105\n\t\t}, 400);\n\t});\n}",
"function scrollSub(id){\n var topPos = document... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get date and time to start according to service window for current workrequest Calls WFR AbBldgOpsHelpDeskgetServiceWindowStartFromSLA Fills in date and time started | function getDateAndTimeStarted(){
var panel = View.panels.get('tool_form');
var wrId = panel.getFieldValue("wrtl.wr_id");
var result = {};
try {
result = Workflow.callMethod("AbBldgOpsHelpDesk-SLAService-getServiceWindowStartFromSLA", 'wr','wr_id',wrId);
}
catch (e) {
Workflow.handleError(e);
}
if (result.code == 'executed') {
var start = eval('(' + result.jsonExpression + ')');
//split isodate yyyy-mm-dd
temp = start.date_start.substring(1, start.date_start.length - 1).split("-");
date = FormattingDate(temp[2], temp[1], temp[0], strDateShortPattern);
//split isotime hh:mm:ss
tmp = start.time_start.substring(1, start.time_start.length - 1).split(":");
if (tmp[0] > 12) {
time = FormattingTime(tmp[0], tmp[1], "PM", timePattern);
}
else {
time = FormattingTime(tmp[0], tmp[1], "AM", timePattern);
}
$("tool_form_wrtl.date_start").value = date;
$("tool_form_wrtl.time_start").value = time;
$("Storedtool_form_wrtl.time_start").value = tmp[0] + ":" + tmp[1] + ".00.000";
}
else {
Workflow.handleError(result);
}
} | [
"function getDateAndTimeStarted(){\n var panel = View.getControl('', 'sched_wr_cf_cf_form');\n var wrId = panel.getFieldValue(\"wrcf.wr_id\");\n\n //kb:3024805\n\tvar result = {};\n\t//Retrieves service window start for SLA, next working day for this SLA after today ,file=\"ServiceLevelAgreementHandler\"\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the jsTree for the given selector | function updateTreeStructure(selector) {
$.getJSON(tree_url + '?dir=' + dir_url, function(data) {
if (data.html) {
/*
* Remove the existing tree, update the content and build the new tree.
* Need to do it this way, otherwise the tree doesn't open to the correct folder.
*/
$(selector).jstree('destroy');
$(selector).html(data.html);
createTree(selector);
}
});
} | [
"updateTreeSelection_() {\n if (angular.isUndefined(this.tree_)) {\n return;\n }\n\n this.tree_['deselect_all']();\n this.tree_['select_node'](this.selectionName_);\n }",
"function updateJSTree( updateJSTreeAction ) {\n //alert(\"JSTreeAction : \" + updateJSTreeAction);\n\n var objClassVal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the image (get the buffer and offset) into a new zipLoaderInstance | function parseImageFromZip(doSkipJPG, offsetInReader) {
return new Promise(function(resolve){
var zipLoaderInstance2 = ZipLoader.unzip( MLJ.core.Scene._zipFileArrayBuffer, doSkipJPG, offsetInReader );
resolve(zipLoaderInstance2);
});
} | [
"zipParser(blob){\n var zip = O.esri.zip;\n var _this = this;\n /*O.esri.*/zip.createReader(new /*O.esri.*/zip.BlobReader(blob), function (zipReader) {\n zipReader.getEntries(function (entries) {\n _this.initMap(entries);\n //if(entries)alert(\"TPK downloaded and unzipped!\");\n zip... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets if the provided structure is a JSDocableNodeStructure. | static isJSDocable(structure) {
switch (structure.kind) {
case StructureKind_1.StructureKind.Class:
case StructureKind_1.StructureKind.Constructor:
case StructureKind_1.StructureKind.ConstructorOverload:
case StructureKind_1.StructureKind.GetAccessor:
case StructureKind_1.StructureKind.Method:
case StructureKind_1.StructureKind.MethodOverload:
case StructureKind_1.StructureKind.Property:
case StructureKind_1.StructureKind.SetAccessor:
case StructureKind_1.StructureKind.Enum:
case StructureKind_1.StructureKind.EnumMember:
case StructureKind_1.StructureKind.Function:
case StructureKind_1.StructureKind.FunctionOverload:
case StructureKind_1.StructureKind.CallSignature:
case StructureKind_1.StructureKind.ConstructSignature:
case StructureKind_1.StructureKind.IndexSignature:
case StructureKind_1.StructureKind.Interface:
case StructureKind_1.StructureKind.MethodSignature:
case StructureKind_1.StructureKind.PropertySignature:
case StructureKind_1.StructureKind.Namespace:
case StructureKind_1.StructureKind.VariableStatement:
case StructureKind_1.StructureKind.TypeAlias:
return true;
default:
return false;
}
} | [
"static isJSDoc(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.JSDoc;\r\n }",
"static isJSDocableNode(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.ClassDeclaration:\r\n case typescript_1.SyntaxKind.ClassExpression:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
do invoice transition on save activity | function saveActivityAndDoTransition() {
Y.doccirrus.jsonrpc.api.activity.read( { query: { _id: ko.unwrap( activities[0] ) } } )
.then(function( res ) {
var
data = res.data && res.data[0],
isCorrectTransition = false;
// checking if transition is allowed
if( 'INVOICEREF' === data.actType || 'INVOICE' === data.actType ) {
fsm[data.status].forEach(function( item ) {
if( item.transition === transition.transition ) {
isCorrectTransition = true;
}
});
}
if( !isCorrectTransition ) {
Y.doccirrus.DCWindow.notice( {
type: 'info',
message: i18n( 'InCaseMojit.ActivityDetailsVM.error.not_correct_status' ),
window: {
width: 'medium'
}
} );
return null;
}
return data;
}).then(function( res ) {
if( res ) {
// test transition
activityDetailsVM.saveAttachmentsAndTransition( transitionArgs )
.then(function( res ) {
return res;
}).then(function() {
roundReceiptAmount = parseFloat( currentActivity && currentActivity.amount ? currentActivity.amount() : 0 ).toFixed( 2 );
roundOutstanding = parseFloat( res.totalReceiptsOutstanding ).toFixed( 2 );
if ( currentActivity && ( roundReceiptAmount !== roundOutstanding ) && ( 'pay' === transition.transition || 'derecognize' === transition.transition ) ) {
willBalanceInvoice = true;
}
if( !willBalanceInvoice ) {
Y.doccirrus.api.activity
.transitionActivity( {
activity: res,
transitionDescription: transition,
letMeHandleErrors: true,
isTest: true
} );
}
}).then(function() {
if( !willBalanceInvoice ) {
res.notCreateNew = true;
return Y.doccirrus.api.activity
.transitionActivity( {
activity: res,
transitionDescription: transition,
letMeHandleErrors: true,
isTest: false
} ).then( function() {
var patientId = unwrap( currentPatient._id() );
if( patientId ) {
caseFolders.load( { patientId: patientId } );
}
});
}
});
}
}).fail( function( error ) {
Y.Array.invoke( Y.doccirrus.errorTable.getErrorsFromResponse( error ), 'display' );
} );
} | [
"function saveInvoiceNumber( itcb ) {\n // this step only applies to invoices\n if ( 'INVOICE' !== activity.actType && 'RECEIPT' !== activity.actType ) { return itcb( null ); }\n\n var\n setArgs = {\n 'conten... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize the map of all resources in JSON | entitiesToJSON(){
let res = {
"id": this.id,
"resources": {}
};
(this.entitiesByID||{})::entries().forEach(([id,obj]) => res.resources[id] = (obj instanceof Resource) ? obj.toJSON(): obj);
return res;
} | [
"toJSON(depth = 0, initDepth = depth){\n\n /**\n * Converts a resource object into serializable JSON.\n * May fail to serialize recursive objects which are not instances of Resource\n * @param value - resource object\n * @param depth - depth of nested resources to output\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Byteswap an arbitrary buffer, flipping from one endian to the other, returning a new buffer with the resultant data | function byteswap64(buf) {
var swap = Buffer.alloc(buf.length);
for (var i = 0; i < buf.length; i++) {
swap[i] = buf[buf.length -1 - i];
}
return swap;
} | [
"function byteswap64(buf) {\n var swap = new Buffer(buf.length);\n for (var i = 0; i < buf.length; i++) {\n swap[i] = buf[buf.length -1 - i];\n }\n return swap;\n}",
"function to_little_endian(){\n\tbinary_input.reverse();\n\tbinary_key.reverse();\n}",
"function _swapEndian(val, length) {\n if (length <... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the selected values are allowed, IE we have resources named after it | function check_allowed() {
var material = $(select_div+" "+"#pd-material-type").find("option[selected]").attr("value");
var material_dict = get_material_dict(data, material);
var allowed = material_dict.allowed;
for(var i = 0; i < allowed.length; i++) {
var good = true;
var chem = allowed[i];
for(var j = 0; j < elements_nums.length; j++) {
if(chem[elements_nums[0]] != elements_nums[1]){
good = false;
break;
}
}
if(good){
return true
}
}
return false
} | [
"function validation_for_select_boxes(element){\n\tif(element.value != \"Default\")\n\t\treturn true;\n\telse{\n\t\talert(\"please select \"+ element.name);\n\t\treturn false;\n\t}\n}",
"function requireSelects ( form, requiredSelect ) {\n for ( var i = 0; i < requiredSelect.length; i++ ) {\n element = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if this relates to the active query being executed then immediately send the cancel, else the query can be removed from the queue and never submitted to the driver. | function cancel (notify, callback) {
const qid = notify.getQueryId()
if (workQueue.length() === 0) {
setImmediate(() => {
callback(new Error(`Error: [msnodesql] cannot cancel query (empty queue) id ${qid}`))
})
return
}
const first = workQueue.first((_idx, currentItem) => {
if (currentItem.commandType !== driverCommandEnum.QUERY) {
return false
}
const args = currentItem.args
const not = args[0]
const currentQueryId = not.getQueryId()
return qid === currentQueryId
})
if (first) {
if (first.paused) {
execCancel(qid, first, () => {
freeStatement(notify, () => {
workQueue.dropItem(first)
callback(null)
})
})
} else {
execCancel(qid, first, callback)
}
} else {
setImmediate(() => {
callback(new Error(`Error: [msnodesql] cannot cancel query (not found) id ${qid}`))
})
}
} | [
"function cancelQuery() {\n// console.log(\"Cancelling query, currentQuery: \" + qwQueryService.currentQueryRequest);\n if (qwQueryService.currentQueryRequest != null) {\n var queryInFly = mnPendingQueryKeeper.getQueryInFly(qwQueryService.currentQueryRequest);\n queryInFly && queryInFly.canc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns memory usage as a percentage of total memory available (0100) | function getMemUsage() {
var total = os.totalmem(),
usage = total - os.freemem(),
perc = usage / total * 100;
return {
usage : usage
, total : total
, percentage : perc
};
} | [
"function calcPhysicalMem()\n{\n\tvar os = require('os');\n\n\tvar totalm = (os.totalmem() / 1024 / 1024).toFixed(2);\n\tvar freem = (os.freemem() / 1024 / 1024).toFixed(2) ;\n\tvar usedm = (totalm - freem);\n\n\n\tmetrics[\"phys_mem_used\"].value = usedm;\n\tmetrics[\"phys_mem_free\"].value = freem;\n\tmetrics[\"p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates, or attempts to evaluate, a ForInStatement | function evaluateForInStatement({ node, environment, evaluate, logger, reporting, typescript, statementTraversalStack }) {
// Compute the 'of' part
const expressionResult = evaluate.expression(node.expression, environment, statementTraversalStack);
// Ensure that the initializer is a proper VariableDeclarationList
if (!typescript.isVariableDeclarationList(node.initializer)) {
throw new UnexpectedNodeError({ node: node.initializer, typescript });
}
// Only 1 declaration is allowed in a ForOfStatement
else if (node.initializer.declarations.length > 1) {
throw new UnexpectedNodeError({ node: node.initializer.declarations[1], typescript });
}
for (const literal in expressionResult) {
// Prepare a lexical environment for the current iteration
const localEnvironment = cloneLexicalEnvironment(environment);
// Define a new binding for a break symbol within the environment
setInLexicalEnvironment({ env: localEnvironment, path: BREAK_SYMBOL, value: false, newBinding: true, reporting, node });
// Define a new binding for a continue symbol within the environment
setInLexicalEnvironment({ env: localEnvironment, path: CONTINUE_SYMBOL, value: false, newBinding: true, reporting, node });
// Evaluate the VariableDeclaration and manually pass in the current literal as the initializer for the variable assignment
evaluate.nodeWithArgument(node.initializer.declarations[0], localEnvironment, literal, statementTraversalStack);
// Evaluate the Statement
evaluate.statement(node.statement, localEnvironment);
// Check if a 'break' statement has been encountered and break if so
if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, BREAK_SYMBOL)) {
logger.logBreak(node, typescript);
break;
}
else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, CONTINUE_SYMBOL)) {
logger.logContinue(node, typescript);
// noinspection UnnecessaryContinueJS
continue;
}
else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, RETURN_SYMBOL)) {
logger.logReturn(node, typescript);
return;
}
}
} | [
"function ForInStatement() {\n}",
"function evaluateForOfStatement({ node, environment, evaluate, logger, reporting, typescript, statementTraversalStack }) {\n // Compute the 'of' part\n const expressionResult = evaluate.expression(node.expression, environment, statementTraversalStack);\n // Ensure that ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
yesterday(thisDate) / /All my troubles seemed so far away. | function yesterday(thisDate) {
// adjustForLeapYears(thisDate);
if (thisDate[2]!=1) {
return [thisDate[0],thisDate[1],thisDate[2]-1];
} else if (thisDate[1]!=0) {
return [thisDate[0],thisDate[1]-1,monthLength[thisDate[1]-1]];
} else {
var tempYear = thisDate[0]-1;
adjustForLeapYears('yesterday()',tempYear);
return [tempYear,11,31];
}
} | [
"function getYesterday(){\n\treturn getDate(-1);\n}",
"getYesterday() {\n let yesterday = new Date();\n yesterday.setDate(yesterday.getDate() - 1);\n return this.format(yesterday);\n }",
"function dateForYesterday() {\n var date = new Date().toMidnight();\n date.setDate(date.getDate() - 1);\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The AnimationMixer is a player for animations on a particular object in the scene. When multiple objects in the scene are animated independently, one AnimationMixer may be used for each object. | function AnimationMixer() {
this._clips = {};
this._bindings = {};
this._activeClips = {};
} | [
"animationMixer(root) {\r\n const mixer = new AnimationMixer(root);\r\n this.mixers.add(mixer);\r\n return mixer;\r\n }",
"animationMixer(root) {\r\n const mixer = new types_1.AnimationMixer(root);\r\n this.mixers.add(mixer);\r\n return mixer;\r\n }",
"setupMixer(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
promap :: Profunctor p => (a > b, c > d, p b c) > p a d . . Function wrapper for [`fantasyland/promap`][]. . . `fantasyland/promap` implementations are provided for the following . builtin types: Function. . . ```javascript . > promap (Math.abs, x => x + 1, Math.sqrt) (100) . 11 . ``` | function promap(f, g, profunctor) {
return Profunctor.methods.promap (profunctor) (f, g);
} | [
"function promap(f, g, profunctor) {\n return Profunctor.methods.promap(profunctor)(f, g);\n }",
"function Function$prototype$promap(f, g) {\n var profunctor = this;\n return function(x) { return g (profunctor (f (x))); };\n }",
"function Function$prototype$promap(f, g) {\n var profunctor = this;\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Topic: BST, recursion For a Binary Search Tree find the 'kth' largest element Runtime: O(n) Space: O(h) | function findKthBiggest(root, k) {} | [
"function findLargest(root) {\n let current = root\n\n while(current) {\n if (!current.right) {\n return current.value\n }\n current = current.right\n }\n}",
"function largestNodeBST(root) {\n if (root == null) return null;\n else if (root.right == null) return root;\n else return larges... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fix roles when only one role is missing Valid is an array of json objects for players Player is a json object for a player Returns the updated valid array for the team | function fixSingleRole(valid, player, role) {
//slot 1:1 except when we have to fix jungle issues
if(role === 'Jungle' && !player['Smite']) {
var jungler = findJungler(valid);
if(!jungler) { // nobody has smite so we're jungle by default
player['Role'] = role;
valid.push(player);
return valid;
}
player['Role'] = jungler['Role'];
jungler['Role'] = 'Jungle';
valid.push(jungler);
valid.push(player);
}
else {
player['Role'] = role;
valid.push(player);
}
return valid;
} | [
"function verifyOneOfEachRoleInRecommendedTeam(){\n //Figure out what roles are missing\n var rolesToBeAdded = new Array();\n for (var i in classesMap)\n if (classesMap[i] == 0)\n rolesToBeAdded.push(i);\n\n //Starting from the rear, find the lowest scoring hero with more than 1 other ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether saved data and form data are different to avoid unnecessary popup. | function isSavedDataAndFormDataDifferent(){
var savedData = getSavedData();
var formData = getFormData();
delete(savedData._autosaveTime);
delete(formData.item);
return JSON.stringify(savedData) !== JSON.stringify(formData);
} | [
"function isSavedDataAndFormDataDifferent(){\n var savedData = getSavedData();\n var formData = getFormData();\n\n delete(savedData._autosaveTime);\n delete(formData.item);\n\n return JSON.stringify(savedData) !== JSON.stringify(formData);\n }",
"function hasDataChanged() {\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checkDate (yearField, monthField, dayField, STRING labelString [, OKtoOmitDay==false]) Check that yearField.value, monthField.value, and dayField.value form a valid date. If they don't, labelString (the name of the date, like "Birth Date") is displayed to tell the user which date field is invalid. If it is OK for the day field to be empty, set optional argument OKtoOmitDay to true. It defaults to false. | function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{ // Next line is needed on NN3 to avoid "undefined is not a number" error
// in equality comparison below.
if (checkDate.arguments.length == 4) OKtoOmitDay = false;
if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);
if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);
if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
else if (!isDay(dayField.value))
return warnInvalid (dayField, iDay);
if (isDate (yearField.value, monthField.value, dayField.value))
return true;
alert (iDatePrefix + labelString + iDateSuffix)
return false
} | [
"function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)\r\n{ // Next line is needed on NN3 to avoid \"undefined is not a number\" error\r\n // in equality comparison below.\r\n if (checkDate.arguments.length == 4) OKtoOmitDay = false;\r\n if (!isYear(yearField.value)) return warnI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
loadJSON Function: Parm 1: file path of the json file Return: No return Description: Load the JSON for our animals, and rebuild the DOM using renderAll after it has been retrieved. | function loadJSON(fileUrl) {
// Declare our xhr object
const xhr = new XMLHttpRequest();
// Set up the callback for our successful request
xhr.onload = function() {
// Parse the JSON
arry = JSON.parse(xhr.responseText);
console.log(arry);
renderAll(arry);
};
// Open the request
xhr.open('GET', fileUrl, true);
// Send the request
xhr.send();
} | [
"function loadJsonFile() {\n loadFile();\n}",
"function load_json() {\n var file = document.getElementById('file');\n \n if(file.files.length) {\n var reader = new FileReader();\n \n reader.onload = function(e) {\n //document.getElementById('... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks to see if value falls between first and last. | function between(first, last, value)
{
return (first < last ? value >= first && value <= last : value >= last && value <= first);
} | [
"function valueInRange(start, value, finish) {\n return start <= value && value <= finish;\n}",
"function valueInRange (start, value, finish) {\n\t return (start <= value) && (value <= finish);\n\t}",
"function valueInRange (start, value, finish) {\n return (start <= value) && (value <= finish);\n}",
"fu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Code below contains a closure related to the variable 'fact', but does not contain a closure relative to the variable 'data'. Note: Inner functions do not remember everything from outer functions. | function outerFn() {
var data = "Something from outer";
var fact = "Remember me!";
return function innerFn() {
// in debugger console, value
// of data is reference error
// while fact is string
// This is because, innerFn()
// is evaluated and fact is
// consequently able to be
// established as a variable
debugger
return fact;
}
} | [
"function outerFn(){\n\tvar data = \"something from outerFn\";\n\tvar fact = \"Remember me!\"\n\treturn function innerFn(){\n\t\t// if you keep the chrome dev tools open\n\t\t// this will pause our code and place us\n\t\t// in the sources tab where we can \n\t\t// examine variables\n\t\tdebugger\n\t\treturn fact;\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interface function for computing shape of output tensor. | computeOutputShape() {
throw new Error('Unimplemented.');
} | [
"computeOutputShape(inputShape) {\n const inputShapes = _utils_types_utils__WEBPACK_IMPORTED_MODULE_6__[\"normalizeShapeList\"](inputShape);\n if (inputShapes.length !== this.inputLayers.length) {\n throw new _errors__WEBPACK_IMPORTED_MODULE_2__[\"ValueError\"](`Invalid inputShape argument ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handlers for scrolling on the left hand panel (i.e. y axis). | function addLeftScrollbarHandlers() {
$(".scroll_y").bind("touchmove", function(event) {
// One event only, get position of touch as a percentage.
var that = $(this);
var touches = event.originalEvent.touches;
if (touches.length != 1) return;
var touch = touches[0];
// Compute position of touch as a percentage.
var yaxis = that.attr("id") == "vscroll";
var y = (touch.pageY - that.offset().top) / that.height();
var percent = y;
var temp = parseFloat(LEFTSCROLLNUB/100).toFixed(1);
var clampUpper = parseFloat(1-temp).toFixed(1);
percent = percent.clamp(0, (clampUpper));// 1 - (windowsize / (xaxis ? dDataSet.columns.length : dDataSet.rows.length) )
// Update scrollbars.
that.find(".nub_y").css("top", (percent * 100) + "%");
// Adjust the percentage relative to the window size.
if (yaxis) target_wRow = Math.floor(_ROWLENGTH * percent);
else target_wcOL = Math.floor(_COLLENGTH * percent);
scrollAnimate_Y();
});
$('#downarrow').bind("touchstart", function(event) {
var that = $(this);
that.attr("src", "images/arrowdn_sel.png");
if(target_wRow < parseInt(_ROWLENGTH)-windowsize && target_wRow > -1) {
target_wRow += 1;
scrollAnimate_Y();
}
});
$('#uparrow').bind("touchstart", function(event) {
var that = $(this);
that.attr("src", "images/arrow_sel.png");
if(target_wRow > -1) {
target_wRow -= 1;
scrollAnimate_Y();
}
});
$('#downarrow').bind("touchend", function(event) { var that = $(this); that.attr("src", "images/arrowdn.png"); });
$('#uparrow').bind("touchend", function(event) { var that = $(this); that.attr("src", "images/arrow.png"); });
} | [
"function eltdSideAreaScroll(){\n\n\n }",
"function addLeftNavigationScrollbar() {\n\taddLeftGraphicalScrollbar();\n\tadjustLeftScrollbarSize();\n\taddLeftScrollbarHandlers();\n}",
"handleMouseScroll(e) {\n //\n }",
"function edgtfSideAreaScroll(){\n\t\tvar sideMenu = $('.edgtf-side-menu');\n\t\t\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
' Name : verifyPromocode ' Return type : Boolean ' Input Parameter(s) : none ' Purpose : This method is used to call check the state of Promo code. ' History Header : Version Date Developer Name ' Added By : 1.0 19 Feb 2014 UmamaheswaraRao ' | function verifyPromocode() {
var visiblePromoCodeInputId = getVisiblePromoCodeBoxId();
var promocodeEntryValue = $("#" + visiblePromoCodeInputId).val();
if(promocodeEntryValue) {
if(validationTracking === NOTVALIDATED){
promoCodeErrorHandling(messages['promocode.state.error1'], visiblePromoCodeInputId);
activateCheckoutPayButton();
return false;
} else if(validationTracking === UNVALIDATED){
promoCodeErrorHandling(messages['promocode.state.error2'], visiblePromoCodeInputId);
activateCheckoutPayButton();
return false;
}
}
return true;
} | [
"function $checkIfValidPromocode(){\n\t\t if(window.console){if(!console.trace) {console.trace = console.log;}}\n\t\t/*\n\t\tIf the promo code is valid, update the price, add logic here via regex or API\n\n\t\tExample :*/\n\t\tvar discountCodeInputValue = $('#discount_coupon').val();\n\t\t\n\t\t//this API call woul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recieves nativeParams from an adUnit. If the params were not of type 'type', passes them on directly. If they were of type 'type', translate them into the predefined specific asset requests for that type of native ad. | function processNativeAdUnitParams(params) {
if (params && params.type && typeIsSupported(params.type)) {
return SUPPORTED_TYPES[params.type];
}
return params;
} | [
"function buildNativeRequest(nativeReq) {\n let request = {ver: '1.1', assets: []};\n for (let k of Object.keys(nativeReq)) {\n let v = nativeReq[k];\n let desc = NATIVE_INDEX[k];\n if (desc === undefined) {\n continue;\n }\n let assetRoot = {\n id: desc.id,\n required: ~~v.required,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of cards in the deck. | function getNumCards(deck)
{
return deck.length;
} | [
"function cardCount(_deck) {\r\n if (!_deck) {\r\n console.log(\"cardCount: no deck id specified\");\r\n return;\r\n }\r\n \r\n console.log(\"cardCount for deck \" + _deck);\r\n \r\n var deck = $(\"#\"+_deck);\r\n if (deck.length == 0) {\r\n console.log(\"c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find image from instagram | function findPictureOf(keyword){
var response = getResultsFromSite(keyword);
//loop through the responses and find the ones with location
for (var i = 0; i < response.length; i++){
//can create a function out side and call it
//encapsulated anonymous function - put in a function because the part with the marker is async and takes longer, so you will be done with the for loop before you reach
if (response[i].images.standard_resolution.url){
console.log("Image found at index " + i);
console.log(response[i].images.standard_resolution.url);
(function(i){
image = '<img src='+response[i].images.standard_resolution.url+' />';
})(i);
break;
}
}
return image;
} | [
"function findImg(search, cb) {\n \n // add `+animated+filetype:gif` to the search for maximum funtimes\n \n $.getJSON(\"http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=\"+search+\"+moustache&callback=?\",\n function(data){\n // TRY ME LATER: What about storing the whole doc in the the Mustac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get books Local Storage | static getBooks() {
let books;
if (localStorage.getItem("books") === null) {
books = [];
} else {
books = JSON.parse(localStorage.getItem("books"));
}
return books;
} | [
"static getBooks() {\n let books = JSON.parse(localStorage.getItem('books')) || [];\n return books;\n }",
"static getBooksFromLS() {\n let books;\n if (localStorage.getItem('books') === null) {\n books = [];\n } else {\n books = JSON.parse(localStorage.getItem('book... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws democratic words onto the layout | function drawDem(words) {
svgDem.append("g")
.attr("transform", "translate(" + layoutDem.size()[0] / 2 + "," + layoutDem.size()[1] / 2 + ")")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("fill", "#4682B4")
.style("font-family", "Impact")
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.word; });
} | [
"function drawWords() {\n\tctx.font = \"18px Arial\";\n\tctx.fillStyle = \"white\";\n\tctx.textAlign = \"center\";\n\tfor(var i = 0; i < words.length; i++) {\n\t\tctx.fillText(words[i], xPos[i], yPos[i]);\n\t}\n}",
"function drawWords() {\n\n\t// Draw out each word in the array of word objects\n\tfor (object in w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edit book status we will call this funciton inside of the click handler function in order to pass the book ID and statusChange | function changeReadStatus(bookID, currentStatus) {
$.ajax({
method: 'PUT',
// need the book ID in the url
// can grab with data-id
// will get with the click handler
url: `/books/isRead/${bookID}`,
data: {
currentStatus: currentStatus,
},
})
.then(function (response) {
refreshBooks();
})
.catch(function (err) {
console.log('error', err);
alert('Error! Try again later');
});
} | [
"function changeStatus(e) {\n let bookIndex = e.target.dataset.index;\n let chosenBook = library[bookIndex];\n\n if (chosenBook.readStatus == \"already read\") {\n chosenBook.readStatus = \"unread\";\n } else {\n chosenBook.readStatus = \"already read\";\n }\n createTable();\n sav... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The description of the directory. If this directory is not a mailing list, then setting this attribute will send round a "DirName" update via nsIAddrBookSession. attribute AString dirName; | get dirName()
{
//exchWebService.commonAbFunctions.logInfo("exchangeAbFolderDirectory: get dirName\n");
var result = exchWebService.commonAbFunctions.getDescription(this.uuid);
if (this.useGAL) {
result = result + " (+GAL)";
}
return result;
} | [
"get directory() {\n return this._directory;\n }",
"get description()\n\t{\n\t\texchWebService.commonAbFunctions.logInfo(\"exchangeAbFolderDirectory: get description\\n\");\n\t\treturn this._description;\n\t}",
"get dir(){\r\n\t\treturn path2lst(this.path).slice(0, -1).join('/') }",
"get dirPrefId()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets a value on the control with the given name attribute | function setValue(name, value) {
var nameSelect = "[name='" + escapeName(name) + "']";
jq(nameSelect).val(value);
} | [
"function setValueByName (name, value) {\n\n}",
"function setValueByName(name, value) {\n document.getElementsByName(name)[0].value = value;\n}",
"function setAttrByName (attributename, value){\n var attribute = findAttribute(attributename);\n attribute.set(\"current\", value);\n}",
"setAttribute(name,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search for Quiz using title using fuzzy module | searchTitleFuzzy(input){
// Fuzzy Search the quiz title
let results = fuzzy.filter(input, this.quizList, {extract: (el) => {
return el.title;
}})
this.searchFuzzy(results);
} | [
"searchTitle(){\r\n let userQueryRegex = /.*\\S.*/; // Input cannot be blank\r\n let userQuery = read.question(\"Search Quiz Title: (-1 to exit)\\n>> \", {limit: userQueryRegex, limitMessage: \"Type something!\"});\r\n\r\n if(userQuery == -1) this.searchAQuiz();\r\n else this.searchTit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::WAFv2::WebACL.TextTransformation` resource | function cfnWebACLTextTransformationPropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnWebACL_TextTransformationPropertyValidator(properties).assertSuccess();
return {
Priority: cdk.numberToCloudFormation(properties.priority),
Type: cdk.stringToCloudFormation(properties.type),
};
} | [
"renderProperties(x) { return ui.divText(`Properties for ${x.name}`); }",
"format() {\n if(this.properties[\"text\"]) {\n this.formattedText = this.addLineBreaks(this.properties[\"text\"], 27);\n }\n }",
"function TextProperty() {}",
"function displayText(text, x, y, properties){\n\tctx.save();\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
method simplex2_out() search index for out from basis | simplex2_out() {
var ind = -1;
var a = 0;
for (let i=0; i<this.n; i++) {
if (this.b_numerator[i] >= 0) continue;
if (this.b_numerator[i] / this.b_denominator[i] < a) {
ind = i;
a = this.b_numerator[i] / this.b_denominator[i];
}
}
return ind;
} | [
"simplex_out(index_in) {\n\t\tvar ind = -1;\n\t\tvar min_a = 0;\n\t\tfor (let i=0; i<this.n; i++) {\n\t\t\tif (this.numerator[i][index_in] <= 0) continue;\nvar a = (this.b_numerator[i] / this.b_denominator[i]) * (this.denominator[i][index_in] / this.numerator[i][index_in]);\n\t\t\tif (a < 0) continue;\n\t\t\tif (in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
O(kn) time and O(n) space where K is the number of maxSteps and n is the height of the stairs and the size of the memoization structure | function staircaseTraversal(height, maxSteps) {
return stairsHelper(height, maxSteps, {0:1, 1:1});
// Write your code here.
function stairsHelper(height, maxSteps, memoize) {
if(height in memoize) return memoize[height];
let ways = 0;
for(let step = 1; step < Math.min(maxSteps, height) + 1; step++) {
ways += stairsHelper(height - step, maxSteps, memoize);
}
memoize[height] = ways;
return ways;
}
} | [
"function stepPerms(n) {\n // set a counter variable to keep track of how many ways\n // return the number of different ways to climb the stairs\n\n // find a base case\n // if the steps left is negative, return 0\n // if we have no steps left, return 1\n // memoization: if cache[n] exists, return the cache\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes the active camera | updateCamera() {
this.camera = this.cameras.get(this.currentCameraID);
this.interface.setActiveCamera(this.camera);
} | [
"updateCamera() {\n this.camera = this.cameras[this.selectedCamera];\n this.interface.setActiveCamera(this.camera);\n }",
"setCamera(camera) {\n this.activeCamera = camera;\n }",
"updateCurrentCamera() {\n this.camera = this.cameras[this.selectedCamera];\n this.camera.reset();\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new CUBRID connection instance | function CUBRIDConnection(brokerServer, brokerPort, user, password, database, cacheTimeout) {
// Using EventEmitter.call on an object will do the setup of instance methods / properties
// (not inherited) of an EventEmitter.
// It is similar in purpose to super(...) in Java or base(...) in C#, but it is not implicit in Javascript.
// Because of this, we must manually call it ourselves:
EventEmitter.call(this);
this._queryCache = null;
if (typeof cacheTimeout !== 'undefined' && cacheTimeout > 0) {
this._queryCache = new Cache();
}
this._socket = new Net.Socket();
// Connection parameters
this.brokerServer = brokerServer || 'localhost';
this.initialBrokerPort = brokerPort || 33000;
this.connectionBrokerPort = -1;
this.user = user || 'public';
this.password = password || '';
this.database = database || 'demodb';
// Session public variables
this.autoCommitMode = null; //will be initialized on connect
this.sessionId = 0;
// Execution semaphore variables; prevent double-connect-attempts, overlapping-queries etc.
this.connectionOpened = false;
this.connectionPending = false;
this.queryPending = false;
// Driver events
this.EVENT_ERROR = 'error';
this.EVENT_CONNECTED = 'connect';
this.EVENT_ENGINE_VERSION_AVAILABLE = 'engine version';
this.EVENT_BATCH_COMMANDS_COMPLETED = 'batch execute done';
this.EVENT_QUERY_DATA_AVAILABLE = 'query data';
this.EVENT_SCHEMA_DATA_AVAILABLE = 'schema data';
this.EVENT_FETCH_DATA_AVAILABLE = 'fetch';
this.EVENT_FETCH_NO_MORE_DATA_AVAILABLE = 'fetch done';
this.EVENT_BEGIN_TRANSACTION = 'begin transaction';
this.EVENT_SET_AUTOCOMMIT_MODE_COMPLETED = 'set autocommit mode';
this.EVENT_COMMIT_COMPLETED = 'commit';
this.EVENT_ROLLBACK_COMPLETED = 'rollback';
this.EVENT_QUERY_CLOSED = 'close query';
this.EVENT_CONNECTION_CLOSED = 'close';
this.EVENT_LOB_READ_COMPLETED = 'lob read completed';
//Auto-commit constants
this.AUTOCOMMIT_ON = true;
this.AUTOCOMMIT_OFF = false;
//Database schema variables
this.SCHEMA_TABLE = CASConstants.CUBRIDSchemaType.CCI_SCH_CLASS;
this.SCHEMA_VIEW = CASConstants.CUBRIDSchemaType.CCI_SCH_VCLASS;
this.SCHEMA_ATTRIBUTE = CASConstants.CUBRIDSchemaType.CCI_SCH_ATTRIBUTE;
//Private variables
this._CASInfo = [0, 0xFF, 0xFF, 0xFF];
this._queriesPacketList = [];
this._INVALID_RESPONSE_LENGTH = -1;
this._PREVENT_CONCURRENT_REQUESTS = true;
this._LOB_MAX_IO_LENGTH = 128 * 1024;
//Database engine version
this._DB_ENGINE_VER = '';
//Uncomment the following lines if you will not always provide an 'error' listener in your consumer code,
//to avoid any unexpected exception. Be aware that:
//Error events are treated as a special case in node. If there is no listener for it,
//then the default action is to print a stack trace and exit the program.
//http://nodejs.org/api/events.html
//this.on('error',function(err){
// Helpers.logError(err.message);
// //... (add your own error-handling code)
//});
} | [
"function CUBRIDConnection(brokerServer, brokerPort, user, password, database, cacheTimeout) {\n // Using EventEmitter.call on an object will do the setup of instance methods / properties\n // (not inherited) of an EventEmitter.\n // It is similar in purpose to super(...) in Java or base(...) in C#, but it is no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=================================================================== from functions/io/FlushOut.java =================================================================== Needed early: Builtin Needed late: IO ArcObject | function FlushOut() {
} | [
"_final(cb) {\n // flush outstream\n this.flushOutstream(true)\n .then(() => {\n cb();\n })\n .catch((err) => cb(err)); // cb and return\n }",
"_flush() {\n const centralDirectoryOffset = this._offset;\n let centralDirectorySize = 0;\n for (const i in this._files)\n this... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Raises "Not Implemented" exception | static notImplemented_() {
throw new Error('Not implemented');
} | [
"notImplemented () {\n throw new Error('Not Implemented')\n }",
"function notImplemented() {\n throw new Error(\"Not implemented\");\n }",
"function notImplemented(){throw new Error(\"Not implemented\");}",
"function notImplemented() {\n throw new Error(\"Not implemented\");\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the global variable that holds the request Send the request to the server to get the last week questions | function processlastWeek() {
lastWeekClient = new XMLHttpRequest();
var url = 'http://developer.cege.ucl.ac.uk:'+ httpPortNumber + "/getlastWeek/";
lastWeekClient.open('GET',url,true);
lastWeekClient.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
lastWeekClient.onreadystatechange = lastWeekUploaded;
lastWeekClient.send();
} | [
"function informAboutQuiz(date) {\n var start_date = new Date(date)\n var end_date = new Date(date)\n end_date.setHours(end_date.getHours() + 1)\n request = `${DEADLINE_SCHEDULING_SUGGESTION_API}/${COLLEGE_NAME}/inform_about_event/quiz/${quiz_course_selection_dropdown.value}/${start_date.toISOString()}/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Record a guest's order in DOM and in memory, clear the current order, prep for next guest | function completeGuest () {
if (currentOrder.length > 0) {
$("#checkButton").show();
$("#orderButton").text("Click an item to start another order");
var items = $("#currentOrder").children().clone();
$("#totalOrder,.guestOrder").append(items);
$("#currentOrder h2").remove();
$("#totalOrder h3").last().remove();
guest += 1;
order.push(currentOrder);
currentOrder = [];
$("#currentOrder h3").text("Guest" + guest);
};
} | [
"function resetActiveOrder () {\n activeOrder = {};\n}",
"function saveAndPrintOrderList() {\n orders.push(currentOrder);\n\n // Reset current order numbers\n currentOrderNumber = 1;\n for (var i=0; i<orders.length; i++) {\n currentOrder = orders[i];\n printCurrentOrder();\n curr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pull user can define a specific pool. if he defines 0 then all pools _places user can define a specific places in a pool. if 0 all places | function depositWithNodes(uint _pull, uint _places) external payable {
deposit();
if (_pull == 0 && _places == 0) {
return;
}
changePool(_pull, _places);
} | [
"function poolClickHandler(e) {\n let elm = $(e.target);\n\n if (elm.hasClass('deletePool')) {\n let name = elm.first().prev().text();\n let data = {name: name};\n log('/leavePool', name);\n $.post('/leavePool', data);\n elm.parent().remove();\n if ($('.pool').length == 0) {\n $('#poolGraph... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Step 3: when the add news button is clicked, set the state of addNews to true and display the component declared below | addNewsClick(){
this.setState({
addNews: true,
})
} | [
"render(){\n let addNews=\"\"\n if(this.state.addNews === true){\n addNews = <AddEditNews\n handleFieldChange={this.handleFieldChange}\n editNews={this.state.editNews}closeModal={this.closeModal}\n addNews={this.state.addNews} editArticleChanges={this.editArticleChanges} addNewArticle={thi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates the SSN to 10 digit number | validateSSN(ssn) {
if (!this.isNumeric(ssn) || ssn.toString().length !== 10) {
return { numeric: false, error: "SSN can only be a 10 digit number" };
} else {
return { numeric: true, error: null };
}
} | [
"function SSNValidation(ssn) {\r\nvar matchArr = ssn.match(/^(\\d{3})-?\\d{2}-?\\d{4}$/);\r\nvar numDashes = ssn.split('-').length - 1;\r\nif (matchArr == null || numDashes == 1 || numDashes == 0) {\r\nalert('Invalid SSN. Must be 9 digits in the format (###-##-####).');\r\nmsg = \"does not appear to be valid\";\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert strings to boolean | function toBoolean(string) {
if (string === 'true') {
return true;
} else if (string === 'false') {
return false;
}
} | [
"function stringToBoolean(str) {\n\tif (str == \"true\") {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function str2bool(str){\n return str===\"Y\" ? true : false;\n}",
"function stringToBoolean(string) {\n\tswitch(string.toLowerCase()) {\n\t\tcase \"true\":\n\t\tcase \"yes\":\n\t\tcase \"on\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create puzzle piece divs row by row with correct portion of photo | function slicepuzzle()
{
// get number of pieces from input form
piecenumber = $("input[name=piecenumber]:checked").val();
// total number of pixels in the photo
totalpixels = photox * photoy;
// total number of pixels in each puzzle piece
piecepixels = totalpixels / piecenumber;
// x and y dimension of square piece
piecesize = Math.sqrt(piecepixels);
// number of rows and columns of pieces inside photo
piecerows = photoy / piecesize;
piececols = photox / piecesize;
// create puzzle pieces row by row
for (i = 0; i < piecerows; i++)
{
for (j = 0; j < piececols; j++)
{
// create piece and number it by id
$("#puzzlec").append("<div class='piece' id='piece" + i + j + "'></div>");
// set user-selected (or default) background-image of each piece and resize
$("#piece" + i + j).css("background-image", pic);
$("#piece" + i + j).css("background-size", bgsize);
// set position of imaage inside of piece
var xpos = (-1 * piecesize) * j;
var ypos = (-1 * piecesize) * i;
var bgpos = xpos + "px " + ypos + "px";
$("#piece" + i + j).css("background-position", bgpos);
// here's that amazing jQuery magic for dragging DIV's and snapping to grid
$("#piece" + i + j).draggable({containment: "#puzzlec"});
$("#piece" + i + j).draggable({snap: "#puzzlec"});
$("#piece" + i + j).draggable({snap: ".piece"});
}
}
// set the width and height for all pieces in the css class, including 1px border on each edge
$(".piece").css("width", piecesize-2);
$(".piece").css("height", piecesize-2);
// fade in completed puzzle
$("#puzzlec").animate({opacity: "1"},500,"linear");
// randomize piece placement!
shakepuzzle();
// start checking for solutions
$(".piece").mouseup(function(){solution();});
} | [
"function slicepuzzle()\n{\n\t// calculate number of pieces in each row and column based on total number of pieces\n\t// find middle factors of piecenum so rows and columns are even\n\tvar piecegrid = midfactors(piecenumber);\n\t\n\t// bigger number of grid pair goes for bigger photo dimension\n\tpiececols = ((phot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
init :: (Applicative f, Foldable f, Monoid (f a)) => f a > Maybe (f a) . . Returns Just all but the last of the given structure's elements if the . structure contains at least one element; Nothing otherwise. . . ```javascript . > S.init ([1, 2, 3]) . Just ([1, 2]) . . > S.init ([]) . Nothing . . > S.init (Cons (1) (Cons (2) (Cons (3) (Nil)))) . Just (Cons (1) (Cons (2) (Nil))) . . > S.init (Nil) . Nothing . ``` | function init(foldable) {
// Fast path for arrays.
if (Array.isArray (foldable)) {
return foldable.length > 0 ? Just (foldable.slice (0, -1)) : Nothing;
}
var empty = Z.empty (foldable.constructor);
return Z.map (Pair.snd, Z.reduce (function(m, x) {
return Just (Pair (x) (maybe (empty) (pair (append)) (m)));
}, Nothing, foldable));
} | [
"function init(xs) {\n return xs.length > 0 ? Just (xs.slice (0, -1)) : Nothing;\n }",
"function _init(array) {\n for (var i = 0, len = array.length; i < len; i++) {\n var value = array[i];\n if (Array.isArray(value)) {\n _init(value);\n }\n else if (value == undefined) {\n array[i] = 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculates the max possible sum from the midpoint up | function greatestRightMovingSum(nums, midPoint, end) {
let sum = 0;
let greatestSum = -Infinity;
for (let i = midPoint; i <= end; i++) {
sum += nums[i];
if (sum > greatestSum) greatestSum = sum;
}
return greatestSum;
} | [
"function greatestLeftMovingSum(nums, start, midPoint) {\n let sum = 0;\n let greatestSum = -Infinity;\n for (let i = midPoint; i >= 0; i--) {\n sum += nums[i];\n if (sum > greatestSum) greatestSum = sum;\n }\n return greatestSum;\n}",
"maxSum() {\n let maxResult = 0;\n\n const findMaxSum = node ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the strength of the player | function set_player_strength(Player, hand) {
Player.player_strength = get_hand_strength(hand);
return Player;
} | [
"ChangeStrength(int, int, int) {\n\n }",
"set wavingGrassStrength(value) {}",
"set shadowStrength(value) {}",
"addStrength(num) {\n this.strength = lodash_1.clamp(this.strength + num, 1, this.game.maxWebStrength);\n if (this.load >= this.strength) {\n this.snap();\n }\n }... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a string describing the remote address of a socket. | function describeAddress(socket) {
if (socket.remoteFamily === "IPv6") {
return `[${socket.remoteAddress}]:${socket.remotePort}`;
}
return `${socket.remoteAddress}:${socket.remotePort}`;
} | [
"getMeaningfulIPTo(socket) {\n if (api.isLoopbackAddress(socket)) {\n return '127.0.0.1';\n } else if (api.isPrivateNetwork(socket)) {\n return api.getLocalIP();\n } else {\n return api.getExternalIP();\n }\n }",
"GetRemoteAddr()\n {\n if(this._SocketValid())\n {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove product modifiers of specific cart item, based on cart item ID | function removeProductModifier(itemID){
itemModifiers = JSON.parse(window.localStorage.getItem('itemModifiers'))
if (itemID in itemModifiers) {
delete itemModifiers[itemID]
}
window.localStorage.setItem('itemModifiers',JSON.stringify(itemModifiers))
} | [
"function remove_from_cart(product_id) {\n removeProduct(product_id);\n}",
"cartMinusOne(product, id) {\r\n if (product.quantity == 1) {\r\n this.cartRemoveItem(id);\r\n } else {\r\n product.quantity = product.quantity - 1;\r\n }\r\n }",
"function removeFromCart (item) {\n co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables or disables the UI. Typically while the image is uploading. | disableUploadUi(disabled){this.uploadButton.prop('disabled',disabled);this.addButton.prop('disabled',disabled);this.addButtonFloating.prop('disabled',disabled);this.imageCaptionInput.prop('disabled',disabled);this.overlay.toggle(disabled)} | [
"enable() {\r\n if (!this.isEnabled) {\r\n this.isEnabled = true;\r\n this.show();\r\n }\r\n }",
"function enableImageUI(layer) {\n $imageViewer.find('.imageLayers div[id=\"imageLayer_' + layer.id + '\"] ul')\n .find('button, input').each(function (... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the symbol with the given name. | function lisp_intern(name) {
var native_string = lisp_string_native_string(name);
var symbol = lisp_symbols_table[native_string];
if (typeof(symbol) !== "undefined") {
return symbol;
} else {
symbol = lisp_make_symbol_do_not_call(name);
lisp_symbols_table[native_string] = symbol;
return symbol;
}
} | [
"_getSymbol(name){\n if(!this.__symbols[name]){\n this.__symbols[name] = Symbol(name);\n }\n return this.__symbols[name];\n }",
"symbol(name, searchContext) {\r\n return this.symbols(searchContext)[name];\r\n }",
"function getSymbolValue(state, name) {\n if ((0, labels_1.is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the kernelspec for a kernel. | function getKernelSpec(kernel, baseUrl, ajaxSettings) {
var url = utils.urlPathJoin(baseUrl, KERNELSPEC_SERVICE_URL, encodeURIComponent(kernel.name));
ajaxSettings = ajaxSettings || {};
ajaxSettings.dataType = 'json';
ajaxSettings.cache = false;
return utils.ajaxRequest(url, ajaxSettings).then(function (success) {
if (success.xhr.status !== 200) {
return utils.makeAjaxError(success);
}
var data = success.data;
try {
validate.validateKernelSpecModel(data);
}
catch (err) {
return utils.makeAjaxError(success, err.message);
}
return data.spec;
}, onKernelError);
} | [
"function getKernelSpecs(options) {\n if (options === void 0) { options = {}; }\n var baseUrl = options.baseUrl || utils.getBaseUrl();\n var url = utils.urlPathJoin(baseUrl, KERNELSPEC_SERVICE_URL);\n var ajaxSettings = utils.copy(options.ajaxSettings || {});\n ajaxSettings.method = 'GET';\n ajaxS... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PRIVATE MODULE METHODS An example of a private method. Feel free to remove this. | function modulePrivateMethod () {
return;
} | [
"function internalPrivateThing() {}",
"function Utils() {\n\t\n }",
"function LeathermanModule() {\n }",
"function _privateFn(){}",
"function Module(){}",
"function Helpers() {\r\n }",
"protected internal function m252() {}",
"function Helpers() {\n}",
"function constructor()\n {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the minimum axisaligned 3D boundary enclosing the given 3D points. | points3ToAABB3(points, aabb = math.AABB3()) {
let xmin = math.MAX_DOUBLE;
let ymin = math.MAX_DOUBLE;
let zmin = math.MAX_DOUBLE;
let xmax = -math.MAX_DOUBLE;
let ymax = -math.MAX_DOUBLE;
let zmax = -math.MAX_DOUBLE;
let x;
let y;
let z;
for (let i = 0, len = points.length; i < len; i++) {
x = points[i][0];
y = points[i][1];
z = points[i][2];
if (x < xmin) {
xmin = x;
}
if (y < ymin) {
ymin = y;
}
if (z < zmin) {
zmin = z;
}
if (x > xmax) {
xmax = x;
}
if (y > ymax) {
ymax = y;
}
if (z > zmax) {
zmax = z;
}
}
aabb[0] = xmin;
aabb[1] = ymin;
aabb[2] = zmin;
aabb[3] = xmax;
aabb[4] = ymax;
aabb[5] = zmax;
return aabb;
} | [
"function minimum3 (x,y,z) {\n return Math.min(x, y, z);\n}",
"function bezier_bounds(p0, p1, p2, p3, width)\n{\n\t// This computes the coefficients of the derivative of the bezier curve.\n\t// We will use this to compute the zeroes to get the maxima.\n\tlet a = -p0 + 3 * p1 - 3 * p2 + p3;\n\tlet b = 2 * p0 ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the stops as an array of Stops object (array of Jsons) by reading the stops table | function getStops() {
stopsTableRows = getStopsTableRows()
stops = []
for (var i = 0; i < stopsTableRows.length; i++) {
row = stopsTableRows[i]
rowID = row.id
airportInputID = getAirportInputID(rowID)
daysInputID = getDaysInputID(rowID)
airport = $("#" + airportInputID).val()
days = $("#" + daysInputID).val()
var stopObject = Object()
stopObject.airport = airport
stopObject.days = days
stops.push(stopObject)
}
return stops
} | [
"function getStops () {\n return StopsForage.get();\n }",
"_getStops() {\n const properties = this._properties;\n const stopsProperties = properties.stops;\n const defaultStopCount = 10;\n let stops = null;\n\n // If stop properties are defined\n if (stopsProperties) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a feature set using a map object mapReq map request object callback function that will handle errors and array of features | function getFeatureInfo(mapReq, callback){
var getFeatureInfoError = validateMapQuery(mapReq);
if(!getFeatureInfoError){
createMap(mapReq, function(createMapError, map){
if(createMapError){
callback(createMapError);
}
else{
map.queryMapPoint(mapReq.i, mapReq.j, {}, function(err, results) {
if (err) throw err;
console.log(results)
var attributes = [];
for(var resultsIndex = 0; resultsIndex < results.length; ++resultsIndex){
if(mapReq.query_layers.indexOf(results[resultsIndex].layer) != -1){
var features = results[resultsIndex].featureset; // assuming you're just grabbing the first object in the array
var feature;
while ((feature = features.next())) {// grab all of the attributes and push to a temporary array
attributes.push(feature.attributes());
}
}
}
callback(null, attributes);
});
}
});
} else{
callback(getFeatureInfoError)
}
} | [
"_constructGeoJsonResponse(features) {\n var featureSet = features.map(this._constructGeoJson);\n\n var response = {\n type: 'FeatureCollection',\n features: featureSet\n };\n\n return response;\n }",
"function FeatureSet() {\n this.features = [];\n this.map = {};\n}",
"function createF... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper to determine the 'relevant' controls for a set of field group names | function getControlsByFieldGroupId(vFieldGroups) {
return oVerticalLayout.getControlsByFieldGroupId(vFieldGroups).filter(function(ctrl) {
return /^input\d+(-\d\d)*$/.test(ctrl.getId());
});
} | [
"function _addFieldGroups() {\n var dialog = $('#perc-edit-section-dialog');\n var fieldGroups = [\n { groupName : \"perc-section-general-container\", groupLabel : \"Section\"},\n { groupName : \"perc-section-users-container\", groupLabel : \"Users... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retrieves access token from page hash for use after user is redirected after logging in | function getAccessToken(){
var url = window.location.hash; // get full page url
var access_token = url.substring(url.indexOf("#")+14, url.indexOf("&")); // get access token from hash
console.log("access_token: " + access_token);
return(access_token);
} | [
"function getAccessTokenFromUrl() {\n return utils.parseQueryString(window.location.hash).access_token;\n }",
"function getAccessTokenFromUrl() {\n return utils.parseQueryString(window.location.hash).access_token;\n}",
"findYNABToken() {\n let token = null\n const search = window.location.ha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set REDIS hash key(s) | async setHash(key, data) {
// this.log(`Caching hash ${key}`);
const fields = Object.keys(data);
if (fields.length > 1)
await this.client.hmset(key, ...fields.map((field) => [field, data[field]]).flat());
else
await this.client.hset(key, fields[0], data[fields[0]]);
} | [
"set (key, value) {\n let hashed = hash(key);\n this.buckets[hash % this.buckets.length].push({key : value});\n }",
"setKey(hash) {\n this[hashSym].set(hash);\n return this;\n }",
"function setRedisKey(key, value){\n client.set(key, value, function(err, response){\n if (err) console.log(err, e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads all of the selected patient's drawings to the cloud database | function sync(id) {
var uploaded = "No";
myDB.transaction(function(transaction) {
transaction.executeSql("SELECT * FROM drawings_local where pid=? AND uploaded=?", [id,uploaded], function(tx, results) {
if (results.rows.length == 0) {
navigator.notification.alert("Already synced");
} else {
var success = 1, i;
uploaded = "Yes";
for (i = 0; i < results.rows.length; i++) {
var dataString = "drawing=" + results.rows.item(i).drawing + "&score=" + results.rows.item(i).score + "&pid=" + results.rows.item(i).pid + "&uploaded=" + uploaded + "&insert=";
$.ajax({
type: "POST",
url: "https://aesthetics-tool.000webhostapp.com/upload_drawing.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
myDB.transaction(function(transaction) {
transaction.executeSql("UPDATE drawings_local SET uploaded=? WHERE pid=?", [uploaded,id], function(tx, result) {
},
function(error){success = 0;});
});
} else if (data == "error") {
success = 0;
}
}
});
}
if (success == 1) {
navigator.notification.alert("Sync complete");
} else {
navigator.notification.alert("Something went wrong");
}
}
},
function(error){ navigator.notification.alert('Something went Wrong');});
});
} | [
"function saveDrawing()\n{\n var ref = database.ref('drawings');\n var data = {\n \n drawing:drawing\n\n }\n ref.push(data);\n\n}",
"function loadDrawings() {\n while(i < 49) {\n drawing = \"drawings/\" + i + \".jpg\";\n drawingM = \"drawings/Mobile/\" + i + \".jpg\";\n i++;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes callback once every interval specified. Defaults to 1000ms. Will stop when executed for repeatCount times. Normally this will return an interval id integer, but if specified this may return a Timer object too. | function interval(callback, interval, repeatCount) {
if (typeof interval === "undefined") { interval = 1000; }
if (typeof repeatCount === "undefined") { repeatCount = 1; }
if (repeatCount === 0) {
return Runtime.getTimer().setInterval(callback, interval);
}
var ivl = Runtime.getTimer().setInterval(function () {
repeatCount--;
if (repeatCount < 0) {
Runtime.getTimer().clearInterval(ivl);
} else {
callback();
}
}, interval);
return ivl;
} | [
"setInterval(script, interval) {\n const timerId = this.getId();\n\n this.create(timerId, 0, interval, script);\n\n return () => sp.DeleteTimer(timerId);\n }",
"function setInterval(callBack, delay) {\n let a = {\n clear: function () {\n clearTimeout(a.timer)\n }\n };\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a function to remove all null values from an array. | function removeNull(arr) {
return arr.filter(Boolean);
} | [
"function removeNull(array) {\n\t\t\t\treturn array.filter(x => x !== null)\n\t\t\t}",
"function filterNulls(arr){\n return arr.filter( x => x == null)\n}",
"function clean(arr) {\n return arr.filter(value => value !== null && value !== undefined);\n}",
"removeNullVals(A){\n return A.filter(elem =>... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove the dead connections from the given connection list. | function cleanList(list) {
var prev;
var conn = list.first;
while (conn !== null) {
var next = conn.nextReceiver;
if (!conn.callback) {
conn.nextReceiver = null;
}
else if (!prev) {
list.first = conn;
prev = conn;
}
else {
prev.nextReceiver = conn;
prev = conn;
}
conn = next;
}
if (!prev) {
list.first = null;
list.last = null;
}
else {
prev.nextReceiver = null;
list.last = prev;
}
} | [
"function cleanupConnections(connections) {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }",
"function cleanupConnections(connections) {\n algorithm_1.ArrayExt.removeAllWhere(connections, isDeadConnection);\n }",
"function cleanupConnections(connections) {\r\n algor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
link a specific node in a certain direction | _linkTo(node, direction) {
if (direction <= 0) {
node.inputEdges.push(this);
}
if (direction >= 0) {
node.outputEdges.push(this);
}
node.edges.push(this);
return true;
} | [
"function makeLinkBetweenNode(node) {\n let temp = {};\n for (let i = 0; i < node.properties.pointsAdj.length; i++) {\n temp[node.properties.pointsAdj[i].name] = node.properties.pointsAdj[i].distance;\n }\n adjNodeArray[node.properties.name] = temp;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
UnloadContent will be called once per game and is the place to unload all content. | unloadContent() {
// TODO: Unload any non ContentManager content here
} | [
"unloadContent() {\n // TODO: Unload any non ContentManager content here\n }",
"unloadContent() {\n if (this.content && this.content.destroy) {\n this.content.destroy();\n }\n this.content = null;\n this.contentState = TILE_CONTENT_STATE.UNLOADED;\n return true;\n }",
"unl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load the image inside a div with the maximum dimensions received as props so that the image assumes the div size and not its natural dimensions | nonResizedImage() {
return (
<div style={{ width: this.props.maxWidth, height: this.props.maxHeight }}>
<Image src={this.props.src} onLoad={this.handleImageLoaded} />
</div>
);
} | [
"function Image(props) {\r\n return (\r\n <img src={props.path}\r\n alt=\"\"\r\n style={{\r\n maxWidth: \"100%\",\r\n maxHeight: \"100%\",\r\n }} />\r\n );\r\n}",
"render(){\n return(\n <div>\n <img src={this.props.imag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a wrapped node from a compiler node. | function createWrappedNode(node, opts = {}) {
const { compilerOptions = {}, sourceFile, typeChecker } = opts;
const projectContext = new ProjectContext_1.ProjectContext(undefined, new fileSystem_1.FileSystemWrapper(new fileSystem_1.DefaultFileSystemHost()), compilerOptions, { createLanguageService: false, typeChecker });
const wrappedSourceFile = projectContext.compilerFactory.getSourceFile(getSourceFileNode(), { markInProject: true });
return projectContext.compilerFactory.getNodeFromCompilerNode(node, wrappedSourceFile);
function getSourceFileNode() {
return sourceFile == null ? getSourceFileFromNode(node) : sourceFile;
}
function getSourceFileFromNode(compilerNode) {
if (compilerNode.kind === typescript_1.SyntaxKind.SourceFile)
return compilerNode;
if (compilerNode.parent == null)
throw new errors.InvalidOperationError("Please ensure the node was created from a source file with 'setParentNodes' set to 'true'.");
let parent = compilerNode;
while (parent.parent != null)
parent = parent.parent;
if (parent.kind !== typescript_1.SyntaxKind.SourceFile)
throw new errors.NotImplementedError("For some reason the top parent was not a source file.");
return parent;
}
} | [
"function createWrappedNode(node, opts) {\n if (opts === void 0) { opts = {}; }\n var _a = opts.compilerOptions, compilerOptions = _a === void 0 ? {} : _a, sourceFile = opts.sourceFile, typeChecker = opts.typeChecker;\n var projectContext = new ProjectContext_1.ProjectContext(new fileSystem_1.FileSystemWra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return initial (first) date to be displayed in the schedule | getInitialDate() {
const currentDate = new Date();
currentDate.setDate(currentDate.getDate() - currentDate.getDay());
return currentDate;
} | [
"getEarliestDate() {\r\n // counting that dates were sorted in initialization\r\n var date = this.events[0].start_date;\r\n if (this.eras && this.eras.length > 0) {\r\n if (this.eras[0].start_date.isBefore(date)) {\r\n return this.eras[0].start_date... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
enterNamespaceName() adds a namespaceName onto the namespace stack at the current index, 'entering' into that namespace (it is now the current namespace). The namespace object returned from this method also has a pointer to its parent | function enterNamespaceName(namespaceName) {
namespaceStack.unshift( namespaceName );
return fw.namespace( fw.utils.currentNamespaceName() );
} | [
"function enterNamespace(namespace) {\n namespaceStack.unshift( namespace.getName() );\n return namespace;\n}",
"function parse_namespace(state, parent)\n{\n\t// handle \"namespace\" keyword\n\tlet where = state.get();\n\tlet token = module.get_token(state);\n\tmodule.assert(token.type == \"keyword\" && token.v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a desired bearing to a basic X image coordinate for a specific node bearing. Works only for a full 360 panorama. | function bearingToBasic(desiredBearing, nodeBearing) {
// 1. Take difference of desired bearing and node bearing in degrees.
// 2. Scale to basic coordinates.
// 3. Add 0.5 because node bearing corresponds to the center
// of the image. See
// https://mapillary.github.io/mapillary-js/classes/viewer.html
// for explanation of the basic coordinate system of an image.
var basic = (desiredBearing - nodeBearing) / 360 + 0.5;
// Wrap to a valid basic coordinate (on the [0, 1] interval).
// Needed when difference between desired bearing and node
// bearing is more than 180 degrees.
return wrap(basic, 0, 1);
} | [
"findAngle(bBox) {\n const ANGLE_CALIBRATION_MULTIPLIER = 0.75;\n \n // Find horizontal center of the object\n let centerX = parseFloat(bBox.x) + (parseFloat(bBox.w) / 2);\n // console.log(\"findAngle(): centerX=\" + centerX);\n \n // Find offset of the center of the object relative to the midd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Example For a = [8, 4, 8, 4, 20], the output should be findDistinctNumbers(a) = [8, 4, 20]. | function findDistinctNumbers(a) {
return a.filter((num, i) => i === a.indexOf(num));
} | [
"function findUniques(a){\n let result = []\n for (num of a){\n let match = false;\n for (unum of result){\n if (num == unum){\n match = true;\n }\n }\n if (!match){\n result.push(num);\n }\n }\n return result;\n}",
"fu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
25to44 2orMore 45to64 65Plus Asian Black Hawaiian Hispanic Married with Children Native Single Female with Children Single Male with Children Single or Cohabitating under 65 Total U25 White filter for total | function TotalFilter(feature) {
if ((feature.properties['STATEABV'] === st)&&(feature.properties['Group'] === "Total")) return true
} | [
"function filtertotal(num) {\n return num.Total > 50000;}",
"function ageU25Filter(feature) {\r\n if ((feature.properties['STATEABV'] === st)&&(feature.properties['Group'] === \"U25\")&&(feature.properties['TOTAL'] > 99)) return true\r\n}",
"TotalGHG(){\n return this.industries.map(i=>i.wwt_KPI_GHG()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
7.1.11 ToUint8Clamp ( argument ) | function ToUint8Clamp(argument) {
var number = Number(argument);
if ($isNaN(number)) return 0;
if (number <= 0) return 0;
if (number >= 255) return 255;
var f = floor(number);
if ((f + 0.5) < number) return f + 1;
if (number < (f + 0.5)) return f;
if (f % 2) return f + 1;
return f;
} | [
"function clampUint8(value) {\n return Math.max(0, Math.min(255, Math.round(value)));\n}",
"function ToUint8(v) { return v & 0xFF; }",
"function floatToUint8Clamped(floatArray){\n\tvar uint8Array = new Uint8ClampedArray(floatArray);\n\tvar rgbaArray = new Uint8ClampedArray(uint8Array.length * 4);\n\tuint8Array... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Go to the previous slide, either subslide or main slide, whichever is previous | function goToPreviousSlide() {
if (getCurrentSubSlide() != -1 && getCurrentSubSlide() > 0) {
goToSlide(getCurrentMainSlide(), getCurrentSubSlide() - 1);
return true;
}
if (getCurrentMainSlide() > 0) {
goToSlide(getCurrentMainSlide() - 1);
return true;
}
} | [
"function previousSlide() {\r\n var index = currentIndex == 0 ? (numSlides - 1) : (currentIndex - 1);\r\n gotoSlide(index);\r\n }",
"function goToPreviousSlide(){\n myPresentation.goToPreviousSlide();\n displayNumberCurrentSlide();\n selectOptionInSelector(myPresentation.getCurrent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks which page you are on, and runs the right functions | function WhatPage(){
if (window.location.href.includes("hackforums.net/member.php?action=profile&uid=")){
RunOnEveryPage();
RunOnProfile();
return;
}
if (window.location.href.includes("hackforums.net/managegroup.php?gid=")){
RunOnEveryPage();
HighlightUser();
return;
}
else{
RunOnEveryPage();
return;
}
} | [
"function checkPage() {\n console.log('CHECK PAGE RUN');\n let page = window.location.pathname.split('/')[6];\n\n switch (page) {\n case '8f003a39e5':\n getStoryContent();\n break;\n case '97cc350c5e':\n console.log('RUN SHIPPIN... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Advanced Examples It might be best to master the basics first, but this is included to tease the many possibilies LeanTween provides. | function advancedExamples(){
LeanTween.delayedCall(gameObject, 14f, function(){
for(var i:int=0; i < 10; i++){
// Instantiate Container
var rotator:GameObject = new GameObject("rotator"+i);
rotator.transform.position = new Vector3(10.2f,2.85f,0f);
// Instantiate Avatar
var dude:GameObject = GameObject.Instantiate(prefabAvatar, Vector3.zero, prefabAvatar.transform.rotation ) as GameObject;
dude.transform.parent = rotator.transform;
dude.transform.localPosition = new Vector3(0f,1.5f,2.5f*i);
// Scale, pop-in
dude.transform.localScale = new Vector3(0f,0f,0f);
LeanTween.scale(dude, new Vector3(0.65f,0.65f,0.65f), 1f).setDelay(i*0.2f).setEase(LeanTweenType.easeOutBack);
// Color like the rainbow
var period:float = LeanTween.tau/10*i;
var red:float = Mathf.Sin(period + LeanTween.tau*0f/3f) * 0.5f + 0.5f;
var green:float = Mathf.Sin(period + LeanTween.tau*1f/3f) * 0.5f + 0.5f;
var blue:float = Mathf.Sin(period + LeanTween.tau*2f/3f) * 0.5f + 0.5f;
var rainbowColor:Color = new Color(red, green, blue);
LeanTween.color(dude, rainbowColor, 0.3f).setDelay(1.2f + i*0.4f);
// Push into the wheel
LeanTween.moveZ(dude, 0f, 0.3f).setDelay(1.2f + i*0.4f).setEase(LeanTweenType.easeSpring).setOnComplete(
function( rot:GameObject ){
LeanTween.rotateAround(rot, Vector3.forward, -1080f, 12f);
}
).setOnCompleteParam( rotator );
// Jump Up and back down
LeanTween.moveLocalY(dude,4f,1.2f).setDelay(5f + i*0.2f).setLoopPingPong().setRepeat(2).setEase(LeanTweenType.easeInOutQuad);
// Alpha Out, and destroy
LeanTween.alpha(dude, 0f, 0.6f).setDelay(9.2f + i*0.4f).setDestroyOnComplete(true).setOnComplete(
function(rot:GameObject){
Destroy( rot ); // destroying parent as well
}
).setOnCompleteParam( rotator );
}
}).setOnCompleteOnStart(true).setRepeat(-1); // Have the OnComplete play in the beginning and have the whole group repeat endlessly
} | [
"_makeTween () {\n // pass callbacks context\n this._o.callbacksContext = this._o.callbacksContext || this;\n this.tween = new Tween( this._o );\n // make timeline property point to tween one is \"no timeline\" mode\n ( this._o.isTimelineLess ) && ( this.timeline = this.tween );\n }",
"function on... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an object containing various attributes for a given MIDI number. Throws error for invalid midiNumbers. | function getAttributes(midiNumber) {
var attrs = midiNumberAttributesCache[midiNumber];
if (!attrs) {
throw Error('Invalid MIDI number');
}
return attrs;
} // Returns all MIDI numbers corresponding to natural notes, e.g. C and not C# or Bb. | [
"function getAttributes(midiNumber) {\n const attrs = midiNumberAttributesCache[midiNumber];\n if (!attrs) {\n throw Error('Invalid MIDI number');\n }\n return attrs;\n}",
"midi_to_obj(_midi_data){\n\t\treturn {\n\t\t\ttype: _midi_data[0].toString(16).substr(0, 1).toLowerCase(),\n\t\t\t ch: parseInt(_midi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fonction du choix des pages et d'affichage du top recent | function pageTop(item, offset, limit){
$.ajax({
method: "POST",
url: "functions/display-top-recent.php",
data: { id: 315, offset: offset, limit: limit }
})
.done(function( html ) {
$("#top-recent").html(html);
});
} | [
"function loadRecent() {\n if (paginationOptions.pageFirst > 0) {\n paginationOptions.pageFirst = 0;\n }\n viewsOptions.page = paginationOptions.pageFirst;\n\n return retreiveArticles(viewsOptions);\n }",
"function fetchRecent() {\n addAbout() \n fetchProjects(numRecentResponse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pack meta data is the number and value of distinct symbols plus the length of the packed byte stream. | function DecodePackMeta(src) {
var nsym = src.ReadByte()
var P = new Array(nsym)
for (var i = 0; i < nsym; i++)
P[i] = src.ReadByte()
var len = src.ReadUint7()
return [P, nsym, len]
} | [
"pack(data) {\n return data;\n }",
"_packData(buf) {\n const objType = this._objType;\n if (objType.isCollection) {\n buf.writeUInt8(objType.collectionFlags);\n if (objType.collectionType === constants.TNS_OBJ_PLSQL_INDEX_TABLE) {\n this._ensureAssocKeys();\n buf.writeLengt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update a plugin via its github repo, using "data" in arguments for "release", "update" and "init" plugin's methods | updateViaGithub(plugin, ...data) {
let directory = "";
let key = -1;
// check plugin
return Promise.resolve().then(() => {
return (0, checkOrchestrator_1.default)("updateViaGithub/plugin", plugin).then(() => {
return (0, checkNonEmptyString_1.default)("updateViaGithub/github", (0, extractGithub_1.default)(plugin)).catch(() => {
return Promise.reject(new ReferenceError("Plugin \"" + plugin.name + "\" must be linked in the package to a github project to be updated"));
});
}).then(() => {
key = this.getPluginsNames().findIndex((pluginName) => {
return pluginName === plugin.name;
});
return -1 < key ? Promise.resolve() : Promise.reject(new Error("Plugin \"" + plugin.name + "\" is not registered"));
});
// check plugin directory
}).then(() => {
return (0, checkAbsoluteDirectory_1.default)("updateViaGithub/directory", this.directory).then(() => {
directory = (0, node_path_1.join)(this.directory, plugin.name);
return (0, checkAbsoluteDirectory_1.default)("updateViaGithub/plugindirectory", directory);
});
// release plugin
}).then(() => {
const pluginName = plugin.name;
return plugin.release(...data).then(() => {
this.emit("released", plugin, ...data);
return plugin.destroy();
}).then(() => {
this.emit("destroyed", pluginName, ...data);
this.plugins.splice(key, 1);
return Promise.resolve();
});
// download plugin
}).then(() => {
return (0, gitUpdate_1.default)(directory).then(() => {
return (0, createPluginByDirectory_1.default)(directory, this.externalRessourcesDirectory, this._logger, ...data);
});
// check plugin modules versions
}).then((_plugin) => {
return this.checkModules(_plugin).then(() => {
return Promise.resolve(_plugin);
});
}).then((_plugin) => {
// update dependencies & execute update script
return Promise.resolve().then(() => {
return !_plugin.dependencies ? Promise.resolve() : (0, npmUpdate_1.default)(directory);
}).then(() => {
return _plugin.update(...data);
}).then(() => {
this.emit("updated", _plugin, ...data);
return _plugin.init(...data);
// execute init script
}).then(() => {
this.emit("initialized", _plugin, ...data);
this.plugins[key] = _plugin;
return Promise.resolve(_plugin);
});
});
} | [
"function updatePluginJson() {\n // Read and parse content.\n var pkg = getPackage();\n var plugin = getPlugin();\n\n // Create assignments in plugin.json\n plugin.packageName = pkg.name;\n plugin.header.commitHash = getCommitHash();\n\n // Write the result.\n plugin = JSON.stringify(plugin, null, 2);\n fs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
and finally a delete cookie function so we can reset the cookie | function deleteCookie(){
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
} | [
"function delete_cookie(){\n CookieUtil.unset(\"cookie_count\");\n window.location.reload();\n}",
"function removeCookie(cookie) {\n}",
"function deleteCookie(cname) { // cookie name\r\n \r\n document.cookie = cname + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\"; // Así es como se borra una cooki... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert to native SVGPoint | native () {
// create new point
const point = new SVGPoint()
// update with current values
point.x = this.x
point.y = this.y
return point
} | [
"function svgPoint(element, x, y) {\n var pt = maincanvas.createSVGPoint();\n pt.x = x;\n pt.y = y;\n return pt.matrixTransform(element.getScreenCTM().inverse());\n}",
"function svgPoint(element, x, y) {\n var pt = svg.createSVGPoint();\n pt.x = x;\n pt.y = y;\n var output = pt.matrixTransform(ele... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify duration to be in minutes | function durationInMinutes(duration) {
const match = duration.match(/((\d+)\shrs?)?\s?((\d+)\smin)?/);
const durationString = `${match[2] || '0'}:${match[4] || '00'}`;
return moment.duration(durationString).asMinutes();
} | [
"toMinutes() {\n return MINUTES.convert(this.duration, this.unit);\n }",
"convertSecondsToMinutes(songDuration) {\n const minutes = Math.floor(parseInt(songDuration) / 60000);\n const seconds = ((parseInt(songDuration % 60000) / 1000).toFixed(0));\n const duration = (seconds === 60 ? (minutes +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export state of the workspace Note: useful for tagging | export_state() {
let state_metadata = { 'color': {}, 'pinned': {}, 'visibility': {}, 'camera': { 'position': {}, 'up': {} }, 'target': {} };
state_metadata['camera']['position']['x'] = this.camera.position.x;
state_metadata['camera']['position']['y'] = this.camera.position.y;
state_metadata['camera']['position']['z'] = this.camera.position.z;
state_metadata['camera']['up']['x'] = this.camera.up.x;
state_metadata['camera']['up']['y'] = this.camera.up.y;
state_metadata['camera']['up']['z'] = this.camera.up.z;
state_metadata['target']['x'] = this.controls.target.x;
state_metadata['target']['y'] = this.controls.target.y;
state_metadata['target']['z'] = this.controls.target.z;
state_metadata['pinned'] = Array.from(this.uiVars.pinnedObjects);
for (let key in this.meshDict) {
if (this.meshDict.hasOwnProperty(key)) {
state_metadata['color'][key] = this.meshDict[key].object.children[0].material.color.toArray();
state_metadata['visibility'][key] = this.meshDict[key].visibility;
}
}
return state_metadata;
} | [
"export() {\n\t\tconsole.log(JSON.stringify(this.state.notes));\n\t\tconsole.log(this.state.notes);\n\t}",
"function dumpWorkspace (state) {\n const {key, wordCharIndex, wordCipherIndex} = state.workspace;\n return {key, wordCharIndex, wordCipherIndex};\n }",
"export() {\n // const log = this.entiti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CTA Change loupe and color button search | function changeColorBtn(e) {
e.preventDefault();
let element = document.getElementById('html').attributes;
if(element[2].value === 'dark') {
// change loupe
let loupe = document.getElementById('loupe');
loupe.src = '/assets/lupa_light.svg';
// change text color button
let textBtn = document.querySelector('#btn-search');
textBtn.style.color = '#FFFFFF';
// change background button search
let color = document.querySelector('.submit');
color.style.background = '#EE3EFE';
color.style.border = '1px solid #110038';
} else {
// change luope
let loupe = document.getElementById('loupe');
loupe.src = '/assets/lupa.svg';
// change text color button
let textBtn = document.querySelector('#btn-search');
textBtn.style.color = '#110038';
// change background button search
let color = document.querySelector('.submit');
color.style.background = '#F7C9F3';
color.style.border = '1px solid #110038';
}
} | [
"function searchColour(colour)\n\t{\n document.getElementById('txtSearch').style.backgroundColor = colour;\n\t}",
"function searchModeDisplay() {\n let colorCodeInput = document.getElementById(\"search-bar\").value;\n\n firstColorBox.style.backgroundColor = colorCodeInput;\n firstColorBox.style.borderBottomLe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::Serverless::Function.DeploymentPreference` resource | function cfnFunctionDeploymentPreferencePropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnFunction_DeploymentPreferencePropertyValidator(properties).assertSuccess();
return {
Enabled: cdk.booleanToCloudFormation(properties.enabled),
Type: cdk.stringToCloudFormation(properties.type),
Alarms: cdk.listMapper(cdk.stringToCloudFormation)(properties.alarms),
Hooks: cdk.listMapper(cdk.stringToCloudFormation)(properties.hooks),
};
} | [
"function cfnFunctionDeploymentPreferencePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_DeploymentPreferencePropertyValidator(properties).assertSuccess();\n return {\n Alarms: cdk.listMapper(cdk.stringToCloudFormation)(pro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
run: calls itself every time the browser is ready for rendering a frame draws the Scene | function run() {
/**
tell the browser to call the function 'run' whenever it is ready to re-render the 'canvas'
this assures that the demo runs at a good framerate
and is only called when the browser-tap of the demo is in focus
*/
requestAnimationFrame( run, canvas );
/**
render the scene
*/
Scene.draw( gl );
} | [
"function renderScene() {\n if (m_initialized === false) {\n initScene();\n }\n m_viewer.render();\n }",
"draw() {\n this.renderScene();\n }",
"function renderLoop() {\r\n requestAnimFrame(renderLoop);\r\n drawScene();\r\n}",
"function render() {\n if (running) {\n w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CONCATENATED MODULE: ./src/components/Login/LoginSuccess.jsx / Copyright 2019 Gravitational, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | function LoginSuccess() {
return /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null, /*#__PURE__*/react_default.a.createElement(components_LogoHero, null), /*#__PURE__*/react_default.a.createElement(design_src["j" /* CardSuccessLogin */], null));
} | [
"function Logout() {\r\n return (\r\n <div>\r\n This is the Logout component\r\n </div>\r\n )\r\n}",
"function AuthFailedPage () {\n return <div>Sorry! It looks like there was a problem trying to log in.</div>\n}",
"welcome() {\r\n if (this.props.user && this.props.user.displayName) {\r\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
edit restaurant. only one update needed due to reference data. | function editRestaurant(req ,res) {
let _id = req.params.id;
let rest = req.body;
db.Restaurant.findOne({_id}, function(err, restaurant){
restaurant = rest;
restaurant.save();
res.json(restaurant);
});
} | [
"function editRestaurant(req, res, next) {\n var id = req.session.user.id;\n var restaurant = req.restaurant;\n DBController.editRestaurantById(id, restaurant, function(err, result) {\n if (err) throw err;\n next();\n });\n}",
"async edit ({ view, params, auth }) {\n /**\n * Find ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
findInArray() returns an array of strings ("matches") that do not have the inputed prefix | function findInArray(prefix, array) {
const matches = [];
for (let string of array) {
if (!string.startsWith(prefix)) matches.push(string);
}
returnMatches(matches);
} | [
"function findNoPrefix( prefix, haystack ) {\n var len = haystack.length,\n no_prefix = [];\n \n for( let n=0; n < len; n++ )\n if( !hasPrefix( prefix, haystack[n] ) ) no_prefix.push( haystack[n] );\n \n return no_prefix;\n}",
"startsWithInArray(prefix, array) {\n return array.find((element) => el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |