Why Can This Not Write To Directory ‘Output’?

I am attempting to write a file to an existing directory, using node, path, and fs.

How it’s supposed to work:

  1. Init mock data.
  2. Loop through mock data.
  3. Write mock string to existing directory ‘output’
  4. End program.

How it’s working:

  1. Init mock data.
  2. Loop through mock data.
  3. Attempt to write to existing directory.
  4. Yield error:

Error:

throw new Error(`Error writing: ${err.message}`);
                                ^

Error: Error writing: ENOENT: no such file or directory, open 'C:Usersusernametestcheeriooutput55-207-0-228_2025-04-29_15:27:51.txt'
    at C:UsersusernametestcheeriocomponentsWriteFile.js:31:11
    at node:fs:2385:7
    at FSReqCallback.oncomplete (node:fs:188:23)

Repository

I’m working off this repository. The function handling node:fs writefile is found at /component/WriteFile.js; it is being invoked here, on these lines..

Project Tree

This is the project structure:

project-root/
├── components/             
├── node_modules/            
├── output/                  // Target for file write. 
├── .gitignore               
├── index.js               
├── LICENSE                 
├── package-lock.json        
├── package.json            
└── README.md                

WriteFile Snippet

Posting relevant code here for convenience.
WriteFile.js

const fs = require('node:fs');
const path = require('path');

const makeFile = async (fileName, { contentString, ip }) => {
    const now = new Date();
    const dateString =
        now.getFullYear() +
        '-' +
        String(now.getMonth() + 1).padStart(2, '0') +
        '-' +
        String(now.getDate()).padStart(2, '0') +
        '_' +
        String(now.getHours()).padStart(2, '0') +
        ':' +
        String(now.getMinutes()).padStart(2, '0') +
        ':' +
        String(now.getSeconds()).padStart(2, '0');

    contentString = `DATE: ${dateString}nFor ip: ${ip}n${contentString}`;

    const filepath = path.join(
        __dirname,
        '..',
        'output',
        `${fileName}_${dateString}.txt`
    );

    try {
        await fs.writeFile(filepath, contentString, 'utf16le', (err) => {
            if (err) {
                throw new Error(`Error writing: ${err.message}`);
            }
        });
        return 'Success';
    } catch (error) {
        console.error('nError:n', error.message, 'n');
    } finally {
        // Code that will run regardless of try/catch result
        // Remember, don't have a return in finally.
        console.log('Final completed.');
    }
};

module.exports = { makeFile };

Invoked At:

Which is being called at:

async function main() {
    let start = performance.now();
    let elapse;
    i = 0;
    for (const ip of ipList) {
        i++;
        if (i > 3) {
            break;
        }
        const sleep = (ms) =>
            new Promise((resolve) => {
                setTimeout(resolve, ms);
            });
        await sleep(500);

        await makeFile(ip.replaceAll('.', '-'), {
            contentString: 'Mockdata',
            ip: ip
        });
    }
    elapse = performance.now() - start;
    console.log('Total time elapsed: ', elapse / 1000);
}

how can I extract audio from video mp4 for macOS

I’m building a React JS app where I need to extract audio from a video file and convert it into a Blob with MIME type ‘audio/wav’. The extracted Blob will later be uploaded to Ai like chahgpt for Speech-to-Text.my this tow function working on web and desktop windows application but it problem on only macOS. thanks in advance.


    const extractAudioFromVideoFallback = async (videoFile: File): Promise<Blob | null> => {
    const audioContext = new AudioContext();

    try {
        const arrayBuffer = await videoFile.arrayBuffer();
        const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);

        const offlineCtx = new OfflineAudioContext({
            numberOfChannels: audioBuffer.numberOfChannels,
            length: audioBuffer.length,
            sampleRate: audioBuffer.sampleRate,
        });

        const source = offlineCtx.createBufferSource();
        source.buffer = audioBuffer;
        source.connect(offlineCtx.destination);
        source.start();

        const renderedBuffer = await offlineCtx.startRendering();
        return audioBufferToWavBlob(renderedBuffer);
    } catch (err) {
        console.warn("Decoding failed or no audio track found:", err);
        return null;
    }
};

const audioBufferToWavBlob = (audioBuffer: AudioBuffer): Blob => {
    const numOfChan = audioBuffer.numberOfChannels;
    const length = audioBuffer.length * numOfChan * 2 + 44;
    const buffer = new ArrayBuffer(length);
    const view = new DataView(buffer);

    const writeString = (view: DataView, offset: number, string: string) => {
        for (let i = 0; i < string.length; i++) {
            view.setUint8(offset + i, string.charCodeAt(i));
        }
    };

    let offset = 0;
    writeString(view, offset, 'RIFF'); offset += 4;
    view.setUint32(offset, 36 + audioBuffer.length * numOfChan * 2, true); offset += 4;
    writeString(view, offset, 'WAVE'); offset += 4;
    writeString(view, offset, 'fmt '); offset += 4;
    view.setUint32(offset, 16, true); offset += 4;
    view.setUint16(offset, 1, true); offset += 2;
    view.setUint16(offset, numOfChan, true); offset += 2;
    view.setUint32(offset, audioBuffer.sampleRate, true); offset += 4;
    view.setUint32(offset, audioBuffer.sampleRate * numOfChan * 2, true); offset += 4;
    view.setUint16(offset, numOfChan * 2, true); offset += 2;
    view.setUint16(offset, 16, true); offset += 2;
    writeString(view, offset, 'data'); offset += 4;
    view.setUint32(offset, audioBuffer.length * numOfChan * 2, true); offset += 4;

    let interleaved = new Int16Array(audioBuffer.length * numOfChan);
    for (let i = 0; i < audioBuffer.length; i++) {
        for (let channel = 0; channel < numOfChan; channel++) {
            const sample = audioBuffer.getChannelData(channel)[i];
            const s = Math.max(-1, Math.min(1, sample));
            interleaved[i * numOfChan + channel] = s < 0 ? s * 0x8000 : s * 0x7FFF;
        }
    }

    let index = 44;
    for (let i = 0; i < interleaved.length; i++, index += 2) {
        view.setInt16(index, interleaved[i], true);
    }

    return new Blob([buffer], { type: 'audio/wav' });
};


Hide Non-Visible Slides + Make Responsive

I have a few things that I am trying to do with SwiperJS. You can see on my site here: http://newgl.greenlegion.com

ISSUE 1: i cannot figure out a way to see more of the slide on mobile. It’s tough since the text on the slide gets bigger and you do not want it to run off the slide. Needs a min-height of the view port for the div of the slide. Shocked this is not responsive.

ISSUE 2: I am trying to hide the non-visible slides since instead of transitioning larger, I want them smaller on a timeline. The slides in the background are larger so you see them.

I tried to “hide” and “show” with d-none based on if there is a class of swiper-slide-visible is present, but does not seem to work (or I am calling the add/removeClass wrong).

    const targetElement = $(".swiper-slide");

    function checkAndHandleClass() {
        if (targetElement.hasClass("swiper-slide-visible")) {
            console.log("Element has 'swiper-slide-visible'");
            targetElement.removeClass("d-none");  //DOES NOT WORK
        } else {
            console.log("Element does not have 'swiper-slide-visible'");
            targetElement.addClass("d-none"); //DOES NOT WORK
        }
    }

    // Initial check on page load
    checkAndHandleClass();

    // Mutation Observer for monitoring class changes
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.attributeName === "class") {
                checkAndHandleClass();
            }
        });
    });

    observer.observe(targetElement[0], {
        attributes: true,
        attributeFilter: ["class"]
    });

Get file address with ASP.NET

I have a C# application with ASP.NET MVC and Framework 4.8, and CSHTML pages. I also have the DevExpress MVC version 21.2 libraries, although I don’t think it’s important. I need to put a button on my Index screen that, when pressed, launches an OpenFileDialog or similar dialog box, but not embedded in the screen. I need to save the file address in a string variable in the controller when I select a file and press “OK.” I don’t want to do anything with the file.
I’ve tried doing it with JavaScript, with DevExpress components, and I’m getting too many errors.

setState function not recognized as function

In my React Native app, I’m having a problem where the setState function is not being recognized as a function.

I already inserted the context provider on the App root page and exported the context properties, and it still doesn’t work.

I’m trying to call it on a component, and still getting the “setAppCompany is not a function”

App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import AppProviders from './mobile/src/providers/AppProviders';
import Route from './mobile/src/navigations/Route';
import Layout from './mobile/src/layout/Layout';

export default function App() {
  return (
    <AppProviders>
      <NavigationContainer>
        <Layout>
          <Route />
        </Layout>
      </NavigationContainer>
    </AppProviders>
  );
}

AppProviders.js

import React from 'react';
import CompanyProvider from '../contexts/CompanyContext';
import UserProvider from '../contexts/UserContext';

const AppProviders = ({ children }) => {
  return (
    <CompanyProvider>
      <UserProvider>{children}</UserProvider>
    </CompanyProvider>
  );
};

export default AppProviders;

CompanyContext.js

import React, { createContext, useState, useContext } from 'react';
export const CompanyContext = createContext();

export default function CompanyProvider({ children }) {
  const [appCompanyId, setAppCompany] = useState(null);

  return (
    <CompanyContext.Provider value={(appCompanyId, setAppCompany)}>
      {children}
    </CompanyContext.Provider>
  );
}

export const useCompany = () => {
  const context = useContext(CompanyContext);
  const { appCompanyId, setAppCompany } = context;
  return { appCompanyId, setAppCompany };
}

UserContext.js

import React, { createContext, useState, useContext } from 'react';
export const UserContext = createContext();

export default function UserProvider({ children }) {
  const [logged, setLogged] = useState(false);
  const [userId, setUserId] = useState(null);
  const [token, setToken] = useState('');
  const [admin, setAdmin] = useState(false);

  return (
    <UserContext.Provider
      value={
        (logged, setLogged, userId, setUserId, token, setToken, admin, setAdmin)
      }>
      {children}
    </UserContext.Provider>
  );
}

export function useUser() {
  const context = useContext(UserContext);
  const {
    logged,
    setLogged,
    userId,
    setUserId,
    token,
    setToken,
    admin,
    setAdmin,
  } = context;
  return {
    logged,
    setLogged,
    userId,
    setUserId,
    token,
    setToken,
    admin,
    setAdmin,
  };
}

TopBar.js (Component using context properties)

import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { Picker } from '@react-native-picker/picker';
import { getCompaniesByUserId } from '../services/api/company.services';
import { useUser } from '../contexts/UserContext';
import { useCompany } from '../contexts/CompanyContext';

const TopBar = () => {
  // Hooks ------------------------------------->
  const { userId } = useUser();
  const { setAppCompany } = useCompany();

  const [selectedCompany, setSelectedCompany] = useState(null);
  const [avaliableCompanies, setAvailableCompanies] = useState([
    { idEmpresa: 1, nomeEmpresa: 'Rooftop Bar' },
    { idEmpresa: 2, nomeEmpresa: 'Restaurante Brilhante' },
  ]);

  useEffect(() => {
    if (avaliableCompanies == null)
      setAvailableCompanies(getCompaniesByUserId(userId));

    if (avaliableCompanies != null && selectedCompany == null)
      setSelectedCompany(avaliableCompanies[0]);
  }, [avaliableCompanies, selectedCompany, userId]);

  useEffect(() => {
    if (selectedCompany != null) setAppCompany(selectedCompany);
  }, [selectedCompany, setAppCompany]);

  // JSX ------------------------------------->
  return (
    <View style={styles.topBar}>
      <Text style={styles.title}>RoofStock</Text>
      <View style={styles.selectorContainer}>
        <Text style={styles.label}>Company:</Text>
        <Picker
          selectedValue={selectedCompany}
          onValueChange={setSelectedCompany}
          style={styles.picker}
          dropdownIconColor="#fff">
          {avaliableCompanies.map((company) => (
            <Picker.Item
              label={company.nomeEmpresa}
              value={company.idEmpresa}
            />
          ))}
        </Picker>
      </View>
    </View>
  );
};

I tried to use the setState function in the context created and couldn’t. I was expecting to use the setState function to control and manage state based on this data around the app.

p5.js Cannot convert undefined or null to object

I am trying to make a grid for a game, and I set up the grid, but when I use a for loop to display all of the cells it gives me an error – Uncaught TypeError: Cannot convert undefined or null to object. I think that there is something undefined in the grid array but there shouldn’t be. Another theory is that the grid is empty, although it should have 16 cells in it.

let bgCol = '#A6A6A6';
let rows = 4;
let cols = 4;
let grid = [];
let size = 50;


function setup() {
    createCanvas(windowWidth, windowHeight);
    background(bgCol);
    for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
            grid.push(new Cell({x: r * size, y: c * size}, 0));
        }
    }
}

function draw() {
    background(bgCol);
    for (let g of grid) {
        grid[g].dis();
    }
}

class Cell {
    constructor(pos, num, col = '#FFFFFF') {
        this.pos = pos;
        this.num = num;
        this.col = col; // White as placeholder until later
    }
    dis() {
        stroke('#000000');
        strokeWeight(2);
        fill(this.col);
        square(this.pos.x, this.pos.y, size, 5);
        if (this.num) {
            textSize(size - 5);
            text(this.num, this.pos.x + 5, this.pos.y + 5);
        }
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.11.0/p5.js"></script>

Video capture/analysis on simple static snack (hot fries) site

Alright, so we’ve got this pretty basic, mostly static marketing website – you know, the kind that just shows off the product, here it is andycappshotfries.com. Nothing fancy on the backend, just simple HTML/CSS/JS and maybe a tiny script for a contact form.

But we’ve got this wild idea we wanna slap onto it: a “Spiciness Challenge” feature! The plan is users can record a quick video right in their browser, chowing down on the product, upload it, and then our server (somehow!) runs computer vision magic (think Python and OpenCV) to analyze their reaction and give ’em a “spiciness score.”

Here’s the rub – bolting this complex video capture and processing beast onto a super simple site? That’s got us scratching our heads. We need some solid technical game plan.

Specifically, we’re kinda lost on:

  1. Client-Side Video Fun: How do we even reliably capture video from a user’s webcam across different browsers without it being a total nightmare? Are there any slick JavaScript libraries beyond just wrestling with navigator.mediaDevices.getUserMedia() directly? And resizing or formatting that video on the fly before uploading – what’s the play there?
  2. The Upload Beast: Video files can get chunky fast, right? What’s the smoothest, most robust way to pump potentially big files up to our server? Should we mess with chunked uploads, try WebSockets, or can a standard form post actually cut it? We definitely need real-time progress feedback for the user, and bonus points if it can resume uploads if the connection flakes out.
  3. Backend Black Magic (Video Processing): This is where it gets really spicy. What kind of server-side setup are we even talking about to handle incoming video files? How do we trigger our Python/OpenCV script once a video lands? And the big one: how do we handle a bunch of users uploading and needing processing at the same time without melting the server? Do we need message queues (like RabbitMQ or Kafka)? Or maybe serverless functions (AWS Lambda, Google Cloud Functions) are the way to go for scaling this processing? We definitely need it to be async – take the video, tell the user “got it!”, and do the heavy lifting in the background.
  4. Keeping Users Happy (UX): Nobody likes staring at a frozen screen. How do we keep users in the loop – “Recording…”, “Uploading…”, “Processing…”? And how do we handle errors gracefully so they don’t just see a broken page? A little preview of their video before they send it off would be sweet too.
  5. The Not-So-Fun Stuff (Security/Privacy): This involves user videos, so obviously, privacy and security are massive. What absolutely essential steps do we need to take to keep that video data safe? Any specific privacy considerations we might be missing?

Basically, we’re looking for architectural pointers and technology ideas that can handle this kind of media processing horsepower and bolt onto our existing simple site structure without us having to rebuild the whole darn thing from scratch (unless we totally have to, then tell us!).

–“What did I try?–
I’ve been researching the different components needed: looking into client-side video capture APIs (like getUserMedia), various file upload strategies suitable for large files (e.g., chunked uploads), and potential backend architectures for running Python/OpenCV video analysis scripts (considering options like serverless functions, message queues, or dedicated processing services).
–What I`m expecting?–
I was hoping to find a more established, standard pattern or set of technologies specifically recommended for adding this kind of complex media processing and interaction feature onto a web presence that starts from a very simple/static site structure.
–What actually resulted?–
My research showed that while individual pieces exist, integrating them cohesively and efficiently for performance and scalability (especially with large video files and processing queues) onto a minimal backend infrastructure is a complex architectural challenge with multiple potential approaches, none of which seem straightforward without significant changes. This uncertainty and need for high-level architectural guidance is why I’m asking the question.”

Fill circle area with text input

I’ve a circle of gratitude section on a page.

See here – https://prnt.sc/ut6a7MbqUIoS

The idea is the page will have a input box where user can input there name and when press submit button, the name will be in the box on the right side.

I’ve tried with this –

const canvas = document.getElementById('gratitude-circle');
const ctx = canvas.getContext('2d');
const form = document.getElementById('gratitude-form');
const input = document.getElementById('name-input');

const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const circleRadius = 250;
const minTextGap = 10; // Minimum gap between texts
const names = [];

function clearCircle() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // Draw decorative wreath (stylized circle with leaves)
  ctx.save();
  ctx.beginPath();
  ctx.arc(centerX, centerY, circleRadius, 0, 2 * Math.PI);
  ctx.strokeStyle = '#7bbf8e';
  ctx.lineWidth = 4;
  ctx.shadowColor = '#b8e2c8';
  ctx.shadowBlur = 8;
  ctx.stroke();
  ctx.restore();
  // Draw simple leaf accents (simulate wreath)
  for (let i = 0; i < 24; i++) {
    const angle = (i / 24) * 2 * Math.PI;
    const leafX = centerX + (circleRadius - 18) * Math.cos(angle);
    const leafY = centerY + (circleRadius - 18) * Math.sin(angle);
    ctx.save();
    ctx.translate(leafX, leafY);
    ctx.rotate(angle + Math.PI / 2);
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.quadraticCurveTo(6, 8, 0, 18);
    ctx.quadraticCurveTo(-6, 8, 0, 0);
    ctx.fillStyle = '#b8e2c8';
    ctx.globalAlpha = 0.7;
    ctx.fill();
    ctx.globalAlpha = 1;
    ctx.restore();
  }
  // Draw central message
  ctx.save();
  ctx.font = '28px Segoe UI, Arial';
  ctx.fillStyle = '#7bbf8e';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText('Thank you', centerX, centerY - 28);
  ctx.font = 'bold 32px Segoe UI, Arial';
  ctx.fillStyle = '#4a8c6b';
  ctx.fillText('for being part', centerX, centerY + 4);
  ctx.font = '28px Segoe UI, Arial';
  ctx.fillStyle = '#7bbf8e';
  ctx.fillText('of our story.', centerX, centerY + 36);
  ctx.restore();
}

function drawNames() {
  clearCircle();
  if (names.length === 0) return;
  // Place names along the circumference
  const totalNames = names.length;
  const fontSize = 22;
  ctx.font = 'bold 22px Segoe UI, Arial';
  let totalArcLength = 0;
  let nameArcLengths = [];
  // First, measure arc length for each name
  for (let i = 0; i < totalNames; i++) {
    const name = names[i];
    const textWidth = ctx.measureText(name).width;
    // Arc length = width / radius
    const arc = textWidth / circleRadius;
    nameArcLengths.push(arc);
    totalArcLength += arc;
  }
  // Calculate starting angle so names are centered
  let gap = minTextGap / circleRadius;
  let totalGap = gap * totalNames;
  let startAngle = -totalArcLength / 2 - totalGap / 2;
  let angle = startAngle;
  for (let i = 0; i < totalNames; i++) {
    const name = names[i];
    const arc = nameArcLengths[i];
    const theta = angle + arc / 2;
    const x = centerX + circleRadius * Math.cos(theta);
    const y = centerY + circleRadius * Math.sin(theta);
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(theta + Math.PI / 2);
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillStyle = '#333';
    ctx.fillText(name, 0, 0);
    ctx.restore();
    angle += arc + gap;
  }
}

form.addEventListener('submit', function(e) {
  e.preventDefault();
  const name = input.value.trim();
  if (name && names.length < 100) { // Limit to avoid overfilling
    names.push(name);
    drawNames();
    input.value = '';
  }
});

clearCircle();
body {
  background: #fff7f3;
  font-family: 'Segoe UI', Arial, sans-serif;
  margin: 0;
  padding: 0;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

#gratitude-form {
  margin-bottom: 32px;
  display: flex;
  gap: 12px;
}

#name-input {
  padding: 10px 16px;
  border-radius: 20px;
  border: 1px solid #b2b2b2;
  font-size: 1.1rem;
  outline: none;
}

#gratitude-form button {
  padding: 10px 20px;
  border-radius: 20px;
  border: none;
  background: #7bbf8e;
  color: #fff;
  font-size: 1.1rem;
  cursor: pointer;
  transition: background 0.2s;
}

#gratitude-form button:hover {
  background: #5fa06e;
}

.circle-area {
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}

#gratitude-circle {
  background: transparent;
  display: block;
  border-radius: 50%;
  box-shadow: 0 0 0 2px #e0e0e0;
}
<div class="container">
  <form id="gratitude-form">
    <input type="text" id="name-input" placeholder="Enter your name" autocomplete="off" required />
    <button type="submit">Add Name</button>
  </form>
  <div class="circle-area">
    <canvas id="gratitude-circle" width="600" height="600"></canvas>
  </div>
</div>

It looks like this – https://prnt.sc/ktSamLH1dpOr

Is there any way to develop a dynamic area like this?

How to patch a custom resource in kubernetes using the javascript client

I created a custom resource definition and also added the status subresource:

subresources:
        status: {}

I’m trying to update it with the following code but I’m getting all sorts of errors:

async function setLastSyncedImage(jobsetName, image) {
  let patch = {
    status: {
      lastSyncedImage: image
    }
  }

  await k8sApi.patchNamespacedCustomObjectStatus(
    {
      group: GROUP,
      version: VERSION,
      namespace: NAMESPACE,
      plural: PLURAL,
      name: jobsetName,
      body: patch
    },
    {
      headers: {
        'Content-Type': 'application/merge-patch+json'
      }
    }
  )
}

With that, I’m getting the following error:

'{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"error decoding patch: json: cannot unmarshal object into Go value of type []handlers.jsonPatchOp","reason":"BadRequest","code":400}n'

it seems to ignore the Content-Type header I give it. so if instead I give it the patch like so:

let patch = [{
    "op": "replace",
    "path": "/status/lastSyncedImage",
    "value": image
  }]

That’s the error message I’m getting:

{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"the server rejected our request due to an error in our request","reason":"Invalid","details":{},"code":422}n'

I can’t find any example online that will allow me to patch the status of the resource

Printing a Local Report without Preview

I using visual studio 2022 with MVC NET 8 and C# language and Microsoft reporting service 2016.

I Want to print invoice without preview report using java script.
I have too ID for too type invoice. The first invoice data for cash money
And there’d to delivery invoice it deferent data.
So I need to print invoice by click button depend on invoice type …. Cash or delivery using java script

How to store a light and dark theme with HTML/JS using a dropdown box?

I am currently working on a light and dark theme for a website that several others and I are designing. Currently, I have an html dropdown box that allows you to select a color theme option, and upon selecting it, it automatically changes the theme, which is done through a CSS class being activated or deactivated. However, when you refresh the page it doesn’t remember what was selected.

How would I go about changing this? I’d like to use this “Apply Button” that another person designed if possible. Here’s what I have currently:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Settings</title>
        <link rel="stylesheet" href="/html/css/settings.css">
        <script type="text/javascript" src="/html/js/darkmode.js" defer></script>
    </head>
    <body class="">
        <%include file="navbar.html"/>
        <div class="settings-container">
            <h1>Settings</h1>
    
            <div class="setting">
                <div class="special-text">
                    <label for="dark-mode-select">Color Theme:</label>
                    </div>
                    <select id="dark-mode-select" onchange="changeColor()">
                        <option value="light" id="light">Light</option>
                        <option value="dark" id="dark">Dark</option>
                    </select>
            </div>
    
            <div class="setting">
                <label for="font-size-slider">Font Size:</label>
                <input type="range" id="font-size-slider" min="1" max="100" value="50">
                <span id="font-size-value">50</span>
            </div>
    
            <div class="setting">
                <div class="special-text">
                <label for="profanity-filter">Profanity Filter:</label>
                <input type="checkbox" id="profanity-filter">
            </div>
            </div>
    
            <div class="button-container">
                <button id="apply-settings">Apply</button>
            </div>
        </div>

Color Change JS:

function changeColor(){
    //alert("colorchange")
    let theme = localStorage.getItem('theme')
    //const themeChange = document.getElementById('dark-mode-select')
    const themeChangeDark = document.getElementById('dark').selected
    const themeChangeLight = document.getElementById('light').selected


    const enableDarkmode = () => {
        document.body.classList.add('darkmode')
        localStorage.setItem('theme', 'dark')
    }

    const enableLightmode = () => {
        document.body.classList.remove('darkmode')
        localStorage.setItem('theme', 'light')
    }

    if(theme === "dark") enableDarkmode()



    if(themeChangeDark == true){
        theme = localStorage.getItem('theme')
        enableDarkmode()
    } else if(themeChangeLight == true){
        theme = localStorage.getItem('theme')
        enableLightmode()
    }
}

Apply Button JS:

document.addEventListener("DOMContentLoaded", function () {
    const fontSizeSlider = document.getElementById("font-size-slider");
    const fontSizeValue = document.getElementById("font-size-value");
    const darkModeSelect = document.getElementById("dark-mode-select");
    const profanityFilterCheckbox = document.getElementById("profanity-filter");
    const applyButton = document.getElementById("apply-settings");
    const body = document.body;
    const baseFontSize = 16;



    darkModeSelect.addEventListener("change", function() {
        const colorTheme = this.value;
      });

    function applyStoredSettings() {
        const storedFontSize = localStorage.getItem("fontSize");
        if (storedFontSize) {
            applyFontSize(storedFontSize);
            fontSizeSlider.value = storedFontSize;
            fontSizeValue.textContent = storedFontSize;
        }
        darkModeSelect.value = colorTheme;
        
    }

    function applyFontSize(value) {
        const scaleFactor = value / 50;
        const newFontSize = baseFontSize * scaleFactor;
        fontSizeValue.textContent = value;
        body.style.fontSize = newFontSize + "px";
    }

    fontSizeSlider.addEventListener("input", () => applyFontSize(fontSizeSlider.value));

    applyButton.addEventListener("click", function () {
        localStorage.setItem("fontSize", fontSizeSlider.value);
        localStorage.setItem("theme", colorTheme);
        localStorage.setItem("profanityFilter", profanityFilterCheckbox.checked);
        alert("Settings applied globally!");
    });

    applyStoredSettings();

In the code you can see I’ve tried using local storage to set “theme” as the color chosen in both of the JS files, but it doesn’t seem to actually remember the chosen value.

How to pass a parameter to php file

I want to create an app in which you can drag-and-drop your local file and upload it to a web server.
I made it.
My next challenge is you can upload your file into a different folder depending on who you are.
For example if you are ‘Mr.A’, you upload your file into ‘image/A’ in the server,
on the other hand if you are ‘Mr.B’, you upload your file into ‘image/B’, something like that.
My question is how can you pass a parameter (which indicates who you are) to the PHP file(from index.html to upload.php).
My codes are below.
I mean I want to add a select who you are in ‘index.html’ and pass that parameter to ‘upload.php’.
Is it possible?
If so, can you tell me how?

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>D&D upload</title>
    <link rel="stylesheet" href="style.css">
    <script src="upload.js"></script>
</head>
<body>
  <h1>D&D upload</h1>
    <p id="text_message"></p>
    <section id="dropzone">
      <p>drop your file here</p>
    </section>
</body>
</html>

upload.php


<?php
if( isset($_FILES['uploadFile']) ) {
  if( move_uploaded_file( $_FILES['uploadFile']['tmp_name'], './image/'.$_FILES['uploadFile']['name']) ){
    echo 'true';
  } else {
    echo 'false';
  }
  return;
}
?>

upload.js


function uploadFile(file) {
  const upload_uri = "./upload.php";
  const xhr = new XMLHttpRequest();
  const fd = new FormData();
  let p_element = document.getElementById("text_message");

  xhr.open("post", upload_uri, true);
  xhr.onreadystatechange = function() {
    if( xhr.readyState === 4 && xhr.status === 200) {

      if( xhr.responseText === 'true' ) {
        p_element.textContent = 'success';
      } else {
        p_element.textContent = 'failed';
      }
    }
  };
  fd.append('uploadFile', file);
  xhr.send(fd);
}

window.addEventListener('DOMContentLoaded', function(){

  let dropzone = document.getElementById('dropzone');

  dropzone.addEventListener("dragenter", function(e){
    e.stopPropagation();
    e.preventDefault();
  });

  dropzone.addEventListener("dragover", function(e){
    e.stopPropagation();
    e.preventDefault();
  });

  dropzone.addEventListener("drop", function(e){
    e.stopPropagation();
    e.preventDefault();

    const upload_files = e.dataTransfer.files;

    for(let i=0; i<upload_files.length; i++) {
      uploadFile(upload_files[i]);
    }
  });
});

OS of my web server is Ubuntu 22.04.4 LTS and my php version is PHP 8.3.9
I am waiting for your support.

Issue on iPhone: “Can’t open this page” Error — Triggered During Navigation Menu Events [closed]

Issue Summary: I’ve implemented a three-layer navigation menu on my site. The issue arises after repeated interactions with the menu — the page eventually reloads unexpectedly, and just before the reload, a JavaScript error appears.

Navigation Flow:-

  1. Tap the hamburger menu → Opens Section 1
  2. Click an item in Section 1 → Opens Section 3
  3. Click “Back” → Returns to Section 2
  4. Click an item in Section 2 → Opens Section 3

After repeating this process a few times, when I click on the hamburger/back/close icon, the page reloads unexpectedly (the first time) and throws an error right before reloading (the second time, getting “can’t open this page”).

What I Need: I need help identifying and resolving the issue causing this reload and error. It’s urgent.