anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
function getUsers() { return db('users') .select('id', 'username') }
for listing users for dev testing (excluding passwords)
function makeNewStrike(line, strikeHorder){ strikeHolder[line.strike] = {}; strikeHolder[line.strike].numberStrike = line.numberStrike; sortCallsAndPuts(line, [strikeHolder[line.strike]]); }
if strike not already in object, make a new object for the strike THEN add the call or put
function getStr(str) { console.log(str.length); }
let dom: HTMLElement | null = document.getElementById('root'); console.log(dom.id)
function getMovie() { //GETTING THE ID FROMSESSION STORAGE let movieId = sessionStorage.getItem("movieId"); axios .get("https://www.omdbapi.com?apikey=af465f0e&i=" + movieId) .then(response => { console.log(response); let movie = response.data; let imdbid = movie.imdbID; // UPDATIN...
GETTING THE MOVIE WHICH IS SELECTED
function checkIfPresent(output, X, isActor){ var set = -1 if(output.length == 0){ return set } output.forEach((element,index,output) => { if(isActor){ if(element.Name === X){ set = index return set } } else{ if(...
using this function for both actors array and genre array by passing true or false to isActor
function createCharReader (nextChar, rewind) { let charsRead = 0 return { nextChar () { charsRead += 1 return nextChar() }, reset () { rewind(charsRead) charsRead = 0 }, rewind (n = 1) { rewind(n) charsRead -= n } } }
lets you read chars, and optionally reset the cursor to where it was before reading
function search() { const text = this.value; if (text === '') { rows.forEach(row => row.style.display = null); return; } const length = names.length; const regex = new RegExp(text, 'gi'); for (let i = 0; i < length; i++) { if (names[i].match(regex)) rows[i].style.display ...
Implement the search function
function canAccessProperty(object, property) { try { const unused = object[property]; return true; } catch (errors) { return false; } }
Return true if |object|.|property| can be called without throwing an error.
function DateRegisterTK(monthExtend) { // body... var date = new Date($('#RegisDateTK').val()); date.setMonth(date.getMonth() + monthExtend); var dd = date.getDate(); var mm = date.getMonth() + 1; //January is 0! var yyyy = date.getFullYear(); if (dd < 10) { dd = '0' + dd; } ...
get endDate contract in modal register ticket from comboboxDate
function addNew(){ var req = new XMLHttpRequest(); var newExercise = document.getElementById("inputNew"); var measurement; if (newExercise.elements.name.value == ""){ alert ("Error: Name is required."); return; } /*Formatting measurement*/ if(newExercise.elements.measurement.checked){ ...
Function for adding new item from form
function compareEquality1(a, b) { if(a == b) { return "Equal"; } return "Not Equal"; }
practice comparing different values
function deactivate() {}
this method is called when your extension is deactivated
function sample_population(population, fitnesses, selection_rate) { num_of_selected_chromosome = parseInt(selection_rate * population.length) mating_population = [] // console.log(num_of_selected_chromosome + " " + population.length) for (var i = 0; i < num_of_selected_chromosome; i++) mating_population.pu...
Sample Populasi population = generate_population(5) fitnesses = calculate_population_fitness(population) console.log(sample_population(population, fitnesses))
function showTiles() { var tiles = getTiles(); var formHTML = "<ul>"; for (var i = 0; i < tiles.length; i++) { formHTML = formHTML + '<li>' + tiles[i].title + '</li>'; } formHTML = formHTML + "</ul>"; $( "div#tilesList" ).html(formHTML); }
Display the list of Tiles for the current Project.
parts(key) { var raw = this.param(key); var parts = raw.split('|'); for (var i = 0; i < parts.length; ++i) { parts[i] = parts[i].trim(); } return parts; }
Split a data attribute by | and return the trimmed parts
function submitPasswordChangeRequest(form) { return new Promise(function (resolve, reject) { // Emulate an API call. Reject a portion of the requests. setTimeout(function () { // reject if password is incorrect if (form.currentPassword !== 'qqQQ11!!') { reject({ code: 401 ...
Submit a password change request to the backend.
function where(list, properties, k) { var names = [] return reduce(list, function(list, v, k) { var names = true for (var k in properties) { if (properties[k] !== v[k]) { names = false } } if (names == true) { list.push(v) ...
Write a function where() that filters for all the values in the properties object.
function nextGeneration () { var changes = false; Life.nextGrid = matrix(Life.HEIGHT, Life.WIDTH, false); for ( var h=0; h < Life.WIDTH; h++ ) { for ( var v=0; v < Life.HEIGHT; v++ ) { // get the number of living neighbors var aliveCount = evaluateNeighbors( h, v ) switch (true) { ...
evaluate all cells and build new matrix for next generation
function loadTable() { if (hiddenCmd.dispatch) { hiddenCmd.dispatch("refresh"); } else { setTimeout(loadTable, 1000); } }
webEdition SDK webEdition CMS $Rev$ $Author$ $Date$ This source is part of the webEdition SDK. The webEdition SDK is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License the Free Software Foundation; either version 3 of the License, or any later version. The G...
function xSwapImg(imgDiv,srcImg,srcAltImg){ /* Update by Christian Vallee <cv@valtechnologie.com> ==> No need to specify absolute URL for images anymore, this feature will find it on its own */ // looking for the images' root URL based on the current image var str = imgDiv.src; var pos = str.search(srcImg)...
Toggle expanded / collapsed versions of items' images
sendMessage() { // Construct the message here const message = { sender: this.state.sender, reciever: this.props.replier, subject: 'RE: ', body: this.state.body, msgType: 'reply', reply: this.props.replyId }; // Post...
Hits API with body of carve
function n(t,e){if(!t)throw new Error("[vue-router] "+e)}
vuerouter v3.0.1 (c) 2017 Evan You
function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += ...
=========================================================================== Send a value on a given number of bits. IN assertion: length <= 16 and value fits in length bits.
function g() { 'use strict'; var x, y, grid = canvasDatagrid({ parentNode: document.body, allowFreezingColumns: true, allowFreezingRows: true, debug: false }); grid.style.columnHeaderCellHeight = 40; grid.style.cellHeight = 40; ...
globals canvasDatagrid: false / this file is for developing in a sandbox on a local machine
addToRenderedList() { if (this.state.renderedArray.length <= 5) { let renderedArray = this.state.renderedArray; let foodArray = this.state.foodArray; if (this.state.foodArray.length > 5) { renderedArray = renderedArray.concat(foodArray.slice(0, 5)); foodArray = foodArray.slice(5);...
feeds the food array to the renderedList to fix performance
function ajaxExtend( target, src ) { var deep, key, 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 ); } retur...
A special extend for ajax options that takes "flat" options (not to be deep extended) Fixes 9887
function QueueDrawAgent(selector, h, w, problem, options) { this.canvas = document.getElementById(selector); this.canvas.innerHTML = ''; this.two = new Two({ height: h, width: w }).appendTo(this.canvas); this.problem = problem; this.nodeRadius = 25; this.options = options; this.iterate = functi...
An agent to draw queues for bfs and dfs
function received_animals(animals_res, user_input, res){ animals_res.setEncoding("utf8"); let body = ""; animals_res.on("data", function(chunk){ body += chunk; }); animals_res.on("end", function(){ let animals_info = JSON.parse(body);//convert from a JSON string to js obj let animals_array_length = animals_i...
Catch the information of each animal
respondWithRedirect(ctx) { if (!ctx.session) { return ctx.response.status(this.status).send('Invalid credentials'); } ctx.session.flashExcept(['_csrf']); ctx.session.flash('auth', { errors: { uid: this.code === 'E_INVALID_AUTH_UID' ? ['Invalid logi...
Flash error message and redirect the user back
function getPackageInformationSafe(packageLocator) { const packageInformation = getPackageInformation(packageLocator); if (!packageInformation) { throw internalTools_1.makeError(internalTools_1.ErrorCode.INTERNAL, `Couldn't find a matching entry in the dependency tree for the specified parent (this is pr...
Returns information about a package in a safe way (will throw if they cannot be retrieved)
function action(args, env) { // Prompt for tasks if ( args.length === 0 ) { prompt('Task:', _promptFinished); } // Process Tasks else { for ( let i = 0; i < args[0].length; i++ ) { _process(args[0][i], i+1, args[0].length); } } }
This command remove 1 or more Tasks
function newSumZero(arr) { // left = beginning of the array let left = 0; // right = end of array, remember it's zero indexed let right = arr.length - 1; // left < right is our fail safe while (left < right) { let sum = arr[left] + arr[right]; if (sum === 0) { return [arr[left], arr[right]]; } else if (...
Refactoring, using Multiple Pointers method Time Complexity O(N), Space Complexity O(1)
removeUser(userID) { if(userID in this.users) { delete this.users[userID]; return true; } else { return false; } }
removes user by UID returns true if successful, false otherwise
function cfnHttpNamespacePropsToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnHttpNamespacePropsValidator(properties).assertSuccess(); return { Name: cdk.stringToCloudFormation(properties.name), Description: cdk.stringToCloudFormation(pro...
Renders the AWS CloudFormation properties of an `AWS::ServiceDiscovery::HttpNamespace` resource
async function createIngredientAndUnit(item) { //ingredient let ingredient = await strapi.api.ingredient.services.ingredient.findOne({ name: item.ingredient.name, }); if (!ingredient) { ingredient = await strapi.api.ingredient.services.ingredient.create({ name: item.ingredient.name, }); } ...
Read the documentation ( to customize this controller
function parseXML(xml){ console.log("in parseXML"); $("h1").html("Final Project Assignment<br>" + "Kody Scharf, Andrew Lee<br>" + "991455754, 991457820<br>"); }
end of doc load
animMoveBack(direction) { let anim = this.renderAnimation('moveBack', direction); let board = this.board; let pixi = this.pixi; anim.frames.forEach((frame, frameId) => { let offsetRatio = (frameId + 1) / anim.frames.length; let offset = board.getOffset(-offsetRatio / 2, direction); a...
Moving back and forward is similar to moving. But the offset ratio is cut in half to reflect that the destination is halfatile away. Also, it is a negative ratio, since the offset is behind the unit.
function displayEmptyPageMessage() { $("#emptyPageMessageWrapper").removeClass("hidden"); }
Displays the "empty page" message on the page
async function updatePrivacy(privacy, username) { if(arguments.length != 2 || typeof privacy !== "string") { throw("updatePrivacy: You must have a privacy and a username"); } const usersCollection = await users(); let user = await usersCollection.findOne({userDisplayName: username}); if(user == null)...
Leo wrote this given a boolean, sets user's privacy setting
function addRecord(){ let codigo = document.getElementById('codigo').value; let nombre = document.getElementById('nombre').value; let precio = document.getElementById('precio').value; productos.push(new IngrProducto(codigo,nombre,precio)); }
Funcion para poblar los campos
function frmPatientSummary_checkuncheck(eventobject) { com.healogics.utility.showLoading(); searchPatient_closeSearchList(); //Sandeep offline changes for chart if (isIpad && !isNetworkAvailable()) { var error_label = ERROR_CONSTANTS.NO_NETWORK_CONNECTION; com.healogics.utility.showError...
Method to select/unselect wound from wound list
function redirect(url, response) { console.log('redirect to ' + url); response.writeHead(301, {Location: 'http://' + url}); response.end(); }
Redirect to the real url
function getCurrentRunTime(startTime, currentTime = undefined) { if (currentTime === undefined) { currentTime = new Date().getTime(); } return currentTime - startTime; }
Returns the current run time
function parseInput(str) { var input = {}; var tokens = str.trim().toLowerCase().split(/\s/); var halves = mergeTokens(tokens); if (!validateInput(halves)) return null; input['department'] = halves[0]; input['courseNumber'] = halves[1]; return input; }
Parse the input string and return an object with department and courseNumber properties filled in.
function updateCounter() { var cartCounter = document.getElementById('itemCount'); cartCounter.textContent = cart.items.length; }
Update the cart count in the header nav with the number of items in the Cart
function implementsAnyMethods(obj, methods) { if (typeof obj !== 'object' || obj === null) { return false; } for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) { var method = methods_1[_i]; if (method in obj && typeof obj[method] === 'function') { r...
Return true if the object passed in implements any of the named methods.
function remember() { // store our current tweets array in localstorage // but remove last memory of it first localStorage.removeItem('twitter'); // remember tweets array localStorage.setItem('twitter', JSON.stringify(tweets)); }
vote poll from Albert's codes
function useQueries(createHistory) { return function () { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var history = createHistory(options); var stringifyQuery = options.stringifyQuery; var parseQueryString = options.parseQueryString; if (typeo...
Returns a new createHistory function that may be used to create history objects that know how to handle URL queries.
consume (key) { if (_state[key].length > 0) return _state[key].shift(); return false; }
for consuming queuelike objs
function date(callback) { console.log(new Date); setTimeout(function() { let date = new Date; callback(date); },3000) }
esto me sirve para poner una funcion dentro de otra funcion y me permite trabajar esto de forma bastante espeficica por lo que entiendo abajo sentencio la funcion date con callback y hace un console log como new Date despues hace un metodo setTimeOut
task_assigned_to(){ var user_id = Session.get('mySession'); Meteor.subscribe('fetch_assigned_task_to', user_id); // var task_assign_by_1 = Session.get('task_assign_to'); // return task_assignment.find({ 'user_id_by' : task_assign_by },{sort: {created_at: -1}}).fetch(); return task_assignment.find...
helper function is used to show the task which was assigned by you to someone
function ReactGridLayout(props, context) { _classCallCheck(this, ReactGridLayout); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _initialiseProps.call(_this); (0, _utils.autoBindHandlers)(_this, ['onDragStart', 'onDrag', 'onDragStop', 'onResizeStart', 'onR...
TODO publish internal ReactClass displayName transform
function assertCompiler(name, Compiler) { if (typeof Compiler !== 'function') { throw new Error('Cannot `' + name + '` without `Compiler`') } }
Assert a compiler is available.
function upsertInner(db, docId, diffFun) { return new PouchPromise(function (fulfill, reject) { if (typeof docId !== 'string') { return reject(new Error('doc id is required')); } db.get(docId, function (err, doc) { if (err) { /* istanbul ignore next */ if (err.status !== 404) ...
this is essentially the "update sugar" function from daleharvey/pouchdb1388 the diffFun tells us what delta to apply to the doc. it either returns the doc, or false if it doesn't need to do an update after all
function wait() { if ( questionCounter < 7 ) { questionCounter++; generateHTML(); counter = 30; timerWrapper(); } else { finalScreen(); } }
Keeps the game going until the final question, then it will switch to the final screen.
function bookmarkWhere() { var string = JSON.stringify(where); localStorage.setItem('whereBookmark', string); }
saves the data into local storage
function clickOutside(e) { var container = $("#navList"); if ((!container.is(e.target) && !$("#mobile-nav").is(e.target))) // if the target of the click isn't the container... { container.removeClass("show"); } }
Close navList if click outside div
function goBack() { id('data').innerHTML = ""; id("find-btn").disabled = false; }
Resets the contents and reenable the find buttons;
function add_to_main_windows_list(window_id) { var temp_main_windows_list = get_main_windows_list(); var index = temp_main_windows_list.indexOf(window_id); if (index < 0) { //this windows is not in the list currently temp_main_windows_list.push(window_id); } localStorage.main_windows = temp_main_w...
ADD TO main_windows LIST
function getMedicamentosPaciente(req, res){ console.log('- GET MEDICAMENTOS PACIENTE -'); var query = Paciente.findById(req.params.idPaciente); query.populate({ path: 'medicamentos', model: 'Medicamento' }) .exec(function (err, paciente) { if (err) { ...
Obtengo los medicamentos de un determinado paciente
function tick(e) { node .each(gravity(e.alpha * .1)) .each(collide(.5)) .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); label .style("left", function(d) { return (d.x - d.dx / 2) + "px"; }) .style("top", function(d) { return (d.y - d.dy / 2) + "px"; }...
Simulate forces and update node and label positions on tick.
function createNewReplyBox(reply_location){ div_top = reply_location.parentElement.parentElement.childNodes[3]; debugger; div1 = document.createElement("div"); div1.className = "replies"; div1.style.display = "block"; div_top.parentNode.insertBefore(div1, div_top.nextSibling); blank1 = document.createTex...
create new reply box
function convertToFahrenheit(temp){ let fahr = temp *9/5 +32; console.log(`${temp} degrees in C is ${fahr} degrees in F`); }
Fahrenheit = Celcius 9/5 +32
function copy() { // Copy these folders and contents as is gulp.src([ 'src/background/**', 'src/content/**', 'src/popup/**', 'src/styles/**', 'src/vendor/**'], {base: 'src'}) .pipe(gulp.dest(OUTPUT_DIR_WEB_EXTENSION)); // Compile less into css gulp.src('src/**/*.less', {base: 'src'}) ...
Define our tasks using plain functions
function setEventBehaviour(){ button.style("pointer-events","all"); }
sets event behaviour button needs always be clickable even if nonClickable layer blocks it
function SpriteCollision(offset, sprite1, sprite2) { for (var x = 0; x < sprite1.width; ++x) { var xx = +x + +offset[0]; if (xx < 0 || xx >= sprite2.width) continue; for (var y = 0; y < sprite1.height; ++y) { var yy = +y + +offset[1]; if (yy < 0 || yy >= sprite2.height) continue; var pix1 = sprite1.r...
Sprite based collision checking
function datosugerencia($id_sugerencia){ var id = $id_sugerencia; var base_url= 'http://localhost/sistema_monedas/'; $.ajax({ url: base_url + "sugerencias/view/" + id, type:"POST", success:function(resp){ $("#modal-default .modal-body").html(resp); ...
MERCADO SECCION MONEDAS SUGERENCIAS
function handleTransparentNavbar() { setTransparentNavbar(dispatch, (fixedNavbar && window.scrollY === 0) || !fixedNavbar); }
A function that sets the transparent state of the navbar.
function removeComment() { let shortenId2=this.id.slice(15) // console.log(shortenId2) let commentRef3= firebase.database().ref("posts/"+shortenId2); let optionConfirmRemove = confirm ("Confirma si quieres eliminar el comentario") if (optionConfirmRemove == true){ commentRef3.remove(); }...
Funcion para eliminar comentarios
function buttonsSetting() { var buttons = document.getElementsByTagName("li"); for (var i = 0; i < buttons.length; i++) { buttons[i].bubbles = true; EventUtil.addHandler(buttons[i], "click", buttonFunc(i, "custom")); } }
initialize all the button click function
getProcessedValue(value) { const { minDate, maxDate, maxDetail, returnValue, } = this.props; const processFunction = (() => { switch (returnValue) { case 'start': return getDetailValueFrom; case 'end': return getDetailValueTo; case 'range': ...
Gets current value in a desired format.
function ScenarioStepFactory(step,ctx) { this.isAction = () => step.action !== undefined this.isConsumedMessage = () => (step.message !== undefined) && (step.consumed_by !== undefined) this.isProducedMessage = () => (step.message !== undefined) && (step.produced_by !== undefined) this.isCalledAPI = () => (step....
If you have a new step, just add a condition and create the class
function getLineContent(cm, lineView) { var ext = cm.display.externalMeasured; if (ext && ext.line == lineView.line) { cm.display.externalMeasured = null; lineView.measure = ext.measure; return ext.built } return buildLineContent(cm, lineView) }
Wrapper around buildLineContent which will reuse the structure in display.externalMeasured when possible.
function leaveClient() { socket.emit('leave', {name: playerId}); }
Client wants to leave the game
function makeInterval() { intervalID = setInterval(function() { fadeOutAndIn(); }, intervalTime); }
Function to set the interval execution
function resolveCircularModuleDependency$1(fn) { { if (!isFunction$2(fn)) { throw new TypeError(`Circular module dependency must be a function.`); } } return fn(); }
When LWC is used in the context of an Aura application, the compiler produces AMD modules, that doesn't resolve properly circular dependencies between modules. In order to circumvent this issue, the module loader returns a factory with a symbol attached to it. This method returns the resolved value if it received a fac...
function _subfunction(placeObject){ console.log('displayed'+placeObject.name); var retval=new VenueObject(placeObject);//turn that off retval.done(function(marker){ placeObject.marker=marker; }); }
the above contains processing for the entry the following displays it, but should be extracted possibly to the updateVenueMarkerVisibilityFlag... this attempts to display all
function getTemperature(){ $.getJSON("api/getTemp", function(tempJson){ updateGraph(tempJson); }); }
Get the temp from the the API with a getJSON call
async function getArtists() { //In questa copia del progetto, mi sono salvato tutti gli artisti e le loro informazioni in un file json artistsList = await fetch('artists.json').then(r => r.json()); }
Data fetch: artists' info
function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = __webpack_require__(4695); createDebug.destroy = destroy; Object.keys...
This is the common logic for both the Node.js and web browser implementations of `debug()`.
function addInventory() { var query = "SELECT * from products"; connection.query(query, function (error, results) { if (error) throw error; inquirer.prompt([ { type: "input", message: "What is the id of the product you want to add?", ...
Function to add to inventory
restart() { this.x = 200; this.y = 380; }
Set player to intial location.
function applyTransforms(el, nobodyscale) { // zoomer area and scale value var zoomerArea = el.querySelector('.zoomer__area'), zoomerAreaSize = {width: zoomerArea.offsetWidth, height: zoomerArea.offsetHeight}, zoomerOffset = zoomerArea.getBoundingClientRect(), scaleVal = zoomerAreaSize.width/zoomerAreaSize...
applies the necessary transform value to scale the item up
function bodyBG(image) { let bg = "linear-gradient(45deg,rgba(0, 0, 0, 0.6) 65%, rgba(250, 250, 250, 0.34))"; if (window.innerWidth < 800) { document.body.style.backgroundImage = bg + ",url('img/sm/" + image + "')"; } else { document.body.style.backgroundImage = bg + ",url('img/" + image + ...
Change the BG of body
function HandlerStackEntry(k, next) { this.k = k; this.next = next; }
Constructor for a stack entry on the global exception handler stack
render() { return ( <div> {this.props.children(this.state.count, this.incrementCount)} </div> ); }
render the children of this component the children of this component is an arrow function that takes the count and inrementCount and renders the original component and passes the count and inrementCount to it
getId(title, year) { //using the google youtube api to get the video id let youtube = (params, callback) => { axios.get(this.state.url, { params: params }).then(function(response) { callback(response.data.items[0]) }).catch(function(error) { console.error(error); }); ...
method to get the movieID and setting it to state
function updateProfile() { if (newName.value!="") { name.innerHTML = newName.value; } if (newEmail.value!="") { email.innerHTML = newEmail.value; } if (newPhone.value!="") { phone.innerHTML = newPhone.value; } if (newZipcode.value!="") { zipcode.innerHTML = newZipcode.value; } if (newPassw...
update the profile and clear the input text
function createControls(camera, domElement) { // Create new OrbitControls linked to the camera and the renderer's DOM element const controls = new OrbitControls(camera, domElement); return controls; }
Function to initialize the controls
async createTypePlant(req, res) { const { name, legendary } = req.body; const newType = new TypePlant({ name, legendary }); try { await newType.save(function (err) { if (err) return res.status(400).json({ error: `Error en los datos ingresados` }); res.status(200).json({ message: `Planta ${name} creada ...
================================ POSTS =============================== create new user
function subscribe(name, callback) { // Subscripton names are lowercased so both 'Shift+Space' and 'shift+space' works. name = name.toLowerCase(); // remove spaces so both 'Shift + Space' and 'shift+space' works. name.replace(/\s/, ''); if (typeof __subscriptions[name] === 'undefined') { __su...
creates a subscription and returns the unsubscribe function;
function particle() { for (var i=0; i<50; i++) { var dir = new THREE.Vector3(2*Math.random()-1, Math.random()*4, 2*Math.random()-1); dir.multiplyScalar(6/dir.length()); var color = (Math.random() > 0.5) ? 0x333333 : 0x666666; var p = new Particle(obj.position, dir, color, 0.1); ...
var j = 0;
function propertyValue(t, v) { if (t === 'string') return util.inspect(v, { colors: true }); else if (t === 'number' || t === 'boolean') return v.toString().blue; else if (t === 'object' && v == 'null') return 'null'.blue; else if (t === 'undefined') return 'undef...
TODO: check if result is React component and highlight it
get not() { return { /** * Returns true if PageElement currently does not exist. */ exists: () => !this.exists(), /** * Returns true if PageElement is currently not visible. */ isVisible: () => !this.isVisible(),...
returns the negated variants of PageElementCurrently's state check functions
onAddComment(evt){ evt.preventDefault(); if (this.state.comment.trim() === ''){ return; } const newComment = { content: this.state.comment, posted: new Date(), } // empty the comment text this.setState({comment: ''}); ...
Adds the comment to local storage via redux actions
function makeCompare (fn) { return function (value, key) { return hasOwn(this, key) && fn(value, this[key]) } }
makes a function to compare the object values from the specified compare operation callback
function resetTodosList (jsonObject) { //empty tasks jsonObject.tasks = []; console.log('tasks list emptied successfully'); //turn into string and save it to the file jsonObject = JSON.stringify(jsonObject); return fs.writeFile('todo.json',jsonObject); }
resets the amount of tasks to 0 takes the todosFile json and modifies the tasks in it this function is invoked when the user enter the command 'reset'
function drawRoundCorner(Wright, r, transform$$1) { var angle = Math.PI/2 * Wright / (Wright + Wtop); // not sanitizing this one, because negative values // are useful to fill the box correctly. var ri = { x: r.x - Wright, y: r.y - Wtop ...
draws one round corner, starting at origin (needs to be translated/rotated to be placed properly).
function updateQuiz(pointer, value, currentlyEditing) { setQuiz(oldQuiz => { let q = [...oldQuiz.problems]; q = q.map((problem, i) => { if (i === pointer) { if (currentlyEditing.type === QUESTION) { return { ...problem, question: value }; } else if (currentlyEditi...
Helper functions for state...
function cargarMT(){ if( APIcompatible() ) { //[1] $('#cargarMT').trigger('click'); //[2] }else{ mostrarAlert('API FileRader no compatible con este navegador.') } }
Carga la MT / 1. Comprueba si el API es compatible con el navegador 2. Hacemos trigger en el input que carga la ventana del explorador de archivos