query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Scribe Appender for log4js. Sends logging events via Scribe using nodescribe.
function scribeAppender(category, layout, client) { var isReady = false; var STORED_MESSAGES_LIMIT = 1000; // number of messages we store until scribe is fully connected var storedMessages = []; client.open(function(err){ if(err) { return console.log(err); ...
[ "function scribeAppender(layout) {\n if(!layout) {\n layout = passThrough;\n }\n\n return function(loggingEvent) {\n var msg = layout(loggingEvent);\n // msg = uncolorize(msg);\n if (loggingEvent.level.levelStr === 'TRACE'){\n console.timing(msg)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filter callback which decides if branch is apply with search filter
function filterCallback(branch, search) { if (Array.isArray(search)) { let i = 0 while(search[i]) { if (branch.name.search(search[i] + "") != -1) return true; i++ } return false } return branch.name.search(search) != -1 }
[ "function filter(parentBranch, search) {\n\tif (parentBranch.branches.length > 0) {\n\t\tparentBranch.branches = parentBranch.branches.filter(childBranch => filter(childBranch, search))\n\n\t\tif (parentBranch.branches.length > 0)\n\t\t\treturn parentBranch;\n\n\t\treturn false;\n\t}\n\n\treturn filterCallback(pare...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify to action hide loading
function hideLoading() { _updateState(hotelStates.HIDE_LOADING); }
[ "function hideLoadingMessage() {}", "function showLoaderOnVoAction() {\n $(\".voAction\").on(\"click\", function () {\n $(\".loader-wrapper\").show();\n $(\".loader-wrapper .loader\").show();\n });\n }", "function showLoadingMessage() {}", "function chartUI_Hide_LoadingN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Same as [[authenticate]] but returns a boolean over raising exceptions
async check() { try { await this.authenticate(); } catch (error) { /** * Throw error when it is not an instance of the authentication */ if (error instanceof AuthenticationException_1.AuthenticationException === false) { ...
[ "authenticate(data) {\n\t\tvar saltAndHash = null;\n\t\tsaltAndHash = hashPassword(data.password, this.getSalt());\n\t\treturn this.getSaltedHash() == saltAndHash.saltedHash;\n\t}", "isAuthenticated() {\n return !!this.credentials;\n }", "function authenticateUser(username, userpassword, hashed)\n{\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if the user hovers over a day, give specific information about the weather for that day
handleDayMouseEnter(state) { var newComponents = []; newComponents.push(<p key={0} className="datestring">{state.date.toString().substring(0,15)}</p>) newComponents.push(<p key={1} >{state.weatherDescription.toLowerCase().split(' ').map((s) => s.charAt(0).toUpperCase() + s.substring(1)).join(' ...
[ "function displayWeather(data) {\n document.querySelector(\"#day0\").innerText = weekday(data.daily[0].dt);\n document.querySelector(\"#date0\").innerText = date(data.daily[0].dt);\n document.querySelector(\"#weather-icon0\").src =\n \"http://openweathermap.org/img/wn/\" +\n data.daily[0].weather[0].icon +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
content and target can be specified as props or as children. this method normalizes the two approaches, preferring child over prop.
understandChildren() { const { children, content: contentProp, target: targetProp } = this.props; // #validateProps asserts that 1 <= children.length <= 2 so content is optional const [targetChild, contentChild] = React.Children.toArray(children); return { content: contentChild == null ? contentPr...
[ "function delegate(targets, props) {\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== \"production\") {\n errorWhen(!(props && props.target), ['You must specity a `target` prop indicating a CSS selector string matching', 'the target elements that should receive a tippy.'].join(' '));\n }\n\n var l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether or not a parent element contains a given child element. If `allowVirtualParents` is true, this method may return `true` if the child has the parent in its virtual element hierarchy.
function elementContains(parent, child, allowVirtualParents) { if (allowVirtualParents === void 0) { allowVirtualParents = true; } var isContained = false; if (parent && child) { if (allowVirtualParents) { isContained = false; while (child) { var nextPa...
[ "function elementContains(parent, child, allowVirtualParents) {\n if (allowVirtualParents === void 0) { allowVirtualParents = true; }\n var isContained = false;\n if (parent && child) {\n if (allowVirtualParents) {\n isContained = false;\n while (child) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset interactables objects to their original color
resetInteracts() { let i; for (i = 0; i < this._objects.intersects.length; i++) { this._objects.intersects[i].material.color.setHex(this._objects.intersects[i].originalColor); } }
[ "function reset_obj_color(){\n var is=inputs.length, cs=components.length, cons=connections.length;\n var i;\n for(i=0; i<is; i++){\n inputs[i].attr({stroke:'#000000', fill:'#FFFFFF'});\n }\n for(i=0; i<cs; i++){\n components[i].attr({stroke:'#000000', fill:'#FFFFFF'});\n }\n for(i=0; i<cons; i++){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LTNode (logical tree node) depending on the type does different work: 1. if terminal: node represents single condition term that interacts with other terms via logical operators (i.e. && or ||). Such term may include preprocessing code, comparison, and conditional jump: +>R: add S, TV: sub U, W | logical tree node comp...
function LTNode(jmpCmd, nodeType, parent, connection) { this._id = LTNode.__nextId++; //assign node identifier this._type = nodeType; //type of the node: root, non-terminal, or terminal //two next members are used exclusively by terminal node, other node types should //set them to NULLs this._jmpCmd = jmpCmd; ...
[ "createTerminalNode(parent, t) {\r\n return new TerminalNode_1.TerminalNode(t);\r\n }", "createTerminalNode(parent, t) {\n return new TerminalNode_1.TerminalNode(t);\n }", "function getNodeType(node) {\n if (node.length === 17) {\n return 'branch'\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the DOM node that represents the document node after the given position. May return `null` when the position doesn't point in front of a node or if the node is inside an opaque node view. This is intended to be able to call things like `getBoundingClientRect` on that DOM node. Do not mutate the editor DOM directly...
nodeDOM(pos) { let desc = this.docView.descAt(pos); return desc ? desc.nodeDOM : null; }
[ "function getJsDocTagAtPosition(node, position) {\n var jsDoc = getJsDocHavingNode(node).jsDoc;\n if (!jsDoc)\n return undefined;\n for (var _i = 0, jsDoc_1 = jsDoc; _i < jsDoc_1.length; _i++) {\n var _a = jsDoc_1[_i], pos = _a.pos, end = _a.end, tags =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve stores under this company
getStores() { Service.get(this).getStores(state.get(this).params.companyId); }
[ "getStores(companyId) {\n // Reset\n this.displayData.stores = [];\n // Retrieve stores and store\n return Resource.get(this).resource('Store:getStores', {companyId})\n .then((stores) => {\n // Remove extra stuff\n this.displayData.stores = stores.filter((store) => {\n return store._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helpful functions for calculations flips sign for all elements in array
function flipSignForAll1D(arr) { for (let i = 0; i < arr.length; i++) { arr[i] *= -1; } }
[ "function invertSign(arr) {\n const invertArr = [];\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i] * -1;\n invertArr.push(item);\n }\n return invertArr;\n}", "function outlookNegative(array){\n for(let x = 0; x < array.length; x++){\n if(array[x] > 0){\n array[x] = a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Default project authentication failure.
function defaultProjectFail(req, res, fail) { if (fail === undefined) { res.redirect('/projects'); } else { fail(); } }
[ "function authProjectOwner(id, username, pass, fail) {\n db.get().collection('projects').find({ id: id, owner: username }).toArray((err, project) => {\n if (err || project.length != 1) {\n fail();\n }\n if (project.length == 1) {\n pass();\n }\n });\n}", "fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function that calculates How long to trigger the note for
function getNoteDuration(note){ return Math.abs(note.stopTime - currTime); }
[ "lengthOfBeat(){\n return 60.0/this.tempo;\n }", "function calculateNoteDurationInSixteenth(note) {\n \n // Remove r if is a rest\n\tlet noteDuration = note.duration.replace('r', '');\n \n // Calculate the duration of the notes in 16th\n\tlet noteDurationInSixteenth = (16 / parseInt(noteDuration));\n\n\t/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws a point that follows mouse on coordinate plane
function drawHoverPoint(pt) { // checking browser for Canvas support if (plane.getContext) { // when integer snap is enabled, point will only // be drawn on discrete coordinates. Otherwise translation does nothing let translation = integerSnapTranslate(); // returns coord pair object // draw poin...
[ "draw() {\n stroke(255);\n point(this.x, this.y);\n }", "function draw() {\n if (mouseIsPressed) {\n line(mouseX, mouseY, pmouseX, pmouseY);\n }\n}", "function mousePressed(){\n strokeWeight(controllers.pointStroke);\n stroke(255);\n current = createVector(mouseX, mouseY);\n point(mouseX, mouseY...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the shopping cart.
clearCart() { this._cart.clear(); }
[ "function clearCart () {\n\t\tcart = [];\n}", "function clearCart() {\n setCart([])\n setItemsCount(0)\n setCartTotal(0)\n }", "function clearCart(){\n \tcart=[];\n \tsaveCart(); \n \tdisplayCart(); \n }", "clearCart() {\n let cartItems = cart.map(item => item.id);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
default config for a format button
get formatButton() { return { label: "Format", type: "rich-text-editor-heading-picker", }; }
[ "get formatButton() {\n return {\n ...super.formatButton,\n label: this.t.formatButton,\n blocks: this.formatBlocks,\n };\n }", "function autoFormat(){\n modifyContent(supportedAction.FORMAT);\n }", "get removeFormatButton() {\n return {\n ...super.removeFormatButton,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort allScores array in descending order
function sortAllScores() { allScores.sort(function aaa(x,y){ if (x.score > y.score){ return -1; } if (x.score < y.score){ return 1; } return 0; }); }
[ "function sortByScoreDown() {\n arrayLivros.sort((a, b) => fullscoreForSort(b._scores) - fullscoreForSort(a._scores));\n}", "function sortScores() {\n scoresArray.sort(function (a, b) {\n return b.score - a.score;\n });\n scoresArray = scoresArray.slice(0,10);\n}", "function sortScores() {\n Highscore...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
On a real production server, nginx would be used for serving assets
setupStaticServer() { this.app.use( vhost( `${Config.subdomains.static}.${Config.domain}`, express.static(Config.dirs.static) ) ); // if(Config.isProd) { this.app.use(Config.paths.assets, express.static(Config.dirs.assets)); // } }
[ "serveBuildAssetFiles() {\n /* eslint-disable no-unused-vars */\n\n // serve static files from versioning folder\n this.app.use(\n `/${WP_DEFINE_ASSETS_DIRNAME}`,\n express.static(\n path.join(__dirname, `../${WP_DEFINE_WEB_OUTPUT_DIRNAME}/${WP_DEFINE_ASSETS_DIRNAME}`),\n ),\n );\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper Methods Fade out music. fm is fade multiplier to control speed of fading
function FadeOut(fm:float):void { _audio.volume -= Time.deltaTime * fm; }
[ "function FadeIn(fm:float):void {\n\t_audio.volume += Time.deltaTime * fm;\n}", "function __musicFade(_obj, isFadeIn, step, triggerNextAfterFinish){\n var currentVol = _obj.jPlayer('option','volume');\n var targetVol;\n if(isFadeIn){\n targetVol = currentVol + step;\n }else{...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates this role definition with the supplied properties
update(properties) { return __awaiter(this, void 0, void 0, function* () { const s = ["BasePermissions"]; if (hOP(properties, s[0]) !== undefined) { properties[s[0]] = assign(metadata(`SP.${s[0]}`), properties[s[0]]); const bpObj = properties[s[0]]; ...
[ "update(properties) {\r\n if (hOP(properties, \"BasePermissions\") !== undefined) {\r\n properties[\"BasePermissions\"] = extend({ __metadata: { type: \"SP.BasePermissions\" } }, {\r\n High: properties[\"BasePermissions\"].High.toString(),\r\n Low: properties[\"BasePe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the crosshair coordinates centering mouse coordinates.
function renderCrosshairUpdateLogic () { crosshairX = SI.game.Renderer.getScene().getMouseX() - crosshairSpriteHalfSize; crosshairY = SI.game.Renderer.getScene().getMouseY() - crosshairSpriteHalfSize; }
[ "function updateCrosshair(newX, newY) {\n if (plot === null) {\n return;\n }\n var axes = plot.getAxes();\n var x = ( typeof newX !== 'undefined') ? newX : axes.xaxis.min;\n var y = ( typeof newY !== 'undefined') ? newY : null;\n plot....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
call when we get new data from backend activationsData: activationsData[sentenceIndex][tokenIndex][layerIndex][neuronIndex] = value textData: textData[sentenceIndex][wordIndex] = wordString predData: predData[sentenceIndex][wordIndex] = wordString labels: labels[sentenceIndex][wordIndex] = labelString topNeurons: list ...
processData(activationsData, textData, predData, labels, topNeurons, topNeuronsByCategory){ let text = this.getSentences(textData, labels); let pred = this.getSentences(predData, labels); // load input text and prediction text into interface this.setState({text, pred}); let ac...
[ "function labelizeData(){ \n\t\n\t//var top_concept = vis.select('circle[id=\"'+ data.top_id +'\"]');\n\tvar nodelist = getTopMostConcepts();\n\t\n\t// intent labels\n\tfor (var i=0; i < nodelist.length; i++) {\n\t\tvar cur = nodelist[i];\n\t\t\n\t\tvar parentlist = /*(treeVis) ? getTreeParentData(cur) :*/ getParen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set each students blood type properly according to their parents'
function prepareFamilyBlood(jsonData) { familyBlood = jsonData; console.log(familyBlood); allStudents.forEach((student) => { if (familyBlood.pure.includes(student.lastName) === true && familyBlood.half.includes(student.lastName) === false) { student.bloodType = "Pure blood"; } else if (familyBlood....
[ "function addBlood(familyNames, studentArray) {\n pure = familyNames.pure;\n half = familyNames.half;\n\n for (i = 0; i < studentArray.length; i++) {\n studentArray[i].blood = \"\";\n for (x = 0; x < pure.length; x++) {\n if (studentArray[i].lastName == pure[x]) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Because we can read stdout and stderr through pipes only, we need to bind some functions to pipe events
function bindListeners(process, { onData, onError, onClose }) { process.stdout.on('data', onData); process.stderr.on('data', onError); process.on('close', onClose); }
[ "function pipesetup() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n return streams.reduce(function (src, dst) {\n src.on('error', function (err) {\n return dst.emit('error', err);\n });\n return src.pi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Brings this drill to the front of the screen. Used for relayering.
bringToFront() { this.game.setChildIndex(this, this.game.children.length - 1); }
[ "function bringToFront() {\n canvas.bringToFront(canvas.getActiveObject());\n}", "sendToFront()\r\n {\r\n this.wm.sendToFront(this);\r\n }", "goToFront() {\n // This should only ever be used for sprites // used by compiler\n if (this.renderer) {\n // Let the renderer re-order the spri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
a morph geometry node is similar to a standard node, and the node is also contained in FBXTree.Objects.Geometry, however it can only have attributes for position, normal and a special attribute Index defining which vertices of the original geometry are affected Normal and position attributes only have data for the vert...
function genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform) { var morphGeo = new THREE.BufferGeometry(); if (morphGeoNode.attrName) morphGeo.name = morphGeoNode.attrName; var vertexIndices = (parentGeoNode.PolygonVertexIndex !== undefined) ? parentGeoNode.PolygonVertexIndex.a : [...
[ "genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform, name) {\n const vertexIndices = parentGeoNode.PolygonVertexIndex !== void 0 ? parentGeoNode.PolygonVertexIndex.a : [];\n const morphPositionsSparse = morphGeoNode.Vertices !== void 0 ? morphGeoNode.Vertices.a : [];\n const indices = mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
component names always start with a Capital letter, otherwise React treats them as DOM tags passing the Form component props and deconstructing props object q will take the user input, book or author two other functions are the parameters passed to the Form props handleInputChange and handleFormSubmit come from Home.js
function Form({ q, handleInputChange, handleFormSubmit }) { return ( <form> <div className="form-group"> <label htmlFor="Query"> <strong>Book</strong> </label> <input className="form-control" id="Title" type="text" /* The curly braces...
[ "function Form({ q, handleInputChange, handleFormSubmit }) {\n\n // returns the data input from the home page\n return (\n <form>\n {/* jsx attributes, similiar to html */}\n <div className=\"form-group\">\n <label htmlFor=\"Query\">\n {/* prints the word Book in bold above the query ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retries a failed payment. you will receive a webhook.
retryPayment(id, metadata) { const path = `/payments?${id}/actions/retry`; const method = 'POST'; const options = buildOptions(this.token, this.endPoint, path, method, metadata); return goCardlessRequest(options); }
[ "function retry_post() {\n retries = retries -1;\n if (success || retries == 0)\n return 0;\n // no luck yet\n fetch_client_whorls()\n}", "retry() {}", "attemptFailed() {\n if (!this.inProgress) {\n throw new Error('No attempt is in progress');\n }\n\n if (this.newBackoff) {\n const sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A helper function to check whether an array a2 is included inside an array a1
function arrayIncludesArray(a1, a2) { for(let i = 0; i < a1.length; i++) { if(a1[i][0] == a2[0] && a1[i][1] == a2[1]) return true } return false }
[ "arraysItemInArray(a, b) {\r\n for(let item of a) {\r\n if(b.includes(item)) return true;\r\n }\r\n return false;\r\n }", "function arrayContained(array1, array2) {\n // if either array is a falsy value, return\n if (!array1 || !array2)\n return false;\n\n // compare len...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Puts charger icons in the map
function putChargers(map){ // First charger icons var icon = new H.map.Icon('/static/img/preview_30.png'); var coords = window.first_chargers_array; // Put first chargers in the map for(var i=0; i<coords.length; i++){ var incidentMarker = new H.map.Marker({ lat: coords[i]["coords...
[ "setupIcons() {\n // Under icons\n this.add.image(this.canvasGame.width / 2 - 330, 150, 'env').setScale(0.4);\n this.add.image(this.canvasGame.width / 2 - 110, 150, 'soc').setScale(0.4);\n this.add.image(this.canvasGame.width / 2 + 110, 150, 'eco').setScale(0.4);\n this.add.image(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
END TABBER FORMATTING FUNCTIONS ///////////////////////////////////////////////////////// //////////////////////////////////Section5: START Generic Helper FUNCTIONS///////////////////////////////////////////////////////// / To remove extra spaces from a value. Arguments: 1) Value to be trimmed. Sample Call: SP_Trim(obj...
function SP_Trim(value) { value = new String(value); return value.replace(/^\s+|\s+$/g, ""); }
[ "function SP_Trim(value) \n{\n value = new String(value);\n return value.replace(/^\\s+|\\s+$/g, \"\");\n}", "function RTrim(pstrValue) {\r\n\r\n\tif(pstrValue != null || pstrValue != undefined){\r\n\tvar w_space = String.fromCharCode(32);\r\n\tvar v_length = pstrValue.length;\r\n\tvar strTemp = \"\";\r\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
contains the player pool and related methods
function PlayerPool(){ this._players = []; }
[ "function createItemPool() {\n item_pool.push(function() {\n sunflower = new sprite({\n context: canvas.getContext(\"2d\"),\n width: 80,\n height: 67,\n x: 0,\n y: -100,\n image: n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets navigation frame width to the value stored in the cookie usally called on document load
function PMA_setFrameSize() { pma_navi_width = PMA_getCookie('pma_navi_width'); //alert('from cookie: ' + typeof(pma_navi_width) + ' : ' + pma_navi_width); if (pma_navi_width != null) { if (parent.text_dir == 'ltr') { parent.document.getElementById('mainFrameset').cols = pma_navi_width +...
[ "function PMA_saveFrameSizeReal()\n{\n if (parent.text_dir == 'ltr') {\n pma_navi_width = parseInt(parent.document.getElementById('mainFrameset').cols)\n } else {\n pma_navi_width = parent.document.getElementById('mainFrameset').cols.match(/\\d+$/) \n }\n if ((pma_navi_width > 0) && (pma_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hovers an item via the keyboard.
_hoverViaKeyboard(item) { if (!item) { return; } const that = this; item.$.addClass('focus'); item.setAttribute('focus', ''); that._focusedViaKeyboard = item; that._ensureVisible(item); }
[ "function onEditorAutocompleteHover(hoveredItem) {\n \n }", "_onHover(menuID, itemID) {\n this._dbus.emit_signal('OnHover', GLib.Variant.new('(is)', [menuID, itemID]));\n }", "_onPointerOver() {\n this.addState(\"hovered\");\n }", "function threadItemHoverOver(item) {\n item.addEvents({\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback for the swprecache results
function swPrecache_callback(error) { console.log("Error:" + error) }
[ "function cacheResult(data) {\n var args = Array.prototype.slice.call(arguments);\n lscache.set(cacheKey, data, minstl);\n dfd.resolveWith(jqXHR, args);\n }", "function callback(rsc) {\n cache[id] = rsc; // Cache the result\n // Execute the plan\n var plan = plans[id];\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize an i18n message into two arrays: messageParts and placeholders. These arrays will be used to generate `$localize` tagged template literals.
function serializeI18nMessageForLocalize(message) { const pieces = []; message.nodes.forEach(node => node.visit(serializerVisitor$2, pieces)); return processMessagePieces(pieces); }
[ "function serializeI18nMessageForLocalize(message) {\n var pieces = [];\n var serializerVisitor = new LocalizeSerializerVisitor(message.placeholderToMessage, pieces);\n message.nodes.forEach(function (node) {\n return node.visit(serializerVisitor);\n });\n return processMessagePieces(pieces);\n}", "functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a new instance of the 'PdfPageNumberFieldInfoCollection' class.
function PdfAutomaticFieldInfoCollection(){/** * Internal variable to store instance of `pageNumberFields` class. * @private */this.automaticFieldsInformation=[];// }
[ "function PdfAutomaticFieldInfoCollection() {\n /**\n * Internal variable to store instance of `pageNumberFields` class.\n * @private\n */\n this.automaticFieldsInformation = [];\n //\n }", "function PdfDocumentPageCollection(document) {\n /**\n * It ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
truncateObject truncates each key in the object separately, which is useful for handling circular references.
function truncateObject(obj, level) { var maxLength = scale(maxObjectLength, level); var dst = {}; var length = 0; for (var key in obj) { dst[key] = truncate(obj[key], level); length++; if (length >= maxLength) { break; } } return dst; }
[ "function truncateObj(obj, level) {\n var dst = {};\n for (var attr in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, attr)) {\n dst[attr] = module.exports.truncate(obj[attr], level);\n }\n }\n\n return dst;\n}", "function truncatedProps(obj, truncateLength = 100) {\n const result = {}\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Selects a random word within the words array and returns it.
function selectWord() { var words = ["apple", "ice", "orange", "car", "computer", "game", "math", "school", "juice", "soda", "carrot", "purple", "movie", "superhero"]; return words[Math.round(Math.random() * words.length)]; }
[ "function chooseWord() {\n return wordsArray[Math.floor(Math.random() * wordsArray.length)];\n }", "selectWord (randomWords){\n var index = Math.round(Math.random() * (randomWords.length - 1))\n return randomWords[index]\n }", "function selectWord() {\n return wordArr[Math.floor(Math.random() * wo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return from an array all the text nodes between two other nodes on the page
function getInterveningTextNodes(node_array, first_node, second_node) { var desired_nodes = []; node_array.forEach(node => { if (first_node.compareDocumentPosition(node) == 4 && second_node.compareDocumentPosition(node) == 2 && node.nodeType == 3){ desired_nodes.push(node);...
[ "textNodes() {\n\t\t\t/*\n\t\t\t\tBase case: this collection contains a single text node.\n\t\t\t*/\n\t\t\tif (this.length === 1 && this[0] instanceof Text) {\n\t\t\t\treturn [this[0]];\n\t\t\t}\n\t\t\t/*\n\t\t\t\tFirst, create an array containing all descendent and contents nodes\n\t\t\t\twhich are text nodes.\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
randomly inverts goose direction in unpredicatble ways.
invertDirectionRandom() { let hasInverted = false; if (Math.random() < 0.5) { let temp = this.deltaY; this.deltaY = this.deltaX; this.deltaX = temp; hasInverted = true; } if (Math.random() < 0.5) { this.deltaX = -this.deltaX; hasInverted = true; } if (Math.ran...
[ "function resetDirection() {\n posX = random(trueFalse);\n posY = random(trueFalse);\n w = 0;\n z = 0;\n}", "function randomDirection() {\n const x = Math.random()\n const y = Math.random()\n return new Two.Vector(x,y).normalize()\n }", "function randomDirection () {\n if (Math.random() <= 0.5) {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Only enable the touch UI if the device supports touch events.
function optionallyEnableTouchUI(){ // Check if the browser supports touch events if('ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch) { forceTouchUI(); } }
[ "function is_touch_device() {\r\n return false;\r\n }", "enable() {\n this.target.addEventListener('touchstart', this.recordTouchStartValues.bind(this));\n this.target.addEventListener('touchend', this.detectSwipeDirection.bind(this));\n }", "_onTouchStart(event) {\n if (event.type === 'touc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
................................................................. userId > getLaUltimaMedidaPorUsuario() > .................................................................
async getLaUltimaMedidaPorUsuario(userId) { var textoSQL = "SELECT * FROM Medidas WHERE IdUsuario=" + userId + " ORDER BY IdMedida DESC LIMIT 0, 1"; return new Promise((resolver, rechazar) => { this.laConexion.all(textoSQL, (err, res) => { (err ? rechazar(err) : resolver(res)) })...
[ "function listarMedicoseAuxiliares(usuario, res){\n\t\tconnection.acquire(function(err, con){\n\t\t\tcon.query(\"select crmv, nomeMedico, telefoneMedico, emailMedico from Medico, Responsavel where Medico.Estado = Responsavel.Estado and Medico.Cidade = Responsavel.Cidade and Responsavel.idusuario = ?\", [usuario.idu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
equip a weapon by name equips fists if no name given
equipWeapon(name) { const weapon = name || "fists" this.equippedWeapon = Item.create(weapon) if (this.stored.weapon && this.stored.weapon !== "fists") { this.loot(this.stored.weapon) } this.stored.weapon = weapon }
[ "equipWeapon(weapon) {\n this.weapon = weapon\n }", "equipArmor(name) {\n const armor = name || \"naked\"\n this.equippedArmor = Item.create(armor)\n\n if (this.stored.armor && this.stored.armor !== \"naked\") {\n this.loot(this.stored.armor)\n }\n\n this.stored.armor = armor\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create Release on GitHub.
async function createRelease(releaseDescription, prevReleaseId) { // Create draft release if BOOL_CREATE_RELEASE is undefined // Publish release if BOOL_CREATE_RELEASE is not undefined const boolCreateDraft = !BOOL_CREATE_RELEASE const releaseResponse = await octokit.repos.createRelease({ owner: GH_OWNER, ...
[ "function createNewRelease(RELEASE_NAME,TRAVIS_REPO_SLUG){\n var body = { \n tag_name: RELEASE_NAME,\n target_commitish: 'master',\n name: 'test prerelease draft',\n body: 'some text for body',\n draft: true,\n prerelease: true\n };\n fetch(`https://api.github.com/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursive backtrack solution: generate powerset, but skip duplicates. Complexity: Time: nlogn sort + n2^n = n(2^n + logn) Same as powerset plus sort. Space: worst case no duplicates is same as powerset. stack space reaches max depth of n at any time = O(n) output would be 2^n sets average of n/2 = n 2^n so total is n/2...
function subsetsWithDups2( nums ) { nums.sort( ( a, b ) => a - b ); // Sort for duplicate checking const backtrack = ( subsets, partial, offset ) => { const completeSubset = Array.prototype.concat.call( partial ); subsets.push( completeSubset ); for ( let i = offset; i < nums.length; i++ ) { if (...
[ "function genPowerSet(n) {\r\n binaryList = genBinary(n); // list of binary strings\r\n var pS = []; // where the subsets are stored\r\n for(let i = 0; i < binaryList.length; i++) { // iterate through the list of binary numbers\r\n var binStr = binar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to check if URL is unique
function isUrlUnique(url){ return ($.inArray(url, uniqueLinks) === -1) ? true : false; }
[ "function isUrlUnique(url){\n return (jQuery.inArray(url, uniqueLinks) === -1) ? true : false;\n }", "function isUrlUnique(url){\nreturn ($.inArray(url, uniqueLinks) === -1) ? true : false;\n}", "function isDuplicateUrl(url) {\n return dbops.checkDuplicateData(url);\n}", "function checkurl(str){\n var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor function creates cellPhone object
function cellPhone(manufacturer, model, color, price){ this.manufacturer = manufacturer; this.model = model; this.color = color; this.price = price; this.getPrice = function(){ return this.price; }; this.getModel = function(){ return this.model; }; this.getDetails = f...
[ "function CellPhone(brand, sc, c) {\n this.brand = brand\n this.screensize = sc\n this.carrier = c\n}", "function CellPhone(brand, screenSize, carrier) {\n this.Brand = brand\n this.ScreenSize = screenSize\n this.Carrier = carrier\n}", "function Cellphone(Model, Color, Brand, Size) {\n this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if the given city is not empty and not longer than 120 letters
static checkCity(city) { try { NonEmptyString.validate(city, CITY_CONSTRAINTS); return ""; } catch (error) { console.error(error); return "The address' city should not be empty or larger than 120 letters"; } }
[ "function isCity(s){\n\ts=trim(s);\n\treturn isCharsInBag (s, \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ \");\n}", "function validateCityNameString(cityName) {\n\treturn cityName && cityName.toString().trim() != '';\n\n}", "function checkCity(city){\n var pattern = /[\\w ]+/;\n if(pattern.test...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createGame onclick emit a message on the 'create' channel to create a new game with default parameters
function createGame() { socket.emit('create'); }
[ "function createGame() {\n console.log('Creating game...');\n socket.emit('create', {size: 'normal', teams: 2, dictionary: 'Simple'});\n}", "function createGame () {}", "function hostCreateNewGame() {\n this.emit('newGameCreated', {\n gameStart: true\n });\n}", "function createNewGame() {\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves references for a specified user.
async getReferences(req, res) { var applicationId; if (!req.query || !req.query.applicationId) { return res .status(400) .send({ error: "applicationId param was not provided with request." }); } ({ applicationId } = req.query); const matchedReferences = await References.findOne...
[ "function getUserRoomRef(user){\n for(var i=0;i<places.length;i++){\n if(user===places[i].id){\n return places[i];\n }\n }\n}", "async function getUserReferrals (t, userId = 0, email = '') {\n let url = t.config.apiUrl + apiVersion + '/users/referred?'\n\n if (userId && userId > 0) {\n url += 'i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to fetch data using inquirer
function fetchData() { inquirer .prompt([ { type: 'input', name: 'title', message: 'Title of your application ', }, { type: 'list', message: 'Choose a license for my application(Choose None if not in the list)', name: 'license', choices: ['MIT', 'ISC', 'gpl', 'N...
[ "function getResponseFromUser(){\n inquirer.prompt(questions).then(result => {\n userPurchase(result.productID, result.unit);\n });\n}", "function likeToBuy(){\r\n var question = [\r\n {\r\n type: 'input',\r\n name: 'item_id',\r\n message: \"What is the ID of the item you'd like to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is a user able to update or delete an existing Drawing document??
static _canModify(user, doc, data) { if (user.isGM) return true; // GM users can do anything return doc.data.author === user.id; // Users may only update their own created drawings }
[ "canEditDocument() {\n return this.user.editOwn('document') && this.isDocAuthor && this.isInProgress;\n }", "canEdit() {\n return this.user.updateAny('persons') || (this.isDocAuthor && this.user.updateOwn('persons'));\n }", "function checkEdit() {\n let ui = DocumentApp.getUi()\n let response = ui.ale...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TASK: check if some groups have more guests than chairs and break them into smaller groups
function reducingBigGroups(guestList) { let guests = {}; i = 1; while (guestList.length > 0) { n = guestList[0].length; if (n <= tableChairs) { guests[`GROUP ${i++}`] = guestList[0]; guestList.shift(); } else { console.log(`\n${guestList[0]} --> This group has ${n} members, we have ...
[ "damageGroups (groups, challengeDue, roundUpDamage) {\n // Sort from low to high template challenge.\n groups.sort(\n (a, b) => a.template.challenge - b.template.challenge\n );\n\n for (let group of groups) {\n const groupChallenge = group.quantity * group.template....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts next_state that would be set and checks if the test parameters can be generated for that state. Returns: "attempt_next_state" : With current parameters, switching to this state is not possible. Try next state logical state according to state machine. "attempt_same_state" : Something has changed such as num_cook...
function attempt_switching_state_to(attempt_state) { if (attempt_state == "st_testing") { if (binary_cookiesets.length == 0) { console.log("APPU DEBUG: Finished testing all cookiesets"); return "done"; } current_cookiesets_test_index = 0; curr_binary_cs = binary_cookiesets[current_cookiesets_...
[ "_transport_validateNextState(nextState = {}) {\n const nextDirection = nextState?.direction;\n switch (true) {\n // no state change, abort\n case Object.entries(nextState).every(([key, val]) => this.#state[key] === val):\n return null;\n // attempting to play reverse past zero, abort\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Algorithm set count as zero In a loop traverse the given array to find non zero element,if found then replace with element at index 'count'(repeat looop till end) All non zero elements shifted to front and count again set to 0. Function which pushes all zeros to end of an array.
function pushZerosToEnd(arr, n) { let count = 0; for (let i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; while (count < n) arr[count++] = 0; }
[ "function move_zeroes(arr) {\n let numZeroes = 0;\n for (let i = 0; i < arr.length; i += 1) {\n if (arr[i] === 0) {numZeroes += 1}\n }\n\n while (arr.indexOf(0) > -1) {\n let idx = arr.indexOf(0);\n arr.splice(idx, 1);\n }\n\n for (let i = 0; i < numZeroes; i += 1) {\n arr.push(0);\n }\n\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an HTTP response's error status to the equivalent error code.
function mapCodeFromHttpResponseErrorStatus(status) { var serverError = status.toLowerCase().replace('_', '-'); return Object.values(Code).indexOf(serverError) >= 0 ? serverError : Code.UNKNOWN; }
[ "function mapCodeFromHttpResponseErrorStatus(status) {\r\n var serverError = status.toLowerCase().replace('_', '-');\r\n return Object.values(Code).indexOf(serverError) >= 0\r\n ? serverError\r\n : Code.UNKNOWN;\r\n}", "function mapCodeFromHttpResponseErrorStatus(status) {\n var serverError...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mapping of attribute names to required namespaces:
static attributeNamespace () { return { 'href': SvgElement.xlink, 'xlink': SvgElement.xmlns, // Only the xmlns attribute needs the trailing slash. See #984 'xmlns': `${SvgElement.xmlns}/`, // IE needs the xmlns namespace when setting 'xmlns:xlink'. See...
[ "static attributeNamespace() {\n return {\n 'href': SvgElement.xlink,\n 'xlink': SvgElement.xmlns,\n // Only the xmlns attribute needs the trailing slash. See #984\n 'xmlns': \"\".concat(SvgElement.xmlns, \"/\"),\n // IE needs the xmlns namespace when setting 'xmlns:xlink'. See #984\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draw the board use same for loops to draw rows/cols, then drawSquare function called with c,r,board[r][c] as x,y and color arguments
function drawBoard() { for (r = 0; r < ROW; r++) { for (c = 0; c < COL; c++) { drawSquare(c, r, board[r][c]) } } }
[ "function drawBoard() {\n\tfor(let i = 0; i < ROW; i++) {\n\t\tfor(let j = 0; j < COLUMN; j++) {\n\t\t\tdrawSquare(j, i, board[i][j]);\n\t\t}\n\t}\n}", "function drawChessboard (squareColor){\n\tfor (j = 0; j < numRows; j++) {\n var yCorner = yOrigin + j * size;\n\t\tfor (i = 0; i < numCols; i++) {\n \t v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We are setting the initial state of this.state.movie to ''.
constructor(props) { super(props); this.state = { movie: '', }; }
[ "setInititalState() {\n this.setState({\n selectedMovie: null,\n });\n }", "prepareMovieState() {\n this.gameOrchestrator.interface3D.setCurrentMenu(MENUS.InGameMenu);\n this.gameOrchestrator.changeState(new MovieState(this.gameOrchestrator));\n }", "chooseMovie(chosenM) {\n chos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publish an IPFS hash to the blockchain. Pay for the TX with the WIF. Optional preface text will replace the default 'IPFS UPDATE' used to signal updates for the ipfswebserver.
async publish(hash, wif, preface) { try { // Create an EC Key Pair from the user-supplied WIF. const ecPair = _this.bchjs.ECPair.fromWIF(wif) // Generate the public address that corresponds to this WIF. const ADDR = _this.bchjs.ECPair.toCashAddress(ecPair) // console.log(`Publishing $...
[ "function publish(hash) {\n throw \"TODO: Implement publish\";\n }", "async publish(ipfs) {\n console.log(\"to be implemented\")\n }", "function notary_send(hash, callback) {\n \n web3.eth.getAccounts(function (error, accounts) {\n contract.methods.addDocHash(hash).send({\n from: account...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Randomize Easy Pie Chart values
static initRandomEasyPieChart() { jQuery('.js-pie-randomize').on('click', e => { jQuery(e.currentTarget) .parents('.block') .find('.pie-chart') .each((index, element) => { jQuery(element).data('easyPieChart').update(Math.floor((Math...
[ "function easypie_randomize(){\n\t\t\n\t\tvar items = $.percentage_easy_pie;\n\t for (var i = 0; i < items.length; i++) {\n\t //do stuff\n\t var newValue = Math.round(100*Math.random());\n\t $(this).data('easyPieChart').update(newValue);\n\t $('span', this).text(newValue);\n\t } \n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Installs importer test logger.
function installTestLogger() { testLogger = new importer.TestLogger(); importer.getLogger = () => { return testLogger; }; }
[ "static setup() {\r\n if (!Utils.exists(Logicker.log)) {\r\n super.setup(C.LOG_SRC.LOGICKER);\r\n }\r\n }", "function setupLogger(logDir) {\n // configure logger to use as default error handler\n var tsFormat = function tsFormat() {\n return new Date().toLocaleTimeString();\n };\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HistoryPage renders: a 'Table' which contains the data of the previous winnings a 'Button' to go back to the 'WheelPage' State: historyEntries: List ( list of all prizes that have been won ) API Calls: getAll( "/history", setHistoryEntries ) > gets a list of all history entries and stores it in the historyEntries list
function HistoryPage( props ) { const [historyEntries, setHistoryEntries] = useState( [] ); useEffect( () => { Api.getAll( "/history", setHistoryEntries ); }, [] ); return ( <Container className="history-page"> <Container className="link-container"> <Link ...
[ "function refreshHistory() {\n ResultsHistoryService.getResults().then((results) => {\n view.history = results;\n }).catch((error) => {\n displayToast(error.message);\n });\n }", "function renderSearchHistory() {\n if (JSON.parse(localStorag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialise a astar grid in parallel to main "GRID"
function aStarInit() { var i, j; // create the aStarGrid for (i = 0; i < gridsize; i++) { aStarGrid[i] = []; for (j = 0; j < gridsize; j++) { aStarGrid[i][j] = new gridSpot(i, j); // console.log("A* Initialise: " + i + ", " + j); } } for (i...
[ "init() {\n this.prepareGrid();\n this.configureCells();\n }", "function initialiseGrid() {\n // Initialise 2D array\n grid = new Array(GRID_X);\n for (var i = 0; i < GRID_X; i++) {\n grid[i] = new Array(GRID_Y);\n }\n\n // Fill array with gridSections objects\n for (var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This FlowNode extends the Actor. What it mainly does is delegate what it it asked to do To the nodes from the actor. External Interface is not really needed anymore. Because the flow has ports just like a normal node
function Flow(id, map, identifier, loader, ioHandler, processManager) { var self = this; if (!id) { throw Error('xFlow requires an id'); } if (!map) { throw Error('xFlow requires a map'); } // Call the super's constructor Actor.apply(this, arguments); if (loader) { this.loader = loader;...
[ "function Flow(id, map, identifier, loader, ioHandler, processManager) {\n\n var self = this;\n\n // Call the super's constructor\n Actor.apply(this, arguments);\n\n // External vs Internal links\n this.linkMap = {};\n\n // indicates whether this is an action instance.\n this.actionName = undefined;\n\n // ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the settlement object with the newest values based on inputs and configurations.
function updateComponent_() { var size = { min: vm_.settlement.populationRange.min, max: vm_.settlement.populationRange.max }; vm_.settlement.population = vm_.getPopulation(size.min, size.max); vm_.settlement.readyCash = vm_.getReadyCash(vm_.settlement.gpLimit, vm_.settlement.population); ...
[ "updateForConfig() {\n this.iteratePlans((classId, dayIndex, hourIndex) => {\n const lesson = this[classId][dayIndex][hourIndex];\n if (lesson) {\n // apply latest texts and specifications from user configuration\n this[classId][dayIndex][hourIndex] = this.getPlanLesson(lesson.lessonId, l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
menu to go back or end
function backMenu() { inquirer.prompt([ { type: 'list', message: 'What would you like to do?', name: 'action', choices: [ "go back to main menu", "end session" ] } ]).then(({ action }) => { switch...
[ "function backToMenu() {\n toggle();\n clearImages();\n pageNumber = START_PAGE_NUM;\n }", "function goBack() {\n navigation.goBack();\n }", "function menuListBackBtn()\n{\n\tvar url = makeURL(\"Menu\", \"GoBackFromMenuList\");\n\t$.post(url, null, function (jSonData) { renderResponse(jSonDa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
applies discount if year of book is over 2000
applyDiscount(book){ if(book.year > 2000){ let reducedPrice = this.percentage*book.price; return (book.price - reducedPrice); }else{ return book.price; } }
[ "function afterYear (citation, year) { return citation.year >= year; }", "applyDiscount(discount) {\n if (discount > 100 || discount < 0) {\n console.error(\"Invalid discount for \" + this.name);\n }\n this.price -= (discount / 100) * this.price;\n }", "function applyDiscount(price, discount){\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the current values and update all registered devices
function updateDevices() { // TODO controls: get values of all controls of the form and call updateDevice on each device for(i in devices){ var value; switch(devices[i].type){ case "item-generator": var x = document.getElementById("control-item-generator"); ...
[ "function updateDeviceValues()\n{\n //Run through all known devices\n for(i = 0; i < devices.length; i++)\n {\n updateDeviceValue(devices[i]);\n }\n\n setTimeout(updateDeviceValues, updateRate);\n}", "function readInDevices(){\n\t\tcon.query(\"SELECT * FROM devices\", function (err, result, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets NIS Node Host and port
function setNISNode() { let portNum = 7890; try { portNum = parseInt(nisport.value); } catch (e) { //port is not a valid int } if (nishost.value=="") { nishost.focus(); return false; } if (nispo...
[ "_setHostPort(params) {\n params.push(...['--host-port', `${this._options.host}:${this._options.port}`]);\n }", "set host(uri) {\n this.config.host = uri;\n }", "setHost(hostName) {\r\n this._hostName = hostName || \"localhost\";\r\n }", "function setHost(newHost) {\n options.host = newHo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the index into alternateVersions array of the game for a given command id. This compliments getCommandIdForAlternateVersion()
function getAlternateVersionForCommandId(commandId) { return alternateVersionCommands.findIndex(id => id == commandId); }
[ "function getCommandIdForAlternateVersion(versionIndex) {\n return alternateVersionCommands[versionIndex];\n}", "function isAlternateVersionCommandId(commandId) {\n return getAlternateVersionForCommandId(commandId) >= 0;\n}", "static GetIndexOf(Id)\n\t{\n\t\tfor (var i = 0; i < GlobalUpgrades.length; i++)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If endpoint discovery should perform for this request when no operation requires endpoint discovery for the given service. SDK performs config resolution in order like below: 1. If set in client configuration. 2. If set in env AWS_ENABLE_ENDPOINT_DISCOVERY. 3. If set in shared ini config file with key 'endpoint_discove...
function resolveEndpointDiscoveryConfig(request) { var service = request.service || {}; if (service.config.endpointDiscoveryEnabled !== undefined) { return service.config.endpointDiscoveryEnabled; } //shared ini file is only available in Node //not to check env in browser if (util.isBrowser()) return u...
[ "function discoverEndpoint(request, done) {\n var service = request.service || {};\n if (hasCustomEndpoint(service) || request.isPresigned()) return done();\n var operations = service.api.operations || {};\n var operationModel = operations[request.operation];\n var isEndpointDisco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that gets more versions on click
function getMoreVersions(startIndex) { $('#moreVersions').addClass('hidden'); console.log("More...."); $.post('/memberAPI/getItemVersionsHistory', { itemId: itemId, size: 20, from: startIndex, antiCSRF: bSafesCommonUIObj.antiCS...
[ "function changeAllVersionCompareTo(e) {\n e.preventDefault()\n $('article:visible .versions').each(function() {\n let $root = $(this).parents('article')\n let currentVersion = $root.data('version')\n let $foundElement = null\n $(this).find('li.version a').each(function() {\n let se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenience function to scroll to an element in the main page. element: the reference to the HTML element that should be scrolled to duration: scroll duration in milliseconds; defaults to 0 (no transition) easingFunction: defines the scrolling rate over time; defaults to ease in and out sin. You can either use one of t...
function smoothScrollToElement(element, { duration, easingFunction, offsetTop = 0, offsetLeft = 0 } = {}) { const rect = element.getBoundingClientRect(); smoothScrollTo({ top: document.scrollingElement.scrollTop + Math.round(rect.top) + offsetTop, left: document.scrollingElement.scrollLeft + M...
[ "scrollToElement(element, offset = 0, duration = 1000) {\n if (this.get(\"isDestroyed\")) {\n return;\n }\n if (element) {\n this.stopScroll();\n this.set(\"lastAnimated\", element);\n element.velocity(\"scroll\", {\n container: element.offsetParent(),\n axis: \"x\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If we want to add more games that our team played, we can use this method.
addGame(opponentName, teamGoals, opponentGoals) { let game = { opponent: opponentName, teamGoals: teamGoals, opponentGoals: opponentGoals } this.games.push(game); }
[ "addGame(opponentName, teamPoints, opponentPoints) {\n const game = {\n opponent: opponentName,\n teamPoints: teamPoints,\n opponentPoints: opponentPoints\n };\n return team._games.push(game);\n }", "addGame (opponent, teamPoints, opponentPoints) {\n let game = {\n opponent: opp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates the content of the SVG file representing the tooltip
function tooltip(options) { var arrow = options.arrow; var shadowSize = (options.shadow) ? options.shadow.size : 0; var shadowSideMultiplier = 2.5; var pathOptions = { x: shadowSideMultiplier * shadowSize, y: shadowSideMultiplier * shadowSize, width: options.width, height...
[ "drawToolTips() {\n this.tooltip = this.svg.append(\"g\")\n .attr(\"id\", \"tooltip\")\n .style(\"display\", \"none\");\n // Le cercle extérieur bleu clair\n this.tooltip.append(\"circle\")\n .attr(\"fill\", \"#CCE5F6\")\n .attr(\"r\", 10);\n /...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if `h` is `react.createElement`.
function react(h) { var node = h && h('div') return Boolean( node && ('_owner' in node || '_store' in node) && node.key == null ) }
[ "function react(h) {\n var node = h && h('div')\n return Boolean(\n node && ('_owner' in node || '_store' in node) && node.key === null\n )\n}", "function hasCreateElement(){\n\treturn typeof document.createElement == \"function\"; \n}", "function isElement( o ) {\n\n return (\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
closeModel function is use to close bootstrap model/popup
function closeModel(type) { if (type == "save_page_text") { $('#myModal').modal('toggle'); } else if (type == "save_page_video") { $('#videoModal').modal('toggle'); } else if (type == "countdown") { $('#CountdownModal').modal('toggle'); } else if (type == "sav...
[ "function closeModel(){\n model.style.display ='none';\n close.closeBtn.display='none';\n}", "function closeModel() {\n // console.log(\"close click\")\n containerDiv.remove();\n\n}", "function close_tag_mng(){\r\n $(\"#tag_mng_model\").modal(\"hide\");\r\n}", "function open_close_model() {\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the size of the artifact from 1 which was initially set when the container was first created for the artifact. Updating the size indicates that we are done uploading all the contents of the artifact
patchArtifactSize(size, artifactName) { return __awaiter(this, void 0, void 0, function* () { const resourceUrl = new url_1.URL(utils_1.getArtifactUrl()); resourceUrl.searchParams.append('artifactName', artifactName); const parameters = { Size: size }; const data ...
[ "patchArtifactSize(size, artifactName) {\n return __awaiter(this, void 0, void 0, function* () {\n const headers = utils_1.getUploadHeaders('application/json', false);\n const resourceUrl = new url_1.URL(utils_1.getArtifactUrl());\n resourceUrl.searchParams.append('artifactNa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scan the /entities/ folder and build the inheritance chain for each entity based on merging shared and server functionality combined with entity baseClass inheritance.
registerEntities() { const entitiesFound = fs.readdirSync(ENTITY_FOLDER); const rawEntities = {}; const resolvedEntities = {}; const resolveEntity = (entityName) => { const entity = rawEntities[entityName]; if (entity.baseClass == null) { return r...
[ "function collectEntitiesInFolder(folderName) {\n\n for (const fileName of fs.readdirSync(folderName)) {\n\n const fullPath = folderName + '/' + fileName;\n\n if (fs.lstatSync(fullPath).isDirectory() && (!foldersToExclude.includes(fullPath))) {\n collectEntitiesInFolder(fullPath);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if we're at the end of the query return the query if so, else return false;
checkEndOfQuery(){ if(this.seekingDelimiter){ return false; } var query = false; var demiliterFound = false; if(!this.quoteType && this.buffer.length >= this.delimiter.length){ demiliterFound = this.buffer.slice(-this.delimiter.length).join('') === this.delimiter; } if (demiliterFound) { // tri...
[ "checkEndOfQuery(){\n\t\tvar demiliterFound = false;\n\t\tif(!this.quoteType && this.buffer.length >= this.delimiter.length){\n\t\t\tdemiliterFound = this.buffer.slice(-this.delimiter.length).join('') === this.delimiter;\n\t\t}\n\n\t\tif (demiliterFound) {\n\t\t\t// trim the delimiter off the end\n\t\t\tthis.buffer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the text content of the first page of a pdf file
function readPdf(arrayBuffer) { return new Promise((resolve, reject) => pdfjsLib.getDocument(arrayBuffer).promise.then(function (fullPdf) { fullPdf.getPage(1).then(function (pdfPage) { pdfPage.getTextContent().then(function (textContent) { var textItems = textContent.items; var fullText = []...
[ "function getPage(page, pdf) {\n return pdf.getPage(page)\n }", "verifyPageNumberInsidePdf(pageNumber, pdfFilePath) {\r\n let dataBuffer = fs.readFileSync(pdfFilePath);\r\n pdf(dataBuffer).then((data) => {\r\n assert.expectToContain(pageNumber, data.numpages);\r\n }).catch((err...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets SearchAPI service responce to Consts
function parseSearchAPI(responseJson) { var constsKey = getAssetsKey(); SUConsts[constsKey].HomePage = responseJson.HomePageUrl; SUConsts[constsKey].StartPage = responseJson.HomePageUrl; SUConsts[constsKey].NewTab = responseJson.NewTab.Url; SUConsts[constsKey].Suggest = responseJ...
[ "rewriteSearchResponse(response) {\n return response;\n }", "constructor() { \n BaseResponse.initialize(this);LeadSearchResponseAllOf.initialize(this);\n LeadSearchResponse.initialize(this);\n }", "constructor() { \n \n ExclusionListResponseValue.initialize(this);\n }", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a string into CommandLines based on newline characters
function splitLines(text) { return createCommandLines(text.split(/\r?\n/)); }
[ "function get_splitted_command_line(string) {\n function split(string) {\n return $.terminal.split_equal(string, num_chars);\n }\n function skip_empty(array) {\n // we remove lines that are leftovers after adding space at the end\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send invitation to email
async send ({ commit, rootGetters }, email) { const invited = await invitations.create({ email, group: rootGetters['groups/activeGroupId'], }) commit(types.APPEND, { invited }) }
[ "_sendInvitation(user, password) {\n return this.mailer.invite({email: user.email, password: password})\n }", "function send_invite() {\r\n\tvar mailer = new Mail();\r\n\tvar admin = app.getObjects(\"User\",{username:\"admin\"})[0];\r\n\tvar hp = get_home_page();\r\n\tmailer.setFrom(admin.email, admin.fullnam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
endregion parse office region setDecompressionLocation
function setDecompressionLocation(newLocation) { if (newLocation != undefined) { decompressLocation = newLocation + "/officeDist"; } else { decompressLocation = "officeDist"; } }
[ "function wrappedRegionJParser (file, beg, end, fmt, cb) {\n if (beg >= end) {\n wrappedJParser(file, beg, fmt, cb);\n } else {\n inflateRegion(\n file, beg, end,\n function (b, ebsz) {\n nextBlockOffset(\n file, end,\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers or deregisters pending action bound with upload progress.
_updatePendingAction() { const pendingActions = this.editor.plugins.get( _ckeditor_ckeditor5_core_src_pendingactions__WEBPACK_IMPORTED_MODULE_1__["default"] ); if ( this.loaders.length ) { if ( !this._pendingAction ) { const t = this.editor.t; const getMessage = value => `${ t( 'Upload in progress' ) } ...
[ "_updatePendingAction() {\n const pendingActions = this.editor.plugins.get(\n _ckeditor_ckeditor5_core_src_pendingactions__WEBPACK_IMPORTED_MODULE_1__[\n 'default'\n ]\n );\n\n if (this.loaders.length) {\n if (!this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a reference to the AbortController constructor. In browsers, AbortController will always be available as global (native or polyfilled)
getAbortController() { return AbortController; }
[ "function createAbortController() {\n if (supportsAbortController) {\n return new AbortController();\n }\n return undefined;\n }", "function createAbortSignal() {\n const signal = Object.create(AbortSignal.prototype);\n EventTarget.call(signal);\n abortedFlags.set(signa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform stream implementation, receive a binary chunk
_transform(chunk, encoding, callback) { const bg = concatgen([this._tmpbuf, chunk]); let recbytes = []; while (true) { // Get next byte, or save any incomplete record const b = bg.next(); if (b.done) { this._tmpbuf = Buffer.from(recbytes); return callback(); } r...
[ "function transform(chunk, encoding, cb) {\n // only transform for raw bytes\n if (raw) {\n const response = BSON.deserialize(chunk);\n response.cursor.firstBatch.forEach(function(doc) {\n this.push(BSON.serialize(doc));\n }.bind(this));\n return cb();\n }\n // otherwise go ba...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
camera state: opened / closed
switchCamera() { const value = this.state.cameraOpened ? false : true; const action = switchCameraState(value); store.dispatch(action); // reverse color while it is turning if (value) { this.cameraRef.current.className = `${"tool-icon-name"} ${"toolIcon-rev"}`; ...
[ "switchCamera() {\n var state = this.state;\n state.cameraType = state.cameraType === Camera.constants.Type.back ? Camera.constants.Type.front : Camera.constants.Type.back;\n this.setState(state);\n }", "function EngineState(){\n this.initialized = false;\n this.ActiveCamera = 0;\n}", "function open...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a function for workspacesWorkspaceHooksUidGet / Returns the webhook with the specified id installed on the given workspace.
workspacesWorkspaceHooksUidGet(incomingOptions, cb) { const Bitbucket = require('./dist'); let defaultClient = Bitbucket.ApiClient.instance; // Configure API key authorization: api_key let api_key = defaultClient.authentications['api_key']; api_key.apiKey = incomingOptions.apiKey; // Uncomment t...
[ "workspacesWorkspaceHooksUidGet(incomingOptions, cb) {\n const Bitbucket = require('./dist');\n let defaultClient = Bitbucket.ApiClient.instance;\n // Configure API key authorization: api_key\n let api_key = defaultClient.authentications['api_key'];\n api_key.apiKey = incomingOptions.apiKey;\n // ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to check compatibility Returns the best matched friend entry
function compatibilityTest(scores) { var match = {}; var matchIndex = 0; var sum = 0; for (var i=0; i<friends.length; i++) { var tempSum = 0; // Get the diff between each score for a given friend and the new friend // Add them up together for (var j=0; j<friends[i].answers.length; j++) { var friendScore...
[ "function compatibility (newFriend, friends) {\n\tvar bestMatch = friends[0];\n\tfor (var i = 0; i < friends.length; i++) {\n\t\tif (friendshipDifference(newFriend, friends[i]) < friendshipDifference(newFriend, bestMatch)) {\n\t\t\tbestMatch = friends[i];\n\t\t}\n\t}\n\treturn bestMatch;\n}", "function findBestMa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a proper todo li with correct HTML
function makeTodoHTML(todoText) { return "<li class=\"todo-item\"><span class=\"delete-todo\"><i class=\"fa fa-times\" aria-hidden=\"true\"></i></span> " + todoText + "</li>"; }
[ "function createTodoListItem(todo) {\n var checkbox = document.createElement('input');\n checkbox.className = 'toggle';\n checkbox.type = 'checkbox';\n checkbox.addEventListener('change', checkboxChanged.bind(this, todo));\n\n var label = document.createElement...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the list of items at the given range. The returned items are the highest list item blocks that cover the range. Returns an empty list if no list of items can cover the range
function getItemsAtRange(opts, value, range) { range = range || value.selection; if (!range.startKey) { return (0, _immutable.List)(); } var document = value.document; var startBlock = document.getClosestBlock(range.startKey); var endBlock = document.getClosestBlock(range.endKey); ...
[ "ranges () {\n var range = this._list.at(0)\n const ranges = []\n while (range) {\n ranges.push([range.data.a, range.data.b])\n range = range.prev\n }\n return ranges\n }", "async getBlocksByRange (from: number, to: number, blockchain: string = 'bc', opts: Object = { asBuffer: true }): P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
x update the OffCanvas content
_updateOffCanvasContent(response) { OffCanvas.setContent(response, false, this._registerRemoveProductTriggerEvents.bind(this)); }
[ "_refreshCanvas() {\n this._refreshCanvasSize();\n this.renderCanvas();\n }", "function updateDraw(){\r\n //ToDo\r\n }", "static _updateCanvas() { if (this._canvas) this._updateExistingCanvas(); }", "render() {\n render(offscreenCanvas);\n }", "update(){\n this.draw();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decide whether or not 'bot' needs to be passed in to this function (find a way to avoid!) Reduce Play to the bare minimum inputs: url Move bot, voiceChannel, textChannel, to a BroadcastInitialize function of some sort.
Play(bot, voiceChannel, textChannel, url){ this.Broadcast = bot.Client.createVoiceBroadcast(); this.VoiceChannel = voiceChannel; this.TextChannel = textChannel; var self = this; this.JoinChannel(this.VoiceChannel) .then(function() { self.PlaySong(url); }) ...
[ "function setBroadcastOrExt() {\n clearTimeout(setCallTimeout);\n Debug(\"setBroadcastOrExt Channe broadcast tunedSource > \"+ tunedSource);\n if($('.page-active .widget .video-object .broadcast-object #vidObject').length == 0) {\n $('.page-active .widget .video-object .broadcast-object').html('<object id=\"v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
xEvent, Copyright 20012007 Michael Foster (CrossBrowser.com) Part of X, a CrossBrowser Javascript Library, Distributed under the terms of the GNU LGPL
function xEvent(evt) // object prototype { var e = evt || window.event; if(!e) return; if(e.type) this.type = e.type; if(e.target) this.target = e.target; else if(e.srcElement) this.target = e.srcElement; // Section B if (e.relatedTarget) this.relatedTarget = e.relatedTarget; else if (e.type ==...
[ "function xEvent(evt) // object prototype\n{\n var e = evt || window.event;\n if(!e) return;\n if(e.type) this.type = e.type;\n if(e.target) this.target = e.target;\n else if(e.srcElement) this.target = e.srcElement;\n\n // Section B\n if (e.relatedTarget) this.relatedTarget = e.relatedTarget;\n else if (e....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to remove Firewall Api Key
function removeFirewallAPIKey() { $.ajax({ url: '/en-US/splunkd/__raw/servicesNS/-/Splunk_TA_paloalto/storage/passwords/%3Afirewall_api_key%3A', type: 'DELETE' }).success(function () { console.log('Firewall API Key Deleted.'); }).error(function () { console.log('Error deleting Firewa...
[ "remove() {\n try {\n const keyManager = new KeyManager();\n\n keyManager.deleteKey();\n\n console.log('API key removed.'.blue);\n\n return;\n } catch (error) {\n console.error(error.message.red);\n }\n }", "function removeUserApiKey()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }