Images array with random starting point and fade ins needs smoother transitions

I have a full screen slideshow of four images (in an array) that loads/starts at a random image then cycles through the rest of the images with fade ins. My problem is the fade ins do not fade over the previous image, but fades in from white (or a background color if/when added). I would like a crossfade wherein new image and current image fade smoothly in and out respectively, but I’m at a loss. I can create a crossfading slideshow without a random starting point, so I’m familiar with javascript to CSS, but the javascript code that I’ve stitched together for the added random start has me flailing. I’ve spent hours on stack overflow going through similar issues but none have done the job. My ignorance in javascript is definitely an issue, but I’m usually capable enough to get done what I need to get done. Any help is greatly appreciated, with JS fiddles and-or notes if possible. Thanks in advance, code as follows:

const images = [
  "hero-1.jpg",
  "hero-2.jpg",
  "hero-3.jpg",
  "hero-4.jpg",
];

const imgElement = document.getElementById("myImage");

let currentIndex;

function fadeInImage(index) {
  imgElement.style.opacity = 0;
  imgElement.src = images[index];
  let opacity = 0;
  imgElement.style.opacity = opacity;

  const intervalId = setInterval(() => {
    opacity += 0.01;
    imgElement.style.opacity = opacity;

    if (opacity >= 1) {
      clearInterval(intervalId);
    }

  }, 20);

  currentIndex = index;

}

function playImages() {
  let randomIndex = Math.floor(Math.random() * images.length);
  fadeInImage(randomIndex);

  setInterval(() => {
    currentIndex = (currentIndex + 1) % images.length;
    fadeInImage(currentIndex);
  }, 5000);
}

playImages();
body,
html {
  height: 100%;
  margin: 0;
  padding: 0px;
  outline: none;
  border: 0px;
}

.homehero {
  height: 100%;
}

.homehero img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}
<div class="homehero"><img id="myImage" alt="" /></div>

chart.js stacked bar with dynamic values ​and long data labels with a line below the text [closed]

I need to get the value from the previous page url parameter to calculate and display the value in the dynamic chart. It can make a vertical stacked bar chart like the image below. And I want every bar to have a line and an icon including the dynamic value of the bar extending to the right and press the popup to see more details.
Should I code in chart.js? Does anyone have any suggestions? or plugin wordpress

enter image description here

How to run Laravel queue on the production server?

I have used the queue job in my Laravel project to send emails to multiple users. My code is working perfectly on the local system, but on the production server, when I run the queue:work command, it shows a 504 Gateway Timeout error and the server is crashing.

How to solve this problem on the production server?

video post linkedin api Did my video release succeed or fail?

I am trying to upload videos using LinkedIn API V2 and everything is going smoothly without any errors. According to the LinkedIn API, it returns 201. The postResponse resource returns 1. But there is no update on my platform, I don’t know which step went wrong? Now there’s no clue about troubleshooting at all.Please help.
This is my code

<?php
// Example of LinkedIn API video upload and publishing dynamics

//
$accessToken = '{Token}';
$personURN = 'urn:li:person:{URN}'; // URN

//
$videoFilePath = $_FILES['file']['tmp_name'];
$videoFileSize = filesize($videoFilePath);
$videoMimeType = mime_content_type($videoFilePath);

// Step 1: Initialize upload
$initUploadUrl = 'https://api.linkedin.com/rest/videos?action=initializeUpload';

$initHeaders = [
    'Authorization: Bearer ' . $accessToken,
    'Content-Type: application/json',
    'X-Restli-Protocol-Version: 2.0.0',
    'LinkedIn-Version: 202405' // 
];

$initData = [
    'initializeUploadRequest' => [
        'owner' => $personURN,
        'fileSizeBytes' => $videoFileSize,
        'uploadCaptions' => false,
        'uploadThumbnail' => false
    ]
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $initUploadUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($initData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $initHeaders);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode !== 200) {
    die('Initialization upload failed: ' . $response);
}

$initResponse = json_decode($response, true);
$uploadUrl = $initResponse['value']['uploadInstructions'][0]['uploadUrl'];
$videoAsset = $initResponse['value']['video'];

// Step 2: Upload video files
$uploadHeaders = [
    'Authorization: Bearer ' . $accessToken,
    'Content-Type: ' . $videoMimeType,
    'X-Restli-Protocol-Version: 2.0.0'
];

$videoFile = fopen($videoFilePath, 'r');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uploadUrl);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $videoFile);
curl_setopt($ch, CURLOPT_INFILESIZE, $videoFileSize);
curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);

$uploadResponse = curl_exec($ch);
$uploadHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

fclose($videoFile);

if ($uploadHttpCode !== 201 && $uploadHttpCode !== 200) {
    die('Video upload failed: ' . $uploadResponse);
}

// Step 3: Create a dynamic that includes a video
$postUrl = 'https://api.linkedin.com/rest/posts';

$postData = [
    'author' => $personURN,
    'commentary' => 'This is the dynamic description text of my video', // describe
    'visibility' => 'PUBLIC', // PUBLIC, CONNECTIONS
    'distribution' => [
        'feedDistribution' => 'MAIN_FEED',
        'targetEntities' => [],
        'thirdPartyDistributionChannels' => []
    ],
    'content' => [
        'media' => [
            'title' => 'My video title',
            'id' => $videoAsset
        ]
    ],
    'lifecycleState' => 'PUBLISHED',
    'isReshareDisabledByAuthor' => false
];

$postHeaders = [
    'Authorization: Bearer ' . $accessToken,
    'Content-Type: application/json',
    'X-Restli-Protocol-Version: 2.0.0',
    'LinkedIn-Version: 202405'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeaders);

$postResponse = curl_exec($ch);
$postHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);
print_r($postHttpCode);
print_r($postResponse);
if ($postHttpCode === 201) {
    echo 'Video dynamic release successful!';
} else {
    echo 'Posting dynamic failed: ' . $postResponse;
}
?>

The information returned by the interface is:2011Video dynamic release successful!
Why is the platform not displaying? Where did my problem lie?How should I adjust?

What is the best way to parse such files & use variables as well as their values? [closed]

//file1.php
<?php $config['english']['login'] = "login here";
$config['english']['logout'] = "logout";

//file2.php
<?php $anotherVar['english']['varone'] = "Some text in var one";
$anotherVar['english']['vartwo'] = "Some text in var two";

Now, consider a whole bunch of files with data like this. The variables can be anyting!

I need to create similar files for other languages.

I can use eval(), parse the file & explode with “=” etc. but the variable values can be in multiple lines, and some lines could be commented out, etc., which is a big headache if i just parse using file_get_contents or with file

What is the best way to achieve what i want?
I want to list all such variables from a given list of files in “english”
And then, for each file, I want to take the value of each variable in the file and then write out to files in other directories, replacing ‘english’ with ‘german’ in the variable name, for example, ( for ‘german’, i will do an api call to google translate & get the german translated text, for example)

Edited:
What i have tried so far: read file contents with every line into an array, and explode it with ‘=’, and then include the files as well & do an eval() , and get the German text etc. Very ugly way to do it. Am sure that there is a better way.

I have inherited this where for, english, for example, the strings are stored in the examples I have given above. Gettext or storing the strings in a database would have been better, but, sadly, this is what i have!

EDIT2
What I finally want to achieve is to write out to new files like this:

//file1German.php
<?php $config['german']['login'] = "login here (text actually translated to German)";
$config['english']['logout'] = "logout(text actually translated to German)";

//file2German.php
<?php $anotherVar['english']['varone'] = "Some text in var one(text actually translated to German)";
$anotherVar['english']['vartwo'] = "Some text in var two(text actually translated to German)";

PHP Mail Form Not Sending All Fields [duplicate]

I began using a short template to create a PHP Mail Form for a quick way of getting volunteer information. However, each time I attempt to add new fields: Phone, Address and Help (checkboxes) they don’t come through via PHP mail.

Instead they show up blank, but the email does go through.

I’ve swapped out $php_id for $id, as well as eliminated ajax. Neither worked. Additionally, I attempted using “id” vs ‘ajax_id’ and that would not make any difference.

I’m sure this is something stupid that I just don’t understand, but I would appreciate any assistance you could provide so I can get this up and running for a friend.

HTML:

<form action="/" method="post" class="contact_form" id="contact_form">
<div class="returnmessage" data-success="Your message has been received, We will contact you soon."></div>
<div class="empty_notice"><span>Please Fill Required Fields</span></div>
                <div class="first">
                <ul>
                <li>
                <input id="name" type="text" placeholder="Name">
                </li>
                <li>
                <input id="phone" type="tel" placeholder="Phone">
                </li>
                <li>
                <input id="email" type="email" placeholder="Email">
                </li>
                <li>
                <input id="address" type="text" placeholder="Address">
                </li>
                </ul>
                How can you help?<br>
                <p>
                <label>
<input type="checkbox" name="help" value="doors" id="help_0">Knock Doors</label>
                <br>
                <label>
<input type="checkbox" name="help" value="bank" id="help_1">Phone Bank</label>
                <br>
                <label>
<input type="checkbox" name="help" value="sign" id="help_2">Host Yard Sign</label>
                <br>
                <label>
<input type="checkbox" name="help" value="fund" id="help_3">Plan Fundraiser</label>
                <br>
                <label>
<input type="checkbox" name="help" value="meet" id="help_4">Set Up Meet and Greet</label>
                <br>
                </p><br>
                </div>
                <div class="last">
                <textarea id="message" placeholder="Message"></textarea>
                </div>
                <div class="grax_tm_button">
                <a id="send_message" href="#">Send Message</a>
                            </div>
                        </form>


PHP:

<?php

// Put contacting email here
$php_main_email = "[email protected]";

//Fetching Values from URL
$php_name = $_POST['ajax_name'];
$php_phone = $_POST["phone"];
$php_email = $_POST['ajax_email'];
$php_address = $_POST["address"];
$php_help = $_POST["help"];
$php_message = $_POST['ajax_message'];


//Sanitizing email
$php_email = filter_var($php_email, FILTER_SANITIZE_EMAIL);


//After sanitization Validation is performed
if (filter_var($php_email, FILTER_VALIDATE_EMAIL)) {
    
    
        $php_subject = "FORM SUBMITTAL";
        
// To send HTML mail, the Content-type header must be set
        $php_headers = 'MIME-Version: 1.0' . "rn";
        $php_headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
        $php_headers .= 'From:' . $php_email. "rn"; // Sender's Email
        
        $php_template = '<div style="padding:50px;"> ' . 
        '<strong style="color:#012345;">Name:</strong>  ' . $php_name . '<br/>'
        . '<strong style="color:#f00a77;">Phone:</strong>  ' . $php_phone . '<br/>'
        . '<strong style="color:#012345;">Email:</strong>  ' . $php_email . '<br/>'
        . '<strong style="color:#f00a77;">Address:</strong>  ' . $php_address . '<br/>'
        . '<strong style="color:#f00a77;">Help:</strong>  ' . $php_help . '<br/>'
        . '<strong style="color:#012345;">Message:</strong>  ' . $php_message . '<br/><br/>'
        . 'This is a Contact Confirmation mail.'
        . '<br/>'
        . 'We will contact you as soon as possible .</div>';
        $php_sendmessage = "<div style="background-color:#f5f5f5; color:#333;">" . $php_template . "</div>";
        
        // message lines should not exceed 70 characters (PHP rule), so wrap it
        $php_sendmessage = wordwrap($php_sendmessage, 70);
        
        // Send mail by PHP Mail Function
        mail($php_main_email, $php_subject, $php_sendmessage, $php_headers);
        echo "";
    
    
} else {
    echo "<span class='contact_error'>* Invalid email *</span>";
}

?>

I can not import any components from my own React component library

I am developing a component library for the components we use in common in our projects.For now only one button has been added.

-> main_folder -> lib -> Button -> index.jsx

export function Button(){
    return <button>Deneme</button>
}

-> main_folder -> lib -> main.js

export { Button } from './components/Button/index.jsx'

I’m getting build with Vite with library mode

-> main_folder -> vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from 'path';

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  build: {
    lib: {
      entry: resolve(__dirname, 'lib/main.js'),
      name: 'salaui',
      formats: ['es']
    },
    rollupOptions: {
      external: ['react', 'react-dom', 'react/jsx-runtime'],
    }
  }
})

and this is my package.json

{
  "name": "salaui",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint .",
    "preview": "vite preview",
    "prepublishOnly": "npm run build"
  },
  "dependencies": {
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "salaui": "file:"
  },
  "devDependencies": {
    "@eslint/js": "^9.21.0",
    "@types/react": "^19.0.10",
    "@types/react-dom": "^19.0.4",
    "@vitejs/plugin-react": "^4.3.4",
    "eslint": "^9.21.0",
    "eslint-plugin-react-hooks": "^5.1.0",
    "eslint-plugin-react-refresh": "^0.4.19",
    "globals": "^15.15.0",
    "vite": "^6.2.0"
  },
  "main": "dist/salaui.js",
  "files": [
    "dist"
  ]
}

I have a problem like this, when I add the button () I created to a project I created using vite, I can work smoothly, but when I add it to an old project, I cannot use it. I get the following error;

Objects are not valid as a React child (found: object with keys {$$typeof, type, key, props, _owner, _store}). If you meant to render a collection of children, use an array instead.

  • This is from old project (webpack)

enter image description here

this is webpack.dev.js used in this old project

const { merge } = require('webpack-merge');
const common = require('./webpack.common');

module.exports = merge(common, {
  mode: 'development',
  devtool: 'source-map',
  devServer: {
    port: 3100,
    https: true,
    host: 'localhost',
    historyApiFallback: true,
    hot: true,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
      'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization'
    }
  }
});
  • This is from new project (vite)

enter image description here

Could someone help me figure it out? Thanks a lot!

route optimization api shipmentIndex undefined

I’m using the Route Optimization API, but I’m noticing that I’m not getting all my points and that the missing delivery doesn’t have a shipmentIndex.

import { NextResponse } from 'next/server';
import { GoogleAuth } from 'google-auth-library';

const getOptimizedRoutes = async () => {
    try {
        // Setup autenticación para Google API
        const auth = new GoogleAuth();

        const projectId = process.env.GOOGLE_CLOUD_PROJECT_ID;
        const authClient = await auth.getClient();
        const token = await authClient.getAccessToken();

        // Coordenadas de Urvet México (punto de inicio/fin)
        const warehouseLat = 20.7014147;
        const warehouseLng = -103.4553225;

        // Clientes de ejemplo con coordenadas distribuidas en Guadalajara
        // Asegurando que ninguno tenga las mismas coordenadas que el almacén
        const exampleClients = [
            { id: 1, name: "Cliente 1", lat: 20.6597, lng: -103.3496 },  // Centro de Guadalajara
            { id: 2, name: "Cliente 2", lat: 20.6753, lng: -103.3868 },  // Zapopan
            { id: 3, name: "Cliente 3", lat: 20.6408, lng: -103.3249 },  // Tlaquepaque
            { id: 4, name: "Cliente 4", lat: 20.6169, lng: -103.2778 },  // Tonalá
            { id: 5, name: "Cliente 5", lat: 20.6934, lng: -103.4212 }   // Cerca de Urvet pero diferente
        ];

        // Log de clientes originales
        console.log('Clientes originales:', exampleClients.map(c => ({
            id: c.id,
            name: c.name,
            coordenadas: `${c.lat}, ${c.lng}`
        })));

        // Crear shipments con IDs únicos
        const shipments = exampleClients.map((client, index) => ({
            // ID único para cada shipment
            label: `Cliente-${client.id}`,
            deliveries: [
                {
                    arrivalLocation: {
                        latitude: client.lat,
                        longitude: client.lng
                    },
                    duration: "300s"
                }
            ],
            // Agregando algunos campos extras
            loadDemands: {
                weight: {
                    amount: "50"  // 50 kg
                }
            }
        }));

        // Crear vehículo con configuración adecuada
        const vehicles = [
            {
                startLocation: {
                    latitude: warehouseLat,
                    longitude: warehouseLng
                },
                endLocation: {
                    latitude: warehouseLat,
                    longitude: warehouseLng
                },
                // Campos adicionales para mejor optimización
                costPerKilometer: 1.0,
                costPerHour: 30.0,
                loadLimits: {
                    weight: {
                        maxLoad: "1000"  // 1000 kg
                    }
                }
            }
        ];

        const requestBody = {
            model: {
                shipments,
                vehicles,
                globalStartTime: {
                    seconds: Math.floor(Date.now() / 1000)
                },
                globalEndTime: {
                    seconds: Math.floor(Date.now() / 1000) + (8 * 60 * 60)
                }
            },
            // Opciones adicionales para mejor optimización
            considerRoadTraffic: true,
            populateTransitionPolylines: true,
            searchMode: "RETURN_FAST"
        };

        console.log('Request a la API:', JSON.stringify(requestBody, null, 2));

        const response = await fetch(
            `https://routeoptimization.googleapis.com/v1/projects/${projectId}:optimizeTours`,
            {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token.token}`,
                    'Content-Type': 'application/json',
                    'x-goog-user-project': projectId
                },
                body: JSON.stringify(requestBody)
            }
        );

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`Error en la API de Google: ${response.status} - ${errorText}`);
        }

        const result = await response.json();
        
        // Log de la respuesta de la API para debug
        console.log('Respuesta de la API:', JSON.stringify(result, null, 2));
        
        // Mapear visitas de vuelta a los clientes usando los índices de shipment
        const clientsInRoutes = [];
        const visitedShipmentIndices = new Set();
        
        // Procesar todas las visitas de todas las rutas
        result.routes.forEach((route, routeIndex) => {
            console.log(`Ruta ${routeIndex + 1}:`);
            
            route.visits.forEach((visit, visitIndex) => {
                // Verificar si esta visita corresponde a un shipment (cliente)
                if (visit.shipmentIndex) {
                    const clientIndex = visit.shipmentIndex - 1;
                    if (clientIndex >= 0 && clientIndex < exampleClients.length) {
                        visitedShipmentIndices.add(clientIndex);
                        clientsInRoutes.push(exampleClients[clientIndex]);
                        
                        console.log(`  Visita ${visitIndex + 1}: Cliente ${exampleClients[clientIndex].id} (${exampleClients[clientIndex].name})`);
                    } else {
                        console.warn(`  Visita ${visitIndex + 1}: Índice de cliente inválido - ${clientIndex}`);
                    }
                } else {
                    console.warn(`  Visita ${visitIndex + 1}: No tiene shipmentIndex`);
                }
            });
        });
        
        // Encontrar clientes que no fueron visitados
        const missingClients = exampleClients.filter((client, index) => 
            !visitedShipmentIndices.has(index)
        );
        
        // Crear el formato de respuesta final
        const routes = result.routes.map((route, index) => {
            // Extraer solo los clientes de esta ruta basado en los shipmentIndex
            const routeClients = route.visits
                .filter(visit => visit.shipmentIndex)
                .map(visit => {
                    const clientIndex = visit.shipmentIndex - 1;
                    if (clientIndex >= 0 && clientIndex < exampleClients.length) {
                        return exampleClients[clientIndex];
                    }
                    return null;
                })
                .filter(Boolean);
                
            // Crear waypoints para esta ruta
            const waypoints = [
                // Punto inicial (depósito)
                {
                    location: [warehouseLng, warehouseLat],
                    client: "Urvet México",
                    weight: 0
                },
                // Clientes en esta ruta
                ...routeClients.map(client => ({
                    location: [client.lng, client.lat],
                    client: client.name,
                    id: client.id,
                    weight: 50 // Peso fijo de ejemplo
                })),
                // Punto final (depósito)
                {
                    location: [warehouseLng, warehouseLat],
                    client: "Urvet México",
                    weight: 0
                }
            ];
            
            return {
                vehicle_id: `Vehículo ${index + 1}`,
                waypoints: waypoints,
                clients: routeClients,
                totalClients: routeClients.length
            };
        });

        // Asegurar que todos los clientes estén asignados a una ruta
        if (missingClients.length > 0) {
            console.warn('¡ADVERTENCIA! Clientes faltantes:', missingClients.map(c => ({
                id: c.id,
                name: c.name,
                coordenadas: `${c.lat}, ${c.lng}`
            })));
        } else {
            console.log('¡ÉXITO! Todos los clientes han sido incluidos en las rutas.');
        }

        return {
            success: true,
            routes: routes,
            summary: {
                totalClients: exampleClients.length,
                totalRoutes: routes.length,
                clientsPerRoute: routes.map(r => ({
                    vehicle: r.vehicle_id,
                    clientCount: r.totalClients,
                    clients: r.clients.map(c => c.id)
                })),
                missingClients: missingClients.length > 0 ? missingClients.map(c => ({
                    id: c.id,
                    name: c.name,
                    coordinates: [c.lng, c.lat]
                })) : []
            }
        };
    } catch (error) {
        console.error('Error en optimización de rutas:', error);
        throw error;
    }
}

export async function GET() {
    try {
        const result = await getOptimizedRoutes();
        return NextResponse.json(result);
    } catch (error) {
        console.error('Error en el procesamiento:', error);
        return NextResponse.json({
            success: false,
            error: error.message
        }, { status: 500 });
    }
} 

Ruta 1:
Visita 1: Cliente 4 (Cliente 4)
Visita 2: Cliente 1 (Cliente 1)
Visita 3: No tiene shipmentIndex
Visita 4: Cliente 2 (Cliente 2)
Visita 5: Cliente 3 (Cliente 3)
¡ADVERTENCIA! Clientes faltantes: [ { id: 5, name: ‘Cliente 5’, coordenadas: ‘20.6934,
-103.4212’ } ]

How to Export Chart Data from React Plotly.js to Excel on Button Click?

I’m developing a React application with multiple charts using the Plotly.js library. I want to implement a feature where users can download the data used to generate the charts in an Excel file.

Currently, I have a button labeled “Export to Excel”, and when it’s clicked, I want the underlying data (that was used to render the chart) to be downloaded as an Excel file.

What I’ve tried:
I know that Plotly.js exposes the chart data via plotly.react or plotly.js’s data property.

I’ve explored libraries like xlsx to create Excel files, but I’m facing error after installing the dependencies since we are using vite in the application.

What I need help with:
How can I extract the data from Plotly.js (e.g., the traces) and format it into a downloadable Excel file when the user clicks the “Export to Excel” button?

If you have any specific code snippets or examples using xlsx or other libraries to achieve this, that would be helpful.

Additional Notes:

The charts are created dynamically, so I want to ensure that the data changes are captured at the moment the export button is clicked.

I am using react-plotly.js as the wrapper for Plotly in React.

If possible, I’d like to keep the export process as simple as possible.

The component is getting dragged when i try to select the text – React

<LabelCard
      identifier={identifier}
      type={LabelType.Default}
      defaultPosition={defaultPosition}
      $expandedOffset={expandedOffset}
      locked={locked}
      selectedToolTypeProp={selectedToolType}
      isExpanded={isExpanded}
      originalPosRef={originalPosRef}
      cardRef={cardRef}
    >
      <Content ref={cardRef}>
        <Title selected={isSelected}>{title}</Title>
        {!isMobile && <SubTitle selected={isSelected}>({subtitle})</SubTitle>}
        {isMobile && isExpandable && (
          <InfoButton onClick={onExpand}>
            <Icon name={Icons.Info} selected={isExpanded} />
          </InfoButton>
        )}
        {description.length > 0 && (
          <DescriptionContent
            ref={descriptionRef}
            expanded={isExpanded}
            expandedHeight={expandedHeight}
          >
            <Description>{description}</Description>
          </DescriptionContent>
        )}
      </Content>
</LabelCard>

This is my component where we render LabelCard inside which i have a hook responsible for dragging.
inside this hook i have mouseDown function:

function mouseDown(e: { clientX: number; clientY: number }) {
      if (!card) {
        return;
      }

      startX = e.clientX;
      startY = e.clientY;
      initialX = card.offsetLeft;
      initialY = card.offsetTop;

      document.addEventListener('mousemove', mouseMove);
      document.addEventListener('mouseup', mouseUp);
    }

I tried to check:

if (cardRef?.current && cardRef.current.contains(e.target as Node)) {
        return;
      }

This prevents dragging even when i click on some blank space. This blank space is typically part of the text itself like whitespace so maybe thats why i can not drag the label altogether even when i am not clicking on text.
Is there any solution to prevent dragging when i am selecting the text? while also being able to drag when i click on the blank space?
(I also tried to check if click was on TEXT NODE but it seems as it is not able to differentiate between text and space).

Two simultaneously events in Javascript [closed]

I have two simultaneously events

document.addEventListener("DOMContentLoaded", function() {
 Array.from(popUps).forEach((el, index) => {
  const listener = () => {
        let trParent = el.parentNode;
        popUpsChilds[index].classList.toggle("show");
        tableThMain.classList.toggle("toggle-goods-popup-for-head");
        el.classList.toggle("toggle-goods-popup-for-cell");
        trParent.classList.toggle("tr-height");
       
    }

    el.addEventListener("mouseover", listener, false);
    el.addEventListener("mouseout", listener, false);
 });
});

Sometimes, when page may be is not loaded completely, “mouseout” couldn’t happen. But i’ve putted DOMContentLoaded event.
What should I do with it?

Query Selector Ref in React returns empty NodeList when trying to access children element

I have some content that I dynamically inject onto the DOM using dangerously set inner HTML. When I reference it using a Ref, and query it, the NodeList is always empty, but when I look at the just sidebarContent.current, the NodeList is not empty.

Why does this happen?

import React, { useEffect, useState } from 'react';

const PostSideBar = ({ sidebarContent }) => {
    const [childNodes, setChildNodes] = useState([]);

    useEffect(() => {
        if (sidebarContent.current) {
            const h2Elements = sidebarContent.current.querySelectorAll('h2');
            setChildNodes(h2Elements);
            console.log(h2Elements); // Check the h2 elements
        }
    }, [sidebarContent]);

    return <div>PostSideBar</div>;
};

export default PostSideBar;

conerting text to worshiptools format using javascript

Im trying to use javascript to convert ultimate guitar.com formatting to worshiptools/chordpro as im going to use the javascript code in gdevelop5 to make a webapp for my church to utilise

I tried writing it many ways but its not exactly putting the text inline but my code outputs only

[G]           [D]          [Em]
Amazing grace, how sweet the sound
[G]          [D]           [C]
That saved a wretch like me

i Tried This

function convertUltimateGuitarToWorshipTools(ultimateGuitarText) {
    // Split input text into lines (songs may have multiple lines of chords/lyrics)
    const lines = ultimateGuitarText.split('n');

    const worshipToolsText = lines.map(line => {
        // This pattern finds the chords, which are typically words in uppercase or lowercase
        const chordPattern = /b([A-G][#b]?(m|maj|min|sus|dim|aug)?)b/g;
        
        // Replace each found chord with the WorshipTools format (i.e., [chord] )
        return line.replace(chordPattern, (match, chord) => {
            return `[${chord}]`;
        });
    }).join('n'); // Join the lines back into a single string

    return worshipToolsText;
}

// Example Ultimate Guitar input (with chords above the lyrics)
const ultimateGuitarText = `
G           D          Em
Amazing grace, how sweet the sound
G          D           C
That saved a wretch like me
`;

// Convert the Ultimate Guitar text to WorshipTools format
const worshipToolsText = convertUltimateGuitarToWorshipTools(ultimateGuitarText);

// Output the converted text
console.log(worshipToolsText);

but i need this to be the output

[G]Amazing grac[D]e, how swee[Em]t the sound
[G]That saved [D]a wretch lik[C]e me

Read data from RFID card reader connected to serial port

I am trying to read data from RFID card reader connected to serial port using javascript’s Web Serial API. I was able to connect to my card reader but the data logged doesn’t seem to be from my console logs. How do I capture this data.

Serial port

Here is the code that I am using.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Serial Data Reader</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        #status {
            font-size: 16px;
        }
        #serial-data {
            font-size: 18px;
            font-weight: bold;
            color: green;
        }
    </style>
</head>
<body>
    <h1>Serial Data from COM Port</h1>
    
    <button id="connectBtn">Connect to Device</button>
    <p id="status">Not connected</p>
    <p id="serial-data">Waiting for data...</p>

    <script>
        let port;
        let reader;
        let writer;
        let inputDone;
        let inputStream;
        let outputStream;

        const statusElement = document.getElementById('status');
        const serialDataElement = document.getElementById('serial-data');
        const connectButton = document.getElementById('connectBtn');

        // Request permission to access the serial device and open it
        async function connectToDevice() {
            try {
                port = await navigator.serial.requestPort(); // Request the user to select a serial port
                console.log("Port selected:", port); // Log port information
                await port.open({ baudRate: 9600 }); // Open the serial port (adjust baud rate if needed)

                // Setup the input and output streams
                inputStream = port.readable;
                outputStream = port.writable;
                inputDone = inputStream.getReader();

                statusElement.textContent = `Connected to ${port.getInfo().usbVendorId}:${port.getInfo().usbProductId}`;

                // Start reading data from the device
                readSerialData();
            } catch (err) {
                console.error('Error accessing serial port:', err);
                statusElement.textContent = 'Error: Could not connect to device';
            }
        }

        // Read data from the serial port
        async function readSerialData() {
            try {
                // Continuously read data from the device
                while (true) {
                    const { value, done } = await inputDone.read(); // Read the data
                    if (done) {
                        console.log("Stream done");
                        break;
                    }
                    
                    // Log the raw data for debugging
                    console.log("Raw data received:", value);

                    // Check if the value is valid, and decode if it's a valid Uint8Array
                    if (value && value.length > 0) {
                        const receivedData = new TextDecoder().decode(value); // Decode the data
                        console.log("Decoded data:", receivedData); // Log the decoded data
                        serialDataElement.textContent = receivedData.trim(); // Show the data in the frontend
                    } else {
                        console.warn("Empty data received");
                    }
                }
            } catch (err) {
                console.error('Error reading from the serial port:', err);
                statusElement.textContent = 'Error: Failed to read data';
            }
        }

        // Set up the button to connect to the device
        connectButton.addEventListener('click', () => {
            statusElement.textContent = 'Connecting to device...';
            connectToDevice();
        });
    </script>
</body>
</html>

The output:

Select port

Data from card reader

The data logged seems to be different from the data I was looking for. When I scan the card the data that is logged in another website is “1256111915”(card number) but in my console it logs as “733994570”.

How to know if remote peer is disconnected when using Cloudflare Calls SFU?

Is there any way to determine if a remote peer is disconnected while using the Cloudflare SFU without a signaling server?

One solution would be implementing a signaling server that sends a heartbeat every 5 seconds. If no response is received, the session could be terminated.

However, since the client’s peer connection is aware of other connections, I assume it should detect the disconnection.

This is what I have tried to check, but to no avail.

 peerConnection.ontrack = (event: RTCTrackEvent) => {
  const checkTrack = setInterval(() => {
    if (event.track.readyState === "ended") {
      console.log(`Track ${event.track.id} is closed with mid ${event.transceiver.mid}`);
      clearInterval(checkTrack);
    }

    if (event.transceiver.currentDirection === 'stopped' || event.transceiver.currentDirection === 'inactive') {
      console.log(`Transceiver ${event.track.id} is closed with mid ${event.transceiver.mid}`);
      clearInterval(checkTrack);
    }
  }, 500);

  event.track.onended = () => {
    console.log(`${event.transceiver.mid} is ended, ${event.track.id}`);
  };

  event.track.onmute = () => {
    console.log(`${event.transceiver.mid} is muted, ${event.track.id}`);
  };
};