query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
This part is the randomizer for the lower letter
function randomLowerLetter(){ return String.fromCharCode((Math.random()*26)+97); }
[ "function genLowerLetters (){\n var random=lowerLetters[Math.floor(Math.random()*lowerLetters.length)];\n return random;\n }", "function getRandomLowerCase() {\n return String.fromCharCode(Math.floor(Math.random() * 26) + 97);\n }", "function get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
...function that calculates the variable expire by subtracting the the date now from expires on and returning minutes
function calculateExpire() { var expiresIn = Math.round((((messageObject.expiresOn-new Date(Date.now())) % 86400000) % 3600000) / 60000); // minutes console.log(expiresIn); return expiresIn }
[ "getTimeLeft() {\n let now = new Date();\n let timeLeft = Math.ceil((this.expireTime.getTime() - now.getTime()) / 1000);\n return timeLeft;\n }", "function calculateExpiryDate() {\n var now = new Date().getTime();\n var distance = expiryTimestamp - now;\n var days = Math.floor(distance / (1000 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the decimal part of a float number
function decimal(f) { return f - Math.floor(f); }
[ "function decimalPart(num) {\n var n = (num + \"\").split(\".\")[1];\n return n;\n}", "function getDecimal(f) {\n return f - parseInt(f);\n}", "function makeFloat(n) {\n\t\tn += (n.toString().indexOf('.') == -1) ? \".0\" : \"\";\n\t\treturn n;\n\t}", "function fractionalPart(n) {\n const nSplit = (n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Linearizes the given AST into a stack.
function convertTreeToStack(ast, stack) { estraverse.traverse(ast, { enter: function(node) { stack.push(node); } }); }
[ "function Assign_Lex_Stack() {\r\n}", "function stackAnalyzer() {\n data.functions.forEach(function(func) {\n var lines = func.labels[0].lines;\n var hasAlloca = false;\n for (var i = 0; i < lines.length; i++) {\n var item = lines[i];\n if (!item.assignTo || item.intertype != 'allo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return an iterator over the keys of the lru map
* keys() { for (const [key] of this) { yield key; } }
[ "keys() {\n return this[symbol_1.LRU_LIST].toArray().map(k => k.key);\n }", "keys()\n {\n // Local variable dictionary\n let keys = new LinkedList();\n\n // Get the keys\n for (let counter = 0; counter < this.#table.getLength(); counter++)\n {\n // Get th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that when ECDH crypto key is exported and imported it gives the same key as the original one.
async testImportExportCryptoKeyECDH() { const curveTypes = Object.keys(EllipticCurves.CurveType); for (let curve of curveTypes) { const curveTypeString = EllipticCurves.curveToString(EllipticCurves.CurveType[curve]); const keyPair = await EllipticCurves.generateKeyPair('ECDH', cu...
[ "async testImportExportJsonKeyECDH() {\n for (let testKey of TEST_KEYS) {\n const jwk = /** @type{!webCrypto.JsonWebKey} */ ({\n 'kty': 'EC',\n 'crv': testKey.curve,\n 'x': Bytes.toBase64(Bytes.fromHex(testKey.x), true),\n 'y': Bytes.toBase64(Bytes.fromHex(testKey.y), true),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validation for days and night
function validate_days (night, day) { var night = document.getElementById(night).value; var days = document.getElementById(day).value; var totalday = parseInt(days) - 1; if (night != totalday) { error_msg_alert('Number of days must be greater than night by 1.'); $('#' + day).css({ border: '1px solid red' }); ...
[ "function checkDay(d){\n\t if (d<=0 || d>=32) {\n\t alert(\"Please fix your day number.\");\n\t }\n\t \treturn false\n\t }", "function validator() {\n if ((Number(day) < 0 || Number(day) > 31) || (Number(month) < 0 || Number(month) > 12)) {\n alert(\"Enter valid day or month\")\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the closest line start for the given position.
function findClosestLineStartPosition(linesMap, position, low = 0, high = linesMap.length - 1) { while (low <= high) { const pivotIdx = Math.floor((low + high) / 2); const pivotEl = linesMap[pivotIdx]; if (pivotEl === position) { return pivotIdx; }...
[ "function findStartLine(cm, n, precise) { // 1561\n var minindent, minline, doc = cm.doc; // 1562\n var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 100...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts a nonce, and generates a unique hash for the block. Updates the hash and nonce properties of the block accordingly. Hint: The format of the hash is up to you. Remember that it needs to be unique and deterministic, and must become invalid if any of the block's properties change.
calculateHash(nonce) { // Your code here }
[ "updateNonce() {\n\t\tthis.nonce += 1;\n\t\tlet updatedBlock = new Block(this.index, this.transactions, this.prevHash, this.targetHash, this.timestamp, this.nonce);\n\t\tthis.hash = updatedBlock.hash;\n\t}", "updateNonce() {\r\n this.nonce += 1;\r\n let updatedBlock = new Block(this.index, this.transactions...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the seed value input
function readSeed() { var input = $("#seedInput").val().trim(); loadSeed(input); }
[ "function genSeed() {\n var timestamp = Date.now();\n seed = parseInt((timestamp*2).toString().slice(0,9)).toString(36);\n seedInput.val(seed);\n }", "function get_random_seed() {\n // Get random seed value from input form\n let rand_seed = document.getElementById(\"random-seed-form\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Anything to do with updating any aspect of a comment can go through this function, as we treat comments as immutable meaning if any part of it changes a new comment is created with updated data. On the server the original would be changed though. General overview of the lifecycle Sends comment to server, which means se...
updateComment(comment, field) { const data = { updateField: field, comment: comment }; this.socket.emit('comment update', data); this.applyWaitingFeedbackForEvent("comment update", comment.id); }
[ "onUpdateComment(data) {\n const updateField = data.updateField;\n const comment = JSON.parse(data.comment);\n\n // replace old comment with the new one in the same index so it doesn't affect sorting order.\n let newComments = this.state.comments\n .update(this.state.comments....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes a refresh token grant request against the given URI. If the first parameter is an instance of [[XsuaaServiceCredentials]], the response's access_token will be verified. If the first parameter is an URI, the response will not be verified.
function refreshTokenGrant(xsuaaUriOrCredentials, clientCredentials, refreshToken, options) { var authHeader = headerForClientCredentials(clientCredentials); var body = objectToXWwwUrlEncodedBodyString({ grant_type: GrantType.REFRESH_TOKEN, refresh_token: refreshToken }); return executeX...
[ "function refreshToken() {\n makeRequest({\n refresh_token: refresh,\n client_id: id,\n client_secret: secret,\n grant_type: 'refresh_token'\n });\n}", "function refreshAccess () {\n return new Promise(function (resolve, reject) {\n // Return if there no refresh token:\n if(!refreshToken) {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an 'original' and 'new' cell, if the original cell uses shared strings and the new cell uses inline strings, replace the contents of the original cell's shared strings in the shared string table with the new cell's inlined strings and change the new cell's 't', 'v', and 'is' to match. Side effects: newCell is mod...
function _lookupAndOverwriteSharedStrings(sharedStrings, origCell, newCell) { // if the original cell used shared strings if (origCell.v && CellValues.SharedString.xmlValue == origCell.t) { var isInlineStr = false, isInvalidFormatStr = false; // if the new cell uses inline string...
[ "function insertOrOverwriteCell(cells, newCell, allowOverwrite, allowMerge, overwriteSharedStrings, sharedStrings) {\n var parseCol = CellRefUtil.parseCellRefColumn;\n var cellIdx = parseCol(newCell.r);\n // if an existing cell has the same index, overwrite it (if allowed), return\n var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resize IFRAME windows and Chat room elements
function iframeResize(i_id) { // Get window height var xSize = new Array(); xSize = inner_size(); if ( (!xSize[1] && document.getElementById(i_id).style.height == "") ) { document.getElementById(i_id).style.height = "550px"; // Cannot be adjusted dynamically return; } else { var containerWidth = x...
[ "function _resizeIframe() {\n if (isOn && $iframe) {\n var chatBoxWidth = chatBox.$panel.innerWidth() + \"px\";\n $iframe.attr(\"width\", chatBoxWidth);\n }\n }", "static resizeIframe() {\n const calculatePageY = (elem) => {\n return elem.offsetParent\n ? elem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves those schemas which depends on other collections data.
function saveSchemas(app) { var keys = Object.keys(DependenciesMap); if (keys.length == 0) { _l('Default data saved...'); event.emit(COMPLETED_EVENT); return; } HandlerArray = []; var errFlag = true; keys.forEach(function (k) { dependenciesExists(k) && HandlerArra...
[ "saveSchema(schema) {\n if (schema.name) {\n this.definitions[schema.name.toLowerCase()] = schema;\n }\n if (schema.id) {\n this.definitions[schema.id.toLowerCase()] = schema;\n }\n }", "function saveSchema(schemaJSON1){\n\tWebUtils.doPost(\"/schema?operation=s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function formatDate converts a date in string to a date object in local time. Args: string: date in string
function formatDate(string){ var options = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }; return new Date(string).toLocaleDateString([],options); }
[ "function formatDateLocal(format, locale, date) {\n\tvar formatters = dateFormatters;\n\tvar lang = locale.slice(0, 2);\n\n\t// Use date formatters to get time as current local time\n\treturn format.replace(rtoken$1, function($0) {\n\t\treturn formatters[$0] ? formatters[$0](date, lang) : $0 ;\n\t});\n}", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
marquee text accross the display
function displayTextMarquee(text) { $("#display").empty(); $('#display').append("<marquee behavior=scroll direction='left' scrollamount='22'>"+text+"</marquee>") }
[ "function generateMarquee() {\n\t$(\"#trainMessage\").html(trainMessageArray[0]);\n\tsetInterval(generateMarqeeText, 20000);\n}", "function makeMarquee() {\n const title = 'Made by Madison Hardt'\n const marqueeText = new Array(500).fill(title).join(' &mdash; ')\n const marquee = document.querySelector('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unselect the feature when it's popup is closed
function onPopupClose(evt) { selectFeaturesControl.unselect(selectedFeature); }
[ "function handleFeaturePopupClose(event) {\t\t\t\n select_feature_control.unselect(environment.active_feature);\t\t\t\t\n\t\tconsole.log(\"closing popup..\" + environment.active_feature);\t\t\t\n }", "function onFeatureUnSelect(evt) {\n feature = evt.feature;\n if (feature.popup) {\n popup....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears the hierarchy selection for the given bank and all of its descendants.
resetExpansion(bank, pathSet) { pathSet.delete(bank.pathId); bank.childNodes.forEach((bc) => { this.resetExpansion(bc, pathSet); }); }
[ "clear () {\n this._tree = [];\n }", "function clearUITree(tree){\n tree.jstree('deselect_all');\n tree.find('ul').empty();\n }", "clear() {\n this.subtree.clear();\n }", "clear () {\n Object.keys(this.children).forEach(childName => this.children[childName].cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to update the card count after every "deal" finishes
function updateCount() { $('.playCount').html("Player cards: " + playerHand.length); $('.compCount').html("Computer cards: " + compHand.length); }
[ "updateCardCounter() {\n const counterElement = this.element.querySelector('.deck-counter');\n counterElement.textContent = this.cards.length;\n }", "function updateMyCardCount() {\n var count = LocalState.myHand.length;\n\n // update my local state\n LocalState.cardCounts[Network.myId] = count;\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method update our new friend name This method updates the state based on input from the user. This keeps our state matched to what is on screen. Our listener in our JSX (in the render method) will fire this code to make sure our variable state matches what the physical input on the screen has. That way, at any given ti...
updateNewFriend (e) { //remember that calling setState triggers a re-render if the data on screen changes //It is an incremental change so it's only the stuff that actually changed. this.setState({ newFriend: e.target.value }); }
[ "handleFriendChange(e) {\n this.setState({ friendName: e.target.value });\n }", "onNameUpdate(event) {\n if (event.target.innerText.length == 0) {\n event.target.innerText = \"Anonymous\"\n }\n if (this.state.username !== event.target.innerText) {\n let notification = (\"// SYSTEM NOTIFICAT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete Competition Division from Comp Details
function removeCompetitionDivisionAction(payload) { return { type: ApiConstants.API_COMPETITION_DIVISION_DELETE_LOAD, payload, }; }
[ "deleteDivision(division, phase) {\n this.props.deleteDivision({divisionName: division, phase: phase});\n }", "onRemoveCompetition(e) {\n\t\tvar compId = e.currentTarget.id.replace(\"remove-\", \"\"),\n\t\t\tcomp = factory.All[compId];\n\t\tuserModel.Competitions.remove(comp);\n\t\tthis.forceUpdate();\n\t}", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A chart which displays commit activity from a GitHub project.
function ActivityChart(props) { function onChangeRepo(event) { event.preventDefault(); var repo = event.target['repo'].value; actions.selectRepo(props.dispatch, repo); } function onResetClick() { props.dispatch(actions.resetRepo()); } function onZoomClick() { if (props.isZoomed...
[ "function getDataForGitHubCourseCommitsCharts(array){\n\n var commits = []; var linesOfCodeAdded = []; var linesOfCodeDeleted = []; var data = [];\n\n for (var i = 0; i < array.length; i++){\n\n var valueset1 = [];var valueset2 = [];var valueset3 = [];\n\n valuese...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RETURNS THE LEADERBOARD FOR MATCH AND TIME LIMIT
getMatchLeaderboard(matchName, timeInMillis) { return Match.find({ matchName }).exec().then(matches => { if (matches.length === 0) throw new CustomError("Invalid match name provided.", 404); return PlayerStat.find({ match: matches[0] }).exec().then(playerStats => { return...
[ "static periodicMatch() {\n\t\t// In order from longest waiting to shortest waiting\n\t\tfor (const [formatid, formatTable] of exports.Ladders.searches) {\n\t\t\tif (formatTable.numPlayers > 2) continue; // TODO: implement\n\t\t\tconst matchmaker = exports.Ladders.call(void 0, formatid);\n\t\t\tlet longest = null;\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
init and returns an instance of Progress
static factory() { return new Progress().init(); }
[ "function Progress() {\n this.percent = 0;\n this.el = document.createElement('canvas');\n this.ctx = this.el.getContext('2d');\n this.color = '#00bbff';\n this.shadowColor = 'rgba(0, 187, 255, 0.3)';\n this.fontSize = 12;\n this.font = 'helvetica, arial, sans-serif';\n this.size(52);\n}", "function VNPro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create confirmation dialog when trying to delete a role
function deleteRole() { let role_id = $(this).data().roleid; DeleteDialog( "Delete Role from Database", "Are you sure you want to remove the role from the database? <br> The action can <b>not</b> be reversed.", "role", role_id ); }
[ "function deleteRoleConfirm(role, ev)\n {\n // var confirm = $mdDialog.confirm()\n\n var index = vm.contacts.map(function (e) {\n if(e.hasOwnProperty(\"roles\")){\n return e.roles.findIndex(function (x) {\n return x.id === role.id\n });\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
need to override how templates are lexed because of delimiters
scanTemplateElement() { let startLocation = this.getLocation(); let start = this.index; while (this.index < this.source.length) { let ch = this.source.charCodeAt(this.index); switch (ch) { case 0x60: { // ` // don't include the traling "`" ...
[ "beforeParseTemplate(){}", "function parseTemplate(delims) {\n var oldprevChar = prevChar; // record old previous char\n var ts = inPtr-2; // record entry point for later rewinding\n var tn = parseTemplateIdentifier(); // get template name\n var args;\n var tc; // actual code to insert\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when an unsupported expression is encountered, throw an error
function unsupportedExpression(node){ console.error(node) var err = new Error('Unsupported expression: ' + node.type) err.node = node throw err }
[ "getExpressionOrThrow() {\r\n return errors.throwIfNullOrUndefined(this.getExpression(), \"Expected to find an expression.\");\r\n }", "validateMetricExpression(expr) {\n if (expr.searchAccount !== undefined || expr.searchRegion !== undefined) {\n throw new Error('Cannot create an Alar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. No guarantees are made about order, or duplicates sumIntervals([1,4], [3,5] [7, 10], [8, 9]) => (51) + (107) => 4+3 => 7 [1,4] and ...
function sumIntervals(intervals){ var removedSomething = false; //Keep reducing the list until no more elements are removed while(true) { removedSomething = false; //ensure that intervals are always sorted based where they start intervals.sort(function(a, b){return a[0]-b[0]}); for(var i = ...
[ "function sumIntervals(intervals){\n\n let sorted = intervals.sort((a,b) => a[0] - b[0]);\n\n let unique = [sorted.shift()];\n\n const hasOverlap = (a, b) => {\n if((b[0] > a[0]) && (b[0]) > a[1]) return false;\n return true;\n };\n\n const combine = (a, b) => b[1]>a[1] ? [a[0], b[1]] :...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start all threads that start with the green flag.
greenFlag () { this.stopAll(); this.emit(Runtime.PROJECT_START); this.ioDevices.clock.resetProjectTimer(); this.targets.forEach(target => target.clearEdgeActivatedValues()); // Inform all targets of the green flag. for (let i = 0; i < this.targets.length; i++) { ...
[ "function start_green () {\n visual.swap(_.flippar(_.merge, {color: \"green\"}));\n setTimeout(start_red, green_length);\n }", "function redLightGreenLight(blue, purple){\r\n for (var i = 0; i < blue; i++){\r\n\r\n if (purple){\r\n run();\r\n }\r\n else {\r\n stop();\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a root component and sets it up with features and host bindings. Shared by renderComponent() and ViewContainerRef.createComponent().
function createRootComponent(componentView, componentDef, rootView, rootContext, hostFeatures) { var tView = rootView[TVIEW]; // Create directive instance with factory() and store at next index in viewData var component = instantiateRootComponent(tView, rootView, componentDef); rootContext.components.pu...
[ "function createRootComponent(componentView, componentDef, rootLView, hostFeatures) {\n var tView = rootLView[TVIEW]; // Create directive instance with factory() and store at next index in viewData\n\n var component = instantiateRootComponent(tView, rootLView, componentDef); // Root view only contains an instance...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
zwraca statyczna ocene pozycji na podstawie szachownica.ocena
function ocen_statycznie() { return szachownica.ocena.material + (szachownica.ocena.faza_gry * szachownica.ocena.tablice + (70 - szachownica.ocena.faza_gry) * szachownica.ocena.tablice_koncowka) * 0.03; }
[ "function zmien_ocene(ruch_t)\n{\n let nr_bierki_p = szachownica.pola[ruch_t.wiersz_p][ruch_t.kolumna_p];\n let nr_bierki_k = szachownica.pola[ruch_t.wiersz_k][ruch_t.kolumna_k];\n\n if(nr_bierki_k !== 0)\n zmien_ocene_usun(ruch_t.wiersz_k, ruch_t.kolumna_k);\n\n szachownica.ocena.tablice += wart...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
const handleCallback () => setTheme('light');
function handleCallback() { setTheme('light'); }
[ "function setColorTheme(){\n\n}", "handleThemeChange(event) {\n const { updateConfig } = this.props;\n\n updateConfig({\n theme: {\n palette: {\n type: event.target.value,\n },\n },\n });\n }", "setTheme(state,themeName){\n state.currentTheme = themeName;\n }",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable or disable expanded (wide) character mode.
setExpandedCharacters(expanded) { this.expanded = expanded; }
[ "function toggleCharExpr() {\n\tlexingCharExpr = !lexingCharExpr;\n}", "isExpandedCharacters() {\n return this.expanded;\n }", "function toggleEditorMode() {\n\tif (KeyboardMode == \"ace\") {\n\t\tKeyboardMode = \"vim\";\n\t} else {\n\t\tKeyboardMode = \"ace\";\n\t};\n\tsetEditorModeAndKeyboard();\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates modal window with Login Form injected
function doModalLogin() { customModalBox.htmlBox('yt-LoginContent_Popup', '', 'Log in'); $('ctl00_txtLoginUsername1').focus(); loginClose(); }
[ "function doModalLogin_() {\n\tcustomModalBox.htmlBox('yt-LoginContent_Popup', '', 'Log in'); \n\tloginClose_();\n}", "function login() {\n $('#login').modal('show');\n}", "function login() {\n vm.modal.show();\n }", "function showLogin() {\n openLoginDialog();\n }", "openLogin(){\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We now need to recursively insert chunks into the database.
function insertChunk(remainingData, indx) { var fullsplit = remainingData.length > CHUNK_SIZE; console.log(remainingData); var uploadingChunk = remainingData.slice(0, fullsplit ? CHUNK_SIZE : remainingData.length); client.query('INSERT INTO...
[ "function insertChunk(chunk,i) {\n console.log(`${config.color.yellow} chunk ${++i} ${config.color.white}[ resolved ]`);\n return new Promise(function(resolve, reject) {\n records.insertMany(chunk, function(err) {\n if(err) reject(err);\n else resolve();\n });\n });\n }", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the node address
async nodeAddressTest(address) { const result = await this.requestServer(address, 'ping', { method: 'GET', timeout: this.options.request.pingTimeout }); if(!result.address) { throw new Error(`Host ${ address } is wrong`); } }
[ "async checkNodeAddress(address) {\n const result = await this.requestServer(address, 'ping', {\n method: 'GET',\n timeout: this.options.request.pingTimeout\n });\n\n if(result.address != this.address) {\n throw new Error(`Host ${this.address} is wrong`);\n }\n }", "che...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updateHotel function to get Hotel by id.
update(req, res) { Hotel.update(req.params.id, req.body, function(err, result) { if (err) { return res.send(err); } return res.json(results); }); }
[ "update(hotel,params){\n this.sendAction('update',hotel,params);\n }", "function hotel(t, id) {\r\n return t.state.objs.hotels[id];\r\n }", "get HotelID() {\n return this._HotelID;\n }", "function setFeatureHotel(req, res){\r\n var hotelId = req.params.id;\r\n var params = req.body...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a function that maps all loans created to a table
function renderTableData() { return loans.map(loan => {const {amount, borrower_name, lender_name} = loan return ( <tr key = {amount, borrower_name, lender_name}> <td>{amount}</td> <td>{borrower_name}</td> <td>{lender_name}</td> </tr> )}) }
[ "static async getAllLoans() {\n const { rows } = await db.query('SELECT * FROM loans ORDER BY id ASC');\n return rows;\n }", "static tableFromMap(map) { return grok_UI_TableFromMap(map); }", "function lander_table( lander, isnew = true ){\n var table = {};\n if(isnew){ \n table = {' ': [ ' ', 'curre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show only employees from a selected organisation
function showOrgPeople(orgName){ orgBookDiv.style.display = "none"; addressBook = JSON.parse(localStorage['addressBook']); // Loop over the array addressBook and insert into the page viewEmployeesDiv.innerHTML = ''; viewEmployeesDiv.innerHTML += '<div class="back"><a href="#" class="backbutton" data-id="' + n...
[ "viewEmployeesByDepartment() {\n\t\treturn this.connection.query(\n `\n SELECT\n e1.id AS ID,\n e1.first_name AS First_Name,\n e1.last_name AS Last_Name,\n role.title AS Role,\n department.name AS Department,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
snapshot_type computed: true, optional: false, required: false
get snapshotType() { return this.getStringAttribute('snapshot_type'); }
[ "sfFormatSnapshot(snapshot, type) {\n\t\tvar sfName = SF.sfriseName(type.modelName);\n\t\tvar so = new this.sforce.SObject(sfName);\n\t\tif(snapshot.id != null)\n\t\t\tso.Id = snapshot.id;\n\t\tsnapshot.eachAttribute((name, meta) =>{\n\t\t\tvar metaOptions = type.metaForProperty(name).options;\n\t\t\tif(metaOptions...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description 1. Matrix Generator merupakan sebuah fungsi yang menerima input berupa string 2. Fungsi akan mengembalikan sebuah array multidimensi
function matrixGenerator(str) { // your code here let result = []; let jumlahArr = 1; for (let h = 1; h < str.length; h++) { if (h * h >= str.length) { jumlahArr = h; break; } } let selisih = jumlahArr * jumlahArr - str.length; let indexStr = 0; for (let i = 1; i <= jumlahArr; i++) ...
[ "function getMatrix(){\n var debug = false;\n var Ngroups = parseInt(document.getElementById(\"input_categories\").value);\n var genMatrix = createArray(Ngroups,Ngroups); // initialise\n\n for (m=0;m<Ngroups;m++){\n for (n=0;n<Ngroups;n++){\n // get the values from the form:\n if (debug) console.log(\"value (\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions / Initialize the default look to canvas
function init() { clearCanvas() drawBackgroundColor() drawOrigin() }
[ "function initialize() {\n createCanvas(480, 300);\n background(0);\n frameRate(fr);\n strokeWeight(.1);\n stroke(255);\n}", "function setupCanvas() {\n\tcanvas = document.getElementById('canvas');\n\tcontext = canvas.getContext('2d');\n\tfixRetina();\n\tsetButtonStates();\n}", "function init() {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
JScript source code check if the str is only contains blank
function chkblank(str){ if (str.replace(/ */,"")=="") return true; else return false; }
[ "function blank(s) {\n\tif (typeof s !== \"string\") toss(\"type\");\n\tif (s.length === 0) return true;\n\treturn false;\n}", "function StringIsNullOrWhiteSpace(str){\n \treturn str === null || str.match(/^ *$/) !== null;\n\t}", "function $S(s) {\n return s != null && s.toString().length > 0\n}", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create an internal function to create x axis
function createXAxis() { return d3.svg.axis().scale(that.x).orient('bottom').ticks(chart.xAxis.tickCount); }
[ "function make_x_gridlines() {\r\n return d3.axisBottom(xTime)\r\n }", "drawXAxis() {\n const scale = this.createTimeScale(this.dateSelect.currentRange());\n const axis = this.createTimeAxis(scale);\n\n this.svg\n .append('g')\n .attr('class', 'x_axis inner_grid')\n .attr('transform'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an URL, return the hostname it belongs to. This includes subdomain, but excludes www. Example: > drive.google.com When using the parseDomain function, returns only the domain, not the subdomain. This is better for determining thirdparty scripts and cookies, but is 3x slower.
function extractHostname(url){ var parsedDomain = parseDomain(url); if(parsedDomain === null){ return ''; } return parsedDomain.domain + '.' + parsedDomain.tld; /* var hostname = ''; // ../index is internal if (url.charAt(0) === '.') { return ''; } //find & rem...
[ "function domainName(url){\n let split1 = url.split('.')\n let split2 = []\n let domain = ''\n if(split1[0].includes('//')){\n split2 = split1[0].split('//')\n } \n \n if(split2.length === 0){\n split1.forEach((x,i)=>{\n if(x==='www'){\n domain = split1[i+1]\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select a buoy. We show the location and allow variables to be selected.
function selectBuoy() { // Reset all buttons. for (var i=0; i<buoys.markers.length; i++) { buoys.markers[i].icon.imageDiv.firstChild.setAttribute( 'src', 'js/OpenLayers/img/marker-blue.png'); } this.icon.imageDiv.firstChild.setAttribute('src', 'js/OpenLayers/img/marker.png'); ...
[ "select(location){\n\t\tthis._menu.select(location);\n\t}", "beautyselect(){\n cy.get('.border-left-0').click();\n cy.get('.dropdown-menu >').contains('Beauty').then(option => {\n cy.wrap(option).contains('Beauty');\n option[0].click();\n\n })\n \n }", "musicse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function retrieves from response article json the first image and resturns it, otherwise default image is returned.
function getArticleFirstImageFile(article) { if (article.article_representations.length > 0) { return article.article_representations[0].representation.image_file; } return DEFAULT_ARTICLE_IMAGE; }
[ "function extract_images_from(json_images) {\n Logger.log(json_images);\n Logger.log(\"json parsing after image API returns a response\");\n //var image_url = json_images.items[0].link;\n if (json_images.items != undefined) {\n var image_url = json_images.items[0].link;\n Logger.log(image_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In masterdetail grids, when checking or unchecking a checkbox in the parent table, this function checks or unchecks the checkboxes in the detail table
function SelectChildCheckBoxes(grid, senderId) { try { //Get the grid object var grid = window[grid]; var masterRowCounter = -1; //Get the sender checkbox var senderCheckBox = document.getElementById(senderId); if (senderCheckBox != null) { //I...
[ "function toggleMasterCheckBasedOnAllOtherCheckboxes() {\r\n // What we need to do here is check to see if every checkbox is checked.\r\n // If it is, the master checkbox in the header should be checked as well.\r\n var allCheckboxes = $('tbody input:checkbox', tableElement);\r\n var tot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get maximum fact (theoretical) value of sector square
function getMaxSectorSquare() { const sorted = [...portrait].sort((a, b) => (b.value - a.value)); return sorted[0].value; }
[ "function solarPersonalMax() {\n\n return (this[CONSTANT_TRAIT_ESSENCE] * 3) + this[CONSTANT_TRAIT_WILLPOWER];\n\n }", "get pmax() {\n var s, i\n s = 0\n for(i = 0; i < _cs.length; i++) {\n s += Math.abs(_cs[i])\n }\n return s\n }", "function highestCommonFactor() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
7. Write a function called `greaterThan` that takes two parameters and returns `true` if the second parameter is greater than the first. Otherwise the function should return `false`. A:
function greaterThan(x,y){ if (x < y) { return true } else { return false } }
[ "function greaterThan (a, b) {\n if (b > a) {\n return (true);\n} else{\n return (false);\n}\n}", "function greaterThan(a,b) \n{\n if (b > a) \n {\n return true; \n } else \n {\n return false; \n }\n}", "function greaterThan(a, b) {\nif (b > a) {\nreturn true;\n } else {\n return false;\n }\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check and return true if an object not undefined or null
function isPresent(obj) { return obj !== undefined && obj !== null; }
[ "function isPresent(obj) {\n return obj !== undefined && obj !== null;\n}", "function objectDefinedNotNull(obj) {\r\n return typeof obj !== \"undefined\" && obj !== null;\r\n}", "function is_undefined_or_null( object ) {\r\n\tif ( object === \"undefined\" ) {\r\n\t\treturn true;\r\n\t} else {\r\n\t\tretur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Guess. 5 points. Write a function that generates a random number, and asks the user to try to guess this number. When all is said and done, your function should output the random number and the number of attempts it took the user to correctly guess that number. Your function should also provided helpful hints, indicati...
function guess() { // WRITE YOUR EXERCISE 4 CODE HERE let number=Math.floor(Math.random()*999)+1; let attempts=0; let correct_answer = false; while (correct_answer==false) { let guess=prompt('enter your guess') if(guess>=1 && guess<=1000 && Number.isInteger(Number(guess))){ console.log("1"); ...
[ "function guess() {\n\n // WRITE YOUR EXERCISE 4 CODE HERE\nlet random = Math.floor(Math.random()*1000)+1;\nlet number = 0;\nlet guesses=0;\nlet output=\"\";\nlet p=document.getElementById(\"guess-output\");\nwhile(number!=random){\n if((number<1 || number>1000 || number%1!=0) && guesses>0){\n number=Number(pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prohibit introspection queries A GraphQL document is only valid if all fields selected are not fields that return an introspection type. Note: This rule is optional and is not part of the Validation section of the GraphQL Specification. This rule effectively disables introspection, which does not reflect best practices...
function NoSchemaIntrospectionCustomRule(context) { return { Field: function Field(node) { var type = Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_1__["getNamedType"])(context.getType()); if (type && Object(_type_introspection_mjs__WEBPACK_IMPORTED_MODULE_2__["isIntrospectionType"])(type)) { ...
[ "function NoSchemaIntrospectionCustomRule(context) {\n return {\n Field(node) {\n const type = Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_1__[\"getNamedType\"])(context.getType());\n\n if (type && Object(_type_introspection_mjs__WEBPACK_IMPORTED_MODULE_2__[\"isIntrospectionType\"])(type)) {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Squeezes trits given an offset and length
squeeze(trits, offset, length) { do { const limit = length < Curl.HASH_LENGTH ? length : Curl.HASH_LENGTH; trits.set(this._state.subarray(0, limit), offset); this.transform(); length -= Curl.HASH_LENGTH; offset += limit; } while (length ...
[ "squeeze(trits, offset, length) {\r\n do {\r\n const limit = length < Curl.HASH_LENGTH ? length : Curl.HASH_LENGTH;\r\n trits.set(this._state.subarray(0, limit), offset);\r\n Curl.transform(this._state, this._rounds);\r\n length -= Curl.HASH_LEN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Until webidl2js gains support for checking for Window, this would have to do.
function isWindow(val) { if (typeof val !== "object") { return false; } const wrapper = idlUtils.wrapperForImpl(val); if (typeof wrapper === "object") { return wrapper === wrapper._globalProxy; } // `val` may be either impl or wrapper currently, because webidl2js currently unwraps Window objects (a...
[ "function isWindow(val) {\n if (typeof val !== \"object\") {\n return false;\n }\n const wrapper = utils$7.wrapperForImpl(val);\n if (typeof wrapper === \"object\") {\n return wrapper === wrapper._globalProxy;\n }\n // `val` may be either impl or wrapper currently, because webidl2js curr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function parseXML: This function is called from index.html. It reads the XML file and adds the proper code to make it function correctly. This function will call the other functions to create the controller for the scrolling animations and the style sheet.
function parseXML(xml) { "use strict"; $("#loading").hide(); //hide the loading animation /*------------------------------------------------------------------------------------ HTML Head: Any content that is suitable for the head will be parsed in this section. This includes the t...
[ "function parseXML(xml) {\r\n\r\n \"use strict\";\r\n\t$(\"#loading\").hide();\t\t\t\t//hide the loading animation\r\n\t$(\"#loading-text\").hide();\t\t\t//hide the loading text\r\n /*------------------------------------------------------------------------------------\r\n HTML Head:\r\n \r\n Any cont...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
3 UZDUOTIS sukurti funkcija "printMetinisPajamuDydis()" , kuri atspausdina i konsole suma 12 atlyginimu (vienas atlyginimas yra lygus "uzduotis 1" kintamajam "atlyginimas")
function printMetinisPajamuDydis(){ let metinis = atlyginimas*12; console.log(metinis); }
[ "function printMetinisPajamuDydis() {\n //var x = 12;\n //var ats = atlyginimas * x;\n //console.log(\"metinis pajamu dydis: \", atlyginimas*x);\n // ARBA viena eilute surasome viska\n console.log(\"metinis pajamu dydis: \", atlyginimas * 12);\n}", "function printMetinisPajamuDydis() {\nvar metinesPajamos = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createItem(id,parentDiv,price): IN: id name of an item in the format of location of in json, Example: id = root(ELMNT_ID_SPACE_CHAR)parent(ELMNT_ID_SPACE_CHAR)child(ELMNT_ID_SPACE_CHAR)item (ELMNT_ID_SPACE_CHAR) is a GLOBAL VAR parentDiv the div ID where the new element being created should be nested price price of the...
function createItem(id,parentDiv,CustomStyle,price){ var nm = id.substring(id.lastIndexOf(ELMNT_ID_SPACE_CHAR)+1);//create var for elements name attribute var newItem = HTMLelement("p",{class:'item stockYES', id:id, value:price, name:nm, innerHTML:nm, CustomStyl...
[ "function createItemNode(dataType, itemData){\n // Create containe structure and information\n var divTag = document.createElement(\"div\");\n if (dataType == \"name\") {\n divTag.setAttribute(\"class\", \"prodName\");\n }\n else {\n divTag.setAttribute(\"class\", \"prodPrice\");\n }\n // Creating the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a provided WIF string to a public key string.
function convertWIFToPublicKey (wif, network) { if (!validateNetwork(network)) { throw new Error('Invalid network choice') } if (!validateWIF(wif)) { throw new Error('Invalid WIF key') } return new zcash.PrivateKey(wif, network).toPublicKey() }
[ "wif2pubkey( wif ){\n\n\t\tlet compressed = this.compressed;\n\t\tlet r = this.wif2privkey(wif);\n\t\tthis.compressed = r['compressed'];\n\t\tlet pubkey = this.newPubkey(r['privkey']);\n\t\tthis.compressed = compressed;\n\t\treturn {'pubkey':pubkey,'compressed':r['compressed']};\n\n\t}", "function privToPub(privW...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the crops argument into the beginning coordinates of a slice operation.
function getSliceBeginCoords(crops, blockShape) { var sliceBeginCoords = [0]; for (var i = 0; i < blockShape; ++i) { sliceBeginCoords.push(crops[i][0]); } return sliceBeginCoords; }
[ "function getSliceBeginCoords(crops, blockShape) {\n var sliceBeginCoords = [0];\n for (var i = 0; i < blockShape; ++i) {\n sliceBeginCoords.push(crops[i][0]);\n }\n return sliceBeginCoords;\n}", "function getSliceBeginCoords(crops, blockShape) {\n const sliceBeginCoords = [0];\n\n for (let i = 0; i < bl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In this kata you will create a function that takes in a list and returns a list with the reverse order. Examples reverseList([1,2,3,4]) == [4,3,2,1] reverseList([3,1,5,4]) == [4,5,1,3] My Answer using reverse
function reverseList(list) { return list.reverse() }
[ "function reverseList(list) {\r\n return list.reverse();\r\n}", "function reverseList(list) {\n return list.reverse();\n}", "function reverseList(list) {\n return list.reverse()\n}", "function reverseList(list) {\n return list.reverse();\n}", "function reverseList(list) {\n let myarrayRev=list.revers...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads all books and sets them to books
function loadBooks() { API.getBooks() .then(res => setBooks(res.data) ) .catch(err => console.log(err)); }
[ "function loadBooks() {\n API.getBooks()\n .then(res =>\n setSavedBooks(res.data)\n )\n .catch(err => console.log(err));\n }", "function loadBooks() {\n API.getBooks()\n .then((res) => setBooks(res.data))\n .catch((err) => cons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save todos to localStorage
saveTodos(todos) { localStorage.setItem('todos', JSON.stringify(todos)) }
[ "function saveTodo() {\n localStorage.setItem(\"todos\", JSON.stringify(todos));\n }", "function saveTodos() {\n localStorage.setItem(TODOS_LS, JSON.stringify(todos));\n}", "function saveToStorege() {\n localStorage.setItem('list_todos', JSON.stringify(todos))\n}", "function saveToDos()\n{\n localSto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper class, stores away tagged blockes removed from the text during working
function BlockSafe() { this.map = new Array(); this.takeOut = function(intext, tag, addClass) { var open = new RegExp("^(.*)<"+tag+"\\b([^>]*)>(.*)$", "i"); var close = new RegExp("^(.*)</"+tag+">(.*)$", "i"); var out = ''; var depth = 0; var scoop; var tagParams; var n = 0; v...
[ "function delete_tags(){\n var indices = word_selector.get_selected_indices();\n var region = sentence.get_region(indices);\n region.clear_tags();\n update_region_list();\n update_subregions();\n}", "function cleanContentBlockColor($range) {\n\tlet taggedArray = $($range + \" .tagged\");\n\tfor(let...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create replace pane instances.
createReplacePane(isRtl) { this.replaceDiv = createElement('div'); this.replaceTabContentDiv.appendChild(this.replaceDiv); this.replaceWith = createElement('input', { className: 'e-de-op-replacewith e-input', attrs: { placeholder: this.localeValue.getConstant('Replace wit...
[ "function createPane(e) {\n let newPane = createElement(\"div\", \"pane-item\", \"pane-\" + paneCount);\n\n let controls = createElement(\"div\", \"pane-controller-holder\");\n let controlsRight = createElement(\"div\");\n let controlsLeft = createElement(\"div\");\n\n // let backButton = createEleme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For any object with subtype 'mark', the width and height properties are set to the grid spacing value. If the object is a group, then make a recursive call to check for objects with subtype 'mark' and fix the height/width values.
function restoreSizeForMarkersWithinGroup(group) { var groupObjects = group.getObjects(); for (var i = 0; i < groupObjects.length; i++) { $log.debug('Type: ' + groupObjects[i].type + ', subtype: ' + groupObjects[i].subtype + ", id: " + groupObjects[i].id); if (gro...
[ "function restoreSizeForMarkersWithinGroup(group, restoreToWidth, restoreToHeight) {\n if (group.type === 'group') {\n var groupObjects = group.getObjects();\n for (var i = 0; i < groupObjects.length; i++) {\n $log.debug('Type: ' + groupObjects[i].type + '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return ALL moves from position
getMoves(pos){ let moves = []; const N = this.getUp(pos); const E = this.getRight(pos); const S = this.getDown(pos); const W = this.getLeft(pos); moves.push(N); moves.push(E); moves.push(S); moves.push(W); return moves; }
[ "get_moves() {\n let dir1 = ccw(this.dir);\n let dir2 = this.dir;\n let dir3 = cw(this.dir);\n let pos1 = get_next_position(this.pos, dir1);\n let pos2 = get_next_position(this.pos, dir2);\n let pos3 = get_next_position(this.pos, dir3);\n return [pos1, pos2, pos3];\n }", "all...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Algorithm that is searching for a hidden singles.
function bustHiddenSingles(arr) { let def = []; for (let y = 0; y < arr.length; y++) { // Moving between items and searching arrays. for (let x = 0; x < arr[y].length; x++) { if (typeof arr[y][x] === "object") { def = arr[y][x]; for (let m = 0; m < arr[y].length; m++) { // Sea...
[ "function aiSameDangerAndHiddenNear() {\n\tfor ( var i in grid ) {\n\t\tif ( grid[ i ].danger == grid[ i ].hiddenNear && grid[ i ].danger !== 0 ) {\n\t\t\t//console.log(\"Flagging all hidden: \", grid[i].x, grid[i].y, grid[i].danger, grid[i].hiddenNear);\n\t\t\tvar centerX = grid[ i ].x;\n\t\t\tvar centerY = grid[ ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private: Get output channel value from received message payload
function Ctr700_DO_GetChannelValue (vChannelValue_p) { // evaluate channel type and value from received message payload switch (typeof vChannelValue_p) { // -------- Boolean -------- case "boolean": { Trace...
[ "get outputChannel() {\r\n return this._OUTPUT_CHANNEL;\r\n }", "function caml_input_value (chanid) {\n var chan = caml_ml_channels[chanid];\n\n var buf = caml_create_bytes(8);\n chan.file.read(chan.offset,buf,0,8);\n\n // Header is 20 bytes\n var len = caml_marshal_data_size (buf, 0) + 20;\n\n va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
==================== Endo of product addition and updation checks ==================== Ajax function For populating catetories combobox
function ajaxCategoryAction(category) { //alert('hello'); var categoryId = category.value; //alert(categoryId); if(categoryId != document.getElementById("lastCatValue").value) { if(categoryId == "") { categoryId = 0; } else { document.getElementById("lastCatValue").value = categ...
[ "function loadDropDownAccessorySupplier(){\n \t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: getAbsolutePath() + \"accessorysupplier/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add new student to database
function addStud(student){ conn.query("INSERT INTO students (name, place, class, help) VALUES (?, ?, ?, ?)", [student.name, student.place, student.class, student.help], function(err, data){ if (err) throw err; }); }
[ "function addStudentInDatabase() {\n const roll = document.getElementById(\"add_roll\").value;\n const name = document.getElementById(\"add_name\").value;\n const department = document.getElementById(\"add_department\").value;\n const year = document.getElementById(\"add_year\").value;\n const semester = docum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CreateLocal regrava os dados em localstorage. Recebe um array de objetos /0 = clientes, 1 = profissionais, 2 = login, 3 = pontos gps
function createLocal(table){ setLocal(); console.log("table"); console.log(table); if (Array.isArray(table)) { if (table[0].tipo == 0) { localStorage.clientes = JSON.stringify(table); } else if (table[0].tipo == 1) { localStorage.profissionais = JSON.stringify(table); } } else if (table.tipo == 2...
[ "function setLocal() {\n localStorage.setItem('registroDePacientes', JSON.stringify(registroDePacientes))\n}", "function limparPedidos(){\r\n localStorage.setItem('PedidoCliente', JSON.stringify([]));\r\n}", "function agregarLocal(curso){\n //se obtiene la infomque hay en el local\n let local = infoLo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolve Transifex config. Will overwrite the provided 'currentData' with options defined in the task config
function resolveConfig(currentData, options) { var data = _.merge({}, currentData , options); var optionsKeys = flattenKeys(data); /* The expected keys that should be present in the config file or in the command line args */ var requiredKeys = ["transifex.api", "transifex.auth.user", "...
[ "async function currentConfig() {\n let config = Config.default();\n config.resolver = new Resolver(config);\n config.artifactor = new Artifactor();\n config.paths = await contractPaths(config);\n config.base_path = config.contracts_directory;\n return config;\n}", "getAndSetCurrentTaskData() {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
raw display of a externalized term
function showTerm_extern(O) { return JSON.stringify(O) }
[ "function TermDisplay(term) {\n return StaticDataService.ParseTerm(term);\n }", "lldisplayWordDefinition() {\r\n console.log(`\\nDefinition: ${this.definition}`);\r\n }", "function getFinalTerm(card){\n return card.displayTerm + \" (\" + card.definition.toString() + \")\";\n}", "f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the rights for categories
function setCategoryRights(){ var catRights = allEnabled(); //set the Admin rights setRight(catRights,'Admin','New Meeting',false); setRight(catRights,'Admin','Hide',false); //set the viewer rights setFalse(catRights[1]); //all viewer rights false setRight(catRigh...
[ "function setRight(accessRights,role,action,enabled){\n var roleIdx = wordLookup(role,$.roles);\n var actionIdx = wordLookup(action,$.allActions);\n accessRights[roleIdx][actionIdx].enabled = enabled;\n }", "assignRights () {\n const rights = Array.from(arguments)\n const resource = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all objects from the scene.
function clearScene() { for (var i = scene.children.length - 1; i >= 0; --i) { var obj = scene.children[i]; scene.remove(obj); } }
[ "function clearScene() {\r\n for( var i = scene.children.length - 1; i >= 0; i--) { \r\n obj = scene.children[i];\r\n scene.remove(obj); \r\n }\r\n}", "removeSceneObjects() {\n for (let i = 0; i < this.displayObjects.length; i++) {\n this.scene.remove(this.displayObjects[i]);\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sell/ arrival by sell: /products?sortBy=sold&order=desc&limit=4 by arrival: /products?sortBy=createdAt&order=desc&limit=4 if no params are sent, then reponse with all products
function listAllProducts(req, res) { let sortBy = (req.query.sortBy ? req.query.sortBy : "sold"); let order = req.query.order ? req.query.order : "desc"; // let limit = req.query.limit ? parseInt(req.query.limit) : 6; const { page, limit } = req.body; const limit = limit || 6; const skip = page || 1; co...
[ "static async getOrderItems (req, res, next) {\n const { seller_id } = req.user\n\n const page = parseInt(req.query.page) || 1\n const limit = parseInt(req.query.limit) || 2\n const offset = parseInt(page - 1, 10) * limit\n\n const sort = { price: 1 }\n\n try {\n const results = await OlistRe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
select new item and focus the list
function SelectItemAt(index, focus) { list.ensureIndexIsVisible(index); list.selectedIndex = index; if (focus) list.focus(); }
[ "_focus(item) {\n this.$.listBox._focus(item);\n }", "selectFocused(){this._tabs[this._focusIndex].selectItem()}", "selectFocused() {\n this._tabs[this._focusIndex].selectItem();\n }", "jumptoSelected(andfocus) {\n let sel = this.optionlist.querySelector('li[aria-selected=\"true\"]');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets all available timeslots for next two weeks
function calculateTimeslots(d) { var list = []; var olist = []; var name = ""; var tempDate; d = new Date(d.setDate(d.getDate() - d.getDay() +1)); //get date for Monday this week //set Monday (2 slots) d.setHours(9); d.setMinutes(0); d.setSeconds(0); tempDate = d.toISOString(); //9am slot list.push(te...
[ "function getAvailableTimes(formInput, listOfBusyTimes) {\n\n console.log(listOfBusyTimes);\n\n var today = new Date(formInput.startDate);\n var tomorrow = new Date(formInput.endDate);\n tomorrow.setDate(tomorrow.getDate() + 1);\n\n var timeslots = createIntervals(today, tomorrow, formInput.length);\n\n //for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to add reservations to the table. Also; in case of no reservations, display the noreservationbanner, else hide it.
function addReservationToTable(reservations) { reservations.forEach((reserve) => { let row = document.createElement('tr'); let nDate = new Date(reserve.date); //reserve.date is in string format,so convert it to date format. let bookedDate = nDate.toLocaleDateString('en-IN'); l...
[ "function addReservationToTable(reservations) {\n // TODO: MODULE_RESERVATIONS\n // 1. Add the Reservations to the HTML DOM so that they show up in the table\n\n //Conditionally render the no-reservation-banner and reservation-table-parent\n if (reservations.length==0){\n var table = document.getElementById(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a promise which resolves to an Array of ProfileBOs. Returns all profiles.
getAllProfiles() { return this.#fetchAdvanced(this.#getAllProfilesURL()).then((responseJSON) => { let profileBOs = ProfileBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(profileBOs); }) }) }
[ "async function getAllProfiles() {\n const response = await fetch(`/profiles`);\n if(response.ok){\n const profiles = await response.json();\n return profiles.map( (p) => Profile.from(p) );\n } else\n throw `ERROR fetching /profiles`;\n}", "matchProfiles() {\n return this.#fetchAd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
logInfo(agentId, whoami, requestIp, dateNow, agentDir+"/cfg");
function logInfo(agentId, whoami, ip, date, ipLogFileAddress) { // .................................................................. log the information ............... if (agentId === undefined || whoami === undefined || ip === undefined || date === undefined || ipLogFileAddress === undefined) { return; } //cons...
[ "function serverLog(path, ip)\n{\n // Constructing the activity message\n msg = date + ':' + path + ' was accessed by ' + ip + '\\n';\n\n // Save the activity in the logs\n saveLog(msg);\n}", "function log(statCode, url, ip, err) {\n var logStr = statCode + ' - ' + url + ' - ' + ip;\n if (err) logSt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace generated values in regexes and strings of an expected report: CHANNEL_NAME: the channel name is generated from the test parameters.
function replaceValuesInExpectedReport(expectedReport, channelName) { if (expectedReport.report.body !== undefined) { if (expectedReport.report.body["document-uri"] !== undefined) { expectedReport.report.body["document-uri"] = replaceFromRegexOrString( expectedReport.report.body["document-uri"], "...
[ "static _replacePatterns(input){\n patterns.forEach(([pattern, fixValue]) => {\n input = input.replace(pattern, fixValue)\n })\n return input\n }", "_testAndReplaceUrl(config, url) {\n let rawRegexp = config.regexp;\n let regexp = new RegExp(rawRegexp, 'i');\n\n if(regexp.test(url)) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subscribe to the chart events (contained in 'dispatch') and pass eventHandler functions in the 'options' parameter
function configureEvents(dispatch, options){ if (dispatch && options){ angular.forEach(dispatch, function(value, key){ if (options[key] === undefined || options[key] === null){ if (scope._config.exten...
[ "function configureEvents(dispatch, options){\n if (dispatch){\n angular.forEach(dispatch, function(value, key){\n (options[key] === undefined || options[key] === null)\n ? options[key] = value.on\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create menu using structure: array( 'a' => array( 'items' => array( 'a' => array( 'items' => array( 'a' => array( 'params' => array(), 'items' => array() ), 'b' => array( 'params' => array(), 'items' => array() ) ) ), 'b' => array( 'items' => array( 'a' => array( 'params' => array(), 'items' => array() ), 'b' => array(...
function createMenuTree(ul, items) { $.each(items, function(name, item) { var innerUl = null; if (objectSize(item.items) > 0) { innerUl = $('<ul>'); createMenuTree(innerUl, item.items); } var li = createMenuItem(name, null, innerUl); if (objectSize(item.params) > 0) { $.each(item.params...
[ "function buildMainMenu(menuHtml, menuItems) {\n //for each menu item on this menu level\n for (var j = 0; j < menuItems.length; j++) {\n //create a new <li> tag\n var menuLink;\n if (menuItems[j].children.length < 1) {\n menuLink = $('<li><a href=\"'+menuItems[j].path+'\">'+menuItems[j].title+'</a>...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
multiply a quantity (with unit)
function multiply(quatity, times) { var _ref = /(-?\d+(?:\.\d+)?)(.*)/.exec(quatity) || [], _ref2 = _slicedToArray(_ref, 3), num = _ref2[1], unit = _ref2[2]; var timedNum = parseFloat(num) * times; return "".concat(timedNum).concat(unit); }
[ "function multiply() {\r\n\tsave.number = Decimal.times(save.number, save.multiplier1);\r\n}", "function multiply (quatity, times) {\n var ref = /(-?\\d+(?:\\.\\d+)?)(.*)/.exec(quatity) || [];\n var num = ref[1];\n var unit = ref[2];\n var timedNum = parseFloat(num) * times;\n return (\"\" + timedNum + unit)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a loading spinner to the top right of the map
function addLoadingControl() { var loadingControl = L.Control.loading({ separate: true, position: "topright" }); mapImpl.addControl(loadingControl); }
[ "function startTreemapLoading() {\n // Hide the containers.\n if (!isToolbarHidden) {\n $('#toolbar').hide();\n }\n $('#main').hide();\n\n // Update the loading message.\n var formattedName = treemapName;\n if (treemapName !== '') {\n formattedName = \"'\" + treemapName + \"'\";\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the difference of two number values in desired units converted from seconds
function secondDiff(time1,time2,unit,returnSigned) { sec = time2-time1; if (!returnSigned) sec = Math.abs(sec); // Return in specified units if (unit == "s") { return sec; } else if (unit == "m") { return sec/60; } else if (unit == "h") { return sec/3600; } else if (unit == "d") { return se...
[ "seconds(prevTime, curTime){\n let time = curTime - prevTime;\n let seconds = time/1000;\n return seconds.toFixed(2);\n}", "function diffByUnit(a, b, unit) {\r\n return moment.duration(Math.round(a.diff(b, unit, true)), // returnFloat=true\r\n unit);\r\n}", "function getSecondsDifference(start, e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
outputs the word in " _ _ a _ " format. this is all the client gets to see, to prevent cheating.
displayWord(word,letters){ let dWord = ''; for(let i=0; i< word.length; i++){ if (letters.indexOf(word[i]) === -1) { dWord = dWord + '_'; } else { dWord = dWord + '' + word[i]; } } return dWord; }
[ "function printWord()\n{\n // word is initially blank and is populated with letter or underscores and spaces\n var word = '';\n for(var i = 0; i < game.word.length; i++)\n {\n var letter = game.letterArray[i];\n // if letter is not a space, call letters display function which returns the l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Get Betting Events by Season / / Year of the season Examples: 2020, 2021, etc.
getBettingEventsBySeasonPromise(season){ var parameters = {}; parameters['season']=season; return this.GetPromise('/v3/nfl/odds/{format}/BettingEvents/{season}', parameters); }
[ "function getDriversBySeason(request, response){\n\tvar season = request.query.season;\n\tif(season){\n\t\tvar query = \"SELECT drivers.*, races.year, count(CASE WHEN position=1 THEN 1 END)::int as wins \"+\n\t\t\"FROM drivers \"+\n\t\t\"INNER JOIN results USING(driver_id) \"+\n\t\t\"LEFT JOIN races USING(race_id) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encapsulates an animation style. Instantiated and returned by the `style()` function.
function AnimationStyleMetadata() { }
[ "_getAnimationStyle(styles, state, animation) {\n if (this.getTweeningValue && this.getTweeningValue('step'))\n state.step = this.getTweeningValue('step');\n\n invariant(defined(state.step), 'Must define step for animation to run');\n invariant(defined(state.index), 'Must define index for animation to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A filter function for hostname and IP (v4 & v6) address
function hostNameIpFilter(field) { filterUsingFn(field, isHostNameIpUnsafe); }
[ "function filter_ipv6_addr(data)\n{\n\tvar v6_ip = data;\n\tvar v6_ip_s = data.split(':');\n\tvar tmp_ip ='';\n\tvar tmp_ip_1 ='';\n\tvar tmp_ip_2 ='';\n\tvar isabridge = data.split('::');\n\n\tif (isabridge.length == 2)\n\t\treturn v6_ip;\n\n\tfor (var i = 0; i <8; i++)\n\t{\n\t\tif (v6_ip_s[i] == 0)\n\t\t{\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new building based on an inputted name, of level one to the list
function addBuilding(buildingName) { let typeID; let buildingID; $.ajax('/building/byBuildingName/' + buildingName) .done((res) => { typeID = res[0].typeID; $.ajax('/building/byBuildingType/' + typeID) .done((res) => { buildingID = res[0].buildingID; let payload = { buildingID: buildingID,...
[ "addBuildingPartToBuildingPart (ID, name, type, defaultLine) {\n // Get the correct push-target\n let target\n\n if (type === 'Building') {\n target = this.project.buildings\n } else {\n target = this.getCurrentBuildingPart(true)\n }\n\n // Get the buildingParts array of the current buil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function displayes the current playerlist, also the color that has been assigned to the player, the controlkeys and a deletebutton, but if the playertable is empty it calls the "hideTableIfEmpty"function to hide table
function displayData() { var temp = document.getElementById("player-table"); temp.hidden = false; var table = document.getElementById("player-table"); var i = 1; while (table.rows.length > 1) { table.deleteRow(i); } i = 1; players.forEach(function (entry) { var row = tabl...
[ "function loadTable(){\n document.getElementById('add-player').style.display = 'none'\n document.getElementById('edit-players').style.display = 'block'\n}", "function displayPlayer(player){\r\n\tif(player.getLastPosition() !== 0){\r\n\t\t$(`#cell-${player.lastPosition[0]}-${player.lastPosition[1]}`).removeC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to create a PuzPayload from a PUZAPP
function puzapp_to_puzpayload(puzdata) { var meta = { title: puzdata.title, author: puzdata.author, copyright: puzdata.copyright, note: puzdata.notes, width: puzdata.width, height: puzdata.height, } var pp_clues = []; // Sort the entries by number then dir...
[ "function prepareProdpadPayload() {\n prodpadPostIdeaPayload.description = prodpadDescription;\n prodpadPostIdeaPayload.title = prodpadTitle;\n prodpadPostIdeaPayload.business_case.problem = prodpadProblem;\n prodpadPostIdeaPayload.business_case.value = prodpadValue;\n}", "function createSigningPayloa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the dialog by mouse cursor
function moveDialog(event) { if (container.el) { container.el.style.left = Math.min( Math.max(container.elStartX + event.clientX - container.mouseStartX, offWindow ? (border - container.el.getBoundingClientRect().width) : 0), window.innerWidth - (offWindow ? border : container.el.getBoundingClientRect...
[ "function moveDialog(event) {\n if (container.el) {\n container.el.style.left = Math.min(\n Math.max(container.elStartX + event.clientX - container.mouseStartX, 0),\n window.innerWidth - container.el.getBoundingClientRect().width\n ) + 'px';\n\n container.el.style.top =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function called if isolation is clicked, if isolation is active and state = ready allow go to run
function enableRunState() { if ($scope.actualState == 'RDY' && neumaticaRB.checked) { $scope.isTestOrReadyDisabled = false; } else { $scope.isTestOrReadyDisabled = true; } }
[ "function Start_button()\n{ \n Delay(2000);\n \n Split_button();\n \n Aliases.browser.pageSapiensDecision.FindElement(\"//*[(text()='Start')]\").Click();\n \n //Verify that Button should become disabled\n// aqObject.CheckProperty(Aliases.browser.pageSapiensDecision.FindElement(\"//p-splitbutton/div\"), \"c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get every case with a certain status_id Status number range is 1 4.
getCaseOnStatus(status_id: number): Promise <Case[]>{ return axios.get(url+'/allCases/status/'+status_id); }
[ "async function GetAllStatusDistinct() {\n try {\n let table = await controller.GetTable(\"PullRequests\" , {}, 'PR_Number' , 1);\n let results = [];\n await table.forEach(doc => {\n results.push(doc.Status);\n });\n return results.filter((item, i, ar) => ar.indexOf(item) === i);\n } catch (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increments state.counter and loads next 5 items when right button clicked
nextFive() { let nextCounter = 0; if (!(this.state.counter+5 >= this.state.productsNumber)) { nextCounter = this.state.counter+5; } this.setState({counter: nextCounter}, () => {this.getFive()}); }
[ "changeCarouselRight() {\n\n // fetches more data from actions\n if(this.state.index >= this.state.listings.length - 4) {\n this.props.fetchData();\n }\n \n // used to change the index where the display starts from\n this.setState({\n ...this.state,\n index: this.state.index + 4 >= ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }