Jest: Test suite failed to run…Cannot find module ‘../build/Release/canvas.node’

Jest is not able to find the package canvas in dependencies even though it is present.yarn run test is failing with the following error.

packages/first/src/layouts/EventsTable.spec.tsx
  ● Test suite failed to run

    Cannot find module '../build/Release/canvas.node'
    Require stack:
    - /Users/abc/Documents/monorepo/node_modules/canvas/lib/bindings.js
    - /Users/abc/Documents/monorepo/node_modules/canvas/lib/canvas.js
    - /Users/abc/Documents/monorepo/node_modules/canvas/index.js
    - /Users/abc/Documents/monorepo/node_modules/jsdom/lib/jsdom/utils.js
    - /Users/abc/Documents/monorepo/node_modules/jsdom/lib/jsdom/living/events/MouseEvent-impl.js
    - /Users/abc/Documents/monorepo/node_modules/jsdom/lib/jsdom/living/generated/MouseEvent.js
    - /Users/abc/Documents/monorepo/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js
    - /Users/abc/Documents/monorepo/node_modules/jsdom/lib/jsdom/living/aborting/AbortSignal-impl.js
    - /Users/abc/Documents/monorepo/node_modules/jsdom/lib/jsdom/living/generated/AbortSignal.js
    - /Users/abc/Documents/monorepo/node_modules/jsdom/lib/jsdom/living/generated/AddEventListenerOptions.js
......

Canvas is installed and present in the dependency list.

yarn why canvas 

└─ pdfjs-dist@npm:3.11.174
   └─ canvas@npm:2.11.2 (via npm:^2.11.2)

Tried removing all packages rm -rf node_modules and reinstalled, the problem still persists.

Node version – v18.16.1
yarn version – v3.2.3

Why does DOMException constructor directly derive from Function.prototype but DOMException.prototype directly from Error.prototype?

In other words, why isn’t DOMException like AggregateError, EvalError, etc?

devtools evaluation screenshot
Both expressions evaluate to true:

Object.getPrototypeOf(DOMException) === Function.prototype
Object.getPrototypeOf(DOMException.prototype) === Error.prototype

I used to think the following generalization has no counterexamples:

If

  • X and Y are constructor functions, and
  • Y is not the Object() constructor, and
  • X.prototype has Y.prototype as its [[Prototype]] object
    Then
  • X has Y as its [[Prototype]] object

For example, the above generalization holds for the following X,Y pairs

  1. HTMLElement, Element
  2. AggregateError, Error
  3. AsyncFunction, Function
  4. Node, EventTarget
  5. Element, Node
  6. RTCError, DOMException

The only case I know of in which the generalization fails is when X = DOMException and Y = Error.

Is there a deeper reason why the DOMException constructor itself cannot have the Error constructor as its [[Prototype]]?

Problems generating a variable in google TAG manager

I’m trying to generate a custom JavasCript varialbe in Google TAG Manager but I don’t know why its not working.

If I INSPECT the web and look for the variable it works fine. .

dataLayer[index]["gtm.element"][0].value

— >>

But when I write the code in Custon Javascript variable in google tag managet it don’t return anything

function (){
   for (var i = 0; i < window.dataLayer.length; i++) {
      if (window.dataLayer[i].event === "gtm.formSubmit") {
        index = i;
      }
   }
     //return dataLayer[index];
     return dataLayer[index]["gtm.element"][0].value;
}

If I run the first option of return (return dataLayer[index];) it returns the index correctly

I need to know what I am doing wrong

Autocomplete MUI is warning that I need a key for each child passed

I am using the Autocomplete component from MUI and am running into an issue where I am getting this warning:
Warning: Each child in a list should have a unique “key” prop.

I’ve already added keys to both renderOption and renderTags, but am still getting the warning message.

It is not breaking my code, but I like to keep warnings down to a minimum because usually they do start breaking things in production.

Please let me know any suggestions you have.

I’ve added keys to both renderOption and renderTags below and still get the error.

I tried the checked solution and the one below it from
this question but it did not seem to make a difference.

Here is my code:

<Autocomplete
 multiple
 limitTags={2}
 options={allMeetings}
 getOptionLabel={(option)=>option.title}
 renderOption={(props, option)=>{
     const { key, ...restProps} = props;
     return (
         <li {...restProps} key={option.meetingId+key} style={{flexDirection: "column",         justifyContent: "flex-start"}}> 
         <Typography variant='subtitle1'>{option.title}</Typography>
         <Typography variant='caption'>{option.date}&nbsp;-&nbsp;{option.startTime}</Typography>
         </li>)
         }}
 renderTags={(tagValue, getTagProps)=> {
    return tagValue.map((option, index)=>{
         const {key, ...restProps} = getTagProps({index});
          return <Chip {...restProps} key={key} label={option.title} />
     })
  }}
 renderInput={(params, index)=> {
     return <TextField 
            {...params}
            label="Meetings"/>
  }}/>

allMeetings is an object i am passing that has title, meetingId, start and endtime, and date.

key that I am getting from props is the title of the meeting object

in my db I am sure that meetingIds are unique and not duplicating.

For reference I’ve attached what logs in the console when I add a console.log(option) within renderOption. meetingId starts at meeting and continues as meeting-1, meeting-2, etc.
meeting object that is being passed through autocomplete

Regex validation error in ‘formvalidation.io’ [duplicate]

I’ve post this question also on the github channel of the library but it looks no one answer question’s there.
So I try to find an answer here.

I’m trying to validate a password with a RegEx, and a second password field to verify that it’s the same as the first.
The Regex works correctly until a first succesfull check, then start to return a failure regex validation every 2 form validation.

This is the formvalidation options:

       var fl = FormValidation.formValidation(frmp, {
        fields: {
            'password': {
                validators: {
                    notEmpty: {
                        message: "Field Required"
                    },
                    regexp: {
                        regexp: /^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[_.,-+*!#@?])([a-zA-Z0-9_.,-+*!#@?]{8,25})$/g,
                        message: "Password should be between 8 and 25 char, 1 uppercase, 1 number and 1 _.,-+*!#@"
                    }
                },
            },
            'rpassword': {
                validators: {
                    notEmpty: {
                        message: "Field Required"
                    },
                    identical: {
                        compare: function () {
                            return frmp.querySelector('[name="password"]').value;
                        },
                        message: "Passwords don't match"
                    }
                },
            },
        },
        plugins: {
            trigger: new FormValidation.plugins.Trigger,
            bootstrap: new FormValidation.plugins.Bootstrap5(),
            excluded: new FormValidation.plugins.Excluded
        }
    })

Please take a look at this example on Codepen:

Codepen Example

Fill in the first field with a password that respects the RegEx rule and validate the field, then contiinue typing in the field to start the form validation. The RegEx rule generates the error alternately, once yes and once no, even if the field contains a password that respects the RegEx rule

How can I code a cooldown to a key press?

In my game, there is a “boost” option that pushs the player forward when they press Left Shift.
The problem is you can spam the button and go flying across the map.
To resolve this issue I want to add a small cooldown that will give the player good speed, but also won’t let the player exploit the feature by speeding across the entire map in 5 seconds.

I have tried looking up how to fix the issue but nothing helped because the code was in something like c++ or python.

Here is the code for my movement:

function Input() {
    document.addEventListener('keydown', (event) => {
    var name = event.key;
    var code = event.code;
    if (code == "ArrowRight" || code == "KeyD") {
        velX+= 5
    }
    if (code == "ArrowDown" || code == "KeyS") {
        velY+= 5
    }
    if (code == "ArrowUp" || code == "KeyW") {
        velY-= 5
    }
    if (code == "ArrowLeft" || code == "KeyA") {
        velX-= 5
        
    }
    if (code == "ShiftLeft") {
        velX *= 2
        velY *= 2
    }
    

    }, false);
}

Quill parse and replace

After experimenting a lot with contenteditable elements, I finally chosed Quill to create a rich text message box on a chat app, because it is correctly handling selection, which appears to be a mess when dealing directly with a contenteditable element.

In my experiments I used to parse the innerHTML and replace some strings by their emoji unicode counterpart (eg: '<3': '❤️'), and used Autolinker library to replace found links by a link tag in my editable element.

google.com --> <a href="https://www.google.com">google.com</a>

I want to avoid Quill toolbar and replace automatically emojis and links.

So, I guess I have to replace editor’s content at some place…

I’m really new to Quill, but I understand that it is working with a specific internal model called deltas, that allows operational transform (correct me if I’m wrong).

This assumption done, how would I check/parse these deltas and replace specific content in it in a way that preserves selection and caret position?

References:

https://github.com/nadar/quill-delta-parser

Scrollbar of datatable scroll too much

The scrollbar of my table scrolls too much when I press arrow down or up, for example: enter image description here

Is it possible to change the amount of pixel of scrollbar move ?

I use scrollY: 21.1rem for the scrollbar, but I see something strange here:
enter image description here
enter image description here
enter image description here

That’s what I see when my table scroll, is it normal?

Apollo GraphQL detect subscription started

I use graphql-ws to subscribe to GraphQL events. I use Observable interface to listen to the events. using error callback we can detect that subscription is failed to start, But there is no way to detect that it’s successfully started

next happens when we get an event, But I would like to wrap the Observable with a Promise and await for it to start subscription

And while the promise is not resolved, I want to show a progress bar. I can reject the promise in the error but I couldn’t find anyway to resolve it when server returns response to the subscription request

function toObservable(operation) {
  return new Observable((observer) =>
    client.subscribe(operation, {
      next: (data) => observer.next(data),
      error: (err) => observer.error(err),
      complete: () => observer.complete(),
    }),
  );
}

Why webpack is compressing my bundle by default

In the company Im currently working for there is a react app that uses webpack 5.
The webpack config file is like this:

const HtmlWebpackPlugin = require("html-webpack-plugin");
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");
const path = require("path");
const deps = require("./package.json").dependencies;
const dotenv = require("dotenv").config();

module.exports = (env = {}) => {
  const mode = env.NODE_ENV === "prod" ? "production" : "development";

  return {
    entry: "./src/index",
    mode: mode,
    devtool: mode === "production" ? false : "source-map",
    devServer: {
      static: path.join(__dirname, "dist"),
      port: 3000,
      hot: true,
      historyApiFallback: true,
      client: {
        overlay: false,
      },
    },
    resolve: {
      extensions: ['.tsx', '.ts', '.js'], 
    },
    output: {
      publicPath: "/",
    },
    module: {
      rules: [
        {
          test: /.tsx?$/,  // TypeScript loader
          exclude: /node_modules/,
          use: 'ts-loader',
        },
        { test: /.m?js/, type: "javascript/auto" },
        {
          test: /.m?js/,
          resolve: {
            fullySpecified: false,
          },
        },
        {
          test: /.m?js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env", "@babel/preset-react"],
              plugins: [
                "@babel/plugin-proposal-class-properties",
                "@babel/plugin-transform-async-to-generator",
                "@babel/plugin-syntax-jsx",
                "@babel/plugin-syntax-dynamic-import",
              ],
            },
          },
        },
        {
          test: /.scss$/,
          use: [
            mode !== "production"
              ? "style-loader"
              : MiniCssExtractPlugin.loader,
            "css-loader",
            "sass-loader",
          ],
        },
        {
          test: /.css$/,
          use: [
            mode !== "production"
              ? "style-loader"
              : MiniCssExtractPlugin.loader,
            "css-loader",
          ],
        },
        {
          test: /.(png|svg|jpg|gif|ico)$/,
          use: ["file-loader"],
        },
        {
          test: /.(woff|woff2|eot|ttf|otf)$/,
          use: [
            {
              loader: "file-loader",
            },
          ],
        },
        {
          test: /.json$/,
          loader: "json-loader",
        },
        {
          test: /.txt$/i,
          use: "raw-loader",
        },
      ],
    },
    plugins: [
      new ModuleFederationPlugin({
        name: "mainApp",
        library: { type: "var", name: "mainApp" },
        remotes: {
          linkManagement: "linkManagement",
        },
        shared: {
          "react-router-dom": {
            singleton: true,
          },
          "react-dom": {
            singleton: true,
          },
          react: {
            requiredVersion: deps.react,
            singleton: true,
          },
          "component-lib": {
            singleton: true,
          },
        },
      }),
      new HtmlWebpackPlugin({
        template: "./public/index.html",
      }),
      new MiniCssExtractPlugin({
        filename: "[name].css",
        chunkFilename: "[id].css",
      }),
      new webpack.DefinePlugin({
        VERSION: JSON.stringify("3.0.67"),
        ENV: JSON.stringify(env.NODE_ENV),
        AUTH0_CONFIG_DOMAIN: JSON.stringify(process.env.AUTH0_CONFIG_DOMAIN),
        //some other env vars here
      }),
    ],
  };
};

The app is rather slow so I thought about compressing the bundle using gzip. Before doing that I wanted to see how much space and how long does it take to fetch the bundle. When I build the app I see the /dist directory is created and there is a file called main.js (among others). When I run the app I go to localhost:3000 and I see in the network request that main.js file being fetched. However, I already see this in the Response Headers

Content-Encoding: gzip

I see no files that end in .gz in the /dist directory. Why is this main.js app being gzipped by default?

In the docs it specically says that if you want to compress you need to install a plugin

https://webpack.js.org/plugins/compression-webpack-plugin/

If I go ahead and install the plugin and copy the code provided by the docs I can successfully see the files ending in .gz in my /dist directory. However, when I go to localhost:3000 the manin.js file has the same size and takes the same time as before.

Am I missing something?

Prevent dedentation of template literals

The Problem

I am defining a template literal in JavaScript that is used to store python code.

Here is the MRE:

const execTemplate = python_code = """${formattedCode}
"""

where formattedCode can be any python code, for example:

def fibonacci(n):
    fib_sequence = [0, 1]
    while len(fib_sequence) < n:
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    return fib_sequence

first_20_fib = fibonacci(20)
print(first_20_fib)

Here’s what would happen if the code above was executed:

def fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence

# Generate the first 20 Fibonacci numbers
first_20_fib = fibonacci(20)
print(first_20_fib)

Research

I have tried both inserting the variable directly as shown, but I have also tried the replace() method, which does not solve the problem: const executableString = execTemplate.replace("%CODE%", formattedCode.trim()); where %CODE% is a placeholder in execTemplate.

Why is this?

Is there a more efficient way to code mousepressed() function?

I am trying to code a snooker game in JavaScript with only using the libraries: p5.min.js, p5.sound.min.js and matter.js.

Here is my code:

function mousePressed() {
 var force = 1000; 
 var forceX = (cueBall.position.x-mouseX)/force;
 var forceY = (cueBall.position.y- mouseY)/force;
 var magnitude = Math.sqrt(forceX * forceX + forceY * forceY);
 if (magnitude > 1) {
    var scale = 1 / magnitude;
    forceX *= scale;
    forceY *= scale;
 }    

 var appliedForce = {x:forceX,y:forceY};
 print(forceX,forceY);
 Body.applyForce(cueBall,{x:cueBall.position.x,y:cueBall.position.y},appliedForce);
}

This is to meant to apply a force on the cue ball by clicking on the mouse.

I am wondering if there a better way to apply the force and also limit the force on the cue ball?

Javascript: Drag’n’drop starts with not-allowed cursor at the droptarget place: instantly not-allowed cursor flickers at the start of dragging

Drag’n’drop starts with not-allowed cursor at the droptarget place: instantly not-allowed cursor flickers at the start of dragging.

Please try this code and try dragging the white div:

<div id="droptarget">
  <div id="draggable" draggable="true">This div is draggable</div>
</div>


<style>
#draggable {
  text-align: center;
  background: white;
  height: 200px;
}

#droptarget {
  width: 500px;
  height: 500px;
  background: blueviolet;
  margin: 10px;
  padding: 20px;
}
</style>


<script>
const target = document.getElementById("droptarget")
target.addEventListener("dragover", (event) => {
  event.preventDefault()
})
target.addEventListener("dragenter", (event) => {
  event.preventDefault()
})
</script>

The not-allowed cursor should not be displayed, but it is displayed.

React Native: Issue with Fetch API – Unable to Retrieve Data from Server

I’m facing an issue with fetching data from a server in my React Native project. I’ve been using the Fetch API to make a simple GET request, but I’m unable to retrieve the data. Here’s a snippet of my code:

import React, { useEffect } from 'react';

export default function MyComponent() {
  useEffect(() => {
    fetchData();
  }, []);

  async function fetchData() {
    try {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      console.log('Data:', data);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  }

  return (
    // My component JSX here
  );
}

I’ve confirmed that the API endpoint is accessible and returns valid JSON when accessed through a browser or tools like Postman. However, when I run this code in my React Native app, the data variable remains undefined, and I don’t see any errors in the console.

Could someone please review my code and suggest potential reasons why the Fetch API might not be working as expected in a React Native environment? Any guidance or troubleshooting tips would be greatly appreciated. Thank you!

I am looking for models and examples of this application that will help me solve this exercise: [closed]

Project idea: “Secure Bank”
Problem: Securing financial transactions and sensitive banking information is an ongoing concern for both banks and customers. “SecureBank” is an application aimed at improving the security and convenience of online banking.
Functionalities:

  1. Register and Login: Users can create an account and log in securely with: Use his details via message biometric data (such as fingerprint or facial recognition) for extra security. Message
  2. Transactions and Payments: Customers can manage accounts, transfer money to other accounts, view account statements and set up automatic payments.
  3. Security features: The app may include advanced security features such as fraud detection, two-step verification, and suspicious activity notifications.
    3-SecurityLog : Message
  4. Customer Service: Users can communicate with the bank’s customer service directly through the app for questions and support.
  5. Administrator: Entity may be needed if there are specific privileges or authorities that are not performed by regular users (“User”). This entity may be responsible for administrative tasks such as setting security parameters, user management, and so on.
  6. Security” may be responsible for aspects such as access control, security settings and log keeping.
    “Administrator” would then have specific administrative rights, including access to security settings. It is important to clearly define the relationships between these entities, for example how “User” and “Administrator” are related to “Security”.
    User roles:
  7. Customer: Can manage bank accounts, make transactions and use security features.
  8. Bank clerk: Can handle customer requests, validate transactions and provide support through the app.
    Data storage:
    The application stores data about user profiles, financial transactions, account balances, security logs and customer service calls. This data translates to entities such as “User,” “Transaction,” “Account,” “Security Log,” and “Customer Service Call.”
    “SecureBank” aims to make online banking more secure and user-friendly. It offers advanced security features to protect customers’ financial data while simplifying access to banking services. This helps build trust between customers and their bank and reduces financial fraud.

Explaining Open Banking and API Security