Is it possible to share one view between two models in ExtJs?

Is it possible to share one view between two models? I have a panel with many identical components. Each of them has three numberField controls (new value, current and past), its own controller and viewmodel. But I also have a parent model. Can I use standard extjs tools to bind two models (parent and child) with different property names to one control?

// view pseudocode

{
    xtype: 'panel',
    
    controller: 'parentController',
    viewModel:{
        id: 'parent',
        type: 'parent'
    },
    
    items:[{
        xtype: 'panel',
        
        controller: 'childController',
        viewModel:{
            id: 'child_1',
            type: 'child'
        },
        
        items:[{
            xtype: 'numberfield', 
            minValue: 0,
            bind: '{child_1}',
        },{
            xtype: 'numberfield', 
            minValue: 0,
            bind: '{child_2}',
        }]
    }]
}

// parent viewModel pseudocode

{
    data: {
        child_1_1: 0,
        child_1_2: 0
    }
}

// child viewModel pseudocode

{
    data: {
        child_1: 0,
        child_2: 0
    }
}

// need child_1_1 <-> child_1 and child_1_2 <-> child_2

I want something similar to this. I would like to be able to both assign and read both models and get the same values, as well as declaratively bind methods to value change events.

Getting text inside of a search input and give a variable the text value in javascript

Basically, there is an input tag that has the id bar, and it’s a search input.

<input id="bar" type="search">

and I tried to get the value of that input with jQuery.

var query = document.getElementById("bar");

And it opens a new tab that searches whatever you typed into the search bar into google. But it doesn’t get the text, it just says ‘undefined’. And no, I typed stuff.

Repl

How i get the params id from url using server side components in nextjs?

I’m trying to fetch an API but it’s only working on the server side, so I need my component to be server-side, but all the hooks I found to get the url id are client side, is there one that allows it?

I’ve already tried useSearchParams, useRouter and nothing, here’s the component I’m trying to run.

import FerramentaCard from '@/components/ferramentas/ferramenta';

export default async function Ferramenta() {
  const response = await fetch(`https://gameinfo.albiononline.com/api/gameinfo/items/${query.id}/data`, { method: 'GET', mode: 'no-cors' });
  const ferramentaInfo = await response.json();

  return <FerramentaCard ferramentaInfo={ferramentaInfo} />;
}

I would like to create a visual effect for when each attack happens in this JS code

doAttack(attacking, attacked) {
        if(attacking.life <= 0 || attacked.life <=0 ) {
            log.addMessage('O inimigo está morto.');
            return;
        }
        const attackFactor = (Math.random(2) * 2).toFixed(2);
        const defenseFactor = (Math.random(2) * 2).toFixed(2);

        const actualAttack = attacking.attack * attackFactor;
        const actualDefense = attacked.defense * defenseFactor;

        if(actualAttack > actualDefense) {
            attacked.life -= actualAttack;
            attacked.life = attacked.life < 0 ? 0 : attacked.life;

            log.addMessage(`${attacking.name} causou ${actualAttack.toFixed(2)} de dano em ${attacked.name}`)
        } else {
            log.addMessage(`${attacked.name} conseguiu dar parry.`)
        }

        this.checkBattleEnd();
        this.update();
    },

I tried this, but each time I added any code in the doAttack method the attacks stopped working, I was expecting that with the creation of perfomVisualEffect and adding him inside the doAttack method the flash effect should work. I’m new at JS and trying to learn, the first step was to create a battle simulation, and worked fine, now I’m looking to improve the simulation with visual effects.

doAttack(attacking, attacked) {
    if (attacking.life <= 0 || attacked.life <= 0) {
        log.addMessage('O inimigo está morto.');
        return;
    }

    const attackFactor = Math.random() * 2;
    const defenseFactor = Math.random() * 2;

    const actualAttack = attacking.attack * attackFactor;
    const actualDefense = attacked.defense * defenseFactor;

    if (actualAttack > actualDefense) {
        attacked.life -= actualAttack;
        attacked.life = Math.max(attacked.life, 0);

        this.performVisualEffect(attacked);
        
        log.addMessage(`${attacking.name} causou ${actualAttack.toFixed(2)} de dano em ${attacked.name}`);
    } else {
        log.addMessage(`${attacked.name} conseguiu dar parry.`);
        this.update();
    }

    this.checkBattleEnd();
}

performVisualEffect(character) {
    const attackedEl = this.getFighterElement(character);

    // Add the 'attacked' class to trigger the visual effect
    attackedEl.classList.add('attacked');

    // Listen for the 'transitionend' event to ensure the visual effect is complete
    attackedEl.addEventListener('transitionend', () => {
        attackedEl.classList.remove('attacked');
        this.update();
    }, { once: true }); // Use { once: true } to remove the listener after it's triggered
}

Cannot resolve old react version

I have an old react template which I want to update. I get this error:

npm update                   
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^18.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.2.0 || ^17.0.0" from [email protected]
npm ERR! node_modules/react-modal-video
npm ERR!   react-modal-video@"^1.2.9" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:

Do you know how I can fix this?

Retrieving users data from websites [closed]

There is a language practice site that I use, and every user there has an id, for example (id: 50a56k097). And someone there retrieved the user data and knew the previous usernames of these ids if they changed them. My question is, how can I do this? How can I extract user data from this site easily?I’ve heard about webscraper but dont know how to use it

or is there any script to do that ?

I tried everything to do that but couldnt find the way

Como reestabelecer conexão com SSE mesmo após atualizar a página? [closed]

Olá, pessoal! Criei uma página HTML para a exibição de pedidos atualizados sem a necessidade de recarregamento total da página. Minha API foi desenvolvida em Python (Flask) e para a comunicação servidor-cliente estou utilizando o SSE.

A página está inserindo corretamente os dados via javascript, mas caso a página seja atualizada o conteúdo da div some e só retorna se o serviço da API for reiniciado, quando consulto o console do navegador ele mostra que a conexão com o servidor sse está pendente, quando deveria retornar 200.

Como posso fazer para que mesmo atualizando a página ela volte a estabelecer conexão com o servidor SSE?

Uncaught TypeError Failed to set the ‘voice’ property on ‘SpeechSynthesisUtterance’: Failed to convert value to ‘SpeechSynthesisVoice’

How can I change voice value of speechSynthesisUtteranceObject to other value like number or string without getting this error?

SpeechSynthesisUtterance Object:
 SpeechSynthesisUtterance {text: 'hi', lang: '', voice: null, volume: 1, rate: 1, …}
    

 html.html:49  Uncaught TypeError: Failed to set the 'voice' property on 'SpeechSynthesisUtterance': Failed to convert value to 'SpeechSynthesisVoice'.
    at HTMLSelectElement.changeSpeaker

When I changed value of speechSynthesisUtterance.voice it returned me error

Laravel blade.php file can’t execute linked javascript code

I have been trying to execute javascript code from my blade.php file, and it doesnt recognize the function that I want

I have this select

<div class="row mb-3">
          <div class="col">
            <form id="filter">
              <div class="form-group">
                <label for="statusFilter">Filtro por Estado</label>
                <select onChange="filter()" class="form-control" id="statusFilter">
                  <option value="Todos">Todos</option>
                  <option value="Pendiente">Pendiente</option>
                  <option value="Aceptada">Aceptada</option>
                  <option value="Rechazada">Rechazada</option>
                </select>
              </div>
            </form>
          </div>
        </div>

As you can see, when it changes it should trigger the filter function wich is

function filter(){
  console.log("HOLAAAAA");
}

But instead of the console log, I get

absences:49 Uncaught TypeError: filter is not a function
    at HTMLSelectElement.onchange (absences:49:84)

On the php file i’m importing the js file called absences.js like this

<script src="{{ asset('js/absences.js') }}"></script>

I tried calling it like this on the layout that I made

<script src="/js/absences.js"></script>

but it won’t work either.
It’s worth noticing that when I go to the route of the app (I’m working with Laragon) wich is http://justifacil.test/js/absences.js it returns all the code of the js file, so I assume that is correct and the app can retrieve the code but it wont execute on the on change event.

