React Router v6 refreshing page when previous path was different

I have some question about forcing to reload page.
I have context provider who is fetching data on the first render.
I have different paths, on homepage I’m showing that fethced data.

But if user changes path (route) to for example “/about” and he come back to “/” i want to make that page will be refreshed (for fetching data on more time). Hmm, how can I achieve this?

how to rotate vector around axis in world coordinates?

I have an axis in world coordinates, as defined by 2 vectors, for example one that points upwards at x = 10:

const axisStart = new Vector3(10, 0, 0)
const axisEnd = new Vector3(10, 0, 1)

I’m getting the normalized axis direction like so:

const axisDirection = new Vector3().subVectors(axisEnd, axisStart).normalize()

How can I rotate a vector (e.g. Vector3(50, 0, 0)) around my original axis?

I’ve tried using Vector3.applyAxisAngle(axisDirection , radians), but because the axis has been normalized, the rotation happens around the world center (0, 0) and not around the axis’ original position.

SQL Parse Error Using JavaScript with Express and MySQL

I am trying to make a log in system. Right now I am working on allowing the user to register. I am trying to make it so you can’t create an account that has the same username or email as another. However, it is giving me a parse error.

Here is the code:

app.post("/create", (req, res) => {
  const email = req.body.email;
  const username = req.body.username;
  const password = req.body.password;

  db.query("SELECT email, username FROM users WHERE email = ? AND username = ?"),
    [email, username],
    (err, result) => {
      if (err) {
        console.log(err);
      } else if (result) {
        res.send("Username or Email is already in use.")
      } else {
        db.query(
          "INSERT INTO users (email, username, password) VALUES (?,?,?)",
          [email, username, password],
          (err, result) => {
            if (err) {
              console.log(err);
            } else {
              res.send("Values Inserted");
            }
          }
        );
      }
    };
});

Here is the error I am getting:

{
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND username = ?' at line 1",
  sqlState: '42000',
  index: 0,
  sql: 'SELECT email, username FROM users WHERE email = ? AND username = ?'
}

How to make 1 year timeout – node

im making a bot in node and i wanted to make a timeout with the lenght of 365 days, and node doesn’t allow me to do it, how can i do it?

Current Code:

setTimeout(() => {
 talkedRecently.delete(message.author.id);
}, 31536000000);

Output:

(node:21788) TimeoutOverflowWarning: 31536000000 does not fit into a 32-bit signed integer.

Thanks in advance!

How to update lists after delete a category

I want to update the Category list after delete a category, I used custom hook for fetching data from the server. I’m not sure how to update state on custom fetch hook

const {data, error, loading} = useFetch("/api/admin/category");
    const [category, setCategory]= useState([]);

    useEffect(() => {
        setCategory(data)
    },[])

    const deleteHandler = (id) => {

        const deleteRequest = async () => {
            const data = await axios.delete(`/api/admin/category/${id}`);
            return data;
        }

        deleteRequest()
            .then(res => {
                data.filter((item) => {
                    return id !== item.id;
                })
            })
    }

Can WinForms be used to create an app that has functionality similar to Chrome extensions? Detecting what was clicked, modifying CSS.. etc

I am interested in creating a visual web scraper. Visual meaning the user clicks in a web page to decide what elements to scrape and the app knows what the user clicked on. The user doesn’t need to be technical and knows CSS or XPath. Some Chrome extensions do this like https://dataminer.io and AnyPicker.

Then I came across ScrapeStorm which is a desktop app and does the same thing without using a Chrome extension. It’s an Electron app.

I don’t have experience developing Chrome Extensions or using Electron.

I know .NET and Javascript. My question is.. can I develop a desktop app similar to Scrapestorm using WinForms and using some type of a browser control in it and be able to fully interact with the control?
What libraries and technologies do I need so that C# code can interact with HTML elements and user actions in a browser control in realtime? (I think Electron uses BrowserWindow). The reason I am going with WinForms other than being familiar with it is that the app will be doing stuff with the scraped data using .NET and I prefer to do everything in a single .NET app.
I will also be looking at Electron.NET and see if maybe it’s a better choice, even though I am not familiar with Electron and Node.

What is the purpose of “additionalItems” property on arrays in rjsf?

I’m studying rjsf documentation and I’m confused about the additionalItems section of array docs.

Here is the example code from the docs:

const Form = JSONSchemaForm.default;

const schema = {
  type: "array",
  items: {
    type: "string"
  },
  additionalItems: {
    type: "boolean"
  }
};

ReactDOM.render((
  <Form schema={schema} />
), document.getElementById("app"));

and here is the official codepen

The rendered form seems to behave exactly the same if I remove the additionalItems, so what is the purpose? I guess it has one, since it’s explicitly brought up in the docs, but I can’t figure it out 🙂

How to avoid the browser to freeze with very long function

