Navbar toggler button open but not close after

Here my code with a collapsible navbar. The toggler button opens but not closes the menu:

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" integrity="sha384-4LISF5TTJX/fLmGSxO53rV4miRxdg84mZsxmO8Rx5jGtp/LbrixFETvWa5a6sESd" crossorigin="anonymous">

    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/ui/1.14.0/jquery-ui.min.js" integrity="sha256-Fb0zP4jE3JHqu+IBB9YktLcSjI1Zc6J2b6gTjB0LpoM=" crossorigin="anonymous"></script>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/select2-bootstrap-5-theme.min.css" />

<nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #134d8c;">
    <div class="container-fluid">
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                <li class="nav-item">
                    <a href="/www" class="nav-link <?php echo ($page == 'home') ? 'active' : '' ?>">
                        <i class="fs-5 bi-house"></i> <span class="ms-1 me-2 d-none d-sm-inline">Home</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="parametri.php" class="nav-link <?php echo ($page == 'parametri') ? 'active' : '' ?>">
                        <i class="fs-5 bi-gear"></i> <span class="ms-1 me-2 d-none d-sm-inline">Parametri</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="anagrafiche.php?nav=anagrafica_alunni" class="nav-link <?php echo ($page == 'anagrafica_alunni') ? 'active' : '' ?>">
                        <i class="fs-5 bi-backpack2"></i> <span class="ms-1 me-2 d-none d-sm-inline">Anagrafica alunni</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="anagrafiche.php?nav=anagrafica_famiglie" class="nav-link <?php echo ($page == 'anagrafica_famiglie') ? 'active' : '' ?>">
                        <i class="fs-5 bi-people"></i> <span class="ms-1 me-2 d-none d-sm-inline">Anagrafica famiglie</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="bonus.php" class="nav-link <?php echo ($page == 'bonus') ? 'active' : '' ?>">
                        <i class="fs-5 bi-trophy"></i> <span class="ms-1 me-2 d-none d-sm-inline">Bonus</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="turni_pulizie.php" class="nav-link <?php echo ($page == 'turni_pulizie') ? 'active' : '' ?>">
                        <i class="fs-5 bi-trash"></i> <span class="ms-1 me-2 d-none d-sm-inline">Turni pulizie</span>
                    </a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fs-5 bi-cookie"></i> Turni cucina
                    </a>
                    <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <li><a href="turni_cucina.php" class="ms-1 me-2 nav-link <?php echo ($page == 'turni_cucina') ? 'active' : '' ?>">Calendario</a></li>
                        <li><a href="turni_cucina_famiglie.php" class="ms-1 me-2 nav-link <?php echo ($page == 'turni_cucina_famiglie') ? 'active' : '' ?>">Famiglie</a></li>
                        <li><a href="turni_fissi_cucina.php" class="ms-1 me-2 nav-link <?php echo ($page == 'turni_fissi_cucina') ? 'active' : '' ?>">Fissi</a></li>
                        <li><a href="turni_cucina_scambi.php" class="ms-1 me-2 nav-link <?php echo ($page == 'turni_cucina_scambi') ? 'active' : '' ?>">Scambi</a></li>
                        <li><a href="turni_cucina_pagamenti.php" class="ms-1 me-2 nav-link <?php echo ($page == 'turni_cucina_pagamenti') ? 'active' : '' ?>">Pagamenti</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

I found this similar question, but my code seems already as the answer suggests (include jquery before bootstrap).
Why it works in one way only?

How can I stop port.postMessage() in a node.js worker from causing a memory leak?

I have this basic example of the problem:

//main.js
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');

worker.on('message', function (message) {

    //no-op

});

And:

//worker.js
const { parentPort } = require('worker_threads');

while (1) {

    const message = {foo: true};

    parentPort.postMessage(message);


}

This causes a rapid growth in memory usage. Within seconds it’s gigabytes. Within a couple of minutes it’s all the system memory, and the process is killed. I’ve tried adding delete message; after the postMessage() call, and in the message handler of main.js. Neither of these seem to have any effect. I’ve tried running it natively, and in various node based docker containers; it’s always the same.

My questions are:

  1. Why does it work this way? Why isn’t the object being garbage collected when main.js’s message handler is returning? And if it’s a case of postMessage() carelessly growing some message queue in the parent thread with freshly created objects, why does it do that, rather than waiting?

  2. How do I get around this?

I imagine someone is thinking “Why would you send so many messages?”. The answer is to demonstrate the problem. In the real scenario it was larger but much more infrequent message sends, and that caused a much slower but still completely unacceptable memory leak.

What’s the deal here?

How to Mock Kafka Client for Unittesting in NestJS

I am new to Typescript and currently do not understand how to mock a Kafka Client in a NestJS Application.

What I want to achieve

I have a NestJS Application which has the following controller:

consumer.controller.ts

import { Controller} from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';
import { ConsumerService } from './consumer.service';

@Controller()
export class ConsumerController {
  constructor(private readonly consumerService: ConsumerService) {}

  /**
   * Handles events from the 'Topic-1' topic.
   * @param context - The Kafka context containing the message and metadata.
   */
  @EventPattern('Topic-1')
  async dosomething(@Payload() message: any) {
    // do something
  }
}

consumer.service.ts

import { Injectable, OnModuleDestroy, OnModuleInit, Inject } from '@nestjs/common';
import { Client, ClientKafka } from '@nestjs/microservices';

@Injectable()
export class ConsumerService implements OnModuleInit, OnModuleDestroy {
  constructor() {}

  @Client(microserviceConfig)
  private readonly client: ClientKafka;

  /**
   * Lifecycle hook that is called when the module is destroyed.
   * Closes the Kafka client connection.
   */
  async onModuleDestroy() {
    await this.client.close();
  }

  async onModuleInit() {
    const requestPatterns = [
      'Topic-1',
      'Topic-2',
    ];

    requestPatterns.forEach((pattern) => {
      this.client.subscribeToResponseOf(pattern);
    });

    await this.client.connect();
  }
}

I skipped the microserviceconfig for the real KafkaClient because I want to Use my Kafka Mock for Unit testing.

This is the module

consumer.module.ts

import { Module } from '@nestjs/common';
import { ConsumerController } from './consumer.controller';
import { ConsumerService } from './consumer.service';

@Module({
  controllers: [ConsumerController],
  providers: [ConsumerService],
})
export class ConsumerModule {}

And this is My Unit-Test for the Service:

import { Test, TestingModule } from '@nestjs/testing';
import { ConsumerService } from "./consumer.service";
import { ClientKafka } from '@nestjs/microservices';

describe('ConsumerService', () => {
  let emailService: ConsumerService;
  let kafka: ClientKafka;
  let emailNotificationService: EmailNotificationService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ConsumerService,
        {
          provide: ClientKafka,
          useValue: {
            subscribeToResponseOf: jest.fn(),
            connect: jest.fn().mockResolvedValue(undefined),
            emit: jest.fn(),
          }
        }
      ],
    }).compile();

    emailService = module.get(ConsumerService);
    kafka = module.get(ClientKafka);
  });


    it('Subscribe to right topics', async() => {
      await emailService.onModuleInit();
      expect(kafka.subscribeToResponseOf).toHaveBeenCalledWith('Topic-1');
      expect(kafka.subscribeToResponseOf).toHaveBeenCalledWith('Topic-2');
    })
});

But when I run the tests I get an error when trying to call this.client which indicates client is null.
I guess that is because Dependency Injection of my Kafka Mock is not working. Do I need to add the ClientKafka to the constructor? I tried doing that, but then building the consumer.module.ts failed.
How to do this?

Javascript Phone Number mask for azerbaijani numbers

I’ve been trying to implement a code snippet for the telephone input field in my WordPress FunnelKit builder checkout, but it isn’t working as expected when users re-enter their numbers. I aim to create an input format similar to the one on this example, with a few modifications. Specifically, I would like to fix the initial 0 digit at the start of the field, so as the user types, the format appears as:

(056) 234-56-67

The 0 digit should remain fixed at the start as they continue typing. Below is the previous code snippet I added to functions.php, but it doesn’t fully achieve the intended behavior. Could you please assist with a solution that aligns with this format?

Thank you!

add_action( 'wp_footer', 'funnelkit_phone_mask' );

function funnelkit_phone_mask() {
   wc_enqueue_js( "
      $('#tel_no, #alt_tel_no')
      .keydown(function(e) {
         var key = e.which || e.charCode || e.keyCode || 0;
         var phone = $(this);
         // Don't allow anything but numbers and some control keys
         if (key !== 8 && key !== 9) {
           if (phone.val().length === 0) {
            phone.val('(' + phone.val()); // add opening bracket
           }
           if (phone.val().length === 4) {
            phone.val(phone.val() + ') '); // add closing bracket and space after area code
           }
           if (phone.val().length === 9) {
            phone.val(phone.val() + '-'); // add first hyphen after 3 digits
           }
           if (phone.val().length === 12) {
            phone.val(phone.val() + '-'); // add second hyphen after 2 more digits
           }
         }
         return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
        });
   " );
}

// Function to set the placeholder and maxlength for both phone fields
add_action( 'wp_footer', 'funnelkit_phone_placeholder' );

function funnelkit_phone_placeholder() {
   wc_enqueue_js( "
      // Set placeholder and maxlength for tel_no field
      $('#tel_no').attr('placeholder', 'Tel. nömrəsi (___) ___-__-__');
      $('#tel_no').attr('maxlength', '15'); // Limit input to 15 characters

      // Set placeholder for alt_tel_no field
      $('#alt_tel_no').attr('placeholder', 'Alternativ tel. nomresi (___) ___-__-__');
      $('#alt_tel_no').attr('maxlength', '15'); // Limit input to 15 characters
   " );
}

How to convert an image url to File object from Google oAuth response?

In my React project I have a google oAuth API which I’m retrieving the google image url from the response:

const userInfoResponse = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', {
   headers: { Authorization: `Bearer ${googleResponse.access_token}` }
});

const google_image = userInfoResponse.data.picture;
console.log(google_image);
//https://lh3.googleusercontent.com/a/ACg8ocKjThtaGf5USLuL2LBMBuYxfDG0gDdM-RLA_I__UvNI3p_2Hlk=s96-c

Now I want to convert this URL to a File Object. So i tried to first convert this to a blob and then use the blob to construct a File but is not working as expected!

const googleImageResponse = await fetch(google_image);
const blob = await googleImageResponse.blob();
const googleImageFile = new File([blob], "profileAvatar.png");
const formData = new FormData();
formData.append('profile', googleImageFile);
formData.append('record', userResponse.data.id);

But in the above code the blob type is text/html and not an image. So when I’m adding the File to the FormData is failing to render it because the image is not of image type.


Required Solution:

I want to be able to:

  • Get Image URL from Google Response (e.g. https://lh3.googleusercontent.com/a/ACg8ocKjThtaGf5USLuL2LBMBuYxfDG0gDdM-RLA_I__UvNI3p_2Hlk=s96-c)
  • Convert Image URL to File
  • Pass File to FormData
  • Pass FormData toan API!

Once time onclick interferes with Undo button

I am making a tic tac toe game and I want to ensure that a single square can only be clicked once, I have found a way to do this by using null modifiers but this means that if a move is undone the null remains and that square becomes unplayable. I want a way to prevent a square from being played more than once but would become playble again if the undo button were used

Currently to prevent a square from being played more than once I’m using:

onclick="myFunction(); this.onclick=null;"

this does solve my initial problem of preventing more than one move per square but it means that when a move is undone that square remains unplayable as the onclick remains null.

The function sometimes skip some steps/expressions

I have made a logic that matches users whom have made requests to donors. I wrote the logic to accept partial donation. Lets say a user wants $5000 and there are two donors looking at give $3000 and $4000, it will take the $3000 and then $2000 from the second user to complete the receivers donation request.

The logic works a fine but the issue sometimes after matching 4k user and 3k user to our recipient it still accept other matches.

Heres my codebase:

async function fetchOpenRequestsAndTransactions(transactionRepository: TransactionRepository, currency: string) {
  const [openRequests, availableTransactions] = await Promise.all([
    transactionRepository.getOpenRequestsByOldest(currency),
    transactionRepository.getAvailableTransactionsByOldest(currency),
  ]);

  return [openRequests, availableTransactions];
}

function prepareUpdates(
  updatesRequests: any[],
  updatesTransactions: any[],
  request: IRequest,
  transaction: ITransaction,
  isRequestMatchComplete: boolean,
  isTxMatchComplete: boolean,
) {
  updatesRequests.push({
    id: request.id,
    matchedAmount: request.matchedAmount,
    isMatchComplete: isRequestMatchComplete,
    lastUpdatedAt: request.updatedAt,
  });

  updatesTransactions.push({
    id: transaction.id,
    unMatchedAmount: transaction.unMatchedAmount,
    isMatchComplete: isTxMatchComplete,
    lastUpdatedAt: transaction.updatedAt,
  });
}

async function handleDonationRequest(job, dbInstance) {
  const { currency } = job.data;

  // load dependencies
  await dependencyInjectorLoader(dbInstance);

  const transactionRepository = Container.get<TransactionRepository>(TransactionRepository);

  const [openRequests, availableTransactions] = await fetchOpenRequestsAndTransactions(transactionRepository, currency);

  const updatesRequests = [];
  const updatesTransactions = [];
  const matchesToCreate = [];

  for (let i = 0; i < openRequests.length; i++) {
    const request = openRequests[i] as IRequest;

    console.log('Processing request: ', i, 'Request ID:', request.id, 'Transactions: ', availableTransactions.length);

    let amountNeeded = request.amount - request.matchedAmount;
    let isRequestMatchComplete = false;

    for (const transaction of availableTransactions as ITransaction[]) {
      if (amountNeeded <= 0 || isRequestMatchComplete) break;

      let isTxMatchComplete = false;

      if (transaction.unMatchedAmount > 0) {
        const contribution = Math.min(amountNeeded, transaction.unMatchedAmount);

        request.matchedAmount += contribution;
        transaction.unMatchedAmount -= contribution;

        amountNeeded -= contribution;

        isRequestMatchComplete = amountNeeded === 0;
        isTxMatchComplete = transaction.unMatchedAmount === 0;

        prepareUpdates(
          updatesRequests,
          updatesTransactions,
          request,
          transaction,
          isRequestMatchComplete,
          isTxMatchComplete,
        );

        matchesToCreate.push({
          amount: contribution,
          currency: currency,
          request: request.id,
          transaction: transaction.id,
        });

        console.log(`Request ${request.id} received ${contribution} from transaction ${transaction.id}`);
      }
    }

    if (isRequestMatchComplete) {
      request.isMatchComplete = true;
    }
  }

  if(!matchesToCreate.length) return;
  await transactionRepository.startTxCall(async tx => {
    await Promise.all([
      transactionRepository.createMatches(tx, matchesToCreate),
      transactionRepository.batchUpdateRequests(tx, updatesRequests),
      transactionRepository.batchUpdateTransactions(tx, updatesTransactions),
    ]);
  });
}

The batch update calls all implement optimistic locking with the updatedAt field.

It behaves like the checks get skipped sometimes. This mostly happens when I have multiple people testing it

Count Button Not Appearing

I’ve been following along with React JS – React Tutorial for Beginners by Programming with Mosh on YouTube; however, I have been having difficulty with importing complex components into a list. The DOM will not update with the multiple components in a list. After playing around with the files, I can no longer see the number increment next to the increment button. I don’t have the faintest idea what happened here. What am I missing for the number to appear?

//Counter.jsx

import React, { component } from "react";

class Counter extends Component {
    state = {
    count: 0
};
styles = {
    fontSize: 10, 
    fontWeight: "bold",
};
handleIncrement = () => {
    this.setState({ count: this.state.count + 1 });
};

render() {
    return (
        <React.Fragment>
            <span style={this.styles} className={this.getBadgeClasses()}>
                {this.formatCount()}
            </span>
            <button
                onClick={this.handleIncrement}
                className="btn btn-secondary btn-sm"
               >
                Increment
            </button>
        <React.Fragment>
            );
}
getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
}

formatCount() {
    const { count } = this.state;
    return count === 0 ? "Zero" : count;
    }
}
export default Counter;
//Counters.jsx

import React, { Component } from "react";
import Counter from "./Counter";

class Counters extends Component {
    state = {};
    render() {
        return (
            <div>
                <Counter />
                <Counter />
                <Counter />
                <Counter />
            </div>
        );
    }
}

export default Counters;
//index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "bootstrap/dist/css/bootstrap.css";
import Counters from "./Components/Counters";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <React.StrictMode>
        <Counters />
    <React.StrictMode>
);
reportWebVitals();

Image of the DOM

I have tried to restore everything back to before creating the Counters file where it displayed the Counter file in the DOM but that doesn’t seem to fix the issue. I added code blocks of each files: Counter.jsx, Counters.jsx, and index.js. I also attached a img of the DOM.

Issue with a JS based slideshow

I need to control slider images with the bottom dot pagination properly. But something I’m missing or doing wrong in the code.

You can check the working demo here- https://playcode.io/2070692

And to me, it looks like the issue is here-

I tried to put control inside dots with this:

const currentSlide = (n) => {
    showSlides((slideIndex = n));
};

const dots = document.querySelectorAll('.dot');

dots.forEach((dot) => {
    dot.addEventListener('click', () => {
        console.log(`${slideIndex}`);
        currentSlide(slideIndex + 1);
    });
});

Download multiple files as a folder in JS [duplicate]

In JS, I have the following function to download one file from a URL:

export async function downloadFile(url: string, filename: string) {
  const res = await fetch(url);
  const blob = await res.blob();
  const blobUrl = window.URL.createObjectURL(blob);

  const a = document.createElement('a');
  a.style['display'] = 'none';
  a.href = blobUrl;
  a.download = `${filename}.pdf`;

  window.document.body.appendChild(a);
  a.click();
  window.document.body.removeChild(a);
}

I can reuse this function to download an array of files but I’d like them to download all at once inside a folder.

The browser downloads this folder which would contain all my files. How do I do that?

accessing c# web assembly from javascript in .net MVC

I need to access some c# code from javascript in MVC ,NET (not blazor).
I have the below. I get no error message it just continues to the next statement after the ajax call. There could be 2 possible issues i think. My url: ‘/Home/CreatePostcodeFromCoordinates’, is wrong.
Or my C# assemply is not part of the assembly? or something similar. I am not that experienced with Web techs, I come from a DB background but can’t be that difficult to get this link working right? Can’t see anything else wrong. Also does the return value from C# need to be some special format or a string (as per now) is ok? this could be another reason?
Thank you!

console.log("just before /Home/CreatePostcodeFromCoordinates");

$.ajax({
    type: "POST",
    url: '/Home/CreatePostcodeFromCoordinates',
    data: { param1: longitude, param2: latitude },
    success: function (response) {
        console.log('success');
        console.log(response);
    },
    error: function (error) { 
        console.error(error);
    }
});

Why am I getting UNABLE_TO_VERIFY_LEAF_SIGNATURE when trying to access ldaps?

I’m using a Vagrant VM with Ubuntu 24.04 Noble to develop a project. I’m using Node 20.18.0 and NestJs 10.4.5.
In one of the routes, I´m trying to access a secure ldap server using NodeJs’s ldapts module. This is how I’m doing it:

const client = new Client({
    url: 'ldaps://<ldapip>',
    timeout: 0,
    connectTimeout: 0,
});
const bindDN = 'CN=Administrator,CN=Users,DC=myproject,DC=local';
const password = 'mypdw';

try {
    console.log('D1');
    let cert = fs.readFileSync('/vagrant/backend/certs/mycert.crt');

    console.log(cert.toString('base64'));
    await client.startTLS({
      ca: [cert],
    });
    
    console.log('D2');
    await client.bind(bindDN, password);
    
    console.log('D3');
    (...)
} catch (error) {
    return { status: 500, msg: 'LDAP fail', error }
} finally {
    await client.unbind();
}

When I run this code, D0, D1 and the certificate are printed correctly, but it doesn’t reach point D2. It fails with the following error:

{"code":"UNABLE_TO_VERIFY_LEAF_SIGNATURE"}}

I know for sure that the certificate is emmited by the AD’s CA. I’m using Chromium and the CA is correctly imported to it.
I also tried to create a file with both the user certificate and the CA’s certificate in it and it didn’t work also.

What am I doing wrong ? Do I have to import the CA or certificate in some system certificate database or something ?

JS – recursive function on multidimensional array to filter out only “checked” items (and its parents if a child is selected)

I have this kind of array (i call it categories, these have childCats too)

var cats = [
  {
      "id": 1,
      "name": "A",
      "parentCategoryId": null,
      "parentCategory": null,
      "childCategories": [
          {
              "id": 2,
              "name": "B",
              "parentCategoryId": 1,
              "parentCategory": null,
              "childCategories": [
                  {
                      "id": 3,
                      "name": "C",
                      "parentCategoryId": 2,
                      "parentCategory": null,
                      "childCategories": []
                  },
                  {
                      "id": 4,
                      "name": "D",
                      "parentCategoryId": 2,
                      "parentCategory": null,
                      "childCategories": []
                  },
                  {
                      "id": 5,
                      "name": "E",
                      "parentCategoryId": 2,
                      "parentCategory": null,
                      "childCategories": []
                  }
              ]
          }
      ]
  },
  {
      "id": 66,
      "name": "BLA",
      "parentCategoryId": null,
      "parentCategory": null,
      "childCategories": []
  },  
  
];