Event Listener is not calling function

I have an HTML/CSS file with a form and I’m trying to add an event listener to the button of the form.
The HTML looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    ... all css files here
</head>


<body class="registrationFormBody"> 
    <section class="sectionForms">

        <div class="serviceProviderRegistrationFormDiv">
            <form class="serviceProviderRegistrationForm">
                .... labels and inputs
                <button id="verifyProviderAddress" type="button" value="ProviderAddress">Verify</button>
            </form>
        </div>
    </section>
</body>
<script type="module" src="publicjsGeocode.js"></script>
</html>

I also have my Geocode file that correctly selects the button:

let buttonVerifyProviderAddress = document.getElementById("verifyProviderAddress");

buttonVerifyProviderAddress.addEventListener("click", () => onClickVerifyAddress());

function onClickVerifyAddress()
{
    window.alert("I'm in");
    console.log("Verifying");
}

I checked on the debugger, the event listener is there:

enter image description here

But it’s not calling it. When I click nothing happens. No console.log, no window alert.
What am I doing wrong?

I’ve tried already change the way of adding the listener:

buttonVerifyProviderAddress.addEventListener("click",()=>{console.log("Hey")});
buttonVerifyProviderAddress.onclick = ()=>{console.log("Ola");};

But nothing happens.
I think something is preventing the event listener to actually call, but what? Does anyone have a clue?

Problems with Responsiveness

I did in my project accessibility button but I have problem with the Responsiveness of the Button. I can’t see the menu in screens untill the size 1300px and and even then there is a problem ‘cuz the the menu became bigger the bigger the screen. What can I do the solve this?

Here’s the code of the menu:

import React, { useState } from "react";
import "../../../css/AccessibilityMenu.css";

const AccessibilityMenu = ({
  style,
  onToggleDarkMode,
  onToggleTextOnly,
  onToggleAnimations,
  onToggleLinkHighlight,
}) => {
  const [fontSize, setFontSize] = useState(16);

  const fontFamilies = [
    { name: "Arial", text: " מעבר לפונט אריאל" },
    { name: "Times New Roman", text: "מעבר לפונט טיימס ניו רומן" },
    { name: "Verdana", text: "מעבר לפונט ורדנה " },
  ];

  const increaseLineSpacing = () => {
    const bodyStyles = getComputedStyle(document.body);
    const currentFontSize = parseFloat(bodyStyles.fontSize);
    const currentLineSpacing =
      parseFloat(bodyStyles.lineHeight) / currentFontSize;
    const newLineSpacing = currentLineSpacing + 0.2;
    document.body.style.lineHeight = `${newLineSpacing}`;
  };

  const decreaseLineSpacing = () => {
    const bodyStyles = getComputedStyle(document.body);
    const currentFontSize = parseFloat(bodyStyles.fontSize);
    const currentLineSpacing =
      parseFloat(bodyStyles.lineHeight) / currentFontSize;
    const newLineSpacing = currentLineSpacing - 0.2;
    document.body.style.lineHeight = `${newLineSpacing}`;
  };

  const increaseTextSize = () => {
    setFontSize((prevFontSize) => {
      const newFontSize = prevFontSize + 2;
      document.documentElement.style.fontSize = `${newFontSize}px`;
      console.log("New Font Size:", newFontSize);
      return newFontSize;
    });
  };

  const decreaseTextSize = () => {
    setFontSize((prevFontSize) => {
      const newFontSize = prevFontSize - 2;
      document.documentElement.style.fontSize = `${newFontSize}px`;
      console.log("New Font Size:", newFontSize);
      return newFontSize;
    });
  };

  const changeFontFamily = (fontFamily) => {
    document.body.style.fontFamily = fontFamily;
  };

  const changeTextColor = (color) => {
    document.body.style.color = color;
  };

  const toggleHeaderHighlight = () => {
    const headers = document.querySelectorAll("h1, h2, h3, h4, h5, h6");
    headers.forEach((header) => {
      header.classList.toggle("highlighted-header");
    });
  };

  return (
    <div className="accessibility-menu" style={style}>
      <button onClick={increaseTextSize}>הגדל טקסט</button>
      <button onClick={decreaseTextSize}>הקטן טקסט</button>
      <button onClick={onToggleDarkMode}>מצב לילה</button>
      <button onClick={onToggleTextOnly}>מצב טקסט בלבד</button>
      <button onClick={() => changeTextColor("black")}>טקסט שחור</button>
      <button onClick={() => changeTextColor("blue")}>טקסט כחול</button>
      <button onClick={() => changeTextColor("red")}>טקסט אדום</button>
      <button onClick={onToggleLinkHighlight}>הדגש קישורים</button>
      <button onClick={toggleHeaderHighlight}>סמן כותרות</button>

      <div className="font-family-buttons">
        {fontFamilies.map((fontFamily) => (
          <button
            key={fontFamily.name}
            onClick={() => changeFontFamily(fontFamily.name)}
          >
            {fontFamily.text}
          </button>
        ))}
      </div>
      <button onClick={increaseLineSpacing}>הגדל רווח בין שורות</button>
      <button onClick={decreaseLineSpacing}>הקטן רווח בין שורות</button>
    </div>
  );
};

