query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Given a collapsed selection, move the focus `maxDistance` forward within the selected block. If the selection will go beyond the end of the block, move focus to the start of the next block, but no further. This function is not Unicodeaware, so surrogate pairs will be treated as having length 2.
function moveSelectionForward( editorState: EditorState, maxDistance: number, ): SelectionState { const selection = editorState.getSelection(); // Should eventually make this an invariant warning( selection.isCollapsed(), 'moveSelectionForward should only be called with a collapsed SelectionState', ...
[ "function moveCaret(win, charCount) {\n var sel, range;\n if (win.getSelection) {\n sel = win.getSelection();\n if (sel.rangeCount > 0) {\n var textNode = sel.focusNode;\n var newOffset = sel.focusOffset + charCount;\n sel.collapse(textNode, Math.min(textNode.len...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function will Send A get request that contais file id to get the sheets and call the displayOptions above
async function getFileSheets() { const fileId = selectFileSelectBox.value; worksheetSelect.innerHTML = defaultOptionSelect; if (fileId == 'none') { displayErrorMessage("Please select a file"); return false; } /* Send A request to get the sheets */ const res = await fetch(`/getsheets/${fileId}`); cons...
[ "async getIdsForSheet(id) { //x\n try {\n let result = await get(\"QuestionSheet/GetQuestionIdsForSheet\", id);\n return result;\n }\n catch (err) {\n this.handleError(err);\n }\n }", "function getBonusSheet(auth) {\n return new Promise((resolve, re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParsertable_partitioning_clauses.
visitTable_partitioning_clauses(ctx) { return this.visitChildren(ctx); }
[ "visitIndex_partitioning_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitQuery_partition_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitPartition_by_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitPartitioning_storage_clause(ctx) {\n\t return this.visitChildre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to get a diff between old fetched repos and new repos
function getDiffFromExistingRepos(newRepos) { if (typeof newRepos === 'object' && typeof cachedResults === 'object') { // get an array of old repos name var existingReposName = cachedResults.concat(droppedResults).map(function (item) { if (typeof item != 'undefined') { return item.name; } }); return...
[ "getV3ProjectsIdRepositoryCommitsShaDiff(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
accepts an append request, returns a Promise to append it, enriching it with auth
function appendPromise(requestWithoutAuth) { return new Promise((resolve, reject) => { return getAuthorizedClient().then((client) => { const sheets = google.sheets('v4'); const request = requestWithoutAuth; request.auth = client; return sheets.spreadsheets.values.append(request, (err, resp...
[ "function attachToken(request) {\r\n var token = getToken();\r\n if (token) {\r\n request.headers = request.headers || {};\r\n request.headers['x-access-token'] = token;\r\n }\r\n return request;\r\n }", "function post_authorization_request(authorization_request) {\n return new Promise((...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Forms a localized relative date string from a given Date object. For example, '1 day'. Options: referenceDate: The date to compare to. Defaults to Date.now(). minUnit: The minimum unit that can be displayed in the string. Units are referenced using abbreviations of the following convention: 's': seconds 'm': minutes 'h...
function relativeDateString(date, opts) { opts = opts || {}; opts.minUnit = opts.minUnit || 's'; opts.referenceDate = opts.referenceDate || Date.now(); // TODO: Mark negative diffs so they can be handled differently // in the future (ie. adding an 'ago' vs 'from now' suffix) ...
[ "relDateText(dateStr, now) {\n if (now == null) {\n now = new Date();\n }\n const date = new Date(dateStr);\n const period = Dates.getDateDeltaString(date, now);\n const relDateKey =\n date > now ? 'notification_is_due' : 'notification_was_due';\n return this._format(relDateKey, { period...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mutable registry of service implementations, bound to a service definitions.
function ServiceRegistry() { var services = new HashMap(); var listeners = []; /** * Retrieve a service for a specific definition. * * @param {ServiceDefinition} definition - The service definition. * @returns {Service|null} The service, if one exists, otherwise undefined. */ ...
[ "function getAllDefinitions(m, def_id) {\n if (def_id != null) {\n for (var j=0; j<def_id.length; j++)\n m[def_id[j]] = definitions[def_id[j]]\n }\n}", "getServices() {\n let services = []\n this.informationService = new Service.AccessoryInformation();\n this.informationService\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads file input library
function loadFileInputLibrary(pO) { var fM = new ModuleObj("FileInput"); // Set current module object to this module. This is necessary for // creating expressions. As a result the expressions in this library // get seq numbers starting from 1. See description at ModuleObj. // // VERIF...
[ "importLibrary(file) {\n const controller = this;\n this.persistenceController.loadLibraryFromFile(file, function (lib) {\n if (lib != null) {\n if (controller.addLibrary(lib) == null) {\n InfoDialog.showDialog('Can\\'t import this library: a library with t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(6) Write a function to create a new string from a given string changing the position of first and last characters. The string length must be greater than or equal to 1.
function switch_first_last(str){ const first = str.substr(0, 1); const last = str.substr((str.length - 1), 1); const middle = str.slice(1, str.length - 1); return last + middle + first; }
[ "function front22(str) {\n if (str.length >= 2) {\n var first2 = str.slice(0, 2);\n return first2 + str + first2;\n }\n else {\n return str;\n }\n}", "function backAround(str) {\n var last = str.charAt(str.length - 1);\n return last + str + last;\n\n}", "function modifyLas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parseLatLng :: (Map, L.LatLng) > BasePosition
function parseLatLng(self, latLng) { return _private(self).positionParser.parse(latLng); }
[ "function gpsToLatLng(text) {\n var text = text.replace(/\\s+$/,'').replace(/^\\s+/,'');\n\n // simplest format is decimal numbers and minus signs and that's about it\n // one of them must be negative, which means it's the longitude here in North America\n if (text.match(/^[\\d\\.\\-\\,\\s]+$/)) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the percent an expense is of the income and update smile
function smiles(expense, income, smile) { // calculate spending percentage var percent = (parseFloat(expense))/ (parseFloat(income)) * 100; var rangesRent = "<br>Good: Less than 25% of income<br>Okay: 25-35% of income<br>Bad: More than 35% of income"; var rangesSaved = "<br>Good: More than 20% of income...
[ "function profit(info) {\n //return console.log((info.inventory * info.sellPrice)-(info.inventory * info.costPrice)); // 54000 gewinn - 39204\n // shorter:\n return console.log(Math.round(info.inventory * (info.sellPrice-info.costPrice))); // needs to be rounded in this case\n}", "function caloriesBurned() {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParsercomposite_range_partitions.
visitComposite_range_partitions(ctx) { return this.visitChildren(ctx); }
[ "visitSubpartition_by_range(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitRange_partition_desc(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitOn_range_partitioned_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitRange_subpartition_desc(ctx) {\n\t return this.visitChildren(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort pages by status code
function sortPages() { pages.sort(function(a, b) { if (a.code == 'error') return -1; if (b.code == 'error') return 1; return b.code - a.code; }); }
[ "function sortByButtonOrder (pageObjs)\n{\n\tvar sortedList = new Array ();\n\tfor (var n = 0; n < pageObjs.pageList.length; n++)\n\t{\n\t\tvar pos = parseInt (pageObjs.pageObjArray[pageObjs.pageList[n]][gBUTTON_ORDER]);\n\t\tif (pos >= 0)\n\t\t\tsortedList [pos] = pageObjs.pageList[n];\n\t}\n\t// get rid of [0] si...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to alert errors in a nonblocking way. Message is an array, each element (created with document.createTextNode) being one line. Position is an array consisting of two elements, a "paddingleft" value and a "paddingtop" value.
function errorAlert(message, positionArray, errorAlertCallback) { // Try executing the non-blocking way. If nothing else works, fall back to window.alert. try { // Function for appending the message to the container. function appendText(textArray, elm) { for (i = 0, l = textArray.length; i < l; i += ...
[ "_calculateErrorMsgTooltipPosition(inputElement, errorMsgHolder) {\n const bodyRect = document.body.getBoundingClientRect(),\n elemRect = inputElement.getBoundingClientRect(),\n offsetTop = elemRect.top - bodyRect.top;\n\n errorMsgHolder.style.top = offsetTop + elemRect.height + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map this effect through a position mapping. Will return / `undefined` when that ends up deleting the effect.
map(mapping) { let mapped = this.type.map(this.value, mapping); return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped); }
[ "static mapEffects(effects, mapping) {\n if (!effects.length)\n return effects;\n let result = [];\n for (let effect of effects) {\n let mapped = effect.map(mapping);\n if (mapped)\n result.push(mapped);\n }\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A placeholder can contain have lines of text.
function PlaceholderLine(props) { var className = props.className, length = props.length; var classes = (0, _classnames.default)('line', length, className); var rest = (0, _lib.getUnhandledProps)(PlaceholderLine, props); var ElementType = (0, _lib.getElementType)(PlaceholderLine, props); return _react.d...
[ "static addBlankLine(excerptTokens) {\n let newlines = '\\n\\n';\n // If the existing text already ended with a newline, then only append one newline\n if (excerptTokens.length > 0) {\n const previousText = excerptTokens[excerptTokens.length - 1].text;\n if (/\\n$/.test(pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes whitespace at beginning and end of block so: x > x
function trim(rootBlockNode) { if (rootBlockNode) { node = rootBlockNode.firstChild; if (node && node.type == 3) { node.value = node.value.replace(startWhiteSpaceRegExp, ''); } node = rootBlockNode.lastChild; if (node && node.type == 3) { node.value = node.value.replace...
[ "function splitMultilineDiffBlock ({added, removed, value}) {\n let lines = value.split('\\n')\n let blocks = []\n// lines = lines.filter(line=>line.length>0)\n lines.forEach((line, index) => {\n blocks.push({added, removed, value: line})\n if (index < lines.length - 1) blocks.push({value: '\\n'})\n })\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An object that creates an overlay with basic error popup
constructor(error_message, overlay=page_overlay, closeable=true) { this.overlay = overlay this.popup = new Popup("Error", "error-popup", closeable) let error_screen_obj = this; error_screen_obj.popup.bottom_buttons[0] = new PopupButton("Dismiss", "error-close-button", 0, function() { error_screen_...
[ "function createNewErrorOverlay(data) {\n const HmrErrorOverlay = customElements.get('hmr-error-overlay');\n if (HmrErrorOverlay) {\n const overlay = new HmrErrorOverlay(data);\n clearErrorOverlay();\n document.body.appendChild(overlay);\n }\n}", "function showErrorMessage(error){\n var errorDiv=$(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the FocusTrap from the stack, and activates the FocusTrap that is the new top of the stack.
deregister(focusTrap) { focusTrap._disable(); const stack = this._focusTrapStack; const i = stack.indexOf(focusTrap); if (i !== -1) { stack.splice(i, 1); if (stack.length) { stack[stack.length - 1]._enable(); } } }
[ "async function exitFocus() {\n xapi.Command.UserInterface.Extensions.Panel.Update({ PanelId: 'focus_on_me', Visibility: 'Auto' })\n xapi.Command.UserInterface.Message.Alert.Display({ Title: 'System Lost Focus', Text: 'Access to Webex Assistant and Ultrasound Pairing disabled', Duration: 5 })\n await GMM.write('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Crea un body a partir de una lista de objetos, ubicando los datos en la columna correspondiente
function CrearBody(listaObjetos, listaColumnas) { var tabla = $("#tabla"); var tBody = $("<tbody></tbody>"); tBody.prop('id', 'tbody'); listaObjetos.forEach(function (persona) { var fila = $("<tr></tr>"); //Uso map para tomar el valor var columnasTbody...
[ "function CrearBody(listaObjetos, listaColumnas) {\n var tabla = $(\"#tabla\");\n var tBody = $(\"<tbody></tbody>\");\n tBody.prop('id', 'tbody');\n listaObjetos.forEach(function (vehiculo) {\n var fila = $(\"<tr></tr>\");\n //Uso map para tomar el valor\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a selection that does not partially select any atomic ranges.
function skipAtomicInSelection(doc, sel, bias, mayClear) { var out; for (var i = 0; i < sel.ranges.length; i++) { var range = sel.ranges[i]; var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); var newHead = skipAtomic(doc, range.head, bias, mayClear); if (out || newAnchor != r...
[ "createRangeBySelectedCells() {\n const sq = this.wwe.getEditor();\n const range = sq.getSelection().cloneRange();\n const selectedCells = this.getSelectedCells();\n const [firstSelectedCell] = selectedCells;\n const lastSelectedCell = selectedCells[selectedCells.length - 1];\n\n if (selectedCells...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scroll horizontal rueda mouse solo en div class containerhorizontal
function scrollHorizontal() { $('.container-horizontal').on('mousewheel', function (event, delta) { this.scrollLeft -= delta * 30; event.preventDefault(); }); }
[ "scrollLeft() {\n let x = this.scrollElement.scrollLeft - this.scrollElement.clientWidth;\n let y = this.scrollElement.scrollTop;\n this._scrollTo(x, y);\n }", "function setScrollers(container) { \n\t\tvar header = $('>div.tabs-header', container); \n\t\tvar tabsWidth = 0; \n\t\t$('ul.tabs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize population before starting the optimization process Binary encoding is used to represent solutions
initializePopulation() { for (let i = 0; i < this.solutionsCount; i++) { // solution this.population.push(this.getRandomSolution()) // fitness value this.fitness_values.push(NaN); } }
[ "function createInitialPopulation() {\n //inits the array\n genomes = [];\n //for a given population size\n for (var i = 0; i < populationSize; i++) {\n //randomly initialize the 7 values that make up a genome\n //these are all weight values that are updated t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the given HTML into the specified row. Returns true it the HTML is empty, otherwise returns false.
writeImagesHtml(domRow, html) { let isEmpty = false; // remove empty rows... if (html === '') { domRow.parentElement.removeChild(domRow); isEmpty = true; } // add the html for the images domRow.innerHTML = html; return isEmpty; }
[ "function verifyRow(row, isEditable, classes, placeholders) {\n ok( row.attr(\"rowId\").trim().length > 0, \"row should have a 'rowId' attribute\" );\n\n equal( row.children(\"td\").size(), 4, \"Row should have 4 cells\" );\n\n if(isEditable == true) {\n ok(row.hasClass(\"cs-writeable-editmode\"), \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Chapter 101 RopeGroup Load unknown remaining twin
function C101_KinbakuClub_RopeGroup_LoadRemainingTwin() { if (C101_KinbakuClub_RopeGroup_LeftTwinStatus != "StartTied") { C101_KinbakuClub_RopeGroup_CurrentStage = 450; C101_KinbakuClub_RopeGroup_LoadRightTwin(); } else C101_KinbakuClub_RopeGroup_LoadLeftTwin(); }
[ "function C101_KinbakuClub_RopeGroup_Load() {\n\n\t// Load correct stage\n\t// After intro player has a choice each time she goes to the group, until a twin is released\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage > 100 && C101_KinbakuClub_RopeGroup_CurrentStage < 700) {\n\t\tC101_KinbakuClub_RopeGroup_CurrentSta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns textarea's selection start.
get selectionStart() { return this.$.textarea.selectionStart; }
[ "function _getRange() {\n\t\t// sel: a selection object representing the range of text selected by the user\n\t\tvar sel = win.getSelection();\n\t\t// Return a range object representing the current selection or false\n\t\treturn (sel.rangeCount) ? sel.getRangeAt(0) : false;\n\t}", "get selectionEnd() {\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=========================================== Checker Object =========================================== each checker has one validateObj and can link to another checker
function CheckerObj(validateObj, linkChecker) { this.validateObj = validateObj; this.linkChecker = linkChecker; // this.ctrlList = ctrlList; this.IsPass = function(ctrlObj, isQuite) { var res = true; if (this.linkChecker != null) { res = this.linkChecker.IsPass(ctrlObj, isQuite); } i...
[ "function validator(){\n var o = {\n stringValidator: isUpperCase(\"asdasf\"),\n passwordValidator: isDigit(\"asda564sd\"),\n colorValidator: isHexadecimal(\"asd444\"),\n yearValidator: doesBelong(2020)\n }\n\n return o;\n}", "function MarketValidator(filePath) {\n\n this.filePath = filePa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hides the popup for a given step
function hidePopup(step) { if (step.tether) { step.tether.disable(); } step.popup[0].style.setProperty('display', 'none', 'important'); }
[ "function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }", "function hidePopup () {\r\n editor.popups.hide('customPlugin.popup');\r\n }", "hide() {\n\t\tthis.element.style.visibility = 'hidden';\n\t}", "hide() {\n this.StartOverPopoverBlock.remove(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
trigger max value on change
function setMaxValue(myCurrentMaxValue) { $("input[name='maxvalue']").val(myCurrentMaxValue) .trigger('change'); }
[ "maxHandleChange(event, index, maxPrice) {\n this.setState({ maxPrice });\n }", "function setDataInputMax(x)\n{\n\tdataInputMax = x;\n}", "verifyValueMax() {\n this.discount.value = discountHandler.getFixedValue(this.discount.value, this.discount.type);\n }", "function setDataMax(x)\n{\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to check the comment length and if enter is hit, then submit the comment.
function checkCommentLength(textareaObj) { let key = event.keyCode || event.which; //check the number of character in textbox if (textareaObj.value.length > 0) { $(textareaObj).siblings('.comment-submit').removeAttr('disabled'); /*I'm not sure if I should add the 'hit enter' feature. Comment...
[ "function submitToBot(event) {\r\n\tif(event && event.keyCode != 13){\r\n\t\treturn false;\r\n\t}\r\n\tvar v = textInput.value.trim();\r\n\tif(v.length > 0) {\r\n\t\tnewInput(v);\r\n\t}\r\n}", "function submitOnEnter(event){\n\tif (event.keyCode == 13 && !event.shiftKey) {\n\t\tevent.preventDefault();\n\t\tnewMes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decide on scope of name, given flags. The namespace dictionaries may be modified to record information about the new name. For example, a new global will add an entry to global. A name that was global can be changed to local.
function analyze_name(ste, scopes, name, flags, bound, local, free, global){ if(flags & DEF_GLOBAL){ if(flags & DEF_NONLOCAL){ var exc = PyErr_Format(_b_.SyntaxError, "name '%s' is nonlocal and global", name) ...
[ "function _processNameScope() {\n processedGraph.root = {id: '', children: [], stacked: false};\n const {nodeMap, root} = processedGraph;\n\n for (const id of nameScopeIds) {\n const nameScope = _createNameScope(id);\n nodeMap[id] = nameScope;\n const parent = nameScope.parent ? nodeMap[nameScope.parent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given object is an instance of CustomResource. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.
static isInstance(obj) { return utils.isInstance(obj, "__pulumiComponentResource"); }
[ "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VirtualMachineResource.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will be called when a role's condition is removed. It will return only those
function processRoleConditionRemoval(oldRole) { return relationshipHelper.getConditionalAndDirectGrants(oldRole, 'members', 'role').directGrants; }
[ "function removeCondition(conditionEditor/*:ConditionEditorBase*/)/*:void*/ {\n this.removeAppliedCondition$Mv72(conditionEditor);\n }", "function removeRole() {\r\n\r\n //defining what I want to pull from the role table\r\n var role = 'SELECT * FROM role';\r\n connection.query(role, function (err, r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes two sorted arrays of arrays and returns their intersection
function intersectSortedArrays(a, b) { var isect = []; var i = 0, j = 0, ii = a.length, jj = b.length; while (i < ii && j < jj) { var c = compareArrays(a[i], b[j]); if (c == 0) isect.push(a[i]); if (c <= 0) i++; if (c >= 0) j++; } r...
[ "function intersection(nums1, nums2){\n\tlet obj = {};\n\tlet arr1, arr2\n\n\tif( nums1.length < nums2.length ){\n\t\tarr1 = nums1\n\t\tarr2 = nums2\n\t} else {\n\t\tarr1 = nums2 \n\t\tarr2 = nums1\n\t};\n\n\tlet result = []\n\tlet count = arr1.length;\n\n\tfor ( let i = 0 ; i < arr1.length ; i ++ ){\n\t\tobj[arr1[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========================================================================// generiranje objektov dklima|dpadavine|dsonce ========================================================================// generiranje objektov klima, padavine, sonce
function generateKlimaPadavineSonce(objname) { try { eval("var dbobjs = query(createSelectStatement" + objname + "(" + this.postaja + "," + this.tip + ",'" + this.datumz + "','" + this.datumk + "'))"); if (parseInt(dbobjs.size()) > 0) { var iter = dbobjs.iterator(); while (iter.hasNext()) { ...
[ "function KlimaPadavineSonce(parent, postaja, tip, idmm, datum, ime_vnasalca, ime_opazovalca) {\n this.getClass = function() { return \"KlimaPadavineSonce\" };\n this.parent = parent; \n this.name = \"d\" + this.parent.name; \t\t\t\t\t\t\t\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets up visual feedback in response to user interacting with the tree items (i.e., mousehovering an item, etc).
function hookItemsVisualFeedback() { var current = arguments.callee; var dynCss = CSSProvider.dynamicCSS; // @visual effect for mouse over on tree items. var hoverCb = function(event) { var el = event.body.htmlElement; if (current.lastClicked && current.lastClicked === el) { ...
[ "function treeCallback (data) {\n\tconsole.log('>Motion at Tree');\n\tconsole.log(' event: ', data);\n\n\t//I wanted this to happen regardless so I commented out the motionActive \n\t//if (motionActive) {\n\t\tdoit('tree');\n\n\t\tif (toggleProp) {\n\t\t\tsetTimeout(doit,10000,'lamp');\n\t\t} else {\n\t\t\tsetTime...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
close all native mongos connections
_closeMongos(){ this._mongoAliases.forEach(alias => { delete this[alias] }) this._mongoDbNames.forEach((refName)=>{ if (this[refName] == null) return this._closePromises.push(this[refName].close().then(()=>{ self._logger.info(`Mongo/${refName} connection closed`) ...
[ "async closeDatabase() {\n await mongoose.connection.close();\n await mongoDb.stop();\n }", "function closeAllConnections() {\n var i;\n for (i = 0; i < _connections.length; i++) {\n try {\n _connections[i].disconnect();\n } catch (err) { console.error(err...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populates topAdjMatrix with the data from topEdges
function populateTopAdjMatrix(edges) { for(var i = 0; i < edges.length; i++){ var from = edges[i].from, to = edges[i].to; topAdjMatrix[from][to] = edges[i].id; } }
[ "function assignDataSets(nodes, edges){\n topNodes = new vis.DataSet(nodes);\n topEdges = new vis.DataSet(edges);\n algTopEdges = new vis.DataSet(edges);\n\n topData = {nodes: topNodes, edges: topEdges};\n algTopData = {nodes: topNodes, edges: algTopEdges};\n\n resEdges = new vis.DataSet([]);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hide or show backToTop image, based on the offset
function hideOrShowBackToTopIcon(obj, offset){ if (jQuery(obj).scrollTop() > offset) { jQuery('div.backToTop').show(); } else { jQuery('div.backToTop').hide(); } }
[ "function arrowToTopFun() {\n\tif(supportAndMaintance[0].getClientRects()[0].top < 0){\n\t\tarrowToTop[0].style.opacity = '0.5';\n\t}else{\n\t\tarrowToTop[0].style.opacity = '0';\n\t}\n}", "goToTopView() {\n this._camera.position.set(0, 1.5, 0);\n }", "function animationBtnBackTop() {\n var $ba...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a new type of annotation.
static define() { return new AnnotationType() }
[ "function newAnnotation(type) {\n \n updateAutori();\n //ricavo il testo selezionato\n selezione = selection();\n \n //differenza tra selezione e fragmentselection: per operare sui nodi serve il primo, poichè è sostanzialmente\n //un riferimento all'interno del documento; il secondo invece estr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a method that will return a boolean depending on whether or not the singly linked list is empty or not.
isEmpty() { // An empty list in its most simplified form is a list // with a head that is null. // So what this does, it it grabs the boolean for head == null, and returns that. return this.head == null; // Alternative: if (this.head==null) { return true; ...
[ "function isEmpty () {\n return _navigationStack.length === 0;\n }", "isEmpty() {\n return (this.queue.length == 0);\n }", "isEmpty() {\n return ((this.front === -1) && (this.rear === -1));\n }", "isEmpty() {\n return queue.length === 0;\n }", "isEmpty() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is called on a loop, only really activates if shift is pressed. Purpose is to update leaderboard with team scores Need to add actual users to leaderboard might not have time
function checkLeaderboard() { //Would've used tab, but would change focus to other objs. var leaderboard = document.getElementById("leaderboardWindow"); if (keyStates.shift.pressed && leaderboard.style.display == "none") { // Checks to see if shift is pressed and the window is not already opened socket.emit('ge...
[ "function addScore() {\n var input = nameInput.value;\n\n var user = {name: input, score: timer};\n // add new score to array\n leaderboardArr.push({name: input, score: timer});\n\n // updates array in local storage\n localStorage.setItem(\"leaderboard\", JSON.stringify(leaderboardArr));\n\n hi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Based on the parentName, this creates a fully classified name of a property
function getPropertyName(parentName, parent, indexer) { var propertyName = parentName || ""; if (parent instanceof Array) { if (parentName) { propertyName += "[" + indexer + "]"; } } else { if (parentName) { propertyName += "."; } propertyName += indexer; } return propertyNa...
[ "function createCustomTypeName(type, parent) {\n var parentType = parent ? parent.key : null;\n var words = type.split(/\\W|_|\\-/);\n if (parentType) words.unshift(parentType);\n words = words.map(function (word) {\n return word[0].toUpperCase() + word.slice(1);\n });\n return words.join('') + 'Type';\n}"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
More correct typeof string handling array which normally returns typeof 'object'
function typeStr (obj) { return isArray(obj) ? 'array' : typeof obj; }
[ "function dataTypeSeer(array) {\n\tfor (var i = 0; i < array.length; i++) {\n\t\tconsole.log(typeof array[i]);\n\t};\n}", "function arrayOrObject(value) {\n if(Array.isArray(value)) return \"array\";\n return \"object\";\n}", "function checkType(str) {\n var obj = {\n datatype: typeof str,\n le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset the state of the change objects to show no changes. This means set previousKey to currentKey, and clear all of the queues (additions, moves, removals). Set the previousIndexes of moved and added items to their currentIndexes Reset the list of additions, moves and removals
_reset() { if (this.isDirty) { let record; for (record = this._previousItHead = this._itHead; record !== null; record = record._next) { record._nextPrevious = record._next; } for (record = this._additionsHead; record !== null; record = record._next...
[ "resetIndexes()\n {\n const self = this;\n self[_reducedIndexes] = null;\n self[_optimizedIndexes] = null;\n self[_naiveIndex] = null;\n self[_keyStatistics] = null;\n }", "reset() {\r\n\t\tthis.changeState(this.initial);\r\n\t}", "resetIndex() {\n this._offset = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: FormatNumber(srcStr, nAfterDot). Description: Format a number string with dot, and return a rounded number. Param: srcStrA number string being formated. nAfterDotA number indicates for decimal digits. Return: A worked number. ie: FormatNumber(3.562454665, 2)3.56 FormatNumber(3.565454665, 2)3.57 FormatNumber(3...
function FormatNumber(srcStr, nAfterDot){ var srcStr,nAfterDot; var resultStr,nTen; srcStr = ""+srcStr+""; strLen = srcStr.length; dotPos = srcStr.indexOf(".",0); if (dotPos == -1){ resultStr = srcStr+"."; for (i=0;i<nAfterDot;i++){ resultStr = resultStr+"0"; } }else{ if ((strLen - dotPos ...
[ "function formatDecimal4(val, n) {\n n = n || 2;\n var str = \"\" + Math.round ( parseFloat(val) * Math.pow(10, n) );\n while (str.length <= n) {\n str = \"0\" + str;\n }\n var pt = str.length - n;\n return str.slice(0,pt) + \".\" + str.slice(pt);\n}", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
register a CAF (after initialising the heap object)
function h$addCAF(o) { h$CAFs.push(o); h$CAFsReset.push([o.f, o.d1, o.d2]); }
[ "static init()\n {\n let aeFDC = Component.getElementsByClass(document, PCx86.APPCLASS, \"fdc\");\n for (let iFDC = 0; iFDC < aeFDC.length; iFDC++) {\n let eFDC = aeFDC[iFDC];\n let parmsFDC = Component.getComponentParms(eFDC);\n let fdc = new FDC(parmsFDC);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create collapsible header NOTE:: will need to add extra parameter to find if location is open; currently flagging even indeces as open locations
function createCollapsibleHeader(i, id, name, collapsibleHeader) { // console.log('name: ' + name + ', id: ' + id) var beerLink = $("<a>").attr('id', id).text(name).attr('href', 'brewery.html') beerLink.addClass("btn yellow accent-4 black-text waves-effect waves-orange brew-button") beerLink.on("click",...
[ "_collapseHeading(heading) {\n heading.expanded = false;\n }", "_expandHeading(heading) {\n heading.expanded = true;\n }", "function hsCollapseAllVisible() {\n $('#content .hsExpanded:visible').each(function() {\n hsCollapse($(this).children(':header'));\n });\n}", "function build...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The create card funciton with if and return;
function createCard() { inquirer.prompt(createprompt).then(function(response) { if(res.type === 'Cloze') { var fc = new flashcard(res.front.trim(), res.back.trim(), true); if(!fc.valudate()) { createCard(); } else { return; } ...
[ "function createCard(){\n\t\tinquirer.prompt([\n\t\t\t{\n\t\t\t\ttype: \"list\",\n\t\t\t\tmessage: \"What kind of cards would you like to create?\",\n\t\t\t\tchoices: [\"basic\", \"cloze\"],\n\t\t\t\tname: \"cardChoice\"\n\t\t\t}\n\t\t])\n\t\t.then(function(card_menu){\n\t\t\tswitch(card_menu.cardChoice){\n\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes signature from comments
removeCommentSignature (_comment) { if (_comment != '' && typeof(_comment) != 'undefined') { return _comment.slice(-1) == ']' ? _comment.substr(0, _comment.split('').length - 6) : _comment; } else if (_comment == '') return _comment; else return ''; }
[ "function decomment(source) {\n let lines = source.split(\"\\n\");\n return lines.filter((line) => !/^\\s*[/]{2}/.test(line)).join(\"\\n\");\n}", "function _unwrapCommentBlock(){\n var parent = $(this).parents(\"pre\");\n var unwrappedHTML = parent.html().replace(this.outerHTML, this.innerHTML);\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append to the current section content.
appendToCurrent(toAppend) { this.currentSectionContent += toAppend +"\n"; }
[ "appendCurrentHeader(header) {\n this.currentSectionContent += header + \"\\n\";\n }", "appendLoader(loader) {\n //append to body\n loader.appendTo($(this.section));\n }", "function addSection(id)\n{\n current_template_index=0;\n\n var sectionID = \"section-\"+current_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
js/physics/hitdetector.js Creates WorldEvents for collisions between bodies.
function HitDetector() { this.xOverlap = [0, 0]; this.yOverlap = [0, 0]; this.overlap = [0, 0, null]; // start, end, axis if any }
[ "_setupCollision () {\n this.PhysicsManager.getEventHandler().on(this.PhysicsManager.getEngine(), 'collisionStart', (e) => {\n\n for (let pair of e.pairs) {\n let bodyA = pair.bodyA\n let bodyB = pair.bodyB\n\n if (bodyB === this.body) {\n this.onCollisionWith(bodyA)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts completions for a module or object
function getCompletions(obj) { return [].concat( getSubCompletions(obj.functions), getSubCompletions(obj.fields) ); }
[ "async complete(text) {\n //TODO\n await this._makeCompletions();\n if (!text.match(/[a-zA-Z]$/)) return [];\n let ans = [];\n try{\n const word = text.split(/\\s+/).map(w=> normalize(w)).slice(-1)[0];\n ans = this.completions.get(word[0]).filter((w) => w.startsWith(word));\n }catch(err)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Standalone mode calculates the name numbering system used on the images and then calls the callback function i.e. image01 or image00001
function getImageNumbering(callback){ var num = '0'; if (opts.imageArray.length === 0 && opts.imagesInfo.length === 4) { (function intern(){ var path = [opts.imagePath, opts.imagesInfo[0], num, '1.', opts.imagesInfo[1]].join(''); var $img =...
[ "function getImageName(category, callBack) {\n\t\t\tif (getImageName.imageName) {\n\t\t\t\tcallBack(getImageName.imageName);\n\t\t\t} else {\n\t\t\t\tsuite.execute('vm image list --json', function (result) {\n\t\t\t\t\tvar imageList = JSON.parse(result.text);\n\n\t\t\t\t\timageList.some(function (image) {\n\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set priority/desc_name value to rule string
function set_str_rulePriority(str_rule, str_prio){ var cf = document.forms[0]; var ruleArr = str_rule.split("\x02"); ruleArr[_prio] = str_prio; ruleArr.push(ruleArr[_name]); ruleArr[_name] = cf.name.value; return (parts_arrayToString(ruleArr)); }
[ "function editProperty(ruleStr,styleSheet,property,value,ruleRepeatCount)\r\n{\r\n\tvar rule = findRule(ruleStr,styleSheet.cssRules,ruleRepeatCount);\r\n var execStr = \"rule.style.\"+property+\"=\"+value;\r\n\trule.style[property] = value;\r\n}", "function ruleLine(r) {\n return util.format('%s %s %s', r.u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO:A function to check if all inputs have been provided.
function checkAllInputs() {}
[ "function validateArgs() {\n //No arguments or any argument set including the help argument are both\n //automatically valid.\n //If -pre, -dest, -ign, -ext, -enc, or -cst were provided, -repo\n //must also have been provided.\n //The presence of -sets and -args is always optional...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads a SETUP frame from the buffer and returns it.
function deserializeSetupFrame(buffer, streamId, flags, encoders) { (0, _invariant2.default)( streamId === 0, 'RSocketBinaryFraming: Invalid SETUP frame, expected stream id to be 0.' ); let offset = FRAME_HEADER_SIZE; const majorVersion = buffer.readUInt16BE(offset); offset += 2; const minorVersion...
[ "function getNextFrame() {\n if (length >= frameByteSize) {\n // copy the frame\n buf.copy(frameBuffer, 0, 0, frameByteSize);\n // move remaining buffer content to the beginning\n buf.copy(buf, 0, frameByteSize, length);\n length -= frameByteSize;\n return frameBuffer;\n }\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a class / prototype has Kite input mappings
function hasModelInputs(cls) { return Reflect.hasMetadata(MK_KITE_INPUTS, cls); }
[ "function isKiteModel(cls) {\n return Reflect.hasMetadata(MK_KITE_MODEL, cls);\n}", "static isDefined(input) {\n return typeof (input) !== 'undefined';\n }", "isValidInputParams(context, word) {\n if (context < 0) {\n console.log(`Error: Context value ${context} should be zero or greater`);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Classifies streets by size
streetsClass() { const classify = new Map(); classify.set(1, 'tiny'); classify.set(2, 'small'); classify.set(3, 'normal'); classify.set(4, 'big'); classify.set(5, 'huge'); console.log(`${this.name}, built in ${this.yearBuilt}, is a ${classify.get(this.size)}...
[ "function composeStreets() {\n var lampsList = dataFactory.getLampList();\n var streetData = [];\n for (var i = 0 ; i < lampsList.length ; i++){\n if (JSON.stringify(streetData).indexOf(JSON.stringify(lampsList[i].address) ) === -1){\n var street = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies styling for the header from the config
_applyConfigStyling() { if (this.backgroundColor) { const darkerColor = new ColorManipulator().shade(-0.55, this.backgroundColor); this.headerEl.style['background-color'] = this.backgroundColor; /* For browsers that do not support gradients */ this.headerEl.style['background-image'] = `linear-grad...
[ "function addHeaderStyle(element) {\n element.style.margin = '6px 0px 3px 0px';\n element.style.width = width + 'px';\n element.style.textAlign = 'center';\n element.style.backgroundColor = '#cccccc';\n element.style.fontVariant = 'small-caps';\n element.style.fontWeight = 'normal';\n element.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function that assigning the task into calendar
function assignTask(){ var priority_sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("priority_queue"); var all_priority_range = priority_sheet.getDataRange(); var all_priority_data = all_priority_range.getValues(); var eventCal=CalendarApp.getCalendarById("impanyu@gmail.com"); var currentTim...
[ "function addTaskToCalendar(task, calendar, freeBlock) {\n var p = new promise.Promise(),\n req = {};\n ev = {\n 'summary': task.name,\n 'start': { 'dateTime': freeBlock.startTime.toISOString() },\n 'end': { 'dateTime' : freeBlock.startTime.clone().addMinutes(task.length).toISOStri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to push to the stack, we'll increment size, enqueue q2 with the element and then enqueue q2 with all of the elements in q1 then we simply swap the references between q1 and q2
push(element){ this.size++; this.q2.push(element); while(this.q1.length > 0) this.q2.push(this.q1.shift()); // shift is same as dequeue //swap q1 and q2 let q = this.q1; this.q1 = this.q2; this.q2 = q; }
[ "enQueue(item) {\n // move all items from stack1 to stack2, which reverses order\n this.alternateStacks(this.stack1, this.stack2)\n\n // new item will be at the bottom of stack1 so it will be the last out / last in line\n this.stack1.push(item);\n\n // move items back to stack1, from stack2\n this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function asks the user to confirm or cancel the deleting of a testimonial
function confirmDelete() { if (document.forms[0].txtPageSection.value == 3) { var answer = confirm("Do you really want to delete this testiminial?"); if (answer) { return true; } else { return false; } } }
[ "function deleteTicket(){\n var ticket_number = $('#selected_ticket_number').text();\n if (confirm(\"Are you sure you want to delete this ticket?\")) {\n $.post( '/newticket', { \"delete_ticket\": ticket_number } ).done(function(response) {\n $(`#ticket_row_${ticket_number}`).hide('fast');\n select...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test whether touches are from the same source whether this is the same touchmove event.
function sameTouch (event, touch) { return (event && event.touch) && (touch.identifier == event.touch.identifier); }
[ "function touchMove(event) {\n if (this.touchStartLocation &&\n (Math.abs(this.touchStartLocation[0] - event.touches[0].clientX) > 25 ||\n Math.abs(this.touchStartLocation[1] - event.touches[0].clientY) > 25)) {\n this.cancelTap();\n }\n }", "function didTouchMove(touch) {\n return Mat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A filename is supplied as an argument to this function. The filename is then added to threatTable as a row.
function addToThreatTable(fileName) { var threatTable = document.getElementById("threatTable").getElementsByTagName('tbody')[0]; var row = threatTable.insertRow(1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = fileName; cell2.innerHTML = "Possible Malware".font...
[ "function insertDBRow (fileHash, numberscount, letterscount, wordscount, sentencescount, colemanLiauNum, automatedReadabiltyNum){\n    db.run(`INSERT INTO textsinfo(fileHash, numbercount, lettercount, wordcount, sentencescount, colemanLiau, automatedReadability) VALUES(?,?,?,?,?,?,?)`, [fileHash, numberscount, lett...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a subpatch for thunks
function thunks(a, b, patch, index) { var nodes = handleThunk(a, b) var thunkPatch = diff(nodes.a, nodes.b) if (hasPatches(thunkPatch)) { patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch) } }
[ "function performBackpatching()\n\t{\n\t\t// Reference Variables (static)\n\t\tperformReferenceBackpatching();\n\t\t// Jumps\n\t\tperformJumpBackpatching();\n\t}", "function Window_ModPatchCreate() {\r\n this.initialize.apply(this, arguments);\r\n}", "function utilPatch(orig, diff) /* patched object */ {\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes of Map of file/filecontent pairs, and creates a temp dir that matches the file structure of the Map. Example: generateFixture('myfixture', new Map([ ['foo.js'], ['bar/baz.txt', 'some text'], ])); Creates: /tmp/myfixture_1/foo.js (empty file) /tmp/myfixture_1/bar/baz.txt (with 'some text')
async function generateFixture(fixtureName, files) { _temp.default.track(); const MAX_CONCURRENT_FILE_OPS = 100; const tempDir = await _fsPromise.default.tempdir(fixtureName); if (files == null) { return tempDir; } // Map -> Array with full paths const fileTuples = Array.from(files, tuple => { /...
[ "async function tempFile(dir, opts = { prefix: \"\", postfix: \"\" }) {\n const r = Math.floor(Math.random() * 1000000);\n const filepath = path.resolve(`${dir}/${opts.prefix || \"\"}${r}${opts.postfix || \"\"}`);\n await mkdir(path.dirname(filepath), true);\n const file = await open(fil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update a previously drawn square.
function updateSquare(width, height, x, y, color, graphics) { const rect = new Phaser.Geom.Rectangle(width, height, x, y); graphics.clear(); graphics.fillStyle = { color: `0x${color}` }; graphics.fillRectShape(rect); }
[ "updateSquares() {\n if(this.squareProps.length !== this.squares.length) {\n const diff = this.squareProps.length - this.squares.length;\n if(diff > 0) {\n for (let i = 0; i < diff; i++) {\n let newSquareInstance = this.baseSquare.createInstance(\"\" + i);\n this.squares.push...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the string name of the sampler uniform for code generation purposes
function channelSamplerName(num) { // texture 2 sampler has number 0 (0 and 1 are used for back buffer and scene) return num === -1 ? "uSampler" : `uBufferSampler${num}`; }
[ "getSkierAsset() {\n var skierAssetName;\n switch (vars.skierDirection) {\n case 0:\n skierAssetName = 'skierCrash'\n break;\n case 1:\n skierAssetName = 'skierLeft';\n break;\n case 2:\n skierA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and register a unique state for identifying the concrete authentication
function registerState() { let state = crypto.pseudoRandomBytes(20).toString('hex'); while (awaitingAuthentication[state] !== undefined) { state = crypto.pseudoRandomBytes(20).toString('hex'); } let observable = Rx.Observable.create(observer => awaitingAuthentication[state] = observer); retu...
[ "async created () {\n // Create a new instance of OIDC client using members of the given options object\n this.oidcClient = new Oidc.UserManager({\n userStore: new Oidc.WebStorageStateStore(),\n authority: options.authority,\n client_id: options.client_id,\n redirect_uri: redir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add a function to your script named `addToCollection(title, artist, year)`
function addToCollection(title, artist, year){ console.log("inside of addToCollection func." +" Title of the song "+ title + " Name of the Artist "+ artist + " The Year the song was released " + year); // that, when called, creates a new record object and pushes it into the "collection" array // - this function ...
[ "function insertNewGenre() {\n // Add code here\n}", "insert({ Meteor, Store }, { title }) {\n const id = Meteor.uuid();\n\n Meteor.call(\n 'documents.insert',\n {\n _id: id,\n title,\n }, (error) => {\n if (error) {\n Bert.alert(error.reason, 'danger');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show busy indicator inside an element
function showBusy(jqElem) { jqElem.html('<div class="busybox container center"><div class="busy"><img src="img/spinner1.gif"></div></div>'); }
[ "function showLoading(selector) {\n var html = \"<div>\";\n html += \"<img src='imagens/ajax-loader.gif'></div>\";\n insertHtml(selector, html);\n }", "function addWaitWithoutText(dom) {\n $(dom).attr(\"disabled\", \"disabled\");\n string = '<i class=\"m-loader\"></i>';\n $(dom).html(st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scrolls chat history to latest input
function scrollChatHistory() { // get last element var $last = $chatHistory.children(".chat-input").last(); var numChats = $(".chat-input").length; // if more than one chat if ( numChats > 1 ) { // get second to last eleme...
[ "function scrolTopToBottom()\n{\n let chatHistory = document.querySelector(\".chat__history\");\n chatHistory.scrollTop = chatHistory.scrollHeight;\n}", "function scrollToLastMessage () {\n $(\"#zone_chat\").animate({\n scrollTop: $('#zone_chat')[0].scrollHeight - $('#zone_chat')[0].client...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Action e) Alice solves a Key Exchange Transaction by providing the correct key
async function solveExchangeTx(contract, targetAddress, amount, key) { return await contract.functions .solve(wallet.alice.publicKey, new SignatureTemplate(wallet.alice.privateKey), key) .to(targetAddress, amount) .withFeePerByte(1) .send() }
[ "function ecDH(alicePublicKeyBase64){\r\n console.log('Received Alice public key: ', alicePublicKeyBase64);\r\n socket.emit('Acknowledgement', ' received your public key.');\r\n console.log('Sending Bob public keys: ', bobPublicKeyBase64);\r\n socket.emit('ecDH', bobPublicKeyBase64);\r\n bobSharedKey...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all paths in rootDir, starting at dirname. We don't want the paths to include rootDir so if rootDir = storybookstatic, paths will be like iframe.html rather than storybookstatic/iframe.html
function getPathsInDir(ctx, rootDir, dirname = '.') { try { return fs .readdirSync(join(rootDir, dirname)) .map((p) => join(dirname, p)) .map((pathname) => { const stats = fs.statSync(join(rootDir, pathname)); if (stats.isDirectory()) { return getPathsInDir(ctx, rootDir...
[ "function getRootPathname() {\n let pathname,\n pathRoot,\n indEnd\n\n pathname = window.location.pathname;\n\n if (pathname === '/') {\n pathRoot = pathname;\n } else {\n indEnd = pathname.indexOf('/', 1);\n pathRoot = pathname.slice(0, indEnd);\n }\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads path from server and moves the roverSprite
function roverPath(path) { roverSprite.followPath(path); }
[ "function animatePaths(){\n // Creating a shallow copy of the gamePath and move it forward by two.\n const tempPath = gamePath.slice(2);\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n drawBoard();\n decorateBoard();\n\n // Differentiate player and gamePath by using different coloration.\n drawPath(pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[MSOFFCRYPTO] 2.3.6.1 RC4 Encryption Header
function parse_RC4Header(blob) { var o = {}; var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4); if(vers.Major != 1 || vers.Minor != 1) throw 'unrecognized version code ' + vers.Major + ' : ' + vers.Minor; o.Salt = blob.read_shift(16); o.EncryptedVerifier = blob.read_shift(16); o.EncryptedVerifierH...
[ "function ARC4init(key) {\n var i, j, t;\n for (i = 0; i < 256; ++i)\n this.S[i] = i;\n j = 0;\n for (i = 0; i < 256; ++i) {\n j = (j + this.S[i] + key[i % key.length]) & 255;\n t = this.S[i];\n this.S[i] = this....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current number of points spend in the build
function getTotalPoints() { var totalPoints = window.currentBuild.traits.line1.total + window.currentBuild.traits.line2.total + window.currentBuild.traits.line3.total + window.currentBuild.traits.line4.total + window.currentBuild.traits.line5.total; return totalPoints; }
[ "getNumberOfCoins() {\n let numberOfCoins = 120000 + (this.numberOfBlocks) * 100;\n return numberOfCoins;\n }", "get points() {\n if (this.issues) {\n return this.issues.reduce((pts, issue) => pts + issue.points, 0);\n }\n\n return 0;\n }", "calculateTimeSpent()\n {\n let timesta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get lists of available MIDI controllers
function getDevices(midiAccess) { const outputs = midiAccess.outputs.values(); // add outputs to the global array and the select menu: for (let o of outputs) { addMidiItem(o); } // if any of the devices change state, add or delete it: midiAccess.onstatechange = function (item) { // if an item ch...
[ "getConnectedControllers() {\n\n var _thisSvc = this;\n\n var controllerList = [];\n\n for(var controllerId in _thisSvc.controllerInfoCollection) {\n\n var controllerInfo =\n _thisSvc.controllerInfoCollection[controllerId];\n\n controllerList.push({\n controllerId: controllerInf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List the billing.BillDetail objects [PRODUCTION] [See on api.ovh.com](
GiveAccessToAllEntriesOfTheBill(billId) { let url = `/me/bill/${billId}/details`; return this.client.request('GET', url); }
[ "list(_, since) {\n let found = false;\n console.log(`${rpad('invoice:', 31)} ${rpad('amount:', 7)} ${rpad('status:', 15)} ${rpad('conf:', 10)} pending:`);\n API.iterInvoices(\n since,\n (invoice, state, callback) => {\n found = true;\n consol...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log(duplicate([1, 2, 3, 4, 5])); // [1,2,3,4,5,1,2,3,4,5];
function duplicate(arr){ arr.forEach(item => arr.push(item)) return arr; }
[ "function dupelements(arr,a,b){\n\tvar dup = []; \n for(var i=a+1;i<b;i++){\n\tdup.push(arr[i]);\n}\nreturn dup;}", "function uniqMethod() {\n\tvar testarray=[1,2,2,1,2,3,1,1,1,4,4,4,4,3,3,5,6,6,7,7];\n\tvar result=_.uniq(testarray);\n\tconsole.log(result);\n}", "function remove_duplicates(arr) {\n console.lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
runner for selection sort nonrecursive
function selectionSort() { for (var i = 0; i < dataArray.length; i++) { sSort(i); sleep(500); redraw(); } }
[ "function sortResults() {\n let perDesc = (a, b) => a[0] - b[0]\n let perAsc = (a, b) => b[0] - a[0]\n let indDesc = (a, b) => (a[1] + a[2]) - (b[1] + b[2])\n let indAsc = (a, b) => (b[1] + b[2]) - (a[1] + a[2])\n switch (sortBy.value) {\n case \"0\":\n result.sort(perDesc)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
============================================================ ============================================================ class L2DExpressionParam ============================================================ ============================================================
function L2DExpressionParam() { this.id = ""; this.type = -1; this.value = null; }
[ "constructor(params) {\n this.OP = params.OP;\n this.x = params.x - 1;\n this.y = params.y - 1;\n this.z = params.z - 1;\n this.x2 = params.x2 ? params.x2 - 1 : null;\n this.y2 = params.y2 ? params.y2 - 1 : null;\n this.z2 = params.z2 ? params.z2 - 1 : null;\n this.W = params.W;\n }", "li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CLOSEDIV: closes either highlightExpandedDivLine or downplayExpandedDivLine (div w/ options to highlight/downplay missing)
function closeDiv(element) { element.style.display='none'; }
[ "function closeAllDivs() {\r\n\tcloseDiv(highlightExpandedDivLine); \r\n\tcloseDiv(downplayExpandedDivLine); \r\n\tcloseDiv(highlightExpandedDivBar); \r\n\tcloseDiv(downplayExpandedDivBar); \r\n\tcloseDiv(annotateExpandedDivLine); \r\n\tcloseDiv(annotateExpandedDivBar);\r\n}", "function openDiv(element) {\r\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
utils.js (c) Copyright 2018, Brian Mottershead. All rights reserved. / UTILITIES Returns ancestor of QTI (XML) element with a specified tag.
function getQTIAncestor(elem, tagName) { while (elem && elem.tagName!=tagName) elem = elem.parentElement; return elem; }
[ "function selectAncestor(elem, type) {\n type = type.toLowerCase();\n if (elem.parentNode === null) {\n console.log('No more parents');\n return undefined;\n }\n var tagName = elem.parentNode.tagName;\n\n if (tagName !== undefined && tagName.toLowerCase() === type) {\n return elem.pare...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close client socket under the given peer key.
closeClient(key) { if (this.clients[key]) { this.clients[key].close(); delete this.clients[key]; } }
[ "close(callback) {\r\n debugLog(\"ServerSecureChannelLayer#close\");\r\n // close socket\r\n this.transport.disconnect(() => {\r\n this._abort();\r\n if (_.isFunction(callback)) {\r\n callback();\r\n }\r\n });\r\n }", "function onSocke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets the articles for the previous page, returns nothing if we are on the first page
previousPage(currentPage) { if (currentPage > 1) { this.getArticles(currentPage-1); } }
[ "prev() {\n\t\t\tif (this.currPage > 1) {\n\t\t\t\tthis.currPage--;\n\t\t\t\tthis._loadPage();\n\t\t\t}\n\t\t}", "function GetRecordsPrevious(){\n CleanTable('available_records_table');\n GetRecords(records.previous_page);\n}", "function loadRecent() {\n \n if (paginationOptions.pageFirst > 0) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates cat list item for each cat and makes it clickable.
createCatListItem(cat) { let catListItem = document.createElement("li"); catListItem.textContent = cat.name; document.getElementById("cats-list").appendChild(catListItem); catListItem.addEventListener("click", () => { catApp.setCurrentCat(cat); catApp.setAdminSettings(false); }); }
[ "function createCategoriesSlider() {\n let startPoint = document.querySelector(\".dashboard__categories__slider\");\n\n categories.forEach((cat, i) => {\n let sliderItem = document.createElement(\"div\");\n sliderItem.className = \"categories__slider__item\";\n sliderItem.classList.add(`${cat.classes}`);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a 32bit floating number and move pointer forward by 4 bytes.
readFloat32() { const value = this._data.getFloat32(this.offset, this.littleEndian); this.offset += 4; return value; }
[ "function readFloat(x, f)\n//\n// Input: none\n// Output: x = pointer to a float variable\n// Purpose: reads a floating point value from a hot start file\n//\n{\n // --- read a value from the file\n fread(x, sizeof(float), 1, f);\n\n // --- test if the value is NaN (not a number)\n if ( (x) != (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make invisible all the cards that are not the desired type the one from active tab
function solveActiveCards(type) { let filterReset = type === ""; /* No type means no filter, then we should reset filters */ let invisibleClass = "invisible"; let cards = document.getElementsByClassName("more-cards__card-wrapper") if (filterReset) { /* We reset the invisible filter */ r...
[ "function hideCards() {\n\tcards.forEach(card => {\n\t\tcard.classList.add(\"hidden\");\n\t})\n}", "function hideCard(card) {\n // get a list of all cards\n\n let cardArray = ['lbValue','kgValue','ozValue','gmValue'];\n\n \tfor(var i= 0;i < cardArray.length; i++) {\n \t\tif(cardArray[i] == card) {\n \t\t\tlet ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the name of the export, displayed in the web app header
function renameExport(fbDatabaseUrl, exportName) { var token = ScriptApp.getOAuthToken(); var fb = FirebaseApp.getDatabaseByUrl(fbDatabaseUrl || FIREBASE_DB_URL, token); fb.setData('siteTitle', exportName || EXPORT_NAME); }
[ "function M_app_name() {\n document.title = V_app_name;\n}", "function setTitle( uInfo ) {\n window.document.title = \"\" + uInfo.serviceId; // Set the browser window/tab title\n }", "_updateTitle()\n {\n document.head.querySelector('title').innerText = `[${this._toStrin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new shirt to the cart contents
function add_shirt() { var size = validate_size( 'shirt_size', '70th Anniversary Golf Shirt' ); if( ! size ) { return; } var shirt = {}; shirt.amount = 35; shirt.item_name = shirt_id; shirt.on0 = shirt_size_code; shirt.os0 = size; shirt.tax_rate = 13; cart_contents.push( shirt ); rebuild_cart(); }
[ "function add_hat()\n{\n\tvar hat = {};\n\that.amount = 15;\n\that.item_name = hat_id;\n\that.tax_rate = 13;\n\n\tcart_contents.push( hat );\n\trebuild_cart();\n}", "function addToCart() {\n var currentFlavor = document.getElementById(\"flavor-select\");\n var currentPrice = document.getElementById(\"curren...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a function for postV3ProjectsIdPipeline
postV3ProjectsIdPipeline(incomingOptions, cb) { const Gitlab = require('./dist'); let defaultClient = Gitlab.ApiClient.instance; // Configure API key authorization: private_token_header let private_token_header = defaultClient.authentications['private_token_header']; private_token_header.apiKey = 'YOUR API ...
[ "postV3ProjectsIdTriggers(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if tag exists in source list
tagInSourceList(tag) { return this.props.sourceTags.find((source) => { return source.label === tag; }) ? true : false; }
[ "hasTag(tag) {\n var tags = this.getTags();\n for (var i = 0; i < tags.length; i++) {\n if (tags[i] == tag) {\n return true;\n }\n }\n return false;\n }", "function isSource(_socketid, _sourceList){\n return _sourceList.hasOwnProperty(_socketid)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw what lies in deep space
function drawDeepSpace(ctx) { ctx.lineWidth = 1; ctx.strokeStyle = me.style.courseColor; ctx.fillStyle = me.style.textColor; ctx.font = me.style.fontSize.eta + ' ' + me.style.font; uni.deepspace.fleets.forEach(function(entry) { drawFleet(ctx, entry.fleet, entry....
[ "draw(ctx) {\r\n if (this.isDistanced) {\r\n this.distanceGraph();\r\n }\r\n // draw all nodes and store them in grid array\r\n this.nodeList.forEach(node => {\r\n node.draw(ctx);\r\n storeNodeAt(node, node.x, node.y);\r\n });\r\n\r\n // draw all edges\r\n this.edgeList.forEach(e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filter tasks by deadline: tomorrow/next week
function deadlineFilter() { var filter = document.getElementById("date_filter"); var deadlineList = document.getElementsByClassName("isDeadline"); hide("notDeadline"); var today = new Date(); var tomorrow = new Date(); var nextWeekMonday = new Date(); var nextWeekSunday = new Date()...
[ "sortTasks() {\n var tempTasks = this.taS.getTasks();\n tempTasks.sort(function(a,b){\n return a.deadline-b.deadline;\n });\n return tempTasks;\n }", "function find_job_in_period(start, end, task, jobs){\n for(var i=0;i<jobs.length;i++){\n var job = jobs[i];\n if(job.task === ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create new object which maps gridState to 2D Immutable array, and merge the results back into the prior state.
function setInitialState(state, incomingData) { let width = incomingData.gridWidth; let outerArray = []; for (let i = 0; i < width; i++) { let innerArray = []; for (let j = 0; j < width; j++) { innerArray.push( { index: [i, j], alive: false }) } outerArray.push(innerArray)...
[ "getState() {\n let state = [];\n for (let x = 1; x < this.w+1; x++) {\n state[x-1] = [];\n for (let y = 1; y < this.h+1; y++) {\n state[x-1][y-1] = this.state[x][y];\n }\n };\n\n return state;\n }", "function newGrid() {\n for (var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function used to fetch all news for specific category and assign it to "liftNewsInCategory and rightNewsInCategory" local variables for storing it.
getAllNews() { this.dataBase.findByIndex("/news", ["_id", "title", "attachment"],"categoryId", mvc.routeParams.id).then( data => { if (data) { let length = data.docs.length; this.liftNewsInCategory = data.docs.slice(0, length / 2); this.rightNewsInCat...
[ "function everythingCategoryAPICall(theCategory) {\n return new Promise((resolve, reject) => {\n newsapi.v2.everything({\n q: theCategory\n }).then(response => {\n resolve(response);\n })\n })\n}", "getArticlesCategory (category: string, callback: mixed) {\n\t\tsuper.query(\"select * from New...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register the plugins services into the container
async registerPluginsServices() { for (let p of this.getPlugins()) { const { name, plugin, path } = p; this.currentPluginPath = path; if (plugin.registerServices) { if (!_.isFunction(plugin.registerServices)) { throw new PluginError( ...
[ "async bootContainer() {\n this.createContainer();\n await this.registerFrameworkServices();\n await this.registerPluginsServices();\n await this.registerApplicationServices();\n\n for (let p of this.getPlugins()) {\n const { path, plugin } = p;\n this.curren...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the nodes with their ports that branch away from the node `to` in the path array `paths`
function branchingPoints (paths, to, port) { var toMap = _.keyBy(to, 'node') // the paths that do not go through a continuation node var branchingPaths = _(paths) .reject((path) => _.find(path, (p) => toMap[p.node])) .map((path) => _.reverse(path)) .value() // the pathes to the continuations (withou...
[ "findPaths(fromNavNode, toNavNode) {\r\n\t\tlet walkingPaths = [[fromNavNode]];\r\n\t\tlet rtn = [];\r\n\r\n\t\twhile( walkingPaths.length > 0 ) {\r\n\t\t\tlet curPath = walkingPaths.pop();\r\n\t\t\tlet curNode = curPath[curPath.length-1].node;\r\n\t\t\tlet noRoute = false;\r\n\t\t\twhile( !noRoute && curNode != to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }