JavaScript Assignment Possibly in Wrong Scope?

Here’s my code:

const myMenu = {
    bIsExpanded: false,
    menuDiv: "",

    initialize: function() {
        this.menuDiv = document.getElementById("my_menu");
    },

    clickMenu: function() {
        if(this.bIsExpanded) {
            this.menuDiv.style.display = "none";
            this.bIsExpanded = false;
            return;
        }

        this.menuDiv.style.display = "block";
        this.bIsExpanded = true;
    }
}

The initialize() method is called on page load, and is definitely being called. clickMenu() is called when an element is clicked, and is also being called correctly. The element is stored correctly within the initialize() function, but is forgotten by the clickMenu() function, and is throwing a console error as being undefined.

Why is the assignment in initialize() not assigning to the myMenu property??

TradingView Lightweight Charts library not working with own data

I am having issues with using the lightweightcharts candlestick chart code with my own data.

Problem 1 is that the code below plots the candlestick chart as expected with my own financial csv file dataset, except it doesn’t plot the y-axis. I have tried several solutions but the y-axis still isn’t visible (see screenshot attached).

Here is the code to plot a static candlestick lightweight chart using your own csv file:

html file:
see screenshots below of code. Apparently the format isn’t right for stack overflow to upload….

HTML FILE CODE

js file:
see screenshots below of code. Apparently the format isn’t right for stack overflow to upload….
code part 1
code part 2

When I run the code it shows a beautiful candlestick chart in my browser (see image attached), however, the only thing that’s missing is the y-axis. How I can get the y-axis to plot with the values on it? I have attached another image of a candlestick chart which DOES show the y-axis. This is what I want on my chart. NOTE: The code that produces the candlestick chart with the y-axis shown on the chart doesn’t import the data from a csv file, it just lists the data as a long list of data points inside brackets () within the js file, whereas in the code above I have imported the data as a csv file.

CANDLESTICK CHART NO Y AXIS

CANDLESTICK CHART WITH Y AXIS

Problem 2 is that I want to plot a candlestick chart using NON-FINANCIAL data from a csv file. I thought that I would just be able to plug in my non-financial csv file into the code above, but unfortunately, running it produces a graph with nothing on it (see screenshot below).

BLANK CHART

Attached is the format of my financial data (date, high, low). The lightweightcharts code requires data in the format of date, open, high, low, close. I have tried removing open and close from the code so that the chart doesnt require those values, and I have also kept open and close in the code and set them to the high and low values to see if the code does indeed require at least some value for open and close. Both methods generate a chart that is blank (see screenshot attached). I have also attached a screenshot of the dataset; it is a very small dataset – perhaps this is the issue? Maybe there aren’t enough values to plot?
DATA SET

PS my non-financial data has values between 900 and 1150. The original data is between 0.9 and 1.15 but I multiplied it by 1000 because I thought perhaps the variation in the high and low values were too small to be seen on the chart, which is why the chart displays nothing. But I’m now not sure now why nothing is appearing on the chart.

I am writing my code on Visual Studio Code on Mac.

Thanks

HI my js will not print out the total in the field i specify in and i cant figure out why

when i purchace smth from the table it just says NAN on the check out page.It will not display the acctualprice.

This is the table and in html

 <form id="purchaseForm">
        <table class="shopping-cart">
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Details</th>
                    <th>Price</th>
                    <th>Quantity</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody id="productDetails">
                
            </tbody>
            <tr class="grandTotal">
                <td colspan="4"></td>
                <td>Total:</td>
                <td><input type="text" id="grandTotal" name="grandTotal" readonly></td>
            </tr>
        </table>
        <button type="button" onclick="submitForm()">Submit</button>
        <button type="reset">Reset</button>
    </form>
    <script src="js/API.js"></script>
    
    <div id="confirm">
        <h2>Confirmation</h2>
        <div id="confirmationItems"></div>
        <div id="confirmationTotal"></div>
        <p>Shipping Fee: $7.99</p>
        <p>Total Amount (including shipping): <span id="totalAmount"></span></p>
    </div>

this is the calcultions

function calculateTotal(itemNumber) {
  const price = [179.99, 109.99, 569.99, 94.47, 249.99]; // Prices for each item
  const quantity = parseInt(document.forms["purchaseForm"]["quantity" + itemNumber].value);
  const subtotal = price[itemNumber - 1] * quantity;
  
  document.forms["purchaseForm"]["total" + itemNumber].value = subtotal;

  updateGrandTotal();
}

function updateGrandTotal() {
  const total1 = parseFloat(document.forms["purchaseForm"]["total1"].value) || 0;
  const total2 = parseFloat(document.forms["purchaseForm"]["total2"].value) || 0;
  const total3 = parseFloat(document.forms["purchaseForm"]["total3"].value) || 0;
  const total4 = parseFloat(document.forms["purchaseForm"]["total4"].value) || 0;
  const total5 = parseFloat(document.forms["purchaseForm"]["total5"].value) || 0;

  const grandTotal = total1 + total2 + total3 + total4 + total5;

  document.forms["purchaseForm"]["grandTotal"].value = grandTotal;
}

function submitForm() {
  const grandTotal = document.forms["purchaseForm"]["grandTotal"].value;
  alert("Total Amount Due: €" + grandTotal);
}

this it the confirm page that is not working

   function submitForm() { $('#confirm').show();
 var grandTotal = parseFloat($("#grandTotal").val());

    var items = [];
    $("#productDetails tr").each(function() {
        var itemName = $(this).find("td:eq(0)").text();
        var quantity = parseInt($(this).find("td:eq(3)").text());
        var total = parseFloat($(this).find("td:eq(4)").text());
        items.push({ itemName: itemName, quantity: quantity, total: total });
    });

    $("#confirmationItems").empty();
    items.forEach(function(item) {
        $("#confirmationItems").append("<p>Item: " + item.itemName + ", Quantity: " + item.quantity + ", Total: $" + item.total + "</p>");
    });

    $("#confirmationTotal").text("Total Amount: $" + grandTotal);
 
    var shippingFee = 7.99;
    var totalAmount = grandTotal + shippingFee;
    $("#totalAmount").text(totalAmount.toFixed(2));
}

table is filled out by an api

for it to show the price on the Total amoutI.

I do not know where the problem lies and i would appreciete any help with this.

How can I mark the parts of the car in react native

I want it to show the parts when I click on the numbers.
2-left door.
9-right door.
enter image description here

I can also show it as painted, changed, locally painted or original. My main purpose is to show the damage information to the car. I don’t know how to do this. Does it make sense to do it on a single picture or to take 13 pieces of pictures and combine them?

Segurança da informação ou programação Web?

Não sei nada de programação mas to começando a estudar agora, e de todas as areas a quem mas me atraiu foi a de segurança da informação (hacker), mas do com dificudade de encontra material de estudo na internet.

Por outro lado tem muito material pra programação Web com muitos curso e tal, muita gente fala que esta é a melhor area para quem esta começando na programação. Então eu to na duvida de vou pra a area que atraiu minha atenção ou vou para area que ta todo mundo falando sobre.

My javascript file wont work in php file, but works in html [closed]

Ive linked my script file into the php page, but it doesnt work.

  <script src="script.js"></script>
    
</head>
<body>
    <div class="wrapper">
        <i class="fa-solid fa-angle-left"></i>
        <div class="carousel">
        <img src="images/image1.webp" alt="">
        <img src="images/image2.jpg" alt="">
        <img src="images/image3.webp" alt="">
        <img src="images/image4.jpg" alt="">
        <img src="images/image5.webp" alt="">
    </div>
    <i class="fa-solid fa-angle-right"></i>
</div> 
const carousel = document.querySelector(".carousel");

const dragging = (e)=>{
    carousel.scrollLeft = e.pageX;
}
     
carousel.addEventListener("mousemove",dragging);

when I change the extension to html it starts working.

Find all duplicates in JavaScript array with objects [duplicate]

Before you mark it as duplicated, I searched tens of answers and none of them worked for my case.
Most of them are to find unique primitive values in an array.

I am looking to get a new array with all objects from an array that have the same name.

var array = [  
    
    { 
    "name": "Item A",
    "price": "584.04",
    },
    { 
    "name": "Item A",
    "price": "584.04",
    },
    { 
    "name": "Item A",
    "price": "584.04",
    },
    { 
    "name": "Item B",
    "price": "584.04",
    },
    { 
    "name": "Item C",
    "price": "584.04",
    },
    { 
    "name": "Item A",
    "price": "584.04",
    },
]

It has nothing to do with How can I group an array of objects by key?

I found this answer

To find all duplicates in a JavaScript array of objects based on a specific property (in this case, “name”), you can use a combination of reduce() and filter() functions. Here’s a way to do it:

var array = [
    {
        "name": "Item A",
        "price": "584.04",
    },
    {
        "name": "Item A",
        "price": "584.04",
    },
    {
        "name": "Item A",
        "price": "584.04",
    },
    {
        "name": "Item B",
        "price": "584.04",
    },
    {
        "name": "Item C",
        "price": "584.04",
    },
    {
        "name": "Item A",
        "price": "584.04",
    },
];

var duplicates = array.reduce(function(acc, current, index, array) {
    if (array.findIndex(item => item.name === current.name) !== index && !acc.find(item => item.name === current.name)) {
        acc.push(current);
    }
    return acc;
}, []);

console.log(duplicates);

Next.js + Vercel – “gamestate” of my Game switches between two states when it is LIVE on Vercel, load balancer?

In my game, you have to click a button to increase the users counter by +1.

Client

  • The vue.js Client App just provides the button.

  • Clicking the button makes API requests to the backend

  • Display the API response “counterValue”

Server

  • The backend , increases and returns the users “counterValue”

  • The “users” and their increasing “counterValue” are persistend over different API calls.

No serverside statemanagement is used. Code:

import type { NextApiRequest, NextApiResponse } from ‘next’

{ sql } from “@vercel/postgres”;

let cachedUsers: User[] = []

—————————————–

When testing the game locally, everything works fine!

The Problem:

(origState –> newState):
W
hen the Game is deployed to Vercel! then it can happen, after clicking the button verry fast (counter = 100) (origState), you get another gamestate, with counter = 0. (newState)

(newState –> origState):
When I increase the counter in newState quickly to 20, it can happen that is **jumps back to origState! **with counter = 100).

(origState –> newState):
I click button many times from (100 to 170), switches back to newState! with counter = 20.

(newState –> origState):
When I increase quickly the counter from 20 to 230 in newState, **jumps back to origState! **with counter = 170).

—————-

My Thoughts

  • Locally this never happens.

  • I think, there might be a load balancer or something. A “second server” for handling the requests 😀 Because it only switches between origState and newState… not more.

I did some internet research for this but it’s hard to search for this problem.

comment cree une application qui a un algorithme similaire a tik tok

Bonjour,

Je suis un étudiant cherchant à créer un algorithme similaire à celui de TikTok. Mon problème est que je suis confronté à des défis techniques complexes pour développer un système de recommandation efficace et réactif, capable de comprendre les préférences des utilisateurs et de leur recommander du contenu pertinent. J’ai besoin d’aide pour comprendre les meilleures pratiques en matière de traitement de données massives, d’apprentissage automatique et de conception d’algorithmes de recommandation. Pouvez-vous me conseiller sur la meilleure approche à adopter pour atteindre cet objectifJe suis conscient que cette tâche nécessite une expertise approfondie, et je suis prêt à investir du temps et des efforts pour y parvenir. Je suis ouvert à toute suggestion ou ressource que vous pourriez recommander, que ce soit des livres, des articles, des cours en ligne ou des tutoriels. Mon but est de créer un algorithme robuste et innovant qui offre une expérience utilisateur immersive et personnalisée, tout en maintenant une efficacité opérationnelle élevée. Votre contribution serait extrêmement précieuse pour moi dans cette entreprise. Je suis déterminé à acquérir les compétences nécessaires pour réaliser ce projet et je suis prêt à suivre des recommandations spécifiques ou des chemins de formation que vous pourriez suggérer. Je suis conscient que le développement d’un algorithme de recommandation de qualité nécessite une compréhension approfondie des techniques telles que le filtrage collaboratif, le traitement du langage naturel et les réseaux de neurones. Votre expérience et votre expertise seront cruciales pour m’aider à naviguer à travers ces domaines complexes et à élaborer une solution viable. Merci encore pour votre considération et j’attends avec impatience votre guidance dans ce projet.

I’m Unable to Upload Videos/audios in Google Gemini API 1.5Pro

Can someone help me to use Google Gemini API1.5Pro model with Video/audio Processing?

I’ve already searched almost in all search engines, but can’t find any resource to learn.
My requirement is to upload an audio file and ask the AI to summarize it.

I’m using Node.js with Google AI Studio(@google/generative-ai)
any suggestion will be highly valued!

I’ve tried the following:-

  • I’ve installed the google generative package and explore with it
    the Gemini AI API1.5Pro is working perfectly with text-only results and text-and/or-image results, but I couldn’t find any way to explore with audio files and video files.

React Router Dom – why is my page not rendering?

I am trying to use react router dom to allow me to create different web pages. I want the page to load my HomePage on default path ‘/’ but nothing renders. Anyone know why this might not be working?

Index.js:


    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';

    ReactDOM.render(
    <React.StrictMode>
    <App />
    </React.StrictMode>,
    document.getElementById('root')
    );

