Use placeholders and $wpdb->prepare(); found $sql

I create my custom plugin and test in plugin check plugin but it give me error like
Use placeholders and $wpdb->prepare(); found $sql

// Execute

$sql = "SELECT {$found_rows} p.ID AS course_id, X.*,IF(X.status = %s AND uim.meta_value IS NOT NULL, uim.meta_value, X.status) AS status FROM ( SELECT ui.* FROM `{$stepup_lms_user_items}` ui  LEFT JOIN `{$stepup_lms_user_items}` uix    ON ui.item_id = uix.item_id AND ui.user_id = uix.user_id    AND ui.user_item_id < uix.user_item_id  WHERE uix.user_item_id IS NULL) X {$join}   {$where}    {$limit}";

        // Only the dynamic value goes through prepare
        $rows = $db->wpdb->get_results(
                $wpdb->prepare( $sql, 'finished' )
        );

Also I write query inside $wpdb->prepare(); then it give another error like

Use placeholders and $wpdb->prepare(); found interpolated variable {$found_rows} at "SELECT {$found_rows} p.ID AS course_id, X.*,IF(X.status = %s AND uim.meta_value IS NOT NULL, uim.meta_value, X.status) AS status FROM (tSELECT ui.*tFROM {$stepup_lms_user_items} uitLEFT JOIN {$stepup_lms_user_items} uixtON ui.item_id = uix.item_idtAND ui.user_id = uix.user_idtAND ui.user_item_id < uix.user_item_idtWHERE uix.user_item_id IS NULL) X {$join}t{$where}t{$limit}"

But It is not solve.

Please help me

Thanks in advance.

I try bellow links

I refer wordpress document https://make.wordpress.org/core/2022/10/31/postponed-to-wp-6-2-escaping-table-and-field-names-with-wpdbprepare/

also view other resource https://github.com/WordPress/WordPress-Coding-Standards/issues/2442

I want to resolve my ERROR and warning in Plugin Check plugin.

Where is first view file in Symfony?

I am new in Symfony and I start to create basic MVC project. When I create project and run it I see welcome page. In laravel this file is in views/welcome.blade.php. In symfony where is this file.

How to get array_splice from upper to lower?

When I run the following code, I’m receiving this output:

PHP
PHP What
PHP What is
PHP What is PHP

However I want to receive the following output:

PHP What is PHP
PHP What is
PHP What
PHP

What thing needs to change to extract values from Upper to Lower

<?php
// Horje.Com
$stringSentence = 'PHP What is PHP';
$stringSentence = preg_replace('/s+/', ' ', $stringSentence);
$buffer = '';
$count = 1;
$length = strlen($stringSentence);
for ($i = 0; $i < $length; $i++) {
    if ($stringSentence[$i] !== ' ') {
       $buffer .= $stringSentence[$i];
    } else {
        //echo ' '.$count++.' '.$buffer.'&lt;/br&gt;';
        $pieces = explode(" ", $stringSentence);
        $first_part = implode(" ", array_splice($pieces, 0, $count++));
        echo ''.$first_part.'</br>';
        $buffer = '';
    }
}

$pieces = explode(" ", $stringSentence);
$first_part = implode(" ", array_splice($pieces, 0, $count++));

echo ''.$first_part.'';

I keep getting “Failed to open stream: Permission denied” and changing permissions on the folder does not work

I am switching from Windows to Linux (Fedora), and I keep getting this error in my Laravel project that I did not have on Windows:

enter image description here

It’s apparently related to permissions, but running these commands doesn’t fix the issue:

sudo chmod -R 777 /var/www
sudo chmod -R 777 storage/
sudo chown -R apache:apache /var/www/
sudo chmod -R 777 /var/www/html/cursos/victor-robles/master-fullstack/api-rest-laravel/storage/framework/views/

I have checked if permissions have been set properly with ls -la and this is what I get:

api-rest-laravel folder:

drwxr-xr-x. 1 apache apache    402 Sep 18 10:51 .
drwxrwxrwx. 1 apache apache     56 Sep 18 02:02 ..
drwxr-xr-x. 1 apache apache     52 Aug 18 22:33 app
-rwxrwxrwx. 1 apache apache    425 Apr 15 08:24 artisan
drwxr-xr-x. 1 apache apache     50 Aug 18 22:33 bootstrap
-rwxrwxrwx. 1 apache apache   2462 Aug 18 23:27 composer.json
-rwxrwxrwx. 1 apache apache 299734 May  1 13:24 composer.lock
drwxr-xr-x. 1 apache apache    204 Aug 18 22:33 config
drwxr-xr-x. 1 apache apache    102 Aug 18 22:33 database
drwxr-xr-x. 1 apache apache     24 Aug 18 22:33 docs
-rwxrwxrwx. 1 apache apache    258 Apr 15 08:24 .editorconfig
-rwxrwxrwx. 1 apache apache   1139 Sep 18 02:20 .env
-rwxrwxrwx. 1 apache apache   1084 Apr 15 08:24 .env.example
-rwxrwxrwx. 1 apache apache    186 Apr 15 08:24 .gitattributes
-rwxrwxrwx. 1 apache apache    286 Apr 15 08:24 .gitignore
-rwxrwxrwx. 1 apache apache    354 Apr 15 08:24 package.json
-rwxrwxrwx. 1 apache apache   1173 Apr 15 08:24 phpunit.xml
drwxr-xr-x. 1 apache apache     78 Aug 18 22:33 public
-rwxrwxrwx. 1 apache apache   3932 Apr 15 08:24 README.md
drwxr-xr-x. 1 apache apache     20 Aug 18 22:33 resources
drwxr-xr-x. 1 apache apache     36 Aug 18 22:33 routes
drwxr-xr-x. 1 apache apache     32 Aug 18 22:33 storage
drwxr-xr-x. 1 apache apache     46 Aug 18 22:33 tests
drwxr-xr-x. 1 apache apache    596 Aug 18 22:34 vendor
-rwxrwxrwx. 1 apache apache    331 Apr 15 08:24 vite.config.js

api-rest-laravel/storage

drwxr-xr-x. 1 apache apache  32 Aug 18 22:33 .
drwxr-xr-x. 1 apache apache 402 Sep 18 10:51 ..
drwxr-xr-x. 1 apache apache  68 Aug 18 22:33 app
drwxr-xr-x. 1 apache apache  70 Aug 18 22:33 framework
drwxr-xr-x. 1 apache apache  42 Aug 18 22:33 logs

api-rest-laravel/storage/framework

drwxr-xr-x. 1 apache apache   70 Aug 18 22:33 .
drwxr-xr-x. 1 apache apache   32 Aug 18 22:33 ..
drwxr-xr-x. 1 apache apache   28 Aug 18 22:33 cache
-rwxrwxrwx. 1 apache apache  119 Apr 15 08:24 .gitignore
drwxr-xr-x. 1 apache apache   20 Aug 18 22:33 sessions
drwxr-xr-x. 1 apache apache   20 Aug 18 22:33 testing
drwxrwxrwx. 1 apache apache 4052 Sep 18 02:24 views

I have also tried restarting apache with sudo systemctl restart httpd several times but nothing works.

Please, any ideas?

prevent PHP from using ellipses (…) in the paths of INCLUDE statements in error messages

I have a .php page that generates a Fatal error:

...
#2 [path1]/header.php(22): include('/Library/WebSer...') 
#3 [path2]/index.php(4): include('/Library/WebSer...')
...

