Inconsistent Behavior of WebCodecs’ copyTo() Method Across Different Browsers and Systems

I’m currently facing an intriguing issue with the WebCodecs API, specifically the copyTo() method. While implementing a feature using this method, I’ve encountered an ‘undefined’ error. Curiously, this error does not occur consistently across all platforms. On some devices, the code executes perfectly, but on others, it fails with this error.
I would appreciate any insights or experiences you might have regarding this issue.

const decoder = new VideoDecoder({
    output(frame) {
        // console.log('frame', frame);
        videoFrames.push(frame);
        ctx.drawImage(frame, 0, 0);
        checkFrameReady();
        frame.close();
    },
    error(e) {
        console.error(e);
    },
});
function checkFrameReady() {
    if (videoFrames.length) {
        const vf = videoFrames[0];
        if (vf && !videoBuffer) {
            videoBuffer = new Uint8Array(vf.allocationSize());
            createVideoTextures(vf, videoBuffer.buffer);
        }
        processNewChunk();
    } 
}

async function createVideoTextures(frame: VideoFrame, buffer: ArrayBuffer) {
    let f
    try {
        // console.log('frame', frame, buffer, typeof frame.codedHeight);
        f = frame.clone();
        await f.copyTo(buffer);
    } catch (e) {
        console.error('Error caught:', e);
    } finally {
        // console.log('videoBuffer', buffer);

        // frame.close();
    }
    
}
hardware Browser error
MacBook Pro 13-inch, 2020 2 GHz 4 core Intel Core i5 Chrome 121 undefined
MacBook air 13-inch, 2020 Intel Core i3 Chrome 121 undefined
MacBook Pro 13-inch, 2020 2 GHz 4 core Intel Core i5 Safari no error but very laggy
MacBook Pro 13-inch, 2020 2 GHz 4 core Intel Core i5 Chrome 109 no error
MacBook Pro 14-inch, 2021 M1 pro Chrome 121 no error
MacBook Pro 13-inch, 2021 M1 Chrome 121 no error
MacBook Pro 13-inch, 2021 M1 Chrome 121 no error
Ipad pro, 2021 M1 Chrome 120 no error but very laggy
Ipad pro, 2021 M1 Safari no error but very laggy
Iphone 13 Chrome 120 no error but very laggy
Iphone 13 Safari no error but very laggy
Xiaomi 11 pro, snapdragon 888 Chrome 120 no error

I guess it is a problem with the chip architecture, but there is an x86 device that does not meet the requirements.

Pevent triggering auto save in material ui datagrid

I created one data-grid and tried to add some records. Add record will create a new empty row. Without filling I tried to press TAB key, but when focusing on save button, it automatically saved. How can I prevent this behaviour. I need to manually press enter while focusing on save button.

Code below

"use client"
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/DeleteOutlined';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Close';
import {
  GridRowsProp,
  GridRowModesModel,
  GridRowModes,
  DataGrid,
  GridColDef,
  GridToolbarContainer,
  GridActionsCellItem,
  GridEventListener,
  GridRowId,
  GridRowModel,
  GridRowEditStopReasons,
} from '@mui/x-data-grid';

const roles = ['Market', 'Finance', 'Development'];
const initialRows: GridRowsProp = [
  {
    id: 1,
    name: "Ash",
    age: 25,
    joinDate: "10-10-2023",
    role: "Market",
  },
];

interface EditToolbarProps {
  setRows: (newRows: (oldRows: GridRowsProp) => GridRowsProp) => void;
  setRowModesModel: (
    newModel: (oldModel: GridRowModesModel) => GridRowModesModel,
  ) => void;
}

function EditToolbar(props: EditToolbarProps) {
  const { setRows, setRowModesModel } = props;

  const handleClick = () => {
    const id = 10;
    setRows((oldRows) => [...oldRows, { id, name: '', age: '', isNew: true }]);
    setRowModesModel((oldModel) => ({
      ...oldModel,
      [id]: { mode: GridRowModes.Edit, fieldToFocus: 'name' },
    }));
  };

  return (
    <GridToolbarContainer>
      <Button color="primary" startIcon={<AddIcon />} onClick={handleClick}>
        Add record
      </Button>
    </GridToolbarContainer>
  );
}

export default function FullFeaturedCrudGrid() {
  const [rows, setRows] = React.useState(initialRows);
  const [rowModesModel, setRowModesModel] = React.useState<GridRowModesModel>({});

  const handleRowEditStop: GridEventListener<'rowEditStop'> = (params, event) => {
    if (params.reason === GridRowEditStopReasons.rowFocusOut) {
      event.defaultMuiPrevented = true;
    }
  };

  const handleEditClick = (id: GridRowId) => () => {
    setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.Edit } });
  };

  const handleSaveClick = (id: GridRowId) => () => {
    setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.View } });
  };

  const handleDeleteClick = (id: GridRowId) => () => {
    setRows(rows.filter((row) => row.id !== id));
  };

  const handleCancelClick = (id: GridRowId) => () => {
    setRowModesModel({
      ...rowModesModel,
      [id]: { mode: GridRowModes.View, ignoreModifications: true },
    });

    const editedRow = rows.find((row) => row.id === id);
    if (editedRow!.isNew) {
      setRows(rows.filter((row) => row.id !== id));
    }
  };

  const processRowUpdate = (newRow: GridRowModel) => {
    const updatedRow = { ...newRow, isNew: false };
    setRows(rows.map((row) => (row.id === newRow.id ? updatedRow : row)));
    return updatedRow;
  };

  const handleRowModesModelChange = (newRowModesModel: GridRowModesModel) => {
    setRowModesModel(newRowModesModel);
  };

  const columns: GridColDef[] = [
    { field: 'name', headerName: 'Name', width: 180, editable: true },
    {
      field: 'age',
      headerName: 'Age',
      type: 'number',
      width: 80,
      align: 'left',
      headerAlign: 'left',
      editable: true,
    },
    {
      field: 'joinDate',
      headerName: 'Join date',
      type: 'string',
      width: 180,
      editable: true,
    },
    {
      field: 'role',
      headerName: 'Department',
      width: 220,
      editable: true,
      type: 'singleSelect',
      valueOptions: ['Market', 'Finance', 'Development'],
    },
    {
      field: 'actions',
      type: 'actions',
      headerName: 'Actions',
      width: 100,
      cellClassName: 'actions',
      getActions: ({ id }) => {
        const isInEditMode = rowModesModel[id]?.mode === GridRowModes.Edit;

        if (isInEditMode) {
          return [
            <GridActionsCellItem
              icon={<SaveIcon />}
              label="Save"
              sx={{
                color: 'primary.main',
              }}
              onClick={handleSaveClick(id)}
            />,
            <GridActionsCellItem
              icon={<CancelIcon />}
              label="Cancel"
              className="textPrimary"
              onClick={handleCancelClick(id)}
              color="inherit"
            />,
          ];
        }

        return [
          <GridActionsCellItem
            icon={<EditIcon />}
            label="Edit"
            className="textPrimary"
            onClick={handleEditClick(id)}
            color="inherit"
          />,
          <GridActionsCellItem
            icon={<DeleteIcon />}
            label="Delete"
            onClick={handleDeleteClick(id)}
            color="inherit"
          />,
        ];
      },
    },
  ];

  return (
    <Box
      sx={{
        height: 500,
        width: '100%',
        '& .actions': {
          color: 'text.secondary',
        },
        '& .textPrimary': {
          color: 'text.primary',
        },
      }}
    >
      <DataGrid
        rows={rows}
        columns={columns}
        editMode="row"
        rowModesModel={rowModesModel}
        onRowModesModelChange={handleRowModesModelChange}
        onRowEditStop={handleRowEditStop}
        processRowUpdate={processRowUpdate}
        slots={{
          toolbar: EditToolbar,
        }}
        slotProps={{
          toolbar: { setRows, setRowModesModel },
        }}
      />
    </Box>
  );
}

Thanks in advance

Search with autocomplete in Openweathermap API

