How can I navigate to two different routes, using one parameter which will have two types of values?

I am building an API and I am working on routes to find entries from the database.
Main route to the sub route is /api/v1/entries/
I want to go to two different routes from here one is for getting entries of the user with “user_id” and one is for getting entries of a particular date with “date

I know if I will write the routes as

router.get("/:user_id", getEntriesOfUser);

router.get("/:date", getEntriesOfDate);

it will always go to the first route, so what I tried is

router.get("/user/:user_id", getEntriesOfUser);

router.get("/date/:date", getEntriesOfDate);

Above method is working for me but I found it confusing as I have to use “/user” as a middle path because I also have a path /users/user/:id route in my API.
Also I do not want to use user in entries route.

Is there any way I can do it as the first approach.

ive been working on a moviewebsite and when seeding all the data im using createMany but im getting error

this is my code where i am getting the error ive checked the database its working properly and prisma is working as well so i cant figure out why i am getting this error (https://i.sstatic.net/8MJbIPBT.png)

this is my schema and ive tried restarting prisma updating prisma but nothing works and i keep getting an error stating that Error: Cannot read properties of undefined (reading ‘createMany’)

Is there any way to dynamically highlight specific letter(s) in a word, without making every single letter a separate element?

I have a div with a handful of spans, each span containing one word. The user can tap/click a word to select it, but I’m also trying to implement keyboard input.

I’d like to highlight each letter in any matching words as the user types.

For example, let’s say we have these five words:

banana
cat
baby
ball
candy

If the user types “ba” I’d like to highlight the first two letters in “banana” , “baby” , and “ball” (then if they type an ‘n’, it would un-highlight the letters in “baby” and “ball” and would highlight the first three letters of “banana” only)

These words are all dynamically generated from a word list array, so I’m hoping there might be a way to achieve this highlighting without having to wrap every single letter in a span.

Is this possible?

Window is not defined even after ‘use client’, UseEffect(), and Next/Dynamic SSR: Disabled | NextJs 14

Here is my folder structure. The page is consisted of broken down client-side components, especially “hero.jsx”.
enter image description here

In page.jsx or the main page, i imported all of these components and make sure that they’re not SSR’d

page.jsx

**"use client";**
**import dynamic from "next/dynamic";**

import styles from "./page.module.css";
import LocomotiveScroll from "locomotive-scroll";
import { useEffect } from "react";

// Dynamically import components with SSR disabled
**const Hero = dynamic(() => import("./components/home/hero/hero"), {
  ssr: false,
});
const Services = dynamic(() => import("./components/home/services/services"), {
  ssr: false,
});
const Splash = dynamic(() => import("./components/splash/splash"), {
  ssr: false,
});
const Navbar = dynamic(() => import("./components/navbar/navbar"), {
  ssr: false,
});
**
const Home = () => {

  
  **useEffect(() => {**
  **  if (typeof window !== 'undefined') {**
      const locomotiveScroll = new LocomotiveScroll();
      setIsClient(true)
   ** } **
      
  }, []);
  return (
    <main
      className={styles.main}
      style={{
        paddingBottom: "600px",
      }}
    >
      <Navbar></Navbar>
      <Splash></Splash>
      <Hero></Hero>
      <Services></Services>
    </main>
  );
};

export default Home;

and the animation happens in hero.jsx with window variable called

hero.jsx

**"use client";**
import styles from "./styles.module.css";
import Image from "next/image";
import gsap from "gsap";
import { useEffect, useRef } from "react";
import { ScrollTrigger } from "gsap/ScrollTrigger";

export default function Hero() {
  //ref for texts
  const bioText = useRef(null)
  const descText = useRef(null)
  const ctaText = useRef(null)

  //ref for sliders
  const firstList = useRef(null)
  const secondList = useRef(null)
  const slider = useRef(null)
  const textWeb = useRef(null)

  let xPercent = 0;
  let direction = -1;


**  useEffect(()=>{**

   ** if (typeof window !== "undefined") {**
      requestAnimationFrame(animation)
      gsap.registerPlugin(ScrollTrigger)
      const timeline = gsap.timeline()
  
      timeline
        .to(slider.current, {
          scrollTrigger: {
            trigger: document.documentElement,
            start: 0,
            end: **window**.innerHeight,
            scrub: 0.25,
            onUpdate: (e) => (direction = e.direction * -1),
          },
          // x:'-=300px'
        })
        .to([slider.current, textWeb.current], {
          duration: 2.5,
          clipPath: "inset(0% 0% 0% 0%)",
          ease: "power1.inOut",
        })
        .to(bioText.current, {
          duration: 1,
          clipPath: "inset(0% 0% 0% 0%)",
          ease: "power1.inOut",
        }, 1)
        .to(descText.current, {
          duration: 1,
          clipPath: "inset(0% 0% 0% 0%)",
          ease: "power1.inOut",
        }, 1)
        .to(ctaText.current, {
          duration: 1,
          clipPath: "inset(0% 0% 0% 0%)",
          ease: "power1.inOut",
        }, 1);
   ** }**


      
**  }, [])**

  const animation = () =>{
    if(xPercent <= -100){
      xPercent = 0;
    }
    if(xPercent > 0){
      xPercent = -100;
    }
    gsap.set(firstList.current, {
      xPercent: xPercent
    })
    gsap.set(secondList.current, {
      xPercent: xPercent
    })
    xPercent += 0.01 * direction;
    requestAnimationFrame(animation)


  }
  return (
    <div className={styles.hero}>
      <div className={styles.upperColumn}>
        <div ref={bioText} data-scroll data-scroll-speed='0.2' className={styles.textWrapper}>
        <div className={styles.profilePicture}>
          <Image
            src={"/images/pp rayyan.jpg"}
            fill={true}
            alt="profile picture rayyan"
          />
        </div>
        <p className={styles.mainParagraph}>
          Rayyan is a web designer, <span className={styles.bolderText}>combining the skills of a designer and a
          developer
            </span>.
        </p>
        </div>
        <div ref={ctaText} data-scroll data-scroll-speed='0.05' className={styles.textWrapper}>
        <p className={styles.mainParagraph}>Know more about him.</p>
        </div>
        
      </div>
      <div className={styles.midColumn}>
        <h1 ref={textWeb} className={styles.webText}>WEB</h1>
        <div ref={descText} className={styles.textWrapper}>
        <p className={styles.mainParagraph}>
          He is known for his web designs, animations, and interactions,
          utilizing his React expertise to implement prototypes.
        </p>
        </div>
        
      </div>
      <div className={styles.lowColumn}>
        <div data-scroll ref={slider} className={styles.slider}>
        <div  ref={firstList} className={styles.sliderList}>
          <h1>DESIGNER</h1>
          <div className={styles.svgContainer}>
          <svg xmlns="http://www.w3.org/2000/svg" width="182" height="182" viewBox="0 0 182 182" fill="none">
    <path fill-rule="evenodd" clip-rule="evenodd" d="M16.047 144.74L54.7868 106H0V76H54.7868L16.047 37.2602L37.2602 16.047L75.567 54.3538V0H105.567V55.2198L144.74 16.0463L165.954 37.2595L127.213 76H182V106H127.213L165.954 144.74L144.74 165.954L105.567 126.78V182H75.567V127.646L37.2602 165.953L16.047 144.74Z" fill="#FF4D00"/>
  </svg>
          </div>
          <h1>DEVELOPER</h1>
          <div className={styles.svgContainer}>
          <svg xmlns="http://www.w3.org/2000/svg" width="182" height="182" viewBox="0 0 182 182" fill="none">
    <path fill-rule="evenodd" clip-rule="evenodd" d="M16.047 144.74L54.7868 106H0V76H54.7868L16.047 37.2602L37.2602 16.047L75.567 54.3538V0H105.567V55.2198L144.74 16.0463L165.954 37.2595L127.213 76H182V106H127.213L165.954 144.74L144.74 165.954L105.567 126.78V182H75.567V127.646L37.2602 165.953L16.047 144.74Z" fill="#FF4D00"/>
  </svg>
          </div>
       
        </div>
        <div ref={secondList} className={styles.sliderList}>
          <h1>DESIGNER</h1>
          <div className={styles.svgContainer}>
          <svg xmlns="http://www.w3.org/2000/svg" width="182" height="182" viewBox="0 0 182 182" fill="none">
    <path fill-rule="evenodd" clip-rule="evenodd" d="M16.047 144.74L54.7868 106H0V76H54.7868L16.047 37.2602L37.2602 16.047L75.567 54.3538V0H105.567V55.2198L144.74 16.0463L165.954 37.2595L127.213 76H182V106H127.213L165.954 144.74L144.74 165.954L105.567 126.78V182H75.567V127.646L37.2602 165.953L16.047 144.74Z" fill="#FF4D00"/>
  </svg>
          </div>
          <h1>DEVELOPER</h1>
          <div className={styles.svgContainer}>
          <svg xmlns="http://www.w3.org/2000/svg" width="182" height="182" viewBox="0 0 182 182" fill="none">
    <path fill-rule="evenodd" clip-rule="evenodd" d="M16.047 144.74L54.7868 106H0V76H54.7868L16.047 37.2602L37.2602 16.047L75.567 54.3538V0H105.567V55.2198L144.74 16.0463L165.954 37.2595L127.213 76H182V106H127.213L165.954 144.74L144.74 165.954L105.567 126.78V182H75.567V127.646L37.2602 165.953L16.047 144.74Z" fill="#FF4D00"/>
  </svg>
          </div>
       
        </div>
          
        </div>
      </div>
    </div>
  );
}

can’t deploy with the error like this even though it doesn’t affect anything in terms of visual or animation in the dev env.


Logs:

Error in the dev-enviroment (this still works after the browser has rendered it, everything is fine even server-console is saying window is undefined):

** тип ReferenceError: window is not defined**
at webpack_require (C:UsersHPDocumentscodingportfolio-v4.nextserverwebpack-runtime.js:33:42)
at eval (./src/app/page.jsx:10:75)
at (ssr)/./src/app/page.jsx (C:UsersHPDocumentscodingportfolio-v4.nextserverapppage.js:162:1)
at Object.webpack_require [as require] (C:UsersHPDocumentscodingportfolio-v4.nextserverwebpack-runtime.js:33:42)
at JSON.parse ()

Error in the production, vercel enviroment (this failed to deploy):
ReferenceError: window is not defined
at 9948 (/vercel/path0/.next/server/app/page.js:17:49975)
at Object.t [as require] (/vercel/path0/.next/server/webpack-runtime.js:1:127)
at require (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:16:18490)
at I (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:94362)
at /vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:96668
at F._fromJSON (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:97106)
at JSON.parse ()
at O (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:94083)
at t (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:100582) {
digest: ‘3351242129’
}

Specs:
“dependencies”: {
“gsap”: “^3.12.5”,
“locomotive-scroll”: “^5.0.0-beta.13”,
“next”: “14.2.5”,
“react”: “^18”,
“react-dom”: “^18”
}
}

I’ve tried using all the methods in the official error documentation of nextjs which is https://nextjs.org/docs/messages/react-hydration-error

How can I detect when the body element is focused and respond to it?

You’d think this would be easy, but at least in Chrome it’s seemingly not.

If one calls document.body.focus() then this is easy, but what about when the body ends up implicitly focused? None of the traditional methods seem able to detect this.


I have an app that needs to always control the focus, and in the rare cases where we lose it there seems to be no way to programmatically detect that and get it back on course.


I tried many approaches to detect body focus from the onfocus attribute to document.body.addEventListener('focus') to window.addEventListener('focus') to window.addEventListener('focusin') but none of these work for an implicitly focused body element in my testing.

Is this just not possible? It seems so simple but I’ve spent a day on this now with no success.

How to make typescript build to emit both .d.ts and .d.mts

Recently, i want to make a node.js package, seeing other package that have the .d.ts and .d.mts declaration. so how to do that?

This is my tsconfig.json file:

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "ES6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
    "lib": [
      "ES2022"
    ] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "commonjs" /* Specify what module code is generated. */,
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    "rootDirs": [
      "./src"
    ] /* Allow multiple folders to be treated as one when resolving modules. */,
    "typeRoots": [
      "./node_modules/@types"
    ] /* Specify multiple folders that act like './node_modules/@types'. */,
    "types": [
      "node"
    ] /* Specify type package names to be included without being referenced in a source file. */,
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
    // "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */
    // "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */
    // "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    "sourceMap": true /* Create source map files for emitted JavaScript files. */,
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    "outDir": "./dist" /* Specify an output folder for all emitted files. */,
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,

    /* Type Checking */
    "strict": true /* Enable all strict type-checking options. */,
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true /* Skip type checking all .d.ts files. */
  }
}

I’d expect that the typings file generate both .d.ts and .d.mts file.

Please assist me in creating a submenu for this sidebar menu

Please check full code at : https://jsfiddle.net/zsv5ncex/
I want to add submenu but so confuse cuz i dont understand css even chatgpt, claude dont know the answer.

#sidebar .side-menu li.active {
  /*  */
  background: var(--grey);
  position: relative;
}
#sidebar .side-menu li a {
  /*  */
  width: 100%;
  height: 100%;
  background: var(--light);
  display: flex;
  align-items: center;
  border-radius: 48px;
  font-size: 16px;
  color: var(--dark);
  white-space: nowrap;
  overflow-x: hidden;
}

AJAX / Javascript not sending form mail – says success but does not actually send

I have what should be a simple issue: (code below)
So after you enter the text, and hit submit, it :

  1. never sends an email
  2. displays the Fail message

I’m hoping without to many horribly mean comments someone can explain why its not actually sending the email / why its failing?

Form :

<form id="form"  action="submit">
                        <div class="form_left">
                       
                            <label>Name <small><em>(required)</em></small></label>
                            <input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] text-input" id="name" />
                         
                            <label>Email <small><em>(required)</em></small></label>
                            <input name="email" type="text" class="validate[required,custom[email]] text-input" id="email" />
                          
                            <label>Website</label>
                            <input type="text" name="web" id="web" />
                      
                      </div>
                        <div class="form_right">
                        <p class="text">
                        <label>Your Message <small><em>(required)</em></small></label>
                        <textarea name="text" class="validate[required,length[6,300]] text-input" id="comment" cols="10" rows="10"></textarea>
                        </p>
                        </div>
                        
                        <div class="form_submit"><input type="submit" value="post" class="read_more2" />
                        </div>
                  </form>

Javascript being used for form:

<script type="text/javascript">
$(document).ready(function() {

 callSuccessFunction() }, 
$("#form").validationEngine({
    ajaxSubmit: true,
        ajaxSubmitFile: "ajaxSubmit.php",
        ajaxSubmitMessage: "Thank you, your post has been sent!",
    success :  false, ajaxSubmitMessage: "failed to send",
    failure : function() {}
})


});
</script>

ajaxSubmit.php Page :

<?php

$name = $_POST['name']; 
$email = $_POST['email'];  
$web = $_POST['web']; 
$body = $_POST['text'];  
$receiver = "[email protected]" ;  
if (!empty($name) & !empty($email) && !empty($body)) {
$body = "Name:{$name}nnWebsite :{$web}nnComments:{$body}";
$send = mail($receiver, 'Contact Form Submission', $body, "From: {$email}");
if ($send) {
    echo 'true';
}

}

?>

How to get elements after jquery page changes (I got always the same)

I was using a jquery library to reordering tables (here the link of a fiddle).

After sorting I want to gives attributes to elements on reordered table (like id=line1,id=line2 etc), but after updating by jquery like

    const t = document.querySelectorAll('#tablea')[0];
    for (var i = 0, row; row = t.rows[i]; i++) {
        console.log(row.cells[1]); //it's 1 because the first line is the header
    }

I got always the same result.
Like the page was not changed.

If you search the first line you got always the first line in previous page content.

I putted also the Javascript code after the code where it’s called the library JS that refreshes the table.

Why this and how to solve it.

TNX

How to make a Proxy trap assignment to itself?

Consider the following Proxy object:

let proxy = new Proxy({}, handler);

If I perform the following assignment, the proxy instance will be overwriten, losing the trap handlers:

proxy = {};

Alright, but if I perform the assignment using Object.assign, it keeps being the same instance (retaining the trap handlers):

Object.assign({}, proxy);

But doing it this way, none of the proxy traps get triggered.

Is it possible to make the proxy trap any of those assignment methods (using either = or Object.assign?

most stones removed with same row or column

I am not able to understand what is logical flaw in my code

I am trying to solve this problem:

947. Most Stones Removed with Same Row or Column

On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.

A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.

Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.

/**

 * @param {number[][]} stones
 * @return {number}
 */
var removeStones = function (stones) {
    const rowMap = {}
    const colMap = {}
    for (let i = 0; i < stones.length; i++) {
        const [row, col] = stones[i]
        if (!rowMap[row]) rowMap[row] = 0
        if (!colMap[col]) colMap[col] = 0
        rowMap[row] += 1
        colMap[col] += 1
    }
    return findMaxMove(stones, 0, rowMap, colMap)
};

const findMaxMove = (stones, index, rowMap, colMap) => {
    if (index == stones.length) return 0
    const [row, col] = stones[index]
    let isInCol = colMap[col] > 1
    let isInRow = rowMap[row] > 1
    let removedMove = 0
    if (isInCol || isInRow) {
        const colMapCopy = { ...colMap, [col]: colMap[col] - 1 }
        const rowMapCopy = { ...rowMap, [row]: rowMap[row] - 1 }
        removedMove = 1 + findMaxMove(stones, index + 1, rowMapCopy, colMapCopy);
    }
    return Math.max(removedMove, findMaxMove(stones, index + 1, rowMap, colMap))
}

It is passing for some case and not passing for some case:

case where it is not working:

stones = [[0,1],[1,2],[1,3],[3,3],[2,3],[0,2]]
Expected: 5
Output: 4

I got to know from internet that it is common problem to solve using Disjoint set but I wanted to solve with Brute force before I dive into Disjoint set.

Any help please

Angular Libraries: ‘rootDir’ is expected to contain all source files

A question, I don’t know if this happens to anyone, I don’t know how to fix it.

From an entrypoint (a component) I want to import the model of the other, but I get the error:

File is not under 'rootDir' 'packages'. 'rootDir' is expected to contain all source files

For example, importing a material module that has all the modules inside is much more like it too, models that can be used in other components/entry-points of the angular lib, etc.

How can I fix it? Does anyone know?

I post photos of the structure

(https://i.sstatic.net/Jp60TaJ2.png)

(https://i.sstatic.net/F80XKrVo.png)

(https://i.sstatic.net/fGHGSJ6t.png)

I tried to solve it in several ways, but none of them worked for me

I tried in tsconfig, angularjson, adding another angular, rootDir, exclude, include to the folders and nothing helped

In fact i have only one project. Its an angular library with 2 entry points, but the tsconfig i configure is the tsconfig of the entire library. This is the structure:
project

--ngx-rydex 
----dinamic-images 
-------models 
---------buttonForm.ts 
-------index.ts 
-------ng-package 
-------publicapi 
----recaptcha 
-------index.ts 
-------ng-package 
-------publicapi 

So, one model i have in dinamic-images component i want to use in recaptcha component

Discord JS v14 Bot Script Not Working (Specifically, GuildCreate and GuildMemberAdd not triggering)

Okay. I’ve tried everything I can think of here, and I can’t seem to find anything that is a similar problem to mine. The closest thing might be this post.

I’m trying to build a Discord bot that can detect how recently a user created their account, immediately after they join the server. There have been lots of problems with people creating alternate accounts to bypass bans, and the goal is to more easily identify these people.

At it’s simplest form, the bot needs to detect A: When another user joins the guild, and B: When it is added to a guild. I’ve set my permissions properly, as far as I can tell; yet the GuildCreate and GuildMemberAdd events are NOT triggered at all. No logging or anything.

My script was originally taken from another bot I built back in November~January or so. Really the only thing I kept from it was the command loader, since it worked decently for me.

I’ve left the code for my events, to highlight my purpose with the bot, but really if anyone can provide a solution that allows the first line of the events to be logged I’ll be more than happy.

EDIT:
I should also add, that my bot starts successfully and I can execute its commands in the server. But it doesn’t appear in the member list, or in the member list on any channels. All of them are open to everyone.

Here is my code:

const { token, clientId } = require('./config.json');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const fs = require('fs');
const path = require('path');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { Database } = require('./components/Database.js');

// Create a new client instance
const client = new Client({
  intents: [
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildPresences,
        GatewayIntentBits.GuildVoiceStates, // For voice states
        GatewayIntentBits.MessageContent // For content in messages
  ],
});

// Create a collection to store command files
client.commands = new Collection();

// Function to recursively read command files from the 'commands' directory
async function readCommandFiles(dir) {
    const files = await fs.promises.readdir(dir);

    for (const file of files) {
       const filePath = path.join(dir, file);
        const stat = await fs.promises.stat(filePath);
  
        if (stat.isDirectory()) {
            await readCommandFiles(filePath);
        }
        else if (file.endsWith('.js')) {
            console.log("File: " + filePath);
            const command = require('./' + filePath);
            if (command.data == undefined) { // No specified command data
                continue;
            }
            client.commands.set(command.data.name, command);
        }
    }
}

async function refresh_guild(GuildID) {
    // Update the server-side commands
    try {
        console.log('Started refreshing guild commands.');

        await rest.put(
            Routes.applicationGuildCommands(clientId, GuildID),
            { body: client.commands.map(command => command.data.toJSON()) },
        );

        console.log('Successfully reloaded guild commands.');
    }
    catch (error) {
        console.error('Error while refreshing guild commands:', error);
    }
}

async function reload() {
    // Get ALL watchlists
    let tables = await db.get('watchlist', 'guild', 'guild', '*');

    // Read the command files
    await readCommandFiles('commands');

    // Refresh ALL guild commands
    for (let table of tables) {
        await refresh_guild(table.guild);
    }
}

// Create the watchlist database
const db = new Database('./watchlist.db');

// Set the REST API version
const rest = new REST({ version: '9' }).setToken(token);

// When the client is ready, run this code (only once)
// Adds and enables commands in the server
client.once('ready', async () => {
    console.log('Ready!');
    
    // Reload the server-side commands
    await reload();
});

client.on('guildCreate', async (guild) => {
    console.log("I don't freaking work!")
    console.log(`Joined a new guild: ${guild.name} (ID: ${guild.id})`);
    
    // Create the watchlist table for the guild
    let table = db.createIfAbsent('watchlist', ['time', 'unit', 'log_channel', 'guild'])
    .then(() => {})
    .catch((error) => {
        console.error(error);
    });

    await refresh_guild(guild.id);
});

client.on('guildDelete', (guild) => {
    console.log('Guess who doesn't work... Meeeeeeeeeee! ')
    console.log(guild);
})

client.on('guildMemberAdd', async (member) => {
    console.log("Still not effing working!");

    // Wait for the watchlist table
    let watchlist = await db.get('watchlist', '*', 'guild', (member.guild.id + ''));

    console.log(watchlist);

    // Get the first table
    watchlist = watchlist[0];

    if (watchlist.log_channel == undefined) {
        console.warn("Error: LOG CHANNEL NOT FOUND")
        return;
    }
    
    // Figure out if the admins should be notified
    
    // Get the watchlist channel
    const log_channel = member.guild.channels.cache.get(watchlist.log_channel);
    
    // The channel doesn't work
    if (!log_channel) {
        throw new Error("LogChannelError: The log channel doesn't seem to exist!");
    }
    
    // Record any suspicious members in the watchlist channel
});

const interaction = require('./events/interactionCreate.js');

client.on(interaction.event, interaction.execute);
console.log(client.login(token).then((stuff) => {
    console.log("Logged In");
    return(stuff);
}).catch((error) => { console.log(error) }));

module.exports = {
    client
}

I appreciate the help.

Using javascript, how do I create a variable inside a function whose value persists across function calls?

I have a simple function which uses 1 global variable named “index”. I would prefer to incorporate it into the function such that it doesn’t automatically reset each time the function is called. In other words I want the value to persist across calls (just for the length of the session).

var index = 1;


function slideImages(offset = 0) {
  let i;
  let slides = document.getElementsByClassName("mySlides");
  let maxCount = slides.length;

  index += offset;

  if (index > maxCount) {
    index = 1;
  }
  if (index < 1) {
    index = maxCount;
  }

  for (i = 0; i < maxCount; i++) {
    slides[i].style.display = "none";
  }

  slides[index - 1].style.display = "block";
}

Javascript Closure with multiple inner functions

I am new to Javascript and i came across the concept of closure.
I am unable the understand the output of this code.
Can someone please help to understand the output’s logic?

function outer() {
    const name = "Name 1";
    function innerFunc() {
      console.log(name);
      let name2 = "Name 2";
        function innerFunc2()
        {
            let name3 = "Name 3";
            console.log(name2);
            function innerFunc3()
                {
                    console.log(name3);
                }
            return innerFunc3;
        }
      return innerFunc2;
    }
    return innerFunc;
  }
  
  const myFunc = outer();
  myFunc();

I have tried running the code it return the value of first console.log i.e Name 1