Scrolling down makes div`s stick to top after eachother

I have multiple chapters (1, 2 and 3) and each chapter has text underneath them. When scrolling down, I need the chapters to stick to the top but one after eachother the more you scroll down. Each chapter has different heights (because of their content and also because of different screen sizes). How to make that work? I cannot figure out how to make the height variable and to stack the chapters one after eachother when scrolling down. top-0 should be top minus height of previous chapter but how to get that variable height of the previous chapter? Here the base code.

<div>
  <div className="sticky top-0 z-10 w-full bg-red-400">
    <h1>
      Chapter 1 div – big height big height big height big height big height big
      height
    </h1>
  </div>
  <p>
    Here text – here text - Here text – here textHere text – here textHere text
    – here textHere text – here text Here text – here text - Here text – here
    textHere text – here textHere text – here textHere text – here textHere text
    – here text - Here text – here textHere text – here textHere text – here
    textHere text – here textHere text – here text - Here text – here textHere
    text – here textHere text – here textHere text – here textHere text – here
    text - Here text – here textHere text – here textHere text – here textHere
    text – here text
  </p>
  <div className="sticky top-0 z-10 w-full bg-green-400">
    <h1>
      Chapter 2 div – biggest height biggest heightbiggest heightbiggest
      heightbiggest height heightbiggest heightbiggest heightheightbiggest
      heightbiggest heightheightbiggest heightbiggest height
    </h1>
  </div>
  <p>
    More words – more words - More words – more words - More words – more words
    - More words – more words - More words – more words - More words – more
    words -{" "}
  </p>
  <div className="sticky top-0 z-10 w-full bg-yellow-400">
    <h1>Chapter 3 div – small height </h1>
  </div>
  <p>
    Read this - Read this - Read this - Read this - Read this - Read this - Read
    this - Read this - Read this - Read this - Read this -{" "}
  </p>
</div>;

In this picture here you see my goal. The second pic on the right shows how it should look when having scrolled all the way down. So one-by-one the chapters stack horizontally.Picture of my goal

Why website testimonials (owl carousel) not showing with WP Rocket enabled + images served as webp?

I am trying to optimize a website for faster page load speed. I did 2 things: (1) converted all images to WebP format and (2) purchased WP Rocket and enabled it on the site. Performance improved slightly but the testimonial sliders (which operate on JQuery’s owl carousel) are not showing on the 2 pages where I have them displayed.

When I troubleshoot the problem on Chrome Inspect tool, I get this error: “Uncaught SyntaxError: unexpected string” and this is the line where the error happens:

                navText: [
                "<img src="/wp-content/uploads/2020/01/arrow_left.png.webp" /> Prev Video",
                "Next Video <img src="/wp-content/uploads/2020/01/arrow_right.png.webp" />"],

Here is the full code snippet:

        jQuery(document).ready(function($) {
            var owl = $('.full-video-slider');
                owl.owlCarousel({
                items:1,
                margin: 0,
                nav: true,
                navText: [
                "<img src="/wp-content/uploads/2020/01/arrow_left.png.webp" /> Prev Video",
                "Next Video <img src="/wp-content/uploads/2020/01/arrow_right.png.webp" />"],
                autoplay:false,
                loop: true,
                video:true,
                videoWidth: false,
                videoHeight: false,
            });
        });

I tried to override this in Chrome by replacing the erroneous line with the following line and the error goes away:

        navText : ["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],

Here is the problem: I am using the Avada Child Theme and cannot find the index.html file where this code snippet is located! I tried everything to fix this problem and I am totally stumped!

I already tried to excluded the Owl Carousel CSS/JS files from optimization (in WP Rocket), to disable and re-enabled various WP Rocket settings, and I even reached out to WP Rocket support team which was no help at all!

Any help, advise, or tip on how I could go about fixing this problem would be very greatly appreciated!

P.s. when I exclude the 2 pages with the testimonial sliders from WP Rocket’s Caching, then I see the testimonial sliders as before, but my website performance goes back down, which defeats the whole purpose!

Please help!!!

Uncaught runtime errors: teams.map is not a function with React

Working on website using reactJS and Laravel, while fetching json data from URL using map function finding this error on console :

teams.map is not a function TypeError: teams.map is not a function

API json response from URL :

{ "get": "teams", "parameters": { "name": "manchester united" }, "errors": [], "results": 1, "paging": { "current": 1, "total": 1 }, "response": [ { "team": { "id": 33, "name": "Manchester United", "code": "MUN", "country": "England", "founded": 1878, "national": false, "logo": "https://media.api-sports.io/football/teams/33.png" }, "venue": { "id": 556, "name": "Old Trafford", "address": "Sir Matt Busby Way", "city": "Manchester", "capacity": 76212, "surface": "grass", "image": "https://media.api-sports.io/football/venues/556.png" } } ] }

Getting json data like this :

`import React, { useEffect, useState } from “react”;

const TeamStats = () => {

    const [teams, setTeams] = useState([]);
  
    const getTeams = async () => {
      const response = await fetch("http://localhost:8000/home");
      const data = await response.json();
      console.log(data);
      setTeams(data);
    };
  
    useEffect(() => {
        getTeams();
    }, []);
     ....
     ....

           {teams.map(res => (
                <h4 className="text-black text-overflow">{res.response.team.name}</h4>
                ))}`

the API data calling was successful found in console.log but to display data on window error is popping again here’s my code and also attaching console output image.

enter image description here

How to use one mute unmute button for multiple videos on the same page?

I have the following code which I am using to mute/unmute a video. I have 3 other videos on the same page, I want to apply this mute/unmute wave animation button to every single video.

Additionally, I want only one video will play sound at a time. That means if I unmute a video and then unmute another video, the previous video will be muted automatically, and unmute the current one.

Here is my current working code which works perfectly for a single video.

document.addEventListener('DOMContentLoaded', function() {
    
    var muteButton = document.querySelector('#mute-button');
    var unmuteButton = document.querySelector('#unmute-button');
    var heroBackgroundVideo = document.querySelector('.herosection video');
    
    // Ensure the video is ready to play before changing the muted property
    heroBackgroundVideo.play();
    
    muteButton.addEventListener('click', function (event) {
     heroBackgroundVideo.muted = true;
     muteButton.classList.add('d-none');
     unmuteButton.classList.remove('d-none');
    }); 
    
    unmuteButton.addEventListener('click', function (event) {
     heroBackgroundVideo.muted = false;
     unmuteButton.classList.add('d-none');
     muteButton.classList.remove('d-none');
    }); 
    
    });
#myVideo{
    background-color:#ccc;
    position:fixed;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
}
.button-wrapper {
     position: fixed;
     bottom: 30px; /* Adjust this value to move the button up or down */
     right: 30px; /* Adjust this value to move the button left or right */
    }
    
    
    .loader{
       height:40px;
       display: flex;
       align-items: center;
       cursor: pointer;
    }
    
    .loader .stroke{
       display: block;
       position: relative;
       background: #f1f1f1;
       height: 100%;
       width: 3px;
       border-radius: 50px;
       margin: 0 5px;
       animation: animate 1.2s linear infinite;
    }
    
    @keyframes animate{
       50%{
           height: 20%;
       }
       100%{
           height: 100%;
       }
    }
    
    .stroke:nth-child(1){
       animation-delay: 0s;
    }
    .stroke:nth-child(2){
       animation-delay: 0.3s;
    }
    .stroke:nth-child(3){
       animation-delay: 0.6s;
    }
    .stroke:nth-child(4){
       animation-delay: 0.9s;
    }
    .stroke:nth-child(5){
       animation-delay: 0.6s;
    }
    .stroke:nth-child(6){
       animation-delay: 0.3s;
    }
    .stroke:nth-child(7){
       animation-delay: 0s;
    }
    .d-none{
        display: none;
    }
    #unmute-button .stroke{
        background: #f00;
    }
<div class="herosection">
      <video id="myVideo" autoplay loop muted>
         <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
     </video>
    </div>
    
    <div class="button-wrapper">
     <div class="loader d-none" id="mute-button">
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
     </div>
     <div class="loader" id="unmute-button">
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
       <span class="stroke"></span>
     </div>
    </div>

I tried following code, but it didn’t work.

document.addEventListener('DOMContentLoaded', function() {

var muteButtons = document.querySelectorAll('#mute-button');
var unmuteButtons = document.querySelectorAll('#unmute-button');
var videos = document.querySelectorAll('video');
var currentPlayingVideo = null;

videos.forEach(function(video, index) {
 // Ensure the video is ready to play before changing the muted property
 video.play();
 video.addEventListener('play', function() {
 currentPlayingVideo = video;
 muteButtons[index].classList.remove('d-none');
 unmuteButtons[index].classList.add('d-none');
 });
});

muteButtons.forEach(function(button, index) {
 button.addEventListener('click', function (event) {
 videos.forEach(function(video) {
 if (video !== currentPlayingVideo) {
  video.muted = true;
 } else {
  video.muted = false;
  muteButtons[index].classList.add('d-none');
  unmuteButtons[index].classList.remove('d-none');
 }
 });
 });
});

unmuteButtons.forEach(function(button, index) {
 button.addEventListener('click', function (event) {
 videos.forEach(function(video) {
 if (video === currentPlayingVideo) {
  video.muted = false;
  muteButtons[index].classList.remove('d-none');
  unmuteButtons[index].classList.add('d-none');
 }
 });
 });
});

});

Can Anyone Help?

Move an element along the svg path while placing it in center viewport

I am trying to create a scroll animation, for that i created a svg path and added a element which moves along the path when the user scrolls

Is there any way to make that element stay in the center of the viewport vertically while moving along the path when sccrolled?

I tried the below code, but as I scroll down initially the element doesn’t come into view even though its moving along the path, halfway through the scroll it comes into the view and i can see that the element is moving along the path

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      #pathIcon2 {
        position: absolute;
        inset: 0;
        width: 10px;
        height: 10px;
        background-size: 25px;
      }
      body {
        display: grid;
        align-items: center;
        align-content: center;
        justify-content: center;
        justify-items: center;
      }
      #pathIcon {
        position: absolute;
        inset: 0;
        width: 10px;
        height: 10px;
        background-size: 25px;
        offset-rotate: 0rad;
      }

      #Path_440 {
        stroke-width: 2;
        stroke: #001d36
      }

      #Path_444 {
        stroke-width: 4;
        stroke: #001d36
      }

      #theFill {
        stroke-width: 4;
        stroke: #55b0ff
      }

    </style>
  </head>

  <body translate="no">
    <div style="height: 175px"></div>
    <div style="position: relative">
      <svg
        width="543"
        height="7907"
        viewBox="0 0 543 7907"
        fill="none"
      >
        <defs>
          <path
            id="Path_440"
            d="M125.5 1V1C125.5 79.173 188.872 142.545 267.045 142.545H393.878C419.836 142.545 445.339 149.367 467.83 162.327V162.327C513.721 188.769 542 237.703 542 290.666V313.599L539.827 333.733C534.083 386.937 499.558 432.677 449.965 452.783L424.708 463.022C419.644 465.075 415.15 468.319 411.607 472.48V472.48C406.374 478.625 403.5 486.433 403.5 494.505V504.159V504.159C403.5 517.05 393.05 527.5 380.159 527.5H11.5C5.70101 527.5 1 532.201 1 538V538V943.5V943.5C1 949.299 5.701 954 11.5 954H389.5V954C397.232 954 403.5 960.268 403.5 968V1352.34V2115.19C403.5 2149.43 375.742 2177.19 341.5 2177.19V2177.19C307.258 2177.19 279.5 2204.95 279.5 2239.19V2420C279.5 2427.18 273.68 2433 266.5 2433V2433H17C10.3726 2433 5 2438.37 5 2445V2445V2845V2845C5 2853.84 12.1634 2861 21 2861H266.5V2861C273.68 2861 279.5 2866.82 279.5 2874V4003.55C279.5 4057.53 235.736 4101.3 181.75 4101.3V4101.3C127.764 4101.3 84 4145.06 84 4199.05V4332.5V4332.5C84 4335.81 86.6863 4338.5 90 4338.5H182.5V4338.5C185.814 4338.5 188.5 4341.19 188.5 4344.5V4762C188.5 4764.76 186.261 4767 183.5 4767V4767H91C87.134 4767 84 4770.13 84 4774V4774V5105.66C84 5183.53 147.128 5246.66 225 5246.66H261.159C319.061 5246.66 366 5293.6 366 5351.5V5351.5V5456V5456C366 5463.46 359.956 5469.5 352.5 5469.5H112.5C103.94 5469.5 97 5476.44 97 5485V5485V5861.5V5861.5C97 5871.44 105.059 5879.5 115 5879.5H348V5879.5C357.941 5879.5 366 5887.56 366 5897.5V6447C366 6456.94 357.941 6465 348 6465V6465H111C104.096 6465 98.5 6470.6 98.5 6477.5V6477.5V6858.5V6858.5C98.5 6867.61 105.887 6875 115 6875H348V6875C357.941 6875 366 6883.06 366 6893V7574.93C366 7627.95 323.019 7670.93 270 7670.93V7670.93C216.981 7670.93 174 7713.91 174 7766.93V7906.5"
            
          ></path>
        </defs>
        <use href="#Path_440" stroke-width="10" stroke-dasharray="20 10"></use>
        <use
          id="theFill"
          href="#Path_440"
          style="stroke-dasharray: 1991.82px, 9259.88px"
          stroke-width="10"
          stroke="#4cacff"
        ></use>
      </svg>
      <div
        id="pathIcon"
        stroke="#4cacff"
        style="
          offset-path: path(
            'M 125.5 1 V 1 C 125.5 79.173 188.872 142.545 267.045 142.545 H 393.878 C 419.836 142.545 445.339 149.367 467.83 162.327 V 162.327 C 513.721 188.769 542 237.703 542 290.666 V 313.599 L 539.827 333.733 C 534.083 386.937 499.558 432.677 449.965 452.783 L 424.708 463.022 C 419.644 465.075 415.15 468.319 411.607 472.48 V 472.48 C 406.374 478.625 403.5 486.433 403.5 494.505 V 504.159 V 504.159 C 403.5 517.05 393.05 527.5 380.159 527.5 H 11.5 C 5.70101 527.5 1 532.201 1 538 V 538 V 943.5 V 943.5 C 1 949.299 5.701 954 11.5 954 H 389.5 V 954 C 397.232 954 403.5 960.268 403.5 968 V 1352.34 V 2115.19 C 403.5 2149.43 375.742 2177.19 341.5 2177.19 V 2177.19 C 307.258 2177.19 279.5 2204.95 279.5 2239.19 V 2420 C 279.5 2427.18 273.68 2433 266.5 2433 V 2433 H 17 C 10.3726 2433 5 2438.37 5 2445 V 2445 V 2845 V 2845 C 5 2853.84 12.1634 2861 21 2861 H 266.5 V 2861 C 273.68 2861 279.5 2866.82 279.5 2874 V 4003.55 C 279.5 4057.53 235.736 4101.3 181.75 4101.3 V 4101.3 C 127.764 4101.3 84 4145.06 84 4199.05 V 4332.5 V 4332.5 C 84 4335.81 86.6863 4338.5 90 4338.5 H 182.5 V 4338.5 C 185.814 4338.5 188.5 4341.19 188.5 4344.5 V 4762 C 188.5 4764.76 186.261 4767 183.5 4767 V 4767 H 91 C 87.134 4767 84 4770.13 84 4774 V 4774 V 5105.66 C 84 5183.53 147.128 5246.66 225 5246.66 H 261.159 C 319.061 5246.66 366 5293.6 366 5351.5 V 5351.5 V 5456 V 5456 C 366 5463.46 359.956 5469.5 352.5 5469.5 H 112.5 C 103.94 5469.5 97 5476.44 97 5485 V 5485 V 5861.5 V 5861.5 C 97 5871.44 105.059 5879.5 115 5879.5 H 348 V 5879.5 C 357.941 5879.5 366 5887.56 366 5897.5 V 6447 C 366 6456.94 357.941 6465 348 6465 V 6465 H 111 C 104.096 6465 98.5 6470.6 98.5 6477.5 V 6477.5 V 6858.5 V 6858.5 C 98.5 6867.61 105.887 6875 115 6875 H 348 V 6875 C 357.941 6875 366 6883.06 366 6893 V 7574.93 C 366 7627.95 323.019 7670.93 270 7670.93 V 7670.93 C 216.981 7670.93 174 7713.91 174 7766.93 V 7906.5'
          );
          offset-distance: 17.7024%;
          background-image: url('https://via.placeholder.com/25x25/FF0000?text=red');
        "
      ></div>
    </div>

    <script id="rendered-js">
      const pathLength = Path_440.getTotalLength();

      function clamp(min, val, max) {
        return Math.min(Math.max(min, val), max);
      }

      function updatePath() {
        const docElt = document.documentElement;
        const pathBox = theFill.getBoundingClientRect();
        const scrollProgress = clamp(
          0,
          -pathBox.y / (pathBox.height - docElt.clientHeight),
          1
        );

        pathIcon.style.offsetDistance = `${scrollProgress * 100}%`;

        // These lines fill in the dashes as you scroll down.
        const drawLength = pathLength * scrollProgress;
        const rest = pathLength - drawLength;
        theFill.style.strokeDasharray = `${drawLength}px ${rest}px`;
      }

      updatePath();
      window.addEventListener("scroll", () => updatePath());
    </script>
  </body>
</html>

$or operator from mongoose not providing all necessary data when used with the find() Method

I am using the find method alongside with the $or operator to check the database for any existing duplicate data in this line const duplicate = await NewItemsData.find({ $or: newItems }); checking the variable in the consoleconsole.log(duplicate) I discovered that some data gotten are missing. Here is the code:

please help me out to know where this problem is coming from. The aim of the code is to create an array containing duplicate data, then filter the newItems array creating another array that contains data existing in the newItems array but not in the duplicates array.

const createMoneyInTransact = asyncHandler(async (req, res) => {
 const {newItems}= req.body
 console.log(newItems)

//check the database to see if any data found in the newItems array coming in from the frontend
//already exists in the NewItemsData database if it exists, create a new array of all duplicates

  const duplicate = await NewItemsData.find({ $or: newItems });
  console.log(duplicate)
     if(Array.isArray(duplicate) && duplicate.length === 0){
        console.log('no duplicates')
         const create_newItems = await NewItemsData.create(newItems)
       console.log(create_newItems)
    }else{
        console.log('duplicate exists')
        //helper function that compares two objects in arrays by their properties
    const containsObject=(obj, arr, key)=>{
        return arr.some((element)=>{
            return element[key] === obj[key]
        })

     }

     // Filter the newItems array and keep only the objects that are 
     //not in the duplicate array
     const newUniqueItems = newItems.filter((obj)=>{
         return !containsObject(obj, duplicate, 'productName')
     })

     console.log(newUniqueItems)
     const create_newUniqueItems = await NewItemsData.create(newUniqueItems)
     console.log(create_newUniqueItems)

    }
})


//console.log Data
//console.log(newItems) displays the result below
[
  {
    productName: 'vally',
    sellingPriceOfTotal: 3619,
    quantityCount: 11,
    unitOfQuantity: 'grams',
    sellingPrice: '329'
  },
  {
    productName: 'Tridant',
    sellingPriceOfTotal: 2400,
    quantityCount: 4,
    unitOfQuantity: 'grams',
    sellingPrice: '600'
  },
  {
    productName: 'trulia',
    sellingPriceOfTotal: 1600,
    quantityCount: 4,
    unitOfQuantity: 'kg',
    sellingPrice: '400'
  },
  {
    productName: 'constr',
    sellingPriceOfTotal: 1362,
    quantityCount: 3,
    unitOfQuantity: 'kg',
    sellingPrice: '454'
  }
]
//console.log(duplicate) displays the result below
[
  {
    _id: new ObjectId("6598d46d37efd2db72ee9ecd"),
    productName: 'Tridant',
    sellingPriceOfTotal: '2400',
    quantityCount: 4,
    unitOfQuantity: 'grams',
    sellingPrice: 600,
    __v: 0
  },
  {
    _id: new ObjectId("6599150ebd9fedd3f0b9e721"),
    productName: 'trulia',
    sellingPriceOfTotal: '1600',
    quantityCount: 4,
    unitOfQuantity: 'kg',
    sellingPrice: 400,
    __v: 0
  }
]

//productName: vally was surposed to be among the duplicate but was not picked up
//console.log(newUniqueItems) displays the result below
[
  {
    productName: 'vally',
    sellingPriceOfTotal: '3619',
    quantityCount: 11,
    unitOfQuantity: 'grams',
    sellingPrice: 329
  },
  {
    productName: 'constr',
    sellingPriceOfTotal: '1362',
    quantityCount: 3,
    unitOfQuantity: 'kg',
    sellingPrice: 454
  }
]
//but vally is not supposed to be among the filtered array because it is a duplicate hence
//the errow message below

MongoServerError: E11000 duplicate key error collection: test.newitemsdatas index: productName_1 dup key: { productName: "vally" }
    at C:UsersUSERDesktopbussiness-booksservernode_modulesmongodbliboperationsinsert.js:50:33
    at C:UsersUSERDesktopbussiness-booksservernode_modulesmongodbliboperationscommand.js:84:64
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

//here is the NewItemsData Data Model
const mongoose = require('mongoose');
const MoneyInData = require('./MoneyInData');

const newItemsSchema = new mongoose.Schema({

    productName:{
        type: String,
        required: true,
        unique: true
    },
    sellingPriceOfTotal:{
      type: String,
      //required: true
    },
    quantityCount: {
        type: Number,
    },
    unitOfQuantity:{
        type: String,
    },
    costPrice:{
      type: Number,
      //required: true
    },
    sellingPrice:{
        type: Number,
       required:true
    },
    moneyInData:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'MoneyInData'
    },

})

module.exports = mongoose.model('NewItemsData', newItemsSchema);

Chart.js display data labels as integers on x axis

I am working on a chart which reads data from a .csv file and displays the emisivities of four surface types against wavelenghts between 3.660 and 14.559. Example of my source dataframe (in total 531 observations):

x1,x2,y_oakface,y_clybrkcm,y_distd_wn,y_sndpgaz1
3.66027,2732.04,0.965892,0.531653,0.974703,0.710034
3.66544,2728.18,0.965664,0.525966,0.974765,0.703811
3.67063,2724.32,0.968696,0.527477,0.974827,0.709377

14.397,694.587,0.975169,0.976188,0.960436,0.982283
14.4775,690.728,0.974855,0.975476,0.959794,0.984235
14.5588,686.869,0.973462,0.977953,0.959163,0.981849

I managed to get the graph working by using the values in x1 column as labels:
emissivity chart

I would like to have the x axis labels displayed as integers between 3-14. What is the best way to go about this? See my code below.

d3.csv("data/emisdata2.csv").then(makeChart);


// Plot the data with Chart.js
function makeChart(emisdata) {
  var wlLabels = emisdata.map(function (d) {
    return d.x1;
  });
  var oakData = emisdata.map(function (d) {
    return d.y_oakface;
  });
  var brickData = emisdata.map(function (d) {
    return d.y_clybrkcm;
  });
  var soilData = emisdata.map(function (d) {
    return d.y_sndpgaz1;
  });
  var waterData = emisdata.map(function (d) {
    return d.y_distd_wn;
  });

  const data = {
    labels: wlLabels,

    datasets: [
      {
        label: "Oak leaf",
        data: oakData,
        borderColor: "green",
        backgroundColor: 'rgba(0, 77, 0, 0.5)',
        pointStyle: false,
      },
      {
        label: "Clay brick",
        data: brickData,
        borderColor: "red",
        backgroundColor: 'rgba(255, 0, 0, 0.5)', 
        pointStyle: false,
      },
      {
        label: "Sandy soil",
        data: soilData,
        borderColor: 'rgba(139, 69, 19, 1)',
        backgroundColor: 'rgba(139, 69, 19, 0.5)', 
        pointStyle: false,
      },
      {
        label: "Distilled water",
        data: waterData,
        borderColor: 'blue',
        backgroundColor: 'rgba(0, 0, 255, 0.5)', 
        pointStyle: false,
      }
    ]
  }
  const config =  {
    type: "line",
    data: data,
    options: {
        responsive: true,
        plugins: {
            legend: {
              position: 'top',
            },
            title: {
              display: true,
              text: 'Interactive feature 2',
            },
          },
          scales: {
            x: {
              display: true,
              title: {
                display: true,
                text: 'Wavelength (micrometer)', // X-axis label
              },
              ticks:{
                stepSize: 1,
                precision: 0,

              }
            },
            y: {
              display: true,
              title: {
                display: true,
                text: 'Emissivity', // Y-axis label
              },
              
              suggestedMax: 1,
            },
          },
      
    }
}
  var chart = new Chart("myChart", config)}

I tried playing around with the tick configuration and also defining the x axis manually but neither worked. When I remove the labels the lines disappear.

How to stream realtime microphone stream from the browser to icecast using nodejs as a middleware

I am trying to build a web-based Icecast client using nodeJS as a middleware server.

in high level what I’m trying to achieve is

  1. WebApp captures the user’s microphone using navigator.mediaDevices.getUserMedia({ audio: true });
  2. WebApp streams the microphone feed to nodeJS server (using WebRTC or Socket)
  3. NodeJS server relays the microphone stream to an Icecast server using nodeshout

So far I was able to stream a static file from my nodejs server to the icecast server, and stream a 10 sec buffer of the captured microphone feed to the node server using a socket to nodeServer.
but I’m missing the steps needed to convert the audio/webm buffer to a streamable mp3.

I’ve tried converting it using ffmpeg but it doesn’t seem to work with live streams.

is there any way to achieve this?
i don’t mind switching to a different language for the middleware if that’s not possible on nodejs

ScrolltoIndex is inconsistently returning to index 0 at the end in React Native

I’m having a strange behavior where the Slider I made sometimes returns to index 0 (first slide), but most times it returns to index 1. I made a Sandbox in case you need it, but I can’t figure out how to make expo work in sandbox.

HERE is the sandbox

Here’s the code for that view

import React, { useEffect, useRef, useState } from "react";
import { StyleSheet, SafeAreaView, Animated, FlatList, View, Text, Image, Dimensions, Pressable } from "react-native";

const data = [
  {
    id: 1,
    text: "Making Testing Easier",
    img: "https://e1.pxfuel.com/desktop-wallpaper/85/884/desktop-wallpaper-beautiful-judo-throws-judoka-thumbnail.jpg",
  },
  {
    id: 2,
    text: "Instructional Videos",
    img: "https://i.pinimg.com/originals/2b/84/c9/2b84c904ec3373b90f4fcad956233211.jpg",
  },
  {
    id: 3,
    text: "Newaza Fully Expanded",
    img: "https://i.pinimg.com/474x/d4/55/8c/d4558cf325344900b9eead6cb74dab20.jpg",
  },
];

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

const CustomButton = ({ onPress, title, btnstyle, textstyle }) => {
  return (
    <Pressable style={btnstyle} onPress={onPress}>
      <Text style={textstyle}>{title}</Text>
    </Pressable>
  );
};

const SlideItem = ({ item }) => {
  return (
    <View style={styles.slideitemcontainer}>
      <View style={styles.overlay}>
        <Image source={item.img} resizeMode="cover" style={styles.image} />
      </View>
      <View style={styles.txtcontent}>
        <Text style={styles.title}>{item.text}</Text>
      </View>
      <View style={styles.btncontent}>
        <CustomButton
          title="Get Started"
          btnstyle={styles.btnPrimary}
          textstyle={styles.btnPrimaryText}
        />
        <CustomButton
          title="Login"
          btnstyle={styles.btnSecondary}
          textstyle={styles.btnSecondaryText}
        />
      </View>
    </View>
  );
};

const Pagination = ({ data, scrollX }) => {
  return (
    <View style={styles.paginationcontainer}>
      {data.map((_, idx) => {
        const inputRange = [(idx - 1) * width, idx * width, (idx + 1) * width];

        const dotWidth = scrollX.interpolate({
          inputRange,
          outputRange: [12, 30, 12],
          extrapolate: "clamp",
        });

        const backgroundColor = scrollX.interpolate({
          inputRange,
          outputRange: [
            "rgba(255, 255, 255, .3)",
            "rgba(204, 204, 204, .7)",
            "rgba(255, 255, 255, .3)",
          ],
          extrapolate: "clamp",
        });
        return (
          <Animated.View
            key={idx.toString()}
            style={[styles.dot, { width: dotWidth, backgroundColor }]}
          />
        );
      })}
    </View>
  );
};

const App = () => {
  const [index, setIndex] = useState(0);
  const scrollX = useRef(new Animated.Value(0)).current;
  const flatlistRef = useRef(null);

  const handleScroll = (event) => {
    Animated.event(
      [
        {
          nativeEvent: {
            contentOffset: {
              x: scrollX,
            },
          },
        },
      ],
      {
        useNativeDriver: false,
      },
    )(event);
  };

  const handleOnViewableItemsChanged = useRef(({ viewableItems }) => {
    setIndex(viewableItems[0].index);
  }).current;

  const viewabilityConfig = useRef({
    itemVisiblePercentThreshold: 50,
  }).current;

  useEffect(() => {
    flatlistRef?.current?.scrollToIndex({
      behavior: "smooth",
      animated: true,
      index: index,
    });
  }, [index]);

  useEffect(() => {
    const timer = setTimeout(() => {
      const nextIndex = index === data.length - 1 ? 0 : index + 1;
      setIndex(nextIndex);
    }, 2000);
    return () => clearTimeout(timer);
  }, [index]);

  const getItemLayout = (data, index) => ({
    length: width,
    offset: width * index,
    index,
  });

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={data}
        ref={flatlistRef}
        getItemLayout={getItemLayout}
        renderItem={({ item }) => <SlideItem item={item} />}
        horizontal
        pagingEnabled
        snapToAlignment="center"
        showsHorizontalScrollIndicator={false}
        onScroll={handleScroll}
        onViewableItemsChanged={handleOnViewableItemsChanged}
        viewabilityConfig={viewabilityConfig}
      />
      <Pagination data={data} scrollX={scrollX} index={index} />
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  overlay: {
    position: "absolute",
    width: "100%",
    height: "100%",
    flex: 1,
    left: 0,
    top: 0,
    opacity: 0.7,
  },
  slideitemcontainer: {
    width,
    height,
    alignItems: "center",
    backgroundColor: "black",
  },
  image: {
    flex: 1,
    width,
  },
  txtcontent: {
    position: "absolute",
    top: "25%",
    paddingHorizontal: "2%",
  },
  btncontent: {
    position: "absolute",
    bottom: "25%",
    width: "70%",
  },
  title: {
    fontSize: 45,
    fontWeight: "bold",
    color: "#fff",
  },
  btnPrimary: {
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 8,
    paddingHorizontal: 36,
    borderRadius: 8,
    elevation: 3,
    backgroundColor: "#0079D1",
    borderColor: "#0079D1",
    borderStyle: "solid",
    borderWidth: 2,
    marginBottom: 10,
  },
  btnPrimaryText: {
    fontSize: 13,
    fontWeight: "600",
    color: "white",
    textTransform: "uppercase",
  },
  btnSecondary: {
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 8,
    paddingHorizontal: 36,
    borderRadius: 8,
    elevation: 3,
    backgroundColor: "white",
    borderColor: "#0079D1",
    borderStyle: "solid",
    borderWidth: 2,
  },
  btnSecondaryText: {
    fontSize: 13,
    fontWeight: "600",
    color: "#0079D1",
    textTransform: "uppercase",
  },
  usjacontainer: {
    width,
    display: "flex",
    alignItems: "center",
    position: "absolute",
    bottom: "13%",
  },
  usja: {
    width: 40,
    height: 40,
    alignItems: "center",
    display: "flex",
    justifyContent: "center",
  },
  paginationcontainer: {
    position: "absolute",
    bottom: 35,
    flexDirection: "row",
    height: 64,
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
  },
  dot: {
    height: 12,
    width: 12,
    borderRadius: 6,
    marginHorizontal: 3,
    backgroundColor: "rgba(255, 255, 255, .4)",
  },
  dotActive: {
    backgroundColor: theme.colors.secondary,
  },
});

More specifically, the useEffect is probably where I am messing up

useEffect(() => {
    const timer = setTimeout(() => {
        const nextIndex = index === data.length - 1 ? 0 : index + 1;
        setIndex(nextIndex);
    }, 2000);
    return () => clearTimeout(timer);
}, [index]);

SIDENOTE – Is there a way to make it so that the animation only moves forward, rather than a backwards slide to 0? Infinity scroll is always so much more pleasant.

Can’t figure out why the css transition doesn’t work

So the code is basically this

JS
const loadSliderImg = (src) =>
    new Promise((resolve, reject) => {
        const sliderImg = new Image()
        sliderImg.onload = () =>
            resolve(sliderImg)
        sliderImg.src = src
    })
loadSliderImg("slider-img.png").then(
    (sliderImg) => (
        (sliderImg.className = "slider-img"),
        (sliderImg.style.top =  "100px",
        document.getElementById("div-container").appendChild(sliderImg),
    setTimeout(() => {
        sliderImg.style.left = "400px"
    }, 1)
    )
)

CSS
.div-container {
  display: block;
  width: 100%;
}
.slider-img {
  position: relative;
  width: 3px;
  height: 150px;
  transition: left 3s;
}

Tried a bunch of stuff but the result is still the same, image moves instantly. I have very similar code where everything goes right, no idea what’s the problem here

NGNIX proxy fails when downloading a large file

I have a Flask server that downloads files using chunks of 4096 bytes.
between the flask and the client, we use a Nginx server.
downloads fail after about more than 1 GB, with this error in the Ngnix proxy:

024/01/07 15:03:45 [error] 23#23: *4891 readv() failed (104: Connection reset by 
peer) while reading upstream, client: *.*.*.*, server: , request: "GET /api/asset- 
service/v1/recordings/68f38d34-9e10-4bd1-a173-5b2217b70818/download? 
connector_uuid=f7e88796-4d87-4143-9c6c-54a8d154d9f6 HTTP/1.1", upstream: 
"http://*.*.*.*:8080/v1/api/recordings/68f38d34-9e10-4bd1-a173- 
5b2217b70818/download?connector_uuid=f7e88796-4d87-4143-9c6c-54a8d154d9f6", host: 
"*.*.*.*:8080", referrer: "https://localhost:8000/recordings"

I refactor the ngnix.conf file with all the solutions I found, but still getting the same error.

This is the ngnix conf:

load_module /usr/lib/nginx/modules/ndk_http_module.so;
load_module /usr/lib/nginx/modules/ngx_http_lua_module.so;

pcre_jit on;

worker_processes  1;
events {
    worker_connections  1024;
}

env STACK_NAME;
env NAMESPACE;
http {
    server_tokens off;
    client_body_timeout 3600;
    gzip on;
    gzip_static on;
    gzip_min_length  500;
    gzip_proxied     any;
    gzip_comp_level 4;
    gzip_types  text/css text/javascript text/xml text/plain text/x-component application/javascript application/json application/xml application/rss+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml;
    gzip_vary on;
    gzip_disable     "msie6";
    resolver kube-dns.kube-system.svc.cluster.local ipv6=off;

    # Increased timeouts for large file transfers
    proxy_read_timeout 3600s;
    proxy_send_timeout 3600s;
    proxy_connect_timeout 3600s;

    # Buffer size adjustments
    proxy_buffer_size  128k;
    proxy_buffers 4 256k;
    proxy_busy_buffers_size 256k;
    types_hash_max_size 4096;
    # Keepalive connections
    keepalive_timeout  300s;
    keepalive_requests 10000;
    # resolver 127.0.0.11 ipv6=off;
    client_max_body_size       0;
    proxy_max_temp_file_size   0;
    proxy_buffering off;
    server_names_hash_bucket_size 256;
    log_format trace '$remote_addr $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for" ($request_id)';


    server {
        set_by_lua $kn 'return os.getenv("NAMESPACE")' ;
        listen       443 ssl;
        listen      8080 ssl;

        # redirect http to https
        error_page 497 https://$host:$server_port$request_uri;

        ssl_protocols  TLSv1.2 TLSv1.3;
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers   on;

        access_log /var/log/nginx/access.log trace;

    
        add_header X-Frame-Options “DENY”; #Prevent ClickJacking
        add_header X-XSS-Protection "1; mode=block"; #XSS Filter
        add_header X-Content-Type-Options nosniff; #Prevent Mime-Type Risks
    

        location /ws {

            location ~ /ws/socket.io/(.*) {

                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "Upgrade";
                proxy_pass http://notifications-service.$kn.svc.cluster.local:8080/socket.io/$1$is_args$args;
            }

            location ~ ^/ws/wsproxy-service/(.*) {
                proxy_read_timeout 3600s;
                proxy_send_timeout 3600s;
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header X-Request-ID $request_id;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "Upgrade";
                proxy_pass http://wsproxy-service.$kn.svc.cluster.local:8080/api/$1$is_args$args;
            }
        }

        location /api {
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            location ~ ^/api/([w-]*)/v(d+)/swagger.json {

                proxy_pass http://$1.$kn.svc.cluster.local:8080/v$2/swagger.json;
            }

            location ~ ^/api/([w-]*)/v(d+)/ui {

                proxy_pass http://$1.$kn.svc.cluster.local:8080/v$2/ui;
            }

            location ~* ^/api/([w-]*)/v(d+)/(.*) {
                # Adjusted timeouts for large file transfers
                proxy_read_timeout 3600s;
                proxy_send_timeout 3600s;
                if ($request_method = OPTIONS ) {
                    add_header Access-Control-Allow-Origin *;
                    add_header Access-Control-Allow-Methods "GET, OPTIONS, PUT, DELETE";
                    add_header Access-Control-Allow-Headers "origin, authorization, accept, access-code, aad-token, Content-type";
                    add_header Access-Control-Allow-Credentials "true";
                    add_header Content-Length 0;
                    add_header Content-Type text/plain;
                    return 200;
                }

                rewrite_by_lua '
                    if string.match(ngx.var.request_uri, "/health$") == nil
                    and string.match(ngx.var.request_uri, "/beat_health$") == nil
                    and string.match(ngx.var.request_uri, "/celery_health/.*") == nil
                    and string.match(ngx.var.request_uri, "/admin/create_db$") == nil
                    and ngx.var.request_uri ~= "/api/user-service/v1/decrypt-token" then
                        local res = ngx.location.capture("/check_license_expiration")
                        if (res) and res.status ~= 200 then
                            ngx.exit(ngx.HTTP_PAYMENT_REQUIRED)
                        end
                    end
                ';

                proxy_http_version 1.1;
                proxy_set_header HOST $host;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Request-ID $request_id;
                proxy_send_timeout         1200;
                proxy_read_timeout         1200;

                proxy_pass http://$1.$kn.svc.cluster.local:8080/v$2/api/$3$is_args$args;
            }
        }

        location /tests {
            location ~* ^/tests/([w-]*)/(.*) {
                proxy_http_version 1.1;
                proxy_set_header HOST $host;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Request-ID $request_id;
                proxy_send_timeout         1200;
                proxy_read_timeout         1200;

                proxy_pass http://$1.$kn.svc.cluster.local:8080/tests/$2$is_args$args;
            }
        }

        location / {

            proxy_pass http://frontend.$kn.svc.cluster.local:8080;
        }

        location /nginx_status {
            stub_status;
            allow 127.0.0.1;
            deny all;
        }
    }
}

This is the client code (download_file function):

import { action, observable } from 'mobx';
import axios from 'axios';
import BaseStore from './baseStore';
import { getAuthHeaders } from '../utils/tokenRequest';
import MessageService from '../utils/MessageService';

class RecordingsStore extends BaseStore {
    @observable downloadingFiles = new Map();

    downloadBlob(blob, originalFilename) {
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = originalFilename;

      // Append to html link element page
      document.body.appendChild(link);

      // Start download
      link.click();

      setTimeout(() => {
        // Clean up and remove the link
        link.parentNode.removeChild(link);
        window.URL.revokeObjectURL(url);
      }, 100);
    }

    @action
    async downloadFile(recording, messages, i18next) {
      try {
        const cancelToken = axios.CancelToken.source();
        this.downloadingFiles.set(recording.id, { progress: '0', cancelToken });
        const authHeaders = await getAuthHeaders();
        const headers = {
          ...authHeaders,
        };
        const response = await axios.get(`api/asset-service/v1/recordings/${recording.id}/download?connector_uuid=${recording.connector_uuid}`, {
          headers,
          withCredentials: true,
          responseType: 'blob',
          onDownloadProgress: (progressEvent) => {
            const percentage = ((progressEvent.loaded * 100) / progressEvent.total).toFixed(1);
            this.downloadingFiles.set(recording.id, { progress: percentage, cancelToken });
          },
          cancelToken: cancelToken.token,
        });
        const contentDisposition = response.headers.get('content-disposition');
        const filenameMatch = contentDisposition && contentDisposition.match(/filename="?([^";]+)"?/);
        const originalFilename = filenameMatch ? filenameMatch[1] : 'unknown_filename';

        this.downloadBlob(response.data, originalFilename);
      } catch (error) {
        if (!axios.isCancel(error)) {
          console.error('failed to download file', error);
          MessageService.showMessage(messages, error?.response?.status || 500, {}, i18next);
        }
      } finally {
        this.downloadingFiles.delete(recording.id);
      }
    }

    @action
    cancelDownload(id) {
      const downloadingFile = this.downloadingFiles.get(id);
      if (downloadingFile) {
        downloadingFile.cancelToken.cancel();
      }
    }
}

export default new RecordingsStore();

Thanks

Why nullable objects must have a value?

I Write this code in ListHandlerfile.cs.

protected override void PrepareQuery(SqlQuery query)
{

    base.PrepareQuery(query);


    var PR = ProviderCredentialingFormRow.Fields;
    var connection = SqlConnections.NewByKey("Default");

    var user = connection.TryFirst<ProviderRegistrationRow>(ProviderRegistrationRow.Fields.UserId == User.GetIdentifier());
    var team = user.TeamId;

    query.Where(PR.TeamId == (Int32)team);
}

But I got this error Nullable object must have value. How I clear It?

Can’t make div to animates smoothly to previous height with React’s FramerMotion

I’ve managed to animate expanding .project-card div when useState changes to true and .project-details appears. I have a problem with animating it to previous height when isActive changes to false and .project-card collapse immediatelly.

Appreciate all help and suggestions.

import '../styles/project.css';
import { useState, useTransition } from 'react';
import { motion } from 'framer-motion';
import { MdOutlineArrowForwardIos } from 'react-icons/md';

function Project(project) {
  const { index } = project;
  const [isActive, setIsActive] = useState(false);
  const handleClick = () => {
    setIsActive((current) => !current);
  };
  return (
    <motion.div
      key={project.id}
      className='project-card'
      initial={{ opacity: 0, y: 300, height: '57px' }}
      animate={{ opacity: 1, y: 0, height: isActive ? 'auto' : '57px' }}
      exit={{ opacity: 0, y: 300 }}
      transition={{ duration: 0.9, delay: index * 0.2, ease: 'backInOut'  }}>
  
      <div className='project-card-top'>
        <div className='project-title'>
          <div>
            <MdOutlineArrowForwardIos
              onClick={handleClick}
              className='project arrow'
              style={{
                transform: isActive ? 'rotate(0)' : '',
              }}
            />
            <h3 class='blue'>{project.name}</h3>
          </div>

          <div className='project-techs'>
            {project.technology.map((title) => {
              return (
                <div
                  key={title}
                  className='tech-img'>
                  <img src={`./assets/icons/${title}`} />
                </div>
              );
            })}

            {project.commercial ? (
              <div>
                <p className='project-tech commercial'>Commercial</p>
              </div>
            ) : null}
          </div>
        </div>
        {isActive && (
          <motion.div
            initial={{ opacity: 0}}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{
              duration: 0.3,
              delay: 0.5,
              ease: 'backInOut',
            }}
            className='project-details'>
            <div className='project-description'>{project.description}</div>
          </motion.div>
        )}
      </div>

    </motion.div>
  );
}
export default Project;

I’ve tried with GPT some options inluding :

declaring height style and

transition={{ 
  duration: 0.3,
  height: {
    duration: 0.3,
    ease: 'easeOut'
  }
}}

mouse enters, decrease the size of the image by 5% each second

I put an image in a div. When I move the mouse into the div, the image should decrease by 5% every second. I’ve done this script but nothing happens.

document.addEventListener("DOMContentLoaded", (event) => {
    const element = document.getElementsByTagName("footer")[0];
    const div = element.getElementsByTagName("div")[0];
    var urlImg = "https://www.coding-academy.fr/wp-content/uploads/2017/10/CODING_LOGO_CMJN.png";

    var imagejavascript = document.createElement("img");
    imagejavascript.src = urlImg;
    imagejavascript.style.width = "100%";
    imagejavascript.style.height = "100%";
    div.appendChild(imagejavascript);

    const img = div.getElementsByTagName("img")[0];
    var isOnDiv = false;
    var currentHeight = 100;

    div.addEventListener("mouseenter", function() {
        if (isOnDiv) return;
        isOnDiv = true;

        var intervalId = setInterval(function() {
            currentHeight -= 5;
            img.style.height = currentHeight + "%";

            if (currentHeight <= 0) {
                clearInterval(intervalId);
                setTimeout(function() {
                    isOnDiv = false;
                    currentHeight = 100;
                    img.style.height = "100%";
                }, 1000);
            }
        }, 1000);
    });

    div.addEventListener("click", function() {
        div.removeChild(img);
    });
});

I’m trying to find a way to reduce the image size by 5% every second I enter the mouse in the div.