I’m trying to make a program to create a duty shifts table for a medical department.
To do that, i create all the possibile combination of doctor–>shift of all the days, then I have to create all possible combinations to select which are the bests.
This is an array of arrays combinations, which it can be so long, and browser stuck.
I read I can use setTimeout in my for loop, but I didn’t understand how.

I have this code (previously I used recursion but I read it’s better not to):

function newCombos (list, miglioriComb=[], punteggioX=[], current = []){
for (let a in list[0]){
for (let b in list[1]){
for (let c in list[2]){
for (let d in list[3]){
for (let e in list [4]){
current =[list[0][a],list[1][b],list[2][c],list[3][d],list[4][e]]; //create combinations
let tempODS=creaODS(current);//here I evaluate the combination
        let tempPunteggio=calcolaPenalty(tempODS);
//now I insert in an array the best combinations and in another array the best score(less is better)
        if (punteggioX.length===0) {punteggioX.push(tempPunteggio); miglioriComb.push(current); }
            else for (jj=0;jj<punteggioX.length; jj++){
            if (tempPunteggio<punteggioX[jj]) {
                    punteggioX.splice(jj, 0, tempPunteggio);
                miglioriComb.splice(jj, 0, current);
                if (punteggioX.length>lunghezzaMax){ punteggioX.splice(-1); miglioriComb.splice(-1);} 
                    break;}
        else if (punteggioX.length<lunghezzaMax) {punteggioX.push(tempPunteggio); miglioriComb.push(current);}}
      
}}}}}
return {miglioriComb, punteggioX};}

list is something like this (but with much much more values):

[
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
];

How can I put in this code a setTimeout to avoid the browser to stuck?

Is there a way to return in console.log or in the HTML at which point is the function (like a percentage)?.

Is better to use a webworker?

Thanks a lot

how to hanlde the exception for nestjs websocket of adapter @nestjs/platform-ws

I am trying to send the exception using nestjs websocket based on conditions, tried using

throw new WsException(‘Invalid data’);

but not sending any exception

Here is the sample code

import WebSocket from 'ws';
import {
  SubscribeMessage,
  WebSocketGateway,
  WsException,
} from '@nestjs/websockets';

@WebSocketGateway({ path: '/api' })
export class MainGateway {
  @SubscribeMessage('message')
  handleMessage(client: WebSocket, payload: any) {
    if (payload.id === 4) {
      throw new WsException('Invalid Data');
    }
    client.send(JSON.stringify({ id: payload.id }));
  }
}

and I’m creating the connection using angular here is the code snippet

export class WsComponent implements OnInit {
  public value!: number;
  public subject$ = webSocket('ws://localhost:3000/api');

  ngOnInit(): void {
    const event = { event: 'message', data: { id: 4 } };

    this.subject$.subscribe({
      next: (v: any) => (this.value = v.id),
      error: (e) => console.error(e),
      complete: () => console.info('complete'),
    });

    this.subject$.next(event);
  }
}

Please help me to solve the issue

JavaScript insert value into event.target.files

I have JavaScript that invokes the File Open dialogue, and the a handler to process the selected file, and store the filename into a database (as a ‘recent files’ list).

The handler gets the file name from event.target.files[0], opens it, reads the contents.

When retrieving the recent files list from the database, I would like to render the file as href ​link, which when clicked would invoke the same handler as if the file had been selected from the File Open Dialogue.

The handler is as follows:

function readFile(e) {
  var file = e.target.files[0];
  if (!file) return;
  var reader = new FileReader();
  reader.readAsText(file);
.
.
}

How can I insert the filename into e.target.file[0] so I can call the same readFile function as is called when selecting the file from File Open Dialogue?

Currently I have this:

<a href=''
   onclick='e.target.file[0] = file_path; readFile(e);'>
 file-name </a>

Add class to element when clicked elsewhere + condition on class presence

I’m having a sliding menu with sub-menus. I’m trying to hide an element in the navigation row when a user clicks one of the parent menu item that has a sub-menu (clicks on the expand arrow) + I want to show back the hidden element when the users clicks back to the top-level menu.
My menu’s <ul> element get’s a class of slide-menu-is-active-parent when any of the sub-menus is open.

This is a simple version of my row html:

<div class="navigation row">
  <nav>
    <ul id="nav-menu">
      <li>Menu item 1</li>
        <span class="submenu-button">
        <ul class="sub-menu">
          <li>Sub-menu item 1</li>
          <li>Sub-menu item 2</li>
          <li>Sub-menu item 3</li>
        </ul>
      </li>
      <li>Menu item 2</li>
        <span class="submenu-button">
        <ul class="sub-menu">
          <li>Sub-menu item 1</li>
          <li>Sub-menu item 2</li>
          <li>Sub-menu item 3</li>
        </ul>
      </li>
    <ul id="nav-menu">
  <nav>
</div>

<div class="content-row">
  [whatever content...]