(where I’ve substituted [path#] for the path to files in the traceback) and in both, the file being included is truncated and presented as "/Library/WebSer..." with ellipses instead of the full path and most importantly, without the file_name.

Based on PHP – Stop displaying full path in errors, I take it that once upon a time PHP did not do this, i.e., when reporting an error, it gave the full path, including the file_name, but maybe I’m misunderstanding this 11 year old question and answer.

I’ve looked through all of the php.ini directives at https://www.php.net/manual/en/ini.list.php, and don’t see one that addresses what I want, i.e., I want the full path, including file_name, displayed instead of a truncated path with ellipses at the end like “include(‘/Library/WebSer…’)”.

Is there way to force display of the full path in the “include()”?

Thank you.

i am creating a ecom website using vite react [closed]

i have various product cards and when i add an item to cart , i want the text and icon of add to cart should change to go to cart by checking if that item is in the cart or not,but the function is returning false everytime even the item has been added to the cart, when i am creating a custom cart it is working properly

findProductInCart code below

export const findProductInCart = (cart, id) => {
    const result = cart?.length > 0 && cart.some((product) => product.id === id);

    return result;
};

button text logic

<button onClick={() => onCartClick(product)}>
    {isProductInCart ? (
         <>
             <ShoppingCartCheckoutOutlinedIcon />
             Go to Cart
         </>
     ) : (
         <>
             <ShoppingCartOutlinedIcon />
             Add to Cart
         </>
     )}
</button>

Add to cart Logic

const { cart, cartDispatch } = useCart();
  const navigate = useNavigate();
  const isProductInCart = findProductInCart(cart, product.id);

  const onCartClick = (product) => {
    !isProductInCart
      ? cartDispatch({
          type: "ADD_TO_CART",
          payload: { product },
        })
      : navigate("/cart");
  };

Issue with setThemingColor on groups

We’re working with Forge Viewer v7 and trying to color objects based on their ID. The idea is simple: when we provide an ID, the viewer should color the corresponding objects and sub-objects.

We’ve used viewer.setThemingColor(dbId, colorCode, null, true) hoping it would apply the color recursively:

dbIds.forEach(dbId => {
  let color = new THREE.Color(colour);
  let colorCode = new THREE.Vector4(color.r, color.g, color.b, 1);
  vm.viewer.setThemingColor(dbId, colorCode, null, true);
});

It works fine when the ID matches a geometry node directly (like a mesh), but when the node corresponds to a group, the sub-object inside that group are not colored. It seems the recursive flag doesn’t traverse into the group structure as expected.

Has anyone run into this issue before or found a reliable way to color all sub-objects belonging to an ID node? Any advice or ideas would be greatly appreciated.

fetch API GET error “TypeError: Failed to fetch” – ASP NET Core 8 Razor Pages

Summary:

ASP.NET Core 8 Razor Pages application –
Trying to GET some data from backend using fetch-API. The Request hits the GET Handler. The handler does the work and returns Content("0"). Back in JavaScript I get "TypeError: Failed to fetch". No Response is sent.

Setup:

The Login page is the default page, setup like below in Program.cs:

builder.Services.AddRazorPages(options =>
{
    options.Conventions.AddPageRoute("/Auth/Login", "/");
})

Use Case – Forgot Password

User fills-in the ID and clicks on the Button. Button click is handled in JavaScript. It makes a fetch api GET call to the GET Handler in Login.cshtml.cs file.

JavaScript Code:

try {
 const showResult = async () => {
    const resp = await fetch(`/?handler=ForgotPwd&UserName=${usrname}`, {method:'GET'});
    if (resp.ok) {
        return resp.text();
    }
    else alert(resp.status);
 };
 showResult()
 .then(ret => {
     alert(ret);
 });
}
catch (ex) {
    alert(ex);
}

GET Handler Code:

public async Task<IActionResult> OnGetForgotPwdAsync(string UserName)
{
//Processing...
return Content("0");    //SUCCESS
}

FetchAPIError

As you can see above the Response is blank. Alert shows the TypeError.

If I try any other URL (e.g. /Auth/Login?handler…), I get 404 status code, which means the above URL is correct. Also, the breakpoint on the GET Handler gets hit.

Placeholder(popup) flickering on dragging card in react-grid-layout library

I’m using the react-grid-layout library for drag-and-drop functionality. The requirement is to drag filters and drop them into the available boxes. However, when I drag a filter, the popup of the dragged item (the placeholder) starts flickering.

I observed this issue on Chrome and Edge, but on another laptop, it seems to work fine on Edge.

Initially, I thought the issue was related to component re-rendering, so I suspected the onDrag function might be causing it. However, even after commenting out the function, the issue still persists. It might be related to CSS.

Engine.update not advancing simulation ( having trouble with deltaTime )

so i am trying to run a matter instance in a worker thread.
Im running it with my own loop as shown below. However I’m experiencing trouble with game pacing. Before getting to the explanation here is my code below:

function gameLoop(currentTime) {
  const elapsed = currentTime - state.lastTime;
  state.lastTime = currentTime;
  state.accumulator += elapsed;

  while (state.accumulator >= state.physicsDelta) {
    Engine.update(state.engine, state.physicsDelta);
    state.accumulator -= state.physicsDelta;
  }

  requestAnimationFrame(workerGameLoop);
}

requestAnimationFrame(workerGameLoop)

state.lastTime is initialized to performance.now
and currentTime is handled by requestAnimationFrame.

state.physicsDelta is set to a value of 1000/60 or 16.666 …

If the game is to run at say 30fps then we would expect to see the Engine.update method be called twice to maintain pace.
However after testing, Calling Engine.update isnt really “progressing” the simulation more, calling it 100 times within the same loop doesn’t seem to advance it any further either. Am i missing something?

The reason I have matter on a worker thread is so I can decouple the rendering/physics which will be useful down the line for network games.

this snippet below also runs in the gameLoop function once per animation frame. It pings the main thread with physics data

  // Add all dynamic bodies
  for (const [id, body] of state.dynamicBodies.entries()) {
    bodiesData.push({
      id,
      x: body.position.x,
      y: body.position.y,
      offset: body.offset,
      angle: body.angle,
      velocity: body.velocity,
    });
    updatedIds.add(id);
  }


  if (bodiesData.length > 0) {
    postMessage({ type: "update", payload: bodiesData });
  }

I do have a working html demo you can test where I use the same principle for maintaining physics pace, but only here its running on the main thread.

Feel free to check it out! test the physics pacing by changing your display to a lower frequency, or letting your browser switch to power saving.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Matter.js Top-Down Player Demo</title>
    <style>
      /* Basic styling to center the canvas and remove scrollbars */
      body {
        margin: 0;
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        background-color: #1a1a1a;
      }
      canvas {
        display: block;
        background-color: #2c2c2c;
      }
      .instructions {
        position: absolute;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        color: #fff;
        font-family: Arial, sans-serif;
        font-size: 16px;
        background-color: rgba(0, 0, 0, 0.5);
        padding: 10px 20px;
        border-radius: 10px;
        pointer-events: none; /* Make it non-interactive */
      }
    </style>
  </head>
  <body>
    <div class="instructions">Use WASD to move</div>
    <!-- The Matter.js library is loaded from a CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>

    <script>
      function createRectWithOrigin(
        x,
        y,
        width,
        height,
        origin = { x: 0.5, y: 0.5 },
        options = {}
      ) {
        // Calculate the center offset from the desired origin
        const offsetX = (0.5 - origin.x) * width;
        const offsetY = (0.5 - origin.y) * height;

        // Create the rectangle at the world position plus the offset
        const rect = Bodies.rectangle(
          x + offsetX,
          y + offsetY,
          width,
          height,
          options
        );

        // Shift vertices so the physics center aligns with the origin
        //Body.translate(rect, Vector.create(-offsetX, -offsetY));

        return rect;
      }

      /**
       * Create thin rectangles along a line path to approximate a line for collisions.
       * @param {Vector[]} points - Array of points [{x, y}, ...] defining the line path
       * @param {number} thickness - The thickness of the rectangles
       * @param {object} options - Optional Matter.js body options
       * @param {World} world - Matter.World to add the rectangles to
       * @returns {Body[]} - Array of rectangle bodies created
       */
      function createLineBodies(
        x,
        y,
        points,
        thickness = 2,
        options = {},
        world
      ) {
        const bodies = [];

        for (let i = 0; i < points.length - 1; i++) {
          const p1 = points[i];
          const p2 = points[i + 1];

          // Compute segment vector
          const delta = Vector.sub(p2, p1);
          const length = Vector.magnitude(delta);

          // Compute angle
          const angle = Math.atan2(delta.y, delta.x);
          const wallOptions = {
            ...options,
            isStatic: true,
            friction: 0.01, // Low friction to encourage sliding
            render: {
              fillStyle: "#a1a1a1",
            },
          };
          // Create thin rectangle for this segment
          const rect = Bodies.rectangle(
            x + (p1.x + p2.x) / 2,
            y + (p1.y + p2.y) / 2,
            length,
            thickness,
            Object.assign({}, wallOptions, { angle })
          );

          bodies.push(rect);
          if (world) World.add(world, rect);
        }

        return bodies;
      }

      /**
       * Create a compound Matter.js body from pre-decomposed convex polygons
       * @param {number} x - world x position of the origin
       * @param {number} y - world y position of the origin
       * @param {Array[]} convexParts - array of convex vertex sets, e.g. [[{x,y},...], ...]
       * @param {object} options - Matter.js body options applied to all parts
       * @param {Vector} origin - optional offset vector to shift origin (default {x:0,y:0})
       * @param {World} world - optional Matter.World to add the body to
       * @returns {Body} compound Matter.js body
       */
      function createCompoundBody(
        x,
        y,
        convexParts,
        options = {},
        origin = { x: 0, y: 0 },
        world
      ) {
        const parts = convexParts.map((vertices) => {
          // Create each convex body at origin; options can include render or physics settings
          return Bodies.fromVertices(x, y, [vertices], options, true);
        });

        // Combine all parts into a single compound body
        const compound = Body.create({
          parts: parts,
          ...options,
        });

        // Adjust origin if requested
        if (origin.x !== 0 || origin.y !== 0) {
          Body.translate(compound, { x: -origin.x, y: -origin.y });
        }

        return compound;
      }

      // --- MODULE ALIASES ---
      // These aliases make the code easier to read
      const { Engine, Render, Runner, World, Bodies, Body, Events, Vector } =
        Matter;

      // --- SCENE SETUP ---
      const sceneWidth = 800;
      const sceneHeight = 600;

      // 1. Create the physics engine
      const engine = Engine.create();

      // Disable gravity for a top-down view
      engine.world.gravity.y = 0;

      // 2. Create the renderer
      const render = Render.create({
        element: document.body,
        engine: engine,
        options: {
          width: sceneWidth,
          height: sceneHeight,
          wireframes: false, // Set to false for solid colors
          background: "#333",
          showPerformance: true,
        },
      });

      // 3. Create a runner to step the engine forward

      // --- PLAYER SETUP ---
      const playerRadius = 15;
      const player = Bodies.circle(
        sceneWidth / 2,
        sceneHeight / 2,
        playerRadius,
        {
          label: "player",
          // Physics properties for a "slidey" feel with acceleration
          frictionAir: 0.08, // Increased air friction for a smoother stop
          friction: 0.0, // Very low friction against other bodies
          restitution: 0.0, // A little bounciness
          inertia: Infinity, // Prevents the player from rotating on collision
          render: {
            fillStyle: "#4287f5", // Player color
          },
        }
      );

      // --- CHASER SETUP ---
      const chasers = [];
      const chaserCount = 0;
      const chaserRadius = 14;
      const chaserForce = 0.000511;
      const chaserOptions = {
        label: "chaser",
        frictionAir: 0.07,
        friction: 0.0,
        density: 0.00051,
        restitution: 0.0, // Make them a bit bouncy
        render: {
          fillStyle: "#f55a42", // Chaser color
        },
      };

      for (let i = 0; i < chaserCount; i++) {
        // Spawn them in random locations away from the center
        const x = Math.random() * sceneWidth;
        const y = Math.random() * sceneHeight;
        const chaser = Bodies.circle(x, y, chaserRadius, chaserOptions);
        chasers.push(chaser);
      }

      // --- WALLS & OBSTACLES ---
      // The walls are static, meaning they don't move
      const wallOptions = {
        isStatic: true,
        friction: 0.01, // Low friction to encourage sliding
        render: {
          fillStyle: "#a1a1a1",
        },
      };

      const wallThickness = 50;

      const walls = [
        ...createLineBodies(200, 100, [
          { x: 0, y: 0 },
          { x: 500, y: 5 },
          { x: 500, y: 30 },
          { x: 0, y: 35 },
          { x: 0, y: 200 },
          { x: 100, y: 200 },
          { x: 400, y: 210 },
        ]), // Top
        Bodies.rectangle(sceneWidth / 2, 0, sceneWidth, wallThickness, {
          ...wallOptions,
        }), // Top
        // Outer boundaries
        Bodies.rectangle(
          sceneWidth / 2,
          sceneHeight,
          sceneWidth,
          wallThickness,
          { ...wallOptions }
        ), // Bottom
        Bodies.rectangle(0, sceneHeight / 2, wallThickness, sceneHeight, {
          ...wallOptions,
        }), // Left
        Bodies.rectangle(
          sceneWidth,
          sceneHeight / 2,
          wallThickness,
          sceneHeight,
          { ...wallOptions }
        ), // Right
      ];

      // --- CORNER OBSTACLES ---
      // These are made of two static rectangles to test multi-body collisions
      const cornerSize = 150;
      const cornerThickness = 20;

      // Top-left corner
      const topLeftCorner = [
        createRectWithOrigin(
          100,
          wallThickness / 2,
          10,
          500,
          { x: 0.5, y: 0 },
          {
            ...wallOptions,
            render: {
              fillStyle: "#9217f5",
            },
          }
        ),
      ];

      // Bottom-right corner
      const bottomRightCorner = [
        Bodies.rectangle(
          sceneWidth - cornerSize / 2,
          sceneHeight - 100 - cornerThickness / 2,
          cornerSize,
          cornerThickness,
          { ...wallOptions }
        ),
        Bodies.rectangle(
          sceneWidth - cornerSize + cornerThickness / 2,
          sceneHeight - 100 - cornerSize / 2,
          cornerThickness,
          cornerSize,
          { ...wallOptions }
        ),
      ];

      World.add(engine.world, [
        player,
        ...walls,
        ...topLeftCorner,
        ...bottomRightCorner,
        ...chasers, // Add this line
      ]);

      const keys = {};
      const playerForce = 0.0015; // A small force value for gradual acceleration

      window.addEventListener("keydown", (event) => {
        keys[event.code] = true;
      });

      window.addEventListener("keyup", (event) => {
        keys[event.code] = false;
      });

      // This event runs just before the engine updates each frame
      Events.on(engine, "beforeUpdate", (event) => {
        const force = Vector.create(0, 0);

        if (keys["KeyW"]) {
          force.y -= playerForce;
        }
        if (keys["KeyS"]) {
          force.y += playerForce;
        }
        if (keys["KeyA"]) {
          force.x -= playerForce;
        }
        if (keys["KeyD"]) {
          force.x += playerForce;
        }

        // Apply the calculated force to the player's center
        Body.applyForce(player, player.position, force);

        chasers.forEach((chaser) => {
          // Calculate vector from chaser to player
          const direction = Vector.sub(player.position, chaser.position);

          // Normalize the vector (get a unit vector)
          const normalizedDirection = Vector.normalise(direction);

          // Create a force vector and apply it to the chaser
          const force = Vector.mult(normalizedDirection, chaserForce);
          Body.applyForce(chaser, chaser.position, force);
        });
      });

      const physicsDelta = 1000 / 600;

      let lastTime = performance.now();
      let accumulator = 0;

      // This function will be our main game loop.
      function gameLoop(currentTime) {
        debugger;
        // Calculate how much time has passed since the last frame.
        const elapsed = currentTime - lastTime;
        lastTime = currentTime;

        // Add the elapsed time to an accumulator.
        accumulator += elapsed;

        // Trigger the 'beforeUpdate' event where all your movement logic lives.
        // The default runner does this automatically, so we must do it manually here.
        Events.trigger(engine, "beforeUpdate", {
          timestamp: engine.timing.timestamp,
        });

        // While the accumulator has enough time for one or more physics steps,
        // update the engine. This loop ensures the physics simulation "catches up"
        // if rendering falls behind, maintaining a consistent simulation speed.
        while (accumulator >= physicsDelta) {
          // Update the engine by a fixed amount.
          Engine.update(engine, physicsDelta);
          accumulator -= physicsDelta;
        }

        // Render the current state of the world.
        // This is done once per frame, regardless of how many physics steps were taken.
        Render.world(render);

        // Request the next animation frame from the browser to continue the loop.
        requestAnimationFrame(gameLoop);
      }

      // Start the custom game loop!
      requestAnimationFrame(gameLoop);
    </script>
  </body>
</html>

Low conversion rate after launch — need step-by-step digital marketing fix for new e-commerce clothing store [closed]

I launched a new e-commerce clothing store 3 months ago targeting urban 18–34 customers. Traffic sources are a mix of Google Ads (Search + Shopping), Facebook/Instagram paid campaigns, organic search, and a few influencer posts. Current monthly averages: ~10,000 sessions, 0.7% conversion rate (~70 orders), bounce rate ~65%, average order value ₹1,200, ad spend ₹60,000/month with CPA ≈ ₹857 and ROAS ~1.2. Users add to cart but drop off at checkout or during payment selection. Organic visibility is low for primary product keywords.your text

Launched Search + Shopping campaigns and several FB/IG creatives (carousel + short video).

Set up basic remarketing (FB pixel + Google remarketing tag).

Added 10% first-order discount, free shipping on orders over ₹1,000.

Reduced checkout steps from 5 to 3 and added trust badges.

Created blog posts and social content but with low posting cadence.

Ran one A/B test on CTA text and swapped product thumbnails.

Enabled dynamic product ads for cart abandoners.
Results: traffic increased slightly, CTR on ads is OK, but conversion rate and CPA barely moved.

Conversion rate to rise to 2–3% within 6–8 weeks.

CPA to fall to ₹200–₹350 and ROAS to reach 2.5–3x.

Reduced checkout abandonment and higher repeat purchase rate from remarketing flows.

What is the standard protocol for logging out a user in a React app? How to properly reset Redux and other state?

I’m building a React single-page application with authentication and Redux for state management. I need to ensure that when a user logs out, all app state—including Redux state, React Context, and local component state—is fully reset.

One approach I’ve seen (and tested) is:

window.location.reload();

This effectively resets the entire app, but it feels heavy-handed, causes a full page reload, and doesn’t allow for fine-grained control over cleanup.

My questions are:

  1. Is calling window.location.reload() considered standard or acceptable for logging out in modern React apps, especially when using Redux?

  2. What are the recommended alternatives to fully reset app state, including Redux state, React Context, and any internal component state, without reloading the page?

  3. Are there common patterns or pitfalls for implementing a “soft logout” that ensures a clean slate for the next user session?

I’m looking for guidance on best practices in the React ecosystem for handling logout properly while ensuring all app state is cleared.

I want to update a single item in a list, but it is not updating [duplicate]

I created a component which consist of a list of employees. I want to be able to edit and delete each item separately. The delete is working as desired, but the update is not working. My database is Mysql.

This is my code

import axios from "axios";
import { useState, useEffect } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import Student from "./Student";
import { FaGetPocket } from "react-icons/fa";
import { FaHome } from "react-icons/fa";
import { FaAmazonPay } from "react-icons/fa";
import { FaPlus } from "react-icons/fa";
import { FaRegEdit } from "react-icons/fa";
import { FaTimes } from "react-icons/fa";
import "./DashboardList.css"; // Custom CSS file
//import { Pagination } from "./Pagination";


function Updatestudent () {

  const [users, setUsers] = useState([]);
  const [error, setError] = useState("");

  const navigate = useNavigate(); // ✅ Fix: Call useNavigate()

  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [age, setAge] = useState("");
  const [id, setId] = useState("");
  const [items, setItems] = useState([]);
  const [selectedItem, setSelectedItem] = useState(null);
  const [err, setErr] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [postsPerPage] = useState(5);

  const [data, setData] = useState({
    name: "",
    email: "",
    age: "",
  });
   
 
  useEffect(() => {
    axios
      .get("http://localhost:8081/users")
      .then((res) => {
        console.log("✅ Unique Data fetched:", res.data);
        setItems(res.data);
        //setData(res.data);
      })
      .catch((err) => {
        console.error("❌ Error fetching data:", err);
        setError("Failed to load data. Please check server.");
      });
  }, []);
  

  //const indexOfLastPost = currentPage * postsPerPage;
  //const indexOfFirstPost = indexOfLastPost - postsPerPage;
  //const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);

  const handleSelectItem = (itemId) => {
    const item = items.find(i => i.id === itemId);
    setSelectedItem(item);
    setData(items);
  };

  //const handleChange = (e) => {
  //  setData({ ...items, [e.target.name]: e.target.value });
  //};

  const handleAdd= (event) => {
    event.preventDefault();
    axios
      .post("http://localhost:8081/users", { name, email, age })
      .then((res) => {
        console.log("✅ Employee added successfully:", res);
        navigate("/"); // ✅ Fix: Properly navigate after success
      })
      .catch((err) => console.error("❌ Error adding student:", err));
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:8081/student/${id}`);
      navigate("/"); // Fix: Properly navigate after success
      setUsers(users.filter((user) => user.id !== id)); // ✅ Optimized UI update without reloading
      console.log("✅ Employee deleted successfully:", res);
          } catch (err) {
      console.error("❌ Error deleting student:", err);
    }
  };

  const handleUpdate = async (id) => {
    try {
      await axios.put('http://localhost:8081/update/:id'+ id, items)
      .then( (event) => {
        console.log("Employee Updated successfully:", items);
      navigate("/")}); // Fix: Properly navigate after success
       } catch (err) {
        console.log("Employee Updated successfully:", items);
    }
  };


  const handleSubmit = (event) => {
    event.preventDefault();

    handleUpdate(id)
    axios
    .put('http://localhost:8081/update/:id'+ id,  data )
     .then((event) => {
       console.log("Employee Updated successfully:", data);
       navigate("/"); // Fix: Properly navigate after success
     })
    .catch((err) => console.error("Error Updating Employee:", err));
  };


  return (
    <div className="dashboard-list w-100 vh-100 justify-content-between align-items-center p-4" >
      <div className="container p-4 bg-white rounded shadow">
      <h2 className="list-title">Employees List</h2>
      <div className="mb-2 form-control">
      <button className=" ms-2 btn btn-outline-primary">Add
      <Link to="/create" >
        <FaPlus className="ms-2 icon" color="" size="1.5rem"
          ></FaPlus>
        </Link> 
        </button>
        </div>
      <ul id="list" className="list-container">
        {items.map(item => (
          <tr key={item.id} className="list-item" align-items-center="true">
            <button className=" ms-3 btn btn-outline-success">Edit
             <FaRegEdit className="ms-3 icon" color="green"  onClick={() =>  {handleSelectItem(item.id)}}
             size="1.5rem" ></FaRegEdit>
             </button>
             <button className=" ms-3 btn btn-outline-danger">Del.
             <FaTimes className="ms-3 icon" color="red" onClick={() => {if (confirm("Do you want to delete this item?")) {handleDelete(item.id)};}}
              size="1.5rem" ></FaTimes>
             </button>
             <td className=" ms-3 ">
            {item.name}  
            </td> 
            <td className=" ms-3 ">
            {item.email}  
            </td> 
            <td className=" ms-3 ">
            {item.age}  
             </td>
            </tr>
        ))}
      </ul>
      {selectedItem && (
        <div className="d-flex justify-content-right align-items-center">
          <div className="w-100 bg-white rounded p-3">
          <h3>Details</h3>
          <form >
          <div>
          <input className="mb-2 form-control"  
           type="text" 
            defaultValue={selectedItem.name} 
            onChange={handleChange}
               />
          </div>
          <div>
          <input className="mb-2 form-control"  
              type="email" 
               defaultValue={selectedItem.email} 
               onChange={handleChange}
           />
           </div>
            <div>
            <input  className="mb-2 form-control"  
            type="number" 
            defaultValue={selectedItem.age} 
             onChange={handleChange}
           />
           </div>
          {/* Display other item properties */}
          <p></p>
          <button
            className="btn btn-success"
              onClick={(e) => handleUpdate(e,selectedItem.id)}>
                Update
           </button>
           </form>
           
           </div>
          </div>
        
      )}
       <Link to="/" className="mb-2 form-control" >
            <FaHome className="ms-2 icon" color="green" size="3rem"
             ></FaHome>
          </Link>
        </div>
       </div>
       
      )
  }
     
export default Updatestudent;

When I click the Edit button, it display selected item with inputs to edit.
When I click the update, the record in the mysql database is suppose to be updated. below is the backend (server) code

const express = require("express");
const cors = require("cors");
const mysql = require("mysql");

const app = express();
app.use(cors());
app.use(express.json()); // Enable JSON parsing

// MySQL Connection
const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "crud",
});


db.connect((err) => {
  if (err) {
    console.error("Database connection failed:", err);
    return;
  }
  console.log("Connected to MySQL database");
});

// ✅ Fetch all users
app.get("/users", (req, res) => {
  const sql = "SELECT * FROM users";
  db.query(sql, (err, data) => {
    if (err) {
      console.error("SQL Query Error:", err);
      return res.status(500).json({ error: "Database query failed" });
    }
    return res.json(data);
  });
});

//Fetch a single user
app.get("/user/:id", (req, res) => {
  const { id } = req.params.id; // ✅ Extract id from URL
  const sql = "SELECT * FROM users WHERE id = ?";
  db.query(sql, id, (err, data) => {
    if (err) {
      console.error("SQL Query Error:", err);
      return res.status(500).json({ error: "Database query failed" });
    }
    return res.json(data);
  });
});


// ✅ Add a new user
app.post("/users", (req, res) => {
  const sql = "INSERT INTO users (`Name`, `Email`, `Age`) VALUES (?, ?, ?)";
  const values = [req.body.name, req.body.email, req.body.age];

  db.query(sql, values, (err, data) => {
    if (err) {
      console.error("SQL Insert Error:", err);
      return res.status(500).json({ error: "Database insertion failed" });
    }
    return res.json({ message: "User added successfully", id: data.insertId });
  });
});

// ✅ Update an existing user
app.put("/update/:id", (req, res) => {
  const { id } = req.params; // Extract id from URL
  db.query("UPDATE 'users' SET 'name' = ?, 'email' = ?, 'age' = ? WHERE 'id' = ?", [name, email, age], (err) => {
    const values = [req.body.name, req.body.email, req.body.age];
    if (err) return res.status(500).send(err);
    res.send('Record updated successfully');
  });
});


// ✅ Delete an existing user
app.delete("/student/:id", (req, res) => {
  const sql = "DELETE FROM users WHERE ID = ?";
  const id = req.params.id;

  db.query(sql, id, (err, data) => {
    if (err) {
      console.error("SQL Delete Error:", err);
      return res.status(500).json({ error: "Database deletion failed" });
    }
    return res.json({ message: "User deleted successfully" });
  });
});

// Fetch single record
app.get('/record/user/:id', (req, res) => {
  const {id} = req.params;
  db.query('SELECT * FROM users WHERE id = ?', [id], (err, result) => {
    if (err) return res.status(500).send(err);
    res.json(result[0]);
  });
});

// Update record
app.put('/record/:id', (req, res) => {
  const id = req.params.id;
  const { name1, email, age } = req.body; // Example fields
  db.query('UPDATE users SET name = ?, email = ?, age = ? WHERE id = ?', [name1, email, age], (err) => {
    const values = [req.body.name, req.body.email, req.body.age];
    if (err) return res.status(500).send(err);
    res.send('Record updated successfully');
  });
});


// ✅ Start the server
app.listen(8081, () => {
  console.log("Server is running on port 8081");
});

Prisma user.create() and user.delete() throwing errors with Clerk Inngest events

I’m using Prisma with PostgreSQL and Inngest to sync Clerk user events (user.created, user.updated, user.deleted) to my database.

I have the following Prisma schema for User:

model User {
  id     String @id
  name   String
  email  String?
  image  String
  cart   Json @default("{}")
}

And my Inngest functions:

import prisma from '/lib/prisma';
import { inngest } from './client';

export const syncUserCreation = inngest.createFunction(
  { id: 'sync-user-create' },
  { event: 'clerk/user.created' },
  async ({ event }) => {
    const { data } = event;
    await prisma.user.create({
      data: {
        id: data.id,
        email: data.email_addresses[0].email_addresses, // <- seems wrong
        name: `${data.first_name} ${data.last_name}`,
        image: data.image_url,
      }
    });
  }
);

export const syncUserDeletion = inngest.createFunction(
  { id: 'sync-user-delete' },
  { event: 'clerk/user.deleted' },
  async ({ event }) => {
    const { data } = event;
    await prisma.user.delete({
      where: { id: data.id }
    });
  }
);

When creating a user:

PrismaClientValidationError:
Invalid prisma.user.create() invocation:
Argument email is missing.

When deleting a user:

PrismaClientKnownRequestError:
Invalid prisma.user.delete() invocation:
No record was found for a delete.

What I’ve tried

Changed

email_addresses[0].email_addresses to email_addresses[0]?.email_address

Tried using prisma.user.deleteMany() instead of delete() to avoid errors if user doesn’t exist

Need help creating a filter interface in JSUI / V8UI for Max/MSP using the Mgraphics API

Since I am a complete novice in programming, I decided to ask you for help.

Here is a reference to the filter I would like to get.

enter image description here

Reference
My thoughts: most likely, this is not a Band Pass filter, but two cutoff filters with adaptive Slope (from 12 to 48 dB/Octave). Moving up sets the distance between the bands and the filter slope, while moving horizontally sets the frequency. The amplitude range on the graph is from (unknown) to ~+6 dB.

I tried to create this using GPT’s, but without success.

If anyone can help me with this, I would be very grateful! Thank you!