How to delete oldest row sql using sequelize. subquery

I try to delete just oldest row in table so sql gonna be like this.

DELETE FROM `session` WHERE `id` IN (
  SELECT `id`
  FROM `session`
  WHERE `userId` = :id
  ORDER BY `createdAt` DESC
  LIMIT 1
)

But using sequelize it will look like this.

const foundToken = await SessionModel.findOne({
  attributes: ["id"],
    where: {
      userId: foundUser.id,
    },
    order: [["createdAt", "DESC"]],
  })
  if (foundToken)
    await SessionModel.destroy({
      where: {
    id: foundToken.id,
  },
})

So how can I make it better then this?
Using Signal instance with subquery.

Type error cannot read the properties of undefined in JavaScript

Hey fellow developers!

I’m encountering a frustrating error in my JavaScript code and could use some help.

I’m trying to iterate over an array of objects using the map() function, but I’m getting the following error:

TypeError: Cannot read properties of undefined (reading 'map')

Here’s my code snippet:

const data = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' }
];

const result = data.map(item => item.name);

I’ve double-checked my data structure, and it seems correct. Any ideas what could be causing this error? I’ve tried logging data to the console, and it’s defined.

Thanks in advance for your help!

Is JavaScript Being Disabled Something to Worry About? [closed]

I’m brand new to any kind of web dev, writing my first web forms app that has a page for uploading files that contains a TextBox field that I want to make sure is filled in and an email field that I want to check for validity (nothing fancy, just a “well formed” address) if the user enters an email.

I have everything working as I want it to using validators and JavaScript to enable or disable the AjaxFileUpload div depending on those two fields.

In the way-too-many hours of Googling to figure out how to do things I’ve come across posts that said things like “Make sure you also validate server side in case your JavaScript is by passed” and “check it server side also in case JavaScript is disabled.”

While making this post, a couple were listed from 2010 and 2011 asking pretty much this same thing.

What’s the current opinion of this? Do I need to worry about it being disabled?

Thanks in advance for any advice.

Is there a way to send a message from a native MacOS app, to a Safari extension, then wait for a response?

So, according to Apple’s documentation, when you use sendNativeMessage to send a message to your app from a Safari web extension, there is a callback for the response, and the example of the native beginRequest(with context:) function does supply a response.

However, the example for sending data from the native app to the javascript extension via SFSafariApplication.dispatchMessage(withName:, toExtensionWithIdentifier:, userInfo:) simply sends a message and logs an error if there is one, likewise the javascript side does nothing to respond.

Is there a way to send data from the native app to the javascript and get some data in response?

Furthermore, is there a way to send a single message to the javascript in the extension without having to open a persistent connection? (How does one even maintain a persistent connection with a Manifest V3 based extension?)

The obvious solution is to just send a message to the extension, hoping it’s received and processed correctly, then separately receiving a message which is interrogated and inferred to be a response to the previous message. In the end it’s the same result, I’m just looking to see if there’s a better way.

How to display API result on front-end for users

I have this JavaScript POST Method code that sends data to an API and receive results/response. The code works perfectly and does it job. But the API sends the results to Console, which I’ve been able to produce them on Screen for users.

Is there a way to display a few selected infos (some keys and corresponding values) to user on Screen and not all the Infos provided by the API? The code I have below displays all the Infos to user on Screen which I don’t want to.

Also, I’ll like to have each of the displayed elements Stylable to what I want, and not just appear as json format on Screen. The infos include (payment_id, pay_address, pay_amount) generated by the API.

Below is what I’ve tried so far

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
<style>

</style>
</head>
<body>

  <div id="html_logger">
  </div>

<script>
//POST Method to the API and results are displayed in Console
var myHeaders = new Headers();
myHeaders.append("x-api-key", "XXXXXXXXXX");
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify(
{
  "price_amount": 6,
  "price_currency": "usd",
  "order_id": "API-Testing",
  "order_description": "NewAge Wears",
}
);

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://api.nowpayments.io/v1/payment", requestOptions)
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

//function to display result on Screen for users.
//This shows the entire result received from the API
(function () {
    var old_logger = console.log;
    var html_logger = document.getElementById('html_logger');
    console.log = function(msg) {
      old_logger.call(this, arguments);
      if (typeof msg == 'object') {
        html_logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(msg, undefined, 4) : msg) + '<br>';
      } else {
        html_logger.innerHTML += msg + '<br>';
      }
    }
})();
</script>
</body>
</html>

How do I display a few selected result to the user on Screen and not all the info received from the API. Then have them styled to what I want.

This is the result from the API: In Console
| On Screen

Thanks Greatly!!

Create “path” to “dotted” variable such as “a.b.c.d.e.f”

It is simple to create a variable such as “a”, but as soon as I want to create “a.b”, I need to know that “a” exists first, I’m trying to create a function such as “function SetPathedVariable(DottedName, Value)“.

In the console I have tried to check and create things like “[‘a.b’]” “[‘a’][‘b’]” (and many other variations), sometimes preceded by “window” as they are global variables, so far nothing I have tried works.

To make global variables easier to manage and recognise I’m creating ONE global variable and grouping variables as required, for example this is the sort of thing I currently have to do first:

var GlobalVarJs = {};
    GlobalVarJs.BtnHelp = {}; 

I want to remove the above initialization and if the first global variable is “GlobalVarJs.BtnHelp.SomeVariable” then I want it set and after creating the two above levels by executing:

SetPathedVariable("GlobalVarJs.BtnHelp.SomeVariable", "SomeValue")"

Any help appreciated, I don’t know enough Javascript to work it out yet.

Using eval() it would have been easy but I’ve been avoiding that (probably for no good reason). People talk about injection but is that a problem for information that doesn’t come from user input? Most people are very vague in their statements on the security issues.

How can I use DataTable and php?

I’m currently building a basic search utility for my site. However I’m stuck on DataTables and inserting php.

At present, I have an array with simulated data (ie Title and Description), and at a later stage I’ll replace the simulated array for a database.

I have an html file, which has a simple DataTable. I would like to ask how can I insert the simulated array/database into the DataTable?

my spider.php file reads:-

<?php
     for ($arrcount=0; $arrcount <= 50; $arrcount++) {
         $result_title[$arrcount] = "Header Title:- ".$arrcount;
         $result_description[$arrcount] = "Description Line:- ".$arrcount;
     }
     include($_SERVER['DOCUMENT_ROOT'].'/public/pubdsply.html'); 
 ?>

and my pubdsply.html:

   <!DOCTYPE html>
   <html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="description" content="">
      <meta name="author" content="">
      <title>Landing Page - Start Bootstrap Theme</title>
      Bootstrap core CSS -->
      <link href="layout/public/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
      <!--Custom fonts for this template -->
      <link href="layout/public/vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
      <link href="layout/public/vendor/simple-line-icons/css/simple-line-icons.css" rel="stylesheet" type="text/css">
      <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">
      <!-- Custom styles for this template -->
      <link href="layout/public/css/landing-page.min.css" rel="stylesheet">
      Data Table-->
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/style.min.css" rel="stylesheet" />
      <link href="/layout/publictable/css/styles.css" rel="stylesheet" />
      <script src="https://use.fontawesome.com/releases/v6.3.0/js/all.js" crossorigin="anonymous"></script>
   </head>
   <body>
      <?php
         if(session_status() !== PHP_SESSION_ACTIVE) {
         session_start();
                 }
                 ?>
      <!-- Navigation -->
      <nav class="navbar navbar-light bg-light static-top">
         <div class="container">
            <!--<a class="navbar-brand"><?= $_SESSION['settings_title'] ?></a>-->
            <a class="navbar-brand" href="#">Start Bootstrap</a>
            <a class="btn btn-primary btn-sm" href="regsignin.php">Sign In</a>
         </div>
      </nav>
      <!------------------------------------------------------------------------------------------------>
      <div id="layoutSidenav_content">
         <main>
            <div class="container-fluid px-4">
               <h1 class="mt-4">Tables</h1>
               <ol class="breadcrumb mb-4">
                  <li class="breadcrumb-item"><a href="index.html">Dashboard</a></li>
                  <li class="breadcrumb-item active">Tables</li>
               </ol>
               <div class="card mb-4">
                  <div class="card-body">
                     DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the
                     <a target="_blank" href="https://datatables.net/">official DataTables documentation</a>.
                  </div>
               </div>
               <div class="card mb-4">
                  <div class="card-header">
                     <i class="fas fa-table me-1"></i>
                     DataTable Example
                  </div>
                  <div class="card-body">
                     <table id="datatablesSimple">
                        <thead>
                           <tr>
                              <th>Name</th>
                              <th>Position</th>
                              <th>Office</th>
                              <th>Age</th>
                              <th>Start date</th>
                              <th>Salary</th>
                           </tr>
                        </thead>
                        <tfoot>
                           <tr>
                              <th>Name</th>
                              <th>Position</th>
                              <th>Office</th>
                              <th>Age</th>
                              <th>Start date</th>
                              <th>Salary</th>
                           </tr>
                        </tfoot>
                        <tbody>
                           <?
                              for ($arrcount=0; $arrcount <= 50; $arrcount++) {
                              echo "<tr>";
                              echo "<td>";
                              echo $result_title[$arrcount] . "<br>";
                              echo  $result_description[$arrcount] . "<br>";
                              echo "</td>";
                              echo "</tr>";
                              }
                              ?>
                        </tbody>
                     </table>
                  </div>
               </div>
            </div>
         </main>
      </div>
      <!-- Bootstrap core JavaScript -->
      <script src="layout/public/vendor/jquery/jquery.min.js"></script>
      <script src="layout/public/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
      DataTable -->
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
      <script src="/layout/publictable/js/scripts.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/simple-datatables.min.js" crossorigin="anonymous"></script>
      <!--<script src="/layout/publictable/js/datatables-simple-demo.js"></script>-->
   </body>
</html>

The result I’m getting is that it’s echoing the php code, instead of displaying the array.

May I please ask how I can solve this?
Thank You.

I’ve tried copying the code from the pubdsply.html file to php file, and to a tpl file and got the same result, it just echo’s the php code (ie for loop).

Why is my dropdown menu not displaying properly

Im trying to get a dropdown menu for my project but the menu doesnt show.
Here is the HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/your-path-to-uicons/css/uicons-heart-rate-monitor.css" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <script src="index.js"></script>
    <title>Internship Project (Documed)</title>
</head>
<body>
    <div class="container">
        <!-- Navbar -->
        <nav class="main-nav">
            <img src="images/logo.png">

            <ul class="main-menu">
                <li><a href="#">HOME</a></li>
                <li class="dropdown">
                    <a href="#">ABOUT US <img class="about-drop" src="images/down-arrow.png"></a></li>
                    <ul class="dropdown-menu">
                        <li><a href="#">What we do</a></li>
                        <li><a href="#">Departments</a></li>
                        <li><a href="#">Testimonials</a></li>
                    </ul>
                </li>
                <li><a href="#">CONTACT US</a></li>
            </ul>

            <ul class="right-button">
                <li>
                    <a href="#">
                        <button class="button">Make An Appointment</button>
                    </a>
                </li>
            </ul>
        </nav>
    </div>

The css

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap');
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    font-family:  "Poppins", sans-serif;
}

body {
    font-weight: 400;
    font-style: normal;
    background: #fff;
    color: #000;
    font-size: 15px;
    line-height: 1.5;
}

a {
    color: #727289;
    text-decoration: none;
}

ul {
    list-style: none;
}

.button {
    cursor: pointer;
    color: #fff;
    background-color: #009DFF;
    padding: 12px 20px;
    border: none;
    border-radius: 5px;
    font-size: 14px;
    transition: 0.3s;
}

.button:hover {
    color: #009DFF;
    background-color: #fff;
    border: #009DFF 1px solid;
}

.button2 {
    cursor: pointer;
    color: #fff;
    height: 42.5px;
    background-color: transparent;
    padding: 9px 24px;
    border: #fff 1px solid;
    border-radius: 5px;
    font-size: 15px;
    transition: 0.3s;
}

.button2:hover {
    background-color: #fff;
    border: none;
    color: #009DFF;
}

.button3 {
    cursor: pointer;
    color: #5DB2FF;
    display: inline-block;
    background-color: transparent;
    border: #5DB2FF 1px solid;
    -webkit-border-radius: 0.5s;
    border-radius: 5px;
    text-align: center;
    font-size: 15px;
    font-weight: 400;
    padding: 9px 24px;
    transition: 0.5s;
    -webkit-transition: 0.5s;
}

.button3:hover {
    color: #fff;
    background-color: #5DB2FF;
    border: none;
}

.container {
    margin-top: 10px;
    width: 90%;
    max-width: 1100px;
    margin-left: 210px;
    margin-right: 210px;
    margin-top: 20px;
}

.main-nav {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 60px;
    padding: 18px 0px;
    font-size: 15px;
    margin-bottom: 25px;
}

.main-nav .logo {
    width: 110px;
}

.main-nav ul {
    display: flex;
    padding: 0;
    font-size: 15px;
    font-weight: 600;
}

.main-nav .main-menu .about-drop {
    width: 18px;
    height: 18px;
}

.main-nav .main-menu .dropdown {
    position: relative;
}

.main-nav .main-menu .dropdown-menu {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    background-color: gray;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 10px 0;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    min-width: 200px;
}

.main-nav .main-menu .dropdown-menu li {
    padding: 10px 20px;
}

.main-nav .main-menu .dropdown-menu li a {
    color: #727289;
    text-decoration: none;
    display: block;
}

.main-nav .main-menu .dropdown-menu li a:hover {
    color: #009DFF;
}

.dropdown:hover .dropdown-menu,
.dropdown:active .dropdown-menu {
    display: block;
}

.dropdown-menu { 
    display: hidden
}

/* Adjustments for the About Us dropdown icon */
.about-drop {
    margin-left: 5px;
    transition: transform 0.3s;
}

.dropdown:hover .about-drop {
    transform: rotate(180deg);
}

.main-nav ul li {
    position: relative;
}

.main-nav ul li a:hover {
    border-bottom: 2px solid #009DFF;

}

.main-nav ul.main-menu {
    margin-left: 20px;
}

.main-nav ul.main-menu li {
    margin: 25px;
}

Pls note that this is just a section of the code involving the navbar and dropdown menu. I did this to reduce the amount of content being displayed. I would also like to know if i should use javascript.

I tried changing the display and position but it didnt show.

Why is extraOptions undefined in baseQueryWithReauth when making a request with RTK Query?

I’m using RTK Query with fetchBaseQuery and a custom baseQueryWithReauth function for handling authentication. My setup involves checking for authentication and refreshing tokens if necessary.

Here’s the relevant code:

baseQuery.js

import { fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { authApiSlice } from "~/features/api/authApiSlice";

// Create a base query instance
const baseQuery = fetchBaseQuery({
  baseUrl: import.meta.env.VITE_API_BASE_URL,
  credentials: "include",
  prepareHeaders: (headers) => {
    headers.set("x-api-key", localStorage.getItem("apiKey") || '');
    return headers;
  },
});

const baseQueryWithReauth = async (args, api, extraOptions) => {
  console.log('Base Query Args:', args);
  console.log('Extra Options:', extraOptions);

  const shouldSkipAuth = extraOptions?.skipAuth || false;

  let result = await baseQuery(args, api, extraOptions);

  if (!shouldSkipAuth && result.error && result.error.status === 401) {
    const refreshResult = await api.dispatch(
      authApiSlice.endpoints.refreshToken.initiate()
    );

    if (refreshResult.data) {
      result = await baseQuery(args, api, extraOptions);
    } else {
      return refreshResult;
    }
  }

  return result;
};

export { baseQueryWithReauth as baseQuery };

authApiSlice.js:

import { createApi } from "@reduxjs/toolkit/query/react";
import { baseQuery } from "~/services/api/baseQuery";

export const authApiSlice = createApi({
  reducerPath: "authApi",
  baseQuery,
  endpoints: (builder) => ({
    login: builder.mutation({
      query: ({ email, password }) => ({
        url: `/auth/login`,
        method: "POST",
        body: { email, password },
        extraOptions: { skipAuth: true }, // Skip auth for login
      }),
    }),
    refreshToken: builder.mutation({
      query: () => ({
        url: `/auth/refresh-token`,
        method: "POST",
      }),
    }),
  }),
});

export const { useLoginMutation } = authApiSlice;

Login.jsx

const [login] = useLoginMutation();

const handleLogin = async (email, password) => {
  try {
    const result = await login({ email, password }).unwrap();
    console.log('Login result:', result);
  } catch (err) {
    console.error('Login error:', err);
  }
};

What I Tried

  1. Log Debugging: I’ve logged the extraOptions in baseQueryWithReauth to verify if it’s being passed correctly.
  2. Endpoint Configuration: I’ve configured extraOptions in the authApiSlice endpoints, specifically for the login endpoint to skip authentication.

What I Expected

  1. I expected that the extraOptions set for the login request would be available in the baseQueryWithReauth function, allowing it to skip the authentication logic for login requests.
  2. Instead, I see extraOptions is undefined in baseQueryWithReauth, which causes issues while login.

ReaCT AND NODE JS HAVE PROBLEM WITH COOKIES

I am making an online forum.I tried to login and after checking the data the server sends a server side cookie then iI use a basic React.useEffect to get the value from another path in node to extract the sessionId but no cookie registered in firefox no nothing

App.js

const express = require('express')
var cors = require('cors');
const app = express()
const forumpage = require("./routes/forumpage")
const peopleroute = require("./routes/users")
const cookieParser = require('cookie-parser');
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(cookieParser())

app.use(cors({
    origin: 'http://localhost:3000', // Replace with your frontend URL
    credentials: true // Allows cookies to be sent with requests
}));


app.use("/users", peopleroute)
app.use("/forumpage", forumpage)


app.listen(5000, () => {
    console.log("App runs on port 5000")
})

Cookie line of the login post function

res.cookie('sessionId', 'sessionId', {
       httpOnly: true, // Makes the cookie inaccessible via JavaScript on the 

});

Trying to get the session id from frontend(This is in the backend)

const usernames = async (req, res) => {

    console.log(req.cookies.sessionId)
    res.send(req.cookies.sessionId)




}

Frontend part that calls the last function

    const [user, setUser] = React.useState([])
    React.useEffect(() => {

        axios.get("http://localhost:5000/users/usersessions").then((response) => {
            setUser(response.data)
        })
    }, [])
console.log(user)

How to rejoin an array of strings with a line break in JS? [closed]

I’m trying to rejoin an array of strings that was initially a large block of text separated by forward slashes:

function formatItemData() {
const lineItems = document.querySelectorAll('.cfw-cart-item-data');

lineItems.forEach((lineItem) => {
    let newLineItem = lineItem.textContent.split(' / ');


    lineItem.textContent = newLineItem.join("/n"); // How do I create a new textContent with the strings joined, but with a line break in place of the "/"?
    
});

};

document.addEventListener('DOMContentLoaded', formatItemData);

I can’t figure out how to rejoin the array into a new “textContent” but separated by line breaks. Any input?

Semantics of insChild in backdraft.js component

Imagine I have a component called ClockFace and this code to display Big Ben:

class BigBen extends Component {
    bdElements() {
        return e.div(
            { className: 'clocktower' },
            e.div(
                { className: 'clockface', bdAttach: 'clockGoesHere' }
            )
        )
    }

    insertClockFace() {
        this.clockGoesHere.insChild(ClockFace, { ...ClockFace kwargs... })
    }
}

This doesn’t work (and of course it doesn’t, since this.clockGoesHere is just a DOM node). What’s the right way to use insChild here?

Infinite scroll working on Chrome and Mozilla (localhost), but it is glitching on Safari. what am I doing wrong?

I’m working on a website with 9 sections and implemented an infinite scroll feature. When you reach the last section, the first one is added to the bottom of the page. This works fine in most browsers, but I’m encountering issues in Safari and on mobile devices after deploying to Heroku. I’m using Rails and Stimulus

import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static targets = ["section", "selectedImage", "dropbtn", "navbar"];
  sectionIds = ["section1", "section2", "section3", "section4", "section5", "section6", "section7", "section8", "section9"];

  connect() {
    this.prevScrollpos = window.scrollY;
    this.navbarTarget.style.transform = "translateY(-100%)";
    this.scrollHandler = this.handleScroll.bind(this);
    this.infiniteScrollHandler = this.checkInfiniteScroll.bind(this);
    window.addEventListener("scroll", this.scrollHandler);
    window.addEventListener("scroll", this.infiniteScrollHandler);
    this.observeSections();
  }

  disconnect() {
    window.removeEventListener("scroll", this.scrollHandler);
    window.removeEventListener("scroll", this.infiniteScrollHandler);
  }

  handleScroll() {
    let currentScrollPos = window.scrollY;
    if (this.prevScrollpos > currentScrollPos) {
      this.navbarTarget.style.top = "0";
    } else {
      this.navbarTarget.style.top = "100px";
    }
    this.prevScrollpos = currentScrollPos;
  }

  toggleDropdown() {
    const dropdown = document.getElementById("myDropdown");
    dropdown.style.display = dropdown.style.display === "block" ? "none" : "block";
  }

  scrollToSection(event) {
    event.preventDefault();
    const imageSrc = event.currentTarget.getAttribute("data-image-src");
    this.selectedImageTarget.src = imageSrc;

    this.toggleDropdown();
    const sectionClassName = event.currentTarget.getAttribute("href").substring(1);
    const sectionName = event.currentTarget.innerText;
    const contentHTML = `<img src="${imageSrc}" alt="" class="dot"> ${sectionName}`;

    this.dropbtnTarget.innerHTML = contentHTML;

    const sections = document.getElementsByClassName(sectionClassName);

    if (sections.length > 0) {
      const section = sections[0];

      this.element.querySelectorAll("a").forEach((link) => {
        link.classList.remove("active");
      });

      event.currentTarget.classList.add("active");

      section.scrollIntoView({
        behavior: "smooth",
        block: "center",
        inline: "nearest",
      });
    }
  }

  updateDropdownButton(sectionName, imageSrc) {
    const contentHTML = `<img src="${imageSrc}" alt="" class="dot"> ${sectionName}`;
    this.dropbtnTarget.innerHTML = contentHTML;
  }

  observeSections() {
    const observerOptions = {
      root: null,
      rootMargin: '0px',
      threshold: 0.95
    };

    const observerCallback = (entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const section = entry.target;
          const sectionName = section.getAttribute('data-section-name');
          const imageSrc = section.getAttribute('data-image-src');
          this.updateDropdownButton(sectionName, imageSrc);
        }
      });
    };

    this.observer = new IntersectionObserver(observerCallback, observerOptions);
    this.observeAllSections();
  }

  observeAllSections() {
    this.sectionIds.forEach(id => {
      const section = document.getElementById(id);
      if (section) {
        this.observer.observe(section);
      }
    });
  }

  checkInfiniteScroll() {
    if (!this.infiniteScrollPending) {
      this.infiniteScrollPending = true;
      requestAnimationFrame(() => {
        this.infiniteScrollPending = false;
        const buffer = 50; // Add a small buffer
        if ((window.innerHeight + window.scrollY + buffer) >= document.body.offsetHeight) {
          this.moveFirstSectionToBottom();
        }
      });
    }
  }

  moveFirstSectionToBottom() {
    const firstSection = document.getElementById(this.sectionIds[0]);
    if (firstSection) {
      firstSection.parentNode.appendChild(firstSection);
      this.sectionIds.push(this.sectionIds.shift());
      this.observer.disconnect();
      this.observeAllSections();
    }
  }
}

What is the value of maximum call stack in javascript? [closed]

I was just being curious about how many times a function or a statement is called in a recursion before “maximum call stack exceeded” error is encountered. I know it varies from system to system but what does it depend upon, how is it determined and is there a way to modify it?

I ran an infinite recursion to see in different systems (VSCode in my windows machine, Browser – Firefox, LeetCode’s JS compiler) to check how many times each of them will run the code.

The code:

function doRecursion(target = 0) {
  target++;
  console.log(target);
  doRecursion(target);
}

doRecursion()
  1. VSCode in my windows machine ran it exactly 10351 times
    Screenshot
  2. Firefox ran it a little more than 1573 times
    Screenshot
  3. LeetCode’s stack kept varying
    Screenshot0
    Screenshot1

Failed Deployment on Netlify

I have a React website deployed on Netlify, the website is live and I made some changes on my Github file but the changes are not reflecting because the deployment keeps failing when it gets to the build stage

I have searched for a possible solution, and changed the deployment settings based on solutions provided online to Build command: CI= npm run build but I still get the same error.

// error log
8:58:53 PM: Netlify Build                                                 
8:58:53 PM: 
8:58:53 PM: ​
8:58:53 PM: ❯ Version
8:58:53 PM:   @netlify/build 29.54.0
8:58:53 PM: ​
8:58:53 PM: ❯ Flags
8:58:53 PM:   accountId: 60e33a08c5f3c1a88eb16b3b
8:58:53 PM:   baseRelDir: true
8:58:53 PM:   buildId: 66cf8145c77b7d0008018c4c
8:58:53 PM:   deployId: 66cf8145c77b7d0008018c4e
8:58:53 PM: ​
8:58:53 PM: ❯ Current directory
8:58:53 PM:   /opt/build/repo
8:58:53 PM: ​
8:58:53 PM: ❯ Config file
8:58:53 PM:   No config file was defined: using default values.
8:58:53 PM: ​
8:58:53 PM: ❯ Context
8:58:53 PM:   production
8:58:53 PM: ​
8:58:53 PM: Build command from Netlify app                                
8:58:53 PM: 
8:58:53 PM: ​
8:58:53 PM: $ CI= npm run build
8:58:54 PM: > [email protected] build
8:58:54 PM: > react-scripts build
8:58:54 PM: node:internal/modules/cjs/loader:1143
8:58:54 PM:   throw err;
8:58:54 PM:   ^
8:58:54 PM: Error: Cannot find module 'ajv/dist/compile/codegen'
8:58:54 PM: Require stack:
8:58:54 PM: - /opt/build/repo/node_modules/ajv- 
keywords/dist/definitions/typeof.js
8:58:54 PM: - /opt/build/repo/node_modules/ajv- 
keywords/dist/keywords/typeof.js
8:58:54 PM: - /opt/build/repo/node_modules/ajv- 
keywords/dist/keywords/index.js
8:58:54 PM: - /opt/build/repo/node_modules/ajv- 
keywords/dist/index.js
8:58:54 PM: - /opt/build/repo/node_modules/schema- 
utils/dist/validate.js
8:58:54 PM: - /opt/build/repo/node_modules/schema- 
utils/dist/index.js
8:58:54 PM: - /opt/build/repo/node_modules/mini-css-extract- 
plugin/dist/index.js
8:58:54 PM: - /opt/build/repo/node_modules/react- 
scripts/config/webpack.config.js
8:58:54 PM: - /opt/build/repo/node_modules/react- 
scripts/scripts/build.js
8:58:54 PM:     at Module._resolveFilename 
(node:internal/modules/cjs/loader:1140:15)
8:58:54 PM:     at Module._load 
(node:internal/modules/cjs/loader:981:27)
8:58:54 PM:     at Module.require 
(node:internal/modules/cjs/loader:1231:19)
8:58:54 PM:     at require (node:internal/modules/helpers:177:18)
8:58:54 PM:     at Object.<anonymous> 
(/opt/build/repo/node_modules/ajv- 
keywords/dist/definitions/typeof.js:3:19)
8:58:54 PM:     at Module._compile 
(node:internal/modules/cjs/loader:1364:14)
8:58:54 PM:     at Module._extensions..js 
(node:internal/modules/cjs/loader:1422:10)
8:58:54 PM:     at Module.load 
(node:internal/modules/cjs/loader:1203:32)
8:58:54 PM:     at Module._load 
(node:internal/modules/cjs/loader:1019:12)
8:58:54 PM:     at Module.require 
(node:internal/modules/cjs/loader:1231:19) {
8:58:54 PM:   code: 'MODULE_NOT_FOUND',
8:58:54 PM:   requireStack: [
8:58:54 PM:     '/opt/build/repo/node_modules/ajv- 
keywords/dist/definitions/typeof.js',
8:58:54 PM:     '/opt/build/repo/node_modules/ajv- 
keywords/dist/keywords/typeof.js',
8:58:54 PM:     '/opt/build/repo/node_modules/ajv- 
keywords/dist/keywords/index.js',
8:58:54 PM:     '/opt/build/repo/node_modules/ajv- 
keywords/dist/index.js',
8:58:54 PM:     '/opt/build/repo/node_modules/schema- 
utils/dist/validate.js',
8:58:54 PM:     '/opt/build/repo/node_modules/schema- 
utils/dist/index.js',
8:58:54 PM:     '/opt/build/repo/node_modules/mini-css-extract- 
plugin/dist/index.js',
8:58:54 PM:     '/opt/build/repo/node_modules/react- 
scripts/config/webpack.config.js',
8:58:54 PM:     '/opt/build/repo/node_modules/react- 
scripts/scripts/build.js'
8:58:54 PM:   ]
8:58:54 PM: }
8:58:54 PM: Node.js v18.20.4​
8:58:54 PM: "build.command" failed                                        
8:58:54 PM:   Error message
8:58:54 PM:   Command failed with exit code 1: CI= npm run build 
(https://ntl.fyi/exit-code-1)
8:58:54 PM: ​
8:58:54 PM:   Error location
8:58:54 PM:   In Build command from Netlify app:
8:58:54 PM:   CI= npm run build​
8:58:54 PM:   Resolved config
8:58:54 PM:   build:
8:58:54 PM:     command: CI= npm run build
8:58:54 PM:     commandOrigin: ui
8:58:54 PM:     environment:
8:58:54 PM:       - NPM_FLAGS
8:58:54 PM:     publish: /opt/build/repo/build
8:58:54 PM:     publishOrigin: ui
8:58:55 PM: Failed during stage 'building site': Build script 
returned 
non-zero exit code: 2 (https://ntl.fyi/exit-code-2)
8:58:55 PM: Build failed due to a user error: Build script 
returned 
non-zero exit code: 2
8:58:55 PM: Failing build: Failed to build site
8:58:55 PM: Finished processing build request in 45.693s