What i now need is to get an array with checked items (and its parents)

This means, i checked only “C”, i get:

[
  {
      "name": "A",
      "childCategories": [
          {
              "name": "B",
              "childCategories": [
                  {
                      "name": "C",
                      "childCategories": []
                  }
              ]
          }
      ]
  }
]

if i checked “C” and “D”:

var cats = [
  {
      "name": "A",
      "childCategories": [
          {
              "name": "B",
              "childCategories": [
                  {
                      "name": "C",
                      "childCategories": []
                  },
                  {
                      "name": "D",
                      "childCategories": []
                  }
              ]
          }
      ]
  },    
];

and for “B” this:

var cats = [
  {
      "name": "A",
      "childCategories": [
          {
              "name": "B",
              "childCategories": []
          }
      ]
  },    
];

What i currently have (and it feels like a mess) is that: (result in console.log(..))

console.clear();
var cats = [
  {
      "id": 1,
      "name": "A",
      "parentCategoryId": null,
      "parentCategory": null,
      "childCategories": [
          {
              "id": 2,
              "name": "B",
              "parentCategoryId": 1,
              "parentCategory": null,
              "childCategories": [
                  {
                      "id": 3,
                      "name": "C",
                      "parentCategoryId": 2,
                      "parentCategory": null,
                      "childCategories": []
                  },
                  {
                      "id": 4,
                      "name": "D",
                      "parentCategoryId": 2,
                      "parentCategory": null,
                      "childCategories": []
                  }
              ]
          }
      ]
  },
  {
      "id": 66,
      "name": "BLA",
      "parentCategoryId": null,
      "parentCategory": null,
      "childCategories": []
  },  
  
];

var checkedInterests = ['C'];
var checkedInterestsForDisplay = [];

var getInterestsForDisplay = function(arr){
  for(var a of arr){
      if(checkedInterests.includes(a.name)){
          
          a.childCategories=[];
          checkedInterestsForDisplay.push(a);
          
          //also if a child is checked, the parent should be expanded
          var getParents = function(arrayToFindParent, parentIdToFind){          
          
              for(var aTFP of arrayToFindParent){              
                  if(aTFP.id == parentIdToFind){
                      aTFP.childCategories=checkedInterestsForDisplay;                      
                      checkedInterestsForDisplay = [aTFP];                      
                      //again check if it has parents
                      getParents(cats, aTFP.parentCategoryId);
                  }
                  else {
                      getParents(aTFP.childCategories, parentIdToFind);
                  }
              }
          }
          getParents(cats, a.parentCategoryId);
      }
      getInterestsForDisplay(a.childCategories);
  }
}

getInterestsForDisplay(cats);

console.log('checkedInterestsForDisplay', checkedInterestsForDisplay);

this works oky, but if var checkedInterests = [‘C’,’D’];
i get a “Maximum call stack size exceeded”

I am converting Excel to JSON but not getting correct format

i am not able to get exact match in output for special characters other than english for eg below characters

邮件

倫理規定

i am getting below output

“clientPartnerCode”: “1240”,
“documentCode”: “361527”,
“fileName”: “02946976_VALEO u90aeu4ef6 – To Supplier Dynacast Holdings Limited Bank Account Change confirmation.pdf”,
“documentType”: “Certificate”,
“filePath”: “/users/vleuftpusr2/Migration_attachments_supplier/MergeattachmentsValeoSuppierFiles”

But i want as below

“clientPartnerCode”: “1240”,
“documentCode”: “361527”,
“fileName”: “02946976_VALEO 邮件 – To Supplier Dynacast Holdings Limited Bank Account Change confirmation.pdf”,
“documentType”: “Certificate”,
“filePath”: “/users/vleuftpusr2/Migration_attachments_supplier/MergeattachmentsValeoSuppierFiles”

Make a cursor on a half circle

I want to create a semi circle on which I’d like to add a cursor that will move from the left to the right according a score :

0/10 it will be at the beginning and 10/10 it will be at the end.

I have tried to create something using radial-gradient and conic-gradient, but I’m not sure it the right way to start that.

Here is a jsfiddle showing that.

https://jsfiddle.net/tfm43vry/

Thank you for your help