App.use() necessary on only certain browsers?

I was just setting up a project and trying to set up a favicon. For some reason I require app.use on chrome, but not on any other browers. I am unsure as to why.


root - server.js, views, images
views - index.ejs 
images - yuhyuh.png

This is the basic layout of what I have right now
I have rendered index.ejs and I was trying to set up a favicon which I did using


    <link rel="icon" href="/images/yuhyuh.png">

and for some reason it wasn’t showing up at all on chrome, so I used this snippet I found online without really understanding what it really does or why it is even necessary at all

    app.use("/images", express.static('images')); 

It worked, but I realized that when I delete this piece the favicon still shows up on every other browser except for Chrome. I tested Microsoft Edge, Firefox, even Opera GX. Is this line necessary, is it showing up because I am locally hosting? I am unsure as to whether I need to keep this and why it occurs.

I tried to read into the documentation of app.use() and it referenced middleware, I understand that this is running the image through express.static? To showcase images within my express function, but to my understanding ejs is just html mixed up with js and this would not be required when rendering an html page, so I dont see why it is necessary now. I apologize if this seems like a question I can easily google, most of those sources left me more confused than not.

Django – Redirection to Strava API Auth Page is not working

So I’m Trying to redirect my django web app after the user submitted the form AND if the user chose ‘Strava Link’ Option from the form.

What I’m currently doing is to open Strava’s API Authorization Page for code/token exchange so my app will fetch the data from user’s Strava account.

My current problem is that it does not redirect to my Strava API’s Authorization page (No Error, nothing) and I tried printing the Authorization URL so I can debug it. I Tried Manually opening the Authorization URL and It is working.

I’ve watched some Strava API tutorials using python and all of them manually enters the link to copy the code after the user clicked ‘Authorized’.

Is My method correct?

Form Submission -> Redirect the user to Strava’s API Authorization
Page (stuck on this step) -> Callback to return the code/token ->
Fetch the data

Here’s my current code innside views.py:

async def index(request):
    if request.method == 'POST': #Start of process after Form Submitted
        try:
            data_dict = link_validation(request, data_dict) 
            #Rest of the code Here (Irrelevant and not related to Strava API)
        except Exception as e:
            return render(request, 'index.html', {'error_message': str(e)})
    else:
        return render(request, 'index.html')
        

def link_validation(request, data_dict):
    redirect_to_strava_auth(request)
    #Rest of the code logic here to be put when Strava API Authorization is solved

def redirect_to_strava_auth(request):
    auth_url = f"https://www.strava.com/oauth/authorize?client_id={STRAVA_CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&approval_prompt=force&scope=read,profile:read_all,activity:read"
    print("Redirect URL:", auth_url) #Prints a valid link and I tried opening it in browser manually, it works
    return redirect(auth_url) #This is the problem I can't solve (Not producing any error, just no redirection) 
    
#This function will be executed right after the user clicked the 'Authorize' on my Strava API
def exchange_code_for_token(request):
    code = request.GET.get('code')
    
    token_url = "https://www.strava.com/oauth/token"
    payload = {
        'client_id': STRAVA_CLIENT_ID,
        'client_secret': STRAVA_CLIENT_SECRET,
        'code': code,
        'grant_type': 'authorization_code'
    }
    response = requests.post(token_url, data=payload)
    if response.status_code == 200:
        access_token = response.json()['access_token']
        # Save access_token to the user session or database
        return HttpResponseRedirect('/index/')  # Redirect to success page or any other page
    else:
        return HttpResponse("Error exchanging code for access token")

Here’s my current Strava API Settings:

enter image description here

Here’s the current step by step demo of my current progress on youtube video
(Ignore the error message that appeared in card as it is not related to API Redirection).

YOUTUBE: django strava API redirection to auth page not working

Alternative Solution Idea (In case my method won’t really work) – Via JavaScript:

Conditional Check on javascript if auth code already exists -> Put the
Authorization Page as <a href = ""> on Form -> User manually clicks
the link -> User Authorizes my API -> Redirect back to my django app
along with Auth Code/Token and store it in session -> Pass the code when form is submitted to views.py

Animation to move the photo frame

I would like to create a wavy animation and apply it to a photo placed in a scene, is there a way to do this?
Youtube achieves it with css, but css cannot be applied to objects, so I am looking for another way.
Can someone please help me?

I looked for documentation, but could only find videos that were realized with css.

Using JS – how do I make a chart like this?

enter image description here

I’ve been trying to get this made using Chart.js or even ApexCherts – but haven’t been able to do it. The closest this looks like is a Polar Chart, this is what I have so far:

enter image description here

This is my code:

 <div class="my-4">
                <canvas id="myRadarChart"></canvas>
            </div>

 <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
{{-- <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-labels-dv"></script> --}}
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>
<script src="https://unpkg.com/chart.js-plugin-labels-dv/dist/chartjs-plugin-labels.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const chartDataObj = @json($responseData['chartData']);

        const chartData = {
            labels: chartDataObj.labels,
            datasets: [{
                    label: 'Personal Data',
                    data: chartDataObj.personalData,
                    fill: true,
                    backgroundColor: 'rgba(255, 99, 132, 0.2)', // Light pink fill
                    borderColor: 'rgb(255, 99, 132)', // Pink border
                    pointBackgroundColor: 'rgb(255, 99, 132)', // Pink points
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgb(255, 99, 132)'
                },
                {
                    label: 'Organisation Data',
                    data: chartDataObj.orgData,
                    fill: true,
                    backgroundColor: 'rgba(54, 162, 235, 0.2)', // Light blue fill
                    borderColor: 'rgb(54, 162, 235)', // Blue border
                    pointBackgroundColor: 'rgb(54, 162, 235)', // Blue points
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgb(54, 162, 235)'
                }
            ]
        };

        const options = {
            elements: {
                line: {
                    borderWidth: 5,
                    tension: 0.8, // Adjust this value for more or less curvature
                },
                point: {
                    radius: 10
                }
            },
            scales: {
                r: {
                    angleLines: {
                        display: false
                    },
                    suggestedMin: 40,
                    suggestedMax: 100,
                    ticks: {
                        backdropColor: 'transparent',
                        stepSize: 20
                    },
                    pointLabels: {
                        font: {
                            size: 15 // Reduced for a more professional look
                        },
                        color: '#666'
                    },
                    grid: {
                        color: 'rgba(0, 0, 0, 0.0)'
                    }
                }
            },
            plugins: {
                labels: {
                    render: 'label',
                    arc: true,
                    position: 'outside',
                    fontColor: '#666',
                    fontSize: 9,
                    outsidePadding: 4,
                    textMargin: 4,
                    fontStyle: 'normal',
                },
                legend: {
                    display: false, // Set to true for professional charts to identify datasets
                    position: 'top' // A common position for legends in professional reporting
                },
                filler: {
                    propagate: true
                },
                tooltip: {
                    usePointStyle: true, // Use point style for better readability
                    backgroundColor: 'rgba(0,0,0,0.8)' // Semi-transparent black for a sleek look
                }
            },
            maintainAspectRatio: true,
        };

        // Chart.register(ChartDataLabels);
        const config = {
            type: 'polarArea',
            data: chartData,
            options: options
        };


        const myRadarChart = new Chart(
            document.getElementById('myRadarChart'),
            config
        );
    });
</script>

Even to get the labels to curve, I had to resort to a plugin. But then again, it’s far from what I need. Is there a Chart library that helps me get this result? Or a plugin that can help me achieve this?

Connecting a HTML Form to a Firebase Database

There is a similar question to this but it’s from almost a decade ago.

I’ve got a HTML Form which gets filled out and console.log printed out. I’ve got my firebase database. I’m just having so many issues trying to get them to connect. I know the firebase database is set up correct as I’ve been able to connect and send hard coded data to it via a python script

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form</title>
  <script src="https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.6.7/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.6.7/firebase-firestore.js"></script>
</head>
<body>
  <h1>Form</h1>
  <form id="contactForm">
    <label for="first">First Name:</label><br>
    <input type="text" id="first" name="first"><br>

    <label for="last">Last Name:</label><br>
    <input type="text" id="last" name="last"><br>

    <label for="email">Email:</label><br>
    <input type="email" id="email" name="email"><br>

    <label for="phone">Phone:</label><br>
    <input type="tel" id="phone" name="phone"><br><br>

    <button type="submit">Submit</button>
  </form>
  <script src="app.js"></script>
</body>
</html>

I’ve tried many different ways to connect this via JS but I just cant seem to work it out

var firebaseConfig = {
apiKey: "APIKEY",
authDomain: "AUTHDOMAIN",
databaseURL: "DATABASEURL",
projectId: "PROJECTID",
storageBucket: "STORAGEBUCKET",
messagingSenderId: "MESSAGINGSENDERID",
appId: "APPID"

};

firebase.initializeApp(firebaseConfig);

var db = firebase.database();

document.getElementById('contactForm').addEventListener('submit', function(e) {
    e.preventDefault();
    print("Test")
    var first = document.getElementById('first').value;
    var last = document.getElementById('last').value;
    var email = document.getElementById('email').value;
    var phone = document.getElementById('phone').value;
    print("Test2")
    db.ref('users').push({
        first : first,
        last : last,
        email : email,
        phone : phone,
    })
    print("Test3")
    .then(() => {
        print("Test4")
        console.log("Data submitted successfully.");
        document.getElementById('contactForm').reset();
    })
    .catch((error) => {
        console.error("Error submitting data: ", error);
    });
});

from flask import Flask, request

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit_form():
    data = request.form

    print(data)
    return 'Form submitted successfully'

if __name__ == '__main__':
    app.run(debug=True)

I’m completely lost at this point and have absolute no clue. When I try to import

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

This seems to break for whatever reason console.log but if I don’t firebase is undefined.

I need help. Please

Why am i getting error “Uncaught ReferenceError: increment is not defined”

The code looks fine but still gets the error added event handler also



document.addEventListener('DOMContentLoaded', function() {
    
    let count = 0
    let countEl = document.getElementById("count-el")
    function increment() {
        count = count + 1
        countEl.innerText=count;
        // set countEl's innerText to the count
    }
    increment()
countEl.addEventListener("click", increment);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./index.js"></script>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <h1>People entered:</h1>
    <h2 id="count-el">0</h2>
    <button id="increment-btn" onclick="increment()">INCREMENT</button>
</body>
</html>

Please check the code, the error shows for this line INCREMENT Specifically for “INCREMENT” in that line

Trying to save an array from a class in local storage and retrieve it on load

I’m trying to set an item within local storage and have it be able to update every time the user either adds a new book, deletes a book, or changes the read status of the book.

So far i have added an array within the Books class and set its value to get the item from the local storage if there is one already and if not, the array will be empty. I also added a method to the same class which is suppose to set the item into local storage as well as turn it into a sting via the JSON method but it does not seem to save it because when i inspect it and look into the local storage its length is equal to 0.

const libraryDOM = {
    bookDisplay: document.getElementById("book-display"),
    addBookBtn: document.getElementById("new-book"),
    titleInput: document.getElementById("title"),
    titleError: document.getElementById("title-error"),
    authorInput: document.getElementById("author"),
    authorError: document.getElementById("author-error"),
    pagesInput: document.getElementById("pages"),
    pagesError: document.getElementById("pages-error"),
    bookForm: document.getElementById("form"),
    subBtn: document.getElementById("submit-btn")
};

class Book {
    constructor(name, author, pages) {
        this.name = name;
        this.author = author;
        this.pages = pages;
        this.read = false;
    }
    get nameOfBook() {
        return this.name;
    }
    get authorOfBook() {
        return this.author;
    }
    get numOfPages() {
        return this.pages;
    }
}

class Books {
    constructor() {
        this.bookArr = JSON.parse(localStorage.getItem("bookArr")) || [];
    }
    addBookToArray(name, author, pages) {
        let book = new Book(name, author, pages);
        this.bookArr.push(book);
        this.saveBooksToLocalStorage(); // Save books to local storage after updating
        return book;
    }
    changeReadStatus(book) {
        book.read = true; // Set the read status
        this.saveBooksToLocalStorage(); // Save books to local storage after updating
    }
    saveBooksToLocalStorage() {
        localStorage.setItem("bookArr", JSON.stringify(this.bookArr));
    }
    get allBooks() {
        return this.bookArr;
    }
}

let newBook = new Books();
let bookArray = newBook.allBooks;

function renderBooks(book) {
    const newBookDiv = document.createElement("div");
    const dltBtn = document.createElement("button");
    const readBtn = document.createElement("button");
    newBookDiv.textContent = book.nameOfBook + " " + book.authorOfBook + " " + book.numOfPages;
    newBookDiv.classList.add("book");
    dltBtn.textContent = "Delete";
    readBtn.textContent = "Read";
    newBookDiv.append(dltBtn, readBtn);
    libraryDOM.bookDisplay.append(newBookDiv);
    dltBtn.addEventListener("click", (i) => {
        if (bookArray[i] == dltBtn[i]) {
            bookArray.splice(bookArray.indexOf(book), 1);
            newBookDiv.remove();
            dltBtn.remove();
            newBook.saveBooksToLocalStorage(); // Save books to local storage after updating
            console.log(bookArray);
        }
    });
    readBtn.addEventListener("click", (i) => {
        if (bookArray[i] == readBtn[i]) {
            newBook.changeReadStatus(book);
            console.log(bookArray);
        }
    });
}

libraryDOM.addBookBtn.addEventListener("click", addBook);
libraryDOM.subBtn.addEventListener("click", submitBook);

function addBook() {
    libraryDOM.bookForm.style.visibility = "visible";
    console.log("click");
}

function submitBook(e) {
    const title = libraryDOM.titleInput.value;
    const author = libraryDOM.authorInput.value;
    const pages = libraryDOM.pagesInput.value;
    if (libraryDOM.titleInput.validity.valueMissing) {
        libraryDOM.titleError.style.display = "flex";
        e.preventDefault();
    } else { 
        libraryDOM.titleError.style.display = "none"; 
        e.preventDefault();
    }
    if (libraryDOM.authorInput.validity.valueMissing) {
        libraryDOM.authorError.style.display = "flex";
        e.preventDefault();
    } else {
        libraryDOM.authorError.style.display = "none";
        e.preventDefault();
    }
    if (libraryDOM.pagesInput.validity.valueMissing) {
        libraryDOM.pagesError.style.display = "flex";
        e.preventDefault();
    } else {
        libraryDOM.pagesError.style.display = "none";
        e.preventDefault();
    }
    if (libraryDOM.titleInput.validity.valid &&
        libraryDOM.authorInput.validity.valid &&
        libraryDOM.pagesInput.validity.valid) {
        const pushBooks = newBook.addBookToArray(title, author, pages);
        libraryDOM.bookForm.style.visibility = "hidden";
        renderBooks(pushBooks);
        console.log(bookArray);
        e.preventDefault();
    }
}

bookArray.forEach(renderBooks);

Flask-SocketIO: Python code can send, but cannot receive. JavaScript code can receive, but cannot send

I am working on a multiplayer web game that uses Flask-SocketIO for real-time communication between the server and clients. However, I am facing an issue where the Python code can successfully send data to the clients, but it cannot receive any emissions from the JavaScript code. On the other hand, the JavaScript code can receive data from the server, but it is unable to send any emissions back.

I apologize in advance for bad code or stupid mistakes, I am new to sockets and do not fully understand them.

Here is a summary of the issue:

  • The Python code is using Flask-SocketIO and includes event handlers for the ‘player_data’ event.
  • The JavaScript code is using the SocketIO library and includes event handlers for the ‘player_data’ event.
  • The client successfully connects to the server, but when the Python code emits the ‘player_data’ event, the JavaScript code DOES receive it.
  • However, when the JavaScript code emits the ‘player_data’ event, the Python code also does not receive it.

I tried to send real time player location data back and forth from my flask server and javascript. The sockets successfully connected, the initial user data is sent to the client, then the client tries to send data back, no errors are reported, but the code on the socket.on() function in my python code does get executed.

Expected Behaviour

  • The Python code should be able to emit ‘player_data’ events that the JavaScript client can receive.
  • The JavaScript client should be able to emit ‘player_data’ events that the Python code can receive.

Actual Behaviour

  • The Python code emits ‘player_data’ events and the JavaScript client receives them.
  • The JavaScript client emits ‘player_data’ events, BUT the Python code never receives them. No visible errors.

Javascript:

var players = {};
var socket = io('/game');

socket.on('connect', () => {
    console.log('Connected to server.');
});

socket.on('player_data', function(updatedPlayers) {
    console.log("Updated players data:");
    players = updatedPlayers;
    console.log(players);
});

var player_id = generateUserId(Object.keys(players));

function send_player_data(id, x, y) {
    console.log("Sending player data: " + id + " " + x + " " + y);
    socket.emit('player_data', {
        id: id,
        x: x,
        y: y
    });
}

send_player_data(id, x, y)

Javascript Output:

8game.js:116 Sending player data: 737510 768 662
game.js:108 Updated players data:
game.js:110 {}
game.js:104 Connected to server.
171game.js:116 Sending player data: 737510 768 662

Python Code:

@app.route('/game', methods=['GET', 'POST'])
def game():
    return render_template('game.html')

socketio = SocketIO(app, max_http_buffer_size=1000000)

players = {}

@socketio.on('connect', namespace='/game')
def handle_connect():
    print('Client connected')
    emit('player_data', players)

@socketio.on('disconnect', namespace='/game')
def handle_disconnect():
    print('Client disconnected')

@socketio.on('player_data', namespace='/game')
def handle_player_data(data):
    print('Player state update:', data)
    
    player_id = data['id']
    player_x = data['x']
    player_y = data['y']
    active = True 

    players[player_id] = {"x": player_x, "y": player_y, "active": active}

    emit('player_data', players, broadcast=True)

Python Output (This is obviously fills my console with repetitions so here’s a snippet):

INFO:werkzeug:127.0.0.1 - - [10/Mar/2024 02:41:20] "POST /socket.io/?EIO=4&transport=polling&t=OucF7WY&sid=ezy6IQ_nADGehX0LAAAC HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2024 02:41:20] "POST /socket.io/?EIO=4&transport=polling&t=OucF7XQ&sid=ezy6IQ_nADGehX0LAAAC HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2024 02:41:20] "POST /socket.io/?EIO=4&transport=polling&t=OucF7YI&sid=ezy6IQ_nADGehX0LAAAC HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2024 02:41:20] "POST /socket.io/?EIO=4&transport=polling&t=OucF7ZA&sid=ezy6IQ_nADGehX0LAAAC HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2024 02:41:20] "POST /socket.io/?EIO=4&transport=polling&t=OucF7a9&sid=ezy6IQ_nADGehX0LAAAC HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2024 02:41:21] "POST /socket.io/?EIO=4&transport=polling&t=OucF7bb&sid=ezy6IQ_nADGehX0LAAAC HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2024 02:41:21] "POST /socket.io/?EIO=4&transport=polling&t=OucF7eW&sid=ezy6IQ_nADGehX0LAAAC HTTP/1.1" 200 -

Optimizing JS long task without webworker – is setTimeout a good way and the only way? [closed]

I am trying to optimize some of my JS long tasks.

Using webworker is a good way but webworker can’t handle DOM. So I am thinking about using setTimeout to do this.

Looks it work great. But this setTimeout a good way to do this job? Is there any modern technologies to postpone some function calls?

Original code:

var time = 0;

window.setInterval(function () {
  time++;
  $('#timer').html(time);
}, 100);

$('#reset').on('click', function () {
  $('#output').empty();
  time = 0;
});

$('#button1').on('click', function () {
  var result;
  for (var i = 0; i < 1e9; i++) {
    result = i;
  }
  $('#output').html('Done! Counted to ' + result);
});

$('#button2').on('click', function () {
  var blob = new Blob(
    Array.prototype.map.call(
      document.querySelectorAll('script[type="text/js-worker"]'),
      function (oScript) { return oScript.textContent; }
    ),
    { type: 'text/javascript' }
  );

  // Create a new worker containing all "text/js-worker" scripts.
  var worker = new Worker(window.URL.createObjectURL(blob));

  // Listen for a message from the worker
  worker.addEventListener('message', function (e) {
    $('#output').html(e.data);
  }, false);

  // Start the worker
  worker.postMessage('');
});
<script type="text/js-worker">
  var result;
  self.addEventListener('message', function (e) {
    for (var i = 0; i < 1e9; i++) {
      result = i;
    }
    // Send message back to the main script
    self.postMessage('Done! Worker counted to ' + result);
  }, false);
</script>

<button type="button" id="button1">Run without Workers</button>
<button type="button" id="button2">Run with Workers</button>
<button type="button" id="reset">Reset</button>
<div>Timer: <span id="timer">0</span></div>
<div>Output: <span id="output"></span></div>

Optimized by setTimeout:

var time = 0;

window.setInterval(function () {
  time++;
  $('#timer').html(time);
}, 100);

$('#reset').on('click', function () {
  $('#output').empty();
  time = 0;
});

$('#button1').on('click', function () {
  var result;

  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
  }, 1000);
  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
  }, 2000);
  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
  }, 3000);
  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
  }, 4000);
  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
  }, 5000);
  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
  }, 6000);
  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
  }, 7000);
  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
  }, 8000);
  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
  }, 9000);
  setTimeout(()=>{
    for (var i = 0; i < 1e8; i++) {
      result = i;
    }
    $('#output').html('Done! Counted to ' + result);
  }, 10000);

});

$('#button2').on('click', function () {
  var blob = new Blob(
    Array.prototype.map.call(
      document.querySelectorAll('script[type="text/js-worker"]'),
      function (oScript) { return oScript.textContent; }
    ),
    { type: 'text/javascript' }
  );

  // Create a new worker containing all "text/js-worker" scripts.
  var worker = new Worker(window.URL.createObjectURL(blob));

  // Listen for a message from the worker
  worker.addEventListener('message', function (e) {
    $('#output').html(e.data);
  }, false);

  // Start the worker
  worker.postMessage('');
});
<script type="text/js-worker">
  var result;
  self.addEventListener('message', function (e) {
    for (var i = 0; i < 1e9; i++) {
      result = i;
    }
    // Send message back to the main script
    self.postMessage('Done! Worker counted to ' + result);
  }, false);
</script>

<button type="button" id="button1">Run without Workers</button>
<button type="button" id="button2">Run with Workers</button>
<button type="button" id="reset">Reset</button>
<div>Timer: <span id="timer">0</span></div>
<div>Output: <span id="output"></span></div>

discord.js: ‘ReferenceError: Message not defined’

im gonna go to make an open ai discord bot but this is happen
yesterday, i make open ai bot with SAME CODE like this but today it full with error
someone pls help me

require('dotenv/config');
const{ Client } = require('discord.js');
const{ OpenAI } = require('openai');

const client = new Client({
    intents: [
        'Guilds', 
        'GuildMembers', 
        'GuildMessages', 
        'MessageContent'],
});

client.on('ready', () => {
    console.log('gpt READY!')
})

const IGNORE_PREFIX = "!";
const CHANNELS = ['1041682904729800829', '1042040860382089297'];

const openai = new OpenAI({
    apiKey: process.env.OPENAI_KEY,
})

client.on('messageCreate', async (message) => {
    if (message.author.bot) return;
    if (message.content.startsWith(IGNORE_PREFIX)) return;
    if (!CHANNELS.includes(message.channelId) && !message.mentions.users.has(client.user.id)) return;

    const response = await openai.chat.completions.create({
        model: 'gpt-3.5-turbo-16k-0613',
        messages: [
            {
                // name:
                role: 'system',
                content: 'Chat GPT is a friendly chatbot.'
            },
            {
                // name:
                role: 'user',
                content: messages.content,
            }
        ]
    }).catch((error) => console.error('OpenAI Error:n',error));

    message.reply(response.choices[0].message.content);
});

client.login(process.env.TOKEN);

and this is happen

gpt READY!
node:events:496
      throw er; // Unhandled 'error' event
      ^

ReferenceError: messages is not defined
    at Client.<anonymous> (D:---------APPgpt discord.jsindex.js:41:26)

Node.js v20.11.1
[nodemon] app crashed - waiting for file changes before starting...

pls help me im a beginner javacript coder so pls help me
i apreciate you if you help me

How change function updateStyle in module ‘vite:css-post’ in vite?

My project is assembled using the vite package.

I need add all style in shadow dom.

I didn’t find a plugin that could do this.

My config

import react from '@vitejs/plugin-react';
import * as path from 'path';
import { defineConfig, splitVendorChunkPlugin } from 'vite';
import htmlPlugin from 'vite-plugin-html-config';
import { dependencies } from './package.json';

const exclVendors = ['react', 'react-router-dom', 'react-dom'];
function renderChunks(deps: Record<string, string>) {
  let chunks = {};
  Object.keys(deps).forEach((key) => {
    if (exclVendors.includes(key)) return;
    chunks[key] = [key];
  });
  return chunks;
}

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 8082,
  }
  envPrefix: 'APP_',
  resolve: {
    alias: [{ find: '@', replacement: path.resolve(__dirname, 'src') }],
  },
  plugins: [
    react(),
    htmlPlugin({ favicon: './src/assets/logo.svg' }),
    splitVendorChunkPlugin(),
  ],
  build: {
    sourcemap: false,
    rollupOptions: {
      output: {
        manualChunks: {
          ...renderChunks(dependencies),
        },
      },
    },
  },
});

But I found a module that does this.

it is plugin in vite with name ‘vite:css-post’

function cssPostPlugin(config) {

  return {
     name: 'vite:css-post'
     ....
  }
}

In

function updateStyle(id, content) { 
 ....

 if (!style) {
   style = document.createElement('style');
   style.setAttribute('type', 'text/css');
   style.setAttribute('data-vite-dev-id', id);
   style.textContent = content;
   try {
      const shadow = document.body.attachShadow({mode: 'open'});    
   } catch (e) {
                
   }
   
   // It is i chenged *document.head* to document.body.shadowRoot  
   
   document.body.shadowRoot.appendChild(style);
}
 ....
}

if change one line all work.

document.body.shadowRoot.appendChild(style);

How can I override this function in vite.config.ts ?

Is there a regex pattern to remove all numbers preceding every “<" in a string?

While I’ve utilized simple regex patterns for things like form validation and small string edits, this snippet has proven to be more challenging than my other tasks.
My current patterns perform a number of functions including adding line breaks at specific points.

...().replace(/^.s+|s+$/gm, '').replace(/>/g, ">r").replace(/(.{99})/g, "$1r"));


1<div class="form-group stacked" aria-live="polite" id="test-input">
2<label for="company">
3Business name4<sup>
5*6</sup>
7</label>
8<div class="input-wrapper is-clear">
9<input type="text" class="form-control stacked has-clear" id="company" name="company" required="" 
aria-required="true" value="">
10</input>
11<button class="btn clear-field-button" type="button" tabindex="0" style="display: inline-block;" 
aria-label="Clear Business name input field">
12<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 22.673 22.674">...

Should render as

<div class="form-group stacked" aria-live="polite" id="test-input">
<label for="company">
3Business name<sup>
5*</sup>
</label>
<div class="input-wrapper is-clear">
<input type="text" class="form-control stacked has-clear" id="company" name="company" required="" 
aria-required="true" value="">
</input>
<button class="btn clear-field-button" type="button" tabindex="0" style="display: inline-block;" 
aria-label="Clear Business name input field">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 22.673 22.674">...

Any guidance and/or solutioning is greatly appreciated.
Thank you.

Load SQL database saved MS word document to Syncfusion Document Editor

Model.Attchment contains the byte[] of the document. It comes to the client side with my script, but not displayed in the Document Editor.

This is the script I’m using :
`
var base64Content = “@Html.Raw(Convert.ToBase64String(Model.Attachment))”;
var documentEditor = new ej.documenteditor.DocumentEditor({
isReadOnly: false
});

documentEditor.appendTo('#documenteditor_titlebar');

// Function to load the document into the Document Editor
function loadDocument() {
    documentEditor.open({
        document: {
            fileContent: base64Content,
            fileName: "document.docx",
            fileType: "Docx",
        }
    });
}

// Load the document when the DOM content is fully loaded
document.addEventListener("DOMContentLoaded", function () {
    loadDocument();
});

`

Searching into an array of long strings specific things. Then save it on a JSON Object

I’m new. I’m working on a program that reads a bunch of docx documents. I get the document content from his XML with XPATH and xmldom. It gives me an array with every line of the document. The thing is, I have something like this:

