Divide a number into n parts by percentage

Trying to come up with a function to correctly split a given number into n parts, with each part split by percentage.

Let’s say I need to split 12 into 3 parts. The first part should be 50% of 6, second 30% of 6 and third 20% of 6. With rounding, this would result in:
[6,5,2] totalling 13.

Is there a way to run this calculation so it can correctly split 12 into 3 parts by the %, whereby it reduces the last item in the array by 1, then the second to last item in the array by 1 and so on until all 3 numbers total 12? In the example above, the end result would be [6,5,1].

Trying to avoid calculating the 3 parts individually then calculating the difference to manually reduce each, so attempting to work out a function to handle it.

Reactjs mui spacing Stack and Grid

I used Stack, Divider Box and Grid, I am having trouble when spacing, please see the result below

<Stack direction="row"  spacing={1}>
  <Divider>
     <Box py={3} sx={{width: '100%', border: 1}}>
          <Stack
            direction="row"
            justifyContent="flex-end"
            alignItems="center"
            spacing={3}
            sx={{ marginBottom: '9px', width: 150 }}
          >

           <Grid container spacing={3} sx={{float: 'right'}} justify="flex-end">
                <Grid item xs sx={{float: 'right'}}>
                <LocalFireDepartmentIcon
                color={selectedThreat ? '#E01C1C' : 'disable'}
              />
                <Typography
                variant="subtitle2"
                sx={{ letterSpacing: '1.5px', marginLeft: '4px' }}
                className={classes.upperCase}
              >
                {name}
              </Typography>
                </Grid>
                <Grid item xs sx={{float: 'right'}}>
                <Typography
                variant="p"
                sx={{ letterSpacing: '1.5px', textDecoration: "underline", color: '#191F25', fontSize: '14px', lineHeight: '20px'  }}
                onClick={handleOpen}
              >
                Cancel
              </Typography>
                </Grid>
            </Grid>

          </Stack>
     </Box>
  </Divider>
</Stack>

Expected Result

enter image description here

current result

enter image description here

Don’t read this comment, I did this because I can submit question,
Don’t read this comment, I did this because I can submit question,
Don’t read this comment, I did this because I can submit question,
Don’t read this comment, I did this because I can submit question,

How running JavaScript function in order?

What am I doing?
I’m try running two function in order but JavaScript is calling and running two function in same time.

What’s the problem?
The setModalBox function give undefined error if is called before setProjects function.

What have I already tried?
I tried used Promise with setTimeout it work, but can sometimes setModalBox function be called before and give of same error.

Part of JavaScript:

  init() {
    this.setProjects();
    // this.setModalBox();
  }

  setProjects() {
    let response_promise = fetch("contents/projects.json")

    document.addEventListener("DOMContentLoaded", function() {
      response_promise.then(response => response.json().then(projects => {
        // ? Gradient in border for each color language

        for(let project in projects){
          // Div project
          var div = document.createElement("div");
          div.className = "project";
          div.id = `project-${projects[project].name}`
          document.querySelector(".projects").appendChild(div);

          // Tittle project
          var h1 = document.createElement("h1");
          h1.className = "tittle-project";
          h1.innerHTML = projects[project].name;
          document.querySelector(`#project-${projects[project].name}`).appendChild(h1);

          // Paragraph project
          var p = document.createElement("p");
          p.className = "about-project";
          p.innerHTML = projects[project].about;
          document.querySelector(`#project-${projects[project].name}`).appendChild(p);
        }
      }))
    }, false)

    return new Promise((resolve, reject)=>{
      setTimeout(()=>{
        this.setModalBox()
      }, Math.random() * 2000)
    })
  };

  setModalBox(){
    let projectsLength = document.querySelectorAll(".projects")[0].children.length;
    let modalBox = this.modalBox;

    for(let i = 0; i <= projectsLength; i++){
      let projectsAll = document.querySelectorAll(".projects")[0].children[i];

      // That "try" is for not to show error in console
      try{
        // Open Modal Box
        projectsAll.onclick = function(){
          modalBox.style.display = "block"
        };
      }catch{}

      // Close Modal Box, when click at "X"
      this.modalBoxClose.onclick = function(){
        modalBox.style.display = "None"
      };

      // Close Modal Box, when click out of Modal Box
      window.onclick = function(){
        if(event.target == modalBox){
          modalBox.style.display = "None"
        }
      }

      // Close Modal Box, when press esc key
      document.addEventListener("keydown", function(event){
        if(event.key == "Escape"){
          modalBox.style.display = "None"
        }
      })
    }
  }

HTML:

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Projetos - Vitor Hugo's Portifolio</title>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>

  <body>
    <header>
      <div id="wrapperJS" style="position: relative; overflow: hidden">
      <nav>
        <a class="logo" href="/">Vitor Hugo</a>
        <div class="mobile-menu">
          <div class="line-1"></div>
          <div class="line-2"></div>
          <div class="line-3"></div>
        </div>
          <ul class="nav-list">
            <li><a href="index.html">Home</a></li>
            <li><a href="sobre.html">Sobre</a></li>
            <li><a href="projetos.html">Projetos</a></li>
            <li><a href="contatos.html">Contato</a></li>
          </ul>
        </nav>
      </div>
    </header>
    <script src="mobile-screen.js"></script>

    <!-- Boxes -->
    <div class="projects"></div>

    <!-- Modal Boxes -->
    <div class="modal-box">
      <div class="modal-box-contents">
        <span class="modal-box-close">&times;</span>
        <p>test</p>
      </div>
    </div>
  </body>
</html>

What I have to do? please help me. If need more information,ask. And sorry for any error orthography and grammar I am studing English.

Renaming ID of all child elements after dynamically deleting line in table

I created a form in Google Apps Script, to send data to a sheet, but I wanted a way to dynamically add rows by clicking a button. I found this article (https://www.geeksforgeeks.org/how-to-dynamically-add-remove-table-rows-using-jquery/) that uses jquery that works well great, even shows how to delete a line, whilst also renaming the <tr> tag id to the correct number as well as the text content of the first <td> tag.

However, I added an autocomplete input using materialize, and thought I could use the same method to change the <input> ID when deleting a row, but, seem to be failing miserably.

To see what I’m talking about, I’d invite you to run the code snippit, and add a few rows. If you delete any of the rows (apart from the last one), then all the Row numbers go down by one, the <tr> tag ids go down by one, but the <input> tag ids don’t.

I apologize if my query isn’t clear, and would be happy to try and explain more, if needed.

Here is all the code to recreate the project in a “normal” code editor :

JS in first snippit, html in second

let rowIdx = 1;

//This list would be generated from a google sheet on page load for the autocomplete input
let listRecettes = {
  "Banana": null,
  "Orange": null,
  "Mango": null,
}

//ON LOAD  
document.addEventListener('DOMContentLoaded', function() {

  var elems = document.querySelectorAll('.autocomplete');
  var instances = M.Autocomplete.init(elems);

  // Load words into autocomplete
  populateWordsRecettes();
});


//Autocomplete initialize
function populateWordsRecettes() {
  var autocomplete = document.getElementById("recettes1");
  var instances = M.Autocomplete.init(autocomplete, {
    data: listRecettes
  });
}

//autocomplete initialize for added rows
function newLineAutocomplete() {
  var autocomplete = document.getElementById(`recettes${rowIdx}`);
  var instances = M.Autocomplete.init(autocomplete, {
    data: listRecettes
  });
  console.log(`Row ${rowIdx} initialized`);
}

document.getElementById('btnAjouterLigne').addEventListener('click', addLine);

function addLine() {
  // jQuery button click event to add a row.
  // Adding a row inside the tbody.
  $('#tableBodyCasse').append(`<tr id="R${++rowIdx}">
          <td class = "row-index">Row ${rowIdx}</td>
          <td><div class = "input-field"><input type="text" id="recettes${rowIdx}" class="autocomplete"></div></td>
          <td>Lorum Ipsum</td>
          <td>Lorum Ipsum</td>
          <td>Lorum Ipsum</td>
          <td><button class="btn waves-effect red darken-4 waves-light btnSupprimerLigne">Delete</button></td>
           </tr>`);

  //Initialize the autocomplete for new row
  newLineAutocomplete();
}


//delete line
$('#tableBodyCasse').on('click', '.btnSupprimerLigne', function() {

  // Getting all the rows next to the 
  // row containing the clicked button
  let child = $(this).closest('tr').nextAll();

  // Iterating across all the rows 
  // obtained to change the index
  child.each(function() {

    // Getting <tr> id.
    let id = $(this).attr('id');

    // Getting the <p> inside the .row-index class.
    let idx = $(this).children('.row-index');

    // Gets the row number from <tr> id.
    let dig = parseInt(id.substring(1));

    // Modifying row index.
    idx.html(`Row ${dig - 1}`);

    // Modifying row id.
    $(this).attr('id', `R${dig - 1}`);
  });



  //MY PROBLEM STARTS HERE
  let childInput = $(this).find('input').nextAll();
  childInput.each(function() {
    let idInput = $(this).attr('id');
    let digInput = parseInt(idInput.substring(9));
    console.log(digInput);
    $(this).attr('id', `recettes${digInput - 1}`);
  });

  // Removing the current row.
  $(this).closest('tr').remove();

  // Decreasing the total number of rows by 1.
  rowIdx--;
});
<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
  </script>

</head>

<body>

  <div class="container">
    <!-- CONTAINER START -->
    <table class="striped">
      <thead>
        <tr>
          <th>Row num</th>
          <th>Product</th>
          <th>Type</th>
          <th>Qty</th>
          <th>Total</th>
          <th>Delete line</th>
        </tr>
      </thead>

      <tbody id="tableBodyCasse">
        <tr id="R1">
          <td class="row-index">Row 1</td>
          <td>
            <div class="input-field"><input type="text" id="recettes1" class="autocomplete"></div>
          </td>
          <td>unknown</td>
          <td>2</td>
          <td>5,4</td>
          <td><button class="btn waves-effect red darken-4 waves-light btnSupprimerLigne">Delete</button>
          </td>
        </tr>
      </tbody>
    </table>

    <button class="btn waves-effect waves-light" id="btnAjouterLigne">Add line
    <i class="material-icons left">add_circle_outline</i>
  </button>


  </div>
  <!--CONTAINER END -->






  <?!= include("page-casse-js"); ?>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>

</html>

Cant write more than one letter in TextInput

Im unable to write more than one letter in the text input.

I have tried to run after clearing the cache expo r -c

Does anyone has any idea why is this happening and how to fix it.

Running with

“expo”: “^44.0.5”,
“react”: “17.0.1”,
“react-dom”: “17.0.1”,
“react-native”: “0.64.3”,

const Posts = () => {

    const isDarkMode = useColorScheme() === 'dark'

    const [search, setSearch] = useState('')
    const [refresh, setRefresh] = useState(false);

    const handleOnEndReach = () => {

    }

    const handleRefresh = () => {
        setRefresh(true)
        setTimeout(() => {
            setRefresh(false)
        }, 3000)
    }

    return (
        <TouchableWithoutFeedback
            onPress={() => Keyboard.dismiss()}
            style={{flex: 1, backgroundColor: isDarkMode ? colors.dark.background : colors.light.background}}
        >
            <FlatList
                ListHeaderComponent={() => 
                    <TextInput
                        value={search}
                        onChangeText={setSearch}
                        style={{padding: '2.5%'}}
                        keyboardAppearance={isDarkMode ? 'dark' : 'light'}
                        placeholder='Search...'
                        
                    />
                }
                style={{padding: '2.5%'}}
                onEndReached={handleOnEndReach}
                onEndReachedThreshold={0.5}
                refreshControl={
                    <RefreshControl refreshing={refresh} onRefresh={handleRefresh} tintColor={isDarkMode ? 'white' : 'black'}/>
                }
            />
        </TouchableWithoutFeedback>
    )
}

Import/Export in VSCode Javascript for React

I’m following a tutorial on React course.

Currently, I’m trying to make a react info website. I’m trying to import a component of react but it does not load on the ‘live’ website. (I have a live server extension added on VSCode)

Code:

HTML:

<html>
    <head>
        <link rel="stylesheet" href="index.css">
        <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
        <script crossorigin src=
        "https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    </head>
    <body>
        
        <div id="root"></div>
        <div id="root2"></div>
        <script src="index.js" type="text/babel"></script>
    </body>
</html>

JavaScript:

import { Header } from './Header'

function Page() {
    return (
        <div>
            <Header />
            <MainContent />
            <Footer />
        </div>
    )
}

function MainContent() {
    return ( Listed info in HTML format
 )}

function Footer() {
    return (footer tag in HTML format
    )
}

ReactDOM.render(<Page />, document.getElementById("root"))

React/Javascript component:

export function Header() {
    return (
        <header>
            <nav className="nav">
                <img className="nav-logo" src="../React info web/images/react_logo.png" />
                <ul className="nav-items">
                    <li>Pricing </li>
                    <li>About</li>
                    <li>Contact</li>
                </ul>
            </nav>
        </header>
    )
}

I’ve noticed that when I remove ‘import’ and ” in ‘Javascript’. The website loads up perfectly.
I’m utterly confused and need assistance. I tried combing through the documentation and
still can’t figure out what wrong

What type of function is this?

const xhr = new XMLHttpRequest(),
    method = "GET",
    url = "https://developer.mozilla.org/";

xhr.open(method, url, true);
xhr.onreadystatechange = function () {
  // In local files, status is 0 upon success in Mozilla Firefox
  if(xhr.readyState === XMLHttpRequest.DONE) {
    var status = xhr.status;
    if (status === 0 || (status >= 200 && status < 400)) {
      // The request has been completed successfully
      console.log(xhr.responseText);
    } else {
      // Oh no! There has been an error with the request!
    }
  }
};
xhr.send();

This code represent an XHR request and response. I was watching a tutorial on AJAX and xhr.onreadystatechange was described as an object property. I know that function expressions are anonymous functions assigned to variables but what about anonymous functions assigned to object properties. What is the name of this kind of function that is called when an object property updates? This hasn’t really been taught in basic javascript or ES6 from what I can see.

Converting Three.js function from a sphere to a torus

This function listed below shows a sphere of starbursts. I cant seem to figure out how to make this same function but generate a torus of starbursts instead of a sphere.
The parameters would include the toroids major and minor radii.

Here is what the final outcome should look like:
Final outcome

let camera, scene, renderer;
let cameraControls;
let clock = new THREE.Clock();
let root = null, sphereRadius;



function createSceneA() {
    sphereRadius = 15;
    root = starburstsOnSphereA(400, sphereRadius, 100, 1)
    scene.add(root);
}


function starburstsOnSphereA(nbrBursts, sphereRadius, maxRays, maxRad) {
    let root = new THREE.Object3D();
    for (let i = 0; i < nbrBursts; i++) {
        let mesh = starburstA(maxRays, maxRad);
        let p = getRandomPointOnSphere(sphereRadius);
        mesh.position.set(p.x, p.y, p.z);
        root.add(mesh);
    }
    return root;
}

function starburstA(maxRays, maxRad) {
    let rad = 1;   // had been rad = 10?????
    let origin = new THREE.Vector3(0, 0, 0);
    let innerColor = getRandomColor(0.8, 0.1, 0.8);
    let black = new THREE.Color(0x000000);
    let geom = new THREE.Geometry();
    let nbrRays = getRandomInt(1, maxRays);
    for (let i = 0; i < nbrRays; i++) {
        let r = rad * getRandomFloat(0.1, maxRad);
        let dest = getRandomPointOnSphere(r);
        geom.vertices.push(origin, dest);
        geom.colors.push(innerColor, black);
    }
    let args = {vertexColors: true, linewidth: 2};
    let mat = new THREE.LineBasicMaterial(args);
    return new THREE.Line(geom, mat, THREE.LineSegments);
}




function animate() {
    window.requestAnimationFrame(animate);
    render();
}

let controls = new function() {
    this.nbrBursts = 400;
    this.burstRadius = 1.0;
    this.maxRays = 100;
    this.Go = update;
}

function initGui() {
    let gui = new dat.GUI();
    gui.add(controls, 'nbrBursts', 5, 2000).step(5).name('Nbr of bursts');
    gui.add(controls, 'burstRadius', 0.1, 5.0).name('Burst radius');
    gui.add(controls, 'maxRays', 5, 200).name('Max nbr of rays');
    gui.add(controls, 'Go');
}

function update() {
    let nbrBursts = controls.nbrBursts;
    let burstRadius = controls.burstRadius;
    let maxRays = controls.maxRays;
    if (root)
        scene.remove(root);
    root = starburstsOnSphereA(nbrBursts, sphereRadius, maxRays, burstRadius);
    scene.add(root);
}



function render() {
    let delta = clock.getDelta();
    cameraControls.update(delta);
    renderer.render(scene, camera);
}


function init() {
    let canvasWidth = window.innerWidth;
    let canvasHeight = window.innerHeight;
    let canvasRatio = canvasWidth / canvasHeight;

    scene = new THREE.Scene();

    renderer = new THREE.WebGLRenderer({antialias : true, preserveDrawingBuffer: true});
    renderer.gammaInput = true;
    renderer.gammaOutput = true;
    renderer.setSize(canvasWidth, canvasHeight);
    renderer.setClearColor(0x000000, 1.0);

    camera = new THREE.PerspectiveCamera( 40, canvasRatio, 1, 1000);
    camera.position.set(0, 0, 40);
    camera.lookAt(new THREE.Vector3(0, 0, 0));
    cameraControls = new THREE.OrbitControls(camera, renderer.domElement);

}


function addToDOM() {
    let container = document.getElementById('container');
    let canvas = container.getElementsByTagName('canvas');
    if (canvas.length>0) {
        container.removeChild(canvas[0]);
    }
    container.appendChild( renderer.domElement );
}



init();
createSceneA();
initGui();
addToDOM();
animate();
function getRandomPointOnSphere(rad) {
  rad = rad || 1.0;
  var theta = Math.random() * 2 * Math.PI;
  var phi = Math.acos(2 * Math.random() - 1);
  var x = rad * Math.cos(theta) * Math.sin(phi);
  var y = rad * Math.sin(theta) * Math.sin(phi);
  var z = rad * Math.cos(phi);
  return new THREE.Vector3(x, y, z);
}

Using the older version of three js: Three.js code

JavaScript ListItem onClick issue

I’m working on a web-app in HTML and JS and I need to catch the clicks on each listItem of a list.
The list is dynamically created in a for-loop as follows:

var i = document.createElement("li");
i.innerHTML = "something"
uList.appendChild(i);

How can I make listItems clickable or catch clicks on each of them separately (get the specific item clicked)?
I’ve tried adding an eventListener on the list, and then isolate the target of the event (click). The problem is that this would count as many clicks as the size of the list.

How to set up conditionals in setup function in Vue 3 Composition API

I am attempting to build a basic Vue 3 app with composition API that enables the user to guess an audible musical note by selecting buttons displaying 4 randomly shuffled musical notes from a selection of 7 notes (A,B,C,D,E,F,G). The first part of the setup function, under // Handle Audio passes 7 musical notes (imported as mp3 clips in assets) into an array called audioArray. The notes in audioArray are then shuffled in shuffleAudio, then passed to audio.value. The audio is played when the user clicks “click for audio”, and reshuffled with the onBeforeMount life cycle hook. Meanwhile, under // handleLetters, each of the four buttons are configured to display a letter corresponding to a musical note, which are shuffled when shuffleLetter is called by onBeforeMount.

I am now trying to get the buttons to trigger “correct” and “incorrect” messages when the user selects either the correct or incorrect note. To do this, I tried setting up the buttons with click events (ex. handleSelectOne, handleSelectTwo…etc.). For example, in handleSelectOne, if the button note displayed is “A” and the musical note playing is noteA, then the message displayed is ‘CORRECT’ when the user taps the “A” button, else ‘INCORRECT’. However, I tried putting a breakpoint on handleSelectOne, but the event isn’t triggered upon selecting A when noteA is played. Meanwhile, I am not sure if my conditional is setup correctly. How can I set up the logic in handleSelectOne to respond correctly if the button letter is A and corresponds to the note being played?

Here is my code so far:

template

<template>
  <div div class="flex justify-center">
    <button @click="handleAudio">Click for Audio</button>
  </div>
  <div class="flex justify-center">
    <button @click="handleSelectOne">{{ letters.letterDisplayOne }}</button>
    <button @click="handleSelectTwo">{{ letters.letterDisplayTwo }}</button>
    <button @click="handleSelectThree">{{ letters.letterDisplayThree }}</button>
    <button @click="handleSelectFour">{{ letters.letterDisplayFour }}</button>
    <button @click="handleSelectNone">None</button>
  </div>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

script

<script>
import { ref, reactive, onBeforeMount } from 'vue';
const noteA = require("../assets/note-a.mp3")
const noteB = require("../assets/note-b.mp3")
const noteC = require("../assets/note-c.mp3")
const noteD = require("../assets/note-d.mp3")
const noteE = require("../assets/note-e.mp3")
const noteF = require("../assets/note-f.mp3")
const noteG = require("../assets/note-g.mp3")

export default {
  name: 'Button',
  components: {},
  setup() {

// Handle Audio
    const audioArray = ref([noteA, noteB, noteC, noteD, noteE, noteF, noteG])
    const audio = ref(audioArray.value)

    const shuffleAudio = () => {
      audioArray.value = audioArray.value.sort(() => 0.5 - Math.random())
    }
    
    const handleAudio = () => {
      audio.value = new Audio(audioArray.value[0]);
      audio.value.play()
      console.log(audioArray.value)
    }

// Handle Letters
    const letters = reactive({
      letterDisplayOne: '',
      letterDisplayTwo: '',
      letterDisplayThree: '',
      letterDisplayFour: ''
    })

    const letterArray = ref(['A','B','C','D','E','F','G'])

    const shuffleLetter = () => {
      letterArray.value = letterArray.value.sort(() => 0.5 - Math.random())
    }

    const handleLetterArray = () => {
      letters.letterDisplayOne = letterArray.value[0]
      letters.letterDisplayTwo = letterArray.value[1]
      letters.letterDisplayThree = letterArray.value[2]
      letters.letterDisplayFour = letterArray.value[3]
    }

// Handle message
    const message = ref('')

    const handleSelectOne = () => {
      if (letters.letterDisplayOne === 'A' && audio.value === audioArray.value[noteA]) {
        message.value = 'CORRECT!!!!'
      } else {
        message.value = 'INCORRECT!!!!'
      }
    }

    const handleSelectTwo = () => {
      // functionality for handleSelectTwo
    }

    const handleSelectThree = () => {
      // functionality for handleSelectThree
    }

    const handleSelectFour = () => {
      // functionality for handleSelectFour
    }

    const handleSelectNone = () => {
      // functionality for handleSelectNone
    }

    onBeforeMount(() => {
      shuffleAudio()
      shuffleLetter()
      handleLetterArray()
    })

    return {
      audioArray,
      shuffleAudio,
      audio,
      handleAudio,
      letters,
      letterArray,
      shuffleLetter,
      handleLetterArray,
      message,
      handleSelectOne,
      handleSelectTwo,
      handleSelectThree,
      handleSelectFour,
      handleSelectNone
    }
  }
}

I want help in adding an event listener

I’m a django developer not good at javascript. I have a django template i really want to use Javascript for. i tried reading online for help but i’m not understanding

I want to add an addEventlistener to this code below

<div class="box-element hidden" id="request-info">
        <button id="send-payment">Send request</button>

Also, I want it to display a response when submitted. Response like “Request sent”. Please I know about console.log, I don’t want it in console.log.

I know JS is really good at this.

Change Angular base href with ngx-translate

I have already implemented ngx-translate succesfully. Now, I want to change the base href of my Angular project, depending on the language I choose from my header menu.

Currently, my URL looks like this: “localhost:4200”. Then, when you launch the project, it must show something like this: “localhost:4200/en” or like this: “localhost:4200/es”, depending on the choosen language.

My index html has this:

<base href="/"/>

And my header component ts file has a function that changes the language using ngx-translate. As you can see, I tried to use ‘replaceState’ to show the choosen language in the URL, and it worked, but it disappears once I navigate to another route.


import { Component, OnInit } from '@angular/core';
//For translate language
import { TranslateService } from '@ngx-translate/core'; 
import { Router, Event, NavigationStart, NavigationEnd } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {


  constructor(private translate: TranslateService,
              private router: Router,
              private location: Location,
              ) 
    { translate.addLangs(['es','en']);
      translate.setDefaultLang('es'); 
    }

  ngOnInit(): void {



  }


  useLanguage(language: string): void {
    this.translate.use(language); 
    // alert(language);

    // location.replace("https://www.google.com");
    // return;


    const modified_path = language;
    this.location.replaceState(modified_path);

  } 
 

}



Disabling jQuery animations for mobile only

I’m trying to disable the scrollTo animation in jQuery for mobile only. I have looked on Stackoverflow and none of the solutions have worked for me thusfar. Some of them point to this link but it didn’t help me.

I have the following code which is used to detect whether or not the user is on a mobile device but I’m not sure how to proceed after that. It’s likely staring at me in the face and I just don’t see it. I tried simply writing an if else statement within my function(gotodiv) but it didn’t work.


 (function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bbd+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

Here is my jQuery if it helps:

$(document).ready(function(gotodiv) {
    function gotodiv(){
            $('html, body').animate({
                scrollTop: $("#divscr").offset().top
            }, 6000); 

    }

    window.setTimeout( gotodiv, 45000 ); //Time in milliseconds
   
});

error Command failed with exit code 134 web3 dapp react website

i’m a starter on reactjs / web3 / dapp coding, i started for one of my project and i got and issue that i can’t resolve it, i’m trying to make a website for mint some nft, i added react-helmet for try to add a title to my website and since that i got many error, i resolve some of them but now i got that and i dont know how i can resolve it

Command failed with exit code 134: npm run generate i tried this and it didn’t work !

<--- Last few GCs --->

[14260:000002D98912B060]   106202 ms: Mark-sweep 1965.7 (2094.4) -> 1965.7 (2094.4) MB, 1661.6 / 0.0 ms  (average mu = 0.115, current mu = 0.008) allocation failure scavenge might not succeed
[14260:000002D98912B060]   107977 ms: Mark-sweep 1966.8 (2095.6) -> 1966.8 (2095.6) MB, 1765.9 / 0.0 ms  (average mu = 0.063, current mu = 0.005) allocation failure scavenge might not succeed


<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF70241401F v8::internal::CodeObjectRegistry::~CodeObjectRegistry+112511
 2: 00007FF7023A3146 DSA_meth_get_flags+65542
 3: 00007FF7023A3FFD node::OnFatalError+301
 4: 00007FF702CD5ADE v8::Isolate::ReportExternalAllocationLimitReached+94
 5: 00007FF702CC000D v8::SharedArrayBuffer::Externalize+781
 6: 00007FF702B635FC v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1468
 7: 00007FF702B702A9 v8::internal::Heap::PublishPendingAllocations+1129
 8: 00007FF702B6D27A v8::internal::Heap::PageFlagsAreConsistent+2842
 9: 00007FF702B5FEF9 v8::internal::Heap::CollectGarbage+2137
10: 00007FF702B5E0B0 v8::internal::Heap::AllocateExternalBackingStore+2000
11: 00007FF702B7BD20 v8::internal::FreeListManyCached::Reset+1408
12: 00007FF702B7C3D5 v8::internal::Factory::AllocateRaw+37
13: 00007FF702B8E0CE v8::internal::FactoryBase<v8::internal::Factory>::AllocateRawArray+46
14: 00007FF702B90D2A v8::internal::FactoryBase<v8::internal::Factory>::NewFixedArrayWithFiller+74
15: 00007FF702B90F83 v8::internal::FactoryBase<v8::internal::Factory>::NewFixedArrayWithMap+35
16: 00007FF702999E5E v8::internal::HashTable<v8::internal::NumberDictionary,v8::internal::NumberDictionaryShape>::New<v8::internal::Isolate>+110
17: 00007FF702C8EFA0 v8::internal::Builtins::code_handle+167152
18: 00007FF702C8AEDD v8::internal::Builtins::code_handle+150573
19: 00007FF702C8A9C0 v8::internal::Builtins::code_handle+149264
20: 00007FF702D635B1 v8::internal::SetupIsolateDelegate::SetupHeap+494673
21: 000002D98B888789
error Command failed with exit code 134.

That’s my index.js :

import { useWeb3React } from "@web3-react/core"
import { injected } from "../components/wallet/connectors"
import 'bootstrap/dist/css/bootstrap.css'
import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
            </Helmet>
            ...
        </div>
    );
  }
};


export default function Home() {

  const { active, account, library, connector, activate, deactivate } = useWeb3React()
  
  async function connect() {
    try {
      await activate(injected)
    } catch (ex) {
      console.log(ex)
    }
  }

  async function disconnect() {
    try {
      deactivate()
    } catch (ex) {
      console.log(ex)
    }
  }
  
  return (
    <div className="container-fluid"> 
      <div className="row">
        <div className="col">
          
        </div>
        <div className="col-6">
          <h1 className="text-center title">ANGRY SHARKS</h1>
        </div>
        <div className="col text-end">
          {active ? <button onClick={disconnect} className="btn btn-outline-light connextion">Disconnect</button> : 
            <button onClick={connect} className="btn btn-outline-light connextion">Connect to metamask</button>}
        </div>
        <div className="container-fluid square-box d-flex justify-content-center align-items-center">
          <button type="button" className="btn btn-outline-light btn-lg" data-bs-toggle="button">MINT</button>
        </div>
      </div>
    </div>
  )
}

thanks for people who will help me i’m not very good in reactjs and web3 dapp coding

Place download request in one tab but complete in another

A web app opens new tab and places a POST request to the server to create a file for a download. Here is the code that sends the file back:

Response.AppendHeader("content-disposition", "attachment; filename=name");
Response.ContentType = "application/octet-stream";
Response.WriteFile(zipPath);
Response.Flush();
Response.End();

What can happen is that the user can close the new tab and no download would take a place. Is there any chance that the app would still get the file? I understand that placing request in the app is the way to go, but I am dealing with existing architecture.

Thanks for help.