anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
Update the water position and draw : object pool water sprites
function updateWater() { // animate water for (var i = 0; i < water.length; i++) { water[i].update(); water[i].draw(); } // remove water that has gone off screen if (water[0] && water[0].x < -platformWidth) { var w = water.splice(0, 1)[0]; w.x = water[water.length-1].x + pla...
SOLUTION SAVING /////////////////////////////////////////// //////////////// html5 storage
function HTML5_SolutionStorage() { }
the first pair where the sum is 0. Return an array that includes both values that sum to zero or undefined if a pair does not exist. sumZero([3,2,1,0,1,2,3]) => [3,3] sumZero([2,0,1,3]) => undefined sumZero([1,2,3]) => undefined
function sumZero(arr){ for(let i = 0; i < arr.lenght; i++){ for(let j = 0; j < arr.lenght; j++){ if(arr[i] + arr[j] === 0){ return [arr[i], arr[j]]; } } } }
CERTIFICATONS ENDS////////////////// / / / / ////////////////////ACHIEVEMENTS STARTS
function insertAchievements(data) { var achievements=""; achievements+='<div class="row achievement" id="'+data.achievementId+'">'; achievements+='<div class="row">'; achievements+='<div class="col-md-6 text-left">'; achievements+='<div style="font-size:18px;color:#008322;"><i class="fa fa-trophy"></i>&n...
Is called when databases are connected and adapter received configuration.
async onReady() { // Init info await this.initInfoStates(); // store all current (acknowledged) state values const allStates = await this.getStatesAsync('*'); for (const id in allStates) { if (allStates[id] && allStates[id].ack) { this.currentStateValu...
Merge two trees together The roots of tree1 and tree2 must be the same revision
function mergeTree(in_tree1, in_tree2) { var queue = [{tree1: in_tree1, tree2: in_tree2}]; var conflicts = false; while (queue.length > 0) { var item = queue.pop(); var tree1 = item.tree1; var tree2 = item.tree2; if (tree1[1].status || tree2[1].status) { tree1[1].status = ...
function to block bad immoral language...lol
function smutEngine() { smut="#@&*%!#@&*%!#@&*%!"; cmp="sex shit fuck piss dick porno cum cunt prick arse feck " +"asshole pedophile man-boy man/boy dong twat "; txt=document.isn.dirt.value; tstx=""; for (var i=0;i<16;i++){ pos=cmp.indexOf(" "); wrd=cmp.substring(0,pos); wrdl=wrd.length cmp=cmp...
Gets the suggestions from the database and adds them to the current state
getSearchSuggestions(term) { console.log(this.state.text); // GET request for movies axios .get('/api/searchgames', { params: { term: term } }) .then( function(response) { console.log(response.data); movieArray = response.data; ...
target, name > boolean
function Has(target, name) { if(!(this instanceof Has)) return new Has(target, name); else Read.call(this, target); Object.defineProperties(this, { "name": { value: name }, "origin": { value: (name in target) } }); // define diff Object.defineProperty(th...
Helper to get a typed SimpleDbStore for the document target object store.
function documentTargetStore(txn){return SimpleDb.getStore(txn,DbTargetDocument.store);}
Do this when collides == true
function collideAction(ball, p) { ball.vy = -ball.vy; if(paddleHit == 1) { ball.y = p.y - p.h; particlePos.y = ball.y + ball.r; multiplier = -1; } else if(paddleHit == 2) { ball.y = p.h + ball.r; particlePos.y = ball.y - ball.r; multiplier = 1; } points++; increaseSpd(); if(collision) { ...
DISPLAY ZOMATO API RESULTS
function displayResults (cuisine) { console.log(cuisine); }
| start_loading:void () | | Ready to start loading.
start_loading(){ this.model.preload(); }
Inser5t list items into DOM
function createList() { [...richestPeople].forEach((person, index ) => { const listItem = document.createElement('li'); listItem.setAttribute('data-index', index); listItem.innerHTML = `<span class="number">${index + 1}</span> <div class="draggable" draggable="true"> <p ...
206 // 207 Unlifts the DevTools store to act like the app's store. // 208 209
function unliftStore(liftedStore, reducer) { // 210 return _extends({}, liftedStore, { // 211 devToolsStore: liftedStore, // 212 dispatch: function dispatch(action) { // 213 li...
removed expired aggregated total from local store
function removeExpiredAggTotals() { var now = new Date().getTime(); var cache_time = 3600000; //1 hour (3600000 ms) for (var i = 0; i < localStorage.length; i++) { var key = localStorage.key(i); var agg_data = JSON.parse(localStorage[key]); //check within cache time if ((now...
Get weather by coordinates
getWeather(){ // Construct the API url to call let url = 'https://api.openweathermap.org/data/2.5/weather?lat=' + this.state.latitude + '&lon=' + this.state.longitude + '&units=metric&appid=ce0cb4b99e8ee814c20a4f76609c8196'; // console.log(url); // Call the API, and set the state of the weather forecast fet...
Autoupdate interval millisec Used from buttons to send commands to pre.di.c
function control_cmd(cmd, update=true) { // Sends the command to pre.di.c through by the server's PHP: // https://www.w3schools.com/js/js_ajax_http.asp var myREQ = new XMLHttpRequest(); myREQ.open("GET", "php/functions.php?command=" + cmd, true); myREQ.send(); // Then update the web page i...
Normalize `position` to add an `indent`.
function normalize(position) { var offsets = ctx.offset; var line = position.line; var result = []; while (++line) { if (!(line in offsets)) { break; } result.push((offsets[line] || 0) + 1); } return { start: position, indent: result }; }
A special extend for ajax options that takes "flat" options (not to be deep extended) Fixes 9887
function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } ret...
Listener for clicks on window, Set the last selected element.
onPageClick_() { this.pageClicks_++; this.lastSelection_ = this.win_.document.activeElement; }
render main window view
function renderMainWindow () { var targetMainPage = process.cwd() + '/html/main.html'; var html = fs.readFileSync(targetMainPage, 'utf8'); $('#window').append(html); }
Represent k1, k2 in a Joint Sparse Form
function getJSF(k1, k2) { var jsf = [ [], [], ]; k1 = k1.clone(); k2 = k2.clone(); var d1 = 0; var d2 = 0; var m8; while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { // First phase var m14 = (k1.andln(3) + d1) & 3; var m24 = (k2.andln(3) + d2) & 3; if (m14 === 3) m14 = -1; ...
Namespace and Property Utilities definitions;
function cloneFn(obj) { // "Static" types. if (isUndefined(obj) || isStaticType(obj)) return obj; var clonedObj = null; // Array. if (typeUtils.isArray(obj)) { clonedObj = []; for (var i = 0; i < obj.length; i++) clonedObj[i] = cloneFn(obj[i]); return clonedObj; } // Objects. clonedObj = new obj.con...
A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric characters such as '012ABC'. The reason why we are not using simply a number counter is that the number string gets longer over time, and it can also overflow, where as the the nextId will grow much slower, it is a string, and it ...
function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromChar...
called when we know the calendar couldn't be rendered when it was initialized, but we think it's ready now
function lateRender() { setTimeout(function() { // IE7 needs this so dimensions are calculated correctly if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once renderView(); } },0); }
Modal controls and listeners Initialize existing modal
function init_modal(selector) { $(selector).draggable({ addClasses:false }); }
Use the Google API Loader script to load the google.picker script.
function loadPicker() { gapi.load('auth', {'callback': onAuthApiLoad}); gapi.load('picker', {'callback': onPickerApiLoad}); }
calculate 2s complement checksum over a buffer, starting with a byte index
checksum( buf, start, length ) { let sum = 0; for( var i = start; i < start+length; i++ ) { sum = sum + buf[i]; } return ((~sum)+1) & 0xFF; }
Para Reposotory que utilizar MongoDb, passar o nome do database.collection no atributo da entidade
constructor() { super('loja.produtoInformacoes', 'pgMongoDb'); }
Resizes the canvas Code originally found at
function resizeCanvas(e){ var canvas = document.getElementById('mapCanvas'); var ctx = canvas.getContext('2d'); canvas.width = 950; canvas.height= 1200; var isMobile = { Android: function() { return navigator.userAgent.match(/Android/i); }, BlackBerry: function() { r...
get vendor property name that contains uppercase letter. e.g. webkitTransform
function getProperty(prop, host) { var targetHost = host || document.body.style; if (!(prop in targetHost)) { var char1 = prop.charAt(0).toUpperCase(); var charLeft = prop.substr(1); for (var i = 0; i < vendors.length; i++) { var vendorProp = vendors[i] + char1 + charLeft; ...
select items to analyze / graph type
function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); }
Copyright (c) 2015present, Facebook, Inc. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. Provides the empty string for anonymous operations.
function opName(operation) { return operation.name ? operation.name.value : ''; }
hide or show viaurl
function switchForm(to=0) { let viaurl = document.getElementById('new-i-form-viaurl'); let viaform = document.getElementById('new-i-form-page'); if (viaurl && viaform) { viaurl.style.display = to ? 'none' : ''; viaform.style.display = to ? '' : 'none'; } }
Pushes down a context to the given range by clearing all overrides between pushDownFrom and range.commonAncestorContainer, and clearing all overrides inside and along the range's boundary (see walkBoundary()), invoking pushDownOverride on all siblings of the range boundary that are not contained in it. Requires range's...
function pushDownContext(liveRange, pushDownFrom, cacOverride, getOverride, clearOverride, clearOverrideRec, pushDownOverride) { // Because range may be mutated during traversal, we must only // refer to it before traversal. var cac = liveRange.commonAncestorContainer; walkBoundary(liveRange, getOverride, pushD...
Hint: it may be helpful to get the height of your BST
function isBalanced(root) { }
function to write README file
function writeToFile(readMe, data) { const userData = generateMD(data); fs.writeFile(readMe, userData, function(err) { if(err) { throw err } else { console.log("You have successfully created a new README.md file.") } }) }
Goes to specified state.
changeState(state) { if(this.getStates().indexOf(state) != -1){ if(this.prevState[this.prevState.length - 1] != this.state) this.prevState.push(this.state); this.state = state; }else throw new Error("") }
populates the list of selectable pages, binds left and right arrow keys
function setupNav() { setupPageSelector(); setupRecipeSelector(); }
Gets credit cards list
fetchCreditCards(accountId) { let promise = this.remotePaymentAPI.query({accountId: accountId}).$promise; // check if if was OK or not let parsedResultPromise = promise.then((data) => { this.creditCardsPerAccount.set(accountId, data); }); return parsedResultPromise; }
End GC related code A utility function that returns a function that returns a timeout promise of the given value
function weShouldWait(delay) { return function (value) { return WinJS.Promise.timeout(delay). then(function () { return value; }); }; }
adds a Salutation to the recognize list
addSalutation() { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function* () { try { yield this.salutationService.addSalutation(this.newSalutation.value); } catch (err) { console.error(err); } ...
Balance the '(parent) left heavy, (child) right heavy' condition
leftRightCase(node) { if (!node.left) { throw new Error("leftRightCase: left child not set"); } node.left = this.rotateLeft(this.nodes[node.left]).id; return this.rotateRight(node); }
function to update existing duration logs in the reporting module.
function completeDurationLogs(jobId) { var ReportLog = mongoose.model('ReportLog'); var updateObj = { 'log.jobStatus': 'F' }; ReportLog.update( { 'type': 'durationLog', 'log.jobId': jobId, }, updateObj,{ multi: true } ,function(err, updatedReportLog){ if(e...
Function that executes on click of second next button
function next_step2(){ addAnimation(document.getElementById("second"), 'bounceOutRight'); setTimeout(function() { document.getElementById("second").style.display="none"; document.getElementById("third").style.opacity=0; document.getElementById("third").style.display="block"; ...
Give beforeSelectionChange handlers a change to influence a selection update.
function filterSelectionChange(doc, sel, options) { var obj = { ranges: sel.ranges, update: function(ranges) { var this$1 = this; this.ranges = []; for (var i = 0; i < ranges.length; i++) { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), ...
Funcion que se ejecuta al inicio
function init(){ mostrarform(false); listar(); $("#formulario").on("submit",function(e){ guardaryeditar(e); }); }
draw the avaiable colors we can use
function drawPalette() { $('#palette').html(' '); for (let i = 0; i < SQUARE_COLORS_ARRAY.length; i++) { let div = '<div id="color' + i + '"></div>'; $('#palette').append(div); $('#color' + i).css('background', SQUARE_COLORS_ARRAY[i]); } //add the click events $('#palette div').each(function(div) { $(`#c...
var pattern_config = require('./patternlabconfig.json');
function isDirectory(dir){ try { return fs.statSync(dir).isDirectory(); } catch (err){ return false; } }
! moment.js locale configuration
function a(e,a,c,n){var t={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[e+" Tage",e+" Tagen"],w:["eine Woche","einer Woche"],M:["ein Monat","einem Monat"],MM:[e+" Monate",e+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[e+" Jahre",e+" Jahren"]};return a?t[c][0]:t[c][1]}
Make sure result is not too big for display
function formatResult ( result, PRECISION, MAXDIGITS ) { // Number. if ( !isNaN ( result ) && result.toExponential().length > MAXDIGITS ) { return result.toPrecision( PRECISION ).replace ( /\+/g, ''); } else { return result; } }
Returns true if a to the given pathname/query combination is currently active.
function isActive(_ref, indexOnly, currentLocation, routes, params) { var pathname = _ref.pathname, query = _ref.query; if (currentLocation == null) return false; // TODO: This is a bit ugly. It keeps around support for treating pathnames // without preceding slashes as absolute paths, but possibly also...
Pick a moment m from moments so that m[fn](other) is true for all other. This relies on the function fn to be transitive. moments should either be an array of moment objects or an array, whose first element is an array of moment objects.
function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments...
Takes any number of passed in arguments that are numbers, and multiplies them.
function multiplyCommand(arguments, receivedMessage) { if (arguments.length < 2) { receivedMessage.channel.send("Not enough values to multiply. Try !`multiply 2 4 10` or `!multiply 5.2 7`") return } let product = 1 arguments.forEach((value) => { product = product * parseFloat(va...
getTotalLength() equivalent for circle, rect, polyline, polygon and line shapes adapted from
function getDistance(p1, p2) { return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)); }
GeneralHomepage component displays Navbar Displays welcome banner Routes users to /login or /signup
function GeneralHomepage(props) { return ( // <Router> <React.Fragment> <Navbar sticky='top'> <Navbar.Brand> <Link to="/"> <img height={60} src="/static/img/small-new-logo.png"/> </Link> </Navbar.Brand> <Navbar.Collapse className="j...
Absolute path to app dir
async function main() { const account = await nodemailer.createTestAccount(); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'the.one.brogrammers.inc@gmail.com', pass: `zkkhp65GZT9iB8GJ42Wf` } }); const mailOptions = { ...
returns true if this link can be picked up by linkify rule from plain text
can_be_linkify(dest) { let match = dest.match(/^(https?:|\/\/)/i); if (!match) return false; let proto = match[0]; let len = linkify.testSchemaAt(dest, proto, proto.length); return len && (len === dest.length - proto.length); }
Send GET request to run aiishellfe commands
function configure(option, hostname) { if (confirm('Do you want to "' + option + '" "' + hostname + '" ?')) $.get(AII_URL + '/cgi-bin/dashboard-aii.cgi', { 'action': 'configure', 'hostname': hostname, 'option': option }, fun...
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; }