cursor Hover issues when used along with cursor moving function

I am trying to create a custom mouse cursor where the body tag gets some classes applied depending upon the status of mouse cursor.
Like:

  1. cursor-moving: whenever the mouse is moved
  2. cursor-idle: whenever the mouse is idle
  3. cursor-hover: whenever the mouse is moved over an anchor or a button tag.

But this javascript code is not working when I try to hover over the link elements. I tried to do a console, and it shows cursor-hover is working, but very intermittently and that too for a tiny second.

Hint: I have also written a style which will change the background-color of body when this hover thing works.

const customCursor = document.querySelector(".cursor");
let isCursorMoving = false;
let cursorIdleTimeout;
let isCursorOverLink = false;

function updateCursor(event) {
  const x = event.clientX + "px";
  const y = event.clientY + "px";

  customCursor.style.setProperty("--cursor-left", x);
  customCursor.style.setProperty("--cursor-top", y);

  if (!isCursorMoving) {
    document.body.classList.add("cursor-moving");
    document.body.classList.remove("cursor-idle");
    clearTimeout(cursorIdleTimeout);
  }

  cursorIdleTimeout = setTimeout(() => {
    isCursorMoving = false;
    document.body.classList.remove("cursor-moving");
    document.body.classList.add("cursor-idle");
  }, 1000);
}

function handleLinkEnter(event) {
  if (event.target.tagName === "A" || event.target.tagName === "BUTTON") {
    document.body.classList.add("cursor-hover");
  }
}

function handleLinkLeave(event) {
  if (event.target.tagName === "A" || event.target.tagName === "BUTTON") {
    document.body.classList.remove("cursor-hover");
  }
}

document.addEventListener("mousemove", updateCursor);
document.addEventListener("mouseenter", handleLinkEnter);
document.addEventListener("mouseleave", handleLinkLeave);
* {
  box-sizing: border-box;
}

body {
  background: #3f3f3f;
}

:root {
  --cursor-size: 32px;
  --tail-size: 1px;
  --tail-gap: 48px;
  --tail-color: #111;
  --cursor-color: #fff;
}

.cursor {
  position: fixed;
  left: var(--cursor-left, 0);
  top: var(--cursor-top, 0);
  width: var(--cursor-width, var(--cursor-size));
  height: var(--cursor-height, var(--cursor-size));
  z-index: 999999;
}

.cursor::before,
.cursor::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  background: var(--cursor-color);
  transform: translate(-50%, -50%);
}

.cursor::before {
  width: 1px;
  height: var(--cursor-size);
}

.cursor::after {
  width: var(--cursor-size);
  height: 1px;
}

.cursor .tail {
  position: absolute;
  left: 0;
  top: 0;
  background: var(--tail-color);
  opacity: 0.6;
}

.cursor .tail::before {
  content: "";
  position: absolute;
  background: var(--tail-color);
}

.cursor .tail-x {
  width: 100vw;
  height: var(--tail-size);
  left: var(--tail-gap);
}

.cursor .tail-x::before {
  left: calc(-100vw - var(--tail-gap) - var(--tail-gap));
  right: 0;
  width: 100vw;
  height: var(--tail-size);
}

.cursor .tail-y {
  width: var(--tail-size);
  height: 100vh;
  top: var(--tail-gap);
}

.cursor .tail-y::before {
  top: calc(-100vw - var(--tail-gap) - var(--tail-gap));
  bottom: 0;
  height: 100vw;
  width: var(--tail-size);
}

body {
  display: grid;
  height: 100vh;
  width: 100vw;
  place-items: center;
}

body.cursor-hover {
  background: yellow;
}

body.cursor-hover a {
  color: #000;
}

a {
  display: inline-block;
  color: #fff;
  padding: 4px;
}
<div class="cursor">
  <span class="tail tail-x"></span>
  <span class="tail tail-y"></span>
</div>

<a href="#">Link</a>

VueJS nullish coalescing operator (??) error in v-calendar

I am getting “You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.” error

The full error:

error  in ./node_modules/v-calendar/dist/es/index.js

Module parse failed: Unexpected token (1889:19)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| const resolveEl = (target) => {
|   if (target == null)
>     return target ?? null;
|   if (document && isString_1(target))
|     return document.querySelector(target);

 @ ./src/main.js 13:0-35 15:0-65 27:12-21 29:12-25 30:30-38 31:32-42
 @ multi (webpack)-dev-server/client?http://192.168.88.134:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

My babel.config.js file

module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"],
  plugins: [
    "@babel/plugin-proposal-nullish-coalescing-operator",
    "@babel/plugin-proposal-optional-chaining",
  ],
};

My vue.config.js file

module.exports = {
  transpileDependencies: ["@gtm-support/vue-gtm", "v-calendar"],
  productionSourceMap: false,
  chainWebpack: (config) => {
    if (process.env.NODE_ENV === "development") {
      config.output
        .filename("[name].[hash].js")
        .chunkFilename("[name].[hash].js")
        .end();
    }
  },

I have installed necessary plugin with this command:

npm install --save-dev @babel/plugin-proposal-nullish-coalescing-operator @babel/plugin-proposal-optional-chaining

But it is still not working.

MongoDB Update Nested Object

I am trying to represent a grid structure within a MongoDB. I am having trouble updating a nested object. More specifically, the columns array located within the layouts rows row array element. I have created the following models:

layoutModel.js

const LayoutSchema = new mongoose.Schema({
    rows: {
        type : Array , "default" : []
    },
})

rowModel.js

const RowSchema = new mongoose.Schema({
    columns: {
        type : Array , "default" : []
    },


    user_id: {
        type: String,
        unique: false,
    },
    layout_id: {
        type: String,
        unique: false,
    }
})

columnModel.js

const ColumnSchema = new mongoose.Schema({
    column: {
        type : Array , "default" : []
    },

    user_id: {
        type: String,
        unique: false,
    },
    layout_id: {
        type: String,
        unique: false,
    }
})

I am able to find the layout associated with the current user, and then add a new row to the layout database object.

server.js

// database models
const Layout = require("./database/models/layout.js")
const User = require("./database/models/userModel.js")
const Row = require("./database/models/rowModel.js")
const Column = require("./database/models/columnModel.js")

app.post('/add-row', jsonParser, (req, res) => {
  User.findOne({ _id: req.body.profile_id })
    .then((user) => {
        const new_row = new Row({columns: [],}) //create new row database object
        new_row.save() //save object

        //find user's layout database object
        Layout.findOne({_id:user.layout_id}).then((layout) => {
          //found user's layout
          layout.rows = [new_row, ...layout.rows] //add new row to array of all the old rows
          layout.save() //save object
        })
    })
  res.send('Add row')
})

database example

However, when I try to add a new column to the row within the layouts rows array it does not update in the database. I am not sure why.

app.post('/add-column', jsonParser, (req, res) => {
  User.findOne({ _id: req.body.profile_id })
  .then((user) => {
    //user is logged in so get the users layout
    Layout.findOne({_id:user.layout_id})
      .then((layout) => {
         //found layout
         for(let row in layout.rows){  
          let row_id = layout.rows[row]._id.toString()  //current row's id
          if(row_id === req.body.var_row_id){           //found row to add column to
           const new_column = new Column({column: [],}) //create new column database object
           new_column.save()
           layout.rows[row].columns = [...layout.rows[row].columns, new_column] //add new column to array of all the old columns
           layout.save()
          }
         }
     })
     
  })
})

Any advice is greatly appreciated.

I want to add Upload Image option in my addProducts.html page

I want to Add Upload Image in my input form , input form is taking product Name, Product Description, Product Model , PRODUCT Price where i want to add one thing more upload image option so that we can choose desired image to add data of product

/ / addProduct.html page code / /

Products

<link rel="stylesheet" href="css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Luckiest+Guy&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/all.min.css">
<link rel="stylesheet" href="css/myStyle.css">




<!--header section-->

    
        
            
                <a href="index.html">Sneakers</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse"
                    data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                    
                

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item">
                            <a class="nav-link activeLink" href="index.html">Home</a>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button"
                                data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                Products
                            </a>
                            <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                                <a class="dropdown-item" href="addProduct.html">Add Product</a>
                            </div>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="contacts.html">Contact</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <!--add product section-->
        <div class="col-md-8">
            <!--alert to tell products added-->
            <div id="successProductAlert" class="alert alert-warning" role="alert">
                Product added successfully!
            </div>
            <form>
                <div class="form-group">
                    <label for="productName">Product Name</label>
                    <input onkeyup="disableBtn()" id="productName" type="text" class="form-control">
                </div>
                <div class="form-group">
                    <label for="productText">Product Description</label>
                    <textarea onkeyup="disableBtn()" id="productDesc" class="form-control" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label for="productModel">Product Model</label>
                    <input onkeyup="disableBtn()" id="productModel" type="text" class="form-control">
                </div>
                <div class="form-group">
                    <label for="productPrice">Product Price</label>
                    <input onkeyup="disableBtn()" id="productPrice" type="text" class="form-control">
                </div>
            </form>
            <button id="productBtn" type="submit" class="btn btn-primary">Add Product</button>
        </div>
        <!--end product section-->
    </div>
</section>
<!--END header section-->

<!-- view product section-->
<section class="my-5">
    <div class="container">
        <h2 id="productHeadline">Our Products</h2>
        <div id="searchItem" class="w-50 my-4">
            <input type="text" placeholder="Search" class="form-control" id="mySearchInp">
            <i class="fas fa-lg fa-search mySearch"></i>
        </div>
        <div class="row" id="dataRow">
        </div>
    </div>
</section>
<!--end of view product-->

<!--scripts-->
<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/myJs.js"></script>

/// I want that when I upload Image and fill the form data and after Click on Add Product Button for Adding Product my description and desired Image so that my description and desired image will show like the image attached but image should be that one which i uploaded . i have tried alot but not solve the problem . if someone understand the logic please provide the code for that.

(https://i.stack.imgur.com/BM4yI.jpg)

ESLint not checking Typescript errors in VueJS 2 class-based components

This is my eslintrc.js:

module.exports = {
  root: true,
  env: {
    node: true
  },
  plugins: ['@typescript-eslint', 'prettier'],
  extends: [
    'plugin:vue/essential',
    'eslint:recommended',
    '@vue/typescript',
    '@vue/typescript/recommended',
    '@vue/prettier',
    '@vue/prettier/@typescript-eslint'
  ],
  parserOptions: {
    ecmaVersion: 2020
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    quotes: ['error', 'single', 'avoid-escape'],
    semi: ['error', 'always'],
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/no-non-null-assertion': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    'prettier/prettier': 'error',
    'vue/valid-v-slot': [
      'error',
      {
        allowModifiers: true
      }
    ]
  },
  overrides: [
    {
      files: ['**/tests/unit/**/*.spec.{j,t}s?(x)'],
      env: {
        jest: true
      }
    }
  ]
};

I start it via vue-cli-service lint. Typescript errors in Vue templates get picked up but ones in the classes don’t. Prettier errors all get picked up, regardless where. My Intellij IDEA also picks up Typescript errors in the components, so I assume my tsconfig is configured correctly:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules",
    "tests/cypress/**/*"
  ]
}

I also do have these dev dependencies (among others, ignored here):

    "@typescript-eslint/eslint-plugin": "^4.18.0",
    "@typescript-eslint/parser": "^4.18.0",
    "@vue/cli-plugin-babel": "^5.0.7",
    "@vue/cli-plugin-eslint": "^5.0.7",
    "@vue/cli-plugin-typescript": "^5.0.7",
    "@vue/cli-service": "^5.0.7",
    "@vue/eslint-config-prettier": "^6.0.0",
    "@vue/eslint-config-typescript": "^7.0.0",
    "eslint": "^7.32.0",
    "eslint-loader": "^4.0.2",
    "eslint-plugin-prettier": "^4.2.1",
    "eslint-plugin-vue": "^7.20.0",
    "prettier": "^2.7.1",
    "typescript": "~4.4.4",
    "vue-cli-plugin-vuetify": "^2.0.7",
    "vue-eslint-parser": "^7.11.0",
    "vue-template-compiler": "2.7.10",

But then what might be the problem? Is there an example ESLint setup for Vue2 typescript based classes somewhere? Nowadays I can only find Vue 3 references

Javascript set checkbox checked value to false [closed]

I’m having an issue with Javascript. I’m trying to limit the number of checked checkbox to 5. I have a Javascript script that shows me the alert I ask to show but the still put the checkbox on checked.

To do so I’m using this Javascript script:

function change(_this) {
   if ($('input[type=checkbox]:checked').length > 5) {
      alert("allowed only 5");
      this.checked = false;
   }
}

I’ve tried also

$(this).prop('checked', false);

And my checkboxes are the classical one

<input type="checkbox" name="memberName" value="Name1" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name2" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name3" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name4" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name5" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name6" onchange="change(this)">

What can cause this issue?

Fetching data from Firestore in React

I am creating a chat application in React using Firebase. I am focusing on Group chats mostly. I am not able to fetch the messages from Firestore. I am able to Post the messages to db but not retrieve it. Here’s the Chat.js component code.

onst Chat = ({ groupId }) => {
  const [messages, setMessages] = useState([]);
  const scroll = useRef();
  const [selectedGroupId, setSelectedGroupId] = useState(null);

  const chatGroupsData = [
    { id: 'Group1', name: 'Group1' },
    { id: 'Group2', name: 'Group2' },
  ];

  const handleGroupSelection = (selectedGroupId) => {
    setSelectedGroupId(selectedGroupId);
  };

  useEffect(() => {
  if (groupId) { 
    console.log("Fetching messages for groupId:", groupId);
    const messagesCollectionRef = collection(db, 'ChatGroups', groupId, 'Messages');
    const q = query(messagesCollectionRef, orderBy('timestamp'));
    const unsubscribe = onSnapshot(q, (querySnapshot) => {
      let messages = [];
      querySnapshot.forEach((doc) => {
        messages.push({ ...doc.data(), id: doc.id, groupId });
      });
      setMessages(messages);
    }, (error) => {
      console.error('Error fetching messages:', error);
    });
    
    return () => unsubscribe();
  }
}, [groupId]);

console.log("Messages:", messages);

  return (
    <div className="flex h-screen">
      {/* Chat List (Left Side) */}
      <div className={style.chatList}>
        {/* Chat list content */}
        <Sidebar chatGroups={chatGroupsData} onSelectGroup={handleGroupSelection} />
      </div>
      
      {/* Chat Interface (Right Side) */}
      <div className={style.chatInterface}>
        <div className={style.chatHeader}>
        <h2 className="text-xl font-semibold">Mental Health</h2> {/* Adjust the title */}
        </div>
        {/* Chat Messages */}
        <main className={style.main}>
          {examplemessages &&
            examplemessages
            .filter((message) => message.groupId === selectedGroupId) // Filter messages by groupId
            .map((message) => (
            <Message key={message.id} message={message} groupId={selectedGroupId} />
          ))}
        </main>
        {/* Send Message Component */}
        <SendMessage scroll={scroll} groupId={selectedGroupId} />
      </div>

      {/* Scroll Indicator */}
      <span ref={scroll}></span>
      
    </div>
    
  );
};

All the necessary imports are made. I’ve cross checked with all other components are working fine.

I’ve tried hardcoding the sample messages in the component itself which are successfully rendered. Also the console.log("Messages:", messages); returns and empty array.

React Query and Localstorage

I’m new to react query I’m getting user data after Login and store it in a localstorage hook, after I navigate to Page.tsx I get the data but when I use invalidateQuery somewhere else it doesn’t work and the data still not updated

useGetParcels.tsx

import { getBikerParcels } from "@/models/bikerModels";
import { getSenderParcels } from "@/models/senderModels";
import { User } from "@/types/dataTypes";
import { useQuery } from "@tanstack/react-query";

const useGetParcels = (userData: User) => {
  return useQuery(
    ["user-parcels", userData?.id],
    async () => {
      let res;
      if (userData.type === "biker") {
        res = await getBikerParcels(userData?.id);
      } else if (userData?.type === "sender") {
        res = await getSenderParcels(userData?.id);
      }
      const parcels = res.data.parcels;
      return parcels;
    },
    {
      staleTime: 1000 * 60 * 100,
      enabled: userData?.id?.length > 0,
    }
  );
};

export default useGetParcels;

Page.tsx

"use client";

import React from "react";
import SenderTable from "./senderTable";
import useLocalStorage from "@/hooks/useLocalStorage";
import BikerTable from "./bikerTable";
import useGetParcels from "@/hooks/queries/useGetParcels";
import Loading from "@/components/Loading";
import Nav from "@/components/Nav";

export default function Dashboard() {
  const [userData] = useLocalStorage("userData", null);

  const { data: parcels, isLoading, error } = useGetParcels(userData);

  if (isLoading) {
    return <Loading />;
  }

  return (
    <>
      {userData?.type === "sender" && <Nav />}
      {userData?.type === "sender" ? (
        <SenderTable parcels={parcels} />
      ) : (
        <BikerTable parcels={parcels} />
      )}
    </>
  );
}

tried removing the optional chaining and it worked but I get TypeError: Cannot read properties of null (reading 'id') Error

Complation failed when I try to use ‘@gradio/client’ API in an angular-based ionic app

When I try to use gradio/client in a simple blank ionic app (angular), compilation fail and return this error message:

[ng] node:buffer - Error: Module build failed: UnhandledSchemeError: Reading from "node:buffer" is not handled by plugins (Unhandled scheme).
[ng] Webpack supports "data:" and "file:" URIs by default.
[ng] You may need an additional plugin to handle "node:" URIs.
[ng]
[ng]
[ng] × Failed to compile.

Any suggestion?

I’ve already tried to downgrade node-fetch as suggested in other answers

Unable to return function and usestate from reusable component

I have a react app that allows multipule file uploads to fire base. I am trying to create the component to be resusable however I have run into an issue where I am unable to return the function and also the usestate araay.


const useUploader = (data, foldername) => {
  const [upLoadcomplete, setuploacomplete] = useState()

  const uploadFiles = async () => {
    // function doing things.. one of which is to setuploacomplete depending on outcome.  
    }
  return uploadFiles
}
export default useUploader

On another jsx there is a button which uses an on submit to call the custom hook, I would like for that hook to carry out the function, but also be able to update another div with the status if complete or now.. however I can’t seem to figure out how to do it. I was trying useEffects, but this caused the function to run before the submit button was pressed.. which isn’t want I wanted!

Any help would be great!!

how write a json sync with extra-fs

I have a problem when I write different values with extra-fs.
I’m doing a casino game test on 20 simultaneous balances, except that it doesn’t seem to really work when I write it in my json.

So what happens is that as soon as I run my program, it executes 20 files, each with a different betting tactic, and as soon as I win or lose, it writes them to my json.
The only drawback is that as soon as I run it, it doesn’t work properly.
it doesn’t write well and also doesn’t change all the values at the same time.

Here’s my program, which writes 20 values simultaneously:

 async updateJson(mainValue, newValue) {
        if (!this.getJson) return ":(";

        try {
            const data = await fs.readFile(this.getJson, 'utf8');
            const balanceData = JSON.parse(data);
            balanceData[mainValue] = newValue;
      
            await fs.writeFile(this.getJson, JSON.stringify(balanceData, null, 2), 'utf8');
        } catch (err) {
            console.error("Error:", err);
        }
}

here’s the json before execution:

{
  "Balance1": 800,
  "Balance2": 800,
  "Balance3": 800,
  "Balance4": 800,
  "Balance5": 800,
  "Balance6": 800,
  "Balance7": 800,
  "Balance8": 800,
  "Balance9": 800,
  "Balance10": 800,
  "Balance11": 800,
  "Balance12": 800,
  "Balance13": 800,
  "Balance14": 800,
  "Balance15": 800,
  "Balance16": 800,
  "Balance17": 800,
  "Balance18": 800,
  "Balance19": 800,
  "Balance20": 800
}

after execution:

{
  "Balance1": 800,
  "Balance2": 800,
  "Balance3": 800,
  "Balance4": 800,
  "Balance5": 800,
  "Balance6": 800,
  "Balance7": 800,
  "Balance8": 800,
  "Balance9": 800.05,
  "Balance10": 800.1,
  "Balance11": 800,
  "Balance12": 800,
  "Balance13": 800,
  "Balance14": 800,
  "Balance15": 800,
  "Balance16": 800,
  "Balance17": 800,
  "Balance18": 800,
  "Balance19": 800,
  "Balance20": 800
}00
}

and my error:

Error: SyntaxError: ./Balance.json: Unexpected number in JSON at position 398
    at JSON.parse (<anonymous>)
    at Object.readFileSync (C:Users#DesktopSimulatorBetProjectnode_modulesjsonfileindex.js:52:17)
    at Bet.retrieveData (C:Users#DesktopSimulatorBetProjectbloCasinobetmainBet.js:12:36)
    at Americaine.bettingTactics (C:Users#DesktopSimulatorBetProjectbloCasinobetcrashamericaine.js:21:46)
    at Bet.betAlgo (C:Users#DesktopSimulatorBetProjectbloCasinobetmainBet.js:61:33)
    at startBetting (C:Users#DesktopSimulatorBetProjecttest.js:67:16)
    at startScript (C:Users#DesktopSimulatorBetProjecttest.js:239:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async C:Users#DesktopSimulatorBetProjecttest.js:37:17
Error: SyntaxError: ./Balance.json: Unexpected number in JSON at position 398
    at JSON.parse (<anonymous>)
    at Object.readFileSync (C:Users#DesktopSimulatorBetProjectnode_modulesjsonfileindex.js:52:17)
    at Bet.retrieveData (C:Users#DesktopSimulatorBetProjecttestbetmainBet.js:12:36)
    at contreAlembert.bettingTactics (C:Users#DesktopSimulatorBetProjecttestbetcrashcontreAlembert.js:15:46)       
    at Bet.betAlgo (C:Users#DesktopSimulatorBetProjecttestbetmainBet.js:61:33)
    at startBetting (C:Users#DesktopSimulatorBetProjecttest.js:77:16)
    at startScript (C:Users#DesktopSimulatorBetProjecttest.js:239:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async C:Users#DesktopSimulatorBetProjecttest.js:37:17...

How to add a transparent image on a existing image with opencv in Node.js?

I am trying to add a transparent image on an existing image

I tried below:

import cv from "@u4/opencv4nodejs";

const image = await cv.imreadAsync(SCREENSHOT_PATH); // jpg
const grid = await cv.imreadAsync(GRID_IMAGE_PATH); // png

const roi = image.getRegion(new cv.Rect(520, 165, 561, 564));

await grid.copyToAsync(roi);

await cv.imwriteAsync(OUTPUT_PATH, image);

While this adds the image, it does not preserve transparency

Angular 16 standalone app, not sure how to use services. Error: “I18nService” type, must be a standalone component / directive / pipe or an NgModule

I’m creating a standalone app from scratch, I don’t have an ngModule.

I’m creating a translation service, and a pipe to use it.

testing it on app.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { I18nPipe } from './pipes/i18n.pipe';
import { I18nService } from './services/i18n.service';

@Component({
    selector: 'ct-v4',
    standalone: true,
    imports: [CommonModule, RouterOutlet, I18nPipe],
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
    title = 'ct-v4';
    constructor(private i18nService: I18nService) {}

    ngOnInit(): void {
        this.i18nService.initLanguage('en');
    }
}

My i18n service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class I18nService {
    private translations: { [key: string]: string } = {};

    constructor(private http: HttpClient) {}

    initLanguage(lang: string, isFallback = false): void {
        this.http.get(`/langs/${lang}.json`).subscribe({
            next: (data: any) => {
                this.translations = data;
            },
            error: (error) => {
                console.error(`Language file for ${lang} not found.`);
                if (!isFallback) {
                    console.info('Falling back to default language: en');
                    this.initLanguage('en', true);
                } else {
                    console.error('Even the default language "en" is missing. Stopping language initialization.');
                }
            }
        });
    }

    i18n(key: string): string {
        return this.translations[key] || key;
    }
}

The pipe itself is not complaining because it’s also standalone,
I get this error:

NullInjectorError: R3InjectorError(Standalone[AppComponent])[I18nService -> I18nService -> HttpClient -> HttpClient]: 
      NullInjectorError: No provider for HttpClient!

I’m not finding examples online on how to use services in standalone angular apps

Any ideas?

Why all the cards get activated when i click the active button of a specific card?

When I click the active button of a specific card to make it active, all of the cards get activated. Here I used the variable className and I set it manually to the value : “card mb-3 border-3”, and I want when clicking the button active, the className should have a border of the value : “border-info”, but I still get all the cards activated although I used the parameter id to differentiate between them. Please how to solve this problem?

function GridMod({articles, updateArticleList}) {

    const [className, setClassName] = useState("card mb-3 border-3");

    const Status = (id) => {
        let classname = className;
        
        if(articles.filter((article) => article.id === id))
        {
            if(classname == "card mb-3 border-3"){
                setClassName("card mb-3 border-info border-3")
            }
            console.log("activated!")
        }
    };`

    const Remove = async (id) => {
        try {
            await axios.delete(`http://localhost:3001/articles/${id}`);
            const updatedArticles = articles.filter((article) => article.id !== id);
            updateArticleList(updatedArticles);
        } catch (error) {
            console.error(error);
        }
    }

    return (
        <div className='container'>
                <div className="container">
                <div className="row">
                    {
                        articles.map((article)=>(    
                        <div className="col-sm" >
                        <div className={className} key={article.id}  style={{width:"18rem"}}>
                            <img className="card-img-top" src={article.image} alt="Card image cap"style={{height:"250px" }} />
                            <div className="card-body">
                            <h5 className="card-title">{article.title}</h5>
                            <p className="card-text">{article.description}</p>
                            <Link to={`/blog/edit/${article.id}`} className='btn btn-primary'>
                            <AiFillAlipayCircle/> Edit blog
                            </Link>  &nbsp;&nbsp;
                            <button onClick={() =>Remove(article.id)}>Delete</button>  &nbsp;&nbsp;   
                            <button onClick={()=>Status(article.id)}>Active</button>
                            </div>
                            </div>
                        </div>
                        ))
                    }
                </div>
                </div>
        </div>
    );
}
export default GridMod;