query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Detect whether the message contains hate word.
function detectHate(data) { let reg = new RegExp('.*\\bhate\\b.*',"i"); return reg.test(data); }
[ "function containsSwearwords(message) {\n return message !== badWordsFilter.clean(message);\n}", "function isShouting(message) {\n console.log('hey hey ', message);\n return message.replace(/[^A-Z]/g, '').length > message.length / 2 || message.replace(/[^!]/g, '').length >= 3;\n}", "function containsSwearwo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get direction after coordinate transpose
function getTransposedDirection(direction, coordinate) { if (coordinate.isTransposed) { switch (direction) { case constant_1.DIRECTION.BOTTOM: return constant_1.DIRECTION.LEFT; case constant_1.DIRECTION.LEFT: return constant_1.DIRECTION.BOTTOM; case constant_1.DIRECTION.RIGHT: ...
[ "getDirection() {\n\n var mat = this.getViewMatrix()\n var forward = vec3.fromValues(-mat[2], -mat[1 * 4 + 2], -mat[2 * 4 + 2]);\n vec3.normalize(forward, forward);\n\n return forward;\n }", "direction(tile) {\n var direction = new Array(2);\n direction[0] = this._row - tile._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds the streamer to the my streamers
function AddStreamer(arg){ // appends the streamer names to the list var list = document.getElementById("my-streamers-list"); var li = document.createElement("li"); var span = document.createElement("span"); span.innerHTML = " "; li.innerHTML = arg.name; // checks if streams is offline // and sets the ci...
[ "function addStreamer(streamer) {\n var newStreamer = streamer[0].toLowerCase();\n var streamerExist = $('.streamer-container').find('*').hasClass(newStreamer);\n if (streamer) {\n // fix .fadeOut default setting from display:none (which will prevent additional msgs to show)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
listen for clicks on start and stop
function clickListener(){ start_span.addEventListener('click', function(){ startTimer("start"); }) stop_span.addEventListener('click', function(){ stopTimer("stop"); }) reset_span.addEventListener('click', function(){ resetTimer("reset"); }) }
[ "listenStopButton() {\n\n //Show stop button\n this.fbRStopBtn.style.display = 'inline';\n\n this.stopBtns.forEach(element => {\n element.addEventListener('click', this.handleStopButton, false);\n });\n }", "function startStop(numberOfButtons, button) {\n if (numberOfBut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a descriptive name from JobCode
function getNameFromJob(job) { var name = 'Unknown'; if (job.substr(0, 3) == 'VJ1') { name = 'Urin'; } else if (job.substr(0, 3) == 'VK1') { name = 'Prostata'; } return name; }
[ "function getJobCode(job) {\n\tif (job == 'Director de projectes') {\n\t\treturn 'Director_Projectes';\n\t} if (job == 'Programador Senior') {\n\t\treturn 'Programador_Senior';\n\t} if (job == 'Programador Mid-Level') {\n\t\treturn 'Programador_Mid';\n\t} if (job == 'Programador Junior') {\n\t\treturn 'Programador_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
select HRUs to match user entered percentage
function selectHRU(){ var perc = $("#hru_percent").val(); var perc_temp = 0; if(perc == "") return; if(parseFloat(perc) == 0) return; $("#hru_info_temp_select > option").each(function() { $(this).attr('selected', false); if(parseFloat(perc_temp) < parseFloat(perc)) { perc_temp = parseFloat(perc...
[ "function percentagePhD( data ){\n return( (_.reduce(\n _.pluck( _.where( data, {Level: \"Doctoral\"} ), \"AWARDS\"),//list for _.reduce\n function( memo, awardNum){ //iteratee for _.reduce\n return( memo + awardNum);\n }) / totalDegrees(data) * 100) //after total ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cosine Similarity Calculation functions
function ComputeCosineSimilarity(vecA, vecB) { return VectorDotProduct(vecA, vecB) / (VectorMagnitude(vecA) * VectorMagnitude(vecB)); }
[ "static cosineSimilarity(vector1, vector2) {\n const v1 = Array.from(vector1.values());\n const v2 = Array.from(vector2.values());\n let dotProduct = 0.0;\n let ss1 = 0.0;\n let ss2 = 0.0;\n const length = Math.min(v1.length, v2.length);\n for (let i = 0; i < length; i++) {\n // Ignore pai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
unzips wat to temp, determines main html, renders in preferred viewer
function openWAT_v2(opened_file) { const watfile_path = opened_file.split("/"); const full_filename = watfile_path[watfile_path.length - 1]; // file.wat const filename = full_filename.substr(0, full_filename.indexOf(".wat")); let unzipper = unzip_wat(opened_file); unzipper.on("error", function(err) { con...
[ "function ReadOfArchiveFileCompletedJsZipTry2(evt)\n{\n\n var htmlZipFile = new JSZip();\n\n htmlZipFile.loadAsync(evt.target.result)\n .then(function success(zip) {\n console.log('Read zip file');\n \t var filesStr = \"HTML Files (should only be one):<br><br> \";\n var fileNames = zip.file(/.h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Window resize event listener Attached only when responsive mode is enabled, it checks wether a different size mapping can be activated after resize and forces the slot to be refreshed if it's the case
handleWindowResize() { const { windowResizeDebounce } = this; clearTimeout(this.windowResizeListenerDebounce); this.windowResizeListenerDebounce = setTimeout(() => { const currentSizeMappingIndex = this.getCurrentSizeMappingIndex(); if (currentSizeMappingIndex !== this.currentSizeMappi...
[ "function onWindowResize() {\n updateSizes();\n }", "function handleWindowResize() {}", "onResizeStart() {}", "function handleWindowResize() {\r\n // TODO: add code\r\n}", "handleWindowResize() {\n this.forceUpdate();\n }", "static onResize() {\n Scene.active.onResize();\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCIONES Funcion para registrar los datos de un banco
function registrarBanco() { Ext.Ajax.request({ url: 'control/registrarBanco.php', method: 'GET', params: { ajax: 'true', nombre: Ext.getCmp('nombreBanco').getValue().replace(/ +/g,'-'), estatus: 1, }, //R...
[ "async register() {\n await this.connection.query('INSERT INTO users(email, password, first_name, last_name) VALUES(?,?,?,?)',\n [this.email, this.password, this.name.first, this.name.last]);\n }", "static async register(data) {\n // add json validation here\n const duplicateCheck = await db.query(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
On drain handler to clear binding.
function onDrainClearBinding () { this._binding.clear() }
[ "onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reseller.list_snapshot [PRODUCTION] [See on api.ovh.com](
ListInstanceCurrentSnapshots(serviceName) { let url = `/hosting/reseller/${serviceName}/snapshot`; return this.client.request('GET', url); }
[ "DetailOfASnapshot(serviceName, snapshotId) {\n let url = `/hosting/reseller/${serviceName}/snapshot/${snapshotId}`;\n return this.client.request('GET', url);\n }", "async snapshot() {\n const suite = suites.get(this);\n const dispatch = new dispatch_1.Dispatch(suite);\n cons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search Girvi By Serial Number
function searchGirviBySerialNo(serialNo) { poststr = "grvSerialNo=" + encodeURIComponent(serialNo); search_banner_girvi_by_amount('include/php/olgssndv.php', poststr); //change in filename @AUTHOR: SANDY21NOV13 }
[ "function searchBySerialNum( searchText ){\n\t\tfor (var i = 0; i < terminalDetailArray.length; i++) {\n\t\t\tvar currentTerminal = terminalDetailArray[i];\n\t\t\tif(currentTerminal.serialNumber == searchText){\n\t\t\t\tif(currentTerminal.latitude == 0 && currentTerminal.longitude ==0 ){\n\t\t\t\t\talert(\"The term...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
bit like data in component one store per application di component bisa diakses dengan $store.state.counter tapi ada cara lebih better ketika mengkases state/data di bawah ini, yakni dengan getter
state() { return { counter: 0 }; }
[ "function getCountersState() {\n return {\n counters: store.getAll()\n };\n}", "function getAppState() {\n console.log('getting app state...');\n return {\n count: CounterStore.getCount()\n };\n}", "getCounterValue() {\n return this.state.counter;\n }", "count() {\n let num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing VpcPeeringConnection resource's state with the given name, ID, and optional extra properties used to qualify the lookup.
static get(name, id, state, opts) { return new VpcPeeringConnection(name, state, Object.assign(Object.assign({}, opts), { id: id })); }
[ "static get(name, id, state, opts) {\n return new VpcPeeringConnectionAccepter(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new VpnConnection(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This calls all implementations of hook_theme and builds the DrupalGap theme registry.
function drupalgap_theme_registry_build() { try { var modules = module_implements('theme'); $.each(modules, function(index, module) { var function_name = module + '_theme'; var fn = window[function_name]; var hook_theme = fn(); $.each(hook_theme, function(element, variables) { ...
[ "function addTheme() {\n\n}", "function theme_init() {\n\t// prepare\n\ttheme_prepare();\n\n\t// toggle\n\ttheme_toggle();\n\n\t// select\n\ttheme_select();\n}", "function FRESHTheme() {\n\n }", "function themesLoaded() {\r\n // Update the themesMap to override the hardcoded values\r\n themesMap = them...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to pretty print running processes
function printRunningProcesses(processes){ processes.map(function(element){ console.log(" pid: " + element.pid + " ; " + "name: " + element.name); }) }
[ "function list() {\n var n = countProcesses();\n\n // Check if the processes map is empty\n if (n == 0) {\n return \"No processes\";\n }\n else {\n var output = \"\" + n + \" running \";\n\n // Pluralize\n if (n == 1)\n output += \"process \\r\\n\";\n els...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
jqpm commands Install given list of packages. :param packages: List of package names to install
function installPackages(packages) { async.forEach(packages, function(name) { var installCallback = function(err) { if (err) { log('error', "failed to install %s: %s", name, err); } else { log('info', "%s installed successfully", name); } }; var query = name + " jquery language:JavaScript"; g...
[ "function installPackages(packages) {\n spawn.sync('npm', [\n 'install',\n '-D',\n ...packages\n ], { stdio: 'inherit' });\n}", "function installPackages(packages) {\n const parsedPackages = parsePackageArray(packages);\n const orderedPackages = orderPackageObj(parsedPackages);\n return orderedPacka...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output: "abdec" Explanation: The smallest substring having all characters of the pattern is "abdec" abdbca
function smallestSubstringWithallChara(str, pattern) { let end = 0; let start = 0; const charaMap = {}; let match = 0; let resultChara = '' let maxLength = 0; for(let i = 0; i < pattern.length; i++) { if (!charaMap[pattern[i]]) charaMap[pattern[i]] = 0; charaMap[pattern[i]] ...
[ "function minLength(s) {\n // return s.split(\"CD\");\n\n let currWord = s;\n\n while (true) {\n const newWord = currWord.split(\"AB\").join(\"\").split(\"CD\").join(\"\");\n if (newWord.length === currWord.length) return currWord.length;\n else currWord = newWord;\n }\n}", "function findSubstring(st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
refresh page every day (at 00:00) set date in header
function writeCurrentDate() { //upisivanje u header let headerDate = document.querySelector("#headerDate"); todayDate = new Date(); yesterdayDate = new Date(Date.now() - 86400000); let weekday = todayDate.toLocaleDateString(undefined, { weekday: "long" }); //undefined bi trebalo dati system default le...
[ "function refreshPage() {\n // we're on the scheduled page and there is a scheduled date (ie not cancellation)\n // and calendar view is active and the scheduledDateTime is not on the calendar\n // force calendar to go to the new scheduled date\n if ($('.scheduled-page').length > 0 && sc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gen pet tips html
function gen_pet_tips_html(equipid, big_img_root, equip_face_img, pet_skill_url, pet_desc, pet_name){ var pet_attrs = get_pet_attrs_info(pet_desc); var template = get_tips_template($("pet_tips_template").innerHTML); var result = template.format(equipid, big_img_root,equip_face_img, pet_name, pet_attrs.pet_grade, p...
[ "function gen_equip_tips_html(equipid, equip_name, equip_desc, equip_type_desc, big_img_root, equip_face_img, pet_skill_url){\t\n\tvar template = get_tips_template($(\"equip_tips_template\").innerHTML);\n\tvar result = template.format(equipid, big_img_root, equip_face_img, equip_name, equip_type_desc, equip_desc);\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create add form when submitted, parse input and add new source to data list.
createAddForm() { this.addForm = document.createElement('form') this.addForm.setAttribute('hidden', '') let sourceLabel = document.createElement('label') sourceLabel.innerText = 'Source:' this.addForm.appendChild(sourceLabel) this.addForm.appendChild(document.createEleme...
[ "function addDataSource() {\n source = currentDataSource();\n if (!hasUserAddedSource(source)) {\n search[\"sources\"].push({ \"id\": source[\"id\"], \"filters\": [], \"limit\": 10 });\n changedToDataSource();\n\n var optionElement = document.getElementById(\"Source-Option-\" + source[\"id\"]);\n opti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search for internalId in results use first result
function searchResults(results,columns,filterBy,filterColumn){ var resultIndex = 0; if(filterBy && filterColumn){ resultIndex = filterResults(results,filterBy,filterColumn); } if(results.length > 0){ var data = ''; var internalid; for (var k = 0; k < columns.length; k++) { va...
[ "findSearchResult(id) {\n //TODO: Store all search results in a map, and then just get the one at key[id]?\n // would that be more efficient?\n var $result = this.$results.children().filter('[data-db-id=\"' + id + '\"]');\n if ($result.length > 0) {\n return $result[0];\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
assigns logged menu buttons events
function assignLoggedMenuEvents(){ /* news */ Event.observe($('btnNews'), 'click', function(event){ MenuDialog.toDailyNewsDialog(); }); /* statistics */ Event.observe($('btnStatistics'), 'click', function(event){ MenuDialog.toRaitingsAndStatisticsDialog(); }); /* my page */ Event.observe($('btnMyP...
[ "function assignUnloggedMenuEvents(){\n\t\t/* about */\n\t\tEvent.observe($('btnAbout'), 'click', function(event){\n\t\t\tMenuDialog.toAboutDialog();\n\t\t});\n\t\t/* news */\n\t Event.observe($('btnNews'), 'click', function(event){\n\t\t\tMenuDialog.toDailyNewsDialog();\n\t\t});\n\t\t/* statistics */\n\t\tEvent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filtrar Estabelecimento e GP.
function filtrarEstabGp() { function dado() { //ajax var type = 'POST', url = '/_22060/filtrarEstabGp', data = { estabelecimento_id : $('.estab' ).val(), gp_id : $('._gp_id').val(), up_id : $('._up_id').val(), data_ini : $('#data-ini').val(), data...
[ "function filtrar(){\n const resultado = inventario.filter( filtrarmarca ).filter( filtrararticulo );\n mostrar(resultado);\n}", "function filtroGrupoArmado(){\n var paginas;\n myFeatureLayer = new QueryTask(servicio);\n var query = new Query();\n query.wh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transitions two cards The old one is deleted at the end
function transitionCards(cards){ if (!isInFocus){ $(cards[0]).remove(); return; } // Pick a random animation let animation = Math.floor(Math.random() * 8); // If animating the old card if (animation <= 3){ $(cards[1]).css("z-index", "0"); $(cards[0]).css("z-index", "1"); let name; switch(animati...
[ "function slideOutFrontAndReplace () {\n\tif (!isTransitioningCard) {\n\t\tisTransitioningCard = true;\n\t\tsmoothScroll();\n\t\tvar frontCard = $('.frontResult');\n\t\tvar secondCard = frontCard.next();\n\t\t\n\n\t\tfrontCard.animate({\n\t left: '-150%'\n\t }, { duration: 500, queue: false, complete: func...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return cdata escaped CDATA `str`.
function cdata(str) { return '<![CDATA[' + escape(str) + ']]>'; }
[ "function cdata (str) {\n return '<![CDATA[' + escape(str) + ']]>';\n}", "function ConvertToCDATAString(string) {\n return string\n .replace(/\\s+/g, \"_\")\n .replace(/[^a-zA-Z0-9_\\.\\-\\:\\u0080-\\uFFFF]+/g, \"\");\n}", "function StripCdataEnclosure(string) {\n\t\tif (string.indexOf(\"<![CDATA[\") > ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function returns all techs
function getAllTechs (req, res) { TECH.findAll({ where: { ProfileId: 1 } }).then(techs => { res.send({ techs: techs }) }).catch(err => { console.log(err) res.send(false) }) }
[ "function listTech(){\n let techs = [];\n techs.push(\"Node.js\");\n techs.push(\"Ruby\");\n response[\"status\"] = 200;\n response[\"message\"] = \"The list of supported technologies\";\n response[\"body\"] = techs;\n\n return response;\n}", "function listTechnologies(){\n let available =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set level height and width on load
function ImportLevelBounds(levelWidth, levelHeight) { if(levelHeight != undefined) { LevelHeight = levelHeight; _heightInputBox.value = levelHeight; } else { LevelHeight = _canvas.height; _heightInputBox.value = _canvas.height; } if(levelWidth != undefine...
[ "set_level() {\n this.height = (this.totalVolume + this.minVolume) * this.maxHeight / this.maxVolume;\n\n }", "set heightmapWidth(value) {}", "function initLevel() {\n\tbuildLevel(levelNum);\n\tdraw(null);\n}", "function sizingOnload() {\n \n narrow = new Narrow();\n medium = new Medium();\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
product image zoom initialization function
function initzoom() { if ($('.easyzoom').length > 0) { var $easyzoom = $('.easyzoom').easyZoom(); } }
[ "function image_zoom_init() {\n\n}", "function initImageZoom() {\n\n \t//reset the zoom\n \tpublicAPI.resetZoom();\n\n \tvar\t$parentWidth = $parent.width();\n\n\n \tif($parentWidth) {\n\n\t\t\tvar $imageWidth = $image[0].naturalWidth,\n \t\t$imageHeight = $image[0].naturalHeight,\n\n \t\tnewHei...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use a preconfigured TypeScript "printer" to render the text of a node, without comments.
function nodeToString(typeNode) { return LineFeedPrinter_1.lineFeedPrinter.printNode(typescript_1.EmitHint.Unspecified, typeNode, typeNode.getSourceFile()); }
[ "function print(node) {\n\t if (node.kind === 'Fragment') {\n\t return 'fragment ' + node.name + ' on ' + String(node.type) + printFragmentArgumentDefinitions(node.argumentDefinitions) + printDirectives(node.directives) + printSelections(node, '') + '\\n';\n\t } else if (node.kind === 'Root') {\n\t return n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a session by id.
function findById(id, settings) { settings = settings || __1.ServerConnection.makeSettings(); var running = runningSessions.get(settings.baseUrl) || []; var session = algorithm_1.find(running, function (value) { return value.id === id; }); if (session) { return Promise.resolv...
[ "function findSessionById(id, options) {\n var sessions = Private.runningSessions;\n for (var clientId in sessions) {\n var session = sessions[clientId];\n if (session.id === id) {\n var sessionId = {\n id: id,\n notebook: { path: session.notebookPath },\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
static boolean function that checks if the given url has already been checked.
function hasBeenChecked(url,checkedUrls){ var hasBeenChecked = false; if(checkedUrls.indexOf(url)!=-1) return true; return hasBeenChecked }
[ "function UrlExists(url) {\n var http = new XMLHttpRequest();\n try {\n http.open(\"HEAD\", url, false);\n http.send();\n return http.status != 404;\n } catch (error) {\n return false;\n }\n }", "function isUrlUnique(url){\n\t\treturn ($.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method that creates the dialogues of the game and puts them in the hash tables
createDialogues() { let sData = currentScene.cache.json.get('dialogues').SingleDialogues; let nData = currentScene.cache.json.get('notes').Notes; this.dialoguesHashTable = new HashTable(); this.notesHashTable = new HashTable(); sData.forEach(temp => { ...
[ "function addDialogues(){\n dialogues={\n\n//npc_name:{font_name, key to press to go to the next 'scene', key to press to exit the dialogue, which face to use(disabled by default)\n gray_critter:{ font:\"small\", skipkey:\"a\", esckey:\"b\", who: faces,\n scenes:[\n//each 'scene' corresponds t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
scroll to the last message into view.
navigateToBottom() { let lastMessage = document.getElementById("lastMessage"); if(lastMessage){ lastMessage.scrollIntoView(true); } }
[ "function goToLastMessage() {\n\t\tdocument.getElementById('last').scrollIntoView(true);\n\t}", "function godown ()\n{ $messages.lastElementChild.scrollIntoView();\n}", "function scrollToLastMessage() {\n // Put message container scroll on last message received/sent\n $timeout(function() {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns Keystone Auth Token ID
function getAuthTokenId() { return _store2.default.getState().login.getIn(['keystoneAccess', 'token', 'id']); }
[ "getAccessTokenSysID() {}", "function makeAuthToken() {\n var token = 'Auth'+ new Date().getTime();\n\n return token;\n }", "generateTokenId() {\n switch (this.constructor.name) {\n case 'DeviceCode':\n case 'RefreshToken':\n case 'AuthorizationCode':\n return nanoid(27...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adiciona um elemento span ao div e o retorna.
function AdicionaSpanAoDiv(texto, id_span, classe, div) { var span = CriaSpan(texto, id_span, classe); div.appendChild(span); return span; }
[ "function addSpan(parent_div) {\n\n var parent = document.getElementById(parent_div)\n var child = document.createElement('span')\n parent.appendChild(child)\n return child\n\n}", "function createNewSpan(data) {\r\n return $(document.createElement('span'))\r\n\t ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fibonacci with a for loop if you know that whatever arry comes out, the first few elements will always be the same, than go \ ahead and initialize them
function fibonacci(n) { var arr=[]; for(let i=0; i<n;i++){ arr.push(i); } for(let i=2;i<n;i++){ arr[i]=arr[i-1]+arr[i-2] } return arr; }
[ "function fibonacciSeries(){\n var fib=[];\n fib[0]=0;\n fib[1]=1;\n\n for(var i=fib.length; i<=50; i++){\n fib[i] = fib[i-2] + fib [i-1];\n console.log(fib);\n } \n}", "function fibonacci10(){\n let result = [1,1];\n for(let i=2; i <10; i++){\n let newFib = res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Broadcast the "viewed" message.
function broadcastViewedMessage(messageChannel, videoId) { console.log(`Publishing message on "viewed" exchange.`); const msg = { video: { id: videoId } }; const jsonMsg = JSON.stringify(msg); messageChannel.publish("viewed", "", Buffer.from(jsonMsg)); // Publish message to the "viewed" exchang...
[ "function viewers(room) {\n const sockets = io.sockets.clients(room);\n const data = sockets.map(function(socket) { return socket.id; });\n if (data.length) io.sockets.in(room).emit('viewers', data);\n}", "function view(bot, message) {\n let texts = ['view','View']\n let isView = false\n texts.forE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
detect click outside the bounds of an element, thanks to
function clickOutsideBounds(e) { if (status() === 2 /* Preview */ && !$element.is(e.target) && $element.has(e.target).length === 0) { status(1 /* Collapsed */); } }
[ "function clickOutsideBounds(e) {\n if (status() === 2 /* Preview */ && !$element.is(e.target) && $element.has(e.target).length === 0) {\n status(1 /* Collapsed */);\n }\n }", "outsideClickDetection(e) {\n if (this.elements.wrapper.contains(e.targ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns a collection of attributes values needed for subscription(s) search.
function getSubscriptionAttributes(body) { let subAttributes=[body.type]; for (var attributename in body) { if ((attributename !== '_id') && (attributename !== 'id') && (attributename !== 'type')){ subAttributes.push(attributename); } } /*Display Entity (ies) attributes */ ...
[ "get attributes() {\n return Object.values(this.attr).reduce((result, cur) => {\n return result.concat(cur);\n }, []);\n }", "getAttributes () {\n\t\tlet ret = [];\n\t\tfor (let i in this.attributes)\n\t\t\tret.push(this.attributes[i]);\n\t\treturn ret;\n\t}", "getAttributeList () {\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Criar os marcadores para a lista de locais
function criarMarcadores(map) { for (localKey in locais) { const posicao = locais[localKey]; const title = legendasLocais[localKey].descricao; posicao.forEach((pos) => { const [lat, lng] = pos; criarMarcador(map, { lat, lng }, title, localKey); }); } }
[ "function agregarMarcadores (marcador) { \n debugger;\n var claves = [];\n for (var key in marcadores)\n {\n claves.push(key);\n }\n //Verificamos si ya existe el marcador obtenido de la bd en la lista\n //que mantiene el cliente se sus marcadores.\n var result = $.inArray(marcador.id, claves);\n //var ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup toggleablility given a mapping array of objects
function map(mapping){// Make a jquery collection of all of the toggleable elements var $toggleables=_.reduce(mapping,function($set,pair){if(pair.show)return $set.add(pair.show);else return $set;},$());// Loop through the mappings and assign click listeners _.each(mapping,function(pair){// Required properties if(!_.has...
[ "function toggleHandler(e) {\n var $evt = $(e.target);\n var type = $evt.attr('name');\n //toggle true or false value in object\n markersSet[type] = !markersSet[type];\n if (markersSet[type]) {\n toggleMarkers(type, true);\n } else {\n toggleMarkers(type, false);\n }\n }", "functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create video object from url
function VideoObj(url) { // If url is null or empty if (url == undefined || url == "") { return null; } var obj = {}; // Init OBJ // try for youtube var youtubeRegex = /(\?v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/; ...
[ "function parseVideo(url) {\n var type = null;\n var id = null;\n\n if (url.match(/(https?:\\/\\/|).*(mp4|m4v|mov)(\\?|$)/) !== null) {\n type = 'mp4';\n id = url;\n }\n else {\n // - Supported YouTube URL formats:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
watch for league change in league dropdown menu
function watchLeagueChange() { $("#allLeagues").on("change", function () { const selectedLeague = $(this).val(); getTeams(selectedLeague); }); }
[ "function watchTeamChange() {\n $(\"#selectedLeague, #allLeagues\").on(\"change\", function () {\n const idTeam = $(this).val();\n $(\"#teamId\").val(idTeam);\n });\n}", "function selectLeague(e){\n\t\t\t\tvar allowed = [1500, 2500, 10000];\n\t\t\t\tvar cp = parseInt($(\".league-select option:selected\")....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will generate a random 26 character string for the PHP session ID
function random_id() { var result = ''; chars = '0123456789abcdefghijklmnopqrstuvwxyz'; for (var i = 26; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))]; return result; }
[ "function generateSessionID() {\n\tlet alphaNum = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890\";\n\n\tlet id = \"\";\n\n\tfor(var i = 0; i < 3; i++) {\n\t\tlet index = randomInt(0, alphaNum.length);\n\t\tlet char = alphaNum[index];\n\t\tid += char;\n\t}\n\n\tid += \"-\";\n\n\tfor(var i = 0; i < 3; i++) {\n\t\tlet index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new Zone into the server
addOrigin(name) { const key = name.split('.')[0] if (this.zone[key]) throw 'This zone already exists on the server. Please try adding a record.' this.zone[key] = new Zone() this.zone[key].setOrigin(key + '.') return this }
[ "function zoneAdd (zone) {\n\n\t\tdatabases.zones.insert({name: zone}, function (err, doc) {\n\t\t\t// send back current zones\n\t\t\tsendZones();\n\t\t});\n\t}", "async function addZone(zone) {\r\n let res = await fetch(STOCK_API_URL + \"addZone\", {\r\n method: 'POST',\r\n mode: 'cors',\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get row from tile id
getRowFromTile(id){ let row; if(id.split('_')[1][1] != undefined){ row = id.split('_')[1][0] + id.split('_')[1][1]; }else { row = id.split('_')[1][0]; } return row; }
[ "getRowFromTile(id) {\n let row;\n if (id.split('_')[1][1] != undefined) {\n row = id.split('_')[1][0] + id.split('_')[1][1];\n } else {\n row = id.split('_')[1][0];\n }\n return row;\n }", "function getRow(tile) {\n return parseInt(tile.id.split(\"_\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies initial settings to the TimePicker element.
_applyInitialSettings() { const that = this, value = that.value; let hours, minutes; hours = value.getHours(); minutes = value.getMinutes(); if (that.format === '12-hour') { if (hours < 12) { that._ampm = 'am'; that.$amCon...
[ "_initTimePickerInitialValue() {\n if (document.querySelector('#timePickerInitialValue')) {\n new TimePicker(document.querySelector('#timePickerInitialValue'));\n }\n }", "_applyInitialSettings() {\n const that = this,\n value = that.value;\n let hours, minutes;\n\n hou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bind render function to Koa context
use(app) { const self = this; app.context.render = async function (tpl, locals, options) { const ctx = this; const finalLocals = lodash_merge_1.default({}, self.helpers, self.defaultLocals, ctx.state, locals); ctx.body = await self.render(tpl, finalLocals, options); ...
[ "defaultResultHandler(res, ctx) {\r\n res.render(this.view, ctx)\r\n }", "function decorateContextFunction(ctx, next) {\r\n ctx.render = (content) => render(content, document.querySelector('main'));\r\n ctx.setUserNav = setUserNav;\r\n next();\r\n}", "dorender(ctx) {}", "async render(req, n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take answers from props, arrange them so Seller's answers appear first then sort answers
arrangeAnswers() { const { answers } = this.props; // Sort array of answer objects by their value for helpfulness property if (answers) { // filter all answers authored by 'Seller' to seperate arrays const sellerAnswers = answers.filter((answer) => answer.answerer_name === 'Seller'); const...
[ "sortAnswers(answerList) {\n const sortedAnswerList = _.sortBy(answerList, 'helpfulness');\n // Reverse the order of the answers so the most helpful is first\n this.setState({ entries: [...sortedAnswerList.reverse()] });\n }", "sortByDifficulty(answers) {\n\t\tconst compareCorrectness = (a, b) => {\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Bit Crusher Effect. Adapted from
function BitCrusher (sampleRate, bits) { var self = this, sample = 0.0; self.sampleRate = sampleRate; self.resolution = bits ? Math.pow(2, bits-1) : Math.pow(2, 8-1); // Divided by 2 for signed samples (8bit range = 7bit signed) self.pushSample = function (s) { sample = Math.floor(s * self.resolution + 0.5) ...
[ "function Crush(resolution, mix) {\n var that = audioLib.BitCrusher(Gibber.sampleRate);\n\tif(typeof arguments[0] === \"object\") {\n\t\tvar obj = arguments[0];\n\t\t\n\t\tfor(key in obj) {\n\t\t\tthat[key] = obj[key];\n\t\t}\n\t}\n\t\n\tthat.name = \"Crush\";\n\tthat.type = \"fx\";\n\t\n\tthat.gens = [];\n\ttha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The implementation Return a promise for the results of an entity request for a given entity. May immediately resolve to a the cached results for some key. If a request is made then the results will be cached for next time.
function getCacheableEntity(key, id, request, refresh) { console.time('getCacheableEntity:' + key); if (!refresh && cache[key]) { console.timeEnd('getCacheableEntity:' + key); return $q.when(cache[key]); } return spEntityService.getEntity...
[ "resolve(key, value) {\n const requests = this._requests.get(key) || [];\n if (requests.length > 0) {\n const request = requests.shift();\n request.resolve(value);\n return;\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will reset seconds to 30.
function resetSeconds() { seconds = 30; $("#time").html("<h2>" + seconds + "</h2>"); intervalId = setInterval(decrement, 1000); decrement(); }
[ "function reset() {\n seconds = 15;\n }", "function reset_seconds()\r\n{\r\n\tseconds=0;\r\n}", "function resetTimer() {\n values.timer = 20;\n }", "function removeTime() {\n timer = timer > 30 ? timer - 30 : 0;\n}", "function resetClockinTimeout() {\n clearClockinTimeout();\n console...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
has_css_class checks if a DOM object has class x set
function has_css_class(dom_ob, cl) { var classes=dom_ob.className.split(" "); return array_search(cl, classes)!==false; }
[ "function hasClass(element, cls) {\nreturn (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n}", "function xHasClass(e, c) {\r\n e = xGetElementById(e);\r\n if (!e || !e.className)\r\n return false;\r\n return (e.className == c) || e.className.match(new RegExp('\\\\b'+c+'\\\\b'));\r\n}", "fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of bonus points earned for making the current phrase NOTE: Currently hardcoded to only support two words, because I'm not sure how our current bonus mechanism translates to 3+ words yet
function bonusScore () { // Currently, we have two kinds of bonus: Match and Phrase var bonus = 0; // TODO: Yeah, I know we can fail faster here, but it's 3 in the morning var firstWord = formWord(state.words[0]); var secondWord = formWord(state.words[1]); // Check for a Match Bonus, where bot...
[ "function phraseBonus (first, second) {\n // TODO: (Maybe) add scoring logic to this function separately\n var phrase = first + \" \" + second;\n return (bonusPhrases[phrase] ? config.phraseBonus : 0);\n}", "calculateReadability() {\n const vocab = this.props.store.profile.vocab;\n const text = thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::Kendra::DataSource.SalesforceCustomKnowledgeArticleTypeConfiguration` resource
function cfnDataSourceSalesforceCustomKnowledgeArticleTypeConfigurationPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnDataSource_SalesforceCustomKnowledgeArticleTypeConfigurationPropertyValidator(properties).assertSuccess(); return { Doc...
[ "function cfnDataSourceSalesforceKnowledgeArticleConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_SalesforceKnowledgeArticleConfigurationPropertyValidator(properties).assertSuccess();\n return {\n CustomKnowle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This sample demonstrates how to Add Database principals permissions.
async function kustoDatabaseAddPrincipals() { const subscriptionId = process.env["KUSTO_SUBSCRIPTION_ID"] || "12345678-1234-1234-1234-123456789098"; const resourceGroupName = process.env["KUSTO_RESOURCE_GROUP"] || "kustorptest"; const clusterName = "kustoCluster"; const databaseName = "KustoDatabase8"; co...
[ "setupPermissions() {\n if (!this.role) {\n this.addDefaultPermisionRole();\n }\n else if (iam.Role.isRole(this.role)) {\n this.addLambdaInvokePermission(this.role);\n }\n }", "SetPermissions() {\n\n }", "setupPermissions() {\n if (!this.role) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes two collumn names and swaps them in tableCollumns and tableData
function Reorder(a, b) { var ai = -1; var bi = -1; for (var i = 0; i < tableCollumns.length; i++) { if (tableCollumns[i].title == a) { ai = i; } if (tableCollumns[i].title == b) { bi = i; } if (ai != -1 && bi != -1) { break; } } if (ai == -1 || bi == -1) { console.error(ai, bi); ...
[ "function reOrderCols() {\n\t\n}", "function swapColumns(a, b)\n {\n var colA = columns[a];\n var colB = columns[b];\n\n colA.setAttribute('column', b);\n colB.setAttribute('column', a);\n\n document.body.insertBefore(colB, colA);\n columns[a] = colB;\n columns[b] = colA;\n }", "function ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function called once data is loaded from Twitter API. Calls bubble chart function to display inside vis div
function display(data) { myBubbleChart('#vis', data); }
[ "function display(error, data) {\n myBubbleChart('#activity_chart');\n}", "function display(data) {\n myBubbleChart('#agriculture_plot', data);\n}", "function prepBubbleChart() {\n // setup url\n var urlGet = \"php/bubbleDataLoadAjax.php\";\n // get data from MySQL then calls function\n downloadUrl(urlGet,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create get each entry function with id and callback as parameter
function getEachEntry(id, callback) { console.log(id); // create ajax GET call that gets each entries with id $.ajax({ type: "GET", url: `/api/entries/${id}`, dataType: "json", contentType: "application/json", headers: { Authorization: `Bearer ${jwt}` } }) .done(function(entry)...
[ "function get_entries()\n{\n RMPApplication.debug (\"begin get_entries\");\n c_debug(dbug.country, \"=> get_entries\");\n var my_pattern = {}; // we retrieve all objects in collection\n var options = {};\n eval(collectionid).listCallback(my_pattern, options, get_entries_ok, get_entries_ko);\n R...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate pubkey extraction parameter. When extracting a pubkey from a signature, we have to distinguish four different cases. Rather than putting this burden on the verifier, Bitcoin includes a 2bit value with the signature. This function simply tries all four cases and returns the value that resulted in a successful ...
function calcPubKeyRecoveryParam (e, signature, Q) { typeforce(types.tuple( types.BigInt, types.ECSignature, types.ECPoint ), arguments) for (var i = 0; i < 4; i++) { var Qprime = recoverPubKey(e, signature, i) // 1.6.2 Verify Q if (Qprime.equals(Q)) { return i } ...
[ "function deriveP2PKPubKey(publicKey) {\n // const pubkey = typeConverter.hexStrToBuffer(publicKey);\n // bitcoinjs.payments.p2pk({pubkey}).pubkey;\n return publicKey\n}", "function recoverPubKey(curve,e,signature,i){assert.strictEqual(i&3,i,'Recovery param is more than two bits');var n=curve.n;var G=cur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the grid, the rule and the zeroToOneRatio
reset(rule, zeroRatio) { this.zeroToOneRatio = zeroRatio; rule = rule.split('/'); this.birthConditions = rule[0].split("").map(function(item) { return parseInt(item); }); this.birthConditions.shift(0,1); this.surviveConditions = rule[1].split("").map(function(item) { return parse...
[ "_resetGrid(){\n\t\tthis._grid = {\n\t\t\t0: {\n\t\t\t\t0: 1\n\t\t\t}\n\t\t};\n\t\tthis._spirals = 0;\n\t}", "function resetGrid() {\n removeGrid();\n buildGrid(getDIMForGrid());\n}", "reset() {\n logger.info('Resetting grid');\n for (let j = 0; j < 7; j++) {\n for (let i = 0; i < 6; ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
luego de que se selecciono que capa, se procede a cargar realmente el shp o kml
function consultarTipoCapaSelected(capa, esCargaShape, fileName) { $("#modalTipoCapa").modal("hide"); if(!isNaN(esCargaShape)) _esCargaShape = esCargaShape; if(fileName) _fileName = fileName; _capa = capa; if (_esCargaShape == 0) { cargarShapeFile(_fileName); } el...
[ "function solicitar_archivos_thumnail(idFalla){\n // Se modifica el estado del thumnail durante la carga\n $(\"#imagenThumb\").attr(\"src\",\"app/views/res/generandoArchivos.svg\");\n window.nameSpaceCgi.transformarNubePtos(idFalla);\n }", "function consultarTipoCapa(esCargaShape, fileNa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a multidimensional instructionsarray where similar volumes are grouped while instructions are still sorted by ascending wellnumber if possible
function groupedInstructions(brokenDownSubstances) { let res = []; for (let s = 0; s < brokenDownSubstances.length; s++) { res.push(sortBySmallestWell(groupAmounts(brokenDownSubstances[s]))); } return res; }
[ "function groupTopSubs(array){\n if(array.length <= 8){\n return array;\n }\n\n var temp = ['other', 0]; \n \n for(var i = 7; i < array.length; i++){\n temp[1] += array[i][1];\n }\n\n array = array.slice(0, 7)\n array.push(temp);\n\n return array;\n}", "function create_groups() {\n var array = [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables the ObserveChanges plugin.
enableObserveChangesPlugin() { const _this = this; this.hot._registerTimeout( setTimeout(() => { _this.hot.updateSettings({ observeChanges: true }); }, 0)); }
[ "enableObserveChangesPlugin() {\n let _this = this;\n\n this.hot._registerTimeout(\n setTimeout(() => {\n _this.hot.updateSettings({\n observeChanges: true\n });\n }, 0));\n }", "enableObservers() {\n\t\tfor ( const observer of this._observers.values() ) {\n\t\t\tobserver.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
requestApi api: url to call eg: method: GET, POST, DELETE body: Payload to send to server
function requestApi(api, method, body) { api = api || "/posts"; method = method || "GET"; body = body || null; return new Promise(function(resolve, reject) { let myHeaders = { 'Content-Type': 'application/json' } let options = { url: api, method: method, headers: myHeaders...
[ "apiRequest(data)\n {\n\n }", "testApi ()\n {\n var bodyData = {}\n this.sendTestApiCall('http://127.0.0.1:8080/api/v1/test',bodyData);\n }", "_publicApiRequest(method, params, callback) {\n let options = {\n host: 'bx.in.th',\n path: `/api/${method}/?${que...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current tally of incorrect answers from the DOM and increments it by 1
function incrementWrongAnswer() { let oldScore = parseInt(document.getElementById("incorrect").innerText); document.getElementById("incorrect").innerText = ++oldScore; }
[ "function correctAnswerTally () {\n \t\tcorrectAnswerCount += 1;\n \t\t $(\"#totalCorrect\").text(correctAnswerCount);\n\t\t}", "function increaseAnsweredIncorrect() {\n answeredIncorrect++;\n}", "function countCorrectAnswers() {\n correctAnswers++;\n}", "function incrementWrongAnswer() {\n let...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Each `` will register/unregister itself We use this to detect when tabs are added/removed to trigger the update of the tabs
registeredTabs() { this.updateTabs() }
[ "function TabWatcher () {\n\t\tthis.add = function (id, url, callback) {\n\t\t\temit(callback, null);\n\t\t};\n\t}", "registerTabs() {\n const uris = this.tabs.map((tab) => tab.uri);\n\n $.cookie('open-tabs', JSON.stringify(uris), {expires : 365, path : '/'});\n }", "async registerT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Build and return a collection of aircraft sources (ships or / airbase with ready aircraft) within air op range of the selected / zone.
function getNewMissionAircraftSources(mission) { var sources = []; for (var i = 0; i < aircraftSources.length; i++) { var source = aircraftSources[i]; if (inAirOpRange(source.Location)) { var aircraftCount = mission == "CAP" ? source.FSquadrons : source.TSquadrons + sou...
[ "function loadAircraftSources() {\n landingZones = [];\n aircraftSources = [];\n\n for (var i = 0; i < ships.length; i++) {\n var ship = ships[i];\n\n if (canHasAircraft(ship)) {\n if ($.inArray(ship.Location, landingZones) == -1) {\n landingZones.push(ship.Location)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if body is empty
function checkBody(res, body, cbk, isTrue) { if (isTrue) { cbk(body); return; } if (typeof body !== 'undefined' && body !== null && Object.keys(body).length > 0) { cbk(body); } else { Jwr(res, false, {}, "Requested body seems blank"); } }
[ "get hasBody() {\n return (this.headers.get(\"transfer-encoding\") !== null ||\n !!parseInt(this.headers.get(\"content-length\") ?? \"\"));\n }", "function checkBody(body) {\n let retval = \"App-Message: User supplied empty body.\";\n if (notFalsy(body)) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the cursor to the end of an contenteditable element see
function setCursorToEnd(contentEditableElement) { var range, selection; if(document.createRange) { // Create a range (a range is a like the selection but invisible) range = document.createRange(); // Select the entire contents of the element with the range ...
[ "function move_cursor_to_end(ele) {\n var selection = ele.ownerDocument.defaultView.getSelection();\n var range = ele.ownerDocument.createRange();\n var focusNode = ele;\n while (focusNode.nodeType == 1) {\n var children = focusNode.childNodes;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the user clicks on the button, toggle between hiding and showing the Apply dropdown content
function ApplyFunction() { document.getElementById("Apply_myDropdown").classList.toggle("show"); }
[ "toggle() {\n !this.isDropdownShowing ? this.show() : this.hide();\n }", "function toggleDropdown() {\n dropdownIsHidden ? showDropdown() : hideDropdown();\n }", "function toggleDistrict() {\n dropdownDistrict.style.display = \"block\"\n console.log('toggle')\n\n}", "function showCipherDropd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CMLayerDataset Class Global Variables CMLayerDataset Constructor
function CMLayerDataset() { CMLayer.call(this); this.TheDataset=null; // default }
[ "function CMDataset() \r\n{\r\n\tCMBase.call(this);\r\n\tthis.URL=null;\r\n\t\r\n\tthis.SelectedFeature=-1;\r\n\tthis.MouseOverFeatureIndex=-1; // array of flags for rows?\r\n\tthis.ClickTolerance=8;\r\n}", "function CMDatasetSQL() \r\n{\r\n\tCMDataset.call(this);\r\n\tthis.TheData=null;\r\n\tthis.TheBounds;\r\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function does the entire process of adding spans then substitution of the dates it process the entire html page
function addDatesToPage() { // checkForReferrer(startMondayList); // sets startMonday createRelativeDateDict(startMonday, numberOfWeeks); var pageText = document.body.innerHTML; var processedPage = processMarkers(pageText); document.body.innerHTML = processedPage; replaceRelativeDates(); }
[ "function updateDates() {\n $('span.date').each(function (index, dateElem) {\n var formatted = moment($(dateElem).data('date')).format('l');\n formatted = formatted.replace(/\\d\\d(\\d\\d)/, \"$1\");\n $(dateElem).text(formatted);\n });\n}", "function parseDate(){\n for(var i = 0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepend this game object to another game object and return this
prependTo(gameObject) { this.parent = gameObject; this.parent.gameObjects.unshift(this); return this; }
[ "appendTo(gameObject)\n {\n this.parent = gameObject;\n this.parent.gameObjects.push(this);\n return this;\n }", "prependTo(node) {\n node.prependChild(this);\n return this;\n }", "prepend(handler) {\n const layer = this._wrap(handler);\n layer.next = this.first;\n this.firs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Quarry.io Reception Back Client Knows how to produce multiple router sockets each one connected to a different reception server back end The backend client will heartbeat to the reception back socket telling it the stack routes we provide THe routing therefore is done automatically by the routes we emit from here The r...
function factory(options){ options || (options = {}); options.name || (options.name = 'reception_back_client'); var department = options.department; var dns = options.dns; var switchboard = options.switchboard; var backclient = Device('core.box', { name:options.name }) var warehouse = Warehouse()...
[ "function factory(options){\n\n options || (options = {});\n options.name || (options.name = 'reception_server');\n\n var id = options.id;\n\n var server = Device('core.box', {\n name:options.name\n })\n\n var front = Device('core.wire', {\n type:'router',\n direction:'bind',\n address:options.fro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the canvas elements and style them MinSun: initialized patientWave and patientProgressWave
createElements() { this.progressWave = this.wrapper.appendChild( // for doctor part this.style(document.createElement('wave'), { position: 'absolute', zIndex: 4, left: 0, top: 0, bottom: 0, ov...
[ "addCanvas() {\n const entry = {};\n const leftOffset = this.maxCanvasElementWidth * this.canvases.length;\n\n // Default wave - for doctor's part\n entry.wave = this.wrapper.appendChild(\n this.style(document.createElement('canvas'), {\n position: 'absolute',\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function getMessageWithTime Purpose: Takes a message (usually to be logged) and appends the current time to the beginning Returns: Given parameter with time appended to the front Parameters: Message to append time to
function getMessageWithTime(message) { let today = new Date(); let date = today.getDay() + '/' + today.getMonth() + '/' + today.getFullYear() + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds() + ": "; return date + message; }
[ "function getMessageWithTime(message) {\n let today = new Date();\n let date = today.getDay() + '/' + today.getMonth() + '/' + today.getFullYear() + ' ';\n let hours = today.getHours();\n let minutes = today.getMinutes();\n let seconds = today.getSeconds();\n if(String(hours).length === 1) {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an array of disk lables.
function dskLbls() { var a = []; for (var i = 0; i < dsks.length; i++) { a.push(dskLbl(i)); } return a; }
[ "function getDisks(){\n\t\tvar disks = [\n {name:\"500B83DEF\", type:\"System\", status:\"n/a\", allocations:\"None\", unallocated:\"-\", total:\"930.39 GB\"},\n {name:\"74B83DEF\", type:\"Base\", status:\"In Use\", allocations:\"None\", unallocated:\"-\", total:\"454 TB\"}\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the information on albums Denne metode er lavet af Jeppe, Johan & Benjamin
function updateAlbum() { const title = $('#changeAlbumTitle').val() const desc = $('#changeAlbumDesc').val() updateInfo(title, desc, true) }
[ "function actualizarAlbumesArtista(album){\n \t\t\t\n \t\t\t//alert(\"eeee --> \"+album.artista);\n \t\t\tvar tracks=album.tracks;\n \t\t\tgets++;\n \t\t\t//console.debug(\"gets1 x: \"+gets); \n \t\t\t//ponemos para que pare la barra de progreso faltando 5 albumes\n \t\t\t//por si acaso fallan algunos...\n \t\t\tif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to switch between play button and pause button on click
function playpause(){ if($('#pause').hasClass('activeButton')) { $('#slider,#play,#pause').click(function(){ $('#pause').removeClass('activeButton'); $('#play').addClass('activeButton'); $('#pause').hide(); $('#play').show(); autoswitch=false; }); } //When play is clicked, activate pa...
[ "playAndPauseControl() {\n // Pause Game\n this.htmlPauseBtn.click((event) => {\n this.audio.playButtonPressed();\n this.htmlPauseBtn.addClass('hide');\n this.htmlPlayBtn.removeClass('hide');\n this.modalPause.removeClass('hide');\n this.audio.pau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convertor class for translating TML (TWiki Meta Language) into HTML The design goal was to support roundtrip conversion from wellformed TML to XHTML1.0 and back to identical TML. Notes that some deprecated TML syntax is not supported.
function TML2HTML() { /* Constants */ var startww = "(^|\\s|\\()"; var endww = "($|(?=[\\s\\,\\.\\;\\:\\!\\?\\)]))"; var PLINGWW = new RegExp(startww+"!([\\w*=])", "gm"); var TWIKIVAR = new RegExp("^%(<nop(?:result| *\\/)?>)?([A-Z0-9_:]+)({.*})?$", ""); var MARKER = new RegExp("\u0001([0-9]+)...
[ "function wikitext_to_plain_text(wikitext) {\r\n\t\tif (!wikitext || !(wikitext = wikitext.trim())) {\r\n\t\t\t// 一般 template 中之 parameter 常有設定空值的狀況,因此首先篩選以加快速度。\r\n\t\t\treturn wikitext;\r\n\t\t}\r\n\t\t// TODO: \"《茶花女》维基百科词条'''(法语)'''\"\r\n\t\twikitext = wikitext\r\n\t\t// 去除註解 comments。\r\n\t\t// e.g., \"親会社<!--...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to check how many categories have been checked in the edit subject page
function CountChecksE(which, id) { var maxchecked = 2; var count = 0; var box; if(document.getElementById('edit_subject_' + id).gp.checked == true) { if( which == "gp" ) { box = document.getElementById('edit_subject_' + id).gp; } count++; } if(document.getElementById('edit_subjec...
[ "function setCatCount(){\n\t$(\"#catLstCnt\").text($(\"[name='category']:checked\").length);//Length of Category List\n}", "function setSCatCount(){\n\t$(\"#sCatLstCnt\").text($(\"[name='subCat']:checked\").length);//Length of Sub Category List\n}", "function setSCatCount(){\n\tvar totCount = 0;\n\t$('#parentCa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produces the sections for command line usage. This contains the help guide to display
function commandLineUsageSections() { let sections = [ { header: 'SLCSP Command Line Tool', content: clu.header_content() }, { header: 'Options', optionList: [ { name:"help", description: ...
[ "function helpSection(){\n console.log(\"Usage :-\");\n console.log(\"$ ./todo add \\\"todo item\\\" # Add a new todo\");\n console.log(\"$ ./todo ls # Show remaining todos\");\n console.log(\"$ ./todo del NUMBER # Delete a todo\");\n console.log(\"$ ./todo done NUMBER # Com...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Precedence: modules's config if exists if not project's config if exists if not global config if exists
config(name) { var v = this.module.config(name); return v !== undefined ? v : this.proj && this.proj.config(name); }
[ "function processConfig() {\n var config = module.config();\n var logicalModule;\n for(var absModuleId in config) { // nully tolerant\n if(absModuleId && (logicalModule = O.getOwn(config, absModuleId)))\n getLogicalModule(logicalModule).push(absModuleId);\n }\n }", "static _loadConfig() {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the major search bar
function displayMajorSearchBar(){ document.getElementById("classList").style.display="none"; document.getElementById("anyoneSearch").style.display="none"; document.getElementById("majorSearch").style.display=""; }
[ "function display_search_interface() {\n status.display_search_interface = true;\n }", "function tycheesCommon_openSearchWindow() {\n\tsea001_mw000_show();\n}", "function displaySearch()\n {\n//\tconsole.log (\"Clicked search menu\");\n\n\t$(\"#search\").css(\"visibility\",\"visible\");\n }", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns 4 spaces per tab level.
function tabLevel(nbTabs) { var result = ""; for (var i = 0; i < nbTabs; i++) { result += " "; } return result; }
[ "getTabString() {\n if (this.getUseSoftTabs()) {\n return lang.stringRepeat(\" \", this.getTabSize());\n } else {\n return \"\\t\";\n }\n }", "function tabs (n) {\n var tabs = \"\"; \n for (var i = 0; i < n; i++) {\n tabs += tabS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to like blog
function likeBlog(like) { var deferred = $q.defer(); $http.post(REST_API_URI + "blog/like", like).then(function (response) { deferred.resolve(response.data); }, function (errorResponse) { console.log("Error Liking Blog"); ...
[ "function displayPostLikeWidget( blog_id, post_id, width, slim, result, obj_id ) {\n\n\t\tif ( !obj_id ) {\n\t\t\tobj_id = blog_id + '-' + post_id;\n\t\t}\n\n\t\twpLikes.updatePostFeedback( result, blog_id, post_id, slim, obj_id );\n\n\t\tvar likePostFrameDoc = window.parent.frames[ 'like-post-frame-' + obj_id ].do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ex. 4.5 Takes a paragraph as an agrument and returns an array on names
function catNames(paragraph){ var colon = paragraph.indexOf(":"); return paragraph.slice(colon + 2).split(", "); }
[ "function extractNames(paragraph){\n var start = paragraph.indexOf(\"(mother \") + \"(mother \".length;\n var end = paragraph.indexOf(\")\");\n console.log(start, end);\n return paragraph.slice(start, end);\n \n}", "function catNames(paragraph) {\n return paragraph.slice(paragraph.indexOf(\":\") ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search the stories show the stories that include the text of the search in the text field
function searchStories(){ let searchValue = document.getElementById('search_text').value; let storyList = JSON.parse(localStorage.getItem('stories')); // check if stories exist if (storyList !== null){ let ratingList = JSON.parse(localStorage.getItem('ratings')); // push the results to a...
[ "search(search_text) {\n for (let i=0; i < this.notes.length; i++){\n if ( this.notes[i].includes(search_text) ) {\n console.log(\"Showing results for search [\" + search_text + \"]\");\n console.log(\"Note ID: \" + i);\n console.log(this.notes[i]);\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs the greatest claim Performs the claim action with the highest priority: hu > peng/kong > chow > draw
function executeGreatestClaim(roomId) { const room = rooms[roomId]; //console.log('end timer'); //console.log(room.currentClaims); const tile = room.rnd.getLastDiscard(); room.timerElapsed = true; let maxIndices = []; let greatestClaim = ClaimTypes.none; for (let i = 0; i < 4; i++) { ...
[ "function act_just_pray() {\n if (rnd(100) < 75) {\n updateLog(` Nothing happens`);\n } else if (rnd(43) == 10) {\n /*\n v12.4.5 - prevents our hero from getting too many free +AC/WC\n */\n crumble_altar();\n return 'crumble';\n } else if (rnd(43) == 10) {\n if (player.WEAR || player.SHIE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate wraparound returns object with new value and direction
function calculateWrappedPosition(animContext, newValue) { var pathLength = animContext.maxValue - animContext.minValue, shiftedValue = newValue - animContext.minValue, outsideAmt, numBounces, newPosition; if ((shiftedV...
[ "function wrapDirection(direction,directions){\n if (direction<0){\n direction += directions;\n } \n if (direction >= directions){\n direction -= directions;\n }\n return direction;\n}", "function wrapDirection(direction, directions) {\n if (direction < 0) {\n direction += ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple mutation updates the status of a Feedback row. Useful if they've completed a review of a piece of usersubmitted Feedback. For moderators or better only.
async updateFeedbackStatus(parent, args, ctx, info) { const callingUserData = await checkAuth(ctx, { type: USER_TYPE_MODERATOR, status: USER_STATUS_NORMAL, flagExclude: USER_FLAG_DISALLOW_FEEDBACK_SUBMISSION, action: "updateFeedbackStatus", }); // Fire off the mutation. return c...
[ "editFeedbackStatus(feedback_info) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n try {\r\n const result = yield index_1.database.updateFeedback({ feedback_id: feedback_info.feedback_id }, { status: feedback_info.status });\r\n if (result.error) {\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve all the package info stored for this package name.
getAllInfoForPackageName(name) { const infos = []; const seen = new (_set || _load_set()).default(); for (const pattern of this.patternsByPackage[name]) { const info = this.patterns[pattern]; if (seen.has(info)) { continue; } seen.add(info); infos.push(info); } ...
[ "get packageNames() {\n return this.packageIds\n }", "async getPackages() {\n return [];\n }", "get packages() {\n return this.getAttribute('packages');\n }", "async getPackages () {\n // route parameters\n const response = await this.api('/packages', 'GET', null, false, null);...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the current building data from the MapitStore
function getBuildingState() { return { data: MapitStore.getAll() }; }
[ "function get_building_info(){\n return building_info;\n}", "getBuildingList() {\n return this.buildingList;\n }", "getBuildingInfo(){\n return {\n buildingName: this.name,\n floors: this.floors,\n elevators: this.elevators\n }; \n }", "get buildi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a gaussian distribution of valid points (within bounds, not too many overlaps)
function getGaussianDistribution(num) { var positions = []; var x, y; distribution = gaussian(mean, variance); for(var i = 0; i < num; i++) { // sample until next point is valid do{ x = distribution.ppf(Math.random()); y = distribution.ppf(Math.random()); } while(!validOverlapPoint([x,...
[ "function gaussian(pt){\r\n\treturn Math.exp(-(pt[0] * pt[0] + pt[1] * pt[1]));\r\n}", "function gauss (x,mu,sigma){ return ( 1/Math.sqrt(2*Math.PI*(sigma**2)) ) * Math.exp( -1/2 * ((x - mu)**2)/sigma**2 ); }", "function gaussian(x, center, height, std_dev) {\n let peak_xc = center || mouseX - width / 2;\n //...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculate the average rating based on resService, resClean and resQual
function avgRating(resService, resClean, resQual) { let resServicetoNum = convertToNumber(resService) let resCleantoNum = convertToNumber(resClean) let resQualtoNum = convertToNumber(resQual) return Math.floor((resServicetoNum + resCleantoNum + resQualtoNum) / 3); }
[ "getAverageRating() {\n let ratingSum = this._rating.reduce((currentSum, rating)=> currentSum + rating, 0 )\n return ratingSum / this._rating.length;\n }", "getAverageRating() {\n //use the reduce method to find the sume of the ratings array. Divied this sum by length of the `ratings` arra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Event handler for handling change of the text field containing player's guess.
function updateGuess(ev) { if (hasGameEnded(guesses, secret)) { return; } let text = ev.target.value; let fieldLength = text.length; if (fieldLength > 4) { text = text.substr(0, 4); } setGuess(text); }
[ "function updateGuess(ev) {\n if (hasGameEnded(status)) {\n console.log(\"update guess -> game ended\")\n return;\n }\n let text = ev.target.value;\n let fieldLength = text.length;\n if (fieldLength > 4) {\n text = text.substr(0, 4);\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if address exists in Tangle of IOTA else create new
function isAddressExists(cb) { self.iota.api.getAccountData(self.seed, {}, function(error, response) { if(!!response && !!response.addresses && response.addresses.length > 0) { cb({success: true}); } else { cb({success: false}); } }); }
[ "function registerAddress() {\n\t\tisAddressExists(function(isExists) {\n \t\tif(!isExists.success) {\n \t\t\tcreateFirstBlankTransaction(self);\n \t\t}\n \t});\n\t}", "function checkAddress(address) {\n if (address.oracle==oracle.name) {\n return true;\n } else {\n return false;\n }\n}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }