How to control scrolling of an element scrolling another

As you can see the structure of my html, I am trying to position the cursor in the left column of the screen and scroll down so that instead of scrolling inside the body and going to the footer, i want it to scroll the righ side. And when the content ends, the footer of my page is displayed. I don’t know if I understood myself but I want the content of the right column to be shown specifically when I position myself in both columns and scroll.
Here i show my html, css and javascript code. Perhaps something is preventing the action i want to do.

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Two Columns</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;700&display=swap">
    <script src="scroll.js"></script>
</head>
<body id="the-body">
    <div class="content" id="content">
        <div class="column-1" id="column-1">
          <img class="brownie-img" src="brownie.jpg" alt="Brownie de Cacao">
        </div>
        <div class="column-2" id="column-2">
            <h1>Brownie de Cacao</h1>
            <h2>Descripción</h2>
            <div class="description">
                <p>"Lorem Ipsum Content..."</p>
            </div>
        </div>
    </div>
    <footer>
      <div class="footer-content">
          <p>&copy; 2023 Mi Sitio Web. Todos los derechos reservados.</p>
          <ul>
              <li><a href="#">Política de privacidad</a></li>
              <li><a href="#">Términos y condiciones</a></li>
          </ul>
      </div>
  </footer>
</body>
</html>
html{
    height: 100%;
    width: 100%;
    background-color: brown;
}

body{
    height: 100%;
    width: 100%;
    margin: 0;
}

.content{
    background-color: bisque;
    display: flex;
    height: 100vh;
    overflow-y: auto;
}

.column-1{
    width: 50%;
    text-align: center;
    border-right: 1px solid brown;
    overflow-y: auto;
    max-height: 100vh;
}

.brownie-img-container{
  overflow: auto;
  width: 100%;
  height: 100%;
}

.title{
    margin: 0;
}

.brownie-img{
    width: 50%;
    border-radius: 50%;
    margin-top: 25vh;
}

.column-2{
    width: 50%;
    text-align: center;
    padding: 10px;
    font-family: 'IBM Plex Sans', sans-serif;
    overflow-y: auto;
    max-height: 100vh;
}

.description{
    text-align: justify;
}
document.addEventListener('DOMContentLoaded', function()
{   
    var column1 = document.getElementById('column-1');
    var column2 = document.getElementById('column-2');

    column1.addEventListener('scroll', function () 
    {
        column2.scrollTop = column1.scrollTop;
    });
});

By the moment i don´t have any other idea.

libreria frappe-react-sdk / file.uploadFile

Instale la libreria frappe-react-sdk y necesito enviar una foto.
Utilizo el codigo que sugieren en la documentacion:

const myFile; //Your File object

const fileArgs = {
  /** If the file access is private then set to TRUE (optional) */
  "isPrivate": true,
  /** Folder the file exists in (optional) */
  "folder": "Home",
  /** File URL (optional) */
  "file_url": "",
  /** Doctype associated with the file (optional) */
  "doctype": "User",
  /** Docname associated with the file (mandatory if doctype is present) */
  "docname": "Administrator",
  /** Field to be linked in the Document **/
  "fieldname" : "image"
}

file.uploadFile(
            myFile,
            fileArgs,
            /** Progress Indicator callback function **/
            (completedBytes, totalBytes) => console.log(Math.round((c / t) * 100), " completed")
        )
        .then(() => console.log("File Upload complete"))
        .catch(e    

Cambio todos los datos segun mi app..En myFile detallan que va un objeto, yo solo tengo la ruta a la imagen: file//example/etc

Cuando realizo la llamada me sale éste error:

 {"_server_messages": "["{\"message\": \"Fields `file_name` or `file_url` must be set for File\", \"title\": \"Message\", \"indicator\": \"red\", \"raise_exception\": 1}"]", "exc": "["Traceback (most recent call last):\n  File \"apps/frappe/frappe/app.py\", line 94, in application\n    response = frappe.api.handle()\n  File \"apps/frappe/frappe/api.py\", line 54, in handle\n    return frappe.handler.handle()\n  File \"apps/frappe/frappe/handler.py\", line 47, in handle\n    data = execute_cmd(cmd)\n  File \"apps/frappe/frappe/handler.py\", line 85, in execute_cmd\n    return frappe.call(method, **frappe.form_dict)\n  File \"apps/frappe/frappe/__init__.py\", line 1620, in call\n    return fn(*args, **newargs)\n  File \"apps/frappe/frappe/handler.py\", line 223, in upload_file\n    return frappe.get_doc(\n  File \"apps/frappe/frappe/model/document.py\", line 305, in save\n    return self._save(*args, **kwargs)\n  File \"apps/frappe/frappe/model/document.py\", line 327, in _save\n    return self.insert()\n  File \"apps/frappe/frappe/model/document.py\", line 253, in insert\n    self.run_method(\"before_insert\")\n  File \"apps/frappe/frappe/model/document.py\", line 914, in run_method\n    out = Document.hook(fn)(self, *args, **kwargs)\n  File \"apps/frappe/frappe/model/document.py\", line 1271, in composer\n    return composed(self, method, *args, **kwargs)\n  File \"apps/frappe/frappe/model/document.py\", line 1253, in runner\n    add_to_return_value(self, fn(self, *args, **kwargs))\n  File \"apps/frappe/frappe/model/document.py\", line 911, in fn\n    return method_object(*args, **kwargs)\n  File \"apps/frappe/frappe/core/doctype/file/file.py\", line 61, in before_insert\n    self.set_file_name()\n  File \"apps/frappe/frappe/core/doctype/file/file.py\", line 333, in set_file_name\n    frappe.throw(\n  File \"apps/frappe/frappe/__init__.py\", line 534, in throw\n    msgprint(\n  File \"apps/frappe/frappe/__init__.py\", line 502, in msgprint\n    _raise_exception()\n  File \"apps/frappe/frappe/__init__.py\", line 451, in _raise_exception\n    raise raise_exception(msg)\nfrappe.exceptions.MandatoryError: Fields `file_name` or `file_url` must be set for File\n"]", "exc_type": "MandatoryError", "exception": "frappe.exceptions.MandatoryError: Fields `file_name` or `file_url` must be set for File", "httpStatus": 417, "httpStatusText": undefined, "message": "There was an error while uploading the file."}

I need help making a random number that simulates follower growth for a minigame I wrote in javascript

For the sake of this example:

  1. There is no follower loss
  2. Followers are earned after the minigame ends, once – not as a live update
  3. Follower count for users start at 1 and are stored in the database

What do I mean?

  • At the end of the minigame, I will be displaying a random number – this random number will attempt to immitate that of earning followers. For that reason, I need help attempting to make an equation/loop/system that adapts from having 1 follower to millions in javascript.

What I have tried to do initially to create this random number:
data.Followers+100*Math.floor(Math.random() * 1.5) + 0.3/8

Current followers + 100 multiplied by a random number in the range of 0.3 to 1.5 and finally divided by 8. This is my initial equation to simulate follower growth, the issue is that the value remains too constant, and as you have more followers it becomes extremely easy to earn them.

data.Followers can be any number but will always start at 1. This is the follower count stored on the user. The reason I add 100 is to make up for low follower counts.

My goal is to possibly start earning followers at a faster rate but as you have more, you will earn less but maintain growth. There is no follower loss as mentioned.

I’m new to stackoverflow and bad at explaining, if anything needs clarifying I will be happy to edit this post answering your question.

Remote dubbing the `fetlch()` function in JS and HTML code with VS Code

I want to use my home-server (debian 12) as development environment with vs code. Right now I am trying to develop some simple client side stuff with pure JS and HTML. I am working on an searchbar with fetch().I can debug the following file just fine on my local system (debian 12) but it will not continue to debug correctly after the fetch call (index.html). I tried breakpoints on const cities = [] (works local and remote) console.log(cities (only works locally; remote shows to continue working but its not getting further). Thanks for helping! Her is my index.html file:

<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
    <title>Project P06</title>
    <meta name="desription" content="Project P06">
    <meta name="viewport" content="width=device-width, initial-scale=1">
<!--    <link rel="stylesheet" href="./styles.css">-->
  </head>
  <body>
    <div class="city-search">
      <form action="" method="get" class="city-form">
        <input type="search" name="city" id="city" placeholder="City or State">
        <ul class="suggestions">
          <li>Filter for city</li>
          <li>Or filter for state!</li>
        </ul>
      </form>
    </div>
    
  </body>
  <script>
    const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
    const cities = []
    fetch(endpoint)
      .then(bitstream => bitstream.json())
      .then(data => cities.push(...data))
    console.log(cities)

    function match_cities(search_string, cities){
      const regex = new RegExp(search_string, "gi")
      return cities.filter(place => {
        return place.city.match(regex) //  place.state.match(regex)
      })
      return matching_cities
    }

    function display_search_result(){
      
      const matched_cities = match_cities(this.value, cities)
      let suggestions_html = matched_cities.map(place => {
        html_string =`
       <li>
          <span class="city-name"> ${place.city}, ${place.state}</span>
          <span class="city-population">${place.population}</span>
        </li>`
        return html_string
      })
      suggestions_html = suggestions_html.join('n')
      search_suggestions.innerHTML = suggestions_html
    }
    
    const search_input = document.querySelector("#city")
    const search_suggestions = document.querySelector(".suggestions")
    console.log(search_suggestions)
    search_input.addEventListener("change", display_search_result)
    search_input.addEventListener("keyup", display_search_result)
    // create search results in DOMd


  </script>

</html>

To develop on my home-server I open VS Code and connect to my home-server via ssh. I can edit code on my home-server and the live server of VS Code shows me the changes in my local browser. For debugging remote I use this launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Chrome : Launch with sourcemaps",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost:5500",
            "runtimeArgs": [
                "--remote-debugging-port=9222",
                "--user-data-dir=remote-debug-profile"
            ]
        }
    ]
}

This works for stuff like this index.html pefectly fine. I can use breakpoints here:

<!Doctype html>
  <html>
    <head></head>
    <body>
      <p>Code</p>
    </body>
    <script>
      console.log("testing");
      console.log("Testing 2");
    </script>
  </html>

If it try to use the same launch.json for my code it just “stops” debugging, without stopping the debugger.
debugger just stopps and doesn’t continue

I can’t use AJAX to save information about liked movies

I am new to Django and to creating web applications in general. So I don’t really understand what I did wrong. I have a web application with movies.
my site

By clicking on the like button, the id of the liked movie should be saved.

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const likeButtons = document.querySelectorAll(".like-button");

        likeButtons.forEach(button => {
            button.addEventListener("click", function () {
                const movieId = this.getAttribute("data-id");

                if (!this.classList.contains("liked")) {
                    this.classList.add("liked");
                    sendLikeToServer(movieId, true);
                } else {
                    this.classList.remove("liked");
                    sendLikeToServer(movieId, false);
                }
            });
        });

        function sendLikeToServer(movieId, likeStatus) {
            fetch('/like-movie/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({ movieId: movieId, like: likeStatus })
            })
            .then(response => response.json())
            .then(data => {
                console.log(data);
                if (data.likedMovies.length === 3) {
                    window.location.href = "{% url 'recommendations' %}";
                }
            });
        
        }


        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== "") {
                const cookies = document.cookie.split(";");
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === name + "=") {
                        cookieValue = decodeURIComponent(
                            cookie.substring(name.length + 1)
                        );
                        break;
                    }
                }
            }
            return cookieValue;
        }
    });
</script>

In views.py the method is prescribed:

def like_movie(request):
    data = json.loads(request.body)
    movie_id = data.get('movieId')
    like_status = data.get('like')

    liked_movies = request.session.get('liked_movies', [])

    if like_status and movie_id not in liked_movies:
        liked_movies.append(movie_id)
    elif not like_status and movie_id in liked_movies:
        liked_movies.remove(movie_id)

    request.session['liked_movies'] = liked_movies

    return JsonResponse({'status': 'success', 'liked_movies': liked_movies})

In urls.py also provided a URL route:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('filmlibrary/', views.Filmlibrary, name='filmlibrary'),
    path('like-movie/', views.like_movie, name='like_movie'),
    path('recommendations/', views.Recommendations, name='recommendations'),
]

So, when I click on the like of a movie, I get an error in the browser console:

erorr

On the one hand, I understand what the second mistake is about. The Response contains the html of the page with the error. On the other hand, I don’t understand what to do about it. Please help me with this problem!

I tried adding to urls.py The project has a like-movie route, and the first error disappeared, but this is not what I need. In this case, the address bar says http://127.0.0.1:8000/like-movie/filmlibrary /, but I need to http://127.0.0.1:8000/movies_app/filmlibrary /.

In general, I want to be redirected to the page after liking three movies recommendations.html and there were liked movies and recommendations for them. If anything, I use the Neo4j database and the neomodel library

Module ‘”@uppy/core”‘ has no exported member ‘debugLogger’

I’m trying to start up a new project in vanilla typescript with uppy but I keep getting an import error:

Module ‘”@uppy/core”‘ has no exported member ‘debugLogger’. Did you mean to use ‘import debugLogger from “@uppy/core”‘ instead?

I’m following the docs and example sandboxes.

{
  "name": "vanilla-typescript",
  "version": "1.0.0",
  "description": "JavaScript and TypeScript example starter project",
  "main": "index.html",
  "scripts": {
    "start": "parcel index.html --open",
    "build": "parcel build index.html"
  },
  "dependencies": {
    "parcel-bundler": "^1.6.1",
    "@uppy/core": "^3.8.0",
    "@uppy/drag-drop": "^3.0.3",
    "@uppy/status-bar": "^3.2.5",
    "@uppy/xhr-upload": "^3.6.0"
  },
  "devDependencies": {
    "typescript": "4.4.4"
  },
  "resolutions": {
    "@babel/preset-env": "7.13.8"
  },
  "keywords": ["typescript", "javascript"]
}
import "./styles.css";

import Uppy, { debugLogger } from "@uppy/core";

console.log({ debugLogger });

Here’s a test sandbox that errors and won’t start up. What am I doing wrong here?

Retrieving information about top-level code in a JavaScript module

I am currently exploring effective strategies for retrieving metadata from the top-level code within JavaScript modules. While established methodologies exist for functions, I am specifically interested in gathering insights into successful strategies and industry-recognized techniques for extracting meaningful metadata from the top-level code.

Consider the following JavaScript snippet:

const myVar = 1;
console.log('hello from top level');

function myFunction() {
    console.log('hello from function');
}

I am seeking the community’s expertise on professional approaches, accepted practices, or inherent JavaScript techniques commonly utilized to extract metadata from top-level code. Any suggestions or guidance on tools or methods that provide a comprehensive understanding of the composition and attributes of top-level code within JavaScript modules would be highly appreciated.

propper way in NodeJS to load a cjs in a module project

To give you a bit of context, I am supposed to develop code for a bot which uses a webpage as primary developing base, which means, action code must be written on the web page so I guess the code in question is loaded on server side then run by eval when appropiate. It’s ok for a few lines of code, but in a large project you can imagine the kind of nightmare it can be.

So my goal is to setup a testing environment, and have that code under a git repo. Then, once my tests pass, I can upload the code.

now, my particular problem at hand is: now I want to be able to load a javascript file from a nodejs module, load a function and be able to run that function from a test suite:

code for sarasa.js:

function sarasa2(){
    console.log( " aca toy!");    
    return true;
}

testing code:

import { Test } from "../../myjsunit/testSuite.js";

import  fs from 'fs';


class so_Test extends Test {
    
    test_load_and_run(){
        let fname = "testsjs/micro/sarasa.js";
        
        let code = fs.readFileSync( fname ).toString() ;
        
        eval( "("+code+")" );
        
        let actual = sarasa2();

        this.assertTrue( actual );
        this.done();
    }
}

export { so_Test }

(please do not worry about testing framework)

the error I get is:

ReferenceError: sarasa2 is not defined

question: is it possible to run the function defined inside the loaded file?.

Error when working on a Typescript RPC library in Vue but works in React

I am working on a typescript RPC library in Vite/Vue 3. The library I am trying to work on is as follows:

"verusd-rpc-ts-client": "git+https://github.com/VerusCoin/verusd-rpc-ts-client.git",

I am getting the following error:

Module "util" has been externalized for browser compatibility. Cannot access "util.debuglog" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
get @ verusd-rpc-ts-client.js?v=63353c53:4935
Show 1 more frame
Show less
verusd-rpc-ts-client.js?v=63353c53:4935 Module "util" has been externalized for browser compatibility. Cannot access "util.inspect" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
get @ verusd-rpc-ts-client.js?v=63353c53:4935
Show 1 more frame
Show less
verusd-rpc-ts-client.js?v=63353c53:9155 Module "stream" has been externalized for browser compatibility. Cannot access "stream.Transform" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
get @ verusd-rpc-ts-client.js?v=63353c53:9155
Show 1 more frame
Show less
verusd-rpc-ts-client.js?v=63353c53:9292 Module "buffer" has been externalized for browser compatibility. Cannot access "buffer.Buffer" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
get @ verusd-rpc-ts-client.js?v=63353c53:9292
Show 1 more frame
Show less
verusd-rpc-ts-client.js?v=63353c53:12567 Uncaught ReferenceError: Buffer is not defined
    at node_modules/verus-typescript-primitives/dist/constants/vdxf.js (verusd-rpc-ts-client.js?v=63353c53:12567:63)
    at __require (chunk-RSJERJUL.js?v=63353c53:3:50)
    at node_modules/verus-typescript-primitives/dist/vdxf/index.js (verusd-rpc-ts-client.js?v=63353c53:13773:18)
    at __require (chunk-RSJERJUL.js?v=63353c53:3:50)
    at node_modules/verus-typescript-primitives/dist/vdxf/classes/Challenge.js (verusd-rpc-ts-client.js?v=63353c53:14025:15)
    at __require (chunk-RSJERJUL.js?v=63353c53:3:50)
    at node_modules/verus-typescript-primitives/dist/vdxf/classes/index.js (verusd-rpc-ts-client.js?v=63353c53:15656:23)
    at __require (chunk-RSJERJUL.js?v=63353c53:3:50)
    at node_modules/verus-typescript-primitives/dist/index.js (verusd-rpc-ts-client.js?v=63353c53:16165:18)
    at __require (chunk-RSJERJUL.js?v=63353c53:3:50)

Now the error could be related to the library itself but the same library works fine in Vue JS. I can make direct rpc calls from the URL but want to use the library directly so any changes made to the library could be integrated in my code by simply making it as a submodule.

My code is JS:

proxyRPC:

// proxyVerusd.js
import { VerusdRpcInterface } from 'verusd-rpc-ts-client'

const verusd = VerusdRpcInterface("iJhCezBExJHvtyH3fGhNnt2NhU4Ztkf2yq", "https://api.verustest.net");

export const fetchConversion = async () => {
  const res = await verusd.getCurrency('bridge.veth')
  const info = await verusd.getInfo()

  const block = info.result.longestchain

  const bestState = res.result.bestcurrencystate
  const currencyNames = res.result.currencynames
  const currencies = bestState.reservecurrencies
  const count = currencies.length
  const { supply } = bestState
  const daiKey = Object.keys(res?.result?.currencynames).find((key) => currencyNames !== undefined && currencyNames[key] === 'DAI.vETH')
  const daiAmount = currencies.find(c => c.currencyid === daiKey).reserves

  let list = currencies.map((token) => ({ name: currencyNames[token.currencyid], amount: token.reserves, daiPrice: daiAmount / token.reserves }))
  const bridge = { name: 'Bridge.vETH', amount: supply, daiPrice: (daiAmount * count) / supply }

  let conversions = [
    { symbol: 'vrsc', price: 0 },
    { symbol: 'eth', price: 0 },
    { symbol: 'mkr', price: 0 },
    { symbol: 'dai', price: 0 }
  ]

  try {
    conversions = await Promise.all(
      urls.map(async (url) => fetch(url)
        .then((res) => res.json())
        .then((c) => ({
          symbol: c.symbol,
          price: c.market_data.current_price.usd
        })))
    )
  } catch (error) {
    // eslint-disable-next-line no-console
    console.error('%s: fetching prices %s', Date().toString(), error)
  }
  list = list.map((token) => {
    switch (token.name) {
      case 'VRSCTEST':
      case 'VRSC':
        return {
          ...token,
          price:
            conversions.find((c) => c.symbol === 'vrsc')?.price
        }
      case 'vETH':
        return {
          ...token,
          price: conversions.find((c) => c.symbol === 'eth')?.price
        }
      case 'DAI.vETH':
        return {
          ...token,
          price: 1
        }
      case 'MKR.vETH':
        return {
          ...token,
          price: conversions.find((c) => c.symbol === 'mkr')?.price
        }
      // return { ...token, price: vrscPrice }
      default:
        return { ...token }
    }
  })
  return { list, bridge, currencies }
}

