React Mui DatePicker – cs localisation

I’m trying to use DatePicker in Czech language.

I used this code

import * as React from 'react';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs from 'dayjs';
import 'dayjs/locale/cs';

export default function BasicDatePicker() {
  const language = 'cs';
  dayjs.locale(language);

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DatePicker label="Test picker" />
    </LocalizationProvider>
  );
}

The problem is that the months were translated correctly, but the letters indicating the names of the days remained in English. In addition, in the Czech calendar, the day starts on Monday, here it starts on Sunday (see screen).

Screenshot

when I look in the dayjs/locale/cs file, all the translations are fine, but the calendar does not reflect this.

The full example is here: enter link description here

Is there anyone here who can identify the problem?

Adding a custom item to a react-google-places-autocomplete?

I was wondering if it’s possible to add a custom item into a GooglePlacesAutocomplete? I can’t seem to get it to work. Addresses work wonderfully, but I can’t add my own item, preferably to be the first item.

Tried a few things such as:

autocompletionRequest={{
                componentRestrictions: { country: 'AU' },
                types: ['(regions)', **'Remote'],**
              }}

I also tried adding ‘option’, but had no luck. Has anyone ever done this? I need to add a default entry, specifically ‘Remote’ as I’m building a website which could have remote as a location option.

<GooglePlacesAutocomplete
apiKey="xxx"
fetchDetails={true}
defaultValue={where ? { label: where } : null}
onLoadFailed={(error) => console.error("Google Places Autocomplete load failed", error)}
selectProps={{
placeholder: "Enter suburb for the task...",
sClearable: true,
menuPortalTarget: document.body,
value: where ? { label: where } : null,
onChange: (selectedOption) => {
  if (selectedOption) {
    setWhere(selectedOption.label);
  } else {
    setWhere('');
  }
},
styles: {
  control: (provided) => ({
    ...provided,
    height: '48px', // Slightly smaller to match NextUI "lg" more closely
    minHeight: '48px',
    borderRadius: '0.375rem', // Matches NextUI's rounded-lg
    borderColor: 'hsl(214, 100%, 50%)', // Primary color similar to NextUI
    boxShadow: 'none',
    '&:hover': {
      borderColor: 'hsl(214, 100%, 50%)',
    },
    '&.is-focused': {
      borderColor: 'hsl(214, 100%, 50%)',
      boxShadow: '0 0 0 2px rgba(0, 111, 238, 0.2)', // Similar to NextUI focus effect
    },
  }),
  singleValue: (provided) => ({
    ...provided,
    color: 'black',
  }),
  input: (provided) => ({
    ...provided,
    color: 'black',
  }),
  menu: (provided) => ({
    ...provided,
    zIndex: 9999,
    borderRadius: '0.375rem',
    boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)',
  }),
  option: (provided, state) => ({
    ...provided,
    backgroundColor: state.isSelected 
      ? 'hsl(214, 100%, 50%)' 
      : state.isFocused 
        ? 'hsl(214, 100%, 95%)' 
        : 'white',
    color: state.isSelected ? 'white' : 'black',
    ':active': {
      backgroundColor: 'hsl(214, 100%, 50%)',
      color: 'white',
    },
  }),
  dropdownIndicator: (provided) => ({
    ...provided,
    color: 'hsl(214, 20%, 50%)', // Subtle indicator color
  }),
  clearIndicator: (provided) => ({
    ...provided,
    color: 'hsl(214, 20%, 50%)', // Subtle clear indicator color
  }),
},
}}
autocompletionRequest={{
componentRestrictions: { country: 'AU' },
types: ['(regions)'],
// Add a custom filter to remove train stations and other irrelevant results
strictbounds: true,
}}
/>

Using JSON Schema Dependencies for Dynamic Dropdowns in JSON Forms

I’m using JSON Forms to render a field mapping view where users can map/translate a chosen field and its enumeration values to values in another system. The issue is that based on the input of field, I’d like to dynamically populate the fieldMapping.

Input data from system A

const results = [
  {
    label: "Background Color",
    name: "background_color",
    options: [
      { label: "Green", value: "green" },
      { label: "Red", value: "red" },
      { label: "Blue", value: "blue" },
    ],
  },
  {
    label: "Text Color",
    name: "text_color",
    options: [
      { label: "Black", value: "black" },
      { label: "White", value: "white" },
      { label: "Grey", value: "grey" },
    ],
];

I want to use this results array to populate the field dropdown with the name property and dynamically change the available options for fieldMapping based on the selected field.

For example:

  • If the user selects Background Color in the field dropdown, the fieldMapping section should allow mapping only the values [green, red, blue].
  • If the user selects Text Color in the field dropdown, the fieldMapping section should allow mapping only the values [black, white, grey].

Here’s the JSON schema I’m working on:

const schema = {
  type: "object",
  properties: {
    field: {
      type: "string",
      enum: results.map((r) => r.name), // Dropdown for "background_color", "text_color", etc.
    },
    fieldMapping: {
      type: "array",
      items: {
        type: "object",
        properties: {
          value: { type: "string" },
          mappedValue: { type: "string" },
        },
        required: ["value", "mappedValue"],
      },
    },
  },
  dependencies: {
    field: {
      oneOf: results.map((r) => ({
        properties: {
          field: { enum: [r.name] },
          fieldMapping: {
            type: "array",
            items: {
              type: "object",
              properties: {
                value: {
                  type: "string",
                  enum: r.options.map((o) => o.value), // Dynamically populated enum
                },
                mappedValue: { type: "string" },
              },
              required: ["value", "mappedValue"],
            },
          },
        },
      })),
    },
  },
};

The problem

The field dropdown renders correctly and displays the available fields, but the fieldMapping dropdown for value always displays an input field instead of dynamically showing the appropriate options (enum) for the selected field. It seems like the dependencies or oneOf logic is not being applied correctly.

I’ve verified that the schema is being generated as expected and includes the appropriate enum values for each field. However, JSON Forms does not seem to dynamically update the fieldMapping dropdown when the field changes.

Inserting id in localStorage returns null [closed]

i’ve been making a cart for my e commerce page, now i need to put my cart objects in localStorage, i manage that via array, then that array i insert in localStorage

The array is composed of an id that i need it to be different object after object that I add or remove

My objects array of products that will be added to localStorage is called “cart”

Here the logic to insert my idid: cart.length == 0 ? 1 : cart[cart.length - 1].id + 1

¿How it works? first check that products array (my cart) is empty, then set the first object id as 1, in else case, the following object to be added, check the id that was inserted before, and insert the id +1 than the previous one

The problem here is the first object inserted is id=1, but the following objects are id NULL

function handleSubmit(e){
    e.preventDefault()
    const newArray = products.filter(product => product.id == id).map(e => ({
      id: cart.length == 0 ? 1 : cart[cart.length - 1].id + 1,
      type: e.type,
      prod: e.prod,
      img: e.img,
      price: e.price
    }))
    setCart(newArray)
    updateCart(newArray)
    localStorage.setItem('cart', JSON.stringify(cart))
    // alert('El producto fue agregado al carrito')
  }

here app.jsx where i define cart

const [ cart, setCart ] = useState([])

  function updateCart(newArray){
    setCart([...cart, newArray])
  }

here: product => product.id == id compare my store with the id given by useParams hook

What i doing wrong here? Thanks!!!

I am trying to get the value of a JWT token saved as a cookie in my browser, but I am getting undefined in the log statement

Here is the function I am setting the cookies in

login: async (req, res) => {
    try {
            res.clearCookie('authtoken')
            const { email, password } = req.body;
    
            if (!email || !password) {
                return res.status(400).json({ error: 'Email and password are required.'});
            }
    
            const employee = await employeeModel.findOne({ where: { Email: email } });
    
            if (!employee) {
                return res.status(404).json({ error: 'Employee not found.' });
            }
    
            const user = await userModel.findOne({ where: { EmployeeId: employee.EmployeeID } });
    
            if (!user) {
                return res.status(404).json({ error: 'User not found.' });
            }

            const isMatch = await bcrypt.compare(password, user.password);
            if (!isMatch) {
                return res.status(401).json({ error: 'Invalid password.' });
            }
    
            const token = jwt.sign({userId:user.user_id}, process.env.JWT_SECRET, { expiresIn: '2h' })
            res.cookie('authtoken', token, { httpOnly: true,path: '/' })
                
            return res.status(200).json({ message: 'Login successful.' });
        } catch (error) {
            console.log('An error occurred signing in', error);
            return res.status(500).json({ error: 'An error occurred logging in.' });
        }
    },

and here is how I am trying to access it

    viewAll: async (req, res) => {
        try {
            const {token} = req.cookies;

            console.log(token);
            
            const blockItems = await blockModel.findAll();
            return res.status(200).json(blockItems);
        } catch (error) {
            console.log('An error occurred fetching blocks', error);
            return res.status(500).json({ error: 'Internal Server Error' });
        }
    }

It logs out undefined

I have tried setting the cookie-parser, even used the withCredentials from the frontend, but I am still getting undefined.

Puppeteer PDF page margin that allows overflow

I want to add spacing (padding/margin or however it is possible) to all dynamic pages. Also I want to be able sometimes to ignore that spacing, for some sections, ideally with negative margins.

Applying style @page {margin: 50px;} or giving margin to Page instance works for applying spacing to all pages. But it does not allow me exit its content. It does not allow me to move something When I give negative margin, its content gets clipped of

<style>
    @page {
       padding: 50px;
    }
    .header {
        margin: -20px -30px 0;
        background-color: #000000;
        color: white;
    }
</style>

<div class="header">
    Header
</div>

enter image description here

Having a single wrapper html element that has padding .page {padding: 50px;} allows me to exit its content with negative margins. But only the horizontal padding applies to all pages. Only the first page has the padding top and only the last page has padding bottom. I would like to apply padding to all 4 sides of all pdf pages.

Ideally I want something like this

@page {
    padding: 50px;
    overflow: visible;
}

But the @page does not allow overflowing.

I can’t manually control the padding for each page individually, the content is dynamic. I would prefer not positioning with absolute

How to give padding to all dynamic pages with the ability to ignore it?

Scraping and downloading images from a public folder (Dropbox, Drive etc) [closed]

I am building a feature in my app where users can paste a public folder link (from services like Dropbox, OneDrive, or Google Drive), view the images in the folder, and select which ones to download and upload to Azure Blob Storage.

The users should be able to enter a link of a public URL and then, I want to show them previews of the images. The ones they choose will be downloaded to my Blob Storage.

I have one thing here that does kind of something similar. In that, people can paste any website they want and with a scraper, I am able to access the images etc being used there. It’s being done in a socket connection where I am able to get all the images and fonts being used on a site.

Here’s how that looks like:

socket.on("scrapeURL", async (targetUrl: string) => {
  try {
    const svgs: any = [];
    const images: any = [];
    const tempSvgs: any = [];
    const tempImages: any = [];

    socket.emit("scrapeProgress", `Fetching ${targetUrl}.`);

    let response;
    try {
      response = await axios.get(targetUrl, {
        headers: {
          "Content-Type": "application/json",
          "User-Agent": "app-backend-server",
          Accept: "*/*",
          Connection: "keep-alive",
        },
      });
    } catch (error) {
      socket.emit("scrapeError", "Unable to fetch the target URL.");
      return;
    }

    const html = response?.data || undefined;

    if (!html) {
      socket.emit("scrapeError", "Unable to fetch the target URL.");
      return;
    }

    socket.emit("scrapeProgress", "Loading data to Cheerio.");

    // Load HTML content into Cheerio
    const $ = cheerio.load(html);

    socket.emit("scrapeProgress", "Getting images details.");

    // Extracting images
    $("img").each((index, element) => {
      const imageUrl = $(element).attr("src");
      const lazyImageUrl = $(element).attr("data-lazy-src");
      const imgUrl = lazyImageUrl || imageUrl || null;

      if (imgUrl) {
        tempImages.push(url.resolve(targetUrl, imgUrl));
      }
    });

    // Extracting background images
    $("[style]").each((index, element) => {
      const style = $(element).attr("style");
      if (style && style.includes("background-image")) {
        const regex = /url(['"]?(.*?)['"]?)/;
        const match = regex.exec(style);
        if (match && match[1]) {
          tempImages.push(match[1]);
        }
      }
    });

    socket.emit("scrapeProgress", "Getting SVGs details.");

    // Extracting SVGs
    $("svg").each((index, element) => {
      const svgContent = $.html(element);
      tempSvgs.push(`data:image/svg+xml,${encodeURIComponent(svgContent)}`);
    });

    for (const image of tempImages) {
        images.push(image);
    }

    for (const svg of tempSvgs) {
        svgs.push(svg);
    }

    socket.emit("scrapeResult", {
      images,
      allImages: images?.length ?? 0,
      allSvgs: svgs?.length ?? 0,
    });
  } catch (error: any) {
    if (error?.message && error.message.includes("ENOTFOUND")) {
      socket.emit("scrapeError", Err.notFound("Target URL not found."));
    } else {
      socket.emit("scrapeError", `Target URL not found.`);
    }
  }
});

What I am trying to do now is something similar for other public folders like Dropbox, Google Drive and OneDrive. In the public folder, I want to be able to access and save any images in that folder.

Note It doesn’t necessarily have to be a scraping solution. But anything that lets me download images from these public folders. Is there a way I can do this?

React Material UI – Navbar Items Positioning Issue

I am facing a issue while positioning the menu items in my Navbar component when screen size is small.

This is the view of normal screen.
enter image description here

On small screen, the view is like this:
enter image description here

There is an empty space between the Appbar and the menu. As per my knowledge this is due to flex properties. I tried to remove **flexGrow: 1** property from the styles. But this didn’t work.

Here is my component code:

import {
  AppBar,
  Toolbar,
  Stack,
  Menu,
  MenuItem
} from '@mui/material'
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown'
import { MuiTypography } from '../typography/Typography'
import { MuiButton, MuiIconButton } from '../form-controls/Button'
import { useState } from 'react'
import { Link, useLocation } from 'react-router-dom'
import MenuIcon from '@mui/icons-material/Menu';

export const MuiNavbar = ({ title, logoIcon, navItems, handleTitleClick }) => {
  const location = useLocation();
  const navLinkStyles = (path) => {
    const isActive = location.pathname === path ? true : false;
    return {
      fontWeight: isActive ? 'bold' : 'normal',
    }
  }

  const [anchorNav, setAnchorNav] = useState(null);
  const openMenu = (e) => {
    setAnchorNav(e.currentTarget);
  }
  const closeMenu = () => {
    setAnchorNav(null);
  }


  return (
    <AppBar position='static' color='transparent'>
      <Toolbar variant="dense">
        <MuiIconButton size='large' edge='start' color='inherit' aria-label='logo' icon={logoIcon} onClick={handleTitleClick} sx={{ display: { xs: 'none', md: 'flex' } }} />
        <MuiTypography
          variant='h6'
          component='div'
          sx={{
            flexGrow: 1,
            display: { xs: 'none', md: 'flex' }
          }}
          text={title}
          onClick={handleTitleClick}
        />
        <Stack direction='row' spacing={2} sx={{ display: { xs: 'none', md: 'flex' } }}>
          {
            navItems.map(item => {
              return item?.hasSubMenu ? (
                <MuiNavSubMenu key={item.id} item={item} sx={navLinkStyles} />
              ) : (
                item?.type === "custom"
                  ? <MenuItem key={item.id}>{item.customComponent}</MenuItem>
                  : <MenuItem key={item.id} component={Link} to={item.to} sx={navLinkStyles(item.to)}>{item.title}</MenuItem>
              );
            })
          }
        </Stack>
        <Stack spacing={2} sx={{ display: { xs: 'flex', md: 'none' } }}>
          <MuiIconButton size='large' edge='start' color='inherit' icon={<MenuIcon />} onClick={openMenu} />
          <Menu open={anchorNav} onClose={closeMenu} sx={{ display: { xs: 'flex', md: 'none' } }}>
            {
              navItems.map(item => {
                return item?.hasSubMenu ? (
                  <MuiNavSubMenu key={item.id} item={item} sx={navLinkStyles} />
                ) : (
                  item?.type === "custom"
                    ? <MenuItem key={item.id}>{item.customComponent}</MenuItem>
                    : <MenuItem key={item.id} component={Link} to={item.to} sx={navLinkStyles(item.to)}>{item.title}</MenuItem>
                );
              })
            }
          </Menu>
        </Stack>
        <MuiTypography
          variant='h6'
          component='div'
          sx={{ display: { xs: 'flex', md: 'none' }}}
          text={title}
          onClick={handleTitleClick}
        />
      </Toolbar>
    </AppBar>
  )
}

This is the code for subcomponent MuiNavSubMenu

export const MuiNavSubMenu = ({ item }) => {
  const [anchorEl, setAnchorEl] = useState(null)
  const open = Boolean(anchorEl)
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget)
  }
  const handleClose = () => {
    setAnchorEl(null)
  }

  const location = useLocation();

  const navLinkStyles = (path) => {
    const isActive = location.pathname === path ? true : false;

    return {
      fontWeight: isActive ? 'bold' : 'normal',
    }
  }

  var itemId = item.id;
  var menuItemId = itemId + "-menu";

  return (
    <Stack direction="row" spacing={2}>
      <MuiButton
        key={itemId}
        id={itemId}
        color="inherit"
        aria-controls={open ? { menuItemId } : undefined}
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        endIcon={<KeyboardArrowDownIcon />}
        onClick={handleClick}
        text={item.title}
        href={item.to}
      />
      <Menu
        key={menuItemId}
        id={menuItemId}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        MenuListProps={{
          "aria-labelledby": { itemId },
        }}
      >
        {
          item.subItems.map(i => {
            return i?.hasSubMenu ? (
              <MuiNavSubMenu key={i.id} item={i} sx={navLinkStyles} />
            ) : (
              <MenuItem key={i.id} component={Link} to={i.to} sx={navLinkStyles(i.to)} onClick={i.handleClose}>{i.title}</MenuItem>
            );


          })
        }
      </Menu>
    </Stack>
  );
}

Please help.
Thanks & Regards

I tried to remove **flexGrow: 1** property from the styles. But this didn’t work.

“TypeError: CredentialsProvider is not a function in NextAuth.js – Next.js 13 setup issue”

ive been stuck for three days at this


import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        // Dummy user validation - replace with real logic
        if (
          credentials.email === "[email protected]" &&
          credentials.password === "password"
        ) {
          return { id: 1, name: "Test User", email: "[email protected]" };
        }
        return null; // Return null for failed login
      },
    }),
  ],
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
thats my route.js and its been telling me "TypeError: next_auth_providers_credentials__WEBPACK_IMPORTED_MODULE_1__ is not a function"  ive done almost everyhtinng what chat gpt told me whats wrong in this please tell me as soon as possible or im gonna kill myself

im currently working on frontend part and imm gonna do backend later in frontend i want when i click login it should send me to the username page i already created that and a tost saying youre logged in

Web form blocking when accessing via VPN, TOR, etc [closed]

Good morning.
Any clue what is the cause of this domain blocking my access to a web form of search whenever it is accessed through a VPN, TOR, proxy, etc (even if the country is the same as the site being accessed)?
The response in this case is always an iframe with the message and the error of: Forbidden 403

It is not the same when the form is accessed without any “intermediary”, i.e. with the original Ip provided by the original ISP.

Note: the domain name is changed for certain reasons.

This is the request:

GET /directoryxxxxxxxx/search-public_search.action HTTP/1.1
Host: dominio-interno.dominio.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.5666.197 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://www.dominio.com/services/query-users
Dnt: 1
Sec-Gpc: 1
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: iframe
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-site
Sec-Ch-Ua-Platform: "Windows"
Sec-Ch-Ua: "Google Chrome";v="113", "Chromium";v="113", "Not=A?Brand";v="24"
Sec-Ch-Ua-Mobile: ?0
Priority: u=4
Te: trailers
Connection: keep-alive

This is the response:

HTTP/2 403 Forbidden
Server: awselb/2.0
Date: Wed, 11 Dec 2024 09:47:21 GMT
Content-Type: text/html
Content-Length: 520

<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
</body>
</html>
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->

Is it possible that it is some WAF protection system of the site, some kind of script? Where should I look?.

Thanks in advance.

Mobile Browser Camera feed to detect/recognise the local image i passed in React JS

I’ve been trying to detect the image i passed to the ‘detectTrigger()’ function when the browser camera feed is placed infront of this page.

  1. What i do is pass the image asset local path i want to detect to the detectTrigger().
  2. After running this page(ill run this in my mobile using ngrok), Mobile phone browser camera feed(back camera) will be opened.
  3. I show the mobile camera feed to the image i passed(ill keep them open in my system)
  4. Now camera feed should detect the image shown to it, if the image is same as the image passed to the detectTrigger().

I don’t know where im going wrong, the image is not being detected/recognised, can anyone help me in this.

    import React, { useRef, useState, useEffect } from 'react';
    import cv from "@techstark/opencv-js";
    
    
    const AR = () => {
        const videoRef = useRef(null);
        const canvasRef = useRef(null);
        const [modelVisible, setModelVisible] = useState(false);

    const loadTriggerImage = async (url) => {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.crossOrigin = "anonymous"; // Handle CORS
            img.src = url;
            img.onload = () => resolve(img);
            img.onerror = (e) => reject(e);
        });
    };

    const detectTrigger = async (triggerImageUrl) => {
        try {
            console.log("Detecting trigger...");
            const video = videoRef.current;
            const canvas = canvasRef.current;
    
            if (video && canvas && video.videoWidth > 0 && video.videoHeight > 0) {
                const context = canvas.getContext("2d");
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
    
                context.drawImage(video, 0, 0, canvas.width, canvas.height);
                const frame = cv.imread(canvas);
    
                const triggerImageElement = await loadTriggerImage(triggerImageUrl);
                const triggerCanvas = document.createElement("canvas");
                triggerCanvas.width = triggerImageElement.width;
                triggerCanvas.height = triggerImageElement.height;
                const triggerContext = triggerCanvas.getContext("2d");
                triggerContext.drawImage(triggerImageElement, 0, 0);
                const triggerMat = cv.imread(triggerCanvas);
    
                const detector = new cv.ORB();
                const keyPoints1 = new cv.KeyPointVector();
                const descriptors1 = new cv.Mat();
                detector.detectAndCompute(triggerMat, new cv.Mat(), keyPoints1, descriptors1);
    
                const keyPoints2 = new cv.KeyPointVector();
                const descriptors2 = new cv.Mat();
                detector.detectAndCompute(frame, new cv.Mat(), keyPoints2, descriptors2);
    
                const matcher = new cv.BFMatcher(cv.NORM_HAMMING, true);
                const matches = new cv.DMatchVector();
                matcher.match(descriptors1, descriptors2, matches);
    
                const goodMatches = [];
                for (let i = 0; i < matches.size(); i++) {
                    const match = matches.get(i);
                    if (match.distance < 30) { // Tightened threshold
                        goodMatches.push(match);
                    }
                }
                console.log(`Matches Found: ${matches.size()}, Good Matches: ${goodMatches.length}`);
    
                // Require a minimum number of good matches
                if (goodMatches.length > 10) {
                    console.log("Trigger Image Detected!");
                    // Optional: Verify matches using homography (if necessary)
                    const srcPoints = [];
                    const dstPoints = [];
                    goodMatches.forEach((match) => {
                        srcPoints.push(keyPoints1.get(match.queryIdx).pt.x, keyPoints1.get(match.queryIdx).pt.y);
                        dstPoints.push(keyPoints2.get(match.trainIdx).pt.x, keyPoints2.get(match.trainIdx).pt.y);
                    });
    
                    const srcMat = cv.matFromArray(goodMatches.length, 1, cv.CV_32FC2, srcPoints);
                    const dstMat = cv.matFromArray(goodMatches.length, 1, cv.CV_32FC2, dstPoints);
    
                    const homography = cv.findHomography(srcMat, dstMat, cv.RANSAC, 5);
    
                    if (!homography.empty()) {
                        setModelVisible(true);
                    } else {
                        console.log("Homography failed, no coherent match.");
                        setModelVisible(false);
                    }
    
                    // Cleanup matrices
                    srcMat.delete();
                    dstMat.delete();
                    homography.delete();
                } else {
                    console.log("Trigger Image Not Detected.");
                    setModelVisible(false);
                }
    
                // Cleanup
                frame.delete();
                triggerMat.delete();
                keyPoints1.delete();
                keyPoints2.delete();
                descriptors1.delete();
                descriptors2.delete();
                matcher.delete();
            }
        } catch (error) {
            console.error("Error detecting trigger:", error);
        }
    };

    useEffect(() => {
        const triggerImageUrl = '/assets/pavan-kumar-nagendla-11MUC-vzDsI-unsplash.jpg'; // Replace with your trigger image path

        // Start video feed
        navigator.mediaDevices
            .getUserMedia({ video: { facingMode: "environment" } })
            .then((stream) => {
                if (videoRef.current) videoRef.current.srcObject = stream;
            })
            .catch((error) => console.error("Error accessing camera:", error));

        // Start detecting trigger at intervals
        const intervalId = setInterval(() => detectTrigger(triggerImageUrl), 500);

        return () => clearInterval(intervalId);
    }, []);

    return (
        <div
            className="ar"
            style={{
                display: "grid",
                placeItems: "center",
                height: "100vh",
                width: "100vw",
                position: "relative",
            }}
        >
            <div>
                <video ref={videoRef} autoPlay muted playsInline style={{ width: "100%" }} />
                <canvas ref={canvasRef} style={{ display: "none" }} />
                {modelVisible && (
                    <div
                        style={{
                            position: "absolute",
                            top: "50%",
                            left: "50%",
                            transform: "translate(-50%, -50%)",
                            color: "white",
                            fontSize: "24px",
                            background: "rgba(0,0,0,0.7)",
                            padding: "20px",
                            borderRadius: "10px",
                        }}
                    >
                        Trigger Image Detected! Model Placeholder
                    </div>
                )}
            </div>
        </div>
    );
};

export default AR;

Sequelize ORM: Dynamically set database schema for sequelizeInstance (or repositories) at runtime?

For our SaaS API we use schema-based multitenancy, which means every customer (~tenant) has its own separate schema within the same (MySQL) database, without interfering with other customers. Each schema consists of the same underlying entity-model.

Everytime a new customer is registered to the system, a new isolated schema is automatically created within the db. This means, the schema is created at runtime and not known in advance. The customer’s schema is named according to the customer’s domain.

For every request that arrives at our API, we extract the user’s tenancy-affiliation from the JWT and determine which db-schema to use to perform the requested db-operations for this tenant.

After having established a connection to a (MySQL) database via Sequelize ORM (e.g. using createConnection), our only chance to set the schema for a db-operation is to resort to the QueryBuilder:

const projects = await sequelize.query(
select * from${tenantId}.projects where(“projexts.category = purchase

This means, we are forced to use the QueryBuilder as it does not seem to be possible to set the schema when working with the EntityManager API (or the Repository API).

However, we want/need to use these APIs, because they are much simpler to write, require less code and are also less error-prone, since they do not rely on writing queries “manually” employing a string-based syntax.

Question

In case of sequelize ORM, is it possible to somehow set the db-schema when working with the EntityManager or repositories?

Something like this?

// set schema when instantiating sequelize const sequelize = new Sequelize(MYSQL_DB, MYSQL_USER, MYSQL_PASSWD, { host: MYSQL_HOST, port: MYSQL_PORT, dialect: MYSQL_DIALECT, });

`// should find all matching “projects” entities within schema
const tenantDB = request.header.origin
const userData = await tenantDB.projects.findAll({ where: {category: ‘Purchase’}

// should find a matching “item” entity within schema using same sequelize
const itemData = tenantDB.items.findOne({ where: {id: 1}})`

Notes:

The db-schema needs to be set in a request-scoped way to avoid setting the schema for other requests, which may belong to other customers. Setting the schema for the whole connection is not an option.
We are aware that one could create a whole new connection and set the schema for this connection, but we want to reuse the existing connection. So simply creating a new connection to set the schema is not an option.

Is it possible to add a locale to Intl.DateTimeFormat?

I am building a multi-lingual website with the languages Dutch, English and Papiamentu (spoken on Curaçao and Bonaire). I can use Intl.DateTimeFormat with Dutch and English but Papiamentu seems to not be supported as I get everything back in English:

Intl.DateTimeFormat('en', { dateStyle: 'full' }).format(new Date());
// "Wednesday, December 11, 2024" <= correct

Intl.DateTimeFormat('nl', { dateStyle: 'full' }).format(new Date());
// "woensdag 11 december 2024" <= correct

Intl.DateTimeFormat('pap', { dateStyle: 'full' }).format(new Date());
// "Wednesday, December 11, 2024" <= not correct as this is in English, expected "djaweps, 11 di desèmber 2024"

Is there a way to extend the dictionary used by Intl to add support for locales that it doesn’t know? I’d like to do it without polyfills if possible.

Linux: How to enable the sound card?

I’ve used SoundCard Switch GNOME extension to disable sound card, but now I can’t enable it (using the same tool).

    _onToggle(menuItem, state) {
      if (state) {
        let cmd = ["pkexec", "tee", "/sys/bus/pci/rescan"];
        this._write_command(cmd);
      } else {
        let cmd = ["pkexec", "tee", "/sys/class/sound/card0/device/remove"];
        this._write_command(cmd);
      }

I tried command line:
sudo tee /sys/bus/pci/rescan <<<1 but no sound card is enabled.

How do I enable the sound card from command line?

How do i resolve a “Cannot read properties of undefined (reading ‘requestHandler’)”

So I am implementing Sentry on my Node project, but when I run it I am getting this error.

TypeError: Cannot read properties of undefined (reading ‘requestHandler’)
at file:///C:/Users/HP/Documents/sentry-test/app.js:16:25
at ModuleJob.run (node:internal/modules/esm/module_job:268:25)
at async onImport.tracePromise.proto (node:internal/modules/esm/loader:543:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:116:5)

Here is the code

import express from 'express';
import * as Sentry from '@sentry/node';

Sentry.init({
    dsn: 'https:my dsn',
    tracesSampleRate: 1.0,
});

const app = express();

app.use(Sentry.Handlers.requestHandler());

app.get('/', (req, res) => {
    res.send('Hello, Sentry!');
});

app.get('/error', (req, res) => {
    throw new Error('This is a test error for Sentry!');
});

app.use(Sentry.Handlers.errorHandler());

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});

I changed my code from using import to using const (commonJs Syntax). The issue still persists.

I tried to log the handlers object to verify using console.log(Sentry.Handlers); which returned undefined