How to import .mjs files in laravel in a proper way?

I am trying to use PDF.js library in a Laravel application. I want to use the default viewer provided by the library, but then I get this error on the server, even though it’s working totally OK locally.

Basically, the server responds with plain/text content-type and not application/javascript which makes problems with browser’s type checking the file

enter image description here

How to fix this issue?

I suspect that it’s happening due to the way the viewer is used
enter image description here

React Web App – Incorrect Color Highlighting Logic in Music Theory Application

I am developing a React web application designed for music composers. The app features a dynamic UI that allows users to select musical scales and chords, with visual feedback to indicate compatibility between chosen chords and scales. However, I’ve encountered some bugs related to the color highlighting logic, which I’m struggling to resolve.

App Description:

The application displays a set of musical notes, scales, and chords in a table format. Users can select chords and scales, and the app highlights incompatible chords or scales in red based on the selection. Here are the key functionalities:

Selecting a Chord: When a chord is selected, scales not containing all notes of the chord and chords not fully included in any non-red-highlighted scale are highlighted in red.

Selecting a Scale: Selecting a scale highlights in red the chords that don’t have all their notes in the selected scale and scales not including all notes of at least one non-red-highlighted chord.

Deselecting a Chord: Deselecting a chord removes red highlights from chords and scales affected solely by that chord’s selection.

Deselecting a Scale: Deselecting a scale removes red highlights from chords and scales affected solely by that scale’s selection.

(https://i.stack.imgur.com/te9R0.png)

Bugs Identified:

  • If I first press a chord and then a scale, scales that were marked in red due to the chord selection stop being red. The expected behavior is that the app should keep scales already highlighted in red and mark additional ones as needed.

  • When a chord is selected, followed by a scale, and then the scale is deselected, only those chords/scales that turned red upon the scale’s selection should revert to white. Similarly, if a scale is selected, followed by a chord, and then the chord is deselected, only the scales/chords that turned red upon the chord’s selection should revert to white.

NOTE: The application functions correctly when only chords or only scales are selected, and also when scales are selected before chords. The issue arises when selecting scales after chords.

I’ve included my React component (App.js) and CSS (App.css) code below for reference. I am looking for guidance on how to debug and fix these issues.


App.js

import React, { useState } from 'react';
import './App.css';

const notes = ['Do', 'Do#', 'Re', 'Re#', 'Mi', 'Fa', 'Fa#', 'Sol', 'Sol#', 'La', 'La#', 'Si'];
const scaleQualities = ['Mayor', 'Menor', "Pent Mayor"]; // Used only for scales
const chordQualities = ['Mayor', 'Menor', 'Sus2', 'Sus4']; // Used for chords

// Get the index of a note within an octave
const getIndexInOctave = (note) => {
  return notes.indexOf(note);
};

// Define intervals for different scale qualities
const scaleIntervals = {
  'Mayor': [2, 2, 1, 2, 2, 2, 1],
  'Menor': [2, 1, 2, 2, 1, 2, 2],
  'Pent Mayor': [2, 2, 3, 2, 3]
};

// Generate a scale based on a root note and quality
const generateScale = (rootNote, quality) => {
  let scale = [rootNote];
  let intervals = scaleIntervals[quality];
  let currentNote = rootNote;

  intervals.forEach(interval => {
    currentNote = getNoteAtInterval(currentNote, interval);
    scale.push(currentNote);
  });

  return scale;
};

const getNoteAtInterval = (startNote, interval) => {
  let startIndex = getIndexInOctave(startNote);
  let targetIndex = (startIndex + interval) % notes.length;
  return notes[targetIndex];
};

// Define intervals for different chord qualities
const chordIntervals = {
  'Mayor': [4, 3],
  'Menor': [3, 4],
  'Sus2': [2, 5],
  'Sus4': [5, 2]
};

// Generate a chord based on a root note and quality
const generateChord = (rootNote, quality) => {
  let chord = [rootNote];
  let intervals = chordIntervals[quality];
  let currentNote = rootNote;

  intervals.forEach(interval => {
    currentNote = getNoteAtInterval(currentNote, interval);
    chord.push(currentNote);
  });

  return chord;
};

// Generate all major and minor scales
let generatedScales = {};
notes.forEach(note => {
  scaleQualities.forEach(quality => {
    let scaleName = `${note} ${quality}`;
    generatedScales[scaleName] = generateScale(note, quality);
  });
});

// Generate all chords
let generatedChords = {};
notes.forEach(note => {
  chordQualities.forEach(quality => {
    let chordName = `${note} ${quality}`;
    generatedChords[chordName] = generateChord(note, quality);
  });
});

// Initial state for the application
const initialState = {
  buttons: notes.reduce((acc, note) => {
    scaleQualities.forEach(quality => {
      acc[`scale-${note} ${quality}`] = 'white';
    });
    chordQualities.forEach(quality => {
      acc[`chord-${note} ${quality}`] = 'white';
    });
    return acc;
  }, {}),
  selectedChord: '',
  selectedScale: ''
};

const App = () => {
  const [selectedChord, setSelectedChord] = useState('');
  const [selectedScale, setSelectedScale] = useState('');
  const [buttons, setButtons] = useState(initialState.buttons); // Agregado

  // Check if a chord is compatible with a scale
  const isChordCompatibleWithScale = (chord, scale) => {
    if (!generatedChords[chord] || !generatedScales[scale]) {
      return false;
    }
  
    return generatedChords[chord].every(note => generatedScales[scale].includes(note));
  };
  
  // Check if any chord is incompatible with a scale
  const isAnyChordIncompatibleWithScale = (buttons, scale) => {
    return Object.keys(buttons).some(key => {
      if (key.startsWith("chord-") && buttons[key] === 'green') {
        const chord = key.substring(6);
        return !isChordCompatibleWithScale(chord, scale);
      }
      return false;
    });
  };
  
  // Check if any scale is incompatible with a chord
  const isAnyScaleIncompatibleWithChord = (buttons, chord) => {
    return Object.keys(buttons).some(key => {
      if (key.startsWith("scale-") && buttons[key] === 'green') {
        const scale = key.substring(6);
        return !isChordCompatibleWithScale(chord, scale);
      }
      return false;
    });
  };

  // Handle click on a chord button
  const handleChordClick = (chord) => {
    const chordKey = `chord-${chord}`;
    if (buttons[chordKey] === 'red') {
      return; // Do nothing if the button is red
    }
    let newButtons = { ...buttons };
  
    const wasSelected = newButtons[chordKey] === 'green';
    newButtons[chordKey] = wasSelected ? 'white' : 'green';
  
    // Update the compatibility of scales with the selected/deselected chord
    Object.keys(newButtons).forEach(key => {
      if (key.startsWith("scale-")) {
        if (!wasSelected) {
          newButtons[key] = isChordCompatibleWithScale(chord, key.substring(6)) ? newButtons[key] : 'red';
        } else if (newButtons[key] === 'red') {
          newButtons[key] = isAnyChordIncompatibleWithScale(newButtons, key.substring(6)) ? 'red' : 'white';
        }
      }
    });
  
    // Update the compatibility of chords with the updated scales
    Object.keys(newButtons).forEach(key => {
      if (key.startsWith("chord-") && key !== chordKey) {
        const currentChord = key.substring(6);
        const isCompatibleWithAnyNonRedScale = Object.keys(newButtons).some(scaleKey => {
          return scaleKey.startsWith("scale-") && newButtons[scaleKey] !== 'red' && isChordCompatibleWithScale(currentChord, scaleKey.substring(6));
        });
  
        newButtons[key] = newButtons[key] === 'green' || isCompatibleWithAnyNonRedScale ? newButtons[key] : 'red';
      }
    });
  
    // If a chord is deselected, check all chords and update their color state
    if (wasSelected) {
      Object.keys(newButtons).forEach(key => {
        if (key.startsWith("chord-")) {
          const currentChord = key.substring(6);
          // Check if the chord is not currently selected
          if (newButtons[key] !== 'green') {
            const isCompatibleWithAnyNonRedScale = Object.keys(newButtons).some(scaleKey => {
              return scaleKey.startsWith("scale-") && newButtons[scaleKey] !== 'red' && isChordCompatibleWithScale(currentChord, scaleKey.substring(6));
            });
  
            newButtons[key] = isCompatibleWithAnyNonRedScale ? 'white' : 'red';
          }
        }
      });
    }
  
    setButtons(newButtons);
  };
  
  // Handle click on a scale button
  const handleScaleClick = (scale) => {
    const scaleKey = `scale-${scale}`;
    if (buttons[scaleKey] === 'red') {
      return; // Do nothing if the button is red
    }
  
    let newButtons = { ...buttons };
  
    // Toggle the state of the current scale between selected and unselected
    newButtons[scaleKey] = newButtons[scaleKey] === 'green' ? 'white' : 'green';
  
    // Check compatibility of all chords with the current scale
    Object.keys(newButtons).forEach(key => {
      if (key.startsWith("chord-")) {
        const currentChord = key.substring(6);
        if (newButtons[scaleKey] === 'green') {
          newButtons[key] = isChordCompatibleWithScale(currentChord, scale) ? newButtons[key] : 'red';
        } else {
          newButtons[key] = isAnyScaleIncompatibleWithChord(newButtons, currentChord) ? 'red' : (newButtons[key] === 'green' ? 'green' : 'white');
        }
      }
    });
  
    // Update the state of scales based on the chords not marked in red
    Object.keys(newButtons).forEach(scaleKey => {
      if (scaleKey.startsWith("scale-")) {
        const currentScale = scaleKey.substring(6);
        newButtons[scaleKey] = !Object.keys(generatedChords).some(chordKey => {
          if (newButtons[`chord-${chordKey}`] !== 'red') {
            return generatedChords[chordKey].every(note => generatedScales[currentScale].includes(note));
          }
          return false;
        }) ? 'red' : (newButtons[scaleKey] === 'green' ? 'green' : 'white');
      }
    });
  
    setButtons(newButtons);
  };

  // Generate cells for a row of chords or scales
  const generateRowCells = (type, rowQuality) => {
    return notes.map((note) => {
      const combination = `${note} ${rowQuality}`;
      const buttonType = type === 'chord' ? `chord-${combination}` : `scale-${combination}`;
      const buttonColor = buttons[buttonType];
      const isButtonIncompatible = buttonColor === 'red';

      return (
        <td
          key={note}
          onClick={() => {
            if (type === 'chord') {
              handleChordClick(combination);
            } else {
              handleScaleClick(combination);
            }
          }}
          style={{ backgroundColor: buttonColor }}
          className={isButtonIncompatible ? "incompatible" : ""}
        >
          {combination}
        </td>
      );
    });
  };

  // Generate table rows for chords or scales
  const generateTableRows = (type) => {
    const qualities = type === 'chord' ? chordQualities : scaleQualities;
    return qualities.map((quality) => (
      <tr key={quality}>
        <th>{quality}</th>
        {generateRowCells(type, quality)}
      </tr>
    ));
  };

  return (
    <div className="App">
      <h1 className="title">ChordProg</h1>

      <div className="table-container">
        <h2>Acordes</h2>
        <table className="chord-table">
          <thead>
            <tr>
              <th></th> {/* Empty cell in the corner */}
              {notes.map((note) => (
                <th key={note}>{note}</th>
              ))}
            </tr>
          </thead>
          <tbody>{generateTableRows('chord')}</tbody>
        </table>
      </div>

      <div className="table-container">
        <h2>Escalas</h2>
        <table className="scale-table">
          <thead>
            <tr>
              <th></th> {/* Empty cell in the corner */}
              {notes.map((note) => (
                <th key={note}>{note}</th>
              ))}
            </tr>
          </thead>
          <tbody>{generateTableRows('scale')}</tbody>
        </table>
      </div>
    </div>
  );
};

export default App;

App.css

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');

body, h1, h2, h3, p, figure, ul, li, table, td, th {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Roboto', sans-serif;
  background-color: #f0f2f5;
  color: #333;
  line-height: 1.6;
}

.App {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
  text-align: center;
  zoom: 0.70;
}

.title {
  font-size: 2.5em;
  margin-bottom: 30px;
  color: #4a90e2;
}

.table-container {
  margin-top: 30px;
  width: 90%;
  max-width: 1000px;
}

.chord-table, .scale-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  background-color: white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

th, td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: center;
}

th {
  background-color: #eaeaea;
  font-weight: 700;
}

td {
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

td:hover {
  color: #0401d6;
}

.selected {
  background-color: #ff6347;
  color: white;
}

.table-container h2 {
  margin-bottom: 15px;
  color: #333;
  font-size: 1.5em;
}

@media (max-width: 768px) {
  .title {
    font-size: 2em;
  }

  .table-container {
    width: 100%;
  }
}`

.selected {
  background-color: #4CAF50;
  color: white;
}

.compatible {
}

.incompatible {
  cursor: not-allowed;
  background-color: #ff4a4a;
  color: white;
}


What I Tried:
I have implemented the logic for changing the color states of the buttons representing chords and scales based on their compatibility. The logic involves iterating over the buttons and updating their color state to ‘red’ or ‘white’ depending on the selection and compatibility criteria. When a chord or scale is selected, the app checks for compatibility with other chords and scales and updates the UI accordingly.

What I Expected:
My expectation was that upon selecting a chord or a scale, the application would correctly identify and highlight in red those scales and chords that are not compatible with the selected one. Moreover, upon deselecting a chord or a scale, only the highlights affected by that specific selection should revert back to white, while keeping other red highlights intact.

What Actually Happened:
The issue arises in the sequence of actions. If I first select a chord and then a scale, the red highlights (indicating incompatibility) that were applied due to the chord selection are incorrectly cleared when a scale is selected. Conversely, if I select a scale first and then a chord, the application behaves as expected. This inconsistency suggests that there might be a flaw in the logic that handles the state updates of the buttons when interacting with them in a specific order. The problem seems to lie in the way the application handles state updates when a new selection is made, particularly when it involves interacting with the chords after the scales.

When importing an image in Next.js it shows corrupted

I am trying to import an image in next.js but it shows corrupted. I don’t understand why.
I have the correct path to the image but it shows corrupted.
Putting the path directly in the src=’../pathimagepath/image.svg’ works fine, but when I pass it with an import it doesn’t work.

Corrupted img

This is my code

"use client";
import React, {useState} from 'react';
import Logo from '../assets/Logo.svg';
import hamburgerBtn from '../assets/hamburgerBtn';
import '../app/globals.css';



function Navbar() {

    const [toggle,setToggle]=useState(false);
    const handleClick = ()=> setToggle(!toggle);


    return (
        <div className='w-full h-[80px] bg-white'>
            <div className="2xl:max-w-[1400px] 2xl:px-[0] xl:max-w-[1180px] lg:max-w-[924px] md:max-w-[668px] sm:max-w-[540px] max-w-[460px] md:px-[0px] sm:px-[40px] px-[40px] m-auto w-full h-full flex justify-between items-center">
                <img src={Logo} className='sm:h-[40px] h-[30px] ' />
                <div className="hidden md:flex items-center">
                    <ul className='flex gap-6'>
                        <li>Home</li>
                        <li>About</li>
                        <li>Contact</li>
                    </ul>
                </div>

                <div className='md:hidden' onClick={handleClick}>
                    <img className="sm:h-[25px] h-[20px] " src={hamburgerBtn}/>
                </div>


            </div>
        </div>
    )
}

export default Navbar;

I tried to import it in a Logo.jsx but it doesn´t work.
I need to import everything as an object because I need to make a toggle with the hamburgerBtn and a closeBtn.

i cant access to value of a getterFunction on pinia

the function seems like work well and i can see the value but cant access to this getter function

i write this code to setup store value exist but can access to it

const pro = ref()
const getProductList = computed(() => pro.value)

const getProducts = (val1 = 'newest', val2 = '', val3 = 0, val4 = 0, val5 = 0, val6 = '', val7) => {
  pro.value = null
  axios.get('', {
      params: {
        sort: val1,
        title: val2,
        flash_id: '',
        max_price: val3,
        min_price: val4,
        available: val5,
        category_id: val6,
        vip: 0,
        attribute_value_id: [val7]
      }
    })
    .then((res) => {
      pro.value = res.data.data.products
      console.log(pro.value)
    })
    .catch(err => {
      console.log(err)
    })
}

why are these nested ol items overlapping each other?

i have what should be a pretty normal nested OL with code basically copypasted from here with some minor additions from this thread here where someone was having a similar problem to me, but no matter what i do, i can’t get the list items to stop overlapping. specifically, it shoves all the main list items (1, 2, 3 etc) into one neat and tidy list without any breaks for sublists (1.1, 1.1.1, etc), which do at least show up and are arranged properly but it all just sits on top of each other all weird, example of the weird overlapping

here’s the CSS:

li {
    padding: 10px 10px 10px 10px;
    line-height: 16px; }

a {
 color:#fff; }

#toccontain {
 position:fixed;
 left:0px;
 top:0px;
 width:300px;}

section {
  display: flex;}

ol {
  position: fixed;
  width: 10rem;
  counter-reset: item;
  list-style-position: outside;}
ol li {
  display: block;
  clear: left;
  list-style-position: outside;
  list-style-type: lower-alpha;}
ol li:before {
  content: counters(item, ".") " ";
  counter-increment: item;}

a:hover {
  color: green;}

.active {
  color: green;}

here’s the html:

<section>
    <div id="toccontain">
    <center>Contents</center>
    <ol>
    
      <li><a href="#intro" style="text-decoration: none;">Introduction</a></li>
      <li><a href="#debut" style="text-decoration: none;">Debut</a>
        <ol>
          <li><a href="#2-1" style="text-decoration: none;">The Targets</a>
            <ol>
              <li><a href="#2-1-1" style="text-decoration: none;">Simone Silvestri</a></li>
              <li><a href="#2-1-2" style="text-decoration: none;">Sean Flynn</a></li>
              <li><a href="#2-1-3" style="text-decoration: none;">Jett Baili</a></li>
            </ol>
          </li>
          <li><a href="#2-2" style="text-decoration: none;">The Crime</a>
            <ol>
              <li><a href="#2-2-1" style="text-decoration: none;">Conditions</a></li>
              <li><a href="#2-2-2" style="text-decoration: none;">Discovery</a></li>
            </ol>
          </li>
          <li><a href="#2-3" style="text-decoration: none;">Investigation</a></li>
        </ol>
      </li>
      <li><a href="#3" style="text-decoration: none;">GFGJGHJ</a>
        <ol>
          <li><a href="#3-1" style="text-decoration: none;">JHKJHK</a></li>
            
          <li><a href="#3-2" style="text-decoration: none;">GGR</a></li>
            
          <li><a href="#3-3" style="text-decoration: none;">IGRGn</a></li>
        </ol>
      </li>
    </ol>
    </div>

(insert long, long, long article here that has no code issues within itself)

</section>

i’ll quickly note here that except for the third section all of those subheadings have had their corresponding subheadings in the article set up properly. clicking them to navigate to different headings also still works so long as i can actually click on them, which… i normally can’t with the overlapped ones because they’re all sitting on top of each other, but the point is that it responds totally normally other than being stacked in one spot

and finally javascript, to which my sole edit from the original was swapping ul to ol:

function isElementInViewport(el) {
  var rect = el.getBoundingClientRect();

  return (
    rect.top >= -1 &&
    rect.left >= 0 &&
    rect.bottom <=
      (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

const handler = (entries) => {
  // Get all the links from the side menu
  const allLinks = document.querySelectorAll("ol li a");

  // Get all the sections we want to track
  const allSections = document.querySelectorAll("h2");

  // Get all entries that have just come into the viewport
  const allEntries = new Set(
    entries
      .filter((entry) => entry.isIntersecting == true)
      .map((entry) => entry.target)
  );

  let currentSection;

  // Look through all sections
  for (let i = 0; i < allSections.length; i++) {
    // Get the current section
    currentSection = allSections[i];
    // If the section is in the viewport or it has just intersected, set it as active
    if (isElementInViewport(currentSection) || allEntries.has(currentSection)) {
      // Set all links as unactive
      allLinks.forEach((link) => link.classList.remove("active"));
      // Set current link to active
      document
        .querySelector(`a[href="#${currentSection.id}"]`)
        .classList.add("active");
      // Exit loop after setting first active link
      break;
    }
  }
};

// Create a new observer with the handler
const observer = new IntersectionObserver(handler);

// Observe all sections that have an `id` applied
document.querySelectorAll("h2").forEach((section) => {
  observer.observe(section);
});

i’ve tried changing the ol style to inline or inline-block, both of those just break the look of the list and also don’t even fix the overlapping problem. i’ve tried a whole bunch of stuff actually and scrounged around quite a bit looking for answers but no one has the same problem as i’m having and nothing’s working right. the part of the script i really NEEDED to use, the way the table of contents highlights what header you’re on, works perfectly even with the weird overlapping subheaders (i can see them lighting up green as i scroll through, for example) and i’d really like to keep it but i just can’t figure out how to fix the overlap without messing up the script somehow.

trying to separate the ol into a list per heading (eg section 1 is its own individual ol, so is section 2, etc) and resigning myself to manually numbering each item just resulted in all of them piling on top of each other even worse than before, it’s incorrigible. i don’t know if i broke something somewhere, somehow, or if the original code was just not viable for this to begin with, and i do not know enough about js or how ol/ul works to figure it out

i have no choice but to use only ol for this because i need to use ul in the article itself. it’s an absolute behemoth of 10,000 words and counting, so it pretty badly needs a good TOC (especially because its subject is fictional and basically serves as a wikipedia article for my players to use, and as the sole compendium of information available it does need to be… y’know, navigable), but i TRULY cannot get this thing to work and i’ve no idea why. i haven’t seen any issue with something like this before, even with some other TOC codes i tried before this one (which don’t have the highlighting effect that i want), so what’s happening here? is it something in the javascript? how do i fix that?

React Electron Forge not rendering

I’m having a problem with integrating React and Electron Forge.
I followed this guide:
Electron Forge with react?
and it actually works, BUT it only works like this:

import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import Layout from "./components/Layout/Layout.jsx";
console.log('Loaded React.');
ReactDOM.render(<h1>hola</h1>, document.getElementById('root'));

When I try to render a component it only shows a blank screen

import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import Layout from "./components/Layout/Layout.jsx";
console.log('Loaded React.');
ReactDOM.render(<Layout />, document.getElementById('root'));

I’m using .jsx extension because it doesn’t recognize it without it, which I think is a problem in webpack config or something like that BUT I know that is not the main problem, because I actually got this to work at some point xD and I dont remember exactly what I did.
So…that is not the problem but what should I do so that the component actually renders :'(?

import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import Layout from "./components/Layout/Layout.jsx";
console.log('Loaded React.');
ReactDOM.render(<Layout />, document.getElementById('root'));

Expected it to render the component “Layout” but it shows blank screen.

Type ‘{ another: () => void; }’ is missing the following properties Error Coming

I have a Parent file name Home.tsx and two child (Card.tsx and Product.tsx).Where I have pass the data to child (card.tsx) to parent(Home.tsx).so i write typescript according to it.now when i want to pass the same data to the another child (product.tsx) it showing the error.

Home.tsx:
import React, { useState } from 'react'
import data from './Data'
import Card from './Card';
import { type } from 'os';
import { NavLink } from 'react-router-dom';
type data={
title: string;
src: string;
price: number;
}

export default function Home() {
  const [user,setUser]=useState<data[]>(data); 
  const [total,setTotal]=useState(0); 
  const [count,setCount]=useState(0); 
  const totalTaker=(e:number)=>{
    setTotal(total+e);
  }  
  const Increaser=(e:number)=>{
    setCount(1+count);
  }
  return (
    <div>
      <div className='row m-0 border-bottom p-2 mb-3' >
        <div className='col-lg-10'>
        <h5>Farhan Pavel</h5>
        </div>
        <div className='col-lg-2 '>
            <div><p>Total Items:{count}</p></div>
            <div><h5>Total Price:{total}$ </h5></div>
            <button className='btn btn-dark'><NavLink className={"text-white text-decoration-none"} to="/addcart">View Cart</NavLink></button>
        </div>
      </div>
        <section className='row m-0 '>
        {
           user.map((e)=>(
            <div className='col-lg-3 col-sm-6 col-md-6'>
               <Card pass={e} totalTaker={totalTaker} Increaser={Increaser} />//error here
            </div>
           ))
        }
        </section>
    </div>
  )
}
Card:
import React, { useEffect, useState } from 'react'
import { FaCheck } from "react-icons/fa";
type all={
    pass: {
        title: string;
        src: string;
        price: number;
    };
    totalTaker:(e:number)=>void;
    Increaser:(e:number)=>void;
  another:(e:string)=>void;
}


export default function Card(props:all) {
    const [isOn,setOn]=useState(true);
    const [count,setCount]=useState(0);
    const clicker=(e:React.MouseEvent<HTMLButtonElement>)=>{
      setOn(false); 
      // setCount(1);
       props.totalTaker(props.pass.price);
       props.Increaser(0);
       console.log(props.pass.title);
     }
    
    return (
   <div className='card mb-3' style={{width:"18rem"}}>
    <img src={props.pass.src} className='card-img-top' alt="" />
    <div className="card-body">
    <h5 className="card-title">{props.pass.title}</h5>
    <p className="card-text">{isOn?<span>{props.pass.price}$</span>:<span> {props.pass.price}$ <FaCheck /> Item is Added</span>}</p>
    <button className='btn btn-dark mb-5' onClick={clicker}>Add to Cart</button>
  </div>
    </div>
  )
}
Product:
import React from 'react'
import Card from './Card'

export default function Product() {
 var another=()=>{
    
 }
    return (
    <div>
      <Card another={another}/>//error here
    </div>
  )
}

so please can you help to solve this error

Why socket.io server dont receive the connection from android studio client?

im stuck with trying to set connection between my socket.io server on node js (socket.io ver:4.7.2) to android studio (socket ver:2.0.0), can someone help resolve this problem? When i updating the activity nothing happend on server

server:

const express = require('express'); //requires express module
const socket = require('socket.io'); //requires socket.io module
const fs = require('fs');
const app = express();
var PORT = process.env.PORT || 3000;
const server = app.listen(PORT); //tells to host server on localhost:3000


//Playing variables:
app.use(express.static('public')); //show static files in 'public' directory
console.log('Server is running');
const io = socket(server);

//Socket.io Connection------------------
io.on('connection', function(socket) {

    console.log('Client connected.');

    // Disconnect listener
    socket.on('disconnect', function() {
        console.log('Client disconnected.');
    });
});

client:
SocketHandler.kt

import io.socket.client.IO
import io.socket.client.Socket
import java.net.URISyntaxException

object SocketHandler {

    lateinit var mSocket: Socket

    @Synchronized
    fun setSocket() {
        try {
// "http://10.0.2.2:3000" is the network your Android emulator must use to join the localhost network on your computer
// "http://localhost:3000/" will not work
// If you want to use your physical phone you could use your ip address plus :3000
// This will allow your Android Emulator and physical device at your home to connect to the server
            mSocket = IO.socket("http://0.0.0.0:3000")
        } catch (e: URISyntaxException) {

        }
    }

    @Synchronized
    fun getSocket(): Socket {
        return mSocket
    }

    @Synchronized
    fun establishConnection() {
        mSocket.connect()
    }

    @Synchronized
    fun closeConnection() {
        mSocket.disconnect()
    }
}

ActivityCode

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState:   Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

*        SocketHandler.setSocket()
        val mSocket = SocketHandler.getSocket()
        mSocket.connect()*

        val Dec_button = findViewById<TextView>(R.id.login_button)
        Dec_button.setOnClickListener {
            val intent = Intent(this, LoginPage::class.java)
            startActivity(intent)
        }
    }
}

Im was trynna to rebooting, changing the local ip’s adress (in activity), googling

Firestore UpdateDoc() Issue – Inconsistent Sign of Transaction Amounts for Current User and Friends

I’m facing an issue with Firestore where the transaction amounts for the current user and their friends are having the same sign. According to my logic, if a user initiates a ‘Friends Owe Me’ transaction, the friend’s amount should be negative, and for the current user, it should be positive. Similarly, for ‘I Owe Friends,’ the friend’s amount should be positive, and the current user’s amount should be negative.

I’ve verified that balances are updated correctly for friends, but there seems to be an issue with updating the balances for the current user. I’m using Firestore’s updateDoc() function to handle these updates.

Here is my Function to handle the logic:

const addBill = async (title, totalAmount, selectedFriends, splitOption) => {
  try {
    if (!title || !totalAmount || isNaN(totalAmount)) {
      throw new Error('Please enter a valid title and total amount.');
    }

    const totalAmountValue = parseFloat(totalAmount);
    const timestamp = new Date().toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });

    const currentUserDocRef = doc(db, 'users', userInfo.uid);

    let friendsIncludingCurrentUser;
    if (splitOption === 'Split Equally') {
      friendsIncludingCurrentUser = [...selectedFriends, userInfo.uid];
    } else if (splitOption === 'I Owe Friends' || splitOption === 'Friends Owe Me') {
      friendsIncludingCurrentUser = [...selectedFriends];
    }

    const numberOfFriends = friendsIncludingCurrentUser.length;
    const amountPerFriend = totalAmountValue / numberOfFriends;

    const balancesSnapshot = await getDocs(
      query(collection(db, 'users'), where('uid', 'in', friendsIncludingCurrentUser))
    );
    const existingBalances = {};
    balancesSnapshot.forEach((doc) => {
      const friendId = doc.id;
      existingBalances[friendId] = doc.data().balances || 0;
    });

    const balancesUpdate = {};
    const transactionsUpdate = [];

    for (const friendId of friendsIncludingCurrentUser) {
      const friendDocRef = doc(db, 'users', friendId);
      const isCurrentUser = friendId === userInfo.uid;

      if (existingBalances.hasOwnProperty(friendId)) {
        const friendBalanceChange = splitOption === 'Friends Owe Me' ? -totalAmountValue / numberOfFriends : amountPerFriend;
        balancesUpdate[friendId] = existingBalances[friendId] + friendBalanceChange;

        const friendTransaction = {
          title,
          amount: friendBalanceChange,
          from: splitOption === 'I Owe Friends' ? currentUserDocRef.id : friendId,
          to: splitOption === 'I Owe Friends' ? friendId : currentUserDocRef.id,
          createdAt: timestamp,
        };

        transactionsUpdate.push(friendTransaction);

        if (isCurrentUser) {
          const currentUserTransaction = {
            title,
            amount: splitOption === 'Friends Owe Me' ? Math.abs(friendBalanceChange) : -Math.abs(friendBalanceChange),
            from: friendId,
            to: currentUserDocRef.id,
            createdAt: timestamp,
          };

          transactionsUpdate.push(currentUserTransaction);
        }

        await updateDoc(friendDocRef, {
          transactions: arrayUnion(friendTransaction),
        });
      }
    }

    const currentUserBalanceChange = splitOption === 'I Owe Friends' ? -totalAmountValue / numberOfFriends : amountPerFriend;
    const currentUserExistingBalance = existingBalances[userInfo.uid] || 0;

    balancesUpdate[userInfo.uid] = currentUserExistingBalance - Math.abs(currentUserBalanceChange);

    for (const friendId of friendsIncludingCurrentUser) {
      const friendDocRef = doc(db, 'users', friendId);
      const friendBalancesUpdate = { balances: balancesUpdate[friendId] };
      await updateDoc(friendDocRef, friendBalancesUpdate);
    }

    const currentUserBalancesUpdate = { balances: balancesUpdate[userInfo.uid] };
    const currentUserTransactionsUpdate = { transactions: arrayUnion(...transactionsUpdate) };
    await updateDoc(currentUserDocRef, currentUserBalancesUpdate);
    await updateDoc(currentUserDocRef, currentUserTransactionsUpdate);

  } catch (error) {
    console.error('Error adding bill:', error);
    throw error;
  }
};

I’m relatively new to Firestore, and I’m eager to learn. Any guidance or suggestions on how to resolve this inconsistency would be greatly appreciated.
Thank you

How to add hash in URL [closed]

I want to add the bookmarking feature for the app like allow to return to opened store via URL. I want to do it using “hashchange” event and replacing window.location.hash via click on store item. But when i try to do it URL changes from #storeId to ?storeId. I don’t understand why it happens. Could someone help me find the answer?

I tried many times using history object and location object. But every time # changes to ?

Why does clicking a Leaflet marker sometimes open the wrong marker?

In this https://net-control.us/map.php?NetID=10684 Leaflet map several markers (05, 13, 21) open the wrong marker when clicked. As a demonstration display this map, center the markers, zoom in once or twice, then click one of those markers.

All the markers in question open correctly if you increase the distance between them by zooming in further. I’ve seen this before in other Leaflet maps but have never been able to figure out why. Please only serious answers or suggestions.

If you plan to lecture me about showing code or the color of the marker or some other non-answer save it! If you want to tell me to search for other answers, save it, I’ve already done that too. I’d really like a serious proposal for a solution. If you have no idea, then don’t answer.

I’ve test in Safari, Chrome, Firefox, Brave and a few others the issues is prevalent in all of them. While there may be some other issues with this map, none show up about the problem in console.log.
My only expectation is an explanation why this is happening because I’m pretty sure there is no solution based on coding but if I’m wrong let me know.

Pass array from html to javascript

I’m trying to create a carousel so I can click through each element in csv file:

In a routes/index.js file I’m reading a csv file with film data in an array, and then loading this into the index.ejs file when its opened:

//get request - open index.ejs page
router.get(['/', '/index', '/discover', '/home'], function (req, res) {

  //read film data into array for frontend
  const films = [];
  fs.createReadStream('film_data.csv')
    .pipe(csvParser())
    .on('data', (row) => {
      films.push(row);
    })
   .on('end', () => {
      res.render('index', { title: 'Express', session: { email:req.cookies.sessionEmail }, films: films });
    })
});

In the index.ejs file I am trying to create a carousel so I click next or previous and show the next film title in the array:

<!-- Film carousel -->
<div class="carousel" id="film-carousel" data='<%- films %>'>
  <button id="prev-btn">Previous</button>
  <div id="current-film">
    <!-- films displayed here from scripts/index.js -->
  </div>
  <button id="next-btn">Next</button>
</div>

<!-- END film carousel -->

The functionality for this is handled in the scripts/index.js file, however I don’t know how to put the array from the .ejs file to the .js file so I can implement this, does anyone know how to do this?

This is my scripts/index.js file:

window.onload = function () {
  const currentFilmElement = document.getElementById('current-film');
  const prevButton         = document.getElementById('prev-btn');
  const nextButton         = document.getElementById('next-btn');

  var films        = document.getElementById('film-carousel').getAttribute('data');
  var currentIndex = 0;

  // Initial update
  updateFilm();

  // Function to update the displayed film
  function updateFilm() {
    currentFilmElement.innerHTML = `<strong>Title:</strong> ${films[currentIndex].primaryTitle} <br><p></p>`;
  }

  // Event listener for the previous button
  prevButton.addEventListener('click', function () {
    currentIndex = (currentIndex - 1);
    if(currentIndex < 0) {
      currentIndex = 0;
    }
    updateFilm();
  });

  // Event listener for the next button
  nextButton.addEventListener('click', function () {
    currentIndex = (currentIndex + 1);
    updateFilm();
  });
};

Currently I am trying to pass it as a data attribute which i am accessing in the scipts/index.js file, but when I try to use the array here I get errors, and rather than seeing film data it is in the format [object object], [object object] etc.
Can anyone advise?

Angular ReactiveForm does not change its value after it is prefilled

I use a reactiveForm for an edit mode. I use patchValue to prefill the data that I want to edit. The UI works fine but the value of the form never changes.

I check what happens when I change a value :

public ngOnInit(): void {
        this.form.valueChanges.subscribe(value => {
            this.changeDetectorRef.detectChanges();
            console.log('value has changed', value); // Return updated values of the form
            console.log(this.form.value); // return initial value of the form
        });
}

I don’t understand why the form value doesn’t change. And What is more disturbing : if I refresh the page after the form as loaded, I don’t have any issue.

Any Idea on where I should investigate?

Can’t link and display images in ParcelJS

I have a problem with my project in react with parcel. The problem is that the images are not shown. Does anyone know why and how to solve the problem?The images folder is a subfolder of the folder where the react components are also loaded correctly, so it should work. For the configuration I don’t have the configuration file but use the json package.
The fonts seem to work instead

I put the image in the same directory but didn’t work

React: this.forceUpdate and passing state through react-router-dom Link component

I solved my own problem already but I have no clue as to what’s happening and why it works.

I have a Link component that Link to the same page it’s currently on, but for a different product. So the same component but displaying a different product.
<Link to={directUrl} onClick={() => this.forceUpdate} state={{ urlPicture: picture }}> (Do note is in a sub-component, not the main component it routes to itself.)

Because it routes to the same page, Link doesn’t automatically refresh the page. To solve this I added onClick={() => this.forceUpdate}, but now my state didn’t pass properly. I checked this with the following lines of code in the other component.

location = useLocation()
const [ firstImage, setFirstImage ] = useState(location.state?.urlPicture || null)
console.log(`here is ${mainPicture}`) //mainPicture is just a string

However, when I replace onClick={() => this.forceUpdate} with onClick={() => window.location.reload()}, then my state does pass properly through the Link.

I do know that there is a difference between the 2 and that this.forceUpdate is the lighter of the 2, but to my knowledge it should refresh the component and update it’s state. I don’t see why it’s not sufficient and honestly I have no clue why it’s working the way it does.

Thanks in advance.