Firebase getDoc function not resolving or throwing errors

I’m facing an issue with the getDoc function in Firebase Firestore. When I try to use getDoc to retrieve a document from the Firestore database in my web application, it neither resolves nor throws any errors.

Here’s my code snippet in js:


import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.1/firebase-app.js';
import { getFirestore, collection, addDoc, doc, setDoc, getDoc, query, getDocs, onSnapshot, updateDoc, where } from 'https://www.gstatic.com/firebasejs/9.1.1/firebase-firestore.js';

const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "AUTH_DOMAIN",
  projectId: "PROJECT_ID",
  storageBucket: "STORAGE_BUCKET",
  messagingSenderId: "MESSAGING_SENDER_ID",
  appId: "APP_ID",
  measurementId: "MEASUREMENT_ID"
};

const app = initializeApp(config);
const db = getFirestore(app);


[... other functions]


async function cropImage() {
    if (!selectedUser) {
        return;
    }

    try {
   
        const imageDataURL = croppedCanvas.toDataURL();
        const cleanedURL = cleanAndValidateUrl(imageDataURL);

        if (!cleanedURL) {
            console.error('Invalid image URL');
            return;
        }
        const userDocRef = doc(db, 'character_sheet', selectedUser);
        const imagesCollectionRef = collection(userDocRef, 'images');         
        
        try {
            const imagesCollectionSnapshot = await getDocs(imagesCollectionRef); //HERE THE CODE STOPS, RETURNING NOTHING
   
            if (!imagesCollectionSnapshot.empty) {
                // If the collection doesn't exist, create it
                await addDoc(imagesCollectionRef, {});
            }
        } catch (error) {
            console.error("Error retrieving images collection:", error);
        }
        
        // Get a reference to a new document in the images collection
        var newImageRef = doc(imagesCollectionRef);

        // Clean and validate the image URL
        const cleanedImageUrl = cleanAndValidateUrl($('#previewImage').attr('src'));
        if (typeof cleanedImageUrl !== 'string') {
            console.error('Cleaned image URL is not a string:', cleanedImageUrl);
            return;
        }
        
        // Set the document data (image)
        await setDoc(newImageRef, {
            imageUrl: cleanedImageUrl,
            cropData: {
                x: croppedData.x,
                y: croppedData.y,
                width: croppedData.width,
                height: croppedData.height,
                rotate: croppedData.rotate,
                scaleX: croppedData.scaleX,
                scaleY: croppedData.scaleY
            }
        });

        // Display success message
        alert("Image uploaded successfully.");

        // Clear the preview
        $('#previewImage').attr('src', '');
        cropper.destroy();
        console.log('Image uploaded successfully');
    } catch (error) {
        console.error('Error uploading image:', error);
    }
}

When I run this code, the error block inside the catch statement is not executed. However, I can confirm that the document exists in the Firestore database, and the Firebase configuration is correct.

Interestingly, when I try to access the same collection and document from another page using getDoc, it works perfectly fine.

Could anyone provide insights into why getDoc might not be resolving or throwing errors in this scenario? Any help would be greatly appreciated. Thank you!

I’m having problems sending the html file with Eliysa js

I couldn’t send an html file either. I wonder what the problem is?

    import { Elysia } from 'elysia'
    import { html } from '@elysiajs/html'
    import { staticPlugin } from '@elysiajs/static'
    
    const app = new Elysia();
    app.use(staticPlugin({ assets : "./public"}))
    app.use(html())
    app.get('/file', async () => Bun.file('./public/index.html'))
    app.listen(3000)

index.html
path

Error:
Error Message

I want to link a static html fee with elysia.js but I get a file not found error.

How to make a universal input component for controlled usage and react-hook-form?

I want to make a custom component in which there is a reset button for a specific field and it appears only when there is a value in an input. The component can be controlled or not. I have made the part, but when setting the value asynchronously in react-hook-form, the reset button doesn’t appear because I don’t know how to track the change of target.value. Advise if it is possible to do this or is it better to do it differently?

const InputBase = forwardRef<HTMLInputElement, InputProps>((props, ref) => {
  const innerRef = useRef<HTMLInputElement>(null!);
  const [isResetVisible, setIsResetVisible] = useState(!!props.value);

  useImperativeHandle(ref, () => innerRef.current, []);

  useEffect(() => {
    setIsResetVisible(!!props.value);
  }, [props.value]);

  const handleClean = useCallback(() => {
    const isControlled = typeof props.value !== 'undefined';
    if (!isControlled) {
      innerRef.current.value = '';
      setIsResetVisible(false);
    }
    const event = new InputEvent('change');
    Object.defineProperty(event, 'target', {
      value: {
        ...innerRef.current,
        ...(isControlled ? { value: '' } : {}),
      },
    });

    props.onChange?.(event as unknown as ChangeEvent<HTMLInputElement>);
  }, []);

  const handleOnChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => {
      if (!isResetVisible && e.target.value) {
        setIsResetVisible(true);
      } else if (isResetVisible && !e.target.value) {
        setIsResetVisible(false);
      }
      props.onChange?.(e);
    },
    [props.onChange, isResetVisible]
  );

  return (
    <InputGroup size="md">
      <Input {...props} onChange={handleOnChange} ref={innerRef} pr="4.5rem" />
      {isResetVisible && (
        <InputRightElement width="4.5rem">
          <Button h="1.75rem" size="sm" onClick={handleClean}>
            Clear
          </Button>
        </InputRightElement>
      )}
    </InputGroup>
  );
});

How do I rotate a rectangle of latitude and longitude? google maps,

I have a rectangle in google map, it needs to be rotated from the clicked point, the rectangle doesn’t come out either. how to rotate a rectangle and the points inside it.

// 21 qator 22 qator va 71 qatorlarda

var inputHeight = document.querySelector("#inputHeight");
var inputWidth = document.querySelector("#inputWidth");
var inputX = document.querySelector('#inputx');
var inputY = document.querySelector('#inputy');
var inputa = document.querySelector('#alfa');
var apiKey = 'AIzaSyCcWRW3OffFhrY95FEcdTKCIQuuxKkEHNY';

function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {
      center: {
        lat: 39.760000,
        lng: 64.420000,
      },
      position: google.maps.ControlPosition.TOP_TOP,
      zoom: 16,
      heading: 0,
      tilt: 0,
      mapId: "90f87356969d889c",
    });
    const buttons = [
      ["Rotate Left", "rotate", 5, google.maps.ControlPosition.LEFT_CENTER], // buni bosganda alfa 5 gradus qushiladi
      ["Rotate Right", "rotate", -5, google.maps.ControlPosition.RIGHT_CENTER], // buni bosganda alfa -5 gradus buladi
    ];
    
    buttons.forEach(([text, mode, amount, position]) => {
      const controlDiv = document.createElement("div");
      const controlUI = document.createElement("button");
  
      controlUI.classList.add("ui-button");
      controlUI.innerText = `${text}`;
      controlUI.addEventListener("click", () => {
        adjustMap(mode, amount);
      });
      controlDiv.appendChild(controlUI);
      map.controls[position].push(controlDiv);      
    });
  
    const adjustMap = function (mode, amount) {
      switch (mode) {
        
        case "rotate":
          map.setHeading(map.getHeading() + amount);
          break;
        default:
          break;
      }
    };
    map.addListener('click', function (event) {
      var latitude = 39.760000; // Belgilangan nuqta latitude qiymati
      var longitude = 64.420000; // Belgilangan nuqta longitude qiymati
      
      // Draw a rectangle on the map
      
      
      var rectangle = new google.maps.Rectangle({
        strokeColor: '#050505',
        strokeOpacity: 0.8,
        strokeWeight: 1,
        fillColor: '#FF0000',
        fillOpacity: 0.2,
        map: map,
        // bounds: {
        //   north: latitude,
        //   south: latitude - (inputHeight.value - 1) * (inputX.value/111000),
        //   east: longitude + (inputWidth.value - 1) * (inputY.value/85380),
        //   west: longitude
        // },111000
      });
      // İki nokta arasındaki koordinatları tanımlayın
      // var pointA = new google.maps.LatLng(39.760000, 64.420000);
      // var pointB = new google.maps.LatLng(39.760011, 64.420011);

      // // İki nokta arasındaki mesafeyi hesaplayın
      // var distance = google.maps.geometry.spherical.computeDistanceBetween(pointA, pointB);

      // // 20 metreye ulaşmak için gereken oranı hesaplayın
      // var ratio = 20;

      // // Orantıyı kullanarak 20 metrelik noktaları bulun
      // var point20A = google.maps.geometry.spherical.interpolate(pointA, pointB, ratio);
      // var point20B = google.maps.geometry.spherical.interpolate(pointB, pointA, ratio);

      // // Çizgi oluşturun
      // var line = new google.maps.Polyline({
      //   path: [point20A, point20B],
      //   geodesic: true,
      //   strokeColor: '#FF0000',
      //   strokeOpacity: 1.0,
      //   strokeWeight: 2
      // });
      
      var alfa = inputa.value // ana bu burchak ana shera tushishi kerak
      var cosin = Math.cos((Math.PI * alfa) / 180)
      var sinus = Math.sin((Math.PI * alfa) / 180)
      var heightx = inputX.value/111000
      var heighty = inputY.value/85380
      
      // Convert coordinates to elevation
      var elevator = new google.maps.ElevationService();
      var locations = []
      for (var j = 0; j <= (inputHeight.value - 1);  j++) {
        for (var i = 0; i <= (inputWidth.value - 1); i++){
          locations.push({lat: latitude - (j * heightx * cosin) + ((i * heighty) * sinus) , lng: longitude + (i * (heighty * cosin)) + (j * heightx) * sinus});
        }
      }
       if let rotation = rotation, let center = zoneCenter {
        let radians = Double(rotation) * (Double.pi/180.0)
        print(radians)
        var newPoints: [CLLocationCoordinate2D] = []
        for point in squarePoints {
            let latitude: CLLocationDegrees = center.latitude + (point.longitude - center.longitude) * sin(radians) + (point.latitude - center.latitude) * cos(radians)

            let longitude: CLLocationDegrees = center.longitude + (point.longitude - center.longitude) * cos(radians) - (point.latitude - center.latitude) * sin(radians)

            newPoints.append(CLLocationCoordinate2DMake(latitude, longitude))
        }

        squarePointsWithRotation = newPoints
        squareOverlay = MKPolygon(coordinates: &newPoints, count: squarePoints.count)
        mapView.add(squareOverlay)
    }
}
      

      // var locations = [
      //   { lat: latitude, lng: longitude},
      //   { lat: latitude + (inputX.value/111000) * Math.sin((Math.PI * 45) /180), lng: longitude + (((inputY.value/85380) * Math.cos((Math.PI * 45) / 180))) },
        
      //   { lat: latitude - inputWidth.value * (inputY.value/85380) + (((inputY.value/85380) * Math.cos((Math.PI * 45) / 180))), lng: longitude + (((inputX.value/111000) * Math.cos((Math.PI * 45) / 180)))},
      //   { lat: latitude - inputWidth.value * (inputY.value/85380) + (inputX.value/85380) * Math.sin((Math.PI * 45) /180), lng: longitude + (inputX.value/111000)*inputHeight.value + (((inputY.value/85380) * Math.cos((Math.PI * 45) / 180)))},
        
        
      // ];
      var locationsList = document.getElementById('chiq')
      locations.forEach(function(location) {
        var listItem = document.createElement("li"); // Yangi <li> elementini yaratamiz
        listItem.textContent = "Lat: " + location.lat + ", Lng: " + location.lng; // Matnni belgilaymiz
        locationsList.appendChild(listItem); // <ul> elementining ichiga <li> elementini qo'shamiz
      });
      var positionalRequest = {
        'locations': locations
      };
      var evalu = []
      elevator.getElevationForLocations(positionalRequest, function (results, status) {
        if (status === google.maps.ElevationStatus.OK) {
          if (results) {
            var gridParent = document.getElementById('pixelCanvas');
            gridParent.innerHTML = ""; // Jadvalni tozalash
            for ( var j =0; j < (inputHeight.value + 1); j++){
              var row = document.createElement("tr");
              for (var i = 0; i < (inputWidth.value ); i++) {
                var elevation = results[j* inputWidth.value + i].elevation.toFixed(2);
                evalu.push(results[j* inputWidth.value + i].elevation.toFixed(2));
                var cell = document.createElement("td");
                cell.textContent = elevation;
                row.appendChild(cell);
                gridParent.appendChild(row);
              }
            }
            
          }
        }
      });
        for (var i = 0; i < locations.length; i++) {
          var marker = new google.maps.Marker({
            position: locations[i],
            map: map,
            label: (i + 1).toString(),
            zIndex: locations[i].alt,   
          });
        }  
    });
  }

  // for (var i = 0; i < locations.length; i++) {
  //   var marker = new google.maps.Marker({
  //     position: locations[i],
  //     map: map
  //   });
  
  window.initMap = initMap;

// console.log(inputHeight.value * (inputX.value/1840))
// Evalu massivini HTML-da ko'rsatish
var evaluContainer = document.getElementById('evaluContainer');
evaluContainer.textContent = JSON.stringify(evalu);
// console.log(locations)
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=' + apiKey + '&callback=initMap';
script.defer = true;
script.async = true;
document.head.appendChild(script);

when you turn the card, the square must also turn. When I rotate the corner, it looks like a rhombus. When I turn it to 30 degrees, it misses 7 degrees, when I turn it to 60 degrees, it misses 9 degrees.

when the google map is rotated by 5 degrees, the rectangle should also rotate accordingly. only the points of the rectangle are output. I also posted the tested code.

Component value does not update on React-hook-form – NextJS

So, I have tried everything but cannot figure this out at all.
I have this reusable component made with ShadCn Slider,

function SliderWithCounter({ min, max, step = 1, onChange, value }: any) {
  const [sliderValue, setSliderValue] = useState(min);

  const handleChange = (newValue: any) => {
    console.log("SliderWithCounter - newValue:", newValue);
    setSliderValue(newValue);
    onChange(newValue);
  };

  const handleIncrement = () => {
    setSliderValue(Math.min(sliderValue + step, max));
  };

  const handleDecrement = () => {
    setSliderValue(Math.max(sliderValue - step, min));
  };

  return (
    <div className="flex flex-row justify-between items-center gap-2 ">
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger type="button">
            <Slider
              value={[sliderValue]}
              defaultValue={[min]}
              max={max}
              step={step}
              onChange={handleChange}
              className="w-[250px] md:flex hidden"
            />
          </TooltipTrigger>
          <TooltipContent sideOffset={5}>{sliderValue}</TooltipContent>
        </Tooltip>
      </TooltipProvider>
      <div className="flex flex-row gap-2 items-center justify-center">
        <Button onClick={handleIncrement} variant={"outline"} type="button">
          +
        </Button>
        <Input
          value={sliderValue}
          className="md:w-[60px]"
          onChange={(e) => setSliderValue(e.target.value)}
        />
        <Button onClick={handleDecrement} variant={"outline"} type="button">
          -
        </Button>
      </div>
    </div>
  );
}
export default SliderWithCounter;

The UI portion of this works perfectly, the slider moves, the input field value updates and vice-versa.

But now I import this into my form:

 <FormField
                control={form.control}
                name="batchSize"
                render={({ field }) => {
                  return (
                    <FormItem>
                      <FormLabel className="flex flex-row items-center gap-2">
                        Batch size
                        <ToolTipComponent tooltipText="Number of images" />
                      </FormLabel>
                      <FormControl>
                        <SliderWithCounter
                          min={1}
                          max={20}
                          onChange={(value: any) => {
                            console.log("FormField - onValueChange:", value);
                            field.onChange(value);
                          }}
                          step={1}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  );
                }}
              />

formSchema: batchSize: z.array(z.number()),
And the default value for this is batchSize: [],

Now the onChange of the form never fires, I cannot see the console.log ever, I want the values to be updated to use in my form, but I have no idea how to fix this. Thanks for your help!

Flutter Web – Set the EventListener to other tab and get the Title and details from it using javascript

First, I will explain what I want to do. I am trying to open the payment gateway url from my flutter web app using html.window. I am able to open the link in next tab and also done the all payment to success. Now, for giving the payment status to my web app back, I am checking the title of that payment gateway tab that contains status and transaction id. But I am unable to do this.

Here is the flutter code first:-

 void openURLAndListen(String url)async {
  js.context.callMethod('openURLAndListen', [url]);

    // Wait for a brief duration to ensure JavaScript function execution
    await Future.delayed(const Duration(microseconds: 500));
   
    html.window.addEventListener('PAGE_LOADED', (event){
    MessageEvent event2 = event as MessageEvent;
    print("Get Message from js ${event2.data}");
  });
    
  }

Here is the Javascript function :-

function openURLAndListen(url) {
    var openedWindow = window.open(url, '_blank');

    openedWindow.onload = function(){

// Get the title of the page
        var titles = [];
            var tabs = document.querySelectorAll('title');
            tabs.forEach(function(tab) {
                titles.push(tab.innerText);
            });
            // Notify Flutter app with the page title
            window.parent.postMessage({ type: "PAGE_LOADED", titles: titles }, url);
    }

}

This javascript file was called in index.xml file in web folder.

Please give me the proper solution for this, correct me if the function is not correct.

I had tried to use addEventListener to call the title details on opened window.

Image is not showing in javascript image slider

I had created an image slider using HTML & JavaScript. The images are showing and working well when I use the slider with window.setInterval property and also with my next button but when I press my back button , the images are not found after the first image is shown. This means when I hit previous button the images are appearing in descending order one by one, but after first picture the Javascript function is unable to loop images from last picture to the first picture.
Inspecting the page following error is shown
undefined:1

   Failed to load resource: net::ERR_FILE_NOT_FOUND

Please Help!

following is my Javascript code

arr=["SMSlogo.jpg","spiderlogo.jpg","yt.jpg"];
        var value=0;
        slide();
        function slide(){
            document.getElementById("pic").src=arr[value];  
            value++;
            if(value==arr.length){
                value=0;
            }
        }
        window.setInterval(slide,3000);

        function back(){
            document.getElementById("pic").src=arr[value];
            value--;
            if(value==0){
                value=arr[arr.length-1];
            }
        }
        function next(){
            document.getElementById("pic").src=arr[value];
            value++;
            if(value==arr.length){
                value=0;
            }
        }

I’m expecting that my back button work properly and all images should be visible when I click the back button.

How to implement a consent prompt when navigating away from a page without user interaction in JavaScript?

I’m developing a web application where I have an index.php page containing a form with hidden input storing request data and a submit button. I want to implement a feature where if the user attempts to navigate away from the page (e.g., by right-clicking and clicking back or reloading), a consent prompt should appear before allowing the navigation. However, I encountered an error message stating: “Blocked attempt to show a ‘beforeunload’ confirmation panel for a frame that never had a user gesture since its load.”

Here’s a simplified version of my code:

<!DOCTYPE html>
<html>
<head>
    <title>Consent Prompt</title>
</head>
<body>
    <form id="myForm" action="process.php" method="post">
        <input type="hidden" name="requestData" value="someData">
        <button type="submit">Submit</button>
    </form>
    <script>
        window.addEventListener('beforeunload', function(e) {
            e.preventDefault();
            e.returnValue = '';
        });
    </script>
</body>
</html>

save content of inner html as a html file in angular

I’m using this innerHTML to show html form in out angular component

this.html = this.sanitizer.bypassSecurityTrustHtml(
      '<iframe width="100%" height="800" src="assets/template_forms/registration_form.html"></iframe>',
    );

HTML

<div [innerHtml]="html"></div>

Save

form is being rendered now after entering the values need to save updated content of that whole form in html format in the same assets folder.

Trouble extracting xml property from ajax response

I’m using SharePoint on Premises 2019 and I have an ajax request to a SharePoint list. The list has a preexisting column named attachments which contains images that were uploaded to it.

Now the ajax request to return elements of the list returns a xml response for the attachments column. The response

xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml"><id>e3a2717c-932c-43a0-b1c6-f81a75329948</id><title /><updated>2024-03-26T06:02:30Z</updated><entry><id>http://po/sites/pssm/_api/Web/Lists(guid'f80db476-8b0c-4a8b-b9b6-0516028525d5')/Items(25)/AttachmentFiles('contact.webp')</id><category term="SP.Attachment" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /><link rel="edit" href="Web/Lists(guid'f80db476-8b0c-4a8b-b9b6-0516028525d5')/Items(25)/AttachmentFiles('contact.webp')" /><title /><updated>2024-03-26T06:02:30Z</updated><author><name /></author><content type="application/xml"><m:properties><d:FileName>contact.webp</d:FileName><d:FileNameAsPath m:type="SP.ResourcePath"><d:DecodedUrl>contact.webp</d:DecodedUrl></d:FileNameAsPath><d:ServerRelativePath m:type="SP.ResourcePath"><d:DecodedUrl>/sites/pssm/Lists/PoliceHomeAds/Attachments/25/contact.webp</d:DecodedUrl></d:ServerRelativePath><d:ServerRelativeUrl>/sites/pssm/Lists/PoliceHomeAds/Attachments/25/contact.webp</d:ServerRelativeUrl></m:properties></content></entry></feed>

Here the image url can be found in the serverRelativeUrl tag of xml response.

This is my js loop statement that generates the tag.

  <a" href="' + objArray[i].AttachmentFiles.__deferred.uri + '">    </a>;

For now I’m using anchor tag just so I can see the results returned by the statement more clearly. If I use image tag, it just shows me the browser image default icon.

Do help. How can I display image?

html web component html content?

Providing innerHTML as a string is seems very error prone while document.createElement is very tedious. Is there a JSX-like way to define web component’s html content?

Instead of doing innerHTML string

class Foo extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    this.innerHTML = `<p>foo</p>`;
  }
}

Do something like

class Foo extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    this.innerHTML = (<p>foo</p>);
  }
}

error in sql query result while search with nodes

i have one query for search where i have string Ennemie d’état and if i search with key Ennemie d’état then it show data not found problem is in single quote (‘) my query is as below:

WHERE (
post_tbl.title LIKE (‘%${key.replace(/’/g, “”” )}%’) or post_tbl.caption like (‘%${key.replace( /’/g, “”” )}%’) )

Unable to Resolve jQuery ReferenceError: $ is not defined in JavaScript File

I’m encountering an issue with my JavaScript file where I’m getting the error “Uncaught ReferenceError: $ is not defined” in the browser console. I’m using jQuery in my JavaScript code, but it seems like jQuery is not being recognized.

Here’s the relevant portion of my JavaScript file (address.js):

console.log("Hi");

$(document).ready(function(){
    $(document).on("click",".make-default-address",function(){
        let id = $(this).attr("data-address-id")
        let this_val = $(this)

        console.log("Id is:", id);
        console.log("Element is:", this_val);

        $.ajax({
            url:"/make-default-address",
            data: {
                "id":id
            },
            dataType: "json",
            success: function(response){
                console.log("Address Made default.....");
                if (response.boolean == True){
                    $(".check").hide()
                    $(".action_btn").show()



                    $(".check"+id).show()
                    $(".button"+id).hide()
                }
            }
        })
    })
})

I’ve ensured that jQuery is loaded before this script in my HTML file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="{% static 'assets/js/address.js' %}"></script>

However, I’m still getting the error. Can someone please help me understand what might be causing this issue and how I can resolve it?

Any assistance would be greatly appreciated. Thank you!
script tag:

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Converting my python script to Javascript

I wrote a python script that given a JSON and a list of .npy files, reads each file and prints the numpy arrays. I like to convert it into Javascript but all my attempts so far fails. What is the proper way to convert it?

Here is my Python script:

import numpy as np
import json

with open('model_weights.json', 'r') as f:
    json_data = json.load(f)

for layer_name, layer_data in json_data.items():
    print(f"Layer: {layer_name}")

    weight_file = layer_data['weight']
    weight_data = np.load(weight_file)
    print("Weight:")
    print(weight_data)

    # Read and print the bias data
    bias_file = layer_data['bias']
    bias_data = np.load(bias_file)
    print("Bias:")
    print(bias_data)

    print()

Which prints like this:


Layer: conv_mid.0
Weight:
[[[[ 5.11894599e-02  6.01319224e-02  2.16415059e-02]
   [-5.73022485e-01  6.34898171e-02 -5.68771400e-02]
   [-4.38963100e-02 -9.82442126e-02  2.19287891e-02]]
...
...
Bias:
[-0.00059052  0.00416504 -0.00031364  0.00533698 -0.01785151 -0.00343998
  0.00104868  0.00327141]
...
...

Here is the JSON:

{
    "conv_mid.0": {
        "weight": "conv_mid.0_weight.npy",
        "bias": "conv_mid.0_bias.npy"
    },
    "conv_mid.1": {
        "weight": "conv_mid.1_weight.npy",
        "bias": "conv_mid.1_bias.npy"
    },
    "conv_mid.2": {
        "weight": "conv_mid.2_weight.npy",
        "bias": "conv_mid.2_bias.npy"
    },
    "conv_mid.3": {
        "weight": "conv_mid.3_weight.npy",
        "bias": "conv_mid.3_bias.npy"
    }
}

File Format: WebM encoded with the VP8 codec is not previewing in Safari browser

We have developed a feature in our Angular application to create a video file using MediaRecorder APIs. This application is intended to work seamlessly across Chrome, Edge, and Safari browsers. Users can create and preview the video file.

When a video file is created in Chrome and Edge, the format of the video file is WebM. The feature functions correctly in Chrome and Edge browsers, allowing users to create video files (including audio) and preview them.

However, when users perform the same action in Safari browser, the created video file format is MP4, which can be previewed in all supported browsers. The issue arises when attempting to preview the file created using Chrome and Edge in Safari browser.

The video files are stored in Azure Blob Storage via a .NET Core API.

Has anyone encountered a similar challenge and can offer assistance in resolving this issue? We require a universal video file format that can be used across all major browsers.