Anchor link loads wrong page on click, but correct page after refresh (HTML/XAMPP)

I have this div in index.html at C:xampphtdocsproyectindex.html:

<div class="splide__slide">
                            <div class="card card-style slide-1">
                                <div class="content mb-0">
                                    <h1 class="text-center-editado-slide1">Bars&Restaurants</h1>
                                    <p class="text-center-editado-subtitulo-slide1"> Descubrí propuestas
                                        irresistibles para tu próxima salida </p>
                                    <p class="boxed-text-xl-slide1-contenido mt-n3 font-14">
                                        Salir a comer es un plan único, por eso reunimos varias propuestas para vos.
                                    </p>
                                    <a href="../whereTo/barsRestaurants.html"
                                        class="btn btn-m btn-center-l rounded-s shadow-xl mb-4 btn-personalizado-1">
                                        Ver opciones...
                                    </a>
                                </div>
                            </div>

When I click the button, it opens the wrong page:

On click → incorrect page, after refresh → correct page.

If I press F5, it then goes to the correct file:

correct-images

This also happens in production, not only in XAMPP.

I don’t understand why the link works incorrectly on the first click, but correctly after refresh.
How can I fix this?

Have I written incorrect code for rendering a block element in the Slate.js editor?

I am building a rich text editor using Slate in React. I borrowed code from a Slate rich text typescript example code. Only difference is I am using tailwindcss instead of @emotion/css. The specified format on the block Button (BlockButton), should run the respective case block defined in the renderElement function, and the html tag should render on the editor. For e.g. I click the BlockButton of ‘heading-one’, the h1 heading should render on the editor. However, nothing is happening, why?

utils.tsx:

...

export const ToggleBlock = (editor: CustomEditor, format: CustomElementFormat) => {
  ...
  let newProperties: Partial<Element>
  if (isAlignType(format)) {
    newProperties = {
      align: isActive ? undefined : format,
    }
  } else {
    newProperties = {
      type: isActive ? "paragraph" : isList ? "list-item" : format,
    } as Element
  }
  
  Transforms.setNodes<Element>(editor, newProperties)

  ...
}

export const renderElement = ({attributes, element, children}: RenderElementProps) => {
  const style: React.CSSProperties = {}

  console.log(`element type ${element.type}`)
  if (isAlignElement(element)) {
    style.textAlign = element.align as AlignType;
  }
  switch (element.type) {
    case 'heading-one': {
      console.log(`h1 ${children}`)
      return (
        <h1 style={style} {...attributes}>{children}</h1>
      );
    }
            
    case 'heading-two': {
      console.log("h2")
      return (
        <h2 style={style} {...attributes}>{children}</h2>
      );
    }

    case 'heading-three': {
      console.log("h3")
      return (
        <h3 style={style} {...attributes}>{children}</h3>
      );
    }
            
    case 'heading-four': {
      console.log("h4")
      return (
        <h4 style={style} {...attributes}>{children}</h4>
      );
    }
            
    case 'quote': {
      console.log("quote")
      return (
        <blockquote style={style} {...attributes}>{children}</blockquote>
      );
    }
        
    case 'list-item': {
      console.log("list-item")
      return (
        <li style={style} {...attributes}>{children}</li>
      );
    }
            
    case 'bulleted-list': {
      console.log("bulleted-list")
      return (
        <ul style={style} {...attributes}>{children}</ul>
      );
    }

    case 'numbered-list': {
      console.log("numbered-list")
      return (
        <ol style={style} {...attributes}>{children}</ol>
      );
    }
        
    default: {
      console.log("paragraph")
      return (
        <p style={style} {...attributes}>{children}</p>
      );
    }
  }
}

...

Toolbar.tsx:

...
export const BlockButton = ({ format, Icon }: BlockButtonProps) => {
  const editor = useSlate();

  return (
    <Button
      active={true}
      Icon={Icon}
      onPointerDown={(event: React.PointerEvent<HTMLButtonElement>) => {
        event.preventDefault();
      }}
      onClick={() => ToggleBlock(editor, format)} // Calling ToggleBlock
    />
  )
}
    
...

App.tsx:

...

function App() {
  ...

  return (
    <>
      <h1>Editor</h1>
      <div id='container'>
        <Slate initialValue={initialValue} editor={editor}>
          <Toolbar>
           ...
            <BlockButton format='heading-one' Icon={BsTypeH1} /> 
          </Toolbar>
          <div id="editor-container">
            <Editable 
              renderElement={renderElement}
              renderLeaf={renderLeaf}
              className='editor' 
              placeholder='write something...'
              onKeyDown={event => keyHandler(event)}
            />
          </div>
        </Slate>
      </div>
    </>
  )
}

export default App

Please correct my understanding and code regarding where I went wrong.

Media upload on Android not working with react-hook-form

I’ve made a website using React and uploaded the website on Vercel, but I have a problem. On the website, I have a file input which accepts image and video files. It worked and uploaded files easily on the computer, but on mobile (I have Android), the image and video I chose from the gallery did not upload. I’m using react-hook-form and react-dropzone. I don’t know what the problem this, or how to fix it.

Here’s a snippet from the code for inputs:
this code snippet

I tried a lot but I didn’t reach the solution.

How to Create a Corner-Based 3D Fold Animation on Scroll for Two Columns (CSS + JS)

I’m trying to create a 3D corner fold animation that triggers based on scroll position, similar to this effect:

Example Screenshot

Here’s what I want to achieve:

I have two side-by-side columns (left_box and right_box).

As the user scrolls down and a column becomes visible, a 3D fold animation should play.

When the column is about to scroll out of view (at the bottom of the viewport), the animation should reverse — as if it’s “folding away.”

I’d like the animation to feel like a smooth, curved 3D fold — not a simple fade or slide.

My Questions:

  1. Is this possible with just CSS and JavaScript (no external libraries like GSAP)?

  2. How can I implement the 3D corner fold effect in CSS — should I use transform: perspective(…) rotateX(…) or some combination of pseudo-elements?

  3. How do I make sure the animation plays smoothly both when entering and leaving the viewport?

Constraints:

I want to avoid heavy libraries if possible.

I only need the effect on the bottom corners, not the whole element.

Cross-browser compatibility would be nice, but modern browsers are my main target.

Any code examples or demos would be really helpful!

Errors with Calculating the Second Focus Point of an Orbit (Ellipse)

I’m currently coding a 2d physics sim in javascript and am trying to determin the second focus of an ellipse. My current systems ecentricity is way too low and I’ve debugged it, but can’t find what is wrong with my maths. Additionally, the points moves around way too much and isn’t where it should be. I understand that it should oscillate a little bit as the other planets will also tug on the planet I’m trying to measure, but its completeley unrealistic.

The maths I’ve tried replicating
Currently I’m getting the velocity of the orbiting planet with respect to its parent (the sun) and the distance between the planet and the sun to try calculating the escentricity using e = (v × h)/μ – r/|r|. Then using this I ofset another point away from the centre of the elipse in the same direction as the semi-major axis in the opposite direction the the sun to try finding the second focus point.
My current code ↓

export function findSecondFocus(i) {
    let parentIndex = bodies[i].parentIndex;
    let parent = bodies[parentIndex];
    const relativeSpatiumVector = [
        bodies[i].position[0] - parent.position[0],
        bodies[i].position[1] - parent.position[1],
    ];
    //calculate the relative position vector of the body relative to what its orbiting
    const relativeVelocityVector = [
        bodies[i].velocity[0] - parent.velocity[0],
        bodies[i].velocity[1] - parent.velocity[1],
    ];
    //calcualte the relative velocity
    const r = Math.hypot(relativeSpatiumVector[0], relativeSpatiumVector[1]);
    // r represents the distance between the body and what it is orbiting
    // uses math.hypot to form a right angle to triangle to use pythagoras theorem to calculate the scalar distance
    const velocityScalar = Math.hypot(
        relativeVelocityVector[0],
        relativeVelocityVector[1]
    );


    const mu_sim = gravity * parent.mass; 
    const specificOrbitalEnergy = velocityScalar ** 2 / 2 - mu_sim / r;
    //calcualtes specific orbital energy which is the sum of their potetial and kinetic energies.
    //it is given by ε=v^2/2 -μ/r where μ=GM

    const a = -mu_sim / (2 * specificOrbitalEnergy);
    //calcualte the semi-major axis by rearranging ε=-μ/(2a)

    // The eccentricity vector formula is: e = (v × h)/μ - r/|r|
    const rvDot = relativeSpatiumVector[0] * relativeVelocityVector[0] +
              relativeSpatiumVector[1] * relativeVelocityVector[1];

    const rUnit = [
        relativeSpatiumVector[0] / r,
        relativeSpatiumVector[1] / r
    ];

    const eccentricityVector = [
        ((velocityScalar**2 - mu_sim / r) * rUnit[0] - rvDot * relativeVelocityVector[0]) / mu_sim,
        ((velocityScalar**2 - mu_sim / r) * rUnit[1] - rvDot * relativeVelocityVector[1]) / mu_sim,
    ];
    const eccentricityScalar = Math.hypot(
        eccentricityVector[0],
        eccentricityVector[1]
    );
    //calculate the eccentricity of the orbit
    const eccentricityUnitVector = [
        eccentricityVector[0] / eccentricityScalar,
        eccentricityVector[1] / eccentricityScalar,
    ];
    //convert ecentricity to a unit vector by dividing by its magnituted so that it has a length of 1
    const distanceFromCentre = a * eccentricityScalar; // c = ae

    // First focus is at parent position
    // Center is OPPOSITE to eccentricity direction from first focus
    const ellipseCenter = [
        parent.position[0] - distanceFromCentre * eccentricityUnitVector[0],
        parent.position[1] - distanceFromCentre * eccentricityUnitVector[1],
    ];

    // Second focus is equal distance on OTHER side of center
    const secondFocus = [
        ellipseCenter[0] - distanceFromCentre * eccentricityUnitVector[0],
        ellipseCenter[1] - distanceFromCentre * eccentricityUnitVector[1],
    ];

    //finally calculate the position of the second focus point by offsetting the position of the first focus (parent planet) by 2 times the distance from the centre of the ellipse

    console.log(secondFocus);
    console.log("Eccentricity:", eccentricityScalar);
    console.log("Semi-major axis:", a);
}

I appreciate any help 🙂

Updating Woocommerce Product Attributes

I’m building a purchase order system for my Woocommerce store. Everything is working as expected except for product attributes. With my current code (shown below) the attributes are updated in the database and they show up in the product edit page, but my front end product search filter doesn’t show the updated attributes. I thought refreshing the lookup table would fix this, but so far it isn’t working. I’ve also cleared caches (browser and server) but no luck. When I change the attributes through the product edit page directly it works as expected, so I do think it has something to do with my code.

if (!empty($ov['attributes']) && is_array($ov['attributes'])) {
  $pairs = [];
  foreach ($ov['attributes'] as $key => $val) {
    $name = trim((string)$val);
    if ($name === '') continue;
    $attr_slug   = strtolower(str_replace('_', '-', $key));
    $tax         = function_exists('wc_attribute_taxonomy_name')
                    ? wc_attribute_taxonomy_name($attr_slug)
                    : 'pa_' . $attr_slug;
    if (!taxonomy_exists($tax)) continue;
    $pairs[] = [$tax, $name];
  }

  if ($pairs) {
    foreach ($pairs as [$tax, $name]) {
      $term = term_exists($name, $tax);
      if (!$term) {
        $res = wp_insert_term($name, $tax);
        if (!is_wp_error($res)) $term = $res;
      }
      if ($term && !is_wp_error($term)) {
        $term_id = is_array($term) ? (int)$term['term_id'] : (int)$term;
        wp_set_post_terms($product_id, [$term_id], $tax, false);
      }
    }

    $meta_attrs = get_post_meta($product_id, '_product_attributes', true);
    if (!is_array($meta_attrs)) $meta_attrs = [];

    foreach ($pairs as [$tax, $name]) {
      $meta_attrs[$tax] = array(
        'name'         => $tax,  
        'value'        => '',    
        'position'     => 0,
        'is_visible'   => 1,     
        'is_variation' => 0,     
        'is_taxonomy'  => 1
      );
    }

    update_post_meta($product_id, '_product_attributes', $meta_attrs);

    if (function_exists('wc_delete_product_transients')) {
      wc_delete_product_transients($product_id);
    }

    tsf_po_refresh_attribute_lookup( $product_id );
  }
}

Why does this query slow down this much over time

I’m testing with a very simple database queue to see how fast I can process it. At the moment without even doing anything else then just retrieving it from the queue.

A simple CTE query selects one row from the queue and updates it’s status from 0 to 1 to be able to run the script in parallel or on multiple servers. The columns used in the WHERE clause are indexed and the ORDER BY is on the primary key. The queue table has been filled with a million records and status 0.

I run a very simple PHP script from the command line to see how many rows I can roughly handle in 10 seconds before it exits.

When I run this script with a fresh table and all rows have status 0, I can handle about 7000 requests in 10 seconds. Every subsequent execution without resetting the queue will make it slower and slower as time goes on. If I manually update 500000 rows to status 1 and run the script, it will only take about 50 per 10 seconds. Manually resetting all rows to status 0 will increase the speed again.

I have no idea what I could do to optimize this as indexes are in place, hardware is sufficient and query is about as simple as can be.

I’m using SQL Server on Windows Server 2022 and Ubuntu 24.04 for a simple PHP script are running on two separate VM’s on Proxmox with 32 cores and 32 GB ram provisioned to each server. Neither server every exceeds 10% CPU or 25% ram. The physical server has 256GB ram, 96 x AMD EPYC 9454P 48-Core Processor (1 Socket) and NVME SSD disks. Network between them is around 12 Gbits/sec according to iperf3.

The is my table’s definition:

CREATE TABLE [dbo].[testqueue] (
[id] [bigint] IDENTITY(1,1) NOT NULL,
[guid] [uniqueidentifier] NOT NULL,
[created] [datetime] NOT NULL,
[notbefore] [datetime] NOT NULL,
[status] [tinyint] NOT NULL,
[task] [nvarchar](255) NOT NULL,
[data] [nvarchar](max) NULL,
[completed] [datetime] NULL,
CONSTRAINT [PK_testqueue] PRIMARY KEY CLUSTERED ([id] ASC)
)
CREATE INDEX [ix_guid] ON [dbo].[testqueue] ([guid])
CREATE INDEX [ix_selector] ON [dbo].[testqueue] ([status],[notbefore])

And this is my PHP script:

$connection = new PDO('sqlsrv:Server='.$server.';Database='.$db.';', $user, $pass);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$time  = time();

$count = 0;
$query = '
  WITH CTE AS (
    SELECT TOP 1 * 
    FROM [dbo].[testqueue] 
    WHERE [status]=0 
    AND [notbefore]<=getdate() 
    ORDER BY [id] ASC
  )

  UPDATE CTE 
  SET [status]=1
  OUTPUT INSERTED.id
';

$statement = $connection->prepare($query);
do {
  if ($statement->execute()) {
    //do something later
  }
  $count++;
  if (time() - $time > 10) {
    break;
  }
} while (true);

The execution plan doesn’t show any warnings for indexes and says 25% goes to a Clustered index Scan and 75% to a Clustered Index Update.

execution plan

Prevent from reloading on component re-render in a tabbed Next.js dashboard

I’ve developed a tabbed UI dashboard in Next.js and React, where each new menu item opens in a new tab inside the dashboard panel. I can manage the tab mount state without issues.

However, I’m facing a problem with my component: whenever I switch tabs and the component re-renders, the reloads its URL. I want the to retain its state and not reload when the tab changes or the component re-renders.

How can I prevent the from reloading in this scenario?

Thank you for your help!

Error 405: Moved Temporarily from Google Apps Script even though server still accepts the payload

Assume the following simple setup for sending telemetry to Google Sheets:

Curl -> Google Apps Script deployed as Web App -> Google Sheet -> Cell 1:1

Google Apps script is a simple doPost() that prints the json payload into the Cell 1:1 of the Sheet it is an extension of.

This works fine for the most part. Data sent by Curl is being received by Google Sheet. However, the response from google’s server comes with an Error 405: Moved Temporarily:

<H1>Moved Temporarily</H1>
The document has moved <A HREF="https://script.googleusercontent.com/macros/echo?user_content_key=balhblah"

But, even though the response indicates an error, the data still appears in the Google Sheet. What is the reason for 405-ing, and why does Google still accept data despite throwing an error?

Curl script line:

curl -X POST "https://script.google.com/macros/s/xxxxxxxx/exec" -H "Content-Type: application/json"

Google Apps Script code for the doPost():

function doPost(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  var rawData;
  if (e.postData) {
    rawData = e.postData.contents;   // get the request's payload
  } else {
    rawData = "";                    // fallback to empty string if there is no data
  }

  // Append to the end of the sheet
  sheet.appendRow([rawData]);

  return ContentService
    .createTextOutput("Data received.");
}

Separate out data from AI response

I am making a AI powered SAAS dashboard and if I send some query to backend I want to separate out the text, code-block and graphs from the response of AI backend to separately render them on different parts of the screen.

I haven’t tried it yet still don’t know how the response of the backend will be.

What really happens in the browser when you swtich from landscape to portrait mode in a tablet?

Currently I am working on very strange bug in a legacy ASP.NET MVC application and it is reproducible only on IPads. One of the page does not fit screen and strangely when I switch to landscape and back to portrait issue gets fixed and page fully fits into the screen. My question is as a workaround solution is there any way to programatically rotate the page to landscape and back to portrait without user noticing on the page load? More essential question is what really happens in the browser when you switch from landscape to portrait?

Blazor – when JavaScript runs for custom context menu, app navigates back to homepage

Background

I have a Blazor server-side app I’m building which will be a music sheets website. I’m having trouble running JavaScript code for a context menu. I’ve started adding a custom context menu, so users will be able to right-click on the page and I give them a list of custom actions they can take.

Problem

When I pull up the context menu on the UI, then click on one of the menu items, the script executes but it navigates back to the home page and I have no idea why. After putting in a bunch of console logging and using a sleep timer, it seems to just happen when the JavaScript finishes running, not on any particular action.

Code Details

Basically all the JavaScript code is doing is logging to the console and then closing the menu, I haven’t programmed any of the actions the menu will eventually take. Below is the code for NewSheet.razor. I’m only including relevant code for now, but I can add more details upon request.

@*HTML for context menu*@
<nav id="context-menu" class="context-menu">
    <ul class="context-menu__items">
        <li class="context-menu__item">
            <a href="#" data-action="add-verse" class="context-menu__link"> Add Verse</a>
        </li>
        <li class="context-menu__item">
            <a href="#" class="context-menu__link"> Add Chorus</a>
        </li>
        <li class="context-menu__item">
            <a href="#" class="context-menu__link"> Add Bridge</a>
        </li>
        <li class="context-menu__item">
            <a href="#" class="context-menu__link"> Add Line (notes and lyrics)</a>
        </li>
    </ul>
