Using variable from one JavaScript code in a piece of jQuery code

I have an autofade button attached to each instance of my audio tracks:

<input type="button" id="autofadebtn<?php echo $track;?>"  value="Fade Out"

onclick="$(document).ready(function()

{
    $('#<?php echo $track;?>')[0].volume = .5;
    $('#<?php echo $track;?>').animate({volume: 0}, 30000); 
  });

  $('#<?php echo $track;?>').promise().done(function() { 
  $('#<?php echo $track;?>').trigger('pause');
});
    "
    >

I also have a volume slider:

var audio<?php echo $track;?> = document.getElementById("<?php echo $track;?>");
var slider<?php echo $track;?> = document.getElementById("slider<?php echo $track;?>");
var display<?php echo $track;?> = document.getElementById("display<?php echo $track;?>");


slider<?php echo $track;?>.addEventListener("input", sliderActions);

function sliderActions( )
{
  var newVolume = slider<?php echo $track;?>.value;

  display<?php echo $track;?>.innerText = newVolume; // range 0 to 100
  audio<?php echo $track;?>.volume = newVolume / 100; // range 0 to 1 
}

My issue is that I would like my autofade button to start at the volume the user moves the volume slider to. Currently the auto fade starts at .5. I can’t work out which variable to use from the volume slider. The autofade button is within the input tag whilst the volume slider script is at the bottom of the page.

I’ve tried replacing the volume = .5 in the autofade with the named variables from the volume slider but each time the autofade stops working.

Using chart.js with a background image plugin, can’t get entire image to show

I have successfully created a canvas background image plugin for a Chart.js chart, as shown here.

I’m using the plugin, instead of a CSS background, because I need the image to stay with the chart data points (‘scatter’ type chart).

However, I can’t make it show the entire image, no matter what settings I try in the plugin. It is cropping the image vertically. I’m using the same setup as shown at the link:

const custplugin = {
  id: 'custplugin',
  beforeDraw: (chart) => {
    if (image.complete) {
      const ctx = chart.ctx;
      const {top, left, width, height} = chart.chartArea;
      const x = left + width / 2 - image.width / 2;
      const y = top + height / 2 - image.height / 2;
      ctx.drawImage(image, x, y);
    } else {
      image.onload = () => chart.draw();
    }
  }
};

I tried setting CSS ‘overflow: visible’ for the ‘canvas’ element and the div holding that, but that has no effect. I’ve tried messing with the ‘const x’ and ‘const y’ settings in the plugin, but nothing seems to work.

How can I get the entire image to show?

Thanks for any help.

Sortablejs is slow on Chrome with large table (2000 records)

When my sortablejs has an table of 2000+ records it gets realy slow and the page gives me the option to wait or close tab.
But this table is used by clients(in need of an good UX) so this cant happen to them.

I have the following code example:

<!-- Latest Sortable -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/Sortable.min.js"></script>

<div id="left"></div>
<div id="right"></div> 
var left = document.getElementById("left");
var right = document.getElementById("right");

generateTable(2000, left)
generateTable(10, right)

function generateTable(nOfRows, wrap) {
  var newTable = document.createElement("table"),
      tBody = newTable.createTBody(),
      nOfColumns = 5,
      row = generateRow(nOfColumns);

  tBody.classList.add("sortable");
  
  for (var i = 0; i < nOfRows; i++) {
    tBody.appendChild(row.cloneNode(true));
  }

  (wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
}

function generateRow(n) {
  var row = document.createElement("tr"),
      text = document.createTextNode("cell");

  for (var i = 0; i < n; i++) {
    row.insertCell().appendChild(text.cloneNode(true));
  }

  return row.cloneNode(true);
}


Sortable.create(document.getElementsByClassName('sortable')[0], {
  items: "tr",
  group: '1',
  animation: 100
});

Sortable.create(document.getElementsByClassName('sortable')[1], {
  items: "tr",
  group: '1',
  animation: 100
});

code example

Unable to connect Backend on other network

I am making a group project in which one member doing Frontend and I am doing Backend . I what that using my IP he connect with Backend
When my laptop and his laptop both are in same network and I add his IP in cors then it works but when he is on different , he is unable to communicate with my Backend

My backend is in Node.js & Express.js

I am in ubuntu so I allow my port from firewall using

sudo ufw allow 8080

also use differant cors options like,

app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}))

and

app.use(cors())

and I listen on 0.0.0.0

const server = app.listen(PORT, '0.0.0.0', () => {
   console.log(`Server started on port ${PORT}`);
});

but still my friend is unable to access my Backend . I want to make it universal , means who enter my ip and port he can access like : 192.168.xx.xxx:8080/

why i docker build -t php84 . failed to authorize?

docker pull php success

Dockerfile:
FROM php
sudo docker build -t php84 .

[+] Building 21.9s (3/3) FINISHED docker:default
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 46B 0.0s
=> ERROR [internal] load metadata for docker.io/library/php:latest 21.8s
=> [auth] library/php:pull token for registry-1.docker.io 0.0s

[internal] load metadata for docker.io/library/php:latest:


Dockerfile:1

1 | >>> FROM php
2 |

ERROR: failed to solve: php: failed to resolve source metadata for docker.io/library/php:latest: failed to authorize: failed to fetch oauth token: Post “https://auth.docker.io/token”: dial tcp 103.214.168.106:443: connect: connection refused

why ?

Laravel 9, Parent child bulk insert while replacing uuid to id

I have following table structure.

Table: movies

id uuid title
1 uuid-m01 movie 1

Table: categories

id uuid title
1 uuid-c01 category 1
2 uuid-c02 category 2

Table: movie_categories

id movie_id category_id uuid
.. …….. ……….. ……..

POST: …/api/movies/create

{
  "title": "movie 2",
  "category_ids": [
    "uuid-c01",
    "uuid-c02"
  ]
}

Models/APIs/v1/Movie.php

class Movie extends Model {
    ...

    public function movieCategories() {
        return $this->hasMany(MovieCategory::class);
    }

    ...
}

Models/APIs/v1/MovieCategory.php

class MovieCategory extends Model {
    ...

    public function movie() {
        return $this->belongsTo(Movie::class);
    }
    public function category() {
        return $this->hasOne(Category::class);
    }
}

Models/APIs/v1/Category.php

class Category extends Model {
    public function movieCategory() {
        return $this->belongsTo(MovieCategory::class);
    }
}

Controllers/APIs/v1/MovieController.php

public function store(MovieRequest $request) {
    try {
        $Post = $request->validated();

        $Movie = Movie::create([
            'uuid'  => Str::uuid(),
            'title' => $Post['title'],
        ]);

        $Movie->movieCategories()->create($Post['category_ids']);

        ...
    } catch (Throwable $th) {
        ...
    }
}

Now, the question is that in the category_ids I am passing the uuids of categories, but in the movie_categories table the column is accepting the id of the categories table.

When I am running the code, I am getting the following error:

{
  ...
  "error": {
    "code": "22003",
    "message": "SQLSTATE[22003]: Numeric value out of range: 1264 Out of 
                range value for column 'category_id' at row 1 (SQL: 
                insert into `movie_categories` 
                (`movie_id`, `category_id`, `uuid`, `updated_at`, `created_at`) 
                values 
                (3, uuid-c01, uuid-string, 2025-04-01 07:36:18, 2025-04-01 07:36:18))"
  }
}

Whereas the output should be:

Table: movie_categories

id movie_id category_id uuid
# 2 1 uuid-mc3
# 2 2 uuid-mc4

I know that there are various other ways to achieve this, such as: Observers, MySQL triggers, Fetching ids before inserting, but I was wondering if there is more appropriate(Laravel based) solution this problem.

Display the current events of a week with custom styling on page in WordPress

