While index.html does not give an error, javascript gives an error when index.php is processed

I don’t get any errors in index.html, but when I do index.php I get the error:
sidebarmenu.js:88 uncaught typeerror: Cannot read properties of null (reading ‘closest’)
At htmldocument. (sidebarmenu.js:88:33)

Line 88:
Var closestnav = elements. Closest(“nav[class^=sidebar-nav]”);

Why don’t I get an error in index.html? Why do I get an error in index.php and the sidebar is broken?

iOS Shortcut “Run Javascript on webpage” to scrape Mastercard Conversion rates

first of all I want to say that my programming knowledge is very basic, therefore I use GPT a lot, also this is my first stackoverflow question, so my explainging could be better. That said, I am trying to make an iOS shortcut that inputs 4 different values into a Mastercard Conversion rate web “https://www.mastercard.com.ar/es-ar/consumidores/soporte/convertidor-moneda.html” to later scrape the exchange rate and add it to a Numbers spreadsheet (I think those last 2 steps wont be a problem). The problem I am having is that the first field is overwritten from ARS to EUR and the 3rd is left empty, however, if i erase step 3 from the code (see code below), it works perfectly (obviously 3rd field is left empty).
This is the code i managed to get:

// Step 1: Set the "From" Currency to ARS
var fromDropdownButton = document.getElementById('tCurrency');
fromDropdownButton.click(); // Open the dropdown menu for "From" currency
var fromOptions = document.querySelectorAll('ul.dropdown-menu li a');
for (let option of fromOptions) {
    if (option.textContent.includes('ARS')) { // Match the "ARS" currency
        option.click(); // Select "ARS"
        break;
    }
}

// Step 2: Set the "Amount" to 10000
var amountField = document.getElementById('txtTAmt');
if (amountField) {
    amountField.value = "10000"; // Input the amount
    amountField.dispatchEvent(new Event('input', { bubbles: true })); // Trigger input event
}

// Step 3: Set the "To" Currency to EUR
var toDropdownButton = document.getElementById('cardCurrency');
toDropdownButton.click(); // Open the dropdown menu for "To" currency
var toOptions = document.querySelectorAll('ul.dropdown-menu li a');
for (let option of toOptions) {
    if (option.textContent.includes('EUR')) { // Match the "EUR" currency
        option.click(); // Select "EUR"
        break;
    }
}

// Step 4: Set the "Bank Fee" to 0
var bankFeeField = document.getElementById('BankFee');
if (bankFeeField) {
    bankFeeField.value = "0"; // Input the bank fee
    bankFeeField.dispatchEvent(new Event('input', { bubbles: true })); // Trigger input event
}

// Completion message
completion("Form filled successfully: From=ARS, Amount=10000, To=EUR, Bank Fee=0");

Thank you in advance to anyone who offers help :).

My WordPress site’s menu on the mobile version doesn’t appear, it’s an empty square [closed]

I created a website on WordPress for a client. In the mobile version, the menu button is not showing up, it is an empty square. When I click on it, the menu options are all white and there is no writing on them.

I tried to change the CSS code myself with the help of AI, but I am not able to do it because I do not understand anything about programming and even following the step-by-step instructions suggested by AI and making the changes, it does not change anything.

enter image description here

why if condition inside else doesnt run?

function validategender() {
  var gender = $('.gender').val();
  if ($(".gender:checked").length > 1 || $(".gender:checked").length == 0) {
    $('#gendercheck').text("select a gender");
    return false;
  } else {
    if ($(".gender:checked").length == 1) {
      $('#gendercheck').text("");
      return true;
    }
    return false;
  }
}

for some reason after the else is checked the if inside else aint working

fullcalendar v6 cdn script initialisation event sources format ics not loading

I am trying to load ics files in fullcalendar I inserted on my html page via script tags from the premium bundle scheduler as of the official documentation https://fullcalendar.io/docs/initialize-globals#premium-bundle

Now I want to load events from public ics files with this sample code. Unfortunately as you can see in the code snippet, no holiday is displaying from any of the 2 public ics files and no error in my console is displaying.

What am I missing in my code to make the holidays appear in the calendar?

<!DOCTYPE html>
<html lang='en'>
  <head>
    <meta charset='utf-8' />
    <script src='https://cdn.jsdelivr.net/npm/[email protected]/index.global.min.js'></script>
    <script>
          document.addEventListener('DOMContentLoaded', function() {
            var calendarEl = document.getElementById('calendar');
            var calendar = new FullCalendar.Calendar(calendarEl, {
                schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
                initialView: 'dayGridMonth',
                locale: 'fr',
                buttonText: {
                    today: 'Aujourd’hui',
                    day: 'jour',
                    week:'semaine',
                    month:'mois'
                },
                eventSources: [
                    {
                    url: "https://www.gov.uk/bank-holidays/england-and-wales.ics",
                    format: "ics",
                    },
                    {
                        url: 'https://calendar.google.com/calendar/ical/fr.french%23holiday%40group.v.calendar.google.com/public/basic.ics',
                        format: 'ics'
                    }
                ]                
            });
            calendar.render();
          });
    
    </script>
  </head>
  <body>
    <div id='calendar'></div>
  </body>
</html>

Merci pour votre aide

How to activate a border when selecting an image? [closed]

I have the following code, I want that when selecting any of the 4 images that are in the container image, a border is activated for its container so that the user can see that this image is selected, and the border is removed if the user clicks again , about it, I already implemented the code to make it work but it doesn’t work, I don’t know much about code, so I don’t know how to solve it

add in the css the .image-conainer.selected and there add the border to call it when an image is selected but it doesn’t work

How to set specific data into FormData?

How to send data to the server (Django Rest Framework) so that the server receives data in this format:

{
   "key":"value",
   "key_aray":[
      "key":"value",
      "files":[
         {
            "key":"value",
            "file":"File"
         }
      ]
   ]
}

Without files I could wrap everything in an object and JSON.stringify(object). But with files I can’t do that.

Global SaSS import / Use Vite 6 SaSS 1.83

So I recently updated my react project dependency and I’m having an issue with SaSS.

Before the update I was importing a SaSS file in Vite’s config file like so:

css: {
preprocessorOptions: {
  scss: {
    additionalData: `@import 'src/mixins.scss';`,
  },
},

According to this article the @import statement have been deprecated in SaSS 1.83, therefore I changed it to: additionalData: @use “src/mixins.scss” as *;, instead.

This worked fine until I updated Vite to version 6.0.4.. When running the App I get an error saying that could not find the src/mixins.scss file.

    [plugin:vite:css] [sass] Can't find stylesheet to import.
  ╷
1 │ @use "src/mixins.scss" as *;
  │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵
  

    src/App.scss 1:1  root stylesheet

So to recap, when running the latest version of Sass with Vite 5.4.0 it works fine with the @use statement in Vite’s config file, however in Vite 6.0.4 it does not work and I get the Can’t find stylesheet to import. error mentioned above.

Any help would be greatly appreciated.

Thanks

Upgrading tcp server connection to tls in Deno

I tried to upgrade a tcp connection to tls in deno in my http server but it doesnt work and i cant find any solutions online, just more people with my issue.

I tried using Deno.startTls, but its client only. I tried with ffi with a rust program (made by ChatGPT) which also didn’t work. I dont want to use a node module because i like the level of control in Deno.TcpConn and i dont want to proxy it or use a proxy service (like NGINX) as i need protocol level control.

Why is the datetime attribute not defined on HTMLTimeElement in JavaScript?

When working with DOM elements in JavaScript, HTML attributes generally become properties of the corresponding JavaScript HTML object. However, there are exceptions to this rule, such as class and data-attributes.

That said, I don’t understand why the datetime attribute seems to cause an issue. Specifically, why is datetime not defined on the HTMLTimeElement type?

As a result, I’m forced to use the generic method setAttribute('datetime', ...);.

Can someone explain why this happens?

React Query Mutation Updates Database but Fails to Re-Render Button Text Dynamically

I’m making a web app with simillar functionalities to this one where I’m trying to get data from the backend and change the text of a button according to that boolean.

The issue, is even though the data in the backend is correctly updating and console shows no errors, the text of the button is not updating from “validate” to unvalidate”.
A quick console.log of the authUser?.climbedRoutes?.includes(route._id) always prints false (I checked the mongodb and the id is correctly in the authUser’s climbedRoutes array)

This is how I’m doing the check in my Voie.jsx page:

import React from "react";
import { useParams } from "react-router-dom";
import { QueryClient, useQuery, useQueryClient, useMutation } from "@tanstack/react-query";

import useValidate from "../../hooks/useValidate";

const VoiePage = () => {
  const { id } = useParams();
  const { data: authUser } = useQuery({ queryKey: ["authUser"] });

  const { data: route, isLoading, isError } = useQuery({
    queryKey: ["voie", id],
    queryFn: async () => {
      try {
        const res = await fetch(`/api/routes/voie/${id}`);
        const data = await res.json();
        if (!res.ok) {
          throw new Error(data.error || "Something went wrong");
        }
        return data;
      } catch (error) {
        throw new Error(error.message);
      }
    },
  });


  const { validate, isLoading: isPending } = useValidate();

  if (isLoading) {
    return <div className="text-white">Loading...</div>;
  }

  if (isError) {
    return <div className="text-red-500">Error loading route.</div>;
  }

  return (
            <button
              className="btn btn-outline rounded-full btn-md"
              onClick={() => validate(id)}
            >
              {isPending && "Validating..."}
              {!isPending && (authUser?.climbedRoutes?.includes(route._id) ? "Validated" : "Validate")}
              {console.log(authUser?.climbedRoutes)}
            </button>
  );
};

export default VoiePage;

UseValidate is a hook I am importing:

import { useMutation, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";

const useValidate = () => {

    const queryClient = useQueryClient();

    const { mutate: validate, isPending } = useMutation({
        mutationFn: async (id) => {
            try {
                const res = await fetch(`/api/routes/validate/${id}`, {
                    method: "POST",
                });
                if (!res.ok) {
                    throw new Error("Something went wrong");
                }
                return await res.json();
            } catch (error) {
                throw new Error(error.message);
            }
        },
        onSuccess: () => {
            Promise.all([
                queryClient.invalidateQueries(["routes"]),
                queryClient.invalidateQueries(["authUser"]),
            ]);
            toast.success("Route validated successfully");
        },
        onError: (error) => {
            toast.error(error.message);
        }
    })
    return { validate, isPending };
}

export default useValidate;

How to handle event on data label in Vue Chart.js?

This is my chart component and I want to handle events on labels I define in data. I would like to show the tooltip with bar data when I hover on a label.

my bar chart

<template>
  <Bar :data="data" :options="options" />
</template>

<script setup>
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  BarElement,
  CategoryScale,
  LinearScale
} from 'chart.js'
import { Bar } from 'vue-chartjs'

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)

export const data = {
  labels: [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ],
  datasets: [
    {
      label: 'Data One',
      backgroundColor: '#f87979',
      data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11]
    }
  ]
}
export const options = {
  responsive: true,
  maintainAspectRatio: false
}
</script>

Snippet:
https://stackblitz.com/github/apertureless/vue-chartjs/tree/main/sandboxes/bar?file=src%2FchartConfig.ts

How to capture system/tab audio in FlutterFlow for transcription with Whisper API?

I’m trying to capture audio playing from a browser tab (system audio) in a FlutterFlow web app, record it, and then send it to OpenAI’s Whisper API for transcription. However, I’ve run into several issues:

Using getDisplayMedia with {audio: true, video: true} does not show the “Share audio” checkbox in the browser prompt. Without selecting “Share audio,” no audio track is provided by the MediaStream.

I tried multiple browsers (Chrome, Edge, Brave) and different mime types (audio/webm; codecs=opus, audio/ogg; codecs=opus) to ensure compatibility with the MediaRecorder and Whisper API.

Even when a recording is produced, it either contains no audio track or fails to be recognized by the Whisper API due to format issues.

The core issue: I need a reliable way to capture the system or tab audio so that I can record it and send it to Whisper for transcription directly in FlutterFlow’s environment.

Is there a known workaround or a best practice for capturing system (or tab) audio in FlutterFlow apps running on the web? Has anyone successfully managed to include the “Share audio” option consistently or found another approach for capturing system audio?

TabAudioListenerButton (Custom Widget)

// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/backend/schema/structs/index.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/widgets/index.dart'; // Imports other custom widgets
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom widget code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'dart:html' as html;
import 'dart:js_util' as js_util;
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:http/http.dart' as http;
import 'dart:convert';

class TabAudioListenerButton extends StatefulWidget {
  final void Function()? onAudioStreamObtained;
  final void Function(String error)? onError;

  /// Callback called after transcription is available (once recording stops)
  final void Function(String transcription)? onTranscriptionUpdate;

  final double? width;
  final double? height;

  const TabAudioListenerButton({
    Key? key,
    this.onAudioStreamObtained,
    this.onError,
    this.onTranscriptionUpdate,
    this.width,
    this.height,
  }) : super(key: key);

  @override
  _TabAudioListenerButtonState createState() => _TabAudioListenerButtonState();
}

class _TabAudioListenerButtonState extends State<TabAudioListenerButton> {
  html.MediaStream? _mediaStream;
  Object? _mediaRecorder;
  bool _isRecording = false;
  List<dynamic> _chunks = [];

  @override
  void dispose() {
    _stopRecording();
    super.dispose();
  }

  Future<html.MediaStream?> getDisplayMedia() async {
    final mediaDevices = html.window.navigator.mediaDevices;
    if (mediaDevices == null) return null;

    try {
      // Récupérer uniquement l'audio du micro
      final constraints = {'audio': true, 'video': true};

      final stream = await js_util.promiseToFuture<html.MediaStream?>(
          js_util.callMethod(mediaDevices, 'getDisplayMedia', [constraints]));
      return stream;
    } catch (e) {
      widget.onError?.call(e.toString());
      return null;
    }
  }

  Future<void> _startCaptureAndRecord() async {
    if (!kIsWeb) {
      widget.onError?.call('Not running on web platform.');
      return;
    }

    final mediaStream = await getDisplayMedia();
    if (mediaStream != null) {
      setState(() {
        _mediaStream = mediaStream;
      });
      widget.onAudioStreamObtained?.call();
      _startRecording();
    } else {
      widget.onError?.call('Failed to get media stream.');
    }
  }

  void _startRecording() {
    if (_mediaStream == null || _mediaStream!.getAudioTracks().isEmpty) {
      widget.onError?.call('No audio track found.');
    }

    String mimeType = 'audio/webm; codecs=opus';
    bool isSupported = js_util.callMethod(
        js_util.getProperty(html.window, 'MediaRecorder'),
        'isTypeSupported',
        [mimeType]) as bool;
    if (!isSupported) {
      mimeType = 'audio/ogg; codecs=opus';
      isSupported = js_util.callMethod(
          js_util.getProperty(html.window, 'MediaRecorder'),
          'isTypeSupported',
          [mimeType]) as bool;
      if (!isSupported) {
        widget.onError?.call('No supported mimeType found.');
        return;
      }
    }

    _chunks.clear();

    final mediaRecorder = js_util
        .callConstructor(js_util.getProperty(html.window, 'MediaRecorder'), [
      _mediaStream,
      {
        'mimeType': mimeType,
      }
    ]);

    js_util.setProperty(mediaRecorder, 'ondataavailable',
        js_util.allowInterop((event) {
      final chunk = js_util.getProperty(event, 'data');
      if (chunk != null) {
        _chunks.add(chunk);
      }
    }));

    js_util.setProperty(mediaRecorder, 'onstop',
        js_util.allowInterop((event) async {
      if (_chunks.isNotEmpty) {
        final blob =
            js_util.callConstructor(js_util.getProperty(html.window, 'Blob'), [
          _chunks,
          {'type': mimeType}
        ]);

        // Téléchargement du blob
        final url = html.Url.createObjectUrl(blob);
        final anchor = html.document.createElement('a') as html.AnchorElement;
        anchor.href = url;
        anchor.download = 'audio_recording.webm';
        html.document.body!.append(anchor);
        anchor.click();
        anchor.remove();
        html.Url.revokeObjectUrl(url);

        final arrayBuffer = await js_util
            .promiseToFuture(js_util.callMethod(blob, 'arrayBuffer', []));
        final bytes = Uint8List.view((arrayBuffer as ByteBuffer));

        final transcription = await transcribeAudioChunk(bytes);
        if (transcription != null && transcription.isNotEmpty) {
          widget.onTranscriptionUpdate?.call(transcription);
        }
        _chunks.clear();
      }
    }));

    js_util.callMethod(mediaRecorder, 'start', []);

    setState(() {
      _mediaRecorder = mediaRecorder;
      _isRecording = true;
    });
  }

  void _stopRecording() async {
    if (_mediaRecorder != null) {
      js_util.callMethod(_mediaRecorder!, 'stop', []);
    }
    _mediaStream?.getTracks().forEach((track) => track.stop());

    setState(() {
      _mediaRecorder = null;
      _mediaStream = null;
      _isRecording = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    final isCapturing = _mediaStream != null && _isRecording;
    Widget content = ElevatedButton(
      onPressed: isCapturing ? _stopRecording : _startCaptureAndRecord,
      style: ElevatedButton.styleFrom(
        backgroundColor: isCapturing ? Colors.red : Colors.green,
      ),
      child: Icon(
        isCapturing ? Icons.stop : Icons.play_arrow,
        color: Colors.white,
      ),
    );

    if (widget.width != null || widget.height != null) {
      content = SizedBox(
        width: widget.width,
        height: widget.height,
        child: Center(child: content),
      );
    } else {
      content = Center(child: content);
    }

    return content;
  }

  Future<String?> transcribeAudioChunk(Uint8List audioData) async {
    const openaiApiKey = "YOUR_OPENAI_API_KEY";
    final uri = Uri.parse('https://api.openai.com/v1/audio/transcriptions');
    final request = http.MultipartRequest('POST', uri);
    request.headers['Authorization'] = 'Bearer $openaiApiKey';
    request.files.add(http.MultipartFile.fromBytes('file', audioData,
        filename: 'audio.webm'));
    request.fields['model'] = 'whisper-1';

    final response = await request.send();

    if (response.statusCode == 200) {
      final respStr = await response.stream.bytesToString();
      final jsonResp = json.decode(respStr) as Map<String, dynamic>;
      return jsonResp['text'] as String?;
    } else {
      final respStr = await response.stream.bytesToString();
      print('Error transcribing audio: ${response.statusCode} - $respStr');
      return null;
    }
  }
}

What have I tried ?

Tried getDisplayMedia with various constraint combinations (video: false, audio: true and video: true, audio: true) on multiple browsers.

Tried filtering out video tracks and only using audio tracks from the MediaStream.

Attempted changing mime types for the MediaRecorder, checking MediaRecorder.isTypeSupported for audio/webm; codecs=opus and audio/ogg; codecs=opus.

Attempted to record both continuous streams and chunks, as well as sending the entire recorded blob to the Whisper API after recording.

Verified that the downloaded recorded file either has no audio track or isn’t properly recognized by Whisper.

Experimented with getUserMedia to capture microphone audio but that doesn’t work and doesn’t solve the requirement of capturing system or tab audio.

enter image description here

enter image description here

enter image description here

How to fix issue with array and method ‘push’?

My code: (typescrypt)

userRouter.post('/', (req, res) => {const newUser = { 
id: +(new Date()), 
name: req.body.name, 
email: req.body.email, 
password: req.body.password
}
usersDB.push(newUser:)        
res.status(201).send(newUser) })`

MyArray:

export const usersDB = [
   {id: "1", name: "Max", email: "[email protected]", password: "123"},
{id: "2", name: "Anne", email: "[email protected]", password: "123"}]

Issue in VScode:
screenshot

I tried to add types for each element of array by different ways, but I hadn’t any benefit

How to generate a p12 with javascript generated key pair and server side internal CA

I’m working on a client-certificate based authentication of users for a website.

The server configuration part is OK
(Apache server, keywords: SSLCACertificateFile / SSLVerifyDepth / SSLVerifyClient optional)

The server code part is OK too:

  • I’m getting the client certificate’s data (serial, DN etc),
  • if the user is logged in (login+password), he’s proposed to register the client-certificate his browser provided
  • if he does, he won’t need to enter login+password again, his client-certificate will be his open sesame
    (based on testing client certificate serial/DN against serial/DN stored into DB at registering time).
  • he is free to unregister the certificate anytime from within his profile page, he just has to be logged in (even from a browser without certificate, with log+pass).

So far, so good.

Now I’d like to simplify the process for the users, so they don’t have to bother creating/purchasing their certificates.
I’d like to let them download a certificate from an internal CA.
I’m not totally sure about the way I imagine this process, as described below:

  • a “generate client certificate” button is proposed for logged in users
  • on click, a key pair is generated client side, using Web Crypto API: crypto.subtle.generateKey()
  • the public key is then ajax-sent to the browser
  • … here some server side magic (1) …
  • the server returns a certificate signed by a dedicated internal intermediate CA,
  • … here some client side magic (2) …
  • the user now has a .p12 keystore containing the downloaded certificate and the private key (which has never been sent outside of the client).
  • he just has to install it in his browser (or host system)

About “magic (1)” :
I want the CSR generation done server side.
But I don’t have the client private key to sign the CSR.
I’ve read here and there, it’s not a problem, I can sign a CSR with a dummy private key, then generate the final certificate from this CSR using the force_pubkey flag
(e.g. https://security.stackexchange.com/a/185202)
So this is my first question: is this practice acceptable? otherwise what are the security risks involved?
I mean, nobody should be able to do anything with this certificate except my user, who is the only one having the private key corresponding to this certificate… any security flaw I haven’t seen here?

About “magic (2)”:
At that point, I have:

  • the locally generated private key, strictly kept locally
  • its corresponding public key, which we previously sent to the server
  • a certificate for this public key, signed server side by the internal CA
    Now I haven’t found anything yet, neither on Mozilla’s Web Crypto API documentation nor anywhere else, about this apparently simple question:
    How can I, with javascript, gather the private key and the certificate together into a .p12 or .pfx keystore?