How can I pass a variable that consists of options to `client.request` undici?

I have a function that uses undici.Client, I am trying to use client.request with some options that are stored in a variable to make the call but I get the following error:

InvalidArgumentError: invalid opts

My function is as follows:

module.exports.request = async (clientName, method, path, options) => {
  const client = await getClient(clientName);
  log.info('calling %s from %s', path, client.url);
  let preparedOptions = await prepareOptions(clientName, method, client.url + path, options);
  console.log('options---->', preparedOptions);
  return client.request(path, preparedOptions)
    .catch(async (err) => {
      if (!isNil(err.response) && (err.response.statusCode === 401 || err.response.statusCode === 403)) {
        preparedOptions = await prepareOptions(clientName, method, client.url + path, options, true);
        return client.request(path, preparedOptions);
      }
      throw err;
    });
};

The console.log(preparedOptions) looks like:

options---------------------------------> {
  retry: {
    limit: 3,
    methods: [ 'GET', 'POST' ],
    statusCodes: [ 100 ],
    calculateDelay: [Function: calculateDelay]
  },
  method: 'GET'
}

This looks like a reasonable output to me.

How can I overcome this error?

I have created a gist if further info is required on other functions used

PS: The current function will not match on gist as I am updating it but if more info on prepareOptions or getClient is reqiured, you can refer to the gist.

Return string from nested function [duplicate]

I have this function (it is a fetch function), and I need it to return a new API URL (using the same API variable). What am I not understanding here?

var generateUrl = function(city) {
     var apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&exclude=minutely,hourly,daily,alerts" + apiKey;
     var response = fetch(apiUrl).then(function(response){
        response.json().then(function(data) {
            apiUrl = "https://api.openweathermap.org/data/2.5/onecall?lat=" + data.coord.lat + "&lon=" + data.coord.lon + "&exclude=minutely,hourly,alerts&units=imperial" + apiKey;
        });
    });
    return apiUrl;
}

How to force body to load after all my scripts in head are loaded

I have a lot of scripts and styles in head tag and sometimes body loads before they (scripts and styles) are loaded, this causes some bugs like content doesn’t loads properly. Here’s how my head looks like:

<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 href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="w3.css">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
 <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,500,1,0" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
    integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <!--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">-->
  <script src="index.js"></script>
  <title>NCA</title>
</head> 

Now I can’t do $(document).ready(function () { ... }); as there are many functions in my index.js file and also I want to force the body load after head is loaded… Is there any way to do it?

Password Protect Websites – Showing different content, depending on password

im looking for a way to password protect a website in such way, that depending on which password a person is using at the landing page, different content will be shown. (MVP)

I wish that it also tracks the logins in count and if possible from which location.

does anyone know an addon, code, or can come up with a easy solution?
It can also be custom code without the wordpress functionality or so, as long as we can fulfill the password protection leading to different pages.

cheers

Stop table row height from filling whole table body

I have a table, when I add a row to it, the row’s height will fill the whole body of the table. I want to force the height to only be around 10% of the tables body height, and let the rest of the tabe body to be empty. I’ve tried adding a height propery of 10% to the tbody tr selector but nothing happens. My goal is to have a row take up about 10% of the open area, and then when I click add row, another one will appear under it until the whole table body is full of rows.

Here is my code

#home-index {
            margin-top: 10px;
        }

        tbody {
            height: 604px;
        }

        td {
            border: 1px solid lightgray;
        }

        .hours-cell:hover {
            background-color: darkorange;
        }

        tr {
            border: 1px solid lightgray;
        }

        th {
            border: 1px solid lightgray;
        }
        .dropdown {
            width: 25%
        }
<table>
                <thead>
                    <tr>
                        <th>Project</th>
                        <th>Task</th>
                            <th>7/11</th>
                            <th>7/12</th>
                            <th>7/13</th>                           
                        <th>Total Hours</th>        
                    </tr>
                </thead>
                <tbody>
                    <tr>
                       <td class="dropdown"><select asp-for="Project" asp-items="Model.Projects"></select></td>
                       <td class="dropdown"><select asp-for="Task"></select></td>
                            <td class="hours-cell">--</td>
                            <td class="hours-cell">--</td>
                            <td class="hours-cell">--</td>
                            <td></td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="2">Overall Totals</td>
                            <td class="hours-cell">--</td>
                            <td class="hours-cell">--</td>
                            <td class="hours-cell">--</td>
                            <td></td>
                    </tr>
                    <tr>
                        <td colspan="2">Over/Under</td>
                            <td class="hours-cell">--</td>
                            <td class="hours-cell">--</td>
                            <td class="hours-cell">--</td>
                            <td></td>
                    </tr>
                </tfoot> 
           </table>

Collapse an accordion menu

I have this simple collapsible menu on www.keokuk.com
I would like for the previous menu to close when you click on the next one.

this is the javascript:

<script>
    var coll = document.getElementsByClassName("collapsible");
    var i;

    for (i = 0; i < coll.length; i++) {
      coll[i].addEventListener("click", function () {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.maxHeight) {
          content.style.maxHeight = null;
        } else {
          content.style.maxHeight = content.scrollHeight + "px";

        }
      });
    }
  </script>

How do I create a NavBar using React Boostrap in JS?

I am trying to create a boostrap react navbar, I am following a guide and this code SHOULD be working but it isn’t. Instead it only displays the “database” text and not the navbar. Please do keep in mind that I know there are different ways of creating ne but I want to fix this code. Any help would be greatly appreciated!

App.js:

import './App.css';

import {Home} from './Home';
import {Student} from './Student';
import {Professor} from './Professor';
import {Course} from './Course';
import {Navigation} from './Navigation';

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

function App() {
  return (
    <Router>
      <div className="container">
        <h3 className="m-3 d-flex justify-content-center">
          Database
        </h3>

        <Navigation/>

        <Routes>
          <Route path='/' component={Home} />
          <Route path='/student' component={Student}/>
          <Route path='/professor' component={Professor}/>
          <Route path='/course' component={Course}/>
        </Routes>
      </div>
    </Router>
  );
}


export default App;

Navigation.js:

import React,{Component} from 'react';
import {NavLink} from 'react-router-dom';
import {Navbar, Nav} from 'react-bootstrap';

export class Navigation extends Component
{
    render()
    {
        return
        {
            <Navbar bg="dark" expand="lg">
                <Navbar.Toggle aria-controls="basic-navbar-nav"/>
                <Navbar.Collapse id="basic-navbar-nav">
                    <Nav>
                        <NavLink className="d-inline p-2 bg-dark text-white" to="/">
                            Home
                        </NavLink>
                        <NavLink className="d-inline p-2 bg-dark text-white" to="/student">
                            Students
                        </NavLink>
                        <NavLink className="d-inline p-2 bg-dark text-white" to="/professor">
                            Professors
                        </NavLink>
                        <NavLink className="d-inline p-2 bg-dark text-white" to="/course">
                            Courses
                        </NavLink>
                    </Nav>
                </Navbar.Collapse>
            </Navbar>
        }
    }
}

Is there a general Error Handler in Colyseus?

I am fairly new to Colyseus (colyseus.io) and want to know if there exists a global error catcher. I am working on an already existing code with all the controllers created and it would be rookie to implement try and catch in all the controllers. I need a global error catcher to that detects breaks in the code and responds to the client. Is there an existing library for that or an existing code implementation.

what is the usecase of c++ in 2022 and in further times?

almost 50% of 2022 is over we are already booming with technological advancements. is it still profitable to learn c++? what are its use cases? for example, javascript is the language of the internet, websites are made using JS, and rust and solidity are used in web3 development.

Where can c++ be used?
I tried searching for this and found that game development can be done by using c++. What other options do I have?

Cypress loop execution order

I’ve used the idea described here to run the test multiple times with different input values. But I’ve met a problem that Cypress manages loop pretty strange. To test the problem I’ve created a minimized application:

$(document).ready(() => {
  $('#submit').on('click', () => {
    $('#result').val($('#result').val() + $('#select').val() + 'n');
  });
});
select, button, textarea{
  font-size: 1.2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select">
  <option value="" disabled="" selected="">Choose</option>
  <option value="first">First</option>
  <option value="second">Second</option>
  <option value="third">Third</option>
  <option value="fourth">Fourth</option>
</select>
<button id="submit">Add</button>
<br>
<textarea id="result" rows="20" cols="50"></textarea>

The test I run using Cypress:

describe('Test', () => {
    it('should add entries to textarea', () => {
        cy.visit('http://localhost/cypress-fail/index.html');
        cy.get('#select', { timeout: 10000 }).should('be.visible');
        let selected = [];
        for (let i = 0; i < 4; i++) {
            selected.push(i + 1);
            let last_selected = selected[selected.length - 1];
            cy.get('#select').children('option').then($options => { console.log(($options[last_selected])); cy.wrap($options[last_selected]).invoke('attr','value').then(value => cy.get('#select').select(value))});
            cy.get('#submit').click().then(()=> console.log("submitted"));
            cy.wrap(selected).should('have.length', i + 1);
            //expect(selected).to.have.length(i+1);
            cy.get('#result').invoke('val').then(text => {
                let list = text.split('n').filter(a => a);
                cy.wrap(list).should('have.length', i + 1);
            })
        }
    })
})

As the result of the test I get assert error:

assert: expected [ 1, 2, 3, 4, 5 ] to have a length of 1 but got 5

However if I use the “expect” line and try Chai-style this test passes, but it checks the array each loop first and then loops again to add selected entries into textarea.
Can it be that Cypress has its own loop execution logic? Is there a way to make it work more predictably?
And in total I’ve noticed that since version 10.0.0 Cypress won’t wait where it did before, like waiting for page to load where now I have to add timeout configs.

How to handle errors when localStorage permission is not granted?

I came across this interview question which asked me the question how do you handle errors when localStorage permission is denied.

I researched through docs and found that such an issue could arise if user has setup browser to deny use of storing data. This results in code throwing SecurityError

I tried to come up with a solution by wrapping localStorage methods viz. setItem() & getItem() into try{..} catch(e){...} blocks.

I was curious to know if a browser fails to give access to localStorage What other options do I have to store my data so that I can gracefully handle this scenario ?

CSS file failed to load resource

my CSS file won’t load when I open it up as a webpage, but when I see the output of it all the design changes are there. Does anyone know why this is happening? I don’t know if the css href is in incorrect or if I’m missing something in my code. Thank you for any help.
Here’s the code:

<!DOCTYPE html>
<html lang = "en">

<head>
  <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cormorant+SC:wght@300&display=swap" rel="stylesheet">


  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width">
  <link href="France/france.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class = "headerFrance">
  <h1 class = "title">France</h1>
  <hr>
</div>
<div class = "generalInfo">
<div class = "fashionTips span-col-two"">
  <h2 >Fashion Tips</h2>
</div>
<div class = "climate">
  <h2>Climate</h2>
</div>
<div class = "brands">
  <h2>Brands</h2>
</div>
<div class = "fashionInfluencers">
  <h2>Fashion Influencers</h2>
</div>
</div>
<div class = "photoGallery">
  <div class = "galleryHead">
    <h2 class = "pictureTitle">Photo Inspo</h2>
  </div>
  <div class = "rowOne">
    <img src = "xxx">
    <img src = "xxx">
    <img src = "xxx">
    <img src = "xxx">
  </div>
   <div class = "rowTwo">
    <img src = "xxx">
    <img src = "xxx">
    <img src = "xxx">
    <img src = "xxx">
  </div>
   <div class = "rowThree">
    <img src = "xxx">
    <img src = "xxx">
    <img src = "xxx">
    <img src = "xxx">
  </div>
  

  
</body>

Here’s an image of the file directory if that helps too

how can i show the output in only 2 decimals

<!DOCTYPE html>
<html lang="en">
  <head> </head>

  <body translate="no">
    <input type="number" placeholder="user enter's here" name="price" id="price_1" />

    <input type="number" name="qty" value="0.0039" id="qty_1" />

    <input type="number" placeholder="output" name="total" id="total_1" readonly />

    <script src="https://cpwebassets.codepen.io/assets/common/stopExecutionOnTimeout-1b93190375e9ccc259df3a57c1abc0e64599724ae30d7ea4c6877eb615f89387.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script id="rendered-js">
      "use strict";
      $("#price_1, #qty_1").keyup(function () {
        var price = parseFloat($("#price_1").val());
        var qty = parseFloat($("#qty_1").val());
        $("#total_1").val(price * qty);
      });

      //# sourceURL=pen.js
    </script>
  </body>
</html>

i do have a code which substract the amount user enter’s and when user enter an decimal number it will show very long number how can i short it to two places 39409.44

Can a Proxy really provide access to private fields of a class?

I’m reading the documentation here, and it seems to imply that even for private fields, it would be possible to access them via a Proxy. See the blurb that starts with “….To fix this….”. But the example given, doesn’t work. My code is shown below:

The class with the private field:

class Danger {
    #areYouSure = "magic";

    grave(){
        console.log("Yes, grave danger");
        return true;
    }

}

module.exports = Danger;

Trying to use a proxy to access it:

const Danger = require('./testing-private');

const handler = {
    get(target, property, receiver){
        return target[property];
    }
};
const dangerProxy = new Proxy(new Danger(), handler);

console.log("--------------------------------------", dangerProxy.areYouSure);

This prints out:

-------------------------------------- undefined

If I replace “dangerProxy.areYouSure” with “dangerProxy.#areYouSure”. I get

/home/zaphod/code/math/js-experiments/src/danger-proxy.js:29
console.log("--------------------------------------", dangerProxy.#areYouSure);
                                                                 ^

SyntaxError: Private field '#areYouSure' must be declared in an enclosing class
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1032:15)
    at Module._compile (node:internal/modules/cjs/loader:1067:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Is there a way to get this working or are my expectations incorrect?