export const fetchCurrency = async (currency) => {
  try {
    const response = await verusd.getCurrency(currency);
    return response;
  } catch (error) {
    console.error("Error fetching currency:", error);
    throw error;
  }
};

export const fetchInfo = async () => {
  try {
    const response = await verusd.getInfo();
    return response;
  } catch (error) {
    console.error("Error fetching info:", error);
    throw error;
  }
};

// You can add more proxy methods here if needed


I use the code above in my Vue component as follows:

<script>
import { fetchInfo, fetchConversion } from "./utils/proxyGet"; 

export default {
  name: 'VerusCurrencies',
  async mounted() {
    await this.getConsole();
  },
  methods: {
    async getConsole() {
      try {
        //const res = await fetchCurrency("Bridge.vEth");
        const info = await fetchInfo();
        const getCon = await fetchConversion();
 
        //console.log(res);
        console.log(info);
        console.log(getCon);
      } catch (error) {
        // Handle errors if needed
        console.log("Cannot get data")
      }
    },
  }
}

</script>

Is the beginner javascript shuffling algorithm an unbiased shuffle

There are many shuffling algorithms, with probably the most famous being Fisher-Yates. However, one common algorithm that you often see presented is this:

function shuffle(arr) {
    return arr.sort(() => Math.random() - 0.5;
}

Clearly, this does shuffle the array, since the expected value of Math.random is 0.5, subtracting 0.5 yields 0, so the odds of the comparison function returning lesser or greater is 50%. However, it’s not clear to me that this is an unbiased sort.

Does anyone have an intuition of whether it is unbiased or no?

JavaScript Promises and synchronous behaviour

I am trying to deserialise a JSON object which has a type key whose value is a string; if the type is “a”, the object class is defined in “a.js” and this file contains an initialisation function a_init. There may be a subobjects key whose value is an array of objects. If so, these nested objects should be processed in the same way.

The code I have looks like this:

var files = [];

function load(obj) {
  if (!!obj["type"]) {
    let type       = obj.type;
    let subobjects = obj.subobjects;
    let promise    = new Promise(function(resolve) {
                         let script = document.createElement("script");
                         script.setAttribute("src", type + ".js");
                         script.addEventListener("load",resolve);
                         document.head.appendChild(script);
                     });
    promise.then(function() {
        if (!files.includes(type)) {
          files.push(type);
          if (subobjects instanceof Array) {
            for (element of subobjects) {
              load(element);
            }
          }
          let func = window[type + "_init"];
          if (typeof(func) =="function") {
            func(obj);
          }
        }
    });
  }
}

For an object like this:

{ "type": "a",
  "data": "foo",
  "subobjects": [
      { "type": "b",
        "data": "1"
      }
  ]
}

the output is:

This is A
This is B

(The functions a_init and b_init just display a message for testing purposes.)

My problem is that I would like the subobjects to be initialized before the outer object, so b_init would complete before a_init to give this output:

This is B
This is A

but of course the nested call to load just creates a new promise and then completes before the new promise does.

Is there any way to enforce synchronicity here to control the order of events?

I am having problems with tag not working when it is clearly there in the html body in the browser console

I have a jsp file which has an “iframe” tag where my data is shown when user searches for a field. When user clicks search, my servlet gets userdata from the database and create html page using StringBuilder, and convert everything to string at the end and send it to the iframe tag to be displayed. It all works fine but my function inside the script tag is not being picked up by the browser when it is clearly there. I have tried putting my script function in the head and the body tag but it didn’t work. Even I put a simple script function to print error it still gives me the same error. Here is how I am calling the function

 htmlContent.append(String.format("<td><button type='button'          onclick="sendRequest('%s')">%s</button></td>",

Here is my script tag

 htmlContent.append("<script>");  htmlContent.append("function sendRequest(RecorderID) {");  htmlContent.append("  var url = 'updateRecorderInfoServlet?RecorderID=' + RecorderID        htmlContent.append("  console.log('Request URL:', url);");
htmlContent.append("     window.location.href = url;");                  htmlContent.append("}");htmlContent.append("</script>");

This is my jsp file

 <script>
       
        function submitForm() {
            // Get the form data
            var formData = new FormData(document.getElementById('displayForm'));

            // Send a POST request using JavaScript Fetch API
            fetch('getRecorderInfoServlet', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                },
                body: formData.get('Recorder_ID')
            })
            .then(response => response.text())
            .then(data => {
                // Update the iframe content
                document.getElementById('resultFrame').contentWindow.document.body.innerHTML = data;
            })
            .catch(error => console.error('Error:', error));
        }
   
     
    </script>

“`

<header>    
    <a href="landingPageServlet" title="Home"><span>&#127968;</span></a>
    <h1>Search by User ID</h1>
</header>
        
 <form id = "displayForm" onsubmit="event.preventDefault(); submitForm();" >
        <label for="recorderId">Enter Recorder ID:</label>
        <input type="text" id="recorderId" name="Recorder_ID" required/>
        <br>
        <input type="submit" value="Search">
    </form>


   <iframe id="resultFrame" name="resultFrame" width="100%" height="500px"></iframe>


</body>

I am expecting to transfer the recorder id to to another servlet when user clicks on the recorder id in the table. I could've used dispatcher too but that doesn't allow me to use onClick. I want to transfer the user id only when user clicks on the tag. Manually putting the function in the browser console works perfectly fine. 

crypto.subtle.importKey throws unspecified Error

I’m trying to sign a text using WEB Crypto API. I’m depending on a 3rd party to extract the certificate from a smart card, which returns a Base64 string representation of it. As far as I understand, first I need to convert it to a cryptoKey object to pass it to the sign method and that is where the error occurs. Here is how it looks in the console.

Here is what I’m doing:

  const res = await fetch("https://localhost:53952/getsigner",{
    method: "POST",
    headers: {
      'Content-type': 'application/json',
    },
    body: "{}"
  })

const body = await res.json();
const signCertString = body.chain[0];

const binaryCert = Uint8Array.from(atob(signCertString), c => c.charCodeAt(0));
const certBuffer = binaryCert.buffer;

crypto.subtle.importKey(
  "pkcs8",
  certBuffer,
  {
    name: "RSASSA-PKCS1-v1_5",
    hash: { name: "SHA-256" },
  },
  true,
  ["sign"]
)
  .then((cryptoKey) => {
    console.log("CryptoKey object created:", cryptoKey);
  })
  .catch((error) => {
    console.error("Error creating CryptoKey object:", error);
  });

how to animate radial-gradient color and percentage?

It works for box-shadow but how do I transition radial-gradient color and percentage smoothly?
do i need java script? if so, i wanna know if there’s library to do make this easly.

        body {
            background-color: black;
        }
        .seven {
            width: 200px;
            height: 200px;
            margin: 50px auto;
            animation: colorChange 10s infinite linear;
        }

        @keyframes colorChange {
            0%, 100% {
                background: radial-gradient(circle, #9157c7 0%, #9157c7 50%, #3c1f8b 70%);
                box-shadow: 0 0 7vh #5f2bb3;
            }
            16.67% {
                background: radial-gradient(circle, #6a878b 0%, #6a878b 50%, #899e8f 65%);
                box-shadow: 0 0 7vh #aac4b1;
            }
            29.17% {
                background: radial-gradient(circle, #bbc0d4 0%, #bbc0d4 50%, #5c6069 70%);
                box-shadow: 0 0 7vh #70727e;
            }
            50% {
                background: radial-gradient(circle, #045886 0%, #045886 50%, #376c7a 65%);
                box-shadow: 0 0 7vh #376c7a;
            }
            70.83% {
                background: radial-gradient(circle, #dd9849 0%, #dd9849 50%, #7e4b52 70%);
                box-shadow: 0 0 7vh #7e4b52;
            }
            83.33% {
                background: radial-gradient(circle, #9157c7 0%, #9157c7 50%, #3c1f8b 70%);
                box-shadow: 0 0 7vh #5f2bb3;
            }
        }

    <div class="seven"></div>