App.js:**

    import React from 'react';
    import HomePage from './pages/HomePage';
    import JoinPage from './pages/JoinPage';

    import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

    function App() {
    return (
    <Router>
    <Routes>
    <Route path='/' element={<HomePage />} />
    <Route path='/join' element={<JoinPage />} />
    </Routes>
    </Router>
    )
    }

export default App;

/pages/HomePage.js:**

    import React from 'react';
    import './HomePage.css';

    function HomePage() {
    return (
    <div>
    <h1>CLAPS</h1>
    <div className="homepage-buttons">
    <button onClick={handleJoinRoom}>JOIN ROOM</button>
    <button onClick={handleShowRules}>RULES</button>
    </div>
    </div>
    );

    function handleJoinRoom() {
    // Handle Join Room button click
    console.log("Join Room button clicked");
    // Add your logic for joining a room
    }

    function handleShowRules() {
    // Handle Rules button click
    console.log("Rules button clicked");
    // Add your logic for showing the rules
    }
    }

    export default HomePage;

Thanks!

Running the above just brings up a blank page. It for some reason renders the background colour from /pages/HomePage.css but no other elements are rendered.

Html/css and jacaScript mouse event

im new to programming and im currently working on my first website.

im using a mouseover event in js to change display property in css.
mouseout event will trigger the display: none propery in the css.

when i hover mouser over the MENY it rappid fiers mouseover and mouseout signals when the mouse have not left the bigger div for the mouseout event and i have no idea how to fix this problem.

Dropdown menu
JS codeNavbar html

tried to maipulate the htm css and js.

Troubles with writing image to file. C++, JavaScript

Currently im trying to create a website using c++ and crow framework for backend and vanilla js for client side. Now i have some troubles with image saving. I need to upload image to server and save it to file, but when im doing that and trying open the file window saying me that type is not supported or file corrupted.

Here is my code on clien side:

let main_img;
document.getElementById('do_magic').addEventListener('click', async publish => {

    publish.preventDefault();

    const data = new FormData();

    data.append('main_img', imgs[0]);


    const res = await fetch(HOST + '/', {
        method: 'POST',
        body: data
    });

    if (res.status == 200)
        console.log('OK!');

});

function uploadFile(inputElement) {
    var file = inputElement.files[0];
    main_img = file;
}

All i do there is getting img from input element and put it in formdata object, then just fetch it to server.

On server side code looking like this:

CROW_ROUTE(app, "/").methods("POST"_method)([](const crow::request& req, crow::response& res)
{
    if (!token_writer_auth(req)) //check for user rights
    {
        res.code = 403;
        res.end();
    }

    const crow::multipart::message msg(req);

    const std::string i = msg.part_map.find("main_img")->second.body;

    std::ofstream o("./static/pic/test.jpg");
    o << i;

    res.code = 200;
    res.end();
});

Its pretty straightforward code but how you can see very bad. Im some kind of newbie of programming, but i succesfully create other functionality that work corectly. I know that for web is better to use webp img format, so next i need to somehow convert uploaded img to webp and then save it to file. If someone can help me with that ill be very gratefull 🙂

Javascript and Spring communication, how to include an Authorization Header on redirect?

I’m doing some practice with a SpringBoot Project which includes a JWT Filter.
Right now the filter is extracting the token from the Authorization Header, everything is working correctly as it should, tested it with Postman.
The problem is that im trying to make a web page, server side rendered using Thymeleaf and i don’t know how to keep the token inside my requests.
Right now I’m testing a login page, the endpoint receives credentials and returns the appropriate Response, including JWT inside the body, my Javascript code is supposed to receive the token, save it inside the local storage and include it inside the request when redirecting.
When hardcoding the token inside the Header using some browser extension it works how it should, but without it, it doesn’t work.
I’ve made some research and I’ve understood that what I’m doing is wrong since axios it’s used with SPAs and it’s not able to redirect to another page and modify the Header.
Is there any way i can perform what i want?
Sorry if it looks stupid but I don’t actually have any front-end knowledge, it was just something i wanted to add to my Spring project.

This is what i tried without success.

`async function handleSuccess(response) {
    const token = response.data.jwt;
    const redirect = response.data.url;
    localStorage.setItem('jwt', token);
    const headers = {
        'Authorization': `Bearer ${token}`
    };

    try {
        // Await the axios.get request
        const result = await axios.get(redirect, { headers: headers });
        console.log('Headers:', headers);
        window.location.href = redirect;
    } catch (error) {
        // Handle errors during redirection
        alert('errore');
        console.error('Error during redirection:', error);
    }
} `