export default AccessibilityMenu;

Ans this is the code of the css:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accessibility-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background-color: white;
  border: 1px solid #ccc;
  padding: 1rem;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  max-width: 100%;
  width: auto;
}

.accessibility-menu button {
  background-color: #4a90e2;
  border: none;
  color: white;
  font-size: 14px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  padding: 0.5rem 1rem;
  text-align: center;
  cursor: pointer;
  transition: background-color 0.3s ease;
  border-radius: 10px 10px 10px;
}

body.dark-mode {
  background-color: #333;
  color: red;
  font-weight: bold;
}

body.dark-mode a {
  color: red;
}

/* High contrast mode */
body.high-contrast {
  background-color: #fff;
  color: #000;
}

body.high-contrast a {
  color: #000;
}

/* Text-only mode */
body.text-only * {
  background: none !important;
  color: #000 !important;
  font-size: 16px !important;
  font-weight: normal !important;
  text-decoration: none !important;
  font-family: Arial, sans-serif !important;
}

body.text-only img {
  display: none !important;
}

body.text-only *::before,
body.text-only *::after {
  content: none !important;
}

.font-family-buttons button:not(:last-child) {
  margin-bottom: 0.5rem;
}

.highlight-links {
  background-color: yellow;
}

.highlighted-header {
  text-decoration: underline;
}

.zoomed-element {
  transform: scale(1.5);
  transition: transform 0.3s ease-in-out;
}

:root {
  --animation-speed: 1s;
}

.some-animation {
  animation-duration: var(--animation-speed);
}

@media only screen and (min-width: 320px) and (max-width: 480px) {
  .accessibility-menu {
    top: auto;
    bottom: 10%;
    max-height: 500px;
    overflow-y: auto;
    width: auto;
  }
}

@media only screen and (min-width: 481px) and (max-width: 767px) {
  .accessibility-menu {
    top: auto;
    bottom: 10%;
    max-height: 500px;
    overflow-y: auto;
    width: auto;
  }
}

@media only screen and (min-width: 768px) and (max-width: 1023px) {
  .accessibility-menu {
    top: auto;
    bottom: 10%;
    max-height: 500px;
    overflow-y: auto;
    width: auto;
  }
}

@media only screen and (min-width: 1024px) and (max-width: 1215px) {
  .accessibility-menu {
    top: auto;
    bottom: 10%;
    max-height: 500px;
    overflow-y: auto;
  }
}

@media only screen and (min-width: 1216px) {
  .accessibility-menu {
    top: auto;
    bottom: 10%;
    max-height: 500px;
    overflow-y: auto;
  }
}

And this is the code of the button itself:

import React, { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import "../../../css/AccessibilityButton.css";
import AccessibilityMenu from "./AccessibilityMenu";

const AccessibilityButton = (props) => {
  const [menuVisible, setMenuVisible] = useState(false);
  const [menuStyle, setMenuStyle] = useState({});

  const handleClick = () => {
    setMenuVisible((prevVisible) => !prevVisible);
  };

  const handleKeyPress = (event) => {
    if (event.key === "Enter") {
      handleClick();
    }
  };

  const toggleAnimations = () => {
    document.body.classList.toggle("animation-active");
  };

  const toggleLinkHighlight = () => {
    const links = document.querySelectorAll("a");
    links.forEach((link) => {
      link.classList.toggle("highlight-links");
    });
  };

  useEffect(() => {
    const buttonElement = document.querySelector(".accessibility-button");
    if (buttonElement) {
      const rect = buttonElement.getBoundingClientRect();
      setMenuStyle({
        position: "absolute",
        top: `${rect.bottom}px`,
        left: `${rect.left}px`,
      });
    }
  }, []);

  const toggleDarkMode = () => {
    document.body.classList.toggle("dark-mode");
  };

  const toggleTextOnly = () => {
    document.body.classList.toggle("text-only");
  };

  const changeColors = (bgColor, textColor) => {
    document.body.style.backgroundColor = bgColor;
    document.body.style.color = textColor;
  };

  return (
    <>
      <button
        className="accessibility-button"
        onClick={handleClick}
        onKeyPress={handleKeyPress}
        aria-label={props.ariaLabel}
        tabIndex={0}
      >
        תפריט נגישות
      </button>
      {menuVisible &&
        createPortal(
          <AccessibilityMenu
            style={menuStyle}
            onToggleDarkMode={toggleDarkMode}
            onToggleTextOnly={toggleTextOnly}
            onChangeColors={changeColors}
            onToggleAnimations={toggleAnimations}
            onToggleLinkHighlight={toggleLinkHighlight}
          />,
          document.body
        )}
    </>
  );
};

export default AccessibilityButton;

And this is the code of the css of the button itslef:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accessibility-button {
  position: absolute;
  top: 60px;
  right: 5px;
  font-size: 16px;
  padding: 8px 16px;
  border: none;
  background-color: #007bff;
  color: white;
  cursor: pointer;
}

.accessibility-button:focus {
  outline: none;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.5);
}

@media only screen and (min-width: 1px) and (max-width: 480px) {
  .accessibility-button {
    position: absolute;
    top: 60px;
    right: 5px;
    font-size: 16px;
    padding: 4px 8px;
    border: none;
    background-color: #007bff;
    color: white;
    cursor: pointer;
  }
}

javascript create a variable with array

I need to create this data structure in Javascript:

var bar_data = {
  data: [
    [sistOper[0], tot[0]],
    [sistOper[1], tot[1]],
    [sistOper[2], tot[2],
    [sistOper[3], tot[3]]
  ],
  color: '#3c8dbc'
}

It works correctly, but if I have an array with 20 elements this syntax is very inefficient.

I’ve tried this, but doesn’t work:

var bar_data = {
  data: [[ sistOper, tot ]],
  color: '#3c8dbc'
}

Any suggestions?

When I run this JavaScript code in Visual Studio Code, some console.log() operations work but some don’t

I am working on a JavaScript objects exercise for a course I’m following, but when I run the code I don’t get the expected result. I’ve cut the code down to the essentials for clarity.

const myObject = {
    _array: [ 
        {item: 'a', item2: 'b', item3: 'c'},
        {item: 'd', item2: 'e', item3: 'f'},
        {item: 'g', item2: 'h', item3: 'i'}
        ],

    get items () {
        return this._array;
    },

    addThing (newItem1, newItem2, newItem3) {
        let thing = {
            item1: newItem1,
            item2: newItem2,
            item3: newItem3
        };
        /* `this.players.push(player);` is adding a new player object to the `_players` array of the `team` object. It uses the `push()` method to add the `player` object to the array. */
        this._array.push(thing);
      }

}
console.log('hello before');
myObject.addThing('j', 'k', 'l');
console.log(myObject._array);
console.log('hello after');

Running this from a terminal window gives me the expected result where the array is dumped …

Terminal capture

… but running it with F5 or Run and Debug gives me this

Debug console capture

I’d like to understand why there is no output of _array when run this way.