anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
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); }
Write the font list to console
function listFonts () { asciify.getFonts(function (err, fonts) { if (err) { return console.error(err); } var padSize = ('' + fonts.length).length; fonts.forEach(function (font, index) { console.log(pad(padSize, index+1, '0') + ': ' + font); }); }); }
add to localStorage 3
function saveTodos(todoinput){ let todo; if (localStorage.getItem('todo') === null){ todo = []; console.log(todo); } else{ todo = JSON.parse(localStorage.getItem('todo')); } todo.push(todoinput); localStorage.setItem('todo', JSON.stringify(todo)); }
The renderer needs a size and the actual canvas we draw on needs to be added to the body of the webpage. We also specify that the renderer will be computing soft shadows
function initRenderer() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; w...
Unbias network to give byte values 0..255 and record position i to prepare for sort
function unbiasnet() { var i; var j; for (i = 0; i < netsize; i++) { network[i][0] >>= netbiasshift; network[i][1] >>= netbiasshift; network[i][2] >>= netbiasshift; network[i][3] = i; // record colour no } }
geographic distance courtesy the haversine formula
function geoDistanceKm(p1,p2) { var R = 6371; // km var x1 = p2.lat()-p1.lat(); var dLat = x1.toRad(); var x2 = p2.lng()-p1.lng(); var dLon = x2.toRad(); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(p1.lat().toRad()) * Math.cos(p2.lat().toRad()) * Math.sin(dLon/2) * Math.si...
integer IP to binary string representation
function IPv4_intA_to_binstrA( strnum ) { var numStr = strnum.toString( 2 ); /* Initialize return value as string */ var numZeros = 32 - numStr.length; /* Calculate no. of zeros */ if (numZeros > 0) { for (var i = 1; i <= numZeros; i++) { numStr = "0" + numStr } } return numStr; }
checks if the username is unique, if it is, connect them to that activity
function name_validate(roomParam) { roomParam.child("people/" + $("#input_name").val()).once('value', snapshot => { if (!snapshot.exists()) { let name = $("#input_name").val(); roomParam.child("people/" + name).set(true); //adds username to the database, within the room they are joinin...
When downloaded, we are ready to draw deferred charts.
function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; }
Escapes all potentially dangerous characters, so that the resulting string can be safely inserted into attribute or element text.
function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); }
Gets the table rows of the specified table, keyed by scopes
getTableRowsScoped(tableName) { return this.blockchain.getTableRowsScoped(this.accountName, tableName); }
Selects the correct recipes for that kind of weather
function select_by_weather(recipes) { recipes.forEach(recipe => { recipe['weather'] = false; }); let selectedChoices = findIfFilters("weather"); if (selectedChoices.length === 0) { document.querySelector('#no-filter-chosen').style.display = 'block'; } else { filter("weather",...
let a = new Human(); a.sayHello();
function AlevelStudent (obj = {name: 'Anatoliy', age: 23, marks:[1, 2, 3, 4, 5]}) { Human.call(this, obj); this.marks = obj.marks; }
Given a type reference in introspection, return the GraphQLType instance. preferring cached instances before building new instances.
function getType(typeRef) { if (typeRef.kind === _introspection.TypeKind.LIST) { var itemRef = typeRef.ofType; if (!itemRef) { throw new Error('Decorated type deeper than introspection query.'); } return new _definition.GraphQLList(getType(itemRef)); } if (typeRef.kind === _i...
Iteration 3: All scores average Get the average of all scores with 2 decimals
function scoresAverage(someArray) { if (someArray.length === 0) { return 0; } const sumScores = someArray.reduce((acc, eachScore) => { if (!eachScore.score) { return acc } return acc + eachScore.score; },0) let avgScore = sumScores / someArray.length; let roundedScore = M...
Fontion de codage de la phrase
function encoder() { let phraseCodee = ''; for (var i = 0; i < phraseAcoder.value.length; i++) { lettre = phraseAcoder.value.charAt(i); position = alphabet.indexOf(lettre); // suppression des ponctuations et espaces if ((lettre == ' ') || (lettre == '!') || (lettre == ',') || (le...
Runtime helper for checking keyCodes from config. exposed as Vue.prototype._k passing in eventKeyName as last argument separately for backwards compat
function checkKeyCodes ( eventKeyCode, key, builtInKeyCode, eventKeyName, builtInKeyName ) { var mappedKeyCode = config.keyCodes[key] || builtInKeyCode; if (builtInKeyName && eventKeyName && !config.keyCodes[key]) { return isKeyNotMatch(builtInKeyName, eventKeyName) } else if (mappedKeyCode) { r...
END rescheduleJob Checks whether the current time is within the time window set in config record
function isWithinTimeWindow(starttime, endtime) { //Dummy Record to get current timeof day var dummyConfig = record.create({type: "customrecord_flo_spider_configuration", isDynamic: true}); currenttime = dummyConfig.getValue({fieldId: 'custrecord_flo_conf_current_tod'}) ...
play and update data eith the new score
play(id) { this.playSound(id); userSequence.push(id); for(i=0; i<userSequence.length; i++){ if(userSequence[i] != gameSequence[i]){ gameOver = true; this.setState({flashIndex: 0}); Alert.alert("Try Again!") this.addAndUp...
vpb_setcookie('myCookie', 'The value of the cookie', 7) var myCookie = vpb_getcookie('myCookie'); vpb_removecookie('myCookie')
function vpb_IE_detected() { var ua = window.navigator.userAgent; var old_ie = ua.indexOf('MSIE '); var new_ie = ua.indexOf('Trident/'); if ((old_ie > -1) || (new_ie > -1)) { return true; } else { return false; } }
define faces of a cube
function colorCube() { quad( 1, 0, 3, 2 ); quad( 2, 3, 7, 6 ); quad( 3, 0, 4, 7 ); quad( 6, 5, 1, 2 ); quad( 4, 5, 6, 7 ); quad( 5, 4, 0, 1 ); }
Display a single evaluation. GET evaluations/:id
async show({ params }) { const evaluation = await Evaluation.findOrFail(params.id); return evaluation; }
Flips only the alignment edge of an element rectangle. This is used instead of nudging the alignment edges into position, when alignTargetEdge is specified.
function _flipAlignmentEdge(elementEstimate, target, gap, coverTarget) { var alignmentEdge = elementEstimate.alignmentEdge, targetEdge = elementEstimate.targetEdge, elementRectangle = elementEstimate.elementRectangle; var oppositeEdge = alignmentEdge * -1; var newEstimate = _estimatePosition(elementRectangl...
Add new Task to list
function addTask() { var taskId = "task_" + taskCount++; var task = createTask(taskId, "", ""); taskList[taskId] = task; var domElement = createNewTaskDOMElement(task); taskListDOMElements[taskId] = domElement; showTaskDetail(task); }
================================================================================= ================================================================================== Sets the iinput array that is the first table in the Data View. ==================================================================================
function setInputValues(dgInputs) { var impTbl = document.getElementById("InputValuesTable"); //impTbl.innerHTML = ""; var keys = dgInputs.keys() var values = dgInputs.values(); var tableData = ""; for (var i = 0; i < keys.length;i++) { if (i % 2 && i != 0) tableData = tableData + "<tr><td>"+ k...
This function is to update a data source
static async updateDataSource(email, dataSourceID, dataSourceName) { return new Promise((resolve, reject) => { Database.sendQuery('UPDATE datasource SET sourceName=$3 WHERE ( email = $1) AND ( ID = $2) RETURNING *;', [email, dataSourceID, dataSourceName]) .then((result) => { if (result.rows.length > 0) re...
function to pop up overlay with winning message
function winOver() { if (player.win === true){ let message = document.createTextNode('You win!'); let messageBtn = document.createTextNode('Play again?') let doc = document, overlay = doc.createElement('div'), winMessageDiv = doc.createElement('div'), winMes...
(public) this mod a
function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; }
Read the last five messages to the users
readLatestMessages(messageNumber){ var entireMessages = this.get('messages'); if (messageNumber > entireMessages.length) messageNumber = entireMessages.length; var begin = Math.abs(messageNumber - entireMessages.length); var end = Math.abs(messageNumber - entireMessages.lengt...
create function to check if the last move made makes this a win display winning message if it is a winner
function checkWinner() { var win = true; for (var i = 0; i < 4; i++) { for (var j = 0; j < 4; j++) { if (!(cells[i][j].innerHTML == i * 4 + j + 1)) if (!(i == 3 && j == 3)) win = false; } } if (win) { alert("Congratulations! You won...
Aux function that retrieves the indentation level of some code line, useful for YAML decoding.
function indentLevel(linea) { var level = 0; for ( i in linea ) { if ( linea[i] != ' ' ) { break;} level += 1; } return (level); }
pure javascript to scale the game
function resize() { var canvas = document.querySelector("canvas"); var parent = document.getElementById('wheel_game'); var windowWidth = parent.offsetWidth; var windowHeight = parent.offsetHeight; var windowRatio = windowWidth / windowHeight; var gameRatio = game.config.width / game.config.heigh...
Handles responses to an ajax request: sets all responseXXX fields accordingly finds the right dataType (mediates between contenttype and expected dataType) returns the corresponding response
function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = respo...
Returns the monster name for a given monster ID. Requires the sky_monster file to be loaded.
function getMonName(monId) { var female = (monId > 600); if (female) { monId -= 600; } if (WMSkyPoke[monId]) { // (female ? "[F]" : "[M]") + return WMSkyPoke[monId]; } else { return "Unknown"; } }
static contextType = ThemeContext;
render() { return ( <ThemeContext.Consumer> { value => ( <div style={{ border: `5px solid ${value.color}`, padding: "5px" }}> <div>Header</div> <Title /> </div>...
Mix in a 32bit integer into the pool
function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; }
Returns whether the specified locator is a dependency tree root (in which case it's part of the project) or not
function isDependencyTreeRoot(packageLocator) { if (packageLocator.name === null) return true; for (const dependencyTreeRoot of runtimeState.dependencyTreeRoots) if (dependencyTreeRoot.name === packageLocator.name && dependencyTreeRoot.reference === packageLocator.reference) return true; return false; }
==================== getLongestWord v2 ====================
function getLongestWord(word1, word2) { return (word1.length > word2.length) ? word1 : word2; }
returns the covariance of X and Y
function cov( x, y, size){ var sum=0; for(var i=0;i<size;i++){ sum+=x[i]*y[i]; } sum/=size; // var avg1 = avg(x,size); // var avg2 = avg(y,size); // var avgMult = avg1 * avg2; // var total = sum - avgMult; //console.log("cov : " + (sum - avg(x,size)*avg(y,size))) return sum - avg(x,size)*avg(y,s...
Remove page from object
function removeProp(obj, propName) { const changedObj = { ...obj }; if (changedObj[propName]) { delete changedObj[propName]; } return changedObj; }
Challenge 4 Awesome job! Other lighthouse operators are jealous of your grid. Just to show off, let's write a new function for the system which will count up how many cells total there are. Given the code you just wrote, this should be pretty easy. Write a new function called totalCells() which will return the total nu...
function totalCells(){ var rows = countRows(); var cols = countColumns(); var size = rows * cols; return size; }