How to make random 404 pages?

I’m hosting a website on Neocities, and I want to make a random 404 webpage. So basically when you reload the 404 page it loads a different one every time or changes images and text on an existing one.

I think Javascript is needed and I never used Javascript, so can you explain it very detailed for me?

javascript : display the words “accept” or “deny”

I want to display the words “accept” or “deny” in the “observation” column from the “average” column line by line, but the problem is that my code displays the first line.

Here’s my PHP code:

<table name="cart" class="table table-bordered">
    <tr style='background: whitesmoke;'>
        <th>Evaluation</th>
        <th>Devoir</th>
        <th>Examen</th>
        <th>moyennne</th>
        <th>observation</th>
    </tr>
    <?php
    $query = "SELECT * FROM s3  limit 10";
    $result = mysqli_query($conn,$query);

    while($row = mysqli_fetch_array($result) ){
        $id = $row['id'];
  
        $numstudent = $row['numstudent'];
        $evaluation = $row['evaluation'];
        $devoir = $row['devoir'];
        $examen = $row['examen']; 
    ?>
        <tr name="line_items">
            <td><input class="decimal form-control" type='text' name='evaluation_<?= $id ?>' value='<?= $evaluation ?>' ></td>
            <td><input class="decimal form-control" type='text' name='devoir_<?= $id ?>' value='<?= $devoir ?>' ></td>
            <td><input class="decimal form-control" type='text'  name='examen_<?= $id ?>' value='<?= $examen ?>' ></td>
            <td><input class="decimal form-control" type='text' id="fname" name='item_total' jAutoCalc="((({evaluation_<?= $id ?>} + {devoir_<?= $id ?>})/2)+({examen_<?= $id ?>}*2))/3" >
             
            </td>
            <td><input class="form-control" type='text' id="fname1"  readonly></td>
        </tr>
    <?php
    }
    ?>
</table>

and javascript code:

document.getElementById("fname").onchange = function() {
  myFunction()
};

function myFunction() {
  var x = document.getElementById("fname");
  var y = document.getElementById("fname1");
  var val = "";
  var z = x.value;
  if (z >= 10.00) {
    val = "admis";
  } else {
    val = "ajourné";
  }

  y.value = val;;
}

When entering grades, the average and observation are automatically changed for a single line.
I want to enter them line by line, and the average and observation are automatically changed.
How do I do this?

Express-validator invokes catch block of the controller

I use express-validator to check email from req.body. Validation works fine, but when I enter proper email (errors array of express-validator is empty) catch block (errorHandler – “Network error”) of the controller kicks in. When I remove validation logic from controller everything works fine. Why?

errorHandler:

    const errorHandler = (error, req, res, next) => {
  if (error instanceof AppError) {
    return res.status(error.statusCode).json({
      message: error.message,
      statusCode: error.statusCode,
    });
  }

  return res.status(500).send({ message: "Network error." });
};
module.exports = errorHandler;

controller:

    exports.sendForgotPasswordEmail = async (req, res, next) => {
  try {
    const result = validationResult(req);
    if (!result.isEmpty()) {
      throw new AppError(result.array()[0].msg, 400);
    }

    const data = matchedData(req);
    const { email } = data;
    
    const emailHash = bcrypt.hashSync(email, 8);
    const token =
      Math.random().toString(36).substring(7) +
      Math.round(new Date().getTime() / 1000) +
      emailHash;
    const user = await User.findOne({ email });
    if (!user) {
      throw new AppError("User doesn't exists.", 400);
    }  
      await ResetPassword.updateOne(
        {
          email,
        },
        {
          $set: {
            email,
            token,
            siteUrl: process.env.SITE_URL,
            timestamp: Date.now(),
          },
        },
        {
          upsert: true,
        }
      );
      res.send({
        message:
          "Reset Password Link sent to the registered email successfully.",
      });
    
  } catch (error) {
    return next(error);
  }
};

route:

    router.post(
  "/forgot-password",
  body("email")
    .trim()
    .notEmpty()
    .withMessage("Email can not be empty")
    .isEmail()
    .withMessage("Email must contain @ character."),
  sendForgotPasswordEmail
);

Inconsistent JavaScript module execution on Shopify dev store

I’m working on a custom JavaScript setup for a Shopify development store. I use Vite to bundle everything into a single JS file that gets included via:

{{ 'bundle.js' | asset_url | script_tag }}

The Problem
On some page loads, all logs and functionality behave as expected.

