query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
This buy function is for the purchase of armor ONLY This is ran from the checkBuy() function and the user pays the money and collects the item
function buyItem() { addArmor(); $('#alerts').append("<br />An item has being bought<br />"); removeMoneyI(); }
[ "function buyItem(){\n\tvar buyNum = buy_arr[buyItems].id;\n\tvar targetIcon = $.iconObj[items_arr[buyNum].name];\n\ttargetIcon.purchased = true;\n\tbuy_arr[buyItems].purchased = true;\n\tplaySound('soundBuy');\n\t\n\tpukiXPEarn -= items_arr[buyNum].xpBuy;\n\tconText.text = textCollection.replace('[XP]',user_data.x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add HD or MP4 when mouseover each video title links in YouTube List Page
function visualize() { var titles = d.getElementsByTagName('div'); var temp = document.createElement("div"); var style = "padding:1px;background:#f00;color:#fff;"; var videolink = s ? 'video-mini-title' : 'video-title'; for ( var i=0, l=titles.length; i<l; i++ ) { (function(){ var t ...
[ "function youtubelist(data){\n for(var i=0;i<data.length;i++){\n html+=\"<a href=\\\"\" + data[i].url + \"\\\">\" + data[i].title +\"</a>\"; \n }\n $(\".right_box.movie\").html(html);\n }", "function changeYtVidTitle(str) {\r\n if (typeof str !== 'undefine...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
refreshes losses count in html
function refreshLosses() { $("#losses").text("Losses: " + losses) }
[ "function updateLosses() {\n losses += 1;\n lossesDOM.innerHTML = losses;\n }", "function lossCounter(){\n losses++;\n $(\"#numberLosses\").text(losses);\n reset();\n }", "function lossUpdate () {\n losses ++;\n //change the value on the html\n $(\"#...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
launches submission form page into its own window instead of as a tab in the current window
function SubmissionForm() { var urlLink = "https://docs.google.com/a/noaa.gov/spreadsheet/viewform?usp=drive_web&formkey=dHAycC1MYndJb0hTdGRaYXAzVTVBdWc6MA#gid=0"; var Win = open(urlLink, "SubmissionFormPage","height=800,width=1000,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes"); W...
[ "function OpenWinSubmitForm\t(URL, action, nextPage, target, args, winObject) \n{\n\tmyWinID = OpenWin (URL, target, winObject);\n\tSubmitForm (action, nextPage, target, args);\n\treturn myWinID;\t\n}", "function submitCurrentTab() {\n\tchrome.windows.getCurrent(function(win){\n\t\tchrome.tabs.getSelected(win.id,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update the side bar of code list, added drugs, and removed codes
function updateCodeList() { let added_tags = ''; let remove_tags = ''; Object.keys(selectedCode).forEach((key, idx) => { if (selectedCode[key] == 0) { let visit = key.split('-')[0]; let code = key.split('-')[1]; let name = ptTestData[2][code]; remove_t...
[ "function updateSideBar(){\r\n count = 1;\r\n //update playlist titles\r\n for(i = playListStack.length; i > 0; i--){\r\n $(\"#playlist\"+count).text(playListStack[i-1].name);\r\n Playtrack = playListStack[i-1].url;\r\n Playtitle =playListStack[i-1].name;\r\n $(\"#playlist\"+count).data({ url...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Step 2: Run function freezeHeader to freeze the header row, unfreeze all other rows/columns manually
function freezeHeader() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; sheet.setFrozenRows(1) }
[ "function unfreezeHeader () {\r\n\tvar header = $('.ui-jqgrid-htable thead')\r\n\t$('.jqgfirstrow').height(0);\r\n\theader.css('max-width', '');\r\n\theader.css('position','relative');\r\n}", "function freezeTableHeader() {\n $('table#planning').floatThead({\n position: 'fixed',\n autoReflow: 'tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function converts the current Div Location in order to display a proper header INNER FUNCTION CALLS: none
function convertCurrentDivLocation(currentDivLocation) { console.log('CURRENT DIV: ', currentDivLocation); switch (currentDivLocation) { case 'projectManager': $('#' + currentDivLocation) .find('#pageLocation') .html("<p>Project Manager <small id='projectHeader'>---</small></p>"); br...
[ "function convertCurrentDivLocation (currentDivLocation){\n\tconsole.log(\"CURRENT DIV: \", currentDivLocation);\n\tswitch(currentDivLocation) {\n\t\tcase \"projectManager\":\n\t\t\t$('#'+currentDivLocation).find(\"#pageLocation\").html(\"<p>Project Manager <small id='projectHeader'>---</small></p>\");\n\t\t\tbreak...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Private helpers: Takes the given callerprovided properties, selects only known ones, validates them, and returns the known subset. By default, only validates properties that are present. (This allows `User.prototype.patch` to not require any.) You can pass `true` for `required` to validate that all required properties ...
function validate(props, required) { var safeProps = {}; for (var prop in User.VALIDATION_INFO) { var val = props[prop]; validateProp(prop, val, required); safeProps[prop] = val; } return safeProps; }
[ "function CfnUserPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this is the real operational function to update the highlighted features
function _updateFeatures() { // this function hides those layers that aren't on the current level _updateLayers(); removeHighlightPolygons(); // this for loop goes through every highlight definition. // if there are features to be shown on the current level, show them; else, don't. ...
[ "function _updateFeatures() {\n // this function hides those layers that aren't on the current level\n _updateLayers();\n\n removeHighlightPolygons();\n\n // this for loop goes through every highlight definition.\n // if there are features to be shown on the cu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an interval for snapping together coordinates that be coincident bug have diverged because of floating point rounding errors. Intended to be small enought not not to snap points that should be distinct. This is not a robust method... e.g. some formulas for some inputs may produce errors that are larger than thi...
function getHighPrecisionSnapInterval(coords) { var maxCoord = Math.max.apply(null, coords.map(Math.abs)); return maxCoord * 1e-14; }
[ "static roundToNearestInterval(value, interval) {\n return Math.round(value / interval) * interval;\n }", "snapTo(x) {\r\n return this.map(p => {\r\n return (Math.abs(p - x) <= Sylvester.precision) ? x : p;\r\n });\r\n }", "function snapCritical() {\r\n function fuzzyEquals(a, b) { return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes phiC using the curing level
function CSIRO_phiC(C) { return ((1.12)/(1+59.2*Math.exp(-0.124*(C-50)))); }
[ "function phi([n00, n01, n10, n11]){\r\n return (n11 * n00 - n10 * n01)/\r\n Math.sqrt((n10 + n11)*\r\n (n00 + n01)*\r\n (n01 + n11)*\r\n (n00 + n10));\r\n }", "function phi([n00, n01, n10, n11]){\n return (n11 * n00 - n10 * n01)/Math.sqrt((n11+n0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
5) Arrays appendKitten(name) appends a kitten to the kittens array and returns a new array, leaving the kittens array unchanged:
function appendKitten(name){ var newArray = [...kittens, name]; return newArray; }
[ "function appendKitten(newKitten) {\n return kittens.concat(newKitten);\n}", "function appendKitten(name) {\n \n return kittens.concat(name);\n \n}", "function appendKitten(){\n return [...kittens, 'Broom'];\n}", "function destruvielyAppendKitten(name) {\n return kittens.push(name)\n}", "function prep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find RMS of signal
RMS(buffer) { var total = 0; for (var i = 0, n = buffer.length; i < n; i++) { total += buffer[i] * buffer[i]; } return Math.sqrt(total / n); }
[ "function pcmGetRms(src) {\r\n var numSamples = src.length;\r\n var rms = 0;\r\n for (var i = 0; i < numSamples; i++) {\r\n rms += Math.pow(src[i], 2);\r\n }\r\n return Math.sqrt(rms / numSamples);\r\n }", "function pcmGetRms(src) {\r\n const numSamples = src.le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method that calculates the IMC
calcularIMC() { const peso = this.peso; const altura = this.altura; return (peso / altura * altura) }
[ "calculateIMC(){\n\t let imc = this.weight /(this.height^2);\n\t\n\t return this._getIMCDiagnostic(imc);\n }", "get imc() {\n const IMC = this.peso / (this.altura ** 2);\n return IMC.toFixed(2);\n }", "calcMvalues() {\n var _this = this;\n var data = this.data;\n\n if (_thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an instance of LimitdServer. Options: `db` the path to the database. Required. `port` the port to listen to. Defaults to 9231. `hostname` the hostname to bind to. Defaults to INADDR_ANY `log_level` the verbosity of the logs. Defaults to 'info'. `metrics_api_key`, the DataDog api key to log metrics to. Defaults ...
function LimitdServer (options) { EventEmitter.call(this); var self = this; if (!options.db) { throw new TypeError('"db" is required'); } this._config = _.extend({}, defaults, options); var configError = validateConfig(this._config); if (configError) { throw new Error(configError); } this....
[ "function DebugAdapterServer(port, host) {\n this.port = port;\n this.host = host;\n }", "start (port) {\n // Listen for and handle incoming HTTP requests\n this.server.on('request', (request, response) => {\n const res = new Response(response)\n this.handleRequest(request, res)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that finds the move numbers of a jump move being made that uses recursive code to calculate multiple jumps in one turn and return a move string that represents it.
function findJumpMove(source, destination, index, position) { // index between 2 - 34 but subtract 2 for math calculations var topLeftOffset = ((Math.floor((index - 2) / 4) + 1) % 2) + 4; var topRightOffset = ((Math.floor((index - 2) / 4) + 1) % 2) + 3; var bottomLeftOffset = (Math.floor((index - 2) / 4) % 2) +...
[ "function knightjumps(str) {\n const knight = [parseInt(str[1]), parseInt(str[3])] //get number values for knight's position\n //create a nested array of possible moves ([x, y])\n const moves = [\n [-1, 2], [1, 2],\n [-2, 1], [2, 1],\n [-2, -1], [2, -1],\n [-1, -2], [1, -2]\n ]\n //reduce moves, ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
line 4097, (corelib), module JSON
function JSON() {}
[ "function Json () {}", "function JSJaCJSON() {}", "function JSONType() {}", "function createJSONObj() {\n if (typeof JSON == 'undefined') {\n\twtolog('Browser lacks native JSON, fixing...');\n\tJSON = {'parse': function(data) { return json_parse(data); }}\n }\n}", "function JsonExtension() {}", "fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
actively close the session
end() { this.session.close(); }
[ "function close_session() {\n check_init();\n\n if (session.id) {\n assistant.deleteSession({\n assistant_id: CREDENTIALS.assistantId,\n session_id: session.id,\n }, \n function(err, response) {\n if (!handle_error(err)) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function Populates the Autocomplete ul with relevant User's Info
function autoCompleteShowData(input) { let allUsers = Object.keys(Users); autocomplete.innerHTML = ""; //Check for Usernames that contain the input text if (input.length > 0) { for (let user in allUsers) { if (allUsers[user].includes(input)) { ...
[ "function initMembersAutoComplete() {\n users = {}, newObj = {}\n console.log('autocomplete');\n $.ajax({\n method: 'GET',\n url: serverURL + '/users',\n headers: {\n token: localStorage.getItem('todo_token')\n }\n })\n .done(function(data) {\n let kvp = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decrypts signed string into an object. Verifies that signature is valid.
function verifyAndDecrypt(s, secret_key) { var ss = s.split(':'); if (ss.length !== 2) { throw new Error('invalid token'); } var signature = ss[0]; var encoded = ss[1]; if( signature !== crypto.createHmac('sha1', secret_key).update(encoded).digest('hex') ) { throw new Error('invalid token'); } var cip...
[ "decrypt(str, settings){}", "decrypt(str, key, step) {\n\tvar str_fact = this.knows(str);\n\tvar key_fact = this.knows(key);\n\n\tif (! str.isEncrypted()) {\n\t throw 'Agent: ' + this.id + ' is trying to decrypt non encrypted message: ' + str;\n\t}\n\t\n\tif (str_fact != null) {\n\t if (key_fact != null) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hide scroll buttons if siblings don't have overflow.
function displayScrollButtons() { $('.btn-scroll').each(function() { const target = $($(this).data('target'))[0]; if (target.offsetWidth < target.scrollWidth) { $(this).css('visibility', 'visible'); } else { $(this).css('visibility', 'hidden'); } }); }
[ "function displayScrollButtons() {\n $('.btn-scroll').each(function() {\n var target = $($(this).data('target'))[0];\n if (target.offsetWidth < target.scrollWidth) {\n $(this).css('visibility', 'visible');\n } else {\n $(this).css('visibility', 'hidden');\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
["Elie", "Tim", "Matt"] / filter Q1 Write a function called filterLetters which accepts an array of letters and returns the number of occurrences of a specific letter. This function should be case insensitive
function filterLetters(array, letter) { return array.filter(function(value) { return value.toLowerCase() === letter.toLowerCase(); }).length; }
[ "function filterLetters(arr, letter) {\n return arr.filter(function(val){\n return val.toLowerCase() === letter.toLowerCase();\n }).length;\n}", "function filterLetters (arr, letter) {\r\n//my own way \r\n var count = 0;\r\n for (var i=0;i<arr.length; i++){\r\n if (arr[i].toLowerCase() === let...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if attribute with given selector NOT contain expected word
function expectNoAttributeValue(selector, attributeName, value) { let attributeValue = null; tryBlock(() => browser.waitUntil(() => { attributeValue = getAttribute(selector, attributeName); return !isContainWord(attributeValue, value); }), `Incorrect attribute '${attribut...
[ "function expectNoAttributeValue(selector, attributeName, value) {\n let attributeValue;\n Reporter_1.Reporter.debug(`Validate element '${selector}' doesn't have attribute '${attributeName}' which contains '${value}'`);\n tryBlock(() => browser.waitUntil(() => {\n attributeValue = ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Polls server for list of active games to render in Lobby activeGames :: (jwt: string) > game[]
function activeGames(jwt) { const activeGamesURL = BASE_URL + '/game/active_games' return httpRequestJWT(activeGamesURL, 'get', jwt) }
[ "getCurrentGames() {\n\n // TODO: AXIOS Requeset to get information about active games for this user\n\n let activeGamesList = [];\n\n let numGames = 0;\n\n // Axios request\n // Iterating on games\n\n if (numGames === 0) {\n // No past games :(\n acti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1. Fetch GitHub info for user "FerdinandObermeier" 2. After obtaining the data and the url to fetch users repos, fetch all public repos of the respective user 3. Set the repo data to two different state variables. One will act as a default to refer to when searching. The other one acts as actively displayed list of rep...
getUsersGitHub() { fetch('https://api.github.com/users/FerdinandObermeier') .then(res => res.json().then(data => { this.setState({gitHubUser: data}); fetch(this.state.gitHubUser.repos_url).then(res => res.json().then(data => { this.setState({userReposDefault: data, use...
[ "function getRepositories() {\n const username = document.getElementById(\"username\").value;\n const req = new XMLHttpRequest();\n req.addEventListener('load', displayRepositories);\n req.open(\"GET\", `https://api.github.com/users/${username}/repos`);\n req.send();\n }", "async function getRepos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new SummaryRdfView
function SummaryRdfView(settings) { if (!(this instanceof SummaryRdfView)) return new SummaryRdfView(settings); RdfView.call(this, 'Summary', settings); }
[ "function createMeasuresSummaryTable(view, index){\n\n // get fields\n var fields = view.tableGroups[index].fields;\n \n // get HTML table\n var summaryTable = $('measuresSummary');\n tBody = summaryTable.tBodies[0];\n \n // if fields were defined\n if (fields != undefined) {\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add new video to model
add(videoId) { this.videos.push({ url: `http://www.youtube.com/embed/${videoId}?autoplay=1` , videoId: videoId , id: uuid.v4() }); this.emit('change'); }
[ "add(video) {\n this.videos.add(video);\n }", "async videoAdd(request, response) {\n try {\n const { title, url, favorite } = request.body;\n const newVideo = mongoose.model('video')\n\n await new newVideo({\n title,\n url,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Possible improvements: Use hysteresis to include weak edges that are attached to strong edges Replace Gaussian filter with an adaptive filter to prevent smoothing out edgesToImage img has shape [W, H, 3]
function cannyEdgeDetector(img) { // First, blur image with 5x5 Gaussian kernel to remove noise const blurKernel = tf.tensor([ [2, 4, 5, 4, 2], [4, 9, 12, 9, 4], [5, 12, 15, 12, 5], [2, 4, 5, 4, 2], [4, 9, 12, 9, 4] ]).div(159); let blurred = convolve(img, blurKernel) // Calculate gradient along each di...
[ "function edge( __src ) {\n var gx = grayscale( filter(__src, new Filter.hsobel()) );\n var gy = grayscale( filter(__src, new Filter.vsobel()) );\n\n // sqrt(gx^2 + gy^2)\n var h = gx.h,\n w = gx.w;\n var g = new RGBAImage(w, h);\n var data = g.data,\n data1 = gx.data,\n data2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Asynchronously calculates the ID (key) in the routing_table parameter that is closest to "target".
function route(target, id, routing_table, cb) { cb(Object.keys(routing_table).reduce(function(acc, id) { return Math.abs(id - target) < Math.abs(acc - target) ? id : acc; }, id)); }
[ "static getTargetId(url, target) {\n const splitter = target + \"s\";\n let url_part = url.split(splitter).pop();\n if (target === \"restaurant\") {\n url_part = url_part.split(\"/?is_favorite\")[0];\n return Promise.resolve(url_part.substring(1));\n } else {\n if (url_part) {\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a graph that can be used to sort a layer of nodes. The graph will contain all base and subgraph nodes from the request layer in their original hierarchy and any edges that are incident on these nodes and are of the type requested by the "relationship" parameter. Nodes from the requested rank that do not have...
function buildLayerGraph(g, rank, relationship) { var root = createRootNode(g), result = new Graph({ compound: true }).setGraph({ root: root }).setDefaultNodeLabel(function (v) { return g.node(v); }); _.forEach(g.nodes(), functi...
[ "function buildLayerGraph(g, rank, relationship) {\n\t var root = createRootNode(g),\n\t result = new Graph({ compound: true }).setGraph({ root: root })\n\t .setDefaultNodeLabel(function(v) { return g.node(v); });\n\n\t _.forEach(g.nodes(), function(v) {\n\t var node = g.node(v),\n\t parent = g.pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called upon a ping.
onping() { this.emitReserved("ping"); }
[ "onping() {\r\n this.emitReserved(\"ping\");\r\n }", "onping() {\n this.emitReserved(\"ping\");\n }", "onping() {\n\t super.emit(\"ping\");\n\t }", "function pingHandler () {\n send.call(this, 'ping');\n}", "_onPing () {\n // log( 'Event: ping' );\n\n thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the Cookie header for us (returned as a string)
function parseCookie(req) { var c = null; if (req.headers['cookie']) c = req.headers['cookie'].split('=').pop(); return (c); }
[ "function parseCookie() {\n let cookie = document.cookie.split(';');\n for (let i = 0; i < cookie.length; i++) {\n let parts = cookie[i].split('=');\n if (parts.length === 2 && parts[1].length !== 0) {\n return parts.join('=');\n }\n }\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds the toggle switch to the TOC
function addSbRightTocToggle() { if(!document.getElementById) return; var header = jQuery('#sb__right__toc__header'); if(!header.length) return; var obj = document.createElement('span'); obj.id = 'sb__right__toc__toggle'; obj.innerHTML = '<span>&minus;</span>'; obj.cla...
[ "toggleToc(){\n this.tocOn = !this.tocOn;\n this.displayToc();\n }", "function toggleTOC() {\n let toc = document.getElementById(\"toc-section\");\n if (toc == null) {\n return\n }\n if (toc.classList.contains(\"hide\")) {\n toc.classList.remove(\"hide\");\n } else {\n // if sidebar-section i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getFirstCheckedId(tblName) return the first Checked row id from column 0
function getFirstCheckedId(tblName) { for (var i=1; i<tblName.rows.length; i++) { if (tblName.rows(i).cells(0).firstChild.checked) return tblName.rows(i).cells(0).firstChild.name; } return null; }
[ "function getFirstChecked(tblName)\n\t{\n\t\tfor (var i=1; i<tblName.rows.length; i++)\n\t\t{\n\t\t\tif (tblName.rows(i).cells(0).firstChild.checked) return i;\n\t\t}\n\t\treturn -1;\n\t}", "function getFirstSelectedCheckbox() {\n\n\treturn document.querySelector('.tableCheck:checked').getAttribute('data-id');\n}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Builds a Quaternion from the given euler angles in radians / The rotations will get applied in following order: / 1. pitch (X axis), 2. yaw (Y axis), 3. roll (Z axis) / / The pitch (attitude), counterclockwise rotation around X axis / The yaw (heading), counterclockwise rotation around Y axis / The roll (bank), count...
static fromEulerAngles(pitch, yaw, roll) { return new Quaternion().setFromEulerAngle(pitch, yaw, roll); }
[ "static fromVector3EulerAngles(eulerAngles) {\n return new Quaternion().setFromEulerAngle(eulerAngles.x, eulerAngles.y, eulerAngles.z);\n }", "function euler2quat(e) {\n\n\tif(!e) return;\n \n var roll = .5 * e[0] * to_radians,\n pitch = .5 * e[1] * to_radians,\n yaw = .5 * e[2] * to_r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to create Bubbleplot
function bubbleplot(samples) { // create data variable for plot var data = [{ x: samples.otu_ids, y: samples.sample_values, mode: "markers", marker: { size: samples.sample_values, color: samples.otu_ids }, text: samples.otu_labels }]; // create layout variable for plot var layo...
[ "function BubbleData(otu) {\n data = [\n {\n x: otu.map(x => x.otu_ids_original),\n y: otu.map(x => x.sample_values),\n mode: \"markers\",\n text: otu.map(x => x.otu_labels),\n marker: {\n color: otu.map(x => x.otu_ids_original),\n size: otu.map(x => x.sample_values),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the selected district
function getSelectedDistrict() { return getCache(EXTRA_DISTRICT); }
[ "function selectDefaultDistrict() {\n usStatelayer.queryFeatures({\n where: propertyNames.StateLayer.Name + \"='\" + selectedMemberLocation.state + \"'\",\n returnGeometry: true,\n outFields: [propertyNames.StateLayer.Id]\n }).then(function (respons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Atualiza a lista de escudos.
function _AtualizaListaEscudos() { _AtualizaListaArmasArmaduras( 'escudos', Dom('div-equipamentos-escudos'), gPersonagem.escudos, AdicionaEscudo); }
[ "function _AtualizaListaArmaduras() {\n _AtualizaListaArmasArmaduras(\n 'armaduras', Dom('div-equipamentos-armaduras'), gPersonagem.armaduras, AdicionaArmadura);\n}", "function _AtualizaListaArmas() {\n _AtualizaListaArmasArmaduras(\n 'armas', Dom('div-equipamentos-armas'), gPersonagem.armas, Adiciona...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements the Harmonic Oscillator
function _harmonicOscillator(t, params) { if (!params._isPrepared) { params._cycles = params.cycles || 1; params._negativeHandler = _parseNegativeHandler(params.negativeHander); params._shift = params.shift || 0; } var cycles = params._cycles; var v = ...
[ "function playHarmonic() {\n stopNoteIfActive();\n synth.playFreq(3, res.ref.hertz, percussive(1.75));\n synth.playFreq(4, res.hertz , percussive(1.75));\n synth.stopFreqAfter(3, 10);\n synth.stopFreqAfter(4, 10);\n}", "get harmonicity() {\n if (this._getOscType(this._oscillator, \"fm\") || this._getOs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get last donation amount
function getLastDonation(){ return GM_getValue('lastDonation'); }
[ "function getLastDonation() {\n extraLife.getUserDonations(extraLifeID).then(checkLastDonation, function(error) {\n console.log(error);\n });\n}", "function setLastDonation(cost){\n GM_setValue('lastDonation', cost);\n }", "function lastPaidAmount(billerCorpAccounts_id) {\n\tvar lastPaidAmountSec = \"<...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens the tooltip. This is considered to be a "manual" triggering. The `context` is an optional value to be injected into the tooltip template when it is created.
open(context) { if (!this._windowRef && this._ngbTooltip && !this.disableTooltip) { this._windowRef = this._popupService.open(this._ngbTooltip, context); this._windowRef.instance.tooltipClass = this.tooltipClass; this._windowRef.instance.id = this._ngbTooltipWindowId; ...
[ "open(context) {\n if (!this._windowRef && this._ngbTooltip && !this.disableTooltip) {\n const { windowRef, transition$ } = this._popupService.open(this._ngbTooltip, context, this.animation);\n this._windowRef = windowRef;\n this._windowRef.instance.animation = this.animation...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
strip color carousel feature
dismantle_color_carousel() { var colorCarousel = document.querySelectorAll('.product-single > .mini-carousel'); if (colorCarousel.length < 1) { throw('Error finding color carousel'); } colorCarousel = colorCarousel[0]; var product = document.getElementsByClassName('pr...
[ "function clearStrip() {\n setAllPixels('rgb(0,0,0)')\n }", "function clearDotColor() {\n for (var i=0; i<slideDots.length; i++) {\n slideDots[i].style.backgroundColor = '';\n }\n}", "function color(nb){\n\tlet ok=false;\n\tlet i=0;\n\twhile (i<=3 && !ok){\n\t\tif (carousel.children[i].style.display===...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send requests for the given endpoints every hour
function sendRequests1() { sendRequests(tokenList[0], userIdList[0], pathList_1h, nextUser); setTimeout(sendRequests1, 3600000); }
[ "function sendRequests24() {\n sendRequests(tokenList[0], userIdList[0], pathList_24h, nextUser);\n setTimeout(sendRequests24, 86400000);\n}", "sendWeatherReport() {\n const rule = new schedule.RecurrenceRule();\n\n rule.hour = 10;\n rule.minute = 15;\n rule.second = 0;\n\n schedule.scheduleJ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if there is a value in the input, and if we haven't selected anything to edit, then it should add a to do to the to do list and clear the input value
add() { let selected = this.props.todo.selected; let input = document.getElementById('input-to-do'); let val = input.value; if (val && !this.props.todo.editing) { this.props.addToDo(this.props.todo.todo, this.props.todo.totalToDos); input.value = ''; } ...
[ "edit() {\n let selected = this.props.todo.selected;\n let input = document.getElementById('input-to-do');\n let val = input.value;\n\n if (this.props.todo.editing) {\n this.props.addEdits(selected, this.props.todo.todo, this.props.todo.totalToDos);\n this.props.tur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all the JSON.stringified job properties decoded back to objects job (object) raw job from redis to decode callback (function) f(job)
function _decodeJob(job, callback) { [ 'chain', 'onerror', 'chain_results', 'onerror_results', 'oncancel', 'oncancel_results', 'params', 'num_attempts' ].forEach(function (property) { try { ...
[ "_parseJobArgv(job){\n\t\treturn JSON.parse(job.payload.toString());\n\t}", "_getJobHash (job) {\n return JSON.stringify(job);\n }", "function getJobProperty(uuid, prop, meta, cb) {\n if (typeof (uuid) === 'undefined') {\n return cb(new wf.BackendInternalError(\n 'Workflow...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register collaborator for a given documentId
_register(collaboratorId, documentId, selection, collaboratorInfo) { let collaborator = this._collaborators[collaboratorId] if (!collaborator) { collaborator = this._collaborators[collaboratorId] = { collaboratorId: collaboratorId, documents: {} } } // Extend with collabora...
[ "_unregister(collaboratorId, documentId) {\n let collaborator = this._collaborators[collaboratorId]\n delete collaborator.documents[documentId]\n let docCount = Object.keys(collaborator.documents).length\n // If there is no doc left, we can remove the entire collaborator entry\n if (docCount === 0) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that all pointers are coherent in this tree
checkInternalPointers () { if (this.left) { if (this.left.parent !== this) throw new Error(`Parent pointer broken for key ${this.key}`) this.left.checkInternalPointers() } if (this.right) { if (this.right.parent !== this) throw new Error(`Parent pointer broken for key ${this.key}`) ...
[ "function _checkIntegrity() {\n\t var node = this._first;\n\t var count = 0;\n\t var prevNode;\n\t while (node) {\n\t if (!node._prev && (node !== this._first)) {\n\t throw 'No prev but not first';\n\t }\n\t if (node._prev !== prevNode) {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
= Description The receiver of the +onIdle+ "poll event". The app priority defines the interval. Extend this method, if you are going to perform regular actions in a app. Intended for "slow infinite loops".
onIdle() { /* Extend this */ }
[ "function poll() {\n this.log('poll start');\n \n // Check global event registers\n if( lastActiveEvent && \n lastActiveEvent.ts > this.lastActivity &&\n (!lastIdleEvent || lastIdleEvent.ts < lastActiveEvent.ts) ) {\n this.lastActivity = lastActiveEvent.ts;\n this.lastSource = la...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancels current filter application ('filterBuilder' mode).
filterBuilderCancel() { const that = this; that.filterBuilder.value = that.cachedFilter.filterBuilder; if (that.context.filterType === 'string') { that.caseSensitive.checked = that.cachedFilter.caseSensitive; } }
[ "function cancelClickHandler() {\r\n // reset the dropdowns to be consistent with the current filters in the\r\n // application state\r\n updateDropdownsWithCurrentFilters();\r\n }", "cancelFiltersAndSearch () {\n this.filtersBlock.handleClearFilters()\n this.filtersBlock.clearSearch()\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate game search data and if successful, send it to server
function validate_game_search() { var form = get_form_data('#search_game_form'); if (!is_field_empty(form.order_phase) && check_field_int(form.order_phase, 'order_phase')) return false; if (!is_field_empty(form.retreat_phase) && check_field_int(form.retreat_phase, 'retreat_p...
[ "function searchGame(e) {\r\n e.preventDefault();\r\n\r\n //Clear single game\r\n single_gameEl.innerHTML = '';\r\n\r\n //Get search term\r\n let term = search.value; \r\n term = term.replace(/\\s+/g, '-').toLowerCase();\r\n let encodedTerm = encodeURIComponent(term);\r\n\r\n //Check for emp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the user has bought oxen or not. User can only leave the store if oxen has been bought.
function checkHasOxen() { if(numOxen >= 1){ return true; } return false; }
[ "function shouldTrackPurchase() {\r\n return RhEasyShopify && RhEasyShopify.pageType === 'checkout' &&\r\n ShopifyObject && ShopifyObject.Checkout && ShopifyObject.Checkout.page === 'thank_you' &&\r\n ShopifyObject.checkout && ShopifyObject.checkout.line_items && ShopifyObject.checkout.line_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Kill data older than the specified interval in the specified table
function CullData ( sensorId, interval, table ) { pool.getConnection( function ( err, connection ) { if ( err ) console.log( err ); connCount++; if ( config.debug ) console.log( 'Cleanup connection added.' ); connection.query( "DELETE FROM " + table + " WHERE `logical_sensor_id` = ? AND `timestamp` < ( ( CON...
[ "function cleanseData(table, beforeTimestamp) {\n table.where('timestamp').below(beforeTimestamp).toArray(function(rows) {\n _(rows).forEach(function(row) {\n table.delete(row.id);\n })\n });\n }", "killInterval() {\n clearInterval(t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The purpose of this function is to check the existence of a role.
function isExist(check, accessor, objJRole, objRoleManager) { //If role is new. if (check === true) { objRoleManager.create(objJRole); removeSpinner("modalSpinnerRole"); return true; } var existMessage = getUiProps().MSG0007; document.getElementById("popupRoleErrorMsg").innerHTML = existMessage; removeSpinn...
[ "function hasRole(role) {\n return this.roles.indexOf(role) > -1;\n}", "function exists(role) {\r\n\tcheckNotNull(role);\r\n\r\n\tif (thematicRoleContexts != null) {\r\n\t\tfor ( var i = 0; i < thematicRoleContexts.size(); i++) {\r\n\t\t\tvar thematicRoleContext = thematicRoleContexts.get(i);\r\n\r\n\t\t\tif (th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if all fields have been rated
function allFieldsRated() { var allValuesExist = $('#new_review input[id*="review"]').filter(function(i) { return i != 7 //excludes :overall_rating }).toArray().every(function(field) { return field.getAttribute('value') !== null }); return allValuesExist; } // allFieldsRated
[ "isRatedFinish(){\n\t\tlet numOfQuestion = Object.keys(this.props.questionData).length;\n\t\tlet numOfRated = Object.keys(this.state).length;\n\t\tlet result = (numOfRated === numOfQuestion) ? true : false; \n\t\treturn result;\n\t}", "checkIfAllReviewed() {\n return (this.flags.length + this.reveiledNum) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle web search, when clicking over a movie
function handleWebSearch() { moviesList.on("click", ".movie__title", function(e) { var movieTitle = $(e.currentTarget).text(); window.open( "https://www.google.com/search?q=" + encodeURIComponent(movieTitle) + " " + encodeURIComponent(config.searchSufix) ); }); }
[ "function onSearchButtonClick(){\t\n\tmovieSearch($('.search-box').val());\t\n}", "function searchmovie(value) {\r\n const path = \"search/movie\";\r\n const search_url = generateUrl(path) + \"&query=\" + value;\r\n requestmovie(search_url, renderMovieSearch, handlerror);\r\n}", "onSearch(e) {\n\t e.prevent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the breadcrumbs based on Path value
function generateBreadcrumbs (path){ $("#perc-chart-breadcrumb-list").html(""); breadcrumbItems = []; breadcrumbItems = path.split("/"); var siteName = prefs.getString(SITE_NAME); if (siteName == "@all"){ $("#perc-chart-breadcrumb-list").append(' <li atitle = "" ><span id = "perc-breadcrumb-items...
[ "function getBreadcrumbs (path) {\n\n var breadcrumbs = [{\n link : '/',\n name : 'Home'\n }];\n var pieces = path.split('/');\n\n for (var i = 0; i < pieces.length; i++) {\n var part = pieces[i];\n\n if (part){ // There are some empty strings....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Request Face/Look person only.
function start_face_person(source="hmi") { add_desire(source + "_face_person", "FacePerson", "", 1, 10); add_desire(source + "_look_at_person", "LookAtPerson", "", 1, 10); add_desire(source + "_track_people", "TrackPeople", "", 1, 10); }
[ "function FacePerson(name, person)\n{\n\tif (!person) person = Game.player.name;\n\tSetPersonDirection(name, GetAngleDirection(name, person));\n}", "isFriendRequested() {\n return this.props.user.friendRequests.filter(user => user.spotifyId === this.props.auth.spotifyId).length > 0;\n }", "isPerson() {\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In syncsupporting browsers, this adds a listener for the sync event. In nonsyncsupporting browsers, this will retry the queue on service worker startup.
_addSyncListener() { if ('sync' in self.registration) { self.addEventListener('sync', event => { if (event.tag === `${TAG_PREFIX}:${this._name}`) { { logger_js.logger.log(`Background sync for tag '${event.tag}' ` + `has been received`); } const ...
[ "_addSyncListener() {\n if ('sync' in registration) {\n self.addEventListener('sync', (event) => {\n event.waitUntil(this.replayRequests());\n });\n } else {\n // If the browser doesn't support background sync, retry\n // every time the service worker starts up as a fallback.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads userdefined and default settings from JSON
function load() { const saved = storage.readJSON(filename, 1) || {}; const defaults = storage.readJSON(defaultsFilename, 1) || {}; data = {}; for (const key in defaults) { if (typeof saved[key] === typeof defaults[key]) { data[key] = saved[key]; } else { data[key] = default...
[ "function loadSettings() {\n try {\n\t\tconst data = fs.readFileSync(__dirname+'/settings.json', 'utf8')\n\t\tconst settings = JSON.parse(data)\n return settings\n\t} catch (err) {\n console.error(err)\n\t}\n}", "load() {\n\t\tObject.keys(this.settings).forEach((key) => {\n\t\t\tthis.settings[key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detects if the current browser is based on WebKit.
function DetectWebkit() { if (uagent.search(engineWebKit) > -1) return true; else return false; }
[ "function DetectWebkit()\n{\n if (uagent.search(engineWebKit) > -1)\n return true;\n else\n return false;\n}", "function isWebKit() {\n return isBrowser()\n && /AppleWebKit/i.test(navigator.userAgent)\n && !isBlink() && !isEdge() && !isTrident();\n}", "function M_isWebKit() {\n return navi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loop through specs and add to specsElement
function loopThroughSpecs(selectedLaptop) { for (const spec of selectedLaptop.specs) { const specItem = document.createElement("li"); specItem.innerText = spec; specsElement.appendChild(specItem); } }
[ "function listSpecs(spec) {\n const li = document.createElement(\"li\");\n li.appendChild(document.createTextNode(spec));\n pcSpecsElement.appendChild(li);\n}", "setTestList() {\n const ul = document.getElementById('tests');\n for (let i in this.testList) {\n // TODO(chenghan): Able to pass spec par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
STEP 1: SORT NAMES by LAST NAME! / function nameCmp: compare two names by last name
function nameCmp(names1,names2) { //split arrays var namesSplit1 = names1.split(" "); var namesSplit2 = names2.split(" "); //get last name var lastName1 = namesSplit1[namesSplit1.length - 1]; var lastName2 = namesSplit2[namesSplit2.length - 1]; //compare names if(lastName1 < lastName2) return -1; if...
[ "function nameCompare(name1, name2) {\n var name1List = name1.split(\" \");\n var name2List = name2.split(\" \");\n\n // Returns two last names\n var lastName1 = name1List[name1List.length - 1];\n var lastName2 = name2List[name2List.length - 1];\n\n // Compare last names\n if (lastName1 < lastN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to find the given profile `name` in `profiles` to make sure it exists. If found, return `name`, indicating that it's a valid name. If it isn't a valid name (or is falsy), try to find the default profile name, and return it if it's in `profiles`. If that fails, return null, indicating that no profile name applies to...
function resolveProfileName(config, name) { if (!name) { return null; } var profiles = config.profiles; if (name && profiles[name]) { return name; } var defaultProfileName = config.defaultProfile; if (defaultProfileName && profiles[defaultProfileName]) { return defaultProfileName; } consol...
[ "function resolveProfileName(config, name) {\n if (!name) {\n return null;\n }\n let profiles = config.profiles;\n if (name && profiles[name]) {\n return name;\n }\n let defaultProfileName = config.defaultProfile;\n if (defaultProfileName && profiles[defaultProfileName]) {\n return defaultProfileNam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Algorithm A5.6 from "The NURBS Book" The total number of bezier segments required to decompose a given bspline curve = Number of internal knots + 1 = Length of knot vector 2(p+1) + 1 = (m+1) 2(p+1) + 1 = m 2p See
decompose() { let p = this.degree; let U = this.knots; let m = U.length - 1; let P = this.cpoints; let dim = this.dimension; let alphas = new common_1.NDArray({ shape: [p] }); let a = p; let b = p + 1; let total_bezier = m - 2 * p; ...
[ "getSegments() {\n const { knots, points, degree } = this;\n const result = [];\n const v = ts3dutils.Vector.pack(points, new Float64Array(points.length * 4));\n const vectorFromV = (i) => new ts3dutils.Vector(v.slice(i * 4, (i + 1) * 4));\n let k = degree + 1; // k = knot index w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
determines if the user selection was correct and adjusts score accordingly.
function userSelection() { stopCountdown(); if ($(this).attr("data-name") == correctAnswers[questionSelector]) { rightWrong = true; correct++; var newScore = score += points; $("#score").text(newScore); } else { incorrect++ } ...
[ "function handleQuestion(selection) {\n var answer = questions[currentQuestion].answer;\n \n if (selection == answer) {\n score++\n showAlert('Right', 400);\n }\n \n else {\n showAlert('Wrong', 400);\n }\n }", "function handleScore(choice, c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes errors and returns first error input element name
getElementName(errors) { return Object.keys(errors.collect())[0]; }
[ "get errorName () { return $('#register-error-name') }", "function getFirstError(errors) {\n \n for (var error in errors) {\n if (errors[error]) {\n return error;\n }\n }\n \n }", "function getFirstError($root) {\n\treturn $root.find(\".digiforms_valid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update the to and from time state
onfromTimeChange(time) { this.setState({ fromTime: time }); }
[ "function setFromAndToTime(fromTm, toTm)\n{\n\tif (fromTm > 0)\n\t\t$(\"#fromtimeentry\").val(getStringFromTime(fromTm));\n\telse\n\t\t$(\"#fromtimeentry\").val('12:00 AM');\n\tif (toTm > 0)\n\t\t$(\"#totimeentry\").val(getStringFromTime(toTm));\n\telse\n\t\t$(\"#totimeentry\").val('12:00 AM');\n}", "resetFromAnd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the build beta details resource ID associated with a specific build.
function getBuildBetaDetailsResourceIDForBuild(api, id) { return api_1.GET(api, `/builds/${id}/relationships/buildBetaDetail`) }
[ "function getBuildIDForBuildBetaDetail(api, id) {\n return api_1.GET(api, `/buildBetaDetails/${id}/relationships/build`)\n}", "function getBuildIDForBetaAppReviewSubmission(api, id) {\n return api_1.GET(api, `/betaAppReviewSubmissions/${id}/relationships/build`)\n}", "function getBuildIDForBetaBuildLocali...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
JD_TO_BAHAI Calculate Bahai date from Julian day
function jd_to_bahai(jd) { var major, cycle, year, month, day, gy, bstarty, bys, days, bld; jd = Math.floor(jd) + 0.5; gy = jd_to_gregorian(jd)[0]; bstarty = jd_to_gregorian(BAHAI_EPOCH)[0]; bys = gy - (bstarty + (((gregorian_to_jd(gy, 1, 1) <= jd) && (jd <= gregorian_to_jd(gy, 3, 20...
[ "function jd_to_bahai(jd)\n{\n var major, cycle, year, month, day,\n gy, bstarty, bys, days, bld;\n\n jd = Math.floor(jd) + 0.5;\n gy = jd_to_gregorian(jd)[0];\n bstarty = jd_to_gregorian(BAHAI_EPOCH)[0];\n bys = gy - (bstarty + (((gregorian_to_jd(gy, 1, 1) <= jd) && (jd <= gregorian_to_jd(gy,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Let our webhook connection know we want to start monitoring a job by ID.
function addJobToCheckStatus(jobID) { if (!conn || conn.readyState != WebSocket.OPEN) { return; } conn.send(jobID); }
[ "jobReady(id) {\n return this.__post(`jobs/${id}/ready`);\n }", "startJobStatusUpdates() {\n this.bus.emit(jcm.MESSAGE_TYPE.START_UPDATE, {\n [jcm.PARAM.JOB_ID]: this.jobId,\n });\n this.state.listeningForJob = true;\n }", "async function startWebhook()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
makes a color legend for a variable
function legend_color(svg, x_pos, y_pos, width, color, title) { // creates element for legend svg.append('g') .attr('class', 'legendLinear') .attr('transform', 'translate(' + x_pos + ', ' + y_pos + ')'); // legend information let legendLinear = d3.legendColor() .shapeWidth(width) .orient('...
[ "function addcolorlegend(cy){\n cy.$('node[id = \"l1\"]')\n .style('color', 'black')\n .style('background-height',50)\n .style('background-width',200)\n .style('background-position-y','100%')\n .style('shape','rectangle')\n .style('width',200)\n .style...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Push module for sonar login
function SonarPusher(hickey) { var listener_cometd = new jQuery.Cometd(); var handshakeListener = null; var subscribeListener = null; var sendSubscribtion = null; var _connect_num = 1; this.login = function() { push_connect(SONAR_PUSH_URL); } function push_connect(server_url) ...
[ "function pushLogin(username, password) {\n API.triggerServerEvent(\"tryLogin\", username, password);\n}", "function schedulePush() {\n\t\tif (pushTimeout) {\n\t\t\tclearTimeout(pushTimeout);\n\t\t}\n\t\tpushTimeout = setTimeout(function() {\n\t\t\tpushTimeout = undefined;\n\t\t\tvar remoteModules = {\n\t\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert dec integer string
function decstr2int(str) { var i = -1; if (is_digit(str)==true) i = parseInt(str, [10]); return i; }
[ "function binToDec(str) {\n return Number.parseInt(Number.parseInt(bin, 2), 10);\n}", "function toInt (str) {\n\n}", "function bin_to_dec(bstr) { \n return parseInt(bstr, 2);\n }", "function convertTo2DigitString(n){\treturn (n > 9 ? n : '0' + n); }", "function toDec(ch) {\n\t\t\tch = ch.substring(0,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a codepoint, return true if it falls within one of the scripts or script families defined above and false otherwise. Micro benchmarks shows that this is faster than /[\u3000\u30FF\u4E00\u9FAF\uFF00\uFF60\uAC00\uD7AF\u0900\u109F]/.test() in Firefox, Chrome and Node.
function supportedCodepoint(codepoint) { for (var i = 0; i < allBlocks.length; i += 2) { if (codepoint >= allBlocks[i] && codepoint <= allBlocks[i + 1]) { return true; } } return false; }
[ "function supportedCodepoint(codepoint) {\n for (var i = 0; i < allBlocks.length; i += 2) {\n if (codepoint >= allBlocks[i] && codepoint <= allBlocks[i + 1]) {\n return true;\n }\n }\n return false;\n}", "function characterScript(code) {\n for (let script of SCRIPTS) {\n if (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the scroll position of the browse tree if selected item off screen
function browseScrollPos() { var $selectedItem = $('.workspace-browse li.selected .page__container.selected'), $browseTree = $('.workspace-browse'); if ($selectedItem.length) { var selectedTop = $selectedItem.offset().top, selectedBottom = selectedTop + $selectedItem.height(), ...
[ "function treeMenuScroll() {\n\tif(currentItem == null)\n\t\treturn;\n\tvar trObj = showTreeWindow.document.getElementById(currentItem.index);\t\n\tif(trObj == null)\n\t\treturn;\n\ttrObj.scrollIntoView(false);\n}", "function update_scroll_position()\n\t{\n\t\tif ( List.selection < List.scroll ) {\n\t\t\tList.scr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all keys in storage, not including internal keys used to store expiration.
keys (includeExpired) { // create list to return var ret = [] // iterate over storage keys to find all non-expiration keys var that = this this._iterKeys(function (storageKey) { // if its not a timestamp key, skip it if (storageKey.indexOf(that._expiration_key_prefix) !== 0) { /...
[ "getAllKeys() {\n return myCache.keys();\n }", "async getKeys() {\n return await AsyncStorage.getAllKeys()\n }", "keys() {\n return AsyncStorage.getAllKeys();\n }", "keys() {\n const storage = global.localStorage ? global.localStorage : store.data;\n return Object.keys(storage);\n }",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set annotation for this element.
setAnnotation(text) { this.annotation = text; }
[ "function Annotation() {\n this.guid_ = tr.b.GUID.allocateSimple();\n this.view_ = undefined;\n }", "function Annotation() {\n _classCallCheck(this, Annotation);\n\n Annotation.initialize(this);\n }", "function setAnnotationPosition(//it is in dedicated line here.\n annotation, offsetX, offsetY...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We have an EventLogView and an EventLogStore: The basic architecture is that one can request views on the event log from the store, which returns a view object and then deals with getting the data required for the view. The view object is accessed by React components and distributes updates etc. See also: components/Ev...
function EventLogView(store, live) { EventEmitter.call(this); this._store = store; this.live = live; this.log = []; this.add = this.add.bind(this); if (live) { this._store.addListener(ActionTypes.ADD_EVENT, this.add); } }
[ "renderComponent(ViewComponent){\n return(\n <div className=\"ui padded grid\">\n <CreateEventSteps view={this.state.view} handleChangeView={this.handleChangeView}/>\n {ViewComponent}\n </div>\n )\n }", "function ViewEvent(events) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is MIDI note the tonic
isTonic(note) { return (note % 12) == this.offset(); }
[ "isEqualTo (midiNote) {\n return this.pitch === midiNote\n }", "function matchToMetronome(midiMessageType, noteTimeStamp){\n var step = (60 / tempo) * 1000;\n // Closer to current tick\n if (Math.abs(tickTime + step - noteTimeStamp) > Math.abs(tickTime - noteTimeStamp))\n {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return index of first occurrence of specified element in array, or 1 if not found
function findInArray(arr, element) { var i; for (i = 0; i < arr.length; ++i) { if (arr[i] === element) { return i; } } return -1; }
[ "function myIndexOf(array, ele) {\n for (var i = 0; i < array.length; i++) {\n if (array[i] === ele) {\n return i;\n }\n }\n return -1;\n}", "function myindexOf(array, element)\r\n{\r\n for(let i = 0; i < array.length; i++) \r\n {\r\n if (array[i] == element)\r\n return i;\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function finds requested data for a planet and appends fata to document
function reqPlanet() { if(this.status === 404){ throwError(); } const requestData = JSON.parse(this.responseText); const name = requestData.name; one.innerHTML = 'Name: ' + name; const terrain = requestData.terrain; two.innerHTML = `terrain: ${terrain}`; const population = requestData.population; three.in...
[ "function empirePlanets () {\n const requestData = JSON.parse(this.responseText);\n console.log('requestData: ', requestData.planets);\n let planetArray = requestData.planets;\n //buildEmprire(planetArray);\n DOMEmpire(planetArray);\n}", "function updatePlanets() {\n // Get the planet informaton from the we...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Section 6 /////////////////////////////////////////// The problem with `nextLabel` is that it uses a global variable for the count, so no matter which label you pass in, you'll always increment the same count. Fix that by writing a function that generates a new function for each label to be sequenced
function labelMaker(label) { // START let count = 0; return function(){ return label+'-'+count++; }; // END }
[ "function incrementLabelNumber() {\n\t\tpreviousLabelNum = labelNum;\n\t\n\t\tif (labelNum != (beerCount - 1)) {\n\t\t\tlabelNum += 1;\n\t\t} else {\n\t\t\tlabelNum = 0;\n\t\t}\n\t}", "function labelMaker1(label) {\n // START\n let count = 0;\n return function(counter){\n if(!isNaN(counter))\n count = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if we encountered any error , stop the DB and terminate the process
function stop(err) { console.log("ISSUE WITH MYSQL \n" + err); process.exit(1); }
[ "function dbQueryCheck(err) {\n if (err) {\n console.log(\"Database query error: \" + err);\n console.log(\"\\n!!<< FATAL ERROR: STOPPING THE SERVER >>!!\");\n process.exit(0);\n };\n}", "async terminate() {\n await db.terminate(this.connection);\n }", "function endDbConnection() {\n pg....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter worksheet by year.
function yearFilter(type, year) { var uppercase = type.toUpperCase(); switch(uppercase) { case "ADD": activeSheet.applyFilterAsync( "JAHR(Date (year))", year, tableau.FilterUpdateType.ADD)...
[ "function filterByYear(e) {\n setYear(e.target.value);\n const filteredData = props.expenses.filter(item => (parseInt(item.date.getFullYear()) === parseInt(e.target.value)))\n props.filteredData(filteredData);\n }", "function yearFilter(value) {\r\n return (value.Year == display_year);\r\n}", "func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load all markdown documents
function loadAllMdownDocs(doc, anchor){ var promises = []; $.each(arrDocNames, function(i, name){ promises.push( new Promise(function (resolve, reject) { $.get("./markdown/" + name + ".md") .done(function (value) {resolve({value:value, name:name})}) .fail(function () {reject("The doc...
[ "function parseMarkdownFiles() {\n const contentsDirectory = path.join(__dirname, '../contents');\n fs.readdir(contentsDirectory, (err, files) => {\n if (err) {\n console.error('Error reading the contents directory:', err);\n return;\n }\n\n files.filter((file) => fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trigger table upload action
function triggerUploadAction() { if (!appInfo.triggers) return; var triggerToRun; appInfo.triggers.forEach(function (trigger) { // For each trigger enabled for current segment if (!trigger.isEnabled || trigger.action.segment !== appInfo.type) return; // Saving trigger if its ...
[ "function applyUploadEvent(){\n $(UPLOAD_COMPONENT_SELECTOR).on('fileuploadersuccess', function(){\n var $uploaderContainer = $(this).closest(UPLOAD_CONTAINER_SELECTOR),\n tableUpdaterWidget = $(UPLOAD_TABLE_SELECTOR, $uploaderContainer).data(TABLE_UPDATER_WIDGET);\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively parse directory for page URLs.
function parseUrlForPages(urlprefix, directory) { fsReadDirSyncCache[directory] = fsReadDirSyncCache[directory] || fs.readdirSync(directory); var res = []; fsReadDirSyncCache[directory].forEach(function(fname) { // TODO: this should account for all page extensions // not just js(x) and ts(x)...
[ "async function parseTree({ url, currPath, page }) {\n console.log(`creating/recreating path: ${currPath}`);\n await page.goto(url);\n resolveFolder(currPath);\n await page.waitForSelector(\".Box-row\");\n const itemRows = await page.$$(\".Box-row\");\n const folders = [];\n // potential parallel spot\n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the tween to its start
function updateToStart() { for ( var i = 0; i < script.api.tweenObjects.length; i++) { var tweenObject = script.api.tweenObjects[i]; updateColorComponent( tweenObject.component, tweenObject.startValue ); } }
[ "function setupTween() {\n \n if (!script.api.manualStart) {\n var startRaw = getRawByName(\"start\");\n script.api.start = getValueFromRaw(startRaw);\n \n }\n\n if (!script.api.manualEnd) {\n var endRaw = getRawByName(\"end\");\n script.api.end = getValueFromRaw(endRaw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the string x,y as [x, y]
static toCoords(string) { return [parseFloat(string.split(',')[0]), parseFloat(string.split(',')[1])]; }
[ "getCoordsAsString(){\n\t\tvar coords = \"(\" + this.x + \",\" + this.y + \")\";\n\t\treturn coords;\n\t}", "function toString(xy) {\n return xy ? xy.x + ', ' + xy.y : '';\n }", "function toString(xy) {\n return xy.x + ', ' + xy.y;\n }", "function point(x, y) {\n return '' + x +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make, move, and rotate the ship
makeShip(){ // Rotate push(); translate(this.x1, this.y1); angleMode(DEGREES); rotate(this.heading); noFill(); stroke(255); imageMode(CENTER); image(pie, 0, 0, width/55, width/35); pop(); // Move forward angleMode(DEGREES); this.yacceleration = width/100...
[ "function rotateShip() {\n if (game.setup.shipRotate == 270) {\n game.setup.shipRotate = 0;\n } else {\n game.setup.shipRotate = game.setup.shipRotate + 90;\n }\n}", "function createShip(){\n translate(x, y);\n rotate(rotationAngle);\n createFalconHitBox();\n applySkin();\n}", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load PNX XML from Primo DB
function loadXML(url) { //Creating a Native empty Dom Element var xml = $.ajax({ url: url, dataType: "xml", async: false, error: function() { logJS('XML retrieval error') } }).responseXML; //logJS(pnxRecord); return xml; }
[ "async load (filename) {\n const xml = await fs.readFile(filename, { encoding: \"utf8\" })\n this.options.log(2, `loading XML file ${chalk.blue(filename)}: ${xml.length} bytes`)\n const dom = slimdomSAX.sync(xml, { position: false })\n let m\n if ((m = xml.match(/^(<\\?xml.+?\\?>\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a bitmask, performs a bitwise not (~) on a single mask, returns mask (C_vector)
function b_NOT(mask){ for(i=0; i<mask.length; i++){ mask[i] = !mask[i]; } return mask; }
[ "function invertMask(mask){\n return mask.add(scalar(1)).sub(scalar(2)).mul(scalar(-1))\n}", "function sc_bitNot(x) {\n\n\n\n\n var res = ~x;\n \n\n\n\n\n\n\n\n \n return res;\n}", "function BitwiseNotExpression() {\n}", "function getNotSelectedAndAncillaries(selectedVectorType) {\n $log.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
executes store application installation script (AddAppDevPackage.ps1)
function installApp(path, projecttype, buildtype, buildarchs) { Log("Attempt to install application..."); Log("\tDirectory : " + path); var command = "powershell -ExecutionPolicy RemoteSigned \". " + WINDOWS_STORE_UTILS + "; Install-App " + "'" + getPackage(path, projecttype, buildtype, buildarchs) + "\\A...
[ "function InstallApps() {\n\n //go through array of apps to install from back to front, ensuring that each install succeeds or showing warning\n //if counter > 0 we have apps to try to install else call configure device\n if (APPS_TO_INSTALL_COUNTER > 0) {\n APPS_TO_INSTALL_COUNTER--;\n //ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle ajax request and call cb function
function handleAjaxRequest(data, cbDone, cbFail) { $.post(SnthObj.ajaxurl, data, '' ,'json') .done(function(response) { if(response.type == 'success') { cbDone(response); } else { console.log(response.type); ...
[ "function AjaxCallback() { \r\n if( 4 == this.req.readyState ) {\r\n if( 200 != this.req.status ) {\r\n if (this.errorCall != null) {\r\n this.errorCall();\r\n }\r\n } else { \r\n if (this.successCall != null) { \r\n this.successCall(); \r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a helper function to padding string from left with space. len <= 10
function padding(str, len){ return (' ' + str).slice(-len); }
[ "function left_pad(str) {\n return (\" \" + str).slice(-9);\n}", "function padLeft( string, length, padding ) {\n padding = or( padding, NBSP );\n return fillStringLength(padding, length - string.length) + string;\n }", "function pad(str, width, padding) {\n return Array(width - str.length)....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a String list of available call functions, separated by comma, based on what functions are supported by the current VoIP engine Possible values: conference,transfer,mute,hold,chat or ERROR, if webphone is not yet started
function getavailablecallfunc () { if (typeof (webphone_api.plhandler) === 'undefined' || webphone_api.plhandler === null) { webphone_api.Log('ERROR, webphone_api: getavailablecallfunc webphone_api.plhandler is not defined'); return 'ERROR, webphone is not yet started'; } else { ...
[ "function getCallOptions () {\n return {\n constraints: {\n audio: true,\n video: true\n },\n onHangup: hangup,\n onRequestingMedia: onRequestingMedia,\n onAllow: onAllow,\n pre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Localised setConfig, also sets context and explorer config
setConfig() { super.setConfig(); if (this.setContexts) { this.setContexts(); } if (this.explorer) { this.explorer.setConfig(this.config); this.explorer.refresh(); } }
[ "setConfig() {\n\t\tthis.config = config.get();\n\t}", "setConfig(config) { this.config = config; }", "set config(obj) {\n this._config = obj;\n }", "function setContext() {\n\n $context = $( Config.get( 'context' ) );\n\n }", "setConfig(config) {\n super.setConfig(this.processConfig(config...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pie chart showing number of games played with X number of people
function _numPeopleInGame(elt, gameData) { if (elt instanceof jQuery) { elt = elt.get(0); } var data = new google.visualization.DataTable(); data.addColumn('string', 'Number of Players'); data.addColumn('number', 'Count'); var numPlayersTally = {}; ...
[ "function drawCountPieChart()\n{\n\tvar data = new google.visualization.DataTable();\n\tdata.addColumn('string', 'Name');\n data.addColumn('number', 'Messages');\n\t\n\tfor(var participant in participants)\n\t{\n\t\tif(participants[participant].hasOwnProperty(\"messageCount\"))\n\t\t{\n\t\t\tdata.addRow([partici...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Your program should take a number as input. That number should be the number of sheep you have. The function should display the number along with the message "Another sheep jumps over the fence" until no more sheep are left. Input: 3 Output: 3 Another sheep jumps over the fence 2 Another sheep jumps over the fence 1 An...
function countSheep(currentNumberSheep) { if (currentNumberSheep === 0) { console.log('All sheep jumped over the fence'); return } else { console.log(currentNumberSheep + ' ' + '- Another sheep jumps over the fence'); totalNumberSheep = currentNumberSheep -= 1; countSheep...
[ "function sheepCounter(number) {\n if (number === 0) {\n return;\n }\n\n console.log(number + ': Another sheep jumps over the fence');\n sheepCounter(number - 1);\n}", "function countingSheep(num) {\n if (num === 0 ) {\n return;\n }\n countingSheep(num - 1);\n console.log(num,'Another jumped over th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply new server data for the specified path..
function syncTreeApplyServerOverwrite(syncTree, path, newData) { return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData)); }
[ "function syncTreeApplyServerOverwrite(syncTree, path, newData) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));\r\n }", "function syncTreeApplyServerOverwrite(syncTree, path, newData) {\r\n return syncTreeApplyOperationToSyncPoints...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }