move sub array to main array with only one value [closed]

I am strugging to format the below array.

const arr = [
    {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": [
      {
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 3,
        "name": "Glem vital"
      },
      {
        "id": 2,
        "name": "Shiv"
      }
    ]    
  },
  {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": [
      {
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 3,
        "name": "Glem vital"
      },
      {
        "id": 2,
        "name": "Shiv"
      }
    ]    
  },
  {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": [
      {
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 3,
        "name": "Glem vital"
      },
      {
        "id": 2,
        "name": "Shiv"
      }
    ],
  }
];

I want OutPut in below format:

arr = [
    {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": 
      {
        "id": 1,
        "name": "Test 1"
      }  
  },
  {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": 
      {
        "id": 2,
        "name": "Glem vital"
      }   
  },
  {
    "id": 96,
    "body": "Post on FB",
    "smAccounts":
      {
        "id": 3,
        "name": "Shiv"
      }
  }
];

Can’t find a solution to login to external webapp through auth0 [closed]

I’m using a web application (this is not mine app, just external), which implements an auth0.
My aim is to login to my account via JS-code. Like, I want to make http calls not through UI, but from my code. As far as I understand, I need to provide my credentials to auth0, they would return me JWT, and I would provide it to webapp. Can you please help me?

I’ve found this example, but how can I know details like “scope”?

auth0.authorize({
  audience: 'https://mystore.com/api/v2',
  scope: 'read:order write:order',
  responseType: 'token',
  redirectUri: 'https://example.com/auth/callback'
});

How to install expo cli on windows 10

I get those errors and i don’t know what to do, anyone with the solution help me please

I was expecting expo to be successfully installed.

What can I do to get started with my mobile app development journey please help me out

React native/Javascript class that can iterate images pixels for build a new one and modify them

I didn’t found solution yet.
My goal is to implement an Image and then a Blur class not linked to a react native component.
It must take an uri in input and return an output uri of the modify image.
So the goal is to be able to read an image, iterate pixels, modify them, rebuild an image.

All that if possible without using too much external libraries.

I made several tests but always an echec.
For exemple, this do not read the pixels:

class Image{
    constructor(src){
        this.src = src
        this.datas = null
    }

    async load(){
        try {
            console.log('Fetching image from:', this.src);
            const response = await fetch(this.src);
            console.log('response',response)
            const blob = await response.blob();
            const reader = new FileReader();

            return new Promise((resolve, reject) => {
              reader.onload = () => {
                const buffer = reader.result;
                this.datas = new Uint8Array(buffer);
                console.log('Image loaded successfully');
                resolve();
              };

              reader.onerror = (error) => {
                console.error('Error during FileReader operation:', error);
                reject(error);
              };

              console.log('Starting to read image blob');
              reader.readAsArrayBuffer(blob);
            });
          } catch (error) {
            console.error('Error loading image:', error);
          }
    }

Thank you in advance for your help.

style object broken in JS

Im trying to use .style to style some things on the thing that i’m working on. it’s a weather app and
I don’t know why but it doesn’t work so I’m going to send you guys the codes and tell me what’s wrong:

<!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
        href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&family=Roboto:wght@300;400;500;700;900&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <title>Weather App | Radmehr Firoozbkaht</title>
</head>

<body>

    <div class="container" id=".container">
        <div class="search-box" id=".search-box">
            <i class="fa-solid fa-location-dot"></i>
            <input type="text" placeholder="Enter your location">
            <button class="fa-solid fa-magnifying-glass"></button>
        </div>

        <div class="not-found" id=".not-found">
            <img src="images/404.png">
            <p>Oops! Invalid location :/</p>
        </div>

        <div class="weather-box" id=".weather-box">
            <img src="">
            <p class="temperature"></p>
            <p class="description"></p>
        </div>

