query stringlengths 9 34k | document stringlengths 8 5.39M | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
create a CSL.Engine defaults to chicago style and build in citeprocSYS if undefined | function createCiteproc(citeprocJSONObject, citeprocSys, citeprocStyle){
var defaultCiteprocSys = {
retrieveItem: function(id){
return citeprocJSONObject.citationItems[id];
},
retrieveLocale: function(lang){
return defaultLocale[lang];
}
}
if (!citeprocSys)
citeprocS... | [
"function getProcessor(styleID) {\n // Get the CSL style as a serialized string of XML\n var xhr = getXMLHTTPInstance();\n xhr.open('GET', '/cite/readCSLFile/' + styleID, false);\n xhr.send(null);\n var styleAsText = xhr.responseText;\n\n // Instantiate and return the engine\n var citeproc = ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes all the systems. | processSystems() {
for (var i = 0, length = this.systems.length; i < length; i++) {
var system = this.systems[i];
if (system.shouldProcess()) system.process();
}
} | [
"process() {\n this.notifySystems();\n this.processSystems();\n }",
"function startAll() {\n wtfos(function (err, os_) {\n if (err) {\n return callback(err);\n }\n\n os = os_;\n async.forEachSeries(\n systems,\n cacheSystem,\n callback\n );\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively walks through nested arrays and convert string values to numbers and objects with value properties to values. Check the tests in data core > data normalization for a detailed specification of expected values | function recursiveConvert(value) {
if(Chartist.isFalseyButZero(value)) {
// This is a hole in data and we should return undefined
return undefined;
} else if((value.data || value) instanceof Array) {
return (value.data || value).map(recursiveConvert);
} else if(value.hasO... | [
"_normalize(value, deepXml) {\n if (value instanceof Array) {\n const result = [];\n value.map((item) => {\n result.push(this._normalize(item, deepXml));\n });\n value = result;\n }\n else if (typeof value === 'object') {\n l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TASK: SCREENSHOT // /////////////////////////////////////////////////////////////////////////// Load screenshots regarding a certain task. | function loadScreenshots(worker, taskId) {
if (taskId != null) {
var screenshots = datastore.readScreenshots(taskId);
worker.port.emit("ScreenshotsLoaded", screenshots);
}
} | [
"function makeScreenshot() {\n var window,\n task = inProgress;\n\n // If timeout and message both triggered\n if (!task) {\n return;\n }\n\n inProgress = false;\n window = task.window;\n\n clearTimeout(task.timeout);\n\n chrome.tabs.capt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve modifiers from the userdefined regexp pattern. | function getModifiers ( modifiers ) {
var modifier_list = [];
for (var mod in modifiers) {
if ((modifiers[mod] === 'global' ||
modifiers[mod] === 'g') &&
modifier_list.indexOf('g') === -1) {
modifier_list.push('g');
}
if ((modifiers[mod] === 'case-insensitive' ||
modifiers[... | [
"getModifiersAt(selector) {\n const rv = [];\n this.modifiers.forEach((mod) => {\n if (SmoSelector.sameNote(mod.startSelector, selector)) {\n rv.push(mod);\n }\n });\n return rv;\n }",
"getModifiersAt(selector) {\n const rv = [];\n this.modifiers.forEach((mod) => {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
functions allow us to define a behavior they must have a unique name they can take in parameters ( which are used inside the function) simple function that add a "kiwi" to any list that is passed in ourList will represent any list we want to add a "kiwi" to | function addKiwi(ourList){
ourList.push("kiwi");
} | [
"function addToList(list, newThing) {\n\n // var input = document.getElementById('my-input').value;\n var newListItem = newThing;\n $('#fav-list').append('<li>' + newListItem + '</li>');\n\n // var newList = list.innerHTML + newListItem;\n // in line 20, the 'list' in list.innerHTML refers to list in line 14, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the outofthebox Workbox background sync handler will queue the req when we're offline, but it'll return an error to the UI. This is confusing to the UI, so we roll our own plugin that sends a nice resp. | async function wowBackgroundSyncHandler({ event }) {
const uuid = event.request.headers.get(cc.xWowUuidHeader)
try {
console.debug(`SW attempting req for ${uuid}`)
const response = await fetch(event.request.clone())
console.debug('this request worked, so fire the others off!')
processQueueNow() // d... | [
"handleRequest(list) {\n if (this.currentOperation) {\n this.log(\"Cancelling sync operation with timer id\", this.currentOperation);\n clearTimeout(this.currentOperation);\n }\n list.forEach(e => {\n this.addToQueue(e);\n });\n // notify with fictional status 'syncing', in reality it ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Crash at a nonconforming character. | function crash(at, expect) {
var code = value.charCodeAt(index)
var label
var base
var message
// Non-EOF.
if (code === code) {
label = 'character'
base =
'Unexpected character ' +
serializeFormattedCode(code) +
' (' +
serializeCharCode(code) +
... | [
"function badCharacterNoBreakHere(context) {\n const charCode = 131;\n return {\n character({ chr, i }) {\n if (chr.charCodeAt(0) === charCode) {\n context.report({\n ruleId: badChars.get(charCode),\n message: \"Bad character - NO BREAK HE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add a animal to a db | function addAnimal(name, type, id_user) {
let animal = {
_id: new Date().toISOString(),
name: name,
type: type,
id_user: 1
};
return this.db.put(animal);
} | [
"function addAnimalBreed(animal_id, breed_id){\n return db('animal_breeds').insert({animal_id, breed_id}, 'animal_breeds_id')\n}",
"async function insertAnimalType() {\n await db('animal_type').insert({ animal_id: 1, type_id: 1 });\n await db('animal_type').insert({ animal_id: 4, type_id: 1 });\n await db('... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
moves candy based on which arrow was clicked (known via e, which is usually click event) | function moveCandy(e){
var fromCandy = parseCandyFromInput();
var id = e.target.id;
var dir;
if (id == "up-arrow"){
dir = "up";
}
else if (id == "down-arrow") {
dir = "down";
}
else if (id == "right-arrow") {
dir = "right";
}
else if (id == "left-arrow") {
dir = "left";
}
var toCandy = board.getC... | [
"function moveCandyByDragging(e){\n\tvar x = e.pageX - mouseDownCoordinates.left - fromTopLeftX;\n\tvar y = e.pageY - mouseDownCoordinates.top - fromTopLeftY;\n\tcurrentlyDragging.style.left = x + 'px';\n\tcurrentlyDragging.style.top = y + 'px';\n\tcurrentlyDragging.style.height = sizeOfCandy + 'px';\n\tcurrentlyD... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert DOCS filename to document number using unix filing scheme | function DOCSUnix2Num(filename) {
var docnum = 0;
var c = "";
var numbersRegex = /[0-9]/;
var lettersRegex = /[ABCDEFGHIJKLMNOPQRSTUV]/;
// Calculate doc number from characters
for (j = 1; j < filename.length+1; j++){
docnum *= 32;
c = filename.slice(j-1,j).toUpperCase();
i... | [
"function DOCSEnh2Num(filename) {\n\t var docnum = 0;\n\t var c = \"\";\n\t var numbersRegex = /[0-9]/;\n\t var lettersRegex = /[ABCDEFGHIJKLMNOPQRSTUVWXYZ]/;\n\t \n\t // Calculate doc number from characters\n\t for (j = 1; j < filename.length+1; j++){\n \tdocnum *= 36;\n \tc = f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::IoTEvents::DetectorModel.AssetPropertyValue` resource | function cfnDetectorModelAssetPropertyValuePropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnDetectorModel_AssetPropertyValuePropertyValidator(properties).assertSuccess();
return {
Quality: cdk.stringToCloudFormation(properties.quality),
... | [
"function cfnAssetAssetPropertyPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAsset_AssetPropertyPropertyValidator(properties).assertSuccess();\n return {\n Alias: cdk.stringToCloudFormation(properties.alias),\n LogicalId: c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add all child nodes between `startIndex` and `endIndex` (or the whole node, if not given). If `sync` is passed, use it to synchronize after every block element. | addAll(parent, startIndex, endIndex) {
let index = startIndex || 0;
for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {
this.findAtPoint(parent, index);
this.addDOM(d... | [
"addAll(parent, sync, startIndex, endIndex) {\n let index = startIndex || 0\n for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild,\n end = endIndex == null ? null : parent.childNodes[endIndex];\n dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CONCATENATED MODULE: ./src/templates/interface/video/dynamicreveal.js Add UI animations that expands once video ad starts and collapses the slot once video ad finishes | function dynamic_reveal_add(video, container, params) {
var slot = ad_engine_["slotService"].get(params.slotName);
var slotExpanded = false;
video.addEventListener('loaded', function () {
if (!slotExpanded) {
ad_engine_["slotTweaker"].expand(slot);
slotExpanded = true;
// Delay dispatching event so it'... | [
"function showVideo() {\n setTimeout(function(){\n domElements.IMAGE_WRAPPER.classList.remove(POSTER_READY);\n domElements.IMAGE_WRAPPER.classList.add(POSTER_HIDE);\n domElements.VIDEO.style.display = 'block';\n domElements.PANEL.classList.add(REVEAL);\n }, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open the task view sidepane. | function openTaskView() {
withUniqueClass(
requireCursor(),
['content', 'task_list_item__body'],
all,
click,
);
} | [
"function attachViewButtonHandler() {\n\t\tvar taskFile = \"tasks/task\" + (currentTask() + 1) + \".js\";\n\t\twindow.open(taskFile, \"\", 'left=100, top=100, width=700, height=600, menubar=no, status=no, channelmode=no');\n\t}",
"function openTaskWindow(_taskId) {\n let taskWindow = new BrowserWindow({\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
createAvengers(avengers); Write and call a new function that removes the s for Ant Man and Wasp, and adds an for Captain America. | function avengersReassemble(){
var $avengers = $('#avengers');
$('.ant-man, .wasp', $avengers).remove();
var $captAmerica = createAvenger('Captain America');
// $('<li>')
// .addClass('captain-america')
// .text('Captain America');
$avengers.append($captAmerica);
$avengers.... | [
"function add_to_avaengers_arr() {\n\n\n\n}",
"function initAvengers(){\n var ironMan = new avenger(\"IRONMAN\" , 1000, 75, 80, \"./assets/images/ironManPic.jpg\");\n var thor = new avenger(\"THOR\" , 1400, 100, 120, \"./assets/images/thor.jpg\" );\n var hulk = new avenger(\"HULK\" , 2000, 150, 150, \"./... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter function renders the filter section of the expense tracker, sets user inputs into state. | function Filter ({categoryFilter, setCategoryFilter, setNameFilter, dateSort, setDateSort, setExpenseList, nameFilter}) {
//Functions
//Set category filter state to event value
const categoryFilterHandler = (e) => {
setCategoryFilter(e.target.value)
}
//Set name filte... | [
"filter() {\n if (this.input.value) {\n this.applyFilter();\n } else {\n this.discardFilter();\n }\n }",
"function filterExp() {\n let filterType = document.getElementById(\"filter-type\");\n \n if (filterType.value !== \"none\") {\n const expFilteredD... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Import single event into time slot table | importEvent(event) {
if (event.isValid()) {
var startSlot = getTimeslot(event.start);
var endSlot = getTimeslot(event.end);
this.addSlots(startSlot, endSlot, event.id);
}
} | [
"insert_continue(tx,event,lat1,long1,speed,bearing,timestamp,event_row){\n tx.executeSql(\"Insert into Events \"+event_query+\" values(0,'\"+event+\"',\"+event_row.curr_timestamp+\",\"+timestamp+\",'\"+event_row.curr_lat+\"','\"+lat1+\"','\"+event_row.curr_long+\"','\"+long1+\"',\"+event_row.curr_bearing+\",\"+b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves localespecific rules used to determine which day period to use when more than one period is defined for a locale. There is a rule for each defined day period. The first rule is applied to the first day period and so on. Fall back to AM/PM when no rules are available. A rule can specify a period as time range,... | function getLocaleExtraDayPeriodRules(locale){var data=findLocaleData(locale);checkFullData(data);var rules=data[19/* ExtraData */][2/* ExtraDayPeriodsRules */]||[];return rules.map(function(rule){if(typeof rule==='string'){return extractTime(rule);}return[extractTime(rule[0]),extractTime(rule[1])];});} | [
"function getLocaleExtraDayPeriodRules(locale) {\n const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__[\"ɵfindLocaleData\"])(locale);\n checkFullData(data);\n const rules = data[_angular_core__WEBPACK_IMPORTED_MODULE_0__[\"ɵLocaleDataIndex\"].ExtraData][2 /* ExtraDayPeriodsRules */] || [];\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add a new book to the localstorage list of "Books" | static addBookToList(book) {
// get the all the books from local-storage
let storedBooks = JSON.parse(localStorage.getItem('Books'))
// check if the stored-books is not null
storedBooks = storedBooks ? storedBooks : []
// then push a new book to the list
storedBooks.push(... | [
"static addBooks(book){\n const books = Store.getBooks();\n books.push(book);\n //update the books in local storage\n localStorage.setItem('books',JSON.stringify(books));\n }",
"static addBook(book){\n\n // Get book from local storage\n const books = Store.getBooks();... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: fetchRemoteNode Fetch node at given path from remote. Constructs a node like this: timestamp last update of the node, if known. Otherwise 0. data data of the node received from remote storage, or undefined deleted whether remote storage knows this node. mimeType MIME type of the node | function fetchRemoteNode(path, isDeleted) {
logger.info("fetch remote", path);
return remoteAdapter.get(path).
then(function(node) {
if(! node) {
node = {};
}
if(util.isDir(path) && (! node.data)) {
node.data = {};
}
return node;
});
} | [
"function fetchRemoteNode(path, isDeleted) {\n logger.info(\"fetch remote\", path);\n return remoteAdapter.get(path);\n }",
"function fetchRemoteNode(path, parentData, callback) {\n var isForeign = isForeignPath(path);\n\n function done(data, mimeType) {\n callback(prepareRemoteNode(\n da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
========================================================================== Update Storage Level Chart ========================================================================== | function updateStorageLevelChart() {
storageLevelChart.data.labels = [];
storageLevelChart.data.datasets[0].data = [];
storageLevelChart.data.datasets[0].backgroundColor = [];
let status;
storageLevel.forEach(storage => {
if (storage.level >= 6) {
status = "good";
} else if (storage.level <= 2... | [
"updateChart() {\r\n this.alpaca.getAccount().then((resp) => {\r\n this.chart.data.datasets[0].data.push({\r\n t: new Date(),\r\n y: resp.equity\r\n });\r\n this.chart.update();\r\n });\r\n this.updateOrders(); // Updates positions and orders in case any changed were made\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Format the given jQueryXML document by stripping out empty text nodes and indenting XML elements | function formatXMLDocument($xml, noStrip) {
if (!isDocument($xml)) {
console.warn('Called formatXMLDocument with an argument which is not a XML document');
return formatXML($xml);
}
stripEmptyTextNodes($xml[0], _.object(noStrip, noStrip));
indent($xml[0].chi... | [
"function formatXml(objDom, strIndent)\r\n{\r\n\tvar objChild;\r\n\tvar objNew;\r\n\r\n\tif (indentOrigLen == 0) \r\n\t{\r\n\t\ttempstrIndent = new String;\r\n\t\ttempstrIndent = strIndent;\r\n\t\tindentOrigLen = tempstrIndent.length;\r\n\t}\r\n\r\n\tif (objDom.childNodes.length > 0)\r\n\t{\r\n\t\tfor(var i = 1; i ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toggle on and off the contentEditable attribute on the slides | function toggleEditMode(mode) {
var slides = document.querySelectorAll('section');
_.each(slides, function(s) {
s.setAttribute('contentEditable', mode);
});
} | [
"function toggleContentEditable() {\n var post_desc = document.getElementById('post-desc');\n var content_edit = post_desc.getAttribute('contenteditable');\n var title = document.getElementById('post-title-id');\n var title_edit = title.getAttribute('contenteditable');\n if (content_edit === \"true\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves to the next noncomment token. | function moveNext(state) {
moveNextInternal(state);
while (state.currentTokenType === 5 /* Comment */)
moveNextInternal(state);
} | [
"function next () {\n token = tokens[++current]\n }",
"function moveNext () {\n\t\tvar expect = self.expect;\n\t\tvar ch = it.next();\n\t\tif(ch === undefined)\n\t\t\treturn ch;\n\t\tfunction ignore_line () {\n\t\t\tvar chCode = ch.charCodeAt(0);\n\t\t\twhile(chCode != 10) {\n\t\t\t\tch = it.next();\n\t\t\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
search for local installation of Windows 10 Kit in the Windows registry | function getWindowsKitPath(toolname) {
var cmdLine = 'powershell -noprofile -noninteractive -Command "Get-ItemProperty \\"HKLM:\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots\\" -Name KitsRoot10 | Select-Object -ExpandProperty KitsRoot10"';
return execute(cmdLine).then(function (args) {
var toolPath = p... | [
"function scanUninstallKeys(nameSearched) {\r\n var HKLM = 0x80000002;\r\n var dName;\r\n try\r\n {\r\n oLoc = new ActiveXObject(\"WbemScripting.SWbemLocator\");\r\n oSvc = oLoc.ConnectServer(null, \"root\\\\default\");\r\n oReg = oSvc.Get(\"StdRegProv\");\r\n //-------------... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override header field values with values from the ZIP64 extra field | function parseZip64ExtendedInformation(data) {
var size, compressedSize, offset, diskNumStart;
if(data.length >= Constants.EF_ZIP64_SCOMP) {
size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);
if(_entryHeader.size === Constants.EF_ZIP64_OR_32) {
_entryHeader.s... | [
"function parseZip64ExtendedInformation(data) {\n\t\t var size, compressedSize, offset, diskNumStart;\n\n\t\t if(data.length >= Constants.EF_ZIP64_SCOMP) {\n\t\t size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);\n\t\t if(_entryHeader.size === Constants.EF_ZIP64_OR_32) {\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
429 Too Many Requests | function TooManyRequests (message, data) {
FeathersError.call(this, message, 'TooManyRequests', 429, 'too-many-requests', data);
} | [
"function TooManyRequests(message, data) {\n cov_1x4tdstmam.f[301]++;\n cov_1x4tdstmam.s[1491]++;\n\n FeathersError.call(this, message, 'TooManyRequests', 429, 'too-many-requests', data);\n }",
"function TooManyRequests(message, data) {\n\t FeathersError.call(this, message, 'Too... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chapter 12 After Class When the player and Jennifer starts to train in fighting | function C012_AfterClass_Jennifer_StartFight() {
CurrentTime = CurrentTime + 50000;
ActorSetCloth("Clothed");
PlayerClothes("Clothed");
} | [
"function C010_Revenge_SidneyJennifer_StartFight() {\n\t\t\n\t// Sets the fight difficulty\n\tvar SidneyDifficulty = \"Hard\";\n\tvar JenniferDifficulty = \"Normal\";\n\tif (ActorSpecificGetValue(\"Jennifer\", ActorSubmission) < 0) JenniferDifficulty = \"Hard\";\n\n\t// Launch the double fight\n\tC010_Revenge_Sidne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hides the 'Save Cover' button | function hideSaveCoverButton() {
saveCoverButton.classList.add('hidden');
} | [
"function displaySaveCoverButton() {\n saveCoverButton.classList.remove('hidden');\n}",
"function hideSaveDeleteButtons() {\n artworkInfo.style.display = \"none\"\n}",
"hideSaveButtons() {\n //TODO: implement it later. NO-OP for now.\n }",
"function hideSavedCoversPage() {\n savedView.classList... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in a json grammar object `grammar` and replaces all defined pattern variables. Original object is directly modified, but can also be received in return value. | function processGrammar(grammar, additionalVariables = {}) {
// Exit early if no variables defined
if (!('variables' in grammar) || typeof grammar.variables !== 'object')
return grammar;
log_1.default.debug(`Variables Table:`);
if (log_... | [
"function processGrammar(grammar, additionalVariables = {}) {\n // Exit early if no variables defined\n if (!('variables' in grammar) || typeof grammar.variables !== 'object')\n return grammar;\n /**\n * Shadow grammar definitions with ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces the links in the element. | replaceLinks(links)
{
this.element.innerHTML = '';
this.element.appendChild(links);
} | [
"function changeLinks() {\n var text = DocumentApp.getActiveDocument().getBody().editAsText();\n var indices = text.getTextAttributeIndices();\n \n var style = {};\n style[DocumentApp.Attribute.LINK_URL] = getSettings()[\"replacementLink\"];\n style[DocumentApp.Attribute.UNDERLINE] = false;\n \n for (var i ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Spawns a black hole and pushes it into the array if there does not exist a collision. | function spawnBlackHole(game){
var collide = false;
if(game.state == "pause" || game.blackHoleArray.length >= 15){
//cap the number of black holes available to spawn to 15.
return;
}
var color_selector = Math.floor(Math.random()*100);
var color;
if (color_selector < 50){
color = 1; //blue, common, 50%
}
... | [
"function insertBlackHoles() {\n\tif (!pause && !over) {\n\t\tdo {\n\t\t\tvar x = Math.floor(Math.random() * 950) + 25;\n\t\t\tvar y = Math.floor(Math.random() * 535) + 65;\n\t\t} \n\t\twhile (checkCollision(blackHoles, x, y, 1) && blackHoles.length < 20);\n\n\t\tvar type = Math.floor(Math.random() * 15);\n\t\t// S... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function makes the text flicker that indicates which key to press next. | function flicker() {
if (counter == array.length) { return; }
currentText = document.querySelectorAll("span")[counter + 1];
currentText.classList.toggle("flicker");
} | [
"textFlicker() {\n if(this.tsunamiText.alpha == 1 && this.warningText.alpha == 1) {\n this.tsunamiText.alpha = 0;\n this.warningText.alpha = 0;\n } else {\n this.tsunamiText.alpha = 1;\n this.warningText.alpha = 1;\n }\n }",
"function onscreenTex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
inserts the SVG Web library into the page | function insertSVGWeb() {
document.write('<script type="text/javascript" '
+ 'src="' + svgSrcURL + '" '
+ 'data-path="' + svgDataPath + '" '
+ 'data-debug="' + svgDebug + '"></script>');
} | [
"function injectSVG() {\n\n\t\tvar ajax = new XMLHttpRequest(),\n\t\t\torigin = window.location.origin,\n\t\t\twpPath = '/wp-content/themes/northman/',\n\t\t\tajaxPath = origin === 'http://localhost' ? '' : origin + wpPath;\n\n\t\tajax.open('GET', ajaxPath + 'assets/img/svg.svg?v=1', true);\n\t\tajax.send();\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if cep was founded at DB | async function checkCepAtDb(cep) {
let response;
let status1 = false;
try {
//verifica se cep esta cadastrado sem sucesso ou não existe no ws do correio
var queryString = `select * from ceptable where cep = '${cep}' `
response = await pool.query(queryString);
if (response.rowCount <= 0) {
st... | [
"function poExist(e) { return e.zinus_po === row['PONUMBER'].value; }",
"function isFromEurasia(cel) {\n let res = false;\n if (cel.land === 'Eurasia') {\n answer.landmass = 'Eurasia';\n res = true;\n }\n\n return res;\n}",
"function consultationNeeded(fever, precon, headinjury, fracture){\n \t\tif (... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the CmdNode that represents the given fullCmd. | function getCmdNode(fullCmd, cmdTree, depth=0, fullCmdList=undefined) {
if (depth==0) {
fullCmdList = fullCmd.split(' ').filter(arg=>arg!="");
}
if (cmdTree.cmd['cmd']==fullCmdList[depth]) {
if (cmdTree.next!==undefined && (depth+1)!=fullCmdList.length) {
for (let currentCmd of c... | [
"getCommand(cmd) {\n return MonikaCore.commands.has(cmd)\n ? MonikaCore.commands.get(cmd)\n : undefined;\n }",
"function isNodeCommand(cmd){\n\tcmd = TrimStr(cmd);\n\tif(cmd[0] == \">\")\n\t\treturn true;\n\telse\n\t\treturn false;\n}",
"getCmd (\n\t\trequest // command to parse\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
!en Class for Label Frame. !zh LabelFrame | function LabelFrame () {
// the location of the label on rendering texture
this._rect = null;
// uv data of frame
this.uv = [];
// texture of frame
this._texture = null;
// store original info before packed to dynamic atlas
this._original = null;
} | [
"function Label2() {\n\n\tthis.Type = \"Label\";\n this.Text = \"...\";\n}",
"set label(l){this._l=l;this._label=l}",
"_addLabel() {\n this._labelContainer = new Label('label-passed');\n\n gsap.fromTo(this._labelContainer.position, {\n y: -window.innerHeight / 2,\n }, {\n y: 0,\n ease... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Additional public API method to refresh the connection if still open (close, reopen). For example, if the app suspects bad data / missed heart beats, it can try to refresh. Returns boolean, whether websocket was closed. | refresh() {
if (this.ws) {
this.ws.close();
return true;
}
return false;
} | [
"function IsOpen() {\n return (ws && ws.readyState == WebSocket.OPEN);\n }",
"onClose () {\n debug(`Websocket connection is closed, try to reconnect`)\n this.ws.terminate()\n this.ws.removeAllListeners()\n return this.connect(err => debug(err ? `Got an error on websocket connection: ${err.me... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively inserts the specified point p at the node n or one of its descendants. The bounds are defined by [x1, x2] and [y1, y2]. | function insert(n, p, x1, y1, x2, y2) {
if (isNaN(p.x) || isNaN(p.y)) return; // ignore invalid points
if (n.leaf) {
var v = n.point;
if (v) {
// If the point at this leaf node is at the same position as the new
// point we are adding, we leave the point associated with the
/... | [
"function insert(n, p, x1, y1, x2, y2) {\r\n if (isNaN(p.x) || isNaN(p.y)) return; // ignore invalid points\r\n if (n.leaf) {\r\n var v = n.point;\r\n if (v) {\r\n // If the point at this leaf node is at the same position as the new\r\n // point we are adding, we leave the point associ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
draw a horizontal arcing arrow ctx: canvas context inax: start x value inbx: end x value y: y value alpha_degrees: angle of ends to horizontal (30=shallow, >90=silly) | function drawHorizArcArrow(ctx, inax, inbx, y, //mandatory
alpha_degrees, upside, barb_length) { //optional
(alpha_degrees==undefined) && (alpha_degrees=45);
(upside==undefined) && (upside=true);
drawHorizArc(ctx, inax, inbx, y, alpha_degrees, upside);... | [
"drawLineWithArrows(\n x0,\n y0,\n x1,\n y1,\n aWidth,\n aLength,\n arrowStart,\n arrowEnd,\n ctx,\n color\n ) {\n var dx = x1 - x0;\n var dy = y1 - y0;\n var angle = Math.atan2(dy, dx);\n var length = Math.sqrt(dx * dx + dy * dy);\n\n ctx.translate(x0, y0);\n ctx.ro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize the section type. | serializeSectionType(writer, sectionBreakCode) {
writer.writeStartElement('w', 'type', this.wNamespace);
writer.writeAttributeString('w', 'val', this.wNamespace, sectionBreakCode); //GetSectionBreakCode(sectionBreakCode));
writer.writeEndElement();
} | [
"writeTypeSection(writer) {\r\n BinaryModuleWriter.writeSection(writer, SectionType.Type, this.moduleBuilder._types);\r\n }",
"serialize () {\n\n for (let i = 0, ln1 = this._tree.length; i < ln1; ++i) {\n\n let section = this._tree[i];\n let nodes = (section.nodes || []);\n\n if (!(sec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the own property of an object | function getOwnProperty(obj, name) {
return Object.prototype.hasOwnProperty.call(obj, name)
? obj[name] : undefined;
} | [
"function getOwnProperty(obj, prop) {\r\n return Object.prototype.hasOwnProperty.call(obj, prop)\r\n ? obj[prop]\r\n : undefined;\r\n }",
"function getOwnProperty(obj, name) {\n\t\treturn Object.prototype.hasOwnProperty.call(obj, name)\n\t\t\t? obj[name] : undefined;\n\t}",
"function... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
constrain the triangulated mesh to a set of edges the user specifies. Papers: An incremental algorithm based on edge swapping for constructing restricted Delaunay triangulations Marc Vigo Anglada Constrained Delaunay Triangulation using Plane Subdivision Vid Domiter | function delaunay_constrain(vertices, constrained_edges, triangles) {
if (!triangles) {
triangles = delaunay_triangulate(vertices);
}
// first find any places where an edge touches a point and split the edge there
var del_edges = [];
var add_edges = [];
for (var e=0; e<constrained_edges.length; e++) {
var edg... | [
"triangulate ( bound, isReal ) {\n\n if(bound.length < 2) {\n Log(\"BREAK ! the hole has less than 2 edges\");\n return;\n // if the hole is a 2 edges polygon, we have a big problem\n } else if(bound.length === 2) {\n Log(\"BREAK ! the hole has only 2 edges\");\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Multiple column bar chart | function multiColumnBarPlotter(e) {
// We need to handle all the series simultaneously.
if (e.seriesIndex !== 0) return;
var g = e.dygraph;
var ctx = e.drawingContext;
var sets = e.allSeriesPoints;
var y_bottom = e.dygraph.toDomYCoord(0);
// Find the minimum separation between x-values.
... | [
"function multiColumnBarPlotter(e) {\n function darkenColor(colorStr) {\n // Defined in dygraph-utils.js\n var color = Dygraph.toRGB_(colorStr);\n color.r = Math.floor((255 + color.r) / 2);\n color.g = Mat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Discards a locally saved video. | function _discardVideo() {
var filepath = path.split("/");
file = filepath[6];
fileString = file.toString();
myFolder = fileSystemModule.knownFolders.temp();
myFile = myFolder.getFile(fileString);
myFile.remove();
} | [
"function _discardVideo() {\n var filepath = file.split(\"/\");\n var fileEnd = filepath[6];\n var fileString = fileEnd.toString();\n var myFolder = fileSystemModule.knownFolders.temp();\n myFile = myFolder.getFile(fileString);\n if (myFile) {\n myFile.remove();\n } else {\n conso... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw the current turtle path, and begin a new one. | drawPath() {
this.ctx.stroke();
this.begin();
} | [
"update() {\n\t\t//draw the new step and save the step\n\t\tthis.drawPath();\n\t\t//draw the turtle on top of everything\n\t\tthis.draw();\n\t}",
"drawPath() {\n\t\tif (this.drawing) {\n\t\t\trenderingContext.beginPath();\n\t\t\trenderingContext.moveTo(this.previousPos.x, this.previousPos.y);\n\t\t\trenderingCont... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function collides and edge and a polygon, taking into account edge adjacency. | function CollideEdgePolygon(manifold, edgeA, xfA, polygonB, xfB) {
DEBUG && common.debug("CollideEdgePolygon");
// Algorithm:
// 1. Classify v1 and v2
// 2. Classify polygon centroid as front or back
// 3. Flip normal if necessary
// 4. Initialize normal range to [-pi, pi] about face normal
... | [
"function CollideEdgePolygon(manifold, edgeA, xfA, polygonB, xfB) {\n DEBUG && common.debug('CollideEdgePolygon')\n\n // Algorithm:\n // 1. Classify v1 and v2\n // 2. Classify polygon centroid as front or back\n // 3. Flip normal if necessary\n // 4. Initialize normal range to [-pi, pi] about face normal\n /... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The mean anomaly of the sun. | meanSolarAnomaly(julianCentury) {
const T = julianCentury;
/* Equation from Astronomical Algorithms page 163 */
const term1 = 357.52911;
const term2 = 35999.05029 * T;
const term3 = 0.0001537 * Math.pow(T, 2);
const M = term1 + term2 - term3;
return unwindAngle(M);
} | [
"function sun_geom_mean_anomaly(t)\n{\n\treturn RAD(357.52911 + t*(35999.05029 - t*0.0001537));\n}",
"sunGeometricMeanAnomaly(t) {\n return 357.52911 + t * (35999.05029 - 0.0001537*t);\n }",
"function calcGeomMeanAnomalySun(t){\n var M = 357.52911 + t * (35999.05029 - 0.0001537 * t);\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ends search process by hiding Loading spinner and refreshing items. Use it together with `onSearch` event to indicate search end. See more on [GitHub]( | endSearch() {
if (!this._isEnabled) {
return;
}
this.hideLoading();
// When inside Ionic Modal and onSearch event is used,
// ngDoCheck() doesn't work as _itemsDiffer fails to detect changes.
// See https://github.com/eakoriakin/ionic-selectable/issues/44.
... | [
"function searchQueryFinish(){\n $('#search-loader-wrap').remove();\n \n $searchResults.fadeIn('slow');\n }",
"onSearchClosed() {\n\n }",
"onSearchBackCallback() {\n this.showResults(!this.showResults());\n this.showItem(false);\n }",
"startSearch() {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make it possible to take the filter row out of the AltHolder list. | removeSelf() {
// triggered by clicking the exit button
this.holder.remove()
// take self out of the filter list on the AltHolder ob
// this is a function set by the AltHolder on each row it creates
this.removeFromList(this)
} | [
"refilter() {\n this.items.forEach((item) => {\n let visible = false;\n\n // Check for text in cells\n this.config.columns.forEach((column) => {\n if (String(column.get(item.cells)).indexOf(this.filter) > -1) {\n visible = true;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
performs a single tick of the algorithm. When the tick is complete, this.currentNode will contain the node with the lowest cost path. | tick() {
if (!this.finished) {
if (this.openSet.length > 0) {
// current is node having the lowest fScore in openSet,
// sort openSet so lowest f-score is at end of the array, then pop it off the end
const current = this.openSet.sort((n1, n2) => n2.f -... | [
"tick() {\n if (!this.finished) {\n if (this.openSet.length > 0) {\n // current is node having the lowest fScore in openSet,\n // sort openSet so lowest f-score is at end of the array, then pop it off the end\n const current = this.openSet.sort((n1, n2)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
== EASY ANIMATION FUNCTIONS ==// Remove all animation classes from elem | function removeAnimClasses(elem) {
var cn = elem.className;
var ac = [" toLeft"," toRight"," fromLeft"," fromRight"]; //Animation classes
for (var i=0;i<ac.length;i++) {
while (cn.indexOf(ac[i])>=0) {
cn = cn.replace(ac[i],"");
}
}
elem.className=cn;
} | [
"_removeAnimationClasses() {\n\t\tthis.$target.removeClass( 'animated' );\n\t\tthis.$target.removeClass( this.animationClassesString );\n\t\tthis.$target.css( 'animation-duration', '' );\n\t}",
"function clearAnim() {\n toClear = document.querySelectorAll('.animated');\n for (i = 0; i < toClear.length; i++) {\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the URL for a hash instruction and execute. | function processHashInstruction() {
switch (window.location.hash) {
case '#nocache':
deleteAllCaches();
Common.customAlert('Deleted all Caches');
break;
case '#unregister':
unregisterServiceWorkers();
Common.customAlert('Unregistered Service Workers');
break;
case '#d... | [
"async function detectHash() {\n var URLparam = location.search || \"\";\n\n if (URLparam !== \"\") {\n getHashParam(URLparam);\n } else {\n defaultFilter();\n defaultSort();\n }\n }",
"function getUrlHash(url) {\n\t var match = url.match(hashRege... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get previous valid element | getPreviousValidElement(inline) {
let previousValidInline = undefined;
while (inline instanceof FieldElementBox) {
if (HelperMethods.isLinkedFieldCharacter(inline)) {
if (inline instanceof FieldElementBox && inline.fieldType === 0) {
previousValidInline = ... | [
"function getPreviousElement(e) {\n var element = e.previousSibling;\n if (element.nodeType == 3) {\n element = element.previousSibling;\n }\n if (element && element.tagName) {\n return element;\n }\n }",
"function getPreviousFocusableElement(element) {\n return findElementFromAncestorZoneDFS(element, isFo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the npm dependencies to be injected | function getNpmDependencies () {
return CSS_NPM_DEPENDENCIES.map(dep => dep.src);
} | [
"function getNpmDependencies () {\n return JS_NPM_DEPENDENCIES.map(dep => dep.src);\n}",
"function findPackageDeps () {\n var pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'))\n var requiredDeps = Object.keys(pkg.dependencies)\n var devDeps = Object.keys(pkg.devDependencies)\n var optionalDeps = Ob... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes back a move | function TakeMove ()
{
//Going back a move
GameBoard.hisPly--;
GameBoard.ply--;
//Defining these for readability
let move = GameBoard.history[GameBoard.hisPly].move;
let from = FROMSQ(move);
let to = TOSQ(move);
//En passant case, for "undo" case
if (GameBoard.enPas != SQUARES.NO_SQ)
{
HASH_EP();
}
... | [
"function moveBack() {\n\tif (currentMoveNum > 0 && currentMoveNum <= totalMoves) {\n\t\tvar move = moveListLog[currentMoveNum - 1];\n\t\tundoLogMove(move);\n\t\tcurrentMoveNum -= 1;\n\t}\n}",
"get_move_back() {\n let dir = cw(cw(this.dir));\n let pos = get_next_position(this.pos, dir);\n return po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function queries the server using AJAX GET and calls the specified callback when the data arrives (the server's data is assumed to be JSON that will be deserialized and passed as an object to the callback) FIXME the strings in the hash must be sufficiently "nice" (not contain weird characters, etc because they are... | function queryServer (httpGetHash, callback) {
// CHANGE ME if need be... this is the address of the script that
// should be generating the JSON bundle
var scriptAddress = "serve.php";
var xmlhttp = new XMLHttpRequest();
httpGetString = formatHttpGetStr(httpGetHash);
var fullScriptQuery = scriptAddress + "?" ... | [
"function process() {\n\tbinStr = xhr.responseText;\n\n\t// only bother calculating the hash if there is no ''\n\t// marker indicating that we should ignore the hash\n\tvar actualHash = '';\n\tif (urls[1] !== '') {\n\t actualHash = needSHA256(binStr, finish);\n\t if (!actualHash) {\n\t\t// hash is being calcu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if there are no differences in nonsearch (path/object) params, false if there are differences | function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {
// Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.
function notSearchParam(key) {
return fromAndToState.params[key].location != "search";
}
var nonQueryParam... | [
"function nonSearchParamsEqual(fromAndToState,fromParams,toParams){ // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.\n\tfunction notSearchParam(key){return fromAndToState.params[key].location != \"search\";}var nonQueryParamKeys=fromAndToState.params.$$keys(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the attribute in a map and returns the modifier value. If the attribute doesn't exist, 0 is returned. | findAttribute(name, attributes) {
return attributes[name] || 0
} | [
"findAttribute(name, attributes) {\n return attributes[name] || 0\n }",
"function getModByAttr(string) {\n for (item of abilitiesArray) {\n if (item.attr == string) {\n return item.mod;\n }\n }\n}",
"function getAttr(elem, key)\n{\n try { return parseInt(elem.attr(key)) }\n catch(e) { ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to append yourCharacter and enemies available to their respective sections | function character(){
$('.enemySection').append($('.chooseCharacter'));
$('.yourSection').append(this);
} | [
"function character(){\n\t$('.enemySection').append($('.chooseCharacter'));\n\t$('.yourSection').append(this);\n} //End function to append yourCharacter and enemies available to their respective sections",
"function setEnemies() {\n if (game.isPlayerCharacterChosen === true && game.isDefenderChosen === false) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
private classes manages commands history | function History(){
var self = this;
this.commands = loadHistory();
var currIndex = this.commands.length;
this.add = function(command) {
if(command == _.last(this.commands)) {
currIndex ... | [
"function History() {\n // This is the actual buffer where previous commands are kept.\n // 'this._buffer[0]' should always be equal the empty string. This is so\n // that when you try to go in to the \"future\", you will just get an empty\n // command.\n this._buffer = [''];\n\n // This is an index in to the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
======================================================= Return a hash of variables that have to be positive. The rule is that log() vars need to be positive, but ln() vars don't. Why?! ======================================================= | function getMustBePositiveVars(r)
{
var foundChild = r.findAllInstancesOfClass("SquareRoot");
if (foundChild.length > 0)
return true;
foundChild = r.findAllInstancesOfClass("Logarithm");
if (foundChild.length > 0)
return true;
foundChild = r.findAllInstancesOfClass("Power"); // for power < 1
if (... | [
"getRedundantVarnames() {\n var assignments = {};\n var engine = this;\n\n // Get a list of variable names which are assigned to a boolean literal\n estraverse.traverse(this.ast, {\n enter: function (node) {\n if (node.type === 'VariableDeclaration') {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modifies the ballAngleMod, making sure it stays within bounds | function modAngle(modification)
{
if (isBetween(-1.5, 1.5, (ballAngleMod + modification)))
{
ballAngleMod += modification;
}
} | [
"function SetBallAngle(ballAngle)\n{\n ballAngle = ballAngle - 1.5708;\n var speed = 25;\n var xunits = Math.cos(ballAngle) * speed;\n var yunits = Math.sin(ballAngle) * speed;\n cannonBall.speedX += xunits;\n cannonBall.speedY += yunits;\n}",
"function ballAngle(angle) {\n if (angle === ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to generate an S1 image stack for AOI | function getSARstack(aoi){
var s1 = ee.ImageCollection('COPERNICUS/S1_GRD_FLOAT')
.filterBounds(aoi)
.filterDate(startDate, endDate)
.filterMetadata('resolution_meters', 'equals' , 10)
.filter(ee.Filter.eq('instrumentMode', 'IW'));
if (slopeCorrection){
s1 = slope_correction(
... | [
"function createStacks() {\n\tfullStack = new Stack(0, 0, images.length-1, getImageDiv(images[0]));\n\tseriesStacks = new Array();\n\tvar i = 0;\n\tvar k = 0;\n\twhile (k < images.length) {\n\t\tvar stack = getSeriesStack(k);\n\t\tseriesStacks[i++] = stack;\n\t\tk = stack.lastIndex + 1;\n\t}\n}",
"function stack(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getHeaderLabels returns an array of strings from with the first row. sheet: the sheet object that contains the data to be processed range: the exact range of cells where the data is stored columnHeadersRowIndex: specifies the row number where the column names are stored. This argument is optional and it defaults to the... | function getHeaderLabels(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = heade... | [
"function getHeaders(sheet) {\n let headings = sheet\n .getDataRange()\n .offset(0, 0, 1)\n .getValues()[0];\n let headers = [];\n for (let i = 0; i < headings.length; i++) {\n let header = headings[i];\n // headers[header] = i + 1;\n headers[i] = header;\n }\n return headers;\n}",
"functio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove linebreaks from string and replaces with space | function remove_linebreaks(str) {
return str.replace(/[\r\n]+/gm, " ");
} | [
"function replaceNewlineWithSpace(str) {\n return str.replace(/\\n/g, ' ');\n}",
"function removeLineBreaks(string) {\n return string.replace(/\\n/g, '');\n}",
"function restoreLineBreaks(str){\n return str.replace(/\\\\n/g, '\\n');\n}",
"function replaceLineBreaks(originalText)\r\n{\r\n var parsedTex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes the module view(s) using the location manager, according tot he module's settings | async closeViews() {
// Make this module has a view to open
if (!this.getConfig().viewClass)
return;
// Make sure there is a location manager to close this module with
if (!this.locationManager)
return;
// Get the location from the settings
... | [
"close() {\n\n // Set the current panel.\n AppState.currentNuts3Panel = 'symbology';\n\n // Set the panels visibility.\n AppState.setPanelsVisibility();\n\n // Deselect the NUTS3 feature.\n MapLayers.nuts3.deselectNuts3();\n\n }",
"static close() {\n var windowPosition = wi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
displayReps: creates dropdowns(officeTitle>personName) using apiResponse | function displayReps(apiResponse){
$("#candidateListId").empty();
var offices = apiResponse.offices;
for (var officeIndex=0; officeIndex<offices.length; officeIndex++){
var office = offices[officeIndex];
var newDiv = $("<div></div>");
var dropDownId = officeName2Id(office.name);
... | [
"populateEdificiNames() {\n services_1.Services.getAllBuildings().then(edificiResponse => {\n $.each(edificiResponse, (key, item) => {\n if (item.Stato === \"Disponibile\") {\n $('#selectEdificio').append(`<option name = \"${item.Nome}\" value = \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the level a nav is in | function getLevel(el) {
return parseInt(el.parentNode.getAttribute('data-o-hierarchical-nav-level'), 10);
} | [
"function getLevel () {\n var val = window.location.search.match(new RegExp('[?&]level=(\\\\d+)'));\n val = val ? val[1] : MIN_LEVEL;\n val = Math.min(Math.max(MIN_LEVEL, val), MAX_LEVEL);\n return val;\n }",
"function getCurrentLevel() {\n return current_level;\n }",
"get level... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
END : check browser support input file. / START : check browser support html5 canvas. | function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
} | [
"function supports_canvas() {\r\n return !!document.createElement(\"canvas\").getContext;\r\n}",
"function checkHTML5(){\n var html5ready = true;\n \n var canvas;\n var ctx;\n var retTxtDebug = '';\n try {\n canvas = document.createElement(\"canvas\"); \n if( !(\"getContext\" i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the value of what is displayed on the calculator. | function setCalculatorDisplay (val) {
calculatorDisplay.innerHTML = val;
currentDisplay = val;
} | [
"updateDisplay () {\n document.querySelector('.calculator-display').innerHTML = this.data.currentValue\n }",
"function updateDisplay() {\n\tconst display = document.querySelector('.calculator-screen');\n\tdisplay.value = Calculator.display_value;\n}",
"setMutatorValue(_value) {\n this.value = _va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an accept button. | function okButton(options = {}) {
options.accept = true;
return createButton(options);
} | [
"function okButton(options) {\n if (options === void 0) { options = {}; }\n options.accept = true;\n return createButton(options);\n }",
"function enableAcceptButton() {\t\t\n\tvar xbutton = document.getElementById(\"acceptbutton\");\n\tif( xbutton != undefined ){\n\t\tdocument.getElementB... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds labels to the leaf nodes that dont have bar charts. | function addLeafLabelsNotIsolates() {
graph.element.selectAll('.node--leaf:not(.isolates) text').remove()
graph.element.selectAll('.node--leaf:not(.isolates)')
.append('text')
.attr('class', 'leafLabelNoIsolates')
.attr('dy', 5)
.attr('x', 13)
... | [
"function addInternalLabels() {\n graph.style.parentLabels = !graph.style.parentLabels\n updateInternalLabels(graph.style.parentLabels)\n }",
"function updateLeafLabels(active) {\n graph.element.selectAll('.node--leaf text').remove()\n if (active) {\n graph.element.select... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function: create new .gitconfig gitrc n [name] | function createNewGitConfig() {
// no name provided
if( !name ) {
console.error( 'What do you want to call your new .gitconfig file?\n' );
console.error( 'Usage: gitrc -n [name]\n' );
return process.exit( 1 );
}
// get the pathway for creation
var newFilename = path.join( GITCONFIGS, name );
// that name... | [
"function createGit (argv, next) {\n const path = argv.path\n gitInit(path, next)\n}",
"function createGit() {\n for (var i = 0; i < gitArr.length; i++) {\n new Git(gitArr[i][0], gitArr[i][1], gitArr[i][2], gitArr[i][3], gitArr[i][4]);\n }\n}",
"function newConfig() {\r\n //TODO\r\n}",
"async functi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets bottom coordinate, translating elements position. | setBottom(bottom) {
this.setTop(bottom - this.offsetHeight);
} | [
"set bottom(bottom) {\n this._frame.origin.y = bottom - this.height;\n }",
"_updatePosFromBottom() {\n this._topLeft = this._bottomRight.$subtract(this._size);\n this._updateCenter();\n }",
"function setBottom(elt, x, y, z){\n\trotateTop(elt);\n\tset3dPosition(elt, x, z, y);\n}",
"f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
WEndRec() make the last record the current record. | function WEndRec()
{
this.WSetRow(this.rows - 1);
} | [
"function endRec() {\n lastPausedT = curTime();\n lastPaused = curGranule(lastPausedT);\n lastEventRecTime += lastPausedT - lastResumedT;\n modeUpdate(prot.mode.buffering, curTime());\n\n // No update to the database, as we're still recording\n\n // Start our buffering timer\n awaitBuffering();... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
============================== 26. Write a JavaScript function to calculate the nth root of a number. Test Data : console.log(nthroot(64, 2)); 8 console.log(nthroot(64, 2)); 0.125 ============================== ??????????? | function nthroot(x, n)
{
ng = n % 2;
if((ng == 1) || x<0)
x = -x;
var r = Math.pow(x, 1 / n);
n = Math.pow(r, n);
if(Math.abs(x - n) < 1 && (x > 0 === n > 0))
return ng ? -r : r;
} | [
"function nthroot(x, n)\r\n {\r\n ng = n % 2;\r\n if((ng == 1) || x<0)\r\n x = -x;\r\n var r = Math.pow(x, 1 / n);\r\n n = Math.pow(r, n);\r\n\r\n if(Math.abs(x - n) < 1 && (x > 0 === n > 0))\r\n return ng ? -r : r;\r\n }",
"function root(num, root){\n\treturn Math.pow(num, 1/root);\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the steam list of app ids and game names | function getGameID (callback){
console.log('enter getGameID');
// steam api url
var url1 ='https://api.steampowered.com/ISteamApps/GetAppList/v2';
var tempData = '';
var tempdata1;
// calls the steam url and processes
https.get(url1, function(response) {
// whi... | [
"function getGameInfo(appID) {\n\n}",
"function getSteamGameList(apiKey, steamId) {\n\n return new Promise(function(resolve, reject) {\n\n var url = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/'\n + '?key=' + apiKey\n + '&steamid=' + steamId\n + '&inc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Associate the disruption information with a place data source and equipment info, if possible | postProcessBeforeUpserting(doc, { organizationSourceIds, organizationName }) {
const result = super.postProcessBeforeUpserting(doc, { organizationSourceIds, organizationName });
const properties = result.properties;
if (!properties) return result;
properties.lastUpdate = new Date().toISOString();
... | [
"_equipmentChatData(data, labels, props) {\n props.push(\n CONFIG.DND5E.equipmentTypes[data.armor.type],\n labels.armor || null,\n data.stealth.value ? game.i18n.localize(\"DND5E.StealthDisadvantage\") : null\n );\n }",
"async function oregon_character_spell_equipment(source, dest) {\n let ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the JSON text for a narration intro and returns the parsed JS object. If the intro is effectively empty, return null as if the input had been null. | function parseIntroText(introText) {
const parsedIntro = JSON.parse(introText);
if (
parsedIntro &&
parsedIntro.content &&
parsedIntro.content.length === 1 &&
!("content" in parsedIntro.content[0])
) {
return null;
}
return parsedIntro;
} | [
"function parseArtistJson(inputText){\n // var len = \"\\\"\"extract\\\":\\\"\".length;\n var text = inputText.substring(inputText.indexOf(\"\\\"extract\\\":\\\"\")+11, inputText.indexOf(\"\\\\n\\\\n\"));\n // var text = inputText.substring(0, inputText.indexOf(\"\\\\n\\\\n\"));\n return text;\n}",
"get intro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: replaceNodeByText Replace a Node by a TextNode | function replaceNodeByText(node, text){
node.parentNode.replaceChild( document.createTextNode(text), node );
} | [
"function setText(node, text) {\n if (node.hasChildNodes() && node.firstChild.nodeType == Node.TEXT_NODE) {\n node.firstChild.nodeValue = text;\n } else {\n addText(node, text);\n }\n}",
"function replaceNodeText(sourceFile, replaceStart, replaceEnd, newText) {\n doManipulation_1.doManipulation(source... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
extract the actual numerical value from a node of type rational. currently assumes result will be integer (currently returns BN) | function rationalValue(definition) {
let identifier = typeIdentifier(definition);
let absoluteValue = identifier.match(/_(\d+)_by_1$/)[1];
let isNegative = identifier.match(/_minus_/) != null;
return isNegative ? new bn_js_1.default(absoluteValue).neg() : new bn_js_1.default(absoluteValue);
} | [
"function rationalValue(definition) {\n let identifier = typeIdentifier(definition);\n let absoluteValue = identifier.match(/_(\\d+)_by_1$/)[1];\n let isNegative = identifier.match(/_minus_/) != null;\n return isNegative ? new bn_js_1.default(absoluteValue).neg() : new bn_js_1.default(ab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getTotalNumberOfSales() should return the total number of units sold | getTotalNumberOfSales() {
var sum = 0;
for(var i = 0; i <= this.employees.length - 1; i++){
sum += this.employees[i].salesUnits;
}
return sum;
} | [
"function totalSale(sales) {\n return sales.reduce((sum, cur) => sum + cur, 0);\n}",
"function sales() {\n\n var counter = 0;\n\n for (var i = 0; i < totalTransactions; i++) {\n if (transactions[i]['type'] === 'sale') {\n counter +=1;\n }\n }\n return counter;\n\n}",
"function totalSal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
,, | Inoreader | '' version of inoreaderSubscribe() using window.open(): produces popup window, but won't work if browser.link.open_newwindow=3 and browser.link.open_newwindow.restriction=0 (ie. if dactyl's popup option is 'tab' without 'resized') / adapted from inoreader bookmarklet | function inoreaderSubscribe(url=buffer.URL){
var w = 640, h = 400;
width = content.window.innerWidth || content.document.documentElement.clientWidth || screen.width;
height = content.window.innerHeight || content.document.documentElement.clientHeight || screen.height;
var left = ((width/2)-(w/2))+scr... | [
"handleBrowserJSNewWindow (evt) {\n shell.openExternal(evt.channel.url, { activate: !flux.settings.S.getState().os.openLinksInBackground })\n }",
"handleBrowserOpenNewWindow (evt) {\n const url = URL.parse(evt.url, true)\n let mode = 'external'\n if (url.host === 'inbox.google.com') {\n mode = '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepare the behavior services | async prepareBehavior() {
await this.addBehavior('requestDelays', new BehaviorFail({ banLifetime: '20m', failSuspicionLevel: 200 }));
await this.addBehavior('authentication', new BehaviorFail({ banLifetime: '15m', failSuspicionLevel: 10 }));
await this.addBehavior('registration', new BehaviorFail({ ba... | [
"_setServices() {\n //need to run through the possible configurations and then specify\n }",
"async __prepareWorkflowManager () {\n\n\t\t// Inject the dependencies the workflow manager requires.\n\t\tthis.workflowManager.inject(`sharedLogger`, sharedLogger);\n\t\tthis.workflowManager.inject(`MessageObject`, M... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add animation class to logo | function animationLogo() {
logo.classList.add('logo-animate');
} | [
"function animateLogo () {\n\t\tvar repeatVisitFlag = IBM.common.util.storage.getItem(\"v18larv\");\n\t\t\n\t\t// Allow animation to be forced to show via URL param (for debugging, presentations, show-and-tell, etc).\n\t\tif (IBM.common.util.url.getParam(\"animatelogo\")) {\n\t\t\t$(\"#ibm-home\").addClass(\"ibm-an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function will adjust the size of signature fields Sample Call: SP_AdjustSignFieldSize() | function SP_AdjustSignFieldSize()
{
var newLineCount = 0;
var TotalSignLength = 0;
$("#mcPage_002").find("textarea").each(function()
{
if(this.id.indexOf('mastercontrol.route.esig.sigstatus') == 0)
{
if(this.value != "")
{
var newLineCount = this.value.match(/\n/gi);
if(newLineCount)
{
... | [
"function SP_SetAttachLinkFieldSize() // renamed function: old name was SP_SetAttachnLinkFieldSize()\n{\n\tvar oField = document.getElementById(arguments[0]);\n\t// Browser check for Safari & Chrome. When items are less than 4.\n\tif(oField.options.length <= 4 && (navigator.userAgent.indexOf(\"Safari\") > 0 || nav... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends text request to server via POST request | function postReq(path, textReq, responseCallback = null) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
if (responseCallback !== null) responseCallback(xhr);
}
};
xhr.open("POST", path, true);
xhr.send(te... | [
"function sendText(text) {\n $.post(TEXT_API, data=text);\n}",
"function upload(response, postData) {\n console.log('Request handler \"upload\" was called.');\n response.writeHead(200, {\"Content-Type\": \"text/plain\"});\n response.write(\"You've sent the text: \" + querystring.parse(postData).text);\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dispatches navigation action to |this.getRouteFromHash()| if that is defined in |this.routes|, otherwise to |this.defaultRoute|. | navigateToCurrentHash() {
const hashRoute = this.getRouteFromHash();
const newRoute = hashRoute in this.routes ? hashRoute : this.defaultRoute;
this.dispatch(actions.Actions.navigate({ route: newRoute }));
// TODO(dproy): Handle case when new route has a permalink.
} | [
"navigateToCurrentHash() {\n const hashRoute = this.getRouteFromHash();\n const newRoute = hashRoute in this.routes ? hashRoute : this.defaultRoute;\n this.dispatch(actions.Actions.navigate({ route: newRoute }));\n // TODO(dproy): Handle case when new route has a permalink.\n }",
"f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns the motor "backwards" at speed ( default 100% ) | backwards(speed) {
if (speed === undefined) {
this._speed = -100;
} else {
if (speed < 0 || speed > 100) {
throw "Speed must be between 0 and 100"
}
this._speed = -speed;
}
this._applySpeed();
} | [
"function reverse(force)\n{\n\tchange_speed(speed * -1, force);\n}",
"MoveBackwards(){\n this.velocityX -= Math.cos(this.car.rotation) * this.power;\n this.velocityY -= Math.sin(this.car.rotation) * this.power;\n }",
"changeBackwardGear(){\n if(this.speed == 0){\n this.gear = 6;\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function clears the cities array so that we can call displaySavedCities when the page loads, and also when the user inputs a new city. This way we can update the cities list right after the user inputs a new city. But if we didn't clear the list before updating, it would display both the old list, and the new list... | function clearSavedCities() {
searchedCities.empty()
} | [
"function clear() {\n cities = [];\n}",
"function clearList() {\n setCities([])\n setmaxValue(0)\n }",
"function AutocompleteCitiesReset() {\n _AutocompleteCities = new Array();\n}",
"function removeCities() {\n clearMarkers(cityMarkers);\n clearMarkers(coordinateMarkers);\n ci... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The FunctionUint Class, provide the information about the function unit and the operation of the function unit. | function FunctionUnit (name, execTime) {
this.name = name;
this.busy = false;
this.Op = "";
this.Fi = "";
this.Fj = "";
this.Fk = "";
this.Qj = "";
this.Qk = "";
this.Rj = true;
this.Rk = true;
this.exec = 0;
this.execTime = execTime; // The clock need in execution stag... | [
"ToUInt32() {\n\n }",
"ToUInt16() {\n\n }",
"function UInt(name,\n\t{\n\t\tsize = 1,\n\t\tbigEndian = true,\n\t\ttransform = value => value,\n\t} = {}\n) {\n\tif ((size < 1) || (size > 4)) {\n\t\tthrow new Error('Javascript bit operations are only safe to 32 bits, so we can\\'t do sizes over that');\n\t}\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if given element contains given parent somewhere in the DOM tree. | function hasParent(element, parent) {
var elem = element;
while (elem) {
if (elem === parent) {
return true;
} else if (elem.parentNode) {
elem = elem.parentNode;
} else {
return false;
}
}
return false;
} | [
"function hasParent(element, parent) {\n let elem = element;\n while (elem) {\n if (elem === parent) {\n return true;\n }\n else if (elem.parentNode) {\n elem = elem.parentNode;\n }\n else {\n return false;\n }\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate image from statblock so user can save | function blockToImage() {
html2canvas(document.querySelector("#capture")).then(canvas => {
canvas.toBlob(function(blob) {
saveAs(blob, "statblock.png");
});
});
} | [
"function output_image(page, filename, format) {\n\n if (format == \"svg\") {\n var outfile = fs.open(filename, 'w');\n var length = page.content.length;\n outfile.writeLine(length);\n outfile.writeLine(page.content);\n outfile.close();\n }\n else if (format == \"raw\") {... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PART 22 Define a function which returns the english name for any given number string from 1(ONE) to 99(NINETYNINE) . Assume that the number will always have 2 digits Parameters: number (string) Example 1: "01" > "ONE" Example 1: "51" > "FIFTYONE" Example 1: "10" > "TEN" Example 1: "12" > "TWELVE" Example 1: "11" > "ELE... | function getNumberName(numberString) {
let digitName10 = "";
let digitName1 = "";
if (numberString[0] === "1") {
//Define tenth digit place if tenth digit place is "1"
switch (numberString[1]) {
case "0":
digitName10 = "TEN";
break;
... | [
"function nameNumber(num) {\n\t// function returns the name of any number (less than 1000)\n\tvar units, teens, tens, name;\n\n\tunits = {0: \"\", 1: \"one\", 2: \"two\", 3: \"three\", 4: \"four\", 5: \"five\",\n\t\t\t6: \"six\", 7: \"seven\", 8: \"eight\", 9: \"nine\"};\n\n\tteens = {10: \"ten\", 11: \"eleven\", 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
var svg2img = require('svg2img'); var btoa = require('btoa'); | async function convertToImage({name, svg}) {
const req = await fetch('/api/draw', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
mode: 'cors',
body: JSON.stringify({
name,
img... | [
"function svg2img(svg){\n var xml = new XMLSerializer().serializeToString(svg);\n var svg64 = btoa(xml); //for utf8: btoa(unescape(encodeURIComponent(xml)))\n var b64start = 'data:image/svg+xml;base64,';\n var image64 = b64start + svg64;\n return image64;\n}",
"function svg2img(svg) {\n var xml = new XMLSer... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts and returns an array of flavor objects based on data in the DOM. Each flavor object should contain five properties: element: the HTMLElement that corresponds to the .flavor div in the DOM name: the name of the flavor description: the description of the flavor price: how much the flavor costs quantity: how many... | function extractFlavors() {
var flaveArr = [];
forEachFlavor( function(flavor) {
flaveArr[flaveArr.length] = flavor;
});
flaveArr = flaveArr.map(function(flavor){
return {
element: flavor,
name: flavor.querySelector('.description h2').textContent,
description: flavor.querySelector('.description... | [
"function extractFlavors() {\n var getFlavor = document.getElementsByClassName(\"flavor\");\n var flavorArray = [];\n\n for(i=0; i<getFlavor.length; i++){\n\n \tvar elementFlavor= getFlavor[i];\n \tvar h2 = elementFlavor.querySelector(\".description h2\");\n \tvar elementName = h2.innerHTML;\n\n \tvar p = el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get weather section by type | function getWeatherSection(type, weatherSectionArr) {
var fullWeatherSectionFields = ['enabled', 'fgColor', 'bgColor', 'conditions', 'feedUrl', 'layer'];
var result = {};
var weatherItem = {};
//find the appropriate section
if (weatherSectionArr && weatherSectionArr.length > 0) {
... | [
"function getSectionByType(type, sectionItems) {\n var section = {};\n if (sectionItems && sectionItems.length > 0) {\n for(var i = 0; i < sectionItems.length; i ++) {\n var item = sectionItems[i];\n if (item['_type'] && (item['_type'].toLowerCase() === type.t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses through selected Filters and checks then in the UI | checkSelectedFilters() {
const selectedFilters = this.anomalyFilterModel.getSelectedFilters();
selectedFilters.forEach((filter) => {
const [section, filterName] = filter;
$(`#${section} .filter-item__checkbox[data-filter="${filterName}"]`).prop('checked', true);
});
} | [
"showCheck(filter, isInitial) {\n\n /* If no tags/licenses selected, or all tags selected, SHOW ALL and DESELECT ALL BUTTONS. */\n for ( var i = 0; i < this.FILTERS.length; i++ ) {\n if( this.FILTERS[i]['name'] === filter ) {\n if( (this.FILTERS[i]['selected'].length === 0) ||\n (this.F... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |