NestJS Passport Local ends up never responding

I’m trying to implement authentication system described in https://docs.nestjs.com/recipes/passport using Passport Strategies and Guards. When I use AuthGuard('local') to validate and issue jwt tokens to users I end up waiting for response forever. Here are my code snippets

// auth.module.ts
@Module({
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy, JwtStrategy, RefreshJwtStrategy],
  imports: [
    UsersModule,
    ConfigModule,
    PassportModule,
    JwtModule.registerAsync({
      inject: [ConfigService],
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        secret: configService.get<string>('JWT_SECRET_KEY'),
        signOptions: {
          expiresIn: configService.get<string>('JWT_ACCESS_TOKEN_TTL'),
        },
      }),
    }),
  ],
})
export class AuthModule {}
// auth.service.ts
export class AuthService {
  constructor(
    private readonly userRepository: UsersRepository,
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
  ) {}

  /**
   * Return user with given username and matching password.
   * @param email User's email.
   * @param password User's password.
   */
  public async validateUser(
    email: string,
    password: string,
  ): Promise<User | null> {
    const user = await this.userRepository.getUserByEmail(email);

    if (user && (await compare(password, user.password))) return user;

    return null;
  }

  public async createTokenPair(user: any): Promise<TokenPairEntity> {
    // This is omitted for the sake of brevity.
  }
}
// users.repository.ts
@Injectable()
export class UsersRepository {
  public constructor(
    @InjectModel(User.name) private readonly userModel: Model<User>,
  ) {}

  public async getUserByEmail(email: string): Promise<User | null> {
    return this.userModel.findOne({ email }).select(['-__v']).exec();
  }

  // Other methods are omitted for the sake of brevity.
}
// auth.strategy.ts
@Injectable()
export class LocalStrategy extends PassportStrategy(Passport, 'local') {
  public constructor(private readonly authService: AuthService) {
    super({ usernameField: 'email', passwordField: 'password' });
  }

  public async validate(email: string, password: string): Promise<User> {
    const user = await this.authService.validateUser(email, password);

    if (!user) throw new UnauthorizedException();

    return user;
  }
}
// auth.guards.ts
export class LocalAuthGuard extends AuthGuard('local') {}
// auth.controller.ts
@Controller('auth')
export class AuthController {
  public constructor(private readonly authService: AuthService) {}

  @Post('login')
  @UseGuards(LocalAuthGuard)
  public async login(@Request() req: Req): Promise<TokenPairEntity> {
    return this.authService.createTokenPair(req.user);
  }
}

After some debugging I found that my request gets stuck in LocalGuard.canActivate().

// auth.guards.ts
export class LocalAuthGuard extends AuthGuard('local') {
  public canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const result = super.canActivate(context);
    console.log(result);
    return result;
  }
}

Here console.log(result) prints Promise { <pending> }. LocalStrategy’s validate method is not reached after this.

Python Flask Socket as Listener for Database Changes

I want to make a Websocket that sends a message to the connected clients when something changes in a specific table in the database. I already have the functions for changing items in the db and want to call a function that notifies the clients.

def addXtoDB(...):
    # code to add...
    notifyClients();

def editXtoDB(...):
    # code to edit...
    notifyClients();


def notifyClients();
    # ??

And how can I access that in Javascript/Typescript?

NextJS: directly forward request to backend and response to client in /api

My project stack consists of a Next.js server to handle front-end and a separate backend server to store user data etc,.

When a client wants to send a request to the back end, they send an API request to the Next.js server, which then gets data from the separate backend server.

The problem is, I can’t figure out how to forward these requests to the server and the response from the server to the client without data being lost, or the code being very messy.

This is what I’m using right now:

export default function handler(req: NextApiRequest, res: NextApiResponse){
    fetch(url, {
        method: "post",
        body: req.body
     }).then(response => res.status(200).json(response.body))
}

Obviously, with this solution, the headers are lost. I could manually add a headers field, but that was just an example. There are lots of other fields to add, and I’m looking for a way to include all of them.

Important Note: the reason I have to intercept the request is to insert JWT token.

Google map car icon rotation

How can I rotate car icon (svg file) right, left, up, down by the latitude and longitude values from current driver’s driving route.

I’ve a method that bears a angle but it is requiring From Lat/Long to To Lat/Lang, driver is returning only current latitude/longitude values as it is driving on road without destination.

My requirement is I should be able to see my active drivers on google map driving and taking turns on roads like right, left without any destination or pickup location.

Need a javascript function to rotate car icon by current driver’s latitude/longitude.

Thanks,
Abdul

Need a javascript function to rotate car icon by current driver’s latitude/longitude.

Foreach loop solution in Php or JavaScript

I want to create a foreach loop where I compare a value A with a different value (Value (n)) with each loop , and if the value A is greater than the value (n) the loop should continue till the items in loop are finished.

But the catch is that I want the value of A to be subtracted from by the value (n) it was compared to, with each interaction. So that in the next iteration
Value A is less than it was in the previous loop
i.e new value of A = value A – Value (n).

Don’t know how to return the new value of A to the ongoing foreach loop

I can’t seem to figure it out yet. Lack of knowledge I guess.

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 ?