TypeError is not a function on what should be a function

I’m attempting to create a reusable callback function for axios post requests based on this answer. The issue I’m running into now is that the destructured callback function is not being recognized in the component I’m attempting to use it in. Here is the component:

const AddParameterTest = ({ params, tankId }) => {

  const [date, setDate] = useState(parseAbsoluteToLocal(moment().format()));
  const [selectedParam, setSelectedParam] = useState(params[0]);
  const [value, setValue] = useState("");
  const valueRef = useRef();
  const { handlePost, status, error, response, loading } = axiosPost();
            ^This should be a function
  const onChange = (e) => {
    setValue(e.target.value);
  };

  const clickHandler = () => {
    const test = {
      param_id: selectedParam.id,
      param_value: value,
      test_date: moment(date).format("YYYY-MM-DD HH:mm:ss"),
      tank_id: tankId
    }
    
    const res = handlePost("api/tests/newTest", test); <--Error here on attempting to click the button
  }

  return (
    <>
      <ParamList params={params} selectedParam={selectedParam} onSelect={setSelectedParam} />
      <ParamValue value={value} onChange={onChange} ref={valueRef} />
      <MyDatePicker aria-label='date' value={date} onChange={setDate} />
      <Button title="Log" onClick={clickHandler} />
    </>
  )
}

export default AddParameterTest

Here is the js file for the util:

export const axiosPost = async () => {
  const [response, setResponse] = useState(null);
  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { token } = useAuth();


  const handlePost = useCallback(async (url, data) => {
    setLoading(true);

    try {
      console.log("Data", data);
      console.log("url", url);
      const res = await axios.post(`${url}`, JSON.stringify(data),
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-type": "application/json"
          }
        }
      )
      
      setResponse(res?.data);
    }
    catch(e) {
      setError(e);
    }
    finally {
      setLoading(false);
    }

  }, []);

  return { handlePost, status, error, response, loading }
}

Still rather messy but hoping that if I can figure out the issue, I can start to clean things up.

Any idea why it won’t recognize the handlePost as a function in the component? Is it even possible and the post I followed above is deprecated?

Infinite loading of skeleton loaders with onload/@load event

I have an issue where the image skeleton loader keeps loading infinitely even though I’m using the @load event in Quasar.

const imgLoaded = ref({});

// template
<q-skeleton v-if="!imgLoaded[img?.image_url]"></q-skeleton>

<q-img @load="(url) => imgLoaded[url] = true" :src="img?.image_url" />

The Quasar docs say that @load event is ‘Emitted when image has been loaded by the browser. @param src – URL of image that has been loaded’. After the handler sets imgLoaded[url] to true, the skeleton should stop showing and the image should be displayed. However, the skeleton keeps loading infinitely.

The same thing is happening with the onload. Now when I need the image url for img.src, I need to take it directly from the store:

// template
<q-skeleton v-if="!imgLoaded[img?.image_url]">

// script
const imgLoaded = ref({});

const onImgLoad = (url) => {
    imgLoaded.value[url] = true;
};

onMounted(() => {
    if (storeProducts.featuredProducts && storeProducts.featuredProducts.length) {
        storeProducts.featuredProducts.forEach((product) => {
            const img = new Image();
            img.onload = () => onImgLoad(product?.image_url);
            img.src = product?.image_url;
        });
    }
});

However, this approach also causes the skeleton loader to load infinitely.

I’m looking for a possible solution.

How would I persist a user’s authentication status across two different ports sitting on localhost using firebase Authentication

How can I transfer the users authentication status from one localhost, say on port 3000 to another localhost service running on port 3001?

I know firebase Authentication typically persists the users authentication across different pages and domain, however I need to pass the current users authentication to a webapp running on a different port but same domain.

React Webapp code:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';

//firebase config stores the data for the database and application. It was removed for security reasons

const app = initializeApp(firebase_conf)
const db = getFirestore(app)
const auth = getAuth(app)


export { db, auth };

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter basename="/peerscribe/webapp">
      <App/>
    </BrowserRouter>
  </React.StrictMode>
);

Website/Raw js code:


// Initialize Firebase app
const app = initializeApp(firebaseConfig);

// Initialize Firestore and Auth
const db = getFirestore(app);
const auth = getAuth(app);

// Set up authentication state observer
function setupAuthObserver() {
    onAuthStateChanged(auth, async (user) => {
        if (user) {
            // Check if email is verified and update Firestore if it has changed
            if (user.emailVerified) {
                const userDocRef = doc(db, 'users', user.uid);

                try {
                    // Get current user data from Firestore
                    const userDoc = await getDoc(userDocRef);

                    // Check if the document exists and email verification status needs updating
                    if (userDoc.exists() && userDoc.data().emailVerified === false) {
                        console.log('Updating email verification status in Firestore');

                        // Update the email verification status
                        await setDoc(userDocRef, {
                            emailVerified: true
                        }, { merge: true });

                        console.log('Email verification status updated successfully');
                    }
                } catch (error) {
                    console.error('Error updating email verification status:', error);
                }
            }
            modifyNavBar();
        }
    });
}

// Initialize the observer when the module loads
setupAuthObserver();

// Nav logic that always uses absolute links:
function modifyNavBar() {
  let anchors = document.querySelector('header').querySelectorAll('a');
  let loglinks = ['#', `http://localhost:3000/peerscribe/webapp/dashboard`];
  let dynamicAnchors = [anchors[3], anchors[4]];// WILL NEED TO BE CHANGED IF MORE NAVLINKS ARE ADDED
  let text = ["logout", "webapp"];
  for (let i = 0;i<dynamicAnchors.length;i++)
  {

    dynamicAnchors[i].setAttribute('href', loglinks[i]);
    dynamicAnchors[i].innerText = text[i];

    if (i == 0){
      dynamicAnchors[i].setAttribute('onclick', 'logout()');
    }
  }      
}

Things I’ve tried:

  • using firebase’s Idtokens (not custom tokens)
  • using cookies
  • passing the firebase authentication object to the other service running on another port.

Everytime I try to retrieve a desired userId from a firebase firestore reference (which has been initialized) it returns the userId just fine. I know the userId and document exists within the firstore collection. I also know that it is seeing and retrieving all of the documents within a collection along with each documents respective data. However, when trying to use the currently authenticated userId (auth.currentUser) on the webapp, it returns null. It should match the userId that was found on the website(not the react app) and use it to compare the fields in each document.

I am very new to React apps, firebase, and how they work so I wouldn’t be surprised if the issue was right in front of me.

datalist shows two visual representations of the dropdown option list

With this datalist generated by the code below, in chrome/edge, I click on the input box, and two dropdowns show up at the same time, like this. What am I doing wrong? it only shows the one list in both Firefox and Safari

https://jsfiddle.net/f0qw9Lmn/

enter image description here

const comboInput = document.getElementById('combo-input');
const datalist = document.getElementById('options');
comboInput.addEventListener('mousedown', function(e) {
  if (datalist.style['display'] == 'block') {
    datalist.style['display'] = 'none';
  } else {
    datalist.style['display'] = 'block';
  }
});
.combo-box {
  position: relative;
  display: inline-block;
}

/* always show arrow, not just on hover */
input::-webkit-calendar-picker-indicator {
  opacity: 100;
  display: inline-block;
}

#options {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  border: 1px solid #ccc;
  border-top: none;
  display: none;
  background-color: #fff;
  z-index: 1;
}

#options option:hover {
  background-color: #eee;
}
<div class="combo-box">
  <input type="text" list="options" id="combo-input"/>
  <datalist id="options" style="display: none;" >
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
    <option value="Option 3">Option 3</option-->
  </datalist>
</div>

Is the JavaScript call stack actually on a stack?

In V8, the engine is responsible for creating the JavaScript runtime call stack, which allows it to track its position within the code. The engine comprises two main components: Ignition, an interpreter that processes bytecode, and TurboFan, a compiler that generates optimized machine code.

My question is: When Ignition interprets bytecode, it utilizes handlers, which are C++ functions corresponding to specific bytecode instructions. Executing these handlers creates a C++ call stack, distinct from the JavaScript function call stack. How do these two stacks coexist in stack memory?

Can’t run packaged Electron/React application

I am trying to produces a Windows application, my main workstation is macOS I packaged the exe file there and tried running it on Windows and I got an error so I tried building it on my Windows machine and the same issue occurred.

  • I am using WebStorm
  • Electron with React
  • Using Electron builder to distribute the app

This is the error:

enter image description here

My package.json file:

{
  "name": "car_rental",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@electron/remote": "^2.1.2",
    "@testing-library/dom": "^10.4.0",
    "@testing-library/jest-dom": "^6.6.3",
    "@testing-library/react": "^16.2.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.8.2",
    "concurrently": "^9.1.2",
    "cross-env": "^7.0.3",
    "electron-is-dev": "^3.0.1",
    "motion": "^12.4.10",
    "react": "^19.0.0",
    "react-calendar": "^5.1.0",
    "react-dom": "^19.0.0",
    "react-router": "^7.3.0",
    "react-scripts": "5.0.1",
    "wait-on": "^8.0.2",
    "web-vitals": "^2.1.4"
  },

  "main": "public/electron.js",
  "homepage": "./",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "electron:serve": "concurrently -k "cross-env BROWSER=none npm run start" "npm run electron:start"",
    "electron:build": "npm run build && electron-builder -c.extraMetadata.main=build/electron.js",
    "electron:start": "wait-on tcp:3000 &&  electron ."

  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "electron": "^35.0.1",
    "electron-builder": "^25.1.8"
  },
  "build": {
    "appId": "your.id",
    "extends": null,
    "files": [
      "dist/**/*",
      "build/**/*",
      "node_modules/**/*",
      "package.json"
    ],
    "directories": {
      "buildResources": "assets"
    }
  }
}

My electron.js file is located in the public folder. This is the content:

const {app, BrowserWindow, Menu} = require("electron");
const isDev = require("electron-is-dev");
const path = require("path");

require("@electron/remote/main").initialize();

function createWindow () {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            devTools: true,
            enableRemoteModule: true
        }, autoHideMenuBar: true,
    });
    Menu.setApplicationMenu(null);

    win.loadURL(isDev ? "http://localhost:3000" : `file://${path.join(__dirname, "../build/index.html")}`);

}

app.whenReady().then(()=>{
    createWindow();
    app.on("activate", () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    })
});

app.on("window-all-closed", () => {
    if (process.platform !== "darwin") {
        app.quit();
    }
})



I would prefer a solution based on macOS so that I could directly package Windows app on my macOS (M1) machine.

Select2 Retrieving Custom Properties using JS

I’m trying to retrieve custom properties from the select2 controls using the method described here:

https://select2.org/programmatic-control/retrieving-selections

I can see it says the following:

Calling select2(‘data’) will return a JavaScript array of objects representing the current selection. Each object will contain all of the properties/values that were in the source data objects passed through processResults and templateResult callbacks.

$('#mySelect2').select2('data');

However, my problem is that for some reason, doing the select2(‘data’) only returns the ID and Text values but does not bring back any other custom properties I set.

My ProcessResults looks like so:

    processResults: function (response) {
        if (!config.serverSide) {
            return {
                results: (response.results || []).map(function (item) {
                    return {
                        id: item[idField],
                        text: item[textField],
                        disabled: item.Disabled === true,
                        dataItem: item <== this is what i'm trying to get.
                    };
                })
            };
        } else {
            return {
                results: (response.Results || []).map(function (item) {
                    return {
                        id: item[idField],
                        text: item[textField],
                        disabled: item.Disabled === true,
                        dataItem: item <== this is what i'm trying to get.
                    };
                }),
                pagination: {
                    more: response.Pagination?.more || false
                }
            };
        }
    }

What’s interesting is that when any sort of event handlers are called, I can see the whole object show up and can also see that the dataItem is available for use.

So doing the following allows me to access my dataItem:

$('#element').on('select2:select', (e) => {
    let data = e.params.data;
    let item = data.dataItem;
});

I’ve tried multiple ways to try and extract the dataItem value using .select2(‘data’) but I just can’t seem to figure out why it doesn’t work.

Any help in figuring out how to access custom properties would be appreciated!

Why can’t I recreate this CryptoJS hashing loop (for AES key derivation) in C?

I am trying to recreate this loop written in JS. From the CryptoJS library, it takes a passphrase and a salt, hashes them 10,000 times (to later derive an AES Key and IV). I believe it is just MD5(passphrase + salt) 10,000 times.

     while (derivedKeyWords.length < keySize) {
                    if (block) {
                        hasher.update(block);
                    }
                    block = hasher.update(password).finalize(salt);
                    hasher.reset();

                    // Iterations
                    for (var i = 1; i < 10000; i++) {
                        block = hasher.finalize(block);
                        hasher.reset();
                    }

                    derivedKey.concat(block);
                }

Simple enough, but when I try to recreate this in C (using OpenSSL’s MD5 function), it gives a different derived key result.

while (sizeof(derivedkey) < keysize) {
    MD5_Init(&ctx5);
    
    if (sizeof(dgest) > 0) {
        MD5_Update(&ctx5, dgest, sizeof(dgest));
    }
    
    MD5_Update(&ctx5, password, sizeof(password));
    MD5_Update(&ctx5, salt, sizeof(salt));
    MD5_Final(dgest, &ctx5);
    
    for (int j = 1; j < 10000; j++) {
            MD5_Init(&ctx5);
            MD5_Update(&ctx5, dgest, sizeof(dgest));
            MD5_Final(dgest, &ctx5);
    }
    strcat(derivedkey, dgest);
    //I've also tried memcpy(derivedkey, dgest, sizeof(dgest));
}

Thanks!

React keeps refreshing my page after a fetch

So i am following an tutorial on an react webapp https://youtu.be/LDB4uaJ87e0?si=8-b0n60EMVbllXxD&t=10012

I am using React 19 and Tailwind 4.0 since i only installed this server on 08-03-2025
until now i got everything working with only some struggles with tailwind 4.0

Made the addJob & deleteJob and now i when i also added the toastify plugin i noticed this will not work when i deleteJob and the problem seems to be in the try to fetch data.

when i commend out this specific code it will work as expected. Normal page navigation will work as expected with or without code commented. No loading favicon then.

Commented code from App.jsx deleteJob

const res = await fetch(`/api/jobs/${id}`, {
      method: "DELETE",
    });

Same goes for addJob:

const res = await fetch("/api/jobs", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(newJob),
    });

when i do not commend this out my whole page will refresh and my console will look like this Console image I stated that it will refresh also by the favicon loading.

This is my App.jsx:

import React from "react";
import {
  Route,
  createBrowserRouter,
  createRoutesFromElements,
  Router,
  RouterProvider,
} from "react-router-dom";
import HomePage from "./pages/HomePage";
import MainLayout from "./layouts/MainLayout";
import JobsPage from "./pages/JobsPage";
import NotFoundPage from "./pages/NotFoundPage";
import JobPage, { jobLoader } from "./pages/JobPage";
import AddJobPage from "./pages/AddJobPage";

const App = () => {
  // Add new Job
  const addJob = async (newJob) => {
    const res = await fetch("/api/jobs", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(newJob),
    });
    return;
  };

  // Delete Job
  const deleteJob = async (id) => {
    const res = await fetch(`/api/jobs/${id}`, {
      method: "DELETE",
    });
    return;
  };

  const router = createBrowserRouter(
    createRoutesFromElements(
      <Route path="/" element={<MainLayout />}>
        <Route index element={<HomePage />} />
        <Route path="/jobs" element={<JobsPage />} />
        <Route path="/add-job" element={<AddJobPage addJobSubmit={addJob} />} />
        <Route
          path="/jobs/:id"
          element={<JobPage deleteJob={ deleteJob } />}
          loader={jobLoader}
        />
        <Route path="*" element={<NotFoundPage />} />
      </Route>
    )
  );
  return <RouterProvider router={router} />;
};

export default App;

JobPage:

import React from "react";
import { useParams, useLoaderData, useNavigate } from "react-router-dom";
import { FaArrowLeft, FaMapMarker } from "react-icons/fa";
import { Link } from "react-router-dom";
import { toast } from "react-toastify";

const JobPage = ({ deleteJob }) => {
  const navigate = useNavigate();
  const { id } = useParams();
  const job = useLoaderData();

  const onDeleteClick = (jobId) => {
    const confirm = window.confirm("Are you sure want to delete this job?");
    if (!confirm) return;

    deleteJob(jobId);
    toast.success("Job deleted!");
    navigate("/jobs");
  };

  return (
    <>
      <section>
        <div className="container m-auto py-6 px-6">
          <Link
            to="/jobs"
            className="text-indigo-500 hover:text-indigo-600 flex items-center"
          >
            <FaArrowLeft className="mr-2" /> Back to Job Listings
          </Link>
        </div>
      </section>

      <section className="bg-indigo-50">
        <div className="container m-auto py-10 px-6">
          <div className="grid grid-cols-1 md:grid-cols-[70%_30%] w-full gap-6">
            <main>
              <div className="bg-white p-6 rounded-lg shadow-md text-center md:text-left">
                <div className="text-gray-500 mb-4">{job.type}</div>
                <h1 className="text-3xl font-bold mb-4">{job.title}</h1>
                <div className="text-gray-500 mb-4 flex align-middle justify-center md:justify-start">
                  <FaMapMarker className="mr-1 text-orange-700" />
                  <p className="text-orange-700">{job.location}</p>
                </div>
              </div>

              <div className="bg-white p-6 rounded-lg shadow-md mt-6">
                <h3 className="text-indigo-800 text-lg font-bold mb-6">
                  Job Description
                </h3>

                <p className="mb-4">{job.description}</p>

                <h3 className="text-indigo-800 text-lg font-bold mb-2">
                  Salary
                </h3>

                <p className="mb-4">{job.salary} / Year</p>
              </div>
            </main>

            {/* <!-- Sidebar --> */}
            <aside>
              {/* <!-- Company Info --> */}
              <div className="bg-white p-6 rounded-lg shadow-md">
                <h3 className="text-xl font-bold mb-6">Company Info</h3>

                <h2 className="text-2xl">{job.company.name}</h2>

                <p className="my-2">{job.company.description}</p>

                <hr className="my-4" />

                <h3 className="text-xl">Contact Email:</h3>

                <p className="my-2 bg-indigo-100 p-2 font-bold">
                  {job.company.contactEmail}
                </p>

                <h3 className="text-xl">Contact Phone:</h3>

                <p className="my-2 bg-indigo-100 p-2 font-bold">
                  {job.company.contactPhone}
                </p>
              </div>

              {/* <!-- Manage --> */}
              <div className="bg-white p-6 rounded-lg shadow-md mt-6">
                <h3 className="text-xl font-bold mb-6">Manage Job</h3>
                <Link
                  to={`/jobs/edit/${id}`}
                  className="bg-indigo-500 hover:bg-indigo-600 text-white text-center font-bold py-2 px-4 rounded-full w-full focus:outline-none focus:shadow-outline mt-4 block"
                >
                  Edit Job
                </Link>
                <button
                  onClick={() => onDeleteClick(job.id)}
                  className="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded-full w-full focus:outline-none focus:shadow-outline mt-4 block"
                >
                  Delete Job
                </button>
              </div>
            </aside>
          </div>
        </div>
      </section>
    </>
  );
};

const jobLoader = async ({ params }) => {
  const res = await fetch(`/api/jobs/${params.id}`);
  const data = await res.json();
  return data;
};

export { JobPage as default, jobLoader };

I pressed delete button on JobPage.jsx and was expected to go to /jobs with an toast.succes notify in right top of my screen. I have searched over 3 hours now without succes. ChatGPT also dont know and keeps telling me my errors come from the form…

Trying to build azure speech program that can transcribe and diarize audio real-time, how do I do this on javascript/html? Can’t find working examples

I specifically am trying to build an application that can run an html-javascript file that can recognize the speech input from a microphone, transcribe it, and assign it to a speaker, continuously until I hit stop.

I have a working code that can transcribe from microphone input well enough, but when I tweaked it so the config would diarize, I only saw it transcribe the text without identifying the speaker, even though I had set the config to diarize, as well.

After I tweaked it to diarize, I wrote this:

<!DOCTYPE html>
<html>

<head>
    <title>Speech Sample</title>
    <meta charset="utf-8" />
    <script type="text/javascript" src="./difflib-browser.js"></script>
</head>

<body style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:13px;">
    <div id="warning">
        <h1 style="font-weight:500;">Speech Recognition Speech SDK not found
            (microsoft.cognitiveservices.speech.sdk.bundle.js missing).</h1>
    </div>
    <div id="content" style="display:none">
        <table>
            <tr>
                <td></td>
                <td>
                    <h2 style="font-weight:500;">Microsoft Cognitive Services Speech SDK</h2>
                    <h3 style="font-weight:500;">Javascript Browser Sample</h3>
                </td>
            </tr>
            <tr>
                <td align="right"><a href="https://www.microsoft.com/cognitive-services/sign-up"
                        target="_blank">Subscription</a>:</td>
                <td><input id="key" type="text" size="60" placeholder="required: speech subscription key"></td>
            </tr>
            <tr>
                <td align="right">Region:</td>
                <td align="left">
                    <select id="regionOptions">
                        <option value="westus" selected="selected">West US</option>
                        <option value="westus2">West US 2</option>
                        <option value="eastus">East US</option>
                        <option value="eastus2">East US 2</option>
                        <option value="eastasia">East Asia</option>
                        <option value="southeastasia">South East Asia</option>
                        <option value="centralindia">Central India</option>
                        <option value="northeurope">North Europe</option>
                        <option value="westeurope">West Europe</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td align="right">Recognition language:</td>
                <td align="left">
                    <select id="languageOptions">
                        <option value="en-US" selected="selected">English - US</option>
                        <!-- Add other languages as desired -->
                    </select>
                </td>
            </tr>
            <tr>
                <td align="right"><b></b></td>
                <td>
                    <button id="scenarioStartButton">Start</button>
                    <button id="scenarioStopButton" disabled="disabled">Stop</button>
                </td>
            </tr>
            <tr>
                <td align="right">Results:</td>
                <td align="left">
                    <textarea id="phraseDiv" style="display: inline-block;width:500px;height:200px"></textarea>
                </td>
            </tr>
            <tr>
                <td align="right">Events:</td>
                <td align="left">
                    <textarea id="statusDiv"
                        style="display: inline-block;width:500px;height:200px;overflow: scroll;white-space: nowrap;">
                    </textarea>
                </td>
            </tr>
        </table>
    </div>

    <!-- Speech SDK REFERENCE -->
    <script src="https://aka.ms/csspeech/jsbrowserpackageraw"></script>

    <!-- Speech SDK presence check -->
    <script>
        function Initialize(onComplete) {
            if (!!window.SpeechSDK) {
                document.getElementById('content').style.display = 'block';
                document.getElementById('warning').style.display = 'none';
                onComplete(window.SpeechSDK);
            }
        }
    </script>

    <script>
        var SpeechSDK;
        var phraseDiv, statusDiv;
        var key, authorizationToken;
        var regionOptions;
        var recognizer;
        
        document.addEventListener("DOMContentLoaded", function () {
            scenarioStartButton = document.getElementById('scenarioStartButton');
            scenarioStopButton = document.getElementById('scenarioStopButton');
            phraseDiv = document.getElementById("phraseDiv");
            statusDiv = document.getElementById("statusDiv");
            key = document.getElementById("key");
            regionOptions = document.getElementById("regionOptions");

            scenarioStartButton.addEventListener("click", function () {
                doContinuousRecognition();
            });

            scenarioStopButton.addEventListener("click", function() {
                if (recognizer) {
                    recognizer.stopContinuousRecognitionAsync();
                }
            });
        });

        function getAudioConfig() {
            return SpeechSDK.AudioConfig.fromDefaultMicrophoneInput();
        }

        function getSpeechConfig() {
            var speechConfig = SpeechSDK.SpeechConfig.fromSubscription(key.value, regionOptions.value);
            speechConfig.setProperty(SpeechSDK.PropertyId.SpeechServiceConnection_EnableSpeakerDiarization, "true"); // Enable speaker diarization
            console.log("Speaker diarization enabled."); // Log confirmation
            return speechConfig;
        }

        function onRecognized(sender, recognitionEventArgs) {
            var result = recognitionEventArgs.result;
            console.log(result); // Log the entire result for debugging
            phraseDiv.scrollTop = phraseDiv.scrollHeight;
        
            var speakerId = result.speakerId ? ` [Speaker ID: ${result.speakerId}]` : '';
        
            statusDiv.innerHTML += `(recognized) Reason: ${SpeechSDK.ResultReason[result.reason]}`;
            phraseDiv.innerHTML += `${result.text}${speakerId}rn`;
        }

        function doContinuousRecognition() {
            var audioConfig = getAudioConfig();
            var speechConfig = getSpeechConfig();
            if (!audioConfig || !speechConfig) return;

            recognizer = new SpeechSDK.SpeechRecognizer(speechConfig, audioConfig);
            recognizer.recognized = onRecognized;

            recognizer.startContinuousRecognitionAsync();
        }

        Initialize(async function (speechSdk) {
            SpeechSDK = speechSdk;
        });
    </script>
</body>

</html>

Client side request for monero-wallet-rpc with credentials

I wonder how to create a axios request from client side for monero-wallet-rpc with –rpc-login credentials because all of my tries are failing with response status code 401. Below is my sample command to run my wallet rpc.

monero-wallet-rpc ^
--testnet ^
--wallet-file C:/monero/testnet_wallet ^
--password "Password" ^
--rpc-bind-port 28083 ^
--daemon-address http://localhost:28081 ^
--rpc-login testuser:testpassword ^
--rpc-access-control-origins "*" ^
--tx-notify "C:/Windows/System32/curl.exe -X POST -H "Content-Type: application/json" -d "{\"txid\":\"%s\"}" http://localhost:3000/api/webhook"

Here is my code within my axios.
Method 1 axios: failed with 401

try {
  const response = await axios.post('http://localhost:28083/json_rpc', {
    jsonrpc: '2.0',
    id: '0',
    method: 'make_integrated_address',
  },
  {
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    },
    auth: {
      username: 'testuser',
      password: 'testpassword'
    }
  });
  const { integrated_address, payment_id } = response.data.result;
  consolelog(integrated_address, payment_id)
} catch (error) {
  console.log('error:', error);
}

Method 2 axios: failed with 401

try {
  const response = await axios.post('http://localhost:28083/json_rpc', {
    jsonrpc: '2.0',
    id: '0',
    method: 'make_integrated_address',
  },
  {
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Authorization': 'Basic ' + Buffer.from('testuser:testpassword').toString('base64')
    }
  });
  const { integrated_address, payment_id } = response.data.result;
  consolelog(integrated_address, payment_id)
} catch (error) {
  console.log('error:', error);
}

Method 3 curl: failed 401

curl -v -u testuser:testpassword 
http://127.0.0.1:28083/json_rpc 
-H "Content-Type: application/json" 
-d '{"jsonrpc":"2.0","id":"0","method":"make_integrated_address","params":{}}'

Method 4 browser: success
So i tried to access it via direct url into browser (http://127.0.0.1:28083/json_rpc), the browser asked me for credentials, after entering the credentials,I got a response. this means i got access but it shows an error because im accessing it without the method and parameters

{
  "error": {
    "code": -32600,
    "message": "Invalid Request"
  },
  "id": 0,
  "jsonrpc": "2.0"
}

Method 4 Run monero RPC without credentials: success
If i run the command disabling the rpc-login, my axios request are working fine.

monero-wallet-rpc ^
--testnet ^
--wallet-file C:/monero/testnet_wallet ^
--password "Password" ^
--rpc-bind-port 28083 ^
--daemon-address http://localhost:28081 ^
--disable-rpc-login ^
--tx-notify "C:/Windows/System32/curl.exe -X POST -H "Content-Type: application/json" -d "{\"txid\":\"%s\"}" http://localhost:3000/api/webhook"

Anyone know why all my method on axios are failing into 401 status code?

useFormContext()’s watch not triggering a re-render

In a const component, I have this watch configured:

const { watch, setValue, control } = useFormContext<QuoteCalculatorValues>();
const fuelCostWatch = watch('fees')?.[fuel_costs]?.[0];
const watchPath = `fees.[fuel_costs][0].`;

‘fees’ is a key/value array, with the following:

export type FormPayableAccessoryFeeDto = {
    quantity: number;
    rate: number;
};

export interface FormPayableAccessoryFeeIndexDto {
    [key: string]: FormPayableAccessoryFeeDto[] | undefined;
}

export type QuoteCalculatorValues = {
    fees: FormPayableAccessoryFeeIndexDto;
};

Here’s an input I configured to be monitored by the watch

<Controller
    name={`fees.[fuel_costs][0].quantity`}
    control={control}
    render={({ field }) => (
        <Input
          field={field}
          defaultValue={0}
          onChange={value => {
            setValue(`fees.[fuel_costs][0].quantity`, value as never);
          }}
        />
      )}
/>

I’m expecting that because I’m watch‘ing values in fee, when I change the value in the input, the component should re-render.

One thing I noticed, is that in onChange, I have to cast value as never, which might indicate a problem I guess ?

I tested this with a more basic structure (ex: if I watch('info') and create an input on info.firstName) and this works.

Is there a problem with the way my form data’s structured ?

Can’t find button using playwright (or puppeteer) for web scraping

There are many similar questions (like this: Scraping Websites With Playwright), yet I did not find and solution to this:

I have this url:
https://www.derstandard.at/search?n=&fd=2025-02-17&td=2025-03-06&s=score&query=apple

Which leads to a page that looks like this.
enter image description here

I’m interested in the number 71 (that is circled in red). I think much of the content is server-rendered or somehow fetched. I first tried Rselenium as I’m more familiar with R. Yet, on my arm mac, I could not connect to the server on localhost…

I now am using playwright with node to somehow get this number. Yet I am still failing. My script looks like this:

const { firefox } = require("playwright");

(async () => {
  // Launch Firefox in headless mode
  const browser = await firefox.launch({ headless: false });
  const page = await browser.newPage();

  // Navigate to the website
  const url =
    "https://www.derstandard.at/search?n=&fd=2025-02-17&td=2025-03-06&s=score&query=ukraine";
  await page.goto(url, { waitUntil: "domcontentloaded" });

  // Check if the button exists before trying to click
  const buttonSelector = ".message-component";
  if (await page.$(buttonSelector)) {
    console.log("Clicking the button...");
    await page.click(buttonSelector);
    await page.waitForTimeout(2000); // Wait a bit for content to update
  } else {
    console.log("Button not found, continuing...");
  }

  // Extract all <h1> elements
  const h1s = await page.evaluate(() =>
    Array.from(document.querySelectorAll("h1")).map((el) => el.innerText.trim())
  );

  console.log("Extracted <h1> elements:", h1s);

  // Close the browser
  await browser.close();
})();

As I am prompted with this site first:
enter image description here

As I have to click the left button first to get to this site…
However, I can’t access this button either:/

If anyone has any idea on how I programatically can get this number, that would be very very much appreciated!:)

selecting a city doesn’t populate the area dropdown in my subarea form in Laravel 11

I have created City, Area, Subarea Crud in Laravel 11.
where city and area are simple are working correctly but the subarea blade in add form
when city is selected then why respected areas to that city is not show in dropdown of area. I check and use ChatGPT solution in my blade ajax script and try almost every solution but the problem not solved. if you need any code part to understand problem then I can provide that but I want a exact solution of my problem.

the laravel blade :


`@extends('layouts.app')
@section('content')
    <div class="main-content app-content">
        <div class="container-fluid">
            <!-- Page Header -->
            <div class="d-md-flex d-block align-items-center justify-content-between my-4 page-header-breadcrumb">
                <h1 class="page-title fw-semibold fs-18 mb-0">{{ isset($subarea) ? 'Edit Sub Area' : 'Add Sub Area' }}</h1>
                <div class="ms-md-1 ms-0">
                    <nav>
                        <ol class="breadcrumb mb-0">
                            <li class="breadcrumb-item">Route Management</li>
                            <li class="breadcrumb-item active" aria-current="page">Subarea</li>
                        </ol>
                    </nav>
                </div>
            </div>
            <!-- Form and List -->
            <div class="container">
                <div class="row">
                    <!-- Add/Edit Form -->
                    <div class="col-xl-6">
                        <div class="card custom-card">
                            <div class="card-body">
                                <form
                                    action="{{ isset($subarea) ? route('subareas.update', $subarea->id) : route('subareas.store') }}"
                                    method="POST">
                                    @csrf
                                    @if (isset($subarea))
                                        @method('PUT')
                                    @endif

                                    <div class="mb-3">
                                        <label for="city-dropdown" class="form-label fs-14 text-dark">City</label>
                                        <select id="city-dropdown" name="city_id"
                                            class="form-control js-example-basic-single">
                                            <option value="">Select a City</option>
                                            @foreach ($cities as $city)
                                                <option value="{{ $city->id }}"
                                                    {{ isset($subarea) && $subarea->city_id == $city->id ? 'selected' : '' }}>
                                                    {{ $city->city_name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="area-dropdown" class="form-label fs-14 text-dark">Area</label>
                                        <select id="area-dropdown" name="area_id" class="form-control js-example-basic-single">
                                            <option value="">Select an Area</option>
                                            @if(isset($subarea))
                                                @foreach($subarea->city->areas as $area)
                                                    <option value="{{ $area->id }}" 
                                                        {{ $subarea->area_id == $area->id ? 'selected' : '' }}>
                                                        {{ $area->area_name }}
                                                    </option>
                                                @endforeach
                                            @endif
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="form-text" class="form-label fs-14 text-dark">Sub Area Name</label>
                                        <input type="text" class="form-control" id="form-text" name="sub_area_name"
                                            value="{{ old('sub_area_name', isset($subarea) ? $subarea->sub_area_name : '') }}"
                                            placeholder="Sub Area Name">
                                    </div>

                                    <button class="btn btn-primary"
                                        type="submit">{{ isset($subarea) ? 'Update' : 'Add' }}</button>
                                </form>
                            </div>
                            <div class="card-footer d-none border-top-0"></div>
                        </div>
                    </div>

                    <!-- Right Side List of Saved Sub Areas -->
                    <div class="col-xl-6">
                        <div class="card custom-card">
                            <div class="card-body">
                                <h5 class="card-title">Saved Sub Areas</h5>
                                <div class="table-responsive">
                                    <table class="table text-nowrap">
                                        <thead>
                                            <tr>
                                                <th scope="col">City</th>
                                                <th scope="col">Area</th>
                                                <th scope="col">Sub Area</th>
                                                <th scope="col">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($subareas as $subarea)
                                                <tr>
                                                    <td>{{ $subarea->city->city_name }}</td>
                                                    <td>{{ $subarea->area->area_name }}</td>
                                                    <td>{{ $subarea->sub_area_name }}</td>
                                                    <td>
                                                        <div class="hstack gap-2 fs-15">
                                                            <a href="{{ route('subareas.edit', $subarea->id) }}"
                                                                class="btn btn-icon btn-sm btn-info-light m-1">
                                                                <i class="ri-edit-line"></i>
                                                            </a>
                                                            <form method="POST"
                                                                action="{{ route('subareas.destroy', $subarea->id) }}">
                                                                @csrf
                                                                @method('DELETE')
                                                                <button type="submit"
                                                                    class="btn btn-icon btn-sm btn-danger-light m-1">
                                                                    <i class="ri-delete-bin-line"></i>
                                                                </button>
                                                            </form>
                                                        </div>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection



`This is My script to populate areas dropdown after city is selected`
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="../assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script>
    $(document).ready(function() {
        $('.js-example-basic-single').select2();

        // Handle city change
        $('#city-dropdown').on('change', function() {
            var cityId = $(this).val();
            var areaDropdown = $('#area-dropdown');
            
            areaDropdown.empty().append('<option value="">Loading...</option>');
            
            if (cityId) {
                $.ajax({
                    url: "{{ route('get-areas', '') }}/" + cityId,
                    type: 'GET',
                    success: function(data) {
                        areaDropdown.empty()
                            .append('<option value="">Select an Area</option>');
                        $.each(data, function(index, area) {
                            areaDropdown.append(new Option(area.area_name, area.id));
                        });
                        areaDropdown.trigger('change');
                    },
                    error: function(xhr) {
                        console.error('Error:', xhr.responseText);
                        areaDropdown.empty().append('<option value="">Error loading areas</option>');
                    }
                });
            }
        });

        // Trigger initial load if editing
        @if(isset($subarea))
            $('#city-dropdown').trigger('change');
        @endif
    });
</script>

Any help is much appreciated!




I tried ChatGPT But it waste my many time I can't find exact solution ChatGPT says me that check select2 and jquery load before script of ajax. I do this but not solved my problem. Then I try to change ajax query :

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="../assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script>
    $(document).ready(function() {
        $('.js-example-basic-single').select2();

        // Handle city change
        $('#city-dropdown').on('change', function() {
            var cityId = $(this).val();
            var areaDropdown = $('#area-dropdown');
            
            areaDropdown.empty().append('<option value="">Loading...</option>');
            
            if (cityId) {
                $.ajax({
                    url: "{{ route('get-areas', '') }}/" + cityId,
                    type: 'GET',
                    success: function(data) {
                        areaDropdown.empty()
                            .append('<option value="">Select an Area</option>');
                        $.each(data, function(index, area) {
                            areaDropdown.append(new Option(area.area_name, area.id));
                        });
                        areaDropdown.trigger('change');
                    },
                    error: function(xhr) {
                        console.error('Error:', xhr.responseText);
                        areaDropdown.empty().append('<option value="">Error loading areas</option>');
                    }
                });
            }
        });

        // Trigger initial load if editing
        @if(isset($subarea))
            $('#city-dropdown').trigger('change');
        @endif
    });
</script>`

but this not solve my problem.

How do make this script work with firebase and github?

I’m working on a project that involves connecting my script code for a community form to Firebase and GitHub, but I’m running into some issues and could use some guidance. I was told that Firebase was the best free option for global storage, but I couldn’t make it work properly. I have the SDK setup properly but the rest of script I’m not sure.

const usernames = [
    "HappyTiger", "BraveElephant", "GentlePanda", "CuriousDolphin", "KindRabbit"
];

async function assignUsername() {
    let deviceId = localStorage.getItem("deviceId");
    if (!deviceId) {
        deviceId = "device_" + Math.random().toString(36).substr(2, 9);
        localStorage.setItem("deviceId", deviceId);
    }

    const userRef = db.collection("users").doc(deviceId);
    const doc = await userRef.get();

    if (doc.exists) {
        localStorage.setItem("username", doc.data().username);
    } else {
        const newUsername = usernames[Math.floor(Math.random() * usernames.length)];
        await userRef.set({ username: newUsername });
        localStorage.setItem("username", newUsername);
    }
}

async function submitPost() {
    const title = document.getElementById("post-title").value.trim();
    const content = document.getElementById("post-content").value.trim();
    const imageInput = document.getElementById("post-image");
    const username = localStorage.getItem("username") || "AnonymousUser";

    if (!title || !content) return;

    const reader = new FileReader();
    reader.onload = async function(event) {
        await db.collection("posts").add({
            title,
            content,
            image: imageInput.files.length ? event.target.result : "",
            likes: 0,
            username,
            timestamp: firebase.firestore.FieldValue.serverTimestamp()
        });
        loadPosts();
    };

    if (imageInput.files.length) {
        reader.readAsDataURL(imageInput.files[0]);
    } else {
        reader.onload();
    }
}

async function loadPosts() {
    const postsContainer = document.getElementById("posts");
    postsContainer.innerHTML = "";

    const querySnapshot = await db.collection("posts").orderBy("timestamp", "desc").get();
    querySnapshot.forEach((doc) => {
        const post = doc.data();
        const postId = doc.id;
        const currentUsername = localStorage.getItem("username") || "AnonymousUser";
        const isOwner = post.username === currentUsername;
        const isLiked = localStorage.getItem(`liked_${postId}`) === "true";

        const postElement = document.createElement("div");
        postElement.classList.add("forum-post");
        postElement.innerHTML = `
            <h3>${post.title}</h3>
            <p>${post.content}</p>
            <p><strong>Posted by:</strong> ${post.username}</p>
            ${post.image ? `<img src="${post.image}" class="forum-image">` : ''}
            <button onclick="likePost('${postId}')" ${isLiked ? "disabled" : ""}>${post.likes} Likes</button>
            ${isOwner ? `<button onclick="deletePost('${postId}')">Delete</button>` : ""}
        `;

        postsContainer.appendChild(postElement);
    });
}

async function likePost(postId) {
    const postRef = db.collection("posts").doc(postId);

    const doc = await postRef.get();
    if (doc.exists && !localStorage.getItem(`liked_${postId}`)) {
        const currentLikes = doc.data().likes || 0;
        await postRef.update({ likes: currentLikes + 1 });
        localStorage.setItem(`liked_${postId}`, "true");
        loadPosts();
    }
}

async function deletePost(postId) {
    const postRef = db.collection("posts").doc(postId);
    const doc = await postRef.get();
    if (doc.exists && doc.data().username === localStorage.getItem("username")) {
        await postRef.delete();
        loadPosts();
    }
}

document.addEventListener("DOMContentLoaded", async function() {
    await assignUsername();
    loadPosts();
});