query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Disconnect from the micro:bit.
disconnect() { if (this._ble) { this._ble.disconnect(); } this.reset(); }
[ "disconnect() {\n\t\tthis.debug('Requesting disconnect from peer');\n\t}", "disconnect() {\n\t\t\tthis.connected = false;\n\t\t\t// Emitting event 'disconnect', 'exit' and finally 'close' to make it similar to Node's childproc & cluster\n\t\t\tthis._emitLocally('disconnect');\n\t\t}", "function DisconnectFromDe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a second team to use for the test
createSecondTeam(callback) { const testTeamCreator = new TestTeamCreator({ test: this, userOptions: this.userOptions, teamOptions: Object.assign({}, this.teamOptions, { creatorToken: this.users[1].accessToken }), repoOptions: Object.assign({}, this.repoOptions, { creatorIndex: 0, withKnownC...
[ "createTeam (callback) {\n\t\tlet data = {\n\t\t\tname: RandomString.generate(10)\n\t\t};\n\t\tthis.apiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/companies',\n\t\t\t\tdata: data,\n\t\t\t\ttoken: this.userData[0].accessToken\t// first user creates it\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the magnitude of a number
function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); }
[ "function magnitude() {\n return sqrt(this[buildMethodName(prefix, \"magnitudeSquared\")]());\n }", "function magnitudeSquared() {\n var x = getX.call(this),\n y = getY.call(this);\n return x * x + y * y;\n }", "function magToEnergy(mag) {\n \n // E = 10 ^ (11.8 + 1.5...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an array of `types` and flattens them, removing duplicates and returns a `UnionTypeAnnotation` node containg them.
function createUnionTypeAnnotation(types) { var flattened = removeTypeDuplicates(types); if (flattened.length === 1) { return flattened[0]; } else { return t.unionTypeAnnotation(flattened); } }
[ "function Union() {\n var alternatives = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n alternatives[_i] = arguments[_i];\n }\n var match = function () {\n var cases = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n cases[_i] = arguments[_i];\n }\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new Sentry CLI instance.
getSentryCli() { const cli = new SentryCli(this.options.configFile, { silent: this.isSilent(), org: this.options.org, project: this.options.project, authToken: this.options.authToken, url: this.options.url, vcsRemote: this.options.vcsRemote, }); if (this.isDryRun()) { ...
[ "create() {\n const uuid = `urn:uuid:${uuidv4()}`;\n\n this.metadata = new PackageMetadata();\n this.manifest = new PackageManifest();\n this.spine = new PackageSpine();\n this.setUniqueIdentifier(uuid);\n }", "start() {\n if (this._cli !== null)\n return;\n this._cli = readline.createI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get more images if we can when close to wall bottom
function getMoreImages() { // Return 0 if fetched all images, 1 if enough to fill screen and >1 otherwise var uncovered_px = $box.height()+$box.offset().top - ($(document).scrollTop()+window.innerHeight), uncovered_rows = uncovered_px / settings.row_height; if (unloaded) { // Don't load more than if not al...
[ "function viewBiggestImage() {\n var list = document.body.getElementsByTagName(\"img\");\n if(list.length <= 0)\n return;\n var areaMax = 0;\n var biggestImageIndex = 0;\n for(var i = 0; i < list.length; i++){\n if(list[i].src === \"\") // skip img tags that don't have a src; they aren'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepares the content of the Dropdown for the Item Types
prepareSelectTypes() { let items_buffer = getReferencesOfType('AGItem'); let that = this; let types_buffer = []; let append_buffer = "<option item_type = ''></option>"; if (items_buffer.length > 0) { items_buffer.forEach(function (element) { let type_b...
[ "prepareSelectItems() {\n let that = this;\n let items_buffer = getReferencesOfType('AGItem');\n let select_item_buffer = '';\n if (items_buffer.length > 0) {\n items_buffer.forEach(function (element) {\n select_item_buffer = select_item_buffer + '<option value ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show or Hide Passport View Sub Div
function showHidePassportRoleDiv(){ if(document.getElementById('empPassportMenuViewId').checked==true){ document.getElementById('passportMenuSubTableDivId').style.display = "block"; }else{ document.getElementById('passportMenuSubTableDivId').style.display = "none"; } }
[ "function showHidePayStubRoleDiv(){ \n\tif(document.getElementById('paystubMenuViewId').checked==true){\n\t\tdocument.getElementById('payStubMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('payStubMenuSubTableDivId').style.display = \"none\";\n\t}\n}", "function showDepEmploy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
similar to Array.prototype.reduce, except the reducer is an async function. items are handled serially, so no more than one promise is awaiting resolution at any time.
static reduce(array, reducer, initialValue) { if (typeof reducer !== 'function') { throw new Error('Second arg must be a reducer function') } const numItems = array.length return new P((resolve, reject) => { function processItem({ accum, index }) { const item = array[index] reducer(accum, item)...
[ "function mapReduce (mapper, reducer, list) {\n return new Promise((resolve, reject) => {\n Promise.all(list.map(mapper)).then(results => {\n reducer(results).then(resolve)\n })\n })\n}", "function processPromisesParallel(items, batchSize, handler, onUpdate) {\n return __awaiter(this, void 0, void...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the `DirectionMode` for the given language isoCode. The language isoCode is compared to the configured list of languages(`direction.rtlLanguages` vs `direction.ltrLanguages`). If no language is given, or no language mapping could be found, we fallback to the default `direction.mode`.
getDirection(language) { var _a, _b, _c, _d, _e; if (language && ((_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.rtlLanguages) === null || _b === void 0 ? void 0 : _b.includes(language))) { return DirectionMode.RTL; } if (language && ((_d = (_c = this.config...
[ "static getLanguageName() {\n let twoLetterLangName = global.language.value.toLowerCase().split('-')[0];\n switch (twoLetterLangName) {\n case \"en\":\n return \"english\";\n case \"de\":\n return \"german\";\n case \"es\":\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a position string, eg a1, from an array index
getPositionStringForIndex (index) { let { row, column } = this.getCoordinates(index) const number = Math.abs(row - 7) + 1 const letter = String.fromCharCode(97 + column) return `${letter}${number}` }
[ "getIndexForPositionString (positionString = 'a1') {\n const { row, column } = this.getCoordinatesForPositionString(positionString)\n let index = Math.abs(column - 8) + (row * 8)\n index = Math.abs(index - 64)\n return index\n }", "function returnACharacter(string, index) {\n return string[index];\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create an array of length len filled with with value val
function newFilledArray(len, val) { var array = []; for (var i = 0; i < len; i++) { array[i] = val; } return array; }
[ "function createArray(len, value) {\n let tmpArray = [];\n for (let i = 0; i < len; i++) {\n tmpArray[i] = value;\n }\n return tmpArray;\n }", "function newFilledArray(len, val) {\n\tvar sourceArray = [];\n\tvar makeArray = {\n\t\tset: function(len, val) {\n\t\t\twhile (0 < len--) {\n\t\t\t\tsou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read lat and lng fields and store them
function readLatLngFields() { current_lat = jQuery(field_lat).text(); current_lng = jQuery(field_lng).text(); }
[ "function setCoordinatesFiled(lat, lng) {\n $locationCoords[0].value = lat;\n $locationCoords[1].value = lng;\n }", "function takeGeo (position) {\n\tvar lat = position.coords.latitude;\n var lon = position.coords.longitude;\n}", "function markerLocation(){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load userdefined class codes
function loadCodes(type) { var file = __dirname + "/code." + type; fs.exists(file, function(exists) { if (!exists) return; codeTypes[type] = {}; fs.readFile(file, function(err, data) { var curr; _.each(data.toString().split(/[\n\r]+/), function(line) { line = line.replace(/\s*\#.*$/, ''); if ...
[ "function class_init()\r\n {\r\n var SCRIPT = \"fx_bobj_CeProperties=>class_init: \";\r\n fx_trace(SCRIPT+\"Entering\");\r\n\r\n importClass(Packages\r\n .com.crystaldecisions.sdk.occa.infostore\r\n .CePropertyID);\r\n\r\n go_date_format\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_________set up storage client and controller_________________________
function setUpStorageClient(err, credentials){ if (err) return console.log(err); storageClient = new StorageManagementClient(credentials, subscriptionId); //getStorageAccountsLists(); //getStorageKeyList(); createStorageAccount(); //getStorageKeyList(); }
[ "function StorageDelegate() {\n}", "constructor() { \n \n S3StorageConfig.initialize(this);\n }", "init() {\n let localStore = model.getLocalStore();\n if (_.isNull(localStore)) {\n localStorage.setItem('vanillaPress', JSON.stringify(jsonData));\n localStore = model.getL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to append the Github information to the file
function appendGitFile(githubresponse) { fs.appendFile('README.md', githubresponse, function (err) { if (err) throw err; console.log('The file has been updated!'); } ) }
[ "function generateGitContent(data) {\n return (\n `\n## Github details\n${data.name} <br>\n[GitHub URL](${data.url}) <br>\n[Image URL](${data.image}) <br>\nEmail: ameliajanegoodson@gmail.com <br>\n\n`)\n}", "function displayGithubLink() {\n\t\tvar formattedGithub = HTMLgithub.replace('%data%', bio.conta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to cast UInt8[] to UInt32
function UInt8toUInt32(value) { return (new DataView(value.buffer)).getUint32(); }
[ "function UInt32toUInt8(value) {\n console.log(value);\n t = [\n value >> 24,\n (value << 8) >> 24,\n (value << 16) >> 24,\n (value << 24) >> 24\n ];\n console.log(t);\n return t;\n}", "function U32A2WA(a) {\n\treturn WordArray.create(transformEndiannessU32(new Uint32Ar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We cannot set `textContent` directly in `render`, because React adds/deletes text nodes when rendering, which confuses screen readers and doesn't cause them to read changes.
setTextContent(textContent) { // We could set `innerHTML`, but it's better to avoid it. ReactDOM .findDOMNode(this) .textContent = textContent || ''; }
[ "function setTextContent(node, value) {\n if (predicates_1.isCommentNode(node)) {\n node.data = value;\n }\n else if (predicates_1.isTextNode(node)) {\n node.value = value;\n }\n else {\n const tn = modification_1.constructors.text(value);\n tn.parentNode = node;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles an intercepted call to the `elementClose` function from incremental dom.
function handleInterceptedCloseCall_() { if (currentParent_ === tree_) { IncrementalDomAop.stopInterception(); isCapturing_ = false; callback_(tree_); callback_ = null; currentParent_ = null; renderer_ = null; tree_ = null; } else { currentParent_ = currentParent_.parent; } }
[ "function closeElement(element) {\r\n element.remove();\r\n}", "function closeEvent() {\n var event = new Event('close-interface');\n document.dispatchEvent(event);\n}", "function closeDiv(element) {\r\n\telement.style.display='none';\t\t\t\t\t\r\n}", "function onFinalElementEvent() {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
showGraph() displays the graph by showing a list of all vertices and the vertices that are adjacent to them
function showGraph() { for(var i = 0; i < this.vertices; i++) { putstr(i + " -> "); for( var j =0; j < this.vertices; j++) { if (this.adj[i][j] != undefined) putstr(this.adj[i][j] + ' '); } print(); } }
[ "printGraph() {\r\n console.log(\"Graph: \");\r\n console.log('nodeList ', this.nodeList);\r\n console.log('edgeList ', this.edgeList);\r\n console.log('graph_algo ', this.graph_algo);\r\n console.log('Current startNode is ', this.currentStartNode);\r\n console.log('Current endNode is ', this.curr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
wrap fn to protect from modifying the original one
function wrap (fn) { return function () { return fn.apply(this, arguments) } }
[ "function super_fn() {\n if (!oldFn) {\n return\n }\n each(arguments, function(arg, i) {\n args[i] = arg\n })\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Latent Dirichlet Allocation (LDA) model. This abstraction permits for different underlying representations, including local and distributed data structures.
function LDAModel(kernelP, refIdP) { this.kernelP = kernelP; this.refIdP = refIdP; }
[ "function DLC() {\n\t\tthis.initialize.apply(this, arguments);\n\t}", "function LAppModel()\n{\n //L2DBaseModel.apply(this, arguments);\n L2DBaseModel.prototype.constructor.call(this);\n \n this.modelHomeDir = \"\";\n this.modelSetting = null;\n this.tmpMatrix = [];\n}", "function train(model,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds or updates a "Highlight" or "Unhighlight" option in the content action menu.
function addMenuItem( updateOnly ) { var text, tooltip, $oldItem = $( '#ca-highlightcomments' ); if ( updateOnly && !$oldItem.length ) { return; } if ( commentsAreHighlighted ) { text = msg.unhighlightText; tooltip = msg.unhighlightTooltip; } else { text = msg.highlightText; tooltip = msg.hig...
[ "function menuHighlightClick() {\n Data.Edit.Mode = EditModes.Highlight;\n updateMenu();\n}", "function theClickedItem(item) {\n setHighlightItem(item);\n }", "function menuTextClick() {\n Data.Edit.Mode = EditModes.Text;\n updateMenu();\n}", "function i2uiHighlightMenuOption(obj,flag,id,menuid)\r\n{\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
build with images, css, js opt
async function build(){ let imgSrc = './dev/assets/img/*.+(png|jpg|gif|svg)', imgDst = './build/assets/img', jscopy = gulp.src(['./dev/assets/js/**/*.js']).pipe(uglify()).pipe(gulp.dest('./build/assets/js')), csscopy = gulp.src(['./dev/assets/css/**/*.css']).pipe(cleanCSS()).pipe(gulp.dest(...
[ "function happycol_buildGel(args){\n\t//check options and assign variables\n\tif(jQuery(args.theClass + '_gel').length==0){\n\t\tjQuery('body').append(\n\t\t\t'<div class=\"' + args.theatre + '_gel\"></div>'\n\t\t);\n\t}\n\targs.$gel = jQuery(args.theClass + '_gel');\n\targs.$gel.css({\n\t\t'background-color':'#' +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill the users selector with a list of users
function fillUsersSelector($selectItem, userList) { $selectItem.empty(); for (var i = 0; i < userList.length; i++) { var user = userList[i]; $selectItem.append($("<option>").val(user.id).text(user.userName)) } }
[ "function populateUserList() {\r\n var editorIds = new Object();\r\n for (var seg in wazeModel.segments.objects) {\r\n var segment = wazeModel.segments.get(seg);\r\n var updatedBy = segment.attributes.updatedBy;\r\n if (editorIds[updatedBy] == null) {\r\n var user = wazeModel.u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
algorithm for binary search 1. set upper and lower bounds variables at zero and arr.length 1 2. set up a while loop (low <= high) 3. inside of the while loop assign mid = Math.floor(low + (highlow) /2) 4. if statement: check first if arr[mid] equals the value, if so return check next if arr[mid] is less than value, if ...
function binarySearch(arr, value) { let low = 0; let high = arr.length - 1; while (low <= high) { let mid = Math.floor(low + (high - low) / 2); if (arr[mid] === value) { return mid } else if (arr[mid] < value) { low = mid + 1; } else { //arr[mid] > value high = mid - 1; } ...
[ "function binarySearchRecursive(array, value){\n\tlet upperBound = array.length\n\tlet midPoint = Math.round(upperBound / 2);\n\tlet lowerBound = 0;\n\n\tfunction searchIt(){\n\t\tif (upperBound - lowerBound <= 1 && array[midPoint] !== value) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (array[midPoint] === value) {\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
drawSkier() draws the skier on the canvas
drawSkier() { var skierAssetName = this.getSkierAsset(); var skierImage = vars.loadedAssets[skierAssetName]; var x = (vars.gameWidth - skierImage.width) / 2; var y = (vars.gameHeight - skierImage.height) / 2; ctx.drawImage(skierImage, x, y, skierImage.width, skierImage.height); ...
[ "function draw_s() {\n ctx.beginPath()\n canvas_arrow(ctx, passthroughCoords.x - 2, passthroughCoords.y - 2, refractedCoords.x + 2, refractedCoords.y + 2)\n ctx.stroke()\n }", "draw()\n {\n var canvas = document.getElementById(\"CANVAS\");\n var ctx = canvas.getContext(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loadDefaults attempts to load the ExchangeWallet configuration from the default wallet config path on the server and will autofill the page on the subform if settings are found.
async loadDefaults () { // No default config files for seeded assets right now. const walletDef = app().walletDefinition(this.currentAsset.id, this.currentWalletType) if (walletDef.seeded) return const loaded = app().loading(this.form) const res = await postJSON('/api/defaultwalletcfg', { asse...
[ "function setDefaultValues(moduleName, dialog) {\n let promise;\n let defaults;\n\n const form = dialog.querySelector(\"[name = 'settings']\");\n const textinput = document.getElementsByClassName(\"textinput\");\n const labeltext = document.getElementsByClassName(\"labeltext\");\n const checkboxin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit a parse tree produced by KotlinParsermultiLineStringLiteral.
exitMultiLineStringLiteral(ctx) { }
[ "exitMultiLineStringExpression(ctx) {\n\t}", "exitLineStringExpression(ctx) {\n\t}", "exitMultiVariableDeclaration(ctx) {\n\t}", "exitMultiLineStringContent(ctx) {\n\t}", "exitLineStringContent(ctx) {\n\t}", "visitExit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "exitStatementWithoutTra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if an ignore filter was provided execute it on the resource otherwise return false
ignore(resource, context){ return this.ignoreFn ? this.ignoreFn(resource, context) : false; }
[ "exclude(resource, context){\n return this.excludeFn ? this.excludeFn(resource, context) : false;\n }", "shouldBeIgnored() {\n if (!this.json_.tag_)\n return false;\n\n var tag = this.json_.tag_;\n if (!tag.startsWith(\"autogenerated:\"))\n return false;\n\n if (tag == \"autogenerated:ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show and hide background options
function toggleBgOption(theme, bg_type) { jQuery('#gaddon-setting-row-' + theme + '_bg_color, #gaddon-setting-row-' + theme + '_bg_image').hide(); if (bg_type == 'color') { jQuery('#gaddon-setting-row-' + theme + '_bg_color').slideDown(); } if (bg_type == 'image') { jQuery('#ga...
[ "function showHideOptions() {\r\n\r\n // Toggle show options status in CurStepObj and draw code window\r\n // TODO: It is not necessary to draw the entire code window. Separate\r\n // drawCodeWindow() function into 2 (or 3) functions, and call the\r\n // the one responsible for drawing butto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a map of child SVG elements by id.
__createIconMap() { const icons = {}; this.querySelectorAll('[id]').forEach((icon) => { icons[this.__getIconId(icon.id)] = icon; }); return icons; }
[ "function generateElementMap(el, data = null){\n if (!data) {\n data = {};\n data[el.id] = {\n el: el,\n parent: null\n }\n }\n el.children && el.children.forEach(child => {\n generateElementMap(child, data);\n data[child.id] = {\n el: chi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sendRequest / Allows or not to click on the "Sign in" button, according to login and / password values. The button may not be clickable until inputs are correct. / / Parameters : / elt : button. / login : login to be checked. / pass : password to be checked.
function sendRequest(elt, login, pass){ elt.disabled = false; if (passDynListen(pass) && loginDynListen(login)) { elt.disabled = false; return true; } else { elt.disabled = true; } return false; }
[ "clickLoginButton() {\n this.loginButton.waitForDisplayed()\n this.loginButton.click()\n }", "static login() {\n const doc = navigationDocument.documents[navigationDocument.documents.length - 1]\n const e = doc.getElementsByTagName('textField').item(0)\n const user = encodeURIComponent(e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fires events to the dispatcher if the current step in the grid has any notes to be played.
function playPatternStepAtTime(pt) { for (var k in currentPattern) { if (currentPattern[k][currentStep] == '1') { dispatcher.trigger('patterngrid:notehit', k, pt); } dispatcher.trigger('patterngrid:stepchanged', currentStep); } }
[ "function onFootStrike() {\n if(applicationStarted){\n stepTracker();\n }\n}", "function expectedEventsDispatched()/* : Boolean*/\n {\n for (var i/*:uint*/ = 0; i < this._expectedEventTypes$_LKQ.length; ++i )\n {\n var expectedEvent/* : String*/ = this._expectedEventTyp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the User has entered a File Name and confirmed he wants to create a File
function GistCreateFile() { var name = $("div#overlay-body input").val().trim(); CloseOverlay(); // Make sure the Filename is at least 1 charater long and ends with .js if (endsWith(name, ".js")) { if (name.length == 3) { Logger.error("Please enter a valid Filename."); re...
[ "function createNewTextFile(searchInput) {\n //if there is not text input on search submit\n if (!searchInput) {\n return blankFile();\n } else {\n return namedFile(searchInput);\n }\n }", "function FileName(evt) //Alphabates and .\n{\n var charCode = (evt.w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RemoveObsoleteClassRefsScanner This scanner removes references (class attributes) to classes that are obsolete (because they have been removed).
function RemoveObsoleteClassRefsScanner( obsoleteClasses ) { this.obsoleteClasses = obsoleteClasses; }
[ "static unbind(keys, classRef) {\n for (const key of keys) {\n for (const i in listeners[key]) {\n if (listeners[key][i] === classRef) {\n delete listeners[key][i]\n }\n }\n }\n }", "function removeModelClasses() {\n modelClasses = null;\n}", "function removeClass(obj, c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function handles order created event.
async handleOrderItemCreatedEvent(data={}) { let {orderItem,trackId} = data, logger = Logger.create("handleOrderItemCreatedEvent", trackId); logger.info("enter", {orderItem}); // @WARNING : We do not modify stock for orders items generated // from list subscriptions. ...
[ "function newOrder() {\n\tdb.collection(\"currentOrders\").where(\"notify\", \"==\", 1).onSnapshot((snapshot) => {\n console.log(\"New order invoked!\");\n\t\t// console.log(snapshot.docChanges());\n\t\tsnapshot.docChanges().forEach(change => {\n\t\t\tconsole.log(\"change: \",change.doc.data());\n\t\t\t\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Thrown when a module tries to define an already existing hook.
function HookAlreadyExists (message, hook) { RegistryKeyAlreadySet.call(this, message); this.hook = hook; }
[ "function unlinkHookFn () {\n fqHookFilename = fqProjDirname + '/.git/hooks/pre-commit';\n fsObj.unlink( fqHookFilename, function ( error_data ) {\n // Ignore any error\n eventObj.emit( '07LinkHook' );\n });\n }", "function hookErrors() {\n window.onerror = function(msg, url, line, col, err...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the set of matching resources of a given type and properties in the CloudFormation template.
findResources(type, props = {}) { return (0, resources_1.findResources)(this.template, type, props); }
[ "allResourcesProperties(type, props) {\n const matchError = (0, resources_1.allResourcesProperties)(this.template, type, props);\n if (matchError) {\n throw new Error(matchError);\n }\n }", "allResources(type, props) {\n const matchError = (0, resources_1.allResources)(th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
make a FUNCTION that will see if ANY COMBINATION of the INPUT coins make up = AMOUNT IF run code else return 1 make parameters of array and total figure out whats the highest coin in array subtract highest coin from total check if highest coin is higher than remainder IF so subtract again ELSE find highest coin thats l...
function coinCombo(array, total) { var highestElement = Math.max(...array); var orderArray = array.sort(); var coins = Math.floor(total / highestElement); var remainder = total % highestElement; orderArray.pop(); if (remainder === 0) { return coins; } else { return coins + coinCombo(orderArray, re...
[ "function nonConstructibleChange(coins) {\n // Sort array\n const sortedCoins = coins.sort((a, b) => (a - b));\n let change = 0;\n // Find smallest sum that does not exist in array\n // Algo: If we have coins sorted - if next coin is greater than 1st coin + 1, we cannot make 1st coin + 1 change\n for (let i =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates the message field and returns true if valid. If reporting is true it'll display a message if the field is not valid.
function validateMessageField(reporting = true) { var messageField = $("#message"); if (!hasText(messageField)) { console.log("message error"); setError(messageField, true); if (reporting) { displayError("What, cat got your tongue?"); } return false; } els...
[ "function validateNameField(reporting = true) {\n var nameField = $(\"#name\");\n if (!hasText(nameField)) {\n console.log(\"name error\");\n setError(nameField, true);\n if (reporting) {\n displayError(\"You need to tell me your name!\");\n }\n return false;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The first frame in an environment is the "innermost" frame. The tail operation takes you to the "enclosing" environment
function first_frame(env) { return head(env); }
[ "tail() {\n return null;\n }", "restore_stack(stuff){\n const v = stuff.stack;\n const s = v.length;\n for(var i=0; i<s; i++){\n this.stack[i] = v[i];\n }\n this.last_refer = stuff.last_refer;\n this.call_stack = [...stuff.call_stack];\n this.tco_counter = [...stuff.tco_counter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw Col for note
function drawCol(note) { const { notes_insert } = NOTES_DOM; const notesCOL = createNoteCol(note); if (!notesCOL) return; notes_insert.append(notesCOL); }
[ "function drawFlag(row, col) {\n var path = new Path2D(game.path_flag);\n ctx.fillStyle = \"#d63031\";\n x_px = col * game.cell_size_px + game.cell_size_px / 7;\n y_px = row * game.cell_size_px + game.cell_size_px / 7;\n ctx.translate(x_px, y_px);\n ctx.fill(path);\n ctx.translate(-x_px, -y_px)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a fuction called `last(input)` that returns the last character of a string
function last(input) { var stringLength = input.length; return input.charAt(stringLength - 1); }
[ "function removeLastChar (string) {\n return string.slice(0, string.length -1)\n}", "function getLastWord() {\n console.log(\"get last word start\");\n var lastWord = \"\";\n \n var input = document.getElementById(\"searchInput\").value;\n \n var parsedInput = input.substr(0, input.length).repl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cancels and closes the dialog with the specified uniqueDialogCssClass identifier, if one exists uniqueDialogCssClass : CSS class to be used as the dialog's ID (should be unique to the dialog) buttonId : The button id to use when closing the dialog. Defaults to DIALOG_CANCELED
function cancelDialogIfOpen(uniqueDialogCssClass, buttonId) { Dialogs_get().cancelModalDialogIfOpen(uniqueDialogCssClass, buttonId); }
[ "@action closeDialog() {\r\n\t\tif (this.dialog) this.dialog.opened = false;\r\n\t}", "cancel () {\n this.close();\n this._reject(new Error('User closed dialog.'));\n }", "function closeSuccessDialog() {\n successDialog.classList.add(\"dialog-success__hide\");\n // Timeout for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds the new drive
async function addNewDrive() { const driveName = document.getElementById("drive-name").value const userPermissionList = generatePermissionList() const data = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ info: { drivePath: path, ...
[ "function openAddNewDriveWindow() {\n activateOverlay()\n document.getElementById(\"drive-list\").style.pointerEvents = \"none\";\n document.getElementById(\"add-new-drive-window\").style.display = \"block\"\n document.getElementById(\"close-add-drive-window\").addEventListener(\"click\", closeAddNewDriveWindow...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load gym details master
function LoadGymDetails(){ $(loader).html('<i class="fa fa-spinner fa-4x fa-spin">'); var id = $(DGYM_ID).attr( "name" ); $.ajax({ url: window.location.href, type:'POST', data:{autoloader:'true',action:'load_gym_details',type:'master',id:id}, success: function(data){ data = $.parseJSON(data); ...
[ "function loadGameMasterChunk(filename){\n\n\t\t\t$.getJSON( webRoot+\"data/gamemaster/\"+filename+\".json?v=\"+siteVersion, function( data ){\n\t\t\t\tobject[filename] = data;\n\n\t\t\t\tchunksLoaded++;\n\n\t\t\t\tif(filename == \"pokemon\"){\n\t\t\t\t\tobject.pokemon.sort((a,b) => (a.dex > b.dex) ? 1 : ((b.dex > ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change default ad group bid by "cpc" units.
function changeBid(adGroup,cpc){ var adGroupCpc = adGroup.getKeywordMaxCpc(); adGroupCpc = adGroupCpc + adGroupCpc * cpc; adGroupCpc = Number(adGroupCpc.toFixed(4)); // set precision adGroup.setKeywordMaxCpc(adGroupCpc); Logger.log('Changing adGroup: '+adGroup.getId()+' '+adGroup.getName()+' from:'+adGr...
[ "function decreaseBid(target) {\n var newBidModifier = target.getBidModifier() - BID_INCREMENT;\n newBidModifier = Math.max(newBidModifier, 0.1); // Modifier cannot be less than 0.1 (-90%)\n\n // TODO: Reset bid modifier to 0% (1.0) if the current conversion rate is below avg conversion rate\n // var ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query the PEDASI API for data source internal metadata and render it into the 'metadataInternal' panel.
function populateMetadataInternal() { "use strict"; const table = document.getElementById("metadataInternal"); const url = getBaseURL(); fetch(url).then(function (response) { if (response.ok) { return response.json(); } throw new Error("Internal metadata request fa...
[ "function privateDisplaySongMetadata(){\n\t\t/*\n\t\t\tSets all elements that will contain the active song's name metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"name\"]') ){\n\t\t\tvar metaNames = document.querySelectorAll('[amplitude-song-info=\"name\"]');\n\t\t\tfor( i = 0; i < metaNa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Class: mxCoordinateAssignment Sets the horizontal locations of node and edge dummy nodes on each layer. Uses median down and up weighings as well as heuristics to straighten edges as far as possible. Constructor: mxCoordinateAssignment Creates a coordinate assignment. Arguments: intraCellSpacing the minimum buffer betw...
function mxCoordinateAssignment(layout, intraCellSpacing, interRankCellSpacing, orientation, initialX, parallelEdgeSpacing) { this.layout = layout; this.intraCellSpacing = intraCellSpacing; this.interRankCellSpacing = interRankCellSpacing; this.orientation = orientation; this.initialX = initialX; this.parallelEd...
[ "toCoordinate() {\n assertParameters(arguments);\n \n return new Coordinate(this._width, this._height);\n }", "constructor(x = 0, y = 0) {\n this.x = x; // position for x \n this.y = y; // position for y\n }", "function Node(x,y) {\n\tthis.x = x;\n\tthis.y = y;\t\n}", "constructor(m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Captures a screen and send a message with captured data
function captureScreen() { chrome.tabs.captureVisibleTab({format: 'png'}, function (imgData) { sendMessage('saveImg', imgData) }); }
[ "function captureScreenshot() {\n setTimeout(() => {\n Page.captureScreenshot({ format: 'png' }).then(afterCapture);\n }, timeout);\n }", "function camera_sent(viewer, key) {\n logmessage(\"=> \" + viewer + \": \" + key);\n}", "function Capture() {\n setInterv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
undefined since f doesn't define baz Callbacks invocation of callback sets the context
function foo(callback){ callback(); }
[ "function callback(callback){\n callback()\n}", "static fromCallback (f) {\n return new Signal(emit => {\n f((e, a) => {\n if (typeof e !== 'undefined' && e !== null) {\n emit.error(e)\n } else {\n emit.next(a)\n }\n })\n })\n }", "hasCallback() {}", "s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get All competitions of this clubs
function getCompetitions(req,res) { process.nextTick(() => { let query = Competition.find({}).where('club').equals(req.params.id).populate('place').select('_id scheduledDate description state place'); query.exec((err,competitions) => { if(err) return res.status(500).json({ status: 500, message: "Oops so...
[ "get_all_citations(){\r\n\t\t\tlet citations = this.citations.slice();\r\n\t\t\tshuffle(citations);\r\n\r\n\t\t\treturn citations;\r\n\t\t}", "function addActiveCompetitions(data) {\n let activeCompetitions = \"\";\n data.forEach(function (competition) {\n activeCompetitions += `<p>${competition.name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets and sets the config map used with the last update for Stack matching stack name. It will overwrite all configuration in the Pulumi..yaml file in Workspace.WorkDir().
refreshConfig(stackName) { return __awaiter(this, void 0, void 0, function* () { yield this.runPulumiCmd(["config", "refresh", "--force", "--stack", stackName]); return this.getAllConfig(stackName); }); }
[ "static merge (config) {\n currentConfig = assign({}, currentConfig, config);\n }", "updateConfig(application) {\n const updatedConfig = { };\n const configs = Array.prototype.slice.call(arguments, 1);\n\n return this.getConfig(application).then(existingConfig => {\n ld.assign....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Algoritma 1. Memahami definisi mendaki: satu kali mendaki adalah 1 kali naik dan 1 kali turun 1. Buat function countValley dengan sebuah parameter (road) 1.1 road adalah sebuah string 2. Buat variabel bernama lowestPoint dan inisiasikan dengan angka 0 3. Buat variabel bernama naikTurun dan inisiasikan dengan angka 0 4....
function countValley(road){ let lowestPoint = 0; let naikTurun = 0; let mendaki = 0; for(let i = 0 ; i < road.length ; i++ ){ if( road[i] == 'U'){ naikTurun += 1 } else if( road[i] == 'D'){ naikTurun -= 1 } if( na...
[ "function tentukanDeretGeometri(arr) {\n // you can only write your code here!\n \n var selisih =[]\n\n if(arr[0] < arr[1]){\n for (var i = 0; i < arr.length-1; i++){\n \n selisih += arr[i+1]/arr[i]\n // console.log(\"ini adalah arr[i+1] : \"+arr[i+1])\n // console.log(\"ini adala...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for setting alternate row colors in the table for classsummary.html page.
function setRowColorClassTableSummary(doc) { var elements = getElementsByClassName(doc, "summaryTable"); var table = elements[0]; if (table){ var rowNum = 0; for (var i = 1,len = table.rows.length; i < len; i++) { if(table.rows[i].style.display.indexOf('none') == -1) ...
[ "function adjustRowsColor(mainTable)\n{ \n if(mainTable=='asns')\n\t mainTable = document.getElementById('asns');\n\t \n\tvar rows = mainTable.getElementsByTagName(\"tr\");\n\tvar rowNumber = 0;\n\t\n\tfor(var j=0; j<rows.length; j++)\n\t{\n if(isVisible(rows[j]))//process only visible rows\n\t\t{\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The GlobalStateManager is a global singleton that manages application state. Class declaration
function GlobalStateManager() { // Holds the currently-selected project this.currentProject = null; // Holds the currently-selected file this.currentFile = null; // Length of time to display for realtime graphs, in seconds this.realtimeTimeWindow = 600; // Holds incrementing graph identifier this.nextGraphI...
[ "function AppManager(){\n}", "function Globals() {\r\n\r\n\t/** @private */ var store = {};\r\n\t/** @private */ var count = 0;\r\n\t\r\n\t/**\r\n\t * Returns an array of all global variables names.\r\n\t * @public\r\n\t */\r\n\tthis.getValues = function() {\r\n\t\tvar result = new Array();\r\n\t\tfor (element in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The last operator selected will determine which operation performed Perform operation on total and display to output
function getTotal(){ switch (lastOperator[lastOperator.length - 1]){ //Addition case operators[0]: total += currentVal; primaryOutput.innerHTML = Number(total.toFixed(6)); break; //Subtraction case operators[1]: total -= currentVal; primaryOutput.innerHTML = Number(total.to...
[ "function updateTotal(){\n if(lastOp == \"+\"){\n $(\"#history\").html(lastVal + \"+\" + currentVal)\n total = parseFloat(lastVal) + parseFloat(currentVal);\n lastVal = total;\n currentVal = total;\n $(\"#total\").html(total.toString());\n }\n if(lastOp == \"-\"){\n $(\"#histo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add new domain to database and find/set its grade
function addDomain(domain){ db.collection('domains').insert({"domain": domain, "grade": "Calculating"}, function(err, result) {}); testSSL(domain, 0, function(grade){ db.collection('domains').update({"domain": domain},{$set: {"grade": grade}}, function(err, result){}); }); }
[ "addGrades(grade) {\r\n this.grades.push(grade);\r\n this.write();\r\n }", "function add(grade) {\n\tthis.grades.push(grade);\n}//end add function", "function addLearner() {\n var id = uuidv4();\n\n ref\n .doc(id)\n .set({\n id: id,\n firstName: firstNa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
once the info has been collected this handler recommends meals
canHandle(handlerInput) { const attributesManager = handlerInput.attributesManager; const sessionAttributes = attributesManager.getSessionAttributes(); const slots = ["timeOfDay", "cuisine", "allergies", "diet"]; // the meal recommendations are based on these factors and can only be done once they have be...
[ "function bookRecommendations () {\n \n fetch(\n 'https://api.nytimes.com/svc/books/v3/lists/current/e-book-fiction.json?api-key=HXMcUKu4hWhoZPQBW99bGZ9An0FdbWEl'\n )\n .then(function(res) {\n return res.json();\n })\n .then(function(res) {\n console.log(res);\n dis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
const lenu32 = readVaruint32(); eatBytes(lenu32.nextIndex); console.log("len", lenu32); const strlen = lenu32.value; dump([strlen], "string length"); const bytes = readBytes(strlen); eatBytes(strlen); const value = utf8.decode(bytes); return [t.moduleNameMetadata(value)]; } this section contains an array of function na...
function parseNameSectionFunctions() { var functionNames = []; var numberOfFunctionsu32 = readU32(); var numbeOfFunctions = numberOfFunctionsu32.value; eatBytes(numberOfFunctionsu32.nextIndex); for (var i = 0; i < numbeOfFunctions; i++) { var indexu32 = readU32(); var index = indexu32.v...
[ "function getOperations(){ //-------------> working\n\nvar count = codeLines.length;\n\nfor(var i=0; i<count; i++){ \n\n\t\tvar commentTest = (/@/.test(codeLines[i].charAt(0))); //Checking for comments\n\t\tvar textTest = (/.text/.test( codeLines[i])); //checking for .text keyword \n\t\tvar globalTest = /.glob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draws point using point object specs
function drawPoint() { push(); noStroke(); fill(String(this.color)); ellipse(this.x, this.y, this.strokeSize, this.strokeSize); pop(); }
[ "function point(xx,yy){\nthis.x = xx;\nthis.y = yy;\n}", "display() {\n //set the color\n stroke(this.element*255) ;\n //draw the point\n point(this.identity.x,this.identity.y)\n }", "function ShapePoint( options )\r\n{\r\n\tthis.instanceType = \"ShapePoint\";\r\n\tthis.x = 0 ;\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new verifier.
function verifier(value, name) { this._value = value; this._name = name; }
[ "async createVoter(ctx, args) {\n\n args = JSON.parse(args);\n\n //create a new voter\n let newVoter = await new Voter(ctx, args.voterId, args.registrarId, args.firstName, args.lastName);\n\n //update state with new voter\n await ctx.stub.putState(newVoter.voterId, Buffer.from(JSON.stringify(newVoter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add more input fields for contestants on request
function addFields () { $("#contestantsForm").append('<input type="text" /><br/><input type="text" /><br/>'); }
[ "function addMoreEducation(){\n\tclear_form_elements(\"#edu-form\");\n\t$(\".un-editable-outer\").show();\n\t$(\"#education-form\").slideDown();\n\t$(\"input[name=add-more]\").hide();\n\t$(\"input[name=save-eduinfo]\").show();\n\t$(\"a#cancel-education\").fadeIn(\"slow\");\n\t\n\t$(\"input[name=update-eduinfo]\").h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates drain for condition status panel
function updateDrainCheckbox (callback,silently,eventInfo) { var done = _.once(function () { //TAS.debug("leaving PFConditions.updateDrainCheckbox"); if (typeof callback === "function") { callback(); } }); getAttrs(["condition-Drained", "condition_is_drained"], function (v) { var levels = parseInt(v["cond...
[ "async startMonitor() {\n this.monitor = true\n this.fill()\n this.node.swarm.db.events.subscribe(() => {\n //update the data on swarm update if monitoring is On\n this.fill()\n })\n }", "statusUpdatePhase() {\n let _filter = (stat)=>{\n if (--stat.turn > 0) return true;\n Fiel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove '.tecellselected' class from all of table Cell
removeClassAttrbuteFromAllCellsIfNeed() { const cells = domUtils.findAll( this.wwe.getBody(), `td.${TABLE_CELL_SELECTED_CLASS_NAME},th.${TABLE_CELL_SELECTED_CLASS_NAME}` ); cells.forEach(node => { removeClass(node, TABLE_CELL_SELECTED_CLASS_NAME); if (!node.getAttribute('class')) {...
[ "function MDUO_deselect_selected_tblrows(tblBody){\n console.log(\"========== MDUO_deselect_selected_tblrows ========== \");\n console.log(\" tblBody\", tblBody);\n if (tblBody){\n const selected_tablerows = tblBody.querySelectorAll(\"[data-selected=true]\")\n console.log(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the balance of a Dash address
function getDashBalance(dashAddress) { var response = UrlFetchApp.fetch('http://explorer.darkcoin.io/chain/Dash/q/addressbalance/' + dashAddress); var json = response.getContentText(); var data = JSON.parse(json); return data; }
[ "async balanceOf(address) {\n await this.getContract()\n return await this.contract.methods.balanceOf(address).call()\n }", "function getBalance(btcAddress) {\n var response = UrlFetchApp.fetch('http://blockchain.info/address/' + btcAddress + '?format=json');\n var json = response.getContentText();\n va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dynamically create the portfolio list in the portfolio folder
function populatePortfolio() { for (project in portfolio) { // Create a list item for each project, add appropriate classes and click events. const listItem = document.createElement('li'); addClass(listItem, ['folioItem', `${portfolio[project].listClass}`]); listI...
[ "@action\n createPortfolio(portfolioName) {\n requester.Portfolio.create(portfolioName)\n .then(() => {\n this.getPortfolios(); // gets new portfolios\n })\n .catch(err => console.log(err));\n }", "function addPortfolio() {\n const jsPortfolio = document.querySelector('.portfolio-add...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Center x,y of the current map
function getMapCenter() { var mapcenter = { "point_x": map.getCenter().lng, "point_y": map.getCenter().lat } return mapcenter; }
[ "function centerCleveland(){\n map.setView([41.502405, -81.673895],13);\n}", "_setCenter() {\n\t\tlet width = this._dim.width;\n\t\tlet height = this._dim.height;\n\n\t\tlet leftDiff = Math.round((this._dim.areaWidth - width) / 2);\n\t\tlet topDiff = Math.round((this._dim.areaHeight - height) / 2);\n\n\t\tlet p ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the raw websocket message data to a valid message.
function parseMessage(data) { if (isMessage(data)) { return data; } if (typeof data !== 'string') { throw new Error('Message not parsable'); } const message = JSON.parse(data); if (!isMessage(message)) { throw new Error('Invalid message...
[ "_wsHandleOnMessage(message) {\n console.info(message);\n if (message.data.split(';')[0] === 'metadata') {\n\n console.info(JSON.parse(message.data.split(';')[1]));\n this.setState({\n metadata: JSON.parse(message.data.split(';')[1]),\n });\n\n }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize window drag drop events, dragFilesUpload and sendIMages.
initWindowDnd() { console.log('initWindowDnd'); window.addEventListener("dragenter", function (e) { document.querySelector("#dropzone").style.visibility = ""; document.querySelector("#dropzone").style.opacity = 1; }); window.addEventListen...
[ "function init()\n {\n var f = 'MovableDividers.init()';\n UTILS.checkArgs(f, arguments, []);\n\n $(framesContainerDiv).append(tlDiv);\n $(framesContainerDiv).append(v_Div);\n $(framesContainerDiv).append(trDiv);\n $(framesContainerDiv).append(DIV({style: 'clear: both;'}));\n $(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shows class_view, and removes group_id from sessionStorage if disconnect is not true
function group_leave_response(username, class_id, group_id, disconnect) { // This function must call socket.groups_get(username, class_id) $login_view.hide(); $class_view.show(); $group_view.hide(); if(!disconnect){ sessionStorage.removeItem('group_id'); } }
[ "function logout_response(disconnect) {\n $login_view.show();\n $class_view.hide();\n $group_view.hide();\n\n\n $error_username.hide();\n $error_class_id.hide();\n\n $class_id.css(\"border-color\", null);\n $username.css(\"border-color\", null);\n\n $class_id.val(\"\");\n $username.val(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
mouseClicked : if mouseClicked, check to see if a creature is clicked on if so, replace creature with a new instance of Creature
function mouseClicked() { let replaceMe = -1; for (let i = 0; i < menagerie.length; i++) { if (menagerie[i].within(mouseX, mouseY)) { replaceMe = i; } //end if } //end for loop that iterates through menagerie if (replaceMe > -1) { let origX = menagerie[replaceMe].x;...
[ "function mouseClicked() {\n allFish.push(new Fish(mouseX, mouseY,random(2),random(5,80)));\n}", "function initMouse() {\r\n\tGame.mouse = Crafty.e(\"2D, Mouse\").attr({\r\n\t\tw : Game.width(),\r\n\t\th : Game.height(),\r\n\t\tx : 0,\r\n\t\ty : 0\r\n\t});\r\n\t//Everytime somewhere is clicked, this method is ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(For IE <=9) Starts tracking propertychange events on the passedin element and override the value property so that we can distinguish user events from value changes in JS.
function startWatchingForValueChange(target,targetInst){activeElement=target;activeElementInst=targetInst;activeElement.attachEvent('onpropertychange',handlePropertyChange);}
[ "on_change(ev){\r\n\t\tthis.val = this.get_value();\r\n\t\t// hack to get around change events not bubbling through the shadow dom\r\n\t\tthis.dispatchEvent(new CustomEvent('pion_change', { \r\n\t\t\tbubbles: true,\r\n\t\t\tcomposed: true\r\n\t\t}));\r\n\t\t\r\n\t\tif(!this.hasAttribute(\"noupdate\")){ //Send valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTIONS//////// Generates letter box base on number of answer letters
function genBoxes() { for (var i = 0; i < answer_length; i++) { if (answer[i] != " ") { var letter = answer[i].toUpperCase(); // var $newBoxDiv = $("<div class='letterBox'></div> ").text(answer[i].toUpperCase()); // var $newBoxDiv = $("<div class ='flip-container'> <div...
[ "function start(){\n\tvar div = \"\";\n\tfor ( i = 0; i < 25; i++) {\n\t\tvar element = \"let\" + i;\n\t\tdiv = div + '<div class = \"letter\" onclick = \"check('+i+')\" id=\"'+element+'\">'+letters[i]+'</div>';\n\t\tif ((i + 1) % 7 == 0) div = div + '<div style = \"clear:both;\"></div>';\n\t}\n\tdocument.getElemen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build an array of node paths containing the entire ancestry of the current node path. NOTE: The current node path is included in this.
function getAncestry() { var path = this; var paths = []; do { paths.push(path); } while (path = path.parentPath); return paths; }
[ "pathList(){\n let pathList = []\n let current = this\n while(current){\n if(current.pathId()) pathList.unshift(current.pathId())\n current = current.parent\n }\n return pathList\n }", "function getNodesChain(node) {\n var chain = [];\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves a value current towards target. This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta. Negative values of maxDelta pushes the value away from target.
static MoveTowards(current, target, maxDelta) { let result = 0; if (Math.abs(target - current) <= maxDelta) { result = target; } else { result = current + Scalar.Sign(target - current) * maxDelta; } return result; }
[ "static MoveTowardsAngle(current, target, maxDelta) {\n const num = Scalar.DeltaAngle(current, target);\n let result = 0;\n if (-maxDelta < num && num < maxDelta) {\n result = target;\n }\n else {\n result = Scalar.MoveTowards(current, current +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper function to create a unit with a fixed prefix
function fixedUnit(str) { var unit = type.Unit.parse(str); unit.fixPrefix = true; return unit; } // Source: http://www.wikiwand.com/en/Physical_constant
[ "function addPrefixZero(num){\n if(num<10){\n return \"0\"+num;\n }\n return num;\n}", "function parsePrefixUnitPower(text) {\n\t\tlet pow = 1, u = null; //unit power, the unit object\n\n\t\t//try to find simply as {prefix + unit}\n\t\tu = parsePrefixUnit(text, pow);\n\t\tif(u) {return u;}\n\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if a bid increase is needed, false otherwise
function isBidIncreaseNeeded(stats, currentBid, baselineConversionRate) { var conversions = stats.getConversions(); var conversionRate = stats.getConversionRate(); var position = stats.getAveragePosition(); var targetBid = (conversionRate / baselineConversionRate) if (isBidChangeSignificant(current...
[ "function isBidDecreaseNeeded(stats, currentBid, baselineConversionRate) {\n var conversions = stats.getConversions();\n var conversionRate = stats.getConversionRate();\n var targetBid = (conversionRate / baselineConversionRate)\n\n if (isBidChangeSignificant(currentBid, targetBid)) {\n var isDec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merges the browsing config provided with the current browsing config
function mapBrowsingConfig(currentConfig, config) { if (!config) return currentConfig; var validatedConfig = getValidatedBrowsingConfig(config); return __assign({}, currentConfig, validatedConfig); }
[ "static merge (config) {\n currentConfig = assign({}, currentConfig, config);\n }", "cb(config) {\n //you have access to the gulp config here for\n //any extra customization after merging => don't forget to return config\n return merge(config, serverConfig);\n }", "updateConfig(application) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the total duration of the videos from JSON.
function inventory_json_to_total_duration(data) { var total_duration = 0; for (var i = 0, len = data.events.length; i < len; i++) { var event = data.events[i]; total_duration += event.event_duration; } return total_duration; }
[ "function totalVideosDuration(channel) {\n let totalDuration = 0;\n channel.videos.forEach((video) => (totalDuration += video.duration));\n return totalDuration;\n\n // Alternative Solution:\n // return channel.videos.reduce(\n // (totalDuration, video) => totalDuration + video.duration,\n // 0\n // );\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The main function to check whether a given graph contains cycle or not
function isCycle(graph ) { var parent = [-1,-1,-1]; // Iterate through all edges of graph, find subset of both // vertices of every edge, if both subsets are same, then // there is cycle in graph. for(var i = 0; i < graph.E; ++i) { var x = find(parent, graph.edges[i].src); ...
[ "function cyclicArray(arr){\n let i=0, \n count =0;\n //create checks to see if arr[0] or i itself are out of bounds of the array, if so exit the loop\n while((i >=0 && arr[i]>=0) || (i <arr.length && arr[i] <arr.length)) {\n //if the count is greater than arr.length-1 that means one element is v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the RESTOCK function from a selection within start() First we query the homework11_db.auctionItems table, then we allow the user to input the restock amount via an Inquirer prompt
function restockAuction() { connection.query("SELECT * FROM auctionItems", function(err,results) { if (err) throw err; console.log(results); inquirer.prompt([{ name: "choice", type: "rawlist", choices: function(){ var choiceArray = []; ...
[ "function firstPrompt() {\n inquirer\n .prompt([\n { name: \"item\",\n type: \"input\",\n message: \"\\n What is the Id of the product you want to buy? \",\n validate: function (value) \n {\n if (isNaN(value) === f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change timeline index and update regions accordingly
function shiftTimeline(newTimelineIdx) { timelineIdx = newTimelineIdx; for(ii = 0; ii < earth.regions.length; ii++) { earth.regions[ii].setStats(matrixInfected[ii][timelineIdx]); } }
[ "function changeRegion(array, index, region) {\n array[index].region = region;\n return array\n}", "assignRegions(indices, callback = null) {\n const color = this.getColor();\n\n // Modifying the new data before setting it as the state\n let currentData = cloneDeep(this.state.scenarioData);\n le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initializes function chain to pull info out of json file, when complete fires triggered
function init() { loadJSON(function(response) { let actual_JSON = JSON.parse(response); triggered(actual_JSON); }); }
[ "function LoadJson(){}", "function readStartingData(){\n readUser = JSON.parse(fs.readFileSync('data/user.json'));\n listDoc = JSON.parse(fs.readFileSync('data/documents.json'));\n}", "static LoadCARender(json, callback)\n {\n // stops attempting to load file if there is no file\n if (json ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an instance of DialogController.
function DialogController(renderer, settings, resolve, reject) { this.resolve = resolve; this.reject = reject; this.settings = settings; this.renderer = renderer; }
[ "initDialog() {\n this.view = new InviteDialogView(this);\n }", "function Dialog() {}", "newWorkspaceDialog() {\n\t\tlet Dialog_SelectWorkspace = require(path.join(__rootdir, \"js\", \"dialogs\", \"selworkspace.js\"))\n\t\tnew Dialog_SelectWorkspace(600, \"\", (result) => {\n\t\t\tif(result === false)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the Range to that new span tag insert. This function works well when no child span is rendered. / harmony default export
function createRangeToSpan(span) { const { textNode, start, end } = getRenderingPosition(span) if (!textNode) { throw new Error( `The textNode on to create a span is not found. ${span.id}` ) } if (start < 0) { throw new Error(`start must be positive, but ${sta...
[ "function createSpan(){\n return document.createElement('span');\n}", "getRangeStart() {\n return ChromeVoxState.instance.getCurrentRange().start.node;\n }", "getSelectedRange() {\n let range;\n if (!Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"isNullOrUndefined\"])(this.start...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Binary search for GB18030. Returns largest i such that table[i] <= val.
function findIdx(table, val) { if (table[0] > val) return -1; var l = 0, r = table.length; while (l < r-1) { // always table[l] <= val < table[r] var mid = l + ((r-l+1) >> 1); if (table[mid] <= val) l = mid; else r = mid; } return l; }
[ "function binarySearch(arr, value) {\n let low = 0;\n let high = arr.length - 1;\n\n while (low <= high) {\n let mid = Math.floor(low + (high - low) / 2);\n if (arr[mid] === value) {\n return mid\n } else if (arr[mid] < value) {\n low = mid + 1;\n } else { //arr[mid] > value\n high = m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO(sort) remove this when old style is deprecated This breaks the binding for allChangedBrowserSnapshotsSorted, specifically so that when a user clicks approve, the snapshot stays in place until reload. Called by the route when entered and snapshots load. Called by polling when snapshots reload after build is finishe...
initializeSnapshotOrdering() { if (!this.launchDarkly.variation('snapshot-sort-api')) { const orderedBrowserSnapshots = {}; // Get snapshots without making new request const buildSnapshotsWithDiffs = this.store .peekAll('snapshot') .filterBy('build.id', get(this, 'build.id')) ...
[ "function loadHashes() {\n global_hashes = new Set([]);\n for (note of raw_notes) {\n hashes = note[\"hashes\"];\n if (hashes == null) {\n continue;\n }\n for (hash of hashes) {\n global_hashes.add(hash);\n }\n }\n renderHashes(Array.from(global_h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a module, and the list of modules for this current branch, ensure that each of the dependencies of this module is evaluated (unless one is a circular dependency already in the list of seen modules, in which case we execute it) Then we evaluate the module itself depthfirst left to right execution to match ES6 modu...
function ensureEvaluated(moduleName, seen, loader) { var entry = loader.defined[moduleName]; // if already seen, that means it's an already-evaluated non circular dependency if (!entry || entry.evaluated || !entry.declarative) return; // this only applies to declarative modules which late-execut...
[ "function breakCircularDependencies(modules) {\n\n const byName = new Map();\n modules.forEach(mod => byName.set(mod.name, mod));\n \n // Make a list of nodes \n const nodes = Array.from(byName.keys());\n // An Array<Array<number>> array for the edges\n const edges = [];\n\n // Build the adjacencyList\n no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets fired on click of submit details and updates the merchant details to the current merchant
submitDetails(){ Keyboard.dismiss(); if(this.handleButtonValidation()){ return; } let merchantDetails = { ...this.props.merchantDetails, merchantName: this.state.merchantName, businessName: this.state.businessName, phoneNumber: ...
[ "function postEditCommodityAPI() {\n var msg = callAPI(uRL + '/' + idManufacturer, \"GET\");\n if(msg)\n {\n $('#manufacturer-id').val(msg['tradeId']);\n $('#manufacturer-name').val(msg['companyName']);\n $('#manufacturer-address').val(msg['address']['street']);\n }\n else\n {\n alert(\"Không lấy ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pizzaObject constructor, used to pass user selection to pizzaobject
function pizzaObject(flavour,size,crust) { this.flavour=flavour; this.size=size; this.crust=crust; this.delivery=delivery; this.price=flavour[1]+size[1]+crust[1]+deliverySelect[1]; }
[ "function Pizza(toppings, size){\n this.toppings = [];\n this.size = size;\n}", "function selectPokemon(){\n var choosePokemon = prompt(\"Choose a Pokemon: BULBASAUR, CHARMANDER, SQUIRTLE, PIKACHU, DRATINI, EEVEE, MEOWTH, or RATTATA?\").toLowerCase();\n if (choosePokemon === \"bulbasaur\") {myPokemon = new Bu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the field props based on the key
static getFieldProps(key, props){ return { iconmap: IconMap[key], id : key, name : key, value : props.values?.[key], error : props.errors?.[key], }; }
[ "kvProps(key: string, name: ?string = null) {\n let finalName = name;\n if (!finalName) {\n if (/^[a-zA-Z_][a-zA-Z_0-9]*$/.test(key)) {\n finalName = key;\n } else {\n throw new Error(`HrQuery::kvProps expected either the second argument to be provided, or for the first argument to be ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the locale data for a given locale.
function findLocaleData(locale) { const normalizedLocale = normalizeLocale(locale); let match = getLocaleData(normalizedLocale); if (match) { return match; } // let's try to find a parent locale const parentLocale = normalizedLocale.split('-')[0]; match = getLocaleData(parentLocale);...
[ "function getLocale () {\n return locale\n}", "function _getLocale(name) {\n\treturn _locales[name] || _locales.$def;\n}", "async getLocales(req, _id) {\n const criteria = {\n aposDocId: _id.split(':')[0]\n };\n if (!self.apos.permission.can(req, 'view-draft')) {\n criter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If there are any pending deletes for the onDemand buffer, this will rotate through them and delete them
cleanOnDemandBuffer() { if (this._pendingOnDemandDeletes.length > 0) { var pending = this._pendingOnDemandDeletes.shift(); this.deletePendingOnDemand(pending.delete_range); } }
[ "resetOnDemandBuffer()\n {\n const video = this.playBuffer();\n this._pendingOnDemandDeletes = [];\n for (var rangeIdx = 0; rangeIdx < video.buffered.length; rangeIdx++)\n {\n let start = video.buffered.start(rangeIdx);\n let end = video.buffered.end(rangeIdx);\n this.deletePendingOnDema...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hides the posts div if there are no posts in the posts area
function checkPostsDisplay(){ if($('#posts').children().length == 0){ $('#posts').hide(); }else{ $('#posts').show(); } }
[ "function hideDashboardPostboxes(){\n var dashboardContainer = jQuery('#dashboard-widgets');\n if(dashboardContainer.length > 0){\n jQuery('#postbox-container-2').remove();\n jQuery('#postbox-container-3').remove();\n jQuery('#postbox-container-4').remove();\n }\n }", "removeBlogPosts() {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to read a list of elements (if columns is a number 2dim array, if array of strings object as in readline)
readList(rows, columns, format) { const ret = []; for (let i = 0; i < rows; i++) { ret.push(this.readLine(columns, format)); } return ret; }
[ "function readListString(row,firstDataRow){\r\n\tretString = \"\";\r\n\tvalue = \"\";\r\n\tset(\"V[firstVisRow]\", _listfirstvisiblerow);\r\n\tset(\"V[lastVisRow]\", _listlastvisiblerow);\r\n\tset(\"V[lastRow]\", _listlastrow);\r\n\tfirstVisRow = parseInt(firstVisRow,10);\r\n\tlastVisRow = parseInt(lastVisRow,10);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
validate the response to the test request
validateResponse (data) { Assert.deepEqual(data, {}, 'request should return empty response'); }
[ "function responseValid(response, data) {\n\tmessage = new Response();\n\tmessage.status = \"valid\";\n\tmessage.data = data;\n\n\tresponse.writeHead(200, {\"Content-Type\": \"text/plain\"});\n\tresponse.write(JSON.stringify(message));\n\tresponse.end();\n}", "function validateSpeechFailUPResponse(response) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends an initial streamToken to the server, performing the handshake required to make the StreamingWrite RPC work. Subsequent calls should wait until onHandshakeComplete was called.
Sr() { // TODO(dimond): Support stream resumption. We intentionally do not set the // stream token on the handshake, ignoring any stream token we might have. const t = {}; t.database = Jn(this.N), this.wr(t); }
[ "streamHandshakeHandler(msg) {\n\n // Also his only role is to receive the message and log it. It doesn't even\n // do anything useful with it. Gods what a stupid handler.\n console.log(JSON.parse(msg.data));\n\n let start_msg = {\n \"client_id\": this.id,\n \"rover...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the current query as the kind of 'item' that is used everywhere
function itemFromCurrentQuery() { var params = getSearchParameters(); params.title = dojo.byId("queryTitle").value; params.comment = dojo.byId("queryComment").value; params.query = dojo.byId("query").value; return params; }
[ "getCurrentItem() {\n\t\t\tlet itemID = currentAdventure.rooms[currentRoom].item_id;\n\t\t\t\n\t\t\tif (!itemID)\n\t\t\t\treturn null;\n\n\t\t\tlet items = currentAdventure.items;\n\t\t\tlet itemObj = {};\n\n\t\t\tfor (let i=0; i < items.length; i++){\n\t\t\t\tif (items[i].id === itemID)\n\t\t\t\t\titemObj = items[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }