transform a data structure from an object of arrays to an array

I have forgotten most of what I learnt so treat ma as a novice. 🙁

I have an object of arrays returned from a database select statement as below :-

options:[{"breed":"bulldog"},{"breed":"labrador"}{"breed":"beagle"},{"breed":"dobermann"}]

Using javascript, how can I transpose this into an array as below :-

const breed ["bulldog","labrador","beagle","dobermann"];

The array will be used to populate a node-red dropdown menu.

Thanks for looking or advising.

I have tried split and map, but I cant seem to arrive at my required.
Maybe because I did not code it correctly.

Plain constant value spontaneously change when DOM updates when using Vue

I have a simple Vue signin/signup form.
I have prepared funny dummy data for placeholders, so every time page reloads it will be displaying a random person data in my form:

<script>
    // ...

    const dummyData = [
        ['Euclid', '[email protected]'],
        ['Gauss', '[email protected]'],
        ['Einstein', '[email protected]'],
    ];

    const cDummy = dummyData[Math.floor(Math.random()*dummyData.length)];

    console.log(cDummy);
</script>

Then I use the data in cDummy const in template:

<template>
    <label v-if="!isLogin">
        <div>Name</div>
        <input type="text" v-model="login" :placeholder="cDummy[0]" required>
    </label>
    <label>
        <div>Email</div>
        <input type="email" v-model="email" :placeholder="cDummy[1]" required>
    </label>
</template>

The problem is when I change reactive isLogin variable, the newly added input Name field placeholder name sometimes does not fit with dummy email. For example, the mail was [email protected] and the added name is Euclid and so on.

Why is it happening?
I only see one console.log() message in console with correct data!

onload() function not working more than once

I have a button that calls a function that is suppose to write a document and then print it. It works fine the first time I press the button, but when I run this function a 2nd time, the printWindow.onload doesn’t run again. Resulting in the print() window not showing up again. I have tried other things like adding an eventListener instead but I get the same problem. Appreaciate all answers.

function printPDF(html: any) {
const printWindow = window.open("", "PRINT");

if (printWindow) {
  printWindow.document.write(html);
  printWindow.document.close();
  printWindow.focus()

  printWindow.onload = () => {
    printWindow.print();
    printWindow.close();
  }
  printWindow.onunload = () => {
    setIsLoading(false);
  }
 }
}

How do I prevent the addition of points in a slider but not the decrease?

This would be a score distributor for an online RPG.
My issue is that I would like to prevent the addition of points when the total reaches 0, and the slider should stop from moving forward, but not prevent the decrease of points.
I’m a complete beginner, so my question might be super silly. Thanks for the help.

This would be a score distributor for an online RPG.
My issue is that I would like to prevent the addition of points when the total reaches 0, and the slider should stop from moving forward, but not prevent the decrease of points.
I’m a complete beginner, so my question might be super silly. Thanks for the help.

document.addEventListener("DOMContentLoaded", function () {
            const characteristics = ['Forza',];

            const skills = [
                'Equitazione',];

            const characteristicsContainer = document.getElementById('characteristics');
            const skillsContainer = document.getElementById('skills');

            // Aggiungi caratteristiche
            characteristics.forEach(characteristic => {
                createSlider(characteristic, characteristicsContainer, 'totalCharacterPoints');
            });

            // Aggiungi abilità
            skills.forEach(skill => {
                createSlider(skill, skillsContainer, 'totalSkillPoints');
            });

            function createSlider(label, container, totalPointsId) {
    const labelElement = document.createElement('label');
    labelElement.textContent = `${label}:`;

    const inputElement = document.createElement('input');
    inputElement.type = 'range';
    inputElement.min = 0;
    inputElement.max = 20;  // Puoi mantenere il valore massimo a 20 o impostarlo secondo le tue esigenze iniziali.
    inputElement.value = 0;

    const valueElement = document.createElement('span');
    valueElement.textContent = inputElement.value;

    container.appendChild(labelElement);
    container.appendChild(inputElement);
    container.appendChild(valueElement);


inputElement.addEventListener('input', function () {
    const totalPoints = parseInt(document.getElementById(totalPointsId).textContent);
    const currentValue = parseInt(this.value);

    if (currentValue > 0 || (currentValue < 0 && totalPoints > 0)) {
        if (currentValue < 0) {
            // Verifica se si sta cercando di togliere più punti di quelli rimanenti
            const newValue = Math.max(currentValue, -totalPoints);
            this.value = newValue;
            valueElement.textContent = newValue;
        } else {
            // Aggiorna il valore e i punti totali solo se il totale è maggiore di 0
            valueElement.textContent = currentValue;
            updateTotalPoints();
        }
    } else {
        // Impedisci l'aggiunta di punti quando il totale è 0, ma consenti la diminuzione
        this.value = 0;
    }

    disableSliderIfNoPoints();
});

function disableSliderIfNoPoints() {
    const remainingPoints = parseInt(document.getElementById(totalPointsId).textContent);

    // Disabilita lo slider solo se non ci sono più punti disponibili
    this.disabled = remainingPoints === 0 && parseInt(this.value) === 0;
}
}


            function updateTotalPoints() {
                const totalCharacterPoints = 80;
                const totalSkillPoints = 100;

                const characterPointsUsed = Array.from(document.querySelectorAll('#characteristics input'))
                    .reduce((total, input) => total + parseInt(input.value), 0);

                const skillPointsUsed = Array.from(document.querySelectorAll('#skills input'))
                    .reduce((total, input) => total + parseInt(input.value), 0);

                const remainingCharacterPoints = Math.max(0, totalCharacterPoints - characterPointsUsed);
                const remainingSkillPoints = Math.max(0, totalSkillPoints - skillPointsUsed);

                document.getElementById('totalCharacterPoints').textContent = remainingCharacterPoints;
                document.getElementById('totalSkillPoints').textContent = remainingSkillPoints;
            }

        function disableSlidersIfNoPoints() {
    const remainingCharacterPoints = parseInt(document.getElementById('totalCharacterPoints').textContent);
    const remainingSkillPoints = parseInt(document.getElementById('totalSkillPoints').textContent);

    // Rimuovi la condizione che disabilita gli slider quando i punti sono esauriti
    document.querySelectorAll('#characteristics input').forEach(input => {
        input.disabled = false;
    });

    document.querySelectorAll('#skills input').forEach(input => {
        input.disabled = false;
    });
}
        });

execution of paragraph text in background even if browser tab change in react js

I am working on a react project where i am calling an api and in response i am getting some data which i am storing in state. For showing data, i am mapping that state and in that state value is a long text which i am showing through Typewriter animation

<Typewriter
text={
data.result
delay={5}
onAnimationComplete={(value) =>handleAnimationComplete(value)
}
/>

when i call the api then fully code is working and data is being animated as i required. but when i change the tab then animation get paused and when i go back to that tab then it continues from that position.

but i want continuous execution of that data in background even if tab is changed.

Tried many solution but not working as per my requirement. any help would be appreciated

Reordering pairs of elements in a JavaScript array

I need to create an algorithm in JavaScript that works on an array data of length N containing elements "a" and "b" in random order. Half of the elements are "a" and half are "b". The total number of elements can be odd, so "a" or "b" will have one more element than the other in that case.

The objective is to create a function, called reorderArray(data), which, given the data array as input, reorders the elements so that, starting from the first element, approximately 50% of the pairs of consecutive values are equal ("a","a" or "b","b") and the remaining approximately 50% are different ("a","b" or "b","a").

Here are two examples of possible reordered arrays:

var data1 = ["a","a","b","b","b","b","a","a"];
var data2 = ["b","a","b","a","a","b","a","b","b"];

var data1Reordered = reorderArray(data1);
var data2Reordered = reorderArray(data2);

console.log(data1Reordered); // ["b","a","a","a","b","b","b","a"]; 4 same pairs, 3 different pairs
console.log(data2Reordered); // ["b","b","b","a","a","a","b","a","b"]; 4 same pairs, 4 different pairs

Same code, same input but different output in Appwrite function

I have been on this issue for a while now, and still cannot find a solution.

I’m currently working on a JS/TS Vue App (using the project scaffolding by Quasar framework).
We have an on premise Appwrite server with cloud functions enabled.

I’m trying to port some of the code to a single Appwrite function.
The function listens for POST requests with a JSON object as the body and returns the result as a JSON object.

Appwrite server version : 1.4.4 (I’m not the admin)

Local node version 20 or 21

Appwrite Node version 18.0

The problem

The issue is : The code in the function doesn’t give me the same output as when the code is tested locally.

Context

Basically, I have a 3 Typescript files containing classes A, B and C that import different things from eachother, that’s why I include them all for the function. Class A has a method processJson(json): json that is the one I’m trying to turn into a single Appwrite function.

Since Appwrite functions have a Node 18.0 runtime, I first need to transpile the files to Javascript.
As I don’t have a lot of experience with that, I use the tsup package to build the files like so :

  1. Create an empty dir somewhere
  2. Copy file A.ts, B.ts and C.ts to this dir
  3. CD to the dir
  4. Run npx tsup --format esm A.ts B.ts C.ts which outputs to ./dist/A.mjs ./dist/B.mjs ./dist/C.mjs
  5. Move the dist dir inside the dir of the Appwrite function, so I end up with something like this : somepath/appwrite/functions/myfunction/dist/... and somepath/appwrite/functions/myfunction/main.js (the Appwrite function). Inside main.js I then import the compiled depedency like import { MyClass } from './dist/A.mjs'
  6. Finally, I deploy the function to Appwrite using the CLI. So npx appwrite deploy function, select my function and deploy it.

The function deploys successfully (no build or deploy error) and I’m able to query it through Postman, Python and Appwrite’s UI by sending a POST request with the (non stringified) JSON test object that I have. The function does return wihtout crashing, but the result is not the one I expect.

When testing the code locally (with the Quasar app in dev mode), with the same JSON as input I get output A, when testing that same JSON with the function, I get output B.

So far I tried :

  • Deploying the same code on a different function: same issue
  • Using NVM to test locally with the same Node version as Appwrite (Node 18.0) : local test works, same issue for the function. I was thinking maybe some syntax I used was too recent for version 18.0…
  • Make small tweaks to the functions main.js file and redeploy to see if changes were actually pushed : changes are pushed

I don’t really know what to do next, as I said, I’m not familiar with Typescript building, and I used the flag –format esm with tsup as I was getting import errors otherwise (CommonJS, etc).

I just have a feeling that the problem has to be related to this somehow, as I feel I’ve tried everything else so maybe there’s something obvious that I’m missing…

Odoo 17 error: @spreadsheet/hooks: The following modules are needed by other modules but have not been defined

I have an Odoo 17 on-premise install. I installed some modules and then somehow this error started showing in the browser directly when clicking on the dashboard app:

The following modules are needed by other modules but have not been defined, they may not be present in the correct asset bundle:

    @spreadsheet/hooks

The following modules could not be loaded because they have unmet dependencies, this is a secondary error which is likely caused by one of the above problems:

    @spreadsheet_edition/bundle/actions/abstract_spreadsheet_action
    @spreadsheet_dashboard_edition/bundle/action/dashboard_edit_action

I couldn’t find anything in GitHub issues or other places regarding this error. How could something like this happen, and how can I repair it, without needing to start a new database from scratch? Can I somehow find the code that is missing and install it once again?

There seems to be some JS code missing?

Parsing Date String Treats February as March

Trying to convert a date-time string from the database (stored local time) and keeping it local instead of being converted to UTC time. The one way I am approaching this is taking the date and splitting the parts and applying the values into a JavaScript date object. For some reason, I give it a date of 2023-02-01 and it thinks its March even when I parse the date value to be an integer and subtract 1.

Like wise:

  • 2023-01-01 is January
  • 2023-03-01 is March
  • 2023-04-01 is April
  • and so on…
const dateString = '2023-02-01T09:00:00Z'

const splitDateTime = new Date(dateString)
    .toISOString()
    .split('T'); // ['2023-02-01', '09:00:00']


const dateHalfSplit = splitDateTime[0].split('-'); // ['2023','02','01']
const timeHalfSplit = splitDateTime[1].split(':'); // ['09','00','00']

localDate = new Date();
localDate.setFullYear(parseInt(dateHalfSplit[0]));
localDate.setMonth(parseInt(dateHalfSplit[1]) - 1);
localDate.setDate(parseInt(dateHalfSplit[2]));
localDate.setHours(parseInt(timeHalfSplit[0]));
localDate.setMinutes(parseInt(timeHalfSplit[1]));
localDate.setSeconds(parseInt(timeHalfSplit[2].split('.')[0]));

console.info(localDate.toLocaleDateString('en-US', {
    day: '2-digit',
    year: 'numeric',
    month: 'long',
    hour: 'numeric',
    minute: '2-digit',
    hour12: true
}));

// Output: March 01, 2023 at 9:00 AM

Granted, this is not an ideal way to handle dates, from the database backend, but is there something I am missing that somehow this is not handling February correctly or could this be a browser bug?

Module not found error for ‘@material-ui/core’ in React project

I’m encountering a “Module not found” error in my React project when trying to import ‘@material-ui/core’ in one of my components. The error specifically points to the file located in ‘C:Main Projectresumebuildersrccomponents’. I have already installed the ‘@material-ui/core’ package using npm, and it appears in my ‘node_modules’ directory.

Here’s the relevant import statement in my component:

import {Button,TextField} from '@material-ui/core'

And here's the error message:
Module not found: Error: Can't resolve '@material-ui/core' in 'C:Main Projectresumebuildersrccomponents'

I’ve tried the following troubleshooting steps:

  1. Ensured that ‘@material-ui/core’ is listed as a dependency in my ‘package.json’.

  2. Deleted ‘node_modules’ and ‘package-lock.json’, then ran ‘npm install’ again.

  3. Checked for typos in the import statement and the package name.

Despite these efforts, the error persists. Any guidance on how to resolve this issue would be greatly appreciated!

How to create elements and display them using JavaScript?

I was working on a simple rock paper scissors game where in the user chooses from the three buttons available and the round is played according to some defined function which works fine. I want to display those details which i am console logging on the page so i tried creating a div and then a para tag and then appending it but its not working.

function playGameRound(playerSelection){
    const display = document.createElement('div');

    let computerSelection = getComputerChoice();
    console.log(`You chose ${playerSelection} and the computer chose ${computerSelection}`);

    const details = document.createElement('p');
    details.innerText = `You chose ${playerSelection} and the computer chose ${computerSelection}`;
    display.appendChild(details)
    let result = playRound(playerSelection, computerSelection);

    if(result == 1) console.log("YOU WIN");
    else if(result == -1) console.log("YOU LOSE");
    else console.log("TIE BORINGGG");
}

const rockBtn = document.getElementById('rock');
const paperBtn = document.getElementById('paper');
const scissorsBtn = document.getElementById('scissors');

rockBtn.addEventListener("click", () => playGameRound('rock'));
paperBtn.addEventListener("click",() => playGameRound('paper'));
scissorsBtn.addEventListener("click",() => playGameRound('scissors'));

Can someone explain why is the para not displayed?

listen to local storage changes inside useEffect

I have a context variable to check if the user is authenticated or not, what i want to do is to update the context variable whenever the local storage has changed here’s the authContext.js code

import { createContext, useContext, useEffect, useState } from "react";

const authContext = createContext();

export function AuthProvider({ children }) {
  const [isAutenticated, setIsAuthenticated] = useState(null);

  useEffect(() => {
    const checkUser = () => {
      const auth = localStorage.getItem("isAuthenticated") ? true : false;

      if (auth !== null) {
        setIsAuthenticated(auth);
      }
    };

    window.addEventListener("storage", checkUser);

    return () => {
      window.removeEventListener("storage", checkUser);
    };
  }, []);

  return (
    <authContext.Provider value={[isAutenticated, setIsAuthenticated]}>
      {children}
    </authContext.Provider>
  );
}

export function useAuthContext() {
  return useContext(authContext);
}

after calling the api, the local storage is changed but the context variable doesn’t change

Button events ignored 8thwall

I am so stumped, I can’t get my webAR experience to work. I’m hoping I can get help here. I just need my button activate my rain.glb If I can get that going everything else will make sense to me I think.

This is what is going in the head

<!-- Copyright (c) 2022 8th Wall, Inc. -->
<!-- head.html is optional; elements will be added to your html head before app.js is loaded. -->

<!-- Use "8thwall:" meta tags to hook into 8th Wall's build process and developer tools. -->
<meta name="8thwall:renderer" content="aframe:1.3.0">
<meta name="8thwall:package" content="@8thwall.xrextras">
<meta name="8thwall:package" content="@8thwall.landing-page">

<!-- Other external scripts and meta tags can also be added. -->
<meta name="apple-mobile-web-app-capable" content="yes">

<script crossorigin="anonymous" src="//cdn.8thwall.com/web/aframe/aframe-extras-6.1.1.min.js"></script>

in the body

<button id="rainBtn">Toggle Rain Visibility</button>

<a-scene
  tap-place
  xrextras-gesture-detector
  landing-page
  xrextras-loading
  xrextras-runtime-error
  renderer="colorManagement:true; webgl2: true;"
  xrweb="allowedDevices: any">
 
   <!-- Assets -->
 <a-assets>
      <a-asset-item id="raccoonasset" src="assets/raccoon5.glb"></a-asset-item>
      <a-asset-item id="emperorasset" src="assets/emperor3.glb"></a-asset-item>
      <a-asset-item id="heartasset" src="assets/pixel-heart1.glb"></a-asset-item>
      <a-asset-item id="rainasset" src="assets/rain.glb"></a-asset-item>
 </a-assets>

    <!-- Lights and Camera -->
    <a-entity light="type: directional; castShadow: true; color: white; intensity: 0.5;" position="5 10 7"></a-entity>
    <a-light type="ambient" intensity="0.7"></a-light>
    <a-camera position="0 2 2" raycaster="objects: .cantap" cursor="fuse: false; rayOrigin: mouse;"></a-camera>

<xrextras-named-image-target name="model-target">
  <a-entity
    id="raccoon-glb-target"
    gltf-model="#raccoonasset"
    scale="0.2 0.2 0.2"
    position="0 -0.35 0"
    animation-mixer="timeScale: 1"
  ></a-entity>
</xrextras-named-image-target>

<xrextras-named-image-target name="emperor-target">
  <a-entity
    id="emperor-glb-target"
    gltf-model="#emperorasset"
    scale="0.9 0.9 0.9"
    animation-mixer="timeScale: 1"
  ></a-entity>
</xrextras-named-image-target>

<xrextras-named-image-target name="heart-target">
  <a-entity
    id="heart-glb-target"
    gltf-model="#heartasset"
    scale="0.5 0.5 0.5"
    animation-mixer="timeScale: 0"
    animation__spin="property: rotation; dur: 5000; easing: linear; loop: true; to: 0 360 0"
    animation__move-up-down="property: position; dur: 3000; easing: easeInOutQuad; loop: true; to: 0 1 0"
  ></a-entity>
</xrextras-named-image-target>


  <!-- Rain model -->
  <a-entity
    id="rain-glb-target"
    gltf-model="#rainasset"
    scale="2 2 2"
    position="0 0.8 0"
    animation-mixer
    visible="false">
  </a-entity>

</a-scene>


in the app.js

// Copyright (c) 2022 8th Wall, Inc.
//
// app.js is the main entry point for your 8th Wall app. Code here will execute after head.html
// is loaded, and before body.html is loaded.
import './main.css'

// app.js

import {onClickRainButton} from './rain-button'

AFRAME.registerComponent('rain-button', {
  init() {
    console.log('Rain button component initialized.')

    const rainBtn = document.getElementById('rainBtn')
    if (rainBtn) {
      rainBtn.addEventListener('click', onClickRainButton)
      console.log('Event listener registered for rain button.')
    } else {
      console.error('Rain button element not found.')
    }
  },
})

and in the rain-button.js

// rain-button.js

// Function to handle click event on the rain button
function onClickRainButton() {
   console.log('Rain button clicked.');
  // Get the rain entity
  const rainEntity = document.querySelector('#rain-glb-target')

  // Check if the rain entity exists and toggle its visibility
  if (rainEntity) {
    const isVisible = rainEntity.getAttribute('visible')
    rainEntity.setAttribute('visible', !isVisible)
  }
}

export {onClickRainButton}

I hope i don’t burn anyone’s eyes and I appreciate any help.

I tried a couple of different ways to write this and I tried just adding a simple url link to my button, I tried using just a tap on screen but nothing works, so I think it’s a larger problem that I am not seeing.