TypeError: functions.storage.object is not a function with firebase

I am trying to use Firebase Functions to listen for file upload events in Cloud Storage, but I encountered an error during deployment that says:

functions.storage.object is not a function.

    const functions = require("firebase-functions");

    exports.processFile = functions.storage.object().onFinalize(async (object) => {try {console.log("File uploaded:", object.name);

    if (!object.name) {
      console.log("No file name found.");
      return null;
    }

    console.log(`File content type: ${object.contentType}`);
    return null;
    } catch (error) {console.error("Error processing file:", error);return null;}});

version
“firebase-admin”: “^11.8.0”,
“firebase-functions”: “^4.3.1”,
“node”: “16”

I follow all instruction and also asked chatgpt. I think everything is right.but I cannot deplot it to the cloud. Hope someone can help me!

issue problem TypeError: functions.storage.object is not a function

help me to fix this issue

Problem with redux, doesn’t see store. reducer Manager.ts:23 Store does not have a valid reducer

I’m trying to make the modal load in a separate chunk, then I had to include slice in the store when launching the modal, but the following error appears in the browser console

I found this article in the documentation in Redux Toolkit code splitting

reducerManager.ts:23 Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

import { combineReducers, Reducer, ReducersMapObject, UnknownAction} from "@reduxjs/toolkit";
import {ReducerManager, StateSchema, StateSchemaKey} from "./StateSchema.ts";



export function createReducerManager(initialReducers : ReducersMapObject<StateSchema>): ReducerManager {
    const reducers = { ...initialReducers }

    let combinedReducer = combineReducers(reducers)

    let keysToRemove: StateSchemaKey[] = []

    return {
        getReducerMap: () => reducers,
        reduce: (state: StateSchema, action : UnknownAction) => {
            if (keysToRemove.length > 0) {
                state = { ...state }
                for (let key of keysToRemove) {
                    delete state[key]
                }
                keysToRemove = []
            }
            return combinedReducer(state, action)
        },
        add: (key : StateSchemaKey, reducer : Reducer) => {
            if (!key || reducers[key]) {
                return
            }
            reducers[key] = reducer
            combinedReducer = combineReducers(reducers)
        },
        remove: (key : StateSchemaKey) => {
            if (!key || !reducers[key]) {
                return
            }

            // Remove it from the reducer mapping
            delete reducers[key]

            // Add the key to the list of keys to clean up
            keysToRemove.push(key)

            // Generate a new combined reducer
            combinedReducer = combineReducers(reducers)
        }
    }
}

I tried to type, but reduce was still an error.

import {combineReducers, configureStore, ReducersMapObject} from "@reduxjs/toolkit";
import {StateSchema} from "@/app/StoreProvider/config/StateSchema.ts";
import {userReducer} from '@/entities/User'
import {createReducerManager} from "./reducerManager.ts";

export function createReduxStore(initialState?: StateSchema) {
    // @ts-ignore
    const rootReducer: ReducersMapObject<StateSchema> = combineReducers({
        user: userReducer,
    })


    const reducerManager = createReducerManager(rootReducer);

    const store = configureStore<StateSchema>({
        reducer: reducerManager.reduce,
        preloadedState: initialState,
    })

    // @ts-ignore
    store.reducerManager = reducerManager

    return store
}

Here again TS showed an error, but I decided to ignore it because I don’t understand what is needed from me

The error itself is displayed in the browser console

reducerManager.ts:23 Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values ​​are reducers.

This is where I’m trying to take advantage

const store = useStore() as ReduxStoreWithManager

 const username = useSelector(getLoginUsername);
 const password = useSelector(getLoginPassword);
 const isLoading = useSelector(getLoginIsLoading);
 const error = useSelector(getLoginError);



 useEffect(() => {
     store.reducerManager.add('loginForm', loginReducer)
    dispatch({type : "@INIT LOGIN_FORM"})
     return () => {
         store.reducerManager.remove('loginForm');
         dispatch({type : "@REMOVE LOGIN_FORM"})

     }
 })

how to not show the lightslide popup in lightgallery and click to external link?

I have been using lightgallery – [https://www.lightgalleryjs.com/][1] for my wordpress project. The problem I am facing is I don’t want to show the popup on image click but instead show the external url on image click. But I haven’t found any settings/events/methods which prevent the popup to not show and go to external url on image click.

Javascript code am using with settings right now is :

$(document).ready(function(){
                $('.lg-img-wrap').click(false);
                $('#lightgallery').lightGallery({
                    autoplay : false,
                    share : false,
                    download : false,
                    videojs: true,
                    closable: false,
                    gallery: false,
                    dynamic: false,
                    hash: false,
                    // onSliderLoad: function(el) {
                    //     el.closeGallery();
                    // }
                });
            });

I want to know whether the option I mentioned is possible or not ? If yes how am I to achieve that ?

Thanks in advance for any suggestions or help or guidance.

Swiper Carousel glitch – last slide displays during slide transition

I’m using Swiper carousel.

One thing I’m finding is that it’ll briefly show the last slide when transitioning between Slides 1 & 2. Why is this? Is this a known glitch?

Here’s a JSFiddle and I’ve included a sample of my script below.

<div class="swiper-container relative w-full text-center text-white curve-bottom overflow-hidden">

        <div class="swiper-wrapper">
            
            <div class="swiper-slide">
                <img src="https://placehold.co/600x400?text=Slide1" alt="Glasgow" class="w-full h-full object-center object-cover">
            </div>
            
            <div class="swiper-slide">
                <img src="https://placehold.co/600x400?text=Slide2" alt="London" class="w-full h-full object-right-top object-cover">
            </div>
            
            <div class="swiper-slide">
                <img src="https://placehold.co/600x400?text=Slide3" alt="Manchester" class="w-full h-full object-left object-cover">
            </div>
            
            <div class="swiper-slide">
                <img src="https://placehold.co/600x400?text=Slide4" alt="Edinburgh" class="w-full h-full object-center object-cover">
            </div>

        </div>
    
    </div>

    <!-- Swiper.js Script -->
    <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
    <script>
        const swiper = new Swiper('.swiper-container', {
            loop: true, // Ensures seamless looping
            autoplay: {
                delay: 2500, // 7 seconds between slides
                disableOnInteraction: false, // Continues autoplay after interactions
            },
            effect: 'fade', // Smooth fade transition between slides
            fadeEffect: {
                crossFade: true, // Prevents visible overlap of slides
            },
            speed: 2500, // Controls the duration of fade transitions
        });
    </script>

    <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">

    <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>

Node js fetch wrapper library can’t send post request

I made http request library for my ctfs.
This is wrapper for fetch API.

If you use fetch directly, a normal request is made, but when i send post request with this library, the get request is sent. I really don’t know why this happens.

Target server is uvicorn under caddy

the sector of code that should send post request

const res1 = await this.rh.sendRequest("POST", "/live");
console.log(res1)
if (res1.status !== 201) throw Error("Cannot open vm");
console.log("waiting for vm open...");

RequestHelper.ts

import {
  ContentType,
  HttpAuthorize, HttpAuthorizeSchema, HttpCookie,
  HttpHeader,
  HttpHeaderObject,
  HttpRequestBody,
  HttpRequestMethod,
  HttpResponse
} from "./types";
import {CookieBuilder} from "./CookieBuilder";


export class RequestHelper {
  private BASE_URL: string;

  private CONTENT_TYPE: ContentType | string;
  private AUTHORIZATION: HttpAuthorize | null;
  private COOKIE: CookieBuilder;

  private CUSTOM_HEADERS: Headers;

  constructor(baseURL: string) {
    this.BASE_URL = baseURL;

    this.CONTENT_TYPE = "";
    this.AUTHORIZATION = null;
    this.COOKIE = new CookieBuilder();

    this.CUSTOM_HEADERS = new Headers();
  }

  // GETTER ===============================================================================
  getBaseURL(): string {
    return this.BASE_URL;
  }

  getContentType(): ContentType | string {
    return this.CONTENT_TYPE;
  }

  getHeaders(): HttpHeaderObject {
    return Object.fromEntries([...this.CUSTOM_HEADERS]);
  }

  getAuth(): HttpAuthorize | null {
    return this.AUTHORIZATION;
  }

  getCookie(): HttpCookie {
    return this.COOKIE.getCookies();
  }

  // SETTER ===============================================================================
  setBaseUrl(baseURL: string): RequestHelper  {
    this.BASE_URL = baseURL;
    return this;
  }

  setContentType(contentType: ContentType | string): RequestHelper {
    this.CONTENT_TYPE = contentType;
    return this;
  }

  addHeader(key: HttpHeader | string, value: string): RequestHelper {
    this.CUSTOM_HEADERS.set(key, value);
    return this;
  }

  delHeader(key: HttpHeader): RequestHelper {
    this.CUSTOM_HEADERS.delete(key);
    return this;
  }

  setHeader(obj: HttpHeaderObject): RequestHelper {
    this.CUSTOM_HEADERS = new Headers(obj);
    return this;
  }

  resetHeader(): RequestHelper {
    this.CUSTOM_HEADERS = new Headers();
    return this;
  }

  setAuth(schema: HttpAuthorizeSchema, value: string): RequestHelper {
    this.AUTHORIZATION = {
      schema,
      value
    }
    return this;
  }

  setBasicAuth(username: string, password: string): RequestHelper {
    const authString = Buffer.from(`${username}:${password}`).toString("base64");
    this.AUTHORIZATION = {
      schema: "Basic",
      value: authString,
    }
    return this;
  }

  setBearerAuth(token: string) {
    this.AUTHORIZATION = {
      schema: "Bearer",
      value: token,
    }
  }

  resetAuth(): RequestHelper {
    this.AUTHORIZATION = null;
    return this;
  }

  setCookie(key: string, value: string): RequestHelper {
    this.COOKIE.setCookie(key, value);
    return this;
  }

  delCookie(key: string): RequestHelper {
    this.COOKIE.delCookie(key);
    return this;
  }

  resetCookie(): RequestHelper {
    this.COOKIE.resetCookie();
    return this;
  }

  // EXECUTES =============================================================================
  async sendRequest<t = any>(method: HttpRequestMethod | string, path: string, body?: HttpRequestBody | string, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    // build url
    let url = `${this.BASE_URL.endsWith("/") ? this.BASE_URL.substring(0, this.BASE_URL.length-1) : this.BASE_URL}/${path.startsWith("/") ? path.substring(1, path.length) : path}`;
    if (url.endsWith("/")) url = url.substring(0, url.length-1);

    // header priority (one-time > custom setters(auth, content-type..) > fixed headers)
    // merge fixed headers(permanent header) and specific headers(one-time header)
    const requestHeader = new Headers(this.getHeaders());
    if (this.CONTENT_TYPE)
      requestHeader.set("Content-Type", this.CONTENT_TYPE);
    if (this.AUTHORIZATION)
      requestHeader.set("Authorization", `${this.AUTHORIZATION.schema} ${this.AUTHORIZATION.value}`);
    if (Object.keys(this.COOKIE.getCookies()).length)
      requestHeader.set("Cookie", this.COOKIE.build());
    if (customHeader) {
      Object.entries(customHeader).forEach(([k, v]) => {
        requestHeader.set(k, v);
      });
    }

    let requestBody = "";
    if (body && typeof body !== "string") {
      switch (this.CONTENT_TYPE) {
        case "application/json":
          requestBody = JSON.stringify(body);
          break;
        case "application/x-www-form-urlencoded":
          requestBody = Object.entries(body).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
          break;
        default:
          requestBody = body.toString();
      }
    }else if (body) requestBody = body;

    const res = await fetch(url, {
      method: method,
      headers: requestHeader,
      body: requestBody || undefined,
      cache: "no-cache"
    });

    let bytes: Uint8Array | null;
    let text: string | null;
    let json: t | null;
    let formData: FormData | null;
    const formRegex = /((?<group>(?<key>[^=&]+)=(?<value>[^=&]+))&?)/g
    try { bytes = await res.bytes(); } catch (e) { bytes = null }
    try { if (bytes !== null) text = new TextDecoder().decode(bytes); else throw Error() } catch (e) { text = null }
    try { if (text !== null) json = JSON.parse(text) as t;            else throw Error() } catch (e) { json = null }
    try { if (text !== null && formRegex.test(text)) {
      formData = Object.fromEntries(text.split("&").map((e) => e.split("=")));
    } else throw Error(); } catch (e) { formData = null }

    return {
      ok: res.ok,
      url: res.url,
      headers: res.headers,
      status: res.status,
      statusText: res.statusText,
      bytes,
      text,
      json,
      formData,
    }
  }

  async get<t = any>(path: string, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("GET", path, undefined, customHeader);
  }

  async post<t = any>(path: string, body?: HttpRequestBody, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("POST", path, body, customHeader);
  }

  async put<t = any>(path: string, body?: HttpRequestBody, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("PUT", path, body, customHeader);
  }

  async patch<t = any>(path: string, body?: HttpRequestBody, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("PATCH", path, body, customHeader);
  }

  async delete<t = any>(path: string, body?: HttpRequestBody, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("DELETE", path, body, customHeader);
  }
}

ProblemHelper.ts

import {
  ContentType,
  HttpAuthorize, HttpAuthorizeSchema, HttpCookie,
  HttpHeader,
  HttpHeaderObject,
  HttpRequestBody,
  HttpRequestMethod,
  HttpResponse
} from "./types";
import {CookieBuilder} from "./CookieBuilder";


export class RequestHelper {
  private BASE_URL: string;

  private CONTENT_TYPE: ContentType | string;
  private AUTHORIZATION: HttpAuthorize | null;
  private COOKIE: CookieBuilder;

  private CUSTOM_HEADERS: Headers;

  constructor(baseURL: string) {
    this.BASE_URL = baseURL;

    this.CONTENT_TYPE = "";
    this.AUTHORIZATION = null;
    this.COOKIE = new CookieBuilder();

    this.CUSTOM_HEADERS = new Headers();
  }

  // GETTER ===============================================================================
  getBaseURL(): string {
    return this.BASE_URL;
  }

  getContentType(): ContentType | string {
    return this.CONTENT_TYPE;
  }

  getHeaders(): HttpHeaderObject {
    return Object.fromEntries([...this.CUSTOM_HEADERS]);
  }

  getAuth(): HttpAuthorize | null {
    return this.AUTHORIZATION;
  }

  getCookie(): HttpCookie {
    return this.COOKIE.getCookies();
  }

  // SETTER ===============================================================================
  setBaseUrl(baseURL: string): RequestHelper  {
    this.BASE_URL = baseURL;
    return this;
  }

  setContentType(contentType: ContentType | string): RequestHelper {
    this.CONTENT_TYPE = contentType;
    return this;
  }

  addHeader(key: HttpHeader | string, value: string): RequestHelper {
    this.CUSTOM_HEADERS.set(key, value);
    return this;
  }

  delHeader(key: HttpHeader): RequestHelper {
    this.CUSTOM_HEADERS.delete(key);
    return this;
  }

  setHeader(obj: HttpHeaderObject): RequestHelper {
    this.CUSTOM_HEADERS = new Headers(obj);
    return this;
  }

  resetHeader(): RequestHelper {
    this.CUSTOM_HEADERS = new Headers();
    return this;
  }

  setAuth(schema: HttpAuthorizeSchema, value: string): RequestHelper {
    this.AUTHORIZATION = {
      schema,
      value
    }
    return this;
  }

  setBasicAuth(username: string, password: string): RequestHelper {
    const authString = Buffer.from(`${username}:${password}`).toString("base64");
    this.AUTHORIZATION = {
      schema: "Basic",
      value: authString,
    }
    return this;
  }

  setBearerAuth(token: string) {
    this.AUTHORIZATION = {
      schema: "Bearer",
      value: token,
    }
  }

  resetAuth(): RequestHelper {
    this.AUTHORIZATION = null;
    return this;
  }

  setCookie(key: string, value: string): RequestHelper {
    this.COOKIE.setCookie(key, value);
    return this;
  }

  delCookie(key: string): RequestHelper {
    this.COOKIE.delCookie(key);
    return this;
  }

  resetCookie(): RequestHelper {
    this.COOKIE.resetCookie();
    return this;
  }

  // EXECUTES =============================================================================
  async sendRequest<t = any>(method: HttpRequestMethod | string, path: string, body?: HttpRequestBody | string, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    // build url
    let url = `${this.BASE_URL.endsWith("/") ? this.BASE_URL.substring(0, this.BASE_URL.length-1) : this.BASE_URL}/${path.startsWith("/") ? path.substring(1, path.length) : path}`;
    if (url.endsWith("/")) url = url.substring(0, url.length-1);

    // header priority (one-time > custom setters(auth, content-type..) > fixed headers)
    // merge fixed headers(permanent header) and specific headers(one-time header)
    const requestHeader = new Headers(this.getHeaders());
    if (this.CONTENT_TYPE)
      requestHeader.set("Content-Type", this.CONTENT_TYPE);
    if (this.AUTHORIZATION)
      requestHeader.set("Authorization", `${this.AUTHORIZATION.schema} ${this.AUTHORIZATION.value}`);
    if (Object.keys(this.COOKIE.getCookies()).length)
      requestHeader.set("Cookie", this.COOKIE.build());
    if (customHeader) {
      Object.entries(customHeader).forEach(([k, v]) => {
        requestHeader.set(k, v);
      });
    }

    let requestBody = "";
    if (body && typeof body !== "string") {
      switch (this.CONTENT_TYPE) {
        case "application/json":
          requestBody = JSON.stringify(body);
          break;
        case "application/x-www-form-urlencoded":
          requestBody = Object.entries(body).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
          break;
        default:
          requestBody = body.toString();
      }
    }else if (body) requestBody = body;

    const res = await fetch(url, {
      method: method,
      headers: requestHeader,
      body: requestBody || undefined,
      cache: "no-cache"
    });

    let bytes: Uint8Array | null;
    let text: string | null;
    let json: t | null;
    let formData: FormData | null;
    const formRegex = /((?<group>(?<key>[^=&]+)=(?<value>[^=&]+))&?)/g
    try { bytes = await res.bytes(); } catch (e) { bytes = null }
    try { if (bytes !== null) text = new TextDecoder().decode(bytes); else throw Error() } catch (e) { text = null }
    try { if (text !== null) json = JSON.parse(text) as t;            else throw Error() } catch (e) { json = null }
    try { if (text !== null && formRegex.test(text)) {
      formData = Object.fromEntries(text.split("&").map((e) => e.split("=")));
    } else throw Error(); } catch (e) { formData = null }

    return {
      ok: res.ok,
      url: res.url,
      headers: res.headers,
      status: res.status,
      statusText: res.statusText,
      bytes,
      text,
      json,
      formData,
    }
  }

  async get<t = any>(path: string, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("GET", path, undefined, customHeader);
  }

  async post<t = any>(path: string, body?: HttpRequestBody, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("POST", path, body, customHeader);
  }

  async put<t = any>(path: string, body?: HttpRequestBody, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("PUT", path, body, customHeader);
  }

  async patch<t = any>(path: string, body?: HttpRequestBody, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("PATCH", path, body, customHeader);
  }

  async delete<t = any>(path: string, body?: HttpRequestBody, customHeader?: HttpHeaderObject | null): Promise<HttpResponse<t>> {
    return await this.sendRequest<t>("DELETE", path, body, customHeader);
  }
}

full code: https://github.com/yeonfish6040/webhtools

How to study javascript in a more interesting way? [closed]

big bros! I have a strong desire to become a full-stack developer, but my laziness often gets in the way. I’ve tried various methods to stay consistent, but unfortunately, none of them last beyond a week. I really want to make progress and learn in a way that keeps me motivated and engaged. Can you suggest some interesting or effective ways to study that will help me stay on track? I’d really appreciate your advice!

How can I lock the orientation to portrait mode on Android using React Native?

I want my react native app to support only portrait view . I have tried updating the android manifest but it does not seems to be working . When I disable the lock orientation mode on my device , my app turns into landscape mode .

I have tried updating the android manifest file using ,
android:screenOrientation="portrait"
But when I turn off the screen orientation lock on my device the app turns into landscape mode . Can anyone suggest a solution please .

Page Rendering Multiple Times in Next.js (v14.0.1)

I’m developing a new feature in a Next.js project and have encountered an unexpected behavior. The page hosting the component in question is rendering multiple times, even though the props remain unchanged across all renders.

– Observations:

  • Development Mode: The page renders 3 times.

  • Production Mode: The page renders 4 times.

– Environment:

Next.js version: 14.0.1

Node.js version: v23.5.0

  • URL Example:
    I access the page using the following URL:
    /en-us/buy-appartment-C0010101

Code Example:
Here is the code for the page:

import {
  generatePropertyDetailMetadata,
} from 'app/[lng]/(property-details)/utils';
import { PropertyDetailContainer } from 'containers/PropertyDetailContainer';
import { getCitiesWithNeighborhoods } from 'lib/services/server/getCitiesWithNeighborhoods';
import { getTrends } from 'lib/services/server/getTrends';
import { isWebViewServer } from 'lib/utils/helpersServer/isWebView';
import { Metadata } from 'next';

import { Box } from 'components/base/components/Box';
import { Container } from 'components/base/components/Container';
import { PageFooterSSR } from 'components/PageFooter/PageFooterSSr';

import { PropertyDetailPageSSRProps } from './types';
import { Suspense } from 'react';

export async function generateMetadata({
  params,
  searchParams,
}: PropertyDetailPageSSRProps): Promise<Metadata> {
  return generatePropertyDetailMetadata({
    params,
    searchParams,
  });
}

export const revalidate = 3600;

const BuyPropertyDetailPage = async ({
  params,
  searchParams,
}: PropertyDetailPageSSRProps) => {
  const isWebView = isWebViewServer() || !!searchParams?.referralOrigin;
  return (
    <>
      <Box sx={{ backgroundColor: 'blue_gray.50' }}>
        <Container maxWidth="xl">
          <Box sx={{ py: 2 }}>
            <PropertyDetailContainer
              params={params}
              searchParams={searchParams}
            />
          </Box>
        </Container>
      </Box>
      {!isWebView && <PageFooterSSR trends={[]} />}
    </>
  );
};

export default BuyPropertyDetailPage;

Issue:
The component BuyPropertyDetailPage is being rendered multiple times without any change in props.

What I’ve Tried:
Verified that props (params, searchParams) remain the same across renders.
Tested the behavior in production mode and development mode.

Angular barcode scanner libraries not returning accurate results

I have been trying to create a barcode scanner component in Angular 14. Tried multiple libraries like ngx-barcode-scanner, zxing-js/ngx-scanner, Quagga JS etc. But none of them are giving accurate results.

Please suggest a library that gives accurate barcode scanner results. Free libraries are better but if none of Free libraries work accurately, paid libraries are also fine. Please suggest.

Change User-Agent for iframe (HTMLIFrameElement) to embed Grafana dashboard in React

I want to embed a Grafana dashboard via ifram (see: https://grafana.com/docs/grafana/latest/dashboards/share-dashboards-panels/#embed-panel):

 <iframe
    id="id"
    title="Dashboard"
    user-agent="someUserAgentString" // that has no effect
    width="100%"
    height="100%"
    src={grafanaUrl}>
</iframe>

I need to change the user-agent for this iframe because this is needed in our environment as form of validation/security. I tried what I could find:

useEffect(() => {
    const iframe = document.querySelector('iframe');
    const window = iframe.contentWindow;
    const navi = window.navigator;

// these didn't seem to work
    Object.defineProperty(navi, 'user-agent', {value: 'someUserAgentString', writable: true})
    Object.defineProperty(navi, 'userAgent', {value: 'someUserAgentString', writable: true})

//also didn't seem to work
    async function getSrc() {
        const res = await fetch(grafanaUrl, {
            method: 'GET',
            headers: {
                'User-Agent' : 'someUserAgentString',
                writable: 'true'
            }
        });
        const blob = await res.blob();
        const urlObject = URL.createObjectURL(blob);
        document.querySelector('iframe').setAttribute("src", urlObject)
    }
    getSrc();
}, []); 

Issue converting JSON to XML using fast-xml-parser v4.5.1

I’m using the fast-xml-parser library (v4.5.1) with this CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/fast-xml-parser/4.5.1/fxparser.min.js"></script>

The conversion from XML to JSON works perfectly, but I run into an issue when converting JSON back to XML. Here’s my function for converting JSON to XML:

function convertJSONInXML(jsonData) {
  const options = {
    ignoreAttributes: false,
  };

  const builder = new XMLBuilder(options);
  let xmlDataStr = builder.build(jsonData);
}

However, when I run this, I get the following error:

ReferenceError: XMLBuilder is not defined

I’ve already tried a few things to fix this. First, I made sure the CDN link for fast-xml-parser is correct and verified it’s version 4.5.1. I also tested other libraries like xml-js, but none of them worked properly for my use case or JSON structure.

The weird part is that the XML-to-JSON conversion works fine using XMLParser, but the JSON-to-XML part with XMLBuilder just doesn’t work. I’m not sure if I’m missing something in the setup or if there’s another way I need to initialize XMLBuilder. Any ideas on what I might be doing wrong or how to make this work?

canvasTexture is blurry meanwhile the origin canvas is not

I’m using canvas as a texture to render a plane, but canvasTexutre on the plane is a little blurry. How can I fix that?

enter image description here

import * as THREE from "three";

const image = document.getElementById('origin-img')

/* --- draw 【canvas】 by image--- */
const canvas = document.getElementById('canvas')
canvas.width = image.width
canvas.height = image.height
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, image.width, image.height)

/* --- threejs scene --- */
const itemWidth = 300
const itemHeight = 300

const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(itemWidth / -2, itemWidth / 2, itemHeight / 2, itemHeight / -2, 0, 1000);
camera.position.z = 100;

const renderer = new THREE.WebGLRenderer({
  canvas: document.getElementById('webgl')
});
renderer.setSize(itemWidth, itemHeight);

// create a plane which uses 【canvas】 as texture
const geometry = new THREE.PlaneGeometry(image.width, image.height, 64, 64);
const material = new THREE.MeshBasicMaterial({
  map: new THREE.CanvasTexture(
    canvas,
    THREE.Texture.DEFAULT_MAPPING,
    THREE.ClampToEdgeWrapping,
    THREE.ClampToEdgeWrapping,
    THREE.LinearFilter,
    THREE.LinearMipmapLinearFilter,
    THREE.RGBAFormat,
    THREE.UnsignedByteType,
    1
  )
});
const plane = new THREE.Mesh(geometry, material);
scene.add(plane);

renderer.render(scene, camera);
<div class="app" style="display: flex; justify-content: space-between; width: 1200px;">
  <div class="item-container">
    <div class="item">
      <img id='origin-img' src="./origin-texture.png">
    </div>
    <div class="caption">Origin Image</div>
  </div>
  <div class="item-container">
    <div class="item">
      <canvas id="canvas"></canvas>
    </div>
    <div class="caption">Draw canvas by image</div>
  </div>
  <div class="item-container">
    <div class="item">
      <canvas id="webgl"></canvas>
    </div>
    <div class="caption">In threejs, create a plane which uses canvas as a texture</div>
  </div>
</div>
<script type="module" src="./index.js"></script>

TypeError: AsyncStorage.getItem is not a function

there seems to be an issue with the AsyncStorage library, whenever I try to use one of the objects of AsyncStorage, it throws a type error, when yesterday it never threw any typeErrors, and I am wondering what could be the cause of this? I am using expo with javascript, and react native

Error in CheckToken: TypeError: AsyncStorage.getItem is not a function
    at CheckToken (file:///C:/Users/karam/PrepAndCount/accessToken.js:46:42)
    at file:///C:/Users/karam/PrepAndCount/accessToken.js:90:1
    at ModuleJob.run (node:internal/modules/esm/module_job:271:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:547:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:116:5)
    ```


  [1]: https://i.sstatic.net/8kdZkfTK.png

swiper-bundle.min slider menu – save active class on item after click on it

i am using swiper-bundle to create a slider horizontal menu .
swiper-bundle.min.css and swiper-bundle.min.js .

i added an active class to the first item and trying to give each item the active class
after click on it and remove active from the siblings .

it works to give active class to items but not save the active on the clicked item .
how to save active on item after click on it ?

<div class="pt_sec_nav_cats">
<div class="container-fluid">
<div class="swiper pt_sec_nav_slide_prnt">
<div class="swiper-wrapper pt_sec_nav_slide">
<div class="swiper-slide active">
<a class="sof-swiper-link" href="index.php">home</a>
</div>
<?php foreach ( $items as $i => $item ) : 
$route = YendifVideoShareRoute::getCategoryRoute( $item, (int) $params->get( 'itemid', 0 ) );
$item_link = Route::_( $route );
?>
<div class="swiper-slide " >
<a href="<?php echo $item_link; ?>" class="sof-swiper-link">
<?php echo YendifVideoShareHelper::Truncate( $item->title, $params->get( 'title_length', 0 ) );?>
</a>
</div>                              

<?php endforeach; ?>                
</div>          
<button class="swiper-button-next sof-swiper-button"></button>
<button class="swiper-button-prev sof-swiper-button"></button>
</div>
</div>
</div>

<script>
$(document).ready(function() {
$(".swiper-slide").click(function() {
$(this).addClass("active").siblings().removeClass("active");
localStorage.setItem('toggleState', $(this).hasClass('active'));
});   
const toggleState = localStorage.getItem('toggleState'); 
if (toggleState === 'true') { 
const activeLi = $("#" + toggleState);
activeLi.addClass("active");       
}   
});
</script>

How to generate server-side PDFs containing charts (ECharts, ApacheChart) and tables in Node.js efficiently

I am currently generating PDFs server-side using Puppeteer, which contains dynamic data including charts (ECharts, ApacheChart) and tables. After generating the PDFs, I send them to Telegram. However, Puppeteer is resource-heavy and not the most efficient solution for this use case.

I would like to explore alternatives for generating these PDFs. My goal is to:

Use JSX or HTML to render dynamic data.
Create a PDF containing charts and tables.
Ensure the solution is lightweight and optimized for server-side processing.
What are some better approaches to generate PDFs server-side in Node.js, especially with charting libraries like ECharts and ApacheChart? Is there any lightweight library or tool that could replace Puppeteer?

Here is the sample code I am currently using with Puppeteer

const puppeteer = require('puppeteer');
const fs = require('fs');

async function generatePDF() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  const chartHtml = `
    <html>
      <head>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
      </head>
      <body>
        <div id="chart" style="width: 600px; height: 400px;"></div>
        <script>
          const chart = echarts.init(document.getElementById('chart'));
          chart.setOption({
            xAxis: {
              type: 'category',
              data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            },
            yAxis: {
              type: 'value'
            },
            series: [{
              data: [820, 932, 901, 934, 1290, 1330, 1320],
              type: 'line'
            }]
          });
        </script>
      </body>
    </html>
  `;

  await page.setContent(chartHtml);
  await page.pdf({ path: 'chart.pdf', format: 'A4' });

  await browser.close();
}

generatePDF();