        <div class="weather-details" id=".weather-details">
            <div class="humidity">
                <i class="fa-solid fa-water"></i>
                <div class="text">
                    <span></span>
                    <p>Humidity</p>
                </div>
            </div>
            <div class="wind">
                <i class="fa-solid fa-wind"></i>
                <div class="text">
                    <span></span>
                    <p>Wind Speed</p>
                </div>
            </div>
        </div>

    </div>

    <script src="https://kit.fontawesome.com/7c8801c017.js" crossorigin="anonymous"></script>
    <script src="index.js"></script>
</body>

</html>

Java Script:

const container = document.querySelector('.container');
const search = document.querySelector('.search-box button');
const weatherBox = document.querySelector('.weather-box');
const weatherDetails = document.querySelector('.weather-details');
const error404 = document.querySelector('.not-found');

search.addEventListener('click', () => {

    const APIKey = 'Your Api Key';
    const city = document.querySelector('.search-box input').value;

    if (city === ''){
        return;
    }

    fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${APIKey}`)
        .then(response => response.json())
        .then(json => {

            if (json.cod === '404') {
                container.style.height = '400px';
                weatherBox.style.display = 'none';
                weatherDetails.style.display = 'none';
                error404.style.display = 'block';
                error404.classList.add('fadeIn');
                return;
            }

            error404.style.display = 'none';
            error404.classList.remove('fadeIn');

            const image = document.querySelector('.weather-box img');
            const temperature = document.querySelector('.weather-box .temperature');
            const description = document.querySelector('.weather-box .description');
            const humidity = document.querySelector('.weather-details .humidity span');
            const wind = document.querySelector('.weather-details .wind span');

            switch (json.weather[0].main) {
                case 'Clear':
                    image.src = 'images/clear.png';
                    break;

                case 'Rain':
                    image.src = 'images/rain.png';
                    break;

                case 'Snow':
                    image.src = 'images/snow.png';
                    break;

                case 'Clouds':
                    image.src = 'images/cloud.png';
                    break;

                case 'Haze':
                    image.src = 'images/mist.png';
                    break;

                default:
                    image.src = '';
            }

            temperature.innerHTML = `${parseInt(json.main.temp)}<span>°C</span>`;
            description.innerHTML = `${json.weather[0].description}`;
            humidity.innerHTML = `${json.main.humidity}%`;
            wind.innerHTML = `${parseInt(json.wind.speed)}Km/h`;

            weatherBox.style.display = '';
            weatherDetails.style.display = '';
            weatherBox.classList.add('fadeIn');
            weatherDetails.classList.add('fadeIn');
            container.style.height = '590px';


        });


});

so i tried everything but nothing worked aswell and i even asked AI but it couldn’t guess why asWell
so please help me because I’m dying trying to fix it

Dash app client-side callback not passing value to server-side callback

I’m working on a Dash app integrated with a Django template, and I’m encountering an issue where a client-side callback is not passing a value to a server-side callback. The value is correctly logged in the browser’s console but appears as None on the server side when the server-side callback is triggered.

**Minimal Code
**

# template.html
{% load plotly_dash %}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script>
            setTimeout(function() {
                function getSelectedLAName() {
                    const selected_la_name_element = document.getElementById('selected-la-name');
                    if (selected_la_name_element) {
                        const selected_la_name = selected_la_name_element.getAttribute('data-la-name');
                        console.log("Selected LA Name:", selected_la_name);
                        return selected_la_name;
                    } else {
                        console.log("Element not found");
                        return null;
                    }
                }

                getSelectedLAName();  // Call the function to test
            }, 500);  // Delay in milliseconds
        </script>
    </head>
    <body>
        <h1>DASH APP Test</h1>
        <div id="selected-la-name" data-la-name="{{ selected_la.search_term }}"></div>
        {{ selected_la.search_term }} 
        <div id="dash-container" style="width: 100%; height: 600px; border: 1px solid red;">
             {% plotly_app name="dash_app" ratio=1 %}
        </div>
    </body>
</html>
# dash_app.py
from django_plotly_dash import DjangoDash
from dash import dcc, html
from dash.dependencies import Input, Output
from common.common_utils import *
import plotly.graph_objects as go

app = DjangoDash('dash_app')

app.layout = html.Div([
    html.Div(id='selected_la_name', style={'display': 'none'}),
    dcc.Dropdown(
        id='data-type',
        options=[
            {'label': 'Number', 'value': 'number'},
            {'label': 'Percentage', 'value': 'percentage'}
        ],
        value='number',
        style={'height': '30px', 'width': '50%', 'font-size': '16px'}
    ),
    dcc.Graph(
        id='heatmap',
        style={'height': '600px', 'padding': '8px'}
    )
])

# Client-side callback to extract value from hidden div
app.clientside_callback(
    """
    function() {
        const selected_la_name_element = document.getElementById('selected-la-name');
        return selected_la_name_element ? selected_la_name_element.getAttribute('data-la-name') : null;
    }
    """,
    Output('selected_la_name', 'children'),
    Input('heatmap', 'id')  # Dummy input to trigger the callback
)

# Server-side callback to update the graph
@app.callback(
    Output('heatmap', 'figure'),
    [Input('data-type', 'value'),
     Input('selected_la_name', 'children')]
)
def update_graph(data_type, selected_la_name):
    print(f"Received selected_la_name: {selected_la_name}") 
    if not selected_la_name:
        return go.Figure()  

    if data_type == 'number':
        data_norm, data = func_name(selected_la_name)
    else:
        data_norm, data = func_name(selected_la_name)

    fig = go.Figure(data=go.Heatmap(
        x=data_norm.columns,
        y=data_norm.index,
        z=data_norm.values
    ))
    return fig

OUTPUTS

In template.html

  • console.log(“Selected LA Name:”, selected_la_name);
    Output is correct

  • {{ selected_la.search_term }}
    output is correct

in dash_app.py

  • print(f”Received selected_la_name: {selected_la_name}”)
    Outputs: None (ie incorrect)

What I Have Tried:

  • Verified that the data-la-name attribute is correctly set in the HTML.
  • Checked that the client-side callback is executed and logs the expected value.
  • Ensured there is a delay to allow the DOM to fully load, but the issue persists.

Additional Information:

Using Dash version 2.9.3
Using Django version 4.2.13

Thank you for your help!

Passing a value from a service worker to HTML

I am trying to improve a progressive web app that I made fairly recently. To save a little time when developing and to reduce the risk of an error I would like to display the version number automatically instead of manually copying it into HTML.

The version number is defined as the cache name in the service worker:

const cacheName = '1.6.2';

The service worker is registered by register.js which is called in the head of each HTML page.

<script src="register.js" defer></script>

Then in a script at the end of the body I have:

document.getElementById('versionNo').innerHTML = cacheName;

And in the HTML:

<span id="version">Version: <span id="versionNo"></span></span>

However this leaves the version number blank and the javascript console reports “jquery.js:2 Uncaught ReferenceError: cacheName is not defined”. Is there an error in my thinking or is this just not possible?

How to apply multiple times rotation on same image using Sharp library in Node.js?

I am sending an image from front end to backend ( using multer ) . At backend , I want to rotate it multiple times. If 1 rotation is done, I am storing that image in backend itself. For next rotation, I am giving path of the previously rotated image ( which I have stored in backend itself ). Once this process is done, I am sending that image to front end.

At backend I am using Node.js and Sharp library.

But what is happening, that 1st time image is rotating properly. Getting stored at backend but 2nd time gets error that “Image is not there or it is inaccessible”

I checked that there is an image present in respective folder at backend. And I am sending it’s correct path also. ( I tried both relative and absolute path of the image for this process )

Here is the rotation implementation using sharp library.

sharp(resolvedImagePath)
    .rotate(rotate)
    .toFile(fullQualityOutputPath, (err, info) => {
     
      if (err) {
        fullQualityResult = {
          success: false,
          message: "Error processing full-quality image",
        };
      } else {
        fullQualityResult = {
          success: true,
          message: "Full-quality image processed",
          image_url: fullQualityOutputPath, // Path to the full-quality image
        };
      }
    });
       
  Where am I wrong ? Why "Image inaccessible" type error I am getting ? 

Have a problem with the webpage size being too large

I have i problem with the width of the webpage being to wide.

let map;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

  map = new Map(document.getElementById("map"), {
    center: { lat: 60.3690453554567, lng: 5.350072840196482 },
    zoom: 15,
    mapId: "e1b5c8f5a7e3b6e",
  });

  marker = new google.maps.marker.AdvancedMarkerElement({
    map,
    position: { lat: 60.3690453554567, lng: 5.350072840196482 },
    });
}

initMap();
* {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  max-width: 960px;
  margin: 0 auto;
}
.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #333;
    padding: 15px 20px;
  }
  
  .navbar-links-container {
    display: flex;
    list-style-type: none;
    margin: 0;
    padding: 0;
  }
  
  .navbar-link a {
    color: white;
    text-decoration: none;
    font-size: 1rem;
    padding: 8px 12px;
    transition: background-color 0.3s ease;
  }
  
  .navbar-link a:hover {
    background-color: #575757;
    border-radius: 4px;
  }
  .navbar-hamburgerMenu {
    color: white;
  }
  

#map {
    height: 500px;
    width: 40%;
    margin: 0px;
    padding: 20px;
    position: relative;
    top: -100px;
    left: 0px;
    align-items: center;

}

h2 {
    display: flex;
    font-family: Arial, sans-serif;
    font-size: 30px;
    font-weight: bold;
    color: #000;
    margin: 0 0 10px 0;
    position: relative;
    top: -100px;
    left: 0px;
    align-items: center;
    text-align: center;
}

h1 {
    display: flex;
    font-family: Arial, sans-serif; 
    font-size: 30px;
    font-weight: bold;
    color: #000;
    margin: 0 0 10px 0;
    position: relative;
    top: 220px;
    left: 600px;
    text-align: center;
}

.ul_kontakt li {
    display: flex;
    list-style-type: none;
    list-style-position: inside;
    line-height: 1.5;
    font-size: 20px;
    position: relative;
    top: 200px;
    left: 600px;
    text-align: center;
}

.div_kontakt {
  position: relative;
  justify-content: center;
  float: right;
  text-align: center;
  max-width: 960px;
  margin: 0 auto;
  padding: 0 20px;
  
}
<!DOCTYPE html>
<html>
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>
            HVLTopia Kontakt oss
        </title>
    <script>
        (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
          key: "AIzaSyDMSf58ogqi6b-SYOZiuQ-a6PuQDXRrtY4",
          v: "weekly",
          // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
          // Add other bootstrap parameters as needed, using camel case.
        });
      </script>
    <link rel="stylesheet" href="kontakt.css">
    <body>
        <nav class="navbar">
            <ul class="navbar-links-container">
              <li class="navbar-link"><a href="#home">Home</a></li>
              <li class="navbar-link"><a href="#news">Status</a></li>
              <li class="navbar-link"><a href="#contact">Info</a></li>
              <li class="navbar-link"><a href="#about">Contact</a></li>
            </ul>
            <svg
              class="navbar-hamburgerMenu"
              width="40"
              height="28"
              viewBox="0 0 40 28"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M2 14H38M2 2H38M2 26H38"
                stroke="white"
                stroke-width="4"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </nav>
        <div class="kontakt">
          <h1>
            Kontakt Info:
        </h1>
          <ul class="ul_kontakt">
            <li>
                Telefon: +47 123 45 678
            </li>
            <li>
                Besøksadresse: 5003 Bergen
            </li>
            <li>
                Fax: +47 123 45 678
            </li>
            <li>
                Epostadresse: [email protected]  
            </li>
          </ul>
        </div>
        <h2>
            Finn oss her:
        </h2>
      <div id="map">
        <script src="kontakt.js"></script>
        </div>
            
        </body>
</html>

Tried to change the width on the different contents.
Mostly the problem width the ul and h1 but i am not sure how to fix it.

I have tried a few things, but nothing seems to work.

Anyone that could help me

Is it possible to scrape for dynamic content with HtmlUnit?

I try to use HtmlUnit to automate login process on my local TP-Link Router web-page. This is how the login page with the form on it is rendered in my Firefox browser:

The standard TP-Link Router login page

And here is the code snippet to interact with the form:

package org.example;

import org.htmlunit.BrowserVersion;
import org.htmlunit.WebClient;
import org.htmlunit.html.HtmlInput;
import org.htmlunit.html.HtmlPage;

import java.io.IOException;

public class LoginFormScraper {
    public static void main(String[] args) throws IOException {

        try (WebClient webClient = new WebClient(BrowserVersion.FIREFOX)) {
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setCssEnabled(false);

            HtmlPage page = webClient.getPage("http://tplinkwifi.net/webpages/index.html#/login");
            webClient.waitForBackgroundJavaScript(30 * 1000);
            HtmlInput passwordInput = page.getFirstByXPath("//input[@type='password']");

            if (passwordInput != null) {
                passwordInput.setValue("foo");
                // continue form scraping
            } else {
                System.out.println("No input element found!");
                System.out.println("///////////////////////");
                System.out.println(page.asXml());
            }
        }
    }
}

However, the output produced by that code is always like this, indicating that the page content is never given a chance to be fully loaded in the headless browser window:

No input element found!
///////////////////////
<?xml version="1.0" encoding="UTF-8"?>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <meta name="version" content="AX55v1_1.11.0_2024-06-28T02:38:47.196Z"/>
    <meta name="ui-type" content="svr"/>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=0"/>
    <meta name="apple-touch-fullscreen" content="yes"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
    <meta name="format-detection" content="telephone=no"/>
    <link rel="shortcut icon" href="./assets/ico/favicon-ccbe82f2.ico"/>
    <title>
      Opening...
    </title>
    <script type="module" crossorigin="" src="./js/index-6a96bdab.js">
    </script>
    <link rel="modulepreload" crossorigin="" href="./js/index-ba20424f.js"/>
    <link rel="modulepreload" crossorigin="" href="./js/vendor-d41cf34c.js"/>
    <link rel="modulepreload" crossorigin="" href="./js/su-a307a2f8.js"/>
    <link rel="modulepreload" crossorigin="" href="./js/update-store-e417b711.js"/>
    <link rel="stylesheet" href="./assets/css/index-3aab50d1.css"/>
  </head>
  <body>
    <div id="app">
    </div>
    <script type="text/javascript">
//<![CDATA[

    (function handleUnsupportedBrowser() {
      try {
        // https://cn.vuejs.org/about/faq.html#what-browsers-does-vue-support
        const isIE
          = window.ActiveXObject
          || 'ActiveXObject' in window
          || /MSIE|Trident/.test(window.navigator.userAgent)
        const isUnsupportedBrowser = !localStorage || !localStorage.setItem || isIE

        if (isUnsupportedBrowser) {
          throw new Error('unsupported browser')
        }
      } catch (error) {
        location.href = './error.html'
      }
    })()
  
//]]>
    </script>
  </body>
</html>

Is there any way I can access HTML elements in a situation like this with HtmlUnit or should I use a different tool?

Will the Provider render my whole App client-side?

I am following this PostHog tutorial and it involves wrapping my whole app in the PostHogProvider, which has a use client directive. Will this effectively turn my whole app into a client side app and opt me out of Next.js server components?

// app/providers.js
'use client'
import posthog from 'posthog-js'
import { PostHogProvider } from 'posthog-js/react'

export default function PHProvider({ children, bootstrapData }) {
  if (typeof window !== 'undefined') {
    posthog.init("<ph_project_api_key>", {
      api_host: "https://us.i.posthog.com",
      bootstrap: bootstrapData
    })
  }

  return <PostHogProvider client={posthog}>{children}</PostHogProvider>
}

React Internal server error: URI error on successfull api call

Im new to React and have created a Remix React app which calls a python hosted api backend to recieve a timestamp (for now).

The api call is successfull and there is full communication with the backend, however the problem is that once the data has been fetched it throws an “[vite] Internal server error: URI error”, which i cannot troubleshoot.

Step 1 -> go to http://localhost:5173/dashboards/external/AAA

Step 2 -> dashboards.external.$iata.tsx is displayed and a api call is made to my python made backend

Step 3 -> HTML is loaded but the terminal throws “[vite] Internal server error: URI error”

import { useParams } from "@remix-run/react";
import { json, LoaderFunction } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import styles from '~/styles/spinner.css';

export function links() {
  return [{ rel: "stylesheet", href: styles }];
}

type LoaderData = {
  apiData: any;
};

export const loader: LoaderFunction = async ({ request }) => {
  const url = new URL(request.url);
  const iata = encodeURIComponent(url.pathname.split('/').pop() || '');

  console.log(iata);

  const currentDate = new Date();
  const firstDayOfYear = new Date(currentDate.getFullYear(), 0, 1);
  const timezoneOffset = -currentDate.getTimezoneOffset();

  const headers = {
    "ITS-API-Key": process.env.API_KEY || "",
    "from": firstDayOfYear.toISOString(),
    "to": currentDate.toISOString(),
    "offset": timezoneOffset.toString()
  };

    let apiData = null;

    const response = await fetch("http://localhost:5000/init", {
        method: "GET",
        headers: headers
    });

    const responseData = await response.text();

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }

    apiData = JSON.parse(responseData);

  return json({ apiData});
};

function LoadingSpinner() {
    return (
      <div className="spinner">
        Loading...
      </div>
    );
  }

export default function ExternalDashboard() {
  const { iata } = useParams();
  const { apiData } = useLoaderData<LoaderData>();

  return (
    <div>
      <h1>External Dashboard</h1>
      <p>Current airport: {iata}</p>
    </div>
  );
}

I cant see why this URI error happens in the first place and it seems to be a vite related issue, the error stack doesnt print anything useful either.

Quastion with redirect Next [closed]

I am writing an application on react + next, and I encountered a redirect, I see in many places that after a redirect an empty object is returned, some do not return anything. Could you help me figure out why some write this way, others that way?

How to create conditional assignment in initialValues of Formik

I have initialValues in Formik but I want to assign values in accordance with another field.

I have this code:

const initialValues: MyValues = {
    fieldType: fieldType.FIELDA,
    fieldInformation: '',
    fieldB: '', 
    dateRange: {
      from: lastWeek,
      to: today,
    },
  };

I want something like:

const initialValues: MyValues = {
    fieldType: fieldType.FIELDA,
    fieldInformation: '',
    fieldB: fieldType === fieldType.FieldA ? 'all' : '', 
    dateRange: {
      from: lastWeek,
      to: today,
    },
  };

So fieldB depends on the value of fieldType. How can I achieve that? The problem is that fieldType is a radioButton and I want to initialize with ” if fieldType.FIELDB is chosen.

Open URL prefilling basic auth

On our lan we have a simple web page with buttons that open various internal sites.

Clicking the button opens the URL in a new tab. This is done using:

var win = window.open('http://' + url, '_blank');
win.focus();

When the new page opens the basic auth popup appears and we have to fill this in and click sign in. Is there any way to populate this using javascript or jquery and click sign in ?

I’ve tried the following, but nothing happened when I clicked the button.

let xhr = new XMLHttpRequest();
xhr.open('get', url, async, username, password)
xhr.send()

Thanks