Why does using setState in React makes function repeat?

There is a button that toggles dark and light mode so I am trying to save the state of what mode it is on in localStorage. However, when I try to change the state to anything inside the React function it calls the function infinitely and gives this error:
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

How do I change the state without re-rendering the function infinitely?

let localDark = localStorage.getItem("dark");

function Mode() {
    const [dark, setDark] = useState(false);

    const onClick = () => {
        if (dark) {
            setDark(false);
            document.querySelector("body").classList.remove("dark");
        } else {
            setDark(true);
            document.querySelector("body").classList.add("dark");
        }
        localStorage.setItem("dark", dark);
    };

    if (localDark !== null) {
        localDark = JSON.parse(localStorage.getItem("dark"));
        setDark(localDark); // this is what causes the error
        // onClick();
    }

    return (
        <div onClick={onClick} className="mode">
            {dark ? <Light /> : <Dark />}
        </div>
    );
}

How to Loop this array. How to iteration my array

const numArr = [1,2,3,4];
for (let i=0; i<numArr.length; i++) {
let indexNum = String(numArr[i]);
console.log(indexNum+numArr[0],indexNum+numArr[1],indexNum+numArr[2],indexNum+numArr[3]);}

result is

  • 11 12 13 14
  • 21 22 23 24
  • 31 32 33 34
  • 41 42 43 44

I would like to get this output?

  • 12 13 14
  • 23 24 34
  • 11 22 33 44
    How do i iterate array.
    I want to start second iteration is index-1 and third iteration start index-2, fourth is index-3 and so on..

How do I looping this array..

javascript […str.matchAll() ] return assoitaive array or object

when we using .matchAll() sgainst a string,and reteieve value using spread operator syntax then it return like this ( see on chrome console )


[
[
  "#111",
  "#111"
]
index: 44, 
input: 'nwhatever string', 
groups: {…}, 
indices: Array(2)
]

although it say array.length is 2 then what are these other property?

is this assiative array like PHP or this is object or array because javascript array has numeric value only (AFAIK) and if it is object then why .length working ?

Most complex hello world program

Here is a challenge for SO: Create the unnecessarily difficult hello world program you can think of. The program can be written in any language as long as it prints the phrase “Hello world!” 

I did nothing; this isn’t a problem; it’s just a fun challenge.

How do I write this more efficiently? [duplicate]

I am trying to make it so that in JS I can get a certain string 30% of the time, another one 10% of the time, etc etc down to one variable 0.1% of the time. Currently, I have an array and I pick a random item from the array and simply weigh the variables in the array.

I have tried googling the issue however I am unable to put the issue into words. The following is a simplified version of the code

let weights = ["var1", "var1", "var1", "var1", "var2", "var2"]; // etc etc
let x = 0;

function getrandom() {
    x = weights[Math.floor(Math.random() * weights.length)]; // return random thing from array
}

JSON data is refused by Lightweight Charts

I want to use LightWeight Charts by TradingView. I process data with Python and serve it via Flask to JSON:

from flask import Flask, jsonify, render_template
from datetime import datetime

app = Flask(__name__)


@app.route('/')
def home(name=None):
    return render_template('index.html', name=name)

@app.route('/data')
def data():
    ind_df = d.request_data(...) # dummy method
    ind_df['Date'] = ind_df['Date'].map(lambda t: int(t.timestamp()))
    ind_df = ind_df.set_index('Date')
    return jsonify(ind_df.to_dict())

then I have index.json:

// Create the Lightweight Chart within the container element
const chart = LightweightCharts.createChart(
  document.getElementById('container')
);

// Create the Main Series (Candlesticks)
const mainSeries = chart.addCandlestickSeries();


fetch('/data')
  .then(response => response.json())
  .then(data => {
    // use the data to create a visualization
    console.log(data)

    mainSeries.setData(data);
  });

my data is succesfully logged in console but I have “uncaught type error” to chart.

The question is in what shape does LightWeight Charts accept the data? I have a DataFrame that I will change .to_json(). The problem is about indexing.

In place of

          {
            time: "2018-10-19",
            open: 180.34,
            high: 180.99,
            low: 178.57,
            close: 179.85,
          }

I have:

{ "Open":
     { "epoch1": value1,
       "epoch2": value2,
       "epoch3": value3,
       ...
     },
   "Close:
      ...
}

How should I convert my data?

how can I ask another questions in my code after choosing one of the options?

Hello I have a problem with this exercise:
Write a program that calculates the area of a figure?

What figure? 1 – rectangle, 2 – triangle
if user will choose rectangle the program should ask questions:
-Enter base length:
-Enter the height of the rectangle:
statement: This field is:

if user will choose second options what is triangle a program will ask questions as:
-Enter the side length
-Enter the length of side
statement: The area of the triangle is:

    var bok1 = Number(prompt("Ile wynosi pierwszy bok prostokata?"));
    var bok2 = Number(prompt("Ile wynosi drugi bok prostokata?"));
    var podstawa trojkata = Number(prompt("Podaj długość podstawy:"));
    var wysokosc trojkata = Number(prompt("Podaj wysokosc podstawy:"));
    var co_obliczyc = (prompt("Co chcesz obliczyc? prostokat czy trojkat?"));
    switch(co_obliczyc) {

so I wrote sth like that and stuck I don’t want my program to ask every questions at first and then calculate I want program to ask about the figure then if user will chose one of this he has to give dimensions for the selected figure I have no idea how to do this please help

Get fill with document.getElementById in JavaScript

I’m starting to learn JavaScript and I had a question.
I have two icons, one with red fill and one with blue fill. Is there a way that with document.getElementById().style.fill I can get the fill they have and then do a comparison.
Something like:
if(document.getElementById(“Icon1”).style.fill == “red”){ … }

I tried to do it with: if(document.getElementById(“Icon1”).style.fill == “red”) but it didn’t work

Javascript library: Send logs to parent application [closed]

I am writing a javascript library to be used by another application.
Another application will use the
window.samplelib to access my library objects.
This library will generate many logs based on the workflow. On each log generation, I want to send it back to parent application as well via subscription. What’s the best way to achieve this?

How to create model with association M-N via Sequelize

Stack: NodeJs, PostgreSQL, Sequelize, Express.
I have two associated models (User and Role) through User_Roles.
When I create new user via Sequelize.create(), how can i fill the User_Roles table to define which roles (i get the array filled with role ID) the user have. The roles are already defined in table (roles)

The models:

const User = sequelize.define('users', {
  id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
  email: { type: DataTypes.STRING(320), allowNull: false, unique: true, isEmail: true },
});

const Role = sequelize.define('roles', {
  id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
  title: { type: DataTypes.STRING(64), allowNull: false, unique: true },
});

const User_Roles = sequelize.define('user_roles', {}, { timestamps: false });

// Associations

User.belongsToMany(Role, { through: User_Roles });
Role.belongsToMany(User, { through: User_Roles });

UserController:

async create(req, res, next) {
    const { email, roles } = req.body;

    if (!email) {
      return next(ApiError.badRequest('Invalid request'));
    }

    if (!Array.isArray(roles) || !roles.length) {
      return next(ApiError.badRequest('Invalid request'));
    }

    const isExistThisEmail = await User.findOne({ where: { email } });
    if (isExistThisEmail) {
      return next(ApiError.badRequest('The email already exists'));
    }

    const user = await User.create({ email });

    return res.status(201).json(createdUser);
  }

The roles in DB

vs code extension to control browser tabs

Problem: When developing inside vs code you may have several chrome browsers open that respectively have mulitple tabs open in each browser window pertaining to different topics in regards to your development tasks or other. When you need to move back to a certain browser you have to leave vs code and hover or open each browser to find the exact tab with the information you are looking for.

Solution: Build Vs Code extention that you can manage your browsers by opening new browser windows or restore minimized browser windows. The extension would create new browser groups for each new window you open, and then create a tree view of the browser windows by grouped names.

Benefit: You would not need to leave vs code to restore or open theses windows (this doesnt mean the browser opens in vs code (webview?), I just mean you dont have to leave vs code to search for which window group to restore).

Current: Debugging locally, I can activate the extension which then does a quick pick of options for ‘Installs’ or ‘Browser’. The Installs options is outside of the scope of the question but would just open one off URLs to helpful/needful installs. The Browser options show options to open google, youtube, and default groups Primary, Secondary, and Tertiary. The goal would be opening google or youtube or any additional defaults in a new browser attaching a grouped name (Primary, Seconday, Tertiary) and then if you minimize that window I would be able to restore a minimized browser group by chosing their respective name.

Issue: The Browser default URLs, google and youtube at the moment, open in the same default browser without designating a group name and in turn opening a minimized browser with the group name does not work either.

Attempts: In the below code I have tried to open and asign browser group names like:
open(<url>, options)
I cant find good docs for what the options entail
window.open(<url>, options)
Errors arent helpful but breaks at start on const window = require(‘window’);
vscode.window.open(browser.link, browser.detail)
Opens in default
vscode.commands.executeCommand('vscode.open',vscode.Uri.parse(browser.link))
Opens in default

Let me know what you think, thanks.

`

const vscode = require(‘vscode’);
const open = require(‘open’);

/**

  • @param {vscode.ExtensionContext} context
    */

function activate(context) {

var opts = [
    {label: "Installs", detail:"Software Installation"},
    {label: "Browsers", detail: "Browser Manager"}
]
var installs = [
    {label: "python", link: "https://Python.org/download/"},
    {label: "node", link: "https://https://nodejs.org/en/download/"},
    {label: "aws cli", link: "https://docs.aws.amazon.com/cli/latest/
                                userguide/getting-started-install.html"}
]
var browsers = [
    {label: "google", link: "https://Google.com", detail: "Primary"},
    {label: "YouTube", link: "https://youtube.com", detail: "Primary"},
    {label: "Primary Browser", detail: "Primary"},
    {label: "Secondary Browser", detail: "Secondary"},
    {label: "Tertiary Browser", detail: "Tertiary"},    
]
vscode.window.showInformationMessage('Browser Manager Activated!');
let disposable = vscode.commands.registerCommand(
    'browsermanager.ManageChrome', 
    async function () {

        const opt = await vscode.window.showQuickPick(opts, {
            matchOnDetail: true
        })

        if (opt.label == "Installs"){
            const install = await vscode.window.showQuickPick(installs, {
                matchOnDetail: true
            })
            open(install.link)
        }
        else if (opt.label == "Browsers"){
            const browser = await vscode.window.showQuickPick(browsers, {
                matchOnDetail: true
            })
            if (["Primary","Secondary","Tertiary"].includes(browser.detail)) {

                vscode.commands.executeCommand(
                    'vscode.open', 
                    vscode.Uri.parse(browser.link)
                    )
            }
            else{
                vscode.commands.executeCommand(
                    'vscode.open', 
                    vscode.Uri.parse(browser.link)
                    )
            }
        }   
});

context.subscriptions.push(disposable);

}

function deactivate() {}

module.exports = {
activate,
deactivate
}

`

The right way to return booleans from C++ to JavaScript using v8 js engine

I am trying to embed v8 static libs into my standalone C++ application ( macOS: Monterey 12.6, CPU: Intel Core i7, Xcode: 13.1 (13A1030d) )

  1. I’ve written a simple bash script to get v8 static libs:
git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git
export PATH=$PWD/depot_tools:$PATH

mkdir v8
cd v8
fetch v8
cd v8

git checkout branch-heads/9.4
gclient sync

gn gen out/x64.release--args='
is_component_build = false
is_debug = false
target_cpu = "x64"
use_goma = false
v8_enable_backtrace = true
v8_enable_disassembler = true
v8_enable_object_print = true
v8_enable_verify_heap = true
dcheck_always_on = false
v8_monolithic = true
v8_use_external_startup_data = false'

ninja -C out/x64.release v8_monolith
  1. copy libv8_monolith.a, libv8_libplatform.a, libv8_libbase.a from out/x64.release/obj to my xcode c++ console project’s folder and link them to it.
  2. the c++ part of test project looks like:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <filesystem>

#include <v8.h>
#include <libplatform/libplatform.h>

using namespace v8;

Local<Context> GetNewContext(Isolate* _isolate, Local<Context> _context) {
    EscapableHandleScope scope(_isolate);
    return scope.Escape(Local<Context>::New(_isolate, _context));
}

std::string ToStdString(v8::Isolate *isolate, v8::MaybeLocal<v8::Value> valueMaybe) {
    if (valueMaybe.IsEmpty())
        return {};

    auto value = valueMaybe.ToLocalChecked();

    if (value->IsNullOrUndefined())
        return {};

    auto strLocalMaybe = value->ToString(isolate->GetCurrentContext());

    if (strLocalMaybe.IsEmpty())
        return {};

    auto strLocal = strLocalMaybe.ToLocalChecked();

    if (strLocal.IsEmpty())
        return {};

    String::Utf8Value data(isolate, strLocal);

    if (data.length() == 0)
        return {};

    return std::string(*data);
}

bool LoadScript(const std::string& path, Isolate* _isolate, Local<Context> _context) {
    Locker locker(_isolate);
    Isolate::Scope isolateScope(_isolate);
    HandleScope scope(_isolate);
    Local<Context> context = GetNewContext(_isolate, _context);
    Context::Scope ctxScope(context);
    TryCatch try_catch(_isolate);

    std::ifstream file(path.c_str());
    if (!file.is_open()) {
        return false;
    }
    
    std::stringstream buffer;
    buffer << file.rdbuf();
    
    std::string data = buffer.str();

    Local<String> source = String::NewFromUtf8(_isolate, data.c_str(), NewStringType::kNormal).ToLocalChecked();

    auto fakePath = path;//Resource::GetFakeAssetPath(path);
    Local<String> name = String::NewFromUtf8(_isolate, fakePath.c_str(), NewStringType::kNormal).ToLocalChecked();
    Local<Script> compiled_script;
    auto origin = ScriptOrigin(name);

    if (!Script::Compile(context, source, &origin).ToLocal(&compiled_script)) {
        return false;
    }

    Local<Value> result;
    auto run = compiled_script->Run(context);
    if (!run.ToLocal(&result)) {
        return false;
    }

    return true;
}

void LogCallback(const FunctionCallbackInfo<Value> &args) {
    if (args.Length() < 1) {
        return;
    }

    Isolate *isolate = args.GetIsolate();
    HandleScope scope(isolate);

    std::stringstream str;
    int l = args.Length();
    for (int i = 0; i < l; i++) {
        MaybeLocal<String> maybeValue = args[i]->ToString(isolate->GetCurrentContext());
        if (!maybeValue.IsEmpty()) {
            auto value = ToStdString(isolate, maybeValue.ToLocalChecked());

            str << value.c_str() << " ";
        } else {
            str << "{unknown} ";
        }
    }

    std::cout << str.str() << std::endl;
}

void CreateTrue(const FunctionCallbackInfo<Value> &args) {
    v8::Isolate *isolate(args.GetIsolate());
    args.GetReturnValue().Set(v8::True(isolate));
}

void CreateFalse(const FunctionCallbackInfo<Value> &args) {
    v8::Isolate *isolate(args.GetIsolate());
    args.GetReturnValue().Set(v8::False(isolate));
}


int main(int argc, const char * argv[]) {
    std::unique_ptr<Platform> platform = v8::platform::NewDefaultPlatform();
    
    V8::InitializePlatform(platform.get());
    V8::Initialize();
    
    Isolate::CreateParams create_params;
    create_params.array_buffer_allocator = ArrayBuffer::Allocator::NewDefaultAllocator();
    Isolate* isolate = Isolate::New(create_params);
    
    Local<Context> context;
    {
        Locker l(isolate);
        Isolate::Scope isolate_scope(isolate);
        HandleScope handle_scope(isolate);
        
        Local<ObjectTemplate> global = ObjectTemplate::New(isolate);
        
        global->Set(isolate, "log", FunctionTemplate::New(isolate, LogCallback));
        
        global->Set(isolate, "cpp_CreateTrue", FunctionTemplate::New(isolate, CreateTrue));
        global->Set(isolate, "cpp_CreateFalse", FunctionTemplate::New(isolate, CreateFalse));
        
        context = Context::New(isolate,  nullptr, global);
        
        auto jsLikeBool = v8::Boolean::New(isolate, true);
        // at this point typeof this jsLikeBool equals to string, but should be equal to boolean
        if (jsLikeBool->IsBoolean()) {
            std::cout << "c++::GetBoolean jsLikeBoolean has boolean type" << std::endl;
        } else {
            std::cout << "c++::GetBoolean jsLikeBoolean DOES NOT have boolean type, but HAS: " << ToStdString(isolate, jsLikeBool->TypeOf(isolate)) << std::endl;
        }
    }
    
    if (!LoadScript(std::filesystem::current_path() / "assets" / "bools.js", isolate, context)) {
        return 1;
    }
    
    isolate->Dispose();
    V8::Dispose();
    V8::ShutdownPlatform();
    
    delete create_params.array_buffer_allocator;
    return 0;
}
  1. assets/bools.js file:
const Js_CreateTrue = () => true;
const Js_CreateFalse = () => false;

const CheckCreator = function(tag, getter, expectedType, expectedValue) {
    const value = getter();
    const valueType = typeof value;
    
    if (valueType !== expectedType) {
        log(`JS::test ${tag} failed types check, actual: ${valueType}, but expected: ${expectedType}`);
    }
        
    if (value !== expectedValue) {
        log(`JS::test ${tag} failed values check, actual: ${value}, but expected: ${expectedValue}`);
    }
}

CheckCreator("Js_CreateTrue", Js_CreateTrue, "boolean", true); // OK
CheckCreator("Js_CreateFalse", Js_CreateFalse, "boolean", false); // OK

CheckCreator("cpp_CreateTrue", cpp_CreateTrue, "boolean", true); // FAILED: gets an empty string
CheckCreator("cpp_CreateFalse", cpp_CreateFalse, "boolean", false); // causes crash in c++, actual type is `symbol`

I have already tried different tags/branches of v8 sources, nothing helps.
How to get rid of such strange behaviour with returning booleans from C++ to JS?

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist. index.html:1

I’m making a small programm here in HTML/JS and I’m getting an error I’ve never seen before.

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

This is my code.

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>Document</title>
    </head>
    <body>
        <div>
        <label for="lgn">Login:</label>
        <input name="lgn" type="text" class="login-text">
        </div>
        <div>
        <label for="psswrt">Password:</label>
        <input name="psswrt" type="password" class="password-text">
        </div>
        <button class="submit-button">Submit</button>
        <div class="answer-display"></div>

        <script src="script.js"></script>
    </body>
</html>

script.js

let loginData = ["test login"]
let passwordData = []

const lgn = document.querySelector(".login-text")
const pswrt = document.querySelector(".password-text")
const btn = document.querySelector(".submit-button")
const ansr = document.querySelector(".answer-display")

Please help

When the redirectURI in the keycloak in http://localhost:3000/admin/home is working fine but when url has queryparams its throwing 502 error page

When the redirectURI in the keycloak in http://localhost:3000/admin/home is working fine but when url has queryparams its throwing 502 error page

working URL:-http://localhost:3000/admin/home
Not working URL:- http://localhost:3000/admin-forward?target={someValue}&token={someValue}}Client setup in keycloak

Keycloak Version:- 16.1.1
React-18
Routerv6

It should route to the correct page, its working in logged in user

Why do I get “undefined” when I pass the “total” to a function using `useEffect` and output the value in that function?

I have a button in Next.js and when I click it I’m calling the reduceprice function:

  <IconButton
    onClick={() => {
      context.setcount(context.count - 1);
      handledelete(item);
      reduceprice();
    }}
  >
    <CloseIcon />
  </IconButton>

After I added some products I’m calculating the total price with useEffect and I can get the total price. I pass the total in reduceprice function, but when I click on button I get undefined

  function reduceprice(total) {
    console.log(total);
  }

  useEffect(() => {
    let total = 0;
    let prices = context.card;
    let i = 0;
    for (i = 0; i < prices.length; i++) {
      total += parseFloat(prices[i].price.replace("US $", ""));
    }
    let tot = "US $" + total.toString();
    reduceprice(total);

    console.log(tot);
  }, []);

Why do I get “undefined” when I pass the “total” to a function using useEffect and output the value in that function?