My current solution is to use Events Manager as that seemed to be the only free plugin enabling me to:

  1. Add and edit event names, start and end time (also enable lots of non-technical users to do so)
  2. Display multi-day events
  3. Embed the calendar within a page
  4. Style the calendar with custom CSS

But my client wants a week-view for the calendar and it it’s current form it has just gotten too small, with too many events.
Events Manger does not offer a week-view functionality.

I have done extensive research on this subject, installed and uninstalled countless WP calendars just to see how their functionality is not what it is claimed to be on their website.

That is why I am asking here:

Have you been using a free plugin or solution to display a week-view with said functionality?

I don’t have a problem coming up with my own solution, it just seems like overkill to handle a custom ACF type and sort through the data and display the current week etc.

If there is no out-of-the-box solution, how would you go about configuring ACF and displaying the events with PHP, sorted by date and time in a week-view.

I’m not good with PHP.

I am trying to connect a web application UI (running in a Docker container) to a MySQL database (also in a Docker container) on the same network [duplicate]

I am trying to connect a web application UI (running in a Docker container) to a MySQL database (also in a Docker container) on the same network. The connection succeeds from within the application container, but fails during the UI installation process. checked network connectivity using ping I verified the database credentials are correct. I tried connecting using different tools

checked network connectivity using ping or nslookup. I verified the database credentials are correct. I tried connecting using different tools

How do I ensure user-specific sessions/ data for concurrent users, when my custom php plugin (that accesses my wp databases) [closed]

Problem Summary:

I’m building a WordPress plugin for a multi-user parent portal. Parents log in and edit forms for their children.

Each parent only has one child, and users are never supposed to see each other’s data.
BUT: When concurrent users are logged in on different machines (different IPs, different browsers), something strange happens:

The “Currently managing: {child name}” message switches names depending on which user accessed a tab most recently.

This happens even when:

  • Users are logged in separately, not reusing browsers
  • They each have different credentials
  • They each only have one child
  • Sessions are intended to be separate

Suspected Root Cause
We store the active child ID in a session variable like this:

$_SESSION['current_child_id'] = $user->{"Serial no."};

And use that to determine which student name to display:

$child_id = $_SESSION['current_child_id'];
$child = $wpdb->get_row("SELECT * FROM gsp25 WHERE `Serial no.` = '$child_id'");
echo "Currently managing: " . $child->{"Name of student"};

We use session_start() consistently in all functions.

The Issue

Even though each user logs in on a different machine, one user’s session variable seems to overwrite another’s.

There’s no shared login or intentional impersonation — just unexpected session data bleeding across users.

What We’ve Tried

  • Using session_start() with no session_name() (just default PHPSESSID)
  • Ensuring no output before session starts
  • Confirming that session IDs are different across users
  • Setting the child ID once on login
  • Logging to debug.log shows each user has a different session_id()

What We Need Help With

  • What else could cause cross-user $_SESSION variable leakage?
  • Could WordPress, a plugin, or a server-side misconfiguration (e.g. shared
    session storage) cause this?
  • Is there a better way to isolate each user’s context than relying on PHP sessions?

Session Init Code

This is at the top of every handler function that touches $_SESSION:

if (!session_id()) session_start();

We do not use session_name() anymore. We rely entirely on PHP’s default PHPSESSID cookie.

Where We Set Session State (on login):

$_SESSION['parent_logged_in'] = true;
$_SESSION['parent_email'] = $parent_email;
$_SESSION['current_child_id'] = $user->{"Serial no."};

Server Setup:
I do not know much about this, other than that this is a custom plugin on a website hosted at wordpress.com, using tables from a wp database.
We’ve verified that each user gets a unique session_id() via session_id()

Thank you experts, and appreciate your help with this.

Chartjs: Connect canvas background image and chart (type: ‘scatter’) so that data points remain in same spot on image?

I have successfully created a canvas background image plugin for a Chart.js chart, as shown here.

It is better at staying in place than a css background image, however, when the window is resized, the data points end up in different spots relative to the image. Is there any way to make the chart change size at the same rate as the image, so that the data points stay put relative to the image?

I’ve tried changing the ‘responsive’ and ‘maintainAspectRatio’ settings, but they don’t seem to make a difference in this regard.

My custom plugin is as shown at the link above:

const custplugin = {
  id: 'custplugin',
  beforeDraw: (chart) => {
    if (image.complete) {
      const ctx = chart.ctx;
      const {top, left, width, height} = chart.chartArea;
      const x = left + width / 2 - image.width / 2;
      const y = top + height / 2 - image.height / 2;
      ctx.drawImage(image, x, y);
    } else {
      image.onload = () => chart.draw();
    }
  }
};

Thanks for any help.

How to invoke durable function activity from within a callback function?

I’m trying to consume messages from kafka topic using Azure durable function and as the new messages arrive I want to invoke the activity function to process the messages. The problem here is that the callback function isn’t able to access the context and other local variables which are needed to invoke the activity function.

Please suggest if I’m dong it correctly and if there are any better/alternate approaches.

Here is my function code:

/* the orchestrator is invoked by a timer trigger */
/* using kafka javascript SDK (@confluentinc/kafka-javascript) to create a consumer */

const kafkaConsumerOrchestratorName = 'kafka_consumer_orchestrator';
const kafkaConsumerActivityName = 'kafka_consumer_activity';

df.app.orchestration(kafkaConsumerOrchestratorName, function* (context) {
    yield kafkaService.consumer.run({
        eachMessage: async ({ topic, partition, message }) => {
            /* context not accessible here */
            yield context.df.callActivity(kafkaConsumerActivityName, { topic, partition, message });
        }
    });
});

df.app.activity(kafkaConsumerActivityName, {
    handler: async (input, context) => {
        /* process messages */
        console.log(input);
    }
});

How to stop autoplay video with mutationObserver in YT

okay I am trying to stop autoplay youtube video after loading, using mutationobserver from JS.

The problem is the Youtube is a SPA(single page application). Due to which, if I stop the mutationobserver after pausing the first video video.pause(). I need to refresh page manually after switching to another video.
And if don’t stop after first excution i can’t play any video at all. Everytime I play a video mutation obserser notice & call function to execute video.pause().

Q. Can we use mutationObserver to check if ytb-watch-video-id has been changed. coonsidering if this change means page changed & call the function to pause autoplay?

<video tabindex="-1" class="video-stream html5-main-video" controlslist="nodownload" style="..." ytb-watch-video-id="S...s" ytb-miniplayer-video src="blob:https://www.youtube.com/...2b"></video>

How to contribute to a project where the repository only contains .patch files?

I’m trying to contribute to Zen Desktop (a browser based desktop environment, dev branch), but the repository only contains .patch files across all branches : no original .js/.css source files. For example:

src/browser/components/panelUI.css.patch  
src/browser/themes/shared/tabs.css.patch  

I do see .css and .js files but with .patch at the end and this is same everywhere.

I read the contribution and installation guidelines but I do not any explicit documentation on patch management.

How should I set up a development environment if the repo only provides patches? Are there any commands that I need to execute before I can start contributing?

Link: https://github.com/zen-browser/desktop

Grateful if any of you can help me!

ExpressJS Res.Download() Not Sending File to Download

I am trying to download the file from expressjs backend using Axios. The file is of size 1kB but on attempting to download it every time, I am getting 17 bytes file that does not open.

Here is my backend code:

const __dirname = path.resolve();

app.get("/download", function(req, res, next) {

        const dirPath = `${__dirname}/images/${req.query.dir}/output`;

        let files = fs.readdirSync(dirPath);

        res.download(`${dirPath}/${files[0]}`);

        res.status(200).send("Download complete");
});

And my frontend code is:

