Where to put the ‘type’ prop / option in react-apexcharts?

Seems that there are at least three ‘locations’ where I can define the type of a chart (e.g. ‘bar’, ‘line’, etc.)

  1. As a prop of the Chart component <Chart type='bar'...
  2. According to the Apexcharts docs it can also be set on the
    series
  3. And finally it can be set on the chart option like chart: {type: 'bar'}

I used to set the type on the series, but the Chart component requires the prop ‘type’ (v1.5) and react-apexcharts throws an error if it the value is undefined.

Question: Can somebody explain when to use what and especially: How can I create a chart with mixed types of multiple series, if the required prop can only contain one type? Is there some kind of ‘Overwrite Sequence’?

Applying a dynamic number of forces to particles in threejs compute shader

I’ve been making a particle system using threejs, based off one of the examples, and I’ve been trying to expand on it by adding functionality for a varying number of attractor objects, just simple pull forces on particles. For one of them its working fine, but as soon as I try to iterate over them it suddenly breaks, only applying the force from the first attractor. However, whenever I add a new attractor item it does a little burst of pulling different particles to the same location.

I have a few instanced storage buffers in which i’m storing particle positions, velocities, and also three buffers for attractor position, strength, and radius. Here’s my current compute shader for updating particle positions:

const computeUpdate = Fn(() => {
        // retrieve position and velocity from storage
        const position = positionBuffer.element(instanceIndex);
        const velocity = velocityBuffer.element(instanceIndex);


        let i = 0;
        for (i; i < maxAttractors; i++) {
            const attractorPositionB = attractorPositionBuffer.element(i);
            const attractorRadiusB = attractorRadiusBuffer.element(i);
            const attractorStrengthB = attractorStrengthBuffer.element(i);

            const toAttractor = attractorPositionB.sub(position);
            const distance = toAttractor.length();

            let magnitude = float(999999).pow(attractorRadiusB.sub(distance))
            magnitude = magnitude.clamp(0, 1);

            const direction = toAttractor.div(distance);
            const force = direction.mul(attractorStrengthB.div(distance.pow(2).clamp(50, 999999)).mul(magnitude))
            velocity.addAssign(force);
        }

        // apply forces
        //velocity.addAssign(totalForce);
        velocity.addAssign(gravity);
        //velocity.mulAssign(damping);

        position.addAssign(velocity);

    });

I know that my attractors are being initialized correctly, and if I take the code out of the for loop and manually specify and index it works perfectly, but in the loop it only does the first attractor, with no errors in the console.

I’ve also tried unwrapping the loop block, as I thought it might have been an issue with the for loop itself, but when I did so, it had the exact same effect as with the for loop.

get the value from the attribute using selectized funtion but they show null value

Title: Issue with retrieving data-tax-rate value in input field when using Selectize in Laravel

Question:

I am working with a Laravel application where I have a dropdown populated with items and their respective tax-rate attributes. I want to update the value of an input field with the tax-rate when an item is selected from the dropdown.

The problem I am facing is that when I use the Selectize library for the dropdown, the tax rate field does not update and instead shows null. However, when I do not use Selectize, it works properly.

Here is my code:

<!-- Include Selectize CSS only -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.default.min.css" />

<!-- Your Select Dropdown -->
<select name="items[]" class="form-control section" onchange="updateTaxRate(this)">
    <option value="" selected>Choose...</option>
    @foreach ($items as $item)
        <option value="{{ $item->id }}" data-tax-rate="18">{{ $item->name }}</option>
    @endforeach
</select>



function updateTaxRate(selectElement) {
    // Get the selected option element
    const selectedOption = selectElement.options[selectElement.selectedIndex];
    
    // Retrieve the tax rate from the selected option's data attribute
    const taxRate = selectedOption.getAttribute('data-tax-rate');
    
    console.log("Tax rate from data attribute:", taxRate);

    // Find the closest 'tr' (table row) element
    const row = selectElement.closest('tr');
    
    // Find the tax rate input within this row
    const taxRateInput = row.querySelector('.tax_rate');
    
    if (taxRateInput) {
        // Set the tax rate input's value
        taxRateInput.value = taxRate;
    }
}

How to do a mulitistreming platform where i can stream on youtube,facebook etc. when i start live on my server

I’m creating a streaming platform where users can start a live stream that simultaneously goes live on other platforms like YouTube, Facebook, Twitch, LinkedIn, Kick, Loco, and Discord (web version). To achieve this, I’m planning to use WebRTC, but I don’t have any foundational knowledge of it.

I found that platforms like YouTube and LinkedIn expect an RTMP URL, according to their API documentation (though I’m not fully sure what this means). I believe I need to use this, but I’m not clear on how to proceed.

How can I build this platform and implement the multi-streaming feature to send one live stream to multiple platforms at once? Can someone guide me on this project?

Getting not supported dom exception when trying to access camera in electron

i am trying to stream a video stream from my camera on electron desktop app, but i get a not supported dom exception whenever i try to call the following code in my frontend script.

navigator.mediaDevices
      .getDisplayMedia(constraints)
      .then((strem) => {
        setSrcObject(strem);
      })

i am not sure why it’s not able to open the camera, i am using windows 11 in my laptop.
I have tried printing systemPreferences.getMediaAccessStatus('camera) and it says granted.

Pls note that i trying to build a screen sharing feature, somewhat similar to slack’s i also want to use screen sharing simultaneously with the front cam.
So far i am able to stream desktopcapturer, but when accessing camera i get the following error

{
    "error": {
         code: 9,
         message:"Not supported",
         name:"NotSupportedError",
         [[prototype]]:DomException

     }
}

React Code Block Rendering Issues with Prism.js in Large Messages

Problem

I’m building a message parser component in React that handles different types of content including code blocks. When the code content is very large (hundreds of lines), the syntax highlighting stops working and sometimes the component completely fails to render any subsequent code blocks.

Code

Here’s a simplified version of my current implementation:

const MessageParser = ({ message }) => {
  const messageRef = useRef(null);

  useEffect(() => {
    if (!messageRef.current) return;

    // Handle code highlighting
    requestAnimationFrame(() => {
      try {
        Prism.highlightAllUnder(messageRef.current);
      } catch (error) {
        console.error('Prism highlighting error:', error);
      }
    });
  }, [message]);

  const renderItem = (item, index) => {
    if (item.coding) {
      const language = getLanguage(item.coding);
      const formattedCode = item.coding
        .replace(/\n/g, 'n')
        .trim();
      
      return (
        
          
            
              {formattedCode}
            
          
        
      );
    }
    // ... other rendering logic
  };

  return (
    
      {parseMessage(message)}
    
  );
};

Expected Behavior

  • All code blocks should render with proper syntax highlighting
  • Performance should remain stable regardless of code block size
  • Subsequent code blocks should continue to render even after a large code block

Actual Behavior

  • When code blocks are very large (>1000 lines), syntax highlighting fails
  • After encountering a large code block, subsequent code blocks sometimes fail to render
  • Performance degrades significantly with large code blocks
  • Sometimes the entire component becomes unresponsive

Environment

  • React 18.2.0
  • Prism.js (latest version)
  • Modern browsers (Chrome 120, Firefox 121, Safari 17)

What I’ve Tried

  1. Wrapping the Prism.highlight call in requestAnimationFrame
  2. Using useEffect to handle highlighting
  3. Adding error boundaries around code blocks
  4. Implementing basic error handling for the highlighting process

Question

What’s the best way to handle very large code blocks in React while maintaining:

  1. Proper syntax highlighting
  2. Good performance
  3. Reliable rendering of all code blocks

Is there a recommended approach for chunking or virtualizing large code blocks with Prism.js? Or should I consider a different syntax highlighting library for better performance with large code blocks?

What I’ve Tried

  1. Wrapping the Prism.highlight call in requestAnimationFrame
  2. Using useEffect to handle highlighting
  3. Adding error boundaries around code blocks
  4. Implementing basic error handling for the highlighting process

Question

What’s the best way to handle very large code blocks in React while maintaining:

  1. Proper syntax highlighting
  2. Good performance
  3. Reliable rendering of all code blocks

Is there a recommended approach for chunking or virtualizing large code blocks with Prism.js? Or should I consider a different syntax highlighting library for better performance with large code blocks?

Why is my Javascript Carousel Starting On the Wrong Slide?

I was building a carousel for my portfolio and for some reason it is starting on the wrong slide. I am using html, css, and javascript. Everything looks good in terms of the content, but for some reason the carousel is starting on the wrong place and some of the content is not appearing so it feels like it’s a javascript issue. But it’s been driving me crazzzzyyyy

Here’s what i tried:

   <script> 
document.addEventListener("DOMContentLoaded", function() {
    // Selectors and initial setup
    const carouselContainer = document.querySelector(".carousel-wrapper"); 
    const slides = document.querySelectorAll(".carousel-slide");
    let currentIndex = 0; // Start at the first slide
    const totalItems = slides.length;

    // Log total slides and initial state
    console.log("Total slides:", totalItems);
    slides.forEach((slide, index) => {
        console.log(`Slide ${index} - Source: ${slide.querySelector("img").src}`);
    });

    function updateCarousel() {
        const offset = -(100 * currentIndex); // Offset calculation
        carouselContainer.style.transition = 'transform 0.5s ease';
        carouselContainer.style.transform = `translateX(${offset}%)`;
        console.log(`Updating carousel - Current Index: ${currentIndex}, Offset: ${offset}%`);
    }

    document.querySelector(".control-button-next").addEventListener("click", () => {
        if (currentIndex < totalItems - 1) { 
            currentIndex++;
            console.log("Next button clicked - New Index:", currentIndex);
            updateCarousel();
        }
    });

    document.querySelector(".control-button-prev").addEventListener("click", () => {
        if (currentIndex > 0) { 
            currentIndex--;
            console.log("Previous button clicked - New Index:", currentIndex);
            updateCarousel();
        }
    });

    updateCarousel(); // Initial display
});
        </script> 

It starts on slide 6 on my website instead of slide 1 and I have 0 clue as to why

“TypeError: Cyclical Structure in JSON Object during User Login in React Native/Expo”

I’m working on a React Native/Expo app where I implement user login. However, when attempting to log in a user, I encounter the following error:
Login error: [TypeError: cyclical structure in JSON object]

This error seems related to a cyclical reference within an object in my code. I’m unsure where this cycle is occurring or how to resolve it. The error message does not specify which part of my code contains the cyclical structure, making it difficult to pinpoint the exact issue.

I reviewed the objects used in the login function, looking for any references that might be circular, but nothing stood out.

I tried to stringyfy the object manually with JSON.stringify() to see if it would throw the same error. This confirmed a cyclical structure but didn’t help identify it.
My expectation was that the login would proceed smoothly and allow the user to log in without issues.
I would appreciate any guidance on how to debug cyclical references in objects in JavaScript, especially in the context of Expo/React Native.

const signInUserWithNumber = async () => {
        try {
            setIsLoading(true)
            setError('') // Clear any previous error messages

            const user = { number, password }

            // Make the POST request with user number and password
            const response = await axios.post('http://10.0.2.2:5000/login', user, {
                headers: {
                    'Content-Type': 'application/json',
                },
            })

            // If login is successful, store the token and navigate to the next screen
            const token = response.data.token
            await AsyncStorage.setItem('token', token)
            setToken(token)
            router.push('/link-up') // Navigate to link-up screen
        } catch (error) {
            console.error('Login error:', error)
            setError('Login failed. Please check your number and password.')
        } finally {
            setIsLoading(false)
        }
//endpoint to login
app.post('/login', async (req, res) => {
    try {
        const { number, password } = req.body

        // Check if the user exists already
        const user = await User.findOne({ number })
        if (!user) {
            return res.status(401).json({ message: 'Invalid number or password' })
        }

        // Compare provided password with hashed password in the database
        const isPasswordValid = await bcrypt.compare(password, user.password)
        if (!isPasswordValid) {
            return res.status(401).json({ message: 'Invalid password' })
        }

        // Generate JWT token upon successful login
        const secretKey = process.env.JWT_SECRET || 'defaultSecretKey'
        const token = jwt.sign({ userId: user._id }, secretKey, {
            expiresIn: '15m',
        })

        return res.status(200).json({ token })
    } catch (error) {
        console.error('Login error:', error)
        res.status(500).json({ message: 'Login failed' })
    }
})

expected ” to equal undefined – Cypress

I’m trying to create a class that I can reuse for future scenarios just changing the name of the program that the patient will be enrolled in, but I’m getting the error: expected ” to equal undefined

    moduleAssignedAssertion(program) {

        cy.intercept('GET', '')
        cy.wait('@moduleAssigned').its('response.statusCode').should('eq', 200)
        cy.get('@moduleAssigned').then(moduleAssigned => {
          expect(moduleAssigned.response.body[0].result.data.assigned_modules[0].name).to.eq(program)
        })

    }

Then I call this afterward

      dashboard.moduleAssignedAssertion('Shoulder')

Why does Stripe charge VAT in Checkout Session but not in PaymentIntent/Invoices, and how to charge $3 after processing fees in JavaScript?

I’m using Stripe in my javascript project and have a few questions regarding VAT charges and how Stripe handles processing fees.

  • VAT Charge in Stripe Checkout Session: When I create a Stripe Checkout Session, VAT is automatically added to the price. However,
    when I use PaymentIntent or Invoice methods, VAT is not added
    automatically. Why is VAT only applied in Checkout Session, and how
    can I manually apply VAT in PaymentIntent or Invoice?

    Stripe Processing Fee Deduction: When using PaymentIntent or Invoice, Stripe deducts processing fees from the total amount. This
    results in the customer being charged less than the original amount.
    How can I ensure the customer is charged exactly $3, taking the
    processing fee into account?

Example Code:

For the Checkout Session, I’m doing something like this:

const stripe = require('stripe')(YOUR_STRIPE_SECRET_KEY);

export async function checkoutSession({
  customer,
  price,
  quantity,
  metadata,
}: CreateCheckoutSessionParam) {
  const commonSessionParams: Stripe.Checkout.SessionCreateParams = {
    payment_method_types: ['card'],
    billing_address_collection: 'required',
    customer,
    customer_update: {
      shipping: 'auto',
      address: 'auto',
      name: 'auto',
    },
    line_items: [
      {
        price: price.id,
        quantity,
      },
    ],
    automatic_tax: { enabled: true },
    tax_id_collection: { enabled: true },
    allow_promotion_codes: true,
    success_url: `${getURL()}/en/dashboard/account`,
    cancel_url: `${getURL()}/en/dashboard/account`,
  };

For Invoice, I’m trying to create a similar flow but facing issues with the Stripe processing fee. How can I charge the customer exactly $3?

// Create an invoice for the payment
    const invoice = await stripe.invoices.create({
      customer: customerId,
      auto_advance: true,
      collection_method: 'charge_automatically',
      currency: 'usd',
      metadata: {
        userId,
        rechargeAmount: chargeAmount,
      },
    });
    // Add line item for the recharge
    await stripe.invoiceItems.create({
      customer: customerId,
      amount: chargeAmount,
      currency: 'usd',
      description: `Auto-recharge for ${topUpCredits} credits`,
      invoice: invoice.id,
    });

    // Finalize the invoice
    const finalizedInvoice = await stripe.invoices.finalizeInvoice(invoice.id);

    if (finalizedInvoice.status === 'paid') {
      await updateUserExecutionsAdmin(userId, newExecution);
      return NextResponse.json({
        success: true,
        message: 'Payment succeeded.',
      });
    }

I’ve created a snake game in Phaser, but there’s a minor issue:

when the snake moves, it looks like it ‘jumps’ rather than moving smoothly. How can I fix this?

Below are some functions I’ve implemented for my Phaser snake game: update, move, setBodyPartTexture, and grow

update(time) {
    if (time >= this.moveTime && this.gameStarted) {
        this.keyLock = false;
        if (this.moveEvents.length > 0) {
            this.direction = this.moveEvents.shift();
        }
        this.move();
        this.moveTime = time + this.speed;
        return true;
    }
    return false;
}

move() {
    let oldHeadPosition = { x: this.snakeHead.x, y: this.snakeHead.y };
    this.directions.unshift(this.direction.clone());
    this.snakeHead.x += this.direction.x * this.bodyPartLength;
    this.snakeHead.y += this.direction.y * this.bodyPartLength;

    if (this.snakeHead.x > this.scene.game.config.width || this.snakeHead.x < 0 || this.snakeHead.y > this.scene.game.config.height || this.snakeHead.y < 0) {
        return;
    }

    for (let i = 1; i < this.body.length; i++) {
        let oldBodyPosition = { x: this.body[i].x, y: this.body[i].y };
        let oldBodyDirection = this.directions[i];
        this.body[i].x = oldHeadPosition.x;
        this.body[i].y = oldHeadPosition.y;
        oldHeadPosition = oldBodyPosition;
        this.setBodyPartTexture(i, oldBodyDirection);
    }
    this.setTailTexture();
    if (this.positions.length > this.body.length * this.bodyPartLength) {
        this.positions.pop();
        this.directions.pop();
    }
    this.moveTime = this.scene.time.now + this.speed;
}

setBodyPartTexture(i, oldBodyDirection) {
    if (!oldBodyDirection.equals(this.directions[i - 1])) {
        let prevDirection = `${this.directions[i - 1].x},${this.directions[i - 1].y}`;
        let currDirection = `${oldBodyDirection.x},${oldBodyDirection.y}`;
        let textureMap = {
            "1,0,0,-1": "bodyUpRight",
            "0,1,-1,0": "bodyUpRight",
            "-1,0,0,1": "bodyRightUp",
            "0,-1,1,0": "bodyRightUp",
            "0,1,1,0": "bodyRightDown",
            "-1,0,0,-1": "bodyRightDown",
            "0,-1,-1,0": "bodyDownRight",
            "1,0,0,1": "bodyDownRight",
        };
        let directionKey = `${prevDirection},${currDirection}`;
        this.body[i].setTexture(textureMap[directionKey]);
    } else {
        if (oldBodyDirection.y != 0) {
            this.body[i].setTexture("bodyVertical");
        } else {
            this.body[i].setTexture("bodyHorizontal");
        }
    }
}

grow() {
    let newPart = this.scene.physics.add.sprite(-1 * this.bodyPartLength, -1 * this.bodyPartLength, "tailRight");
    this.scene.physics.add.collider(this.snakeHead, newPart, this.endGame, null, this.scene.snake);

    this.bodyParts.push(newPart);
    this.body.push(newPart);

    this.eat.play();
    score++;
    scoreNumber.innerHTML = score;
    if (score > highScore) {
        highScore = score;
        document.querySelector("#high-score p").innerHTML = highScore;
        document.getElementById("highScoreNumber").innerHTML = highScore;
    }
}

These are the functions I’m using. However, I’m experiencing an issue: when the snake moves, it appears to ‘jump’ instead of moving smoothly. Can anyone help me solve this issue?

As you can see in this video, I’m experiencing that issue.
https://www.awesomescreenshot.com/video/33408786?key=90beb12f2ca0ed729a0133a2b7ad36a6

I’ve tried to make the snake’s movement smoother, so it moves fluidly instead of ‘jumping.

I’ve tried using deltaTime, velocity, and the Tween method, but I haven’t found a solution.

Applying scroll-snap-type on view-timeline based animated scroll

TL;DR: in this jsfiddle https://jsfiddle.net/kLp728xw/, I want to apply scroll-snap not only on vertical scroll as it already does, but also on horizontal scroll where the number 1~5 is shown.


I want to apply scroll-snap effect on contents that are animated with @keyframes horizontally like slideshow, along view-timeline. The horizontal scroll part code from the jsfiddle is shown below.
I simply tried to add scroll-snap-type: mandatory, overflow: scroll, and scroll-snap-align: start like we normally do, but couldn’t get it working.

Is this possible first of all? If not, can you guys think of any workaround perhaps using JavaScript? (was wondering I can utilize IntersectionObserver for example.)

What I want as a baseline is the “hybrid scrolling” – as shown in fiddle, vertical and horizontal mixed scrolling – with scroll snap. If the current jsfiddle code is already stepping toward deadend, I’d love to know how to implement from the scratch zero base.

<!-- HTML -->
<div class="section pin">
  <div class="sticky">
    <div class="slides">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="item">5</div>
    </div>
  </div>
</div>
/* CSS */
.section.pin {
  height: 500vh;

  view-timeline-name: --section-pin;
  view-timeline-axis: block;
}

.sticky {
  height: 100vh;
  width: 100vw;
  position: sticky;
  top: 0;
}

.slides {
  height: 100vh;
  width: 400vw;

  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;

  animation: horizontalScroll linear both;
  animation-timeline: --section-pin;
  animation-range: contain 0%;
}

@keyframes horizontalScroll {
  from {
    transform: translateX(0);
  }

  to {
    transform: translateX(-100%);
  }
}

.item {
  width: 100vw;
  min-width: 100vw;
  height: 100vh;
}

How to make those “dark glows” over photos in css?

I’m currently writing a new website, but I have one little problem. I’m coding slideshow header and I would like to make photos darker in order to make the text more visible. I know I could just edit photos, but there is such option in CSS I guess. I remember when once I was making a site in WordPress Elementor and there were such option for slideshow, unfortunatelly I don’t remember how this option is called, it was long time ago and now I don’t use any CMSes.

Well, I don’t know how it’s called and I can’t find anything online. I think it would be possible to just create a div container, create a half-transparent box and place it before my slides, but I’m not sure if there are some other options to get this effect.