On other loads (without code changes), my module logs still appear (showing the script ran), but core functionality breaks silently.

Most commonly, event listeners like click and change don’t fire, or DOM-dependent code fails to execute.

This only happens sometimes, seemingly depending on when and how Shopify renders DOM elements, or how third-party apps modify them.

I’ve wrapped my initialization in DOMContentLoaded, but it doesn’t reliably fix the issue.

Tried Solutions

  • Removing Vite entirely and using plain tags – same issue.
  • Switching to import maps – no improvement.
  • Adding a version parameter to the script URL (?v=123) and dynamically parsing it to bypass Shopify caching – no effect.

Example 1: Overall JS Initialization Logic
I initialize many features and utilities from different modules, like so:

import { initA, initB } from './module-a.js';
import { initC, initD } from './module-b.js';
import { setupLightbox } from './lightbox.js';

const initialize = () => {
  initA();
  initB();
  initC();
  initD();

  if (window.location.href.includes('custom-config')) {
    initCustomFeature();
  }
};

document.addEventListener('DOMContentLoaded', () => {
  console.log('DOM loaded');
  initialize();

  setupLightbox({
    selector: '.lightbox',
    loop: true,
    touchNavigation: true,
  });
});

Even though DOMContentLoaded fires and logs appear, some modules fail to work properly — especially ones relying on DOM elements added by Shopify sections or apps.

Module with Click + Change Event Listeners
This is a simplified version of a module where the issue appears:

export const exampleFeature = {
  initialize() {
    this.sizeContainer = document.querySelector('.size-options');
    this.countSelector = document.querySelector('.count-selector');

    this.setupEventListeners();
    this.updateCountOptions('4');
  },

  setupEventListeners() {
    this.sizeContainer?.addEventListener('click', (e) => {
      const selected = e.target.closest('.size-option');
      if (!selected) return;

      document.querySelectorAll('.size-option').forEach((el) => el.classList.remove('active'));
      selected.classList.add('active');

      this.updateCountOptions(selected.dataset.size);
    });

    this.countSelector?.addEventListener('change', (e) => {
      const value = e.target.value;
      this.updateSelectionUI(value);
    });
  },

  updateCountOptions(size) {
    // Logic to update count options
  },

  updateSelectionUI(value) {
    // Update UI or internal state
  },
};

This module often fails silently: either the event listeners don’t fire, or the DOM elements return null when selected — despite DOMContentLoaded supposedly guaranteeing that the DOM is ready.

Javascript backend Output: Unexpected end of JSON input

I am new to fullstack development and I’m trying to send data from my frontend javascript to my backend. For debugging I tried to send the data back to the frontend, but I get the error “{success: false, error: ‘Unexpected end of JSON input’}”.

Here is my frontend code:

form.addEventListener("submit", async (e) => {
      e.preventDefault();

      const team_name = document.getElementById("team_name").value;
      const post_description = document.getElementById("post-description").value;
      const posts = postList;

      const fullData = {
        team_name,
        post_description,
        posts,
        email: user_email
      };
      console.log("Data sent to backend:", fullData);

      const res = await fetch("https://blue-heart-681f.alexandrosmostl.workers.dev/create_team", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(fullData)
      });


      const result = await res.json();
console.log("Backend Response:", result);
console.log("All user data from backend (data):", result.data);

    });

And here is my backend code:

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type"
};

export default {
  async fetch(request, env, ctx) {
    const headers = {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type",
    };

    if (request.method === "OPTIONS") {
      return new Response(null, { headers: corsHeaders });
    }

    const url = new URL(request.url);
    const pathname = url.pathname;

if (request.method === "POST" && pathname === "/create_team") {
  const headers = {
    "Content-Type": "application/json",
    ...corsHeaders,
  };

  try {
    let body;
    try {
      body = await request.json();
    } catch (e) {
      return new Response(JSON.stringify({ success: false, error: "Invalid JSON-Body" }), { headers });
    }

    const { team_name, email, post_description, posts } = body;

    if (!team_name) {
      return new Response(JSON.stringify({ success: false, error: "Team-Name is missing" }), { headers });
    }
    if (!email) {
      return new Response(JSON.stringify({ success: false, error: "Email is missing" }), { headers });
    }
    if (!post_description) {
      return new Response(JSON.stringify({ success: false, error: "post_description is missing" }), { headers });
    }
    if (!posts) {
      return new Response(JSON.stringify({ success: false, error: "posts is missing" }), { headers });
    }

    const user = await supabaseGetUserByEmail(email);
    if (!user) {
      return new Response(JSON.stringify({ success: false, error: "User not found" }), { headers });
    }

    let currentTeams = {};
    try {
      currentTeams = user.leading_teams ? JSON.parse(user.leading_teams) : {};
    } catch (_) {}

    const baseId = team_name.toLowerCase().replace(/s+/g, "_").replace(/[^w]/g, "");
    let uniqueId = baseId;
    let counter = 1;
    const existingIds = Object.values(currentTeams);
    while (existingIds.includes(uniqueId)) {
      counter++;
      uniqueId = `${baseId}_${counter}`;
    }

    currentTeams[team_name] = uniqueId;

    await supabaseUpdateUser(email, {
      leading_teams: JSON.stringify(currentTeams)
    });

    return new Response(JSON.stringify({ success: true }), {
  headers: {
    "Content-Type": "application/json",
    ...corsHeaders
  }
});


  } catch (e) {
    return new Response(JSON.stringify({ success: false, error: e.message }), { headers });
  }
}


    return new Response(JSON.stringify({ message: "POST only allowed with /signup, /additional or /login" }), { headers });
  }
};

I’m sorry if my code is messy…

When i test my application, I get the following error message:

Data sent to backend: {team_name: 'wdefre', post_description: '•What we don•Your skillsn•Your profilen•What we offerwdew', posts: Array(1), email: '[email protected]'}
dashboard-script.js:88 Backend Response: {success: false, error: 'Unexpected end of JSON input'}
dashboard-script.js:89 All user data from backend (data): undefined

How to convert the pre-ES6 code to ES6 code [closed]

Consider you have a set of code snippets where the code is written in pre-ES6

function InputMask(options) {
  options = extend({
    formatCharacters: null,
    pattern: null,
    isRevealingMask: false,
    placeholderChar: DEFAULT_PLACEHOLDER_CHAR,
    selection: {
      start: 0,
      end: 0
    },
    value: ''
  }, options)
}

What is the best way to convert this code to ES6? TypeScript is preferable and on top of it. Should we have a class-based transformation or would function-based do the work?

export default class InputMask {

  constructor(options: InputMaskOptions) {
    options = extend(
      {
        formatCharacters: null,
        pattern: '',
        isRevealingMask: false,
        placeholderChar: DEFAULT_PLACEHOLDER_CHAR,
        selection: { start: 0, end: 0 },
        value: '',
      },
      options,
    );
    this.placeholderChar = options.placeholderChar;
    this.formatCharacters = mergeFormatCharacters(options.formatCharacters);
  }
}

This is what I thought of doing and somewhat it works but then there are minor issues like options.formatCharacters is having error of:

Argument of type 'FormatCharacters | undefined' is not assignable to parameter of type 'FormatCharacters'.
  Type 'undefined' is not assignable to type 'FormatCharacters'

and then functionality is kind of broken too.

How to convert the preES6 code to ES6 code

Consider you have a set of code snippet where the code is written in pre-es6

function InputMask(options) {
options = extend({
formatCharacters: null,
pattern: null,
isRevealingMask: false,
placeholderChar: DEFAULT_PLACEHOLDER_CHAR,
selection: {start: 0, end: 0},
value: ''
}, options)
}

What is the best way to convert this code to ES6, typescript is preferrable and on top of it. should we have a class based transformation or does function based would do the work.

export default class InputMask {

  constructor(options: InputMaskOptions) {
    options = extend(
      {
        formatCharacters: null,
        pattern: '',
        isRevealingMask: false,
        placeholderChar: DEFAULT_PLACEHOLDER_CHAR,
        selection: { start: 0, end: 0 },
        value: '',
      },
      options,
    );
    this.placeholderChar = options.placeholderChar;
    this.formatCharacters = mergeFormatCharacters(options.formatCharacters);
  }
}

This is what I thought of doing and somewhat it works but then there are minor issues like options.formatCharacters is having error of “Argument of type ‘FormatCharacters | undefined’ is not assignable to parameter of type ‘FormatCharacters’.
Type ‘undefined’ is not assignable to type ‘FormatCharacters'” and then functionality is kind of broken too. I tried on the internet about this issue, but there isn’t much so kindly help.

Install the oldest dependency versions compatible with my package.json version ranges

Consider a typical JavaScript library published on npm, with dependencies. The package declares its dependencies in package.json, where it does not specify exact versions of those dependencies but rather version ranges with which it purports to be compatible.

It seems to me that ideally, one part of such a library’s CI system or pre-release testing process would be to run the test suite using the oldest possible versions of all dependencies that are consistent with those version ranges. After all, if your package.json says you depend on "libfoo": "^1.2.3" and "libbar": ">=0.2.0" but you haven’t actually tested your latest changes with libfoo 1.2.3 or libbar 0.2.0, then how can you know that your version ranges are still correct? You might have written code that depends on a bugfix introduced in libbar 0.2.1, in which case your declared version range would now be a lie.

How can I do this? Is there some simple incantation I can use to make npm (or Yarn) disregard my lockfile and install the oldest possible versions of all my dependencies?

React Flow documentation site is down — any alternative sources for guidance? [closed]

I’m new to React and working on a project that requires using React Flow. However, the official React Flow documentation seems to be down — I’ve been trying to access it since yesterday without success.

I’ve searched for alternative guides or examples on GitHub, blogs, and YouTube, but I haven’t found anything that provides a complete overview or matches the latest version.

Are there any recommended alternative sources or community resources where I can learn how to use React Flow effectively?

odoo18: How to add WYSIWYG on website portal textarea?

In odoo18, i have customized the view of the frontend page /my/account by inheriting the view “portal.portal_my_details” to add a custom field wrapped into an HTML textarea. I have added the class .o_wprofile_editor_form to the in order to use the nativ frontend public Widget “websiteProfileEditor“:

// enterprise/odoo/addons/website_profile/static/src/website_profil.js:
publicWidget.registry.websiteProfileEditor=publicWidget.Widget.extend({
selector:'.o_wprofile_editor_form',
//...
start: async function () {

const textareaEl=this.el.querySelector("textarea.o_wysiwyg_loader");

My custom xml inherited view:

<template id="portal_my_details_zsb"   inherit_id="portal.portal_my_details">
              <xpath expr="//form" position="attributes">
                    <attribute name="enctype">multipart/form-data</attribute>
                </xpath>
    <xpath expr="//form" position="attributes">
               <attribute name="class">o_wprofile_editor_form</attribute>
    </xpath>
    <xpath expr="//form/div[hasclass('o_portal_details')]/div/div" position="inside">
               
    <div t-attf-class="col-12 py-2 #{error.get('website_description') and 'o_has_error' or ''} col-xl-12">
    <label class="col-form-label form-label" for="website_description">Activités</label>
    <textarea name="website_description" id="website_description"><t t-out="partner.website_description"/>
    </textarea>
                    </div>
        </xpath>
    </template>

After the corresponding page is loaded, the textarea is covered by a spin-icon (loading…). See image

The corresponding rendered html is:

<div class="form-group  col-xl-12"><label class="col-form-label" for="website_description" data-oe-model="ir.ui.view" data-oe-id="10438" data-oe-field="arch" data-oe-xpath="/data/xpath[2]/fieldset/div[8]/label[1]">Activités</label>

<div class="position-relative o_wysiwyg_textarea_wrapper">

<textarea 
class="form-control o_wysiwyg_loader"
name="website_description" id="website_description">
&lt;ul&gt;&lt;li&gt;Coach bien-etre &lt;/li&gt;&lt;li&gt; reiki III &lt;br&gt;&lt;/li&gt;&lt;li&gt;constellateur niv 2&lt;br&gt;&lt;/li&gt;&lt;li&gt;prof Lou Yong&lt;/li&gt;&lt;/ul&gt; 
</textarea>

<div class="o_wysiwyg_loading">
<i class="text-600 text-center fa fa-circle-o-notch fa-spin fa-2x"></i></div></div>
</div>

enter image description here

Why are export conflicts silently removed in ES6 modules

Let’s suppose we have 3 files

// a.mjs
export * from "./b.mjs";
export * from "./c.mjs";

// b.mjs
export const foo = 1;
export const bar = 2;

// c.mjs
export const bar = 3;

Both “b.mjs” and “c.mjs” export bar, so they create a conflict when they’re re-exported from “a.mjs“.

I was expecting either one of the two to “shadow” the other one or the whole thing to throw, but instead it turns out that “a.mjs” only exports foo.

Why is JavaScript pretending that the conflicting exports don’t exist at all?

(Tested in both Chromium and Node)

Plotly control slider with javascript

I took the first plotly’s sliders example https://plotly.com/javascript/sliders/
and added to the page a button that changes the slider position.

It does indeed change the slider but the plot itself is not updated.
It should go on ‘green’ but remains on ‘blue’.

Any suggestions on how to control the slider and the plot using javascript ?

// this is my code
document.getElementById("btn").onclick = () => {
    let newl = document.getElementById('graph').layout
    newl.sliders[0].active = 1
    Plotly.relayout("graph", newl)
}

// this is the plotly example cut and pasted
Plotly.newPlot('graph', [{
    x: [1, 2, 3],
    y: [2, 1, 3]
}], {
    sliders: [{
        pad: {
            t: 30
        },
        currentvalue: {
            xanchor: 'right',
            prefix: 'color: ',
            font: {
                color: '#888',
                size: 20
            }
        },
        steps: [{
            label: 'red',
            method: 'restyle',
            args: ['line.color', 'red']
        }, {
            label: 'green',
            method: 'restyle',
            args: ['line.color', 'green']
        }, {
            label: 'blue',
            method: 'restyle',
            args: ['line.color', 'blue']
        }]
    }]
}, { showSendToCloud: true });
<script src="https://cdn.plot.ly/plotly-3.0.1.min.js" charset="utf-8"></script>
<div id="btn">Click to change slider's position</div>
<div id="graph"></div>

Yubikey for touchless website authentication

I am currently working on a website for a small set of users. The backend is done using C# and .Net Core, but i don’t think that matters much for this question.

I would like to use a yubikey as following:

  • Without an authorized yubikey present the site should not work (e.g. say “not authorized”).
  • When an authorized key is present, i want each request to be authorized by the key, without any need to press the button on it.

Is this combination (discoverable credentials and also touchless) possible with a yubikey (using webauthn?)?

I thought about maybe handling the authentification in the nginx reverse proxy and then only passing the user to the actual application, is that how you usually do it?

I actually don’t have the yubikey yet, because before buying them i want to make sure this usecase is possible.

I couldn’t find & Setup ESPN Source for Live NFL Shedule

I’m building a website that displays the NFL schedule and I’d like to integrate a free API from ESPN (or any other reliable source) to automatically pull in up-to-date NFL game schedules.

After some research, I couldn’t find any official public ESPN API for NFL schedules, but I noticed some third-party sites or browser dev tools showing ESPN schedule data fetched in JSON format (e.g., from endpoints like site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard). I’m not sure if using this kind of data is allowed or if there’s a better/official way to do it.

Here’s what I want to know:

Is there a public or unofficial ESPN API that I can legally use to fetch NFL schedule data?

If yes, how can I fetch and display this data on my website (e.g., using JavaScript or PHP)?

Are there alternative free APIs or data sources you recommend for NFL schedules?

I want to keep it legal, reliable, and ideally free. Any guidance or examples would be much appreciated!

mediapipe custom pose connections

I am using mediapipe with javascript. Everything works alright until i try to show connections between spesific landmarks (in my case bettween landmarks 11, 13, 15, 12, 14, 16)

here is my custom connections array:

const myConnections = [
    [11, 13], // Left Shoulder to Left Elbow
    [13, 15], // Left Elbow to Left Wrist
    [12, 14], // Right Shoulder to Right Elbow
    [14, 16], // Right Elbow to Right Wrist
];

here is how i call them

// Draw connections
      drawingUtils.drawConnectors(landmarks, myConnections, { color: '#00FF00', lineWidth: 4 });

I can draw only the landmarks i want, but not the connections between them. I tried logging the landmarks to see if they aren’t recognised, and they returned values for X, Y, Z with VISIBILITY being UNDEFINED

console.log("Landmark 11 (Left Shoulder):", landmarks[11].visibility);
      console.log("Landmark 13 (Left Elbow):", landmarks[13].x);
      console.log("Landmark 15 (Left Wrist):", landmarks[15].y);

I tried changing the array to something like the code below and call them with the

drawingUtils.drawConnectors()

but it didnt work.

const POSE_CONNECTIONS = [
    [PoseLandmarker.LEFT_SHOULDER, PoseLandmarker.LEFT_ELBOW],
    [PoseLandmarker.LEFT_ELBOW, PoseLandmarker.LEFT_WRIST],
    [PoseLandmarker.RIGHT_SHOULDER, PoseLandmarker.RIGHT_ELBOW],
    [PoseLandmarker.RIGHT_ELBOW, PoseLandmarker.RIGHT_WRIST]
];

I used some generated code with a previous version of the mediapipe api (pose instead of vision) and it was working there