</div>

I tried the following script to add a class od menu-open to the some-content element when both conditions are met: the user clicks on the sub-menu button and when the <ul id="nav-menu"> element get’s the slide-menu-is-active-parent class when opened. And with the class added to my content row, I could use simple .content-row.menu-open{display:none} to hide it.

function($) {
    $("#nav-menu .submenu-button").click(function(){
        if ($('#nav-menu').hasClass('slide-menu-is-active-parent')) {
            $('.content-row').addClass('menu-open');
        } else {
            $('.content-row').removeClass('menu-open');
        }
    });  
});

But that doesn’t work. Any tips on where my script is lacking?

Javascript substring replace and output

Hi guys I wonder how to reconstruct string. I need to replace br tag inside string with ‘n’ new line character. So I’m simply doing it like this:

let a='Some<br>Text'
let b=a.replace(/<br>/gi, 'n');

But when I try to make an output to console this way:

console.log(JSON.stringify(b))

It shows the string like this:

SomenText

But if I’m doing output this way:

console.log(b)

It returns:

Some
Text

So why? And is it possible to use console.log(JSON.stringify(b)) to show the string in a proper way. I mean like this:
Some
Text

Logging out after posting

im getting error, that my logging status is refreshed after posting and when i tried to repair it i just got more errors and i dont know how to straighten everything. Here i publish my code, if u can help me or get me any advise i will be very thankful. Thanks.

I guess that its all in the “isAuth” and “setIsAuth” but idk, and it looks to me, like the only one of them is needed, but im trying to learn from tutorial where both were used

App.js

import React, { Component } from 'react';
import './css/main.css';
import { BrowserRouter as Router, Routes, Route, Link, Navigate } from 'react-router-dom';
import Home from './pages/Home';
import CreatePost from './pages/CreatePost';
import Calendar from './pages/Calendar';
import Login from './pages/Login';
import { signOut } from 'firebase/auth'
import { auth } from './firebaseconf';


class App extends Component {


  constructor(props) {
    super(props);
    this.state = {
      setIsAuth: false,
      isAuth: false
    };
  }


  signIn = () => {
    this.setState({ setIsAuth: true });
  }

  signUserOut = () => {
    signOut(auth).then(() => {
      localStorage.clear();
      this.setState({ setIsAuth: false });
      window.location.pathname = "/login";
    });
  }

  render() {
    return (
      <Router>
        <nav>
          <Link to="/">Home</Link>
          {!this.state.isAuth ? (
            <Link to="/login">Login</Link>
          ) : (
            <>
              <Link to="/createpost"> Create New Post</Link>
              <Link to="/calendar"> Calendar</Link>
              <button onClick={this.signUserOut}>Log out</button>
            </>
          )}
        </nav>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/login" element={<Login setIsAuth={this.signIn} />} />
          <Route path="/createpost" element={<CreatePost setIsAuth={this.signIn} />} />
          <Route path="/calendar" element={<Calendar />} />
        </Routes>
      </Router>


    );
  }
}

export default App;

CreatePost.js

import React, { Component } from 'react';
import { addDoc, collection } from 'firebase/firestore';
import { db } from '../firebaseconf';

class CreatePost extends Component {
    constructor(props) {
        super(props);
        this.state = {
            setTitle: "",
            setPostText: "",
        };
    }

    sTitle = (event) => {
        this.setState({ setTitle: (event.target.value) });
    }

    sPostText = (event) => {
        this.setState({ setPostText: (event.target.value) });
    }

    collectionRef = collection(db, "posts");

    createPost = async () => {
        await addDoc(this.collectionRef, { title: this.state.setTitle || null, postText: this.state.setPostText || null });
        window.location.pathname = "/";
    }


    render() {
        return (
            <div className="cpPage">
                <div className="cpContainer">
                    <h1>Create a Post</h1>
                    <div className="inputGp">
                        <label>Title:</label>
                        <input
                            placeholder="Title..."
                            onChange={this.sTitle}
                        />
                    </div>
                    <div className="inputGp">
                        <label>Post:</label>
                        <textarea
                            placeholder="Write your post..."
                            onChange={this.sPostText}
                        />
                    </div>
                    <button onClick={this.createPost}>Add your post</button>
                </div>
            </div>
        );
    }
}
export default CreatePost;

Login.js

import React from 'react';
import { auth, provider } from '../firebaseconf';
import { signInWithPopup } from 'firebase/auth';
import { useNavigate } from 'react-router-dom';

function Login(setIsAuth) {
    let navigate = useNavigate();

    const singInWithGoogle = () => {
        signInWithPopup(auth, provider).then((result) => {
            localStorage.setItem("isAuth", true);
            setIsAuth();
            navigate("/");
        });
    };

    return (
        <div>
            <button onClick={singInWithGoogle}>Sign in with Google</button>
        </div>
    );

}
export default Login;