I have weather app script with Openweathermap API. Now I get location when location icon is clicked. I would like to have search with autocomplete list of cities to choose a city from this list.

How to change this code so that you can select a city from the list that appears when entering the city name? I mean when I write some city name will be a list of cities from which I can choose the right one.

Now there is no any list of cities to choose. Only I have to write name of city properly. I need to get this list from Openweathermap API which load the weather data too.

I have this code:


const geoLocationCoords = document.querySelector(".location-btn");

geoLocationCoords.addEventListener("click", () => {
  navigator.geolocation.getCurrentPosition(async (postion) => {
    const latitude = postion.coords.latitude;
    const longitude = postion.coords.longitude;

    localStorage.setItem("latitude", latitude);
    localStorage.setItem("longitude", longitude);

    weatherDetails(latitude, longitude, units);
    // airQuality(latitude, longitude);
    // futureForecast(coords[0], coords[1]);
  });
});

// weather details at the specified location

async function weatherDetails(latitude, longitude, units) {
  const openWeatherApi = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${APIKEY}&units=${units}`;

  try {
    let response = await fetch(openWeatherApi);
    let weatherData = await response.json();

    weatherDetailsUpdate(weatherData);
    airQuality(weatherData.coord.lon, weatherData.coord.lon);

    futureForecast(latitude, longitude);
  } catch (error) {
    console.error(error);
  }
}

//get weather location from input field by clicking Enter key or search icon

//when enter key is clicked

const searchInput = document.querySelector("#location-search-btn");
const searchInputclick = document.querySelector(".search-btn");

searchInput.addEventListener("keypress", (event) => {
  if (event.key === "Enter") {
    event.preventDefault();
    getLocation(searchInput);
    searchInput.value = "";
  }
});

searchInputclick.addEventListener("click", () => {
  getLocation(searchInput);
  searchInput.value = "";
});

async function getLocation(position) {
  // let position;
  let openWeatherApi;
  if (typeof position === "object") {
    openWeatherApi = `https://api.openweathermap.org/data/2.5/weather?q=${position.value}&appid=${APIKEY}&units=${units}`;
    localStorage.setItem("location", position.value);
  } else {
    openWeatherApi = `https://api.openweathermap.org/data/2.5/weather?q=${position}&appid=${APIKEY}&units=${units}`;
    localStorage.setItem("location", position);
  }

  let response = await fetch(openWeatherApi);
  let weatherData = await response.json();

  let latitude = weatherData.coord.lat;
  let longitude = weatherData.coord.lon;

  localStorage.setItem("latitude", latitude);
  localStorage.setItem("longitude", longitude);

  weatherDetailsUpdate(weatherData);
  airQuality(weatherData);
  futureForecast(weatherData.coord.lat, weatherData.coord.lon);

  if (weatherData.cod === "404") {
    alert("Please enter a valid location");
  }
}```



Thank you for help. 

Does VSCode have a built in MarkdownString to HTML function?

I’m working on a custom VSCode extension for a proprietary language. I’ve created a new Activity Bar option and added a WebviewView to it. Within this new WebviewView I’d like to display some documentation for various language commands that we have. The documentation has been added to a javascript file and the text within the strings has been pre-formatted using Markdown which works perfectly with the inbuilt auto-complete (CompletionItemProvider) and the hover functionality (HoverProvider).

I’d like to be able to use the existing documentation, however the view only supports HTML and I haven’t been able to find a way to convert the text to HTML or get the MarkdownString to conver to HTML using standard VSCode functionality.

Via search, the only suggestion I’ve found so far is to install a 3rd party extension to get such functionality. Is this really the only solution? Surely there must be some internal function/method to convert the MarkdownString to HTML, VSCode does it somehow, right?

why can’t I access a key of an object with input values [duplicate]

I am trying to write a program in which when user choses an option of select input the program saves it in a variable and then uses that variable to find the chosen option’s name in an object and then show the value of that key.
but it returns undefined every time, why does this happen and how can I fix it.

HTML:

<body>
    <select id="select">
        <option value="cat">cat</option>
        <option value="lion">lion</option>
        <option value="tiger">tiger</option>
    </select>
    <script src="Untitled-1.js"></script>
</body>
</html>

JS:

let inp = document.querySelector("#select")

let array = [
    {
        cat: 2,
        lion: 4,
        tiger: 6,
    },

    {
        camel: 2,
        lizard: 4,
        dog: 6,
    },

]
let value = inp.value
let obj = array[0]
function func() {
    console.log(obj.value)
}

inp.addEventListener("change", func)

How can I get javascript output to show in VS Studio?

I am a complete beginner and so am just playing around with writing some code. I can get output to show in browser web developer tools, but nothing shows up (even errors) in the output panel on VSS. From what I’ve seen (videos), when I save my file, the the output should automatically show in the output panel. I’m missing something but don’t know what. I am using Visual Studio Code version 1.85.2
screenshot of code in program

I have seen a lot of suggestions of saving, or right click and click ‘run’. It doesn’t show up ‘run’ for me on the right click menu but I have clicked the green play icon in the top left corner. It switched my view over from ‘output’ to ‘terminal’ and then prints my local file path.

Another solution suggested going into setting and enabling ‘Run in terminal’, but that option wasn’t there that I could see.

I have the extensions ‘live server’ and ‘prettier’ installed.

Thanks

Azurite giving bad request (statusCode-400)

Java Code:
BlobContainerClient blobContainerClient = new BlobContainerClientBuilder()
.endpoint(“https://maya-deploy.swinfra.net:443/devstoreaccount1”)
.credential(credential)
.containerName(“maya-container”)
.buildClient();

    System.out.println("Container URL: " + blobContainerClient.getAccountUrl());
    System.out.println("Container Name: " + blobContainerClient.getBlobContainerName());

            blobContainerClient.createIfNotExists();

BlobClient blobClient = blobContainerClient.getBlobClient(“pilsner-blob3”);

    try {
        blobClient.uploadFromFile("C:\SOUMYA\Azurite\maya-container\actual_bill\hemant_mf_us_inc_87601453\20231101-20231130\202311291132\571d1005-ca07-4557-8a6c-9878d10aaba2\_manifest.json");
        System.out.println("uploaded successfully");
    } catch (UncheckedIOException ex) {
        `System.err.printf(ex.getMessage());`
    }

Exception:
Exception in thread “main” com.azure.storage.blob.models.BlobStorageException: Status code 400, (empty body)
at java.base/java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:732)
at com.azure.core.implementation.http.rest.ResponseExceptionConstructorCache.invoke(ResponseExceptionConstructorCache.java:56)
at com.azure.core.implementation.http.rest.RestProxyBase.instantiateUnexpectedException(RestProxyBase.java:356)
at com.azure.core.implementation.http.rest.AsyncRestProxy.lambda$ensureExpectedStatus$1(AsyncRestProxy.java:127)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:113)
at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2400)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request(FluxMapFuseable.java:171)
at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set(Operators.java:2196)
at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onSubscribe(Operators.java:2070)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe(FluxMapFuseable.java:96)
at reactor.core.publisher.MonoJust.subscribe(MonoJust.java:55)
at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:157)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:129)
at reactor.core.publisher.FluxHide$SuppressFuseableSubscriber.onNext(FluxHide.java:137)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:129)
at reactor.core.publisher.FluxHide$SuppressFuseableSubscriber.onNext(FluxHide.java:137)
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:79)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1839)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:151)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:129)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1839)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:151)
at reactor.core.publisher.SerializedSubscriber.onNext(SerializedSubscriber.java:99)
at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.onNext(FluxRetryWhen.java:174)
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:79)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1839)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:151)
at reactor.core.publisher.Operators$MonoInnerProducerBase.complete(Operators.java:2666)
at reactor.core.publisher.MonoSingle$SingleSubscriber.onComplete(MonoSingle.java:180)
at reactor.core.publisher.MonoFlatMapMany$FlatMapManyInner.onComplete(MonoFlatMapMany.java:260)
at reactor.core.publisher.FluxContextWrite$ContextWriteSubscriber.onComplete(FluxContextWrite.java:126)
at reactor.core.publisher.FluxMap$MapConditionalSubscriber.onComplete(FluxMap.java:275)
at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onComplete(FluxSwitchIfEmpty.java:85)
at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2402)
at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set(Operators.java:2196)
at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onSubscribe(Operators.java:2070)
at reactor.core.publisher.MonoJust.subscribe(MonoJust.java:55)
at reactor.core.publisher.Mono.subscribe(Mono.java:4490)
at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onComplete(FluxSwitchIfEmpty.java:82)
at reactor.core.publisher.FluxDoFinally$DoFinallySubscriber.onComplete(FluxDoFinally.java:128)
at reactor.core.publisher.FluxHandle$HandleSubscriber.onComplete(FluxHandle.java:220)
at reactor.core.publisher.FluxMap$MapConditionalSubscriber.onComplete(FluxMap.java:275)
at reactor.core.publisher.FluxDoFinally$DoFinallySubscriber.onComplete(FluxDoFinally.java:128)
at reactor.core.publisher.FluxHandleFuseable$HandleFuseableSubscriber.onNext(FluxHandleFuseable.java:208)
at reactor.core.publisher.FluxContextWrite$ContextWriteSubscriber.onNext(FluxContextWrite.java:107)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1839)
at reactor.core.publisher.MonoCollectList$MonoCollectListSubscriber.onComplete(MonoCollectList.java:129)
at reactor.core.publisher.FluxPeek$PeekSubscriber.onComplete(FluxPeek.java:260)
at reactor.core.publisher.FluxMap$MapSubscriber.onComplete(FluxMap.java:144)
at reactor.netty.channel.FluxReceive.onInboundComplete(FluxReceive.java:413)
at reactor.netty.channel.ChannelOperations.onInboundComplete(ChannelOperations.java:424)
at reactor.netty.channel.ChannelOperations.terminate(ChannelOperations.java:478)
at reactor.netty.http.client.HttpClientOperations.onInboundNext(HttpClientOperations.java:712)
at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:113)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412)
at com.azure.core.http.netty.implementation.AzureSdkHandler.channelRead(AzureSdkHandler.java:222)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:442)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412)
at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436)
at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:346)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:318)
at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:442)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412)
at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1383)
at io.netty.handler.ssl.SslHandler.decodeNonJdkCompatible(SslHandler.java:1257)
at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1297)
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:529)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:468)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:290)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:833)
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99)
at reactor.core.publisher.Mono.block(Mono.java:1742)
at com.azure.storage.common.implementation.StorageImplUtils.blockWithOptionalTimeout(StorageImplUtils.java:146)
at com.azure.storage.blob.BlobContainerClient.createIfNotExistsWithResponse(BlobContainerClient.java:374)
at com.azure.storage.blob.BlobContainerClient.createIfNotExists(BlobContainerClient.java:340)
at org.example.AzuriteExample.main(AzuriteExample.java:89)

How to open Stripe checkout form in modal using pure javascirpt with backend (Laravel)

i have a laravel backend api to store amount in stripe session when it response backend i want to open the stripe checkout modal form and when pay with cart amount should show in the stripe how can i do that

public function createStripeFormCheckout(Request $request): Response|array|Application|ResponseFactory
{
$stripe = new StripeClient(“sk_test_51LQ8H9Kv5bxntkGeAQtM6prJtxsL5072U6gTTNaAa8Qj5WxJWBqOKqMyE10FkQdOUfRyQlnux2Gfe3DWadAPXkux005SxOfJEB”);

    try {
        $token = $request->query('token');
        $amount = $request->query('amount');

        if ($amount == null) {
            return $this->errorResponse("Please set amount for creating checkout");
        }
        $customer = null;
        if ($token != null) {
            $customer = TokenLog::getUserFromToken(Customer::class, $token);
        }

        if ($customer == null) {
            return $this->errorResponse("User is not found");
        }

        $stripe_key = "sk_test_51LQ8H9Kv5bxntkGeAQtM6prJtxsL5072U6gTTNaAa8Qj5WxJWBqOKqMyE10FkQdOUfRyQlnux2Gfe3DWadAPXkux005SxOfJEB";
        $currency_code = BusinessSetting::getCurrencyCode();

        if ($stripe_key == null) {
            return $this->errorResponse("Stripe key is not set by admin");
        }

        Stripe::setApiKey($stripe_key);
        $session = $stripe->checkout->sessions->create([
            'payment_method_types' => ['card'],
            'client_reference_id' => 1,
            'line_items' => [
                [
                    'price_data' => [
                        'currency' => 'USD',
                        'unit_amount' => $amount * 100,
                        'product_data' => [
                            'name' => BusinessSetting::getBusinessName(),
                        ],
                    ],
                    'quantity' => 1,

                ]
            ],
            'payment_intent_data' => [
                'metadata' => [
                    'customer_id' => $customer->id,
                ]
            ],
            'mode' => 'payment',
            'success_url' => $this->success_url,
            'cancel_url' => $this->success_url,
        ]);
       
        return [
            'checkout_url' => $session->url,
            'checkout_id' => $session->id,
        ];
    } catch (Exception $e) {
        return $this->errorResponse($e->getMessage());
    }
}

i have this code in the laravel side your text

$(document).on('click', SELECTORS.CONTINUE_TOP_PAY, handlePayment);

const stripe = Stripe('pk_test_51NnDhLAEvF6SvM6zlzzEiufIj2nmc8PAke79UhlGzmUliEDRs7qj2MOL6jTWI4kEbvDyqLJR9V4sPgXLrDm3Ntsr00JzrMJaZt');
async function handlePayment() {
    const selectedPaymentMethod = $(`${SELECTORS.PAYMENT_METHODS}.${CLASS_NAMES.SELECTED}`);
    let paymentMethod = null;

    if (selectedPaymentMethod.length > 0) {
        paymentMethod = selectedPaymentMethod.data('payment-method');
    } else {
        showPopup('error', 'ops...', 'No payment method selected');
        return;
    }
    if (paymentMethod === "card") {
        handleStripePayment()
    } else {

        continueOrder();
    }


}
async function handleStripePayment() {
    try {
        const totalAmountText = $('.checkout_total_price').text();
        const totalAmount = parseFloat(totalAmountText.replace(/[^0-9.]/g, ''));
        const total = totalAmount;
        let token = isAuthenticated()

        const response = await fetch(`/api/v1/customer/payments/create_stripe_form_checkout?token=${token}&amount=${total}`, {
            method: "GET",
            headers: {
                'Content-Type': 'application/json',
            },
        });
        const session = await response.json();

       
        let handler = StripeCheckout.configure({
            key: 'pk_test_51NnDhLAEvF6SvM6zlzzEiufIj2nmc8PAke79UhlGzmUliEDRs7qj2MOL6jTWI4kEbvDyqLJR9V4sPgXLrDm3Ntsr00JzrMJaZt',
            locale: 'auto',
            token: async function (token) {
                await continueOrder()
            }
        });

        handler.open({
            name: 'TAARUFF',
            description: 'Payment Description',
            amount: total * 100,
            currency: 'PKR',
            panelLabel: 'Pay Now',
        });

        
    } catch (error) {
        showPopup('error', 'ops...', error);
    }
}

this code on js client side

Style isolation in microfrontend architecture

I have a case. I need to integrate one Vue js application into another using the Webpack Module Federation plugin. Using the configs, I was able to distribute the component to another application (layout). However, I’m having a problem with my app’s styles overriding the app’s layout styles. I use bootstrap as global styles. It contains styles for tags that break layout styles. If I use shdow root, I have to make quite a lot of changes to the code, at least manually encapsulating the styles. Secondly, the styles I encapsulate in shdow root contain :root selectors, which do not apply to shadow root styles. Is it possible to solve the styling problem with a simple, elegant solution?

Main and Renderer handling promises, but Preload can be non-promise?

Considering the renderer and main are handling promises, will the code below force the process to become synchronous if openFile() is not also set to async await?

contextBridge.exposeInMainWorld('myAPI',
  {
    openFile: () => ipcRenderer.invoke('dialog:openFile'),
    ...

If the code below is absolutely unnecessary, can somebody explain why async await can be omitted like in the code above?

contextBridge.exposeInMainWorld('myAPI',
  {
    openFile: async () => await ipcRenderer.invoke('dialog:openFile'),
    ...

FWIW:

renderer.js

el.addEventListener('click', async ()=>{
  const filePath = await window.myAPI.openFile()
  left.textContent = filePath
})


main.js

ipcMain.handle('dialog:openFile', async ()=>{
  const { canceled, filePaths } = await dialog.showOpenDialog()
  if (!canceled) return filePaths[0]
})

How do I load a remote script (widget) inside a react component

Is it possible to load these 2 scripts which renders a widget inside a div and load it as a react component ?

<div id="position-size-calculator-124020">
    <script type="text/javascript" src="https://www.cashbackforex.com/Content/remote/remote-widgets.js"></script>
    
    <script type="text/javascript"> RemoteCalc({"Url":"https://www.cashbackforex.com", "TopPaneStyle":"YmFja2dyb3VuZDogcmdiYSg0MCwgNDIsIDQ2KTsgY29sb3I6IHdoaXRlOyBib3JkZXItYm90dG9tOiBub25lOw==","BottomPaneStyle":"YmFja2dyb3VuZDogIzE1MTgxZDsgYm9yZGVyOiBzb2xpZCAwcHggIzJhMmUzOTsgY29sb3I6ICNGRkY=","ButtonStyle":"YmFja2dyb3VuZDogIzM0MzU0MDsgY29sb3I6IHdoaXRlOyBib3JkZXItcmFkaXVzOiAyMHB4OyA=","TitleStyle":"dGV4dC1hbGlnbjogbGVmdDsgZm9udC1zaXplOiA0MHB4OyBmb250LXdlaWdodDogNTAwOyBjb2xvcjogI0ZGRg==","TextboxStyle":"YmFja2dyb3VuZDogIzE1MTgxZDsgY29sb3I6ICNGRkYKOyBib3JkZXI6IHNvbGlkIDBweCAjOTE5NGExOw==","ContainerWidth":"100%","HighlightColor":"rgba(0,0,0,1.0)","IsDisplayTitle":false,"IsShowChartLinks":false,"IsShowEmbedButton":false,"Lang":"en","CompactType":"large","Calculator":"position-size-calculator","ContainerId":"position-size-calculator-124020"});</script>
</div>

unwanted long margin at the bottom

<body>
<div class="nav" id="Nav">
    <a href="#top">Home</a>
    <a href="#nav1">Shop</a>
    <a href="#nav2">Blog</a>
    <a href="#nav3">About</a>
    <a href="#nav4">Contact</a>
  </div>
  <div id="page">


    <img src="xyz" height="300" width="300" style="display: block; margin: 0 auto;">
  </div>
  <div id="nav1"></div>
</body>
  
  
<style>
.nav {
  text-align: center;
  background-color: #edb021;
  position: absolute;
  width: 50%;
  top: 45%;
  left: 50%;
  margin-left: -25%;
  border: 1px solid black;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
  line-height: 4em;
  border-radius: 10px;
}
.nav a {
  text-decoration: none;
  color: #000;
  font-size: 1em;
  font-weight: 300;
  margin: 5%;
}
.nav a:hover {
  color: #EDB021;
  text-decoration: underline;
}
.scrolldown {
  top: 0vh;
  width: 100%;
  text-align: center;
  position: fixed;
  border-top: none;
  border-left: none;
  border-right: none;
  border-bottom: 1px solid black;
  border-radius: 0;
  background-color: rgba(255,255,255,0.06);
    -webkit-backdrop-filter: blur(20px);
            backdrop-filter: blur(20px);
  animation-direction: normal;
  animation: navChange 0.25s linear 1;
  margin-left: -50%;
  z-index: 9999;
}
.scrollup {
  text-align: center;
  background-color: #edb021;
  position: absolute;
  width: 50%;
  left: 50%;
  margin-left: -25%;
  border: 1px solid black;
  line-height: 3em;
  border-radius: 10px;
  animation-direction: normal;
  z-index: 9999;
  animation: navChangeBack 0.25s linear 1;
}

@keyframes navChange {
  0% {
    border: 1px solid black;
    border-radius: 10px;
    position: fixed;
    width: 50%;
    left: 50%;
    margin-left: -25%;
    border: 1px solid black;
  }
  100% {
    border: 1px solid rgba(0, 0, 0, 0);
    border-bottom: 1px solid black;
    border-radius: 0;
    position: fixed;
    top: 0%;
    width: 100%;
    margin-left: -50%;
  }
}
@keyframes navChangeBack {
  0% {
    border: 1px solid rgba(0, 0, 0, 0);
    border-bottom: 1px solid black;
    border-radius: 0;
    width: 100%;
    margin-left: -50%;
  }
  100% {
    border: 1px solid black;
    border-radius: 10px;
    width: 50%;
    left: 50%;
    margin-left: -25%;
    border: 1px solid black;
  }
}
@media only screen and (max-width: 600px) {
  .nav.pagenav {
    display: none;
  }
  #Nav {
    display: none;
  }
}
      
</style>
  
 
  
<script>
    //Determine Scroll Direction
var dir = []
function logScrollDirection() {
    var previous = window.scrollY;
    window.addEventListener('scroll', function(){
        window.scrollY > previous ? dir = "down" : dir = "up" ;
        previous = window.scrollY;
    });
  return dir;
}
logScrollDirection();
//Scroll Direction Determined
//Sticky Nav Start
window.onscroll = function() {
  logScrollDirection();
  expAndStick();
};
var nav = document.getElementById("Nav");
var sticky = nav.offsetTop;
function expAndStick() {
  if ((window.pageYOffset >= sticky)&&(dir == "down")) {
    nav.classList.remove("scrollup");
    nav.classList.add("scrolldown");
  } else if ((window.pageYOffset <= sticky)&&(dir == "up")) {
    nav.classList.remove("scrolldown");
    nav.classList.add("scrollup");
  } 
}
</script>

Click to open image shows unwanted space

this is the code I used in Elementor to create the header but it leaves a long unwanted margin after the nav bar

I already tried removing line height, margins everything but I do not want to use z-index for another container to cover up the space

also, I added this in a separate header, and footer plugin which comes along with Elementkit

Write a program that finds the smallest positive integer that when represented in base 10 [closed]

Write a program that finds the smallest positive integer that when represented in base 10, moving the least significant digit to become the most significant digit, the new integer is exactly triple the original integer. For example, 14 becomes 41 which is close to triple but not exact. Another close example is 103 becoming 310, again very close to triple but not exact. The program must be completed in less than 5 seconds on a modern laptop, printing the integer to the console. Please submit one node.js source file. We should be able to execute your code as follows:

I wrote the below code but not sure and need some input and help writing better code

function findTripleInteger() {
    let number =5000;
    let multiplication=0;
    let currentDate = new Date();
    for (let i = 0; i <= number; i++)
    {
        let len-i.toString().length;
        //console.log("The len is:" + len); 
        let vl =i.toString().substring(0,len-1); 
        //console.log("The vl is:" + v1); 
        let dividend= i;
        let divisor = 10;
        let remainder = dividend % divisor;
        
        //console.log("The remainder is: " + remainder);
        var concatstring = remainder+vl;
        //console.log(concatstring);
        multiplication = i * 3;
        //console.log("The multiplication is: " + multiplication); 
        var diff=parseInt(concatstring) -multiplication;
        //console.log("The diff is: " + diff);
        if (diff===1|| diff===-1)
        {
            console.log("Integral num is: " + (i * 3 = multiplication));
        }
    }
    console.log("Execution time is: " + currentDate.getSeconds());
}

My program below