</nav>
<script>
    var MenuOpen = false;
    var ContextMenuActive = "context-menu--active";
    var MenuElement = document.querySelector("#context-menu");


    function clickInsideElement(e, className) {
        var el = e.srcElement || e.target;

        if (el.classList.contains(className)) {
            return el;
        } else {
            while (el = el.parentNode) {
                if (el.classList && el.classList.contains(className)) {
                    return el;
                }
            }
        }

        return false;
    }


    function getPosition(e) {
        var posx = 0;
        var posy = 0;

      if (!e) var e = window.event;

      if (e.pageX || e.pageY) {
          posx = e.pageX;
          posy = e.pageY;
      } else if (e.clientX || e.clientY) {
          posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
          posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
      }

      return {
          x: posx,
          y: posy
      }
    }


    function init() {
        contextListener();
        clickListener();
        keyupListener();
        resizeListener();
    }


    function contextListener() {
        document.addEventListener("contextmenu", function(e) {
            //var taskItemInContext = clickInsideElement(e, "task"); // this should check if the click is on one of the context menu items, but instead causes the menu to never open.
            //if (taskItemInContext) {
                if (MenuOpen) {
                    toggleMenuOff();

                } else {
                    e.preventDefault();
                    toggleMenuOn();
                    positionMenu(e);
                }
        });
    }


    function clickListener() {
        document.addEventListener("click", function(e) {
            var clickeElIsLink = clickInsideElement(e, "context-menu__link");

            if (clickeElIsLink) {
                e.preventDefault();
                menuItemListener(clickeElIsLink); // logs the data attribute to the console. This essentially tells you which menu option was selected.
            } else {
                var button = e.which || e.button;
                if (button === 1) {
                    toggleMenuOff();
                }
            }
        });
    }


    // If user presses esc button then close the menu
    function keyupListener() {
        window.onkeyup = function(e) {
            if (e.keyCode === 27) {
                toggleMenuOff();
            }
        }
    }


    // If the user is resizing the browser window then close the context menu for now.
    function resizeListener() {
        window.onresize = function(e) {
            toggleMenuOff();
        };
    }


    // Safe method for toggling on the context MenuElement. Does check first to make sure menu is closed before attempting to open.
    function toggleMenuOn() {
        if (!MenuOpen) {
            MenuElement.classList.add(ContextMenuActive);
            MenuOpen = true;
        }
    }


    // Safe method for toggling off the context MenuElement. Does check first to make sure menu is open before attempting to close.
    function toggleMenuOff() {
        if (MenuOpen) {
            MenuElement.classList.remove(ContextMenuActive); // this doesn't seem to be causing an issue. Page still redirects, even when this is commented out.
            MenuOpen = false;
        }
    }


    function positionMenu(e) {
        var clickCoords = getPosition(e);
        var clickCoordsX = clickCoords.x;
        var clickCoordsY = clickCoords.y;

        var menuWidth = MenuElement.offsetWidth + 4;
        var menuHeight = MenuElement.offsetHeight + 4;

        var windowWidth = window.innerWidth;
        var windowHeight = window.innerHeight;

        if ((windowWidth - clickCoordsX) < menuWidth) {
            MenuElement.style.left = windowWidth - menuWidth + "px";
        } else {
            MenuElement.style.left = clickCoordsX + "px";
        }

        if ((windowHeight - clickCoordsY) < menuHeight) {
            MenuElement.style.top = windowHeight - menuHeight + "px";
        } else {
            MenuElement.style.top = clickCoordsY + "px";
        }
    }


    // Function called to take an action from clicking on one of the menu items. After action is taken, closes the menu.
    function menuItemListener(link) {
        console.log(link.getAttribute("data-action")); // this is where the data action attribute is logged to the console.
    }


</script>

Main Question:

Why does the app keep navigating back to the home page when the script runs?

Steam inventory API returns 403 when fetching user’s CS:GO inventory from backend

I’m building a website that requires Steam login. After the user logs in I call Steam’s inventory endpoint to show their cs inventory, but im getting that error. After logging in console shows

Fetching inventory for SteamID: 7656119xxxx
Trying new API: https://steamcommunity.com/inventory/xxxxxxxxxxx/730/2?l=english&count=5000
Steam returned status 403

app.get('/inventory', async (req, res) => {
  if (!req.user) return res.status(401).json({ error: 'Not logged in' });

  const steamid = String(req.user._json?.steamid || req.user.id);
  const url = `https://steamcommunity.com/inventory/${steamid}/730/2?l=english&count=5000`;

  const response = await fetch(url, {
    headers: { 'User-Agent': 'Mozilla/5.0' }
  });

  if (!response.ok) {
    return res.status(500).json({ error: `Steam returned status ${response.status}` });
  }

  const json = await response.json();
  // …process json…
});

What’s the best way to create a mutex lock in JavaScript?

So far I have created a function used to set a timeout to simulate a mutex. I’m thinking there has to be a better way to do this though, maybe a built in function?

function RenderTreeMutex() {
    if(rendering || dragging || resetting) {
        setTimeout(RenderTreeMutex, 50);
        return;
    }
  }

This method seems a bit unorthodox, there must be a cleaner way?