[
  '-1911312-14668500FECHA:  15-12-25',
  'NOMBRE Y APELLIDO:  Jhon dee',
  'C.I.: 20020202                                  EDAD: 45                       ',
  'DIRECCION:  LA CASA',
  'TLF:  55555555',
  'CORREO: thiisatest@gmail',
  '                                            HISTORIA CLINICA GINECO-OBSTETRICA',
  'HO',
  'NULIG',
  'FUR',
  '3-8-23',
  'EG',
  '',
  'FPP',
  '',
  'GS',
  '',
  'GSP',
  '',
  '',
  'MC:  CONTROL GINECOLOGICO',
  'HEA',
  '',
  'APP:  NIEGA PAT, NIEGA ALER, QX NIEGA.',
  'APF: MADRE HTA, ABUELA DM.',
  '',
  'AGO: MENARQUIA:  10                FUR:                         CICLO:      4/28              ',
  '    TIPO: EUM',
  ' MET ANTICONCEP:  GENODERM DESDE HACE 3 AÑOS.',
  'PRS:                                      NPS:                                                   ITS: VPH LIE BAJO GRADO 2017 , BIOPSIA.',
  'FUC:  NOV 2022, NEGATIVA. COLPO NEGATIVA.',
  '',
  '',
  'EMBARAZO',
  '#/AÑO',
  'TIPO DE PARTO',
  'INDICACION',
  'RN',
  'SEXO',
  'RN',
  'PESO',
  'OBSERVACIONES',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  'EXAMEN FISICO:',
  'PESO:  80,1                  TALLA:                    TA: MMHG                    FC:                    FR: ',  
  '',
  'PIEL Y MUCOSA:  DLN',
  'CARDIOPULMONAR: DLN',
  '',
  'MAMAS: ',
  '',
  'ABDOMEN: ',
  'GENITALES:  CUELLO SIN SECRECION , COLPO SE EVDIENCIA DOS LEISONES HPRA 1 Y HORA 5',
  '',
  'EXTREMIDADES: DLN',
  'NEUROLOGICO: DLN',
  '',
  ' IDX:  LESION EN CUELLO UTERINO',
  '',
  'PLAN: DEFEROL OMEGA, CAUTERIZACION Y TIPIFICACION VIRAL',
  '22-8-23',
  'SE TOMA MUESTRA DE TIPIFICACION VIRAL.',
  '',
  '',
  '',
  'LABORATORIOS:',
  'FECHA',
  'HB/HTO',
  'LEU/PLAQ',
  'GLICEMIA',
  'UREA',
  'CREAT',
  'HIV/VDRL',
  'UROANALISIS',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  ... 44 more items
]

So, I want to put this content on a js object like:

const customObj = {
 fecha: "fecha on the doc",
....
}

But well I think this will works:

const fillObject = (inputArray, keywords) => {
    const customObj = {};
    keywords.forEach((keyword, index) => {
        customObj[keyword] = inputArray.map(line => {
            const keywordIndex = line.indexOf(keyword);
            if (keywordIndex !== -1) {
                const nextKeywordIndex = keywords.slice(index + 1).reduce((acc, nextKeyword) => {
                    const nextKeywordIndex = line.indexOf(nextKeyword);
                    return nextKeywordIndex !== -1 && nextKeywordIndex < acc ? nextKeywordIndex : acc;
                }, line.length);
                return line.slice(keywordIndex, nextKeywordIndex).trim();
            }
            return null;
        }).filter(Boolean);
    });
    console.log(customObj);
    return customObj;
};

From the function I get this: the keyword with the content before the next keyword, and i want to get only the important data.
The format of the documents is always the same, but sometimes i get spaces between a keyword and its content and sometimes I don’t. The words are always capitalized.

I try the function mentioned before, but i want to be more precise on my searching and in how the data looks in the object. The final result has to be a little more accurate because the output actually looks like this:

'FECHA:': [ 'FECHA: 19-10-23' ],
    'NOMBRE Y APELLIDO:': [ 'NOMBRE Y APELLIDO: John Dee' ],
    'C.I.:': [ 'C.I.: 3232323' ],
    'EDAD:': [ 'EDAD: 56' ],
    'DIRECCION:': [ 'DIRECCION:   Marylan ],
    'TLF:': [ 'TLF:  55555555' ],
    'CORREO:': [ 'CORREO:  [email protected]' ],
    'CONTACTO:': [
      'CONTACTO:  IG                                            HISTORIA CLINICA GINECO-OBSTETRICA'
    ],

As you can see some properties are weird like “contacto” does not fit well.

Need Help Rendering Data Dynamically in React Component

I’m having trouble showing fetched data in a React component. I’ve built a component that fetches information from an API using Axios. Although I can fetch the data successfully, I struggle to display it on the screen as intended.

I expect the component to dynamically show the fetched data, updating the UI accordingly.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const MyComponent = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://api.example.com/data');
        setData(response.data);
        setLoading(false);
      } catch (error) {
        console.error('Error fetching data:', error);
        setLoading(false);
      }
    };

    fetchData();

    return () => {
      
    };
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (!data) {
    return <div>Error fetching data</div>;
  }

  return (
    <div>
      <h1>Fetched Data</h1>
      <ul>
        {data.map((item, index) => (
          <li key={index}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default MyComponent;