axios({
      url: `http://example.com/download?dir=${someDir}`,
      method: "GET",
      responseType: "blob"
    })
      .then(res => {
        //console.log(res.data);
        const href = URL.createObjectURL(res.data);
        //console.log(href);
        
        const link = document.createElement("a");
        link.href = href;
        link.setAttribute("download", output.jpeg);
        document.body.appendChild(link);
        link.click();

        document.body.removeChild(link);
        URL.revokeObjectURL(href);
      })
      .catch(er => console.log(er));

I am puzzled to find the root cause of this. Help on this appreciated

Why isn’t my react front end displaying anything?

I wanted to create a DisplayItems page which takes a GET method (in this case, dummy information from "http://localhost:8000/itemTest") and returns a table with the information with a radio button which allows you to pick which item you would like to bid on. This code used to work correctly but since adding a database to my front end, the code no longer works.

import React, { useState, useEffect } from "react";
import { useLocation, Link } from "react-router-dom";
import axios from "axios";

const DisplayItems = () => {
  const [items, setItems] = useState([]);
  const [filteredItems, setFilteredItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedItemId, setSelectedItemId] = useState(null);

  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const searchQuery = searchParams.get("search") || "";

  useEffect(() => {
    axios
      .get("http://localhost:8000/itemTest")
      .then((response) => {
        console.log("API Response:", response.data);
        setItems(Array.isArray(response.data.item) ? response.data.item : []); // Ensure items is an array
        setLoading(false);
      })
      .catch((err) => {
        console.error("Error details:", err);
        setError(err.response?.data?.message || "Error fetching items");
        setLoading(false);
      });
  }, []);

  useEffect(() => {
    if (!searchQuery) {
      setFilteredItems(items);
    } else {
      const filtered = items.filter((item) =>
        item.name?.toLowerCase().includes(searchQuery.toLowerCase()) // Handle cases where name might be undefined
      );
      setFilteredItems(filtered);
    }
  }, [searchQuery, items]);

  const handleRadioChange = (id) => {
    setSelectedItemId(id);
  };

  if (loading) {
    return <p>Loading items...</p>;
  }

  if (error) {
    return <p>{error}</p>;
  }

  return (
    <div className="form-container">
      <h2>Display Items</h2>
      <div>
        {items.length > 0 ? (
          <table>
            <thead>
              <tr>
                <th>Select</th>
                <th>Name</th>
                <th>Description</th>
                <th>Price</th>
              </tr>
            </thead>
            <tbody>
              {filteredItems.map((item) => (
                <tr key={item.id}>
                  <td>
                    <input
                      type="radio"
                      name="bidSelection"
                      checked={selectedItemId === item.id}
                      onChange={() => handleRadioChange(item.id)}
                    />
                  </td>
                  <td>{item.name}</td>
                  <td>{item.itemdescription}</td>
                  <td>${item.price}</td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <p>No items found.</p>
        )}
      </div>
      {selectedItemId && (
        <div>
          <Link to={`/forward/${selectedItemId}`}>
            <button>Bid</button>
          </Link>
        </div>
      )}
    </div>
  );
};

export default DisplayItems;

I have tried using "http://localhost:8000/itemTest" whose data is:

[{"id":"1","name":"bike","itemdescription":"This is a bicycle, used for transportation.","startingprice":"19.99","price":"19.99","highestbidderid":"","image_url":"http://example.com/sample-image.jpg"},{"id":"2","name":"paper","itemdescription":"a lovely piece of paper.","startingprice":"1.99","price":"1.99","highestbidderid":"","image_url":"http://example.com/sample-image.jpg"}]

I have checked my data initialization as well:

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class ItemCreate(BaseModel):
    itemdescription: str
    name: str
    price: float
    shippingprice: float
    endtime: datetime
    startingprice: float
    valid: bool
    action_type: str
    id: int

I have tried to debug this code for hours, but I cannot find why it was once working fine, and now it doesn’t.