anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
Simple task queue to sequentialize actions. Assumes callbacks will eventually fire (once).
function TaskQueue$2() { this.promise = new PouchPromise$1(function (fulfill) {fulfill(); }); }
=============================== LANGUAGES FILES CLIENT ========== ================================
function callLanguages(){ if (localStorage.getItem("language")) localStorage.getItem("language") == 2 ? language_file = 'json/pt.json' : language_file = 'json/en.json' else language_file = 'json/en.json' $.getJSON(language_file, function(json){ localStorage.setItem("json", JSO...
recurses, calling itself once for each letter in the string
function printString(myString) { console.log(myString[0]); if (myString.length > 1) { let mySubString = myString.substring(1, myString.length); printString(mySubString); } else { // complete once there are no remaining letters to shift to the left return true; } }
getText() function definition. This is the pdf reader function.
function getText(typedarray) { //PDFJS should be able to read this typedarray content var pdf = PDFJS.getDocument(typedarray); return pdf.then(function(pdf) { // get all pages text var maxPages = pdf.pdfInfo.numPages; var countPromises ...
Downloads the module from github
_downloadModule() { // If URL is not provided, throw error. if(!this.evt.options.url) { return BbPromise.reject(new SError('Github URL is required. (eg. serverless module install <github-url>)', SError.errorCodes.UNKNOWN)); } let _this = this, spinner = SCli.spinner(), ...
the function will create todo and get the data
function createTodo() { var titleVal = $todoTitle.value; var descrpVal = $todoDescrp.value; // event entered multiple space will be removed because of trim() method if (titleVal.trim() != "") { todoList.push({ title: titleVal, descrp: descrpVal }); showDOMList(); document.querySel...
while preventing any attempt to rehydration until after reinsertion.
function resetComponentStateWhenRemoved(vm) { const { state } = vm; if (state !== VMState.disconnected) { const { oar, tro } = vm; // Making sure that any observing record will not trigger the rehydrated on this vm tro.reset(); // Making sure that any observing acce...
! moment.js locale configuration
function r(o,M){var D=o.split("_");return M%10==1&&M%100!=11?D[0]:M%10>=2&&M%10<=4&&(M%100<10||M%100>=20)?D[1]:D[2]}
Checks for unprocessed items in the directory of the current page and dispatches a scroll event if necessary.
function listenToScroll() { logTrace('invoking listenToScroll()'); const interval = 1000; window.clearInterval(checkForItemsInterval); checkForItemsInterval = window.setInterval(function checkForItems() { // prevent listening during page load if (pageLoads === true) { logVerbose('Stopped checkForI...
$ is abbreviated to be: document.querySelect() Find all HTML elements with id:code_numberHere Retrieve the address name from the registers object and tap into the rip property which will retrieve the address of the current function For example, HTML element could have id="code_1000" which refers to the row with address...
function highlightCurrentCode() { // Change the css property by applying a highlighted background color of orange $("#code_" + registers["rip"]).css('background-color', '#df9857'); }
WeaponCtrl is a seperate class, used for deciding what type of weapon the player is currently using. It is a body in the level
constructor () { }
Build a zone from the values in the form, formatted as YAML. This shouldn't be called unless input has been validated. It will sanity check for the "isvalid" class in the name and coordinates field.
function addZone() { if ($('#location').hasClass("is-valid") && $('#zoneName').hasClass("is-valid")) { let name = $('#zoneName').val(); let latitude = $('#location').attr("data-latitude"); let longitude = $('#location').attr("data-longitude"); let radius = $('#radius').val() === '' ?...
Monkey patching filesaver and html2canvas
function monkeyPatch() { return { transform: (code, id) => { const file = path.parse(id).base; // Only one define call per module is allowed by requirejs so // we have to remove calls that other libraries make if (file === 'FileSaver.js') { code = code.replace(/define !== null\) &...
Return whether or not the sound exists in the sound library.
has(soundName) { return this._titleCase(soundName) in this.dict; }
Attempt sign in, used by the form in the sign in menu.
function attemptSignIn(email,password){ firebase.auth().signInWithEmailAndPassword(email, password).then((user) => { uid = user.user.uid; }).catch((error) => { console.log(error); }); }
Responsively hides children based on the selected implementation.
function Hidden(props) { var _props$implementation = props.implementation, implementation = _props$implementation === void 0 ? 'js' : _props$implementation, _props$lgDown = props.lgDown, lgDown = _props$lgDown === void 0 ? false : _props$lgDown, _props$lgUp = props.lgUp, lgUp = _props$lg...
ajax request na ziskanie dat pre gate_man
function load_all_time_slots() { $.post('gate_man_AJAX/load_all_time_slots.php',{ },function(data){ if (typeof data === 'object'){ parse_data(data); }else if(data){ create_exception(data ,23,'danger'); }else{ create_exception("Could not connect to the ...
Return the address of the plcrvoting referenced by this contract instance
voting() { return __awaiter(this, void 0, void 0, function* () { const deployed = this.requireDeployed(); return yield deployed.methods.voting().call(); }); }
href = Thiago Vallin / Rafa Reis
decodeHtml(html) { const txt = document.createElement('textarea'); txt.innerHTML = html; return txt.value; }
let table = document.createElement("table"); let tr = document.createElement("tr"); let td = document.createElement("td"); console.log(tr) console.log(td)
function tab (stroke, stb){ let table = document.createElement("table"); document.body.append(table) for(let i = 0; i < stroke; i++){ let tr = document.createElement("tr"); tr.classList.add('box') for(let i = 0; i < stb; i++){ let td = document.createElement("td"); ...
Intializes all database connections and adds them to the databases storage object. Allows for database connections to be reused and passed to other files. Needs to be run before the server starts listening for requests.
async function initializeDatabases() { // const databases = await Promise.all([connect(uri)]); const searchbar = await connect( connectionString, 'searchbar' ); databases.searchbar = searchbar; }
End CrossBrowser DHTML Menu / New Options code
function optionEdit(assign_id, optionData) { var data = optionData.split('|'); var elements = $('opt_mid').getElementsByTagName('option'); for (i=0; i<elements.length; i++) { elements[i].removeAttribute('selected'); if (data[1] == '0') { if (elements[i].value == data[0] && elements[i].getAttribute('class'...
Return a randomly oriented vector with the given length.
randomVec (length) { const deg = 2 * Math.PI * Math.random(); return Util.scale([Math.sin(deg), Math.cos(deg)], length); }
Ensure all props option syntax are normalized into the Objectbased format.
function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: nul...
When the user clicks anywhere outside of the modal, close it
function closeWindow(modalId, modalId2) { var modal = document.getElementById(modalId); var modal2 = document.getElementById(modalId2); // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } el...
Constructs a new RoomPool and sets listeners and emitters from the given socket.io instance.
constructor(socketIoInstance) { this.rooms = {}; SafeSocket.socketsOn(socketIoInstance, 'connection', (socket) => { Logger.logInfo('socket ' + socket.id + ' connected'); socket.emit('clientConnectedToServer', { socketId: socket.id }); // Default socket.io actions socket....
Show wishlist managment page
function WishlistManage(id, id_wishlist) { $.ajax({ type: 'GET', async: true, url: baseDir + 'themes/raindrop/modules/blockwishlist/managewishlist.php', data: 'id_wishlist=' + id_wishlist + '&refresh=' + false, cache: false, success: function(data) { $('#' + id).hide(); $('#' + id).html(...
No side effect Generated by BUCKLESCRIPT VERSION 5.0.3, PLEASE EDIT WITH CARE
function toPartialClassName(param) { switch (param) { case 0 : return "1/2"; case 1 : return "1/3"; case 2 : return "2/3"; case 3 : return "1/4"; case 4 : return "3/4"; case 5 : return "1/5"; case 6 : ...
Called when regl is destroyed
function destroyTextures () { for (var i = 0; i < numTexUnits; ++i) { gl.activeTexture(GL_TEXTURE0 + i); gl.bindTexture(GL_TEXTURE_2D, null); textureUnits[i] = null; } values(textureSet).forEach(destroy); stats.cubeCount = 0; stats.textureCount = 0; }
function for setting the start coordinates for the projectile
setStart(x, y){ if (this.alive == false){ this.x = x + 130; this.y = y + 17; } }
Criar Dados em Outra Entidade
function createEntityNode(entidade, atributo, atributoValor) { var xml = "<?xml version='1.0' encoding='utf-8'?>" + "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" + GenerateAuthenti...
Simple formula generating a random value around the average in between min and max
function vary(avg, percentage, min, max) { var value = avg * (1 + ((percentage / 100) * (2 * Math.random() - 1))); value = Math.max(value, min); value = Math.min(value, max); return value; }
Get offset for starting at point i
function point_offset(i) { return 4*i; }
This is a kludge to keep keymaps mostly working as raw objects (backwards compatibility) while at the same time support features like normalization and multistroke key bindings. It compiles a new normalized keymap, and then updates the old object to reflect this.
function normalizeKeyMap(keymap) { var copy = {}; for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { var value = keymap[keyname]; if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } if (value == "...") { delete keymap[keyname]; continue } var keys = map(k...
Restart the ball from the center of the screen
function ballReset() { if (player1Score >= WINNING_SCORE || player2Score >= WINNING_SCORE) { showingWinScreen = true; } ballSpeedX = -ballSpeedX; ballX = canvas.width / 2; ballY = canvas.height / 2; }
Populate `_hostNode` on the rendered host/text component with the given DOM node. The passed `inst` can be a composite.
function precacheNode(inst, node) { var hostInst = getRenderedHostOrTextFromComponent(inst); hostInst._hostNode = node; node[internalInstanceKey] = hostInst; }
From module 'name' (e.g. 'density'), find numeric index in the 'svgObjectNames' array.
function getIndexFromName(name) { var i; for(i=0; i<svgObjectNames.length; i++) if(svgObjectNames[i] == name) return i; throw new Error("Did not find '" + name + "'."); }
create a new export function, used by both the main export and the .ctor export, contains common logic for dealing with arguments
function through2 (construct) { return function (options, transform, flush) { if (typeof options == 'function') { flush = transform transform = options options = {} } if (typeof transform != 'function') transform = noop if (typeof flush != 'function') flush = null...
Button Function to actually get the content of what the user has put in the box
contents_of_input(e){ e.preventDefault(); var val = {text: this.refs.formControl.value, done:false, id: this.state.id }; // retrieve input const current_array = Array.from(this.state.todos); // copy of current array current_array.push(val); // pushing value of current array console.log(current_...
assign val to move for sorting
function moveSortVal(pos,mv){ "use strict"; //fill in for larger sizes! return 0; }
Unescape function taken from
function funescape(_, escaped, escapedWhitespace) { var high = parseInt(escaped, 16) - 0x10000; // NaN means non-codepoint return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode(high + 0x10000) : // Supple...
question / Welcome. In this kata, you are asked to square every digit of a number. For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. Note: The function accepts an integer and returns an integer answer standard
function squareDigits(num){ return Number(('' + num).split('').map(function (val) { return val * val;}).join('')); }
Build a destructive iterator for the value list
function iteratorFor(items) { var iterator = { next: function() { var value = items.shift() return {done: value === undefined, value: value} } } if (support.iterable) { iterator[Symbol.iterator] = function() { return iterator } } return...
NOTE: THIS IS A TEMPORARY WORKAROUND. In the near future we will overhaul the AEDoc parser to separate syntactic/semantic analysis, at which point this will be wired up to the same ApiDocumentation layer used for the API Review files
_getReleaseTagForDeclaration(declaration) { let releaseTag = ReleaseTag_1.ReleaseTag.None; // We don't want to match "bill@example.com". But we do want to match "/**@public*/". // So for now we require whitespace or a star before/after the string. const releaseTagRegExp = /(?:\s|\*)@(in...
private methods This method is called during Metadata initialization to correctly "wrap" properties.
function movePropDefsToProto(proto) { var stype = proto.entityType || proto.complexType; var extra = stype._extra; var alreadyWrapped = extra.alreadyWrappedProps || {}; stype.getProperties().forEach(function (prop) { var propName = prop.name; // we only want to wrap props that haven't alre...
================================================================================ === Test grant revocation ================================================================================
async function testRevokeVestingSchedule(owner, account, [totalAmount, vestingAmount, startDay], [duration, cliffDuration, interval, isRevocable], revokeOnDay) { const ownerBalanceBefore = await CpuCoin.methods.balanceOf(owner).call(); const accountBalanceBefore = await CpuCoin.methods.balanceOf(account...
format date of order
getDateFormated(date) { const formatDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }).format; return formatDate(date); }
Validate that children, if any, are instances of ``.
function onlyProgressBar(props, propName, componentName) { var children = props[propName]; if (!children) { return null; } var error = null; __WEBPACK_IMPORTED_MODULE_7_react___default.a.Children.forEach(children, function (child) { if (error) { return; } // eslint-disable-next-line n...
generates table of frequencies for notes see:
function generateFrequencyTable() { var noteNames = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']; var root12_2 = 1.059463094359; var freq_by_note = {}; // fill 4, 5, 6, and 7 octaves var freq = 440.0; // A4 ['4', '5', '6', '7'].forEach(function(octave) { var f =...
Implement the identical functionality for filter and not
function winnow(elements, qualifier, not) { if (jQuery.isFunction(qualifier)) { return jQuery.grep(elements, function (elem, i) { /* jshint -W018 */ return !!qualifier.call(elem, i, elem) !== not; }); } if (qualifier.nodeType) { ...
= Description Replaces the data of the value. Extend this method, if you want clientside validation in the value itself. = Parameters +_value+:: The new data to replace the old data with.
set(_value) { if (this.differs(_value)) { this.value = _value; if (this.id) { require('comm/values').changed(this); } Queue.push(() => { this.refresh(); }); } }
push an unfilled limit purchase order to the queue
async purchase(quantity, price) { try { const symbol = this.symbol.meta; const tickSize = symbol.tickSize; //minimum price difference you can trade by const priceSigFig = symbol.priceSigFig; const quantitySigFig = symbol.quantitySigFig; const unconfir...
Create virtual table of cells with all cells, including span cells.
function createVirtualTable() { var rows = domTable.rows; for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) { var cells = rows[rowIndex].cells; for (var cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex],...
Load Triggers from Database to memory
function loadTriggers(){ Triggers.find({}, function (err, triggers) { if (err) throw err; triggers.forEach(function(elem){ triggerObj[elem.triggerId] = elem.triggers; }); console.log("TRIGGER OBJ UPDATED", triggerObj); }); }
This section of function declarations defines functions used to save and reload the state of game play. One of the simplest functions in this app. Just bundle up the current values of the set of global variables representing the current state of play, and turn then into an object with a timestamp of now. Then store it ...
function saveGameClient() { // The global variable gameState is updated with a new object // representing the state of play (ie the values of the set of // global variables representing the state of play) after every // corrent guess. It is also updated with saving to the cloud. gameState = { gameAnswers,...
random number upto max
function getRandomInt(max){ return Math.floor(Math.random() * Math.floor(max)); }
Unused at the moment, but likely to be required for fetching any initial data that may be needed appwide or on first load. Best approach is to have the retrieve data maintained in redux's store, then have lowerlevel containers connect/listen to the store. Avoids needing to map the props directly to children components/...
componentDidMount() { const { dispatch } = this.props; }
Create an example with gaussians to train the kmeans opn
function addExample(rowName, centroid, stddev) { var row = []; for (var i = 0; i < centroid.length; ++i) { row.push([names[i], centroid[i] + rng.normal(0, stddev), now]); } //plugin.log("normal dist = ", rng.normal()); dataset.recordRow(rowName, row) }
This service worker has a cache strategy: cache first except for resources where you mark another strategy, these can be network first or network only When you change version below you invalide the cache (this happens immediately not on next page load) ironboy 2019
constructor() { this.debug = false; this.version = 1.6; this.production = false; this.myRoute = 'serviceWorker.js'; this.lastRequestTime = 0; this.log('running from scratch...'); this.addEventListeners(); }
function creates a new element with text. A unique identifier is set to the new element
function createNewElement(elementType, newElementUniqueIdentifier, elementStr, parentElementID) { var newElement = document.createElement(elementType); newElement.setAttribute("id", newElementUniqueIdentifier) var elementText = document.createTextNode(elementStr); newElement.appendChild(elementText); document...
The actual plugin constructor
function Plugin( element, options ) { this.element = element; // jQuery has an extend method which merges the contents of two or // more objects, storing the result in the first object. The first object // is generally empty as we don't want to alter the default options for // f...
Normalize raw function directives into object format.
function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } }
Event that is emitted whenever unprocessed items appear in the directory of the current page. Returns if filtering was invoked.
function onScroll() { logTrace('invoking onScroll()'); if (pageLoads === true) { logWarn('Cancelled emitted scroll event, because page load is in progress.'); return false; } let remainingItems; if ( (currentPageType !== 'following') || (hideFollowing === true) ) { remainingItems = filte...
document.getElementById("characters").innerHTML = ""; continue; popArr(); let requestData = request.response.split("\n");
function printStored(){ document.getElementById("characters").innerHTML = (winningPhrase.join(" ")); }
Factory to get the `offset` for a line and columnbased `position` in the bound indices.
function positionToOffsetFactory(indices) { return positionToOffset /* Get the `offset` for a line and column-based * `position` in the bound indices. */ function positionToOffset(position) { var line = position && position.line var column = position && position.column if (!isNaN(line) && !isNaN(...
inverts the Z axis uses Y for X and flips it and inverts it depending on the orientation so it maps to left and right this is basically emulating a steering wheel
function normalizeAcceleration(acceleration) { var flipAcceleration = (window.orientation == 90 || window.orientation == 180) ? 1 : -1; var xDirection = (window.orientation == 0 || window.orientation == 180) ? acceleration.x : acceleration.y; return { x: xDirection * flipAcceleration, z: acceler...
Draws all objects in sceneObj[][] on the screen
function drawSceneObjects() { for (var i = 0; i < sceneWidth / tileSize; i++) { for (var j = 0; j < sceneHeight / tileSize; j++) { if (sceneObj[i] != null && sceneObj[i][j] != null) { ctx.drawImage(sceneObj[i][j].image, sceneObj[i][j].x, sceneObj[i][j].y); } } } if (selectedO...
strings go in quotation marks and should be separate from variables
function subtractVars() { }
After 5 hours of debugging, I found out that sometimes the content script does not get automatically injected. Therefore, I ensure that the content script becomes injected by executing it explicitly.
function ensureSendMessage(tabId, message, callback){ chrome.tabs.executeScript(tabId, {file: "cscript.js"}, function(){ if(chrome.runtime.lastError) { console.error(chrome.runtime.lastError); throw Error("Unable to inject script into tab " + tabId); } // Now it's inj...
Create HTTP error abstract base class.
function createHttpErrorConstructor() { function HttpError() { throw new TypeError('cannot construct abstract class'); } inherits(HttpError, Error); return HttpError; }
Gets all dependencies recursively on a codebook. Only works where getDirectDeps has been used to populate directDependencies
function getDepsRecursive(field, visited = []) { if (visited.indexOf(field) !== -1) return visited.push(field) for (let dep of field.directDependencies) getDepsRecursive(dep, visited) return visited }
Given a number of fifths, return the octaves they span
function fOcts (f) { return Math.floor(f * 7 / 12) }
chceme orders uchovavat v userovi / pro orders pouzijeme novou collection, muzou byt velmi velke (order history)
addOrder() { /* order musi mit user _id, a veci v cart */ const db = getDb(); return this.getCart().then(products => { const order = { items: products, user: { _id: new ObjectId(this._id), name: this.username, } }; /* vytvorime v orders ...
return true if a rev exists in the rev tree, false otherwise
function revExists(revs, rev) { var toVisit = revs.slice(); var splitRev = rev.split('-'); var targetPos = parseInt(splitRev[0], 10); var targetId = splitRev[1]; var node; while ((node = toVisit.pop())) { if (node.pos === targetPos && node.ids[0] === targetId) { return true; } var branche...
Class definition, inheritance and setup
function SecurityMode (id, controller) { // Call superconstructor first (AutomationModule) SecurityMode.super_.call(this, id, controller); var self = this; this._testRule = function () { // wrapper to correct this and parameters in testRule self.testRule.call(self, null); }; // Create instance variables th...
A bit "area of improvement" example on my opinion he tries to show 2 approaches, thus no one is good :)
function VehicleFactory() { }
Cedula 4857 rango de numeros
function validarCedula(elemento) { if(elemento.value.length > 0 && elemento.value.length < 11){ var codigA = elemento.value.charCodeAt(elemento.value.length-1) if((codigA >= 48 && codigA <= 57)){ }else { elemento.value = elemento.value.substring(0, elemento.value.length-1) ...
Function to: Convert temperature of both an input and select field respectively, In celsius, fahrenheit and kelvin
function temperature() { let temperature1 = document.querySelector('#temperature1').value; let temperature2 = document.querySelector('#temperature2').value; let number1 = document.querySelector('#number1').value; let number2 = document.querySelector('#number2').value; let temp1 = document.querySelector('#temp...
keep routes in my switch staetment
function App(){ const [posts, setPosts] = useState([]); const fetchPosts = ()=>{ const res = getPosts(); res.then((posts) => { console.log(posts) setPosts(posts.reverse()) }); } useEffect(()=>{fetchPosts()}, []) return( <> <Router> <Navbar/> <Switch> <R...
Renders the AWS CloudFormation properties of an ``AWS::Lambda::Function.TracingConfig`` resource
function cfnFunctionTracingConfigPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnFunction_TracingConfigPropertyValidator(properties).assertSuccess(); return { Mode: cdk.stringToCloudFormation(properties.mode), }; }
store our working values
constructor(x, y, w, h, myString){ this.x = x; this.y = y; this.w = w; this.h = h; this.myString = myString; this.strokeGreen = 0 // keep track of how many times this object has been hit this.time = 6; }
Gets the current page context that we're using.
get pageContext () { return (this.currentContext && this.currentContext.page) || this.page }
change current topic on click if not current was clicked
onTopicClick(topic) { if (topic.rowid === this.currentTopic) { return; } this.currentTopic = topic.rowid; localStorage.setItem('currentTopic', this.currentTopic); this.loadSelections(); }
Returns an array with the diferent campus
static getCampus() { return [ { name: 'BI', code: 3, }, { name: 'GI', code: 2, }, { name: 'AR', code: 1, }, ]; }
Creates notification. It creates and stores the new object in the master list of them. Appends the html to the notification section
function createNotification(message, type, seconds){ currentNotifications.push({ message : message, cyclesRemaining : seconds, type : type }); var typeClass = ""; var typeText = ""; if(type == "positive"){ typeClass = "positive-notification"; typeText = "dark-text"; }else if(type == "negative"){ typeClass =...
Generate unique id Returns string id
function generate() { var str = ''; var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001); if (seconds === previousSeconds) { counter++; } else { counter = 0; previousSeconds = seconds; } str = str + encode(alphabet.lookup, version); str = str...
Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree.
function isInstalled(projectConfig, dependencyConfig) { const project = _xcode().default.project(projectConfig.pbxprojPath).parseSync(); const libraries = (0, _getGroup.default)(project, projectConfig.libraryFolder); if (!libraries) { return false; } return (0, _hasLibraryImported.default)(libraries, d...
Returns output with relative filepaths expanded using the provided directory
function expandFilePathInOutput(output, cwd) { const lines = output.split('\n'); for (let i = 0; i < lines.length; i++) { const matches = lines[i].match(/\s*(\S+\.go):(\d+):/); if (matches && matches[1] && !path.isAbsolute(matches[1])) { lines[i] = lines[i].replace(matches[1], path.j...
4. Write a function that receives marks received by a student in 3 subjects and returns the average and percentage of these marks. there should be 3 functions one is the mainFunction and other are for average and percentage. Call those functions from mainFunction and display result in mainFunction
function main(maths, physics, computer) { function average() { var average = (maths + physics + computer) / 3; return average; } function percentage() { var percentage = ((maths + physics + computer) / 300) * 100; return percentage; } average(); percentage(); ...
finds the circle with the most marked cells keeps looping until it no longer finds circles with any marked cells
function findBestCircles(arrValidCircles) { var i; for (i = 0; i < arrValidCircles.length; i++) { iCount = arrayMarkCount(arrValidCircles[i][0], arrValidCircles[i][1], arrValidCircles[i][2], arrValidCircles[i][3]); if ((iCount > 0) && arrayCircleCheck(arrValidCircles[i][0], arrValidCircles[i][1], arrVali...
create function to process if answer is correct
function processAnswer(answer) { // set boolean switch to false displayQuestion = false; // clear page clearPage(); // set timeLeft to 3 for between question time timeLeft = 3; run(); // declare correct answer var correctAnswer = questions[que...
Create labels for the legend
function createLabels(varname, positions, range) { if (!positions) { console.log('[error] Create labels requires positions (x,y,z) array'); return; } if (positions.length % 3 !== 0) { console.log('[error] Create labels require positions array contain 3d points'); return; } ...
function to create first table and update
function uniqueCellWriter(column, record) { var html = column.attributeWriter(record), input ='', td = '<td'; if (column.index % 5 === 4) { html = ''; input = '<input class="recollection-id" type="hidden" value=' + record['id'] + '><input class="recollection-input" type="text" maxlength="1">'; } ...
Set the game state back to its original state to play another game.
function resetGame() { console.log("resetGame was called"); playerCount = 0; for (i=0; i<globalBoard.length; i++) for (j=0; j<globalBoard.length; j++) globalBoard[i][j] = null; return globalBoard; }
Return a new string that swaps the case of all of the letters:
function swapCase(string) { let output = []; string.split("").forEach((char) => { if (char === char.toUpperCase()) { output.push(char.toLowerCase()); } else { output.push(char.toUpperCase()); } }); return output.join(""); }
debugCallback function is primarily for just making sure the GeoJSON labels itself in the div and below the cities table. mydata is the only variable that will be called in this function, but is created in the next function.
function debugCallback(mydata){ //appending the text label of "GeoJSON data: " as well as the actual //text of the GeoJSON file. //JSON stringify is what helps label the data file. $("#mydiv").append('<br>GeoJSON data: <br>' + JSON.stringify(mydata)); }
var event = window.event;
function changeColor(event){ // console.log(event); var x = event.which || event.keyCode; // console.log(x); if (x == 66){ ctx.strokeStyle = 'blue'; } if (x == 71){ ctx.strokeStyle = 'green'; } if (x == 82){ ctx.strokeStyle = 'red'; } if (x == 89)...
Define function that will run on page load
function init() { let dropdownMenu = d3.select("#selDataset"); // Read json data d3.json("samples.json").then(function (response) { // Parse and filter data to get sample names let names = response.names; // Add dropdown option for each sample for (i = 0; i < names.length; i+...
r = "xy/R mod m"; x,y != r
function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
! LIMPIAR INPUTS DE ASIGNACION
function limpiarAsignacion() { $('#a_centro').empty(); $('#a_empleadosCentro').empty(); $('#a_todosEmpleados').prop("checked", false); }